geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! A set of `GeoTIFFs` rendered as one elevation surface, read window by
//! window so memory follows the output tile instead of the input size.
//!
//! Each tile reads, from every source it overlaps, only the pixels under
//! it, at the coarsest overview that still has at least the tile's
//! resolution. Sources may use different CRSs (one UTM zone each, for
//! example); where they overlap, the first source in the given order wins,
//! so a later source only fills pixels an earlier one leaves as nodata.
//!
//! A planet DEM is ~26,000 files, more than a process may keep open, so a
//! source's reader is opened when a tile needs it and parked in a bounded
//! pool: the descriptors a build holds follow the pool, not the source count.

use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};

use geolith::error::{GeolithError, Result};

use crate::terrain::cog::Cog;
use crate::terrain::crs::Crs;
use crate::terrain::dem::{Dem, GeoTransform};
use crate::terrain::source::{Bounds, ElevationSource};

/// Metres per degree of latitude on the WGS84 sphere approximation.
const METRES_PER_DEGREE: f64 = 111_320.0;

/// Points sampled along each tile edge when projecting it into a source
/// CRS; edges curve in a transverse Mercator grid.
const EDGE_SAMPLES: usize = 8;

/// Idle readers kept across tiles. A planet DEM is ~26,000 files and holding
/// one reader per source exceeds the 10,240-file hard limit of macOS, so the
/// pool bounds what a build keeps open: sources are opened on demand and the
/// oldest reader is closed once the pool is full.
const MAX_OPEN_READERS: usize = 32;

/// Extra source pixels read around a window so bilinear sampling at the
/// tile edge has all four neighbours.
const WINDOW_PAD: i64 = 2;

/// One input raster of a mosaic: where it is and what it covers, with no
/// reader held (see [`ReaderPool`]).
#[derive(Debug)]
struct MosaicSource {
    path: PathBuf,
    crs: Crs,
    bounds: Bounds,
    /// `(width, height, transform)` per level, full resolution first.
    levels: Vec<(u32, u32, GeoTransform)>,
    range: Option<(f32, f32)>,
}

/// Open readers, keyed by source path, shared by every tile in flight.
///
/// A window takes its source's reader (opening the file when the pool holds
/// none) and puts it back, so the descriptors a build holds follow this pool
/// and not the number of sources.
#[derive(Debug, Default)]
struct ReaderPool {
    open: Vec<(PathBuf, Cog)>,
}

impl ReaderPool {
    /// The reader for `path`: a parked one, or a new open of the file.
    fn take(&mut self, path: &Path, crs: Crs) -> Result<Cog> {
        let parked = self.open.iter().position(|(open, _)| open == path);
        match parked {
            Some(index) => Ok(self.open.swap_remove(index).1),
            None => Cog::open(path, Some(crs)),
        }
    }

    /// Park `reader` for `path`, closing the oldest first when full.
    fn put(&mut self, path: PathBuf, reader: Cog) {
        if self.open.len() >= MAX_OPEN_READERS {
            self.open.remove(0);
        }
        self.open.push((path, reader));
    }
}

/// `GeoTIFFs` rendered as one elevation surface.
#[derive(Debug)]
pub struct CogMosaic {
    sources: Vec<MosaicSource>,
    epsg: u32,
    readers: Mutex<ReaderPool>,
}

impl CogMosaic {
    /// Open every path as one mosaic, in the given order.
    ///
    /// `crs_override` applies to every source. Each source is read once, for
    /// its bounds, levels and elevation range, and closed; tiles open readers
    /// from a bounded pool, so a planet of 26,000 files fits in a process.
    ///
    /// # Errors
    ///
    /// Returns an error when `paths` is empty or a source cannot be read.
    pub fn open(paths: &[PathBuf], crs_override: Option<Crs>) -> Result<Self> {
        if paths.is_empty() {
            return Err(GeolithError::GeoTiff("no DEM files to read".into()));
        }
        let mut sources = Vec::with_capacity(paths.len());
        for path in paths {
            sources.push(open_source(path, crs_override)?);
        }
        let epsg = sources[0].crs.epsg();
        Ok(Self {
            sources,
            epsg,
            readers: Mutex::new(ReaderPool::default()),
        })
    }

