Skip to main content

geolith_tiles_builder/terrain/
clip.rs

1//! Polygon mask for terrain tiles: pixels outside the polygon become nodata
2//! and tiles that miss it are not written.
3//!
4//! The mask is applied one pixel row at a time. For a row's latitude, the
5//! polygon edges crossing that latitude give the longitudes where the row
6//! enters and leaves the polygon (even-odd rule, so holes and islands work).
7//! Edges are bucketed by latitude band, so a row reads only the edges near
8//! it even for a national outline with hundreds of thousands of vertices.
9
10use std::path::Path;
11
12use geojson::{GeoJson, Geometry, GeometryValue, Position};
13use geolith::error::{GeolithError, Result};
14
15use crate::terrain::source::Bounds;
16
17/// Latitude bands per degree in the edge index.
18const BANDS_PER_DEGREE: f64 = 20.0;
19
20/// One polygon edge in longitude/latitude.
21#[derive(Debug, Clone, Copy)]
22struct Edge {
23    lon0: f64,
24    lat0: f64,
25    lon1: f64,
26    lat1: f64,
27}
28
29/// A polygon mask in WGS84 longitude/latitude.
30#[derive(Debug, Clone)]
31pub struct ClipMask {
32    bounds: Bounds,
33    edges: Vec<Edge>,
34    /// Edge indices per latitude band, from `bounds.1` upward.
35    bands: Vec<Vec<u32>>,
36}
37
38impl ClipMask {
39    /// Read every Polygon and `MultiPolygon` ring of a `GeoJSON` file.
40    ///
41    /// # Errors
42    ///
43    /// Returns [`GeolithError::GeoJson`] when the file cannot be read or
44    /// parsed, or holds no polygon.
45    pub fn from_geojson(path: &Path) -> Result<Self> {
46        let text = std::fs::read_to_string(path)?;
47        let geojson: GeoJson = text
48            .parse()
49            .map_err(|e| GeolithError::GeoJson(format!("{}: {e}", path.display())))?;
50        let mut rings = Vec::with_capacity(64);
51        match geojson {
52            GeoJson::FeatureCollection(fc) => {
53                for feature in fc.features {
54                    if let Some(geometry) = feature.geometry {
55                        collect_rings(&geometry, &mut rings);
56                    }
57                }
58            }
59            GeoJson::Feature(feature) => {
60                if let Some(geometry) = feature.geometry {
61                    collect_rings(&geometry, &mut rings);
62                }
63            }
64            GeoJson::Geometry(geometry) => collect_rings(&geometry, &mut rings),
65        }
66        Self::from_rings(&rings).ok_or_else(|| {
67            GeolithError::GeoJson(format!("{}: no Polygon or MultiPolygon", path.display()))
68        })
69    }
70
71    /// Build a mask from closed or open rings of `[lon, lat]` points, or
72    /// `None` when no ring has an area.
73    #[must_use]
74    pub fn from_rings(rings: &[Vec<[f64; 2]>]) -> Option<Self> {
75        let mut edges = Vec::with_capacity(rings.iter().map(Vec::len).sum());
76        for ring in rings.iter().filter(|r| r.len() >= 3) {
77            for (i, a) in ring.iter().enumerate() {
78                let b = ring[(i + 1) % ring.len()];
79                if a[1] != b[1] {
80                    edges.push(Edge {
81                        lon0: a[0],
82                        lat0: a[1],
83                        lon1: b[0],
84                        lat1: b[1],
85                    });
86                }
87            }
88        }
89        if edges.is_empty() {
90            return None;
91        }
92        let bounds = edges.iter().fold(
93            (
94                f64::INFINITY,
95                f64::INFINITY,
96                f64::NEG_INFINITY,
97                f64::NEG_INFINITY,
98            ),
99            |b, e| {
100                (
101                    b.0.min(e.lon0).min(e.lon1),
102                    b.1.min(e.lat0).min(e.lat1),
103                    b.2.max(e.lon0).max(e.lon1),
104                    b.3.max(e.lat0).max(e.lat1),
105                )
106            },
107        );
108        let band_count = ((bounds.3 - bounds.1) * BANDS_PER_DEGREE).ceil() as usize + 1;
109        let mut bands = vec![Vec::new(); band_count];
110        let band_of = |lat: f64| ((lat - bounds.1) * BANDS_PER_DEGREE) as usize;
111        for (index, edge) in edges.iter().enumerate() {
112            let (lo, hi) = (edge.lat0.min(edge.lat1), edge.lat0.max(edge.lat1));
113            let index = u32::try_from(index).ok()?;
114            for band in &mut bands[band_of(lo)..=band_of(hi).min(band_count - 1)] {
115                band.push(index);
116            }
117        }
118        Some(Self {
119            bounds,
120            edges,
121            bands,
122        })
123    }
124
125    /// Bounding box of the polygon.
126    #[must_use]
127    pub const fn bounds(&self) -> Bounds {
128        self.bounds
129    }
130
131    /// `true` when `bounds` intersects the polygon's bounding box.
132    #[must_use]
133    pub fn may_intersect(&self, bounds: Bounds) -> bool {
134        let b = self.bounds;
135        b.0 <= bounds.2 && bounds.0 <= b.2 && b.1 <= bounds.3 && bounds.1 <= b.3
136    }
137
138    /// Sorted longitudes where a row at `lat` crosses the polygon; the row is
139    /// inside between crossings 0 and 1, 2 and 3, and so on.
140    #[must_use]
141    pub fn crossings(&self, lat: f64) -> Vec<f64> {
142        if lat < self.bounds.1 || lat > self.bounds.3 {
143            return Vec::new();
144        }
145        let band = (((lat - self.bounds.1) * BANDS_PER_DEGREE) as usize).min(self.bands.len() - 1);
146        let mut xs: Vec<f64> = self.bands[band]
147            .iter()
148            .filter_map(|&i| {
149                let e = self.edges[i as usize];
150                // Half-open in latitude, so a vertex on the row counts once.
151                let crosses = (e.lat0 <= lat) != (e.lat1 <= lat);
152                crosses.then(|| e.lon0 + (lat - e.lat0) / (e.lat1 - e.lat0) * (e.lon1 - e.lon0))
153            })
154            .collect();
155        xs.sort_by(f64::total_cmp);
156        xs
157    }
158
159    /// `true` when the point lies inside the polygon.
160    #[must_use]
161    pub fn contains(&self, lon: f64, lat: f64) -> bool {
162        inside(&self.crossings(lat), lon)
163    }
164}
165
166/// `true` when `lon` falls inside the spans of a sorted crossing list.
167#[must_use]
168pub fn inside(crossings: &[f64], lon: f64) -> bool {
169    crossings.partition_point(|&x| x <= lon) % 2 == 1
170}
171
172/// Append the rings of a Polygon or `MultiPolygon` (inside collections too).
173fn collect_rings(geometry: &Geometry, rings: &mut Vec<Vec<[f64; 2]>>) {
174    let ring = |r: &Vec<Position>| -> Vec<[f64; 2]> {
175        r.iter()
176            .filter(|p| p.len() >= 2)
177            .map(|p| [p[0], p[1]])
178            .collect()
179    };
180    match &geometry.value {
181        GeometryValue::Polygon { coordinates } => rings.extend(coordinates.iter().map(ring)),
182        GeometryValue::MultiPolygon { coordinates } => {
183            rings.extend(coordinates.iter().flatten().map(ring));
184        }
185        GeometryValue::GeometryCollection { geometries } => {
186            for g in geometries {
187                collect_rings(g, rings);
188            }
189        }
190        _ => {}
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    /// A 10° square from (0, 0) to (10, 10) with a 2° hole at (4..6, 4..6),
199    /// plus a 1° island at (20..21, 5..6).
200    fn mask() -> ClipMask {
201        ClipMask::from_rings(&[
202            vec![
203                [0.0, 0.0],
204                [10.0, 0.0],
205                [10.0, 10.0],
206                [0.0, 10.0],
207                [0.0, 0.0],
208            ],
209            vec![[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0]],
210            vec![[20.0, 5.0], [21.0, 5.0], [21.0, 6.0], [20.0, 6.0]],
211        ])
212        .expect("mask")
213    }
214
215    #[test]
216    fn points_inside_outside_in_the_hole_and_on_the_island() {
217        let m = mask();
218        assert!(m.contains(1.0, 1.0));
219        assert!(m.contains(9.5, 5.0));
220        assert!(!m.contains(5.0, 5.0), "hole");
221        assert!(!m.contains(15.0, 5.5), "gap between square and island");
222        assert!(m.contains(20.5, 5.5), "island");
223        assert!(!m.contains(-1.0, 5.0));
224        assert!(!m.contains(5.0, 11.0), "above the bounds");
225        assert!(!m.contains(5.0, -0.5), "below the bounds");
226    }
227
228    #[test]
229    fn crossings_list_every_boundary_on_a_row() {
230        assert_eq!(mask().crossings(5.5), vec![0.0, 4.0, 6.0, 10.0, 20.0, 21.0]);
231        assert_eq!(mask().crossings(2.0), vec![0.0, 10.0]);
232    }
233
234    #[test]
235    fn a_row_through_a_vertex_counts_it_once() {
236        // A diamond: the row at lat 5 passes through the left and right vertices.
237        let m = ClipMask::from_rings(&[vec![[0.0, 5.0], [5.0, 0.0], [10.0, 5.0], [5.0, 10.0]]])
238            .expect("diamond");
239        assert_eq!(m.crossings(5.0).len() % 2, 0);
240        assert!(m.contains(5.0, 5.0));
241        assert!(m.contains(5.0, 9.0));
242        assert!(!m.contains(1.0, 9.0));
243    }
244
245    #[test]
246    fn bounds_and_bbox_test() {
247        let m = mask();
248        assert_eq!(m.bounds(), (0.0, 0.0, 21.0, 10.0));
249        assert!(m.may_intersect((9.0, 9.0, 12.0, 12.0)));
250        assert!(!m.may_intersect((30.0, 0.0, 31.0, 1.0)));
251    }
252
253    #[test]
254    fn rings_without_area_give_no_mask() {
255        assert!(ClipMask::from_rings(&[]).is_none());
256        assert!(ClipMask::from_rings(&[vec![[0.0, 0.0], [1.0, 0.0]]]).is_none());
257        assert!(
258            ClipMask::from_rings(&[vec![[0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]]).is_none(),
259            "a flat ring has no edge that crosses a row"
260        );
261    }
262
263    #[test]
264    fn geojson_feature_collection_feature_and_geometry_all_load() {
265        let dir = tempfile::tempdir().expect("tempdir");
266        let square = r#"{"type":"Polygon","coordinates":[[[0,0],[2,0],[2,2],[0,2],[0,0]]]}"#;
267        let multi = r#"{"type":"MultiPolygon","coordinates":[[[[0,0],[2,0],[2,2],[0,2],[0,0]]]]}"#;
268        let cases = [
269            square.to_string(),
270            format!(r#"{{"type":"Feature","properties":{{}},"geometry":{multi}}}"#),
271            format!(
272                r#"{{"type":"FeatureCollection","features":[{{"type":"Feature","properties":{{}},"geometry":{{"type":"GeometryCollection","geometries":[{square},{{"type":"Point","coordinates":[9,9]}}]}}}},{{"type":"Feature","properties":{{}},"geometry":null}}]}}"#
273            ),
274        ];
275        for (i, text) in cases.iter().enumerate() {
276            let path = dir.path().join(format!("{i}.geojson"));
277            std::fs::write(&path, text).expect("write");
278            let m = ClipMask::from_geojson(&path).expect("loads");
279            assert!(m.contains(1.0, 1.0), "case {i}");
280            assert!(!m.contains(3.0, 1.0), "case {i}");
281        }
282    }
283
284    #[test]
285    fn geojson_without_a_polygon_or_unparseable_is_an_error() {
286        let dir = tempfile::tempdir().expect("tempdir");
287        let point = dir.path().join("point.geojson");
288        std::fs::write(&point, r#"{"type":"Point","coordinates":[1,1]}"#).expect("write");
289        assert!(ClipMask::from_geojson(&point).is_err());
290        let junk = dir.path().join("junk.geojson");
291        std::fs::write(&junk, "not json").expect("write");
292        assert!(ClipMask::from_geojson(&junk).is_err());
293    }
294}