mamaps-build: country label start zooms from footprint x headcount
- Commit
9fcf2325fd6a205044a26b6a3badf3defd65c65e- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-29 23:54 UTC (2 months ago)
- Parents
4c77309
Diff
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex 1b3d6ae146..c544eba736 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -196,6 +196,10 @@ struct Relation { id: i64, /// A building relation's S3DB attributes (a multipolygon `building=*`), `None` otherwise. building: Option<BuildingAttrs>,+ /// A `place` relation's headcount (`population` tag), for country label zoom scoring+ /// (see `extract_fallback::country_zoom`). Read in pass 1 while the tags are in hand;+ /// `None` for every non-place relation and for places nobody counted (Antarctica).+ population: Option<u64>, /// The ISO 3166-1 code of an `admin_level=2` relation, `None` for every other relation. What /// the tile's marking convention is resolved from — see [`crate::schema::boundaries::Conventions`]. iso: Option<String>,
scripts/maps/mamaps_build/src/extract_fallback.rs
diff --git a/scripts/maps/mamaps_build/src/extract_fallback.rs b/scripts/maps/mamaps_build/src/extract_fallback.rsindex 0ddda82244..20534e4554 100644--- a/scripts/maps/mamaps_build/src/extract_fallback.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback.rs@@ -74,6 +74,68 @@ pub struct FallbackStats { /// `(kind, total, linked)` per place kind, sorted by kind. `linked` counts both halves; /// the ratio is the per-kind hit rate the build log prints. pub per_kind: Vec<(String, u64, u64)>,+ /// Country zoom overrides assigned (place tagged id count).+ pub country_zooms: u64,+}++/// A country's label zoom from its ground footprint and headcount.+///+/// Pure area buries Vatican City, Singapore and Monaco until deep zoom; pure+/// population buries Russia, Canada and Mongolia under their own emptiness. The+/// score multiplies the two so a place must be big *or* populous to surface+/// early, and tiny *and* empty to wait:+///+/// `score = log10(area_m2) + AOI_COVERAGE_WEIGHT * log10(population + 1)`+///+/// The weight (2.0) is what keeps Singapore (6 M people, 725 km²) and Switzerland+/// off the backstop: with equal weights a microstate's area term (~1e8 → 8)+/// caps its score near 15 no matter the headcount, so population could never+/// lift one. Weighting population double counts headcount the way a reader+/// does — people are the point of a label — while area still separates Russia+/// (20.5) from Nauru (10.7). The `+1` keeps unpopulated Antarctica finite.+///+/// Bucket edges calibrated against real countries (see+/// `country_zoom_scores_area_times_headcount` — every edge asserted):+///+/// | score | start zoom | example |+/// |---|---|---|+/// | ≥ 26 | 0 | Russia, USA, France, Germany, Japan, Egypt |+/// | ≥ 23.5 | 1 | Switzerland |+/// | ≥ 20 | 2 | Singapore |+/// | ≥ 14.5 | 3 | Liechtenstein, Nauru, Tuvalu — everything on by z3 |+/// | < 14.5 | 4 | Vatican City (tiny and near-empty) |+///+/// z3 shows every country whose label cannot collide with another country's:+/// at z3 a tile spans 45° and a country label spans a fraction of a tile, so+/// neighbours are tiles apart. z4 is the backstop for the tail, never later —+/// a country is never street-level detail.+///+/// Why z0 holds France as well as Russia: at z0 the world is four tiles and a+/// label is a few dozen pixels — France and Russia never share a tile, so they+/// cannot collide. Gating France out would empty the tile, not declutter it.+///+/// Ground area from planar deg² via equirectangular projection at the shape's+/// own mid-latitude: exact enough for bucketing (adjacent buckets differ ~4x),+/// cheap enough to run over every country once per build.+pub fn country_zoom(area_deg2: f64, mid_lat_deg: f64, population: u64) -> u8 {+ const M_PER_DEG: f64 = 111_320.0;+ /// How much a doubling of headcount moves the score relative to a doubling+ /// of ground area. 2.0: people are the point of a label, and without it no+ /// microstate could ever leave the backstop on headcount alone.+ const AOI_COVERAGE_WEIGHT: f64 = 2.0;+ let area_m2 = area_deg2.max(0.0) * M_PER_DEG * M_PER_DEG * mid_lat_deg.to_radians().cos().max(0.05);+ let score = area_m2.log10() + AOI_COVERAGE_WEIGHT * (population as f64 + 1.0).log10();+ if score >= 26.0 {+ 0+ } else if score >= 23.5 {+ 1+ } else if score >= 20.0 {+ 2+ } else if score >= 14.5 {+ 3+ } else {+ 4+ } } /// Which admin-level band a place or a boundary belongs to.@@ -304,6 +366,21 @@ fn select_link(point: (f64, f64), band: Band, candidates: &[&Boundary]) -> Optio pub fn extend_region_links( store: &crate::store::Store, region_links: &mut HashMap<u64, u64>,+) -> Result<FallbackStats> {+ extend_region_links_with(store, region_links, &mut HashMap::new(), &HashMap::new())+}++/// [`extend_region_links`], also filling `country_zooms`: place tagged id → label start+/// zoom for `country` places, from each country's ground footprint and headcount (see+/// [`country_zoom`]). `populations` maps place tagged id → `population` tag headcount+/// (relation places; node/way countries are absent and score as unpopulated — the area+/// term still separates Russia from Nauru). The caller hands both maps to the tiler+/// beside `region_links`.+pub fn extend_region_links_with(+ store: &crate::store::Store,+ region_links: &mut HashMap<u64, u64>,+ country_zooms: &mut HashMap<u64, u8>,+ populations: &HashMap<u64, u64>, ) -> Result<FallbackStats> { // Pass 1: boundary shapes. Only `region_area` areas (the mask's own shapes, carrying the // admin level in `kind_detail`); border lines enclose nothing.@@ -329,7 +406,11 @@ pub fn extend_region_links( // Pass 2: places. Positional, so node, way-centroided and relation-centroided labels all // link by the tagged id they already carry — the only path that can link non-node places,- // since the member map is node-keyed.+ // since the member map is node-keyed. Country labels also gain their area+population+ // start zoom here (see `country_zoom`): the linked boundary's footprint is in hand,+ // so no third pass is needed. The headcount comes from `populations` (relation+ // places, filled by the caller while tags were in hand); absent entries score as+ // unpopulated — Antarctica's case — never as missing. let mut stats = FallbackStats::default(); let mut per_kind: HashMap<String, (u64, u64)> = HashMap::new(); let mut buf: Vec<&Boundary> = Vec::new();@@ -368,6 +449,30 @@ pub fn extend_region_links( stats.fallback_linked += 1; entry.1 += 1; }+ // A country label starts at the zoom its footprint earns. The linked+ // boundary (member half inserted before this pass, fallback half just+ // above — both visible in `region_links` now) carries the ground area;+ // the place feature carries the headcount via its population rank... but+ // the rank buckets are lossy, so read the headcount from the store+ // feature's own tags is impossible here — instead the population comes+ // from the place feature's `kind_detail` rank inverted through the same+ // buckets `schema::places` used. Simpler and exact: keep a place-id →+ // population map from the pass-2 scan itself (see `populations` below).+ // Unlinked countries keep the schema floor (z0): a missing link must+ // never hide a country.+ if kind_name == "country" {+ if let Some(target) = region_links.get(&feature.id) {+ if let Some(boundary) = boundaries.iter().find(|b| b.id == *target) {+ let mid_lat = boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0);+ let population = populations.get(&feature.id).copied().unwrap_or(0);+ country_zooms.insert(+ feature.id,+ country_zoom(boundary.area, mid_lat, population),+ );+ stats.country_zooms += 1;+ }+ }+ } } stats.fallback_missed = stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked);
scripts/maps/mamaps_build/src/extract_fallback_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_fallback_part1.rs b/scripts/maps/mamaps_build/src/extract_fallback_part1.rsindex f32a2b897c..40ac9763f9 100644--- a/scripts/maps/mamaps_build/src/extract_fallback_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_fallback_part1.rs@@ -10,6 +10,34 @@ mod tests { fn boundary(id: u64, level: u16, polygons: Vec<Polygon>) -> Boundary { Boundary::new(id, level, polygons) }+ /// The score is area × headcount² in log space, population weighted double so a+ /// microstate's headcount can actually lift it. Measured scores: Russia 28.63,+ /// USA 29.26, France 26.57, Mongolia 24.32, Singapore 21.73, Liechtenstein+ /// 16.56, Nauru 14.82, Vatican City 10.62 — every expectation asserted.+ #[test]+ fn country_zoom_scores_area_times_headcount() {+ // z0: score ≥ 26 — vast and populous, plus populous western Europe (a z0+ // world tile holds four labels that never share a tile, so no collision).+ assert_eq!(country_zoom(289.0, 55.0, 144_000_000), 0, "Russia");+ assert_eq!(country_zoom(170.0, 40.0, 335_000_000), 0, "USA");+ assert_eq!(country_zoom(9.5, 47.0, 68_000_000), 0, "France");+ assert_eq!(country_zoom(6.2, 51.0, 84_000_000), 0, "Germany");+ // z1: 23.5–26. Switzerland (23.67) leads Mongolia (24.32)? No: 24.32 ≥+ // 23.5 → z1 as well. Both vast-and-empty vs small-and-rich meet here.+ assert_eq!(country_zoom(27.0, 46.0, 3_000_000), 1, "Mongolia");+ assert_eq!(country_zoom(0.72, 46.8, 8_800_000), 1, "Switzerland");+ // z2: 20–23.5 — tiny but millions of people.+ assert_eq!(country_zoom(0.012, 1.35, 6_000_000), 2, "Singapore");+ // z3: 14.5–20 — everything else with a pulse, on by z3.+ assert_eq!(country_zoom(0.0028, 47.1, 39_000), 3, "Liechtenstein");+ assert_eq!(country_zoom(0.00037, -0.5, 12_000), 3, "Nauru");+ // z4 backstop, never later: tiny AND near-empty.+ assert_eq!(country_zoom(0.000007, 41.9, 800), 4, "Vatican City");+ // Antarctica (11.71): vast but uncounted. The backstop is honest — no+ // headcount exists to score, and area alone must not outrank every+ // populated microstate.+ assert_eq!(country_zoom(240.0, -80.0, 0), 4, "Antarctica");+ } #[test] fn nested_shapes_link_each_place_kind_to_its_own_level() {
scripts/maps/mamaps_build/src/extract_part1.rs
diff --git a/scripts/maps/mamaps_build/src/extract_part1.rs b/scripts/maps/mamaps_build/src/extract_part1.rsindex 2638ca1187..d10ea64c20 100644--- a/scripts/maps/mamaps_build/src/extract_part1.rs+++ b/scripts/maps/mamaps_build/src/extract_part1.rs@@ -15,7 +15,7 @@ pub fn extract( graph: &Path, spill_path: &Path, region: Option<osm_ingest::bbox::BBox>,-) -> Result<(Store, Stats, HashMap<u64, u64>)> {+) -> Result<(Store, Stats, HashMap<u64, u64>, HashMap<u64, u64>)> { // Stage A's boundaries are printed with their elapsed time so an external RSS sampler can say // which of them the peak belongs to. Three candidates sit within seconds of each other -- the ref // vector, the id index built beside it, and the node pass's per-chunk accumulators -- and@@ -151,6 +151,19 @@ pub fn extract( &mut sink, &mut stats, )?;+ // Country headcounts for label zoom scoring (see `extract_fallback::country_zoom`):+ // relation id (tagged) -> `population` tag. Node/way countries have no relation to+ // read it from and score as unpopulated; the area term still separates Russia from+ // Nauru. Built BEFORE `relations` is dropped below (it dies at "OSM tables freed").+ let country_populations: HashMap<u64, u64> = relations+ .iter()+ .filter_map(|r| {+ r.population.and_then(|pop| {+ (r.class.layer == tilecodec::mamaps::dict::LAYER_PLACES)+ .then(|| (tagged_id(r.id, ELEMENT_RELATION), pop))+ })+ })+ .collect(); // The OSM tables are dead from here: relations, member refs and the coordinate table serve // only materialisation. Dropping them before the externals (coastline, transit, graph) // keeps the RankIndex bitset (~1.5 GB on planet), the resolved bitset and the mapped locs@@ -176,7 +189,7 @@ pub fn extract( .iter() .map(|(&node, &rel)| (tagged_id(node, ELEMENT_NODE), tagged_id(rel, ELEMENT_RELATION))) .collect();- Ok((store, stats, region_links))+ Ok((store, stats, region_links, country_populations)) } /// Spill bytes per classified feature, calibrated from measured builds.@@ -546,6 +559,7 @@ fn run_pass1( name: name.clone(), id: relation.id, building: None,+ population: None, iso: iso.clone(), }); }@@ -556,6 +570,7 @@ fn run_pass1( name, id: relation.id, building,+ population: Some(schema::places::population_of(&relation.tags)), iso: None, }); }
scripts/maps/mamaps_build/src/main_part1.rs
diff --git a/scripts/maps/mamaps_build/src/main_part1.rs b/scripts/maps/mamaps_build/src/main_part1.rsindex c76ea9361e..33ac85e448 100644--- a/scripts/maps/mamaps_build/src/main_part1.rs+++ b/scripts/maps/mamaps_build/src/main_part1.rs@@ -55,7 +55,7 @@ fn run( // an empty graph dir with no `metadata.bin`, paid for in full. check_graph_dir(&graph_dir, run.region)?; - let (store, stats, mut region_links) = extract::extract(+ let (store, stats, mut region_links, country_populations) = extract::extract( input, layers, &run.coastline,@@ -68,7 +68,15 @@ fn run( // The containment fallback: member-less place labels gain links from the whole-polygon // shapes above, never overwriting a member link. Runs here — after the store is sealed // and before the tiler reads the map — because only whole rings answer containment.- match crate::extract_fallback::extend_region_links(&store, &mut region_links) {+ // It also assigns country label start zooms from footprint × headcount (same pass,+ // footprints in hand).+ let mut country_zooms: std::collections::HashMap<u64, u8> = std::collections::HashMap::new();+ match crate::extract_fallback::extend_region_links_with(+ &store,+ &mut region_links,+ &mut country_zooms,+ &country_populations,+ ) { Ok(fallback) => { if fallback.places_total > 0 { println!(@@ -83,6 +91,13 @@ fn run( println!(" {kind}: {linked}/{total} ({rate:.0}%)"); } }+ if fallback.country_zooms > 0 {+ println!(+ " country label zooms: {} countr{} scored by footprint x headcount",+ fallback.country_zooms,+ if fallback.country_zooms == 1 { "y" } else { "ies" },+ );+ } } Err(e) => return Err(format!("region fallback: {e}")), }@@ -155,6 +170,7 @@ fn run( scratch: scratch_path(out), dem, region_links,+ country_zooms, // Honour the operator's backend choice: `MAPS_ANON_SPILL=1` (or any truthy value) stages // the tile-chunk spill in pagefile-backed anonymous memory instead of the scratch file // beside the output. Same chunks, same offsets, same bytes -- the merge reads through the
scripts/maps/mamaps_build/src/rings_part1.rs
diff --git a/scripts/maps/mamaps_build/src/rings_part1.rs b/scripts/maps/mamaps_build/src/rings_part1.rsindex 35766eb17f..978543baba 100644--- a/scripts/maps/mamaps_build/src/rings_part1.rs+++ b/scripts/maps/mamaps_build/src/rings_part1.rs@@ -324,6 +324,7 @@ mod tests { force_chunk_spill_file: false, dem: crate::dem::Dem::from_grids(14, 17, Vec::new()), region_links: std::collections::HashMap::new(),+ country_zooms: std::collections::HashMap::new(), }; let store = crate::store::Store::of(&features).expect("spill"); let (bytes, stats) = crate::tiler::build(&store, &settings).expect("build");@@ -403,6 +404,7 @@ mod tests { force_chunk_spill_file: false, dem: crate::dem::Dem::from_grids(14, 17, Vec::new()), region_links: std::collections::HashMap::new(),+ country_zooms: std::collections::HashMap::new(), }; let store = crate::store::Store::of(&features).expect("spill"); let (bytes, _) = crate::tiler::build(&store, &settings).expect("build");@@ -433,4 +435,97 @@ mod tests { assert!(saw[1], "Superior water reaches z5"); assert!(saw[2], "Superior water reaches z14"); }++ /// **Country label gating, end to end.** Two `country` places through the real+ /// pipeline with scored start zooms: a Russia-scale label (z0) and a Vatican-scale+ /// label (z4). The z0 tile carries only Russia; the z4 tile carries both. A third+ /// unscored country keeps the schema floor and rides every zoom — a missing score+ /// must never hide a country.+ #[test]+ fn country_labels_start_at_their_scored_zoom() {+ use crate::schema::Class;+ use tilecodec::mamaps::body::Body;+ use tilecodec::mamaps::dict;++ fn country(id: u64) -> crate::extract::Feature {+ let class = crate::schema::places::classify(+ &[("place", "country"), ("name", "Test")] as &[(&str, &str)],+ )+ .expect("classified");+ crate::extract::Feature {+ class,+ geometry: tile_build::geom::Geometry::Points(vec![(10.0, 10.0)]),+ name: Some("Test".to_string()),+ id,+ transit_color: 0,+ transit_ordinal: 0,+ transit_lanes: 0,+ transit_taper: 0,+ lane_count: 0,+ turn_fwd: Vec::new(),+ turn_bwd: Vec::new(),+ carriageway: tilecodec::mamaps::body::Carriageway::default(),+ building: None,+ }+ }++ let russia = 1001u64;+ let vatican = 1002u64;+ let unscored = 1003u64;+ let features = vec![country(russia), country(vatican), country(unscored)];+ let mut zooms: std::collections::HashMap<u64, u8> = std::collections::HashMap::new();+ zooms.insert(russia, 0);+ zooms.insert(vatican, 4);+ let settings = crate::tiler::Settings {+ build_id: 1,+ scratch: std::env::temp_dir()+ .join(format!("mamaps_countries_{}.tilechunks", std::process::id())),+ force_chunk_spill_file: false,+ dem: crate::dem::Dem::from_grids(14, 17, Vec::new()),+ region_links: std::collections::HashMap::new(),+ country_zooms: zooms,+ };+ let store = crate::store::Store::of(&features).expect("spill");+ let (bytes, _) = crate::tiler::build(&store, &settings).expect("build");++ // Which ids does each zoom's `places` layer carry?+ let mut at_zoom: std::collections::HashMap<u8, Vec<u64>> =+ std::collections::HashMap::new();+ for (id, _, body) in tilecodec::mamaps::read::read_all(&bytes).expect("read") {+ let (z, _, _) = tilecodec::pmtiles::tile_zxy(id);+ if z != 0 && z != 4 {+ continue;+ }+ let body = Body::parse(&body).expect("parse");+ let Some(layer) = body.layer(dict::LAYER_PLACES) else {+ continue;+ };+ let country_kind = crate::schema::kind("country");+ let has = |want: u64| {+ layer+ .features+ .iter()+ .enumerate()+ .filter(|(_, f)| f.kind == country_kind)+ .any(|(i, _)| body.feature_id(dict::LAYER_PLACES, i) == Some(want))+ };+ for want in [russia, vatican, unscored] {+ if has(want) {+ at_zoom.entry(z).or_default().push(want);+ }+ }+ }+ let mut z0 = at_zoom.get(&0).cloned().unwrap_or_default();+ let mut z4 = at_zoom.get(&4).cloned().unwrap_or_default();+ z0.sort_unstable();+ z4.sort_unstable();+ z0.dedup();+ z4.dedup();+ assert_eq!(z0, vec![russia, unscored], "z0 carries Russia and the unscored country");+ assert_eq!(+ z4,+ vec![russia, vatican, unscored],+ "z4 carries all three — Vatican joins, nothing leaves"+ );+ } }
scripts/maps/mamaps_build/src/schema/places.rs
diff --git a/scripts/maps/mamaps_build/src/schema/places.rs b/scripts/maps/mamaps_build/src/schema/places.rsindex 9eec2263f0..a3db9713d7 100644--- a/scripts/maps/mamaps_build/src/schema/places.rs+++ b/scripts/maps/mamaps_build/src/schema/places.rs@@ -147,7 +147,12 @@ fn rank_of(tags: &(impl TagSource + ?Sized)) -> u16 { .unwrap_or(0) } -fn population_of(tags: &(impl TagSource + ?Sized)) -> u64 {+/// A `population` tag as a headcount: commas and spaces stripped, unparseable or+/// absent as zero (nobody counted — Antarctica's case, not an error).+///+/// `pub` for pass 1, which reads it off place relations while the tags are in hand+/// (country label zoom scoring); the spill record never carries tags.+pub fn population_of(tags: &(impl TagSource + ?Sized)) -> u64 { tags .get("population") .map(str::trim)
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex 8b06895a41..2f61d2d62c 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -268,6 +268,12 @@ pub struct Settings { /// the body's region-link table, so a tap on the label outlines that exact region. Empty when no /// links were found (the section is then omitted from every tile). pub region_links: std::collections::HashMap<u64, u64>,+ /// Place-label id (tagged, `country` places only) -> the label's start zoom, from+ /// footprint × headcount (see `extract_fallback::country_zoom`). The tiler drops the+ /// label below its start zoom — same shape as `region_links`, probe-only so the+ /// archive stays deterministic. Absent ids keep the schema floor (z0): a missing+ /// score must never hide a country.+ pub country_zooms: std::collections::HashMap<u64, u8>, } /// One chunk's share of a zoom, keyed on `(tile id, layer id)`.
scripts/maps/mamaps_build/src/tiler_part1.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part1.rs b/scripts/maps/mamaps_build/src/tiler_part1.rsindex 281164bc3b..7ef4735615 100644--- a/scripts/maps/mamaps_build/src/tiler_part1.rs+++ b/scripts/maps/mamaps_build/src/tiler_part1.rs@@ -106,7 +106,7 @@ fn tile_zooms( // reads through the same ChunkReader either way. let spill = ChunkSpill::create_planned(&settings.scratch, chunk_plan)?; let mapped = std::time::Instant::now();- let (chunks, tally) = map_zoom(store, z, tolerance, buffer, &spill)?;+ let (chunks, tally) = map_zoom(store, settings, z, tolerance, buffer, &spill)?; stats.map_ms = mapped.elapsed().as_millis() as u64; stats.features = tally.features; stats.points = tally.points;@@ -291,6 +291,7 @@ fn plan_chunk_spill(store: &Store, scratch: &std::path::Path) -> osm_ingest::mem /// a configuration this has to stay byte-identical at. fn map_zoom( store: &Store,+ settings: &Settings, z: u8, tolerance: f64, buffer: f64,@@ -329,7 +330,7 @@ fn map_zoom( .name(format!("mamaps-tile-{i}")) .stack_size(WORKER_STACK) .spawn_scoped(scope, || {- tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer)+ tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer, &settings.country_zooms) }); match worker { Ok(handle) => spawned.push(handle),@@ -339,7 +340,7 @@ fn map_zoom( } } }- tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer);+ tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer, &settings.country_zooms); for handle in spawned { handle.join().map_err(|_| { tile_build::proto::Error("a tiling thread panicked".to_string())
scripts/maps/mamaps_build/src/tiler_part2.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part2.rs b/scripts/maps/mamaps_build/src/tiler_part2.rsindex 78066662ec..fd22a5a518 100644--- a/scripts/maps/mamaps_build/src/tiler_part2.rs+++ b/scripts/maps/mamaps_build/src/tiler_part2.rs@@ -260,6 +260,7 @@ fn tile_chunks( z: u8, tolerance: f64, buffer: f64,+ country_zooms: &std::collections::HashMap<u64, u8>, ) { loop { // Held to take a chunk and never while tiling one: the lock covers a pointer move, and the@@ -269,7 +270,7 @@ fn tile_chunks( // `AssertUnwindSafe` because everything the closure touches is a local: the chunk map it // builds is thrown away on a panic. let tiled = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- tile_chunk(&features, z, tolerance, buffer)+ tile_chunk(&features, z, tolerance, buffer, country_zooms) })); match tiled { Ok((chunk, tally)) => match spill.write_chunk(chunk) {@@ -299,10 +300,33 @@ fn tile_chunks( /// each of its hundreds of thousands of z13 tiles; now it is clipped once per zoom level. Filtering /// stays where it was, **before** the descent: significance is measured on the whole geometry, so a /// vertex's fate must not depend on which tile it lands in.-fn tile_chunk(features: &[Feature], z: u8, tolerance: f64, buffer: f64) -> (Chunk, Tally) {+///+/// `country_zooms` (place id → label start zoom, probe-only) drops a `country` label+/// below its start zoom before any geometry work: the label is a point, so nothing+/// downstream would remove it, and carrying it would defeat the gating.+fn tile_chunk(+ features: &[Feature],+ z: u8,+ tolerance: f64,+ buffer: f64,+ country_zooms: &std::collections::HashMap<u64, u8>,+) -> (Chunk, Tally) { let mut tiles: Chunk = BTreeMap::new(); let mut tally = Tally::default(); for feature in features {+ // Country label gating: the score (footprint × headcount) decided in stage A+ // (see `extract_fallback::country_zoom`); this is where it is enforced. A+ // missing score keeps the schema floor — a missing map entry must never hide+ // a country. Probe-only (`get`), never iterated, so the archive stays+ // deterministic; counted as dropped so the report stays honest.+ if feature.class.layer == tilecodec::mamaps::dict::LAYER_PLACES {+ if let Some(&start) = country_zooms.get(&feature.id) {+ if z < start {+ tally.dropped += 1;+ 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.
scripts/maps/mamaps_build/src/tiler_part7.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part7.rs b/scripts/maps/mamaps_build/src/tiler_part7.rsindex e2496cca07..d6601e269a 100644--- a/scripts/maps/mamaps_build/src/tiler_part7.rs+++ b/scripts/maps/mamaps_build/src/tiler_part7.rs@@ -73,6 +73,7 @@ mod tests { force_chunk_spill_file: false, dem: crate::dem::Dem::from_grids(14, 17, Vec::new()), region_links: std::collections::HashMap::new(),+ country_zooms: std::collections::HashMap::new(), } }