Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / traffic.rs
traffic.rs263 lines · 11.1 KiBRaw
| 1 | //! `traffic`: one line per drivable **component** segment of the v6 routing graph. |
| 2 | //! |
| 3 | //! The one layer whose geometry is not in the `.osm.pbf` and not in a prepared product either: it |
| 4 | //! is read straight from the app's v6 routing graph — `metadata.bin`, `nodes.bin`, `edges.bin` and |
| 5 | //! `intermediate.bin`, produced by `scripts/maps/osm_ingest`'s `road_graph`. Building from the |
| 6 | //! graph is what makes every feature's `component_id` match, byte for byte and with no coordination |
| 7 | //! file, the ids the traffic server computes from the same graph. The authoritative spec is |
| 8 | //! `analysis/traffic_id_contract.md`; the reader below mirrors `maps/src/main/rust/src/graph.rs`. |
| 9 | //! |
| 10 | //! # What one feature is |
| 11 | //! |
| 12 | //! A big edge's polyline is `source_node -> interior points -> target_node`. A **component** |
| 13 | //! segment is one consecutive vertex pair of that polyline, and each becomes one `GEOM_LINE` |
| 14 | //! feature carrying `component_id = (big_edge_id << 16) | seg_index` in the body's id side table. |
| 15 | //! The tiler does not coalesce this layer, so its features stay one-to-one with those ids. |
| 16 | //! |
| 17 | //! # Emit-each-segment-once (dedup), verbatim from the contract §3 |
| 18 | //! |
| 19 | //! A two-way road is two directed edges over the same ground. To draw it once — and, more |
| 20 | //! importantly, so the archive and the server pick the **same** directed `big_edge_id` for a |
| 21 | //! physical segment — this canonicalises identically to WS1: |
| 22 | //! |
| 23 | //! 1. Skip any edge with `REVERSE_GEOMETRY_FLAG` (`0x40`): it is the reverse twin of a *curved* |
| 24 | //! two-way road and stores no geometry of its own; its non-flag twin owns the shape. |
| 25 | //! 2. A straight two-way chord stores no blob and the flag is set on neither direction, so step 1 |
| 26 | //! alone would emit both. For an edge with no stored geometry that has a drivable twin, emit |
| 27 | //! only the canonical direction (`source_idx < target_idx`). A genuine one-way has no twin, so |
| 28 | //! it is emitted regardless. |
| 29 | //! |
| 30 | //! # Drivable |
| 31 | //! |
| 32 | //! An edge is drivable iff `(type_ & 0x3F)` is in `1..=9` (motorway..living_street). The road-class |
| 33 | //! bits are masked before the range test so the reverse-geometry flag never trips it. |
| 34 | |
| 35 | use std::path::Path; |
| 36 | |
| 37 | use osm_ingest::proto::{err, Result}; |
| 38 | #[cfg(test)] |
| 39 | use tile_build::geom::Geometry; |
| 40 | #[cfg(test)] |
| 41 | use tilecodec::mamaps::dict::{self, LAYER_TRAFFIC}; |
| 42 | |
| 43 | #[cfg(test)] |
| 44 | use super::Class; |
| 45 | #[cfg(test)] |
| 46 | use crate::store::Sink; |
| 47 | |
| 48 | /// The zoom the traffic overlay first surfaces at. |
| 49 | /// |
| 50 | /// Component lines are dense — roughly the whole drivable network as one line per edge — so a |
| 51 | /// traffic overlay only earns its bytes where a street network reads at all. z13 is the shallowest |
| 52 | /// zoom a city's arterials are legible; below it the overlay would be a red smear (and z12 alone |
| 53 | /// cost 0.38GB on the california build). Raise it to trim the archive further, lower it to show |
| 54 | /// motorway congestion sooner. The store packs `min_zoom` in five bits, so anything up to 31 is |
| 55 | /// representable. |
| 56 | #[cfg(test)] |
| 57 | pub const MIN_ZOOM: u8 = 13; |
| 58 | |
| 59 | /// Bits reserved for the component-segment index inside a packed component id. Shared on-disk/wire |
| 60 | /// contract with the server and the device — keep in sync with `graph.rs::COMPONENT_SEG_BITS` and |
| 61 | /// `analysis/traffic_id_contract.md` §1. |
| 62 | #[cfg(test)] |
| 63 | pub const COMPONENT_SEG_BITS: u32 = 16; |
| 64 | #[cfg(test)] |
| 65 | pub const COMPONENT_SEG_MASK: u64 = (1 << COMPONENT_SEG_BITS) - 1; |
| 66 | |
| 67 | /// `component_id = (big_edge_id << 16) | seg_index`. |
| 68 | #[inline] |
| 69 | #[cfg(test)] |
| 70 | pub fn pack_component_id(big_edge_id: u64, seg_index: u32) -> u64 { |
| 71 | debug_assert!(u64::from(seg_index) <= COMPONENT_SEG_MASK); |
| 72 | (big_edge_id << COMPONENT_SEG_BITS) | u64::from(seg_index) |
| 73 | } |
| 74 | |
| 75 | /// The inverse of [`pack_component_id`]. |
| 76 | #[inline] |
| 77 | #[cfg(test)] |
| 78 | pub fn unpack_component_id(component_id: u64) -> (u64, u32) { |
| 79 | (component_id >> COMPONENT_SEG_BITS, (component_id & COMPONENT_SEG_MASK) as u32) |
| 80 | } |
| 81 | |
| 82 | /// The class every traffic segment carries: layer `traffic`, no kind and no detail. |
| 83 | /// |
| 84 | /// No `kind`/`kind_detail`, because the layer is not drawn by the basemap style — it is filtered on |
| 85 | /// and recoloured by the renderer from a pushed id→speed table, keyed on the `component_id` in the |
| 86 | /// body's id side table rather than on any interned attribute. Keeping it out of [`dict::KINDS`] |
| 87 | /// avoids disturbing the frozen kind table for a value nothing matches by name. |
| 88 | #[cfg(test)] |
| 89 | pub fn traffic_class() -> Class { |
| 90 | Class { |
| 91 | layer: LAYER_TRAFFIC, |
| 92 | kind: dict::NONE, |
| 93 | kind_detail: dict::NONE, |
| 94 | flags: 0, |
| 95 | area: false, |
| 96 | min_zoom: MIN_ZOOM, |
| 97 | min_area_px: 0.0, |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // --- v6/v7 graph on-disk constants (see traffic_id_contract.md §2 / graph.rs) ----------------- |
| 102 | |
| 103 | pub(crate) const MARG_MAGIC: u32 = 0x4752_414D; // "MARG" |
| 104 | /// First graph version with blocked record sections (v7). The build reads v7 straight out of |
| 105 | /// `road_graph`; v8/v9 (planet5's varint / zstd-block shape points, see [`GRAPH_VERSION_MAX`]) |
| 106 | /// load too, for the junction-reconstruction check. |
| 107 | pub(crate) const GRAPH_VERSION: u32 = 7; |
| 108 | /// Newest graph version read: v9. |
| 109 | pub(crate) const GRAPH_VERSION_MAX: u32 = 9; |
| 110 | /// v8+: 16 geometry edges per coarse intermediate entry (`graph.rs` INTERMEDIATE_BLOCK_V8). |
| 111 | const INTERMEDIATE_BLOCK_V8: u64 = 16; |
| 112 | /// Oldest graph version accepted: v6 raw tables still read directly. |
| 113 | pub(crate) const GRAPH_VERSION_MIN: u32 = 6; |
| 114 | /// One escape block index per 1024 edges (`graph.rs` ESCAPE_BLOCK). |
| 115 | pub(crate) const ESCAPE_BLOCK: u64 = 1024; |
| 116 | /// One coarse geometry offset per 32 geometry edges (`graph.rs` INTERMEDIATE_BLOCK). |
| 117 | pub(crate) const INTERMEDIATE_BLOCK: u64 = 32; |
| 118 | /// One rank word per 512 edges = 64 present bytes (`graph.rs` RANK_BLOCK_BYTES). |
| 119 | const RANK_BLOCK_BYTES: usize = 64; |
| 120 | /// `type_` bit 6: this edge stores no geometry of its own; its twin runs `target -> source`. |
| 121 | #[cfg(test)] |
| 122 | const REVERSE_GEOMETRY_FLAG: u8 = 0x40; |
| 123 | /// The low six bits of `type_` are the road class. |
| 124 | pub(crate) const ROAD_TYPE_MASK: u8 = 0x3F; |
| 125 | /// A `target_delta` of `i16::MIN` means the true target is in the escape table. |
| 126 | const TARGET_DELTA_ESCAPE: i16 = i16::MIN; |
| 127 | /// A `dist` u24 of all-ones means the true target and distance are in the escape table. |
| 128 | const DIST_MM_ESCAPE: u32 = 0x00FF_FFFF; |
| 129 | /// The most vertices a big edge's polyline holds (`geom.rs` MAX_POINTS); the reader stops here. |
| 130 | const MAX_POINTS: usize = 256; |
| 131 | |
| 132 | fn u16_at(buf: &[u8], at: usize) -> u16 { |
| 133 | u16::from_le_bytes([buf[at], buf[at + 1]]) |
| 134 | } |
| 135 | fn i16_at(buf: &[u8], at: usize) -> i16 { |
| 136 | i16::from_le_bytes([buf[at], buf[at + 1]]) |
| 137 | } |
| 138 | fn u32_at(buf: &[u8], at: usize) -> u32 { |
| 139 | u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) |
| 140 | } |
| 141 | fn i32_at(buf: &[u8], at: usize) -> i32 { |
| 142 | i32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) |
| 143 | } |
| 144 | fn u64_at(buf: &[u8], at: usize) -> u64 { |
| 145 | u64::from_le_bytes([ |
| 146 | buf[at], |
| 147 | buf[at + 1], |
| 148 | buf[at + 2], |
| 149 | buf[at + 3], |
| 150 | buf[at + 4], |
| 151 | buf[at + 5], |
| 152 | buf[at + 6], |
| 153 | buf[at + 7], |
| 154 | ]) |
| 155 | } |
| 156 | |
| 157 | fn align_up8(n: usize) -> usize { |
| 158 | (n + 7) & !7 |
| 159 | } |
| 160 | |
| 161 | /// Inflate every block of a validated section and concatenate. |
| 162 | /// |
| 163 | /// Batch-tool path (traffic/junction stream whole tables), so one pass beats |
| 164 | /// per-block caching. The device inflates lazily instead — see |
| 165 | /// `maps/.../graph_part1.rs::BlockedView`. |
| 166 | pub(crate) fn inflate_all(view: &tilecodec::blocked::Blocked) -> Result<Vec<u8>> { |
| 167 | // Blocks inflate independently (`Blocked::block` is `&self` and pure), so they go across the |
| 168 | // pool a group at a time and are appended in block order: the same bytes the one-block-at-a- |
| 169 | // time loop produced. On the planet graph this was ~13 GB of nodes + edge records inflated on |
| 170 | // one thread, the 1m40s at ~1.3 cores before the junction layer's first connector. |
| 171 | use rayon::prelude::*; |
| 172 | const GROUP: usize = 4096; |
| 173 | let mut out = Vec::with_capacity(view.unpacked_len() as usize); |
| 174 | let n = view.block_count(); |
| 175 | let mut start = 0usize; |
| 176 | while start < n { |
| 177 | let end = (start + GROUP).min(n); |
| 178 | let blocks: Vec<std::result::Result<Vec<u8>, _>> = tile_build::par::install(|| { |
| 179 | (start..end).into_par_iter().map(|b| view.block(b)).collect() |
| 180 | }); |
| 181 | for block in blocks { |
| 182 | out.extend_from_slice(&block.map_err(|e| osm_ingest::proto::Error(e.0))?); |
| 183 | } |
| 184 | start = end; |
| 185 | } |
| 186 | if out.len() as u64 != view.unpacked_len() { |
| 187 | return err("a blocked section inflated short of its unpacked length".to_string()); |
| 188 | } |
| 189 | Ok(out) |
| 190 | } |
| 191 | |
| 192 | /// Bytes an [`EdgeBitmap`] over `edges` edges occupies: a `u64` rank word per 512 edges plus one |
| 193 | /// present byte per 8 edges (`graph.rs` `EdgeBitmap`). |
| 194 | fn present_offset(edges: u64) -> usize { |
| 195 | ((edges.div_ceil(512) + 1) * 8) as usize |
| 196 | } |
| 197 | fn edge_bitmap_bytes(edges: u64) -> usize { |
| 198 | present_offset(edges) + edges.div_ceil(8) as usize |
| 199 | } |
| 200 | |
| 201 | /// The subset of the v6/v7 graph reader the traffic layer needs: node coordinates, |
| 202 | /// edge targets and types, and big-edge geometry. Names, distances and speed |
| 203 | /// limits are skipped — the server reads those; the archive carries only |
| 204 | /// geometry and the id. |
| 205 | /// |
| 206 | /// The three tables are file mappings rather than heap `Vec`s: a planet graph is gigabytes, and |
| 207 | /// `Graph::load` runs while the OSM tables are still alive, so reading them whole would stack that |
| 208 | /// many gigabytes of commit on top of the peak. Mapped, the OS pages the working set (junction |
| 209 | /// walks nodes in order) and no commit is charged. Same bytes, same layout, same readers. |
| 210 | /// |
| 211 | /// Under v7 the record arrays are ZBLK sections, inflated eagerly at load |
| 212 | /// into `nodes_owned`/`rec_owned` (a batch tool, unlike the device's lazy |
| 213 | /// sections — the whole graph is walked anyway). The escapes, names and |
| 214 | /// intermediate tables stay mapped in both versions. |
| 215 | /// |
| 216 | /// `pub(crate)` because [`crate::schema::junction`] reads the same four files for the same reason |
| 217 | /// and must not carry a second copy of this byte layout. |
| 218 | pub(crate) struct Graph { |
| 219 | nodes: osm_ingest::mem::Mapped, |
| 220 | edges: osm_ingest::mem::Mapped, |
| 221 | inter: osm_ingest::mem::Mapped, |
| 222 | /// Inflated v7 nodes table. Empty on the v6 path, where `nodes` serves. |
| 223 | nodes_owned: Vec<u8>, |
| 224 | /// Inflated v7 edge-record array. Empty on the v6 path, where the head of |
| 225 | /// `edges` serves. Escapes/names always read from `edges` at computed offsets. |
| 226 | rec_owned: Vec<u8>, |
| 227 | pub(crate) node_count: u64, |
| 228 | escape_first_off: usize, |
| 229 | escapes_off: usize, |
| 230 | // intermediate.bin sub-table offsets |
| 231 | geom_rank_off: usize, |
| 232 | geom_present_off: usize, |
| 233 | coarse_off: usize, |
| 234 | within_off: usize, |
| 235 | /// Geometry edges per coarse entry: 32 (v6/v7) or 16 (v8+). |
| 236 | inter_block: u64, |
| 237 | /// v8+: blobs are zigzag varint deltas on a 1e-6 degree grid. |
| 238 | varint_v8: bool, |
| 239 | /// v9: the inflated blob (the file holds a ZSEC section). Empty otherwise. |
| 240 | blob_owned: Vec<u8>, |
| 241 | } |
| 242 | |
| 243 | impl Graph { |
| 244 | /// Node records: mapped on v6, inflated on v7. |
| 245 | fn nb(&self) -> &[u8] { |
| 246 | if self.nodes_owned.is_empty() { |
| 247 | &self.nodes |
| 248 | } else { |
| 249 | &self.nodes_owned |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | /// Edge records: mapped head on v6, inflated on v7. |
| 254 | fn rb(&self) -> &[u8] { |
| 255 | if self.rec_owned.is_empty() { |
| 256 | &self.edges |
| 257 | } else { |
| 258 | &self.rec_owned |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | include!("traffic_s1.rs"); |