Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / maps / src / main / rust / src / graph_part1.rs
graph_part1.rs203 lines · 9.2 KiBRaw
| 1 | /// The whole-world routing dataset. Immutable after construction. |
| 2 | pub struct Graph { |
| 3 | // mmap regions kept alive for the lifetime of the graph. The three |
| 4 | // mandatory ones are `Some` on the multi-file path (one region per file) |
| 5 | // and `None` on the single-archive path (the one archive region below |
| 6 | // backs everything instead); exactly one side is populated, checked in |
| 7 | // `assemble`. |
| 8 | _nodes_region: Option<MmapRegion>, |
| 9 | _edges_region: Option<MmapRegion>, |
| 10 | _intermediate_region: Option<MmapRegion>, |
| 11 | _road_names_region: Option<MmapRegion>, |
| 12 | _lanes_region: Option<MmapRegion>, |
| 13 | _elevation_region: Option<MmapRegion>, |
| 14 | // The single-archive file on the `load_archive` path, which backs every |
| 15 | // pointer above instead of the six per-file regions. `None` on the |
| 16 | // multi-file `load` path. |
| 17 | _archive_region: Option<MmapRegion>, |
| 18 | // Owned byte backing for host tests (the host stub cannot mmap): the |
| 19 | // graph keeps these alive exactly like the regions. Always empty in |
| 20 | // production. |
| 21 | _owned_buffers: Vec<Vec<u8>>, |
| 22 | |
| 23 | nodes: *const u8, |
| 24 | pub node_count: u32, // real nodes; nodes.bin has node_count + 1 (sentinel) |
| 25 | pub edge_count: u64, |
| 26 | |
| 27 | // `edges.bin`, in five sections: |
| 28 | // [ EdgeRec[E] ][ pad ][ u32 escape_first[E/1024 + 1] ][ EscapeRow[escapes] ] |
| 29 | // [ pad ][ u64 name rank[..] ][ u8 name present[..] ][ u32 name_off[named] ] |
| 30 | // The records hold `target` as an i16 delta and `dist_mm` as a u24; either |
| 31 | // field's sentinel sends both to the escape table. See `EdgeRec`. |
| 32 | edges: *const u8, |
| 33 | escape_first: *const u8, // u32[E.div_ceil(ESCAPE_BLOCK) + 1] |
| 34 | escapes: *const u8, // EscapeRow[escape_count], ascending by edge_idx |
| 35 | /// Edges whose `target` or `dist_mm` came out of the escape table rather than |
| 36 | /// the record. Validated against the block index's total at load. |
| 37 | pub escape_count: u64, |
| 38 | names: EdgeBitmap, |
| 39 | name_off: *const u8, // u32[named_edges], indexed by rank in `names` |
| 40 | /// Edges with a name at all. Validated against the rank index's total at load. |
| 41 | pub named_edges: u64, |
| 42 | |
| 43 | // `intermediate.bin`, blob first and every table in a trailer. `off(g) = |
| 44 | // coarse[g / INTERMEDIATE_BLOCK] + within[g]` for the g-th *geometry* edge, |
| 45 | // where g is the edge's rank in `geometry`. |
| 46 | intermediate_data: *const u8, // delta-encoded coordinate bytes, at offset 0 |
| 47 | geometry: EdgeBitmap, // which edges store a polyline, and their rank |
| 48 | intermediate_coarse: *const u8, // u64[G.div_ceil(BLOCK) + 1] |
| 49 | intermediate_within: *const u8, // u16[G + 1] |
| 50 | |
| 51 | // Real OSM turn-lane data (see `edge_lane_masks`). Sparse: only the edges that |
| 52 | // actually carry `turn:lanes` appear, which on a planet is 2.9 M of 1.07 G. |
| 53 | // Optional as a whole too — absent until the graph is regenerated with lane |
| 54 | // extraction, in which case routing falls back to topology-inferred lanes. |
| 55 | lane_index: *const u8, // LaneEntry[lane_edges + 1], ascending by edge_idx |
| 56 | lane_edges: u32, |
| 57 | lane_data: *const u8, // packed u16 per-lane masks |
| 58 | |
| 59 | road_names: *const u8, |
| 60 | pub road_names_size: usize, |
| 61 | |
| 62 | // `elevation.bin`, an OPTIONAL `i16[node_count]` of per-node ground elevation in metres, baked |
| 63 | // from the DEM at graph-build time (WS-G route profile). Null when the file is absent or its |
| 64 | // length does not match `node_count`, in which case [`Graph::node_elevation`] reads 0 for every |
| 65 | // node and the route profile comes out flat. A sidecar like `road_names.bin`/`lanes.bin`: no |
| 66 | // metadata count and no GRAPH_VERSION bump, validated by its own length instead. |
| 67 | // |
| 68 | // Under v7 the file is a ZBLK section ([`elevation_blocked`]); the loader |
| 69 | // dispatches on the magic, so absence still reads as all-zero. |
| 70 | elevation: *const u8, |
| 71 | |
| 72 | /// v7 blocked views, parsed (not inflated) at load. `None` on the v6 path, |
| 73 | /// where the raw pointers above serve directly. |
| 74 | /// |
| 75 | /// Each view inflates and keeps a block (4096 records) the first time a |
| 76 | /// record in it is read. A route only touches the blocks along its search |
| 77 | /// frontier, whereas inflating whole sections up front meant ~10 GiB of heap |
| 78 | /// for the world pack on the first route: a multi-minute stall, then an OOM |
| 79 | /// kill on an 8 GB phone. |
| 80 | nodes_view: Option<BlockedView>, |
| 81 | edges_view: Option<BlockedView>, |
| 82 | elevation_view: Option<BlockedView>, |
| 83 | |
| 84 | /// The optional highway overlay. See `graph_overlay.rs`. |
| 85 | overlay: Option<Overlay>, |
| 86 | |
| 87 | // Derived cost tables (computed in `load`, matching the C++ `init`). |
| 88 | pub lon_to_mm_scale: [u32; 4096], |
| 89 | pub time_scale_fixed: [u64; 4], |
| 90 | pub edge_time_multipliers: [[u64; 16]; 4], |
| 91 | } |
| 92 | |
| 93 | /// A parsed ZBLK section that borrows nothing. |
| 94 | /// |
| 95 | /// The offset table is copied (8 bytes per block — 524 KB for 268 M planet |
| 96 | /// bodies) so this owns everything it needs except the frames themselves, |
| 97 | /// which stay in the mmap region (or archive slice) the caller keeps alive |
| 98 | /// exactly like the raw tables. No lifetime ties the two structs together. |
| 99 | pub(crate) struct BlockedView { |
| 100 | record_len: usize, |
| 101 | records_per_block: u64, |
| 102 | /// `log2(records_per_block)` when it is a power of two (always, for packs |
| 103 | /// the writer produces), so the hot lookup shifts instead of dividing. |
| 104 | block_shift: Option<u32>, |
| 105 | unpacked_len: u64, |
| 106 | /// Absolute file offsets of each block start, plus the file end. |
| 107 | offsets: Vec<u64>, |
| 108 | frames: *const u8, |
| 109 | /// Inflated blocks, filled on first read. A block that fails to decode is |
| 110 | /// stored empty, so its records read as absent rather than retrying. |
| 111 | blocks: Box<[std::sync::OnceLock<Box<[u8]>>]>, |
| 112 | } |
| 113 | |
| 114 | // Raw pointers into a mapping the graph owns: Send exactly like the tables. |
| 115 | unsafe impl Send for BlockedView {} |
| 116 | unsafe impl Sync for BlockedView {} |
| 117 | |
| 118 | impl BlockedView { |
| 119 | /// Parse over `bytes` (the whole section file/slice). Refuses bad magic, |
| 120 | /// unknown flags, zero stride, and offsets outside the section. Mirrors |
| 121 | /// `tilecodec::blocked::Blocked::parse` without borrowing it, so no |
| 122 | /// lifetime ties this view to the mapping. |
| 123 | pub(crate) fn parse(bytes: &[u8]) -> Option<BlockedView> { |
| 124 | if bytes.len() < 28 { |
| 125 | return None; |
| 126 | } |
| 127 | let u32_at = |o: usize| { |
| 128 | u32::from_le_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]) |
| 129 | }; |
| 130 | let u64_at = |o: usize| { |
| 131 | u64::from_le_bytes([ |
| 132 | bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3], bytes[o + 4], |
| 133 | bytes[o + 5], bytes[o + 6], bytes[o + 7], |
| 134 | ]) |
| 135 | }; |
| 136 | if u32_at(0) != tilecodec::blocked::BLOCKED_MAGIC || u32_at(4) != 0 { |
| 137 | return None; |
| 138 | } |
| 139 | let record_len = u32_at(8) as usize; |
| 140 | let records_per_block = u32_at(12) as u64; |
| 141 | let unpacked_len = u64_at(16); |
| 142 | if record_len == 0 || records_per_block == 0 { |
| 143 | return None; |
| 144 | } |
| 145 | let block_count = u32_at(24) as usize; |
| 146 | let mut offsets = Vec::with_capacity(block_count + 1); |
| 147 | for i in 0..=block_count { |
| 148 | let o = u64_at(28 + i * 8); |
| 149 | if o > bytes.len() as u64 || (i > 0 && o < offsets[i - 1]) { |
| 150 | return None; |
| 151 | } |
| 152 | offsets.push(o); |
| 153 | } |
| 154 | // No end-equality check: a blocked record array may share its file |
| 155 | // with trailing tables (`edges.bin`'s escapes/names). Truncation is |
| 156 | // still refused above — an offset past the bytes fails. |
| 157 | Some(BlockedView { |
| 158 | record_len, |
| 159 | records_per_block, |
| 160 | block_shift: records_per_block |
| 161 | .is_power_of_two() |
| 162 | .then(|| records_per_block.trailing_zeros()), |
| 163 | unpacked_len, |
| 164 | offsets, |
| 165 | frames: bytes.as_ptr(), |
| 166 | blocks: (0..block_count).map(|_| std::sync::OnceLock::new()).collect(), |
| 167 | }) |
| 168 | } |
| 169 | |
| 170 | /// The `record_len` bytes of record `id`, or `None` when it is out of range |
| 171 | /// or its block does not decode. |
| 172 | #[inline] |
| 173 | pub(crate) fn record(&self, id: u64) -> Option<&[u8]> { |
| 174 | let (b, i) = match self.block_shift { |
| 175 | Some(s) => (id >> s, id & (self.records_per_block - 1)), |
| 176 | None => (id / self.records_per_block, id % self.records_per_block), |
| 177 | }; |
| 178 | let block = self.blocks.get(b as usize)?.get_or_init(|| self.inflate(b as usize)); |
| 179 | let at = i as usize * self.record_len; |
| 180 | block.get(at..at + self.record_len) |
| 181 | } |
| 182 | |
| 183 | /// Decode block `b`'s zstd frame, checking it against the size the header |
| 184 | /// implies. Empty on any failure. |
| 185 | #[cold] |
| 186 | fn inflate(&self, b: usize) -> Box<[u8]> { |
| 187 | let block_bytes = self.records_per_block * self.record_len as u64; |
| 188 | let want = block_bytes.min(self.unpacked_len.saturating_sub(b as u64 * block_bytes)) as usize; |
| 189 | let (start, end) = (self.offsets[b] as usize, self.offsets[b + 1] as usize); |
| 190 | let frame = unsafe { std::slice::from_raw_parts(self.frames.add(start), end - start) }; |
| 191 | let mut out = Vec::with_capacity(want); |
| 192 | let decoded = ruzstd::decoding::StreamingDecoder::new(frame) |
| 193 | .ok() |
| 194 | .and_then(|mut d| std::io::Read::read_to_end(&mut d, &mut out).ok()); |
| 195 | if decoded.is_none() || out.len() != want { |
| 196 | return Box::default(); |
| 197 | } |
| 198 | out.into_boxed_slice() |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | unsafe impl Send for Graph {} |
| 203 | unsafe impl Sync for Graph {} |