Subversion Repositories Tronxy-X3A-Marlin

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 ron 1
/**
2
 * Marlin 3D Printer Firmware
3
 * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
 *
5
 * Based on Sprinter and grbl.
6
 * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
 
23
/**
24
 * planner.cpp
25
 *
26
 * Buffer movement commands and manage the acceleration profile plan
27
 *
28
 * Derived from Grbl
29
 * Copyright (c) 2009-2011 Simen Svale Skogsrud
30
 *
31
 * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
32
 *
33
 *
34
 * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
35
 *
36
 * s == speed, a == acceleration, t == time, d == distance
37
 *
38
 * Basic definitions:
39
 *   Speed[s_, a_, t_] := s + (a*t)
40
 *   Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
41
 *
42
 * Distance to reach a specific speed with a constant acceleration:
43
 *   Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
44
 *   d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
45
 *
46
 * Speed after a given distance of travel with constant acceleration:
47
 *   Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
48
 *   m -> Sqrt[2 a d + s^2]
49
 *
50
 * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
51
 *
52
 * When to start braking (di) to reach a specified destination speed (s2) after accelerating
53
 * from initial speed s1 without ever stopping at a plateau:
54
 *   Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
55
 *   di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
56
 *
57
 * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
58
 *
59
 * --
60
 *
61
 * The fast inverse function needed for Bézier interpolation for AVR
62
 * was designed, written and tested by Eduardo José Tagle on April/2018
63
 */
64
 
65
#include "planner.h"
66
#include "stepper.h"
67
#include "temperature.h"
68
#include "ultralcd.h"
69
#include "language.h"
70
#include "parser.h"
71
 
72
#include "Marlin.h"
73
 
74
#if ENABLED(MESH_BED_LEVELING)
75
  #include "mesh_bed_leveling.h"
76
#elif ENABLED(AUTO_BED_LEVELING_UBL)
77
  #include "ubl.h"
78
#endif
79
 
80
#if ENABLED(AUTO_POWER_CONTROL)
81
  #include "power.h"
82
#endif
83
 
84
// Delay for delivery of first block to the stepper ISR, if the queue contains 2 or
85
// fewer movements. The delay is measured in milliseconds, and must be less than 250ms
86
#define BLOCK_DELAY_FOR_1ST_MOVE 100
87
 
88
Planner planner;
89
 
90
  // public:
91
 
92
/**
93
 * A ring buffer of moves described in steps
94
 */
95
block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
96
volatile uint8_t Planner::block_buffer_head,    // Index of the next block to be pushed
97
                 Planner::block_buffer_nonbusy, // Index of the first non-busy block
98
                 Planner::block_buffer_planned, // Index of the optimally planned block
99
                 Planner::block_buffer_tail;    // Index of the busy block, if any
100
uint16_t Planner::cleaning_buffer_counter;      // A counter to disable queuing of blocks
101
uint8_t Planner::delay_before_delivering;       // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
102
 
103
uint32_t Planner::max_acceleration_mm_per_s2[NUM_AXIS_N],    // (mm/s^2) M201 XYZE
104
         Planner::max_acceleration_steps_per_s2[NUM_AXIS_N], // (steps/s^2) Derived from mm_per_s2
105
         Planner::min_segment_time_us;                       // (µs) M205 Q
106
 
107
float Planner::max_feedrate_mm_s[NUM_AXIS_N], // (mm/s) M203 XYZE - Max speeds
108
      Planner::axis_steps_per_mm[NUM_AXIS_N], // (steps) M92 XYZE - Steps per millimeter
109
      Planner::steps_to_mm[NUM_AXIS_N],       // (mm) Millimeters per step
110
      Planner::min_feedrate_mm_s,             // (mm/s) M205 S - Minimum linear feedrate
111
      Planner::acceleration,                  // (mm/s^2) M204 S - Normal acceleration. DEFAULT ACCELERATION for all printing moves.
112
      Planner::retract_acceleration,          // (mm/s^2) M204 R - Retract acceleration. Filament pull-back and push-forward while standing still in the other axes
113
      Planner::travel_acceleration,           // (mm/s^2) M204 T - Travel acceleration. DEFAULT ACCELERATION for all NON printing moves.
114
      Planner::min_travel_feedrate_mm_s;      // (mm/s) M205 T - Minimum travel feedrate
115
 
116
#if ENABLED(JUNCTION_DEVIATION)
117
  float Planner::junction_deviation_mm;       // (mm) M205 J
118
  #if ENABLED(LIN_ADVANCE)
119
    #if ENABLED(DISTINCT_E_FACTORS)
120
      float Planner::max_e_jerk[EXTRUDERS];   // Calculated from junction_deviation_mm
121
    #else
122
      float Planner::max_e_jerk;
123
    #endif
124
  #endif
125
#else
126
  float Planner::max_jerk[NUM_AXIS];          // (mm/s^2) M205 XYZE - The largest speed change requiring no acceleration.
127
#endif
128
 
129
#if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
130
  float Planner::k0[MOV_AXIS],
131
        Planner::k1[MOV_AXIS],
132
        Planner::k2[MOV_AXIS],
133
        Planner::sqrtk1[MOV_AXIS];
134
#endif
135
 
136
#if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
137
  bool Planner::abort_on_endstop_hit = false;
138
#endif
139
 
140
#if ENABLED(DISTINCT_E_FACTORS)
141
  uint8_t Planner::last_extruder = 0;     // Respond to extruder change
142
  #define _EINDEX (E_AXIS + active_extruder)
143
#else
144
  #define _EINDEX E_AXIS
145
#endif
146
 
147
int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
148
 
149
float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement
150
 
151
#if DISABLED(NO_VOLUMETRICS)
152
  float Planner::filament_size[EXTRUDERS],          // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
153
        Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area
154
        Planner::volumetric_multiplier[EXTRUDERS];  // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
155
#endif
156
 
157
#if HAS_LEVELING
158
  bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
159
  #if ABL_PLANAR
160
    matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
161
  #endif
162
  #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
163
    float Planner::z_fade_height,      // Initialized by settings.load()
164
          Planner::inverse_z_fade_height,
165
          Planner::last_fade_z;
166
  #endif
167
#else
168
  constexpr bool Planner::leveling_active;
169
#endif
170
 
171
#if ENABLED(SKEW_CORRECTION)
172
  #if ENABLED(SKEW_CORRECTION_GCODE)
173
    float Planner::xy_skew_factor;
174
  #else
175
    constexpr float Planner::xy_skew_factor;
176
  #endif
177
  #if ENABLED(SKEW_CORRECTION_FOR_Z) && ENABLED(SKEW_CORRECTION_GCODE)
178
    float Planner::xz_skew_factor, Planner::yz_skew_factor;
179
  #else
180
    constexpr float Planner::xz_skew_factor, Planner::yz_skew_factor;
181
  #endif
182
#endif
183
 
184
#if ENABLED(AUTOTEMP)
185
  float Planner::autotemp_max = 250,
186
        Planner::autotemp_min = 210,
187
        Planner::autotemp_factor = 0.1f;
188
  bool Planner::autotemp_enabled = false;
189
#endif
190
 
191
// private:
192
 
193
int32_t Planner::position[NUM_AXIS] = { 0 };
194
 
195
uint32_t Planner::cutoff_long;
196
 
197
float Planner::previous_speed[NUM_AXIS],
198
      Planner::previous_nominal_speed_sqr;
199
 
200
#if ENABLED(DISABLE_INACTIVE_EXTRUDER)
201
  uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
202
#endif
203
 
204
#ifdef XY_FREQUENCY_LIMIT
205
  // Old direction bits. Used for speed calculations
206
  unsigned char Planner::old_direction_bits = 0;
207
  // Segment times (in µs). Used for speed calculations
208
  uint32_t Planner::axis_segment_time_us[2][3] = { { MAX_FREQ_TIME_US + 1, 0, 0 }, { MAX_FREQ_TIME_US + 1, 0, 0 } };
209
#endif
210
 
211
#if ENABLED(LIN_ADVANCE)
212
  float Planner::extruder_advance_K; // Initialized by settings.load()
213
#endif
214
 
215
#if HAS_POSITION_FLOAT
216
  float Planner::position_float[NUM_AXIS]; // Needed for accurate maths. Steps cannot be used!
217
#endif
218
 
219
#if ENABLED(ULTRA_LCD)
220
  volatile uint32_t Planner::block_buffer_runtime_us = 0;
221
#endif
222
 
223
/**
224
 * Class and Instance Methods
225
 */
226
 
227
Planner::Planner() { init(); }
228
 
229
void Planner::init() {
230
  ZERO(position);
231
  #if HAS_POSITION_FLOAT
232
    ZERO(position_float);
233
  #endif
234
  ZERO(previous_speed);
235
  previous_nominal_speed_sqr = 0;
236
  #if ABL_PLANAR
237
    bed_level_matrix.set_to_identity();
238
  #endif
239
  clear_block_buffer();
240
  delay_before_delivering = 0;
241
}
242
 
243
#if ENABLED(S_CURVE_ACCELERATION)
244
 
245
  /**
246
   * This routine returns 0x1000000 / d, getting the inverse as fast as possible.
247
   * A fast-converging iterative Newton-Raphson method can reach full precision in
248
   * just 1 iteration, and takes 211 cycles (worst case; the mean case is less, up
249
   * to 30 cycles for small divisors), instead of the 500 cycles a normal division
250
   * would take.
251
   *
252
   * Inspired by the following page:
253
   *  https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
254
   *
255
   * Suppose we want to calculate  floor(2 ^ k / B)  where B is a positive integer
256
   * Then, B must be <= 2^k, otherwise, the quotient is 0.
257
   *
258
   * The Newton - Raphson iteration for x = B / 2 ^ k yields:
259
   *  q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
260
   *
261
   * This can be rearranged to:
262
   *  q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
263
   *
264
   * Each iteration requires only integer multiplications and bit shifts.
265
   * It doesn't necessarily converge to floor(2 ^ k / B) but in the worst case
266
   * it eventually alternates between floor(2 ^ k / B) and ceil(2 ^ k / B).
267
   * So it checks for this case and extracts floor(2 ^ k / B).
268
   *
269
   * A simple but important optimization for this approach is to truncate
270
   * multiplications (i.e., calculate only the higher bits of the product) in the
271
   * early iterations of the Newton - Raphson method. This is done so the results
272
   * of the early iterations are far from the quotient. Then it doesn't matter if
273
   * they are done inaccurately.
274
   * It's important to pick a good starting value for x. Knowing how many
275
   * digits the divisor has, it can be estimated:
276
   *
277
   *   2^k / x = 2 ^ log2(2^k / x)
278
   *   2^k / x = 2 ^(log2(2^k)-log2(x))
279
   *   2^k / x = 2 ^(k*log2(2)-log2(x))
280
   *   2^k / x = 2 ^ (k-log2(x))
281
   *   2^k / x >= 2 ^ (k-floor(log2(x)))
282
   *   floor(log2(x)) is simply the index of the most significant bit set.
283
   *
284
   * If this estimation can be improved even further the number of iterations can be
285
   * reduced a lot, saving valuable execution time.
286
   * The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
287
   * Research, Silicon Valley,August 26, 2008, available at
288
   * https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
289
   * suggests, for its integer division algorithm, using a table to supply the first
290
   * 8 bits of precision, then, due to the quadratic convergence nature of the
291
   * Newton-Raphon iteration, just 2 iterations should be enough to get maximum
292
   * precision of the division.
293
   * By precomputing values of inverses for small denominator values, just one
294
   * Newton-Raphson iteration is enough to reach full precision.
295
   * This code uses the top 9 bits of the denominator as index.
296
   *
297
   * The AVR assembly function implements this C code using the data below:
298
   *
299
   *  // For small divisors, it is best to directly retrieve the results
300
   *  if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
301
   *
302
   *  // Compute initial estimation of 0x1000000/x -
303
   *  // Get most significant bit set on divider
304
   *  uint8_t idx = 0;
305
   *  uint32_t nr = d;
306
   *  if (!(nr & 0xFF0000)) {
307
   *    nr <<= 8; idx += 8;
308
   *    if (!(nr & 0xFF0000)) { nr <<= 8; idx += 8; }
309
   *  }
310
   *  if (!(nr & 0xF00000)) { nr <<= 4; idx += 4; }
311
   *  if (!(nr & 0xC00000)) { nr <<= 2; idx += 2; }
312
   *  if (!(nr & 0x800000)) { nr <<= 1; idx += 1; }
313
   *
314
   *  // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
315
   *  uint32_t tidx = nr >> 15,                                       // top 9 bits. bit8 is always set
316
   *           ie = inv_tab[tidx & 0xFF] + 256,                       // Get the table value. bit9 is always set
317
   *           x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8));  // Position the estimation at the proper place
318
   *
319
   *  x = uint32_t((x * uint64_t(_BV(25) - x * d)) >> 24);            // Refine estimation by newton-raphson. 1 iteration is enough
320
   *  const uint32_t r = _BV(24) - x * d;                             // Estimate remainder
321
   *  if (r >= d) x++;                                                // Check whether to adjust result
322
   *  return uint32_t(x);                                             // x holds the proper estimation
323
   *
324
   */
