geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! MLT (`MapLibre` Tiles) encoding for geolith.
//!
//! Transcodes [`TileFeature`] slices to MLT format by first encoding to MVT
//! protobuf, then converting to MLT via `mlt-core`'s columnar encoder. MLT
//! tiles have built-in lightweight compression (no external gzip needed).

use geolith::tile::{feature::TileFeature, mvt};
use mlt_core::encoder::{EncoderConfig, Network, Profile};
use mlt_core::mvt::mvt_to_tile_layers;

use crate::tiles_error::TilesError;

/// Encode a group of tile features into MLT bytes.
///
/// Internally encodes to MVT protobuf first, then transcodes to MLT
/// via `mlt-core`'s columnar encoder. Returns raw MLT bytes (no gzip).
///
/// # Errors
///
/// Returns an error if MVT encoding, MLT conversion, or MLT encoding fails.
/// Also catches panics from `mlt-core` and turns them into
/// [`TilesError::MltPanic`]. A tile cannot be skipped (the archive would have
/// a hole), so the build fails, and the caller names the tile. This works only
/// because the release profile unwinds.
pub fn encode_tile(features: &[TileFeature]) -> Result<Vec<u8>, TilesError> {
    let mvt_bytes = mvt::encode_tile(features);

    std::panic::catch_unwind(|| mvt_to_mlt(&mvt_bytes)).map_err(|panic| TilesError::MltPanic {
        message: geolith::geometry::guard::message_of(panic.as_ref()),
    })?
}

/// Encoder settings for tiles drawn by `MapLibre` GL JS.
///
/// The `Web` profile stores no triangles (GL JS ignores them) and keeps the
/// source feature order, which is the draw order geolith wrote. FSST and
/// `FastPFOR` stay on, as they were with mlt-core 0.9's defaults.
fn encoder_config() -> EncoderConfig {
    EncoderConfig::from_profile(Profile::Web(Network::default()))
        .with_fsst(true)
        .with_fastpfor(true)
}

fn mvt_to_mlt(mvt_bytes: &[u8]) -> Result<Vec<u8>, TilesError> {
    let tile_layers = mvt_to_tile_layers(mvt_bytes).map_err(TilesError::MltParse)?;

    let cfg = encoder_config();
    let mut output = Vec::new();
    for tile_layer in tile_layers {
        let layer_bytes = tile_layer.encode(cfg).map_err(TilesError::MltEncode)?;
        output.extend_from_slice(&layer_bytes);
    }
    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use geolith::layer::Layer;
    use geolith::tile::feature::{GeomType, PropValue as TilePropValue};
    use std::sync::Arc;

    fn make_point_feature(layer: Layer, x: i32, y: i32, kind: &str) -> TileFeature {
        let geometry = vec![
            (1u32 & 0x7) | (1u32 << 3),
            ((x << 1) ^ (x >> 31)) as u32,
            ((y << 1) ^ (y >> 31)) as u32,
        ];
        TileFeature {
            layer,
            id: 1,
            geom_type: GeomType::Point,
            geometry,
            properties: Arc::new(vec![("kind".into(), TilePropValue::Str(kind.into()))]),
            sort_key: 0,
        }
    }

    /// A decoded layer: its name and its `(x, y, kind)` points.
    type DecodedLayer = (String, Vec<(i32, i32, String)>);

    /// Decode MLT bytes with `mlt_core`'s own decoder into
    /// `(layer name, [(x, y, kind)])`, sorted by name and point.
    fn decode(bytes: &[u8]) -> Vec<DecodedLayer> {
        let mut parser = mlt_core::Parser::default();
        let mut dec = mlt_core::Decoder::default();
        let mut out = Vec::new();
        for layer in parser.parse_layers(bytes).expect("MLT output must parse") {
            let mlt_core::Layer::Tag01(layer) = layer else {
                panic!("expected an MVT-compatible layer");
            };
            let tile = layer.into_tile(&mut dec).expect("decode layer");
            let kind = tile
                .property_names()
                .iter()
                .position(|n| n == "kind")
                .expect("kind column");
            let mut points: Vec<(i32, i32, String)> = tile
                .features()
                .iter()
                .map(|f| {
                    let mlt_core::geo_types::Geometry::Point(p) = f.geometry() else {
                        panic!("expected a point");
                    };
                    let mlt_core::PropValue::Str(Some(k)) = &f.properties()[kind] else {
                        panic!("expected a kind string");
                    };
                    (p.x(), p.y(), k.to_string())
                })
                .collect();
            points.sort();
            out.push((tile.name().to_string(), points));
        }
        out.sort();
        out
    }

    #[test]
    fn encoded_points_decode_to_their_coordinates_and_kinds() {
        let features = vec![
            make_point_feature(Layer::Places, 100, 200, "locality"),
            make_point_feature(Layer::Places, 300, 400, "country"),
        ];
        let mlt_bytes = encode_tile(&features).expect("encode");
        assert_eq!(
            decode(&mlt_bytes),
            vec![(
                "places".to_string(),
                vec![
                    (100, 200, "locality".to_string()),
                    (300, 400, "country".to_string())
                ]
            )]
        );
    }

    #[test]
    fn encodes_an_empty_feature_set() {
        let features: Vec<TileFeature> = vec![];

        let mlt_bytes = encode_tile(&features).expect("empty input must encode");

        assert!(
            mlt_bytes.is_empty(),
            "an empty feature set produces no MLT bytes"
        );
    }

    #[test]
    fn encode_tile_with_multi_layer_features() {
        let features = vec![
            make_point_feature(Layer::Places, 100, 200, "city"),
            make_point_feature(Layer::Pois, 300, 400, "restaurant"),
            make_point_feature(Layer::Roads, 500, 600, "primary"),
        ];
        let mlt_bytes = encode_tile(&features).expect("multi-layer encode");
        let point = |x, y, k: &str| vec![(x, y, k.to_string())];
        assert_eq!(
            decode(&mlt_bytes),
            vec![
                ("places".to_string(), point(100, 200, "city")),
                ("pois".to_string(), point(300, 400, "restaurant")),
                ("roads".to_string(), point(500, 600, "primary")),
            ]
        );
    }

    #[test]
    fn mvt_to_mlt_with_malformed_bytes_errors() {
        let bad = vec![0xFFu8; 20];
        let result = mvt_to_mlt(&bad);
        assert!(result.is_err(), "malformed MVT must error");
    }
}