Modern Apps git

← Modern-Apps.git

maps: frame stats overlay plus twist-rotate camera

Commit
755a10510af5a9fba7a631b9648d0f598a022b09
Author
vayun-mathur <[email protected]>
When
2026-09-16 04:55 UTC (2 months ago)
Parents
80d5590

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 9aebbabebb..84e2e25516 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@@ -188,15 +188,23 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      * Applies a transform gesture, anchoring the geographic point under      * [centroidDp] so pinch-zoom keeps that point fixed. Deltas are in logical      * (dp) units.+     *+     * [rotationDeg] is the two-finger twist since the last event, in degrees+     * (Compose's `detectTransformGestures` convention: counterclockwise positive).+     * 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).      */     internal fun onGesture(         centroidDp: Offset,         panDp: Offset,         zoomChange: Float,+        rotationDeg: Float = 0f,         minZoom: Double,         maxZoom: Double,         scrollEnabled: Boolean,         zoomEnabled: Boolean,+        rotateEnabled: Boolean = true,     ) {         val vp = viewportDp ?: return         // Never zoom out past a full-screen world.@@ -224,9 +232,24 @@ class CameraState(initial: CameraPosition = CameraPosition()) {             }         } +        var bearing = position.bearing+        if (rotateEnabled && rotationDeg != 0f) {+            bearing = wrapBearing(bearing - rotationDeg * ROTATION_SENSITIVITY)+        }+         // `copy`, not a fresh `CameraPosition`: a gesture pans and zooms, and rebuilding         // the position from scratch would silently reset the bearing to north.-        position = position.copy(target = center, zoom = zoom)+        position = position.copy(target = center, zoom = zoom, bearing = bearing)+    }++    /**+     * 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.+     */+    internal fun onRotate(deltaDeg: Double) {+        if (deltaDeg == 0.0) return+        position = position.copy(bearing = wrapBearing(position.bearing + deltaDeg))     }      /**@@ -241,11 +264,22 @@ class CameraState(initial: CameraPosition = CameraPosition()) { }  /** Largest tilt the renderer supports, in degrees. Mirrors the native `PITCH_MAX_DEG` cap. */-const val MAX_PITCH: Double = 60.0+const val MAX_PITCH: Double = 65.0  /** Degrees of tilt per Dp of two-finger vertical drag: a ~150 Dp drag sweeps the full range. */ private const val PITCH_DEG_PER_DP = 0.4 +/**+ * How much of the twist gesture reaches the bearing: 1.0 tracks the fingers exactly.+ *+ * Below 1.0 would feel laggy against the fingers; above would overshoot them. The detector+ * reports the rotation since the last event, so this is a pure gain, not a threshold.+ */+private const val ROTATION_SENSITIVITY = 1.0f++/** Bearing wrapped to 0–360: spinning past north continues through it rather than clamping. */+internal fun wrapBearing(bearing: Double): Double = ((bearing % 360.0) + 360.0) % 360.0+ /** Zoom levels covered by a quick-zoom drag across the full viewport height. */ private const val QUICK_ZOOM_LEVELS_PER_VIEWPORT = 4.0 
library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.kt b/library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.ktnew file mode 100644index 0000000000..b5b7fc384e--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/FrameStatsOverlay.kt@@ -0,0 +1,88 @@+package com.vayunmathur.library.map++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.BasicText+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive++/**+ * The native step names in [MapNative.lastFrameStepTimesNanos] order.+ *+ * A mirror of the `Step::ALL` short names in `timing.rs` — adding a step there means+ * appending here. Counted rather than zipped: on drift ([times] shorter or longer) the+ * table shows `n/a` rows rather than mislabelling them.+ */+private val STEP_NAMES = listOf(+    "jni", "upl", "sel", "fen", "ret", "acq", "rec", "plc",+    "ter", "flt", "car", "bld", "sym", "trf", "arw", "msk",+    "ral", "ovl", "sub", "prs",+)++/**+ * The per-step frame-time table for the debug overlay: one monospace row per native step,+ * last frame's ms, polled from [MapNative.lastFrameStepTimesNanos].+ *+ * Off by default ([enabled]) so release pays nothing: no poll, no composition, no JNI. The+ * poll runs at ~3 Hz through [renderer]'s live handle and never touches the frame loop — it+ * reads the native copy rather than asking for a frame, so the overlay cannot keep the map+ * awake or change its pacing.+ *+ * @param renderer the live renderer to poll; a zero handle (no surface yet) reads as `n/a`.+ */+@Composable+fun FrameStatsOverlay(+    renderer: SurfaceMapRenderer,+    modifier: Modifier = Modifier,+    enabled: Boolean = false,+) {+    if (!enabled) return+    var times by remember { mutableStateOf(LongArray(0)) }+    LaunchedEffect(renderer) {+        while (isActive) {+            val handle = renderer.handle+            times = if (handle != 0L) {+                try {+                    MapNative.lastFrameStepTimesNanos(handle)+                } catch (_: Throwable) {+                    LongArray(0)+                }+            } else {+                LongArray(0)+            }+            delay(POLL_MILLIS)+        }+    }+    Box(+        modifier+            .background(Color(0xC0000000))+            .padding(6.dp),+    ) {+        Column {+            // Strings first, composables second: the rows are plain data, emitted below.+            for (i in STEP_NAMES.indices) {+                val name = STEP_NAMES[i]+                val ms = times.getOrNull(i)?.let { it / 1_000_000.0 }+                // One decimal, fixed width-ish: the table must not jitter while panning.+                val text = if (ms == null) "$name  n/a" else "$name %5.1f".format(ms)+                BasicText(text, style = TextStyle(color = Color.White, fontSize = 10.sp))+            }+        }+    }+}++/** How often the overlay polls the native copy: ~3 Hz, slow enough to cost nothing. */+private const val POLL_MILLIS = 333L
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 5a9e9fdb8f..312c08a706 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@@ -89,17 +89,19 @@ internal fun Modifier.mapGestures(             cameraState.setViewport(Size(it.width / density, it.height / density))         }         .pointerInput(cameraState, gestures, zoomRange, density) {-            detectTransformGestures { centroid, pan, zoom, _ ->-                if (!gestures.isScrollEnabled && !gestures.isZoomEnabled) return@detectTransformGestures+            detectTransformGestures { centroid, pan, zoom, rotation ->+                if (!gestures.isScrollEnabled && !gestures.isZoomEnabled && !gestures.isRotateEnabled) return@detectTransformGestures                 zoomAnim.value?.cancel()                 cameraState.onGesture(                     centroidDp = toDp(centroid),                     panDp = toDp(pan),                     zoomChange = zoom,+                    rotationDeg = rotation,                     minZoom = zoomRange.start.toDouble(),                     maxZoom = zoomRange.endInclusive.toDouble(),                     scrollEnabled = gestures.isScrollEnabled,                     zoomEnabled = gestures.isZoomEnabled,+                    rotateEnabled = gestures.isRotateEnabled,                 )             }         }
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex 89a1e39541..ecf584a01b 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -374,6 +374,16 @@ internal object MapNative {      */     external fun pickAt(handle: Long, xDp: Float, yDp: Float): Long +    /**+     * The last frame's per-step times in nanos, in native step order (see the `Step` enum's+     * `ALL` in `timing.rs`).+     *+     * For the debug overlay's slow poll (~2–4 Hz): a copy, so the render thread never blocks+     * on it. Empty when the handle is dead or nothing has been drawn yet. Must never drive+     * the frame loop.+     */+    external fun lastFrameStepTimesNanos(handle: Long): LongArray+     /**      * Destroy the renderer, wait for the GPU to go idle, and release the window.      *
library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.ktindex ead2ae4a9f..29e35d47cb 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt@@ -1,16 +1,18 @@ package com.vayunmathur.library.map  /**- * Which pan/zoom gestures are enabled. Rotation and tilt are unsupported (the- * map is always north-up), so there are no toggles for them.+ * Which pan/zoom/rotate gestures are enabled. Tilt (two-finger vertical drag) is always on+ * where the detector runs; rotation needs no separate detector, so it is one flag here.  */ data class GestureOptions(     val isScrollEnabled: Boolean = true,     val isZoomEnabled: Boolean = true,+    val isRotateEnabled: Boolean = true, ) {     companion object {-        /** Pan + zoom enabled; rotation/tilt unsupported anyway. */-        val RotationLocked = GestureOptions(isScrollEnabled = true, isZoomEnabled = true)+        /** Pan + zoom, rotation locked north-up (the old default behaviour). */+        val RotationLocked =+            GestureOptions(isScrollEnabled = true, isZoomEnabled = true, isRotateEnabled = false)          /** All gestures disabled (static map). */         val AllDisabled = GestureOptions(isScrollEnabled = false, isZoomEnabled = false)
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex 6775188024..09c85a9365 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -397,12 +397,15 @@ class SurfaceMapRenderer(         val position: CameraPosition         val widthDp: Float         val heightDp: Float-        // Forced to zero on the Compose path. `Projection` — and therefore every-        // `MapMarker`, pin and cluster positioned through it — is north-up only for bearing, so-        // honouring a bearing there would rotate the basemap out from under overlays that-        // did not rotate with it. Tilt is different: `Projection` is now pitch-aware (ray/plane),-        // so pitch *is* honoured on both paths and overlays follow it. Bearing is reachable-        // only through [camera], on a surface with no Compose overlays above it.+        // Forced to zero on the Compose path, even though CameraState now carries a+        // twist-gesture bearing: `Projection` — and therefore every `MapMarker`, pin+        // and cluster positioned through it — is north-up only for bearing, so honouring+        // one there would rotate the basemap out from under overlays that did not rotate+        // with it. The twist gesture still turns the state (the compass reads it), but the+        // Compose basemap stays north-up; only the overlay-free `[camera]` path below draws+        // it. Tilt is different: `Projection` is pitch-aware (ray/plane), so pitch *is*+        // honoured on both paths and overlays follow it. Bearing is reachable only through+        // [camera], on a surface with no Compose overlays above it.         val bearing: Float         val state = composeCamera         if (state != null) {
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 9dbea681ca..a37cce945c 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@@ -129,6 +129,12 @@ fun VectorMap(     onMapClickWithScreen: ((MapClick) -> Unit)? = null,     onFrame: () -> Unit = {},     fallback: @Composable (MapRenderState.Unavailable) -> Unit = {},+    /**+     * Show the per-step native frame-time table over the map. Off by default so release+     * pays nothing; a dev host passes true (e.g. from its `DEV_BUILD`). Polls the native+     * copy at ~3 Hz and never wakes the frame loop.+     */+    showFrameStats: Boolean = false,     content: @Composable MapScope.() -> Unit = {}, ) {     val density = LocalDensity.current.density@@ -197,6 +203,7 @@ fun VectorMap(             modifier = Modifier.fillMaxSize(),             onFrame = onFrame,             fallback = fallback,+            showFrameStats = showFrameStats,         )          if (imageOverlay != null) {
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex 4cb48830cb..46d23c6974 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -4,6 +4,8 @@ import android.content.Context import android.graphics.SurfaceTexture import android.view.Surface import android.view.TextureView+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect@@ -85,6 +87,12 @@ internal fun VulkanMapSurface(     modifier: Modifier = Modifier,     onFrame: () -> Unit = {},     fallback: @Composable (MapRenderState.Unavailable) -> Unit = {},+    /**+     * Show the per-step frame-time table ([FrameStatsOverlay]) over the surface. Off by+     * default so release pays nothing; a dev host passes true (e.g. from its `DEV_BUILD`).+     * The overlay polls the native copy and never wakes the frame loop.+     */+    showFrameStats: Boolean = false, ) {     val context = LocalContext.current     val density = LocalDensity.current.density@@ -221,17 +229,26 @@ internal fun VulkanMapSurface(         ConnectivityMonitor.isOnline.collect { renderer.setOnline(it) }     } -    AndroidView(-        factory = {-            TextureView(context).apply {-                // The map is opaque, so tell the compositor: a translucent TextureView is-                // blended every frame for nothing.-                isOpaque = true-                surfaceTextureListener = host-            }-        },-        modifier = modifier,-    )+    Box(modifier) {+        AndroidView(+            factory = {+                TextureView(context).apply {+                    // The map is opaque, so tell the compositor: a translucent TextureView is+                    // blended every frame for nothing.+                    isOpaque = true+                    surfaceTextureListener = host+                }+            },+            modifier = Modifier.fillMaxSize(),+        )++        // The debug table floats over the surface's top-start corner; gated inside, so+        // `false` composes nothing at all.+        FrameStatsOverlay(+            renderer = renderer,+            enabled = showFrameStats,+        )+    }      // Over the TextureView rather than instead of it: the listener that reports the failure     // only runs once the view is attached, so removing the view would remove the thing that
library/map/src/test/java/com/vayunmathur/library/map/CameraRotationTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/CameraRotationTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/CameraRotationTest.ktnew file mode 100644index 0000000000..6ca0d5a28e--- /dev/null+++ b/library/map/src/test/java/com/vayunmathur/library/map/CameraRotationTest.kt@@ -0,0 +1,170 @@+package com.vayunmathur.library.map++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The twist-rotate camera contract.+ *+ * The two-finger twist turns [CameraPosition.bearing], which wraps 0–360 rather than+ * clamping; pan and zoom never reset it (the position is `copy`ied, not rebuilt); the+ * rotate gate ([GestureOptions.isRotateEnabled]) suppresses only rotation; and the saver+ * round-trips the bearing alongside target/zoom/pitch. `animateTo`'s short-way turn is+ * pinned here too, since reset-north rides it.+ *+ * Plain JVM unit tests like [FrameLoopWakeTest]: `CameraState` is Compose snapshot state,+ * which reads and writes fine off-device as long as nothing composes it.+ */+class CameraRotationTest {++    private fun camera(): CameraState =+        CameraState().apply { setViewport(Size(400f, 800f)) }++    /** A no-op gesture: no pan, no zoom, no twist. */+    private fun CameraState.idle() {+        onGesture(+            centroidDp = Offset.Zero,+            panDp = Offset.Zero,+            zoomChange = 1f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+        )+    }++    @Test+    fun twist_turns_the_bearing() {+        val c = camera()+        // Compose reports twist counterclockwise-positive; the camera is clockwise, hence -20.+        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 bearing_wraps_past_north_both_ways() {+        val c = camera()+        c.onRotate(350.0)+        assertEquals(350.0, c.position.bearing, 1e-9)+        c.onRotate(20.0)+        assertEquals(10.0, c.position.bearing, 1e-9, "350 + 20 wraps through north to 10")+        c.onRotate(-30.0)+        assertEquals(340.0, c.position.bearing, 1e-9, "10 - 30 wraps the other way to 340")+    }++    @Test+    fun rotation_accumulates_across_gestures() {+        val c = camera()+        repeat(4) { c.onRotate(15.0) }+        assertEquals(60.0, c.position.bearing, 1e-9)+    }++    @Test+    fun pan_and_zoom_preserve_the_bearing() {+        val c = camera()+        c.onRotate(45.0)+        // A pan with no twist.+        c.onGesture(+            centroidDp = Offset(200f, 400f),+            panDp = Offset(10f, -5f),+            zoomChange = 1f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+        )+        assertEquals(45.0, c.position.bearing, 1e-9, "panning must not reset the bearing")+        // A zoom with no twist.+        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, "zooming must not reset the bearing")+    }++    @Test+    fun rotate_gate_suppresses_only_rotation() {+        val c = camera()+        c.onGesture(+            centroidDp = Offset(200f, 400f),+            panDp = Offset(10f, 0f),+            zoomChange = 1f,+            rotationDeg = -30f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = true,+            zoomEnabled = true,+            rotateEnabled = false,+        )+        assertEquals(0.0, c.position.bearing, absoluteTolerance = 1e-9)+        assertTrue(+            c.position.target.longitude != 0.0 || c.position.target.latitude != 0.0,+            "the pan must still apply while rotation is gated",+        )+    }++    @Test+    fun disabled_gestures_leave_the_camera_alone() {+        val c = camera()+        val before = c.position+        c.onGesture(+            centroidDp = Offset.Zero,+            panDp = Offset(50f, 50f),+            zoomChange = 2f,+            rotationDeg = -30f,+            minZoom = 0.0,+            maxZoom = 20.0,+            scrollEnabled = false,+            zoomEnabled = false,+            rotateEnabled = false,+        )+        assertEquals(before, c.position)+    }++    @Test+    fun zero_twist_is_a_no_op() {+        val c = camera()+        c.onRotate(30.0)+        val before = c.position+        c.onRotate(0.0)+        assertEquals(before, c.position)+        c.idle()+        assertEquals(before, c.position)+    }++    @Test+    fun wrap_bearing_normalises() {+        assertEquals(0.0, wrapBearing(0.0), 1e-9)+        assertEquals(0.0, wrapBearing(360.0), 1e-9)+        assertEquals(10.0, wrapBearing(370.0), 1e-9)+        assertEquals(350.0, wrapBearing(-10.0), 1e-9)+        assertEquals(180.0, wrapBearing(180.0), 1e-9)+    }++    @Test+    fun compass_hides_only_near_north() {+        // Mirrors CompassButton's own threshold (|normalized| < 1° hides): a bearing the+        // gesture can actually leave behind must read as rotated, and reset-north's 0.0+        // must read as north. (The button itself is untestable here — it composes.)+        assertTrue(abs(((10.0 + 180.0) % 360.0 + 360.0) % 360.0 - 180.0) >= 1.0)+        assertTrue(abs(((0.0 + 180.0) % 360.0 + 360.0) % 360.0 - 180.0) < 1.0)+    }+}