Skip to main content

mln_engine/tile/
mvt.rs

1// Tiles are read with fast-mvt's lazy reader: a layer is decoded when it is
2// asked for and a feature when it is read, and tags and geometry are read
3// from the tile's bytes.
4//
5// Errors: a tile whose layers can't be found, or a layer that fast-mvt can't
6// decode, fails `MvtTile::layer`; a feature it can't decode, or whose tags
7// are malformed, fails `MvtLayer::feature`, so reading a value afterwards
8// can't fail; a malformed geometry fails `MvtFeature::geometry`.
9
10#[cfg(test)]
11use std::collections::BTreeSet;
12use std::ops::Range;
13use std::sync::{Arc, OnceLock};
14
15use fast_mvt::{MvtLazyFeature, MvtLazyLayer, MvtLazyReader, MvtResult, MvtValueRef};
16use feature::{Identifier, PropertyMap, Value};
17use geometry::Point;
18use mln_style::constants::EXTENT;
19use mln_style::feature::GeometryCollection;
20use mln_style::geometry::FeatureType;
21use mln_style::hash::HashMap;
22
23use crate::tile::TileError;
24use crate::tile::geometry_tile_data::fixup_polygons;
25use crate::tile::tile_data::FeatureGroups;
26
27/// The MVT geometry types, as fast-mvt reads a feature's type.
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29#[repr(i32)]
30enum MvtGeometryType {
31    Point = 1,
32    LineString = 2,
33    Polygon = 3,
34}
35
36impl MvtGeometryType {
37    fn from_i32(value: i32) -> Option<Self> {
38        match value {
39            1 => Some(MvtGeometryType::Point),
40            2 => Some(MvtGeometryType::LineString),
41            3 => Some(MvtGeometryType::Polygon),
42            _ => None,
43        }
44    }
45}
46
47/// A layer of the tile: its name and its message, as ranges of the tile's
48/// bytes.
49struct LayerEntry {
50    name: Range<usize>,
51    data: Range<usize>,
52}
53
54struct MvtData {
55    bytes: Arc<Vec<u8>>,
56    /// The tile's layers in tile order, found on the first lookup.
57    layers: OnceLock<Vec<LayerEntry>>,
58}
59
60/// Mapbox Vector Tile data. Cloning shares the bytes and the layers found in
61/// them.
62#[derive(Clone)]
63pub struct MvtTile(Arc<MvtData>);
64
65impl MvtTile {
66    #[must_use]
67    pub fn new(bytes: Arc<Vec<u8>>) -> Self {
68        MvtTile(Arc::new(MvtData { bytes, layers: OnceLock::new() }))
69    }
70
71    /// The tile's bytes.
72    #[must_use]
73    pub fn bytes(&self) -> &Arc<Vec<u8>> {
74        &self.0.bytes
75    }
76
77    /// The tile's layers. Only a successful search is kept: a tile that
78    /// fails is searched again next time.
79    fn layers(&self) -> Result<&[LayerEntry], TileError> {
80        if let Some(layers) = self.0.layers.get() {
81            return Ok(layers);
82        }
83        let bytes = &self.0.bytes;
84        let range = |slice: &[u8]| {
85            let start = slice.as_ptr() as usize - bytes.as_ptr() as usize;
86            start..start + slice.len()
87        };
88        let layers = MvtLazyReader::new(bytes)?
89            .layers()
90            .map(|layer| LayerEntry { name: range(layer.name().as_bytes()), data: range(layer.data()) })
91            .collect();
92        Ok(self.0.layers.get_or_init(|| layers))
93    }
94
95    fn find(&self, name: &str) -> Result<Option<&LayerEntry>, TileError> {
96        let bytes = &self.0.bytes;
97        Ok(self.layers()?.iter().find(|entry| bytes.get(entry.name.clone()) == Some(name.as_bytes())))
98    }
99
100    /// The first layer named `name`, decoded; `None` if there is none.
101    pub(crate) fn layer(&self, name: &str) -> Result<Option<MvtLayer<'_>>, TileError> {
102        let Some(data) = self.find(name)?.and_then(|entry| self.0.bytes.get(entry.data.clone())) else {
103            return Ok(None);
104        };
105        Ok(Some(MvtLayer { layer: MvtLazyLayer::decode(data)? }))
106    }
107
108    /// Whether the tile has a layer named `name`, found without decoding it.
109    pub(crate) fn has_layer(&self, name: &str) -> Result<bool, TileError> {
110        Ok(self.find(name)?.is_some())
111    }
112
113    /// The names of the tile's layers, each once, in byte order.
114    #[cfg(test)]
115    pub(crate) fn layer_names(&self) -> Result<Vec<String>, TileError> {
116        let bytes = &self.0.bytes;
117        let names: BTreeSet<&[u8]> = self.layers()?.iter().filter_map(|entry| bytes.get(entry.name.clone())).collect();
118        Ok(names.into_iter().map(|name| String::from_utf8_lossy(name).into_owned()).collect())
119    }
120}
121
122/// A layer of an [`MvtTile`], decoded.
123pub struct MvtLayer<'a> {
124    layer: MvtLazyLayer<'a>,
125}
126
127impl MvtLayer<'_> {
128    pub(crate) fn name(&self) -> &str {
129        self.layer.name()
130    }
131
132    pub(crate) fn extent(&self) -> u32 {
133        self.layer.extent()
134    }
135
136    pub(crate) fn len(&self) -> usize {
137        self.layer.feature_count()
138    }
139
140    /// The feature at `i`, with its tags checked. Fails with
141    /// [`TileError::OutOfRange`] past the end, and with fast-mvt's error for
142    /// a feature it can't decode or a malformed tag.
143    pub(crate) fn feature(&self, i: usize) -> Result<MvtFeature<'_>, TileError> {
144        let feature = match self.layer.feature(i) {
145            Some(feature) => feature?,
146            None => return Err(TileError::vector_range_check(i, self.layer.feature_count())),
147        };
148        for property in feature.properties() {
149            property?;
150        }
151        Ok(MvtFeature { layer: &self.layer, feature })
152    }
153
154    /// Groups by geometry type and by the value-table index of each key's
155    /// first tag, as `get_value` reads it: equal indices are equal values.
156    /// Equal values at distinct indices only split a group. `None` for a
157    /// malformed feature, leaving its error to `feature`.
158    pub(crate) fn group_features(&self, keys: &[String]) -> Option<FeatureGroups> {
159        /// A key the feature has no tag for.
160        const ABSENT: u32 = u32::MAX;
161        let count = self.layer.feature_count();
162        // Grouping costs about as much as evaluating each feature once.
163        let limit = count / 4 + 8;
164        let value_count = self.layer.values().len();
165        let slots: Vec<Option<usize>> =
166            (self.layer.keys().iter()).map(|key| keys.iter().position(|k| k == key)).collect();
167        let mut index: HashMap<Box<[u32]>, u32> = HashMap::default();
168        let mut codes = vec![ABSENT; keys.len() + 1];
169        let mut groups = FeatureGroups { of_feature: Vec::with_capacity(count), first: Vec::new() };
170        for (i, feature) in self.layer.features().enumerate() {
171            let feature = feature.ok()?;
172            codes.fill(ABSENT);
173            codes[keys.len()] = feature.geom_type_value().unwrap_or(0) as u32;
174            let mut tags = feature.tags();
175            while let Some(key) = tags.next() {
176                let (key, value) = (key.ok()?, tags.next()?.ok()?);
177                let slot = *slots.get(key as usize)?;
178                if value as usize >= value_count {
179                    return None;
180                }
181                if let Some(slot) = slot
182                    && codes[slot] == ABSENT
183                {
184                    codes[slot] = value;
185                }
186            }
187            let group = if let Some(&group) = index.get(codes.as_slice()) {
188                group
189            } else {
190                if groups.first.len() == limit {
191                    return None;
192                }
193                let group = groups.first.len() as u32;
194                index.insert(codes.as_slice().into(), group);
195                groups.first.push(i);
196                group
197            };
198            groups.of_feature.push(group);
199        }
200        Some(groups)
201    }
202}
203
204/// A feature of an [`MvtLayer`], whose tags are known to be well formed.
205pub struct MvtFeature<'a> {
206    layer: &'a MvtLazyLayer<'a>,
207    feature: MvtLazyFeature<'a, 'a>,
208}
209
210impl MvtFeature<'_> {
211    /// The tags; [`MvtLayer::feature`] checked them.
212    fn properties(&self) -> impl Iterator<Item = (&str, MvtValueRef<'_>)> {
213        self.feature.properties().map_while(Result::ok)
214    }
215
216    pub(crate) fn get_type(&self) -> FeatureType {
217        match self.feature.geom_type_value().and_then(MvtGeometryType::from_i32) {
218            Some(MvtGeometryType::Point) => FeatureType::Point,
219            Some(MvtGeometryType::LineString) => FeatureType::LineString,
220            Some(MvtGeometryType::Polygon) => FeatureType::Polygon,
221            None => FeatureType::Unknown,
222        }
223    }
224
225    pub(crate) fn get_id(&self) -> Identifier {
226        self.feature.id().map_or(Identifier::Null, Identifier::Uint)
227    }
228
229    /// The value of the first tag whose key is `key`; `None` for none or a
230    /// null value.
231    pub(crate) fn get_value(&self, key: &str) -> Option<Value> {
232        let (_, value) = self.properties().find(|&(tag_key, _)| tag_key == key)?;
233        match value {
234            MvtValueRef::Null => None,
235            value => Some(to_value(value)),
236        }
237    }
238
239    /// Every property. A repeated key keeps its first value. The tags are
240    /// sorted by key before they are copied, so that the map is built by
241    /// appending and a repeated key is copied once.
242    pub(crate) fn get_properties(&self) -> PropertyMap {
243        // A feature seldom has a key twice: room for one tag per key.
244        let mut tags = Vec::with_capacity(self.layer.keys().len());
245        tags.extend(self.properties());
246        // Stable, so the first of a repeated key stays first and is kept.
247        tags.sort_by_key(|&(key, _)| key);
248        tags.dedup_by(|(a, _), (b, _)| a == b);
249        tags.into_iter().map(|(key, value)| (key.to_owned(), to_value(value))).collect()
250    }
251
252    /// The geometry, scaled to `util::EXTENT`. Version 1 polygons go
253    /// through [`fixup_polygons`].
254    pub(crate) fn geometry(&self) -> Result<GeometryCollection, TileError> {
255        let scale = EXTENT as f32 / self.layer.extent() as f32;
256        let lines = GeometryCollection::from(
257            decode_geometry(self.feature.geometry_commands(), scale).map_err(TileError::Geometry)?,
258        );
259        Ok(
260            if self.layer.version() < 2
261                && self.feature.geom_type_value().and_then(MvtGeometryType::from_i32) == Some(MvtGeometryType::Polygon)
262            {
263                fixup_polygons(&lines)
264            } else {
265                lines
266            },
267        )
268    }
269}
270
271fn to_value(value: MvtValueRef<'_>) -> Value {
272    match value {
273        MvtValueRef::String(value) => Value::String(value.to_owned()),
274        MvtValueRef::Float(value) => Value::Double(f64::from(value)),
275        MvtValueRef::Double(value) => Value::Double(value),
276        MvtValueRef::Int(value) | MvtValueRef::SInt(value) => Value::Int(value),
277        MvtValueRef::UInt(value) => Value::Uint(value),
278        MvtValueRef::Bool(value) => Value::Bool(value),
279        MvtValueRef::Null => Value::Null,
280    }
281}
282
283/// Decodes a feature's geometry commands into rings, scaling each
284/// coordinate by `scale` and rounding it, as `mapbox::vector_tile`'s
285/// `feature::getGeometries` does. A `MoveTo` starts a new ring (each point
286/// of a multipoint is a ring of its own), a `ClosePath` repeats the ring's
287/// first point, and no commands give one empty ring. The errors are C++'s
288/// `std::runtime_error` texts, or fast-mvt's for malformed commands.
289fn decode_geometry(
290    mut commands: impl Iterator<Item = MvtResult<u32>>,
291    scale: f32,
292) -> Result<Vec<Vec<Point<i16>>>, String> {
293    #[derive(Clone, Copy, PartialEq, Eq)]
294    #[repr(u32)]
295    enum MvtCommand {
296        MoveTo = 1,
297        LineTo = 2,
298        ClosePath = 7,
299    }
300
301    impl MvtCommand {
302        fn from_u32(value: u32) -> Option<Self> {
303            match value {
304                1 => Some(MvtCommand::MoveTo),
305                2 => Some(MvtCommand::LineTo),
306                7 => Some(MvtCommand::ClosePath),
307                _ => None,
308            }
309        }
310    }
311
312    /// The most points a command reserves room for: its count comes from
313    /// the tile, unchecked (C++ caps it the same way).
314    const MAX_RESERVE: usize = 1024 * 1024 / 16;
315
316    let mut next = || commands.next().transpose().map_err(|e| e.to_string());
317    let (min, max) = (f32::from(i16::MIN), f32::from(i16::MAX));
318    let mut rings = Vec::new();
319    let mut ring: Vec<Point<i16>> = Vec::new();
320    let (mut x, mut y) = (0i64, 0i64);
321    while let Some(command) = next()? {
322        let count = (command >> 3) as usize;
323        match MvtCommand::from_u32(command & 0x7) {
324            Some(id @ (MvtCommand::MoveTo | MvtCommand::LineTo)) => {
325                if id == MvtCommand::LineTo {
326                    // Room for the ClosePath of a polygon ring.
327                    ring.reserve(count.min(MAX_RESERVE) + 1);
328                }
329                for _ in 0..count {
330                    let (Some(dx), Some(dy)) = (next()?, next()?) else {
331                        return Err("geometry command parameters past the end".to_owned());
332                    };
333                    if id == MvtCommand::MoveTo && !ring.is_empty() {
334                        rings.push(std::mem::take(&mut ring));
335                    }
336                    x = x.wrapping_add(i64::from(zigzag(dx)));
337                    y = y.wrapping_add(i64::from(zigzag(dy)));
338                    let px = (x as f32 * scale).round();
339                    let py = (y as f32 * scale).round();
340                    if px > max || px < min || py > max || py < min {
341                        return Err("paths outside valid range of coordinate_type".to_owned());
342                    }
343                    // A NaN scale passes the range check and becomes 0.
344                    ring.push(Point::new(px as i16, py as i16));
345                }
346            }
347            Some(MvtCommand::ClosePath) => {
348                if let Some(&first) = ring.first() {
349                    ring.push(first);
350                }
351            }
352            None => return Err("unknown command".to_owned()),
353        }
354    }
355    rings.push(ring);
356    Ok(rings)
357}
358
359fn zigzag(value: u32) -> i32 {
360    (value >> 1) as i32 ^ -((value & 1) as i32)
361}
362
363#[cfg(test)]
364mod tests {
365    use geometry::Point;
366
367    use super::decode_geometry;
368
369    fn rings(commands: &[u32], scale: f32) -> Vec<Vec<(i16, i16)>> {
370        let rings = decode_geometry(commands.iter().copied().map(Ok), scale).unwrap();
371        rings.iter().map(|ring| ring.iter().map(|p: &Point<i16>| (p.x, p.y)).collect()).collect()
372    }
373
374    #[test]
375    fn decodes_rings() {
376        // No commands: one empty ring.
377        assert_eq!(rings(&[], 1.0), vec![vec![]]);
378        // MoveTo(2): each point is a ring.
379        assert_eq!(rings(&[17, 2, 4, 2, 2], 1.0), vec![vec![(1, 2)], vec![(2, 3)]]);
380        // MoveTo, LineTo(2), MoveTo, LineTo(1): two lines.
381        assert_eq!(
382            rings(&[9, 0, 0, 18, 2, 0, 0, 2, 9, 2, 2, 10, 1, 1], 1.0),
383            vec![vec![(0, 0), (1, 0), (1, 1)], vec![(2, 2), (1, 1)]]
384        );
385        // ClosePath repeats the first point; the scale rounds.
386        assert_eq!(rings(&[9, 2, 2, 18, 2, 0, 0, 2, 15], 2.5), vec![vec![(3, 3), (5, 3), (5, 5), (3, 3)]]);
387    }
388
389    #[test]
390    fn rejects_malformed_commands() {
391        let error = |commands: &[u32], scale| decode_geometry(commands.iter().copied().map(Ok), scale).unwrap_err();
392        assert_eq!(error(&[3], 1.0), "unknown command");
393        assert_eq!(error(&[17, 2, 4, 2], 1.0), "geometry command parameters past the end");
394        assert_eq!(error(&[9, 2, 0], 40000.0), "paths outside valid range of coordinate_type");
395    }
396}