/// Pass 1 (ways + relations) plus the corridor promotion. Moved whole from /// `extract` so part files can cut at fn boundaries; behavior identical. /// /// `blob_kinds_in` is an optional pre-computed mask (the graph sidecar) that lets this pass skip /// node blobs; `None` means scan the whole file. Either way the mask it returns is complete. /// /// `spill_plan` is the budget gate's backend choice: the ways spill stages anonymously or through /// the `.tmp` at `ways_path`. Decided by the caller from pass-0 counts, not here, because this /// pass cannot know the graph size that shares its peak. #[allow(clippy::too_many_arguments)] fn run_pass1( input: &Path, blobs: &[pbf::BlobLoc], blob_kinds_in: Option<&[u8]>, select: &Select, layers: Layers, ways_path: &Path, spill_plan: osm_ingest::mem::SpillPlan, stats: &mut Stats, timer: &mut crate::timing::PhaseTimer, ) -> Result { // --- pass 1: ways and relations ------------------------------------------------------- // // `run_pass_sink` rather than `run_pass`, because `run_pass`'s contract is to hand back every // chunk at once and these chunks hold the node refs of every classified way — the 2.7 GB this // spill exists to be rid of. Here a chunk is appended to the file and freed while its // neighbours are still decoding. // // `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 mut ways = WaySink::create_planned(ways_path, spill_plan)?; let mut relations: Vec = Vec::new(); // The needed-node bitset, fused into this pass: every classified way sets // its refs here in the drain below, so pass 3 never re-reads the ways // spill to collect them. Grows on demand (the maximum is not known until // the last push); member refs join after the drain. let mut needed = NeededBits::new_growable(); // `admin_centre`/`label` node member -> boundary relation id (raw), gathered as region shapes // are classified below. See [`Pass1Out::region_label_nodes`]. let mut region_label_nodes: HashMap = HashMap::new(); // Road ways carrying a `ref`, for the corridor pass below. A small minority of ways, // and the only thing pass 1 keeps in memory besides the relations. let mut corridors: Vec = Vec::new(); let blob_kinds = pbf::run_pass_sink( input, blobs, pbf::PassSpec { blob_kinds: blob_kinds_in, want: KIND_WAYS | KIND_RELATIONS, label: "Pass 1: ways and relations", }, || { ( Vec::::new(), Vec::::new(), Vec::::new(), Vec::<(i64, i64)>::new(), Vec::::new(), ) }, |state, block| { let mut kinds = 0u8; // This block's refs land past here; sorted and deduped below, so the drain sets // the needed bitset in ascending runs instead of chasing every ref. let refs_from = state.4.len(); 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) { // A numbered road's `min_zoom` is decided per corridor, not per // way, so that a route does not vanish where its class changes. // Slip roads are left out: they carry the parent's `ref` and // would be promoted into junction stubs at world zoom. if class.layer == tilecodec::mamaps::dict::LAYER_ROADS && class.flags & tilecodec::mamaps::body::FLAG_IS_LINK == 0 && way.refs.len() >= 2 { if let Some(route) = crate::corridor::route_key(&way.tags) { state.2.push(crate::corridor::Segment { way_id: way.id, route, first_node: way.refs[0], last_node: way.refs[way.refs.len() - 1], min_zoom: class.min_zoom, }); } } let name = schema::display_name(&way.tags, class.layer); // A road's carriageway lane count, per-lane turn masks and directional // split, baked so the renderer can draw the lanes individually, place // turn arrows and put the centre line where the traffic divides. Zero, // empty and default for every other layer. let is_road = class.layer == tilecodec::mamaps::dict::LAYER_ROADS; let lane_count = if is_road { schema::roads::lane_count(&way.tags) } else { 0 }; let (turn_fwd, turn_bwd) = if is_road { schema::roads::turn_masks(&way.tags) } else { (Vec::new(), Vec::new()) }; let carriageway = if is_road { schema::roads::carriageway(&way.tags) } else { Carriageway::default() }; // A building's S3DB attributes, parsed once here beside its class. // Zero-cost for the overwhelming majority of ways, which are not // buildings. let building = if class.layer == LAYER_BUILDINGS { Some(schema::buildings::attrs(&way.tags)) } else { None }; // Encoded HERE, on the worker, into the chunk's ways-spill blocks: the // drain only patches each block's first id and appends it. This was // the serial drain's record-by-record encode, which held pass 1 to ~4 // of 192 cores on the planet (4m40s). Same bytes; see `WayBlock`. if state.0.last().is_none_or(|b| b.len() >= WAY_BLOCK_WAYS) { state.0.push(WayBlock::new()); } let refs: &[i64] = way.refs; state.0.last_mut().expect("pushed above").push( way.id, &class, refs, name.as_deref(), lane_count, &turn_fwd, &turn_bwd, carriageway, building, )?; state.4.extend_from_slice(refs); } } Element::Relation(relation) => { // Two relation types carry a shape. Anything else — a site, a // public_transport — does not. if !matches!( relation.tags.get_str("type"), Some("multipolygon" | "boundary") ) { 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: Vec<_> = relation .members .iter() .filter(|m| m.kind == MEMBER_WAY) .map(|m| (m.id, m.role == b"inner")) .collect(); // **The schema decides**, not the relation's `type` tag. Both an // administrative border and a protected area are `type=boundary`, and // one is a line while the other is a shape — which is exactly the // distinction `Class::area` exists to make. let area = class.area; let name = schema::display_name(&relation.tags, class.layer); // A multipolygon building (a footprint with a courtyard) carries S3DB // attributes just as a building way does. let building = if class.layer == LAYER_BUILDINGS { Some(schema::buildings::attrs(&relation.tags)) } else { None }; // A country's code, kept so the region shape below can stamp its // driving side and centre-line colour onto the tiles it covers. let iso = schema::boundaries::country_code(&relation.tags) .map(str::to_string); // An administrative relation yields *two* features: the border, which // is a line and is what the basemap draws, and the region's shape, // which nothing draws and the region mask reads. They cannot be one // feature — a clipped polygon grows tile-edge segments and the border // layer strokes them into a grid. See `schema::boundaries`. if let Some(shape) = schema::boundaries::region_area(&relation.tags, false) { // The boundary points at its own label/centre node directly: record // that node -> this relation so the place label it becomes can carry // the id. `label` overwrites `admin_centre` (the label node is the // one that renders; admin_centre is the capital, a different node). for m in relation.members.iter() { if m.kind == MEMBER_NODE && m.role == b"admin_centre" { state.3.push((m.id, relation.id)); } } for m in relation.members.iter() { if m.kind == MEMBER_NODE && m.role == b"label" { state.3.push((m.id, relation.id)); } } state.1.push(Relation { class: shape, members: members.clone(), area: true, name: name.clone(), id: relation.id, building: None, population: None, iso: iso.clone(), }); } state.1.push(Relation { class, members, area, name, id: relation.id, building, population: Some(schema::places::population_of(&relation.tags)), iso: None, }); } } Element::Node(_) => {} } Ok(()) })?; sort_dedup_tail(&mut state.4, refs_from); Ok(kinds) }, |(chunk_ways, chunk_relations, chunk_corridors, chunk_label_nodes, chunk_refs)| { // Chunks arrive in file order and a PBF's ways are sorted by id, so appending here // leaves the file in ascending id order. `WaySink::push_block` refuses an id that does // not advance rather than letting an unsorted file reorder the archive silently. for block in &chunk_ways { ways.push_block(block)?; } // Fused ref collection: the refs were decoded on the worker, so the bitset takes // them now instead of a later pass re-reading the spill to find them again. A bitset // is order- and duplicate-blind, so the per-block sort/dedup changes no bit. for &node in &chunk_refs { needed.set_growable(node)?; } relations.extend(chunk_relations); corridors.extend(chunk_corridors); // `label` was pushed after `admin_centre`, so inserting in order lets the label win. for (node_id, rel_id) in chunk_label_nodes { region_label_nodes.insert(node_id, rel_id); } Ok(()) }, )?; let (counts, store) = ways.finish_either()?; stats.ways_classified = counts.ways; let (ways, way_refs, way_max_ref, ways_anon, way_blocks) = (counts.ways, counts.refs, counts.max_ref, store.map(std::sync::Arc::new), counts.blocks); stats.relations_classified = relations.len() as u64; // A numbered road changes class along its length, so deciding `min_zoom` per way chops // a corridor into stubs at the zooms where only its motorway parts survive. Promote // each connected same-`ref` run to the shallowest zoom any of its ways asks for, then // drop the segments: only the (way id, zoom) overrides are needed from here. timer.switch("corridors"); let promoted = crate::corridor::promote(&corridors); stats.corridor_promotions = promoted.len() as u64; drop(corridors); Ok(Pass1Out { relations, promoted, blob_kinds, ways, way_refs, way_max_ref, ways_anon, way_blocks, region_label_nodes, needed, }) } /// Sort and dedup `v[from..]` in place, leaving `v[..from]` untouched. fn sort_dedup_tail(v: &mut Vec, from: usize) { v[from..].sort_unstable(); let mut write = from; for read in from..v.len() { if write == from || v[read] != v[write - 1] { v[write] = v[read]; write += 1; } } v.truncate(write); }