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

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