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
//! Polygon mask for terrain tiles: pixels outside the polygon become nodata
//! and tiles that miss it are not written.
//!
//! The mask is applied one pixel row at a time. For a row's latitude, the
//! polygon edges crossing that latitude give the longitudes where the row
//! enters and leaves the polygon (even-odd rule, so holes and islands work).
//! Edges are bucketed by latitude band, so a row reads only the edges near
//! it even for a national outline with hundreds of thousands of vertices.

use std::path::Path;

use geojson::{GeoJson, Geometry, GeometryValue, Position};
use geolith::error::{GeolithError, Result};

use crate::terrain::source::Bounds;

/// Latitude bands per degree in the edge index.
const BANDS_PER_DEGREE: f64 = 20.0;

/// One polygon edge in longitude/latitude.
#[derive(Debug, Clone, Copy)]
struct Edge {
    lon0: f64,
    lat0: f64,
    lon1: f64,
    lat1: f64,
}

/// A polygon mask in WGS84 longitude/latitude.
#[derive(Debug, Clone)]
pub struct ClipMask {
    bounds: Bounds,
    edges: Vec<Edge>,
    /// Edge indices per latitude band, from `bounds.1` upward.
    bands: Vec<Vec<u32>>,
}

impl ClipMask {
    /// Read every Polygon and `MultiPolygon` ring of a `GeoJSON` file.
    ///
    /// # Errors
    ///
    /// Returns [`GeolithError::GeoJson`] when the file cannot be read or
    /// parsed, or holds no polygon.
    pub fn from_geojson(path: &Path) -> Result<Self> {
        let text = std::fs::read_to_string(path)?;
        let geojson: GeoJson = text
            .parse()
            .map_err(|e| GeolithError::GeoJson(format!("{}: {e}", path.display())))?;
        let mut rings = Vec::with_capacity(64);
        match geojson {
            GeoJson::FeatureCollection(fc) => {
                for feature in fc.features {
                    if let Some(geometry) = feature.geometry {
                        collect_rings(&geometry, &mut rings);
                    }
                }
            }
            GeoJson::Feature(feature) => {
                if let Some(geometry) = feature.geometry {
                    collect_rings(&geometry, &mut rings);
                }
            }
            GeoJson::Geometry(geometry) => collect_rings(&geometry, &mut rings),
        }
        Self::from_rings(&rings).ok_or_else(|| {
            GeolithError::GeoJson(format!("{}: no Polygon or MultiPolygon", path.display()))
        })
    }

    /// Build a mask from closed or open rings of `[lon, lat]` points, or
    /// `None` when no ring has an area.
    #[must_use]
    pub fn from_rings(rings: &[Vec<[f64; 2]>]) -> Option<Self> {
        let mut edges = Vec::with_capacity(rings.iter().map(Vec::len).sum());
        for ring in rings.iter().filter(|r| r.len() >= 3) {
            for (i, a) in ring.iter().enumerate() {
                let b = ring[(i + 1) % ring.len()];
                if a[1] != b[1] {
                    edges.push(Edge {
                        lon0: a[0],
                        lat0: a[1],
                        lon1: b[0],
                        lat1: b[1],
                    });
                }
            }
        }
        if edges.is_empty() {
            return None;
        }
        let bounds = edges.iter().fold(
            (
                f64::INFINITY,
                f64::INFINITY,
                f64::NEG_INFINITY,
                f64::NEG_INFINITY,
            ),
            |b, e| {
                (
                    b.0.min(e.lon0).min(e.lon1),
                    b.1.min(e.lat0).min(e.lat1),
                    b.2.max(e.lon0).max(e.lon1),
                    b.3.max(e.lat0).max(e.lat1),
                )
            },
        );
        let band_count = ((bounds.3 - bounds.1) * BANDS_PER_DEGREE).ceil() as usize + 1;
        let mut bands = vec![Vec::new(); band_count];
        let band_of = |lat: f64| ((lat - bounds.1) * BANDS_PER_DEGREE) as usize;
        for (index, edge) in edges.iter().enumerate() {
            let (lo, hi) = (edge.lat0.min(edge.lat1), edge.lat0.max(edge.lat1));
            let index = u32::try_from(index).ok()?;
            for band in &mut bands[band_of(lo)..=band_of(hi).min(band_count - 1)] {
                band.push(index);
            }
        }
        Some(Self {
            bounds,
            edges,
            bands,
        })
    }

