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

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

extract_part1_s1.rs292 lines · 15.3 KiBRaw
1/// Pass 1 (ways + relations) plus the corridor promotion. Moved whole from
2/// `extract` so part files can cut at fn boundaries; behavior identical.
3///
4/// `blob_kinds_in` is an optional pre-computed mask (the graph sidecar) that lets this pass skip
5/// node blobs; `None` means scan the whole file. Either way the mask it returns is complete.
6///
7/// `spill_plan` is the budget gate's backend choice: the ways spill stages anonymously or through
8/// the `.tmp` at `ways_path`. Decided by the caller from pass-0 counts, not here, because this
9/// pass cannot know the graph size that shares its peak.
10#[allow(clippy::too_many_arguments)]
11fn run_pass1(
12 input: &Path,
13 blobs: &[pbf::BlobLoc],
14 blob_kinds_in: Option<&[u8]>,
15 select: &Select,
16 layers: Layers,
17 ways_path: &Path,
18 spill_plan: osm_ingest::mem::SpillPlan,
19 stats: &mut Stats,
20 timer: &mut crate::timing::PhaseTimer,
21) -> Result<Pass1Out> {
22 // --- pass 1: ways and relations -------------------------------------------------------
23 //
24 // `run_pass_sink` rather than `run_pass`, because `run_pass`'s contract is to hand back every
25 // chunk at once and these chunks hold the node refs of every classified way — the 2.7 GB this
26 // spill exists to be rid of. Here a chunk is appended to the file and freed while its
27 // neighbours are still decoding.
28 //
29 // `blob_kinds` comes back from this pass and lets the later ones skip whole blobs, which on a
30 // planet extract is most of the file.
31 let mut ways = WaySink::create_planned(ways_path, spill_plan)?;
32 let mut relations: Vec<Relation> = Vec::new();
33 // The needed-node bitset, fused into this pass: every classified way sets
34 // its refs here in the drain below, so pass 3 never re-reads the ways
35 // spill to collect them. Grows on demand (the maximum is not known until
36 // the last push); member refs join after the drain.
37 let mut needed = NeededBits::new_growable();
38 // `admin_centre`/`label` node member -> boundary relation id (raw), gathered as region shapes
39 // are classified below. See [`Pass1Out::region_label_nodes`].
40 let mut region_label_nodes: HashMap<i64, i64> = HashMap::new();
41 // Road ways carrying a `ref`, for the corridor pass below. A small minority of ways,
42 // and the only thing pass 1 keeps in memory besides the relations.
43 let mut corridors: Vec<crate::corridor::Segment> = Vec::new();
44 let blob_kinds = pbf::run_pass_sink(
45 input,
46 blobs,
47 pbf::PassSpec {
48 blob_kinds: blob_kinds_in,
49 want: KIND_WAYS | KIND_RELATIONS,
50 label: "Pass 1: ways and relations",
51 },
52 || {
53 (
54 Vec::<WayBlock>::new(),
55 Vec::<Relation>::new(),
56 Vec::<crate::corridor::Segment>::new(),
57 Vec::<(i64, i64)>::new(),
58 Vec::<i64>::new(),
59 )
60 },
61 |state, block| {
62 let mut kinds = 0u8;
63 // This block's refs land past here; sorted and deduped below, so the drain sets
64 // the needed bitset in ascending runs instead of chasing every ref.
65 let refs_from = state.4.len();
66 visit_block(block, KIND_WAYS | KIND_RELATIONS, &mut kinds, &mut |el| {
67 match el {
68 Element::Way(way) => {
69 if !select.matches(|k| way.tags.get_str(k)) {
70 return Ok(());
71 }
72 if let Some(class) = schema::classify(&way.tags, true, layers) {
73 // A numbered road's `min_zoom` is decided per corridor, not per
74 // way, so that a route does not vanish where its class changes.
75 // Slip roads are left out: they carry the parent's `ref` and
76 // would be promoted into junction stubs at world zoom.
77 if class.layer == tilecodec::mamaps::dict::LAYER_ROADS
78 && class.flags & tilecodec::mamaps::body::FLAG_IS_LINK == 0
79 && way.refs.len() >= 2
80 {
81 if let Some(route) = crate::corridor::route_key(&way.tags) {
82 state.2.push(crate::corridor::Segment {
83 way_id: way.id,
84 route,
85 first_node: way.refs[0],
86 last_node: way.refs[way.refs.len() - 1],
87 min_zoom: class.min_zoom,
88 });
89 }
90 }
91 let name = schema::display_name(&way.tags, class.layer);
92 // A road's carriageway lane count, per-lane turn masks and directional
93 // split, baked so the renderer can draw the lanes individually, place
94 // turn arrows and put the centre line where the traffic divides. Zero,
95 // empty and default for every other layer.
96 let is_road =
97 class.layer == tilecodec::mamaps::dict::LAYER_ROADS;
98 let lane_count = if is_road {
99 schema::roads::lane_count(&way.tags)
100 } else {
101 0
102 };
103 let (turn_fwd, turn_bwd) = if is_road {
104 schema::roads::turn_masks(&way.tags)
105 } else {
106 (Vec::new(), Vec::new())
107 };
108 let carriageway = if is_road {
109 schema::roads::carriageway(&way.tags)
110 } else {
111 Carriageway::default()
112 };
113 // A building's S3DB attributes, parsed once here beside its class.
114 // Zero-cost for the overwhelming majority of ways, which are not
115 // buildings.
116 let building = if class.layer == LAYER_BUILDINGS {
117 Some(schema::buildings::attrs(&way.tags))
118 } else {
119 None
120 };
121 // Encoded HERE, on the worker, into the chunk's ways-spill blocks: the
122 // drain only patches each block's first id and appends it. This was
123 // the serial drain's record-by-record encode, which held pass 1 to ~4
124 // of 192 cores on the planet (4m40s). Same bytes; see `WayBlock`.
125 if state.0.last().is_none_or(|b| b.len() >= WAY_BLOCK_WAYS) {
126 state.0.push(WayBlock::new());
127 }
128 let refs: &[i64] = way.refs;
129 state.0.last_mut().expect("pushed above").push(
130 way.id,
131 &class,
132 refs,
133 name.as_deref(),
134 lane_count,
135 &turn_fwd,
136 &turn_bwd,
137 carriageway,
138 building,
139 )?;
140 state.4.extend_from_slice(refs);
141 }
142 }
143 Element::Relation(relation) => {
144 // Two relation types carry a shape. Anything else — a site, a
145 // public_transport — does not.
146 if !matches!(
147 relation.tags.get_str("type"),
148 Some("multipolygon" | "boundary")
149 ) {
150 return Ok(());
151 }
152 if !select.matches(|k| relation.tags.get_str(k)) {
153 return Ok(());
154 }
155 if let Some(class) = schema::classify(&relation.tags, false, layers) {
156 let members: Vec<_> = relation
157 .members
158 .iter()
159 .filter(|m| m.kind == MEMBER_WAY)
160 .map(|m| (m.id, m.role == b"inner"))
161 .collect();
162 // **The schema decides**, not the relation's `type` tag. Both an
163 // administrative border and a protected area are `type=boundary`, and
164 // one is a line while the other is a shape — which is exactly the
165 // distinction `Class::area` exists to make.
166 let area = class.area;
167 let name = schema::display_name(&relation.tags, class.layer);
168 // A multipolygon building (a footprint with a courtyard) carries S3DB
169 // attributes just as a building way does.
170 let building = if class.layer == LAYER_BUILDINGS {
171 Some(schema::buildings::attrs(&relation.tags))
172 } else {
173 None
174 };
175 // A country's code, kept so the region shape below can stamp its
176 // driving side and centre-line colour onto the tiles it covers.
177 let iso = schema::boundaries::country_code(&relation.tags)
178 .map(str::to_string);
179 // An administrative relation yields *two* features: the border, which
180 // is a line and is what the basemap draws, and the region's shape,
181 // which nothing draws and the region mask reads. They cannot be one
182 // feature — a clipped polygon grows tile-edge segments and the border
183 // layer strokes them into a grid. See `schema::boundaries`.
184 if let Some(shape) =
185 schema::boundaries::region_area(&relation.tags, false)
186 {
187 // The boundary points at its own label/centre node directly: record
188 // that node -> this relation so the place label it becomes can carry
189 // the id. `label` overwrites `admin_centre` (the label node is the
190 // one that renders; admin_centre is the capital, a different node).
191 for m in relation.members.iter() {
192 if m.kind == MEMBER_NODE && m.role == b"admin_centre" {
193 state.3.push((m.id, relation.id));
194 }
195 }
196 for m in relation.members.iter() {
197 if m.kind == MEMBER_NODE && m.role == b"label" {
198 state.3.push((m.id, relation.id));
199 }
200 }
201 state.1.push(Relation {
202 class: shape,
203 members: members.clone(),
204 area: true,
205 name: name.clone(),
206 id: relation.id,
207 building: None,
208 population: None,
209 iso: iso.clone(),
210 });
211 }
212 state.1.push(Relation {
213 class,
214 members,
215 area,
216 name,
217 id: relation.id,
218 building,
219 population: Some(schema::places::population_of(&relation.tags)),
220 iso: None,
221 });
222 }
223 }
224 Element::Node(_) => {}
225 }
226 Ok(())
227 })?;
228 sort_dedup_tail(&mut state.4, refs_from);
229 Ok(kinds)
230 },
231 |(chunk_ways, chunk_relations, chunk_corridors, chunk_label_nodes, chunk_refs)| {
232 // Chunks arrive in file order and a PBF's ways are sorted by id, so appending here
233 // leaves the file in ascending id order. `WaySink::push_block` refuses an id that does
234 // not advance rather than letting an unsorted file reorder the archive silently.
235 for block in &chunk_ways {
236 ways.push_block(block)?;
237 }
238 // Fused ref collection: the refs were decoded on the worker, so the bitset takes
239 // them now instead of a later pass re-reading the spill to find them again. A bitset
240 // is order- and duplicate-blind, so the per-block sort/dedup changes no bit.
241 for &node in &chunk_refs {
242 needed.set_growable(node)?;
243 }
244 relations.extend(chunk_relations);
245 corridors.extend(chunk_corridors);
246 // `label` was pushed after `admin_centre`, so inserting in order lets the label win.
247 for (node_id, rel_id) in chunk_label_nodes {
248 region_label_nodes.insert(node_id, rel_id);
249 }
250 Ok(())
251 },
252 )?;
253 let (counts, store) = ways.finish_either()?;
254 stats.ways_classified = counts.ways;
255 let (ways, way_refs, way_max_ref, ways_anon, way_blocks) =
256 (counts.ways, counts.refs, counts.max_ref, store.map(std::sync::Arc::new), counts.blocks);
257 stats.relations_classified = relations.len() as u64;
258
259 // A numbered road changes class along its length, so deciding `min_zoom` per way chops
260 // a corridor into stubs at the zooms where only its motorway parts survive. Promote
261 // each connected same-`ref` run to the shallowest zoom any of its ways asks for, then
262 // drop the segments: only the (way id, zoom) overrides are needed from here.
263 timer.switch("corridors");
264 let promoted = crate::corridor::promote(&corridors);
265 stats.corridor_promotions = promoted.len() as u64;
266 drop(corridors);
267
268 Ok(Pass1Out {
269 relations,
270 promoted,
271 blob_kinds,
272 ways,
273 way_refs,
274 way_max_ref,
275 ways_anon,
276 way_blocks,
277 region_label_nodes,
278 needed,
279 })
280}
281/// Sort and dedup `v[from..]` in place, leaving `v[..from]` untouched.
282fn sort_dedup_tail(v: &mut Vec<i64>, from: usize) {
283 v[from..].sort_unstable();
284 let mut write = from;
285 for read in from..v.len() {
286 if write == from || v[read] != v[write - 1] {
287 v[write] = v[read];
288 write += 1;
289 }
290 }
291 v.truncate(write);
292}