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.

ubl_G29.cpp 70KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. #include "../../../inc/MarlinConfig.h"
  23. #if ENABLED(AUTO_BED_LEVELING_UBL)
  24. #include "../bedlevel.h"
  25. #include "../../../MarlinCore.h"
  26. #include "../../../HAL/shared/persistent_store_api.h"
  27. #include "../../../libs/hex_print_routines.h"
  28. #include "../../../module/configuration_store.h"
  29. #include "../../../lcd/ultralcd.h"
  30. #include "../../../module/stepper.h"
  31. #include "../../../module/planner.h"
  32. #include "../../../module/motion.h"
  33. #include "../../../module/probe.h"
  34. #include "../../../gcode/gcode.h"
  35. #include "../../../libs/least_squares_fit.h"
  36. #if HOTENDS > 1
  37. #include "../../../module/tool_change.h"
  38. #endif
  39. #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE)
  40. #include "../../../core/debug_out.h"
  41. #if ENABLED(EXTENSIBLE_UI)
  42. #include "../../../lcd/extui/ui_api.h"
  43. #endif
  44. #include <math.h>
  45. #define UBL_G29_P31
  46. #if HAS_LCD_MENU
  47. void _lcd_ubl_output_map_lcd();
  48. #endif
  49. #define SIZE_OF_LITTLE_RAISE 1
  50. #define BIG_RAISE_NOT_NEEDED 0
  51. int unified_bed_leveling::g29_verbose_level,
  52. unified_bed_leveling::g29_phase_value,
  53. unified_bed_leveling::g29_repetition_cnt,
  54. unified_bed_leveling::g29_storage_slot = 0,
  55. unified_bed_leveling::g29_map_type;
  56. bool unified_bed_leveling::g29_c_flag;
  57. float unified_bed_leveling::g29_card_thickness = 0,
  58. unified_bed_leveling::g29_constant = 0;
  59. xy_bool_t unified_bed_leveling::xy_seen;
  60. xy_pos_t unified_bed_leveling::g29_pos;
  61. #if HAS_BED_PROBE
  62. int unified_bed_leveling::g29_grid_size;
  63. #endif
  64. /**
  65. * G29: Unified Bed Leveling by Roxy
  66. *
  67. * Parameters understood by this leveling system:
  68. *
  69. * A Activate Activate the Unified Bed Leveling system.
  70. *
  71. * B # Business Use the 'Business Card' mode of the Manual Probe subsystem with P2.
  72. * Note: A non-compressible Spark Gap feeler gauge is recommended over a business card.
  73. * In this mode of G29 P2, a business or index card is used as a shim that the nozzle can
  74. * grab onto as it is lowered. In principle, the nozzle-bed distance is the same when the
  75. * same resistance is felt in the shim. You can omit the numerical value on first invocation
  76. * of G29 P2 B to measure shim thickness. Subsequent use of 'B' will apply the previously-
  77. * measured thickness by default.
  78. *
  79. * C Continue G29 P1 C continues the generation of a partially-constructed Mesh without invalidating
  80. * previous measurements.
  81. *
  82. * C G29 P2 C tells the Manual Probe subsystem to not use the current nozzle
  83. * location in its search for the closest unmeasured Mesh Point. Instead, attempt to
  84. * start at one end of the uprobed points and Continue sequentially.
  85. *
  86. * G29 P3 C specifies the Constant for the fill. Otherwise, uses a "reasonable" value.
  87. *
  88. * C Current G29 Z C uses the Current location (instead of bed center or nearest edge).
  89. *
  90. * D Disable Disable the Unified Bed Leveling system.
  91. *
  92. * E Stow_probe Stow the probe after each sampled point.
  93. *
  94. * F # Fade Fade the amount of Mesh Based Compensation over a specified height. At the
  95. * specified height, no correction is applied and natural printer kenimatics take over. If no
  96. * number is specified for the command, 10mm is assumed to be reasonable.
  97. *
  98. * H # Height With P2, 'H' specifies the Height to raise the nozzle after each manual probe of the bed.
  99. * If omitted, the nozzle will raise by Z_CLEARANCE_BETWEEN_PROBES.
  100. *
  101. * H # Offset With P4, 'H' specifies the Offset above the mesh height to place the nozzle.
  102. * If omitted, Z_CLEARANCE_BETWEEN_PROBES will be used.
  103. *
  104. * I # Invalidate Invalidate the specified number of Mesh Points near the given 'X' 'Y'. If X or Y are omitted,
  105. * the nozzle location is used. If no 'I' value is given, only the point nearest to the location
  106. * is invalidated. Use 'T' to produce a map afterward. This command is useful to invalidate a
  107. * portion of the Mesh so it can be adjusted using other UBL tools. When attempting to invalidate
  108. * an isolated bad mesh point, the 'T' option shows the nozzle position in the Mesh with (#). You
  109. * can move the nozzle around and use this feature to select the center of the area (or cell) to
  110. * invalidate.
  111. *
  112. * J # Grid Perform a Grid Based Leveling of the current Mesh using a grid with n points on a side.
  113. * Not specifying a grid size will invoke the 3-Point leveling function.
  114. *
  115. * L Load Load Mesh from the previously activated location in the EEPROM.
  116. *
  117. * L # Load Load Mesh from the specified location in the EEPROM. Set this location as activated
  118. * for subsequent Load and Store operations.
  119. *
  120. * The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will
  121. * start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with
  122. * each additional Phase that processes it.
  123. *
  124. * P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the
  125. * 3D Printer to the same state it was in before the Unified Bed Leveling Compensation
  126. * was turned on. Setting the entire Mesh to Zero is a special case that allows
  127. * a subsequent G or T leveling operation for backward compatibility.
  128. *
  129. * P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using
  130. * the Z-Probe. Usually the probe can't reach all areas that the nozzle can reach. For delta
  131. * printers only the areas where the probe and nozzle can both reach will be automatically probed.
  132. *
  133. * Unreachable points will be handled in Phase 2 and Phase 3.
  134. *
  135. * Use 'C' to leave the previous mesh intact and automatically probe needed points. This allows you
  136. * to invalidate parts of the Mesh but still use Automatic Probing.
  137. *
  138. * The 'X' and 'Y' parameters prioritize where to try and measure points. If omitted, the current
  139. * probe position is used.
  140. *
  141. * Use 'T' (Topology) to generate a report of mesh generation.
  142. *
  143. * P1 will suspend Mesh generation if the controller button is held down. Note that you may need
  144. * to press and hold the switch for several seconds if moves are underway.
  145. *
  146. * P2 Phase 2 Probe unreachable points.
  147. *
  148. * Use 'H' to set the height between Mesh points. If omitted, Z_CLEARANCE_BETWEEN_PROBES is used.
  149. * Smaller values will be quicker. Move the nozzle down till it barely touches the bed. Make sure the
  150. * nozzle is clean and unobstructed. Use caution and move slowly. This can damage your printer!
  151. * (Uses SIZE_OF_LITTLE_RAISE mm if the nozzle is moving less than BIG_RAISE_NOT_NEEDED mm.)
  152. *
  153. * The 'H' value can be negative if the Mesh dips in a large area. Press and hold the
  154. * controller button to terminate the current Phase 2 command. You can then re-issue "G29 P 2"
  155. * with an 'H' parameter more suitable for the area you're manually probing. Note that the command
  156. * tries to start in a corner of the bed where movement will be predictable. Override the distance
  157. * calculation location with the X and Y parameters. You can print a Mesh Map (G29 T) to see where
  158. * the mesh is invalidated and where the nozzle needs to move to complete the command. Use 'C' to
  159. * indicate that the search should be based on the current position.
  160. *
  161. * The 'B' parameter for this command is described above. It places the manual probe subsystem into
  162. * Business Card mode where the thickness of a business card is measured and then used to accurately
  163. * set the nozzle height in all manual probing for the duration of the command. A Business card can
  164. * be used, but you'll get better results with a flexible Shim that doesn't compress. This makes it
  165. * easier to produce similar amounts of force and get more accurate measurements. Google if you're
  166. * not sure how to use a shim.
  167. *
  168. * The 'T' (Map) parameter helps track Mesh building progress.
  169. *
  170. * NOTE: P2 requires an LCD controller!
  171. *
  172. * P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. There are two different paths to
  173. * go down:
  174. *
  175. * - If a 'C' constant is specified, the closest invalid mesh points to the nozzle will be filled,
  176. * and a repeat count can then also be specified with 'R'.
  177. *
  178. * - Leaving out 'C' invokes Smart Fill, which scans the mesh from the edges inward looking for
  179. * invalid mesh points. Adjacent points are used to determine the bed slope. If the bed is sloped
  180. * upward from the invalid point, it takes the value of the nearest point. If sloped downward, it's
  181. * replaced by a value that puts all three points in a line. This version of G29 P3 is a quick, easy
  182. * and (usually) safe way to populate unprobed mesh regions before continuing to G26 Mesh Validation
  183. * Pattern. Note that this populates the mesh with unverified values. Pay attention and use caution.
  184. *
  185. * P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assumes the existence of
  186. * an LCD Panel. It is possible to fine tune the mesh without an LCD Panel using
  187. * G42 and M421. See the UBL documentation for further details.
  188. *
  189. * Phase 4 is meant to be used with G26 Mesh Validation to fine tune the mesh by direct editing
  190. * of Mesh Points. Raise and lower points to fine tune the mesh until it gives consistently reliable
  191. * adhesion.
  192. *
  193. * P4 moves to the closest Mesh Point (and/or the given X Y), raises the nozzle above the mesh height
  194. * by the given 'H' offset (or default 0), and waits while the controller is used to adjust the nozzle
  195. * height. On click the displayed height is saved in the mesh.
  196. *
  197. * Start Phase 4 at a specific location with X and Y. Adjust a specific number of Mesh Points with
  198. * the 'R' (Repeat) parameter. (If 'R' is left out, the whole matrix is assumed.) This command can be
  199. * terminated early (e.g., after editing the area of interest) by pressing and holding the encoder button.
  200. *
  201. * The general form is G29 P4 [R points] [X position] [Y position]
  202. *
  203. * The H [offset] parameter is useful if a shim is used to fine-tune the mesh. For a 0.4mm shim the
  204. * command would be G29 P4 H0.4. The nozzle is moved to the shim height, you adjust height to the shim,
  205. * and on click the height minus the shim thickness will be saved in the mesh.
  206. *
  207. * !!Use with caution, as a very poor mesh could cause the nozzle to crash into the bed!!
  208. *
  209. * NOTE: P4 is not available unless you have LCD support enabled!
  210. *
  211. * P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and
  212. * work with the Mesh if it is Mean Adjusted. You can specify a C parameter to
  213. * Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically
  214. * execute a G29 P6 C <mean height>.
  215. *
  216. * P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified
  217. * with the C parameter. Being able to adjust the height of a Mesh is useful tool. It
  218. * can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally,
  219. * you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring
  220. * 0.000 at the Z Home location.
  221. *
  222. * Q Test Load specified Test Pattern to assist in checking correct operation of system. This
  223. * command is not anticipated to be of much value to the typical user. It is intended
  224. * for developers to help them verify correct operation of the Unified Bed Leveling System.
  225. *
  226. * R # Repeat Repeat this command the specified number of times. If no number is specified the
  227. * command will be repeated GRID_MAX_POINTS_X * GRID_MAX_POINTS_Y times.
  228. *
  229. * S Store Store the current Mesh in the Activated area of the EEPROM. It will also store the
  230. * current state of the Unified Bed Leveling system in the EEPROM.
  231. *
  232. * S # Store Store the current Mesh at the specified location in EEPROM. Activate this location
  233. * for subsequent Load and Store operations. Valid storage slot numbers begin at 0 and
  234. * extend to a limit related to the available EEPROM storage.
  235. *
  236. * S -1 Store Print the current Mesh as G-code that can be used to restore the mesh anytime.
  237. *
  238. * T Topology Display the Mesh Map Topology.
  239. * 'T' can be used alone (e.g., G29 T) or in combination with most of the other commands.
  240. * This option works with all Phase commands (e.g., G29 P4 R 5 T X 50 Y100 C -.1 O)
  241. * This parameter can also specify a Map Type. T0 (the default) is user-readable. T1
  242. * is suitable to paste into a spreadsheet for a 3D graph of the mesh.
  243. *
  244. * U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds.
  245. * Only used for G29 P1 T U. This speeds up the probing of the edge of the bed. Useful
  246. * when the entire bed doesn't need to be probed because it will be adjusted.
  247. *
  248. * V # Verbosity Set the verbosity level (0-4) for extra details. (Default 0)
  249. *
  250. * X # X Location for this command
  251. *
  252. * Y # Y Location for this command
  253. *
  254. * With UBL_DEVEL_DEBUGGING:
  255. *
  256. * K # Kompare Kompare current Mesh with stored Mesh #, replacing current Mesh with the result.
  257. * This command literally performs a diff between two Meshes.
  258. *
  259. * Q-1 Dump EEPROM Dump the UBL contents stored in EEPROM as HEX format. Useful for developers to help
  260. * verify correct operation of the UBL.
  261. *
  262. * W What? Display valuable UBL data.
  263. *
  264. *
  265. * Release Notes:
  266. * You MUST do M502, M500 to initialize the storage. Failure to do this will cause all
  267. * kinds of problems. Enabling EEPROM Storage is required.
  268. *
  269. * When you do a G28 and G29 P1 to automatically build your first mesh, you are going to notice that
  270. * UBL probes points increasingly further from the starting location. (The starting location defaults
  271. * to the center of the bed.) In contrast, ABL and MBL follow a zigzag pattern. The spiral pattern is
  272. * especially better for Delta printers, since it populates the center of the mesh first, allowing for
  273. * a quicker test print to verify settings. You don't need to populate the entire mesh to use it.
  274. * After all, you don't want to spend a lot of time generating a mesh only to realize the resolution
  275. * or probe offsets are incorrect. Mesh-generation gathers points starting closest to the nozzle unless
  276. * an (X,Y) coordinate pair is given.
  277. *
  278. * Unified Bed Leveling uses a lot of EEPROM storage to hold its data, and it takes some effort to get
  279. * the mesh just right. To prevent this valuable data from being destroyed as the EEPROM structure
  280. * evolves, UBL stores all mesh data at the end of EEPROM.
  281. *
  282. * UBL is founded on Edward Patel's Mesh Bed Leveling code. A big 'Thanks!' to him and the creators of
  283. * 3-Point and Grid Based leveling. Combining their contributions we now have the functionality and
  284. * features of all three systems combined.
  285. */
  286. void unified_bed_leveling::G29() {
  287. bool probe_deployed = false;
  288. if (g29_parameter_parsing()) return; // Abort on parameter error
  289. const int8_t p_val = parser.intval('P', -1);
  290. const bool may_move = p_val == 1 || p_val == 2 || p_val == 4 || parser.seen('J');
  291. #if HOTENDS > 1
  292. const uint8_t old_tool_index = active_extruder;
  293. #endif
  294. // Check for commands that require the printer to be homed
  295. if (may_move) {
  296. planner.synchronize();
  297. if (axes_need_homing()) gcode.home_all_axes();
  298. #if HOTENDS > 1
  299. if (active_extruder != 0) tool_change(0);
  300. #endif
  301. }
  302. // Invalidate Mesh Points. This command is a little bit asymmetrical because
  303. // it directly specifies the repetition count and does not use the 'R' parameter.
  304. if (parser.seen('I')) {
  305. uint8_t cnt = 0;
  306. g29_repetition_cnt = parser.has_value() ? parser.value_int() : 1;
  307. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  308. set_all_mesh_points_to_value(NAN);
  309. }
  310. else {
  311. while (g29_repetition_cnt--) {
  312. if (cnt > 20) { cnt = 0; idle(); }
  313. const mesh_index_pair closest = find_closest_mesh_point_of_type(REAL, g29_pos);
  314. const xy_int8_t &cpos = closest.pos;
  315. if (cpos.x < 0) {
  316. // No more REAL mesh points to invalidate, so we ASSUME the user
  317. // meant to invalidate the ENTIRE mesh, which cannot be done with
  318. // find_closest_mesh_point loop which only returns REAL points.
  319. set_all_mesh_points_to_value(NAN);
  320. SERIAL_ECHOLNPGM("Entire Mesh invalidated.\n");
  321. break; // No more invalid Mesh Points to populate
  322. }
  323. z_values[cpos.x][cpos.y] = NAN;
  324. #if ENABLED(EXTENSIBLE_UI)
  325. ExtUI::onMeshUpdate(cpos, 0.0f);
  326. #endif
  327. cnt++;
  328. }
  329. }
  330. SERIAL_ECHOLNPGM("Locations invalidated.\n");
  331. }
  332. if (parser.seen('Q')) {
  333. const int test_pattern = parser.has_value() ? parser.value_int() : -99;
  334. if (!WITHIN(test_pattern, -1, 2)) {
  335. SERIAL_ECHOLNPGM("Invalid test_pattern value. (-1 to 2)\n");
  336. return;
  337. }
  338. SERIAL_ECHOLNPGM("Loading test_pattern values.\n");
  339. switch (test_pattern) {
  340. #if ENABLED(UBL_DEVEL_DEBUGGING)
  341. case -1:
  342. g29_eeprom_dump();
  343. break;
  344. #endif
  345. case 0:
  346. GRID_LOOP(x, y) { // Create a bowl shape similar to a poorly-calibrated Delta
  347. const float p1 = 0.5f * (GRID_MAX_POINTS_X) - x,
  348. p2 = 0.5f * (GRID_MAX_POINTS_Y) - y;
  349. z_values[x][y] += 2.0f * HYPOT(p1, p2);
  350. #if ENABLED(EXTENSIBLE_UI)
  351. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  352. #endif
  353. }
  354. break;
  355. case 1:
  356. LOOP_L_N(x, GRID_MAX_POINTS_X) { // Create a diagonal line several Mesh cells thick that is raised
  357. z_values[x][x] += 9.999f;
  358. z_values[x][x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1] += 9.999f; // We want the altered line several mesh points thick
  359. #if ENABLED(EXTENSIBLE_UI)
  360. ExtUI::onMeshUpdate(x, x, z_values[x][x]);
  361. ExtUI::onMeshUpdate(x, (x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1), z_values[x][x + (x < (GRID_MAX_POINTS_Y) - 1) ? 1 : -1]);
  362. #endif
  363. }
  364. break;
  365. case 2:
  366. // Allow the user to specify the height because 10mm is a little extreme in some cases.
  367. for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in
  368. for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) { // the center of the bed
  369. z_values[x][y] += parser.seen('C') ? g29_constant : 9.99f;
  370. #if ENABLED(EXTENSIBLE_UI)
  371. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  372. #endif
  373. }
  374. break;
  375. }
  376. }
  377. #if HAS_BED_PROBE
  378. if (parser.seen('J')) {
  379. if (g29_grid_size) { // if not 0 it is a normal n x n grid being probed
  380. save_ubl_active_state_and_disable();
  381. tilt_mesh_based_on_probed_grid(false /* false says to do normal grid probing */ );
  382. restore_ubl_active_state_and_leave();
  383. }
  384. else { // grid_size == 0 : A 3-Point leveling has been requested
  385. save_ubl_active_state_and_disable();
  386. tilt_mesh_based_on_probed_grid(true /* true says to do 3-Point leveling */ );
  387. restore_ubl_active_state_and_leave();
  388. }
  389. do_blocking_move_to_xy(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)));
  390. report_current_position();
  391. probe_deployed = true;
  392. }
  393. #endif // HAS_BED_PROBE
  394. if (parser.seen('P')) {
  395. if (WITHIN(g29_phase_value, 0, 1) && storage_slot == -1) {
  396. storage_slot = 0;
  397. SERIAL_ECHOLNPGM("Default storage slot 0 selected.");
  398. }
  399. switch (g29_phase_value) {
  400. case 0:
  401. //
  402. // Zero Mesh Data
  403. //
  404. reset();
  405. SERIAL_ECHOLNPGM("Mesh zeroed.");
  406. break;
  407. #if HAS_BED_PROBE
  408. case 1: {
  409. //
  410. // Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
  411. //
  412. if (!parser.seen('C')) {
  413. invalidate();
  414. SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh.");
  415. }
  416. if (g29_verbose_level > 1) {
  417. SERIAL_ECHOPAIR("Probing around (", g29_pos.x);
  418. SERIAL_CHAR(',');
  419. SERIAL_ECHO(g29_pos.y);
  420. SERIAL_ECHOLNPGM(").\n");
  421. }
  422. const xy_pos_t near = g29_pos + probe.offset_xy;
  423. probe_entire_mesh(near, parser.seen('T'), parser.seen('E'), parser.seen('U'));
  424. report_current_position();
  425. probe_deployed = true;
  426. } break;
  427. #endif // HAS_BED_PROBE
  428. case 2: {
  429. #if HAS_LCD_MENU
  430. //
  431. // Manually Probe Mesh in areas that can't be reached by the probe
  432. //
  433. SERIAL_ECHOLNPGM("Manually probing unreachable points.");
  434. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  435. if (parser.seen('C') && !xy_seen) {
  436. /**
  437. * Use a good default location for the path.
  438. * The flipped > and < operators in these comparisons is intentional.
  439. * It should cause the probed points to follow a nice path on Cartesian printers.
  440. * It may make sense to have Delta printers default to the center of the bed.
  441. * Until that is decided, this can be forced with the X and Y parameters.
  442. */
  443. g29_pos.set(
  444. #if IS_KINEMATIC
  445. X_HOME_POS, Y_HOME_POS
  446. #else
  447. probe.offset_xy.x > 0 ? X_BED_SIZE : 0,
  448. probe.offset_xy.y < 0 ? Y_BED_SIZE : 0
  449. #endif
  450. );
  451. }
  452. if (parser.seen('B')) {
  453. g29_card_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness((float) Z_CLEARANCE_BETWEEN_PROBES);
  454. if (ABS(g29_card_thickness) > 1.5f) {
  455. SERIAL_ECHOLNPGM("?Error in Business Card measurement.");
  456. return;
  457. }
  458. probe_deployed = true;
  459. }
  460. if (!position_is_reachable(g29_pos)) {
  461. SERIAL_ECHOLNPGM("XY outside printable radius.");
  462. return;
  463. }
  464. const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES);
  465. manually_probe_remaining_mesh(g29_pos, height, g29_card_thickness, parser.seen('T'));
  466. SERIAL_ECHOLNPGM("G29 P2 finished.");
  467. report_current_position();
  468. #else
  469. SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present.");
  470. return;
  471. #endif
  472. } break;
  473. case 3: {
  474. /**
  475. * Populate invalid mesh areas. Proceed with caution.
  476. * Two choices are available:
  477. * - Specify a constant with the 'C' parameter.
  478. * - Allow 'G29 P3' to choose a 'reasonable' constant.
  479. */
  480. if (g29_c_flag) {
  481. if (g29_repetition_cnt >= GRID_MAX_POINTS) {
  482. set_all_mesh_points_to_value(g29_constant);
  483. }
  484. else {
  485. while (g29_repetition_cnt--) { // this only populates reachable mesh points near
  486. const mesh_index_pair closest = find_closest_mesh_point_of_type(INVALID, g29_pos);
  487. const xy_int8_t &cpos = closest.pos;
  488. if (cpos.x < 0) {
  489. // No more REAL INVALID mesh points to populate, so we ASSUME
  490. // user meant to populate ALL INVALID mesh points to value
  491. GRID_LOOP(x, y) if (isnan(z_values[x][y])) z_values[x][y] = g29_constant;
  492. break; // No more invalid Mesh Points to populate
  493. }
  494. else {
  495. z_values[cpos.x][cpos.y] = g29_constant;
  496. #if ENABLED(EXTENSIBLE_UI)
  497. ExtUI::onMeshUpdate(cpos, g29_constant);
  498. #endif
  499. }
  500. }
  501. }
  502. }
  503. else {
  504. const float cvf = parser.value_float();
  505. switch ((int)truncf(cvf * 10.0f) - 30) { // 3.1 -> 1
  506. #if ENABLED(UBL_G29_P31)
  507. case 1: {
  508. // P3.1 use least squares fit to fill missing mesh values
  509. // P3.10 zero weighting for distance, all grid points equal, best fit tilted plane
  510. // P3.11 10X weighting for nearest grid points versus farthest grid points
  511. // P3.12 100X distance weighting
  512. // P3.13 1000X distance weighting, approaches simple average of nearest points
  513. const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345
  514. weight_factor = weight_power ? POW(10.0f, weight_power) : 0;
  515. smart_fill_wlsf(weight_factor);
  516. }
  517. break;
  518. #endif
  519. case 0: // P3 or P3.0
  520. default: // and anything P3.x that's not P3.1
  521. smart_fill_mesh(); // Do a 'Smart' fill using nearby known values
  522. break;
  523. }
  524. }
  525. break;
  526. }
  527. case 4: // Fine Tune (i.e., Edit) the Mesh
  528. #if HAS_LCD_MENU
  529. fine_tune_mesh(g29_pos, parser.seen('T'));
  530. #else
  531. SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present.");
  532. return;
  533. #endif
  534. break;
  535. case 5: adjust_mesh_to_mean(g29_c_flag, g29_constant); break;
  536. case 6: shift_mesh_height(); break;
  537. }
  538. }
  539. #if ENABLED(UBL_DEVEL_DEBUGGING)
  540. //
  541. // Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  542. // good to have the extra information. Soon... we prune this to just a few items
  543. //
  544. if (parser.seen('W')) g29_what_command();
  545. //
  546. // When we are fully debugged, this may go away. But there are some valid
  547. // use cases for the users. So we can wait and see what to do with it.
  548. //
  549. if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
  550. g29_compare_current_mesh_to_stored_mesh();
  551. #endif // UBL_DEVEL_DEBUGGING
  552. //
  553. // Load a Mesh from the EEPROM
  554. //
  555. if (parser.seen('L')) { // Load Current Mesh Data
  556. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  557. int16_t a = settings.calc_num_meshes();
  558. if (!a) {
  559. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  560. return;
  561. }
  562. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  563. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  564. return;
  565. }
  566. settings.load_mesh(g29_storage_slot);
  567. storage_slot = g29_storage_slot;
  568. SERIAL_ECHOLNPGM("Done.");
  569. }
  570. //
  571. // Store a Mesh in the EEPROM
  572. //
  573. if (parser.seen('S')) { // Store (or Save) Current Mesh Data
  574. g29_storage_slot = parser.has_value() ? parser.value_int() : storage_slot;
  575. if (g29_storage_slot == -1) // Special case, the user wants to 'Export' the mesh to the
  576. return report_current_mesh(); // host program to be saved on the user's computer
  577. int16_t a = settings.calc_num_meshes();
  578. if (!a) {
  579. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  580. goto LEAVE;
  581. }
  582. if (!WITHIN(g29_storage_slot, 0, a - 1)) {
  583. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  584. goto LEAVE;
  585. }
  586. settings.store_mesh(g29_storage_slot);
  587. storage_slot = g29_storage_slot;
  588. SERIAL_ECHOLNPGM("Done.");
  589. }
  590. if (parser.seen('T'))
  591. display_map(g29_map_type);
  592. LEAVE:
  593. #if HAS_LCD_MENU
  594. ui.reset_alert_level();
  595. ui.quick_feedback();
  596. ui.reset_status();
  597. ui.release();
  598. #endif
  599. #ifdef Z_PROBE_END_SCRIPT
  600. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  601. if (probe_deployed) {
  602. planner.synchronize();
  603. gcode.process_subcommands_now_P(PSTR(Z_PROBE_END_SCRIPT));
  604. }
  605. #else
  606. UNUSED(probe_deployed);
  607. #endif
  608. #if HOTENDS > 1
  609. tool_change(old_tool_index);
  610. #endif
  611. return;
  612. }
  613. void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const float value) {
  614. float sum = 0;
  615. int n = 0;
  616. GRID_LOOP(x, y)
  617. if (!isnan(z_values[x][y])) {
  618. sum += z_values[x][y];
  619. n++;
  620. }
  621. const float mean = sum / n;
  622. //
  623. // Sum the squares of difference from mean
  624. //
  625. float sum_of_diff_squared = 0;
  626. GRID_LOOP(x, y)
  627. if (!isnan(z_values[x][y]))
  628. sum_of_diff_squared += sq(z_values[x][y] - mean);
  629. SERIAL_ECHOLNPAIR("# of samples: ", n);
  630. SERIAL_ECHOLNPAIR_F("Mean Mesh Height: ", mean, 6);
  631. const float sigma = SQRT(sum_of_diff_squared / (n + 1));
  632. SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6);
  633. if (cflag)
  634. GRID_LOOP(x, y)
  635. if (!isnan(z_values[x][y])) {
  636. z_values[x][y] -= mean + value;
  637. #if ENABLED(EXTENSIBLE_UI)
  638. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  639. #endif
  640. }
  641. }
  642. void unified_bed_leveling::shift_mesh_height() {
  643. GRID_LOOP(x, y)
  644. if (!isnan(z_values[x][y])) {
  645. z_values[x][y] += g29_constant;
  646. #if ENABLED(EXTENSIBLE_UI)
  647. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  648. #endif
  649. }
  650. }
  651. #if HAS_BED_PROBE
  652. /**
  653. * Probe all invalidated locations of the mesh that can be reached by the probe.
  654. * This attempts to fill in locations closest to the nozzle's start location first.
  655. */
  656. void unified_bed_leveling::probe_entire_mesh(const xy_pos_t &near, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) {
  657. probe.deploy(); // Deploy before ui.capture() to allow for PAUSE_BEFORE_DEPLOY_STOW
  658. #if HAS_LCD_MENU
  659. ui.capture();
  660. #endif
  661. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  662. uint8_t count = GRID_MAX_POINTS;
  663. mesh_index_pair best;
  664. do {
  665. if (do_ubl_mesh_map) display_map(g29_map_type);
  666. const int point_num = (GRID_MAX_POINTS) - count + 1;
  667. SERIAL_ECHOLNPAIR("\nProbing mesh point ", point_num, "/", int(GRID_MAX_POINTS), ".\n");
  668. #if HAS_DISPLAY
  669. ui.status_printf_P(0, PSTR(S_FMT " %i/%i"), GET_TEXT(MSG_PROBING_MESH), point_num, int(GRID_MAX_POINTS));
  670. #endif
  671. #if HAS_LCD_MENU
  672. if (ui.button_pressed()) {
  673. ui.quick_feedback(false); // Preserve button state for click-and-hold
  674. SERIAL_ECHOLNPGM("\nMesh only partially populated.\n");
  675. ui.wait_for_release();
  676. ui.quick_feedback();
  677. ui.release();
  678. probe.stow(); // Release UI before stow to allow for PAUSE_BEFORE_DEPLOY_STOW
  679. return restore_ubl_active_state_and_leave();
  680. }
  681. #endif
  682. best = do_furthest
  683. ? find_furthest_invalid_mesh_point()
  684. : find_closest_mesh_point_of_type(INVALID, near, true);
  685. if (best.pos.x >= 0) { // mesh point found and is reachable by probe
  686. const float measured_z = probe.probe_at_point(
  687. best.meshpos(),
  688. stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level
  689. );
  690. z_values[best.pos.x][best.pos.y] = measured_z;
  691. #if ENABLED(EXTENSIBLE_UI)
  692. ExtUI::onMeshUpdate(best.pos, measured_z);
  693. #endif
  694. }
  695. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  696. } while (best.pos.x >= 0 && --count);
  697. #if HAS_LCD_MENU
  698. ui.release();
  699. #endif
  700. probe.stow(); // Release UI during stow to allow for PAUSE_BEFORE_DEPLOY_STOW
  701. #if HAS_LCD_MENU
  702. ui.capture();
  703. #endif
  704. #ifdef Z_AFTER_PROBING
  705. probe.move_z_after_probing();
  706. #endif
  707. restore_ubl_active_state_and_leave();
  708. do_blocking_move_to_xy(
  709. constrain(near.x - probe.offset_xy.x, MESH_MIN_X, MESH_MAX_X),
  710. constrain(near.y - probe.offset_xy.y, MESH_MIN_Y, MESH_MAX_Y)
  711. );
  712. }
  713. #endif // HAS_BED_PROBE
  714. #if HAS_LCD_MENU
  715. typedef void (*clickFunc_t)();
  716. bool click_and_hold(const clickFunc_t func=nullptr) {
  717. if (ui.button_pressed()) {
  718. ui.quick_feedback(false); // Preserve button state for click-and-hold
  719. const millis_t nxt = millis() + 1500UL;
  720. while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag!
  721. idle(); // idle, of course
  722. if (ELAPSED(millis(), nxt)) { // After 1.5 seconds
  723. ui.quick_feedback();
  724. if (func) (*func)();
  725. ui.wait_for_release();
  726. return true;
  727. }
  728. }
  729. }
  730. serial_delay(15);
  731. return false;
  732. }
  733. void unified_bed_leveling::move_z_with_encoder(const float &multiplier) {
  734. ui.wait_for_release();
  735. while (!ui.button_pressed()) {
  736. idle();
  737. gcode.reset_stepper_timeout(); // Keep steppers powered
  738. if (encoder_diff) {
  739. do_blocking_move_to_z(current_position.z + float(encoder_diff) * multiplier);
  740. encoder_diff = 0;
  741. }
  742. }
  743. }
  744. float unified_bed_leveling::measure_point_with_encoder() {
  745. KEEPALIVE_STATE(PAUSED_FOR_USER);
  746. move_z_with_encoder(0.01f);
  747. return current_position.z;
  748. }
  749. static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); }
  750. float unified_bed_leveling::measure_business_card_thickness(float in_height) {
  751. #if HAS_LCD_MENU
  752. ui.capture();
  753. #endif
  754. save_ubl_active_state_and_disable(); // Disable bed level correction for probing
  755. do_blocking_move_to(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)), in_height);
  756. //, _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f);
  757. planner.synchronize();
  758. SERIAL_ECHOPGM("Place shim under nozzle");
  759. LCD_MESSAGEPGM(MSG_UBL_BC_INSERT);
  760. ui.return_to_status();
  761. echo_and_take_a_measurement();
  762. const float z1 = measure_point_with_encoder();
  763. do_blocking_move_to_z(current_position.z + SIZE_OF_LITTLE_RAISE);
  764. planner.synchronize();
  765. SERIAL_ECHOPGM("Remove shim");
  766. LCD_MESSAGEPGM(MSG_UBL_BC_REMOVE);
  767. echo_and_take_a_measurement();
  768. const float z2 = measure_point_with_encoder();
  769. do_blocking_move_to_z(current_position.z + Z_CLEARANCE_BETWEEN_PROBES);
  770. const float thickness = ABS(z1 - z2);
  771. if (g29_verbose_level > 1) {
  772. SERIAL_ECHOPAIR_F("Business Card is ", thickness, 4);
  773. SERIAL_ECHOLNPGM("mm thick.");
  774. }
  775. ui.release();
  776. restore_ubl_active_state_and_leave();
  777. return thickness;
  778. }
  779. void unified_bed_leveling::manually_probe_remaining_mesh(const xy_pos_t &pos, const float &z_clearance, const float &thick, const bool do_ubl_mesh_map) {
  780. #if HAS_LCD_MENU
  781. ui.capture();
  782. #endif
  783. save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
  784. do_blocking_move_to_xy_z(current_position, z_clearance);
  785. ui.return_to_status();
  786. mesh_index_pair location;
  787. const xy_int8_t &lpos = location.pos;
  788. do {
  789. location = find_closest_mesh_point_of_type(INVALID, pos);
  790. // It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
  791. if (!location.valid()) continue;
  792. const xyz_pos_t ppos = {
  793. mesh_index_to_xpos(lpos.x),
  794. mesh_index_to_ypos(lpos.y),
  795. Z_CLEARANCE_BETWEEN_PROBES
  796. };
  797. if (!position_is_reachable(ppos)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points)
  798. LCD_MESSAGEPGM(MSG_UBL_MOVING_TO_NEXT);
  799. do_blocking_move_to(ppos);
  800. do_blocking_move_to_z(z_clearance);
  801. KEEPALIVE_STATE(PAUSED_FOR_USER);
  802. #if HAS_LCD_MENU
  803. ui.capture();
  804. #endif
  805. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  806. serialprintPGM(parser.seen('B') ? GET_TEXT(MSG_UBL_BC_INSERT) : GET_TEXT(MSG_UBL_BC_INSERT2));
  807. const float z_step = 0.01f; // existing behavior: 0.01mm per click, occasionally step
  808. //const float z_step = planner.steps_to_mm[Z_AXIS]; // approx one step each click
  809. move_z_with_encoder(z_step);
  810. if (click_and_hold()) {
  811. SERIAL_ECHOLNPGM("\nMesh only partially populated.");
  812. do_blocking_move_to_z(Z_CLEARANCE_DEPLOY_PROBE);
  813. ui.release();
  814. return restore_ubl_active_state_and_leave();
  815. }
  816. z_values[lpos.x][lpos.y] = current_position.z - thick;
  817. #if ENABLED(EXTENSIBLE_UI)
  818. ExtUI::onMeshUpdate(location, z_values[lpos.x][lpos.y]);
  819. #endif
  820. if (g29_verbose_level > 2)
  821. SERIAL_ECHOLNPAIR_F("Mesh Point Measured at: ", z_values[lpos.x][lpos.y], 6);
  822. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  823. } while (location.valid());
  824. if (do_ubl_mesh_map) display_map(g29_map_type); // show user where we're probing
  825. restore_ubl_active_state_and_leave();
  826. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_DEPLOY_PROBE);
  827. }
  828. inline void set_message_with_feedback(PGM_P const msg_P) {
  829. ui.set_status_P(msg_P);
  830. ui.quick_feedback();
  831. }
  832. void abort_fine_tune() {
  833. ui.return_to_status();
  834. do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
  835. set_message_with_feedback(GET_TEXT(MSG_EDITING_STOPPED));
  836. }
  837. void unified_bed_leveling::fine_tune_mesh(const xy_pos_t &pos, const bool do_ubl_mesh_map) {
  838. if (!parser.seen('R')) // fine_tune_mesh() is special. If no repetition count flag is specified
  839. g29_repetition_cnt = 1; // do exactly one mesh location. Otherwise use what the parser decided.
  840. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  841. const float h_offset = parser.seenval('H') ? parser.value_linear_units() : 0;
  842. if (!WITHIN(h_offset, 0, 10)) {
  843. SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n");
  844. return;
  845. }
  846. #endif
  847. mesh_index_pair location;
  848. if (!position_is_reachable(pos)) {
  849. SERIAL_ECHOLNPGM("(X,Y) outside printable radius.");
  850. return;
  851. }
  852. save_ubl_active_state_and_disable();
  853. LCD_MESSAGEPGM(MSG_UBL_FINE_TUNE_MESH);
  854. #if HAS_LCD_MENU
  855. ui.capture(); // Take over control of the LCD encoder
  856. #endif
  857. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES); // Move to the given XY with probe clearance
  858. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  859. do_blocking_move_to_z(h_offset); // Move Z to the given 'H' offset
  860. #endif
  861. MeshFlags done_flags{0};
  862. const xy_int8_t &lpos = location.pos;
  863. do {
  864. location = find_closest_mesh_point_of_type(SET_IN_BITMAP, pos, false, &done_flags);
  865. if (lpos.x < 0) break; // Stop when there are no more reachable points
  866. done_flags.mark(lpos); // Mark this location as 'adjusted' so a new
  867. // location is used on the next loop
  868. const xyz_pos_t raw = {
  869. mesh_index_to_xpos(lpos.x),
  870. mesh_index_to_ypos(lpos.y),
  871. Z_CLEARANCE_BETWEEN_PROBES
  872. };
  873. if (!position_is_reachable(raw)) break; // SHOULD NOT OCCUR (find_closest_mesh_point_of_type only returns reachable)
  874. do_blocking_move_to(raw); // Move the nozzle to the edit point with probe clearance
  875. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  876. do_blocking_move_to_z(h_offset); // Move Z to the given 'H' offset before editing
  877. #endif
  878. KEEPALIVE_STATE(PAUSED_FOR_USER);
  879. if (do_ubl_mesh_map) display_map(g29_map_type); // Display the current point
  880. ui.refresh();
  881. float new_z = z_values[lpos.x][lpos.y];
  882. if (isnan(new_z)) new_z = 0; // Invalid points begin at 0
  883. new_z = FLOOR(new_z * 1000) * 0.001f; // Chop off digits after the 1000ths place
  884. lcd_mesh_edit_setup(new_z);
  885. do {
  886. new_z = lcd_mesh_edit();
  887. #if ENABLED(UBL_MESH_EDIT_MOVES_Z)
  888. do_blocking_move_to_z(h_offset + new_z); // Move the nozzle as the point is edited
  889. #endif
  890. idle();
  891. SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
  892. } while (!ui.button_pressed());
  893. if (!lcd_map_control) ui.return_to_status(); // Just editing a single point? Return to status
  894. if (click_and_hold(abort_fine_tune)) break; // Button held down? Abort editing
  895. z_values[lpos.x][lpos.y] = new_z; // Save the updated Z value
  896. #if ENABLED(EXTENSIBLE_UI)
  897. ExtUI::onMeshUpdate(location, new_z);
  898. #endif
  899. serial_delay(20); // No switch noise
  900. ui.refresh();
  901. } while (lpos.x >= 0 && --g29_repetition_cnt > 0);
  902. ui.release();
  903. if (do_ubl_mesh_map) display_map(g29_map_type);
  904. restore_ubl_active_state_and_leave();
  905. do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES);
  906. LCD_MESSAGEPGM(MSG_UBL_DONE_EDITING_MESH);
  907. SERIAL_ECHOLNPGM("Done Editing Mesh");
  908. if (lcd_map_control)
  909. ui.goto_screen(_lcd_ubl_output_map_lcd);
  910. else
  911. ui.return_to_status();
  912. }
  913. #endif // HAS_LCD_MENU
  914. bool unified_bed_leveling::g29_parameter_parsing() {
  915. bool err_flag = false;
  916. #if HAS_LCD_MENU
  917. set_message_with_feedback(GET_TEXT(MSG_UBL_DOING_G29));
  918. #endif
  919. g29_constant = 0;
  920. g29_repetition_cnt = 0;
  921. if (parser.seen('R')) {
  922. g29_repetition_cnt = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS;
  923. NOMORE(g29_repetition_cnt, GRID_MAX_POINTS);
  924. if (g29_repetition_cnt < 1) {
  925. SERIAL_ECHOLNPGM("?(R)epetition count invalid (1+).\n");
  926. return UBL_ERR;
  927. }
  928. }
  929. g29_verbose_level = parser.seen('V') ? parser.value_int() : 0;
  930. if (!WITHIN(g29_verbose_level, 0, 4)) {
  931. SERIAL_ECHOLNPGM("?(V)erbose level implausible (0-4).\n");
  932. err_flag = true;
  933. }
  934. if (parser.seen('P')) {
  935. const int pv = parser.value_int();
  936. #if !HAS_BED_PROBE
  937. if (pv == 1) {
  938. SERIAL_ECHOLNPGM("G29 P1 requires a probe.\n");
  939. err_flag = true;
  940. }
  941. else
  942. #endif
  943. {
  944. g29_phase_value = pv;
  945. if (!WITHIN(g29_phase_value, 0, 6)) {
  946. SERIAL_ECHOLNPGM("?(P)hase value invalid (0-6).\n");
  947. err_flag = true;
  948. }
  949. }
  950. }
  951. if (parser.seen('J')) {
  952. #if HAS_BED_PROBE
  953. g29_grid_size = parser.has_value() ? parser.value_int() : 0;
  954. if (g29_grid_size && !WITHIN(g29_grid_size, 2, 9)) {
  955. SERIAL_ECHOLNPGM("?Invalid grid size (J) specified (2-9).\n");
  956. err_flag = true;
  957. }
  958. #else
  959. SERIAL_ECHOLNPGM("G29 J action requires a probe.\n");
  960. err_flag = true;
  961. #endif
  962. }
  963. xy_seen.x = parser.seenval('X');
  964. float sx = xy_seen.x ? parser.value_float() : current_position.x;
  965. xy_seen.y = parser.seenval('Y');
  966. float sy = xy_seen.y ? parser.value_float() : current_position.y;
  967. if (xy_seen.x != xy_seen.y) {
  968. SERIAL_ECHOLNPGM("Both X & Y locations must be specified.\n");
  969. err_flag = true;
  970. }
  971. // If X or Y are not valid, use center of the bed values
  972. if (!WITHIN(sx, X_MIN_BED, X_MAX_BED)) sx = X_CENTER;
  973. if (!WITHIN(sy, Y_MIN_BED, Y_MAX_BED)) sy = Y_CENTER;
  974. if (err_flag) return UBL_ERR;
  975. g29_pos.set(sx, sy);
  976. /**
  977. * Activate or deactivate UBL
  978. * Note: UBL's G29 restores the state set here when done.
  979. * Leveling is being enabled here with old data, possibly
  980. * none. Error handling should disable for safety...
  981. */
  982. if (parser.seen('A')) {
  983. if (parser.seen('D')) {
  984. SERIAL_ECHOLNPGM("?Can't activate and deactivate at the same time.\n");
  985. return UBL_ERR;
  986. }
  987. set_bed_leveling_enabled(true);
  988. report_state();
  989. }
  990. else if (parser.seen('D')) {
  991. set_bed_leveling_enabled(false);
  992. report_state();
  993. }
  994. // Set global 'C' flag and its value
  995. if ((g29_c_flag = parser.seen('C')))
  996. g29_constant = parser.value_float();
  997. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  998. if (parser.seenval('F')) {
  999. const float fh = parser.value_float();
  1000. if (!WITHIN(fh, 0, 100)) {
  1001. SERIAL_ECHOLNPGM("?(F)ade height for Bed Level Correction not plausible.\n");
  1002. return UBL_ERR;
  1003. }
  1004. set_z_fade_height(fh);
  1005. }
  1006. #endif
  1007. g29_map_type = parser.intval('T');
  1008. if (!WITHIN(g29_map_type, 0, 2)) {
  1009. SERIAL_ECHOLNPGM("Invalid map type.\n");
  1010. return UBL_ERR;
  1011. }
  1012. return UBL_OK;
  1013. }
  1014. static uint8_t ubl_state_at_invocation = 0;
  1015. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1016. static uint8_t ubl_state_recursion_chk = 0;
  1017. #endif
  1018. void unified_bed_leveling::save_ubl_active_state_and_disable() {
  1019. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1020. ubl_state_recursion_chk++;
  1021. if (ubl_state_recursion_chk != 1) {
  1022. SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row.");
  1023. #if HAS_LCD_MENU
  1024. set_message_with_feedback(GET_TEXT(MSG_UBL_SAVE_ERROR));
  1025. #endif
  1026. return;
  1027. }
  1028. #endif
  1029. ubl_state_at_invocation = planner.leveling_active;
  1030. set_bed_leveling_enabled(false);
  1031. }
  1032. void unified_bed_leveling::restore_ubl_active_state_and_leave() {
  1033. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1034. if (--ubl_state_recursion_chk) {
  1035. SERIAL_ECHOLNPGM("restore_ubl_active_state_and_leave() called too many times.");
  1036. #if HAS_LCD_MENU
  1037. set_message_with_feedback(GET_TEXT(MSG_UBL_RESTORE_ERROR));
  1038. #endif
  1039. return;
  1040. }
  1041. #endif
  1042. set_bed_leveling_enabled(ubl_state_at_invocation);
  1043. }
  1044. mesh_index_pair unified_bed_leveling::find_furthest_invalid_mesh_point() {
  1045. bool found_a_NAN = false, found_a_real = false;
  1046. mesh_index_pair farthest { -1, -1, -99999.99 };
  1047. GRID_LOOP(i, j) {
  1048. if (!isnan(z_values[i][j])) continue; // Skip valid mesh points
  1049. // Skip unreachable points
  1050. if (!probe.can_reach(mesh_index_to_xpos(i), mesh_index_to_ypos(j)))
  1051. continue;
  1052. found_a_NAN = true;
  1053. xy_int8_t near { -1, -1 };
  1054. float d1, d2 = 99999.9f;
  1055. GRID_LOOP(k, l) {
  1056. if (isnan(z_values[k][l])) continue;
  1057. found_a_real = true;
  1058. // Add in a random weighting factor that scrambles the probing of the
  1059. // last half of the mesh (when every unprobed mesh point is one index
  1060. // from a probed location).
  1061. d1 = HYPOT(i - k, j - l) + (1.0f / ((millis() % 47) + 13));
  1062. if (d1 < d2) { // Invalid mesh point (i,j) is closer to the defined point (k,l)
  1063. d2 = d1;
  1064. near.set(i, j);
  1065. }
  1066. }
  1067. //
  1068. // At this point d2 should have the near defined mesh point to invalid mesh point (i,j)
  1069. //
  1070. if (found_a_real && near.x >= 0 && d2 > farthest.distance) {
  1071. farthest.pos = near; // Found an invalid location farther from the defined mesh point
  1072. farthest.distance = d2;
  1073. }
  1074. } // GRID_LOOP
  1075. if (!found_a_real && found_a_NAN) { // if the mesh is totally unpopulated, start the probing
  1076. farthest.pos.set((GRID_MAX_POINTS_X) / 2, (GRID_MAX_POINTS_Y) / 2);
  1077. farthest.distance = 1;
  1078. }
  1079. return farthest;
  1080. }
  1081. mesh_index_pair unified_bed_leveling::find_closest_mesh_point_of_type(const MeshPointType type, const xy_pos_t &pos, const bool probe_relative/*=false*/, MeshFlags *done_flags/*=nullptr*/) {
  1082. mesh_index_pair closest;
  1083. closest.invalidate();
  1084. closest.distance = -99999.9f;
  1085. // Get the reference position, either nozzle or probe
  1086. const xy_pos_t ref = probe_relative ? pos + probe.offset_xy : pos;
  1087. float best_so_far = 99999.99f;
  1088. GRID_LOOP(i, j) {
  1089. if ( (type == (isnan(z_values[i][j]) ? INVALID : REAL))
  1090. || (type == SET_IN_BITMAP && !done_flags->marked(i, j))
  1091. ) {
  1092. // Found a Mesh Point of the specified type!
  1093. const xy_pos_t mpos = { mesh_index_to_xpos(i), mesh_index_to_ypos(j) };
  1094. // If using the probe as the reference there are some unreachable locations.
  1095. // Also for round beds, there are grid points outside the bed the nozzle can't reach.
  1096. // Prune them from the list and ignore them till the next Phase (manual nozzle probing).
  1097. if (!(probe_relative ? probe.can_reach(mpos) : position_is_reachable(mpos)))
  1098. continue;
  1099. // Reachable. Check if it's the best_so_far location to the nozzle.
  1100. const xy_pos_t diff = current_position - mpos;
  1101. const float distance = (ref - mpos).magnitude() + diff.magnitude() * 0.1f;
  1102. // factor in the distance from the current location for the normal case
  1103. // so the nozzle isn't running all over the bed.
  1104. if (distance < best_so_far) {
  1105. best_so_far = distance; // Found a closer location with the desired value type.
  1106. closest.pos.set(i, j);
  1107. closest.distance = best_so_far;
  1108. }
  1109. }
  1110. } // GRID_LOOP
  1111. return closest;
  1112. }
  1113. /**
  1114. * 'Smart Fill': Scan from the outward edges of the mesh towards the center.
  1115. * If an invalid location is found, use the next two points (if valid) to
  1116. * calculate a 'reasonable' value for the unprobed mesh point.
  1117. */
  1118. bool unified_bed_leveling::smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  1119. const float v = z_values[x][y];
  1120. if (isnan(v)) { // A NAN...
  1121. const int8_t dx = x + xdir, dy = y + ydir;
  1122. const float v1 = z_values[dx][dy];
  1123. if (!isnan(v1)) { // ...next to a pair of real values?
  1124. const float v2 = z_values[dx + xdir][dy + ydir];
  1125. if (!isnan(v2)) {
  1126. z_values[x][y] = v1 < v2 ? v1 : v1 + v1 - v2;
  1127. #if ENABLED(EXTENSIBLE_UI)
  1128. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  1129. #endif
  1130. return true;
  1131. }
  1132. }
  1133. }
  1134. return false;
  1135. }
  1136. typedef struct { uint8_t sx, ex, sy, ey; bool yfirst; } smart_fill_info;
  1137. void unified_bed_leveling::smart_fill_mesh() {
  1138. static const smart_fill_info
  1139. info0 PROGMEM = { 0, GRID_MAX_POINTS_X, 0, GRID_MAX_POINTS_Y - 2, false }, // Bottom of the mesh looking up
  1140. info1 PROGMEM = { 0, GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y - 1, 0, false }, // Top of the mesh looking down
  1141. info2 PROGMEM = { 0, GRID_MAX_POINTS_X - 2, 0, GRID_MAX_POINTS_Y, true }, // Left side of the mesh looking right
  1142. info3 PROGMEM = { GRID_MAX_POINTS_X - 1, 0, 0, GRID_MAX_POINTS_Y, true }; // Right side of the mesh looking left
  1143. static const smart_fill_info * const info[] PROGMEM = { &info0, &info1, &info2, &info3 };
  1144. LOOP_L_N(i, COUNT(info)) {
  1145. const smart_fill_info *f = (smart_fill_info*)pgm_read_ptr(&info[i]);
  1146. const int8_t sx = pgm_read_byte(&f->sx), sy = pgm_read_byte(&f->sy),
  1147. ex = pgm_read_byte(&f->ex), ey = pgm_read_byte(&f->ey);
  1148. if (pgm_read_byte(&f->yfirst)) {
  1149. const int8_t dir = ex > sx ? 1 : -1;
  1150. for (uint8_t y = sy; y != ey; ++y)
  1151. for (uint8_t x = sx; x != ex; x += dir)
  1152. if (smart_fill_one(x, y, dir, 0)) break;
  1153. }
  1154. else {
  1155. const int8_t dir = ey > sy ? 1 : -1;
  1156. for (uint8_t x = sx; x != ex; ++x)
  1157. for (uint8_t y = sy; y != ey; y += dir)
  1158. if (smart_fill_one(x, y, 0, dir)) break;
  1159. }
  1160. }
  1161. }
  1162. #if HAS_BED_PROBE
  1163. //#define VALIDATE_MESH_TILT
  1164. #include "../../../libs/vector_3.h"
  1165. void unified_bed_leveling::tilt_mesh_based_on_probed_grid(const bool do_3_pt_leveling) {
  1166. const float x_min = probe.min_x(), x_max = probe.max_x(),
  1167. y_min = probe.min_y(), y_max = probe.max_y(),
  1168. dx = (x_max - x_min) / (g29_grid_size - 1),
  1169. dy = (y_max - y_min) / (g29_grid_size - 1);
  1170. xy_float_t points[3];
  1171. probe.get_three_points(points);
  1172. float measured_z;
  1173. bool abort_flag = false;
  1174. #ifdef VALIDATE_MESH_TILT
  1175. float z1, z2, z3; // Needed for algorithm validation below
  1176. #endif
  1177. struct linear_fit_data lsf_results;
  1178. incremental_LSF_reset(&lsf_results);
  1179. if (do_3_pt_leveling) {
  1180. SERIAL_ECHOLNPGM("Tilting mesh (1/3)");
  1181. #if HAS_DISPLAY
  1182. ui.status_printf_P(0, PSTR(S_FMT " 1/3"), GET_TEXT(MSG_LCD_TILTING_MESH));
  1183. #endif
  1184. measured_z = probe.probe_at_point(points[0], PROBE_PT_RAISE, g29_verbose_level);
  1185. if (isnan(measured_z))
  1186. abort_flag = true;
  1187. else {
  1188. measured_z -= get_z_correction(points[0]);
  1189. #ifdef VALIDATE_MESH_TILT
  1190. z1 = measured_z;
  1191. #endif
  1192. if (g29_verbose_level > 3) {
  1193. serial_spaces(16);
  1194. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1195. }
  1196. incremental_LSF(&lsf_results, points[0], measured_z);
  1197. }
  1198. if (!abort_flag) {
  1199. SERIAL_ECHOLNPGM("Tilting mesh (2/3)");
  1200. #if HAS_DISPLAY
  1201. ui.status_printf_P(0, PSTR(S_FMT " 2/3"), GET_TEXT(MSG_LCD_TILTING_MESH));
  1202. #endif
  1203. measured_z = probe.probe_at_point(points[1], PROBE_PT_RAISE, g29_verbose_level);
  1204. #ifdef VALIDATE_MESH_TILT
  1205. z2 = measured_z;
  1206. #endif
  1207. if (isnan(measured_z))
  1208. abort_flag = true;
  1209. else {
  1210. measured_z -= get_z_correction(points[1]);
  1211. if (g29_verbose_level > 3) {
  1212. serial_spaces(16);
  1213. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1214. }
  1215. incremental_LSF(&lsf_results, points[1], measured_z);
  1216. }
  1217. }
  1218. if (!abort_flag) {
  1219. SERIAL_ECHOLNPGM("Tilting mesh (3/3)");
  1220. #if HAS_DISPLAY
  1221. ui.status_printf_P(0, PSTR(S_FMT " 3/3"), GET_TEXT(MSG_LCD_TILTING_MESH));
  1222. #endif
  1223. measured_z = probe.probe_at_point(points[2], PROBE_PT_STOW, g29_verbose_level);
  1224. #ifdef VALIDATE_MESH_TILT
  1225. z3 = measured_z;
  1226. #endif
  1227. if (isnan(measured_z))
  1228. abort_flag = true;
  1229. else {
  1230. measured_z -= get_z_correction(points[2]);
  1231. if (g29_verbose_level > 3) {
  1232. serial_spaces(16);
  1233. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1234. }
  1235. incremental_LSF(&lsf_results, points[2], measured_z);
  1236. }
  1237. }
  1238. probe.stow();
  1239. #ifdef Z_AFTER_PROBING
  1240. probe.move_z_after_probing();
  1241. #endif
  1242. if (abort_flag) {
  1243. SERIAL_ECHOLNPGM("?Error probing point. Aborting operation.");
  1244. return;
  1245. }
  1246. }
  1247. else { // !do_3_pt_leveling
  1248. bool zig_zag = false;
  1249. const uint16_t total_points = sq(g29_grid_size);
  1250. uint16_t point_num = 1;
  1251. xy_pos_t rpos;
  1252. LOOP_L_N(ix, g29_grid_size) {
  1253. rpos.x = x_min + ix * dx;
  1254. LOOP_L_N(iy, g29_grid_size) {
  1255. rpos.y = y_min + dy * (zig_zag ? g29_grid_size - 1 - iy : iy);
  1256. if (!abort_flag) {
  1257. SERIAL_ECHOLNPAIR("Tilting mesh point ", point_num, "/", total_points, "\n");
  1258. #if HAS_DISPLAY
  1259. ui.status_printf_P(0, PSTR(S_FMT " %i/%i"), GET_TEXT(MSG_LCD_TILTING_MESH), point_num, total_points);
  1260. #endif
  1261. measured_z = probe.probe_at_point(rpos, parser.seen('E') ? PROBE_PT_STOW : PROBE_PT_RAISE, g29_verbose_level); // TODO: Needs error handling
  1262. abort_flag = isnan(measured_z);
  1263. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1264. if (DEBUGGING(LEVELING)) {
  1265. const xy_pos_t lpos = rpos.asLogical();
  1266. DEBUG_CHAR('(');
  1267. DEBUG_ECHO_F(rpos.x, 7);
  1268. DEBUG_CHAR(',');
  1269. DEBUG_ECHO_F(rpos.y, 7);
  1270. DEBUG_ECHOPAIR_F(") logical: (", lpos.x, 7);
  1271. DEBUG_CHAR(',');
  1272. DEBUG_ECHO_F(lpos.y, 7);
  1273. DEBUG_ECHOPAIR_F(") measured: ", measured_z, 7);
  1274. DEBUG_ECHOPAIR_F(" correction: ", get_z_correction(rpos), 7);
  1275. }
  1276. #endif
  1277. measured_z -= get_z_correction(rpos) /* + probe.offset.z */ ;
  1278. if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR_F(" final >>>---> ", measured_z, 7);
  1279. if (g29_verbose_level > 3) {
  1280. serial_spaces(16);
  1281. SERIAL_ECHOLNPAIR("Corrected_Z=", measured_z);
  1282. }
  1283. incremental_LSF(&lsf_results, rpos, measured_z);
  1284. }
  1285. point_num++;
  1286. }
  1287. zig_zag ^= true;
  1288. }
  1289. }
  1290. probe.stow();
  1291. #ifdef Z_AFTER_PROBING
  1292. probe.move_z_after_probing();
  1293. #endif
  1294. if (abort_flag || finish_incremental_LSF(&lsf_results)) {
  1295. SERIAL_ECHOPGM("Could not complete LSF!");
  1296. return;
  1297. }
  1298. vector_3 normal = vector_3(lsf_results.A, lsf_results.B, 1).get_normal();
  1299. if (g29_verbose_level > 2) {
  1300. SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1301. SERIAL_CHAR(',');
  1302. SERIAL_ECHO_F(normal.y, 7);
  1303. SERIAL_CHAR(',');
  1304. SERIAL_ECHO_F(normal.z, 7);
  1305. SERIAL_ECHOLNPGM("]");
  1306. }
  1307. matrix_3x3 rotation = matrix_3x3::create_look_at(vector_3(lsf_results.A, lsf_results.B, 1));
  1308. GRID_LOOP(i, j) {
  1309. float mx = mesh_index_to_xpos(i),
  1310. my = mesh_index_to_ypos(j),
  1311. mz = z_values[i][j];
  1312. if (DEBUGGING(LEVELING)) {
  1313. DEBUG_ECHOPAIR_F("before rotation = [", mx, 7);
  1314. DEBUG_CHAR(',');
  1315. DEBUG_ECHO_F(my, 7);
  1316. DEBUG_CHAR(',');
  1317. DEBUG_ECHO_F(mz, 7);
  1318. DEBUG_ECHOPGM("] ---> ");
  1319. DEBUG_DELAY(20);
  1320. }
  1321. apply_rotation_xyz(rotation, mx, my, mz);
  1322. if (DEBUGGING(LEVELING)) {
  1323. DEBUG_ECHOPAIR_F("after rotation = [", mx, 7);
  1324. DEBUG_CHAR(',');
  1325. DEBUG_ECHO_F(my, 7);
  1326. DEBUG_CHAR(',');
  1327. DEBUG_ECHO_F(mz, 7);
  1328. DEBUG_ECHOLNPGM("]");
  1329. DEBUG_DELAY(20);
  1330. }
  1331. z_values[i][j] = mz - lsf_results.D;
  1332. #if ENABLED(EXTENSIBLE_UI)
  1333. ExtUI::onMeshUpdate(i, j, z_values[i][j]);
  1334. #endif
  1335. }
  1336. if (DEBUGGING(LEVELING)) {
  1337. rotation.debug(PSTR("rotation matrix:\n"));
  1338. DEBUG_ECHOPAIR_F("LSF Results A=", lsf_results.A, 7);
  1339. DEBUG_ECHOPAIR_F(" B=", lsf_results.B, 7);
  1340. DEBUG_ECHOLNPAIR_F(" D=", lsf_results.D, 7);
  1341. DEBUG_DELAY(55);
  1342. DEBUG_ECHOPAIR_F("bed plane normal = [", normal.x, 7);
  1343. DEBUG_CHAR(',');
  1344. DEBUG_ECHO_F(normal.y, 7);
  1345. DEBUG_CHAR(',');
  1346. DEBUG_ECHO_F(normal.z, 7);
  1347. DEBUG_ECHOLNPGM("]");
  1348. DEBUG_EOL();
  1349. /**
  1350. * Use the code below to check the validity of the mesh tilting algorithm.
  1351. * 3-Point Mesh Tilt uses the same algorithm as grid-based tilting, but only
  1352. * three points are used in the calculation. This guarantees that each probed point
  1353. * has an exact match when get_z_correction() for that location is calculated.
  1354. * The Z error between the probed point locations and the get_z_correction()
  1355. * numbers for those locations should be 0.
  1356. */
  1357. #ifdef VALIDATE_MESH_TILT
  1358. auto d_from = []() { DEBUG_ECHOPGM("D from "); };
  1359. auto normed = [&](const xy_pos_t &pos, const float &zadd) {
  1360. return normal.x * pos.x + normal.y * pos.y + zadd;
  1361. };
  1362. auto debug_pt = [](PGM_P const pre, const xy_pos_t &pos, const float &zadd) {
  1363. d_from(); serialprintPGM(pre);
  1364. DEBUG_ECHO_F(normed(pos, zadd), 6);
  1365. DEBUG_ECHOLNPAIR_F(" Z error = ", zadd - get_z_correction(pos), 6);
  1366. };
  1367. debug_pt(PSTR("1st point: "), probe_pt[0], normal.z * z1);
  1368. debug_pt(PSTR("2nd point: "), probe_pt[1], normal.z * z2);
  1369. debug_pt(PSTR("3rd point: "), probe_pt[2], normal.z * z3);
  1370. d_from(); DEBUG_ECHOPGM("safe home with Z=");
  1371. DEBUG_ECHOLNPAIR_F("0 : ", normed(safe_homing_xy, 0), 6);
  1372. d_from(); DEBUG_ECHOPGM("safe home with Z=");
  1373. DEBUG_ECHOLNPAIR_F("mesh value ", normed(safe_homing_xy, get_z_correction(safe_homing_xy)), 6);
  1374. DEBUG_ECHOPAIR(" Z error = (", Z_SAFE_HOMING_X_POINT, ",", Z_SAFE_HOMING_Y_POINT);
  1375. DEBUG_ECHOLNPAIR_F(") = ", get_z_correction(safe_homing_xy), 6);
  1376. #endif
  1377. } // DEBUGGING(LEVELING)
  1378. }
  1379. #endif // HAS_BED_PROBE
  1380. #if ENABLED(UBL_G29_P31)
  1381. void unified_bed_leveling::smart_fill_wlsf(const float &weight_factor) {
  1382. // For each undefined mesh point, compute a distance-weighted least squares fit
  1383. // from all the originally populated mesh points, weighted toward the point
  1384. // being extrapolated so that nearby points will have greater influence on
  1385. // the point being extrapolated. Then extrapolate the mesh point from WLSF.
  1386. static_assert((GRID_MAX_POINTS_Y) <= 16, "GRID_MAX_POINTS_Y too big");
  1387. uint16_t bitmap[GRID_MAX_POINTS_X] = { 0 };
  1388. struct linear_fit_data lsf_results;
  1389. SERIAL_ECHOPGM("Extrapolating mesh...");
  1390. const float weight_scaled = weight_factor * _MAX(MESH_X_DIST, MESH_Y_DIST);
  1391. GRID_LOOP(jx, jy) if (!isnan(z_values[jx][jy])) SBI(bitmap[jx], jy);
  1392. xy_pos_t ppos;
  1393. LOOP_L_N(ix, GRID_MAX_POINTS_X) {
  1394. ppos.x = mesh_index_to_xpos(ix);
  1395. LOOP_L_N(iy, GRID_MAX_POINTS_Y) {
  1396. ppos.y = mesh_index_to_ypos(iy);
  1397. if (isnan(z_values[ix][iy])) {
  1398. // undefined mesh point at (ppos.x,ppos.y), compute weighted LSF from original valid mesh points.
  1399. incremental_LSF_reset(&lsf_results);
  1400. xy_pos_t rpos;
  1401. LOOP_L_N(jx, GRID_MAX_POINTS_X) {
  1402. rpos.x = mesh_index_to_xpos(jx);
  1403. LOOP_L_N(jy, GRID_MAX_POINTS_Y) {
  1404. if (TEST(bitmap[jx], jy)) {
  1405. rpos.y = mesh_index_to_ypos(jy);
  1406. const float rz = z_values[jx][jy],
  1407. w = 1.0f + weight_scaled / (rpos - ppos).magnitude();
  1408. incremental_WLSF(&lsf_results, rpos, rz, w);
  1409. }
  1410. }
  1411. }
  1412. if (finish_incremental_LSF(&lsf_results)) {
  1413. SERIAL_ECHOLNPGM("Insufficient data");
  1414. return;
  1415. }
  1416. const float ez = -lsf_results.D - lsf_results.A * ppos.x - lsf_results.B * ppos.y;
  1417. z_values[ix][iy] = ez;
  1418. #if ENABLED(EXTENSIBLE_UI)
  1419. ExtUI::onMeshUpdate(ix, iy, z_values[ix][iy]);
  1420. #endif
  1421. idle(); // housekeeping
  1422. }
  1423. }
  1424. }
  1425. SERIAL_ECHOLNPGM("done");
  1426. }
  1427. #endif // UBL_G29_P31
  1428. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1429. /**
  1430. * Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
  1431. * good to have the extra information. Soon... we prune this to just a few items
  1432. */
  1433. void unified_bed_leveling::g29_what_command() {
  1434. report_state();
  1435. if (storage_slot == -1)
  1436. SERIAL_ECHOPGM("No Mesh Loaded.");
  1437. else
  1438. SERIAL_ECHOPAIR("Mesh ", storage_slot, " Loaded.");
  1439. SERIAL_EOL();
  1440. serial_delay(50);
  1441. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1442. SERIAL_ECHOLNPAIR_F("Fade Height M420 Z", planner.z_fade_height, 4);
  1443. #endif
  1444. adjust_mesh_to_mean(g29_c_flag, g29_constant);
  1445. #if HAS_BED_PROBE
  1446. SERIAL_ECHOLNPAIR_F("Probe Offset M851 Z", probe.offset.z, 7);
  1447. #endif
  1448. SERIAL_ECHOLNPAIR("MESH_MIN_X " STRINGIFY(MESH_MIN_X) "=", MESH_MIN_X); serial_delay(50);
  1449. SERIAL_ECHOLNPAIR("MESH_MIN_Y " STRINGIFY(MESH_MIN_Y) "=", MESH_MIN_Y); serial_delay(50);
  1450. SERIAL_ECHOLNPAIR("MESH_MAX_X " STRINGIFY(MESH_MAX_X) "=", MESH_MAX_X); serial_delay(50);
  1451. SERIAL_ECHOLNPAIR("MESH_MAX_Y " STRINGIFY(MESH_MAX_Y) "=", MESH_MAX_Y); serial_delay(50);
  1452. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_X ", GRID_MAX_POINTS_X); serial_delay(50);
  1453. SERIAL_ECHOLNPAIR("GRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y); serial_delay(50);
  1454. SERIAL_ECHOLNPAIR("MESH_X_DIST ", MESH_X_DIST);
  1455. SERIAL_ECHOLNPAIR("MESH_Y_DIST ", MESH_Y_DIST); serial_delay(50);
  1456. SERIAL_ECHOPGM("X-Axis Mesh Points at: ");
  1457. LOOP_L_N(i, GRID_MAX_POINTS_X) {
  1458. SERIAL_ECHO_F(LOGICAL_X_POSITION(mesh_index_to_xpos(i)), 3);
  1459. SERIAL_ECHOPGM(" ");
  1460. serial_delay(25);
  1461. }
  1462. SERIAL_EOL();
  1463. SERIAL_ECHOPGM("Y-Axis Mesh Points at: ");
  1464. LOOP_L_N(i, GRID_MAX_POINTS_Y) {
  1465. SERIAL_ECHO_F(LOGICAL_Y_POSITION(mesh_index_to_ypos(i)), 3);
  1466. SERIAL_ECHOPGM(" ");
  1467. serial_delay(25);
  1468. }
  1469. SERIAL_EOL();
  1470. #if HAS_KILL
  1471. SERIAL_ECHOLNPAIR("Kill pin on :", int(KILL_PIN), " state:", READ(KILL_PIN));
  1472. #endif
  1473. SERIAL_EOL();
  1474. serial_delay(50);
  1475. #if ENABLED(UBL_DEVEL_DEBUGGING)
  1476. SERIAL_ECHOLNPAIR("ubl_state_at_invocation :", ubl_state_at_invocation, "\nubl_state_recursion_chk :", ubl_state_recursion_chk);
  1477. serial_delay(50);
  1478. SERIAL_ECHOLNPAIR("Meshes go from ", hex_address((void*)settings.meshes_start_index()), " to ", hex_address((void*)settings.meshes_end_index()));
  1479. serial_delay(50);
  1480. SERIAL_ECHOLNPAIR("sizeof(ubl) : ", (int)sizeof(ubl)); SERIAL_EOL();
  1481. SERIAL_ECHOLNPAIR("z_value[][] size: ", (int)sizeof(z_values)); SERIAL_EOL();
  1482. serial_delay(25);
  1483. SERIAL_ECHOLNPAIR("EEPROM free for UBL: ", hex_address((void*)(settings.meshes_end_index() - settings.meshes_start_index())));
  1484. serial_delay(50);
  1485. SERIAL_ECHOLNPAIR("EEPROM can hold ", settings.calc_num_meshes(), " meshes.\n");
  1486. serial_delay(25);
  1487. #endif // UBL_DEVEL_DEBUGGING
  1488. if (!sanity_check()) {
  1489. echo_name();
  1490. SERIAL_ECHOLNPGM(" sanity checks passed.");
  1491. }
  1492. }
  1493. /**
  1494. * When we are fully debugged, the EEPROM dump command will get deleted also. But
  1495. * right now, it is good to have the extra information. Soon... we prune this.
  1496. */
  1497. void unified_bed_leveling::g29_eeprom_dump() {
  1498. uint8_t cccc;
  1499. SERIAL_ECHO_MSG("EEPROM Dump:");
  1500. persistentStore.access_start();
  1501. for (uint16_t i = 0; i < persistentStore.capacity(); i += 16) {
  1502. if (!(i & 0x3)) idle();
  1503. print_hex_word(i);
  1504. SERIAL_ECHOPGM(": ");
  1505. for (uint16_t j = 0; j < 16; j++) {
  1506. persistentStore.read_data(i + j, &cccc, sizeof(uint8_t));
  1507. print_hex_byte(cccc);
  1508. SERIAL_CHAR(' ');
  1509. }
  1510. SERIAL_EOL();
  1511. }
  1512. SERIAL_EOL();
  1513. persistentStore.access_finish();
  1514. }
  1515. /**
  1516. * When we are fully debugged, this may go away. But there are some valid
  1517. * use cases for the users. So we can wait and see what to do with it.
  1518. */
  1519. void unified_bed_leveling::g29_compare_current_mesh_to_stored_mesh() {
  1520. const int16_t a = settings.calc_num_meshes();
  1521. if (!a) {
  1522. SERIAL_ECHOLNPGM("?EEPROM storage not available.");
  1523. return;
  1524. }
  1525. if (!parser.has_value() || !WITHIN(g29_storage_slot, 0, a - 1)) {
  1526. SERIAL_ECHOLNPAIR("?Invalid storage slot.\n?Use 0 to ", a - 1);
  1527. return;
  1528. }
  1529. g29_storage_slot = parser.value_int();
  1530. float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  1531. settings.load_mesh(g29_storage_slot, &tmp_z_values);
  1532. SERIAL_ECHOLNPAIR("Subtracting mesh in slot ", g29_storage_slot, " from current mesh.");
  1533. GRID_LOOP(x, y) {
  1534. z_values[x][y] -= tmp_z_values[x][y];
  1535. #if ENABLED(EXTENSIBLE_UI)
  1536. ExtUI::onMeshUpdate(x, y, z_values[x][y]);
  1537. #endif
  1538. }
  1539. }
  1540. #endif // UBL_DEVEL_DEBUGGING
  1541. #endif // AUTO_BED_LEVELING_UBL