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

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

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