    /// Bounding box of the polygon.
    #[must_use]
    pub const fn bounds(&self) -> Bounds {
        self.bounds
    }

    /// `true` when `bounds` intersects the polygon's bounding box.
    #[must_use]
    pub fn may_intersect(&self, bounds: Bounds) -> bool {
        let b = self.bounds;
        b.0 <= bounds.2 && bounds.0 <= b.2 && b.1 <= bounds.3 && bounds.1 <= b.3
    }

    /// Sorted longitudes where a row at `lat` crosses the polygon; the row is
    /// inside between crossings 0 and 1, 2 and 3, and so on.
    #[must_use]
    pub fn crossings(&self, lat: f64) -> Vec<f64> {
        if lat < self.bounds.1 || lat > self.bounds.3 {
            return Vec::new();
        }
        let band = (((lat - self.bounds.1) * BANDS_PER_DEGREE) as usize).min(self.bands.len() - 1);
        let mut xs: Vec<f64> = self.bands[band]
            .iter()
            .filter_map(|&i| {
                let e = self.edges[i as usize];
                // Half-open in latitude, so a vertex on the row counts once.
                let crosses = (e.lat0 <= lat) != (e.lat1 <= lat);
                crosses.then(|| e.lon0 + (lat - e.lat0) / (e.lat1 - e.lat0) * (e.lon1 - e.lon0))
            })
            .collect();
        xs.sort_by(f64::total_cmp);
        xs
    }

    /// `true` when the point lies inside the polygon.
    #[must_use]
    pub fn contains(&self, lon: f64, lat: f64) -> bool {
        inside(&self.crossings(lat), lon)
    }
}

/// `true` when `lon` falls inside the spans of a sorted crossing list.
#[must_use]
pub fn inside(crossings: &[f64], lon: f64) -> bool {
    crossings.partition_point(|&x| x <= lon) % 2 == 1
}

