Skip to main content

mln_style/feature/
tile_feature.rs

1use std::borrow::Cow;
2use std::ops::{Deref, DerefMut, Range};
3use std::sync::Arc;
4
5use crate::error::Error;
6use crate::feature::{Identifier, PropertyMap, Value, ValueRef};
7use crate::geometry::{FeatureType, Point};
8
9/// Normalized vector tile coordinates. Each geometry coordinate represents a
10/// point in a bidimensional space, varying from -V...0...+V, where V is the
11/// maximum extent applicable.
12pub type GeometryCoordinate = Point<i16>;
13
14pub type GeometryCoordinates = Vec<GeometryCoordinate>;
15
16/// The rings or lines of a feature's geometry, with the triangles of a
17/// pre-tessellated polygon.
18///
19/// `Clone` keeps the triangles. `==` compares only the rings: the triangles
20/// are a tessellation of them.
21#[derive(Clone, Debug, Default)]
22pub struct GeometryCollection {
23    rings: Vec<GeometryCoordinates>,
24    /// The pre-tessellated triangles of an MLT polygon feature: the tile's
25    /// shared index buffer and the range of this feature's triangles in it.
26    triangles: Option<(Arc<[u32]>, Range<usize>)>,
27}
28
29impl GeometryCollection {
30    #[must_use]
31    pub const fn new() -> Self {
32        GeometryCollection { rings: Vec::new(), triangles: None }
33    }
34
35    /// The triangles of a pre-tessellated polygon: three indices per
36    /// triangle into the vertices of the rings, numbered from 0 across the
37    /// rings in order. Empty unless the tile carried triangles. Nothing
38    /// checks that the indices are in range.
39    #[must_use]
40    pub fn triangles(&self) -> &[u32] {
41        match &self.triangles {
42            Some((owner, range)) => &owner[range.clone()],
43            None => &[],
44        }
45    }
46
47    /// Sets the triangles to `owner[range]`. Panics if `range` is out of
48    /// bounds.
49    pub fn set_triangles(&mut self, owner: Arc<[u32]>, range: Range<usize>) {
50        assert!(range.start <= range.end && range.end <= owner.len());
51        self.triangles = Some((owner, range));
52    }
53}
54
55impl PartialEq for GeometryCollection {
56    fn eq(&self, other: &Self) -> bool {
57        self.rings == other.rings
58    }
59}
60
61impl From<Vec<GeometryCoordinates>> for GeometryCollection {
62    fn from(rings: Vec<GeometryCoordinates>) -> Self {
63        GeometryCollection { rings, triangles: None }
64    }
65}
66
67impl Deref for GeometryCollection {
68    type Target = Vec<GeometryCoordinates>;
69    fn deref(&self) -> &Self::Target {
70        &self.rings
71    }
72}
73
74impl DerefMut for GeometryCollection {
75    fn deref_mut(&mut self) -> &mut Self::Target {
76        &mut self.rings
77    }
78}
79
80static EMPTY_PROPERTIES: PropertyMap = PropertyMap::new();
81static EMPTY_GEOMETRIES: GeometryCollection = GeometryCollection::new();
82
83/// A feature as expressions and buckets read it: a view of a tile's
84/// feature (`mln_engine::tile::Feature`), or a feature made for evaluating an
85/// expression. Reading a value never fails: a reader whose data can be
86/// malformed checks it when it makes the view.
87pub trait GeometryTileFeature {
88    fn feature_type(&self) -> FeatureType;
89
90    /// The value of the property `key`, borrowed from the feature; `None`
91    /// for none or a null value.
92    fn value_ref(&self, key: &str) -> Option<ValueRef<'_>>;
93
94    /// [`value_ref`](Self::value_ref), owned.
95    fn value(&self, key: &str) -> Option<Value> {
96        self.value_ref(key).map(Value::from)
97    }
98
99    /// The feature's properties; empty by default. A view that decodes its
100    /// properties on demand returns them owned.
101    fn properties(&self) -> Cow<'_, PropertyMap> {
102        Cow::Borrowed(&EMPTY_PROPERTIES)
103    }
104
105    /// The feature's id; [`Identifier::Null`] by default.
106    fn id(&self) -> Identifier {
107        Identifier::Null
108    }
109
110    /// The feature's geometries; empty by default. A view that decodes its
111    /// geometry on demand returns it owned, and fails for a geometry it
112    /// can't decode.
113    fn geometries(&self) -> Result<Cow<'_, GeometryCollection>, Error> {
114        Ok(Cow::Borrowed(&EMPTY_GEOMETRIES))
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    struct Feature;
123
124    impl GeometryTileFeature for Feature {
125        fn feature_type(&self) -> FeatureType {
126            FeatureType::Point
127        }
128        fn value_ref(&self, _key: &str) -> Option<ValueRef<'_>> {
129            None
130        }
131    }
132
133    #[test]
134    fn a_feature_has_no_properties_id_or_geometry_by_default() {
135        assert!(Feature.properties().is_empty());
136        assert_eq!(Feature.id(), Identifier::Null);
137        assert!(Feature.geometries().unwrap().is_empty());
138    }
139
140    /// Triangles are a slice of their owner, which clones keep and equality
141    /// ignores.
142    #[test]
143    fn triangles_are_the_owner_s_range() {
144        let mut c = GeometryCollection::from(vec![vec![Point::new(0, 0), Point::new(1, 0), Point::new(0, 1)]]);
145        assert_eq!(c.triangles(), <&[u32]>::default());
146        let owner: Arc<[u32]> = Arc::from(vec![9, 9, 0, 1, 2, 9]);
147        c.set_triangles(owner, 2..5);
148        assert_eq!(c.triangles(), &[0, 1, 2]);
149        assert_eq!(c.clone().triangles(), &[0, 1, 2]);
150        assert_eq!(c, GeometryCollection::from(c.to_vec()));
151    }
152}