    /// Number of source rasters.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.sources.len()
    }

    /// `true` when the mosaic has no sources; [`CogMosaic::open`] never
    /// returns such a mosaic.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.sources.is_empty()
    }
}

impl ElevationSource for CogMosaic {
    fn wgs84_bounds(&self) -> Bounds {
        self.sources.iter().map(|s| s.bounds).fold(
            (
                f64::INFINITY,
                f64::INFINITY,
                f64::NEG_INFINITY,
                f64::NEG_INFINITY,
            ),
            |a, b| (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)),
        )
    }

    fn elevation_range(&self) -> Option<(f32, f32)> {
        self.sources
            .iter()
            .filter_map(|s| s.range)
            .reduce(|a, b| (a.0.min(b.0), a.1.max(b.1)))
    }

    fn source_epsg(&self) -> u32 {
        self.epsg
    }

    fn patches(&self, bounds: Bounds, metres_per_pixel: f64) -> Result<Vec<Cow<'_, Dem>>> {
        let mut patches = Vec::with_capacity(2);
        for source in self.sources.iter().filter(|s| overlaps(s.bounds, bounds)) {
            let mut reader = {
                let mut pool = self.readers.lock().unwrap_or_else(PoisonError::into_inner);
                pool.take(&source.path, source.crs)?
            };
            let window = source.window(&mut reader, bounds, metres_per_pixel);
            let mut pool = self.readers.lock().unwrap_or_else(PoisonError::into_inner);
            pool.put(source.path.clone(), reader);
            drop(pool);
            if let Some(dem) = window? {
                patches.push(Cow::Owned(dem));
            }
        }
        Ok(patches)
    }
}

impl MosaicSource {
    /// Source pixels under `bounds` as a small [`Dem`], or `None` when the
    /// footprint misses the raster.
    fn window(
        &self,
        reader: &mut Cog,
        bounds: Bounds,
        metres_per_pixel: f64,
    ) -> Result<Option<Dem>> {
        let centre_lat = f64::midpoint(bounds.1, bounds.3);
        let level = pick_level(&self.levels, self.crs, centre_lat, metres_per_pixel);
        let (width, height, transform) = self.levels[level];

        let (mut min_c, mut min_r) = (f64::INFINITY, f64::INFINITY);
        let (mut max_c, mut max_r) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
        for (lon, lat) in edge_points(bounds) {
            let (x, y) = self.crs.from_wgs84(lon, lat);
            let (c, r) = transform.to_pixel(x, y);
            min_c = min_c.min(c);
            min_r = min_r.min(r);
            max_c = max_c.max(c);
            max_r = max_r.max(r);
        }
        let x0 = (min_c.floor() as i64 - WINDOW_PAD).max(0);
        let y0 = (min_r.floor() as i64 - WINDOW_PAD).max(0);
        let x1 = (max_c.ceil() as i64 + WINDOW_PAD).min(i64::from(width));
        let y1 = (max_r.ceil() as i64 + WINDOW_PAD).min(i64::from(height));
        if x0 >= x1 || y0 >= y1 {
            return Ok(None);
        }
        let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);

        let values = reader.read_window(level, x0, y0, w, h)?;

        Ok(Some(Dem {
            width: w,
            height: h,
            values,
            transform: GeoTransform {
                origin_x: transform.origin_x + x0 as f64 * transform.pixel_width,
                origin_y: transform.origin_y - y0 as f64 * transform.pixel_height,
                pixel_width: transform.pixel_width,
                pixel_height: transform.pixel_height,
            },
            crs: self.crs,
        }))
    }
}

