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

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

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