325
  static uint32_t get_period_inverse(uint32_t d) {
326
 
327
    static const uint8_t inv_tab[256] PROGMEM = {
328
      255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
329
      225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
330
      199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
331
      175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
332
      153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
333
      134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
334
      116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
335
      100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
336
      85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
337
      71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
338
      59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
339
      47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
340
      36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
341
      26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
342
      17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
343
      8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
344
    };
345
 
346
    // For small denominators, it is cheaper to directly store the result.
347
    //  For bigger ones, just ONE Newton-Raphson iteration is enough to get
348
    //  maximum precision we need
349
    static const uint32_t small_inv_tab[111] PROGMEM = {
350
      16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
351
      1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
352
      524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
353
      349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
354
      262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
355
      209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
356
      174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
357
    };
358
 
359
    // For small divisors, it is best to directly retrieve the results
360
    if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
361
 
362
    register uint8_t r8 = d & 0xFF,
363
                     r9 = (d >> 8) & 0xFF,
364
                     r10 = (d >> 16) & 0xFF,
365
                     r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
366
    register const uint8_t* ptab = inv_tab;
367
 
368
    __asm__ __volatile__(
369
      // %8:%7:%6 = interval
370
      // r31:r30: MUST be those registers, and they must point to the inv_tab
371
 
372
      A("clr %13")                      // %13 = 0
373
 
374
      // Now we must compute
375
      // result = 0xFFFFFF / d
376
      // %8:%7:%6 = interval
377
      // %16:%15:%14 = nr
378
      // %13 = 0
379
 
380
      // A plain division of 24x24 bits should take 388 cycles to complete. We will
381
      // use Newton-Raphson for the calculation, and will strive to get way less cycles
382
      // for the same result - Using C division, it takes 500cycles to complete .
383
 
384
      A("clr %3")                       // idx = 0
385
      A("mov %14,%6")
386
      A("mov %15,%7")
387
      A("mov %16,%8")                   // nr = interval
388
      A("tst %16")                      // nr & 0xFF0000 == 0 ?
389
      A("brne 2f")                      // No, skip this
390
      A("mov %16,%15")
391
      A("mov %15,%14")                  // nr <<= 8, %14 not needed
392
      A("subi %3,-8")                   // idx += 8
393
      A("tst %16")                      // nr & 0xFF0000 == 0 ?
394
      A("brne 2f")                      // No, skip this
395
      A("mov %16,%15")                  // nr <<= 8, %14 not needed
396
      A("clr %15")                      // We clear %14
397
      A("subi %3,-8")                   // idx += 8
398
 
399
      // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
400
      L("2")
401
      A("cpi %16,0x10")                 // (nr & 0xF00000) == 0 ?
402
      A("brcc 3f")                      // No, skip this
403
      A("swap %15")                     // Swap nibbles
404
      A("swap %16")                     // Swap nibbles. Low nibble is 0
405
      A("mov %14, %15")
406
      A("andi %14,0x0F")                // Isolate low nibble
407
      A("andi %15,0xF0")                // Keep proper nibble in %15
408
      A("or %16, %14")                  // %16:%15 <<= 4
409
      A("subi %3,-4")                   // idx += 4
410
 
411
      L("3")
412
      A("cpi %16,0x40")                 // (nr & 0xC00000) == 0 ?
413
      A("brcc 4f")                      // No, skip this
414
      A("add %15,%15")
415
      A("adc %16,%16")
416
      A("add %15,%15")
417
      A("adc %16,%16")                  // %16:%15 <<= 2
418
      A("subi %3,-2")                   // idx += 2
419
 
420
      L("4")
421
      A("cpi %16,0x80")                 // (nr & 0x800000) == 0 ?
422
      A("brcc 5f")                      // No, skip this
423
      A("add %15,%15")
424
      A("adc %16,%16")                  // %16:%15 <<= 1
425
      A("inc %3")                       // idx += 1
426
 
427
      // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
428
      // we have at least 9 MSBits available to enter the initial estimation table
429
      L("5")
430
      A("add %15,%15")
431
      A("adc %16,%16")                  // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table)
432
      A("add r30,%16")                  // Only use top 8 bits
433
      A("adc r31,%13")                  // r31:r30 = inv_tab + (tidx)
434
      A("lpm %14, Z")                   // %14 = inv_tab[tidx]
435
      A("ldi %15, 1")                   // %15 = 1  %15:%14 = inv_tab[tidx] + 256
436
 
437
      // We must scale the approximation to the proper place
438
      A("clr %16")                      // %16 will always be 0 here
439
      A("subi %3,8")                    // idx == 8 ?
440
      A("breq 6f")                      // yes, no need to scale
441
      A("brcs 7f")                      // If C=1, means idx < 8, result was negative!
442
 
443
      // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
444
      A("sbrs %3,0")                    // shift by 1bit position?
445
      A("rjmp 8f")                      // No
446
      A("add %14,%14")
447
      A("adc %15,%15")                  // %15:16 <<= 1
448
      L("8")
449
      A("sbrs %3,1")                    // shift by 2bit position?
450
      A("rjmp 9f")                      // No
451
      A("add %14,%14")
452
      A("adc %15,%15")
453
      A("add %14,%14")
454
      A("adc %15,%15")                  // %15:16 <<= 1
455
      L("9")
456
      A("sbrs %3,2")                    // shift by 4bits position?
457
      A("rjmp 16f")                     // No
458
      A("swap %15")                     // Swap nibbles. lo nibble of %15 will always be 0
459
      A("swap %14")                     // Swap nibbles
460
      A("mov %12,%14")
461
      A("andi %12,0x0F")                // isolate low nibble
462
      A("andi %14,0xF0")                // and clear it
463
      A("or %15,%12")                   // %15:%16 <<= 4
464
      L("16")
465
      A("sbrs %3,3")                    // shift by 8bits position?
466
      A("rjmp 6f")                      // No, we are done
467
      A("mov %16,%15")
468
      A("mov %15,%14")
469
      A("clr %14")
470
      A("jmp 6f")
471
 
472
      // idx < 8, now %3 = idx - 8. Get the count of bits
473
      L("7")
474
      A("neg %3")                       // %3 = -idx = count of bits to move right. idx range:[1...8]
475
      A("sbrs %3,0")                    // shift by 1 bit position ?
476
      A("rjmp 10f")                     // No, skip it
477
      A("asr %15")                      // (bit7 is always 0 here)
478
      A("ror %14")
479
      L("10")
480
      A("sbrs %3,1")                    // shift by 2 bit position ?
481
      A("rjmp 11f")                     // No, skip it
482
      A("asr %15")                      // (bit7 is always 0 here)
483
      A("ror %14")
484
      A("asr %15")                      // (bit7 is always 0 here)
485
      A("ror %14")
486
      L("11")
487
      A("sbrs %3,2")                    // shift by 4 bit position ?
488
      A("rjmp 12f")                     // No, skip it
489
      A("swap %15")                     // Swap nibbles
490
      A("andi %14, 0xF0")               // Lose the lowest nibble
491
      A("swap %14")                     // Swap nibbles. Upper nibble is 0
492
      A("or %14,%15")                   // Pass nibble from upper byte
493
      A("andi %15, 0x0F")               // And get rid of that nibble
494
      L("12")
495
      A("sbrs %3,3")                    // shift by 8 bit position ?
496
      A("rjmp 6f")                      // No, skip it
497
      A("mov %14,%15")
498
      A("clr %15")
499
      L("6")                            // %16:%15:%14 = initial estimation of 0x1000000 / d
500
 
501
      // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
502
      // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
503
      // to get more than 18bits of precision (the initial table lookup gives 9 bits of
504
      // precision to start from). 18bits of precision is all what is needed here for result
505
 
506
      // %8:%7:%6 = d = interval
507
      // %16:%15:%14 = x = initial estimation of 0x1000000 / d
508
      // %13 = 0
509
      // %3:%2:%1:%0 = working accumulator
510
 
511
      // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
512
      A("clr %0")
513
      A("clr %1")
514
      A("clr %2")
515
      A("ldi %3,2")                     // %3:%2:%1:%0 = 0x2000000
516
      A("mul %6,%14")                   // r1:r0 = LO(d) * LO(x)
517
      A("sub %0,r0")
518
      A("sbc %1,r1")
519
      A("sbc %2,%13")
520
      A("sbc %3,%13")                   // %3:%2:%1:%0 -= LO(d) * LO(x)
521
      A("mul %7,%14")                   // r1:r0 = MI(d) * LO(x)
522
      A("sub %1,r0")
523
      A("sbc %2,r1")
524
      A("sbc %3,%13")                   // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
525
      A("mul %8,%14")                   // r1:r0 = HI(d) * LO(x)
526
      A("sub %2,r0")
527
      A("sbc %3,r1")                    // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
528
      A("mul %6,%15")                   // r1:r0 = LO(d) * MI(x)
529
      A("sub %1,r0")
530
      A("sbc %2,r1")
531
      A("sbc %3,%13")                   // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
532
      A("mul %7,%15")                   // r1:r0 = MI(d) * MI(x)
533
      A("sub %2,r0")
534
      A("sbc %3,r1")                    // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
535
      A("mul %8,%15")                   // r1:r0 = HI(d) * MI(x)
536
      A("sub %3,r0")                    // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
537
      A("mul %6,%16")                   // r1:r0 = LO(d) * HI(x)
538
      A("sub %2,r0")
539
      A("sbc %3,r1")                    // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
540
      A("mul %7,%16")                   // r1:r0 = MI(d) * HI(x)
541
      A("sub %3,r0")                    // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
542
      // %3:%2:%1:%0 = (1<<25) - x*d     [169]
543
 
544
      // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
545
 
546
      // %16:%15:%14 = x = initial estimation of 0x1000000 / d
547
      // %3:%2:%1:%0 = (1<<25) - x*d = acc
548
      // %13 = 0
549
 
550
      // result = %11:%10:%9:%5:%4
551
      A("mul %14,%0")                   // r1:r0 = LO(x) * LO(acc)
552
      A("mov %4,r1")
553
      A("clr %5")
554
      A("clr %9")
555
      A("clr %10")
556
      A("clr %11")                      // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
557
      A("mul %15,%0")                   // r1:r0 = MI(x) * LO(acc)
558
      A("add %4,r0")
559
      A("adc %5,r1")
560
      A("adc %9,%13")
561
      A("adc %10,%13")
562
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
563
      A("mul %16,%0")                   // r1:r0 = HI(x) * LO(acc)
564
      A("add %5,r0")
565
      A("adc %9,r1")
566
      A("adc %10,%13")
567
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
568
 
569
      A("mul %14,%1")                   // r1:r0 = LO(x) * MIL(acc)
570
      A("add %4,r0")
571
      A("adc %5,r1")
572
      A("adc %9,%13")
573
      A("adc %10,%13")
574
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
575
      A("mul %15,%1")                   // r1:r0 = MI(x) * MIL(acc)
576
      A("add %5,r0")
577
      A("adc %9,r1")
578
      A("adc %10,%13")
579
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8
580
      A("mul %16,%1")                   // r1:r0 = HI(x) * MIL(acc)
581
      A("add %9,r0")
582
      A("adc %10,r1")
583
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
584
 
585
      A("mul %14,%2")                   // r1:r0 = LO(x) * MIH(acc)
586
      A("add %5,r0")
587
      A("adc %9,r1")
588
      A("adc %10,%13")
589
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
590
      A("mul %15,%2")                   // r1:r0 = MI(x) * MIH(acc)
591
      A("add %9,r0")
592
      A("adc %10,r1")
593
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
594
      A("mul %16,%2")                   // r1:r0 = HI(x) * MIH(acc)
595
      A("add %10,r0")
596
      A("adc %11,r1")                   // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
597
 
598
      A("mul %14,%3")                   // r1:r0 = LO(x) * HI(acc)
599
      A("add %9,r0")
600
      A("adc %10,r1")
601
      A("adc %11,%13")                  // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
602
      A("mul %15,%3")                   // r1:r0 = MI(x) * HI(acc)
603
      A("add %10,r0")
604
      A("adc %11,r1")                   // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
605
      A("mul %16,%3")                   // r1:r0 = HI(x) * HI(acc)
606
      A("add %11,r0")                   // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
607
 
608
      // At this point, %11:%10:%9 contains the new estimation of x.
609
 
610
      // Finally, we must correct the result. Estimate remainder as
611
      // (1<<24) - x*d
612
      // %11:%10:%9 = x
613
      // %8:%7:%6 = d = interval" "\n\t"
614
      A("ldi %3,1")
615
      A("clr %2")
616
      A("clr %1")
617
      A("clr %0")                       // %3:%2:%1:%0 = 0x1000000
618
      A("mul %6,%9")                    // r1:r0 = LO(d) * LO(x)
619
      A("sub %0,r0")
620
      A("sbc %1,r1")
621
      A("sbc %2,%13")
622
      A("sbc %3,%13")                   // %3:%2:%1:%0 -= LO(d) * LO(x)
623
      A("mul %7,%9")                    // r1:r0 = MI(d) * LO(x)
624
      A("sub %1,r0")
625
      A("sbc %2,r1")
626
      A("sbc %3,%13")                   // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
627
      A("mul %8,%9")                    // r1:r0 = HI(d) * LO(x)
628
      A("sub %2,r0")
629
      A("sbc %3,r1")                    // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
630
      A("mul %6,%10")                   // r1:r0 = LO(d) * MI(x)
631
      A("sub %1,r0")
632
      A("sbc %2,r1")
633
      A("sbc %3,%13")                   // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
634
      A("mul %7,%10")                   // r1:r0 = MI(d) * MI(x)
635
      A("sub %2,r0")
636
      A("sbc %3,r1")                    // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
637
      A("mul %8,%10")                   // r1:r0 = HI(d) * MI(x)
638
      A("sub %3,r0")                    // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
639
      A("mul %6,%11")                   // r1:r0 = LO(d) * HI(x)
640
      A("sub %2,r0")
641
      A("sbc %3,r1")                    // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
642
      A("mul %7,%11")                   // r1:r0 = MI(d) * HI(x)
643
      A("sub %3,r0")                    // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
644
      // %3:%2:%1:%0 = r = (1<<24) - x*d
645
      // %8:%7:%6 = d = interval
646
 
647
      // Perform the final correction
648
      A("sub %0,%6")
649
      A("sbc %1,%7")
650
      A("sbc %2,%8")                    // r -= d
651
      A("brcs 14f")                     // if ( r >= d)
652
 
653
      // %11:%10:%9 = x
654
      A("ldi %3,1")
655
      A("add %9,%3")
656
      A("adc %10,%13")
657
      A("adc %11,%13")                  // x++
658
      L("14")
659
 
660
      // Estimation is done. %11:%10:%9 = x
661
      A("clr __zero_reg__")             // Make C runtime happy
662
      // [211 cycles total]
663
      : "=r" (r2),
664
        "=r" (r3),
665
        "=r" (r4),
666
        "=d" (r5),
667
        "=r" (r6),
668
        "=r" (r7),
669
        "+r" (r8),
670
        "+r" (r9),
671
        "+r" (r10),
672
        "=d" (r11),
673
        "=r" (r12),
674
        "=r" (r13),
675
        "=d" (r14),
676
        "=d" (r15),
677
        "=d" (r16),
678
        "=d" (r17),
679
        "=d" (r18),
680
        "+z" (ptab)
681
      :
682
      : "r0", "r1", "cc"
683
    );
684
 
685
    // Return the result
686
    return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
687
  }
688
 
689
#endif // S_CURVE_ACCELERATION
690
 
691
#define MINIMAL_STEP_RATE 120
692
 
693
/**
694
 * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
695
 * by the provided factors.
696
 **
697
 * ############ VERY IMPORTANT ############
698
 * NOTE that the PRECONDITION to call this function is that the block is
699
 * NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR
700
 * is not and will not use the block while we modify it, so it is safe to
701
 * alter its values.
702
 */
703
void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
704
 
705
  uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
706
           final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
707
 
708
  // Limit minimal step rate (Otherwise the timer will overflow.)
709
  NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE));
710
  NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE));
711
 
712
  #if ENABLED(S_CURVE_ACCELERATION)
713
    uint32_t cruise_rate = initial_rate;
