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

Modern-Apps.git / scripts / maps / mamaps_build / src / dem.rs

dem.rs457 lines · 21.2 KiBRaw
1//! Load the `.mdem` heightmap dataset `dem_ingest` produced and hand the tiler one grid per output
2//! tile — the second half of WS-G's build side, closing the gap the wire format left open.
3//!
4//! `dem_ingest` fetches AWS terrarium PNG tiles and downsamples them into one small square `u16`
5//! grid per map tile at a single zoom (`--out-zoom`, default 14; `--dim`, default 9), each sample
6//! `metres + 32768` row-major from the tile's top-left. That is exactly the layout
7//! [`tilecodec::mamaps::body::Heightmap`] carries on the wire, so a tile at the dataset's own zoom
8//! is a **verbatim copy** of its grid — no resample, byte for byte what the ingest computed,
9//! unless the tile is flat enough to coarsen (see `FLAT_RELIEF_M`).
10//!
11//! A tile at any other zoom is **resampled**: `dim * dim` points are sampled across the tile's own
12//! extent (the same slippy walk `dem_ingest` does over the terrarium grid), each bilinearly
13//! interpolated from the covering dataset grid. A tile with no data under it at all — off the fetch
14//! coverage, or open ocean the ingest dropped with `--skip-flat` — yields `None`, so that tile omits
15//! the section and stays 16-byte, matching the format's rule. A tile whose grid is entirely sea
16//! level yields `None` the same way, whatever the zoom: it carries no relief, and a flat sea-level
17//! grid would make the renderer draw earth-coloured terrain over open water (see [`Dem::heightmap_for`]).
18
19use std::collections::HashMap;
20use std::f64::consts::PI;
21use std::path::Path;
22
23use rayon::prelude::*;
24use tile_build::par;
25use tilecodec::mamaps::body::Heightmap;
26use tilecodec::pmtiles::tile_id;
27use tilecodec::proto::{err, Error, Result};
28
29/// The `.mdem` dataset's magic and version, as `dem_ingest` writes them.
30const MAGIC: &[u8; 4] = b"MDEM";
31const VERSION: u8 = 1;
32
33/// The biased `u16` for zero metres: sea level, and what a sample with no DEM under it reads as.
34/// The same bias [`Heightmap`] and the terrarium source use.
35const SEA_LEVEL: u16 = 32768;
36
37/// Whether every sample in a grid is sea level, i.e. the tile is all ocean / flat coast at 0 m and
38/// carries no relief worth a terrain grid. See [`Dem::heightmap_for`] for why such tiles drop it.
39fn all_sea_level(samples: &[u16]) -> bool {
40 samples.iter().all(|&s| s == SEA_LEVEL)
41}
42
43/// A tile flatter than this (max sample minus min sample, in metres) carries
44/// a coarse grid: at 5x5 the elevation error is bounded by the relief the
45/// grid cannot see, and below a 10-storey building over a tile (~1 km at
46/// z14) the mesh is indistinguishable from full resolution.
47pub const FLAT_RELIEF_M: u16 = 32;
48
49/// The coarse grid side length for flat tiles. 5x5x2+2 = 52 bytes against
50/// 9x9x2+2 = 164 — a 68% saving where it applies, with zero reader changes
51/// (the wire carries a per-tile `dim`, and sampling/tessellation derive
52/// from it).
53pub const FLAT_DIM: u16 = 5;
54
55/// The relief (max minus min sample) of a grid, in sample units (metres).
56fn relief(samples: &[u16]) -> u16 {
57 let (mut lo, mut hi) = (u16::MAX, u16::MIN);
58 for &s in samples {
59 lo = lo.min(s);
60 hi = hi.max(s);
61 }
62 hi - lo
63}
64
65/// Downsample a `dim x dim` grid to `FLAT_DIM x FLAT_DIM` by picking the
66/// evenly-spaced rows/columns (corners included, so the tile edges agree
67/// with a full-resolution neighbour's skirt). Only called when
68/// `dim >= FLAT_DIM` and the grid is flat — the values barely vary, so
69/// nearest-pick and averaging differ by less than the relief itself.
70fn coarsen(samples: &[u16], dim: usize) -> Vec<u16> {
71 let flat = FLAT_DIM as usize;
72 let mut out = Vec::with_capacity(flat * flat);
73 for row in 0..flat {
74 let src_row = row * (dim - 1) / (flat - 1);
75 for col in 0..flat {
76 let src_col = col * (dim - 1) / (flat - 1);
77 out.push(samples[src_row * dim + src_col]);
78 }
79 }
80 out
81}
82
83/// A loaded `.mdem` dataset: one `u16` grid per output tile, keyed by pmtiles tile id at the
84/// dataset's own zoom.
85pub struct Dem {
86 /// The zoom the grids were sampled at — the one a tile can copy verbatim rather than resample.
87 out_zoom: u8,
88 /// The grid side length, so every grid is `dim * dim` samples. Shared by every tile.
89 dim: u16,
90 /// `tile_id(out_zoom, x, y)` -> the tile's `dim * dim` samples, row-major from its top-left.
91 grids: HashMap<u64, Vec<u16>>,
92}
93
94impl Dem {
95 /// Read and parse a `.mdem` dataset from disk.
96 ///
97 /// Mapped, not read: the 13 GB world file would otherwise cost a
98 /// single-threaded `fs::read` plus a full copy before parsing starts.
99 /// The mapping faults pages in on the pool's 64 threads during the
100 /// parallel parse below, and the bytes are never copied — each tile's
101 /// samples land directly in its grid `Vec`. The mapping drops on return;
102 /// the `Dem` owns its grids.
103 pub fn load(path: &Path) -> Result<Dem> {
104 let mapped = osm_ingest::mem::Mapped::open(path).map_err(Error)?;
105 Dem::parse(&mapped)
106 }
107
108 /// Parse a `.mdem` dataset: a 12-byte header (`MDEM`, version, out_zoom, `dim` u16, tile count
109 /// u32), then per tile a `u64` tile id and its `dim * dim` `u16` samples, little-endian.
110 ///
111 /// Tiles parse on the pool: records are fixed-stride (`8 + cells * 2` bytes), so tile `i`
112 /// starts at `12 + i * stride` with no dependency on any other tile. Each worker decodes a
113 /// contiguous run into owned `(id, samples)` pairs; the single-threaded fold inserts them in
114 /// file order. Same pairs as the serial loop — the map holds the same contents, and nothing
115 /// ever iterates it (only `heightmap_for`'s `.get`), so no byte can move. The 13 GB world
116 /// dataset's per-sample `u16::from_le_bytes` + per-tile alloc + hash insert runs ~50 s
117 /// serially on every build regardless of region; fanning out the decode leaves only the
118 /// `fs::read` and the inserts.
119 fn parse(bytes: &[u8]) -> Result<Dem> {
120 if bytes.len() < 12 {
121 return err("a .mdem dataset is shorter than its 12-byte header");
122 }
123 if &bytes[0..4] != MAGIC {
124 return err("not a .mdem dataset (bad magic)");
125 }
126 if bytes[4] != VERSION {
127 return err(format!("unsupported .mdem version {} (this build reads {VERSION})", bytes[4]));
128 }
129 let out_zoom = bytes[5];
130 let dim = u16::from_le_bytes([bytes[6], bytes[7]]);
131 if dim < 2 {
132 return err("a .mdem grid dimension is less than 2");
133 }
134 let count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
135 let cells = dim as usize * dim as usize;
136 // One tile: an 8-byte id then `cells` little-endian u16 samples.
137 let stride = 8 + cells * 2;
138 if bytes.len() < 12 + count.saturating_mul(stride) {
139 return err("a .mdem dataset ends before its tile count");
140 }
141 // Decoded tile indices, not tiles: the byte slices borrow `bytes`, so the
142 // pool maps indices to owned pairs and the fold inserts in file order.
143 // Chunks of 1024 tiles balance scheduling against per-task overhead
144 // (~170 KB of samples per chunk at dim 9 — L2-resident working set).
145 const PARSE_CHUNK_TILES: usize = 1024;
146 let chunks = count.div_ceil(PARSE_CHUNK_TILES);
147 let mut pairs: Vec<Vec<(u64, Vec<u16>)>> = Vec::with_capacity(chunks);
148 par::install(|| {
149 (0..chunks)
150 .into_par_iter()
151 .map(|chunk| {
152 let lo = chunk * PARSE_CHUNK_TILES;
153 let hi = (lo + PARSE_CHUNK_TILES).min(count);
154 let mut out = Vec::with_capacity(hi - lo);
155 for i in lo..hi {
156 let at = 12 + i * stride;
157 let id =
158 u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"));
159 let mut samples = Vec::with_capacity(cells);
160 for c in 0..cells {
161 let o = at + 8 + c * 2;
162 samples.push(u16::from_le_bytes([bytes[o], bytes[o + 1]]));
163 }
164 out.push((id, samples));
165 }
166 out
167 })
168 .collect_into_vec(&mut pairs);
169 });
170 let mut grids = HashMap::with_capacity(count);
171 for chunk in pairs.drain(..) {
172 for (id, samples) in chunk {
173 grids.insert(id, samples);
174 }
175 }
176 Ok(Dem { out_zoom, dim, grids })
177 }
178
179 /// The heightmap for one output tile, or `None` when no DEM covers it (so the tile omits the
180 /// section and stays 16-byte).
181 ///
182 /// A tile at the dataset's own zoom is a verbatim copy of its grid — byte for byte what the
183 /// ingest sampled, independent of neighbour coverage. Any other zoom is resampled onto this
184 /// tile's grid.
185 ///
186 /// A grid that is **entirely sea level** yields `None` whatever the zoom: an all-ocean tile
187 /// carries no relief, and emitting a flat sea-level heightmap makes the renderer draw its
188 /// earth-coloured terrain grid over what should be open water (the renderer's contract is
189 /// "no heightmap over ocean" — see `library/map`'s `terrain.rs`). Dropping it here is the
190 /// backstop for a `.mdem` built without `dem_ingest --skip-flat`. A flat *land* tile at exactly
191 /// sea level loses nothing visible: its flat `earth` fill draws the same ground the flat grid
192 /// would have, and its features sit at 0 m either way.
193 pub fn heightmap_for(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {
194 if z == self.out_zoom {
195 let samples = self.grids.get(&tile_id(z, x, y))?;
196 if all_sea_level(samples) {
197 return None;
198 }
199 // A flat tile's grid is mostly repetition: coarsen it. Steep
200 // tiles keep the full grid.
201 if relief(samples) <= FLAT_RELIEF_M && self.dim >= FLAT_DIM {
202 return Some(Heightmap { dim: FLAT_DIM, samples: coarsen(samples, self.dim as usize) });
203 }
204 return Some(Heightmap { dim: self.dim, samples: samples.clone() });
205 }
206 self.resample(z, x, y)
207 }
208
209 /// Resample the dataset's grids onto one tile's `dim * dim` grid, sampling `dim * dim` points
210 /// across the tile's own extent from its top-left — the same slippy walk `dem_ingest` runs over
211 /// the terrarium grid, sourced from the loaded grids instead of PNGs.
212 fn resample(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {
213 let dim = self.dim as usize;
214 let mut samples = Vec::with_capacity(dim * dim);
215 let mut any = false;
216 for row in 0..dim {
217 let fy = y as f64 + row as f64 / (self.dim as f64 - 1.0);
218 let lat = tile_y_to_lat(fy, z);
219 for col in 0..dim {
220 let fx = x as f64 + col as f64 / (self.dim as f64 - 1.0);
221 let lon = tile_x_to_lon(fx, z);
222 match self.sample_at(lon, lat) {
223 Some(v) => {
224 any = true;
225 samples.push(v);
226 }
227 // No DEM here: sea level, as `dem_ingest` fills a missing terrarium pixel. A
228 // tile entirely over missing DEM is dropped below.
229 None => samples.push(SEA_LEVEL),
230 }
231 }
232 }
233 // A tile whose every sample is sea level carries no relief: drop it so the renderer paints
234 // open water rather than a flat earth-coloured terrain grid (see `heightmap_for`).
235 if !any || all_sea_level(&samples) {
236 return None;
237 }
238 // Same flat-tile coarsening as the verbatim path: the resampled grid
239 // is full resolution, so relief is measured on it directly.
240 if relief(&samples) <= FLAT_RELIEF_M && self.dim >= FLAT_DIM {
241 return Some(Heightmap { dim: FLAT_DIM, samples: coarsen(&samples, dim) });
242 }
243 Some(Heightmap { dim: self.dim, samples })
244 }
245
246 /// Build a dataset directly from grids, for tests that inject a synthetic DEM into the tiler
247 /// rather than round-tripping bytes through disk.
248 #[cfg(test)]
249 pub(crate) fn from_grids(out_zoom: u8, dim: u16, grids: Vec<(u64, Vec<u16>)>) -> Dem {
250 Dem { out_zoom, dim, grids: grids.into_iter().collect() }
251 }
252
253 /// The elevation at one lon/lat, bilinearly interpolated within the dataset grid that covers it,
254 /// or `None` when that grid was not fetched.
255 fn sample_at(&self, lon: f64, lat: f64) -> Option<u16> {
256 let n = (1u64 << self.out_zoom) as f64;
257 // The fractional tile position at the dataset zoom. Clamped so a point exactly on the
258 // world's right/bottom edge lands in the last tile rather than one past it.
259 let tx = lon_to_tile_x(lon, self.out_zoom).clamp(0.0, n - f64::EPSILON);
260 let ty = lat_to_tile_y(lat, self.out_zoom).clamp(0.0, n - f64::EPSILON);
261 let ix = tx.floor() as u64;
262 let iy = ty.floor() as u64;
263 let grid = self.grids.get(&tile_id(self.out_zoom, ix, iy))?;
264 let last = self.dim as usize - 1;
265 // The point's position within the tile's grid: the fraction across the tile scaled onto the
266 // `dim - 1` cells between the grid's edge samples.
267 let gx = (tx - ix as f64) * last as f64;
268 let gy = (ty - iy as f64) * last as f64;
269 let x0 = gx.floor() as usize;
270 let y0 = gy.floor() as usize;
271 let x1 = (x0 + 1).min(last);
272 let y1 = (y0 + 1).min(last);
273 let fx = gx - x0 as f64;
274 let fy = gy - y0 as f64;
275 let d = self.dim as usize;
276 let at = |cx: usize, cy: usize| grid[cy * d + cx] as f64;
277 let top = at(x0, y0) * (1.0 - fx) + at(x1, y0) * fx;
278 let bot = at(x0, y1) * (1.0 - fx) + at(x1, y1) * fx;
279 let v = top * (1.0 - fy) + bot * fy;
280 Some(v.round().clamp(0.0, u16::MAX as f64) as u16)
281 }
282}
283
284// --- slippy / web-mercator tile math, matching `dem_ingest` so a resample lands where the ingest
285// would have sampled ---
286
287fn lon_to_tile_x(lon: f64, z: u8) -> f64 {
288 (lon + 180.0) / 360.0 * (1u64 << z) as f64
289}
290
291fn lat_to_tile_y(lat: f64, z: u8) -> f64 {
292 let r = lat.clamp(-85.05112878, 85.05112878).to_radians();
293 (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64
294}
295
296fn tile_x_to_lon(x: f64, z: u8) -> f64 {
297 x / (1u64 << z) as f64 * 360.0 - 180.0
298}
299
300fn tile_y_to_lat(y: f64, z: u8) -> f64 {
301 let n = PI * (1.0 - 2.0 * y / (1u64 << z) as f64);
302 n.sinh().atan().to_degrees()
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 /// Serialise a synthetic `.mdem` dataset the way `dem_ingest` does, for the parser to read back.
310 fn dataset(out_zoom: u8, dim: u16, tiles: &[(u64, Vec<u16>)]) -> Vec<u8> {
311 let mut out = Vec::new();
312 out.extend_from_slice(MAGIC);
313 out.push(VERSION);
314 out.push(out_zoom);
315 out.extend_from_slice(&dim.to_le_bytes());
316 out.extend_from_slice(&(tiles.len() as u32).to_le_bytes());
317 for (id, grid) in tiles {
318 out.extend_from_slice(&id.to_le_bytes());
319 for &s in grid {
320 out.extend_from_slice(&s.to_le_bytes());
321 }
322 }
323 out
324 }
325
326 /// A ramp grid whose sample at `(col, row)` is `32768 + row * 10 + col`, so a read-back can name
327 /// which cell it got.
328 fn ramp(dim: u16) -> Vec<u16> {
329 let d = dim as usize;
330 let mut g = Vec::with_capacity(d * d);
331 for row in 0..d {
332 for col in 0..d {
333 g.push(SEA_LEVEL + (row * 10 + col) as u16);
334 }
335 }
336 g
337 }
338
339 #[test]
340 fn a_tile_at_the_datasets_zoom_is_a_verbatim_copy() {
341 let (z, dim) = (14u8, 17u16);
342 let (x, y) = (2730u64, 6335u64);
343 let grid = ramp(dim);
344 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), grid.clone())])).expect("parse");
345 let hm = dem.heightmap_for(z, x, y).expect("a heightmap for the covered tile");
346 assert_eq!(hm.dim, dim);
347 assert_eq!(hm.samples, grid, "the grid is copied byte for byte at the dataset's own zoom");
348 // And it reads back through the wire type's own accessor.
349 assert_eq!(hm.sample(0, 0), Some(SEA_LEVEL));
350 assert_eq!(hm.sample(3, 2), Some(SEA_LEVEL + 23));
351 assert_eq!(Heightmap::metres(hm.sample(3, 2).unwrap()), 23);
352 assert_eq!(hm.sample(dim, 0), None, "out of range");
353 }
354
355 #[test]
356 fn a_tile_off_coverage_has_no_heightmap() {
357 let (z, dim) = (14u8, 17u16);
358 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, 10, 10), ramp(dim))])).expect("parse");
359 assert!(dem.heightmap_for(z, 999, 999).is_none(), "an uncovered tile omits the section");
360 }
361
362 #[test]
363 fn an_all_sea_level_tile_has_no_heightmap() {
364 let (z, dim) = (14u8, 17u16);
365 let (x, y) = (2730u64, 6335u64);
366 let sea = vec![SEA_LEVEL; dim as usize * dim as usize];
367 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), sea)])).expect("parse");
368 assert!(
369 dem.heightmap_for(z, x, y).is_none(),
370 "an all-ocean tile drops its heightmap so the renderer paints open water",
371 );
372 }
373
374 #[test]
375 fn a_resampled_all_sea_level_tile_has_no_heightmap() {
376 let (oz, dim) = (14u8, 17u16);
377 // Cover the whole z13 block so every resample point hits coverage, yet all at sea level.
378 let sea: Vec<u16> = vec![SEA_LEVEL; dim as usize * dim as usize];
379 let mut tiles = Vec::new();
380 for cx in 2730..=2732u64 {
381 for cy in 6334..=6336u64 {
382 tiles.push((tile_id(oz, cx, cy), sea.clone()));
383 }
384 }
385 let dem = Dem::parse(&dataset(oz, dim, &tiles)).expect("parse");
386 assert!(
387 dem.heightmap_for(13, 1365, 3167).is_none(),
388 "a resampled all-sea-level tile drops its heightmap too",
389 );
390 }
391
392 /// A coarser tile resamples from the covering grids. Sampled over a tile whose whole extent is
393 /// covered, a flat field must come back flat and non-empty.
394 #[test]
395 fn a_coarser_tile_resamples_within_range() {
396 let (oz, dim) = (14u8, 17u16);
397 // A z13 tile's dim*dim points span its three edge columns/rows of z14 tiles: x in
398 // 2730..=2732 and y in 6334..=6336 for z13 (1365, 3167). Cover that whole 3x3 block so no
399 // sample point falls off coverage (which would read as sea level).
400 let flat: Vec<u16> = vec![SEA_LEVEL + 100; dim as usize * dim as usize];
401 let mut tiles = Vec::new();
402 for cx in 2730..=2732u64 {
403 for cy in 6334..=6336u64 {
404 tiles.push((tile_id(oz, cx, cy), flat.clone()));
405 }
406 }
407 let dem = Dem::parse(&dataset(oz, dim, &tiles)).expect("parse");
408 let hm = dem.heightmap_for(13, 1365, 3167).expect("a resampled heightmap");
409 // A perfectly flat field coarsens: 5x5 of 100 m everywhere.
410 assert_eq!(hm.dim, FLAT_DIM, "a flat resampled tile coarsens");
411 assert_eq!(hm.samples.len(), FLAT_DIM as usize * FLAT_DIM as usize);
412 assert!(
413 hm.samples.iter().all(|&s| s == SEA_LEVEL + 100),
414 "resampling a flat 100 m field is still 100 m everywhere",
415 );
416 }
417
418 #[test]
419 fn a_short_dataset_is_refused() {
420 assert!(Dem::parse(b"MDE").is_err(), "shorter than the header");
421 assert!(Dem::parse(b"XXXX\x01\x0e\x11\x00\x00\x00\x00\x00").is_err(), "bad magic");
422 // A header claiming one tile with no tile bytes behind it.
423 let mut short = dataset(14, 17, &[]);
424 short[8] = 1; // claim one tile
425 assert!(Dem::parse(&short).is_err(), "a claimed tile past the end is refused");
426 }
427
428 /// A flat tile (relief under `FLAT_RELIEF_M`) coarsens to `FLAT_DIM`:
429 /// corners survive so tile edges agree with full-resolution neighbours.
430 #[test]
431 fn a_flat_tile_coarsens_and_a_steep_tile_does_not() {
432 let (z, dim) = (14u8, 9u16);
433 let (x, y) = (2730u64, 6335u64);
434 // Relief 8 m: flat farmland. Corners pinned to distinct values so the
435 // test can tell nearest-pick from averaging.
436 let mut flat = vec![SEA_LEVEL + 100; dim as usize * dim as usize];
437 flat[0] = SEA_LEVEL + 96;
438 flat[8] = SEA_LEVEL + 104;
439 flat[72] = SEA_LEVEL + 97;
440 flat[80] = SEA_LEVEL + 103;
441 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), flat)])).expect("parse");
442 let hm = dem.heightmap_for(z, x, y).expect("a heightmap");
443 assert_eq!(hm.dim, FLAT_DIM, "a flat tile coarsens");
444 assert_eq!(hm.samples.len(), FLAT_DIM as usize * FLAT_DIM as usize);
445 assert_eq!(hm.samples[0], SEA_LEVEL + 96, "top-left corner survives");
446 assert_eq!(hm.samples[4], SEA_LEVEL + 104, "top-right corner survives");
447 assert_eq!(hm.samples[20], SEA_LEVEL + 97, "bottom-left corner survives");
448 assert_eq!(hm.samples[24], SEA_LEVEL + 103, "bottom-right corner survives");
449 // A steep tile (relief over the threshold) keeps the full grid.
450 let steep = ramp(dim);
451 assert!(relief(&steep) > FLAT_RELIEF_M, "the ramp is steep: {}", relief(&steep));
452 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), steep.clone())])).expect("parse");
453 let hm = dem.heightmap_for(z, x, y).expect("a heightmap");
454 assert_eq!(hm.dim, dim, "a steep tile keeps full resolution");
455 assert_eq!(hm.samples, steep);
456 }
457}