Skip to main content

geolith/source/
shapefile_reader.rs

1//! Shapefile reader for pre-processed water and land polygons.
2//!
3//! Reads `water-polygons-split-3857` and `land-polygons-split-3857` shapefiles,
4//! reprojecting from EPSG:3857 (Web Mercator) to EPSG:4326 (WGS84).
5//!
6//! These shapefiles provide the ocean and land polygons for z6+ where
7//! Natural Earth data is too coarse.
8
9use std::collections::HashMap;
10use std::path::Path;
11use std::sync::Arc;
12
13use crate::source::bbox_filter::Bbox;
14use crate::source::input::{DataSource, InputFeature};
15
16/// Half of the Earth's circumference in EPSG:3857 meters.
17const HALF_CIRCUMFERENCE: f64 = 20_037_508.342_789_244;
18
19/// Reproject a coordinate from EPSG:3857 (Web Mercator) to EPSG:4326 (WGS84).
20///
21/// Returns `(longitude, latitude)` in degrees.
22fn mercator_to_wgs84(x: f64, y: f64) -> (f64, f64) {
23    let lon = x * 180.0 / HALF_CIRCUMFERENCE;
24    let lat = (std::f64::consts::PI / 2.0
25        - 2.0
26            * (-y / HALF_CIRCUMFERENCE * std::f64::consts::PI)
27                .exp()
28                .atan())
29        * 180.0
30        / std::f64::consts::PI;
31    (lon, lat)
32}
33
34/// Reproject a `geo::Coord` from EPSG:3857 to EPSG:4326.
35fn reproject_coord(coord: geo::Coord<f64>) -> geo::Coord<f64> {
36    let (lon, lat) = mercator_to_wgs84(coord.x, coord.y);
37    geo::Coord { x: lon, y: lat }
38}
39
40/// Stream land polygons from a shapefile through `emit`.
41///
42/// Expects `land-polygons-split-3857` in EPSG:3857 projection.
43/// Coordinates are reprojected to WGS84 before emission. When `bbox` is
44/// provided, shapes whose EPSG:3857 bbox reprojects to a region outside the
45/// WGS84 bbox are skipped without decoding — a large speedup for small bbox
46/// builds against global shapefiles.
47///
48/// # Errors
49///
50/// `GeolithError::Shapefile` when the shapefile cannot be opened or a shape
51/// cannot be read.
52pub fn read_land_polygons(
53    path: &Path,
54    bbox: Option<&Bbox>,
55    emit: impl FnMut(InputFeature),
56) -> crate::error::Result<u64> {
57    read_shapefile(path, DataSource::LandPolygons, bbox, emit)
58}
59
60/// Stream water polygons from a shapefile through `emit`.
61///
62/// Expects `water-polygons-split-3857` in EPSG:3857 projection.
63/// Coordinates are reprojected to WGS84 before emission. See
64/// [`read_land_polygons`] for `bbox` semantics.
65///
66/// # Errors
67///
68/// `GeolithError::Shapefile` when the shapefile cannot be opened or a shape
69/// cannot be read.
70pub fn read_water_polygons(
71    path: &Path,
72    bbox: Option<&Bbox>,
73    emit: impl FnMut(InputFeature),
74) -> crate::error::Result<u64> {
75    read_shapefile(path, DataSource::WaterPolygons, bbox, emit)
76}
77
78/// Stream polygons from a shapefile, tagging with the given source.
79///
80/// The optional `bbox` (WGS84) enables early-skip before full geometry decode.
81fn read_shapefile(
82    path: &Path,
83    source: DataSource,
84    bbox: Option<&Bbox>,
85    mut emit: impl FnMut(InputFeature),
86) -> crate::error::Result<u64> {
87    let mut reader = shapefile::Reader::from_path(path).map_err(|e| {
88        crate::error::GeolithError::Shapefile(format!(
89            "Failed to open shapefile {}: {e}",
90            path.display()
91        ))
92    })?;
93
94    let mut idx: u64 = 0;
95    let mut emitted: u64 = 0;
96    let mut skipped_by_bbox: u64 = 0;
97
98    for result in reader.iter_shapes_and_records() {
99        let (shape, _record) = result.map_err(|e| {
100            crate::error::GeolithError::Shapefile(format!(
101                "Failed to read shape at index {idx}: {e}"
102            ))
103        })?;
104
105        if let Some(b) = bbox
106            && let Some(shape_bbox_3857) = shape_bbox_3857(&shape)
107            && !bbox_intersects_3857(b, shape_bbox_3857)
108        {
109            skipped_by_bbox += 1;
110            idx += 1;
111            continue;
112        }
113
114        let geometry = match shape {
115            shapefile::Shape::Polygon(poly) => convert_shapefile_polygon(&poly),
116            shapefile::Shape::PolygonZ(poly) => convert_shapefile_polygon_z(&poly),
117            _ => {
118                tracing::trace!("Skipping non-polygon shape at index {idx}");
119                idx += 1;
120                continue;
121            }
122        };
123
124        let geometry = match geometry {
125            Some(geom) => geom,
126            None => {
127                idx += 1;
128                continue;
129            }
130        };
131
132        emit(InputFeature {
133            id: idx,
134            geometry: Arc::new(geometry),
135            properties: HashMap::new(),
136            bbox: None,
137            source: source.clone(),
138        });
139
140        idx += 1;
141        emitted += 1;
142    }
143
144    tracing::info!(
145        "Shapefile: read {emitted} polygons from {} (bbox-skipped {skipped_by_bbox})",
146        path.display()
147    );
148
149    Ok(emitted)
150}
151
152/// Extract the EPSG:3857 bounding box of a shape as `[min_x, min_y, max_x, max_y]`.
153fn shape_bbox_3857(shape: &shapefile::Shape) -> Option<[f64; 4]> {
154    match shape {
155        shapefile::Shape::Polygon(p) => {
156            let bb = p.bbox();
157            Some([bb.min.x, bb.min.y, bb.max.x, bb.max.y])
158        }
159        shapefile::Shape::PolygonZ(p) => {
160            let bb = p.bbox();
161            Some([bb.min.x, bb.min.y, bb.max.x, bb.max.y])
162        }
163        _ => None,
164    }
165}
166
167/// Check if an EPSG:3857 bbox (reprojected to WGS84) intersects the target WGS84 bbox.
168fn bbox_intersects_3857(target_wgs84: &Bbox, shape_3857: [f64; 4]) -> bool {
169    let (min_lon, min_lat) = mercator_to_wgs84(shape_3857[0], shape_3857[1]);
170    let (max_lon, max_lat) = mercator_to_wgs84(shape_3857[2], shape_3857[3]);
171    target_wgs84.intersects(min_lon, min_lat, max_lon, max_lat)
172}
173
174/// Convert a shapefile Polygon to a reprojected `geo::Geometry`.
175fn convert_shapefile_polygon(poly: &shapefile::Polygon) -> Option<geo::Geometry<f64>> {
176    let rings = poly.rings();
177    if rings.is_empty() {
178        return None;
179    }
180
181    let mut geo_polygons: Vec<geo::Polygon<f64>> = Vec::with_capacity(1);
182    let mut current_exterior: Option<geo::LineString<f64>> = None;
183    let mut current_interiors: Vec<geo::LineString<f64>> = Vec::new();
184
185    for ring in rings {
186        let coords: Vec<geo::Coord<f64>> = match ring {
187            shapefile::PolygonRing::Outer(points) | shapefile::PolygonRing::Inner(points) => points
188                .iter()
189                .map(|p| reproject_coord(geo::Coord { x: p.x, y: p.y }))
190                .collect(),
191        };
192
193        if coords.len() < 4 {
194            continue;
195        }
196
197        match ring {
198            shapefile::PolygonRing::Outer(_) => {
199                // Flush previous polygon if any
200                if let Some(ext) = current_exterior.take() {
201                    geo_polygons.push(geo::Polygon::new(
202                        ext,
203                        std::mem::take(&mut current_interiors),
204                    ));
205                }
206                current_exterior = Some(geo::LineString::new(coords));
207            }
208            shapefile::PolygonRing::Inner(_) => {
209                current_interiors.push(geo::LineString::new(coords));
210            }
211        }
212    }
213
214    // Flush last polygon
215    if let Some(ext) = current_exterior {
216        geo_polygons.push(geo::Polygon::new(ext, current_interiors));
217    }
218
219    match geo_polygons.len() {
220        0 => None,
221        1 => Some(geo::Geometry::Polygon(geo_polygons.into_iter().next()?)),
222        _ => Some(geo::Geometry::MultiPolygon(geo::MultiPolygon::new(
223            geo_polygons,
224        ))),
225    }
226}
227
228/// Convert a shapefile `PolygonZ` to a reprojected `geo::Geometry`.
229///
230/// Same as [`convert_shapefile_polygon`] but handles the Z variant.
231fn convert_shapefile_polygon_z(poly: &shapefile::PolygonZ) -> Option<geo::Geometry<f64>> {
232    let rings = poly.rings();
233    if rings.is_empty() {
234        return None;
235    }
236
237    let mut geo_polygons: Vec<geo::Polygon<f64>> = Vec::with_capacity(1);
238    let mut current_exterior: Option<geo::LineString<f64>> = None;
239    let mut current_interiors: Vec<geo::LineString<f64>> = Vec::new();
240
241    for ring in rings {
242        let coords: Vec<geo::Coord<f64>> = match ring {
243            shapefile::PolygonRing::Outer(points) | shapefile::PolygonRing::Inner(points) => points
244                .iter()
245                .map(|p| reproject_coord(geo::Coord { x: p.x, y: p.y }))
246                .collect(),
247        };
248
249        if coords.len() < 4 {
250            continue;
251        }
252
253        match ring {
254            shapefile::PolygonRing::Outer(_) => {
255                if let Some(ext) = current_exterior.take() {
256                    geo_polygons.push(geo::Polygon::new(
257                        ext,
258                        std::mem::take(&mut current_interiors),
259                    ));
260                }
261                current_exterior = Some(geo::LineString::new(coords));
262            }
263            shapefile::PolygonRing::Inner(_) => {
264                current_interiors.push(geo::LineString::new(coords));
265            }
266        }
267    }
268
269    if let Some(ext) = current_exterior {
270        geo_polygons.push(geo::Polygon::new(ext, current_interiors));
271    }
272
273    match geo_polygons.len() {
274        0 => None,
275        1 => Some(geo::Geometry::Polygon(geo_polygons.into_iter().next()?)),
276        _ => Some(geo::Geometry::MultiPolygon(geo::MultiPolygon::new(
277            geo_polygons,
278        ))),
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn mercator_to_wgs84_origin() {
288        let (lon, lat) = mercator_to_wgs84(0.0, 0.0);
289        assert!(lon.abs() < 1e-10);
290        assert!(lat.abs() < 1e-10);
291    }
292
293    #[test]
294    fn mercator_to_wgs84_london() {
295        // London: approximately -14226.5, 6711533.7 in EPSG:3857
296        let (lon, lat) = mercator_to_wgs84(-14_226.5, 6_711_533.7);
297        assert!((lon - (-0.1278)).abs() < 0.01, "lon={lon}");
298        assert!((lat - 51.5074).abs() < 0.01, "lat={lat}");
299    }
300
301    #[test]
302    fn mercator_to_wgs84_extremes() {
303        // Max EPSG:3857 extent
304        let (lon, _lat) = mercator_to_wgs84(HALF_CIRCUMFERENCE, 0.0);
305        assert!((lon - 180.0).abs() < 1e-6);
306
307        let (lon, _lat) = mercator_to_wgs84(-HALF_CIRCUMFERENCE, 0.0);
308        assert!((lon - (-180.0)).abs() < 1e-6);
309    }
310
311    #[test]
312    fn nonexistent_shapefile_errors() {
313        let result = read_land_polygons(Path::new("/tmp/nonexistent-land.shp"), None, |_| {});
314        assert!(result.is_err());
315    }
316
317    fn write_tiny_shapefile(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
318        use shapefile::dbase::TableWriterBuilder;
319        use shapefile::record::polygon::{Polygon as ShapePolygon, PolygonRing};
320        use shapefile::{Point, Writer};
321
322        let path = dir.join(format!("{name}.shp"));
323        let table = TableWriterBuilder::new();
324        let mut writer = Writer::from_path(&path, table).expect("create writer");
325
326        let outer = vec![
327            Point::new(0.0, 0.0),
328            Point::new(1_000_000.0, 0.0),
329            Point::new(1_000_000.0, 1_000_000.0),
330            Point::new(0.0, 1_000_000.0),
331            Point::new(0.0, 0.0),
332        ];
333        let polygon = ShapePolygon::with_rings(vec![PolygonRing::Outer(outer)]);
334
335        writer
336            .write_shape_and_record(&polygon, &shapefile::dbase::Record::default())
337            .expect("write polygon");
338
339        let outer2 = vec![
340            Point::new(5_000_000.0, 5_000_000.0),
341            Point::new(6_000_000.0, 5_000_000.0),
342            Point::new(6_000_000.0, 6_000_000.0),
343            Point::new(5_000_000.0, 5_000_000.0),
344        ];
345        let polygon2 = ShapePolygon::with_rings(vec![PolygonRing::Outer(outer2)]);
346        writer
347            .write_shape_and_record(&polygon2, &shapefile::dbase::Record::default())
348            .expect("write polygon 2");
349
350        path
351    }
352
353    #[test]
354    fn read_land_polygons_emits_features_from_real_shapefile() {
355        let dir = tempfile::tempdir().expect("tmp");
356        let path = write_tiny_shapefile(dir.path(), "land");
357        let mut count = 0u64;
358        let result = read_land_polygons(&path, None, |feat| {
359            assert!(matches!(feat.source, DataSource::LandPolygons));
360            count += 1;
361        });
362        assert!(result.is_ok(), "{:?}", result.err());
363        assert_eq!(result.unwrap(), 2);
364        assert_eq!(count, 2);
365    }
366
367    #[test]
368    fn read_water_polygons_emits_features_from_real_shapefile() {
369        let dir = tempfile::tempdir().expect("tmp");
370        let path = write_tiny_shapefile(dir.path(), "water");
371        let mut count = 0u64;
372        let result = read_water_polygons(&path, None, |feat| {
373            assert!(matches!(feat.source, DataSource::WaterPolygons));
374            count += 1;
375        });
376        assert!(result.is_ok(), "{:?}", result.err());
377        assert_eq!(result.unwrap(), 2);
378        assert_eq!(count, 2);
379    }
380
381    #[test]
382    fn read_shapefile_skips_features_outside_bbox() {
383        let dir = tempfile::tempdir().expect("tmp");
384        let path = write_tiny_shapefile(dir.path(), "land2");
385        let bbox = Bbox {
386            min_lon: -120.0,
387            min_lat: -80.0,
388            max_lon: -100.0,
389            max_lat: -60.0,
390        };
391        let mut count = 0u64;
392        let result = read_land_polygons(&path, Some(&bbox), |_| {
393            count += 1;
394        });
395        assert!(result.is_ok());
396        assert_eq!(count, 0, "polygons fully outside bbox must be skipped");
397    }
398
399    #[test]
400    fn read_shapefile_with_full_world_bbox_keeps_all() {
401        let dir = tempfile::tempdir().expect("tmp");
402        let path = write_tiny_shapefile(dir.path(), "land3");
403        let bbox = Bbox {
404            min_lon: -180.0,
405            min_lat: -85.0,
406            max_lon: 180.0,
407            max_lat: 85.0,
408        };
409        let mut count = 0u64;
410        let result = read_land_polygons(&path, Some(&bbox), |_| {
411            count += 1;
412        });
413        assert!(result.is_ok());
414        assert_eq!(count, 2);
415    }
416
417    /// The corners (1e6, 1e6) and (6e6, 6e6) m in EPSG:3857 come out in
418    /// degrees as PROJ gives them (`cs2cs EPSG:3857 EPSG:4326`).
419    #[test]
420    fn read_shapefile_emits_polygons_reprojected_as_proj_does() {
421        let dir = tempfile::tempdir().expect("tmp");
422        let path = write_tiny_shapefile(dir.path(), "land4");
423        let mut features = Vec::new();
424        read_land_polygons(&path, None, |f| features.push(f)).expect("read");
425        let has_vertex = |lon: f64, lat: f64| {
426            features.iter().any(|f| match f.geometry.as_ref() {
427                geo::Geometry::Polygon(p) => p
428                    .exterior()
429                    .0
430                    .iter()
431                    .any(|c| (c.x - lon).abs() < 1e-9 && (c.y - lat).abs() < 1e-9),
432                other => panic!("expected a polygon, got {other:?}"),
433            })
434        };
435        assert!(has_vertex(8.983_152_841_195, 8.946_573_850_543));
436        assert!(has_vertex(53.898_917_047_171, 47.353_704_702_433));
437    }
438}