Modern Apps git

← Modern-Apps.git

various fixes

Commit
953499db932ac036d73c0d21966855a4006f1fb0
Author
vayun-mathur <[email protected]>
When
2026-09-06 03:27 UTC (3 months ago)
Parents
f891b8b

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 7e94d38249..984a00b1d9 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -35,6 +35,7 @@ body:         - music         - musicbrainz         - notes+        - nowplaying         - office         - openassistant         - passwords@@ -46,6 +47,7 @@ body:         - things         - translate         - travel+        - tuner         - unblockjam         - vpn         - voxels
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 856592bef3..f54bdb8a7d 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -35,6 +35,7 @@ body:         - music         - musicbrainz         - notes+        - nowplaying         - office         - openassistant         - passwords@@ -46,6 +47,7 @@ body:         - things         - translate         - travel+        - tuner         - unblockjam         - vpn         - voxels
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex fee106cf3b..64be80cbe1 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['alchemist', 'appstore', 'astronomy', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['alchemist', 'appstore', 'astronomy', 'calculator', 'calendar', 'camera', 'chess', 'clock', 'code', 'contacts', 'education', 'email', 'everysync', 'files', 'findfamily', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'maps', 'measure', 'messages', 'music', 'musicbrainz', 'notes', 'nowplaying', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'solitaire', 'speech', 'things', 'translate', 'travel', 'tuner', 'unblockjam', 'vpn', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex c6316fe231..441668df64 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2096,6 +2096,7 @@ dependencies = [  "ash",  "jni",  "jni_http",+ "png",  "serde_json",  "sha2 0.10.9",  "tilecodec",
README.md
diff --git a/README.md b/README.mdindex b23e94d752..8b9cfb40f3 100644--- a/README.md+++ b/README.md@@ -65,6 +65,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Music** | [Homepage](https://ma.vayunmathur.com/apps/music) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.music/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Music&packageName=com.vayunmathur.music&apk=music-release.apk) | | **MusicBrainz** | [Homepage](https://ma.vayunmathur.com/apps/musicbrainz) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.musicbrainz/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=MusicBrainz&packageName=com.vayunmathur.musicbrainz&apk=musicbrainz-release.apk) | | **Notes** | [Homepage](https://ma.vayunmathur.com/apps/notes) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.notes/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Notes&packageName=com.vayunmathur.notes&apk=notes-release.apk) |+| **Now Playing** | [Homepage](https://ma.vayunmathur.com/apps/nowplaying) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.nowplaying/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Now%20Playing&packageName=com.vayunmathur.nowplaying&apk=nowplaying-release.apk) | | **Office** | [Homepage](https://ma.vayunmathur.com/apps/office) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.office) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Office&packageName=com.vayunmathur.office&apk=office-release.apk) | | **Open Assistant** | [Homepage](https://ma.vayunmathur.com/apps/openassistant) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.openassistant) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=OpenAssistant&packageName=com.vayunmathur.openassistant&apk=openassistant-release.apk) | | **Passwords** | [Homepage](https://ma.vayunmathur.com/apps/passwords) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.passwords/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Passwords&packageName=com.vayunmathur.passwords&apk=passwords-release.apk) |@@ -75,6 +76,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Taxi (US and Canada only)** | [Homepage](https://ma.vayunmathur.com/apps/taxi) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://ma.vayunmathur.com/fdroid) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Taxi&packageName=com.vayunmathur.taxi&apk=taxi-release.apk) | | **Translate** | [Homepage](https://ma.vayunmathur.com/apps/translate) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.translate/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Translate&packageName=com.vayunmathur.translate&apk=translate-release.apk) | | **Travel** | [Homepage](https://ma.vayunmathur.com/apps/travel) | In Progress | In Progress |+| **Tuner** | [Homepage](https://ma.vayunmathur.com/apps/tuner) | In Progress | In Progress | | **VPN** | [Homepage](https://ma.vayunmathur.com/apps/vpn) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.vpn/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=VPN&packageName=com.vayunmathur.vpn&apk=vpn-release.apk) | | **Weather** | [Homepage](https://ma.vayunmathur.com/apps/weather) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.weather) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Weather&packageName=com.vayunmathur.weather&apk=weather-release.apk) | | **Web** | [Homepage](https://ma.vayunmathur.com/apps/web) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.web/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Web&packageName=com.vayunmathur.web&apk=web-release.apk) |
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex bbaa9ea9d8..44ba0087bb 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -119,6 +119,7 @@ import com.vayunmathur.findfamily.util.Platform import com.vayunmathur.findfamily.util.UwbSessionManager import com.vayunmathur.library.ui.BackupButtons import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.rememberCameraState import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconCopy@@ -280,6 +281,12 @@ fun MainPage(         person = selectedUser?.let { PersonUiState(it, userPositions[it.id], waypoints) }     ) +    // Owned here, not by MapView: the two animateTo effects below drive it, and MapView is+    // reached through MainPageContent's stateless `map` slot. This was previously a+    // process-global `val camera` in MapView.kt for exactly that reason. rememberSaveable+    // inside rememberCameraState now also carries it across rotation and process death.+    val camera = rememberCameraState()+     MainPageContent(         state = state,         familyActions = familyActions,@@ -315,6 +322,7 @@ fun MainPage(              MapView(                 ffViewModel,+                camera = camera,                 onUserClick = {                     ffViewModel.selectUser(it)                 },
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 8982dc7768..df199f5f2f 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -5,7 +5,6 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import com.vayunmathur.library.ui.MaterialTheme@@ -15,7 +14,6 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue@@ -49,7 +47,6 @@ import com.vayunmathur.findfamily.util.FindFamilyViewModel import com.vayunmathur.library.ui.invisibleClickable import kotlinx.coroutines.Dispatchers 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.VectorMap@@ -57,8 +54,6 @@ import kotlin.io.encoding.Base64 import kotlin.math.abs import kotlin.math.cos -val camera = CameraState(CameraPosition())- data class SelectedUser(val user: User, val isShowingPresent: Boolean, val historicalPosition: GeoPoint?) data class SelectedWaypoint(val waypoint: Waypoint, val range: Double, val onMoveWaypoint: (Coord) -> Unit) @@ -67,6 +62,7 @@ private fun GeoPoint.toCoord() = Coord(latitude, longitude) @Composable fun MapView(     viewModel: FindFamilyViewModel,+    camera: CameraState,     onUserClick: (Long) -> Unit,     onMapClick: () -> Unit,     selectedUser: SelectedUser? = null,@@ -105,23 +101,27 @@ fun MapView(                 cameraState = camera,                 zoomRange = 0f..20f,                 onMapClick = { onMapClick() },-            )--            if (initialized) {-                // The coordinate at the screen centre — i.e. the live position of-                // the waypoint currently being placed/dragged. Computed outside the-                // Canvas draw scope so we never invoke callbacks while drawing.-                val draggedCoord = remember(camera.position, sizeInDp) {-                    camera.projection?.positionFromScreenLocation(sizeInDp)?.toCoord()-                }-                // Report the dragged position back to the parent outside of drawing.-                if (selectedWaypoint != null && draggedCoord != null) {-                    LaunchedEffect(draggedCoord) {-                        selectedWaypoint.onMoveWaypoint(draggedCoord)+            ) {+                if (initialized) {+                    // The coordinate at the screen centre — i.e. the live position of+                    // the waypoint currently being placed/dragged. Computed outside the+                    // Canvas draw scope so we never invoke callbacks while drawing.+                    val draggedCoord = remember(camera.position, sizeInDp) {+                        camera.projection?.positionFromScreenLocation(sizeInDp)?.toCoord()+                    }+                    // Report the dragged position back to the parent outside of drawing.+                    if (selectedWaypoint != null && draggedCoord != null) {+                        LaunchedEffect(draggedCoord) {+                            selectedWaypoint.onMoveWaypoint(draggedCoord)+                        }                     }-                }-                key(camera.position, sizeInDp) {                     Canvas(Modifier.fillMaxSize()) {+                        // Read inside the draw lambda, so a camera move re-runs drawing only.+                        // This used to be three `camera.projection!!` reads wrapped in a+                        // `key(camera.position, sizeInDp)` that threw the whole subtree away+                        // every frame of a pan — and crashed outright in the frames before+                        // the viewport was measured.+                        val proj = projection ?: return@Canvas                         val allWaypoints =                             if (selectedWaypoint?.waypoint?.id == 0L) (waypoints + selectedWaypoint.waypoint) else waypoints                         for (waypoint in allWaypoints) {@@ -130,13 +130,12 @@ fun MapView(                             val coord = if (selectedWaypoint?.waypoint == waypoint) {                                 draggedCoord ?: waypoint.coord                             } else waypoint.coord-                            val center =-                                camera.projection!!.screenLocationFromPosition(coord.toGeoPoint())+                            val center = proj.screenLocationFromPosition(coord.toGeoPoint())                             if (center !in size.toDpSize()) continue                             val circumferenceAtLatitude =                                 40_075_000 * cos(radians(waypoint.coord.lat))                             val radiusInDegrees = 360 * radiusMeters / circumferenceAtLatitude-                            val edgePoint = camera.projection!!.screenLocationFromPosition(+                            val edgePoint = proj.screenLocationFromPosition(                                 GeoPoint(coord.lon + radiusInDegrees, coord.lat)                             )                             val radiusPx = abs((center.x - edgePoint.x).toPx())@@ -148,35 +147,23 @@ fun MapView(                             )                         }                     }-                }-                for (user in users) {-                    if (selectedUser != null && user.id != selectedUser.user.id) continue-                    val position = userPositions[user.id]?.coord?.toGeoPoint() ?: continue-                    val center =-                        camera.projection!!.screenLocationFromPosition(position) - DpOffset(-                            35.dp,-                            35.dp-                        )--                    Box(Modifier.offset(center.x, center.y)) {-                        UserPicture(-                            user,-                            70.dp,-                            selectedUser != null && !selectedUser.isShowingPresent-                        ) {-                            onUserClick(user.id)+                    for (user in users) {+                        if (selectedUser != null && user.id != selectedUser.user.id) continue+                        val position = userPositions[user.id]?.coord?.toGeoPoint() ?: continue+                        MapMarker(position) {+                            UserPicture(+                                user,+                                70.dp,+                                selectedUser != null && !selectedUser.isShowingPresent+                            ) {+                                onUserClick(user.id)+                            }                         }                     }-                }-                if (selectedUser != null && !selectedUser.isShowingPresent && selectedUser.historicalPosition != null) {-                    val center =-                        camera.projection!!.screenLocationFromPosition(selectedUser.historicalPosition) - DpOffset(-                            35.dp,-                            35.dp-                        )--                    Box(Modifier.offset(center.x, center.y)) {-                        UserPicture(selectedUser.user, 70.dp)+                    if (selectedUser != null && !selectedUser.isShowingPresent && selectedUser.historicalPosition != null) {+                        MapMarker(selectedUser.historicalPosition) {+                            UserPicture(selectedUser.user, 70.dp)+                        }                     }                 }             }
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 20fc1c3b75..72ced04919 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt@@ -11,7 +11,6 @@ import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width@@ -31,7 +30,6 @@ import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.image.compose.AsyncImage@@ -218,38 +216,33 @@ private fun TrackingMap(order: Order, modifier: Modifier = Modifier) {     }      Box(modifier) {-        VectorMap(cameraState = camera)-        val projection = camera.projection-        if (projection != null) {+        VectorMap(cameraState = camera) {             // Distinct glyph per pin: menu = restaurant, arrow = courier, home = you.             restaurant?.let {-                MapPin(projection.screenLocationFromPosition(it),-                    MaterialTheme.colorScheme.tertiary) { IconRestaurant() }+                MapMarker(it) { PinChrome(MaterialTheme.colorScheme.tertiary) { IconRestaurant() } }             }             destination?.let {-                MapPin(projection.screenLocationFromPosition(it),-                    MaterialTheme.colorScheme.primary) { IconHome() }+                MapMarker(it) { PinChrome(MaterialTheme.colorScheme.primary) { IconHome() } }             }             driver?.let {-                MapPin(projection.screenLocationFromPosition(it),-                    MaterialTheme.colorScheme.secondary) { IconDeliveryDining() }+                MapMarker(it) { PinChrome(MaterialTheme.colorScheme.secondary) { IconDeliveryDining() } }             }         }     } } -/** A circular marker centred on [at]. */+/**+ * The circular disc a pin's icon sits on. Stays app-side rather than moving into+ * `:library:map` with the positioning: it reads `colorScheme`, and that module has no+ * material3.+ */ @Composable-private fun MapPin(-    at: DpOffset,+private fun PinChrome(     color: androidx.compose.ui.graphics.Color,     icon: @Composable () -> Unit, ) {-    val size = 32.dp-    Box(Modifier.offset(at.x - size / 2, at.y - size / 2)) {-        Surface(color = color, shape = CircleShape, modifier = Modifier.size(size)) {-            Box(contentAlignment = Alignment.Center) { icon() }-        }+    Surface(color = color, shape = CircleShape, modifier = Modifier.size(32.dp)) {+        Box(contentAlignment = Alignment.Center) { icon() }     } } 
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 18a21a0e2b..13d880a1e1 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -82,7 +82,6 @@ javaxAnnotation = "1.3.2" jsr305 = "3.0.2" zxing = "3.5.4" libphonenumber = "9.0.34"-litertlmAndroid = "0.14.0" brotli = "0.1.2" # Zstandard JNI bindings (com.github.luben) for the offline geocoder block codec. zstdJni = "1.5.6-9"@@ -131,6 +130,7 @@ gplayapi = "3.6.4" streamWebrtc = "1.3.8"  [libraries]+kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" }  # ============================================================================= # GOOGLE / ANDROID / JETBRAINS@@ -165,6 +165,10 @@ androidx-fragment-ktx = { group = "androidx.fragment", name = "fragment-ktx", ve androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" } androidx-lifecycle-viewmodel-ktx = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle" } androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }+# Supplies androidx.lifecycle.compose.LocalLifecycleOwner. The androidx.compose.ui.platform+# one is deprecated. Consumed by :library:map only — deliberately not in+# common-conventions-library, which would reconfigure every module for one consumer.+androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" } androidx-sqlite = { module = "androidx.sqlite:sqlite", version.ref = "sqlite" } androidx-sqlite-framework = { module = "androidx.sqlite:sqlite-framework", version.ref = "sqlite" } androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "workRuntimeKtx" }@@ -258,7 +262,6 @@ javax-annotation-api = { module = "javax.annotation:javax.annotation-api", versi google-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" } zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" }-litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" } brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" } zstd-jni = { module = "com.github.luben:zstd-jni", version.ref = "zstdJni" } apksig = { module = "com.android.tools.build:apksig", version.ref = "apksig" }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.ktindex 44b9ba79fe..12e328f7ff 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt@@ -6,28 +6,127 @@ package com.vayunmathur.library.downloadservice  * The server must host each file under https://data.vayunmathur.com/models/  * and set Content-Length + ETag.  *- * To populate the mirror, upload these HuggingFace source files under the given- * mirror paths (left = mirror path, right = HuggingFace source):+ * # Gemma 4 is five files, not one  *- *   models/gemma-4-E2B-it.litertlm- *     <- https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm+ * The single `.litertlm` was replaced by this repo's own `.maml` format when `:openassistant`+ * moved off `com.google.ai.edge.litertlm` onto `:library:ml`. Several files rather than one because+ * they have different lifetimes and different readers:+ *+ *   * the decoder, which the GPU binds,+ *   * the embedding, which only the host reads a row at a time and which is therefore its own+ *     graph rather than tensors inside the decoder,+ *   * the tokenizer table, which is tiny and is read once into memory,+ *   * the vision tower and the audio tower, each of which is a separate encoder that produces+ *     soft tokens in the decoder's embedding space.+ *+ * The first three must be present before the assistant will start - see `Gemma4Handle.FILES`.+ * The two encoders are optional at load: a device that never sends a picture or a clip still+ * answers text.+ *+ * To populate the mirror, produce the files from the ONNX export and upload them:+ *+ *   models/gemma4_text.maml+ *     <- python3 scripts/ml/maml_convert.py decoder_model_merged_fp16.onnx \+ *          --graph gemma4_text -o gemma4_text.maml+ *   models/gemma4_embed.maml+ *     <- python3 scripts/ml/maml_convert.py embed_tokens_fp16.onnx \+ *          --graph gemma4_embed -o gemma4_embed.maml+ *   models/gemma4_tokenizer.spm1+ *     <- python3 scripts/ml/gemma4_tokenizer.py --tokenizer tokenizer.json \+ *          -o gemma4_tokenizer.spm1+ *   models/gemma4_vision.maml+ *     <- python3 scripts/ml/maml_convert.py vision_encoder_fp16.onnx \+ *          --graph gemma4_vision -o gemma4_vision.maml+ *   models/gemma4_audio.maml+ *     <- python3 scripts/ml/maml_convert.py audio_encoder_fp16.onnx \+ *          --graph gemma4_audio -o gemma4_audio.maml+ *+ * The ONNX inputs are `onnx-community/gemma-4-E2B-it-ONNX`, which is Apache-2.0 and ungated.  */ object ModelUrls {     const val MIRROR_BASE = "https://data.vayunmathur.com/models/" -    // On-disk file name.-    const val GEMMA_FILE = "gemma4-2b.litertlm"+    /** The decoder: 35 layers at int4 with per-block scales. */+    const val GEMMA_TEXT_FILE = "gemma4_text.maml"+    const val GEMMA_TEXT_URL = "${MIRROR_BASE}gemma4_text.maml"+    const val GEMMA_TEXT_SHA256 =+        "f9043d69180c209ac57db30179bbca75342991a8a2fa6899916cff05cc155620"++    /** The two embedding tables, gathered on the host. */+    const val GEMMA_EMBED_FILE = "gemma4_embed.maml"+    const val GEMMA_EMBED_URL = "${MIRROR_BASE}gemma4_embed.maml"+    const val GEMMA_EMBED_SHA256 =+        "b1ca4f34c3f2a05a71cb231e8b1e3795267b2550b87dd51d49ea15f84c0ef90a"++    /** The BPE table: 262144 pieces, 514906 merges, byte fallback. */+    const val GEMMA_TOKENIZER_FILE = "gemma4_tokenizer.spm1"+    const val GEMMA_TOKENIZER_URL = "${MIRROR_BASE}gemma4_tokenizer.spm1"+    const val GEMMA_TOKENIZER_SHA256 =+        "bfb34775a267c98b4062edbd91848865fdf05583b9df3a49e6eab7a0ee251383"++    /**+     * The vision tower: 16 layers at int4, with the patch and output projections left at fp16.+     *+     * Optional, and deliberately not in the same download as the decoder. It is 93 MB on top of+     * 2.8 GB, a device that never sends a picture never needs it, and the assistant answers text+     * perfectly well without it - see `Gemma4Engine.canSeeImages`.+     */+    const val GEMMA_VISION_FILE = "gemma4_vision.maml"+    const val GEMMA_VISION_URL = "${MIRROR_BASE}gemma4_vision.maml"+    const val GEMMA_VISION_SHA256 =+        "4c53c0a8383f2ea99f8beed50bd5eac203565436313d0c2dd77b389ea1cf38e3" -    // Mirror download URL.-    const val GEMMA_URL = "${MIRROR_BASE}gemma-4-E2B-it.litertlm"+    /**+     * The audio tower: a 12-layer conformer at int4, with the three end projections, the two+     * subsampling convolutions, the twelve depthwise convolutions and the twelve+     * relative-position tables all left at fp16.+     *+     * Optional on the same terms as the vision tower. 166 MB, and a device that never sends a+     * clip never needs it.+     */+    const val GEMMA_AUDIO_FILE = "gemma4_audio.maml"+    const val GEMMA_AUDIO_URL = "${MIRROR_BASE}gemma4_audio.maml"+    const val GEMMA_AUDIO_SHA256 =+        "be3ac4f968835fa257291f0845be642750f71e63e197a6e199ad5210316cb4f2" -    // SHA-256 integrity check (verified against the file uploaded to the mirror).-    const val GEMMA_SHA256 = "181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c"+    val GEMMA_TEXT =+        ModelDownloadItem(GEMMA_TEXT_URL, GEMMA_TEXT_FILE, "Model", GEMMA_TEXT_SHA256)+    val GEMMA_EMBED =+        ModelDownloadItem(GEMMA_EMBED_URL, GEMMA_EMBED_FILE, "Embeddings", GEMMA_EMBED_SHA256)+    val GEMMA_TOKENIZER = ModelDownloadItem(+        GEMMA_TOKENIZER_URL,+        GEMMA_TOKENIZER_FILE,+        "Tokenizer",+        GEMMA_TOKENIZER_SHA256,+    )+    val GEMMA_VISION =+        ModelDownloadItem(GEMMA_VISION_URL, GEMMA_VISION_FILE, "Vision", GEMMA_VISION_SHA256)+    val GEMMA_AUDIO =+        ModelDownloadItem(GEMMA_AUDIO_URL, GEMMA_AUDIO_FILE, "Audio", GEMMA_AUDIO_SHA256) -    val GEMMA = ModelDownloadItem(GEMMA_URL, GEMMA_FILE, "Model", GEMMA_SHA256)+    /**+     * Everything downloaded on OpenAssistant first launch.+     *+     * Smallest first, so a user on a slow connection sees progress early and so the two large+     * files are the ones a resume is most likely to land in the middle of. The two encoders go+     * after the tokenizer and before the two large ones: together they are 259 MB, they are what+     * make the assistant able to answer about a photograph or a recording, and a resume that+     * stalls in the decoder should not leave them unfetched.+     */+    val INITIAL = listOf(GEMMA_TOKENIZER, GEMMA_VISION, GEMMA_AUDIO, GEMMA_TEXT, GEMMA_EMBED) -    /** Everything downloaded on OpenAssistant first launch. */-    val INITIAL = listOf(GEMMA)+    /**+     * Files an earlier build downloaded and this one does not use.+     *+     * Deleted on startup rather than left to rot: the litertlm bundle alone was several+     * gigabytes, and a user upgrading would otherwise carry both copies forever.+     */+    val OBSOLETE = listOf(+        "gemma4-2b.litertlm",+        "gemma-4-E2B-it.litertlm",+        "gemma4.litertlm",+        "gemma4-4b.litertlm",+    ) }  /** A single model file fetched from the self-hosted mirror, with optional SHA-256. */
library/map/build.gradle.kts
diff --git a/library/map/build.gradle.kts b/library/map/build.gradle.ktsindex 43cec3ea9c..a171420816 100644--- a/library/map/build.gradle.kts+++ b/library/map/build.gradle.kts@@ -17,10 +17,19 @@ androidComponents { dependencies {     implementation(libs.androidx.compose.foundation) -    // 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.+    // For androidx.lifecycle.compose.LocalLifecycleOwner, which drives the frame loop's+    // ON_START/ON_STOP reconciliation. Scoped to this module rather than the convention+    // plugin: one consumer does not justify reconfiguring every module.+    implementation(libs.androidx.lifecycle.runtime.compose)++    // The renderer's HTTP transport, and now also ConnectivityMonitor (package+    // com.vayunmathur.library.util), which drives live online/offline into the renderer.+    // 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.+    //+    // Deliberately not :library — that would drag Room, DataStore, Navigation 3 and+    // :sdk:games onto this module's compile classpath for one object.     implementation(project(":library:network"))      // Own GeoPoint/GeoBounds – no spatialk exposure for non-maplibre apps.@@ -47,7 +56,7 @@ dependencies {  // The Vulkan vector-tile renderer: `library/map/src/main/rust`, on ash. //-// arm64 only, which is what the five consumer apps build+// arm64 only, which is what the seven 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. //
library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.ktindex b7285309b7..44dd3e7056 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt@@ -3,9 +3,11 @@ package com.vayunmathur.library.map import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable+import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.listSaver+import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.geometry.Offset@@ -63,11 +65,18 @@ class CameraState(initial: CameraPosition = CameraPosition()) {         return log2(dim / Mercator.TILE_SIZE).coerceAtLeast(0.0)     } -    /** Current projection, or null before the viewport has been measured. */-    val projection: Projection?-        get() = viewportDp?.let { vp ->+    /**+     * Current projection, or null before the viewport has been measured.+     *+     * [derivedStateOf], not a plain getter: [MapMarker] reads this once per marker per frame+     * during a pan, and the previous getter allocated a fresh [Projection] on every read.+     * With photos' cluster count that is real GC pressure.+     */+    val projection: Projection? by derivedStateOf {+        viewportDp?.let { vp ->             Projection(position.target, position.zoom, vp.width, vp.height, labelQueryProvider)         }+    }      /** Suspends until the viewport is measured, then returns the projection. */     suspend fun awaitProjection(): Projection =@@ -196,7 +205,28 @@ private fun anchoredZoom(  private fun lerp(start: Double, end: Double, t: Double): Double = start + (end - start) * t -/** Remembers a [CameraState] seeded with [initial]. */+/**+ * Saves the camera across configuration change and process death.+ *+ * Only `(lon, lat, zoom)`: [CameraState.viewportDp] is re-measured by the next layout pass+ * and [CameraState.labelQueryProvider] is re-registered by the surface, so persisting either+ * would restore a value that is immediately overwritten — and a stale viewport would produce+ * a wrong projection for one frame.+ */+private val CameraStateSaver = listSaver<CameraState, Double>(+    save = {+        listOf(it.position.target.longitude, it.position.target.latitude, it.position.zoom)+    },+    restore = { CameraState(CameraPosition(GeoPoint(it[0], it[1]), it[2])) },+)++/**+ * Remembers a [CameraState] seeded with [initial], surviving rotation and process death.+ *+ * [initial] applies only on first composition; a restored camera wins over it. Hosts that+ * refit the camera from a `LaunchedEffect` — `taxi` and `fooddelivery` do — overwrite the+ * restored position anyway, so restoration is inert for them.+ */ @Composable fun rememberCameraState(initial: CameraPosition = CameraPosition()): CameraState =-    remember { CameraState(initial) }+    rememberSaveable(saver = CameraStateSaver) { CameraState(initial) }
library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.ktnew file mode 100644index 0000000000..ffec8b8f03--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt@@ -0,0 +1,53 @@+package com.vayunmathur.library.map++/**+ * Which optional map layers to draw. Both are off by default.+ *+ * Every `.mamaps` archive already carries POI and transit data — the tiler has emitted both+ * for some time — but nothing drew either, so every archive paid storage, bandwidth and+ * decode cost for bytes that were discarded. Turning them on is opt-in rather than opt-out+ * because most consumers (findfamily, photos, weather, taxi, fooddelivery) show a map as a+ * backdrop for their own pins, and neither layer helps that: POI icons compete with the pin,+ * and rail lines are noise outside a transit app. `maps` opts into transit, driven by its+ * own layers toggle; `mapcompare` can drive both.+ *+ * # What turning one on costs+ *+ * Unlike the light/dark switch, this is not free. Both layers are gated at **tessellation**+ * time precisely so that leaving them off costs nothing — with [poi] off no label is shaped+ * and no collision candidate is built for any resident tile. The price is that flipping+ * either one invalidates the meshes already on the GPU, so the renderer re-tessellates the+ * resident tiles from the archive it already holds. No tile is refetched and none is+ * evicted; the existing meshes keep drawing until their replacements land, so the map does+ * not blank. Expect a brief burst of worker activity, not a reload.+ *+ * Setting the same values again is a no-op, so it is safe to pass a freshly-constructed+ * instance on every recomposition.+ */+data class LayerOptions(+    /**+     * Points of interest: an icon plus a wrapped label per feature, at z17 and deeper.+     *+     * Matches the reference basemap's `pois` layer — the same 36 kinds, the same sprite+     * sheet, the same six-way colour split by kind, and the same left/right anchor flip at+     * the screen edge. Density is governed by the archive, which drops each kind below its+     * own minimum zoom, so this stays empty at world zoom whatever the flag says.+     */+    val poi: Boolean = false,+    /**+     * Rail transit lines, coloured per route.+     *+     * Non-bus routes only. Each line takes the operator's own `colour=` tag from OSM, so+     * these are brand colours and are deliberately **not** shifted by the dark palette —+     * a line that is red on the network map stays red on a dark basemap.+     */+    val transit: Boolean = false,+) {+    companion object {+        /** The default: basemap only. */+        val None = LayerOptions()++        /** Both optional layers on. */+        val All = LayerOptions(poi = true, transit = true)+    }+}
library/map/src/main/java/com/vayunmathur/library/map/MapMarker.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapMarker.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapMarker.ktnew file mode 100644index 0000000000..9e02e4b56d--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapMarker.kt@@ -0,0 +1,109 @@+package com.vayunmathur.library.map++import androidx.compose.foundation.layout.LayoutScopeMarker+import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.ui.Modifier+import androidx.compose.ui.layout.Layout+import androidx.compose.ui.unit.Density+import kotlin.math.roundToInt++/** Which part of a marker sits on its geographic position. */+enum class MarkerAnchor {+    /** The marker's centre. What a circular pin or a cluster chip wants. */+    Center,++    /** The middle of the marker's bottom edge. What a teardrop pin wants. */+    BottomCenter,+}++/**+ * Receiver for [VectorMap]'s `content`, giving overlays a way to position themselves+ * geographically instead of each host re-deriving screen coordinates.+ *+ * Four apps had independently reimplemented "put this Compose thing at this lat/lon", three+ * of them with the same `offset(x - size/2, y - size/2)` arithmetic and one with a literal+ * `DpOffset(35.dp, 35.dp)` for a 70 dp avatar. [MapMarker] is that, once.+ */+@Stable+@LayoutScopeMarker+class MapScope internal constructor(private val cameraState: CameraState) {++    /**+     * The live projection, or null before the viewport is measured.+     *+     * Exposed because `findfamily`'s geofence circles are drawn in a `Canvas` and genuinely+     * need to project arbitrary points, not just anchor a composable. One caller does not+     * justify inventing a geo-aware draw scope, so it gets the projection directly — but+     * read it *inside* the draw lambda, not in composition, for the same reason [MapMarker]+     * reads it during placement.+     *+     * Nullable on purpose. It was previously common for hosts to write `projection!!`, which+     * is a live crash in the frames before the viewport is measured.+     */+    val projection: Projection?+        get() = cameraState.projection++    /**+     * Places [content] at [position] on the map.+     *+     * ## The projection is read during *placement*+     *+     * This is the one non-obvious correctness requirement here, and nothing enforces it, so:+     * `screenLocationFromPosition` is called inside the `layout {}` placement lambda. Never+     * hoist it into composition or into the measure block.+     *+     * Reading it in composition would make the camera a composition dependency, so every+     * marker's composition scope would invalidate on every frame of a pan — with a dense+     * cluster set that is strictly worse than the hand-rolled per-frame re-projection this+     * replaces. Reading it during placement makes the camera a *placement* dependency, so+     * Compose re-runs placement alone and skips both recomposition and measurement. It is+     * the same distinction as `Modifier.offset(x, y)` versus `Modifier.offset { }`.+     *+     * The symptom of getting this wrong is a frame-rate regression while panning, not a+     * failure, so it will not show up in a test.+     *+     * Measurement always happens; only placement is skipped when there is no projection yet+     * or the marker is wholly outside the viewport. Skipping measurement instead would make+     * the marker's size a function of the camera, which would reintroduce the per-frame+     * measure pass being avoided.+     */+    @Composable+    fun MapMarker(+        position: GeoPoint,+        modifier: Modifier = Modifier,+        anchor: MarkerAnchor = MarkerAnchor.Center,+        content: @Composable () -> Unit,+    ) {+        Layout(content = content, modifier = modifier) { measurables, constraints ->+            // Loosened: a marker is sized by its content, not stretched to the map.+            val childConstraints = constraints.copy(minWidth = 0, minHeight = 0)+            val placeables = measurables.map { it.measure(childConstraints) }+            val width = placeables.maxOfOrNull { it.width } ?: 0+            val height = placeables.maxOfOrNull { it.height } ?: 0++            // MeasureScope is a Density; PlacementScope is not, so capture it here.+            val density: Density = this+            // The map fills its parent, so the incoming maxima are the viewport in px and+            // this node sits at the parent's top-left — which makes the projected offset+            // directly usable as a placement offset.+            val viewportWidth = constraints.maxWidth+            val viewportHeight = constraints.maxHeight++            layout(width, height) {+                val projected = projection?.screenLocationFromPosition(position) ?: return@layout+                val originX = with(density) { projected.x.toPx() }.roundToInt()+                val originY = with(density) { projected.y.toPx() }.roundToInt()+                val x = originX - width / 2+                val y = when (anchor) {+                    MarkerAnchor.Center -> originY - height / 2+                    MarkerAnchor.BottomCenter -> originY - height+                }+                val offscreen = x + width < 0 || y + height < 0 ||+                    x > viewportWidth || y > viewportHeight+                if (offscreen) return@layout+                placeables.forEach { it.place(x, y) }+            }+        }+    }+}
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex 080e7f520b..11883a2733 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -81,6 +81,21 @@ internal object MapNative {      */     external fun setPalette(handle: Long, dark: Boolean, muted: Boolean) +    /**+     * Turn the optional layers (POI, transit) on or off.+     *+     * Not free, unlike [setPalette]. Both layers are gated at tessellation time so that+     * leaving them off costs nothing, which means changing either invalidates every mesh+     * already on the GPU. The native side bumps a generation counter; the render loop then+     * sees the resident tiles are stale and re-tessellates them on the existing worker+     * pool, reading the archive it already has. Nothing is refetched or evicted, and the+     * old meshes keep drawing until the new ones land.+     *+     * A call that changes nothing does nothing, so this is safe to drive from a+     * `LaunchedEffect` that may re-run for unrelated reasons.+     */+    external fun setLayers(handle: Long, poi: Boolean, transit: 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.
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 ba1499433a..ead2ae4a9f 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@@ -37,4 +37,9 @@ data class OrnamentOptions( data class MapOptions(     val gestureOptions: GestureOptions = GestureOptions(),     val ornamentOptions: OrnamentOptions = OrnamentOptions(),+    /**+     * Which optional layers (POI, transit) to draw. Both off by default — see+     * [LayerOptions] for why, and for what turning one on costs.+     */+    val layerOptions: LayerOptions = LayerOptions(), )
library/map/src/main/java/com/vayunmathur/library/map/MapRenderState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapRenderState.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapRenderState.ktnew file mode 100644index 0000000000..ae4732e3fc--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapRenderState.kt@@ -0,0 +1,46 @@+package com.vayunmathur.library.map++/**+ * Whether this map surface is actually drawing.+ *+ * Exists because both failure paths used to be silent: a `Log.e` and a flat background+ * rectangle, with nothing the host could react to. The *state* lives here; the rendered+ * message does not. `:library:map` has no resources and deliberately no material3, so a+ * themed, translated message belongs in `:library:ui` — see `MapUnavailableMessage` there,+ * which takes plain parameters rather than a [MapRenderState] so `:library:ui` never has to+ * depend on this module.+ *+ * ## Not exhaustive+ *+ * This covers the two failures the surface can observe at creation time. A renderer that+ * creates successfully and then stops drawing — device lost, swapchain loss, a driver that+ * accepts every command and presents nothing — is still [Rendering] as far as this is+ * concerned, and still a black map. Detecting that would need a liveness signal out of the+ * native side, which does not exist.+ */+sealed interface MapRenderState {+    /** No surface yet, or one created and not yet reported. The normal first state. */+    data object Initialising : MapRenderState++    /** A native renderer exists and the frame loop is driving it. */+    data object Rendering : MapRenderState++    /** The renderer could not be brought up. [reason] says which of the two ways. */+    data class Unavailable(val reason: Reason) : MapRenderState++    /** Why the renderer is not up. Both correspond to a real failure site in the surface. */+    enum class Reason {+        /**+         * `libmap_renderer.so` did not load, so there is no renderer to create. Typically an+         * ABI the build did not produce — this module is arm64-only unless+         * `-PemulatorAbi=x86_64` was passed.+         */+        RendererLibraryMissing,++        /**+         * The library loaded but `MapNative.create` returned 0: Vulkan failed to initialise,+         * or the archive could not be opened. Details are in logcat under `MapRenderer`.+         */+        RendererStartFailed,+    }+}
library/map/src/main/java/com/vayunmathur/library/map/Mercator.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Mercator.kt b/library/map/src/main/java/com/vayunmathur/library/map/Mercator.ktindex dc4f4bc63a..be4f76bddb 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/Mercator.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/Mercator.kt@@ -7,24 +7,24 @@ import kotlin.math.pow import kotlin.math.sin import kotlin.math.sinh -/** A point in Web-Mercator world pixels (logical, 256 px/tile, known-good grid). */+/** A point in Web-Mercator world pixels (logical, 512 px/tile). */ internal data class WorldPx(val x: Double, val y: Double)  /**- * Standard Web Mercator with a 256-logical-px tile grid, matching the Rust+ * Standard Web Mercator on a 512-logical-px tile grid, matching the Rust  * renderer's `TILE_SIZE`. All values are in density-independent ("logical")  * pixels so callers can work in `Dp` and only convert to device pixels when  * drawing. The projection is internally consistent with the tile rendering  * (both use this object), so overlays pin exactly to the basemap regardless  * of device density.  *- * MapLibre parity (ground scale at the same zoom float) comes from a +1 zoom- * offset applied at the camera boundary, NOT from a 512 tile: a 512 TILE_SIZE- * was tried and reverted (task 1, magenta verdict — label quads invisible,- * roads cut at seams) while 256 renders both clean.+ * 512 is MapLibre's convention and the one the vector archives are authored on.+ * This was 256 while the renderer compensated with a +1 zoom offset at the camera+ * boundary, which meant this object and the basemap it was supposed to agree with+ * were a factor of two apart.  */ internal object Mercator {-    const val TILE_SIZE = 256.0+    const val TILE_SIZE = 512.0      /** Total map width/height in logical px at [zoom]. */     fun worldSize(zoom: Double): Double = TILE_SIZE * 2.0.pow(zoom)
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex bf8157ffd2..254707a37b 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size@@ -36,14 +37,14 @@ import kotlin.math.roundToInt  *  * ## 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.+ * Fills, lines and casings, in light and dark, with pan, pinch, double-tap and quick zoom,+ * plus optional POI and transit layers and a native pick for tile-baked place labels. 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.+ * If Vulkan fails to initialise the map shows its background colour rather than crashing,+ * and everything that failed is in logcat under `MapRenderer`. Hosts that want to say so can+ * pass [fallback]; `:library:ui` has a themed message for it. 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.@@ -51,8 +52,17 @@ import kotlin.math.roundToInt  *   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.+ * @param onFrame called after each presented frame.+ *+ *   Kept for `library/map/src/androidTest/.../BasemapScreenshotTest.kt`, which counts frames+ *   to prove the renderer presented anything at all — the only way to observe that, since+ *   Vulkan needs a real GPU. It used to *also* fire from a `LaunchedEffect` on the camera,+ *   so that `photos` could re-project overlays on a pan that drew no new tiles; [MapMarker]+ *   makes that unnecessary and nothing else wanted the second signal, so this now means+ *   what its name says and nothing more.+ * @param fallback drawn over the surface when the renderer could not be brought up, so a+ *   failure is not a silent flat rectangle. Defaults to drawing nothing, which is the old+ *   behaviour. `:library:ui` has a themed, translated message for this.  */ @Composable fun VectorMap(@@ -73,15 +83,15 @@ fun VectorMap(     onMapClickWithScreen: ((MapClick) -> Unit)? = null,     onFrame: () -> Unit = {},     archivePath: String? = null,-    content: @Composable () -> Unit = {},+    fallback: @Composable (MapRenderState.Unavailable) -> Unit = {},+    content: @Composable MapScope.() -> 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()-    }+    // Remembered and @Stable so the content lambda gets the same receiver across+    // recompositions. A fresh receiver every time would make large content subtrees —+    // `maps`' MapLayers is one — permanently unskippable.+    val mapScope = remember(cameraState) { MapScope(cameraState) }      Box(         modifier@@ -101,16 +111,18 @@ fun VectorMap(             cameraState = cameraState,             darkBasemap = darkBasemap,             muted = style == MapStyle.Muted,+            layerOptions = options.layerOptions,             archivePath = archivePath,             modifier = Modifier.fillMaxSize(),             onFrame = onFrame,+            fallback = fallback,         )          if (imageOverlay != null) {             GeoreferencedOverlay(imageOverlay, cameraState)         } -        content()+        mapScope.content()     } } 
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex 0cfea9ced8..0cc447b334 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -2,8 +2,6 @@ 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@@ -11,13 +9,20 @@ import android.view.TextureView import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.DpRect import androidx.compose.ui.viewinterop.AndroidView+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.library.map.PlacedLabel+import com.vayunmathur.library.util.ConnectivityMonitor import java.io.File  /**@@ -33,7 +38,7 @@ import java.io.File  * 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+ * never navigated away from and back. Seven consumer apps' navigation is, so the  * known-good configuration wins over the cheaper one. The cost is one extra composite  * per frame.  *@@ -47,9 +52,11 @@ internal fun VulkanMapSurface(     cameraState: CameraState,     darkBasemap: Boolean,     muted: Boolean,+    layerOptions: LayerOptions = LayerOptions(),     archivePath: String? = null,     modifier: Modifier = Modifier,     onFrame: () -> Unit = {},+    fallback: @Composable (MapRenderState.Unavailable) -> Unit = {}, ) {     val context = LocalContext.current     val density = LocalDensity.current.density@@ -68,10 +75,55 @@ internal fun VulkanMapSurface(      DisposableEffect(host) { onDispose { host.dispose() } } +    // Stop driving Vulkan while the host is not visible. ON_START/ON_STOP rather than+    // resume/pause because a STARTED-but-not-RESUMED app — split-screen, PiP — is on screen+    // and must keep drawing.+    //+    // This stops *rendering* only. The Rust side's in-flight tile fetches are not paused,+    // and that is where the data cost actually is, so backgrounding does not fully quiesce+    // the map.+    val lifecycleOwner = LocalLifecycleOwner.current+    DisposableEffect(lifecycleOwner, host) {+        val observer = LifecycleEventObserver { _, event ->+            when (event) {+                Lifecycle.Event.ON_START -> host.onStarted()+                Lifecycle.Event.ON_STOP -> host.onStopped()+                else -> Unit+            }+        }+        lifecycleOwner.lifecycle.addObserver(observer)+        onDispose {+            lifecycleOwner.lifecycle.removeObserver(observer)+            host.onStopped()+        }+    }+     // 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) } +    // Unlike the palette, this one is not free: the optional layers are gated at+    // tessellation time, so a change re-tessellates the resident set. `setLayers` ignores+    // a call that changes nothing, which is what makes driving it from an effect safe.+    LaunchedEffect(layerOptions, host) { host.setLayers(layerOptions) }++    // Live connectivity, replacing a single sample taken in onSurfaceTextureAvailable.+    // Collected here rather than inside the host so every MapNative call stays on the+    // composition dispatcher, like setPalette and setLayers.+    //+    // Two deliberate behaviour changes from the probe this replaces. ConnectivityMonitor+    // requires NET_CAPABILITY_VALIDATED, which the probe did not — an improvement for a tile+    // fetcher, since a captive portal handing back HTML for a byte range is worse than+    // knowing you are offline. And it reports false where there is no ConnectivityManager,+    // where the probe optimistically returned true; that only arises under unit/Robolectric,+    // where the effect is to pin the map to cache.+    LaunchedEffect(host) {+        // Seeded synchronously so the first value is not spuriously false. This also+        // lazily starts the monitor.+        host.setOnline(ConnectivityMonitor.isOnline(context))+        ConnectivityMonitor.isOnline.collect { host.setOnline(it) }+    }+     AndroidView(         factory = {             TextureView(context).apply {@@ -83,6 +135,11 @@ internal fun VulkanMapSurface(         },         modifier = modifier,     )++    // Over the TextureView rather than instead of it: the listener that reports the failure+    // only runs once the view is attached, so removing the view would remove the thing that+    // produces the state.+    (host.renderState as? MapRenderState.Unavailable)?.let { fallback(it) } }  /**@@ -105,10 +162,42 @@ private class MapSurfaceHost(     private var surface: Surface? = null     private var frameCallback: Choreographer.FrameCallback? = null +    /**+     * Written only from the main-thread [TextureView.SurfaceTextureListener] callbacks, so+     * the `mutableStateOf` needs no synchronisation.+     */+    var renderState: MapRenderState by mutableStateOf(MapRenderState.Initialising)+        private set++    /**+     * Whether the host is at least STARTED. Owned here rather than split across a+     * `pause()`/`resume()` pair so there is exactly one writer per input and one reconciler+     * ([syncFrameLoop]) deciding whether the callback should be posted. The orderings that+     * pair gets wrong — backgrounded before the texture arrives, texture destroyed while+     * stopped, ON_START before the handle exists — all collapse into "recompute the+     * predicate" here.+     */+    private var started = false+     /** Remembered so a surface created after the theme was set still starts in it. */     private var dark = false     private var muted = false +    /**+     * Remembered for the same reason as [dark]: `MapNative.create` deliberately takes no+     * layer arguments, so a surface created after the host chose its layers has to be told+     * about them before its first frame — otherwise the first resident set is tessellated+     * without them and immediately thrown away.+     */+    private var layers = LayerOptions()++    /**+     * Remembered for the same reason as [layers]. Previously this was sampled exactly once,+     * inside `onSurfaceTextureAvailable`, so going offline mid-session left the renderer+     * retrying and coming back left it pinned to cache.+     */+    private var online = true+     /**      * 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@@ -123,6 +212,7 @@ private class MapSurfaceHost(         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")+                renderState = MapRenderState.Unavailable(MapRenderState.Reason.RendererLibraryMissing)                 return             }             val created = Surface(texture)@@ -132,10 +222,15 @@ private class MapSurfaceHost(                 Log.e(TAG, "the Vulkan renderer failed to start; see MapRenderer in logcat")                 created.release()                 surface = null+                renderState = MapRenderState.Unavailable(MapRenderState.Reason.RendererStartFailed)                 return             }-            MapNative.setOnline(handle, isOnline())-            startFrameLoop()+            MapNative.setOnline(handle, online)+            // Before the first frame, so the very first resident set is tessellated with+            // the layers the host asked for instead of being built and then invalidated.+            MapNative.setLayers(handle, layers.poi, layers.transit)+            renderState = MapRenderState.Rendering+            syncFrameLoop()         }          override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) {@@ -152,34 +247,55 @@ private class MapSurfaceHost(         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()+    private fun syncFrameLoop() {+        val shouldRun = started && handle != 0L+        if (shouldRun) {+            if (frameCallback != null) return+            val callback = object : Choreographer.FrameCallback {+                override fun doFrame(frameTimeNanos: Long) {+                    if (handle == 0L) {+                        if (frameCallback === this) frameCallback = null+                        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()+                    }+                    // Re-post only while still the installed callback: teardown() and+                    // onStopped() null this out, and a callback already dispatched for this+                    // frame cannot be un-posted by removeFrameCallback.+                    if (frameCallback === this) Choreographer.getInstance().postFrameCallback(this)                 }-                Choreographer.getInstance().postFrameCallback(this)             }+            frameCallback = callback+            Choreographer.getInstance().postFrameCallback(callback)+        } else {+            frameCallback?.let { Choreographer.getInstance().removeFrameCallback(it) }+            frameCallback = null         }-        frameCallback = callback-        Choreographer.getInstance().postFrameCallback(callback)+    }++    fun onStarted() {+        started = true+        syncFrameLoop()+    }++    fun onStopped() {+        started = false+        syncFrameLoop()     }      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) {@@ -188,6 +304,11 @@ private class MapSurfaceHost(         }         surface?.release()         surface = null+        // Back to Initialising, not sticky-Unavailable: the surface is gone, and a+        // TextureView that is recreated (navigation, backgrounding) gets a fresh attempt.+        renderState = MapRenderState.Initialising+        // handle is now 0, so this is what removes the callback.+        syncFrameLoop()     }      fun dispose() = teardown()@@ -228,14 +349,14 @@ private class MapSurfaceHost(         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)+    fun setLayers(options: LayerOptions) {+        this.layers = options+        if (handle != 0L) MapNative.setLayers(handle, options.poi, options.transit)+    }++    fun setOnline(online: Boolean) {+        this.online = online+        if (handle != 0L) MapNative.setOnline(handle, online)     }      private companion object {
library/map/src/main/rust/Cargo.toml
diff --git a/library/map/src/main/rust/Cargo.toml b/library/map/src/main/rust/Cargo.tomlindex 99202ebf58..c25e756551 100644--- a/library/map/src/main/rust/Cargo.toml+++ b/library/map/src/main/rust/Cargo.toml@@ -45,6 +45,12 @@ tilecodec = { path = "../../../../tilecodec/src/main/rust" } # stack, so pmtiles range requests keep `library:network`'s reduced CA bundle. jni_http = { path = "../../../../jni-http/src/main/rust" } ab_glyph = "0.2.32"+# The POI sprite sheet is a PNG, and nothing else in this crate can decode one. Already in+# the workspace lock file, so this promotes an existing transitive crate to a direct+# dependency rather than adding to the tree. Decoding at first use ships the 28 KB+# compressed sheet instead of the 466 KB of raw RGBA a `build.rs` decode would bake into+# the `.so` — the same trade the fonts make with `ab_glyph`.+png = "0.18"  # `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
library/map/src/main/rust/assets/fonts/NotoSans-Italic.ttf
diff --git a/library/map/src/main/assets/fonts/NotoSans-Italic.ttf b/library/map/src/main/rust/assets/fonts/NotoSans-Italic.ttfsimilarity index 100%rename from library/map/src/main/assets/fonts/NotoSans-Italic.ttfrename to library/map/src/main/rust/assets/fonts/NotoSans-Italic.ttf
library/map/src/main/rust/assets/fonts/NotoSans-Medium.ttf
diff --git a/library/map/src/main/assets/fonts/NotoSans-Medium.ttf b/library/map/src/main/rust/assets/fonts/NotoSans-Medium.ttfsimilarity index 100%rename from library/map/src/main/assets/fonts/NotoSans-Medium.ttfrename to library/map/src/main/rust/assets/fonts/NotoSans-Medium.ttf
library/map/src/main/rust/assets/fonts/NotoSans-Regular.ttf
diff --git a/library/map/src/main/assets/fonts/NotoSans-Regular.ttf b/library/map/src/main/rust/assets/fonts/NotoSans-Regular.ttfsimilarity index 100%rename from library/map/src/main/assets/fonts/NotoSans-Regular.ttfrename to library/map/src/main/rust/assets/fonts/NotoSans-Regular.ttf
library/map/src/main/rust/assets/sprites/sprites.json
diff --git a/library/map/src/main/assets/sprites/sprites.json b/library/map/src/main/rust/assets/sprites/sprites.jsonsimilarity index 100%rename from library/map/src/main/assets/sprites/sprites.jsonrename to library/map/src/main/rust/assets/sprites/sprites.json
library/map/src/main/rust/assets/sprites/sprites.png
diff --git a/library/map/src/main/assets/sprites/sprites.png b/library/map/src/main/rust/assets/sprites/sprites.pngsimilarity index 100%rename from library/map/src/main/assets/sprites/sprites.pngrename to library/map/src/main/rust/assets/sprites/sprites.png
library/map/src/main/rust/assets/sprites/[email protected]
diff --git a/library/map/src/main/assets/sprites/[email protected] b/library/map/src/main/rust/assets/sprites/[email protected]similarity index 100%rename from library/map/src/main/assets/sprites/[email protected]rename to library/map/src/main/rust/assets/sprites/[email protected]
library/map/src/main/rust/assets/sprites/[email protected]
diff --git a/library/map/src/main/assets/sprites/[email protected] b/library/map/src/main/rust/assets/sprites/[email protected]similarity index 100%rename from library/map/src/main/assets/sprites/[email protected]rename to library/map/src/main/rust/assets/sprites/[email protected]
library/map/src/main/rust/examples/place_probe.rs
diff --git a/library/map/src/main/rust/examples/place_probe.rs b/library/map/src/main/rust/examples/place_probe.rsindex 8979aa4985..2304d1d325 100644--- a/library/map/src/main/rust/examples/place_probe.rs+++ b/library/map/src/main/rust/examples/place_probe.rs@@ -103,7 +103,14 @@ fn main() {                 }                 let id = placement::candidate_id(tile.z, tile.x, tile.y, index, label_idx);                 let rect = placement::screen_rect(label.anchor, tile_clip, extent, text_px, label.total_advance, 24.0);-                candidates.push(placement::Candidate { id, rank: label.rank, pop: label.pop, rect });+                candidates.push(placement::Candidate {+                    id,+                    rank: label.rank,+                    pop: label.pop,+                    rect,+                    // Places have no `text-variable-anchor`, so there is no second box.+                    alternate: None,+                });                 // Resolve the display name via anchor -> point feature coords.                 let cx = (label.anchor.0 * tile_extent).round() as i16;                 let cy = (label.anchor.1 * tile_extent).round() as i16;@@ -137,7 +144,7 @@ fn main() {         println!("entered   rank {r}: {} candidates", entered[r]);     } -    let accepted: HashSet<u64> = placement::place(&candidates).into_iter().collect();+    let accepted: HashSet<u64> = placement::place(&candidates).into_iter().map(|(id, _)| id).collect();     println!("placed    {} / {} candidates", accepted.len(), candidates.len());     let mut placed_rank: HashMap<u8, usize> = HashMap::new();     for c in &candidates {@@ -150,7 +157,7 @@ fn main() {     }      // Acceptance order for blocker attribution: re-run place to get order.-    let order = placement::place(&candidates);+    let order: Vec<u64> = placement::place(&candidates).into_iter().map(|(id, _)| id).collect();     let pos: HashMap<u64, usize> = order.iter().enumerate().map(|(i, id)| (*id, i)).collect();     // For each culled candidate, the earliest-accepted overlapping box.     let mut by_id: HashMap<u64, &placement::Candidate> = HashMap::new();
library/map/src/main/rust/examples/places_probe.rs
diff --git a/library/map/src/main/rust/examples/places_probe.rs b/library/map/src/main/rust/examples/places_probe.rsindex b75ccbe6c7..396817ccd0 100644--- a/library/map/src/main/rust/examples/places_probe.rs+++ b/library/map/src/main/rust/examples/places_probe.rs@@ -199,7 +199,15 @@ fn main() {             let text_px = layer.text_size.at(z as f64);             if text_px > 0.0 {                 let (mut v, mut idx) = (Vec::new(), Vec::new());-                map_renderer::tile::symbol::emit_label(label, text_px, 256.0, &mut v, &mut idx);+                map_renderer::tile::symbol::emit_label(+                    label,+                    map_renderer::style::Anchor::Center,+                    (0.0, 0.0),+                    text_px,+                    256.0,+                    &mut v,+                    &mut idx,+                );                 let xs: Vec<f32> =                     v.chunks(4).map(|c| c[0]).collect();                 let (lo, hi) = (@@ -231,9 +239,20 @@ fn main() {      // Shape a synthetic label to isolate emit from tile data (placement bypass).     let (shaped, total) =-        map_renderer::tess::text::shape(&atlas, glyph::Weight::Regular, "San Francisco");+        map_renderer::tess::text::shape(&atlas, glyph::Weight::Regular, "San Francisco", false);     let (mut v, mut idx) = (Vec::new(), Vec::new());-    map_renderer::tess::text::emit(&atlas, glyph::Weight::Regular, &shaped, total, (0.5, 0.5), 14.0, 256.0, false, &mut v, &mut idx);+    map_renderer::tess::text::emit(+        &atlas,+        glyph::Weight::Regular,+        &[map_renderer::tess::text::ShapedLine { glyphs: shaped.clone(), advance: total }],+        (0.5, 0.5),+        map_renderer::style::Anchor::Center,+        (0.0, 0.0),+        14.0,+        256.0,+        &mut v,+        &mut idx,+    );     println!(         "synthetic 'San Francisco' @14px/256px: {} glyphs -> {} verts, {} idx",         shaped.len(),@@ -263,6 +282,9 @@ fn main() {                     parts_offset: 0,                     part_count: 1,                     transit_color: 0,+                    transit_ordinal: 0,+                    transit_lanes: 0,+                    transit_taper: 0,                 }],                 parts: vec![Part { coord_start: 0, point_count: 1, winding: WINDING_OUTER }],                 coords: vec![(2048, 2048)],@@ -279,7 +301,15 @@ fn main() {             let layer = &layers[label.layer_index];             let text_px = layer.text_size.at(6.0);             let (mut v, mut idx) = (Vec::new(), Vec::new());-            map_renderer::tile::symbol::emit_label(label, text_px, 256.0, &mut v, &mut idx);+            map_renderer::tile::symbol::emit_label(+                    label,+                    map_renderer::style::Anchor::Center,+                    (0.0, 0.0),+                    text_px,+                    256.0,+                    &mut v,+                    &mut idx,+                );             let (mut x0, mut x1, mut y0, mut y1) =                 (f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY);             for c in v.chunks(4) {
library/map/src/main/rust/examples/pmtiles_roads_probe.rs
diff --git a/library/map/src/main/rust/examples/pmtiles_roads_probe.rs b/library/map/src/main/rust/examples/pmtiles_roads_probe.rsnew file mode 100644index 0000000000..9f8d56b46e--- /dev/null+++ b/library/map/src/main/rust/examples/pmtiles_roads_probe.rs@@ -0,0 +1,87 @@+//! The `roads` counterpart of [`roads_probe`] for the vendored PMTiles basemap.+//!+//! ```text+//! cargo run --offline -p map_renderer --example pmtiles_roads_probe -- 6 10 24+//! ```+//!+//! Same question, other side of the comparator: which `kind`s does the reference+//! archive carry at a zoom where ours looks fragmented? HTTP is shelled to `curl`,+//! as `probe_archive` does, so the crate keeps no HTTP dependency.++use std::process::Command;+use tilecodec::mvt::Tile;+use tilecodec::proto::{err, Result};+use tilecodec::stream::{RangeReader, StreamArchive};++const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";++struct CurlReader;++impl RangeReader for CurlReader {+    fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+        let range = format!("{}-{}", offset, offset + length as u64 - 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()));+        }+        Ok(out.stdout)+    }+}++fn show(value: Option<&tilecodec::mvt::Value>) -> String {+    use tilecodec::mvt::Value;+    match value {+        Some(Value::String(s)) => s.clone(),+        Some(other) => format!("{other:?}"),+        None => "-".to_string(),+    }+}++fn main() {+    let args: Vec<String> = std::env::args().collect();+    if args.len() < 4 {+        eprintln!("usage: pmtiles_roads_probe Z X Y");+        std::process::exit(2);+    }+    let z: u8 = args[1].parse().expect("z");+    let x: u32 = args[2].parse().expect("x");+    let y: u32 = args[3].parse().expect("y");++    let mut archive = StreamArchive::open(CurlReader).expect("open archive");+    let Some(bytes) = archive.tile(z, x, y).expect("read tile") else {+        println!("{z}/{x}/{y} is absent");+        return;+    };+    let tile = Tile::decode(&bytes).expect("decode mvt");+    let Some(layer) = tile.layers.iter().find(|l| l.name == "roads") else {+        println!("{z}/{x}/{y} has no roads layer");+        return;+    };++    let mut totals: std::collections::BTreeMap<(String, String), (u32, f64)> = Default::default();+    for feature in &layer.features {+        let kind = show(feature.get("kind"));+        let detail = show(feature.get("kind_detail"));+        let mut length = 0.0f64;+        if let Some(lines) = tilecodec::mvt::decode_lines(&feature.geometry) {+            for line in lines {+                for pair in line.windows(2) {+                    let dx = (pair[1].0 - pair[0].0) as f64;+                    let dy = (pair[1].1 - pair[0].1) as f64;+                    length += (dx * dx + dy * dy).sqrt();+                }+            }+        }+        let entry = totals.entry((kind, detail)).or_insert((0, 0.0));+        entry.0 += 1;+        entry.1 += length;+    }++    println!("{z}/{x}/{y} extent {} — roads by (kind, kind_detail):", layer.extent);+    for ((kind, detail), (count, length)) in totals {+        println!("  {kind:<14} {detail:<16} {count:>6} features  {length:>12.0} units");+    }+}
library/map/src/main/rust/examples/roads_probe.rs
diff --git a/library/map/src/main/rust/examples/roads_probe.rs b/library/map/src/main/rust/examples/roads_probe.rsindex cf22f0f11d..a31c3aa8d3 100644--- a/library/map/src/main/rust/examples/roads_probe.rs+++ b/library/map/src/main/rust/examples/roads_probe.rs@@ -25,6 +25,7 @@ fn main() {     let reader = FileRangeReader::open(&path).expect("open archive");     let mut archive = MamapsArchive::open(reader).expect("parse archive");     println!("archive z{}..{}", archive.header.min_zoom, archive.header.max_zoom);+    let schema = archive.dictionary.clone();      let Some(body) = archive.tile(z, x, y).expect("read tile") else {         println!("{z}/{x}/{y} is absent");@@ -34,7 +35,6 @@ fn main() {         println!("{z}/{x}/{y} has no roads layer");         return;     };-    let schema = dict::schema();      // (kind, detail) -> (feature count, total tile-local length)     let mut totals: std::collections::BTreeMap<(String, String), (u32, f64)> = Default::default();@@ -47,8 +47,7 @@ fn main() {         };         let mut length = 0.0f64;         for part in layer.parts_of(feature) {-            let points = layer.points(part);-            for pair in points.windows(2) {+            for pair in layer.points(part).windows(2) {                 let dx = (pair[1].0 - pair[0].0) as f64;                 let dy = (pair[1].1 - pair[0].1) as f64;                 length += (dx * dx + dy * dy).sqrt();
library/map/src/main/rust/shaders/line.frag
diff --git a/library/map/src/main/rust/shaders/line.frag b/library/map/src/main/rust/shaders/line.fragindex c6e55446c1..920895f00e 100644--- a/library/map/src/main/rust/shaders/line.frag+++ b/library/map/src/main/rust/shaders/line.frag@@ -1,49 +1,63 @@ #version 450--// Line fragment, with the dash pattern.+// Line fragment: edge coverage, then the dash pattern.+//+// `outEdgePx` is a signed pixel distance from the band's centreline, and `misc.y` says+// whether this pass has to antialias the edge itself. Under MSAA it does not: the+// rasteriser already resolves partial coverage, and a second coverage term on top fades+// a diagonal road twice - at z6 a 2.9px highway crossing at an angle kept one pixel of+// strength against three for the near-vertical stretches of the same road. Without MSAA+// the box filter is the only thing standing between a diagonal road and a staircase, so+// it stays for that case.+//+// The sub-pixel fade is separate and always applies: `line.vert` widens anything thinner+// than MIN_HALF_WIDTH_PX so the rasteriser can hit it, and the alpha here gives that width+// back. MSAA cannot do this - the geometry really is a pixel wide by then. // // `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+// 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 = 1) in float inEdgePx; layout(location = 0) out vec4 outColor;- layout(push_constant) uniform Push {     mat4 tileToClip;     vec4 color;     vec4 line;+    // x: tile span in px, y: 1 when the pass is single-sampled and this shader owns+    // edge antialiasing, 0 when MSAA is resolving it.     vec4 misc; } push; +// Mirrors `style::paint::MIN_HALF_WIDTH_PX`; must match `line.vert`.+const float MIN_HALF_WIDTH_PX = 0.5;+ void main() {-    float halfWidthPx = push.line.x;+    float wantHalfPx = push.line.x;+    float halfWidthPx = max(wantHalfPx, MIN_HALF_WIDTH_PX);+    // Hand back the width the vertex shader added to make the quad rasterisable, so+    // a 0.3px road draws as a faint pixel rather than a solid one.+    float coverage = clamp(wantHalfPx / halfWidthPx, 0.0, 1.0);+    // Box filter over the pixel, only when nothing else is doing it.+    float box = clamp(halfWidthPx - abs(inEdgePx) + 0.5, 0.0, 1.0);+    coverage *= mix(1.0, box, push.misc.y);+    if (coverage <= 0.0) discard;+     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;+    if (dashOff > 0.0) {+        float width = max(halfWidthPx * 2.0, 1.0);+        float on = dashOn * width;+        float off = dashOff * width;+        float period = on + off;+        if (period > 0.0 && mod(inDistancePx, period) > on) discard;     }--    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;+    outColor = vec4(push.color.rgb, push.color.a * coverage); }
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.vertindex 0213eaa8ad..d5926314c7 100644--- a/library/map/src/main/rust/shaders/line.vert+++ b/library/map/src/main/rust/shaders/line.vert@@ -1,28 +1,30 @@ #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+// 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)+//   offset = normal * (offsetMul * gapHalf + widthMul * halfWidth + lateral) // // `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+// `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`.-+//+// `lateral` shifts the whole band sideways, which is how transit routes sharing+// one track fan out into parallel coloured lines. It is a push constant for the+// same reason the width is: it is a screen measurement that ramps with zoom, and+// baking it into vertices would re-tessellate the layer on every zoom step. 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(location = 1) out float outEdgePx; layout(push_constant) uniform Push {     mat4 tileToClip;     vec4 color;@@ -30,17 +32,33 @@ layout(push_constant) uniform Push {     vec4 misc; } push; +// Mirrors `style::paint::MIN_HALF_WIDTH_PX`, which GLSL cannot include.+// `the_shader_floor_matches_the_style_constant` pins the two together.+const float MIN_HALF_WIDTH_PX = 0.5;+ void main() {-    float halfWidthPx = push.line.x;+    float wantHalfPx = push.line.x;     float gapHalfPx = push.line.y;     float tilePx = max(push.misc.x, 1.0);-+    float lateralPx = push.misc.z;+    // A quad thinner than a pixel falls between pixel centres and rasterises as+    // stipple, so give it a pixel of geometry to land on. The fragment shader takes+    // the difference back off as alpha, which is how a thin road fades instead of+    // snapping to full strength.+    float halfWidthPx = max(wantHalfPx, MIN_HALF_WIDTH_PX);     // 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;+    float offsetPx = inExtrude.x * gapHalfPx + inExtrude.y * halfWidthPx + lateralPx;+    // Where this band's centreline sits: 0 for a plain stroke, and+    // gapHalf + halfWidth out on the offset side for a casing band. The lateral+    // shift has to be here too, or `outEdgePx` is measured from the old centre and+    // `line.frag`'s box filter fades the whole line instead of just its edges.+    float centrePx = inExtrude.x * gapHalfPx + sign(inExtrude.x) * halfWidthPx + lateralPx;+    // Signed distance from that centre, which spans -halfWidth..+halfWidth across+    // every band and so interpolates one unit per screen pixel.+    outEdgePx = offsetPx - centrePx;     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/shaders/sprite.frag
diff --git a/library/map/src/main/rust/shaders/sprite.frag b/library/map/src/main/rust/shaders/sprite.fragnew file mode 100644index 0000000000..7123943990--- /dev/null+++ b/library/map/src/main/rust/shaders/sprite.frag@@ -0,0 +1,32 @@+#version 450+// Sprite fragment: a POI icon, sampled straight out of the RGBA sheet.+//+// Deliberately not `symbol.frag`. A glyph is a signed distance field that has to be+// thresholded, smoothed and haloed; an icon is already the picture. Sampling it through+// the SDF path would read its red channel as a distance and draw a smeared silhouette.+//+// Shares `symbol.vert` and the symbol pipeline layout verbatim — same vertex format, same+// push block, same descriptor set slot. Only the bound atlas and this shader differ.+layout(location = 0) in vec2 inUv;+layout(location = 0) out vec4 outColor;+layout(push_constant) uniform Push {+    mat4 tileToClip;+    // rgb is the layer's TEXT colour and is deliberately unused here: the reference style+    // sets no `icon-color`, so an icon draws in its own colours. Only `.a` is read, which+    // carries the layer's opacity ramp.+    vec4 color;+    vec4 line;+    vec4 misc;+} push;+layout(set = 0, binding = 0) uniform sampler2D atlas;+void main() {+    vec4 texel = texture(atlas, inUv);+    float alpha = texel.a * push.color.a;+    // A sprite sheet is mostly empty space between icons, and the pipeline has no depth+    // test, so discarding fully-transparent fragments is what keeps one icon's padding+    // from blending over the label beside it.+    if (alpha <= 0.001) discard;+    // The sheet stores straight (unpremultiplied) alpha and the pipeline blends+    // SRC_ALPHA / ONE_MINUS_SRC_ALPHA, so the colour must not be premultiplied here.+    outColor = vec4(texel.rgb, alpha);+}
library/map/src/main/rust/shaders/symbol.frag
diff --git a/library/map/src/main/rust/shaders/symbol.frag b/library/map/src/main/rust/shaders/symbol.fragindex da4cd61236..6e7fceb62e 100644--- a/library/map/src/main/rust/shaders/symbol.frag+++ b/library/map/src/main/rust/shaders/symbol.frag@@ -14,35 +14,29 @@ layout(location = 0) out vec4 outColor; layout(push_constant) uniform Push {     mat4 tileToClip;     vec4 color;-    // x: text size in px per em, y: halo width in px, z/w: atlas texel (1/W,1/H).+    // x: text size in device px per em, y: halo width in device px, z: SDF value+    // change across one em, w: unused.     vec4 line;     // x: tile span in px, yzw: halo color rgb.     vec4 misc; } push;- layout(set = 0, binding = 0) uniform sampler2D atlas; void main() {     // SDF is in `.r` by the upload contract (`glyph::expand_sdf_r8_to_rgba8`     // writes [v, v, v, v]; pinned by     // `the_rgba8_expansion_carries_sdf_in_every_channel`).     float dist = texture(atlas, inUv).r;-    // One-texel smoothing in SDF units: the atlas spread is 8px per cell side,-    // i.e. 8/64 = 0.125 of the 0..1 range, so a texel is ~1/(spread) of that.-    // fwidth would be ideal; constant 1-texel smoothing is the M1 approximation.-    float texel = max(push.line.z, push.line.w);-    float edge0 = 0.5 - texel;-    float edge1 = 0.5 + texel;-    float face = smoothstep(edge0, edge1, dist);--    // Halo: edge test dilated by halo px converted to SDF units. Halo width is-    // in screen px; one em is push.line.x px and spans 8 SDF-px of spread per-    // side... M1 approximates: haloSdf = haloPx / textPx * 0.5 (half the em-    // range maps the full SDF range). Both line.x (text size) and line.y-    // (halo width) are device px now that the density fix scales the size —-    // the ratio is unit-clean either way.-    float haloSdf = push.line.y / max(push.line.x, 1.0) * 0.5;-    float halo = smoothstep(0.5 - haloSdf - texel, 0.5 - haloSdf + texel, dist);-+    // Smooth across exactly one screen pixel of the distance field. `fwidth` is how+    // much `dist` changes between neighbouring fragments, so this tracks the label's+    // size for free. The previous constant band was one atlas texel of the 0..1 SDF+    // range - about 0.001 - which is far narrower than a pixel at any label size and+    // so drew hard, aliased edges.+    float aa = max(fwidth(dist), 1e-4);+    float face = smoothstep(0.5 - aa, 0.5 + aa, dist);+    // Halo: the edge test dilated outwards. A halo of `haloPx` screen px is+    // `haloPx / textPx` ems, and `line.z` is how much the SDF moves across an em.+    float haloSdf = push.line.y / max(push.line.x, 1.0) * push.line.z;+    float halo = smoothstep(0.5 - haloSdf - aa, 0.5 - haloSdf + aa, dist);     vec3 haloRgb = push.misc.yzw;     vec3 rgb = mix(haloRgb, push.color.rgb, face);     float alpha = max(halo * push.color.a, face * push.color.a);
library/map/src/main/rust/src/bridge.rs
diff --git a/library/map/src/main/rust/src/bridge.rs b/library/map/src/main/rust/src/bridge.rsindex f97ecb0e89..f4df0aa589 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -15,7 +15,7 @@ //! critical path, and no JNI in the hot loop.  use crate::camera::Camera;-use crate::style::{self, Layer, Palette};+use crate::style::{self, Layer, LayerToggles, Palette, SharedToggles}; use crate::tile::cache::{RangeCache, DEFAULT_MAX_BYTES}; use crate::tile::geometry::{self, TileMesh}; use crate::tile::select::{self, TileId};@@ -110,6 +110,10 @@ struct MapHandle {     /// 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,+    /// Which optional layers (POI, transit) are on, plus the generation that identifies+    /// them. Shared with the tile workers, which gate tessellation on it and stamp every+    /// mesh they build with the generation they read.+    toggles: Arc<SharedToggles>,     /// 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.@@ -196,6 +200,10 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(     let (finished_tx, finished_rx) = std::sync::mpsc::channel::<(u64, TileResult)>();      let zoom_range = Arc::new(ZoomRange::unknown());+    // Both optional layers start off: the five existing consumers never asked for POI+    // icons or transit lines, and defaulting them on would make every one of them pay+    // for shaping labels it does not draw.+    let toggles = Arc::new(SharedToggles::new(LayerToggles::default()));     // One `Receiver` shared by every worker, so whichever is free takes the next tile.     let queue = Arc::new(Mutex::new(wanted_rx));     match normalize_local_archive_path(&archive_path) {@@ -209,6 +217,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(                     finished_tx.clone(),                     online.clone(),                     zoom_range.clone(),+                    toggles.clone(),                 );             }         }@@ -223,6 +232,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(                     finished_tx.clone(),                     online.clone(),                     zoom_range.clone(),+                    toggles.clone(),                 );             }         }@@ -235,6 +245,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(                     queue.clone(),                     finished_tx.clone(),                     zoom_range.clone(),+                    toggles.clone(),                 );             }         }@@ -249,6 +260,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>(         absent: HashSet::new(),         online,         palette: Palette::new(dark != 0, muted != 0),+        toggles,         zoom_range,         frames: 0,         density: 1.0,@@ -264,6 +276,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( /// 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.+#[allow(clippy::too_many_arguments)] fn spawn_worker(     index: usize,     archive_url: String,@@ -272,6 +285,7 @@ fn spawn_worker(     finished: Sender<(u64, TileResult)>,     online: Arc<OnlineFlag>,     zoom_range: Arc<ZoomRange>,+    toggles: Arc<SharedToggles>, ) {     let started = std::thread::Builder::new()         .name(format!("map-tiles-{index}"))@@ -313,14 +327,20 @@ fn spawn_worker(                 let Ok(tile) = next else { return };                 let key = tile.key(); +                // Read per tile, not once per worker: a toggle change has to reach the+                // very next tile built, and both halves come from one atomic load so the+                // stamp can never describe different flags than the mesh was built with.+                let (enabled, generation) = toggles.get();                 let result = match archive.tile(tile.z, tile.x, tile.y) {-                    Ok(Some(body)) => TileResult::Ready(geometry::build(+                    Ok(Some(body)) => TileResult::Ready(geometry::build_toggled(                         &body,                         layers,                         tile.z,                         tile.x,                         tile.y,                         rings_validated,+                        enabled,+                        generation,                     )),                     Ok(None) => TileResult::Absent,                     Err(e) => {@@ -346,6 +366,7 @@ fn spawn_file_worker(     queue: Arc<Mutex<Receiver<TileId>>>,     finished: Sender<(u64, TileResult)>,     zoom_range: Arc<ZoomRange>,+    toggles: Arc<SharedToggles>, ) {     let Some(path) = path else {         // Empty archive_path == remote fallback already handled by caller printing a log,@@ -379,9 +400,11 @@ fn spawn_file_worker(                 };                 let Ok(tile) = next else { return };                 let key = tile.key();+                let (enabled, generation) = toggles.get();                 let result = match archive.tile(tile.z, tile.x, tile.y) {-                    Ok(Some(body)) => TileResult::Ready(geometry::build(-                        &body, layers, tile.z, tile.x, tile.y, rings_validated,+                    Ok(Some(body)) => TileResult::Ready(geometry::build_toggled(+                        &body, layers, tile.z, tile.x, tile.y, rings_validated, enabled,+                        generation,                     )),                     Ok(None) => TileResult::Absent,                     Err(e) => {@@ -454,19 +477,17 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( ) -> jboolean {     let Some(map) = handle_mut(handle) else { return 0 }; -    // MapLibre parity lives HERE, once, as a +1 zoom offset — not in TILE_SIZE.-    // A 512 TILE_SIZE was tried and reverted (task 1, magenta verdict: label-    // quads invisible, roads cut at seams) while 256 tile-local math renders-    // both clean. Viewing the world one level deeper doubles ground-feature-    // size on screen — matching MapLibre's 512-equivalent display at the same-    // zoom float — while tile addressing (floor of the OFFSET zoom, so z+1-    // tiles), tessellation, emission and the clip matrix all stay on the-    // known-good 256 grid. Sizes, halo and gating are screen-space ramps-    // evaluated at the offset zoom, so labels keep their MapLibre-matched px.+    // The camera zoom crosses the boundary untouched. MapLibre parity is+    // `camera::TILE_SIZE` being 512, the convention the archives are authored on, so+    // tile addressing is the plain floor of this zoom and every style ramp is+    // evaluated at the zoom the authored `basemap.json` meant by it. This was+    // previously a 256 grid with a +1 offset applied here, which reached the same+    // ground scale but fetched z+1 tiles — four times as many as MapLibre for the+    // same screenful — and read every ramp one level deep.     let camera = Camera {         center_lon: center_lon as f64,         center_lat: center_lat as f64,-        zoom: zoom as f64 + 1.0,+        zoom: zoom as f64,         width_dp,         height_dp,         density,@@ -502,11 +523,18 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // 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();+    // A tile is "had" only if it was tessellated at the current toggle generation, so a+    // toggle change re-requests the resident set through this same loop rather than+    // needing a path of its own. The stale mesh keeps drawing until its replacement+    // arrives.+    let (_, generation) = map.toggles.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)+        if map.renderer.has_tile(key, generation)+            || map.absent.contains(&key)+            || !map.in_flight.insert(key)         {             continue;         }@@ -527,15 +555,16 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         // 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 - 1.0,+            "z{:.2} @{:.4},{:.4} vp {}x{}dp {}x{}px msaa {}x | 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,+            map.renderer.samples(),             tiles,             meshes,             draws,@@ -584,6 +613,33 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setPalette<'l>     } } +/// Turn the optional layers on or off.+///+/// Not free, unlike [`setPalette`](Java_com_vayunmathur_library_map_MapNative_setPalette):+/// POI and transit are gated at tessellation time so that leaving them off costs nothing,+/// which means turning one on invalidates every resident mesh. Bumping the generation is+/// all this does; the render loop notices the resident tiles are stale and re-requests+/// them through the existing worker pool, reading the archive it already has. Nothing is+/// refetched, nothing is evicted, and the old meshes keep drawing until the new ones land.+///+/// A call that changes nothing bumps nothing, because the host is expected to call this+/// from a Compose effect that may re-run for unrelated reasons.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setLayers<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    poi: jboolean,+    transit: jboolean,+) {+    if let Some(map) = handle_mut(handle) {+        let wanted = LayerToggles { poi: poi != 0, transit: transit != 0 };+        if map.toggles.set(wanted) {+            log_info(&format!("layers changed: poi={} transit={}", wanted.poi, wanted.transit));+        }+    }+}+ #[no_mangle] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setOnline<'l>(     _env: JNIEnv<'l>,
library/map/src/main/rust/src/camera.rs
diff --git a/library/map/src/main/rust/src/camera.rs b/library/map/src/main/rust/src/camera.rsindex c46fb12583..58c91f9f6c 100644--- a/library/map/src/main/rust/src/camera.rs+++ b/library/map/src/main/rust/src/camera.rs@@ -1,27 +1,27 @@ //! The camera: a snapshot from Kotlin to a per-tile clip-space matrix. //!-//! Web Mercator with a 256-logical-px tile grid (world = 256 * 2^zoom),-//! matching `:library:map`'s `Mercator.kt` — 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.+//! Web Mercator on a 512-logical-px tile grid (world = 512 * 2^zoom), matching+//! `:library:map`'s `Mercator.kt` — 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. //!-//! MapLibre parity (ground scale at the same zoom float) comes from a +1 zoom-//! offset applied once at the JNI boundary (`bridge`), NOT from a 512 tile:-//! tile-local math (tessellation, emission, the clip matrix) stays 256-based-//! and known-good, while the camera views the world one level deeper so-//! ground features render at MapLibre's 512-equivalent size. A 512 TILE_SIZE-//! was tried (task 1, P2) and reverted: positions aligned but label quads went-//! invisible and roads cut at tile seams — too much subtle tile-local fallout-//! for what should be an outer-scale change.+//! 512 is also what gives MapLibre parity: the vector archives are authored on+//! that convention, so at the same zoom float a tile covers the same ground and+//! renders at the same size. This used to be a 256 grid with a compensating +1+//! zoom offset applied at the JNI boundary, which produced the right ground scale+//! by a different route but had two costs: tile addressing took the floor of the+//! *offset* zoom, so a screenful fetched four times as many tiles as MapLibre+//! does, and every style ramp — widths, `text_size`, opacity and the `min_zoom`+//! layer gating — was evaluated one level away from the zoom the authored+//! `basemap.json` those values were transcribed from meant by it. //! //! Only the camera crosses JNI, once per frame. Everything per-tile is derived here. -/// Logical pixels across one tile: 256, the known-good tile-local grid.-/// World scale is 256 * 2^zoom. MapLibre parity is the bridge's +1 zoom-/// offset, not this constant: doubling here doubles tile-local assumptions-/// everywhere (task 1, magenta verdict) while an outer zoom offset scales the-/// final matrix only. Tile addressing (z/x/y) is floor(zoom) either way.-pub const TILE_SIZE: f64 = 256.0;+/// Logical pixels across one tile: 512, the convention the archives are authored on.+///+/// World scale is 512 * 2^zoom, which is MapLibre's, so tile addressing is the plain+/// floor of the camera zoom and every ramp is evaluated at the zoom the style means.+pub const TILE_SIZE: f64 = 512.0;  /// The camera as Kotlin measured it. #[derive(Clone, Copy, Debug)]@@ -142,12 +142,12 @@ mod tests {     }      #[test]-    fn the_world_is_256_dp_per_tile() {-        // Known-good tile-local grid: world = 256 * 2^zoom. MapLibre parity is-        // the bridge's +1 zoom offset, not this constant.-        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);+    fn the_world_is_512_dp_per_tile() {+        // MapLibre's convention, and the one the archives are authored on: tile+        // addressing is the plain floor of the camera zoom.+        assert_eq!(world_size(0.0), 512.0);+        assert_eq!(world_size(1.0), 1024.0);+        assert_eq!(world_size(14.0), 512.0 * 16384.0);     }      #[test]@@ -167,15 +167,15 @@ mod tests {     #[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);+        assert!((p.x - TILE_SIZE / 2.0).abs() < 1e-9);+        assert!((p.y - TILE_SIZE / 2.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);+        // 1024 Dp viewport, so tile 0/0's bottom-right corner lands at clip (0, 0).+        let camera = Camera { width_dp: 1024.0, height_dp: 1024.0, ..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}");@@ -184,8 +184,7 @@ mod tests {      /// Task-1 camera-scale parity: the viewport centre always maps to clip     /// origin through the shared matrix, whatever the tile grid. Pins the-    /// matrix half of the anchor contract at the 256 tile-local grid with the-    /// +1 parity offset applied to the camera zoom.+    /// matrix half of the anchor contract on the 512 grid.     #[test]     fn an_anchor_at_viewport_centre_projects_to_clip_origin() {         // z10 centred on SF: the SF tile-local centre must land at clip (0,0)@@ -225,9 +224,9 @@ mod tests {      #[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+        // At z0 with a 512 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 camera = Camera { width_dp: 512.0, height_dp: 512.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);@@ -253,7 +252,7 @@ mod tests {         // 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);+        assert!((camera.tile_span_dp(16) - 512.0 * 8.0).abs() < 1e-9);     }      #[test]
library/map/src/main/rust/src/style/mod.rs
diff --git a/library/map/src/main/rust/src/style/mod.rs b/library/map/src/main/rust/src/style/mod.rsindex 837483707c..14f5f5ffad 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -62,6 +62,106 @@ pub enum Variant {     Dark, } +/// An optional layer group the host app opts into at runtime.+///+/// A layer with no toggle is basemap and always drawn. The two that have one carry data+/// every archive already ships but which most consumers do not want: POI icons clutter a+/// map whose job is to show one pin, and transit lines are noise outside a transit app.+/// Defaulting them **off** is what makes the five existing consumers cost nothing.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Toggle {+    Poi,+    Transit,+}++/// Which optional layers are on. Both off by default.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]+pub struct LayerToggles {+    pub poi: bool,+    pub transit: bool,+}++impl LayerToggles {+    /// Is a layer carrying `toggle` drawn?+    ///+    /// `None` is basemap, and always yes — which is why this takes an `Option` rather+    /// than making every caller special-case the common layer.+    pub fn enabled(&self, toggle: Option<Toggle>) -> bool {+        match toggle {+            None => true,+            Some(Toggle::Poi) => self.poi,+            Some(Toggle::Transit) => self.transit,+        }+    }+}++/// The toggles plus a generation counter, in one atomic word, shared with the tile+/// workers.+///+/// Gating happens at **tessellation** time rather than at draw time, because that is+/// where the cost is: with POI off, no label is shaped and no placement candidate is+/// built for any resident tile. The price of gating there is that a toggle change+/// invalidates meshes, so every mesh records the generation it was built at and the+/// renderer re-requests anything stale. Re-tessellation goes through the existing worker+/// pool and reads the archive it already has, so nothing is refetched and nothing is+/// evicted — the same "re-decorate without reloading" shape as a palette switch, one step+/// heavier.+///+/// One word rather than three atomics so a worker's read is a consistent snapshot: a+/// mesh tagged with one generation but built from another's flags would either never be+/// refreshed or be refreshed forever.+#[derive(Debug)]+pub struct SharedToggles(std::sync::atomic::AtomicU32);++impl SharedToggles {+    /// Generations start at 1, so a mesh from a default-initialised 0 is always stale.+    pub fn new(toggles: LayerToggles) -> SharedToggles {+        SharedToggles(std::sync::atomic::AtomicU32::new(Self::pack(toggles, 1)))+    }++    fn pack(toggles: LayerToggles, generation: u32) -> u32 {+        (generation << 2) | (u32::from(toggles.poi) << 1) | u32::from(toggles.transit)+    }++    /// The current toggles and the generation they belong to.+    pub fn get(&self) -> (LayerToggles, u32) {+        let word = self.0.load(std::sync::atomic::Ordering::Acquire);+        (+            LayerToggles { poi: word & 0b10 != 0, transit: word & 0b01 != 0 },+            word >> 2,+        )+    }++    /// Set the toggles, bumping the generation. Returns `true` when anything changed.+    ///+    /// A no-op set must not bump: the host may call this on every recomposition, and a+    /// bump there would re-tessellate the whole resident set for nothing.+    pub fn set(&self, toggles: LayerToggles) -> bool {+        let (current, generation) = self.get();+        if current == toggles {+            return false;+        }+        self.0.store(+            Self::pack(toggles, generation.wrapping_add(1).max(1)),+            std::sync::atomic::Ordering::Release,+        );+        true+    }+}++/// Where a label sits relative to its anchor point.+///+/// Only the horizontal cases exist, because only they are used: place labels are centred+/// and the reference `pois` layer offers `["left", "right"]`. `Left` means the label's+/// left edge is at the anchor, so the text runs to the **right** of the point — which is+/// MapLibre's sense of the word and the opposite of the intuitive reading.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Anchor {+    Center,+    Left,+    Right,+}+ impl Variant {     pub fn from_dark(dark: bool) -> Variant {         if dark {@@ -166,6 +266,20 @@ pub struct Layer {     /// style draws road casings. Whether there is a gap *at all* is decided once, at     /// tessellation time, by [`gapped`](Self::gapped).     pub gap_width: Ramp,+    /// Distance between two adjacent parallel lines of one corridor, in Dp.+    ///+    /// Only `transit-rail` sets it. Screen-space rather than a ground distance, and constant+    /// across zoom: the fan widens in discrete jumps as [`lanes`](Self::lanes) steps up, which+    /// is what makes a colour visibly re-assign at a boundary instead of its neighbours merely+    /// closing in on it.+    pub spread: Ramp,+    /// How many parallel lanes a corridor draws at a given zoom, floored at read.+    ///+    /// The one thing a feature cannot carry: it is a property of the camera, not of the route.+    /// A feature carries its colour's ordinal and its corridor's colour count+    /// ([`tilecodec::mamaps::body::Feature::transit_ordinal`]) and+    /// [`Layer::lane_offset_px`] turns the three into a lateral offset per frame.+    pub lanes: Ramp,     /// Dash and gap lengths in line widths, as `line-dasharray` defines them.     pub dash: (f32, f32),     /// Halo color (ARGB), light and dark. The authored `text-halo-color` per layer;@@ -179,12 +293,49 @@ pub struct Layer {     /// Text size in px, as a zoom ramp. Zero/empty for non-symbol layers.     ///     /// The authored `text-size` is a *pixel* size at the camera zoom (unlike a road-    /// width in Dp it is not density-scaled — MapLibre sizes text in screen px).+    /// width in Dp it is not density-scaled - MapLibre sizes text in screen px, and+    /// the renderer applies density on the way to the shader because the tile span it+    /// is measured against is in device px).+    ///+    /// This is the arm for a place **below** [`Layer::rank_threshold`].     pub text_size: Ramp,+    /// Text size for a place **at or above** [`Layer::rank_threshold`], where the+    /// authored style gives a second arm.+    ///+    /// `places_country` and `places_locality` size their labels with a two-arm `case`+    /// on `population_rank`, and the gap is wide: at z10 a locality is 12px below the+    /// threshold and 20px above it. Collapsing that to a single ramp drew every small+    /// town at close to city size - and because a label's collision box follows its+    /// size, those towns then beat the cities they should have lost to.+    pub text_size_large: Option<Ramp>,+    /// The population rank at which [`Layer::text_size_large`] takes over, per zoom.+    ///+    /// Falls as the camera descends (13 at z2 down to 8 at z15): the closer in, the+    /// smaller a place may be and still be worth drawing large.+    pub rank_threshold: Option<Ramp>,     /// Uppercase the label (`text-transform: uppercase` in the authored style).     pub uppercase: bool,     /// Glyph weight: the authored `text-font` reduced to Regular/Medium.     pub medium: bool,+    /// Which optional layer group this belongs to, or `None` for always-on basemap.+    pub toggle: Option<Toggle>,+    /// Draw a sprite icon beside the label, named by the feature's `kind`.+    ///+    /// Only the POI layers set this. The reference style's `icon-image` is+    /// `match(kind, "station", "train_station", kind)`, which is a rename of one kind and+    /// otherwise the kind itself — so a boolean plus that one rule says all of it, and no+    /// per-layer icon name has to be authored.+    pub icon: bool,+    /// `text-offset` in ems, applied along the resolved anchor.+    pub text_offset: (f32, f32),+    /// `text-max-width` in ems, the target width line breaking aims for. Zero means no+    /// wrapping, which is what every place layer wants.+    pub text_max_width: f32,+    /// `text-variable-anchor`: the anchors to try, in order, before giving up.+    ///+    /// Empty means the label is centred and does not move, which is the place layers'+    /// behaviour and what MapLibre does with no variable anchor declared.+    pub variable_anchor: Vec<Anchor>,     pub min_zoom: u8,     pub max_zoom: u8,     /// The `style/basemap.json` layer this was transcribed from.@@ -259,6 +410,29 @@ impl Layer {         zoom >= self.min_zoom && zoom <= self.max_zoom     } +    /// This label's size in px at `zoom`, for a place of population rank `pop`.+    ///+    /// Picks between the two arms the authored style declares. A layer without a second+    /// arm answers from [`Layer::text_size`] whatever the rank, which is what every+    /// non-place symbol layer wants.+    pub fn text_size_for(&self, zoom: f64, pop: u16) -> f32 {+        match (&self.text_size_large, &self.rank_threshold) {+            (Some(large), Some(threshold)) if f32::from(pop) >= threshold.at(zoom) => {+                large.at(zoom)+            }+            _ => self.text_size.at(zoom),+        }+    }++    /// Whether any place could produce a visible label at `zoom`.+    ///+    /// The cheap per-layer gate before the per-label sizing: a layer whose *widest* arm+    /// has ramped to zero cannot draw anything, whatever ranks the tile holds.+    pub fn text_visible_at(&self, zoom: f64) -> bool {+        let large = self.text_size_large.as_ref().map_or(0.0, |ramp| ramp.at(zoom));+        self.text_size.at(zoom).max(large) > 0.0+    }+     /// A casing: two bands offset either side of the centreline.     ///     /// Read at tessellation time, so it cannot vary with zoom — one geometry has to serve every@@ -274,6 +448,41 @@ impl Layer {         Stroke { width_dp: self.width.at(zoom), gap_width_dp: self.gap_width.at(zoom) }     } +    /// How far sideways a transit feature's mesh shifts at `zoom`, in device pixels.+    ///+    /// `count` is the corridor's colour count and `ordinal` the colour's index within it, both+    /// straight off the feature; `taper` is how far into the lane this piece sits, over 255.+    ///+    /// Past the style's lane count the colours are squashed onto the lanes there are rather+    /// than the fan growing without bound. Squashing rather than wrapping is what keeps the map+    /// free of crossings at every zoom: the map is monotonic in `ordinal`, so two colours can+    /// come to share a lane but can never swap sides.+    ///+    /// It squashes from the **middle**. Ordinal zero takes lane zero and the last ordinal takes+    /// the last lane, so the outermost line on each side of a corridor keeps a lane to itself+    /// for as long as there is one to spare, and the doubling-up happens where it is least+    /// visible. Six colours over four lanes go `0,1,1,2,2,3` — one, two, two, one — where+    /// spacing them evenly would give `0,0,1,2,2,3` and crowd the two edges instead.+    pub fn lane_offset_px(+        &self,+        zoom: f64,+        density: f32,+        ordinal: u8,+        count: u8,+        taper: u8,+    ) -> f32 {+        let lanes = (self.lanes.at(zoom).floor() as i32).min(count as i32);+        if lanes < 2 {+            return 0.0;+        }+        // `lanes >= 2` implies `count >= 2`, so the divisor cannot be zero. The `+ steps` is+        // the round-to-nearest, which is what puts the wider buckets in the middle.+        let (span, steps) = (lanes - 1, count as i32 - 1);+        let lane = (2 * ordinal as i32 * span + steps) / (2 * steps);+        (2 * lane - (lanes - 1)) as f32 * self.spread.at(zoom) * density / 2.0+            * (taper as f32 / 255.0)+    }+     /// The fill opacity this layer draws at `zoom`, in 0..=1.     pub fn opacity_at(&self, zoom: f64) -> f32 {         self.opacity.at(zoom).clamp(0.0, 1.0)@@ -591,6 +800,78 @@ mod tests {         assert_eq!(count, ids.len(), "layer ids are used as identities");     } +    /// The lane arithmetic, at density 1 so a Dp is a pixel: `lanes` lanes of the constant+    /// 6 Dp spacing, centred on the track, so an even count straddles it and an odd one sits+    /// one line on it. The count comes from the style's zoom step, not from the feature.+    #[test]+    fn a_corridor_fans_out_centred_on_the_track_it_shares() {+        let rail = find("transit-rail");+        let of = |zoom: f64, ordinal: u8, count: u8| rail.lane_offset_px(zoom, 1.0, ordinal, count, 255);+        assert_eq!([of(9.0, 0, 2), of(9.0, 1, 2)], [-3.0, 3.0], "two lanes straddle it");+        assert_eq!([of(11.0, 0, 3), of(11.0, 1, 3), of(11.0, 2, 3)], [-6.0, 0.0, 6.0]);+        assert_eq!(+            [of(13.0, 0, 4), of(13.0, 1, 4), of(13.0, 2, 4), of(13.0, 3, 4)],+            [-9.0, -3.0, 3.0, 9.0],+        );+        // Past the zoom's lane count the ordinals squash, so a busy corridor shares lanes+        // rather than fanning off the street — from the middle, so the outermost line on each+        // side keeps a lane of its own.+        assert_eq!(of(9.0, 1, 4), of(9.0, 0, 4), "ordinals 0 and 1 of 4 share lane 0 of 2");+        assert_eq!(of(9.0, 3, 4), of(9.0, 2, 4), "and 2 and 3 share lane 1");+        assert!(of(9.0, 2, 4) > of(9.0, 1, 4), "without the two halves swapping");+        // A corridor of one has nothing to fan, and neither does a single-lane zoom.+        assert_eq!(of(13.0, 0, 1), 0.0);+        assert_eq!(of(8.0, 1, 4), 0.0);+    }++    /// Two groups of three merging, at a zoom that can draw four lanes: the outermost line on+    /// each side keeps a lane to itself and the four in the middle pair up, rather than the+    /// crowding landing on the two edges where it is most visible.+    #[test]+    fn a_corridor_past_its_lane_budget_doubles_up_in_the_middle() {+        let rail = find("transit-rail");+        let of = |ordinal: u8| rail.lane_offset_px(13.0, 1.0, ordinal, 6, 255);+        assert_eq!(+            [of(0), of(1), of(2), of(3), of(4), of(5)],+            [-9.0, -3.0, -3.0, 3.0, 3.0, 9.0],+            "one, two, two, one across the four lanes z13 draws",+        );+    }++    /// The property the whole lane-order pass rests on: within a corridor the offset never+    /// decreases as the ordinal rises, at any zoom and any colour count. Two lines can come+    /// to share a lane, but they can never cross.+    #[test]+    fn squashing_a_corridor_onto_fewer_lanes_never_reorders_it() {+        let rail = find("transit-rail");+        for count in 1u8..=12 {+            for step in 0..=40 {+                let zoom = 4.0 + f64::from(step) * 0.5;+                let offsets: Vec<f32> = (0..count)+                    .map(|ordinal| rail.lane_offset_px(zoom, 1.0, ordinal, count, 255))+                    .collect();+                assert!(+                    offsets.windows(2).all(|w| w[0] <= w[1]),+                    "count {count} at zoom {zoom}: {offsets:?}",+                );+                // And the fan always reaches its full width: the first and last ordinals take+                // the outermost lanes, which is what makes the squashing land in the middle.+                let (first, last) = (offsets[0], offsets[offsets.len() - 1]);+                assert_eq!(first, -last, "count {count} at zoom {zoom}: {offsets:?}");+            }+        }+    }++    /// The taper is a fraction of whatever the offset turns out to be, which is why it has to+    /// travel separately from the lane index.+    #[test]+    fn a_taper_scales_the_offset_it_eases_into() {+        

Diff truncated.