714
  #endif
715
 
716
  const int32_t accel = block->acceleration_steps_per_s2;
717
 
718
          // Steps required for acceleration, deceleration to/from nominal rate
719
  uint32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
720
           decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
721
          // Steps between acceleration and deceleration, if any
722
  int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
723
 
724
  // Does accelerate_steps + decelerate_steps exceed step_event_count?
725
  // Then we can't possibly reach the nominal rate, there will be no cruising.
726
  // Use intersection_distance() to calculate accel / braking time in order to
727
  // reach the final_rate exactly at the end of this block.
728
  if (plateau_steps < 0) {
729
    const float accelerate_steps_float = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
730
    accelerate_steps = MIN(uint32_t(MAX(accelerate_steps_float, 0)), block->step_event_count);
731
    plateau_steps = 0;
732
 
733
    #if ENABLED(S_CURVE_ACCELERATION)
734
      // We won't reach the cruising rate. Let's calculate the speed we will reach
735
      cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
736
    #endif
737
  }
738
  #if ENABLED(S_CURVE_ACCELERATION)
739
    else // We have some plateau time, so the cruise rate will be the nominal rate
740
      cruise_rate = block->nominal_rate;
741
  #endif
742
 
743
  #if ENABLED(S_CURVE_ACCELERATION)
744
    // Jerk controlled speed requires to express speed versus time, NOT steps
745
    uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * (STEPPER_TIMER_RATE),
746
             deceleration_time = ((float)(cruise_rate - final_rate) / accel) * (STEPPER_TIMER_RATE);
747
 
748
    // And to offload calculations from the ISR, we also calculate the inverse of those times here
749
    uint32_t acceleration_time_inverse = get_period_inverse(acceleration_time);
750
    uint32_t deceleration_time_inverse = get_period_inverse(deceleration_time);
751
  #endif
752
 
753
  // Store new block parameters
754
  block->accelerate_until = accelerate_steps;
755
  block->decelerate_after = accelerate_steps + plateau_steps;
756
  block->initial_rate = initial_rate;
757
  #if ENABLED(S_CURVE_ACCELERATION)
758
    block->acceleration_time = acceleration_time;
759
    block->deceleration_time = deceleration_time;
760
    block->acceleration_time_inverse = acceleration_time_inverse;
761
    block->deceleration_time_inverse = deceleration_time_inverse;
762
    block->cruise_rate = cruise_rate;
763
  #endif
764
  block->final_rate = final_rate;
765
}
766
 
767
/*                            PLANNER SPEED DEFINITION
768
                                     +--------+   <- current->nominal_speed
769
                                    /          \
770
         current->entry_speed ->   +            \
771
                                   |             + <- next->entry_speed (aka exit speed)
772
                                   +-------------+
773
                                       time -->
774
 
775
  Recalculates the motion plan according to the following basic guidelines:
776
 
777
    1. Go over every feasible block sequentially in reverse order and calculate the junction speeds
778
        (i.e. current->entry_speed) such that:
779
      a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of
780
         neighboring blocks.
781
      b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed)
782
         with a maximum allowable deceleration over the block travel distance.
783
      c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero).
784
    2. Go over every block in chronological (forward) order and dial down junction speed values if
785
      a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable
786
         acceleration over the block travel distance.
787
 
788
  When these stages are complete, the planner will have maximized the velocity profiles throughout the all
789
  of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In
790
  other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements
791
  are possible. If a new block is added to the buffer, the plan is recomputed according to the said
792
  guidelines for a new optimal plan.
793
 
794
  To increase computational efficiency of these guidelines, a set of planner block pointers have been
795
  created to indicate stop-compute points for when the planner guidelines cannot logically make any further
796
  changes or improvements to the plan when in normal operation and new blocks are streamed and added to the
797
  planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are
798
  bracketed by junction velocities at their maximums (or by the first planner block as well), no new block
799
  added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute
800
  them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute
801
  point) are all accelerating, they are all optimal and can not be altered by a new block added to the
802
  planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum
803
  junction velocity is reached. However, if the operational conditions of the plan changes from infrequently
804
  used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is
805
  recomputed as stated in the general guidelines.
806
 
807
  Planner buffer index mapping:
808
  - block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed.
809
  - block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether
810
      the buffer is full or empty. As described for standard ring buffers, this block is always empty.
811
  - block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal
812
      streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the
813
      planner buffer that don't change with the addition of a new block, as describe above. In addition,
814
      this block can never be less than block_buffer_tail and will always be pushed forward and maintain
815
      this requirement when encountered by the Planner::discard_current_block() routine during a cycle.
816
 
817
  NOTE: Since the planner only computes on what's in the planner buffer, some motions with lots of short
818
  line segments, like G2/3 arcs or complex curves, may seem to move slow. This is because there simply isn't
819
  enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and then
820
  decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this happens and
821
  becomes an annoyance, there are a few simple solutions: (1) Maximize the machine acceleration. The planner
822
  will be able to compute higher velocity profiles within the same combined distance. (2) Maximize line
823
  motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
824
  the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
825
  for the planner to compute over. It also increases the number of computations the planner has to perform
826
  to compute an optimal plan, so select carefully.
827
*/
828
 
829
// The kernel called by recalculate() when scanning the plan from last to first entry.
830
void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
831
  if (current) {
832
    // If entry speed is already at the maximum entry speed, and there was no change of speed
833
    // in the next block, there is no need to recheck. Block is cruising and there is no need to
834
    // compute anything for this block,
835
    // If not, block entry speed needs to be recalculated to ensure maximum possible planned speed.
836
    const float max_entry_speed_sqr = current->max_entry_speed_sqr;
837
 
838
    // Compute maximum entry speed decelerating over the current block from its exit speed.
839
    // If not at the maximum entry speed, or the previous block entry speed changed
840
    if (current->entry_speed_sqr != max_entry_speed_sqr || (next && TEST(next->flag, BLOCK_BIT_RECALCULATE))) {
841
 
842
      // If nominal length true, max junction speed is guaranteed to be reached.
843
      // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
844
      // the current block and next block junction speeds are guaranteed to always be at their maximum
845
      // junction speeds in deceleration and acceleration, respectively. This is due to how the current
846
      // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
847
      // the reverse and forward planners, the corresponding block junction speed will always be at the
848
      // the maximum junction speed and may always be ignored for any speed reduction checks.
849
 
850
      const float new_entry_speed_sqr = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
851
        ? max_entry_speed_sqr
852
        : MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next ? next->entry_speed_sqr : sq(float(MINIMUM_PLANNER_SPEED)), current->millimeters));
853
      if (current->entry_speed_sqr != new_entry_speed_sqr) {
854
 
855
        // Need to recalculate the block speed - Mark it now, so the stepper
856
        // ISR does not consume the block before being recalculated
857
        SBI(current->flag, BLOCK_BIT_RECALCULATE);
858
 
859
        // But there is an inherent race condition here, as the block may have
860
        // become BUSY just before being marked RECALCULATE, so check for that!
861
        if (stepper.is_block_busy(current)) {
862
          // Block became busy. Clear the RECALCULATE flag (no point in
863
          // recalculating BUSY blocks). And don't set its speed, as it can't
864
          // be updated at this time.
865
          CBI(current->flag, BLOCK_BIT_RECALCULATE);
866
        }
867
        else {
868
          // Block is not BUSY so this is ahead of the Stepper ISR:
869
          // Just Set the new entry speed.
870
          current->entry_speed_sqr = new_entry_speed_sqr;
871
        }
872
      }
873
    }
874
  }
875
}
876
 
877
/**
878
 * recalculate() needs to go over the current plan twice.
879
 * Once in reverse and once forward. This implements the reverse pass.
880
 */
881
void Planner::reverse_pass() {
882
  // Initialize block index to the last block in the planner buffer.
883
  uint8_t block_index = prev_block_index(block_buffer_head);
884
 
885
  // Read the index of the last buffer planned block.
886
  // The ISR may change it so get a stable local copy.
887
  uint8_t planned_block_index = block_buffer_planned;
888
 
889
  // If there was a race condition and block_buffer_planned was incremented
890
  //  or was pointing at the head (queue empty) break loop now and avoid
891
  //  planning already consumed blocks
892
  if (planned_block_index == block_buffer_head) return;
893
 
894
  // Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
895
  // block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
896
  // NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
897
  const block_t *next = NULL;
898
  while (block_index != planned_block_index) {
899
 
900
    // Perform the reverse pass
901
    block_t *current = &block_buffer[block_index];
902
 
903
    // Only consider non sync blocks
904
    if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
905
      reverse_pass_kernel(current, next);
906
      next = current;
907
    }
908
 
909
    // Advance to the next
910
    block_index = prev_block_index(block_index);
911
 
912
    // The ISR could advance the block_buffer_planned while we were doing the reverse pass.
913
    // We must try to avoid using an already consumed block as the last one - So follow
914
    // changes to the pointer and make sure to limit the loop to the currently busy block
915
    while (planned_block_index != block_buffer_planned) {
916
 
917
      // If we reached the busy block or an already processed block, break the loop now
918
      if (block_index == planned_block_index) return;
919
 
920
      // Advance the pointer, following the busy block
921
      planned_block_index = next_block_index(planned_block_index);
922
    }
923
  }
924
}
925
 
926
// The kernel called by recalculate() when scanning the plan from first to last entry.
927
void Planner::forward_pass_kernel(const block_t* const previous, block_t* const current, const uint8_t block_index) {
928
  if (previous) {
929
    // If the previous block is an acceleration block, too short to complete the full speed
930
    // change, adjust the entry speed accordingly. Entry speeds have already been reset,
931
    // maximized, and reverse-planned. If nominal length is set, max junction speed is
932
    // guaranteed to be reached. No need to recheck.
933
    if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH) &&
934
      previous->entry_speed_sqr < current->entry_speed_sqr) {
935
 
936
      // Compute the maximum allowable speed
937
      const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters);
938
 
939
      // If true, current block is full-acceleration and we can move the planned pointer forward.
940
      if (new_entry_speed_sqr < current->entry_speed_sqr) {
941
 
942
        // Mark we need to recompute the trapezoidal shape, and do it now,
943
        // so the stepper ISR does not consume the block before being recalculated
944
        SBI(current->flag, BLOCK_BIT_RECALCULATE);
945
 
946
        // But there is an inherent race condition here, as the block maybe
947
        // became BUSY, just before it was marked as RECALCULATE, so check
948
        // if that is the case!
949
        if (stepper.is_block_busy(current)) {
950
          // Block became busy. Clear the RECALCULATE flag (no point in
951
          //  recalculating BUSY blocks and don't set its speed, as it can't
952
          //  be updated at this time.
953
          CBI(current->flag, BLOCK_BIT_RECALCULATE);
954
        }
955
        else {
956
          // Block is not BUSY, we won the race against the Stepper ISR:
957
 
958
          // Always <= max_entry_speed_sqr. Backward pass sets this.
959
          current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this.
960
 
961
          // Set optimal plan pointer.
962
          block_buffer_planned = block_index;
963
        }
964
      }
965
    }
966
 
967
    // Any block set at its maximum entry speed also creates an optimal plan up to this
968
    // point in the buffer. When the plan is bracketed by either the beginning of the
969
    // buffer and a maximum entry speed or two maximum entry speeds, every block in between
970
    // cannot logically be further improved. Hence, we don't have to recompute them anymore.
971
    if (current->entry_speed_sqr == current->max_entry_speed_sqr)
972
      block_buffer_planned = block_index;
973
  }
974
}
975
 
976
/**
977
 * recalculate() needs to go over the current plan twice.
978
 * Once in reverse and once forward. This implements the forward pass.
979
 */
980
void Planner::forward_pass() {
981
 
982
  // Forward Pass: Forward plan the acceleration curve from the planned pointer onward.
983
  // Also scans for optimal plan breakpoints and appropriately updates the planned pointer.
984
 
985
  // Begin at buffer planned pointer. Note that block_buffer_planned can be modified
986
  //  by the stepper ISR,  so read it ONCE. It it guaranteed that block_buffer_planned
987
  //  will never lead head, so the loop is safe to execute. Also note that the forward
988
  //  pass will never modify the values at the tail.
989
  uint8_t block_index = block_buffer_planned;
990
 
991
  block_t *current;
992
  const block_t * previous = NULL;
993
  while (block_index != block_buffer_head) {
994
 
995
    // Perform the forward pass
996
    current = &block_buffer[block_index];
997
 
998
    // Skip SYNC blocks
999
    if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
1000
      // If there's no previous block or the previous block is not
1001
      // BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise,
1002
      // the previous block became BUSY, so assume the current block's
1003
      // entry speed can't be altered (since that would also require
1004
      // updating the exit speed of the previous block).
1005
      if (!previous || !stepper.is_block_busy(previous))
1006
        forward_pass_kernel(previous, current, block_index);
1007
      previous = current;
1008
    }
1009
    // Advance to the previous
1010
    block_index = next_block_index(block_index);
1011
  }
1012
}
1013
 
1014
/**
1015
 * Recalculate the trapezoid speed profiles for all blocks in the plan
1016
 * according to the entry_factor for each junction. Must be called by
1017
 * recalculate() after updating the blocks.
1018
 */