/// The `GeoTIFFs` a `--dem` path names: the file itself, or every `.tif` and
/// `.tiff` file directly inside a directory, sorted by path so the mosaic
/// order never depends on the filesystem.
///
/// # Errors
///
/// Returns an error when the directory cannot be read or holds no `GeoTIFF`.
pub fn dem_files(path: &Path) -> Result<Vec<PathBuf>> {
    if !path.is_dir() {
        return Ok(vec![path.to_path_buf()]);
    }
    let mut files = Vec::with_capacity(64);
    for entry in std::fs::read_dir(path)? {
        let file = entry?.path();
        let is_tiff = file
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(|e| e.eq_ignore_ascii_case("tif") || e.eq_ignore_ascii_case("tiff"));
        if is_tiff && file.is_file() {
            files.push(file);
        }
    }
    if files.is_empty() {
        return Err(GeolithError::GeoTiff(format!(
            "{}: no .tif or .tiff files in the directory",
            path.display()
        )));
    }
    files.sort();
    Ok(files)
}

/// Open one source and read its smallest overview for the elevation range.
fn open_source(path: &Path, crs_override: Option<Crs>) -> Result<MosaicSource> {
    let mut cog = Cog::open(path, crs_override)?;
    let crs = cog.crs();
    let mut levels = Vec::with_capacity(cog.levels());
    for level in 0..cog.levels() {
        if let (Some((w, h)), Some(t)) = (cog.size(level), cog.geo_transform(level)) {
            levels.push((w, h, t));
        }
    }
    let (w0, h0, t0) = levels[0];
    let smallest = levels.len() - 1;
    let (ws, hs, _) = levels[smallest];
    let range = value_range(&cog.read_window(smallest, 0, 0, ws, hs)?);
    // The metadata is all the mosaic keeps: a reader held here would be one
    // descriptor per source (see ReaderPool).
    drop(cog);

    let dem = Dem {
        width: w0,
        height: h0,
        values: Vec::new(),
        transform: t0,
        crs,
    };
    Ok(MosaicSource {
        path: path.to_path_buf(),
        crs,
        bounds: dem.wgs84_bounds(),
        levels,
        range,
    })
}

/// Minimum and maximum of the non-NaN values.
fn value_range(values: &[f32]) -> Option<(f32, f32)> {
    values
        .iter()
        .filter(|v| !v.is_nan())
        .fold(None, |acc, &v| match acc {
            None => Some((v, v)),
            Some((lo, hi)) => Some((lo.min(v), hi.max(v))),
        })
}

/// The coarsest level whose pixels are no larger than `metres_per_pixel`,
/// or full resolution when even that is coarser.
fn pick_level(
    levels: &[(u32, u32, GeoTransform)],
    crs: Crs,
    lat: f64,
    metres_per_pixel: f64,
) -> usize {
    let scale = metres_per_unit(crs, lat);
    levels
        .iter()
        .rposition(|(_, _, t)| t.pixel_width * scale <= metres_per_pixel)
        .unwrap_or(0)
}

/// Ground metres per CRS unit at latitude `lat`.
fn metres_per_unit(crs: Crs, lat: f64) -> f64 {
    match crs {
        Crs::Wgs84 => METRES_PER_DEGREE * lat.to_radians().cos(),
        Crs::WebMercator => lat.to_radians().cos(),
        _ => 1.0,
    }
}

/// Points along the four edges of `bounds`, corners included.
fn edge_points(bounds: Bounds) -> Vec<(f64, f64)> {
    let (min_lon, min_lat, max_lon, max_lat) = bounds;
    let mut points = Vec::with_capacity(4 * (EDGE_SAMPLES + 1));
    for i in 0..=EDGE_SAMPLES {
        let t = i as f64 / EDGE_SAMPLES as f64;
        let lon = min_lon + t * (max_lon - min_lon);
        let lat = min_lat + t * (max_lat - min_lat);
        points.extend([
            (lon, min_lat),
            (lon, max_lat),
            (min_lon, lat),
            (max_lon, lat),
        ]);
    }
    points
}

/// `true` when two geographic boxes intersect.
fn overlaps(a: Bounds, b: Bounds) -> bool {
    a.0 <= b.2 && b.0 <= a.2 && a.1 <= b.3 && b.1 <= a.3
}

#[cfg(test)]
mod tests {
    use super::*;

    fn transform(pixel: f64) -> GeoTransform {
        GeoTransform {
            origin_x: 500_000.0,
            origin_y: 2_100_000.0,
            pixel_width: pixel,
            pixel_height: pixel,
        }
    }

