-
Notifications
You must be signed in to change notification settings - Fork 0
/
motion.cpp
2852 lines (2701 loc) · 121 KB
/
motion.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
/*
This file is part of Repetier-Firmware.
Repetier-Firmware is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Repetier-Firmware is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Repetier-Firmware. If not, see <http://www.gnu.org/licenses/>.
This firmware is a nearly complete rewrite of the sprinter firmware
by kliment (https://github.com/kliment/Sprinter)
which based on Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware.
Functions in this file are used to communicate using ascii or repetier protocol.
*/
#include "Repetier.h"
// ================ Sanity checks ================
#ifndef STEP_DOUBLER_FREQUENCY
#error Please add new parameter STEP_DOUBLER_FREQUENCY to your configuration.
#else
#if STEP_DOUBLER_FREQUENCY < 7000 || STEP_DOUBLER_FREQUENCY > 20000
#if CPU_ARCH==ARCH_AVR
#error STEP_DOUBLER_FREQUENCY should be in range 10000-16000.
#endif
#endif
#endif
#ifdef EXTRUDER_SPEED
#error EXTRUDER_SPEED is not used any more. Values are now taken from extruder definition.
#endif
#ifdef ENDSTOPPULLUPS
#error ENDSTOPPULLUPS is now replaced by individual pullup configuration!
#endif
#ifdef EXT0_PID_PGAIN
#error The PID system has changed. Please use the new float number options!
#endif
// ####################################################################################
// # No configuration below this line - just some error checking #
// ####################################################################################
#ifdef SUPPORT_MAX6675
#if !defined SCK_PIN || !defined MOSI_PIN || !defined MISO_PIN
#error For MAX6675 support, you need to define SCK_PIN, MISO_PIN and MOSI_PIN in pins.h
#endif
#endif
#if X_STEP_PIN < 0 || Y_STEP_PIN < 0 || Z_STEP_PIN < 0
#error One of the following pins is not assigned: X_STEP_PIN,Y_STEP_PIN,Z_STEP_PIN
#endif
#if EXT0_STEP_PIN < 0 && NUM_EXTRUDER > 0
#error EXT0_STEP_PIN not set to a pin number.
#endif
#if EXT0_DIR_PIN < 0 && NUM_EXTRUDER > 0
#error EXT0_DIR_PIN not set to a pin number.
#endif
#if PRINTLINE_CACHE_SIZE < 4
#error PRINTLINE_CACHE_SIZE must be at least 5
#endif
//Inactivity shutdown variables
millis_t previousMillisCmd = 0;
millis_t maxInactiveTime = MAX_INACTIVE_TIME * 1000L;
millis_t stepperInactiveTime = STEPPER_INACTIVE_TIME * 1000L;
long baudrate = BAUDRATE; ///< Communication speed rate.
#if USE_ADVANCE
#if ENABLE_QUADRATIC_ADVANCE
int maxadv = 0;
#endif
int maxadv2 = 0;
float maxadvspeed = 0;
#endif
uint8_t pwm_pos[NUM_PWM]; // 0-NUM_EXTRUDER = Heater 0-NUM_EXTRUDER of extruder, NUM_EXTRUDER = Heated bed, NUM_EXTRUDER+1 Board fan, NUM_EXTRUDER+2 = Fan
volatile int waitRelax = 0; // Delay filament relax at the end of print, could be a simple timeout
PrintLine PrintLine::lines[PRINTLINE_CACHE_SIZE]; ///< Cache for print moves.
PrintLine *PrintLine::cur = NULL; ///< Current printing line
#if CPU_ARCH == ARCH_ARM
volatile bool PrintLine::nlFlag = false;
#endif
ufast8_t PrintLine::linesWritePos = 0; ///< Position where we write the next cached line move.
volatile ufast8_t PrintLine::linesCount = 0; ///< Number of lines cached 0 = nothing to do.
ufast8_t PrintLine::linesPos = 0; ///< Position for executing line movement.
/**
Move printer the given number of steps. Puts the move into the queue. Used by e.g. homing commands.
Does not consider rotation but updates position correctly considering rotation. This can be used to
correct positions when changing tools.
\param x Distance in x direction in steps
\param y Distance in y direction in steps
\param z Distance in z direction in steps
\param e Distance in e direction in steps
\param feedrate Feed rate to be used in mm/s. Gets new active feedrate.
\param waitEnd If true will block until move is finished.
\param checkEndstop True if triggering endstop should stop move.
\param pathOptimize If false start and end speeds get fixed to minimum values.
*/
void PrintLine::moveRelativeDistanceInSteps(int32_t x, int32_t y, int32_t z, int32_t e, float feedrate, bool waitEnd, bool checkEndstop, bool pathOptimize) {
#if NUM_EXTRUDER > 0
if(Printer::debugDryrun() || (MIN_EXTRUDER_TEMP > 30 && Extruder::current->tempControl.currentTemperatureC < MIN_EXTRUDER_TEMP && !Printer::isColdExtrusionAllowed() && Extruder::current->tempControl.sensorType != 0))
e = 0; // should not be allowed for current temperature
#endif
#if MOVE_X_WHEN_HOMED == 1 || MOVE_Y_WHEN_HOMED == 1 || MOVE_Z_WHEN_HOMED == 1
if(!Printer::isHoming() && !Printer::isNoDestinationCheck()) {
#if MOVE_X_WHEN_HOMED
if(!Printer::isXHomed())
x = 0;
#endif
#if MOVE_Y_WHEN_HOMED
if(!Printer::isYHomed())
y = 0;
#endif
#if MOVE_Z_WHEN_HOMED
if(!Printer::isZHomed() && !Printer::isZProbingActive())
z = 0;
#endif
}
#endif // MOVE_X_WHEN_HOMED == 1 || MOVE_Y_WHEN_HOMED == 1 || MOVE_Z_WHEN_HOMED == 1
float savedFeedrate = Printer::feedrate;
Printer::destinationSteps[X_AXIS] = Printer::currentPositionSteps[X_AXIS] + x;
Printer::destinationSteps[Y_AXIS] = Printer::currentPositionSteps[Y_AXIS] + y;
Printer::destinationSteps[Z_AXIS] = Printer::currentPositionSteps[Z_AXIS] + z;
Printer::destinationSteps[E_AXIS] = Printer::currentPositionSteps[E_AXIS] + e;
Printer::feedrate = feedrate;
#if NONLINEAR_SYSTEM
if (!queueNonlinearMove(checkEndstop, pathOptimize, false)) {
Com::printWarningFLN(PSTR("moveRelativeDistanceInSteps / queueDeltaMove returns error"));
}
#else
#if DISTORTION_CORRECTION
Printer::destinationSteps[Z_AXIS] -= Printer::zCorrectionStepsIncluded; // correct as it will be added later in Cartesian move computation
#endif
queueCartesianMove(checkEndstop, pathOptimize);
#endif
Printer::feedrate = savedFeedrate;
Printer::updateCurrentPosition(false);
if(waitEnd)
Commands::waitUntilEndOfAllMoves();
previousMillisCmd = HAL::timeInMilliseconds();
}
/** Adds the steps converted to mm to the lastCmdPos position and moves to that position using Printer::moveToReal.
Will use Printer::isPositionAllowed to prevent illegal moves.
\param x Distance in x direction in steps
\param y Distance in y direction in steps
\param z Distance in z direction in steps
\param e Distance in e direction in steps
\param feedrate Feed rate to be used in mm/s. Gets new active feedrate.
\param waitEnd If true will block until move is finished.
\param pathOptimize If false start and end speeds get fixed to minimum values.
*/
void PrintLine::moveRelativeDistanceInStepsReal(int32_t x, int32_t y, int32_t z, int32_t e, float feedrate, bool waitEnd, bool pathOptimize) {
#if MOVE_X_WHEN_HOMED == 1 || MOVE_Y_WHEN_HOMED == 1 || MOVE_Z_WHEN_HOMED == 1
if(!Printer::isHoming() && !Printer::isNoDestinationCheck()) { // prevent movements when not homed
#if MOVE_X_WHEN_HOMED
if(!Printer::isXHomed())
x = 0;
#endif
#if MOVE_Y_WHEN_HOMED
if(!Printer::isYHomed())
y = 0;
#endif
#if MOVE_Z_WHEN_HOMED
if(!Printer::isZHomed() && !Printer::isZProbingActive())
z = 0;
#endif
}
#endif // MOVE_X_WHEN_HOMED == 1 || MOVE_Y_WHEN_HOMED == 1 || MOVE_Z_WHEN_HOMED == 1
Printer::lastCmdPos[X_AXIS] += x * Printer::invAxisStepsPerMM[X_AXIS];
Printer::lastCmdPos[Y_AXIS] += y * Printer::invAxisStepsPerMM[Y_AXIS];
Printer::lastCmdPos[Z_AXIS] += z * Printer::invAxisStepsPerMM[Z_AXIS];
#if LAZY_DUAL_X_AXIS
Printer::sledParked = false;
#endif
if(!Printer::isPositionAllowed( Printer::lastCmdPos[X_AXIS], Printer::lastCmdPos[Y_AXIS], Printer::lastCmdPos[Z_AXIS])) {
return; // ignore move
}
#if NUM_EXTRUDER > 0
if(Printer::debugDryrun() || (MIN_EXTRUDER_TEMP > 30 && Extruder::current->tempControl.currentTemperatureC < MIN_EXTRUDER_TEMP && !Printer::isColdExtrusionAllowed() && Extruder::current->tempControl.sensorType != 0))
e = 0; // should not be allowed for current temperature
#endif
Printer::moveToReal(Printer::lastCmdPos[X_AXIS], Printer::lastCmdPos[Y_AXIS], Printer::lastCmdPos[Z_AXIS],
(Printer::currentPositionSteps[E_AXIS] + e) * Printer::invAxisStepsPerMM[E_AXIS], feedrate, pathOptimize);
Printer::updateCurrentPosition();
if(waitEnd)
Commands::waitUntilEndOfAllMoves();
previousMillisCmd = HAL::timeInMilliseconds();
}
#if !NONLINEAR_SYSTEM
#if DISTORTION_CORRECTION
/* Special version which adds distortion correction to z. Gets called from queueCartesianMove if needed. */
void PrintLine::queueCartesianSegmentTo(uint8_t check_endstops, uint8_t pathOptimize) {
// Correct the bumps
Printer::zCorrectionStepsIncluded = Printer::distortion.correct(Printer::destinationSteps[X_AXIS], Printer::destinationSteps[Y_AXIS], Printer::destinationSteps[Z_AXIS]);
Printer::destinationSteps[Z_AXIS] += Printer::zCorrectionStepsIncluded;
#if DEBUG_DISTORTION
Com::printF(PSTR("zCorr:"), Printer::zCorrectionStepsIncluded * Printer::invAxisStepsPerMM[Z_AXIS], 3);
Com::printF(PSTR(" atX:"), Printer::destinationSteps[X_AXIS]*Printer::invAxisStepsPerMM[X_AXIS]);
Com::printFLN(PSTR(" atY:"), Printer::destinationSteps[Y_AXIS]*Printer::invAxisStepsPerMM[Y_AXIS]);
#endif
PrintLine::waitForXFreeLines(1);
uint8_t newPath = PrintLine::insertWaitMovesIfNeeded(pathOptimize, 0);
PrintLine *p = PrintLine::getNextWriteLine();
float axisDistanceMM[E_AXIS_ARRAY]; // Axis movement in mm
p->flags = (check_endstops ? FLAG_CHECK_ENDSTOPS : 0);
#if MIXING_EXTRUDER
if(Printer::isAllEMotors()) {
p->flags |= FLAG_ALL_E_MOTORS;
}
#endif
p->joinFlags = 0;
if(!pathOptimize) p->setEndSpeedFixed(true);
p->dir = 0;
//Find direction
//Printer::zCorrectionStepsIncluded = 0;
for(uint8_t axis = 0; axis < 4; axis++) {
p->delta[axis] = Printer::destinationSteps[axis] - Printer::currentPositionSteps[axis];
p->secondSpeed = Printer::fanSpeed;
if(axis == E_AXIS) {
if(Printer::mode == PRINTER_MODE_FFF) {
Printer::extrudeMultiplyError += (static_cast<float>(p->delta[E_AXIS]) * Printer::extrusionFactor);
p->delta[E_AXIS] = static_cast<int32_t>(Printer::extrudeMultiplyError);
Printer::extrudeMultiplyError -= p->delta[E_AXIS];
Printer::filamentPrinted += p->delta[E_AXIS] * Printer::invAxisStepsPerMM[axis];
}
#if defined(SUPPORT_LASER) && SUPPORT_LASER
else if(Printer::mode == PRINTER_MODE_LASER) {
p->secondSpeed = ((p->delta[X_AXIS] != 0 || p->delta[Y_AXIS] != 0) && (LaserDriver::laserOn || p->delta[E_AXIS] != 0) ? LaserDriver::intensity : 0);
p->delta[E_AXIS] = 0;
}
#endif
}
if(p->delta[axis] >= 0)
p->setPositiveDirectionForAxis(axis);
else
p->delta[axis] = -p->delta[axis];
axisDistanceMM[axis] = p->delta[axis] * Printer::invAxisStepsPerMM[axis];
if(p->delta[axis]) p->setMoveOfAxis(axis);
Printer::currentPositionSteps[axis] = Printer::destinationSteps[axis];
}
if(p->isNoMove()) {
if(newPath) // need to delete dummy elements, otherwise commands can get locked.
PrintLine::resetPathPlanner();
return; // No steps included
}
float xydist2;
#if ENABLE_BACKLASH_COMPENSATION
if((p->isXYZMove()) && ((p->dir & XYZ_DIRPOS) ^ (Printer::backlashDir & XYZ_DIRPOS)) & (Printer::backlashDir >> 3)) { // We need to compensate backlash, add a move
PrintLine::waitForXFreeLines(2);
uint8_t wpos2 = PrintLine::linesWritePos + 1;
if(wpos2 >= PRINTLINE_CACHE_SIZE) wpos2 = 0;
PrintLine *p2 = &PrintLine::lines[wpos2];
memcpy(p2, p, sizeof(PrintLine)); // Move current data to p2
uint8_t changed = (p->dir & XYZ_DIRPOS) ^ (Printer::backlashDir & XYZ_DIRPOS);
float back_diff[4]; // Axis movement in mm
back_diff[E_AXIS] = 0;
back_diff[X_AXIS] = (changed & 1 ? (p->isXPositiveMove() ? Printer::backlashX : -Printer::backlashX) : 0);
back_diff[Y_AXIS] = (changed & 2 ? (p->isYPositiveMove() ? Printer::backlashY : -Printer::backlashY) : 0);
back_diff[Z_AXIS] = (changed & 4 ? (p->isZPositiveMove() ? Printer::backlashZ : -Printer::backlashZ) : 0);
p->dir &= XYZ_DIRPOS; // x,y and z are already correct
for(uint8_t i = 0; i < 4; i++) {
float f = back_diff[i] * Printer::axisStepsPerMM[i];
p->delta[i] = abs((long)f);
if(p->delta[i]) p->dir |= XSTEP << i;
}
//Define variables that are needed for the Bresenham algorithm. Please note that Z is not currently included in the Bresenham algorithm.
if(p->delta[Y_AXIS] > p->delta[X_AXIS] && p->delta[Y_AXIS] > p->delta[Z_AXIS]) p->primaryAxis = Y_AXIS;
else if (p->delta[X_AXIS] > p->delta[Z_AXIS] ) p->primaryAxis = X_AXIS;
else p->primaryAxis = Z_AXIS;
p->stepsRemaining = p->delta[p->primaryAxis];
//Feedrate calc based on XYZ travel distance
xydist2 = back_diff[X_AXIS] * back_diff[X_AXIS] + back_diff[Y_AXIS] * back_diff[Y_AXIS];
if(p->isZMove())
p->distance = sqrt(xydist2 + back_diff[Z_AXIS] * back_diff[Z_AXIS]);
else
p->distance = sqrt(xydist2);
Printer::backlashDir = (Printer::backlashDir & 56) | (p2->dir & XYZ_DIRPOS);
p->calculateMove(back_diff, pathOptimize, p->primaryAxis);
p = p2; // use saved instance for the real move
}
#endif
//Define variables that are needed for the Bresenham algorithm. Please note that Z is not currently included in the Bresenham algorithm.
if(p->delta[Y_AXIS] > p->delta[X_AXIS] && p->delta[Y_AXIS] > p->delta[Z_AXIS] && p->delta[Y_AXIS] > p->delta[E_AXIS]) p->primaryAxis = Y_AXIS;
else if (p->delta[X_AXIS] > p->delta[Z_AXIS] && p->delta[X_AXIS] > p->delta[E_AXIS]) p->primaryAxis = X_AXIS;
else if (p->delta[Z_AXIS] > p->delta[E_AXIS]) p->primaryAxis = Z_AXIS;
else p->primaryAxis = E_AXIS;
p->stepsRemaining = p->delta[p->primaryAxis];
if(p->isXYZMove()) {
xydist2 = axisDistanceMM[X_AXIS] * axisDistanceMM[X_AXIS] + axisDistanceMM[Y_AXIS] * axisDistanceMM[Y_AXIS];
if(p->isZMove())
p->distance = RMath::max((float)sqrt(xydist2 + axisDistanceMM[Z_AXIS] * axisDistanceMM[Z_AXIS]), fabs(axisDistanceMM[E_AXIS]));
else
p->distance = RMath::max((float)sqrt(xydist2), fabs(axisDistanceMM[E_AXIS]));
} else
p->distance = fabs(axisDistanceMM[E_AXIS]);
p->calculateMove(axisDistanceMM, pathOptimize, p->primaryAxis);
}
#endif
/**
Put a move to the current destination coordinates into the movement cache.
If the cache is full, the method will wait, until a place gets free. During
wait communication and temperature control is enabled.
destinationSteps must be excluding any z correction! We will add that if required here.
@param check_endstops Read end stop during move.
*/
void PrintLine::queueCartesianMove(uint8_t check_endstops, uint8_t pathOptimize) {
ENSURE_POWER
#if LAZY_DUAL_X_AXIS
if(Printer::sledParked && (Printer::currentPositionSteps[X_AXIS] != Printer::destinationSteps[X_AXIS] ||
Printer::currentPositionSteps[Y_AXIS] != Printer::destinationSteps[Y_AXIS] ||
Printer::currentPositionSteps[Z_AXIS] != Printer::destinationSteps[Z_AXIS]))
Printer::sledParked = false;
#endif
Printer::constrainDestinationCoords();
Printer::unsetAllSteppersDisabled();
#if DISTORTION_CORRECTION
if(Printer::distortion.isEnabled() && Printer::destinationSteps[Z_AXIS] < Printer::distortion.zMaxSteps() && Printer::isZProbingActive() == false && !Printer::isHoming()) {
// we are inside correction height so we split all moves in lines of max. 10 mm and add them
// including a z correction
int32_t deltas[E_AXIS_ARRAY], start[E_AXIS_ARRAY];
for(fast8_t i = 0; i < E_AXIS_ARRAY; i++) {
deltas[i] = Printer::destinationSteps[i] - Printer::currentPositionSteps[i];
start[i] = Printer::currentPositionSteps[i];
}
deltas[Z_AXIS] += Printer::zCorrectionStepsIncluded;
start[Z_AXIS] -= Printer::zCorrectionStepsIncluded;
float dx = Printer::invAxisStepsPerMM[X_AXIS] * deltas[X_AXIS];
float dy = Printer::invAxisStepsPerMM[Y_AXIS] * deltas[Y_AXIS];
float len = dx * dx + dy * dy;
if(len < 100) { // no splitting required
queueCartesianSegmentTo(check_endstops, pathOptimize);
return;
}
// we need to split longer lines to follow bed curvature
len = sqrt(len);
int segments = (static_cast<int>(len) + 9) / 10;
#if DEBUG_DISTORTION
Com::printF(PSTR("Split line len:"), len);
Com::printFLN(PSTR(" segments:"), segments);
#endif
for(int i = 1; i <= segments; i++) {
for(fast8_t j = 0; j < E_AXIS_ARRAY; j++) {
Printer::destinationSteps[j] = start[j] + (i * deltas[j]) / segments;
}
queueCartesianSegmentTo(check_endstops, pathOptimize);
}
return;
}
#endif
waitForXFreeLines(1);
uint8_t newPath = insertWaitMovesIfNeeded(pathOptimize, 0);
PrintLine *p = getNextWriteLine();
float axisDistanceMM[E_AXIS_ARRAY]; // Axis movement in mm
p->flags = (check_endstops ? FLAG_CHECK_ENDSTOPS : 0);
#if MIXING_EXTRUDER
if(Printer::isAllEMotors()) {
p->flags |= FLAG_ALL_E_MOTORS;
}
#endif
p->joinFlags = 0;
if(!pathOptimize) p->setEndSpeedFixed(true);
p->dir = 0;
//Find direction
Printer::zCorrectionStepsIncluded = 0;
for(uint8_t axis = 0; axis < 4; axis++) {
p->delta[axis] = Printer::destinationSteps[axis] - Printer::currentPositionSteps[axis];
p->secondSpeed = Printer::fanSpeed;
if(axis == E_AXIS) {
if(Printer::mode == PRINTER_MODE_FFF) {
Printer::extrudeMultiplyError += (static_cast<float>(p->delta[E_AXIS]) * Printer::extrusionFactor);
p->delta[E_AXIS] = static_cast<int32_t>(Printer::extrudeMultiplyError);
Printer::extrudeMultiplyError -= p->delta[E_AXIS];
Printer::filamentPrinted += p->delta[E_AXIS] * Printer::invAxisStepsPerMM[axis];
}
#if defined(SUPPORT_LASER) && SUPPORT_LASER
else if(Printer::mode == PRINTER_MODE_LASER) {
p->secondSpeed = ((p->delta[X_AXIS] != 0 || p->delta[Y_AXIS] != 0) && (LaserDriver::laserOn || p->delta[E_AXIS] != 0) ? LaserDriver::intensity : 0);
p->delta[E_AXIS] = 0;
}
#endif
}
if(p->delta[axis] >= 0)
p->setPositiveDirectionForAxis(axis);
else
p->delta[axis] = -p->delta[axis];
axisDistanceMM[axis] = p->delta[axis] * Printer::invAxisStepsPerMM[axis];
if(p->delta[axis]) p->setMoveOfAxis(axis);
Printer::currentPositionSteps[axis] = Printer::destinationSteps[axis];
}
if(p->isNoMove()) {
if(newPath) // need to delete dummy elements, otherwise commands can get locked.
resetPathPlanner();
return; // No steps included
}
float xydist2;
#if ENABLE_BACKLASH_COMPENSATION
if((p->isXYZMove()) && ((p->dir & XYZ_DIRPOS) ^ (Printer::backlashDir & XYZ_DIRPOS)) & (Printer::backlashDir >> 3)) { // We need to compensate backlash, add a move
waitForXFreeLines(2);
uint8_t wpos2 = linesWritePos + 1;
if(wpos2 >= PRINTLINE_CACHE_SIZE) wpos2 = 0;
PrintLine *p2 = &lines[wpos2];
memcpy(p2, p, sizeof(PrintLine)); // Move current data to p2
uint8_t changed = (p->dir & XYZ_DIRPOS) ^ (Printer::backlashDir & XYZ_DIRPOS);
float back_diff[4]; // Axis movement in mm
back_diff[E_AXIS] = 0;
back_diff[X_AXIS] = (changed & 1 ? (p->isXPositiveMove() ? Printer::backlashX : -Printer::backlashX) : 0);
back_diff[Y_AXIS] = (changed & 2 ? (p->isYPositiveMove() ? Printer::backlashY : -Printer::backlashY) : 0);
back_diff[Z_AXIS] = (changed & 4 ? (p->isZPositiveMove() ? Printer::backlashZ : -Printer::backlashZ) : 0);
p->dir &= XYZ_DIRPOS; // x,y and z are already correct
for(uint8_t i = 0; i < 4; i++) {
float f = back_diff[i] * Printer::axisStepsPerMM[i];
p->delta[i] = abs((long)f);
if(p->delta[i]) p->dir |= XSTEP << i;
}
//Define variables that are needed for the Bresenham algorithm. Please note that Z is not currently included in the Bresenham algorithm.
if(p->delta[Y_AXIS] > p->delta[X_AXIS] && p->delta[Y_AXIS] > p->delta[Z_AXIS]) p->primaryAxis = Y_AXIS;
else if (p->delta[X_AXIS] > p->delta[Z_AXIS] ) p->primaryAxis = X_AXIS;
else p->primaryAxis = Z_AXIS;
p->stepsRemaining = p->delta[p->primaryAxis];
//Feedrate calc based on XYZ travel distance
xydist2 = back_diff[X_AXIS] * back_diff[X_AXIS] + back_diff[Y_AXIS] * back_diff[Y_AXIS];
if(p->isZMove())
p->distance = sqrt(xydist2 + back_diff[Z_AXIS] * back_diff[Z_AXIS]);
else
p->distance = sqrt(xydist2);
// 56 seems to be xstep|ystep|e_posdir which just seems odd
Printer::backlashDir = (Printer::backlashDir & 56) | (p2->dir & XYZ_DIRPOS);
p->calculateMove(back_diff, pathOptimize, p->primaryAxis);
p = p2; // use saved instance for the real move
}
#endif
//Define variables that are needed for the Bresenham algorithm. Please note that Z is not currently included in the Bresenham algorithm.
if(p->delta[Y_AXIS] > p->delta[X_AXIS] && p->delta[Y_AXIS] > p->delta[Z_AXIS] && p->delta[Y_AXIS] > p->delta[E_AXIS]) p->primaryAxis = Y_AXIS;
else if (p->delta[X_AXIS] > p->delta[Z_AXIS] && p->delta[X_AXIS] > p->delta[E_AXIS]) p->primaryAxis = X_AXIS;
else if (p->delta[Z_AXIS] > p->delta[E_AXIS]) p->primaryAxis = Z_AXIS;
else p->primaryAxis = E_AXIS;
p->stepsRemaining = p->delta[p->primaryAxis];
if(p->isXYZMove()) {
xydist2 = axisDistanceMM[X_AXIS] * axisDistanceMM[X_AXIS] + axisDistanceMM[Y_AXIS] * axisDistanceMM[Y_AXIS];
if(p->isZMove())
p->distance = RMath::max((float)sqrt(xydist2 + axisDistanceMM[Z_AXIS] * axisDistanceMM[Z_AXIS]), fabs(axisDistanceMM[E_AXIS]));
else
p->distance = RMath::max((float)sqrt(xydist2), fabs(axisDistanceMM[E_AXIS]));
} else
p->distance = fabs(axisDistanceMM[E_AXIS]);
p->calculateMove(axisDistanceMM, pathOptimize, p->primaryAxis);
}
#endif
void PrintLine::calculateMove(float axisDistanceMM[], uint8_t pathOptimize, fast8_t drivingAxis) {
#if NONLINEAR_SYSTEM
long axisInterval[VIRTUAL_AXIS_ARRAY]; // shortest interval possible for that axis
#else
long axisInterval[E_AXIS_ARRAY];
#endif
//float timeForMove = (float)(F_CPU)*distance / (isXOrYMove() ? RMath::max(Printer::minimumSpeed, Printer::feedrate) : Printer::feedrate); // time is in ticks
float timeForMove = (float)(F_CPU) * distance / Printer::feedrate; // time is in ticks
//bool critical = Printer::isZProbingActive();
if(linesCount < MOVE_CACHE_LOW && timeForMove < LOW_TICKS_PER_MOVE) { // Limit speed to keep cache full.
//Com::printF(PSTR("L:"),(int)linesCount);
//Com::printF(PSTR(" Old "),timeForMove);
timeForMove += (3 * (LOW_TICKS_PER_MOVE - timeForMove)) / (linesCount + 1); // Increase time if queue gets empty. Add more time if queue gets smaller.
//Com::printFLN(PSTR("Slow "),timeForMove);
//critical = true;
}
timeInTicks = timeForMove;
UI_MEDIUM; // do check encoder
// Compute the slowest allowed interval (ticks/step), so maximum feedrate is not violated
int32_t limitInterval0;
int32_t limitInterval = limitInterval0 = timeForMove / stepsRemaining; // until not violated by other constraints it is your target speed
float toTicks = static_cast<float>(F_CPU) / stepsRemaining;
if(isXMove()) {
axisInterval[X_AXIS] = axisDistanceMM[X_AXIS] * toTicks / (Printer::maxFeedrate[X_AXIS]); // mm*ticks/s/(mm/s*steps) = ticks/step
#if !NONLINEAR_SYSTEM || defined(FAST_COREXYZ)
limitInterval = RMath::max(axisInterval[X_AXIS], limitInterval);
#endif
} else axisInterval[X_AXIS] = 0;
if(isYMove()) {
axisInterval[Y_AXIS] = axisDistanceMM[Y_AXIS] * toTicks / Printer::maxFeedrate[Y_AXIS];
#if !NONLINEAR_SYSTEM || defined(FAST_COREXYZ)
limitInterval = RMath::max(axisInterval[Y_AXIS], limitInterval);
#endif
} else axisInterval[Y_AXIS] = 0;
if(isZMove()) { // normally no move in z direction
axisInterval[Z_AXIS] = axisDistanceMM[Z_AXIS] * toTicks / Printer::maxFeedrate[Z_AXIS]; // must prevent overflow!
#if !NONLINEAR_SYSTEM || defined(FAST_COREXYZ)
limitInterval = RMath::max(axisInterval[Z_AXIS], limitInterval);
#endif
} else axisInterval[Z_AXIS] = 0;
if(isEMove()) {
axisInterval[E_AXIS] = axisDistanceMM[E_AXIS] * toTicks / Printer::maxFeedrate[E_AXIS];
limitInterval = RMath::max(axisInterval[E_AXIS], limitInterval);
} else axisInterval[E_AXIS] = 0;
#if DRIVE_SYSTEM == DELTA
if(axisDistanceMM[VIRTUAL_AXIS] >= 0) {// only for deltas all speeds in all directions have same limit
axisInterval[VIRTUAL_AXIS] = axisDistanceMM[VIRTUAL_AXIS] * toTicks / (Printer::maxFeedrate[Z_AXIS]);
limitInterval = RMath::max(axisInterval[VIRTUAL_AXIS], limitInterval);
}
#endif
fullInterval = limitInterval = limitInterval > LIMIT_INTERVAL ? limitInterval : LIMIT_INTERVAL; // This is our target speed
if(limitInterval != limitInterval0) {
// new time at full speed = limitInterval*p->stepsRemaining [ticks]
timeForMove = (float)limitInterval * (float)stepsRemaining; // for large z-distance this overflows with long computation
}
float inverseTimeS = (float)F_CPU / timeForMove;
if(isXMove()) {
axisInterval[X_AXIS] = timeForMove / delta[X_AXIS];
speedX = axisDistanceMM[X_AXIS] * inverseTimeS;
if(isXNegativeMove()) speedX = -speedX;
} else speedX = 0;
if(isYMove()) {
axisInterval[Y_AXIS] = timeForMove / delta[Y_AXIS];
speedY = axisDistanceMM[Y_AXIS] * inverseTimeS;
if(isYNegativeMove()) speedY = -speedY;
} else speedY = 0;
if(isZMove()) {
axisInterval[Z_AXIS] = timeForMove / delta[Z_AXIS];
speedZ = axisDistanceMM[Z_AXIS] * inverseTimeS;
if(isZNegativeMove()) speedZ = -speedZ;
} else speedZ = 0;
if(isEMove()) {
axisInterval[E_AXIS] = timeForMove / delta[E_AXIS];
speedE = axisDistanceMM[E_AXIS] * inverseTimeS;
if(isENegativeMove()) speedE = -speedE;
}
#if NONLINEAR_SYSTEM
axisInterval[VIRTUAL_AXIS] = limitInterval; //timeForMove/stepsRemaining;
#endif
fullSpeed = distance * inverseTimeS;
//long interval = axis_interval[primary_axis]; // time for every step in ticks with full speed
//If acceleration is enabled, do some Bresenham calculations depending on which axis will lead it.
#if RAMP_ACCELERATION
// slowest time to accelerate from v0 to limitInterval determines used acceleration
// t = (v_end-v_start)/a
float slowestAxisPlateauTimeRepro = 1e15; // 1/time to reduce division Unit: 1/s
uint32_t *accel = (isEPositiveMove() ? Printer::maxPrintAccelerationStepsPerSquareSecond : Printer::maxTravelAccelerationStepsPerSquareSecond);
#if defined(INTERPOLATE_ACCELERATION_WITH_Z) && INTERPOLATE_ACCELERATION_WITH_Z != 0
uint32_t newAccel[4];
float accelFac = (100.0 + (EEPROM::accelarationFactorTop() - 100.0) * Printer::currentPosition[Z_AXIS] / Printer::zLength) * 0.01;
#if INTERPOLATE_ACCELERATION_WITH_Z == 1 || INTERPOLATE_ACCELERATION_WITH_Z == 3
newAccel[X_AXIS] = static_cast<int32_t>(accel[X_AXIS] * accelFac);
newAccel[Y_AXIS] = static_cast<int32_t>(accel[Y_AXIS] * accelFac);
#else
newAccel[X_AXIS] = accel[X_AXIS];
newAccel[Y_AXIS] = accel[Y_AXIS];
#endif
#if INTERPOLATE_ACCELERATION_WITH_Z == 2 || INTERPOLATE_ACCELERATION_WITH_Z == 3
newAccel[Z_AXIS] = static_cast<int32_t>(accel[Z_AXIS] * accelFac);
#else
newAccel[Z_AXIS] = accel[Z_AXIS];
#endif
newAccel[E_AXIS] = accel[E_AXIS];
accel = newAccel;
#endif // INTERPOLATE_ACCELERATION_WITH_Z
for(fast8_t i = 0; i < E_AXIS_ARRAY ; i++) {
if(isMoveOfAxis(i))
// v = a * t => t = v/a = F_CPU/(c*a) => 1/t = c*a/F_CPU
slowestAxisPlateauTimeRepro = RMath::min(slowestAxisPlateauTimeRepro, (float)axisInterval[i] * (float)accel[i]); // steps/s^2 * step/tick Ticks/s^2
}
// Errors for delta move are initialized in timer (except extruder)
#if !NONLINEAR_SYSTEM
error[X_AXIS] = error[Y_AXIS] = error[Z_AXIS] = error[E_AXIS] = delta[primaryAxis] >> 1;
#endif
#if NONLINEAR_SYSTEM
error[E_AXIS] = stepsRemaining >> 1;
#endif
invFullSpeed = 1.0 / fullSpeed;
accelerationPrim = slowestAxisPlateauTimeRepro / axisInterval[primaryAxis]; // a = v/t = F_CPU/(c*t): Steps/s^2
//Now we can calculate the new primary axis acceleration, so that the slowest axis max acceleration is not violated
fAcceleration = 262144.0 * (float)accelerationPrim / F_CPU; // will overflow without float!
accelerationDistance2 = 2.0 * distance * slowestAxisPlateauTimeRepro * fullSpeed / ((float)F_CPU); // mm^2/s^2
startSpeed = endSpeed = minSpeed = safeSpeed(drivingAxis);
if(startSpeed > Printer::feedrate)
startSpeed = endSpeed = minSpeed = Printer::feedrate;
// Can accelerate to full speed within the line
if (startSpeed * startSpeed + accelerationDistance2 >= fullSpeed * fullSpeed)
setNominalMove();
vMax = F_CPU / fullInterval; // maximum steps per second, we can reach
// if(p->vMax>46000) // gets overflow in N computation
// p->vMax = 46000;
//p->plateauN = (p->vMax*p->vMax/p->accelerationPrim)>>1;
#if USE_ADVANCE
if(!isXYZMove() || !isEPositiveMove()) {
#if ENABLE_QUADRATIC_ADVANCE
advanceRate = 0; // No head move or E move only or sucking filament back
advanceFull = 0;
#endif
advanceL = 0;
} else {
float advlin = fabs(speedE) * Extruder::current->advanceL * 0.001 * Printer::axisStepsPerMM[E_AXIS];
advanceL = (uint16_t)((65536L * advlin) / vMax); //advanceLscaled = (65536*vE*k2)/vMax
#if ENABLE_QUADRATIC_ADVANCE
advanceFull = 65536 * Extruder::current->advanceK * speedE * speedE; // Steps*65536 at full speed
long steps = (HAL::U16SquaredToU32(vMax)) / (accelerationPrim << 1); // v^2/(2*a) = steps needed to accelerate from 0-vMax
advanceRate = advanceFull / steps;
if((advanceFull >> 16) > maxadv) {
maxadv = (advanceFull >> 16);
maxadvspeed = fabs(speedE);
}
#endif
if(advlin > maxadv2) {
maxadv2 = advlin;
maxadvspeed = fabs(speedE);
}
}
#endif
UI_MEDIUM; // do check encoder
updateTrapezoids();
// how much steps on primary axis do we need to reach target feedrate
//p->plateauSteps = (long) (((float)p->acceleration *0.5f / slowest_axis_plateau_time_repro + p->vMin) *1.01f/slowest_axis_plateau_time_repro);
#else
#if USE_ADVANCE
#if ENABLE_QUADRATIC_ADVANCE
advanceRate = 0; // No advance for constant speeds
advanceFull = 0;
#endif
#endif
#endif
#ifdef DEBUG_STEPCOUNT
// Set in delta move calculation
#if !NONLINEAR_SYSTEM
totalStepsRemaining = delta[X_AXIS] + delta[Y_AXIS] + delta[Z_AXIS];
#endif
#endif
#ifdef DEBUG_QUEUE_MOVE
if(Printer::debugEcho()) {
logLine();
Com::printFLN(Com::tDBGLimitInterval, limitInterval);
Com::printFLN(Com::tDBGMoveDistance, distance);
Com::printFLN(Com::tDBGCommandedFeedrate, Printer::feedrate);
Com::printFLN(Com::tDBGConstFullSpeedMoveTime, timeForMove);
}
#endif
// Make result permanent
if (pathOptimize) waitRelax = 70;
pushLine();
DEBUG_MEMORY;
}
/**
This is the path planner.
It goes from the last entry and tries to increase the end speed of previous moves in a fashion that the maximum jerk
is never exceeded. If a segment with reached maximum speed is met, the planner stops. Everything left from this
is already optimal from previous updates.
The first 2 entries in the queue are not checked. The first is the one that is already in print and the following will likely to become active.
The method is called before lines_count is increased!
*/
void PrintLine::updateTrapezoids() {
ufast8_t first = linesWritePos;
PrintLine *firstLine;
PrintLine *act = &lines[linesWritePos];
InterruptProtectedBlock noInts;
// First we find out how far back we could go with optimization.
ufast8_t maxfirst = linesPos; // first non fixed segment we might change
if(maxfirst != linesWritePos)
nextPlannerIndex(maxfirst); // don't touch the line printing
// Now ignore enough segments to gain enough time for path planning
millis_t timeleft = 0;
// Skip as many stored moves as needed to gain enough time for computation
#if PRINTLINE_CACHE_SIZE < 10
#define minTime 4500L * PRINTLINE_CACHE_SIZE
#else
#define minTime 45000L
#endif
while(timeleft < minTime && maxfirst != linesWritePos) {
timeleft += lines[maxfirst].timeInTicks;
nextPlannerIndex(maxfirst);
}
// Search last fixed element
while(first != maxfirst && !lines[first].isEndSpeedFixed())
previousPlannerIndex(first);
if(first != linesWritePos && lines[first].isEndSpeedFixed())
nextPlannerIndex(first);
// now first points to last segment before the end speed is fixed
// so start speed is also fixed.
if(first == linesWritePos) { // Nothing to plan, only new element present
act->block(); // Prevent stepper interrupt from using this
noInts.unprotect();
act->setStartSpeedFixed(true);
act->updateStepsParameter();
act->unblock();
return;
}
// now we have at least one additional move for optimization
// that is not a wait move
// First is now the new element or the first element with non fixed end speed.
// anyhow, the start speed of first is fixed
firstLine = &lines[first];
firstLine->block(); // don't let printer touch this or following segments during update
noInts.unprotect();
ufast8_t previousIndex = linesWritePos;
previousPlannerIndex(previousIndex);
PrintLine *previous = &lines[previousIndex]; // segment before the one we are inserting
#if DRIVE_SYSTEM != DELTA
// filters z-move<->not z-move
/* if((previous->primaryAxis == Z_AXIS && act->primaryAxis != Z_AXIS) || (previous->primaryAxis != Z_AXIS && act->primaryAxis == Z_AXIS))
{
previous->setEndSpeedFixed(true);
act->setStartSpeedFixed(true);
act->updateStepsParameter();
firstLine->unblock();
return;
}*/
#endif // DRIVE_SYSTEM
if(previous->isEOnlyMove() != act->isEOnlyMove()) {
previous->maxJunctionSpeed = previous->endSpeed; // act->startSpeed; // maybe remove this. Previous should be at minimum and systems have nothing in common
previous->setEndSpeedFixed(true);
act->setStartSpeedFixed(true);
act->updateStepsParameter();
firstLine->unblock();
return;
} else {
computeMaxJunctionSpeed(previous, act); // Set maximum junction speed if we have a real move before
}
// Increase speed if possible neglecting current speed
backwardPlanner(linesWritePos, first);
// Reduce speed to reachable speeds
forwardPlanner(first);
#ifdef DEBUG_PLANNER
if(Printer::debugEcho()) {
Com::printF(PSTR("Planner: "), (int)linesCount);
previousPlannerIndex(first);
Com::printF(PSTR(" F "), lines[first].startSpeed, 1);
Com::printF(PSTR(" - "), lines[first].endSpeed, 1);
Com::printF(PSTR("("), lines[first].maxJunctionSpeed, 1);
Com::printF(PSTR(","), (int)lines[first].joinFlags);
nextPlannerIndex(first);
}
#endif
// Update precomputed data
do {
lines[first].updateStepsParameter();
#ifdef DEBUG_PLANNER
if(Printer::debugEcho()) {
Com::printF(PSTR(" / "), lines[first].startSpeed, 1);
Com::printF(PSTR(" - "), lines[first].endSpeed, 1);
Com::printF(PSTR("("), lines[first].maxJunctionSpeed, 1);
Com::printF(PSTR(","), (int)lines[first].joinFlags);
#ifdef DEBUG_QUEUE_MOVE
Com::println();
#endif
}
#endif
//noInts.protect();
lines[first].unblock(); // start with first block to release next used segment as early as possible
nextPlannerIndex(first);
lines[first].block();
//noInts.unprotect();
} while(first != linesWritePos);
act->updateStepsParameter();
act->unblock();
#ifdef DEBUG_PLANNER
if(Printer::debugEcho()) {
Com::printF(PSTR(" / "), lines[first].startSpeed, 1);
Com::printF(PSTR(" - "), lines[first].endSpeed, 1);
Com::printF(PSTR("("), lines[first].maxJunctionSpeed, 1);
Com::printFLN(PSTR(","), (int)lines[first].joinFlags);
}
#endif
}
/* Computes the maximum junction speed of the newly added segment under
optimal conditions. There is no guarantee that the previous move will be able to reach the
speed at all, but if it could exceed it will never exceed this theoretical limit.
if you define ALTERNATIVE_JERK the new jerk computations are used. These
use the cosine of the angle and the maximum speed
Jerk = (1-cos(alpha))*min(v1,v2)
This sets jerk to 0 on zero angle change.
Old New
0°: 0 0
30°: 51,8 13.4
45°: 76.53 29.3
90°: 141 100
180°: 200 200
Speed from 100 to 200
Old New(min) New(max)
0°: 100 0 0
30°: 123,9 13.4 26.8
45°: 147.3 29.3 58.6
90°: 223 100 200
180°: 300 200 400
*/
inline void PrintLine::computeMaxJunctionSpeed(PrintLine *previous, PrintLine *current) {
#if NONLINEAR_SYSTEM
/* if (previous->moveID == current->moveID) // Avoid computing junction speed for split nonlinear lines
{
if(previous->fullSpeed > current->fullSpeed)
previous->maxJunctionSpeed = current->fullSpeed;
else
previous->maxJunctionSpeed = previous->fullSpeed;
return;
}*/
#endif
#if USE_ADVANCE
if(Printer::isAdvanceActivated()) {
// if we start/stop extrusion we need to do so with lowest possible end speed
// or advance would leave a drolling extruder and can not adjust fast enough.
if(previous->isEMove() != current->isEMove()) {
previous->setEndSpeedFixed(true);
current->setStartSpeedFixed(true);
previous->endSpeed = current->startSpeed = previous->maxJunctionSpeed = RMath::min(previous->endSpeed, current->startSpeed);
previous->invalidateParameter();
current->invalidateParameter();
return;
}
}
#endif // USE_ADVANCE
// if we are here we have to identical move types
// either pure extrusion -> pure extrusion or
// move -> move (with or without extrusion)
// First we compute the normalized jerk for speed 1
float factor = 1.0;
float lengthFactor = 1.0;
#ifdef REDUCE_ON_SMALL_SEGMENTS
if(previous->distance < MAX_JERK_DISTANCE)
lengthFactor = static_cast<float>(MAX_JERK_DISTANCE * MAX_JERK_DISTANCE) / (previous->distance * previous->distance);
#endif
float maxJoinSpeed = RMath::min(current->fullSpeed, previous->fullSpeed);
#if (DRIVE_SYSTEM == DELTA) // No point computing Z Jerk separately for delta moves
#ifdef ALTERNATIVE_JERK
float jerk = maxJoinSpeed * lengthFactor * (1.0 - (current->speedX * previous->speedX + current->speedY * previous->speedY + current->speedZ * previous->speedZ) / (current->fullSpeed * previous->fullSpeed));
#else
float dx = current->speedX - previous->speedX;
float dy = current->speedY - previous->speedY;
float dz = current->speedZ - previous->speedZ;
float jerk = sqrt(dx * dx + dy * dy + dz * dz) * lengthFactor;
#endif // ALTERNATIVE_JERK
#else // DELTA
#ifdef ALTERNATIVE_JERK
float jerk = maxJoinSpeed * lengthFactor * (1.0 - (current->speedX * previous->speedX + current->speedY * previous->speedY + current->speedZ * previous->speedZ) / (current->fullSpeed * previous->fullSpeed));
#else
float dx = current->speedX - previous->speedX;
float dy = current->speedY - previous->speedY;
float jerk = sqrt(dx * dx + dy * dy) * lengthFactor;
#endif // ALTERNATIVE_JERK
#endif // DELTA
if(jerk > Printer::maxJerk) {
factor = Printer::maxJerk / jerk; // always < 1.0!
if(factor * maxJoinSpeed * 2.0 < Printer::maxJerk)
factor = Printer::maxJerk / (2.0 * maxJoinSpeed);
}
#if DRIVE_SYSTEM != DELTA
if((previous->dir | current->dir) & ZSTEP) {
float dz = fabs(current->speedZ - previous->speedZ);
if(dz > Printer::maxZJerk)
factor = RMath::min(factor, Printer::maxZJerk / dz);
}
#endif
float eJerk = fabs(current->speedE - previous->speedE);
if(eJerk > Extruder::current->maxStartFeedrate)
factor = RMath::min(factor, Extruder::current->maxStartFeedrate / eJerk);
previous->maxJunctionSpeed = maxJoinSpeed * factor; // set speed limit
#ifdef DEBUG_QUEUE_MOVE
if(Printer::debugEcho()) {
Com::printF(PSTR("ID:"), (int)previous);
Com::printFLN(PSTR(" MJ:"), previous->maxJunctionSpeed);
}
#endif // DEBUG_QUEUE_MOVE
}
/** Update parameter used by updateTrapezoids
Computes the acceleration/deceleration steps and advanced parameter associated.
*/
void PrintLine::updateStepsParameter() {
if(areParameterUpToDate() || isWarmUp()) return;
float startFactor = startSpeed * invFullSpeed;
float endFactor = endSpeed * invFullSpeed;
vStart = vMax * startFactor; //starting speed
vEnd = vMax * endFactor;
#if CPU_ARCH == ARCH_AVR
uint32_t vmax2 = HAL::U16SquaredToU32(vMax);
accelSteps = ((vmax2 - HAL::U16SquaredToU32(vStart)) / (accelerationPrim << 1)) + 1; // Always add 1 for missing precision
decelSteps = ((vmax2 - HAL::U16SquaredToU32(vEnd)) / (accelerationPrim << 1)) + 1;
#else
uint64_t vmax2 = static_cast<uint64_t>(vMax) * static_cast<uint64_t>(vMax);
accelSteps = ((vmax2 - static_cast<uint64_t>(vStart) * static_cast<uint64_t>(vStart)) / (accelerationPrim << 1)) + 1; // Always add 1 for missing precision
decelSteps = ((vmax2 - static_cast<uint64_t>(vEnd) * static_cast<uint64_t>(vEnd)) / (accelerationPrim << 1)) + 1;
#endif
#if USE_ADVANCE
#if ENABLE_QUADRATIC_ADVANCE
advanceStart = (float)advanceFull * startFactor * startFactor;
advanceEnd = (float)advanceFull * endFactor * endFactor;
#endif
#endif
if(static_cast<int32_t>(accelSteps + decelSteps) >= stepsRemaining) { // can't reach limit speed
uint32_t red = (accelSteps + decelSteps - stepsRemaining) >> 1;
accelSteps = accelSteps - RMath::min(static_cast<int32_t>(accelSteps), static_cast<int32_t>(red));
decelSteps = decelSteps - RMath::min(static_cast<int32_t>(decelSteps), static_cast<int32_t>(red));
}
setParameterUpToDate();
#ifdef DEBUG_QUEUE_MOVE
if(Printer::debugEcho()) {
Com::printFLN(Com::tDBGId, (int)this);
Com::printF(Com::tDBGVStartEnd, (long)vStart);
Com::printFLN(Com::tSlash, (long)vEnd);
Com::printF(Com::tDBAccelSteps, (long)accelSteps);
Com::printF(Com::tSlash, (long)decelSteps);
Com::printFLN(Com::tSlash, (long)stepsRemaining);
Com::printF(Com::tDBGStartEndSpeed, startSpeed, 1);
Com::printFLN(Com::tSlash, endSpeed, 1);
Com::printFLN(Com::tDBGFlags, (uint32_t)flags);
Com::printFLN(Com::tDBGJoinFlags, (uint32_t)joinFlags);
}
#endif
}
/**
Compute the maximum speed from the last entered move.
The backwards planner traverses the moves from last to first looking at deceleration. The RHS of the accelerate/decelerate ramp.
start = last line inserted
last = last element until we check
*/
inline void PrintLine::backwardPlanner(ufast8_t start, ufast8_t last) {
PrintLine *act = &lines[start], *previous;
float lastJunctionSpeed = act->endSpeed; // Start always with safe speed
//PREVIOUS_PLANNER_INDEX(last); // Last element is already fixed in start speed
while(start != last) {
previousPlannerIndex(start);
previous = &lines[start];
previous->block();
// Avoid speed calculation once cruising in split delta move
#if NONLINEAR_SYSTEM
/*if (previous->moveID == act->moveID && lastJunctionSpeed == previous->maxJunctionSpeed)
{
act->startSpeed = RMath::max(act->minSpeed, previous->endSpeed = lastJunctionSpeed);
previous->invalidateParameter();
act->invalidateParameter();
}*/
#endif
/* if(prev->isEndSpeedFixed()) // Nothing to update from here on, happens when path optimize disabled
{
act->setStartSpeedFixed(true);
return;
}*/
// Avoid speed calculations if we know we can accelerate within the line
lastJunctionSpeed = (act->isNominalMove() ? act->fullSpeed : sqrt(lastJunctionSpeed * lastJunctionSpeed + act->accelerationDistance2)); // acceleration is acceleration*distance*2! What can be reached if we try?
// If that speed is more that the maximum junction speed allowed then ...
if(lastJunctionSpeed >= previous->maxJunctionSpeed) { // Limit is reached
// If the previous line's end speed has not been updated to maximum speed then do it now
if(previous->endSpeed != previous->maxJunctionSpeed) {
previous->invalidateParameter(); // Needs recomputation
previous->endSpeed = RMath::max(previous->minSpeed, previous->maxJunctionSpeed); // possibly unneeded???
}
// If actual line start speed has not been updated to maximum speed then do it now
if(act->startSpeed != previous->maxJunctionSpeed) {
act->startSpeed = RMath::max(act->minSpeed, previous->maxJunctionSpeed); // possibly unneeded???
act->invalidateParameter();
}
lastJunctionSpeed = previous->endSpeed;
} else {
// Block previous end and act start as calculated speed and recalculate plateau speeds (which could move the speed higher again)
act->startSpeed = RMath::max(act->minSpeed, lastJunctionSpeed);
lastJunctionSpeed = previous->endSpeed = RMath::max(lastJunctionSpeed, previous->minSpeed);
previous->invalidateParameter();
act->invalidateParameter();
}
act = previous;
} // while loop
}