Modern Apps git

← Modern-Apps.git

maps: 3D buildings, terrain, pick buffer, LOD morph, curved labels

Commit
1afb65ed2718c0279a313a529a7976c397921d02
Author
vayun-mathur <[email protected]>
When
2026-09-10 05:19 UTC (2 months ago)
Parents
09d265d

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 4d26579b93..9aebbabebb 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@@ -20,14 +20,15 @@ import kotlin.math.log2 /**  * Where the camera is, and which way is up.  *- * [bearing] **defaults to zero**, so every existing call site, the saver, and the whole- * Compose path are unchanged: a north-up camera composes the same axis-aligned matrices it- * always did, and the overlays and image quad positioned against them stay correct.+ * [bearing] and [pitch] both **default to zero**, so every existing call site, the saver, and+ * the whole Compose path are unchanged until something tilts or rotates the camera: a north-up,+ * level camera composes exactly the axis-aligned matrices it always did.  *- * Tilt is still deliberately unsupported. A bearing is a rotation, which composes into the- * clip matrices as a 2x2 and leaves the projection orthographic; a tilt would make it- * perspective, and every screen-space measurement downstream — label boxes, the image- * quad, [Projection] itself — assumes it is not.+ * [bearing] is a rotation, which composes into the clip matrices as a plain 2x2 and is still+ * honoured only on the [SurfaceMapRenderer.camera] path, because the Compose overlays are laid+ * out north-up. [pitch] is the perspective tilt; unlike bearing it *is* honoured on the Compose+ * path, because [Projection] is now pitch-aware (ray/plane), so `MapMarker`s and pins follow the+ * tilt instead of floating off the ground.  */ data class CameraPosition(     val target: GeoPoint = GeoPoint(0.0, 0.0),@@ -39,12 +40,21 @@ data class CameraPosition(      * navigation is the one caller that sets it, through [SurfaceMapRenderer.camera].      *      * **Setting it on a [CameraState] does nothing.** The Compose path forces it to zero-     * before the frame, because [Projection] is north-up and everything positioned through-     * it — every `MapMarker`, pin and cluster — would stay put while the basemap turned+     * before the frame, because [Projection]'s bearing is north-up and everything positioned+     * through it — every `MapMarker`, pin and cluster — would stay put while the basemap turned      * underneath. Ignoring it is a visible no-op; honouring it would be a silent wrong      * render that nothing reports.      */     val bearing: Double = 0.0,+    /**+     * Camera tilt away from straight-down, in degrees, expected in `0.0..`[MAX_PITCH].+     *+     * Zero is the flat top-down map. Driven by the two-finger vertical-drag tilt gesture (see+     * `MapGestures`) and honoured on both the Compose and [SurfaceMapRenderer.camera] paths:+     * [Projection] intersects the eye ray with the ground plane, so overlays anchored through it+     * stay glued to their ground point under tilt.+     */+    val pitch: Double = 0.0, )  /**@@ -67,6 +77,14 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      */     internal var labelQueryProvider: ((DpRect, Set<String>) -> List<PlacedLabel>)? by mutableStateOf(null) +    /**+     * Marker pick provider: registered by the rendered surface (see `VulkanMapSurface`),+     * answering `(xDp, yDp) -> marker id` from the renderer's id buffer. Null until a surface+     * registers — a projection without a live renderer answers [pickMarker][Projection.pickMarker]+     * with `0` (nothing) rather than hitting a dead handle.+     */+    internal var markerPickProvider: ((Float, Float) -> Long)? by mutableStateOf(null)+     /**      * Sets the measured viewport and enforces the minimum "fill" zoom so the map      * always covers the viewport (no blank margins when zoomed all the way out),@@ -94,7 +112,7 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      */     val projection: Projection? by derivedStateOf {         viewportDp?.let { vp ->-            Projection(position.target, position.zoom, vp.width, vp.height, labelQueryProvider)+            Projection(position.target, position.zoom, vp.width, vp.height, position.pitch, labelQueryProvider, markerPickProvider)         }     } @@ -117,6 +135,7 @@ class CameraState(initial: CameraPosition = CameraPosition()) {                 ),                 zoom = lerp(start.zoom, target.zoom, t),                 bearing = start.bearing + turn * t,+                pitch = lerp(start.pitch, target.pitch, t),             )         }     }@@ -209,8 +228,24 @@ class CameraState(initial: CameraPosition = CameraPosition()) {         // the position from scratch would silently reset the bearing to north.         position = position.copy(target = center, zoom = zoom)     }++    /**+     * 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.+     */+    internal fun onTilt(deltaDp: Float) {+        val next = (position.pitch - deltaDp * PITCH_DEG_PER_DP).coerceIn(0.0, MAX_PITCH)+        if (next != position.pitch) position = position.copy(pitch = next)+    } } +/** Largest tilt the renderer supports, in degrees. Mirrors the native `PITCH_MAX_DEG` cap. */+const val MAX_PITCH: Double = 60.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+ /** Zoom levels covered by a quick-zoom drag across the full viewport height. */ private const val QUICK_ZOOM_LEVELS_PER_VIEWPORT = 4.0 @@ -234,7 +269,7 @@ private fun lerp(start: Double, end: Double, t: Double): Double = start + (end - /**  * Saves the camera across configuration change and process death.  *- * Only `(lon, lat, zoom, bearing)`: [CameraState.viewportDp] is re-measured by the next+ * Only `(lon, lat, zoom, bearing, pitch)`: [CameraState.viewportDp] is re-measured by the next  * layout pass and [CameraState.labelQueryProvider] is re-registered by the surface, so  * persisting either would restore a value that is immediately overwritten — and a stale  * viewport would produce a wrong projection for one frame.@@ -246,12 +281,20 @@ private val CameraStateSaver = listSaver<CameraState, Double>(             it.position.target.latitude,             it.position.zoom,             it.position.bearing,+            it.position.pitch,         )     },-    // `getOrElse` rather than `it[3]`: a bundle written before the bearing existed is-    // three long, and a restored camera is not worth an IndexOutOfBounds.+    // `getOrElse` rather than `it[n]`: a bundle written before the bearing or pitch existed is+    // three or four long, and a restored camera is not worth an IndexOutOfBounds.     restore = {-        CameraState(CameraPosition(GeoPoint(it[0], it[1]), it[2], it.getOrElse(3) { 0.0 }))+        CameraState(+            CameraPosition(+                GeoPoint(it[0], it[1]),+                it[2],+                it.getOrElse(3) { 0.0 },+                it.getOrElse(4) { 0.0 },+            )+        )     }, ) 
library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.ktindex f7116fe7a2..f6b1af5cc0 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt@@ -59,6 +59,17 @@ data class LayerOptions(      * a line that is red on the network map stays red on a dark basemap.      */     val transit: Boolean = false,+    /**+     * Live traffic: a per-component overlay coloured red/amber/green by live speeds.+     *+     * The geometry is a line layer baked into the archive (one segment per graph component+     * edge); the colours are not authored but pushed at runtime through+     * [SurfaceMapRenderer.setTrafficSpeeds] as a `component_id → ARGB` table. Gated at+     * tessellation like [poi]/[transit], so leaving it off costs nothing — only a navigation+     * view wants the whole drivable network drawn a second time. A segment with no pushed+     * colour draws nothing, so the basemap road shows through as the no-data look.+     */+    val traffic: Boolean = false, ) {     companion object {         /** The default: basemap only. */
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 f7acd261c5..5a9e9fdb8f 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@@ -13,6 +13,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerId import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.input.pointer.pointerInput@@ -102,6 +103,16 @@ internal fun Modifier.mapGestures(                 )             }         }+        // Declared after the transform detector so it sees pointer events first and can consume+        // a two-finger vertical drag out from under it, turning that gesture into a tilt instead+        // of a pan. A pinch (fingers moving apart / opposite) or a twist is left untouched, so+        // zoom still works.+        .pointerInput(cameraState, gestures, density) {+            if (!gestures.isScrollEnabled && !gestures.isZoomEnabled) {+                return@pointerInput+            }+            detectVerticalTiltGestures { dyPx -> 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.         .pointerInput(cameraState, gestures, zoomRange, density) {@@ -142,7 +153,67 @@ internal fun Modifier.mapGestures( }  /**- * Single-pointer tap gestures: [onTap], [onDoubleTap], and the "quick zoom" that+ * Two-finger vertical-drag tilt, reported to [onTilt] as the signed vertical movement in **px**+ * since the last event (down is positive). Mirrors Google Maps: both fingers dragged up together+ * tilts into the map, down flattens it.+ *+ * Claims the gesture only while both fingers move the same way vertically and vertically more+ * than horizontally — a parallel drag. A pinch (opposite vertical directions) or a mostly-+ * horizontal move is left unconsumed, so [detectTransformGestures] still gets its pinch-zoom and+ * single-finger pan. Sits alongside the transform detector; consuming the moves it claims is what+ * stops that detector from also panning on them.+ */+private suspend fun PointerInputScope.detectVerticalTiltGestures(onTilt: (Float) -> Unit) =+    awaitEachGesture {+        awaitFirstDown(requireUnconsumed = false)+        val previous = mutableMapOf<PointerId, Offset>()+        val slop = viewConfiguration.touchSlop+        var tilting = false+        var accumulated = 0f+        while (true) {+            val event = awaitPointerEvent()+            val pressed = event.changes.filter { it.pressed }+            if (pressed.isEmpty()) break+            // Only a two-finger gesture tilts. Any other count resets so a finger added or lifted+            // mid-gesture cannot leave a stale baseline that jumps the pitch.+            if (pressed.size != 2) {+                previous.clear()+                tilting = false+                accumulated = 0f+                continue+            }+            val a = pressed[0]+            val b = pressed[1]+            val pa = previous[a.id]+            val pb = previous[b.id]+            previous[a.id] = a.position+            previous[b.id] = b.position+            if (pa == null || pb == null) continue+            val dyA = a.position.y - pa.y+            val dyB = b.position.y - pb.y+            val dxA = a.position.x - pa.x+            val dxB = b.position.x - pb.x+            // Parallel and vertical: same vertical direction, each finger moving more up/down than+            // sideways. Rejects the pinch (dyA*dyB < 0) and the mostly-horizontal two-finger pan.+            val parallelVertical =+                dyA * dyB > 0f && abs(dyA) >= abs(dxA) && abs(dyB) >= abs(dxB)+            if (!parallelVertical) {+                tilting = false+                continue+            }+            val dy = (dyA + dyB) / 2f+            if (!tilting) {+                accumulated += dy+                if (abs(accumulated) < slop) continue+                tilting = true+            }+            a.consume()+            b.consume()+            onTilt(dy)+        }+    }++/** Single-pointer tap gestures: [onTap], [onDoubleTap], and the "quick zoom" that  * follows a double-tap the user holds and swipes — [onQuickZoomStart] then  * [onQuickZoom] with the tapped anchor and the signed vertical drag in px (down is  * positive). A gesture reports either a double-tap or a quick zoom, never both.
library/map/src/main/java/com/vayunmathur/library/map/MapMarker.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapMarker.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapMarker.ktindex 9e02e4b56d..be6da99e14 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapMarker.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapMarker.kt@@ -1,109 +1,43 @@ package com.vayunmathur.library.map -import androidx.compose.foundation.layout.LayoutScopeMarker-import androidx.compose.runtime.Composable-import androidx.compose.runtime.Stable-import androidx.compose.ui.Modifier-import androidx.compose.ui.layout.Layout-import androidx.compose.ui.unit.Density-import kotlin.math.roundToInt--/** Which part of a marker sits on its geographic position. */-enum class MarkerAnchor {-    /** The marker's centre. What a circular pin or a cluster chip wants. */-    Center,--    /** The middle of the marker's bottom edge. What a teardrop pin wants. */-    BottomCenter,-}- /**- * Receiver for [VectorMap]'s `content`, giving overlays a way to position themselves- * geographically instead of each host re-deriving screen coordinates.+ * A pin the renderer draws inside its own frame, glued to a ground position.+ *+ * The sprite counterpart of [UserPuck]: moved into the renderer so it pans and tilts in+ * lock-step with the basemap instead of trailing it by a frame the way a Compose overlay does.+ * A host passes a list to [VectorMap]'s `markers`; a tap resolves back to one through+ * [Projection.pickMarker], which returns the [id] set here.  *- * Four apps had independently reimplemented "put this Compose thing at this lat/lon", three- * of them with the same `offset(x - size/2, y - size/2)` arithmetic and one with a literal- * `DpOffset(35.dp, 35.dp)` for a 70 dp avatar. [MapMarker] is that, once.+ * @param id the host's own stable id for this pin, echoed back verbatim by+ *   [Projection.pickMarker] so the host maps a tap to its feature without matching on position.+ *   `0` is reserved by the pick path to mean "nothing", so avoid it for a real pin.+ * @param position the ground point the pin sits on.+ * @param icon which atlas icon to draw — one of [MarkerIcon].  */-@Stable-@LayoutScopeMarker-class MapScope internal constructor(private val cameraState: CameraState) {--    /**-     * The live projection, or null before the viewport is measured.-     *-     * Exposed because `findfamily`'s geofence circles are drawn in a `Canvas` and genuinely-     * need to project arbitrary points, not just anchor a composable. One caller does not-     * justify inventing a geo-aware draw scope, so it gets the projection directly — but-     * read it *inside* the draw lambda, not in composition, for the same reason [MapMarker]-     * reads it during placement.-     *-     * Nullable on purpose. It was previously common for hosts to write `projection!!`, which-     * is a live crash in the frames before the viewport is measured.-     */-    val projection: Projection?-        get() = cameraState.projection+data class MapMarker(+    val id: Long,+    val position: GeoPoint,+    val icon: Int,+) -    /**-     * Places [content] at [position] on the map.-     *-     * ## The projection is read during *placement*-     *-     * This is the one non-obvious correctness requirement here, and nothing enforces it, so:-     * `screenLocationFromPosition` is called inside the `layout {}` placement lambda. Never-     * hoist it into composition or into the measure block.-     *-     * Reading it in composition would make the camera a composition dependency, so every-     * marker's composition scope would invalidate on every frame of a pan — with a dense-     * cluster set that is strictly worse than the hand-rolled per-frame re-projection this-     * replaces. Reading it during placement makes the camera a *placement* dependency, so-     * Compose re-runs placement alone and skips both recomposition and measurement. It is-     * the same distinction as `Modifier.offset(x, y)` versus `Modifier.offset { }`.-     *-     * The symptom of getting this wrong is a frame-rate regression while panning, not a-     * failure, so it will not show up in a test.-     *-     * Measurement always happens; only placement is skipped when there is no projection yet-     * or the marker is wholly outside the viewport. Skipping measurement instead would make-     * the marker's size a function of the camera, which would reintroduce the per-frame-     * measure pass being avoided.-     */-    @Composable-    fun MapMarker(-        position: GeoPoint,-        modifier: Modifier = Modifier,-        anchor: MarkerAnchor = MarkerAnchor.Center,-        content: @Composable () -> Unit,-    ) {-        Layout(content = content, modifier = modifier) { measurables, constraints ->-            // Loosened: a marker is sized by its content, not stretched to the map.-            val childConstraints = constraints.copy(minWidth = 0, minHeight = 0)-            val placeables = measurables.map { it.measure(childConstraints) }-            val width = placeables.maxOfOrNull { it.width } ?: 0-            val height = placeables.maxOfOrNull { it.height } ?: 0--            // MeasureScope is a Density; PlacementScope is not, so capture it here.-            val density: Density = this-            // The map fills its parent, so the incoming maxima are the viewport in px and-            // this node sits at the parent's top-left — which makes the projected offset-            // directly usable as a placement offset.-            val viewportWidth = constraints.maxWidth-            val viewportHeight = constraints.maxHeight--            layout(width, height) {-                val projected = projection?.screenLocationFromPosition(position) ?: return@layout-                val originX = with(density) { projected.x.toPx() }.roundToInt()-                val originY = with(density) { projected.y.toPx() }.roundToInt()-                val x = originX - width / 2-                val y = when (anchor) {-                    MarkerAnchor.Center -> originY - height / 2-                    MarkerAnchor.BottomCenter -> originY - height-                }-                val offscreen = x + width < 0 || y + height < 0 ||-                    x > viewportWidth || y > viewportHeight-                if (offscreen) return@layout-                placeables.forEach { it.place(x, y) }-            }-        }-    }+/**+ * The marker icon ids, mirroring the renderer's `crate::marker::icon` table. Passed as an int+ * across the JNI boundary (see [MapNative.setMarkers]); the renderer resolves each to a sprite in+ * the shared atlas.+ *+ * The pin ids are the app's own; the vehicle ids are reserved for the transit-vehicle overlay+ * (WS-F) so a mode resolves to a sprite through the same table. An id the renderer does not know+ * simply draws nothing, so adding one here without the native side is a no-op rather than a crash.+ */+object MarkerIcon {+    const val PARKING = 0+    const val TRANSIT_STOP = 1+    const val SEARCH = 2+    const val SAVED = 3+    const val FAMILY = 4++    const val VEHICLE_BUS = 5+    const val VEHICLE_TRAM = 6+    const val VEHICLE_TRAIN = 7+    const val VEHICLE_FERRY = 8 }
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 d84454c95e..3b919e492b 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@@ -63,6 +63,12 @@ internal object MapNative {      * [bearing] is degrees clockwise from north for whatever points up the screen. Zero      * is north-up, which is every frame the Compose path draws; the native side      * short-circuits it, so a north-up frame composes exactly the matrices it always did.+     *+     * [pitch] is the tilt away from straight-down in degrees; the native side clamps it to the+     * supported band and short-circuits zero, so a level camera is byte-for-byte unchanged.+     * [frameTimeNanos] is the Choreographer frame clock, forwarded to shaders (dash phase, LOD+     * morph, vehicle interpolation) through a push-constant slot; the native side reduces it+     * modulo an hour before it becomes a float.      */     external fun render(         handle: Long,@@ -70,9 +76,11 @@ internal object MapNative {         centerLat: Float,         zoom: Float,         bearing: Float,+        pitch: Float,         widthDp: Float,         heightDp: Float,         density: Float,+        frameTimeNanos: Long,     ): Boolean      external fun resize(handle: Long, width: Int, height: Int)@@ -104,6 +112,41 @@ internal object MapNative {      */     external fun setLayers(handle: Long, poi: Boolean, transit: Boolean, kinds: String) +    /**+     * Turn the live-traffic overlay on or off.+     *+     * Gated at tessellation like [setLayers], so an archive without the traffic layer — or a+     * consumer that never enables it — costs nothing: turning it on invalidates the resident+     * meshes and they re-tessellate on the worker pool with the traffic layer, and turning it+     * off stops drawing at once and drops the geometry on the next re-tessellation. The+     * per-segment colours arrive separately through [setTrafficSpeeds].+     *+     * Its own entry point rather than a fourth argument to [setLayers] so the existing layer+     * call keeps its shape for the five consumers that never draw traffic.+     */+    external fun setTrafficEnabled(handle: Long, enabled: Boolean)++    /**+     * Push the live-traffic colour table. [ids] holds each drawn segment's `component_id` and+     * [argbColors] the fully-resolved ARGB the host wants drawn for it, index for index. The+     * host owns the theme, so the colours are final; the renderer only looks them up per frame.+     *+     * Two parallel arrays rather than a packed buffer: it is what the caller already has (a+     * `LongArray` of ids and an `IntArray` of colours), and it crosses the boundary in two bulk+     * reads with no per-element JNI traffic. The whole table is replaced each call — a stale id+     * left behind would colour a road the latest data no longer covers. A segment whose id is+     * absent draws nothing, so the basemap road shows through as the no-data look. Mismatched+     * lengths are truncated to the shorter. This is a pure recolour: no tessellation, no upload.+     */+    external fun setTrafficSpeeds(handle: Long, ids: LongArray, argbColors: IntArray)++    /**+     * Drop every pushed traffic colour so the overlay stops drawing on the next frame, without+     * waiting for a toggle-off re-tessellation to evict the geometry. What the host calls when+     * the viewport moves off the squares it has readings for, or the toggle goes off.+     */+    external fun clearTraffic(handle: Long)+     /**      * Tell the renderer whether the device is online. When offline it serves stale cached      * ranges instead of attempting a request, so a previously-viewed area keeps drawing.@@ -135,35 +178,84 @@ internal object MapNative {     /** Take the puck away: no fix, or a host that stopped asking for one. */     external fun clearUserPuck(handle: Long) +    /**+     * Replace the app's pins with a marker set the renderer draws as billboarded sprites.+     *+     * [ids] holds each marker's stable host id (echoed back by [pickAt]), [lonLat] is a flat+     * `[lon0, lat0, lon1, lat1, …]`, and [icons] is each marker's icon id (see the native+     * `crate::marker::icon` table: parking/transit/search/saved/family, plus the transit-vehicle+     * ids WS-F reuses). Three parallel bulk arrays, the same convention as [setRoute] and+     * [setTrafficSpeeds]: a viewport of pins crosses the boundary in a few reads with no per-pin+     * traffic. `Float` coordinates for the same reason [render]'s are.+     *+     * Free in the [setPalette] sense: the geometry is the shared unit quad billboarded per marker,+     * so nothing is tessellated or uploaded. The whole set is replaced each call — a stale pin left+     * behind would pick wrong. Moving the pins into the renderer is what stops them trailing the+     * basemap on a pan or tilt. Mismatched array lengths are truncated to the shortest; an empty set+     * is the same as [clearMarkers].+     */+    external fun setMarkers(handle: Long, ids: LongArray, lonLat: FloatArray, icons: IntArray)++    /** Take every marker away: the host cleared its pins. */+    external fun clearMarkers(handle: Long)++    /**+     * Replace the simulated transit vehicles with a set the renderer draws as billboarded sprites.+     *+     * The same three parallel bulk arrays as [setMarkers] — [ids] each vehicle's stable per-trip id,+     * [lonLat] a flat `[lon0, lat0, lon1, lat1, …]`, and [icons] each vehicle's mode sprite id (the+     * `VEHICLE_*` entries in [MarkerIcon]) — because a vehicle is a marker whose icon names a mode+     * sprite, so it reuses the marker draw path verbatim.+     *+     * Separate from [setMarkers] so the app's ~1 Hz vehicle recompute replaces only the vehicles and+     * leaves the pins untouched, and so the moving vehicle sprites stay out of the pin id-buffer pick+     * (they are not tap targets). Free in the [setPalette] sense: the geometry is the shared unit+     * quad billboarded per vehicle, so nothing is tessellated or uploaded. The whole set is replaced+     * each call — a trip that ended, left the bbox, or was cancelled must drop out rather than+     * linger. Mismatched array lengths are truncated to the shortest; an empty set is the same as+     * [clearVehicles].+     */+    external fun setVehicles(handle: Long, ids: LongArray, lonLat: FloatArray, icons: IntArray)++    /** Take every simulated vehicle away: the transit toggle went off, or the surface was hidden. */+    external fun clearVehicles(handle: Long)+     /**      * Draw a navigation route line over the basemap and under the puck.      *-     * [points] is a flat `[lon0, lat0, lon1, lat1, …]` array — one array rather than a-     * list of objects because a route is thousands of points and a per-point crossing is-     * exactly what this boundary exists to avoid. `Float` for the same reason [render]'s-     * coordinates are. A trailing odd element is ignored, and fewer than two distinct-     * points draws nothing.+     * [points] is a flat `[lon0, lat0, lon1, lat1, …]` array holding every coloured+     * segment's points concatenated; [segmentLengths] is the point count of each segment+     * in order, and [segmentColors] the ARGB fill of each, index for index. Three bulk+     * arrays rather than a list of objects because a route is thousands of points and a+     * per-point crossing is exactly what this boundary exists to avoid. `Float` for the+     * coordinates for the same reason [render]'s are.      *-     * One polyline and one colour, which is what the consumer draws — see [RouteStyle].+     * A **list of coloured segments** with one shared casing — the phone's per-step+     * colouring (traffic bands, transit brand colours, the travelled grey during nav) is+     * produced on the device and pushed here, so the route pans in lock-step with the+     * basemap. A single-colour route (Android Auto) is a one-segment list. See [RouteStyle].      *-     * Not free, but paid **once**: the native side tessellates the polyline on the calling-     * thread and uploads it. It never rebuilds it after that — the mesh is normalised into+     * Not free, but paid **once**: the native side tessellates the segments on the calling+     * thread and uploads them. It never rebuilds after that — the mesh is normalised into      * the route's own bounding square, and Web Mercator is a pure scale in zoom, so the      * same vertices are correct at every zoom and only the matrix changes per frame. A-     * navigation session therefore costs one tessellation, not one per zoom step, which is-     * the difference that matters on a car's power budget.+     * navigation session therefore costs one tessellation per push, not one per zoom step.      *-     * An array that cannot be read leaves the route **unchanged** rather than clearing it:-     * a bad frame of route data must not blank a route being followed.+     * Arrays that cannot be read leave the route **unchanged** rather than clearing it:+     * a bad frame of route data must not blank a route being followed. A segment of fewer+     * than two distinct points draws nothing, and a route with no drawable segment is the+     * same as [clearRoute]. Mismatched [segmentLengths]/[segmentColors] lengths are+     * truncated to the shorter.      *      * Widths are Dp and colours are ARGB, like everything else here.      */     external fun setRoute(         handle: Long,         points: FloatArray,+        segmentLengths: IntArray,+        segmentColors: IntArray,         widthDp: Float,         casingDp: Float,-        color: Int,         casingColor: Int,     ) @@ -215,6 +307,17 @@ internal object MapNative {         y1Dp: Float,     ): Array<String> +    /**+     * Pick the renderer-drawn marker under a tap via the GPU id buffer.+     *+     * [xDp]/[yDp] are Dp from the viewport top-left. Returns the tapped marker's own id — the value+     * set on it in [setMarkers] — so the caller rejoins the tap to its feature without matching on+     * position, or `0` when no marker was hit. Unlike a Compose CPU hit-test this stays correct+     * under tilt and never trails the basemap on a pan, because it reads back the same id the+     * renderer drew for the frame under the finger.+     */+    external fun pickAt(handle: Long, xDp: Float, yDp: Float): Long+     /**      * Destroy the renderer, wait for the GPU to go idle, and release the window.      *
library/map/src/main/java/com/vayunmathur/library/map/MapScope.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapScope.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapScope.ktnew file mode 100644index 0000000000..7d5842a3cd--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapScope.kt@@ -0,0 +1,92 @@+package com.vayunmathur.library.map++import androidx.compose.foundation.layout.LayoutScopeMarker+import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.ui.Modifier+import androidx.compose.ui.layout.Layout+import androidx.compose.ui.unit.Density+import kotlin.math.roundToInt++/** Which part of a marker sits on its geographic position. */+enum class MarkerAnchor {+    /** The marker's centre. What a circular pin or a cluster chip wants. */+    Center,++    /** The middle of the marker's bottom edge. What a teardrop pin wants. */+    BottomCenter,+}++/**+ * Receiver for [VectorMap]'s `content`, giving Compose overlays a way to position themselves+ * geographically instead of each host re-deriving screen coordinates.+ *+ * This is the Compose-overlay path: content placed here is a second, unsynchronised pass that+ * lags the basemap by a frame while panning. Renderer-drawn pins that must stay glued under+ * pan/tilt go through [VectorMap]'s `markers` (the [MapMarker] data class) instead; this scope+ * is for arbitrary Compose content (avatars, geofence canvases, clusters) that a sprite atlas+ * cannot express.+ */+@Stable+@LayoutScopeMarker+class MapScope internal constructor(private val cameraState: CameraState) {++    /**+     * The live projection, or null before the viewport is measured.+     *+     * Exposed because `findfamily`'s geofence circles are drawn in a `Canvas` and genuinely+     * need to project arbitrary points, not just anchor a composable. Read it *inside* the+     * draw lambda, not in composition, for the same reason [MapMarker] reads it during+     * placement. Nullable on purpose: it is null in the frames before the viewport is measured.+     */+    val projection: Projection?+        get() = cameraState.projection++    /**+     * Places [content] at [position] on the map.+     *+     * The projection is read during *placement* (inside the `layout {}` lambda), never in+     * composition or measurement: that makes the camera a placement dependency, so a pan+     * re-runs placement alone and skips recomposition and measurement. Hoisting the projection+     * read into composition reintroduces a per-frame recomposition of every marker; the symptom+     * is a pan frame-rate regression, not a failure, so nothing catches it in a test.+     */+    @Composable+    fun MapMarker(+        position: GeoPoint,+        modifier: Modifier = Modifier,+        anchor: MarkerAnchor = MarkerAnchor.Center,+        content: @Composable () -> Unit,+    ) {+        Layout(content = content, modifier = modifier) { measurables, constraints ->+            // Loosened: a marker is sized by its content, not stretched to the map.+            val childConstraints = constraints.copy(minWidth = 0, minHeight = 0)+            val placeables = measurables.map { it.measure(childConstraints) }+            val width = placeables.maxOfOrNull { it.width } ?: 0+            val height = placeables.maxOfOrNull { it.height } ?: 0++            // MeasureScope is a Density; PlacementScope is not, so capture it here.+            val density: Density = this+            // The map fills its parent, so the incoming maxima are the viewport in px and this+            // node sits at the parent's top-left — which makes the projected offset directly+            // usable as a placement offset.+            val viewportWidth = constraints.maxWidth+            val viewportHeight = constraints.maxHeight++            layout(width, height) {+                val projected = projection?.screenLocationFromPosition(position) ?: return@layout+                val originX = with(density) { projected.x.toPx() }.roundToInt()+                val originY = with(density) { projected.y.toPx() }.roundToInt()+                val x = originX - width / 2+                val y = when (anchor) {+                    MarkerAnchor.Center -> originY - height / 2+                    MarkerAnchor.BottomCenter -> originY - height+                }+                val offscreen = x + width < 0 || y + height < 0 ||+                    x > viewportWidth || y > viewportHeight+                if (offscreen) return@layout+                placeables.forEach { it.place(x, y) }+            }+        }+    }+}
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 38a9f08021..79e476b3f5 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@@ -3,6 +3,8 @@ package com.vayunmathur.library.map import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.dp+import kotlin.math.cos+import kotlin.math.sin  /**  * One tile-baked placed label hit by [Projection.queryRenderedLabels].@@ -35,7 +37,7 @@ data class PlacedLabel( )  /**- * Immutable snapshot of the camera (center + zoom) and viewport used to map+ * Immutable snapshot of the camera (center + zoom + pitch) and viewport used to map  * between geographic [GeoPoint]s and on-screen [DpOffset]s. Mirrors the subset  * of maplibre-compose's projection API the apps call, so migration is an  * import swap.@@ -43,6 +45,12 @@ data class PlacedLabel(  * The map center projects to the viewport center; offsets are density  * independent (`Dp`) and measured from the viewport's top-left corner.  *+ * At [pitchDeg] `== 0` this is the plain orthographic inverse it always was. When tilted it+ * mirrors the native perspective in `camera::Camera` exactly — [screenLocationFromPosition]+ * projects through the same divide, [positionFromScreenLocation] intersects the eye ray with the+ * ground plane — so Compose overlays land where the renderer drew the basemap under them. Bearing+ * is not carried here: the Compose path renders north-up, so a projection for it does too.+ *  * [labelQuery] answers [queryRenderedLabels]: null until a rendered surface  * registers one (see `VulkanMapSurface`), so a projection without a live  * renderer answers empty rather than crashing.@@ -52,34 +60,99 @@ class Projection internal constructor(     private val zoom: Double,     private val widthDp: Float,     private val heightDp: Float,+    private val pitchDeg: Double = 0.0,     private val labelQuery: ((DpRect, Set<String>) -> List<PlacedLabel>)? = null,+    private val markerPick: ((Float, Float) -> Long)? = null, ) {+    private val halfW = widthDp / 2.0+    private val halfH = heightDp / 2.0+    // Perspective constants, mirroring `camera::Camera::perspective` so this agrees with what the+    // renderer drew. `d` (camera-to-centre distance) cancels at pitch 0, so it only sets the+    // foreshortening strength; only used on the tilted branches below.+    private val d = 1.5 * heightDp+    private val fx = d / halfW+    private val fy = d / halfH+     /** Screen location (from the viewport top-left) of a geographic [position]. */     fun screenLocationFromPosition(position: GeoPoint): DpOffset {         val c = Mercator.project(center.longitude, center.latitude, zoom)         val p = Mercator.project(position.longitude, position.latitude, zoom)-        val x = (p.x - c.x) + widthDp / 2.0-        val y = (p.y - c.y) + heightDp / 2.0-        return DpOffset(x.toFloat().dp, y.toFloat().dp)+        val sx = p.x - c.x+        val sy = p.y - c.y+        if (pitchDeg == 0.0) {+            return DpOffset((sx + halfW).toFloat().dp, (sy + halfH).toFloat().dp)+        }+        val pitch = Math.toRadians(pitchDeg)+        val psin = sin(pitch)+        val pcos = cos(pitch)+        val w = d - psin * sy+        // Behind the eye — only past the horizon, which the pitch cap keeps off-screen. Push it+        // far off rather than dividing by a non-positive w.+        if (w <= 0.0) return DpOffset((-1e5f).dp, (-1e5f).dp)+        val screenX = halfW + (fx * sx / w) * halfW+        val screenY = halfH + (fy * pcos * sy / w) * halfH+        return DpOffset(screenX.toFloat().dp, screenY.toFloat().dp)     } -    /** Geographic position under a screen [offset] (from the viewport top-left). */+    /**+     * Geographic position under a screen [offset] (from the viewport top-left).+     *+     * The tilted branch intersects the eye ray with the flat ground **plane**, ignoring terrain+     * elevation: over relief this leaves a bounded vertical error, which is fine for gestures+     * (pan/anchor follow the finger approximately). Exact ground/feature hits under tilt go through+     * the GPU instead — label picks via `pickLabels` and precise hits via `pickAt`'s id/depth+     * readback — both of which are terrain-correct because they read what was actually drawn.+     */     fun positionFromScreenLocation(offset: DpOffset): GeoPoint {         val c = Mercator.project(center.longitude, center.latitude, zoom)-        val x = c.x + (offset.x.value - widthDp / 2.0)-        val y = c.y + (offset.y.value - heightDp / 2.0)-        return Mercator.unproject(x, y, zoom)+        val sx: Double+        val sy: Double+        if (pitchDeg == 0.0) {+            sx = offset.x.value - halfW+            sy = offset.y.value - halfH+        } else {+            val pitch = Math.toRadians(pitchDeg)+            val psin = sin(pitch)+            val pcos = cos(pitch)+            val ndcX = (offset.x.value - halfW) / halfW+            val ndcY = (offset.y.value - halfH) / halfH+            // Invert clip.y = fy*cos*sy / (d - sin*sy) for sy, then clip.x for sx. The denominator+            // only vanishes at/above the horizon, which the pitch cap keeps off-screen; clamp to a+            // tiny positive so a query exactly on it maps far away rather than to a NaN.+            val denom = (fy * pcos + ndcY * psin).coerceAtLeast(1e-6)+            sy = ndcY * d / denom+            val w = d - psin * sy+            sx = ndcX * w / fx+        }+        return Mercator.unproject(c.x + sx, c.y + sy, zoom)     }      /** The lon/lat bounds of the currently visible viewport. */     fun queryVisibleBoundingBox(): GeoBounds {-        val topLeft = positionFromScreenLocation(DpOffset(0.dp, 0.dp))-        val bottomRight = positionFromScreenLocation(DpOffset(widthDp.dp, heightDp.dp))+        if (pitchDeg == 0.0) {+            val topLeft = positionFromScreenLocation(DpOffset(0.dp, 0.dp))+            val bottomRight = positionFromScreenLocation(DpOffset(widthDp.dp, heightDp.dp))+            return GeoBounds(+                west = topLeft.longitude,+                south = bottomRight.latitude,+                east = bottomRight.longitude,+                north = topLeft.latitude,+            )+        }+        // Tilted: the visible ground is a trapezoid, so take the AABB of all four screen corners'+        // ground points. The top edge recedes toward the horizon, so this box is larger than the+        // untilted one — correctly, since that ground really is on screen.+        val corners = listOf(+            positionFromScreenLocation(DpOffset(0.dp, 0.dp)),+            positionFromScreenLocation(DpOffset(widthDp.dp, 0.dp)),+            positionFromScreenLocation(DpOffset(0.dp, heightDp.dp)),+            positionFromScreenLocation(DpOffset(widthDp.dp, heightDp.dp)),+        )         return GeoBounds(-            west = topLeft.longitude,-            south = bottomRight.latitude,-            east = bottomRight.longitude,-            north = topLeft.latitude,+            west = corners.minOf { it.longitude },+            south = corners.minOf { it.latitude },+            east = corners.maxOf { it.longitude },+            north = corners.maxOf { it.latitude },         )     } @@ -94,4 +167,15 @@ class Projection internal constructor(      */     fun queryRenderedLabels(box: DpRect, layerIds: Set<String>): List<PlacedLabel> =         labelQuery?.invoke(box, layerIds) ?: emptyList()++    /**+     * The [MapMarker.id] of the renderer-drawn pin under a tap at ([xDp], [yDp]) (Dp from the+     * viewport top-left), or `0` when the tap hit no pin.+     *+     * The marker counterpart of [queryRenderedLabels]: it reads the renderer's GPU id buffer, so a+     * pin stays tappable under tilt — where its screen box is no longer a plain projection of its+     * lon/lat — and never trails the basemap on a pan. Registered by `VulkanMapSurface`, so this is+     * `0` only when nothing is under the finger or no rendered surface is live.+     */+    fun pickMarker(xDp: Float, yDp: Float): Long = markerPick?.invoke(xDp, yDp) ?: 0L }
library/map/src/main/java/com/vayunmathur/library/map/RouteOverlay.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/RouteOverlay.kt b/library/map/src/main/java/com/vayunmathur/library/map/RouteOverlay.ktnew file mode 100644index 0000000000..91ed5f17a4--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/RouteOverlay.kt@@ -0,0 +1,39 @@+package com.vayunmathur.library.map++import androidx.compose.ui.graphics.Color++/**+ * A navigation route drawn inside the renderer's frame, so it pans in lock-step with the+ * basemap the way the puck, region mask and traffic already do.+ *+ * A route is a list of [segments], each its own polyline and fill [colour][RouteSegment.color]+ * — a driving route split into traffic bands, a transit route into per-line colours, an+ * active navigation leg into a travelled grey behind the puck and the mode colour ahead. The+ * renderer strokes them into one mesh, draws a single continuous casing over the whole thing,+ * then paints each segment's fill over it. [style] carries what the segments share: the line+ * width and the casing.+ *+ * A plain single-colour route is just a one-segment list:+ * `RouteOverlay(listOf(RouteSegment(points, Color(0xFF1A73E8))))`. `null` (or an all-empty+ * list) draws nothing, which is how a route is cleared. Pushed into the renderer through+ * [VectorMap]'s `route` parameter, out of band from the frame loop.+ */+data class RouteOverlay(+    val segments: List<RouteSegment>,+    val style: RouteStyle = RouteStyle(),+) {+    /** True when there is nothing to draw, which the surface treats the same as `null`. */+    fun isEmpty(): Boolean = segments.all { it.points.size < 2 }+}++/**+ * One coloured run of a [RouteOverlay]: a polyline and the colour its fill is painted.+ *+ * [points] are lon-first ([GeoPoint]), in order. Each run carries its whole polyline,+ * including the point it shares with its neighbours, so the strokes meet end to end under the+ * shared casing. A run of fewer than two distinct points draws nothing.+ */+data class RouteSegment(+    val points: List<GeoPoint>,+    val color: Color,+)
library/map/src/main/java/com/vayunmathur/library/map/RouteStyle.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/RouteStyle.kt b/library/map/src/main/java/com/vayunmathur/library/map/RouteStyle.ktindex 7b85d1ac07..c6100cbfaa 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/RouteStyle.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/RouteStyle.kt@@ -24,23 +24,24 @@ import androidx.compose.ui.unit.dp  * 1.0, `6.dp` at density 2.0, and nobody knows which unit it was tuned on. Any Dp value  * picked from it silently chooses one density to be correct at.  *- * So it is not picked from it. `8.dp` is `maps/src/main/java/com/vayunmathur/maps/ui/- * RouteLayer.kt:52`, the phone's route width — the only density-correct route width in- * this app, chosen by someone looking at the result. The casing keeps the reference's- * proportion, which had the casing half again as wide as the line.+ * So it is not picked from it. `8.dp` is the phone's route width — set in+ * `maps/src/main/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilder.kt`, the only+ * density-correct route width in this app, chosen by someone looking at the result. The+ * casing keeps the reference's proportion, which had the casing half again as wide as the+ * line.  *  * A head unit is read at about 70 cm against a phone's 30 cm, so there is a real argument  * for going wider than the phone here. Nobody has seen this on a head unit yet, so that  * argument has not been acted on: this is the grounded number, and widening it is a  * deliberate change someone should make while looking at one.  *- * # One colour, deliberately+ * # Colour is per-segment  *- * The phone's route is coloured per navigation step — traffic bands, transit brand- * colours, a travelled grey behind the puck — but it is drawn in Compose over `VectorMap`- * and is not migrating to the renderer. Nothing that consumes this API needs per-segment- * colour, so it does not have one; if `RouteLayer` is ever migrated, that is when the- * shape should be revisited against a real caller.+ * The fill colour is not here: it rides on each [RouteSegment], because the whole point of+ * the route overlay is to colour each run differently — traffic bands, transit brand colours,+ * a travelled grey behind the puck during navigation. What stays shared, and lives here, is+ * the geometry of the stroke: the line width and the casing that outlines the lot. The car+ * (Android Auto) passes a single segment and one colour through the same path.  *  * # Why there is a casing at all  *@@ -55,8 +56,6 @@ data class RouteStyle(     val width: Dp = 8.dp,     /** How far the casing stands out past the route line **on each side**. */     val casingWidth: Dp = 2.dp,-    /** The route line's colour. */-    val color: Color = Color(0xFF1A73E8),     /** The casing's colour. Unused when [casingWidth] is zero. */     val casingColor: Color = Color.White, )
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 a93bd17257..1c866ce6cc 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@@ -7,6 +7,7 @@ import android.view.Surface import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.DpRect import java.io.File@@ -160,16 +161,39 @@ class SurfaceMapRenderer(     /** Remembered so a fix taken before the surface existed is drawn in the first frame. */     private var userPuck: UserPuck? = null +    /**+     * The app pins to draw, remembered so a set pushed before the surface existed — or one that+     * outlives a surface being recreated — is still there in the first frame, the same way+     * [userPuck] and [routeSegments] are.+     */+    private var markers: List<MapMarker> = emptyList()++    /**+     * The simulated transit vehicles to draw, remembered on the same terms as [markers] so a set+     * pushed before the surface existed — or one that outlives a surface being recreated — is still+     * there in the first frame. Kept apart from [markers] because the host pushes the two on+     * different cadences (vehicles at ~1 Hz, pins on a tap/search).+     */+    private var vehicles: List<MapMarker> = emptyList()+     /**      * The route to draw, and how, remembered so a route set before the surface existed —      * or one that outlives a surface being recreated — is still there in the first frame.      *-     * Kept as the points rather than as anything native, because the native mesh dies with-     * the renderer and this has to be able to rebuild it.+     * Kept as the coloured segments rather than as anything native, because the native mesh+     * dies with the renderer and this has to be able to rebuild it.      */-    private var route: List<GeoPoint>? = null+    private var routeSegments: List<RouteSegment>? = null     private var routeStyle = RouteStyle() +    /**+     * The last-pushed live-traffic colour table (`component_id`s and their ARGB), remembered so+     * a push that arrived before the surface existed — or that has to outlive the surface being+     * recreated — is re-applied in the first frame, the same way [route] is. `null` means the+     * overlay has nothing to draw (never pushed, or cleared).+     */+    private var trafficSpeeds: Pair<LongArray, IntArray>? = null+     /** The region to mask and which rung of the admin stack it is, or `null` for no mask. */     private var regionProbe: RegionMask? = null @@ -221,9 +245,13 @@ class SurfaceMapRenderer(         // Before the first frame, so the very first resident set is tessellated with         // the layers the host asked for instead of being built and then invalidated.         MapNative.setLayers(handle, layers.poi, layers.transit, layers.poiKinds.joinToString(","))+        MapNative.setTrafficEnabled(handle, layers.traffic)         applyUserPuck()         applyRoute()         applyRegionMask()+        applyTraffic()+        applyMarkers()+        applyVehicles()         renderState = MapRenderState.Rendering         syncFrameLoop()     }@@ -282,17 +310,27 @@ class SurfaceMapRenderer(      * Draw exactly one frame, for a host driving its own loop instead of using      * [start]/[stop]. Returns whether a frame was actually presented — false when there is      * no renderer, no measured viewport, or the swapchain needed rebuilding.+     *+     * Uses `System.nanoTime()` as the animation clock; the Choreographer loop passes its own+     * `frameTimeNanos` through the [renderFrame]`(Long)` overload instead.+     */+    fun renderFrame(): Boolean = renderFrame(System.nanoTime())++    /**+     * As [renderFrame], but with the frame clock supplied by the caller — the Choreographer's+     * `frameTimeNanos`, which the renderer forwards to shaders so animation is tied to the+     * presented frame rather than to wall-clock jitter.      */-    fun renderFrame(): Boolean {+    fun renderFrame(frameTimeNanos: Long): Boolean {         if (handle == 0L) return false         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, so+        // `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. That is a silent wrong render, not an error: the map-        // turns, the pins stay put, and nothing anywhere reports it. Bearing is reachable+        // 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.         val bearing: Float         val state = composeCamera@@ -315,9 +353,11 @@ class SurfaceMapRenderer(             position.target.latitude.toFloat(),             position.zoom.toFloat(),             bearing,+            position.pitch.toFloat(),             widthDp,             heightDp,             density,+            frameTimeNanos,         )         if (drawn) onFrame()         if (!regionResolved) applyRegionMask()@@ -334,7 +374,7 @@ class SurfaceMapRenderer(                         if (frameCallback === this) frameCallback = null                         return                     }-                    renderFrame()+                    renderFrame(frameTimeNanos)                     // Re-post only while still the installed callback: detachSurface() and                     // stop() null this out, and a callback already dispatched for this frame                     // cannot be un-posted by removeFrameCallback.@@ -357,16 +397,38 @@ class SurfaceMapRenderer(     }      /**-     * Turn the optional POI and transit layers on or off. Not free — see [LayerOptions].-     * A call that changes nothing does nothing.+     * Turn the optional POI, transit and traffic layers on or off. Not free — see+     * [LayerOptions]. A call that changes nothing does nothing.      */     fun setLayers(options: LayerOptions) {         this.layers = options         if (handle != 0L) {             MapNative.setLayers(handle, options.poi, options.transit, options.poiKinds.joinToString(","))+            MapNative.setTrafficEnabled(handle, options.traffic)         }     } +    /**+     * Push the live-traffic colour table: [ids] holds each segment's `component_id` and+     * [argbColors] the fully-resolved ARGB to draw it, index for index. The host owns the+     * theme, so the colours are final. Replaces the whole table each call; a segment whose id+     * is absent draws nothing (the basemap road shows through). Cheap — a pure recolour, no+     * tessellation — so it is safe to drive from a camera-idle callback.+     *+     * Remembered so it survives the surface being recreated. Has no visible effect unless the+     * traffic layer is enabled through [setLayers]/[LayerOptions.traffic].+     */+    fun setTrafficSpeeds(ids: LongArray, argbColors: IntArray) {+        this.trafficSpeeds = ids to argbColors+        applyTraffic()+    }++    /** Clear the live-traffic overlay so it draws nothing until the next [setTrafficSpeeds]. */+    fun clearTraffic() {+        this.trafficSpeeds = null+        applyTraffic()+    }+     /**      * Tell the renderer whether the device is online. Offline it serves stale cached ranges      * instead of attempting a request, so a previously-viewed area keeps drawing.@@ -385,6 +447,50 @@ class SurfaceMapRenderer(         applyUserPuck()     } +    /**+     * Replace the app's pins with [markers], drawn by the renderer as billboarded sprites so they+     * pan and tilt in lock-step with the basemap instead of trailing it the way a Compose overlay+     * does. An empty list clears them. Cheap: the geometry is the shared unit quad, so this is a+     * pure state push, no tessellation.+     */+    fun setMarkers(markers: List<MapMarker>) {+        this.markers = markers+        applyMarkers()+    }++    /**+     * Replace the simulated transit vehicles with [vehicles], drawn by the renderer as billboarded+     * sprites through the same path as [setMarkers]. An empty list clears them. Cheap: the geometry+     * is the shared unit quad, so this is a pure state push, no tessellation.+     *+     * Separate from [setMarkers] so the host's ~1 Hz vehicle recompute replaces only the vehicles+     * and leaves the app pins untouched; drive it from the vehicle ticker rather than merging it+     * into the pin set.+     */+    fun setVehicles(vehicles: List<MapMarker>) {+        this.vehicles = vehicles+        applyVehicles()+    }++    /**+     * The id of the pin under a tap, or `0` when the tap hit no pin. [xDp]/[yDp] are Dp from the+     * viewport top-left. Reads the renderer's id buffer (see the native `pickAt`), so it stays+     * correct under tilt and never trails the basemap on a pan, unlike a Compose CPU hit-test.+     *+     * The returned value is whatever [MapMarker.id] the host set, so it maps the tap back to its+     * own feature. `internal` because it is wired through [Projection.pickMarker] like the label+     * pick, so a caller without a live renderer gets `0` rather than a dead handle.+     */+    internal fun pickAt(xDp: Float, yDp: Float): Long {+        val h = handle+        if (h == 0L) return 0L+        return try {+            MapNative.pickAt(h, xDp, yDp)+        } catch (_: Throwable) {+            0L+        }+    }+     /** Dim everything outside the region [mask] names, or clear the mask with `null`. */     fun setRegionMask(mask: RegionMask?) {         this.regionProbe = mask@@ -393,8 +499,10 @@ class SurfaceMapRenderer(     }      /**-     * Draw [points] as the navigation route, over the basemap and under the puck. `null`-     * or fewer than two distinct points draws nothing, which is how a route is cleared.+     * Draw [points] as a single-colour navigation route, over the basemap and under the+     * puck. `null` or fewer than two distinct points draws nothing, which is how a route is+     * cleared. The convenience path for a host that wants one line in one colour — Android+     * Auto, which has no view hierarchy to hang a Compose overlay in.      *      * Main thread, like everything else here. Not free, but paid once per route rather      * than once per frame: the native side tessellates the polyline and uploads it here,@@ -402,18 +510,28 @@ class SurfaceMapRenderer(      * one tessellation however long the drive or however much the driver zooms. Setting      * the same route again does re-tessellate, so drive this from a state change rather      * than from a per-frame callback.-     *-     * This exists because Android Auto hands the app a bare `Surface` with no view-     * hierarchy, so the Compose route overlay the phone draws above the map has nowhere to-     * live. The phone path is unaffected: a renderer with no route set draws exactly what-     * it drew before.      */     fun setRoute(points: List<GeoPoint>?, style: RouteStyle = RouteStyle()) {-        this.route = points+        this.routeSegments = points?.let { listOf(RouteSegment(it, DEFAULT_ROUTE_COLOR)) }         this.routeStyle = style         applyRoute()     } +    /**+     * Draw a multi-segment, per-segment-coloured route (see [RouteOverlay]), over the+     * basemap and under the puck. `null` or an all-empty overlay draws nothing, which is+     * how a route is cleared. This is what the phone pushes: the traffic-band / transit /+     * travelled-grey colouring resolved on the device into one coloured segment per run.+     *+     * Same cost model as the single-colour [setRoute]: one tessellation per push, never+     * per frame or per zoom step.+     */+    fun setRoute(overlay: RouteOverlay?) {+        this.routeSegments = overlay?.segments+        this.routeStyle = overlay?.style ?: RouteStyle()+        applyRoute()+    }+     /**      * Task-17 pick: placed labels intersecting [box] (Dp), restricted to      * [layerIds] (our flat ids), in placement order. Parses the native@@ -481,33 +599,106 @@ class SurfaceMapRenderer(         }     } +    private fun applyMarkers() {+        if (handle == 0L) return+        val pins = markers+        if (pins.isEmpty()) {+            MapNative.clearMarkers(handle)+            return+        }+        // Three parallel bulk arrays, the convention the native side reads: ids, then interleaved+        // lon/lat, then icon ids. Packed once here rather than crossing the boundary per pin.+        val ids = LongArray(pins.size)+        val lonLat = FloatArray(pins.size * 2)+        val icons = IntArray(pins.size)+        for (i in pins.indices) {+            val pin = pins[i]+            ids[i] = pin.id+            lonLat[i * 2] = pin.position.longitude.toFloat()+            lonLat[i * 2 + 1] = pin.position.latitude.toFloat()+            icons[i] = pin.icon+        }+        MapNative.setMarkers(handle, ids, lonLat, icons)+    }++    private fun applyVehicles() {+        if (handle == 0L) return+        val vs = vehicles+        if (vs.isEmpty()) {+            MapNative.clearVehicles(handle)+            return+        }+        // Three parallel bulk arrays, the convention the native side reads: ids, then interleaved+        // lon/lat, then icon ids. Packed once here rather than crossing the boundary per vehicle.+        val ids = LongArray(vs.size)+        val lonLat = FloatArray(vs.size * 2)+        val icons = IntArray(vs.size)+        for (i in vs.indices) {+            val v = vs[i]+            ids[i] = v.id+            lonLat[i * 2] = v.position.longitude.toFloat()+            lonLat[i * 2 + 1] = v.position.latitude.toFloat()+            icons[i] = v.icon+        }+        MapNative.setVehicles(handle, ids, lonLat, icons)+    }+     private fun applyRoute() {         if (handle == 0L) return-        val points = route-        if (points == null || points.size < 2) {+        // Drawable segments only: fewer than two points strokes nothing, and dropping them+        // here keeps the native side's per-segment ranges aligned with the colours.+        val drawable = routeSegments?.filter { it.points.size >= 2 }+        if (drawable.isNullOrEmpty()) {             MapNative.clearRoute(handle)             return         }-        // Flat lon/lat pairs: one array crosses JNI instead of one call per point, which-        // for a cross-city route is thousands of crossings saved. Built here rather than-        // held, because a route is set once and this is not a per-frame path.-        val flat = FloatArray(points.size * 2)-        points.forEachIndexed { at, point ->-            flat[at * 2] = point.longitude.toFloat()-            flat[at * 2 + 1] = point.latitude.toFloat()+        // Flat lon/lat pairs across every segment, plus a point count and colour per+        // segment: three bulk arrays cross JNI instead of one call per point, which for a+        // cross-city route is thousands of crossings saved. Built here rather than held,+        // because a route is set once and this is not a per-frame path.+        val flat = FloatArray(drawable.sumOf { it.points.size } * 2)+        val lengths = IntArray(drawable.size)+        val colors = IntArray(drawable.size)+        var at = 0+        drawable.forEachIndexed { i, segment ->+            lengths[i] = segment.points.size+            colors[i] = segment.color.toArgb()+            for (point in segment.points) {+                flat[at * 2] = point.longitude.toFloat()+                flat[at * 2 + 1] = point.latitude.toFloat()+                at+++            }         }         MapNative.setRoute(             handle,             flat,+            lengths,+            colors,             routeStyle.width.value,             routeStyle.casingWidth.value,-            routeStyle.color.toArgb(),             routeStyle.casingColor.toArgb(),         )     } +    private fun applyTraffic() {+        if (handle == 0L) return+        val speeds = trafficSpeeds+        if (speeds == null) {+            MapNative.clearTraffic(handle)+        } else {+            MapNative.setTrafficSpeeds(handle, speeds.first, speeds.second)+        }+    }+     private companion object {         const val TAG = "SurfaceMapRenderer"         const val CACHE_DIR_NAME = "vectortilecache"++        /**+         * The fill the single-colour [setRoute] convenience paints: the car's `#1A73E8`,+         * the one route colour in this app authored against a real rendering (see+         * [RouteStyle]). A per-segment route carries its own colours instead.+         */+        val DEFAULT_ROUTE_COLOR = Color(0xFF1A73E8)     } }
library/map/src/main/java/com/vayunmathur/library/map/TrafficColorTable.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/TrafficColorTable.kt b/library/map/src/main/java/com/vayunmathur/library/map/TrafficColorTable.ktnew file mode 100644index 0000000000..4390c8f71f--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/TrafficColorTable.kt@@ -0,0 +1,29 @@+package com.vayunmathur.library.map++/**+ * A live-traffic colour push: one fully-resolved ARGB per drawn component segment.+ *+ * [ids] holds each segment's `component_id` (`packed(big_edge_id, seg_index)`, the shared+ * traffic id contract) and [argb] the `0xAARRGGBB` the host wants drawn for it, index for+ * index. The host owns the theme, so the colours are final — the renderer only looks them up.+ *+ * A segment whose id is not in [ids] draws nothing and the basemap road shows through, so a+ * host sends only the segments it has a reading for (omitting no-data rather than encoding it).+ * Passed to [VectorMap]'s `trafficColors`; `null` or an empty table clears the overlay.+ *+ * Equality is by **content**, not array identity, so a host that rebuilds an identical table on+ * recomposition does not trigger a redundant re-push: the effect that drives this is keyed on+ * the value. Mismatched array lengths are truncated to the shorter on the native side.+ */+data class TrafficColorTable(val ids: LongArray, val argb: IntArray) {+    override fun equals(other: Any?): Boolean {+        if (this === other) return true+        if (other !is TrafficColorTable) return false+        return ids.contentEquals(other.ids) && argb.contentEquals(other.argb)+    }++    override fun hashCode(): Int = 31 * ids.contentHashCode() + argb.contentHashCode()++    /** True when there is nothing to draw, which the surface treats the same as `null`. */+    fun isEmpty(): Boolean = ids.isEmpty() || argb.isEmpty()+}
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 3fb4d6aa05..8687594070 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@@ -62,6 +62,16 @@ import kotlin.math.roundToInt  *   which city or country a details sheet is about. Drawn inside the renderer's frame for the  *   same reason as [userPuck]: an overlay composed on top would lag the map by a frame while  *   panning. `null` draws no mask.+ * @param trafficColors the live-traffic overlay's `component_id → ARGB` table. The baked+ *   traffic geometry is gated by [LayerOptions.traffic]; this supplies the colours the host+ *   resolved from its own palette. `null` (or an empty table) clears the overlay, which is+ *   what a host passes when the traffic toggle is off. Pushed into the renderer's frame like+ *   [regionMask] rather than composed on top, for the same reason.+ * @param route the navigation route, drawn inside the renderer's frame so it pans in+ *   lock-step with the basemap instead of trailing it by a frame the way a Compose overlay+ *   does. A list of per-segment-coloured runs (see [RouteOverlay]) — traffic bands, transit+ *   brand colours, the travelled grey during navigation — resolved by the host. `null` (or+ *   an all-empty overlay) draws nothing.  * @param onFrame called after each presented frame.  *  *   Kept for `library/map/src/androidTest/.../BasemapScreenshotTest.kt`, which counts frames@@ -85,6 +95,20 @@ fun VectorMap(     imageOverlay: ImageOverlay? = null,     userPuck: UserPuck? = null,     regionMask: RegionMask? = null,+    trafficColors: TrafficColorTable? = null,+    route: RouteOverlay? = null,+    /**+     * App pins the renderer draws inside its own frame, glued to the ground so they pan and tilt+     * in lock-step with the basemap instead of trailing it the way a Compose overlay does (see+     * [MapMarker]). A tap resolves back to one through [Projection.pickMarker]. Empty draws none.+     */+    markers: List<MapMarker> = emptyList(),+    /**+     * Simulated transit vehicles the renderer draws inside its own frame, glued to the ground like+     * [markers] but pushed on their own ~1 Hz cadence and not tap-pickable (see [MapMarker]). Empty+     * draws none — which is how a host stops them when the transit layer is off.+     */+    vehicles: List<MapMarker> = emptyList(),     onMapClick: (GeoPoint) -> Unit = {},     /**      * Tap with the screen point attached (see [MapClick]): what@@ -162,6 +186,10 @@ fun VectorMap(             archivePath = archivePath,             userPuck = userPuck,             regionMask = regionMask,+            trafficColors = trafficColors,+            route = route,+            markers = markers,+            vehicles = vehicles,             modifier = Modifier.fillMaxSize(),             onFrame = onFrame,             fallback = fallback,
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 e9ec30431e..26a05a94e4 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@@ -54,6 +54,27 @@ internal fun VulkanMapSurface(     userPuck: UserPuck? = null,     /** Dim everything outside the administrative region this names. `null` draws no mask. */     regionMask: RegionMask? = null,+    /**+     * The live-traffic colour table. `null` or an empty table clears the overlay; otherwise its+     * `component_id → ARGB` entries are pushed to the renderer. Has no visible effect unless+     * [LayerOptions.traffic] is on.+     */+    trafficColors: TrafficColorTable? = null,+    /**+     * The navigation route to draw inside the renderer's frame. `null` or an all-empty+     * overlay draws nothing. Pushed like [regionMask], out of band from the frame loop, so+     * it pans in lock-step with the basemap.+     */+    route: RouteOverlay? = null,+    /** App pins the renderer draws as billboarded sprites; empty draws none. */+    markers: List<MapMarker> = emptyList(),+    /**+     * Simulated transit vehicles the renderer draws as billboarded sprites, on the same shared+     * sprite path as [markers] but pushed on their own ~1 Hz cadence; empty draws none. Kept apart+     * from [markers] so a vehicle recompute does not churn the pins and the moving sprites stay out+     * of the pin tap-pick.+     */+    vehicles: List<MapMarker> = emptyList(),     modifier: Modifier = Modifier,     onFrame: () -> Unit = {},     fallback: @Composable (MapRenderState.Unavailable) -> Unit = {},@@ -71,7 +92,14 @@ internal fun VulkanMapSurface(         cameraState.labelQueryProvider = { box: DpRect, layerIds: Set<String> ->             renderer.pickLabels(box, layerIds)         }-        onDispose { cameraState.labelQueryProvider = null }+        // The marker pick counterpart: taps resolve to a renderer-drawn pin's id through the id+        // buffer. Cleared on dispose so a projection without a live renderer answers 0, not a dead+        // handle.+        cameraState.markerPickProvider = { xDp: Float, yDp: Float -> renderer.pickAt(xDp, yDp) }+        onDispose {+            cameraState.labelQueryProvider = null+            cameraState.markerPickProvider = null+        }     }      DisposableEffect(host) { onDispose { host.dispose() } }@@ -115,6 +143,34 @@ internal fun VulkanMapSurface(     // Same reasoning as the puck: a selection arrives from a tap, not from the frame loop.     LaunchedEffect(regionMask, host) { renderer.setRegionMask(regionMask) } +    // The traffic colour table: pushed like the region mask, out of band from the frame loop.+    // Keyed on the table's *value* (content equality) so a host rebuilding an identical table+    // on recomposition does not re-push. `null` or empty clears — a pure state swap either way,+    // no tessellation. The layer-10 on/off gate rides `layerOptions` above, not this.+    LaunchedEffect(trafficColors, host) {+        val table = trafficColors+        if (table == null || table.isEmpty()) {+            renderer.clearTraffic()+        } else {+            renderer.setTrafficSpeeds(table.ids, table.argb)+        }+    }++    // The route: pushed like the region mask, out of band from the frame loop. Keyed on the+    // overlay's *value* (data-class equality) so the phone rebuilding an identical route on+    // recomposition does not re-tessellate. `null` or an all-empty overlay clears it.+    LaunchedEffect(route, host) { renderer.setRoute(route) }++    // App pins: pushed like the puck, out of band from the frame loop, so they pan and tilt in+    // lock-step with the basemap. Keyed on the list's value so an identical set rebuilt on+    // recomposition does not re-push; an empty list clears them.+    LaunchedEffect(markers, host) { renderer.setMarkers(markers) }++    // Simulated transit vehicles: pushed like the pins but on their own ~1 Hz cadence, keyed on the+    // list's value so an identical recompute does not re-push. An empty list clears them, which is+    // how the ticker stops them when the transit toggle goes off or the surface is hidden.+    LaunchedEffect(vehicles, host) { renderer.setVehicles(vehicles) }+     // Live connectivity, replacing a single sample taken in onSurfaceTextureAvailable.     // Collected here rather than inside the renderer so every MapNative call stays on the     // composition dispatcher, like setPalette and setLayers.
library/map/src/main/rust/examples/place_probe.rs
diff --git a/library/map/src/main/rust/examples/place_probe.rs b/library/map/src/main/rust/examples/place_probe.rsindex 7814121ecc..4e0f31c2db 100644--- a/library/map/src/main/rust/examples/place_probe.rs+++ b/library/map/src/main/rust/examples/place_probe.rs@@ -54,6 +54,8 @@ fn main() {         height_dp: h,         density: 3.0,         bearing_deg: 0.0,+        pitch_deg: 0.0,+        time_seconds: 0.0,     };     let extent = ((camera.width_dp * camera.density) as u32, (camera.height_dp * camera.density) as u32);     println!("camera    z6 SF viewport {extent:?} device px");
library/map/src/main/rust/examples/places_probe.rs
diff --git a/library/map/src/main/rust/examples/places_probe.rs b/library/map/src/main/rust/examples/places_probe.rsindex 4481bb45e8..6e773aae2c 100644--- a/library/map/src/main/rust/examples/places_probe.rs+++ b/library/map/src/main/rust/examples/places_probe.rs@@ -286,12 +286,16 @@ fn main() {                     transit_ordinal: 0,                     transit_lanes: 0,                     transit_taper: 0,+                    lane_count: 0,                 }],                 parts: vec![Part { coord_start: 0, point_count: 1, winding: WINDING_OUTER }],                 coords: vec![(2048, 2048)],             }],             names: vec!["Testland".to_string()],             ids: Vec::new(),+            turn_lanes: Vec::new(),+            buildings: Vec::new(),+            heightmap: None, carriageways: Vec::new(), convention: None,         };         let mesh = geometry::build(&body, layers, 6, 32, 40, false);         println!(
library/map/src/main/rust/examples/probe_archive.rs
diff --git a/library/map/src/main/rust/examples/probe_archive.rs b/library/map/src/main/rust/examples/probe_archive.rsindex 449b209d6a..01dfd71030 100644--- a/library/map/src/main/rust/examples/probe_archive.rs+++ b/library/map/src/main/rust/examples/probe_archive.rs@@ -184,6 +184,8 @@ fn main() {         height_dp: 867.0,         density: 3.0,         bearing_deg: 0.0,+        pitch_deg: 0.0,+        time_seconds: 0.0,     };     let layers = style::layers();     let wanted = select::resident_set(&camera, min_zoom, max_zoom);
library/map/src/main/rust/examples/zoom_sweep.rs
diff --git a/library/map/src/main/rust/examples/zoom_sweep.rs b/library/map/src/main/rust/examples/zoom_sweep.rsindex 0034b2c191..a04b785b9d 100644--- a/library/map/src/main/rust/examples/zoom_sweep.rs+++ b/library/map/src/main/rust/examples/zoom_sweep.rs@@ -146,6 +146,8 @@ fn main() {                 height_dp: 867.0,                 density: 3.0,                 bearing_deg: 0.0,+                pitch_deg: 0.0,+                time_seconds: 0.0,             };             let tiles = select::visible(&camera, min_zoom, max_zoom);             let mut absent = 0;
library/map/src/main/rust/shaders/building.frag
diff --git a/library/map/src/main/rust/shaders/building.frag b/library/map/src/main/rust/shaders/building.fragnew file mode 100644index 0000000000..2edfa1a418--- /dev/null+++ b/library/map/src/main/rust/shaders/building.frag@@ -0,0 +1,35 @@+#version 450++// Building fragment: flat per-face shading (WS-A).+//+// The face normal is constant across the triangle (the CPU gives all three vertices the same+// one), so lighting it against a single fixed direction gives every face one flat tone - the+// S3DB look, and no shadows. The colour is the per-vertex ARGB the wall/roof carries; blending+// is the pipeline's job, so it passes straight through with its own alpha.+layout(location = 0) in vec3 vNormal;+layout(location = 1) in vec4 vColor;+layout(push_constant) uniform Push {+    mat4 tileToClip;+    // The palette's building colour, for geometry the archive gave none. See below.+    vec4 color;+    vec4 line;+    vec4 misc;+    vec4 morph;+} push;+layout(location = 0) out vec4 outColor;+void main() {+    vec3 n = normalize(vNormal);+    // A fixed light from above and the north-west, in tile-local space (x east, y south, z up),+    // so roofs read brightest and the walls facing away sit a shade darker.+    vec3 lightDir = normalize(vec3(-0.4, -0.4, 1.0));+    float diffuse = max(dot(n, lightDir), 0.0);+    // Generous ambient so a shadowed wall stays legible rather than going black.+    float light = 0.55 + 0.45 * diffuse;+    // Zero alpha is the tessellator's "this wall or roof has no colour of its own" marker (see+    // `extrude_building`): fall back to the pushed palette colour. Vertex colour is baked when the+    // tile is tessellated, where the palette is not known, so this is what lets a light/dark+    // switch recolour untagged buildings without re-tessellating them. A building that carries an+    // OSM `building:colour` has a real alpha and keeps it in both palettes.+    vec4 base = vColor.a < 0.5 ? push.color : vColor;+    outColor = vec4(base.rgb * light, base.a);+}
library/map/src/main/rust/shaders/building.vert
diff --git a/library/map/src/main/rust/shaders/building.vert b/library/map/src/main/rust/shaders/building.vertnew file mode 100644index 0000000000..71a90611e1--- /dev/null+++ b/library/map/src/main/rust/shaders/building.vert@@ -0,0 +1,50 @@+#version 450++// Building: extruded 3D walls and roof caps (WS-A, OSM Simple 3D Buildings).+//+// Unlike the position-only fill vertex, a building vertex carries a height, a face normal+// and its own colour — the three things flat 2D layers never need. See `tess::roof` for the+// layout the CPU packs.+//+// The incoming height is **tile-normalised** (a fraction of the tile's ground width, the+// same unit x/y are) so the mesh is zoom-independent like every other tile mesh. `line.x`+// carries the tile's world-px span for this frame; multiplying the two recovers the real+// world-px height the WS0 perspective matrix expects in its `z` input. At pitch 0 that matrix+// ignores z for x/y, so a building drawn from directly overhead collapses to its footprint.++layout(location = 0) in vec3 inPosition; // tile-local (u, v, height); u,v in 0..1+layout(location = 1) in vec3 inNormal;   // face normal in the same tile-local space+layout(location = 2) in vec4 inColor;    // per-vertex ARGB, R8G8B8A8_UNORM -> 0..1++layout(push_constant) uniform Push {+    // Tile-local (u, v, height, 1) to clip space — the WS0 matrix. `height` is world-px.+    mat4 tileToClip;+    vec4 color;+    // x: the tile's world-px span this frame, the tile-norm-height -> world-px scale (WS-A).+    // y, z, w: unused by the building path.+    vec4 line;+    vec4 misc;+    vec4 morph;+} push;++layout(location = 0) out vec3 vNormal;+layout(location = 1) out vec4 vColor;++void main() {+    float worldHeight = inPosition.z * push.line.x;+    // The height column's w term (tileToClip[2][3]) is 0 on the ortho fast-path (pitch 0) and+    // -cos(pitch) once tilted. That distinguishes the two, and they need different z inputs.+    if (abs(push.tileToClip[2][3]) < 1e-6) {+        // Pitch 0: the ortho matrix copies z straight to clip depth and never lets height touch+        // x/y, so the building already reads as its flat footprint. Feed the small tile-normalised+        // height (clamped into range) instead of the world-px one, which would fall outside the+        // [0, w] depth range and clip the whole building away.+        gl_Position = push.tileToClip * vec4(inPosition.xy, clamp(inPosition.z, 0.0, 0.99), 1.0);+    } else {+        // Tilted: the full perspective maps a real world-px height to both the projected rise and a+        // depth inside the near/far range, so buildings extrude and occlude correctly.+        gl_Position = push.tileToClip * vec4(inPosition.xy, worldHeight, 1.0);+    }+    vNormal = inNormal;+    vColor = inColor;+}
library/map/src/main/rust/shaders/fill.frag
diff --git a/library/map/src/main/rust/shaders/fill.frag b/library/map/src/main/rust/shaders/fill.fragindex a43b3828b6..bdc7e22529 100644--- a/library/map/src/main/rust/shaders/fill.frag+++ b/library/map/src/main/rust/shaders/fill.frag@@ -1,7 +1,8 @@ #version 450  // Fill fragment: the layer colour. Blending is the pipeline's job — src-alpha over-// one-minus-src-alpha — so the colour passes straight through.+// one-minus-src-alpha — so the colour passes straight through, scaled by the per-tile+// LOD cross-fade opacity (WS-D) so a finer tile ramps in over its coarse ancestor.  layout(location = 0) out vec4 outColor; @@ -10,8 +11,10 @@ layout(push_constant) uniform Push {     vec4 color;     vec4 line;     vec4 misc;+    // x: per-tile opacity/morph factor (1.0 = fully present) for WS-D's LOD cross-fade.+    vec4 morph; } push;  void main() {-    outColor = push.color;+    outColor = vec4(push.color.rgb, push.color.a * push.morph.x); }
library/map/src/main/rust/shaders/fill.vert
diff --git a/library/map/src/main/rust/shaders/fill.vert b/library/map/src/main/rust/shaders/fill.vertindex 7bec8928da..0e99971af6 100644--- a/library/map/src/main/rust/shaders/fill.vert+++ b/library/map/src/main/rust/shaders/fill.vert@@ -14,15 +14,20 @@ layout(location = 0) in vec2 inPosition;  layout(push_constant) uniform Push {-    // Tile-local 0..1 to clip space.+    // Tile-local (u, v, height, 1) to clip space. `height` (the vertex z) is 0 for+    // every flat 2D layer and a real world-px height for buildings/terrain.     mat4 tileToClip;     vec4 color;     // x: half stroke width in px, y: half the casing gap in px,     // z: dash length, w: gap length (both in line widths).     vec4 line;     // x: the screen size of one tile in px, which is what converts a pixel width-    // into tile-local units. y, z, w unused.+    // into tile-local units. y: edge-AA flag. z: lane lateral offset px. w: the+    // per-frame clock in seconds (WS0), read by the animated line paths.     vec4 misc;+    // x: per-tile opacity/morph factor (1.0 = fully present), reserved for WS-D's+    // LOD cross-fade. y, z, w reserved.+    vec4 morph; } push;  void main() {
library/map/src/main/rust/shaders/line.frag
diff --git a/library/map/src/main/rust/shaders/line.frag b/library/map/src/main/rust/shaders/line.fragindex 920895f00e..17d072544c 100644--- a/library/map/src/main/rust/shaders/line.frag+++ b/library/map/src/main/rust/shaders/line.frag@@ -30,8 +30,11 @@ layout(push_constant) uniform Push {     vec4 color;     vec4 line;     // x: tile span in px, y: 1 when the pass is single-sampled and this shader owns-    // edge antialiasing, 0 when MSAA is resolving it.+    // edge antialiasing, 0 when MSAA is resolving it. w: the per-frame clock in seconds.     vec4 misc;+    // y: dash phase speed in px/s (WS-B). 0 for every static line, so the dash pattern+    // is byte-identical; only the traffic and route draws set it.+    vec4 morph; } push;  // Mirrors `style::paint::MIN_HALF_WIDTH_PX`; must match `line.vert`.@@ -57,7 +60,14 @@ void main() {         float on = dashOn * width;         float off = dashOff * width;         float period = on + off;-        if (period > 0.0 && mod(inDistancePx, period) > on) discard;+        // Scroll the dash by a clock-driven phase: `morph.y` is a per-draw phase speed+        // in px/s and `misc.w` is the per-frame clock in seconds. Both are 0 for every+        // static line (morph.y defaults to 0; the clock starts at 0), so `phase` is 0+        // and `mod(inDistancePx - phase, period)` collapses to the un-phased test —+        // static roads, rail and borders are byte-identical. Traffic and route set+        // morph.y to make their dashes travel.+        float phase = push.misc.w * push.morph.y;+        if (period > 0.0 && mod(inDistancePx - phase, period) > on) discard;     }     outColor = vec4(push.color.rgb, push.color.a * coverage); }
library/map/src/main/rust/shaders/pick.frag
diff --git a/library/map/src/main/rust/shaders/pick.frag b/library/map/src/main/rust/shaders/pick.fragnew file mode 100644index 0000000000..8422e1eed7--- /dev/null+++ b/library/map/src/main/rust/shaders/pick.frag@@ -0,0 +1,14 @@+#version 450+// Id-buffer pick fragment: write this feature's 1-based pick slot to the R32_UINT target, so+// reading back the tapped pixel yields the slot (0 = nothing). The slot is carried as the bit+// pattern of a float in the push block's `color.x` — `floatBitsToUint` recovers the exact u32,+// which a plain float-to-uint cast would round. The whole quad writes the id: a marker's tap+// box is its rectangle, which is what a generous touch target wants.+layout(location = 0) out uint outId;+layout(push_constant) uniform Push {+    mat4 tileToClip;+    vec4 color;+} push;+void main() {+    outId = floatBitsToUint(push.color.x);+}
library/map/src/main/rust/shaders/pick.vert
diff --git a/library/map/src/main/rust/shaders/pick.vert b/library/map/src/main/rust/shaders/pick.vertnew file mode 100644index 0000000000..c6a3755052--- /dev/null+++ b/library/map/src/main/rust/shaders/pick.vert@@ -0,0 +1,12 @@+#version 450+// Id-buffer pick vertex: the shared unit quad, placed exactly like the puck/marker sprites+// through `screen_quad_to_clip` (billboarded, upright and screen-constant under tilt), so a+// marker's pick box lands where its icon is drawn. Position only — the pick pass writes an id,+// not a picture, so there is no UV.+layout(location = 0) in vec2 inLocal;+layout(push_constant) uniform Push {+    mat4 tileToClip;+} push;+void main() {+    gl_Position = push.tileToClip * vec4(inLocal, 0.0, 1.0);+}
library/map/src/main/rust/shaders/symbol_billboard.vert
diff --git a/library/map/src/main/rust/shaders/symbol_billboard.vert b/library/map/src/main/rust/shaders/symbol_billboard.vertnew file mode 100644index 0000000000..be1c438d49--- /dev/null+++ b/library/map/src/main/rust/shaders/symbol_billboard.vert@@ -0,0 +1,43 @@+#version 450++// Billboard symbol vertex: point-label glyph quads that stay upright and pinned to their+// ground anchor under camera tilt. Text labels are tessellated per frame at the frame's text+// size (positions arrive tile-local and final), and each vertex also carries the label's+// ground anchor so this shader can, when tilted, project the anchor with perspective and hang+// the glyph off it at a constant screen offset.+//+// At pitch 0 the renderer clears the billboard flag (push.line.w) and this reduces to the plain+// `tileToClip * position` the flat map has always used — byte-identical output. A curved (line)+// label writes each glyph vertex as its own anchor (offset zero), so even with the flag set it+// projects straight onto the ground and stays map-aligned.++layout(location = 0) in vec2 inPosition;+layout(location = 1) in vec2 inUv;+layout(location = 2) in vec2 inAnchor;+layout(location = 0) out vec2 outUv;+layout(push_constant) uniform Push {+    mat4 tileToClip;+    vec4 color;+    // x: text size in px per em (halo SDF), y: halo width px, z: atlas sdf-per-em,+    // w: billboard flag (>0.5 = tilt billboard; 0 = flat, drawn straight through tileToClip).+    vec4 line;+    // x: tile span in px (unused here), yzw: halo color rgb.+    vec4 misc;+    // The pitch-0 tile matrix's linear 2x2 (column-major m0,m1,m4,m5), so the screen-constant+    // glyph offset can be reconstructed while the anchor goes through the perspective matrix.+    vec4 morph;+} push;+void main() {+    outUv = inUv;+    if (push.line.w > 0.5) {+        vec4 a = push.tileToClip * vec4(inAnchor, 0.0, 1.0);+        vec2 off = inPosition - inAnchor;+        // Column-major 2x2 * off: the same screen offset the ortho matrix would give this glyph,+        // scaled by the anchor's clip-w so the perspective divide leaves it screen-constant.+        vec2 offClip = vec2(push.morph.x * off.x + push.morph.z * off.y,+                            push.morph.y * off.x + push.morph.w * off.y);+        gl_Position = vec4(a.xy + offClip * a.w, a.z, a.w);+    } else {+        gl_Position = push.tileToClip * vec4(inPosition, 0.0, 1.0);+    }+}
library/map/src/main/rust/shaders/terrain.frag
diff --git a/library/map/src/main/rust/shaders/terrain.frag b/library/map/src/main/rust/shaders/terrain.fragnew file mode 100644index 0000000000..fdeeaebf1c--- /dev/null+++ b/library/map/src/main/rust/shaders/terrain.frag@@ -0,0 +1,25 @@+#version 450++// Terrain fragment: the ground colour, slope-shaded (WS-G, 3D terrain relief).+//+// The base colour is the `earth` style layer's, pushed per draw (linear RGBA, palette- and+// opacity-resolved by the renderer). The vertex stage has already reduced the surface normal to a+// single scalar shade — full (1.0) at pitch 0, so the ground reads as the flat map's one colour,+// and a diffuse term once tilted so hills show relief. Blending is the pipeline's job, so the+// colour passes through with its own alpha.++layout(location = 0) in float vShade;++layout(push_constant) uniform Push {+    mat4 tileToClip;+    vec4 color; // the earth layer's colour, linear RGBA+    vec4 line;+    vec4 misc;+    vec4 morph;+} push;++layout(location = 0) out vec4 outColor;++void main() {+    outColor = vec4(push.color.rgb * vShade, push.color.a);+}
library/map/src/main/rust/shaders/terrain.vert
diff --git a/library/map/src/main/rust/shaders/terrain.vert b/library/map/src/main/rust/shaders/terrain.vertnew file mode 100644index 0000000000..b5821e703f--- /dev/null+++ b/library/map/src/main/rust/shaders/terrain.vert@@ -0,0 +1,63 @@+#version 450++// Terrain: the DEM-displaced ground grid (WS-G, 3D terrain relief).+//+// Like the building vertex, a terrain vertex carries a height and a normal — but no per-vertex+// colour: the whole ground is one style colour (the `earth` layer's), pushed per draw, and the+// relief is conveyed by shading that colour against the normal. See `tess::terrain` for the layout.+//+// The incoming height is **tile-normalised** (a fraction of the tile's ground width, the same unit+// x/y are) so the grid is zoom-independent like every other tile mesh. `line.x` carries the tile's+// world-px span for this frame; multiplying the two recovers the real world-px height the WS0+// perspective matrix expects in its `z` input. At pitch 0 that matrix ignores z for x/y, so the+// grid reads as the flat tile footprint.++layout(location = 0) in vec3 inPosition; // tile-local (u, v, height); u,v in 0..1+layout(location = 1) in vec3 inNormal;   // surface normal in the same tile-local space++layout(push_constant) uniform Push {+    // Tile-local (u, v, height, 1) to clip space — the WS0 matrix. `height` is world-px.+    mat4 tileToClip;+    vec4 color;+    // x: the tile's world-px span this frame, the tile-norm-height -> world-px scale (WS-G).+    // y, z, w: unused by the terrain path.+    vec4 line;+    vec4 misc;+    vec4 morph;+} push;++layout(location = 0) out float vShade;++// Placed just short of the far plane so, at pitch 0, the ground sits behind every building (which+// write depths in [0, 0.99]) rather than in front of them — see the pitch-0 branch below.+const float ORTHO_GROUND_DEPTH = 0.9995;++void main() {+    float worldHeight = inPosition.z * push.line.x;+    // The height column's w term (tileToClip[2][3]) is 0 on the ortho fast-path (pitch 0) and+    // -cos(pitch) once tilted — the same test the building shader uses to tell the two apart.+    bool ortho = abs(push.tileToClip[2][3]) < 1e-6;++    if (ortho) {+        // Pitch 0: the ortho matrix never lets height touch x/y, so the grid already reads as the+        // flat tile footprint. Feed a fixed near-far depth instead of the terrain height so the+        // ground never wins the depth test against the buildings drawn over it (they write small+        // depths near the front); the flat 2D layers are depth-off and paint over it regardless.+        gl_Position = push.tileToClip * vec4(inPosition.xy, 0.0, 1.0);+        gl_Position.z = ORTHO_GROUND_DEPTH * gl_Position.w;+        // No directional shading overhead, so the ground reads as the flat map's single colour.+        vShade = 1.0;+    } else {+        // Tilted: the full perspective maps a real world-px height to both the projected rise and a+        // depth inside the near/far range, so hills rise, occlude what is behind them, and let+        // buildings on the far side of a ridge be hidden by it.+        gl_Position = push.tileToClip * vec4(inPosition.xy, worldHeight, 1.0);+        // A fixed light from above and the north-west, in tile-local space (x east, y south, z up),+        // so slopes facing it read brighter and the far sides of hills sit a shade darker.+        vec3 n = normalize(inNormal);+        vec3 lightDir = normalize(vec3(-0.4, -0.4, 1.0));+        float diffuse = max(dot(n, lightDir), 0.0);+        // Generous ambient so a shadowed slope stays legible rather than going black.+        vShade = 0.55 + 0.45 * diffuse;+    }+}
library/map/src/main/rust/src/bridge.rs
diff --git a/library/map/src/main/rust/src/bridge.rs b/library/map/src/main/rust/src/bridge.rsindex a035dae639..00d9193517 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -16,7 +16,8 @@ //! critical path, and no JNI in the hot loop.  use crate::camera::Camera;-use crate::overlay::RouteStyle;+use crate::marker::Marker;+use crate::overlay::{RouteSegment, RouteStyle}; use crate::style::{self, Layer, LayerToggles, Palette, SharedToggles}; use crate::tile::cache::{RangeCache, DEFAULT_MAX_BYTES}; use crate::tile::geometry::{self, TileMesh};@@ -26,7 +27,7 @@ use crate::tile::source::{ }; use crate::vulkan::context::{ANativeWindow_acquire, ANativeWindow_fromSurface}; use crate::vulkan::renderer::{Renderer, UserPuck};-use jni::objects::{JClass, JFloatArray, JObject, JString};+use jni::objects::{JClass, JFloatArray, JIntArray, JLongArray, JObject, JString}; use jni::sys::{jboolean, jfloat, jint, jlong}; use jni::JNIEnv; use std::collections::HashSet;@@ -491,9 +492,11 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     center_lat: jfloat,     zoom: jfloat,     bearing: jfloat,+    pitch: jfloat,     width_dp: jfloat,     height_dp: jfloat,     density: jfloat,+    frame_time_nanos: jlong, ) -> jboolean {     let Some(map) = handle_mut(handle) else { return 0 }; @@ -507,6 +510,13 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     //     // `bearing` is degrees clockwise from north for whatever points up the screen: 0 on     // every phone frame, and the car's heading during heading-up navigation.+    //+    // `pitch` is the tilt away from straight-down, clamped to the renderer's supported band+    // here so no matrix has to defend against a wild value. `frame_time_nanos` is the host's+    // Choreographer clock, reduced modulo an hour before it becomes an `f32` so a long uptime+    // does not blow past the ~7 significant digits an `f32` has and coarsen the animation clock+    // to tens of milliseconds — a once-an-hour wrap is invisible to the periodic effects that+    // read it.     let camera = Camera {         center_lon: center_lon as f64,         center_lat: center_lat as f64,@@ -515,6 +525,8 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         height_dp,         density,         bearing_deg: bearing as f64,+        pitch_deg: (pitch as f64).clamp(0.0, crate::camera::PITCH_MAX_DEG),+        time_seconds: ((frame_time_nanos.rem_euclid(3_600_000_000_000)) as f64 / 1_000_000_000.0) as f32,     };     // Task-17 pick needs the frame's density for Dp→device-px; remember it.     map.density = density;@@ -694,27 +706,172 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearUserPuck<     } } +/// Replace the app's pins with a marker set, drawn by the renderer as billboarded sprites.+///+/// Three parallel bulk arrays, the same convention as+/// [`setRoute`](Java_com_vayunmathur_library_map_MapNative_setRoute) and+/// [`setTrafficSpeeds`](Java_com_vayunmathur_library_map_MapNative_setTrafficSpeeds): `ids[i]` is+/// the host's own stable id for marker `i` (echoed back by+/// [`pickAt`](Java_com_vayunmathur_library_map_MapNative_pickAt)), `lonLat` holds+/// `[lon0, lat0, lon1, lat1, …]`, and `icons[i]` is the icon id (see `crate::marker::icon`). Bulk+/// arrays rather than a list of objects so a viewport's worth of pins crosses the boundary in a+/// few `get_*_array_region` reads with no per-pin JNI traffic; `float` coordinates for the same+/// reason the camera's are.+///+/// The whole set is replaced each call, not merged — a stale pin left behind would sit under the+/// finger and pick wrong. Moving the pins into the renderer is what stops them trailing the basemap+/// on a pan or tilt the way the Compose overlays did. Mismatched lengths are truncated to the+/// shortest; an empty set is the same as+/// [`clearMarkers`](Java_com_vayunmathur_library_map_MapNative_clearMarkers). Arrays that cannot be+/// read leave the markers **unchanged** rather than blanking them.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setMarkers<'l>(+    env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    ids: JLongArray<'l>,+    lon_lat: JFloatArray<'l>,+    icons: JIntArray<'l>,+) {+    let Some(map) = handle_mut(handle) else { return };+    let id_len = env.get_array_length(&ids).unwrap_or(0).max(0) as usize;+    let icon_len = env.get_array_length(&icons).unwrap_or(0).max(0) as usize;+    let coord_len = env.get_array_length(&lon_lat).unwrap_or(0).max(0) as usize;+    // Each marker consumes two floats (lon, lat), so the coordinate array bounds the count too.+    let n = id_len.min(icon_len).min(coord_len / 2);+    if n == 0 {+        map.renderer.set_markers(Vec::new());+        return;+    }+    let mut id_buf = vec![0i64; n];+    let mut icon_buf = vec![0i32; n];+    let mut coord_buf = vec![0f32; n * 2];+    if env.get_long_array_region(&ids, 0, &mut id_buf).is_err()+        || env.get_int_array_region(&icons, 0, &mut icon_buf).is_err()+        || env.get_float_array_region(&lon_lat, 0, &mut coord_buf).is_err()+    {+        log("the marker arrays could not be read; leaving the markers unchanged");+        return;+    }+    let markers: Vec<Marker> = (0..n)+        .map(|i| Marker {+            // A Kotlin id is a signed `long` and an icon a signed `int`; the bit pattern is what+            // matters and the cast keeps it.+            id: id_buf[i] as u64,+            lon: coord_buf[i * 2] as f64,+            lat: coord_buf[i * 2 + 1] as f64,+            icon: icon_buf[i] as u32,+        })+        .collect();+    map.renderer.set_markers(markers);+}++/// Take every marker away: the host cleared its pins.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearMarkers<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+) {+    if let Some(map) = handle_mut(handle) {+        map.renderer.set_markers(Vec::new());+    }+}++/// Replace the simulated transit vehicles with a set the renderer draws as billboarded sprites.+///+/// The same three parallel bulk arrays as+/// [`setMarkers`](Java_com_vayunmathur_library_map_MapNative_setMarkers) — `ids[i]` the host's+/// stable per-trip id, `lonLat` the flat `[lon0, lat0, lon1, lat1, …]`, and `icons[i]` the mode+/// sprite id (a vehicle uses the `VEHICLE_*` ids in `crate::marker::icon`) — because a vehicle is+/// just a [`Marker`] whose icon names a mode sprite, so it reuses the marker draw path verbatim.+///+/// Separate from [`setMarkers`](Java_com_vayunmathur_library_map_MapNative_setMarkers) so the app's+/// ~1 Hz vehicle recompute replaces only the vehicles, leaving the pins (which change on a tap or+/// search) untouched, and so the moving vehicle sprites stay out of the pin id-buffer pick. The+/// whole set is replaced each call — a trip that ended, left the bbox, or was cancelled must drop+/// out rather than linger. Mismatched lengths are truncated to the shortest; an empty set is the+/// same as [`clearVehicles`](Java_com_vayunmathur_library_map_MapNative_clearVehicles). Arrays that+/// cannot be read leave the vehicles **unchanged** rather than blanking them.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setVehicles<'l>(+    env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    ids: JLongArray<'l>,+    lon_lat: JFloatArray<'l>,+    icons: JIntArray<'l>,+) {+    let Some(map) = handle_mut(handle) else { return };+    let id_len = env.get_array_length(&ids).unwrap_or(0).max(0) as usize;+    let icon_len = env.get_array_length(&icons).unwrap_or(0).max(0) as usize;+    let coord_len = env.get_array_length(&lon_lat).unwrap_or(0).max(0) as usize;+    // Each vehicle consumes two floats (lon, lat), so the coordinate array bounds the count too.+    let n = id_len.min(icon_len).min(coord_len / 2);+    if n == 0 {+        map.renderer.set_vehicles(Vec::new());+        return;+    }+    let mut id_buf = vec![0i64; n];+    let mut icon_buf = vec![0i32; n];+    let mut coord_buf = vec![0f32; n * 2];+    if env.get_long_array_region(&ids, 0, &mut id_buf).is_err()+        || env.get_int_array_region(&icons, 0, &mut icon_buf).is_err()+        || env.get_float_array_region(&lon_lat, 0, &mut coord_buf).is_err()+    {+        log("the vehicle arrays could not be read; leaving the vehicles unchanged");+        return;+    }+    let vehicles: Vec<Marker> = (0..n)+        .map(|i| Marker {+            id: id_buf[i] as u64,+            lon: coord_buf[i * 2] as f64,+            lat: coord_buf[i * 2 + 1] as f64,+            icon: icon_buf[i] as u32,+        })+        .collect();+    map.renderer.set_vehicles(vehicles);+}++/// Take every simulated vehicle away: the transit toggle went off, or the surface was hidden.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearVehicles<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+) {+    if let Some(map) = handle_mut(handle) {+        map.renderer.set_vehicles(Vec::new());+    }+}+ /// Draw a navigation route line over the basemap and under the puck. ///-/// `points` is a flat `[lon0, lat0, lon1, lat1, …]` array. One array rather than a list of-/// objects because a route is thousands of points and a per-point JNI crossing is exactly-/// what the rest of this boundary exists to avoid; `float` rather than `double` for the-/// same reason the camera's coordinates are (see+/// `points` is a flat `[lon0, lat0, lon1, lat1, …]` array holding every coloured run's+/// points concatenated; `segment_lengths` is the point count of each run in order, and+/// `segment_colors` the ARGB fill of each, index for index. Three bulk arrays rather than a+/// list of objects because a route is thousands of points and a per-point JNI crossing is+/// exactly what the rest of this boundary exists to avoid; `float` rather than `double` for+/// the same reason the camera's coordinates are (see /// [`render`](Java_com_vayunmathur_library_map_MapNative_render)) — seven significant /// digits is about a centimetre at the equator, and a route is a shape to follow rather-/// than a survey. A trailing odd element is ignored.+/// than a survey. ///-/// One polyline and one colour, which is what the consumer draws: the car renderer this-/// replaces stroked a single `Path` over the whole route twice, a casing under a fill. The-/// phone's per-step traffic colouring stays in Compose over `VectorMap` and is not-/// migrating, so a per-segment API here would be surface with no caller.+/// A **list of coloured runs**, one casing: the phone colours the route per navigation+/// step (traffic bands, transit brand colours, a travelled grey behind the puck), and that+/// colouring now lives in the renderer so the route pans in lock-step with the basemap. The+/// casing is drawn once over the whole route and each run's fill over it in run colour. A+/// single-colour route (Android Auto) is just a one-run list. /// /// Tessellated here, on the calling thread, and uploaded once. That is affordable because /// it happens when the route is set and never again: the mesh is zoom-independent, so no /// frame and no zoom step rebuilds it. See [`crate::overlay`]. ///-/// An empty array, a single point, or a run of identical points draws nothing, which is-/// the same outcome as [`clearRoute`](Java_com_vayunmathur_library_map_MapNative_clearRoute).+/// An empty array, a run of fewer than two distinct points, or lengths that sum past the+/// points available all draw nothing for the affected run, and a route with no drawable run+/// is the same outcome as+/// [`clearRoute`](Java_com_vayunmathur_library_map_MapNative_clearRoute). Arrays that cannot+/// be read leave the route **unchanged** rather than blanking a route being followed. #[no_mangle] #[allow(clippy::too_many_arguments)] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setRoute<'l>(@@ -722,13 +879,14 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setRoute<'l>(     _class: JClass<'l>,     handle: jlong,     points: JFloatArray<'l>,+    segment_lengths: JIntArray<'l>,+    segment_colors: JIntArray<'l>,     width_dp: jfloat,     casing_dp: jfloat,-    color: jint,     casing_color: jint, ) {     let Some(map) = handle_mut(handle) else { return };-    let count = match env.get_array_length(&points) {+    let point_floats = match env.get_array_length(&points) {         Ok(length) => length.max(0) as usize,         // Reading failed, so we know nothing about the intended route. Leaving the current         // one alone beats blanking a route the driver is following.@@ -737,22 +895,43 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setRoute<'l>(             return;         }     };-    let mut flat = vec![0f32; count];+    let segment_count = env.get_array_length(&segment_lengths).unwrap_or(0).max(0) as usize;+    let color_count = env.get_array_length(&segment_colors).unwrap_or(0).max(0) as usize;+    let segment_count = segment_count.min(color_count);++    let mut flat = vec![0f32; point_floats];     if env.get_float_array_region(&points, 0, &mut flat).is_err() {         log("the route array could not be read; leaving the route unchanged");         return;     }-    let coords: Vec<(f64, f64)> =-        flat.chunks_exact(2).map(|pair| (pair[0] as f64, pair[1] as f64)).collect();-    let style = RouteStyle {-        width_dp,-        casing_dp,+    let mut lengths = vec![0i32; segment_count];+    let mut colors = vec![0i32; segment_count];+    if segment_count > 0+        && (env.get_int_array_region(&segment_lengths, 0, &mut lengths).is_err()+            || env.get_int_array_region(&segment_colors, 0, &mut colors).is_err())+    {+        log("the route segment arrays could not be read; leaving the route unchanged");+        return;+    }++    // Walk the flat point buffer run by run: each length is a point count, so it consumes+    // twice that many floats. A length that would overrun the buffer is clamped, so a+    // mismatched pair truncates rather than reading past the array.+    let mut segments: Vec<RouteSegment> = Vec::with_capacity(segment_count);+    let mut cursor = 0usize;+    for (len, color) in lengths.into_iter().zip(colors) {+        let count = len.max(0) as usize;+        let end = (cursor + count * 2).min(flat.len());+        let run: Vec<(f64, f64)> =+            flat[cursor..end].chunks_exact(2).map(|pair| (pair[0] as f64, pair[1] as f64)).collect();+        cursor = end;         // ARGB arrives as a signed `int` because that is what a Kotlin colour is; the bit         // pattern is what matters and the cast keeps it.-        color: color as u32,-        casing_color: casing_color as u32,-    };-    let mesh = crate::overlay::tessellate(&coords, style);+        segments.push(RouteSegment { points: run, color: color as u32 });+    }++    let style = RouteStyle { width_dp, casing_dp, casing_color: casing_color as u32 };+    let mesh = crate::overlay::tessellate(&segments, style);     if let Err(e) = map.renderer.set_route(mesh.as_ref()) {         log(&format!("uploading the route failed: {e}"));     }@@ -834,6 +1013,11 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearRegionMas /// means every kind the style draws. A name the schema has no id for is skipped rather than /// refused: the chip list is app data and a typo there should narrow the map oddly, not blank it. ///+/// Traffic is a third optional layer but rides its own entry point+/// ([`setTrafficEnabled`](Java_com_vayunmathur_library_map_MapNative_setTrafficEnabled)) rather+/// than a fourth argument here, so adding it did not change this call's shape for the five+/// existing consumers.+/// /// A call that changes nothing bumps nothing, because the host is expected to call this /// from a Compose effect that may re-run for unrelated reasons. #[no_mangle]@@ -855,7 +1039,10 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setLayers<'l>(             .collect(),     );     if let Some(map) = handle_mut(handle) {-        let wanted = LayerToggles { poi: poi != 0, transit: transit != 0 };+        // Traffic is carried through its own setter, so preserve whatever it was set to.+        let traffic = map.toggles.get().0.traffic;+        let wanted =+            LayerToggles { poi: poi != 0, transit: transit != 0, traffic };         if map.toggles.set(wanted, filter) {             log_info(&format!(                 "layers changed: poi={} transit={} kinds=[{names}]",@@ -865,6 +1052,103 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setLayers<'l>(     } } +/// Turn the live-traffic overlay on or off.+///+/// Gates the overlay at **tessellation** like [`setLayers`], so an archive without the layer —+/// or a consumer that never enables traffic — pays nothing: flipping it on bumps the toggle+/// generation and the resident tiles re-tessellate with the traffic layer through the existing+/// worker pool (nothing refetched, nothing evicted). It also flips a per-frame draw guard so a+/// toggle-off stops the overlay drawing immediately, before that re-tessellation lands.+///+/// The per-segment colours arrive separately through+/// [`setTrafficSpeeds`](Java_com_vayunmathur_library_map_MapNative_setTrafficSpeeds); this call+/// is only the geometry gate. Its own entry point rather than a fourth argument to [`setLayers`]+/// so the existing layer call keeps its shape.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setTrafficEnabled<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    enabled: jboolean,+) {+    if let Some(map) = handle_mut(handle) {+        let on = enabled != 0;+        // The renderer's per-frame draw guard, set every call so it tracks the toggle even+        // when the tessellation state is otherwise unchanged.+        map.renderer.set_traffic_enabled(on);+        // Re-use the current POI/transit/kinds snapshot and flip only traffic, so this+        // shares the one generation counter with setLayers rather than racing a second.+        let (current, kinds, _) = map.toggles.get();+        let wanted = LayerToggles { traffic: on, ..current };+        if map.toggles.set(wanted, kinds) {+            log_info(&format!("traffic layer {}", if on { "on" } else { "off" }));+        }+    }+}++/// Push the live-traffic colour table: `ids[i]` is a segment's `component_id` and+/// `colors[i]` the fully-resolved ARGB the device wants drawn for it.+///+/// Two parallel arrays rather than a packed buffer, agreed with the device workstream: it is+/// what a Kotlin caller already has in hand (a `LongArray` of ids and an `IntArray` of ARGB+/// from its own palette), and it crosses the boundary in two bulk `get_*_array_region` reads+/// with no per-element JNI traffic. The device owns the theme, so the colours are final here —+/// the renderer only looks them up.+///+/// Replacing the whole table each call, not merging: a viewport's worth of readings arrives at+/// once, and a stale id left behind would colour a road the latest data no longer covers.+/// Ids absent from the table draw nothing (the basemap road shows through), which is the+/// no-data behaviour. Mismatched lengths are truncated to the shorter. This is a pure+/// state swap — no tessellation and no upload — so it is the recolour hot path and is cheap.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setTrafficSpeeds<'l>(+    env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    ids: JLongArray<'l>,+    colors: JIntArray<'l>,+) {+    let Some(map) = handle_mut(handle) else { return };+    let id_len = env.get_array_length(&ids).unwrap_or(0).max(0) as usize;+    let color_len = env.get_array_length(&colors).unwrap_or(0).max(0) as usize;+    let n = id_len.min(color_len);+    if n == 0 {+        // An empty push is a clear: the host has no readings for the current viewport.+        map.renderer.clear_traffic();+        return;+    }+    let mut id_buf = vec![0i64; n];+    let mut color_buf = vec![0i32; n];+    if env.get_long_array_region(&ids, 0, &mut id_buf).is_err()+        || env.get_int_array_region(&colors, 0, &mut color_buf).is_err()+    {+        log("the traffic arrays could not be read; leaving the colours unchanged");+        return;+    }+    // The bit pattern is what matters: a Kotlin colour is a signed `int` and an id is a signed+    // `long`, and both reinterpret to the unsigned the renderer keys and paints with.+    let ids_u64: Vec<u64> = id_buf.into_iter().map(|v| v as u64).collect();+    let colors_u32: Vec<u32> = color_buf.into_iter().map(|v| v as u32).collect();+    map.renderer.set_traffic_speeds(&ids_u64, &colors_u32);+}++/// Take the live-traffic overlay away: the toggle went off, or the viewport moved off the+/// squares the host has readings for.+///+/// Clears the pushed colours so the overlay stops drawing on the very next frame, without+/// waiting for the toggle-driven re-tessellation to evict the geometry. Cheap and idempotent,+/// like [`clearRegionMask`](Java_com_vayunmathur_library_map_MapNative_clearRegionMask).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearTraffic<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+) {+    if let Some(map) = handle_mut(handle) {+        map.renderer.clear_traffic();+    }+}+ #[no_mangle] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setOnline<'l>(     _env: JNIEnv<'l>,@@ -941,6 +1225,32 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_pickLabels<'l>     out } +/// Pick the renderer-drawn marker under a tap: the id-buffer readback path.+///+/// `x`/`y` are Dp from the viewport top-left, converted to device px with the last frame's+/// density (the same conversion [`pickLabels`](Java_com_vayunmathur_library_map_MapNative_pickLabels)+/// makes), because the id buffer is device-px. Returns the tapped marker's own id — the value the+/// host set on it in [`setMarkers`](Java_com_vayunmathur_library_map_MapNative_setMarkers) — so the+/// host rejoins the tap to its feature without matching on position, or `0` when the tap hit no+/// marker. That replaces the Compose CPU hit-test, which trailed the basemap on a pan and could not+/// place a pin's box under tilt at all.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_pickAt<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    x_dp: jfloat,+    y_dp: jfloat,+) -> jlong {+    let Some(map) = handle_mut(handle) else { return 0 };+    let density = map.density;+    // Negative Dp is off the top-left of the viewport; clamp to zero before scaling so the cast to+    // an unsigned device coordinate cannot wrap. The native side clamps the far edges to the extent.+    let x = (x_dp.max(0.0) * density).round() as u32;+    let y = (y_dp.max(0.0) * density).round() as u32;+    map.renderer.pick_at(x, y) as jlong+}+ fn handle_mut(handle: jlong) -> Option<&'static mut MapHandle> {     if handle == 0 {         return None;
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 08f313c923..5443226bfb 100644--- a/library/map/src/main/rust/src/camera.rs+++ b/library/map/src/main/rust/src/camera.rs@@ -23,6 +23,15 @@ /// floor of the camera zoom and every ramp is evaluated at the zoom the style means. pub const TILE_SIZE: f64 = 512.0; +/// Largest camera tilt we allow, in degrees.+///+/// Not cosmetic: at this cap the horizon still sits above the top of the screen (the+/// perspective's far edge is a finite ground distance), so [`Camera::screen_to_world`]+/// always meets the ground plane and tile selection never has to cover an infinite+/// trapezoid. `fy = d/half_h = 3` and the horizon enters the screen only past+/// `atan(fy) ≈ 71°`, so 60 leaves a margin. See [`Camera::pitch_deg`].+pub const PITCH_MAX_DEG: f64 = 60.0;+ /// The camera as Kotlin measured it. #[derive(Clone, Copy, Debug)] pub struct Camera {@@ -37,10 +46,25 @@ pub struct Camera {     /// Which compass direction points **up** the screen, in degrees clockwise from     /// north. Zero is north-up, which is every path but heading-up car navigation.     ///-    /// A rotation, not a tilt: the projection stays orthographic, so this composes-    /// into the clip matrices as a plain 2x2 and nothing downstream needs a-    /// perspective divide. Tilt would be a different and much larger change.+    /// A rotation, not a tilt: it composes into the clip matrices as a plain 2x2. Tilt is+    /// [`pitch_deg`](Self::pitch_deg), which is the perspective term and composes separately.     pub bearing_deg: f64,+    /// Camera tilt away from straight-down, in degrees, expected in `0..=`[`PITCH_MAX_DEG`]+    /// (the JNI boundary clamps it; the matrices below assume nothing).+    ///+    /// Zero is the classic top-down orthographic map — every path but the tilt gesture — and+    /// is short-circuited in every matrix builder so the ortho fast-path is byte-for-byte what+    /// it always was. Above zero [`world_quad_to_clip`](Self::world_quad_to_clip) produces a+    /// true perspective (real z, w-divide) and [`screen_quad_to_clip`](Self::screen_quad_to_clip)+    /// billboards its quad upright.+    pub pitch_deg: f64,+    /// Seconds since an arbitrary epoch, forwarded from the host's per-frame `frameTimeNanos`.+    ///+    /// Not part of the projection — it never enters a matrix, so it changes no camera test —+    /// but it rides on the camera because it is the other thing that arrives exactly once per+    /// frame. The renderer forwards it to shaders through the `Push.misc.w` slot; the animated+    /// workstreams (dash phase, LOD morph, vehicles) read it there.+    pub time_seconds: f32, }  /// A point in Web Mercator world pixels at some zoom.@@ -50,6 +74,21 @@ pub struct WorldPx {     pub y: f64, } +/// The tilt-dependent constants of the perspective projection, computed once per matrix.+///+/// Only built on the pitched path; the ortho fast-path never touches it. `d` is the+/// camera-to-centre distance and cancels at pitch 0, so its only job is setting how strong+/// the foreshortening is; `fx`/`fy` are focal terms; `depth_a`/`depth_b` map view distance to+/// Vulkan's `[0, 1]` clip depth (`ndc_z = depth_a - depth_b/w`).+#[derive(Clone, Copy)]+struct Perspective {+    fx: f64,+    fy: f64,+    d: f64,+    depth_a: f64,+    depth_b: f64,+}+ /// Total map width and height in logical px at `zoom`. pub fn world_size(zoom: f64) -> f64 {     TILE_SIZE * 2f64.powf(zoom)@@ -187,15 +226,23 @@ impl Camera {         // the rotation.         let dx = origin.x - center.x;         let dy = origin.y - center.y;-        let kx = 2.0 / self.width_dp as f64;-        let ky = 2.0 / self.height_dp as f64;+        if self.pitch_deg == 0.0 {+            let kx = 2.0 / self.width_dp as f64;+            let ky = 2.0 / self.height_dp as f64; -        [-            (kx * cos * span) as f32, (ky * -sin * span) as f32, 0.0, 0.0, //-            (kx * sin * span) as f32, (ky * cos * span) as f32, 0.0, 0.0, //-            0.0, 0.0, 1.0, 0.0, //-            (kx * (cos * dx + sin * dy)) as f32, (ky * (-sin * dx + cos * dy)) as f32, 0.0, 1.0,-        ]+            return [+                (kx * cos * span) as f32, (ky * -sin * span) as f32, 0.0, 0.0, //+                (kx * sin * span) as f32, (ky * cos * span) as f32, 0.0, 0.0, //+                0.0, 0.0, 1.0, 0.0, //+                (kx * (cos * dx + sin * dy)) as f32, (ky * (-sin * dx + cos * dy)) as f32, 0.0, 1.0,+            ];+        }+        // Tilted: the same bearing-rotated screen offset as above, but kept as world px (Dp)+        // rather than pre-scaled to clip, and fed through the perspective divide. `a`/`b` are+        // the `u`/`v`/constant terms of a tile-local point's screen offset `sx`/`sy`.+        let a = [cos * span, sin * span, cos * dx + sin * dy];+        let b = [-sin * span, cos * span, -sin * dx + cos * dy];+        self.perspective_plane(a, b)     }      /// Column-major 4x4 taking a quad's local −1..1 coordinates to Vulkan clip space,@@ -226,16 +273,242 @@ impl Camera {         let (cos, sin) = self.rotation();         let dx = anchor.x - center.x;         let dy = anchor.y - center.y;-        let kx = 2.0 / self.width_dp as f64;-        let ky = 2.0 / self.height_dp as f64;+        if self.pitch_deg == 0.0 {+            let kx = 2.0 / self.width_dp as f64;+            let ky = 2.0 / self.height_dp as f64; +            return [+                (kx * cos * radius_dp) as f32, (ky * -sin * radius_dp) as f32, 0.0, 0.0, //+                (kx * sin * radius_dp) as f32, (ky * cos * radius_dp) as f32, 0.0, 0.0, //+                0.0, 0.0, 1.0, 0.0, //+                (kx * (cos * dx + sin * dy)) as f32, (ky * (-sin * dx + cos * dy)) as f32, 0.0, 1.0,+            ];+        }+        // Tilted: project the anchor's ground point through the same perspective, then hang a+        // screen-aligned quad of fixed Dp size off it. The corners offset in clip by the+        // anchor's own `w`, so the perspective divide leaves a constant *screen* size — the quad+        // stays upright and keeps its radius rather than being smeared along the ground. Its+        // local axes still turn with the bearing, so the puck's cone points the right way.+        let (psin, pcos) = self.pitch_deg.to_radians().sin_cos();+        let p = self.perspective();+        let sx = cos * dx + sin * dy;+        let sy = -sin * dx + cos * dy;+        let aw = p.d - psin * sy;+        let ax = p.fx * sx;+        let ay = p.fy * pcos * sy;+        let az = p.depth_a * aw - p.depth_b;+        let rx = radius_dp / (self.width_dp as f64 / 2.0) * aw;+        let ry = radius_dp / (self.height_dp as f64 / 2.0) * aw;         [-            (kx * cos * radius_dp) as f32, (ky * -sin * radius_dp) as f32, 0.0, 0.0, //-            (kx * sin * radius_dp) as f32, (ky * cos * radius_dp) as f32, 0.0, 0.0, //-            0.0, 0.0, 1.0, 0.0, //-            (kx * (cos * dx + sin * dy)) as f32, (ky * (-sin * dx + cos * dy)) as f32, 0.0, 1.0,+            (cos * rx) as f32, (-sin * ry) as f32, 0.0, 0.0, //+            (sin * rx) as f32, (cos * ry) as f32, 0.0, 0.0, //+            0.0, 0.0, 0.0, 0.0, //+            ax as f32, ay as f32, az as f32, aw as f32,         ]     }++    /// The tilt-dependent perspective constants for this camera. See [`Perspective`].+    fn perspective(&self) -> Perspective {+        let half_w = self.width_dp as f64 / 2.0;+        let half_h = self.height_dp as f64 / 2.0;+        // MapLibre-like: the centre sits 1.5 viewport-heights from the eye. `d` cancels at+        // pitch 0, so this only sets the foreshortening strength.+        let d = 1.5 * self.height_dp as f64;+        let n = 0.1 * d;+        let f = 10.0 * d;+        Perspective { fx: d / half_w, fy: d / half_h, d, depth_a: f / (f - n), depth_b: f * n / (f - n) }+    }++    /// Build the perspective clip matrix from the screen-flat plane coefficients.+    ///+    /// `a = [a_u, a_v, a_0]` and `b = [b_u, b_v, b_0]` give the bearing-rotated screen offset of+    /// a tile-local point `(u, v)` from the camera centre, in world px (Dp): `sx = a_u*u + a_v*v+    /// + a_0`, `sy = b_u*u + b_v*v + b_0`. The matrix maps `(u, v, height, 1)`; the third input+    /// is a world-px height above the ground plane (0 for every flat 2D layer, a real height for+    /// buildings/terrain).+    ///+    /// # Camera model (the seam WS-G extends to a heightfield)+    ///+    /// The ground is a plane at camera-to-centre distance `d`, tilted back by `pitch`. A point at+    /// screen-flat offset `(sx, sy)` and height `hh` sits in camera space at+    /// ```text+    /// Xc = sx+    /// Yc = -sy*cos + hh*sin+    /// Zc = -d + sy*sin + hh*cos      (w = -Zc, the perspective divisor)+    /// ```+    /// with `sy > 0` (lower on screen) nearer the eye. With `fx = d/half_w`, `fy = d/half_h` the+    /// projection reduces, at `pitch == 0` and `hh == 0`, term-for-term to the ortho matrix — the+    /// reason pitch 0 takes the fast path and this is only ever built when tilted. WS-G replaces+    /// the flat `hh` here (and the single plane solve in [`screen_to_world`](Self::screen_to_world))+    /// with a DEM sample; keep the forward and inverse in step.+    fn perspective_plane(&self, a: [f64; 3], b: [f64; 3]) -> [f32; 16] {+        let (sin, cos) = self.pitch_deg.to_radians().sin_cos();+        let Perspective { fx, fy, d, depth_a, depth_b } = self.perspective();

Diff truncated.