maps: size_lab + graph_thin measurement tools for planet size (#planet5)
- Commit
7f8d55f8382d47aa9488a20255ea7661e750ed4e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 23:23 UTC (22 days ago)
- Parents
86a4c35
Measurement tooling for the planet-size study, all examples/ targets with dev-dependencies only, so nothing reaches a shipping binary or the Android cdylib. tile_build/examples/size_lab (modes): - bodies: stratified per-zoom sample of unique bodies, re-encoded under each codec (DEFLATE-9, zstd 19 C and pure-Rust, trained per-band dictionaries) and each data transform (DEM drop/quantise/adaptive/ delta, coordinate snapping, landtype/road simplification, layer and table drops); planet projection by a per-zoom ratio estimator against exact stored totals; host decode timings. - sidecars: 64 KiB-block zstd compressibility of every sidecar; ZBLK sections decoded and re-encoded. - recompress: exact whole-archive tile data under zstd-rs 19, +dictionaries, C zstd 19/22, with per-tile decode+parse time. - cmp: base vs candidate geometry deviation per zoom band and layer (vertex-to-segment, Hausdorff, dropped features) and DEM surface error on a 33x33 lattice. - render: side-by-side software renders of one tile from several archives (native zoom or overzoomed crop) for visual review. - dem-pyramid: savings if heightmaps inherited from ancestors within a tolerance (a format change; measured to rule it in or out). - transit: exact SHAPE_COORDS size after stop-preserving DP thinning, EXCEPTIONS packed size, and the unread ROUTE_TRIPS stream. - zblk: ZBLK re-encode at zstd 10/19/22 and 4096/16384-record blocks with per-block decode cost. - zooms: exact stored bytes per zoom. maps/src/main/rust/examples/graph_thin: error-bounded DP thinning of a routing graph's intermediate.bin keeping its layout (presence bitmap copied, offsets rebuilt, i16 delta overflow bridged, bound re-checked after bridging), optional keep-zone around junctions, and validation by loading the result with the real Graph reader. Reports varint/1e-6 deg format-change estimates for the thinned blob. Verified on the planet archive and US West builds (numbers in the planet-size report).
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex af96780b62..b913c6d57a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5512,9 +5512,13 @@ version = "0.1.0" dependencies = [ "memmap2", "miniz_oxide 0.8.9",+ "png", "rayon",+ "ruzstd", "sha2 0.11.1", "tilecodec",+ "zstd",+ "zstd-rs", ] [[package]]
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.rsnew file mode 100644index 0000000000..1ea4cc5d4d--- /dev/null+++ b/maps/src/main/rust/examples/graph_thin.rs@@ -0,0 +1,300 @@+//! `graph_thin` — planet-size prototype: error-bounded shape-point thinning of a routing graph's+//! `intermediate.bin`, keeping the on-disk layout (no reader change).+//!+//! ```text+//! cargo run --release --example graph_thin -- IN_GRAPH_DIR OUT_GRAPH_DIR TOL_CM+//! ```+//!+//! Every stored polyline (source node + interior points + target node) is Douglas-Peucker+//! simplified with tolerance `TOL_CM` (perpendicular distance in centimetres on a local+//! equirectangular projection), endpoints always kept — so straight runs collapse to their+//! endpoints and bends keep exactly the vertices that carry them. Interior points are re-added+//! wherever a gap would overflow the format's `i16` e7 delta (~365 m), so the result is always+//! encodable. `edges.bin` distances and times are untouched (route length / ETA cannot move);+//! only the decoded polyline does, by at most `TOL_CM` from the original.+//!+//! The presence bitmap and its rank index are copied verbatim (an edge whose interior empties+//! keeps an empty blob), so `G` and every edge's geometry rank are unchanged; only the blob and+//! the two-level offset table are rebuilt. Every other graph file is copied. Also reports the+//! size the thinned polylines would take under two candidate *format changes*: zigzag-varint+//! deltas, and the same at a 1e-6 degree (~11 cm) grid.+//!+//! Experiment tooling (examples/): never in the cdylib.++use offlinerouter::graph::{Graph, LatLon, INTERMEDIATE_BLOCK};++fn read_u64(b: &[u8], at: usize) -> u64 {+ u64::from_le_bytes(b[at..at + 8].try_into().unwrap())+}++fn seg_dist_sq(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l2 = dx * dx + dy * dy;+ if l2 == 0.0 {+ return (p.0 - a.0).powi(2) + (p.1 - a.1).powi(2);+ }+ let t = (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0);+ let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);+ (p.0 - qx).powi(2) + (p.1 - qy).powi(2)+}++fn dp(pts: &[(f64, f64)], tol_sq: f64, keep: &mut [bool]) {+ let mut stack = vec![(0usize, pts.len() - 1)];+ while let Some((a, b)) = stack.pop() {+ if b <= a + 1 {+ continue;+ }+ let (mut worst, mut wi) = (0.0, a);+ for i in a + 1..b {+ let d = seg_dist_sq(pts[i], pts[a], pts[b]);+ if d > worst {+ worst = d;+ wi = i;+ }+ }+ if worst > tol_sq {+ keep[wi] = true;+ stack.push((a, wi));+ stack.push((wi, b));+ }+ }+}++fn push_uvarint(out: &mut usize, mut v: u64) {+ loop {+ *out += 1;+ v >>= 7;+ if v == 0 {+ break;+ }+ }+}++fn zz(v: i64) -> u64 {+ ((v << 1) ^ (v >> 63)) as u64+}++fn main() -> std::process::ExitCode {+ let a: Vec<String> = std::env::args().skip(1).collect();+ if a.len() < 3 {+ eprintln!("usage: graph_thin IN_GRAPH_DIR OUT_GRAPH_DIR TOL_CM");+ return std::process::ExitCode::from(2);+ }+ let (inp, outp) = (a[0].trim_end_matches('/'), a[1].trim_end_matches('/'));+ let tol_cm: f64 = a[2].parse().expect("TOL_CM");+ // Optional: keep every shape point within KEEP_END_M (along the line) of either node, so+ // the approach/exit bearings guidance derives maneuvers from are untouched ("full detail+ // at junctions").+ let keep_end_m: f64 = a.get(3).map(|v| v.parse().expect("KEEP_END_M")).unwrap_or(0.0);+ let g = Graph::load(&format!("{inp}/")).expect("load graph");+ let inter = std::fs::read(format!("{inp}/intermediate.bin")).expect("read intermediate");+ 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 within_bytes = (gcount + 1) * 2;+ let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;+ let blob_len = inter.len() as u64 - trailer;+ let bitmap = &inter[blob_len as usize..(blob_len + bitmap_bytes) as usize];+ let present_off = ((e.div_ceil(512) + 1) * 8) as usize;+ let present = &bitmap[present_off..];++ 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 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);+ let (mut var_e7, mut var_e6) = (0usize, 0usize);+ let mut max_dev_m = 0.0f64;+ let mut rank = 0u64;+ let mut block_start = 0u64;+ for idx in 0..e {+ if present[(idx / 8) as usize] & (1 << (idx % 8)) == 0 {+ continue;+ }+ if rank % INTERMEDIATE_BLOCK == 0 {+ block_start = blob.len() as u64;+ coarse.push(block_start);+ }+ within.push((blob.len() as u64 - block_start) as u16);+ 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 {+ panic!("edge {idx} present in the bitmap but not decodable");+ };+ assert!(!rev, "a stored polyline decoded reversed");+ let cnt = cnt as usize;+ if cnt < 3 {+ continue;+ }+ let poly = &buf[..cnt];+ pts_in += (cnt - 2) as u64;+ // Local metres: equirectangular about the source.+ let lat0 = poly[0].lat_e7 as f64 * 1e-7;+ let kx = 0.011_131_949 * lat0.to_radians().cos(); // m per e7 unit of lon (×1e-7 deg × 111319.49 m)+ let ky = 0.011_131_949;+ let xy: Vec<(f64, f64)> = poly+ .iter()+ .map(|p| ((p.lon_e7 - poly[0].lon_e7) as f64 * kx, (p.lat_e7 - poly[0].lat_e7) as f64 * ky))+ .collect();+ let mut keep = vec![false; cnt];+ keep[0] = true;+ keep[cnt - 1] = true;+ if tol_m > 0.0 {+ dp(&xy, tol_m * tol_m, &mut keep);+ if keep_end_m > 0.0 {+ let mut acc = vec![0.0f64; cnt];+ for k in 1..cnt {+ acc[k] = acc[k - 1] + ((xy[k].0 - xy[k - 1].0).powi(2) + (xy[k].1 - xy[k - 1].1).powi(2)).sqrt();+ }+ let total = acc[cnt - 1];+ for k in 1..cnt - 1 {+ if acc[k] <= keep_end_m || total - acc[k] <= keep_end_m {+ keep[k] = true;+ }+ }+ }+ } else {+ keep.iter_mut().for_each(|k| *k = true);+ }+ // i16 delta bridging: walk kept points, re-adding the farthest in-range original point+ // whenever the next kept point is out of delta range of the previous one.+ let fits = |a: &LatLon, b: &LatLon| {+ (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;+ while i < cnt - 1 {+ if !keep[i] {+ i += 1;+ continue;+ }+ let prev = *out_idx.last().unwrap();+ if fits(&poly[prev], &poly[i]) {+ out_idx.push(i);+ i += 1;+ } else {+ // Farthest original point after prev that still fits (always prev+1 at worst,+ // since the original encoded every consecutive pair).+ let mut j = prev + 1;+ while j + 1 < i && fits(&poly[prev], &poly[j + 1]) {+ j += 1;+ }+ out_idx.push(j);+ readded += 1;+ }+ }+ // Bridging re-adds split DP's chords, which can leave a dropped vertex farther than the+ // tolerance from the new, shorter chord: restore the bound by re-inserting the worst+ // vertex of any span that breaks it, until none does (only ever adds points, so the+ // i16 fit established above still holds).+ let mut kept: Vec<usize> = out_idx.iter().copied().chain(std::iter::once(cnt - 1)).collect();+ if tol_m > 0.0 {+ loop {+ let mut changed = false;+ let mut next = Vec::with_capacity(kept.len() + 4);+ for w in kept.windows(2) {+ next.push(w[0]);+ let (mut worst, mut wi) = (tol_m * tol_m, usize::MAX);+ for k in w[0] + 1..w[1] {+ let d = seg_dist_sq(xy[k], xy[w[0]], xy[w[1]]);+ if d > worst {+ worst = d;+ wi = k;+ }+ }+ if wi != usize::MAX {+ next.push(wi);+ changed = true;+ }+ }+ next.push(cnt - 1);+ kept = next;+ if !changed {+ break;+ }+ }+ out_idx = kept[..kept.len() - 1].to_vec();+ }+ // Deviation of the thinned polyline from every dropped original vertex: the exact+ // max over the original vertices (straight original segments between them cannot+ // stray farther than their endpoints from a chord).++ for w in kept.windows(2) {+ for k in w[0] + 1..w[1] {+ max_dev_m = max_dev_m.max(seg_dist_sq(xy[k], xy[w[0]], xy[w[1]]).sqrt());+ }+ }+ // 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);+ for &k in &out_idx[1..] {+ let p = poly[k];+ let dl = (p.lat_e7 - prev.lat_e7) as i16;+ let dn = (p.lon_e7 - prev.lon_e7) as i16;+ blob.extend_from_slice(&dl.to_le_bytes());+ blob.extend_from_slice(&dn.to_le_bytes());+ push_uvarint(&mut var_e7, zz((p.lat_e7 - prev.lat_e7) as i64));+ push_uvarint(&mut var_e7, zz((p.lon_e7 - prev.lon_e7) as i64));+ let q = ((p.lat_e7 as f64 / 10.0).round() as i32, (p.lon_e7 as f64 / 10.0).round() as i32);+ push_uvarint(&mut var_e6, zz((q.0 - prev6.0) as i64));+ push_uvarint(&mut var_e6, zz((q.1 - prev6.1) as i64));+ prev = p;+ prev6 = q;+ pts_out += 1;+ }+ }+ assert_eq!(rank, gcount, "geometry rank count");+ // Sentinel: the blob length, in the final block's slot.+ if rank % INTERMEDIATE_BLOCK == 0 {+ coarse.push(blob.len() as u64);+ block_start = blob.len() as u64;+ }+ within.push((blob.len() as u64 - block_start) as u16);+ // 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 {+ coarse.push(blob.len() as u64);+ }+ assert_eq!(coarse.len() as u64 * 8, 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");+ for f in std::fs::read_dir(inp).expect("readdir") {+ let f = f.unwrap();+ let name = f.file_name().into_string().unwrap();+ if name == "intermediate.bin" || !f.file_type().unwrap().is_file() {+ continue;+ }+ std::fs::copy(f.path(), format!("{outp}/{name}")).expect("copy");+ }+ let mut out = blob;+ let new_blob = out.len();+ out.extend_from_slice(bitmap);+ for c in &coarse {+ out.extend_from_slice(&c.to_le_bytes());+ }+ for w in &within {+ out.extend_from_slice(&w.to_le_bytes());+ }+ out.extend_from_slice(&gcount.to_le_bytes());+ std::fs::write(format!("{outp}/intermediate.bin"), &out).expect("write");+ // 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}, \+ 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,+ inter.len(),+ out.len(),+ blob_len,+ new_blob,+ trailer,+ var_e7,+ var_e6+ );+ std::process::ExitCode::SUCCESS+}
scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex 3b808c927c..e5b4ec1ad3 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -55,3 +55,13 @@ sha2.workspace = true memmap2.workspace = true [profile.release] opt-level = 3++# Size-lab experiment (examples/size_lab.rs) only: the C zstd reference+# encoder + dictionary trainer, and the two pure-Rust codecs the shipping+# path uses (zstd-rs encode, ruzstd decode), measured side by side. Never+# linked into the shipping binaries.+[dev-dependencies]+zstd.workspace = true+zstd-rs.workspace = true+ruzstd.workspace = true+png.workspace = true
scripts/maps/tile_build/examples/size_lab.rs
diff --git a/scripts/maps/tile_build/examples/size_lab.rs b/scripts/maps/tile_build/examples/size_lab.rsnew file mode 100644index 0000000000..8f86bc974b--- /dev/null+++ b/scripts/maps/tile_build/examples/size_lab.rs@@ -0,0 +1,1006 @@+//! `size_lab` — measured size experiments on a real `.mamaps` (planet-size study).+//!+//! Usage:+//! size_lab bodies IN.mamaps [PER_ZOOM] [OUT_DIR]+//! size_lab sidecars IN.mamaps [WINDOWS] [OUT_DIR]+//!+//! `bodies`: stratified sample of unique tile bodies per zoom (stride over the+//! deduplicated data section), every body re-encoded under each codec and each+//! data transform; per-zoom totals are scaled with a ratio estimator against+//! the zoom's exact stored total, so the planet projection is+//! `sum_z exact_stored_z * (variant_sample_z / stored_sample_z)`.+//! Dictionaries are trained on a disjoint sample (offset by half a stride).+//!+//! `sidecars`: per sidecar section, WINDOWS evenly spaced 1 MiB windows, each+//! cut into independent 64 KiB blocks (what a random-access mmap reader would+//! inflate), compressed with zstd 19 (C reference and the pure-Rust zstd-rs+//! the build would ship). ZBLK sections are decoded and recompressed.+//!+//! Experiment tooling only (examples/, dev-dependencies): nothing here is in a+//! shipping binary.+use std::collections::BTreeMap;+use std::fs::File;+use std::io::Write as _;+use std::sync::Mutex;+use std::time::Instant;++use rayon::prelude::*;+use tile_build::mamaps::body::{Body, Heightmap, Layer, Part, Scratch, GEOM_POINT, GEOM_POLYGON};+use tile_build::mamaps::dict::Dictionary;+use tile_build::mamaps::{header, index};+use tilecodec::pmtiles::tile_zxy;++const H: usize = tile_build::mamaps::body::BODY_HEADER_LEN;++#[derive(Clone, Copy)]+struct Ent {+ z: u8,+ off: u64,+ len: u32,+}++fn zstd_c(data: &[u8], level: i32) -> usize {+ zstd::bulk::compress(data, level).expect("zstd").len()+}++fn zstd_c_dict(c: &mut zstd::bulk::Compressor<'_>, data: &[u8]) -> Vec<u8> {+ c.compress(data).expect("zstd dict")+}++fn zstd_rs(data: &[u8], level: i32) -> Vec<u8> {+ let cfg = zstd_rs::CompressionConfig { level, ..zstd_rs::CompressionConfig::DEFAULT };+ let mut enc = zstd_rs::Compressor::new(cfg).expect("cfg");+ let mut out = Vec::new();+ enc.compress(data, None, &mut out).expect("zstd-rs");+ out+}++fn zstd_rs_dict(data: &[u8], level: i32, d: &zstd_rs::EncoderDictionary) -> Vec<u8> {+ let cfg = zstd_rs::CompressionConfig { level, ..zstd_rs::CompressionConfig::DEFAULT };+ let mut enc = zstd_rs::Compressor::new(cfg).expect("cfg");+ let mut out = Vec::new();+ enc.compress(data, Some(d), &mut out).expect("zstd-rs dict");+ out+}++fn deflate9(data: &[u8]) -> usize {+ miniz_oxide::deflate::compress_to_vec(data, 9).len()+}++fn band(z: u8) -> usize {+ match z {+ 0..=9 => 0,+ 10..=11 => 1,+ 12 => 2,+ 13 => 3,+ _ => 4,+ }+}+const BANDS: [&str; 5] = ["z0-9", "z10-11", "z12", "z13", "z14"];++// ---------------------------------------------------------------- transforms++fn ser(body: &Body) -> Vec<u8> {+ let mut s = Scratch::default();+ match tile_build::mamaps::body::serialize_into_v10(body, &mut s) {+ Ok(b) => b.to_vec(),+ Err(e) if e.0.contains("marking convention") => {+ // A transform dropped every feature with a non-default carriageway:+ // the sparse table is then empty and the convention must go too.+ let mut b = body.clone();+ b.convention = None;+ b.carriageways.clear();+ let mut s = Scratch::default();+ tile_build::mamaps::body::serialize_into_v10(&b, &mut s).expect("serialize").to_vec()+ }+ Err(e) => panic!("serialize: {e:?}"),+ }+}++/// Rebuild a layer keeping only features `keep` says yes to, with per-part+/// coordinate rewriting through `edit` (None = drop the part).+fn rebuild_layer(+ layer: &Layer,+ mut keep: impl FnMut(usize) -> bool,+ mut edit: impl FnMut(u8, &[(i16, i16)], u16) -> Option<Vec<(i16, i16)>>,+) -> (Layer, Vec<usize>) {+ let mut nl = Layer::new(layer.layer_id);+ let mut kept = Vec::new();+ for (i, f) in layer.features.iter().enumerate() {+ if !keep(i) {+ continue;+ }+ let start = nl.parts.len() as u32;+ let from = f.parts_offset as usize;+ let mut np = 0u32;+ for p in &layer.parts[from..from + f.part_count as usize] {+ let pts = layer.points(p);+ let Some(out) = edit(f.geom_type, pts, p.winding) else { continue };+ nl.parts.push(Part { coord_start: nl.coords.len() as u32, point_count: out.len() as u32, winding: p.winding });+ nl.coords.extend_from_slice(&out);+ np += 1;+ }+ if np == 0 {+ nl.parts.truncate(start as usize);+ continue;+ }+ let mut nf = *f;+ nf.parts_offset = start;+ nf.part_count = np;+ nl.features.push(nf);+ kept.push(i);+ }+ (nl, kept)+}++/// Filter every dense-parallel side table of `layer_id` down to `kept`.+fn filter_tables(body: &mut Body, layer_id: u8, kept: &[usize]) {+ fn f<T: Clone>(v: &mut Vec<(u8, Vec<T>)>, id: u8, kept: &[usize]) {+ for (lid, t) in v.iter_mut() {+ if *lid == id {+ *t = kept.iter().map(|&i| t[i].clone()).collect();+ }+ }+ v.retain(|(_, t)| !t.is_empty());+ }+ f(&mut body.ids, layer_id, kept);+ f(&mut body.turn_lanes, layer_id, kept);+ f(&mut body.buildings, layer_id, kept);+ f(&mut body.carriageways, layer_id, kept);+ f(&mut body.region_links, layer_id, kept);+ if body.carriageways.is_empty() {+ body.convention = None;+ }+}++fn apply_layer(+ body: &Body,+ layer_id: u8,+ keep: impl FnMut(&Layer, usize) -> bool,+ edit: impl FnMut(u8, &[(i16, i16)], u16) -> Option<Vec<(i16, i16)>>,+) -> Body {+ let mut b = body.clone();+ let Some(pos) = b.layers.iter().position(|l| l.layer_id == layer_id) else { return b };+ let layer = b.layers[pos].clone();+ let mut keep = keep;+ let (nl, kept) = rebuild_layer(&layer, |i| keep(&layer, i), edit);+ if nl.features.is_empty() {+ b.layers.remove(pos);+ } else {+ b.layers[pos] = nl;+ }+ filter_tables(&mut b, layer_id, &kept);+ // Names no longer referenced are kept (the name table is per tile); a+ // real build would drop them, so this slightly understates savings.+ b+}++fn ring_area2(pts: &[(i16, i16)]) -> i64 {+ let mut a = 0i64;+ for i in 0..pts.len() {+ let (x0, y0) = pts[i];+ let (x1, y1) = pts[(i + 1) % pts.len()];+ a += x0 as i64 * y1 as i64 - x1 as i64 * y0 as i64;+ }+ a.abs()+}++fn line_len(pts: &[(i16, i16)]) -> f64 {+ pts.windows(2)+ .map(|w| (((w[1].0 - w[0].0) as f64).powi(2) + ((w[1].1 - w[0].1) as f64).powi(2)).sqrt())+ .sum()+}++fn dp(pts: &[(i16, i16)], tol: f64, keep: &mut [bool], a: usize, b: usize) {+ if b <= a + 1 {+ return;+ }+ let (ax, ay) = (pts[a].0 as f64, pts[a].1 as f64);+ let (bx, by) = (pts[b].0 as f64, pts[b].1 as f64);+ let (dx, dy) = (bx - ax, by - ay);+ let l2 = dx * dx + dy * dy;+ let mut best = 0.0;+ let mut bi = a;+ for (i, p) in pts.iter().enumerate().take(b).skip(a + 1) {+ let (px, py) = (p.0 as f64, p.1 as f64);+ let d = if l2 == 0.0 {+ ((px - ax).powi(2) + (py - ay).powi(2)).sqrt()+ } else {+ ((dy * px - dx * py + bx * ay - by * ax).abs()) / l2.sqrt()+ };+ if d > best {+ best = d;+ bi = i;+ }+ }+ if best > tol {+ keep[bi] = true;+ dp(pts, tol, keep, a, bi);+ dp(pts, tol, keep, bi, b);+ }+}++fn simplify(geom: u8, pts: &[(i16, i16)], tol: f64) -> Vec<(i16, i16)> {+ if geom == GEOM_POINT || pts.len() < 4 {+ return pts.to_vec();+ }+ let n = pts.len();+ let mut keep = vec![false; n];+ keep[0] = true;+ keep[n - 1] = true;+ if geom == GEOM_POLYGON {+ // Closed ring: anchor at first point and the farthest point from it.+ let far = (1..n)+ .max_by_key(|&i| {+ let dx = (pts[i].0 - pts[0].0) as i64;+ let dy = (pts[i].1 - pts[0].1) as i64;+ dx * dx + dy * dy+ })+ .unwrap_or(n - 1);+ keep[far] = true;+ dp(pts, tol, &mut keep, 0, far);+ dp(pts, tol, &mut keep, far, n - 1);+ } else {+ dp(pts, tol, &mut keep, 0, n - 1);+ }+ let out: Vec<_> = pts.iter().zip(&keep).filter(|(_, k)| **k).map(|(p, _)| *p).collect();+ let min = if geom == GEOM_POLYGON { 4 } else { 2 };+ if out.len() < min { pts.to_vec() } else { out }+}++fn snap(geom: u8, pts: &[(i16, i16)], q: i16) -> Vec<(i16, i16)> {+ if geom == GEOM_POINT {+ return pts.to_vec();+ }+ let s = |v: i16| -> i16 {+ let r = ((v as i32 + (q as i32) / 2).div_euclid(q as i32)) * q as i32;+ r.clamp(i16::MIN as i32, i16::MAX as i32) as i16+ };+ let mut out: Vec<(i16, i16)> = Vec::with_capacity(pts.len());+ for &(x, y) in pts {+ let p = (s(x), s(y));+ if out.last() != Some(&p) {+ out.push(p);+ }+ }+ let min = if geom == GEOM_POLYGON { 4 } else { 2 };+ if out.len() < min { pts.to_vec() } else { out }+}++fn hm_quant(hm: &Heightmap, step: i32) -> Heightmap {+ Heightmap {+ dim: hm.dim,+ samples: hm+ .samples+ .iter()+ .map(|&s| {+ let m = s as i32 - 32768;+ let q = ((m as f64 / step as f64).round() as i32) * step;+ (q + 32768).clamp(0, 65535) as u16+ })+ .collect(),+ }+}++/// Subsample a dim-N grid to ceil(N/2)+? keeping corners (N odd -> (N+1)/2).+fn hm_half(hm: &Heightmap) -> Heightmap {+ let d = hm.dim as usize;+ if d < 3 {+ return hm.clone();+ }+ let idx: Vec<usize> = if d % 2 == 1 { (0..d).step_by(2).collect() } else {+ let mut v: Vec<usize> = (0..d).step_by(2).collect();+ if *v.last().unwrap() != d - 1 { v.push(d - 1); }+ v+ };+ let mut samples = Vec::with_capacity(idx.len() * idx.len());+ for &r in &idx {+ for &c in &idx {+ samples.push(hm.samples[r * d + c]);+ }+ }+ Heightmap { dim: idx.len() as u16, samples }+}++/// Format-change simulation: 2D predictive (left, or up for column 0) zigzag+/// residuals stored in the same u16 slots, so only entropy changes.+fn hm_delta(hm: &Heightmap) -> Heightmap {+ let d = hm.dim as usize;+ let mut out = vec![0u16; hm.samples.len()];+ for r in 0..d {+ for c in 0..d {+ let v = hm.samples[r * d + c] as i32;+ let pred = if c > 0 {+ let l = hm.samples[r * d + c - 1] as i32;+ if r > 0 {+ let u = hm.samples[(r - 1) * d + c] as i32;+ let ul = hm.samples[(r - 1) * d + c - 1] as i32;+ (l + u - ul).clamp(l.min(u), l.max(u)) // MED/LOCO-I predictor+ } else {+ l+ }+ } else if r > 0 {+ hm.samples[(r - 1) * d] as i32+ } else {+ 32768+ };+ let e = v - pred;+ out[r * d + c] = ((e << 1) ^ (e >> 31)) as u16;+ }+ }+ Heightmap { dim: hm.dim, samples: out }+}++/// Bilinear reconstruction of grid `g` (dim `dg`) at fractional position (fr, fc) in [0,1].+fn bilin(g: &[u16], dg: usize, fr: f64, fc: f64) -> f64 {+ let gr = fr * (dg - 1) as f64;+ let gc = fc * (dg - 1) as f64;+ let r0 = (gr.floor() as usize).min(dg - 1);+ let c0 = (gc.floor() as usize).min(dg - 1);+ let r1 = (r0 + 1).min(dg - 1);+ let c1 = (c0 + 1).min(dg - 1);+ let (fy, fx) = (gr - r0 as f64, gc - c0 as f64);+ let at = |r: usize, c: usize| g[r * dg + c] as f64;+ let top = at(r0, c0) * (1.0 - fx) + at(r0, c1) * fx;+ let bot = at(r1, c0) * (1.0 - fx) + at(r1, c1) * fx;+ top * (1.0 - fy) + bot * fy+}++/// (max abs, sum sq, n) error of `new` against `orig`, evaluated at every original sample.+/// Both surfaces are bilinear and the coarse grid's nodes are a subset of the fine grid's,+/// so the difference is bilinear inside each fine cell: the max over these nodes IS the max+/// over the whole continuous surface.+fn hm_err(orig: &Heightmap, new: &Heightmap) -> (f64, f64, u64) {+ let d = orig.dim as usize;+ let dn = new.dim as usize;+ let mut mx = 0.0f64;+ let mut ss = 0.0f64;+ for r in 0..d {+ for c in 0..d {+ let fr = r as f64 / (d - 1) as f64;+ let fc = c as f64 / (d - 1) as f64;+ let e = (bilin(&new.samples, dn, fr, fc) - orig.samples[r * d + c] as f64).abs();+ mx = mx.max(e);+ ss += e * e;+ }+ }+ (mx, ss, (d * d) as u64)+}++fn subsample(hm: &Heightmap, dn: usize) -> Heightmap {+ let d = hm.dim as usize;+ let mut s = Vec::with_capacity(dn * dn);+ for r in 0..dn {+ for c in 0..dn {+ s.push(hm.samples[(r * (d - 1) / (dn - 1)) * d + c * (d - 1) / (dn - 1)]);+ }+ }+ Heightmap { dim: dn as u16, samples: s }+}++/// Error-bounded adaptive grid: the coarsest aligned sub-grid (dim-1 divisible by dn-1) whose+/// bilinear reconstruction stays within tol/2 of the full grid, then elevation quantised to a+/// step of floor(tol) metres (rounding error <= tol/2). Total max error <= tol by construction.+/// No format change: dim is per tile on the wire already.+fn hm_adapt(hm: &Heightmap, tol: f64) -> Heightmap {+ let d = hm.dim as usize;+ let mut cands: Vec<usize> = (2..=d).filter(|dn| (d - 1) % (dn - 1) == 0).collect();+ cands.sort();+ let mut pick = hm.clone();+ for dn in cands {+ let sub = subsample(hm, dn);+ if hm_err(hm, &sub).0 <= tol / 2.0 + 1e-9 {+ pick = sub;+ break;+ }+ }+ let q = tol.floor().max(1.0) as i32;+ if q > 1 { hm_quant(&pick, q) } else { pick }+}++struct Ids {+ landtype: u8,+ roads: u8,+ buildings: u8,+ junction: u8,+}++/// Named transforms; each returns the transformed body (or None = unchanged).+fn transforms() -> Vec<&'static str> {+ vec![+ "identity_v10",+ "hm_drop",+ "hm_q2m",+ "hm_q4m",+ "hm_half_dim",+ "hm_delta*",+ "hm_adapt1m",+ "hm_adapt2m",+ "hm_adapt5m",+ "hm_adapt2m_delta*",+ "hm_delta_q2m*",+ "coord_q2_le13",+ "coord_q4_le12_q2_13",+ "landtype_simp2_le13",+ "landtype_simp4_le13",+ "landtype_dropsmall_le13",+ "roads_simp2_le13",+ "junction_drop",+ "buildings_drop_attrs",+ "ids_drop",+ "names_drop",+ "combo_A",+ "combo_B*",+ ]+}++fn apply(name: &str, body: &Body, z: u8, ids: &Ids) -> Body {+ let mut b = body.clone();+ match name {+ "identity_v10" => {}+ "hm_drop" => b.heightmap = None,+ "hm_q2m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_quant(h, 2)),+ "hm_q4m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_quant(h, 4)),+ "hm_half_dim" => b.heightmap = b.heightmap.as_ref().map(hm_half),+ "hm_delta*" => b.heightmap = b.heightmap.as_ref().map(hm_delta),+ "hm_adapt1m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_adapt(h, 1.0)),+ "hm_adapt2m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_adapt(h, 2.0)),+ "hm_adapt5m" => b.heightmap = b.heightmap.as_ref().map(|h| hm_adapt(h, 5.0)),+ "hm_adapt2m_delta*" => b.heightmap = b.heightmap.as_ref().map(|h| hm_delta(&hm_adapt(h, 2.0))),+ "hm_delta_q2m*" => b.heightmap = b.heightmap.as_ref().map(|h| hm_delta(&hm_quant(h, 2))),+ "coord_q2_le13" | "coord_q4_le12_q2_13" => {+ if z <= 13 {+ let q = if name == "coord_q4_le12_q2_13" && z <= 12 { 4 } else { 2 };+ for l in b.layers.clone() {+ b = apply_layer(&b, l.layer_id, |_, _| true, |g, p, _| Some(snap(g, p, q)));+ }+ }+ }+ "landtype_simp2_le13" | "landtype_simp4_le13" => {+ if z <= 13 {+ let tol = if name.contains("simp4") { 4.0 } else { 2.0 };+ b = apply_layer(&b, ids.landtype, |_, _| true, |g, p, _| Some(simplify(g, p, tol)));+ }+ }+ "roads_simp2_le13" => {+ if z <= 13 {+ b = apply_layer(&b, ids.roads, |_, _| true, |g, p, _| Some(simplify(g, p, 2.0)));+ }+ }+ "landtype_dropsmall_le13" => {+ if z <= 13 {+ // < 2x2 px of a 512 px tile (8 units/px): polygons under 256 units^2,+ // lines under 16 units. Holes under the same area are dropped too.+ b = apply_layer(+ &b,+ ids.landtype,+ |l, i| {+ let f = &l.features[i];+ let from = f.parts_offset as usize;+ let parts = &l.parts[from..from + f.part_count as usize];+ if f.geom_type == GEOM_POLYGON {+ let outer: i64 = parts.iter().filter(|p| !p.is_hole()).map(|p| ring_area2(l.points(p))).sum();+ outer / 2 >= 256+ } else if f.geom_type == GEOM_POINT {+ true+ } else {+ parts.iter().map(|p| line_len(l.points(p))).sum::<f64>() >= 16.0+ }+ },+ |g, p, w| {+ if g == GEOM_POLYGON && w == tile_build::mamaps::body::WINDING_HOLE && ring_area2(p) / 2 < 256 {+ None+ } else {+ Some(p.to_vec())+ }+ },+ );+ }+ }+ "junction_drop" => {+ b = apply_layer(&b, ids.junction, |_, _| false, |_, p, _| Some(p.to_vec()));+ }+ "buildings_drop_attrs" => b.buildings.clear(),+ "ids_drop" => b.ids.clear(),+ "names_drop" => {+ b.names.clear();+ for l in &mut b.layers {+ for f in &mut l.features {+ f.name_idx = tile_build::mamaps::body::NAME_NONE;+ }+ }+ }+ "combo_A" => {+ // No format change: hm 2 m quant + half dim at z<=12, coord q2 at z<=13,+ // landtype simp2 + drop-small at z<=13.+ b.heightmap = b.heightmap.as_ref().map(|h| {+ let q = hm_quant(h, 2);+ if z <= 12 { hm_half(&q) } else { q }+ });+ if z <= 13 {+ b = apply(+ "landtype_dropsmall_le13",+ &apply("landtype_simp2_le13", &b, z, ids),+ z,+ ids,+ );+ b = apply("coord_q2_le13", &b, z, ids);+ }+ }+ "combo_B*" => {+ b = apply("combo_A", &b, z, ids);+ b.heightmap = b.heightmap.as_ref().map(hm_delta);+ }+ _ => unreachable!("{name}"),+ }+ let _ = ids.buildings;+ b+}++// ---------------------------------------------------------------- bodies++struct Arch {+ map: memmap2::Mmap,+ hdr: header::Header,+ dict: Dictionary,+}++fn open(path: &str) -> Arch {+ let f = File::open(path).expect("open");+ let map = unsafe { memmap2::Mmap::map(&f).expect("mmap") };+ let hdr = header::Header::parse(&map[..tilecodec::stream::OPEN_PREFIX_BYTES as usize]).expect("header");+ let dict = Dictionary::parse(&map[hdr.dict_offset as usize..hdr.dict_offset as usize + hdr.dict_len as usize]).expect("dict");+ Arch { map, hdr, dict }+}++fn entries(a: &Arch) -> Vec<Ent> {+ let hdr = &a.hdr;+ let root = index::parse_root(&a.map[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize]).expect("root");+ let per: Vec<Vec<Ent>> = root+ .par_iter()+ .map(|re| {+ let raw_len = re.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;+ let at = (hdr.leaf_offset + re.leaf_offset) as usize;+ let raw = if re.stored_len == 0 {+ a.map[at..at + raw_len].to_vec()+ } else {+ index::decompress_leaf(&a.map[at..at + re.stored_len as usize], raw_len).expect("leaf")+ };+ index::parse_leaf(&raw)+ .expect("leaf")+ .iter()+ .map(|e| {+ let (z, _, _) = tile_zxy(re.base_tile_id + e.tile_id_lo as u64);+ Ent { z, off: hdr.data_offset + re.base_data_offset + e.offset_delta as u64, len: e.length }+ })+ .collect()+ })+ .collect();+ let mut all: Vec<Ent> = per.into_iter().flatten().collect();+ all.sort_by_key(|e| (e.off, e.z));+ all.dedup_by_key(|e| e.off);+ all+}++#[derive(Default, Clone)]+struct Acc {+ n: u64,+ stored: u64,+ raw: u64,+ v: BTreeMap<String, u64>,+ t_inflate_ns: u64,+ t_zstd_ns: u64,+ t_zstd_dict_ns: u64,+ t_parse_ns: u64,+ hm_dims: BTreeMap<u16, u64>,+ identical_v10: u64,+ hm_err: BTreeMap<String, (f64, f64, u64)>,+}++impl Acc {+ fn add(&mut self, k: &str, n: usize) {+ *self.v.entry(k.to_string()).or_default() += n as u64;+ }+ fn merge(&mut self, o: &Acc) {+ self.n += o.n;+ self.stored += o.stored;+ self.raw += o.raw;+ for (k, v) in &o.v {+ *self.v.entry(k.clone()).or_default() += v;+ }+ self.t_inflate_ns += o.t_inflate_ns;+ self.t_zstd_ns += o.t_zstd_ns;+ self.t_zstd_dict_ns += o.t_zstd_dict_ns;+ self.t_parse_ns += o.t_parse_ns;+ for (k, v) in &o.hm_dims {+ *self.hm_dims.entry(*k).or_default() += v;+ }+ self.identical_v10 += o.identical_v10;+ for (k, v) in &o.hm_err {+ let e = self.hm_err.entry(k.clone()).or_insert((0.0, 0.0, 0));+ e.0 = e.0.max(v.0);+ e.1 += v.1;+ e.2 += v.2;+ }+ }+}++fn raw_of(a: &Arch, e: &Ent) -> Vec<u8> {+ let stored = &a.map[e.off as usize..e.off as usize + e.len as usize];+ tile_build::mamaps::read::decompress(a.hdr.compression, stored).expect("inflate")+}++fn cmd_bodies(path: &str, per_zoom: usize, out_dir: &str) {+ let a = open(path);+ let t0 = Instant::now();+ let ents = entries(&a);+ eprintln!("unique bodies {} in {:.1}s", ents.len(), t0.elapsed().as_secs_f64());+ let lid = |n: &str| a.dict.layers.iter().position(|l| l == n).expect(n) as u8;+ let ids = Ids { landtype: lid("landtype"), roads: lid("roads"), buildings: lid("buildings"), junction: lid("junction") };++ // Exact per-zoom totals and the stratified samples.+ let mut by_z: BTreeMap<u8, Vec<Ent>> = BTreeMap::new();+ for e in &ents {+ by_z.entry(e.z).or_default().push(*e);+ }+ let mut exact: BTreeMap<u8, (u64, u64)> = BTreeMap::new();+ let mut sample: Vec<Ent> = Vec::new();+ let mut train: Vec<Vec<Vec<u8>>> = vec![Vec::new(); 5];+ for (z, v) in &by_z {+ exact.insert(*z, (v.len() as u64, v.iter().map(|e| e.len as u64).sum()));+ let step = (v.len() / per_zoom.max(1)).max(1);+ let mut i = 0;+ while i < v.len() {+ sample.push(v[i]);+ // Disjoint training sample: half a stride later (only when the+ // stride leaves room; tiny zooms train on what there is).+ if step >= 2 && i + step / 2 < v.len() {+ train[band(*z)].push(v[i + step / 2].off.to_le_bytes().to_vec());+ }+ i += step;+ }+ }+ eprintln!("sample {} bodies; training dictionaries...", sample.len());+ // Training bodies: raw payload past the 16-byte header (what is compressed).+ let off_to_ent: std::collections::HashMap<u64, Ent> = ents.iter().map(|e| (e.off, *e)).collect();+ let dicts: Vec<Vec<u8>> = train+ .par_iter()+ .enumerate()+ .map(|(bi, offs)| {+ let mut samples: Vec<Vec<u8>> = offs+ .iter()+ .map(|o| {+ let e = off_to_ent[&u64::from_le_bytes(o[..8].try_into().unwrap())];+ raw_of(&a, &e)[H..].to_vec()+ })+ .collect();+ // zdict wants < 4 GB total and a bounded count; cap at 200k samples.+ samples.truncate(200_000);+ let d = zstd::dict::from_samples(&samples, 112 * 1024).unwrap_or_default();+ eprintln!(" dict {}: {} samples -> {} B", BANDS[bi], samples.len(), d.len());+ d+ })+ .collect();+ for (i, d) in dicts.iter().enumerate() {+ std::fs::write(format!("{out_dir}/dict_{}.zdict", BANDS[i]), d).expect("write dict");+ }+ let rs_dicts: Vec<Option<zstd_rs::EncoderDictionary>> = dicts+ .iter()+ .map(|d| {+ if d.is_empty() {+ return None;+ }+ let dd = zstd_rs::Dictionary::new(d, zstd_rs::DictionaryFormat::Zstd).ok()?;+ zstd_rs::EncoderDictionary::new(&dd, 19).ok()+ })+ .collect();++ let tnames = transforms();+ let acc: Mutex<BTreeMap<u8, Acc>> = Mutex::new(BTreeMap::new());+ let done = std::sync::atomic::AtomicUsize::new(0);+ sample.par_chunks(64).for_each(|chunk| {+ let mut local: BTreeMap<u8, Acc> = BTreeMap::new();+ let mut cdicts: Vec<Option<zstd::bulk::Compressor>> = dicts+ .iter()+ .map(|d| if d.is_empty() { None } else { zstd::bulk::Compressor::with_dictionary(19, d).ok() })+ .collect();+ for e in chunk {+ // Copied first so the timing below measures decode, not a page fault on the mmap.+ let stored = a.map[e.off as usize..e.off as usize + e.len as usize].to_vec();+ let ti = Instant::now();+ let raw = tile_build::mamaps::read::decompress(a.hdr.compression, &stored).expect("inflate");+ let t_inf = ti.elapsed().as_nanos() as u64;+ let tp = Instant::now();+ let body = Body::parse(&raw).expect("parse");+ let t_parse = tp.elapsed().as_nanos() as u64;+ let payload = &raw[H..];+ let acc = local.entry(e.z).or_default();+ acc.n += 1;+ acc.stored += e.len as u64;+ acc.raw += raw.len() as u64;+ acc.t_inflate_ns += t_inf;+ acc.t_parse_ns += t_parse;+ if let Some(h) = &body.heightmap {+ *acc.hm_dims.entry(h.dim).or_default() += 1;+ }+ acc.add("codec:deflate9", H + deflate9(payload));+ acc.add("codec:zstdC_19", H + zstd_c(payload, 19));+ let rs19 = zstd_rs(payload, 19);+ acc.add("codec:zstdRS_19", H + rs19.len());+ // Decode timing of the shipping decoder (ruzstd) on the zstd-rs frame.+ let td = Instant::now();+ let mut out = vec![0u8; payload.len()];+ let mut dec = ruzstd::decoding::FrameDecoder::new();+ let n = dec.decode_all(&rs19, &mut out).expect("ruzstd");+ acc.t_zstd_ns += td.elapsed().as_nanos() as u64;+ assert_eq!(&out[..n], payload, "ruzstd round trip");+ let bi = band(e.z);+ if let Some(c) = cdicts[bi].as_mut() {+ let fr = zstd_c_dict(c, payload);+ acc.add("codec:zstdC_19_dict", H + fr.len());+ } else {+ acc.add("codec:zstdC_19_dict", H + zstd_c(payload, 19));+ }+ if let Some(d) = rs_dicts[bi].as_ref() {+ let fr = zstd_rs_dict(payload, 19, d);+ acc.add("codec:zstdRS_19_dict", H + fr.len());+ if let Some(rd) = ruzstd::decoding::Dictionary::decode_dict(&dicts[bi]).ok() {+ let td = Instant::now();+ let mut dec = ruzstd::decoding::FrameDecoder::new();+ dec.add_dict(rd).expect("add dict");+ let mut out = vec![0u8; payload.len()];+ let n = dec.decode_all(&fr, &mut out).expect("ruzstd dict");+ acc.t_zstd_dict_ns += td.elapsed().as_nanos() as u64;+ assert_eq!(&out[..n], payload, "ruzstd dict round trip");+ }+ } else {+ acc.add("codec:zstdRS_19_dict", H + rs19.len());+ }+ for t in &tnames {+ let nb = apply(t, &body, e.z, &ids);+ if t.starts_with("hm_") && !t.contains("delta") {+ if let (Some(o), Some(n)) = (&body.heightmap, &nb.heightmap) {+ let (m, ss, c) = hm_err(o, n);+ let ent = acc.hm_err.entry(t.to_string()).or_insert((0.0, 0.0, 0));+ ent.0 = ent.0.max(m);+ ent.1 += ss;+ ent.2 += c;+ }+ }+ let r = ser(&nb);+ if *t == "identity_v10" && r == raw {+ acc.identical_v10 += 1;+ }+ acc.add(&format!("xf:{t}:raw"), r.len());+ acc.add(&format!("xf:{t}:zstdC19"), H + zstd_c(&r[H..], 19));+ if let Some(c) = cdicts[bi].as_mut() {+ acc.add(&format!("xf:{t}:zstdC19dict"), H + zstd_c_dict(c, &r[H..]).len());+ }+ }+ }+ let mut g = acc.lock().unwrap();+ for (z, l) in local {+ g.entry(z).or_default().merge(&l);+ }+ let d = done.fetch_add(chunk.len(), std::sync::atomic::Ordering::Relaxed) + chunk.len();+ if d % 20_000 < 64 {+ eprintln!(" {d}/{} ({:.0}s)", sample.len(), t0.elapsed().as_secs_f64());+ }+ });+ let acc = acc.into_inner().unwrap();++ // Report: per-variant planet projection (ratio estimator per zoom).+ let mut out = String::new();+ let total_exact: u64 = exact.values().map(|v| v.1).sum();+ out += &format!("archive {path}\nunique bodies {} exact stored {:.3} GB\n\n", ents.len(), total_exact as f64 / 1e9);+ out += "zoom bodies sampled exact_GB ratio_raw/stored identical_v10 hm_dims\n";+ for (z, a) in &acc {+ let (c, s) = exact[z];+ out += &format!(+ "z{:<3} {:>9} {:>7} {:>8.3} {:>8.3} {:>8}/{:<8} {:?}\n",+ z, c, a.n, s as f64 / 1e9, a.raw as f64 / a.stored as f64, a.identical_v10, a.n, a.hm_dims+ );+ }+ let keys: Vec<String> = acc.values().flat_map(|a| a.v.keys().cloned()).collect::<std::collections::BTreeSet<_>>().into_iter().collect();+ out += "\nvariant planet_GB delta_GB per-band GB (z0-9 z10-11 z12 z13 z14)\n";+ let mut tsv = String::from("variant\tplanet_gb\tdelta_gb\tz0_9\tz10_11\tz12\tz13\tz14\n");+ for k in &keys {+ let mut total = 0.0;+ let mut per_band = [0.0f64; 5];+ for (z, a) in &acc {+ let (_, s) = exact[z];+ let v = *a.v.get(k).unwrap_or(&0) as f64;+ let est = s as f64 * v / a.stored as f64;+ total += est;+ per_band[band(*z)] += est;+ }+ let delta = total - total_exact as f64;+ out += &format!(+ "{:<40} {:>10.3} {:>10.3} {}\n",+ k,+ total / 1e9,+ delta / 1e9,+ per_band.iter().map(|g| format!("{:.2}", g / 1e9)).collect::<Vec<_>>().join(" ")+ );+ tsv += &format!(+ "{k}\t{:.4}\t{:.4}\t{}\n",+ total / 1e9,+ delta / 1e9,+ per_band.iter().map(|g| format!("{:.4}", g / 1e9)).collect::<Vec<_>>().join("\t")+ );+ }+ // Decode timing (host, per body, single thread inside a rayon worker).+ out += "\nhost decode time per body (us): inflate(DEFLATE, current) | ruzstd(zstd-rs 19) | ruzstd+dict | Body::parse\n";+ for (z, a) in &acc {+ let n = a.n.max(1) as f64;+ out += &format!(+ "z{:<3} {:>8.1} {:>8.1} {:>8.1} {:>8.1} (avg raw {:.0} B)\n",+ z,+ a.t_inflate_ns as f64 / n / 1e3,+ a.t_zstd_ns as f64 / n / 1e3,+ a.t_zstd_dict_ns as f64 / n / 1e3,+ a.t_parse_ns as f64 / n / 1e3,+ a.raw as f64 / n+ );+ }+ let mut all = Acc::default();+ for a in acc.values() {+ all.merge(a);+ }+ let n = all.n as f64;+ out += &format!(+ "all {:>8.1} {:>8.1} {:>8.1} {:>8.1}\n",+ all.t_inflate_ns as f64 / n / 1e3,+ all.t_zstd_ns as f64 / n / 1e3,+ all.t_zstd_dict_ns as f64 / n / 1e3,+ all.t_parse_ns as f64 / n / 1e3+ );+ out += "\nDEM error vs current archive grid (metres; max over the continuous bilinear surface):\n";+ for (k, (m, ss, n)) in &all.hm_err {+ out += &format!(" {:<14} max {:>6.2} rms {:>6.3}\n", k, m, (ss / (*n).max(1) as f64).sqrt());+ }+ out += &format!("total {:.0}s\n", t0.elapsed().as_secs_f64());+ print!("{out}");+ std::fs::write(format!("{out_dir}/bodies.txt"), &out).unwrap();+ std::fs::write(format!("{out_dir}/bodies.tsv"), &tsv).unwrap();+}++// ---------------------------------------------------------------- sidecars++fn kind_name(k: u8) -> &'static str {+ match k {+ 1 => "graph_meta",+ 2 => "graph_nodes",+ 3 => "graph_edges",+ 4 => "graph_intermediate",+ 5 => "graph_names",+ 6 => "graph_lanes",+ 7 => "graph_elevation",+ 8 => "poi_index",+ 9 => "poi_names",+ 10 => "poi_attrs",+ 11 => "poi_spatial",+ 12 => "poi_words",+ 13 => "transit",+ 14 => "graph_overlay",+ 15 => "poi_region",+ 16 => "poi_admin",+ _ => "?",+ }+}++fn cmd_sidecars(path: &str, windows: usize, out_dir: &str) {+ let a = open(path);+ let view = tilecodec::mamaps::archive::ArchiveView::parse(&a.map, &a.hdr).expect("view");+ let mut out = String::from("section bytes_GB zblk sampled_MB zstdC19_64K zstdRS19_64K zstdC19_1M xz9e_1M(ref) est_GB(C19_64K)\n");+ let mut tsv = String::from("section\tbytes\tzblk\tratio_c19_64k\tratio_rs19_64k\tratio_c19_1m\test_gb_c19_64k\n");+ for e in &view.entries {+ let sec = &a.map[e.offset as usize..(e.offset + e.len) as usize];+ let is_zblk = sec.len() > 4 && &sec[..4] == b"ZBLK";+ if is_zblk {+ // Decode the ZBLK and recompress its blocks at higher levels.+ let b = tilecodec::blocked::Blocked::parse(sec).expect("zblk");+ let nb = b.block_count();+ let step = (nb / windows.max(1)).max(1);+ let idxs: Vec<usize> = (0..nb).step_by(step).collect();+ let r: Vec<(u64, u64, u64, u64, u64)> = idxs+ .par_iter()+ .map(|&i| {+ let raw = b.block(i).expect("block");+ let stored = b.block_offset(i + 1).unwrap() - b.block_offset(i).unwrap();+ (raw.len() as u64, stored, zstd_c(&raw, 19) as u64, zstd_c(&raw, 22) as u64, zstd_rs(&raw, 19).len() as u64)+ })+ .collect();+ let (raw, st, c19, c22, rs19) = r.iter().fold((0, 0, 0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4));+ let unpacked = b.unpacked_len();+ out += &format!(+ "{:<22} {:>8.3} ZBLK unpacked {:.3} GB, sample {} blocks: current {:.3}x C19 {:.3}x C22 {:.3}x RS19 {:.3}x -> est C19 {:.3} GB\n",+ kind_name(e.kind),+ e.len as f64 / 1e9,+ unpacked as f64 / 1e9,+ idxs.len(),+ raw as f64 / st as f64,+ raw as f64 / c19 as f64,+ raw as f64 / c22 as f64,+ raw as f64 / rs19 as f64,+ e.len as f64 * c19 as f64 / st as f64 / 1e9+ );+ tsv += &format!("{}\t{}\t1\t{:.4}\t{:.4}\t\t{:.4}\n", kind_name(e.kind), e.len, raw as f64 / c19 as f64, raw as f64 / rs19 as f64, e.len as f64 * c19 as f64 / st as f64 / 1e9);+ continue;+ }+ let win = 1usize << 20;+ let blk = 64usize << 10;+ let n = windows.min((sec.len() / win).max(1));+ let starts: Vec<usize> = if sec.len() <= win * windows {+ (0..sec.len()).step_by(win).collect()+ } else {+ (0..n).map(|i| (sec.len() - win) / n.max(1) * i).collect()+ };+ let r: Vec<(u64, u64, u64, u64)> = starts+ .par_iter()+ .map(|&s| {+ let w = &sec[s..(s + win).min(sec.len())];+ let mut c19 = 0u64;+ let mut rs19 = 0u64;+ for b in w.chunks(blk) {+ c19 += zstd_c(b, 19) as u64;+ rs19 += zstd_rs(b, 19).len() as u64;+ }+ (w.len() as u64, c19, rs19, zstd_c(w, 19) as u64)+ })+ .collect();+ let (raw, c19, rs19, c1m) = r.iter().fold((0, 0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2, a.3 + b.3));+ out += &format!(+ "{:<22} {:>8.3} raw {:>9.1} {:>9.3}x {:>9.3}x {:>9.3}x {:>12} {:>8.3}\n",+ kind_name(e.kind),+ e.len as f64 / 1e9,+ raw as f64 / 1e6,+ raw as f64 / c19 as f64,+ raw as f64 / rs19 as f64,+ raw as f64 / c1m as f64,+ "-",+ e.len as f64 * c19 as f64 / raw as f64 / 1e9+ );+ tsv += &format!(+ "{}\t{}\t0\t{:.4}\t{:.4}\t{:.4}\t{:.4}\n",+ kind_name(e.kind),+ e.len,+ raw as f64 / c19 as f64,+ raw as f64 / rs19 as f64,+ raw as f64 / c1m as f64,+ e.len as f64 * c19 as f64 / raw as f64 / 1e9+ );+ }+ print!("{out}");+ std::fs::write(format!("{out_dir}/sidecars.txt"), &out).unwrap();+ std::fs::write(format!("{out_dir}/sidecars.tsv"), &tsv).unwrap();+ let _ = std::io::stdout().flush();+}++include!("size_lab_more.rs");++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let mode = args.get(1).map(String::as_str).unwrap_or("");+ if mode == "render" {+ return cmd_render(&args);+ }+ if mode == "cmp" {+ // size_lab cmp BASE CAND PER_ZOOM OUT_DIR+ std::fs::create_dir_all(&args[5]).unwrap();+ return cmd_cmp(&args[2], &args[3], args[4].parse().unwrap(), &args[5]);+ }+ let path = args.get(2).expect("usage: size_lab bodies|sidecars IN.mamaps [N] [OUT_DIR]");+ let out_dir = args.get(4).cloned().unwrap_or_else(|| ".".into());+ std::fs::create_dir_all(&out_dir).unwrap();+ match mode {+ "bodies" => cmd_bodies(path, args.get(3).and_then(|s| s.parse().ok()).unwrap_or(2000), &out_dir),+ "sidecars" => cmd_sidecars(path, args.get(3).and_then(|s| s.parse().ok()).unwrap_or(64), &out_dir),+ "transit" => cmd_transit(path, &out_dir),+ "zblk" => cmd_zblk(path),+ "zooms" => cmd_zooms(path),+ "recompress" => cmd_recompress(path, args.get(3).map(String::as_str).unwrap_or(".")),+ "dem-pyramid" => cmd_dem_pyramid(path, args[3].parse().unwrap(), &out_dir),+ _ => eprintln!("usage: size_lab bodies|sidecars IN.mamaps [N] [OUT_DIR]"),+ }+}
scripts/maps/tile_build/examples/size_lab_more.rs
diff --git a/scripts/maps/tile_build/examples/size_lab_more.rs b/scripts/maps/tile_build/examples/size_lab_more.rsnew file mode 100644index 0000000000..b1bfd9d3f9--- /dev/null+++ b/scripts/maps/tile_build/examples/size_lab_more.rs@@ -0,0 +1,1039 @@+// Included into size_lab.rs: recompress / cmp / render / dem-pyramid modes.++/// Every leaf entry with its first tile id, sorted by tile id (not deduplicated).+struct TileIndex {+ ents: Vec<(u64, u32, u64, u32)>, // (tile_id, run_length, abs offset, len)+}++impl TileIndex {+ fn build(a: &Arch) -> TileIndex {+ let hdr = &a.hdr;+ let root = index::parse_root(&a.map[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize]).expect("root");+ let per: Vec<Vec<(u64, u32, u64, u32)>> = root+ .par_iter()+ .map(|re| {+ let raw_len = re.leaf_entry_count as usize * index::LEAF_ENTRY_LEN;+ let at = (hdr.leaf_offset + re.leaf_offset) as usize;+ let raw = if re.stored_len == 0 {+ a.map[at..at + raw_len].to_vec()+ } else {+ index::decompress_leaf(&a.map[at..at + re.stored_len as usize], raw_len).expect("leaf")+ };+ index::parse_leaf(&raw)+ .expect("leaf")+ .iter()+ .map(|e| (re.base_tile_id + e.tile_id_lo as u64, e.run_length, hdr.data_offset + re.base_data_offset + e.offset_delta as u64, e.length))+ .collect()+ })+ .collect();+ let mut ents: Vec<_> = per.into_iter().flatten().collect();+ ents.sort_by_key(|e| e.0);+ TileIndex { ents }+ }+ fn find(&self, id: u64) -> Option<(u64, u32)> {+ let i = self.ents.partition_point(|e| e.0 <= id);+ if i == 0 {+ return None;+ }+ let e = self.ents[i - 1];+ (id < e.0 + e.1 as u64).then_some((e.2, e.3))+ }+}++fn body_at(a: &Arch, off: u64, len: u32) -> Body {+ let stored = &a.map[off as usize..off as usize + len as usize];+ let raw = tile_build::mamaps::read::decompress(a.hdr.compression, stored).expect("inflate");+ Body::parse(&raw).expect("parse")+}++// ------------------------------------------------------------ recompress (exact, whole archive)++fn cmd_recompress(path: &str, out_dir: &str) {+ let a = open(path);+ let t0 = Instant::now();+ let ents = entries(&a);+ let total_now: u64 = ents.iter().map(|e| e.len as u64).sum();+ // Dictionaries per zoom band from a 1-in-N sample (<= 20k bodies per band).+ let mut by_band: Vec<Vec<Ent>> = vec![Vec::new(); 5];+ for e in &ents {+ by_band[band(e.z)].push(*e);+ }+ let dicts: Vec<Vec<u8>> = by_band+ .par_iter()+ .map(|v| {+ if v.len() < 64 {+ return Vec::new();+ }+ let step = (v.len() / 20_000).max(1);+ let samples: Vec<Vec<u8>> = v.iter().step_by(step).map(|e| raw_of(&a, e)[H..].to_vec()).collect();+ zstd::dict::from_samples(&samples, 112 * 1024).unwrap_or_default()+ })+ .collect();+ let dict_bytes: usize = dicts.iter().map(|d| d.len()).sum();+ let rs_dicts: Vec<Option<zstd_rs::EncoderDictionary>> = dicts+ .iter()+ .map(|d| {+ if d.is_empty() {+ return None;+ }+ let dd = zstd_rs::Dictionary::new(d, zstd_rs::DictionaryFormat::Zstd).ok()?;+ zstd_rs::EncoderDictionary::new(&dd, 19).ok()+ })+ .collect();+ #[derive(Default, Clone, Copy)]+ struct S {+ n: u64,+ now: u64,+ raw: u64,+ rs19: u64,+ rs19d: u64,+ c19: u64,+ c22: u64,+ t_now: u64,+ t_zstd: u64,+ }+ let acc: Mutex<[S; 15]> = Mutex::new([S::default(); 15]);+ ents.par_chunks(256).for_each(|chunk| {+ let mut loc = [S::default(); 15];+ let mut dec = ruzstd::decoding::FrameDecoder::new();+ for e in chunk {+ let stored = a.map[e.off as usize..e.off as usize + e.len as usize].to_vec();+ let t = Instant::now();+ let raw = tile_build::mamaps::read::decompress(a.hdr.compression, &stored).expect("inflate");+ let _ = Body::parse(&raw).expect("parse");+ let t_now = t.elapsed().as_nanos() as u64;+ let p = &raw[H..];+ let rs = zstd_rs(p, 19);+ let t = Instant::now();+ let mut out = vec![0u8; p.len()];+ dec.decode_all(&rs, &mut out).expect("ruzstd");+ let mut full = raw[..H].to_vec();+ full.extend_from_slice(&out);+ let _ = Body::parse(&full).expect("parse zstd");+ let t_z = t.elapsed().as_nanos() as u64;+ let s = &mut loc[e.z.min(14) as usize];+ s.n += 1;+ s.now += e.len as u64;+ s.raw += raw.len() as u64;+ s.rs19 += (H + rs.len()) as u64;+ s.rs19d += (H + match &rs_dicts[band(e.z)] {+ Some(d) => zstd_rs_dict(p, 19, d).len(),+ None => rs.len(),+ }) as u64;+ s.c19 += (H + zstd_c(p, 19)) as u64;+ s.c22 += (H + zstd_c(p, 22)) as u64;+ s.t_now += t_now;+ s.t_zstd += t_z;+ }+ let mut g = acc.lock().unwrap();+ for z in 0..15 {+ let (o, l) = (&mut g[z], loc[z]);+ o.n += l.n;+ o.now += l.now;+ o.raw += l.raw;+ o.rs19 += l.rs19;+ o.rs19d += l.rs19d;+ o.c19 += l.c19;+ o.c22 += l.c22;+ o.t_now += l.t_now;+ o.t_zstd += l.t_zstd;+ }+ });+ let g = acc.into_inner().unwrap();+ let mut out = format!(+ "archive {path}\nunique bodies {} tile data now {:.4} GB (all, every body recompressed; exact)\ndictionaries: {} B total (5 zoom bands, 112 KiB each)\n",+ ents.len(),+ total_now as f64 / 1e9,+ dict_bytes+ );+ out += "zoom bodies now_MB raw_MB zstdRS19 zstdRS19+dict zstdC19 zstdC22 decode_us(now) decode_us(zstd)\n";+ let mut t = S::default();+ for z in 0..15 {+ let s = g[z];+ if s.n == 0 {+ continue;+ }+ out += &format!(+ "z{z:<3} {:>9} {:>8.1} {:>8.1} {:>9.1} {:>12.1} {:>9.1} {:>8.1} {:>12.1} {:>12.1}\n",+ s.n,+ s.now as f64 / 1e6,+ s.raw as f64 / 1e6,+ s.rs19 as f64 / 1e6,+ s.rs19d as f64 / 1e6,+ s.c19 as f64 / 1e6,+ s.c22 as f64 / 1e6,+ s.t_now as f64 / s.n as f64 / 1e3,+ s.t_zstd as f64 / s.n as f64 / 1e3+ );+ t.n += s.n;+ t.now += s.now;+ t.raw += s.raw;+ t.rs19 += s.rs19;+ t.rs19d += s.rs19d;+ t.c19 += s.c19;+ t.c22 += s.c22;+ t.t_now += s.t_now;+ t.t_zstd += s.t_zstd;+ }+ out += &format!(+ "TOTAL {:>9} {:>8.1} {:>8.1} {:>9.1} {:>12.1} {:>9.1} {:>8.1} {:>12.1} {:>12.1}\n",+ t.n,+ t.now as f64 / 1e6,+ t.raw as f64 / 1e6,+ t.rs19 as f64 / 1e6,+ (t.rs19d as f64 + dict_bytes as f64) / 1e6,+ t.c19 as f64 / 1e6,+ t.c22 as f64 / 1e6,+ t.t_now as f64 / t.n as f64 / 1e3,+ t.t_zstd as f64 / t.n as f64 / 1e3+ );+ out += &format!("RECOMPRESS_TSV\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", t.now, t.rs19, t.rs19d + dict_bytes as u64, t.c19, t.c22, t.t_now / t.n.max(1), t.t_zstd / t.n.max(1));+ out += &format!("(decode = decompress + Body::parse on one host core; {:.0}s)\n", t0.elapsed().as_secs_f64());+ print!("{out}");+ std::fs::write(format!("{out_dir}/recompress.txt"), &out).unwrap();+}++// ------------------------------------------------------------ geometry / DEM comparison++struct SegGrid {+ cell: f64,+ origin: f64,+ n: usize,+ cells: Vec<Vec<u32>>,+ segs: Vec<((f64, f64), (f64, f64))>,+}++impl SegGrid {+ fn new(segs: Vec<((f64, f64), (f64, f64))>) -> SegGrid {+ let (origin, span, n) = (-1024.0, 6144.0, 48usize);+ let cell = span / n as f64;+ let mut cells = vec![Vec::new(); n * n];+ let ci = |v: f64| (((v - origin) / cell).floor() as i64).clamp(0, n as i64 - 1) as usize;+ for (k, (a, b)) in segs.iter().enumerate() {+ let (x0, x1) = (ci(a.0.min(b.0)), ci(a.0.max(b.0)));+ let (y0, y1) = (ci(a.1.min(b.1)), ci(a.1.max(b.1)));+ for y in y0..=y1 {+ for x in x0..=x1 {+ cells[y * n + x].push(k as u32);+ }+ }+ }+ SegGrid { cell, origin, n, cells, segs }+ }+ /// Distance to the nearest segment, or None beyond `cap`.+ fn nearest(&self, p: (f64, f64), cap: f64) -> Option<f64> {+ let n = self.n as i64;+ let cx = ((p.0 - self.origin) / self.cell).floor() as i64;+ let cy = ((p.1 - self.origin) / self.cell).floor() as i64;+ let mut best = f64::INFINITY;+ let rmax = (cap / self.cell).ceil() as i64 + 1;+ for r in 0..=rmax {+ if best.is_finite() && best <= (r as f64 - 1.0).max(0.0) * self.cell {+ break;+ }+ for y in cy - r..=cy + r {+ for x in cx - r..=cx + r {+ if (y - cy).abs() != r && (x - cx).abs() != r {+ continue;+ }+ if x < 0 || y < 0 || x >= n || y >= n {+ continue;+ }+ for &k in &self.cells[(y * n + x) as usize] {+ let (a, b) = self.segs[k as usize];+ best = best.min(seg_dist_sq_f(p, a, b).sqrt());+ }+ }+ }+ }+ (best <= cap).then_some(best)+ }+}++fn seg_dist_sq_f(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let l2 = dx * dx + dy * dy;+ let t = if l2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0) };+ let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);+ (p.0 - qx).powi(2) + (p.1 - qy).powi(2)+}++fn layer_segs_pts(l: &Layer) -> (Vec<((f64, f64), (f64, f64))>, Vec<(f64, f64)>) {+ let mut segs = Vec::new();+ let mut pts = Vec::new();+ for f in &l.features {+ if f.geom_type == GEOM_POINT {+ continue;+ }+ let from = f.parts_offset as usize;+ for p in &l.parts[from..from + f.part_count as usize] {+ let v = l.points(p);+ for w in v.windows(2) {+ segs.push(((w[0].0 as f64, w[0].1 as f64), (w[1].0 as f64, w[1].1 as f64)));+ }+ if f.geom_type == GEOM_POLYGON && v.len() > 2 && v.first() != v.last() {+ let (a, b) = (v[v.len() - 1], v[0]);+ segs.push(((a.0 as f64, a.1 as f64), (b.0 as f64, b.1 as f64)));+ }+ pts.extend(v.iter().map(|q| (q.0 as f64, q.1 as f64)));+ }+ }+ (segs, pts)+}++fn tile_lat(z: u8, y: u64) -> f64 {+ let n = std::f64::consts::PI * (1.0 - 2.0 * (y as f64 + 0.5) / (1u64 << z) as f64);+ n.sinh().atan().to_degrees()+}++/// Metres per extent unit for tile (z, y).+fn m_per_unit(z: u8, y: u64) -> f64 {+ 40_075_016.686 * tile_lat(z, y).to_radians().cos() / (1u64 << z) as f64 / 4096.0+}++#[derive(Default, Clone)]+struct DevAcc {+ n: u64,+ sum_m: f64,+ max_m: f64,+ max_units: f64,+ hist: Vec<u64>, // 0.01-unit buckets up to the cap (32 units)+ missing: u64,+ sym_max_u: f64,+}+impl DevAcc {+ fn add(&mut self, d_units: f64, mpu: f64) {+ if self.hist.is_empty() {+ self.hist = vec![0; 3_201];+ }+ let m = d_units * mpu;+ self.n += 1;+ self.sum_m += m;+ self.max_m = self.max_m.max(m);+ self.max_units = self.max_units.max(d_units);+ self.hist[((d_units * 100.0) as usize).min(3_200)] += 1;+ }+ fn merge(&mut self, o: &DevAcc) {+ if self.hist.is_empty() {+ self.hist = vec![0; 3_201];+ }+ if o.hist.is_empty() {+ self.missing += o.missing;+ return;+ }+ self.n += o.n;+ self.sum_m += o.sum_m;+ self.max_m = self.max_m.max(o.max_m);+ self.max_units = self.max_units.max(o.max_units);+ self.missing += o.missing;+ self.sym_max_u = self.sym_max_u.max(o.sym_max_u);+ for (a, b) in self.hist.iter_mut().zip(o.hist.iter()) {+ *a += b;+ }+ }+ fn pct(&self, q: f64) -> f64 {+ let target = (self.n as f64 * q).ceil() as u64;+ let mut c = 0;+ for (i, h) in self.hist.iter().enumerate() {+ c += h;+ if c >= target {+ return i as f64 / 100.0;+ }+ }+ 32.0+ }+}++fn cmd_cmp(base: &str, cand: &str, per_zoom: usize, out_dir: &str) {+ let a = open(base);+ let b = open(cand);+ let ia = TileIndex::build(&a);+ let ib = TileIndex::build(&b);+ let mut by_z: BTreeMap<u8, Vec<(u64, u64, u32)>> = BTreeMap::new();+ for &(id, _, off, len) in &ia.ents {+ let (z, _, _) = tile_zxy(id);+ by_z.entry(z).or_default().push((id, off, len));+ }+ let mut sample = Vec::new();+ for (_, v) in &by_z {+ let step = (v.len() / per_zoom.max(1)).max(1);+ sample.extend(v.iter().step_by(step).copied());+ }+ let nl = a.dict.layers.len();+ // key (zoom, layer) -> deviations; DEM per zoom+ let acc: Mutex<(BTreeMap<(u8, u8), DevAcc>, BTreeMap<u8, (f64, f64, u64, u64, u64)>)> = Mutex::new((BTreeMap::new(), BTreeMap::new()));+ let cap = 32.0;+ sample.par_chunks(32).for_each(|chunk| {+ let mut dev: BTreeMap<(u8, u8), DevAcc> = BTreeMap::new();+ let mut dem: BTreeMap<u8, (f64, f64, u64, u64, u64)> = BTreeMap::new();+ for &(id, off, len) in chunk {+ let (z, _x, y) = tile_zxy(id);+ let Some((boff, blen)) = ib.find(id) else { continue };+ let ba = body_at(&a, off, len);+ let bb = body_at(&b, boff, blen);+ let mpu = m_per_unit(z, y);+ for lid in 0..nl as u8 {+ let (la, lb) = (ba.layer(lid), bb.layer(lid));+ let Some(la) = la else { continue };+ let (sa, pa) = layer_segs_pts(la);+ if pa.is_empty() {+ continue;+ }+ let d = dev.entry((z, lid)).or_default();+ let Some(lb) = lb else {+ d.missing += pa.len() as u64;+ continue;+ };+ let (sb, pb) = layer_segs_pts(lb);+ if sb.is_empty() {+ d.missing += pa.len() as u64;+ continue;+ }+ let gb = SegGrid::new(sb);+ // A -> B: how far each original vertex now is from the candidate geometry.+ for p in &pa {+ match gb.nearest(*p, cap) {+ Some(dd) => d.add(dd, mpu),+ None => d.missing += 1,+ }+ }+ // B -> A (symmetric Hausdorff half): candidate vertices against the original.+ if !sa.is_empty() {+ let ga = SegGrid::new(sa);+ for p in &pb {+ if let Some(dd) = ga.nearest(*p, cap) {+ d.sym_max_u = d.sym_max_u.max(dd);+ }+ }+ }+ }+ // DEM: both bilinear surfaces on a 33x33 lattice.+ let e = dem.entry(z).or_insert((0.0, 0.0, 0, 0, 0));+ match (&ba.heightmap, &bb.heightmap) {+ (Some(ha), Some(hb)) => {+ for r in 0..33 {+ for c in 0..33 {+ let (fr, fc) = (r as f64 / 32.0, c as f64 / 32.0);+ let d = (bilin(&ha.samples, ha.dim as usize, fr, fc) - bilin(&hb.samples, hb.dim as usize, fr, fc)).abs();+ e.0 = e.0.max(d);+ e.1 += d * d;+ e.2 += 1;+ }+ }+ }+ (Some(_), None) | (None, Some(_)) => e.3 += 1,+ _ => {}+ }+ e.4 += 1;+ }+ let mut g = acc.lock().unwrap();+ for (k, v) in dev {+ g.0.entry(k).or_default().merge(&v);+ }+ for (k, v) in dem {+ let e = g.1.entry(k).or_insert((0.0, 0.0, 0, 0, 0));+ e.0 = e.0.max(v.0);+ e.1 += v.1;+ e.2 += v.2;+ e.3 += v.3;+ e.4 += v.4;+ }+ });+ let (dev, dem) = acc.into_inner().unwrap();+ let mut out = format!("cmp base={base}\n cand={cand}\n(sampled {} tiles; deviation = distance from each base vertex to the candidate's geometry in the same tile/layer, in extent units (1/4096 tile) and metres; vertices with nothing within 32 units = dropped features; Hausdorff_u = max(base->cand, cand->base) over matched geometry. px: 1 unit = 1/16 px at the tile's own zoom (256-px tiles), 1/4 px for a z14 tile at z16, 1 px at z18)\n", sample.len());+ out += "band layer verts mean_m max_m p50_u p99_u p99.9_u max_u hausdorff_u dropped%\n";+ let bands: [(&str, std::ops::RangeInclusive<u8>); 5] = [("z0-9", 0..=9), ("z10-11", 10..=11), ("z12", 12..=12), ("z13", 13..=13), ("z14", 14..=14)];+ let mut tsv = String::from("band\tlayer\tverts\tmean_m\tmax_m\tp99_u\tp999_u\tmax_u\thausdorff_u\tdropped_pct\n");+ for (bn, r) in bands.iter() {+ for lid in 0..nl as u8 {+ let mut d = DevAcc::default();+ for z in r.clone() {+ if let Some(v) = dev.get(&(z, lid)) {+ d.merge(v);+ }+ }+ if d.n == 0 {+ continue;+ }+ let name = a.dict.layers[lid as usize].clone();+ let miss = 100.0 * d.missing as f64 / (d.n + d.missing).max(1) as f64;+ out += &format!(+ "{bn:<8} {name:<11} {:>9} {:>8.3} {:>7.2} {:>6.2} {:>6.2} {:>7.2} {:>6.2} {:>11.2} {:>9.4}\n",+ d.n,+ d.sum_m / d.n as f64,+ d.max_m,+ d.pct(0.5),+ d.pct(0.99),+ d.pct(0.999),+ d.max_units,+ d.max_units.max(d.sym_max_u),+ miss+ );+ tsv += &format!("{bn}\t{name}\t{}\t{:.4}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.3}\t{:.4}\n", d.n, d.sum_m / d.n as f64, d.max_m, d.pct(0.99), d.pct(0.999), d.max_units, d.max_units.max(d.sym_max_u), miss);+ }+ }+ out += "\nDEM (candidate vs base surface, 33x33 lattice per tile; metres)\n";+ let (mut gm, mut gs, mut gn) = (0.0f64, 0.0f64, 0u64);+ for (z, (m, ss, n, mism, tiles)) in &dem {+ if *n == 0 && *mism == 0 {+ continue;+ }+ gm = gm.max(*m);+ gs += ss;+ gn += n;+ out += &format!(" z{z:<2} tiles {tiles:>7} max {m:>8.2} rms {:>7.3} presence_mismatch {mism}\n", (ss / (*n).max(1) as f64).sqrt());+ }+ out += &format!(" all max {gm:.2} rms {:.3}\n", (gs / gn.max(1) as f64).sqrt());+ tsv += &format!("DEM\tall\t{gn}\t\t\t{gm:.3}\t\t\t{:.4}\n", (gs / gn.max(1) as f64).sqrt());+ print!("{out}");+ std::fs::write(format!("{out_dir}/cmp.txt"), &out).unwrap();+ std::fs::write(format!("{out_dir}/cmp.tsv"), &tsv).unwrap();+}++// ------------------------------------------------------------ render++struct Canvas {+ w: usize,+ h: usize,+ px: Vec<[u8; 3]>,+}++impl Canvas {+ fn new(w: usize, h: usize, bg: [u8; 3]) -> Canvas {+ Canvas { w, h, px: vec![bg; w * h] }+ }+ fn blend(&mut self, x: i64, y: i64, c: [u8; 3], a: f32) {+ if x < 0 || y < 0 || x as usize >= self.w || y as usize >= self.h {+ return;+ }+ let p = &mut self.px[y as usize * self.w + x as usize];+ for i in 0..3 {+ p[i] = (p[i] as f32 * (1.0 - a) + c[i] as f32 * a) as u8;+ }+ }+ /// Even-odd scanline fill of a set of rings (pixel coords).+ fn fill(&mut self, rings: &[Vec<(f64, f64)>], c: [u8; 3], a: f32) {+ let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY);+ for r in rings {+ for p in r {+ y0 = y0.min(p.1);+ y1 = y1.max(p.1);+ }+ }+ let ys = (y0.floor().max(0.0)) as i64;+ let ye = (y1.ceil().min(self.h as f64 - 1.0)) as i64;+ let mut xs: Vec<f64> = Vec::new();+ for y in ys..=ye {+ let fy = y as f64 + 0.5;+ xs.clear();+ for r in rings {+ let n = r.len();+ for i in 0..n {+ let (p, q) = (r[i], r[(i + 1) % n]);+ if (p.1 <= fy) != (q.1 <= fy) {+ xs.push(p.0 + (fy - p.1) / (q.1 - p.1) * (q.0 - p.0));+ }+ }+ }+ xs.sort_by(|a, b| a.partial_cmp(b).unwrap());+ for pair in xs.chunks(2) {+ if pair.len() < 2 {+ break;+ }+ let (xa, xb) = ((pair[0].round().max(0.0)) as i64, (pair[1].round().min(self.w as f64)) as i64);+ for x in xa..xb {+ self.blend(x, y, c, a);+ }+ }+ }+ }+ fn line(&mut self, p: (f64, f64), q: (f64, f64), wpx: f64, c: [u8; 3]) {+ let len = ((q.0 - p.0).powi(2) + (q.1 - p.1).powi(2)).sqrt();+ let steps = (len * 2.0).ceil().max(1.0) as usize;+ let r = (wpx / 2.0).max(0.5);+ let ri = r.ceil() as i64;+ for s in 0..=steps {+ let t = s as f64 / steps as f64;+ let (x, y) = (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t);+ for dy in -ri..=ri {+ for dx in -ri..=ri {+ if ((dx * dx + dy * dy) as f64) <= r * r {+ self.blend(x.round() as i64 + dx, y.round() as i64 + dy, c, 1.0);+ }+ }+ }+ }+ }+}++fn kind_style(name: &str) -> Option<[u8; 3]> {+ let n = name;+ Some(if n.contains("water") || n == "lake" || n == "river" || n == "bay" || n == "strait" || n == "reservoir" || n == "ocean" || n == "canal" || n == "stream" || n == "basin" {+ [170, 211, 223]+ } else if n.contains("forest") || n.contains("wood") || n == "nature_reserve" || n == "national_park" || n == "protected_area" {+ [173, 209, 158]+ } else if n.contains("grass") || n == "park" || n == "meadow" || n == "golf_course" || n == "recreation_ground" || n == "cemetery" || n == "scrub" {+ [205, 235, 176]+ } else if n == "farmland" || n == "orchard" || n == "vineyard" || n == "allotments" {+ [238, 240, 213]+ } else if n == "residential" || n == "commercial" || n == "industrial" || n == "retail" {+ [224, 223, 223]+ } else if n == "sand" || n == "beach" || n == "bare_rock" || n == "glacier" || n == "wetland" || n == "quarry" {+ [242, 239, 233]+ } else {+ return None;+ })+}++fn render_body(body: &Body, dict: &Dictionary, z: u8, crop: (f64, f64, f64), size: usize) -> Canvas {+ let mut cv = Canvas::new(size, size, [242, 239, 233]);+ let (cx, cy, cs) = crop;+ let s = size as f64 / cs;+ let to_px = |p: &(i16, i16)| ((p.0 as f64 - cx) * s, (p.1 as f64 - cy) * s);+ let lid = |n: &str| dict.layers.iter().position(|l| l == n).map(|i| i as u8);+ // Hillshade first (from the heightmap), as a multiply over the background.+ if let Some(hm) = &body.heightmap {+ let d = hm.dim as usize;+ let mpu_px = 40_075_016.686 / (1u64 << z) as f64 / 4096.0 / s; // ~metres per pixel+ for py in 0..size {+ for px in 0..size {+ let (ux, uy) = ((cx + px as f64 / s) / 4096.0, (cy + py as f64 / s) / 4096.0);+ if !(0.0..=1.0).contains(&ux) || !(0.0..=1.0).contains(&uy) {+ continue;+ }+ let e = 1.0 / 4096.0 / s * 2.0;+ let hx = bilin(&hm.samples, d, uy, (ux + e).min(1.0)) - bilin(&hm.samples, d, uy, (ux - e).max(0.0));+ let hy = bilin(&hm.samples, d, (uy + e).min(1.0), ux) - bilin(&hm.samples, d, (uy - e).max(0.0), ux);+ let (gx, gy) = (3.0 * hx / (4.0 * mpu_px), 3.0 * hy / (4.0 * mpu_px));+ let shade = ((-gx * 0.7 - gy * 0.7 + 1.0) / (1.0 + gx * gx + gy * gy).sqrt()).clamp(0.0, 1.5);+ let v = (shade * 170.0).clamp(0.0, 255.0) as u8;+ cv.blend(px as i64, py as i64, [v, v, v], 0.5);+ }+ }+ }+ let draw_polys = |cv: &mut Canvas, l: &Layer, colour: &dyn Fn(u16) -> Option<[u8; 3]>, alpha: f32| {+ for f in &l.features {+ if f.geom_type != GEOM_POLYGON {+ continue;+ }+ let Some(c) = colour(f.kind) else { continue };+ let from = f.parts_offset as usize;+ let rings: Vec<Vec<(f64, f64)>> = l.parts[from..from + f.part_count as usize].iter().map(|p| l.points(p).iter().map(to_px).collect()).collect();+ cv.fill(&rings, c, alpha);+ }+ };+ if let Some(l) = lid("landtype").and_then(|i| body.layer(i)) {+ draw_polys(&mut cv, l, &|k| kind_style(dict.kind_name(k).unwrap_or("")), 0.85);+ for f in &l.features {+ if f.geom_type == 1 {+ let from = f.parts_offset as usize;+ for p in &l.parts[from..from + f.part_count as usize] {+ for w in l.points(p).windows(2) {+ cv.line(to_px(&w[0]), to_px(&w[1]), 1.5, [130, 180, 210]);+ }+ }+ }+ }+ }+ if let Some(l) = lid("buildings").and_then(|i| body.layer(i)) {+ draw_polys(&mut cv, l, &|_| Some([200, 190, 180]), 1.0);+ for f in &l.features {+ let from = f.parts_offset as usize;+ for p in &l.parts[from..from + f.part_count as usize] {+ let v = l.points(p);+ for i in 0..v.len() {+ cv.line(to_px(&v[i]), to_px(&v[(i + 1) % v.len()]), 1.0, [150, 140, 130]);+ }+ }+ }+ }+ if let Some(l) = lid("boundaries").and_then(|i| body.layer(i)) {+ for f in &l.features {+ let from = f.parts_offset as usize;+ for p in &l.parts[from..from + f.part_count as usize] {+ for w in l.points(p).windows(2) {+ cv.line(to_px(&w[0]), to_px(&w[1]), 1.5, [160, 100, 170]);+ }+ }+ }+ }+ if let Some(l) = lid("roads").and_then(|i| body.layer(i)) {+ for pass in 0..2 {+ for f in &l.features {+ let name = dict.kind_name(f.kind).unwrap_or("");+ let major = name.contains("highway") || name.contains("major") || name.contains("motorway") || name.contains("trunk") || name.contains("primary");+ let w = if major { 5.0 } else if name.contains("path") || name.contains("foot") || name.contains("track") { 1.2 } else { 3.0 };+ let (c, ww) = if pass == 0 { ([120, 120, 120], w + 1.5) } else if major { ([252, 214, 164], w) } else { ([255, 255, 255], w) };+ let from = f.parts_offset as usize;+ for p in &l.parts[from..from + f.part_count as usize] {+ for wv in l.points(p).windows(2) {+ cv.line(to_px(&wv[0]), to_px(&wv[1]), ww, c);+ }+ }+ }+ }+ }+ cv+}++fn write_png(path: &str, cv: &Canvas) {+ let f = File::create(path).expect("png create");+ let mut enc = png::Encoder::new(std::io::BufWriter::new(f), cv.w as u32, cv.h as u32);+ enc.set_color(png::ColorType::Rgb);+ enc.set_depth(png::BitDepth::Eight);+ let mut w = enc.write_header().expect("png header");+ let data: Vec<u8> = cv.px.iter().flat_map(|p| p.iter().copied()).collect();+ w.write_image_data(&data).expect("png data");+}++/// `render OUT.png Z X Y CROP_Q ARCH [ARCH...]`: side-by-side renders of one tile from each+/// archive. CROP_Q = 1 renders the whole tile (its native zoom); 4 renders the top-left-of-centre+/// quarter-of-a-quarter, i.e. what the z+2 view of that tile shows (overzoom), and so on.+fn cmd_render(args: &[String]) {+ let out = &args[2];+ let z: u8 = args[3].parse().unwrap();+ let x: u64 = args[4].parse().unwrap();+ let y: u64 = args[5].parse().unwrap();+ let q: f64 = args[6].parse().unwrap();+ let archs = &args[7..];+ let size = 768usize;+ let cs = 4096.0 / q;+ let crop = ((4096.0 - cs) / 2.0, (4096.0 - cs) / 2.0, cs);+ let mut panels = Vec::new();+ for p in archs {+ let a = open(p);+ let ix = TileIndex::build(&a);+ let id = tilecodec::pmtiles::tile_id(z, x, y);+ let cv = match ix.find(id) {+ Some((off, len)) => render_body(&body_at(&a, off, len), &a.dict, z, crop, size),+ None => Canvas::new(size, size, [255, 0, 255]),+ };+ panels.push(cv);+ }+ let gap = 8;+ let mut all = Canvas::new(size * panels.len() + gap * (panels.len() - 1), size, [255, 255, 255]);+ for (i, p) in panels.iter().enumerate() {+ for yy in 0..size {+ for xx in 0..size {+ all.px[yy * all.w + i * (size + gap) + xx] = p.px[yy * size + xx];+ }+ }+ }+ write_png(out, &all);+ println!("wrote {out}");+}++// ------------------------------------------------------------ DEM pyramid redundancy++/// `dem-pyramid ARCH TOL_M`: how much the heightmaps would shrink if a tile whose grid is within+/// TOL_M of its nearest kept ancestor's (bilinearly upsampled) surface stored none and the+/// reader fell back to that ancestor (a format change: the shipped reader draws such a tile+/// flat). Measured exactly over every body: each body re-encoded without its heightmap and+/// zstd-19 compressed, against the same body with it.+fn cmd_dem_pyramid(path: &str, tol: f64, out_dir: &str) {+ let a = open(path);+ let ix = TileIndex::build(&a);+ // Kept heightmaps per tile id, processed zoom by zoom (parents first).+ let mut kept: std::collections::HashMap<u64, (u8, u64, u64)> = std::collections::HashMap::new(); // tile -> ancestor (z,x,y) whose grid serves it+ let mut grids: std::collections::HashMap<u64, Heightmap> = std::collections::HashMap::new();+ let mut by_z: BTreeMap<u8, Vec<(u64, u64, u32)>> = BTreeMap::new();+ for &(id, _, off, len) in &ix.ents {+ let (z, _, _) = tile_zxy(id);+ by_z.entry(z).or_default().push((id, off, len));+ }+ let mut out = format!("dem-pyramid {path} tol={tol} m\n zoom with_dem dropped saved_MB(zstd19)\n");+ let (mut tot_saved, mut tot_drop, mut tot_dem) = (0i64, 0u64, 0u64);+ for (z, v) in &by_z {+ let res: Vec<(u64, Option<Heightmap>, Option<(u8, u64, u64)>, i64)> = v+ .par_iter()+ .map(|&(id, off, len)| {+ let (_, x, y) = tile_zxy(id);+ let body = body_at(&a, off, len);+ let Some(hm) = body.heightmap.clone() else { return (id, None, None, 0) };+ if *z == 0 {+ return (id, Some(hm), None, 0);+ }+ // Serving ancestor: the parent's own grid, or whatever serves the parent.+ let pid = tilecodec::pmtiles::tile_id(z - 1, x / 2, y / 2);+ let anc = kept.get(&pid).copied().unwrap_or((z - 1, x / 2, y / 2));+ let aid = tilecodec::pmtiles::tile_id(anc.0, anc.1, anc.2);+ let Some(ag) = grids.get(&aid) else { return (id, Some(hm), None, 0) };+ let k = 1u64 << (z - anc.0);+ let (ox, oy) = ((x - anc.1 * k) as f64, (y - anc.2 * k) as f64);+ let d = hm.dim as usize;+ let mut mx = 0.0f64;+ for r in 0..d {+ for c in 0..d {+ let fr = (oy + r as f64 / (d - 1) as f64) / k as f64;+ let fc = (ox + c as f64 / (d - 1) as f64) / k as f64;+ let e = (bilin(&ag.samples, ag.dim as usize, fr, fc) - hm.samples[r * d + c] as f64).abs();+ mx = mx.max(e);+ }+ }+ if mx <= tol {+ let mut nb = body.clone();+ nb.heightmap = None;+ let with = zstd_rs(&ser(&body)[H..], 19).len() as i64;+ let without = zstd_rs(&ser(&nb)[H..], 19).len() as i64;+ (id, None, Some(anc), with - without)+ } else {+ (id, Some(hm), None, 0)+ }+ })+ .collect();+ let (mut saved, mut dropped, mut with_dem) = (0i64, 0u64, 0u64);+ for (id, hm, anc, s) in res {+ if let Some(h) = hm {+ grids.insert(id, h);+ with_dem += 1;+ }+ if let Some(an) = anc {+ kept.insert(id, an);+ dropped += 1;+ with_dem += 1;+ saved += s;+ }+ }+ out += &format!(" z{z:<3} {with_dem:>9} {dropped:>8} {:>10.2}\n", saved as f64 / 1e6);+ tot_saved += saved;+ tot_drop += dropped;+ tot_dem += with_dem;+ }+ out += &format!(" all {tot_dem:>9} {tot_drop:>8} {:>10.2}\nDEMPYR_TSV\t{tol}\t{tot_dem}\t{tot_drop}\t{tot_saved}\n", tot_saved as f64 / 1e6);+ print!("{out}");+ std::fs::write(format!("{out_dir}/dem_pyramid_{tol}.txt"), &out).unwrap();+}++// ------------------------------------------------------------ transit pack analysis++fn rd_u32(b: &[u8], at: usize) -> u32 {+ u32::from_le_bytes(b[at..at + 4].try_into().unwrap())+}++fn uvar(b: &[u8], pos: &mut usize) -> u64 {+ let (mut r, mut s) = (0u64, 0);+ loop {+ let c = b[*pos];+ *pos += 1;+ r |= ((c & 0x7f) as u64) << s;+ if c < 0x80 {+ return r;+ }+ s += 7;+ }+}++fn uvar_len(v: u64) -> usize {+ let mut n = 1;+ let mut v = v >> 7;+ while v > 0 {+ n += 1;+ v >>= 7;+ }+ n+}++/// `transit WORLD.transit`: exact sizes of SHAPE_COORDS after error-bounded thinning (stop+/// vertices kept, so ROUTE_STOP_SHAPE stays valid after an index remap) at several+/// tolerances, with and without a 1e-6 deg grid; and what EXCEPTIONS would take packed.+fn cmd_transit(path: &str, out_dir: &str) {+ let f = File::open(path).expect("open");+ let m = unsafe { memmap2::Mmap::map(&f).expect("mmap") };+ let nsec = rd_u32(&m, 8) as usize;+ let route_count = rd_u32(&m, 16) as usize;+ let sec = |i: usize| -> &[u8] {+ let at = 80 + i * 16;+ let off = u64::from_le_bytes(m[at..at + 8].try_into().unwrap()) as usize;+ let len = u64::from_le_bytes(m[at + 8..at + 16].try_into().unwrap()) as usize;+ &m[off..off + len]+ };+ let mut out = format!("transit {path}: {nsec} sections, {route_count} routes\n");+ let shapes = sec(20);+ let shape_idx = sec(21);+ let routes = sec(2);+ let rss = sec(22);+ // Protected vertices per blob offset: every stop's vertex of every route using it.+ let mut prot: std::collections::HashMap<u32, Vec<u32>> = std::collections::HashMap::new();+ for r in 0..route_count {+ let off = rd_u32(shape_idx, r * 4);+ if off == u32::MAX {+ continue;+ }+ let n_stops = rd_u32(routes, r * 32 + 16) as usize;+ let first = rd_u32(routes, r * 32 + 20) as usize;+ let e = prot.entry(off).or_default();+ for k in 0..n_stops {+ let v = rd_u32(rss, (first + k) * 4);+ if v != u32::MAX {+ e.push(v);+ }+ }+ }+ let offs: Vec<u32> = {+ let mut v: Vec<u32> = prot.keys().copied().collect();+ v.sort();+ v+ };+ let tols = [0.0f64, 0.5, 1.0, 2.0, 5.0];+ // (bytes e7, bytes 1e-6 grid, points) per tolerance+ let res: Vec<Vec<(u64, u64, u64)>> = offs+ .par_iter()+ .map(|&off| {+ let mut pos = off as usize;+ let n = rd_u32(shapes, pos) as usize;+ pos += 4;+ let (mut la, mut lo) = (0i64, 0i64);+ let mut pts = Vec::with_capacity(n);+ for _ in 0..n {+ let dla = uvar(shapes, &mut pos);+ let dlo = uvar(shapes, &mut pos);+ la += ((dla >> 1) as i64) ^ -((dla & 1) as i64);+ lo += ((dlo >> 1) as i64) ^ -((dlo & 1) as i64);+ pts.push((la, lo));+ }+ let mut keep_base = vec![false; n];+ if n > 0 {+ keep_base[0] = true;+ keep_base[n - 1] = true;+ }+ for &v in &prot[&off] {+ if (v as usize) < n {+ keep_base[v as usize] = true;+ }+ }+ let lat0 = if n > 0 { pts[0].0 as f64 * 1e-7 } else { 0.0 };+ let kx = 0.011_131_949 * lat0.to_radians().cos();+ let xy: Vec<(f64, f64)> = pts.iter().map(|p| (p.1 as f64 * kx, p.0 as f64 * 0.011_131_949)).collect();+ tols.iter()+ .map(|&tol| {+ let mut keep = keep_base.clone();+ if tol > 0.0 && n > 2 {+ // DP between consecutive protected vertices.+ let anchors: Vec<usize> = (0..n).filter(|&i| keep_base[i]).collect();+ for w in anchors.windows(2) {+ let mut stack = vec![(w[0], w[1])];+ while let Some((a, b)) = stack.pop() {+ if b <= a + 1 {+ continue;+ }+ let (mut worst, mut wi) = (tol * tol, usize::MAX);+ for i in a + 1..b {+ let d = seg_dist_sq_f(xy[i], xy[a], xy[b]);+ if d > worst {+ worst = d;+ wi = i;+ }+ }+ if wi != usize::MAX {+ keep[wi] = true;+ stack.push((a, wi));+ stack.push((wi, b));+ }+ }+ }+ } else {+ keep.iter_mut().for_each(|k| *k = true);+ }+ let (mut b7, mut b6, mut np) = (4u64, 4u64, 0u64);+ let (mut p7, mut p6) = ((0i64, 0i64), (0i64, 0i64));+ for i in 0..n {+ if !keep[i] {+ continue;+ }+ let (a, o) = pts[i];+ let z = |v: i64| ((v << 1) ^ (v >> 63)) as u64;+ b7 += (uvar_len(z(a - p7.0)) + uvar_len(z(o - p7.1))) as u64;+ p7 = (a, o);+ let q = ((a as f64 / 10.0).round() as i64, (o as f64 / 10.0).round() as i64);+ b6 += (uvar_len(z(q.0 - p6.0)) + uvar_len(z(q.1 - p6.1))) as u64;+ p6 = q;+ np += 1;+ }+ (b7, b6, np)+ })+ .collect()+ })+ .collect();+ out += &format!("SHAPE_COORDS now {} B, {} unique blobs\n tol_m bytes_e7 bytes_1e-6 points\n", shapes.len(), offs.len());+ for (ti, tol) in tols.iter().enumerate() {+ let (b7, b6, np) = res.iter().fold((0u64, 0u64, 0u64), |a, r| (a.0 + r[ti].0, a.1 + r[ti].1, a.2 + r[ti].2));+ out += &format!(" {tol:<5} {b7:>12} {b6:>12} {np:>10}\nTRANSIT_SHAPES_TSV\t{tol}\t{b7}\t{b6}\t{np}\n");+ }+ // EXCEPTIONS packed: per service CSR (EXCEPTIONS_IDX) => drop service_idx, varint date+ // delta (days) + added bit in the low bit.+ let exc = sec(12);+ let rows = exc.len() / 12;+ let mut packed = 0u64;+ let mut prev_svc = u32::MAX;+ let mut prev_date = 0i64;+ let days = |d: u32| -> i64 {+ // YYYYMMDD -> day number (approx, monotone within a service)+ let (y, mo, da) = ((d / 10000) as i64, ((d / 100) % 100) as i64, (d % 100) as i64);+ y * 372 + mo * 31 + da+ };+ for r in 0..rows {+ let svc = rd_u32(exc, r * 12);+ let date = days(rd_u32(exc, r * 12 + 4));+ let added = rd_u32(exc, r * 12 + 8) as i64;+ let delta = if svc != prev_svc { date } else { date - prev_date };+ packed += uvar_len(((delta.max(0) as u64) << 1) | added as u64) as u64;+ prev_svc = svc;+ prev_date = date;+ }+ out += &format!("EXCEPTIONS now {} B ({} rows x 12 B); packed (CSR keeps service, varint date delta + added bit) {} B\nTRANSIT_EXC_TSV\t{}\t{}\n", exc.len(), rows, packed, exc.len(), packed);+ out += &format!("ROUTE_TRIPS (varint stream, unread when ROUTE_TRIP_RECS is present) {} B\nTRANSIT_RT_TSV\t{}\n", sec(4).len(), sec(4).len());+ print!("{out}");+ std::fs::write(format!("{out_dir}/transit.txt"), &out).unwrap();+}++// ------------------------------------------------------------ ZBLK re-encode++/// `zblk FILE`: exact size of a ZBLK section re-encoded at zstd 10/19/22 with 4096- and+/// 16384-record blocks, plus ruzstd decode time per block (what one cold lookup costs).+fn cmd_zblk(path: &str) {+ let f = File::open(path).expect("open");+ let m = unsafe { memmap2::Mmap::map(&f).expect("mmap") };+ let b = tilecodec::blocked::Blocked::parse(&m).expect("zblk");+ let rl = b.record_len();+ let nb = b.block_count();+ let raw: Vec<Vec<u8>> = (0..nb).into_par_iter().map(|i| b.block(i).expect("block")).collect();+ let all: Vec<u8> = raw.concat();+ let mut out = format!("{path}: {} B, record_len {rl}, {} blocks of {} records, unpacked {} B\n", m.len(), nb, b.records_per_block(), all.len());+ for per in [4096usize, 16384] {+ for level in [10, 19, 22] {+ let chunks: Vec<&[u8]> = all.chunks(per * rl).collect();+ let frames: Vec<Vec<u8>> = chunks.par_iter().map(|c| zstd_rs(c, level)).collect();+ let total: usize = 28 + 8 * (frames.len() + 1) + frames.iter().map(|f| f.len()).sum::<usize>();+ // Decode cost: sample 2000 frames.+ let step = (frames.len() / 2000).max(1);+ let t = Instant::now();+ let mut n = 0;+ let mut dec = ruzstd::decoding::FrameDecoder::new();+ for (fr, c) in frames.iter().zip(chunks.iter()).step_by(step) {+ let mut o = vec![0u8; c.len()];+ dec.decode_all(fr, &mut o).expect("dec");+ n += 1;+ }+ let us = t.elapsed().as_secs_f64() * 1e6 / n as f64;+ out += &format!(" block {per:>5} level {level:>2}: {total:>12} B ({:.3}x of now) decode {us:.0} us/block\nZBLK_TSV\t{path}\t{per}\t{level}\t{total}\t{us:.1}\n", total as f64 / m.len() as f64);+ }+ }+ print!("{out}");+}++/// `zooms ARCH`: exact stored bytes of unique bodies per zoom (a body shared across zooms is+/// counted once, at the lowest zoom that references it).+fn cmd_zooms(path: &str) {+ let a = open(path);+ let ents = entries(&a);+ let mut z = [0u64; 15];+ let mut n = [0u64; 15];+ for e in &ents {+ z[e.z.min(14) as usize] += e.len as u64;+ n[e.z.min(14) as usize] += 1;+ }+ for i in 0..15 {+ println!("ZOOM\t{i}\t{}\t{}", n[i], z[i]);+ }+ println!("LEAVES\t{}", a.hdr.leaf_len);+}