Skip to main content

geolith_tiles_builder/layers/
buildings.rs

1//! Buildings layer — building footprints from Overture.
2//!
3//! Maps Overture `buildings/building` and `buildings/building_part` to the
4//! protomaps `buildings` layer with `kind`, `height`, and zoom-dependent
5//! height quantization.
6
7use crate::layers::Layer;
8use crate::source::input::{DataSource, InputFeature};
9use crate::tile::feature::PropValue;
10use std::sync::Arc;
11
12/// Result of processing a single Overture feature into a layer feature.
13#[derive(Debug, Clone)]
14pub struct ProcessedFeature {
15    /// Source feature ID.
16    pub id: u64,
17    /// Source geometry (WGS84, not yet projected).
18    pub geometry: Arc<geo::Geometry<f64>>,
19    /// Target output layer.
20    pub layer: Layer,
21    /// Minimum zoom level to include this feature.
22    pub min_zoom: u8,
23    /// Maximum zoom level for this feature.
24    pub max_zoom: u8,
25    /// Sort rank within the layer (lower = drawn first).
26    pub sort_rank: i32,
27    /// Output MVT properties.
28    pub properties: Vec<(String, PropValue)>,
29}
30
31/// Process a feature into a buildings layer feature.
32///
33/// Routes to the appropriate handler based on data source.
34/// May return two features for OSM buildings with addresses (building + address point).
35pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
36    match &feature.source {
37        DataSource::Overture { .. } => process_overture(feature),
38        DataSource::Osm { .. } => process_osm(feature),
39        _ => None,
40    }
41}
42
43/// Process a feature and return all generated features (may include address point).
44pub fn process_all(feature: &InputFeature) -> Vec<ProcessedFeature> {
45    let mut results = Vec::with_capacity(2);
46
47    if let Some(building) = process(feature) {
48        results.push(building);
49    }
50
51    // OSM buildings with addr:housenumber get a separate address point at z15
52    if matches!(&feature.source, DataSource::Osm { .. })
53        && let Some(addr) = extract_address(feature)
54    {
55        results.push(addr);
56    }
57
58    results
59}
60
61/// Process Overture building features.
62fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
63    let overture_otype = feature.overture_otype().unwrap_or("");
64    let kind = match overture_otype {
65        "building_part" => "building_part",
66        _ => "building",
67    };
68
69    let min_zoom = if kind == "building_part" { 14 } else { 11 };
70
71    let height = feature.get_f64("height");
72    let num_floors = feature.get_f64("num_floors");
73    let effective_height = height.or_else(|| num_floors.map(|f| f * 3.0));
74
75    let mut properties = Vec::with_capacity(4);
76    properties.push(("kind".into(), PropValue::Str(kind.into())));
77
78    if let Some(h) = effective_height {
79        properties.push(("height".into(), PropValue::F64(h)));
80    }
81
82    Some(ProcessedFeature {
83        id: feature.id,
84        geometry: feature.geometry.clone(),
85        layer: Layer::Buildings,
86        min_zoom,
87        max_zoom: 15,
88        sort_rank: 400,
89        properties,
90    })
91}
92
93/// Process OSM building/building:part features.
94///
95/// Height parsing sanitizes comma decimals (`"89,1"` → `"89.1"`)
96/// and strips `" m"` suffix. If no height, estimates from levels:
97/// `height = max(levels, 1) * 3 + 2`.
98fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
99    let has_building = feature.has_key("building");
100    let has_building_part = feature.has_key("building:part");
101
102    if !has_building && !has_building_part {
103        return None;
104    }
105
106    let (kind, min_zoom) = if has_building_part {
107        ("building_part", 14u8)
108    } else {
109        ("building", 11)
110    };
111
112    let effective_height = parse_osm_height(feature);
113
114    let mut properties = Vec::with_capacity(4);
115    properties.push(("kind".into(), PropValue::Str(kind.into())));
116
117    if let Some(h) = effective_height {
118        properties.push(("height".into(), PropValue::F64(h)));
119    }
120
121    if let Some(name) = feature.get_str("name") {
122        properties.push(("name".into(), PropValue::Str(name.to_string())));
123    }
124
125    Some(ProcessedFeature {
126        id: feature.id,
127        geometry: feature.geometry.clone(),
128        layer: Layer::Buildings,
129        min_zoom,
130        max_zoom: 15,
131        sort_rank: 400,
132        properties,
133    })
134}
135
136/// Parse OSM height from tags with sanitization.
137///
138/// Tries `height` tag first (sanitizing comma decimals and " m" suffix),
139/// then falls back to `building:levels` estimation.
140fn parse_osm_height(feature: &InputFeature) -> Option<f64> {
141    if let Some(height_str) = feature.get_str("height") {
142        let sanitized = height_str
143            .replace(',', ".")
144            .trim_end_matches(" m")
145            .trim()
146            .to_string();
147        if let Ok(h) = sanitized.parse::<f64>()
148            && h > 0.0
149        {
150            return Some(h);
151        }
152    }
153
154    if let Some(levels_str) = feature.get_str("building:levels")
155        && let Ok(levels) = levels_str.parse::<f64>()
156    {
157        let effective_levels = levels.max(1.0);
158        return Some(effective_levels * 3.0 + 2.0);
159    }
160
161    // Direct numeric properties
162    feature.get_f64("height").or_else(|| {
163        feature
164            .get_f64("building:levels")
165            .map(|l| l.max(1.0) * 3.0 + 2.0)
166    })
167}
168
169/// Extract an address point feature from an OSM building with `addr:housenumber`.
170fn extract_address(feature: &InputFeature) -> Option<ProcessedFeature> {
171    let housenumber = feature.get_str("addr:housenumber")?;
172
173    let centroid = match feature.geometry.as_ref() {
174        geo::Geometry::Polygon(p) => {
175            use geo::Centroid;
176            p.centroid().map(|c| Arc::new(geo::Geometry::Point(c)))
177        }
178        geo::Geometry::MultiPolygon(mp) => {
179            use geo::Centroid;
180            mp.centroid().map(|c| Arc::new(geo::Geometry::Point(c)))
181        }
182        geo::Geometry::Point(_) => Some(feature.geometry.clone()),
183        _ => None,
184    }?;
185
186    let mut properties = Vec::with_capacity(4);
187    properties.push(("kind".into(), PropValue::Str("address".into())));
188    properties.push((
189        "addr_housenumber".into(),
190        PropValue::Str(housenumber.to_string()),
191    ));
192
193    if let Some(street) = feature.get_str("addr:street") {
194        properties.push(("addr_street".into(), PropValue::Str(street.to_string())));
195    }
196
197    Some(ProcessedFeature {
198        id: feature.id,
199        geometry: centroid,
200        layer: Layer::Buildings,
201        min_zoom: 15,
202        max_zoom: 15,
203        sort_rank: 401,
204        properties,
205    })
206}
207
208/// Quantize building height by zoom level.
209///
210/// Reduces tile size by rounding heights at lower zooms where precision
211/// doesn't matter visually.
212#[must_use]
213pub fn quantize_height(height: f64, zoom: u8) -> f64 {
214    match zoom {
215        0..=12 => (height / 20.0).round() * 20.0,
216        13 => (height / 10.0).round() * 10.0,
217        14 => (height / 5.0).round() * 5.0,
218        _ => height,
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use crate::source::input::{DataSource, OsmElementType};
226    use std::collections::HashMap;
227
228    fn make_feature(otype: &str, props: &[(&str, PropValue)]) -> InputFeature {
229        let mut properties = HashMap::new();
230        for (k, v) in props {
231            properties.insert(k.to_string(), v.clone());
232        }
233        InputFeature {
234            id: 1,
235            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(7.42, 43.73))),
236            properties,
237            bbox: None,
238            source: DataSource::Overture {
239                theme: "buildings".into(),
240                otype: otype.into(),
241            },
242        }
243    }
244
245    fn make_osm(props: &[(&str, PropValue)]) -> InputFeature {
246        let mut properties = HashMap::new();
247        for (k, v) in props {
248            properties.insert(k.to_string(), v.clone());
249        }
250        InputFeature {
251            id: 42,
252            geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
253                geo::LineString::from(vec![
254                    (0.0, 0.0),
255                    (0.0, 1.0),
256                    (1.0, 1.0),
257                    (1.0, 0.0),
258                    (0.0, 0.0),
259                ]),
260                vec![],
261            ))),
262            properties,
263            bbox: None,
264            source: DataSource::Osm {
265                element_type: OsmElementType::Way,
266                relations: Vec::new(),
267            },
268        }
269    }
270
271    fn has_prop(p: &[(String, PropValue)], key: &str, val: &PropValue) -> bool {
272        p.iter().any(|(k, v)| k == key && v == val)
273    }
274
275    fn get_prop<'a>(p: &'a [(String, PropValue)], key: &str) -> Option<&'a PropValue> {
276        p.iter().find(|(k, _)| k == key).map(|(_, v)| v)
277    }
278
279    #[test]
280    fn building_has_correct_kind_and_zoom() {
281        // An unknown Overture type falls back to a plain building.
282        for otype in ["building", "something_else"] {
283            let feat = make_feature(otype, &[]);
284            let result = process(&feat).expect(otype);
285            assert_eq!(result.layer, Layer::Buildings, "{otype}");
286            assert_eq!(result.min_zoom, 11, "{otype}");
287            assert_eq!(result.sort_rank, 400, "{otype}");
288            assert!(
289                has_prop(
290                    &result.properties,
291                    "kind",
292                    &PropValue::Str("building".into())
293                ),
294                "{otype}"
295            );
296        }
297    }
298
299    #[test]
300    fn building_part_starts_at_zoom_14() {
301        let feat = make_feature("building_part", &[]);
302        let result = process(&feat).unwrap();
303        assert_eq!(result.min_zoom, 14);
304        assert!(has_prop(
305            &result.properties,
306            "kind",
307            &PropValue::Str("building_part".into())
308        ));
309    }
310
311    #[test]
312    fn height_from_direct_attribute() {
313        let feat = make_feature("building", &[("height", PropValue::F64(25.0))]);
314        let result = process(&feat).unwrap();
315        assert_eq!(
316            get_prop(&result.properties, "height"),
317            Some(&PropValue::F64(25.0))
318        );
319    }
320
321    #[test]
322    fn height_estimated_from_floors() {
323        let feat = make_feature("building", &[("num_floors", PropValue::F64(5.0))]);
324        let result = process(&feat).unwrap();
325        assert_eq!(
326            get_prop(&result.properties, "height"),
327            Some(&PropValue::F64(15.0))
328        );
329    }
330
331    #[test]
332    fn direct_height_preferred_over_floors() {
333        let feat = make_feature(
334            "building",
335            &[
336                ("height", PropValue::F64(30.0)),
337                ("num_floors", PropValue::F64(5.0)),
338            ],
339        );
340        let result = process(&feat).unwrap();
341        assert_eq!(
342            get_prop(&result.properties, "height"),
343            Some(&PropValue::F64(30.0))
344        );
345    }
346
347    #[test]
348    fn height_quantization() {
349        assert_eq!(quantize_height(17.0, 12), 20.0);
350        assert_eq!(quantize_height(17.0, 13), 20.0);
351        assert_eq!(quantize_height(17.0, 14), 15.0);
352        assert_eq!(quantize_height(17.0, 15), 17.0);
353    }
354
355    #[test]
356    fn quantize_low_zoom_levels() {
357        assert_eq!(quantize_height(50.0, 0), 60.0);
358        assert_eq!(quantize_height(10.0, 5), 20.0);
359        assert_eq!(quantize_height(9.0, 12), 0.0);
360    }
361
362    #[test]
363    fn unsupported_source_returns_none() {
364        let mut feat = make_feature("building", &[]);
365        feat.source = DataSource::LandPolygons;
366        assert!(process(&feat).is_none());
367        assert!(process_all(&feat).is_empty());
368    }
369
370    #[test]
371    fn overture_no_height_emits_no_height_prop() {
372        let feat = make_feature("building", &[]);
373        let result = process(&feat).unwrap();
374        assert!(get_prop(&result.properties, "height").is_none());
375    }
376
377    #[test]
378    fn osm_without_building_tag_returns_none() {
379        let feat = make_osm(&[("name", PropValue::Str("foo".into()))]);
380        assert!(process(&feat).is_none());
381    }
382
383    #[test]
384    fn osm_with_building_tag() {
385        let feat = make_osm(&[("building", PropValue::Str("yes".into()))]);
386        let r = process(&feat).unwrap();
387        assert_eq!(r.layer, Layer::Buildings);
388        assert_eq!(r.min_zoom, 11);
389        assert_eq!(r.max_zoom, 15);
390        assert_eq!(r.sort_rank, 400);
391        assert!(has_prop(
392            &r.properties,
393            "kind",
394            &PropValue::Str("building".into())
395        ));
396    }
397
398    #[test]
399    fn osm_with_building_part_tag() {
400        let feat = make_osm(&[("building:part", PropValue::Str("yes".into()))]);
401        let r = process(&feat).unwrap();
402        assert_eq!(r.min_zoom, 14);
403        assert!(has_prop(
404            &r.properties,
405            "kind",
406            &PropValue::Str("building_part".into())
407        ));
408    }
409
410    #[test]
411    fn osm_includes_name_when_present() {
412        let feat = make_osm(&[
413            ("building", PropValue::Str("residential".into())),
414            ("name", PropValue::Str("Empire State".into())),
415        ]);
416        let r = process(&feat).unwrap();
417        assert!(has_prop(
418            &r.properties,
419            "name",
420            &PropValue::Str("Empire State".into())
421        ));
422    }
423
424    #[test]
425    fn osm_omits_name_when_missing() {
426        let feat = make_osm(&[("building", PropValue::Str("yes".into()))]);
427        let r = process(&feat).unwrap();
428        assert!(get_prop(&r.properties, "name").is_none());
429    }
430
431    /// OSM `height` and `building:levels` resolve to metres: a parseable
432    /// positive height wins ("m" suffix and decimal comma allowed), else
433    /// levels at 3 m each plus 2 m (zero levels count as one), else none.
434    #[test]
435    fn osm_height_and_levels_resolve_to_metres() {
436        let s = |v: &str| PropValue::Str(v.into());
437        type Case = (&'static str, Vec<(&'static str, PropValue)>, Option<f64>);
438        let cases: [Case; 13] = [
439            ("plain number", vec![("height", s("12.5"))], Some(12.5)),
440            ("metre suffix", vec![("height", s("33 m"))], Some(33.0)),
441            ("decimal comma", vec![("height", s("89,1"))], Some(89.1)),
442            (
443                "comma and suffix",
444                vec![("height", s("12,5 m"))],
445                Some(12.5),
446            ),
447            (
448                "numeric height",
449                vec![("height", PropValue::F64(42.0))],
450                Some(42.0),
451            ),
452            (
453                "unparseable height",
454                vec![("height", s("abc")), ("building:levels", s("4"))],
455                Some(14.0),
456            ),
457            (
458                "empty height",
459                vec![("height", s("")), ("building:levels", s("2"))],
460                Some(8.0),
461            ),
462            (
463                "zero height",
464                vec![("height", s("0")), ("building:levels", s("3"))],
465                Some(11.0),
466            ),
467            ("negative height", vec![("height", s("-5"))], None),
468            ("zero levels", vec![("building:levels", s("0"))], Some(5.0)),
469            (
470                "numeric levels",
471                vec![("building:levels", PropValue::F64(5.0))],
472                Some(17.0),
473            ),
474            (
475                "unparseable levels",
476                vec![("building:levels", s("many"))],
477                None,
478            ),
479            ("neither", vec![], None),
480        ];
481        for (case, tags, expected) in cases {
482            let mut all = vec![("building", s("yes"))];
483            all.extend(tags);
484            let r = process(&make_osm(&all)).expect(case);
485            assert_eq!(
486                get_prop(&r.properties, "height"),
487                expected.map(PropValue::F64).as_ref(),
488                "{case}"
489            );
490        }
491    }
492
493    #[test]
494    fn osm_with_housenumber_emits_address_point() {
495        let feat = make_osm(&[
496            ("building", PropValue::Str("yes".into())),
497            ("addr:housenumber", PropValue::Str("221B".into())),
498            ("addr:street", PropValue::Str("Baker St".into())),
499        ]);
500        let results = process_all(&feat);
501        assert_eq!(results.len(), 2);
502        let addr = &results[1];
503        assert_eq!(addr.min_zoom, 15);
504        assert_eq!(addr.max_zoom, 15);
505        assert_eq!(addr.sort_rank, 401);
506        assert!(has_prop(
507            &addr.properties,
508            "kind",
509            &PropValue::Str("address".into())
510        ));
511        assert!(has_prop(
512            &addr.properties,
513            "addr_housenumber",
514            &PropValue::Str("221B".into())
515        ));
516        assert!(has_prop(
517            &addr.properties,
518            "addr_street",
519            &PropValue::Str("Baker St".into())
520        ));
521        assert!(matches!(addr.geometry.as_ref(), geo::Geometry::Point(_)));
522    }
523
524    #[test]
525    fn osm_address_omits_street_when_missing() {
526        let feat = make_osm(&[
527            ("building", PropValue::Str("yes".into())),
528            ("addr:housenumber", PropValue::Str("10".into())),
529        ]);
530        let results = process_all(&feat);
531        assert_eq!(results.len(), 2);
532        let address = results
533            .iter()
534            .find(|r| matches!(r.geometry.as_ref(), geo::Geometry::Point(_)))
535            .expect("the address point is emitted");
536        assert!(has_prop(
537            &address.properties,
538            "addr_housenumber",
539            &PropValue::Str("10".into())
540        ));
541        assert!(get_prop(&address.properties, "addr_street").is_none());
542    }
543
544    #[test]
545    fn osm_address_from_multipolygon() {
546        let mut feat = make_osm(&[
547            ("building", PropValue::Str("yes".into())),
548            ("addr:housenumber", PropValue::Str("5".into())),
549        ]);
550        let poly = geo::Polygon::new(
551            geo::LineString::from(vec![
552                (0.0, 0.0),
553                (0.0, 2.0),
554                (2.0, 2.0),
555                (2.0, 0.0),
556                (0.0, 0.0),
557            ]),
558            vec![],
559        );
560        feat.geometry = Arc::new(geo::Geometry::MultiPolygon(geo::MultiPolygon(vec![poly])));
561        let results = process_all(&feat);
562        assert_eq!(results.len(), 2);
563        assert!(matches!(
564            results[1].geometry.as_ref(),
565            geo::Geometry::Point(_)
566        ));
567    }
568
569    #[test]
570    fn osm_address_from_point_geometry() {
571        let mut feat = make_osm(&[
572            ("building", PropValue::Str("yes".into())),
573            ("addr:housenumber", PropValue::Str("7".into())),
574        ]);
575        feat.geometry = Arc::new(geo::Geometry::Point(geo::Point::new(1.0, 2.0)));
576        let results = process_all(&feat);
577        assert_eq!(results.len(), 2);
578        assert!(matches!(
579            results[1].geometry.as_ref(),
580            geo::Geometry::Point(_)
581        ));
582    }
583
584    #[test]
585    fn osm_address_unsupported_geometry_no_address() {
586        let mut feat = make_osm(&[
587            ("building", PropValue::Str("yes".into())),
588            ("addr:housenumber", PropValue::Str("9".into())),
589        ]);
590        feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
591            (0.0, 0.0),
592            (1.0, 1.0),
593        ])));
594        assert_eq!(process_all(&feat).len(), 1, "a line gets no address point");
595        let untagged = make_osm(&[("building", PropValue::Str("yes".into()))]);
596        assert_eq!(
597            process_all(&untagged).len(),
598            1,
599            "no housenumber, no address point"
600        );
601    }
602
603    #[test]
604    fn overture_with_addr_housenumber_does_not_emit_address() {
605        // Overture addresses come from the addresses theme, so a building
606        // is one feature with or without a housenumber.
607        let tagged = [("addr:housenumber", PropValue::Str("1".into()))];
608        for props in [&tagged[..], &[]] {
609            let results = process_all(&make_feature("building", props));
610            assert_eq!(results.len(), 1, "{props:?}");
611        }
612    }
613}