Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / tiler_part5.rs
tiler_part5.rs369 lines · 18.4 KiBRaw
| 1 | fn encode_batch( |
| 2 | batch: Vec<(u64, Vec<ChunkEntry>)>, |
| 3 | dem: &crate::dem::Dem, |
| 4 | conventions: &crate::schema::boundaries::Conventions, |
| 5 | region_links: &std::collections::HashMap<u64, u64>, |
| 6 | ) -> Result<Vec<Encoded>> { |
| 7 | // Split the batch into tasks by cumulative geometry cost rather than by tile count. A dense |
| 8 | // city tile is orders of magnitude more work than a rural one, and `with_min_len` — which forces |
| 9 | // contiguous runs of a fixed *count* — cannot give that tile a task of its own: it stays welded |
| 10 | // to its cheap neighbours while the rest of the pool drains. Grouping by cost lets the biggest |
| 11 | // tiles fall into their own tasks. Order is untouched: the groups are contiguous slices of the |
| 12 | // batch in order, each group is encoded in order, and the per-group results are flattened in |
| 13 | // group order — so `collect`'s positional guarantee still lands every tile where it was, and the |
| 14 | // archive is byte for byte the same. |
| 15 | let groups = partition_by_cost(batch, par::encode_task_count()); |
| 16 | par::install(|| { |
| 17 | let grouped: Result<Vec<Vec<Encoded>>> = groups |
| 18 | .into_par_iter() |
| 19 | // One DEFLATE state and one serialisation buffer per worker, not one per tile. |
| 20 | // `compress_to_vec` builds a 65,712-byte `CompressorOxide` every call, and at a tile |
| 21 | // each across 64 cores that construction swamps the compression it exists to do -- see |
| 22 | // `mamaps::write::compress_body_with`. The `Scratch` is there for the same reason on |
| 23 | // the serialisation side: its allocations, not its encoding, were what made |
| 24 | // serialisation cost 20.9 s of CPU at 16 threads and 1120 s at 64. Reused across every |
| 25 | // tile in a group, not merely once per task. |
| 26 | .map_init( |
| 27 | || (tilecodec::gz::Compressor::new(), tilecodec::mamaps::body::Scratch::default()), |
| 28 | |(deflate, scratch), group| { |
| 29 | group |
| 30 | .into_iter() |
| 31 | .map(|(id, layers)| { |
| 32 | encode_tile(id, layers, dem, conventions, region_links, deflate, scratch) |
| 33 | }) |
| 34 | .collect::<Result<Vec<Encoded>>>() |
| 35 | }, |
| 36 | ) |
| 37 | .collect(); |
| 38 | Ok(grouped?.into_iter().flatten().collect()) |
| 39 | }) |
| 40 | } |
| 41 | |
| 42 | /// Coalesce, stage C, serialise and DEFLATE one merged tile, reusing the worker's compressor and |
| 43 | /// serialisation scratch. |
| 44 | /// |
| 45 | /// Pulled out of [`encode_batch`] so the batch can be split into cost-balanced groups and this run |
| 46 | /// per tile inside each group; the steps and their order are unchanged, so the encoded bytes are |
| 47 | /// too. A tile whose layers all empty out under coalescing and stage C comes back as |
| 48 | /// `(id, None, ..)` rather than being dropped, because its stage C and coalescing counters still |
| 49 | /// belong in the build report. |
| 50 | fn encode_tile( |
| 51 | id: u64, |
| 52 | mut layers: Vec<ChunkEntry>, |
| 53 | dem: &crate::dem::Dem, |
| 54 | conventions: &crate::schema::boundaries::Conventions, |
| 55 | region_links: &std::collections::HashMap<u64, u64>, |
| 56 | deflate: &mut tilecodec::gz::Compressor, |
| 57 | scratch: &mut tilecodec::mamaps::body::Scratch, |
| 58 | ) -> Result<Encoded> { |
| 59 | // **Coalesce first.** An OSM way is an editing unit, not a rendering one, so a road arrives as |
| 60 | // hundreds of two-point fragments each carrying its own 28 bytes of header -- see |
| 61 | // `crate::coalesce`. Merging them before stage C is also what keeps stage C off tens of |
| 62 | // thousands of features it would only copy through. |
| 63 | let mut lines = crate::coalesce::Stats::default(); |
| 64 | for entry in &mut layers { |
| 65 | // The traffic layer is one feature per component segment, each carrying a distinct |
| 66 | // component_id in the id table. Coalescing merges a class's lines into one feature, which |
| 67 | // would collapse every segment's id onto whichever came first — so it is skipped, keeping |
| 68 | // the layer one-to-one with its ids. |
| 69 | // |
| 70 | // The junction layer is skipped for the neighbouring reason: it carries no ids, but each |
| 71 | // feature is one lane's connector through an intersection and they all share a class, so |
| 72 | // coalescing would chain unrelated connectors — a left turn and the through movement beside |
| 73 | // it — into one polyline and draw a ribbon between them. |
| 74 | if entry.layer.layer_id == tilecodec::mamaps::dict::LAYER_TRAFFIC |
| 75 | || entry.layer.layer_id == tilecodec::mamaps::dict::LAYER_JUNCTION |
| 76 | { |
| 77 | continue; |
| 78 | } |
| 79 | lines.add(crate::coalesce::coalesce_lines_with_ids( |
| 80 | &mut entry.layer, |
| 81 | Some(&mut entry.ids), |
| 82 | Some(&mut entry.turn_lanes), |
| 83 | Some(&mut entry.buildings), |
| 84 | Some(&mut entry.carriageways), |
| 85 | )); |
| 86 | } |
| 87 | // **Stage C**, per tile: winding normalised, hole containment resolved, degenerate rings |
| 88 | // dropped. Once, here, in `f64` with no frame budget, instead of every frame on device in `i32` |
| 89 | // under one. This is what makes `FLAG_RINGS_VALIDATED` true. |
| 90 | let mut rings = crate::rings::Stats::default(); |
| 91 | for entry in &mut layers { |
| 92 | rings.add(crate::rings::normalise_with_ids( |
| 93 | &mut entry.layer, |
| 94 | Some(&mut entry.ids), |
| 95 | Some(&mut entry.turn_lanes), |
| 96 | Some(&mut entry.buildings), |
| 97 | )); |
| 98 | } |
| 99 | // A layer that ended up empty - every feature in it fell below the minimum area after |
| 100 | // clipping, or lost its exterior to stage C - costs bytes in the archive and a draw call on |
| 101 | // device for nothing. |
| 102 | layers.retain(|entry| !entry.layer.features.is_empty()); |
| 103 | if layers.is_empty() { |
| 104 | return Ok((id, None, rings, lines)); |
| 105 | } |
| 106 | // Phase B: a full-bleed single-water-polygon tile is water, not a tile. One |
| 107 | // water polygon covering the whole tile draws exactly what the style's water |
| 108 | // background already paints, so storing it buys a body, an index entry and a |
| 109 | // fetch for zero pixels. `None` (not stored) like an emptied tile, and the |
| 110 | // reader overzooms the parent whose background shows through. |
| 111 | if is_water_background(&layers) { |
| 112 | return Ok((id, None, rings, lines)); |
| 113 | } |
| 114 | // What the `u16` feature index in the body format has to hold. Sampled here because this is the |
| 115 | // shape that reaches the encoder: after coalescing merged the line fragments and after stage C |
| 116 | // dropped what it drops. |
| 117 | // |
| 118 | // Read before the read-modify-write: the slot almost never grows, and an unconditional |
| 119 | // `fetch_max` from every encode thread on every tile kept these few cache lines bouncing |
| 120 | // across 192 cores on zooms of millions of small tiles. Same maximum either way. |
| 121 | for entry in &layers { |
| 122 | let slot = &WIDEST_LAYER[entry.layer.layer_id as usize]; |
| 123 | let n = entry.layer.features.len() as u64; |
| 124 | if slot.load(Ordering::Relaxed) < n { |
| 125 | slot.fetch_max(n, Ordering::Relaxed); |
| 126 | } |
| 127 | } |
| 128 | // Fuse the layers' name tables into the body's one, in layer order, remapping every feature's |
| 129 | // index as it goes. First-use order is deterministic (merge order within a layer, layer order |
| 130 | // across them), so the same tile always carries the same table. A probe-only `HashMap` keeps the |
| 131 | // fusion linear rather than quadratic in the tile's name count; it is never iterated, and a name |
| 132 | // is cloned only the first time it is seen, so the table's order and bytes are exactly what a |
| 133 | // linear `position` scan produced. |
| 134 | let mut names: Vec<String> = Vec::new(); |
| 135 | let mut name_index: HashMap<String, u16> = HashMap::new(); |
| 136 | for entry in &mut layers { |
| 137 | for feature in &mut entry.layer.features { |
| 138 | if feature.name_idx != tilecodec::mamaps::body::NAME_NONE { |
| 139 | let name = &entry.names[feature.name_idx as usize - 1]; |
| 140 | feature.name_idx = match name_index.get(name.as_str()) { |
| 141 | Some(&at) => at, |
| 142 | None => { |
| 143 | let idx = names.len() as u16 + 1; |
| 144 | names.push(name.clone()); |
| 145 | name_index.insert(name.clone(), idx); |
| 146 | idx |
| 147 | } |
| 148 | }; |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | // Fuse the layers' id tables into the body's one. Unlike names these are values rather than |
| 153 | // indices, so nothing is remapped and nothing is deduplicated — the table is simply the |
| 154 | // surviving `places`/`poi` layers' vectors, in layer order, which `Merged` already delivers |
| 155 | // ascending. |
| 156 | // |
| 157 | // Checked against the feature count rather than assumed. `coalesce_lines` rebuilds a layer's |
| 158 | // features and `rings::normalise` retains over them, and both now rewrite the id table |
| 159 | // alongside. That is easy to get wrong and silent when it is - every id after the first casualty |
| 160 | // would describe the wrong feature - so this fails the build instead. |
| 161 | let mut ids: Vec<(u8, Vec<u64>)> = Vec::new(); |
| 162 | for entry in &mut layers { |
| 163 | if entry.ids.is_empty() { |
| 164 | continue; |
| 165 | } |
| 166 | if entry.ids.len() != entry.layer.features.len() { |
| 167 | return err(format!( |
| 168 | "layer {} has {} id(s) for {} feature(s) after coalesce and \ |
| 169 | stage C", |
| 170 | entry.layer.layer_id, |
| 171 | entry.ids.len(), |
| 172 | entry.layer.features.len(), |
| 173 | )); |
| 174 | } |
| 175 | ids.push((entry.layer.layer_id, std::mem::take(&mut entry.ids))); |
| 176 | } |
| 177 | // The region-link table: for each `places` label, the tagged relation id of the boundary it |
| 178 | // names, looked up from stage A's link map by the label's own (tagged node) id — which is |
| 179 | // exactly what the id table above holds. Dense-parallel to the layer's features like the id |
| 180 | // table, with REGION_NONE where a label links to no region. Emitted only when at least one |
| 181 | // label in the tile links somewhere, so a tile of unlinked labels (or no places at all) carries |
| 182 | // no table. |
| 183 | let mut region_links_table: Vec<(u8, Vec<u64>)> = Vec::new(); |
| 184 | if !region_links.is_empty() { |
| 185 | for (layer_id, node_ids) in &ids { |
| 186 | if *layer_id != tilecodec::mamaps::dict::LAYER_PLACES { |
| 187 | continue; |
| 188 | } |
| 189 | let links: Vec<u64> = node_ids |
| 190 | .iter() |
| 191 | .map(|id| { |
| 192 | region_links |
| 193 | .get(id) |
| 194 | .copied() |
| 195 | .unwrap_or(tilecodec::mamaps::body::REGION_NONE) |
| 196 | }) |
| 197 | .collect(); |
| 198 | if links.iter().any(|&l| l != tilecodec::mamaps::body::REGION_NONE) { |
| 199 | region_links_table.push((*layer_id, links)); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | // The turn-lane table, built the same way as the id table and checked against the feature count |
| 204 | // for the same reason: coalesce and stage C rebuild a layer's features and rewrite this |
| 205 | // alongside, and a drift would misattribute every lane after the first. Only emitted when some |
| 206 | // road actually has turn masks, so a tile with none carries no table at all. |
| 207 | let mut turn_lanes: Vec<(u8, Vec<tilecodec::mamaps::body::LaneTurns>)> = Vec::new(); |
| 208 | for entry in &mut layers { |
| 209 | if entry.turn_lanes.is_empty() { |
| 210 | continue; |
| 211 | } |
| 212 | if entry.turn_lanes.len() != entry.layer.features.len() { |
| 213 | return err(format!( |
| 214 | "layer {} has {} turn record(s) for {} feature(s) after coalesce \ |
| 215 | and stage C", |
| 216 | entry.layer.layer_id, |
| 217 | entry.turn_lanes.len(), |
| 218 | entry.layer.features.len(), |
| 219 | )); |
| 220 | } |
| 221 | if entry.turn_lanes.iter().all(|t| t.is_empty()) { |
| 222 | entry.turn_lanes.clear(); |
| 223 | continue; |
| 224 | } |
| 225 | turn_lanes.push((entry.layer.layer_id, std::mem::take(&mut entry.turn_lanes))); |
| 226 | } |
| 227 | // The building side table, built the same way and checked against the feature count for the same |
| 228 | // reason. A tile whose buildings all carried default attrs (no S3DB tags) emits no table at all |
| 229 | // — the renderer falls back to its own default height and colour — so the table is paid for only |
| 230 | // where 3D data exists. |
| 231 | let mut buildings: Vec<(u8, Vec<BuildingAttrs>)> = Vec::new(); |
| 232 | for entry in &mut layers { |
| 233 | if entry.buildings.is_empty() { |
| 234 | continue; |
| 235 | } |
| 236 | if entry.buildings.len() != entry.layer.features.len() { |
| 237 | return err(format!( |
| 238 | "layer {} has {} building record(s) for {} feature(s) after \ |
| 239 | coalesce and stage C", |
| 240 | entry.layer.layer_id, |
| 241 | entry.buildings.len(), |
| 242 | entry.layer.features.len(), |
| 243 | )); |
| 244 | } |
| 245 | if entry.buildings.iter().all(|b| *b == BuildingAttrs::default()) { |
| 246 | entry.buildings.clear(); |
| 247 | continue; |
| 248 | } |
| 249 | buildings.push((entry.layer.layer_id, std::mem::take(&mut entry.buildings))); |
| 250 | } |
| 251 | // The carriageway side table, built like the two above and checked against the feature count for |
| 252 | // the same reason. |
| 253 | // |
| 254 | // A tile where no road's split was ever surveyed usually emits no table at all, so it costs |
| 255 | // nothing for lane data that does not exist. The exception is a tile whose country is not the |
| 256 | // default one: the convention only reaches the wire alongside a table, and a tile of untagged |
| 257 | // residential streets in Tokyo still has to say that traffic keeps left. So an all-default table |
| 258 | // is kept exactly when there is a non-default convention to carry with it. |
| 259 | let (z, x, y) = tilecodec::pmtiles::tile_zxy(id); |
| 260 | let convention = conventions.at_tile(z, x, y); |
| 261 | let mut carriageways: Vec<(u8, Vec<tilecodec::mamaps::body::Carriageway>)> = Vec::new(); |
| 262 | for entry in &mut layers { |
| 263 | if entry.carriageways.is_empty() { |
| 264 | continue; |
| 265 | } |
| 266 | if entry.carriageways.len() != entry.layer.features.len() { |
| 267 | return err(format!( |
| 268 | "layer {} has {} carriageway record(s) for {} feature(s) after \ |
| 269 | coalesce and stage C", |
| 270 | entry.layer.layer_id, |
| 271 | entry.carriageways.len(), |
| 272 | entry.layer.features.len(), |
| 273 | )); |
| 274 | } |
| 275 | if convention == tilecodec::mamaps::body::MarkingConvention::default() |
| 276 | && entry.carriageways.iter().all(|c| c.is_empty()) |
| 277 | { |
| 278 | entry.carriageways.clear(); |
| 279 | continue; |
| 280 | } |
| 281 | carriageways.push((entry.layer.layer_id, std::mem::take(&mut entry.carriageways))); |
| 282 | } |
| 283 | let convention = (!carriageways.is_empty()).then_some(convention); |
| 284 | let body = Body { |
| 285 | extent: EXTENT as u16, |
| 286 | layers: layers.into_iter().map(|entry| entry.layer).collect(), |
| 287 | names, |
| 288 | ids, |
| 289 | turn_lanes, |
| 290 | buildings, |
| 291 | // The DEM heightmap is produced by a separate ingest stage keyed by tile, not from OSM |
| 292 | // geometry. Sample its grid onto this tile's z/x/y; a tile with no DEM under it (ocean, |
| 293 | // off-coverage) gets None and stays 16-byte. |
| 294 | heightmap: dem.heightmap_for(z, x, y), |
| 295 | carriageways, |
| 296 | convention, |
| 297 | region_links: region_links_table, |
| 298 | }; |
| 299 | // v10 narrowed records + sparse side tables are the default: same |
| 300 | // geometry either way — only the fixed records shrink — so this |
| 301 | // changes bytes, never shapes. `MAMAPS_V8=1` opts back out to the |
| 302 | // dense v8 bodies (escape hatch for bisecting a suspect build). A command-line flag |
| 303 | // (`--v8-bodies`), never the environment, and part of the build id. |
| 304 | let encoded_body = if crate::tiler::V8_BODIES.load(std::sync::atomic::Ordering::Relaxed) { |
| 305 | tilecodec::mamaps::body::serialize_into(&body, scratch) |
| 306 | } else { |
| 307 | tilecodec::mamaps::body::serialize_into_v10(&body, scratch) |
| 308 | }?; |
| 309 | let raw_len = encoded_body.len(); |
| 310 | let level = crate::tiler::size_opts().zstd_level; |
| 311 | let stored = if level > 0 { |
| 312 | tilecodec::mamaps::write::compress_body_zstd_level(encoded_body, level) |
| 313 | } else { |
| 314 | tilecodec::mamaps::write::compress_body_with(deflate, encoded_body) |
| 315 | }; |
| 316 | // Compute the dedup key here, in the parallel worker, rather than on the serial append thread. |
| 317 | // It is a pure function of the stored bytes, so the key — and every dedup decision the writer |
| 318 | // makes from it — is unchanged; it just no longer walks the whole body downstream of this phase. |
| 319 | let hash = tilecodec::mamaps::write::hash64(&stored); |
| 320 | Ok((id, Some((stored, raw_len, hash)), rings, lines)) |
| 321 | } |
| 322 | |
| 323 | /// Split a merged batch into contiguous groups of roughly equal cumulative geometry cost. |
| 324 | /// |
| 325 | /// `target_tasks` is the number of groups aimed for — a few per thread. Cost is a tile's feature |
| 326 | /// and coordinate count, which is what stage C, serialisation and DEFLATE all scale with; a tile |
| 327 | /// heavier than the per-group budget on its own becomes its own group, which is the whole point. |
| 328 | /// The groups are contiguous and in batch order, so flattening their encoded results reproduces the |
| 329 | /// batch's tile order exactly — the archive does not move. |
| 330 | fn partition_by_cost( |
| 331 | batch: Vec<(u64, Vec<ChunkEntry>)>, |
| 332 | target_tasks: usize, |
| 333 | ) -> Vec<Vec<(u64, Vec<ChunkEntry>)>> { |
| 334 | let total: u64 = batch.iter().map(|(_, layers)| tile_cost(layers)).sum(); |
| 335 | let target = (total / target_tasks.max(1) as u64).max(1); |
| 336 | let mut groups: Vec<Vec<(u64, Vec<ChunkEntry>)>> = Vec::new(); |
| 337 | let mut current: Vec<(u64, Vec<ChunkEntry>)> = Vec::new(); |
| 338 | let mut current_cost = 0u64; |
| 339 | for (id, layers) in batch { |
| 340 | let cost = tile_cost(&layers); |
| 341 | // Flush before adding a tile that would push a non-empty group past the budget, so a heavy |
| 342 | // tile does not drag its cheap predecessors into an oversized task. |
| 343 | if !current.is_empty() && current_cost + cost > target { |
| 344 | groups.push(std::mem::take(&mut current)); |
| 345 | current_cost = 0; |
| 346 | } |
| 347 | current.push((id, layers)); |
| 348 | current_cost += cost; |
| 349 | // A group at or over budget is closed; a single tile heavier than the budget closes here on |
| 350 | // its own, which is the isolation `with_min_len`'s fixed run length could not provide. |
| 351 | if current_cost >= target { |
| 352 | groups.push(std::mem::take(&mut current)); |
| 353 | current_cost = 0; |
| 354 | } |
| 355 | } |
| 356 | if !current.is_empty() { |
| 357 | groups.push(current); |
| 358 | } |
| 359 | groups |
| 360 | } |
| 361 | |
| 362 | /// A tile's encode cost: its features plus its coordinates, summed across layers. Both stage C and |
| 363 | /// the compressor scale with these, and it is the ratio between tiles that matters, not the unit. |
| 364 | fn tile_cost(layers: &[ChunkEntry]) -> u64 { |
| 365 | layers |
| 366 | .iter() |
| 367 | .map(|entry| entry.layer.features.len() as u64 + entry.layer.coords.len() as u64) |
| 368 | .sum() |
| 369 | } |