Modern Apps git

← Modern-Apps.git

map: expose basemap geometry; watch map gets real linework

Commit
4531e0199ff30940bc6159704bc521fc70df68ab
Author
Vayun Mathur <[email protected]>
When
2026-11-25 02:18 UTC (11 days ago)
Parents
18b4f73
library/map gains MapGeometry.query (Kotlin over one
new JNI entry): bbox tiles from the same TileSource the
renderer workers use, roads/path/water/buildings walked
from decoded bodies, <=25 tiles centre-first, <=512
features, E7 coords (~1cm), never throws, fresh
read-only mmap per query off the render path. Rust
geometry_query tests 6/6 + synthetic-archive integration
3/3.

WearMapRegion now queries the real archive: roads,
water, and buildings populate the watch snapshot;
degraded means source-UNAVAILABLE (an ocean region is a
complete empty map, not 'degraded'). Renderer unchanged
- it already draws these kinds.

Verified: library:map 99 tests + assemble + lint;
:maps full tests; WearMapRegionTest 13/13; wear goldens
9/9 + assemble. Pre-existing maps lint error unchanged.

Diff

library/map/src/main/java/com/vayunmathur/library/map/MapGeometry.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapGeometry.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapGeometry.ktnew file mode 100644index 0000000000..21b224d88f--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapGeometry.kt@@ -0,0 +1,180 @@+package com.vayunmathur.library.map++/**+ * Bounded Kotlin access to basemap geometry from the on-device `.mamaps`+ * archive — the geometry the Vulkan renderer otherwise keeps entirely+ * on the native side.+ *+ * Data comes from the archive's own decoded tile bodies, through the+ * same codec and tile selection the renderer uses (no second parser):+ * `roads` lines become [MapGeometryKind.ROAD]/[MapGeometryKind.PATH],+ * water features on the merged `landtype` layer become+ * [MapGeometryKind.WATER], and `buildings` polygons become+ * [MapGeometryKind.BUILDING]. Coordinates are plain lon/lat+ * ([GeoPoint]); quantization to a caller's grid (the wear snapshot's+ * 2 m) is the caller's step, at its own resolution.+ *+ * Performance discipline: a query is viewport-bounded (only tiles+ * covering [GeoBounds] are read, at the archive's deepest zoom capped+ * street-level, stepping out until the tile count fits), feature- and+ * point-capped on the native side ([MAX_FEATURES], plus a native point+ * budget that never cuts a feature mid-ring), and entirely off the+ * render path — it opens its own read-only archive view and never+ * touches a renderer handle. Call it from a background thread; it does+ * file I/O. Results arrive in wear priority order (roads, paths,+ * water, buildings), tiles centre-first.+ *+ * Honesty: when there is no readable archive (no path, no file, an+ * unparseable file, or the native library is absent) every requested+ * kind is reported in [MapGeometryResult.unsourcedKinds] and the+ * feature list is empty — callers must name those kinds degraded+ * rather than draw an empty map as if it were complete. When the+ * archive *was* read, a kind with no features genuinely has none in+ * the region (an ocean or desert bbox), and is not unsourced.+ */++/** A basemap geometry kind a [MapGeometry] query can return. */+enum class MapGeometryKind {+    ROAD,+    PATH,+    WATER,+    BUILDING,+}++/**+ * One extracted feature: a polyline, or one polygon ring/part when+ * [closed]. [kindClass] is the feature's class (a road's highway class+ * such as `residential`, else its kind name such as `lake`/`building`);+ * empty when the source feature carries neither.+ */+data class MapGeometryFeature(+    val kind: MapGeometryKind,+    val kindClass: String,+    val closed: Boolean,+    val points: List<GeoPoint>,+)++/**+ * The outcome of one [MapGeometry.query].+ *+ * [unsourcedKinds] is the set of requested kinds the query could not+ * source at all (archive unavailable). It is empty whenever the archive+ * was read — even for kinds that returned zero features, which is the+ * distinction between "no such features here" and "source unavailable".+ */+data class MapGeometryResult(+    val features: List<MapGeometryFeature> = emptyList(),+    val unsourcedKinds: Set<MapGeometryKind> = emptySet(),+    /** True when a native cap kept geometry back. */+    val truncated: Boolean = false,+    /** Tiles the archive held and the query decoded; 0 = nothing scanned. */+    val coveredTiles: Int = 0,+    /** Tiles covering the bbox at the chosen zoom. */+    val totalTiles: Int = 0,+) {+    fun featuresOf(kind: MapGeometryKind): List<MapGeometryFeature> =+        features.filter { it.kind == kind }+}++/** The geometry source: queries against one on-device archive path. */+object MapGeometry {+    /** Hard ceiling on features per query, whatever a caller asks for. */+    const val MAX_FEATURES = 512++    /** Default feature cap for a region-sized query. */+    const val DEFAULT_MAX_FEATURES = 256++    internal const val KIND_ROAD_BIT = 1+    internal const val KIND_PATH_BIT = 2+    internal const val KIND_WATER_BIT = 4+    internal const val KIND_BUILDING_BIT = 8++    internal fun bitOf(kind: MapGeometryKind): Int = when (kind) {+        MapGeometryKind.ROAD -> KIND_ROAD_BIT+        MapGeometryKind.PATH -> KIND_PATH_BIT+        MapGeometryKind.WATER -> KIND_WATER_BIT+        MapGeometryKind.BUILDING -> KIND_BUILDING_BIT+    }++    /**+     * Query [kinds] inside [bounds] from the archive at [archivePath].+     *+     * A null/blank path, an absent native library, or a native+     * UNAVAILABLE answer all yield an empty result with every requested+     * kind in [MapGeometryResult.unsourcedKinds]; this never throws.+     * Does file I/O: call from a background thread.+     */+    fun query(+        archivePath: String?,+        bounds: GeoBounds,+        kinds: Set<MapGeometryKind> = MapGeometryKind.entries.toSet(),+        maxFeatures: Int = DEFAULT_MAX_FEATURES,+    ): MapGeometryResult {+        if (archivePath.isNullOrBlank() || kinds.isEmpty() ||+            bounds.west >= bounds.east || bounds.south >= bounds.north+        ) {+            return MapGeometryResult(unsourcedKinds = kinds)+        }+        if (!MapNative.isAvailable) {+            return MapGeometryResult(unsourcedKinds = kinds)+        }+        val mask = kinds.fold(0) { acc, kind -> acc or bitOf(kind) }+        val rows = try {+            MapNative.queryGeometry(+                archivePath,+                bounds.west,+                bounds.south,+                bounds.east,+                bounds.north,+                mask,+                maxFeatures.coerceIn(1, MAX_FEATURES),+            )+        } catch (t: Throwable) {+            // The JNI boundary contract: a native failure is an+            // unsourced answer, never a crash in a background sync.+            return MapGeometryResult(unsourcedKinds = kinds)+        }+        return parseRows(rows, kinds)+    }++    /**+     * Parse the native wire rows (see `MapNative.queryGeometry`) into a+     * result. Pure, so host tests pin the shape without a device.+     * Malformed rows are skipped, never fatal; an UNAVAILABLE or+     * unrecognisable header marks every requested kind unsourced.+     */+    internal fun parseRows(rows: Array<String>?, requested: Set<MapGeometryKind>): MapGeometryResult {+        val header = rows?.firstOrNull()?.split('\u0001')+        if (header == null || header.firstOrNull() != "OK") {+            return MapGeometryResult(unsourcedKinds = requested)+        }+        val features = mutableListOf<MapGeometryFeature>()+        for (row in rows.drop(1)) {+            val fields = row.split('\u0001')+            if (fields.size < 4) continue+            val kind = try {+                MapGeometryKind.valueOf(fields[0])+            } catch (t: IllegalArgumentException) {+                continue+            }+            if (kind !in requested) continue+            val coords = fields[3].split(',').mapNotNull { it.toLongOrNull() }+            if (coords.size < 4 || coords.size % 2 != 0) continue+            val points = (coords.indices step 2).map { i ->+                GeoPoint(coords[i] / 1e7, coords[i + 1] / 1e7)+            }+            features += MapGeometryFeature(+                kind = kind,+                kindClass = fields[1],+                closed = fields[2] == "1",+                points = points,+            )+        }+        return MapGeometryResult(+            features = features,+            truncated = header.getOrNull(1) == "1",+            coveredTiles = header.getOrNull(2)?.toIntOrNull() ?: 0,+            totalTiles = header.getOrNull(3)?.toIntOrNull() ?: 0,+        )+    }+}
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 f695549c66..ebd9eea1c5 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@@ -251,6 +251,28 @@ internal object MapNative {         hasBearing: Boolean,     ) +    /**+     * Query basemap geometry in a bounding box from the on-device `.mamaps`+     * archive at [localPath] (see [MapGeometry] for the bounded Kotlin API+     * over this). Handle-free and off the render path by design: it opens+     * its own read-only archive view on the calling thread, so callers must+     * call it off the main thread and never from a frame.+     *+     * Returns `\u0001`-joined rows: row 0 is `OK␁<truncated 0|1>␁+     * <coveredTiles>␁<totalTiles>` or the single row `UNAVAILABLE` (no+     * readable archive); later rows are `<KIND>␁<class>␁<closed 0|1>␁+     * <lonE7,latE7,...>` for ROAD/PATH/WATER/BUILDING features.+     */+    external fun queryGeometry(+        localPath: String?,+        west: Double,+        south: Double,+        east: Double,+        north: Double,+        kindsMask: Int,+        maxFeatures: Int,+    ): Array<String>+     /** Take the puck away: no fix, or a host that stopped asking for one. */     external fun clearUserPuck(handle: Long) 
library/map/src/main/rust/src/bridge/geometry.rs
diff --git a/library/map/src/main/rust/src/bridge/geometry.rs b/library/map/src/main/rust/src/bridge/geometry.rsnew file mode 100644index 0000000000..217bcad4a0--- /dev/null+++ b/library/map/src/main/rust/src/bridge/geometry.rs@@ -0,0 +1,151 @@+//! Basemap geometry queries for Kotlin (see `tile::geometry_query`).+//!+//! One entry point, deliberately **not** handle-based: a geometry query+//! has no surface, no Vulkan and no frame, so it must not queue behind+//! (or block) the render thread. Each call opens its own read-only+//! archive view over the on-device `.mamaps` file — the same+//! `FileRangeReader` + overlay discovery the tile workers use, so a+//! pinned overlay segment is honoured exactly as the renderer honours+//! it — batch-fetches the bbox's tiles through the codec's existing+//! `tiles()` wave, extracts, and drops the view. The file mapping is+//! lazy and the leaf cache is per-call, so a query costs a prefix parse+//! plus the covering tiles' bodies and nothing else.+//!+//! # Wire shape+//!+//! An array of `\u{1}`-joined strings, the `pickLabels` convention:+//!+//! * row 0: `OK \u{1} <truncated 0|1> \u{1} <coveredTiles> \u{1} <totalTiles>`,+//!   or the single row `UNAVAILABLE` when there is no readable archive+//!   (no path, no file, an unparseable archive, or every covering tile+//!   failed to decode). UNAVAILABLE is the honest "source unavailable"+//!   answer; an `OK` with zero features is "scanned, nothing here".+//! * rows 1..: `<KIND> \u{1} <class> \u{1} <closed 0|1> \u{1}+//!   <lonE7,latE7,...>` with KIND one of ROAD/PATH/WATER/BUILDING.+//!   E7 integers keep the payload compact and exact at ~1 cm, far+//!   below the wear consumer's 2 m quantization grid.++use super::log::log;+use crate::tile::geometry_query::{+    query_geometry, GeometryQuery, KIND_BUILDING, KIND_PATH, KIND_ROAD, KIND_WATER,+};+use crate::tile::source::{discover, FileRangeReader};+use jni::objects::{JClass, JObject, JString};+use jni::sys::{jdouble, jint, jobjectArray};+use jni::{jni_str, EnvUnowned};+use std::sync::Arc;+use tilecodec::mamaps::read::{LeafCache, MamapsArchive};++fn kind_name(kind: u32) -> &'static str {+    match kind {+        KIND_ROAD => "ROAD",+        KIND_PATH => "PATH",+        KIND_WATER => "WATER",+        KIND_BUILDING => "BUILDING",+        _ => "BUILDING",+    }+}++fn rows_to_array<'l>(+    env: &mut jni::Env<'l>,+    rows: &[String],+) -> jni::errors::Result<jobjectArray> {+    let out = env.new_object_array(rows.len() as i32, jni_str!("java/lang/String"), JObject::null())?;+    for (i, row) in rows.iter().enumerate() {+        let Ok(js) = env.new_string(row) else { continue };+        let _ = env.set_object_array_element(&out, i, js);+    }+    Ok(out.into_raw())+}++/// Query basemap geometry in a bbox from the on-device archive at+/// `local_path`. See the module docs for the wire shape and bounds.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_queryGeometry<'l>(+    mut env: EnvUnowned<'l>,+    _class: JClass<'l>,+    local_path: JString<'l>,+    west: jdouble,+    south: jdouble,+    east: jdouble,+    north: jdouble,+    kinds_mask: jint,+    max_features: jint,+) -> jobjectArray {+    env.with_env(|env| -> jni::errors::Result<jobjectArray> {+        let unavailable = vec!["UNAVAILABLE".to_string()];+        let path: String = if local_path.is_null() {+            return rows_to_array(env, &unavailable);+        } else {+            match local_path.try_to_string(env) {+                Ok(s) if !s.is_empty() => s,+                _ => return rows_to_array(env, &unavailable),+            }+        };+        let path_ref = std::path::Path::new(&path);+        if !FileRangeReader::exists(path_ref) {+            return rows_to_array(env, &unavailable);+        }+        let query = GeometryQuery {+            west,+            south,+            east,+            north,+            kinds_mask: kinds_mask.max(0) as u32,+            max_features: max_features.max(0) as usize,+        };+        // Same source selection as the tile workers: a pinned overlay+        // serves patch-first, any refusal falls back to the base alone.+        let leaves = Arc::new(LeafCache::new());+        let result = if let Some(found) = discover(path_ref, Arc::clone(&leaves)) {+            query_geometry(&found.overlay, &query)+        } else {+            let reader = match FileRangeReader::open(path_ref) {+                Ok(r) => r,+                Err(e) => {+                    log(&format!("geometry query cannot open {path}: {e}"));+                    return rows_to_array(env, &unavailable);+                }+            };+            match MamapsArchive::open_with_cache(reader, leaves) {+                Ok(archive) => query_geometry(&archive, &query),+                Err(e) => {+                    log(&format!("geometry query cannot parse {path}: {e}"));+                    return rows_to_array(env, &unavailable);+                }+            }+        };+        // Nothing decoded and something failed: that is a broken+        // source, not an empty region. (Nothing decoded with no+        // failures is ordinary absent-tile ground — ocean — and stays+        // an honest OK with zero features.)+        if result.covered_tiles == 0 && result.failed_tiles > 0 {+            return rows_to_array(env, &unavailable);+        }+        let mut rows = Vec::with_capacity(result.features.len() + 1);+        rows.push(format!(+            "OK\u{1}{}\u{1}{}\u{1}{}",+            if result.truncated { 1 } else { 0 },+            result.covered_tiles,+            result.total_tiles,+        ));+        for f in &result.features {+            let mut coords = String::new();+            for (i, &(lon, lat)) in f.points.iter().enumerate() {+                if i > 0 {+                    coords.push(',');+                }+                coords.push_str(&format!("{},{}", (lon * 1e7).round() as i64, (lat * 1e7).round() as i64));+            }+            rows.push(format!(+                "{}\u{1}{}\u{1}{}\u{1}{}",+                kind_name(f.kind),+                f.class,+                if f.closed { 1 } else { 0 },+                coords,+            ));+        }+        rows_to_array(env, &rows)+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}
library/map/src/main/rust/src/bridge/mod.rs
diff --git a/library/map/src/main/rust/src/bridge/mod.rs b/library/map/src/main/rust/src/bridge/mod.rsindex 85f536ef44..aeb352ec13 100644--- a/library/map/src/main/rust/src/bridge/mod.rs+++ b/library/map/src/main/rust/src/bridge/mod.rs@@ -18,8 +18,13 @@ //! `render` drains. That is the split the plan asks for: the expensive half off the //! critical path, and no JNI in the hot loop. //!+//! One exception: `geometry`'s query entry takes no handle and opens its own+//! read-only archive view, so it runs on the caller's (background) thread and+//! never touches the render thread or a frame.+//! //! Split by domain; each module header names what it holds. mod frame;+mod geometry; mod handle; mod layers; mod lifecycle;
library/map/src/main/rust/src/tile/geometry_query.rs
diff --git a/library/map/src/main/rust/src/tile/geometry_query.rs b/library/map/src/main/rust/src/tile/geometry_query.rsnew file mode 100644index 0000000000..007e7df699--- /dev/null+++ b/library/map/src/main/rust/src/tile/geometry_query.rs@@ -0,0 +1,480 @@+//! Bounded basemap-geometry queries for Kotlin consumers (the watch snapshot).+//!+//! The Vulkan renderer decodes `.mamaps` bodies natively and, until now,+//! nothing crossed back to Kotlin except pixels and label picks — so a+//! Kotlin consumer that needs actual road/water/building linework (the+//! Maps wear snapshot) had to declare those kinds degraded. This module+//! is the missing read path. It is deliberately **not** a second planet+//! parser: it opens the archive through the same+//! [`tilecodec::mamaps::read::TileSource`] the tile workers serve from+//! (shared leaf cache, batch body fetch, overlay-aware), selects the+//! tiles covering a bounding box with the same slippy-map maths the+//! renderer uses, and walks the decoded [`Body`] layers the tessellator+//! walks — `roads` lines, water features on `landtype`, `buildings`+//! polygons. No tessellation, no Vulkan, no frame path: a query runs on+//! its own archive view, off the render thread, and can never contend+//! with a frame. At the deepest zoom it also reuses the workers' wash+//! underlay (the z13 parent's water stitched into a gated z14 body,+//! `geometry::wash_overzoom`), so water does not vanish at street zoom.+//!+//! # Bounds (the performance discipline)+//!+//! * **Viewport-bounded.** Only tiles intersecting the query bbox are+//!   fetched, at the archive's own deepest zoom capped at+//!   [`QUERY_ZOOM_CAP`] (street detail without z16+ tile fan-out), and+//!   the tile count is capped at [`MAX_TILES`] by stepping zoom out+//!   until the bbox fits — a whole-continent bbox degrades to coarse+//!   tiles rather than thousands of fetches.+//! * **Feature/point-capped.** At most `max_features` features and+//!   [`MAX_POINTS`] points cross back, in wear priority order+//!   (road, path, water, building — the order the watch snapshot itself+//!   keeps under its byte cap), tiles centre-first. A feature that would+//!   exceed the remaining point budget is skipped whole (never cut+//!   mid-ring, which would corrupt a polygon) and the result is flagged+//!   `truncated` so the caller can say so.+//! * **Quantized output.** Points cross as lon/lat degrees; the JNI+//!   layer re-encodes them as E7 integers, and the Kotlin side's wear+//!   consumer quantizes to its 2 m grid. At region scale the double+//!   round-trip is far below that grid.+//!+//! # Honesty+//!+//! A tile the archive does not hold is `covered == false` ground, not an+//! error: most of a coastal viewport is ocean the writer never stored.+//! [`GeometryResult::covered_tiles`] counts bodies actually decoded, so+//! a caller can tell "scanned, genuinely nothing here" (covered > 0,+//! no features) from "nothing was scanned" (covered == 0). A query over+//! a present archive whose every tile failed to decode reports those in+//! `failed_tiles`; the JNI layer turns covered==0 + failures into its+//! UNAVAILABLE answer rather than a fake empty map.++use super::select::TileId;+use tilecodec::mamaps::body::{Body, GEOM_LINE, GEOM_POLYGON};+use tilecodec::mamaps::dict::{self, LAYER_BUILDINGS, LAYER_LANDTYPE, LAYER_ROADS, NONE};+use tilecodec::mamaps::read::TileSource;++/// Kind bit: a drivable/walkable road line (`roads` layer, not a path).+pub const KIND_ROAD: u32 = 1 << 0;+/// Kind bit: a path (`roads` layer feature whose kind is `path`).+pub const KIND_PATH: u32 = 1 << 1;+/// Kind bit: water — a polygon (lake/ocean/…) or line (river/stream)+/// on the merged `landtype` layer whose kind the style paints as water.+pub const KIND_WATER: u32 = 1 << 2;+/// Kind bit: a building outline (`buildings` layer polygon).+pub const KIND_BUILDING: u32 = 1 << 3;+/// Every kind this query can return.+pub const KIND_ALL: u32 = KIND_ROAD | KIND_PATH | KIND_WATER | KIND_BUILDING;++/// Deepest zoom a geometry query reads, however deep the archive goes.+///+/// The wear region is ~1.2 km across; z15 tiles are ~1.2 km at the+/// equator, so this keeps a region to a handful of tiles while still+/// reading street-level bodies. The archive's own `max_zoom` wins when+/// it is shallower (the published planets stop at z14).+pub const QUERY_ZOOM_CAP: u8 = 15;++/// Most tiles one query fetches. The zoom steps out until the bbox+/// fits this, so the bound holds for any bbox a caller passes.+pub const MAX_TILES: usize = 25;++/// Most points one query returns, across every feature.+///+/// A dense z14/z15 city tile carries on the order of a few thousand+/// road/building points; this holds several such tiles while keeping+/// the JNI string payload in the tens of KB — the wear snapshot's own+/// cap is 48 KB after simplification, and this feeds it, it does not+/// replace it.+pub const MAX_POINTS: usize = 8192;++/// Hard ceiling on `max_features`, however much a caller asks for.+pub const MAX_FEATURES: usize = 512;++/// The `landtype` kinds the style paints as water — the same list the+/// terrain clip uses (`tile::geometry::terrain::WATER_KINDS`), matched+/// by name so an appended dictionary kind cannot silently drift ids.+const WATER_KINDS: [&str; 12] = [+    "ocean", "sea", "lake", "water", "river", "stream", "bay", "strait", "fjord", "reef", "canal",+    "dock",+];++/// `roads`-layer kinds that are not roads a watch should draw as one:+/// rail geometry belongs to the transit styling, and a ferry/aerialway+/// line is a route across water/air, not a street.+const NON_ROAD_KINDS: [&str; 3] = ["rail", "ferry", "aerialway"];++/// One extracted feature: a polyline or one polygon ring/part.+#[derive(Debug, Clone, PartialEq)]+pub struct GeometryFeature {+    /// One of the `KIND_*` bits, as a single value (not a mask).+    pub kind: u32,+    /// The feature's class: the road's `kind_detail` (motorway,+    /// residential, …) when it carries one, else its `kind` name+    /// (major_road, lake, building, …). Empty when the feature is+    /// kind-less.+    pub class: String,+    /// True for a polygon ring (wear fills it), false for a line.+    pub closed: bool,+    /// `(lon, lat)` degrees, in body order.+    pub points: Vec<(f64, f64)>,+}++/// The outcome of one query.+#[derive(Debug, Default, Clone, PartialEq)]+pub struct GeometryResult {+    pub features: Vec<GeometryFeature>,+    /// Tiles the archive held and this query decoded.+    pub covered_tiles: usize,+    /// Tiles covering the bbox at the chosen zoom.+    pub total_tiles: usize,+    /// Tiles whose decode failed (transport/corrupt), as opposed to+    /// tiles the archive simply does not hold.+    pub failed_tiles: usize,+    /// True when a cap (features, points or tile-zoom step-out) kept+    /// geometry back.+    pub truncated: bool,+}++/// A query: geographic bbox, kind mask, feature cap.+#[derive(Debug, Clone, Copy)]+pub struct GeometryQuery {+    pub west: f64,+    pub south: f64,+    pub east: f64,+    pub north: f64,+    pub kinds_mask: u32,+    pub max_features: usize,+}++fn kind_name(kind: u16) -> Option<&'static str> {+    if kind == NONE {+        return None;+    }+    dict::KINDS.get((kind - 1) as usize).copied()+}++fn detail_name(detail: u16) -> Option<&'static str> {+    if detail == NONE {+        return None;+    }+    dict::DETAILS.get((detail - 1) as usize).copied()+}++fn is_water_kind(kind: u16) -> bool {+    kind_name(kind).is_some_and(|name| WATER_KINDS.contains(&name))+}++/// Longitude of tile-local point `px` (extent units) on tile `tile`.+fn point_lon(tile: TileId, extent: u16, px: i16) -> f64 {+    let n = (1u64 << tile.z) as f64;+    (tile.x as f64 + px as f64 / extent.max(1) as f64) / n * 360.0 - 180.0+}++/// Latitude of tile-local point `py` (extent units) on tile `tile`:+/// the inverse Web-Mercator the renderer's camera uses.+fn point_lat(tile: TileId, extent: u16, py: i16) -> f64 {+    let n = (1u64 << tile.z) as f64;+    let y = tile.y as f64 + py as f64 / extent.max(1) as f64;+    let m = std::f64::consts::PI - 2.0 * std::f64::consts::PI * y / n;+    m.sinh().atan().to_degrees()+}++/// The tile containing `(lat, lon)` at `z` (slippy-map, clamped).+fn tile_of(lat: f64, lon: f64, z: u8) -> (u32, u32) {+    let n = (1u64 << z) as f64;+    let max = n as u32 - 1;+    let lat = lat.clamp(-85.051_128_78, 85.051_128_78);+    let x = ((lon + 180.0) / 360.0 * n).floor();+    let lat_r = lat.to_radians();+    let y = ((1.0 - (lat_r.tan() + 1.0 / lat_r.cos()).ln() / std::f64::consts::PI) / 2.0 * n)+        .floor();+    (+        (x as u32).min(max),+        (y as u32).min(max),+    )+}++/// Tiles covering a bbox at `z`, centre-first (nearest tile centre to+/// the bbox centre first) so a capped query keeps the middle of the+/// region — the wear snapshot is centre-first for the same reason.+pub fn tiles_for_bbox(west: f64, south: f64, east: f64, north: f64, z: u8) -> Vec<TileId> {+    if !(west < east && south < north) {+        return Vec::new();+    }+    let (x0, y1) = tile_of(south, west, z);+    let (x1, y0) = tile_of(north, east, z);+    let (cx, cy) = ((west + east) / 2.0, (south + north) / 2.0);+    let mut tiles: Vec<(f64, TileId)> = Vec::new();+    for x in x0..=x1 {+        for y in y0..=y1 {+            let t = TileId { z, x, y };+            // Distance from the bbox centre to this tile's centre, in+            // tile units — only an ordering key, never a measurement.+            let tx = point_lon(t, 1, 0) - cx;+            let ty = point_lat(t, 1, 0) - cy;+            tiles.push((tx * tx + ty * ty, t));+        }+    }+    tiles.sort_by(|a, b| a.0.total_cmp(&b.0));+    tiles.into_iter().map(|(_, t)| t).collect()+}++/// How many tiles cover a bbox at `z`, from its corners alone — O(1)+/// at any zoom, where materialising the tile list for a whole-world+/// bbox at z14 would be hundreds of millions of entries.+fn tile_count(west: f64, south: f64, east: f64, north: f64, z: u8) -> u64 {+    if !(west < east && south < north) {+        return 0;+    }+    let (x0, y1) = tile_of(south, west, z);+    let (x1, y0) = tile_of(north, east, z);+    (x1 as u64 - x0 as u64 + 1) * (y1 as u64 - y0 as u64 + 1)+}++/// The zoom a query reads: the archive's deepest (capped at+/// [`QUERY_ZOOM_CAP`]), stepped out until the bbox needs at most+/// [`MAX_TILES`] tiles. `truncated` reports that a step-out happened,+/// i.e. the caller is reading coarser bodies than the archive holds.+pub fn choose_zoom(min_zoom: u8, max_zoom: u8, q: &GeometryQuery) -> (u8, bool) {+    let mut z = max_zoom.min(QUERY_ZOOM_CAP).max(min_zoom);+    let mut stepped_out = false;+    while z > min_zoom && tile_count(q.west, q.south, q.east, q.north, z) > MAX_TILES as u64 {+        z -= 1;+        stepped_out = true;+    }+    (z, stepped_out)+}++/// Extract the requested kinds from already-decoded bodies.+///+/// `bodies` pairs each tile with its decoded body (`None` = the archive+/// does not hold it). Pure: the same function the JNI path feeds with+/// batch-fetched bodies is what the unit tests feed by hand.+pub fn extract(+    bodies: &[(TileId, Option<&Body>)],+    q: &GeometryQuery,+    max_points: usize,+) -> GeometryResult {+    let mut out = GeometryResult {+        total_tiles: bodies.len(),+        covered_tiles: bodies.iter().filter(|(_, b)| b.is_some()).count(),+        ..GeometryResult::default()+    };+    if q.kinds_mask & KIND_ALL == 0 || !(q.west < q.east && q.south < q.north) {+        return out;+    }+    let max_features = q.max_features.clamp(1, MAX_FEATURES);+    let mut points_left = max_points.min(MAX_POINTS);+    // Wear priority: roads survive a cap longest, buildings first to go.+    for want in [KIND_ROAD, KIND_PATH, KIND_WATER, KIND_BUILDING] {+        if q.kinds_mask & want == 0 {+            continue;+        }+        for (tile, body) in bodies {+            let Some(body) = body else { continue };+            let layer_id = match want {+                KIND_ROAD | KIND_PATH => LAYER_ROADS,+                KIND_WATER => LAYER_LANDTYPE,+                _ => LAYER_BUILDINGS,+            };+            let Some(layer) = body.layer(layer_id) else { continue };+            let extent = body.extent;+            for feature in &layer.features {+                let (kind, class) = match classify(want, feature) {+                    Some(v) => v,+                    None => continue,+                };+                for part in layer.parts_of(feature) {+                    let raw = layer.points(part);+                    if raw.len() < 2 {+                        continue;+                    }+                    let points: Vec<(f64, f64)> = raw+                        .iter()+                        .map(|&(px, py)| (point_lon(*tile, extent, px), point_lat(*tile, extent, py)))+                        .collect();+                    // Full parts only: a polygon cut to the bbox here+                    // would lose its outside ring points and fill+                    // wrong; the Kotlin extractor clips/simplifies.+                    if !part_intersects(&points, q) {+                        continue;+                    }+                    let closed = feature.geom_type == GEOM_POLYGON;+                    if closed && points.len() < 3 {+                        continue;+                    }+                    if out.features.len() >= max_features || points.len() > points_left {+                        out.truncated = true;+                        continue;+                    }+                    points_left -= points.len();+                    out.features.push(GeometryFeature {+                        kind,+                        class: class.clone(),+                        closed,+                        points,+                    });+                }+            }+        }+    }+    out+}++/// Whether one part belongs in the `want` group, and its class string.+fn classify(want: u32, feature: &tilecodec::mamaps::body::Feature) -> Option<(u32, String)> {+    let name = kind_name(feature.kind).unwrap_or("");+    match want {+        KIND_ROAD | KIND_PATH => {+            if feature.geom_type != GEOM_LINE || NON_ROAD_KINDS.contains(&name) {+                return None;+            }+            let is_path = name == "path";+            if (want == KIND_PATH) != is_path {+                return None;+            }+            let class = detail_name(feature.kind_detail)+                .unwrap_or(name)+                .to_string();+            Some((want, class))+        }+        KIND_WATER => {+            if !is_water_kind(feature.kind) {+                return None;+            }+            if feature.geom_type != GEOM_POLYGON && feature.geom_type != GEOM_LINE {+                return None;+            }+            Some((KIND_WATER, name.to_string()))+        }+        _ => {+            if feature.geom_type != GEOM_POLYGON {+                return None;+            }+            Some((KIND_BUILDING, name.to_string()))+        }+    }+}++fn part_intersects(points: &[(f64, f64)], q: &GeometryQuery) -> bool {+    let (mut w, mut s, mut e, mut n) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+    for &(lon, lat) in points {+        w = w.min(lon);+        e = e.max(lon);+        s = s.min(lat);+        n = n.max(lat);+    }+    w <= q.east && e >= q.west && s <= q.north && n >= q.south+}++/// Stitch the parent wash into bodies that need it, in place.+///+/// At the archive's deepest zoom the `landtype` wash is gated: a z14+/// body may carry no water polygon at all, and the renderer reads it+/// from its z13 parent instead (see `geometry::wash_overzoom`). A+/// geometry query at that zoom must do the same or lakes and+/// coastlines would silently vanish — reusing the workers' own+/// `needs_wash_underlay`/`parent_of`/`stitch_parent_wash`, with+/// `parents` holding each needed parent's fetch result. A parent that+/// failed fails its child (counted in `failed`), exactly as the+/// worker fails the tile for retry rather than drawing ocean for land;+/// a parent the archive does not hold leaves the child as it is.+fn apply_wash_underlay(+    pairs: &mut [(TileId, Option<Body>)],+    parents: &[(TileId, Option<Result<Body, ()>>)],+    failed: &mut usize,+) {+    use super::geometry::{needs_wash_underlay, parent_of, stitch_parent_wash};+    for (tile, slot) in pairs.iter_mut() {+        let Some(body) = slot.as_ref() else { continue };+        if !needs_wash_underlay(body, tile.z) {+            continue;+        }+        let (px, py, qx, qy) = parent_of(tile.x, tile.y);+        let parent = parents+            .iter()+            .find(|(t, _)| t.z == tile.z.saturating_sub(1) && t.x == px && t.y == py)+            .map(|(_, r)| r);+        match parent {+            Some(Some(Ok(parent_body))) => {+                *slot = Some(stitch_parent_wash(body, parent_body, qx, qy));+            }+            Some(Some(Err(()))) => {+                *failed += 1;+                *slot = None;+            }+            // Parent absent (or never fetched): the child stands.+            _ => {}+        }+    }+}++/// Run one query against an archive source: choose the zoom, batch-fetch+/// the covering tiles through the source's existing `tiles()` wave, and+/// extract. This is the entry the JNI bridge calls; it allocates one+/// archive view per call and never touches a renderer handle.+pub fn query_geometry<T: TileSource>(source: &T, q: &GeometryQuery) -> GeometryResult {+    let header = source.header();+    let (z, stepped_out) = choose_zoom(header.min_zoom, header.max_zoom, q);+    let tiles = tiles_for_bbox(q.west, q.south, q.east, q.north, z);+    if tiles.is_empty() {+        return GeometryResult { truncated: stepped_out, ..GeometryResult::default() };+    }+    let coords: Vec<(u8, u32, u32)> = tiles.iter().map(|t| (t.z, t.x, t.y)).collect();+    let fetched = source.tiles(&coords);+    let mut failed = 0usize;+    let mut pairs: Vec<(TileId, Option<Body>)> = tiles+        .iter()+        .copied()+        .zip(fetched)+        .map(|(tile, res)| match res {+            Ok(body) => (tile, body),+            Err(_) => {+                failed += 1;+                (tile, None)+            }+        })+        .collect();+    // Wash underlay (deepest-zoom tiles only): fetch each distinct+    // parent once, then stitch — the workers' wave-1.5 discipline.+    if z > header.min_zoom {+        use super::geometry::{needs_wash_underlay, parent_of};+        let mut distinct: Vec<(u8, u32, u32)> = Vec::new();+        for (tile, body) in &pairs {+            if let Some(body) = body {+                if needs_wash_underlay(body, tile.z) {+                    let (px, py, _, _) = parent_of(tile.x, tile.y);+                    let parent = (tile.z - 1, px, py);+                    if !distinct.contains(&parent) {+                        distinct.push(parent);+                    }+                }+            }+        }+        if !distinct.is_empty() {+            let fetched_parents = source.tiles(&distinct);+            let parents: Vec<(TileId, Option<Result<Body, ()>>)> = distinct+                .iter()+                .map(|&(pz, px, py)| TileId { z: pz, x: px, y: py })+                .zip(fetched_parents)+                .map(|(tile, res)| {+                    let mapped = match res {+                        Ok(Some(body)) => Some(Ok(body)),+                        Ok(None) => None,+                        Err(_) => Some(Err(())),+                    };+                    (tile, mapped)+                })+                .collect();+            apply_wash_underlay(&mut pairs, &parents, &mut failed);+        }+    }+    let refs: Vec<(TileId, Option<&Body>)> =+        pairs.iter().map(|(t, b)| (*t, b.as_ref())).collect();+    let mut out = extract(&refs, q, MAX_POINTS);+    out.failed_tiles = failed;+    out.truncated = out.truncated || stepped_out;+    out+}++#[cfg(test)]+mod tests;
library/map/src/main/rust/src/tile/geometry_query/tests.rs
diff --git a/library/map/src/main/rust/src/tile/geometry_query/tests.rs b/library/map/src/main/rust/src/tile/geometry_query/tests.rsnew file mode 100644index 0000000000..78e1639572--- /dev/null+++ b/library/map/src/main/rust/src/tile/geometry_query/tests.rs@@ -0,0 +1,177 @@+use super::*;+use tilecodec::mamaps::body::{Feature, Layer as BodyLayer, Part, NAME_NONE, WINDING_OUTER};+use tilecodec::mamaps::dict::NONE;++fn kind(name: &str) -> u16 {+    crate::style::kind_id(name).expect("schema kind")+}++fn feat(kind: u16, geom_type: u8) -> Feature {+    Feature {+        kind,+        kind_detail: NONE,+        geom_type,+        flags: 0,+        name_idx: NAME_NONE,+        parts_offset: 0,+        part_count: 1,+        transit_color: 0,+        transit_ordinal: 0,+        transit_lanes: 0,+        transit_taper: 0,+        lane_count: 0,+    }+}++fn push(layer: &mut BodyLayer, mut f: Feature, pts: &[(i16, i16)]) {+    f.parts_offset = layer.parts.len() as u32;+    layer.parts.push(Part {+        coord_start: layer.coords.len() as u32,+        point_count: pts.len() as u32,+        winding: WINDING_OUTER,+    });+    layer.coords.extend_from_slice(pts);+    layer.features.push(f);+}++/// One tile at z1/0/0 (west-north quadrant): landtype lake, a road,+/// a path, and a building, all in the tile's middle.+fn body() -> Body {+    let mut body = Body::new(4096);+    let mut land = BodyLayer::new(LAYER_LANDTYPE);+    push(&mut land, feat(NONE, GEOM_POLYGON), &[(0, 0), (4096, 0), (4096, 4096), (0, 4096)]);+    push(&mut land, feat(kind("lake"), GEOM_POLYGON), &[(2000, 2000), (3000, 2000), (3000, 3000), (2000, 3000)]);+    body.layers.push(land);+    let mut roads = BodyLayer::new(LAYER_ROADS);+    push(&mut roads, feat(kind("major_road"), GEOM_LINE), &[(500, 2000), (2000, 2000), (3500, 2000)]);+    push(&mut roads, feat(kind("path"), GEOM_LINE), &[(500, 2500), (3500, 2500)]);+    push(&mut roads, feat(kind("rail"), GEOM_LINE), &[(500, 3000), (3500, 3000)]);+    body.layers.push(roads);+    let mut buildings = BodyLayer::new(LAYER_BUILDINGS);+    push(&mut buildings, feat(kind("building"), GEOM_POLYGON), &[(1000, 1000), (1500, 1000), (1500, 1500), (1000, 1500)]);+    body.layers.push(buildings);+    body+}++fn world() -> GeometryQuery {+    GeometryQuery { west: -180.0, south: -85.0, east: 180.0, north: 85.0, kinds_mask: KIND_ALL, max_features: 256 }+}++#[test]+fn extracts_roads_paths_water_and_buildings_with_classes() {+    let tile = TileId { z: 1, x: 0, y: 0 };+    let body = body();+    let out = extract(&[(tile, Some(&body))], &world(), MAX_POINTS);+    let kinds: Vec<u32> = out.features.iter().map(|f| f.kind).collect();+    // Rail is not a road; the kind-less mainland is not water.+    assert_eq!(kinds, vec![KIND_ROAD, KIND_PATH, KIND_WATER, KIND_BUILDING]);+    assert_eq!(out.features[0].class, "major_road");+    assert!(!out.features[0].closed);+    assert!(out.features[2].closed, "a lake polygon is closed");+    assert!(out.features[3].closed, "a building polygon is closed");+    assert_eq!(out.covered_tiles, 1);+    assert!(!out.truncated);+    // Points land inside the tile's quadrant (west, north).+    for f in &out.features {+        for &(lon, lat) in &f.points {+            assert!((-180.0..0.0).contains(&lon), "lon {lon}");+            assert!((0.0..90.0).contains(&lat), "lat {lat}");+        }+    }+}++#[test]+fn bbox_filtering_drops_features_outside_the_query() {+    let tile = TileId { z: 1, x: 0, y: 0 };+    let body = body();+    // A bbox over the tile's far west edge: only the road/path+    // lines (which start at x=500) reach it; the lake/building do not.+    let (w, n) = (point_lon(tile, 4096, 600), point_lat(tile, 4096, 0));+    let q = GeometryQuery { west: -180.0, south: 0.0, east: w, north: n, kinds_mask: KIND_ALL, max_features: 256 };+    let out = extract(&[(tile, Some(&body))], &q, MAX_POINTS);+    assert!(out.features.iter().all(|f| f.kind == KIND_ROAD || f.kind == KIND_PATH));+    // A bbox nowhere near the tile: honestly empty, still covered.+    let q = GeometryQuery { west: 10.0, south: 10.0, east: 11.0, north: 11.0, kinds_mask: KIND_ALL, max_features: 256 };+    let out = extract(&[(tile, Some(&body))], &q, MAX_POINTS);+    assert!(out.features.is_empty());+    assert_eq!(out.covered_tiles, 1, "scanned and found nothing is not unavailable");+}++#[test]+fn caps_truncate_whole_features_and_flag_it() {+    let tile = TileId { z: 1, x: 0, y: 0 };+    let body = body();+    let q = GeometryQuery { max_features: 2, ..world() };+    let out = extract(&[(tile, Some(&body))], &q, MAX_POINTS);+    assert_eq!(out.features.len(), 2, "road + path survive first (wear priority)");+    assert!(out.truncated);+    // Point cap below every feature's size: nothing partial crosses.+    let out = extract(&[(tile, Some(&body))], &world(), 1);+    assert!(out.features.is_empty());+    assert!(out.truncated);+}++#[test]+fn absent_tiles_are_uncovered_not_failed() {+    let tile = TileId { z: 1, x: 0, y: 0 };+    let out = extract(&[(tile, None)], &world(), MAX_POINTS);+    assert!(out.features.is_empty());+    assert_eq!(out.covered_tiles, 0);+    assert_eq!(out.total_tiles, 1);+    assert_eq!(out.failed_tiles, 0);+}++#[test]+fn wash_underlay_stitches_parent_water_into_a_gated_child() {+    // A z14 child with no landtype at all (gated wash) and a z13+    // parent holding a lake in the child's quadrant: after the+    // underlay the extract must see the water, in the child tile.+    let child = TileId { z: 14, x: 8192, y: 8192 };+    let (px, py, _, _) = crate::tile::geometry::parent_of(child.x, child.y);+    let parent_tile = TileId { z: 13, x: px, y: py };+    let mut child_body = Body::new(4096);+    let mut roads = BodyLayer::new(LAYER_ROADS);+    push(&mut roads, feat(kind("major_road"), GEOM_LINE), &[(100, 100), (3900, 3900)]);+    child_body.layers.push(roads);+    let mut parent_body = Body::new(4096);+    let mut land = BodyLayer::new(LAYER_LANDTYPE);+    push(&mut land, feat(kind("lake"), GEOM_POLYGON), &[(0, 0), (2048, 0), (2048, 2048), (0, 2048)]);+    parent_body.layers.push(land);+    assert!(crate::tile::geometry::needs_wash_underlay(&child_body, child.z));+    let mut pairs = vec![(child, Some(child_body))];+    let parents = vec![(parent_tile, Some(Ok(parent_body)))];+    let mut failed = 0usize;+    apply_wash_underlay(&mut pairs, &parents, &mut failed);+    assert_eq!(failed, 0);+    let refs: Vec<(TileId, Option<&Body>)> =+        pairs.iter().map(|(t, b)| (*t, b.as_ref())).collect();+    let out = extract(&refs, &world(), MAX_POINTS);+    let water: Vec<&GeometryFeature> =+        out.features.iter().filter(|f| f.kind == KIND_WATER).collect();+    assert_eq!(water.len(), 1, "the parent lake reaches the child: {:?}", out.features);+    assert!(water[0].closed);+    // A failed parent fails the child rather than inventing ocean.+    let mut pairs = vec![(child, Some(Body::new(4096)))];+    let parents = vec![(parent_tile, Some(Err(())))];+    let mut failed = 0usize;+    apply_wash_underlay(&mut pairs, &parents, &mut failed);+    assert_eq!(failed, 1);+    assert!(pairs[0].1.is_none());+}++#[test]+fn tile_selection_and_zoom_are_bounded() {+    // The whole world at z15 would be billions of tiles; the zoom+    // steps out until the 25-tile cap holds.+    let (z, stepped) = choose_zoom(0, 14, &world());+    assert!(stepped);+    assert!(tiles_for_bbox(-180.0, -85.0, 180.0, 85.0, z).len() <= MAX_TILES);+    // A street bbox keeps the archive's deepest zoom.+    let q = GeometryQuery { west: -0.001, south: 51.5, east: 0.001, north: 51.502, kinds_mask: KIND_ALL, max_features: 16 };+    let (z, stepped) = choose_zoom(0, 14, &q);+    assert_eq!(z, 14);+    assert!(!stepped);+    assert!(!tiles_for_bbox(q.west, q.south, q.east, q.north, z).is_empty());+    // A degenerate bbox selects nothing.+    assert!(tiles_for_bbox(5.0, 5.0, 5.0, 6.0, 10).is_empty());+}
library/map/src/main/rust/src/tile/mod.rs
diff --git a/library/map/src/main/rust/src/tile/mod.rs b/library/map/src/main/rust/src/tile/mod.rsindex ce21684f03..2b3a04f24e 100644--- a/library/map/src/main/rust/src/tile/mod.rs+++ b/library/map/src/main/rust/src/tile/mod.rs@@ -7,6 +7,7 @@ pub mod arrow; pub mod cache; pub mod geometry;+pub mod geometry_query; pub mod glyph; pub mod placement; pub mod select;
library/map/src/main/rust/tests/geometry_query.rs
diff --git a/library/map/src/main/rust/tests/geometry_query.rs b/library/map/src/main/rust/tests/geometry_query.rsnew file mode 100644index 0000000000..948b13a6c5--- /dev/null+++ b/library/map/src/main/rust/tests/geometry_query.rs@@ -0,0 +1,103 @@+#![allow(dead_code)]+//! The geometry query against a synthetic `.mamaps` archive, through+//! the same file reader + codec the device uses: bbox filtering, caps+//! and empty-region honesty at the archive level (the pure extraction+//! maths is unit-tested in `tile::geometry_query`).++use std::path::PathBuf;+use std::sync::Arc;++use map_renderer::tile::geometry_query::{+    query_geometry, GeometryQuery, KIND_ALL, KIND_BUILDING, KIND_ROAD, KIND_WATER,+};+use map_renderer::tile::source::FileRangeReader;+use tilecodec::mamaps::read::{LeafCache, MamapsArchive};++#[path = "real_archive/fixture.rs"]+mod fixture;++fn open(path: &std::path::Path) -> MamapsArchive<FileRangeReader> {+    MamapsArchive::open_with_cache(+        FileRangeReader::open(path).expect("FileRangeReader::open"),+        Arc::new(LeafCache::new()),+    )+    .expect("archive opens")+}++/// A z14 archive over San Francisco holding the rich fixture body+/// (road, lake, building) in the tile containing the city centre.+fn sf_archive(tag: &str) -> (PathBuf, (u32, u32)) {+    let (x, y) = fixture::tile_of(37.7749, -122.4194, 14);+    let path = fixture::temp_path(tag);+    fixture::write_archive(&path, &[(14, x, y, fixture::rich_body(0))]);+    (path, (x, y))+}++fn sf_query() -> GeometryQuery {+    GeometryQuery {+        west: -122.43,+        south: 37.76,+        east: -122.41,+        north: 37.79,+        kinds_mask: KIND_ALL,+        max_features: 256,+    }+}++#[test]+fn query_reads_roads_water_and_buildings_from_a_real_archive() {+    let (path, _) = sf_archive("geometry-sf");+    let archive = open(&path);+    assert_eq!(archive.header.max_zoom, 14);+    let out = query_geometry(&archive, &sf_query());+    assert!(out.covered_tiles >= 1, "the SF tile was decoded");+    assert_eq!(out.failed_tiles, 0);+    let kinds: Vec<u32> = out.features.iter().map(|f| f.kind).collect();+    assert!(kinds.contains(&KIND_ROAD), "roads came back: {kinds:?}");+    assert!(kinds.contains(&KIND_WATER), "the lake came back: {kinds:?}");+    assert!(kinds.contains(&KIND_BUILDING), "buildings came back: {kinds:?}");+    for f in &out.features {+        for &(lon, lat) in &f.points {+            assert!((-123.0..-122.0).contains(&lon), "lon {lon}");+            assert!((37.0..38.5).contains(&lat), "lat {lat}");+        }+    }+    let _ = std::fs::remove_file(&path);+}++#[test]+fn query_over_empty_ground_is_covered_by_nothing_and_honest() {+    let (path, _) = sf_archive("geometry-empty");+    let archive = open(&path);+    // The Pacific, far from the one stored tile: the archive holds no+    // tile there, so nothing is covered and nothing is invented — and+    // that is not a failure.+    let out = query_geometry(+        &archive,+        &GeometryQuery { west: -150.0, south: 30.0, east: -149.0, north: 31.0, kinds_mask: KIND_ALL, max_features: 256 },+    );+    assert!(out.features.is_empty());+    assert_eq!(out.covered_tiles, 0);+    assert_eq!(out.failed_tiles, 0);+    assert!(out.total_tiles >= 1);+    let _ = std::fs::remove_file(&path);+}++#[test]+fn kind_mask_and_feature_cap_are_respected() {+    let (path, _) = sf_archive("geometry-caps");+    let archive = open(&path);+    let water_only = query_geometry(+        &archive,+        &GeometryQuery { kinds_mask: KIND_WATER, ..sf_query() },+    );+    assert!(!water_only.features.is_empty());+    assert!(water_only.features.iter().all(|f| f.kind == KIND_WATER));+    let capped = query_geometry(+        &archive,+        &GeometryQuery { max_features: 1, ..sf_query() },+    );+    assert_eq!(capped.features.len(), 1);+    assert!(capped.truncated);+    let _ = std::fs::remove_file(&path);+}
library/map/src/test/java/com/vayunmathur/library/map/MapGeometryTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/MapGeometryTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/MapGeometryTest.ktnew file mode 100644index 0000000000..ea04cf19fc--- /dev/null+++ b/library/map/src/test/java/com/vayunmathur/library/map/MapGeometryTest.kt@@ -0,0 +1,88 @@+package com.vayunmathur.library.map++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class MapGeometryTest {++    private val all = MapGeometryKind.entries.toSet()++    @Test+    fun parsesFeatureRowsWithClassesAndClosure() {+        val rows = arrayOf(+            "OK\u00010\u00013\u00014",+            "ROAD\u0001residential\u00010\u0001-1224194000,377749000,-1224193000,377749100",+            "WATER\u0001lake\u00011\u00011000000,510000000,1001000,510000000,1001000,510001000",+            "BUILDING\u0001building\u00011\u00011000000,510000000,1001000,510000000,1001000,510001000",+        )+        val result = MapGeometry.parseRows(rows, all)+        assertTrue(result.unsourcedKinds.isEmpty())+        assertFalse(result.truncated)+        assertEquals(3, result.coveredTiles)+        assertEquals(4, result.totalTiles)+        assertEquals(3, result.features.size)+        val road = result.featuresOf(MapGeometryKind.ROAD).single()+        assertEquals("residential", road.kindClass)+        assertFalse(road.closed)+        assertTrue(kotlin.math.abs(road.points.first().longitude - -122.4194) < 1e-9)+        assertTrue(kotlin.math.abs(road.points.first().latitude - 37.7749) < 1e-9)+        assertTrue(result.featuresOf(MapGeometryKind.WATER).single().closed)+        assertTrue(result.featuresOf(MapGeometryKind.BUILDING).single().closed)+    }++    @Test+    fun unavailableMarksEveryRequestedKindUnsourced() {+        for (rows in listOf(arrayOf("UNAVAILABLE"), emptyArray(), arrayOf("GARBAGE"))) {+            val result = MapGeometry.parseRows(rows, all)+            assertEquals(all, result.unsourcedKinds)+            assertTrue(result.features.isEmpty())+        }+        // Only the requested kinds are blamed.+        val result = MapGeometry.parseRows(arrayOf("UNAVAILABLE"), setOf(MapGeometryKind.ROAD))+        assertEquals(setOf(MapGeometryKind.ROAD), result.unsourcedKinds)+    }++    @Test+    fun scannedEmptyRegionIsNotUnsourced() {+        // OK header, no feature rows: the archive was read and the+        // region genuinely holds none of the requested kinds.+        val result = MapGeometry.parseRows(arrayOf("OK\u00010\u00012\u00012"), all)+        assertTrue(result.unsourcedKinds.isEmpty())+        assertTrue(result.features.isEmpty())+        assertEquals(2, result.coveredTiles)+    }++    @Test+    fun truncatedHeaderAndMalformedRowsAreHonest() {+        val rows = arrayOf(+            "OK\u00011\u00011\u00011",+            "ROAD\u0001\u00010\u0001not,numbers",+            "PATH\u0001path\u00010\u00011000000,510000000,1000500,510000500",+            "WATERBROKENROW",+        )+        val result = MapGeometry.parseRows(rows, all)+        assertTrue(result.truncated)+        // The malformed road row is skipped; the valid path survives.+        assertEquals(listOf(MapGeometryKind.PATH), result.features.map { it.kind })+    }++    @Test+    fun noArchivePathIsUnsourcedWithoutTouchingNative() {+        // archivePath blank: query() must answer unsourced directly.+        // (On a host JVM the native library is absent too; either path+        // lands on the same honest answer.)+        val result = MapGeometry.query(+            archivePath = "",+            bounds = GeoBounds(-0.01, 51.5, 0.01, 51.51),+        )+        assertEquals(all, result.unsourcedKinds)+        assertTrue(result.features.isEmpty())+        val degenerate = MapGeometry.query(+            archivePath = "/nonexistent/basemap.mamaps",+            bounds = GeoBounds(1.0, 1.0, 1.0, 2.0),+        )+        assertEquals(all, degenerate.unsourcedKinds)+    }+}
maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt
diff --git a/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt b/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.ktindex e971d947c3..4037d6fb75 100644--- a/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt+++ b/maps-wear/src/main/java/com/vayunmathur/maps/wear/domain/WearMapsProtocol.kt@@ -26,13 +26,14 @@ import kotlin.math.cos  * What a snapshot contains — and what it honestly does not:  * Coordinates are quantized metres east/north of the snapshot centre  * ([QUANT_STEP_M] per unit, so round-trip error is at most half a step).- * Lines carry roads/paths/water/buildings/route geometry *when the phone- * has a cheap source for them*; points carry POIs from the offline index- * and saved places. `:library:map` exposes no Kotlin geometry API for the- * basemap's road/water/building linework (the Vulkan renderer decodes the- * `.mamaps` tiles natively), so a phone build without such a source sets- * [WearMapSnapshot.degraded] to name the missing kinds instead of faking- * geometry. The watch renders whatever lines it is given.+ * Lines carry roads/paths/water/buildings/route geometry from+ * `:library:map`'s Kotlin geometry API (`MapGeometry`, decoding the+ * downloaded `.mamaps` archive through the renderer's own codec);+ * points carry POIs from the offline index and saved places.+ * [WearMapSnapshot.degraded] names kinds that are *unavailable* - no+ * readable archive - never kinds that were read and simply have no+ * features in this region (an ocean bbox is a complete, empty map).+ * The watch renders whatever lines it is given.  *  * Position source is the PHONE. The watch does not run its own GPS in  * this design (a watch fix would cost watch battery for a worse antenna@@ -127,7 +128,12 @@ data class WearMapSnapshot(     val saved: List<WearSavedPlace> = emptyList(),     /** True when the byte cap dropped or coarsened geometry. */     val truncated: Boolean = false,-    /** Human-honest names of what is missing/coarser, e.g. "roads", "detail". Empty = full. */+    /**+     * Human-honest names of what is unavailable/coarser, e.g. "roads",+     * "detail". A basemap kind appears here only when it could not be+     * sourced (no readable archive), not when it was read and the+     * region simply contains none. Empty = full.+     */     val degraded: List<String> = emptyList(),     /** User bearing (degrees clockwise from north) at publish, -1 = unknown. */     val userBearingDeg: Int = -1,
maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.kt b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.ktindex 229962c341..38ea6451f3 100644--- a/maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.kt+++ b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapRegion.kt@@ -1,6 +1,8 @@ package com.vayunmathur.maps.domain  import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.MapGeometryKind+import com.vayunmathur.library.map.MapGeometryResult import kotlinx.serialization.encodeToString import kotlin.math.abs import kotlin.math.hypot@@ -28,6 +30,42 @@ data class WearRawLine(     val name: String = "", ) +/**+ * Basemap geometry from `:library:map` ([MapGeometryResult]) as raw+ * wear lines, in the result's own priority order. A feature's class is+ * not a display name, so [WearRawLine.name] stays empty.+ */+fun MapGeometryResult.toWearRawLines(): List<WearRawLine> = features.map { feature ->+    WearRawLine(+        kind = when (feature.kind) {+            MapGeometryKind.ROAD -> WearLineKind.ROAD+            MapGeometryKind.PATH -> WearLineKind.PATH+            MapGeometryKind.WATER -> WearLineKind.WATER+            MapGeometryKind.BUILDING -> WearLineKind.BUILDING+        },+        points = feature.points,+        closed = feature.closed,+    )+}++/**+ * The `degraded` names for basemap kinds this result could not source.+ *+ * `degraded` means **unavailable**, not **empty**: a kind whose archive+ * was read but which returned no features (an ocean or desert region)+ * is genuinely absent there and is *not* named. A kind is named only+ * when it sits in [MapGeometryResult.unsourcedKinds] — no planet file,+ * an unreadable one, or no native library. Roads and paths share one+ * source layer, so either unsourced names the group "roads".+ */+fun MapGeometryResult.wearMissingKinds(): List<String> = buildList {+    if (MapGeometryKind.ROAD in unsourcedKinds || MapGeometryKind.PATH in unsourcedKinds) {+        add("roads")+    }+    if (MapGeometryKind.WATER in unsourcedKinds) add("water")+    if (MapGeometryKind.BUILDING in unsourcedKinds) add("buildings")+}+ /** One POI in geographic coords, as a caller supplies it. */ data class WearRawPoint(     val type: Int,@@ -153,8 +191,11 @@ private fun toMeterPts(points: List<GeoPoint>, originLat: Double, originLon: Dou  /**  * Builds a byte-capped snapshot. [missingKinds] names geometry kinds the- * caller could not supply at all (honesty, e.g. basemap linework); they- * are merged into [WearMapSnapshot.degraded] verbatim.+ * caller could not source at all (honesty: unavailable, not merely+ * empty — see [wearMissingKinds]); they are merged into+ * [WearMapSnapshot.degraded] verbatim. [sourceTruncated] says the+ * geometry source itself capped what it returned, so the snapshot is+ * flagged truncated/"detail" even when it fits under the byte cap.  */ fun buildWearMapSnapshot(     center: GeoPoint,@@ -165,6 +206,7 @@ fun buildWearMapSnapshot(     userBearingDeg: Int = -1,     missingKinds: List<String> = emptyList(),     radiusM: Int = WearMapsProtocol.REGION_RADIUS_M,+    sourceTruncated: Boolean = false, ): WearMapSnapshot {     val tolerances = listOf(4.0, 8.0, 16.0, 32.0)     val pointCaps = listOf(80, 60, 40, 20)@@ -175,7 +217,7 @@ fun buildWearMapSnapshot(             userBearingDeg, missingKinds, radiusM,             toleranceM = tolerances[step], pointCap = pointCaps[step],             droppedKinds = droppedKinds,-            coarsened = step > 0,+            coarsened = step > 0 || sourceTruncated,         )         if (encodedSize(snapshot) <= WearMapsProtocol.MAX_JSON_BYTES) return snapshot         // Next rung: also drop the lowest-priority remaining line kind.
maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.ktindex 3cf31a6c72..93882fba4f 100644--- a/maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt+++ b/maps/src/main/java/com/vayunmathur/maps/domain/WearMapsProtocol.kt@@ -26,13 +26,14 @@ import kotlin.math.cos  * What a snapshot contains — and what it honestly does not:  * Coordinates are quantized metres east/north of the snapshot centre  * ([QUANT_STEP_M] per unit, so round-trip error is at most half a step).- * Lines carry roads/paths/water/buildings/route geometry *when the phone- * has a cheap source for them*; points carry POIs from the offline index- * and saved places. `:library:map` exposes no Kotlin geometry API for the- * basemap's road/water/building linework (the Vulkan renderer decodes the- * `.mamaps` tiles natively), so a phone build without such a source sets- * [WearMapSnapshot.degraded] to name the missing kinds instead of faking- * geometry. The watch renders whatever lines it is given.+ * Lines carry roads/paths/water/buildings/route geometry from+ * `:library:map`'s Kotlin geometry API (`MapGeometry`, decoding the+ * downloaded `.mamaps` archive through the renderer's own codec);+ * points carry POIs from the offline index and saved places.+ * [WearMapSnapshot.degraded] names kinds that are *unavailable* - no+ * readable archive - never kinds that were read and simply have no+ * features in this region (an ocean bbox is a complete, empty map).+ * The watch renders whatever lines it is given.  *  * Position source is the PHONE. The watch does not run its own GPS in  * this design (a watch fix would cost watch battery for a worse antenna@@ -127,7 +128,12 @@ data class WearMapSnapshot(     val saved: List<WearSavedPlace> = emptyList(),     /** True when the byte cap dropped or coarsened geometry. */     val truncated: Boolean = false,-    /** Human-honest names of what is missing/coarser, e.g. "roads", "detail". Empty = full. */+    /**+     * Human-honest names of what is unavailable/coarser, e.g. "roads",+     * "detail". A basemap kind appears here only when it could not be+     * sourced (no readable archive), not when it was read and the+     * region simply contains none. Empty = full.+     */     val degraded: List<String> = emptyList(),     /** User bearing (degrees clockwise from north) at publish, -1 = unknown. */     val userBearingDeg: Int = -1,
maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.kt b/maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.ktindex 1d0188d247..6fb5f23cce 100644--- a/maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.kt+++ b/maps/src/main/java/com/vayunmathur/maps/platform/WearMapsSync.kt@@ -2,11 +2,14 @@ package com.vayunmathur.maps.platform  import android.content.Context import com.vayunmathur.library.log.Log+import com.vayunmathur.library.map.GeoBounds import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.MapGeometry import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.wearlink.WearLinkListener import com.vayunmathur.library.wearlink.WearLinkNode import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.maps.data.MapTileCache import com.vayunmathur.maps.data.PoiIndex import com.vayunmathur.maps.data.SavedPlaceStore import com.vayunmathur.maps.data.inViewport@@ -22,9 +25,12 @@ import com.vayunmathur.maps.domain.WearRouteState import com.vayunmathur.maps.domain.WearSavedPlace import com.vayunmathur.maps.domain.buildWearMapSnapshot import com.vayunmathur.maps.domain.buildWearRouteState+import com.vayunmathur.maps.domain.toWearRawLines+import com.vayunmathur.maps.domain.wearMissingKinds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob+import java.io.File import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import kotlinx.serialization.encodeToString@@ -38,18 +44,26 @@ import kotlin.math.cos  *   watch runs no GPS of its own. Every fix publishes a small  *   [WearPosition]; a fresh region is extracted only when  *   [WearRegionHysteresis] says the user nears the snapshot edge.- * - Region geometry is what this app has cheaply in Kotlin: POIs from- *   the offline index ([PoiIndex.inViewport]), saved places, and — while- *   navigating — the route. Basemap road/water/building linework is NOT- *   available in Kotlin (`:library:map` decodes tiles natively), so the- *   snapshot names those kinds in `degraded` rather than faking them;- *   the extractor/renderer carry them the moment a source exists.+ * - Region geometry: POIs from the offline index+ *   ([PoiIndex.inViewport]), saved places, basemap road/path/water/+ *   building linework from `:library:map`'s [MapGeometry] query over+ *   the downloaded `.mamaps` archive, and — while navigating — the+ *   route. When there is no readable archive the snapshot names the+ *   unsourced kinds in `degraded` (unavailable, not merely empty)+ *   rather than faking them.  * - Navigation mirrors [NavigationSessionManager]: Navigating publishes  *   an active [WearRouteState]; Idle/Arrived/Failed publish the explicit  *   `active=false` clear exactly once per transition.  */ object WearMapsSync {     private const val TAG = "WearMapsSync"++    /**+     * Basemap features per region query. The snapshot's own 48 KB cap+     * degrades further from here; this bounds the native extraction to+     * a few street tiles' worth of linework for a 600 m region.+     */+    private const val GEOMETRY_MAX_FEATURES = 320     private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)      @Volatile@@ -145,11 +159,31 @@ object WearMapsSync {         }     } -    /** The cheap-Kotlin extraction: offline POIs + saved places (+ route line while navigating). */+    /**+     * Region extraction: offline POIs + saved places, basemap geometry+     * from [MapGeometry] over the downloaded archive, plus the route+     * line while navigating. Runs on the IO scope: the geometry query+     * does file I/O and never touches the render path.+     */     private fun extractRegion(appContext: Context, center: GeoPoint): WearMapSnapshot {         val radius = WearMapsProtocol.REGION_RADIUS_M.toDouble()         val dLat = radius / 110_540.0         val dLon = radius / (111_320.0 * cos(Math.toRadians(center.latitude)).coerceAtLeast(0.05))+        val bounds = GeoBounds(+            west = center.longitude - dLon, south = center.latitude - dLat,+            east = center.longitude + dLon, north = center.latitude + dLat,+        )+        // No planet downloaded yet (or a partially-written file) reads+        // as a null path here and as unsourced kinds in the result —+        // never as an empty-but-complete map.+        val archiveFile = appContext.getExternalFilesDir(null)+            ?.let { File(it, MapTileCache.BASEMAP_ARCHIVE_FILE) }+            ?.takeIf { it.isFile }+        val geometry = MapGeometry.query(+            archivePath = archiveFile?.absolutePath,+            bounds = bounds,+            maxFeatures = GEOMETRY_MAX_FEATURES,+        )         val points = runCatching {             PoiIndex.initialize(appContext)             PoiIndex.inViewport(@@ -165,7 +199,7 @@ object WearMapsSync {                 WearSavedPlace(it.name, (it.lat * 1e7).toInt(), (it.lon * 1e7).toInt())             }         val route = NavigationSessionManager.session.value.route-        val lines = if (route != null && route.polyline.size >= 2) {+        val routeLine = if (route != null && route.polyline.size >= 2) {             listOf(WearRawLine(WearLineKind.ROUTE, route.polyline))         } else {             emptyList()@@ -173,12 +207,14 @@ object WearMapsSync {         return buildWearMapSnapshot(             center = center,             generatedAtMillis = System.currentTimeMillis(),-            rawLines = lines,+            rawLines = routeLine + geometry.toWearRawLines(),             rawPoints = points,             saved = saved.take(20),             userBearingDeg = lastBearingDeg,-            // Honest absence: no Kotlin source for basemap linework today.-            missingKinds = listOf("roads", "water", "buildings"),+            // degraded = unavailable only: kinds the archive was read+            // for but which simply have no features here are not named.+            missingKinds = geometry.wearMissingKinds(),+            sourceTruncated = geometry.truncated,         )     } 
maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.kt b/maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.ktindex 362a534e67..a83b347e24 100644--- a/maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/domain/WearMapRegionTest.kt@@ -1,6 +1,9 @@ package com.vayunmathur.maps.domain  import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.MapGeometryFeature+import com.vayunmathur.library.map.MapGeometryKind+import com.vayunmathur.library.map.MapGeometryResult import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -105,6 +108,106 @@ class WearMapRegionTest {         }     } +    /** Real-shaped geometry as `MapGeometry` returns it for a city block at the equator. */+    private fun realShapedGeometry() = MapGeometryResult(+        features = listOf(+            MapGeometryFeature(+                MapGeometryKind.ROAD, "residential", closed = false,+                points = listOf(east(-400.0), east(-100.0), east(150.0), east(400.0)),+            ),+            MapGeometryFeature(+                MapGeometryKind.PATH, "path", closed = false,+                points = listOf(north(-300.0), north(300.0)),+            ),+            MapGeometryFeature(+                MapGeometryKind.WATER, "lake", closed = true,+                points = listOf(+                    GeoPoint(100.0 / 111_320.0, 100.0 / 110_540.0),+                    GeoPoint(300.0 / 111_320.0, 100.0 / 110_540.0),+                    GeoPoint(300.0 / 111_320.0, 250.0 / 110_540.0),+                    GeoPoint(100.0 / 111_320.0, 250.0 / 110_540.0),+                ),+            ),+            MapGeometryFeature(+                MapGeometryKind.BUILDING, "building", closed = true,+                points = listOf(+                    GeoPoint(-300.0 / 111_320.0, -200.0 / 110_540.0),+                    GeoPoint(-200.0 / 111_320.0, -200.0 / 110_540.0),+                    GeoPoint(-200.0 / 111_320.0, -100.0 / 110_540.0),+                    GeoPoint(-300.0 / 111_320.0, -100.0 / 110_540.0),+                ),+            ),+        ),+        coveredTiles = 4,+        totalTiles = 4,+    )++    @Test+    fun geometryResultPopulatesRoadsWaterAndBuildings() {+        val geometry = realShapedGeometry()+        val snapshot = buildWearMapSnapshot(+            center, 3L, geometry.toWearRawLines(), emptyList(),+            missingKinds = geometry.wearMissingKinds(),+            sourceTruncated = geometry.truncated,+        )+        assertEquals(emptyList(), snapshot.degraded, "a sourced region is not degraded")+        val kinds = snapshot.lines.map { it.kind }.toSet()+        assertTrue(WearLineKind.ROAD in kinds && WearLineKind.PATH in kinds)+        assertTrue(WearLineKind.WATER in kinds && WearLineKind.BUILDING in kinds)+        assertTrue(snapshot.lines.filter { it.closed }.all {+            it.kind == WearLineKind.WATER || it.kind == WearLineKind.BUILDING+        })+        // Quantized onto the 2 m grid and inside the region.+        assertTrue(snapshot.lines.all { line ->+            line.pts.indices.step(2).all { i ->+                kotlin.math.abs(wearDequantize(line.pts[i])) <= snapshot.radiusM + 2.0+            }+        })+    }++    @Test+    fun unavailableGeometryDegradesEveryBasemapKind() {+        val geometry = MapGeometryResult(+            unsourcedKinds = setOf(+                MapGeometryKind.ROAD, MapGeometryKind.PATH,+                MapGeometryKind.WATER, MapGeometryKind.BUILDING,+            ),+        )+        assertEquals(listOf("roads", "water", "buildings"), geometry.wearMissingKinds())+        val snapshot = buildWearMapSnapshot(+            center, 0L, geometry.toWearRawLines(), emptyList(),+            missingKinds = geometry.wearMissingKinds(),+        )+        assertEquals(listOf("roads", "water", "buildings"), snapshot.degraded)+        assertTrue(snapshot.lines.isEmpty())+    }++    @Test+    fun scannedButEmptyGeometryIsNotDegraded() {+        // The archive was read (tiles covered) and the region simply+        // holds no roads/water/buildings: a complete, empty map.+        val geometry = MapGeometryResult(coveredTiles = 2, totalTiles = 2)+        assertEquals(emptyList(), geometry.wearMissingKinds())+        val snapshot = buildWearMapSnapshot(+            center, 0L, geometry.toWearRawLines(), emptyList(),+            missingKinds = geometry.wearMissingKinds(),+        )+        assertEquals(emptyList(), snapshot.degraded)+    }++    @Test+    fun truncatedGeometryFlagsDetail() {+        val geometry = realShapedGeometry().copy(truncated = true)+        val snapshot = buildWearMapSnapshot(+            center, 0L, geometry.toWearRawLines(), emptyList(),+            missingKinds = geometry.wearMissingKinds(),+            sourceTruncated = geometry.truncated,+        )+        assertTrue(snapshot.truncated)+        assertTrue(snapshot.degraded.contains("detail"))+        assertTrue(snapshot.lines.isNotEmpty(), "capped geometry still draws what came back")+    }+     @Test     fun missingKindsAreNamedHonestly() {         val snapshot = buildWearMapSnapshot(