Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / coalesce.rs
coalesce.rs382 lines · 17.3 KiBRaw
| 1 | //! Merging a layer's line features into one per class, and joining the fragments that continue each |
| 2 | //! other. |
| 3 | //! |
| 4 | //! # Why this exists |
| 5 | //! |
| 6 | //! An OSM way is an **editing** unit. It is split at every junction, bridge, surface change and tag |
| 7 | //! edit, none of which has anything to do with what gets drawn. Carrying one way as one rendering |
| 8 | //! feature therefore pays a feature header and a part entry for each fragment of a road, and on a |
| 9 | //! us-west z7 tile that came to: |
| 10 | //! |
| 11 | //! | | count | width | bytes | |
| 12 | //! |---|---|---|---| |
| 13 | //! | feature records | 57,218 | 16 | 916 KB | |
| 14 | //! | part entries | 57,218 | 12 | 687 KB | |
| 15 | //! | coordinate arena | 189,484 points | ~2-3 | ~0.5 MB | |
| 16 | //! |
| 17 | //! Three quarters of the layer was bookkeeping, 61% of its parts held exactly two points, and the |
| 18 | //! mean was 3.31 points per part. The same tile's `boundaries` layer -- whose relations arrive |
| 19 | //! already merged -- ran 139 features over 667 parts, which is what healthy looks like. |
| 20 | //! |
| 21 | //! It compounds three ways. The headers are the obvious cost. Less obvious is that |
| 22 | //! [`tilecodec::mamaps::body`] restarts its coordinate deltas at every part so a part decodes |
| 23 | //! independently, so at 3.3 points per part most points are the *first* of their part and pay a full |
| 24 | //! absolute coordinate where a continued line would pay one byte. And a `.mamaps` layer indexes its |
| 25 | //! features with a `u16`, so a North America build stopped outright at `layer 4 has 79407 features, |
| 26 | //! past the 65535 a .mamaps body can index`. |
| 27 | //! |
| 28 | //! This is not a container-format problem -- MVT has the same one, which is why `tippecanoe` ships |
| 29 | //! `--coalesce`. It is that nothing in this pipeline ever merged what OSM had split. |
| 30 | //! |
| 31 | //! # What it does |
| 32 | //! |
| 33 | //! Two steps, and the first is the one that matters for the `u16`: |
| 34 | //! |
| 35 | //! 1. **Group by class.** Line features drawn identically -- same `kind`, `kind_detail`, `flags` |
| 36 | //! and `transit_color` -- become one multi-part feature. Nothing about the geometry changes; a |
| 37 | //! `.mamaps` line feature has always been able to hold many parts, and `boundaries` already did. |
| 38 | //! 2. **Join what continues.** Within a group, a part whose last point is another's first point is |
| 39 | //! the same line cut in half, so they are spliced into one part. That removes the part entry and |
| 40 | //! lets the delta run through the joint instead of restarting. |
| 41 | //! |
| 42 | //! # Why it is safe |
| 43 | //! |
| 44 | //! A `.mamaps` feature carries no identity of its own: [`Feature`] is `kind`, `kind_detail`, |
| 45 | //! `geom_type`, `flags`, `transit_color`, the three transit lane fields and a part range, and |
| 46 | //! nothing else. |
| 47 | //! Two line features that |
| 48 | //! agree on all of those are indistinguishable to a renderer, so merging them cannot change a pixel. |
| 49 | //! There are no names or ids on a feature to lose, and `winding` is meaningless on an open path -- |
| 50 | //! which [`crate::rings::normalise`] states outright. |
| 51 | //! |
| 52 | //! `transit_color` is part of the key rather than dropped from it because it is the one per-feature |
| 53 | //! field a renderer reads directly. Two subway lines of different operator colours crossing a tile |
| 54 | //! are the same `kind` and would otherwise collapse into one feature wearing whichever colour came |
| 55 | //! first. The lane fields join it for the same reason one step on: two routes of *one* colour on |
| 56 | //! different corridor ordinals are drawn as two parallel lines, and merging them would put both |
| 57 | //! on whichever ordinal came first. |
| 58 | //! |
| 59 | //! The carriageway joins the key too, and it is the one part of the key that is **not** on the |
| 60 | //! feature: the directional split lives in a side table because it is present on a minority of |
| 61 | //! roads. It has to be in the key all the same, because two four-lane roads that divide 3/1 and |
| 62 | //! 1/3 are drawn as different surfaces with the centre line in different places. A one-way and a |
| 63 | //! two-way are already separated for free, because that one is a flag. |
| 64 | //! |
| 65 | //! Direction is not preserved through a join and does not need to be: nothing in |
| 66 | //! [`tilecodec::mamaps::body`]'s flag set reads a line's direction, so `A -> B` and `B -> A` draw |
| 67 | //! the same. Joins are made head-to-tail only, so a part is never reversed anyway. |
| 68 | //! |
| 69 | //! # Ordering, and why the archive stays reproducible |
| 70 | //! |
| 71 | //! Called on a tile that the merge has already assembled, so it sees a layer's features in the order |
| 72 | //! the store yielded them, and it emits each class at the position of that class's **first** feature. |
| 73 | //! A group's parts stay in feature-then-part order and chains are built by walking them in that |
| 74 | //! order, so nothing here depends on a hash map's iteration order or on how the map phase chunked |
| 75 | //! its input. |
| 76 | |
| 77 | use std::collections::HashMap; |
| 78 | |
| 79 | use crate::coalesce_extra::Run; |
| 80 | use tilecodec::mamaps::body::{ |
| 81 | BuildingAttrs, Carriageway, LaneTurns, Layer, Part, GEOM_LINE, WINDING_OUTER, |
| 82 | }; |
| 83 | |
| 84 | /// What coalescing a build saved, for the report. |
| 85 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] |
| 86 | pub struct Stats { |
| 87 | pub features_before: u64, |
| 88 | pub features_after: u64, |
| 89 | pub parts_before: u64, |
| 90 | pub parts_after: u64, |
| 91 | } |
| 92 | |
| 93 | impl Stats { |
| 94 | pub fn add(&mut self, other: Stats) { |
| 95 | self.features_before += other.features_before; |
| 96 | self.features_after += other.features_after; |
| 97 | self.parts_before += other.parts_before; |
| 98 | self.parts_after += other.parts_after; |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// What makes two line features interchangeable to a renderer. The trailing `name_idx` keeps two |
| 103 | /// differently-named roads or rivers of the same class apart, so a curved label is never attached |
| 104 | /// to a line that merged with a neighbour of another name; same-named fragments still merge. |
| 105 | /// |
| 106 | /// The last three come from the carriageway side table rather than from the feature, and they are |
| 107 | /// in the key for the same reason `transit_color` is: two four-lane roads of one class that divide |
| 108 | /// 3/1 and 1/3 are drawn as different surfaces, and merging them would put both on whichever split |
| 109 | /// came first. `flags` already separates a one-way from a two-way, because that is a flag. |
| 110 | type Class = (u16, u16, u8, u32, u8, u8, u8, u8, u16, u8, u8, u32); |
| 111 | |
| 112 | /// One line part, as `(coord_start, point_count)` into a layer's existing arena. |
| 113 | /// |
| 114 | /// Indices rather than copied points: a group can hold tens of thousands of parts, and a `Vec` of |
| 115 | /// points each would be the allocation this module exists to remove. |
| 116 | pub(crate) type Span = (u32, u32); |
| 117 | |
| 118 | /// Merge a layer's line features by class and splice the parts that continue each other. |
| 119 | /// |
| 120 | /// Polygon features are left exactly as they were, in place; only the parts table and the arena are |
| 121 | /// rebuilt around them, which [`crate::rings::normalise`] does immediately afterwards anyway. |
| 122 | #[cfg(test)] |
| 123 | pub fn coalesce_lines(layer: &mut Layer) -> Stats { |
| 124 | coalesce_lines_with_ids(layer, None, None, None, None) |
| 125 | } |
| 126 | |
| 127 | /// As [`coalesce_lines`], but also rewrites an id side table, a turn-lane side table and a |
| 128 | /// carriageway side table so they stay parallel to the features. |
| 129 | /// |
| 130 | /// The tables are indexed by feature position, so merging lines without rewriting them leaves more |
| 131 | /// entries than features and the encoder rejects the tile. A merged line takes the id of the first |
| 132 | /// feature of its class, which is arbitrary — that is why only layers whose id-carrying features |
| 133 | /// are *not* lines populate the id table at all (see `extract::tracks_ids`). Turn masks are the |
| 134 | /// opposite: they belong to a *road* line, so a line that carries any is held out of merging |
| 135 | /// entirely (each becomes its own survivor) rather than folded into a neighbour and losing them. |
| 136 | /// A carriageway takes the third route: it is part of the merge key, so a survivor's split is by |
| 137 | /// construction the split every line it absorbed had. |
| 138 | pub fn coalesce_lines_with_ids( |
| 139 | layer: &mut Layer, |
| 140 | ids: Option<&mut Vec<u64>>, |
| 141 | turns: Option<&mut Vec<LaneTurns>>, |
| 142 | buildings: Option<&mut Vec<BuildingAttrs>>, |
| 143 | carriageways: Option<&mut Vec<Carriageway>>, |
| 144 | ) -> Stats { |
| 145 | let mut stats = Stats { |
| 146 | features_before: layer.features.len() as u64, |
| 147 | parts_before: layer.parts.len() as u64, |
| 148 | ..Stats::default() |
| 149 | }; |
| 150 | let lines = layer.features.iter().filter(|f| f.geom_type == GEOM_LINE).count(); |
| 151 | // One line feature cannot be merged with anything, and a layer of pure polygons is the common |
| 152 | // case: both would only pay for a rebuild that changes nothing. |
| 153 | // |
| 154 | // Boundaries are never merged at all: their relations arrive one feature per member way, |
| 155 | // and merging them by class would chain the US-Canada border to the US-Mexico border |
| 156 | // across the continent into one part — destroying the per-way tile locality that keeps |
| 157 | // border tiles small and complete. The u16 feature cap this exists to relieve does not |
| 158 | // bind here (relations are already merged); roads are the layer that needs it. |
| 159 | if lines < 2 || layer.layer_id == tilecodec::mamaps::dict::LAYER_BOUNDARIES { |
| 160 | stats.features_after = stats.features_before; |
| 161 | stats.parts_after = stats.parts_before; |
| 162 | return stats; |
| 163 | } |
| 164 | |
| 165 | // A line that carries turn masks is never merged — its arrows belong to that exact segment — |
| 166 | // so it is copied through at its position like a non-line. `false` everywhere when the layer |
| 167 | // has no turn table, which is every layer but a `roads` tile that had `turn:lanes` in it. |
| 168 | let unmergeable: Vec<bool> = match turns.as_deref() { |
| 169 | Some(t) => layer |
| 170 | .features |
| 171 | .iter() |
| 172 | .enumerate() |
| 173 | .map(|(i, _)| t.get(i).is_some_and(|lt| !lt.is_empty())) |
| 174 | .collect(), |
| 175 | None => vec![false; layer.features.len()], |
| 176 | }; |
| 177 | |
| 178 | // The split a feature's key carries, read out before the tables are borrowed mutably below. |
| 179 | // Default when the layer has no carriageway table, which is every layer but `roads`. |
| 180 | let split = |at: usize| -> Carriageway { |
| 181 | carriageways.as_deref().and_then(|c| c.get(at).copied()).unwrap_or_default() |
| 182 | }; |
| 183 | |
| 184 | // Every line part, grouped by class, in feature-then-part order. |
| 185 | let mut order: Vec<Class> = Vec::new(); |
| 186 | let mut group_of: HashMap<Class, usize> = HashMap::new(); |
| 187 | let mut groups: Vec<Vec<Span>> = Vec::new(); |
| 188 | for (index, feature) in layer.features.iter().enumerate() { |
| 189 | if feature.geom_type != GEOM_LINE || unmergeable[index] { |
| 190 | continue; |
| 191 | } |
| 192 | let class = class_of(feature, split(index)); |
| 193 | let at = *group_of.entry(class).or_insert_with(|| { |
| 194 | order.push(class); |
| 195 | groups.push(Vec::new()); |
| 196 | groups.len() - 1 |
| 197 | }); |
| 198 | let from = feature.parts_offset as usize; |
| 199 | for part in &layer.parts[from..from + feature.part_count as usize] { |
| 200 | groups[at].push((part.coord_start, part.point_count)); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // Chains first, so the arena can be laid down in one pass below. |
| 205 | let chains: Vec<Vec<Run>> = groups.iter().map(|parts| chain(parts, &layer.coords)).collect(); |
| 206 | |
| 207 | let mut features = Vec::with_capacity(layer.features.len() - lines + order.len()); |
| 208 | // The original position of each surviving feature, for remapping the side tables below. |
| 209 | let mut kept: Vec<usize> = Vec::with_capacity(features.capacity()); |
| 210 | let mut parts: Vec<Part> = Vec::with_capacity(layer.parts.len()); |
| 211 | let mut coords: Vec<(i16, i16)> = Vec::with_capacity(layer.coords.len()); |
| 212 | let mut emitted: Vec<bool> = vec![false; order.len()]; |
| 213 | |
| 214 | for (index, feature) in layer.features.iter().enumerate() { |
| 215 | if feature.geom_type != GEOM_LINE || unmergeable[index] { |
| 216 | // Copied through at its original position, so a mixed layer keeps its feature order and |
| 217 | // a turn-masked road keeps its own geometry and its arrows. |
| 218 | let from = feature.parts_offset as usize; |
| 219 | let start = parts.len() as u32; |
| 220 | for part in &layer.parts[from..from + feature.part_count as usize] { |
| 221 | let points = points_of(&layer.coords, *part); |
| 222 | parts.push(Part { |
| 223 | coord_start: coords.len() as u32, |
| 224 | point_count: points.len() as u32, |
| 225 | winding: part.winding, |
| 226 | }); |
| 227 | coords.extend_from_slice(points); |
| 228 | } |
| 229 | let mut copy = *feature; |
| 230 | copy.parts_offset = start; |
| 231 | features.push(copy); |
| 232 | kept.push(index); |
| 233 | continue; |
| 234 | } |
| 235 | let class = class_of(feature, split(index)); |
| 236 | let at = group_of[&class]; |
| 237 | if emitted[at] { |
| 238 | continue; |
| 239 | } |
| 240 | emitted[at] = true; |
| 241 | let start = parts.len() as u32; |
| 242 | for run in &chains[at] { |
| 243 | let first = coords.len() as u32; |
| 244 | for (i, &(coord_start, point_count)) in run.iter().enumerate() { |
| 245 | let points = points_of( |
| 246 | &layer.coords, |
| 247 | Part { coord_start, point_count, winding: WINDING_OUTER }, |
| 248 | ); |
| 249 | // The joint is one point in two parts; the second copy would be a zero-length |
| 250 | // segment and `geom::quantize` is no longer around to drop it. |
| 251 | let points = if i == 0 { points } else { &points[1..] }; |
| 252 | coords.extend_from_slice(points); |
| 253 | } |
| 254 | parts.push(Part { |
| 255 | coord_start: first, |
| 256 | point_count: coords.len() as u32 - first, |
| 257 | winding: WINDING_OUTER, |
| 258 | }); |
| 259 | } |
| 260 | let mut merged = *feature; |
| 261 | merged.parts_offset = start; |
| 262 | merged.part_count = parts.len() as u32 - start; |
| 263 | features.push(merged); |
| 264 | kept.push(index); |
| 265 | } |
| 266 | |
| 267 | if let Some(ids) = ids { |
| 268 | if !ids.is_empty() { |
| 269 | *ids = kept.iter().map(|&at| ids[at]).collect(); |
| 270 | } |
| 271 | } |
| 272 | if let Some(turns) = turns { |
| 273 | if !turns.is_empty() { |
| 274 | *turns = kept.iter().map(|&at| turns[at].clone()).collect(); |
| 275 | } |
| 276 | } |
| 277 | if let Some(buildings) = buildings { |
| 278 | if !buildings.is_empty() { |
| 279 | *buildings = kept.iter().map(|&at| buildings[at]).collect(); |
| 280 | } |
| 281 | } |
| 282 | if let Some(carriageways) = carriageways { |
| 283 | if !carriageways.is_empty() { |
| 284 | *carriageways = kept.iter().map(|&at| carriageways[at]).collect(); |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | layer.features = features; |
| 289 | layer.parts = parts; |
| 290 | layer.coords = coords; |
| 291 | stats.features_after = layer.features.len() as u64; |
| 292 | stats.parts_after = layer.parts.len() as u64; |
| 293 | stats |
| 294 | } |
| 295 | |
| 296 | fn class_of(feature: &tilecodec::mamaps::body::Feature, carriageway: Carriageway) -> Class { |
| 297 | ( |
| 298 | feature.kind, |
| 299 | feature.kind_detail, |
| 300 | feature.flags, |
| 301 | feature.transit_color, |
| 302 | feature.transit_ordinal, |
| 303 | feature.transit_lanes, |
| 304 | feature.transit_taper, |
| 305 | feature.lane_count, |
| 306 | feature.name_idx, |
| 307 | carriageway.forward, |
| 308 | carriageway.backward, |
| 309 | carriageway.solid_dividers, |
| 310 | ) |
| 311 | } |
| 312 | |
| 313 | pub(crate) fn points_of(coords: &[(i16, i16)], part: Part) -> &[(i16, i16)] { |
| 314 | let at = part.coord_start as usize; |
| 315 | &coords[at..at + part.point_count as usize] |
| 316 | } |
| 317 | |
| 318 | /// Group `parts` into runs that each form one continuous polyline. |
| 319 | /// |
| 320 | /// Head-to-tail only: a part joins the chain when its first point is the chain's last. Parts are |
| 321 | /// never reversed, so the result is a subset of the joins a reversing walk would find -- and it is |
| 322 | /// the subset that needs no argument about direction. |
| 323 | /// |
| 324 | /// Chains start at parts nothing runs into, so a road is grown from its end rather than from its |
| 325 | /// middle; only then are the leftovers taken, which is what closes a ring road onto itself. Both |
| 326 | /// loops walk `parts` in order, so the output does not depend on the hash map. |
| 327 | fn chain(parts: &[Span], coords: &[(i16, i16)]) -> Vec<Run> { |
| 328 | let ends: Vec<((i16, i16), (i16, i16))> = parts |
| 329 | .iter() |
| 330 | .map(|&(coord_start, point_count)| { |
| 331 | let points = |
| 332 | points_of(coords, Part { coord_start, point_count, winding: WINDING_OUTER }); |
| 333 | // A part with nothing in it cannot join anything; a sentinel keeps the index aligned. |
| 334 | match (points.first(), points.last()) { |
| 335 | (Some(a), Some(b)) => (*a, *b), |
| 336 | _ => ((i16::MIN, i16::MIN), (i16::MAX, i16::MAX)), |
| 337 | } |
| 338 | }) |
| 339 | .collect(); |
| 340 | |
| 341 | let mut by_start: HashMap<(i16, i16), Vec<usize>> = HashMap::new(); |
| 342 | for (i, (first, _)) in ends.iter().enumerate() { |
| 343 | by_start.entry(*first).or_default().push(i); |
| 344 | } |
| 345 | // Whether anything ends where this part starts. A part that nothing runs into is a chain head. |
| 346 | let mut continued = vec![false; parts.len()]; |
| 347 | for (_, last) in &ends { |
| 348 | if let Some(hits) = by_start.get(last) { |
| 349 | for &i in hits { |
| 350 | continued[i] = true; |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | let mut used = vec![false; parts.len()]; |
| 356 | let mut out: Vec<Run> = Vec::new(); |
| 357 | let grow = |from: usize, used: &mut Vec<bool>, out: &mut Vec<Run>| { |
| 358 | let mut run: Run = vec![parts[from]]; |
| 359 | used[from] = true; |
| 360 | let mut tail = ends[from].1; |
| 361 | while let Some(next) = |
| 362 | by_start.get(&tail).and_then(|hits| hits.iter().copied().find(|&j| !used[j])) |
| 363 | { |
| 364 | used[next] = true; |
| 365 | run.push(parts[next]); |
| 366 | tail = ends[next].1; |
| 367 | } |
| 368 | out.push(run); |
| 369 | }; |
| 370 | for i in 0..parts.len() { |
| 371 | if !used[i] && !continued[i] { |
| 372 | grow(i, &mut used, &mut out); |
| 373 | } |
| 374 | } |
| 375 | // Whatever is left is a cycle: every part in it is continued by another, so none is a head. |
| 376 | for i in 0..parts.len() { |
| 377 | if !used[i] { |
| 378 | grow(i, &mut used, &mut out); |
| 379 | } |
| 380 | } |
| 381 | out |
| 382 | } |