#[allow(clippy::too_many_arguments)] fn build_inner( input: &Path, geojson: &Path, names: &Path, index: &Path, attrs: &Path, spatial: &Path, name_index: &Path, region: &Path, bbox: Option, mut reviews: Reviews<'_>, ) -> Result { // Fail before the three passes rather than after them if an output path is // unwritable. for path in [geojson, names, index, attrs, spatial, name_index, region] { if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent) .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?; } } let mut timer = crate::timing::PhaseTimer::start("poi"); let blobs = pbf::scan_blobs(input)?; println!("[poi] Scanned {} data blob(s) in {}", blobs.len(), input.display()); timer.switch("relations"); // --- Pass 1: area relations --------------------------------------------- let (chunks, blob_kinds) = pbf::run_pass( input, &blobs, None, KIND_RELATIONS, "Pass 1: relations", RelPass::default, relation_blob, )?; let mut rel_areas: Vec = Vec::new(); let mut boundaries: Vec = Vec::new(); for chunk in chunks { rel_areas.extend(chunk.areas); boundaries.extend(chunk.boundaries); } let mut outer_wanted: Vec = rel_areas .iter() .flat_map(|a| a.outer_ways.iter().copied()) .chain(boundaries.iter().flat_map(|b| b.member_ways.iter().map(|(w, _)| *w))) .collect(); par_sort_dedup(&mut outer_wanted); println!("{} POI relation(s)", rel_areas.len()); reviews.poll()?; timer.switch("ways"); // --- Pass 2: closed-way areas + the relations' outer ways ---------------- let (chunks, _) = pbf::run_pass( input, &blobs, Some(&blob_kinds), KIND_WAYS, "Pass 2: ways", WayPass::default, |state, block| way_blob(state, block, &outer_wanted), )?; let mut way_areas: Vec = Vec::new(); let mut outer_refs: HashMap> = HashMap::new(); for chunk in chunks { way_areas.extend(chunk.areas); outer_refs.extend(chunk.outer_refs); } // Every node whose location an area centroid needs. let mut needed: Vec = way_areas .iter() .flat_map(|a| a.refs.iter().copied()) .chain(outer_refs.values().flat_map(|r| r.iter().copied())) .collect(); par_sort_dedup(&mut needed); println!("{} closed-way area(s), {} node location(s) needed", way_areas.len(), needed.len()); reviews.poll()?; timer.switch("nodes"); // --- Pass 3: node POIs + the node locations areas need ------------------- let (chunks, _) = pbf::run_pass( input, &blobs, Some(&blob_kinds), KIND_NODES, "Pass 3: nodes", NodePass::default, |state, block| node_blob(state, block, &needed, bbox.as_ref()), )?; let mut pois: Vec = Vec::new(); let mut locs: Vec<(i32, i32)> = vec![(NO_LOC, NO_LOC); needed.len()]; for chunk in chunks { pois.extend(chunk.pois); for (idx, lat, lon) in chunk.locs { locs[idx as usize] = (lat, lon); } } let from_nodes = pois.len(); let location = |id: i64| -> Option<(i32, i32)> { let idx = needed.binary_search(&id).ok()?; let (lat, lon) = locs[idx]; (lat != NO_LOC).then_some((lat, lon)) }; // A POI touches the region when any of its vertices does — same // `complete_ways` rule as the graph. The centroid is computed from the // whole ring regardless, so a border-straddling POI keeps its true // location. let touches = |ids: &mut dyn Iterator| -> bool { let Some(b) = bbox.as_ref() else { return true; }; ids.filter_map(&location).any(|(lat, lon)| b.contains_e7(lat, lon)) }; timer.switch("centroids"); // --- Area centroids ------------------------------------------------------ // Each area's POI depends on that area alone; `collect` keeps area order, so // `pois` comes out exactly as the serial loop pushed it. use rayon::prelude::*; let way_pois: Vec> = crate::par::install(|| { way_areas .par_iter() .with_min_len(256) .map(|area| { if !touches(&mut area.refs.iter().copied()) { return None; } // A closed way's ring is its own node list minus the repeated // closing node. let poi = ring_centroid(area.refs[..area.refs.len() - 1].iter().copied(), &location)?; Some(make_poi( poi, area.type_, area.id, &area.name, area.attrs.clone(), area.self_region, area.place_cap, )) }) .collect() }); pois.extend(way_pois.into_iter().flatten()); let from_ways = pois.len() - from_nodes; let rel_pois: Vec> = crate::par::install(|| { rel_areas .par_iter() .with_max_len(16) .map(|area| { // libosmium assembled a true ring from the member ways; we cannot, // so deduplicate the member node ids instead. That is exact when // the outer ring is a single closed way, and drops the endpoints // shared between consecutive ways when it is split across several. let mut refs: Vec = area .outer_ways .iter() .filter_map(|w| outer_refs.get(w)) .flat_map(|r| r.iter().copied()) .collect(); refs.sort_unstable(); refs.dedup(); if !touches(&mut refs.iter().copied()) { return None; } let poi = ring_centroid(refs.iter().copied(), &location)?; Some(make_poi( poi, area.type_, -area.id, &area.name, area.attrs.clone(), area.self_region, area.place_cap, )) }) .collect() }); pois.extend(rel_pois.into_iter().flatten()); let from_relations = pois.len() - from_nodes - from_ways; println!( "Extracted {} POI(s): {from_nodes} node, {from_ways} closed-way, {from_relations} relation", pois.len() ); // Before the sort: `pois` is still nodes, then ways, then relations, which is // the only place the OSM element type is known. timer.switch("reviews-wait"); reviews.join()?; timer.switch("reviews"); let with_reviews = match reviews.table() { Some(table) => { let n = apply_reviews(&mut pois, from_nodes, from_ways, table); println!("{n} POI(s) with review data ({} review row(s) loaded)", table.len()); n } None => 0, }; // Before the sort: `pois` is still nodes, then ways, then relations, which is // the only place the OSM element type is known. Region links resolve here // for the same reason reviews do — and the stamped ids ride the Morton sort // on the `Poi` struct, so `poi_region.bin` joins by ordinal afterwards. timer.switch("regions-assemble"); let assembled = assemble_boundaries(&boundaries, &outer_refs, &location); timer.switch("regions-stamp"); let with_region = stamp_regions(&mut pois, from_nodes, &boundaries, &assembled); if with_region > 0 { println!("{with_region} POI(s) with a boundary link"); } // Morton order, ties broken by osm_id, so both poi_index.bin and the geojson // are stable across runs. timer.switch("sort"); // `par_sort_by_key` is stable like `sort_by_key`, so equal keys keep the // pre-sort (nodes, ways, relations) order exactly as before. crate::par::install(|| pois.par_sort_by_key(|p| (p.morton, p.osm_id))); let written = write_outputs( &pois, geojson, names, index, attrs, spatial, name_index, region, &mut timer, )?; // `poi_admin.bin` rides beside `poi_region.bin` (no new flag, so every caller emits it). timer.switch("admin"); let admin = admin_table(&boundaries, &assembled, &pois); let admin_entries = write_with(®ion.with_file_name("poi_admin.bin"), |out| { crate::poi_admin::write_admin(out, &admin) })?; println!("Wrote {admin_entries} administrative boundar(ies) to poi_admin.bin"); timer.finish(); Ok(Stats { records: written.records, unique_names: written.unique_names, name_bytes: written.name_bytes, from_nodes, from_ways, from_relations, with_attrs: written.with_attrs, unique_attrs: written.unique_attrs, attr_bytes: written.attr_bytes, spatial_cells: written.spatial_cells, name_entries: written.name_entries, with_reviews, with_region, admin_entries, }) } /// Append each matching review row to its POI's attribute body; returns the match /// count. `pois[..from_nodes]` are nodes, the next `from_ways` closed ways, the /// rest relations (whose `osm_id` is stored negated). fn apply_reviews( pois: &mut [Poi], from_nodes: usize, from_ways: usize, table: &ReviewTable, ) -> usize { use rayon::prelude::*; // Per-POI and independent, so chunking cannot change any POI's body. crate::par::install(|| { pois.par_iter_mut() .enumerate() .with_min_len(4096) .map(|(i, p)| { let (element, id) = if i < from_nodes { (ELEMENT_NODE, p.osm_id) } else if i < from_nodes + from_ways { (ELEMENT_WAY, p.osm_id) } else { (ELEMENT_RELATION, -p.osm_id) }; match table.get(element, id) { Some(review) => { p.attrs = crate::poi_attrs::append( std::mem::take(&mut p.attrs), &review.fields(), ); true } None => false, } }) .filter(|hit| *hit) .count() }) } /// Sort ascending and drop duplicates. The values are plain integers, so an /// unstable parallel sort yields exactly the serial `sort_unstable` + `dedup`. fn par_sort_dedup(v: &mut Vec) { use rayon::prelude::*; crate::par::install(|| v.par_sort_unstable()); v.dedup(); } fn poi_tags<'a>(t: &osm::Tags<'_, 'a>) -> PoiTags<'a> { PoiTags { railway: t.get_str("railway"), public_transport: t.get_str("public_transport"), amenity: t.get_str("amenity"), shop: t.get_str("shop"), tourism: t.get_str("tourism"), leisure: t.get_str("leisure"), healthcare: t.get_str("healthcare"), office: t.get_str("office"), place: t.get_str("place"), } } /// Deepest `admin_level` a place POI may link to, from its `place` value: /// a country links at level 2, a state/province at 4, everything else (cities /// down to neighbourhoods) at 8. Non-place POIs link at any level. fn place_level_cap(place: Option<&str>) -> u8 { match place { Some("country") => 2, Some("state" | "province") => 4, Some(_) => 8, None => 8, } } fn relation_blob(state: &mut RelPass, block: &pbf::PrimitiveBlock) -> Result { let mut kinds = 0u8; visit_block(block, KIND_RELATIONS, &mut kinds, &mut |el: Element| { if let Element::Relation(r) = el { // Boundary relations feed the region-link geometry whether or not they // are POIs themselves. A `boundary=administrative` relation is // linkable when it carries an `admin_level`; `type=boundary` without // one still assembles but links at the deepest level. if r.tags.get_str("type") == Some("boundary") && r.tags.get_str("boundary") == Some("administrative") { let admin_level: u8 = r.tags.get_str("admin_level").and_then(|v| v.parse().ok()).unwrap_or(8); state.boundaries.push(BoundaryRel { id: r.id, admin_level, name: r.tags.get("name").map(|v| v.to_vec()).unwrap_or_default(), name_en: r.tags.get("name:en").map(|v| v.to_vec()).unwrap_or_default(), member_ways: r .members .iter() .filter(|m| { m.kind == MEMBER_WAY && (m.role == b"outer" || m.role == b"inner" || m.role.is_empty()) }) .map(|m| (m.id, m.role != b"inner")) .collect(), label_nodes: r .members .iter() .filter(|m| { m.kind == MEMBER_NODE && (m.role == b"label" || m.role == b"admin_centre") }) .map(|m| m.id) .collect(), }); // A boundary relation with a name and POI tags is still a POI in its // own right (a national park on the relation, a `place` label on the // boundary). Fall through to the area path below. } let is_area = r.tags.get_str("type").is_some_and(|t| AREA_RELATION_TYPES.contains(&t)); if !is_area { return Ok(()); } let name = match r.tags.get("name") { Some(n) if !n.is_empty() => n, _ => return Ok(()), }; if let Some(type_) = tags::classify(&poi_tags(&r.tags)) { let self_region = if r.tags.get_str("boundary") == Some("administrative") { poi_side::tag_relation(r.id) } else { poi_side::REGION_NONE }; state.areas.push(RelArea { id: r.id, type_, name: name.to_vec(), attrs: crate::poi_attrs::encode(|k| r.tags.get(k)), outer_ways: r .members .iter() .filter(|m| { m.kind == MEMBER_WAY && (m.role == b"outer" || m.role.is_empty()) }) .map(|m| m.id) .collect(), self_region, place_cap: place_level_cap(r.tags.get_str("place")), }); } } Ok(()) })?; Ok(kinds) }