Modern Apps git

← Modern-Apps.git

library-map: run archive tests on synthetic archives (#tests)

Commit
aff11fe0c80adb7c42ff2707adad0137d645a171
Author
Vayun Mathur <[email protected]>
When
2026-11-15 17:49 UTC (20 days ago)
Parents
b0062bd
The five real-archive tests in tests/real_archive.rs were
#[ignore]d behind MAMAPS_REAL_ARCHIVE, so the default suite never
exercised the renderer's archive reader. They now build a small
synthetic .mamaps archive in a temp dir through tilecodec's
StreamWriter (the same writer the generator uses) and run against
it by default; MAMAPS_REAL_ARCHIVE still selects the planet file,
with the planet-only assertions (v9/v10 header pin, published body
versions, real relief ranges) kept behind that branch.

The synthetic archive (tests/real_archive/fixture.rs) carries
rich tile bodies -- every basemap layer but traffic, plus turn
lanes, carriageways, building attrs, region links and a DEM
heightmap -- and, for the section-directory test, a sidecar with
the smallest graph/POI/transit payloads ArchiveView accepts. The
tests assert the same behaviour as the planet run: header and
dictionary acceptance, every sidecar kind present, every layer
decoding and tessellating in four cities, heightmaps sampling and
draping into terrain, and an overlay segment serving patch-first
with tombstones over the base.

Left ignored, deliberately: live_planet4_reads_through_the_range_cache
(pins the published planet4 build id/length over the network;
also stale since the archive URL moved to planet5), the five
frame_cpu_bench timing harnesses and the timing.rs report-cost
measurement. map_renderer ignored 12 -> 7.

Verified: cargo test --profile fast -p map_renderer (default run)
575 passed, 0 failed, 7 ignored (was 570 passed, 12 ignored);
the five converted tests pass in 0.04s with no env var set.

Diff

library/map/src/main/rust/tests/real_archive.rs
diff --git a/library/map/src/main/rust/tests/real_archive.rs b/library/map/src/main/rust/tests/real_archive.rsindex 88a1d39196..c769df2dac 100644--- a/library/map/src/main/rust/tests/real_archive.rs+++ b/library/map/src/main/rust/tests/real_archive.rs@@ -1,12 +1,13 @@ //! The renderer's reader against a REAL planet archive (`planet4.mamaps` / `planet5.mamaps`, or the //! byte-identical local build `scripts/maps/inputs/world.mamaps`). //!-//! Ignored by default and gated on `MAMAPS_REAL_ARCHIVE`, so a normal `cargo test` never-//! needs the 80 GB input:+//! By default these tests run against a small SYNTHETIC archive built+//! in-test (see `fixture.rs`): the same reader paths, without the+//! 80 GB input. Set the env var to run them against the planet instead: //! //! ```text //! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps \-//!   cargo test -p map_renderer --test real_archive -- --ignored --nocapture --test-threads=1+//!   cargo test -p map_renderer --test real_archive -- --nocapture --test-threads=1 //! ``` //! //! Everything goes through the code the app runs: `FileRangeReader` (the device's@@ -28,7 +29,8 @@ use tilecodec::mamaps::body::Body; use tilecodec::mamaps::header::Header; use tilecodec::mamaps::read::{LeafCache, MamapsArchive, TileSource}; -const ENV: &str = "MAMAPS_REAL_ARCHIVE";+#[path = "real_archive/fixture.rs"]+mod fixture;  // planet4 claims FLAG_RINGS_VALIDATED without earning it; the renderer must keep repairing. const _: () = assert!(!geometry::TRUST_RINGS_VALIDATED);@@ -42,14 +44,12 @@ const CITIES: &[(&str, f64, f64)] = &[ ]; const ZOOMS: &[u8] = &[0, 4, 8, 10, 12, 13, 14]; -fn archive_path() -> Option<PathBuf> {-    match std::env::var(ENV) {-        Ok(p) if !p.trim().is_empty() && Path::new(&p).is_file() => Some(PathBuf::from(p)),-        _ => {-            eprintln!("{ENV} not set (or not a file): real-archive test skipped");-            None-        }-    }+fn acquire(tag: &str, build: impl FnOnce(&Path)) -> (PathBuf, bool) {+    fixture::acquire(tag, build)+}++fn tile_of(lat: f64, lon: f64, z: u8) -> (u32, u32) {+    fixture::tile_of(lat, lon, z) }  fn open(path: &Path) -> MamapsArchive<FileRangeReader> {@@ -60,16 +60,6 @@ fn open(path: &Path) -> MamapsArchive<FileRangeReader> {     .expect("the app's reader refused the archive") } -/// Slippy-map tile containing (lat, lon) at zoom `z`.-fn tile_of(lat: f64, lon: f64, z: u8) -> (u32, u32) {-    let n = (1u64 << z) as f64;-    let x = ((lon + 180.0) / 360.0 * n).floor();-    let lat_r = lat.to_radians();-    let y = ((1.0 - (lat_r.tan() + 1.0 / lat_r.cos()).ln() / std::f64::consts::PI) / 2.0 * n).floor();-    let max = n as u32 - 1;-    ((x as u32).min(max), (y as u32).min(max))-}- fn all_on() -> LayerToggles {     LayerToggles { poi: true, transit: true, traffic: true, safety: true } }@@ -79,9 +69,10 @@ fn layer_name(id: u8) -> &'static str { }  #[test]-#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"] fn header_version_and_dictionary_are_accepted() {-    let Some(path) = archive_path() else { return };+    let (path, planet) = acquire("header", |p| {+        fixture::write_archive(p, &[(0, 0, 0, fixture::rich_body(120))]);+    });     let mut head = vec![0u8; tilecodec::mamaps::header::HEADER_LEN];     {         use std::io::Read as _;@@ -93,13 +84,25 @@ fn header_version_and_dictionary_are_accepted() {         head[7], header.flags, header.compression, header.layer_count, header.min_zoom,         header.max_zoom, header.build_id, header.file_len     );-    // planet4 is a v9 archive; planet5 a v10 one (dictionary-zstd bodies). Both must open.-    match head[7] {-        tilecodec::mamaps::header::FORMAT_VERSION_V9 => {}-        tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V10 | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V11 => {-            assert_eq!(header.compression, tilecodec::mamaps::header::COMPRESSION_ZSTD_DICT);+    if planet {+        // planet4 is a v9 archive; planet5 a v10 one (dictionary-zstd bodies). Both must open.+        match head[7] {+            tilecodec::mamaps::header::FORMAT_VERSION_V9 => {}+            tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V10 | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V11 => {+                assert_eq!(header.compression, tilecodec::mamaps::header::COMPRESSION_ZSTD_DICT);+            }+            v => panic!("planet4 is v9 and planet5 v10/v11 (superblocks), got v{v}"),         }-        v => panic!("planet4 is v9 and planet5 v10/v11 (superblocks), got v{v}"),+    } else {+        // The synthetic writer's header must sit in the reader's accepted set.+        match head[7] {+            tilecodec::mamaps::header::FORMAT_VERSION+            | tilecodec::mamaps::header::FORMAT_VERSION_V9+            | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V10+            | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V11 => {}+            v => panic!("synthetic archive carries a version the reader refuses, got v{v}"),+        }+        assert_eq!(header.build_id, fixture::BUILD_ID);     }     assert_eq!(header.file_len, std::fs::metadata(&path).unwrap().len());     assert!(header.compressed() && header.rings_validated() && header.leaves_compressed());@@ -124,9 +127,11 @@ fn header_version_and_dictionary_are_accepted() { }  #[test]-#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"] fn section_directory_carries_every_kind_the_app_reads() {-    let Some(path) = archive_path() else { return };+    let (path, _planet) = acquire("sections", |p| {+        fixture::write_archive(p, &[(0, 0, 0, fixture::rich_body(120))]);+        fixture::append_sidecar(p);+    });     let file = std::fs::File::open(&path).unwrap();     // SAFETY: read-only mapping of a file nobody writes while the test runs.     let bytes = unsafe { memmap2::Mmap::map(&file) }.expect("mmap");@@ -165,9 +170,17 @@ struct LayerTally { }  #[test]-#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"] fn every_layer_decodes_and_tessellates_in_four_cities() {-    let Some(path) = archive_path() else { return };+    let (path, planet) = acquire("cities", |p| {+        let mut tiles = Vec::new();+        for &(_, lat, lon) in CITIES {+            for &z in ZOOMS {+                let (x, y) = tile_of(lat, lon, z);+                tiles.push((z, x, y, fixture::rich_body(120)));+            }+        }+        fixture::write_archive(p, &tiles);+    });     let archive = open(&path);     let layers = style::layers();     let rings_validated = archive.header.rings_validated() && geometry::TRUST_RINGS_VALIDATED;@@ -235,24 +248,42 @@ fn every_layer_decodes_and_tessellates_in_four_cities() {     for (name, t) in &tally {         println!("layer {name:<10} tiles {:3} features {}", t.tiles, t.features);     }-    for name in tilecodec::mamaps::dict::LAYERS {-        if *name == "junction" {-            // planet5 (~50 GB revision) builds with --no-junction-layer: lane connectors are drawn-            // only by the carriageway style layers, which style::LANE_RENDERING drops for release.-            // planet4 still carries them; either is valid.-            continue;-        }-        if *name == "traffic" {-            // The writer stopped emitting `traffic` features (mamaps_build extract_part3.rs:-            // "dropped as of the NA diet"); the layer stays in the dictionary with zero-            // features. Pinned so a rebuild that brings it back is noticed.-            assert!(!tally.contains_key(name), "traffic layer is back: wire up and test it");-            continue;+    if planet {+        for name in tilecodec::mamaps::dict::LAYERS {+            if *name == "junction" {+                // planet5 (~50 GB revision) builds with --no-junction-layer: lane connectors are drawn+                // only by the carriageway style layers, which style::LANE_RENDERING drops for release.+                // planet4 still carries them; either is valid.+                continue;+            }+            if *name == "traffic" {+                // The writer stopped emitting `traffic` features (mamaps_build extract_part3.rs:+                // "dropped as of the NA diet"); the layer stays in the dictionary with zero+                // features. Pinned so a rebuild that brings it back is noticed.+                assert!(!tally.contains_key(name), "traffic layer is back: wire up and test it");+                continue;+            }+            assert!(+                tally.get(name).is_some_and(|t| t.features > 0),+                "layer {name} never appeared in {tiles} city tiles"+            );         }+        // planet4 carries v10 bodies, planet5 v11 (MED-residual heightmaps); never a mix.         assert!(-            tally.get(name).is_some_and(|t| t.features > 0),-            "layer {name} never appeared in {tiles} city tiles"+            versions.len() == 1 && versions.keys().all(|&v| (10..=12).contains(&v)),+            "expected one body version, v10 (planet4) or v11/v12 (planet5), got {versions:?}"         );+    } else {+        // The synthetic body carries every layer but `traffic` (which the+        // writer no longer emits, exactly as on the planet).+        for name in ["landtype", "roads", "boundaries", "buildings", "places", "poi", "transit", "junction", "safety"] {+            assert!(+                tally.get(name).is_some_and(|t| t.features > 0),+                "layer {name} never appeared in {tiles} synthetic tiles"+            );+        }+        assert!(!tally.contains_key("traffic"), "traffic layer is back: wire up and test it");+        assert!(versions.len() == 1, "expected one body version, got {versions:?}");     }     assert!(buildings > 0, "no 3D buildings tessellated");     // Lane rendering is switched off in the style (style::LANE_RENDERING, z16+ overzoom), so@@ -264,26 +295,33 @@ fn every_layer_decodes_and_tessellates_in_four_cities() {     assert!(regions > 0, "no region-mask shapes (boundaries)");     assert!(extra.contains_key("heightmap"), "no heightmap on any city tile");     assert!(extra.contains_key("region_links"), "no region-link tables decoded");-    // planet4 carries v10 bodies, planet5 v11 (MED-residual heightmaps); never a mix.-    assert!(-        versions.len() == 1 && versions.keys().all(|&v| (10..=12).contains(&v)),-        "expected one body version, v10 (planet4) or v11/v12 (planet5), got {versions:?}"-    ); }  #[test]-#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"] fn dem_heightmaps_sample_and_drape() {-    let Some(path) = archive_path() else { return };+    // (name, lat, lon, zoom, min peak metres, synthetic heightmap lo..hi)+    type DemCase = (&'static str, f64, f64, u8, i32, (i32, i32));+    let cases: &[DemCase] = &[+        ("Fuji", 35.3606, 138.7274, 12, 2500, (100, 3000)),+        ("Fuji", 35.3606, 138.7274, 10, 2000, (100, 3000)),+        ("SF Twin Peaks", 37.7544, -122.4477, 12, 150, (20, 220)),+        ("Denver flat", 39.7392, -104.9903, 12, 1400, (1500, 1700)),+    ];+    let (path, _planet) = acquire("dem", |p| {+        let tiles: Vec<(u8, u32, u32, Body)> = cases+            .iter()+            .map(|&(_, lat, lon, z, _, (lo, hi))| {+                let (x, y) = tile_of(lat, lon, z);+                (z, x, y, fixture::dem_body(lo, hi))+            })+            .collect();+        fixture::write_archive(p, &tiles);+    });     let archive = open(&path);     let layers = style::layers();-    // Mount Fuji (3776 m) and the SF hills: relief must come through with real metres.-    for &(name, lat, lon, z, min_peak) in &[-        ("Fuji", 35.3606, 138.7274, 12u8, 2500i32),-        ("Fuji", 35.3606, 138.7274, 10u8, 2000i32),-        ("SF Twin Peaks", 37.7544, -122.4477, 12u8, 150i32),-        ("Denver flat", 39.7392, -104.9903, 12u8, 1400i32),-    ] {+    // Mount Fuji (3776 m) and the SF hills on the planet; synthetic+    // heightmaps encode the same relief ranges in-test.+    for &(name, lat, lon, z, min_peak, _) in cases {         let (x, y) = tile_of(lat, lon, z);         let body = archive.tile(z, x, y).unwrap().expect("tile present");         let hm = body.heightmap.as_ref().unwrap_or_else(|| panic!("{name} {z}/{x}/{y}: no heightmap"));@@ -300,10 +338,22 @@ fn dem_heightmaps_sample_and_drape() { }  #[test]-#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"] fn an_overlay_segment_is_discovered_and_served_patch_first() {     use tilecodec::mamaps::write::{Options, StreamWriter};-    let Some(path) = archive_path() else { return };+    let (path, _planet) = acquire("overlay-base", |p| {+        let tiles: Vec<(u8, u32, u32, Body)> = [+            (37.7749, -122.4194),+            (51.5074, -0.1278),+            (40.7580, -73.9855),+        ]+        .iter()+        .map(|&(lat, lon)| {+            let (x, y) = tile_of(lat, lon, 14);+            (14, x, y, fixture::rich_body(120))+        })+        .collect();+        fixture::write_archive(p, &tiles);+    });     let base = open(&path);     let build = base.header.build_id;     let len = base.header.file_len;@@ -319,11 +369,14 @@ fn an_overlay_segment_is_discovered_and_served_patch_first() {     patched.buildings.clear();     assert!(patched.layers.len() < before, "SF z14 had no buildings layer to drop"); -    let dir = std::env::temp_dir().join(format!("real-archive-overlay-{}", std::process::id()));+    let dir = std::env::temp_dir().join(format!("synthetic-overlay-{}", std::process::id()));     let _ = std::fs::remove_dir_all(&dir);     std::fs::create_dir_all(dir.join("overlays/0001")).unwrap();     let base_link = dir.join("basemap.mamaps");+    #[cfg(unix)]     std::os::unix::fs::symlink(&path, &base_link).unwrap();+    #[cfg(not(unix))]+    std::fs::copy(&path, &base_link).unwrap();     let mut writer = StreamWriter::new(Options {         build_id: 0xabcd,         rings_validated: true,@@ -340,7 +393,7 @@ fn an_overlay_segment_is_discovered_and_served_patch_first() {     );     std::fs::write(dir.join("overlays/manifest.json"), manifest).unwrap(); -    let found = discover(&base_link, Arc::new(LeafCache::new())).expect("discover refused a valid overlay over the real base");+    let found = discover(&base_link, Arc::new(LeafCache::new())).expect("discover refused a valid overlay over the base");     assert_eq!(found.seq, 1);     let overlay = found.overlay;     assert_eq!(overlay.header().build_id, build, "the overlay keeps the base identity");@@ -391,6 +444,10 @@ impl map_renderer::tile::source::RangeFetcher for CurlFetcher { /// fetch first, the origin marker it keys the disk cache on, then a cold tile read through /// `CachingRangeReader` + `RangeCache` + the shared decoder — compared byte-for-byte with the /// local copy when `MAMAPS_REAL_ARCHIVE` is set too. Gated on `MAMAPS_LIVE=1` (network).+///+/// Planet-only by construction (it pins the published file's build id and+/// length), so it stays ignored; the synthetic tests above cover the same+/// reader paths offline. #[test] #[ignore = "needs MAMAPS_LIVE=1 and network to data.maproj.org"] fn live_planet4_reads_through_the_range_cache() {@@ -429,7 +486,7 @@ fn live_planet4_reads_through_the_range_cache() {     println!("live: SF z14 has {} layers; {cached} ranges cached under {origin}", body.layers.len());     assert!(cached > 0, "nothing landed in the range cache");     assert_eq!(std::fs::read_to_string(dir.join(".origin")).unwrap().trim(), origin);-    if let Some(path) = archive_path() {+    if let Some(path) = fixture::planet_path() {         let local = open(&path);         assert_eq!(local.header, header, "local world.mamaps is not the published planet4");         assert_eq!(local.tile(14, x, y).unwrap().unwrap(), body, "live and local bodies differ");
library/map/src/main/rust/tests/real_archive/fixture.rs
diff --git a/library/map/src/main/rust/tests/real_archive/fixture.rs b/library/map/src/main/rust/tests/real_archive/fixture.rsnew file mode 100644index 0000000000..6cb3ab4f63--- /dev/null+++ b/library/map/src/main/rust/tests/real_archive/fixture.rs@@ -0,0 +1,293 @@+//! Synthetic `.mamaps` archives for the real-archive tests.+//!+//! The planet tests in `real_archive.rs` run against these archives by+//! default (temp dir, built in-test through the same `StreamWriter` the+//! generator uses); setting `MAMAPS_REAL_ARCHIVE` switches them back to+//! the real planet file. Nothing here reads fixtures from disk.++use std::path::{Path, PathBuf};++use tilecodec::mamaps::archive::{+    self as sidecar, ArchiveEntry, GRAPH_MAGIC, GRAPH_VERSION_MIN, TRANSIT_MAGIC,+};+use tilecodec::mamaps::body::{+    BuildingAttrs, Carriageway, Feature, Heightmap, LaneTurns, Layer as BodyLayer,+    MarkingConvention, Part, GEOM_LINE, GEOM_POINT, GEOM_POLYGON, NAME_NONE, WINDING_OUTER,+};+use tilecodec::mamaps::dict;+use tilecodec::mamaps::header::Header;+use tilecodec::mamaps::write::{Options, StreamWriter};+use tilecodec::pmtiles::tile_id;++/// Build id stamped on every synthetic archive (and its sidecar footer).+pub const BUILD_ID: u64 = 0x5eed_5eed_5eed_5eed;++const ENV: &str = "MAMAPS_REAL_ARCHIVE";++/// The planet archive `MAMAPS_REAL_ARCHIVE` names, if any.+pub fn planet_path() -> Option<PathBuf> {+    match std::env::var(ENV) {+        Ok(p) if !p.trim().is_empty() && Path::new(&p).is_file() => Some(PathBuf::from(p)),+        _ => None,+    }+}++/// The archive under test: the planet file when `MAMAPS_REAL_ARCHIVE`+/// names one (`planet == true`), else the synthetic archive `build`+/// writes to a temp file.+pub fn acquire(tag: &str, build: impl FnOnce(&Path)) -> (PathBuf, bool) {+    match planet_path() {+        Some(path) => (path, true),+        None => {+            let path = temp_path(tag);+            build(&path);+            (path, false)+        }+    }+}++/// Slippy-map tile containing (lat, lon) at zoom `z`.+pub fn tile_of(lat: f64, lon: f64, z: u8) -> (u32, u32) {+    let n = (1u64 << z) as f64;+    let x = ((lon + 180.0) / 360.0 * n).floor();+    let lat_r = lat.to_radians();+    let y = ((1.0 - (lat_r.tan() + 1.0 / lat_r.cos()).ln() / std::f64::consts::PI) / 2.0 * n).floor();+    let max = n as u32 - 1;+    ((x as u32).min(max), (y as u32).min(max))+}++/// A temp `.mamaps` path unique to this test process and `tag`.+pub fn temp_path(tag: &str) -> PathBuf {+    let path = std::env::temp_dir().join(format!(+        "synthetic-archive-{tag}-{}.mamaps",+        std::process::id()+    ));+    let _ = std::fs::remove_file(&path);+    path+}++fn kind(name: &str) -> u16 {+    map_renderer::style::kind_id(name).unwrap_or_else(|| panic!("schema kind {name}"))+}++fn feat(kind: u16, geom_type: u8, name_idx: u16) -> Feature {+    Feature {+        kind,+        kind_detail: dict::NONE,+        geom_type,+        flags: 0,+        name_idx,+        parts_offset: 0,+        part_count: 1,+        transit_color: 0,+        transit_ordinal: 0,+        transit_lanes: 0,+        transit_taper: 0,+        lane_count: 0,+    }+}++fn push(layer: &mut BodyLayer, mut f: Feature, pts: &[(i16, i16)]) {+    f.parts_offset = layer.parts.len() as u32;+    layer.parts.push(Part {+        coord_start: layer.coords.len() as u32,+        point_count: pts.len() as u32,+        winding: WINDING_OUTER,+    });+    layer.coords.extend_from_slice(pts);+    layer.features.push(f);+}++/// A tile body carrying every basemap layer the style draws (all but+/// `traffic`, which the planet writer no longer emits either), plus the+/// optional side tables the reader decodes: turn lanes, carriageways,+/// building attrs, region links and a DEM heightmap peaking at `peak`+/// metres.+pub fn rich_body(peak: i32) -> tilecodec::mamaps::body::Body {+    let mut body = tilecodec::mamaps::body::Body::new(4096);+    body.names = vec![+        "Grid Street".to_string(),+        "Synthetic City".to_string(),+        "Cafe".to_string(),+    ];++    let mut landtype = BodyLayer::new(dict::LAYER_LANDTYPE);+    push(&mut landtype, feat(dict::NONE, GEOM_POLYGON, NAME_NONE), &[(0, 0), (4096, 0), (4096, 4096), (0, 4096)]);+    push(&mut landtype, feat(kind("lake"), GEOM_POLYGON, NAME_NONE), &[(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)]);+    body.layers.push(landtype);++    let mut roads = BodyLayer::new(dict::LAYER_ROADS);+    let mut road = feat(kind("major_road"), GEOM_LINE, 1);+    road.lane_count = 2;+    push(&mut roads, road, &[(100, 100), (1500, 900), (2600, 1800), (3900, 2700)]);+    body.layers.push(roads);++    let mut boundaries = BodyLayer::new(dict::LAYER_BOUNDARIES);+    push(&mut boundaries, feat(kind("region_area"), GEOM_POLYGON, NAME_NONE), &[(200, 200), (3800, 200), (3800, 3800), (200, 3800)]);+    body.layers.push(boundaries);++    let mut buildings = BodyLayer::new(dict::LAYER_BUILDINGS);+    push(&mut buildings, feat(kind("building"), GEOM_POLYGON, NAME_NONE), &[(0, 0), (1000, 0), (1000, 1000), (0, 1000), (0, 0)]);+    body.layers.push(buildings);++    let mut places = BodyLayer::new(dict::LAYER_PLACES);+    push(&mut places, feat(kind("locality"), GEOM_POINT, 2), &[(2048, 2048)]);+    body.layers.push(places);++    let mut poi = BodyLayer::new(dict::LAYER_POI);+    push(&mut poi, feat(kind("cafe"), GEOM_POINT, 3), &[(1024, 1024)]);+    body.layers.push(poi);++    let mut transit = BodyLayer::new(dict::LAYER_TRANSIT);+    let mut line = feat(kind("rail"), GEOM_LINE, NAME_NONE);+    line.transit_color = 0x00E3_1B23;+    line.transit_lanes = 1;+    line.transit_taper = 255;+    push(&mut transit, line, &[(0, 4000), (4096, 200)]);+    body.layers.push(transit);++    let mut junction = BodyLayer::new(dict::LAYER_JUNCTION);+    push(&mut junction, feat(dict::NONE, GEOM_LINE, NAME_NONE), &[(0, 100), (500, 100), (1000, 300)]);+    body.layers.push(junction);++    let mut safety = BodyLayer::new(dict::LAYER_SAFETY);+    push(&mut safety, feat(kind("speed_camera"), GEOM_POINT, NAME_NONE), &[(3000, 3000)]);+    body.layers.push(safety);++    body.ids = vec![(dict::LAYER_BOUNDARIES, vec![4242])];+    body.turn_lanes = vec![(dict::LAYER_ROADS, vec![LaneTurns { forward: vec![0b0110], backward: Vec::new() }])];+    body.buildings = vec![(dict::LAYER_BUILDINGS, vec![BuildingAttrs {+        height: 120,+        min_height: 0,+        roof_height: 0,+        roof_shape: 0,+        roof_direction: 0,+        roof_orientation: 0,+        building_colour: 0,+        roof_colour: 0,+    }])];+    body.carriageways = vec![(dict::LAYER_ROADS, vec![Carriageway { forward: 1, backward: 1, solid_dividers: 0 }])];+    body.convention = Some(MarkingConvention { left_hand: false, yellow_centre: false });+    body.region_links = vec![(dict::LAYER_PLACES, vec![4242])];+    body.heightmap = Some(heightmap(4, 0, peak));+    body+}++/// A `dim` x `dim` heightmap rising by row from `lo` to `hi` metres.+pub fn heightmap(dim: u16, lo: i32, hi: i32) -> Heightmap {+    let mut samples = Vec::with_capacity(dim as usize * dim as usize);+    for row in 0..dim {+        let metres = if dim > 1 { lo + (hi - lo) * i32::from(row) / i32::from(dim - 1) } else { lo };+        for _ in 0..dim {+            samples.push((metres + 32768) as u16);+        }+    }+    Heightmap { dim, samples }+}++/// A rich body whose heightmap spans `lo..hi` metres (DEM tests).+pub fn dem_body(lo: i32, hi: i32) -> tilecodec::mamaps::body::Body {+    let mut body = rich_body(hi);+    body.heightmap = Some(heightmap(8, lo, hi));+    body+}++/// Write `tiles` (any order; the writer needs ascending tile ids) as a+/// tiles-only archive at `path` and return the path.+pub fn write_archive(path: &Path, tiles: &[(u8, u32, u32, tilecodec::mamaps::body::Body)]) -> PathBuf {+    let mut rows: Vec<(u64, &tilecodec::mamaps::body::Body)> = tiles+        .iter()+        .map(|(z, x, y, b)| (tile_id(*z, u64::from(*x), u64::from(*y)), b))+        .collect();+    rows.sort_by_key(|(id, _)| *id);+    // Distinct cities share the z0 tile; the writer wants each id once.+    rows.dedup_by_key(|(id, _)| *id);+    let mut writer = StreamWriter::new(Options {+        build_id: BUILD_ID,+        rings_validated: true,+        ..Options::default()+    })+    .expect("writer options");+    for (id, body) in rows {+        writer.append(id, body).expect("append tile");+    }+    writer.finish_to_path(path).expect("finish archive");+    path.to_path_buf()+}++fn graph_meta(node_count: u64, edge_count: u64) -> Vec<u8> {+    let mut out = Vec::new();+    out.extend_from_slice(&GRAPH_MAGIC.to_le_bytes());+    out.extend_from_slice(&GRAPH_VERSION_MIN.to_le_bytes());+    out.extend_from_slice(&node_count.to_le_bytes());+    out.extend_from_slice(&edge_count.to_le_bytes());+    out.extend_from_slice(&0u64.to_le_bytes());+    out.extend_from_slice(&0u64.to_le_bytes());+    out+}++fn poi_header(magic: &[u8; 4], count: u32, len: usize) -> Vec<u8> {+    let mut out = vec![0u8; len];+    out[0..4].copy_from_slice(magic);+    out[8..12].copy_from_slice(&count.to_le_bytes());+    out+}++/// The smallest payload set `ArchiveView` accepts for every kind the app+/// reads: a one-node graph, one POI record, and a header-only transit+/// pack. Counts are the validators' own arithmetic (see the tilecodec+/// archive tests, whose fixtures these mirror).+fn sidecar_payloads() -> Vec<(u8, Vec<u8>, u64)> {+    let mut transit = vec![0u8; 80 + 20 * 16];+    transit[0..4].copy_from_slice(&TRANSIT_MAGIC.to_le_bytes());+    transit[4..8].copy_from_slice(&7u32.to_le_bytes());+    transit[8..12].copy_from_slice(&20u32.to_le_bytes());+    vec![+        (sidecar::ARCHIVE_KIND_GRAPH_META, graph_meta(1, 0), 0),+        (sidecar::ARCHIVE_KIND_GRAPH_NODES, vec![0u8; 24], 1),+        (sidecar::ARCHIVE_KIND_GRAPH_EDGES, vec![0u8; 16], 0),+        (sidecar::ARCHIVE_KIND_GRAPH_INTERMEDIATE, vec![0u8; 26], 0),+        (sidecar::ARCHIVE_KIND_GRAPH_NAMES, b"\0Grid Street\0".to_vec(), 0),+        (sidecar::ARCHIVE_KIND_GRAPH_LANES, vec![0u8; 12], 0),+        (sidecar::ARCHIVE_KIND_GRAPH_ELEVATION, vec![0u8; 2], 0),+        (sidecar::ARCHIVE_KIND_POI_INDEX, vec![0u8; 14], 0),+        (sidecar::ARCHIVE_KIND_POI_NAMES, b"\0Cafe\0".to_vec(), 0),+        (sidecar::ARCHIVE_KIND_POI_ATTRS, poi_header(b"MAPA", 1, 12), 0),+        (sidecar::ARCHIVE_KIND_POI_SPATIAL, poi_header(b"PSP1", 1, 32), 0),+        (sidecar::ARCHIVE_KIND_POI_WORDS, poi_header(b"PNI1", 1, 16), 0),+        (sidecar::ARCHIVE_KIND_TRANSIT, transit, 0),+        (sidecar::ARCHIVE_KIND_GRAPH_OVERLAY, b"MOVL".to_vec(), 0),+        (sidecar::ARCHIVE_KIND_POI_REGION, poi_header(b"PRG1", 1, 20), 0),+    ]+}++/// Append the sidecar payloads to the tiles-only archive at `path`+/// (header `file_len` patched to cover the whole file).+pub fn append_sidecar(path: &Path) {+    let mut out = std::fs::read(path).expect("read tiles archive");+    let mut header = Header::parse(&out).expect("tile header parses");+    assert_eq!(header.build_id, BUILD_ID);+    while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 {+        out.push(0);+    }+    let mut entries = Vec::new();+    for (kind, bytes, extra) in sidecar_payloads() {+        while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 {+            out.push(0);+        }+        let offset = out.len() as u64;+        out.extend_from_slice(&bytes);+        entries.push(ArchiveEntry { kind, flags: 0, offset, len: bytes.len() as u64, extra });+    }+    while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 {+        out.push(0);+    }+    let dir_offset = out.len() as u64;+    let (dir, footer) = sidecar::serialize_dir(&entries, BUILD_ID, dir_offset);+    out.extend_from_slice(&dir);+    out.extend_from_slice(&footer.serialize());+    header.file_len = out.len() as u64;+    let head = header.serialize();+    out[..head.len()].copy_from_slice(&head);+    std::fs::write(path, &out).expect("write full archive");+}