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