My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

planner.cpp 105KB

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