My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

planner.cpp 110KB

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