1019
void Planner::recalculate_trapezoids() {
1020
  // The tail may be changed by the ISR so get a local copy.
1021
  uint8_t block_index = block_buffer_tail,
1022
          head_block_index = block_buffer_head;
1023
  // Since there could be a sync block in the head of the queue, and the
1024
  // next loop must not recalculate the head block (as it needs to be
1025
  // specially handled), scan backwards to the first non-SYNC block.
1026
  while (head_block_index != block_index) {
1027
 
1028
    // Go back (head always point to the first free block)
1029
    const uint8_t prev_index = prev_block_index(head_block_index);
1030
 
1031
    // Get the pointer to the block
1032
    block_t *prev = &block_buffer[prev_index];
1033
 
1034
    // If not dealing with a sync block, we are done. The last block is not a SYNC block
1035
    if (!TEST(prev->flag, BLOCK_BIT_SYNC_POSITION)) break;
1036
 
1037
    // Examine the previous block. This and all following are SYNC blocks
1038
    head_block_index = prev_index;
1039
  }
1040
 
1041
  // Go from the tail (currently executed block) to the first block, without including it)
1042
  block_t *current = NULL, *next = NULL;
1043
  float current_entry_speed = 0.0, next_entry_speed = 0.0;
1044
  while (block_index != head_block_index) {
1045
 
1046
    next = &block_buffer[block_index];
1047
 
1048
    // Skip sync blocks
1049
    if (!TEST(next->flag, BLOCK_BIT_SYNC_POSITION)) {
1050
      next_entry_speed = SQRT(next->entry_speed_sqr);
1051
 
1052
      if (current) {
1053
        // Recalculate if current block entry or exit junction speed has changed.
1054
        if (TEST(current->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
1055
 
1056
          // Mark the current block as RECALCULATE, to protect it from the Stepper ISR running it.
1057
          // Note that due to the above condition, there's a chance the current block isn't marked as
1058
          // RECALCULATE yet, but the next one is. That's the reason for the following line.
1059
          SBI(current->flag, BLOCK_BIT_RECALCULATE);
1060
 
1061
          // But there is an inherent race condition here, as the block maybe
1062
          // became BUSY, just before it was marked as RECALCULATE, so check
1063
          // if that is the case!
1064
          if (!stepper.is_block_busy(current)) {
1065
            // Block is not BUSY, we won the race against the Stepper ISR:
1066
 
1067
            // NOTE: Entry and exit factors always > 0 by all previous logic operations.
1068
            const float current_nominal_speed = SQRT(current->nominal_speed_sqr),
1069
                        nomr = 1.0f / current_nominal_speed;
1070
            calculate_trapezoid_for_block(current, current_entry_speed * nomr, next_entry_speed * nomr);
1071
            #if ENABLED(LIN_ADVANCE)
1072
              if (current->use_advance_lead) {
1073
                const float comp = current->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
1074
                current->max_adv_steps = current_nominal_speed * comp;
1075
                current->final_adv_steps = next_entry_speed * comp;
1076
              }
1077
            #endif
1078
          }
1079
 
1080
          // Reset current only to ensure next trapezoid is computed - The
1081
          // stepper is free to use the block from now on.
1082
          CBI(current->flag, BLOCK_BIT_RECALCULATE);
1083
        }
1084
      }
1085
 
1086
      current = next;
1087
      current_entry_speed = next_entry_speed;
1088
    }
1089
 
1090
    block_index = next_block_index(block_index);
1091
  }
1092
 
1093
  // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
1094
  if (next) {
1095
 
1096
    // Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it.
1097
    // As the last block is always recalculated here, there is a chance the block isn't
1098
    // marked as RECALCULATE yet. That's the reason for the following line.
1099
    SBI(next->flag, BLOCK_BIT_RECALCULATE);
1100
 
1101
    // But there is an inherent race condition here, as the block maybe
1102
    // became BUSY, just before it was marked as RECALCULATE, so check
1103
    // if that is the case!
1104
    if (!stepper.is_block_busy(current)) {
1105
      // Block is not BUSY, we won the race against the Stepper ISR:
1106
 
1107
      const float next_nominal_speed = SQRT(next->nominal_speed_sqr),
1108
                  nomr = 1.0f / next_nominal_speed;
1109
      calculate_trapezoid_for_block(next, next_entry_speed * nomr, float(MINIMUM_PLANNER_SPEED) * nomr);
1110
      #if ENABLED(LIN_ADVANCE)
1111
        if (next->use_advance_lead) {
1112
          const float comp = next->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
1113
          next->max_adv_steps = next_nominal_speed * comp;
1114
          next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
1115
        }
1116
      #endif
1117
    }
1118
 
1119
    // Reset next only to ensure its trapezoid is computed - The stepper is free to use
1120
    // the block from now on.
1121
    CBI(next->flag, BLOCK_BIT_RECALCULATE);
1122
  }
1123
}
1124
 
1125
void Planner::recalculate() {
1126
  // Initialize block index to the last block in the planner buffer.
1127
  const uint8_t block_index = prev_block_index(block_buffer_head);
1128
  // If there is just one block, no planning can be done. Avoid it!
1129
  if (block_index != block_buffer_planned) {
1130
    reverse_pass();
1131
    forward_pass();
1132
  }
1133
  recalculate_trapezoids();
1134
}
1135
 
1136
#if ENABLED(AUTOTEMP)
1137
 
1138
  void Planner::getHighESpeed() {
1139
    static float oldt = 0;
1140
 
1141
    if (!autotemp_enabled) return;
1142
    if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
1143
 
1144
    float high = 0.0;
1145
    for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
1146
      block_t* block = &block_buffer[b];
1147
      if (
1148
        #if ENABLED(HANGPRINTER)
1149
          block->steps[A_AXIS] || block->steps[B_AXIS] || block->steps[C_AXIS] || block->steps[D_AXIS]
1150
        #else
1151
          block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]
1152
        #endif
1153
      ) {
1154
        const float se = (float)block->steps[E_AXIS] / block->step_event_count * SQRT(block->nominal_speed_sqr); // mm/sec;
1155
        NOLESS(high, se);
1156
      }
1157
    }
1158
 
1159
    float t = autotemp_min + high * autotemp_factor;
1160
    t = constrain(t, autotemp_min, autotemp_max);
1161
    if (t < oldt) t = t * (1 - float(AUTOTEMP_OLDWEIGHT)) + oldt * float(AUTOTEMP_OLDWEIGHT);
1162
    oldt = t;
1163
    thermalManager.setTargetHotend(t, 0);
1164
  }
1165
 
1166
#endif // AUTOTEMP
1167
 
1168
/**
1169
 * Maintain fans, paste extruder pressure,
1170
 */
1171
void Planner::check_axes_activity() {
1172
  uint8_t axis_active[NUM_AXIS] = { 0 };
1173
 
1174
  #if FAN_COUNT > 0
1175
    uint8_t tail_fan_speed[FAN_COUNT] = { 0 };
1176
  #endif
1177
 
1178
  #if ENABLED(BARICUDA)
1179
    #if HAS_HEATER_1
1180
      uint8_t tail_valve_pressure;
1181
    #endif
1182
    #if HAS_HEATER_2
1183
      uint8_t tail_e_to_p_pressure;
1184
    #endif
1185
  #endif
1186
 
1187
  if (has_blocks_queued()) {
1188
 
1189
    #if FAN_COUNT > 0
1190
      for (uint8_t i = 0; i < FAN_COUNT; i++)
1191
        tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
1192
    #endif
1193
 
1194
    block_t* block;
1195
 
1196
    #if ENABLED(BARICUDA)
1197
      block = &block_buffer[block_buffer_tail];
1198
      #if HAS_HEATER_1
1199
        tail_valve_pressure = block->valve_pressure;
1200
      #endif
1201
      #if HAS_HEATER_2
1202
        tail_e_to_p_pressure = block->e_to_p_pressure;
1203
      #endif
1204
    #endif
1205
 
1206
    for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
1207
      block = &block_buffer[b];
1208
      LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
1209
    }
1210
  }
1211
  else {
1212
    #if FAN_COUNT > 0
1213
      for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
1214
    #endif
1215
 
1216
    #if ENABLED(BARICUDA)
1217
      #if HAS_HEATER_1
1218
        tail_valve_pressure = baricuda_valve_pressure;
1219
      #endif
1220
      #if HAS_HEATER_2
1221
        tail_e_to_p_pressure = baricuda_e_to_p_pressure;
1222
      #endif
1223
    #endif
1224
  }
1225
 
1226
  #if ENABLED(DISABLE_X)
1227
    if (!axis_active[X_AXIS]) disable_X();
1228
  #endif
1229
  #if ENABLED(DISABLE_Y)
1230
    if (!axis_active[Y_AXIS]) disable_Y();
1231
  #endif
1232
  #if ENABLED(DISABLE_Z)
1233
    if (!axis_active[Z_AXIS]) disable_Z();
1234
  #endif
1235
  #if ENABLED(DISABLE_E)
1236
    if (!axis_active[E_AXIS]) disable_e_steppers();
1237
  #endif
1238
 
1239
  #if FAN_COUNT > 0
1240
 
1241
    #if FAN_KICKSTART_TIME > 0
1242
 
1243
      static millis_t fan_kick_end[FAN_COUNT] = { 0 };
1244
 
1245
      #define KICKSTART_FAN(f) \
1246
        if (tail_fan_speed[f]) { \
1247
          millis_t ms = millis(); \
1248
          if (fan_kick_end[f] == 0) { \
1249
            fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
1250
            tail_fan_speed[f] = 255; \
1251
          } else if (PENDING(ms, fan_kick_end[f])) \
1252
            tail_fan_speed[f] = 255; \
1253
        } else fan_kick_end[f] = 0
1254
 
1255
      #if HAS_FAN0
1256
        KICKSTART_FAN(0);
1257
      #endif
1258
      #if HAS_FAN1
1259
        KICKSTART_FAN(1);
1260
      #endif
1261
      #if HAS_FAN2
1262
        KICKSTART_FAN(2);
1263
      #endif
1264
 
1265
    #endif // FAN_KICKSTART_TIME > 0
1266
 
1267
    #if FAN_MIN_PWM != 0 || FAN_MAX_PWM != 255
1268
      #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? map(tail_fan_speed[f], 1, 255, FAN_MIN_PWM, FAN_MAX_PWM) : 0)
1269
    #else
1270
      #define CALC_FAN_SPEED(f) tail_fan_speed[f]
1271
    #endif
1272
 
1273
    #if ENABLED(FAN_SOFT_PWM)
1274
      #if HAS_FAN0
1275
        thermalManager.soft_pwm_amount_fan[0] = CALC_FAN_SPEED(0);
1276
      #endif
1277
      #if HAS_FAN1
1278
        thermalManager.soft_pwm_amount_fan[1] = CALC_FAN_SPEED(1);
1279
      #endif
1280
      #if HAS_FAN2
1281
        thermalManager.soft_pwm_amount_fan[2] = CALC_FAN_SPEED(2);
1282
      #endif
1283
    #else
1284
      #if HAS_FAN0
1285
        analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
1286
      #endif
1287
      #if HAS_FAN1
1288
        analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
1289
      #endif
1290
      #if HAS_FAN2
1291
        analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
1292
      #endif
1293
    #endif
1294
 
1295
  #endif // FAN_COUNT > 0
1296
 
1297
  #if ENABLED(AUTOTEMP)
1298
    getHighESpeed();
1299
  #endif
1300
 
1301
  #if ENABLED(BARICUDA)
1302
    #if HAS_HEATER_1
1303
      analogWrite(HEATER_1_PIN, tail_valve_pressure);
1304
    #endif
1305
    #if HAS_HEATER_2
1306
      analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
1307
    #endif
1308
  #endif
1309
}
1310
 
1311
#if DISABLED(NO_VOLUMETRICS)
1312
 
1313
  /**
1314
   * Get a volumetric multiplier from a filament diameter.
1315
   * This is the reciprocal of the circular cross-section area.
1316
   * Return 1.0 with volumetric off or a diameter of 0.0.
1317
   */
1318
  inline float calculate_volumetric_multiplier(const float &diameter) {
1319
    return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5) : 1.0;
1320
  }
1321
 
1322
  /**
1323
   * Convert the filament sizes into volumetric multipliers.
1324
   * The multiplier converts a given E value into a length.
1325
   */
1326
  void Planner::calculate_volumetric_multipliers() {
1327
    for (uint8_t i = 0; i < COUNT(filament_size); i++) {
1328
      volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
1329
      refresh_e_factor(i);
1330
    }
1331
  }
1332
 
1333
#endif // !NO_VOLUMETRICS
1334
 
1335
#if ENABLED(FILAMENT_WIDTH_SENSOR)
1336
  /**
1337
   * Convert the ratio value given by the filament width sensor
1338
   * into a volumetric multiplier. Conversion differs when using
1339
   * linear extrusion vs volumetric extrusion.
1340
   */
1341
  void Planner::calculate_volumetric_for_width_sensor(const int8_t encoded_ratio) {
1342
    // Reconstitute the nominal/measured ratio
1343
    const float nom_meas_ratio = 1 + 0.01f * encoded_ratio,
1344
                ratio_2 = sq(nom_meas_ratio);
1345
 
1346
    volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
1347
      ? ratio_2 / CIRCLE_AREA(filament_width_nominal * 0.5f) // Volumetric uses a true volumetric multiplier
1348
      : ratio_2;                                             // Linear squares the ratio, which scales the volume
1349
 
1350
    refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
1351
  }
1352
#endif
1353
 
1354
#if PLANNER_LEVELING || HAS_UBL_AND_CURVES
1355
  /**
1356
   * rx, ry, rz - Cartesian positions in mm
1357
   *              Leveled XYZ on completion
1358
   */
1359
  void Planner::apply_leveling(float &rx, float &ry, float &rz) {
1360
 
1361
    #if ENABLED(SKEW_CORRECTION)
1362
      skew(rx, ry, rz);
1363
    #endif
1364
 
1365
    if (!leveling_active) return;
1366
 
1367
    #if ABL_PLANAR
1368
 
1369
      float dx = rx - (X_TILT_FULCRUM),
1370
            dy = ry - (Y_TILT_FULCRUM);
1371
 
1372
      apply_rotation_xyz(bed_level_matrix, dx, dy, rz);
1373
 
1374
      rx = dx + X_TILT_FULCRUM;
1375
      ry = dy + Y_TILT_FULCRUM;
1376
 
1377
    #elif HAS_MESH
1378
 
1379
      #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
1380
        const float fade_scaling_factor = fade_scaling_factor_for_z(rz);
1381
      #else
1382
        constexpr float fade_scaling_factor = 1.0;
1383
      #endif
1384
 
1385
      #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
1386
        const float raw[XYZ] = { rx, ry, 0 };
1387
      #endif
1388
 
1389
      rz += (
1390
        #if ENABLED(MESH_BED_LEVELING)
1391
          mbl.get_z(rx, ry
1392
            #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
1393
              , fade_scaling_factor
1394
            #endif
1395
          )
1396
        #elif ENABLED(AUTO_BED_LEVELING_UBL)
1397
          fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(rx, ry) : 0.0
1398
        #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
1399
          fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
1400
        #endif
1401
      );
1402
 
1403
    #endif
1404
  }
1405
 
1406
#endif
1407
 
1408
#if PLANNER_LEVELING
1409
 
1410
  void Planner::unapply_leveling(float raw[XYZ]) {
1411
 
1412
    if (leveling_active) {
1413
 
1414
      #if ABL_PLANAR
1415
 
1416
        matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
1417
 
1418
        float dx = raw[X_AXIS] - (X_TILT_FULCRUM),
1419
              dy = raw[Y_AXIS] - (Y_TILT_FULCRUM);
1420
 
1421
        apply_rotation_xyz(inverse, dx, dy, raw[Z_AXIS]);
1422
 
1423
        raw[X_AXIS] = dx + X_TILT_FULCRUM;
1424
        raw[Y_AXIS] = dy + Y_TILT_FULCRUM;
1425
 
1426
      #elif HAS_MESH
1427
 
1428
        #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
1429
          const float fade_scaling_factor = fade_scaling_factor_for_z(raw[Z_AXIS]);
1430
        #else
1431
          constexpr float fade_scaling_factor = 1.0;
1432
        #endif
1433
 
1434
        raw[Z_AXIS] -= (
1435
          #if ENABLED(MESH_BED_LEVELING)
1436
            mbl.get_z(raw[X_AXIS], raw[Y_AXIS]
1437
              #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
1438
                , fade_scaling_factor
1439
              #endif
1440
            )
1441
          #elif ENABLED(AUTO_BED_LEVELING_UBL)
1442
            fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw[X_AXIS], raw[Y_AXIS]) : 0.0
1443
          #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
1444
            fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
1445
          #endif
1446
        );
1447
 
1448
      #endif
1449
    }
