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

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