chiark / gitweb /
bb1e84be10270f4cf0390c84ad88161c02172790
[marlin.git] / Marlin / planner.cpp
1 /*
2   planner.c - buffers movement commands and manages the acceleration profile plan
3   Part of Grbl
4
5   Copyright (c) 2009-2011 Simen Svale Skogsrud
6
7   Grbl is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Grbl is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with Grbl.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 /* The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis. */
22
23 /*  
24   Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
25   
26   s == speed, a == acceleration, t == time, d == distance
27
28   Basic definitions:
29
30     Speed[s_, a_, t_] := s + (a*t) 
31     Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
32
33   Distance to reach a specific speed with a constant acceleration:
34
35     Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
36       d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
37
38   Speed after a given distance of travel with constant acceleration:
39
40     Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
41       m -> Sqrt[2 a d + s^2]    
42
43     DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
44
45   When to start braking (di) to reach a specified destionation speed (s2) after accelerating
46   from initial speed s1 without ever stopping at a plateau:
47
48     Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
49       di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
50
51     IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
52 */
53                                                                                                             
54 #include "Marlin.h"
55 #include "planner.h"
56 #include "stepper.h"
57 #include "temperature.h"
58 #include "ultralcd.h"
59 #include "language.h"
60
61 //===========================================================================
62 //=============================public variables ============================
63 //===========================================================================
64
65 unsigned long minsegmenttime;
66 float max_feedrate[4]; // set the max speeds
67 float axis_steps_per_unit[4];
68 unsigned long max_acceleration_units_per_sq_second[4]; // Use M201 to override by software
69 float minimumfeedrate;
70 float acceleration;         // Normal acceleration mm/s^2  THIS IS THE DEFAULT ACCELERATION for all moves. M204 SXXXX
71 float retract_acceleration; //  mm/s^2   filament pull-pack and push-forward  while standing still in the other axis M204 TXXXX
72 float max_xy_jerk; //speed than can be stopped at once, if i understand correctly.
73 float max_z_jerk;
74 float max_e_jerk;
75 float mintravelfeedrate;
76 unsigned long axis_steps_per_sqr_second[NUM_AXIS];
77
78 // The current position of the tool in absolute steps
79 long position[4];   //rescaled from extern when axis_steps_per_unit are changed by gcode
80 static float previous_speed[4]; // Speed of previous path line segment
81 static float previous_nominal_speed; // Nominal speed of previous path line segment
82
83 extern volatile int extrudemultiply; // Sets extrude multiply factor (in percent)
84
85 #ifdef AUTOTEMP
86     float autotemp_max=250;
87     float autotemp_min=210;
88     float autotemp_factor=0.1;
89     bool autotemp_enabled=false;
90 #endif
91
92 //===========================================================================
93 //=================semi-private variables, used in inline  functions    =====
94 //===========================================================================
95 block_t block_buffer[BLOCK_BUFFER_SIZE];            // A ring buffer for motion instfructions
96 volatile unsigned char block_buffer_head;           // Index of the next block to be pushed
97 volatile unsigned char block_buffer_tail;           // Index of the block to process now
98
99 //===========================================================================
100 //=============================private variables ============================
101 //===========================================================================
102 #ifdef PREVENT_DANGEROUS_EXTRUDE
103   bool allow_cold_extrude=false;
104 #endif
105 #ifdef XY_FREQUENCY_LIMIT
106   // Used for the frequency limit
107   static unsigned char old_direction_bits = 0;               // Old direction bits. Used for speed calculations
108   static long x_segment_time[3]={0,0,0};                     // Segment times (in us). Used for speed calculations
109   static long y_segment_time[3]={0,0,0};
110 #endif
111
112 // Returns the index of the next block in the ring buffer
113 // NOTE: Removed modulo (%) operator, which uses an expensive divide and multiplication.
114 static int8_t next_block_index(int8_t block_index) {
115   block_index++;
116   if (block_index == BLOCK_BUFFER_SIZE) { block_index = 0; }
117   return(block_index);
118 }
119
120
121 // Returns the index of the previous block in the ring buffer
122 static int8_t prev_block_index(int8_t block_index) {
123   if (block_index == 0) { block_index = BLOCK_BUFFER_SIZE; }
124   block_index--;
125   return(block_index);
126 }
127
128 //===========================================================================
129 //=============================functions         ============================
130 //===========================================================================
131
132 // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the 
133 // given acceleration:
134 FORCE_INLINE float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration)
135 {
136   if (acceleration!=0) {
137   return((target_rate*target_rate-initial_rate*initial_rate)/
138          (2.0*acceleration));
139   }
140   else {
141     return 0.0;  // acceleration was 0, set acceleration distance to 0
142   }
143 }
144
145 // This function gives you the point at which you must start braking (at the rate of -acceleration) if 
146 // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after
147 // a total travel of distance. This can be used to compute the intersection point between acceleration and
148 // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed)
149
150 FORCE_INLINE float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance) 
151 {
152  if (acceleration!=0) {
153   return((2.0*acceleration*distance-initial_rate*initial_rate+final_rate*final_rate)/
154          (4.0*acceleration) );
155   }
156   else {
157     return 0.0;  // acceleration was 0, set intersection distance to 0
158   }
159 }
160
161 // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors.
162
163 void calculate_trapezoid_for_block(block_t *block, float entry_factor, float exit_factor) {
164   unsigned long initial_rate = ceil(block->nominal_rate*entry_factor); // (step/min)
165   unsigned long final_rate = ceil(block->nominal_rate*exit_factor); // (step/min)
166
167   // Limit minimal step rate (Otherwise the timer will overflow.)
168   if(initial_rate <120) {initial_rate=120; }
169   if(final_rate < 120) {final_rate=120;  }
170   
171   long acceleration = block->acceleration_st;
172   int32_t accelerate_steps =
173     ceil(estimate_acceleration_distance(block->initial_rate, block->nominal_rate, acceleration));
174   int32_t decelerate_steps =
175     floor(estimate_acceleration_distance(block->nominal_rate, block->final_rate, -acceleration));
176     
177   // Calculate the size of Plateau of Nominal Rate.
178   int32_t plateau_steps = block->step_event_count-accelerate_steps-decelerate_steps;
179   
180   // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
181   // have to use intersection_distance() to calculate when to abort acceleration and start braking
182   // in order to reach the final_rate exactly at the end of this block.
183   if (plateau_steps < 0) {
184     accelerate_steps = ceil(
185       intersection_distance(block->initial_rate, block->final_rate, acceleration, block->step_event_count));
186     accelerate_steps = max(accelerate_steps,0); // Check limits due to numerical round-off
187     accelerate_steps = min(accelerate_steps,block->step_event_count);
188     plateau_steps = 0;
189   }
190
191   #ifdef ADVANCE
192     volatile long initial_advance = block->advance*entry_factor*entry_factor; 
193     volatile long final_advance = block->advance*exit_factor*exit_factor;
194   #endif // ADVANCE
195   
196  // block->accelerate_until = accelerate_steps;
197  // block->decelerate_after = accelerate_steps+plateau_steps;
198   CRITICAL_SECTION_START;  // Fill variables used by the stepper in a critical section
199   if(block->busy == false) { // Don't update variables if block is busy.
200     block->accelerate_until = accelerate_steps;
201     block->decelerate_after = accelerate_steps+plateau_steps;
202     block->initial_rate = initial_rate;
203     block->final_rate = final_rate;
204   #ifdef ADVANCE
205       block->initial_advance = initial_advance;
206       block->final_advance = final_advance;
207   #endif //ADVANCE
208   }
209   CRITICAL_SECTION_END;
210 }                    
211
212 // Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the 
213 // acceleration within the allotted distance.
214 FORCE_INLINE float max_allowable_speed(float acceleration, float target_velocity, float distance) {
215   return  sqrt(target_velocity*target_velocity-2*acceleration*distance);
216 }
217
218 // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
219 // This method will calculate the junction jerk as the euclidean distance between the nominal 
220 // velocities of the respective blocks.
221 //inline float junction_jerk(block_t *before, block_t *after) {
222 //  return sqrt(
223 //    pow((before->speed_x-after->speed_x), 2)+pow((before->speed_y-after->speed_y), 2));
224 //}
225
226
227 // The kernel called by planner_recalculate() when scanning the plan from last to first entry.
228 void planner_reverse_pass_kernel(block_t *previous, block_t *current, block_t *next) {
229   if(!current) { return; }
230   
231     if (next) {
232     // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
233     // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
234     // check for maximum allowable speed reductions to ensure maximum possible planned speed.
235     if (current->entry_speed != current->max_entry_speed) {
236     
237       // If nominal length true, max junction speed is guaranteed to be reached. Only compute
238       // for max allowable speed if block is decelerating and nominal length is false.
239       if ((!current->nominal_length_flag) && (current->max_entry_speed > next->entry_speed)) {
240         current->entry_speed = min( current->max_entry_speed,
241           max_allowable_speed(-current->acceleration,next->entry_speed,current->millimeters));
242       } else {
243         current->entry_speed = current->max_entry_speed;
244       }
245       current->recalculate_flag = true;
246     
247     }
248   } // Skip last block. Already initialized and set for recalculation.
249 }
250
251 // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This 
252 // implements the reverse pass.
253 void planner_reverse_pass() {
254   uint8_t block_index = block_buffer_head;
255   if(((block_buffer_head-block_buffer_tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1)) > 3) {
256     block_index = (block_buffer_head - 3) & (BLOCK_BUFFER_SIZE - 1);
257     block_t *block[3] = { NULL, NULL, NULL };
258     while(block_index != block_buffer_tail) { 
259       block_index = prev_block_index(block_index); 
260       block[2]= block[1];
261       block[1]= block[0];
262       block[0] = &block_buffer[block_index];
263       planner_reverse_pass_kernel(block[0], block[1], block[2]);
264     }
265   }
266 }
267
268 // The kernel called by planner_recalculate() when scanning the plan from first to last entry.
269 void planner_forward_pass_kernel(block_t *previous, block_t *current, block_t *next) {
270   if(!previous) { return; }
271   
272   // If the previous block is an acceleration block, but it is not long enough to complete the
273   // full speed change within the block, we need to adjust the entry speed accordingly. Entry
274   // speeds have already been reset, maximized, and reverse planned by reverse planner.
275   // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
276   if (!previous->nominal_length_flag) {
277     if (previous->entry_speed < current->entry_speed) {
278       double entry_speed = min( current->entry_speed,
279         max_allowable_speed(-previous->acceleration,previous->entry_speed,previous->millimeters) );
280
281       // Check for junction speed change
282       if (current->entry_speed != entry_speed) {
283         current->entry_speed = entry_speed;
284         current->recalculate_flag = true;
285       }
286     }
287   }
288 }
289
290 // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This 
291 // implements the forward pass.
292 void planner_forward_pass() {
293   uint8_t block_index = block_buffer_tail;
294   block_t *block[3] = { NULL, NULL, NULL };
295
296   while(block_index != block_buffer_head) {
297     block[0] = block[1];
298     block[1] = block[2];
299     block[2] = &block_buffer[block_index];
300     planner_forward_pass_kernel(block[0],block[1],block[2]);
301     block_index = next_block_index(block_index);
302   }
303   planner_forward_pass_kernel(block[1], block[2], NULL);
304 }
305
306 // Recalculates the trapezoid speed profiles for all blocks in the plan according to the 
307 // entry_factor for each junction. Must be called by planner_recalculate() after 
308 // updating the blocks.
309 void planner_recalculate_trapezoids() {
310   int8_t block_index = block_buffer_tail;
311   block_t *current;
312   block_t *next = NULL;
313   
314   while(block_index != block_buffer_head) {
315     current = next;
316     next = &block_buffer[block_index];
317     if (current) {
318       // Recalculate if current block entry or exit junction speed has changed.
319       if (current->recalculate_flag || next->recalculate_flag) {
320         // NOTE: Entry and exit factors always > 0 by all previous logic operations.
321         calculate_trapezoid_for_block(current, current->entry_speed/current->nominal_speed,
322           next->entry_speed/current->nominal_speed);
323         current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed
324       }
325     }
326     block_index = next_block_index( block_index );
327   }
328   // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
329   if(next != NULL) {
330     calculate_trapezoid_for_block(next, next->entry_speed/next->nominal_speed,
331       MINIMUM_PLANNER_SPEED/next->nominal_speed);
332     next->recalculate_flag = false;
333   }
334 }
335
336 // Recalculates the motion plan according to the following algorithm:
337 //
338 //   1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_factor) 
339 //      so that:
340 //     a. The junction jerk is within the set limit
341 //     b. No speed reduction within one block requires faster deceleration than the one, true constant 
342 //        acceleration.
343 //   2. Go over every block in chronological order and dial down junction speed reduction values if 
344 //     a. The speed increase within one block would require faster accelleration than the one, true 
345 //        constant acceleration.
346 //
347 // When these stages are complete all blocks have an entry_factor that will allow all speed changes to 
348 // be performed using only the one, true constant acceleration, and where no junction jerk is jerkier than 
349 // the set limit. Finally it will:
350 //
351 //   3. Recalculate trapezoids for all blocks.
352
353 void planner_recalculate() {   
354   planner_reverse_pass();
355   planner_forward_pass();
356   planner_recalculate_trapezoids();
357 }
358
359 void plan_init() {
360   block_buffer_head = 0;
361   block_buffer_tail = 0;
362   memset(position, 0, sizeof(position)); // clear position
363   previous_speed[0] = 0.0;
364   previous_speed[1] = 0.0;
365   previous_speed[2] = 0.0;
366   previous_speed[3] = 0.0;
367   previous_nominal_speed = 0.0;
368 }
369
370
371
372
373 #ifdef AUTOTEMP
374 void getHighESpeed()
375 {
376   static float oldt=0;
377   if(!autotemp_enabled){
378     return;
379   }
380   if(degTargetHotend0()+2<autotemp_min) {  //probably temperature set to zero.
381     return; //do nothing
382   }
383   
384   float high=0.0;
385   uint8_t block_index = block_buffer_tail;
386   
387   while(block_index != block_buffer_head) {
388     if((block_buffer[block_index].steps_x != 0) ||
389        (block_buffer[block_index].steps_y != 0) ||
390        (block_buffer[block_index].steps_z != 0)) {
391       float se=(float(block_buffer[block_index].steps_e)/float(block_buffer[block_index].step_event_count))*block_buffer[block_index].nominal_speed;
392       //se; mm/sec;
393       if(se>high)
394       {
395         high=se;
396       }
397     }
398     block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
399   }
400    
401   float g=autotemp_min+high*autotemp_factor;
402   float t=g;
403   if(t<autotemp_min)
404     t=autotemp_min;
405   if(t>autotemp_max)
406     t=autotemp_max;
407   if(oldt>t)
408   {
409     t=AUTOTEMP_OLDWEIGHT*oldt+(1-AUTOTEMP_OLDWEIGHT)*t;
410   }
411   oldt=t;
412   setTargetHotend0(t);
413 }
414 #endif
415
416 void check_axes_activity() {
417   unsigned char x_active = 0;
418   unsigned char y_active = 0;  
419   unsigned char z_active = 0;
420   unsigned char e_active = 0;
421   unsigned char fan_speed = 0;
422   unsigned char tail_fan_speed = 0;
423   block_t *block;
424
425   if(block_buffer_tail != block_buffer_head) {
426     uint8_t block_index = block_buffer_tail;
427     tail_fan_speed = block_buffer[block_index].fan_speed;
428     while(block_index != block_buffer_head) {
429       block = &block_buffer[block_index];
430       if(block->steps_x != 0) x_active++;
431       if(block->steps_y != 0) y_active++;
432       if(block->steps_z != 0) z_active++;
433       if(block->steps_e != 0) e_active++;
434       if(block->fan_speed != 0) fan_speed++;
435       block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
436     }
437   }
438   else {
439     #if FAN_PIN > -1
440       if (FanSpeed != 0){
441         analogWrite(FAN_PIN,FanSpeed); // If buffer is empty use current fan speed
442       }
443     #endif
444   }
445   if((DISABLE_X) && (x_active == 0)) disable_x();
446   if((DISABLE_Y) && (y_active == 0)) disable_y();
447   if((DISABLE_Z) && (z_active == 0)) disable_z();
448   if((DISABLE_E) && (e_active == 0)) { disable_e0();disable_e1();disable_e2(); }
449   #if FAN_PIN > -1
450   if((FanSpeed == 0) && (fan_speed ==0)) {
451     analogWrite(FAN_PIN, 0);
452   }
453
454   if (FanSpeed != 0 && tail_fan_speed !=0) { 
455     analogWrite(FAN_PIN,tail_fan_speed);
456   }
457   #endif
458   #ifdef AUTOTEMP
459     getHighESpeed();
460   #endif
461 }
462
463
464 float junction_deviation = 0.1;
465 // Add a new linear movement to the buffer. steps_x, _y and _z is the absolute position in 
466 // mm. Microseconds specify how many microseconds the move should take to perform. To aid acceleration
467 // calculation the caller must also provide the physical length of the line in millimeters.
468 void plan_buffer_line(const float &x, const float &y, const float &z, const float &e, float feed_rate, const uint8_t &extruder)
469 {
470   // Calculate the buffer head after we push this byte
471   int next_buffer_head = next_block_index(block_buffer_head);
472
473   // If the buffer is full: good! That means we are well ahead of the robot. 
474   // Rest here until there is room in the buffer.
475   while(block_buffer_tail == next_buffer_head) { 
476     manage_heater(); 
477     manage_inactivity(1); 
478     LCD_STATUS;
479   }
480   
481   // The target position of the tool in absolute steps
482   // Calculate target position in absolute steps
483   //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
484   long target[4];
485   target[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
486   target[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
487   target[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);     
488   target[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
489   
490   #ifdef PREVENT_DANGEROUS_EXTRUDE
491     if(target[E_AXIS]!=position[E_AXIS])
492     if(degHotend(active_extruder)<EXTRUDE_MINTEMP && !allow_cold_extrude)
493     {
494       position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
495       SERIAL_ECHO_START;
496       SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
497     }
498     #ifdef PREVENT_LENGTHY_EXTRUDE
499     if(labs(target[E_AXIS]-position[E_AXIS])>axis_steps_per_unit[E_AXIS]*EXTRUDE_MAXLENGTH)
500     {
501       position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
502       SERIAL_ECHO_START;
503       SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
504     }
505     #endif
506   #endif
507   
508   // Prepare to set up new block
509   block_t *block = &block_buffer[block_buffer_head];
510   
511   // Mark block as not busy (Not executed by the stepper interrupt)
512   block->busy = false;
513
514   // Number of steps for each axis
515   block->steps_x = labs(target[X_AXIS]-position[X_AXIS]);
516   block->steps_y = labs(target[Y_AXIS]-position[Y_AXIS]);
517   block->steps_z = labs(target[Z_AXIS]-position[Z_AXIS]);
518   block->steps_e = labs(target[E_AXIS]-position[E_AXIS]);
519   block->steps_e *= extrudemultiply;
520   block->steps_e /= 100;
521   block->step_event_count = max(block->steps_x, max(block->steps_y, max(block->steps_z, block->steps_e)));
522
523   // Bail if this is a zero-length block
524   if (block->step_event_count <= dropsegments) { return; };
525
526   block->fan_speed = FanSpeed;
527   
528   // Compute direction bits for this block 
529   block->direction_bits = 0;
530   if (target[X_AXIS] < position[X_AXIS]) { block->direction_bits |= (1<<X_AXIS); }
531   if (target[Y_AXIS] < position[Y_AXIS]) { block->direction_bits |= (1<<Y_AXIS); }
532   if (target[Z_AXIS] < position[Z_AXIS]) { block->direction_bits |= (1<<Z_AXIS); }
533   if (target[E_AXIS] < position[E_AXIS]) { block->direction_bits |= (1<<E_AXIS); }
534   
535   block->active_extruder = extruder;
536   
537   //enable active axes
538   if(block->steps_x != 0) enable_x();
539   if(block->steps_y != 0) enable_y();
540   #ifndef Z_LATE_ENABLE
541     if(block->steps_z != 0) enable_z();
542   #endif
543
544   // Enable all
545   if(block->steps_e != 0) { enable_e0();enable_e1();enable_e2(); }
546
547   if (block->steps_e == 0) {
548         if(feed_rate<mintravelfeedrate) feed_rate=mintravelfeedrate;
549   }
550   else {
551         if(feed_rate<minimumfeedrate) feed_rate=minimumfeedrate;
552   } 
553   
554   float delta_mm[4];
555   delta_mm[X_AXIS] = (target[X_AXIS]-position[X_AXIS])/axis_steps_per_unit[X_AXIS];
556   delta_mm[Y_AXIS] = (target[Y_AXIS]-position[Y_AXIS])/axis_steps_per_unit[Y_AXIS];
557   delta_mm[Z_AXIS] = (target[Z_AXIS]-position[Z_AXIS])/axis_steps_per_unit[Z_AXIS];
558   delta_mm[E_AXIS] = ((target[E_AXIS]-position[E_AXIS])/axis_steps_per_unit[E_AXIS])*extrudemultiply/100.0;
559   if ( block->steps_x <=dropsegments && block->steps_y <=dropsegments && block->steps_z <=dropsegments ) {
560     block->millimeters = fabs(delta_mm[E_AXIS]);
561   } else {
562     block->millimeters = sqrt(square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_AXIS]));
563   }
564   float inverse_millimeters = 1.0/block->millimeters;  // Inverse millimeters to remove multiple divides 
565   
566   // Calculate speed in mm/second for each axis. No divide by zero due to previous checks.
567   float inverse_second = feed_rate * inverse_millimeters;
568   
569   int moves_queued=(block_buffer_head-block_buffer_tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1);
570  
571   // slow down when de buffer starts to empty, rather than wait at the corner for a buffer refill
572   #ifdef OLD_SLOWDOWN
573     if(moves_queued < (BLOCK_BUFFER_SIZE * 0.5) && moves_queued > 1) feed_rate = feed_rate*moves_queued / (BLOCK_BUFFER_SIZE * 0.5); 
574   #endif
575
576   #ifdef SLOWDOWN
577   //  segment time im micro seconds
578   unsigned long segment_time = lround(1000000.0/inverse_second);
579   if ((moves_queued > 1) && (moves_queued < (BLOCK_BUFFER_SIZE * 0.5))) {
580     if (segment_time < minsegmenttime)  { // buffer is draining, add extra time.  The amount of time added increases if the buffer is still emptied more.
581         inverse_second=1000000.0/(segment_time+lround(2*(minsegmenttime-segment_time)/moves_queued));
582     }
583   }
584   #endif
585   //  END OF SLOW DOWN SECTION    
586
587   
588   block->nominal_speed = block->millimeters * inverse_second; // (mm/sec) Always > 0
589   block->nominal_rate = ceil(block->step_event_count * inverse_second); // (step/sec) Always > 0
590
591  // Calculate and limit speed in mm/sec for each axis
592   float current_speed[4];
593   float speed_factor = 1.0; //factor <=1 do decrease speed
594   for(int i=0; i < 4; i++) {
595     current_speed[i] = delta_mm[i] * inverse_second;
596     if(fabs(current_speed[i]) > max_feedrate[i])
597       speed_factor = min(speed_factor, max_feedrate[i] / fabs(current_speed[i]));
598   }
599
600 // Max segement time in us.
601 #ifdef XY_FREQUENCY_LIMIT
602 #define MAX_FREQ_TIME (1000000.0/XY_FREQUENCY_LIMIT)
603
604   // Check and limit the xy direction change frequency
605   unsigned char direction_change = block->direction_bits ^ old_direction_bits;
606   old_direction_bits = block->direction_bits;
607
608   if((direction_change & (1<<X_AXIS)) == 0) {
609      x_segment_time[0] += segment_time;
610   }
611   else {
612     x_segment_time[2] = x_segment_time[1];
613     x_segment_time[1] = x_segment_time[0];
614     x_segment_time[0] = segment_time;
615   }
616   if((direction_change & (1<<Y_AXIS)) == 0) {
617      y_segment_time[0] += segment_time;
618   }
619   else {
620     y_segment_time[2] = y_segment_time[1];
621     y_segment_time[1] = y_segment_time[0];
622     y_segment_time[0] = segment_time;
623   }
624   long max_x_segment_time = max(x_segment_time[0], max(x_segment_time[1], x_segment_time[2]));
625   long max_y_segment_time = max(y_segment_time[0], max(y_segment_time[1], y_segment_time[2]));
626   long min_xy_segment_time =min(max_x_segment_time, max_y_segment_time);
627   if(min_xy_segment_time < MAX_FREQ_TIME) speed_factor = min(speed_factor, speed_factor * (float)min_xy_segment_time / (float)MAX_FREQ_TIME);
628 #endif
629
630   // Correct the speed  
631   if( speed_factor < 1.0) {
632     for(unsigned char i=0; i < 4; i++) {
633       current_speed[i] *= speed_factor;
634     }
635     block->nominal_speed *= speed_factor;
636     block->nominal_rate *= speed_factor;
637   }
638
639   // Compute and limit the acceleration rate for the trapezoid generator.  
640   float steps_per_mm = block->step_event_count/block->millimeters;
641   if(block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0) {
642     block->acceleration_st = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
643   }
644   else {
645     block->acceleration_st = ceil(acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
646     // Limit acceleration per axis
647     if(((float)block->acceleration_st * (float)block->steps_x / (float)block->step_event_count) > axis_steps_per_sqr_second[X_AXIS])
648       block->acceleration_st = axis_steps_per_sqr_second[X_AXIS];
649     if(((float)block->acceleration_st * (float)block->steps_y / (float)block->step_event_count) > axis_steps_per_sqr_second[Y_AXIS])
650       block->acceleration_st = axis_steps_per_sqr_second[Y_AXIS];
651     if(((float)block->acceleration_st * (float)block->steps_e / (float)block->step_event_count) > axis_steps_per_sqr_second[E_AXIS])
652       block->acceleration_st = axis_steps_per_sqr_second[E_AXIS];
653     if(((float)block->acceleration_st * (float)block->steps_z / (float)block->step_event_count ) > axis_steps_per_sqr_second[Z_AXIS])
654       block->acceleration_st = axis_steps_per_sqr_second[Z_AXIS];
655   }
656   block->acceleration = block->acceleration_st / steps_per_mm;
657   block->acceleration_rate = (long)((float)block->acceleration_st * 8.388608);
658   
659 #if 0  // Use old jerk for now
660   // Compute path unit vector
661   double unit_vec[3];
662
663   unit_vec[X_AXIS] = delta_mm[X_AXIS]*inverse_millimeters;
664   unit_vec[Y_AXIS] = delta_mm[Y_AXIS]*inverse_millimeters;
665   unit_vec[Z_AXIS] = delta_mm[Z_AXIS]*inverse_millimeters;
666   
667   // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
668   // Let a circle be tangent to both previous and current path line segments, where the junction
669   // deviation is defined as the distance from the junction to the closest edge of the circle,
670   // colinear with the circle center. The circular segment joining the two paths represents the
671   // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
672   // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
673   // path width or max_jerk in the previous grbl version. This approach does not actually deviate
674   // from path, but used as a robust way to compute cornering speeds, as it takes into account the
675   // nonlinearities of both the junction angle and junction velocity.
676   double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
677
678   // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
679   if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
680     // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
681     // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
682     double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
683                        - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
684                        - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
685                            
686     // Skip and use default max junction speed for 0 degree acute junction.
687     if (cos_theta < 0.95) {
688       vmax_junction = min(previous_nominal_speed,block->nominal_speed);
689       // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
690       if (cos_theta > -0.95) {
691         // Compute maximum junction velocity based on maximum acceleration and junction deviation
692         double sin_theta_d2 = sqrt(0.5*(1.0-cos_theta)); // Trig half angle identity. Always positive.
693         vmax_junction = min(vmax_junction,
694           sqrt(block->acceleration * junction_deviation * sin_theta_d2/(1.0-sin_theta_d2)) );
695       }
696     }
697   }
698 #endif
699   // Start with a safe speed
700   float vmax_junction = max_xy_jerk/2;  
701   if(fabs(current_speed[Z_AXIS]) > max_z_jerk/2) 
702     vmax_junction = max_z_jerk/2;
703   vmax_junction = min(vmax_junction, block->nominal_speed);
704   if(fabs(current_speed[E_AXIS]) > max_e_jerk/2) 
705     vmax_junction = min(vmax_junction, max_e_jerk/2);
706     
707   if ((moves_queued > 1) && (previous_nominal_speed > 0.0001)) {
708     float jerk = sqrt(pow((current_speed[X_AXIS]-previous_speed[X_AXIS]), 2)+pow((current_speed[Y_AXIS]-previous_speed[Y_AXIS]), 2));
709     if((fabs(previous_speed[X_AXIS]) > 0.0001) || (fabs(previous_speed[Y_AXIS]) > 0.0001)) {
710       vmax_junction = block->nominal_speed;
711     }
712     if (jerk > max_xy_jerk) {
713       vmax_junction *= (max_xy_jerk/jerk);
714     } 
715     if(fabs(current_speed[Z_AXIS] - previous_speed[Z_AXIS]) > max_z_jerk) {
716       vmax_junction *= (max_z_jerk/fabs(current_speed[Z_AXIS] - previous_speed[Z_AXIS]));
717     } 
718     if(fabs(current_speed[E_AXIS] - previous_speed[E_AXIS]) > max_e_jerk) {
719       vmax_junction *= (max_e_jerk/fabs(current_speed[E_AXIS] - previous_speed[E_AXIS]));
720     } 
721   }
722   block->max_entry_speed = vmax_junction;
723     
724   // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
725   double v_allowable = max_allowable_speed(-block->acceleration,MINIMUM_PLANNER_SPEED,block->millimeters);
726   block->entry_speed = min(vmax_junction, v_allowable);
727
728   // Initialize planner efficiency flags
729   // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
730   // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
731   // the current block and next block junction speeds are guaranteed to always be at their maximum
732   // junction speeds in deceleration and acceleration, respectively. This is due to how the current
733   // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
734   // the reverse and forward planners, the corresponding block junction speed will always be at the
735   // the maximum junction speed and may always be ignored for any speed reduction checks.
736   if (block->nominal_speed <= v_allowable) { block->nominal_length_flag = true; }
737   else { block->nominal_length_flag = false; }
738   block->recalculate_flag = true; // Always calculate trapezoid for new block
739   
740   // Update previous path unit_vector and nominal speed
741   memcpy(previous_speed, current_speed, sizeof(previous_speed)); // previous_speed[] = current_speed[]
742   previous_nominal_speed = block->nominal_speed;
743
744   
745   #ifdef ADVANCE
746     // Calculate advance rate
747     if((block->steps_e == 0) || (block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0)) {
748       block->advance_rate = 0;
749       block->advance = 0;
750     }
751     else {
752       long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_st);
753       float advance = (STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K) * 
754         (current_speed[E_AXIS] * current_speed[E_AXIS] * EXTRUTION_AREA * EXTRUTION_AREA)*256;
755       block->advance = advance;
756       if(acc_dist == 0) {
757         block->advance_rate = 0;
758       } 
759       else {
760         block->advance_rate = advance / (float)acc_dist;
761       }
762     }
763     /*
764     SERIAL_ECHO_START;
765     SERIAL_ECHOPGM("advance :");
766     SERIAL_ECHO(block->advance/256.0);
767     SERIAL_ECHOPGM("advance rate :");
768     SERIAL_ECHOLN(block->advance_rate/256.0);
769     */
770   #endif // ADVANCE
771
772   calculate_trapezoid_for_block(block, block->entry_speed/block->nominal_speed,
773     MINIMUM_PLANNER_SPEED/block->nominal_speed);
774     
775   // Move buffer head
776   block_buffer_head = next_buffer_head;
777   
778   // Update position
779   memcpy(position, target, sizeof(target)); // position[] = target[]
780
781   planner_recalculate();
782
783   st_wake_up();
784 }
785
786 void plan_set_position(const float &x, const float &y, const float &z, const float &e)
787 {
788   position[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
789   position[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
790   position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);     
791   position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);  
792   st_set_position(position[X_AXIS], position[Y_AXIS], position[Z_AXIS], position[E_AXIS]);
793   previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
794   previous_speed[0] = 0.0;
795   previous_speed[1] = 0.0;
796   previous_speed[2] = 0.0;
797   previous_speed[3] = 0.0;
798 }
799
800 void plan_set_e_position(const float &e)
801 {
802   position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);  
803   st_set_e_position(position[E_AXIS]);
804 }
805
806 uint8_t movesplanned()
807 {
808  return (block_buffer_head-block_buffer_tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1);
809 }
810
811 void allow_cold_extrudes(bool allow)
812 {
813   #ifdef PREVENT_DANGEROUS_EXTRUDE
814     allow_cold_extrude=allow;
815   #endif
816 }