/// Append the rings of a Polygon or `MultiPolygon` (inside collections too).
fn collect_rings(geometry: &Geometry, rings: &mut Vec<Vec<[f64; 2]>>) {
    let ring = |r: &Vec<Position>| -> Vec<[f64; 2]> {
        r.iter()
            .filter(|p| p.len() >= 2)
            .map(|p| [p[0], p[1]])
            .collect()
    };
    match &geometry.value {
        GeometryValue::Polygon { coordinates } => rings.extend(coordinates.iter().map(ring)),
        GeometryValue::MultiPolygon { coordinates } => {
            rings.extend(coordinates.iter().flatten().map(ring));
        }
        GeometryValue::GeometryCollection { geometries } => {
            for g in geometries {
                collect_rings(g, rings);
            }
        }
        _ => {}
    }
}

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

    /// A 10° square from (0, 0) to (10, 10) with a 2° hole at (4..6, 4..6),
    /// plus a 1° island at (20..21, 5..6).
    fn mask() -> ClipMask {
        ClipMask::from_rings(&[
            vec![
                [0.0, 0.0],
                [10.0, 0.0],
                [10.0, 10.0],
                [0.0, 10.0],
                [0.0, 0.0],
            ],
            vec![[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0]],
            vec![[20.0, 5.0], [21.0, 5.0], [21.0, 6.0], [20.0, 6.0]],
        ])
        .expect("mask")
    }

    #[test]
    fn points_inside_outside_in_the_hole_and_on_the_island() {
        let m = mask();
        assert!(m.contains(1.0, 1.0));
        assert!(m.contains(9.5, 5.0));
        assert!(!m.contains(5.0, 5.0), "hole");
        assert!(!m.contains(15.0, 5.5), "gap between square and island");
        assert!(m.contains(20.5, 5.5), "island");
        assert!(!m.contains(-1.0, 5.0));
        assert!(!m.contains(5.0, 11.0), "above the bounds");
        assert!(!m.contains(5.0, -0.5), "below the bounds");
    }

    #[test]
    fn crossings_list_every_boundary_on_a_row() {
        assert_eq!(mask().crossings(5.5), vec![0.0, 4.0, 6.0, 10.0, 20.0, 21.0]);
        assert_eq!(mask().crossings(2.0), vec![0.0, 10.0]);
    }

    #[test]
    fn a_row_through_a_vertex_counts_it_once() {
        // A diamond: the row at lat 5 passes through the left and right vertices.
        let m = ClipMask::from_rings(&[vec![[0.0, 5.0], [5.0, 0.0], [10.0, 5.0], [5.0, 10.0]]])
            .expect("diamond");
        assert_eq!(m.crossings(5.0).len() % 2, 0);
        assert!(m.contains(5.0, 5.0));
        assert!(m.contains(5.0, 9.0));
        assert!(!m.contains(1.0, 9.0));
    }

    #[test]
    fn bounds_and_bbox_test() {
        let m = mask();
        assert_eq!(m.bounds(), (0.0, 0.0, 21.0, 10.0));
        assert!(m.may_intersect((9.0, 9.0, 12.0, 12.0)));
        assert!(!m.may_intersect((30.0, 0.0, 31.0, 1.0)));
    }

    #[test]
    fn rings_without_area_give_no_mask() {
        assert!(ClipMask::from_rings(&[]).is_none());
        assert!(ClipMask::from_rings(&[vec![[0.0, 0.0], [1.0, 0.0]]]).is_none());
        assert!(
            ClipMask::from_rings(&[vec![[0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]]).is_none(),
            "a flat ring has no edge that crosses a row"
        );
    }

    #[test]
    fn geojson_feature_collection_feature_and_geometry_all_load() {
        let dir = tempfile::tempdir().expect("tempdir");
        let square = r#"{"type":"Polygon","coordinates":[[[0,0],[2,0],[2,2],[0,2],[0,0]]]}"#;
        let multi = r#"{"type":"MultiPolygon","coordinates":[[[[0,0],[2,0],[2,2],[0,2],[0,0]]]]}"#;
        let cases = [
            square.to_string(),
            format!(r#"{{"type":"Feature","properties":{{}},"geometry":{multi}}}"#),
            format!(
                r#"{{"type":"FeatureCollection","features":[{{"type":"Feature","properties":{{}},"geometry":{{"type":"GeometryCollection","geometries":[{square},{{"type":"Point","coordinates":[9,9]}}]}}}},{{"type":"Feature","properties":{{}},"geometry":null}}]}}"#
            ),
        ];
        for (i, text) in cases.iter().enumerate() {
            let path = dir.path().join(format!("{i}.geojson"));
            std::fs::write(&path, text).expect("write");
            let m = ClipMask::from_geojson(&path).expect("loads");
            assert!(m.contains(1.0, 1.0), "case {i}");
            assert!(!m.contains(3.0, 1.0), "case {i}");
        }
    }

    #[test]
    fn geojson_without_a_polygon_or_unparseable_is_an_error() {
        let dir = tempfile::tempdir().expect("tempdir");
        let point = dir.path().join("point.geojson");
        std::fs::write(&point, r#"{"type":"Point","coordinates":[1,1]}"#).expect("write");
        assert!(ClipMask::from_geojson(&point).is_err());
        let junk = dir.path().join("junk.geojson");
        std::fs::write(&junk, "not json").expect("write");
        assert!(ClipMask::from_geojson(&junk).is_err());
    }
}