1450
 
1451
    #if ENABLED(SKEW_CORRECTION)
1452
      unskew(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]);
1453
    #endif
1454
  }
1455
 
1456
#endif // PLANNER_LEVELING
1457
 
1458
void Planner::quick_stop() {
1459
 
1460
  // Remove all the queued blocks. Note that this function is NOT
1461
  // called from the Stepper ISR, so we must consider tail as readonly!
1462
  // that is why we set head to tail - But there is a race condition that
1463
  // must be handled: The tail could change between the read and the assignment
1464
  // so this must be enclosed in a critical section
1465
 
1466
  const bool was_enabled = STEPPER_ISR_ENABLED();
1467
  if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
1468
 
1469
  // Drop all queue entries
1470
  block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail;
1471
 
1472
  // Restart the block delay for the first movement - As the queue was
1473
  // forced to empty, there's no risk the ISR will touch this.
1474
  delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
1475
 
1476
  #if ENABLED(ULTRA_LCD)
1477
    // Clear the accumulated runtime
1478
    clear_block_buffer_runtime();
1479
  #endif
1480
 
1481
  // Make sure to drop any attempt of queuing moves for at least 1 second
1482
  cleaning_buffer_counter = 1000;
1483
 
1484
  // Reenable Stepper ISR
1485
  if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
1486
 
1487
  // And stop the stepper ISR
1488
  stepper.quick_stop();
1489
}
1490
 
1491
void Planner::endstop_triggered(const AxisEnum axis) {
1492
  // Record stepper position and discard the current block
1493
  stepper.endstop_triggered(axis);
1494
}
1495
 
1496
float Planner::triggered_position_mm(const AxisEnum axis) {
1497
  return stepper.triggered_position(axis) * steps_to_mm[axis];
1498
}
1499
 
1500
void Planner::finish_and_disable() {
1501
  while (has_blocks_queued() || cleaning_buffer_counter) idle();
1502
  disable_all_steppers();
1503
}
1504
 
1505
/**
1506
 * Get an axis position according to stepper position(s)
1507
 * For CORE machines apply translation from ABC to XYZ.
1508
 */
1509
float Planner::get_axis_position_mm(const AxisEnum axis) {
1510
  float axis_steps;
1511
  #if IS_CORE
1512
    // Requesting one of the "core" axes?
1513
    if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
1514
 
1515
      // Protect the access to the position.
1516
      const bool was_enabled = STEPPER_ISR_ENABLED();
1517
      if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
1518
 
1519
      // ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
1520
      // ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
1521
      axis_steps = 0.5f * (
1522
        axis == CORE_AXIS_2 ? CORESIGN(stepper.position(CORE_AXIS_1) - stepper.position(CORE_AXIS_2))
1523
                            : stepper.position(CORE_AXIS_1) + stepper.position(CORE_AXIS_2)
1524
      );
1525
 
1526
      if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
1527
    }
1528
    else
1529
      axis_steps = stepper.position(axis);
1530
  #else
1531
    axis_steps = stepper.position(axis);
1532
  #endif
1533
  #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
1534
    if (axis != E_AXIS) return (sq(axis_steps / k0[axis] + sqrtk1[axis]) - k1[axis]) / k2[axis];
1535
  #endif
1536
  return axis_steps * steps_to_mm[axis];
1537
}
1538
 
1539
/**
1540
 * Block until all buffered steps are executed / cleaned
1541
 */
1542
void Planner::synchronize() { while (has_blocks_queued() || cleaning_buffer_counter) idle(); }
1543
 
1544
#if ENABLED(UNREGISTERED_MOVE_SUPPORT)
1545
  #define COUNT_MOVE count_it
1546
#else
1547
  #define COUNT_MOVE true
1548
#endif
1549
 
1550
/**
1551
 * Planner::_buffer_steps
1552
 *
1553
 * Add a new linear movement to the planner queue (in terms of steps).
1554
 *
1555
 *  target       - target position in steps units
1556
 *  target_float - target position in mm (HAS_POSITION_FLOAT)
1557
 *  fr_mm_s      - (target) speed of the move
1558
 *  extruder     - target extruder
1559
 *  millimeters  - the length of the movement, if known
1560
 *  count_it     - apply this move to the counters (UNREGISTERED_MOVE_SUPPORT)
1561
 *
1562
 * Returns true if movement was properly queued, false otherwise
1563
 */
1564
bool Planner::_buffer_steps(const int32_t (&target)[NUM_AXIS]
1565
  #if HAS_POSITION_FLOAT
1566
    , const float (&target_float)[NUM_AXIS]
1567
  #endif
1568
  , float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
1569
  #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
1570
    , const bool count_it/*=true*/
1571
  #endif
1572
) {
1573
 
1574
  // If we are cleaning, do not accept queuing of movements
1575
  if (cleaning_buffer_counter) return false;
1576
 
1577
  // Wait for the next available block
1578
  uint8_t next_buffer_head;
1579
  block_t * const block = get_next_free_block(next_buffer_head);
1580
 
1581
  // Fill the block with the specified movement
1582
  if (!_populate_block(block, false, target
1583
    #if HAS_POSITION_FLOAT
1584
      , target_float
1585
    #endif
1586
    , fr_mm_s, extruder, millimeters
1587
    #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
1588
      , count_it
1589
    #endif
1590
  )) {
1591
    // Movement was not queued, probably because it was too short.
1592
    //  Simply accept that as movement queued and done
1593
    return true;
1594
  }
1595
 
1596
  // If this is the first added movement, reload the delay, otherwise, cancel it.
1597
  if (block_buffer_head == block_buffer_tail) {
1598
    // If it was the first queued block, restart the 1st block delivery delay, to
1599
    // give the planner an opportunity to queue more movements and plan them
1600
    // As there are no queued movements, the Stepper ISR will not touch this
1601
    // variable, so there is no risk setting this here (but it MUST be done
1602
    // before the following line!!)
1603
    delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
1604
  }
1605
 
1606
  // Move buffer head
1607
  block_buffer_head = next_buffer_head;
1608
 
1609
  // Recalculate and optimize trapezoidal speed profiles
1610
  recalculate();
1611
 
1612
  // Movement successfully queued!
1613
  return true;
1614
}
1615
 
1616
/**
1617
 * Planner::_populate_block
1618
 *
1619
 * Fills a new linear movement in the block (in terms of steps).
1620
 *
1621
 *  target       - target position in steps units
1622
 *  target_float - target position in mm (HAS_POSITION_FLOAT)
1623
 *  fr_mm_s      - (target) speed of the move
1624
 *  extruder     - target extruder
1625
 *  millimeters  - the length of the movement, if known
1626
 *  count_it     - apply this move to the counters (UNREGISTERED_MOVE_SUPPORT)
1627
 *
1628
 * Returns true is movement is acceptable, false otherwise
1629
 */
1630
bool Planner::_populate_block(block_t * const block, bool split_move,
1631
  const int32_t (&target)[NUM_AXIS]
1632
  #if HAS_POSITION_FLOAT
1633
    , const float (&target_float)[NUM_AXIS]
1634
  #endif
1635
  , float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
1636
  #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
1637
    , const bool count_it/*=true*/
1638
  #endif
1639
) {
1640
 
1641
  const int32_t da = target[A_AXIS] - position[A_AXIS],
1642
                db = target[B_AXIS] - position[B_AXIS],
1643
                dc = target[C_AXIS] - position[C_AXIS]
1644
                #if ENABLED(HANGPRINTER)
1645
                  , dd = target[D_AXIS] - position[D_AXIS]
1646
                #endif
1647
              ;
1648
  int32_t de = target[E_AXIS] - position[E_AXIS];
1649
 
1650
  /* <-- add a slash to enable
1651
    SERIAL_ECHOPAIR("  _populate_block FR:", fr_mm_s);
1652
    SERIAL_ECHOPAIR(" A:", target[A_AXIS]);
1653
    SERIAL_ECHOPAIR(" (", da);
1654
    SERIAL_ECHOPAIR(" steps) B:", target[B_AXIS]);
1655
    SERIAL_ECHOPAIR(" (", db);
1656
    SERIAL_ECHOPAIR(" steps) C:", target[C_AXIS]);
1657
    SERIAL_ECHOPAIR(" (", dc);
1658
    SERIAL_ECHOPAIR(" steps) E:", target[E_AXIS]);
1659
    SERIAL_ECHOPAIR(" (", de);
1660
    SERIAL_ECHOLNPGM(" steps)");
1661
  //*/
1662
 
1663
  #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
1664
    if (de) {
1665
      #if ENABLED(PREVENT_COLD_EXTRUSION)
1666
        if (thermalManager.tooColdToExtrude(extruder)) {
1667
          if (COUNT_MOVE) {
1668
            position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
1669
            #if HAS_POSITION_FLOAT
1670
              position_float[E_AXIS] = target_float[E_AXIS];
1671
            #endif
1672
          }
1673
          de = 0; // no difference
1674
          SERIAL_ECHO_START();
1675
          SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
1676
        }
1677
      #endif // PREVENT_COLD_EXTRUSION
1678
      #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
1679
        if (ABS(de * e_factor[extruder]) > (int32_t)axis_steps_per_mm[E_AXIS_N] * (EXTRUDE_MAXLENGTH)) { // It's not important to get max. extrusion length in a precision < 1mm, so save some cycles and cast to int
1680
          if (COUNT_MOVE) {
1681
            position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
1682
            #if HAS_POSITION_FLOAT
1683
              position_float[E_AXIS] = target_float[E_AXIS];
1684
            #endif
1685
          }
1686
          de = 0; // no difference
1687
          SERIAL_ECHO_START();
1688
          SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
1689
        }
1690
      #endif // PREVENT_LENGTHY_EXTRUDE
1691
    }
1692
  #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
1693
 
1694
  // Compute direction bit-mask for this block
1695
  uint8_t dm = 0;
1696
  #if CORE_IS_XY
1697
    if (da < 0) SBI(dm, X_HEAD);                // Save the real Extruder (head) direction in X Axis
1698
    if (db < 0) SBI(dm, Y_HEAD);                // ...and Y
1699
    if (dc < 0) SBI(dm, Z_AXIS);
1700
    if (da + db < 0) SBI(dm, A_AXIS);           // Motor A direction
1701
    if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
1702
  #elif CORE_IS_XZ
1703
    if (da < 0) SBI(dm, X_HEAD);                // Save the real Extruder (head) direction in X Axis
1704
    if (db < 0) SBI(dm, Y_AXIS);
1705
    if (dc < 0) SBI(dm, Z_HEAD);                // ...and Z
1706
    if (da + dc < 0) SBI(dm, A_AXIS);           // Motor A direction
1707
    if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
1708
  #elif CORE_IS_YZ
1709
    if (da < 0) SBI(dm, X_AXIS);
1710
    if (db < 0) SBI(dm, Y_HEAD);                // Save the real Extruder (head) direction in Y Axis
1711
    if (dc < 0) SBI(dm, Z_HEAD);                // ...and Z
1712
    if (db + dc < 0) SBI(dm, B_AXIS);           // Motor B direction
1713
    if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
1714
  #elif ENABLED(HANGPRINTER)
1715
    if (da < 0) SBI(dm, A_AXIS);
1716
    if (db < 0) SBI(dm, B_AXIS);
1717
    if (dc < 0) SBI(dm, C_AXIS);
1718
    if (dd < 0) SBI(dm, D_AXIS);
1719
  #else
1720
    if (da < 0) SBI(dm, X_AXIS);
1721
    if (db < 0) SBI(dm, Y_AXIS);
1722
    if (dc < 0) SBI(dm, Z_AXIS);
1723
  #endif
1724
  if (de < 0) SBI(dm, E_AXIS);
1725
 
1726
  const float esteps_float = de * e_factor[extruder];
1727
  const uint32_t esteps = ABS(esteps_float) + 0.5f;
1728
 
1729
  // Clear all flags, including the "busy" bit
1730
  block->flag = 0x00;
1731
 
1732
  // Set direction bits
1733
  block->direction_bits = dm;
1734
 
1735
  // Specify if block is to be counted or not
1736
  #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
1737
    block->count_it = count_it;
1738
  #endif
1739
 
1740
  // Number of steps for each axis
1741
  // See http://www.corexy.com/theory.html
1742
  #if CORE_IS_XY
1743
    block->steps[A_AXIS] = ABS(da + db);
1744
    block->steps[B_AXIS] = ABS(da - db);
1745
    block->steps[Z_AXIS] = ABS(dc);
1746
  #elif CORE_IS_XZ
1747
    block->steps[A_AXIS] = ABS(da + dc);
1748
    block->steps[Y_AXIS] = ABS(db);
1749
    block->steps[C_AXIS] = ABS(da - dc);
1750
  #elif CORE_IS_YZ
1751
    block->steps[X_AXIS] = ABS(da);
1752
    block->steps[B_AXIS] = ABS(db + dc);
1753
    block->steps[C_AXIS] = ABS(db - dc);
1754
  #elif IS_SCARA
1755
    block->steps[A_AXIS] = ABS(da);
1756
    block->steps[B_AXIS] = ABS(db);
1757
    block->steps[Z_AXIS] = ABS(dc);
1758
  #elif ENABLED(HANGPRINTER)
1759
    block->steps[A_AXIS] = ABS(da);
1760
    block->steps[B_AXIS] = ABS(db);
1761
    block->steps[C_AXIS] = ABS(dc);
1762
    block->steps[D_AXIS] = ABS(dd);
1763
  #else
1764
    // default non-h-bot planning
1765
    block->steps[A_AXIS] = ABS(da);
1766
    block->steps[B_AXIS] = ABS(db);
1767
    block->steps[C_AXIS] = ABS(dc);
1768
  #endif
1769
 
1770
  block->steps[E_AXIS] = esteps;
1771
 
1772
  block->step_event_count = (
1773
    #if ENABLED(HANGPRINTER)
1774
      MAX5(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], block->steps[D_AXIS], esteps)
1775
    #else
1776
      MAX4(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], esteps)
