impl Graph { pub(crate) fn load(dir: &Path) -> Result { let meta = std::fs::read(dir.join("metadata.bin")).map_err(|e| { osm_ingest::proto::Error(format!( "cannot read {}: {e}", dir.join("metadata.bin").display() )) })?; if meta.len() < 40 { return err(format!("metadata.bin is {} bytes, a v6 MARG header is 40", meta.len())); } if u32_at(&meta, 0) != MARG_MAGIC { return err("metadata.bin is not a MARG graph header".to_string()); } let version = u32_at(&meta, 4); if !(GRAPH_VERSION_MIN..=GRAPH_VERSION_MAX).contains(&version) { return err(format!( "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION_MIN}..=v{GRAPH_VERSION_MAX}" )); } let varint_v8 = version >= 8; let zsec_v9 = version >= 9; let inter_block = if varint_v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK }; let blocked_v7 = version >= GRAPH_VERSION; let node_count = u64_at(&meta, 8); let edge_count = u64_at(&meta, 16); let escape_count = u64_at(&meta, 24); if edge_count > u32::MAX as u64 { return err(format!("edge_count {edge_count} does not fit u32")); } if escape_count > edge_count { return err(format!("escape_count {escape_count} exceeds edge_count {edge_count}")); } // The three tables open concurrently: three page-cache faults on // three files, no dependency between them. Metadata validation above // stays serial — it sizes everything below. Small win, almost free. let (nodes, edges, inter) = std::thread::scope(|scope| { let open = |name: &'static str| { scope.spawn(move || { osm_ingest::mem::Mapped::open(&dir.join(name)).map_err(osm_ingest::proto::Error) }) }; let (a, b, c) = (open("nodes.bin"), open("edges.bin"), open("intermediate.bin")); let nodes = a.join().expect("the nodes.bin opener"); let edges = b.join().expect("the edges.bin opener"); let inter = c.join().expect("the intermediate.bin opener"); nodes .and_then(|nodes| edges.map(|edges| (nodes, edges))) .and_then(|(nodes, edges)| inter.map(|inter| (nodes, edges, inter))) })?; let want_nodes = (node_count + 1) .checked_mul(12) .ok_or_else(|| osm_ingest::proto::Error("node table size overflows".to_string()))?; // v7 nodes are a ZBLK section: parse, check the unpacked length, and // inflate eagerly (batch tool — the whole table is walked). let nodes_owned = if blocked_v7 { let view = tilecodec::blocked::Blocked::parse(&nodes).map_err(|e| { osm_ingest::proto::Error(format!("nodes.bin is not a blocked section: {e}")) })?; if view.unpacked_len() != want_nodes || view.record_len() != 12 { return err(format!( "nodes.bin unpacks to {} byte(s), expected {want_nodes}", view.unpacked_len() )); } inflate_all(&view)? } else { if nodes.len() as u64 != want_nodes { return err(format!( "nodes.bin is {} bytes, expected {} for {node_count}+1 records", nodes.len(), want_nodes, )); } Vec::new() }; // v7 edge records are a ZBLK section at the file head; escapes and // names follow it exactly as before. The records' end comes from the // section, not from `edge_count * 7`. let (escape_first_off, rec_owned) = if blocked_v7 { let view = tilecodec::blocked::Blocked::parse(&edges).map_err(|e| { osm_ingest::proto::Error(format!("edges.bin is not a blocked section: {e}")) })?; if view.unpacked_len() != edge_count * 7 || view.record_len() != 7 { return err(format!( "edges.bin unpacks to {} byte(s), expected {} 7-byte records", view.unpacked_len(), edge_count )); } let rec_end = view.block_offset(view.block_count()).ok_or_else(|| { osm_ingest::proto::Error("edges.bin block table has no end".to_string()) })? as usize; (align_up8(rec_end), inflate_all(&view)?) } else { (align_up8((edge_count as usize) * 7), Vec::new()) }; let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1; let escapes_off = escape_first_off + (escape_blocks as usize) * 4; let want_edges_min = escapes_off + (escape_count as usize) * 12; if edges.len() < want_edges_min { return err(format!( "edges.bin is {} bytes, too short for {edge_count} edges and {escape_count} escapes", edges.len(), )); } if inter.len() < 8 { return err("intermediate.bin is too short to hold its geometry-edge count".to_string()); } let g_edges = u64_at(&inter, inter.len() - 8); if g_edges > edge_count { return err(format!( "intermediate.bin claims {g_edges} geometry edges, past the {edge_count} in the graph" )); } let bitmap_bytes = edge_bitmap_bytes(edge_count); let coarse_bytes = ((g_edges.div_ceil(inter_block) + 1) * 8) as usize; let within_bytes = ((g_edges + 1) * 2) as usize; let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8; if inter.len() < trailer { return err(format!( "intermediate.bin is {} bytes, too short for its {trailer}-byte trailer", inter.len(), )); } let blob_bytes = inter.len() - trailer; // v9: the blob is a ZSEC section; inflate it whole (a batch tool walks it all). let blob_owned = if zsec_v9 { let z = tilecodec::zsec::ZSec::parse(&inter[..blob_bytes]).map_err(|e| { osm_ingest::proto::Error(format!("intermediate.bin v9 blob: {e:?}")) })?; let mut raw = Vec::with_capacity(z.raw_len() as usize); for b in 0..z.block_count() { raw.extend_from_slice( &z.block(b).map_err(|e| osm_ingest::proto::Error(format!("{e:?}")))?, ); } raw } else { Vec::new() }; let geom_rank_off = blob_bytes; let geom_present_off = blob_bytes + present_offset(edge_count); let coarse_off = blob_bytes + bitmap_bytes; let within_off = coarse_off + coarse_bytes; Ok(Graph { nodes, edges, inter, nodes_owned, rec_owned, node_count, escape_first_off, escapes_off, geom_rank_off, geom_present_off, coarse_off, within_off, inter_block, varint_v8, blob_owned, }) } /// A node's `(lat_e7, lon_e7)`. pub(crate) fn node(&self, n: u64) -> (i32, i32) { let base = (n as usize) * 12; (i32_at(self.nb(), base), i32_at(self.nb(), base + 4)) } /// A node's first outgoing edge index. The sentinel record (index `node_count`) holds /// `edge_count`, so `edge_ptr(n+1)` is always defined for a real node `n`. pub(crate) fn edge_ptr(&self, n: u64) -> u32 { u32_at(self.nb(), (n as usize) * 12 + 8) } pub(crate) fn edge_type(&self, idx: u32) -> u8 { self.rb()[(idx as usize) * 7 + 5] } /// The target node of edge `idx` whose source is `s`, decoding the escape table when the /// delta or distance is sentinelled. pub(crate) fn edge_target(&self, idx: u32, s: u32) -> Result { let base = (idx as usize) * 7; let rb = self.rb(); let delta = i16_at(rb, base); let dist = (rb[base + 2] as u32) | ((rb[base + 3] as u32) << 8) | ((rb[base + 4] as u32) << 16); if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE { self.escape_target(idx) } else { Ok(s.wrapping_add_signed(delta as i32)) } } fn escape_target(&self, idx: u32) -> Result { let block = (idx as u64 / ESCAPE_BLOCK) as usize; let lo = u32_at(&self.edges, self.escape_first_off + block * 4); let hi = u32_at(&self.edges, self.escape_first_off + (block + 1) * 4); for r in lo..hi { let rb = self.escapes_off + (r as usize) * 12; if u32_at(&self.edges, rb) == idx { return Ok(u32_at(&self.edges, rb + 4)); } } err(format!("edge {idx} is escaped but has no escape row")) } /// Does edge `idx` store an interior-point blob? pub(crate) fn geom_contains(&self, idx: u32) -> bool { let byte = self.geom_present_off + (idx as usize) / 8; self.inter[byte] & (1u8 << (idx % 8)) != 0 } /// The rank of edge `idx` among the geometry-carrying edges: the number of set bits strictly /// below it in the presence bitmap. fn geom_rank(&self, idx: u32) -> u64 { let byte = (idx as usize) / 8; let block = byte / RANK_BLOCK_BYTES; let mut n = u64_at(&self.inter, self.geom_rank_off + block * 8); for b in (block * RANK_BLOCK_BYTES)..byte { n += self.inter[self.geom_present_off + b].count_ones() as u64; } let mask = ((1u16 << (idx % 8)) - 1) as u8; n += (self.inter[self.geom_present_off + byte] & mask).count_ones() as u64; n } /// The blob byte offset of the `g`th geometry edge: `coarse[g/32] + within[g]`. fn geom_offset(&self, g: u64) -> u64 { let coarse = u64_at(&self.inter, self.coarse_off + (g / self.inter_block) as usize * 8); let within = u16_at(&self.inter, self.within_off + (g as usize) * 2) as u64; coarse + within } /// The `(start, end)` byte range of edge `idx`'s interior-point blob, or `None` when it stores /// no geometry (a straight chord). fn intermediate_range(&self, idx: u32) -> Option<(usize, usize)> { if !self.geom_contains(idx) { return None; } let g = self.geom_rank(idx); Some((self.geom_offset(g) as usize, self.geom_offset(g + 1) as usize)) } /// The full polyline of edge `idx` in canonical `source -> target` order, as `(lat_e7, lon_e7)` /// vertices: the source node, any stored interior points, then the target node. pub(crate) fn polyline(&self, idx: u32, s: u32, t: u32) -> Vec<(i32, i32)> { let (slat, slon) = self.node(s as u64); let (tlat, tlon) = self.node(t as u64); let mut out = Vec::with_capacity(4); out.push((slat, slon)); if let Some((start, end)) = self.intermediate_range(idx) { if self.varint_v8 { // Mirrors graph.rs decode_edge_coords (v8/v9). let blob: &[u8] = if self.blob_owned.is_empty() { &self.inter } else { &self.blob_owned }; let b = &blob[start..end.min(blob.len())]; let q = |v: i32| (v as i64).div_euclid(10) + i64::from((v as i64).rem_euclid(10) >= 5); let (mut qlat, mut qlon) = (q(slat), q(slon)); let mut at = 0usize; let uvar = |at: &mut usize| -> Option { let (mut r, mut sh) = (0u64, 0u32); while *at < b.len() { let x = b[*at]; *at += 1; r |= u64::from(x & 0x7f) << sh; if x & 0x80 == 0 { return Some(r); } sh += 7; } None }; let mut count = 1usize; while at < b.len() && count + 1 < MAX_POINTS { let (Some(a), Some(c)) = (uvar(&mut at), uvar(&mut at)) else { break }; qlat += ((a >> 1) as i64) ^ -((a & 1) as i64); qlon += ((c >> 1) as i64) ^ -((c & 1) as i64); out.push(((qlat * 10) as i32, (qlon * 10) as i32)); count += 1; } out.push((tlat, tlon)); return out; } let (mut lat, mut lon) = (slat, slon); let mut off = start; // count starts at 1 for the source; the reader stops at MAX_POINTS total, matching // `graph.rs::decode_edge_coords`. let mut count = 1usize; while off + 4 <= end && count + 1 < MAX_POINTS { let d_lat = i16_at(&self.inter, off) as i32; let d_lon = i16_at(&self.inter, off + 2) as i32; lat = lat.wrapping_add(d_lat); lon = lon.wrapping_add(d_lon); out.push((lat, lon)); count += 1; off += 4; } } out.push((tlat, tlon)); out } /// Is there a drivable edge running `from -> to`? Used to tell a straight two-way chord (which /// has such a twin and is emitted only in the canonical direction) from a one-way (which has /// none and is always emitted). pub(crate) fn has_drivable_twin(&self, from: u32, to: u32) -> Result { let lo = self.edge_ptr(from as u64); let hi = self.edge_ptr(from as u64 + 1); for e in lo..hi { let rc = self.edge_type(e) & ROAD_TYPE_MASK; if (1..=9).contains(&rc) && self.edge_target(e, from)? == to { return Ok(true); } } Ok(false) } } /// Read the v6 graph at `dir` and push one line feature per drivable component segment into `sink`, /// each carrying its packed `component_id`. Returns the number of segments emitted. /// /// Modelled on [`crate::schema::landtype::stream_prepared`] and /// [`crate::schema::transit::stream_routes`]: a source of geometry outside the `.osm.pbf`, read /// after the OSM passes and streamed straight into the feature sink. Unlike those two it is not /// clipped to a bbox here — the graph is already the built region, and the tiler clips each segment /// per tile like any other line. #[cfg(test)] pub fn stream_graph(dir: &Path, sink: &mut Sink) -> Result { let graph = Graph::load(dir)?; let class = traffic_class(); let mut emitted = 0u64; for n in 0..graph.node_count { let s = n as u32; let lo = graph.edge_ptr(n); let hi = graph.edge_ptr(n + 1); for idx in lo..hi { let ty = graph.edge_type(idx); // Step 1: the reverse twin of a curved two-way owns no geometry; its forward twin does. if ty & REVERSE_GEOMETRY_FLAG != 0 { continue; } // A driving overlay: motorway..living_street only. let rc = ty & ROAD_TYPE_MASK; if !(1..=9).contains(&rc) { continue; } let target = graph.edge_target(idx, s)?; if target as u64 >= graph.node_count { return err(format!( "edge {idx} targets node {target}, past the {} in the graph", graph.node_count, )); } // Step 2: a straight two-way chord is emitted only in the canonical direction; a // one-way (no drivable twin back) is always emitted. if !graph.geom_contains(idx) && graph.has_drivable_twin(target, s)? && s >= target { continue; } let verts = graph.polyline(idx, s, target); for seg in 0..verts.len().saturating_sub(1) { let (a_lat, a_lon) = verts[seg]; let (b_lat, b_lon) = verts[seg + 1]; // A zero-length segment draws nothing and would only cost a feature and an id. if a_lat == b_lat && a_lon == b_lon { continue; } let component_id = pack_component_id(idx as u64, seg as u32); let line = vec![vec![ (a_lon as f64 * 1e-7, a_lat as f64 * 1e-7), (b_lon as f64 * 1e-7, b_lat as f64 * 1e-7), ]]; sink.push_named( &class, &crate::store::EncodedGeom::live(&Geometry::Lines(line))?, None, component_id, )?; emitted += 1; } } } Ok(emitted) }