/
DDA.cpp
2446 lines (2240 loc) · 84.1 KB
/
DDA.cpp
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 "Kinematics/LinearDeltaKinematics.h"
#include <Tools/Tool.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
// 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;
decelStartDistance = dda.totalDistance - dda.beforePrepare.decelDistance;
// 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.
accelDistance = min<float>(dda.beforePrepare.accelDistance, decelStartDistance);
acceleration = dda.acceleration;
deceleration = dda.deceleration;
accelClocks = (dda.topSpeed - dda.startSpeed)/dda.acceleration;
decelClocks = (dda.topSpeed - dda.endSpeed)/dda.deceleration;
topSpeed = dda.topSpeed;
modified = false;
}
// Calculate the steady clocks and set the total clocks in the DDA
void PrepParams::Finalise() noexcept
{
const float steadyDistance = decelStartDistance - accelDistance;
steadyClocks = (steadyDistance <= 0.0) ? 0.0 : steadyDistance/topSpeed;
}
DDA::DDA(DDA* n) noexcept : next(n), prev(nullptr), state(empty)
{
activeDMs = completedDMs = nullptr;
segments = 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 and usePressureAdvance to false, also checkEndstops false for the ATE build
virtualExtruderPosition = 0.0;
filePos = noFilePosition;
#if SUPPORT_LASER || SUPPORT_IOBITS
laserPwmOrIoBits.Clear();
#endif
}
void DDA::ReleaseDMs() noexcept
{
// Normally there should be no active DMs, but release any that there may be
for (DriveMovement* dm = activeDMs; dm != nullptr; )
{
DriveMovement* const dnext = dm->nextDM;
DriveMovement::Release(dm);
dm = dnext;
}
for (DriveMovement* dm = completedDMs; dm != nullptr; )
{
DriveMovement* const dnext = dm->nextDM;
DriveMovement::Release(dm);
dm = dnext;
}
activeDMs = completedDMs = nullptr;
ReleaseSegments();
}
// Return the number of clocks this DDA still needs to execute.
// This could be slightly negative, if the move is overdue for completion.
int32_t DDA::GetTimeLeft() const noexcept
pre(state == executing || state == frozen || state == completed)
{
return (state == completed) ? 0
: (state == executing) ? (int32_t)(afterPrepare.moveStartTime + clocksNeeded - StepTimer::GetTimerTicks())
: (int32_t)clocksNeeded;
}
// Insert the specified drive into the step list, in step time order.
// We insert the drive before any existing entries with the same step time for best performance. Now that we generate step pulses
// for multiple motors simultaneously, there is no need to preserve round-robin order.
inline void DDA::InsertDM(DriveMovement *dm) noexcept
{
DriveMovement **dmp = &activeDMs;
while (*dmp != nullptr && (*dmp)->nextStepTime < dm->nextStepTime)
{
dmp = &((*dmp)->nextDM);
}
dm->nextDM = *dmp;
*dmp = dm;
}
// Remove this drive from the list of drives with steps due and put it in the completed list
// Called from the step ISR only.
void DDA::DeactivateDM(size_t drive) noexcept
{
DriveMovement **dmp = &activeDMs;
while (*dmp != nullptr)
{
DriveMovement * const dm = *dmp;
if (dm->drive == drive)
{
(*dmp) = dm->nextDM;
dm->state = DMState::idle;
dm->nextDM = completedDMs;
completedDMs = dm;
break;
}
dmp = &(dm->nextDM);
}
}
void DDA::DebugPrintVector(const char *name, const float *vec, size_t len) const noexcept
{
debugPrintf("%s=", name);
for (size_t i = 0; i < len; ++i)
{
debugPrintf("%c%f", ((i == 0) ? '[' : ' '), (double)vec[i]);
}
debugPrintf("]");
}
// Print the text followed by the DDA only
void DDA::DebugPrint(const char *tag) const noexcept
{
const size_t numAxes = reprap.GetGCodes().GetTotalAxes();
debugPrintf("%s %u ts=%" PRIu32 " DDA:", tag, (unsigned int)state, afterPrepare.moveStartTime);
if (flags.endCoordinatesValid)
{
float startCoordinates[MaxAxes];
for (size_t i = 0; i < numAxes; ++i)
{
startCoordinates[i] = endCoordinates[i] - (totalDistance * directionVector[i]);
}
DebugPrintVector(" start", startCoordinates, numAxes);
DebugPrintVector(" end", endCoordinates, numAxes);
}
debugPrintf(" s=%.4e", (double)totalDistance);
#if 1
DebugPrintVector(" vec", directionVector, numAxes);
DebugPrintVector(" ext", directionVector + (MaxAxesPlusExtruders - reprap.GetGCodes().GetNumExtruders()), reprap.GetGCodes().GetNumExtruders());
#else
DebugPrintVector(" vec", directionVector, MaxAxesPlusExtruders);
#endif
debugPrintf("\n" "a=%.4e d=%.4e reqv=%.4e startv=%.4e topv=%.4e endv=%.4e cks=%" PRIu32 " fp=%" PRIu32 " fl=%04x\n",
(double)acceleration, (double)deceleration, (double)requestedSpeed, (double)startSpeed, (double)topSpeed, (double)endSpeed, clocksNeeded, (uint32_t)filePos, flags.all);
MoveSegment::DebugPrintList('S', segments);
}
// Print the DDA and active DMs
void DDA::DebugPrintAll(const char *tag) const noexcept
{
DebugPrint(tag);
for (DriveMovement* dm = activeDMs; dm != nullptr; dm = dm->nextDM)
{
dm->DebugPrint();
}
for (DriveMovement* dm = completedDMs; dm != nullptr; dm = dm->nextDM)
{
dm->DebugPrint();
}
}
// 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
bool 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.
// 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 int32_t * const positionNow = prev->DriveCoordinates();
for (size_t axis = numVisibleAxes; axis < numTotalAxes; ++axis)
{
endPoint[axis] = positionNow[axis];
}
flags.all = 0; // set all flags false
// 1. Compute the new endpoints and the movement vector
const Move& move = reprap.GetMove();
if (doMotorMapping)
{
if (!move.CartesianToMotorSteps(nextMove.coords, endPoint, nextMove.isCoordinated)) // transform the axis coordinates if on a delta or CoreXY printer
{
return false; // throw away the move if it couldn't be transformed
}
#if SUPPORT_LINEAR_DELTA
flags.isDeltaMovement = move.IsDeltaMode()
&& (endPoint[X_AXIS] != positionNow[X_AXIS] || endPoint[Y_AXIS] != positionNow[Y_AXIS] || endPoint[Z_AXIS] != positionNow[Z_AXIS]);
#endif
}
bool linearAxesMoving = false;
bool rotationalAxesMoving = false;
bool extrudersMoving = false;
bool forwardExtruding = false;
float accelerations[MaxAxesPlusExtruders];
for (size_t drive = 0; drive < MaxAxesPlusExtruders; drive++)
{
accelerations[drive] = reprap.GetPlatform().Acceleration(drive, nextMove.reduceAcceleration);
if (drive < numVisibleAxes)
{
if (doMotorMapping)
{
endCoordinates[drive] = nextMove.coords[drive];
const float positionDelta = endCoordinates[drive] - prev->GetEndCoordinate(drive, false);
directionVector[drive] = positionDelta;
if (positionDelta != 0.0)
{
if (reprap.GetPlatform().IsAxisRotational(drive) && nextMove.rotationalAxesMentioned)
{
rotationalAxesMoving = true;
}
else if (nextMove.linearAxesMentioned)
{
linearAxesMoving = true;
}
if (Tool::GetXAxes(nextMove.movementTool).IsBitSet(drive) || Tool::GetYAxes(nextMove.movementTool).IsBitSet(drive))
{
flags.xyMoving = true; // this move has XY movement in user space, before axis were mapped
}
}
}
else
{
// Raw motor move on a visible axis
endPoint[drive] = Move::MotorMovementToSteps(drive, nextMove.coords[drive]);
const int32_t delta = endPoint[drive] - positionNow[drive];
directionVector[drive] = (float)delta/reprap.GetPlatform().DriveStepsPerUnit(drive);
if (delta != 0)
{
if (reprap.GetPlatform().IsAxisRotational(drive))
{
rotationalAxesMoving = true;
}
else
{
linearAxesMoving = true;
}
}
}
}
else if (LogicalDriveToExtruder(drive) < reprap.GetGCodes().GetNumExtruders())
{
// 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];
endCoordinates[drive] = directionVector[drive] = movement; // for an extruder, endCoordinates is the amount of movement
if (movement != 0.0)
{
extrudersMoving = true;
if (movement > 0.0)
{
forwardExtruding = true;
}
if (flags.xyMoving && nextMove.usePressureAdvance)
{
const float compensationClocks = reprap.GetMove().GetPressureAdvanceClocks(LogicalDriveToExtruder(drive));
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], reprap.GetPlatform().GetInstantDv(drive)/compensationClocks);
}
}
}
}
else
{
directionVector[drive] = 0.0;
}
}
// 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)
{
prev->endCoordinates[drive] = nextMove.coords[drive];
}
}
return false;
}
// 3. Store some values
tool = nextMove.movementTool;
filePos = nextMove.filePos;
virtualExtruderPosition = nextMove.moveStartVirtualExtruderPosition;
proportionDone = nextMove.proportionDone;
initialUserC0 = nextMove.initialUserC0;
initialUserC1 = nextMove.initialUserC1;
flags.checkEndstops = nextMove.checkEndstops;
flags.canPauseAfter = nextMove.canPauseAfter;
flags.usingStandardFeedrate = nextMove.usingStandardFeedrate;
flags.isPrintingMove = flags.xyMoving && forwardExtruding; // 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.usePressureAdvance = nextMove.usePressureAdvance;
#if SUPPORT_SCANNING_PROBES
flags.scanningProbeMove = nextMove.scanningProbeMove;
#endif
flags.controlLaser = nextMove.isCoordinated && nextMove.checkEndstops == 0;
// 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.endCoordinatesValid = !nextMove.checkEndstops && doMotorMapping;
flags.continuousRotationShortcut = (nextMove.moveType == 0);
#if SUPPORT_LASER || SUPPORT_IOBITS
if (flags.controlLaser)
{
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& 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(reprap.GetPlatform().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, reprap.GetPlatform().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);
acceleration = VectorBoxIntersection(normalisedDirectionVector, accelerations);
if (flags.xyMoving) // apply M204 acceleration limits to XY moves
{
acceleration = min<float>(acceleration, (flags.isPrintingMove) ? nextMove.maxPrintingAcceleration : nextMove.maxTravelAcceleration);
}
deceleration = acceleration;
// 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.GetMotionType(axis) == MotionType::segmentFreeDelta && 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, reprap.GetPlatform().MinMovementSpeed()),
VectorBoxIntersection(normalisedDirectionVector, reprap.GetPlatform().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 the next move asks us to adjust it
if (prev->state == provisional && (move.GetJerkPolicy() != 0 || (flags.isPrintingMove == prev->flags.isPrintingMove && flags.xyMoving == prev->flags.xyMoving)))
{
// 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 = v^2 - 2as
prev->beforePrepare.targetNextSpeed = min<float>(fastSqrtf(deceleration * totalDistance * 2.0), requestedSpeed);
DoLookahead(ring, prev);
startSpeed = prev->endSpeed;
}
else
{
// There is no previous move that we can adjust, so start at zero speed.
startSpeed = 0.0;
}
RecalculateMove(ring);
state = provisional;
return true;
}
// 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
endCoordinates[drive] = prev->endCoordinates[drive]; // adjusting leadscrews doesn't change the position
directionVector[drive] = 0.0;
}
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] * reprap.GetPlatform().DriveStepsPerUnit(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;
virtualExtruderPosition = prev->virtualExtruderPosition;
tool = nullptr;
filePos = prev->filePos;
flags.endCoordinatesValid = prev->flags.endCoordinatesValid;
acceleration = deceleration = reprap.GetPlatform().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);
state = 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;
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 = (reprap.GetMove().GetKinematics().GetMotionType(drive) == MotionType::segmentFreeDelta) ? Z_AXIS : drive;
directionVector[drive] = nextMove.movements[axisToUse];
const int32_t delta = lrintf(nextMove.movements[axisToUse] * reprap.GetPlatform().DriveStepsPerUnit(drive));
endPoint[drive] = prev->endPoint[drive] + delta;
endCoordinates[drive] = prev->endCoordinates[drive];
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;
startSpeed = nextMove.startSpeed;
endSpeed = nextMove.endSpeed;
requestedSpeed = nextMove.requestedSpeed;
acceleration = nextMove.acceleration;
deceleration = nextMove.deceleration;
# 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);
state = provisional;
return true;
}
#endif
#if SUPPORT_REMOTE_COMMANDS
// Set up a remote move. Return true if it represents real movement, else false.
// All values have already been converted to step clocks and the total distance has been normalised to 1.0.
// This one handles the old format movement message, used by older versions of RRF and the ATE
bool DDA::InitFromRemote(const CanMessageMovementLinear& msg) noexcept
{
afterPrepare.moveStartTime = StepTimer::ConvertToLocalTime(msg.whenToExecute);
clocksNeeded = msg.accelerationClocks + msg.steadyClocks + msg.decelClocks;
flags.all = 0;
flags.isRemote = true;
flags.isPrintingMove = flags.usePressureAdvance = (msg.pressureAdvanceDrives != 0);
// Normalise the move to unit distance
totalDistance = 1.0;
// Calculate the speeds and accelerations assuming unit movement length
topSpeed = 2.0/(2 * msg.steadyClocks + (msg.initialSpeedFraction + 1.0) * msg.accelerationClocks + (msg.finalSpeedFraction + 1.0) * msg.decelClocks);
startSpeed = topSpeed * msg.initialSpeedFraction;
endSpeed = topSpeed * msg.finalSpeedFraction;
acceleration = (msg.accelerationClocks == 0) ? 0.0 : (topSpeed * (1.0 - msg.initialSpeedFraction))/msg.accelerationClocks;
deceleration = (msg.decelClocks == 0) ? 0.0 : (topSpeed * (1.0 - msg.finalSpeedFraction))/msg.decelClocks;
// Prepare for movement
PrepParams params; // the default constructor clears params.plan to 'no shaping'
// Set up the move parameters
params.accelDistance = topSpeed * (1.0 + msg.initialSpeedFraction) * msg.accelerationClocks * 0.5;
const float decelDistance = topSpeed * (1.0 + msg.finalSpeedFraction) * msg.decelClocks * 0.5;
params.decelStartDistance = 1.0 - decelDistance;
params.accelClocks = msg.accelerationClocks;
params.steadyClocks = msg.steadyClocks;
params.decelClocks = msg.decelClocks;
params.acceleration = acceleration;
params.deceleration = deceleration;
segments = nullptr;
activeDMs = completedDMs = nullptr;
afterPrepare.drivesMoving.Clear();
for (size_t drive = 0; drive < NumDirectDrivers; drive++)
{
endPoint[drive] = prev->endPoint[drive]; // the steps for this move will be added later
const int32_t delta = (drive < msg.numDrivers) ? msg.perDrive[drive].steps : 0;
directionVector[drive] = (float)delta;
if (delta != 0)
{
EnsureSegments(params); // we are going to need segments
DriveMovement* const pdm = DriveMovement::Allocate(drive);
pdm->totalSteps = labs(delta); // for now this is the number of net steps, but gets adjusted later if there is a reverse in direction
pdm->direction = (delta >= 0); // for now this is the direction of net movement, but gets adjusted later if it is a delta movement
afterPrepare.drivesMoving.SetBit(drive);
reprap.GetPlatform().EnableDrivers(drive, false);
const bool stepsToDo = ((msg.pressureAdvanceDrives & (1u << drive)) != 0)
? pdm->PrepareExtruder(*this, params, (float)delta)
: pdm->PrepareCartesianAxis(*this, params);
if (stepsToDo)
{
InsertDM(pdm);
const int32_t netSteps = (pdm->reverseStartStep < pdm->totalSteps) ? (2 * pdm->reverseStartStep) - pdm->totalSteps : pdm->totalSteps;
if (pdm->direction)
{
endPoint[drive] += netSteps;
}
else
{
endPoint[drive] -= netSteps;
}
// Check for sensible values, print them if they look dubious
if ( reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::PrintAllMoves)
|| (pdm->totalSteps > 1000000 && reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::PrintBadMoves))
)
{
DebugPrintAll("remu_err1");
}
}
else
{
// No steps to do, so release the DM
DriveMovement::Release(pdm);
}
}
}
// 2. Throw it away if there's no real movement.
if (activeDMs == nullptr)
{
// We may have set up the segments, in which case we must recycle them
ReleaseSegments();
return false;
}
if ( reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::PrintAllMoves)
|| params.shapingPlan.debugPrint // show the prepared DDA if debug enabled for both modules
)
{
DebugPrintAll("remu");
}
state = frozen; // must do this last so that the ISR doesn't start executing it before we have finished setting it up
return true;
}
// Set up a remote move. Return true if it represents real movement, else false.
// All values have already been converted to step clocks and the total distance has been normalised to 1.0.
// This version handles the new movement message that includes the input shaping plan and passes extruder movement as distance, not steps
bool DDA::InitFromRemote(const CanMessageMovementLinearShaped& msg) noexcept
{
afterPrepare.moveStartTime = StepTimer::ConvertToLocalTime(msg.whenToExecute);
flags.all = 0;
flags.isRemote = true;
flags.isPrintingMove = flags.usePressureAdvance = msg.usePressureAdvance;
// TODO For now we treat any non-printing move as a non-printing extruder move. Better to pass a flag for it in the CAN message.
flags.isNonPrintingExtruderMove = !flags.isPrintingMove;
// Prepare for movement
PrepParams params;
params.shapingPlan.condensedPlan = msg.shapingPlan;
// Normalise the move to unit distance
params.totalDistance = totalDistance = 1.0;
params.acceleration = acceleration = msg.acceleration;
params.deceleration = deceleration = msg.deceleration;
params.accelClocks = msg.accelerationClocks;
params.steadyClocks = msg.steadyClocks;
params.decelClocks = msg.decelClocks;
clocksNeeded = msg.accelerationClocks + msg.steadyClocks + msg.decelClocks;
// We occasionally receive a message with zero clocks needed. This messes up the calculations, so add one steady clock in this case.
if (clocksNeeded == 0)
{
clocksNeeded = params.steadyClocks = 1;
}
// Set up the plan
segments = nullptr;
reprap.GetMove().GetAxisShaper().GetRemoteSegments(*this, params);
activeDMs = completedDMs = nullptr;
afterPrepare.drivesMoving.Clear();
for (size_t drive = 0; drive < NumDirectDrivers; drive++)
{
endPoint[drive] = prev->endPoint[drive]; // the steps for this move will be added later
if (drive >= msg.numDrivers)
{
directionVector[drive] = 0.0;
}
else if ((msg.extruderDrives & (1u << drive)) != 0)
{
// It's an extruder
const float extrusionRequested = msg.perDrive[drive].extrusion;
directionVector[drive] = extrusionRequested;
if (extrusionRequested != 0.0)
{
DriveMovement* const pdm = DriveMovement::Allocate(drive);
pdm->totalSteps = labs(extrusionRequested); // for now this is the number of net steps, but gets adjusted later if there is a reverse in direction
pdm->direction = (extrusionRequested >= 0.0); // for now this is the direction of net movement, but gets adjusted later if it is a delta movement
afterPrepare.drivesMoving.SetBit(drive);
reprap.GetPlatform().EnableDrivers(drive, false);
const bool stepsToDo = pdm->PrepareExtruder(*this, params, extrusionRequested);
if (stepsToDo)
{
InsertDM(pdm);
const int32_t netSteps = (pdm->reverseStartStep < pdm->totalSteps) ? (2 * pdm->reverseStartStep) - pdm->totalSteps : pdm->totalSteps;
if (pdm->direction)
{
endPoint[drive] += netSteps;
}
else
{
endPoint[drive] -= netSteps;
}
// Check for sensible values, print them if they look dubious
if (pdm->totalSteps > 1000000 && reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::PrintBadMoves))
{
DebugPrintAll("rems_err1");
}
}
else
{
// No steps to do, so release the DM
DriveMovement::Release(pdm);
}
}
}
else
{
const int32_t delta = msg.perDrive[drive].steps;
directionVector[drive] = (float)delta;
if (delta != 0)
{
DriveMovement* const pdm = DriveMovement::Allocate(drive);
pdm->totalSteps = labs(delta); // for now this is the number of net steps, but gets adjusted later if there is a reverse in direction
pdm->direction = (delta >= 0); // for now this is the direction of net movement, but gets adjusted later if it is a delta movement
afterPrepare.drivesMoving.SetBit(drive);
reprap.GetPlatform().EnableDrivers(drive, false);
const bool stepsToDo = pdm->PrepareCartesianAxis(*this, params);
if (stepsToDo)
{
InsertDM(pdm);
const int32_t netSteps = (pdm->reverseStartStep < pdm->totalSteps) ? (2 * pdm->reverseStartStep) - pdm->totalSteps : pdm->totalSteps;
if (pdm->direction)
{
endPoint[drive] += netSteps;
}
else
{
endPoint[drive] -= netSteps;
}
// Check for sensible values, print them if they look dubious
if (pdm->totalSteps > 1000000 && reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::PrintBadMoves))
{
DebugPrintAll("rems_err2");
}
}
else
{
// No steps to do, so release the DM
DriveMovement::Release(pdm);
}
}
}
}
// 2. Throw it away if there's no real movement.
if (activeDMs == nullptr)
{
// We may have set up the segments, in which case we must recycle them
ReleaseSegments();
return false;
}
if ( reprap.GetDebugFlags(Module::Move).IsBitSet(MoveDebugFlags::PrintAllMoves)
|| params.shapingPlan.debugPrint
)
{
DebugPrintAll("rems");
}
state = frozen; // must do this last so that the ISR doesn't start executing it before we have finished setting it up
return true;
}
void DDA::StopDrivers(uint16_t whichDrives) noexcept
{
if (state == executing)
{
for (size_t drive = 0; drive < NumDirectDrivers; ++drive)
{
if (whichDrives & (1u << drive))
{
StopDrive(drive);
}
}
}
}
#endif // SUPPORT_REMOTE_COMMANDS
// 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 are both 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;
bool goingUp = true;
for(;;) // this loop is used to nest lookahead without making recursive calls
{
if (goingUp)
{
// 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
laDDA->MatchSpeeds(); // adjust it if necessary
goingUp = false;
}
else 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->state;
// 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->deceleration * laDDA->totalDistance));