Modern Apps git

← Modern-Apps.git

library:map: read .mamaps, with kind as a u16 and no MVT decode

Commit
b13497802184fb7b32ea01f5f556d8668fbc4157
Author
vayun-mathur <[email protected]>
When
2026-08-28 00:47 UTC (3 months ago)
Parents
04892a8

Diff

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 a059acf3bb..111539ad12 100644--- a/library/map/src/main/rust/Cargo.toml+++ b/library/map/src/main/rust/Cargo.toml@@ -50,3 +50,10 @@ jni_http = { path = "../../../../jni-http/src/main/rust" } # do anyway. [target.'cfg(target_os = "android")'.dependencies] ash = { version = "0.38", default-features = false, features = ["loaded"] }++# The same codec with its writer, for tests and the host probes only. They read the+# published `v4.pmtiles` and convert each MVT tile to a `.mamaps` body through+# `mamaps::from_mvt`, which is behind the `write` feature -- so the device build links+# the read half and nothing else. There is no published `.mamaps` archive yet.+[dev-dependencies]+tilecodec = { path = "../../../../tilecodec/src/main/rust", features = ["write"] }
library/map/src/main/rust/examples/probe_archive.rs
diff --git a/library/map/src/main/rust/examples/probe_archive.rs b/library/map/src/main/rust/examples/probe_archive.rsindex 9345d91727..f5939fa4a9 100644--- a/library/map/src/main/rust/examples/probe_archive.rs+++ b/library/map/src/main/rust/examples/probe_archive.rs@@ -301,7 +301,11 @@ fn main() {             }         }         let names: Vec<&str> = decoded.layers.iter().map(|l| l.name.as_str()).collect();-        let mesh = geometry::build(&decoded, &layers, tile.z, tile.x, tile.y);+        // Converted rather than read: this probe reads the published `v4.pmtiles`, and the+        // renderer now takes a `.mamaps` body. The MVT analysis above stays MVT, because it is+        // about the upstream archive's own ring structure.+        let (converted, _) = tilecodec::mamaps::from_mvt::from_tile(&decoded).expect("converts");+        let mesh = geometry::build(&converted, &layers, tile.z, tile.x, tile.y);         let triangles: usize = mesh.meshes.iter().map(|m| m.indices.len() / 3).sum();          // Per-layer detail, plus how much of the tile each fill actually covers. A layer
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 84167b68a9..0431f570a6 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -19,7 +19,9 @@ use crate::style::{self, Layer, Palette}; use crate::tile::cache::{RangeCache, DEFAULT_MAX_BYTES}; use crate::tile::geometry::{self, TileMesh}; use crate::tile::select::{self, TileId};-use crate::tile::source::{CachingRangeReader, JniRangeFetcher, BASEMAP_PMTILES_URL, CACHE_FORMAT};+use crate::tile::source::{+    basemap_origin, CachingRangeReader, JniRangeFetcher, BASEMAP_ARCHIVE_URL,+}; use crate::vulkan::context::{ANativeWindow_acquire, ANativeWindow_fromSurface}; use crate::vulkan::renderer::Renderer; use jni::objects::{JClass, JObject, JString};@@ -29,8 +31,7 @@ use std::collections::HashSet; use std::os::raw::c_void; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Arc, Mutex};-use tilecodec::mvt::Tile;-use tilecodec::stream::StreamArchive;+use tilecodec::mamaps::MamapsArchive;  /// The archive's zoom range, shared with the worker that reads it out of the header. ///@@ -213,7 +214,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( /// A worker: opens its own view of the archive, then serves tile requests until the queue /// closes. ///-/// Each worker holds its **own** [`StreamArchive`], so its leaf-directory cache and range+/// Each worker holds its **own** [`MamapsArchive`], so its leaf-index cache and range /// reads need no lock. The cost is one 16 KB header fetch per worker at startup and a /// duplicated leaf cache; the alternative — one archive behind a mutex — would serialise /// exactly the round trips this is meant to overlap. The on-disk range cache is shared, and@@ -231,19 +232,27 @@ fn spawn_worker(         .spawn(move || {             let cache = RangeCache::open(                 cache_dir,-                &format!("{CACHE_FORMAT}|{BASEMAP_PMTILES_URL}"),+                // No `build_id` yet: it is in the header, and the header is read through this+                // cache. Re-checked below, once it is known.+                &basemap_origin(BASEMAP_ARCHIVE_URL, None),                 DEFAULT_MAX_BYTES,             );-            let reader = CachingRangeReader::new(BASEMAP_PMTILES_URL, cache, JniRangeFetcher);+            let reader = CachingRangeReader::new(BASEMAP_ARCHIVE_URL, cache, JniRangeFetcher);             reader.set_online(online.get()); -            let mut archive = match StreamArchive::open(reader) {+            let mut archive = match MamapsArchive::open(reader) {                 Ok(a) => a,                 Err(e) => {-                    log(&format!("worker {index} cannot open the pmtiles archive: {e}"));+                    log(&format!("worker {index} cannot open the mamaps archive: {e}"));                     return;                 }             };+            // Now the `build_id` is known, so the cache can be told which build it holds. A+            // republish under the same name wipes it here rather than serving byte offsets from+            // the build before.+            archive+                .reader()+                .reset_origin(&basemap_origin(BASEMAP_ARCHIVE_URL, Some(archive.header.build_id)));             // Publish the real range. Until this lands the renderer works from a guess, and             // a guess that is too high asks for a zoom the archive does not contain and             // silently gets nothing back.@@ -261,18 +270,13 @@ fn spawn_worker(                 let key = tile.key();                  let result = match archive.tile(tile.z, tile.x, tile.y) {-                    Ok(Some(body)) => match Tile::decode(&body) {-                        Ok(decoded) => TileResult::Ready(geometry::build(-                            &decoded, &layers, tile.z, tile.x, tile.y,-                        )),-                        Err(e) => {-                            log(&format!(-                                "tile {}/{}/{} did not decode: {e}",-                                tile.z, tile.x, tile.y-                            ));-                            TileResult::Failed-                        }-                    },+                    Ok(Some(body)) => TileResult::Ready(geometry::build(+                        &body,+                        layers,+                        tile.z,+                        tile.x,+                        tile.y,+                    )),                     Ok(None) => TileResult::Absent,                     Err(e) => {                         log(&format!("tile {}/{}/{} failed: {e}", tile.z, tile.x, tile.y));
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 c4ac678428..4dbee63ffc 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -42,6 +42,7 @@ pub mod paint;  use paint::{Ramp, Stroke};+use tilecodec::mamaps::dict;  /// What pipeline a layer draws with. #[derive(Clone, Copy, PartialEq, Eq, Debug)]@@ -107,9 +108,20 @@ pub struct Layer {     pub id: String,     /// The tile layer to read, e.g. `roads`.     pub source_layer: String,+    /// The same layer, as the id a `.mamaps` body carries.+    ///+    /// Resolved once at load through [`tilecodec::mamaps::dict::LAYERS`], so the render path never+    /// compares a string. A `source` the schema has no id for fails the load.+    pub source_layer_id: u8,     pub kind: LayerKind,     /// Feature `kind` values to draw, or empty for every feature in the layer.     pub kinds: Vec<String>,+    /// The same whitelist as interned ids, sorted.+    ///+    /// The hot path: `tile::geometry` tests every feature of every layer of every tile against+    /// this, and reading a `kind` used to mean a `String` allocation per feature per tile. A name+    /// the schema cannot emit fails the load rather than silently drawing nothing.+    pub kind_ids: Vec<u16>,     /// ARGB in light mode.     pub light: u32,     /// ARGB in dark mode.@@ -142,9 +154,26 @@ pub struct Layer { }  impl Layer {-    /// Does this layer draw a feature whose `kind` is `kind`?+    /// Does this layer draw a feature whose interned `kind` is `kind`?+    ///+    /// The whole of the attribute filtering the renderer does, and all the style asks for.+    pub fn matches_id(&self, kind: u16) -> bool {+        self.kind_ids.is_empty() || self.kind_ids.binary_search(&kind).is_ok()+    }++    /// Does this layer draw a feature whose `kind` is named `kind`?+    ///+    /// Delegates to [`matches_id`](Self::matches_id) rather than comparing strings, so the two can+    /// never disagree. For tests and diagnostics; nothing on the render path takes a name.     pub fn matches(&self, kind: Option<&str>) -> bool {-        self.kinds.is_empty() || kind.is_some_and(|k| self.kinds.iter().any(|own| own == k))+        match kind {+            None => self.matches_id(dict::NONE),+            Some(name) => match kind_id(name) {+                Some(id) => self.matches_id(id),+                // A name the schema cannot emit. Not drawn, because no feature can carry it.+                None => false,+            },+        }     }      /// Is this layer worth asking the archive for at `zoom`?@@ -205,6 +234,11 @@ impl Layer {     } } +/// A `kind` name's interned id, or `None` when the schema has no counterpart.+fn kind_id(name: &str) -> Option<u16> {+    dict::KINDS.iter().position(|k| *k == name).map(|i| i as u16 + 1)+}+ /// Behind everything, before any tile has loaded. /// /// This is the **water** colour, not the land colour. The sea is the thing a world map is@@ -407,8 +441,34 @@ mod tests {         assert!(!highway.matches(None), "a feature with no kind is not a highway");          let earth = find("earth");-        assert!(earth.matches(None), "an unfiltered layer draws everything");-        assert!(earth.matches(Some("anything")));+        assert!(earth.matches(None), "an unfiltered layer draws a feature with no kind");+        assert!(earth.matches(Some("island")), "and every kind the schema can emit");+        assert!(earth.matches(Some("ocean")));+        // A name the schema has no id for cannot be on a feature at all, so nothing draws it.+        // Interning the whitelist is what turns that from a silent miss into an impossibility.+        assert!(!earth.matches(Some("not_a_kind")));+    }++    /// The interned whitelist and the authored names must agree, or the render path filters on+    /// something other than what the style says.+    #[test]+    fn the_interned_whitelist_is_the_authored_one() {+        for l in layers() {+            assert_eq!(+                l.kind_ids.len(),+                l.kinds.len(),+                "`{}` lost a kind when its whitelist was interned",+                l.id,+            );+            for name in &l.kinds {+                assert!(l.matches(Some(name)), "`{}` should draw `{name}`", l.id);+            }+            assert!(l.kind_ids.windows(2).all(|p| p[0] < p[1]), "`{}` is not sorted", l.id);+        }+        // And every layer reads a source the archive actually carries.+        let roads = find("roads-highway");+        assert_eq!(roads.source_layer_id, dict::LAYER_ROADS);+        assert_eq!(find("earth").source_layer_id, dict::LAYER_EARTH);     }      #[test]
library/map/src/main/rust/src/style/paint.rs
diff --git a/library/map/src/main/rust/src/style/paint.rs b/library/map/src/main/rust/src/style/paint.rsindex 60967c0b1c..557cfed653 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -49,6 +49,7 @@ use super::{Layer, LayerKind}; use serde_json::Value as Json; use std::sync::OnceLock;+use tilecodec::mamaps::dict;  /// The flat style, vendored beside the sources. ///@@ -280,22 +281,46 @@ fn layer(json: &Json) -> Result<Layer, String> {         },         Some(_) => return Err(format!("`{id}`'s dash must be `[on, off]`")),     };+    let kinds: Vec<String> = match json.get("kinds") {+        None => Vec::new(),+        Some(Json::Array(kinds)) => kinds+            .iter()+            .map(|kind| {+                kind.as_str()+                    .map(str::to_string)+                    .ok_or_else(|| format!("`{id}`'s kinds must be strings"))+            })+            .collect::<Result<_, _>>()?,+        Some(_) => return Err(format!("`{id}`'s kinds must be an array")),+    };+    // Both halves of the schema closure the plan asks for: a `source` or a `kind` the archive+    // cannot carry is a build failure, not a layer that quietly draws nothing on device.+    let source = string("source")?;+    let source_layer_id = dict::LAYERS+        .iter()+        .position(|name| *name == source)+        .ok_or_else(|| {+            format!("`{id}` reads source layer `{source}`, which no .mamaps archive carries")+        })? as u8;+    let mut kind_ids = kinds+        .iter()+        .map(|name| {+            super::kind_id(name).ok_or_else(|| {+                format!("`{id}` filters on kind `{name}`, which the schema cannot emit")+            })+        })+        .collect::<Result<Vec<u16>, _>>()?;+    // Sorted so the render path's membership test is a binary search over a `u16` slice.+    kind_ids.sort_unstable();+    kind_ids.dedup();+     Ok(Layer {-        source_layer: string("source")?,+        source_layer: source,+        source_layer_id,         authored: string("authored")?,         kind,-        kinds: match json.get("kinds") {-            None => Vec::new(),-            Some(Json::Array(kinds)) => kinds-                .iter()-                .map(|kind| {-                    kind.as_str()-                        .map(str::to_string)-                        .ok_or_else(|| format!("`{id}`'s kinds must be strings"))-                })-                .collect::<Result<_, _>>()?,-            Some(_) => return Err(format!("`{id}`'s kinds must be an array")),-        },+        kinds,+        kind_ids,         light: color(json.get("light"), &id)?,         dark: color(json.get("dark"), &id)?,         opacity: Ramp::parse(json.get("opacity"), &id, "opacity", 1.0)?,
library/map/src/main/rust/src/tile/cache.rs
diff --git a/library/map/src/main/rust/src/tile/cache.rs b/library/map/src/main/rust/src/tile/cache.rsindex 40909d3f06..582163faf9 100644--- a/library/map/src/main/rust/src/tile/cache.rs+++ b/library/map/src/main/rust/src/tile/cache.rs@@ -201,6 +201,16 @@ impl RangeCache {         }     } +    /// Wipe the cache if `origin` differs from its marker.+    ///+    /// Idempotent and cheap, so it can be called again once something is known that was not known+    /// when the cache was opened. That is exactly the `build_id` case: it lives in the archive+    /// header, which is read *through* this cache, so the marker cannot include it until after the+    /// first read.+    pub fn reset_if_origin_changed(&self, origin: &str) {+        self.invalidate_on_origin_change(origin);+    }+     fn invalidate_on_origin_change(&self, origin: &str) {         let marker = self.dir.join(ORIGIN_FILE);         if fs::read_to_string(&marker).map(|s| s.trim() == origin).unwrap_or(false) {
library/map/src/main/rust/src/tile/geometry.rs
diff --git a/library/map/src/main/rust/src/tile/geometry.rs b/library/map/src/main/rust/src/tile/geometry.rsindex cae1dd0da8..bfc0bba7e1 100644--- a/library/map/src/main/rust/src/tile/geometry.rs+++ b/library/map/src/main/rust/src/tile/geometry.rs@@ -3,11 +3,17 @@ //! Pure CPU and a pure function: no Vulkan types, no JNI, so the expensive half of a //! frame is testable on the host and can run on any thread. This is the step the plan //! expects to be the actual bottleneck — a vector map is slow on the CPU, not the GPU.+//!+//! Reads a `.mamaps` body rather than an MVT tile, and that is most of why the format exists: a+//! feature's `kind` is a `u16` tested against a sorted slice instead of a property-map lookup+//! yielding a `String`, and a part's points are a slice of an already-decoded arena instead of a+//! geometry-command walk. Nothing downstream of here changed — fills are still 2 floats a vertex,+//! strokes 7, and the shaders never saw any of it.  use crate::style::{Layer, LayerKind}; use crate::tess::{fill, stroke}; use crate::tile::select::ANCESTOR_DEPTH;-use tilecodec::mvt::{self, GeomType, Tile, Value};+use tilecodec::mamaps::body::{Body, GEOM_LINE, GEOM_POLYGON};  /// Tessellated geometry for one layer of one tile. pub struct LayerMesh {@@ -39,54 +45,48 @@ pub struct TileMesh { /// So the gate here is the *widest* it could need to be, and the renderer decides what is /// actually visible against the camera's own zoom every frame. Layers outside the window /// are still skipped, which keeps this bounded: a z5 tile does not tessellate buildings.-pub fn build(tile: &Tile, layers: &[Layer], z: u8, x: u32, y: u32) -> TileMesh {+pub fn build(tile: &Body, layers: &[Layer], z: u8, x: u32, y: u32) -> TileMesh {     let mut meshes = Vec::with_capacity(layers.len());     let deepest = z.saturating_add(ANCESTOR_DEPTH);+    let extent = tile.extent as u32;      for (index, layer) in layers.iter().enumerate() {         if layer.min_zoom > deepest || layer.max_zoom < z {             continue;         }-        let source = match tile.layer(&layer.source_layer) {-            Some(l) => l,-            None => continue,-        };+        let Some(source) = tile.layer(layer.source_layer_id) else { continue };          let mut vertices: Vec<f32> = Vec::new();         let mut indices: Vec<u32> = Vec::new();-        let extent = source.extent;          for feature in &source.features {-            let kind = feature.get("kind").and_then(as_str);-            if !layer.matches(kind) {+            // Two `u16` compares against a sorted slice. This used to be a `String` allocation and+            // a property-map lookup per feature per tile.+            if !layer.matches_id(feature.kind) {                 continue;             }+            let parts = source.parts_of(feature);             match layer.kind {                 LayerKind::Fill => {-                    if feature.geom_type != GeomType::Polygon {+                    if feature.geom_type != GEOM_POLYGON {                         continue;                     }-                    if let Some(polygons) = mvt::decode_polygons(&feature.geometry) {-                        for rings in &polygons {-                            fill::tessellate(rings, extent, &mut vertices, &mut indices);-                        }-                    }+                    // A feature's parts are exactly one exterior and its holes, which is what the+                    // tessellator takes: the encoder splits a multipolygon into one feature per+                    // ring group rather than making every consumer regroup them.+                    let rings: Vec<Vec<(i32, i32)>> =+                        parts.iter().map(|part| widen(source.points(part))).collect();+                    fill::tessellate(&rings, extent, &mut vertices, &mut indices);                 }                 LayerKind::Line => {                     // Polygons contribute their outlines too: a lake's shoreline and an                     // administrative boundary are both lines drawn over an area feature.-                    let parts: Vec<Vec<(i32, i32)>> = match feature.geom_type {-                        GeomType::LineString => mvt::decode_lines(&feature.geometry).unwrap_or_default(),-                        GeomType::Polygon => mvt::decode_polygons(&feature.geometry)-                            .unwrap_or_default()-                            .into_iter()-                            .flatten()-                            .collect(),-                        _ => continue,-                    };+                    if !matches!(feature.geom_type, GEOM_LINE | GEOM_POLYGON) {+                        continue;+                    }                     let gapped = layer.gapped();-                    for part in &parts {-                        let flat = flatten(part);+                    for part in parts {+                        let flat = flatten(source.points(part));                         stroke::stroke(&flat, extent, gapped, &mut vertices, &mut indices);                     }                 }@@ -102,25 +102,21 @@ pub fn build(tile: &Tile, layers: &[Layer], z: u8, x: u32, y: u32) -> TileMesh {     TileMesh { z, x, y, meshes } } -/// `[(x, y)]` to the flat `[x, y, ...]` the tessellators take.-fn flatten(points: &[(i32, i32)]) -> Vec<i32> {+/// `[(i16, i16)]` to the `[(i32, i32)]` the fill tessellator takes.+fn widen(points: &[(i16, i16)]) -> Vec<(i32, i32)> {+    points.iter().map(|&(x, y)| (x as i32, y as i32)).collect()+}++/// `[(i16, i16)]` to the flat `[x, y, ...]` the stroke tessellator takes.+fn flatten(points: &[(i16, i16)]) -> Vec<i32> {     let mut out = Vec::with_capacity(points.len() * 2);     for &(x, y) in points {-        out.push(x);-        out.push(y);+        out.push(x as i32);+        out.push(y as i32);     }     out } -/// The `kind` property, the Protomaps schema's own classification. Every layer of the-/// style keys off it.-fn as_str(value: &Value) -> Option<&str> {-    match value {-        Value::String(s) => Some(s.as_str()),-        _ => None,-    }-}- #[cfg(test)] mod tests {     use super::*;@@ -129,8 +125,16 @@ mod tests {      const REAL_TILE: &[u8] = include_bytes!("../../tests/fixtures/v5ca_z11_tile.mvt"); -    fn real() -> Tile {-        Tile::decode(REAL_TILE).expect("the published tile decodes")+    /// The published tile, converted to a `.mamaps` body.+    ///+    /// The fixture is still MVT because it was lifted out of the published archive with a ranged+    /// GET, and there is no published `.mamaps` archive yet. Going through `from_mvt` is what+    /// Phase 4 of the plan is: the container and this module are validated on data the tiler+    /// already produced and the app already drew, before any tag→kind schema work exists to be+    /// wrong.+    fn real() -> Body {+        let tile = tilecodec::mvt::Tile::decode(REAL_TILE).expect("the published tile decodes");+        tilecodec::mamaps::from_mvt::from_tile(&tile).expect("converts").0     }      fn mesh_for<'a>(mesh: &'a TileMesh, layers: &[Layer], id: &str) -> Option<&'a LayerMesh> {@@ -316,7 +320,7 @@ mod tests {     #[test]     fn an_empty_tile_produces_no_meshes() {         let layers = style::layers();-        let mesh = build(&Tile::new(), &layers, 11, 0, 0);+        let mesh = build(&Body::new(4096), &layers, 11, 0, 0);         assert!(mesh.meshes.is_empty());     } @@ -326,8 +330,10 @@ mod tests {         let outline = vec![Layer {             id: "water-edge".to_string(),             source_layer: "water".to_string(),+            source_layer_id: tilecodec::mamaps::dict::LAYER_WATER,             kind: LayerKind::Line,             kinds: Vec::new(),+            kind_ids: Vec::new(),             light: 0xFF000000,             dark: 0xFF000000,             opacity: Ramp::constant(1.0),@@ -342,4 +348,49 @@ mod tests {         assert_eq!(mesh.meshes.len(), 1, "the water polygons' outlines stroke");         assert!(!mesh.meshes[0].indices.is_empty());     }+    /// **The Phase 4 milestone, end to end inside this crate.** A `.mamaps` archive is built,+    /// opened through a `RangeReader`, and tessellated -- so the container, the reader, the style's+    /// interned ids and this module are proven together, on data the tiler already produced.+    #[test]+    fn a_tile_read_out_of_a_mamaps_archive_tessellates() {+        use std::cell::RefCell;+        use tilecodec::mamaps::write::{Options, StreamWriter};+        use tilecodec::mamaps::MamapsArchive;+        use tilecodec::stream::RangeReader;++        struct Memory {+            bytes: Vec<u8>,+            requests: RefCell<usize>,+        }+        impl RangeReader for Memory {+            fn read(&self, offset: u64, length: u32) -> tilecodec::proto::Result<Vec<u8>> {+                *self.requests.borrow_mut() += 1;+                if offset >= self.bytes.len() as u64 {+                    return Ok(Vec::new());+                }+                let end = (offset + length as u64).min(self.bytes.len() as u64);+                Ok(self.bytes[offset as usize..end as usize].to_vec())+            }+        }++        let id = tilecodec::pmtiles::tile_id(11, 339, 770);+        let options = Options { min_zoom: 0, max_zoom: 14, ..Options::default() };+        let mut writer = StreamWriter::new(options).expect("options");+        writer.append(id, &real()).expect("append");+        let bytes = writer.finish().expect("finish");++        let mut archive =+            MamapsArchive::open(Memory { bytes, requests: RefCell::new(0) }).expect("open");+        assert_eq!(*archive.reader().requests.borrow(), 1, "a cold open is one request");++        let layers = style::layers();+        let body = archive.tile(11, 339, 770).expect("read").expect("present");+        let mesh = build(&body, layers, 11, 339, 770);+        // The same layers the fixture produces when tessellated directly, so nothing was lost+        // between the encoder and the reader.+        for id in ["earth", "water", "roads-major", "roads-major-casing"] {+            assert!(mesh_for(&mesh, layers, id).is_some(), "{id} should draw");+        }+        assert!(mesh_for(&mesh, layers, "buildings").is_none(), "the tile has no buildings");+    } }
library/map/src/main/rust/src/tile/source.rs
diff --git a/library/map/src/main/rust/src/tile/source.rs b/library/map/src/main/rust/src/tile/source.rsindex 1ce48b43cc..5319c9dd52 100644--- a/library/map/src/main/rust/src/tile/source.rs+++ b/library/map/src/main/rust/src/tile/source.rs@@ -33,12 +33,44 @@ use tilecodec::stream::RangeReader; /// without the `pmtiles://` scheme prefix MapLibre needs to route it. pub const BASEMAP_PMTILES_URL: &str = "https://data.vayunmathur.com/v4.pmtiles"; +/// Where this renderer reads its tiles from.+///+/// **Not published yet.** This renderer now reads `.mamaps`, and no `.mamaps` archive has been+/// built and uploaded — that is the last phase of the plan. Until then the constant names where the+/// archive will live and the device path has nothing to open; the host probes convert `v4.pmtiles`+/// tile by tile through `mamaps::from_mvt` instead, which is what validated everything below it.+///+/// Left pointing at the PMTiles URL rather than a guessed filename, so nothing fetches a 404 and+/// the substitution is one deliberate edit when the archive exists.+pub const BASEMAP_ARCHIVE_URL: &str = BASEMAP_PMTILES_URL;+ /// Bumped when the on-disk cache layout changes, so old entries are dropped rather than /// misread. The URL is in the marker too, because the archive is republished under the /// same name and a cached directory chunk addresses the byte offsets of the build it came /// from. pub const CACHE_FORMAT: &str = "v1"; +/// The cache's origin marker: the layout version, the URL, and the archive's own `build_id`.+///+/// `build_id` is what makes republishing under a stable name safe. The URL alone is not enough —+/// it is deliberately the *same* URL every build, so a cached leaf index would otherwise keep+/// addressing byte offsets from the build it came from, and a user would sit on a stale map+/// forever with no way to notice.+///+/// It arrives in two steps because of an ordering problem with no way around it: the `build_id`+/// lives in the archive header, and the header is read *through* this cache. So the cache opens on+/// `None`, the archive opens, and then [`CachingRangeReader::reset_origin`] is called with the id+/// that came back. A prefix served from a stale cache entry reports the stale id, which is+/// correct-but-late: the entry is refetched within the refresh interval, and the wipe happens then.+/// Costs no extra request either way, because the header is already in the prefix a reader has to+/// fetch to open the archive at all.+pub fn basemap_origin(url: &str, build_id: Option<u64>) -> String {+    match build_id {+        None => format!("{CACHE_FORMAT}|{url}"),+        Some(id) => format!("{CACHE_FORMAT}|{url}|{id:#018x}"),+    }+}+ /// What a range fetch returned. pub struct RangeResponse {     pub status: u16,@@ -74,6 +106,13 @@ impl<F: RangeFetcher> CachingRangeReader<F> {         self.online.store(online, std::sync::atomic::Ordering::Relaxed);     } +    /// Re-check the cache's origin marker, now that the archive's `build_id` is known.+    ///+    /// See [`basemap_origin`] for why this is a second step rather than part of opening the cache.+    pub fn reset_origin(&self, origin: &str) {+        self.cache.reset_if_origin_changed(origin);+    }+     fn is_online(&self) -> bool {         self.online.load(std::sync::atomic::Ordering::Relaxed)     }