From f37df28d1763e054adf2e399858576d71f3c1c76 Mon Sep 17 00:00:00 2001
From: Scott Lahteine <github@thinkyhead.com>
Date: Tue, 26 Feb 2019 22:25:53 -0600
Subject: [PATCH] UBL G29 T current position fix

Counterpart to #12845
---
 Marlin/src/feature/bedlevel/ubl/ubl.cpp |  7 +++++--
 Marlin/src/inc/Conditionals_post.h      | 10 ++++++++--
 2 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/Marlin/src/feature/bedlevel/ubl/ubl.cpp b/Marlin/src/feature/bedlevel/ubl/ubl.cpp
index 2dc3013ba0..349377c0c5 100644
--- a/Marlin/src/feature/bedlevel/ubl/ubl.cpp
+++ b/Marlin/src/feature/bedlevel/ubl/ubl.cpp
@@ -198,8 +198,11 @@
       serialprintPGM(csv ? PSTR("CSV:\n") : PSTR("LCD:\n"));
     }
 
-    const float current_xi = get_cell_index_x(current_position[X_AXIS] + (MESH_X_DIST) / 2.0),
-                current_yi = get_cell_index_y(current_position[Y_AXIS] + (MESH_Y_DIST) / 2.0);
+    // Add XY_PROBE_OFFSET_FROM_EXTRUDER because probe_pt() subtracts these when
+    // moving to the xy position to be measured. This ensures better agreement between
+    // the current Z position after G28 and the mesh values.
+    const float current_xi = find_closest_x_index(current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER),
+                current_yi = find_closest_y_index(current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER);
 
     if (!lcd) SERIAL_EOL();
     for (int8_t j = GRID_MAX_POINTS_Y - 1; j >= 0; j--) {
diff --git a/Marlin/src/inc/Conditionals_post.h b/Marlin/src/inc/Conditionals_post.h
index b91104b77a..7f389c3c57 100644
--- a/Marlin/src/inc/Conditionals_post.h
+++ b/Marlin/src/inc/Conditionals_post.h
@@ -203,11 +203,17 @@
  * Safe Homing Options
  */
 #if ENABLED(Z_SAFE_HOMING)
+  #if ENABLED(AUTO_BED_LEVELING_UBL)
+    // Home close to center so grid points have z heights very close to 0
+    #define _SAFE_POINT(A) (((GRID_MAX_POINTS_##A) / 2) * (A##_BED_SIZE - 2 * (MESH_INSET)) / (GRID_MAX_POINTS_##A - 1) + MESH_INSET)
+  #else
+    #define _SAFE_POINT(A) A##_CENTER
+  #endif
   #ifndef Z_SAFE_HOMING_X_POINT
-    #define Z_SAFE_HOMING_X_POINT X_CENTER
+    #define Z_SAFE_HOMING_X_POINT _SAFE_POINT(X)
   #endif
   #ifndef Z_SAFE_HOMING_Y_POINT
-    #define Z_SAFE_HOMING_Y_POINT Y_CENTER
+    #define Z_SAFE_HOMING_Y_POINT _SAFE_POINT(Y)
   #endif
   #define X_TILT_FULCRUM Z_SAFE_HOMING_X_POINT
   #define Y_TILT_FULCRUM Z_SAFE_HOMING_Y_POINT