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

planner.cpp 111KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830
  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. /**
  23. * planner.cpp
  24. *
  25. * Buffer movement commands and manage the acceleration profile plan
  26. *
  27. * Derived from Grbl
  28. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  29. *
  30. * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
  31. *
  32. *
  33. * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  34. *
  35. * s == speed, a == acceleration, t == time, d == distance
  36. *
  37. * Basic definitions:
  38. * Speed[s_, a_, t_] := s + (a*t)
  39. * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  40. *
  41. * Distance to reach a specific speed with a constant acceleration:
  42. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  43. * d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  44. *
  45. * Speed after a given distance of travel with constant acceleration:
  46. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  47. * m -> Sqrt[2 a d + s^2]
  48. *
  49. * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  50. *
  51. * When to start braking (di) to reach a specified destination speed (s2) after accelerating
  52. * from initial speed s1 without ever stopping at a plateau:
  53. * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  54. * di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  55. *
  56. * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  57. *
  58. * --
  59. *
  60. * The fast inverse function needed for Bézier interpolation for AVR
  61. * was designed, written and tested by Eduardo José Tagle on April/2018
  62. */
  63. #include "planner.h"
  64. #include "stepper.h"
  65. #include "motion.h"
  66. #include "temperature.h"
  67. #include "../lcd/ultralcd.h"
  68. #include "../core/language.h"
  69. #include "../gcode/parser.h"
  70. #include "../Marlin.h"
  71. #if HAS_LEVELING
  72. #include "../feature/bedlevel/bedlevel.h"
  73. #endif
  74. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  75. #include "../feature/filwidth.h"
  76. #endif
  77. #if ENABLED(BARICUDA)
  78. #include "../feature/baricuda.h"
  79. #endif
  80. #if ENABLED(MIXING_EXTRUDER)
  81. #include "../feature/mixing.h"
  82. #endif
  83. #if ENABLED(AUTO_POWER_CONTROL)
  84. #include "../feature/power.h"
  85. #endif
  86. #if ENABLED(BACKLASH_COMPENSATION)
  87. #include "../feature/backlash.h"
  88. #endif
  89. #if ENABLED(POWER_LOSS_RECOVERY)
  90. #include "../feature/power_loss_recovery.h"
  91. #endif
  92. // Delay for delivery of first block to the stepper ISR, if the queue contains 2 or
  93. // fewer movements. The delay is measured in milliseconds, and must be less than 250ms
  94. #define BLOCK_DELAY_FOR_1ST_MOVE 100
  95. Planner planner;
  96. // public:
  97. /**
  98. * A ring buffer of moves described in steps
  99. */
  100. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  101. volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
  102. Planner::block_buffer_nonbusy, // Index of the first non-busy block
  103. Planner::block_buffer_planned, // Index of the optimally planned block
  104. Planner::block_buffer_tail; // Index of the busy block, if any
  105. uint16_t Planner::cleaning_buffer_counter; // A counter to disable queuing of blocks
  106. uint8_t Planner::delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  107. planner_settings_t Planner::settings; // Initialized by settings.load()
  108. uint32_t Planner::max_acceleration_steps_per_s2[XYZE_N]; // (steps/s^2) Derived from mm_per_s2
  109. float Planner::steps_to_mm[XYZE_N]; // (mm) Millimeters per step
  110. #if ENABLED(JUNCTION_DEVIATION)
  111. float Planner::junction_deviation_mm; // (mm) M205 J
  112. #if ENABLED(LIN_ADVANCE)
  113. #if ENABLED(DISTINCT_E_FACTORS)
  114. float Planner::max_e_jerk[EXTRUDERS]; // Calculated from junction_deviation_mm
  115. #else
  116. float Planner::max_e_jerk;
  117. #endif
  118. #endif
  119. #endif
  120. #if HAS_CLASSIC_JERK
  121. #if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
  122. float Planner::max_jerk[XYZ]; // (mm/s^2) M205 XYZ - The largest speed change requiring no acceleration.
  123. #else
  124. float Planner::max_jerk[XYZE]; // (mm/s^2) M205 XYZE - The largest speed change requiring no acceleration.
  125. #endif
  126. #endif
  127. #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT)
  128. bool Planner::abort_on_endstop_hit = false;
  129. #endif
  130. #if ENABLED(DISTINCT_E_FACTORS)
  131. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  132. #endif
  133. #if EXTRUDERS
  134. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  135. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement
  136. #endif
  137. #if DISABLED(NO_VOLUMETRICS)
  138. float Planner::filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
  139. Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area
  140. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  141. #endif
  142. #if HAS_LEVELING
  143. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  144. #if ABL_PLANAR
  145. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  146. #endif
  147. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  148. float Planner::z_fade_height, // Initialized by settings.load()
  149. Planner::inverse_z_fade_height,
  150. Planner::last_fade_z;
  151. #endif
  152. #else
  153. constexpr bool Planner::leveling_active;
  154. #endif
  155. skew_factor_t Planner::skew_factor; // Initialized by settings.load()
  156. #if ENABLED(AUTOTEMP)
  157. float Planner::autotemp_max = 250,
  158. Planner::autotemp_min = 210,
  159. Planner::autotemp_factor = 0.1f;
  160. bool Planner::autotemp_enabled = false;
  161. #endif
  162. // private:
  163. int32_t Planner::position[NUM_AXIS] = { 0 };
  164. uint32_t Planner::cutoff_long;
  165. float Planner::previous_speed[NUM_AXIS],
  166. Planner::previous_nominal_speed_sqr;
  167. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  168. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  169. #endif
  170. #ifdef XY_FREQUENCY_LIMIT
  171. // Old direction bits. Used for speed calculations
  172. unsigned char Planner::old_direction_bits = 0;
  173. // Segment times (in µs). Used for speed calculations
  174. uint32_t Planner::axis_segment_time_us[2][3] = { { MAX_FREQ_TIME_US + 1, 0, 0 }, { MAX_FREQ_TIME_US + 1, 0, 0 } };
  175. #endif
  176. #if ENABLED(LIN_ADVANCE)
  177. float Planner::extruder_advance_K[EXTRUDERS]; // Initialized by settings.load()
  178. #endif
  179. #if HAS_POSITION_FLOAT
  180. float Planner::position_float[XYZE]; // Needed for accurate maths. Steps cannot be used!
  181. #endif
  182. #if IS_KINEMATIC
  183. float Planner::position_cart[XYZE];
  184. #endif
  185. #if HAS_SPI_LCD
  186. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  187. #endif
  188. /**
  189. * Class and Instance Methods
  190. */
  191. Planner::Planner() { init(); }
  192. void Planner::init() {
  193. ZERO(position);
  194. #if HAS_POSITION_FLOAT
  195. ZERO(position_float);
  196. #endif
  197. #if IS_KINEMATIC
  198. ZERO(position_cart);
  199. #endif
  200. ZERO(previous_speed);
  201. previous_nominal_speed_sqr = 0;
  202. #if ABL_PLANAR
  203. bed_level_matrix.set_to_identity();
  204. #endif
  205. clear_block_buffer();
  206. delay_before_delivering = 0;
  207. }
  208. #if ENABLED(S_CURVE_ACCELERATION)
  209. #ifdef __AVR__
  210. /**
  211. * This routine returns 0x1000000 / d, getting the inverse as fast as possible.
  212. * A fast-converging iterative Newton-Raphson method can reach full precision in
  213. * just 1 iteration, and takes 211 cycles (worst case; the mean case is less, up
  214. * to 30 cycles for small divisors), instead of the 500 cycles a normal division
  215. * would take.
  216. *
  217. * Inspired by the following page:
  218. * https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
  219. *
  220. * Suppose we want to calculate floor(2 ^ k / B) where B is a positive integer
  221. * Then, B must be <= 2^k, otherwise, the quotient is 0.
  222. *
  223. * The Newton - Raphson iteration for x = B / 2 ^ k yields:
  224. * q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
  225. *
  226. * This can be rearranged to:
  227. * q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
  228. *
  229. * Each iteration requires only integer multiplications and bit shifts.
  230. * It doesn't necessarily converge to floor(2 ^ k / B) but in the worst case
  231. * it eventually alternates between floor(2 ^ k / B) and ceil(2 ^ k / B).
  232. * So it checks for this case and extracts floor(2 ^ k / B).
  233. *
  234. * A simple but important optimization for this approach is to truncate
  235. * multiplications (i.e., calculate only the higher bits of the product) in the
  236. * early iterations of the Newton - Raphson method. This is done so the results
  237. * of the early iterations are far from the quotient. Then it doesn't matter if
  238. * they are done inaccurately.
  239. * It's important to pick a good starting value for x. Knowing how many
  240. * digits the divisor has, it can be estimated:
  241. *
  242. * 2^k / x = 2 ^ log2(2^k / x)
  243. * 2^k / x = 2 ^(log2(2^k)-log2(x))
  244. * 2^k / x = 2 ^(k*log2(2)-log2(x))
  245. * 2^k / x = 2 ^ (k-log2(x))
  246. * 2^k / x >= 2 ^ (k-floor(log2(x)))
  247. * floor(log2(x)) is simply the index of the most significant bit set.
  248. *
  249. * If this estimation can be improved even further the number of iterations can be
  250. * reduced a lot, saving valuable execution time.
  251. * The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
  252. * Research, Silicon Valley,August 26, 2008, available at
  253. * https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
  254. * suggests, for its integer division algorithm, using a table to supply the first
  255. * 8 bits of precision, then, due to the quadratic convergence nature of the
  256. * Newton-Raphon iteration, just 2 iterations should be enough to get maximum
  257. * precision of the division.
  258. * By precomputing values of inverses for small denominator values, just one
  259. * Newton-Raphson iteration is enough to reach full precision.
  260. * This code uses the top 9 bits of the denominator as index.
  261. *
  262. * The AVR assembly function implements this C code using the data below:
  263. *
  264. * // For small divisors, it is best to directly retrieve the results
  265. * if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  266. *
  267. * // Compute initial estimation of 0x1000000/x -
  268. * // Get most significant bit set on divider
  269. * uint8_t idx = 0;
  270. * uint32_t nr = d;
  271. * if (!(nr & 0xFF0000)) {
  272. * nr <<= 8; idx += 8;
  273. * if (!(nr & 0xFF0000)) { nr <<= 8; idx += 8; }
  274. * }
  275. * if (!(nr & 0xF00000)) { nr <<= 4; idx += 4; }
  276. * if (!(nr & 0xC00000)) { nr <<= 2; idx += 2; }
  277. * if (!(nr & 0x800000)) { nr <<= 1; idx += 1; }
  278. *
  279. * // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
  280. * uint32_t tidx = nr >> 15, // top 9 bits. bit8 is always set
  281. * ie = inv_tab[tidx & 0xFF] + 256, // Get the table value. bit9 is always set
  282. * x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place
  283. *
  284. * x = uint32_t((x * uint64_t(_BV(25) - x * d)) >> 24); // Refine estimation by newton-raphson. 1 iteration is enough
  285. * const uint32_t r = _BV(24) - x * d; // Estimate remainder
  286. * if (r >= d) x++; // Check whether to adjust result
  287. * return uint32_t(x); // x holds the proper estimation
  288. *
  289. */
  290. static uint32_t get_period_inverse(uint32_t d) {
  291. static const uint8_t inv_tab[256] PROGMEM = {
  292. 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  293. 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  294. 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  295. 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  296. 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  297. 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  298. 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  299. 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  300. 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  301. 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  302. 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  303. 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  304. 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  305. 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  306. 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  307. 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  308. };
  309. // For small denominators, it is cheaper to directly store the result.
  310. // For bigger ones, just ONE Newton-Raphson iteration is enough to get
  311. // maximum precision we need
  312. static const uint32_t small_inv_tab[111] PROGMEM = {
  313. 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  314. 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  315. 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  316. 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  317. 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  318. 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  319. 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  320. };
  321. // For small divisors, it is best to directly retrieve the results
  322. if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  323. uint8_t r8 = d & 0xFF,
  324. r9 = (d >> 8) & 0xFF,
  325. r10 = (d >> 16) & 0xFF,
  326. r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
  327. const uint8_t* ptab = inv_tab;
  328. __asm__ __volatile__(
  329. // %8:%7:%6 = interval
  330. // r31:r30: MUST be those registers, and they must point to the inv_tab
  331. A("clr %13") // %13 = 0
  332. // Now we must compute
  333. // result = 0xFFFFFF / d
  334. // %8:%7:%6 = interval
  335. // %16:%15:%14 = nr
  336. // %13 = 0
  337. // A plain division of 24x24 bits should take 388 cycles to complete. We will
  338. // use Newton-Raphson for the calculation, and will strive to get way less cycles
  339. // for the same result - Using C division, it takes 500cycles to complete .
  340. A("clr %3") // idx = 0
  341. A("mov %14,%6")
  342. A("mov %15,%7")
  343. A("mov %16,%8") // nr = interval
  344. A("tst %16") // nr & 0xFF0000 == 0 ?
  345. A("brne 2f") // No, skip this
  346. A("mov %16,%15")
  347. A("mov %15,%14") // nr <<= 8, %14 not needed
  348. A("subi %3,-8") // idx += 8
  349. A("tst %16") // nr & 0xFF0000 == 0 ?
  350. A("brne 2f") // No, skip this
  351. A("mov %16,%15") // nr <<= 8, %14 not needed
  352. A("clr %15") // We clear %14
  353. A("subi %3,-8") // idx += 8
  354. // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
  355. L("2")
  356. A("cpi %16,0x10") // (nr & 0xF00000) == 0 ?
  357. A("brcc 3f") // No, skip this
  358. A("swap %15") // Swap nibbles
  359. A("swap %16") // Swap nibbles. Low nibble is 0
  360. A("mov %14, %15")
  361. A("andi %14,0x0F") // Isolate low nibble
  362. A("andi %15,0xF0") // Keep proper nibble in %15
  363. A("or %16, %14") // %16:%15 <<= 4
  364. A("subi %3,-4") // idx += 4
  365. L("3")
  366. A("cpi %16,0x40") // (nr & 0xC00000) == 0 ?
  367. A("brcc 4f") // No, skip this
  368. A("add %15,%15")
  369. A("adc %16,%16")
  370. A("add %15,%15")
  371. A("adc %16,%16") // %16:%15 <<= 2
  372. A("subi %3,-2") // idx += 2
  373. L("4")
  374. A("cpi %16,0x80") // (nr & 0x800000) == 0 ?
  375. A("brcc 5f") // No, skip this
  376. A("add %15,%15")
  377. A("adc %16,%16") // %16:%15 <<= 1
  378. A("inc %3") // idx += 1
  379. // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
  380. // we have at least 9 MSBits available to enter the initial estimation table
  381. L("5")
  382. A("add %15,%15")
  383. A("adc %16,%16") // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table)
  384. A("add r30,%16") // Only use top 8 bits
  385. A("adc r31,%13") // r31:r30 = inv_tab + (tidx)
  386. A("lpm %14, Z") // %14 = inv_tab[tidx]
  387. A("ldi %15, 1") // %15 = 1 %15:%14 = inv_tab[tidx] + 256
  388. // We must scale the approximation to the proper place
  389. A("clr %16") // %16 will always be 0 here
  390. A("subi %3,8") // idx == 8 ?
  391. A("breq 6f") // yes, no need to scale
  392. A("brcs 7f") // If C=1, means idx < 8, result was negative!
  393. // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
  394. A("sbrs %3,0") // shift by 1bit position?
  395. A("rjmp 8f") // No
  396. A("add %14,%14")
  397. A("adc %15,%15") // %15:16 <<= 1
  398. L("8")
  399. A("sbrs %3,1") // shift by 2bit position?
  400. A("rjmp 9f") // No
  401. A("add %14,%14")
  402. A("adc %15,%15")
  403. A("add %14,%14")
  404. A("adc %15,%15") // %15:16 <<= 1
  405. L("9")
  406. A("sbrs %3,2") // shift by 4bits position?
  407. A("rjmp 16f") // No
  408. A("swap %15") // Swap nibbles. lo nibble of %15 will always be 0
  409. A("swap %14") // Swap nibbles
  410. A("mov %12,%14")
  411. A("andi %12,0x0F") // isolate low nibble
  412. A("andi %14,0xF0") // and clear it
  413. A("or %15,%12") // %15:%16 <<= 4
  414. L("16")
  415. A("sbrs %3,3") // shift by 8bits position?
  416. A("rjmp 6f") // No, we are done
  417. A("mov %16,%15")
  418. A("mov %15,%14")
  419. A("clr %14")
  420. A("jmp 6f")
  421. // idx < 8, now %3 = idx - 8. Get the count of bits
  422. L("7")
  423. A("neg %3") // %3 = -idx = count of bits to move right. idx range:[1...8]
  424. A("sbrs %3,0") // shift by 1 bit position ?
  425. A("rjmp 10f") // No, skip it
  426. A("asr %15") // (bit7 is always 0 here)
  427. A("ror %14")
  428. L("10")
  429. A("sbrs %3,1") // shift by 2 bit position ?
  430. A("rjmp 11f") // No, skip it
  431. A("asr %15") // (bit7 is always 0 here)
  432. A("ror %14")
  433. A("asr %15") // (bit7 is always 0 here)
  434. A("ror %14")
  435. L("11")
  436. A("sbrs %3,2") // shift by 4 bit position ?
  437. A("rjmp 12f") // No, skip it
  438. A("swap %15") // Swap nibbles
  439. A("andi %14, 0xF0") // Lose the lowest nibble
  440. A("swap %14") // Swap nibbles. Upper nibble is 0
  441. A("or %14,%15") // Pass nibble from upper byte
  442. A("andi %15, 0x0F") // And get rid of that nibble
  443. L("12")
  444. A("sbrs %3,3") // shift by 8 bit position ?
  445. A("rjmp 6f") // No, skip it
  446. A("mov %14,%15")
  447. A("clr %15")
  448. L("6") // %16:%15:%14 = initial estimation of 0x1000000 / d
  449. // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
  450. // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
  451. // to get more than 18bits of precision (the initial table lookup gives 9 bits of
  452. // precision to start from). 18bits of precision is all what is needed here for result
  453. // %8:%7:%6 = d = interval
  454. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  455. // %13 = 0
  456. // %3:%2:%1:%0 = working accumulator
  457. // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
  458. A("clr %0")
  459. A("clr %1")
  460. A("clr %2")
  461. A("ldi %3,2") // %3:%2:%1:%0 = 0x2000000
  462. A("mul %6,%14") // r1:r0 = LO(d) * LO(x)
  463. A("sub %0,r0")
  464. A("sbc %1,r1")
  465. A("sbc %2,%13")
  466. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  467. A("mul %7,%14") // r1:r0 = MI(d) * LO(x)
  468. A("sub %1,r0")
  469. A("sbc %2,r1" )
  470. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  471. A("mul %8,%14") // r1:r0 = HI(d) * LO(x)
  472. A("sub %2,r0")
  473. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  474. A("mul %6,%15") // r1:r0 = LO(d) * MI(x)
  475. A("sub %1,r0")
  476. A("sbc %2,r1")
  477. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  478. A("mul %7,%15") // r1:r0 = MI(d) * MI(x)
  479. A("sub %2,r0")
  480. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  481. A("mul %8,%15") // r1:r0 = HI(d) * MI(x)
  482. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  483. A("mul %6,%16") // r1:r0 = LO(d) * HI(x)
  484. A("sub %2,r0")
  485. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  486. A("mul %7,%16") // r1:r0 = MI(d) * HI(x)
  487. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  488. // %3:%2:%1:%0 = (1<<25) - x*d [169]
  489. // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
  490. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  491. // %3:%2:%1:%0 = (1<<25) - x*d = acc
  492. // %13 = 0
  493. // result = %11:%10:%9:%5:%4
  494. A("mul %14,%0") // r1:r0 = LO(x) * LO(acc)
  495. A("mov %4,r1")
  496. A("clr %5")
  497. A("clr %9")
  498. A("clr %10")
  499. A("clr %11") // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
  500. A("mul %15,%0") // r1:r0 = MI(x) * LO(acc)
  501. A("add %4,r0")
  502. A("adc %5,r1")
  503. A("adc %9,%13")
  504. A("adc %10,%13")
  505. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
  506. A("mul %16,%0") // r1:r0 = HI(x) * LO(acc)
  507. A("add %5,r0")
  508. A("adc %9,r1")
  509. A("adc %10,%13")
  510. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
  511. A("mul %14,%1") // r1:r0 = LO(x) * MIL(acc)
  512. A("add %4,r0")
  513. A("adc %5,r1")
  514. A("adc %9,%13")
  515. A("adc %10,%13")
  516. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
  517. A("mul %15,%1") // r1:r0 = MI(x) * MIL(acc)
  518. A("add %5,r0")
  519. A("adc %9,r1")
  520. A("adc %10,%13")
  521. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8
  522. A("mul %16,%1") // r1:r0 = HI(x) * MIL(acc)
  523. A("add %9,r0")
  524. A("adc %10,r1")
  525. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
  526. A("mul %14,%2") // r1:r0 = LO(x) * MIH(acc)
  527. A("add %5,r0")
  528. A("adc %9,r1")
  529. A("adc %10,%13")
  530. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
  531. A("mul %15,%2") // r1:r0 = MI(x) * MIH(acc)
  532. A("add %9,r0")
  533. A("adc %10,r1")
  534. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
  535. A("mul %16,%2") // r1:r0 = HI(x) * MIH(acc)
  536. A("add %10,r0")
  537. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
  538. A("mul %14,%3") // r1:r0 = LO(x) * HI(acc)
  539. A("add %9,r0")
  540. A("adc %10,r1")
  541. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
  542. A("mul %15,%3") // r1:r0 = MI(x) * HI(acc)
  543. A("add %10,r0")
  544. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
  545. A("mul %16,%3") // r1:r0 = HI(x) * HI(acc)
  546. A("add %11,r0") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
  547. // At this point, %11:%10:%9 contains the new estimation of x.
  548. // Finally, we must correct the result. Estimate remainder as
  549. // (1<<24) - x*d
  550. // %11:%10:%9 = x
  551. // %8:%7:%6 = d = interval" "\n\t"
  552. A("ldi %3,1")
  553. A("clr %2")
  554. A("clr %1")
  555. A("clr %0") // %3:%2:%1:%0 = 0x1000000
  556. A("mul %6,%9") // r1:r0 = LO(d) * LO(x)
  557. A("sub %0,r0")
  558. A("sbc %1,r1")
  559. A("sbc %2,%13")
  560. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  561. A("mul %7,%9") // r1:r0 = MI(d) * LO(x)
  562. A("sub %1,r0")
  563. A("sbc %2,r1")
  564. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  565. A("mul %8,%9") // r1:r0 = HI(d) * LO(x)
  566. A("sub %2,r0")
  567. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  568. A("mul %6,%10") // r1:r0 = LO(d) * MI(x)
  569. A("sub %1,r0")
  570. A("sbc %2,r1")
  571. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  572. A("mul %7,%10") // r1:r0 = MI(d) * MI(x)
  573. A("sub %2,r0")
  574. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  575. A("mul %8,%10") // r1:r0 = HI(d) * MI(x)
  576. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  577. A("mul %6,%11") // r1:r0 = LO(d) * HI(x)
  578. A("sub %2,r0")
  579. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  580. A("mul %7,%11") // r1:r0 = MI(d) * HI(x)
  581. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  582. // %3:%2:%1:%0 = r = (1<<24) - x*d
  583. // %8:%7:%6 = d = interval
  584. // Perform the final correction
  585. A("sub %0,%6")
  586. A("sbc %1,%7")
  587. A("sbc %2,%8") // r -= d
  588. A("brcs 14f") // if ( r >= d)
  589. // %11:%10:%9 = x
  590. A("ldi %3,1")
  591. A("add %9,%3")
  592. A("adc %10,%13")
  593. A("adc %11,%13") // x++
  594. L("14")
  595. // Estimation is done. %11:%10:%9 = x
  596. A("clr __zero_reg__") // Make C runtime happy
  597. // [211 cycles total]
  598. : "=r" (r2),
  599. "=r" (r3),
  600. "=r" (r4),
  601. "=d" (r5),
  602. "=r" (r6),
  603. "=r" (r7),
  604. "+r" (r8),
  605. "+r" (r9),
  606. "+r" (r10),
  607. "=d" (r11),
  608. "=r" (r12),
  609. "=r" (r13),
  610. "=d" (r14),
  611. "=d" (r15),
  612. "=d" (r16),
  613. "=d" (r17),
  614. "=d" (r18),
  615. "+z" (ptab)
  616. :
  617. : "r0", "r1", "cc"
  618. );
  619. // Return the result
  620. return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
  621. }
  622. #else
  623. // All other 32-bit MPUs can easily do inverse using hardware division,
  624. // so we don't need to reduce precision or to use assembly language at all.
  625. // This routine, for all other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d
  626. static FORCE_INLINE uint32_t get_period_inverse(const uint32_t d) {
  627. return d ? 0xFFFFFFFF / d : 0xFFFFFFFF;
  628. }
  629. #endif
  630. #endif
  631. #define MINIMAL_STEP_RATE 120
  632. /**
  633. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  634. * by the provided factors.
  635. **
  636. * ############ VERY IMPORTANT ############
  637. * NOTE that the PRECONDITION to call this function is that the block is
  638. * NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR
  639. * is not and will not use the block while we modify it, so it is safe to
  640. * alter its values.
  641. */
  642. void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
  643. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  644. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  645. // Limit minimal step rate (Otherwise the timer will overflow.)
  646. NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE));
  647. NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE));
  648. #if ENABLED(S_CURVE_ACCELERATION)
  649. uint32_t cruise_rate = initial_rate;
  650. #endif
  651. const int32_t accel = block->acceleration_steps_per_s2;
  652. // Steps required for acceleration, deceleration to/from nominal rate
  653. uint32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  654. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
  655. // Steps between acceleration and deceleration, if any
  656. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  657. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  658. // Then we can't possibly reach the nominal rate, there will be no cruising.
  659. // Use intersection_distance() to calculate accel / braking time in order to
  660. // reach the final_rate exactly at the end of this block.
  661. if (plateau_steps < 0) {
  662. const float accelerate_steps_float = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  663. accelerate_steps = _MIN(uint32_t(_MAX(accelerate_steps_float, 0)), block->step_event_count);
  664. plateau_steps = 0;
  665. #if ENABLED(S_CURVE_ACCELERATION)
  666. // We won't reach the cruising rate. Let's calculate the speed we will reach
  667. cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
  668. #endif
  669. }
  670. #if ENABLED(S_CURVE_ACCELERATION)
  671. else // We have some plateau time, so the cruise rate will be the nominal rate
  672. cruise_rate = block->nominal_rate;
  673. #endif
  674. #if ENABLED(S_CURVE_ACCELERATION)
  675. // Jerk controlled speed requires to express speed versus time, NOT steps
  676. uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * (STEPPER_TIMER_RATE),
  677. deceleration_time = ((float)(cruise_rate - final_rate) / accel) * (STEPPER_TIMER_RATE);
  678. // And to offload calculations from the ISR, we also calculate the inverse of those times here
  679. uint32_t acceleration_time_inverse = get_period_inverse(acceleration_time);
  680. uint32_t deceleration_time_inverse = get_period_inverse(deceleration_time);
  681. #endif
  682. // Store new block parameters
  683. block->accelerate_until = accelerate_steps;
  684. block->decelerate_after = accelerate_steps + plateau_steps;
  685. block->initial_rate = initial_rate;
  686. #if ENABLED(S_CURVE_ACCELERATION)
  687. block->acceleration_time = acceleration_time;
  688. block->deceleration_time = deceleration_time;
  689. block->acceleration_time_inverse = acceleration_time_inverse;
  690. block->deceleration_time_inverse = deceleration_time_inverse;
  691. block->cruise_rate = cruise_rate;
  692. #endif
  693. block->final_rate = final_rate;
  694. }
  695. /* PLANNER SPEED DEFINITION
  696. +--------+ <- current->nominal_speed
  697. / \
  698. current->entry_speed -> + \
  699. | + <- next->entry_speed (aka exit speed)
  700. +-------------+
  701. time -->
  702. Recalculates the motion plan according to the following basic guidelines:
  703. 1. Go over every feasible block sequentially in reverse order and calculate the junction speeds
  704. (i.e. current->entry_speed) such that:
  705. a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of
  706. neighboring blocks.
  707. b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed)
  708. with a maximum allowable deceleration over the block travel distance.
  709. c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero).
  710. 2. Go over every block in chronological (forward) order and dial down junction speed values if
  711. a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable
  712. acceleration over the block travel distance.
  713. When these stages are complete, the planner will have maximized the velocity profiles throughout the all
  714. of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In
  715. other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements
  716. are possible. If a new block is added to the buffer, the plan is recomputed according to the said
  717. guidelines for a new optimal plan.
  718. To increase computational efficiency of these guidelines, a set of planner block pointers have been
  719. created to indicate stop-compute points for when the planner guidelines cannot logically make any further
  720. changes or improvements to the plan when in normal operation and new blocks are streamed and added to the
  721. planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are
  722. bracketed by junction velocities at their maximums (or by the first planner block as well), no new block
  723. added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute
  724. them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute
  725. point) are all accelerating, they are all optimal and can not be altered by a new block added to the
  726. planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum
  727. junction velocity is reached. However, if the operational conditions of the plan changes from infrequently
  728. used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is
  729. recomputed as stated in the general guidelines.
  730. Planner buffer index mapping:
  731. - block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed.
  732. - block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether
  733. the buffer is full or empty. As described for standard ring buffers, this block is always empty.
  734. - block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal
  735. streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the
  736. planner buffer that don't change with the addition of a new block, as describe above. In addition,
  737. this block can never be less than block_buffer_tail and will always be pushed forward and maintain
  738. this requirement when encountered by the Planner::discard_current_block() routine during a cycle.
  739. NOTE: Since the planner only computes on what's in the planner buffer, some motions with lots of short
  740. line segments, like G2/3 arcs or complex curves, may seem to move slow. This is because there simply isn't
  741. enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and then
  742. decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this happens and
  743. becomes an annoyance, there are a few simple solutions: (1) Maximize the machine acceleration. The planner
  744. will be able to compute higher velocity profiles within the same combined distance. (2) Maximize line
  745. motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
  746. the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
  747. for the planner to compute over. It also increases the number of computations the planner has to perform
  748. to compute an optimal plan, so select carefully.
  749. */
  750. // The kernel called by recalculate() when scanning the plan from last to first entry.
  751. void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
  752. if (current) {
  753. // If entry speed is already at the maximum entry speed, and there was no change of speed
  754. // in the next block, there is no need to recheck. Block is cruising and there is no need to
  755. // compute anything for this block,
  756. // If not, block entry speed needs to be recalculated to ensure maximum possible planned speed.
  757. const float max_entry_speed_sqr = current->max_entry_speed_sqr;
  758. // Compute maximum entry speed decelerating over the current block from its exit speed.
  759. // If not at the maximum entry speed, or the previous block entry speed changed
  760. if (current->entry_speed_sqr != max_entry_speed_sqr || (next && TEST(next->flag, BLOCK_BIT_RECALCULATE))) {
  761. // If nominal length true, max junction speed is guaranteed to be reached.
  762. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  763. // the current block and next block junction speeds are guaranteed to always be at their maximum
  764. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  765. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  766. // the reverse and forward planners, the corresponding block junction speed will always be at the
  767. // the maximum junction speed and may always be ignored for any speed reduction checks.
  768. const float new_entry_speed_sqr = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
  769. ? max_entry_speed_sqr
  770. : _MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next ? next->entry_speed_sqr : sq(float(MINIMUM_PLANNER_SPEED)), current->millimeters));
  771. if (current->entry_speed_sqr != new_entry_speed_sqr) {
  772. // Need to recalculate the block speed - Mark it now, so the stepper
  773. // ISR does not consume the block before being recalculated
  774. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  775. // But there is an inherent race condition here, as the block may have
  776. // become BUSY just before being marked RECALCULATE, so check for that!
  777. if (stepper.is_block_busy(current)) {
  778. // Block became busy. Clear the RECALCULATE flag (no point in
  779. // recalculating BUSY blocks). And don't set its speed, as it can't
  780. // be updated at this time.
  781. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  782. }
  783. else {
  784. // Block is not BUSY so this is ahead of the Stepper ISR:
  785. // Just Set the new entry speed.
  786. current->entry_speed_sqr = new_entry_speed_sqr;
  787. }
  788. }
  789. }
  790. }
  791. }
  792. /**
  793. * recalculate() needs to go over the current plan twice.
  794. * Once in reverse and once forward. This implements the reverse pass.
  795. */
  796. void Planner::reverse_pass() {
  797. // Initialize block index to the last block in the planner buffer.
  798. uint8_t block_index = prev_block_index(block_buffer_head);
  799. // Read the index of the last buffer planned block.
  800. // The ISR may change it so get a stable local copy.
  801. uint8_t planned_block_index = block_buffer_planned;
  802. // If there was a race condition and block_buffer_planned was incremented
  803. // or was pointing at the head (queue empty) break loop now and avoid
  804. // planning already consumed blocks
  805. if (planned_block_index == block_buffer_head) return;
  806. // Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
  807. // block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
  808. // NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
  809. const block_t *next = nullptr;
  810. while (block_index != planned_block_index) {
  811. // Perform the reverse pass
  812. block_t *current = &block_buffer[block_index];
  813. // Only consider non sync blocks
  814. if (!TEST(current->flag, BLOCK_BIT_SYNC_POSITION)) {
  815. reverse_pass_kernel(current, next);
  816. next = current;
  817. }
  818. // Advance to the next
  819. block_index = prev_block_index(block_index);
  820. // The ISR could advance the block_buffer_planned while we were doing the reverse pass.
  821. // We must try to avoid using an already consumed block as the last one - So follow
  822. // changes to the pointer and make sure to limit the loop to the currently busy block
  823. while (planned_block_index != block_buffer_planned) {
  824. // If we reached the busy block or an already processed block, break the loop now
  825. if (block_index == planned_block_index) return;
  826. // Advance the pointer, following the busy block
  827. planned_block_index = next_block_index(planned_block_index);
  828. }
  829. }
  830. }
  831. // The kernel called by recalculate() when scanning the plan from first to last entry.
  832. void Planner::forward_pass_kernel(const block_t* const previous, block_t* const current, const uint8_t block_index) {
  833. if (previous) {
  834. // If the previous block is an acceleration block, too short to complete the full speed
  835. // change, adjust the entry speed accordingly. Entry speeds have already been reset,
  836. // maximized, and reverse-planned. If nominal length is set, max junction speed is
  837. // guaranteed to be reached. No need to recheck.
  838. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH) &&
  839. previous->entry_speed_sqr < current->entry_speed_sqr) {
  840. // Compute the maximum allowable speed
  841. const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters);
  842. // If true, current block is full-acceleration and we can move the planned pointer forward.
  843. if (new_entry_speed_sqr < current->entry_speed_sqr) {
  844. // Mark we need to recompute the trapezoidal shape, and do it now,
  845. // so the stepper ISR does not consume the block before being recalculated
  846. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  847. // But there is an inherent race condition here, as the block maybe
  848. // became BUSY, just before it was marked as RECALCULATE, so check
  849. // if that is the case!
  850. if (stepper.is_block_busy(current)) {
  851. // Block became busy. Clear the RECALCULATE flag (no point in
  852. // recalculating BUSY blocks and don't set its speed, as it can't
  853. // be updated at this time.
  854. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  855. }
  856. else {
  857. // Block is not BUSY, we won the race against the Stepper ISR:
  858. // Always <= max_entry_speed_sqr. Backward pass sets this.
  859. current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this.
  860. // Set optimal plan pointer.
  861. block_buffer_planned = block_index;
  862. }
  863. }
  864. }
  865. // Any block set at its maximum entry speed also creates an optimal plan up to this
  866. // point in the buffer. When the plan is bracketed by either the beginning of the
  867. // buffer and a maximum entry speed or two maximum entry speeds, every block in between
  868. // cannot logically be further improved. Hence, we don't have to recompute them anymore.
  869. if (current->entry_speed_sqr == current->max_entry_speed_sqr)
  870. block_buffer_planned = block_index;
  871. }
  872. }
  873. /**
  874. * recalculate() needs to go over the current plan twice.
  875. * Once in reverse and once forward. This implements the forward pass.
  876. */
  877. void Planner::forward_pass() {
  878. // Forward Pass: Forward plan the acceleration curve from the planned pointer onward.
  879. // Also scans for optimal plan breakpoints and appropriately updates the planned pointer.
  880. // Begin at buffer planned pointer. Note that block_buffer_planned can be modified
  881. // by the stepper ISR, so read it ONCE. It it guaranteed that block_buffer_planned
  882. // will never lead head, so the loop is safe to execute. Also note that the forward
  883. // pass will never modify the values at the tail.
  884. uint8_t block_index = block_buffer_planned;
  885. block_t *block;
  886. const block_t * previous = nullptr;
  887. while (block_index != block_buffer_head) {
  888. // Perform the forward pass
  889. block = &block_buffer[block_index];
  890. // Skip SYNC blocks
  891. if (!TEST(block->flag, BLOCK_BIT_SYNC_POSITION)) {
  892. // If there's no previous block or the previous block is not
  893. // BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise,
  894. // the previous block became BUSY, so assume the current block's
  895. // entry speed can't be altered (since that would also require
  896. // updating the exit speed of the previous block).
  897. if (!previous || !stepper.is_block_busy(previous))
  898. forward_pass_kernel(previous, block, block_index);
  899. previous = block;
  900. }
  901. // Advance to the previous
  902. block_index = next_block_index(block_index);
  903. }
  904. }
  905. /**
  906. * Recalculate the trapezoid speed profiles for all blocks in the plan
  907. * according to the entry_factor for each junction. Must be called by
  908. * recalculate() after updating the blocks.
  909. */
  910. void Planner::recalculate_trapezoids() {
  911. // The tail may be changed by the ISR so get a local copy.
  912. uint8_t block_index = block_buffer_tail,
  913. head_block_index = block_buffer_head;
  914. // Since there could be a sync block in the head of the queue, and the
  915. // next loop must not recalculate the head block (as it needs to be
  916. // specially handled), scan backwards to the first non-SYNC block.
  917. while (head_block_index != block_index) {
  918. // Go back (head always point to the first free block)
  919. const uint8_t prev_index = prev_block_index(head_block_index);
  920. // Get the pointer to the block
  921. block_t *prev = &block_buffer[prev_index];
  922. // If not dealing with a sync block, we are done. The last block is not a SYNC block
  923. if (!TEST(prev->flag, BLOCK_BIT_SYNC_POSITION)) break;
  924. // Examine the previous block. This and all following are SYNC blocks
  925. head_block_index = prev_index;
  926. }
  927. // Go from the tail (currently executed block) to the first block, without including it)
  928. block_t *block = nullptr, *next = nullptr;
  929. float current_entry_speed = 0.0, next_entry_speed = 0.0;
  930. while (block_index != head_block_index) {
  931. next = &block_buffer[block_index];
  932. // Skip sync blocks
  933. if (!TEST(next->flag, BLOCK_BIT_SYNC_POSITION)) {
  934. next_entry_speed = SQRT(next->entry_speed_sqr);
  935. if (block) {
  936. // Recalculate if current block entry or exit junction speed has changed.
  937. if (TEST(block->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  938. // Mark the current block as RECALCULATE, to protect it from the Stepper ISR running it.
  939. // Note that due to the above condition, there's a chance the current block isn't marked as
  940. // RECALCULATE yet, but the next one is. That's the reason for the following line.
  941. SBI(block->flag, BLOCK_BIT_RECALCULATE);
  942. // But there is an inherent race condition here, as the block maybe
  943. // became BUSY, just before it was marked as RECALCULATE, so check
  944. // if that is the case!
  945. if (!stepper.is_block_busy(block)) {
  946. // Block is not BUSY, we won the race against the Stepper ISR:
  947. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  948. const float current_nominal_speed = SQRT(block->nominal_speed_sqr),
  949. nomr = 1.0f / current_nominal_speed;
  950. calculate_trapezoid_for_block(block, current_entry_speed * nomr, next_entry_speed * nomr);
  951. #if ENABLED(LIN_ADVANCE)
  952. if (block->use_advance_lead) {
  953. const float comp = block->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  954. block->max_adv_steps = current_nominal_speed * comp;
  955. block->final_adv_steps = next_entry_speed * comp;
  956. }
  957. #endif
  958. }
  959. // Reset current only to ensure next trapezoid is computed - The
  960. // stepper is free to use the block from now on.
  961. CBI(block->flag, BLOCK_BIT_RECALCULATE);
  962. }
  963. }
  964. block = next;
  965. current_entry_speed = next_entry_speed;
  966. }
  967. block_index = next_block_index(block_index);
  968. }
  969. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  970. if (next) {
  971. // Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it.
  972. // As the last block is always recalculated here, there is a chance the block isn't
  973. // marked as RECALCULATE yet. That's the reason for the following line.
  974. SBI(next->flag, BLOCK_BIT_RECALCULATE);
  975. // But there is an inherent race condition here, as the block maybe
  976. // became BUSY, just before it was marked as RECALCULATE, so check
  977. // if that is the case!
  978. if (!stepper.is_block_busy(block)) {
  979. // Block is not BUSY, we won the race against the Stepper ISR:
  980. const float next_nominal_speed = SQRT(next->nominal_speed_sqr),
  981. nomr = 1.0f / next_nominal_speed;
  982. calculate_trapezoid_for_block(next, next_entry_speed * nomr, float(MINIMUM_PLANNER_SPEED) * nomr);
  983. #if ENABLED(LIN_ADVANCE)
  984. if (next->use_advance_lead) {
  985. const float comp = next->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  986. next->max_adv_steps = next_nominal_speed * comp;
  987. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  988. }
  989. #endif
  990. }
  991. // Reset next only to ensure its trapezoid is computed - The stepper is free to use
  992. // the block from now on.
  993. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  994. }
  995. }
  996. void Planner::recalculate() {
  997. // Initialize block index to the last block in the planner buffer.
  998. const uint8_t block_index = prev_block_index(block_buffer_head);
  999. // If there is just one block, no planning can be done. Avoid it!
  1000. if (block_index != block_buffer_planned) {
  1001. reverse_pass();
  1002. forward_pass();
  1003. }
  1004. recalculate_trapezoids();
  1005. }
  1006. #if ENABLED(AUTOTEMP)
  1007. void Planner::getHighESpeed() {
  1008. static float oldt = 0;
  1009. if (!autotemp_enabled) return;
  1010. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  1011. float high = 0.0;
  1012. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1013. block_t* block = &block_buffer[b];
  1014. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  1015. const float se = (float)block->steps[E_AXIS] / block->step_event_count * SQRT(block->nominal_speed_sqr); // mm/sec;
  1016. NOLESS(high, se);
  1017. }
  1018. }
  1019. float t = autotemp_min + high * autotemp_factor;
  1020. LIMIT(t, autotemp_min, autotemp_max);
  1021. if (t < oldt) t = t * (1 - float(AUTOTEMP_OLDWEIGHT)) + oldt * float(AUTOTEMP_OLDWEIGHT);
  1022. oldt = t;
  1023. thermalManager.setTargetHotend(t, 0);
  1024. }
  1025. #endif // AUTOTEMP
  1026. /**
  1027. * Maintain fans, paste extruder pressure,
  1028. */
  1029. void Planner::check_axes_activity() {
  1030. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z, DISABLE_E)
  1031. uint8_t axis_active[NUM_AXIS] = { 0 };
  1032. #endif
  1033. #if FAN_COUNT > 0
  1034. uint8_t tail_fan_speed[FAN_COUNT];
  1035. #endif
  1036. #if ENABLED(BARICUDA)
  1037. #if HAS_HEATER_1
  1038. uint8_t tail_valve_pressure;
  1039. #endif
  1040. #if HAS_HEATER_2
  1041. uint8_t tail_e_to_p_pressure;
  1042. #endif
  1043. #endif
  1044. if (has_blocks_queued()) {
  1045. #if FAN_COUNT > 0 || ENABLED(BARICUDA)
  1046. block_t *block = &block_buffer[block_buffer_tail];
  1047. #endif
  1048. #if FAN_COUNT > 0
  1049. FANS_LOOP(i)
  1050. tail_fan_speed[i] = thermalManager.scaledFanSpeed(i, block->fan_speed[i]);
  1051. #endif
  1052. #if ENABLED(BARICUDA)
  1053. #if HAS_HEATER_1
  1054. tail_valve_pressure = block->valve_pressure;
  1055. #endif
  1056. #if HAS_HEATER_2
  1057. tail_e_to_p_pressure = block->e_to_p_pressure;
  1058. #endif
  1059. #endif
  1060. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z, DISABLE_E)
  1061. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1062. block_t *block = &block_buffer[b];
  1063. LOOP_XYZE(i) if (block->steps[i]) axis_active[i] = true;
  1064. }
  1065. #endif
  1066. }
  1067. else {
  1068. #if FAN_COUNT > 0
  1069. FANS_LOOP(i)
  1070. tail_fan_speed[i] = thermalManager.scaledFanSpeed(i);
  1071. #endif
  1072. #if ENABLED(BARICUDA)
  1073. #if HAS_HEATER_1
  1074. tail_valve_pressure = baricuda_valve_pressure;
  1075. #endif
  1076. #if HAS_HEATER_2
  1077. tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  1078. #endif
  1079. #endif
  1080. }
  1081. #if ENABLED(DISABLE_X)
  1082. if (!axis_active[X_AXIS]) disable_X();
  1083. #endif
  1084. #if ENABLED(DISABLE_Y)
  1085. if (!axis_active[Y_AXIS]) disable_Y();
  1086. #endif
  1087. #if ENABLED(DISABLE_Z)
  1088. if (!axis_active[Z_AXIS]) disable_Z();
  1089. #endif
  1090. #if ENABLED(DISABLE_E)
  1091. if (!axis_active[E_AXIS]) disable_e_steppers();
  1092. #endif
  1093. #if FAN_COUNT > 0
  1094. #if FAN_KICKSTART_TIME > 0
  1095. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  1096. #define KICKSTART_FAN(f) \
  1097. if (tail_fan_speed[f]) { \
  1098. millis_t ms = millis(); \
  1099. if (fan_kick_end[f] == 0) { \
  1100. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  1101. tail_fan_speed[f] = 255; \
  1102. } else if (PENDING(ms, fan_kick_end[f])) \
  1103. tail_fan_speed[f] = 255; \
  1104. } else fan_kick_end[f] = 0
  1105. #else
  1106. #define KICKSTART_FAN(f) NOOP
  1107. #endif
  1108. #if FAN_MIN_PWM != 0 || FAN_MAX_PWM != 255
  1109. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? map(tail_fan_speed[f], 1, 255, FAN_MIN_PWM, FAN_MAX_PWM) : 0)
  1110. #else
  1111. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  1112. #endif
  1113. #if ENABLED(FAN_SOFT_PWM)
  1114. #define _FAN_SET(F) thermalManager.soft_pwm_amount_fan[F] = CALC_FAN_SPEED(F);
  1115. #elif ENABLED(FAST_PWM_FAN)
  1116. #define _FAN_SET(F) set_pwm_duty(FAN##F##_PIN, CALC_FAN_SPEED(F));
  1117. #else
  1118. #define _FAN_SET(F) analogWrite(pin_t(FAN##F##_PIN), CALC_FAN_SPEED(F));
  1119. #endif
  1120. #define FAN_SET(F) do{ KICKSTART_FAN(F); _FAN_SET(F); }while(0)
  1121. #if HAS_FAN0
  1122. FAN_SET(0);
  1123. #endif
  1124. #if HAS_FAN1
  1125. FAN_SET(1);
  1126. #endif
  1127. #if HAS_FAN2
  1128. FAN_SET(2);
  1129. #endif
  1130. #endif // FAN_COUNT > 0
  1131. #if ENABLED(AUTOTEMP)
  1132. getHighESpeed();
  1133. #endif
  1134. #if ENABLED(BARICUDA)
  1135. #if HAS_HEATER_1
  1136. analogWrite(pin_t(HEATER_1_PIN), tail_valve_pressure);
  1137. #endif
  1138. #if HAS_HEATER_2
  1139. analogWrite(pin_t(HEATER_2_PIN), tail_e_to_p_pressure);
  1140. #endif
  1141. #endif
  1142. }
  1143. #if DISABLED(NO_VOLUMETRICS)
  1144. /**
  1145. * Get a volumetric multiplier from a filament diameter.
  1146. * This is the reciprocal of the circular cross-section area.
  1147. * Return 1.0 with volumetric off or a diameter of 0.0.
  1148. */
  1149. inline float calculate_volumetric_multiplier(const float &diameter) {
  1150. return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5f) : 1;
  1151. }
  1152. /**
  1153. * Convert the filament sizes into volumetric multipliers.
  1154. * The multiplier converts a given E value into a length.
  1155. */
  1156. void Planner::calculate_volumetric_multipliers() {
  1157. for (uint8_t i = 0; i < COUNT(filament_size); i++) {
  1158. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  1159. refresh_e_factor(i);
  1160. }
  1161. }
  1162. #endif // !NO_VOLUMETRICS
  1163. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1164. /**
  1165. * Convert the ratio value given by the filament width sensor
  1166. * into a volumetric multiplier. Conversion differs when using
  1167. * linear extrusion vs volumetric extrusion.
  1168. */
  1169. void Planner::apply_filament_width_sensor(const int8_t encoded_ratio) {
  1170. // Reconstitute the nominal/measured ratio
  1171. const float nom_meas_ratio = 1 + 0.01f * encoded_ratio,
  1172. ratio_2 = sq(nom_meas_ratio);
  1173. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  1174. ? ratio_2 / CIRCLE_AREA(filwidth.nominal_mm * 0.5f) // Volumetric uses a true volumetric multiplier
  1175. : ratio_2; // Linear squares the ratio, which scales the volume
  1176. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  1177. }
  1178. #endif
  1179. #if HAS_LEVELING
  1180. /**
  1181. * rx, ry, rz - Cartesian positions in mm
  1182. * Leveled XYZ on completion
  1183. */
  1184. void Planner::apply_leveling(float &rx, float &ry, float &rz) {
  1185. if (!leveling_active) return;
  1186. #if ABL_PLANAR
  1187. float dx = rx - (X_TILT_FULCRUM),
  1188. dy = ry - (Y_TILT_FULCRUM);
  1189. apply_rotation_xyz(bed_level_matrix, dx, dy, rz);
  1190. rx = dx + X_TILT_FULCRUM;
  1191. ry = dy + Y_TILT_FULCRUM;
  1192. #elif HAS_MESH
  1193. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1194. const float fade_scaling_factor = fade_scaling_factor_for_z(rz);
  1195. #else
  1196. constexpr float fade_scaling_factor = 1.0;
  1197. #endif
  1198. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1199. const float raw[XYZ] = { rx, ry, 0 };
  1200. #endif
  1201. rz += (
  1202. #if ENABLED(MESH_BED_LEVELING)
  1203. mbl.get_z(rx, ry
  1204. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1205. , fade_scaling_factor
  1206. #endif
  1207. )
  1208. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1209. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(rx, ry) : 0.0
  1210. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1211. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1212. #endif
  1213. );
  1214. #endif
  1215. }
  1216. void Planner::unapply_leveling(float raw[XYZ]) {
  1217. if (leveling_active) {
  1218. #if ABL_PLANAR
  1219. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  1220. float dx = raw[X_AXIS] - (X_TILT_FULCRUM),
  1221. dy = raw[Y_AXIS] - (Y_TILT_FULCRUM);
  1222. apply_rotation_xyz(inverse, dx, dy, raw[Z_AXIS]);
  1223. raw[X_AXIS] = dx + X_TILT_FULCRUM;
  1224. raw[Y_AXIS] = dy + Y_TILT_FULCRUM;
  1225. #elif HAS_MESH
  1226. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1227. const float fade_scaling_factor = fade_scaling_factor_for_z(raw[Z_AXIS]);
  1228. #else
  1229. constexpr float fade_scaling_factor = 1.0;
  1230. #endif
  1231. raw[Z_AXIS] -= (
  1232. #if ENABLED(MESH_BED_LEVELING)
  1233. mbl.get_z(raw[X_AXIS], raw[Y_AXIS]
  1234. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1235. , fade_scaling_factor
  1236. #endif
  1237. )
  1238. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1239. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw[X_AXIS], raw[Y_AXIS]) : 0.0
  1240. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1241. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1242. #endif
  1243. );
  1244. #endif
  1245. }
  1246. #if ENABLED(SKEW_CORRECTION)
  1247. unskew(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]);
  1248. #endif
  1249. }
  1250. #endif // HAS_LEVELING
  1251. #if ENABLED(FWRETRACT)
  1252. /**
  1253. * rz, e - Cartesian positions in mm
  1254. */
  1255. void Planner::apply_retract(float &rz, float &e) {
  1256. rz += fwretract.current_hop;
  1257. e -= fwretract.current_retract[active_extruder];
  1258. }
  1259. void Planner::unapply_retract(float &rz, float &e) {
  1260. rz -= fwretract.current_hop;
  1261. e += fwretract.current_retract[active_extruder];
  1262. }
  1263. #endif
  1264. void Planner::quick_stop() {
  1265. // Remove all the queued blocks. Note that this function is NOT
  1266. // called from the Stepper ISR, so we must consider tail as readonly!
  1267. // that is why we set head to tail - But there is a race condition that
  1268. // must be handled: The tail could change between the read and the assignment
  1269. // so this must be enclosed in a critical section
  1270. const bool was_enabled = STEPPER_ISR_ENABLED();
  1271. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  1272. // Drop all queue entries
  1273. block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail;
  1274. // Restart the block delay for the first movement - As the queue was
  1275. // forced to empty, there's no risk the ISR will touch this.
  1276. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1277. #if HAS_SPI_LCD
  1278. // Clear the accumulated runtime
  1279. clear_block_buffer_runtime();
  1280. #endif
  1281. // Make sure to drop any attempt of queuing moves for at least 1 second
  1282. cleaning_buffer_counter = 1000;
  1283. // Reenable Stepper ISR
  1284. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  1285. // And stop the stepper ISR
  1286. stepper.quick_stop();
  1287. }
  1288. void Planner::endstop_triggered(const AxisEnum axis) {
  1289. // Record stepper position and discard the current block
  1290. stepper.endstop_triggered(axis);
  1291. }
  1292. float Planner::triggered_position_mm(const AxisEnum axis) {
  1293. return stepper.triggered_position(axis) * steps_to_mm[axis];
  1294. }
  1295. void Planner::finish_and_disable() {
  1296. while (has_blocks_queued() || cleaning_buffer_counter) idle();
  1297. disable_all_steppers();
  1298. }
  1299. /**
  1300. * Get an axis position according to stepper position(s)
  1301. * For CORE machines apply translation from ABC to XYZ.
  1302. */
  1303. float Planner::get_axis_position_mm(const AxisEnum axis) {
  1304. float axis_steps;
  1305. #if IS_CORE
  1306. // Requesting one of the "core" axes?
  1307. if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
  1308. // Protect the access to the position.
  1309. const bool was_enabled = STEPPER_ISR_ENABLED();
  1310. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  1311. const int32_t p1 = stepper.position(CORE_AXIS_1),
  1312. p2 = stepper.position(CORE_AXIS_2);
  1313. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  1314. // ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
  1315. // ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
  1316. axis_steps = (axis == CORE_AXIS_2 ? CORESIGN(p1 - p2) : p1 + p2) * 0.5f;
  1317. }
  1318. else
  1319. axis_steps = stepper.position(axis);
  1320. #else
  1321. axis_steps = stepper.position(axis);
  1322. #endif
  1323. return axis_steps * steps_to_mm[axis];
  1324. }
  1325. /**
  1326. * Block until all buffered steps are executed / cleaned
  1327. */
  1328. void Planner::synchronize() {
  1329. while (
  1330. has_blocks_queued() || cleaning_buffer_counter
  1331. #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
  1332. || (READ(CLOSED_LOOP_ENABLE_PIN) && !READ(CLOSED_LOOP_MOVE_COMPLETE_PIN))
  1333. #endif
  1334. ) idle();
  1335. }
  1336. /**
  1337. * Planner::_buffer_steps
  1338. *
  1339. * Add a new linear movement to the planner queue (in terms of steps).
  1340. *
  1341. * target - target position in steps units
  1342. * target_float - target position in direct (mm, degrees) units. optional
  1343. * fr_mm_s - (target) speed of the move
  1344. * extruder - target extruder
  1345. * millimeters - the length of the movement, if known
  1346. *
  1347. * Returns true if movement was properly queued, false otherwise
  1348. */
  1349. bool Planner::_buffer_steps(const int32_t (&target)[XYZE]
  1350. #if HAS_POSITION_FLOAT
  1351. , const float (&target_float)[ABCE]
  1352. #endif
  1353. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  1354. , const float (&delta_mm_cart)[XYZE]
  1355. #endif
  1356. , float fr_mm_s, const uint8_t extruder, const float &millimeters
  1357. ) {
  1358. // If we are cleaning, do not accept queuing of movements
  1359. if (cleaning_buffer_counter) return false;
  1360. // Wait for the next available block
  1361. uint8_t next_buffer_head;
  1362. block_t * const block = get_next_free_block(next_buffer_head);
  1363. // Fill the block with the specified movement
  1364. if (!_populate_block(block, false, target
  1365. #if HAS_POSITION_FLOAT
  1366. , target_float
  1367. #endif
  1368. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  1369. , delta_mm_cart
  1370. #endif
  1371. , fr_mm_s, extruder, millimeters
  1372. )) {
  1373. // Movement was not queued, probably because it was too short.
  1374. // Simply accept that as movement queued and done
  1375. return true;
  1376. }
  1377. // If this is the first added movement, reload the delay, otherwise, cancel it.
  1378. if (block_buffer_head == block_buffer_tail) {
  1379. // If it was the first queued block, restart the 1st block delivery delay, to
  1380. // give the planner an opportunity to queue more movements and plan them
  1381. // As there are no queued movements, the Stepper ISR will not touch this
  1382. // variable, so there is no risk setting this here (but it MUST be done
  1383. // before the following line!!)
  1384. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1385. }
  1386. // Move buffer head
  1387. block_buffer_head = next_buffer_head;
  1388. // Recalculate and optimize trapezoidal speed profiles
  1389. recalculate();
  1390. // Movement successfully queued!
  1391. return true;
  1392. }
  1393. /**
  1394. * Planner::_populate_block
  1395. *
  1396. * Fills a new linear movement in the block (in terms of steps).
  1397. *
  1398. * target - target position in steps units
  1399. * fr_mm_s - (target) speed of the move
  1400. * extruder - target extruder
  1401. *
  1402. * Returns true is movement is acceptable, false otherwise
  1403. */
  1404. bool Planner::_populate_block(block_t * const block, bool split_move,
  1405. const int32_t (&target)[ABCE]
  1406. #if HAS_POSITION_FLOAT
  1407. , const float (&target_float)[ABCE]
  1408. #endif
  1409. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  1410. , const float (&delta_mm_cart)[XYZE]
  1411. #endif
  1412. , float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  1413. ) {
  1414. const int32_t da = target[A_AXIS] - position[A_AXIS],
  1415. db = target[B_AXIS] - position[B_AXIS],
  1416. dc = target[C_AXIS] - position[C_AXIS];
  1417. #if EXTRUDERS
  1418. int32_t de = target[E_AXIS] - position[E_AXIS];
  1419. #else
  1420. constexpr int32_t de = 0;
  1421. #endif
  1422. /* <-- add a slash to enable
  1423. SERIAL_ECHOLNPAIR(" _populate_block FR:", fr_mm_s,
  1424. " A:", target[A_AXIS], " (", da, " steps)"
  1425. " B:", target[B_AXIS], " (", db, " steps)"
  1426. " C:", target[C_AXIS], " (", dc, " steps)"
  1427. #if EXTRUDERS
  1428. " E:", target[E_AXIS], " (", de, " steps)"
  1429. #endif
  1430. );
  1431. //*/
  1432. #if EITHER(PREVENT_COLD_EXTRUSION, PREVENT_LENGTHY_EXTRUDE)
  1433. if (de) {
  1434. #if ENABLED(PREVENT_COLD_EXTRUSION)
  1435. if (thermalManager.tooColdToExtrude(extruder)) {
  1436. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1437. #if HAS_POSITION_FLOAT
  1438. position_float[E_AXIS] = target_float[E_AXIS];
  1439. #endif
  1440. de = 0; // no difference
  1441. SERIAL_ECHO_MSG(MSG_ERR_COLD_EXTRUDE_STOP);
  1442. }
  1443. #endif // PREVENT_COLD_EXTRUSION
  1444. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1445. const float e_steps = ABS(de * e_factor[extruder]);
  1446. const float max_e_steps = settings.axis_steps_per_mm[E_AXIS_N(extruder)] * (EXTRUDE_MAXLENGTH);
  1447. if (e_steps > max_e_steps) {
  1448. #if ENABLED(MIXING_EXTRUDER)
  1449. bool ignore_e = false;
  1450. float collector[MIXING_STEPPERS];
  1451. mixer.refresh_collector(1.0, mixer.get_current_vtool(), collector);
  1452. MIXER_STEPPER_LOOP(e)
  1453. if (e_steps * collector[e] > max_e_steps) { ignore_e = true; break; }
  1454. #else
  1455. constexpr bool ignore_e = true;
  1456. #endif
  1457. if (ignore_e) {
  1458. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1459. #if HAS_POSITION_FLOAT
  1460. position_float[E_AXIS] = target_float[E_AXIS];
  1461. #endif
  1462. de = 0; // no difference
  1463. SERIAL_ECHO_MSG(MSG_ERR_LONG_EXTRUDE_STOP);
  1464. }
  1465. }
  1466. #endif // PREVENT_LENGTHY_EXTRUDE
  1467. }
  1468. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  1469. // Compute direction bit-mask for this block
  1470. uint8_t dm = 0;
  1471. #if CORE_IS_XY
  1472. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1473. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1474. if (dc < 0) SBI(dm, Z_AXIS);
  1475. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1476. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  1477. #elif CORE_IS_XZ
  1478. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1479. if (db < 0) SBI(dm, Y_AXIS);
  1480. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1481. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  1482. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1483. #elif CORE_IS_YZ
  1484. if (da < 0) SBI(dm, X_AXIS);
  1485. if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  1486. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1487. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  1488. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1489. #else
  1490. if (da < 0) SBI(dm, X_AXIS);
  1491. if (db < 0) SBI(dm, Y_AXIS);
  1492. if (dc < 0) SBI(dm, Z_AXIS);
  1493. #endif
  1494. if (de < 0) SBI(dm, E_AXIS);
  1495. #if EXTRUDERS
  1496. const float esteps_float = de * e_factor[extruder];
  1497. const uint32_t esteps = ABS(esteps_float) + 0.5f;
  1498. #else
  1499. constexpr uint32_t esteps = 0;
  1500. #endif
  1501. // Clear all flags, including the "busy" bit
  1502. block->flag = 0x00;
  1503. // Set direction bits
  1504. block->direction_bits = dm;
  1505. // Number of steps for each axis
  1506. // See http://www.corexy.com/theory.html
  1507. #if CORE_IS_XY
  1508. block->steps[A_AXIS] = ABS(da + db);
  1509. block->steps[B_AXIS] = ABS(da - db);
  1510. block->steps[Z_AXIS] = ABS(dc);
  1511. #elif CORE_IS_XZ
  1512. block->steps[A_AXIS] = ABS(da + dc);
  1513. block->steps[Y_AXIS] = ABS(db);
  1514. block->steps[C_AXIS] = ABS(da - dc);
  1515. #elif CORE_IS_YZ
  1516. block->steps[X_AXIS] = ABS(da);
  1517. block->steps[B_AXIS] = ABS(db + dc);
  1518. block->steps[C_AXIS] = ABS(db - dc);
  1519. #elif IS_SCARA
  1520. block->steps[A_AXIS] = ABS(da);
  1521. block->steps[B_AXIS] = ABS(db);
  1522. block->steps[Z_AXIS] = ABS(dc);
  1523. #else
  1524. // default non-h-bot planning
  1525. block->steps[A_AXIS] = ABS(da);
  1526. block->steps[B_AXIS] = ABS(db);
  1527. block->steps[C_AXIS] = ABS(dc);
  1528. #endif
  1529. /**
  1530. * This part of the code calculates the total length of the movement.
  1531. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  1532. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  1533. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  1534. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  1535. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  1536. */
  1537. #if IS_CORE
  1538. float delta_mm[Z_HEAD + 1];
  1539. #if CORE_IS_XY
  1540. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1541. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1542. delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
  1543. delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
  1544. delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  1545. #elif CORE_IS_XZ
  1546. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1547. delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
  1548. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1549. delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
  1550. delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  1551. #elif CORE_IS_YZ
  1552. delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
  1553. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1554. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1555. delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
  1556. delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  1557. #endif
  1558. #else
  1559. float delta_mm[ABCE];
  1560. delta_mm[A_AXIS] = da * steps_to_mm[A_AXIS];
  1561. delta_mm[B_AXIS] = db * steps_to_mm[B_AXIS];
  1562. delta_mm[C_AXIS] = dc * steps_to_mm[C_AXIS];
  1563. #endif
  1564. #if EXTRUDERS
  1565. delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS_N(extruder)];
  1566. #endif
  1567. if (block->steps[A_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[B_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[C_AXIS] < MIN_STEPS_PER_SEGMENT) {
  1568. block->millimeters = (0
  1569. #if EXTRUDERS
  1570. + ABS(delta_mm[E_AXIS])
  1571. #endif
  1572. );
  1573. }
  1574. else {
  1575. if (millimeters)
  1576. block->millimeters = millimeters;
  1577. else
  1578. block->millimeters = SQRT(
  1579. #if CORE_IS_XY
  1580. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
  1581. #elif CORE_IS_XZ
  1582. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
  1583. #elif CORE_IS_YZ
  1584. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
  1585. #else
  1586. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
  1587. #endif
  1588. );
  1589. /**
  1590. * At this point at least one of the axes has more steps than
  1591. * MIN_STEPS_PER_SEGMENT, ensuring the segment won't get dropped as
  1592. * zero-length. It's important to not apply corrections
  1593. * to blocks that would get dropped!
  1594. *
  1595. * A correction function is permitted to add steps to an axis, it
  1596. * should *never* remove steps!
  1597. */
  1598. #if ENABLED(BACKLASH_COMPENSATION)
  1599. backlash.add_correction_steps(da, db, dc, dm, block);
  1600. #endif
  1601. }
  1602. #if EXTRUDERS
  1603. block->steps[E_AXIS] = esteps;
  1604. #endif
  1605. block->step_event_count = _MAX(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], esteps);
  1606. // Bail if this is a zero-length block
  1607. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false;
  1608. #if ENABLED(MIXING_EXTRUDER)
  1609. MIXER_POPULATE_BLOCK();
  1610. #endif
  1611. #if FAN_COUNT > 0
  1612. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  1613. #endif
  1614. #if ENABLED(BARICUDA)
  1615. block->valve_pressure = baricuda_valve_pressure;
  1616. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  1617. #endif
  1618. #if EXTRUDERS > 1
  1619. block->extruder = extruder;
  1620. #endif
  1621. #if ENABLED(AUTO_POWER_CONTROL)
  1622. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS])
  1623. powerManager.power_on();
  1624. #endif
  1625. // Enable active axes
  1626. #if CORE_IS_XY
  1627. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  1628. enable_X();
  1629. enable_Y();
  1630. }
  1631. #if DISABLED(Z_LATE_ENABLE)
  1632. if (block->steps[Z_AXIS]) enable_Z();
  1633. #endif
  1634. #elif CORE_IS_XZ
  1635. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  1636. enable_X();
  1637. enable_Z();
  1638. }
  1639. if (block->steps[Y_AXIS]) enable_Y();
  1640. #elif CORE_IS_YZ
  1641. if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
  1642. enable_Y();
  1643. enable_Z();
  1644. }
  1645. if (block->steps[X_AXIS]) enable_X();
  1646. #else
  1647. if (block->steps[X_AXIS]) enable_X();
  1648. if (block->steps[Y_AXIS]) enable_Y();
  1649. #if DISABLED(Z_LATE_ENABLE)
  1650. if (block->steps[Z_AXIS]) enable_Z();
  1651. #endif
  1652. #endif
  1653. // Enable extruder(s)
  1654. #if EXTRUDERS
  1655. if (esteps) {
  1656. #if ENABLED(AUTO_POWER_CONTROL)
  1657. powerManager.power_on();
  1658. #endif
  1659. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  1660. #define DISABLE_IDLE_E(N) if (!g_uc_extruder_last_move[N]) disable_E##N();
  1661. for (uint8_t i = 0; i < EXTRUDERS; i++)
  1662. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  1663. switch (extruder) {
  1664. case 0:
  1665. #if EXTRUDERS > 1
  1666. DISABLE_IDLE_E(1);
  1667. #if EXTRUDERS > 2
  1668. DISABLE_IDLE_E(2);
  1669. #if EXTRUDERS > 3
  1670. DISABLE_IDLE_E(3);
  1671. #if EXTRUDERS > 4
  1672. DISABLE_IDLE_E(4);
  1673. #if EXTRUDERS > 5
  1674. DISABLE_IDLE_E(5);
  1675. #endif // EXTRUDERS > 5
  1676. #endif // EXTRUDERS > 4
  1677. #endif // EXTRUDERS > 3
  1678. #endif // EXTRUDERS > 2
  1679. #endif // EXTRUDERS > 1
  1680. enable_E0();
  1681. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  1682. #if HAS_DUPLICATION_MODE
  1683. if (extruder_duplication_enabled) {
  1684. enable_E1();
  1685. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1686. }
  1687. #endif
  1688. break;
  1689. #if EXTRUDERS > 1
  1690. case 1:
  1691. DISABLE_IDLE_E(0);
  1692. #if EXTRUDERS > 2
  1693. DISABLE_IDLE_E(2);
  1694. #if EXTRUDERS > 3
  1695. DISABLE_IDLE_E(3);
  1696. #if EXTRUDERS > 4
  1697. DISABLE_IDLE_E(4);
  1698. #if EXTRUDERS > 5
  1699. DISABLE_IDLE_E(5);
  1700. #endif // EXTRUDERS > 5
  1701. #endif // EXTRUDERS > 4
  1702. #endif // EXTRUDERS > 3
  1703. #endif // EXTRUDERS > 2
  1704. enable_E1();
  1705. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1706. break;
  1707. #if EXTRUDERS > 2
  1708. case 2:
  1709. DISABLE_IDLE_E(0);
  1710. DISABLE_IDLE_E(1);
  1711. #if EXTRUDERS > 3
  1712. DISABLE_IDLE_E(3);
  1713. #if EXTRUDERS > 4
  1714. DISABLE_IDLE_E(4);
  1715. #if EXTRUDERS > 5
  1716. DISABLE_IDLE_E(5);
  1717. #endif
  1718. #endif
  1719. #endif
  1720. enable_E2();
  1721. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  1722. break;
  1723. #if EXTRUDERS > 3
  1724. case 3:
  1725. DISABLE_IDLE_E(0);
  1726. DISABLE_IDLE_E(1);
  1727. DISABLE_IDLE_E(2);
  1728. #if EXTRUDERS > 4
  1729. DISABLE_IDLE_E(4);
  1730. #if EXTRUDERS > 5
  1731. DISABLE_IDLE_E(5);
  1732. #endif
  1733. #endif
  1734. enable_E3();
  1735. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  1736. break;
  1737. #if EXTRUDERS > 4
  1738. case 4:
  1739. DISABLE_IDLE_E(0);
  1740. DISABLE_IDLE_E(1);
  1741. DISABLE_IDLE_E(2);
  1742. DISABLE_IDLE_E(3);
  1743. #if EXTRUDERS > 5
  1744. DISABLE_IDLE_E(5);
  1745. #endif
  1746. enable_E4();
  1747. g_uc_extruder_last_move[4] = (BLOCK_BUFFER_SIZE) * 2;
  1748. break;
  1749. #if EXTRUDERS > 5
  1750. case 5:
  1751. DISABLE_IDLE_E(0);
  1752. DISABLE_IDLE_E(1);
  1753. DISABLE_IDLE_E(2);
  1754. DISABLE_IDLE_E(3);
  1755. DISABLE_IDLE_E(4);
  1756. enable_E5();
  1757. g_uc_extruder_last_move[5] = (BLOCK_BUFFER_SIZE) * 2;
  1758. break;
  1759. #endif // EXTRUDERS > 5
  1760. #endif // EXTRUDERS > 4
  1761. #endif // EXTRUDERS > 3
  1762. #endif // EXTRUDERS > 2
  1763. #endif // EXTRUDERS > 1
  1764. }
  1765. #else
  1766. enable_E0();
  1767. enable_E1();
  1768. enable_E2();
  1769. enable_E3();
  1770. enable_E4();
  1771. enable_E5();
  1772. #endif
  1773. }
  1774. #endif // EXTRUDERS
  1775. if (esteps)
  1776. NOLESS(fr_mm_s, settings.min_feedrate_mm_s);
  1777. else
  1778. NOLESS(fr_mm_s, settings.min_travel_feedrate_mm_s);
  1779. const float inverse_millimeters = 1.0f / block->millimeters; // Inverse millimeters to remove multiple divides
  1780. // Calculate inverse time for this move. No divide by zero due to previous checks.
  1781. // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
  1782. float inverse_secs = fr_mm_s * inverse_millimeters;
  1783. // Get the number of non busy movements in queue (non busy means that they can be altered)
  1784. const uint8_t moves_queued = nonbusy_movesplanned();
  1785. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  1786. #if EITHER(SLOWDOWN, ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
  1787. // Segment time im micro seconds
  1788. uint32_t segment_time_us = LROUND(1000000.0f / inverse_secs);
  1789. #endif
  1790. #if ENABLED(SLOWDOWN)
  1791. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / 2 - 1)) {
  1792. if (segment_time_us < settings.min_segment_time_us) {
  1793. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  1794. const uint32_t nst = segment_time_us + LROUND(2 * (settings.min_segment_time_us - segment_time_us) / moves_queued);
  1795. inverse_secs = 1000000.0f / nst;
  1796. #if defined(XY_FREQUENCY_LIMIT) || HAS_SPI_LCD
  1797. segment_time_us = nst;
  1798. #endif
  1799. }
  1800. }
  1801. #endif
  1802. #if HAS_SPI_LCD
  1803. // Protect the access to the position.
  1804. const bool was_enabled = STEPPER_ISR_ENABLED();
  1805. if (was_enabled) DISABLE_STEPPER_DRIVER_INTERRUPT();
  1806. block_buffer_runtime_us += segment_time_us;
  1807. block->segment_time_us = segment_time_us;
  1808. if (was_enabled) ENABLE_STEPPER_DRIVER_INTERRUPT();
  1809. #endif
  1810. block->nominal_speed_sqr = sq(block->millimeters * inverse_secs); // (mm/sec)^2 Always > 0
  1811. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  1812. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1813. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM) // Only for extruder with filament sensor
  1814. filwidth.advance_e(delta_mm[E_AXIS]);
  1815. #endif
  1816. // Calculate and limit speed in mm/sec for each axis
  1817. float current_speed[NUM_AXIS], speed_factor = 1.0f; // factor <1 decreases speed
  1818. LOOP_XYZE(i) {
  1819. #if BOTH(MIXING_EXTRUDER, RETRACT_SYNC_MIXING)
  1820. // In worst case, only one extruder running, no change is needed.
  1821. // In best case, all extruders run the same amount, we can divide by MIXING_STEPPERS
  1822. float delta_mm_i = 0;
  1823. if (i == E_AXIS && mixer.get_current_vtool() == MIXER_AUTORETRACT_TOOL)
  1824. delta_mm_i = delta_mm[i] / MIXING_STEPPERS;
  1825. else
  1826. delta_mm_i = delta_mm[i];
  1827. #else
  1828. const float delta_mm_i = delta_mm[i];
  1829. #endif
  1830. const float cs = ABS(current_speed[i] = delta_mm_i * inverse_secs);
  1831. #if ENABLED(DISTINCT_E_FACTORS)
  1832. if (i == E_AXIS) i += extruder;
  1833. #endif
  1834. if (cs > settings.max_feedrate_mm_s[i]) NOMORE(speed_factor, settings.max_feedrate_mm_s[i] / cs);
  1835. }
  1836. // Max segment time in µs.
  1837. #ifdef XY_FREQUENCY_LIMIT
  1838. // Check and limit the xy direction change frequency
  1839. const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  1840. old_direction_bits = block->direction_bits;
  1841. segment_time_us = LROUND((float)segment_time_us / speed_factor);
  1842. uint32_t xs0 = axis_segment_time_us[X_AXIS][0],
  1843. xs1 = axis_segment_time_us[X_AXIS][1],
  1844. xs2 = axis_segment_time_us[X_AXIS][2],
  1845. ys0 = axis_segment_time_us[Y_AXIS][0],
  1846. ys1 = axis_segment_time_us[Y_AXIS][1],
  1847. ys2 = axis_segment_time_us[Y_AXIS][2];
  1848. if (TEST(direction_change, X_AXIS)) {
  1849. xs2 = axis_segment_time_us[X_AXIS][2] = xs1;
  1850. xs1 = axis_segment_time_us[X_AXIS][1] = xs0;
  1851. xs0 = 0;
  1852. }
  1853. xs0 = axis_segment_time_us[X_AXIS][0] = xs0 + segment_time_us;
  1854. if (TEST(direction_change, Y_AXIS)) {
  1855. ys2 = axis_segment_time_us[Y_AXIS][2] = axis_segment_time_us[Y_AXIS][1];
  1856. ys1 = axis_segment_time_us[Y_AXIS][1] = axis_segment_time_us[Y_AXIS][0];
  1857. ys0 = 0;
  1858. }
  1859. ys0 = axis_segment_time_us[Y_AXIS][0] = ys0 + segment_time_us;
  1860. const uint32_t max_x_segment_time = _MAX(xs0, xs1, xs2),
  1861. max_y_segment_time = _MAX(ys0, ys1, ys2),
  1862. min_xy_segment_time = _MIN(max_x_segment_time, max_y_segment_time);
  1863. if (min_xy_segment_time < MAX_FREQ_TIME_US) {
  1864. const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
  1865. NOMORE(speed_factor, low_sf);
  1866. }
  1867. #endif // XY_FREQUENCY_LIMIT
  1868. // Correct the speed
  1869. if (speed_factor < 1.0f) {
  1870. LOOP_XYZE(i) current_speed[i] *= speed_factor;
  1871. block->nominal_rate *= speed_factor;
  1872. block->nominal_speed_sqr = block->nominal_speed_sqr * sq(speed_factor);
  1873. }
  1874. // Compute and limit the acceleration rate for the trapezoid generator.
  1875. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  1876. uint32_t accel;
  1877. if (!block->steps[A_AXIS] && !block->steps[B_AXIS] && !block->steps[C_AXIS]) {
  1878. // convert to: acceleration steps/sec^2
  1879. accel = CEIL(settings.retract_acceleration * steps_per_mm);
  1880. #if ENABLED(LIN_ADVANCE)
  1881. block->use_advance_lead = false;
  1882. #endif
  1883. }
  1884. else {
  1885. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  1886. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1887. const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
  1888. if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
  1889. } \
  1890. }while(0)
  1891. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  1892. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1893. const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
  1894. if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
  1895. } \
  1896. }while(0)
  1897. // Start with print or travel acceleration
  1898. accel = CEIL((esteps ? settings.acceleration : settings.travel_acceleration) * steps_per_mm);
  1899. #if ENABLED(LIN_ADVANCE)
  1900. #if ENABLED(JUNCTION_DEVIATION)
  1901. #if ENABLED(DISTINCT_E_FACTORS)
  1902. #define MAX_E_JERK max_e_jerk[extruder]
  1903. #else
  1904. #define MAX_E_JERK max_e_jerk
  1905. #endif
  1906. #else
  1907. #define MAX_E_JERK max_jerk[E_AXIS]
  1908. #endif
  1909. /**
  1910. *
  1911. * Use LIN_ADVANCE for blocks if all these are true:
  1912. *
  1913. * esteps : This is a print move, because we checked for A, B, C steps before.
  1914. *
  1915. * extruder_advance_K[active_extruder] : There is an advance factor set for this extruder.
  1916. *
  1917. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  1918. */
  1919. block->use_advance_lead = esteps
  1920. && extruder_advance_K[active_extruder]
  1921. && de > 0;
  1922. if (block->use_advance_lead) {
  1923. block->e_D_ratio = (target_float[E_AXIS] - position_float[E_AXIS]) /
  1924. #if IS_KINEMATIC
  1925. block->millimeters
  1926. #else
  1927. SQRT(sq(target_float[X_AXIS] - position_float[X_AXIS])
  1928. + sq(target_float[Y_AXIS] - position_float[Y_AXIS])
  1929. + sq(target_float[Z_AXIS] - position_float[Z_AXIS]))
  1930. #endif
  1931. ;
  1932. // Check for unusual high e_D ratio to detect if a retract move was combined with the last print move due to min. steps per segment. Never execute this with advance!
  1933. // This assumes no one will use a retract length of 0mm < retr_length < ~0.2mm and no one will print 100mm wide lines using 3mm filament or 35mm wide lines using 1.75mm filament.
  1934. if (block->e_D_ratio > 3.0f)
  1935. block->use_advance_lead = false;
  1936. else {
  1937. const uint32_t max_accel_steps_per_s2 = MAX_E_JERK / (extruder_advance_K[active_extruder] * block->e_D_ratio) * steps_per_mm;
  1938. #if ENABLED(LA_DEBUG)
  1939. if (accel > max_accel_steps_per_s2) SERIAL_ECHOLNPGM("Acceleration limited.");
  1940. #endif
  1941. NOMORE(accel, max_accel_steps_per_s2);
  1942. }
  1943. }
  1944. #endif
  1945. #if ENABLED(DISTINCT_E_FACTORS)
  1946. #define ACCEL_IDX extruder
  1947. #else
  1948. #define ACCEL_IDX 0
  1949. #endif
  1950. // Limit acceleration per axis
  1951. if (block->step_event_count <= cutoff_long) {
  1952. LIMIT_ACCEL_LONG(A_AXIS, 0);
  1953. LIMIT_ACCEL_LONG(B_AXIS, 0);
  1954. LIMIT_ACCEL_LONG(C_AXIS, 0);
  1955. LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
  1956. }
  1957. else {
  1958. LIMIT_ACCEL_FLOAT(A_AXIS, 0);
  1959. LIMIT_ACCEL_FLOAT(B_AXIS, 0);
  1960. LIMIT_ACCEL_FLOAT(C_AXIS, 0);
  1961. LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
  1962. }
  1963. }
  1964. block->acceleration_steps_per_s2 = accel;
  1965. block->acceleration = accel / steps_per_mm;
  1966. #if DISABLED(S_CURVE_ACCELERATION)
  1967. block->acceleration_rate = (uint32_t)(accel * (4096.0f * 4096.0f / (STEPPER_TIMER_RATE)));
  1968. #endif
  1969. #if ENABLED(LIN_ADVANCE)
  1970. if (block->use_advance_lead) {
  1971. block->advance_speed = (STEPPER_TIMER_RATE) / (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * settings.axis_steps_per_mm[E_AXIS_N(extruder)]);
  1972. #if ENABLED(LA_DEBUG)
  1973. if (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * 2 < SQRT(block->nominal_speed_sqr) * block->e_D_ratio)
  1974. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  1975. if (block->advance_speed < 200)
  1976. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  1977. #endif
  1978. }
  1979. #endif
  1980. float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2
  1981. #if ENABLED(JUNCTION_DEVIATION)
  1982. /**
  1983. * Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  1984. * Let a circle be tangent to both previous and current path line segments, where the junction
  1985. * deviation is defined as the distance from the junction to the closest edge of the circle,
  1986. * colinear with the circle center. The circular segment joining the two paths represents the
  1987. * path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  1988. * radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  1989. * path width or max_jerk in the previous Grbl version. This approach does not actually deviate
  1990. * from path, but used as a robust way to compute cornering speeds, as it takes into account the
  1991. * nonlinearities of both the junction angle and junction velocity.
  1992. *
  1993. * NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path
  1994. * mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact
  1995. * stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here
  1996. * is exactly the same. Instead of motioning all the way to junction point, the machine will
  1997. * just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
  1998. * a continuous mode path, but ARM-based microcontrollers most certainly do.
  1999. *
  2000. * NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
  2001. * changed dynamically during operation nor can the line move geometry. This must be kept in
  2002. * memory in the event of a feedrate override changing the nominal speeds of blocks, which can
  2003. * change the overall maximum entry speed conditions of all blocks.
  2004. *
  2005. * #######
  2006. * https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754
  2007. *
  2008. * hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin:
  2009. Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm
  2010. on then on anything with less sides than an octagon. With this, and the
  2011. reverse pass actually recalculating things, a corner acceleration value
  2012. of 1000 junction deviation of .05 are pretty reasonable. If the cycles
  2013. can be spared, a better acos could be used. For all I know, it may be
  2014. already calculated in a different place. */
  2015. // Unit vector of previous path line segment
  2016. static float previous_unit_vec[XYZE];
  2017. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  2018. float unit_vec[] = {
  2019. delta_mm_cart[X_AXIS] * inverse_millimeters,
  2020. delta_mm_cart[Y_AXIS] * inverse_millimeters,
  2021. delta_mm_cart[Z_AXIS] * inverse_millimeters,
  2022. delta_mm_cart[E_AXIS] * inverse_millimeters
  2023. };
  2024. #else
  2025. float unit_vec[] = {
  2026. delta_mm[X_AXIS] * inverse_millimeters,
  2027. delta_mm[Y_AXIS] * inverse_millimeters,
  2028. delta_mm[Z_AXIS] * inverse_millimeters,
  2029. delta_mm[E_AXIS] * inverse_millimeters
  2030. };
  2031. #endif
  2032. #if IS_CORE && ENABLED(JUNCTION_DEVIATION)
  2033. /**
  2034. * On CoreXY the length of the vector [A,B] is SQRT(2) times the length of the head movement vector [X,Y].
  2035. * So taking Z and E into account, we cannot scale to a unit vector with "inverse_millimeters".
  2036. * => normalize the complete junction vector
  2037. */
  2038. normalize_junction_vector(unit_vec);
  2039. #endif
  2040. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  2041. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2042. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  2043. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  2044. float junction_cos_theta = -previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  2045. -previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  2046. -previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS]
  2047. -previous_unit_vec[E_AXIS] * unit_vec[E_AXIS]
  2048. ;
  2049. // NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
  2050. if (junction_cos_theta > 0.999999f) {
  2051. // For a 0 degree acute junction, just set minimum junction speed.
  2052. vmax_junction_sqr = sq(float(MINIMUM_PLANNER_SPEED));
  2053. }
  2054. else {
  2055. NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero.
  2056. // Convert delta vector to unit vector
  2057. float junction_unit_vec[XYZE] = {
  2058. unit_vec[X_AXIS] - previous_unit_vec[X_AXIS],
  2059. unit_vec[Y_AXIS] - previous_unit_vec[Y_AXIS],
  2060. unit_vec[Z_AXIS] - previous_unit_vec[Z_AXIS],
  2061. unit_vec[E_AXIS] - previous_unit_vec[E_AXIS]
  2062. };
  2063. normalize_junction_vector(junction_unit_vec);
  2064. const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec),
  2065. sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive.
  2066. vmax_junction_sqr = (junction_acceleration * junction_deviation_mm * sin_theta_d2) / (1.0f - sin_theta_d2);
  2067. if (block->millimeters < 1) {
  2068. // Fast acos approximation, minus the error bar to be safe
  2069. const float junction_theta = (RADIANS(-40) * sq(junction_cos_theta) - RADIANS(50)) * junction_cos_theta + RADIANS(90) - 0.18f;
  2070. // If angle is greater than 135 degrees (octagon), find speed for approximate arc
  2071. if (junction_theta > RADIANS(135)) {
  2072. const float limit_sqr = block->millimeters / (RADIANS(180) - junction_theta) * junction_acceleration;
  2073. NOMORE(vmax_junction_sqr, limit_sqr);
  2074. }
  2075. }
  2076. }
  2077. // Get the lowest speed
  2078. vmax_junction_sqr = _MIN(vmax_junction_sqr, block->nominal_speed_sqr, previous_nominal_speed_sqr);
  2079. }
  2080. else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later.
  2081. vmax_junction_sqr = 0;
  2082. COPY(previous_unit_vec, unit_vec);
  2083. #endif
  2084. #if HAS_CLASSIC_JERK
  2085. /**
  2086. * Adapted from Průša MKS firmware
  2087. * https://github.com/prusa3d/Prusa-Firmware
  2088. */
  2089. const float nominal_speed = SQRT(block->nominal_speed_sqr);
  2090. // Exit speed limited by a jerk to full halt of a previous last segment
  2091. static float previous_safe_speed;
  2092. // Start with a safe speed (from which the machine may halt to stop immediately).
  2093. float safe_speed = nominal_speed;
  2094. uint8_t limited = 0;
  2095. #if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
  2096. LOOP_XYZ(i)
  2097. #else
  2098. LOOP_XYZE(i)
  2099. #endif
  2100. {
  2101. const float jerk = ABS(current_speed[i]), // cs : Starting from zero, change in speed for this axis
  2102. maxj = max_jerk[i]; // mj : The max jerk setting for this axis
  2103. if (jerk > maxj) { // cs > mj : New current speed too fast?
  2104. if (limited) { // limited already?
  2105. const float mjerk = nominal_speed * maxj; // ns*mj
  2106. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk; // ns*mj/cs
  2107. }
  2108. else {
  2109. safe_speed *= maxj / jerk; // Initial limit: ns*mj/cs
  2110. ++limited; // Initially limited
  2111. }
  2112. }
  2113. }
  2114. float vmax_junction;
  2115. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2116. // Estimate a maximum velocity allowed at a joint of two successive segments.
  2117. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  2118. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  2119. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  2120. float v_factor = 1;
  2121. limited = 0;
  2122. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  2123. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  2124. const float previous_nominal_speed = SQRT(previous_nominal_speed_sqr);
  2125. vmax_junction = _MIN(nominal_speed, previous_nominal_speed);
  2126. // Now limit the jerk in all axes.
  2127. const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
  2128. #if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
  2129. LOOP_XYZ(axis)
  2130. #else
  2131. LOOP_XYZE(axis)
  2132. #endif
  2133. {
  2134. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  2135. float v_exit = previous_speed[axis] * smaller_speed_factor,
  2136. v_entry = current_speed[axis];
  2137. if (limited) {
  2138. v_exit *= v_factor;
  2139. v_entry *= v_factor;
  2140. }
  2141. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  2142. const float jerk = (v_exit > v_entry)
  2143. ? // coasting axis reversal
  2144. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : _MAX(v_exit, -v_entry) )
  2145. : // v_exit <= v_entry coasting axis reversal
  2146. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : _MAX(-v_exit, v_entry) );
  2147. if (jerk > max_jerk[axis]) {
  2148. v_factor *= max_jerk[axis] / jerk;
  2149. ++limited;
  2150. }
  2151. }
  2152. if (limited) vmax_junction *= v_factor;
  2153. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  2154. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  2155. const float vmax_junction_threshold = vmax_junction * 0.99f;
  2156. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  2157. vmax_junction = safe_speed;
  2158. }
  2159. else
  2160. vmax_junction = safe_speed;
  2161. previous_safe_speed = safe_speed;
  2162. #if ENABLED(JUNCTION_DEVIATION)
  2163. vmax_junction_sqr = _MIN(vmax_junction_sqr, sq(vmax_junction));
  2164. #else
  2165. vmax_junction_sqr = sq(vmax_junction);
  2166. #endif
  2167. #endif // Classic Jerk Limiting
  2168. // Max entry speed of this block equals the max exit speed of the previous block.
  2169. block->max_entry_speed_sqr = vmax_junction_sqr;
  2170. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  2171. const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, sq(float(MINIMUM_PLANNER_SPEED)), block->millimeters);
  2172. // If we are trying to add a split block, start with the
  2173. // max. allowed speed to avoid an interrupted first move.
  2174. block->entry_speed_sqr = !split_move ? sq(float(MINIMUM_PLANNER_SPEED)) : _MIN(vmax_junction_sqr, v_allowable_sqr);
  2175. // Initialize planner efficiency flags
  2176. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  2177. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  2178. // the current block and next block junction speeds are guaranteed to always be at their maximum
  2179. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  2180. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  2181. // the reverse and forward planners, the corresponding block junction speed will always be at the
  2182. // the maximum junction speed and may always be ignored for any speed reduction checks.
  2183. block->flag |= block->nominal_speed_sqr <= v_allowable_sqr ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
  2184. // Update previous path unit_vector and nominal speed
  2185. COPY(previous_speed, current_speed);
  2186. previous_nominal_speed_sqr = block->nominal_speed_sqr;
  2187. // Update the position
  2188. static_assert(COUNT(target) > 1, "Parameter to _buffer_steps must be (&target)[XYZE]!");
  2189. COPY(position, target);
  2190. #if HAS_POSITION_FLOAT
  2191. COPY(position_float, target_float);
  2192. #endif
  2193. #if ENABLED(GRADIENT_MIX)
  2194. mixer.gradient_control(target_float[Z_AXIS]);
  2195. #endif
  2196. #if ENABLED(POWER_LOSS_RECOVERY)
  2197. block->sdpos = recovery.command_sdpos();
  2198. #endif
  2199. // Movement was accepted
  2200. return true;
  2201. } // _populate_block()
  2202. /**
  2203. * Planner::buffer_sync_block
  2204. * Add a block to the buffer that just updates the position
  2205. */
  2206. void Planner::buffer_sync_block() {
  2207. // Wait for the next available block
  2208. uint8_t next_buffer_head;
  2209. block_t * const block = get_next_free_block(next_buffer_head);
  2210. // Clear block
  2211. memset(block, 0, sizeof(block_t));
  2212. block->flag = BLOCK_FLAG_SYNC_POSITION;
  2213. block->position[A_AXIS] = position[A_AXIS];
  2214. block->position[B_AXIS] = position[B_AXIS];
  2215. block->position[C_AXIS] = position[C_AXIS];
  2216. block->position[E_AXIS] = position[E_AXIS];
  2217. // If this is the first added movement, reload the delay, otherwise, cancel it.
  2218. if (block_buffer_head == block_buffer_tail) {
  2219. // If it was the first queued block, restart the 1st block delivery delay, to
  2220. // give the planner an opportunity to queue more movements and plan them
  2221. // As there are no queued movements, the Stepper ISR will not touch this
  2222. // variable, so there is no risk setting this here (but it MUST be done
  2223. // before the following line!!)
  2224. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  2225. }
  2226. block_buffer_head = next_buffer_head;
  2227. stepper.wake_up();
  2228. } // buffer_sync_block()
  2229. /**
  2230. * Planner::buffer_segment
  2231. *
  2232. * Add a new linear movement to the buffer in axis units.
  2233. *
  2234. * Leveling and kinematics should be applied ahead of calling this.
  2235. *
  2236. * a,b,c,e - target positions in mm and/or degrees
  2237. * fr_mm_s - (target) speed of the move
  2238. * extruder - target extruder
  2239. * millimeters - the length of the movement, if known
  2240. */
  2241. bool Planner::buffer_segment(const float &a, const float &b, const float &c, const float &e
  2242. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  2243. , const float (&delta_mm_cart)[XYZE]
  2244. #endif
  2245. , const float &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  2246. ) {
  2247. // If we are cleaning, do not accept queuing of movements
  2248. if (cleaning_buffer_counter) return false;
  2249. // When changing extruders recalculate steps corresponding to the E position
  2250. #if ENABLED(DISTINCT_E_FACTORS)
  2251. if (last_extruder != extruder && settings.axis_steps_per_mm[E_AXIS_N(extruder)] != settings.axis_steps_per_mm[E_AXIS_N(last_extruder)]) {
  2252. position[E_AXIS] = LROUND(position[E_AXIS] * settings.axis_steps_per_mm[E_AXIS_N(extruder)] * steps_to_mm[E_AXIS_N(last_extruder)]);
  2253. last_extruder = extruder;
  2254. }
  2255. #endif
  2256. // The target position of the tool in absolute steps
  2257. // Calculate target position in absolute steps
  2258. const int32_t target[ABCE] = {
  2259. int32_t(LROUND(a * settings.axis_steps_per_mm[A_AXIS])),
  2260. int32_t(LROUND(b * settings.axis_steps_per_mm[B_AXIS])),
  2261. int32_t(LROUND(c * settings.axis_steps_per_mm[C_AXIS])),
  2262. int32_t(LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(extruder)]))
  2263. };
  2264. #if HAS_POSITION_FLOAT
  2265. const float target_float[XYZE] = { a, b, c, e };
  2266. #endif
  2267. // DRYRUN prevents E moves from taking place
  2268. if (DEBUGGING(DRYRUN)) {
  2269. position[E_AXIS] = target[E_AXIS];
  2270. #if HAS_POSITION_FLOAT
  2271. position_float[E_AXIS] = e;
  2272. #endif
  2273. }
  2274. /* <-- add a slash to enable
  2275. SERIAL_ECHOPAIR(" buffer_segment FR:", fr_mm_s);
  2276. #if IS_KINEMATIC
  2277. SERIAL_ECHOPAIR(" A:", a);
  2278. SERIAL_ECHOPAIR(" (", position[A_AXIS]);
  2279. SERIAL_ECHOPAIR("->", target[A_AXIS]);
  2280. SERIAL_ECHOPAIR(") B:", b);
  2281. #else
  2282. SERIAL_ECHOPAIR(" X:", a);
  2283. SERIAL_ECHOPAIR(" (", position[X_AXIS]);
  2284. SERIAL_ECHOPAIR("->", target[X_AXIS]);
  2285. SERIAL_ECHOPAIR(") Y:", b);
  2286. #endif
  2287. SERIAL_ECHOPAIR(" (", position[Y_AXIS]);
  2288. SERIAL_ECHOPAIR("->", target[Y_AXIS]);
  2289. #if ENABLED(DELTA)
  2290. SERIAL_ECHOPAIR(") C:", c);
  2291. #else
  2292. SERIAL_ECHOPAIR(") Z:", c);
  2293. #endif
  2294. SERIAL_ECHOPAIR(" (", position[Z_AXIS]);
  2295. SERIAL_ECHOPAIR("->", target[Z_AXIS]);
  2296. SERIAL_ECHOPAIR(") E:", e);
  2297. SERIAL_ECHOPAIR(" (", position[E_AXIS]);
  2298. SERIAL_ECHOPAIR("->", target[E_AXIS]);
  2299. SERIAL_ECHOLNPGM(")");
  2300. //*/
  2301. // Queue the movement
  2302. if (
  2303. !_buffer_steps(target
  2304. #if HAS_POSITION_FLOAT
  2305. , target_float
  2306. #endif
  2307. #if IS_KINEMATIC && ENABLED(JUNCTION_DEVIATION)
  2308. , delta_mm_cart
  2309. #endif
  2310. , fr_mm_s, extruder, millimeters
  2311. )
  2312. ) return false;
  2313. stepper.wake_up();
  2314. return true;
  2315. } // buffer_segment()
  2316. /**
  2317. * Add a new linear movement to the buffer.
  2318. * The target is cartesian, it's translated to delta/scara if
  2319. * needed.
  2320. *
  2321. *
  2322. * rx,ry,rz,e - target position in mm or degrees
  2323. * fr_mm_s - (target) speed of the move (mm/s)
  2324. * extruder - target extruder
  2325. * millimeters - the length of the movement, if known
  2326. * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
  2327. */
  2328. bool Planner::buffer_line(const float &rx, const float &ry, const float &rz, const float &e, const float &fr_mm_s, const uint8_t extruder, const float millimeters
  2329. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2330. , const float &inv_duration
  2331. #endif
  2332. ) {
  2333. float raw[XYZE] = { rx, ry, rz, e };
  2334. #if HAS_POSITION_MODIFIERS
  2335. apply_modifiers(raw);
  2336. #endif
  2337. #if IS_KINEMATIC
  2338. const float delta_mm_cart[] = {
  2339. rx - position_cart[X_AXIS],
  2340. ry - position_cart[Y_AXIS],
  2341. rz - position_cart[Z_AXIS]
  2342. #if ENABLED(JUNCTION_DEVIATION)
  2343. , e - position_cart[E_AXIS]
  2344. #endif
  2345. };
  2346. float mm = millimeters;
  2347. if (mm == 0.0)
  2348. mm = (delta_mm_cart[X_AXIS] != 0.0 || delta_mm_cart[Y_AXIS] != 0.0) ? SQRT(sq(delta_mm_cart[X_AXIS]) + sq(delta_mm_cart[Y_AXIS]) + sq(delta_mm_cart[Z_AXIS])) : ABS(delta_mm_cart[Z_AXIS]);
  2349. inverse_kinematics(raw);
  2350. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2351. // For SCARA scale the feed rate from mm/s to degrees/s
  2352. // i.e., Complete the angular vector in the given time.
  2353. const float duration_recip = inv_duration ? inv_duration : fr_mm_s / mm,
  2354. feedrate = HYPOT(delta[A_AXIS] - position_float[A_AXIS], delta[B_AXIS] - position_float[B_AXIS]) * duration_recip;
  2355. #else
  2356. const float feedrate = fr_mm_s;
  2357. #endif
  2358. if (buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS]
  2359. #if ENABLED(JUNCTION_DEVIATION)
  2360. , delta_mm_cart
  2361. #endif
  2362. , feedrate, extruder, mm
  2363. )) {
  2364. position_cart[X_AXIS] = rx;
  2365. position_cart[Y_AXIS] = ry;
  2366. position_cart[Z_AXIS] = rz;
  2367. position_cart[E_AXIS] = e;
  2368. return true;
  2369. }
  2370. else
  2371. return false;
  2372. #else
  2373. return buffer_segment(raw, fr_mm_s, extruder, millimeters);
  2374. #endif
  2375. } // buffer_line()
  2376. /**
  2377. * Directly set the planner ABC position (and stepper positions)
  2378. * converting mm (or angles for SCARA) into steps.
  2379. *
  2380. * The provided ABC position is in machine units.
  2381. */
  2382. void Planner::set_machine_position_mm(const float &a, const float &b, const float &c, const float &e) {
  2383. #if ENABLED(DISTINCT_E_FACTORS)
  2384. last_extruder = active_extruder;
  2385. #endif
  2386. position[A_AXIS] = LROUND(a * settings.axis_steps_per_mm[A_AXIS]);
  2387. position[B_AXIS] = LROUND(b * settings.axis_steps_per_mm[B_AXIS]);
  2388. position[C_AXIS] = LROUND(c * settings.axis_steps_per_mm[C_AXIS]);
  2389. position[E_AXIS] = LROUND(e * settings.axis_steps_per_mm[E_AXIS_N(active_extruder)]);
  2390. #if HAS_POSITION_FLOAT
  2391. position_float[A_AXIS] = a;
  2392. position_float[B_AXIS] = b;
  2393. position_float[C_AXIS] = c;
  2394. position_float[E_AXIS] = e;
  2395. #endif
  2396. if (has_blocks_queued()) {
  2397. //previous_nominal_speed_sqr = 0.0; // Reset planner junction speeds. Assume start from rest.
  2398. //ZERO(previous_speed);
  2399. buffer_sync_block();
  2400. }
  2401. else
  2402. stepper.set_position(position[A_AXIS], position[B_AXIS], position[C_AXIS], position[E_AXIS]);
  2403. }
  2404. void Planner::set_position_mm(const float &rx, const float &ry, const float &rz, const float &e) {
  2405. float raw[XYZE] = { rx, ry, rz, e };
  2406. #if HAS_POSITION_MODIFIERS
  2407. {
  2408. apply_modifiers(raw
  2409. #if HAS_LEVELING
  2410. , true
  2411. #endif
  2412. );
  2413. }
  2414. #endif
  2415. #if IS_KINEMATIC
  2416. position_cart[X_AXIS] = rx;
  2417. position_cart[Y_AXIS] = ry;
  2418. position_cart[Z_AXIS] = rz;
  2419. position_cart[E_AXIS] = e;
  2420. inverse_kinematics(raw);
  2421. set_machine_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS]);
  2422. #else
  2423. set_machine_position_mm(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], raw[E_AXIS]);
  2424. #endif
  2425. }
  2426. /**
  2427. * Setters for planner position (also setting stepper position).
  2428. */
  2429. void Planner::set_e_position_mm(const float &e) {
  2430. const uint8_t axis_index = E_AXIS_N(active_extruder);
  2431. #if ENABLED(DISTINCT_E_FACTORS)
  2432. last_extruder = active_extruder;
  2433. #endif
  2434. #if ENABLED(FWRETRACT)
  2435. float e_new = e - fwretract.current_retract[active_extruder];
  2436. #else
  2437. const float e_new = e;
  2438. #endif
  2439. position[E_AXIS] = LROUND(settings.axis_steps_per_mm[axis_index] * e_new);
  2440. #if HAS_POSITION_FLOAT
  2441. position_float[E_AXIS] = e_new;
  2442. #endif
  2443. #if IS_KINEMATIC
  2444. position_cart[E_AXIS] = e;
  2445. #endif
  2446. if (has_blocks_queued())
  2447. buffer_sync_block();
  2448. else
  2449. stepper.set_position(E_AXIS, position[E_AXIS]);
  2450. }
  2451. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  2452. void Planner::reset_acceleration_rates() {
  2453. #if ENABLED(DISTINCT_E_FACTORS)
  2454. #define AXIS_CONDITION (i < E_AXIS || i == E_AXIS_N(active_extruder))
  2455. #else
  2456. #define AXIS_CONDITION true
  2457. #endif
  2458. uint32_t highest_rate = 1;
  2459. LOOP_XYZE_N(i) {
  2460. max_acceleration_steps_per_s2[i] = settings.max_acceleration_mm_per_s2[i] * settings.axis_steps_per_mm[i];
  2461. if (AXIS_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  2462. }
  2463. cutoff_long = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
  2464. #if BOTH(JUNCTION_DEVIATION, LIN_ADVANCE)
  2465. recalculate_max_e_jerk();
  2466. #endif
  2467. }
  2468. // Recalculate position, steps_to_mm if settings.axis_steps_per_mm changes!
  2469. void Planner::refresh_positioning() {
  2470. LOOP_XYZE_N(i) steps_to_mm[i] = 1.0f / settings.axis_steps_per_mm[i];
  2471. set_position_mm(current_position);
  2472. reset_acceleration_rates();
  2473. }
  2474. #if ENABLED(AUTOTEMP)
  2475. void Planner::autotemp_M104_M109() {
  2476. if ((autotemp_enabled = parser.seen('F'))) autotemp_factor = parser.value_float();
  2477. if (parser.seen('S')) autotemp_min = parser.value_celsius();
  2478. if (parser.seen('B')) autotemp_max = parser.value_celsius();
  2479. }
  2480. #endif