Modern Apps git

← Modern-Apps.git

maps: add twist and tilt gestures to the globe camera

Commit
e4c33ff0eb6e6cb792c73f87a2ea66a0301e11c5
Author
Vayun Mathur <[email protected]>
When
2026-12-04 23:40 UTC (1 day ago)
Parents
61f75a3
Owner request: in globe view, tilt and twist the camera, not just
pan and zoom. Before this change the globe path was north-up level
by construction: CameraState.onGlobeGesture forced bearing and
pitch to zero, onRotate/onTilt returned early while the globe was
active, MapGestures dropped the twist rotation and never fed the
tilt detector on the globe, and the native globe shaders ignored
the bearing/pitch they were already handed every frame.

The globe now composes exactly the flat camera model in sphere
terms, through one view rotation shared by every layer:

- globeViewRotate (Kotlin Projection, mirrored by the native
  globe_view_rotate and a globeView helper in each *_globe vertex
  shader): roll the unit-sphere point about the view axis by the
  bearing, then tip it about the screen-east axis by the pitch.
  The disc stays centred on the viewport; positive pitch tips the
  north of the sphere toward the viewer. Both zero is the identity,
  so a level globe is bit-identical to before. Bearing/pitch ride
  the globe matrix's previously unused m[3]/m[7] slots (Moon: the
  free line push slot, un-rotated in moon.frag), so no push-constant
  layout changes.

- CameraState: onGlobeGesture accepts the twist (same wrap and
  sensitivity as the flat path) and preserves bearing/pitch through
  pan and pinch-zoom via copy; pan un-rolls by the bearing before
  globePanBy, matching the flat pan's inverse rotation; onRotate
  and onTilt no longer bail out on the globe; the centroid zoom
  anchor projections carry bearing/pitch. State persists through
  the existing CameraPosition saver (bearing/pitch were already
  saved fields) - no new state, no settings or toggles.

- MapGestures: the shared transform and tilt detectors now feed
  the globe identically to the flat map; the tilt detector's
  parallel-drag consumption keeps tilt from fighting pan/pinch,
  as on the flat path.

Clamps: bearing wraps 0-360 (as flat); pitch clamps to the flat
map's MAX_PITCH (65 degrees, the native PITCH_MAX_DEG the JNI
boundary already enforces), so a pitch set on the globe stays
valid when zoom crosses GLOBE_DETAIL_ZOOM onto the flat path with
no re-clamp jump. Tile coverage and the user-puck cull evaluate
visibility in the rotated view frame; label placement, markers
and picking flow through the rotated globe_anchor_to_screen.

Verified: new CameraGlobeGestureTest (twist/wrap/tilt-clamp,
pan/zoom preservation, rotate gate, projection roll/tip and
round-trips, threshold crossing) written before the fix and
failing on the missing view rotation; cargo test 586 passed
including 5 new globe_view_rotate/anchor tests and cargo fmt
clean; the 5 touched shaders compile with the NDK glslc;
./gradlew :maps:lint :maps:lintVitalRelease :maps:testDevUnitTest
:library:map:testDebugUnitTest :library:map:lint all green, so
there were no failures to attribute to the base. maps/AGENTS.md
does not document globe gestures, so only library/map/AGENTS.md
gained the globe-camera note.

Diff

