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

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