Skip to main content

basemapper_core/vector/
mvt.rs

1//! Mapbox Vector Tile (MVT 2.1) decoding.
2//!
3//! Decodes the protobuf with `prost` and expands geometry commands into tile-
4//! space coordinates (0..extent, y down). Polygons are grouped into
5//! exterior-ring-plus-holes using ring winding, as the spec requires.
6
7use prost::Message;
8use std::collections::HashMap;
9
10// ── Protobuf schema (vector_tile.proto, MVT 2.1) ─────────────────────────────
11
12#[derive(Clone, PartialEq, Message)]
13pub(crate) struct PbTile {
14    #[prost(message, repeated, tag = "3")]
15    pub(crate) layers: Vec<PbLayer>,
16}
17
18#[derive(Clone, PartialEq, Message)]
19pub(crate) struct PbLayer {
20    #[prost(uint32, required, tag = "15")]
21    pub(crate) version: u32,
22    #[prost(string, required, tag = "1")]
23    pub(crate) name: String,
24    #[prost(message, repeated, tag = "2")]
25    pub(crate) features: Vec<PbFeature>,
26    #[prost(string, repeated, tag = "3")]
27    pub(crate) keys: Vec<String>,
28    #[prost(message, repeated, tag = "4")]
29    pub(crate) values: Vec<PbValue>,
30    #[prost(uint32, optional, tag = "5")]
31    pub(crate) extent: Option<u32>,
32}
33
34#[derive(Clone, PartialEq, Message)]
35pub(crate) struct PbFeature {
36    #[prost(uint64, optional, tag = "1")]
37    pub(crate) id: Option<u64>,
38    #[prost(uint32, repeated, tag = "2")]
39    pub(crate) tags: Vec<u32>,
40    #[prost(int32, optional, tag = "3")]
41    pub(crate) r#type: Option<i32>,
42    #[prost(uint32, repeated, tag = "4")]
43    pub(crate) geometry: Vec<u32>,
44}
45
46#[derive(Clone, PartialEq, Message)]
47pub(crate) struct PbValue {
48    #[prost(string, optional, tag = "1")]
49    pub(crate) string_value: Option<String>,
50    #[prost(float, optional, tag = "2")]
51    pub(crate) float_value: Option<f32>,
52    #[prost(double, optional, tag = "3")]
53    pub(crate) double_value: Option<f64>,
54    #[prost(int64, optional, tag = "4")]
55    pub(crate) int_value: Option<i64>,
56    #[prost(uint64, optional, tag = "5")]
57    pub(crate) uint_value: Option<u64>,
58    #[prost(sint64, optional, tag = "6")]
59    pub(crate) sint_value: Option<i64>,
60    #[prost(bool, optional, tag = "7")]
61    pub(crate) bool_value: Option<bool>,
62}
63
64/// Layer name of GeoJSON source tiles (MapLibre's GeoJSONWrapper).
65pub const GEOJSON_LAYER: &str = "_geojsonTileLayer";
66
67/// The tile layer a style layer reads: its `source-layer`, or the GeoJSON
68/// tile layer when it has none (`layer.sourceLayer || '_geojsonTileLayer'`).
69pub fn source_layer(layer: &serde_json::Value) -> &str {
70    layer["source-layer"].as_str().unwrap_or(GEOJSON_LAYER)
71}
72
73// ── Decoded model ────────────────────────────────────────────────────────────
74
75/// A feature property value.
76#[derive(Clone, Debug, PartialEq)]
77pub enum Value {
78    String(String),
79    Number(f64),
80    Bool(bool),
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum GeomType {
85    Point,
86    LineString,
87    Polygon,
88}
89
90/// Tile-space point (0..extent, y down).
91pub type Point = (f32, f32);
92
93#[derive(Clone, Debug)]
94pub enum Geometry {
95    /// One or more points.
96    Points(Vec<Point>),
97    /// One or more line strings.
98    Lines(Vec<Vec<Point>>),
99    /// Polygons, each an exterior ring followed by its holes.
100    Polygons(Vec<Vec<Vec<Point>>>),
101}
102
103#[derive(Clone, Debug)]
104pub struct Feature {
105    pub id: Option<u64>,
106    pub geom_type: GeomType,
107    pub properties: HashMap<String, Value>,
108    pub geometry: Geometry,
109}
110
111#[derive(Clone, Debug)]
112pub struct Layer {
113    pub name: String,
114    pub extent: u32,
115    pub features: Vec<Feature>,
116}
117
118#[derive(Clone, Debug, Default)]
119pub struct Tile {
120    pub layers: HashMap<String, Layer>,
121}
122
123/// Decode an MVT. Gzip-compressed input is accepted.
124pub fn decode(bytes: &[u8]) -> Result<Tile, String> {
125    let raw;
126    let data = if bytes.starts_with(&[0x1f, 0x8b]) {
127        use std::io::Read;
128        let mut out = Vec::new();
129        flate2::read::GzDecoder::new(bytes)
130            .read_to_end(&mut out)
131            .map_err(|e| format!("gzip: {e}"))?;
132        raw = out;
133        &raw[..]
134    } else {
135        bytes
136    };
137
138    let pb = PbTile::decode(data).map_err(|e| format!("protobuf: {e}"))?;
139    let mut tile = Tile::default();
140    for l in pb.layers {
141        let values: Vec<Value> = l.values.iter().map(convert_value).collect();
142        let mut features = Vec::with_capacity(l.features.len());
143        for f in &l.features {
144            let geom_type = match f.r#type.unwrap_or(0) {
145                1 => GeomType::Point,
146                2 => GeomType::LineString,
147                3 => GeomType::Polygon,
148                _ => continue, // UNKNOWN geometry: skip, as MapLibre does
149            };
150            let mut properties = HashMap::with_capacity(f.tags.len() / 2);
151            for kv in f.tags.chunks_exact(2) {
152                if let (Some(k), Some(v)) = (l.keys.get(kv[0] as usize), values.get(kv[1] as usize)) {
153                    properties.insert(k.clone(), v.clone());
154                }
155            }
156            let rings = decode_commands(&f.geometry);
157            let geometry = match geom_type {
158                GeomType::Point => Geometry::Points(rings.into_iter().flatten().collect()),
159                GeomType::LineString => Geometry::Lines(rings),
160                GeomType::Polygon => Geometry::Polygons(classify_rings(rings)),
161            };
162            features.push(Feature { id: f.id, geom_type, properties, geometry });
163        }
164        tile.layers.insert(
165            l.name.clone(),
166            Layer { name: l.name, extent: l.extent.unwrap_or(4096), features },
167        );
168    }
169    Ok(tile)
170}
171
172fn convert_value(v: &PbValue) -> Value {
173    if let Some(s) = &v.string_value {
174        Value::String(s.clone())
175    } else if let Some(x) = v.float_value {
176        Value::Number(x as f64)
177    } else if let Some(x) = v.double_value {
178        Value::Number(x)
179    } else if let Some(x) = v.int_value {
180        Value::Number(x as f64)
181    } else if let Some(x) = v.uint_value {
182        Value::Number(x as f64)
183    } else if let Some(x) = v.sint_value {
184        Value::Number(x as f64)
185    } else if let Some(b) = v.bool_value {
186        Value::Bool(b)
187    } else {
188        Value::String(String::new())
189    }
190}
191
192fn zigzag(n: u32) -> i32 {
193    ((n >> 1) as i32) ^ -((n & 1) as i32)
194}
195
196/// Expand MoveTo / LineTo / ClosePath commands into point sequences. Each
197/// MoveTo starts a new sequence; ClosePath closes the current ring.
198fn decode_commands(cmds: &[u32]) -> Vec<Vec<Point>> {
199    let mut out: Vec<Vec<Point>> = Vec::new();
200    let (mut x, mut y) = (0i32, 0i32);
201    let mut i = 0;
202    while i < cmds.len() {
203        let cmd = cmds[i] & 0x7;
204        let count = (cmds[i] >> 3) as usize;
205        i += 1;
206        match cmd {
207            1 | 2 => {
208                for _ in 0..count {
209                    // Truncated geometry: keep what decoded cleanly.
210                    let (Some(&dx), Some(&dy)) = (cmds.get(i), cmds.get(i + 1)) else {
211                        return out;
212                    };
213                    i += 2;
214                    x += zigzag(dx);
215                    y += zigzag(dy);
216                    if cmd == 1 {
217                        out.push(Vec::new());
218                    }
219                    if let Some(cur) = out.last_mut() {
220                        cur.push((x as f32, y as f32));
221                    }
222                }
223            }
224            7 => {
225                if let Some(cur) = out.last_mut() {
226                    if let Some(&first) = cur.first() {
227                        cur.push(first);
228                    }
229                }
230            }
231            _ => return out, // malformed: stop rather than misread
232        }
233    }
234    out
235}
236
237/// Signed area (shoelace). In MVT's y-down tile space, exterior rings have
238/// positive area and holes negative.
239fn signed_area(ring: &[Point]) -> f64 {
240    let mut a = 0.0f64;
241    for w in ring.windows(2) {
242        a += (w[0].0 as f64) * (w[1].1 as f64) - (w[1].0 as f64) * (w[0].1 as f64);
243    }
244    a / 2.0
245}
246
247/// Group rings into polygons: a positive-area ring starts a polygon, negative
248/// rings are its holes. Zero-area rings are dropped. If the first ring is
249/// negative (non-conforming encoder), winding is inverted for the whole
250/// feature, matching MapLibre's `classifyRings`.
251fn classify_rings(rings: Vec<Vec<Point>>) -> Vec<Vec<Vec<Point>>> {
252    let mut polygons: Vec<Vec<Vec<Point>>> = Vec::new();
253    let mut ccw: Option<bool> = None;
254    for ring in rings {
255        let area = signed_area(&ring);
256        if area == 0.0 {
257            continue;
258        }
259        let is_neg = area < 0.0;
260        let exterior_is_neg = *ccw.get_or_insert(is_neg);
261        if is_neg == exterior_is_neg {
262            polygons.push(vec![ring]);
263        } else if let Some(p) = polygons.last_mut() {
264            p.push(ring);
265        }
266    }
267    polygons
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn zigzag_decodes() {
276        assert_eq!(zigzag(0), 0);
277        assert_eq!(zigzag(1), -1);
278        assert_eq!(zigzag(2), 1);
279        assert_eq!(zigzag(3), -2);
280    }
281
282    #[test]
283    fn commands_square_polygon() {
284        // MoveTo(1) (3,6); LineTo(3) (8,12) (20,34) ; ClosePath — from the MVT spec.
285        let cmds = [9, 6, 12, 26, 10, 12, 24, 44, 23, 33, 15];
286        let rings = decode_commands(&cmds);
287        assert_eq!(rings.len(), 1);
288        assert_eq!(rings[0][0], (3.0, 6.0));
289        assert_eq!(rings[0][1], (8.0, 12.0));
290        assert_eq!(rings[0][2], (20.0, 34.0));
291        assert_eq!(rings[0].last(), rings[0].first());
292    }
293
294    #[test]
295    fn rings_with_hole_group_into_one_polygon() {
296        let outer = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)];
297        let hole = vec![(2.0, 2.0), (2.0, 8.0), (8.0, 8.0), (8.0, 2.0), (2.0, 2.0)];
298        assert!(signed_area(&outer) > 0.0);
299        assert!(signed_area(&hole) < 0.0);
300        let polys = classify_rings(vec![outer, hole]);
301        assert_eq!(polys.len(), 1);
302        assert_eq!(polys[0].len(), 2);
303    }
304}