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.h 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2019 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. #pragma once
  23. /**
  24. * planner.h
  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. #include "../Marlin.h"
  32. #include "motion.h"
  33. #include "../gcode/queue.h"
  34. #if ENABLED(DELTA)
  35. #include "delta.h"
  36. #endif
  37. #if ABL_PLANAR
  38. #include "../libs/vector_3.h" // for matrix_3x3
  39. #endif
  40. #if ENABLED(FWRETRACT)
  41. #include "../feature/fwretract.h"
  42. #endif
  43. #if ENABLED(MIXING_EXTRUDER)
  44. #include "../feature/mixing.h"
  45. #endif
  46. // Feedrate for manual moves
  47. #ifdef MANUAL_FEEDRATE
  48. constexpr xyze_feedrate_t manual_feedrate_mm_m = MANUAL_FEEDRATE;
  49. #endif
  50. enum BlockFlagBit : char {
  51. // Recalculate trapezoids on entry junction. For optimization.
  52. BLOCK_BIT_RECALCULATE,
  53. // Nominal speed always reached.
  54. // i.e., The segment is long enough, so the nominal speed is reachable if accelerating
  55. // from a safe speed (in consideration of jerking from zero speed).
  56. BLOCK_BIT_NOMINAL_LENGTH,
  57. // The block is segment 2+ of a longer move
  58. BLOCK_BIT_CONTINUED,
  59. // Sync the stepper counts from the block
  60. BLOCK_BIT_SYNC_POSITION
  61. };
  62. enum BlockFlag : char {
  63. BLOCK_FLAG_RECALCULATE = _BV(BLOCK_BIT_RECALCULATE),
  64. BLOCK_FLAG_NOMINAL_LENGTH = _BV(BLOCK_BIT_NOMINAL_LENGTH),
  65. BLOCK_FLAG_CONTINUED = _BV(BLOCK_BIT_CONTINUED),
  66. BLOCK_FLAG_SYNC_POSITION = _BV(BLOCK_BIT_SYNC_POSITION)
  67. };
  68. /**
  69. * struct block_t
  70. *
  71. * A single entry in the planner buffer.
  72. * Tracks linear movement over multiple axes.
  73. *
  74. * The "nominal" values are as-specified by gcode, and
  75. * may never actually be reached due to acceleration limits.
  76. */
  77. typedef struct block_t {
  78. volatile uint8_t flag; // Block flags (See BlockFlag enum above) - Modified by ISR and main thread!
  79. // Fields used by the motion planner to manage acceleration
  80. float nominal_speed_sqr, // The nominal speed for this block in (mm/sec)^2
  81. entry_speed_sqr, // Entry speed at previous-current junction in (mm/sec)^2
  82. max_entry_speed_sqr, // Maximum allowable junction entry speed in (mm/sec)^2
  83. millimeters, // The total travel of this block in mm
  84. acceleration; // acceleration mm/sec^2
  85. union {
  86. abce_ulong_t steps; // Step count along each axis
  87. abce_long_t position; // New position to force when this sync block is executed
  88. };
  89. uint32_t step_event_count; // The number of step events required to complete this block
  90. #if EXTRUDERS > 1
  91. uint8_t extruder; // The extruder to move (if E move)
  92. #else
  93. static constexpr uint8_t extruder = 0;
  94. #endif
  95. #if ENABLED(MIXING_EXTRUDER)
  96. MIXER_BLOCK_FIELD; // Normalized color for the mixing steppers
  97. #endif
  98. // Settings for the trapezoid generator
  99. uint32_t accelerate_until, // The index of the step event on which to stop acceleration
  100. decelerate_after; // The index of the step event on which to start decelerating
  101. #if ENABLED(S_CURVE_ACCELERATION)
  102. uint32_t cruise_rate, // The actual cruise rate to use, between end of the acceleration phase and start of deceleration phase
  103. acceleration_time, // Acceleration time and deceleration time in STEP timer counts
  104. deceleration_time,
  105. acceleration_time_inverse, // Inverse of acceleration and deceleration periods, expressed as integer. Scale depends on CPU being used
  106. deceleration_time_inverse;
  107. #else
  108. uint32_t acceleration_rate; // The acceleration rate used for acceleration calculation
  109. #endif
  110. uint8_t direction_bits; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h)
  111. // Advance extrusion
  112. #if ENABLED(LIN_ADVANCE)
  113. bool use_advance_lead;
  114. uint16_t advance_speed, // STEP timer value for extruder speed offset ISR
  115. max_adv_steps, // max. advance steps to get cruising speed pressure (not always nominal_speed!)
  116. final_adv_steps; // advance steps due to exit speed
  117. float e_D_ratio;
  118. #endif
  119. uint32_t nominal_rate, // The nominal step rate for this block in step_events/sec
  120. initial_rate, // The jerk-adjusted step rate at start of block
  121. final_rate, // The minimal rate at exit
  122. acceleration_steps_per_s2; // acceleration steps/sec^2
  123. #if FAN_COUNT > 0
  124. uint8_t fan_speed[FAN_COUNT];
  125. #endif
  126. #if ENABLED(BARICUDA)
  127. uint8_t valve_pressure, e_to_p_pressure;
  128. #endif
  129. #if HAS_SPI_LCD
  130. uint32_t segment_time_us;
  131. #endif
  132. #if ENABLED(POWER_LOSS_RECOVERY)
  133. uint32_t sdpos;
  134. #endif
  135. } block_t;
  136. #define HAS_POSITION_FLOAT ANY(LIN_ADVANCE, SCARA_FEEDRATE_SCALING, GRADIENT_MIX)
  137. #define BLOCK_MOD(n) ((n)&(BLOCK_BUFFER_SIZE-1))
  138. typedef struct {
  139. uint32_t max_acceleration_mm_per_s2[XYZE_N], // (mm/s^2) M201 XYZE
  140. min_segment_time_us; // (µs) M205 B
  141. float axis_steps_per_mm[XYZE_N]; // (steps) M92 XYZE - Steps per millimeter
  142. feedRate_t max_feedrate_mm_s[XYZE_N]; // (mm/s) M203 XYZE - Max speeds
  143. float acceleration, // (mm/s^2) M204 S - Normal acceleration. DEFAULT ACCELERATION for all printing moves.
  144. retract_acceleration, // (mm/s^2) M204 R - Retract acceleration. Filament pull-back and push-forward while standing still in the other axes
  145. travel_acceleration; // (mm/s^2) M204 T - Travel acceleration. DEFAULT ACCELERATION for all NON printing moves.
  146. feedRate_t min_feedrate_mm_s, // (mm/s) M205 S - Minimum linear feedrate
  147. min_travel_feedrate_mm_s; // (mm/s) M205 T - Minimum travel feedrate
  148. } planner_settings_t;
  149. #if DISABLED(SKEW_CORRECTION)
  150. #define XY_SKEW_FACTOR 0
  151. #define XZ_SKEW_FACTOR 0
  152. #define YZ_SKEW_FACTOR 0
  153. #endif
  154. typedef struct {
  155. #if ENABLED(SKEW_CORRECTION_GCODE)
  156. float xy;
  157. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  158. float xz, yz;
  159. #else
  160. const float xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR;
  161. #endif
  162. #else
  163. const float xy = XY_SKEW_FACTOR,
  164. xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR;
  165. #endif
  166. } skew_factor_t;
  167. class Planner {
  168. public:
  169. /**
  170. * The move buffer, calculated in stepper steps
  171. *
  172. * block_buffer is a ring buffer...
  173. *
  174. * head,tail : indexes for write,read
  175. * head==tail : the buffer is empty
  176. * head!=tail : blocks are in the buffer
  177. * head==(tail-1)%size : the buffer is full
  178. *
  179. * Writer of head is Planner::buffer_segment().
  180. * Reader of tail is Stepper::isr(). Always consider tail busy / read-only
  181. */
  182. static block_t block_buffer[BLOCK_BUFFER_SIZE];
  183. static volatile uint8_t block_buffer_head, // Index of the next block to be pushed
  184. block_buffer_nonbusy, // Index of the first non busy block
  185. block_buffer_planned, // Index of the optimally planned block
  186. block_buffer_tail; // Index of the busy block, if any
  187. static uint16_t cleaning_buffer_counter; // A counter to disable queuing of blocks
  188. static uint8_t delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  189. #if ENABLED(DISTINCT_E_FACTORS)
  190. static uint8_t last_extruder; // Respond to extruder change
  191. #endif
  192. #if EXTRUDERS
  193. static int16_t flow_percentage[EXTRUDERS]; // Extrusion factor for each extruder
  194. static float e_factor[EXTRUDERS]; // The flow percentage and volumetric multiplier combine to scale E movement
  195. #endif
  196. #if DISABLED(NO_VOLUMETRICS)
  197. static float filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
  198. volumetric_area_nominal, // Nominal cross-sectional area
  199. volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  200. // May be auto-adjusted by a filament width sensor
  201. #endif
  202. static planner_settings_t settings;
  203. static uint32_t max_acceleration_steps_per_s2[XYZE_N]; // (steps/s^2) Derived from mm_per_s2
  204. static float steps_to_mm[XYZE_N]; // Millimeters per step
  205. #if ENABLED(JUNCTION_DEVIATION)
  206. static float junction_deviation_mm; // (mm) M205 J
  207. #if ENABLED(LIN_ADVANCE)
  208. static float max_e_jerk // Calculated from junction_deviation_mm
  209. #if ENABLED(DISTINCT_E_FACTORS)
  210. [EXTRUDERS]
  211. #endif
  212. ;
  213. #endif
  214. #endif
  215. #if HAS_CLASSIC_JERK
  216. #if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
  217. static xyz_pos_t max_jerk; // (mm/s^2) M205 XYZ - The largest speed change requiring no acceleration.
  218. #else
  219. static xyze_pos_t max_jerk; // (mm/s^2) M205 XYZE - The largest speed change requiring no acceleration.
  220. #endif
  221. #endif
  222. #if HAS_LEVELING
  223. static bool leveling_active; // Flag that bed leveling is enabled
  224. #if ABL_PLANAR
  225. static matrix_3x3 bed_level_matrix; // Transform to compensate for bed level
  226. static constexpr xy_pos_t level_fulcrum = { X_TILT_FULCRUM, Y_TILT_FULCRUM };
  227. #endif
  228. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  229. static float z_fade_height, inverse_z_fade_height;
  230. #endif
  231. #else
  232. static constexpr bool leveling_active = false;
  233. #endif
  234. #if ENABLED(LIN_ADVANCE)
  235. static float extruder_advance_K[EXTRUDERS];
  236. #endif
  237. #if HAS_POSITION_FLOAT
  238. static xyze_pos_t position_float;
  239. #endif
  240. #if IS_KINEMATIC
  241. static xyze_pos_t position_cart;
  242. #endif
  243. static skew_factor_t skew_factor;
  244. #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT)
  245. static bool abort_on_endstop_hit;
  246. #endif
  247. private:
  248. /**
  249. * The current position of the tool in absolute steps
  250. * Recalculated if any axis_steps_per_mm are changed by gcode
  251. */
  252. static xyze_long_t position;
  253. /**
  254. * Speed of previous path line segment
  255. */
  256. static xyze_float_t previous_speed;
  257. /**
  258. * Nominal speed of previous path line segment (mm/s)^2
  259. */
  260. static float previous_nominal_speed_sqr;
  261. /**
  262. * Limit where 64bit math is necessary for acceleration calculation
  263. */
  264. static uint32_t cutoff_long;
  265. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  266. static float last_fade_z;
  267. #endif
  268. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  269. /**
  270. * Counters to manage disabling inactive extruders
  271. */
  272. static uint8_t g_uc_extruder_last_move[EXTRUDERS];
  273. #endif // DISABLE_INACTIVE_EXTRUDER
  274. #ifdef XY_FREQUENCY_LIMIT
  275. // Used for the frequency limit
  276. #define MAX_FREQ_TIME_US (uint32_t)(1000000.0 / XY_FREQUENCY_LIMIT)
  277. // Old direction bits. Used for speed calculations
  278. static unsigned char old_direction_bits;
  279. // Segment times (in µs). Used for speed calculations
  280. static xy_ulong_t axis_segment_time_us[3];
  281. #endif
  282. #if HAS_SPI_LCD
  283. volatile static uint32_t block_buffer_runtime_us; //Theoretical block buffer runtime in µs
  284. #endif
  285. public:
  286. /**
  287. * Instance Methods
  288. */
  289. Planner();
  290. void init();
  291. /**
  292. * Static (class) Methods
  293. */
  294. static void reset_acceleration_rates();
  295. static void refresh_positioning();
  296. static void set_max_acceleration(const uint8_t axis, float targetValue);
  297. static void set_max_feedrate(const uint8_t axis, float targetValue);
  298. static void set_max_jerk(const AxisEnum axis, float targetValue);
  299. #if EXTRUDERS
  300. FORCE_INLINE static void refresh_e_factor(const uint8_t e) {
  301. e_factor[e] = (flow_percentage[e] * 0.01f
  302. #if DISABLED(NO_VOLUMETRICS)
  303. * volumetric_multiplier[e]
  304. #endif
  305. );
  306. }
  307. #endif
  308. // Manage fans, paste pressure, etc.
  309. static void check_axes_activity();
  310. // Update multipliers based on new diameter measurements
  311. static void calculate_volumetric_multipliers();
  312. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  313. void apply_filament_width_sensor(const int8_t encoded_ratio);
  314. static inline float volumetric_percent(const bool vol) {
  315. return 100.0f * (vol
  316. ? volumetric_area_nominal / volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM]
  317. : volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM]
  318. );
  319. }
  320. #endif
  321. #if DISABLED(NO_VOLUMETRICS)
  322. FORCE_INLINE static void set_filament_size(const uint8_t e, const float &v) {
  323. filament_size[e] = v;
  324. // make sure all extruders have some sane value for the filament size
  325. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  326. if (!filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  327. }
  328. #endif
  329. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  330. /**
  331. * Get the Z leveling fade factor based on the given Z height,
  332. * re-calculating only when needed.
  333. *
  334. * Returns 1.0 if planner.z_fade_height is 0.0.
  335. * Returns 0.0 if Z is past the specified 'Fade Height'.
  336. */
  337. static inline float fade_scaling_factor_for_z(const float &rz) {
  338. static float z_fade_factor = 1;
  339. if (!z_fade_height) return 1;
  340. if (rz >= z_fade_height) return 0;
  341. if (last_fade_z != rz) {
  342. last_fade_z = rz;
  343. z_fade_factor = 1 - rz * inverse_z_fade_height;
  344. }
  345. return z_fade_factor;
  346. }
  347. FORCE_INLINE static void force_fade_recalc() { last_fade_z = -999.999f; }
  348. FORCE_INLINE static void set_z_fade_height(const float &zfh) {
  349. z_fade_height = zfh > 0 ? zfh : 0;
  350. inverse_z_fade_height = RECIPROCAL(z_fade_height);
  351. force_fade_recalc();
  352. }
  353. FORCE_INLINE static bool leveling_active_at_z(const float &rz) {
  354. return !z_fade_height || rz < z_fade_height;
  355. }
  356. #else
  357. FORCE_INLINE static float fade_scaling_factor_for_z(const float&) { return 1; }
  358. FORCE_INLINE static bool leveling_active_at_z(const float&) { return true; }
  359. #endif
  360. #if ENABLED(SKEW_CORRECTION)
  361. FORCE_INLINE static void skew(float &cx, float &cy, const float &cz) {
  362. if (WITHIN(cx, X_MIN_POS + 1, X_MAX_POS) && WITHIN(cy, Y_MIN_POS + 1, Y_MAX_POS)) {
  363. const float sx = cx - cy * skew_factor.xy - cz * (skew_factor.xz - (skew_factor.xy * skew_factor.yz)),
  364. sy = cy - cz * skew_factor.yz;
  365. if (WITHIN(sx, X_MIN_POS, X_MAX_POS) && WITHIN(sy, Y_MIN_POS, Y_MAX_POS)) {
  366. cx = sx; cy = sy;
  367. }
  368. }
  369. }
  370. FORCE_INLINE static void skew(xyz_pos_t &raw) { skew(raw.x, raw.y, raw.z); }
  371. FORCE_INLINE static void unskew(float &cx, float &cy, const float &cz) {
  372. if (WITHIN(cx, X_MIN_POS, X_MAX_POS) && WITHIN(cy, Y_MIN_POS, Y_MAX_POS)) {
  373. const float sx = cx + cy * skew_factor.xy + cz * skew_factor.xz,
  374. sy = cy + cz * skew_factor.yz;
  375. if (WITHIN(sx, X_MIN_POS, X_MAX_POS) && WITHIN(sy, Y_MIN_POS, Y_MAX_POS)) {
  376. cx = sx; cy = sy;
  377. }
  378. }
  379. }
  380. FORCE_INLINE static void unskew(xyz_pos_t &raw) { unskew(raw.x, raw.y, raw.z); }
  381. #endif // SKEW_CORRECTION
  382. #if HAS_LEVELING
  383. /**
  384. * Apply leveling to transform a cartesian position
  385. * as it will be given to the planner and steppers.
  386. */
  387. static void apply_leveling(xyz_pos_t &raw);
  388. static void unapply_leveling(xyz_pos_t &raw);
  389. FORCE_INLINE static void force_unapply_leveling(xyz_pos_t &raw) {
  390. leveling_active = true;
  391. unapply_leveling(raw);
  392. leveling_active = false;
  393. }
  394. #endif
  395. #if ENABLED(FWRETRACT)
  396. static void apply_retract(float &rz, float &e);
  397. FORCE_INLINE static void apply_retract(xyze_pos_t &raw) { apply_retract(raw.z, raw.e); }
  398. static void unapply_retract(float &rz, float &e);
  399. FORCE_INLINE static void unapply_retract(xyze_pos_t &raw) { unapply_retract(raw.z, raw.e); }
  400. #endif
  401. #if HAS_POSITION_MODIFIERS
  402. FORCE_INLINE static void apply_modifiers(xyze_pos_t &pos
  403. #if HAS_LEVELING
  404. , bool leveling =
  405. #if PLANNER_LEVELING
  406. true
  407. #else
  408. false
  409. #endif
  410. #endif
  411. ) {
  412. #if ENABLED(SKEW_CORRECTION)
  413. skew(pos);
  414. #endif
  415. #if HAS_LEVELING
  416. if (leveling) apply_leveling(pos);
  417. #endif
  418. #if ENABLED(FWRETRACT)
  419. apply_retract(pos);
  420. #endif
  421. }
  422. FORCE_INLINE static void unapply_modifiers(xyze_pos_t &pos
  423. #if HAS_LEVELING
  424. , bool leveling =
  425. #if PLANNER_LEVELING
  426. true
  427. #else
  428. false
  429. #endif
  430. #endif
  431. ) {
  432. #if ENABLED(FWRETRACT)
  433. unapply_retract(pos);
  434. #endif
  435. #if HAS_LEVELING
  436. if (leveling) unapply_leveling(pos);
  437. #endif
  438. #if ENABLED(SKEW_CORRECTION)
  439. unskew(pos);
  440. #endif
  441. }
  442. #endif // HAS_POSITION_MODIFIERS
  443. // Number of moves currently in the planner including the busy block, if any
  444. FORCE_INLINE static uint8_t movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_tail); }
  445. // Number of nonbusy moves currently in the planner
  446. FORCE_INLINE static uint8_t nonbusy_movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_nonbusy); }
  447. // Remove all blocks from the buffer
  448. FORCE_INLINE static void clear_block_buffer() { block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail = 0; }
  449. // Check if movement queue is full
  450. FORCE_INLINE static bool is_full() { return block_buffer_tail == next_block_index(block_buffer_head); }
  451. // Get count of movement slots free
  452. FORCE_INLINE static uint8_t moves_free() { return BLOCK_BUFFER_SIZE - 1 - movesplanned(); }
  453. /**
  454. * Planner::get_next_free_block
  455. *
  456. * - Get the next head indices (passed by reference)
  457. * - Wait for the number of spaces to open up in the planner
  458. * - Return the first head block
  459. */
  460. FORCE_INLINE static block_t* get_next_free_block(uint8_t &next_buffer_head, const uint8_t count=1) {
  461. // Wait until there are enough slots free
  462. while (moves_free() < count) { idle(); }
  463. // Return the first available block
  464. next_buffer_head = next_block_index(block_buffer_head);
  465. return &block_buffer[block_buffer_head];
  466. }
  467. /**
  468. * Planner::_buffer_steps
  469. *
  470. * Add a new linear movement to the buffer (in terms of steps).
  471. *
  472. * target - target position in steps units
  473. * fr_mm_s - (target) speed of the move
  474. * extruder - target extruder
  475. * millimeters - the length of the movement, if known
  476. *
  477. * Returns true if movement was buffered, false otherwise
  478. */
  479. static bool _buffer_steps(const xyze_long_t &target
  480. #if HAS_POSITION_FLOAT
  481. , const xyze_pos_t &target_float
  482. #endif
  483. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  484. , const xyze_float_t &delta_mm_cart
  485. #endif
  486. , feedRate_t fr_mm_s, const uint8_t extruder, const float &millimeters=0.0
  487. );
  488. /**
  489. * Planner::_populate_block
  490. *
  491. * Fills a new linear movement in the block (in terms of steps).
  492. *
  493. * target - target position in steps units
  494. * fr_mm_s - (target) speed of the move
  495. * extruder - target extruder
  496. * millimeters - the length of the movement, if known
  497. *
  498. * Returns true is movement is acceptable, false otherwise
  499. */
  500. static bool _populate_block(block_t * const block, bool split_move,
  501. const xyze_long_t &target
  502. #if HAS_POSITION_FLOAT
  503. , const xyze_pos_t &target_float
  504. #endif
  505. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  506. , const xyze_float_t &delta_mm_cart
  507. #endif
  508. , feedRate_t fr_mm_s, const uint8_t extruder, const float &millimeters=0.0
  509. );
  510. /**
  511. * Planner::buffer_sync_block
  512. * Add a block to the buffer that just updates the position
  513. */
  514. static void buffer_sync_block();
  515. #if IS_KINEMATIC
  516. private:
  517. // Allow do_homing_move to access internal functions, such as buffer_segment.
  518. friend void do_homing_move(const AxisEnum, const float, const feedRate_t);
  519. #endif
  520. /**
  521. * Planner::buffer_segment
  522. *
  523. * Add a new linear movement to the buffer in axis units.
  524. *
  525. * Leveling and kinematics should be applied ahead of calling this.
  526. *
  527. * a,b,c,e - target positions in mm and/or degrees
  528. * fr_mm_s - (target) speed of the move
  529. * extruder - target extruder
  530. * millimeters - the length of the movement, if known
  531. */
  532. static bool buffer_segment(const float &a, const float &b, const float &c, const float &e
  533. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  534. , const xyze_float_t &delta_mm_cart
  535. #endif
  536. , const feedRate_t &fr_mm_s, const uint8_t extruder, const float &millimeters=0.0
  537. );
  538. FORCE_INLINE static bool buffer_segment(abce_pos_t &abce
  539. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  540. , const xyze_float_t &delta_mm_cart
  541. #endif
  542. , const feedRate_t &fr_mm_s, const uint8_t extruder, const float &millimeters=0.0
  543. ) {
  544. return buffer_segment(abce.a, abce.b, abce.c, abce.e
  545. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  546. , delta_mm_cart
  547. #endif
  548. , fr_mm_s, extruder, millimeters);
  549. }
  550. public:
  551. /**
  552. * Add a new linear movement to the buffer.
  553. * The target is cartesian. It's translated to
  554. * delta/scara if needed.
  555. *
  556. * rx,ry,rz,e - target position in mm or degrees
  557. * fr_mm_s - (target) speed of the move (mm/s)
  558. * extruder - target extruder
  559. * millimeters - the length of the movement, if known
  560. * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
  561. */
  562. static bool buffer_line(const float &rx, const float &ry, const float &rz, const float &e, const feedRate_t &fr_mm_s, const uint8_t extruder, const float millimeters=0.0
  563. #if ENABLED(SCARA_FEEDRATE_SCALING)
  564. , const float &inv_duration=0.0
  565. #endif
  566. );
  567. FORCE_INLINE static bool buffer_line(const xyze_pos_t &cart, const feedRate_t &fr_mm_s, const uint8_t extruder, const float millimeters=0.0
  568. #if ENABLED(SCARA_FEEDRATE_SCALING)
  569. , const float &inv_duration=0.0
  570. #endif
  571. ) {
  572. return buffer_line(cart.x, cart.y, cart.z, cart.e, fr_mm_s, extruder, millimeters
  573. #if ENABLED(SCARA_FEEDRATE_SCALING)
  574. , inv_duration
  575. #endif
  576. );
  577. }
  578. /**
  579. * Set the planner.position and individual stepper positions.
  580. * Used by G92, G28, G29, and other procedures.
  581. *
  582. * The supplied position is in the cartesian coordinate space and is
  583. * translated in to machine space as needed. Modifiers such as leveling
  584. * and skew are also applied.
  585. *
  586. * Multiplies by axis_steps_per_mm[] and does necessary conversion
  587. * for COREXY / COREXZ / COREYZ to set the corresponding stepper positions.
  588. *
  589. * Clears previous speed values.
  590. */
  591. static void set_position_mm(const float &rx, const float &ry, const float &rz, const float &e);
  592. FORCE_INLINE static void set_position_mm(const xyze_pos_t &cart) { set_position_mm(cart.x, cart.y, cart.z, cart.e); }
  593. static void set_e_position_mm(const float &e);
  594. /**
  595. * Set the planner.position and individual stepper positions.
  596. *
  597. * The supplied position is in machine space, and no additional
  598. * conversions are applied.
  599. */
  600. static void set_machine_position_mm(const float &a, const float &b, const float &c, const float &e);
  601. FORCE_INLINE static void set_machine_position_mm(const abce_pos_t &abce) { set_machine_position_mm(abce.a, abce.b, abce.c, abce.e); }
  602. /**
  603. * Get an axis position according to stepper position(s)
  604. * For CORE machines apply translation from ABC to XYZ.
  605. */
  606. static float get_axis_position_mm(const AxisEnum axis);
  607. // SCARA AB axes are in degrees, not mm
  608. #if IS_SCARA
  609. FORCE_INLINE static float get_axis_position_degrees(const AxisEnum axis) { return get_axis_position_mm(axis); }
  610. #endif
  611. // Called to force a quick stop of the machine (for example, when
  612. // a Full Shutdown is required, or when endstops are hit)
  613. static void quick_stop();
  614. // Called when an endstop is triggered. Causes the machine to stop inmediately
  615. static void endstop_triggered(const AxisEnum axis);
  616. // Triggered position of an axis in mm (not core-savvy)
  617. static float triggered_position_mm(const AxisEnum axis);
  618. // Block until all buffered steps are executed / cleaned
  619. static void synchronize();
  620. // Wait for moves to finish and disable all steppers
  621. static void finish_and_disable();
  622. // Periodic tick to handle cleaning timeouts
  623. // Called from the Temperature ISR at ~1kHz
  624. static void tick() {
  625. if (cleaning_buffer_counter) {
  626. --cleaning_buffer_counter;
  627. #if ENABLED(SD_FINISHED_STEPPERRELEASE) && defined(SD_FINISHED_RELEASECOMMAND)
  628. if (!cleaning_buffer_counter) queue.inject_P(PSTR(SD_FINISHED_RELEASECOMMAND));
  629. #endif
  630. }
  631. }
  632. /**
  633. * Does the buffer have any blocks queued?
  634. */
  635. FORCE_INLINE static bool has_blocks_queued() { return (block_buffer_head != block_buffer_tail); }
  636. /**
  637. * The current block. nullptr if the buffer is empty.
  638. * This also marks the block as busy.
  639. * WARNING: Called from Stepper ISR context!
  640. */
  641. static block_t* get_current_block() {
  642. // Get the number of moves in the planner queue so far
  643. const uint8_t nr_moves = movesplanned();
  644. // If there are any moves queued ...
  645. if (nr_moves) {
  646. // If there is still delay of delivery of blocks running, decrement it
  647. if (delay_before_delivering) {
  648. --delay_before_delivering;
  649. // If the number of movements queued is less than 3, and there is still time
  650. // to wait, do not deliver anything
  651. if (nr_moves < 3 && delay_before_delivering) return nullptr;
  652. delay_before_delivering = 0;
  653. }
  654. // If we are here, there is no excuse to deliver the block
  655. block_t * const block = &block_buffer[block_buffer_tail];
  656. // No trapezoid calculated? Don't execute yet.
  657. if (TEST(block->flag, BLOCK_BIT_RECALCULATE)) return nullptr;
  658. #if HAS_SPI_LCD
  659. block_buffer_runtime_us -= block->segment_time_us; // We can't be sure how long an active block will take, so don't count it.
  660. #endif
  661. // As this block is busy, advance the nonbusy block pointer
  662. block_buffer_nonbusy = next_block_index(block_buffer_tail);
  663. // Push block_buffer_planned pointer, if encountered.
  664. if (block_buffer_tail == block_buffer_planned)
  665. block_buffer_planned = block_buffer_nonbusy;
  666. // Return the block
  667. return block;
  668. }
  669. // The queue became empty
  670. #if HAS_SPI_LCD
  671. clear_block_buffer_runtime(); // paranoia. Buffer is empty now - so reset accumulated time to zero.
  672. #endif
  673. return nullptr;
  674. }
  675. /**
  676. * "Discard" the block and "release" the memory.
  677. * Called when the current block is no longer needed.
  678. * NB: There MUST be a current block to call this function!!
  679. */
  680. FORCE_INLINE static void discard_current_block() {
  681. if (has_blocks_queued())
  682. block_buffer_tail = next_block_index(block_buffer_tail);
  683. }
  684. #if HAS_SPI_LCD
  685. static uint16_t block_buffer_runtime() {
  686. #ifdef __AVR__
  687. // Protect the access to the variable. Only required for AVR, as
  688. // any 32bit CPU offers atomic access to 32bit variables
  689. bool was_enabled = STEPPER_ISR_ENABLED();
  690. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  691. #endif
  692. millis_t bbru = block_buffer_runtime_us;
  693. #ifdef __AVR__
  694. // Reenable Stepper ISR
  695. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  696. #endif
  697. // To translate µs to ms a division by 1000 would be required.
  698. // We introduce 2.4% error here by dividing by 1024.
  699. // Doesn't matter because block_buffer_runtime_us is already too small an estimation.
  700. bbru >>= 10;
  701. // limit to about a minute.
  702. NOMORE(bbru, 0xFFFFul);
  703. return bbru;
  704. }
  705. static void clear_block_buffer_runtime() {
  706. #ifdef __AVR__
  707. // Protect the access to the variable. Only required for AVR, as
  708. // any 32bit CPU offers atomic access to 32bit variables
  709. bool was_enabled = STEPPER_ISR_ENABLED();
  710. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  711. #endif
  712. block_buffer_runtime_us = 0;
  713. #ifdef __AVR__
  714. // Reenable Stepper ISR
  715. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  716. #endif
  717. }
  718. #endif
  719. #if ENABLED(AUTOTEMP)
  720. static float autotemp_min, autotemp_max, autotemp_factor;
  721. static bool autotemp_enabled;
  722. static void getHighESpeed();
  723. static void autotemp_M104_M109();
  724. #endif
  725. #if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
  726. FORCE_INLINE static void recalculate_max_e_jerk() {
  727. #define GET_MAX_E_JERK(N) SQRT(SQRT(0.5) * junction_deviation_mm * (N) * RECIPROCAL(1.0 - SQRT(0.5)))
  728. #if ENABLED(DISTINCT_E_FACTORS)
  729. for (uint8_t i = 0; i < EXTRUDERS; i++)
  730. max_e_jerk[i] = GET_MAX_E_JERK(settings.max_acceleration_mm_per_s2[E_AXIS_N(i)]);
  731. #else
  732. max_e_jerk = GET_MAX_E_JERK(settings.max_acceleration_mm_per_s2[E_AXIS]);
  733. #endif
  734. }
  735. #endif
  736. private:
  737. /**
  738. * Get the index of the next / previous block in the ring buffer
  739. */
  740. static constexpr uint8_t next_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index + 1); }
  741. static constexpr uint8_t prev_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index - 1); }
  742. /**
  743. * Calculate the distance (not time) it takes to accelerate
  744. * from initial_rate to target_rate using the given acceleration:
  745. */
  746. static float estimate_acceleration_distance(const float &initial_rate, const float &target_rate, const float &accel) {
  747. if (accel == 0) return 0; // accel was 0, set acceleration distance to 0
  748. return (sq(target_rate) - sq(initial_rate)) / (accel * 2);
  749. }
  750. /**
  751. * Return the point at which you must start braking (at the rate of -'accel') if
  752. * you start at 'initial_rate', accelerate (until reaching the point), and want to end at
  753. * 'final_rate' after traveling 'distance'.
  754. *
  755. * This is used to compute the intersection point between acceleration and deceleration
  756. * in cases where the "trapezoid" has no plateau (i.e., never reaches maximum speed)
  757. */
  758. static float intersection_distance(const float &initial_rate, const float &final_rate, const float &accel, const float &distance) {
  759. if (accel == 0) return 0; // accel was 0, set intersection distance to 0
  760. return (accel * 2 * distance - sq(initial_rate) + sq(final_rate)) / (accel * 4);
  761. }
  762. /**
  763. * Calculate the maximum allowable speed squared at this point, in order
  764. * to reach 'target_velocity_sqr' using 'acceleration' within a given
  765. * 'distance'.
  766. */
  767. static float max_allowable_speed_sqr(const float &accel, const float &target_velocity_sqr, const float &distance) {
  768. return target_velocity_sqr - 2 * accel * distance;
  769. }
  770. #if ENABLED(S_CURVE_ACCELERATION)
  771. /**
  772. * Calculate the speed reached given initial speed, acceleration and distance
  773. */
  774. static float final_speed(const float &initial_velocity, const float &accel, const float &distance) {
  775. return SQRT(sq(initial_velocity) + 2 * accel * distance);
  776. }
  777. #endif
  778. static void calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor);
  779. static void reverse_pass_kernel(block_t* const current, const block_t * const next);
  780. static void forward_pass_kernel(const block_t * const previous, block_t* const current, uint8_t block_index);
  781. static void reverse_pass();
  782. static void forward_pass();
  783. static void recalculate_trapezoids();
  784. static void recalculate();
  785. #if ENABLED(JUNCTION_DEVIATION)
  786. FORCE_INLINE static void normalize_junction_vector(xyze_float_t &vector) {
  787. float magnitude_sq = 0;
  788. LOOP_XYZE(idx) if (vector[idx]) magnitude_sq += sq(vector[idx]);
  789. vector *= RSQRT(magnitude_sq);
  790. }
  791. FORCE_INLINE static float limit_value_by_axis_maximum(const float &max_value, xyze_float_t &unit_vec) {
  792. float limit_value = max_value;
  793. LOOP_XYZE(idx) if (unit_vec[idx]) // Avoid divide by zero
  794. NOMORE(limit_value, ABS(settings.max_acceleration_mm_per_s2[idx] / unit_vec[idx]));
  795. return limit_value;
  796. }
  797. #endif // JUNCTION_DEVIATION
  798. };
  799. #define PLANNER_XY_FEEDRATE() (_MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]))
  800. extern Planner planner;