Modern Apps git

← Modern-Apps.git

maps: mamaps_planet5 + transit_planet5 converters, pack graph v8 (#planet5)

Commit
26189e7dec9c9925e9f5d9d21043a94673dba409
Author
Vayun Mathur <[email protected]>
When
2026-11-14 00:54 UTC (22 days ago)
Parents
fdef891
The two planet5 writers that run after mamaps_build, plus pack
support for the v8 graph.

- mamaps_planet5 IN OUT: transcodes a finished tile archive. Every
  body is re-encoded as v11 (MED-residual heightmap) and compressed at
  zstd-19 against its zoom band's trained dictionary (z0-9, z10-11,
  z12, z13, z14; 112 KiB each, trained with the C zdict trainer on a
  fixed stride of up to 20,000 distinct bodies per band -- host only,
  the decoder stays ruzstd). Tiles are re-appended in id order through
  StreamWriter, so runs, content dedup and the content build id are
  rebuilt the way the generator builds them. --verify decodes every
  output body and compares the parsed Body with the input's.
  US West balanced: tile data 2.20 GB -> 1.87 GB (-14.9 %), 23 s on
  192 threads, every body verified.
- transit_planet5 IN OUT: TRIX v7 -> v8. Drops the host-only
  sections; empties ROUTE_TRIPS (unread since TRX v6) after checking
  every route's trip table agrees with its record; thins SHAPE_COORDS
  with DP at --shape-tol-m between protected vertices (every stop's
  vertex of every route sharing the blob, and the ends), remapping
  ROUTE_STOP_SHAPE and rebuilding ROUTE_SHAPE_IDX; ZSEC-wraps every
  section. Planet: 4.44 GB -> 1.19 GB in 31 s; shape points 338.0 M
  -> 173.6 M at 1 m.
- mamaps_pack accepts graph v8 (only intermediate.bin differs, and
  it is validated by its trailer as before).
- tile_build: zstd-rs and zstd become normal (host-only) deps for
  the converter; size_lab moves to examples/size_lab/ so its include
  is not built as a second example.

Verified: cargo test -p tile_build; US West planet5 archive packed
from these outputs opens in the renderer (header v10, SF decodes and
tessellates at z0-14) and routes identically through the archive and
multi-file graph loaders.

Diff

scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex e5b4ec1ad3..c221f8848c 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -38,6 +38,12 @@ path = "src/bin/mamaps_dump.rs" name = "mamaps_pack" path = "src/bin/mamaps_pack.rs" [[bin]]+name = "transit_planet5"+path = "src/bin/transit_planet5.rs"+[[bin]]+name = "mamaps_planet5"+path = "src/bin/mamaps_planet5.rs"+[[bin]] name = "mamaps_churn" path = "src/bin/mamaps_churn.rs" [[bin]]@@ -53,6 +59,12 @@ sha2.workspace = true # Anonymous pagefile-backed mappings for the spill backends (see `anon`): already # in the tree via osm_ingest, so this adds a name to link, not a crate to fetch. memmap2.workspace = true+# Planet5 transcoder (`mamaps_planet5`): the pure-Rust zstd encoder with dictionaries (what the+# reader's `ruzstd` decodes), and the C zstd dictionary trainer -- host-only, never in the+# Android cdylib (tilecodec's reader keeps its single pure-Rust decoder). Both were already in+# the workspace's lockfile.+zstd-rs.workspace = true+zstd.workspace = true [profile.release] opt-level = 3 @@ -61,7 +73,5 @@ opt-level = 3 # 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/main.rs
diff --git a/scripts/maps/tile_build/examples/size_lab/main.rs b/scripts/maps/tile_build/examples/size_lab/main.rsindex 8f86bc974b..51086564d7 100644--- a/scripts/maps/tile_build/examples/size_lab/main.rs+++ b/scripts/maps/tile_build/examples/size_lab/main.rs@@ -977,7 +977,7 @@ fn cmd_sidecars(path: &str, windows: usize, out_dir: &str) {     let _ = std::io::stdout().flush(); } -include!("size_lab_more.rs");+include!("more.rs");  fn main() {     let args: Vec<String> = std::env::args().collect();
scripts/maps/tile_build/src/bin/mamaps_pack.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_pack.rs b/scripts/maps/tile_build/src/bin/mamaps_pack.rsindex e6d7f198ea..2cce943b1e 100644--- a/scripts/maps/tile_build/src/bin/mamaps_pack.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_pack.rs@@ -332,8 +332,10 @@ fn validate_sidecars(         return Err("metadata.bin is not a MARG graph header".to_string());     }     let graph_version = u32_at(&meta, 4);-    if graph_version != 6 && graph_version != 7 {-        return Err(format!("the graph is version {graph_version}, this pack reads v6..=v7"));+    // v8 (planet5) differs from v7 only inside intermediate.bin (varint shape points), which+    // is validated below by its trailer like any other version.+    if !(6..=8).contains(&graph_version) {+        return Err(format!("the graph is version {graph_version}, this pack reads v6..=v8"));     }     let blocked_v7 = graph_version >= 7;     let (node_count, edge_count) = (u64_at(&meta, 8), u64_at(&meta, 16));
scripts/maps/tile_build/src/bin/mamaps_planet5.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_planet5.rs b/scripts/maps/tile_build/src/bin/mamaps_planet5.rsnew file mode 100644index 0000000000..26d39008c0--- /dev/null+++ b/scripts/maps/tile_build/src/bin/mamaps_planet5.rs@@ -0,0 +1,272 @@+//! `mamaps_planet5` — transcode a finished tile archive into the planet5 tile format.+//!+//! ```text+//! mamaps_planet5 IN.mamaps OUT.mamaps [--dict-bytes N] [--train-per-band N]+//! ```+//!+//! Reads the tile archive `mamaps_build` wrote (v8/v9 header, DEFLATE or zstd v10 bodies) and+//! writes the same tiles as:+//!+//! * **v11 bodies** — byte-for-byte the v10 body except that the heightmap is MED-residual coded+//!   (`tilecodec::mamaps::body::serialize_into_v11`); decodes to the identical `Body`;+//! * **dictionary zstd** — one zstd dictionary trained per zoom band (z0-9, z10-11, z12, z13,+//!   z14) on a stride sample of that band's v11 bodies, every body compressed at zstd-19 against+//!   its band's dictionary; the dictionaries go into the v10 header's dictionary section.+//!+//! Every addressed tile id is appended in order through `StreamWriter`, so runs and content+//! dedup are rebuilt exactly as the generator builds them, and the content-derived build id is+//! re-derived over the new bodies (seeded with the input's id).+//!+//! Lossless: `--verify` decodes every output body and compares the parsed `Body` with the+//! input's. Deterministic: the training sample is a fixed stride and the encoder is a pure+//! function of input + dictionary, so the output does not depend on the thread count.+use std::collections::HashMap;+use std::fs::File;+use std::path::PathBuf;+use std::process::ExitCode;+use std::sync::Arc;+use std::time::Instant;++use rayon::prelude::*;+use tile_build::mamaps::body::{serialize_into_v11, Body, Scratch, BODY_HEADER_LEN};+use tile_build::mamaps::header::{Header, FLAG_RINGS_VALIDATED};+use tile_build::mamaps::index;+use tile_build::mamaps::read::decompress;+use tile_build::mamaps::write::{hash64, Options, StreamWriter};+use tile_build::mamaps::zdict::ZDicts;+use tilecodec::pmtiles::tile_zxy;++const BANDS: usize = 5;++fn band(z: u8) -> usize {+    match z {+        0..=9 => 0,+        10..=11 => 1,+        12 => 2,+        13 => 3,+        _ => 4,+    }+}++/// One leaf entry: first tile id, run length, absolute body offset and stored length.+#[derive(Clone, Copy)]+struct Ent {+    id: u64,+    run: u32,+    off: u64,+    len: u32,+}++fn entries(map: &[u8], hdr: &Header) -> Result<Vec<Ent>, String> {+    let root = index::parse_root(&map[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize])+        .map_err(|e| e.0)?;+    let per: Vec<Result<Vec<Ent>, String>> = 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 {+                map[at..at + raw_len].to_vec()+            } else {+                index::decompress_leaf(&map[at..at + re.stored_len as usize], raw_len).map_err(|e| e.0)?+            };+            Ok(index::parse_leaf(&raw)+                .map_err(|e| e.0)?+                .iter()+                .map(|e| Ent {+                    id: re.base_tile_id + e.tile_id_lo as u64,+                    run: e.run_length,+                    off: hdr.data_offset + re.base_data_offset + e.offset_delta as u64,+                    len: e.length,+                })+                .collect())+        })+        .collect();+    let mut out = Vec::new();+    for p in per {+        out.extend(p?);+    }+    out.sort_by_key(|e| e.id);+    Ok(out)+}++/// The v11 encoding of one stored input body.+fn to_v11(map: &[u8], hdr: &Header, off: u64, len: u32) -> Result<(Vec<u8>, Body), String> {+    let stored = &map[off as usize..off as usize + len as usize];+    let raw = decompress(hdr.compression, stored).map_err(|e| e.0)?;+    let body = Body::parse(&raw).map_err(|e| e.0)?;+    let mut s = Scratch::default();+    let v11 = serialize_into_v11(&body, &mut s).map_err(|e| e.0)?.to_vec();+    Ok((v11, body))+}++fn main() -> ExitCode {+    let args: Vec<String> = std::env::args().collect();+    let mut pos = Vec::new();+    let (mut dict_bytes, mut per_band, mut verify) = (112 * 1024usize, 20_000usize, false);+    let mut i = 1;+    while i < args.len() {+        match args[i].as_str() {+            "--dict-bytes" => {+                dict_bytes = args[i + 1].parse().expect("--dict-bytes N");+                i += 1;+            }+            "--train-per-band" => {+                per_band = args[i + 1].parse().expect("--train-per-band N");+                i += 1;+            }+            "--verify" => verify = true,+            a => pos.push(a.to_string()),+        }+        i += 1;+    }+    if pos.len() != 2 {+        eprintln!("usage: mamaps_planet5 IN.mamaps OUT.mamaps [--dict-bytes N] [--train-per-band N] [--verify]");+        return ExitCode::from(2);+    }+    match run(&pos[0], &pos[1], dict_bytes, per_band, verify) {+        Ok(()) => ExitCode::SUCCESS,+        Err(e) => {+            eprintln!("mamaps_planet5: {e}");+            ExitCode::FAILURE+        }+    }+}++fn run(input: &str, output: &str, dict_bytes: usize, per_band: usize, verify: bool) -> Result<(), String> {+    let t0 = Instant::now();+    let f = File::open(input).map_err(|e| format!("open {input}: {e}"))?;+    let map = unsafe { memmap2::Mmap::map(&f) }.map_err(|e| format!("mmap {input}: {e}"))?;+    let hdr = Header::parse(&map[..tilecodec::stream::OPEN_PREFIX_BYTES as usize]).map_err(|e| e.0)?;+    if hdr.compression == tile_build::mamaps::header::COMPRESSION_ZSTD_DICT {+        return Err("the input is already a planet5 archive".into());+    }+    let ents = entries(&map, &hdr)?;+    println!("input: {} leaf entries, {} bytes of tile data ({:.1}s)", ents.len(), hdr.data_len, t0.elapsed().as_secs_f64());++    // 1. Training: a fixed stride over each band's distinct bodies.+    let mut uniq: Vec<Vec<(u64, u32)>> = vec![Vec::new(); BANDS];+    {+        let mut seen: Vec<std::collections::HashSet<u64>> = vec![Default::default(); BANDS];+        for e in &ents {+            let b = band(tile_zxy(e.id).0);+            if seen[b].insert(e.off) {+                uniq[b].push((e.off, e.len));+            }+        }+    }+    let dicts: Vec<Vec<u8>> = uniq+        .par_iter()+        .enumerate()+        .map(|(b, v)| -> Result<Vec<u8>, String> {+            if v.len() < 256 {+                return Ok(Vec::new()); // too few bodies to train on: plain zstd frames+            }+            let step = (v.len() / per_band).max(1);+            let samples: Vec<Vec<u8>> = v+                .iter()+                .step_by(step)+                .map(|&(off, len)| to_v11(&map, &hdr, off, len).map(|(r, _)| r[BODY_HEADER_LEN..].to_vec()))+                .collect::<Result<_, _>>()?;+            let d = zstd::dict::from_samples(&samples, dict_bytes).map_err(|e| format!("train band {b}: {e}"))?;+            println!("  band {b}: {} distinct bodies, trained on {} -> {} B dictionary", v.len(), samples.len(), d.len());+            Ok(d)+        })+        .collect::<Result<_, _>>()?;+    let kept: Vec<Vec<u8>> = dicts.iter().filter(|d| !d.is_empty()).cloned().collect();+    let section = ZDicts::serialize(&kept);+    let verify_dicts = ZDicts::parse(&section).map_err(|e| e.0)?;+    let enc_dicts: Vec<Option<zstd_rs::EncoderDictionary>> = dicts+        .iter()+        .map(|d| -> Result<Option<zstd_rs::EncoderDictionary>, String> {+            if d.is_empty() {+                return Ok(None);+            }+            let dd = zstd_rs::Dictionary::new(d, zstd_rs::DictionaryFormat::Zstd).map_err(|e| format!("{e:?}"))?;+            Ok(Some(zstd_rs::EncoderDictionary::new(&dd, 19).map_err(|e| format!("{e:?}"))?))+        })+        .collect::<Result<_, _>>()?;+    println!("trained {} dictionaries ({} B section) in {:.1}s", kept.len(), section.len(), t0.elapsed().as_secs_f64());++    // 2. Re-encode and append, in tile id order, in batches.+    let out_path = PathBuf::from(output);+    let mut writer = StreamWriter::new(Options {+        min_zoom: hdr.min_zoom,+        max_zoom: hdr.max_zoom,+        build_id: hdr.build_id,+        build_id_from_content: true,+        compress: true,+        zdicts: Some(section),+        rings_validated: hdr.flags & FLAG_RINGS_VALIDATED != 0,+        leaf_entry_capacity: hdr.leaf_entry_capacity,+        spill_dir: out_path.parent().map(|p| p.to_path_buf()),+        min_lon_e7: hdr.min_lon_e7,+        min_lat_e7: hdr.min_lat_e7,+        max_lon_e7: hdr.max_lon_e7,+        max_lat_e7: hdr.max_lat_e7,+        ..Options::default()+    })+    .map_err(|e| e.0)?;+    let cfg = zstd_rs::CompressionConfig { level: 19, ..zstd_rs::CompressionConfig::DEFAULT };+    let (mut raw_in, mut stored_out) = (0u64, 0u64);+    const BATCH: usize = 1 << 21;+    for (bi, batch) in ents.chunks(BATCH).enumerate() {+        // Distinct (offset, band) pairs in this batch, encoded in parallel.+        let mut keys: Vec<(u64, u32, usize)> = batch.iter().map(|e| (e.off, e.len, band(tile_zxy(e.id).0))).collect();+        keys.sort_unstable();+        keys.dedup();+        let encoded: Vec<Result<((u64, usize), Arc<(Vec<u8>, u64)>, u64), String>> = keys+            .par_iter()+            .map_init(+                || zstd_rs::Compressor::new(cfg).expect("zstd level"),+                |enc, &(off, len, b)| {+                    let (v11, body) = to_v11(&map, &hdr, off, len)?;+                    let mut stored = Vec::with_capacity(v11.len() / 2);+                    stored.extend_from_slice(&v11[..BODY_HEADER_LEN]);+                    enc.compress(&v11[BODY_HEADER_LEN..], enc_dicts[b].as_ref(), &mut stored)+                        .map_err(|e| format!("zstd: {e:?}"))?;+                    if verify {+                        let back = tile_build::mamaps::read::decompress_with(+                            tile_build::mamaps::header::COMPRESSION_ZSTD_DICT,+                            &stored,+                            Some(&verify_dicts),+                        )+                        .map_err(|e| e.0)?;+                        if Body::parse(&back).map_err(|e| e.0)? != body {+                            return Err(format!("body at {off} does not round-trip"));+                        }+                    }+                    let h = hash64(&stored);+                    Ok(((off, b), Arc::new((stored, h)), v11.len() as u64))+                },+            )+            .collect();+        let mut by_key: HashMap<(u64, usize), Arc<(Vec<u8>, u64)>> = HashMap::with_capacity(encoded.len());+        for r in encoded {+            let (k, v, raw) = r?;+            raw_in += raw;+            by_key.insert(k, v);+        }+        for e in batch {+            let s = &by_key[&(e.off, band(tile_zxy(e.id).0))];+            for k in 0..e.run as u64 {+                writer.append_stored_with_hash(e.id + k, &s.0, s.1).map_err(|e| e.0)?;+            }+        }+        stored_out += by_key.values().map(|v| v.0.len() as u64).sum::<u64>();+        println!(+            "  batch {bi}: {} entries, {} distinct bodies ({:.0}s)",+            batch.len(),+            by_key.len(),+            t0.elapsed().as_secs_f64()+        );+    }+    writer.finish_to_path(&out_path).map_err(|e| e.0)?;+    let len = std::fs::metadata(&out_path).map_err(|e| e.to_string())?.len();+    println!(+        "wrote {output}: {len} bytes (input tile data {} B, v11 raw {raw_in} B, encoded distinct {stored_out} B) in {:.0}s",+        hdr.data_len,+        t0.elapsed().as_secs_f64()+    );+    Ok(())+}
scripts/maps/tile_build/src/bin/transit_planet5.rs
diff --git a/scripts/maps/tile_build/src/bin/transit_planet5.rs b/scripts/maps/tile_build/src/bin/transit_planet5.rsnew file mode 100644index 0000000000..27ef4c66ba--- /dev/null+++ b/scripts/maps/tile_build/src/bin/transit_planet5.rs@@ -0,0 +1,298 @@+//! `transit_planet5` — rewrite a TRIX v7 transit pack as planet5 TRIX v8.+//!+//! ```text+//! transit_planet5 IN.transit OUT.transit [--shape-tol-m 1.0]+//! ```+//!+//! * drops the host-only sections (27.., RAIL_LINES), as `mamaps_pack` already did;+//! * empties ROUTE_TRIPS (the varint trip stream): readers since TRX v6 take trips from+//!   ROUTE_TRIP_RECS/ROUTE_TRIP_OFF and fall back to the stream only for a route whose table+//!   disagrees with its `n_trips` — checked here for every route, and the stream is kept if any+//!   route would need it;+//! * thins SHAPE_COORDS with Douglas-Peucker at `--shape-tol-m` metres between protected+//!   vertices (every stop's vertex of every route sharing the blob, and both ends), remapping+//!   ROUTE_STOP_SHAPE to the kept vertices and rebuilding ROUTE_SHAPE_IDX; a ride leg still+//!   slices `shape[vertex(board)..=vertex(alight)]` exactly at its stops;+//! * stores every non-empty section as a 64 KiB zstd-19 ZSEC section and stamps version 8.+//!+//! The device reader (maps `transit.rs`) reads v3..=v8; a v7-only reader refuses v8 cleanly.+use std::fs::File;+use std::process::ExitCode;++const HEADER_LEN: usize = 80;+const DEVICE_SECTIONS: usize = 27;+const SEC_ROUTES: usize = 2;+const SEC_ROUTE_STOPS: usize = 3;+const SEC_ROUTE_TRIPS: usize = 4;+const SEC_SHAPE_COORDS: usize = 20;+const SEC_ROUTE_SHAPE_IDX: usize = 21;+const SEC_ROUTE_STOP_SHAPE: usize = 22;+const SEC_ROUTE_TRIP_RECS: usize = 25;+const SEC_ROUTE_TRIP_OFF: usize = 26;+const ROUTE_REC: usize = 32;+const NONE: u32 = u32::MAX;++fn u32_at(b: &[u8], o: usize) -> u32 {+    u32::from_le_bytes(b[o..o + 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 put_uvar(out: &mut Vec<u8>, mut v: u64) {+    loop {+        let b = (v & 0x7f) as u8;+        v >>= 7;+        if v == 0 {+            out.push(b);+            return;+        }+        out.push(b | 0x80);+    }+}++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;+    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) };+    (p.0 - a.0 - t * dx).powi(2) + (p.1 - a.1 - t * dy).powi(2)+}++fn main() -> ExitCode {+    let args: Vec<String> = std::env::args().collect();+    let mut tol = 1.0f64;+    let mut pos = Vec::new();+    let mut i = 1;+    while i < args.len() {+        if args[i] == "--shape-tol-m" {+            tol = args[i + 1].parse().expect("--shape-tol-m M");+            i += 2;+            continue;+        }+        pos.push(args[i].clone());+        i += 1;+    }+    if pos.len() != 2 {+        eprintln!("usage: transit_planet5 IN.transit OUT.transit [--shape-tol-m M]");+        return ExitCode::from(2);+    }+    match run(&pos[0], &pos[1], tol) {+        Ok(()) => ExitCode::SUCCESS,+        Err(e) => {+            eprintln!("transit_planet5: {e}");+            ExitCode::FAILURE+        }+    }+}++fn run(input: &str, output: &str, tol: f64) -> Result<(), String> {+    let f = File::open(input).map_err(|e| format!("open {input}: {e}"))?;+    let m = unsafe { memmap2::Mmap::map(&f) }.map_err(|e| e.to_string())?;+    if m.len() < HEADER_LEN || u32_at(&m, 0) != tilecodec::mamaps::archive::TRANSIT_MAGIC {+        return Err("not a TRIX pack".into());+    }+    let version = u32_at(&m, 4);+    if version != 7 {+        return Err(format!("expected a v7 pack, got v{version}"));+    }+    let count = u32_at(&m, 8) as usize;+    let route_count = u32_at(&m, 16) as usize;+    let sec = |i: usize| -> &[u8] {+        if i >= count {+            return &[];+        }+        let at = HEADER_LEN + 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 sections: Vec<Vec<u8>> = (0..DEVICE_SECTIONS).map(|i| sec(i).to_vec()).collect();+    let routes = sec(SEC_ROUTES);++    // ROUTE_TRIPS: drop only when every route's strided table agrees with its record.+    let trip_off = sec(SEC_ROUTE_TRIP_OFF);+    let recs_len = sec(SEC_ROUTE_TRIP_RECS).len();+    let table_ok = trip_off.len() >= (route_count + 1) * 4+        && (0..route_count).all(|r| {+            let n_trips = u32_at(routes, r * ROUTE_REC + 24);+            let (b, e) = (u32_at(trip_off, r * 4), u32_at(trip_off, r * 4 + 4));+            e >= b && e - b == n_trips && (e as usize) * 16 <= recs_len+        });+    let dropped_trips = if table_ok { std::mem::take(&mut sections[SEC_ROUTE_TRIPS]).len() } else { 0 };++    // SHAPE_COORDS thinning with stop vertices protected.+    let shapes = sec(SEC_SHAPE_COORDS);+    let shape_idx = sec(SEC_ROUTE_SHAPE_IDX);+    let rss = sec(SEC_ROUTE_STOP_SHAPE);+    let (mut pts_in, mut pts_out) = (0u64, 0u64);+    if !shapes.is_empty() && shape_idx.len() >= (route_count + 1) * 4 && tol > 0.0 {+        let mut prot: std::collections::BTreeMap<u32, Vec<u32>> = Default::default();+        for r in 0..route_count {+            let off = u32_at(shape_idx, r * 4);+            if off == NONE {+                continue;+            }+            let n_stops = u32_at(routes, r * ROUTE_REC + 16) as usize;+            let first = u32_at(routes, r * ROUTE_REC + 20) as usize;+            let e = prot.entry(off).or_default();+            for k in 0..n_stops {+                if (first + k + 1) * 4 <= rss.len() {+                    let v = u32_at(rss, (first + k) * 4);+                    if v != NONE {+                        e.push(v);+                    }+                }+            }+        }+        let mut new_shapes = Vec::with_capacity(shapes.len() / 2);+        let mut new_off: std::collections::HashMap<u32, u32> = Default::default();+        let mut remap: std::collections::HashMap<u32, Vec<u32>> = Default::default();+        for (&off, protected) in &prot {+            let mut p = off as usize;+            let n = u32_at(shapes, p) as usize;+            p += 4;+            let (mut la, mut lo) = (0i64, 0i64);+            let mut pts = Vec::with_capacity(n);+            for _ in 0..n {+                let a = uvar(shapes, &mut p);+                let b = uvar(shapes, &mut p);+                la += ((a >> 1) as i64) ^ -((a & 1) as i64);+                lo += ((b >> 1) as i64) ^ -((b & 1) as i64);+                pts.push((la, lo));+            }+            pts_in += n as u64;+            let mut keep = vec![false; n];+            if n > 0 {+                keep[0] = true;+                keep[n - 1] = true;+            }+            for &v in protected {+                if (v as usize) < n {+                    keep[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(|q| (q.1 as f64 * kx, q.0 as f64 * 0.011_131_949)).collect();+            let anchors: Vec<usize> = (0..n).filter(|&i| keep[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(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));+                    }+                }+            }+            let mut map = vec![NONE; n];+            let mut kept = 0u32;+            for i in 0..n {+                if keep[i] {+                    map[i] = kept;+                    kept += 1;+                }+            }+            new_off.insert(off, new_shapes.len() as u32);+            new_shapes.extend_from_slice(&kept.to_le_bytes());+            let (mut pl, mut pn) = (0i64, 0i64);+            for i in 0..n {+                if keep[i] {+                    let (a, b) = pts[i];+                    put_uvar(&mut new_shapes, (((a - pl) << 1) ^ ((a - pl) >> 63)) as u64);+                    put_uvar(&mut new_shapes, (((b - pn) << 1) ^ ((b - pn) >> 63)) as u64);+                    (pl, pn) = (a, b);+                }+            }+            pts_out += kept as u64;+            remap.insert(off, map);+        }+        let mut new_idx = Vec::with_capacity(shape_idx.len());+        let mut new_rss = rss.to_vec();+        for r in 0..route_count {+            let off = u32_at(shape_idx, r * 4);+            if off == NONE {+                new_idx.extend_from_slice(&NONE.to_le_bytes());+                continue;+            }+            new_idx.extend_from_slice(&new_off[&off].to_le_bytes());+            let map = &remap[&off];+            let n_stops = u32_at(routes, r * ROUTE_REC + 16) as usize;+            let first = u32_at(routes, r * ROUTE_REC + 20) as usize;+            for k in 0..n_stops {+                let at = (first + k) * 4;+                if at + 4 > new_rss.len() {+                    continue;+                }+                let v = u32_at(rss, at);+                if v != NONE {+                    let nv = map.get(v as usize).copied().unwrap_or(NONE);+                    if nv == NONE {+                        return Err(format!("route {r}: stop vertex {v} was not kept"));+                    }+                    new_rss[at..at + 4].copy_from_slice(&nv.to_le_bytes());+                }+            }+        }+        new_idx.extend_from_slice(&(new_shapes.len() as u32).to_le_bytes());+        sections[SEC_SHAPE_COORDS] = new_shapes;+        sections[SEC_ROUTE_SHAPE_IDX] = new_idx;+        sections[SEC_ROUTE_STOP_SHAPE] = new_rss;+    }++    // ZSEC every non-empty section; v8 header and directory.+    let raw_total: usize = sections.iter().map(|s| s.len()).sum();+    let stored: Vec<Vec<u8>> = sections+        .iter()+        .map(|s| if s.is_empty() { Vec::new() } else { tilecodec::zsec::write_zsec(s, tilecodec::zsec::ZSEC_BLOCK, 19) })+        .collect();+    let mut out = m[..HEADER_LEN].to_vec();+    out[4..8].copy_from_slice(&tilecodec::mamaps::archive::TRANSIT_VERSION_ZSEC.to_le_bytes());+    out[8..12].copy_from_slice(&(DEVICE_SECTIONS as u32).to_le_bytes());+    let dir_at = out.len();+    out.resize(dir_at + DEVICE_SECTIONS * 16, 0);+    for (i, s) in stored.iter().enumerate() {+        while out.len() % 8 != 0 {+            out.push(0);+        }+        let off = out.len() as u64;+        out.extend_from_slice(s);+        let at = dir_at + i * 16;+        out[at..at + 8].copy_from_slice(&off.to_le_bytes());+        out[at + 8..at + 16].copy_from_slice(&(s.len() as u64).to_le_bytes());+    }+    std::fs::write(output, &out).map_err(|e| format!("write {output}: {e}"))?;+    println!(+        "transit_planet5: {} -> {} bytes (device sections raw {} B after thinning); ROUTE_TRIPS dropped {} B{}; shape points {} -> {} at {} m",+        m.len(),+        out.len(),+        raw_total,+        dropped_trips,+        if table_ok { "" } else { " (kept: a route's trip table disagrees)" },+        pts_in,+        pts_out,+        tol+    );+    Ok(())+}