Modern Apps git

← Modern-Apps.git

maps: globe mode fixes + map UI fixes

Commit
d5ab861755783f83d610daa6be934d91a9b04dcb
Author
vayun-mathur <[email protected]>
When
2026-10-13 23:14 UTC (1 month ago)
Parents
d0a261b
Globe rendering (library/map rust):
- globe_tile_to_clip carries camera centre lon/lat in m[12]/m[13] so
  globe vertex shaders share logic with the flat path (push block is
  at the 128-byte limit); y-sign matches flat matrix + CPU placement.
- globe anchor pick path: far-side markers cull to a miss, matching
  the draw; globe_screen_quad helper shared from placement.
- placement_globe + placement_refresh modules (label resolve, pick
  snapshot split); ResidentTile pub(crate) for the split.
- globe shader variants (fill/line/road_surface/symbol) track the
  shared limb-discard logic; camera globe tests + tile-select tests.

Maps UI:
- globe toggle zooms out to GLOBE_REVEAL_ZOOM when enabling at street
  zoom (sphere only reads past the detail threshold).
- DeparturesSheet loading/empty states bounded to 160dp (sheet no
  longer opens fullscreen while fetching).
- SearchSheet rides above the keyboard (imePadding); manifest
  adjustResize for the same.
- MainActivity persistedLastFix extraction (no behaviour change);
  FrameworkLocationManager usableLastKnown extraction (provider off /
  missing / (0,0) sentinel reads as no fix).
- transit_part9 fixture: drop shared_* header fields (other agent's
  in-progress header work removed them).
- maps graph: part2b blocked-section accessors + part4b
  single-archive loader (structural-stack device side).

Diff

