library:map: Vulkan vector-tile renderer replaces CARTO raster tiles
- Commit
b3eaa856e2a8242da99cbf1346ea1360cda506fa- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 16:58 UTC (3 months ago)
- Parents
ea98676
Diff
.gitattributes
diff --git a/.gitattributes b/.gitattributesindex 85575e96d8..6e5059f8c3 100644--- a/.gitattributes+++ b/.gitattributes@@ -42,6 +42,11 @@ gradlew text eol=lf *.dat -text *.db -text *.pmtiles -text+# Vector tiles are protobuf, and the test fixtures are regenerated from the live archive by+# `probe_archive`. They happen to carry a NUL early enough for git's heuristic to guess binary+# today, but they also carry CRLF pairs, so a regenerated tile that guessed "text" would have+# bytes stripped and fail to decode as a protobuf error rather than a corruption.+*.mvt -text *.spv -text # ---- Archives / compressed ----
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 2555edc161..76c515a20f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -185,6 +185,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]]+name = "appstore_signify"+version = "0.1.0"+dependencies = [+ "base64",+ "ed25519-dalek",+ "jni",+]+ [[package]] name = "array_ref" version = "0.1.0"@@ -205,6 +214,15 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]]+name = "ash"+version = "0.38.0+1.3.281"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"+dependencies = [+ "libloading",+]+ [[package]] name = "astronomy_engine" version = "0.1.0"@@ -1739,6 +1757,16 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]+ [[package]] name = "linux-raw-sys" version = "0.4.15"@@ -1799,6 +1827,18 @@ dependencies = [ "weezl", ] +[[package]]+name = "map_renderer"+version = "0.1.0"+dependencies = [+ "ash",+ "jni",+ "jni_http",+ "serde_json",+ "sha2 0.10.9",+ "tilecodec",+]+ [[package]] name = "md-5" version = "0.10.6"@@ -1839,6 +1879,14 @@ dependencies = [ "simd-adler32", ] +[[package]]+name = "modelrunner"+version = "0.1.0"+dependencies = [+ "ash",+ "jni",+]+ [[package]] name = "network_location_position_estimation_rust" version = "0.1.0"@@ -2955,6 +3003,13 @@ dependencies = [ "syn 3.0.3", ] +[[package]]+name = "tilecodec"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+]+ [[package]] name = "tinystr" version = "0.8.3"
build-logic/src/main/kotlin/NativeAbis.kt
diff --git a/build-logic/src/main/kotlin/NativeAbis.kt b/build-logic/src/main/kotlin/NativeAbis.ktindex 4647341dee..f3d00fbf24 100644--- a/build-logic/src/main/kotlin/NativeAbis.kt+++ b/build-logic/src/main/kotlin/NativeAbis.kt@@ -6,6 +6,18 @@ const val ABI_ARM64 = "arm64-v8a" /** armeabi-v7a: 32-bit-userspace devices, notably Google TV boxes. */ const val ABI_ARMV7 = "armeabi-v7a" +/**+ * 64-bit x86, which no shipping device uses — it is what the Android emulator runs on an+ * x86_64 host.+ *+ * No app should package this: `arm64-v8a` covers every phone and tablet, and on Apple+ * Silicon the emulator is arm64 too. It exists so a native module can be *tested* in an+ * emulator on an x86_64 host, where the alternative is a full-system QEMU translation of an+ * arm64 image. Opt in per module through `rustNativeLib`'s `extraAbis`, and gate it on a+ * Gradle property so release builds never carry it.+ */+const val ABI_X86_64 = "x86_64"+ /** * Per-app ABI opt-in, consumed by `common-conventions-app`. Apps stay arm64-only * unless they declare otherwise:
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktindex 2f66ff285e..1192f4e628 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -28,6 +28,8 @@ data class RustAbi(val abiDir: String, val triple: String, val clangPrefix: Stri private val KNOWN_RUST_ABIS = listOf( RustAbi(ABI_ARM64, "aarch64-linux-android", "aarch64-linux-android"), RustAbi(ABI_ARMV7, "armv7-linux-androideabi", "armv7a-linux-androideabi"),+ // Emulator-only; see [ABI_X86_64]. Never packaged by default.+ RustAbi(ABI_X86_64, "x86_64-linux-android", "x86_64-linux-android"), ) /**
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex 01978b8f49..e9f77f8142 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -130,6 +130,13 @@ configure<com.android.build.api.dsl.ApplicationExtension> { // 32-bit devices (Google TV) opt in with `nativeAbis { armv7 = true }`. ndk { abiFilters.add(ABI_ARM64)+ // `-PemulatorAbi=x86_64` additionally packages x86_64, so a native module can+ // be run in an emulator on an x86_64 host. Off unless asked for, so no release+ // build is affected. abiFilters only filters what was built, so the module+ // must also opt in via `rustNativeLib(extraAbis = ...)`.+ if (providers.gradleProperty("emulatorAbi").orNull == ABI_X86_64) {+ abiFilters.add(ABI_X86_64)+ } } } @@ -184,6 +191,9 @@ configure<com.android.build.api.dsl.ApplicationExtension> { ndk { abiFilters.clear() abiFilters.add(ABI_ARM64)+ if (providers.gradleProperty("emulatorAbi").orNull == ABI_X86_64) {+ abiFilters.add(ABI_X86_64)+ } } // initWith(release) copied DEV_BUILD=false; dev is a developer build, so flip it on. buildConfigField("boolean", "DEV_BUILD", "true")
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.ktindex cdd67e2afc..8982dc7768 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -52,8 +52,7 @@ import kotlinx.coroutines.withContext import com.vayunmathur.library.map.CameraPosition import com.vayunmathur.library.map.CameraState import com.vayunmathur.library.map.GeoPoint-import com.vayunmathur.library.map.RasterMap-import com.vayunmathur.library.map.TileSource+import com.vayunmathur.library.map.VectorMap import kotlin.io.encoding.Base64 import kotlin.math.abs import kotlin.math.cos@@ -102,9 +101,8 @@ fun MapView( ) } }) {- RasterMap(+ VectorMap( cameraState = camera,- tileSource = TileSource.CartoVoyager, zoomRange = 0f..20f, onMapClick = { onMapClick() }, )
findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt
diff --git a/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt b/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.ktindex d7cac7f738..0363e8f15a 100644--- a/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt+++ b/findfamily/src/screenshotTest/kotlin/com/vayunmathur/findfamily/ui/MetadataPreviews.kt@@ -135,14 +135,20 @@ class MetadataPreviews { ) /**- * Stands in for the live [MapView] in the `map` slot. Layoutlib cannot fetch the network- * raster tiles the real [MapView] draws, so instead of a synthetic grid we bundle a real- * CARTO Voyager basemap mosaic (`preview_map_sf.png`, a screenshotTest-only classpath+ * Stands in for the live [MapView] in the `map` slot. Layoutlib cannot reach the network,+ * and the real [MapView] now draws through Vulkan besides, so instead of a synthetic grid+ * we bundle a real basemap mosaic (`preview_map_sf.png`, a screenshotTest-only classpath * resource centered on [mayaLocation]) and overlay the sample person marker exactly like * the app does. The mosaic is a JVM resource rather than an Android drawable so it never- * ships in the app APK. The "© CARTO © OpenStreetMap" attribution is required by the- * basemap terms and must stay visible. Image + static overlays only — no network or- * effects — so it renders under Layoutlib.+ * ships in the app APK. Image + static overlays only — no network or effects — so it+ * renders under Layoutlib.+ *+ * **The mosaic is stale.** It is a CARTO Voyager capture, and the app no longer renders+ * CARTO tiles — it renders the self-hosted Protomaps archive. The attribution below still+ * credits CARTO because that is what this *image* is, and crediting Protomaps for a CARTO+ * capture would be a worse error than the staleness. Regenerating it means capturing the+ * Vulkan renderer on a device, which has to wait until that is verified on hardware; the+ * attribution moves to "© OpenStreetMap contributors · Protomaps" in the same change. */ @Composable private fun StaticMapBackdrop() {
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.ktindex af71314cf4..20fc1c3b75 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt@@ -37,8 +37,7 @@ import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.map.CameraPosition import com.vayunmathur.library.map.GeoPoint-import com.vayunmathur.library.map.RasterMap-import com.vayunmathur.library.map.TileSource+import com.vayunmathur.library.map.VectorMap import com.vayunmathur.library.map.rememberCameraState import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Button@@ -219,7 +218,7 @@ private fun TrackingMap(order: Order, modifier: Modifier = Modifier) { } Box(modifier) {- RasterMap(cameraState = camera, tileSource = TileSource.CartoVoyager)+ VectorMap(cameraState = camera) val projection = camera.projection if (projection != null) { // Distinct glyph per pin: menu = restaurant, arrow = courier, home = you.
library/map/build.gradle.kts
diff --git a/library/map/build.gradle.kts b/library/map/build.gradle.ktsindex 102d7c9be0..41c6df43b3 100644--- a/library/map/build.gradle.kts+++ b/library/map/build.gradle.kts@@ -2,14 +2,51 @@ plugins { id("common-conventions-library") } +androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ )+ }+}+ dependencies { implementation(libs.androidx.compose.foundation) - // Tile fetching + memory/disk cache via library:image (replaces coil).- implementation(project(":library:image"))+ // The renderer's HTTP transport. The Rust crate does not open sockets: it calls back+ // through library/jni-http into NativeHttpBridge here, so pmtiles range requests keep+ // library:network's reduced CA bundle and HttpURLConnection-only policy, and the+ // renderer gains no second TLS stack.+ implementation(project(":library:network")) // Own GeoPoint/GeoBounds – no spatialk exposure for non-maplibre apps. // :maps gets spatialk transitively via maplibre-compose where required. // spatialk dependency fully removed from :library:map after migration. + // :library:image is deliberately gone: it existed to fetch and decode CARTO raster+ // PNGs, and there is no raster tile path any more. }++// The Vulkan vector-tile renderer: `library/map/src/main/rust`, on ash.+//+// arm64 only, which is what the five consumer apps build+// (`common-conventions-app.gradle.kts:131-133`). `libvulkan.so` is on the device, so this+// .so is our own code and nothing else — the whole size argument against bundling Dawn.+//+// `-PemulatorAbi=x86_64` additionally builds x86_64 so the renderer can be run in an+// emulator on an x86_64 host. Vulkan cannot be verified on a build host, and an arm64+// system image on such a host means full-system QEMU translation, so this is the only+// practical way to exercise the GPU path here. Never on by default.+//+// Shaders are GLSL compiled to SPIR-V by the crate's own build.rs, which resolves glslc+// from the NDK and fails the build if it cannot — deliberately unlike+// games/voxels/src/main/rust/build.rs, which writes a 28-byte stub and then draws nothing.+rustNativeLib(+ "map_renderer",+ "map",+ extraAbis = if (providers.gradleProperty("emulatorAbi").orNull == ABI_X86_64) {+ listOf(ABI_X86_64)+ } else {+ emptyList()+ },+)
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.ktnew file mode 100644index 0000000000..a40b712625--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt@@ -0,0 +1,182 @@+package com.vayunmathur.library.map++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.detectTransformGestures+import androidx.compose.foundation.gestures.waitForUpOrCancellation+import androidx.compose.runtime.Composable+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+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.PointerInputChange+import androidx.compose.ui.input.pointer.PointerInputScope+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.sign++/**+ * Viewport measurement and every pan/zoom/tap gesture the map supports.+ *+ * Extracted from [RasterMap] so the WebGPU renderer behaves identically rather+ * than approximately: pan, pinch, double-tap-to-zoom and the double-tap-hold-swipe+ * "quick zoom" are what users of five apps already have, and a second+ * implementation would drift from this one. It also means the px-to-Dp conversion+ * happens in exactly one place, which is the regression the plan is most worried+ * about.+ */+@Composable+internal fun Modifier.mapGestures(+ cameraState: CameraState,+ gestures: GestureOptions,+ zoomRange: ClosedFloatingPointRange<Float>,+ density: Float,+ onMapClick: (GeoPoint) -> Unit,+): Modifier {+ val scope = rememberCoroutineScope()+ // In-flight double-tap zoom animation, cancelled as soon as a new gesture wants+ // to drive the camera itself.+ val zoomAnim = remember { mutableStateOf<Job?>(null) }++ fun toDp(offsetPx: Offset) = Offset(offsetPx.x / density, offsetPx.y / density)+ fun clickAt(offsetPx: Offset) {+ val projection = cameraState.projection ?: return+ val dp = toDp(offsetPx)+ onMapClick(projection.positionFromScreenLocation(DpOffset(dp.x.dp, dp.y.dp)))+ }++ return this+ .onSizeChanged {+ cameraState.setViewport(Size(it.width / density, it.height / density))+ }+ .pointerInput(cameraState, gestures, zoomRange, density) {+ detectTransformGestures { centroid, pan, zoom, _ ->+ if (!gestures.isScrollEnabled && !gestures.isZoomEnabled) return@detectTransformGestures+ zoomAnim.value?.cancel()+ cameraState.onGesture(+ centroidDp = toDp(centroid),+ panDp = toDp(pan),+ zoomChange = zoom,+ minZoom = zoomRange.start.toDouble(),+ maxZoom = zoomRange.endInclusive.toDouble(),+ scrollEnabled = gestures.isScrollEnabled,+ zoomEnabled = gestures.isZoomEnabled,+ )+ }+ }+ // 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) {+ if (!gestures.isZoomEnabled) {+ // Nothing to disambiguate against, so report taps immediately.+ detectTapGestures { clickAt(it) }+ } else {+ var quickZoomStart = cameraState.position+ detectTapAndQuickZoomGestures(+ onTap = { clickAt(it) },+ onDoubleTap = { anchor ->+ zoomAnim.value?.cancel()+ zoomAnim.value = scope.launch {+ cameraState.animateZoomBy(+ deltaZoom = 1.0,+ anchorDp = toDp(anchor),+ minZoom = zoomRange.start.toDouble(),+ maxZoom = zoomRange.endInclusive.toDouble(),+ )+ }+ },+ onQuickZoomStart = {+ zoomAnim.value?.cancel()+ quickZoomStart = cameraState.position+ },+ onQuickZoom = { anchor, dragPx ->+ cameraState.onQuickZoom(+ from = quickZoomStart,+ anchorDp = toDp(anchor),+ dragDp = dragPx / density,+ minZoom = zoomRange.start.toDouble(),+ maxZoom = zoomRange.endInclusive.toDouble(),+ )+ },+ )+ }+ }+}++/**+ * 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.+ *+ * Meant to sit alongside [detectTransformGestures]: it stays out of the way of+ * pan/pinch, and once a quick-zoom drag passes touch slop it consumes the moves so+ * the transform detector cancels instead of also panning.+ */+private suspend fun PointerInputScope.detectTapAndQuickZoomGestures(+ onTap: (Offset) -> Unit,+ onDoubleTap: (Offset) -> Unit,+ onQuickZoomStart: () -> Unit,+ onQuickZoom: (anchor: Offset, dragPx: Float) -> Unit,+) = awaitEachGesture {+ val down = awaitFirstDown()+ down.consume()+ val up = waitForUpOrCancellation() ?: return@awaitEachGesture+ up.consume()++ val secondDown = awaitSecondDown(up)+ if (secondDown == null) {+ onTap(up.position)+ return@awaitEachGesture+ }+ secondDown.consume()++ // Zoom about the tapped point, which stays put for the whole gesture+ // (following the finger instead would drift the map out from under it).+ val anchor = up.position+ val slop = viewConfiguration.touchSlop+ var zooming = false+ var dragOrigin = 0f+ while (true) {+ val event = awaitPointerEvent()+ // A second finger means the user wants a pinch; hand it over untouched.+ if (event.changes.size > 1) return@awaitEachGesture+ val change = event.changes.firstOrNull { it.id == secondDown.id } ?: break+ if (!change.pressed) {+ change.consume()+ break+ }+ val dy = change.position.y - secondDown.position.y+ if (!zooming) {+ if (abs(dy) < slop) continue+ // Start measuring from the slop boundary so the zoom doesn't jump.+ dragOrigin = dy - slop * sign(dy)+ zooming = true+ onQuickZoomStart()+ }+ change.consume()+ onQuickZoom(anchor, dy - dragOrigin)+ }+ if (!zooming) onDoubleTap(anchor)+}++/** The second down of a double-tap, or null if none arrives in time. */+private suspend fun AwaitPointerEventScope.awaitSecondDown(+ firstUp: PointerInputChange,+): PointerInputChange? = withTimeoutOrNull(viewConfiguration.doubleTapTimeoutMillis) {+ val minUptime = firstUp.uptimeMillis + viewConfiguration.doubleTapMinTimeMillis+ var change: PointerInputChange+ do {+ change = awaitFirstDown()+ } while (change.uptimeMillis < minUptime)+ change+}
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.ktnew file mode 100644index 0000000000..0d3f381048--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -0,0 +1,92 @@+package com.vayunmathur.library.map++import android.view.Surface++/**+ * The JNI surface of the Vulkan renderer in `library/map/src/main/rust`.+ *+ * Deliberately five methods and nothing per-feature: Kotlin creates and destroys the+ * renderer for a [Surface], resizes it, reports connectivity, and hands it **one+ * camera snapshot per frame**. Tile selection, fetching, decode, tessellation and+ * drawing all happen on the native side, so the boundary is crossed a handful of times+ * a frame rather than thousands.+ *+ * [handle] values are opaque pointers owned by the native side. Every method tolerates+ * `0`, which is what [create] returns on failure — so a device without a working Vulkan+ * driver degrades to a blank map rather than crashing the app.+ */+internal object MapNative {++ /**+ * Whether `libmap_renderer.so` loaded.+ *+ * False on a device whose ABI we did not build for. The caller shows the background+ * colour rather than crashing.+ */+ val isAvailable: Boolean = try {+ System.loadLibrary("map_renderer")+ true+ } catch (_: Throwable) {+ false+ }++ /**+ * Bring up Vulkan on [surface]. Returns an opaque handle, or 0 on failure.+ *+ * [cacheDir] is where the range cache lives. It should be external files rather than+ * the cache dir: like the archive `maps` downloads, it is large and expensive to+ * rebuild, so it should not be the first thing the platform reclaims.+ */+ external fun create(+ surface: Surface,+ cacheDir: String,+ width: Int,+ height: Int,+ dark: Boolean,+ muted: Boolean,+ ): Long++ /**+ * Draw one frame. Returns false when the frame was skipped because the swapchain+ * needed rebuilding — the next callback will draw.+ *+ * The camera is passed as primitives, not an object, so the call allocates nothing.+ * Longitude and latitude are `Float` rather than `Double` deliberately: a float has+ * ~7 significant digits, which at the equator is about a centimetre, and the camera+ * is a viewing position rather than a measurement.+ */+ external fun render(+ handle: Long,+ centerLon: Float,+ centerLat: Float,+ zoom: Float,+ widthDp: Float,+ heightDp: Float,+ density: Float,+ ): Boolean++ external fun resize(handle: Long, width: Int, height: Int)++ /**+ * Switch palette: light or dark, muted or not.+ *+ * Free: colour reaches the GPU as a push constant and the layer set is identical, so+ * nothing is re-tessellated or re-uploaded. That is why this is a runtime call rather+ * than a [create] argument — the map can follow the system theme.+ */+ external fun setPalette(handle: Long, dark: Boolean, muted: Boolean)++ /**+ * 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.+ */+ external fun setOnline(handle: Long, online: Boolean)++ /**+ * Destroy the renderer, wait for the GPU to go idle, and release the window.+ *+ * Must be called before the [Surface] is released, and exactly once per successful+ * [create].+ */+ external fun destroy(handle: Long)+}
library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.ktindex d755004532..1b3f3b3ee2 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt@@ -18,9 +18,16 @@ data class GestureOptions( } /**- * Map ornaments. Only the attribution label is supported. CARTO/OSM terms- * require visible attribution, so leave it enabled unless the host renders its- * own (e.g. weather shows attribution in its bottom panel).+ * Map ornaments.+ *+ * Attribution is **not** one of them any more, despite [isAttributionEnabled] still being+ * here: `VectorMap` renders it unconditionally, because the OpenStreetMap data's ODbL and+ * the Protomaps schema both require visible credit, and that is a licence condition rather+ * than a host preference. [AllDisabled] therefore cannot hide it — `weather` passes+ * [AllDisabled] and still gets attribution, which is the intended behaviour.+ *+ * The flag is kept because it is part of the options object's shape; it currently governs+ * nothing else, since attribution is the only ornament that was ever implemented. */ data class OrnamentOptions( val isAttributionEnabled: Boolean = true,
library/map/src/main/java/com/vayunmathur/library/map/MapStyle.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapStyle.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapStyle.ktnew file mode 100644index 0000000000..2d467821bb--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapStyle.kt@@ -0,0 +1,30 @@+package com.vayunmathur.library.map++/**+ * Which basemap to draw.+ *+ * Replaces `TileSource`, which named a CARTO raster URL template. There is no URL here+ * because there is no third-party tile source any more: every app renders the self-hosted+ * `data.vayunmathur.com/v4.pmtiles` archive, and the only choice left is how to paint it.+ *+ * Light and dark are a separate axis — see `VectorMap`'s `darkBasemap`, which follows the+ * system theme — so each of these has both.+ */+enum class MapStyle {+ /**+ * The full-contrast basemap. What most apps want.+ *+ * Replaces `TileSource.CartoVoyager`.+ */+ Standard,++ /**+ * The same map, receded, for hosts that draw their own data on top of it.+ *+ * Replaces `TileSource.CartoPositron`, and exists for the same reason it did: `weather`+ * draws a colour-ramp overlay over the basemap, and a full-contrast map underneath+ * fights it for attention. Every colour is blended toward the background, so roads+ * still read as roads but nothing competes with the overlay.+ */+ Muted,+}
library/map/src/main/java/com/vayunmathur/library/map/RasterMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/RasterMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/RasterMap.ktdeleted file mode 100644index 7b1c5884ac..0000000000--- a/library/map/src/main/java/com/vayunmathur/library/map/RasterMap.kt+++ /dev/null@@ -1,373 +0,0 @@-package com.vayunmathur.library.map--import androidx.compose.foundation.Canvas-import androidx.compose.foundation.background-import androidx.compose.foundation.gestures.awaitEachGesture-import androidx.compose.foundation.gestures.awaitFirstDown-import androidx.compose.foundation.gestures.detectTapGestures-import androidx.compose.foundation.gestures.detectTransformGestures-import androidx.compose.foundation.gestures.waitForUpOrCancellation-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.geometry.Size-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.ImageBitmap-import androidx.compose.ui.graphics.drawscope.DrawScope-import androidx.compose.ui.input.pointer.AwaitPointerEventScope-import androidx.compose.ui.input.pointer.PointerInputChange-import androidx.compose.ui.input.pointer.PointerInputScope-import androidx.compose.ui.input.pointer.pointerInput-import androidx.compose.ui.layout.onSizeChanged-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.platform.LocalDensity-import androidx.compose.ui.text.TextStyle-import androidx.compose.ui.text.font.FontFamily-import androidx.compose.ui.unit.DpOffset-import androidx.compose.ui.unit.IntOffset-import androidx.compose.ui.unit.IntSize-import androidx.compose.ui.unit.dp-import androidx.compose.ui.unit.sp-import com.vayunmathur.library.image.ImageLoader-import kotlinx.coroutines.Job-import kotlinx.coroutines.launch-import kotlin.math.abs-import kotlin.math.floor-import kotlin.math.pow-import kotlin.math.roundToInt-import kotlin.math.sign--/** Placement of one tile in the viewport, in logical (dp) coordinates. */-private data class TileBox(- val key: TileKey,- val leftDp: Float,- val topDp: Float,- val sizeDp: Float,-)--/** Background shown behind tiles before/if they load. */-private val MapBackground = Color(0xFFE9E7E2)--/**- * A Compose-native Web-Mercator raster tile viewer. Renders XYZ tiles from- * [tileSource] on a Canvas with parent-tile fallback (no blank flashes while- * panning/zooming), exposes a maplibre-compatible camera/projection via- * [cameraState], and draws an optional georeferenced [imageOverlay] plus a- * composable [content] overlay above the tiles.- */-@Composable-fun RasterMap(- cameraState: CameraState,- modifier: Modifier = Modifier,- tileSource: TileSource = TileSource.CartoVoyager,- zoomRange: ClosedFloatingPointRange<Float> = 0f..20f,- options: MapOptions = MapOptions(),- imageOverlay: ImageOverlay? = null,- onMapClick: (GeoPoint) -> Unit = {},- onFrame: () -> Unit = {},- content: @Composable () -> Unit = {},-) {- val context = LocalContext.current- val density = LocalDensity.current.density- val scope = rememberCoroutineScope()-- val loader = remember(context) { ImageLoader.get(context) }- val cache = remember(tileSource, loader) { TileCache(context, loader, tileSource) }-- val minZoom = tileSource.minZoom- val maxZoom = tileSource.maxZoom- val gestures = options.gestureOptions-- // Fire onFrame whenever the camera moves (drives per-frame reprojection).- LaunchedEffect(cameraState.position, cameraState.viewportDp) {- if (cameraState.viewportDp != null) onFrame()- }-- // Compute the currently visible tiles (recomputed on move) and prefetch them.- val position = cameraState.position- val viewport = cameraState.viewportDp- val visible: List<TileBox> = remember(position, viewport, tileSource) {- if (viewport == null) emptyList() else computeVisibleTiles(position, viewport, minZoom, maxZoom)- }- LaunchedEffect(visible) { visible.forEach { cache.request(scope, it.key) } }-- // In-flight double-tap zoom animation, cancelled as soon as a new gesture- // wants to drive the camera itself.- val zoomAnim = remember { mutableStateOf<Job?>(null) }- fun toDp(offsetPx: Offset) = Offset(offsetPx.x / density, offsetPx.y / density)- fun clickAt(offsetPx: Offset) {- val proj = cameraState.projection ?: return- val dp = toDp(offsetPx)- onMapClick(proj.positionFromScreenLocation(DpOffset(dp.x.dp, dp.y.dp)))- }-- Box(- modifier- .fillMaxSize()- .background(MapBackground)- .onSizeChanged {- cameraState.setViewport(Size(it.width / density, it.height / density))- }- .pointerInput(cameraState, gestures, zoomRange, density) {- detectTransformGestures { centroid, pan, zoom, _ ->- if (!gestures.isScrollEnabled && !gestures.isZoomEnabled) return@detectTransformGestures- zoomAnim.value?.cancel()- cameraState.onGesture(- centroidDp = toDp(centroid),- panDp = toDp(pan),- zoomChange = zoom,- minZoom = zoomRange.start.toDouble(),- maxZoom = zoomRange.endInclusive.toDouble(),- scrollEnabled = gestures.isScrollEnabled,- zoomEnabled = gestures.isZoomEnabled,- )- }- }- // 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) {- if (!gestures.isZoomEnabled) {- // Nothing to disambiguate against, so report taps immediately.- detectTapGestures { clickAt(it) }- } else {- var quickZoomStart = cameraState.position- detectTapAndQuickZoomGestures(- onTap = { clickAt(it) },- onDoubleTap = { anchor ->- zoomAnim.value?.cancel()- zoomAnim.value = scope.launch {- cameraState.animateZoomBy(- deltaZoom = 1.0,- anchorDp = toDp(anchor),- minZoom = zoomRange.start.toDouble(),- maxZoom = zoomRange.endInclusive.toDouble(),- )- }- },- onQuickZoomStart = {- zoomAnim.value?.cancel()- quickZoomStart = cameraState.position- },- onQuickZoom = { anchor, dragPx ->- cameraState.onQuickZoom(- from = quickZoomStart,- anchorDp = toDp(anchor),- dragDp = dragPx / density,- minZoom = zoomRange.start.toDouble(),- maxZoom = zoomRange.endInclusive.toDouble(),- )- },- )- }- },- ) {- // Read cache.tiles inside the draw lambda so tile arrival recomposes.- val tiles = cache.tiles- Canvas(Modifier.fillMaxSize()) {- for (box in visible) {- drawTile(box, tiles, density, minZoom)- }- imageOverlay?.let { drawOverlay(it, cameraState) }- }-- content()-- if (options.ornamentOptions.isAttributionEnabled) {- Attribution(tileSource.attribution, Modifier.align(Alignment.BottomStart))- }- }-}--/**- * 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.- *- * Meant to sit alongside [detectTransformGestures]: it stays out of the way of- * pan/pinch, and once a quick-zoom drag passes touch slop it consumes the- * moves so the transform detector cancels instead of also panning.- */-private suspend fun PointerInputScope.detectTapAndQuickZoomGestures(- onTap: (Offset) -> Unit,- onDoubleTap: (Offset) -> Unit,- onQuickZoomStart: () -> Unit,- onQuickZoom: (anchor: Offset, dragPx: Float) -> Unit,-) = awaitEachGesture {- val down = awaitFirstDown()- down.consume()- val up = waitForUpOrCancellation() ?: return@awaitEachGesture- up.consume()-- val secondDown = awaitSecondDown(up)- if (secondDown == null) {- onTap(up.position)- return@awaitEachGesture- }- secondDown.consume()-- // Zoom about the tapped point, which stays put for the whole gesture- // (following the finger instead would drift the map out from under it).- val anchor = up.position- val slop = viewConfiguration.touchSlop- var zooming = false- var dragOrigin = 0f- while (true) {- val event = awaitPointerEvent()- // A second finger means the user wants a pinch; hand it over untouched.- if (event.changes.size > 1) return@awaitEachGesture- val change = event.changes.firstOrNull { it.id == secondDown.id } ?: break- if (!change.pressed) {- change.consume()- break- }- val dy = change.position.y - secondDown.position.y- if (!zooming) {- if (abs(dy) < slop) continue- // Start measuring from the slop boundary so the zoom doesn't jump.- dragOrigin = dy - slop * sign(dy)- zooming = true- onQuickZoomStart()- }- change.consume()- onQuickZoom(anchor, dy - dragOrigin)- }- if (!zooming) onDoubleTap(anchor)-}--/** The second down of a double-tap, or null if none arrives in time. */-private suspend fun AwaitPointerEventScope.awaitSecondDown(- firstUp: PointerInputChange,-): PointerInputChange? = withTimeoutOrNull(viewConfiguration.doubleTapTimeoutMillis) {- val minUptime = firstUp.uptimeMillis + viewConfiguration.doubleTapMinTimeMillis- var change: PointerInputChange- do {- change = awaitFirstDown()- } while (change.uptimeMillis < minUptime)- change-}--/** Draws one tile, falling back to a scaled ancestor when the exact tile is missing. */-private fun DrawScope.drawTile(- box: TileBox,- tiles: Map<TileKey, ImageBitmap>,- density: Float,- minZoom: Int,-) {- val left = (box.leftDp * density).roundToInt()- val top = (box.topDp * density).roundToInt()- val right = ((box.leftDp + box.sizeDp) * density).roundToInt()- val bottom = ((box.topDp + box.sizeDp) * density).roundToInt()- val dstOffset = IntOffset(left, top)- val dstSize = IntSize(right - left, bottom - top)-- val exact = tiles[box.key]- if (exact != null) {- drawImage(- image = exact,- srcOffset = IntOffset.Zero,- srcSize = IntSize(exact.width, exact.height),- dstOffset = dstOffset,- dstSize = dstSize,- )- return- }- // Walk up the pyramid for a cached ancestor and draw its matching sub-region.- var d = 1- while (box.key.z - d >= minZoom) {- val f = 1 shl d- val pkey = TileKey(box.key.z - d, box.key.x / f, box.key.y / f)- val ancestor = tiles[pkey]- if (ancestor != null) {- val subW = ancestor.width / f- val subH = ancestor.height / f- drawImage(- image = ancestor,- srcOffset = IntOffset((box.key.x % f) * subW, (box.key.y % f) * subH),- srcSize = IntSize(subW, subH),- dstOffset = dstOffset,- dstSize = dstSize,- )- return- }- d++- }-}--/** Stretches the overlay image into its bbox's screen rect (north-up, axis-aligned). */-private fun DrawScope.drawOverlay(overlay: ImageOverlay, cameraState: CameraState) {- val proj = cameraState.projection ?: return- val bbox = overlay.bounds- val nw = proj.screenLocationFromPosition(GeoPoint(bbox.west, bbox.north))- val se = proj.screenLocationFromPosition(GeoPoint(bbox.east, bbox.south))- val left = nw.x.toPx().roundToInt()- val top = nw.y.toPx().roundToInt()- val right = se.x.toPx().roundToInt()- val bottom = se.y.toPx().roundToInt()- drawImage(- image = overlay.bitmap,- srcOffset = IntOffset.Zero,- srcSize = IntSize(overlay.bitmap.width, overlay.bitmap.height),- dstOffset = IntOffset(left, top),- dstSize = IntSize((right - left).coerceAtLeast(1), (bottom - top).coerceAtLeast(1)),- alpha = overlay.opacity,- )-}--@Composable-private fun Attribution(text: String, modifier: Modifier = Modifier) {- androidx.compose.foundation.text.BasicText(- text = text,- modifier = modifier- .padding(2.dp)- .background(Color(0xB3FFFFFF))- .padding(horizontal = 4.dp, vertical = 1.dp),- style = TextStyle(color = Color(0xFF444444), fontSize = 9.sp, fontFamily = FontFamily.SansSerif),- )-}--/** Visible tiles for [position] within [viewport] (dp), at `floor(zoom)` clamped to source range. */-private fun computeVisibleTiles(- position: CameraPosition,- viewport: Size,- minZoom: Int,- maxZoom: Int,-): List<TileBox> {- val zoom = position.zoom- val z = floor(zoom).toInt().coerceIn(minZoom, maxZoom)- val n = 1 shl z- val tileSpanDp = Mercator.TILE_SIZE * 2.0.pow(zoom - z)- val center = Mercator.project(position.target.longitude, position.target.latitude, zoom)- val originX = center.x - viewport.width / 2.0- val originY = center.y - viewport.height / 2.0-- val minTx = floor(originX / tileSpanDp).toInt()- val maxTx = floor((originX + viewport.width) / tileSpanDp).toInt()- val minTy = floor(originY / tileSpanDp).toInt()- val maxTy = floor((originY + viewport.height) / tileSpanDp).toInt()-- val result = ArrayList<TileBox>()- for (ty in minTy..maxTy) {- if (ty < 0 || ty >= n) continue- for (tx in minTx..maxTx) {- val wrappedX = ((tx % n) + n) % n- result += TileBox(- key = TileKey(z, wrappedX, ty),- leftDp = (tx * tileSpanDp - originX).toFloat(),- topDp = (ty * tileSpanDp - originY).toFloat(),- sizeDp = tileSpanDp.toFloat(),- )- }- }- return result-}
library/map/src/main/java/com/vayunmathur/library/map/TileCache.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/TileCache.kt b/library/map/src/main/java/com/vayunmathur/library/map/TileCache.ktdeleted file mode 100644index 8b7e545b71..0000000000--- a/library/map/src/main/java/com/vayunmathur/library/map/TileCache.kt+++ /dev/null@@ -1,49 +0,0 @@-package com.vayunmathur.library.map--import android.content.Context-import androidx.compose.runtime.mutableStateMapOf-import androidx.compose.ui.graphics.ImageBitmap-import androidx.compose.ui.graphics.asImageBitmap-import com.vayunmathur.library.image.ImageLoader-import com.vayunmathur.library.image.ImageRequest-import com.vayunmathur.library.image.ImageResult-import com.vayunmathur.library.image.Size-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.launch--/** Identifies a single XYZ tile. */-internal data class TileKey(val z: Int, val x: Int, val y: Int)--/**- * Fetches raster tiles through [ImageLoader] (memory + disk cache via library:image)- * and holds decoded [ImageBitmap]s in a snapshot-state map.- */-internal class TileCache(- private val context: Context,- private val loader: ImageLoader,- private val source: TileSource,-) {- val tiles = mutableStateMapOf<TileKey, ImageBitmap>()- private val inFlight = HashSet<TileKey>()-- fun get(key: TileKey): ImageBitmap? = tiles[key]-- /** Requests [key] if not already loaded or loading. */- fun request(scope: CoroutineScope, key: TileKey) {- if (key in tiles || key in inFlight) return- inFlight += key- scope.launch {- val bitmap = runCatching {- val request = ImageRequest.Builder(context)- .data(source.url(key.z, key.x, key.y))- .size(Size(source.tileSizePx, source.tileSizePx))- .allowHardware(false)- .build()- val result = loader.execute(request)- (result as? ImageResult.Success)?.bitmap?.asImageBitmap()- }.getOrNull()- inFlight -= key- if (bitmap != null) tiles[key] = bitmap- }- }-}
library/map/src/main/java/com/vayunmathur/library/map/TileSource.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/TileSource.kt b/library/map/src/main/java/com/vayunmathur/library/map/TileSource.ktdeleted file mode 100644index 3b8f48acbd..0000000000--- a/library/map/src/main/java/com/vayunmathur/library/map/TileSource.kt+++ /dev/null@@ -1,36 +0,0 @@-package com.vayunmathur.library.map--/**- * An XYZ raster tile source: a `{z}/{x}/{y}` URL template plus attribution and- * a zoom range. Uses retina (`@2x`) tiles for crispness — [tileSizePx] is the- * pixel size of the fetched image (512 for `@2x`).- */-data class TileSource(- val urlTemplate: String,- val attribution: String,- val minZoom: Int = 0,- val maxZoom: Int = 20,- val tileSizePx: Int = 512,-) {- fun url(z: Int, x: Int, y: Int): String =- urlTemplate- .replace("{z}", z.toString())- .replace("{x}", x.toString())- .replace("{y}", y.toString())-- companion object {- private const val ATTRIBUTION = "© OpenStreetMap © CARTO"-- /** CARTO Voyager — colorful general-purpose basemap (findfamily/photos). */- val CartoVoyager = TileSource(- urlTemplate = "https://basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}@2x.png",- attribution = ATTRIBUTION,- )-- /** CARTO Positron (light_all) — muted basemap for data overlays (weather). */- val CartoPositron = TileSource(- urlTemplate = "https://basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png",- attribution = ATTRIBUTION,- )- }-}
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.ktnew file mode 100644index 0000000000..f4e346751b--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -0,0 +1,181 @@+package com.vayunmathur.library.map++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.isSystemInDarkTheme+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.BasicText+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import kotlin.math.roundToInt++/**+ * The vector map.+ *+ * Renders the self-hosted PMTiles archive at `data.vayunmathur.com/v4.pmtiles` — the same+ * one `maps` streams through MapLibre — with our own Vulkan renderer. No third-party tile+ * CDN and no API key, which is the whole point: CARTO's keyless raster tiles now come back+ * watermarked, and that broke the basemap in five apps (#615).+ *+ * The signature is deliberately close to the `RasterMap` it replaces, so migrating a+ * consumer is an import change and a `tileSource` → `style` rename.+ *+ * ## What is and is not finished+ *+ * Fills, lines and casings, in light and dark, with pan, pinch, double-tap and quick zoom.+ * There are deliberately **no labels** — text is Phase 7 and realistically 40–60% of the+ * total effort — and the style is a ~14-layer stand-in rather than an authored one.+ *+ * It has also **not been verified on hardware.** The whole CPU pipeline is unit-tested, but+ * no frame has been presented on a real GPU. If Vulkan fails to initialise the map shows+ * its background colour rather than crashing, and everything that failed is in logcat under+ * `MapRenderer`. Validation layers are on in debug builds.+ *+ * @param style [MapStyle.Standard] or [MapStyle.Muted] — muted for hosts drawing their own+ * data on top, which is what `weather` needs.+ * @param darkBasemap which palette to paint. Defaults to the system theme. The dark colours+ * are `maps`' own contrast-checked `BasemapPalette`, so the apps agree with each other.+ * Switching is free: only a push constant changes.+ * @param imageOverlay a georeferenced translucent image drawn over the basemap.+ * @param onFrame called after each presented frame — a real per-frame hook, which is what+ * `photos` needs and MapLibre cannot offer.+ */+@Composable+fun VectorMap(+ cameraState: CameraState,+ modifier: Modifier = Modifier,+ style: MapStyle = MapStyle.Standard,+ darkBasemap: Boolean = isSystemInDarkTheme(),+ zoomRange: ClosedFloatingPointRange<Float> = 0f..20f,+ options: MapOptions = MapOptions(),+ imageOverlay: ImageOverlay? = null,+ onMapClick: (GeoPoint) -> Unit = {},+ onFrame: () -> Unit = {},+ content: @Composable () -> Unit = {},+) {+ val density = LocalDensity.current.density++ // A camera move has to reach a consumer that reprojects overlays even on a frame that+ // drew nothing new: a pan with no new tiles still moves every pin.+ LaunchedEffect(cameraState.position, cameraState.viewportDp) {+ if (cameraState.viewportDp != null) onFrame()+ }++ Box(+ modifier+ .fillMaxSize()+ .background(Color(if (darkBasemap) DARK_BACKGROUND else LIGHT_BACKGROUND))+ // Measure the viewport. Everything downstream depends on this: the renderer+ // skips any frame with no viewport, and `CameraState.projection` is null+ // without it — so every pin, marker and cluster the host positions would fail+ // too. It also enforces the minimum "fill" zoom so the world never leaves blank+ // margins.+ .onSizeChanged {+ cameraState.setViewport(Size(it.width / density, it.height / density))+ }+ .mapGestures(cameraState, options.gestureOptions, zoomRange, density, onMapClick),+ ) {+ VulkanMapSurface(+ cameraState = cameraState,+ darkBasemap = darkBasemap,+ muted = style == MapStyle.Muted,+ modifier = Modifier.fillMaxSize(),+ onFrame = onFrame,+ )++ if (imageOverlay != null) {+ GeoreferencedOverlay(imageOverlay, cameraState)+ }++ content()++ // Structurally non-disableable: the data is OpenStreetMap's under ODbL and the+ // schema is Protomaps', so this is a licence condition rather than a preference.+ // `MapOptions.kt:22-23` already asserts as much, and there is deliberately no+ // parameter to hide it — `OrnamentOptions.AllDisabled` cannot.+ MapAttribution(Modifier.align(Alignment.BottomStart))+ }+}++/**+ * A georeferenced image stretched into its bounds' screen rect.+ *+ * Drawn in Compose above the Vulkan surface rather than inside the renderer. The map is+ * north-up and axis-aligned, so this is one screen-aligned quad — exactly what the raster+ * renderer did with `drawImage`, and visually identical. Doing it on the GPU side would+ * mean a texture pipeline: a `VkImage`, a sampler, a descriptor set and a second set of+ * upload paths, for a single full-screen quad that Compose already composites.+ *+ * The tradeoff to know about: it is composited *over* everything the renderer draws, so+ * once labels exist (Phase 7) an overlay that should sit *under* them would have to move+ * into the renderer.+ */+@Composable+private fun GeoreferencedOverlay(overlay: ImageOverlay, cameraState: CameraState) {+ Canvas(Modifier.fillMaxSize()) {+ val projection = cameraState.projection ?: return@Canvas+ val northWest = projection.screenLocationFromPosition(+ GeoPoint(overlay.bounds.west, overlay.bounds.north)+ )+ val southEast = projection.screenLocationFromPosition(+ GeoPoint(overlay.bounds.east, overlay.bounds.south)+ )+ val left = northWest.x.toPx().roundToInt()+ val top = northWest.y.toPx().roundToInt()+ val right = southEast.x.toPx().roundToInt()+ val bottom = southEast.y.toPx().roundToInt()+ drawImage(+ image = overlay.bitmap,+ srcOffset = IntOffset.Zero,+ srcSize = IntSize(overlay.bitmap.width, overlay.bitmap.height),+ dstOffset = IntOffset(left, top),+ // A zero or negative extent is a degenerate bbox, which drawImage rejects.+ dstSize = IntSize((right - left).coerceAtLeast(1), (bottom - top).coerceAtLeast(1)),+ alpha = overlay.opacity,+ )+ }+}++/**+ * Shown before any tile has loaded. Matches the renderer's own backdrop, so the surface+ * appearing does not flash a different colour.+ */+private const val LIGHT_BACKGROUND = 0xFFE9E7E2++/** `BasemapPalette.Fill.Background`, so this and `maps` agree in the dark. */+private const val DARK_BACKGROUND = 0xFF1B1D22++/** `© OpenStreetMap contributors` and the schema's author, as both licences require. */+@Composable+internal fun MapAttribution(modifier: Modifier = Modifier) {+ BasicText(+ text = ATTRIBUTION,+ modifier = modifier+ .padding(2.dp)+ .background(Color(0xB3FFFFFF))+ .padding(horizontal = 4.dp, vertical = 1.dp),+ style = TextStyle(color = Color(0xFF444444), fontSize = 9.sp, fontFamily = FontFamily.SansSerif),+ )+}++/**+ * The tiles are OpenStreetMap data under ODbL, tiled to the Protomaps v4 schema.+ *+ * CARTO is deliberately gone: we no longer use their CDN, and still crediting them would be+ * as wrong as omitting OpenStreetMap.+ */+internal const val ATTRIBUTION = "© OpenStreetMap contributors · Protomaps"
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.ktnew file mode 100644index 0000000000..96122b86d5--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -0,0 +1,200 @@+package com.vayunmathur.library.map++import android.content.Context+import android.graphics.SurfaceTexture+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import android.util.Log+import android.view.Choreographer+import android.view.Surface+import android.view.TextureView+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.viewinterop.AndroidView+import java.io.File++/**+ * Hosts the Vulkan renderer in Compose.+ *+ * ## TextureView, not SurfaceView+ *+ * `maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt:76-83` records why, from+ * production: a **SurfaceView renders into a separate surface and goes black and stops+ * taking input** after the composable is disposed navigating forward and recomposed on+ * the back-pop through Nav3's `AnimatedContent` transition — it only repaints once some+ * later recomposition forces a relayout. A TextureView draws in the normal view+ * hierarchy, so it composites and stays interactive across the transition.+ *+ * `games/voxels/.../ui/VoxelSurfaceView.kt` is a SurfaceView, but voxels' surface is+ * never navigated away from and back. Five consumer apps' navigation is, so the+ * known-good configuration wins over the cheaper one. The cost is one extra composite+ * per frame.+ *+ * A `SurfaceTexture` also gives the lifecycle honestly: returning true from+ * [TextureView.SurfaceTextureListener.onSurfaceTextureDestroyed] means we release it, so+ * the renderer is torn down — device idle, buffers freed, `ANativeWindow` released —+ * exactly when the window goes away.+ */+@Composable+internal fun VulkanMapSurface(+ cameraState: CameraState,+ darkBasemap: Boolean,+ muted: Boolean,+ modifier: Modifier = Modifier,+ onFrame: () -> Unit = {},+) {+ val context = LocalContext.current+ val density = LocalDensity.current.density+ val host = remember(context) { MapSurfaceHost(context, cameraState, density, onFrame) }++ DisposableEffect(host) { onDispose { host.dispose() } }++ // Following the system theme costs nothing: the layer set is identical between+ // variants, so this re-colours in place rather than reloading a single tile.+ LaunchedEffect(darkBasemap, muted, host) { host.setPalette(darkBasemap, muted) }++ AndroidView(+ factory = {+ TextureView(context).apply {+ // The map is opaque, so tell the compositor: a translucent TextureView is+ // blended every frame for nothing.+ isOpaque = true+ surfaceTextureListener = host.listener+ }+ },+ modifier = modifier,+ )+}++/**+ * Owns the native renderer and the frame loop for one surface.+ *+ * Every native call happens on the main thread — the `Choreographer` callback is on it+ * anyway, and the renderer is not safe to drive from two threads at once. The expensive+ * work (range fetch, inflate, MVT decode, tessellation) is on a worker thread inside the+ * native side, so this callback only uploads finished meshes and records a command buffer.+ */+private class MapSurfaceHost(+ context: Context,+ private val cameraState: CameraState,+ private val density: Float,+ private val onFrame: () -> Unit,+) {+ private val appContext = context.applicationContext+ private var handle = 0L+ private var surface: Surface? = null+ private var frameCallback: Choreographer.FrameCallback? = null++ /** Remembered so a surface created after the theme was set still starts in it. */+ private var dark = false+ private var muted = false++ /**+ * Where cached byte ranges live. External files rather than the cache dir: this is+ * large and expensive to rebuild, so it should not be the first thing the platform+ * reclaims, and external files are outside the 25 MB cloud-backup quota.+ */+ private val cacheDir: File by lazy {+ val root = appContext.getExternalFilesDir(null) ?: appContext.filesDir+ File(root, CACHE_DIR_NAME).apply { mkdirs() }+ }++ val listener = object : TextureView.SurfaceTextureListener {+ override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) {+ if (!MapNative.isAvailable) {+ Log.e(TAG, "libmap_renderer.so did not load; the map will not draw")+ return+ }+ val created = Surface(texture)+ surface = created+ handle = MapNative.create(created, cacheDir.absolutePath, width, height, dark, muted)+ if (handle == 0L) {+ Log.e(TAG, "the Vulkan renderer failed to start; see MapRenderer in logcat")+ created.release()+ surface = null+ return+ }+ MapNative.setOnline(handle, isOnline())+ startFrameLoop()+ }++ override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) {+ if (handle != 0L) MapNative.resize(handle, width, height)+ }++ override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean {+ teardown()+ // True: we release the SurfaceTexture, having already dropped the+ // ANativeWindow that pointed at it.+ return true+ }++ override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit+ }++ private fun startFrameLoop() {+ val callback = object : Choreographer.FrameCallback {+ override fun doFrame(frameTimeNanos: Long) {+ if (handle == 0L) return+ val viewport = cameraState.viewportDp+ if (viewport != null) {+ val position = cameraState.position+ val drawn = MapNative.render(+ handle,+ position.target.longitude.toFloat(),+ position.target.latitude.toFloat(),+ position.zoom.toFloat(),+ viewport.width,+ viewport.height,+ density,+ )+ if (drawn) onFrame()+ }+ Choreographer.getInstance().postFrameCallback(this)+ }+ }+ frameCallback = callback+ Choreographer.getInstance().postFrameCallback(callback)+ }++ private fun teardown() {+ frameCallback?.let { Choreographer.getInstance().removeFrameCallback(it) }+ frameCallback = null+ // Destroy before releasing the Surface: the native side waits for the GPU to go+ // idle and releases the ANativeWindow that points at it.+ if (handle != 0L) {+ MapNative.destroy(handle)+ handle = 0L+ }+ surface?.release()+ surface = null+ }++ fun dispose() = teardown()++ fun setPalette(dark: Boolean, muted: Boolean) {+ this.dark = dark+ this.muted = muted+ if (handle != 0L) MapNative.setPalette(handle, dark, muted)+ }++ private fun isOnline(): Boolean {+ val manager = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager+ // No connectivity service is not evidence of being offline, and claiming+ // offline would pin the map to whatever is cached.+ ?: return true+ val network = manager.activeNetwork ?: return false+ val capabilities = manager.getNetworkCapabilities(network) ?: return false+ return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)+ }++ private companion object {+ const val TAG = "VulkanMapSurface"+ const val CACHE_DIR_NAME = "vectortilecache"+ }+}
library/map/src/main/rust/Cargo.toml
diff --git a/library/map/src/main/rust/Cargo.toml b/library/map/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..a059acf3bb--- /dev/null+++ b/library/map/src/main/rust/Cargo.toml@@ -0,0 +1,52 @@+# The Vulkan vector-tile renderer for `:library:map`.+#+# Replaces the CARTO raster basemap in findfamily, photos, weather, taxi and+# fooddelivery (#615) with our own renderer over the self-hosted pmtiles archive.+#+# Why Vulkan and not `androidx.webgpu`: that wrapper bundles Dawn as a 5.79 MB+# `libwebgpu_c_bundled.so` per ABI, to translate to the Vulkan that is already on+# every device we target (minSdk 31). `ash` with `features = ["loaded"]` links+# nothing and dlopen's `libvulkan.so` at run time, so the only native code we ship+# is our own. It also drops a `1.0.0-alpha05` dependency whose API changes between+# alphas, and lets us feed SPIR-V straight to the driver instead of through Dawn's+# SPIR-V path, which is gated behind an unsafe-API toggle in some configurations.+#+# `games/voxels` is the in-repo precedent for all of this and the same ash version.++[package]+name = "map_renderer"+version = "0.1.0"+edition = "2021"+publish = false+license = "GPL-2.0-only"+description = "Vulkan vector-tile map renderer: PMTiles + MVT in, triangles out"++[lib]+name = "map_renderer"+# cdylib for the JNI surface; rlib so the host test binary can link it and run the+# whole CPU pipeline — tessellation, tile selection, the cache — without a device.+crate-type = ["cdylib", "rlib"]++[dependencies]+jni.workspace = true+# Cache keys are SHA-256(url + range), as the Kotlin cache in `maps` uses. Already a+# workspace dependency, so this adds nothing to the lockfile.+sha2.workspace = true+# The authored MapLibre style is parsed at startup rather than transcribed into constants.+# Hand-copying it could not converge: MapLibre renders this exact file correctly, so the+# file is the source of truth and the only way to match it is to evaluate it.+serde_json.workspace = true++# The PMTiles + MVT codec, shared with `scripts/maps/tile_build`, which writes the+# archives this reads. One implementation, so the two cannot drift.+tilecodec = { path = "../../../../tilecodec/src/main/rust" }++# HTTP goes back out through Kotlin: this crate opens no sockets and carries no TLS+# stack, so pmtiles range requests keep `library:network`'s reduced CA bundle.+jni_http = { path = "../../../../jni-http/src/main/rust" }++# `default-features = false` drops the `linked` feature, so nothing links against+# libvulkan at build time; `loaded` dlopen's it, which is what an Android app must+# do anyway.+[target.'cfg(target_os = "android")'.dependencies]+ash = { version = "0.38", default-features = false, features = ["loaded"] }
library/map/src/main/rust/build.rs
diff --git a/library/map/src/main/rust/build.rs b/library/map/src/main/rust/build.rsnew file mode 100644index 0000000000..02da8bee23--- /dev/null+++ b/library/map/src/main/rust/build.rs@@ -0,0 +1,193 @@+//! Compiles the GLSL in `shaders/` to SPIR-V with the NDK's `glslc`.+//!+//! # This deliberately does not do what `games/voxels/build.rs` does+//!+//! That build script (`build.rs:94-106`) resolves `glslc` from two hardcoded+//! absolute paths under one developer's home directory, and when it finds neither+//! it calls `minimal_vert_spv()` / `minimal_frag_spv()` — writing a **28-byte stub**+//! consisting of a SPIR-V header and a single `OpCapability`. A build that takes+//! that path succeeds, installs, runs, and draws nothing at all, with no warning+//! anywhere. The failure surfaces as "the screen is black" long after the build.+//!+//! So this script resolves the compiler from the environment for the *host*+//! platform it is running on, and [`panic!`]s if it cannot find it or if a shader+//! fails to compile. A missing shader compiler must stop the build.+//!+//! SPIR-V is `include_bytes!`d rather than shipped as an asset: the shaders are+//! part of the renderer, and an asset can be missing at run time while a linked+//! `&[u8]` cannot.++use std::env;+use std::path::{Path, PathBuf};+use std::process::Command;++fn main() {+ let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));+ let shader_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"))+ .join("shaders");++ let glslc = find_glslc();+ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=shaders");++ let mut compiled = 0;+ let mut entries: Vec<PathBuf> = std::fs::read_dir(&shader_dir)+ .unwrap_or_else(|e| panic!("cannot read {}: {e}", shader_dir.display()))+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| {+ matches!(+ p.extension().and_then(|e| e.to_str()),+ Some("vert") | Some("frag") | Some("comp")+ )+ })+ .collect();+ // Sorted so the build is reproducible and a diff of the log is stable.+ entries.sort();++ for shader in &entries {+ let name = shader.file_name().expect("shader file name");+ println!("cargo:rerun-if-changed={}", shader.display());+ let target = out_dir.join(format!("{}.spv", name.to_string_lossy()));++ let output = Command::new(&glslc)+ .arg("--target-env=vulkan1.1")+ .arg("-O")+ .arg("-o")+ .arg(&target)+ .arg(shader)+ .output()+ .unwrap_or_else(|e| panic!("cannot run {}: {e}", glslc.display()));++ if !output.status.success() {+ panic!(+ "glslc failed on {}:\n{}{}",+ shader.display(),+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ }+ // A zero-exit that wrote nothing usable is the silent-stub case, caught here+ // rather than at run time on a black screen.+ let written = std::fs::metadata(&target).map(|m| m.len()).unwrap_or(0);+ if written < MIN_SPIRV_BYTES {+ panic!(+ "glslc produced {written} bytes for {}; a real SPIR-V module is at least \+ {MIN_SPIRV_BYTES} bytes",+ shader.display(),+ );+ }+ compiled += 1;+ }++ if compiled == 0 {+ panic!("no shaders found in {}", shader_dir.display());+ }+}++/// A SPIR-V module is a five-word header plus at least a few instructions.+const MIN_SPIRV_BYTES: u64 = 64;++/// `glslc` for the **host** platform, from the NDK.+///+/// Cargo runs this script on the build machine while cross-compiling for Android,+/// so the host triple is what matters, not the target. Searched in order:+///+/// 1. `GLSLC` — an explicit override, for a CI image that puts it elsewhere.+/// 2. `ANDROID_NDK_HOME` / `ANDROID_NDK_ROOT` — set directly by some CI setups.+/// 3. `ANDROID_HOME` / `ANDROID_SDK_ROOT`, then the highest installed `ndk/*`.+/// 4. `sdk.dir` from the repo's `local.properties`, which is what a dev box has.+/// 5. `glslc` on `PATH`.+fn find_glslc() -> PathBuf {+ if let Some(explicit) = env::var_os("GLSLC").map(PathBuf::from) {+ if explicit.is_file() {+ return explicit;+ }+ panic!("GLSLC is set to {explicit:?} but that is not a file");+ }++ let host = host_dir();+ let executable = if cfg!(windows) { "glslc.exe" } else { "glslc" };++ let mut ndks: Vec<PathBuf> = Vec::new();+ for key in ["ANDROID_NDK_HOME", "ANDROID_NDK_ROOT"] {+ if let Some(dir) = env::var_os(key) {+ ndks.push(PathBuf::from(dir));+ }+ }+ let mut sdks: Vec<PathBuf> = Vec::new();+ for key in ["ANDROID_HOME", "ANDROID_SDK_ROOT"] {+ if let Some(dir) = env::var_os(key) {+ sdks.push(PathBuf::from(dir));+ }+ }+ if let Some(dir) = sdk_dir_from_local_properties() {+ sdks.push(dir);+ }+ for sdk in &sdks {+ // Highest version first, so a box with several NDKs uses the newest.+ let mut installed: Vec<PathBuf> = std::fs::read_dir(sdk.join("ndk"))+ .into_iter()+ .flatten()+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| p.is_dir())+ .collect();+ installed.sort();+ installed.reverse();+ ndks.extend(installed);+ }++ for ndk in &ndks {+ let candidate = ndk.join("shader-tools").join(&host).join(executable);+ if candidate.is_file() {+ return candidate;+ }+ }++ if Command::new(executable).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {+ return PathBuf::from(executable);+ }++ panic!(+ "glslc not found. Looked for ndk/*/shader-tools/{host}/{executable} under \+ {sdks:?} and {ndks:?}, then on PATH. Install the NDK, or set GLSLC. The map \+ renderer cannot draw without shaders, so this build stops here rather than \+ producing an app with an empty map.",+ );+}++/// The NDK's prebuilt-tool directory name for the host we are running on.+fn host_dir() -> String {+ let os = if cfg!(target_os = "windows") {+ "windows"+ } else if cfg!(target_os = "macos") {+ "darwin"+ } else {+ "linux"+ };+ // The NDK ships x86_64 host tools even on arm64 macOS, where they run under+ // Rosetta, so the host CPU is deliberately not consulted.+ format!("{os}-x86_64")+}++/// `sdk.dir` out of the repo root's `local.properties`.+///+/// Walks up from the crate rather than assuming a depth, so moving the crate does+/// not silently break shader compilation.+fn sdk_dir_from_local_properties() -> Option<PathBuf> {+ let mut dir: &Path = &PathBuf::from(env::var("CARGO_MANIFEST_DIR").ok()?);+ loop {+ let candidate = dir.join("local.properties");+ if candidate.is_file() {+ let text = std::fs::read_to_string(&candidate).ok()?;+ for line in text.lines() {+ let line = line.trim();+ if let Some(value) = line.strip_prefix("sdk.dir=") {+ // Gradle properties escape the Windows separator.+ return Some(PathBuf::from(value.replace("\\\\", "\\").replace("\\:", ":")));+ }+ }+ return None;+ }+ dir = dir.parent()?;+ }+}
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.rsnew file mode 100644index 0000000000..9f03c14c3f--- /dev/null+++ b/library/map/src/main/rust/examples/probe_archive.rs@@ -0,0 +1,382 @@+//! Probes the live archive end to end, through the real code the app uses.+//!+//! ```text+//! cargo run --offline -p map_renderer --example probe_archive+//! ```+//!+//! This exists because the renderer cannot be verified on a host: Vulkan needs a device.+//! Everything *before* the GPU can be, though, and that is where the bugs were — a+//! hardcoded max zoom that did not match the archive, and tiles that silently resolved to+//! nothing. So this drives the actual [`StreamArchive`], the actual gzip and MVT decoders,+//! the actual style and the actual tessellators against+//! `https://data.vayunmathur.com/v4.pmtiles`, and prints what comes out.+//!+//! HTTP is shelled out to `curl`, which ships with Windows 10+, macOS and every Linux we+//! build on. On device this same trait is implemented over `library/jni-http`; using curl+//! here keeps the crate free of an HTTP dependency that only a diagnostic needs.++use map_renderer::camera::Camera;+use map_renderer::style;+use map_renderer::tess::{fill, stroke};+use map_renderer::tile::geometry;+use map_renderer::tile::select;+use std::process::Command;+use tilecodec::mvt::Tile;+use tilecodec::proto::{err, Result};+use tilecodec::stream::{RangeReader, StreamArchive};++/// Layers whose kind values the style filters on, so a mismatch is silent.+const KIND_REPORT: &[&str] = &["landuse", "water", "landcover", "earth", "buildings"];++const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";++/// A [`RangeReader`] over `curl`, counting requests and bytes so the cost of a screenful is+/// visible rather than assumed.+///+/// The counters are thread-locals because the archive takes ownership of the reader, and a+/// diagnostic is not worth threading a handle back out for.+struct CurlReader;++thread_local! {+ static REQUESTS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };+ static BYTES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };+}++impl RangeReader for CurlReader {+ fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+ let range = format!("{}-{}", offset, offset + length as u64 - 1);+ REQUESTS.with(|c| c.set(c.get() + 1));+ let out = match Command::new("curl").args(["-s", "-f", "--range", &range, URL]).output() {+ Ok(out) => out,+ Err(e) => return err(format!("curl failed to start: {e}")),+ };+ if !out.status.success() {+ return err(format!("curl exited {:?} for range {range}", out.status.code()));+ }+ BYTES.with(|c| c.set(c.get() + out.stdout.len() as u64));+ Ok(out.stdout)+ }+}++/// Signed area of every ring in a polygon geometry, in command-stream order, without any+/// exterior/hole grouping applied.+///+/// This deliberately re-walks the raw command stream rather than using+/// `decode_polygons`, because the grouping is exactly what is under suspicion.+fn raw_rings(geometry: &[u32]) -> Vec<f64> {+ const MOVE_TO: u32 = 1;+ const LINE_TO: u32 = 2;+ const CLOSE_PATH: u32 = 7;++ let mut areas = Vec::new();+ let mut ring: Vec<(i64, i64)> = Vec::new();+ let (mut x, mut y) = (0i64, 0i64);+ let mut i = 0;+ while i < geometry.len() {+ let cmd = geometry[i] & 0x7;+ let count = geometry[i] >> 3;+ i += 1;+ match cmd {+ MOVE_TO | LINE_TO => {+ for _ in 0..count {+ if i + 1 >= geometry.len() {+ return areas;+ }+ let dx = ((geometry[i] >> 1) as i64) ^ -((geometry[i] & 1) as i64);+ let dy = ((geometry[i + 1] >> 1) as i64) ^ -((geometry[i + 1] & 1) as i64);+ i += 2;+ x += dx;+ y += dy;+ ring.push((x, y));+ }+ }+ CLOSE_PATH => {+ let mut sum = 0i64;+ for k in 0..ring.len() {+ let (x1, y1) = ring[k];+ let (x2, y2) = ring[(k + 1) % ring.len()];+ sum += x1 * y2 - x2 * y1;+ }+ areas.push(sum as f64 / 2.0);+ ring.clear();+ }+ _ => return areas,+ }+ }+ areas+}++/// The area a correct tessellation must cover, in tile-normalised units: the even-odd+/// region of every ring, by scanline.+///+/// Not `exterior - sum(holes)`. The archive's ocean polygons have holes that overlap each+/// other and lakes nested inside continent holes, so subtracting each ring independently+/// double-counts both and reads low — 0.7096 against a true 0.7135 on the z0 ocean, which+/// flatters the ratios below by about half a percent.+fn even_odd_area(rings: &[Vec<(i32, i32)>], extent: u32) -> f64 {+ let mut edges: Vec<((i32, i32), (i32, i32))> = Vec::new();+ for ring in rings {+ let mut n = ring.len();+ while n >= 2 && ring[0] == ring[n - 1] {+ n -= 1;+ }+ if n < 3 {+ continue;+ }+ for i in 0..n {+ let (a, b) = (ring[i], ring[(i + 1) % n]);+ if a.1 != b.1 {+ edges.push((a, b));+ }+ }+ }+ if edges.is_empty() {+ return 0.0;+ }+ let lo = edges.iter().map(|e| e.0 .1.min(e.1 .1)).min().unwrap();+ let hi = edges.iter().map(|e| e.0 .1.max(e.1 .1)).max().unwrap();++ let mut crossings: Vec<f64> = Vec::new();+ let mut total = 0.0f64;+ for row in lo..hi {+ let y = row as f64 + 0.5;+ crossings.clear();+ for &((x1, y1), (x2, y2)) in &edges {+ if (y1 as f64 > y) != (y2 as f64 > y) {+ let t = (y - y1 as f64) / (y2 as f64 - y1 as f64);+ crossings.push(x1 as f64 + t * (x2 as f64 - x1 as f64));+ }+ }+ crossings.sort_by(|a, b| a.partial_cmp(b).unwrap());+ let mut i = 0;+ while i + 1 < crossings.len() {+ total += crossings[i + 1] - crossings[i];+ i += 2;+ }+ }+ let scale = 1.0 / extent as f64;+ total * scale * scale+}++fn main() {+ let reader = CurlReader;+ let mut archive = match StreamArchive::open(reader) {+ Ok(a) => a,+ Err(e) => {+ eprintln!("could not open the archive: {e}");+ std::process::exit(1);+ }+ };++ let header = &archive.header;+ println!("archive zoom {}..{}, {} addressed tiles", header.min_zoom, header.max_zoom, header.addressed_tiles);+ println!(" tile_data at {}, leaves at {}", header.tile_data_offset, header.leaf_offset);+ let (min_zoom, max_zoom) = (header.min_zoom, header.max_zoom);++ // Match the device exactly: findfamily sits at null island, z1.87, on a 448x867dp+ // viewport, because it has no location fix to centre on.+ let camera = Camera {+ center_lon: 0.0,+ center_lat: 0.0,+ zoom: 1.87,+ width_dp: 448.0,+ height_dp: 867.0,+ density: 3.0,+ };+ let layers = style::layers();+ let wanted = select::resident_set(&camera, min_zoom, max_zoom);+ println!("viewport z14 SF, {} tiles including ancestors\n", wanted.len());++ let mut drew = 0;+ let mut empty = 0;+ for tile in &wanted {+ let body = match archive.tile(tile.z, tile.x, tile.y) {+ Ok(Some(b)) => b,+ Ok(None) => {+ println!(" z{}/{}/{} ABSENT from the archive", tile.z, tile.x, tile.y);+ empty += 1;+ continue;+ }+ Err(e) => {+ println!(" z{}/{}/{} ERROR {e}", tile.z, tile.x, tile.y);+ empty += 1;+ continue;+ }+ };+ let decoded = match Tile::decode(&body) {+ Ok(t) => t,+ Err(e) => {+ println!(" z{}/{}/{} MVT DECODE FAILED: {e}", tile.z, tile.x, tile.y);+ empty += 1;+ continue;+ }+ };+ // Ring structure of the water layer. The ocean is a polygon with continents cut out+ // as holes; if those holes are lost, the ocean paints over the land and the map is a+ // flat sheet of blue with land showing only where a later layer happens to cover it.+ if tile.z <= 1 {+ for layer in &decoded.layers {+ if layer.name != "water" {+ continue;+ }+ let mut reported = 0;+ for feature in &layer.features {+ if feature.geom_type != tilecodec::mvt::GeomType::Polygon {+ continue;+ }+ let raw = raw_rings(&feature.geometry);+ let grouped = tilecodec::mvt::decode_polygons(&feature.geometry);+ let polygons = grouped.as_ref().map(|p| p.len()).unwrap_or(0);+ let holes: usize =+ grouped.as_ref().map(|p| p.iter().map(|r| r.len() - 1).sum()).unwrap_or(0);+ let kind = feature+ .get("kind")+ .and_then(|v| match v {+ tilecodec::mvt::Value::String(s) => Some(s.clone()),+ _ => None,+ })+ .unwrap_or_default();+ if raw.len() > 1 || kind == "ocean" {+ // Per polygon group, not just the total. If holes are assigned to the+ // wrong exterior, one group over-covers while another under-covers and+ // the totals partly cancel — so an aggregate number hides it.+ let mut detail = String::new();+ let mut worst = 1.0f64;+ if let Some(polygons) = &grouped {+ for (g, rings) in polygons.iter().enumerate() {+ let want = even_odd_area(rings, layer.extent);+ let mut v = Vec::new();+ let mut idx = Vec::new();+ fill::tessellate(rings, layer.extent, &mut v, &mut idx);+ let mut got = 0.0f64;+ for tri in idx.chunks(3) {+ let p = |i: u32| {+ let b = i as usize * fill::FLOATS_PER_VERTEX;+ (v[b] as f64, v[b + 1] as f64)+ };+ let (ax, ay) = p(tri[0]);+ let (bx, by) = p(tri[1]);+ let (cx, cy) = p(tri[2]);+ got += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs()+ / 2.0;+ }+ let ratio = if want > 1e-9 { got / want } else { 1.0 };+ // Distance from 1, so a group that under-covers is as+ // visible as one that over-covers.+ if (ratio - 1.0).abs() > (worst - 1.0).abs() {+ worst = ratio;+ }+ detail.push_str(&format!(+ "\n group {g}: {} rings, want {want:.4}, got \+ {got:.4}, ratio {ratio:.3}",+ rings.len(),+ ));+ }+ }+ println!(+ " water/{kind}: {} rings -> {} polys, {} holes | worst group \+ ratio {worst:.3}{}",+ raw.len(),+ polygons,+ holes,+ detail,+ );+ reported += 1;+ if reported >= 2 {+ break;+ }+ }+ }+ }+ }+ // Save the z0 tile so the hard real geometry becomes a test fixture. A synthetic grid+ // of square holes tessellates perfectly; real coastlines clipped at a tile edge, with+ // collinear runs and holes touching the exterior, do not. Guessing at a synthetic case+ // that reproduces that is slower than using the tile itself.+ if tile.z == 0 && std::env::var("DUMP_Z0").is_ok() {+ let path = "library/tilecodec/src/main/rust/tests/fixtures/v4_z0_tile.mvt";+ match std::fs::write(path, &body) {+ Ok(()) => println!(" wrote {} ({} bytes)", path, body.len()),+ Err(e) => println!(" could not write {path}: {e}"),+ }+ }+ let names: Vec<&str> = decoded.layers.iter().map(|l| l.name.as_str()).collect();+ let mesh = geometry::build(&decoded, &layers, tile.z, tile.x, tile.y);+ let triangles: usize = mesh.meshes.iter().map(|m| m.indices.len() / 3).sum();++ // Per-layer detail, plus how much of the tile each fill actually covers. A layer+ // whose fill covers far less than the polygons it was given is dropping geometry,+ // which on screen is ocean showing through the middle of a continent.+ for m in &mesh.meshes {+ let id = layers[m.layer_index].id;+ let stride = match m.kind {+ style::LayerKind::Fill => fill::FLOATS_PER_VERTEX,+ style::LayerKind::Line => stroke::FLOATS_PER_VERTEX,+ };+ let mut covered = 0.0f64;+ if m.kind == style::LayerKind::Fill {+ for tri in m.indices.chunks(3) {+ let p = |i: u32| {+ let b = i as usize * stride;+ (m.vertices[b] as f64, m.vertices[b + 1] as f64)+ };+ let (ax, ay) = p(tri[0]);+ let (bx, by) = p(tri[1]);+ let (cx, cy) = p(tri[2]);+ covered += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() / 2.0;+ }+ }+ println!(+ " {:<22} {:>6} tris covers {:>6.3} of the tile",+ id,+ m.indices.len() / 3,+ covered,+ );+ }++ // The bounds the vertex shaders assume. A violation here is exactly the class of+ // bug that renders a recognisable map that is badly wrong.+ let mut worst = 0.0f32;+ let mut nonfinite = 0;+ for m in &mesh.meshes {+ let stride = match m.kind {+ style::LayerKind::Fill => fill::FLOATS_PER_VERTEX,+ style::LayerKind::Line => stroke::FLOATS_PER_VERTEX,+ };+ for chunk in m.vertices.chunks(stride) {+ if !chunk[0].is_finite() || !chunk[1].is_finite() {+ nonfinite += 1;+ continue;+ }+ worst = worst.max(chunk[0].abs()).max(chunk[1].abs());+ }+ }++ println!(+ " z{}/{}/{} {:>6} B layers[{}] {} drawn, {} tris, |pos|<={:.3}{}",+ tile.z,+ tile.x,+ tile.y,+ body.len(),+ names.join(","),+ mesh.meshes.len(),+ triangles,+ worst,+ if nonfinite > 0 { format!(" !! {nonfinite} NON-FINITE") } else { String::new() },+ );+ if triangles > 0 {+ drew += 1;+ }+ }++ println!(+ "\n{drew} tiles produced geometry, {empty} produced none, \+ {} range requests, {:.1} KB fetched",+ REQUESTS.with(|c| c.get()),+ BYTES.with(|c| c.get()) as f64 / 1024.0,+ );+ if drew == 0 {+ eprintln!("\nnothing drew: the map would be blank");+ std::process::exit(1);+ }+}
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.fragnew file mode 100644index 0000000000..a43b3828b6--- /dev/null+++ b/library/map/src/main/rust/shaders/fill.frag@@ -0,0 +1,17 @@+#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.++layout(location = 0) out vec4 outColor;++layout(push_constant) uniform Push {+ mat4 tileToClip;+ vec4 color;+ vec4 line;+ vec4 misc;+} push;++void main() {+ outColor = push.color;+}
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.vertnew file mode 100644index 0000000000..7bec8928da--- /dev/null+++ b/library/map/src/main/rust/shaders/fill.vert@@ -0,0 +1,30 @@+#version 450++// Fill: solid triangles from the earcut tessellator.+//+// Vertices carry position only, in tile-local 0..1. The tile's placement and the+// camera both live in the transform, and the layer's colour is a constant, so a+// fill vertex is 8 bytes.+//+// Everything per-draw arrives in a **push constant** block rather than a uniform+// buffer. 112 bytes is inside the 128 the spec guarantees, and it means the+// renderer needs no descriptor sets, no descriptor pool, and no per-tile uniform+// buffers to keep in sync with the camera.++layout(location = 0) in vec2 inPosition;++layout(push_constant) uniform Push {+ // Tile-local 0..1 to clip space.+ 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.+ vec4 misc;+} push;++void main() {+ gl_Position = push.tileToClip * vec4(inPosition, 0.0, 1.0);+}
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.fragnew file mode 100644index 0000000000..c6e55446c1--- /dev/null+++ b/library/map/src/main/rust/shaders/line.frag@@ -0,0 +1,49 @@+#version 450++// Line fragment, with the dash pattern.+//+// `dashOn`/`dashOff` are dash and gap lengths in **line widths**, as the style spec+// defines `line-dasharray`, converted to pixels here.+//+// The degenerate `[2, 0]` pattern has to be special-cased. `boundaries_country`+// produces it through a `step` expression — a zero-length gap means "solid" — and a+// naive `mod(distance, on + off) < on` renders it solid only by accident of `off`+// being exactly zero. Any drift in the period, or a driver that evaluates+// `mod(x, x)` as `x` rather than `0`, turns the whole border into stipple. So a+// non-positive gap short-circuits before any arithmetic happens.++layout(location = 0) in float inDistancePx;++layout(location = 0) out vec4 outColor;++layout(push_constant) uniform Push {+ mat4 tileToClip;+ vec4 color;+ vec4 line;+ vec4 misc;+} push;++void main() {+ float halfWidthPx = push.line.x;+ float dashOn = push.line.z;+ float dashOff = push.line.w;++ // A non-positive gap is a solid line, checked first so [2, 0] never reaches the+ // modulo at all.+ if (dashOff <= 0.0) {+ outColor = push.color;+ return;+ }++ float width = max(halfWidthPx * 2.0, 1.0);+ float on = dashOn * width;+ float off = dashOff * width;+ float period = on + off;+ if (period <= 0.0) {+ outColor = push.color;+ return;+ }++ if (mod(inDistancePx, period) > on) discard;+ outColor = push.color;+}
library/map/src/main/rust/shaders/line.vert
diff --git a/library/map/src/main/rust/shaders/line.vert b/library/map/src/main/rust/shaders/line.vertnew file mode 100644index 0000000000..0213eaa8ad--- /dev/null+++ b/library/map/src/main/rust/shaders/line.vert@@ -0,0 +1,46 @@+#version 450++// Line: extrudes the stroked centreline to its screen-space width.+//+// The tessellator emits geometry that is a function of the tile alone — position,+// the unit normal of the join, and two multipliers — and the width arrives as a+// push constant. That is deliberate: a stroke's width is a screen measurement that+// changes continuously with zoom, so baking it into vertices would re-tessellate+// every road in every visible tile on every zoom step, while panning, on the+// critical path.+//+// offset = normal * (offsetMul * gapHalf + widthMul * halfWidth)+//+// `offsetMul` is 0 for a plain stroke and ±1 for the two bands of a casing;+// `widthMul` is ∓1 for a plain stroke's two edges and 0 / ±2 for a casing band's+// inner and outer edges — a band spans a full width, not a half width. See+// `tess::stroke`.++layout(location = 0) in vec2 inPosition;+layout(location = 1) in vec2 inNormal;+layout(location = 2) in vec2 inExtrude;+layout(location = 3) in float inDistance;++layout(location = 0) out float outDistancePx;++layout(push_constant) uniform Push {+ mat4 tileToClip;+ vec4 color;+ vec4 line;+ vec4 misc;+} push;++void main() {+ float halfWidthPx = push.line.x;+ float gapHalfPx = push.line.y;+ float tilePx = max(push.misc.x, 1.0);++ // The offset is a pixel distance and the normal is a unit vector in tile-local+ // space, so dividing by the tile's pixel size converts one to the other.+ float offsetPx = inExtrude.x * gapHalfPx + inExtrude.y * halfWidthPx;+ vec2 offsetTile = inNormal * (offsetPx / tilePx);+ gl_Position = push.tileToClip * vec4(inPosition + offsetTile, 0.0, 1.0);++ // Distance along the line in pixels, for the dash pattern.+ outDistancePx = inDistance * tilePx;+}
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.rsnew file mode 100644index 0000000000..d39c21e245--- /dev/null+++ b/library/map/src/main/rust/src/bridge.rs@@ -0,0 +1,489 @@+//! The JNI surface: five entry points, and nothing per-feature or per-vertex.+//!+//! Kotlin creates and destroys the renderer for a `Surface`, resizes it, tells it whether+//! the device is online, and hands it **one camera snapshot per frame**. Tile selection,+//! fetching, decode, tessellation and drawing all happen on this side, so the boundary is+//! crossed a handful of times a frame rather than thousands.+//!+//! # Threading+//!+//! `render` is called from Kotlin's `Choreographer` callback, so on the main thread; every+//! Vulkan call happens there and the renderer is never driven from two threads at once.+//! Tile work — the range fetch, the gzip inflate, the MVT decode and the tessellation —+//! runs on a worker thread and hands finished meshes back through a channel, which+//! `render` drains. That is the split the plan asks for: the expensive half off the+//! critical path, and no JNI in the hot loop.++use crate::camera::Camera;+use crate::style::{self, Layer, Palette};+use crate::tile::cache::{RangeCache, DEFAULT_MAX_BYTES};+use crate::tile::geometry::{self, TileMesh};+use crate::tile::select::{self, TileId};+use crate::tile::source::{CachingRangeReader, JniRangeFetcher, BASEMAP_PMTILES_URL, CACHE_FORMAT};+use crate::vulkan::context::{ANativeWindow_acquire, ANativeWindow_fromSurface};+use crate::vulkan::renderer::Renderer;+use jni::objects::{JClass, JObject, JString};+use jni::sys::{jboolean, jfloat, jint, jlong};+use jni::JNIEnv;+use std::collections::HashSet;+use std::os::raw::c_void;+use std::sync::mpsc::{Receiver, Sender};+use std::sync::{Arc, Mutex};+use tilecodec::mvt::Tile;+use tilecodec::stream::StreamArchive;++/// The archive's zoom range, shared with the worker that reads it out of the header.+///+/// Atomics rather than a `Mutex` because `render` reads this every frame, and it must be+/// read live rather than copied once: the range is not known until the header has been+/// fetched, which is a network round trip *after* the surface exists. Copying it at startup+/// is how this was wrong before — it captured the guess and never corrected it, so the+/// renderer asked for a zoom level the archive does not contain and got nothing back.+struct ZoomRange {+ min: std::sync::atomic::AtomicU8,+ max: std::sync::atomic::AtomicU8,+}++impl ZoomRange {+ /// The published archive is z0-15. A wrong guess here is self-correcting once the+ /// header lands, but starting at the truth means the first frames are right too.+ fn unknown() -> ZoomRange {+ ZoomRange {+ min: std::sync::atomic::AtomicU8::new(0),+ max: std::sync::atomic::AtomicU8::new(15),+ }+ }++ fn set(&self, min: u8, max: u8) {+ self.min.store(min, std::sync::atomic::Ordering::Relaxed);+ self.max.store(max, std::sync::atomic::Ordering::Relaxed);+ }++ fn get(&self) -> (u8, u8) {+ (+ self.min.load(std::sync::atomic::Ordering::Relaxed),+ self.max.load(std::sync::atomic::Ordering::Relaxed),+ )+ }+}++/// How many tile workers run in parallel.+///+/// Each tile costs one or two **sequential** range requests — a leaf directory, then the+/// body — so its cost is dominated by round-trip latency, not CPU. One worker serialises+/// every tile behind every other: the archive probe measured a 24-tile screenful taking ~15+/// seconds that way, which is exactly the "really slow to change which elements load"+/// symptom. Four overlaps the waiting without opening enough sockets to matter.+const WORKER_COUNT: usize = 4;++/// What a worker reports back about a tile.+enum TileResult {+ /// Tessellated and ready to upload.+ Ready(TileMesh),+ /// The archive genuinely does not contain it — ordinary off the edge of coverage.+ /// Never retried.+ Absent,+ /// The fetch or decode failed. **Must** clear the in-flight marker so it can be tried+ /// again: leaving it set meant one transient network error blanked that tile for the+ /// rest of the session.+ Failed,+}++/// Everything one map surface owns. Handed to Kotlin as an opaque `jlong`.+struct MapHandle {+ renderer: Renderer,+ layers: Vec<Layer>,+ /// Meshes finished by the workers, waiting to be uploaded on the render thread.+ finished: Receiver<(u64, TileResult)>,+ /// Tiles the workers should fetch.+ wanted: Sender<TileId>,+ /// Requested but not yet arrived, so a tile is not asked for sixty times a second+ /// while it is in flight.+ in_flight: HashSet<u64>,+ /// Tiles the archive does not contain. Remembered so they are not re-requested every+ /// frame forever — most of a coastal viewport is ocean.+ absent: HashSet<u64>,+ online: Arc<OnlineFlag>,+ /// Light or dark. Switching costs nothing: colour is a push constant and the layer set+ /// is identical, so no tile is re-tessellated or re-uploaded.+ /// Light or dark, muted or not. Switching costs nothing: colour is a push constant and+ /// the layer set is identical, so no tile is re-tessellated or re-uploaded.+ palette: Palette,+ /// Read live every frame, because the worker only learns it after fetching the header.+ zoom_range: Arc<ZoomRange>,+ /// Frames drawn, for the once-a-second diagnostic log.+ frames: u32,+}++/// Shared so Kotlin's connectivity callback can reach the reader on the worker thread.+struct OnlineFlag(std::sync::atomic::AtomicBool);++impl OnlineFlag {+ fn set(&self, online: bool) {+ self.0.store(online, std::sync::atomic::Ordering::Relaxed);+ }+ fn get(&self) -> bool {+ self.0.load(std::sync::atomic::Ordering::Relaxed)+ }+}++/// Create the renderer for `surface`. Returns 0 on failure, having logged why.+///+/// # Safety+///+/// Called from the JVM with a live `Surface`.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ surface: JObject<'l>,+ cache_dir: JString<'l>,+ width: jint,+ height: jint,+ dark: jboolean,+ muted: jboolean,+) -> jlong {+ // The bridge back to `:library:network` has to be resolved before any worker thread+ // needs it; doing it here means the failure is visible at startup rather than as a+ // silently blank map.+ if !jni_http::init(&mut env) {+ log("library:network is missing, so tiles cannot be fetched");+ return 0;+ }++ let cache_dir: String = match env.get_string(&cache_dir) {+ Ok(s) => s.into(),+ Err(_) => return 0,+ };++ let window = unsafe {+ let raw_env = env.get_raw() as *mut c_void;+ let raw_surface = surface.as_raw() as *mut c_void;+ ANativeWindow_fromSurface(raw_env, raw_surface)+ };+ if window.is_null() {+ log("ANativeWindow_fromSurface returned null");+ return 0;+ }+ unsafe { ANativeWindow_acquire(window) };++ let renderer = match unsafe { Renderer::new(window, width.max(1) as u32, height.max(1) as u32) } {+ Ok(r) => r,+ Err(e) => {+ log(&format!("Vulkan init failed: {e}"));+ // The renderer never took ownership, so the window is released here.+ unsafe { crate::vulkan::context::ANativeWindow_release(window) };+ return 0;+ }+ };++ let online = Arc::new(OnlineFlag(std::sync::atomic::AtomicBool::new(true)));+ let (wanted_tx, wanted_rx) = std::sync::mpsc::channel::<TileId>();+ let (finished_tx, finished_rx) = std::sync::mpsc::channel::<(u64, TileResult)>();++ let zoom_range = Arc::new(ZoomRange::unknown());+ // One `Receiver` shared by every worker, so whichever is free takes the next tile.+ let queue = Arc::new(Mutex::new(wanted_rx));+ for index in 0..WORKER_COUNT {+ spawn_worker(+ index,+ cache_dir.clone(),+ queue.clone(),+ finished_tx.clone(),+ online.clone(),+ zoom_range.clone(),+ );+ }++ let handle = Box::new(MapHandle {+ renderer,+ layers: style::layers(),+ finished: finished_rx,+ wanted: wanted_tx,+ in_flight: HashSet::new(),+ absent: HashSet::new(),+ online,+ palette: Palette::new(dark != 0, muted != 0),+ zoom_range,+ frames: 0,+ });+ Box::into_raw(handle) as jlong+}++/// A worker: opens its own view of the archive, then serves tile requests until the queue+/// closes.+///+/// Each worker holds its **own** [`StreamArchive`], so its leaf-directory cache and range+/// reads need no lock. The cost is one 16 KB header fetch per worker at startup and a+/// duplicated leaf cache; the alternative — one archive behind a mutex — would serialise+/// exactly the round trips this is meant to overlap. The on-disk range cache is shared, and+/// is safe to share because every entry is written temp-then-renamed.+fn spawn_worker(+ index: usize,+ cache_dir: String,+ queue: Arc<Mutex<Receiver<TileId>>>,+ finished: Sender<(u64, TileResult)>,+ online: Arc<OnlineFlag>,+ zoom_range: Arc<ZoomRange>,+) {+ let started = std::thread::Builder::new()+ .name(format!("map-tiles-{index}"))+ .spawn(move || {+ let cache = RangeCache::open(+ cache_dir,+ &format!("{CACHE_FORMAT}|{BASEMAP_PMTILES_URL}"),+ DEFAULT_MAX_BYTES,+ );+ let reader = CachingRangeReader::new(BASEMAP_PMTILES_URL, cache, JniRangeFetcher);+ reader.set_online(online.get());++ let mut archive = match StreamArchive::open(reader) {+ Ok(a) => a,+ Err(e) => {+ log(&format!("worker {index} cannot open the pmtiles archive: {e}"));+ return;+ }+ };+ // Publish the real range. Until this lands the renderer works from a guess, and+ // a guess that is too high asks for a zoom the archive does not contain and+ // silently gets nothing back.+ zoom_range.set(archive.header.min_zoom, archive.header.max_zoom);+ let layers = style::layers();++ loop {+ // Hold the queue lock only long enough to take one tile, never across the+ // fetch — otherwise the workers would run strictly in turn.+ let next = match queue.lock() {+ Ok(guard) => guard.recv(),+ Err(_) => return,+ };+ let Ok(tile) = next else { return };+ let key = tile.key();++ let result = match archive.tile(tile.z, tile.x, tile.y) {+ Ok(Some(body)) => match Tile::decode(&body) {+ Ok(decoded) => TileResult::Ready(geometry::build(+ &decoded, &layers, tile.z, tile.x, tile.y,+ )),+ Err(e) => {+ log(&format!(+ "tile {}/{}/{} did not decode: {e}",+ tile.z, tile.x, tile.y+ ));+ TileResult::Failed+ }+ },+ Ok(None) => TileResult::Absent,+ Err(e) => {+ log(&format!("tile {}/{}/{} failed: {e}", tile.z, tile.x, tile.y));+ TileResult::Failed+ }+ };+ // A closed receiver means the surface went away mid-decode.+ if finished.send((key, result)).is_err() {+ return;+ }+ }+ })+ .is_ok();+ if !started {+ log(&format!("cannot start tile worker {index}"));+ }+}++/// Draw one frame from a camera snapshot. Returns false if the frame was skipped.+#[no_mangle]+#[allow(clippy::too_many_arguments)]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ center_lon: jfloat,+ center_lat: jfloat,+ zoom: jfloat,+ width_dp: jfloat,+ height_dp: jfloat,+ density: jfloat,+) -> jboolean {+ let Some(map) = handle_mut(handle) else { return 0 };++ let camera = Camera {+ center_lon: center_lon as f64,+ center_lat: center_lat as f64,+ zoom: zoom as f64,+ width_dp,+ height_dp,+ density,+ };++ // Upload whatever the workers finished. Doing it here rather than on a worker keeps+ // every Vulkan call on one thread.+ while let Ok((key, result)) = map.finished.try_recv() {+ map.in_flight.remove(&key);+ match result {+ TileResult::Ready(mesh) => {+ if let Err(e) = map.renderer.upload(key, &mesh) {+ log(&format!("uploading a tile failed: {e}"));+ }+ }+ // Remembered, so a mostly-ocean viewport does not re-request the same empty+ // tiles every frame for the life of the surface.+ TileResult::Absent => {+ map.absent.insert(key);+ }+ // Deliberately not recorded: clearing `in_flight` above is what lets it be+ // tried again, which is the whole point of distinguishing this from `Absent`.+ TileResult::Failed => {}+ }+ }++ // Keep the visible tiles plus any ancestor of one that we already have, but **fetch+ // only the visible tiles**. An ancestor is a fallback for a tile still in flight, so+ // it is only worth drawing if it is already resident — fetching one spends a round trip+ // to show a blurrier version of a tile that is being fetched anyway, and because+ // ancestors sort first it spent that latency before requesting what the user is+ // actually looking at.+ let (min_zoom, max_zoom) = map.zoom_range.get();+ let keep: Vec<u64> =+ select::resident_set(&camera, min_zoom, max_zoom).iter().map(|t| t.key()).collect();+ for tile in select::visible(&camera, min_zoom, max_zoom) {+ let key = tile.key();+ if map.renderer.has_tile(key) || map.absent.contains(&key) || !map.in_flight.insert(key)+ {+ continue;+ }+ // A closed channel means every worker died; the map keeps drawing what it has.+ let _ = map.wanted.send(tile);+ }+ map.renderer.retain(&keep);++ // Once a second, state what the renderer actually has. Every bug in this file so far has+ // been invisible from the outside: a viewport nobody measured, a zoom level the archive+ // does not contain, a tile stuck in flight forever. All of them would have been one line+ // of this away.+ map.frames += 1;+ if map.frames % 60 == 0 {+ let (tiles, meshes, draws, triangles) = map.renderer.stats();+ let (width_px, height_px) = map.renderer.extent();+ // `meshes` is what is resident, `draws` what the last frame actually submitted. They+ // differ wherever the authored style ramps a layer's width to zero, so reporting only+ // the first would claim roads are being drawn at zooms where they are gated out.+ log_info(&format!(+ "z{:.2} @{:.4},{:.4} vp {}x{}dp {}x{}px | resident {} tiles, {} meshes, {} draws, \+ {} tris | {} in flight, {} absent | archive z{}..{}",+ camera.zoom,+ camera.center_lon,+ camera.center_lat,+ camera.width_dp,+ camera.height_dp,+ width_px,+ height_px,+ tiles,+ meshes,+ draws,+ triangles,+ map.in_flight.len(),+ map.absent.len(),+ min_zoom,+ max_zoom,+ ));+ }++ match map.renderer.render(&camera, &map.layers, map.palette, style::background(map.palette.variant)) {+ Ok(drawn) => jboolean::from(drawn),+ Err(e) => {+ log(&format!("frame failed: {e}"));+ 0+ }+ }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_resize<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ width: jint,+ height: jint,+) {+ if let Some(map) = handle_mut(handle) {+ map.renderer.resize(width.max(0) as u32, height.max(0) as u32);+ }+}++/// Switch palette. Free: colour is a push constant and the layer set is identical, so+/// nothing is re-tessellated or re-uploaded.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setPalette<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ dark: jboolean,+ muted: jboolean,+) {+ if let Some(map) = handle_mut(handle) {+ map.palette = Palette::new(dark != 0, muted != 0);+ }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setOnline<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ online: jboolean,+) {+ if let Some(map) = handle_mut(handle) {+ map.online.set(online != 0);+ }+}++/// Destroy the renderer and release its window.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_destroy<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if handle == 0 {+ return;+ }+ // Dropping the handle drops the sender, which ends the worker's `recv` loop, and then+ // the renderer, which waits for the device to go idle before freeing anything.+ unsafe { drop(Box::from_raw(handle as *mut MapHandle)) };+}++fn handle_mut(handle: jlong) -> Option<&'static mut MapHandle> {+ if handle == 0 {+ return None;+ }+ // The handle is only ever the pointer `create` returned, and Kotlin drives all of+ // these from one thread.+ unsafe { Some(&mut *(handle as *mut MapHandle)) }+}++/// Logcat, at error level.+///+/// A renderer that fails silently is the thing this whole layer must not do: an empty map+/// looks exactly like a working map over the sea.+fn log(message: &str) {+ write_log(6, message);+}++/// Logcat, at info level, for the periodic frame report.+fn log_info(message: &str) {+ write_log(4, message);+}++fn write_log(priority: i32, message: &str) {+ #[link(name = "log")]+ extern "C" {+ fn __android_log_write(priority: i32, tag: *const u8, text: *const u8) -> i32;+ }+ let tag = b"MapRenderer\0";+ let mut text: Vec<u8> = message.as_bytes().to_vec();+ text.push(0);+ unsafe {+ __android_log_write(priority, tag.as_ptr(), text.as_ptr());+ }+}
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.rsnew file mode 100644index 0000000000..6af369ba3d--- /dev/null+++ b/library/map/src/main/rust/src/camera.rs@@ -0,0 +1,235 @@+//! The camera: a snapshot from Kotlin to a per-tile clip-space matrix.+//!+//! Web Mercator with a 256-logical-px tile grid, matching `:library:map`'s+//! `Mercator.kt` exactly — the Kotlin side owns the public `Projection` in `Dp`, this+//! side has to agree with it or every overlay drifts from the basemap under it.+//!+//! Only the camera crosses JNI, once per frame. Everything per-tile is derived here.++/// Logical pixels across one tile. Web Mercator's convention, and `Mercator.kt`'s.+pub const TILE_SIZE: f64 = 256.0;++/// The camera as Kotlin measured it.+#[derive(Clone, Copy, Debug)]+pub struct Camera {+ pub center_lon: f64,+ pub center_lat: f64,+ pub zoom: f64,+ /// Viewport in logical pixels (Dp), as the Compose host measured it.+ pub width_dp: f32,+ pub height_dp: f32,+ /// Device pixels per Dp. The only place a physical pixel enters.+ pub density: f32,+}++/// A point in Web Mercator world pixels at some zoom.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct WorldPx {+ pub x: f64,+ pub y: f64,+}++/// Total map width and height in logical px at `zoom`.+pub fn world_size(zoom: f64) -> f64 {+ TILE_SIZE * 2f64.powf(zoom)+}++/// Project lon/lat degrees to world px at `zoom`.+pub fn project(lon: f64, lat: f64, zoom: f64) -> WorldPx {+ let size = world_size(zoom);+ // Mercator y is undefined at the poles; this is the standard web-mapping clamp+ // and the same constant `Mercator.kt` uses.+ let lat = lat.clamp(-85.051_128_78, 85.051_128_78);+ let x = (lon + 180.0) / 360.0 * size;+ let sin_lat = (lat * std::f64::consts::PI / 180.0).sin();+ let y = (0.5 - ((1.0 + sin_lat) / (1.0 - sin_lat)).ln() / (4.0 * std::f64::consts::PI)) * size;+ WorldPx { x, y }+}++/// Inverse of [`project`].+pub fn unproject(x: f64, y: f64, zoom: f64) -> (f64, f64) {+ let size = world_size(zoom);+ let lon = x / size * 360.0 - 180.0;+ let n = std::f64::consts::PI - 2.0 * std::f64::consts::PI * y / size;+ let lat = n.sinh().atan() * 180.0 / std::f64::consts::PI;+ (lon, lat)+}++impl Camera {+ /// The world-px position of the viewport's top-left corner.+ pub fn viewport_origin(&self) -> WorldPx {+ let center = project(self.center_lon, self.center_lat, self.zoom);+ WorldPx {+ x: center.x - self.width_dp as f64 / 2.0,+ y: center.y - self.height_dp as f64 / 2.0,+ }+ }++ /// The screen size of one tile at zoom level `z`, in logical px.+ pub fn tile_span_dp(&self, z: u8) -> f64 {+ TILE_SIZE * 2f64.powf(self.zoom - z as f64)+ }++ /// The screen size of one tile at zoom `z` in **device** px, which is what turns a+ /// pixel line width into tile-local units in the vertex shader.+ pub fn tile_span_px(&self, z: u8) -> f32 {+ (self.tile_span_dp(z) * self.density as f64) as f32+ }++ /// Column-major 4x4 taking tile-local 0..1 to Vulkan clip space.+ ///+ /// ```text+ /// clip.x = 2 * (tile_origin.x + u * span - viewport_origin.x) / width - 1+ /// clip.y = -1 + 2 * (tile_origin.y + v * span - viewport_origin.y) / height+ /// ```+ ///+ /// Note the sign of y. Vulkan's clip space has **y down** — unlike OpenGL, and+ /// unlike WebGPU — and Mercator y also grows downward, so the two agree and no+ /// flip is needed. Adding one anyway mirrors the whole map vertically, which is+ /// easy to miss on a symmetric city and obvious on a coastline.+ pub fn tile_to_clip(&self, z: u8, x: u32, y: u32) -> [f32; 16] {+ let span = self.tile_span_dp(z);+ let origin = self.viewport_origin();+ let tile_x = x as f64 * span;+ let tile_y = y as f64 * span;++ let sx = 2.0 * span / self.width_dp as f64;+ let sy = 2.0 * span / self.height_dp as f64;+ let tx = 2.0 * (tile_x - origin.x) / self.width_dp as f64 - 1.0;+ let ty = 2.0 * (tile_y - origin.y) / self.height_dp as f64 - 1.0;++ [+ sx as f32, 0.0, 0.0, 0.0, //+ 0.0, sy as f32, 0.0, 0.0, //+ 0.0, 0.0, 1.0, 0.0, //+ tx as f32, ty as f32, 0.0, 1.0,+ ]+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn camera(zoom: f64) -> Camera {+ Camera {+ center_lon: 0.0,+ center_lat: 0.0,+ zoom,+ width_dp: 512.0,+ height_dp: 512.0,+ density: 1.0,+ }+ }++ /// Apply a column-major 4x4 to a 2D point, as the vertex shader does.+ fn transform(m: &[f32; 16], u: f32, v: f32) -> (f32, f32) {+ (m[0] * u + m[4] * v + m[12], m[1] * u + m[5] * v + m[13])+ }++ #[test]+ fn the_world_is_256_dp_per_tile() {+ assert_eq!(world_size(0.0), 256.0);+ assert_eq!(world_size(1.0), 512.0);+ assert_eq!(world_size(14.0), 256.0 * 16384.0);+ }++ #[test]+ fn project_and_unproject_round_trip() {+ for zoom in [0.0, 5.0, 11.0, 14.0, 18.0] {+ for &(lon, lat) in+ &[(0.0, 0.0), (-122.4194, 37.7749), (151.2093, -33.8688), (2.3522, 48.8566)]+ {+ let p = project(lon, lat, zoom);+ let (back_lon, back_lat) = unproject(p.x, p.y, zoom);+ assert!((back_lon - lon).abs() < 1e-9, "lon at z{zoom}: {back_lon} vs {lon}");+ assert!((back_lat - lat).abs() < 1e-9, "lat at z{zoom}: {back_lat} vs {lat}");+ }+ }+ }++ #[test]+ fn null_island_is_the_centre_of_the_world() {+ let p = project(0.0, 0.0, 0.0);+ assert!((p.x - 128.0).abs() < 1e-9);+ assert!((p.y - 128.0).abs() < 1e-9);+ }++ #[test]+ fn the_tile_containing_the_camera_covers_the_viewport_centre() {+ // At z1 centred on null island, the four tiles meet exactly at the centre of a+ // 512 Dp viewport, so tile 0/0's bottom-right corner lands at clip (0, 0).+ let camera = camera(1.0);+ let m = camera.tile_to_clip(1, 0, 0);+ let (x, y) = transform(&m, 1.0, 1.0);+ assert!(x.abs() < 1e-5, "x {x}");+ assert!(y.abs() < 1e-5, "y {y}");+ }++ #[test]+ fn clip_space_y_grows_downward_as_vulkan_and_mercator_both_do() {+ // The tile's top edge must land at a *smaller* clip y than its bottom edge. A+ // flip here mirrors the map.+ let camera = camera(1.0);+ let m = camera.tile_to_clip(1, 0, 0);+ let (_, top) = transform(&m, 0.0, 0.0);+ let (_, bottom) = transform(&m, 0.0, 1.0);+ assert!(top < bottom, "top {top} must be above bottom {bottom} in clip space");+ }++ #[test]+ fn a_full_screen_tile_fills_clip_space() {+ // At z0 with a 256 Dp viewport the single tile is exactly the screen, so its+ // corners are the corners of clip space.+ let camera = Camera { width_dp: 256.0, height_dp: 256.0, ..camera(0.0) };+ let m = camera.tile_to_clip(0, 0, 0);+ let (x0, y0) = transform(&m, 0.0, 0.0);+ let (x1, y1) = transform(&m, 1.0, 1.0);+ assert!((x0 - -1.0).abs() < 1e-5, "left {x0}");+ assert!((y0 - -1.0).abs() < 1e-5, "top {y0}");+ assert!((x1 - 1.0).abs() < 1e-5, "right {x1}");+ assert!((y1 - 1.0).abs() < 1e-5, "bottom {y1}");+ }++ #[test]+ fn adjacent_tiles_share_an_edge_with_no_gap() {+ // A seam here is a visible hairline between every pair of tiles.+ let camera = Camera { center_lon: -122.4194, center_lat: 37.7749, ..camera(12.0) };+ let left = camera.tile_to_clip(12, 654, 1583);+ let right = camera.tile_to_clip(12, 655, 1583);+ let (left_edge, _) = transform(&left, 1.0, 0.0);+ let (right_edge, _) = transform(&right, 0.0, 0.0);+ assert!((left_edge - right_edge).abs() < 1e-5, "{left_edge} vs {right_edge}");+ }++ #[test]+ fn overzoom_scales_a_tile_up_rather_than_leaving_a_hole() {+ // The archive stops at z16 and users keep zooming, so a z16 tile drawn at z19+ // must be 8x its normal size.+ let camera = camera(19.0);+ assert!((camera.tile_span_dp(16) - 256.0 * 8.0).abs() < 1e-9);+ }++ #[test]+ fn density_only_affects_the_pixel_span() {+ // tile_span_dp is a logical measurement and must not move with density;+ // tile_span_px is the only thing that scales, because it feeds a pixel width.+ let one = Camera { density: 1.0, ..camera(14.0) };+ let three = Camera { density: 3.0, ..camera(14.0) };+ assert_eq!(one.tile_span_dp(14), three.tile_span_dp(14));+ assert!((three.tile_span_px(14) / one.tile_span_px(14) - 3.0).abs() < 1e-5);+ }++ #[test]+ fn latitude_is_clamped_at_the_mercator_limit_rather_than_returning_infinity() {+ // Mercator y goes to infinity at the poles. The clamp puts +-90 exactly on the+ // top and bottom edges of the world, up to floating-point slack — so the+ // tolerance is one world pixel rather than zero.+ let size = world_size(4.0);+ for lat in [90.0, -90.0, 89.9, -89.9] {+ let p = project(0.0, lat, 4.0);+ assert!(p.y.is_finite(), "y at lat {lat} is {}", p.y);+ assert!(p.y >= -1.0 && p.y <= size + 1.0, "y at lat {lat} is {}, off the map", p.y);+ }+ }+}
library/map/src/main/rust/src/lib.rs
diff --git a/library/map/src/main/rust/src/lib.rs b/library/map/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..fe98a48564--- /dev/null+++ b/library/map/src/main/rust/src/lib.rs@@ -0,0 +1,43 @@+//! The Vulkan vector-tile map renderer behind `:library:map`.+//!+//! Replaces the CARTO raster basemap in findfamily, photos, weather, taxi and+//! fooddelivery (#615) with our own renderer over the self-hosted pmtiles archive at+//! `data.vayunmathur.com/v4.pmtiles` — the same archive `maps` streams through+//! MapLibre.+//!+//! # Layout+//!+//! * [`tess`] — MVT geometry to triangles: earcut fills, stroked lines. Pure, and the+//! half of a frame that actually costs something.+//! * [`style`] — which layers are drawn, in what order, in what colour.+//! * [`camera`] — a camera snapshot from Kotlin to a per-tile clip matrix.+//! * [`tile`] — the streaming PMTiles reader, its range cache, and tile selection.+//! * `vulkan` — device, swapchain, pipelines, frame. Android only.+//!+//! # The JNI boundary+//!+//! Deliberately narrow, and never in the hot loop: Kotlin creates and destroys the+//! renderer for a `Surface`, resizes it, and hands it **one camera snapshot per+//! frame**. Everything else — tile selection, fetching, decode, tessellation,+//! drawing — happens on this side. A per-feature or per-vertex crossing would cost+//! more than the rendering does.+//!+//! `Projection` stays in Kotlin, in `Dp`, because it is public API that every+//! consumer app's overlays are positioned by.+//!+//! # Host builds+//!+//! Everything except the Vulkan and JNI layers compiles and tests on the host, so+//! `cargo test` covers tessellation, tile selection, the cache and the camera maths+//! with no device attached.++pub mod camera;+pub mod style;+pub mod tess;+pub mod tile;++#[cfg(target_os = "android")]+pub mod vulkan;++#[cfg(target_os = "android")]+mod bridge;
library/map/src/main/rust/src/style/expr.rs
diff --git a/library/map/src/main/rust/src/style/expr.rs b/library/map/src/main/rust/src/style/expr.rsnew file mode 100644index 0000000000..a200fbc2a4--- /dev/null+++ b/library/map/src/main/rust/src/style/expr.rs@@ -0,0 +1,635 @@+//! Evaluating MapLibre style expressions.+//!+//! Enough of the spec to render `style/basemap.json`, and deliberately no more. The+//! operators here are exactly the ones that file uses in `fill` and `line` layers, counted+//! from the file itself rather than guessed:+//!+//! | operator | uses | | operator | uses |+//! |---|---|---|---|---|+//! | `get` | 90 | | `literal` | 22 |+//! | `zoom` | 73 | | `case` | 16 |+//! | `interpolate` | 67 | | `coalesce` | 12 |+//! | `exponential` | 54 | | `step` | 5 |+//! | `in` | 37 | | `match` | 3 |+//! | `linear` | 13 | | comparisons | 65 |+//!+//! # Why this exists+//!+//! The previous version of this module was a hand-written table of constants approximating+//! the authored style. It could not converge: every fix revealed another mismatch, because+//! the real values — 34 `landuse` kinds, opacity ramps, per-kind colour cases — are already+//! written down in a file that MapLibre renders correctly. Transcribing a 71-layer style by+//! eye is not a strategy. Evaluating it is.+//!+//! # What is deliberately missing+//!+//! `concat`, `to-string` and the other string operators, because they appear only in+//! `text-field` on `symbol` layers, and labels are a later phase. An unknown operator is an+//! error rather than a silent default, so if that changes it will say so.++use serde_json::Value as Json;+use std::collections::HashMap;++/// A value flowing through an expression.+#[derive(Clone, Debug, PartialEq)]+pub enum Value {+ Null,+ Bool(bool),+ Number(f64),+ String(String),+ /// A `["literal", [...]]` array, used as the haystack of `in`.+ List(Vec<Value>),+}++impl Value {+ pub fn as_number(&self) -> Option<f64> {+ match self {+ Value::Number(n) => Some(*n),+ _ => None,+ }+ }++ pub fn as_str(&self) -> Option<&str> {+ match self {+ Value::String(s) => Some(s.as_str()),+ _ => None,+ }+ }++ /// Truthiness, as the style spec defines it for `case` and the boolean operators.+ pub fn truthy(&self) -> bool {+ match self {+ Value::Null => false,+ Value::Bool(b) => *b,+ Value::Number(n) => *n != 0.0 && !n.is_nan(),+ Value::String(s) => !s.is_empty(),+ Value::List(l) => !l.is_empty(),+ }+ }++ fn from_json(json: &Json) -> Value {+ match js
Diff truncated.