Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / schema / traffic.rs
traffic.rs563 lines · 23.9 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 | use tile_build::geom::Geometry; |
| 39 | use tilecodec::mamaps::dict::{self, LAYER_TRAFFIC}; |
| 40 | |
| 41 | use super::Class; |
| 42 | use crate::store::Sink; |
| 43 | |
| 44 | /// The zoom the traffic overlay first surfaces at. |
| 45 | /// |
| 46 | /// Component lines are dense — roughly the whole drivable network as one line per edge — so a |
| 47 | /// traffic overlay only earns its bytes where a street network reads at all. z13 is the shallowest |
| 48 | /// zoom a city's arterials are legible; below it the overlay would be a red smear (and z12 alone |
| 49 | /// cost 0.38GB on the california build). Raise it to trim the archive further, lower it to show |
| 50 | /// motorway congestion sooner. The store packs `min_zoom` in five bits, so anything up to 31 is |
| 51 | /// representable. |
| 52 | pub const MIN_ZOOM: u8 = 13; |
| 53 | |
| 54 | /// Bits reserved for the component-segment index inside a packed component id. Shared on-disk/wire |
| 55 | /// contract with the server and the device — keep in sync with `graph.rs::COMPONENT_SEG_BITS` and |
| 56 | /// `analysis/traffic_id_contract.md` §1. |
| 57 | pub const COMPONENT_SEG_BITS: u32 = 16; |
| 58 | pub const COMPONENT_SEG_MASK: u64 = (1 << COMPONENT_SEG_BITS) - 1; |
| 59 | |
| 60 | /// `component_id = (big_edge_id << 16) | seg_index`. |
| 61 | #[inline] |
| 62 | pub fn pack_component_id(big_edge_id: u64, seg_index: u32) -> u64 { |
| 63 | debug_assert!(u64::from(seg_index) <= COMPONENT_SEG_MASK); |
| 64 | (big_edge_id << COMPONENT_SEG_BITS) | u64::from(seg_index) |
| 65 | } |
| 66 | |
| 67 | /// The inverse of [`pack_component_id`]. |
| 68 | #[inline] |
| 69 | pub fn unpack_component_id(component_id: u64) -> (u64, u32) { |
| 70 | (component_id >> COMPONENT_SEG_BITS, (component_id & COMPONENT_SEG_MASK) as u32) |
| 71 | } |
| 72 | |
| 73 | /// The class every traffic segment carries: layer `traffic`, no kind and no detail. |
| 74 | /// |
| 75 | /// No `kind`/`kind_detail`, because the layer is not drawn by the basemap style — it is filtered on |
| 76 | /// and recoloured by the renderer from a pushed id→speed table, keyed on the `component_id` in the |
| 77 | /// body's id side table rather than on any interned attribute. Keeping it out of [`dict::KINDS`] |
| 78 | /// avoids disturbing the frozen kind table for a value nothing matches by name. |
| 79 | pub fn traffic_class() -> Class { |
| 80 | Class { |
| 81 | layer: LAYER_TRAFFIC, |
| 82 | kind: dict::NONE, |
| 83 | kind_detail: dict::NONE, |
| 84 | flags: 0, |
| 85 | area: false, |
| 86 | min_zoom: MIN_ZOOM, |
| 87 | min_area_px: 0.0, |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | // --- v6/v7 graph on-disk constants (see traffic_id_contract.md §2 / graph.rs) ----------------- |
| 92 | |
| 93 | pub(crate) const MARG_MAGIC: u32 = 0x4752_414D; // "MARG" |
| 94 | /// Newest graph version: v7 blocked record sections. |
| 95 | pub(crate) const GRAPH_VERSION: u32 = 7; |
| 96 | /// Oldest graph version accepted: v6 raw tables still read directly. |
| 97 | pub(crate) const GRAPH_VERSION_MIN: u32 = 6; |
| 98 | /// One escape block index per 1024 edges (`graph.rs` ESCAPE_BLOCK). |
| 99 | pub(crate) const ESCAPE_BLOCK: u64 = 1024; |
| 100 | /// One coarse geometry offset per 32 geometry edges (`graph.rs` INTERMEDIATE_BLOCK). |
| 101 | pub(crate) const INTERMEDIATE_BLOCK: u64 = 32; |
| 102 | /// One rank word per 512 edges = 64 present bytes (`graph.rs` RANK_BLOCK_BYTES). |
| 103 | const RANK_BLOCK_BYTES: usize = 64; |
| 104 | /// `type_` bit 6: this edge stores no geometry of its own; its twin runs `target -> source`. |
| 105 | const REVERSE_GEOMETRY_FLAG: u8 = 0x40; |
| 106 | /// The low six bits of `type_` are the road class. |
| 107 | pub(crate) const ROAD_TYPE_MASK: u8 = 0x3F; |
| 108 | /// A `target_delta` of `i16::MIN` means the true target is in the escape table. |
| 109 | const TARGET_DELTA_ESCAPE: i16 = i16::MIN; |
| 110 | /// A `dist` u24 of all-ones means the true target and distance are in the escape table. |
| 111 | const DIST_MM_ESCAPE: u32 = 0x00FF_FFFF; |
| 112 | /// The most vertices a big edge's polyline holds (`geom.rs` MAX_POINTS); the reader stops here. |
| 113 | const MAX_POINTS: usize = 256; |
| 114 | |
| 115 | fn u16_at(buf: &[u8], at: usize) -> u16 { |
| 116 | u16::from_le_bytes([buf[at], buf[at + 1]]) |
| 117 | } |
| 118 | fn i16_at(buf: &[u8], at: usize) -> i16 { |
| 119 | i16::from_le_bytes([buf[at], buf[at + 1]]) |
| 120 | } |
| 121 | fn u32_at(buf: &[u8], at: usize) -> u32 { |
| 122 | u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) |
| 123 | } |
| 124 | fn i32_at(buf: &[u8], at: usize) -> i32 { |
| 125 | i32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) |
| 126 | } |
| 127 | fn u64_at(buf: &[u8], at: usize) -> u64 { |
| 128 | u64::from_le_bytes([ |
| 129 | buf[at], |
| 130 | buf[at + 1], |
| 131 | buf[at + 2], |
| 132 | buf[at + 3], |
| 133 | buf[at + 4], |
| 134 | buf[at + 5], |
| 135 | buf[at + 6], |
| 136 | buf[at + 7], |
| 137 | ]) |
| 138 | } |
| 139 | |
| 140 | fn align_up8(n: usize) -> usize { |
| 141 | (n + 7) & !7 |
| 142 | } |
| 143 | |
| 144 | /// Inflate every block of a validated section and concatenate. |
| 145 | /// |
| 146 | /// Batch-tool path (traffic/junction stream whole tables), so one pass beats |
| 147 | /// per-block caching. The device inflates lazily instead — see |
| 148 | /// `maps/.../graph_part1.rs::BlockedView`. |
| 149 | fn inflate_all(view: &tilecodec::blocked::Blocked) -> Result<Vec<u8>> { |
| 150 | let mut cache = tilecodec::blocked::BlockCache::new(0); |
| 151 | let mut out = Vec::with_capacity(view.unpacked_len() as usize); |
| 152 | for b in 0..view.block_count() { |
| 153 | let block = cache |
| 154 | .get(view, b) |
| 155 | .map_err(|e| osm_ingest::proto::Error(e.0))?; |
| 156 | out.extend_from_slice(block); |
| 157 | } |
| 158 | if out.len() as u64 != view.unpacked_len() { |
| 159 | return err("a blocked section inflated short of its unpacked length".to_string()); |
| 160 | } |
| 161 | Ok(out) |
| 162 | } |
| 163 | |
| 164 | /// Bytes an [`EdgeBitmap`] over `edges` edges occupies: a `u64` rank word per 512 edges plus one |
| 165 | /// present byte per 8 edges (`graph.rs` `EdgeBitmap`). |
| 166 | fn present_offset(edges: u64) -> usize { |
| 167 | ((edges.div_ceil(512) + 1) * 8) as usize |
| 168 | } |
| 169 | fn edge_bitmap_bytes(edges: u64) -> usize { |
| 170 | present_offset(edges) + edges.div_ceil(8) as usize |
| 171 | } |
| 172 | |
| 173 | /// The subset of the v6/v7 graph reader the traffic layer needs: node coordinates, |
| 174 | /// edge targets and types, and big-edge geometry. Names, distances and speed |
| 175 | /// limits are skipped — the server reads those; the archive carries only |
| 176 | /// geometry and the id. |
| 177 | /// |
| 178 | /// The three tables are file mappings rather than heap `Vec`s: a planet graph is gigabytes, and |
| 179 | /// `Graph::load` runs while the OSM tables are still alive, so reading them whole would stack that |
| 180 | /// many gigabytes of commit on top of the peak. Mapped, the OS pages the working set (junction |
| 181 | /// walks nodes in order) and no commit is charged. Same bytes, same layout, same readers. |
| 182 | /// |
| 183 | /// Under v7 the record arrays are ZBLK sections, inflated eagerly at load |
| 184 | /// into `nodes_owned`/`rec_owned` (a batch tool, unlike the device's lazy |
| 185 | /// sections — the whole graph is walked anyway). The escapes, names and |
| 186 | /// intermediate tables stay mapped in both versions. |
| 187 | /// |
| 188 | /// `pub(crate)` because [`crate::schema::junction`] reads the same four files for the same reason |
| 189 | /// and must not carry a second copy of this byte layout. |
| 190 | pub(crate) struct Graph { |
| 191 | nodes: osm_ingest::mem::Mapped, |
| 192 | edges: osm_ingest::mem::Mapped, |
| 193 | inter: osm_ingest::mem::Mapped, |
| 194 | /// Inflated v7 nodes table. Empty on the v6 path, where `nodes` serves. |
| 195 | nodes_owned: Vec<u8>, |
| 196 | /// Inflated v7 edge-record array. Empty on the v6 path, where the head of |
| 197 | /// `edges` serves. Escapes/names always read from `edges` at computed offsets. |
| 198 | rec_owned: Vec<u8>, |
| 199 | pub(crate) node_count: u64, |
| 200 | escape_first_off: usize, |
| 201 | escapes_off: usize, |
| 202 | // intermediate.bin sub-table offsets |
| 203 | geom_rank_off: usize, |
| 204 | geom_present_off: usize, |
| 205 | coarse_off: usize, |
| 206 | within_off: usize, |
| 207 | } |
| 208 | |
| 209 | impl Graph { |
| 210 | /// Node records: mapped on v6, inflated on v7. |
| 211 | fn nb(&self) -> &[u8] { |
| 212 | if self.nodes_owned.is_empty() { |
| 213 | &self.nodes |
| 214 | } else { |
| 215 | &self.nodes_owned |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | /// Edge records: mapped head on v6, inflated on v7. |
| 220 | fn rb(&self) -> &[u8] { |
| 221 | if self.rec_owned.is_empty() { |
| 222 | &self.edges |
| 223 | } else { |
| 224 | &self.rec_owned |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | impl Graph { |
| 230 | pub(crate) fn load(dir: &Path) -> Result<Graph> { |
| 231 | let meta = std::fs::read(dir.join("metadata.bin")).map_err(|e| { |
| 232 | osm_ingest::proto::Error(format!( |
| 233 | "cannot read {}: {e}", |
| 234 | dir.join("metadata.bin").display() |
| 235 | )) |
| 236 | })?; |
| 237 | if meta.len() < 40 { |
| 238 | return err(format!("metadata.bin is {} bytes, a v6 MARG header is 40", meta.len())); |
| 239 | } |
| 240 | if u32_at(&meta, 0) != MARG_MAGIC { |
| 241 | return err("metadata.bin is not a MARG graph header".to_string()); |
| 242 | } |
| 243 | let version = u32_at(&meta, 4); |
| 244 | if !(GRAPH_VERSION_MIN..=GRAPH_VERSION).contains(&version) { |
| 245 | return err(format!( |
| 246 | "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION_MIN}..=v{GRAPH_VERSION}" |
| 247 | )); |
| 248 | } |
| 249 | let blocked_v7 = version >= GRAPH_VERSION; |
| 250 | let node_count = u64_at(&meta, 8); |
| 251 | let edge_count = u64_at(&meta, 16); |
| 252 | let escape_count = u64_at(&meta, 24); |
| 253 | if edge_count > u32::MAX as u64 { |
| 254 | return err(format!("edge_count {edge_count} does not fit u32")); |
| 255 | } |
| 256 | if escape_count > edge_count { |
| 257 | return err(format!( |
| 258 | "escape_count {escape_count} exceeds edge_count {edge_count}" |
| 259 | )); |
| 260 | } |
| 261 | |
| 262 | // The three tables open concurrently: three page-cache faults on |
| 263 | // three files, no dependency between them. Metadata validation above |
| 264 | // stays serial — it sizes everything below. Small win, almost free. |
| 265 | let (nodes, edges, inter) = std::thread::scope(|scope| { |
| 266 | let open = |name: &'static str| { |
| 267 | scope.spawn(move || { |
| 268 | osm_ingest::mem::Mapped::open(&dir.join(name)) |
| 269 | .map_err(osm_ingest::proto::Error) |
| 270 | }) |
| 271 | }; |
| 272 | let (a, b, c) = (open("nodes.bin"), open("edges.bin"), open("intermediate.bin")); |
| 273 | let nodes = a.join().expect("the nodes.bin opener"); |
| 274 | let edges = b.join().expect("the edges.bin opener"); |
| 275 | let inter = c.join().expect("the intermediate.bin opener"); |
| 276 | nodes.and_then(|nodes| edges.map(|edges| (nodes, edges))).and_then( |
| 277 | |(nodes, edges)| inter.map(|inter| (nodes, edges, inter)), |
| 278 | ) |
| 279 | })?; |
| 280 | let want_nodes = (node_count + 1) |
| 281 | .checked_mul(12) |
| 282 | .ok_or_else(|| osm_ingest::proto::Error("node table size overflows".to_string()))?; |
| 283 | // v7 nodes are a ZBLK section: parse, check the unpacked length, and |
| 284 | // inflate eagerly (batch tool — the whole table is walked). |
| 285 | let nodes_owned = if blocked_v7 { |
| 286 | let view = tilecodec::blocked::Blocked::parse(&nodes).map_err(|e| { |
| 287 | osm_ingest::proto::Error(format!("nodes.bin is not a blocked section: {e}")) |
| 288 | })?; |
| 289 | if view.unpacked_len() != want_nodes || view.record_len() != 12 { |
| 290 | return err(format!( |
| 291 | "nodes.bin unpacks to {} byte(s), expected {want_nodes}", |
| 292 | view.unpacked_len() |
| 293 | )); |
| 294 | } |
| 295 | inflate_all(&view)? |
| 296 | } else { |
| 297 | if nodes.len() as u64 != want_nodes { |
| 298 | return err(format!( |
| 299 | "nodes.bin is {} bytes, expected {} for {node_count}+1 records", |
| 300 | nodes.len(), |
| 301 | want_nodes, |
| 302 | )); |
| 303 | } |
| 304 | Vec::new() |
| 305 | }; |
| 306 | |
| 307 | // v7 edge records are a ZBLK section at the file head; escapes and |
| 308 | // names follow it exactly as before. The records' end comes from the |
| 309 | // section, not from `edge_count * 7`. |
| 310 | let (escape_first_off, rec_owned) = if blocked_v7 { |
| 311 | let view = tilecodec::blocked::Blocked::parse(&edges).map_err(|e| { |
| 312 | osm_ingest::proto::Error(format!("edges.bin is not a blocked section: {e}")) |
| 313 | })?; |
| 314 | if view.unpacked_len() != edge_count * 7 || view.record_len() != 7 { |
| 315 | return err(format!( |
| 316 | "edges.bin unpacks to {} byte(s), expected {} 7-byte records", |
| 317 | view.unpacked_len(), |
| 318 | edge_count |
| 319 | )); |
| 320 | } |
| 321 | let rec_end = view.block_offset(view.block_count()).ok_or_else(|| { |
| 322 | osm_ingest::proto::Error("edges.bin block table has no end".to_string()) |
| 323 | })? as usize; |
| 324 | (align_up8(rec_end), inflate_all(&view)?) |
| 325 | } else { |
| 326 | (align_up8((edge_count as usize) * 7), Vec::new()) |
| 327 | }; |
| 328 | let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1; |
| 329 | let escapes_off = escape_first_off + (escape_blocks as usize) * 4; |
| 330 | let want_edges_min = escapes_off + (escape_count as usize) * 12; |
| 331 | if edges.len() < want_edges_min { |
| 332 | return err(format!( |
| 333 | "edges.bin is {} bytes, too short for {edge_count} edges and {escape_count} escapes", |
| 334 | edges.len(), |
| 335 | )); |
| 336 | } |
| 337 | |
| 338 | if inter.len() < 8 { |
| 339 | return err("intermediate.bin is too short to hold its geometry-edge count".to_string()); |
| 340 | } |
| 341 | let g_edges = u64_at(&inter, inter.len() - 8); |
| 342 | if g_edges > edge_count { |
| 343 | return err(format!( |
| 344 | "intermediate.bin claims {g_edges} geometry edges, past the {edge_count} in the graph" |
| 345 | )); |
| 346 | } |
| 347 | let bitmap_bytes = edge_bitmap_bytes(edge_count); |
| 348 | let coarse_bytes = ((g_edges.div_ceil(INTERMEDIATE_BLOCK) + 1) * 8) as usize; |
| 349 | let within_bytes = ((g_edges + 1) * 2) as usize; |
| 350 | let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8; |
| 351 | if inter.len() < trailer { |
| 352 | return err(format!( |
| 353 | "intermediate.bin is {} bytes, too short for its {trailer}-byte trailer", |
| 354 | inter.len(), |
| 355 | )); |
| 356 | } |
| 357 | let blob_bytes = inter.len() - trailer; |
| 358 | let geom_rank_off = blob_bytes; |
| 359 | let geom_present_off = blob_bytes + present_offset(edge_count); |
| 360 | let coarse_off = blob_bytes + bitmap_bytes; |
| 361 | let within_off = coarse_off + coarse_bytes; |
| 362 | |
| 363 | Ok(Graph { |
| 364 | nodes, |
| 365 | edges, |
| 366 | inter, |
| 367 | nodes_owned, |
| 368 | rec_owned, |
| 369 | node_count, |
| 370 | escape_first_off, |
| 371 | escapes_off, |
| 372 | geom_rank_off, |
| 373 | geom_present_off, |
| 374 | coarse_off, |
| 375 | within_off, |
| 376 | }) |
| 377 | } |
| 378 | |
| 379 | /// A node's `(lat_e7, lon_e7)`. |
| 380 | pub(crate) fn node(&self, n: u64) -> (i32, i32) { |
| 381 | let base = (n as usize) * 12; |
| 382 | (i32_at(self.nb(), base), i32_at(self.nb(), base + 4)) |
| 383 | } |
| 384 | |
| 385 | /// A node's first outgoing edge index. The sentinel record (index `node_count`) holds |
| 386 | /// `edge_count`, so `edge_ptr(n+1)` is always defined for a real node `n`. |
| 387 | pub(crate) fn edge_ptr(&self, n: u64) -> u32 { |
| 388 | u32_at(self.nb(), (n as usize) * 12 + 8) |
| 389 | } |
| 390 | |
| 391 | pub(crate) fn edge_type(&self, idx: u32) -> u8 { |
| 392 | self.rb()[(idx as usize) * 7 + 5] |
| 393 | } |
| 394 | |
| 395 | /// The target node of edge `idx` whose source is `s`, decoding the escape table when the |
| 396 | /// delta or distance is sentinelled. |
| 397 | pub(crate) fn edge_target(&self, idx: u32, s: u32) -> Result<u32> { |
| 398 | let base = (idx as usize) * 7; |
| 399 | let rb = self.rb(); |
| 400 | let delta = i16_at(rb, base); |
| 401 | let dist = (rb[base + 2] as u32) |
| 402 | | ((rb[base + 3] as u32) << 8) |
| 403 | | ((rb[base + 4] as u32) << 16); |
| 404 | if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE { |
| 405 | self.escape_target(idx) |
| 406 | } else { |
| 407 | Ok(s.wrapping_add_signed(delta as i32)) |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | fn escape_target(&self, idx: u32) -> Result<u32> { |
| 412 | let block = (idx as u64 / ESCAPE_BLOCK) as usize; |
| 413 | let lo = u32_at(&self.edges, self.escape_first_off + block * 4); |
| 414 | let hi = u32_at(&self.edges, self.escape_first_off + (block + 1) * 4); |
| 415 | for r in lo..hi { |
| 416 | let rb = self.escapes_off + (r as usize) * 12; |
| 417 | if u32_at(&self.edges, rb) == idx { |
| 418 | return Ok(u32_at(&self.edges, rb + 4)); |
| 419 | } |
| 420 | } |
| 421 | err(format!("edge {idx} is escaped but has no escape row")) |
| 422 | } |
| 423 | |
| 424 | /// Does edge `idx` store an interior-point blob? |
| 425 | pub(crate) fn geom_contains(&self, idx: u32) -> bool { |
| 426 | let byte = self.geom_present_off + (idx as usize) / 8; |
| 427 | self.inter[byte] & (1u8 << (idx % 8)) != 0 |
| 428 | } |
| 429 | |
| 430 | /// The rank of edge `idx` among the geometry-carrying edges: the number of set bits strictly |
| 431 | /// below it in the presence bitmap. |
| 432 | fn geom_rank(&self, idx: u32) -> u64 { |
| 433 | let byte = (idx as usize) / 8; |
| 434 | let block = byte / RANK_BLOCK_BYTES; |
| 435 | let mut n = u64_at(&self.inter, self.geom_rank_off + block * 8); |
| 436 | for b in (block * RANK_BLOCK_BYTES)..byte { |
| 437 | n += self.inter[self.geom_present_off + b].count_ones() as u64; |
| 438 | } |
| 439 | let mask = ((1u16 << (idx % 8)) - 1) as u8; |
| 440 | n += (self.inter[self.geom_present_off + byte] & mask).count_ones() as u64; |
| 441 | n |
| 442 | } |
| 443 | |
| 444 | /// The blob byte offset of the `g`th geometry edge: `coarse[g/32] + within[g]`. |
| 445 | fn geom_offset(&self, g: u64) -> u64 { |
| 446 | let coarse = u64_at(&self.inter, self.coarse_off + (g / INTERMEDIATE_BLOCK) as usize * 8); |
| 447 | let within = u16_at(&self.inter, self.within_off + (g as usize) * 2) as u64; |
| 448 | coarse + within |
| 449 | } |
| 450 | |
| 451 | /// The `(start, end)` byte range of edge `idx`'s interior-point blob, or `None` when it stores |
| 452 | /// no geometry (a straight chord). |
| 453 | fn intermediate_range(&self, idx: u32) -> Option<(usize, usize)> { |
| 454 | if !self.geom_contains(idx) { |
| 455 | return None; |
| 456 | } |
| 457 | let g = self.geom_rank(idx); |
| 458 | Some((self.geom_offset(g) as usize, self.geom_offset(g + 1) as usize)) |
| 459 | } |
| 460 | |
| 461 | /// The full polyline of edge `idx` in canonical `source -> target` order, as `(lat_e7, lon_e7)` |
| 462 | /// vertices: the source node, any stored interior points, then the target node. |
| 463 | pub(crate) fn polyline(&self, idx: u32, s: u32, t: u32) -> Vec<(i32, i32)> { |
| 464 | let (slat, slon) = self.node(s as u64); |
| 465 | let (tlat, tlon) = self.node(t as u64); |
| 466 | let mut out = Vec::with_capacity(4); |
| 467 | out.push((slat, slon)); |
| 468 | if let Some((start, end)) = self.intermediate_range(idx) { |
| 469 | let (mut lat, mut lon) = (slat, slon); |
| 470 | let mut off = start; |
| 471 | // count starts at 1 for the source; the reader stops at MAX_POINTS total, matching |
| 472 | // `graph.rs::decode_edge_coords`. |
| 473 | let mut count = 1usize; |
| 474 | while off + 4 <= end && count + 1 < MAX_POINTS { |
| 475 | let d_lat = i16_at(&self.inter, off) as i32; |
| 476 | let d_lon = i16_at(&self.inter, off + 2) as i32; |
| 477 | lat = lat.wrapping_add(d_lat); |
| 478 | lon = lon.wrapping_add(d_lon); |
| 479 | out.push((lat, lon)); |
| 480 | count += 1; |
| 481 | off += 4; |
| 482 | } |
| 483 | } |
| 484 | out.push((tlat, tlon)); |
| 485 | out |
| 486 | } |
| 487 | |
| 488 | /// Is there a drivable edge running `from -> to`? Used to tell a straight two-way chord (which |
| 489 | /// has such a twin and is emitted only in the canonical direction) from a one-way (which has |
| 490 | /// none and is always emitted). |
| 491 | pub(crate) fn has_drivable_twin(&self, from: u32, to: u32) -> Result<bool> { |
| 492 | let lo = self.edge_ptr(from as u64); |
| 493 | let hi = self.edge_ptr(from as u64 + 1); |
| 494 | for e in lo..hi { |
| 495 | let rc = self.edge_type(e) & ROAD_TYPE_MASK; |
| 496 | if (1..=9).contains(&rc) && self.edge_target(e, from)? == to { |
| 497 | return Ok(true); |
| 498 | } |
| 499 | } |
| 500 | Ok(false) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | /// Read the v6 graph at `dir` and push one line feature per drivable component segment into `sink`, |
| 505 | /// each carrying its packed `component_id`. Returns the number of segments emitted. |
| 506 | /// |
| 507 | /// Modelled on [`crate::schema::landtype::stream_prepared`] and |
| 508 | /// [`crate::schema::transit::stream_routes`]: a source of geometry outside the `.osm.pbf`, read |
| 509 | /// after the OSM passes and streamed straight into the feature sink. Unlike those two it is not |
| 510 | /// clipped to a bbox here — the graph is already the built region, and the tiler clips each segment |
| 511 | /// per tile like any other line. |
| 512 | pub fn stream_graph(dir: &Path, sink: &mut Sink) -> Result<u64> { |
| 513 | let graph = Graph::load(dir)?; |
| 514 | let class = traffic_class(); |
| 515 | let mut emitted = 0u64; |
| 516 | for n in 0..graph.node_count { |
| 517 | let s = n as u32; |
| 518 | let lo = graph.edge_ptr(n); |
| 519 | let hi = graph.edge_ptr(n + 1); |
| 520 | for idx in lo..hi { |
| 521 | let ty = graph.edge_type(idx); |
| 522 | // Step 1: the reverse twin of a curved two-way owns no geometry; its forward twin does. |
| 523 | if ty & REVERSE_GEOMETRY_FLAG != 0 { |
| 524 | continue; |
| 525 | } |
| 526 | // A driving overlay: motorway..living_street only. |
| 527 | let rc = ty & ROAD_TYPE_MASK; |
| 528 | if !(1..=9).contains(&rc) { |
| 529 | continue; |
| 530 | } |
| 531 | let target = graph.edge_target(idx, s)?; |
| 532 | if target as u64 >= graph.node_count { |
| 533 | return err(format!( |
| 534 | "edge {idx} targets node {target}, past the {} in the graph", |
| 535 | graph.node_count, |
| 536 | )); |
| 537 | } |
| 538 | // Step 2: a straight two-way chord is emitted only in the canonical direction; a |
| 539 | // one-way (no drivable twin back) is always emitted. |
| 540 | if !graph.geom_contains(idx) && graph.has_drivable_twin(target, s)? && s >= target { |
| 541 | continue; |
| 542 | } |
| 543 | let verts = graph.polyline(idx, s, target); |
| 544 | for seg in 0..verts.len().saturating_sub(1) { |
| 545 | let (a_lat, a_lon) = verts[seg]; |
| 546 | let (b_lat, b_lon) = verts[seg + 1]; |
| 547 | // A zero-length segment draws nothing and would only cost a feature and an id. |
| 548 | if a_lat == b_lat && a_lon == b_lon { |
| 549 | continue; |
| 550 | } |
| 551 | let component_id = pack_component_id(idx as u64, seg as u32); |
| 552 | let line = vec![vec![ |
| 553 | (a_lon as f64 * 1e-7, a_lat as f64 * 1e-7), |
| 554 | (b_lon as f64 * 1e-7, b_lat as f64 * 1e-7), |
| 555 | ]]; |
| 556 | sink.push_named(&class, &crate::store::EncodedGeom::live(&Geometry::Lines(line))?, None, component_id)?; |
| 557 | emitted += 1; |
| 558 | } |
| 559 | } |
| 560 | } |
| 561 | Ok(emitted) |
| 562 | } |
| 563 |