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

Modern-Apps.git / scripts / maps / dem_ingest / src / main.rs

main.rs299 lines · 11.3 KiBRaw
1//! Decode COP90 (Copernicus 90 m DSM) GeoTIFF tiles into a per-map-tile `u16`
2//! heightmap grid dataset — the build half of WS-G's 3D terrain relief.
3//!
4//! Given the COP90 tile directory (`inputs/cop90/COP90_hh/` of
5//! `Copernicus_DSM_30_*_DEM.tif` Float32 tiles plus the `COP90_hh.vrt` mosaic)
6//! and a bounding box, it produces one small square `u16` grid per output map
7//! tile. Samples are metres above sea level **biased by 32768** — the same
8//! convention [`tilecodec::mamaps::body::Heightmap`] stores on the wire.
9//!
10//! Each 1°×1° tile file is found by flooring the sample lon/lat to its
11//! south-west corner and sampled nearest-neighbour through its own GeoTIFF tags
12//! (pixel scale + tiepoint). Missing files, nodata cells and NaNs read as sea
13//! level. Network I/O lives in the build scripts; this crate's only raster
14//! dependency is the pure-Rust `tiff` crate — no native GDAL.
15//!
16//! Output is a single `.mdem` dataset (see `dataset.rs`): a header, then per
17//! non-empty tile a pmtiles tile id and its `dim * dim` samples, row-major.
18//! Ocean/flat tiles are omitted by default (`--skip-flat` on;
19//! `--no-skip-flat` keeps them), matching the wire format's rule that an
20//! elevation-free tile carries no section.
21//!
22//! COP90 source tiles are independent, so sampling runs across a rayon pool:
23//! the ascending output-id range is split into contiguous chunks (neighbours
24//! share DEM tiles, so each chunk's own cache stays warm), sampled in parallel,
25//! then the kept grids are merged back in ascending id order and streamed out —
26//! byte-identical to a serial walk.
27
28use std::path::{Path, PathBuf};
29
30use rayon::prelude::*;
31use tilecodec::pmtiles::{tile_zxy, zoom_base};
32
33mod geotags;
34
35mod dataset;
36use dataset::{finish_dataset, open_dataset, write_tile};
37
38mod progress;
39use progress::fmt_hms;
40
41mod sample;
42use sample::{sample_tile, DemCache};
43
44mod tilemath;
45use tilemath::{lat_to_tile_y, lon_to_tile_x};
46
47/// Default DEM input, relative to the repo's `scripts/maps/` working dir.
48const DEFAULT_INPUT: &str = "inputs/cop90/COP90_hh.vrt";
49
50fn main() {
51 if let Err(e) = run() {
52 eprintln!("dem_ingest: {e}");
53 std::process::exit(1);
54 }
55}
56
57struct Args {
58 dem_dir: PathBuf,
59 out: PathBuf,
60 out_zoom: u8,
61 dim: u16,
62 bbox: (f64, f64, f64, f64),
63 skip_flat: bool,
64}
65
66fn run() -> Result<(), String> {
67 let args = parse_args()?;
68 if args.dim < 2 {
69 return Err("--dim must be at least 2".to_string());
70 }
71 let dem_dir = resolve_dem_dir(&args.dem_dir)?;
72 let n = 1u64 << args.out_zoom;
73 // The output tile range the bbox covers, clamped to the world.
74 let (min_lon, min_lat, max_lon, max_lat) = args.bbox;
75 let x0 = lon_to_tile_x(min_lon, args.out_zoom).floor().max(0.0) as u64;
76 let x1 = lon_to_tile_x(max_lon, args.out_zoom).ceil().min(n as f64) as u64;
77 // Latitude runs the other way: max_lat is the smaller tile y.
78 let y0 = lat_to_tile_y(max_lat, args.out_zoom).floor().max(0.0) as u64;
79 let y1 = lat_to_tile_y(min_lat, args.out_zoom).ceil().min(n as f64) as u64;
80 if x1 <= x0 || y1 <= y0 {
81 return Err(format!(
82 "the bbox {min_lon},{min_lat},{max_lon},{max_lat} covers no z{} tiles",
83 args.out_zoom
84 ));
85 }
86
87 // Output tile ids the bbox covers, in ascending id order (Hilbert ids aren't
88 // row-major, so the id range is walked and mapped back to x/y). This is the
89 // exact order the .mdem body must end up in.
90 let (base, end) = (zoom_base(args.out_zoom), zoom_base(args.out_zoom + 1));
91 let mut ids = Vec::new();
92 for id in base..end {
93 let (_, x, y) = tile_zxy(id);
94 if x < x0 || x >= x1 || y < y0 || y >= y1 {
95 continue;
96 }
97 ids.push(id);
98 }
99 let total = ids.len() as u64;
100
101 // Sample in parallel. Each contiguous chunk gets its own DemCache and returns
102 // the tiles it kept plus how many had no DEM coverage; chunks come back in id
103 // order, so the flattened result is already ascending.
104 let dim = args.dim as usize;
105 let skip_flat = args.skip_flat;
106 let threads = rayon::current_num_threads().max(1);
107 let chunk_size = (ids.len() / (threads * 4)).max(1);
108 let done = std::sync::atomic::AtomicU64::new(0);
109 let start = std::time::Instant::now();
110
111 let chunks: Vec<(Vec<(u64, Vec<u16>)>, u64)> = ids
112 .par_chunks(chunk_size)
113 .map(|chunk| -> Result<(Vec<(u64, Vec<u16>)>, u64), String> {
114 let mut cache = DemCache::new();
115 let mut kept: Vec<(u64, Vec<u16>)> = Vec::new();
116 let mut missing = 0u64;
117 for &id in chunk {
118 let (_, x, y) = tile_zxy(id);
119 match sample_tile(&dem_dir, x, y, args.out_zoom, dim, &mut cache)? {
120 Some(grid) if !(skip_flat && is_flat(&grid)) => kept.push((id, grid)),
121 Some(_) => {}
122 None => missing += 1,
123 }
124 let d = done.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
125 if d % 10000 == 0 || d == total {
126 tick(d, total, start);
127 }
128 }
129 Ok((kept, missing))
130 })
131 .collect::<Result<Vec<_>, String>>()?;
132 eprintln!();
133
134 // Merge in chunk (ascending id) order; the sort keeps the body byte-identical
135 // to the serial walk regardless of how chunks were scheduled.
136 let mut tiles: Vec<(u64, Vec<u16>)> = Vec::new();
137 let mut missing = 0u64;
138 for (kept, chunk_missing) in chunks {
139 tiles.extend(kept);
140 missing += chunk_missing;
141 }
142 tiles.sort_by_key(|(id, _)| *id);
143
144 // Stream to disk: header with a zero count, one record per tile, then the
145 // real count patched into the header (see dataset.rs).
146 let mut out = open_dataset(&args.out, args.out_zoom, args.dim)?;
147 let mut written = 0u32;
148 for (id, grid) in &tiles {
149 write_tile(&mut out, *id, grid)?;
150 written += 1;
151 }
152 finish_dataset(out, written)?;
153 println!(
154 "dem_ingest: wrote {} tile(s) at z{} ({}x{}) to {} ({} output tile(s) had no DEM coverage)",
155 written,
156 args.out_zoom,
157 args.dim,
158 args.dim,
159 args.out.display(),
160 missing,
161 );
162 Ok(())
163}
164
165/// Redraw the stderr progress line for `done`/`total` tiles.
166fn tick(done: u64, total: u64, start: std::time::Instant) {
167 let el = start.elapsed().as_secs_f64();
168 let rate = done as f64 / el.max(1e-6);
169 eprint!(
170 "\rdem_ingest: {done}/{total} ({:.1}%) elapsed {} eta {} {:.1} tiles/s",
171 done as f64 / total as f64 * 100.0,
172 fmt_hms(el),
173 fmt_hms((total - done) as f64 / rate.max(1e-6)),
174 rate
175 );
176 let _ = std::io::Write::flush(&mut std::io::stderr());
177}
178
179/// A grid is "flat" when every sample is within ±2 m of one level; omitted as relief-free.
180fn is_flat(grid: &[u16]) -> bool {
181 let (mut lo, mut hi) = (u16::MAX, u16::MIN);
182 for &s in grid {
183 lo = lo.min(s);
184 hi = hi.max(s);
185 }
186 hi.saturating_sub(lo) <= 2
187}
188
189/// Accept either the tile directory or the `.vrt` mosaic path: a `.vrt` file
190/// resolves to the `COP90_hh` sibling its sources live in.
191fn resolve_dem_dir(input: &Path) -> Result<PathBuf, String> {
192 if input.is_dir() {
193 return Ok(input.to_path_buf());
194 }
195 if input.is_file() {
196 if let Some(parent) = input.parent() {
197 let sibling = parent.join("COP90_hh");
198 if sibling.is_dir() {
199 return Ok(sibling);
200 }
201 return Ok(parent.to_path_buf());
202 }
203 }
204 Err(format!(
205 "no COP90 tiles at {} (want the COP90_hh directory or the COP90_hh.vrt mosaic)",
206 input.display()
207 ))
208}
209
210// --- CLI ---
211
212fn parse_args() -> Result<Args, String> {
213 let mut tiles_dir: Option<PathBuf> = None;
214 let mut out: Option<PathBuf> = None;
215 let mut out_zoom = 12u8;
216 let mut dim = 9u16;
217 let mut bbox: Option<(f64, f64, f64, f64)> = None;
218 let mut skip_flat = true;
219 let mut it = std::env::args().skip(1);
220 while let Some(a) = it.next() {
221 match a.as_str() {
222 // The COP90 tile directory, or the COP90_hh.vrt mosaic (the default);
223 // kept under the old flag name so existing invocations still parse.
224 "--tiles-dir" => tiles_dir = Some(PathBuf::from(next(&mut it, "--tiles-dir")?)),
225 "--out" => out = Some(PathBuf::from(next(&mut it, "--out")?)),
226 "--out-zoom" => out_zoom = next(&mut it, "--out-zoom")?.parse().map_err(|_| "--out-zoom must be a number")?,
227 // Accepted for compatibility; COP90 samples at its native ~90 m everywhere.
228 "--dem-zoom" => {
229 next(&mut it, "--dem-zoom")?;
230 }
231 "--dim" => dim = next(&mut it, "--dim")?.parse().map_err(|_| "--dim must be a number")?,
232 "--bbox" => bbox = Some(parse_bbox(&next(&mut it, "--bbox")?)?),
233 "--skip-flat" => skip_flat = true,
234 "--no-skip-flat" => skip_flat = false,
235 "-h" | "--help" => {
236 print_help();
237 std::process::exit(0);
238 }
239 other => return Err(format!("unknown argument {other} (try --help)")),
240 }
241 }
242 Ok(Args {
243 dem_dir: tiles_dir.unwrap_or_else(|| PathBuf::from(DEFAULT_INPUT)),
244 out: out.ok_or("--out is required")?,
245 out_zoom,
246 dim,
247 bbox: bbox.ok_or("--bbox is required")?,
248 skip_flat,
249 })
250}
251
252fn next(it: &mut impl Iterator<Item = String>, flag: &str) -> Result<String, String> {
253 it.next().ok_or_else(|| format!("{flag} needs a value"))
254}
255
256fn parse_bbox(s: &str) -> Result<(f64, f64, f64, f64), String> {
257 let parts: Vec<f64> = s
258 .split(',')
259 .map(|p| p.trim().parse::<f64>().map_err(|_| format!("bad bbox component `{p}`")))
260 .collect::<Result<_, _>>()?;
261 match parts.as_slice() {
262 [min_lon, min_lat, max_lon, max_lat] => Ok((*min_lon, *min_lat, *max_lon, *max_lat)),
263 _ => Err("--bbox is minlon,minlat,maxlon,maxlat".to_string()),
264 }
265}
266
267fn print_help() {
268 println!(
269 "dem_ingest --bbox minlon,minlat,maxlon,maxlat --out FILE [--tiles-dir DIR]\n\
270 \n\
271 Decode COP90 GeoTIFF tiles (COP90_hh/Copernicus_DSM_30_*_DEM.tif, Float32) into a\n\
272 per-map-tile u16 heightmap grid dataset (metres + 32768 bias).\n\
273 \n\
274 Options:\n\
275 \x20 --tiles-dir DIR COP90_hh tile directory or the COP90_hh.vrt mosaic\n\
276 \x20 (default {DEFAULT_INPUT})\n\
277 \x20 --bbox BOX minlon,minlat,maxlon,maxlat to cover (required)\n\
278 \x20 --out FILE the .mdem dataset to write (required)\n\
279 \x20 --out-zoom Z map tile zoom to sample a grid per (default 12)\n\
280 \x20 --dem-zoom Z accepted for compatibility; COP90 is ~90 m everywhere\n\
281 \x20 --dim N grid side length, N*N samples per tile (default 9)\n\
282 \x20 --skip-flat omit tiles with no relief (ocean/flat), matching the wire format\n\
283 \x20 (default on)\n\
284 \x20 --no-skip-flat keep flat tiles too: a world run without it needs tens of GB\n"
285 );
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292 #[test]
293 fn is_flat_omits_a_level_grid_but_keeps_relief() {
294 assert!(is_flat(&vec![32768; 289]), "an all-sea-level grid is flat");
295 let mut relief = vec![32768u16; 289];
296 relief[100] = 32768 + 50;
297 assert!(!is_flat(&relief), "50 m of relief is not flat");
298 }
299}