planner.cpp 109 KB

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