library/map/AGENTS.md
diff --git a/library/map/AGENTS.md b/library/map/AGENTS.mdindex 11de5d3505..bd0d34bc66 100644--- a/library/map/AGENTS.md+++ b/library/map/AGENTS.md@@ -17,6 +17,7 @@ ## Overview **Purpose:** Offline vector-map renderer on a Rust core — Vulkan surface, layers/markers/routes/traffic, gestures, camera state. Declares INTERNET itself (tile fetches). Used by maps, weather, taxi, fooddelivery. **How to use:** `VectorMap` composable in a `MapScope` with `MapStyle` + `LayerOptions`; camera via `CameraState`; overlays for routes/markers/image layers; gestures via `MapGestures`. Tile/bridge work crosses JNI (`MapNative`).+**Globe camera:** while the globe is active the same `CameraPosition.bearing`/`pitch` model applies in sphere terms — the two-finger twist rolls the sphere in its plane and the two-finger vertical drag tips it about its screen-east axis, both persisted by `CameraState` (pitch clamped to the flat map's `MAX_PITCH`). The view rotation is `globeViewRotate` (Kotlin `Projection`, mirrored by the native `globe_view_rotate` and the `*_globe` shaders); pan un-rolls by the bearing before rotating the sphere. **Entry points:** `VectorMap.kt` → `MapScope.kt` → `MapStyle.kt` → `SurfaceMapRenderer.kt`. **Gotchas:** Another agent is mid-refactor here (tile cache moved `tile/cache.rs` → `tile/cache/` dir, `MapTileCache` touched in maps/) — check `git status`/`git log` on this module before deep work; rendering bugs are usually Rust-side. 
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 055a48931d..570c5411d6 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@@ -257,8 +257,10 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      *      * 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.+     * ([globePanBy]); the twist turns the bearing and the two-finger tilt+     * ([onTilt]) turns the pitch, through the same [globeViewRotate] view+     * rotation the projection and the renderer apply, so the globe composes+     * exactly the flat camera's bearing/pitch model in sphere terms.      */     /** [onGesture] on an active globe: pan rotates the sphere, zoom stays centroid-anchored. */     @Suppress("LongParameterList")@@ -266,16 +268,21 @@ class CameraState(initial: CameraPosition = CameraPosition()) {         centroidDp: Offset,         panDp: Offset,         zoomChange: Float,+        rotationDeg: Float,         minZoom: Double,         maxZoom: Double,         scrollEnabled: Boolean,         zoomEnabled: Boolean,+        rotateEnabled: Boolean,         vp: Size,     ) {         var zoom = position.zoom         var center = position.target         if (scrollEnabled && (panDp.x != 0f || panDp.y != 0f)) {-            center = globePanBy(center, panDp, vp, position.zoom)+            // The drag arrives in the rolled screen frame; the sphere basis is+            // north-up, so un-roll it first (the globe counterpart of the flat+            // pan's inverse bearing rotation).+            center = globePanBy(center, unrotatePan(panDp, position.bearing), vp, position.zoom)         }         if (zoomEnabled && zoomChange != 1f && zoomChange > 0f) {             val newZoom = (zoom + log2(zoomChange.toDouble())).coerceIn(minZoom, maxZoom)@@ -285,7 +292,12 @@ class CameraState(initial: CameraPosition = CameraPosition()) {                 zoom = zoomed.zoom             }         }-        position = position.copy(target = center, zoom = zoom, bearing = 0.0, pitch = 0.0)+        var bearing = position.bearing+        if (rotateEnabled && rotationDeg != 0f) {+            bearing = wrapBearing(bearing - rotationDeg * ROTATION_SENSITIVITY)+        }+        // `copy`, not a rebuild: pan/zoom/twist leave the pitch the tilt gesture set.+        position = position.copy(target = center, zoom = zoom, bearing = bearing)     }      internal fun onGesture(@@ -308,7 +320,8 @@ class CameraState(initial: CameraPosition = CameraPosition()) {         // so the threshold crossing is continuous.         if (globeEnabled && position.zoom < GLOBE_DETAIL_ZOOM) {             onGlobeGesture(-                centroidDp, panDp, zoomChange, effectiveMinZoom, maxZoom, scrollEnabled, zoomEnabled, vp,+                centroidDp, panDp, zoomChange, rotationDeg, effectiveMinZoom, maxZoom,+                scrollEnabled, zoomEnabled, rotateEnabled, vp,             )             return         }@@ -351,26 +364,23 @@ 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.+     * 0–360 rather than clamping, so spinning past north continues through it. On an+     * active globe the same bearing rolls the sphere in its plane ([globeViewRotate]).      */     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))     }      /**      * 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.+     * matching Google Maps. Clamped to `0.0..`[MAX_PITCH] — the same clamp as the flat map, so a+     * pitch set on the globe stays valid when zoom crosses [GLOBE_DETAIL_ZOOM] onto the flat+     * path with no re-clamp jump; nothing else about the camera moves. On an active globe the+     * pitch tips the sphere about its screen-east axis ([globeViewRotate]).      */     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)     }@@ -447,13 +457,16 @@ private fun CameraState.anchoredZoom(     // 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.+    // The projections carry the camera's bearing/pitch, so the anchor is the+    // point under the finger in the rolled/tipped view actually on screen.     if (globeEnabled && from.zoom < GLOBE_DETAIL_ZOOM) {         val globeNow = Projection(             center = from.target,             zoom = from.zoom,             widthDp = vp.width,             heightDp = vp.height,+            pitchDeg = from.pitch,+            bearingDeg = from.bearing,             globe = true,         )         val geo = globeNow.positionFromScreenLocation(@@ -464,6 +477,8 @@ private fun CameraState.anchoredZoom(             zoom = newZoom,             widthDp = vp.width,             heightDp = vp.height,+            pitchDeg = from.pitch,+            bearingDeg = from.bearing,             globe = newZoom < GLOBE_DETAIL_ZOOM,         )         // Keep the picked ground under the finger: re-derive the centre whose
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 cba4c45985..ab6745768a 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@@ -96,14 +96,11 @@ 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 = if (cameraState.isGlobeActive) 0f else rotation,+                    rotationDeg = rotation,                     minZoom = zoomRange.start.toDouble(),                     maxZoom = zoomRange.endInclusive.toDouble(),                     scrollEnabled = gestures.isScrollEnabled,@@ -120,11 +117,8 @@ internal fun Modifier.mapGestures(             if (gestures.isTiltDisabled) {                 return@pointerInput             }-            // 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)+                cameraState.onTilt(dyPx / density)             }         }         // Declared after the transform detector so it sees pointer events first and
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 179888d23b..898fe72e9c 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@@ -193,10 +193,8 @@ class Projection internal constructor(      *      * Mirrors the native `globe_project` exactly: the same [GLOBE_DETAIL_ZOOM]      * sphere radius, the same 3D basis, so Compose overlays land where the-     * renderer drew the basemap under them. Bearing/pitch are folded in by the-     * caller's pre-rotation of the basis only insofar as the native path does —-     * the globe path is north-up level (tilt under globe is disabled at call-     * sites), so like every other globe helper this takes no bearing/pitch.+     * renderer drew the basemap under them. Bearing/pitch fold in through+     * [globeViewRotate] on the unit point, exactly as the native path does.      */     private fun globeScreenLocationFromPosition(position: GeoPoint): DpOffset {         val (x, y, z) = globeProject(position.longitude, position.latitude)@@ -230,14 +228,17 @@ class Projection internal constructor(      */     private fun globeProject(longitude: Double, latitude: Double): Triple<Double, Double, Double> {         val (x, y, z) = globePoint(center.longitude, center.latitude, longitude, latitude)+        val (vx, vy, vz) = globeViewRotate(x, y, z, bearingDeg, pitchDeg)         val r = globeRadius()-        return Triple(x * r, y * r, z * r)+        return Triple(vx * r, vy * r, vz * r)     }      private fun globeUnproject(nx: Double, ny: Double, nz: Double): GeoPoint {-        // Normalise back to the unit sphere (nx/ny/nz are in Dp), then invert.+        // Normalise back to the unit sphere (nx/ny/nz are in Dp), undo the+        // camera view rotation, then invert the centre-facing basis.         val r = globeRadius()-        val (lon, lat) = globeLonLat(center.longitude, center.latitude, nx / r, ny / r, nz / r)+        val (x, y, z) = globeViewUnrotate(nx / r, ny / r, nz / r, bearingDeg, pitchDeg)+        val (lon, lat) = globeLonLat(center.longitude, center.latitude, x, y, z)         return GeoPoint(lon, lat)     } @@ -436,3 +437,51 @@ internal fun globeLonLat( }  private const val LAT_MAX = 90.0++/**+ * Rotates a unit-sphere point from the centre-facing basis into the camera's+ * view frame: first the [bearingDeg] roll about the view axis (so the named+ * compass direction points up the screen), then the [pitchDeg] tip about the+ * screen-east axis (positive pitch tips the north of the sphere toward the+ * viewer and slips the camera target down-screen; the disc stays centred on+ * the viewport). Both zero is the identity, bit-identical to the level globe.+ * Mirrors the native `globe_view_rotate`, which must stay in step.+ */+internal fun globeViewRotate(+    x: Double,+    y: Double,+    z: Double,+    bearingDeg: Double,+    pitchDeg: Double,+): Triple<Double, Double, Double> {+    if (bearingDeg == 0.0 && pitchDeg == 0.0) return Triple(x, y, z)+    val b = Math.toRadians(bearingDeg)+    val cosB = cos(b)+    val sinB = sin(b)+    val x1 = cosB * x - sinB * y+    val y1 = sinB * x + cosB * y+    val p = Math.toRadians(pitchDeg)+    val cosP = cos(p)+    val sinP = sin(p)+    return Triple(x1, cosP * y1 - sinP * z, sinP * y1 + cosP * z)+}++/** Inverse of [globeViewRotate]. Mirrors the native `globe_view_unrotate`. */+internal fun globeViewUnrotate(+    x: Double,+    y: Double,+    z: Double,+    bearingDeg: Double,+    pitchDeg: Double,+): Triple<Double, Double, Double> {+    if (bearingDeg == 0.0 && pitchDeg == 0.0) return Triple(x, y, z)+    val p = Math.toRadians(pitchDeg)+    val cosP = cos(p)+    val sinP = sin(p)+    val y1 = cosP * y + sinP * z+    val z1 = -sinP * y + cosP * z+    val b = Math.toRadians(bearingDeg)+    val cosB = cos(b)+    val sinB = sin(b)+    return Triple(cosB * x + sinB * y1, -sinB * x + cosB * y1, z1)+}
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex 6ea49b3b21..587602ff7f 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -74,8 +74,10 @@ internal val MapOnlineDefault: StateFlow<Boolean> = OnlineAlways  *   opts in, driven by its settings toggle. Below [GLOBE_DETAIL_ZOOM] the basemap, the  *   Compose overlays ([Projection]) and the gesture math all use the sphere; past it the  *   sphere is sub-pixel from flat, so both paths use the flat math bit-identically.- *   The globe path is north-up level: bearing and the two-finger tilt are ignored while- *   it is active (tilting a planet is a separate workstream).+ *   On the globe the same bearing/pitch camera model applies in sphere terms:+ *   the twist rolls the sphere in its plane and the two-finger tilt tips it+ *   about its screen-east axis (see `globeViewRotate`), persisted in+ *   [CameraPosition] exactly as on the flat map.  * @param darkBasemap which palette to paint. Defaults to the system theme. The dark colours  *   are `maps`' own contrast-checked `BasemapPalette`, so the apps agree with each other.  *   Switching is free: only a push constant changes.
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 db14f2a604..6153af910f 100644--- a/library/map/src/main/rust/shaders/fill_globe.vert+++ b/library/map/src/main/rust/shaders/fill_globe.vert@@ -35,6 +35,18 @@ layout(location = 0) out float outZ;  const float PI = 3.141592653589793; +// Camera view rotation for the globe: m[3]/m[7] of the globe matrix carry+// the bearing/pitch (degrees). Must match `camera::globe_view_rotate`.+vec3 globeView(vec3 pt) {+    float vb = radians(push.tileToClip[0][3]);+    float vp = radians(push.tileToClip[1][3]);+    if (vb == 0.0 && vp == 0.0) return pt;+    float x1 = cos(vb) * pt.x - sin(vb) * pt.y;+    float y1 = sin(vb) * pt.x + cos(vb) * pt.y;+    return vec3(x1, cos(vp) * y1 - sin(vp) * pt.z, sin(vp) * y1 + cos(vp) * pt.z);+}++ // `globe_tile_to_clip` packs (ox, oy, span) into m[2], m[6], m[10]: row 2 of // columns 0..2, i.e. `tileToClip[0][2]`, `[1][2]`, `[2][2]` in GLSL. // Translation column (m[12]/m[13]): centre lon/lat in degrees.@@ -72,14 +84,15 @@ void main() {     float ky = push.tileToClip[1][1] / max(r, 1e-6);     // 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;+    vec3 v = globeView(vec3(x, y, z));+    float sx = v.x * r;+    float sy2 = v.y * r;     float cx = kx * sx + (kx * hw - 1.0);     float cyy = -(ky * sy2) + (ky * hh - 1.0);     // Depth: sub-camera point (z=1) -> 0, limb (z=0) -> 1, so nearer wins LESS.-    float depth = clamp(1.0 - z, 0.0, 1.0);-    outZ = z;-    if (z < 0.0) {+    float depth = clamp(1.0 - v.z, 0.0, 1.0);+    outZ = v.z;+    if (v.z < 0.0) {         // Far side: emit at far depth so the triangle clips away.         gl_Position = vec4(cx, cyy, 1.0, 1.0);     } else {
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 10920f85e2..6b742948f1 100644--- a/library/map/src/main/rust/shaders/line_globe.vert+++ b/library/map/src/main/rust/shaders/line_globe.vert@@ -32,6 +32,18 @@ layout(push_constant) uniform Push { const float MIN_HALF_WIDTH_PX = 0.5; const float PI = 3.141592653589793; +// Camera view rotation for the globe: m[3]/m[7] of the globe matrix carry+// the bearing/pitch (degrees). Must match `camera::globe_view_rotate`.+vec3 globeView(vec3 pt) {+    float vb = radians(push.tileToClip[0][3]);+    float vp = radians(push.tileToClip[1][3]);+    if (vb == 0.0 && vp == 0.0) return pt;+    float x1 = cos(vb) * pt.x - sin(vb) * pt.y;+    float y1 = sin(vb) * pt.x + cos(vb) * pt.y;+    return vec3(x1, cos(vp) * y1 - sin(vp) * pt.z, sin(vp) * y1 + cos(vp) * pt.z);+}++ void main() {     float ox = push.tileToClip[0][2];     float oy = push.tileToClip[1][2];@@ -76,13 +88,14 @@ void main() {     float ky = push.tileToClip[1][1] / max(r, 1e-6);     float hw = push.morph.y;     float hh = push.morph.w;+    vec3 v = globeView(vec3(x, y, z));     // 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 depth = clamp(1.0 - z, 0.0, 1.0);-    outZ = z;+    float cx = kx * (v.x * r) + (kx * hw - 1.0);+    float cyy = -(ky * (v.y * r)) + (ky * hh - 1.0);+    float depth = clamp(1.0 - v.z, 0.0, 1.0);+    outZ = v.z;     outDistancePx = inDistance * tilePx;-    if (z < 0.0) {+    if (v.z < 0.0) {         gl_Position = vec4(cx, cyy, 1.0, 1.0);     } else {         gl_Position = vec4(cx, cyy, depth, 1.0);
library/map/src/main/rust/shaders/moon.frag
diff --git a/library/map/src/main/rust/shaders/moon.frag b/library/map/src/main/rust/shaders/moon.fragindex d4c19ec1e1..075896a324 100644--- a/library/map/src/main/rust/shaders/moon.frag+++ b/library/map/src/main/rust/shaders/moon.frag@@ -55,14 +55,21 @@ void main() {     // Nearer (larger z) wins LESS, matching the globe tiles' depth regime.     gl_FragDepth = 1.0 - z * 0.5; -    // Invert the east/north/up basis (mirrors `globe_lonlat`).+    // Undo the camera view rotation (push.line.xy: bearing/pitch degrees;+    // mirrors `globe_view_unrotate`), then invert the east/north/up basis+    // (mirrors `globe_lonlat`). Shading keeps the view-frame normal above.+    float vb = radians(push.line.x);+    float vp = radians(push.line.y);+    float y1 = cos(vp) * en.y + sin(vp) * z;+    float z1 = -sin(vp) * en.y + cos(vp) * z;+    vec3 basis = vec3(cos(vb) * en.x + sin(vb) * y1, -sin(vb) * en.x + cos(vb) * y1, z1);     float cLatR = radians(push.color.y);     float sy = sin(cLatR);     float cy = cos(cLatR);-    float ey = cy * en.y + sy * z;-    float ez = -sy * en.y + cy * z;+    float ey = cy * basis.y + sy * basis.z;+    float ez = -sy * basis.y + cy * basis.z;     float lat = asin(clamp(ey, -1.0, 1.0)) * 180.0 / PI;-    float lon = push.color.x + atan(en.x, ez) * 180.0 / PI;+    float lon = push.color.x + atan(basis.x, ez) * 180.0 / PI;     lon = mod(lon + 180.0, 360.0) - 180.0;     vec2 uv = vec2((lon + 180.0) / 360.0, (90.0 - lat) / 180.0);     vec3 albedo = texture(moonColor, uv).rgb;
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 031666484a..584797253c 100644--- a/library/map/src/main/rust/shaders/road_surface_globe.vert+++ b/library/map/src/main/rust/shaders/road_surface_globe.vert@@ -28,6 +28,18 @@ layout(push_constant) uniform Push { const float MIN_HALF_WIDTH_PX = 0.5; const float PI = 3.141592653589793; +// Camera view rotation for the globe: m[3]/m[7] of the globe matrix carry+// the bearing/pitch (degrees). Must match `camera::globe_view_rotate`.+vec3 globeView(vec3 pt) {+    float vb = radians(push.tileToClip[0][3]);+    float vp = radians(push.tileToClip[1][3]);+    if (vb == 0.0 && vp == 0.0) return pt;+    float x1 = cos(vb) * pt.x - sin(vb) * pt.y;+    float y1 = sin(vb) * pt.x + cos(vb) * pt.y;+    return vec3(x1, cos(vp) * y1 - sin(vp) * pt.z, sin(vp) * y1 + cos(vp) * pt.z);+}++ void main() {     float ox = push.tileToClip[0][2];     float oy = push.tileToClip[1][2];@@ -64,14 +76,15 @@ void main() {     float ky = push.tileToClip[1][1] / max(r, 1e-6);     float hw = push.morph.y;     float hh = push.morph.w;+    vec3 v = globeView(vec3(x, y, z));     // 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 depth = clamp(1.0 - z, 0.0, 1.0);+    float cx = kx * (v.x * r) + (kx * hw - 1.0);+    float cyy = -(ky * (v.y * r)) + (ky * hh - 1.0);+    float depth = clamp(1.0 - v.z, 0.0, 1.0);     outT = inT;-    outZ = z;+    outZ = v.z;     outDistancePx = inDistance * tilePx;-    if (z < 0.0) {+    if (v.z < 0.0) {         gl_Position = vec4(cx, cyy, 1.0, 1.0);     } else {         gl_Position = vec4(cx, cyy, depth, 1.0);
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 6e17c13dbd..cbd2ce82e6 100644--- a/library/map/src/main/rust/shaders/symbol_globe.vert+++ b/library/map/src/main/rust/shaders/symbol_globe.vert@@ -29,6 +29,18 @@ layout(push_constant) uniform Push {  const float PI = 3.141592653589793; +// Camera view rotation for the globe: m[3]/m[7] of the globe matrix carry+// the bearing/pitch (degrees). Must match `camera::globe_view_rotate`.+vec3 globeView(vec3 pt) {+    float vb = radians(push.tileToClip[0][3]);+    float vp = radians(push.tileToClip[1][3]);+    if (vb == 0.0 && vp == 0.0) return pt;+    float x1 = cos(vb) * pt.x - sin(vb) * pt.y;+    float y1 = sin(vb) * pt.x + cos(vb) * pt.y;+    return vec3(x1, cos(vp) * y1 - sin(vp) * pt.z, sin(vp) * y1 + cos(vp) * pt.z);+}++ // Must match `camera::globe_point`. vec3 globeOf(float lon, float lat, float cLon, float cLat) {     float latR = radians(lat);@@ -71,11 +83,12 @@ void main() {     float m11 = push.tileToClip[1][1];     vec2 dTile = (inPosition - inAnchor) * (span * push.tileToClip[3][2] / max(r, 1e-6));     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 depth = clamp(1.0 - a.z, 0.0, 1.0);-    outZ = a.z;-    if (a.z < 0.0) {+    vec3 v = globeView(a);+    float ax = kx * (v.x * r) + (kx * hw - 1.0);+    float ay = -(ky * (v.y * r)) + (ky * hh - 1.0);+    float depth = clamp(1.0 - v.z, 0.0, 1.0);+    outZ = v.z;+    if (v.z < 0.0) {         gl_Position = vec4(ax, ay, 1.0, 1.0);     } else {         // Tile +y and clip +y both point down the screen, so the offset adds unflipped.
library/map/src/main/rust/src/camera.rs
diff --git a/library/map/src/main/rust/src/camera.rs b/library/map/src/main/rust/src/camera.rsindex cdf3a20005..074ff7e0c5 100644--- a/library/map/src/main/rust/src/camera.rs+++ b/library/map/src/main/rust/src/camera.rs@@ -216,6 +216,53 @@ pub fn globe_point(center_lon: f64, center_lat: f64, lon: f64, lat: f64) -> (f64     (x, y, z) } +/// Rotates a unit-sphere point from the centre-facing basis into the+/// camera's view frame: first the `bearing_deg` roll about the view axis (so+/// the named compass direction points up the screen), then the `pitch_deg`+/// tip about the screen-east axis (positive pitch tips the north of the+/// sphere toward the viewer and slips the camera target down-screen; the+/// disc stays centred on the viewport). Both zero is the identity,+/// bit-identical to the level globe. Mirrors the Kotlin `globeViewRotate`,+/// which must stay in step.+pub fn globe_view_rotate(+    x: f64,+    y: f64,+    z: f64,+    bearing_deg: f64,+    pitch_deg: f64,+) -> (f64, f64, f64) {+    if bearing_deg == 0.0 && pitch_deg == 0.0 {+        return (x, y, z);+    }+    let b = bearing_deg.to_radians();+    let (cos_b, sin_b) = (b.cos(), b.sin());+    let x1 = cos_b * x - sin_b * y;+    let y1 = sin_b * x + cos_b * y;+    let p = pitch_deg.to_radians();+    let (cos_p, sin_p) = (p.cos(), p.sin());+    (x1, cos_p * y1 - sin_p * z, sin_p * y1 + cos_p * z)+}++/// Inverse of [`globe_view_rotate`]. Mirrors the Kotlin `globeViewUnrotate`.+pub fn globe_view_unrotate(+    x: f64,+    y: f64,+    z: f64,+    bearing_deg: f64,+    pitch_deg: f64,+) -> (f64, f64, f64) {+    if bearing_deg == 0.0 && pitch_deg == 0.0 {+        return (x, y, z);+    }+    let p = pitch_deg.to_radians();+    let (cos_p, sin_p) = (p.cos(), p.sin());+    let y1 = cos_p * y + sin_p * z;+    let z1 = -sin_p * y + cos_p * z;+    let b = bearing_deg.to_radians();+    let (cos_b, sin_b) = (b.cos(), b.sin());+    (cos_b * x + sin_b * y1, -sin_b * x + cos_b * y1, z1)+}+ /// Inverse of [`globe_point`]: the lon/lat of a unit-sphere point in the /// centre-facing basis. Mirrors the Kotlin `globeLonLat`. pub fn globe_lonlat(center_lon: f64, center_lat: f64, x: f64, y: f64, z: f64) -> (f64, f64) {
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 f2994eeb83..de33fea1fe 100644--- a/library/map/src/main/rust/src/camera_globe.rs+++ b/library/map/src/main/rust/src/camera_globe.rs@@ -16,7 +16,11 @@ impl Camera {     ///     /// The translation column carries the camera centre lon/lat in m[12]/m[13]     /// (degrees) — the sphere basis every globe vertex shader needs — and the flat-    /// world width (Dp) in m[14], the scale flat tile-local sizes are measured in. It rides+    /// world width (Dp) in m[14], the scale flat tile-local sizes are measured in.+    /// The otherwise-unused m[3]/m[7] carry the camera bearing/pitch (degrees):+    /// every globe vertex shader rotates its unit-sphere point through+    /// [`globe_view_rotate`](crate::camera::globe_view_rotate) with them, so a+    /// twisted/tipped globe draws exactly what the Kotlin `Projection` projects. 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@@ -43,11 +47,11 @@ impl Camera {             (kx * r) as f32,             0.0,             ox as f32,-            0.0, //+            self.bearing_deg as f32, //             0.0,             (ky * r) as f32,             oy as f32,-            0.0, //+            self.pitch_deg as f32, //             0.0,             0.0,             span as f32,@@ -66,6 +70,7 @@ impl Camera {     /// the globe counterpart of [`screen_quad_to_clip`](Self::screen_quad_to_clip).     pub fn globe_anchor_to_screen(&self, lon: f64, lat: f64) -> Option<(f64, f64)> {         let (x, y, z) = crate::camera::globe_point(self.center_lon, self.center_lat, lon, lat);+        let (x, y, z) = crate::camera::globe_view_rotate(x, y, z, self.bearing_deg, self.pitch_deg);         if z < 0.0 {             return None;         }
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 c43d26a843..b2edaee921 100644--- a/library/map/src/main/rust/src/camera_globe_tests.rs+++ b/library/map/src/main/rust/src/camera_globe_tests.rs@@ -220,4 +220,54 @@ mod tests {             );         }     }++    #[test]+    fn the_view_rotation_is_identity_when_level() {+        let p = globe_view_rotate(0.3, -0.4, 0.8, 0.0, 0.0);+        assert_eq!(p, (0.3, -0.4, 0.8));+    }++    #[test]+    fn the_view_rotation_rolls_east_up_at_bearing_90() {+        // East (1, 0, 0) points up the screen: +y in the view frame.+        let (x, y, z) = globe_view_rotate(1.0, 0.0, 0.0, 90.0, 0.0);+        assert!(x.abs() < 1e-12 && (y - 1.0).abs() < 1e-12 && z.abs() < 1e-12, "{x} {y} {z}");+        // North points left.+        let (x, y, _) = globe_view_rotate(0.0, 1.0, 0.0, 90.0, 0.0);+        assert!((x + 1.0).abs() < 1e-12 && y.abs() < 1e-12, "{x} {y}");+    }++    #[test]+    fn the_view_rotation_tips_north_toward_the_viewer() {+        // North (0, 1, 0) under pitch: y shrinks toward the centre, z grows.+        let (_, y, z) = globe_view_rotate(0.0, 1.0, 0.0, 0.0, 30.0);+        assert!((y - 0.866_025_403_784_438_6).abs() < 1e-12, "y {y}");+        assert!((z - 0.5).abs() < 1e-12, "z {z}");+        // The centre (0, 0, 1) slips down-screen: negative y.+        let (_, y, _) = globe_view_rotate(0.0, 0.0, 1.0, 0.0, 30.0);+        assert!(y < 0.0, "y {y}");+    }++    #[test]+    fn the_view_rotation_round_trips_through_its_inverse() {+        let p = (0.3, -0.4, 0.8);+        let r = globe_view_rotate(p.0, p.1, p.2, 47.0, 31.0);+        let back = globe_view_unrotate(r.0, r.1, r.2, 47.0, 31.0);+        assert!(+            (back.0 - p.0).abs() < 1e-9+                && (back.1 - p.1).abs() < 1e-9+                && (back.2 - p.2).abs() < 1e-9+        );+        let len = r.0 * r.0 + r.1 * r.1 + r.2 * r.2;+        assert!((len - 0.89).abs() < 1e-9, "len {len}");+    }++    #[test]+    fn a_bearing_camera_anchors_east_above_the_centre() {+        let mut c = globe_camera(0.0, 0.0, 2.0);+        c.bearing_deg = 90.0;+        let (sx, sy) = c.globe_anchor_to_screen(20.0, 0.0).expect("east must project");+        assert!(sy < 256.0, "east should be above centre, sy {sy}");+        assert!((sx - 256.0).abs() < 1.0, "sx {sx}");+    } }
library/map/src/main/rust/src/tile/select/coverage.rs
diff --git a/library/map/src/main/rust/src/tile/select/coverage.rs b/library/map/src/main/rust/src/tile/select/coverage.rsindex c4a9fce48d..b4c9375558 100644--- a/library/map/src/main/rust/src/tile/select/coverage.rs+++ b/library/map/src/main/rust/src/tile/select/coverage.rs@@ -148,8 +148,10 @@ fn globe_visible(camera: &Camera, min_zoom: u8, max_zoom: u8) -> Vec<TileId> {             ]             .iter()             .any(|&(lon, lat)| {-                let (_, _, z) =+                let (x, y, z) =                     crate::camera::globe_point(camera.center_lon, camera.center_lat, lon, lat);+                let (_, _, z) =+                    crate::camera::globe_view_rotate(x, y, z, camera.bearing_deg, camera.pitch_deg);                 z >= 0.0             });             if near {
library/map/src/main/rust/src/vulkan/renderer/record_extra2_s1.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra2_s1.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra2_s1.rsindex 63c8fa6ff2..feb4e6d62f 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra2_s1.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra2_s1.rs@@ -417,12 +417,19 @@ impl Renderer {         // is culled above.         let Some(puck) = puck else { return };         if globe {-            let (_, _, z) = crate::camera::globe_point(+            let (px, py, pz) = crate::camera::globe_point(                 camera.center_lon,                 camera.center_lat,                 puck.lon,                 puck.lat,             );+            let (_, _, z) = crate::camera::globe_view_rotate(+                px,+                py,+                pz,+                camera.bearing_deg,+                camera.pitch_deg,+            );             if z < 0.0 {                 return;             }
library/map/src/main/rust/src/vulkan/renderer/record_moon.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_moon.rs b/library/map/src/main/rust/src/vulkan/renderer/record_moon.rsindex 1dd94c9570..e3e2b41b65 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_moon.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_moon.rs@@ -163,7 +163,8 @@ impl Renderer {             tile_to_clip: disc,             // xy: visible-hemisphere centre lon/lat (degrees) for the texture basis.             color: [camera.center_lon as f32, camera.center_lat as f32, 0.0, 1.0],-            line: [0.0; 4],+            // xy: camera bearing/pitch (degrees) for the fragment view rotation.+            line: [camera.bearing_deg as f32, camera.pitch_deg as f32, 0.0, 0.0],             // z: DEM relief strength (normal nudge per metre, tuned for the             // ±10km LDEM range at globe zoom).             misc: [0.0, 0.0, 0.02, camera.time_seconds],
library/map/src/test/java/com/vayunmathur/library/map/CameraGlobeGestureTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/CameraGlobeGestureTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/CameraGlobeGestureTest.ktnew file mode 100644index 0000000000..d584473115--- /dev/null+++ b/library/map/src/test/java/com/vayunmathur/library/map/CameraGlobeGestureTest.kt@@ -0,0 +1,198 @@+package com.vayunmathur.library.map++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Globe twist/tilt: the two-finger twist drives [CameraPosition.bearing] and the+ * two-finger vertical drag drives [CameraPosition.pitch] on an active globe,+ * exactly as on the flat map, and the globe [Projection] honours both so Compose+ * overlays stay glued to the sphere the renderer draws.+ */+class CameraGlobeGestureTest {++    private fun globeCamera(+        zoom: Double = 2.0,+        bearing: Double = 0.0,+        pitch: Double = 0.0,+    ): CameraState {+        val c = CameraState(CameraPosition(GeoPoint(0.0, 0.0), zoom, bearing, pitch))+        c.globeEnabled = true+        c.setViewport(Size(400f, 800f))+        return c+    }++    @Test+    fun globe_twist_turns_the_bearing() {+        val c = globeCamera()+        c.onGesture(+            centroidDp = Offset.Zero,+            panDp = Offset.Zero,+            zoomChange = 1f,+            rotationDeg = -20f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+        )+        assertEquals(20.0, c.position.bearing, 1e-6)+    }++    @Test+    fun globe_bearing_wraps_past_north() {+        val c = globeCamera()+        c.onRotate(350.0)+        c.onRotate(20.0)+        assertEquals(10.0, c.position.bearing, 1e-9)+    }++    @Test+    fun globe_tilt_raises_and_clamps_pitch() {+        val c = globeCamera()+        // Dragging up (negative dy) tilts into the view: 100 Dp up is 40 degrees.+        c.onTilt(-100f)+        assertEquals(40.0, c.position.pitch, 1e-9)+        c.onTilt(-10000f)+        assertEquals(MAX_PITCH, c.position.pitch, 1e-9)+        c.onTilt(10000f)+        assertEquals(0.0, c.position.pitch, 1e-9)+    }++    @Test+    fun globe_pan_and_zoom_preserve_bearing_and_pitch() {+        val c = globeCamera()+        c.onRotate(45.0)+        c.onTilt(-50f)+        c.onGesture(+            centroidDp = Offset(200f, 400f),+            panDp = Offset(30f, -10f),+            zoomChange = 1f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+        )+        assertEquals(45.0, c.position.bearing, 1e-9, "globe pan must not reset the bearing")+        assertEquals(20.0, c.position.pitch, 1e-9, "globe pan must not reset the pitch")+        c.onGesture(+            centroidDp = Offset(200f, 400f),+            panDp = Offset.Zero,+            zoomChange = 2f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+        )+        assertEquals(45.0, c.position.bearing, 1e-9, "globe zoom must not reset the bearing")+        assertEquals(20.0, c.position.pitch, 1e-9, "globe zoom must not reset the pitch")+    }++    @Test+    fun globe_rotate_gate_suppresses_only_rotation() {+        val c = globeCamera()+        c.onGesture(+            centroidDp = Offset(200f, 400f),+            panDp = Offset(20f, 0f),+            zoomChange = 1f,+            rotationDeg = -30f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+            rotateEnabled = false,+        )+        assertEquals(0.0, c.position.bearing, 1e-9)+        assertTrue(+            c.position.target.longitude != 0.0 || c.position.target.latitude != 0.0,+            "the globe pan must still apply while rotation is gated",+        )+    }++    @Test+    fun globe_bearing_rotates_the_projection() {+        // Bearing 90: east points up the screen, north points left.+        val c = globeCamera(bearing = 90.0)+        val proj = assertNotNull(c.projection)+        val east = proj.screenLocationFromPosition(GeoPoint(20.0, 0.0))+        assertTrue(east.y.value < 400f, "east should be above centre at bearing 90, was $east")+        val north = proj.screenLocationFromPosition(GeoPoint(0.0, 20.0))+        assertTrue(north.x.value < 200f, "north should be left of centre at bearing 90, was $north")+    }++    @Test+    fun globe_pitch_tips_the_sphere() {+        val level = assertNotNull(globeCamera().projection)+        val levelNorth = level.screenLocationFromPosition(GeoPoint(0.0, 40.0))+        val tipped = assertNotNull(globeCamera(pitch = 30.0).projection)+        val tippedCentre = tipped.screenLocationFromPosition(GeoPoint(0.0, 0.0))+        val tippedNorth = tipped.screenLocationFromPosition(GeoPoint(0.0, 40.0))+        assertTrue(+            tippedCentre.y.value > 400f,+            "the target should slip down-screen as the sphere tips, was $tippedCentre",+        )+        assertTrue(+            abs(tippedNorth.y.value - 400f) < abs(levelNorth.y.value - 400f),+            "a northern point should move toward the centre under pitch: $levelNorth -> $tippedNorth",+        )+    }++    @Test+    fun globe_projection_round_trips_under_bearing_and_pitch() {+        val c = globeCamera(bearing = 35.0, pitch = 25.0)+        val proj = assertNotNull(c.projection)+        val geo = GeoPoint(15.0, 25.0)+        val round = proj.positionFromScreenLocation(proj.screenLocationFromPosition(geo))+        assertEquals(geo.longitude, round.longitude, 1e-6)+        assertEquals(geo.latitude, round.latitude, 1e-6)+        // And the inverse direction: a screen point survives geo and back.+        val screen = DpOffset(260.dp, 300.dp)+        val back = proj.screenLocationFromPosition(proj.positionFromScreenLocation(screen))+        assertEquals(screen.x.value, back.x.value, 0.01f)+        assertEquals(screen.y.value, back.y.value, 0.01f)+    }++    @Test+    fun globe_view_rotate_identity_and_inverse() {+        val p = globeViewRotate(0.3, -0.4, 0.8, 0.0, 0.0)+        assertEquals(0.3, p.first, 1e-12)+        assertEquals(-0.4, p.second, 1e-12)+        assertEquals(0.8, p.third, 1e-12)+        val rotated = globeViewRotate(0.3, -0.4, 0.8, 47.0, 31.0)+        val back = globeViewUnrotate(rotated.first, rotated.second, rotated.third, 47.0, 31.0)+        assertEquals(0.3, back.first, 1e-9)+        assertEquals(-0.4, back.second, 1e-9)+        assertEquals(0.8, back.third, 1e-9)+        // Rotation preserves the unit length.+        val len = rotated.first * rotated.first + rotated.second * rotated.second ++            rotated.third * rotated.third+        assertEquals(0.3 * 0.3 + 0.4 * 0.4 + 0.8 * 0.8, len, 1e-9)+    }++    @Test+    fun bearing_and_pitch_survive_the_flat_threshold_crossing() {+        val c = globeCamera()+        c.onRotate(30.0)+        c.onTilt(-50f)+        // Zoom in past GLOBE_DETAIL_ZOOM: the flat path takes over with the+        // same bearing/pitch, no re-clamp jump.+        c.onGesture(+            centroidDp = Offset(200f, 400f),+            panDp = Offset.Zero,+            zoomChange = 64f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+        )+        assertTrue(c.position.zoom >= GLOBE_DETAIL_ZOOM, "zoom was ${c.position.zoom}")+        assertEquals(30.0, c.position.bearing, 1e-9)+        assertEquals(20.0, c.position.pitch, 1e-9)+    }+}