//! `mamaps_probe` — read a handful of tiles out of a `.mamaps` archive by range. //! //! `mamaps_dump` reads the whole file into RAM, which dies on a 60 GB archive. //! This opens the archive over a file-backed [`RangeReader`] and prints one line //! per requested tile: which `landtype` kinds it carries and how much ground //! each covers. Built for the Santa Cruz water/land question — the ocean below //! Santa Cruz rendered as land past ~z7 with only rivers showing as water. //! //! Usage: //! mamaps_probe IN.mamaps Z/X/Y [Z/X/Y ...] //! mamaps_probe IN.mamaps --breakdown [SAMPLES_PER_ZOOM] //! //! `--breakdown` walks the whole leaf index (cheap: index only, no bodies) and //! prints per-zoom: addressed tiles, stored bodies, stored (DEFLATE) bytes, plus //! — from up to SAMPLES_PER_ZOOM sampled bodies per zoom (default 200) — the //! share of bodies carrying a heightmap, the mean raw body size, and the mean //! raw heightmap section size. That answers "how much space does height take". use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::process::ExitCode; use tile_build::mamaps::body::{Body, GEOM_POLYGON}; use tile_build::mamaps::dict::Dictionary; use tile_build::mamaps::read::MamapsArchive; use tile_build::proto::{err, Result}; use tilecodec::stream::RangeReader; struct FileRanges { file: std::sync::Mutex, } impl RangeReader for FileRanges { fn read(&self, offset: u64, length: u32) -> Result> { let mut file = self.file.lock().map_err(|_| tile_build::proto::Error("lock".into()))?; file.seek(SeekFrom::Start(offset)) .map_err(|e| tile_build::proto::Error(format!("seek {offset}: {e}")))?; let mut buf = vec![0u8; length as usize]; let mut got = 0usize; while got < buf.len() { match file.read(&mut buf[got..]) { Ok(0) => break, Ok(n) => got += n, Err(e) => return err(format!("read at {offset}: {e}")), } } buf.truncate(got); Ok(buf) } } fn kind_name(dict: &Dictionary, kind: u16) -> &str { if kind == 0 { return "(land-base)"; } dict.kind_name(kind).unwrap_or("?") } fn main() -> ExitCode { let args: Vec = std::env::args().collect(); if args.len() < 3 { eprintln!("usage: mamaps_probe IN.mamaps Z/X/Y [Z/X/Y ...]"); eprintln!(" or: mamaps_probe IN.mamaps --breakdown [SAMPLES_PER_ZOOM]"); return ExitCode::from(2); } let file = match File::open(&args[1]) { Ok(f) => f, Err(e) => { eprintln!("mamaps_probe: cannot open {}: {e}", args[1]); return ExitCode::from(1); } }; if args[2] == "--breakdown" { let samples: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(200); return breakdown(&args[1], samples); } if args[2] == "--layers" { let samples: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(200); return layer_breakdown(&args[1], samples); } if args[2] == "--sidecars" { return sidecars(&args[1]); } let archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(file) }) { Ok(a) => a, Err(e) => { eprintln!("mamaps_probe: open: {e}"); return ExitCode::from(1); } }; println!( "archive z{}-{} build_id {:#018x} validated={}", archive.header.min_zoom, archive.header.max_zoom, archive.header.build_id, archive.header.rings_validated(), ); let mut code = ExitCode::SUCCESS; for spec in &args[2..] { let mut parts = spec.split('/'); let tile = match (parts.next(), parts.next(), parts.next(), parts.next()) { (Some(z), Some(x), Some(y), None) => { match (z.parse::(), x.parse::(), y.parse::()) { (Ok(z), Ok(x), Ok(y)) => (z, x, y), _ => { eprintln!("mamaps_probe: bad tile '{spec}', want Z/X/Y"); code = ExitCode::from(2); continue; } } } _ => { eprintln!("mamaps_probe: bad tile '{spec}', want Z/X/Y"); code = ExitCode::from(2); continue; } }; let (z, x, y) = tile; match archive.tile(z, x, y) { Err(e) => { println!("{z}/{x}/{y}\tERROR {e}"); code = ExitCode::from(1); } Ok(None) => println!("{z}/{x}/{y}\tABSENT"), Ok(Some(body)) => print_tile(&archive.dictionary, z, x, y, &body), } } code } fn print_tile(dict: &Dictionary, z: u8, x: u32, y: u32, body: &Body) { let extent = body.extent.max(1) as f64; let full = extent * extent; let Some(layer) = body.layer(tile_build::mamaps::dict::LAYER_LANDTYPE) else { println!("{z}/{x}/{y}\tno landtype layer"); return; }; // Per-kind ground: sum of absolute ring areas, so holes add rather than cancel. let mut kinds: std::collections::BTreeMap = std::collections::BTreeMap::new(); let mut feats = 0usize; for feature in &layer.features { if feature.geom_type != GEOM_POLYGON { continue; } feats += 1; let mut area = 0.0f64; for part in layer.parts_of(feature) { area += ring_area(layer.points(part)).abs(); } let e = kinds.entry(feature.kind).or_insert((0, 0.0)); e.0 += 1; e.1 += area; } if kinds.is_empty() { println!("{z}/{x}/{y}\tlandtype: no polygons ({feats} polygon features)"); return; } let mut bits: Vec = Vec::new(); for (kind, (count, area)) in &kinds { bits.push(format!("{}x{}={:.1}%", kind_name(dict, *kind), count, 100.0 * area / full)); } let dem = if body.heightmap.is_some() { " dem" } else { "" }; println!("{z}/{x}/{y}\tlandtype: {}{}", bits.join(" "), dem); } fn ring_area(pts: &[(i16, i16)]) -> f64 { let n = pts.len(); if n < 3 { return 0.0; } let mut twice: i64 = 0; for i in 0..n { let (x1, y1) = pts[i]; let (x2, y2) = pts[(i + 1) % n]; twice += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64; } twice as f64 / 2.0 } /// Walk the whole archive and report per-zoom storage: addressed tiles (with /// run-length expansion), stored bodies, stored (DEFLATE) bytes, plus sampled /// body stats — the heightmap share and the raw (pre-DEFLATE) body/heightmap /// sizes that say how much of each zoom is elevation. /// /// The index walk reads only the root (already in the open prefix) plus one /// read per leaf — kilobytes against a 60 GB file. Bodies are fetched only for /// the sample: evenly spaced entries per zoom, so one sample per ~N bodies, /// each a single range read plus inflate. fn breakdown(path: &str, samples_per_zoom: usize) -> ExitCode { use tile_build::mamaps::{header, index}; use tilecodec::pmtiles::tile_zxy; let file = match File::open(path) { Ok(f) => f, Err(e) => { eprintln!("mamaps_probe: cannot open {path}: {e}"); return ExitCode::from(1); } }; let ranges = FileRanges { file: std::sync::Mutex::new(file) }; // Header + dictionary + root straight out of the open prefix. let prefix = match ranges.read(0, tilecodec::stream::OPEN_PREFIX_BYTES) { Ok(p) => p, Err(e) => { eprintln!("mamaps_probe: open: {e}"); return ExitCode::from(1); } }; let hdr = match header::Header::parse(&prefix) { Ok(h) => h, Err(e) => { eprintln!("mamaps_probe: header: {e}"); return ExitCode::from(1); } }; let root = match index::parse_root( &prefix[hdr.root_offset as usize..(hdr.root_offset + hdr.root_len as u64) as usize], ) { Ok(r) => r, Err(e) => { eprintln!("mamaps_probe: root: {e}"); return ExitCode::from(1); } }; let file_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0); println!( "archive z{}-{} build_id {:#018x} validated={} compression={} file={:.2}GB data={:.2}GB bodies_written={} tiles_addressed={}", hdr.min_zoom, hdr.max_zoom, hdr.build_id, hdr.rings_validated(), hdr.compression, file_len as f64 / 1e9, hdr.data_len as f64 / 1e9, hdr.bodies_written, hdr.tiles_addressed, ); // Per-zoom aggregates from the index alone. struct Zoom { addressed: u64, bodies: u64, stored: u64, entries: Vec<(u64, u32)>, } let mut zooms: std::collections::BTreeMap = std::collections::BTreeMap::new(); for root_entry in &root { let raw_len = root_entry.leaf_entry_count as u64 * index::LEAF_ENTRY_LEN as u64; let stored_len = if root_entry.stored_len == 0 { raw_len } else { root_entry.stored_len as u64 }; let stored = match ranges .read((hdr.leaf_offset + root_entry.leaf_offset) as u64, stored_len as u32) { Ok(r) => r, Err(e) => { eprintln!("mamaps_probe: leaf: {e}"); return ExitCode::from(1); } }; let raw = if root_entry.stored_len == 0 { stored } else { match index::decompress_leaf(&stored, raw_len as usize) { Ok(r) => r, Err(e) => { eprintln!("mamaps_probe: leaf inflate: {e}"); return ExitCode::from(1); } } }; let leaf = match index::parse_leaf(&raw) { Ok(l) => l, Err(e) => { eprintln!("mamaps_probe: leaf parse: {e}"); return ExitCode::from(1); } }; for e in &leaf { let (z, _, _) = tile_zxy(root_entry.base_tile_id + e.tile_id_lo as u64); let at = hdr.data_offset + root_entry.base_data_offset + e.offset_delta as u64; let zoom = zooms.entry(z).or_insert(Zoom { addressed: 0, bodies: 0, stored: 0, entries: Vec::new(), }); zoom.addressed += e.run_length as u64; zoom.bodies += 1; zoom.stored += e.length as u64; zoom.entries.push((at, e.length)); } } println!("zoom addressed bodies stored_GB avg_stored"); let mut total_stored = 0u64; for (z, zoom) in &zooms { total_stored += zoom.stored; println!( "z{z:<3} {:>9} {:>8} {:>10.3} {:>8}", zoom.addressed, zoom.bodies, zoom.stored as f64 / 1e9, fmt_bytes(zoom.stored / zoom.bodies.max(1)), ); } println!("total stored bodies: {:.3} GB", total_stored as f64 / 1e9); // Sampled bodies per zoom: heightmap share + raw sizes. let archive = match MamapsArchive::open(FileRanges { file: std::sync::Mutex::new(File::open(path).expect("open")), }) { Ok(a) => a, Err(e) => { eprintln!("mamaps_probe: reopen: {e}"); return ExitCode::from(1); } }; println!("zoom sampled with_dem dem_share avg_raw_body avg_raw_dem dem_of_raw stored_dem dem_of_stored"); for (z, zoom) in &zooms { if zoom.entries.is_empty() { continue; } let step = (zoom.entries.len() / samples_per_zoom.max(1)).max(1); let mut sampled = 0u64; let mut with_dem = 0u64; let mut raw_body = 0u64; let mut raw_dem = 0u64; let mut stored_dem = 0u64; let mut idx = 0usize; while idx < zoom.entries.len() { let (at, len) = zoom.entries[idx]; let stored = match archive.reader().read(at, len) { Ok(s) => s, Err(_) => { idx += step; continue; } }; let raw = match tile_build::mamaps::read::decompress(hdr.compression, &stored) { Ok(r) => r, Err(_) => { idx += step; continue; } }; let body = match Body::parse(&raw) { Ok(b) => b, Err(_) => { idx += step; continue; } }; sampled += 1; raw_body += raw.len() as u64; if let Some(hm) = &body.heightmap { with_dem += 1; raw_dem += (2 + hm.samples.len() * 2) as u64; stored_dem += len as u64; } idx += step; } if sampled == 0 { continue; } // Stored-bytes split: mean stored size of dem vs no-dem bodies, scaled to // the zoom's body count. DEFLATE-compressibility differs between the two // populations, so this is measured, not modelled. let dem_bodies = zoom.bodies as f64 * with_dem as f64 / sampled as f64; let avg_stored_dem = stored_dem.checked_div(with_dem).unwrap_or(0); let stored_dem_total = dem_bodies * avg_stored_dem as f64; println!( "z{z:<3} {:>7} {:>8} {:>8.1}% {:>11} {:>10} {:>8.1}% {:>10} {:>6.1}%", sampled, with_dem, 100.0 * with_dem as f64 / sampled as f64, fmt_bytes(raw_body / sampled), raw_dem .checked_div(with_dem) .map_or_else(|| "-".to_string(), |v| fmt_bytes(v).to_string()), 100.0 * raw_dem as f64 / raw_body.max(1) as f64, fmt_bytes(stored_dem_total as u64), 100.0 * stored_dem_total / zoom.stored.max(1) as f64, ); } ExitCode::SUCCESS } include!("mamaps_probe_parts/mamaps_probe_part1.rs");