library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.ktindex f766b2b196..fec9dfc812 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt@@ -12,10 +12,16 @@ import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size+import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.DpRect+import androidx.compose.ui.unit.dp import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first+import kotlin.math.atan2+import kotlin.math.cos import kotlin.math.log2+import kotlin.math.sin+import kotlin.math.sqrt  /**  * Where the camera is, and which way is up.@@ -173,6 +179,10 @@ class CameraState(initial: CameraPosition = CameraPosition()) {     /**      * Animated zoom by [deltaZoom] levels, keeping the geographic point under      * [anchorDp] fixed for the whole flight (double-tap to zoom).+     *+     * On an active globe the anchor is the sphere point under the finger+     * (limb-clamped by the projection), so the flight keeps that ground fixed+     * rather than the flat point the Mercator branch would name.      */     internal suspend fun animateZoomBy(         deltaZoom: Double,@@ -195,7 +205,8 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      * the vertical distance dragged since the gesture began — down is positive      * and zooms in, up zooms out — and [from] is the camera as of that start,      * so the zoom is absolute rather than accumulated frame by frame. The-     * geographic point under [anchorDp] stays fixed.+     * geographic point under [anchorDp] stays fixed (sphere-anchored on an+     * active globe, like [animateZoomBy]).      */     internal fun onQuickZoom(         from: CameraPosition,@@ -226,6 +237,11 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      * The camera bearing is clockwise-from-north, so it is subtracted. Ignored unless      * [rotateEnabled]; pan and zoom never reset the bearing either way (the position is      * `copy`ied, not rebuilt).+     *+     * On an active globe (flag on and zoomed out past the detail threshold) pan+     * rotates the sphere through the same basis the renderer draws+     * ([globePanBy]), and the twist/tilt gestures are ignored: the globe path+     * is north-up level, and tilting a planet is a separate workstream.      */     internal fun onGesture(         centroidDp: Offset,@@ -243,6 +259,25 @@ class CameraState(initial: CameraPosition = CameraPosition()) {         val effectiveMinZoom = if (globeEnabled) minZoom else maxOf(minZoom, fillZoom(vp))         var zoom = position.zoom +        // Globe: rotate the sphere under the finger; zoom stays Mercator-anchored+        // so the threshold crossing is continuous.+        if (globeEnabled && position.zoom < GLOBE_DETAIL_ZOOM) {+            var center = position.target+            if (scrollEnabled && (panDp.x != 0f || panDp.y != 0f)) {+                center = globePanBy(center, panDp, vp, position.zoom)+            }+            if (zoomEnabled && zoomChange != 1f && zoomChange > 0f) {+                val newZoom = (zoom + log2(zoomChange.toDouble())).coerceIn(effectiveMinZoom, maxZoom)+                if (newZoom != zoom) {+                    val zoomed = anchoredZoom(position.copy(target = center), newZoom, centroidDp, vp)+                    center = zoomed.target+                    zoom = zoomed.zoom+                }+            }+            position = position.copy(target = center, zoom = zoom, bearing = 0.0, pitch = 0.0)+            return+        }+         // Pan: dragging content one way shifts the world the same way, so the         // center moves opposite to the pan. The gesture arrives in screen space but the         // Mercator math below is in world space, so inverse-rotate it by the bearing first@@ -282,9 +317,12 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      * Applies a two-finger twist rotation. [deltaDeg] is clockwise-from-north positive      * (already converted from the gesture detector's convention by [onGesture]); it wraps      * 0–360 rather than clamping, so spinning past north continues through it.+     *+     * Ignored on an active globe, which is north-up level by construction.      */     internal fun onRotate(deltaDeg: Double) {         if (deltaDeg == 0.0) return+        if (globeEnabled && position.zoom < GLOBE_DETAIL_ZOOM) return         position = position.copy(bearing = wrapBearing(position.bearing + deltaDeg))     } @@ -292,13 +330,48 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      * Applies a two-finger vertical-drag tilt. [deltaDp] is the vertical movement since the last      * event (Compose's y, down positive); dragging **up** tilts into the map (raises the pitch),      * matching Google Maps. Clamped to `0.0..`[MAX_PITCH]; nothing else about the camera moves.+     *+     * Ignored on an active globe, whose shaders draw level: tilting a planet is+     * a separate workstream.      */     internal fun onTilt(deltaDp: Float) {+        if (globeEnabled && position.zoom < GLOBE_DETAIL_ZOOM) return         val next = (position.pitch - deltaDp * PITCH_DEG_PER_DP).coerceIn(0.0, MAX_PITCH)         if (next != position.pitch) position = position.copy(pitch = next)     }++    /**+     * Whether the globe path is currently drawing the sphere: the toggle on and+     * zoomed out past the detail threshold, mirroring the native+     * `globe_active` and [Projection]'s globe branch.+     */+    internal val isGlobeActive: Boolean+        get() = globeEnabled && position.zoom < GLOBE_DETAIL_ZOOM } +/**+ * Rotate the globe centre by a screen-space drag [panDp] (Dp, down-positive),+ * as seen through a viewport [vp]: dragging content right moves the planet+ * right, so the centre moves the opposite way along its own parallel/meridian.+ *+ * The globe radius in Dp is half the world width at [zoom] (mirroring+ * `globe_radius` on the native side), so one Dp is `180 / r` degrees of+ * great-circle at the centre. Longitude wraps; latitude clamps to the Mercator+ * bound the flat path honours. Unused [vp]: kept so the signature matches the+ * flat pan it replaces at the call site.+ */+internal fun globePanBy(center: GeoPoint, panDp: Offset, vp: Size, zoom: Double): GeoPoint {+    val r = Mercator.worldSize(zoom) / 2.0+    if (r <= 0.0) return center+    val degPerDp = 180.0 / r+    val lon = wrapLongitude(center.longitude - panDp.x * degPerDp)+    val lat = (center.latitude + panDp.y * degPerDp).coerceIn(-MAX_GLOBE_LAT, MAX_GLOBE_LAT)+    return GeoPoint(lon, lat)+}++/** Latitude clamp for globe panning: the Mercator bound the flat path honours. */+private const val MAX_GLOBE_LAT = 85.05112878+ /** Largest tilt the renderer supports, in degrees. Mirrors the native `PITCH_MAX_DEG` cap. */ const val MAX_PITCH: Double = 65.0 @@ -329,12 +402,51 @@ private const val ANGLE_WRAP_OFFSET_DEG = 540.0 private const val QUICK_ZOOM_LEVELS_PER_VIEWPORT = 4.0  /** [from] re-centered so the geo point under [anchorDp] is still there at [newZoom]. */-private fun anchoredZoom(+private fun CameraState.anchoredZoom(     from: CameraPosition,     newZoom: Double,     anchorDp: Offset,     vp: Size, ): CameraPosition {+    // On an active globe the zoom pivot is the sphere point under the finger,+    // which the projection limb-clamps: zooming keeps that ground fixed, and+    // the centre tracks it so the flight reads as diving toward the finger.+    // Bearing/pitch are level on the globe path, so no inverse-rotation.+    if (globeEnabled && from.zoom < GLOBE_DETAIL_ZOOM) {+        val globeNow = Projection(+            center = from.target,+            zoom = from.zoom,+            widthDp = vp.width,+            heightDp = vp.height,+            globe = true,+        )+        val geo = globeNow.positionFromScreenLocation(+            DpOffset(anchorDp.x.dp, anchorDp.y.dp),+        )+        val globeNext = Projection(+            center = geo,+            zoom = newZoom,+            widthDp = vp.width,+            heightDp = vp.height,+            globe = newZoom < GLOBE_DETAIL_ZOOM,+        )+        // Keep the picked ground under the finger: re-derive the centre whose+        // projection of `geo` at the new zoom lands back on the anchor.+        val moved = globeNext.screenLocationFromPosition(geo)+        val want = DpOffset(anchorDp.x.dp, anchorDp.y.dp)+        // Screen delta (Dp) back to a centre shift: invert through the globe+        // radius scale rather than re-projecting.+        val r = Mercator.worldSize(newZoom) / 2.0+        val dLon = (want.x.value - moved.x.value) / r * 180.0+        val dLat = -(want.y.value - moved.y.value) / r * 180.0+        return from.copy(+            target = GeoPoint(+                wrapLongitude(geo.longitude + dLon),+                (geo.latitude + dLat).coerceIn(-MAX_GLOBE_LAT, MAX_GLOBE_LAT),+            ),+            zoom = newZoom,+        )+    }     // The anchor is a screen point; its offset from the viewport centre is what the     // Mercator math consumes, so inverse-rotate that offset by the bearing first (same     // step as the pan in `onGesture`). At zero bearing this is the identity.
library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.ktindex 6ad36b975a..e3c644caca 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt@@ -93,11 +93,14 @@ internal fun Modifier.mapGestures(             detectTransformGestures { centroid, pan, zoom, rotation ->                 if (gestures.isTransformDisabled) return@detectTransformGestures                 zoomAnim.value?.cancel()+                // The globe is north-up level: the twist gesture has no bearing+                // to drive there (see `CameraState.onGesture`), so drop the+                // rotation rather than spinning a camera the globe never draws.                 cameraState.onGesture(                     centroidDp = toDp(centroid),                     panDp = toDp(pan),                     zoomChange = zoom,-                    rotationDeg = rotation,+                    rotationDeg = if (cameraState.isGlobeActive) 0f else rotation,                     minZoom = zoomRange.start.toDouble(),                     maxZoom = zoomRange.endInclusive.toDouble(),                     scrollEnabled = gestures.isScrollEnabled,@@ -114,7 +117,12 @@ internal fun Modifier.mapGestures(             if (gestures.isTiltDisabled) {                 return@pointerInput             }-            detectVerticalTiltGestures { dyPx -> cameraState.onTilt(dyPx / density) }+            // Tilt is a flat-map gesture: the globe path is level by construction+            // (its shaders ignore pitch), so a two-finger drag there must not+            // tilt a camera the globe never draws tilted.+            detectVerticalTiltGestures { dyPx ->+                if (!cameraState.isGlobeActive) cameraState.onTilt(dyPx / density)+            }         }         // Declared after the transform detector so it sees pointer events first and         // can consume a quick-zoom drag out from under it.
library/map/src/main/java/com/vayunmathur/library/map/Projection.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt b/library/map/src/main/java/com/vayunmathur/library/map/Projection.ktindex a129283aeb..9b9c30bce3 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt@@ -185,6 +185,9 @@ class Projection internal constructor(     private fun globeScreenLocationFromPosition(position: GeoPoint): DpOffset {         val (x, y, z) = globeProject(position.longitude, position.latitude)         if (z < 0.0) return DpOffset(OFF_SCREEN_DP.dp, OFF_SCREEN_DP.dp)+        // Screen y is down-positive from the top-left; north (+y in the sphere+        // basis) renders up, matching `globe_anchor_to_screen` on the native+        // side and every globe vertex shader (`halfH - y`).         return DpOffset((halfW + x).toFloat().dp, (halfH - y).toFloat().dp)     } 
library/map/src/main/rust/shaders/fill_globe.vert
diff --git a/library/map/src/main/rust/shaders/fill_globe.vert b/library/map/src/main/rust/shaders/fill_globe.vertindex 33a4f14c58..bc5e259200 100644--- a/library/map/src/main/rust/shaders/fill_globe.vert+++ b/library/map/src/main/rust/shaders/fill_globe.vert@@ -4,17 +4,24 @@ // // Same inputs as `fill.vert` (position-only tile-local 0..1 in `inPosition.xy`), // but the matrix is the globe matrix from `Camera::globe_tile_to_clip`, not the-// flat tile matrix: its linear 2x2 carries the globe radius (Dp), and its third-// row carries the tile's normalised-world origin + span (ox, oy, span). The-// vertex reconstructs its lon/lat from those, projects through `globe_point`-// (mirroring the CPU), and emits clip + a real depth (near-side nearer).+// flat tile matrix: its linear 2x2 carries the globe radius (Dp), its third+// row carries the tile's normalised-world origin + span (ox, oy, span), and its+// translation column carries the camera centre lon/lat (degrees, m[12]/m[13])+// for the sphere basis. The vertex reconstructs its lon/lat from those,+// projects through the CPU-matching `globe_point` basis, and emits clip + a+// real depth (near-side nearer). //-// Vertices on the far side (z < 0) are pulled behind the near plane (w forced-// negative-side) so the triangle clips away; straddling triangles clip at the-// limb per-fragment via the varying. Depth is `1 - z` mapped into [0, 1): the-// sub-sphere centre is deepest, the limb is nearest — coarser ancestor tiles-// drawn first lose the depth test to finer descendants drawn over them, which-// is the same coarsest-first order the flat loop relies on.+// `misc`/`morph` keep their flat meaning (tile px in `misc.x`, edge AA in+// `misc.y`, tile fade in `morph.x`, draped-z scale in `morph.z`; `morph.y`+// keeps the dash phase speed the line fragment reads) — the limb discard is+// the only fragment difference from `fill.frag`, so opacity, fade and coverage+// match the flat map exactly. Vertices on the far side (z < 0) are pulled+// are pulled behind the near plane so the triangle clips away; straddling+// triangles clip at the limb per-fragment via the varying. Depth is `1 - z`+// mapped into [0, 1): the sub-sphere centre is deepest, the limb is nearest —+// coarser ancestor tiles drawn first lose the depth test to finer descendants+// drawn over them, which is the same coarsest-first order the flat loop relies+// on. Screen y follows the CPU anchor convention (`halfH - y`, north up).  layout(location = 0) in vec3 inPosition; @@ -32,6 +39,7 @@ const float PI = 3.141592653589793;  // `tileToClip[2]` third row: (ox, oy, span) packed by `globe_tile_to_clip`. // Column-major: m[2] = row0-col2, m[6] = row1-col2, m[10] = row2-col2.+// Translation column (m[12]/m[13]): centre lon/lat in degrees.  void main() {     float ox = push.tileToClip[2][0];@@ -43,15 +51,11 @@ void main() {     // Normalised world -> lon/lat (Web Mercator inverse, y down).     float lon = wx * 360.0 - 180.0;     float n = PI - 2.0 * PI * wy;-    // atan(sinh(n)): sinh can overflow for extreme wy; wy is in [0,1] so n in-    // [-PI, PI] and sinh is bounded — safe.+    // atan(sinh(n)): wy is in [0,1] so n in [-PI, PI] and sinh is bounded.     float lat = atan((exp(n) - exp(-n)) * 0.5) * 180.0 / PI;-    // Centre-facing basis is baked CPU-side: the globe matrix's translation is-    // zero and its 2x2 is (kx*r, ky*r), so we reconstruct the unit-sphere point-    // relative to the centre here. The centre lon/lat ride in `misc.xy`-    // (degrees) — pushed per draw by the globe record path.-    float cLon = push.misc.x;-    float cLat = push.misc.y;+    // Sphere basis from the matrix translation column (CPU-side centre).+    float cLon = push.tileToClip[3][0];+    float cLat = push.tileToClip[3][1];     float latR = radians(lat);     float dLon = radians(lon - cLon);     float cLatR = radians(cLat);@@ -61,33 +65,28 @@ void main() {     float sy = sin(cLatR);     float cy = cos(cLatR);     float x = x1;-    float y = y1 * sy - z1 * cy;-    float z = y1 * cy + z1 * sy;-    // Globe radius in Dp is recovered from the matrix scale: m[0] = kx * r with-    // kx = 2/widthDp — but widthDp is not pushed. Instead the record path pushes-    // r (Dp) in `morph.z` (unused by the fill path otherwise).+    float y = y1 * cy - z1 * sy;+    float z = y1 * sy + z1 * cy;+    // Globe radius (Dp) from the matrix scale: m[0] = kx * r with kx = 2/width;+    // half-viewport (Dp) rides in `morph.xy` on the globe branch exactly as the+    // record path pushes it (see the globe branch in `record.rs`).+    float hw = push.morph.x;+    float hh = push.morph.y;     float r = push.morph.z;-    float sx = x * r;-    float sy2 = y * r;-    // Flat clip through the matrix 2x2 + viewport centre: clip = kx * (sx) - 0-    // with the matrix translation column zeroed, plus centre offset. The record-    // path bakes (kx, ky) into m[0]/m[5] and pushes half-viewport (Dp) in-    // `morph.xy`, so: clip = m * (sx, sy) + (kx*hw - 1, ky*hh - 1).     float kx = push.tileToClip[0][0] / max(r, 1e-6);     float ky = push.tileToClip[1][1] / max(r, 1e-6);-    float hw = push.morph.x;-    float hh = push.morph.y;+    // Screen point in Dp: centre + sphere offset, y-up like the CPU anchor math+    // (`halfH - y`), so north renders up.+    float sx = x * r;+    float sy2 = y * r;     float cx = kx * sx + (kx * hw - 1.0);-    float cyy = ky * sy2 + (ky * hh - 1.0);-    // Vulkan clip y is down-positive like Mercator, but NDC y-up convention in-    // the flat matrices negates through ky sign — keep the same sign here.-    // Depth: limb (z=0) -> 0, sub-camera point (z=1) -> ~1. Reversed so nearer-    // (larger z) wins LESS: depth = 1 - z mapped in.+    float cyy = -(ky * sy2) + (ky * hh - 1.0);+    // Depth: limb (z=0) -> 0, sub-camera point (z=1) -> ~1. Nearer (larger z)+    // wins LESS: depth = 1 - z mapped in.     float depth = clamp(1.0 - z, 0.0, 1.0);     outZ = z;     if (z < 0.0) {-        // Far side: emit behind the camera so the triangle clips. w negative-        // flips; use a degenerate far-depth point instead.+        // Far side: emit at far depth so the triangle clips away.         gl_Position = vec4(cx, cyy, 1.0, 1.0);     } else {         gl_Position = vec4(cx, cyy, depth, 1.0);
library/map/src/main/rust/shaders/line_globe.vert
diff --git a/library/map/src/main/rust/shaders/line_globe.vert b/library/map/src/main/rust/shaders/line_globe.vertindex 81a3db6e41..ca1557ee30 100644--- a/library/map/src/main/rust/shaders/line_globe.vert+++ b/library/map/src/main/rust/shaders/line_globe.vert@@ -9,9 +9,15 @@ // height (`inZ`) is ignored on the globe: relief at globe zoom is sub-pixel. // // Push layout: identical block to the flat path. `tileToClip` is the globe-// matrix (2x2 = globe scale, third row = tile ox/oy/span), `misc.xy` is the-// camera centre (degrees), `morph.z` the globe radius (Dp), `morph.xy` the-// half-viewport (Dp). `line`/`misc.zw` keep their flat meaning.+// matrix (2x2 = globe scale, third row = tile ox/oy/span, translation column =+// centre lon/lat degrees), `misc.xyzw` keep their flat meaning (tile px,+// edge AA, lateral shift, clock), and `morph` keeps its flat meaning too+// (fade in x, dash phase speed in y, draped-z scale in z). The half-viewport+// (Dp) rides in `morph.xy` on the globe branch exactly as `record.rs` pushes+// it — note the shaders read the radius from `morph.z`, not from `.xy`.+// edge AA, lateral shift, clock), and `morph` keeps its flat meaning too+// (fade in x, draped-z scale in z). The half-viewport (Dp) rides in+// `morph.xy` on the globe branch exactly as `record.rs` pushes it. layout(location = 0) in vec2 inPosition; layout(location = 1) in vec2 inNormal; layout(location = 2) in vec2 inExtrude;@@ -51,8 +57,9 @@ void main() {     float lon = wx * 360.0 - 180.0;     float n = PI - 2.0 * PI * wy;     float lat = atan((exp(n) - exp(-n)) * 0.5) * 180.0 / PI;-    float cLon = push.misc.x;-    float cLat = push.misc.y;+    // Sphere basis from the matrix translation column (CPU-side centre).+    float cLon = push.tileToClip[3][0];+    float cLat = push.tileToClip[3][1];     float latR = radians(lat);     float dLon = radians(lon - cLon);     float cLatR = radians(cLat);@@ -62,15 +69,16 @@ void main() {     float sy = sin(cLatR);     float cy = cos(cLatR);     float x = x1;-    float y = y1 * sy - z1 * cy;-    float z = y1 * cy + z1 * sy;+    float y = y1 * cy - z1 * sy;+    float z = y1 * sy + z1 * cy;     float r = push.morph.z;     float kx = push.tileToClip[0][0] / max(r, 1e-6);     float ky = push.tileToClip[1][1] / max(r, 1e-6);     float hw = push.morph.x;     float hh = push.morph.y;+    // Screen point y-up like the CPU anchor math (`halfH - y`): north renders up.     float cx = kx * (x * r) + (kx * hw - 1.0);-    float cyy = ky * (y * r) + (ky * hh - 1.0);+    float cyy = -(ky * (y * r)) + (ky * hh - 1.0);     float depth = clamp(1.0 - z, 0.0, 1.0);     outZ = z;     outDistancePx = inDistance * tilePx;
library/map/src/main/rust/shaders/road_surface_globe.vert
diff --git a/library/map/src/main/rust/shaders/road_surface_globe.vert b/library/map/src/main/rust/shaders/road_surface_globe.vertindex f4b7208b23..080f29882b 100644--- a/library/map/src/main/rust/shaders/road_surface_globe.vert+++ b/library/map/src/main/rust/shaders/road_surface_globe.vert@@ -5,7 +5,11 @@ // carriageway width/offsets are screen measurements resolved in tile-local // space exactly as the flat ribbon does, and only the final transform bends // onto the sphere. Markings readouts (`outT`, `outDistancePx`) pass through-// untouched — `road_surface.frag` is shared verbatim.+// untouched — `road_surface.frag` logic is shared with the limb discard added+// (see `road_surface_globe.frag`). `misc`/`morph` keep their flat meaning:+// tile px in `misc.x`, edge AA in `misc.y`, yellow-centre flag in `misc.z`,+// fade in `morph.x`, draped-z scale in `morph.z`; half-viewport (Dp) rides in+// `morph.xy` on the globe branch (radius in `morph.z`, not `.xy`). layout(location = 0) in vec2 inPosition; layout(location = 1) in vec2 inNormal; layout(location = 2) in float inT;@@ -40,8 +44,9 @@ void main() {     float lon = wx * 360.0 - 180.0;     float n = PI - 2.0 * PI * wy;     float lat = atan((exp(n) - exp(-n)) * 0.5) * 180.0 / PI;-    float cLon = push.misc.x;-    float cLat = push.misc.y;+    // Sphere basis from the matrix translation column (CPU-side centre).+    float cLon = push.tileToClip[3][0];+    float cLat = push.tileToClip[3][1];     float latR = radians(lat);     float dLon = radians(lon - cLon);     float cLatR = radians(cLat);@@ -51,15 +56,16 @@ void main() {     float sy = sin(cLatR);     float cy = cos(cLatR);     float x = x1;-    float y = y1 * sy - z1 * cy;-    float z = y1 * cy + z1 * sy;+    float y = y1 * cy - z1 * sy;+    float z = y1 * sy + z1 * cy;     float r = push.morph.z;     float kx = push.tileToClip[0][0] / max(r, 1e-6);     float ky = push.tileToClip[1][1] / max(r, 1e-6);     float hw = push.morph.x;     float hh = push.morph.y;+    // Screen point y-up like the CPU anchor math (`halfH - y`): north renders up.     float cx = kx * (x * r) + (kx * hw - 1.0);-    float cyy = ky * (y * r) + (ky * hh - 1.0);+    float cyy = -(ky * (y * r)) + (ky * hh - 1.0);     float depth = clamp(1.0 - z, 0.0, 1.0);     outT = inT;     outZ = z;
library/map/src/main/rust/shaders/symbol_globe.vert
diff --git a/library/map/src/main/rust/shaders/symbol_globe.vert b/library/map/src/main/rust/shaders/symbol_globe.vertindex 4bf856b09b..32a44fc5ac 100644--- a/library/map/src/main/rust/shaders/symbol_globe.vert+++ b/library/map/src/main/rust/shaders/symbol_globe.vert@@ -3,12 +3,16 @@ // Globe symbol vertex: label quads bent onto the sphere at their anchor. // // Same inputs as `symbol_billboard.vert` (tile-local position + uv + ground-// anchor). The globe record path sets the billboard flag off and pushes the-// globe matrix + centre + radius in the same slots the billboard path uses, so-// this shader bends the anchor through `globe_point` and hangs the glyph quad-// off it at its screen offset — upright labels on a curved planet. Curved-// (line) labels carry each vertex as its own anchor, so they drape along the-// road on the sphere exactly as they lie flat on the plane.+// anchor). The globe record path pushes the globe matrix (translation column =+// centre lon/lat, third row = tile ox/oy/span) with `misc`/`morph` keeping+// their flat meaning: `misc.x` is the tile's world-px span (Dp), `misc.yzw`+// the halo rgb exactly as on the flat path, `line` the text size/halo/sdf/+// billboard flag, and `morph` the globe half-viewport + radius (see above).+// This shader bends the anchor through the CPU-matching `globe_point` basis+// and hangs the glyph quad off it at its screen offset — upright labels on a+// curved planet, with halo intact. Curved (line) labels carry each vertex as+// sphere exactly as they lie flat on the plane. Screen y follows the CPU+// anchor convention (`halfH - y`, north up). layout(location = 0) in vec2 inPosition; layout(location = 1) in vec2 inUv; layout(location = 2) in vec2 inAnchor;@@ -34,7 +38,7 @@ vec3 globeOf(float lon, float lat, float cLon, float cLat) {     float y1 = sin(latR);     float sy = sin(cLatR);     float cy = cos(cLatR);-    return vec3(x1, y1 * sy - z1 * cy, y1 * cy + z1 * sy);+    return vec3(x1, y1 * cy - z1 * sy, y1 * sy + z1 * cy); }  void main() {@@ -48,8 +52,9 @@ void main() {     float alon = awx * 360.0 - 180.0;     float an = PI - 2.0 * PI * awy;     float alat = atan((exp(an) - exp(-an)) * 0.5) * 180.0 / PI;-    float cLon = push.misc.x;-    float cLat = push.misc.y;+    // Sphere basis from the matrix translation column (CPU-side centre).+    float cLon = push.tileToClip[3][0];+    float cLat = push.tileToClip[3][1];     vec3 a = globeOf(alon, alat, cLon, cLat);     float r = push.morph.z;     float kx = push.tileToClip[0][0] / max(r, 1e-6);@@ -57,18 +62,25 @@ void main() {     float hw = push.morph.x;     float hh = push.morph.y;     // Screen offset of this corner from its anchor: tile-local delta scaled by-    // the matrix's flat 2x2 (device px per tile unit is not pushed on this path;-    // reconstruct from the globe scale: tile Dp span = span * worldSize, and the-    // matrix maps Dp -> clip, so off = delta_tile * span * worldSize * k).-    float worldSize = 2.0 * r;-    vec2 off = (inPosition - inAnchor) * span * worldSize;+    // the matrix's flat 2x2. The flat linear part maps tile units to clip; on+    // the globe branch that 2x2 is the globe scale (kx*r per tile-span unit),+    // so reuse it directly: off_clip = flat2x2 * delta_tile.+    float m00 = push.tileToClip[0][0];+    float m01 = push.tileToClip[0][1];+    float m10 = push.tileToClip[1][0];+    float m11 = push.tileToClip[1][1];+    // The 2x2 maps normalised-world delta (span-scaled tile delta) to clip:+    // delta_world = delta_tile * span, clip = 2x2 * delta_world. With the globe+    // matrix the 2x2 already includes r, so scale by span only.+    vec2 dTile = (inPosition - inAnchor) * span;+    vec2 off = vec2(m00 * dTile.x + m10 * dTile.y, m01 * dTile.x + m11 * dTile.y);     float ax = kx * (a.x * r) + (kx * hw - 1.0);-    float ay = ky * (a.y * r) + (ky * hh - 1.0);+    float ay = -(ky * (a.y * r)) + (ky * hh - 1.0);     float depth = clamp(1.0 - a.z, 0.0, 1.0);     outZ = a.z;     if (a.z < 0.0) {         gl_Position = vec4(ax, ay, 1.0, 1.0);     } else {-        gl_Position = vec4(ax + kx * off.x, ay + ky * off.y, depth, 1.0);+        gl_Position = vec4(ax + off.x, ay - off.y, depth, 1.0);     } }
library/map/src/main/rust/src/camera_globe.rs
diff --git a/library/map/src/main/rust/src/camera_globe.rs b/library/map/src/main/rust/src/camera_globe.rsindex e02e664f6d..e080953ec6 100644--- a/library/map/src/main/rust/src/camera_globe.rs+++ b/library/map/src/main/rust/src/camera_globe.rs@@ -13,6 +13,21 @@ impl Camera {     /// centred on the viewport, and the tile's normalised-world origin + span in     /// the third row (m[2], m[6], m[10]), which the globe shaders read to     /// reconstruct the lon/lat per vertex.+    ///+    /// The translation column carries the camera centre lon/lat in m[12]/m[13]+    /// (degrees) — the sphere basis every globe vertex shader needs. It rides+    /// here rather than in the push block because the block is exactly at the+    /// guaranteed 128-byte limit: this keeps `misc`/`morph` meaning what the+    /// flat path means (tile px, edge AA, fade, span scale, dash speed), so the+    /// globe fragment shaders stay shared logic with the limb discard added.+    /// The flat path never takes this branch, so its matrices are unchanged.+    ///+    /// Y-sign: the projection convention is that y-displacement scales by +ky,+    /// matching the flat matrix and the CPU-side `globe_anchor_to_screen` / the+    /// Kotlin `Projection` (north is +y in Dp, clip y is y-down so +sy maps to+    /// negative clip through `halfH - y`). The shaders reconstruct flat clip+    /// through this same matrix, so a label or POI placed CPU-side lands where+    /// the basemap under it drew.     pub fn globe_tile_to_clip(&self, z: u8, x: u32, y: u32) -> [f32; 16] {         let r = crate::camera::globe_radius(self.zoom);         let kx = 2.0 / self.width_dp as f64;@@ -36,8 +51,8 @@ impl Camera {             0.0,             span as f32,             0.0, //-            0.0,-            0.0,+            self.center_lon as f32,+            self.center_lat as f32,             0.0,             1.0,         ]
library/map/src/main/rust/src/camera_globe_tests.rs
diff --git a/library/map/src/main/rust/src/camera_globe_tests.rs b/library/map/src/main/rust/src/camera_globe_tests.rsindex 30921c5bbb..aa4702421b 100644--- a/library/map/src/main/rust/src/camera_globe_tests.rs+++ b/library/map/src/main/rust/src/camera_globe_tests.rs@@ -148,4 +148,36 @@ mod tests {         assert_eq!(m[1], 0.0, "no shear into y");         assert_eq!(m[4], 0.0, "no shear into x");     }++    #[test]+    fn the_globe_matrix_carries_centre_and_tile_shape() {+        // The push-constant contract the globe vertex shaders read: the+        // translation column (m[12]/m[13], column-major) carries the camera+        // centre (degrees) for the sphere basis, the third row (m[2]/m[6]/+        // m[10]) carries the tile's normalised origin + span, and the 2x2+        // carries the globe scale centred on the viewport.+        let c = globe_camera(-122.4194, 37.7749, 2.0);+        let m = c.globe_tile_to_clip(2, 0, 1);+        assert!((m[12] as f64 - -122.4194).abs() < 1e-4, "m[12] centre lon, got {}", m[12]);+        assert!((m[13] as f64 - 37.7749).abs() < 1e-4, "m[13] centre lat, got {}", m[13]);+        let n = 2f64.powi(2);+        assert_eq!(m[2], 0.0f32, "ox of tile x=0");+        assert!((m[6] - (1.0 / n) as f32).abs() < 1e-9, "oy of tile y=1");+        assert!((m[10] - (1.0 / n) as f32).abs() < 1e-9, "span at z2");+        let r = globe_radius(2.0);+        let kx = 2.0 / 512.0;+        assert!((m[0] as f64 - kx * r).abs() < 1e-3, "2x2 carries the globe scale");+    }++    #[test]+    fn the_globe_centre_projects_to_viewport_centre() {+        // The camera centre faces the viewer exactly: its screen anchor is the+        // viewport centre (Dp), which the matrix then maps to clip (0, 0).+        let c = globe_camera(-122.4194, 37.7749, 2.0);+        let (sx_dp, sy_dp) = c+            .globe_anchor_to_screen(-122.4194, 37.7749)+            .expect("centre must project");+        assert!((sx_dp - 256.0).abs() < 1e-9, "sx {sx_dp}");+        assert!((sy_dp - 256.0).abs() < 1e-9, "sy {sy_dp}");+    } }
library/map/src/main/rust/src/tile/placement.rs
diff --git a/library/map/src/main/rust/src/tile/placement.rs b/library/map/src/main/rust/src/tile/placement.rsindex 78783cd7ef..9ee056c983 100644--- a/library/map/src/main/rust/src/tile/placement.rs+++ b/library/map/src/main/rust/src/tile/placement.rs@@ -398,3 +398,4 @@ include!("placement_grid.rs"); include!("placement_part1.rs"); include!("placement_part2.rs"); include!("placement_part3.rs");+include!("placement_globe.rs");
library/map/src/main/rust/src/tile/placement_globe.rs
diff --git a/library/map/src/main/rust/src/tile/placement_globe.rs b/library/map/src/main/rust/src/tile/placement_globe.rsnew file mode 100644index 0000000000..0d3a67add7--- /dev/null+++ b/library/map/src/main/rust/src/tile/placement_globe.rs@@ -0,0 +1,142 @@+/// Globe-aware screen projection for label placement: lon/lat through the+/// orthographic sphere instead of the flat tile matrix.+///+/// Split from `placement.rs` (file-length limit). The flat `project_to_screen`+/// feeds a tile-local point through the tile's clip matrix; on the globe the+/// matrix bends (a 4x4 cannot bend a sphere), so labels placed through it land+/// in flat positions while the basemap under them draws bent — the scattered+/// text of the broken globe. These helpers project through the same+/// `globe_point` basis the vertex shaders and the CPU anchor use, with the+/// same screen convention (`halfH - y`, north up) and the same far-side cull+/// far-side cull (z < 0 draws nothing).+//+// No imports: this file is `include!`d into `placement.rs`, so `Anchor`,+// `BoxInputs` and `Obb` (and the whole parent scope) are already in scope.++/// Screen px of a lon/lat on the globe, or `None` far-side.+///+/// `radius_dp` is the globe radius in Dp (`globe_radius`), `extent_wh` the+/// viewport in device px, `density` device px per Dp. Matches+/// `Camera::globe_anchor_to_screen` + the Dp-to-device mapping the flat+/// `project_to_screen` ends with.+pub fn globe_to_screen(+    camera: &crate::camera::Camera,+    lon: f64,+    lat: f64,+    extent_wh: (u32, u32),+) -> Option<(f32, f32)> {+    let (sx_dp, sy_dp) = camera.globe_anchor_to_screen(lon, lat)?;+    let (w, h) = (extent_wh.0 as f64, extent_wh.1 as f64);+    let px = sx_dp / camera.width_dp as f64 * w;+    let py = sy_dp / camera.height_dp as f64 * h;+    Some((px as f32, py as f32))+}++/// Tile-local anchor to lon/lat at the camera zoom: the inverse of the tile+/// grid the flat path folds into its matrix.+pub fn tile_anchor_lonlat(tz: u8, tx: u32, ty: u32, anchor: (f32, f32)) -> (f64, f64) {+    let n = 2f64.powi(tz as i32);+    let wx = (tx as f64 + anchor.0 as f64) / n;+    let wy = (ty as f64 + anchor.1 as f64) / n;+    let lon = wx * 360.0 - 180.0;+    let n_pi = std::f64::consts::PI - 2.0 * std::f64::consts::PI * wy;+    let lat = n_pi.sinh().atan() * 180.0 / std::f64::consts::PI;+    (lon, lat)+}++/// The screen box a label would occupy on the globe if drawn at `anchor`.+///+/// Same box construction as [`super::anchored_rect`] (text block + icon union,+/// anchor-directed, padded) but centred on the globe-projected anchor rather+/// than the flat matrix projection. Returns `None` far-side.+pub fn globe_anchored_rect(+    camera: &crate::camera::Camera,+    tz: u8,+    tx: u32,+    ty: u32,+    point: (f32, f32),+    extent_wh: (u32, u32),+    inputs: &BoxInputs,+    anchor: Anchor,+) -> Option<(f32, f32, f32, f32)> {+    let (lon, lat) = tile_anchor_lonlat(tz, tx, ty, point);+    let (sx, sy) = globe_to_screen(camera, lon, lat, extent_wh)?;++    let w = inputs.text_px * inputs.advance / crate::tile::glyph::UP_EM as f32;+    let lines = inputs.line_count.max(1) as f32;+    let h = inputs.text_px * (1.0 + (lines - 1.0) * crate::tess::text::LINE_HEIGHT_EM);+    let offset = inputs.offset_em.0.abs() * inputs.text_px;+    let (mut x0, mut x1) = match anchor {+        Anchor::Center => (sx - w * 0.5, sx + w * 0.5),+        Anchor::Left => (sx + offset, sx + offset + w),+        Anchor::Right => (sx - offset - w, sx - offset),+    };+    let (mut y0, mut y1) = (sy - h * 0.5, sy + h * 0.5);+    if let Some((icon_w, icon_h)) = inputs.icon_px {+        x0 = x0.min(sx - icon_w * 0.5);+        x1 = x1.max(sx + icon_w * 0.5);+        y0 = y0.min(sy - icon_h * 0.5);+        y1 = y1.max(sy + icon_h * 0.5);+    }+    Some((+        x0 - inputs.pad_px,+        y0 - inputs.pad_px,+        x1 + inputs.pad_px,+        y1 + inputs.pad_px,+    ))+}++/// Build a curved label's per-glyph screen collision boxes on the globe.+///+/// The segmented analogue of [`globe_anchored_rect`]: each pen point goes+/// tile-local -> lon/lat -> globe screen, and the glyph becomes an [`Obb`]+/// oriented to the screen-space tangent. The tangent is the tile-local tangent+/// rotated by the local sphere bearing (east/north basis at the pen), which at+/// globe zoom is axis-aligned up to the meridian convergence — approximated by+/// the flat linear part, exactly as the flat path does under tilt.+pub fn globe_curved_boxes(+    camera: &crate::camera::Camera,+    tz: u8,+    tx: u32,+    ty: u32,+    placements: &[crate::tess::text::CurvedGlyph],+    tile_clip: [f32; 16],+    extent_wh: (u32, u32),+    text_px: f32,+    pad_px: f32,+) -> Vec<Obb> {+    let (w, h) = (extent_wh.0 as f32, extent_wh.1 as f32);+    let em = crate::tile::glyph::UP_EM as f32;+    let cap_px = crate::tess::text::CAP_HEIGHT_EM * text_px;+    let mut out = Vec::with_capacity(placements.len());+    for cg in placements {+        let advance_px = cg.glyph.advance / em * text_px;+        if advance_px <= 0.0 {+            continue;+        }+        let (lon, lat) = tile_anchor_lonlat(tz, tx, ty, cg.pen);+        let Some((sx, sy)) = globe_to_screen(camera, lon, lat, extent_wh) else { continue };+        // Screen-space tangent through the flat linear part (glyph-scale: the+        // sphere bend varies negligibly across one glyph).+        let dcx = tile_clip[0] * cg.tangent.0 + tile_clip[4] * cg.tangent.1;+        let dcy = tile_clip[1] * cg.tangent.0 + tile_clip[5] * cg.tangent.1;+        let (mut tx, mut ty) = (dcx * w, dcy * h);+        let len = (tx * tx + ty * ty).sqrt();+        if len > 1e-6 {+            tx /= len;+            ty /= len;+        } else {+            tx = 1.0;+            ty = 0.0;+        }+        out.push(Obb {+            cx: sx + tx * advance_px * 0.5,+            cy: sy + ty * advance_px * 0.5,+            hx: advance_px * 0.5 + pad_px,+            hy: cap_px * 0.5 + pad_px,+            cos: tx,+            sin: ty,+        });+    }+    out+}
library/map/src/main/rust/src/tile/select/tests_part2.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests_part2.rs b/library/map/src/main/rust/src/tile/select/tests_part2.rsindex dc175c349c..fd0ebe79c7 100644--- a/library/map/src/main/rust/src/tile/select/tests_part2.rs+++ b/library/map/src/main/rust/src/tile/select/tests_part2.rs@@ -340,3 +340,66 @@ fn the_keep_list_stays_free_of_descendants() {         );     } }++/// **Phase B: a missing tile falls back to its parent, which falls back to the+/// background.** A pruned (or never-stored) water tile resolves to no fetch of its own;+/// the renderer keeps the visible tile's ancestors resident (`resident_set`), draws the+/// coarsest resident one under it, and the style background — the water colour — shows+/// through wherever no ancestor carries land. This pins the chain tile by tile:+///+/// 1. the missing tile's ancestors are exactly the keep list ahead of it;+/// 2. each ancestor step halves the coordinates (the overzoom the reader takes);+/// 3. the background the chain bottoms out at is the water colour, not land.+#[test]+fn a_missing_tile_falls_back_through_its_parent_to_the_water_background() {+    // A mid-Pacific viewport at z12: the visible tiles are deep-ocean tiles the archive+    // does not store (Phase B prunes them), so every one of them must have its parent+    // chain in the keep list.+    let c = camera(-150.0, 0.0, 12.0, 411.0, 891.0);+    let exact = visible(&c, 0, 14);+    assert!(!exact.is_empty(), "the viewport must cover tiles");+    assert!(exact.iter().all(|t| t.z == 12));+    let keep = resident_set(&c, 0, 14);+    for tile in &exact {+        // 1. The parent is kept (and therefore drawable as the overzoom stand-in).+        let parent = tile.ancestor(1).expect("z12 has a parent");+        assert!(+            keep.contains(&parent),+            "{tile:?} is missing with no parent {parent:?} kept to overzoom",+        );+        // 2. Each ancestor step halves the coordinates — the overzoom mapping.+        let grandparent = tile.ancestor(2).expect("z12 has a grandparent");+        assert_eq!(parent.x, tile.x >> 1, "overzoom halves x");+        assert_eq!(parent.y, tile.y >> 1, "overzoom halves y");+        assert_eq!(grandparent.x, tile.x >> 2, "two levels halve twice");+        assert_eq!(grandparent.y, tile.y >> 2);+        assert!(+            keep.contains(&grandparent),+            "{tile:?} is missing with no grandparent {grandparent:?} kept",+        );+    }+    // 3. The chain bottoms out at the water background: the style backdrop behind every+    // tile is the sea colour, so an ocean viewport with no resident ancestor still reads+    // as ocean rather than land or void.+    use crate::style::{background, Variant};+    let water_light = 0xFF80_DEEA;+    let water_dark = 0xFF0D_1B2A;+    assert_eq!(+        background(Variant::Light),+        water_light,+        "the light backdrop must stay the water colour Phase B relies on",+    );+    assert_eq!(+        background(Variant::Dark),+        water_dark,+        "the dark backdrop must stay the water colour Phase B relies on",+    );+    // And the `water` fill arm agrees with it: a stored water polygon and the bare+    // background paint the same sea, which is what makes dropping the tile invisible.+    let water = crate::style::layers()+        .iter()+        .find(|l| l.id == "water")+        .expect("the water fill arm");+    assert_eq!(water.light, water_light, "water fill matches the light backdrop");+    assert_eq!(water.dark, water_dark, "water fill matches the dark backdrop");+}
library/map/src/main/rust/src/vulkan/pick/pass.rs
diff --git a/library/map/src/main/rust/src/vulkan/pick/pass.rs b/library/map/src/main/rust/src/vulkan/pick/pass.rsindex bfb16ca1fb..a41e8967ca 100644--- a/library/map/src/main/rust/src/vulkan/pick/pass.rs+++ b/library/map/src/main/rust/src/vulkan/pick/pass.rs@@ -229,8 +229,23 @@ impl Pick {         for (index, marker) in markers.iter().enumerate() {             let slot = (index as u32).wrapping_add(1);             // The same billboard matrix the sprite is drawn with, sized to the marker's tap box.-            let matrix =-                camera.screen_quad_to_clip(marker.lon, marker.lat, (MARKER_SIZE_DP * 0.5) as f64);+            // Globe: the same globe anchor the draw path resolves (far side culls+            // to a miss, matching the draw that culled the pin itself).+            let matrix = if crate::camera::globe_active(camera) {+                match camera.globe_anchor_to_screen(marker.lon, marker.lat) {+                    Some((sx, sy)) => {+                        crate::vulkan::renderer::globe_screen_quad(+                            camera,+                            sx,+                            sy,+                            (MARKER_SIZE_DP * 0.5) as f64,+                        )+                    }+                    None => continue,+                }+            } else {+                camera.screen_quad_to_clip(marker.lon, marker.lat, (MARKER_SIZE_DP * 0.5) as f64)+            };             let mut push = Push {                 tile_to_clip: matrix,                 color: [0.0; 4],
library/map/src/main/rust/src/vulkan/renderer/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod.rs b/library/map/src/main/rust/src/vulkan/renderer/mod.rsindex 775b318bb1..06a18bc106 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -14,6 +14,7 @@ mod frame; mod mod_extra; mod placement; mod placement_markers;+mod placement_refresh; mod placement_reuse; mod rebuild; mod record;@@ -29,6 +30,7 @@ mod upload_extra; pub(super) mod upload_moon;  pub use mod_extra::Renderer;+pub(crate) use placement::globe_screen_quad;  /// How many frames may be in flight. Two is enough to keep the GPU fed behind vsync /// without adding latency the user can feel when panning.@@ -60,7 +62,10 @@ struct LayerBuffers { /// callback and ~6400 live across 64 resident tiles, near the ~4096 driver hard limit; pooled /// it costs at most 3 pairs (flat fills, stroked lines, ribbon carriageways) plus the /// already-single buildings and terrain meshes.-struct ResidentTile {+///+/// `pub(crate)`: the pick-snapshot split (`placement_refresh`) resolves one+/// label against a tile, so it names this type.+pub(crate) struct ResidentTile {     /// Position-only 2-float fills: every `LayerKind::Fill` mesh plus the region-mask shapes.     flat: Option<(Buffer, Buffer)>,     /// 7-float stroked lines: every `LayerKind::Line` mesh plus the live-traffic segments.
library/map/src/main/rust/src/vulkan/renderer/placement.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement.rs b/library/map/src/main/rust/src/vulkan/renderer/placement.rsindex ffcd2233c0..01f2f9b134 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -116,6 +116,7 @@ impl Renderer {         }         let mut candidates: Vec<placement::SegmentedCandidate> = Vec::new();         let camera_z = camera.zoom.floor().clamp(0.0, 22.0) as u8;+        let globe = crate::camera::globe_active(camera);         for (index, layer) in layers.iter().enumerate() {             if layer.kind != LayerKind::Symbol {                 continue;@@ -175,43 +176,53 @@ impl Renderer {                     // A curved label collides as the row of oriented per-glyph boxes it draws; a                     // point label as one axis-aligned box (plus its variable-anchor alternate). Both                     // go into one `place_segmented` pass so they collide with each other.+                    // Globe and flat share this switch: the box builders differ+                    // (sphere vs matrix projection), the candidate shape does not.                     let (boxes, alternate_boxes) = if let Some(centreline) = &label.centreline {                         let Some(line) = label.lines.first() else {                             continue;                         };                         let ppfu = inputs.text_px / crate::tile::glyph::UP_EM as f32 / tile_span_px;                         let placed = crate::tess::text::layout_along_line(line, centreline, ppfu);-                        let boxes = placement::curved_boxes(-                            &placed,-                            tile_clip,-                            wh,-                            inputs.text_px,-                            inputs.pad_px,-                        );+                        let boxes = if globe {+                            placement::globe_curved_boxes(+                                camera, tile.z, tile.x, tile.y,+                                &placed, tile_clip, wh, inputs.text_px, inputs.pad_px,+                            )+                        } else {+                            placement::curved_boxes(+                                &placed, tile_clip, wh, inputs.text_px, inputs.pad_px,+                            )+                        };                         if boxes.is_empty() {-                            continue; // does not fit its line this frame: nothing to place.+                            continue;                         }                         (boxes, None)                     } else {-                        // The anchor projects with the perspective divide (see-                        // `placement::anchored_rect`): under tilt the box sits where the-                        // billboarded label draws, and distant labels compress onto-                        // overlapping boxes the placer thins by rank. A label whose anchor-                        // is on or behind the eye has no screen position and is skipped —-                        // it cannot be a candidate, so drawing it is unrepresentable here.-                        let Some(primary_rect) =-                            placement::anchored_rect(label.anchor, tile_clip, wh, &inputs, primary)-                        else {-                            continue;+                        let (primary_rect, alt) = if globe {+                            let Some(primary_rect) = placement::globe_anchored_rect(+                                camera, tile.z, tile.x, tile.y, label.anchor, wh, &inputs, primary,+                            ) else { continue };+                            let alt = alternate.and_then(|second| {+                                placement::globe_anchored_rect(+                                    camera, tile.z, tile.x, tile.y, label.anchor, wh, &inputs, second,+                                )+                                .map(|r| vec![placement::Obb::from_rect(r)])+                            });+                            (primary_rect, alt)+                        } else {+                            let Some(primary_rect) =+                                placement::anchored_rect(label.anchor, tile_clip, wh, &inputs, primary)+                            else {+                                continue;+                            };+                            let alt = alternate.and_then(|second| {+                                placement::anchored_rect(label.anchor, tile_clip, wh, &inputs, second)+                                    .map(|r| vec![placement::Obb::from_rect(r)])+                            });+                            (primary_rect, alt)                         };                         let primary_box = placement::Obb::from_rect(primary_rect);-                        // Both anchors share the label's one anchor point, so they project-                        // together: a primary that projected means the alternate does too,-                        // and `and_then` only guards the impossible split.-                        let alt = alternate.and_then(|second| {-                            placement::anchored_rect(label.anchor, tile_clip, wh, &inputs, second)-                                .map(|r| vec![placement::Obb::from_rect(r)])-                        });                         (vec![primary_box], alt)                     };                     candidates.push(placement::SegmentedCandidate {@@ -365,6 +376,9 @@ impl Renderer {     /// pre-pass used (same text size, same padding) so pick boxes match drawn     /// boxes; anchor lon/lat comes from unprojecting the tile-local anchor     /// through the tile's world position at the camera zoom.+    ///+    /// File-length split: the per-label resolve lives in+    /// `refresh_placed_label` (`placement_refresh`), this loop only walks.     pub(super) fn refresh_placed(         &self,         camera: &Camera,@@ -373,6 +387,7 @@ impl Renderer {         extent: vk::Extent2D,     ) {         use crate::tile::placement;+        let globe = crate::camera::globe_active(camera);         let mut placed: Vec<(u32, PlacedHit)> = Vec::new();         for tile in self.tiles.values() {             // Tile origin in world px at the camera zoom: tile (x,y) at ITS@@ -381,7 +396,6 @@ impl Renderer {             // tile_span at tile.z is the tile's own screen size and the             // anchor offsets within it directly.             let span_dp = camera.tile_span_dp(tile.z);-            let origin = camera.viewport_origin();             let tile_wx = tile.x as f64 * span_dp;             let tile_wy = tile.y as f64 * span_dp;             for (label_idx, label) in tile.labels.iter().enumerate() {@@ -406,23 +420,12 @@ impl Renderer {                 } else {                     primary                 };-                let tile_clip = camera.tile_to_clip(tile.z, tile.x, tile.y);-                // Same pitch-aware projection as the pre-pass, so pick boxes match drawn-                // boxes under tilt; an unprojectable anchor has no box and no hit.-                let Some(rect) = placement::anchored_rect(-                    label.anchor,-                    tile_clip,-                    (extent.width, extent.height),-                    &box_inputs(layer, label, camera),-                    anchor,+                let Some((rect, lon, lat)) = self.refresh_placed_label(+                    camera, layer, label, tile, text_px,+                    primary, alternate, anchor, extent, globe, tile_wx, tile_wy, span_dp,                 ) else {                     continue;                 };-                // Anchor tile-local → world px (Dp) → lon/lat.-                let wx = tile_wx + label.anchor.0 as f64 * span_dp;-                let wy = tile_wy + label.anchor.1 as f64 * span_dp;-                let (lon, lat) = crate::camera::unproject(wx, wy, camera.zoom);-                let _ = origin;                 placed.push((                     order,                     PlacedHit {@@ -454,7 +457,11 @@ impl Renderer { /// point (Dp, via [`Camera::globe_anchor_to_screen`]) centred in a `radius_dp` /// quad, in the same shape as [`Camera::screen_quad_to_clip`] so the puck and /// vehicle-ring draws share one contract.-pub(super) fn globe_screen_quad(camera: &Camera, sx_dp: f64, sy_dp: f64, radius_dp: f64) -> [f32; 16] {+///+/// `pub(crate)`: the offscreen pick pass (`vulkan::pick`) resolves the same+/// quad for its tap box, so the pick lands where the pin draws. Re-exported+/// through the renderer root for that caller.+pub fn globe_screen_quad(camera: &Camera, sx_dp: f64, sy_dp: f64, radius_dp: f64) -> [f32; 16] {     let kx = 2.0 / camera.width_dp as f64;     let ky = 2.0 / camera.height_dp as f64;     let cx = sx_dp * kx - 1.0;
library/map/src/main/rust/src/vulkan/renderer/placement_refresh.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement_refresh.rs b/library/map/src/main/rust/src/vulkan/renderer/placement_refresh.rsnew file mode 100644index 0000000000..f99c444d0d--- /dev/null+++ b/library/map/src/main/rust/src/vulkan/renderer/placement_refresh.rs@@ -0,0 +1,68 @@+//! Per-label resolve for the pick snapshot: one label's screen box + lon/lat.+//!+//! File-length split from [`placement`](super::placement) (see `placement.rs`):+//! `refresh_placed` walks the tiles there; this resolves one label through+//! either the flat matrix projection or the globe sphere projection (far side+//! culls), so pick boxes match drawn boxes on both paths.+use super::placement_reuse::box_inputs;+use super::Renderer;+use crate::camera::Camera;+use crate::style::Layer;+use ash::vk;++impl Renderer {+    /// One label's pick box + lon/lat for `refresh_placed`, or `None` when the+    /// anchor has no screen position (behind the eye, or globe far side).+    ///+    /// Same projection the pre-pass placed through — pitch-aware flat matrix,+    /// sphere bend on the globe — so the pick box is the drawn box on both+    /// paths. `tile_wx`/`tile_wy`/`span_dp` are the flat tile origin + span+    /// (Dp) the lon/lat unprojection needs; unused on the globe, where the+    /// sphere basis inverts through the centre instead.+    #[allow(clippy::too_many_arguments)]+    pub(super) fn refresh_placed_label(+        &self,+        camera: &Camera,+        layer: &Layer,+        label: &crate::tile::geometry::ShapedLabel,+        tile: &super::ResidentTile,+        text_px: f32,+        primary: crate::style::Anchor,+        alternate: Option<crate::style::Anchor>,+        anchor: crate::style::Anchor,+        extent: vk::Extent2D,+        globe: bool,+        tile_wx: f64,+        tile_wy: f64,+        span_dp: f64,+    ) -> Option<((f32, f32, f32, f32), f64, f64)> {+        use crate::tile::placement;+        let tile_clip = camera.tile_to_clip(tile.z, tile.x, tile.y);+        let extent_wh = (extent.width, extent.height);+        // Same projection as the pre-pass (pitch-aware flat, sphere on the+        // globe); an unprojectable anchor has no box and no hit.+        let rect = if globe {+            placement::globe_anchored_rect(+                camera, tile.z, tile.x, tile.y, label.anchor,+                extent_wh, &box_inputs(layer, label, camera), anchor,+            )+        } else {+            placement::anchored_rect(+                label.anchor, tile_clip, extent_wh,+                &box_inputs(layer, label, camera), anchor,+            )+        }?;+        // Anchor tile-local → lon/lat. Globe: the sphere basis inverts through+        // the centre (same basis the draw path bends through); flat: world px+        // at the camera zoom.+        let (lon, lat) = if globe {+            placement::tile_anchor_lonlat(tile.z, tile.x, tile.y, label.anchor)+        } else {+            let wx = tile_wx + label.anchor.0 as f64 * span_dp;+            let wy = tile_wy + label.anchor.1 as f64 * span_dp;+            crate::camera::unproject(wx, wy, camera.zoom)+        };+        let _ = (primary, alternate, text_px);+        Some((rect, lon, lat))+    }+}
library/map/src/main/rust/src/vulkan/renderer/record.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record.rs b/library/map/src/main/rust/src/vulkan/renderer/record.rsindex 262f478379..1595e2f681 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record.rs@@ -416,22 +416,17 @@ impl Renderer {                         tile_to_clip: camera.tile_to_clip(tz, tx, ty),                         color: argb_to_rgba(scale_alpha(base, opacity)),                         line: [half_width_px, half_gap_px, layer.dash.0, layer.dash.1],-                        misc: if globe {-                            // Globe: centre lon/lat (degrees) for the sphere basis.-                            [-                                camera.center_lon as f32,-                                camera.center_lat as f32,-                                lateral_px,-                                camera.time_seconds,-                            ]-                        } else {-                            [-                                camera.tile_span_px(tz),-                                edge_aa,-                                lateral_px,-                                camera.time_seconds,-                            ]-                        },+                        // Globe and flat share this block: the globe matrix carries+                        // the centre (translation column) and the radius (2x2), so+                        // `misc`/`morph` keep their flat meaning — tile px, edge AA,+                        // lateral shift, clock, fade, span. The shaders bend through+                        // the matrix and discard past the limb.+                        misc: [+                            camera.tile_span_px(tz),+                            edge_aa,+                            lateral_px,+                            camera.time_seconds,+                        ],                         // `morph.z` is the tile's world-px span (Dp): the draped-`z` scale.                         // On the globe it is the globe radius (Dp) instead, and morph.xy                         // the half-viewport (Dp) — see the `*_globe.vert` headers.
library/map/src/main/rust/src/vulkan/renderer/record_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra.rsindex b63e17ec0b..bab3375764 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra.rs@@ -121,12 +121,10 @@ impl Renderer {                         centre_t,                         f32::from(road.oneway),                     ],-                    misc: if globe {-                        // Globe: centre lon/lat (degrees) for the sphere basis.-                        [camera.center_lon as f32, camera.center_lat as f32, yellow, camera.time_seconds]-                    } else {-                        [tile_span_px, edge_aa, yellow, camera.time_seconds]-                    },+                    // Globe and flat share this block (see the layer loop): the+                    // globe matrix carries the centre and radius; `misc` keeps its+                    // flat meaning (tile px, edge AA, yellow flag, clock).+                    misc: [tile_span_px, edge_aa, yellow, camera.time_seconds],                     // The markings are static, so unlike the traffic draw there is no phase to                     // animate and nothing to fade: `MORPH_NONE` is what the ribbon contract asks                     // for. `morph.z` is the tile's world-px span (Dp) — the draped-`z` scale,@@ -328,6 +326,13 @@ impl Renderer {         fog: u32,         submitted: &mut usize,     ) {+        // Skipped on the globe: the flat terrain mesh drapes through the flat+        // matrix, which the globe branch never takes — drawing it would paste+        // flat relief over the sphere. Relief at globe zoom is sub-pixel+        // anyway, and the globe shaders ignore draped height by construction.+        if crate::camera::globe_active(camera) {+            return;+        }         let Some(earth) = layers             .iter()             .find(|l| l.id == "earth")
library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rsindex 6600a5c65d..f349cfa040 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs@@ -78,20 +78,18 @@ impl Renderer {                     );                     bound = true;                 }-                // Globe push: centre lon/lat + radius/half-viewport, mirroring the-                // flat layer loop's globe branch. Flat path below is unchanged.-                let (misc, morph) = if globe {-                    let r = crate::camera::globe_radius(camera.zoom) as f32;-                    (-                        [camera.center_lon as f32, camera.center_lat as f32, 0.0, camera.time_seconds],-                        [1.0, camera.width_dp / 2.0, r, camera.height_dp / 2.0],-                    )-                } else {-                    (-                        [tile_span_px, edge_aa, 0.0, camera.time_seconds],-                        [1.0, 0.0, camera.tile_span_dp(tile.z) as f32, 0.0],-                    )-                };+                // Globe and flat share this block (see the layer loop): the+                // globe matrix carries the centre and radius; `misc`/`morph`+                // keep their flat meaning (tile px, edge AA, clock; fade, span).+                let (misc, morph) = (+                    [tile_span_px, edge_aa, 0.0, camera.time_seconds],+                    if globe {+                        let r = crate::camera::globe_radius(camera.zoom) as f32;+                        [1.0, camera.width_dp / 2.0, r, camera.height_dp / 2.0]+                    } else {+                        [1.0, 0.0, camera.tile_span_dp(tile.z) as f32, 0.0]+                    },+                );                 let push = Push {                     tile_to_clip,                     color: argb_to_rgba(argb),
library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs b/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rsindex 94b18505a9..050f928981 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs@@ -44,12 +44,13 @@ impl Renderer {          // Icons first, so the label's halo paints over the icon's edge rather than under         // it — the order MapLibre draws them in. On the globe both go through the-        // globe pipelines with the sphere push (centre + radius); flat path below-        // is unchanged.+        // globe pipelines with the sphere matrix (centre + radius in the matrix);+        // `misc.x` keeps its flat meaning (tile span, Dp) and `morph` carries the+        // globe half-viewport + radius (see `symbol_globe.vert`).+        let r = crate::camera::globe_radius(camera.zoom) as f32;         let (globe_misc, globe_morph) = if globe {-            let r = crate::camera::globe_radius(camera.zoom) as f32;             (-                [camera.center_lon as f32, camera.center_lat as f32, 0.0, 0.0],+                [camera.tile_span_dp(tz) as f32, 0.0, 0.0, 0.0],                 [camera.width_dp / 2.0, camera.height_dp / 2.0, r, 0.0],             )         } else {@@ -109,17 +110,14 @@ impl Renderer {                     if globe { 0.0 } else { billboard_flag },                 ],                 // `misc.x` is the tile's world-px span (Dp): the anchor-height scale.-                // `yzw` stay the halo rgb the fragment shader reads. On the globe the-                // centre rides here instead (see above); halo rgb is then unread, and-                // labels draw without halo rather than with a wrong-colour one.-                misc: if globe {-                    globe_misc-                } else {-                    [camera.tile_span_dp(tz) as f32, halo[0], halo[1], halo[2]]-                },+                // `yzw` stay the halo rgb the fragment shader reads. The sphere+                // basis comes from the globe matrix, so the halo stays valid on+                // the globe (see `symbol_globe.vert`).+                misc: [camera.tile_span_dp(tz) as f32, halo[0], halo[1], halo[2]],                 // Repurposed for the symbol billboard pipeline: the pitch-0 tile matrix's linear                 // 2x2, so the shader can add a screen-constant glyph offset under tilt. The symbol                 // fragment shader does not read `morph`, so this collides with nothing.+                // On the globe: half-viewport + radius (see `symbol_globe.vert`).                 morph: globe_morph,             };             self.draw_symbol_batch(
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex 9ca29b7689..737e8a0313 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -55,6 +55,7 @@             android:name=".MainActivity"             android:exported="true"             android:launchMode="singleTop"+            android:windowSoftInputMode="adjustResize"             android:theme="@style/Theme.General">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 40756b0868..f3fc4354e9 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -278,11 +278,16 @@ class MainActivity : ComponentActivity() {     private fun biasPosition(): GeoPoint {         val p = selectedVm.userPosition.value         if (p.latitude != 0.0 || p.longitude != 0.0) return p+        return persistedLastFix() ?: GeoPoint(FALLBACK_LON, FALLBACK_LAT)+    }++    /** The last GPS fix persisted across restarts, or null when none was ever stored. */+    private fun persistedLastFix(): GeoPoint? {         val ds = DataStoreUtils.getInstance(this)-        val lon = ds.getDouble(MapPreferences.KEY_LAST_LON)-        val lat = ds.getDouble(MapPreferences.KEY_LAST_LAT)-        if (lon != null && lat != null && (lat != 0.0 || lon != 0.0)) return GeoPoint(lon, lat)-        return GeoPoint(FALLBACK_LON, FALLBACK_LAT)+        val lon = ds.getDouble(MapPreferences.KEY_LAST_LON) ?: return null+        val lat = ds.getDouble(MapPreferences.KEY_LAST_LAT) ?: return null+        if (lat == 0.0 && lon == 0.0) return null+        return GeoPoint(lon, lat)     }      private fun genericPlace(name: String, lat: Double, lng: Double) =
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex 89aaa3ab67..23b652f722 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -46,6 +46,16 @@ import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.util.DeparturesState import kotlinx.coroutines.delay +/**+ * Fixed height for the board's status states (loading / no departures).+ *+ * Both [LoadingState] and [EmptyState] default to `fillMaxSize`, which inside a+ * `ModalBottomSheet` measures the sheet at full height: the board opens+ * fullscreen while fetching and then snaps down once departures arrive. A+ * bounded status block keeps the sheet at content height through the fetch.+ */+private val BoardStatusHeight = 160.dp+ /**  * Public-transit departure board (P10): a live board for one stop, opened by  * tapping a transit-stop pin. Departures are grouped by line (each with its GTFS@@ -121,12 +131,16 @@ fun DeparturesSheet(                 // only reachable transiently as the sheet opens, and showing nothing for that                 // frame is more honest than showing a spinner for a request nobody made.                 is DeparturesState.Loading -> LoadingState(+                    modifier = Modifier.height(BoardStatusHeight),                     message = stringResource(R.string.transit_departures_loading),                 )                 DeparturesState.Idle -> Unit                 is DeparturesState.Loaded -> {                     if (state.departures.isEmpty()) {-                        EmptyState(title = stringResource(R.string.transit_departures_none))+                        EmptyState(+                            title = stringResource(R.string.transit_departures_none),+                            modifier = Modifier.height(BoardStatusHeight),+                        )                     } else {                         DepartureList(state.departures, now, onTrainTap)                     }
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 15a175cd87..14c04864f0 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -39,6 +39,7 @@ import com.vayunmathur.library.ui.isExpandedWidth import com.vayunmathur.library.ui.rememberFreeHeightSheetState import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.map.GLOBE_DETAIL_ZOOM import com.vayunmathur.library.map.MapBody import com.vayunmathur.library.map.MoonTextures import com.vayunmathur.maps.ui.map.rememberInitialCamera@@ -155,6 +156,14 @@ fun MapPage(     val safetyEnabled by settingsViewModel.safetyLayer.collectAsState()     val transitEnabled by settingsViewModel.transitLayer.collectAsState()     val globeEnabled by settingsViewModel.globeEnabled.collectAsState()+    // Enabling the globe at street zoom shows nothing new: the sphere only+    // reads past the detail threshold. Zoom out to reveal it, so the toggle+    // answers visibly instead of arming a mode the user cannot see.+    LaunchedEffect(globeEnabled) {+        if (globeEnabled && camera.position.zoom >= GLOBE_DETAIL_ZOOM) {+            camera.animateTo(camera.position.copy(zoom = GLOBE_REVEAL_ZOOM))+        }+    }      // The Moon raster pair, loaded lazily on first Moon select (never for Earth     // sessions): 37MB of assets read once, cached for the session. `body` lives@@ -316,3 +325,10 @@ internal fun stopNavigation(context: android.content.Context) {         android.content.Intent(context, com.vayunmathur.maps.util.NavigationService::class.java)     ) }++/**+ * Zoom the globe toggle reveals at: comfortably past the detail threshold so+ * the sphere reads as a sphere, close enough that the home continent is still+ * recognisable rather than a marble.+ */+private const val GLOBE_REVEAL_ZOOM = 3.0
maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.ktindex 4dcd60285f..06b1cfc6f7 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt@@ -2,6 +2,7 @@ package com.vayunmathur.maps.ui  import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier@@ -32,7 +33,13 @@ internal fun MapPageScope.MapSheets(     val placeSheet = sheetState ?: return     FreeHeightBottomSheetScaffold({         if (searchActions != null) {-            SearchSheet(searchState, searchActions, Modifier.padding(top = Spacing.sm))+            SearchSheet(+                searchState,+                searchActions,+                // Ride above the keyboard: the field keeps focus while typing, so+                // without IME padding the keys cover the results being typed for.+                Modifier.padding(top = Spacing.sm).imePadding(),+            )         }     },         Modifier,
maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.ktindex af8f739165..caed546f25 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapSidePanel.kt@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.windowInsetsPadding@@ -53,7 +54,7 @@ fun MapSidePanel(     modifier: Modifier = Modifier, ) {     Surface(modifier = modifier) {-        Column(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.systemBars)) {+        Column(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.systemBars).imePadding()) {             if (searchOpen) {                 SearchSheet(searchState, searchActions, Modifier.padding(top = Spacing.sm))             } else {
maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.ktindex c5e3a9a8d7..d7e37ebfe7 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt@@ -42,6 +42,16 @@ import com.vayunmathur.maps.data.transit.TripItinerary import com.vayunmathur.maps.data.transit.TripStop import com.vayunmathur.maps.util.TripItineraryState +/**+ * Fixed height for the sheet's status states (loading / missing trip).+ *+ * Both [LoadingState] and [EmptyState] default to `fillMaxSize`, which inside a+ * `ModalBottomSheet` measures the sheet at full height: the sheet opens+ * fullscreen while fetching and then snaps down once the itinerary arrives. A+ * bounded status block keeps the sheet at content height through the fetch.+ */+private val BoardStatusHeight = 160.dp+ /**  * A vehicle's full run: every station it was at or will be at, and when.  *@@ -75,10 +85,12 @@ fun TripSheet(             when (state) {                 TripItineraryState.Idle -> Unit                 TripItineraryState.Loading -> LoadingState(+                    modifier = Modifier.height(BoardStatusHeight),                     message = stringResource(R.string.transit_departures_loading),                 )                 TripItineraryState.Missing -> EmptyState(-                    title = stringResource(R.string.transit_departures_none)+                    title = stringResource(R.string.transit_departures_none),+                    modifier = Modifier.height(BoardStatusHeight),                 )                 is TripItineraryState.Loaded -> {                     val itin = state.itinerary
maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.ktindex eb10f2de80..25a90893cb 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt@@ -157,19 +157,30 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {         )         var best: Location? = null         for (provider in providers) {-            if (!locationManager.isProviderEnabled(provider)) continue-            val fix = runCatching { locationManager.getLastKnownLocation(provider) }.getOrNull()-                ?: continue-            // A (0,0) last-known is the OS having nothing real, not the Gulf of Guinea.-            if (fix.latitude == 0.0 && fix.longitude == 0.0) continue+            val fix = usableLastKnown(provider)             val current = best-            if (current == null || fix.elapsedRealtimeNanos > current.elapsedRealtimeNanos) {+            if (fix != null && (current == null || fix.elapsedRealtimeNanos > current.elapsedRealtimeNanos)) {                 best = fix             }         }         return best     } +    /**+     * The OS-cached fix for [provider], or null when the provider is off, has+     * no fix, or only has the (0,0) nothing-real sentinel. A SecurityException+     * (provider state changed mid-call) reads as no fix.+     */+    @SuppressLint("MissingPermission")+    private fun usableLastKnown(provider: String): Location? {+        if (!locationManager.isProviderEnabled(provider)) return null+        val fix = runCatching { locationManager.getLastKnownLocation(provider) }.getOrNull()+            ?: return null+        // A (0,0) last-known is the OS having nothing real, not the Gulf of Guinea.+        if (fix.latitude == 0.0 && fix.longitude == 0.0) return null+        return fix+    }+     override fun onSensorChanged(event: SensorEvent) {         if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {             accelerometerReading = event.values.copyOf()
maps/src/main/rust/src/graph_part2b.rs
diff --git a/maps/src/main/rust/src/graph_part2b.rs b/maps/src/main/rust/src/graph_part2b.rsnew file mode 100644index 0000000000..b08797183a--- /dev/null+++ b/maps/src/main/rust/src/graph_part2b.rs@@ -0,0 +1,233 @@+impl Graph {+    // --- Raw accessors (all unaligned-safe) ---++    /// Whether this graph reads record tables through v7 blocked sections.+    /// Test hook: the loaders set the views, the accessors branch on them.+    pub(crate) fn uses_blocked_sections(&self) -> bool {+        self.nodes_view.is_some() || self.edges_view.is_some()+    }++    #[inline]+    pub fn node(&self, id: u32) -> NodeMaster {+        // Callers guarantee id <= node_count (sentinel index is valid).+        if let Some(view) = &self.nodes_view {+            return self.blocked_node(view, id);+        }+        let r = unsafe { read_at::<NodeRec>(self.nodes, id as usize) };+        NodeMaster {+            lat_e7: r.lat_e7,+            lon_e7: r.lon_e7,+            edge_ptr: u64::from(r.edge_ptr),+        }+    }++    /// A node record out of a v7 blocked section: inflate once (whole section,+    /// cached), then plain indexing. Steady-state memory equals the v6+    /// resident set; the cost is a one-time inflate per section on first+    /// route, not per lookup — which is what keeps the A* hot loop free of+    /// locks and branches past this one.+    #[cold]+    fn blocked_node(&self, view: &BlockedView, id: u32) -> NodeMaster {+        let bytes = self.unpacked_nodes.get_or_init(|| view.unpack().unwrap_or_default());+        let at = id as usize * 12;+        if at + 12 > bytes.len() {+            return NodeMaster {+                lat_e7: 0,+                lon_e7: 0,+                edge_ptr: 0,+            };+        }+        NodeMaster {+            lat_e7: i32::from_le_bytes(bytes[at..at + 4].try_into().expect("4 bytes")),+            lon_e7: i32::from_le_bytes(bytes[at + 4..at + 8].try_into().expect("4 bytes")),+            edge_ptr: u64::from(u32::from_le_bytes(+                bytes[at + 8..at + 12].try_into().expect("4 bytes"),+            )),+        }+    }++    /// Safe node fetch: returns a zeroed node for out-of-range ids, mirroring+    /// the C++ `get_node` fallback.+    ///+    /// Deliberately asymmetric with [`Graph::node`], which is unchecked: the+    /// sentinel index `node_count` is a *valid* read that this method rejects, and+    /// [`Graph::edge_range`] depends on being able to make it.+    #[inline]+    pub fn get_node(&self, id: u32) -> NodeMaster {+        if self.nodes.is_null() || id >= self.node_count {+            return NodeMaster {+                lat_e7: 0,+                lon_e7: 0,+                edge_ptr: 0,+            };+        }+        self.node(id)+    }++    /// Ground elevation of node `id` in metres, or 0 when the graph carries no `elevation.bin` or+    /// `id` is out of range. Baked from the DEM at build time (WS-G); a build without a DEM, or a+    /// node off the DEM's coverage, reads as 0 so the route profile is simply flat there.+    #[inline]+    pub fn node_elevation(&self, id: u32) -> i16 {+        if id >= self.node_count {+            return 0;+        }+        if let Some(view) = &self.elevation_view {+            return self.blocked_elevation(view, id);+        }+        if self.elevation.is_null() {+            return 0;+        }+        unsafe { read_at::<i16>(self.elevation, id as usize) }+    }++    /// An elevation sample out of a v7 blocked section. Same lazy-inflate+    /// discipline as [`Graph::blocked_node`].+    #[cold]+    fn blocked_elevation(&self, view: &BlockedView, id: u32) -> i16 {+        let bytes = self+            .unpacked_elevation+            .get_or_init(|| view.unpack().unwrap_or_default());+        let at = id as usize * 2;+        if at + 2 > bytes.len() {+            return 0;+        }+        i16::from_le_bytes(bytes[at..at + 2].try_into().expect("2 bytes"))+    }++    /// `[start, end)` of node `id`'s outgoing edges in `edges.bin`. `id` must be a+    /// real node, i.e. `id < node_count`.+    ///+    /// The only way to ask that question. Every caller that reads an `edge_ptr`+    /// wants a range, not an offset, so the pairing is expressed once here rather+    /// than transcribed at eight sites — which is also what stops a future+    /// `nodes.bin` layout from leaking out of this file.+    ///+    /// # What the sentinel record is for+    ///+    /// `nodes.bin` carries one record past the real nodes whose `edge_ptr` is+    /// `edge_count`. That is what makes this well-defined for the *last* real node:+    /// `id + 1` is read for every node, so without it the last one would read past+    /// the mapping and every other node's range would be one short of correct.+    /// `edge_range(node_count - 1).1 == edge_count` is the property, and it is+    /// load-bearing at eight sites.+    ///+    /// The sentinel index itself is the highest `id` this may be *passed plus one* —+    /// `edge_range(node_count)` would read `node_count + 1`, which does not exist.+    /// Every caller either iterates `0..node_count` or rejects `id >= node_count`+    /// first.+    ///+    /// Note that this goes through [`Graph::node`], which is unchecked, *not*+    /// [`Graph::get_node`], which would reject the sentinel index and silently+    /// return `edge_ptr = 0` — turning the last node's range into an empty one.+    #[inline]+    pub fn edge_range(&self, id: u32) -> (u64, u64) {+        debug_assert!(id < self.node_count, "node {id} is not a real node");+        (self.node(id).edge_ptr, self.node(id + 1).edge_ptr)+    }++    /// Edge `idx`, which must be one of node `source`'s outgoing edges.+    ///+    /// `source` is what makes the record readable at all: it stores `target` as a+    /// signed delta from it. Passing the wrong one produces a plausible node id+    /// rather than a crash, which is why the debug assertion below exists — it is the+    /// cheapest available guard against the one bug class delta coding introduces.+    #[inline]+    pub fn edge(&self, source: u32, idx: u64) -> Edge {+        debug_assert!(+            {+                let (s, e) = self.edge_range(source);+                (s..e).contains(&idx)+            },+            "edge {idx} is not in node {source}'s range {:?}",+            self.edge_range(source)+        );+        let r = self.edge_rec(source, idx);+        let (target, dist_mm) = if r.escaped() {+            self.escaped_fields(idx)+        } else {+            (+                source.wrapping_add_signed(i32::from(r.target_delta)),+                r.dist_mm(),+            )+        };+        Edge {+            target,+            dist_mm,+            type_: r.type_,+            speed_limit: r.speed_limit,+        }+    }++    /// One edge record, by value. v6 reads the mapped record directly; v7+    /// indexes the lazily inflated section. Same lazy-inflate discipline as+    /// [`Graph::blocked_node`].+    #[inline]+    fn edge_rec(&self, _source: u32, idx: u64) -> EdgeRec {+        if let Some(view) = &self.edges_view {+            return self.blocked_edge(view, idx);+        }+        unsafe { read_at::<EdgeRec>(self.edges, idx as usize) }+    }++    /// An edge record out of a v7 blocked section.+    #[cold]+    fn blocked_edge(&self, view: &BlockedView, idx: u64) -> EdgeRec {+        let bytes = self+            .unpacked_edges+            .get_or_init(|| view.unpack().unwrap_or_default());+        let at = idx as usize * 7;+        if at + 7 > bytes.len() {+            return EdgeRec {+                target_delta: 0,+                dist: [0, 0, 0],+                type_: 0,+                speed_limit: 0,+            };+        }+        EdgeRec {+            target_delta: i16::from_le_bytes([bytes[at], bytes[at + 1]]),+            dist: [bytes[at + 2], bytes[at + 3], bytes[at + 4]],+            type_: bytes[at + 5],+            speed_limit: bytes[at + 6],+        }+    }++    /// `(target, dist_mm)` from the escape table, for an edge whose record carries a+    /// sentinel.+    ///+    /// One load from the block index, then a scan of that block's rows — ~3 of them+    /// at a 0.3% escape rate, usually within one cache line. See [`ESCAPE_BLOCK`].+    ///+    /// A record with a sentinel and no matching row is a corrupt pack that the load-+    /// time checks cannot catch without an O(E) scan. It returns `u32::MAX` as the+    /// target, which every caller already rejects as out of range, so the edge is+    /// skipped rather than followed somewhere arbitrary.+    #[cold]+    fn escaped_fields(&self, idx: u64) -> (u32, u32) {+        let block = (idx / ESCAPE_BLOCK) as usize;+        let lo = unsafe { read_at::<u32>(self.escape_first, block) };+        let hi = unsafe { read_at::<u32>(self.escape_first, block + 1) };+        for r in lo..hi {+            let row = unsafe { read_at::<EscapeRow>(self.escapes, r as usize) };+            if u64::from(row.edge_idx) == idx {+                return (row.target, row.dist_mm);+            }+        }+        debug_assert!(false, "edge {idx} is escaped but has no escape row");+        (u32::MAX, DIST_MM_ESCAPE)+    }++    /// Whether edge `idx` of node `source` points at `want`.+    ///+    /// Four call sites scan a node's edge range looking for the one edge that reaches+    /// a given node and never use the target as a value. Delegating to [`Graph::edge`]+    /// rather than comparing in delta space keeps the escape handling in one place:+    /// the delta form would have to handle both an escaped record that could still+    /// match and a `want − source` outside `i16` range, and the saving over one+    /// sign-extend and one add is nothing.+    #[inline]+    pub fn edge_targets(&self, idx: u64, source: u32, want: u32) -> bool {+        self.edge(source, idx).target == want+    }+}
maps/src/main/rust/src/graph_part4b.rs
diff --git a/maps/src/main/rust/src/graph_part4b.rs b/maps/src/main/rust/src/graph_part4b.rsnew file mode 100644index 0000000000..b830e548f1--- /dev/null+++ b/maps/src/main/rust/src/graph_part4b.rs@@ -0,0 +1,43 @@+impl Graph {++    /// Load the graph from a single-archive `.mamaps` file.+    ///+    /// Maps the one file, parses the tile header and the sidecar directory+    /// (which refuses a corrupt container, a build-id mismatch and any+    /// section the header's counts do not describe), then hands the seven+    /// graph payloads to [`Graph::assemble`]. Optional sections absent from+    /// the directory degrade exactly as absent files do today: no names pool,+    /// topology-inferred lanes, a flat profile.+    pub fn load_archive(path: &str) -> Option<Graph> {+        let region = MmapRegion::map(path)?;+        // The mapping must cover the whole file: ArchiveView::parse checks+        // `bytes.len() == header.file_len`, and a short mapping would refuse+        // a good archive rather than read past it.+        let bytes = unsafe { std::slice::from_raw_parts(region.base(), region.len) };+        let header = Header::parse(bytes).ok()?;+        let view = ArchiveView::parse(bytes, &header).ok()?;+        let section = |kind| view.section(bytes, kind);+        let sections = GraphSections {+            meta: section(ARCHIVE_KIND_GRAPH_META)?,+            nodes: section(ARCHIVE_KIND_GRAPH_NODES)?,+            edges: section(ARCHIVE_KIND_GRAPH_EDGES)?,+            intermediate: section(ARCHIVE_KIND_GRAPH_INTERMEDIATE)?,+            road_names: section(ARCHIVE_KIND_GRAPH_NAMES),+            lanes: section(ARCHIVE_KIND_GRAPH_LANES),+            elevation: section(ARCHIVE_KIND_GRAPH_ELEVATION),+        };+        Graph::assemble(+            sections,+            GraphOwnership {+                nodes: None,+                edges: None,+                intermediate: None,+                road_names: None,+                lanes: None,+                elevation: None,+                archive: Some(region),+                buffers: Vec::new(),+            },+        )+    }+}
maps/src/main/rust/src/transit_part9.rs
diff --git a/maps/src/main/rust/src/transit_part9.rs b/maps/src/main/rust/src/transit_part9.rsindex 6ca96f85f7..2b87054718 100644--- a/maps/src/main/rust/src/transit_part9.rs+++ b/maps/src/main/rust/src/transit_part9.rs@@ -193,10 +193,6 @@             min_lat_e7: 0,             max_lon_e7: 0,             max_lat_e7: 0,-            shared_offset: 0,-            shared_len: 0,-            shared_flags: 0,-            shared_pools: 0,         }     }