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

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