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

planner.cpp 87KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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. Planner planner;
  87. // public:
  88. /**
  89. * A ring buffer of moves described in steps
  90. */
  91. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  92. volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
  93. Planner::block_buffer_tail;
  94. float Planner::max_feedrate_mm_s[XYZE_N], // Max speeds in mm per second
  95. Planner::axis_steps_per_mm[XYZE_N],
  96. Planner::steps_to_mm[XYZE_N];
  97. #if ENABLED(DISTINCT_E_FACTORS)
  98. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  99. #endif
  100. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  101. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0); // The flow percentage and volumetric multiplier combine to scale E movement
  102. #if DISABLED(NO_VOLUMETRICS)
  103. 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
  104. Planner::volumetric_area_nominal = CIRCLE_AREA((DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5), // Nominal cross-sectional area
  105. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  106. #endif
  107. uint32_t Planner::max_acceleration_steps_per_s2[XYZE_N],
  108. Planner::max_acceleration_mm_per_s2[XYZE_N]; // Use M201 to override by software
  109. uint32_t Planner::min_segment_time_us;
  110. // Initialized by settings.load()
  111. float Planner::min_feedrate_mm_s,
  112. Planner::acceleration, // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  113. Planner::retract_acceleration, // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  114. Planner::travel_acceleration, // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  115. Planner::max_jerk[XYZE], // The largest speed change requiring no acceleration
  116. Planner::min_travel_feedrate_mm_s;
  117. #if HAS_LEVELING
  118. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  119. #if ABL_PLANAR
  120. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  121. #endif
  122. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  123. float Planner::z_fade_height, // Initialized by settings.load()
  124. Planner::inverse_z_fade_height,
  125. Planner::last_fade_z;
  126. #endif
  127. #else
  128. constexpr bool Planner::leveling_active;
  129. #endif
  130. #if ENABLED(SKEW_CORRECTION)
  131. #if ENABLED(SKEW_CORRECTION_GCODE)
  132. float Planner::xy_skew_factor;
  133. #else
  134. constexpr float Planner::xy_skew_factor;
  135. #endif
  136. #if ENABLED(SKEW_CORRECTION_FOR_Z) && ENABLED(SKEW_CORRECTION_GCODE)
  137. float Planner::xz_skew_factor, Planner::yz_skew_factor;
  138. #else
  139. constexpr float Planner::xz_skew_factor, Planner::yz_skew_factor;
  140. #endif
  141. #endif
  142. #if ENABLED(AUTOTEMP)
  143. float Planner::autotemp_max = 250,
  144. Planner::autotemp_min = 210,
  145. Planner::autotemp_factor = 0.1;
  146. bool Planner::autotemp_enabled = false;
  147. #endif
  148. // private:
  149. int32_t Planner::position[NUM_AXIS] = { 0 };
  150. uint32_t Planner::cutoff_long;
  151. float Planner::previous_speed[NUM_AXIS],
  152. Planner::previous_nominal_speed;
  153. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  154. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  155. #endif
  156. #ifdef XY_FREQUENCY_LIMIT
  157. // Old direction bits. Used for speed calculations
  158. unsigned char Planner::old_direction_bits = 0;
  159. // Segment times (in µs). Used for speed calculations
  160. uint32_t Planner::axis_segment_time_us[2][3] = { { MAX_FREQ_TIME_US + 1, 0, 0 }, { MAX_FREQ_TIME_US + 1, 0, 0 } };
  161. #endif
  162. #if ENABLED(LIN_ADVANCE)
  163. float Planner::extruder_advance_K; // Initialized by settings.load()
  164. #endif
  165. #if HAS_POSITION_FLOAT
  166. float Planner::position_float[XYZE]; // Needed for accurate maths. Steps cannot be used!
  167. #endif
  168. #if ENABLED(ULTRA_LCD)
  169. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  170. #endif
  171. /**
  172. * Class and Instance Methods
  173. */
  174. Planner::Planner() { init(); }
  175. void Planner::init() {
  176. ZERO(position);
  177. #if HAS_POSITION_FLOAT
  178. ZERO(position_float);
  179. #endif
  180. ZERO(previous_speed);
  181. previous_nominal_speed = 0.0;
  182. #if ABL_PLANAR
  183. bed_level_matrix.set_to_identity();
  184. #endif
  185. clear_block_buffer();
  186. }
  187. #if ENABLED(BEZIER_JERK_CONTROL)
  188. #ifdef __AVR__
  189. // This routine, for AVR, returns 0x1000000 / d, but trying to get the inverse as
  190. // fast as possible. A fast converging iterative Newton-Raphson method is able to
  191. // reach full precision in just 1 iteration, and takes 211 cycles (worst case, mean
  192. // case is less, up to 30 cycles for small divisors), instead of the 500 cycles a
  193. // normal division would take.
  194. //
  195. // Inspired by the following page,
  196. // https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
  197. //
  198. // Suppose we want to calculate
  199. // floor(2 ^ k / B) where B is a positive integer
  200. // Then
  201. // B must be <= 2^k, otherwise, the quotient is 0.
  202. //
  203. // The Newton - Raphson iteration for x = B / 2 ^ k yields:
  204. // q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
  205. //
  206. // We can rearrange it as:
  207. // q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
  208. //
  209. // Each iteration of this kind requires only integer multiplications
  210. // and bit shifts.
  211. // Does it converge to floor(2 ^ k / B) ?: Not necessarily, but, in
  212. // the worst case, it eventually alternates between floor(2 ^ k / B)
  213. // and ceiling(2 ^ k / B)).
  214. // So we can use some not-so-clever test to see if we are in this
  215. // case, and extract floor(2 ^ k / B).
  216. // Lastly, a simple but important optimization for this approach is to
  217. // truncate multiplications (i.e.calculate only the higher bits of the
  218. // product) in the early iterations of the Newton - Raphson method.The
  219. // reason to do so, is that the results of the early iterations are far
  220. // from the quotient, and it doesn't matter to perform them inaccurately.
  221. // Finally, we should pick a good starting value for x. Knowing how many
  222. // digits the divisor has, we can estimate it:
  223. //
  224. // 2^k / x = 2 ^ log2(2^k / x)
  225. // 2^k / x = 2 ^(log2(2^k)-log2(x))
  226. // 2^k / x = 2 ^(k*log2(2)-log2(x))
  227. // 2^k / x = 2 ^ (k-log2(x))
  228. // 2^k / x >= 2 ^ (k-floor(log2(x)))
  229. // floor(log2(x)) simply is the index of the most significant bit set.
  230. //
  231. // If we could improve this estimation even further, then the number of
  232. // iterations can be dropped quite a bit, thus saving valuable execution time.
  233. // The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
  234. // Research, Silicon Valley,August 26, 2008, that is available at
  235. // https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
  236. // suggests , for its integer division algorithm, that using a table to supply the
  237. // first 8 bits of precision, and due to the quadratic convergence nature of the
  238. // Newton-Raphon iteration, then just 2 iterations should be enough to get
  239. // maximum precision of the division.
  240. // If we precompute values of inverses for small denominator values, then
  241. // just one Newton-Raphson iteration is enough to reach full precision
  242. // We will use the top 9 bits of the denominator as index.
  243. //
  244. // The AVR assembly function is implementing the following C code, included
  245. // here as reference:
  246. //
  247. // uint32_t get_period_inverse(uint32_t d) {
  248. // static const uint8_t inv_tab[256] = {
  249. // 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  250. // 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  251. // 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  252. // 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  253. // 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  254. // 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  255. // 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  256. // 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  257. // 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  258. // 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  259. // 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  260. // 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  261. // 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  262. // 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  263. // 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  264. // 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  265. // };
  266. //
  267. // // For small denominators, it is cheaper to directly store the result,
  268. // // because those denominators would require 2 Newton-Raphson iterations
  269. // // to converge to the required result precision. For bigger ones, just
  270. // // ONE Newton-Raphson iteration is enough to get maximum precision!
  271. // static const uint32_t small_inv_tab[111] PROGMEM = {
  272. // 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  273. // 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  274. // 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  275. // 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  276. // 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  277. // 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  278. // 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  279. // };
  280. //
  281. // // For small divisors, it is best to directly retrieve the results
  282. // if (d <= 110)
  283. // return pgm_read_dword(&small_inv_tab[d]);
  284. //
  285. // // Compute initial estimation of 0x1000000/x -
  286. // // Get most significant bit set on divider
  287. // uint8_t idx = 0;
  288. // uint32_t nr = d;
  289. // if (!(nr & 0xff0000)) {
  290. // nr <<= 8;
  291. // idx += 8;
  292. // if (!(nr & 0xff0000)) {
  293. // nr <<= 8;
  294. // idx += 8;
  295. // }
  296. // }
  297. // if (!(nr & 0xf00000)) {
  298. // nr <<= 4;
  299. // idx += 4;
  300. // }
  301. // if (!(nr & 0xc00000)) {
  302. // nr <<= 2;
  303. // idx += 2;
  304. // }
  305. // if (!(nr & 0x800000)) {
  306. // nr <<= 1;
  307. // idx += 1;
  308. // }
  309. //
  310. // // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
  311. // uint32_t tidx = nr >> 15; // top 9 bits. bit8 is always set
  312. // uint32_t ie = inv_tab[tidx & 0xFF] + 256; // Get the table value. bit9 is always set
  313. // uint32_t x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place
  314. //
  315. // // Now, refine estimation by newton-raphson. 1 iteration is enough
  316. // x = uint32_t((x * uint64_t((1 << 25) - x * d)) >> 24);
  317. //
  318. // // Estimate remainder
  319. // uint32_t r = (1 << 24) - x * d;
  320. //
  321. // // Check if we must adjust result
  322. // if (r >= d) x++;
  323. //
  324. // // x holds the proper estimation
  325. // return uint32_t(x);
  326. // }
  327. //
  328. static uint32_t get_period_inverse(uint32_t d) {
  329. static const uint8_t inv_tab[256] PROGMEM = {
  330. 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  331. 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  332. 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  333. 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  334. 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  335. 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  336. 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  337. 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  338. 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  339. 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  340. 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  341. 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  342. 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  343. 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  344. 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  345. 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  346. };
  347. // For small denominators, it is cheaper to directly store the result.
  348. // For bigger ones, just ONE Newton-Raphson iteration is enough to get
  349. // maximum precision we need
  350. static const uint32_t small_inv_tab[111] PROGMEM = {
  351. 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  352. 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  353. 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  354. 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  355. 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  356. 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  357. 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  358. };
  359. // For small divisors, it is best to directly retrieve the results
  360. if (d <= 110)
  361. return pgm_read_dword(&small_inv_tab[d]);
  362. register uint8_t r8 = d & 0xFF;
  363. register uint8_t r9 = (d >> 8) & 0xFF;
  364. register uint8_t r10 = (d >> 16) & 0xFF;
  365. register uint8_t r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
  366. register const uint8_t* ptab = inv_tab;
  367. __asm__ __volatile__(
  368. // %8:%7:%6 = interval
  369. // r31:r30: MUST be those registers, and they must point to the inv_tab
  370. " clr %13" "\n\t" // %13 = 0
  371. // Now we must compute
  372. // result = 0xFFFFFF / d
  373. // %8:%7:%6 = interval
  374. // %16:%15:%14 = nr
  375. // %13 = 0
  376. // A plain division of 24x24 bits should take 388 cycles to complete. We will
  377. // use Newton-Raphson for the calculation, and will strive to get way less cycles
  378. // for the same result - Using C division, it takes 500cycles to complete .
  379. " clr %3" "\n\t" // idx = 0
  380. " mov %14,%6" "\n\t"
  381. " mov %15,%7" "\n\t"
  382. " mov %16,%8" "\n\t" // nr = interval
  383. " tst %16" "\n\t" // nr & 0xFF0000 == 0 ?
  384. " brne 2f" "\n\t" // No, skip this
  385. " mov %16,%15" "\n\t"
  386. " mov %15,%14" "\n\t" // nr <<= 8, %14 not needed
  387. " subi %3,-8" "\n\t" // idx += 8
  388. " tst %16" "\n\t" // nr & 0xFF0000 == 0 ?
  389. " brne 2f" "\n\t" // No, skip this
  390. " mov %16,%15" "\n\t" // nr <<= 8, %14 not needed
  391. " clr %15" "\n\t" // We clear %14
  392. " subi %3,-8" "\n\t" // idx += 8
  393. // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
  394. "2:" "\n\t"
  395. " cpi %16,0x10" "\n\t" // (nr & 0xf00000) == 0 ?
  396. " brcc 3f" "\n\t" // No, skip this
  397. " swap %15" "\n\t" // Swap nibbles
  398. " swap %16" "\n\t" // Swap nibbles. Low nibble is 0
  399. " mov %14, %15" "\n\t"
  400. " andi %14,0x0f" "\n\t" // Isolate low nibble
  401. " andi %15,0xf0" "\n\t" // Keep proper nibble in %15
  402. " or %16, %14" "\n\t" // %16:%15 <<= 4
  403. " subi %3,-4" "\n\t" // idx += 4
  404. "3:" "\n\t"
  405. " cpi %16,0x40" "\n\t" // (nr & 0xc00000) == 0 ?
  406. " brcc 4f" "\n\t" // No, skip this
  407. " add %15,%15" "\n\t"
  408. " adc %16,%16" "\n\t"
  409. " add %15,%15" "\n\t"
  410. " adc %16,%16" "\n\t" // %16:%15 <<= 2
  411. " subi %3,-2" "\n\t" // idx += 2
  412. "4:" "\n\t"
  413. " cpi %16,0x80" "\n\t" // (nr & 0x800000) == 0 ?
  414. " brcc 5f" "\n\t" // No, skip this
  415. " add %15,%15" "\n\t"
  416. " adc %16,%16" "\n\t" // %16:%15 <<= 1
  417. " inc %3" "\n\t" // idx += 1
  418. // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
  419. // we have at least 9 MSBits available to enter the initial estimation table
  420. "5:" "\n\t"
  421. " add %15,%15" "\n\t"
  422. " adc %16,%16" "\n\t" // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table)
  423. " add r30,%16" "\n\t" // Only use top 8 bits
  424. " adc r31,%13" "\n\t" // r31:r30 = inv_tab + (tidx)
  425. " lpm %14, Z" "\n\t" // %14 = inv_tab[tidx]
  426. " ldi %15, 1" "\n\t" // %15 = 1 %15:%14 = inv_tab[tidx] + 256
  427. // We must scale the approximation to the proper place
  428. " clr %16" "\n\t" // %16 will always be 0 here
  429. " subi %3,8" "\n\t" // idx == 8 ?
  430. " breq 6f" "\n\t" // yes, no need to scale
  431. " brcs 7f" "\n\t" // If C=1, means idx < 8, result was negative!
  432. // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
  433. " sbrs %3,0" "\n\t" // shift by 1bit position?
  434. " rjmp 8f" "\n\t" // No
  435. " add %14,%14" "\n\t"
  436. " adc %15,%15" "\n\t" // %15:16 <<= 1
  437. "8:" "\n\t"
  438. " sbrs %3,1" "\n\t" // shift by 2bit position?
  439. " rjmp 9f" "\n\t" // No
  440. " add %14,%14" "\n\t"
  441. " adc %15,%15" "\n\t"
  442. " add %14,%14" "\n\t"
  443. " adc %15,%15" "\n\t" // %15:16 <<= 1
  444. "9:" "\n\t"
  445. " sbrs %3,2" "\n\t" // shift by 4bits position?
  446. " rjmp 16f" "\n\t" // No
  447. " swap %15" "\n\t" // Swap nibbles. lo nibble of %15 will always be 0
  448. " swap %14" "\n\t" // Swap nibbles
  449. " mov %12,%14" "\n\t"
  450. " andi %12,0x0f" "\n\t" // isolate low nibble
  451. " andi %14,0xf0" "\n\t" // and clear it
  452. " or %15,%12" "\n\t" // %15:%16 <<= 4
  453. "16:" "\n\t"
  454. " sbrs %3,3" "\n\t" // shift by 8bits position?
  455. " rjmp 6f" "\n\t" // No, we are done
  456. " mov %16,%15" "\n\t"
  457. " mov %15,%14" "\n\t"
  458. " clr %14" "\n\t"
  459. " jmp 6f" "\n\t"
  460. // idx < 8, now %3 = idx - 8. Get the count of bits
  461. "7:" "\n\t"
  462. " neg %3" "\n\t" // %3 = -idx = count of bits to move right. idx range:[1...8]
  463. " sbrs %3,0" "\n\t" // shift by 1 bit position ?
  464. " rjmp 10f" "\n\t" // No, skip it
  465. " asr %15" "\n\t" // (bit7 is always 0 here)
  466. " ror %14" "\n\t"
  467. "10:" "\n\t"
  468. " sbrs %3,1" "\n\t" // shift by 2 bit position ?
  469. " rjmp 11f" "\n\t" // No, skip it
  470. " asr %15" "\n\t" // (bit7 is always 0 here)
  471. " ror %14" "\n\t"
  472. " asr %15" "\n\t" // (bit7 is always 0 here)
  473. " ror %14" "\n\t"
  474. "11:" "\n\t"
  475. " sbrs %3,2" "\n\t" // shift by 4 bit position ?
  476. " rjmp 12f" "\n\t" // No, skip it
  477. " swap %15" "\n\t" // Swap nibbles
  478. " andi %14, 0xf0" "\n\t" // Lose the lowest nibble
  479. " swap %14" "\n\t" // Swap nibbles. Upper nibble is 0
  480. " or %14,%15" "\n\t" // Pass nibble from upper byte
  481. " andi %15, 0x0f" "\n\t" // And get rid of that nibble
  482. "12:" "\n\t"
  483. " sbrs %3,3" "\n\t" // shift by 8 bit position ?
  484. " rjmp 6f" "\n\t" // No, skip it
  485. " mov %14,%15" "\n\t"
  486. " clr %15" "\n\t"
  487. "6:" "\n\t" // %16:%15:%14 = initial estimation of 0x1000000 / d
  488. // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
  489. // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
  490. // to get more than 18bits of precision (the initial table lookup gives 9 bits of
  491. // precision to start from). 18bits of precision is all what is needed here for result
  492. // %8:%7:%6 = d = interval
  493. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  494. // %13 = 0
  495. // %3:%2:%1:%0 = working accumulator
  496. // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
  497. " clr %0" "\n\t"
  498. " clr %1" "\n\t"
  499. " clr %2" "\n\t"
  500. " ldi %3,2" "\n\t" // %3:%2:%1:%0 = 0x2000000
  501. " mul %6,%14" "\n\t" // r1:r0 = LO(d) * LO(x)
  502. " sub %0,r0" "\n\t"
  503. " sbc %1,r1" "\n\t"
  504. " sbc %2,%13" "\n\t"
  505. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * LO(x)
  506. " mul %7,%14" "\n\t" // r1:r0 = MI(d) * LO(x)
  507. " sub %1,r0" "\n\t"
  508. " sbc %2,r1" "\n\t"
  509. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  510. " mul %8,%14" "\n\t" // r1:r0 = HI(d) * LO(x)
  511. " sub %2,r0" "\n\t"
  512. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  513. " mul %6,%15" "\n\t" // r1:r0 = LO(d) * MI(x)
  514. " sub %1,r0" "\n\t"
  515. " sbc %2,r1" "\n\t"
  516. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  517. " mul %7,%15" "\n\t" // r1:r0 = MI(d) * MI(x)
  518. " sub %2,r0" "\n\t"
  519. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  520. " mul %8,%15" "\n\t" // r1:r0 = HI(d) * MI(x)
  521. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  522. " mul %6,%16" "\n\t" // r1:r0 = LO(d) * HI(x)
  523. " sub %2,r0" "\n\t"
  524. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  525. " mul %7,%16" "\n\t" // r1:r0 = MI(d) * HI(x)
  526. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  527. // %3:%2:%1:%0 = (1<<25) - x*d [169]
  528. // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
  529. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  530. // %3:%2:%1:%0 = (1<<25) - x*d = acc
  531. // %13 = 0
  532. // result = %11:%10:%9:%5:%4
  533. " mul %14,%0" "\n\t" // r1:r0 = LO(x) * LO(acc)
  534. " mov %4,r1" "\n\t"
  535. " clr %5" "\n\t"
  536. " clr %9" "\n\t"
  537. " clr %10" "\n\t"
  538. " clr %11" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
  539. " mul %15,%0" "\n\t" // r1:r0 = MI(x) * LO(acc)
  540. " add %4,r0" "\n\t"
  541. " adc %5,r1" "\n\t"
  542. " adc %9,%13" "\n\t"
  543. " adc %10,%13" "\n\t"
  544. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
  545. " mul %16,%0" "\n\t" // r1:r0 = HI(x) * LO(acc)
  546. " add %5,r0" "\n\t"
  547. " adc %9,r1" "\n\t"
  548. " adc %10,%13" "\n\t"
  549. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
  550. " mul %14,%1" "\n\t" // r1:r0 = LO(x) * MIL(acc)
  551. " add %4,r0" "\n\t"
  552. " adc %5,r1" "\n\t"
  553. " adc %9,%13" "\n\t"
  554. " adc %10,%13" "\n\t"
  555. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
  556. " mul %15,%1" "\n\t" // r1:r0 = MI(x) * MIL(acc)
  557. " add %5,r0" "\n\t"
  558. " adc %9,r1" "\n\t"
  559. " adc %10,%13" "\n\t"
  560. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8
  561. " mul %16,%1" "\n\t" // r1:r0 = HI(x) * MIL(acc)
  562. " add %9,r0" "\n\t"
  563. " adc %10,r1" "\n\t"
  564. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
  565. " mul %14,%2" "\n\t" // r1:r0 = LO(x) * MIH(acc)
  566. " add %5,r0" "\n\t"
  567. " adc %9,r1" "\n\t"
  568. " adc %10,%13" "\n\t"
  569. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
  570. " mul %15,%2" "\n\t" // r1:r0 = MI(x) * MIH(acc)
  571. " add %9,r0" "\n\t"
  572. " adc %10,r1" "\n\t"
  573. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
  574. " mul %16,%2" "\n\t" // r1:r0 = HI(x) * MIH(acc)
  575. " add %10,r0" "\n\t"
  576. " adc %11,r1" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
  577. " mul %14,%3" "\n\t" // r1:r0 = LO(x) * HI(acc)
  578. " add %9,r0" "\n\t"
  579. " adc %10,r1" "\n\t"
  580. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
  581. " mul %15,%3" "\n\t" // r1:r0 = MI(x) * HI(acc)
  582. " add %10,r0" "\n\t"
  583. " adc %11,r1" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
  584. " mul %16,%3" "\n\t" // r1:r0 = HI(x) * HI(acc)
  585. " add %11,r0" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
  586. // At this point, %11:%10:%9 contains the new estimation of x.
  587. // Finally, we must correct the result. Estimate remainder as
  588. // (1<<24) - x*d
  589. // %11:%10:%9 = x
  590. // %8:%7:%6 = d = interval" "\n\t"
  591. " ldi %3,1" "\n\t"
  592. " clr %2" "\n\t"
  593. " clr %1" "\n\t"
  594. " clr %0" "\n\t" // %3:%2:%1:%0 = 0x1000000
  595. " mul %6,%9" "\n\t" // r1:r0 = LO(d) * LO(x)
  596. " sub %0,r0" "\n\t"
  597. " sbc %1,r1" "\n\t"
  598. " sbc %2,%13" "\n\t"
  599. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * LO(x)
  600. " mul %7,%9" "\n\t" // r1:r0 = MI(d) * LO(x)
  601. " sub %1,r0" "\n\t"
  602. " sbc %2,r1" "\n\t"
  603. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  604. " mul %8,%9" "\n\t" // r1:r0 = HI(d) * LO(x)
  605. " sub %2,r0" "\n\t"
  606. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  607. " mul %6,%10" "\n\t" // r1:r0 = LO(d) * MI(x)
  608. " sub %1,r0" "\n\t"
  609. " sbc %2,r1" "\n\t"
  610. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  611. " mul %7,%10" "\n\t" // r1:r0 = MI(d) * MI(x)
  612. " sub %2,r0" "\n\t"
  613. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  614. " mul %8,%10" "\n\t" // r1:r0 = HI(d) * MI(x)
  615. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  616. " mul %6,%11" "\n\t" // r1:r0 = LO(d) * HI(x)
  617. " sub %2,r0" "\n\t"
  618. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  619. " mul %7,%11" "\n\t" // r1:r0 = MI(d) * HI(x)
  620. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  621. // %3:%2:%1:%0 = r = (1<<24) - x*d
  622. // %8:%7:%6 = d = interval
  623. // Perform the final correction
  624. " sub %0,%6" "\n\t"
  625. " sbc %1,%7" "\n\t"
  626. " sbc %2,%8" "\n\t" // r -= d
  627. " brcs 14f" "\n\t" // if ( r >= d)
  628. // %11:%10:%9 = x
  629. " ldi %3,1" "\n\t"
  630. " add %9,%3" "\n\t"
  631. " adc %10,%13" "\n\t"
  632. " adc %11,%13" "\n\t" // x++
  633. "14:" "\n\t"
  634. // Estimation is done. %11:%10:%9 = x
  635. " clr __zero_reg__" "\n\t" // Make C runtime happy
  636. // [211 cycles total]
  637. : "=r" (r2),
  638. "=r" (r3),
  639. "=r" (r4),
  640. "=d" (r5),
  641. "=r" (r6),
  642. "=r" (r7),
  643. "+r" (r8),
  644. "+r" (r9),
  645. "+r" (r10),
  646. "=d" (r11),
  647. "=r" (r12),
  648. "=r" (r13),
  649. "=d" (r14),
  650. "=d" (r15),
  651. "=d" (r16),
  652. "=d" (r17),
  653. "=d" (r18),
  654. "+z" (ptab)
  655. :
  656. : "r0", "r1", "cc"
  657. );
  658. // Return the result
  659. return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
  660. }
  661. #else
  662. // All the other 32 CPUs can easily perform the inverse using hardware division,
  663. // so we don´t need to reduce precision or to use assembly language at all.
  664. // This routine, for all the other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d
  665. static FORCE_INLINE uint32_t get_period_inverse(uint32_t d) {
  666. return 0xFFFFFFFF / d;
  667. }
  668. #endif
  669. #endif
  670. #define MINIMAL_STEP_RATE 120
  671. /**
  672. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  673. * by the provided factors.
  674. */
  675. void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
  676. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  677. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  678. // Limit minimal step rate (Otherwise the timer will overflow.)
  679. NOLESS(initial_rate, MINIMAL_STEP_RATE);
  680. NOLESS(final_rate, MINIMAL_STEP_RATE);
  681. #if ENABLED(BEZIER_JERK_CONTROL)
  682. uint32_t cruise_rate = initial_rate;
  683. #endif
  684. const int32_t accel = block->acceleration_steps_per_s2;
  685. // Steps required for acceleration, deceleration to/from nominal rate
  686. int32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  687. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel)),
  688. // Steps between acceleration and deceleration, if any
  689. plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  690. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  691. // Then we can't possibly reach the nominal rate, there will be no cruising.
  692. // Use intersection_distance() to calculate accel / braking time in order to
  693. // reach the final_rate exactly at the end of this block.
  694. if (plateau_steps < 0) {
  695. accelerate_steps = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  696. NOLESS(accelerate_steps, 0); // Check limits due to numerical round-off
  697. accelerate_steps = min((uint32_t)accelerate_steps, block->step_event_count);//(We can cast here to unsigned, because the above line ensures that we are above zero)
  698. plateau_steps = 0;
  699. #if ENABLED(BEZIER_JERK_CONTROL)
  700. // We won't reach the cruising rate. Let's calculate the speed we will reach
  701. cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
  702. #endif
  703. }
  704. #if ENABLED(BEZIER_JERK_CONTROL)
  705. else // We have some plateau time, so the cruise rate will be the nominal rate
  706. cruise_rate = block->nominal_rate;
  707. #endif
  708. // block->accelerate_until = accelerate_steps;
  709. // block->decelerate_after = accelerate_steps+plateau_steps;
  710. #if ENABLED(BEZIER_JERK_CONTROL)
  711. // Jerk controlled speed requires to express speed versus time, NOT steps
  712. uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * HAL_STEPPER_TIMER_RATE,
  713. deceleration_time = ((float)(cruise_rate - final_rate) / accel) * HAL_STEPPER_TIMER_RATE;
  714. // And to offload calculations from the ISR, we also calculate the inverse of those times here
  715. uint32_t acceleration_time_inverse = get_period_inverse(acceleration_time);
  716. uint32_t deceleration_time_inverse = get_period_inverse(deceleration_time);
  717. #endif
  718. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  719. if (!TEST(block->flag, BLOCK_BIT_BUSY)) { // Don't update variables if block is busy.
  720. block->accelerate_until = accelerate_steps;
  721. block->decelerate_after = accelerate_steps + plateau_steps;
  722. block->initial_rate = initial_rate;
  723. #if ENABLED(BEZIER_JERK_CONTROL)
  724. block->acceleration_time = acceleration_time;
  725. block->deceleration_time = deceleration_time;
  726. block->acceleration_time_inverse = acceleration_time_inverse;
  727. block->deceleration_time_inverse = deceleration_time_inverse;
  728. block->cruise_rate = cruise_rate;
  729. #endif
  730. block->final_rate = final_rate;
  731. }
  732. CRITICAL_SECTION_END;
  733. }
  734. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  735. // This method will calculate the junction jerk as the euclidean distance between the nominal
  736. // velocities of the respective blocks.
  737. //inline float junction_jerk(block_t *before, block_t *after) {
  738. // return SQRT(
  739. // POW((before->speed_x-after->speed_x), 2)+POW((before->speed_y-after->speed_y), 2));
  740. //}
  741. // The kernel called by recalculate() when scanning the plan from last to first entry.
  742. void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
  743. if (!current || !next) return;
  744. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  745. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  746. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  747. float max_entry_speed = current->max_entry_speed;
  748. if (current->entry_speed != max_entry_speed) {
  749. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  750. // for max allowable speed if block is decelerating and nominal length is false.
  751. current->entry_speed = (TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH) || max_entry_speed <= next->entry_speed)
  752. ? max_entry_speed
  753. : min(max_entry_speed, max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  754. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  755. }
  756. }
  757. /**
  758. * recalculate() needs to go over the current plan twice.
  759. * Once in reverse and once forward. This implements the reverse pass.
  760. */
  761. void Planner::reverse_pass() {
  762. if (movesplanned() > 2) {
  763. const uint8_t endnr = BLOCK_MOD(block_buffer_tail + 1); // tail is running. tail+1 shouldn't be altered because it's connected to the running block.
  764. uint8_t blocknr = prev_block_index(block_buffer_head);
  765. block_t* current = &block_buffer[blocknr];
  766. // Last/newest block in buffer:
  767. const float max_entry_speed = current->max_entry_speed;
  768. if (current->entry_speed != max_entry_speed) {
  769. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  770. // for max allowable speed if block is decelerating and nominal length is false.
  771. current->entry_speed = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
  772. ? max_entry_speed
  773. : min(max_entry_speed, max_allowable_speed(-current->acceleration, MINIMUM_PLANNER_SPEED, current->millimeters));
  774. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  775. }
  776. do {
  777. const block_t * const next = current;
  778. blocknr = prev_block_index(blocknr);
  779. current = &block_buffer[blocknr];
  780. reverse_pass_kernel(current, next);
  781. } while (blocknr != endnr);
  782. }
  783. }
  784. // The kernel called by recalculate() when scanning the plan from first to last entry.
  785. void Planner::forward_pass_kernel(const block_t * const previous, block_t* const current) {
  786. if (!previous) return;
  787. // If the previous block is an acceleration block, but it is not long enough to complete the
  788. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  789. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  790. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  791. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH)) {
  792. if (previous->entry_speed < current->entry_speed) {
  793. float entry_speed = min(current->entry_speed,
  794. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  795. // Check for junction speed change
  796. if (current->entry_speed != entry_speed) {
  797. current->entry_speed = entry_speed;
  798. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  799. }
  800. }
  801. }
  802. }
  803. /**
  804. * recalculate() needs to go over the current plan twice.
  805. * Once in reverse and once forward. This implements the forward pass.
  806. */
  807. void Planner::forward_pass() {
  808. block_t* block[3] = { NULL, NULL, NULL };
  809. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  810. block[0] = block[1];
  811. block[1] = block[2];
  812. block[2] = &block_buffer[b];
  813. forward_pass_kernel(block[0], block[1]);
  814. }
  815. forward_pass_kernel(block[1], block[2]);
  816. }
  817. /**
  818. * Recalculate the trapezoid speed profiles for all blocks in the plan
  819. * according to the entry_factor for each junction. Must be called by
  820. * recalculate() after updating the blocks.
  821. */
  822. void Planner::recalculate_trapezoids() {
  823. int8_t block_index = block_buffer_tail;
  824. block_t *current, *next = NULL;
  825. while (block_index != block_buffer_head) {
  826. current = next;
  827. next = &block_buffer[block_index];
  828. if (current) {
  829. // Recalculate if current block entry or exit junction speed has changed.
  830. if (TEST(current->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  831. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  832. const float nomr = 1.0 / current->nominal_speed;
  833. calculate_trapezoid_for_block(current, current->entry_speed * nomr, next->entry_speed * nomr);
  834. #if ENABLED(LIN_ADVANCE)
  835. if (current->use_advance_lead) {
  836. const float comp = current->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
  837. current->max_adv_steps = current->nominal_speed * comp;
  838. current->final_adv_steps = next->entry_speed * comp;
  839. }
  840. #endif
  841. CBI(current->flag, BLOCK_BIT_RECALCULATE); // Reset current only to ensure next trapezoid is computed
  842. }
  843. }
  844. block_index = next_block_index(block_index);
  845. }
  846. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  847. if (next) {
  848. const float nomr = 1.0 / next->nominal_speed;
  849. calculate_trapezoid_for_block(next, next->entry_speed * nomr, (MINIMUM_PLANNER_SPEED) * nomr);
  850. #if ENABLED(LIN_ADVANCE)
  851. if (next->use_advance_lead) {
  852. const float comp = next->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
  853. next->max_adv_steps = next->nominal_speed * comp;
  854. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  855. }
  856. #endif
  857. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  858. }
  859. }
  860. /**
  861. * Recalculate the motion plan according to the following algorithm:
  862. *
  863. * 1. Go over every block in reverse order...
  864. *
  865. * Calculate a junction speed reduction (block_t.entry_factor) so:
  866. *
  867. * a. The junction jerk is within the set limit, and
  868. *
  869. * b. No speed reduction within one block requires faster
  870. * deceleration than the one, true constant acceleration.
  871. *
  872. * 2. Go over every block in chronological order...
  873. *
  874. * Dial down junction speed reduction values if:
  875. * a. The speed increase within one block would require faster
  876. * acceleration than the one, true constant acceleration.
  877. *
  878. * After that, all blocks will have an entry_factor allowing all speed changes to
  879. * be performed using only the one, true constant acceleration, and where no junction
  880. * jerk is jerkier than the set limit, Jerky. Finally it will:
  881. *
  882. * 3. Recalculate "trapezoids" for all blocks.
  883. */
  884. void Planner::recalculate() {
  885. reverse_pass();
  886. forward_pass();
  887. recalculate_trapezoids();
  888. }
  889. #if ENABLED(AUTOTEMP)
  890. void Planner::getHighESpeed() {
  891. static float oldt = 0;
  892. if (!autotemp_enabled) return;
  893. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  894. float high = 0.0;
  895. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  896. block_t* block = &block_buffer[b];
  897. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  898. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  899. NOLESS(high, se);
  900. }
  901. }
  902. float t = autotemp_min + high * autotemp_factor;
  903. t = constrain(t, autotemp_min, autotemp_max);
  904. if (t < oldt) t = t * (1 - (AUTOTEMP_OLDWEIGHT)) + oldt * (AUTOTEMP_OLDWEIGHT);
  905. oldt = t;
  906. thermalManager.setTargetHotend(t, 0);
  907. }
  908. #endif // AUTOTEMP
  909. /**
  910. * Maintain fans, paste extruder pressure,
  911. */
  912. void Planner::check_axes_activity() {
  913. unsigned char axis_active[NUM_AXIS] = { 0 },
  914. tail_fan_speed[FAN_COUNT];
  915. #if ENABLED(BARICUDA)
  916. #if HAS_HEATER_1
  917. uint8_t tail_valve_pressure;
  918. #endif
  919. #if HAS_HEATER_2
  920. uint8_t tail_e_to_p_pressure;
  921. #endif
  922. #endif
  923. if (has_blocks_queued()) {
  924. #if FAN_COUNT > 0
  925. for (uint8_t i = 0; i < FAN_COUNT; i++)
  926. tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
  927. #endif
  928. block_t* block;
  929. #if ENABLED(BARICUDA)
  930. block = &block_buffer[block_buffer_tail];
  931. #if HAS_HEATER_1
  932. tail_valve_pressure = block->valve_pressure;
  933. #endif
  934. #if HAS_HEATER_2
  935. tail_e_to_p_pressure = block->e_to_p_pressure;
  936. #endif
  937. #endif
  938. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  939. block = &block_buffer[b];
  940. LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
  941. }
  942. }
  943. else {
  944. #if FAN_COUNT > 0
  945. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  946. #endif
  947. #if ENABLED(BARICUDA)
  948. #if HAS_HEATER_1
  949. tail_valve_pressure = baricuda_valve_pressure;
  950. #endif
  951. #if HAS_HEATER_2
  952. tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  953. #endif
  954. #endif
  955. }
  956. #if ENABLED(DISABLE_X)
  957. if (!axis_active[X_AXIS]) disable_X();
  958. #endif
  959. #if ENABLED(DISABLE_Y)
  960. if (!axis_active[Y_AXIS]) disable_Y();
  961. #endif
  962. #if ENABLED(DISABLE_Z)
  963. if (!axis_active[Z_AXIS]) disable_Z();
  964. #endif
  965. #if ENABLED(DISABLE_E)
  966. if (!axis_active[E_AXIS]) disable_e_steppers();
  967. #endif
  968. #if FAN_COUNT > 0
  969. #if FAN_KICKSTART_TIME > 0
  970. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  971. #define KICKSTART_FAN(f) \
  972. if (tail_fan_speed[f]) { \
  973. millis_t ms = millis(); \
  974. if (fan_kick_end[f] == 0) { \
  975. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  976. tail_fan_speed[f] = 255; \
  977. } else if (PENDING(ms, fan_kick_end[f])) \
  978. tail_fan_speed[f] = 255; \
  979. } else fan_kick_end[f] = 0
  980. #if HAS_FAN0
  981. KICKSTART_FAN(0);
  982. #endif
  983. #if HAS_FAN1
  984. KICKSTART_FAN(1);
  985. #endif
  986. #if HAS_FAN2
  987. KICKSTART_FAN(2);
  988. #endif
  989. #endif // FAN_KICKSTART_TIME > 0
  990. #ifdef FAN_MIN_PWM
  991. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  992. #else
  993. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  994. #endif
  995. #if ENABLED(FAN_SOFT_PWM)
  996. #if HAS_FAN0
  997. thermalManager.soft_pwm_amount_fan[0] = CALC_FAN_SPEED(0);
  998. #endif
  999. #if HAS_FAN1
  1000. thermalManager.soft_pwm_amount_fan[1] = CALC_FAN_SPEED(1);
  1001. #endif
  1002. #if HAS_FAN2
  1003. thermalManager.soft_pwm_amount_fan[2] = CALC_FAN_SPEED(2);
  1004. #endif
  1005. #else
  1006. #if HAS_FAN0
  1007. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  1008. #endif
  1009. #if HAS_FAN1
  1010. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  1011. #endif
  1012. #if HAS_FAN2
  1013. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  1014. #endif
  1015. #endif
  1016. #endif // FAN_COUNT > 0
  1017. #if ENABLED(AUTOTEMP)
  1018. getHighESpeed();
  1019. #endif
  1020. #if ENABLED(BARICUDA)
  1021. #if HAS_HEATER_1
  1022. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  1023. #endif
  1024. #if HAS_HEATER_2
  1025. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  1026. #endif
  1027. #endif
  1028. }
  1029. #if DISABLED(NO_VOLUMETRICS)
  1030. /**
  1031. * Get a volumetric multiplier from a filament diameter.
  1032. * This is the reciprocal of the circular cross-section area.
  1033. * Return 1.0 with volumetric off or a diameter of 0.0.
  1034. */
  1035. inline float calculate_volumetric_multiplier(const float &diameter) {
  1036. return (parser.volumetric_enabled && diameter) ? 1.0 / CIRCLE_AREA(diameter * 0.5) : 1.0;
  1037. }
  1038. /**
  1039. * Convert the filament sizes into volumetric multipliers.
  1040. * The multiplier converts a given E value into a length.
  1041. */
  1042. void Planner::calculate_volumetric_multipliers() {
  1043. for (uint8_t i = 0; i < COUNT(filament_size); i++) {
  1044. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  1045. refresh_e_factor(i);
  1046. }
  1047. }
  1048. #endif // !NO_VOLUMETRICS
  1049. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1050. /**
  1051. * Convert the ratio value given by the filament width sensor
  1052. * into a volumetric multiplier. Conversion differs when using
  1053. * linear extrusion vs volumetric extrusion.
  1054. */
  1055. void Planner::calculate_volumetric_for_width_sensor(const int8_t encoded_ratio) {
  1056. // Reconstitute the nominal/measured ratio
  1057. const float nom_meas_ratio = 1.0 + 0.01 * encoded_ratio,
  1058. ratio_2 = sq(nom_meas_ratio);
  1059. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  1060. ? ratio_2 / CIRCLE_AREA(filament_width_nominal * 0.5) // Volumetric uses a true volumetric multiplier
  1061. : ratio_2; // Linear squares the ratio, which scales the volume
  1062. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  1063. }
  1064. #endif
  1065. #if PLANNER_LEVELING
  1066. /**
  1067. * rx, ry, rz - Cartesian positions in mm
  1068. * Leveled XYZ on completion
  1069. */
  1070. void Planner::apply_leveling(float &rx, float &ry, float &rz) {
  1071. #if ENABLED(SKEW_CORRECTION)
  1072. skew(rx, ry, rz);
  1073. #endif
  1074. if (!leveling_active) return;
  1075. #if ABL_PLANAR
  1076. float dx = rx - (X_TILT_FULCRUM),
  1077. dy = ry - (Y_TILT_FULCRUM);
  1078. apply_rotation_xyz(bed_level_matrix, dx, dy, rz);
  1079. rx = dx + X_TILT_FULCRUM;
  1080. ry = dy + Y_TILT_FULCRUM;
  1081. #elif HAS_MESH
  1082. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1083. const float fade_scaling_factor = fade_scaling_factor_for_z(rz);
  1084. #else
  1085. constexpr float fade_scaling_factor = 1.0;
  1086. #endif
  1087. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1088. const float raw[XYZ] = { rx, ry, 0 };
  1089. #endif
  1090. rz += (
  1091. #if ENABLED(MESH_BED_LEVELING)
  1092. mbl.get_z(rx, ry
  1093. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1094. , fade_scaling_factor
  1095. #endif
  1096. )
  1097. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1098. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(rx, ry) : 0.0
  1099. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1100. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1101. #endif
  1102. );
  1103. #endif
  1104. }
  1105. void Planner::unapply_leveling(float raw[XYZ]) {
  1106. if (leveling_active) {
  1107. #if ABL_PLANAR
  1108. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  1109. float dx = raw[X_AXIS] - (X_TILT_FULCRUM),
  1110. dy = raw[Y_AXIS] - (Y_TILT_FULCRUM);
  1111. apply_rotation_xyz(inverse, dx, dy, raw[Z_AXIS]);
  1112. raw[X_AXIS] = dx + X_TILT_FULCRUM;
  1113. raw[Y_AXIS] = dy + Y_TILT_FULCRUM;
  1114. #elif HAS_MESH
  1115. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1116. const float fade_scaling_factor = fade_scaling_factor_for_z(raw[Z_AXIS]);
  1117. #else
  1118. constexpr float fade_scaling_factor = 1.0;
  1119. #endif
  1120. raw[Z_AXIS] -= (
  1121. #if ENABLED(MESH_BED_LEVELING)
  1122. mbl.get_z(raw[X_AXIS], raw[Y_AXIS]
  1123. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1124. , fade_scaling_factor
  1125. #endif
  1126. )
  1127. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1128. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw[X_AXIS], raw[Y_AXIS]) : 0.0
  1129. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1130. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1131. #endif
  1132. );
  1133. #endif
  1134. }
  1135. #if ENABLED(SKEW_CORRECTION)
  1136. unskew(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]);
  1137. #endif
  1138. }
  1139. #endif // PLANNER_LEVELING
  1140. /**
  1141. * Planner::_buffer_steps
  1142. *
  1143. * Add a new linear movement to the buffer (in terms of steps).
  1144. *
  1145. * target - target position in steps units
  1146. * fr_mm_s - (target) speed of the move
  1147. * extruder - target extruder
  1148. */
  1149. void Planner::_buffer_steps(const int32_t (&target)[XYZE]
  1150. #if HAS_POSITION_FLOAT
  1151. , const float (&target_float)[XYZE]
  1152. #endif
  1153. , float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  1154. ) {
  1155. const int32_t da = target[A_AXIS] - position[A_AXIS],
  1156. db = target[B_AXIS] - position[B_AXIS],
  1157. dc = target[C_AXIS] - position[C_AXIS];
  1158. int32_t de = target[E_AXIS] - position[E_AXIS];
  1159. /* <-- add a slash to enable
  1160. SERIAL_ECHOPAIR(" _buffer_steps FR:", fr_mm_s);
  1161. SERIAL_ECHOPAIR(" A:", target[A_AXIS]);
  1162. SERIAL_ECHOPAIR(" (", da);
  1163. SERIAL_ECHOPAIR(" steps) B:", target[B_AXIS]);
  1164. SERIAL_ECHOPAIR(" (", db);
  1165. SERIAL_ECHOPAIR(" steps) C:", target[C_AXIS]);
  1166. SERIAL_ECHOPAIR(" (", dc);
  1167. SERIAL_ECHOPAIR(" steps) E:", target[E_AXIS]);
  1168. SERIAL_ECHOPAIR(" (", de);
  1169. SERIAL_ECHOLNPGM(" steps)");
  1170. //*/
  1171. #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1172. if (de) {
  1173. #if ENABLED(PREVENT_COLD_EXTRUSION)
  1174. if (thermalManager.tooColdToExtrude(extruder)) {
  1175. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1176. #if HAS_POSITION_FLOAT
  1177. position_float[E_AXIS] = target_float[E_AXIS];
  1178. #endif
  1179. de = 0; // no difference
  1180. SERIAL_ECHO_START();
  1181. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  1182. }
  1183. #endif // PREVENT_COLD_EXTRUSION
  1184. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1185. if (labs(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
  1186. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1187. #if HAS_POSITION_FLOAT
  1188. position_float[E_AXIS] = target_float[E_AXIS];
  1189. #endif
  1190. de = 0; // no difference
  1191. SERIAL_ECHO_START();
  1192. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  1193. }
  1194. #endif // PREVENT_LENGTHY_EXTRUDE
  1195. }
  1196. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  1197. // Compute direction bit-mask for this block
  1198. uint8_t dm = 0;
  1199. #if CORE_IS_XY
  1200. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1201. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1202. if (dc < 0) SBI(dm, Z_AXIS);
  1203. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1204. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  1205. #elif CORE_IS_XZ
  1206. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1207. if (db < 0) SBI(dm, Y_AXIS);
  1208. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1209. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  1210. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1211. #elif CORE_IS_YZ
  1212. if (da < 0) SBI(dm, X_AXIS);
  1213. if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  1214. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1215. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  1216. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1217. #else
  1218. if (da < 0) SBI(dm, X_AXIS);
  1219. if (db < 0) SBI(dm, Y_AXIS);
  1220. if (dc < 0) SBI(dm, Z_AXIS);
  1221. #endif
  1222. if (de < 0) SBI(dm, E_AXIS);
  1223. const float esteps_float = de * e_factor[extruder];
  1224. const int32_t esteps = abs(esteps_float) + 0.5;
  1225. // Calculate the buffer head after we push this byte
  1226. const uint8_t next_buffer_head = next_block_index(block_buffer_head);
  1227. // If the buffer is full: good! That means we are well ahead of the robot.
  1228. // Rest here until there is room in the buffer.
  1229. while (block_buffer_tail == next_buffer_head) idle();
  1230. // Prepare to set up new block
  1231. block_t* block = &block_buffer[block_buffer_head];
  1232. // Clear all flags, including the "busy" bit
  1233. block->flag = 0x00;
  1234. // Set direction bits
  1235. block->direction_bits = dm;
  1236. // Number of steps for each axis
  1237. // See http://www.corexy.com/theory.html
  1238. #if CORE_IS_XY
  1239. block->steps[A_AXIS] = labs(da + db);
  1240. block->steps[B_AXIS] = labs(da - db);
  1241. block->steps[Z_AXIS] = labs(dc);
  1242. #elif CORE_IS_XZ
  1243. block->steps[A_AXIS] = labs(da + dc);
  1244. block->steps[Y_AXIS] = labs(db);
  1245. block->steps[C_AXIS] = labs(da - dc);
  1246. #elif CORE_IS_YZ
  1247. block->steps[X_AXIS] = labs(da);
  1248. block->steps[B_AXIS] = labs(db + dc);
  1249. block->steps[C_AXIS] = labs(db - dc);
  1250. #elif IS_SCARA
  1251. block->steps[A_AXIS] = labs(da);
  1252. block->steps[B_AXIS] = labs(db);
  1253. block->steps[Z_AXIS] = labs(dc);
  1254. #else
  1255. // default non-h-bot planning
  1256. block->steps[A_AXIS] = labs(da);
  1257. block->steps[B_AXIS] = labs(db);
  1258. block->steps[C_AXIS] = labs(dc);
  1259. #endif
  1260. block->steps[E_AXIS] = esteps;
  1261. block->step_event_count = MAX4(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], esteps);
  1262. // Bail if this is a zero-length block
  1263. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return;
  1264. // For a mixing extruder, get a magnified step_event_count for each
  1265. #if ENABLED(MIXING_EXTRUDER)
  1266. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  1267. block->mix_event_count[i] = mixing_factor[i] * block->step_event_count;
  1268. #endif
  1269. #if FAN_COUNT > 0
  1270. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  1271. #endif
  1272. #if ENABLED(BARICUDA)
  1273. block->valve_pressure = baricuda_valve_pressure;
  1274. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  1275. #endif
  1276. block->active_extruder = extruder;
  1277. #if ENABLED(AUTO_POWER_CONTROL)
  1278. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS])
  1279. powerManager.power_on();
  1280. #endif
  1281. // Enable active axes
  1282. #if CORE_IS_XY
  1283. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  1284. enable_X();
  1285. enable_Y();
  1286. }
  1287. #if DISABLED(Z_LATE_ENABLE)
  1288. if (block->steps[Z_AXIS]) enable_Z();
  1289. #endif
  1290. #elif CORE_IS_XZ
  1291. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  1292. enable_X();
  1293. enable_Z();
  1294. }
  1295. if (block->steps[Y_AXIS]) enable_Y();
  1296. #elif CORE_IS_YZ
  1297. if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
  1298. enable_Y();
  1299. enable_Z();
  1300. }
  1301. if (block->steps[X_AXIS]) enable_X();
  1302. #else
  1303. if (block->steps[X_AXIS]) enable_X();
  1304. if (block->steps[Y_AXIS]) enable_Y();
  1305. #if DISABLED(Z_LATE_ENABLE)
  1306. if (block->steps[Z_AXIS]) enable_Z();
  1307. #endif
  1308. #endif
  1309. // Enable extruder(s)
  1310. if (esteps) {
  1311. #if ENABLED(AUTO_POWER_CONTROL)
  1312. powerManager.power_on();
  1313. #endif
  1314. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  1315. #define DISABLE_IDLE_E(N) if (!g_uc_extruder_last_move[N]) disable_E##N();
  1316. for (uint8_t i = 0; i < EXTRUDERS; i++)
  1317. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  1318. switch (extruder) {
  1319. case 0:
  1320. #if EXTRUDERS > 1
  1321. DISABLE_IDLE_E(1);
  1322. #if EXTRUDERS > 2
  1323. DISABLE_IDLE_E(2);
  1324. #if EXTRUDERS > 3
  1325. DISABLE_IDLE_E(3);
  1326. #if EXTRUDERS > 4
  1327. DISABLE_IDLE_E(4);
  1328. #endif // EXTRUDERS > 4
  1329. #endif // EXTRUDERS > 3
  1330. #endif // EXTRUDERS > 2
  1331. #endif // EXTRUDERS > 1
  1332. enable_E0();
  1333. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  1334. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1335. if (extruder_duplication_enabled) {
  1336. enable_E1();
  1337. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1338. }
  1339. #endif
  1340. break;
  1341. #if EXTRUDERS > 1
  1342. case 1:
  1343. DISABLE_IDLE_E(0);
  1344. #if EXTRUDERS > 2
  1345. DISABLE_IDLE_E(2);
  1346. #if EXTRUDERS > 3
  1347. DISABLE_IDLE_E(3);
  1348. #if EXTRUDERS > 4
  1349. DISABLE_IDLE_E(4);
  1350. #endif // EXTRUDERS > 4
  1351. #endif // EXTRUDERS > 3
  1352. #endif // EXTRUDERS > 2
  1353. enable_E1();
  1354. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1355. break;
  1356. #if EXTRUDERS > 2
  1357. case 2:
  1358. DISABLE_IDLE_E(0);
  1359. DISABLE_IDLE_E(1);
  1360. #if EXTRUDERS > 3
  1361. DISABLE_IDLE_E(3);
  1362. #if EXTRUDERS > 4
  1363. DISABLE_IDLE_E(4);
  1364. #endif
  1365. #endif
  1366. enable_E2();
  1367. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  1368. break;
  1369. #if EXTRUDERS > 3
  1370. case 3:
  1371. DISABLE_IDLE_E(0);
  1372. DISABLE_IDLE_E(1);
  1373. DISABLE_IDLE_E(2);
  1374. #if EXTRUDERS > 4
  1375. DISABLE_IDLE_E(4);
  1376. #endif
  1377. enable_E3();
  1378. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  1379. break;
  1380. #if EXTRUDERS > 4
  1381. case 4:
  1382. DISABLE_IDLE_E(0);
  1383. DISABLE_IDLE_E(1);
  1384. DISABLE_IDLE_E(2);
  1385. DISABLE_IDLE_E(3);
  1386. enable_E4();
  1387. g_uc_extruder_last_move[4] = (BLOCK_BUFFER_SIZE) * 2;
  1388. break;
  1389. #endif // EXTRUDERS > 4
  1390. #endif // EXTRUDERS > 3
  1391. #endif // EXTRUDERS > 2
  1392. #endif // EXTRUDERS > 1
  1393. }
  1394. #else
  1395. enable_E0();
  1396. enable_E1();
  1397. enable_E2();
  1398. enable_E3();
  1399. enable_E4();
  1400. #endif
  1401. }
  1402. if (esteps)
  1403. NOLESS(fr_mm_s, min_feedrate_mm_s);
  1404. else
  1405. NOLESS(fr_mm_s, min_travel_feedrate_mm_s);
  1406. /**
  1407. * This part of the code calculates the total length of the movement.
  1408. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  1409. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  1410. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  1411. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  1412. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  1413. */
  1414. #if IS_CORE
  1415. float delta_mm[Z_HEAD + 1];
  1416. #if CORE_IS_XY
  1417. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1418. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1419. delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
  1420. delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
  1421. delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  1422. #elif CORE_IS_XZ
  1423. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1424. delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
  1425. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1426. delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
  1427. delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  1428. #elif CORE_IS_YZ
  1429. delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
  1430. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1431. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1432. delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
  1433. delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  1434. #endif
  1435. #else
  1436. float delta_mm[ABCE];
  1437. delta_mm[A_AXIS] = da * steps_to_mm[A_AXIS];
  1438. delta_mm[B_AXIS] = db * steps_to_mm[B_AXIS];
  1439. delta_mm[C_AXIS] = dc * steps_to_mm[C_AXIS];
  1440. #endif
  1441. delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS_N];
  1442. 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) {
  1443. block->millimeters = FABS(delta_mm[E_AXIS]);
  1444. }
  1445. else if (!millimeters) {
  1446. block->millimeters = SQRT(
  1447. #if CORE_IS_XY
  1448. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
  1449. #elif CORE_IS_XZ
  1450. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
  1451. #elif CORE_IS_YZ
  1452. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
  1453. #else
  1454. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
  1455. #endif
  1456. );
  1457. }
  1458. else
  1459. block->millimeters = millimeters;
  1460. const float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  1461. // Calculate inverse time for this move. No divide by zero due to previous checks.
  1462. // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
  1463. float inverse_secs = fr_mm_s * inverse_millimeters;
  1464. const uint8_t moves_queued = movesplanned();
  1465. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  1466. #if ENABLED(SLOWDOWN) || ENABLED(ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
  1467. // Segment time im micro seconds
  1468. uint32_t segment_time_us = LROUND(1000000.0 / inverse_secs);
  1469. #endif
  1470. #if ENABLED(SLOWDOWN)
  1471. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / 2 - 1)) {
  1472. if (segment_time_us < min_segment_time_us) {
  1473. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  1474. const uint32_t nst = segment_time_us + LROUND(2 * (min_segment_time_us - segment_time_us) / moves_queued);
  1475. inverse_secs = 1000000.0 / nst;
  1476. #if defined(XY_FREQUENCY_LIMIT) || ENABLED(ULTRA_LCD)
  1477. segment_time_us = nst;
  1478. #endif
  1479. }
  1480. }
  1481. #endif
  1482. #if ENABLED(ULTRA_LCD)
  1483. CRITICAL_SECTION_START
  1484. block_buffer_runtime_us += segment_time_us;
  1485. CRITICAL_SECTION_END
  1486. #endif
  1487. block->nominal_speed = block->millimeters * inverse_secs; // (mm/sec) Always > 0
  1488. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  1489. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1490. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  1491. //FMM update ring buffer used for delay with filament measurements
  1492. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index[1] >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  1493. constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  1494. // increment counters with next move in e axis
  1495. filwidth_e_count += delta_mm[E_AXIS];
  1496. filwidth_delay_dist += delta_mm[E_AXIS];
  1497. // Only get new measurements on forward E movement
  1498. if (!UNEAR_ZERO(filwidth_e_count)) {
  1499. // Loop the delay distance counter (modulus by the mm length)
  1500. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  1501. // Convert into an index into the measurement array
  1502. filwidth_delay_index[0] = int8_t(filwidth_delay_dist * 0.1);
  1503. // If the index has changed (must have gone forward)...
  1504. if (filwidth_delay_index[0] != filwidth_delay_index[1]) {
  1505. filwidth_e_count = 0; // Reset the E movement counter
  1506. const int8_t meas_sample = thermalManager.widthFil_to_size_ratio();
  1507. do {
  1508. filwidth_delay_index[1] = (filwidth_delay_index[1] + 1) % MMD_CM; // The next unused slot
  1509. measurement_delay[filwidth_delay_index[1]] = meas_sample; // Store the measurement
  1510. } while (filwidth_delay_index[0] != filwidth_delay_index[1]); // More slots to fill?
  1511. }
  1512. }
  1513. }
  1514. #endif
  1515. // Calculate and limit speed in mm/sec for each axis
  1516. float current_speed[NUM_AXIS], speed_factor = 1.0; // factor <1 decreases speed
  1517. LOOP_XYZE(i) {
  1518. const float cs = FABS((current_speed[i] = delta_mm[i] * inverse_secs));
  1519. #if ENABLED(DISTINCT_E_FACTORS)
  1520. if (i == E_AXIS) i += extruder;
  1521. #endif
  1522. if (cs > max_feedrate_mm_s[i]) NOMORE(speed_factor, max_feedrate_mm_s[i] / cs);
  1523. }
  1524. // Max segment time in µs.
  1525. #ifdef XY_FREQUENCY_LIMIT
  1526. // Check and limit the xy direction change frequency
  1527. const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  1528. old_direction_bits = block->direction_bits;
  1529. segment_time_us = LROUND((float)segment_time_us / speed_factor);
  1530. uint32_t xs0 = axis_segment_time_us[X_AXIS][0],
  1531. xs1 = axis_segment_time_us[X_AXIS][1],
  1532. xs2 = axis_segment_time_us[X_AXIS][2],
  1533. ys0 = axis_segment_time_us[Y_AXIS][0],
  1534. ys1 = axis_segment_time_us[Y_AXIS][1],
  1535. ys2 = axis_segment_time_us[Y_AXIS][2];
  1536. if (TEST(direction_change, X_AXIS)) {
  1537. xs2 = axis_segment_time_us[X_AXIS][2] = xs1;
  1538. xs1 = axis_segment_time_us[X_AXIS][1] = xs0;
  1539. xs0 = 0;
  1540. }
  1541. xs0 = axis_segment_time_us[X_AXIS][0] = xs0 + segment_time_us;
  1542. if (TEST(direction_change, Y_AXIS)) {
  1543. ys2 = axis_segment_time_us[Y_AXIS][2] = axis_segment_time_us[Y_AXIS][1];
  1544. ys1 = axis_segment_time_us[Y_AXIS][1] = axis_segment_time_us[Y_AXIS][0];
  1545. ys0 = 0;
  1546. }
  1547. ys0 = axis_segment_time_us[Y_AXIS][0] = ys0 + segment_time_us;
  1548. const uint32_t max_x_segment_time = MAX3(xs0, xs1, xs2),
  1549. max_y_segment_time = MAX3(ys0, ys1, ys2),
  1550. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  1551. if (min_xy_segment_time < MAX_FREQ_TIME_US) {
  1552. const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
  1553. NOMORE(speed_factor, low_sf);
  1554. }
  1555. #endif // XY_FREQUENCY_LIMIT
  1556. // Correct the speed
  1557. if (speed_factor < 1.0) {
  1558. LOOP_XYZE(i) current_speed[i] *= speed_factor;
  1559. block->nominal_speed *= speed_factor;
  1560. block->nominal_rate *= speed_factor;
  1561. }
  1562. // Compute and limit the acceleration rate for the trapezoid generator.
  1563. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  1564. uint32_t accel;
  1565. if (!block->steps[A_AXIS] && !block->steps[B_AXIS] && !block->steps[C_AXIS]) {
  1566. // convert to: acceleration steps/sec^2
  1567. accel = CEIL(retract_acceleration * steps_per_mm);
  1568. #if ENABLED(LIN_ADVANCE)
  1569. block->use_advance_lead = false;
  1570. #endif
  1571. }
  1572. else {
  1573. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  1574. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1575. const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
  1576. if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
  1577. } \
  1578. }while(0)
  1579. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  1580. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1581. const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
  1582. if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
  1583. } \
  1584. }while(0)
  1585. // Start with print or travel acceleration
  1586. accel = CEIL((esteps ? acceleration : travel_acceleration) * steps_per_mm);
  1587. #if ENABLED(LIN_ADVANCE)
  1588. /**
  1589. *
  1590. * Use LIN_ADVANCE for blocks if all these are true:
  1591. *
  1592. * esteps : This is a print move, because we checked for A, B, C steps before.
  1593. *
  1594. * extruder_advance_K : There is an advance factor set.
  1595. *
  1596. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  1597. */
  1598. block->use_advance_lead = esteps
  1599. && extruder_advance_K
  1600. && de > 0;
  1601. if (block->use_advance_lead) {
  1602. block->e_D_ratio = (target_float[E_AXIS] - position_float[E_AXIS]) /
  1603. #if IS_KINEMATIC
  1604. block->millimeters
  1605. #else
  1606. SQRT(sq(target_float[X_AXIS] - position_float[X_AXIS])
  1607. + sq(target_float[Y_AXIS] - position_float[Y_AXIS])
  1608. + sq(target_float[Z_AXIS] - position_float[Z_AXIS]))
  1609. #endif
  1610. ;
  1611. // 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!
  1612. // 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.
  1613. if (block->e_D_ratio > 3.0)
  1614. block->use_advance_lead = false;
  1615. else {
  1616. const uint32_t max_accel_steps_per_s2 = max_jerk[E_AXIS] / (extruder_advance_K * block->e_D_ratio) * steps_per_mm;
  1617. #if ENABLED(LA_DEBUG)
  1618. if (accel > max_accel_steps_per_s2)
  1619. SERIAL_ECHOLNPGM("Acceleration limited.");
  1620. #endif
  1621. NOMORE(accel, max_accel_steps_per_s2);
  1622. }
  1623. }
  1624. #endif
  1625. #if ENABLED(DISTINCT_E_FACTORS)
  1626. #define ACCEL_IDX extruder
  1627. #else
  1628. #define ACCEL_IDX 0
  1629. #endif
  1630. // Limit acceleration per axis
  1631. if (block->step_event_count <= cutoff_long) {
  1632. LIMIT_ACCEL_LONG(A_AXIS, 0);
  1633. LIMIT_ACCEL_LONG(B_AXIS, 0);
  1634. LIMIT_ACCEL_LONG(C_AXIS, 0);
  1635. LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
  1636. }
  1637. else {
  1638. LIMIT_ACCEL_FLOAT(A_AXIS, 0);
  1639. LIMIT_ACCEL_FLOAT(B_AXIS, 0);
  1640. LIMIT_ACCEL_FLOAT(C_AXIS, 0);
  1641. LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
  1642. }
  1643. }
  1644. block->acceleration_steps_per_s2 = accel;
  1645. block->acceleration = accel / steps_per_mm;
  1646. #if DISABLED(BEZIER_JERK_CONTROL)
  1647. block->acceleration_rate = (long)(accel * (4096.0 * 4096.0 / (HAL_STEPPER_TIMER_RATE)));
  1648. #endif
  1649. #if ENABLED(LIN_ADVANCE)
  1650. if (block->use_advance_lead) {
  1651. block->advance_speed = (HAL_STEPPER_TIMER_RATE) / (extruder_advance_K * block->e_D_ratio * block->acceleration * axis_steps_per_mm[E_AXIS_N]);
  1652. #if ENABLED(LA_DEBUG)
  1653. if (extruder_advance_K * block->e_D_ratio * block->acceleration * 2 < block->nominal_speed * block->e_D_ratio)
  1654. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  1655. if (block->advance_speed < 200)
  1656. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  1657. #endif
  1658. }
  1659. #endif
  1660. // Initial limit on the segment entry velocity
  1661. float vmax_junction;
  1662. #if 0 // Use old jerk for now
  1663. float junction_deviation = 0.1;
  1664. // Compute path unit vector
  1665. double unit_vec[XYZ] = {
  1666. delta_mm[A_AXIS] * inverse_millimeters,
  1667. delta_mm[B_AXIS] * inverse_millimeters,
  1668. delta_mm[C_AXIS] * inverse_millimeters
  1669. };
  1670. /*
  1671. Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  1672. Let a circle be tangent to both previous and current path line segments, where the junction
  1673. deviation is defined as the distance from the junction to the closest edge of the circle,
  1674. collinear with the circle center.
  1675. The circular segment joining the two paths represents the path of centripetal acceleration.
  1676. Solve for max velocity based on max acceleration about the radius of the circle, defined
  1677. indirectly by junction deviation.
  1678. This may be also viewed as path width or max_jerk in the previous grbl version. This approach
  1679. does not actually deviate from path, but used as a robust way to compute cornering speeds, as
  1680. it takes into account the nonlinearities of both the junction angle and junction velocity.
  1681. */
  1682. vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  1683. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  1684. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed)) {
  1685. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  1686. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  1687. const float cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  1688. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  1689. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS];
  1690. // Skip and use default max junction speed for 0 degree acute junction.
  1691. if (cos_theta < 0.95) {
  1692. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  1693. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  1694. if (cos_theta > -0.95) {
  1695. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  1696. float sin_theta_d2 = SQRT(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  1697. NOMORE(vmax_junction, SQRT(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  1698. }
  1699. }
  1700. }
  1701. #endif
  1702. /**
  1703. * Adapted from Průša MKS firmware
  1704. * https://github.com/prusa3d/Prusa-Firmware
  1705. *
  1706. * Start with a safe speed (from which the machine may halt to stop immediately).
  1707. */
  1708. // Exit speed limited by a jerk to full halt of a previous last segment
  1709. static float previous_safe_speed;
  1710. float safe_speed = block->nominal_speed;
  1711. uint8_t limited = 0;
  1712. LOOP_XYZE(i) {
  1713. const float jerk = FABS(current_speed[i]), maxj = max_jerk[i];
  1714. if (jerk > maxj) {
  1715. if (limited) {
  1716. const float mjerk = maxj * block->nominal_speed;
  1717. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk;
  1718. }
  1719. else {
  1720. ++limited;
  1721. safe_speed = maxj;
  1722. }
  1723. }
  1724. }
  1725. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed)) {
  1726. // Estimate a maximum velocity allowed at a joint of two successive segments.
  1727. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  1728. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  1729. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  1730. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  1731. vmax_junction = min(block->nominal_speed, previous_nominal_speed);
  1732. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  1733. float v_factor = 1;
  1734. limited = 0;
  1735. // Now limit the jerk in all axes.
  1736. const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
  1737. LOOP_XYZE(axis) {
  1738. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  1739. float v_exit = previous_speed[axis] * smaller_speed_factor,
  1740. v_entry = current_speed[axis];
  1741. if (limited) {
  1742. v_exit *= v_factor;
  1743. v_entry *= v_factor;
  1744. }
  1745. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  1746. const float jerk = (v_exit > v_entry)
  1747. ? // coasting axis reversal
  1748. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : max(v_exit, -v_entry) )
  1749. : // v_exit <= v_entry coasting axis reversal
  1750. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : max(-v_exit, v_entry) );
  1751. if (jerk > max_jerk[axis]) {
  1752. v_factor *= max_jerk[axis] / jerk;
  1753. ++limited;
  1754. }
  1755. }
  1756. if (limited) vmax_junction *= v_factor;
  1757. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  1758. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  1759. const float vmax_junction_threshold = vmax_junction * 0.99f;
  1760. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  1761. vmax_junction = safe_speed;
  1762. }
  1763. else
  1764. vmax_junction = safe_speed;
  1765. // Max entry speed of this block equals the max exit speed of the previous block.
  1766. block->max_entry_speed = vmax_junction;
  1767. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  1768. const float v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  1769. // If stepper ISR is disabled, this indicates buffer_segment wants to add a split block.
  1770. // In this case start with the max. allowed speed to avoid an interrupted first move.
  1771. block->entry_speed = STEPPER_ISR_ENABLED() ? MINIMUM_PLANNER_SPEED : min(vmax_junction, v_allowable);
  1772. // Initialize planner efficiency flags
  1773. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  1774. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  1775. // the current block and next block junction speeds are guaranteed to always be at their maximum
  1776. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  1777. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  1778. // the reverse and forward planners, the corresponding block junction speed will always be at the
  1779. // the maximum junction speed and may always be ignored for any speed reduction checks.
  1780. block->flag |= block->nominal_speed <= v_allowable ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
  1781. // Update previous path unit_vector and nominal speed
  1782. COPY(previous_speed, current_speed);
  1783. previous_nominal_speed = block->nominal_speed;
  1784. previous_safe_speed = safe_speed;
  1785. // Move buffer head
  1786. block_buffer_head = next_buffer_head;
  1787. // Update the position (only when a move was queued)
  1788. static_assert(COUNT(target) > 1, "Parameter to _buffer_steps must be (&target)[XYZE]!");
  1789. COPY(position, target);
  1790. #if HAS_POSITION_FLOAT
  1791. COPY(position_float, target_float);
  1792. #endif
  1793. recalculate();
  1794. } // _buffer_steps()
  1795. /**
  1796. * Planner::buffer_segment
  1797. *
  1798. * Add a new linear movement to the buffer in axis units.
  1799. *
  1800. * Leveling and kinematics should be applied ahead of calling this.
  1801. *
  1802. * a,b,c,e - target positions in mm and/or degrees
  1803. * fr_mm_s - (target) speed of the move
  1804. * extruder - target extruder
  1805. * millimeters - the length of the movement, if known
  1806. */
  1807. void Planner::buffer_segment(const float &a, const float &b, const float &c, const float &e, const float &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/) {
  1808. // When changing extruders recalculate steps corresponding to the E position
  1809. #if ENABLED(DISTINCT_E_FACTORS)
  1810. if (last_extruder != extruder && axis_steps_per_mm[E_AXIS_N] != axis_steps_per_mm[E_AXIS + last_extruder]) {
  1811. position[E_AXIS] = LROUND(position[E_AXIS] * axis_steps_per_mm[E_AXIS_N] * steps_to_mm[E_AXIS + last_extruder]);
  1812. last_extruder = extruder;
  1813. }
  1814. #endif
  1815. // The target position of the tool in absolute steps
  1816. // Calculate target position in absolute steps
  1817. const int32_t target[ABCE] = {
  1818. LROUND(a * axis_steps_per_mm[A_AXIS]),
  1819. LROUND(b * axis_steps_per_mm[B_AXIS]),
  1820. LROUND(c * axis_steps_per_mm[C_AXIS]),
  1821. LROUND(e * axis_steps_per_mm[E_AXIS_N])
  1822. };
  1823. #if HAS_POSITION_FLOAT
  1824. const float target_float[XYZE] = { a, b, c, e };
  1825. #endif
  1826. // DRYRUN prevents E moves from taking place
  1827. if (DEBUGGING(DRYRUN)) {
  1828. position[E_AXIS] = target[E_AXIS];
  1829. #if HAS_POSITION_FLOAT
  1830. position_float[E_AXIS] = e;
  1831. #endif
  1832. }
  1833. /* <-- add a slash to enable
  1834. SERIAL_ECHOPAIR(" buffer_segment FR:", fr_mm_s);
  1835. #if IS_KINEMATIC
  1836. SERIAL_ECHOPAIR(" A:", a);
  1837. SERIAL_ECHOPAIR(" (", position[A_AXIS]);
  1838. SERIAL_ECHOPAIR("->", target[A_AXIS]);
  1839. SERIAL_ECHOPAIR(") B:", b);
  1840. #else
  1841. SERIAL_ECHOPAIR(" X:", a);
  1842. SERIAL_ECHOPAIR(" (", position[X_AXIS]);
  1843. SERIAL_ECHOPAIR("->", target[X_AXIS]);
  1844. SERIAL_ECHOPAIR(") Y:", b);
  1845. #endif
  1846. SERIAL_ECHOPAIR(" (", position[Y_AXIS]);
  1847. SERIAL_ECHOPAIR("->", target[Y_AXIS]);
  1848. #if ENABLED(DELTA)
  1849. SERIAL_ECHOPAIR(") C:", c);
  1850. #else
  1851. SERIAL_ECHOPAIR(") Z:", c);
  1852. #endif
  1853. SERIAL_ECHOPAIR(" (", position[Z_AXIS]);
  1854. SERIAL_ECHOPAIR("->", target[Z_AXIS]);
  1855. SERIAL_ECHOPAIR(") E:", e);
  1856. SERIAL_ECHOPAIR(" (", position[E_AXIS]);
  1857. SERIAL_ECHOPAIR("->", target[E_AXIS]);
  1858. SERIAL_ECHOLNPGM(")");
  1859. //*/
  1860. // Always split the first move into two (if not homing or probing)
  1861. if (!has_blocks_queued()) {
  1862. #define _BETWEEN(A) (position[A##_AXIS] + target[A##_AXIS]) >> 1
  1863. const int32_t between[ABCE] = { _BETWEEN(A), _BETWEEN(B), _BETWEEN(C), _BETWEEN(E) };
  1864. #if HAS_POSITION_FLOAT
  1865. #define _BETWEEN_F(A) (position_float[A##_AXIS] + target_float[A##_AXIS]) * 0.5
  1866. const float between_float[ABCE] = { _BETWEEN_F(A), _BETWEEN_F(B), _BETWEEN_F(C), _BETWEEN_F(E) };
  1867. #endif
  1868. DISABLE_STEPPER_DRIVER_INTERRUPT();
  1869. _buffer_steps(between
  1870. #if HAS_POSITION_FLOAT
  1871. , between_float
  1872. #endif
  1873. , fr_mm_s, extruder, millimeters * 0.5
  1874. );
  1875. const uint8_t next = block_buffer_head;
  1876. _buffer_steps(target
  1877. #if HAS_POSITION_FLOAT
  1878. , target_float
  1879. #endif
  1880. , fr_mm_s, extruder, millimeters * 0.5
  1881. );
  1882. SBI(block_buffer[next].flag, BLOCK_BIT_CONTINUED);
  1883. ENABLE_STEPPER_DRIVER_INTERRUPT();
  1884. }
  1885. else
  1886. _buffer_steps(target
  1887. #if HAS_POSITION_FLOAT
  1888. , target_float
  1889. #endif
  1890. , fr_mm_s, extruder, millimeters
  1891. );
  1892. stepper.wake_up();
  1893. } // buffer_segment()
  1894. /**
  1895. * Directly set the planner XYZ position (and stepper positions)
  1896. * converting mm (or angles for SCARA) into steps.
  1897. *
  1898. * On CORE machines stepper ABC will be translated from the given XYZ.
  1899. */
  1900. void Planner::_set_position_mm(const float &a, const float &b, const float &c, const float &e) {
  1901. #if ENABLED(DISTINCT_E_FACTORS)
  1902. #define _EINDEX (E_AXIS + active_extruder)
  1903. last_extruder = active_extruder;
  1904. #else
  1905. #define _EINDEX E_AXIS
  1906. #endif
  1907. const int32_t na = position[A_AXIS] = LROUND(a * axis_steps_per_mm[A_AXIS]),
  1908. nb = position[B_AXIS] = LROUND(b * axis_steps_per_mm[B_AXIS]),
  1909. nc = position[C_AXIS] = LROUND(c * axis_steps_per_mm[C_AXIS]),
  1910. ne = position[E_AXIS] = LROUND(e * axis_steps_per_mm[_EINDEX]);
  1911. #if HAS_POSITION_FLOAT
  1912. position_float[X_AXIS] = a;
  1913. position_float[Y_AXIS] = b;
  1914. position_float[Z_AXIS] = c;
  1915. position_float[E_AXIS] = e;
  1916. #endif
  1917. stepper.set_position(na, nb, nc, ne);
  1918. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  1919. ZERO(previous_speed);
  1920. }
  1921. void Planner::set_position_mm_kinematic(const float (&cart)[XYZE]) {
  1922. #if PLANNER_LEVELING
  1923. float raw[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
  1924. apply_leveling(raw);
  1925. #else
  1926. const float (&raw)[XYZE] = cart;
  1927. #endif
  1928. #if IS_KINEMATIC
  1929. inverse_kinematics(raw);
  1930. _set_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_AXIS]);
  1931. #else
  1932. _set_position_mm(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], cart[E_AXIS]);
  1933. #endif
  1934. }
  1935. /**
  1936. * Sync from the stepper positions. (e.g., after an interrupted move)
  1937. */
  1938. void Planner::sync_from_steppers() {
  1939. LOOP_XYZE(i) {
  1940. position[i] = stepper.position((AxisEnum)i);
  1941. #if HAS_POSITION_FLOAT
  1942. position_float[i] = position[i] * steps_to_mm[i
  1943. #if ENABLED(DISTINCT_E_FACTORS)
  1944. + (i == E_AXIS ? active_extruder : 0)
  1945. #endif
  1946. ];
  1947. #endif
  1948. }
  1949. }
  1950. /**
  1951. * Setters for planner position (also setting stepper position).
  1952. */
  1953. void Planner::set_position_mm(const AxisEnum axis, const float &v) {
  1954. #if ENABLED(DISTINCT_E_FACTORS)
  1955. const uint8_t axis_index = axis + (axis == E_AXIS ? active_extruder : 0);
  1956. last_extruder = active_extruder;
  1957. #else
  1958. const uint8_t axis_index = axis;
  1959. #endif
  1960. position[axis] = LROUND(v * axis_steps_per_mm[axis_index]);
  1961. #if HAS_POSITION_FLOAT
  1962. position_float[axis] = v;
  1963. #endif
  1964. stepper.set_position(axis, v);
  1965. previous_speed[axis] = 0.0;
  1966. }
  1967. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  1968. void Planner::reset_acceleration_rates() {
  1969. #if ENABLED(DISTINCT_E_FACTORS)
  1970. #define HIGHEST_CONDITION (i < E_AXIS || i == E_AXIS + active_extruder)
  1971. #else
  1972. #define HIGHEST_CONDITION true
  1973. #endif
  1974. uint32_t highest_rate = 1;
  1975. LOOP_XYZE_N(i) {
  1976. max_acceleration_steps_per_s2[i] = max_acceleration_mm_per_s2[i] * axis_steps_per_mm[i];
  1977. if (HIGHEST_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  1978. }
  1979. cutoff_long = 4294967295UL / highest_rate;
  1980. }
  1981. // Recalculate position, steps_to_mm if axis_steps_per_mm changes!
  1982. void Planner::refresh_positioning() {
  1983. LOOP_XYZE_N(i) steps_to_mm[i] = 1.0 / axis_steps_per_mm[i];
  1984. set_position_mm_kinematic(current_position);
  1985. reset_acceleration_rates();
  1986. }
  1987. #if ENABLED(AUTOTEMP)
  1988. void Planner::autotemp_M104_M109() {
  1989. if ((autotemp_enabled = parser.seen('F'))) autotemp_factor = parser.value_float();
  1990. if (parser.seen('S')) autotemp_min = parser.value_celsius();
  1991. if (parser.seen('B')) autotemp_max = parser.value_celsius();
  1992. }
  1993. #endif