Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_part3.rs
extract_part3.rs432 lines · 19.1 KiBRaw
| 1 | /// What one relation contributes, decided on the pool. See [`BuiltRelation`]. |
| 2 | enum RelationOutcome { |
| 3 | /// Region-filtered (a `poi` label outside the bbox, a building outside it): counts nothing. |
| 4 | Skip, |
| 5 | /// No geometry: counts `geometry_failed`. |
| 6 | Failed, |
| 7 | /// A finished spill record: counts a feature. |
| 8 | Kept(PreRecord), |
| 9 | } |
| 10 | |
| 11 | /// One relation's geometry and spill record, built off the shared tables with nothing mutable |
| 12 | /// touched, so relations fan out across the pool exactly as [`materialise_ways`]' blocks do. The |
| 13 | /// sink and the conventions grid are fed from these **in relation order** by the serial drain, |
| 14 | /// which is what keeps the archive byte-identical: the drain order is the spill order is the |
| 15 | /// archive's. |
| 16 | /// |
| 17 | /// The record itself ([`PreRecord`]) is built here too -- props, header, geometry bytes -- so the |
| 18 | /// drain only appends; it used to encode every relation (and DEFLATE its frames) on the one |
| 19 | /// serial thread, between pool batches of 4096 that each waited on their slowest relation. On |
| 20 | /// the planet that phase ran 4 minutes at ~8 cores. |
| 21 | struct BuiltRelation { |
| 22 | /// An area relation's ring stats, summed into [`Stats::rings`] whether or not the stitch |
| 23 | /// produced anything -- four additive counts, so the order cannot show. |
| 24 | rings: Option<RingStats>, |
| 25 | outcome: Result<RelationOutcome>, |
| 26 | /// A kept country shape's assembled rings, for `conventions.add` -- which has precedence rules |
| 27 | /// (an interior claim outranks a border one) and so stays serial and in relation order. |
| 28 | conventions: Option<Vec<rings::Polygon>>, |
| 29 | } |
| 30 | |
| 31 | /// Build one relation's geometry and record. Reads only the shared `members` map and the |
| 32 | /// resolved `table`, both immutable, so it is safe to call across the pool. The decisions -- |
| 33 | /// label point or member lines or stitched rings, region keep/drop, record shape -- are the ones |
| 34 | /// the serial drain used to make, in the same order. |
| 35 | fn build_relation( |
| 36 | relation: &Relation, |
| 37 | members: &MemberWays, |
| 38 | table: &NodeLocations, |
| 39 | region: Option<&osm_ingest::bbox::BBox>, |
| 40 | ) -> BuiltRelation { |
| 41 | // A `places` relation (a country, a region) is labelled at its centroid: one point, not a |
| 42 | // stitched shape. The border itself lives in `boundaries`; this is the name. |
| 43 | if is_label(relation.class.layer) { |
| 44 | let line: Vec<(f64, f64)> = relation |
| 45 | .members |
| 46 | .iter() |
| 47 | .filter_map(|(id, _)| members.get(*id)) |
| 48 | .flat_map(|refs| table.line(refs)) |
| 49 | .collect(); |
| 50 | let outcome = match centroid(&line) { |
| 51 | None => Ok(RelationOutcome::Failed), |
| 52 | // `poi` labels are region-filtered; `places` always kept. O(1) point test. |
| 53 | Some(point) |
| 54 | if relation.class.layer == tilecodec::mamaps::dict::LAYER_POI |
| 55 | && !point_touches(&point, region) => |
| 56 | { |
| 57 | Ok(RelationOutcome::Skip) |
| 58 | } |
| 59 | Some(point) => crate::store::EncodedGeom::live(&Geometry::Points(vec![point])) |
| 60 | .and_then(|encoded| { |
| 61 | PreRecord::named( |
| 62 | &relation.class, |
| 63 | &encoded, |
| 64 | relation.name.as_deref(), |
| 65 | tagged_id(relation.id, ELEMENT_RELATION), |
| 66 | ) |
| 67 | }) |
| 68 | .map(RelationOutcome::Kept), |
| 69 | }; |
| 70 | return BuiltRelation { rings: None, outcome, conventions: None }; |
| 71 | } |
| 72 | // A boundary relation's members are the border. Each is emitted as its own line rather than |
| 73 | // stitched: the renderer strokes them, and a gap between two member ways is invisible in a |
| 74 | // stroke while a failed stitch would drop the whole border. |
| 75 | if !relation.area { |
| 76 | let lines: Vec<Vec<(f64, f64)>> = relation |
| 77 | .members |
| 78 | .iter() |
| 79 | .filter_map(|(id, _)| members.get(*id)) |
| 80 | .map(|refs| table.line(refs)) |
| 81 | .filter(|line| line.len() >= 2) |
| 82 | .collect(); |
| 83 | // `empty` is the pre-encode shape test: an encoded empty still carries count bytes, and |
| 84 | // an empty border counts `geometry_failed` rather than pushing an empty record. |
| 85 | let empty = lines.is_empty(); |
| 86 | let outcome = crate::store::EncodedGeom::live(&Geometry::Lines(lines)).and_then(|encoded| { |
| 87 | if empty { |
| 88 | Ok(RelationOutcome::Failed) |
| 89 | } else { |
| 90 | PreRecord::named(&relation.class, &encoded, None, tilecodec::mamaps::body::ID_NONE) |
| 91 | .map(RelationOutcome::Kept) |
| 92 | } |
| 93 | }); |
| 94 | return BuiltRelation { rings: None, outcome, conventions: None }; |
| 95 | } |
| 96 | let member_ways: Vec<MemberWay> = relation |
| 97 | .members |
| 98 | .iter() |
| 99 | .filter_map(|(id, inner)| { |
| 100 | Some(MemberWay { refs: members.get(*id)?.clone(), outer: !inner }) |
| 101 | }) |
| 102 | .collect(); |
| 103 | let mut ring_stats = RingStats::default(); |
| 104 | let polygons = rings::assemble(&member_ways, |id| locate(table, id), &mut ring_stats); |
| 105 | // Buildings are region-filtered; every other area layer is always kept. |
| 106 | let keep = relation.class.layer != tilecodec::mamaps::dict::LAYER_BUILDINGS |
| 107 | || polygons_touch(&polygons, region); |
| 108 | let empty = polygons.is_empty(); |
| 109 | let geometry = Geometry::Polygons(polygons); |
| 110 | let encoded = crate::store::EncodedGeom::live(&geometry); |
| 111 | let Geometry::Polygons(polygons) = geometry else { |
| 112 | unreachable!("just built as Polygons"); |
| 113 | }; |
| 114 | let mut conventions = None; |
| 115 | let outcome = encoded.and_then(|encoded| { |
| 116 | if empty { |
| 117 | return Ok(RelationOutcome::Failed); |
| 118 | } |
| 119 | if !keep { |
| 120 | return Ok(RelationOutcome::Skip); |
| 121 | } |
| 122 | // A multipolygon building carries its S3DB attributes into the building side table, just |
| 123 | // as a building way does. |
| 124 | if let Some(building) = relation.building { |
| 125 | return PreRecord::building(&relation.class, &encoded, None, building).map(RelationOutcome::Kept); |
| 126 | } |
| 127 | // The id is what lets the mask gather a region's tile-clipped pieces back together. |
| 128 | let id = if tracks_ids(&relation.class) { |
| 129 | tagged_id(relation.id, ELEMENT_RELATION) |
| 130 | } else { |
| 131 | tilecodec::mamaps::body::ID_NONE |
| 132 | }; |
| 133 | let record = PreRecord::named(&relation.class, &encoded, None, id)?; |
| 134 | // The country's own shape is also what says how its roads are marked: stamped by the |
| 135 | // drain, from these assembled rings, so the grid and the border line agree. |
| 136 | if relation.iso.is_some() { |
| 137 | conventions = Some(polygons); |
| 138 | } |
| 139 | Ok(RelationOutcome::Kept(record)) |
| 140 | }); |
| 141 | BuiltRelation { rings: Some(ring_stats), outcome, conventions } |
| 142 | } |
| 143 | |
| 144 | /// Relations per pool hand-off in [`materialise_relations`]. Large, because one country-sized |
| 145 | /// multipolygon can take seconds to stitch and a group's drain waits for its slowest relation; |
| 146 | /// with the next group computing while this one drains, that wait is mostly hidden. |
| 147 | const RELATIONS_PER_GROUP: usize = 32 * 1024; |
| 148 | |
| 149 | /// Materialise relations; returns the driving-side conventions. |
| 150 | /// |
| 151 | /// `region` filters the built layers (`roads`, `poi`, `buildings`) the same |
| 152 | /// way [`materialise_ways`] does. `boundaries` region shapes are always kept |
| 153 | /// — the driving-side grid must cover the world even in a region build, or |
| 154 | /// the tiler mis-marks roads at the region's edge. |
| 155 | fn materialise_relations( |
| 156 | relations: &[Relation], |
| 157 | members: &MemberWays, |
| 158 | table: &NodeLocations, |
| 159 | region: Option<&osm_ingest::bbox::BBox>, |
| 160 | sink: &mut Sink, |
| 161 | stats: &mut Stats, |
| 162 | ) -> Result<schema::boundaries::Conventions> { |
| 163 | let mut bar = Progress::new( |
| 164 | "Materialise: relations".to_string(), |
| 165 | relations.len(), |
| 166 | "relation(s)", |
| 167 | true, |
| 168 | ); |
| 169 | // Which driving side and centre-line colour applies where, accumulated as the country shapes |
| 170 | // go past. |
| 171 | let mut conventions = schema::boundaries::Conventions::default(); |
| 172 | pipeline_ordered( |
| 173 | relations.len(), |
| 174 | RELATIONS_PER_GROUP, |
| 175 | |i| build_relation(&relations[i], members, table, region), |
| 176 | |i, built| { |
| 177 | if let Some(r) = built.rings { |
| 178 | stats.rings.outer_rings += r.outer_rings; |
| 179 | stats.rings.inner_rings += r.inner_rings; |
| 180 | stats.rings.unclosed += r.unclosed; |
| 181 | stats.rings.orphan_inner += r.orphan_inner; |
| 182 | } |
| 183 | // `?` in spill order: the first failure in relation order, exactly as inline encoding |
| 184 | // would report it. |
| 185 | match built.outcome? { |
| 186 | RelationOutcome::Skip => {} |
| 187 | RelationOutcome::Failed => stats.geometry_failed += 1, |
| 188 | RelationOutcome::Kept(record) => { |
| 189 | if let (Some(polygons), Some(iso)) = (&built.conventions, &relations[i].iso) { |
| 190 | conventions.add(iso, polygons); |
| 191 | } |
| 192 | sink.push_pre(&record)?; |
| 193 | stats.features += 1; |
| 194 | } |
| 195 | } |
| 196 | bar.tick("relation(s)"); |
| 197 | Ok(()) |
| 198 | }, |
| 199 | )?; |
| 200 | bar.finish("relation(s)"); |
| 201 | |
| 202 | Ok(conventions) |
| 203 | } |
| 204 | |
| 205 | /// Coastline, transit, graph, then finish the store. Moved whole from `extract`. |
| 206 | /// Inputs for [`append_external_and_finish`], grouped so the one call site names them. |
| 207 | struct ExternalFinish<'a> { |
| 208 | coastline: &'a Path, |
| 209 | transit_routes: &'a Path, |
| 210 | graph: &'a crate::GraphGate, |
| 211 | sink: Sink, |
| 212 | stats: &'a mut Stats, |
| 213 | conventions: schema::boundaries::Conventions, |
| 214 | spill_path: &'a Path, |
| 215 | timer: &'a mut crate::timing::PhaseTimer, |
| 216 | } |
| 217 | |
| 218 | fn append_external_and_finish(args: ExternalFinish<'_>) -> Result<Store> { |
| 219 | let ExternalFinish { coastline, transit_routes, graph, mut sink, stats, conventions, spill_path, timer } = args; |
| 220 | // The mainland, last, because clipping it needs the extract's own bounding box and that is |
| 221 | // only known once every OSM feature has been through the sink. Order in the file does not |
| 222 | // matter: the tiler groups by layer id, so `earth` is the first layer of every body whenever it |
| 223 | // was written. |
| 224 | match sink.bbox_degrees() { |
| 225 | Some(bbox) => { |
| 226 | println!( |
| 227 | "reading land polygons within {:.3},{:.3} .. {:.3},{:.3}", |
| 228 | bbox.0, bbox.1, bbox.2, bbox.3, |
| 229 | ); |
| 230 | stats.land_polygons = schema::landtype::stream_prepared(coastline, bbox, &mut sink)?; |
| 231 | stats.features += stats.land_polygons; |
| 232 | } |
| 233 | // Nothing to clip against. Land alone would be an archive of one layer, and the caller |
| 234 | // almost certainly pointed at the wrong extract. |
| 235 | None => return err("the extract produced no features to place land against".to_string()), |
| 236 | } |
| 237 | // The `transit` layer, for the same reason and against the same bounding box: its geometry is |
| 238 | // GTFS rather than OSM (see [`schema::transit`]), so it is read here rather than classified in |
| 239 | // any of the passes above. |
| 240 | timer.switch("transit-routes"); |
| 241 | match sink.bbox_degrees() { |
| 242 | Some(bbox) => { |
| 243 | println!( |
| 244 | "reading transit routes within {:.3},{:.3} .. {:.3},{:.3}", |
| 245 | bbox.0, bbox.1, bbox.2, bbox.3, |
| 246 | ); |
| 247 | stats.transit_routes = schema::transit::stream_routes(transit_routes, bbox, &mut sink)?; |
| 248 | stats.features += stats.transit_routes; |
| 249 | } |
| 250 | None => { |
| 251 | return err("the extract produced no features to place transit routes against" |
| 252 | .to_string()) |
| 253 | } |
| 254 | } |
| 255 | // The `traffic` layer is dropped as of the NA diet: its 12.37GB (360M |
| 256 | // per-segment features, 5x the roads layer) cost more than the overlay earns, |
| 257 | // and the live-traffic display path needs a server contract change before a |
| 258 | // cheaper per-edge form can replace it. The layer stays in the format |
| 259 | // (layer_count 12, dict entry kept) so readers need no change — with zero |
| 260 | // features no body carries it and it costs nothing. `junction` below still |
| 261 | // reads the same graph, which is why the graph build and its validation stay. |
| 262 | // (Formerly: `stats.traffic_segments = schema::traffic::stream_graph(...)`.) |
| 263 | // The `junction` layer rides the graph: a lane connector is built from the junction |
| 264 | // node's own incident edges, so there is nothing to read that the traffic pass did not |
| 265 | // already need. `conventions` decides which side of a road the direction of travel sits |
| 266 | // on, and is borrowed here because it is moved into the store below. |
| 267 | // The first stage that reads `--graph`: with `--graph-ready-file`, everything above ran while |
| 268 | // `road_graph` was still working, and this is where the build waits for it. |
| 269 | if !graph.ready_now() { |
| 270 | timer.switch("graph-wait"); |
| 271 | } |
| 272 | graph.wait().map_err(osm_ingest::proto::Error)?; |
| 273 | timer.switch("junctions"); |
| 274 | if crate::tiler::size_opts().no_junction { |
| 275 | println!("--no-junction-layer: no lane connectors (the release style does not draw them)"); |
| 276 | stats.junction_connectors = 0; |
| 277 | } else { |
| 278 | println!("building lane connectors from the v6 routing graph for the junction layer"); |
| 279 | stats.junction_connectors = |
| 280 | schema::junction::stream_junctions(graph.dir(), &conventions, &mut sink)?; |
| 281 | } |
| 282 | stats.features += stats.junction_connectors; |
| 283 | println!(" {} lane connector(s)", stats.junction_connectors); |
| 284 | // `sink.finish` itself is a flush, not a loop: every feature was serialised and its coordinates |
| 285 | // e7-quantised in the `push` that spilled it, back in `materialise_ways`/`materialise_relations` |
| 286 | // (both parallel, both under a "Materialise:" bar) and in the streams above. The spill's byte |
| 287 | // order is the archive's, so that write stays serial by construction — there is nothing here to |
| 288 | // parallelise. The bar makes the finalise step visible rather than a silent tail of the ~25 s |
| 289 | // this phase costs; `stats.features` is the count the sink is closing over. |
| 290 | timer.switch("finalise"); |
| 291 | let mut bar = Progress::new( |
| 292 | "Finalise: features".to_string(), |
| 293 | stats.features as usize, |
| 294 | "feature(s)", |
| 295 | true, |
| 296 | ); |
| 297 | let store = sink.finish(spill_path)?; |
| 298 | bar.finish("feature(s)"); |
| 299 | let store = store.with_conventions(conventions); |
| 300 | |
| 301 | Ok(store) |
| 302 | } |
| 303 | |
| 304 | /// Node refs, duplicates included, above which the bitset replaces the sorted vector. |
| 305 | /// |
| 306 | /// 256 M refs is a 2 GB `Vec<i64>` plus a sort of 256 M elements, and it is roughly a us-west |
| 307 | /// extract. Below it the vector is smaller than the bitset and this stays exactly as it always was; |
| 308 | /// above it the vector is the largest thing in stage A and the bitset is a constant. |
| 309 | const REFS_IN_MEMORY: usize = 256 << 20; |
| 310 | |
| 311 | /// The node id a bitset will not be sized past. |
| 312 | /// |
| 313 | /// OSM assigns node ids monotonically and is near 13 G, so this is roughly 4x today's high-water |
| 314 | /// mark and 2.6 GB of bitset. It is a bound on the *data*, and a synthetic or non-OSM input with one |
| 315 | /// sparse enormous id would otherwise ask for a bitset the size of the id, so it is an error rather |
| 316 | /// than a clamp: a clamp would silently drop the nodes above it. |
| 317 | const MAX_NODE_ID: i64 = 48 << 30; |
| 318 | |
| 319 | /// The ids pass 3 must resolve, collected the way stage A always did. |
| 320 | /// |
| 321 | /// One bit per node id in `0..=max_id`. |
| 322 | struct NeededBits { |
| 323 | words: Vec<u64>, |
| 324 | /// `max_id + 1`. Kept because the last word is padded and a ref landing in that padding is out |
| 325 | /// of range, not merely addressable. |
| 326 | bits: usize, |
| 327 | count: usize, |
| 328 | } |
| 329 | |
| 330 | impl NeededBits { |
| 331 | #[cfg(test)] |
| 332 | fn new(max_id: i64) -> Result<NeededBits> { |
| 333 | if max_id > MAX_NODE_ID { |
| 334 | return err(format!( |
| 335 | "node id {max_id} is past the {MAX_NODE_ID} this build will size a bitset for; \ |
| 336 | OSM's own ids are near 13 billion, so this input is not an OSM extract" |
| 337 | )); |
| 338 | } |
| 339 | // `max_id` is a maximum, not a count, so the space is one larger. |
| 340 | let bits = max_id.max(0) as usize + 1; |
| 341 | Ok(NeededBits { words: vec![0u64; bits.div_ceil(64)], bits, count: 0 }) |
| 342 | } |
| 343 | |
| 344 | /// An unsized bitset that grows as larger ids arrive, for fusing collection |
| 345 | /// into pass 1's drain: the maximum is not known until the last way is |
| 346 | /// pushed, so the words extend on demand instead. Same guards as [`new`]; |
| 347 | /// the final size is identical to a sized bitset over the same ids. |
| 348 | fn new_growable() -> NeededBits { |
| 349 | NeededBits { words: Vec::new(), bits: 0, count: 0 } |
| 350 | } |
| 351 | |
| 352 | /// Set a bit, growing the words when the id lands past them. |
| 353 | /// |
| 354 | /// Refused rather than grown past [`MAX_NODE_ID`], like [`new`]: an id out |
| 355 | /// there is not an OSM node and growing for it would size the bitset for |
| 356 | /// one corrupt ref. |
| 357 | fn set_growable(&mut self, id: i64) -> Result<()> { |
| 358 | if id < 0 { |
| 359 | return err(format!("node ref {id} is negative")); |
| 360 | } |
| 361 | if id > MAX_NODE_ID { |
| 362 | return err(format!( |
| 363 | "node ref {id} is past the {MAX_NODE_ID} this build will size a bitset for" |
| 364 | )); |
| 365 | } |
| 366 | let at = id as usize; |
| 367 | if at >= self.bits { |
| 368 | self.bits = at + 1; |
| 369 | self.words.resize(self.bits.div_ceil(64), 0); |
| 370 | } |
| 371 | let word = &mut self.words[at / 64]; |
| 372 | let bit = 1u64 << (at % 64); |
| 373 | if *word & bit == 0 { |
| 374 | *word |= bit; |
| 375 | self.count += 1; |
| 376 | } |
| 377 | Ok(()) |
| 378 | } |
| 379 | |
| 380 | #[cfg(test)] |
| 381 | fn set(&mut self, id: i64) -> Result<()> { |
| 382 | // A negative ref is not a node this planet has. Refused rather than skipped: it means the |
| 383 | // spill or the PBF is not what it claims, and skipping would show as a way with a gap in it. |
| 384 | if id < 0 { |
| 385 | return err(format!("node ref {id} is negative")); |
| 386 | } |
| 387 | let at = id as usize; |
| 388 | if at >= self.bits { |
| 389 | return err(format!( |
| 390 | "node ref {id} is past the {} the bitset was sized for", |
| 391 | self.bits - 1 |
| 392 | )); |
| 393 | } |
| 394 | let word = &mut self.words[at / 64]; |
| 395 | let bit = 1u64 << (at % 64); |
| 396 | if *word & bit == 0 { |
| 397 | *word |= bit; |
| 398 | self.count += 1; |
| 399 | } |
| 400 | Ok(()) |
| 401 | } |
| 402 | |
| 403 | /// How many distinct ids were set. The `len` [`NodeLocations::from_bitset`] sizes from. |
| 404 | fn len(&self) -> usize { |
| 405 | self.count |
| 406 | } |
| 407 | |
| 408 | /// Hand the words over to the rank index: the collector is done setting bits and the index is |
| 409 | /// done needing a settable bitset, so one moves into the other rather than both living at once. |
| 410 | /// Consumes `self`; the count travels beside the words so the index need not recount them. |
| 411 | fn into_words(self) -> (Vec<u64>, usize) { |
| 412 | (self.words, self.count) |
| 413 | } |
| 414 | |
| 415 | /// Every set id, ascending. `trailing_zeros` on a word at a time, so an empty stretch of the id |
| 416 | /// space -- which is most of it, since a needed set is a subset of a subset -- costs one compare |
| 417 | /// per 64 ids rather than one per id. |
| 418 | fn ids(&self) -> impl Iterator<Item = i64> + '_ { |
| 419 | self.words.iter().enumerate().flat_map(|(w, word)| { |
| 420 | let mut rest = *word; |
| 421 | std::iter::from_fn(move || { |
| 422 | if rest == 0 { |
| 423 | return None; |
| 424 | } |
| 425 | let bit = rest.trailing_zeros() as usize; |
| 426 | rest &= rest - 1; |
| 427 | Some((w * 64 + bit) as i64) |
| 428 | }) |
| 429 | }) |
| 430 | } |
| 431 | } |
| 432 |