1777
    #endif
1778
  );
1779
 
1780
  // Bail if this is a zero-length block
1781
  if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false;
1782
 
1783
  // For a mixing extruder, get a magnified esteps for each
1784
  #if ENABLED(MIXING_EXTRUDER)
1785
    for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
1786
      block->mix_steps[i] = mixing_factor[i] * esteps;
1787
  #endif
1788
 
1789
  #if FAN_COUNT > 0
1790
    for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
1791
  #endif
1792
 
1793
  #if ENABLED(BARICUDA)
1794
    block->valve_pressure = baricuda_valve_pressure;
1795
    block->e_to_p_pressure = baricuda_e_to_p_pressure;
1796
  #endif
1797
 
1798
  block->active_extruder = extruder;
1799
 
1800
  #if ENABLED(AUTO_POWER_CONTROL)
1801
    if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS])
1802
      powerManager.power_on();
1803
  #endif
1804
 
1805
  // Enable active axes
1806
  #if CORE_IS_XY
1807
    if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
1808
      enable_X();
1809
      enable_Y();
1810
    }
1811
    #if DISABLED(Z_LATE_ENABLE)
1812
      if (block->steps[Z_AXIS]) enable_Z();
1813
    #endif
1814
  #elif CORE_IS_XZ
1815
    if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
1816
      enable_X();
1817
      enable_Z();
1818
    }
1819
    if (block->steps[Y_AXIS]) enable_Y();
1820
  #elif CORE_IS_YZ
1821
    if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
1822
      enable_Y();
1823
      enable_Z();
1824
    }
1825
    if (block->steps[X_AXIS]) enable_X();
1826
  #elif DISABLED(HANGPRINTER) // Hangprinters X, Y, Z, E0 axes should always be enabled anyways
1827
    if (block->steps[X_AXIS]) enable_X();
1828
    if (block->steps[Y_AXIS]) enable_Y();
1829
    #if DISABLED(Z_LATE_ENABLE)
1830
      if (block->steps[Z_AXIS]) enable_Z();
1831
    #endif
1832
  #endif
1833
 
1834
  // Enable extruder(s)
1835
  if (esteps) {
1836
    #if ENABLED(AUTO_POWER_CONTROL)
1837
      powerManager.power_on();
1838
    #endif
1839
 
1840
    #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
1841
 
1842
      #define DISABLE_IDLE_E(N) if (!g_uc_extruder_last_move[N]) disable_E##N();
1843
 
1844
      for (uint8_t i = 0; i < EXTRUDERS; i++)
1845
        if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
1846
 
1847
      switch (extruder) {
1848
        case 0:
1849
          #if EXTRUDERS > 1
1850
            DISABLE_IDLE_E(1);
1851
            #if EXTRUDERS > 2
1852
              DISABLE_IDLE_E(2);
1853
              #if EXTRUDERS > 3
1854
                DISABLE_IDLE_E(3);
1855
                #if EXTRUDERS > 4
1856
                  DISABLE_IDLE_E(4);
1857
                #endif // EXTRUDERS > 4
1858
              #endif // EXTRUDERS > 3
1859
            #endif // EXTRUDERS > 2
1860
          #endif // EXTRUDERS > 1
1861
          enable_E0();
1862
          g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
1863
          #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
1864
            if (extruder_duplication_enabled) {
1865
              enable_E1();
1866
              g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
1867
            }
1868
          #endif
1869
        break;
1870
        #if EXTRUDERS > 1
1871
          case 1:
1872
            DISABLE_IDLE_E(0);
1873
            #if EXTRUDERS > 2
1874
              DISABLE_IDLE_E(2);
1875
              #if EXTRUDERS > 3
1876
                DISABLE_IDLE_E(3);
1877
                #if EXTRUDERS > 4
1878
                  DISABLE_IDLE_E(4);
1879
                #endif // EXTRUDERS > 4
1880
              #endif // EXTRUDERS > 3
1881
            #endif // EXTRUDERS > 2
1882
            enable_E1();
1883
            g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
1884
          break;
1885
          #if EXTRUDERS > 2
1886
            case 2:
1887
              DISABLE_IDLE_E(0);
1888
              DISABLE_IDLE_E(1);
1889
              #if EXTRUDERS > 3
1890
                DISABLE_IDLE_E(3);
1891
                #if EXTRUDERS > 4
1892
                  DISABLE_IDLE_E(4);
1893
                #endif
1894
              #endif
1895
              enable_E2();
1896
              g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
1897
            break;
1898
            #if EXTRUDERS > 3
1899
              case 3:
1900
                DISABLE_IDLE_E(0);
1901
                DISABLE_IDLE_E(1);
1902
                DISABLE_IDLE_E(2);
1903
                #if EXTRUDERS > 4
1904
                  DISABLE_IDLE_E(4);
1905
                #endif
1906
                enable_E3();
1907
                g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
1908
              break;
1909
              #if EXTRUDERS > 4
1910
                case 4:
1911
                  DISABLE_IDLE_E(0);
1912
                  DISABLE_IDLE_E(1);
1913
                  DISABLE_IDLE_E(2);
1914
                  DISABLE_IDLE_E(3);
1915
                  enable_E4();
1916
                  g_uc_extruder_last_move[4] = (BLOCK_BUFFER_SIZE) * 2;
1917
                break;
1918
              #endif // EXTRUDERS > 4
1919
            #endif // EXTRUDERS > 3
1920
          #endif // EXTRUDERS > 2
1921
        #endif // EXTRUDERS > 1
1922
      }
1923
    #else
1924
      enable_E0();
1925
      enable_E1();
1926
      enable_E2();
1927
      enable_E3();
1928
      enable_E4();
1929
    #endif
1930
  }
1931
 
1932
  if (esteps)
1933
    NOLESS(fr_mm_s, min_feedrate_mm_s);
1934
  else
1935
    NOLESS(fr_mm_s, min_travel_feedrate_mm_s);
1936
 
1937
  /**
1938
   * This part of the code calculates the total length of the movement.
1939
   * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
1940
   * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
1941
   * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
1942
   * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
1943
   * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
1944
   */
1945
  #if IS_CORE
1946
    float delta_mm[Z_HEAD + 1];
1947
    #if CORE_IS_XY
1948
      delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
1949
      delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
1950
      delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
1951
      delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
1952
      delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
1953
    #elif CORE_IS_XZ
1954
      delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
1955
      delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
1956
      delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
1957
      delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
1958
      delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
1959
    #elif CORE_IS_YZ
1960
      delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
1961
      delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
1962
      delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
1963
      delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
1964
      delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
1965
    #endif
1966
  #else
1967
    float delta_mm[NUM_AXIS];
1968
    delta_mm[A_AXIS] = da * steps_to_mm[A_AXIS];
1969
    delta_mm[B_AXIS] = db * steps_to_mm[B_AXIS];
1970
    delta_mm[C_AXIS] = dc * steps_to_mm[C_AXIS];
1971
    #if ENABLED(HANGPRINTER)
1972
      delta_mm[D_AXIS] = dd * steps_to_mm[D_AXIS];
1973
    #endif
1974
  #endif
1975
  delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS_N];
1976
 
1977
  if (block->steps[A_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[B_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[C_AXIS] < MIN_STEPS_PER_SEGMENT
1978
    #if ENABLED(HANGPRINTER)
1979
      && block->steps[D_AXIS] < MIN_STEPS_PER_SEGMENT
1980
    #endif
1981
  ) {
1982
    block->millimeters = ABS(delta_mm[E_AXIS]);
1983
  }
1984
  else if (!millimeters) {
1985
    block->millimeters = SQRT(
1986
      #if CORE_IS_XY
1987
        sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
1988
      #elif CORE_IS_XZ
1989
        sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
1990
      #elif CORE_IS_YZ
1991
        sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
1992
      #elif ENABLED(HANGPRINTER)
1993
        sq(delta_mm[A_AXIS]) + sq(delta_mm[B_AXIS]) + sq(delta_mm[C_AXIS]) + sq(delta_mm[D_AXIS])
1994
      #else
1995
        sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
1996
      #endif
1997
    );
1998
  }
1999
  else
2000
    block->millimeters = millimeters;
2001
 
2002
  const float inverse_millimeters = 1.0f / block->millimeters;  // Inverse millimeters to remove multiple divides
2003
 
2004
  // Calculate inverse time for this move. No divide by zero due to previous checks.
2005
  // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
2006
  float inverse_secs = fr_mm_s * inverse_millimeters;
2007
 
2008
  // Get the number of non busy movements in queue (non busy means that they can be altered)
2009
  const uint8_t moves_queued = nonbusy_movesplanned();
2010
 
2011
  // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
2012
  #if ENABLED(SLOWDOWN) || ENABLED(ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
2013
    // Segment time im micro seconds
2014
    uint32_t segment_time_us = LROUND(1000000.0f / inverse_secs);
2015
  #endif
2016
 
2017
  #if ENABLED(SLOWDOWN)
2018
    if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / 2 - 1)) {
2019
      if (segment_time_us < min_segment_time_us) {
2020
        // buffer is draining, add extra time.  The amount of time added increases if the buffer is still emptied more.
2021
        const uint32_t nst = segment_time_us + LROUND(2 * (min_segment_time_us - segment_time_us) / moves_queued);
2022
        inverse_secs = 1000000.0f / nst;
2023
        #if defined(XY_FREQUENCY_LIMIT) || ENABLED(ULTRA_LCD)
2024
          segment_time_us = nst;
2025
        #endif
2026
      }
2027
    }
2028
  #endif
2029
 
2030
  #if ENABLED(ULTRA_LCD)
2031
    // Protect the access to the position.
2032
    const bool was_enabled = STEPPER_ISR_ENABLED();
2033
    if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
2034
 
2035
    block_buffer_runtime_us += segment_time_us;
2036
 
2037
    if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
2038
  #endif
2039
 
2040
  block->nominal_speed_sqr = sq(block->millimeters * inverse_secs);   //   (mm/sec)^2 Always > 0
2041
  block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
2042
 
2043
  #if ENABLED(FILAMENT_WIDTH_SENSOR)
2044
    static float filwidth_e_count = 0, filwidth_delay_dist = 0;
2045
 
2046
    //FMM update ring buffer used for delay with filament measurements
2047
    if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index[1] >= 0) {  //only for extruder with filament sensor and if ring buffer is initialized
2048
 
2049
      constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
2050
 
2051
      // increment counters with next move in e axis
2052
      filwidth_e_count += delta_mm[E_AXIS];
2053
      filwidth_delay_dist += delta_mm[E_AXIS];
2054
 
2055
      // Only get new measurements on forward E movement
2056
      if (!UNEAR_ZERO(filwidth_e_count)) {
2057
 
2058
        // Loop the delay distance counter (modulus by the mm length)
2059
        while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
2060
 
2061
        // Convert into an index into the measurement array
2062
        filwidth_delay_index[0] = int8_t(filwidth_delay_dist * 0.1f);
2063
 
2064
        // If the index has changed (must have gone forward)...
2065
        if (filwidth_delay_index[0] != filwidth_delay_index[1]) {
2066
          filwidth_e_count = 0; // Reset the E movement counter
2067
          const int8_t meas_sample = thermalManager.widthFil_to_size_ratio();
2068
          do {
2069
            filwidth_delay_index[1] = (filwidth_delay_index[1] + 1) % MMD_CM; // The next unused slot
2070
            measurement_delay[filwidth_delay_index[1]] = meas_sample;         // Store the measurement
2071
          } while (filwidth_delay_index[0] != filwidth_delay_index[1]);       // More slots to fill?
2072
        }
2073
      }
2074
    }
2075
  #endif
2076
 
2077
  // Calculate and limit speed in mm/sec for each axis
2078
  float current_speed[NUM_AXIS], speed_factor = 1.0f; // factor <1 decreases speed
2079
  LOOP_NUM_AXIS(i) {
2080
    const float cs = ABS((current_speed[i] = delta_mm[i] * inverse_secs));
2081
    #if ENABLED(DISTINCT_E_FACTORS)
2082
      if (i == E_AXIS) i += extruder;
2083
    #endif
2084
    if (cs > max_feedrate_mm_s[i]) NOMORE(speed_factor, max_feedrate_mm_s[i] / cs);
2085
  }
2086
 
2087
  // Max segment time in µs.
2088
  #ifdef XY_FREQUENCY_LIMIT
2089
 
2090
    // Check and limit the xy direction change frequency
2091
    const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
2092
    old_direction_bits = block->direction_bits;
2093
    segment_time_us = LROUND((float)segment_time_us / speed_factor);
2094
 
2095
    uint32_t xs0 = axis_segment_time_us[X_AXIS][0],
2096
             xs1 = axis_segment_time_us[X_AXIS][1],
2097
             xs2 = axis_segment_time_us[X_AXIS][2],
2098
             ys0 = axis_segment_time_us[Y_AXIS][0],
2099
             ys1 = axis_segment_time_us[Y_AXIS][1],
2100
             ys2 = axis_segment_time_us[Y_AXIS][2];
2101
 
2102
    if (TEST(direction_change, X_AXIS)) {
2103
      xs2 = axis_segment_time_us[X_AXIS][2] = xs1;
2104
      xs1 = axis_segment_time_us[X_AXIS][1] = xs0;
2105
      xs0 = 0;
2106
    }
2107
    xs0 = axis_segment_time_us[X_AXIS][0] = xs0 + segment_time_us;
2108
 
2109
    if (TEST(direction_change, Y_AXIS)) {
2110
      ys2 = axis_segment_time_us[Y_AXIS][2] = axis_segment_time_us[Y_AXIS][1];
2111
      ys1 = axis_segment_time_us[Y_AXIS][1] = axis_segment_time_us[Y_AXIS][0];
2112
      ys0 = 0;
2113
    }
2114
    ys0 = axis_segment_time_us[Y_AXIS][0] = ys0 + segment_time_us;
2115
 
2116
    const uint32_t max_x_segment_time = MAX3(xs0, xs1, xs2),
2117
                   max_y_segment_time = MAX3(ys0, ys1, ys2),
2118
                   min_xy_segment_time = MIN(max_x_segment_time, max_y_segment_time);
2119
    if (min_xy_segment_time < MAX_FREQ_TIME_US) {
2120
      const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
2121
      NOMORE(speed_factor, low_sf);
2122
    }
2123
  #endif // XY_FREQUENCY_LIMIT
2124
 
2125
  // Correct the speed
2126
  if (speed_factor < 1.0f) {
2127
    LOOP_NUM_AXIS(i) current_speed[i] *= speed_factor;
2128
    block->nominal_rate *= speed_factor;
2129
    block->nominal_speed_sqr = block->nominal_speed_sqr * sq(speed_factor);
2130
  }
