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

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

dem.rs254 lines · 10.5 KiBRaw
1//! Sample the `.mdem` heightmap dataset (`dem_ingest`) at graph-node coordinates so
2//! `write_graph` can bake a per-node elevation into `elevation.bin` — the build side of
3//! WS-G's route elevation profile.
4//!
5//! `dem_ingest` fetches AWS terrarium PNG tiles and downsamples them into one small square `u16`
6//! grid per map tile at a single zoom (`--out-zoom`, default 14; `--dim`, default 17), each sample
7//! `metres + 32768` row-major from the tile's top-left. That is exactly the layout
8//! `mamaps_build`'s `dem.rs` and the wire `Heightmap` carry; this is a *self-contained* reader —
9//! `osm_ingest` is deliberately detached from the Android workspace (see `Cargo.toml`), so it
10//! parses the format and reproduces the PMTiles Hilbert tile id itself rather than depending on
11//! `tilecodec`.
12//!
13//! [`Dem::sample_metres`] bilinearly interpolates a single lon/lat within the dataset grid that
14//! covers it, returning **metres** (already un-biased), or `None` when no fetched grid covers the
15//! point — a node off the DEM coverage (open ocean, or outside the build bbox) bakes as 0.
16
17use std::collections::HashMap;
18use std::f64::consts::PI;
19use std::path::Path;
20
21use crate::proto::{err, Result};
22
23/// The `.mdem` dataset's magic and version, as `dem_ingest` writes them.
24const MAGIC: &[u8; 4] = b"MDEM";
25const VERSION: u8 = 1;
26
27/// The biased `u16` for zero metres: sea level, and the bias every terrarium sample carries.
28const SEA_LEVEL: i32 = 32768;
29
30/// A loaded `.mdem` dataset: one `u16` grid per output tile, keyed by PMTiles tile id at the
31/// dataset's own zoom.
32pub struct Dem {
33 /// The zoom the grids were sampled at.
34 out_zoom: u8,
35 /// The grid side length, so every grid is `dim * dim` samples. Shared by every tile.
36 dim: u16,
37 /// `tile_id(out_zoom, x, y)` -> the tile's `dim * dim` samples, row-major from its top-left.
38 grids: HashMap<u64, Vec<u16>>,
39}
40
41impl Dem {
42 /// Read and parse a `.mdem` dataset from disk.
43 pub fn load(path: &Path) -> Result<Dem> {
44 let bytes = std::fs::read(path)
45 .map_err(|e| crate::proto::Error(format!("reading the DEM dataset {}: {e}", path.display())))?;
46 Dem::parse(&bytes)
47 }
48
49 /// Parse a `.mdem` dataset: a 12-byte header (`MDEM`, version, out_zoom, `dim` u16, tile count
50 /// u32), then per tile a `u64` tile id and its `dim * dim` `u16` samples, little-endian.
51 fn parse(bytes: &[u8]) -> Result<Dem> {
52 if bytes.len() < 12 {
53 return err("a .mdem dataset is shorter than its 12-byte header");
54 }
55 if &bytes[0..4] != MAGIC {
56 return err("not a .mdem dataset (bad magic)");
57 }
58 if bytes[4] != VERSION {
59 return err(format!("unsupported .mdem version {} (this build reads {VERSION})", bytes[4]));
60 }
61 let out_zoom = bytes[5];
62 let dim = u16::from_le_bytes([bytes[6], bytes[7]]);
63 if dim < 2 {
64 return err("a .mdem grid dimension is less than 2");
65 }
66 let count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
67 let cells = dim as usize * dim as usize;
68 // One tile: an 8-byte id then `cells` little-endian u16 samples.
69 let stride = 8 + cells * 2;
70 let mut at = 12usize;
71 let mut grids = HashMap::with_capacity(count);
72 for _ in 0..count {
73 if at + stride > bytes.len() {
74 return err("a .mdem tile runs past the end of the dataset");
75 }
76 let id = u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"));
77 at += 8;
78 let mut samples = Vec::with_capacity(cells);
79 for i in 0..cells {
80 let o = at + i * 2;
81 samples.push(u16::from_le_bytes([bytes[o], bytes[o + 1]]));
82 }
83 at += cells * 2;
84 grids.insert(id, samples);
85 }
86 Ok(Dem { out_zoom, dim, grids })
87 }
88
89 /// Elevation in **metres** at one lon/lat, bilinearly interpolated within the dataset grid that
90 /// covers it, or `None` when that grid was not fetched (the node bakes as 0 metres).
91 pub fn sample_metres(&self, lon: f64, lat: f64) -> Option<i16> {
92 let biased = self.sample_biased(lon, lat)?;
93 Some((i32::from(biased) - SEA_LEVEL).clamp(i16::MIN as i32, i16::MAX as i32) as i16)
94 }
95
96 /// The raw biased `u16` sample (metres + 32768), or `None` off coverage. Mirrors the sampler in
97 /// `mamaps_build`'s `dem.rs` so a bake lands where the ingest would have sampled.
98 fn sample_biased(&self, lon: f64, lat: f64) -> Option<u16> {
99 let n = (1u64 << self.out_zoom) as f64;
100 // The fractional tile position at the dataset zoom. Clamped so a point exactly on the
101 // world's right/bottom edge lands in the last tile rather than one past it.
102 let tx = lon_to_tile_x(lon, self.out_zoom).clamp(0.0, n - f64::EPSILON);
103 let ty = lat_to_tile_y(lat, self.out_zoom).clamp(0.0, n - f64::EPSILON);
104 let ix = tx.floor() as u64;
105 let iy = ty.floor() as u64;
106 let grid = self.grids.get(&tile_id(self.out_zoom, ix, iy))?;
107 let last = self.dim as usize - 1;
108 // The point's position within the tile's grid: the fraction across the tile scaled onto the
109 // `dim - 1` cells between the grid's edge samples.
110 let gx = (tx - ix as f64) * last as f64;
111 let gy = (ty - iy as f64) * last as f64;
112 let x0 = gx.floor() as usize;
113 let y0 = gy.floor() as usize;
114 let x1 = (x0 + 1).min(last);
115 let y1 = (y0 + 1).min(last);
116 let fx = gx - x0 as f64;
117 let fy = gy - y0 as f64;
118 let d = self.dim as usize;
119 let at = |cx: usize, cy: usize| grid[cy * d + cx] as f64;
120 let top = at(x0, y0) * (1.0 - fx) + at(x1, y0) * fx;
121 let bot = at(x0, y1) * (1.0 - fx) + at(x1, y1) * fx;
122 let v = top * (1.0 - fy) + bot * fy;
123 Some(v.round().clamp(0.0, u16::MAX as f64) as u16)
124 }
125}
126
127// --- PMTiles Hilbert tile ids (a self-contained copy of `tilecodec::pmtiles::tile_id`, so a
128// dataset written with that function reads back here without a `tilecodec` dependency) ---
129
130/// Number of tiles in every zoom below `z`, i.e. the first tile id at `z`. `(4^z - 1) / 3`.
131fn zoom_base(z: u8) -> u64 {
132 ((1u64 << (2 * z as u32)) - 1) / 3
133}
134
135/// Rotate/flip a quadrant. The canonical Hilbert helper.
136fn rot(n: u64, x: &mut u64, y: &mut u64, rx: u64, ry: u64) {
137 if ry == 0 {
138 if rx == 1 {
139 *x = n.wrapping_sub(1).wrapping_sub(*x);
140 *y = n.wrapping_sub(1).wrapping_sub(*y);
141 }
142 std::mem::swap(x, y);
143 }
144}
145
146/// `(z, x, y)` -> PMTiles tile id.
147fn tile_id(z: u8, x: u64, y: u64) -> u64 {
148 let n = 1u64 << z;
149 let (mut x, mut y) = (x, y);
150 let mut d = 0u64;
151 let mut s = n / 2;
152 while s > 0 {
153 let rx = u64::from(x & s > 0);
154 let ry = u64::from(y & s > 0);
155 d += s * s * ((3 * rx) ^ ry);
156 rot(n, &mut x, &mut y, rx, ry);
157 s /= 2;
158 }
159 zoom_base(z) + d
160}
161
162// --- slippy / web-mercator tile math, matching `dem_ingest` / `mamaps_build`'s `dem.rs` ---
163
164fn lon_to_tile_x(lon: f64, z: u8) -> f64 {
165 (lon + 180.0) / 360.0 * (1u64 << z) as f64
166}
167
168fn lat_to_tile_y(lat: f64, z: u8) -> f64 {
169 let r = lat.clamp(-85.05112878, 85.05112878).to_radians();
170 (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 /// Serialise a synthetic `.mdem` dataset the way `dem_ingest` does, for the parser to read back.
178 fn dataset(out_zoom: u8, dim: u16, tiles: &[(u64, Vec<u16>)]) -> Vec<u8> {
179 let mut out = Vec::new();
180 out.extend_from_slice(MAGIC);
181 out.push(VERSION);
182 out.push(out_zoom);
183 out.extend_from_slice(&dim.to_le_bytes());
184 out.extend_from_slice(&(tiles.len() as u32).to_le_bytes());
185 for (id, grid) in tiles {
186 out.extend_from_slice(&id.to_le_bytes());
187 for &s in grid {
188 out.extend_from_slice(&s.to_le_bytes());
189 }
190 }
191 out
192 }
193
194 /// A ramp grid whose sample at `(col, row)` is `32768 + row * 10 + col`.
195 fn ramp(dim: u16) -> Vec<u16> {
196 let d = dim as usize;
197 let mut g = Vec::with_capacity(d * d);
198 for row in 0..d {
199 for col in 0..d {
200 g.push(SEA_LEVEL as u16 + (row * 10 + col) as u16);
201 }
202 }
203 g
204 }
205
206 /// The lon/lat at the top-left corner of a dataset tile, so a sample there hits grid cell (0,0).
207 fn tile_top_left(z: u8, x: u64, y: u64) -> (f64, f64) {
208 let n = (1u64 << z) as f64;
209 let lon = x as f64 / n * 360.0 - 180.0;
210 let ang = PI * (1.0 - 2.0 * y as f64 / n);
211 let lat = ang.sinh().atan().to_degrees();
212 (lon, lat)
213 }
214
215 #[test]
216 fn samples_read_back_as_unbiased_metres_over_synthetic_terrain() {
217 let (z, dim) = (14u8, 17u16);
218 let (x, y) = (2730u64, 6335u64);
219 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), ramp(dim))])).expect("parse");
220 // The tile's top-left corner is grid cell (0, 0) == SEA_LEVEL, i.e. 0 metres.
221 let (lon, lat) = tile_top_left(z, x, y);
222 assert_eq!(dem.sample_metres(lon, lat), Some(0), "corner is sea level = 0 m");
223 }
224
225 #[test]
226 fn a_point_off_coverage_has_no_sample() {
227 let (z, dim) = (14u8, 17u16);
228 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, 2730, 6335), ramp(dim))])).expect("parse");
229 // Antarctica, nowhere near the one fetched California tile.
230 assert!(dem.sample_metres(0.0, -80.0).is_none(), "a point off coverage bakes as 0");
231 }
232
233 #[test]
234 fn interior_terrain_interpolates_to_a_positive_elevation() {
235 let (z, dim) = (14u8, 17u16);
236 let (x, y) = (2730u64, 6335u64);
237 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), ramp(dim))])).expect("parse");
238 // A point a third of the way into the tile is inside the ramp, so strictly above sea level.
239 let n = (1u64 << z) as f64;
240 let lon = (x as f64 + 0.5) / n * 360.0 - 180.0;
241 let ang = PI * (1.0 - 2.0 * (y as f64 + 0.5) / n);
242 let lat = ang.sinh().atan().to_degrees();
243 assert!(dem.sample_metres(lon, lat).unwrap() > 0, "interior of the ramp is above 0 m");
244 }
245
246 #[test]
247 fn a_short_dataset_is_refused() {
248 assert!(Dem::parse(b"MDE").is_err(), "shorter than the header");
249 assert!(Dem::parse(b"XXXX\x01\x0e\x11\x00\x00\x00\x00\x00").is_err(), "bad magic");
250 let mut short = dataset(14, 17, &[]);
251 short[8] = 1; // claim one tile with no bytes behind it
252 assert!(Dem::parse(&short).is_err(), "a claimed tile past the end is refused");
253 }
254}