Skip to main content

geolith_tiles_builder/layers/
water.rs

1//! Water layer — ocean, lakes, rivers.
2//!
3//! Processes features from multiple data sources:
4//! - **`WaterPolygons`** (z6+): Pre-processed ocean water polygons from shapefile
5//! - **`NaturalEarth`** (z0-5): `ne_50m_ocean`/`ne_50m_lakes` (z0-4),
6//!   `ne_10m_ocean`/`ne_10m_lakes` (z5)
7//! - **OSM**: 17+ water feature types (rivers, streams, canals, etc.)
8//! - **Overture**: `base/water` features with subtype mapping
9
10use geo::{Area, Centroid};
11use std::sync::Arc;
12
13use geolith::names::push_names;
14
15use crate::layers::Layer;
16use crate::source::input::{DataSource, InputFeature};
17use crate::tile::feature::PropValue;
18
19use super::buildings::ProcessedFeature;
20
21/// Process a feature into a water layer feature.
22///
23/// Routes to the appropriate handler based on data source.
24pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
25    match &feature.source {
26        DataSource::Overture { .. } => process_overture(feature),
27        DataSource::WaterPolygons => process_water_polygons(feature),
28        DataSource::NaturalEarth { .. } => process_ne(feature),
29        DataSource::Osm { .. } => process_osm(feature),
30        _ => None,
31    }
32}
33
34/// Compute area-based `min_zoom` for water polygon features.
35///
36/// Mirrors Planetiler's approach: polygon area determines the zoom level
37/// at which a water feature first appears. Larger water bodies show at
38/// lower zooms, smaller ones only at higher zooms.
39///
40/// Area is in WGS84 degrees² (approximate, varies by latitude).
41/// At mid-latitudes (~20°N): 1 deg² ≈ 10,000 km².
42#[must_use]
43fn area_based_min_zoom(geometry: &geo::Geometry<f64>, kind_floor: u8) -> u8 {
44    let area = match geometry {
45        geo::Geometry::Polygon(p) => p.unsigned_area(),
46        geo::Geometry::MultiPolygon(mp) => mp.unsigned_area(),
47        // Point/LineString water features (springs, waterfalls, swimming pools)
48        // should never appear at low zoom — clamp to at least z13.
49        _ => return kind_floor.max(13),
50    };
51
52    let zoom: u8 = if area > 0.1 {
53        3 // ~1000+ km² (Great Lakes)
54    } else if area > 0.01 {
55        5 // ~100+ km² (major reservoirs)
56    } else if area > 0.001 {
57        7 // ~10+ km² (significant lakes)
58    } else if area > 0.0001 {
59        9 // ~1+ km² (medium lakes)
60    } else if area > 0.00001 {
61        11 // ~0.1+ km² (small lakes, talav)
62    } else {
63        13 // tiny ponds
64    };
65
66    zoom.max(kind_floor)
67}
68
69/// Map an Overture water `class` or `subtype` value to (kind, `min_zoom`).
70fn water_kind(value: &str) -> Option<(&'static str, u8)> {
71    Some(match value {
72        "ocean" => ("ocean", 0u8),
73        "sea" => ("sea", 3),
74        "lake" => ("lake", 6),
75        "pond" => ("pond", 10),
76        "reservoir" => ("lake", 6),
77        "river" => ("river", 9),
78        "stream" => ("stream", 13),
79        "canal" => ("canal", 10),
80        "drain" => ("drain", 15),
81        "ditch" => ("ditch", 15),
82        "reef" => ("reef", 11),
83        "swimming_pool" => ("swimming_pool", 14),
84        "fountain" => ("fountain", 14),
85        "dock" => ("dock", 12),
86        "fjord" => ("fjord", 6),
87        "strait" => ("strait", 6),
88        "bay" => ("bay", 6),
89        "basin" => ("basin", 12),
90        "playa" => ("playa", 6),
91        "spring" => ("spring", 14),
92        "waterfall" => ("waterfall", 13),
93        "hot_spring" => ("spring", 14),
94        "water_well" => ("water", 15),
95        "fishpond" => ("pond", 10),
96        "oxbow" | "lagoon" => ("lake", 6),
97        "moat" => ("canal", 10),
98        _ => return None,
99    })
100}
101
102/// Process Overture `base/water` features.
103///
104/// Classified by `class` first, then `subtype`. Overture subtypes are broad
105/// (`canal` holds ditches and drains, `human_made` holds swimming pools,
106/// `physical` holds bays and waterfalls), so a subtype-only match drew
107/// 651k ditches as z10 canals and lost pools, bays, and waterfalls.
108fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
109    let (kind, base_min_zoom) = feature
110        .get_str("class")
111        .and_then(water_kind)
112        .or_else(|| feature.get_str("subtype").and_then(water_kind))
113        .unwrap_or(("water", 6));
114
115    // Adjust min_zoom based on polygon area for lake-type features.
116    // Small lakes/reservoirs get higher min_zoom so they only appear when
117    // zoomed in enough (mirrors Planetiler's area-based zoom assignment).
118    let min_zoom = match kind {
119        "lake" | "pond" | "basin" | "playa" | "water" => {
120            area_based_min_zoom(feature.geometry.as_ref(), base_min_zoom)
121        }
122        _ => base_min_zoom,
123    };
124
125    let mut properties = Vec::with_capacity(3);
126    properties.push(("kind".into(), PropValue::Str(kind.into())));
127
128    push_names(feature, &mut properties);
129
130    if let Some(detail) = feature.get_str("class") {
131        properties.push(("kind_detail".into(), PropValue::Str(detail.to_string())));
132    }
133
134    Some(ProcessedFeature {
135        id: feature.id,
136        geometry: feature.geometry.clone(),
137        layer: Layer::Water,
138        min_zoom,
139        max_zoom: 15,
140        sort_rank: 200,
141        properties,
142    })
143}
144
145/// Process pre-processed water polygons (z6+).
146///
147/// These are the `water-polygons-split-3857` polygons reprojected to WGS84.
148fn process_water_polygons(feature: &InputFeature) -> Option<ProcessedFeature> {
149    let properties = vec![("kind".into(), PropValue::Str("ocean".into()))];
150
151    Some(ProcessedFeature {
152        id: feature.id,
153        geometry: feature.geometry.clone(),
154        layer: Layer::Water,
155        min_zoom: 6,
156        max_zoom: 15,
157        sort_rank: 200,
158        properties,
159    })
160}
161
162/// Process Natural Earth ocean/lake features (z0-5).
163///
164/// - `ne_50m_ocean` / `ne_50m_lakes` → z0-4
165/// - `ne_10m_ocean` / `ne_10m_lakes` → z5
166fn process_ne(feature: &InputFeature) -> Option<ProcessedFeature> {
167    let source_layer = feature.ne_source_layer()?;
168
169    let (kind, min_zoom, max_zoom) = match source_layer {
170        "ne_50m_ocean" => ("ocean", 0u8, 4u8),
171        "ne_50m_lakes" => ("lake", 0, 4),
172        "ne_10m_ocean" => ("ocean", 5, 5),
173        "ne_10m_lakes" => ("lake", 5, 5),
174        _ => return None,
175    };
176
177    // Map NE featurecla to kind for lakes
178    let resolved_kind = if kind == "lake" {
179        match feature.get_str("featurecla") {
180            Some("Playa") => "playa",
181            Some("Reservoir") => "lake",
182            Some("Alkaline Lake") => "lake",
183            _ => "lake",
184        }
185    } else {
186        kind
187    };
188
189    let mut properties = Vec::with_capacity(2);
190    properties.push(("kind".into(), PropValue::Str(resolved_kind.into())));
191
192    push_names(feature, &mut properties);
193
194    Some(ProcessedFeature {
195        id: feature.id,
196        geometry: feature.geometry.clone(),
197        layer: Layer::Water,
198        min_zoom,
199        max_zoom,
200        sort_rank: 200,
201        properties,
202    })
203}
204
205/// Process OSM water features.
206///
207/// Handles 20+ water types including rivers, streams, canals, natural=water,
208/// springs, waterfalls, swimming pools, reservoirs, basins, and named polygon
209/// centroid labels.
210fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
211    // Check waterway tag first (linear features)
212    if let Some(waterway) = feature.get_str("waterway") {
213        return process_osm_waterway(feature, waterway);
214    }
215
216    // natural=water (polygon features)
217    if feature.has_tag("natural", "water") {
218        let water_type = feature.get_str("water").unwrap_or("");
219        let (kind, min_zoom) = match water_type {
220            "river" | "riverbank" => ("river", 9u8),
221            "lake" => ("lake", 6),
222            "reservoir" => ("lake", 6),
223            "pond" => ("pond", 10),
224            "basin" => ("basin", 12),
225            "canal" => ("canal", 10),
226            "stream" => ("stream", 13),
227            _ => ("water", 6),
228        };
229        return emit_water_feature(feature, kind, min_zoom, true);
230    }
231
232    // natural=spring (point features — water sources)
233    if feature.has_tag("natural", "spring") || feature.has_tag("natural", "hot_spring") {
234        return emit_water_feature(feature, "spring", 14, false);
235    }
236
237    // natural=waterfall
238    if feature.has_tag("natural", "waterfall") || feature.has_tag("waterway", "waterfall") {
239        return emit_water_feature(feature, "waterfall", 13, false);
240    }
241
242    // natural=reef
243    if feature.has_tag("natural", "reef") {
244        return emit_water_feature(feature, "reef", 11, false);
245    }
246
247    // leisure=swimming_pool
248    if feature.has_tag("leisure", "swimming_pool") {
249        return emit_water_feature(feature, "swimming_pool", 14, false);
250    }
251
252    // landuse=reservoir or landuse=basin
253    if feature.has_tag("landuse", "reservoir") {
254        return emit_water_feature(feature, "lake", 6, true);
255    }
256    if feature.has_tag("landuse", "basin") {
257        return emit_water_feature(feature, "basin", 12, false);
258    }
259
260    // natural=bay, natural=fjord, natural=strait
261    if feature.has_tag("natural", "bay") {
262        return emit_water_feature(feature, "bay", 6, true);
263    }
264    if feature.has_tag("natural", "fjord") {
265        return emit_water_feature(feature, "fjord", 6, true);
266    }
267    if feature.has_tag("natural", "strait") {
268        return emit_water_feature(feature, "strait", 6, true);
269    }
270
271    // amenity=fountain
272    if feature.has_tag("amenity", "fountain") {
273        return emit_water_feature(feature, "fountain", 14, false);
274    }
275
276    // waterway=dock or waterway=boatyard
277    if feature.has_tag("waterway", "dock") || feature.has_tag("waterway", "boatyard") {
278        return emit_water_feature(feature, "dock", 12, false);
279    }
280
281    // natural=sea
282    if feature.has_tag("natural", "sea") {
283        return emit_water_feature(feature, "sea", 3, true);
284    }
285
286    // place=ocean
287    if feature.has_tag("place", "ocean") {
288        return emit_water_feature(feature, "ocean", 0, true);
289    }
290
291    None
292}
293
294/// Process OSM waterway tags (linear features).
295fn process_osm_waterway(feature: &InputFeature, waterway: &str) -> Option<ProcessedFeature> {
296    let (kind, base_zoom) = match waterway {
297        "river" => ("river", 9u8),
298        "stream" => ("stream", 13),
299        "canal" => ("canal", 10),
300        "drain" => ("drain", 15),
301        "ditch" => ("ditch", 15),
302        "riverbank" => ("river", 6),
303        _ => return None,
304    };
305
306    // Lines get min_zoom = base + 1 per spec (except riverbank which is polygon)
307    let min_zoom = if feature.can_be_line() && !feature.can_be_polygon() {
308        base_zoom.saturating_add(1)
309    } else {
310        base_zoom
311    };
312
313    emit_water_feature(feature, kind, min_zoom, false)
314}
315
316/// Emit a water feature, optionally generating a centroid label
317/// for named polygons.
318fn emit_water_feature(
319    feature: &InputFeature,
320    kind: &str,
321    min_zoom: u8,
322    generate_label: bool,
323) -> Option<ProcessedFeature> {
324    let mut properties = Vec::with_capacity(3);
325
326    // For polygon lake-type features, adjust min_zoom based on area.
327    let min_zoom = match kind {
328        "lake" | "pond" | "basin" | "water" => {
329            area_based_min_zoom(feature.geometry.as_ref(), min_zoom)
330        }
331        _ => min_zoom,
332    };
333    properties.push(("kind".into(), PropValue::Str(kind.into())));
334
335    push_names(feature, &mut properties);
336
337    // For named polygon water features, generate centroid label instead
338    if generate_label && feature.has_key("name") && feature.can_be_polygon() {
339        let label_geom = match feature.geometry.as_ref() {
340            geo::Geometry::Polygon(p) => p.centroid().map(|c| Arc::new(geo::Geometry::Point(c))),
341            geo::Geometry::MultiPolygon(mp) => {
342                mp.centroid().map(|c| Arc::new(geo::Geometry::Point(c)))
343            }
344            _ => None,
345        };
346
347        if let Some(geom) = label_geom {
348            return Some(ProcessedFeature {
349                id: feature.id,
350                geometry: geom,
351                layer: Layer::Water,
352                min_zoom,
353                max_zoom: 15,
354                sort_rank: 200,
355                properties,
356            });
357        }
358    }
359
360    Some(ProcessedFeature {
361        id: feature.id,
362        geometry: feature.geometry.clone(),
363        layer: Layer::Water,
364        min_zoom,
365        max_zoom: 15,
366        sort_rank: 200,
367        properties,
368    })
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374    use crate::source::input::{DataSource, OsmElementType};
375    use std::collections::HashMap;
376
377    fn small_poly() -> Arc<geo::Geometry<f64>> {
378        Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
379            geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
380            vec![],
381        )))
382    }
383
384    fn big_poly() -> Arc<geo::Geometry<f64>> {
385        Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
386            geo::LineString::from(vec![
387                (0.0, 0.0),
388                (10.0, 0.0),
389                (10.0, 10.0),
390                (0.0, 10.0),
391                (0.0, 0.0),
392            ]),
393            vec![],
394        )))
395    }
396
397    fn tiny_poly() -> Arc<geo::Geometry<f64>> {
398        Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
399            geo::LineString::from(vec![(0.0, 0.0), (0.001, 0.0), (0.001, 0.001), (0.0, 0.0)]),
400            vec![],
401        )))
402    }
403
404    fn multipoly() -> Arc<geo::Geometry<f64>> {
405        Arc::new(geo::Geometry::MultiPolygon(geo::MultiPolygon(vec![
406            geo::Polygon::new(
407                geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
408                vec![],
409            ),
410        ])))
411    }
412
413    fn line() -> Arc<geo::Geometry<f64>> {
414        Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
415            (0.0, 0.0),
416            (1.0, 1.0),
417        ])))
418    }
419
420    fn point() -> Arc<geo::Geometry<f64>> {
421        Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0)))
422    }
423
424    fn make_with(
425        props: &[(&str, PropValue)],
426        geom: Arc<geo::Geometry<f64>>,
427        source: DataSource,
428    ) -> InputFeature {
429        let mut properties = HashMap::new();
430        for (k, v) in props {
431            properties.insert(k.to_string(), v.clone());
432        }
433        InputFeature {
434            id: 1,
435            geometry: geom,
436            properties,
437            bbox: None,
438            source,
439        }
440    }
441
442    fn make_feature(props: &[(&str, PropValue)]) -> InputFeature {
443        make_with(props, small_poly(), overture_src())
444    }
445
446    fn overture_src() -> DataSource {
447        DataSource::Overture {
448            theme: String::new(),
449            otype: String::new(),
450        }
451    }
452
453    fn osm_src() -> DataSource {
454        DataSource::Osm {
455            element_type: OsmElementType::Way,
456            relations: vec![],
457        }
458    }
459
460    fn ne_src(layer: &str) -> DataSource {
461        DataSource::NaturalEarth {
462            source_layer: layer.to_string(),
463        }
464    }
465
466    fn has_kind(feat: &ProcessedFeature, k: &str) -> bool {
467        feat.properties
468            .iter()
469            .any(|(key, v)| key == "kind" && *v == PropValue::Str(k.into()))
470    }
471
472    #[test]
473    fn ocean_z0() {
474        let feat = make_feature(&[("subtype", PropValue::Str("ocean".into()))]);
475        let r = process(&feat).unwrap();
476        assert_eq!(r.layer, Layer::Water);
477        assert_eq!(r.min_zoom, 0);
478        assert!(has_kind(&r, "ocean"));
479    }
480
481    #[test]
482    fn lake_z6() {
483        let feat = make_feature(&[("subtype", PropValue::Str("lake".into()))]);
484        assert_eq!(process(&feat).unwrap().min_zoom, 6);
485    }
486
487    #[test]
488    fn river_z9() {
489        let feat = make_feature(&[("subtype", PropValue::Str("river".into()))]);
490        let r = process(&feat).unwrap();
491        assert_eq!(r.min_zoom, 9);
492        assert!(has_kind(&r, "river"));
493    }
494
495    #[test]
496    fn stream_z13() {
497        let feat = make_feature(&[("subtype", PropValue::Str("stream".into()))]);
498        assert_eq!(process(&feat).unwrap().min_zoom, 13);
499    }
500
501    #[test]
502    fn default_water_z6() {
503        let feat = make_feature(&[]);
504        let r = process(&feat).unwrap();
505        assert_eq!(r.min_zoom, 6);
506        assert_eq!(r.sort_rank, 200);
507    }
508
509    #[test]
510    fn overture_all_subtypes() {
511        let cases = [
512            ("sea", 3u8),
513            ("pond", 10),
514            ("reservoir", 6),
515            ("canal", 10),
516            ("drain", 15),
517            ("ditch", 15),
518            ("reef", 11),
519            ("swimming_pool", 14),
520            ("fountain", 14),
521            ("dock", 12),
522            ("fjord", 6),
523            ("strait", 6),
524            ("bay", 6),
525            ("playa", 6),
526            ("spring", 14),
527            ("waterfall", 13),
528            ("hot_spring", 14),
529            ("water_well", 15),
530        ];
531        for (sub, _expected_min) in cases {
532            let feat = make_feature(&[("subtype", PropValue::Str(sub.into()))]);
533            let r = process(&feat).unwrap();
534            assert!(r.min_zoom >= 3 || sub == "ocean");
535        }
536    }
537
538    #[test]
539    fn overture_basin_uses_area() {
540        let feat = make_with(
541            &[("subtype", PropValue::Str("basin".into()))],
542            tiny_poly(),
543            overture_src(),
544        );
545        let r = process(&feat).unwrap();
546        assert!(r.min_zoom >= 12);
547    }
548
549    #[test]
550    fn overture_with_name_and_class() {
551        let feat = make_feature(&[
552            ("subtype", PropValue::Str("lake".into())),
553            ("names.primary", PropValue::Str("Tahoe".into())),
554            ("class", PropValue::Str("alpine".into())),
555        ]);
556        let r = process(&feat).unwrap();
557        assert!(
558            r.properties
559                .iter()
560                .any(|(k, v)| k == "name" && *v == PropValue::Str("Tahoe".into()))
561        );
562        assert!(
563            r.properties
564                .iter()
565                .any(|(k, v)| k == "kind_detail" && *v == PropValue::Str("alpine".into()))
566        );
567    }
568
569    #[test]
570    fn overture_falls_back_to_name_property() {
571        let feat = make_feature(&[
572            ("subtype", PropValue::Str("river".into())),
573            ("name", PropValue::Str("Nile".into())),
574        ]);
575        let r = process(&feat).unwrap();
576        assert!(
577            r.properties
578                .iter()
579                .any(|(k, v)| k == "name" && *v == PropValue::Str("Nile".into()))
580        );
581    }
582
583    /// (subtype, class) pairs from the 2026-08-19.0 release: the class, not
584    /// the broad subtype, decides the kind.
585    #[test]
586    fn overture_class_decides_over_subtype() {
587        let cases = [
588            ("canal", "ditch", "ditch", 15),
589            ("canal", "drain", "drain", 15),
590            ("canal", "moat", "canal", 10),
591            ("human_made", "swimming_pool", "swimming_pool", 14),
592            ("physical", "waterfall", "waterfall", 13),
593            ("spring", "hot_spring", "spring", 14),
594        ];
595        for (subtype, class, kind, zoom) in cases {
596            let feat = make_with(
597                &[
598                    ("subtype", PropValue::Str(subtype.into())),
599                    ("class", PropValue::Str(class.into())),
600                ],
601                Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
602                    (0.0, 0.0),
603                    (1.0, 1.0),
604                ]))),
605                overture_src(),
606            );
607            let r = process(&feat).unwrap();
608            assert!(has_kind(&r, kind), "{subtype}/{class}");
609            assert_eq!(r.min_zoom, zoom, "{subtype}/{class}");
610        }
611    }
612
613    #[test]
614    fn overture_bay_and_lagoon_classes() {
615        for (subtype, class, kind) in [
616            ("physical", "bay", "bay"),
617            ("lake", "lagoon", "lake"),
618            ("pond", "fishpond", "pond"),
619        ] {
620            let feat = make_feature(&[
621                ("subtype", PropValue::Str(subtype.into())),
622                ("class", PropValue::Str(class.into())),
623            ]);
624            assert!(
625                has_kind(&process(&feat).unwrap(), kind),
626                "{subtype}/{class}"
627            );
628        }
629    }
630
631    #[test]
632    fn overture_unknown_subtype() {
633        let feat = make_feature(&[("subtype", PropValue::Str("mystery".into()))]);
634        let r = process(&feat).unwrap();
635        assert!(has_kind(&r, "water"));
636    }
637
638    #[test]
639    fn water_polygons_z6() {
640        let feat = make_with(&[], small_poly(), DataSource::WaterPolygons);
641        let r = process(&feat).unwrap();
642        assert_eq!(r.min_zoom, 6);
643        assert!(has_kind(&r, "ocean"));
644    }
645
646    #[test]
647    fn ne_50m_ocean() {
648        let feat = make_with(&[], small_poly(), ne_src("ne_50m_ocean"));
649        let r = process(&feat).unwrap();
650        assert_eq!(r.min_zoom, 0);
651        assert_eq!(r.max_zoom, 4);
652        assert!(has_kind(&r, "ocean"));
653    }
654
655    #[test]
656    fn ne_50m_lakes() {
657        let feat = make_with(&[], small_poly(), ne_src("ne_50m_lakes"));
658        let r = process(&feat).unwrap();
659        assert_eq!(r.min_zoom, 0);
660        assert!(has_kind(&r, "lake"));
661    }
662
663    #[test]
664    fn ne_10m_ocean_z5() {
665        let feat = make_with(&[], small_poly(), ne_src("ne_10m_ocean"));
666        let r = process(&feat).unwrap();
667        assert_eq!(r.min_zoom, 5);
668        assert_eq!(r.max_zoom, 5);
669    }
670
671    #[test]
672    fn ne_10m_lakes_z5() {
673        let feat = make_with(&[], small_poly(), ne_src("ne_10m_lakes"));
674        assert_eq!(process(&feat).unwrap().min_zoom, 5);
675    }
676
677    #[test]
678    fn ne_lake_featurecla_playa() {
679        let feat = make_with(
680            &[("featurecla", PropValue::Str("Playa".into()))],
681            small_poly(),
682            ne_src("ne_50m_lakes"),
683        );
684        let r = process(&feat).unwrap();
685        assert!(has_kind(&r, "playa"));
686    }
687
688    #[test]
689    fn ne_lake_featurecla_reservoir() {
690        let feat = make_with(
691            &[("featurecla", PropValue::Str("Reservoir".into()))],
692            small_poly(),
693            ne_src("ne_50m_lakes"),
694        );
695        let r = process(&feat).unwrap();
696        assert!(has_kind(&r, "lake"));
697    }
698
699    #[test]
700    fn ne_lake_featurecla_alkaline() {
701        let feat = make_with(
702            &[("featurecla", PropValue::Str("Alkaline Lake".into()))],
703            small_poly(),
704            ne_src("ne_50m_lakes"),
705        );
706        assert!(has_kind(&process(&feat).unwrap(), "lake"));
707    }
708
709    fn has(r: &ProcessedFeature, key: &str, value: &str) -> bool {
710        r.properties
711            .iter()
712            .any(|(k, v)| k == key && *v == PropValue::Str(value.into()))
713    }
714
715    #[test]
716    fn ne_lake_maps_name_columns_to_language_attributes() {
717        let feat = make_with(
718            &[
719                ("name", PropValue::Str("Ladoga".into())),
720                ("name_en", PropValue::Str("Lake Ladoga".into())),
721                ("name_ru", PropValue::Str("Ладожское озеро".into())),
722                ("name_zh", PropValue::Str("拉多加湖".into())),
723            ],
724            small_poly(),
725            ne_src("ne_50m_lakes"),
726        );
727        let r = process(&feat).unwrap();
728        assert!(has(&r, "name:en", "Lake Ladoga"));
729        assert!(has(&r, "name:ru", "Ладожское озеро"));
730        assert!(has(&r, "name:zh-Hans", "拉多加湖"));
731    }
732
733    #[test]
734    fn osm_lake_label_carries_script_and_name_en() {
735        let feat = make_with(
736            &[
737                ("natural", PropValue::Str("water".into())),
738                ("water", PropValue::Str("lake".into())),
739                ("name", PropValue::Str("شالمار متل".into())),
740                ("name:en", PropValue::Str("Dal Lake".into())),
741            ],
742            small_poly(),
743            osm_src(),
744        );
745        let r = process(&feat).unwrap();
746        assert!(has(&r, "script", "Arabic"));
747        assert!(has(&r, "name:en", "Dal Lake"));
748    }
749
750    #[test]
751    fn ne_with_name() {
752        let feat = make_with(
753            &[("name", PropValue::Str("Lake X".into()))],
754            small_poly(),
755            ne_src("ne_50m_lakes"),
756        );
757        let r = process(&feat).unwrap();
758        assert!(
759            r.properties
760                .iter()
761                .any(|(k, v)| k == "name" && *v == PropValue::Str("Lake X".into()))
762        );
763    }
764
765    #[test]
766    fn ne_unknown_layer() {
767        let feat = make_with(&[], small_poly(), ne_src("ne_50m_admin"));
768        assert!(process(&feat).is_none());
769    }
770
771    #[test]
772    fn osm_waterway_river_line_bumps_zoom() {
773        let feat = make_with(
774            &[("waterway", PropValue::Str("river".into()))],
775            line(),
776            osm_src(),
777        );
778        let r = process(&feat).unwrap();
779        assert_eq!(r.min_zoom, 10);
780        assert!(has_kind(&r, "river"));
781    }
782
783    #[test]
784    fn osm_waterway_stream() {
785        let feat = make_with(
786            &[("waterway", PropValue::Str("stream".into()))],
787            line(),
788            osm_src(),
789        );
790        assert_eq!(process(&feat).unwrap().min_zoom, 14);
791    }
792
793    #[test]
794    fn osm_waterway_canal() {
795        let feat = make_with(
796            &[("waterway", PropValue::Str("canal".into()))],
797            line(),
798            osm_src(),
799        );
800        let r = process(&feat).unwrap();
801        assert_eq!(r.min_zoom, 11);
802        assert!(has_kind(&r, "canal"));
803    }
804
805    #[test]
806    fn osm_waterway_drain() {
807        let feat = make_with(
808            &[("waterway", PropValue::Str("drain".into()))],
809            line(),
810            osm_src(),
811        );
812        let r = process(&feat).unwrap();
813        assert!(r.min_zoom >= 15);
814        assert!(has_kind(&r, "drain"));
815    }
816
817    #[test]
818    fn osm_waterway_ditch() {
819        let feat = make_with(
820            &[("waterway", PropValue::Str("ditch".into()))],
821            line(),
822            osm_src(),
823        );
824        assert!(has_kind(&process(&feat).unwrap(), "ditch"));
825    }
826
827    #[test]
828    fn osm_waterway_riverbank_polygon() {
829        let feat = make_with(
830            &[("waterway", PropValue::Str("riverbank".into()))],
831            small_poly(),
832            osm_src(),
833        );
834        let r = process(&feat).unwrap();
835        assert_eq!(r.min_zoom, 6);
836        assert!(has_kind(&r, "river"));
837    }
838
839    #[test]
840    fn osm_waterway_unknown() {
841        let feat = make_with(
842            &[("waterway", PropValue::Str("unknown".into()))],
843            line(),
844            osm_src(),
845        );
846        assert!(process(&feat).is_none());
847    }
848
849    #[test]
850    fn osm_natural_water_default() {
851        let feat = make_with(
852            &[("natural", PropValue::Str("water".into()))],
853            small_poly(),
854            osm_src(),
855        );
856        let r = process(&feat).unwrap();
857        assert!(has_kind(&r, "water"));
858    }
859
860    #[test]
861    fn osm_natural_water_river() {
862        let feat = make_with(
863            &[
864                ("natural", PropValue::Str("water".into())),
865                ("water", PropValue::Str("river".into())),
866            ],
867            small_poly(),
868            osm_src(),
869        );
870        let r = process(&feat).unwrap();
871        assert!(has_kind(&r, "river"));
872        assert_eq!(r.min_zoom, 9);
873    }
874
875    #[test]
876    fn osm_natural_water_lake_with_name_emits_label() {
877        let feat = make_with(
878            &[
879                ("natural", PropValue::Str("water".into())),
880                ("water", PropValue::Str("lake".into())),
881                ("name", PropValue::Str("L".into())),
882            ],
883            small_poly(),
884            osm_src(),
885        );
886        let r = process(&feat).unwrap();
887        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Point(_)));
888    }
889
890    #[test]
891    fn osm_natural_water_lake_multipolygon_label() {
892        let feat = make_with(
893            &[
894                ("natural", PropValue::Str("water".into())),
895                ("water", PropValue::Str("lake".into())),
896                ("name", PropValue::Str("L".into())),
897            ],
898            multipoly(),
899            osm_src(),
900        );
901        let r = process(&feat).unwrap();
902        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Point(_)));
903    }
904
905    #[test]
906    fn osm_natural_water_lake_no_name_keeps_polygon() {
907        let feat = make_with(
908            &[
909                ("natural", PropValue::Str("water".into())),
910                ("water", PropValue::Str("lake".into())),
911            ],
912            small_poly(),
913            osm_src(),
914        );
915        let r = process(&feat).unwrap();
916        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Polygon(_)));
917    }
918
919    #[test]
920    fn osm_natural_water_kinds() {
921        for (water, kind) in [
922            ("riverbank", "river"),
923            ("reservoir", "lake"),
924            ("pond", "pond"),
925            ("basin", "basin"),
926            ("canal", "canal"),
927            ("stream", "stream"),
928        ] {
929            let feat = make_with(
930                &[
931                    ("natural", PropValue::Str("water".into())),
932                    ("water", PropValue::Str(water.into())),
933                ],
934                small_poly(),
935                osm_src(),
936            );
937            assert!(has_kind(&process(&feat).unwrap(), kind), "{water}");
938        }
939    }
940
941    #[test]
942    fn osm_spring() {
943        let feat = make_with(
944            &[("natural", PropValue::Str("spring".into()))],
945            point(),
946            osm_src(),
947        );
948        let r = process(&feat).unwrap();
949        assert!(has_kind(&r, "spring"));
950        assert_eq!(r.min_zoom, 14);
951    }
952
953    #[test]
954    fn osm_hot_spring() {
955        let feat = make_with(
956            &[("natural", PropValue::Str("hot_spring".into()))],
957            point(),
958            osm_src(),
959        );
960        assert!(has_kind(&process(&feat).unwrap(), "spring"));
961    }
962
963    #[test]
964    fn osm_natural_waterfall() {
965        let feat = make_with(
966            &[("natural", PropValue::Str("waterfall".into()))],
967            point(),
968            osm_src(),
969        );
970        let r = process(&feat).unwrap();
971        assert_eq!(r.min_zoom, 13);
972        assert!(has_kind(&r, "waterfall"));
973    }
974
975    #[test]
976    fn osm_reef() {
977        let feat = make_with(
978            &[("natural", PropValue::Str("reef".into()))],
979            small_poly(),
980            osm_src(),
981        );
982        assert!(has_kind(&process(&feat).unwrap(), "reef"));
983    }
984
985    #[test]
986    fn osm_swimming_pool() {
987        let feat = make_with(
988            &[("leisure", PropValue::Str("swimming_pool".into()))],
989            small_poly(),
990            osm_src(),
991        );
992        let r = process(&feat).unwrap();
993        assert_eq!(r.min_zoom, 14);
994        assert!(has_kind(&r, "swimming_pool"));
995    }
996
997    #[test]
998    fn osm_landuse_reservoir_emits_lake_label() {
999        let feat = make_with(
1000            &[
1001                ("landuse", PropValue::Str("reservoir".into())),
1002                ("name", PropValue::Str("R".into())),
1003            ],
1004            small_poly(),
1005            osm_src(),
1006        );
1007        let r = process(&feat).unwrap();
1008        assert!(has_kind(&r, "lake"));
1009        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Point(_)));
1010    }
1011
1012    #[test]
1013    fn osm_landuse_basin() {
1014        let feat = make_with(
1015            &[("landuse", PropValue::Str("basin".into()))],
1016            small_poly(),
1017            osm_src(),
1018        );
1019        let r = process(&feat).unwrap();
1020        assert!(has_kind(&r, "basin"));
1021    }
1022
1023    #[test]
1024    fn osm_natural_bay_fjord_strait() {
1025        for nat in ["bay", "fjord", "strait"] {
1026            let feat = make_with(
1027                &[("natural", PropValue::Str(nat.into()))],
1028                small_poly(),
1029                osm_src(),
1030            );
1031            assert!(has_kind(&process(&feat).unwrap(), nat));
1032        }
1033    }
1034
1035    #[test]
1036    fn osm_amenity_fountain() {
1037        let feat = make_with(
1038            &[("amenity", PropValue::Str("fountain".into()))],
1039            point(),
1040            osm_src(),
1041        );
1042        assert!(has_kind(&process(&feat).unwrap(), "fountain"));
1043    }
1044
1045    #[test]
1046    fn osm_natural_sea() {
1047        let feat = make_with(
1048            &[("natural", PropValue::Str("sea".into()))],
1049            small_poly(),
1050            osm_src(),
1051        );
1052        let r = process(&feat).unwrap();
1053        assert_eq!(r.min_zoom, 3);
1054        assert!(has_kind(&r, "sea"));
1055    }
1056
1057    #[test]
1058    fn osm_place_ocean() {
1059        let feat = make_with(
1060            &[("place", PropValue::Str("ocean".into()))],
1061            small_poly(),
1062            osm_src(),
1063        );
1064        let r = process(&feat).unwrap();
1065        assert_eq!(r.min_zoom, 0);
1066        assert!(has_kind(&r, "ocean"));
1067    }
1068
1069    #[test]
1070    fn osm_unrelated_returns_none() {
1071        let feat = make_with(
1072            &[("highway", PropValue::Str("primary".into()))],
1073            line(),
1074            osm_src(),
1075        );
1076        assert!(process(&feat).is_none());
1077    }
1078
1079    #[test]
1080    fn other_source_returns_none() {
1081        let feat = make_with(&[], small_poly(), DataSource::IndiaBoundary);
1082        assert!(process(&feat).is_none());
1083        let feat = make_with(&[], small_poly(), DataSource::LandPolygons);
1084        assert!(process(&feat).is_none());
1085    }
1086
1087    #[test]
1088    fn area_zoom_huge_polygon() {
1089        let g = big_poly();
1090        assert_eq!(area_based_min_zoom(g.as_ref(), 0), 3);
1091    }
1092
1093    #[test]
1094    fn area_zoom_multipolygon() {
1095        let g = multipoly();
1096        let z = area_based_min_zoom(g.as_ref(), 0);
1097        assert!(z >= 3);
1098    }
1099
1100    #[test]
1101    fn area_zoom_point_clamps_to_13() {
1102        let g = point();
1103        assert_eq!(area_based_min_zoom(g.as_ref(), 0), 13);
1104        assert_eq!(area_based_min_zoom(g.as_ref(), 14), 14);
1105    }
1106
1107    #[test]
1108    fn area_zoom_respects_floor() {
1109        let g = big_poly();
1110        assert_eq!(area_based_min_zoom(g.as_ref(), 8), 8);
1111    }
1112
1113    #[test]
1114    fn area_zoom_tiers() {
1115        // Build polygons with specific areas to hit each tier.
1116        let mk = |side: f64| {
1117            geo::Geometry::Polygon(geo::Polygon::new(
1118                geo::LineString::from(vec![
1119                    (0.0, 0.0),
1120                    (side, 0.0),
1121                    (side, side),
1122                    (0.0, side),
1123                    (0.0, 0.0),
1124                ]),
1125                vec![],
1126            ))
1127        };
1128        // area > 0.01: side ≈ 0.2 → area = 0.04
1129        assert_eq!(area_based_min_zoom(&mk(0.2), 0), 5);
1130        // area > 0.001: side ≈ 0.05 → area = 0.0025
1131        assert_eq!(area_based_min_zoom(&mk(0.05), 0), 7);
1132        // area > 0.0001: side ≈ 0.015 → area ≈ 0.000225
1133        assert_eq!(area_based_min_zoom(&mk(0.015), 0), 9);
1134        // area > 0.00001: side ≈ 0.005 → area ≈ 0.000025
1135        assert_eq!(area_based_min_zoom(&mk(0.005), 0), 11);
1136        // tiny: side = 0.001 → area = 0.000001
1137        assert_eq!(area_based_min_zoom(&mk(0.001), 0), 13);
1138    }
1139}