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

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

sample.rs219 lines · 8.1 KiBRaw
1//! COP90 sampling: a bounded LRU of decoded 1° GeoTIFF tiles and the
2//! nearest-neighbour resample that turns an output map tile's grid points into
3//! biased `u16` heights. Decoding a tile is deterministic, so the cache only
4//! affects speed — two threads with their own caches produce identical grids.
5
6use std::collections::{HashMap, VecDeque};
7use std::path::Path;
8
9use crate::geotags::read_geotags;
10use crate::tilemath::{tile_x_to_lon, tile_y_to_lat};
11
12/// Sea level in the biased `u16` grid: `round(0 m) + 32768`.
13pub const SEA_LEVEL: u16 = 32768;
14
15/// Cap on decoded 1° COP90 tiles held at once (~6 MB each): 96 entries stay
16/// well under a gigabyte while the id-order walk keeps neighbours close.
17const DEM_CACHE_CAP: usize = 96;
18
19/// One decoded COP90 tile: Float32 heights plus its geo transform from its own tags.
20pub struct CopTile {
21 width: u32,
22 height: u32,
23 /// Longitude of the pixel (0,0) centre's west edge; latitude of its north edge.
24 west: f64,
25 north: f64,
26 pixel_w: f64,
27 pixel_h: f64,
28 nodata: Option<f64>,
29 data: Vec<f32>,
30}
31
32impl CopTile {
33 /// Nearest-neighbour sample as a biased `u16`; out-of-range, nodata and NaN
34 /// cells read as sea level.
35 pub fn sample(&self, lon: f64, lat: f64) -> u16 {
36 let col = ((lon - self.west) / self.pixel_w).floor() as i64;
37 let row = ((self.north - lat) / self.pixel_h).floor() as i64;
38 if col < 0 || row < 0 || col >= self.width as i64 || row >= self.height as i64 {
39 return SEA_LEVEL;
40 }
41 let v = self.data[row as usize * self.width as usize + col as usize] as f64;
42 if !v.is_finite() || self.nodata == Some(v) {
43 return SEA_LEVEL;
44 }
45 elevation_to_stored(v)
46 }
47}
48
49/// Sample one output tile's grid, or `None` when no DEM tile under it exists.
50pub fn sample_tile(
51 dem_dir: &Path,
52 ox: u64,
53 oy: u64,
54 out_zoom: u8,
55 dim: usize,
56 cache: &mut DemCache,
57) -> Result<Option<Vec<u16>>, String> {
58 let mut grid = Vec::with_capacity(dim * dim);
59 let mut any_data = false;
60 for row in 0..dim {
61 // Grid point fractional position within the output tile, top-left origin.
62 let fy = oy as f64 + row as f64 / (dim as f64 - 1.0);
63 let lat = tile_y_to_lat(fy, out_zoom);
64 for col in 0..dim {
65 let fx = ox as f64 + col as f64 / (dim as f64 - 1.0);
66 let lon = tile_x_to_lon(fx, out_zoom);
67 // The 1° COP90 cell this lon/lat lands in, by its south-west corner.
68 let key = (lon.floor() as i32, lat.floor() as i32);
69 let sample = match cache.get_or_decode(dem_dir, key)? {
70 Some(tile) => {
71 any_data = true;
72 tile.sample(lon, lat)
73 }
74 // No DEM here: sea level. A tile entirely over missing DEM is dropped by the caller.
75 None => SEA_LEVEL,
76 };
77 grid.push(sample);
78 }
79 }
80 Ok(any_data.then_some(grid))
81}
82
83/// Bounded LRU of decoded COP90 tiles (`None` = no tile file for that 1° cell).
84pub struct DemCache {
85 map: HashMap<(i32, i32), Option<CopTile>>,
86 order: VecDeque<(i32, i32)>,
87}
88
89impl DemCache {
90 pub fn new() -> Self {
91 Self { map: HashMap::new(), order: VecDeque::new() }
92 }
93
94 pub fn get_or_decode(
95 &mut self,
96 dem_dir: &Path,
97 key: (i32, i32),
98 ) -> Result<&Option<CopTile>, String> {
99 if !self.map.contains_key(&key) {
100 let path = dem_dir.join(tile_filename(key.0, key.1));
101 let decoded = if path.is_file() {
102 Some(
103 decode_cop_tile(&path, key)
104 .map_err(|e| format!("decoding {}: {e}", path.display()))?,
105 )
106 } else {
107 None
108 };
109 self.order.push_back(key);
110 self.map.insert(key, decoded);
111 while self.map.len() > DEM_CACHE_CAP {
112 if let Some(old) = self.order.pop_front() {
113 self.map.remove(&old);
114 } else {
115 break;
116 }
117 }
118 }
119 Ok(self.map.get(&key).expect("just inserted"))
120 }
121}
122
123/// The COP90 file covering the 1° cell with south-west corner (`tlon`, `tlat`):
124/// `Copernicus_DSM_30_N00_00_E006_00_DEM.tif` covers lat 0..1, lon 6..7.
125fn tile_filename(tlon: i32, tlat: i32) -> String {
126 let lat_part = if tlat >= 0 { format!("N{tlat:02}") } else { format!("S{:02}", -tlat) };
127 let lon_part = if tlon >= 0 { format!("E{tlon:03}") } else { format!("W{:03}", -tlon) };
128 format!("Copernicus_DSM_30_{lat_part}_00_{lon_part}_00_DEM.tif")
129}
130
131/// Decode one COP90 tile: Float32 pixels via the `tiff` crate, geo transform
132/// from the file's own ModelPixelScale/ModelTiepoint tags (falling back to the
133/// 1° filename grid when the tags are absent).
134fn decode_cop_tile(path: &Path, key: (i32, i32)) -> Result<CopTile, String> {
135 let file = std::fs::File::open(path).map_err(|e| format!("opening: {e}"))?;
136 let mut decoder = tiff::decoder::Decoder::new(file).map_err(|e| format!("tiff header: {e}"))?;
137 let (width, height) = decoder.dimensions().map_err(|e| format!("tiff dimensions: {e}"))?;
138 if width == 0 || height == 0 {
139 return Err("a COP90 tile has no pixels".to_string());
140 }
141 let data = match decoder.read_image().map_err(|e| format!("tiff pixels: {e}"))? {
142 tiff::decoder::DecodingResult::F32(v) => v,
143 _ => return Err("a COP90 tile is Float32, got another sample type".to_string()),
144 };
145 if data.len() != width as usize * height as usize {
146 return Err(format!(
147 "a COP90 tile has {}x{} pixels but {} samples",
148 width,
149 height,
150 data.len()
151 ));
152 }
153 // Filename grid fallback: the 1° cell the name promises.
154 let geo = read_geotags(path).unwrap_or_default();
155 Ok(CopTile {
156 width,
157 height,
158 west: geo.west.unwrap_or(key.0 as f64),
159 north: geo.north.unwrap_or((key.1 + 1) as f64),
160 pixel_w: geo.pixel_w.unwrap_or(1.0 / width as f64),
161 pixel_h: geo.pixel_h.unwrap_or(1.0 / height as f64),
162 nodata: geo.nodata,
163 data,
164 })
165}
166
167/// Biased `u16` for metres: `round(m) + 32768`; non-finite reads as sea level, clamps.
168fn elevation_to_stored(m: f64) -> u16 {
169 if !m.is_finite() {
170 return SEA_LEVEL;
171 }
172 (m.round() + 32768.0).clamp(0.0, u16::MAX as f64) as u16
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn elevation_bias_puts_sea_level_at_32768() {
181 assert_eq!(elevation_to_stored(0.0), 32768);
182 assert_eq!(elevation_to_stored(1.0), 32769);
183 // Sub-metre precision rounds to the nearest metre.
184 assert_eq!(elevation_to_stored(0.6), 32769);
185 // The Dead Sea shore, ~-430 m, sits below the bias.
186 assert_eq!(elevation_to_stored(-430.0), 32338);
187 // Non-finite and out-of-range input reads as sea level / clamps.
188 assert_eq!(elevation_to_stored(f64::NAN), 32768);
189 assert_eq!(elevation_to_stored(f64::INFINITY), 32768);
190 assert_eq!(elevation_to_stored(-40000.0), 0);
191 }
192
193 #[test]
194 fn tile_filenames_cover_all_hemispheres() {
195 assert_eq!(tile_filename(6, 0), "Copernicus_DSM_30_N00_00_E006_00_DEM.tif");
196 assert_eq!(tile_filename(-70, -38), "Copernicus_DSM_30_S38_00_W070_00_DEM.tif");
197 assert_eq!(tile_filename(138, 73), "Copernicus_DSM_30_N73_00_E138_00_DEM.tif");
198 assert_eq!(tile_filename(-88, -89), "Copernicus_DSM_30_S89_00_W088_00_DEM.tif");
199 }
200
201 #[test]
202 fn cop_tile_samples_nearest_neighbour_and_sea_level() {
203 let tile = CopTile {
204 width: 2,
205 height: 2,
206 west: 6.0,
207 north: 1.0,
208 pixel_w: 0.5,
209 pixel_h: 0.5,
210 nodata: Some(-32768.0),
211 data: vec![100.0, -32768.0, f32::NAN, -50.0],
212 };
213 assert_eq!(tile.sample(6.1, 0.9), 32868);
214 assert_eq!(tile.sample(6.6, 0.9), 32768, "nodata reads as sea level");
215 assert_eq!(tile.sample(6.1, 0.4), 32768, "NaN reads as sea level");
216 assert_eq!(tile.sample(6.6, 0.4), 32718);
217 assert_eq!(tile.sample(99.0, 99.0), 32768, "out of range reads as sea level");
218 }
219}