Modern Apps git

← Modern-Apps.git

maps: graph v8 varint shape points + 1 m thinning writer (#planet5)

Commit
5939066d3dadb60940c5ddf44bdbd739e37b7b15
Author
Vayun Mathur <[email protected]>
When
2026-11-14 00:54 UTC (22 days ago)
Parents
9619ccc
Planet5: intermediate.bin (9.6 GB on planet4, fixed i16 1e-7 degree
deltas per shape point) shrinks to an estimated ~5.6 GB.

Reader (Graph::load and the archive loader): graph v8 blobs are
zigzag LEB128 deltas on a 1e-6 degree grid, seeded from the source
node's own grid position (round half up of e7/10), decoded points
landing on multiples of 10 e7 units (<= 5.6 cm per axis from the
original). A varint blob is variable length, so v8 uses 16 geometry
edges per coarse entry (INTERMEDIATE_BLOCK_V8) to keep a block's span
under the u16 within-table (16 x 254 points x 2 x 5 B = 40,640).
v6/v7 graphs decode exactly as before; the overlay writer keeps
stamping v7 (its intermediate is empty).

Writer: examples/graph_thin --v8 rewrites a road_graph output: every
stored polyline Douglas-Peucker thinned to TOL_CM with every point
within KEEP_END_M of either node kept (the approach/exit bearings
guidance derives maneuvers from), then a repair pass re-inserts the
worst vertex of any span a kept point split until every dropped
vertex is within the tolerance again; presence bitmap copied, offset
tables rebuilt, metadata stamped v8, and the result loaded back with
the real reader. planet_build.sh runs it at 100 cm / 25 m.

Measured (US West, 978 routable of 1000 random pairs, base vs
planet5 graph, both through the single-archive loader): intermediate
478.8 -> 325.0 MB; max polyline deviation 1.000 m; route length p95
26.9 m (0.055 %), ETA p95 26 s (0.08 %); the one large outlier is a
destination 4.95 km off-road whose snap moved along a straight desert
road. Multi-file and archive loaders give identical reports.

Verified: cargo test -p offlinerouter (93 pass); route_diff reports
above; planet graph_thin at 1 m: intermediate 9.64 -> 6.53 GB (v7
layout, before varint).

Diff

maps/src/main/rust/examples/graph_thin.rs
diff --git a/maps/src/main/rust/examples/graph_thin.rs b/maps/src/main/rust/examples/graph_thin.rsindex 1ea4cc5d4d..c1d3ac98f3 100644--- a/maps/src/main/rust/examples/graph_thin.rs+++ b/maps/src/main/rust/examples/graph_thin.rs@@ -21,7 +21,7 @@ //! //! Experiment tooling (examples/): never in the cdylib. -use offlinerouter::graph::{Graph, LatLon, INTERMEDIATE_BLOCK};+use offlinerouter::graph::{Graph, LatLon, INTERMEDIATE_BLOCK, INTERMEDIATE_BLOCK_V8};  fn read_u64(b: &[u8], at: usize) -> u64 {     u64::from_le_bytes(b[at..at + 8].try_into().unwrap())@@ -75,7 +75,11 @@ fn zz(v: i64) -> u64 { }  fn main() -> std::process::ExitCode {-    let a: Vec<String> = std::env::args().skip(1).collect();+    let all: Vec<String> = std::env::args().skip(1).collect();+    // `--v8`: write the planet5 layout (graph v8: zigzag-varint deltas on a 1e-6 degree grid,+    // INTERMEDIATE_BLOCK_V8 per coarse entry, no i16 bridging needed). Without it the v7 layout.+    let v8 = all.iter().any(|x| x == "--v8");+    let a: Vec<String> = all.into_iter().filter(|x| x != "--v8").collect();     if a.len() < 3 {         eprintln!("usage: graph_thin IN_GRAPH_DIR OUT_GRAPH_DIR TOL_CM");         return std::process::ExitCode::from(2);@@ -91,7 +95,12 @@ fn main() -> std::process::ExitCode {     let e = g.edge_count;     let gcount = read_u64(&inter, inter.len() - 8);     let bitmap_bytes = (e.div_ceil(512) + 1) * 8 + e.div_ceil(8);-    let coarse_bytes = (gcount.div_ceil(INTERMEDIATE_BLOCK) + 1) * 8;+    let meta = std::fs::read(format!("{inp}/metadata.bin")).expect("read metadata");+    let in_version = u32::from_le_bytes(meta[4..8].try_into().unwrap());+    let in_block = if in_version >= 8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };+    let out_block = if v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };+    let coarse_bytes = (gcount.div_ceil(in_block) + 1) * 8;+    let out_coarse_bytes = (gcount.div_ceil(out_block) + 1) * 8;     let within_bytes = (gcount + 1) * 2;     let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;     let blob_len = inter.len() as u64 - trailer;@@ -101,7 +110,7 @@ fn main() -> std::process::ExitCode {      let tol_m = tol_cm / 100.0;     let mut blob: Vec<u8> = Vec::with_capacity(blob_len as usize);-    let mut coarse: Vec<u64> = Vec::with_capacity(coarse_bytes as usize / 8);+    let mut coarse: Vec<u64> = Vec::with_capacity(out_coarse_bytes as usize / 8);     let mut within: Vec<u16> = Vec::with_capacity(gcount as usize + 1);     let mut buf = vec![LatLon { lat_e7: 0, lon_e7: 0 }; 256];     let (mut pts_in, mut pts_out, mut readded) = (0u64, 0u64, 0u64);@@ -113,11 +122,11 @@ fn main() -> std::process::ExitCode {         if present[(idx / 8) as usize] & (1 << (idx % 8)) == 0 {             continue;         }-        if rank % INTERMEDIATE_BLOCK == 0 {+        if rank % out_block == 0 {             block_start = blob.len() as u64;             coarse.push(block_start);         }-        within.push((blob.len() as u64 - block_start) as u16);+        within.push(u16::try_from(blob.len() as u64 - block_start).expect("a coarse block spans more than 64 KiB"));         rank += 1;         let src = g.find_node_idx_for_edge(idx);         let Some((cnt, rev)) = g.get_edge_coordinates_from(src, idx, &mut buf) else {@@ -164,7 +173,11 @@ fn main() -> std::process::ExitCode {             (b.lat_e7 - a.lat_e7).abs() <= i16::MAX as i32 && (b.lon_e7 - a.lon_e7).abs() <= i16::MAX as i32         };         let mut out_idx: Vec<usize> = vec![0];-        let mut i = 1;+        let mut i = if v8 { cnt - 1 } else { 1 };+        if v8 {+            // No delta range to bridge: varints take any step.+            out_idx.extend((1..cnt - 1).filter(|&k| keep[k]));+        }         while i < cnt - 1 {             if !keep[i] {                 i += 1;@@ -226,6 +239,30 @@ fn main() -> std::process::ExitCode {                 max_dev_m = max_dev_m.max(seg_dist_sq(xy[k], xy[w[0]], xy[w[1]]).sqrt());             }         }+        if v8 {+            let q = |v: i32| (v as i64).div_euclid(10) + i64::from((v as i64).rem_euclid(10) >= 5);+            let (mut pl, mut pn) = (q(poly[0].lat_e7), q(poly[0].lon_e7));+            for &k in &out_idx[1..] {+                let (ql, qn) = (q(poly[k].lat_e7), q(poly[k].lon_e7));+                let mut put = |v: i64| {+                    let mut u = ((v << 1) ^ (v >> 63)) as u64;+                    loop {+                        let b = (u & 0x7f) as u8;+                        u >>= 7;+                        if u == 0 {+                            blob.push(b);+                            break;+                        }+                        blob.push(b | 0x80);+                    }+                };+                put(ql - pl);+                put(qn - pn);+                (pl, pn) = (ql, qn);+                pts_out += 1;+            }+            continue;+        }         // Encode interior points (out_idx[1..]) as i16 deltas, first from the source.         let mut prev = poly[0];         let mut prev6 = (poly[0].lat_e7 / 10, poly[0].lon_e7 / 10);@@ -247,17 +284,17 @@ fn main() -> std::process::ExitCode {     }     assert_eq!(rank, gcount, "geometry rank count");     // Sentinel: the blob length, in the final block's slot.-    if rank % INTERMEDIATE_BLOCK == 0 {+    if rank % out_block == 0 {         coarse.push(blob.len() as u64);         block_start = blob.len() as u64;     }-    within.push((blob.len() as u64 - block_start) as u16);+    within.push(u16::try_from(blob.len() as u64 - block_start).expect("a coarse block spans more than 64 KiB"));     // The table always carries div_ceil(G, 32) + 1 entries; the generator's trailing slot is     // the blob length.-    while (coarse.len() as u64) * 8 < coarse_bytes {+    while (coarse.len() as u64) * 8 < out_coarse_bytes {         coarse.push(blob.len() as u64);     }-    assert_eq!(coarse.len() as u64 * 8, coarse_bytes, "coarse table size");+    assert_eq!(coarse.len() as u64 * 8, out_coarse_bytes, "coarse table size");     assert_eq!(within.len() as u64 * 2, within_bytes, "within table size");      std::fs::create_dir_all(outp).expect("mkdir");@@ -280,11 +317,15 @@ fn main() -> std::process::ExitCode {     }     out.extend_from_slice(&gcount.to_le_bytes());     std::fs::write(format!("{outp}/intermediate.bin"), &out).expect("write");+    let mut meta_out = meta.clone();+    let out_version: u32 = if v8 { 8 } else { in_version.min(7) };+    meta_out[4..8].copy_from_slice(&out_version.to_le_bytes());+    std::fs::write(format!("{outp}/metadata.bin"), &meta_out).expect("write metadata");     // Validate by loading the result with the real reader.     let g2 = Graph::load(&format!("{outp}/")).expect("thinned graph must load");     assert_eq!(g2.edge_count, e);     println!(-        "graph_thin tol_cm={tol_cm} keep_end_m={keep_end_m} interior_points {pts_in} -> {pts_out} ({:.1}%), readded_for_i16 {readded}, \+        "graph_thin v8={v8} tol_cm={tol_cm} keep_end_m={keep_end_m} interior_points {pts_in} -> {pts_out} ({:.1}%), readded_for_i16 {readded}, \          max_dev_m {max_dev_m:.3}\n  intermediate.bin {} -> {} bytes (blob {} -> {}; trailer {})\n  \          format-change estimates for the thinned blob: zigzag-varint e7 {} B, varint at 1e-6 deg {} B",         100.0 * pts_out as f64 / pts_in.max(1) as f64,
maps/src/main/rust/src/graph.rs
diff --git a/maps/src/main/rust/src/graph.rs b/maps/src/main/rust/src/graph.rsindex cc4480a220..ff1e72ec11 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -161,6 +161,11 @@ const fn align_up(n: u64, align: u64) -> u64 { /// entry in a block describes a real blob. pub const INTERMEDIATE_BLOCK: u64 = 32; +/// Geometry edges per coarse block in a v8 (planet5) `intermediate.bin`. Half of+/// [`INTERMEDIATE_BLOCK`] because a varint blob is variable length: at most 254 interior points+/// x 2 varints x 5 bytes = 2540 bytes, and 16 x 2540 = 40,640 still fits the `u16` within-table.+pub const INTERMEDIATE_BLOCK_V8: u64 = 16;+ /// Bytes of presence bitmap one entry of a rank index covers. /// /// 64 bytes is 512 edges and one cache line, so a rank costs one `u64` load plus at
maps/src/main/rust/src/graph_overlay.rs
diff --git a/maps/src/main/rust/src/graph_overlay.rs b/maps/src/main/rust/src/graph_overlay.rsindex 3e873adf03..a4250ad797 100644--- a/maps/src/main/rust/src/graph_overlay.rs+++ b/maps/src/main/rust/src/graph_overlay.rs@@ -264,7 +264,7 @@ mod overlay_tests {         let intermediate = vec![0u8; (EdgeBitmap::bytes(e) + 18) as usize];         let mut meta = Vec::new();         meta.extend_from_slice(&GRAPH_MAGIC.to_le_bytes());-        meta.extend_from_slice(&GRAPH_VERSION.to_le_bytes());+        meta.extend_from_slice(&tilecodec::mamaps::archive::GRAPH_VERSION_BLOCKED.to_le_bytes());         meta.extend_from_slice(&u64::from(n).to_le_bytes());         meta.extend_from_slice(&e.to_le_bytes());         meta.extend_from_slice(&0u64.to_le_bytes());
maps/src/main/rust/src/graph_part1.rs
diff --git a/maps/src/main/rust/src/graph_part1.rs b/maps/src/main/rust/src/graph_part1.rsindex 437338c466..4e46f366f9 100644--- a/maps/src/main/rust/src/graph_part1.rs+++ b/maps/src/main/rust/src/graph_part1.rs@@ -47,6 +47,11 @@ pub struct Graph {     geometry: EdgeBitmap,           // which edges store a polyline, and their rank     intermediate_coarse: *const u8, // u64[G.div_ceil(BLOCK) + 1]     intermediate_within: *const u8, // u16[G + 1]+    // Planet5 (graph v8): blobs are zigzag-varint deltas on a 1e-6 degree grid and the coarse+    // table covers INTERMEDIATE_BLOCK_V8 geometry edges per entry. v6/v7: fixed i16 1e-7+    // degree deltas, INTERMEDIATE_BLOCK per entry.+    intermediate_varint: bool,+    intermediate_block: u64,      // Real OSM turn-lane data (see `edge_lane_masks`). Sparse: only the edges that     // actually carry `turn:lanes` appear, which on a planet is 2.9 M of 1.07 G.
maps/src/main/rust/src/graph_part2.rs
diff --git a/maps/src/main/rust/src/graph_part2.rs b/maps/src/main/rust/src/graph_part2.rsindex 480233ffe3..733ef6fdd5 100644--- a/maps/src/main/rust/src/graph_part2.rs+++ b/maps/src/main/rust/src/graph_part2.rs@@ -39,7 +39,7 @@ impl Graph {         // Explicit count fields rather than a generic section directory: each         // version adds one, and a named field is more debuggable than speculative         // generality.-        let (node_count, edge_count, escape_count, named_edges, blocked_v7) = {+        let (node_count, edge_count, escape_count, named_edges, blocked_v7, varint_v8) = {             let meta = MmapRegion::map(&format!("{base}metadata.bin"))?;             if meta.len < 40 {                 return None;@@ -67,9 +67,11 @@ impl Graph {                 edges,                 escapes,                 named,-                version >= GRAPH_VERSION,+                version >= tilecodec::mamaps::archive::GRAPH_VERSION_BLOCKED,+                version >= tilecodec::mamaps::archive::GRAPH_VERSION_VARINT,             )         };+        let intermediate_block = if varint_v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };          // `edge_count` now comes from the header rather than from `edges.bin`'s         // length. That is the point of version 4, and 5 and 6 are why: the record is@@ -198,7 +200,7 @@ impl Graph {             return None;         }         let bitmap_bytes = EdgeBitmap::bytes(edge_count);-        let coarse_bytes = (geometry_edges.div_ceil(INTERMEDIATE_BLOCK) + 1)+        let coarse_bytes = (geometry_edges.div_ceil(intermediate_block) + 1)             * std::mem::size_of::<u64>() as u64;         let within_bytes = (geometry_edges + 1) * std::mem::size_of::<u16>() as u64;         let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;@@ -223,7 +225,7 @@ impl Graph {         let sentinel = unsafe {             read_at::<u64>(                 intermediate_coarse,-                (geometry_edges / INTERMEDIATE_BLOCK) as usize,+                (geometry_edges / intermediate_block) as usize,             ) + u64::from(read_at::<u16>(intermediate_within, geometry_edges as usize))         };         if sentinel != blob_bytes || geometry.total(edge_count) != geometry_edges {@@ -387,6 +389,8 @@ impl Graph {             geometry,             intermediate_coarse,             intermediate_within,+            intermediate_varint: varint_v8,+            intermediate_block,             lane_index,             lane_edges,             lane_data,
maps/src/main/rust/src/graph_part3.rs
diff --git a/maps/src/main/rust/src/graph_part3.rs b/maps/src/main/rust/src/graph_part3.rsindex 4e67987983..6e2676a999 100644--- a/maps/src/main/rust/src/graph_part3.rs+++ b/maps/src/main/rust/src/graph_part3.rs@@ -74,7 +74,7 @@ impl Graph {     #[inline]     fn geometry_offset(&self, g: u64) -> u64 {         let coarse =-            unsafe { read_at::<u64>(self.intermediate_coarse, (g / INTERMEDIATE_BLOCK) as usize) };+            unsafe { read_at::<u64>(self.intermediate_coarse, (g / self.intermediate_block) as usize) };         let within = unsafe { read_at::<u16>(self.intermediate_within, g as usize) };         coarse + u64::from(within)     }@@ -267,6 +267,37 @@ impl Graph {         let data = unsafe { self.intermediate_data.add(data_off as usize) };         let mut count: u32 = 1;         let mut off: u32 = 0;+        if self.intermediate_varint {+            // v8: zigzag varint deltas on the 1e-6 degree grid, seeded from the source node's+            // own grid position. Each decoded point lands on a multiple of 10 e7 units.+            let blob = unsafe { std::slice::from_raw_parts(data, byte_len as usize) };+            let mut qlat = (lat as i64).div_euclid(10) + i64::from((lat as i64).rem_euclid(10) >= 5);+            let mut qlon = (lon as i64).div_euclid(10) + i64::from((lon as i64).rem_euclid(10) >= 5);+            let mut at = 0usize;+            let mut uvar = |at: &mut usize| -> Option<u64> {+                let (mut r, mut s) = (0u64, 0u32);+                while *at < blob.len() {+                    let b = blob[*at];+                    *at += 1;+                    r |= u64::from(b & 0x7f) << s;+                    if b & 0x80 == 0 {+                        return Some(r);+                    }+                    s += 7;+                }+                None+            };+            while at < blob.len() && count + 1 < 256 {+                let (Some(a), Some(b)) = (uvar(&mut at), uvar(&mut at)) else { break };+                qlat += ((a >> 1) as i64) ^ -((a & 1) as i64);+                qlon += ((b >> 1) as i64) ^ -((b & 1) as i64);+                out[count as usize] = LatLon { lat_e7: (qlat * 10) as i32, lon_e7: (qlon * 10) as i32 };+                count += 1;+            }+            let b = self.node(target);+            out[count as usize] = LatLon { lat_e7: b.lat_e7, lon_e7: b.lon_e7 };+            return count + 1;+        }         // One slot is reserved for the target, so the interior stops one short of         // the 256 points every caller's buffer holds.         while off + 4 <= byte_len && count + 1 < 256 {
maps/src/main/rust/src/graph_part4.rs
diff --git a/maps/src/main/rust/src/graph_part4.rs b/maps/src/main/rust/src/graph_part4.rsindex f993541061..63a5566d84 100644--- a/maps/src/main/rust/src/graph_part4.rs+++ b/maps/src/main/rust/src/graph_part4.rs@@ -111,7 +111,9 @@ impl Graph {         let edge_count = edges;         let escape_count = escapes;         let named_edges = named;-        let blocked_v7 = version >= GRAPH_VERSION;+        let blocked_v7 = version >= tilecodec::mamaps::archive::GRAPH_VERSION_BLOCKED;+        let varint_v8 = version >= tilecodec::mamaps::archive::GRAPH_VERSION_VARINT;+        let intermediate_block = if varint_v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };          // `edge_count` comes from the header rather than from the edges         // payload's length. That is the point of graph version 4, and 5 and 6@@ -239,7 +241,7 @@ impl Graph {             return None;         }         let bitmap_bytes = EdgeBitmap::bytes(edge_count);-        let coarse_bytes = (geometry_edges.div_ceil(INTERMEDIATE_BLOCK) + 1)+        let coarse_bytes = (geometry_edges.div_ceil(intermediate_block) + 1)             * std::mem::size_of::<u64>() as u64;         let within_bytes = (geometry_edges + 1) * std::mem::size_of::<u16>() as u64;         let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;@@ -266,7 +268,7 @@ impl Graph {         let sentinel = unsafe {             read_at::<u64>(                 intermediate_coarse,-                (geometry_edges / INTERMEDIATE_BLOCK) as usize,+                (geometry_edges / intermediate_block) as usize,             ) + u64::from(read_at::<u16>(intermediate_within, geometry_edges as usize))         };         if sentinel != blob_bytes || geometry.total(edge_count) != geometry_edges {@@ -458,6 +460,8 @@ impl Graph {             geometry,             intermediate_coarse,             intermediate_within,+            intermediate_varint: varint_v8,+            intermediate_block,             lane_index,             lane_edges,             lane_data,