2131
 
2132
  // Compute and limit the acceleration rate for the trapezoid generator.
2133
  const float steps_per_mm = block->step_event_count * inverse_millimeters;
2134
  uint32_t accel;
2135
  if (!block->steps[A_AXIS] && !block->steps[B_AXIS] && !block->steps[C_AXIS]
2136
    #if ENABLED(HANGPRINTER)
2137
      && !block->steps[D_AXIS]
2138
    #endif
2139
  ) {
2140
    // convert to: acceleration steps/sec^2
2141
    accel = CEIL(retract_acceleration * steps_per_mm);
2142
    #if ENABLED(LIN_ADVANCE)
2143
      block->use_advance_lead = false;
2144
    #endif
2145
  }
2146
  else {
2147
    #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
2148
      if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
2149
        const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
2150
        if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
2151
      } \
2152
    }while(0)
2153
 
2154
    #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
2155
      if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
2156
        const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
2157
        if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
2158
      } \
2159
    }while(0)
2160
 
2161
    // Start with print or travel acceleration
2162
    accel = CEIL((esteps ? acceleration : travel_acceleration) * steps_per_mm);
2163
 
2164
    #if ENABLED(LIN_ADVANCE)
2165
 
2166
      #if ENABLED(JUNCTION_DEVIATION)
2167
        #if ENABLED(DISTINCT_E_FACTORS)
2168
          #define MAX_E_JERK max_e_jerk[extruder]
2169
        #else
2170
          #define MAX_E_JERK max_e_jerk
2171
        #endif
2172
      #else
2173
        #define MAX_E_JERK max_jerk[E_AXIS]
2174
      #endif
2175
 
2176
      /**
2177
       *
2178
       * Use LIN_ADVANCE for blocks if all these are true:
2179
       *
2180
       * esteps             : This is a print move, because we checked for A, B, C steps before.
2181
       *
2182
       * extruder_advance_K : There is an advance factor set.
2183
       *
2184
       * de > 0             : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
2185
       */
2186
      block->use_advance_lead =  esteps
2187
                              && extruder_advance_K
2188
                              && de > 0;
2189
 
2190
      if (block->use_advance_lead) {
2191
        block->e_D_ratio = (target_float[E_AXIS] - position_float[E_AXIS]) /
2192
          #if IS_KINEMATIC
2193
            block->millimeters
2194
          #else
2195
            SQRT(sq(target_float[X_AXIS] - position_float[X_AXIS])
2196
               + sq(target_float[Y_AXIS] - position_float[Y_AXIS])
2197
               + sq(target_float[Z_AXIS] - position_float[Z_AXIS]))
2198
          #endif
2199
        ;
2200
 
2201
        // Check for unusual high e_D ratio to detect if a retract move was combined with the last print move due to min. steps per segment. Never execute this with advance!
2202
        // This assumes no one will use a retract length of 0mm < retr_length < ~0.2mm and no one will print 100mm wide lines using 3mm filament or 35mm wide lines using 1.75mm filament.
2203
        if (block->e_D_ratio > 3.0f)
2204
          block->use_advance_lead = false;
2205
        else {
2206
          const uint32_t max_accel_steps_per_s2 = MAX_E_JERK / (extruder_advance_K * block->e_D_ratio) * steps_per_mm;
2207
          #if ENABLED(LA_DEBUG)
2208
            if (accel > max_accel_steps_per_s2) SERIAL_ECHOLNPGM("Acceleration limited.");
2209
          #endif
2210
          NOMORE(accel, max_accel_steps_per_s2);
2211
        }
2212
      }
2213
    #endif
2214
 
2215
    #if ENABLED(DISTINCT_E_FACTORS)
2216
      #define ACCEL_IDX extruder
2217
    #else
2218
      #define ACCEL_IDX 0
2219
    #endif
2220
 
2221
    // Limit acceleration per axis
2222
    if (block->step_event_count <= cutoff_long) {
2223
      LIMIT_ACCEL_LONG(A_AXIS, 0);
2224
      LIMIT_ACCEL_LONG(B_AXIS, 0);
2225
      LIMIT_ACCEL_LONG(C_AXIS, 0);
2226
      #if ENABLED(HANGPRINTER)
2227
        LIMIT_ACCEL_LONG(D_AXIS, 0);
2228
      #endif
2229
      LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
2230
    }
2231
    else {
2232
      LIMIT_ACCEL_FLOAT(A_AXIS, 0);
2233
      LIMIT_ACCEL_FLOAT(B_AXIS, 0);
2234
      LIMIT_ACCEL_FLOAT(C_AXIS, 0);
2235
      #if ENABLED(HANGPRINTER)
2236
        LIMIT_ACCEL_FLOAT(D_AXIS, 0);
2237
      #endif
2238
      LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
2239
    }
2240
  }
2241
  block->acceleration_steps_per_s2 = accel;
2242
  block->acceleration = accel / steps_per_mm;
2243
  #if DISABLED(S_CURVE_ACCELERATION)
2244
    block->acceleration_rate = (uint32_t)(accel * (4096.0f * 4096.0f / (STEPPER_TIMER_RATE)));
2245
  #endif
2246
  #if ENABLED(LIN_ADVANCE)
2247
    if (block->use_advance_lead) {
2248
      block->advance_speed = (STEPPER_TIMER_RATE) / (extruder_advance_K * block->e_D_ratio * block->acceleration * axis_steps_per_mm[E_AXIS_N]);
2249
      #if ENABLED(LA_DEBUG)
2250
        if (extruder_advance_K * block->e_D_ratio * block->acceleration * 2 < SQRT(block->nominal_speed_sqr) * block->e_D_ratio)
2251
          SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
2252
        if (block->advance_speed < 200)
2253
          SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
2254
      #endif
2255
    }
2256
  #endif
2257
 
2258
  float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2
2259
 
2260
  #if ENABLED(JUNCTION_DEVIATION)
2261
 
2262
    /**
2263
     * Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
2264
     * Let a circle be tangent to both previous and current path line segments, where the junction
2265
     * deviation is defined as the distance from the junction to the closest edge of the circle,
2266
     * colinear with the circle center. The circular segment joining the two paths represents the
2267
     * path of centripetal acceleration. Solve for max velocity based on max acceleration about the
2268
     * radius of the circle, defined indirectly by junction deviation. This may be also viewed as
2269
     * path width or max_jerk in the previous Grbl version. This approach does not actually deviate
2270
     * from path, but used as a robust way to compute cornering speeds, as it takes into account the
2271
     * nonlinearities of both the junction angle and junction velocity.
2272
     *
2273
     * NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path
2274
     * mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact
2275
     * stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here
2276
     * is exactly the same. Instead of motioning all the way to junction point, the machine will
2277
     * just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
2278
     * a continuous mode path, but ARM-based microcontrollers most certainly do.
2279
     *
2280
     * NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
2281
     * changed dynamically during operation nor can the line move geometry. This must be kept in
2282
     * memory in the event of a feedrate override changing the nominal speeds of blocks, which can
2283
     * change the overall maximum entry speed conditions of all blocks.
2284
     *
2285
     * #######
2286
     * https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754
2287
     *
2288
     * hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin:
2289
          Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm
2290
          on then on anything with less sides than an octagon. With this, and the
2291
          reverse pass actually recalculating things, a corner acceleration value
2292
          of 1000 junction deviation of .05 are pretty reasonable. If the cycles
2293
          can be spared, a better acos could be used. For all I know, it may be
2294
          already calculated in a different place. */
2295
 
2296
    // Unit vector of previous path line segment
2297
    static float previous_unit_vec[XYZE];
2298
 
2299
    float unit_vec[] = {
2300
      delta_mm[A_AXIS] * inverse_millimeters,
2301
      delta_mm[B_AXIS] * inverse_millimeters,
2302
      delta_mm[C_AXIS] * inverse_millimeters,
2303
      delta_mm[E_AXIS] * inverse_millimeters
2304
    };
2305
 
2306
    // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
2307
    if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
2308
      // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
2309
      // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
2310
      float junction_cos_theta = -previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
2311
                                 -previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
2312
                                 -previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS]
2313
                                 -previous_unit_vec[E_AXIS] * unit_vec[E_AXIS]
2314
                                ;
2315
 
2316
      // NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
2317
      if (junction_cos_theta > 0.999999f) {
2318
        // For a 0 degree acute junction, just set minimum junction speed.
2319
        vmax_junction_sqr = sq(float(MINIMUM_PLANNER_SPEED));
2320
      }
2321
      else {
2322
        NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero.
2323
 
2324
        // Convert delta vector to unit vector
2325
        float junction_unit_vec[XYZE] = {
2326
          unit_vec[X_AXIS] - previous_unit_vec[X_AXIS],
2327
          unit_vec[Y_AXIS] - previous_unit_vec[Y_AXIS],
2328
          unit_vec[Z_AXIS] - previous_unit_vec[Z_AXIS],
2329
          unit_vec[E_AXIS] - previous_unit_vec[E_AXIS]
2330
        };
2331
        normalize_junction_vector(junction_unit_vec);
2332
 
2333
        const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec),
2334
                    sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive.
2335
 
2336
        vmax_junction_sqr = (junction_acceleration * junction_deviation_mm * sin_theta_d2) / (1.0f - sin_theta_d2);
2337
        if (block->millimeters < 1) {
2338
 
2339
          // Fast acos approximation, minus the error bar to be safe
2340
          const float junction_theta = (RADIANS(-40) * sq(junction_cos_theta) - RADIANS(50)) * junction_cos_theta + RADIANS(90) - 0.18f;
2341
 
2342
          // If angle is greater than 135 degrees (octagon), find speed for approximate arc
2343
          if (junction_theta > RADIANS(135)) {
2344
            const float limit_sqr = block->millimeters / (RADIANS(180) - junction_theta) * junction_acceleration;
2345
            NOMORE(vmax_junction_sqr, limit_sqr);
2346
          }
2347
        }
2348
      }
2349
 
2350
      // Get the lowest speed
2351
      vmax_junction_sqr = MIN3(vmax_junction_sqr, block->nominal_speed_sqr, previous_nominal_speed_sqr);
2352
    }
2353
    else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later.
2354
      vmax_junction_sqr = 0;
2355
 
2356
    COPY(previous_unit_vec, unit_vec);
2357
 
2358
  #else // Classic Jerk Limiting
2359
 
2360
    /**
2361
     * Adapted from Průša MKS firmware
2362
     * https://github.com/prusa3d/Prusa-Firmware
2363
     */
2364
    const float nominal_speed = SQRT(block->nominal_speed_sqr);
2365
 
2366
    // Exit speed limited by a jerk to full halt of a previous last segment
2367
    static float previous_safe_speed;
2368
 
2369
    // Start with a safe speed (from which the machine may halt to stop immediately).
2370
    float safe_speed = nominal_speed;
2371
 
2372
    uint8_t limited = 0;
2373
    LOOP_NUM_AXIS(i) {
2374
      const float jerk = ABS(current_speed[i]),   // cs : Starting from zero, change in speed for this axis
2375
                  maxj = max_jerk[i];             // mj : The max jerk setting for this axis
2376
      if (jerk > maxj) {                          // cs > mj : New current speed too fast?
2377
        if (limited) {                            // limited already?
2378
          const float mjerk = nominal_speed * maxj; // ns*mj
2379
          if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk; // ns*mj/cs
2380
        }
2381
        else {
2382
          safe_speed *= maxj / jerk;              // Initial limit: ns*mj/cs
2383
          ++limited;                              // Initially limited
2384
        }
2385
      }
2386
    }
2387
 
2388
    float vmax_junction;
2389
    if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
2390
      // Estimate a maximum velocity allowed at a joint of two successive segments.
2391
      // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
2392
      // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
2393
 
2394
      // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
2395
      float v_factor = 1;
2396
      limited = 0;
2397
 
2398
      // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
2399
      // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
2400
      const float previous_nominal_speed = SQRT(previous_nominal_speed_sqr);
2401
      vmax_junction = MIN(nominal_speed, previous_nominal_speed);
2402
 
2403
      // Now limit the jerk in all axes.
2404
      const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
2405
      LOOP_NUM_AXIS(axis) {
2406
        // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
2407
        float v_exit = previous_speed[axis] * smaller_speed_factor,
2408
              v_entry = current_speed[axis];
2409
        if (limited) {
2410
          v_exit *= v_factor;
2411
          v_entry *= v_factor;
2412
        }
2413
 
2414
        // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
2415
        const float jerk = (v_exit > v_entry)
2416
            ? //                                  coasting             axis reversal
2417
              ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : MAX(v_exit, -v_entry) )
2418
            : // v_exit <= v_entry                coasting             axis reversal
2419
              ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : MAX(-v_exit, v_entry) );
2420
 
2421
        if (jerk > max_jerk[axis]) {
2422
          v_factor *= max_jerk[axis] / jerk;
2423
          ++limited;
2424
        }
2425
      }
2426
      if (limited) vmax_junction *= v_factor;
2427
      // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
2428
      // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
2429
      const float vmax_junction_threshold = vmax_junction * 0.99f;
2430
      if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
2431
        vmax_junction = safe_speed;
2432
    }
2433
    else
2434
      vmax_junction = safe_speed;
2435
 
2436
    previous_safe_speed = safe_speed;
2437
    vmax_junction_sqr = sq(vmax_junction);
2438
 
2439
  #endif // Classic Jerk Limiting
2440
 
2441
  // Max entry speed of this block equals the max exit speed of the previous block.
2442
  block->max_entry_speed_sqr = vmax_junction_sqr;
2443
 
2444
  // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
2445
  const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, sq(float(MINIMUM_PLANNER_SPEED)), block->millimeters);
2446
 
2447
  // If we are trying to add a split block, start with the
2448
  // max. allowed speed to avoid an interrupted first move.
2449
  block->entry_speed_sqr = !split_move ? sq(float(MINIMUM_PLANNER_SPEED)) : MIN(vmax_junction_sqr, v_allowable_sqr);
2450
 
2451
  // Initialize planner efficiency flags
2452
  // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
2453
  // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
2454
  // the current block and next block junction speeds are guaranteed to always be at their maximum
2455
  // junction speeds in deceleration and acceleration, respectively. This is due to how the current
2456
  // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
2457
  // the reverse and forward planners, the corresponding block junction speed will always be at the
2458
  // the maximum junction speed and may always be ignored for any speed reduction checks.
2459
  block->flag |= block->nominal_speed_sqr <= v_allowable_sqr ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
2460
 
2461
  // Update previous path unit_vector and nominal speed
2462
  COPY(previous_speed, current_speed);
2463
  previous_nominal_speed_sqr = block->nominal_speed_sqr;
