Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / graph_build_part6.rs

graph_build_part6.rs487 lines · 20.2 KiBRaw
1 use super::*;
2 use crate::tags::{LANE_LEFT, LANE_THROUGH};
3 use crate::testpbf;
4
5 struct Outputs {
6 meta: Vec<u8>,
7 nodes: Vec<u8>,
8 edges: Vec<u8>,
9 lanes: Vec<u8>,
10 names: Vec<u8>,
11 inter: Vec<u8>,
12 }
13
14 fn read_outputs(dir: &Path) -> Outputs {
15 let f = |n: &str| std::fs::read(dir.join(n)).unwrap();
16 let meta = f("metadata.bin");
17 let edge_count = u64::from_le_bytes(meta[16..24].try_into().unwrap());
18 // v7 stores the record arrays as ZBLK sections. The helpers below
19 // mirror the device's raw-table reads, so the boundary inflates back
20 // to the v6 shape (records + original tail): the container has its
21 // own unit tests in tilecodec, and these tests own the content.
22 // `local_of`/`node_at` read nodes the same way.
23 let nodes = unpack_or_raw(&f("nodes.bin"));
24 let edges_raw = f("edges.bin");
25 let edges = match tilecodec::blocked::Blocked::parse(&edges_raw) {
26 Ok(v) => {
27 if v.unpacked_len() != edge_count * 7 || v.record_len() != 7 {
28 panic!("blocked edges unpack to the wrong records");
29 }
30 let mut cache = tilecodec::blocked::BlockCache::new(0);
31 let mut recs = Vec::with_capacity(v.unpacked_len() as usize);
32 for b in 0..v.block_count() {
33 recs.extend_from_slice(cache.get(&v, b).unwrap());
34 }
35 // The v6 tail (pad + escapes + names) starts pad-aligned after
36 // the records section — NOT at the section end, which carries
37 // its own alignment padding. Slice from there.
38 let rec_end = v.block_offset(v.block_count()).unwrap() as usize;
39 let tail_at = (rec_end + 7) & !7;
40 let mut out = recs;
41 while out.len() % 8 != 0 {
42 out.push(0);
43 }
44 out.extend_from_slice(&edges_raw[tail_at..]);
45 out
46 }
47 Err(_) => edges_raw,
48 };
49 Outputs {
50 meta,
51 nodes,
52 edges,
53 lanes: f("lanes.bin"),
54 names: f("road_names.bin"),
55 inter: f("intermediate.bin"),
56 }
57 }
58
59 /// Inflate a ZBLK section, or return the bytes untouched when they are not
60 /// one (v6 raw tables pass through).
61 fn unpack_or_raw(bytes: &[u8]) -> Vec<u8> {
62 let Ok(v) = tilecodec::blocked::Blocked::parse(bytes) else {
63 return bytes.to_vec();
64 };
65 let mut cache = tilecodec::blocked::BlockCache::new(0);
66 let mut out = Vec::with_capacity(v.unpacked_len() as usize);
67 for b in 0..v.block_count() {
68 out.extend_from_slice(cache.get(&v, b).unwrap());
69 }
70 assert_eq!(out.len() as u64, v.unpacked_len());
71 out
72 }
73
74 fn node_at(o: &Outputs, i: usize) -> (i32, i32, u64) {
75 let b = &o.nodes[i * 12..i * 12 + 12];
76 (
77 i32::from_le_bytes(b[0..4].try_into().unwrap()),
78 i32::from_le_bytes(b[4..8].try_into().unwrap()),
79 u64::from(u32::from_le_bytes(b[8..12].try_into().unwrap())),
80 )
81 }
82
83 /// A `u64` field of `metadata.bin` at byte `at`.
84 fn meta_u64(o: &Outputs, at: usize) -> u64 {
85 u64::from_le_bytes(o.meta[at..at + 8].try_into().unwrap())
86 }
87
88 /// `edges.bin`, located and decoded exactly as `graph.rs::load` does: the record
89 /// array sized from `edge_count`, padding to the section boundary, the escape
90 /// block index and the rows.
91 ///
92 /// Every accessor below is a literal mirror of the device's, which is what makes
93 /// these contract tests rather than a re-read of our own tables.
94 ///
95 /// The record array itself is owned: v6 files read it in place, v7 files
96 /// inflate their ZBLK records here (the writer emits v7 only). The tail
97 /// (escapes, names) stays borrowed — its layout relative to its own start
98 /// is identical in both versions.
99 struct Edges<'a> {
100 bytes: &'a [u8],
101 records: Vec<u8>,
102 edge_count: u64,
103 first_at: usize,
104 rows_at: usize,
105 /// The name presence bitmap's rank index, then the bitmap, then the offsets.
106 name_rank_at: usize,
107 name_present_at: usize,
108 name_off_at: usize,
109 }
110
111 impl<'a> Edges<'a> {
112 fn new(
113 bytes: &'a [u8],
114 edge_count: u64,
115 escape_count: u64,
116 ) -> Edges<'a> {
117 // The records may be a ZBLK section (v7 writer) or raw (v6
118 // fixtures). Either way `records` holds the unpacked array and
119 // the tail offsets below are relative to the tail start.
120 let (records, tail_base) = match tilecodec::blocked::Blocked::parse(bytes) {
121 Ok(v) => {
122 assert_eq!(v.unpacked_len(), edge_count * EDGE_REC_BYTES);
123 assert_eq!(v.record_len(), EDGE_REC_BYTES as usize);
124 let mut cache = tilecodec::blocked::BlockCache::new(0);
125 let mut recs = Vec::with_capacity(v.unpacked_len() as usize);
126 for b in 0..v.block_count() {
127 recs.extend_from_slice(cache.get(&v, b).unwrap());
128 }
129 let tail = v.block_offset(v.block_count()).unwrap() as usize;
130 // The tail the writer appended starts pad-aligned after
131 // the records section.
132 (recs, (tail + 7) & !7)
133 }
134 Err(_) => {
135 // v6 raw tail (or a reassembled v6-shape buffer): records
136 // are the first E*7 bytes, the tail starts pad-aligned.
137 let n = (edge_count * EDGE_REC_BYTES) as usize;
138 (bytes[..n].to_vec(), align_up(n as u64, SECTION_ALIGN) as usize)
139 }
140 };
141 // Tail layout from its own start: pad, escape index, rows, pad,
142 // names. Identical in both versions; only the base moves.
143 let first_at = 0usize;
144 let blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;
145 let rows_at = first_at + (blocks * 4) as usize;
146 let name_rank_at =
147 align_up(rows_at as u64 + escape_count * 12, SECTION_ALIGN) as usize;
148 let rank_bytes = ((edge_count.div_ceil(RANK_BLOCK_BITS) + 1) * 8) as usize;
149 Edges {
150 bytes: &bytes[tail_base..],
151 records,
152 edge_count,
153 first_at,
154 rows_at,
155 name_rank_at,
156 name_present_at: name_rank_at + rank_bytes,
157 name_off_at: name_rank_at + PresenceBitmap::bytes(edge_count) as usize,
158 }
159 }
160
161 fn of(o: &'a Outputs) -> Edges<'a> {
162 Edges::new(&o.edges, meta_u64(o, 16), meta_u64(o, 24))
163 }
164
165 /// Unpacked record-array length. The v7 container check.
166 fn records_len(&self) -> usize {
167 self.records.len()
168 }
169
170 /// True when edge `idx` has a name, from the presence bitmap.
171 fn named(&self, idx: u64) -> bool {
172 self.bytes[self.name_present_at + (idx / 8) as usize] & (1u8 << (idx % 8)) != 0
173 }
174
175 /// Edge `idx`'s rank in the name bitmap, computed as `graph.rs` does: the
176 /// block's stored count plus a popcount of the bytes below it.
177 fn name_rank(&self, idx: u64) -> u64 {
178 let byte = (idx / 8) as usize;
179 let block = byte / RANK_BLOCK_BYTES;
180 let at = self.name_rank_at + block * 8;
181 let mut n = u64::from_le_bytes(self.bytes[at..at + 8].try_into().unwrap());
182 for b in block * RANK_BLOCK_BYTES..byte {
183 n += u64::from(self.bytes[self.name_present_at + b].count_ones());
184 }
185 let partial = self.bytes[self.name_present_at + byte] & ((1u8 << (idx % 8)) - 1);
186 n + u64::from(partial.count_ones())
187 }
188
189 /// Edge `idx`'s name offset, or [`NO_NAME`] when it has none.
190 fn name_offset(&self, idx: u64) -> u32 {
191 if !self.named(idx) {
192 return NO_NAME;
193 }
194 let at = self.name_off_at + (self.name_rank(idx) * 4) as usize;
195 u32::from_le_bytes(self.bytes[at..at + 4].try_into().unwrap())
196 }
197
198 fn escape_first(&self, block: u64) -> u32 {
199 let at = self.first_at + (block * 4) as usize;
200 u32::from_le_bytes(self.bytes[at..at + 4].try_into().unwrap())
201 }
202
203 /// `(edge_idx, target, dist_mm)` of escape row `r`.
204 fn row(&self, r: u64) -> (u32, u32, u32) {
205 let b = &self.bytes[self.rows_at + (r * 12) as usize..];
206 (
207 u32::from_le_bytes(b[0..4].try_into().unwrap()),
208 u32::from_le_bytes(b[4..8].try_into().unwrap()),
209 u32::from_le_bytes(b[8..12].try_into().unwrap()),
210 )
211 }
212
213 /// `(target, dist_mm, name_offset, type_, speed_limit)` of edge `idx`, whose
214 /// source is `source` — decoded as `Graph::edge` and
215 /// `Graph::edge_name_offset` do, escape table and name bitmap included.
216 fn get(&self, source: u32, idx: u64) -> (u32, u32, u32, u8, u8) {
217 assert!(idx < self.edge_count, "edge {idx} is past the pack");
218 let b = &self.records[(idx * EDGE_REC_BYTES) as usize..];
219 let delta = i16::from_le_bytes([b[0], b[1]]);
220 let dist = u32::from_le_bytes([b[2], b[3], b[4], 0]);
221 let (type_, speed) = (b[5], b[6]);
222 let name = self.name_offset(idx);
223 if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE {
224 let block = idx / ESCAPE_BLOCK;
225 for r in self.escape_first(block)..self.escape_first(block + 1) {
226 let (row_idx, target, dist_mm) = self.row(u64::from(r));
227 if u64::from(row_idx) == idx {
228 return (target, dist_mm, name, type_, speed);
229 }
230 }
231 panic!("edge {idx} carries a sentinel but has no escape row");
232 }
233 (source.wrapping_add_signed(i32::from(delta)), dist, name, type_, speed)
234 }
235 }
236
237 /// The edge's source: the **largest** node index whose `edge_ptr <= idx`, which
238 /// is how `find_node_idx_for_edge` defines it. Taking the first such node instead
239 /// would land on an empty range wherever degree-0 nodes share an `edge_ptr`.
240 fn source_of(o: &Outputs, idx: u64) -> u32 {
241 (0..node_count(o))
242 .rev()
243 .find(|v| node_at(o, *v).2 <= idx)
244 .unwrap_or(0) as u32
245 }
246
247 /// `(target, dist_mm, name_offset, type_, speed_limit)` of edge `i`, with the
248 /// source recovered from `nodes.bin`. Keeps every existing caller unchanged
249 /// across the delta encoding, and exercises the source recovery as a side effect.
250 fn edge_at(o: &Outputs, i: usize) -> (u32, u32, u32, u8, u8) {
251 Edges::of(o).get(source_of(o, i as u64), i as u64)
252 }
253
254 fn name_at(o: &Outputs, off: u32) -> String {
255 let start = off as usize;
256 let end = start + o.names[start..].iter().position(|b| *b == 0).unwrap();
257 String::from_utf8(o.names[start..end].to_vec()).unwrap()
258 }
259
260 fn edge_count(o: &Outputs) -> u64 {
261 meta_u64(o, 16)
262 }
263
264 fn node_count(o: &Outputs) -> usize {
265 o.nodes.len() / 12 - 1
266 }
267
268 /// `intermediate.bin`, located exactly as `graph.rs::load` does: `G` from the
269 /// last 8 bytes, the four trailer tables sized from `G` and the edge count, and
270 /// the blob as whatever is left over at offset 0.
271 ///
272 /// Every accessor below is a literal mirror of the device's, which is what makes
273 /// these contract tests rather than a re-read of our own tables.
274 struct Inter<'a> {
275 bytes: &'a [u8],
276 geometry_edges: u64,
277 blob_bytes: usize,
278 rank_at: usize,
279 present_at: usize,
280 coarse_at: usize,
281 within_at: usize,
282 }
283
284 impl<'a> Inter<'a> {
285 fn new(bytes: &'a [u8], edge_count: u64) -> Inter<'a> {
286 let len = bytes.len();
287 let geometry_edges = u64::from_le_bytes(bytes[len - 8..].try_into().unwrap());
288 let rank_bytes = ((edge_count.div_ceil(RANK_BLOCK_BITS) + 1) * 8) as usize;
289 let present_bytes = edge_count.div_ceil(8) as usize;
290 let coarse_bytes =
291 ((geometry_edges.div_ceil(INTERMEDIATE_BLOCK) + 1) * 8) as usize;
292 let within_bytes = ((geometry_edges + 1) * 2) as usize;
293 let blob_bytes =
294 len - (rank_bytes + present_bytes + coarse_bytes + within_bytes + 8);
295 Inter {
296 bytes,
297 geometry_edges,
298 blob_bytes,
299 rank_at: blob_bytes,
300 present_at: blob_bytes + rank_bytes,
301 coarse_at: blob_bytes + rank_bytes + present_bytes,
302 within_at: blob_bytes + rank_bytes + present_bytes + coarse_bytes,
303 }
304 }
305
306 /// Whether edge `i` stores a polyline of its own.
307 fn present(&self, i: u64) -> bool {
308 self.bytes[self.present_at + (i / 8) as usize] & (1u8 << (i % 8)) != 0
309 }
310
311 /// Set bits below `i`: the rank block, then a `popcount` of the whole bytes
312 /// after it and of the partial byte `i` falls in.
313 fn rank(&self, i: u64) -> u64 {
314 let byte = (i / 8) as usize;
315 let block = byte / RANK_BLOCK_BYTES;
316 let at = self.rank_at + block * 8;
317 let mut n = u64::from_le_bytes(self.bytes[at..at + 8].try_into().unwrap());
318 for b in block * RANK_BLOCK_BYTES..byte {
319 n += u64::from(self.bytes[self.present_at + b].count_ones());
320 }
321 let partial = self.bytes[self.present_at + byte] & ((1u8 << (i % 8)) - 1);
322 n + u64::from(partial.count_ones())
323 }
324
325 /// Blob offset of the `g`-th geometry edge, reassembled from both levels.
326 fn offset(&self, g: u64) -> u64 {
327 let cb = self.coarse_at + (g / INTERMEDIATE_BLOCK) as usize * 8;
328 let coarse = u64::from_le_bytes(self.bytes[cb..cb + 8].try_into().unwrap());
329 let wb = self.within_at + g as usize * 2;
330 let within = u16::from_le_bytes(self.bytes[wb..wb + 2].try_into().unwrap());
331 coarse + u64::from(within)
332 }
333
334 /// Edge `i`'s stored polyline bytes, or `None` when it stores none — which
335 /// is how the device spells "no geometry" now that a zero-length blob is a
336 /// valid chord.
337 fn blob(&self, i: u64) -> Option<&'a [u8]> {
338 if !self.present(i) {
339 return None;
340 }
341 let g = self.rank(i);
342 let (s, e) = (self.offset(g) as usize, self.offset(g + 1) as usize);
343 Some(&self.bytes[s..e])
344 }
345 }
346
347 fn inter(o: &Outputs) -> Inter<'_> {
348 Inter::new(&o.inter, edge_count(o))
349 }
350
351 /// `lanes.bin`'s sparse index as `(edge_idx, blob_byte_off)` pairs, the trailing
352 /// sentinel included, plus the blob behind it.
353 fn lane_index(o: &Outputs) -> (Vec<(u32, u32)>, Vec<u16>) {
354 let n = u32::from_le_bytes(o.lanes[0..4].try_into().unwrap()) as usize;
355 let index: Vec<(u32, u32)> = (0..=n)
356 .map(|i| {
357 let b = &o.lanes[4 + i * 8..4 + i * 8 + 8];
358 (
359 u32::from_le_bytes(b[0..4].try_into().unwrap()),
360 u32::from_le_bytes(b[4..8].try_into().unwrap()),
361 )
362 })
363 .collect();
364 let blob = o.lanes[4 + (n + 1) * 8..]
365 .chunks_exact(2)
366 .map(|c| u16::from_le_bytes(c.try_into().unwrap()))
367 .collect();
368 (index, blob)
369 }
370
371 /// The device's `edge_lane_masks`: the same lower-bound binary search over the
372 /// sparse index, so a divergence between the search and the file shows up here
373 /// rather than on a phone.
374 fn lane_masks(o: &Outputs, edge_idx: u64) -> Option<Vec<u16>> {
375 let (index, blob) = lane_index(o);
376 let n = index.len() - 1;
377 let want = u32::try_from(edge_idx).ok()?;
378 let mut lo = 0usize;
379 let mut hi = n;
380 while lo < hi {
381 let mid = lo + (hi - lo) / 2;
382 if index[mid].0 < want {
383 lo = mid + 1;
384 } else {
385 hi = mid;
386 }
387 }
388 if lo >= n || index[lo].0 != want {
389 return None;
390 }
391 let (start, end) = (index[lo].1 as usize / 2, index[lo + 1].1 as usize / 2);
392 (end > start).then(|| blob[start..end].to_vec())
393 }
394
395 /// The local id whose coordinates match fixture node `osm_id`, or `None` if
396 /// that node was collapsed away.
397 fn local_of(o: &Outputs, osm_id: i64) -> Option<u32> {
398 let (_, lat, lon) = testpbf::NODES.iter().find(|n| n.0 == osm_id).copied().unwrap();
399 (0..node_count(o) as u32).find(|i| {
400 let (l, g, _) = node_at(o, *i as usize);
401 (l, g) == (lat, lon)
402 })
403 }
404
405 /// Reimplementation of `graph.rs`'s `get_edge_coordinates`, reverse-geometry
406 /// lookup included. The point of decoding it this way rather than reading our
407 /// own chain table back is that it is the device's algorithm that has to
408 /// agree with the file.
409 fn edge_coords(o: &Outputs, edge_idx: u64) -> Option<(Vec<(i32, i32)>, bool)> {
410 let (target, _, _, type_, _) = edge_at(o, edge_idx as usize);
411 let t = inter(o);
412 let pt = |n: u32| {
413 let (lat, lon, _) = node_at(o, n as usize);
414 (lat, lon)
415 };
416 // The blob is interior-only, so the two endpoints come from `nodes.bin`.
417 let decode = |k: u64, from: u32, to: u32| -> Option<Vec<(i32, i32)>> {
418 Some(geom::decode(t.blob(k)?, pt(from), pt(to)))
419 };
420 // Find the source by the same monotonic search the device uses.
421 let u = (0..node_count(o) as u32)
422 .rev()
423 .find(|i| node_at(o, *i as usize).2 <= edge_idx)
424 .unwrap();
425 if type_ & REVERSE_GEOMETRY_FLAG != 0 {
426 let s = node_at(o, target as usize).2;
427 let e = node_at(o, target as usize + 1).2;
428 for k in s..e {
429 if edge_at(o, k as usize).0 == u {
430 // The twin runs `target -> u`, so it is seeded and terminated
431 // the other way round. `get_pt_at` is what flips it on device,
432 // so flip it here too and hand callers a source-to-target
433 // polyline either way.
434 let mut pts = decode(k, target, u)?;
435 pts.reverse();
436 return Some((pts, true));
437 }
438 }
439 return None;
440 }
441 Some((decode(edge_idx, u, target)?, false))
442 }
443
444 #[test]
445 fn rank_agrees_with_a_brute_force_popcount() {
446 // Ids chosen to straddle byte and 512-bit block boundaries, since those
447 // are the two places the three-term rank can be off by one.
448 let ids: Vec<u64> = vec![
449 0, 1, 7, 8, 9, 63, 64, 65, 511, 512, 513, 1023, 1024, 4095, 4096, 9999,
450 ];
451 let mut b = Bitset::new(*ids.last().unwrap());
452 for id in &ids {
453 assert!(b.set(*id), "id {id} listed twice");
454 }
455 let total = b.build_rank(*ids.last().unwrap());
456 assert_eq!(total, ids.len() as u64);
457
458 // A set bit's dense id is its position in the sorted set of set ids...
459 for (want, id) in ids.iter().enumerate() {
460 assert_eq!(b.dense(*id), want as u32, "id {id}");
461 }
462 // ...and for every id, set or not, the rank is the brute-force count of
463 // set bits strictly below it.
464 for id in 0..=*ids.last().unwrap() {
465 let want = ids.iter().filter(|x| **x < id).count() as u32;
466 assert_eq!(b.dense(id), want, "id {id}");
467 }
468 }
469
470 #[test]
471 fn an_empty_bitset_ranks_everything_to_zero() {
472 let mut b = Bitset::new(1024);
473 assert_eq!(b.build_rank(1024), 0);
474 assert_eq!(b.dense(0), 0);
475 assert_eq!(b.dense(1024), 0);
476 assert!(!b.get(7));
477 }
478
479 #[test]
480 fn setting_a_bit_twice_is_reported_once() {
481 let mut b = Bitset::new(64);
482 assert!(b.set(9));
483 assert!(!b.set(9));
484 assert!(b.get(9));
485 assert_eq!(b.build_rank(64), 1);
486 }
487