//! `traffic`: one line per drivable **component** segment of the v6 routing graph. //! //! The one layer whose geometry is not in the `.osm.pbf` and not in a prepared product either: it //! is read straight from the app's v6 routing graph — `metadata.bin`, `nodes.bin`, `edges.bin` and //! `intermediate.bin`, produced by `scripts/maps/osm_ingest`'s `road_graph`. Building from the //! graph is what makes every feature's `component_id` match, byte for byte and with no coordination //! file, the ids the traffic server computes from the same graph. The authoritative spec is //! `analysis/traffic_id_contract.md`; the reader below mirrors `maps/src/main/rust/src/graph.rs`. //! //! # What one feature is //! //! A big edge's polyline is `source_node -> interior points -> target_node`. A **component** //! segment is one consecutive vertex pair of that polyline, and each becomes one `GEOM_LINE` //! feature carrying `component_id = (big_edge_id << 16) | seg_index` in the body's id side table. //! The tiler does not coalesce this layer, so its features stay one-to-one with those ids. //! //! # Emit-each-segment-once (dedup), verbatim from the contract §3 //! //! A two-way road is two directed edges over the same ground. To draw it once — and, more //! importantly, so the archive and the server pick the **same** directed `big_edge_id` for a //! physical segment — this canonicalises identically to WS1: //! //! 1. Skip any edge with `REVERSE_GEOMETRY_FLAG` (`0x40`): it is the reverse twin of a *curved* //! two-way road and stores no geometry of its own; its non-flag twin owns the shape. //! 2. A straight two-way chord stores no blob and the flag is set on neither direction, so step 1 //! alone would emit both. For an edge with no stored geometry that has a drivable twin, emit //! only the canonical direction (`source_idx < target_idx`). A genuine one-way has no twin, so //! it is emitted regardless. //! //! # Drivable //! //! An edge is drivable iff `(type_ & 0x3F)` is in `1..=9` (motorway..living_street). The road-class //! bits are masked before the range test so the reverse-geometry flag never trips it. use std::path::Path; use osm_ingest::proto::{err, Result}; #[cfg(test)] use tile_build::geom::Geometry; #[cfg(test)] use tilecodec::mamaps::dict::{self, LAYER_TRAFFIC}; #[cfg(test)] use super::Class; #[cfg(test)] use crate::store::Sink; /// The zoom the traffic overlay first surfaces at. /// /// Component lines are dense — roughly the whole drivable network as one line per edge — so a /// traffic overlay only earns its bytes where a street network reads at all. z13 is the shallowest /// zoom a city's arterials are legible; below it the overlay would be a red smear (and z12 alone /// cost 0.38GB on the california build). Raise it to trim the archive further, lower it to show /// motorway congestion sooner. The store packs `min_zoom` in five bits, so anything up to 31 is /// representable. #[cfg(test)] pub const MIN_ZOOM: u8 = 13; /// Bits reserved for the component-segment index inside a packed component id. Shared on-disk/wire /// contract with the server and the device — keep in sync with `graph.rs::COMPONENT_SEG_BITS` and /// `analysis/traffic_id_contract.md` §1. #[cfg(test)] pub const COMPONENT_SEG_BITS: u32 = 16; #[cfg(test)] pub const COMPONENT_SEG_MASK: u64 = (1 << COMPONENT_SEG_BITS) - 1; /// `component_id = (big_edge_id << 16) | seg_index`. #[inline] #[cfg(test)] pub fn pack_component_id(big_edge_id: u64, seg_index: u32) -> u64 { debug_assert!(u64::from(seg_index) <= COMPONENT_SEG_MASK); (big_edge_id << COMPONENT_SEG_BITS) | u64::from(seg_index) } /// The inverse of [`pack_component_id`]. #[inline] #[cfg(test)] pub fn unpack_component_id(component_id: u64) -> (u64, u32) { (component_id >> COMPONENT_SEG_BITS, (component_id & COMPONENT_SEG_MASK) as u32) } /// The class every traffic segment carries: layer `traffic`, no kind and no detail. /// /// No `kind`/`kind_detail`, because the layer is not drawn by the basemap style — it is filtered on /// and recoloured by the renderer from a pushed id→speed table, keyed on the `component_id` in the /// body's id side table rather than on any interned attribute. Keeping it out of [`dict::KINDS`] /// avoids disturbing the frozen kind table for a value nothing matches by name. #[cfg(test)] pub fn traffic_class() -> Class { Class { layer: LAYER_TRAFFIC, kind: dict::NONE, kind_detail: dict::NONE, flags: 0, area: false, min_zoom: MIN_ZOOM, min_area_px: 0.0, } } // --- v6/v7 graph on-disk constants (see traffic_id_contract.md §2 / graph.rs) ----------------- pub(crate) const MARG_MAGIC: u32 = 0x4752_414D; // "MARG" /// First graph version with blocked record sections (v7). The build reads v7 straight out of /// `road_graph`; v8/v9 (planet5's varint / zstd-block shape points, see [`GRAPH_VERSION_MAX`]) /// load too, for the junction-reconstruction check. pub(crate) const GRAPH_VERSION: u32 = 7; /// Newest graph version read: v9. pub(crate) const GRAPH_VERSION_MAX: u32 = 9; /// v8+: 16 geometry edges per coarse intermediate entry (`graph.rs` INTERMEDIATE_BLOCK_V8). const INTERMEDIATE_BLOCK_V8: u64 = 16; /// Oldest graph version accepted: v6 raw tables still read directly. pub(crate) const GRAPH_VERSION_MIN: u32 = 6; /// One escape block index per 1024 edges (`graph.rs` ESCAPE_BLOCK). pub(crate) const ESCAPE_BLOCK: u64 = 1024; /// One coarse geometry offset per 32 geometry edges (`graph.rs` INTERMEDIATE_BLOCK). pub(crate) const INTERMEDIATE_BLOCK: u64 = 32; /// One rank word per 512 edges = 64 present bytes (`graph.rs` RANK_BLOCK_BYTES). const RANK_BLOCK_BYTES: usize = 64; /// `type_` bit 6: this edge stores no geometry of its own; its twin runs `target -> source`. #[cfg(test)] const REVERSE_GEOMETRY_FLAG: u8 = 0x40; /// The low six bits of `type_` are the road class. pub(crate) const ROAD_TYPE_MASK: u8 = 0x3F; /// A `target_delta` of `i16::MIN` means the true target is in the escape table. const TARGET_DELTA_ESCAPE: i16 = i16::MIN; /// A `dist` u24 of all-ones means the true target and distance are in the escape table. const DIST_MM_ESCAPE: u32 = 0x00FF_FFFF; /// The most vertices a big edge's polyline holds (`geom.rs` MAX_POINTS); the reader stops here. const MAX_POINTS: usize = 256; fn u16_at(buf: &[u8], at: usize) -> u16 { u16::from_le_bytes([buf[at], buf[at + 1]]) } fn i16_at(buf: &[u8], at: usize) -> i16 { i16::from_le_bytes([buf[at], buf[at + 1]]) } fn u32_at(buf: &[u8], at: usize) -> u32 { u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) } fn i32_at(buf: &[u8], at: usize) -> i32 { i32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) } fn u64_at(buf: &[u8], at: usize) -> u64 { u64::from_le_bytes([ buf[at], buf[at + 1], buf[at + 2], buf[at + 3], buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7], ]) } fn align_up8(n: usize) -> usize { (n + 7) & !7 } /// Inflate every block of a validated section and concatenate. /// /// Batch-tool path (traffic/junction stream whole tables), so one pass beats /// per-block caching. The device inflates lazily instead — see /// `maps/.../graph_part1.rs::BlockedView`. pub(crate) fn inflate_all(view: &tilecodec::blocked::Blocked) -> Result> { // Blocks inflate independently (`Blocked::block` is `&self` and pure), so they go across the // pool a group at a time and are appended in block order: the same bytes the one-block-at-a- // time loop produced. On the planet graph this was ~13 GB of nodes + edge records inflated on // one thread, the 1m40s at ~1.3 cores before the junction layer's first connector. use rayon::prelude::*; const GROUP: usize = 4096; let mut out = Vec::with_capacity(view.unpacked_len() as usize); let n = view.block_count(); let mut start = 0usize; while start < n { let end = (start + GROUP).min(n); let blocks: Vec, _>> = tile_build::par::install(|| { (start..end).into_par_iter().map(|b| view.block(b)).collect() }); for block in blocks { out.extend_from_slice(&block.map_err(|e| osm_ingest::proto::Error(e.0))?); } start = end; } if out.len() as u64 != view.unpacked_len() { return err("a blocked section inflated short of its unpacked length".to_string()); } Ok(out) } /// Bytes an [`EdgeBitmap`] over `edges` edges occupies: a `u64` rank word per 512 edges plus one /// present byte per 8 edges (`graph.rs` `EdgeBitmap`). fn present_offset(edges: u64) -> usize { ((edges.div_ceil(512) + 1) * 8) as usize } fn edge_bitmap_bytes(edges: u64) -> usize { present_offset(edges) + edges.div_ceil(8) as usize } /// The subset of the v6/v7 graph reader the traffic layer needs: node coordinates, /// edge targets and types, and big-edge geometry. Names, distances and speed /// limits are skipped — the server reads those; the archive carries only /// geometry and the id. /// /// The three tables are file mappings rather than heap `Vec`s: a planet graph is gigabytes, and /// `Graph::load` runs while the OSM tables are still alive, so reading them whole would stack that /// many gigabytes of commit on top of the peak. Mapped, the OS pages the working set (junction /// walks nodes in order) and no commit is charged. Same bytes, same layout, same readers. /// /// Under v7 the record arrays are ZBLK sections, inflated eagerly at load /// into `nodes_owned`/`rec_owned` (a batch tool, unlike the device's lazy /// sections — the whole graph is walked anyway). The escapes, names and /// intermediate tables stay mapped in both versions. /// /// `pub(crate)` because [`crate::schema::junction`] reads the same four files for the same reason /// and must not carry a second copy of this byte layout. pub(crate) struct Graph { nodes: osm_ingest::mem::Mapped, edges: osm_ingest::mem::Mapped, inter: osm_ingest::mem::Mapped, /// Inflated v7 nodes table. Empty on the v6 path, where `nodes` serves. nodes_owned: Vec, /// Inflated v7 edge-record array. Empty on the v6 path, where the head of /// `edges` serves. Escapes/names always read from `edges` at computed offsets. rec_owned: Vec, pub(crate) node_count: u64, escape_first_off: usize, escapes_off: usize, // intermediate.bin sub-table offsets geom_rank_off: usize, geom_present_off: usize, coarse_off: usize, within_off: usize, /// Geometry edges per coarse entry: 32 (v6/v7) or 16 (v8+). inter_block: u64, /// v8+: blobs are zigzag varint deltas on a 1e-6 degree grid. varint_v8: bool, /// v9: the inflated blob (the file holds a ZSEC section). Empty otherwise. blob_owned: Vec, } impl Graph { /// Node records: mapped on v6, inflated on v7. fn nb(&self) -> &[u8] { if self.nodes_owned.is_empty() { &self.nodes } else { &self.nodes_owned } } /// Edge records: mapped head on v6, inflated on v7. fn rb(&self) -> &[u8] { if self.rec_owned.is_empty() { &self.edges } else { &self.rec_owned } } } include!("traffic_s1.rs");