My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

planner.cpp 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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. * planner.cpp
  24. *
  25. * Buffer movement commands and manage the acceleration profile plan
  26. *
  27. * Derived from Grbl
  28. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  29. *
  30. * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
  31. *
  32. *
  33. * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  34. *
  35. * s == speed, a == acceleration, t == time, d == distance
  36. *
  37. * Basic definitions:
  38. * Speed[s_, a_, t_] := s + (a*t)
  39. * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  40. *
  41. * Distance to reach a specific speed with a constant acceleration:
  42. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  43. * d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  44. *
  45. * Speed after a given distance of travel with constant acceleration:
  46. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  47. * m -> Sqrt[2 a d + s^2]
  48. *
  49. * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  50. *
  51. * When to start braking (di) to reach a specified destination speed (s2) after accelerating
  52. * from initial speed s1 without ever stopping at a plateau:
  53. * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  54. * di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  55. *
  56. * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  57. *
  58. */
  59. #include "Marlin.h"
  60. #include "planner.h"
  61. #include "stepper.h"
  62. #include "temperature.h"
  63. #include "ultralcd.h"
  64. #include "language.h"
  65. #if ENABLED(MESH_BED_LEVELING)
  66. #include "mesh_bed_leveling.h"
  67. #endif
  68. Planner planner;
  69. // public:
  70. /**
  71. * A ring buffer of moves described in steps
  72. */
  73. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  74. volatile uint8_t Planner::block_buffer_head = 0; // Index of the next block to be pushed
  75. volatile uint8_t Planner::block_buffer_tail = 0;
  76. float Planner::max_feedrate[NUM_AXIS]; // Max speeds in mm per second
  77. float Planner::axis_steps_per_mm[NUM_AXIS];
  78. unsigned long Planner::max_acceleration_steps_per_s2[NUM_AXIS];
  79. unsigned long Planner::max_acceleration_mm_per_s2[NUM_AXIS]; // Use M201 to override by software
  80. millis_t Planner::min_segment_time;
  81. float Planner::min_feedrate;
  82. float Planner::acceleration; // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  83. float Planner::retract_acceleration; // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  84. float Planner::travel_acceleration; // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  85. float Planner::max_xy_jerk; // The largest speed change requiring no acceleration
  86. float Planner::max_z_jerk;
  87. float Planner::max_e_jerk;
  88. float Planner::min_travel_feedrate;
  89. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  90. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  91. #endif
  92. #if ENABLED(AUTOTEMP)
  93. float Planner::autotemp_max = 250;
  94. float Planner::autotemp_min = 210;
  95. float Planner::autotemp_factor = 0.1;
  96. bool Planner::autotemp_enabled = false;
  97. #endif
  98. // private:
  99. long Planner::position[NUM_AXIS] = { 0 };
  100. float Planner::previous_speed[NUM_AXIS];
  101. float Planner::previous_nominal_speed;
  102. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  103. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  104. #endif // DISABLE_INACTIVE_EXTRUDER
  105. #ifdef XY_FREQUENCY_LIMIT
  106. // Old direction bits. Used for speed calculations
  107. unsigned char Planner::old_direction_bits = 0;
  108. // Segment times (in µs). Used for speed calculations
  109. long Planner::axis_segment_time[2][3] = { {MAX_FREQ_TIME + 1, 0, 0}, {MAX_FREQ_TIME + 1, 0, 0} };
  110. #endif
  111. /**
  112. * Class and Instance Methods
  113. */
  114. Planner::Planner() { init(); }
  115. void Planner::init() {
  116. block_buffer_head = block_buffer_tail = 0;
  117. memset(position, 0, sizeof(position)); // clear position
  118. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = 0.0;
  119. previous_nominal_speed = 0.0;
  120. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  121. bed_level_matrix.set_to_identity();
  122. #endif
  123. }
  124. /**
  125. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  126. * by the provided factors.
  127. */
  128. void Planner::calculate_trapezoid_for_block(block_t* block, float entry_factor, float exit_factor) {
  129. unsigned long initial_rate = ceil(block->nominal_rate * entry_factor),
  130. final_rate = ceil(block->nominal_rate * exit_factor); // (steps per second)
  131. // Limit minimal step rate (Otherwise the timer will overflow.)
  132. NOLESS(initial_rate, 120);
  133. NOLESS(final_rate, 120);
  134. long accel = block->acceleration_steps_per_s2;
  135. int32_t accelerate_steps = ceil(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel));
  136. int32_t decelerate_steps = floor(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
  137. // Calculate the size of Plateau of Nominal Rate.
  138. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  139. // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
  140. // have to use intersection_distance() to calculate when to abort accel and start braking
  141. // in order to reach the final_rate exactly at the end of this block.
  142. if (plateau_steps < 0) {
  143. accelerate_steps = ceil(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  144. accelerate_steps = max(accelerate_steps, 0); // Check limits due to numerical round-off
  145. accelerate_steps = min((uint32_t)accelerate_steps, block->step_event_count);//(We can cast here to unsigned, because the above line ensures that we are above zero)
  146. plateau_steps = 0;
  147. }
  148. #if ENABLED(ADVANCE)
  149. volatile long initial_advance = block->advance * entry_factor * entry_factor;
  150. volatile long final_advance = block->advance * exit_factor * exit_factor;
  151. #endif // ADVANCE
  152. // block->accelerate_until = accelerate_steps;
  153. // block->decelerate_after = accelerate_steps+plateau_steps;
  154. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  155. if (!block->busy) { // Don't update variables if block is busy.
  156. block->accelerate_until = accelerate_steps;
  157. block->decelerate_after = accelerate_steps + plateau_steps;
  158. block->initial_rate = initial_rate;
  159. block->final_rate = final_rate;
  160. #if ENABLED(ADVANCE)
  161. block->initial_advance = initial_advance;
  162. block->final_advance = final_advance;
  163. #endif
  164. }
  165. CRITICAL_SECTION_END;
  166. }
  167. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  168. // This method will calculate the junction jerk as the euclidean distance between the nominal
  169. // velocities of the respective blocks.
  170. //inline float junction_jerk(block_t *before, block_t *after) {
  171. // return sqrt(
  172. // pow((before->speed_x-after->speed_x), 2)+pow((before->speed_y-after->speed_y), 2));
  173. //}
  174. // The kernel called by recalculate() when scanning the plan from last to first entry.
  175. void Planner::reverse_pass_kernel(block_t* previous, block_t* current, block_t* next) {
  176. if (!current) return;
  177. UNUSED(previous);
  178. if (next) {
  179. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  180. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  181. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  182. float max_entry_speed = current->max_entry_speed;
  183. if (current->entry_speed != max_entry_speed) {
  184. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  185. // for max allowable speed if block is decelerating and nominal length is false.
  186. if (!current->nominal_length_flag && max_entry_speed > next->entry_speed) {
  187. current->entry_speed = min(max_entry_speed,
  188. max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  189. }
  190. else {
  191. current->entry_speed = max_entry_speed;
  192. }
  193. current->recalculate_flag = true;
  194. }
  195. } // Skip last block. Already initialized and set for recalculation.
  196. }
  197. /**
  198. * recalculate() needs to go over the current plan twice.
  199. * Once in reverse and once forward. This implements the reverse pass.
  200. */
  201. void Planner::reverse_pass() {
  202. if (movesplanned() > 3) {
  203. block_t* block[3] = { NULL, NULL, NULL };
  204. // Make a local copy of block_buffer_tail, because the interrupt can alter it
  205. CRITICAL_SECTION_START;
  206. uint8_t tail = block_buffer_tail;
  207. CRITICAL_SECTION_END
  208. uint8_t b = BLOCK_MOD(block_buffer_head - 3);
  209. while (b != tail) {
  210. b = prev_block_index(b);
  211. block[2] = block[1];
  212. block[1] = block[0];
  213. block[0] = &block_buffer[b];
  214. reverse_pass_kernel(block[0], block[1], block[2]);
  215. }
  216. }
  217. }
  218. // The kernel called by recalculate() when scanning the plan from first to last entry.
  219. void Planner::forward_pass_kernel(block_t* previous, block_t* current, block_t* next) {
  220. if (!previous) return;
  221. UNUSED(next);
  222. // If the previous block is an acceleration block, but it is not long enough to complete the
  223. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  224. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  225. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  226. if (!previous->nominal_length_flag) {
  227. if (previous->entry_speed < current->entry_speed) {
  228. double entry_speed = min(current->entry_speed,
  229. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  230. // Check for junction speed change
  231. if (current->entry_speed != entry_speed) {
  232. current->entry_speed = entry_speed;
  233. current->recalculate_flag = true;
  234. }
  235. }
  236. }
  237. }
  238. /**
  239. * recalculate() needs to go over the current plan twice.
  240. * Once in reverse and once forward. This implements the forward pass.
  241. */
  242. void Planner::forward_pass() {
  243. block_t* block[3] = { NULL, NULL, NULL };
  244. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  245. block[0] = block[1];
  246. block[1] = block[2];
  247. block[2] = &block_buffer[b];
  248. forward_pass_kernel(block[0], block[1], block[2]);
  249. }
  250. forward_pass_kernel(block[1], block[2], NULL);
  251. }
  252. /**
  253. * Recalculate the trapezoid speed profiles for all blocks in the plan
  254. * according to the entry_factor for each junction. Must be called by
  255. * recalculate() after updating the blocks.
  256. */
  257. void Planner::recalculate_trapezoids() {
  258. int8_t block_index = block_buffer_tail;
  259. block_t* current;
  260. block_t* next = NULL;
  261. while (block_index != block_buffer_head) {
  262. current = next;
  263. next = &block_buffer[block_index];
  264. if (current) {
  265. // Recalculate if current block entry or exit junction speed has changed.
  266. if (current->recalculate_flag || next->recalculate_flag) {
  267. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  268. float nom = current->nominal_speed;
  269. calculate_trapezoid_for_block(current, current->entry_speed / nom, next->entry_speed / nom);
  270. current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed
  271. }
  272. }
  273. block_index = next_block_index(block_index);
  274. }
  275. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  276. if (next) {
  277. float nom = next->nominal_speed;
  278. calculate_trapezoid_for_block(next, next->entry_speed / nom, (MINIMUM_PLANNER_SPEED) / nom);
  279. next->recalculate_flag = false;
  280. }
  281. }
  282. /*
  283. * Recalculate the motion plan according to the following algorithm:
  284. *
  285. * 1. Go over every block in reverse order...
  286. *
  287. * Calculate a junction speed reduction (block_t.entry_factor) so:
  288. *
  289. * a. The junction jerk is within the set limit, and
  290. *
  291. * b. No speed reduction within one block requires faster
  292. * deceleration than the one, true constant acceleration.
  293. *
  294. * 2. Go over every block in chronological order...
  295. *
  296. * Dial down junction speed reduction values if:
  297. * a. The speed increase within one block would require faster
  298. * acceleration than the one, true constant acceleration.
  299. *
  300. * After that, all blocks will have an entry_factor allowing all speed changes to
  301. * be performed using only the one, true constant acceleration, and where no junction
  302. * jerk is jerkier than the set limit, Jerky. Finally it will:
  303. *
  304. * 3. Recalculate "trapezoids" for all blocks.
  305. */
  306. void Planner::recalculate() {
  307. reverse_pass();
  308. forward_pass();
  309. recalculate_trapezoids();
  310. }
  311. #if ENABLED(AUTOTEMP)
  312. void Planner::getHighESpeed() {
  313. static float oldt = 0;
  314. if (!autotemp_enabled) return;
  315. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  316. float high = 0.0;
  317. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  318. block_t* block = &block_buffer[b];
  319. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  320. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  321. NOLESS(high, se);
  322. }
  323. }
  324. float t = autotemp_min + high * autotemp_factor;
  325. t = constrain(t, autotemp_min, autotemp_max);
  326. if (oldt > t) {
  327. t *= (1 - (AUTOTEMP_OLDWEIGHT));
  328. t += (AUTOTEMP_OLDWEIGHT) * oldt;
  329. }
  330. oldt = t;
  331. thermalManager.setTargetHotend(t, 0);
  332. }
  333. #endif //AUTOTEMP
  334. /**
  335. * Maintain fans, paste extruder pressure,
  336. */
  337. void Planner::check_axes_activity() {
  338. unsigned char axis_active[NUM_AXIS] = { 0 },
  339. tail_fan_speed[FAN_COUNT];
  340. #if FAN_COUNT > 0
  341. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  342. #endif
  343. #if ENABLED(BARICUDA)
  344. unsigned char tail_valve_pressure = baricuda_valve_pressure,
  345. tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  346. #endif
  347. if (blocks_queued()) {
  348. #if FAN_COUNT > 0
  349. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
  350. #endif
  351. block_t* block;
  352. #if ENABLED(BARICUDA)
  353. block = &block_buffer[block_buffer_tail];
  354. tail_valve_pressure = block->valve_pressure;
  355. tail_e_to_p_pressure = block->e_to_p_pressure;
  356. #endif
  357. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  358. block = &block_buffer[b];
  359. for (int i = 0; i < NUM_AXIS; i++) if (block->steps[i]) axis_active[i]++;
  360. }
  361. }
  362. #if ENABLED(DISABLE_X)
  363. if (!axis_active[X_AXIS]) disable_x();
  364. #endif
  365. #if ENABLED(DISABLE_Y)
  366. if (!axis_active[Y_AXIS]) disable_y();
  367. #endif
  368. #if ENABLED(DISABLE_Z)
  369. if (!axis_active[Z_AXIS]) disable_z();
  370. #endif
  371. #if ENABLED(DISABLE_E)
  372. if (!axis_active[E_AXIS]) {
  373. disable_e0();
  374. disable_e1();
  375. disable_e2();
  376. disable_e3();
  377. }
  378. #endif
  379. #if FAN_COUNT > 0
  380. #if defined(FAN_MIN_PWM)
  381. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  382. #else
  383. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  384. #endif
  385. #ifdef FAN_KICKSTART_TIME
  386. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  387. #define KICKSTART_FAN(f) \
  388. if (tail_fan_speed[f]) { \
  389. millis_t ms = millis(); \
  390. if (fan_kick_end[f] == 0) { \
  391. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  392. tail_fan_speed[f] = 255; \
  393. } else { \
  394. if (PENDING(ms, fan_kick_end[f])) { \
  395. tail_fan_speed[f] = 255; \
  396. } \
  397. } \
  398. } else { \
  399. fan_kick_end[f] = 0; \
  400. }
  401. #if HAS_FAN0
  402. KICKSTART_FAN(0);
  403. #endif
  404. #if HAS_FAN1
  405. KICKSTART_FAN(1);
  406. #endif
  407. #if HAS_FAN2
  408. KICKSTART_FAN(2);
  409. #endif
  410. #endif //FAN_KICKSTART_TIME
  411. #if ENABLED(FAN_SOFT_PWM)
  412. #if HAS_FAN0
  413. thermalManager.fanSpeedSoftPwm[0] = CALC_FAN_SPEED(0);
  414. #endif
  415. #if HAS_FAN1
  416. thermalManager.fanSpeedSoftPwm[1] = CALC_FAN_SPEED(1);
  417. #endif
  418. #if HAS_FAN2
  419. thermalManager.fanSpeedSoftPwm[2] = CALC_FAN_SPEED(2);
  420. #endif
  421. #else
  422. #if HAS_FAN0
  423. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  424. #endif
  425. #if HAS_FAN1
  426. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  427. #endif
  428. #if HAS_FAN2
  429. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  430. #endif
  431. #endif
  432. #endif // FAN_COUNT > 0
  433. #if ENABLED(AUTOTEMP)
  434. getHighESpeed();
  435. #endif
  436. #if ENABLED(BARICUDA)
  437. #if HAS_HEATER_1
  438. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  439. #endif
  440. #if HAS_HEATER_2
  441. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  442. #endif
  443. #endif
  444. }
  445. /**
  446. * Planner::buffer_line
  447. *
  448. * Add a new linear movement to the buffer.
  449. *
  450. * x,y,z,e - target position in mm
  451. * feed_rate - (target) speed of the move
  452. * extruder - target extruder
  453. */
  454. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  455. void Planner::buffer_line(float x, float y, float z, const float& e, float feed_rate, const uint8_t extruder)
  456. #else
  457. void Planner::buffer_line(const float& x, const float& y, const float& z, const float& e, float feed_rate, const uint8_t extruder)
  458. #endif // AUTO_BED_LEVELING_FEATURE
  459. {
  460. // Calculate the buffer head after we push this byte
  461. int next_buffer_head = next_block_index(block_buffer_head);
  462. // If the buffer is full: good! That means we are well ahead of the robot.
  463. // Rest here until there is room in the buffer.
  464. while (block_buffer_tail == next_buffer_head) idle();
  465. #if ENABLED(MESH_BED_LEVELING)
  466. if (mbl.active())
  467. z += mbl.get_z(x - home_offset[X_AXIS], y - home_offset[Y_AXIS]);
  468. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  469. apply_rotation_xyz(bed_level_matrix, x, y, z);
  470. #endif
  471. // The target position of the tool in absolute steps
  472. // Calculate target position in absolute steps
  473. //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
  474. long target[NUM_AXIS] = {
  475. lround(x * axis_steps_per_mm[X_AXIS]),
  476. lround(y * axis_steps_per_mm[Y_AXIS]),
  477. lround(z * axis_steps_per_mm[Z_AXIS]),
  478. lround(e * axis_steps_per_mm[E_AXIS])
  479. };
  480. long dx = target[X_AXIS] - position[X_AXIS],
  481. dy = target[Y_AXIS] - position[Y_AXIS],
  482. dz = target[Z_AXIS] - position[Z_AXIS];
  483. // DRYRUN ignores all temperature constraints and assures that the extruder is instantly satisfied
  484. if (DEBUGGING(DRYRUN))
  485. position[E_AXIS] = target[E_AXIS];
  486. long de = target[E_AXIS] - position[E_AXIS];
  487. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  488. if (de) {
  489. if (thermalManager.tooColdToExtrude(extruder)) {
  490. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  491. de = 0; // no difference
  492. SERIAL_ECHO_START;
  493. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  494. }
  495. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  496. if (labs(de) > axis_steps_per_mm[E_AXIS] * (EXTRUDE_MAXLENGTH)) {
  497. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  498. de = 0; // no difference
  499. SERIAL_ECHO_START;
  500. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  501. }
  502. #endif
  503. }
  504. #endif
  505. // Prepare to set up new block
  506. block_t* block = &block_buffer[block_buffer_head];
  507. // Mark block as not busy (Not executed by the stepper interrupt)
  508. block->busy = false;
  509. // Number of steps for each axis
  510. #if ENABLED(COREXY)
  511. // corexy planning
  512. // these equations follow the form of the dA and dB equations on http://www.corexy.com/theory.html
  513. block->steps[A_AXIS] = labs(dx + dy);
  514. block->steps[B_AXIS] = labs(dx - dy);
  515. block->steps[Z_AXIS] = labs(dz);
  516. #elif ENABLED(COREXZ)
  517. // corexz planning
  518. block->steps[A_AXIS] = labs(dx + dz);
  519. block->steps[Y_AXIS] = labs(dy);
  520. block->steps[C_AXIS] = labs(dx - dz);
  521. #elif ENABLED(COREYZ)
  522. // coreyz planning
  523. block->steps[X_AXIS] = labs(dx);
  524. block->steps[B_AXIS] = labs(dy + dz);
  525. block->steps[C_AXIS] = labs(dy - dz);
  526. #else
  527. // default non-h-bot planning
  528. block->steps[X_AXIS] = labs(dx);
  529. block->steps[Y_AXIS] = labs(dy);
  530. block->steps[Z_AXIS] = labs(dz);
  531. #endif
  532. block->steps[E_AXIS] = labs(de);
  533. block->steps[E_AXIS] *= volumetric_multiplier[extruder];
  534. block->steps[E_AXIS] *= extruder_multiplier[extruder];
  535. block->steps[E_AXIS] /= 100;
  536. block->step_event_count = max(block->steps[X_AXIS], max(block->steps[Y_AXIS], max(block->steps[Z_AXIS], block->steps[E_AXIS])));
  537. // Bail if this is a zero-length block
  538. if (block->step_event_count <= dropsegments) return;
  539. #if FAN_COUNT > 0
  540. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  541. #endif
  542. #if ENABLED(BARICUDA)
  543. block->valve_pressure = baricuda_valve_pressure;
  544. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  545. #endif
  546. // Compute direction bits for this block
  547. uint8_t db = 0;
  548. #if ENABLED(COREXY)
  549. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  550. if (dy < 0) SBI(db, Y_HEAD); // ...and Y
  551. if (dz < 0) SBI(db, Z_AXIS);
  552. if (dx + dy < 0) SBI(db, A_AXIS); // Motor A direction
  553. if (dx - dy < 0) SBI(db, B_AXIS); // Motor B direction
  554. #elif ENABLED(COREXZ)
  555. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  556. if (dy < 0) SBI(db, Y_AXIS);
  557. if (dz < 0) SBI(db, Z_HEAD); // ...and Z
  558. if (dx + dz < 0) SBI(db, A_AXIS); // Motor A direction
  559. if (dx - dz < 0) SBI(db, C_AXIS); // Motor C direction
  560. #elif ENABLED(COREYZ)
  561. if (dx < 0) SBI(db, X_AXIS);
  562. if (dy < 0) SBI(db, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  563. if (dz < 0) SBI(db, Z_HEAD); // ...and Z
  564. if (dy + dz < 0) SBI(db, B_AXIS); // Motor B direction
  565. if (dy - dz < 0) SBI(db, C_AXIS); // Motor C direction
  566. #else
  567. if (dx < 0) SBI(db, X_AXIS);
  568. if (dy < 0) SBI(db, Y_AXIS);
  569. if (dz < 0) SBI(db, Z_AXIS);
  570. #endif
  571. if (de < 0) SBI(db, E_AXIS);
  572. block->direction_bits = db;
  573. block->active_extruder = extruder;
  574. //enable active axes
  575. #if ENABLED(COREXY)
  576. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  577. enable_x();
  578. enable_y();
  579. }
  580. #if DISABLED(Z_LATE_ENABLE)
  581. if (block->steps[Z_AXIS]) enable_z();
  582. #endif
  583. #elif ENABLED(COREXZ)
  584. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  585. enable_x();
  586. enable_z();
  587. }
  588. if (block->steps[Y_AXIS]) enable_y();
  589. #else
  590. if (block->steps[X_AXIS]) enable_x();
  591. if (block->steps[Y_AXIS]) enable_y();
  592. #if DISABLED(Z_LATE_ENABLE)
  593. if (block->steps[Z_AXIS]) enable_z();
  594. #endif
  595. #endif
  596. // Enable extruder(s)
  597. if (block->steps[E_AXIS]) {
  598. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  599. for (int i = 0; i < EXTRUDERS; i++)
  600. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  601. switch(extruder) {
  602. case 0:
  603. enable_e0();
  604. #if ENABLED(DUAL_X_CARRIAGE)
  605. if (extruder_duplication_enabled) {
  606. enable_e1();
  607. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  608. }
  609. #endif
  610. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  611. #if EXTRUDERS > 1
  612. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  613. #if EXTRUDERS > 2
  614. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  615. #if EXTRUDERS > 3
  616. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  617. #endif
  618. #endif
  619. #endif
  620. break;
  621. #if EXTRUDERS > 1
  622. case 1:
  623. enable_e1();
  624. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  625. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  626. #if EXTRUDERS > 2
  627. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  628. #if EXTRUDERS > 3
  629. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  630. #endif
  631. #endif
  632. break;
  633. #if EXTRUDERS > 2
  634. case 2:
  635. enable_e2();
  636. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  637. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  638. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  639. #if EXTRUDERS > 3
  640. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  641. #endif
  642. break;
  643. #if EXTRUDERS > 3
  644. case 3:
  645. enable_e3();
  646. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  647. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  648. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  649. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  650. break;
  651. #endif // EXTRUDERS > 3
  652. #endif // EXTRUDERS > 2
  653. #endif // EXTRUDERS > 1
  654. }
  655. #else
  656. enable_e0();
  657. enable_e1();
  658. enable_e2();
  659. enable_e3();
  660. #endif
  661. }
  662. if (block->steps[E_AXIS])
  663. NOLESS(feed_rate, min_feedrate);
  664. else
  665. NOLESS(feed_rate, min_travel_feedrate);
  666. /**
  667. * This part of the code calculates the total length of the movement.
  668. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  669. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  670. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  671. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  672. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  673. */
  674. #if ENABLED(COREXY) || ENABLED(COREXZ) || ENABLED(COREYZ)
  675. float delta_mm[6];
  676. #if ENABLED(COREXY)
  677. delta_mm[X_HEAD] = dx / axis_steps_per_mm[A_AXIS];
  678. delta_mm[Y_HEAD] = dy / axis_steps_per_mm[B_AXIS];
  679. delta_mm[Z_AXIS] = dz / axis_steps_per_mm[Z_AXIS];
  680. delta_mm[A_AXIS] = (dx + dy) / axis_steps_per_mm[A_AXIS];
  681. delta_mm[B_AXIS] = (dx - dy) / axis_steps_per_mm[B_AXIS];
  682. #elif ENABLED(COREXZ)
  683. delta_mm[X_HEAD] = dx / axis_steps_per_mm[A_AXIS];
  684. delta_mm[Y_AXIS] = dy / axis_steps_per_mm[Y_AXIS];
  685. delta_mm[Z_HEAD] = dz / axis_steps_per_mm[C_AXIS];
  686. delta_mm[A_AXIS] = (dx + dz) / axis_steps_per_mm[A_AXIS];
  687. delta_mm[C_AXIS] = (dx - dz) / axis_steps_per_mm[C_AXIS];
  688. #elif ENABLED(COREYZ)
  689. delta_mm[X_AXIS] = dx / axis_steps_per_mm[A_AXIS];
  690. delta_mm[Y_HEAD] = dy / axis_steps_per_mm[Y_AXIS];
  691. delta_mm[Z_HEAD] = dz / axis_steps_per_mm[C_AXIS];
  692. delta_mm[B_AXIS] = (dy + dz) / axis_steps_per_mm[B_AXIS];
  693. delta_mm[C_AXIS] = (dy - dz) / axis_steps_per_mm[C_AXIS];
  694. #endif
  695. #else
  696. float delta_mm[4];
  697. delta_mm[X_AXIS] = dx / axis_steps_per_mm[X_AXIS];
  698. delta_mm[Y_AXIS] = dy / axis_steps_per_mm[Y_AXIS];
  699. delta_mm[Z_AXIS] = dz / axis_steps_per_mm[Z_AXIS];
  700. #endif
  701. delta_mm[E_AXIS] = (de / axis_steps_per_mm[E_AXIS]) * volumetric_multiplier[extruder] * extruder_multiplier[extruder] / 100.0;
  702. if (block->steps[X_AXIS] <= dropsegments && block->steps[Y_AXIS] <= dropsegments && block->steps[Z_AXIS] <= dropsegments) {
  703. block->millimeters = fabs(delta_mm[E_AXIS]);
  704. }
  705. else {
  706. block->millimeters = sqrt(
  707. #if ENABLED(COREXY)
  708. square(delta_mm[X_HEAD]) + square(delta_mm[Y_HEAD]) + square(delta_mm[Z_AXIS])
  709. #elif ENABLED(COREXZ)
  710. square(delta_mm[X_HEAD]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_HEAD])
  711. #elif ENABLED(COREYZ)
  712. square(delta_mm[X_AXIS]) + square(delta_mm[Y_HEAD]) + square(delta_mm[Z_HEAD])
  713. #else
  714. square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_AXIS])
  715. #endif
  716. );
  717. }
  718. float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  719. // Calculate moves/second for this move. No divide by zero due to previous checks.
  720. float inverse_second = feed_rate * inverse_millimeters;
  721. int moves_queued = movesplanned();
  722. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  723. #if ENABLED(OLD_SLOWDOWN) || ENABLED(SLOWDOWN)
  724. bool mq = moves_queued > 1 && moves_queued < (BLOCK_BUFFER_SIZE) / 2;
  725. #if ENABLED(OLD_SLOWDOWN)
  726. if (mq) feed_rate *= 2.0 * moves_queued / (BLOCK_BUFFER_SIZE);
  727. #endif
  728. #if ENABLED(SLOWDOWN)
  729. // segment time im micro seconds
  730. unsigned long segment_time = lround(1000000.0/inverse_second);
  731. if (mq) {
  732. if (segment_time < min_segment_time) {
  733. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  734. inverse_second = 1000000.0 / (segment_time + lround(2 * (min_segment_time - segment_time) / moves_queued));
  735. #ifdef XY_FREQUENCY_LIMIT
  736. segment_time = lround(1000000.0 / inverse_second);
  737. #endif
  738. }
  739. }
  740. #endif
  741. #endif
  742. block->nominal_speed = block->millimeters * inverse_second; // (mm/sec) Always > 0
  743. block->nominal_rate = ceil(block->step_event_count * inverse_second); // (step/sec) Always > 0
  744. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  745. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  746. //FMM update ring buffer used for delay with filament measurements
  747. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index2 >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  748. const int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  749. // increment counters with next move in e axis
  750. filwidth_e_count += delta_mm[E_AXIS];
  751. filwidth_delay_dist += delta_mm[E_AXIS];
  752. // Only get new measurements on forward E movement
  753. if (filwidth_e_count > 0.0001) {
  754. // Loop the delay distance counter (modulus by the mm length)
  755. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  756. // Convert into an index into the measurement array
  757. filwidth_delay_index1 = (int)(filwidth_delay_dist / 10.0 + 0.0001);
  758. // If the index has changed (must have gone forward)...
  759. if (filwidth_delay_index1 != filwidth_delay_index2) {
  760. filwidth_e_count = 0; // Reset the E movement counter
  761. int8_t meas_sample = thermalManager.widthFil_to_size_ratio() - 100; // Subtract 100 to reduce magnitude - to store in a signed char
  762. do {
  763. filwidth_delay_index2 = (filwidth_delay_index2 + 1) % MMD_CM; // The next unused slot
  764. measurement_delay[filwidth_delay_index2] = meas_sample; // Store the measurement
  765. } while (filwidth_delay_index1 != filwidth_delay_index2); // More slots to fill?
  766. }
  767. }
  768. }
  769. #endif
  770. // Calculate and limit speed in mm/sec for each axis
  771. float current_speed[NUM_AXIS];
  772. float speed_factor = 1.0; //factor <=1 do decrease speed
  773. for (int i = 0; i < NUM_AXIS; i++) {
  774. current_speed[i] = delta_mm[i] * inverse_second;
  775. float cs = fabs(current_speed[i]), mf = max_feedrate[i];
  776. if (cs > mf) speed_factor = min(speed_factor, mf / cs);
  777. }
  778. // Max segement time in us.
  779. #ifdef XY_FREQUENCY_LIMIT
  780. // Check and limit the xy direction change frequency
  781. unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  782. old_direction_bits = block->direction_bits;
  783. segment_time = lround((float)segment_time / speed_factor);
  784. long xs0 = axis_segment_time[X_AXIS][0],
  785. xs1 = axis_segment_time[X_AXIS][1],
  786. xs2 = axis_segment_time[X_AXIS][2],
  787. ys0 = axis_segment_time[Y_AXIS][0],
  788. ys1 = axis_segment_time[Y_AXIS][1],
  789. ys2 = axis_segment_time[Y_AXIS][2];
  790. if (TEST(direction_change, X_AXIS)) {
  791. xs2 = axis_segment_time[X_AXIS][2] = xs1;
  792. xs1 = axis_segment_time[X_AXIS][1] = xs0;
  793. xs0 = 0;
  794. }
  795. xs0 = axis_segment_time[X_AXIS][0] = xs0 + segment_time;
  796. if (TEST(direction_change, Y_AXIS)) {
  797. ys2 = axis_segment_time[Y_AXIS][2] = axis_segment_time[Y_AXIS][1];
  798. ys1 = axis_segment_time[Y_AXIS][1] = axis_segment_time[Y_AXIS][0];
  799. ys0 = 0;
  800. }
  801. ys0 = axis_segment_time[Y_AXIS][0] = ys0 + segment_time;
  802. long max_x_segment_time = max(xs0, max(xs1, xs2)),
  803. max_y_segment_time = max(ys0, max(ys1, ys2)),
  804. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  805. if (min_xy_segment_time < MAX_FREQ_TIME) {
  806. float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME);
  807. speed_factor = min(speed_factor, low_sf);
  808. }
  809. #endif // XY_FREQUENCY_LIMIT
  810. // Correct the speed
  811. if (speed_factor < 1.0) {
  812. for (unsigned char i = 0; i < NUM_AXIS; i++) current_speed[i] *= speed_factor;
  813. block->nominal_speed *= speed_factor;
  814. block->nominal_rate *= speed_factor;
  815. }
  816. // Compute and limit the acceleration rate for the trapezoid generator.
  817. float steps_per_mm = block->step_event_count / block->millimeters;
  818. long bsx = block->steps[X_AXIS], bsy = block->steps[Y_AXIS], bsz = block->steps[Z_AXIS], bse = block->steps[E_AXIS];
  819. if (bsx == 0 && bsy == 0 && bsz == 0) {
  820. block->acceleration_steps_per_s2 = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  821. }
  822. else if (bse == 0) {
  823. block->acceleration_steps_per_s2 = ceil(travel_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  824. }
  825. else {
  826. block->acceleration_steps_per_s2 = ceil(acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  827. }
  828. // Limit acceleration per axis
  829. unsigned long acc_st = block->acceleration_steps_per_s2,
  830. x_acc_st = max_acceleration_steps_per_s2[X_AXIS],
  831. y_acc_st = max_acceleration_steps_per_s2[Y_AXIS],
  832. z_acc_st = max_acceleration_steps_per_s2[Z_AXIS],
  833. e_acc_st = max_acceleration_steps_per_s2[E_AXIS],
  834. allsteps = block->step_event_count;
  835. if (x_acc_st < (acc_st * bsx) / allsteps) acc_st = (x_acc_st * allsteps) / bsx;
  836. if (y_acc_st < (acc_st * bsy) / allsteps) acc_st = (y_acc_st * allsteps) / bsy;
  837. if (z_acc_st < (acc_st * bsz) / allsteps) acc_st = (z_acc_st * allsteps) / bsz;
  838. if (e_acc_st < (acc_st * bse) / allsteps) acc_st = (e_acc_st * allsteps) / bse;
  839. block->acceleration_steps_per_s2 = acc_st;
  840. block->acceleration = acc_st / steps_per_mm;
  841. block->acceleration_rate = (long)(acc_st * 16777216.0 / (F_CPU / 8.0));
  842. #if 0 // Use old jerk for now
  843. float junction_deviation = 0.1;
  844. // Compute path unit vector
  845. double unit_vec[3];
  846. unit_vec[X_AXIS] = delta_mm[X_AXIS] * inverse_millimeters;
  847. unit_vec[Y_AXIS] = delta_mm[Y_AXIS] * inverse_millimeters;
  848. unit_vec[Z_AXIS] = delta_mm[Z_AXIS] * inverse_millimeters;
  849. // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  850. // Let a circle be tangent to both previous and current path line segments, where the junction
  851. // deviation is defined as the distance from the junction to the closest edge of the circle,
  852. // collinear with the circle center. The circular segment joining the two paths represents the
  853. // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  854. // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  855. // path width or max_jerk in the previous grbl version. This approach does not actually deviate
  856. // from path, but used as a robust way to compute cornering speeds, as it takes into account the
  857. // nonlinearities of both the junction angle and junction velocity.
  858. double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  859. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  860. if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
  861. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  862. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  863. double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  864. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  865. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
  866. // Skip and use default max junction speed for 0 degree acute junction.
  867. if (cos_theta < 0.95) {
  868. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  869. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  870. if (cos_theta > -0.95) {
  871. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  872. double sin_theta_d2 = sqrt(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  873. vmax_junction = min(vmax_junction,
  874. sqrt(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  875. }
  876. }
  877. }
  878. #endif
  879. // Start with a safe speed
  880. float vmax_junction = max_xy_jerk / 2;
  881. float vmax_junction_factor = 1.0;
  882. float mz2 = max_z_jerk / 2, me2 = max_e_jerk / 2;
  883. float csz = current_speed[Z_AXIS], cse = current_speed[E_AXIS];
  884. if (fabs(csz) > mz2) vmax_junction = min(vmax_junction, mz2);
  885. if (fabs(cse) > me2) vmax_junction = min(vmax_junction, me2);
  886. vmax_junction = min(vmax_junction, block->nominal_speed);
  887. float safe_speed = vmax_junction;
  888. if ((moves_queued > 1) && (previous_nominal_speed > 0.0001)) {
  889. float dsx = current_speed[X_AXIS] - previous_speed[X_AXIS],
  890. dsy = current_speed[Y_AXIS] - previous_speed[Y_AXIS],
  891. dsz = fabs(csz - previous_speed[Z_AXIS]),
  892. dse = fabs(cse - previous_speed[E_AXIS]),
  893. jerk = sqrt(dsx * dsx + dsy * dsy);
  894. // if ((fabs(previous_speed[X_AXIS]) > 0.0001) || (fabs(previous_speed[Y_AXIS]) > 0.0001)) {
  895. vmax_junction = block->nominal_speed;
  896. // }
  897. if (jerk > max_xy_jerk) vmax_junction_factor = max_xy_jerk / jerk;
  898. if (dsz > max_z_jerk) vmax_junction_factor = min(vmax_junction_factor, max_z_jerk / dsz);
  899. if (dse > max_e_jerk) vmax_junction_factor = min(vmax_junction_factor, max_e_jerk / dse);
  900. vmax_junction = min(previous_nominal_speed, vmax_junction * vmax_junction_factor); // Limit speed to max previous speed
  901. }
  902. block->max_entry_speed = vmax_junction;
  903. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  904. double v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  905. block->entry_speed = min(vmax_junction, v_allowable);
  906. // Initialize planner efficiency flags
  907. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  908. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  909. // the current block and next block junction speeds are guaranteed to always be at their maximum
  910. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  911. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  912. // the reverse and forward planners, the corresponding block junction speed will always be at the
  913. // the maximum junction speed and may always be ignored for any speed reduction checks.
  914. block->nominal_length_flag = (block->nominal_speed <= v_allowable);
  915. block->recalculate_flag = true; // Always calculate trapezoid for new block
  916. // Update previous path unit_vector and nominal speed
  917. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = current_speed[i];
  918. previous_nominal_speed = block->nominal_speed;
  919. #if ENABLED(LIN_ADVANCE)
  920. // bse == allsteps: A problem occurs when there's a very tiny move before a retract.
  921. // In this case, the retract and the move will be executed together.
  922. // This leads to an enormous number of advance steps due to a huge e_acceleration.
  923. // The math is correct, but you don't want a retract move done with advance!
  924. // So this situation is filtered out here.
  925. if (!bse || (!bsx && !bsy && !bsz) || stepper.get_advance_k() == 0 || (uint32_t) bse == allsteps) {
  926. block->use_advance_lead = false;
  927. }
  928. else {
  929. block->use_advance_lead = true;
  930. block->e_speed_multiplier8 = (block->steps[E_AXIS] << 8) / block->step_event_count;
  931. }
  932. #elif ENABLED(ADVANCE)
  933. // Calculate advance rate
  934. if (!bse || (!bsx && !bsy && !bsz)) {
  935. block->advance_rate = 0;
  936. block->advance = 0;
  937. }
  938. else {
  939. long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_steps_per_s2);
  940. float advance = ((STEPS_PER_CUBIC_MM_E) * (EXTRUDER_ADVANCE_K)) * (cse * cse * (EXTRUSION_AREA) * (EXTRUSION_AREA)) * 256;
  941. block->advance = advance;
  942. block->advance_rate = acc_dist ? advance / (float)acc_dist : 0;
  943. }
  944. /**
  945. SERIAL_ECHO_START;
  946. SERIAL_ECHOPGM("advance :");
  947. SERIAL_ECHO(block->advance/256.0);
  948. SERIAL_ECHOPGM("advance rate :");
  949. SERIAL_ECHOLN(block->advance_rate/256.0);
  950. */
  951. #endif // ADVANCE or LIN_ADVANCE
  952. calculate_trapezoid_for_block(block, block->entry_speed / block->nominal_speed, safe_speed / block->nominal_speed);
  953. // Move buffer head
  954. block_buffer_head = next_buffer_head;
  955. // Update position
  956. for (int i = 0; i < NUM_AXIS; i++) position[i] = target[i];
  957. recalculate();
  958. stepper.wake_up();
  959. } // buffer_line()
  960. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && DISABLED(DELTA)
  961. /**
  962. * Get the XYZ position of the steppers as a vector_3.
  963. *
  964. * On CORE machines XYZ is derived from ABC.
  965. */
  966. vector_3 Planner::adjusted_position() {
  967. vector_3 pos = vector_3(stepper.get_axis_position_mm(X_AXIS), stepper.get_axis_position_mm(Y_AXIS), stepper.get_axis_position_mm(Z_AXIS));
  968. //pos.debug("in Planner::adjusted_position");
  969. //bed_level_matrix.debug("in Planner::adjusted_position");
  970. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  971. //inverse.debug("in Planner::inverse");
  972. pos.apply_rotation(inverse);
  973. //pos.debug("after rotation");
  974. return pos;
  975. }
  976. #endif // AUTO_BED_LEVELING_FEATURE && !DELTA
  977. /**
  978. * Directly set the planner XYZ position (hence the stepper positions).
  979. *
  980. * On CORE machines stepper ABC will be translated from the given XYZ.
  981. */
  982. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  983. void Planner::set_position_mm(float x, float y, float z, const float& e)
  984. #else
  985. void Planner::set_position_mm(const float& x, const float& y, const float& z, const float& e)
  986. #endif // AUTO_BED_LEVELING_FEATURE || MESH_BED_LEVELING
  987. {
  988. #if ENABLED(MESH_BED_LEVELING)
  989. if (mbl.active())
  990. z += mbl.get_z(x - home_offset[X_AXIS], y - home_offset[Y_AXIS]);
  991. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  992. apply_rotation_xyz(bed_level_matrix, x, y, z);
  993. #endif
  994. long nx = position[X_AXIS] = lround(x * axis_steps_per_mm[X_AXIS]),
  995. ny = position[Y_AXIS] = lround(y * axis_steps_per_mm[Y_AXIS]),
  996. nz = position[Z_AXIS] = lround(z * axis_steps_per_mm[Z_AXIS]),
  997. ne = position[E_AXIS] = lround(e * axis_steps_per_mm[E_AXIS]);
  998. stepper.set_position(nx, ny, nz, ne);
  999. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  1000. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = 0.0;
  1001. }
  1002. /**
  1003. * Directly set the planner E position (hence the stepper E position).
  1004. */
  1005. void Planner::set_e_position_mm(const float& e) {
  1006. position[E_AXIS] = lround(e * axis_steps_per_mm[E_AXIS]);
  1007. stepper.set_e_position(position[E_AXIS]);
  1008. }
  1009. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  1010. void Planner::reset_acceleration_rates() {
  1011. for (int i = 0; i < NUM_AXIS; i++)
  1012. max_acceleration_steps_per_s2[i] = max_acceleration_mm_per_s2[i] * axis_steps_per_mm[i];
  1013. }
  1014. #if ENABLED(AUTOTEMP)
  1015. void Planner::autotemp_M109() {
  1016. autotemp_enabled = code_seen('F');
  1017. if (autotemp_enabled) autotemp_factor = code_value_temp_diff();
  1018. if (code_seen('S')) autotemp_min = code_value_temp_abs();
  1019. if (code_seen('B')) autotemp_max = code_value_temp_abs();
  1020. }
  1021. #endif