2464
 
2465
  // Update the position (only when a move was queued)
2466
  static_assert(COUNT(target) > 1, "Parameter to _populate_block must be (&target)["
2467
    #if ENABLED(HANGPRINTER)
2468
      "ABCD"
2469
    #else
2470
      "XYZ"
2471
    #endif
2472
    "E]!"
2473
  );
2474
 
2475
  if (COUNT_MOVE) {
2476
    COPY(position, target);
2477
    #if HAS_POSITION_FLOAT
2478
      COPY(position_float, target_float);
2479
    #endif
2480
  }
2481
 
2482
  // Movement was accepted
2483
  return true;
2484
} // _populate_block()
2485
 
2486
/**
2487
 * Planner::buffer_sync_block
2488
 * Add a block to the buffer that just updates the position
2489
 */
2490
void Planner::buffer_sync_block() {
2491
  // Wait for the next available block
2492
  uint8_t next_buffer_head;
2493
  block_t * const block = get_next_free_block(next_buffer_head);
2494
 
2495
  // Clear block
2496
  memset(block, 0, sizeof(block_t));
2497
 
2498
  block->flag = BLOCK_FLAG_SYNC_POSITION;
2499
 
2500
  block->position[A_AXIS] = position[A_AXIS];
2501
  block->position[B_AXIS] = position[B_AXIS];
2502
  block->position[C_AXIS] = position[C_AXIS];
2503
  #if ENABLED(HANGPRINTER)
2504
    block->position[D_AXIS] = position[D_AXIS];
2505
  #endif
2506
  block->position[E_AXIS] = position[E_AXIS];
2507
 
2508
  // If this is the first added movement, reload the delay, otherwise, cancel it.
2509
  if (block_buffer_head == block_buffer_tail) {
2510
    // If it was the first queued block, restart the 1st block delivery delay, to
2511
    // give the planner an opportunity to queue more movements and plan them
2512
    // As there are no queued movements, the Stepper ISR will not touch this
2513
    // variable, so there is no risk setting this here (but it MUST be done
2514
    // before the following line!!)
2515
    delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
2516
  }
2517
 
2518
  block_buffer_head = next_buffer_head;
2519
 
2520
  stepper.wake_up();
2521
} // buffer_sync_block()
2522
 
2523
/**
2524
 * Planner::buffer_segment
2525
 *
2526
 * Add a new linear movement to the buffer in axis units.
2527
 *
2528
 * Leveling and kinematics should be applied ahead of calling this.
2529
 *
2530
 *  a,b,c,e     - target positions in mm and/or degrees
2531
 *  fr_mm_s     - (target) speed of the move
2532
 *  extruder    - target extruder
2533
 *  millimeters - the length of the movement, if known
2534
 */
2535
bool Planner::buffer_segment(const float &a, const float &b, const float &c
2536
  #if ENABLED(HANGPRINTER)
2537
    , const float &d
2538
  #endif
2539
  , const float &e, const float &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
2540
  #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
2541
    , bool count_it /* = true */
2542
  #endif
2543
) {
2544
 
2545
  // If we are cleaning, do not accept queuing of movements
2546
  if (cleaning_buffer_counter) return false;
2547
 
2548
  // When changing extruders recalculate steps corresponding to the E position
2549
  #if ENABLED(DISTINCT_E_FACTORS)
2550
    if (last_extruder != extruder && axis_steps_per_mm[E_AXIS_N] != axis_steps_per_mm[E_AXIS + last_extruder]) {
2551
      position[E_AXIS] = LROUND(position[E_AXIS] * axis_steps_per_mm[E_AXIS_N] * steps_to_mm[E_AXIS + last_extruder]);
2552
      last_extruder = extruder;
2553
    }
2554
  #endif
2555
 
2556
  // The target position of the tool in absolute steps
2557
  // Calculate target position in absolute steps
2558
  const int32_t target[NUM_AXIS] = {
2559
    #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
2560
      LROUND(k0[A_AXIS] * (SQRT(k1[A_AXIS] + a * k2[A_AXIS]) - sqrtk1[A_AXIS])),
2561
      LROUND(k0[B_AXIS] * (SQRT(k1[B_AXIS] + b * k2[B_AXIS]) - sqrtk1[B_AXIS])),
2562
      LROUND(k0[C_AXIS] * (SQRT(k1[C_AXIS] + c * k2[C_AXIS]) - sqrtk1[C_AXIS])),
2563
      LROUND(k0[D_AXIS] * (SQRT(k1[D_AXIS] + d * k2[D_AXIS]) - sqrtk1[D_AXIS])),
2564
    #else
2565
      LROUND(a * axis_steps_per_mm[A_AXIS]),
2566
      LROUND(b * axis_steps_per_mm[B_AXIS]),
2567
      LROUND(c * axis_steps_per_mm[C_AXIS]),
2568
      #if ENABLED(HANGPRINTER)
2569
        LROUND(d * axis_steps_per_mm[D_AXIS]),
2570
      #endif
2571
    #endif
2572
    LROUND(e * axis_steps_per_mm[E_AXIS_N])
2573
  };
2574
 
2575
  #if HAS_POSITION_FLOAT
2576
    const float target_float[NUM_AXIS] = { a, b, c
2577
      #if ENABLED(HANGPRINTER)
2578
        , d
2579
      #endif
2580
      , e
2581
    };
2582
  #endif
2583
 
2584
  // DRYRUN prevents E moves from taking place
2585
  if (DEBUGGING(DRYRUN)) {
2586
    if (COUNT_MOVE) {
2587
      position[E_AXIS] = target[E_AXIS];
2588
      #if HAS_POSITION_FLOAT
2589
        position_float[E_AXIS] = e;
2590
      #endif
2591
    }
2592
  }
2593
 
2594
  /* <-- add a slash to enable
2595
    SERIAL_ECHOPAIR("  buffer_segment FR:", fr_mm_s);
2596
    #if IS_KINEMATIC
2597
      SERIAL_ECHOPAIR(" A:", a);
2598
      SERIAL_ECHOPAIR(" (", position[A_AXIS]);
2599
      SERIAL_ECHOPAIR("->", target[A_AXIS]);
2600
      SERIAL_ECHOPAIR(") B:", b);
2601
    #else
2602
      SERIAL_ECHOPAIR(" X:", a);
2603
      SERIAL_ECHOPAIR(" (", position[X_AXIS]);
2604
      SERIAL_ECHOPAIR("->", target[X_AXIS]);
2605
      SERIAL_ECHOPAIR(") Y:", b);
2606
    #endif
2607
    SERIAL_ECHOPAIR(" (", position[Y_AXIS]);
2608
    SERIAL_ECHOPAIR("->", target[Y_AXIS]);
2609
    #if ENABLED(DELTA) || ENABLED(HANGPRINTER)
2610
      SERIAL_ECHOPAIR(") C:", c);
2611
    #else
2612
      SERIAL_ECHOPAIR(") Z:", c);
2613
    #endif
2614
    SERIAL_ECHOPAIR(" (", position[Z_AXIS]);
2615
    SERIAL_ECHOPAIR("->", target[Z_AXIS]);
2616
    #if ENABLED(HANGPRINTER)
2617
      SERIAL_ECHOPAIR(") D:", d);
2618
      SERIAL_ECHOPAIR(" (", position[D_AXIS]);
2619
      SERIAL_ECHOPAIR("->", target[D_AXIS]);
2620
    #endif
2621
    SERIAL_ECHOPAIR(") E:", e);
2622
    SERIAL_ECHOPAIR(" (", position[E_AXIS]);
2623
    SERIAL_ECHOPAIR("->", target[E_AXIS]);
2624
    SERIAL_ECHOLNPGM(")");
2625
  //*/
2626
 
2627
  // Queue the movement
2628
  if (
2629
    !_buffer_steps(target
2630
      #if HAS_POSITION_FLOAT
2631
        , target_float
2632
      #endif
2633
      , fr_mm_s, extruder, millimeters
2634
      #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
2635
        , count_it
2636
      #endif
2637
    )
2638
  ) return false;
2639
 
2640
  stepper.wake_up();
2641
  return true;
2642
} // buffer_segment()
2643
 
2644
/**
2645
 * Directly set the planner XYZ position (and stepper positions)
2646
 * converting mm (or angles for SCARA) into steps.
2647
 *
2648
 * On CORE machines stepper ABC will be translated from the given XYZ.
2649
 */
2650
 
2651
void Planner::_set_position_mm(const float &a, const float &b, const float &c
2652
  #if ENABLED(HANGPRINTER)
2653
    , const float &d
2654
  #endif
2655
  , const float &e
2656
) {
2657
  #if ENABLED(DISTINCT_E_FACTORS)
2658
    last_extruder = active_extruder;
2659
  #endif
2660
  #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
2661
    position[A_AXIS] = LROUND(k0[A_AXIS] * (SQRT(k1[A_AXIS] + a * k2[A_AXIS]) - sqrtk1[A_AXIS])),
2662
    position[B_AXIS] = LROUND(k0[B_AXIS] * (SQRT(k1[B_AXIS] + b * k2[B_AXIS]) - sqrtk1[B_AXIS])),
2663
    position[C_AXIS] = LROUND(k0[C_AXIS] * (SQRT(k1[C_AXIS] + c * k2[C_AXIS]) - sqrtk1[C_AXIS])),
2664
    position[D_AXIS] = LROUND(k0[D_AXIS] * (SQRT(k1[D_AXIS] + d * k2[D_AXIS]) - sqrtk1[D_AXIS])),
2665
  #else
2666
    position[A_AXIS] = LROUND(a * axis_steps_per_mm[A_AXIS]);
2667
    position[B_AXIS] = LROUND(b * axis_steps_per_mm[B_AXIS]);
2668
    position[C_AXIS] = LROUND(axis_steps_per_mm[C_AXIS] * (c + (
2669
      #if !IS_KINEMATIC && ENABLED(AUTO_BED_LEVELING_UBL)
2670
        leveling_active ? ubl.get_z_correction(a, b) :
2671
      #endif
2672
      0)
2673
    ));
2674
    #if ENABLED(HANGPRINTER)
2675
      position[D_AXIS] = LROUND(d * axis_steps_per_mm[D_AXIS]),
2676
    #endif
2677
  #endif
2678
  position[E_AXIS] = LROUND(e * axis_steps_per_mm[_EINDEX]);
2679
  #if HAS_POSITION_FLOAT
2680
    position_float[A_AXIS] = a;
2681
    position_float[B_AXIS] = b;
2682
    position_float[C_AXIS] = c;
2683
    #if ENABLED(HANGPRINTER)
2684
      position_float[D_AXIS] = d;
2685
    #endif
2686
    position_float[E_AXIS] = e;
2687
  #endif
2688
  if (has_blocks_queued()) {
2689
    //previous_nominal_speed_sqr = 0.0; // Reset planner junction speeds. Assume start from rest.
2690
    //ZERO(previous_speed);
2691
    buffer_sync_block();
2692
  }
2693
  else
2694
    stepper.set_position(position[A_AXIS], position[B_AXIS], position[C_AXIS],
2695
      #if ENABLED(HANGPRINTER)
2696
        position[D_AXIS],
2697
      #endif
2698
      position[E_AXIS]
2699
    );
2700
}
2701
 
2702
void Planner::set_position_mm_kinematic(const float (&cart)[XYZE]) {
2703
  #if PLANNER_LEVELING
2704
    float raw[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
2705
    apply_leveling(raw);
2706
  #elif ENABLED(HANGPRINTER)
2707
    float raw[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
2708
  #else
2709
    const float (&raw)[XYZE] = cart;
2710
  #endif
2711
  #if IS_KINEMATIC
2712
    inverse_kinematics(raw);
2713
    #if ENABLED(HANGPRINTER)
2714
      _set_position_mm(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], cart[E_CART]);
2715
    #else
2716
      _set_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_CART]);
2717
    #endif
2718
  #else
2719
    _set_position_mm(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], cart[E_CART]);
2720
  #endif
2721
}
2722
 
2723
/**
2724
 * Setters for planner position (also setting stepper position).
2725
 */
2726
void Planner::set_position_mm(const AxisEnum axis, const float &v) {
2727
  #if ENABLED(DISTINCT_E_FACTORS)
2728
    const uint8_t axis_index = axis + (axis == E_AXIS ? active_extruder : 0);
2729
    last_extruder = active_extruder;
2730
  #else
2731
    const uint8_t axis_index = axis;
2732
  #endif
2733
  position[axis] = LROUND(axis_steps_per_mm[axis_index] * (v + (
2734
    #if ENABLED(AUTO_BED_LEVELING_UBL)
2735
      axis == Z_AXIS && leveling_active ? ubl.get_z_correction(current_position[X_AXIS], current_position[Y_AXIS]) :
2736
    #endif
2737
    0)
2738
  ));
2739
  #if HAS_POSITION_FLOAT
2740
    position_float[axis] = v;
2741
  #endif
2742
  if (has_blocks_queued())
2743
    buffer_sync_block();
2744
  else
2745
    stepper.set_position(axis, position[axis]);
2746
}
2747
 
2748
// Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
2749
void Planner::reset_acceleration_rates() {
2750
  #if ENABLED(DISTINCT_E_FACTORS)
2751
    #define AXIS_CONDITION (i < E_AXIS || i == E_AXIS + active_extruder)
2752
  #else
2753
    #define AXIS_CONDITION true
2754
  #endif
2755
  uint32_t highest_rate = 1;
2756
  LOOP_NUM_AXIS_N(i) {
2757
    max_acceleration_steps_per_s2[i] = max_acceleration_mm_per_s2[i] * axis_steps_per_mm[i];
2758
    if (AXIS_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
2759
  }
2760
  cutoff_long = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
2761
  #if ENABLED(JUNCTION_DEVIATION) && ENABLED(LIN_ADVANCE)
2762
    recalculate_max_e_jerk();
2763
  #endif
2764
}
2765
 
2766
// Recalculate position, steps_to_mm if axis_steps_per_mm changes!
2767
void Planner::refresh_positioning() {
2768
  LOOP_NUM_AXIS_N(i) steps_to_mm[i] = 1.0f / axis_steps_per_mm[i];
2769
  set_position_mm_kinematic(current_position);
2770
  reset_acceleration_rates();
2771
}
2772
 
2773
#if ENABLED(AUTOTEMP)
2774
 
2775
  void Planner::autotemp_M104_M109() {
2776
    if ((autotemp_enabled = parser.seen('F'))) autotemp_factor = parser.value_float();
2777
    if (parser.seen('S')) autotemp_min = parser.value_celsius();
2778
    if (parser.seen('B')) autotemp_max = parser.value_celsius();
2779
  }
2780
 
2781
#endif