Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / maps / tile_build / src / bin / mamaps_dump.rs

mamaps_dump.rs469 lines · 20.3 KiBRaw
1//! `mamaps_dump` — print a canonical, line-oriented summary of a `.mamaps` archive.
2//!
3//! Usage:
4//! mamaps_dump IN.mamaps [--mode summary|tiles|header|dict] [--layer NAME]
5//!
6//! Print a canonical, line-oriented summary of a `.mamaps` archive: a binary
7//! container is only reviewable if there is a text rendering of it, and a golden
8//! file only diffs if that rendering is deterministic. Everything here is
9//! `BTreeMap`/`BTreeSet` ordered, so there is no sort step and no way for output
10//! order to depend on a hash seed.
11//!
12//! Modes:
13//! summary one line per (zoom, layer): tile/feature counts, geometry-type counts and the
14//! sorted union of `kind`s. The default.
15//! tiles one line per (z/x/y, layer). Verbose, for chasing a single tile.
16//! rings one line per (z/x/y, layer, feature, part): winding, point count and signed area.
17//! The finest grain there is, and only sensible with `--tile`.
18//! geometry one line per (z/x/y, layer) carrying the MEASURES of the shapes rather than their
19//! counts: ring count, total absolute ring area, net signed area and total line length.
20//! What `test/diff_mamaps.py` compares, and the check that says two archives hold the
21//! same picture when they do not hold the same bytes.
22//! header the header fields, one per line. Also what checks a published file is sane.
23//! dict the interned tables, one id per line.
24//!
25//! Unlike the on-device reader this reads the whole file into memory. A `.mamaps` archive is opened by
26//! range request on device, but a dump is a host tool run against a file that is already local, and
27//! the format's whole point is that it is smaller than the MVT it replaces.
28
29use std::collections::{BTreeMap, BTreeSet};
30use std::process::ExitCode;
31
32use tile_build::mamaps::body::{Body, GEOM_LINE, GEOM_POINT, GEOM_POLYGON};
33use tile_build::mamaps::{dict, read};
34use tile_build::pmtiles::tile_zxy;
35
36fn main() -> ExitCode {
37 let args: Vec<String> = std::env::args().collect();
38 let mut input = None;
39 let mut mode = "summary".to_string();
40 let mut only_layer: Option<String> = None;
41 let mut only_tile: Option<(u8, u64, u64)> = None;
42
43 let mut i = 1;
44 while i < args.len() {
45 let take = |i: usize| args.get(i + 1).cloned();
46 match args[i].as_str() {
47 "--mode" => {
48 match take(i) {
49 Some(m) => mode = m,
50 None => {
51 eprintln!("mamaps_dump: --mode needs a value");
52 return ExitCode::from(2);
53 }
54 }
55 i += 2;
56 }
57 "--layer" => {
58 only_layer = take(i);
59 i += 2;
60 }
61 "--tile" => {
62 match take(i).as_deref().and_then(parse_tile) {
63 Some(t) => only_tile = Some(t),
64 None => {
65 eprintln!("mamaps_dump: --tile needs a z/x/y, e.g. 13/1308/2994");
66 return ExitCode::from(2);
67 }
68 }
69 i += 2;
70 }
71 "-h" | "--help" => {
72 usage();
73 return ExitCode::SUCCESS;
74 }
75 other if other.starts_with('-') => {
76 eprintln!("mamaps_dump: unexpected argument '{other}'");
77 usage();
78 return ExitCode::from(2);
79 }
80 other => {
81 if input.is_some() {
82 eprintln!("mamaps_dump: more than one input archive given");
83 return ExitCode::from(2);
84 }
85 input = Some(other.to_string());
86 i += 1;
87 }
88 }
89 }
90
91 let Some(input) = input else {
92 usage();
93 return ExitCode::from(2);
94 };
95 // Mapped, not read: `--mode header` is the planet build's publish gate and touches only the
96 // ~9 KB prefix, but `std::fs::read` pulled the whole archive into memory first -- 81 GB and
97 // 34 s on the Nov 10 planet, and an 81 GB anonymous allocation on a box whose memory budget
98 // is the build's tightest constraint. Every mode sees the same bytes either way; the other
99 // modes simply page in what they walk.
100 let file = match std::fs::File::open(&input) {
101 Ok(f) => f,
102 Err(e) => {
103 eprintln!("mamaps_dump: cannot read {input}: {e}");
104 return ExitCode::from(1);
105 }
106 };
107 let empty = file.metadata().map(|m| m.len() == 0).unwrap_or(false);
108 // SAFETY: a read-only mapping of a finished archive. Nothing in this process writes the
109 // file; another process truncating it mid-dump could fault the read, which for a
110 // diagnostic dump of a published file is the same failure a short read would be.
111 let map = if empty {
112 None
113 } else {
114 match unsafe { memmap2::Mmap::map(&file) } {
115 Ok(m) => Some(m),
116 Err(e) => {
117 eprintln!("mamaps_dump: cannot read {input}: {e}");
118 return ExitCode::from(1);
119 }
120 }
121 };
122 let bytes: &[u8] = map.as_deref().unwrap_or(&[]);
123 match run(bytes, &mode, only_layer.as_deref(), only_tile) {
124 Ok(code) => code,
125 Err(e) => {
126 eprintln!("mamaps_dump: {input}: {e}");
127 ExitCode::from(1)
128 }
129 }
130}
131
132/// `z/x/y` as three integers, or `None` if it is not that.
133fn parse_tile(s: &str) -> Option<(u8, u64, u64)> {
134 let mut parts = s.split('/');
135 let z = parts.next()?.parse().ok()?;
136 let x = parts.next()?.parse().ok()?;
137 let y = parts.next()?.parse().ok()?;
138 parts.next().is_none().then_some((z, x, y))
139}
140
141fn run(
142 bytes: &[u8],
143 mode: &str,
144 only_layer: Option<&str>,
145 only_tile: Option<(u8, u64, u64)>,
146) -> tile_build::proto::Result<ExitCode> {
147 let (header, dictionary, _root) = read::open_prefix(bytes)?;
148 if mode == "header" {
149 // The byte the archive actually carries, not the constant this binary was built with.
150 // `open_prefix` refuses anything but the current version, so the two agree by the time we
151 // get here — but printing the constant would report "3" for a v3 reader no matter what
152 // was on disk, which makes the line useless as a check on a freshly built archive.
153 println!("format_version\t{}", bytes[7]);
154 println!("build_id\t{:#018x}", header.build_id);
155 println!("flags\t{:#06x}", header.flags);
156 println!("bodies_compressed\t{}", header.compressed());
157 println!("rings_validated\t{}", header.rings_validated());
158 println!("compression\t{}", header.compression);
159 println!("layer_count\t{}", header.layer_count);
160 println!("min_zoom\t{}", header.min_zoom);
161 println!("max_zoom\t{}", header.max_zoom);
162 println!("file_len\t{}", header.file_len);
163 println!("dict\t{}+{}", header.dict_offset, header.dict_len);
164 println!("root\t{}+{}", header.root_offset, header.root_len);
165 println!("leaves\t{}+{}\tcount={}", header.leaf_offset, header.leaf_len, header.leaf_count);
166 println!("data\t{}+{}", header.data_offset, header.data_len);
167 println!("leaf_entry_capacity\t{}", header.leaf_entry_capacity);
168 println!("tiles_addressed\t{}", header.tiles_addressed);
169 println!("bodies_written\t{}", header.bodies_written);
170 // The dedup ratio, which is the number worth watching between builds: it is what makes
171 // ocean and empty tiles nearly free.
172 println!(
173 "dedup\t{:.3}",
174 header.bodies_written as f64 / header.tiles_addressed.max(1) as f64,
175 );
176 println!("min_lon_e7\t{}", header.min_lon_e7);
177 println!("min_lat_e7\t{}", header.min_lat_e7);
178 println!("max_lon_e7\t{}", header.max_lon_e7);
179 println!("max_lat_e7\t{}", header.max_lat_e7);
180 println!("prefix_bytes\t{}", 128 + header.dict_len + header.root_len);
181 return Ok(ExitCode::SUCCESS);
182 }
183 if mode == "dict" {
184 for (id, name) in dictionary.layers.iter().enumerate() {
185 println!("layer\t{id}\t{name}");
186 }
187 for (index, name) in dictionary.kinds.iter().enumerate() {
188 println!("kind\t{}\t{name}", index + 1);
189 }
190 for (index, name) in dictionary.details.iter().enumerate() {
191 println!("kind_detail\t{}\t{name}", index + 1);
192 }
193 return Ok(ExitCode::SUCCESS);
194 }
195 if !matches!(mode, "summary" | "tiles" | "geometry" | "rings" | "names" | "ids") {
196 eprintln!("mamaps_dump: unknown mode '{mode}'");
197 return Ok(ExitCode::from(2));
198 }
199
200 let mut agg: BTreeMap<(u8, String), Agg> = BTreeMap::new();
201 let mut undecodable = 0usize;
202 for (tile_id, run_length, body) in read::read_all(bytes)? {
203 let body = match Body::parse(&body) {
204 Ok(b) => b,
205 Err(_) => {
206 undecodable += 1;
207 continue;
208 }
209 };
210 // A run is one body standing in for several tiles, and each of those tiles is really
211 // present — so expanding it is what makes the counts comparable with an archive that
212 // happened not to dedup.
213 for offset in 0..run_length as u64 {
214 let (z, x, y) = tile_zxy(tile_id + offset);
215 if only_tile.is_some_and(|want| want != (z, x, y)) {
216 continue;
217 }
218 for layer in &body.layers {
219 let name = dictionary
220 .layer_name(layer.layer_id)
221 .map(str::to_string)
222 .unwrap_or_else(|| format!("layer{}", layer.layer_id));
223 if only_layer.is_some_and(|want| want != name) {
224 continue;
225 }
226 let mut geoms: BTreeMap<&str, usize> = BTreeMap::new();
227 if mode == "names" {
228 // One line per named feature: the label spot-check. Unnamed features are
229 // silent, so an empty result means "no names here" rather than "no features".
230 for (fi, feature) in layer.features.iter().enumerate() {
231 if let Some(label) = feature.name(&body) {
232 let kind = dictionary.kind_name(feature.kind).unwrap_or("?");
233 println!(
234 "{z}/{x}/{y}\t{name}\tfeature={fi}\tkind={kind}\tlabel={label}"
235 );
236 }
237 }
238 continue;
239 }
240 if mode == "ids" {
241 // One line per feature carrying an archive id. Only `places` and `poi`
242 // have an id table at all, so an empty result on those two means the
243 // build dropped the ids, while an empty result elsewhere is correct.
244 for (fi, feature) in layer.features.iter().enumerate() {
245 let Some(id) = body.feature_id(layer.layer_id, fi) else { break };
246 let kind = dictionary.kind_name(feature.kind).unwrap_or("?");
247 let label = feature.name(&body).unwrap_or("");
248 // The low two bits are the OSM id space; see `extract::tagged_id`.
249 let (space, osm) = match id & 0b11 {
250 0 => ("none", 0),
251 1 => ("node", id >> 2),
252 2 => ("way", id >> 2),
253 _ => ("relation", id >> 2),
254 };
255 println!(
256 "{z}/{x}/{y}\t{name}\tfeature={fi}\tkind={kind}\tid={id}\t{space}/{osm}\tlabel={label}"
257 );
258 }
259 continue;
260 }
261 let mut kinds: BTreeSet<String> = BTreeSet::new();
262 let mut points = 0usize;
263 for feature in &layer.features {
264 *geoms.entry(geom_name(feature.geom_type)).or_default() += 1;
265 kinds.insert(kind_label(&dictionary, feature));
266 points += layer
267 .parts_of(feature)
268 .iter()
269 .map(|p| p.point_count as usize)
270 .sum::<usize>();
271 }
272 if mode == "rings" {
273 for (fi, feature) in layer.features.iter().enumerate() {
274 for (pi, part) in layer.parts_of(feature).iter().enumerate() {
275 let pts = layer.points(part);
276 // Transit colour and lane inputs ride along when set: the
277 // spot-check for coloured lines and for the parallel fan-out
278 // (both empty for every other layer).
279 let color = if feature.transit_color != 0 {
280 format!(
281 "\ttcolor={:06X}\ttordinal={}\ttlanes={}\tttaper={}",
282 feature.transit_color,
283 feature.transit_ordinal,
284 feature.transit_lanes,
285 feature.transit_taper,
286 )
287 } else {
288 String::new()
289 };
290 println!(
291 "{z}/{x}/{y}\t{name}\tfeature={fi}\tpart={pi}\tkind={}\twinding={}\tpoints={}\tsigned={:.2}\tfirst={:?}\tlast={:?}{color}",
292 kind_label(&dictionary, feature),
293 if part.is_hole() { "hole" } else { "outer" },
294 part.point_count,
295 ring_area(pts),
296 pts.first(),
297 pts.last(),
298 );
299 }
300 }
301 continue;
302 }
303 if mode == "geometry" {
304 // Three measures, because they fail differently and the difference
305 // between them is diagnostic:
306 //
307 // rings how many parts. A dropped hole shows up here and nowhere
308 // else -- the geom= column counts FEATURES by type, so a
309 // feature losing a ring looks identical there.
310 // area absolute, summed per ring, so a hole adds rather than
311 // cancels. Sensitive to a ring being lost.
312 // net signed, summed per FEATURE, so holes subtract. This is
313 // the ground actually covered, and it is what a renderer
314 // fills. A self-touching ring's zero-width sliver
315 // contributes nothing to it, which is the point.
316 //
317 // `area` and `net` disagreeing is how a prong of a self-touching
318 // ring changing orientation is told apart from one going missing.
319 let mut rings = 0usize;
320 let mut area = 0.0f64;
321 let mut net = 0.0f64;
322 let mut length = 0.0f64;
323 for feature in &layer.features {
324 for part in layer.parts_of(feature) {
325 let pts = layer.points(part);
326 rings += 1;
327 if feature.geom_type == GEOM_POLYGON {
328 let signed = ring_area(pts);
329 area += signed.abs();
330 net += signed;
331 } else {
332 length += path_length(pts);
333 }
334 }
335 }
336 // Two decimals of an extent unit: far below the quantisation grid the
337 // coordinates are already on, so this cannot manufacture a difference,
338 // and fixed-width so a text diff is meaningful.
339 println!(
340 "{z}/{x}/{y}\t{name}\tfeatures={}\tpoints={points}\trings={rings}\tgeom={}\tarea={area:.2}\tnet={net:.2}\tlength={length:.2}",
341 layer.features.len(),
342 join_counts(&geoms),
343 );
344 continue;
345 }
346 if mode == "tiles" {
347 println!(
348 "{z}/{x}/{y}\t{name}\tfeatures={}\tpoints={points}\textent={}\tgeom={}\tkinds={}",
349 layer.features.len(),
350 body.extent,
351 join_counts(&geoms),
352 kinds.iter().cloned().collect::<Vec<_>>().join(","),
353 );
354 continue;
355 }
356 let entry = agg.entry((z, name)).or_default();
357 entry.tiles += 1;
358 entry.features += layer.features.len();
359 entry.points += points;
360 entry.extents.insert(body.extent);
361 for (geom, count) in geoms {
362 *entry.geoms.entry(geom.to_string()).or_default() += count;
363 }
364 entry.kinds.extend(kinds);
365 }
366 }
367 }
368
369 if mode == "summary" {
370 for ((z, layer), a) in &agg {
371 println!(
372 "z{z}\t{layer}\ttiles={}\tfeatures={}\tpoints={}\textent={}\tgeom={}\tkinds={}",
373 a.tiles,
374 a.features,
375 a.points,
376 a.extents.iter().map(|e| e.to_string()).collect::<Vec<_>>().join("/"),
377 join_counts_owned(&a.geoms),
378 a.kinds.iter().cloned().collect::<Vec<_>>().join(","),
379 );
380 }
381 }
382 // Counted and reported, but not fatal: a dump of a mostly-good archive is more use than no
383 // dump at all, and the count is what says whether to trust the rest.
384 if undecodable > 0 {
385 eprintln!("mamaps_dump: {undecodable} tile(s) could not be decoded");
386 }
387 Ok(ExitCode::SUCCESS)
388}
389
390#[derive(Default)]
391struct Agg {
392 tiles: usize,
393 features: usize,
394 points: usize,
395 extents: BTreeSet<u16>,
396 geoms: BTreeMap<String, usize>,
397 kinds: BTreeSet<String>,
398}
399
400/// How a feature's `kind` prints: its interned name, its numeric detail, or `-` for neither.
401///
402/// `boundaries` carries an admin level rather than a `kind`, so printing the number is the only way
403/// its rows say anything at all.
404fn kind_label(
405 dictionary: &dict::Dictionary,
406 feature: &tile_build::mamaps::body::Feature,
407) -> String {
408 if let Some(level) = feature.detail_number() {
409 return format!("level{level}");
410 }
411 match dictionary.kind_name(feature.kind) {
412 Some(name) => match dictionary.detail_name(feature.kind_detail) {
413 Some(detail) => format!("{name}:{detail}"),
414 None => name.to_string(),
415 },
416 None => "-".to_string(),
417 }
418}
419
420fn geom_name(geom_type: u8) -> &'static str {
421 match geom_type {
422 GEOM_LINE => "line",
423 GEOM_POLYGON => "polygon",
424 GEOM_POINT => "point",
425 _ => "unknown",
426 }
427}
428
429/// Twice-the-signed-area over two, by the shoelace formula, treating the ring as closed.
430///
431/// `i64` throughout before the divide: two `i16` spans multiply to 32 bits and a ring can hold
432/// thousands of them, so accumulating in `f64` would round while `i64` cannot overflow.
433fn ring_area(pts: &[(i16, i16)]) -> f64 {
434 let n = pts.len();
435 if n < 3 {
436 return 0.0;
437 }
438 let mut twice: i64 = 0;
439 for i in 0..n {
440 let (x1, y1) = pts[i];
441 let (x2, y2) = pts[(i + 1) % n];
442 twice += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;
443 }
444 twice as f64 / 2.0
445}
446
447fn path_length(pts: &[(i16, i16)]) -> f64 {
448 pts.windows(2)
449 .map(|w| {
450 let dx = w[1].0 as f64 - w[0].0 as f64;
451 let dy = w[1].1 as f64 - w[0].1 as f64;
452 (dx * dx + dy * dy).sqrt()
453 })
454 .sum()
455}
456
457fn join_counts(m: &BTreeMap<&str, usize>) -> String {
458 m.iter().map(|(k, v)| format!("{k}:{v}")).collect::<Vec<_>>().join(",")
459}
460
461fn join_counts_owned(m: &BTreeMap<String, usize>) -> String {
462 m.iter().map(|(k, v)| format!("{k}:{v}")).collect::<Vec<_>>().join(",")
463}
464
465fn usage() {
466 eprintln!(
467 "usage: mamaps_dump IN.mamaps [--mode summary|tiles|geometry|rings|names|ids|header|dict] [--layer NAME] [--tile Z/X/Y]"
468 );
469}