Modern Apps git

← Modern-Apps.git

maps: earth from a prepared land polygon, and islands from tags

Commit
56436c6ad12a133dfb9a4f608b2176ff531584a6
Author
vayun-mathur <[email protected]>
When
2026-08-28 01:17 UTC (3 months ago)
Parents
6f0e8b9

Diff

scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex 35f6dccfa5..642c8ef617 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -36,6 +36,7 @@ fn main() -> ExitCode {     let mut max_zoom = 14u8;     let mut simplification = tiler::DEFAULT_SIMPLIFICATION;     let mut build_id: Option<u64> = None;+    let mut coastline: Option<PathBuf> = None;      let mut i = 1;     while i < args.len() {@@ -55,6 +56,10 @@ fn main() -> ExitCode {                 report = Some(PathBuf::from(v));                 2             }),+            "--coastline" => value("--coastline").map(|v| {+                coastline = Some(PathBuf::from(v));+                2+            }),             "--layers" => value("--layers").and_then(|v| {                 layers = schema::Layers::parse(&v)?;                 Ok(2)@@ -101,7 +106,16 @@ fn main() -> ExitCode {         return ExitCode::from(2);     } -    match run(&input, &out, report.as_deref(), layers, min_zoom, max_zoom, simplification, build_id) {+    let settings = RunSettings {+        report,+        coastline,+        layers,+        min_zoom,+        max_zoom,+        simplification,+        build_id,+    };+    match run(&input, &out, &settings) {         Ok(()) => ExitCode::SUCCESS,         Err(e) => {             eprintln!("mamaps_build: {e}");@@ -110,17 +124,26 @@ fn main() -> ExitCode {     } } -#[allow(clippy::too_many_arguments)]-fn run(-    input: &std::path::Path,-    out: &std::path::Path,-    report: Option<&std::path::Path>,+/// Everything a run needs beyond its input and output paths.+struct RunSettings {+    report: Option<PathBuf>,+    /// A prepared land polygon for `earth`'s mainland. Without it the layer carries islands only.+    coastline: Option<PathBuf>,     layers: schema::Layers,     min_zoom: u8,     max_zoom: u8,     simplification: f64,     build_id: Option<u64>,+}++fn run(+    input: &std::path::Path,+    out: &std::path::Path,+    run: &RunSettings, ) -> Result<(), String> {+    let (layers, min_zoom, max_zoom, simplification) =+        (run.layers, run.min_zoom, run.max_zoom, run.simplification);+    let report = run.report.as_deref();     let started = std::time::Instant::now();     println!("reading {}", input.display());     let (features, stats) =@@ -138,7 +161,25 @@ fn run(     // 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(|| {+    // The mainland, if a prepared polygon was given. `earth`'s islands come from the PBF like+    // everything else; only the continents need it.+    let mut features = features;+    if let Some(path) = &run.coastline {+        if !layers.earth {+            return Err("--coastline was given but the earth layer is not selected".to_string());+        }+        let land = schema::earth::read_prepared(path).map_err(|e| e.to_string())?;+        println!("read {} land polygon(s) from {}", land.len(), path.display());+        features.extend(land);+    } else if layers.earth {+        // Said out loud, because a map with no mainland is a striking thing to discover later. It is+        // not an error: an island is real data and the renderer's backdrop is the water colour.+        println!(+            "no --coastline given, so `earth` carries islands only and there is no mainland"+        );+    }++    let build_id = run.build_id.unwrap_or_else(|| {         derive_build_id(input, layers, min_zoom, max_zoom, simplification, stats.features)     }); @@ -200,6 +241,7 @@ fn derive_build_id(         }     }     eat(&[+        u8::from(layers.earth),         u8::from(layers.water),         u8::from(layers.buildings),         u8::from(layers.roads),@@ -253,8 +295,9 @@ fn build_report( fn usage() {     eprintln!(         "usage: mamaps_build --input IN.osm.pbf --out OUT.mamaps\n\-         \x20                   [--layers water,buildings,roads,boundaries,landcover,landuse]\n\+         \x20                   [--layers earth,water,buildings,roads,boundaries,landcover,landuse]\n\          \x20                   [--min-zoom N] [--max-zoom N]\n\+         \x20                   [--coastline LAND.geojsonseq]\n\          \x20                   [--simplification F] [--build-id N] [--report FILE]"     ); }
scripts/maps/mamaps_build/src/schema/earth.rs
diff --git a/scripts/maps/mamaps_build/src/schema/earth.rs b/scripts/maps/mamaps_build/src/schema/earth.rsnew file mode 100644index 0000000000..b45882c018--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/earth.rs@@ -0,0 +1,176 @@+//! `earth`: the land itself, which is the one layer that is not a tag query.+//!+//! # Why this is different+//!+//! There is no `natural=land` in OpenStreetMap. Land is defined by its **absence**: the data has+//! `natural=coastline` ways, oriented land-on-the-left, and the continents are whatever those ways+//! enclose. Deriving land from them means stitching every coastline way on the planet into closed+//! rings, orienting them, closing them against the extract's cut edges, and subtracting the result+//! from an ocean rectangle. It is the single hardest piece of this project and the most likely thing+//! to look visibly wrong — a stitch that fails anywhere puts a wedge of ocean through a continent.+//!+//! So it is not done here. [`Source::Prepared`] reads a **pre-validated land polygon** — the+//! OSMCoastline `land_polygons` product, which is effectively the same input Planetiler is given —+//! through `tile_build`'s GeoJSON-seq reader. That takes the largest single risk off the critical+//! path at the cost of one vendored artefact and this provenance note. Self-stitching sits behind+//! the same interface when it is worth the one to two weeks.+//!+//! # `island` is a tag query+//!+//! `place=island` and `place=islet` are real tags on real ways and relations, and they are what the+//! style's `earth` filter implies when it names `island` as a kind. So that half is here and works+//! from the `.osm.pbf` alone — which means the layer is not empty without the vendored polygon, it+//! just has no mainland.++use std::path::Path;++use osm_ingest::proto::{err, Result};+use tile_build::geom::Geometry;+use tilecodec::mamaps::dict::LAYER_EARTH;++use super::{kind, Class, TagSource};++pub const FILTERS: &[&str] = &["place", "natural"];++/// Every `kind` this module can emit.+#[cfg_attr(not(test), allow(dead_code))]+pub const KINDS: &[&str] = &["island", "earth", "cliff"];++/// The `earth` features a `.osm.pbf` alone can produce.+///+/// An island is an area whatever its geometry says, and it is carried from z4: an island big enough+/// to be tagged is big enough to see, and the minimum area filters the rest.+pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {+    if matches!(tags.get("place"), Some("island" | "islet")) {+        return Some(Class {+            min_area_px: 1.0,+            ..Class::area(LAYER_EARTH, kind("island"), 4)+        });+    }+    // A cliff is a line in this layer, and it is what makes a coastal relief map read as relief.+    if tags.get("natural") == Some("cliff") {+        return Some(Class::line(LAYER_EARTH, kind("cliff"), 12));+    }+    None+}++/// Read a prepared land polygon into `earth` features.+///+/// One GeoJSON feature per line, as `tile_build`'s own reader expects, and every polygon becomes one+/// `earth` feature with no kind — which is what the style's unfiltered `earth` layer draws.+pub fn read_prepared(path: &Path) -> Result<Vec<crate::extract::Feature>> {+    let text = std::fs::read_to_string(path).map_err(|e| {+        osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display()))+    })?;+    let mut out = Vec::new();+    for (line_number, line) in text.lines().enumerate() {+        if line.trim().is_empty() {+            continue;+        }+        let Some(feature) = tile_build::geojson::parse_feature(line) else {+            return err(format!(+                "{}:{}: not a GeoJSON feature",+                path.display(),+                line_number + 1,+            ));+        };+        // Polygons only. A prepared land product has nothing else in it, and a line in there would+        // be a sign the wrong file was handed over.+        let polygons = match feature.geometry {+            Geometry::Polygons(polygons) => polygons,+            _ => continue,+        };+        if polygons.is_empty() {+            continue;+        }+        out.push(crate::extract::Feature {+            // No kind: the mainland is what `earth`'s unfiltered layer draws, and giving it one+            // would put it behind a whitelist it is not in.+            class: Class::area(LAYER_EARTH, tilecodec::mamaps::dict::NONE, 0),+            geometry: Geometry::Polygons(polygons),+        });+    }+    if out.is_empty() {+        return err(format!("{} holds no land polygons", path.display()));+    }+    Ok(out)+}++#[cfg(test)]+mod tests {+    use super::*;+    use tilecodec::mamaps::dict;++    fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {+        super::classify(pairs)+    }++    #[test]+    fn an_island_is_an_area_carried_from_a_continental_zoom() {+        for value in ["island", "islet"] {+            let class = classify_tags(&[("place", value)]).expect(value);+            assert_eq!(class.layer, dict::LAYER_EARTH);+            assert_eq!(dict::KINDS[class.kind as usize - 1], "island");+            assert!(class.area);+            assert_eq!(class.min_zoom, 4);+            // A minimum area, because `place=islet` is on some very small rocks.+            assert!(class.min_area_px > 0.0);+        }+    }++    #[test]+    fn a_cliff_is_a_line_and_nothing_else_is_earth() {+        let cliff = classify_tags(&[("natural", "cliff")]).expect("cliff");+        assert!(!cliff.area);+        for pairs in [+            vec![("place", "city")],+            vec![("natural", "coastline")],+            vec![("natural", "water")],+            vec![],+        ] {+            assert!(classify_tags(&pairs).is_none(), "{pairs:?} should not be earth");+        }+    }++    /// **The reason `natural=coastline` is not handled here.** Land is defined by absence: the+    /// coastline ways enclose it, and turning them into polygons is a stitching problem, not a+    /// classification one.+    #[test]+    fn a_coastline_way_is_not_classified_as_land() {+        assert!(classify_tags(&[("natural", "coastline")]).is_none());+    }++    #[test]+    fn a_missing_or_empty_prepared_polygon_is_an_error_rather_than_an_empty_layer() {+        let missing = std::path::Path::new("no_such_land_polygons.geojsonseq");+        assert!(read_prepared(missing).is_err());++        let empty = std::env::temp_dir().join("mamaps_empty_land.geojsonseq");+        std::fs::write(&empty, "\n\n").expect("write");+        let failure = match read_prepared(&empty) {+            Ok(_) => panic!("an empty land file should be refused"),+            Err(e) => e,+        };+        assert!(failure.0.contains("no land polygons"), "{}", failure.0);+        let _ = std::fs::remove_file(&empty);+    }++    #[test]+    fn a_prepared_polygon_reads_as_an_unfiltered_earth_feature() {+        let path = std::env::temp_dir().join("mamaps_land.geojsonseq");+        std::fs::write(+            &path,+            "{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\+             \"coordinates\":[[[-120.0,35.0],[-119.0,35.0],[-119.0,36.0],[-120.0,36.0],\+             [-120.0,35.0]]]}}\n",+        )+        .expect("write");+        let features = read_prepared(&path).expect("read");+        assert_eq!(features.len(), 1);+        assert_eq!(features[0].class.layer, dict::LAYER_EARTH);+        // No kind, so the style's unfiltered `earth` layer draws it.+        assert_eq!(features[0].class.kind, dict::NONE);+        assert_eq!(features[0].class.min_zoom, 0, "the mainland carries a world tile");+        let _ = std::fs::remove_file(&path);+    }+}
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.rsindex 058934ad54..b369b6da81 100644--- a/scripts/maps/mamaps_build/src/schema/mod.rs+++ b/scripts/maps/mamaps_build/src/schema/mod.rs@@ -25,6 +25,7 @@ use tilecodec::mamaps::dict;  pub mod boundaries; pub mod buildings;+pub mod earth; pub mod land; pub mod roads; pub mod water;@@ -148,6 +149,7 @@ pub fn detail(name: &str) -> u16 { /// Which layers a build is producing. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Layers {+    pub earth: bool,     pub water: bool,     pub buildings: bool,     pub roads: bool,@@ -159,6 +161,7 @@ pub struct Layers { impl Layers {     pub fn all() -> Layers {         Layers {+            earth: true,             water: true,             buildings: true,             roads: true,@@ -170,6 +173,7 @@ impl Layers {      pub fn none() -> Layers {         Layers {+            earth: false,             water: false,             buildings: false,             roads: false,@@ -184,6 +188,7 @@ impl Layers {         let mut layers = Layers::none();         for name in list.split(',').map(str::trim).filter(|s| !s.is_empty()) {             match name {+                "earth" => layers.earth = true,                 "water" => layers.water = true,                 "buildings" => layers.buildings = true,                 "roads" => layers.roads = true,@@ -192,8 +197,8 @@ impl Layers {                 "landuse" => layers.landuse = true,                 other => {                     return Err(format!(-                        "unknown layer `{other}`; this generator produces water, buildings, roads, \-                         boundaries, landcover and landuse"+                        "unknown layer `{other}`; this generator produces earth, water, buildings, \+                         roads, boundaries, landcover and landuse"                     ))                 }             }@@ -207,6 +212,7 @@ impl Layers {     /// Is this the layer a classifier just returned one for?     fn wants(&self, layer: u8) -> bool {         match layer {+            dict::LAYER_EARTH => self.earth,             dict::LAYER_WATER => self.water,             dict::LAYER_BUILDINGS => self.buildings,             dict::LAYER_ROADS => self.roads,@@ -228,6 +234,11 @@ pub fn classify(     is_way: bool,     layers: Layers, ) -> Option<Class> {+    if layers.earth {+        if let Some(class) = earth::classify(tags) {+            return Some(class);+        }+    }     if layers.water {         if let Some(class) = water::classify(tags, is_way) {             return Some(class);@@ -268,6 +279,9 @@ pub fn classify( /// that rejects something is a bug. pub fn filters(layers: Layers) -> Vec<&'static str> {     let mut out = Vec::new();+    if layers.earth {+        out.extend_from_slice(earth::FILTERS);+    }     if layers.water {         out.extend_from_slice(water::FILTERS);     }@@ -300,6 +314,7 @@ mod tests {             .chain(roads::KINDS)             .chain(boundaries::KINDS)             .chain(land::KINDS)+            .chain(earth::KINDS)         {             assert!(                 dict::KINDS.contains(name),@@ -323,10 +338,10 @@ mod tests {             Layers { water: true, ..Layers::none() },         );         assert_eq!(-            Layers::parse("water,buildings,roads,boundaries,landcover,landuse").expect("all"),+            Layers::parse("earth,water,buildings,roads,boundaries,landcover,landuse").expect("all"),             Layers::all(),         );-        assert!(Layers::parse("earth").is_err(), "not until the coastline work");+        assert!(Layers::parse("places").is_err(), "this generator draws no labels");         assert!(Layers::parse("").is_err(), "nothing selected");     }