    #[test]
    fn pick_level_takes_the_coarsest_level_fine_enough() {
        let levels = [
            (8, 8, transform(15.0)),
            (4, 4, transform(30.0)),
            (2, 2, transform(60.0)),
        ];
        let utm = Crs::from_epsg(32_643).expect("UTM 43N");
        assert_eq!(
            pick_level(&levels, utm, 19.0, 10.0),
            0,
            "finer than level 0"
        );
        assert_eq!(pick_level(&levels, utm, 19.0, 15.0), 0);
        assert_eq!(pick_level(&levels, utm, 19.0, 45.0), 1);
        assert_eq!(pick_level(&levels, utm, 19.0, 1000.0), 2);
    }

    /// One arc-second (1/3600°) at the equator is 111320 / 3600 = 30.9 m.
    #[test]
    fn geographic_pixels_are_sized_in_ground_metres() {
        let levels = [
            (8, 8, transform(1.0 / 3600.0)),
            (4, 4, transform(2.0 / 3600.0)),
        ];
        assert_eq!(pick_level(&levels, Crs::Wgs84, 0.0, 31.0), 0);
        assert_eq!(pick_level(&levels, Crs::Wgs84, 0.0, 62.0), 1);
        // At 60° north a degree of longitude is half as long.
        assert_eq!(pick_level(&levels, Crs::Wgs84, 60.0, 31.0), 1);
    }

    /// Web Mercator stretches ground by 1 / cos(lat): at 60° north one
    /// projected metre covers half a metre of ground.
    #[test]
    fn web_mercator_metres_shrink_with_latitude() {
        assert!((metres_per_unit(Crs::WebMercator, 0.0) - 1.0).abs() < 1e-12);
        assert!((metres_per_unit(Crs::WebMercator, 60.0) - 0.5).abs() < 1e-12);
    }

    #[test]
    fn value_range_skips_nan() {
        assert_eq!(
            value_range(&[f32::NAN, 3.0, -2.0, f32::NAN]),
            Some((-2.0, 3.0))
        );
        assert_eq!(value_range(&[f32::NAN]), None);
        assert_eq!(value_range(&[]), None);
    }

    #[test]
    fn overlaps_counts_a_shared_edge_and_rejects_a_gap() {
        assert!(overlaps((0.0, 0.0, 1.0, 1.0), (1.0, 0.0, 2.0, 1.0)));
        assert!(!overlaps((0.0, 0.0, 1.0, 1.0), (1.5, 0.0, 2.0, 1.0)));
    }

    #[test]
    fn edge_points_include_all_four_corners() {
        let points = edge_points((1.0, 2.0, 3.0, 4.0));
        for corner in [(1.0, 2.0), (3.0, 2.0), (1.0, 4.0), (3.0, 4.0)] {
            assert!(points.contains(&corner), "missing corner {corner:?}");
        }
    }

    #[test]
    fn dem_files_lists_tiffs_in_path_order_and_skips_other_files() {
        let dir = tempfile::tempdir().expect("tempdir");
        for name in ["b.tif", "a.TIFF", "c.tif.aux.xml", "notes.txt"] {
            std::fs::write(dir.path().join(name), b"").expect("write");
        }
        std::fs::create_dir(dir.path().join("d.tif")).expect("dir named like a tiff");
        let names: Vec<String> = dem_files(dir.path())
            .expect("listed")
            .iter()
            .filter_map(|p| p.file_name()?.to_str().map(str::to_owned))
            .collect();
        assert_eq!(names, ["a.TIFF", "b.tif"]);
    }

    #[test]
    fn dem_files_passes_a_file_through_and_rejects_an_empty_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let file = dir.path().join("x.tif");
        assert_eq!(dem_files(&file).expect("file"), std::slice::from_ref(&file));
        assert!(dem_files(dir.path()).is_err(), "no tiffs yet");
    }

    #[test]
    fn opening_no_files_is_an_error() {
        assert!(CogMosaic::open(&[], None).is_err());
    }
}