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 36KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 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 <https://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 "../MarlinCore.h"
  32. #if ENABLED(JD_HANDLE_SMALL_SEGMENTS)
  33. // Enable this option for perfect accuracy but maximum
  34. // computation. Should be fine on ARM processors.
  35. //#define JD_USE_MATH_ACOS
  36. // Disable this option to save 120 bytes of PROGMEM,
  37. // but incur increased computation and a reduction
  38. // in accuracy.
  39. #define JD_USE_LOOKUP_TABLE
  40. #endif
  41. #include "motion.h"
  42. #include "../gcode/queue.h"
  43. #if ENABLED(DELTA)
  44. #include "delta.h"
  45. #elif ENABLED(POLARGRAPH)
  46. #include "polargraph.h"
  47. #endif
  48. #if ABL_PLANAR
  49. #include "../libs/vector_3.h" // for matrix_3x3
  50. #endif
  51. #if ENABLED(FWRETRACT)
  52. #include "../feature/fwretract.h"
  53. #endif
  54. #if ENABLED(MIXING_EXTRUDER)
  55. #include "../feature/mixing.h"
  56. #endif
  57. #if HAS_CUTTER
  58. #include "../feature/spindle_laser_types.h"
  59. #endif
  60. #if ENABLED(DIRECT_STEPPING)
  61. #include "../feature/direct_stepping.h"
  62. #define IS_PAGE(B) TEST(B->flag, BLOCK_BIT_IS_PAGE)
  63. #else
  64. #define IS_PAGE(B) false
  65. #endif
  66. #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
  67. #include "../feature/closedloop.h"
  68. #endif
  69. // Feedrate for manual moves
  70. #ifdef MANUAL_FEEDRATE
  71. constexpr xyze_feedrate_t _mf = MANUAL_FEEDRATE,
  72. manual_feedrate_mm_s = LOGICAL_AXIS_ARRAY(_mf.e / 60.0f,
  73. _mf.x / 60.0f, _mf.y / 60.0f, _mf.z / 60.0f,
  74. _mf.i / 60.0f, _mf.j / 60.0f, _mf.k / 60.0f);
  75. #endif
  76. #if IS_KINEMATIC && HAS_JUNCTION_DEVIATION
  77. #define HAS_DIST_MM_ARG 1
  78. #endif
  79. enum BlockFlagBit : char {
  80. // Recalculate trapezoids on entry junction. For optimization.
  81. BLOCK_BIT_RECALCULATE,
  82. // Nominal speed always reached.
  83. // i.e., The segment is long enough, so the nominal speed is reachable if accelerating
  84. // from a safe speed (in consideration of jerking from zero speed).
  85. BLOCK_BIT_NOMINAL_LENGTH,
  86. // The block is segment 2+ of a longer move
  87. BLOCK_BIT_CONTINUED,
  88. // Sync the stepper counts from the block
  89. BLOCK_BIT_SYNC_POSITION
  90. // Direct stepping page
  91. #if ENABLED(DIRECT_STEPPING)
  92. , BLOCK_BIT_IS_PAGE
  93. #endif
  94. // Sync the fan speeds from the block
  95. #if ENABLED(LASER_SYNCHRONOUS_M106_M107)
  96. , BLOCK_BIT_SYNC_FANS
  97. #endif
  98. };
  99. enum BlockFlag : char {
  100. BLOCK_FLAG_RECALCULATE = _BV(BLOCK_BIT_RECALCULATE)
  101. , BLOCK_FLAG_NOMINAL_LENGTH = _BV(BLOCK_BIT_NOMINAL_LENGTH)
  102. , BLOCK_FLAG_CONTINUED = _BV(BLOCK_BIT_CONTINUED)
  103. , BLOCK_FLAG_SYNC_POSITION = _BV(BLOCK_BIT_SYNC_POSITION)
  104. #if ENABLED(DIRECT_STEPPING)
  105. , BLOCK_FLAG_IS_PAGE = _BV(BLOCK_BIT_IS_PAGE)
  106. #endif
  107. #if ENABLED(LASER_SYNCHRONOUS_M106_M107)
  108. , BLOCK_FLAG_SYNC_FANS = _BV(BLOCK_BIT_SYNC_FANS)
  109. #endif
  110. };
  111. #define BLOCK_MASK_SYNC ( BLOCK_FLAG_SYNC_POSITION | TERN0(LASER_SYNCHRONOUS_M106_M107, BLOCK_FLAG_SYNC_FANS) )
  112. #if ENABLED(LASER_POWER_INLINE)
  113. typedef struct {
  114. bool isPlanned:1;
  115. bool isEnabled:1;
  116. bool dir:1;
  117. bool Reserved:6;
  118. } power_status_t;
  119. typedef struct {
  120. power_status_t status; // See planner settings for meaning
  121. uint8_t power; // Ditto; When in trapezoid mode this is nominal power
  122. #if ENABLED(LASER_POWER_INLINE_TRAPEZOID)
  123. uint8_t power_entry; // Entry power for the laser
  124. #if DISABLED(LASER_POWER_INLINE_TRAPEZOID_CONT)
  125. uint8_t power_exit; // Exit power for the laser
  126. uint32_t entry_per, // Steps per power increment (to avoid floats in stepper calcs)
  127. exit_per; // Steps per power decrement
  128. #endif
  129. #endif
  130. } block_laser_t;
  131. #endif
  132. /**
  133. * struct block_t
  134. *
  135. * A single entry in the planner buffer.
  136. * Tracks linear movement over multiple axes.
  137. *
  138. * The "nominal" values are as-specified by gcode, and
  139. * may never actually be reached due to acceleration limits.
  140. */
  141. typedef struct block_t {
  142. volatile uint8_t flag; // Block flags (See BlockFlag enum above) - Modified by ISR and main thread!
  143. // Fields used by the motion planner to manage acceleration
  144. float nominal_speed_sqr, // The nominal speed for this block in (mm/sec)^2
  145. entry_speed_sqr, // Entry speed at previous-current junction in (mm/sec)^2
  146. max_entry_speed_sqr, // Maximum allowable junction entry speed in (mm/sec)^2
  147. millimeters, // The total travel of this block in mm
  148. acceleration; // acceleration mm/sec^2
  149. union {
  150. abce_ulong_t steps; // Step count along each axis
  151. abce_long_t position; // New position to force when this sync block is executed
  152. };
  153. uint32_t step_event_count; // The number of step events required to complete this block
  154. #if HAS_MULTI_EXTRUDER
  155. uint8_t extruder; // The extruder to move (if E move)
  156. #else
  157. static constexpr uint8_t extruder = 0;
  158. #endif
  159. #if ENABLED(MIXING_EXTRUDER)
  160. mixer_comp_t b_color[MIXING_STEPPERS]; // Normalized color for the mixing steppers
  161. #endif
  162. // Settings for the trapezoid generator
  163. uint32_t accelerate_until, // The index of the step event on which to stop acceleration
  164. decelerate_after; // The index of the step event on which to start decelerating
  165. #if ENABLED(S_CURVE_ACCELERATION)
  166. uint32_t cruise_rate, // The actual cruise rate to use, between end of the acceleration phase and start of deceleration phase
  167. acceleration_time, // Acceleration time and deceleration time in STEP timer counts
  168. deceleration_time,
  169. acceleration_time_inverse, // Inverse of acceleration and deceleration periods, expressed as integer. Scale depends on CPU being used
  170. deceleration_time_inverse;
  171. #else
  172. uint32_t acceleration_rate; // The acceleration rate used for acceleration calculation
  173. #endif
  174. axis_bits_t direction_bits; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h)
  175. // Advance extrusion
  176. #if ENABLED(LIN_ADVANCE)
  177. bool use_advance_lead;
  178. uint16_t advance_speed, // STEP timer value for extruder speed offset ISR
  179. max_adv_steps, // max. advance steps to get cruising speed pressure (not always nominal_speed!)
  180. final_adv_steps; // advance steps due to exit speed
  181. float e_D_ratio;
  182. #endif
  183. uint32_t nominal_rate, // The nominal step rate for this block in step_events/sec
  184. initial_rate, // The jerk-adjusted step rate at start of block
  185. final_rate, // The minimal rate at exit
  186. acceleration_steps_per_s2; // acceleration steps/sec^2
  187. #if ENABLED(DIRECT_STEPPING)
  188. page_idx_t page_idx; // Page index used for direct stepping
  189. #endif
  190. #if HAS_CUTTER
  191. cutter_power_t cutter_power; // Power level for Spindle, Laser, etc.
  192. #endif
  193. #if HAS_FAN
  194. uint8_t fan_speed[FAN_COUNT];
  195. #endif
  196. #if ENABLED(BARICUDA)
  197. uint8_t valve_pressure, e_to_p_pressure;
  198. #endif
  199. #if HAS_WIRED_LCD
  200. uint32_t segment_time_us;
  201. #endif
  202. #if ENABLED(POWER_LOSS_RECOVERY)
  203. uint32_t sdpos;
  204. #endif
  205. #if ENABLED(LASER_POWER_INLINE)
  206. block_laser_t laser;
  207. #endif
  208. } block_t;
  209. #if ANY(LIN_ADVANCE, SCARA_FEEDRATE_SCALING, GRADIENT_MIX, LCD_SHOW_E_TOTAL)
  210. #define HAS_POSITION_FLOAT 1
  211. #endif
  212. #define BLOCK_MOD(n) ((n)&(BLOCK_BUFFER_SIZE-1))
  213. #if ENABLED(LASER_POWER_INLINE)
  214. typedef struct {
  215. /**
  216. * Laser status flags
  217. */
  218. power_status_t status;
  219. /**
  220. * Laser power: 0 or 255 in case of PWM-less laser,
  221. * or the OCR (oscillator count register) value;
  222. *
  223. * Using OCR instead of raw power, because it avoids
  224. * floating point operations during the move loop.
  225. */
  226. uint8_t power;
  227. } laser_state_t;
  228. #endif
  229. typedef struct {
  230. uint32_t max_acceleration_mm_per_s2[DISTINCT_AXES], // (mm/s^2) M201 XYZE
  231. min_segment_time_us; // (µs) M205 B
  232. float axis_steps_per_mm[DISTINCT_AXES]; // (steps) M92 XYZE - Steps per millimeter
  233. feedRate_t max_feedrate_mm_s[DISTINCT_AXES]; // (mm/s) M203 XYZE - Max speeds
  234. float acceleration, // (mm/s^2) M204 S - Normal acceleration. DEFAULT ACCELERATION for all printing moves.
  235. retract_acceleration, // (mm/s^2) M204 R - Retract acceleration. Filament pull-back and push-forward while standing still in the other axes
  236. travel_acceleration; // (mm/s^2) M204 T - Travel acceleration. DEFAULT ACCELERATION for all NON printing moves.
  237. feedRate_t min_feedrate_mm_s, // (mm/s) M205 S - Minimum linear feedrate
  238. min_travel_feedrate_mm_s; // (mm/s) M205 T - Minimum travel feedrate
  239. } planner_settings_t;
  240. #if ENABLED(IMPROVE_HOMING_RELIABILITY)
  241. struct motion_state_t {
  242. TERN(DELTA, xyz_ulong_t, xy_ulong_t) acceleration;
  243. #if HAS_CLASSIC_JERK
  244. TERN(DELTA, xyz_float_t, xy_float_t) jerk_state;
  245. #endif
  246. };
  247. #endif
  248. #if DISABLED(SKEW_CORRECTION)
  249. #define XY_SKEW_FACTOR 0
  250. #define XZ_SKEW_FACTOR 0
  251. #define YZ_SKEW_FACTOR 0
  252. #endif
  253. typedef struct {
  254. #if ENABLED(SKEW_CORRECTION_GCODE)
  255. float xy;
  256. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  257. float xz, yz;
  258. #else
  259. const float xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR;
  260. #endif
  261. #else
  262. const float xy = XY_SKEW_FACTOR,
  263. xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR;
  264. #endif
  265. } skew_factor_t;
  266. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  267. typedef IF<(BLOCK_BUFFER_SIZE > 64), uint16_t, uint8_t>::type last_move_t;
  268. #endif
  269. class Planner {
  270. public:
  271. /**
  272. * The move buffer, calculated in stepper steps
  273. *
  274. * block_buffer is a ring buffer...
  275. *
  276. * head,tail : indexes for write,read
  277. * head==tail : the buffer is empty
  278. * head!=tail : blocks are in the buffer
  279. * head==(tail-1)%size : the buffer is full
  280. *
  281. * Writer of head is Planner::buffer_segment().
  282. * Reader of tail is Stepper::isr(). Always consider tail busy / read-only
  283. */
  284. static block_t block_buffer[BLOCK_BUFFER_SIZE];
  285. static volatile uint8_t block_buffer_head, // Index of the next block to be pushed
  286. block_buffer_nonbusy, // Index of the first non busy block
  287. block_buffer_planned, // Index of the optimally planned block
  288. block_buffer_tail; // Index of the busy block, if any
  289. static uint16_t cleaning_buffer_counter; // A counter to disable queuing of blocks
  290. static uint8_t delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  291. #if ENABLED(DISTINCT_E_FACTORS)
  292. static uint8_t last_extruder; // Respond to extruder change
  293. #endif
  294. #if ENABLED(DIRECT_STEPPING)
  295. static uint32_t last_page_step_rate; // Last page step rate given
  296. static xyze_bool_t last_page_dir; // Last page direction given
  297. #endif
  298. #if HAS_EXTRUDERS
  299. static int16_t flow_percentage[EXTRUDERS]; // Extrusion factor for each extruder
  300. static float e_factor[EXTRUDERS]; // The flow percentage and volumetric multiplier combine to scale E movement
  301. #endif
  302. #if DISABLED(NO_VOLUMETRICS)
  303. 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
  304. volumetric_area_nominal, // Nominal cross-sectional area
  305. volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  306. // May be auto-adjusted by a filament width sensor
  307. #endif
  308. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  309. static float volumetric_extruder_limit[EXTRUDERS], // Maximum mm^3/sec the extruder can handle
  310. volumetric_extruder_feedrate_limit[EXTRUDERS]; // Feedrate limit (mm/s) calculated from volume limit
  311. #endif
  312. static planner_settings_t settings;
  313. #if ENABLED(LASER_POWER_INLINE)
  314. static laser_state_t laser_inline;
  315. #endif
  316. static uint32_t max_acceleration_steps_per_s2[DISTINCT_AXES]; // (steps/s^2) Derived from mm_per_s2
  317. static float mm_per_step[DISTINCT_AXES]; // Millimeters per step
  318. #if HAS_JUNCTION_DEVIATION
  319. static float junction_deviation_mm; // (mm) M205 J
  320. #if HAS_LINEAR_E_JERK
  321. static float max_e_jerk[DISTINCT_E]; // Calculated from junction_deviation_mm
  322. #endif
  323. #endif
  324. #if HAS_CLASSIC_JERK
  325. // (mm/s^2) M205 XYZ(E) - The largest speed change requiring no acceleration.
  326. static TERN(HAS_LINEAR_E_JERK, xyz_pos_t, xyze_pos_t) max_jerk;
  327. #endif
  328. #if HAS_LEVELING
  329. static bool leveling_active; // Flag that bed leveling is enabled
  330. #if ABL_PLANAR
  331. static matrix_3x3 bed_level_matrix; // Transform to compensate for bed level
  332. #endif
  333. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  334. static float z_fade_height, inverse_z_fade_height;
  335. #endif
  336. #else
  337. static constexpr bool leveling_active = false;
  338. #endif
  339. #if ENABLED(LIN_ADVANCE)
  340. static float extruder_advance_K[EXTRUDERS];
  341. #endif
  342. /**
  343. * The current position of the tool in absolute steps
  344. * Recalculated if any axis_steps_per_mm are changed by gcode
  345. */
  346. static xyze_long_t position;
  347. #if HAS_POSITION_FLOAT
  348. static xyze_pos_t position_float;
  349. #endif
  350. #if IS_KINEMATIC
  351. static xyze_pos_t position_cart;
  352. #endif
  353. static skew_factor_t skew_factor;
  354. #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT)
  355. static bool abort_on_endstop_hit;
  356. #endif
  357. #ifdef XY_FREQUENCY_LIMIT
  358. static int8_t xy_freq_limit_hz; // Minimum XY frequency setting
  359. static float xy_freq_min_speed_factor; // Minimum speed factor setting
  360. static int32_t xy_freq_min_interval_us; // Minimum segment time based on xy_freq_limit_hz
  361. static void refresh_frequency_limit() {
  362. //xy_freq_min_interval_us = xy_freq_limit_hz ?: LROUND(1000000.0f / xy_freq_limit_hz);
  363. if (xy_freq_limit_hz)
  364. xy_freq_min_interval_us = LROUND(1000000.0f / xy_freq_limit_hz);
  365. }
  366. static void set_min_speed_factor_u8(const uint8_t v255) {
  367. xy_freq_min_speed_factor = float(ui8_to_percent(v255)) / 100;
  368. }
  369. static void set_frequency_limit(const uint8_t hz) {
  370. xy_freq_limit_hz = constrain(hz, 0, 100);
  371. refresh_frequency_limit();
  372. }
  373. #endif
  374. private:
  375. /**
  376. * Speed of previous path line segment
  377. */
  378. static xyze_float_t previous_speed;
  379. /**
  380. * Nominal speed of previous path line segment (mm/s)^2
  381. */
  382. static float previous_nominal_speed_sqr;
  383. /**
  384. * Limit where 64bit math is necessary for acceleration calculation
  385. */
  386. static uint32_t acceleration_long_cutoff;
  387. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  388. static float last_fade_z;
  389. #endif
  390. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  391. // Counters to manage disabling inactive extruder steppers
  392. static last_move_t g_uc_extruder_last_move[E_STEPPERS];
  393. #endif
  394. #if HAS_WIRED_LCD
  395. volatile static uint32_t block_buffer_runtime_us; // Theoretical block buffer runtime in µs
  396. #endif
  397. public:
  398. /**
  399. * Instance Methods
  400. */
  401. Planner();
  402. void init();
  403. /**
  404. * Static (class) Methods
  405. */
  406. // Recalculate steps/s^2 accelerations based on mm/s^2 settings
  407. static void reset_acceleration_rates();
  408. /**
  409. * Recalculate 'position' and 'mm_per_step'.
  410. * Must be called whenever settings.axis_steps_per_mm changes!
  411. */
  412. static void refresh_positioning();
  413. // For an axis set the Maximum Acceleration in mm/s^2
  414. static void set_max_acceleration(const uint8_t axis, float inMaxAccelMMS2);
  415. // For an axis set the Maximum Feedrate in mm/s
  416. static void set_max_feedrate(const uint8_t axis, float inMaxFeedrateMMS);
  417. // For an axis set the Maximum Jerk (instant change) in mm/s
  418. #if HAS_CLASSIC_JERK
  419. static void set_max_jerk(const AxisEnum axis, float inMaxJerkMMS);
  420. #else
  421. static void set_max_jerk(const AxisEnum, const_float_t) {}
  422. #endif
  423. #if HAS_EXTRUDERS
  424. FORCE_INLINE static void refresh_e_factor(const uint8_t e) {
  425. e_factor[e] = flow_percentage[e] * 0.01f * TERN(NO_VOLUMETRICS, 1.0f, volumetric_multiplier[e]);
  426. }
  427. static void set_flow(const uint8_t e, const int16_t flow) {
  428. flow_percentage[e] = flow;
  429. refresh_e_factor(e);
  430. }
  431. #endif
  432. // Manage fans, paste pressure, etc.
  433. static void check_axes_activity();
  434. // Apply fan speeds
  435. #if HAS_FAN
  436. static void sync_fan_speeds(uint8_t (&fan_speed)[FAN_COUNT]);
  437. #if FAN_KICKSTART_TIME
  438. static void kickstart_fan(uint8_t (&fan_speed)[FAN_COUNT], const millis_t &ms, const uint8_t f);
  439. #else
  440. FORCE_INLINE static void kickstart_fan(uint8_t (&)[FAN_COUNT], const millis_t &, const uint8_t) {}
  441. #endif
  442. #endif
  443. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  444. void apply_filament_width_sensor(const int8_t encoded_ratio);
  445. static float volumetric_percent(const bool vol) {
  446. return 100.0f * (vol
  447. ? volumetric_area_nominal / volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM]
  448. : volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM]
  449. );
  450. }
  451. #endif
  452. #if ENABLED(IMPROVE_HOMING_RELIABILITY)
  453. void enable_stall_prevention(const bool onoff);
  454. #endif
  455. #if DISABLED(NO_VOLUMETRICS)
  456. // Update multipliers based on new diameter measurements
  457. static void calculate_volumetric_multipliers();
  458. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  459. // Update pre calculated extruder feedrate limits based on volumetric values
  460. static void calculate_volumetric_extruder_limit(const uint8_t e);
  461. static void calculate_volumetric_extruder_limits();
  462. #endif
  463. FORCE_INLINE static void set_filament_size(const uint8_t e, const_float_t v) {
  464. filament_size[e] = v;
  465. if (v > 0) volumetric_area_nominal = CIRCLE_AREA(v * 0.5); //TODO: should it be per extruder
  466. // make sure all extruders have some sane value for the filament size
  467. LOOP_L_N(i, COUNT(filament_size))
  468. if (!filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  469. }
  470. #endif
  471. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  472. FORCE_INLINE static void set_volumetric_extruder_limit(const uint8_t e, const_float_t v) {
  473. volumetric_extruder_limit[e] = v;
  474. calculate_volumetric_extruder_limit(e);
  475. }
  476. #endif
  477. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  478. /**
  479. * Get the Z leveling fade factor based on the given Z height,
  480. * re-calculating only when needed.
  481. *
  482. * Returns 1.0 if planner.z_fade_height is 0.0.
  483. * Returns 0.0 if Z is past the specified 'Fade Height'.
  484. */
  485. static float fade_scaling_factor_for_z(const_float_t rz) {
  486. static float z_fade_factor = 1;
  487. if (!z_fade_height) return 1;
  488. if (rz >= z_fade_height) return 0;
  489. if (last_fade_z != rz) {
  490. last_fade_z = rz;
  491. z_fade_factor = 1 - rz * inverse_z_fade_height;
  492. }
  493. return z_fade_factor;
  494. }
  495. FORCE_INLINE static void force_fade_recalc() { last_fade_z = -999.999f; }
  496. FORCE_INLINE static void set_z_fade_height(const_float_t zfh) {
  497. z_fade_height = zfh > 0 ? zfh : 0;
  498. inverse_z_fade_height = RECIPROCAL(z_fade_height);
  499. force_fade_recalc();
  500. }
  501. FORCE_INLINE static bool leveling_active_at_z(const_float_t rz) {
  502. return !z_fade_height || rz < z_fade_height;
  503. }
  504. #else
  505. FORCE_INLINE static float fade_scaling_factor_for_z(const_float_t) { return 1; }
  506. FORCE_INLINE static bool leveling_active_at_z(const_float_t) { return true; }
  507. #endif
  508. #if ENABLED(SKEW_CORRECTION)
  509. FORCE_INLINE static void skew(float &cx, float &cy, const_float_t cz) {
  510. if (COORDINATE_OKAY(cx, X_MIN_POS + 1, X_MAX_POS) && COORDINATE_OKAY(cy, Y_MIN_POS + 1, Y_MAX_POS)) {
  511. const float sx = cx - cy * skew_factor.xy - cz * (skew_factor.xz - (skew_factor.xy * skew_factor.yz)),
  512. sy = cy - cz * skew_factor.yz;
  513. if (COORDINATE_OKAY(sx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(sy, Y_MIN_POS, Y_MAX_POS)) {
  514. cx = sx; cy = sy;
  515. }
  516. }
  517. }
  518. FORCE_INLINE static void skew(xyz_pos_t &raw) { skew(raw.x, raw.y, raw.z); }
  519. FORCE_INLINE static void unskew(float &cx, float &cy, const_float_t cz) {
  520. if (COORDINATE_OKAY(cx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(cy, Y_MIN_POS, Y_MAX_POS)) {
  521. const float sx = cx + cy * skew_factor.xy + cz * skew_factor.xz,
  522. sy = cy + cz * skew_factor.yz;
  523. if (COORDINATE_OKAY(sx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(sy, Y_MIN_POS, Y_MAX_POS)) {
  524. cx = sx; cy = sy;
  525. }
  526. }
  527. }
  528. FORCE_INLINE static void unskew(xyz_pos_t &raw) { unskew(raw.x, raw.y, raw.z); }
  529. #endif // SKEW_CORRECTION
  530. #if HAS_LEVELING
  531. /**
  532. * Apply leveling to transform a cartesian position
  533. * as it will be given to the planner and steppers.
  534. */
  535. static void apply_leveling(xyz_pos_t &raw);
  536. static void unapply_leveling(xyz_pos_t &raw);
  537. FORCE_INLINE static void force_unapply_leveling(xyz_pos_t &raw) {
  538. leveling_active = true;
  539. unapply_leveling(raw);
  540. leveling_active = false;
  541. }
  542. #else
  543. FORCE_INLINE static void apply_leveling(xyz_pos_t&) {}
  544. FORCE_INLINE static void unapply_leveling(xyz_pos_t&) {}
  545. #endif
  546. #if ENABLED(FWRETRACT)
  547. static void apply_retract(float &rz, float &e);
  548. FORCE_INLINE static void apply_retract(xyze_pos_t &raw) { apply_retract(raw.z, raw.e); }
  549. static void unapply_retract(float &rz, float &e);
  550. FORCE_INLINE static void unapply_retract(xyze_pos_t &raw) { unapply_retract(raw.z, raw.e); }
  551. #endif
  552. #if HAS_POSITION_MODIFIERS
  553. FORCE_INLINE static void apply_modifiers(xyze_pos_t &pos, bool leveling=ENABLED(PLANNER_LEVELING)) {
  554. TERN_(SKEW_CORRECTION, skew(pos));
  555. if (leveling) apply_leveling(pos);
  556. TERN_(FWRETRACT, apply_retract(pos));
  557. }
  558. FORCE_INLINE static void unapply_modifiers(xyze_pos_t &pos, bool leveling=ENABLED(PLANNER_LEVELING)) {
  559. TERN_(FWRETRACT, unapply_retract(pos));
  560. if (leveling) unapply_leveling(pos);
  561. TERN_(SKEW_CORRECTION, unskew(pos));
  562. }
  563. #endif // HAS_POSITION_MODIFIERS
  564. // Number of moves currently in the planner including the busy block, if any
  565. FORCE_INLINE static uint8_t movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_tail); }
  566. // Number of nonbusy moves currently in the planner
  567. FORCE_INLINE static uint8_t nonbusy_movesplanned() { return BLOCK_MOD(block_buffer_head - block_buffer_nonbusy); }
  568. // Remove all blocks from the buffer
  569. FORCE_INLINE static void clear_block_buffer() { block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail = 0; }
  570. // Check if movement queue is full
  571. FORCE_INLINE static bool is_full() { return block_buffer_tail == next_block_index(block_buffer_head); }
  572. // Get count of movement slots free
  573. FORCE_INLINE static uint8_t moves_free() { return BLOCK_BUFFER_SIZE - 1 - movesplanned(); }
  574. /**
  575. * Planner::get_next_free_block
  576. *
  577. * - Get the next head indices (passed by reference)
  578. * - Wait for the number of spaces to open up in the planner
  579. * - Return the first head block
  580. */
  581. FORCE_INLINE static block_t* get_next_free_block(uint8_t &next_buffer_head, const uint8_t count=1) {
  582. // Wait until there are enough slots free
  583. while (moves_free() < count) { idle(); }
  584. // Return the first available block
  585. next_buffer_head = next_block_index(block_buffer_head);
  586. return &block_buffer[block_buffer_head];
  587. }
  588. /**
  589. * Planner::_buffer_steps
  590. *
  591. * Add a new linear movement to the buffer (in terms of steps).
  592. *
  593. * target - target position in steps units
  594. * fr_mm_s - (target) speed of the move
  595. * extruder - target extruder
  596. * millimeters - the length of the movement, if known
  597. *
  598. * Returns true if movement was buffered, false otherwise
  599. */
  600. static bool _buffer_steps(const xyze_long_t &target
  601. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  602. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  603. , feedRate_t fr_mm_s, const uint8_t extruder, const_float_t millimeters=0.0
  604. );
  605. /**
  606. * Planner::_populate_block
  607. *
  608. * Fills a new linear movement in the block (in terms of steps).
  609. *
  610. * target - target position in steps units
  611. * fr_mm_s - (target) speed of the move
  612. * extruder - target extruder
  613. * millimeters - the length of the movement, if known
  614. *
  615. * Returns true is movement is acceptable, false otherwise
  616. */
  617. static bool _populate_block(block_t * const block, bool split_move, const xyze_long_t &target
  618. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  619. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  620. , feedRate_t fr_mm_s, const uint8_t extruder, const_float_t millimeters=0.0
  621. );
  622. /**
  623. * Planner::buffer_sync_block
  624. * Add a block to the buffer that just updates the position or in
  625. * case of LASER_SYNCHRONOUS_M106_M107 the fan pwm
  626. */
  627. static void buffer_sync_block(
  628. TERN_(LASER_SYNCHRONOUS_M106_M107, uint8_t sync_flag=BLOCK_FLAG_SYNC_POSITION)
  629. );
  630. #if IS_KINEMATIC
  631. private:
  632. // Allow do_homing_move to access internal functions, such as buffer_segment.
  633. friend void do_homing_move(const AxisEnum, const float, const feedRate_t, const bool);
  634. #endif
  635. /**
  636. * Planner::buffer_segment
  637. *
  638. * Add a new linear movement to the buffer in axis units.
  639. *
  640. * Leveling and kinematics should be applied ahead of calling this.
  641. *
  642. * a,b,c,e - target positions in mm and/or degrees
  643. * fr_mm_s - (target) speed of the move
  644. * extruder - target extruder
  645. * millimeters - the length of the movement, if known
  646. */
  647. static bool buffer_segment(const abce_pos_t &abce
  648. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  649. , const_feedRate_t fr_mm_s, const uint8_t extruder=active_extruder, const_float_t millimeters=0.0
  650. );
  651. public:
  652. /**
  653. * Add a new linear movement to the buffer.
  654. * The target is cartesian. It's translated to
  655. * delta/scara if needed.
  656. *
  657. * cart - target position in mm or degrees
  658. * fr_mm_s - (target) speed of the move (mm/s)
  659. * extruder - target extruder
  660. * millimeters - the length of the movement, if known
  661. * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
  662. */
  663. static bool buffer_line(const xyze_pos_t &cart, const_feedRate_t fr_mm_s, const uint8_t extruder=active_extruder, const float millimeters=0.0
  664. OPTARG(SCARA_FEEDRATE_SCALING, const_float_t inv_duration=0.0)
  665. );
  666. #if ENABLED(DIRECT_STEPPING)
  667. static void buffer_page(const page_idx_t page_idx, const uint8_t extruder, const uint16_t num_steps);
  668. #endif
  669. /**
  670. * Set the planner.position and individual stepper positions.
  671. * Used by G92, G28, G29, and other procedures.
  672. *
  673. * The supplied position is in the cartesian coordinate space and is
  674. * translated in to machine space as needed. Modifiers such as leveling
  675. * and skew are also applied.
  676. *
  677. * Multiplies by axis_steps_per_mm[] and does necessary conversion
  678. * for COREXY / COREXZ / COREYZ to set the corresponding stepper positions.
  679. *
  680. * Clears previous speed values.
  681. */
  682. static void set_position_mm(const xyze_pos_t &xyze);
  683. #if HAS_EXTRUDERS
  684. static void set_e_position_mm(const_float_t e);
  685. #endif
  686. /**
  687. * Set the planner.position and individual stepper positions.
  688. *
  689. * The supplied position is in machine space, and no additional
  690. * conversions are applied.
  691. */
  692. static void set_machine_position_mm(const abce_pos_t &abce);
  693. /**
  694. * Get an axis position according to stepper position(s)
  695. * For CORE machines apply translation from ABC to XYZ.
  696. */
  697. static float get_axis_position_mm(const AxisEnum axis);
  698. static abce_pos_t get_axis_positions_mm() {
  699. const abce_pos_t out = LOGICAL_AXIS_ARRAY(
  700. get_axis_position_mm(E_AXIS),
  701. get_axis_position_mm(A_AXIS), get_axis_position_mm(B_AXIS), get_axis_position_mm(C_AXIS),
  702. get_axis_position_mm(I_AXIS), get_axis_position_mm(J_AXIS), get_axis_position_mm(K_AXIS)
  703. );
  704. return out;
  705. }
  706. // SCARA AB axes are in degrees, not mm
  707. #if IS_SCARA
  708. FORCE_INLINE static float get_axis_position_degrees(const AxisEnum axis) { return get_axis_position_mm(axis); }
  709. #endif
  710. // Called to force a quick stop of the machine (for example, when
  711. // a Full Shutdown is required, or when endstops are hit)
  712. static void quick_stop();
  713. #if ENABLED(REALTIME_REPORTING_COMMANDS)
  714. // Force a quick pause of the machine (e.g., when a pause is required in the middle of move).
  715. // NOTE: Hard-stops will lose steps so encoders are highly recommended if using these!
  716. static void quick_pause();
  717. static void quick_resume();
  718. #endif
  719. // Called when an endstop is triggered. Causes the machine to stop immediately
  720. static void endstop_triggered(const AxisEnum axis);
  721. // Triggered position of an axis in mm (not core-savvy)
  722. static float triggered_position_mm(const AxisEnum axis);
  723. // Blocks are queued, or we're running out moves, or the closed loop controller is waiting
  724. static bool busy() {
  725. return (has_blocks_queued() || cleaning_buffer_counter
  726. || TERN0(EXTERNAL_CLOSED_LOOP_CONTROLLER, CLOSED_LOOP_WAITING())
  727. );
  728. }
  729. // Block until all buffered steps are executed / cleaned
  730. static void synchronize();
  731. // Wait for moves to finish and disable all steppers
  732. static void finish_and_disable();
  733. // Periodic handler to manage the cleaning buffer counter
  734. // Called from the Temperature ISR at ~1kHz
  735. static void isr() { if (cleaning_buffer_counter) --cleaning_buffer_counter; }
  736. /**
  737. * Does the buffer have any blocks queued?
  738. */
  739. FORCE_INLINE static bool has_blocks_queued() { return (block_buffer_head != block_buffer_tail); }
  740. /**
  741. * Get the current block for processing
  742. * and mark the block as busy.
  743. * Return nullptr if the buffer is empty
  744. * or if there is a first-block delay.
  745. *
  746. * WARNING: Called from Stepper ISR context!
  747. */
  748. static block_t* get_current_block();
  749. /**
  750. * "Release" the current block so its slot can be reused.
  751. * Called when the current block is no longer needed.
  752. */
  753. FORCE_INLINE static void release_current_block() {
  754. if (has_blocks_queued())
  755. block_buffer_tail = next_block_index(block_buffer_tail);
  756. }
  757. #if HAS_WIRED_LCD
  758. static uint16_t block_buffer_runtime();
  759. static void clear_block_buffer_runtime();
  760. #endif
  761. #if ENABLED(AUTOTEMP)
  762. static celsius_t autotemp_min, autotemp_max;
  763. static float autotemp_factor;
  764. static bool autotemp_enabled;
  765. static void autotemp_update();
  766. static void autotemp_M104_M109();
  767. static void autotemp_task();
  768. #endif
  769. #if HAS_LINEAR_E_JERK
  770. FORCE_INLINE static void recalculate_max_e_jerk() {
  771. const float prop = junction_deviation_mm * SQRT(0.5) / (1.0f - SQRT(0.5));
  772. LOOP_L_N(i, EXTRUDERS)
  773. max_e_jerk[E_INDEX_N(i)] = SQRT(prop * settings.max_acceleration_mm_per_s2[E_INDEX_N(i)]);
  774. }
  775. #endif
  776. private:
  777. #if ENABLED(AUTOTEMP)
  778. #if ENABLED(AUTOTEMP_PROPORTIONAL)
  779. static void _autotemp_update_from_hotend();
  780. #else
  781. static void _autotemp_update_from_hotend() {}
  782. #endif
  783. #endif
  784. /**
  785. * Get the index of the next / previous block in the ring buffer
  786. */
  787. static constexpr uint8_t next_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index + 1); }
  788. static constexpr uint8_t prev_block_index(const uint8_t block_index) { return BLOCK_MOD(block_index - 1); }
  789. /**
  790. * Calculate the distance (not time) it takes to accelerate
  791. * from initial_rate to target_rate using the given acceleration:
  792. */
  793. static float estimate_acceleration_distance(const_float_t initial_rate, const_float_t target_rate, const_float_t accel) {
  794. if (accel == 0) return 0; // accel was 0, set acceleration distance to 0
  795. return (sq(target_rate) - sq(initial_rate)) / (accel * 2);
  796. }
  797. /**
  798. * Return the point at which you must start braking (at the rate of -'accel') if
  799. * you start at 'initial_rate', accelerate (until reaching the point), and want to end at
  800. * 'final_rate' after traveling 'distance'.
  801. *
  802. * This is used to compute the intersection point between acceleration and deceleration
  803. * in cases where the "trapezoid" has no plateau (i.e., never reaches maximum speed)
  804. */
  805. static float intersection_distance(const_float_t initial_rate, const_float_t final_rate, const_float_t accel, const_float_t distance) {
  806. if (accel == 0) return 0; // accel was 0, set intersection distance to 0
  807. return (accel * 2 * distance - sq(initial_rate) + sq(final_rate)) / (accel * 4);
  808. }
  809. /**
  810. * Calculate the maximum allowable speed squared at this point, in order
  811. * to reach 'target_velocity_sqr' using 'acceleration' within a given
  812. * 'distance'.
  813. */
  814. static float max_allowable_speed_sqr(const_float_t accel, const_float_t target_velocity_sqr, const_float_t distance) {
  815. return target_velocity_sqr - 2 * accel * distance;
  816. }
  817. #if ENABLED(S_CURVE_ACCELERATION)
  818. /**
  819. * Calculate the speed reached given initial speed, acceleration and distance
  820. */
  821. static float final_speed(const_float_t initial_velocity, const_float_t accel, const_float_t distance) {
  822. return SQRT(sq(initial_velocity) + 2 * accel * distance);
  823. }
  824. #endif
  825. static void calculate_trapezoid_for_block(block_t * const block, const_float_t entry_factor, const_float_t exit_factor);
  826. static void reverse_pass_kernel(block_t * const current, const block_t * const next);
  827. static void forward_pass_kernel(const block_t * const previous, block_t * const current, uint8_t block_index);
  828. static void reverse_pass();
  829. static void forward_pass();
  830. static void recalculate_trapezoids();
  831. static void recalculate();
  832. #if HAS_JUNCTION_DEVIATION
  833. FORCE_INLINE static void normalize_junction_vector(xyze_float_t &vector) {
  834. float magnitude_sq = 0;
  835. LOOP_LOGICAL_AXES(idx) if (vector[idx]) magnitude_sq += sq(vector[idx]);
  836. vector *= RSQRT(magnitude_sq);
  837. }
  838. FORCE_INLINE static float limit_value_by_axis_maximum(const_float_t max_value, xyze_float_t &unit_vec) {
  839. float limit_value = max_value;
  840. LOOP_LOGICAL_AXES(idx) {
  841. if (unit_vec[idx]) {
  842. if (limit_value * ABS(unit_vec[idx]) > settings.max_acceleration_mm_per_s2[idx])
  843. limit_value = ABS(settings.max_acceleration_mm_per_s2[idx] / unit_vec[idx]);
  844. }
  845. }
  846. return limit_value;
  847. }
  848. #endif // !CLASSIC_JERK
  849. };
  850. #define PLANNER_XY_FEEDRATE() _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS])
  851. extern Planner planner;