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

planner.cpp 141KB

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