Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / extract_part1.rs

extract_part1.rs638 lines · 32.2 KiBRaw
1/// Read `input` and spill every feature the schema classifies to `spill_path`.
2///
3/// Features go to disk rather than into a `Vec`, because holding them was 4.9 GB of a measured
4/// 10.03 GB California peak and nothing reads them until the tiler does. Classified ways go to a
5/// scratch file beside it for the same reason. See [`crate::store`].
6///
7/// `region` filters the **built** layers (`roads`, `poi`, `buildings`) to the
8/// region's bbox. Every other layer is always included regardless. `None`
9/// (world) disables the filter entirely.
10pub fn extract(
11 input: &Path,
12 layers: Layers,
13 coastline: &Path,
14 transit_routes: &Path,
15 graph: &Path,
16 spill_path: &Path,
17 region: Option<osm_ingest::bbox::BBox>,
18 timer: &mut crate::timing::PhaseTimer,
19) -> Result<(Store, Stats, HashMap<u64, u64>, HashMap<u64, u64>)> {
20 // Stage A's boundaries are subphase switches on the run's `PhaseTimer`, so an external RSS
21 // sampler can say which of them the peak belongs to. Three candidates sit within seconds of
22 // each other -- the ref vector, the id index built beside it, and the node pass's per-chunk
23 // accumulators -- and guessing between them has already cost more than naming them does.
24 let blobs = pbf::scan_blobs(input)?;
25 let select = Select::parse(&schema::filters())?;
26 let mut stats = Stats::default();
27 // Scratch for this function alone: written in pass 1, read twice below, and removed as soon as
28 // the last read is done. Beside the feature spill, so a build directed at a writable output
29 // directory needs nothing else to be writable.
30 let ways_path = spill_path.with_extension("ways.tmp");
31
32 // A blob-kinds mask cached beside the routing graph -- `road_graph`'s pass 1 wrote it over this
33 // same `.pbf` -- lets pass 1 skip node blobs outright rather than inflating them to learn they
34 // hold no ways or relations. Guarded by blob count, file length and mtime, so a missing or stale
35 // sidecar simply falls back to a full scan. Byte-neutral either way: the mask `run_pass1` returns
36 // carries the skipped blobs' kinds, so it is a complete description of the file regardless.
37 //
38 // The sidecar also proves the graph was built over THIS pbf: when the
39 // region filter is on, a world graph beside a california tile build (or
40 // vice versa) would silently mismatch layers. A missing sidecar here only
41 // warns — the blob mask itself is optional — but a region build still
42 // validates the graph's own coverage below in `append_external_and_finish`.
43 timer.switch("blob-kinds");
44 let graph_kinds = pbf::load_blob_kinds(graph, input, &blobs);
45 if let Some(b) = region.as_ref() {
46 println!(
47 "region filter: keeping roads/pois/buildings touching {:.3},{:.3} .. {:.3},{:.3}",
48 b.min_lon, b.min_lat, b.max_lon, b.max_lat,
49 );
50 }
51
52 let ways_plan = plan_ways_spill(input, &blobs, &ways_path)?;
53 timer.switch("pass1");
54 let pass1 = run_pass1(input, &blobs, graph_kinds.as_deref(), &select, layers, &ways_path, ways_plan, &mut stats, timer)?;
55 timer.switch("member-ways");
56 let members = load_member_ways(input, &blobs, &pass1.blob_kinds, &pass1.relations)?;
57 // --- budget gate (phase 1: real counts) ------------------------------------------
58 //
59 // The planet build died at the junction tail with `cannot commit anon segment` (OS error
60 // 1455): anonymous spills charge RAM+pagefile ("commit"), and nothing checked the charge
61 // against the limit before asking. Pass 1 measured the real counts (classified ways and
62 // relations, total refs, max ref), the ways spill sealed at an exact byte length, and the
63 // graph files stat to theirs -- so the feature spill's backend is decided HERE, from those
64 // counts, failing fast with the numbers when neither backend fits. Same records either way;
65 // the backend never changes a hash.
66 timer.switch("spill-budget");
67 let spill_plan = plan_feature_spill(&pass1, &members, graph, spill_path)?;
68 // Created before the fused node pass below, which spills `places`/`poi` label nodes straight
69 // into it. This sits where pass 4's `Sink::create` used to, moved earlier so those labels reach
70 // the sink in the same order -- chunk order, ahead of every way and relation -- they did when
71 // classification was its own pass after the coordinate resolve. Nothing else touches
72 // `spill_path` until then; the lane-fill temps hang off `with_extension`.
73 let mut sink = Sink::create_planned(spill_path, spill_plan)?;
74 // Take pass 1 apart so each piece can be freed the moment its last reader is done. `pass1`
75 // itself is consumed here: nothing below sees it whole, which is what makes a use-after-free
76 // a compile error rather than a peak.
77 let Pass1Out {
78 relations,
79 promoted,
80 blob_kinds,
81 ways: _,
82 way_refs,
83 way_max_ref,
84 ways_anon,
85 region_label_nodes,
86 mut needed,
87 } = pass1;
88 // The ways spill, shared by refcount with the readers below (lanefill
89 // scan, materialise). Last use is `materialise_ways`; freed there.
90 timer.switch("refs-collect");
91 // Member ways' refs join the fused bitset: the great majority carry no
92 // tags of their own, so nothing else asked for them.
93 for refs in members.values() {
94 for &id in refs {
95 needed.set_growable(id)?;
96 }
97 }
98 let table = build_resolved_table(
99 input,
100 &blobs,
101 &blob_kinds,
102 &members,
103 needed,
104 &select,
105 layers,
106 region.as_ref(),
107 &mut sink,
108 &mut stats,
109 timer,
110 )?;
111 // The node pass was the last reader of the blob-kinds mask. Freed before lanefill so the
112 // mask (one byte per blob, small) does not pin anything beside it -- and, more importantly,
113 // so the next large allocation cannot sit beside a dead one.
114 drop(blob_kinds);
115 timer.switch("lane-inherit");
116 let inherited_lanes = inherit_lane_counts(
117 spill_path,
118 &ways_path,
119 &ways_anon,
120 &table,
121 stats.ways_classified as usize,
122 region.as_ref(),
123 )?;
124 stats.lanes_inherited = inherited_lanes.len() as u64;
125
126 // --- materialise ----------------------------------------------------------------------
127 //
128 // Ways in **id order**, which is the order the spill file is already in. The label nodes were
129 // already spilled into `sink` during the fused node pass above, so this only *adds* ways and
130 // relations after them -- the order the tiler groups by layer id from.
131 timer.switch("materialise-ways");
132 materialise_ways(
133 &ways_path,
134 &ways_anon,
135 &promoted,
136 &inherited_lanes,
137 &table,
138 region.as_ref(),
139 &mut sink,
140 &mut stats,
141 )?;
142 // The ways spill is dead from here: no later phase reads it. Dropping the `Arc`s unmaps the
143 // anon segments, which releases pagefile commit immediately (unlike heap frees, which the
144 // allocator may hold). This is the tens-of-GB ways spill, freed BEFORE the routing graph
145 // is loaded below -- the two must never peak together.
146 drop(ways_anon);
147 drop(promoted);
148 drop(inherited_lanes);
149 timer.switch("materialise-relations");
150 let conventions = materialise_relations(
151 &relations,
152 &members,
153 &table,
154 region.as_ref(),
155 &mut sink,
156 &mut stats,
157 )?;
158 // Country headcounts for label zoom scoring (see `extract_fallback::country_zoom`):
159 // relation id (tagged) -> `population` tag. Node/way countries have no relation to
160 // read it from and score as unpopulated; the area term still separates Russia from
161 // Nauru. Built BEFORE `relations` is dropped below (it dies at "OSM tables freed").
162 let country_populations: HashMap<u64, u64> = relations
163 .iter()
164 .filter_map(|r| {
165 r.population.and_then(|pop| {
166 (r.class.layer == tilecodec::mamaps::dict::LAYER_PLACES)
167 .then(|| (tagged_id(r.id, ELEMENT_RELATION), pop))
168 })
169 })
170 .collect();
171 // The OSM tables are dead from here: relations, member refs and the coordinate table serve
172 // only materialisation. Dropping them before the externals (coastline, transit, graph)
173 // keeps the RankIndex bitset (~1.5 GB on planet), the resolved bitset and the mapped locs
174 // file out of the junction phase, where `Graph::load` needs its own gigabytes.
175 drop(relations);
176 drop(members);
177 drop(table);
178 timer.switch("land-polygons");
179 let store = append_external_and_finish(
180 coastline,
181 transit_routes,
182 graph,
183 sink,
184 &mut stats,
185 conventions,
186 spill_path,
187 timer,
188 )?;
189 // The place-label -> boundary link, tagged into the id space the archive uses (a place carries
190 // its node id tagged as a node; the mask keys on the boundary's relation id tagged as a
191 // relation). The tiler stamps each `places` label with its linked id from this.
192 let region_links: HashMap<u64, u64> = region_label_nodes
193 .iter()
194 .map(|(&node, &rel)| (tagged_id(node, ELEMENT_NODE), tagged_id(rel, ELEMENT_RELATION)))
195 .collect();
196 Ok((store, stats, region_links, country_populations))
197}
198
199/// Spill bytes per classified feature, calibrated from measured builds.
200///
201/// California (10.03 GB peak): ~15.5 M features spilled ~2.0 GB => ~135 B/feature raw. The record
202/// is a varint stream (delta-coded refs were in the *ways* spill, not here; here it is e7
203/// coordinates plus a packed class plus optional names/ids/lane data), so this varies by layer
204/// mix -- but the gate only needs order-of-magnitude, and over-estimating pushes to files, which
205/// is the safe side.
206///
207/// Stored compressed: the spill stages per-chunk DEFLATE frames (~3x on coordinate runs), so the
208/// file holds roughly a third of the raw bytes. 96 B lands between the compressed California
209/// figure (~45 B) and the raw one, leaning the safe way; the gate's job is only to pick the
210/// backend, and files are the safe side.
211const SPILL_BYTES_PER_FEATURE: u64 = 96;
212
213/// Budget gate, phase 0: which backend the *ways* spill stages in.
214///
215/// Runs BEFORE pass 1, so no classified counts exist yet -- only the input size, the blob count
216/// and the commit/disk limits. The ways spill holds one delta-coded record per classified way
217/// (tens of bytes each: a varint id gap, a packed class, delta-coded refs at ~1 B each), and on
218/// planet that is 1.1 B ways => tens of GB. The estimate is deliberately crude (input bytes / 32,
219/// bounded below by 1 GB for planet-scale inputs): over-estimating files a build that would have
220/// fit anon, under-estimating pages it. Files are the safe side -- same records, removed after
221/// materialise -- so the bound leans that way past 8 GB of input.
222fn plan_ways_spill(
223 input: &Path,
224 blobs: &[pbf::BlobLoc],
225 ways_path: &Path,
226) -> Result<osm_ingest::mem::SpillPlan> {
227 let input_bytes = std::fs::metadata(input)
228 .map(|m| m.len())
229 .unwrap_or(0);
230 // No gate on small inputs: the historical anon path, no behaviour change.
231 if input_bytes < (8u64 << 30) {
232 return Ok(osm_ingest::mem::SpillPlan::Anon);
233 }
234 let estimate = (input_bytes / 32).max(1 << 30);
235 let mut budget = osm_ingest::mem::StageBudget::default();
236 budget.ways_spill_bytes = estimate;
237 // Phase 0 knows nothing else yet; the rest is zero, so `anon_commit_bytes` is just this.
238 let context = format!(
239 "stage A ways spill (pre-pass estimate {} from {} input over {} blobs)",
240 osm_ingest::mem::fmt_gb(estimate),
241 osm_ingest::mem::fmt_gb(input_bytes),
242 blobs.len(),
243 );
244 osm_ingest::mem::SpillPlan::decide(&budget, ways_path, &context)
245 .map_err(osm_ingest::proto::Error)
246}
247
248/// Budget gate, phase 1: which backend the *feature* spill stages in.
249///
250/// Runs AFTER pass 1, so every count is real: classified ways/relations, total refs, max ref, the
251/// sealed ways-spill length, member-way refs. The feature estimate is `ways + relations +
252/// externals` times [`SPILL_BYTES_PER_FEATURE`]; the graph sizes from `metadata.bin`'s
253/// 40-byte header before anything is mapped. Relations move the needle less (8.4 M vs 1.1 B ways
254/// on planet) and are counted at struct overhead -- their member refs are already inside the
255/// distinct-node estimate via the bitset walk.
256///
257/// `ways`, not refs: `Pass1Out::way_refs` is the ref *total* (duplicates included, ~12 G on
258/// planet), which would size the spill 10x over and refuse, on estimates alone, builds whose
259/// real spill fits. The externals headroom leans the safe way instead: the junction connectors
260/// (~746 M on planet) arrive after this gate, so half the way count stands in for them plus
261/// land/transit, pushing continent-scale builds to files (same records, removed on success).
262fn plan_feature_spill(
263 pass1: &Pass1Out,
264 members: &MemberWays,
265 graph: &Path,
266 spill_path: &Path,
267) -> Result<osm_ingest::mem::SpillPlan> {
268 let member_refs: u64 = members.values().map(|refs| refs.len() as u64).sum();
269 let refs_total = pass1.way_refs.saturating_add(member_refs);
270 // Distinct nodes <= total refs; the collector dedups, so size the table on the upper bound.
271 // `max_node_id` bounds the rank bitset; `distinct` (upper-bounded here) sizes the resolved
272 // bit and the locs file.
273 let mut budget = osm_ingest::mem::StageBudget::default();
274 budget.distinct_nodes = refs_total;
275 budget.max_node_id = pass1.way_max_ref.max(0) as u64;
276 budget.ways_spill_bytes = pass1
277 .ways_anon
278 .as_ref()
279 .map(|a| a.len())
280 .unwrap_or_else(|| std::fs::metadata(spill_path.with_extension("ways.tmp")).map(|m| m.len()).unwrap_or(0));
281 // Features to come: every classified way and relation materialises at most one feature, plus
282 // the externals below (the junction connectors dominate: ~746 M on planet, arriving after
283 // this gate, hence the ways/2 headroom on the safe side).
284 budget.features_expected = pass1
285 .ways
286 .saturating_add(pass1.relations.len() as u64)
287 .saturating_add(pass1.ways / 2)
288 .saturating_add(2_000_000);
289 budget.bytes_per_feature = SPILL_BYTES_PER_FEATURE;
290 budget.relations = pass1.relations.len() as u64;
291 budget.graph_bytes = graph_mapped_bytes(graph).unwrap_or(0);
292 let context = format!(
293 "stage A feature spill ({} ways, {} relations, {} refs, max node {})",
294 pass1.ways, pass1.relations.len(), refs_total, pass1.way_max_ref,
295 );
296 // Warn-and-file rather than fail: the counts above are order-of-magnitude (the feature
297 // estimate most of all), and refusing on them alone would abort builds whose real spill
298 // fits. Files are the safe side -- same records, removed on success -- and a volume that
299 // truly is too small still fails naturally, with its path in the error.
300 match osm_ingest::mem::SpillPlan::decide(&budget, spill_path, &context) {
301 Ok(plan) => Ok(plan),
302 Err(e) => {
303 eprintln!("WARN: {e}; continuing with file staging");
304 Ok(osm_ingest::mem::SpillPlan::File)
305 }
306 }
307}
308
309/// Bytes the junction phase must address at once: the three mapped graph files plus `lanes.bin`,
310/// plus the `InEdges` reverse index (`4 * (node_count + 1)` start array + 4 per drivable edge,
311/// upper-bounded by 4 per edge). Sized from `metadata.bin`'s 40-byte header -- the same header
312/// `check_graph_dir` already validates -- before anything is mapped.
313fn graph_mapped_bytes(dir: &Path) -> Option<u64> {
314 let meta = std::fs::read(dir.join("metadata.bin")).ok()?;
315 if meta.len() < 40 {
316 return None;
317 }
318 let u64_at = |at: usize| {
319 u64::from_le_bytes([
320 meta[at], meta[at + 1], meta[at + 2], meta[at + 3],
321 meta[at + 4], meta[at + 5], meta[at + 6], meta[at + 7],
322 ])
323 };
324 let node_count = u64_at(8);
325 let edge_count = u64_at(16);
326 let nodes = (node_count.saturating_add(1)).saturating_mul(12);
327 let edges = std::fs::metadata(dir.join("edges.bin")).map(|m| m.len()).unwrap_or(edge_count.saturating_mul(7));
328 let inter = std::fs::metadata(dir.join("intermediate.bin")).map(|m| m.len()).unwrap_or(0);
329 let lanes = std::fs::metadata(dir.join("lanes.bin")).map(|m| m.len()).unwrap_or(0);
330 let in_edges = (node_count.saturating_add(1)).saturating_mul(4).saturating_add(edge_count.saturating_mul(4));
331 Some(nodes.saturating_add(edges).saturating_add(inter).saturating_add(lanes).saturating_add(in_edges))
332}
333/// What pass 1 hands the later phases: relations stay resident, corridors
334/// collapse to (way id, zoom) overrides, and the ways spill stages on whichever backend the
335/// budget gate chose, shared by refcount with every later reader (`Some`) or read back from
336/// the file at `ways_path` (`None`).
337struct Pass1Out {
338 relations: Vec<Relation>,
339 promoted: Vec<(i64, u8)>,
340 blob_kinds: Vec<u8>,
341 /// Classified way count (one materialised feature each, at most). Distinct from
342 /// `way_refs` below: the ref total is ~10x the way count and must not size a feature
343 /// estimate.
344 ways: u64,
345 /// Node ref total, duplicates included -- a capacity for the collector, NOT a feature
346 /// count. Planet's ~12 G refs must never be multiplied by bytes-per-feature.
347 way_refs: u64,
348 way_max_ref: i64,
349 /// The sealed ways spill, shared by refcount with every later reader; `None` on the file
350 /// plan, where readers open `ways_path` instead.
351 ways_anon: Option<std::sync::Arc<tile_build::anon::AnonStore>>,
352 /// `admin_centre`/`label` node member -> its boundary relation id, both raw OSM ids, for every
353 /// relation that carries a region shape. The authoritative half of the place->boundary link:
354 /// OSM points a boundary relation at its own label node directly, so no geometry test is needed.
355 /// `label` wins over `admin_centre` when a relation lists both, since `label` is the place node
356 /// the map actually renders.
357 region_label_nodes: HashMap<i64, i64>,
358 /// The needed-node bitset, collected during the drain above: every
359 /// classified way's refs plus (set by the caller) the member ways' refs.
360 /// Pass 3 resolves exactly these ids, without re-reading the ways spill.
361 needed: NeededBits,
362}
363
364/// Pass 1 (ways + relations) plus the corridor promotion. Moved whole from
365/// `extract` so part files can cut at fn boundaries; behavior identical.
366///
367/// `blob_kinds_in` is an optional pre-computed mask (the graph sidecar) that lets this pass skip
368/// node blobs; `None` means scan the whole file. Either way the mask it returns is complete.
369///
370/// `spill_plan` is the budget gate's backend choice: the ways spill stages anonymously or through
371/// the `.tmp` at `ways_path`. Decided by the caller from pass-0 counts, not here, because this
372/// pass cannot know the graph size that shares its peak.
373#[allow(clippy::too_many_arguments)]
374fn run_pass1(
375 input: &Path,
376 blobs: &[pbf::BlobLoc],
377 blob_kinds_in: Option<&[u8]>,
378 select: &Select,
379 layers: Layers,
380 ways_path: &Path,
381 spill_plan: osm_ingest::mem::SpillPlan,
382 stats: &mut Stats,
383 timer: &mut crate::timing::PhaseTimer,
384) -> Result<Pass1Out> {
385 // --- pass 1: ways and relations -------------------------------------------------------
386 //
387 // `run_pass_sink` rather than `run_pass`, because `run_pass`'s contract is to hand back every
388 // chunk at once and these chunks hold the node refs of every classified way — the 2.7 GB this
389 // spill exists to be rid of. Here a chunk is appended to the file and freed while its
390 // neighbours are still decoding.
391 //
392 // `blob_kinds` comes back from this pass and lets the later ones skip whole blobs, which on a
393 // planet extract is most of the file.
394 let mut ways = WaySink::create_planned(&ways_path, spill_plan)?;
395 let mut relations: Vec<Relation> = Vec::new();
396 // The needed-node bitset, fused into this pass: every classified way sets
397 // its refs here in the drain below, so pass 3 never re-reads the ways
398 // spill to collect them. Grows on demand (the maximum is not known until
399 // the last push); member refs join after the drain.
400 let mut needed = NeededBits::new_growable();
401 // `admin_centre`/`label` node member -> boundary relation id (raw), gathered as region shapes
402 // are classified below. See [`Pass1Out::region_label_nodes`].
403 let mut region_label_nodes: HashMap<i64, i64> = HashMap::new();
404 // Road ways carrying a `ref`, for the corridor pass below. A small minority of ways,
405 // and the only thing pass 1 keeps in memory besides the relations.
406 let mut corridors: Vec<crate::corridor::Segment> = Vec::new();
407 let blob_kinds = pbf::run_pass_sink(
408 input,
409 &blobs,
410 blob_kinds_in,
411 KIND_WAYS | KIND_RELATIONS,
412 "Pass 1: ways and relations",
413 || {
414 (
415 Vec::<(i64, Way)>::new(),
416 Vec::<Relation>::new(),
417 Vec::<crate::corridor::Segment>::new(),
418 Vec::<(i64, i64)>::new(),
419 )
420 },
421 |state, block| {
422 let mut kinds = 0u8;
423 visit_block(block, KIND_WAYS | KIND_RELATIONS, &mut kinds, &mut |el| {
424 match el {
425 Element::Way(way) => {
426 if !select.matches(|k| way.tags.get_str(k)) {
427 return Ok(());
428 }
429 if let Some(class) = schema::classify(&way.tags, true, layers) {
430 // A numbered road's `min_zoom` is decided per corridor, not per
431 // way, so that a route does not vanish where its class changes.
432 // Slip roads are left out: they carry the parent's `ref` and
433 // would be promoted into junction stubs at world zoom.
434 if class.layer == tilecodec::mamaps::dict::LAYER_ROADS
435 && class.flags & tilecodec::mamaps::body::FLAG_IS_LINK == 0
436 && way.refs.len() >= 2
437 {
438 if let Some(route) = crate::corridor::route_key(&way.tags) {
439 state.2.push(crate::corridor::Segment {
440 way_id: way.id,
441 route,
442 first_node: way.refs[0],
443 last_node: way.refs[way.refs.len() - 1],
444 min_zoom: class.min_zoom,
445 });
446 }
447 }
448 let name = schema::display_name(&way.tags, class.layer);
449 // A road's carriageway lane count, per-lane turn masks and directional
450 // split, baked so the renderer can draw the lanes individually, place
451 // turn arrows and put the centre line where the traffic divides. Zero,
452 // empty and default for every other layer.
453 let is_road =
454 class.layer == tilecodec::mamaps::dict::LAYER_ROADS;
455 let lane_count = if is_road {
456 schema::roads::lane_count(&way.tags)
457 } else {
458 0
459 };
460 let (turn_fwd, turn_bwd) = if is_road {
461 schema::roads::turn_masks(&way.tags)
462 } else {
463 (Vec::new(), Vec::new())
464 };
465 let carriageway = if is_road {
466 schema::roads::carriageway(&way.tags)
467 } else {
468 Carriageway::default()
469 };
470 // A building's S3DB attributes, parsed once here beside its class.
471 // Zero-cost for the overwhelming majority of ways, which are not
472 // buildings.
473 let building = if class.layer == LAYER_BUILDINGS {
474 Some(schema::buildings::attrs(&way.tags))
475 } else {
476 None
477 };
478 state.0.push((
479 way.id,
480 Way {
481 class,
482 refs: way.refs.to_vec(),
483 name,
484 lane_count,
485 turn_fwd,
486 turn_bwd,
487 carriageway,
488 building,
489 },
490 ));
491 }
492 }
493 Element::Relation(relation) => {
494 // Two relation types carry a shape. Anything else — a site, a
495 // public_transport — does not.
496 if !matches!(
497 relation.tags.get_str("type"),
498 Some("multipolygon" | "boundary")
499 ) {
500 return Ok(());
501 }
502 if !select.matches(|k| relation.tags.get_str(k)) {
503 return Ok(());
504 }
505 if let Some(class) = schema::classify(&relation.tags, false, layers) {
506 let members: Vec<_> = relation
507 .members
508 .iter()
509 .filter(|m| m.kind == MEMBER_WAY)
510 .map(|m| (m.id, m.role == b"inner"))
511 .collect();
512 // **The schema decides**, not the relation's `type` tag. Both an
513 // administrative border and a protected area are `type=boundary`, and
514 // one is a line while the other is a shape — which is exactly the
515 // distinction `Class::area` exists to make.
516 let area = class.area;
517 let name = schema::display_name(&relation.tags, class.layer);
518 // A multipolygon building (a footprint with a courtyard) carries S3DB
519 // attributes just as a building way does.
520 let building = if class.layer == LAYER_BUILDINGS {
521 Some(schema::buildings::attrs(&relation.tags))
522 } else {
523 None
524 };
525 // A country's code, kept so the region shape below can stamp its
526 // driving side and centre-line colour onto the tiles it covers.
527 let iso = schema::boundaries::country_code(&relation.tags)
528 .map(str::to_string);
529 // An administrative relation yields *two* features: the border, which
530 // is a line and is what the basemap draws, and the region's shape,
531 // which nothing draws and the region mask reads. They cannot be one
532 // feature — a clipped polygon grows tile-edge segments and the border
533 // layer strokes them into a grid. See `schema::boundaries`.
534 if let Some(shape) =
535 schema::boundaries::region_area(&relation.tags, false)
536 {
537 // The boundary points at its own label/centre node directly: record
538 // that node -> this relation so the place label it becomes can carry
539 // the id. `label` overwrites `admin_centre` (the label node is the
540 // one that renders; admin_centre is the capital, a different node).
541 for m in relation.members.iter() {
542 if m.kind == MEMBER_NODE && m.role == b"admin_centre" {
543 state.3.push((m.id, relation.id));
544 }
545 }
546 for m in relation.members.iter() {
547 if m.kind == MEMBER_NODE && m.role == b"label" {
548 state.3.push((m.id, relation.id));
549 }
550 }
551 state.1.push(Relation {
552 class: shape,
553 members: members.clone(),
554 area: true,
555 name: name.clone(),
556 id: relation.id,
557 building: None,
558 population: None,
559 iso: iso.clone(),
560 });
561 }
562 state.1.push(Relation {
563 class,
564 members,
565 area,
566 name,
567 id: relation.id,
568 building,
569 population: Some(schema::places::population_of(&relation.tags)),
570 iso: None,
571 });
572 }
573 }
574 Element::Node(_) => {}
575 }
576 Ok(())
577 })?;
578 Ok(kinds)
579 },
580 |(chunk_ways, chunk_relations, chunk_corridors, chunk_label_nodes)| {
581 // Chunks arrive in file order and a PBF's ways are sorted by id, so appending here
582 // leaves the file in ascending id order. `WaySink::push` refuses an id that does not
583 // advance rather than letting an unsorted file reorder the archive silently.
584 for (id, way) in chunk_ways {
585 // Fused ref collection: the refs are decoded and in hand here,
586 // so the bitset takes them now instead of a later pass
587 // re-reading the spill to find them again.
588 for &node in &way.refs {
589 needed.set_growable(node)?;
590 }
591 ways.push(
592 id,
593 &way.class,
594 &way.refs,
595 way.name.as_deref(),
596 way.lane_count,
597 &way.turn_fwd,
598 &way.turn_bwd,
599 way.carriageway,
600 way.building,
601 )?;
602 }
603 relations.extend(chunk_relations);
604 corridors.extend(chunk_corridors);
605 // `label` was pushed after `admin_centre`, so inserting in order lets the label win.
606 for (node_id, rel_id) in chunk_label_nodes {
607 region_label_nodes.insert(node_id, rel_id);
608 }
609 Ok(())
610 },
611 )?;
612 let (counts, store) = ways.finish_either()?;
613 stats.ways_classified = counts.ways;
614 let (ways, way_refs, way_max_ref, ways_anon) =
615 (counts.ways, counts.refs, counts.max_ref, store.map(std::sync::Arc::new));
616 stats.relations_classified = relations.len() as u64;
617
618 // A numbered road changes class along its length, so deciding `min_zoom` per way chops
619 // a corridor into stubs at the zooms where only its motorway parts survive. Promote
620 // each connected same-`ref` run to the shallowest zoom any of its ways asks for, then
621 // drop the segments: only the (way id, zoom) overrides are needed from here.
622 timer.switch("corridors");
623 let promoted = crate::corridor::promote(&corridors);
624 stats.corridor_promotions = promoted.len() as u64;
625 drop(corridors);
626
627 Ok(Pass1Out {
628 relations,
629 promoted,
630 blob_kinds,
631 ways,
632 way_refs,
633 way_max_ref,
634 ways_anon,
635 region_label_nodes,
636 needed,
637 })
638}