Modern Apps git

← Modern-Apps.git

maps: mamaps_build, an .osm.pbf to .mamaps generator for water

Commit
3d78b4517b9c797d3660ce8b0b91893c9c54a0aa
Author
vayun-mathur <[email protected]>
When
2026-08-28 01:01 UTC (3 months ago)
Parents
b134978

Diff

scripts/maps/mamaps_build/Cargo.lock
diff --git a/scripts/maps/mamaps_build/Cargo.lock b/scripts/maps/mamaps_build/Cargo.locknew file mode 100644index 0000000000..a1fb989653--- /dev/null+++ b/scripts/maps/mamaps_build/Cargo.lock@@ -0,0 +1,102 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "either"+version = "1.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"++[[package]]+name = "mamaps_build"+version = "0.1.0"+dependencies = [+ "osm_ingest",+ "tile_build",+ "tilecodec",+]++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+]++[[package]]+name = "osm_ingest"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+ "rayon",+]++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "tile_build"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+ "rayon",+ "tilecodec",+]++[[package]]+name = "tilecodec"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+]
scripts/maps/mamaps_build/Cargo.toml
diff --git a/scripts/maps/mamaps_build/Cargo.toml b/scripts/maps/mamaps_build/Cargo.tomlnew file mode 100644index 0000000000..9896650d78--- /dev/null+++ b/scripts/maps/mamaps_build/Cargo.toml@@ -0,0 +1,40 @@+# The `.mamaps` generator: one `.osm.pbf` in, one archive out.+#+# DETACHED from both workspaces (the empty `[workspace]` table below), like every+# other host tool under `scripts/maps`: it is built for the host with the host+# toolchain, while `library/map` is a cdylib cross-compiled for+# aarch64-linux-android, and being a member of either workspace would drag that+# workspace's toolchain, profiles and lockfile into the other's build.+#+# Three path dependencies, all already in the tree:+#+#   * `tilecodec` with `write`, for the container. The same code the renderer reads+#     with, so the two cannot drift.+#   * `tile_build`, for the geometry: projection, per-vertex significance,+#     simplification, tile bisection and clipping. That is the part with years of+#     correctness in it and none of it is re-derived here.+#   * `osm_ingest`, for the PBF reader, the node coordinate table, ring assembly and+#     the tag pre-screen.++[package]+name = "mamaps_build"+version = "0.1.0"+edition = "2021"+publish = false+license = "GPL-2.0-only"+description = "Build a .mamaps basemap archive from an OpenStreetMap PBF extract"++[[bin]]+name = "mamaps_build"+path = "src/main.rs"++[dependencies]+tilecodec = { path = "../../../library/tilecodec/src/main/rust", features = ["write"] }+tile_build = { path = "../tile_build" }+osm_ingest = { path = "../osm_ingest" }++[profile.release]+opt-level = 3++# Detach from both the repo-root Android workspace and the other host tools'.+[workspace]
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsnew file mode 100644index 0000000000..ad92014edc--- /dev/null+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -0,0 +1,302 @@+//! Stage A: `.osm.pbf` in, classified geometry in lon/lat out.+//!+//! Three passes, because a PBF is ordered nodes-then-ways-then-relations and a way's geometry needs+//! coordinates that arrived before its tags did:+//!+//! 1. **ways + relations.** Classify tags. Keep the node refs of every classified way and the member+//!    way ids of every classified relation. Node blobs are skipped outright.+//! 2. **ways again**, keeping the refs of the ways that turned out to be relation members. A second+//!    pass rather than keeping every untagged way's refs from the first, because "every untagged way+//!    in California" is 40 M node ids and the members are a few thousand.+//! 3. **nodes.** Fill coordinates for exactly the ids the first two passes asked for, at 16 bytes+//!    per needed node.+//!+//! That last point is the whole memory argument. [`osm_ingest::nodeloc::NodeLocations`] costs+//! `O(needed)`; `graph_build`'s bitset costs 2.5 GB keyed by raw OSM node id whatever the extract,+//! and peaks near 10 GB on California. A water-and-buildings build needs a few million nodes, so it+//! pays tens of megabytes.++use std::collections::HashMap;+use std::path::Path;++use osm_ingest::nodeloc::{resolve_nodes, NodeLocations};+use osm_ingest::osm::{visit_block, Element, MEMBER_WAY};+use osm_ingest::pbf::{self, KIND_RELATIONS, KIND_WAYS};+use osm_ingest::proto::Result;+use osm_ingest::rings::{self, MemberWay, RingStats};+use osm_ingest::select::Select;+use tile_build::geom::Geometry;++use crate::schema::{self, Class, Layers};++/// One classified feature, in lon/lat, ready to tile.+pub struct Feature {+    pub class: Class,+    pub geometry: Geometry,+}++/// What a run of stage A did, for the build report.+#[derive(Debug, Default, Clone)]+pub struct Stats {+    pub ways_classified: u64,+    pub relations_classified: u64,+    pub features: u64,+    /// Classified elements whose geometry could not be built — an extract cut through them, or a+    /// relation's rings would not close.+    pub geometry_failed: u64,+    pub nodes_needed: u64,+    pub rings: RingStats,+}++/// A classified way, held between passes.+struct Way {+    class: Class,+    refs: Vec<i64>,+}++/// A classified relation, held between passes.+struct Relation {+    class: Class,+    /// `(way id, role is inner)`, in the order the relation lists them, which is what+    /// [`rings::assemble`] stitches.+    members: Vec<(i64, bool)>,+}++/// Read `input` and return every feature the schema classifies.+pub fn extract(input: &Path, layers: Layers) -> Result<(Vec<Feature>, Stats)> {+    let blobs = pbf::scan_blobs(input)?;+    let select = Select::parse(&schema::filters(layers))?;+    let mut stats = Stats::default();++    // --- pass 1: ways and relations -------------------------------------------------------+    //+    // `blob_kinds` comes back from this pass and lets the later ones skip whole blobs, which on a+    // planet extract is most of the file.+    let (chunks, blob_kinds) = pbf::run_pass(+        input,+        &blobs,+        None,+        KIND_WAYS | KIND_RELATIONS,+        "Pass 1: ways and relations",+        || (Vec::<(i64, Way)>::new(), Vec::<Relation>::new()),+        |state, block| {+            let mut kinds = 0u8;+            visit_block(block, KIND_WAYS | KIND_RELATIONS, &mut kinds, &mut |el| {+                match el {+                    Element::Way(way) => {+                        if !select.matches(|k| way.tags.get_str(k)) {+                            return Ok(());+                        }+                        if let Some(class) = schema::classify(&way.tags, true, layers) {+                            state.0.push((way.id, Way { class, refs: way.refs.to_vec() }));+                        }+                    }+                    Element::Relation(relation) => {+                        // `type=multipolygon` is what makes a relation an area. A route or a+                        // boundary relation carrying a water tag is not a lake.+                        if relation.tags.get_str("type") != Some("multipolygon") {+                            return Ok(());+                        }+                        if !select.matches(|k| relation.tags.get_str(k)) {+                            return Ok(());+                        }+                        if let Some(class) = schema::classify(&relation.tags, false, layers) {+                            let members = relation+                                .members+                                .iter()+                                .filter(|m| m.kind == MEMBER_WAY)+                                .map(|m| (m.id, m.role == b"inner"))+                                .collect();+                            state.1.push(Relation { class, members });+                        }+                    }+                    Element::Node(_) => {}+                }+                Ok(())+            })?;+            Ok(kinds)+        },+    )?;++    let mut ways: HashMap<i64, Way> = HashMap::new();+    let mut relations: Vec<Relation> = Vec::new();+    for (chunk_ways, chunk_relations) in chunks {+        ways.extend(chunk_ways);+        relations.extend(chunk_relations);+    }+    stats.ways_classified = ways.len() as u64;+    stats.relations_classified = relations.len() as u64;++    // --- pass 2: the member ways pass 1 did not keep --------------------------------------+    let wanted: Vec<i64> = {+        let mut wanted: Vec<i64> = relations+            .iter()+            .flat_map(|r| r.members.iter().map(|(id, _)| *id))+            .filter(|id| !ways.contains_key(id))+            .collect();+        wanted.sort_unstable();+        wanted.dedup();+        wanted+    };+    let mut members: HashMap<i64, Vec<i64>> = HashMap::new();+    if !wanted.is_empty() {+        let (chunks, _) = pbf::run_pass(+            input,+            &blobs,+            Some(&blob_kinds),+            KIND_WAYS,+            "Pass 2: member ways",+            Vec::<(i64, Vec<i64>)>::new,+            |state, block| {+                let mut kinds = 0u8;+                visit_block(block, KIND_WAYS, &mut kinds, &mut |el| {+                    if let Element::Way(way) = el {+                        if wanted.binary_search(&way.id).is_ok() {+                            state.push((way.id, way.refs.to_vec()));+                        }+                    }+                    Ok(())+                })?;+                Ok(kinds)+            },+        )?;+        for chunk in chunks {+            members.extend(chunk);+        }+    }++    // --- pass 3: the coordinates those two asked for --------------------------------------+    let mut needed: Vec<i64> = Vec::new();+    for way in ways.values() {+        needed.extend_from_slice(&way.refs);+    }+    for refs in members.values() {+        needed.extend_from_slice(refs);+    }+    for relation in &relations {+        for (id, _) in &relation.members {+            if let Some(way) = ways.get(id) {+                needed.extend_from_slice(&way.refs);+            }+        }+    }+    let table = NodeLocations::new(needed);+    stats.nodes_needed = table.len() as u64;+    let table = resolve_nodes(input, &blobs, &blob_kinds, "Pass 3: nodes", table)?;++    // --- materialise ----------------------------------------------------------------------+    //+    // Ways in **id order**, not hash order, because the output has to be reproducible and a+    // `HashMap`'s iteration is not. The one place in this pipeline where that is a real risk.+    let mut out = Vec::with_capacity(ways.len() + relations.len());+    let mut ids: Vec<i64> = ways.keys().copied().collect();+    ids.sort_unstable();+    for id in ids {+        let way = &ways[&id];+        let line = table.line(&way.refs);+        match way_geometry(&line, way.class.area) {+            Some(geometry) => {+                out.push(Feature { class: way.class, geometry });+                stats.features += 1;+            }+            None => stats.geometry_failed += 1,+        }+    }+    for relation in &relations {+        let member_ways: Vec<MemberWay> = relation+            .members+            .iter()+            .filter_map(|(id, inner)| {+                let refs = ways.get(id).map(|w| &w.refs).or_else(|| members.get(id))?;+                Some(MemberWay { refs: refs.clone(), outer: !inner })+            })+            .collect();+        let polygons = rings::assemble(&member_ways, |id| locate(&table, id), &mut stats.rings);+        if polygons.is_empty() {+            stats.geometry_failed += 1;+            continue;+        }+        out.push(Feature {+            class: relation.class,+            geometry: Geometry::Polygons(polygons),+        });+        stats.features += 1;+    }+    Ok((out, stats))+}++/// A node's location in lon/lat, which is the order [`rings::assemble`] and GeoJSON both want.+///+/// [`NodeLocations::get`] returns lat/lon, matching the PBF's own field order.+fn locate(table: &NodeLocations, id: i64) -> Option<(f64, f64)> {+    let (lat_e7, lon_e7) = table.get(id)?;+    Some((lon_e7 as f64 * 1e-7, lat_e7 as f64 * 1e-7))+}++/// A way's coordinates as the geometry its class says it is.+///+/// A closed way is a ring only if the tags call it an area; the same shape is a cul-de-sac+/// otherwise. A ring that does not close is closed here rather than dropped, which is what+/// `osmium`'s own export does — an extract cut through the way is the usual reason.+fn way_geometry(line: &[(f64, f64)], area: bool) -> Option<Geometry> {+    if !area {+        return (line.len() >= 2).then(|| Geometry::Lines(vec![line.to_vec()]));+    }+    // Three distinct points at minimum, plus the closing one.+    if line.len() < 3 {+        return None;+    }+    let mut ring = line.to_vec();+    if ring.first() != ring.last() {+        ring.push(ring[0]);+    }+    if ring.len() < 4 {+        return None;+    }+    Some(Geometry::Polygons(vec![vec![ring]]))+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn an_open_way_is_a_line_and_a_closed_one_an_area_only_if_tagged() {+        let square = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)];+        // Tagged an area: a ring.+        match way_geometry(&square, true).expect("area") {+            Geometry::Polygons(polygons) => {+                assert_eq!(polygons.len(), 1);+                assert_eq!(polygons[0][0].len(), 5, "already closed, so nothing is added");+            }+            other => panic!("{other:?}"),+        }+        // The same shape untagged: a loop road, which is a line.+        assert!(matches!(way_geometry(&square, false), Some(Geometry::Lines(_))));+    }++    /// An extract that cuts through a way leaves it unclosed. Closing it is what `osmium export`+    /// does; dropping it would punch a hole in the coastline at every extract boundary.+    #[test]+    fn an_unclosed_area_is_closed_rather_than_dropped() {+        let open = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)];+        match way_geometry(&open, true).expect("closed") {+            Geometry::Polygons(polygons) => {+                let ring = &polygons[0][0];+                assert_eq!(ring.len(), 4);+                assert_eq!(ring.first(), ring.last(), "the ring closes");+            }+            other => panic!("{other:?}"),+        }+    }++    #[test]+    fn a_degenerate_way_produces_nothing() {+        assert!(way_geometry(&[], true).is_none());+        assert!(way_geometry(&[(0.0, 0.0)], true).is_none());+        assert!(way_geometry(&[(0.0, 0.0), (1.0, 1.0)], true).is_none(), "two points bound no area");+        assert!(way_geometry(&[(0.0, 0.0)], false).is_none(), "one point is not a line");+        // But two points are a line.+        assert!(way_geometry(&[(0.0, 0.0), (1.0, 1.0)], false).is_some());+    }+}
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsnew file mode 100644index 0000000000..9bb6fd6525--- /dev/null+++ b/scripts/maps/mamaps_build/src/main.rs@@ -0,0 +1,309 @@+//! `mamaps_build` — one `.osm.pbf` in, one `.mamaps` archive out.+//!+//! The generator this project exists to build. Today it produces `water` and `buildings`; `roads`,+//! `boundaries`, `landcover`, `landuse` and `earth` follow, and the shape does not change when they+//! do because every layer is one module under [`schema`].+//!+//! ```text+//! mamaps_build --input california.osm.pbf --out california.mamaps+//!              [--layers water,buildings] [--min-zoom 0] [--max-zoom 14]+//!              [--simplification 1.0] [--build-id N] [--report FILE]+//! ```+//!+//! # Why not through the existing tiler+//!+//! `tile_build` already turns GeoJSON-seq into PMTiles, and routing through it would have been less+//! new code. But it would also mean encoding to MVT and decoding again, which loses exactly the+//! attributes this format was built to carry: a road's `is_bridge`, a boundary's numeric admin+//! level, a ring's stated winding. So the geometry is reused — projection, significance,+//! simplification, tile bisection, clipping, all of `tile_build` — and only the last step, turning a+//! clipped shape into bytes, is this crate's.++use std::path::PathBuf;+use std::process::ExitCode;++mod extract;+mod schema;+mod tiler;++fn main() -> ExitCode {+    let args: Vec<String> = std::env::args().collect();+    let mut input: Option<PathBuf> = None;+    let mut out: Option<PathBuf> = None;+    let mut report: Option<PathBuf> = None;+    let mut layers = schema::Layers::all();+    let mut min_zoom = 0u8;+    let mut max_zoom = 14u8;+    let mut simplification = tiler::DEFAULT_SIMPLIFICATION;+    let mut build_id: Option<u64> = None;++    let mut i = 1;+    while i < args.len() {+        let value = |name: &str| -> Result<String, String> {+            args.get(i + 1).cloned().ok_or_else(|| format!("{name} needs a value"))+        };+        let taken = match args[i].as_str() {+            "--input" => value("--input").map(|v| {+                input = Some(PathBuf::from(v));+                2+            }),+            "--out" => value("--out").map(|v| {+                out = Some(PathBuf::from(v));+                2+            }),+            "--report" => value("--report").map(|v| {+                report = Some(PathBuf::from(v));+                2+            }),+            "--layers" => value("--layers").and_then(|v| {+                layers = schema::Layers::parse(&v)?;+                Ok(2)+            }),+            "--min-zoom" => value("--min-zoom").and_then(|v| {+                min_zoom = v.parse().map_err(|_| "--min-zoom must be a number".to_string())?;+                Ok(2)+            }),+            "--max-zoom" => value("--max-zoom").and_then(|v| {+                max_zoom = v.parse().map_err(|_| "--max-zoom must be a number".to_string())?;+                Ok(2)+            }),+            "--simplification" => value("--simplification").and_then(|v| {+                simplification =+                    v.parse().map_err(|_| "--simplification must be a number".to_string())?;+                Ok(2)+            }),+            "--build-id" => value("--build-id").and_then(|v| {+                build_id = Some(v.parse().map_err(|_| "--build-id must be a number".to_string())?);+                Ok(2)+            }),+            "-h" | "--help" => {+                usage();+                return ExitCode::SUCCESS;+            }+            other => Err(format!("unexpected argument '{other}'")),+        };+        match taken {+            Ok(step) => i += step,+            Err(e) => {+                eprintln!("mamaps_build: {e}");+                usage();+                return ExitCode::from(2);+            }+        }+    }++    let (Some(input), Some(out)) = (input, out) else {+        usage();+        return ExitCode::from(2);+    };+    if min_zoom > max_zoom {+        eprintln!("mamaps_build: --min-zoom {min_zoom} is deeper than --max-zoom {max_zoom}");+        return ExitCode::from(2);+    }++    match run(&input, &out, report.as_deref(), layers, min_zoom, max_zoom, simplification, build_id) {+        Ok(()) => ExitCode::SUCCESS,+        Err(e) => {+            eprintln!("mamaps_build: {e}");+            ExitCode::FAILURE+        }+    }+}++#[allow(clippy::too_many_arguments)]+fn run(+    input: &std::path::Path,+    out: &std::path::Path,+    report: Option<&std::path::Path>,+    layers: schema::Layers,+    min_zoom: u8,+    max_zoom: u8,+    simplification: f64,+    build_id: Option<u64>,+) -> Result<(), String> {+    let started = std::time::Instant::now();+    println!("reading {}", input.display());+    let (features, stats) =+        extract::extract(input, layers).map_err(|e| format!("{}: {e}", input.display()))?;+    println!(+        "classified {} way(s) and {} relation(s) -> {} feature(s), {} node(s) resolved",+        stats.ways_classified, stats.relations_classified, stats.features, stats.nodes_needed,+    );+    if stats.geometry_failed > 0 {+        // Expected at an extract's cut edges, and worth reporting because a large count means+        // something else.+        println!("  {} classified element(s) produced no geometry", stats.geometry_failed);+    }++    // The build id identifies the *data*: change the input, the zoom range, the layer set or the+    // simplification and every reader has to drop its cache. Derived rather than asked for, so a+    // forgotten `--build-id` cannot silently republish under the old one.+    let build_id = build_id.unwrap_or_else(|| {+        derive_build_id(input, layers, min_zoom, max_zoom, simplification, stats.features)+    });++    let settings = tiler::Settings { min_zoom, max_zoom, simplification, build_id };+    let (bytes, per_zoom) = tiler::build(&features, &settings).map_err(|e| e.to_string())?;+    tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?;+    std::fs::write(out, &bytes).map_err(|e| format!("cannot write {}: {e}", out.display()))?;++    println!("\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}", "zoom", "tiles", "features", "points", "dropped", "bytes");+    for z in &per_zoom {+        println!(+            "z{:<5}{:>10}{:>12}{:>12}{:>10}{:>12}",+            z.zoom, z.tiles, z.features, z.points, z.dropped, z.bytes,+        );+    }+    println!(+        "\nwrote {} ({} bytes, build_id {build_id:#018x}) in {:.1}s",+        out.display(),+        bytes.len(),+        started.elapsed().as_secs_f64(),+    );+    if let Some(path) = report {+        std::fs::write(path, build_report(&stats, &per_zoom, build_id, bytes.len()))+            .map_err(|e| format!("cannot write {}: {e}", path.display()))?;+        println!("report {}", path.display());+    }+    Ok(())+}++/// Hash the inputs that decide what an archive contains.+///+/// The input's **length and modification time** rather than its bytes: digesting 1.3 GB to decide a+/// cache key would double the build's I/O for a number that only has to change when the data does.+/// A rebuild from an unchanged file therefore keeps its id, which is what makes a byte-identical+/// rebuild byte-identical.+fn derive_build_id(+    input: &std::path::Path,+    layers: schema::Layers,+    min_zoom: u8,+    max_zoom: u8,+    simplification: f64,+    features: u64,+) -> u64 {+    let mut h = 0xcbf2_9ce4_8422_2325u64;+    let mut eat = |bytes: &[u8]| {+        for &b in bytes {+            h ^= b as u64;+            h = h.wrapping_mul(0x100_0000_01b3);+        }+    };+    eat(b"mamaps_build/1");+    eat(input.to_string_lossy().as_bytes());+    if let Ok(meta) = std::fs::metadata(input) {+        eat(&meta.len().to_le_bytes());+        if let Ok(time) = meta.modified() {+            if let Ok(since) = time.duration_since(std::time::UNIX_EPOCH) {+                eat(&since.as_secs().to_le_bytes());+            }+        }+    }+    eat(&[u8::from(layers.water), u8::from(layers.buildings), min_zoom, max_zoom]);+    eat(&simplification.to_le_bytes());+    eat(&features.to_le_bytes());+    // The schema table's own version, so a remapped kind invalidates every cache even when the+    // input has not moved.+    eat(&(tilecodec::mamaps::dict::KINDS.len() as u64).to_le_bytes());+    h+}++/// The build report, as JSON so a script can diff two builds.+fn build_report(+    stats: &extract::Stats,+    per_zoom: &[tiler::ZoomStats],+    build_id: u64,+    bytes: usize,+) -> String {+    let mut out = String::from("{\n");+    out.push_str(&format!("  \"build_id\": \"{build_id:#018x}\",\n"));+    out.push_str(&format!("  \"file_bytes\": {bytes},\n"));+    out.push_str(&format!("  \"ways_classified\": {},\n", stats.ways_classified));+    out.push_str(&format!("  \"relations_classified\": {},\n", stats.relations_classified));+    out.push_str(&format!("  \"features\": {},\n", stats.features));+    out.push_str(&format!("  \"geometry_failed\": {},\n", stats.geometry_failed));+    out.push_str(&format!("  \"nodes_needed\": {},\n", stats.nodes_needed));+    out.push_str("  \"zooms\": [\n");+    for (i, z) in per_zoom.iter().enumerate() {+        out.push_str(&format!(+            "    {{ \"zoom\": {}, \"tiles\": {}, \"features\": {}, \"points\": {}, \+             \"dropped\": {}, \"bytes\": {} }}{}\n",+            z.zoom,+            z.tiles,+            z.features,+            z.points,+            z.dropped,+            z.bytes,+            if i + 1 == per_zoom.len() { "" } else { "," },+        ));+    }+    out.push_str("  ]\n}\n");+    out+}++fn usage() {+    eprintln!(+        "usage: mamaps_build --input IN.osm.pbf --out OUT.mamaps\n\+         \x20                   [--layers water,buildings] [--min-zoom N] [--max-zoom N]\n\+         \x20                   [--simplification F] [--build-id N] [--report FILE]"+    );+}++#[cfg(test)]+mod tests {+    use super::*;++    /// The schema's own floor for buildings and the style's have to agree, or the archive either+    /// carries what nothing draws or is asked for what it does not carry.+    #[test]+    fn the_schema_floor_matches_the_styles() {+        // The style's floor lives in `library/map`'s flat style, which this crate does not link. So+        // this pins the number and names where the other copy is: a change here without a change+        // there shows up as a tile the renderer asks for and does not get.+        assert_eq!(+            schema::buildings::MIN_ZOOM,+            14,+            "buildings' floor is 14 in library/map/src/main/rust/style/basemap.flat.json too",+        );+    }++    /// The id has to change when the data would, and not otherwise. A rebuild from an unchanged file+    /// keeps its id, which is what makes a byte-identical rebuild byte-identical.+    #[test]+    fn a_build_id_follows_the_inputs_that_decide_the_output() {+        let path = std::path::Path::new("nonexistent.osm.pbf");+        let base = derive_build_id(path, schema::Layers::all(), 0, 14, 1.0, 100);+        assert_eq!(base, derive_build_id(path, schema::Layers::all(), 0, 14, 1.0, 100), "stable");+        for other in [+            derive_build_id(path, schema::Layers::all(), 1, 14, 1.0, 100),+            derive_build_id(path, schema::Layers::all(), 0, 15, 1.0, 100),+            derive_build_id(path, schema::Layers::all(), 0, 14, 2.0, 100),+            derive_build_id(path, schema::Layers::all(), 0, 14, 1.0, 101),+            derive_build_id(+                path,+                schema::Layers { water: true, buildings: false },+                0,+                14,+                1.0,+                100,+            ),+            derive_build_id(std::path::Path::new("other.osm.pbf"), schema::Layers::all(), 0, 14, 1.0, 100),+        ] {+            assert_ne!(base, other, "a changed input should change the id");+        }+    }++    #[test]+    fn the_report_is_valid_json_shaped_output() {+        let stats = extract::Stats { features: 3, ..extract::Stats::default() };+        let zooms = vec![+            tiler::ZoomStats { zoom: 0, tiles: 1, features: 3, points: 12, dropped: 0, bytes: 40 },+            tiler::ZoomStats { zoom: 1, tiles: 4, features: 3, points: 20, dropped: 1, bytes: 90 },+        ];+        let report = build_report(&stats, &zooms, 42, 1024);+        assert!(report.starts_with("{\n") && report.ends_with("}\n"));+        assert_eq!(report.matches("\"zoom\":").count(), 2);+        // No trailing comma on the last entry, which is the one thing hand-written JSON gets wrong.+        assert!(!report.contains("},\n  ]"));+    }+}
scripts/maps/mamaps_build/src/schema/buildings.rs
diff --git a/scripts/maps/mamaps_build/src/schema/buildings.rs b/scripts/maps/mamaps_build/src/schema/buildings.rsnew file mode 100644index 0000000000..59153d8076--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/buildings.rs@@ -0,0 +1,106 @@+//! `buildings`: the densest layer in the schema, and the simplest to classify.+//!+//! Two kinds and almost no judgement — `building=*` is a building unless it says `no`. What makes it+//! the expensive layer is volume: a city tile holds thousands, and California holds millions. So the+//! style keeps it off below z14 and the schema does not carry it at all above that floor, which is+//! the same decision made twice for two different reasons — the style's is a draw-call cost, this+//! one is archive bytes.+//!+//! `building:part` is a separate kind because a 3D model tags the parts of a building separately+//! from its footprint, and drawing both means drawing the courtyard of a building twice.++use tilecodec::mamaps::dict::LAYER_BUILDINGS;++use super::{kind, Class, TagSource};++/// The pre-screen.+pub const FILTERS: &[&str] = &["building", "building:part"];++/// Every `kind` this module can emit.+#[cfg_attr(not(test), allow(dead_code))]+pub const KINDS: &[&str] = &["building", "building_part"];++/// The shallowest zoom a building is worth carrying at.+///+/// Matches the style's own floor for the `buildings` layer, so the archive holds nothing the+/// renderer would not draw. The two are independent decisions that happen to agree, and+/// `the_schema_floor_matches_the_styles` in the crate root is what keeps them agreeing.+pub const MIN_ZOOM: u8 = 14;++pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {+    // A part first: a way carrying both is a part of a larger footprint, and drawing it as a+    // footprint too would double-paint the courtyard.+    if tags.truthy("building:part") {+        return Some(Class::area(LAYER_BUILDINGS, kind("building_part"), MIN_ZOOM));+    }+    if tags.truthy("building") {+        return Some(Class::area(LAYER_BUILDINGS, kind("building"), MIN_ZOOM));+    }+    None+}++#[cfg(test)]+mod tests {+    use super::*;+    use tilecodec::mamaps::dict;++    fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {+        super::classify(pairs)+    }++    fn kind_name(class: &Class) -> &'static str {+        dict::KINDS[class.kind as usize - 1]+    }++    #[test]+    fn any_building_value_but_no_is_a_building() {+        // OSM tags a building's *type* in the same key, so the value is not a yes/no in practice:+        // `building=house`, `building=church`, `building=yes` are all buildings.+        for value in ["yes", "house", "church", "industrial", "retail", "1", "true"] {+            let class = classify_tags(&[("building", value)]).expect(value);+            assert_eq!(class.layer, dict::LAYER_BUILDINGS);+            assert_eq!(kind_name(&class), "building");+            assert!(class.area, "a building is an area");+            assert_eq!(class.min_zoom, MIN_ZOOM);+        }+    }++    #[test]+    fn building_no_is_not_a_building() {+        // A real tag: `building=no` marks a way that looks like a building and is not.+        assert!(classify_tags(&[("building", "no")]).is_none());+        assert!(classify_tags(&[("building", "false")]).is_none());+        assert!(classify_tags(&[("building", "0")]).is_none());+    }++    /// A 3D model tags parts separately from the footprint. Both are drawn, so they need different+    /// kinds — otherwise a building with parts paints its courtyard twice.+    #[test]+    fn a_part_is_its_own_kind_and_wins_over_the_footprint() {+        let part = classify_tags(&[("building:part", "yes")]).expect("part");+        assert_eq!(kind_name(&part), "building_part");+        let both = classify_tags(&[("building", "yes"), ("building:part", "yes")]).expect("both");+        assert_eq!(kind_name(&both), "building_part", "the part rule is asked first");+    }++    #[test]+    fn nothing_else_is_a_building() {+        for tags in [+            vec![("natural", "water")],+            vec![("highway", "residential")],+            vec![("building:levels", "3")],+            vec![],+        ] {+            assert!(classify_tags(&tags).is_none(), "{tags:?} should not be a building");+        }+    }++    /// The densest layer in the schema stays off the mid zooms. Without a floor, a z10 tile of a+    /// city is megabytes of footprints nothing draws.+    #[test]+    fn buildings_are_not_carried_below_street_zoom() {+        assert_eq!(MIN_ZOOM, 14);+        let class = classify_tags(&[("building", "yes")]).expect("building");+        assert_eq!(class.min_zoom, 14);+    }+}
scripts/maps/mamaps_build/src/schema/mod.rs
diff --git a/scripts/maps/mamaps_build/src/schema/mod.rs b/scripts/maps/mamaps_build/src/schema/mod.rsnew file mode 100644index 0000000000..40b56c977f--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/mod.rs@@ -0,0 +1,227 @@+//! The tag → kind mapping: OSM tags in, `.mamaps` layer and interned ids out.+//!+//! **The main body of work and the main risk of this whole project.** Planetiler's Protomaps+//! profile is thousands of lines of accumulated judgement, and reproducing it is the thing that+//! takes weeks rather than days. So it lives here, alone, behind one function, with no I/O and no+//! geometry: [`classify`] takes tags and returns a [`Class`] or nothing, which makes every rule in+//! it a unit test rather than a screenshot.+//!+//! # The rules+//!+//! Ordered and **first match wins**, like the `osmium tags-filter` expressions this replaces and+//! like Planetiler's own dispatch. Order is therefore load-bearing: a `natural=water` way that also+//! carries `building=yes` is water, because water is asked first.+//!+//! Every layer is pre-screened by [`osm_ingest::select::Select`] before any rule runs. Tag lookup+//! is a linear scan over a block's string table, so at planet scale it matters a great deal whether+//! the common case reads three tags or thirty.+//!+//! # What a `Class` is not+//!+//! It carries no geometry and no name. Names are the largest thing this format drops — an upstream+//! `water` feature carries forty `name:*` localisations — and nothing in the style reads one.++use tilecodec::mamaps::dict;++pub mod buildings;+pub mod water;++/// Tag lookup, so a rule is a pure function of its tags.+///+/// [`osm_ingest::osm::Tags`] borrows from the PBF block it was decoded out of, which would make+/// every test here a synthetic protobuf. Behind this trait a test is a list of pairs, which is what+/// makes the mapping — the risky part — cheap enough to cover properly.+pub trait TagSource {+    fn get(&self, key: &str) -> Option<&str>;++    fn has(&self, key: &str) -> bool {+        self.get(key).is_some()+    }++    /// Is this tag one of OSM's affirmatives?+    ///+    /// `yes`, `true` and `1` all mean yes, and a bridge tagged `viaduct` is still a bridge. Only+    /// `no` and absence mean no.+    fn truthy(&self, key: &str) -> bool {+        !matches!(self.get(key), None | Some("no") | Some("false") | Some("0"))+    }+}++impl TagSource for osm_ingest::osm::Tags<'_, '_> {+    fn get(&self, key: &str) -> Option<&str> {+        self.get_str(key)+    }+}++/// Tags as a plain list, for tests.+impl TagSource for [(&str, &str)] {+    fn get(&self, key: &str) -> Option<&str> {+        self.iter().find(|(k, _)| *k == key).map(|(_, v)| *v)+    }+}++/// Where a feature goes and what it is, once classified.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Class {+    /// An index into [`dict::LAYERS`].+    pub layer: u8,+    /// An index into [`dict::KINDS`], or [`dict::NONE`].+    pub kind: u16,+    /// An index into [`dict::DETAILS`], a number under [`FLAG_DETAIL_NUMERIC`], or+    /// [`dict::NONE`].+    ///+    /// [`FLAG_DETAIL_NUMERIC`]: tilecodec::mamaps::body::FLAG_DETAIL_NUMERIC+    pub kind_detail: u16,+    pub flags: u8,+    /// Is this an area? Decides whether a closed way becomes a polygon or a line.+    ///+    /// Not derivable from the geometry: a closed way is a ring for a lake and a loop road for a+    /// cul-de-sac, and only the tags say which.+    pub area: bool,+    /// The shallowest zoom this feature is worth carrying at.+    ///+    /// Where most of the upstream profile's judgement lives, and the reason a world tile is not+    /// every pond in California. Compared against the tile's zoom, so a feature simply is not+    /// written above it.+    pub min_zoom: u8,+}++impl Class {+    /// A polygon feature with no detail and no flags.+    pub const fn area(layer: u8, kind: u16, min_zoom: u8) -> Class {+        Class { layer, kind, kind_detail: dict::NONE, flags: 0, area: true, min_zoom }+    }++    /// A line feature with no detail and no flags.+    pub const fn line(layer: u8, kind: u16, min_zoom: u8) -> Class {+        Class { layer, kind, kind_detail: dict::NONE, flags: 0, area: false, min_zoom }+    }+}++/// Look up a `kind` name's id at compile-time-ish cost.+///+/// A linear scan over 79 short strings, called once per classified feature. Interning at+/// classification time rather than at encode time is what keeps the encoder free of names entirely.+///+/// Panics on a name the table does not carry, because every name here is a literal in this crate+/// and `every_kind_this_schema_names_is_in_the_dictionary` proves them all.+pub fn kind(name: &str) -> u16 {+    match dict::KINDS.iter().position(|k| *k == name) {+        Some(index) => index as u16 + 1,+        None => panic!("the schema names kind `{name}`, which the dictionary has no id for"),+    }+}++/// Which layers a build is producing.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct Layers {+    pub water: bool,+    pub buildings: bool,+}++impl Layers {+    pub fn all() -> Layers {+        Layers { water: true, buildings: true }+    }++    /// Parse a comma-separated list, e.g. `water,buildings`.+    pub fn parse(list: &str) -> Result<Layers, String> {+        let mut layers = Layers { water: false, buildings: false };+        for name in list.split(',').map(str::trim).filter(|s| !s.is_empty()) {+            match name {+                "water" => layers.water = true,+                "buildings" => layers.buildings = true,+                other => {+                    return Err(format!(+                        "unknown layer `{other}`; this generator produces water and buildings"+                    ))+                }+            }+        }+        if !layers.water && !layers.buildings {+            return Err("no layers selected".to_string());+        }+        Ok(layers)+    }+}++/// Classify one element's tags, or `None` for the overwhelming majority that are not drawn.+///+/// Ordered and first-match-wins. `is_way` distinguishes a way from a relation, which matters+/// because a closed way's area-ness is a tag question while a multipolygon relation is always an+/// area.+pub fn classify(tags: &(impl TagSource + ?Sized), is_way: bool, layers: Layers) -> Option<Class> {+    if layers.water {+        if let Some(class) = water::classify(tags, is_way) {+            return Some(class);+        }+    }+    if layers.buildings {+        if let Some(class) = buildings::classify(tags) {+            return Some(class);+        }+    }+    None+}++/// The `osmium tags-filter` expressions that pre-screen each layer, as one list.+///+/// Reading three tags to reject a feature instead of the thirty the rules would read between them.+/// A superset of what the rules accept, so a screen that lets something through is harmless and one+/// that rejects something is a bug.+pub fn filters(layers: Layers) -> Vec<&'static str> {+    let mut out = Vec::new();+    if layers.water {+        out.extend_from_slice(water::FILTERS);+    }+    if layers.buildings {+        out.extend_from_slice(buildings::FILTERS);+    }+    out+}++#[cfg(test)]+mod tests {+    use super::*;++    /// Every name this crate writes has to be in the dictionary, or [`kind`] panics at runtime on+    /// whichever feature happens to hit that rule first.+    #[test]+    fn every_kind_this_schema_names_is_in_the_dictionary() {+        for name in water::KINDS.iter().chain(buildings::KINDS) {+            assert!(+                dict::KINDS.contains(name),+                "the schema names `{name}`, which the dictionary has no id for",+            );+            // And the lookup really resolves rather than merely being present.+            assert_eq!(dict::KINDS[kind(name) as usize - 1], *name);+        }+    }++    #[test]+    fn a_layer_list_parses_and_rejects_what_this_generator_cannot_build() {+        assert_eq!(Layers::parse("water").expect("water"), Layers { water: true, buildings: false });+        assert_eq!(Layers::parse("water,buildings").expect("both"), Layers::all());+        assert_eq!(Layers::parse(" buildings , water ").expect("spaces"), Layers::all());+        assert!(Layers::parse("roads").is_err(), "not until phase 6");+        assert!(Layers::parse("").is_err(), "nothing selected");+    }++    #[test]+    fn the_pre_screen_is_a_superset_of_what_the_rules_accept() {+        // Not provable in general, so this pins the shape: the screen is a list of tag *keys* the+        // rules actually read, in osmium's `tags-filter` spelling, and no layer has an empty one —+        // an empty screen would let every element in the file through to the rules.+        let all = filters(Layers::all());+        assert!(!all.is_empty());+        for filter in &all {+            assert!(!filter.is_empty(), "an empty screen matches everything");+            assert!(!filter.contains(' '), "`{filter}` is not a bare tag key");+        }+        assert!(filters(Layers { water: true, buildings: false }).len() < all.len());+        // Every key a rule reads for a *decision* has to be in the screen, or the rule never runs.+        for key in ["natural", "waterway", "landuse", "building"] {+            assert!(all.contains(&key), "the screen omits `{key}`");+        }+    }+}
scripts/maps/mamaps_build/src/schema/water.rs
diff --git a/scripts/maps/mamaps_build/src/schema/water.rs b/scripts/maps/mamaps_build/src/schema/water.rsnew file mode 100644index 0000000000..6b696b5532--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/water.rs@@ -0,0 +1,223 @@+//! `water`: the layer a map is mostly made of.+//!+//! Nine kinds, and the classification is nearly all `natural` and `waterway`. The judgement that+//! matters is not *which* kind — that part is a lookup — but the **minimum zoom**: an ocean belongs+//! on a world tile and a drainage ditch does not, and getting that wrong is the difference between+//! a readable coastline and a z4 tile with forty thousand ponds in it.+//!+//! # `ocean` is not here+//!+//! Upstream's `water/ocean` comes from the same stitched coastline that `earth` does, not from a+//! tag: there is no `natural=ocean` way in OSM. So it arrives with the coastline work, and until+//! then the sea is the renderer's background colour — which is what that colour is for, and why it+//! is the water colour rather than the land one.++use tilecodec::mamaps::dict::LAYER_WATER;++use super::{kind, Class, TagSource};++/// The pre-screen. A superset of what the rules below accept.+pub const FILTERS: &[&str] = &["natural", "waterway", "landuse", "water"];++/// Every `kind` this module can emit, for the dictionary-closure test.+#[cfg_attr(not(test), allow(dead_code))]+pub const KINDS: &[&str] =+    &["bay", "fjord", "lake", "river", "sea", "strait", "stream", "water", "canal", "dock", "reef"];++/// Classify a water feature.+///+/// First match wins. `is_way` decides whether a closed way is a ring or a line, which for water is+/// almost always a ring — a `waterway=river` is the exception, and it is a line even when it closes+/// around an island.+pub fn classify(tags: &(impl TagSource + ?Sized), is_way: bool) -> Option<Class> {+    // `natural=*`, the bulk of it. Areas, every one.+    if let Some(natural) = tags.get("natural") {+        let class = match natural {+            // A sea and a bay carry a whole world tile; a strait or a fjord is a coastal+            // feature that only reads once the coast is on screen.+            "sea" => Some(Class::area(LAYER_WATER, kind("sea"), 0)),+            "bay" => Some(Class::area(LAYER_WATER, kind("bay"), 6)),+            "strait" => Some(Class::area(LAYER_WATER, kind("strait"), 6)),+            "fjord" => Some(Class::area(LAYER_WATER, kind("fjord"), 6)),+            "reef" => Some(Class::area(LAYER_WATER, kind("reef"), 10)),+            // The generic one, and by far the most common. A lake if `water` says so.+            "water" => Some(Class::area(LAYER_WATER, water_kind(tags), water_min_zoom(tags))),+            _ => None,+        };+        if class.is_some() {+            return class;+        }+    }++    // `waterway=*`. Rivers and canals are lines that widen into areas when tagged+    // `area=yes`; a stream is a line and stays one.+    if let Some(waterway) = tags.get("waterway") {+        let area = tags.get("area") == Some("yes") || !is_way;+        let (name, min_zoom) = match waterway {+            // A river is the only waterway a continent-scale map draws.+            "river" => ("river", 8),+            "canal" => ("canal", 10),+            "stream" => ("stream", 12),+            // A ditch or a drain is street-level detail at best, and there are millions.+            "ditch" | "drain" => ("stream", 14),+            "dock" => ("dock", 12),+            _ => return None,+        };+        let id = kind(name);+        return Some(if area {+            Class::area(LAYER_WATER, id, min_zoom)+        } else {+            Class::line(LAYER_WATER, id, min_zoom)+        });+    }++    // A reservoir or a basin is tagged on `landuse`, not `natural`.+    if let Some(landuse) = tags.get("landuse") {+        if matches!(landuse, "reservoir" | "basin") {+            return Some(Class::area(LAYER_WATER, kind("water"), 8));+        }+    }+    None+}++/// Which kind a `natural=water` polygon is, from its `water` tag.+///+/// Upstream distinguishes a lake from the generic `water`, and the style gives them the same colour+/// today — but the distinction is in the schema, so it is carried rather than flattened. A restyle+/// that wants lakes bluer than reservoirs then needs no rebuild.+fn water_kind(tags: &(impl TagSource + ?Sized)) -> u16 {+    match tags.get("water") {+        Some("lake") => kind("lake"),+        Some("river" | "canal") => kind("river"),+        Some("lagoon" | "oxbow" | "pond" | "reservoir" | "basin") => kind("water"),+        _ => kind("water"),+    }+}++/// How shallow a `natural=water` polygon is worth carrying.+///+/// A named lake is a landmark and an unnamed pond is not, and a name is the only signal in the tags+/// that separates them. This is the one place the classifier reads `name` at all — for a *decision*,+/// not to carry it.+fn water_min_zoom(tags: &(impl TagSource + ?Sized)) -> u8 {+    if tags.has("name") {+        6+    } else {+        10+    }+}++#[cfg(test)]+mod tests {+    use super::*;+    use tilecodec::mamaps::dict;++    /// Classify an element carrying exactly these tags.+    fn classify_tags(pairs: &[(&str, &str)], is_way: bool) -> Option<Class> {+        super::classify(pairs, is_way)+    }++    fn kind_name(class: &Class) -> &'static str {+        dict::KINDS[class.kind as usize - 1]+    }++    #[test]+    fn the_natural_tags_classify_as_areas() {+        for (value, expected, min_zoom) in [+            ("sea", "sea", 0u8),+            ("bay", "bay", 6),+            ("strait", "strait", 6),+            ("fjord", "fjord", 6),+            ("reef", "reef", 10),+        ] {+            let class = classify_tags(&[("natural", value)], true).expect(value);+            assert_eq!(kind_name(&class), expected);+            assert_eq!(class.layer, dict::LAYER_WATER);+            assert!(class.area, "{value} is an area");+            assert_eq!(class.min_zoom, min_zoom);+        }+    }++    /// The judgement that matters: a named lake is a landmark from z6, an unnamed pond is street+    /// detail. Without this a z6 tile carries every farm pond in the state.+    #[test]+    fn a_named_water_body_is_carried_far_shallower_than_an_unnamed_one() {+        let named = classify_tags(&[("natural", "water"), ("name", "Lake Tahoe")], true).expect("named");+        let pond = classify_tags(&[("natural", "water")], true).expect("unnamed");+        assert_eq!(named.min_zoom, 6);+        assert_eq!(pond.min_zoom, 10);+        assert!(named.min_zoom < pond.min_zoom);+    }++    #[test]+    fn the_water_tag_picks_the_kind() {+        let lake = classify_tags(&[("natural", "water"), ("water", "lake")], true).expect("lake");+        assert_eq!(kind_name(&lake), "lake");+        let river = classify_tags(&[("natural", "water"), ("water", "river")], true).expect("river");+        assert_eq!(kind_name(&river), "river");+        // Anything else, including an absent tag, is the generic kind rather than dropped.+        let pond = classify_tags(&[("natural", "water"), ("water", "pond")], true).expect("pond");+        assert_eq!(kind_name(&pond), "water");+        let bare = classify_tags(&[("natural", "water")], true).expect("bare");+        assert_eq!(kind_name(&bare), "water");+    }++    /// A river is a line that becomes an area when tagged one, which is how OSM models a wide+    /// river: a centreline way plus a riverbank polygon.+    #[test]+    fn a_waterway_is_a_line_unless_it_says_it_is_an_area() {+        let river = classify_tags(&[("waterway", "river")], true).expect("river");+        assert!(!river.area, "a river centreline is a line");+        assert_eq!(river.min_zoom, 8);+        let bank = classify_tags(&[("waterway", "river"), ("area", "yes")], true).expect("bank");+        assert!(bank.area);+        // A relation is always an area, whatever the tags say: a multipolygon is a multipolygon.+        let relation = classify_tags(&[("waterway", "river")], false).expect("relation");+        assert!(relation.area);+    }++    /// There are millions of ditches and drains. Carrying them above street level is what turns a+    /// mid-zoom tile into a mesh of blue hair.+    #[test]+    fn a_ditch_is_held_back_to_street_zoom_and_a_river_is_not() {+        let ditch = classify_tags(&[("waterway", "ditch")], true).expect("ditch");+        let stream = classify_tags(&[("waterway", "stream")], true).expect("stream");+        let river = classify_tags(&[("waterway", "river")], true).expect("river");+        assert_eq!(ditch.min_zoom, 14);+        assert_eq!(stream.min_zoom, 12);+        assert_eq!(river.min_zoom, 8);+        // A ditch is drawn as a stream: the style has no ditch colour and inventing one would be+        // paint, not data.+        assert_eq!(kind_name(&ditch), "stream");+    }++    #[test]+    fn a_reservoir_is_water_even_though_it_is_tagged_landuse() {+        let reservoir = classify_tags(&[("landuse", "reservoir")], true).expect("reservoir");+        assert_eq!(reservoir.layer, dict::LAYER_WATER);+        assert_eq!(kind_name(&reservoir), "water");+        assert!(classify_tags(&[("landuse", "residential")], true).is_none(), "not water");+    }++    /// First match wins, and `natural` is asked first. A polygon tagged both ways is water, because+    /// a lake with a boathouse on its edge is still a lake.+    #[test]+    fn natural_is_asked_before_waterway() {+        let both = classify_tags(&[("waterway", "stream"), ("natural", "water")], true).expect("both");+        assert_eq!(kind_name(&both), "water", "the natural rule won");+    }++    #[test]+    fn everything_else_is_not_water() {+        for tags in [+            vec![("building", "yes")],+            vec![("highway", "residential")],+            vec![("natural", "wood")],+            vec![("waterway", "weir")],+            vec![("name", "Nowhere")],+            vec![],+        ] {+            assert!(classify_tags(&tags, true).is_none(), "{tags:?} should not be water");+        }+    }+}
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsnew file mode 100644index 0000000000..6b9c1cdcd5--- /dev/null+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -0,0 +1,412 @@+//! Stages B, D and E: features in, one `.mamaps` archive out.+//!+//! Zoom by zoom, and within a zoom tile by tile in ascending tile-id order, which is exactly what+//! [`StreamWriter`] requires. That ordering is free rather than arranged: `pmtiles::tile_id` is+//! zoom-major, so every id at z*n* precedes every id at z*n+1*, and sorting within a zoom finishes+//! it.+//!+//! # What is reused+//!+//! All of the geometry, from `tile_build`:+//!+//! * [`geom::project_geometry`] to web-mercator tile units, carrying per-vertex significance.+//! * [`simplify::annotate`] then [`simplify::filter`], which is significance-first simplification:+//!   a vertex's importance is computed **once** on the whole geometry and only then filtered per+//!   zoom, so the same vertex survives or does not regardless of which tile it lands in. Doing it+//!   the other way round is what lets a shared edge simplify differently on each side and open a+//!   seam.+//! * [`geom::tiles_touched`], whose per-segment bisection is not optional: a transcontinental line+//!   touches 16 632 tiles against 34 535 986 for its bounding box.+//! * [`clip`]'s Liang-Barsky for lines and Sutherland-Hodgman for rings, against a tile rect with a+//!   buffer so a stroke at the edge has geometry to join to.+//!+//! # Memory+//!+//! One zoom's `tile -> features` map at a time, held in memory. The plan's design spills that to+//! disk through `tile_build::spill` and will need to for a planet build; a California+//! water-and-buildings run is a few hundred megabytes, so this does not yet. The shape is the same+//! either way — the writer already streams — so the change is local when it is needed.++use std::collections::BTreeMap;++use tile_build::geom::{self, Geometry, IntGeometry, SigPt};+use tile_build::{clip, simplify};+use tilecodec::mamaps::body::{+    Body, Feature as BodyFeature, Layer as BodyLayer, Part, GEOM_LINE, GEOM_POLYGON, WINDING_HOLE,+    WINDING_OUTER,+};+use tilecodec::mamaps::write::{Options, StreamWriter};+use tilecodec::pmtiles::tile_id;+use tilecodec::proto::{err, Result};++use crate::extract::Feature;++/// The tile grid, matching MVT's so nothing downstream rescales.+pub const EXTENT: u32 = 4096;++/// How aggressively to simplify, as a multiple of `tile_build`'s per-zoom tolerance.+pub const DEFAULT_SIMPLIFICATION: f64 = 1.0;++/// Per-zoom counts for the build report.+#[derive(Debug, Default, Clone, Copy)]+pub struct ZoomStats {+    pub zoom: u8,+    pub tiles: u64,+    pub features: u64,+    pub points: u64,+    /// Features dropped because simplification left nothing, or the clip did.+    pub dropped: u64,+    pub bytes: u64,+}++pub struct Settings {+    pub min_zoom: u8,+    pub max_zoom: u8,+    pub simplification: f64,+    pub build_id: u64,+}++/// Tile every feature and write the archive.+pub fn build(features: &[Feature], settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> {+    let bbox = bounds_e7(features);+    let mut writer = StreamWriter::new(Options {+        min_zoom: settings.min_zoom,+        max_zoom: settings.max_zoom,+        build_id: settings.build_id,+        compress: true,+        // Not until stage C exists. Claiming it would let the renderer skip a repair pass that is+        // still the only thing standing between a bad ring and an earcut hang.+        rings_validated: false,+        min_lon_e7: bbox.0,+        min_lat_e7: bbox.1,+        max_lon_e7: bbox.2,+        max_lat_e7: bbox.3,+        ..Options::default()+    })?;++    let mut per_zoom = Vec::new();+    for z in settings.min_zoom..=settings.max_zoom {+        let mut stats = ZoomStats { zoom: z, ..ZoomStats::default() };+        // Keyed on the **tile id**, not on `(x, y)`. Those are different orders: `tile_id` walks a+        // Hilbert curve, so row-major `(x, y)` ascends through it out of sequence and the writer+        // rejects the archive. Cheap to get wrong and caught only by an ordering check, which is+        // why the writer has one.+        let mut tiles: BTreeMap<u64, BTreeMap<u8, BodyLayer>> = BTreeMap::new();+        let tolerance = simplify::tolerance_for(z, settings.max_zoom, settings.simplification);+        let buffer = geom::buffer_for(EXTENT);+        let mut touched: Vec<(u64, u64)> = Vec::new();++        for feature in features {+            if z < feature.class.min_zoom {+                continue;+            }+            let mut projected = geom::project_geometry(&feature.geometry, z, EXTENT);+            // Significance first, then filter: computed on the whole geometry so a vertex's fate+            // does not depend on which tile it lands in.+            simplify::annotate(&mut projected);+            let thinned = simplify::filter(&projected, tolerance);+            if is_empty(&thinned) {+                stats.dropped += 1;+                continue;+            }+            geom::tiles_touched(&thinned, z, EXTENT, buffer, &mut touched);+            for &(tx, ty) in &touched {+                let rect = geom::tile_rect(tx, ty, EXTENT, buffer);+                let clipped = clip::clip_geometry(&thinned, &rect);+                if is_empty(&clipped) {+                    continue;+                }+                let local = geom::to_tile(&clipped, tx, ty, EXTENT);+                let layer = tiles+                    .entry(tile_id(z, tx, ty))+                    .or_default()+                    .entry(feature.class.layer)+                    .or_insert_with(|| BodyLayer::new(feature.class.layer));+                let added = push(layer, feature, &local);+                stats.features += added.0;+                stats.points += added.1;+            }+        }++        // A `BTreeMap` keyed on the tile id, so the emit order **is** the writer's required order+        // and no sort step can be forgotten. A `HashMap` here is the single easiest way to lose+        // byte-identical rebuilds.+        for (id, layers) in tiles {+            let body = Body { extent: EXTENT as u16, layers: layers.into_values().collect() };+            let encoded = tilecodec::mamaps::body::serialize(&body)?;+            stats.bytes += encoded.len() as u64;+            stats.tiles += 1;+            writer.append_encoded(id, &encoded)?;+        }+        per_zoom.push(stats);+    }++    let bytes = writer.finish()?;+    Ok((bytes, per_zoom))+}++/// Append one feature's tile-local geometry to a layer. Returns `(features, points)` added.+///+/// A polygon becomes **one feature per ring group**, so a feature's parts are exactly one exterior+/// and its holes — which is what the tessellator wants and what makes "one outer per feature" an+/// invariant worth stating.+fn push(layer: &mut BodyLayer, feature: &Feature, geometry: &IntGeometry) -> (u64, u64) {+    let class = &feature.class;+    let mut added = (0u64, 0u64);+    match geometry {+        IntGeometry::Polygons(polygons) => {+            for rings in polygons {+                // A ring needs three distinct points plus the closing one; anything less bounds no+                // area. Filtered *before* anything is appended, because a part and its points have+                // to be committed together — the encoder requires the parts to tile the arena+                // exactly, so half-appending a group and rolling it back would leave orphaned+                // coordinates.+                let keep: Vec<(usize, &Vec<(i32, i32)>)> =+                    rings.iter().enumerate().filter(|(_, ring)| ring.len() >= 4).collect();+                // If the exterior did not survive, what is left is a hole with nothing to be a hole+                // in, which would paint as the inverse of the shape.+                if !keep.first().is_some_and(|(index, _)| *index == 0) {+                    continue;+                }+                let parts_offset = layer.parts.len() as u32;+                for (index, ring) in &keep {+                    added.1 += push_part(+                        layer,+                        ring,+                        if *index == 0 { WINDING_OUTER } else { WINDING_HOLE },+                    );+                }+                layer.features.push(BodyFeature {+                    kind: class.kind,+                    kind_detail: class.kind_detail,+                    geom_type: GEOM_POLYGON,+                    flags: class.flags,+                    parts_offset,+                    part_count: keep.len() as u32,+                });+                added.0 += 1;+            }+        }+        IntGeometry::Lines(lines) => {+            let parts_offset = layer.parts.len() as u32;+            for line in lines {+                if line.len() < 2 {+                    continue;+                }+                added.1 += push_part(layer, line, WINDING_OUTER);+            }+            let part_count = layer.parts.len() as u32 - parts_offset;+            if part_count > 0 {+                layer.features.push(BodyFeature {+                    kind: class.kind,+                    kind_detail: class.kind_detail,+                    geom_type: GEOM_LINE,+                    flags: class.flags,+                    parts_offset,+                    part_count,+                });+                added.0 += 1;+            }+        }+        // Points are not carried: the renderer decoded them and threw them away.+        IntGeometry::Points(_) => {}+    }+    added+}++/// Append one path's points to a layer's arena, clamped to what an `i16` holds.+///+/// The clip buffer keeps a coordinate within a few percent of the extent, so `i16` has eight times+/// the headroom needed and this never bites. Clamping rather than asserting because a single stray+/// vertex should not fail a whole build.+fn push_part(layer: &mut BodyLayer, points: &[(i32, i32)], winding: u16) -> u64 {+    let coord_start = layer.coords.len() as u32;+    for &(x, y) in points {+        layer.coords.push((+            x.clamp(i16::MIN as i32, i16::MAX as i32) as i16,+            y.clamp(i16::MIN as i32, i16::MAX as i32) as i16,+        ));+    }+    layer.parts.push(Part { coord_start, point_count: points.len() as u32, winding });+    points.len() as u64+}++fn is_empty(g: &Geometry<SigPt>) -> bool {+    match g {+        Geometry::Points(points) => points.is_empty(),+        Geometry::Lines(lines) => lines.iter().all(|l| l.len() < 2),+        Geometry::Polygons(polygons) => polygons.iter().all(|rings| {+            rings.first().map(|ring| ring.len() < 4).unwrap_or(true)+        }),+    }+}++/// The bounding box of everything, in degrees times 1e7, for the archive header.+fn bounds_e7(features: &[Feature]) -> (i32, i32, i32, i32) {+    let mut out = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);+    let mut seen = false;+    for feature in features {+        for (lon, lat) in coords(&feature.geometry) {+            seen = true;+            let (x, y) = ((lon * 1e7) as i32, (lat * 1e7) as i32);+            out.0 = out.0.min(x);+            out.1 = out.1.min(y);+            out.2 = out.2.max(x);+            out.3 = out.3.max(y);+        }+    }+    if seen {+        out+    } else {+        (0, 0, 0, 0)+    }+}++fn coords(g: &Geometry) -> Vec<(f64, f64)> {+    match g {+        Geometry::Points(points) => points.clone(),+        Geometry::Lines(lines) => lines.iter().flatten().copied().collect(),+        Geometry::Polygons(polygons) => {+            polygons.iter().flatten().flatten().copied().collect()+        }+    }+}++/// A build that produced nothing is a build whose schema matched nothing, which is worth failing on+/// rather than publishing an empty archive.+pub fn check_not_empty(stats: &[ZoomStats]) -> Result<()> {+    if stats.iter().all(|s| s.tiles == 0) {+        return err("the build produced no tiles: nothing in the input matched the schema");+    }+    Ok(())+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::schema::Class;+    use tilecodec::mamaps::dict;++    fn square(lon: f64, lat: f64, size: f64) -> Geometry {+        Geometry::Polygons(vec![vec![vec![+            (lon, lat),+            (lon + size, lat),+            (lon + size, lat + size),+            (lon, lat + size),+            (lon, lat),+        ]]])+    }++    fn lake(lon: f64, lat: f64, size: f64, min_zoom: u8) -> Feature {+        Feature {+            class: Class::area(dict::LAYER_WATER, crate::schema::kind("lake"), min_zoom),+            geometry: square(lon, lat, size),+        }+    }++    fn settings(min_zoom: u8, max_zoom: u8) -> Settings {+        Settings { min_zoom, max_zoom, simplification: DEFAULT_SIMPLIFICATION, build_id: 7 }+    }++    #[test]+    fn a_lake_tiles_and_reads_back_out_of_the_archive() {+        let features = vec![lake(-120.0, 35.0, 0.5, 0)];+        let (bytes, stats) = build(&features, &settings(0, 6)).expect("build");+        check_not_empty(&stats).expect("not empty");++        let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read back");+        assert!(!entries.is_empty());+        // Every stored body holds the water layer and nothing else.+        for (_, _, body) in &entries {+            let body = Body::parse(body).expect("parse");+            let layer = body.layer(dict::LAYER_WATER).expect("water");+            assert!(!layer.features.is_empty());+            assert_eq!(layer.features[0].geom_type, GEOM_POLYGON);+            assert!(body.layer(dict::LAYER_BUILDINGS).is_none());+        }+    }++    /// A feature's `min_zoom` is what keeps a world tile from carrying every pond. Enforced here,+    /// so the archive does not hold what the style would not draw.+    #[test]+    fn a_feature_is_not_written_above_its_own_min_zoom() {+        let features = vec![lake(-120.0, 35.0, 0.01, 10)];+        let (_, stats) = build(&features, &settings(0, 11)).expect("build");+        for s in &stats {+            if s.zoom < 10 {+                assert_eq!(s.tiles, 0, "z{} should be empty", s.zoom);+            }+        }+        assert!(stats.iter().any(|s| s.zoom >= 10 && s.tiles > 0), "and present once it is due");+    }++    /// **Invariant 4 and 5 together.** Ids ascend across the whole archive because `tile_id` is+    /// zoom-major and every emit path is a `BTreeMap`, and the output is byte-identical run to run+    /// because nothing iterates a hash map.+    #[test]+    fn the_output_is_byte_identical_and_its_ids_ascend() {+        let features = vec![+            lake(-120.0, 35.0, 0.4, 0),+            lake(-119.0, 36.0, 0.3, 0),+            Feature {+                class: Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 0),+                geometry: square(-120.1, 35.1, 0.02),+            },+        ];+        let first = build(&features, &settings(0, 8)).expect("first").0;+        let second = build(&features, &settings(0, 8)).expect("second").0;+        assert_eq!(first, second, "two runs of the same input");++        let entries = tilecodec::mamaps::read::read_all(&first).expect("read");+        assert!(entries.windows(2).all(|p| p[1].0 > p[0].0), "ids ascend");+        for (id, _, _) in &entries {+            let (z, _, _) = tilecodec::pmtiles::tile_zxy(*id);+            let range = tilecodec::pmtiles::zoom_base(z)..tilecodec::pmtiles::zoom_base(z + 1);+            assert!(range.contains(id), "id {id} is outside z{z}");+        }+    }++    /// Two layers in one tile, which is the shape the format exists for: a cold tile is one range+    /// request whatever the style is drawing.+    #[test]+    fn a_tile_carrying_two_layers_holds_them_both() {+        let features = vec![+            lake(-120.0, 35.0, 0.02, 0),+            Feature {+                class: Class::area(dict::LAYER_BUILDINGS, crate::schema::kind("building"), 0),+                geometry: square(-120.005, 35.005, 0.002),+            },+        ];+        let (bytes, _) = build(&features, &settings(14, 14)).expect("build");+        let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");+        let both = entries.iter().any(|(_, _, body)| {+            let body = Body::parse(body).expect("parse");+            body.layer(dict::LAYER_WATER).is_some() && body.layer(dict::LAYER_BUILDINGS).is_some()+        });+        assert!(both, "some tile should carry both");+    }++    #[test]+    fn a_build_that_matched_nothing_fails_rather_than_publishing_an_empty_archive() {+        let stats = vec![ZoomStats { zoom: 0, ..ZoomStats::default() }];+        assert!(check_not_empty(&stats).is_err());+        assert!(build(&[], &settings(0, 2)).is_err(), "the writer refuses an empty archive");+    }++    /// Simplification is per zoom, so a shallow tile holds fewer points for the same shape. If this+    /// ever inverts, the tolerance is being applied at the wrong end.+    #[test]+    fn a_shallow_zoom_carries_fewer_points_than_a_deep_one() {+        // A wiggly line, so there is something to simplify away.+        let points: Vec<(f64, f64)> = (0..200)+            .map(|i| (-120.0 + i as f64 * 0.001, 35.0 + (i % 3) as f64 * 0.0005))+            .collect();+        let features = vec![Feature {+            class: Class::line(dict::LAYER_WATER, crate::schema::kind("river"), 0),+            geometry: Geometry::Lines(vec![points]),+        }];+        let (_, stats) = build(&features, &settings(6, 14)).expect("build");+        let at = |z: u8| stats.iter().find(|s| s.zoom == z).expect("zoom").points;+        assert!(at(6) < at(14), "z6 has {} points, z14 has {}", at(6), at(14));+    }+}