-
Notifications
You must be signed in to change notification settings - Fork 583
Expand file tree
/
Copy pathDDA.cpp
More file actions
1517 lines (1372 loc) · 53.8 KB
/
DDA.cpp
File metadata and controls
1517 lines (1372 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DDA.cpp
*
* Created on: 7 Dec 2014
* Author: David
*/
#include "DDA.h"
#include "MoveDebugFlags.h"
#include <Platform/RepRap.h>
#include <Platform/Platform.h>
#include "Move.h"
#include "StepTimer.h"
#include <Endstops/EndstopsManager.h>
#include <Tools/Tool.h>
#include <GCodes/GCodes.h>
#if SUPPORT_CAN_EXPANSION
# include <CAN/CanMotion.h>
# include <CAN/CanInterface.h>
#endif
#ifdef DUET_NG
# define DDA_MOVE_DEBUG (0)
#else
// On the wired Duets we don't have enough RAM to support this
# define DDA_MOVE_DEBUG (0)
#endif
#if DDA_MOVE_DEBUG
// Structure to hold the essential parameters of a move, for debugging
struct MoveParameters
{
float accelDistance;
float steadyDistance;
float decelDistance;
float requestedSpeed;
float startSpeed;
float topSpeed;
float endSpeed;
float targetNextSpeed;
uint32_t endstopChecks;
uint16_t flags;
MoveParameters() noexcept
{
accelDistance = steadyDistance = decelDistance = requestedSpeed = startSpeed = topSpeed = endSpeed = targetNextSpeed = 0.0;
endstopChecks = 0;
flags = 0;
}
void DebugPrint() const noexcept
{
reprap.GetPlatform().MessageF(DebugMessage, "%f,%f,%f,%f,%f,%f,%f,%f,%08" PRIX32 ",%04x\n",
(double)accelDistance, (double)steadyDistance, (double)decelDistance, (double)requestedSpeed, (double)startSpeed, (double)topSpeed, (double)endSpeed,
(double)targetNextSpeed, endstopChecks, flags);
}
static void PrintHeading() noexcept
{
reprap.GetPlatform().Message(DebugMessage,
"accelDistance,steadyDistance,decelDistance,requestedSpeed,startSpeed,topSpeed,endSpeed,"
"targetNextSpeed,endstopChecks,flags\n");
}
};
const size_t NumSavedMoves = 128;
static MoveParameters savedMoves[NumSavedMoves];
static size_t savedMovePointer = 0;
// Print the saved moves in CSV format for analysis
/*static*/ void DDA::PrintMoves() noexcept
{
// Print the saved moved in CSV format
MoveParameters::PrintHeading();
for (size_t i = 0; i < NumSavedMoves; ++i)
{
savedMoves[savedMovePointer].DebugPrint();
savedMovePointer = (savedMovePointer + 1) % NumSavedMoves;
}
}
#else
/*static*/ void DDA::PrintMoves() noexcept { }
#endif
#if DDA_LOG_PROBE_CHANGES
size_t DDA::numLoggedProbePositions = 0;
int32_t DDA::loggedProbePositions[XYZ_AXES * MaxLoggedProbePositions];
bool DDA::probeTriggered = false;
void DDA::LogProbePosition() noexcept
{
if (numLoggedProbePositions < MaxLoggedProbePositions)
{
int32_t *p = loggedProbePositions + (numLoggedProbePositions * XYZ_AXES);
for (size_t drive = 0; drive < XYZ_AXES; ++drive)
{
DriveMovement *dm = pddm[drive];
if (dm != nullptr && dm->state == DMState::moving)
{
p[drive] = endPoint[drive] - dm->GetNetStepsLeft();
}
else
{
p[drive] = endPoint[drive];
}
}
++numLoggedProbePositions;
}
}
#endif
// Convert a float to a uint32_t, with negative values converted to zero
inline uint32_t floatToU32(float f) noexcept
{
return (std::signbit(f)) ? 0 : (uint32_t)f;
}
// Set up the parameters from the DDA, excluding steadyClocks because that may be affected by input shaping
void PrepParams::SetFromDDA(const DDA& dda) noexcept
{
totalDistance = dda.totalDistance;
// Due to rounding error, for an accelerate-decelerate move we may have accelDistance+decelDistance slightly greater than totalDistance.
// We need to make sure that accelDistance <= decelStartDistance for subsequent calculations to work.
decelStartDistance = dda.totalDistance - dda.beforePrepare.decelDistance;
accelDistance = min<float>(dda.beforePrepare.accelDistance, decelStartDistance);
acceleration = dda.maxAcceleration;
deceleration = -dda.maxDeceleration;
accelClocks = lrintf((dda.topSpeed - dda.startSpeed)/acceleration);
decelClocks = lrintf((dda.endSpeed - dda.topSpeed)/deceleration);
const float steadyDistance = decelStartDistance - accelDistance;
steadyClocks = (steadyDistance <= 0.0) ? 0 : lrintf(steadyDistance/dda.topSpeed);
useInputShaping = dda.flags.xyMoving
&& !(dda.flags.isolatedMove || dda.flags.isLeadscrewAdjustmentMove
#if SUPPORT_SCANNING_PROBES
|| dda.flags.scanningProbeMove
#endif
) ;
}
void PrepParams::DebugPrint() const noexcept
{
debugPrintf("pp: td=%.3g"
" ad=%.3g dsd=%.3g a=%.3g d=%.3g ac=%" PRIu32 " sc=%" PRIu32 " dc=%" PRIu32
"\n",
(double)totalDistance,
(double)accelDistance, (double)decelStartDistance,
(double)acceleration, (double)deceleration,
accelClocks, steadyClocks, decelClocks
);
}
DDA::DDA(DDA *_ecv_null n) noexcept : next(n), prev(nullptr)
{
tool = nullptr; // needed in case we pause before any moves have been done
// Set the endpoints to zero, because Move will ask for them.
// They will be wrong if we are on a delta. We take care of that when we process the M665 command in config.g.
for (int32_t& ep : endPoint)
{
ep = 0;
}
flags.all = 0; // in particular we need to set endCoordinatesValid, usePressureAdvance to false, stateBits to empty, also checkEndstops false for the ATE build
SetState(empty); // should alrrady be covered by the above
pressureAdvanceClocks = 0.0;
virtualExtruderPosition = 0.0;
filePos = noFilePosition;
#if SUPPORT_LASER || SUPPORT_IOBITS
laserPwmOrIoBits.Clear();
#endif
}
// Return the number of clocks this DDA still needs to execute.
uint32_t DDA::GetTimeLeft() const noexcept
{
switch (GetState())
{
case provisional:
return clocksNeeded;
case committed:
{
const int32_t timeExecuting = (int32_t)(StepTimer::GetMovementTimerTicks() - afterPrepare.moveStartTime);
return (timeExecuting <= 0) ? clocksNeeded // move has not started yet
: ((uint32_t)timeExecuting > clocksNeeded) ? 0 // move has completed
: clocksNeeded - (uint32_t)timeExecuting; // move is part way through
}
default:
return 0;
}
}
void DDA::DebugPrintVector(const char *_ecv_array name, const float *_ecv_array vec, size_t len) const noexcept
{
debugPrintf("%s=", name);
for (size_t i = 0; i < len; ++i)
{
const char c = (i == 0) ? '[' : ' ';
if (vec[i] == 0.0)
{
debugPrintf("%c0", c); // just print 0 to save characters
}
else
{
debugPrintf("%c%.4g", c, (double)vec[i]);
}
}
debugPrintf("]");
}
// Print the text followed by the DDA only
void DDA::DebugPrint(const char *_ecv_array tag) const noexcept
{
debugPrintf("%s %u ts=%" PRIu32 " DDA: s=%.4g", tag, (unsigned int)GetState(), afterPrepare.moveStartTime, (double)totalDistance);
DebugPrintVector(" vec", directionVector, MaxAxesPlusExtruders);
debugPrintf("\n"
"a=%.4e d=%.4e"
" reqv=%.4e startv=%.4e topv=%.4e endv=%.4e cks=%" PRIu32 " fp=%" PRIu32 " fl=x%04" PRIx32 "\n",
(double)maxAcceleration, (double)maxDeceleration,
(double)requestedSpeed, (double)startSpeed, (double)topSpeed, (double)endSpeed, clocksNeeded, (uint32_t)filePos, flags.all);
}
// Set up a real move. Return true if it represents real movement, else false.
// Either way, return the amount of extrusion we didn't do in the extruder coordinates of nextMove
MovementError DDA::InitStandardMove(DDARing& ring, const RawMove &nextMove, bool doMotorMapping) noexcept
{
// 0. If there are more total axes than visible axes, then we must ignore any movement data in nextMove for the invisible axes.
// Likewise we must ignore any movement data in nextMove for unowned axes.
// The call to CartesianToMotorSteps may adjust the invisible axis endpoints for architectures such as CoreXYU and delta with >3 towers, so set them up here.
const size_t numTotalAxes = reprap.GetGCodes().GetTotalAxes();
const size_t numVisibleAxes = reprap.GetGCodes().GetVisibleAxes();
const Move& move = reprap.GetMove();
// 1. Compute the new endpoints and the movement vector
#if SUPPORT_ASYNC_MOVES
ownedDrives = nextMove.logicalDrivesOwned;
#endif
flags.all = 0; // set all flags false
bool linearAxesMoving = false;
bool rotationalAxesMoving = false;
// Deal with axis movement
if (doMotorMapping)
{
const MovementError err = move.CartesianToMotorSteps(nextMove.coords, endPoint, nextMove.isCoordinated); // transform the axis coordinates to motor endpoints
if (err != MovementError::ok)
{
return err; // throw away the move if it couldn't be transformed
}
// Note, the following loop iterates over both axes and logical drives
for (size_t axisOrDrive = 0; axisOrDrive < numTotalAxes; axisOrDrive++)
{
#if SUPPORT_ASYNC_MOVES
if (nextMove.axesAndExtrudersOwned.IsBitSet(axisOrDrive))
#endif
{
const float positionDelta = nextMove.coords[axisOrDrive] - ring.GetStartCoordinate(axisOrDrive);
ring.SetStartCoordinate(axisOrDrive, nextMove.coords[axisOrDrive]);
directionVector[axisOrDrive] = positionDelta;
if (positionDelta != 0.0)
{
if (move.IsAxisRotational(axisOrDrive))
{
if (nextMove.rotationalAxesMentioned)
{
rotationalAxesMoving = true;
}
}
else if (nextMove.linearAxesMentioned)
{
linearAxesMoving = true;
if (Tool::GetXAxes(nextMove.movementTool).IsBitSet(axisOrDrive) || Tool::GetYAxes(nextMove.movementTool).IsBitSet(axisOrDrive))
{
flags.xyMoving = true; // this move has XY movement in user space, before axis were mapped
}
}
}
}
#if SUPPORT_ASYNC_MOVES
else
{
// This is an axis we don't own, so make sure we don't move it
directionVector[axisOrDrive] = 0.0;
}
if (!ownedDrives.IsBitSet(axisOrDrive))
{
endPoint[axisOrDrive] = prev->endPoint[axisOrDrive];
}
#endif
}
}
else
{
// Raw motor move
for (size_t drive = 0; drive < numVisibleAxes; drive++)
{
#if SUPPORT_ASYNC_MOVES
if (ownedDrives.IsBitSet(drive))
#endif
{
// Raw motor move on a visible axis
const MovementError err = move.MotorMovementToSteps(drive, nextMove.coords[drive], endPoint[drive]);
if (err != MovementError::ok)
{
return err;
}
const int32_t delta = endPoint[drive] - prev->endPoint[drive];
directionVector[drive] = (float)delta/move.DriveStepsPerMm(drive);
if (delta != 0)
{
if (move.IsAxisRotational(drive))
{
rotationalAxesMoving = true;
}
else
{
linearAxesMoving = true;
}
}
}
#if SUPPORT_ASYNC_MOVES
else
{
// This is an axis we don't own, so make sure we don't move it
directionVector[drive] = 0.0;
endPoint[drive] = prev->endPoint[drive];
}
#endif
}
// Set any invisible axis endpoints to the same positions as the previous move
for (size_t drive = numVisibleAxes; drive < numTotalAxes; ++drive)
{
endPoint[drive] = prev->endPoint[drive];
directionVector[drive] = 0.0;
}
}
// Clear out unused logical drives
for (size_t drive = numTotalAxes; drive < MaxAxesPlusExtruders - reprap.GetGCodes().GetNumExtruders(); ++drive)
{
directionVector[drive] = 0.0;
endPoint[drive] = prev->endPoint[drive];
}
// Deal with extruder movement
float accelerations[MaxAxesPlusExtruders];
memcpyf(accelerations, move.Accelerations(nextMove.reduceAcceleration), MaxAxesPlusExtruders);
bool extrudersMoving = false;
for (size_t drive = MaxAxesPlusExtruders - reprap.GetGCodes().GetNumExtruders(); drive < MaxAxesPlusExtruders; ++drive)
{
#if SUPPORT_ASYNC_MOVES
if (ownedDrives.IsBitSet(drive))
#endif
{
// It's an extruder drive. We defer calculating the steps because they may be affected by nonlinear extrusion, which we can't calculate until we
// know the speed of the move, and because extruder movement is relative so we need to accumulate fractions of a whole step between moves.
const float movement = nextMove.coords[drive];
directionVector[drive] = movement; // for an extruder, endCoordinates is the amount of movement
if (movement != 0.0)
{
extrudersMoving = true;
if (movement > 0.0)
{
flags.hasForwardExtrusion = true;
}
if (flags.xyMoving && nextMove.usePressureAdvance)
{
const float compensationClocks = (float)nextMove.pressureAdvance * (float)StepClockRate;
if (compensationClocks > 0.0)
{
// Compensation causes instant velocity changes equal to acceleration * k, so we may need to limit the acceleration
accelerations[drive] = min<float>(accelerations[drive], move.GetMaxInstantDv(drive)/compensationClocks);
}
}
}
}
#if SUPPORT_ASYNC_MOVES
else
{
// This is an extruder we don't own, so make sure we don't move it
directionVector[drive] = 0.0;
}
#endif
}
// 2. Throw it away if there's no real movement.
if (!(linearAxesMoving || rotationalAxesMoving || extrudersMoving))
{
// Update the end position in the previous move, so that on the next move we don't think there is XY movement when the user didn't ask for any
if (doMotorMapping)
{
for (size_t drive = 0; drive < numTotalAxes; ++drive)
{
ring.SetStartCoordinate(drive, nextMove.coords[drive]);
}
}
return MovementError::noMovement;
}
// 3. Store some values
tool = nextMove.movementTool;
filePos = nextMove.filePos;
virtualExtruderPosition = nextMove.moveStartVirtualExtruderPosition;
proportionDone = nextMove.proportionDone;
initialUserC0 = nextMove.initialUserC0;
initialUserC1 = nextMove.initialUserC1;
originalFeedRate = nextMove.originalFeedRate;
pressureAdvanceClocks = (nextMove.usePressureAdvance) ? (float)nextMove.pressureAdvance * (float)StepClockRate : 0.0;
// These 4 or 5 bits can be copied in one go by the compiler generating a ubfx instruction
flags.canPauseAfter = nextMove.canPauseAfter;
flags.checkEndstops = nextMove.checkEndstops;
flags.usingStandardFeedrate = nextMove.usingStandardFeedrate;
flags.usePressureAdvance = nextMove.usePressureAdvance;
#if SUPPORT_SCANNING_PROBES
flags.scanningProbeMove = nextMove.scanningProbeMove;
#endif
flags.isolatedMove = nextMove.checkEndstops || nextMove.moveType != 0;
flags.isPrintingMove = flags.xyMoving && flags.hasForwardExtrusion; // require forward extrusion so that wipe-while-retracting doesn't count
flags.isNonPrintingExtruderMove = extrudersMoving && !flags.isPrintingMove; // flag used by filament monitors - we can ignore Z movement
flags.controlLaserOrIoBits = nextMove.isCoordinated && !nextMove.checkEndstops;
// The end coordinates will be valid at the end of this move if it does not involve endstop checks and is not a raw motor move
flags.continuousRotationShortcut = (nextMove.moveType == 0);
#if SUPPORT_LASER || SUPPORT_IOBITS
if (flags.controlLaserOrIoBits)
{
laserPwmOrIoBits = nextMove.laserPwmOrIoBits;
}
else
{
laserPwmOrIoBits.Clear();
}
#endif
// 4. Normalise the direction vector and compute the amount of motion.
// NIST standard section 2.1.2.5 rule A: if any of XYZ is moving then the feed rate specifies the linear XYZ movement
// We treat additional linear axes the same as XYZ
const Kinematics &_ecv_from k = move.GetKinematics();
if (linearAxesMoving)
{
// There is some linear axis movement, so normalise the direction vector so that the total linear movement has unit length and 'totalDistance' is the linear distance moved.
// This means that the user gets the feed rate that he asked for. It also makes the delta calculations simpler.
// First do the bed tilt compensation for deltas.
directionVector[Z_AXIS] += (directionVector[X_AXIS] * k.GetTiltCorrection(X_AXIS)) + (directionVector[Y_AXIS] * k.GetTiltCorrection(Y_AXIS));
totalDistance = NormaliseLinearMotion(move.GetLinearAxes());
}
else if (rotationalAxesMoving)
{
// Some axes are moving, but not axes that X or Y are mapped to. Normalise the movement to the vector sum of the axes that are moving.
totalDistance = Normalise(directionVector, move.GetRotationalAxes());
}
else
{
// Extruder-only movement. Normalise so that the magnitude is the total absolute movement. This gives the correct feed rate for mixing extruders.
totalDistance = 0.0;
for (size_t d = 0; d < MaxAxesPlusExtruders; d++)
{
totalDistance += fabsf(directionVector[d]);
}
if (totalDistance > 0.0) // should always be true
{
Scale(directionVector, 1.0/totalDistance);
}
}
// 5. Compute the maximum acceleration available
float normalisedDirectionVector[MaxAxesPlusExtruders]; // used to hold a unit-length vector in the direction of motion
memcpyf(normalisedDirectionVector, directionVector, ARRAY_SIZE(normalisedDirectionVector));
Absolute(normalisedDirectionVector, MaxAxesPlusExtruders);
maxAcceleration = VectorBoxIntersection(normalisedDirectionVector, accelerations);
if (flags.xyMoving) // apply M204 acceleration limits to XY moves
{
maxAcceleration = min<float>(maxAcceleration, (flags.isPrintingMove) ? nextMove.maxPrintingAcceleration : nextMove.maxTravelAcceleration);
}
maxDeceleration = maxAcceleration;
// 6. Set the speed to the smaller of the requested and maximum speed.
// Also enforce a minimum speed of 0.5mm/sec. We need a minimum speed to avoid overflow in the movement calculations.
float reqSpeed = (nextMove.inverseTimeMode) ? totalDistance/nextMove.feedRate : nextMove.feedRate;
if (!doMotorMapping)
{
// Special case of a raw or homing move on a delta printer
// We use the Cartesian motion system to implement these moves, so the feed rate will be interpreted in Cartesian coordinates.
// This is wrong, we want the feed rate to apply to the drive that is moving the farthest.
float maxDistance = 0.0;
for (size_t axis = 0; axis < numTotalAxes; ++axis)
{
if (k.GetKinematicsType() == KinematicsType::linearDelta && normalisedDirectionVector[axis] > maxDistance)
{
maxDistance = normalisedDirectionVector[axis];
}
}
if (maxDistance != 0.0) // should be true if we are homing a delta
{
reqSpeed /= maxDistance; // because normalisedDirectionVector is unit-normalised
}
}
// Don't use the constrain function in the following, because if we have a very small XY movement and a lot of extrusion, we may have to make the
// speed lower than the configured minimum movement speed. We must apply the minimum speed first and then limit it if necessary after that.
requestedSpeed = min<float>(max<float>(reqSpeed, move.MinMovementSpeed()),
VectorBoxIntersection(normalisedDirectionVector, move.MaxFeedrates()));
// On a Cartesian printer, it is OK to limit the X and Y speeds and accelerations independently, and in consequence to allow greater values
// for diagonal moves. On other architectures, this is not OK and any movement in the XY plane should be limited on other ways.
if (doMotorMapping)
{
k.LimitSpeedAndAcceleration(*this, normalisedDirectionVector, numVisibleAxes, flags.continuousRotationShortcut); // give the kinematics the chance to further restrict the speed and acceleration
}
// 7. Calculate the provisional accelerate and decelerate distances and the top speed
endSpeed = 0.0; // until we have a following move
MovementError rslt; // this will hold the return value
// See if we can meld this with the end of the previous one (which must currently have the end speed set to zero)
if ( prev->GetState() == provisional // if previous move has not started yet
&& ( move.GetJerkPolicy() != 0 // and melding is allowed
|| ( flags.isPrintingMove == prev->flags.isPrintingMove
&& flags.xyMoving == prev->flags.xyMoving
&& flags.isNonPrintingExtruderMove == prev->flags.isNonPrintingExtruderMove // this is to prevent extruder-only move being melded with Z-axis moves (issue 990)
)
)
)
{
// Try to meld this move to the previous move to avoid stop/start
// Assuming that this move ends with zero speed, calculate the maximum possible starting speed: u^2 = -2as limited to the requested speed
prev->beforePrepare.targetNextSpeed = min<float>(fastSqrtf(maxDeceleration * totalDistance * 2.0), requestedSpeed);
DoLookahead(ring, prev);
startSpeed = prev->endSpeed;
}
else
{
startSpeed = 0.0; // there is no previous move that we can adjust, so start at zero speed.
}
rslt = RecalculateMove(ring);
if (rslt == MovementError::ok)
{
SetState(provisional);
}
return rslt;
}
// Set up a leadscrew motor move returning true if the move does anything
bool DDA::InitLeadscrewMove(DDARing& ring, float feedrate, const float adjustments[MaxDriversPerAxis]) noexcept
{
// 1. Compute the new endpoints and the movement vector
bool realMove = false;
for (size_t drive = 0; drive < MaxAxesPlusExtruders; drive++)
{
endPoint[drive] = prev->endPoint[drive]; // adjusting leadscrews doesn't change the endpoint
directionVector[drive] = 0.0;
}
const Move& move = reprap.GetMove();
for (size_t driver = 0; driver < MaxDriversPerAxis; ++driver)
{
directionVector[driver] = adjustments[driver]; // for leadscrew adjustment moves, store the adjustment needed in directionVector
const int32_t delta = lrintf(adjustments[driver] * move.DriveStepsPerMm(Z_AXIS));
if (delta != 0)
{
realMove = true;
}
}
// 2. Throw it away if there's no real movement.
if (!realMove)
{
return false;
}
// 3. Store some values
flags.all = 0;
flags.isLeadscrewAdjustmentMove = true;
flags.isolatedMove = true;
virtualExtruderPosition = prev->virtualExtruderPosition;
tool = nullptr;
originalFeedRate = 0.0;
filePos = prev->filePos;
maxAcceleration = maxDeceleration = move.NormalAcceleration(Z_AXIS);
#if SUPPORT_LASER && SUPPORT_IOBITS
if (reprap.GetGCodes().GetMachineType() == MachineType::laser)
{
laserPwmOrIoBits.Clear();
}
else
{
laserPwmOrIoBits = prev->laserPwmOrIoBits;
}
#elif SUPPORT_LASER
laserPwmOrIoBits.Clear();
#elif SUPPORT_IOBITS
laserPwmOrIoBits = prev->laserPwmOrIoBits;
#endif
// 4. Normalise the direction vector and compute the amount of motion.
// Currently we normalise the vector sum of all Z motor movement to unit length.
totalDistance = Normalise(directionVector);
// 6. Set the speed to requested feed rate, which the caller must ensure is no more than the maximum speed for the Z axis.
requestedSpeed = feedrate;
// 7. Calculate the provisional accelerate and decelerate distances and the top speed
startSpeed = endSpeed = 0.0;
RecalculateMove(ring);
SetState(provisional);
return true;
}
# if SUPPORT_ASYNC_MOVES
// Set up an async motor move returning true if the move does anything.
// All async moves are relative and linear.
bool DDA::InitAsyncMove(DDARing& ring, const AsyncMove& nextMove) noexcept
{
// 1. Compute the new endpoints and the movement vector
bool realMove = false;
const Move& move = reprap.GetMove();
for (size_t drive = 0; drive < MaxAxesPlusExtruders; drive++)
{
// Note, the correspondence between endCoordinates and endPoint will not be exact because of rounding error.
// This doesn't matter for the current application because we don't use either of these fields.
// If it's a delta then we can only do async tower moves in the Z direction and on any additional linear axes
const size_t axisToUse = (move.GetKinematics().GetKinematicsType() == KinematicsType::linearDelta && drive <= Z_AXIS) ? Z_AXIS : drive;
directionVector[drive] = nextMove.movements[axisToUse];
const int32_t delta = lrintf(nextMove.movements[axisToUse] * move.DriveStepsPerMm(drive));
endPoint[drive] = prev->endPoint[drive] + delta;
if (delta != 0)
{
realMove = true;
}
}
// 2. Throw it away if there's no real movement.
if (!realMove)
{
return false;
}
// 3. Store some values
flags.all = 0;
virtualExtruderPosition = 0;
tool = nullptr;
filePos = noFilePosition;
originalFeedRate = 0.0;
startSpeed = nextMove.startSpeed;
endSpeed = nextMove.endSpeed;
requestedSpeed = nextMove.requestedSpeed;
maxAcceleration = maxDeceleration = nextMove.accelDecel;
# if SUPPORT_LASER || SUPPORT_IOBITS
laserPwmOrIoBits.Clear();
# endif
// Currently we normalise the vector sum of all motor movements to unit length.
totalDistance = Normalise(directionVector);
RecalculateMove(ring);
SetState(provisional);
return true;
}
#endif
// Return true if this move is or might have been intended to be a deceleration-only move
// A move planned as a deceleration-only move may have a short acceleration segment at the start because of rounding error
bool DDA::IsDecelerationMove() const noexcept
{
return beforePrepare.decelDistance == totalDistance // the simple case - is a deceleration-only move
|| (topSpeed < requestedSpeed // can't have been intended as deceleration-only if it reaches the requested speed
&& beforePrepare.decelDistance > 0.98 * totalDistance // rounding error can only go so far
);
}
// Return true if this move is or might have been intended to be a deceleration-only move
// A move planned as a deceleration-only move may have a short acceleration segment at the start because of rounding error
bool DDA::IsAccelerationMove() const noexcept
{
return beforePrepare.accelDistance == totalDistance // the simple case - is an acceleration-only move
|| (topSpeed < requestedSpeed // can't have been intended as deceleration-only if it reaches the requested speed
&& beforePrepare.accelDistance > 0.98 * totalDistance // rounding error can only go so far
);
}
#if 0
#define LA_DEBUG do { if (fabsf(fsquare(laDDA->endSpeed) - fsquare(laDDA->startSpeed)) > 2.02 * laDDA->acceleration * laDDA->totalDistance \
|| laDDA->topSpeed > laDDA->requestedSpeed) { \
debugPrintf("%s(%d) ", __FILE__, __LINE__); \
laDDA->DebugPrint(); \
} \
} while(false)
#else
#define LA_DEBUG do { } while(false)
#endif
// Try to increase the ending speed of this move to allow the next move to start at targetNextSpeed.
// Only called if this move and the next one (which we have just added) are both printing moves, or both non-printing moves.
/*static*/ void DDA::DoLookahead(DDARing& ring, DDA *laDDA) noexcept
//pre(state == provisional)
{
// if (reprap.Debug(moduleDda)) debugPrintf("Adjusting, %f\n", laDDA->targetNextSpeed);
unsigned int laDepth = 0;
// Iterate through the list towards earlier moves
for (;;)
{
// We have been asked to adjust the end speed of this move to match the next move starting at targetNextSpeed
if (laDDA->beforePrepare.targetNextSpeed > laDDA->requestedSpeed)
{
laDDA->beforePrepare.targetNextSpeed = laDDA->requestedSpeed; // don't try for an end speed higher than our requested speed
}
if (laDDA->topSpeed >= laDDA->requestedSpeed)
{
// This move already reaches its top speed, so we just need to adjust the deceleration part
break; // stop going back to previous moves
}
if ( laDDA->IsDecelerationMove()
&& laDDA->prev->beforePrepare.decelDistance > 0.0 // if the previous move has no deceleration phase then no point in adjusting it
)
{
const DDAState st = laDDA->prev->GetState();
// This is a deceleration-only move, and the previous one has a deceleration phase. We may have to adjust the previous move as well to get optimum behaviour.
if ( st == provisional
&& ( reprap.GetMove().GetJerkPolicy() != 0
|| ( laDDA->prev->flags.xyMoving == laDDA->flags.xyMoving
&& ( laDDA->prev->flags.isPrintingMove == laDDA->flags.isPrintingMove
|| (laDDA->prev->flags.isPrintingMove && laDDA->prev->requestedSpeed == laDDA->requestedSpeed) // special case to support coast-to-end
)
)
)
)
{
laDDA->MatchSpeeds();
const float maxStartSpeed = fastSqrtf(fsquare(laDDA->beforePrepare.targetNextSpeed) + (2 * laDDA->maxDeceleration * laDDA->totalDistance));
laDDA->prev->beforePrepare.targetNextSpeed = min<float>(maxStartSpeed, laDDA->requestedSpeed);
// Still going up
laDDA = _ecv_not_null(laDDA->prev);
++laDepth;
continue;
}
// This move is a deceleration-only move but we can't adjust the previous one
if (st == committed)
{
laDDA->flags.hadLookaheadUnderrun = true;
}
}
// This move doesn't reach its requested speed, but either it isn't a deceleration-only move or we can't adjust the previous one
// Set its target end speed to the minimum of the requested speed and the highest we can reach
const float maxReachableSpeed = fastSqrtf(fsquare(laDDA->startSpeed) + (2 * laDDA->maxAcceleration * laDDA->totalDistance));
if (laDDA->beforePrepare.targetNextSpeed > maxReachableSpeed)
{
laDDA->beforePrepare.targetNextSpeed = maxReachableSpeed;
}
break;
}
laDDA->MatchSpeeds(); // adjust the target end speed if necessary
// Iterate back through the list towards later moves
for (;;)
{
if (laDDA->beforePrepare.targetNextSpeed < laDDA->endSpeed)
{
// This situation should not normally happen except by a small amount because of rounding error.
// Don't reduce the end speed of the current move, because that may make the move infeasible.
// Report a lookahead error if the change is too large to be accounted for by rounding error.
if (laDDA->beforePrepare.targetNextSpeed < laDDA->endSpeed * 0.99)
{
ring.RecordLookaheadError();
if (reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::Lookahead))
{
debugPrintf("DDA.cpp(%d) tn=%f ", __LINE__, (double)laDDA->beforePrepare.targetNextSpeed);
laDDA->DebugPrint("la");
}
}
}
else
{
laDDA->endSpeed = laDDA->beforePrepare.targetNextSpeed;
}
LA_DEBUG;
laDDA->RecalculateMove(ring);
if (laDepth == 0)
{
#if 0
if (reprap.Debug(moduleDda))
{
debugPrintf("Complete, %f\n", laDDA->targetNextSpeed);
}
#endif
return;
}
laDDA = _ecv_not_null(laDDA->next);
--laDepth;
// Going back down the list
// We have adjusted the end speed of the previous move as much as is possible. Adjust this move to match it.
laDDA->startSpeed = laDDA->prev->endSpeed;
const float maxEndSpeed = fastSqrtf(fsquare(laDDA->startSpeed) + (2 * laDDA->maxAcceleration * laDDA->totalDistance));
if (maxEndSpeed < laDDA->beforePrepare.targetNextSpeed)
{
laDDA->beforePrepare.targetNextSpeed = maxEndSpeed;
}
}
}
// Try to push babystepping earlier in the move queue, returning the amount we pushed
// Caution! Thus is called with scheduling locked, therefore it must make no FreeRTOS calls, or call anything that makes them
//TODO this won't work for CoreXZ, rotary delta, Kappa, or SCARA with Z crosstalk
float DDA::AdvanceBabyStepping(DDARing& ring, size_t axis, float amount) noexcept
{
if (axis != Z_AXIS)
{
return 0.0; // only Z axis babystepping is supported at present
}
// Find the oldest un-prepared move
DDA *cdda = this;
while (cdda->prev->GetState() == DDAState::provisional)
{
cdda = _ecv_not_null(cdda->prev);
}
// cdda addresses the earliest un-prepared move, which is the first one we can apply babystepping to
// Allow babystepping Z speed up to 10% of the move top speed or up to half the Z jerk rate, whichever is lower
float babySteppingDone = 0.0;
while (cdda != this)
{
if (amount != 0.0 && cdda->flags.xyMoving)
{
// Limit the babystepping Z speed to the lower of 0.1 times the original XYZ speed and 0.5 times the Z jerk
Move& move = reprap.GetMove();
const float maxBabySteppingAmount = cdda->totalDistance * min<float>(0.1, 0.5 * move.GetMaxInstantDv(Z_AXIS)/cdda->topSpeed);
const float babySteppingToDo = constrain<float>(amount, -maxBabySteppingAmount, maxBabySteppingAmount);
cdda->directionVector[Z_AXIS] += babySteppingToDo/cdda->totalDistance;
cdda->totalDistance *= cdda->NormaliseLinearMotion(move.GetLinearAxes());
cdda->RecalculateMove(ring);
babySteppingDone += babySteppingToDo;
amount -= babySteppingToDo;
}
// Even if there is no babystepping to do this move, we may need to adjust the end coordinates
cdda->endPoint[Z_AXIS] += (int32_t)(babySteppingDone * reprap.GetMove().DriveStepsPerMm(Z_AXIS));
// Now do the next move
cdda = _ecv_not_null(cdda->next);
}
return babySteppingDone;
}
// Recalculate the top speed, acceleration distance and deceleration distance, and whether we can pause after this move
// This may cause a move that we intended to be a deceleration-only move to have a tiny acceleration segment at the start
// Check that the move will execute in less than 2^31 step clocks and return MovementError::ok if so
MovementError DDA::RecalculateMove(DDARing& ring) noexcept
{
const float twoA = 2 * maxAcceleration;
const float twoD = 2 * maxDeceleration;
beforePrepare.accelDistance = (fsquare(requestedSpeed) - fsquare(startSpeed))/twoA;
beforePrepare.decelDistance = (fsquare(requestedSpeed) - fsquare(endSpeed))/twoD;
if (beforePrepare.accelDistance + beforePrepare.decelDistance < totalDistance)
{
// This move reaches its top speed
// It sometimes happens that we get a very short acceleration or deceleration segment. Remove any such segments by reducing the top speed to the start or end speed.
// Don't do this if the cause is that the top speed is very low because that results in issues 989 and 994
if (startSpeed >= endSpeed)
{
if (startSpeed + maxAcceleration * MinimumAccelOrDecelClocks > requestedSpeed && startSpeed >= requestedSpeed * 0.9)
{
topSpeed = startSpeed;
beforePrepare.accelDistance = 0.0;
}
else
{
topSpeed = requestedSpeed;
}
}
else
{
if (endSpeed + maxDeceleration * MinimumAccelOrDecelClocks > requestedSpeed && endSpeed >= requestedSpeed * 0.9)
{
topSpeed = endSpeed;
beforePrepare.decelDistance = 0.0;
}
else
{
topSpeed = requestedSpeed;
}
}
}
else
{
// This move has no steady-speed phase, so it's accelerate-decelerate or accelerate-only or decelerate-only move.
// If V is the peak speed, then (V^2 - u^2)/2a + (V^2 - v^2)/2d = dist
// So V^2(2a + 2d) = 2a.2d.dist + 2a.v^2 + 2d.u^2
// So V^2 = (2a.2d.dist + 2a.v^2 + 2d.u^2)/(2a + 2d)
const float vsquared = ((twoA * twoD * totalDistance) + (twoA * fsquare(endSpeed)) + twoD * fsquare(startSpeed))/(twoA + twoD);
if (vsquared > fsquare(startSpeed) && vsquared > fsquare(endSpeed))
{
// It's an accelerate-decelerate move. Calculate accelerate distance from: V^2 = u^2 + 2as.
beforePrepare.accelDistance = (vsquared - fsquare(startSpeed))/twoA;
beforePrepare.decelDistance = (vsquared - fsquare(endSpeed))/twoD;
topSpeed = fastSqrtf(vsquared);
}
else
{
// It's an accelerate-only or decelerate-only move.
// Due to rounding errors and babystepping adjustments, we may have to adjust the acceleration or deceleration slightly.
if (startSpeed < endSpeed)
{
beforePrepare.accelDistance = totalDistance;
beforePrepare.decelDistance = 0.0;
topSpeed = endSpeed;
const float newAcceleration = (fsquare(endSpeed) - fsquare(startSpeed))/(2 * totalDistance);
if (newAcceleration > 1.02 * maxAcceleration)
{
// The acceleration increase is greater than we expect from rounding error, so record an error
ring.RecordLookaheadError();
if (reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::Lookahead))
{
debugPrintf("DDA.cpp(%d) na=%f", __LINE__, (double)newAcceleration);
DebugPrint("rm");
}
}
maxAcceleration = newAcceleration;
}
else
{
beforePrepare.accelDistance = 0.0;
beforePrepare.decelDistance = totalDistance;
topSpeed = startSpeed;
const float newDeceleration = (fsquare(startSpeed) - fsquare(endSpeed))/(2 * totalDistance);
if (newDeceleration > 1.02 * maxDeceleration)
{
// The deceleration increase is greater than we expect from rounding error, so record an error
ring.RecordLookaheadError();
if (reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::Lookahead))
{
debugPrintf("DDA.cpp(%d) nd=%f", __LINE__, (double)newDeceleration);
DebugPrint("rm");
}
}
maxDeceleration = newDeceleration;
}
}
}
// Set up flags.canPauseAfter
if (flags.canPauseAfter && endSpeed != 0.0)
{
const Move& m = reprap.GetMove();
for (size_t drive = 0; drive < MaxAxesPlusExtruders; ++drive)
{
if (endSpeed * fabsf(directionVector[drive]) > m.GetMaxInstantDv(drive))
{
flags.canPauseAfter = false;
break;
}
}
}
// We need to set the number of clocks needed here because we use it before the move has been frozen
const float totalTime = (topSpeed - startSpeed)/maxAcceleration
+ (topSpeed - endSpeed)/maxDeceleration
+ (totalDistance - beforePrepare.accelDistance - beforePrepare.decelDistance)/topSpeed;
clocksNeeded = (uint32_t)totalTime;
return (totalTime < std::numeric_limits<int32_t>::max() - 100) ? MovementError::ok : MovementError::move_duration_too_long;
}