/// [`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, country_zooms: &mut HashMap, populations: &HashMap, ) -> Result { // Pass 1: boundary shapes AND places, in one scan. Only `region_area` // areas (the mask's own shapes, carrying the admin level in `kind_detail`); // border lines enclose nothing. Places are positional, so node, // way-centroided and relation-centroided labels all link by the tagged id // they already carry. // // One scan, not two: the store reader is one sequential cursor over tens // of GB of spill, and both passes filtered it by layer. Collecting both // vectors in a single streaming pass deletes a full decode. Peak is // unchanged — boundaries already lived through place collection. struct PlacePoint { id: u64, point: (f64, f64), kind: Band, kind_name: String, } enum Kept { Boundary(Boundary), Place(PlacePoint), } // The scan decodes the whole store across the pool (`Store::par_scan_where`, file order kept), and // the per-feature filter -- including `Boundary::new`'s area and bbox walk -- runs there too. // The split into the two vectors below is in file order, so both are exactly what the // one-cursor loop built. // Pre-filter on the packed class (no geometry decoded): only an id-carrying boundary area // or place can pass the filter below. let kept = store.par_scan_where( |class, has_id| { has_id && ((class.layer == LAYER_BOUNDARIES && class.area) || class.layer == LAYER_PLACES) }, |feature| { if feature.id == ID_NONE { return None; } if feature.class.layer == LAYER_BOUNDARIES && feature.class.area { let Geometry::Polygons(polygons) = feature.geometry else { return None; }; if polygons.is_empty() { return None; } Some(Kept::Boundary(Boundary::new(feature.id, feature.class.kind_detail, polygons))) } else if feature.class.layer == LAYER_PLACES { let Geometry::Points(points) = feature.geometry else { return None; }; let &point = points.first()?; let kind_name = place_kind_name(feature.class.kind)?; let band = band_for_place_kind(kind_name)?; Some(Kept::Place(PlacePoint { id: feature.id, point, kind: band, kind_name: kind_name.to_string(), })) } else { None } }, )?; let mut boundaries: Vec = Vec::new(); let mut places: Vec = Vec::new(); for item in kept { match item { Kept::Boundary(b) => boundaries.push(b), Kept::Place(p) => places.push(p), } } boundaries.retain(|b| b.bbox.is_some() && b.area > 0.0); let grid = Grid::build(&boundaries); // The `country_zoom` lookup below used to walk `boundaries` linearly per // linked country; indexed by id so it is a hash lookup instead. Built // once — the vec never moves again after this. let boundary_by_id: HashMap = boundaries.iter().enumerate().map(|(i, b)| (b.id, i)).collect(); // 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. 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. // // Collected serially first — the store reader is one sequential cursor — // then linked on the pool: `select_link` is pure per-place work over the // shared grid, and the drain inserts in collection order with member // links winning, exactly as the serial loop did. `select_link` returns // at most one target per place, so the drain cannot double-insert and // the map bytes are identical. // // NOTE: `places` now arrives from the fused pass-1 scan above (same // reader, same filter, same spill order), not from a second scan. What // follows is unchanged: drain order — and therefore every inserted key, // value, stat and country zoom — is identical. let mut stats = FallbackStats::default(); let mut per_kind: HashMap = HashMap::new(); // Member links always win: counted exactly as the serial loop did, // and skipped in the link pass so nothing contends on the map. for place in &places { stats.places_total += 1; let entry = per_kind.entry(place.kind_name.clone()).or_insert((0, 0)); entry.0 += 1; if region_links.contains_key(&place.id) { stats.member_linked += 1; entry.1 += 1; } } // Parallel link: one candidate-set build + `select_link` per // member-less place, on the pool; the drain inserts in collection // order, so the map — and the stats — are identical at every thread // count. `select_link` returns at most one target per place, so the // drain cannot double-insert. The bar ticks in the drain per place, so // it spans the whole pass even though the expensive half runs on the // pool. let mut bar = Progress::new("Fallback: places".to_string(), places.len(), "place(s)", true); const FALLBACK_BATCH: usize = 16 * 1024; let mut batch: Vec = Vec::with_capacity(FALLBACK_BATCH); let mut built: Vec> = Vec::with_capacity(FALLBACK_BATCH); let mut at = 0usize; while at < places.len() { batch.clear(); while at < places.len() && batch.len() < FALLBACK_BATCH { if region_links.contains_key(&places[at].id) { // Member-linked: counted above, nothing to compute. The tick // keeps the bar spanning every place, not just computed ones. bar.tick("place(s)"); at += 1; continue; } batch.push(at); at += 1; } if batch.is_empty() { continue; } built.clear(); par::install(|| { batch .par_iter() .map(|&pi| { let place = &places[pi]; let candidates: Vec<&Boundary> = grid.candidates_for(place.point).map(|i| &boundaries[i]).collect(); select_link(place.point, place.kind, &candidates) }) .collect_into_vec(&mut built) }); for (&pi, target) in batch.iter().zip(built.drain(..)) { let place = &places[pi]; if let Some(target) = target { region_links.insert(place.id, target); stats.fallback_linked += 1; if let Some(entry) = per_kind.get_mut(&place.kind_name) { 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 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. Unlinked countries keep // the schema floor (z0): a missing link must never hide a // country. if place.kind_name == "country" { if let Some(target) = region_links.get(&place.id) { if let Some(&bi) = boundary_by_id.get(target) { let boundary = &boundaries[bi]; let mid_lat = boundary.bbox.map(|(_, y0, _, y1)| (y0 + y1) / 2.0).unwrap_or(0.0); let population = populations.get(&place.id).copied().unwrap_or(0); country_zooms .insert(place.id, country_zoom(boundary.area, mid_lat, population)); stats.country_zooms += 1; } } } bar.tick("place(s)"); } } bar.finish("place(s)"); stats.fallback_missed = stats.places_total.saturating_sub(stats.member_linked + stats.fallback_linked); let mut kinds: Vec<(String, u64, u64)> = per_kind.into_iter().map(|(kind, (total, linked))| (kind, total, linked)).collect(); kinds.sort_by(|a, b| a.0.cmp(&b.0)); stats.per_kind = kinds; Ok(stats) }