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

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

dem.rs298 lines · 12.4 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::f64::consts::PI;
20use std::path::Path;
21
22use rayon::prelude::*;
23use tile_build::par;
24use tilecodec::mamaps::body::Heightmap;
25use tilecodec::pmtiles::tile_id;
26use tilecodec::proto::{err, Error, Result};
27
28/// The `.mdem` dataset's magic and version, as `dem_ingest` writes them.
29const MAGIC: &[u8; 4] = b"MDEM";
30const VERSION: u8 = 1;
31
32/// The biased `u16` for zero metres: sea level, and what a sample with no DEM under it reads as.
33/// The same bias [`Heightmap`] and the terrarium source use.
34const SEA_LEVEL: u16 = 32768;
35
36/// Whether every sample in a grid is sea level, i.e. the tile is all ocean / flat coast at 0 m and
37/// carries no relief worth a terrain grid. See [`Dem::heightmap_for`] for why such tiles drop it.
38fn all_sea_level(samples: &[u16]) -> bool {
39 samples.iter().all(|&s| s == SEA_LEVEL)
40}
41
42/// A tile flatter than this (max sample minus min sample, in metres) carries
43/// a coarse grid: at 5x5 the elevation error is bounded by the relief the
44/// grid cannot see, and below a 10-storey building over a tile (~1 km at
45/// z14) the mesh is indistinguishable from full resolution.
46pub const FLAT_RELIEF_M: u16 = 32;
47
48/// The coarse grid side length for flat tiles. 5x5x2+2 = 52 bytes against
49/// 9x9x2+2 = 164 — a 68% saving where it applies, with zero reader changes
50/// (the wire carries a per-tile `dim`, and sampling/tessellation derive
51/// from it).
52pub const FLAT_DIM: u16 = 5;
53
54/// The relief (max minus min sample) of a grid, in sample units (metres).
55fn relief(samples: &[u16]) -> u16 {
56 let (mut lo, mut hi) = (u16::MAX, u16::MIN);
57 for &s in samples {
58 lo = lo.min(s);
59 hi = hi.max(s);
60 }
61 hi - lo
62}
63
64/// Downsample a `dim x dim` grid to `FLAT_DIM x FLAT_DIM` by picking the
65/// evenly-spaced rows/columns (corners included, so the tile edges agree
66/// with a full-resolution neighbour's skirt). Only called when
67/// `dim >= FLAT_DIM` and the grid is flat — the values barely vary, so
68/// nearest-pick and averaging differ by less than the relief itself.
69fn coarsen(samples: &[u16], dim: usize) -> Vec<u16> {
70 let flat = FLAT_DIM as usize;
71 let mut out = Vec::with_capacity(flat * flat);
72 for row in 0..flat {
73 let src_row = row * (dim - 1) / (flat - 1);
74 for col in 0..flat {
75 let src_col = col * (dim - 1) / (flat - 1);
76 out.push(samples[src_row * dim + src_col]);
77 }
78 }
79 out
80}
81
82/// The grid a tile carries, from its full-resolution `dim x dim` samples.
83///
84/// Default: today's relief gate (flat tiles coarsen to `FLAT_DIM`). Under
85/// `--dem-max-error M` (planet-size prototype): the coarsest aligned sub-grid whose bilinear
86/// reconstruction stays within `M/2` of the full grid, then elevations quantised to a
87/// `floor(M)`-metre step (rounding error <= M/2), so the total error is <= M metres by
88/// construction — flat ground collapses to 2x2, mountains keep 9x9. Either way the emitted
89/// grid's error against the full grid is recorded in [`DEM_STATS`].
90fn finish_grid(z: u8, y: u64, samples: &[u16], dim: u16) -> Heightmap {
91 let o = crate::tiler::size_opts();
92 let tol = if o.dem_px > 0.0 {
93 let lat = tile_y_to_lat(y as f64 + 0.5, z);
94 let m_per_px = 156_543.033_92 * lat.to_radians().cos() / (1u64 << z) as f64;
95 (o.dem_px * m_per_px).max(o.dem_max_error_m.max(1.0))
96 } else {
97 o.dem_max_error_m
98 };
99 let full = Heightmap { dim, samples: samples.to_vec() };
100 let out = if tol > 0.0 {
101 adapt_grid(&full, tol)
102 } else if relief(samples) <= FLAT_RELIEF_M && dim >= FLAT_DIM {
103 Heightmap { dim: FLAT_DIM, samples: coarsen(samples, dim as usize) }
104 } else {
105 full.clone()
106 };
107 DEM_STATS.record(z, &full, &out);
108 out
109}
110
111fn bilinear_at(g: &[u16], dg: usize, fr: f64, fc: f64) -> f64 {
112 let gr = fr * (dg - 1) as f64;
113 let gc = fc * (dg - 1) as f64;
114 let r0 = (gr.floor() as usize).min(dg - 1);
115 let c0 = (gc.floor() as usize).min(dg - 1);
116 let r1 = (r0 + 1).min(dg - 1);
117 let c1 = (c0 + 1).min(dg - 1);
118 let (fy, fx) = (gr - r0 as f64, gc - c0 as f64);
119 let at = |r: usize, c: usize| g[r * dg + c] as f64;
120 let top = at(r0, c0) * (1.0 - fx) + at(r0, c1) * fx;
121 let bot = at(r1, c0) * (1.0 - fx) + at(r1, c1) * fx;
122 top * (1.0 - fy) + bot * fy
123}
124
125/// Max abs and sum of squared error of `new` against `full`, at every full-grid node. Both are
126/// bilinear surfaces and the coarse nodes are a subset of the fine ones, so the difference is
127/// bilinear inside every fine cell: the max over the nodes is the max over the whole surface.
128fn grid_error(full: &Heightmap, new: &Heightmap) -> (f64, f64) {
129 let d = full.dim as usize;
130 let dn = new.dim as usize;
131 let (mut mx, mut ss) = (0.0f64, 0.0f64);
132 for r in 0..d {
133 for c in 0..d {
134 let e = (bilinear_at(
135 &new.samples,
136 dn,
137 r as f64 / (d - 1) as f64,
138 c as f64 / (d - 1) as f64,
139 ) - full.samples[r * d + c] as f64)
140 .abs();
141 mx = mx.max(e);
142 ss += e * e;
143 }
144 }
145 (mx, ss)
146}
147
148fn adapt_grid(full: &Heightmap, tol: f64) -> Heightmap {
149 let d = full.dim as usize;
150 let mut pick = full.clone();
151 for dn in (2..=d).filter(|dn| (d - 1) % (dn - 1) == 0) {
152 let mut sub = Vec::with_capacity(dn * dn);
153 for r in 0..dn {
154 for c in 0..dn {
155 sub.push(full.samples[(r * (d - 1) / (dn - 1)) * d + c * (d - 1) / (dn - 1)]);
156 }
157 }
158 let cand = Heightmap { dim: dn as u16, samples: sub };
159 if grid_error(full, &cand).0 <= tol / 2.0 + 1e-9 {
160 pick = cand;
161 break;
162 }
163 }
164 let q = tol.floor().max(1.0) as i32;
165 if q > 1 {
166 for v in &mut pick.samples {
167 let m = *v as i32 - SEA_LEVEL as i32;
168 let r = ((m as f64 / q as f64).round() as i32) * q;
169 *v = (r + SEA_LEVEL as i32).clamp(0, u16::MAX as i32) as u16;
170 }
171 // Quantising can make a coastal grid all-sea-level; keep it (the caller already decided
172 // the tile has relief) — the renderer's land mask handles the shore.
173 }
174 pick
175}
176
177/// Per-zoom DEM error/size accounting, printed at the end of the build.
178pub struct DemStats {
179 max_bits: [std::sync::atomic::AtomicU64; 15],
180 ss_micro: [std::sync::atomic::AtomicU64; 15],
181 nodes: [std::sync::atomic::AtomicU64; 15],
182 grids: [std::sync::atomic::AtomicU64; 15],
183 cells: [std::sync::atomic::AtomicU64; 15],
184}
185
186#[allow(clippy::declare_interior_mutable_const)]
187const ZERO: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
188pub static DEM_STATS: DemStats = DemStats {
189 max_bits: [ZERO; 15],
190 ss_micro: [ZERO; 15],
191 nodes: [ZERO; 15],
192 grids: [ZERO; 15],
193 cells: [ZERO; 15],
194};
195
196impl DemStats {
197 fn record(&self, z: u8, full: &Heightmap, out: &Heightmap) {
198 use std::sync::atomic::Ordering::Relaxed;
199 let z = (z as usize).min(14);
200 let (mx, ss) = grid_error(full, out);
201 // Non-negative f64s order like their bit patterns.
202 self.max_bits[z].fetch_max(mx.to_bits(), Relaxed);
203 self.ss_micro[z].fetch_add((ss * 1e6).round() as u64, Relaxed);
204 self.nodes[z].fetch_add((full.dim as u64).pow(2), Relaxed);
205 self.grids[z].fetch_add(1, Relaxed);
206 self.cells[z].fetch_add((out.dim as u64).pow(2), Relaxed);
207 }
208
209 pub fn report(&self) {
210 use std::sync::atomic::Ordering::Relaxed;
211 println!("DEM grids (error vs the full dim^2-sample dataset grid, metres):");
212 let (mut gmx, mut gss, mut gn) = (0.0f64, 0.0f64, 0u64);
213 for z in 0..15 {
214 let g = self.grids[z].load(Relaxed);
215 if g == 0 {
216 continue;
217 }
218 let mx = f64::from_bits(self.max_bits[z].load(Relaxed));
219 let ss = self.ss_micro[z].load(Relaxed) as f64 / 1e6;
220 let n = self.nodes[z].load(Relaxed);
221 gmx = gmx.max(mx);
222 gss += ss;
223 gn += n;
224 println!(
225 " DEMSTAT z{z:<2} grids {g:>10} avg_cells {:>6.1} max_err {mx:>7.2} rms_err {:>7.3}",
226 self.cells[z].load(Relaxed) as f64 / g as f64,
227 (ss / n.max(1) as f64).sqrt()
228 );
229 }
230 println!(" DEMSTAT all max_err {gmx:.2} rms_err {:.3}", (gss / gn.max(1) as f64).sqrt());
231 }
232}
233
234/// A loaded `.mdem` dataset: one `u16` grid per output tile, keyed by pmtiles tile id at the
235/// dataset's own zoom.
236pub struct Dem {
237 /// The zoom the grids were sampled at — the one a tile can copy verbatim rather than resample.
238 out_zoom: u8,
239 /// The grid side length, so every grid is `dim * dim` samples. Shared by every tile.
240 dim: u16,
241 /// `tile_id(out_zoom, x, y)` -> the tile's `dim * dim` samples, row-major from its top-left.
242 grids: Grids,
243}
244
245/// The dataset's grids as one sorted id column and one contiguous sample column.
246///
247/// Was a `HashMap<u64, Vec<u16>>`: on the 13 GB world dataset that is ~76 M allocations and a
248/// single-threaded fold of ~76 M inserts on every build regardless of region (the bulk of a
249/// 12-24 s `dem-load` at ~5 cores), plus the map's own slack. Here both columns are built on the
250/// pool and a lookup is a binary search. Same answers as the map for every id, including a file
251/// that repeats one: the map kept the **last** insert, and so does [`Grids::build`].
252struct Grids {
253 /// Tile ids, strictly ascending.
254 ids: Vec<u64>,
255 /// `ids.len() * cells` samples; tile `i`'s grid is `samples[i * cells..][..cells]`.
256 samples: Vec<u16>,
257 cells: usize,
258}
259
260impl Grids {
261 /// From `(id, file index)` for every record and a way to fill a grid from a record index.
262 /// Ids are sorted (already ascending in a `dem_ingest` file, which is checked rather than
263 /// assumed) and a repeated id keeps its last record, as `HashMap::insert` in file order did.
264 fn build<F>(mut keys: Vec<(u64, usize)>, cells: usize, fill: F) -> Grids
265 where
266 F: Fn(usize, &mut [u16]) + Sync,
267 {
268 let ascending = keys.par_windows(2).all(|w| w[0].0 < w[1].0);
269 if !ascending {
270 // (id, index) is a total order with unique keys, so the sort is deterministic; the
271 // last of each id's run is its last record in the file.
272 keys.par_sort_unstable();
273 let mut kept: Vec<(u64, usize)> = Vec::with_capacity(keys.len());
274 for k in keys {
275 match kept.last_mut() {
276 Some(last) if last.0 == k.0 => *last = k,
277 _ => kept.push(k),
278 }
279 }
280 keys = kept;
281 }
282 let mut samples = vec![0u16; keys.len() * cells];
283 if cells > 0 {
284 samples
285 .par_chunks_mut(cells)
286 .zip(keys.par_iter())
287 .for_each(|(grid, &(_, index))| fill(index, grid));
288 }
289 Grids { ids: keys.into_iter().map(|(id, _)| id).collect(), samples, cells }
290 }
291
292 fn get(&self, id: &u64) -> Option<&[u16]> {
293 let i = self.ids.binary_search(id).ok()?;
294 Some(&self.samples[i * self.cells..(i + 1) * self.cells])
295 }
296}
297
298include!("dem_s1.rs");