library:map: varint-delta the mamaps coord arena, not fixed pairs
- Commit
46bba33cc830c489f476b04a81ae14781a46b148- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-28 00:32 UTC (3 months ago)
- Parents
2575a54
Diff
library/tilecodec/src/main/rust/src/mamaps/body.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body.rs b/library/tilecodec/src/main/rust/src/mamaps/body.rsindex 04de4c100e..dd47690e3a 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body.rs@@ -20,11 +20,27 @@ //! # Layout //! //! ```text-//! [BodyHeader 16][LayerIndex × n][per layer: FeatureRecord[] PartEntry[] coords]+//! [BodyHeader 16][LayerIndex × n][per layer: FeatureRecord[] PartEntry[] coord arena] //! ``` //!-//! Every section is 4-byte aligned so a reader takes zero-copy slices, and coordinates are-//! `i16` pairs in extent units with room either side for the clip buffer.+//! The fixed records are 4-byte aligned so a reader takes zero-copy slices of them.+//!+//! # Why coordinates are varints and everything else is not+//!+//! The first draft of this format stored the arena as flat `[i16 x, i16 y]` pairs, on the reasoning+//! that a zero-copy slice is the cheapest possible decode. Measured against the real published+//! archive that cost **1.72× the compressed bytes of the MVT it replaces**, consistently from z0 to+//! z14, because 87% of a body is coordinates and a fixed 4 bytes per point is simply worse than a+//! zigzag varint delta of 1 to 2. The interned dictionary is a real win — upstream `water` features+//! carry forty `name:*` localisations each — but it is not where the bytes are.+//!+//! So the arena is per-part zigzag varint deltas, which is what MVT does and for the same reason,+//! and it brings the format to 1.14× MVT. What is still won over MVT is the *decode*: no per-tile+//! string table, no property map, no `String` allocation per feature, and one flat `Vec` of points+//! per layer rather than a geometry-command walk per feature.+//!+//! Deltas restart at each part, so a part is independently decodable and a long line does not+//! accumulate a large running value. //! //! `raw_len` lives in the body header, which is **outside** the compressed frame, so a //! decompressing reader knows the exact output size before it starts: an exact-length read from@@ -102,7 +118,10 @@ impl Feature { /// One path: a line, or one ring of a polygon. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Part {- /// Where this part's points start in the layer's coordinate arena, in points not bytes.+ /// Where this part's points start in the layer's decoded coordinate arena, in points.+ ///+ /// Derivable from the preceding parts' counts, and carried anyway: it is what `points` indexes+ /// with, and validating it on parse catches a body whose parts and arena disagree. pub coord_start: u32, pub point_count: u32, /// [`WINDING_OUTER`] or [`WINDING_HOLE`], stated rather than derived.@@ -305,20 +324,44 @@ fn parse_layer(layer_id: u8, feature_count: usize, buf: &[u8]) -> Result<Layer> } let coords_at = align4(parts_at + parts_len);- if coords_at + coords_needed * 4 > buf.len() {- return err("a .mamaps layer's coordinates run past its payload");+ if coords_at > buf.len() {+ return err("a .mamaps layer's coordinate arena starts past its payload"); }+ // Walked in parts-table order, because a varint arena has no random access: each part's points+ // are deltas from the one before it, restarting at every part. let mut coords = Vec::with_capacity(coords_needed);- for i in 0..coords_needed {- let at = coords_at + i * 4;- coords.push((- i16::from_le_bytes([buf[at], buf[at + 1]]),- i16::from_le_bytes([buf[at + 2], buf[at + 3]]),+ let mut reader = crate::proto::Reader::new(&buf[coords_at..]);+ for part in &parts {+ if part.coord_start as usize != coords.len() {+ return err(format!(+ "a .mamaps part claims to start at point {} but the arena is {} points in",+ part.coord_start,+ coords.len(),+ ));+ }+ let (mut x, mut y) = (0i32, 0i32);+ for _ in 0..part.point_count {+ x += zigzag(reader.uvarint()?);+ y += zigzag(reader.uvarint()?);+ let (Ok(x), Ok(y)) = (i16::try_from(x), i16::try_from(y)) else {+ return err("a .mamaps coordinate delta walks outside the extent an i16 holds");+ };+ coords.push((x, y));+ }+ }+ if coords.len() != coords_needed {+ return err(format!(+ "a .mamaps layer decoded {} points where its parts want {coords_needed}",+ coords.len(), )); } Ok(Layer { layer_id, features, parts, coords }) } +fn zigzag(v: u64) -> i32 {+ crate::proto::zigzag_decode(v) as i32+}+ /// Round up to the next 4-byte boundary, so every section starts where a reader can slice it. pub(crate) fn align4(at: usize) -> usize { (at + 3) & !3@@ -345,6 +388,40 @@ pub fn serialize(body: &Body) -> Result<Vec<u8>> { u16::MAX, )); }+ // The arena is written in parts-table order with no offsets of its own, so a part has to+ // start exactly where the one before it ended. Checked here rather than trusted, because a+ // caller that got it wrong would produce a body that round-trips to different geometry.+ let mut at = 0u32;+ for part in &layer.parts {+ if part.coord_start != at {+ return err(format!(+ "layer {}'s parts are not contiguous: one starts at point {} where {at} was \+ expected",+ layer.layer_id, part.coord_start,+ ));+ }+ at = at+ .checked_add(part.point_count)+ .ok_or_else(|| crate::proto::Error("a .mamaps layer's parts overflow".into()))?;+ }+ if at as usize != layer.coords.len() {+ return err(format!(+ "layer {}'s parts cover {at} points but its arena holds {}",+ layer.layer_id,+ layer.coords.len(),+ ));+ }+ for feature in &layer.features {+ let end = feature.parts_offset as usize + feature.part_count as usize;+ if feature.part_count == 0 || end > layer.parts.len() {+ return err(format!(+ "layer {}'s feature indexes parts {}..{end} of {}",+ layer.layer_id,+ feature.parts_offset,+ layer.parts.len(),+ ));+ }+ } } let index_end = BODY_HEADER_LEN + layers.len() * LAYER_INDEX_LEN;@@ -369,10 +446,18 @@ pub fn serialize(body: &Body) -> Result<Vec<u8>> { while out.len() % 4 != 0 { out.push(0); }- for (x, y) in &layer.coords {- out.extend_from_slice(&x.to_le_bytes());- out.extend_from_slice(&y.to_le_bytes());+ // The arena, in parts-table order. Deltas restart at each part so a part decodes+ // independently and a long line accumulates nothing.+ let mut writer = crate::proto::Writer::new();+ for part in &layer.parts {+ let (mut px, mut py) = (0i32, 0i32);+ for &(x, y) in layer.points(part) {+ writer.uvarint(crate::proto::zigzag_encode(x as i64 - px as i64));+ writer.uvarint(crate::proto::zigzag_encode(y as i64 - py as i64));+ (px, py) = (x as i32, y as i32);+ } }+ out.extend_from_slice(writer.as_slice()); payloads.push((layer.layer_id, layer.features.len() as u16, out)); } @@ -494,7 +579,7 @@ mod tests { #[test] fn every_layer_payload_starts_four_byte_aligned() {- // What lets a reader take zero-copy slices of the coordinate arena.+ // What lets a reader take zero-copy slices of the fixed records. let bytes = serialize(&sample()).expect("serialize"); let layer_count = bytes[10] as usize; for i in 0..layer_count {@@ -505,6 +590,101 @@ mod tests { } } + /// The measured reason the arena is varints: a delta of 1 to 2 bytes against a fixed 4, on+ /// geometry that is 87% of a body. Asserted on a path whose steps are small, which is what real+ /// simplified geometry looks like.+ #[test]+ fn the_arena_costs_far_less_than_a_fixed_four_bytes_a_point() {+ let mut roads = Layer::new(dict::LAYER_ROADS);+ roads.features.push(Feature {+ kind: 45,+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ parts_offset: 0,+ part_count: 1,+ });+ let points: Vec<(i16, i16)> = (0..1000).map(|i| (i * 3, i * 2)).collect();+ roads.parts.push(Part { coord_start: 0, point_count: 1000, winding: WINDING_OUTER });+ roads.coords = points.clone();+ let body = Body { extent: DEFAULT_EXTENT, layers: vec![roads] };+ let bytes = serialize(&body).expect("serialize");+ // Two bytes a point rather than four: each delta is (3, 2), a single varint byte each.+ assert!(+ bytes.len() < 1000 * 3,+ "{} bytes for 1000 points, against {} flat",+ bytes.len(),+ 1000 * 4,+ );+ assert_eq!(Body::parse(&bytes).expect("parse").layer(dict::LAYER_ROADS).unwrap().coords, points);+ }++ /// Deltas restart at each part, so a part decodes without walking the one before it and a long+ /// line never accumulates a large running value.+ #[test]+ fn each_part_restarts_its_deltas_from_the_origin() {+ let mut layer = Layer::new(dict::LAYER_ROADS);+ layer.features.push(Feature {+ kind: 45,+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ parts_offset: 0,+ part_count: 2,+ });+ layer.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+ layer.parts.push(Part { coord_start: 2, point_count: 2, winding: WINDING_OUTER });+ // The second part starts far from where the first ended; if deltas carried over, the+ // round trip would place it somewhere else entirely.+ layer.coords = vec![(0, 0), (10, 10), (3000, 3000), (3010, 3010)];+ let body = Body { extent: DEFAULT_EXTENT, layers: vec![layer] };+ let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");+ assert_eq!(parsed, body);+ }++ /// The arena has no offsets of its own, so a part must start exactly where the previous one+ /// ended. A caller that got that wrong would otherwise write a body that round-trips to+ /// different geometry.+ #[test]+ fn parts_that_do_not_tile_the_arena_are_refused() {+ let mut layer = Layer::new(dict::LAYER_ROADS);+ layer.features.push(Feature {+ kind: 45,+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ parts_offset: 0,+ part_count: 1,+ });+ layer.parts.push(Part { coord_start: 1, point_count: 2, winding: WINDING_OUTER });+ layer.coords = vec![(0, 0), (1, 1), (2, 2)];+ let gapped = Body { extent: DEFAULT_EXTENT, layers: vec![layer.clone()] };+ assert!(serialize(&gapped).is_err(), "a part starting past the front");++ layer.parts[0].coord_start = 0;+ let over = Body { extent: DEFAULT_EXTENT, layers: vec![layer.clone()] };+ assert!(serialize(&over).is_err(), "an arena longer than its parts cover");++ layer.coords.pop();+ assert!(serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![layer] }).is_ok());+ }++ #[test]+ fn a_feature_indexing_parts_it_does_not_have_is_refused_by_the_encoder() {+ let mut layer = Layer::new(dict::LAYER_ROADS);+ layer.features.push(Feature {+ kind: 45,+ kind_detail: dict::NONE,+ geom_type: GEOM_LINE,+ flags: 0,+ parts_offset: 0,+ part_count: 3,+ });+ layer.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });+ layer.coords = vec![(0, 0), (1, 1)];+ assert!(serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![layer] }).is_err());+ }+ #[test] fn a_features_geometry_reads_back_through_the_part_table() { let bytes = serialize(&sample()).expect("serialize");@@ -631,6 +811,19 @@ mod tests { } } + /// A truncated arena must fail rather than yield a short point list that silently draws a+ /// different shape.+ #[test]+ fn an_arena_that_ends_early_is_refused() {+ let good = serialize(&sample()).expect("serialize");+ for cut in 1..6 {+ let mut bytes = good[..good.len() - cut].to_vec();+ let len = bytes.len() as u32;+ bytes[4..8].copy_from_slice(&len.to_le_bytes());+ assert!(Body::parse(&bytes).is_err(), "an arena {cut} bytes short");+ }+ }+ #[test] fn a_winding_that_is_neither_outer_nor_hole_is_refused() { let mut bytes = serialize(&sample()).expect("serialize");
library/tilecodec/src/main/rust/src/mamaps/dict.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/dict.rs b/library/tilecodec/src/main/rust/src/mamaps/dict.rsindex 6cf9450386..06c89ec0df 100644--- a/library/tilecodec/src/main/rust/src/mamaps/dict.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/dict.rs@@ -22,7 +22,7 @@ //! //! # Size //!-//! Seven layers, 52 kinds and 4 details, at a length byte each: comfortably under 1 KiB, which is+//! Seven layers, 79 kinds and 41 details, at a length byte each: 1092 bytes as measured, which is //! what lets the header, the dictionary and the root index share one 16 KiB opening read. use crate::proto::{err, Result};@@ -55,6 +55,10 @@ pub const LAYER_BUILDINGS: u8 = 6; /// Grouped by the layer that introduced each value and **append-only**: inserting in the middle /// would renumber everything after it, which is the one thing this table exists to prevent. A /// value shared by two layers appears once, because ids are archive-wide.+///+/// The vocabulary is **measured, not guessed**. Everything here appears in the published+/// `v4.pmtiles`, sampled by `tile_build`'s `mamaps_vocabulary` example, which flags any value the+/// table has no id for. Re-run it after an upstream republish. pub const KINDS: &[&str] = &[ // earth "island",@@ -114,6 +118,43 @@ pub const KINDS: &[&str] = &[ // buildings "building", "building_part",+ // Appended after the first measurement against the published archive, which turned up 42 of+ // 54 features on the z0 tile carrying a value the table above had no id for. Append-only, so+ // these take fresh ids rather than disturbing any above.+ // earth+ "earth",+ "cliff",+ // water+ "canal",+ "dock",+ "fountain",+ "reef",+ "swimming_pool",+ // landuse+ "bare_rock",+ "commercial",+ "dog_park",+ "garden",+ "kindergarten",+ "meadow",+ "pitch",+ "platform",+ "railway",+ "recreation_ground",+ "residential",+ "sand",+ "wetland",+ // roads+ "aerialway",+ "ferry",+ // boundaries. The style filters these numerically through `kind_detail`, so no flat style layer+ // names them -- but they are what the data says, and the differential harness compares names.+ "country",+ "region",+ "county",+ "locality",+ "overlay_limit",+ "unrecognized_country", ]; /// Every `kind_detail` value, id 1 upward. Index 0 is [`NONE`].@@ -122,10 +163,61 @@ pub const KINDS: &[&str] = &[ /// detail are different ids. They describe different things and collapsing them would make a /// road's detail collide with a polygon's kind. ///+/// On `roads` this is the OSM highway class, which is what the upstream schema puts here — 30-odd+/// values, not the four the style happens to filter on. Carrying the rest is what lets the+/// generator be checked against upstream feature for feature, and what a future style would need+/// to draw a track differently from a motorway link.+/// /// `boundaries` does not appear here: its detail is a numeric admin level carried in the same /// field under [`super::body::FLAG_DETAIL_NUMERIC`], because an admin level is an integer the-/// style compares with `<=` rather than a name it matches.-pub const DETAILS: &[&str] = &["runway", "taxiway", "pier", "service"];+/// style compares with `<=` rather than a name it matches. The sample confirms it — upstream+/// writes it as an `SInt`, not a string.+pub const DETAILS: &[&str] = &[+ // The four the style filters on, first because they were here first.+ "runway",+ "taxiway",+ "pier",+ "service",+ // The rest of the road classes, measured from the published archive.+ "motorway",+ "motorway_link",+ "trunk",+ "trunk_link",+ "primary",+ "primary_link",+ "secondary",+ "secondary_link",+ "tertiary",+ "tertiary_link",+ "residential",+ "unclassified",+ "living_street",+ "alley",+ "track",+ "path",+ "footway",+ "sidewalk",+ "crossing",+ "steps",+ "corridor",+ "cycleway",+ "pedestrian",+ "rail",+ "subway",+ "tram",+ "light_rail",+ "cable_car",+ "turntable",+ // water+ "basin",+ "canal",+ "lake",+ "river",+ "stream",+ "rock",+ // buildings+ "yes",+]; /// The interned tables as the archive carries them. ///@@ -251,10 +343,12 @@ mod tests { use super::*; #[test]- fn the_dictionary_round_trips_and_stays_under_a_kilobyte() {+ fn the_dictionary_round_trips_and_stays_small_enough_for_the_prefix() { let schema = Dictionary::schema(); let bytes = schema.serialize();- assert!(bytes.len() < 1024, "the dictionary is {} bytes", bytes.len());+ // 1092 bytes as measured. The bound is what the opening prefix can spare beside the header+ // and a useful root, not a round number: at 2 KiB the root still addresses 1.9 M tiles.+ assert!(bytes.len() < 2048, "the dictionary is {} bytes", bytes.len()); assert_eq!(bytes.len() % 4, 0, "the root index after it must start aligned"); assert_eq!(Dictionary::parse(&bytes).expect("should parse"), schema); }@@ -269,10 +363,12 @@ mod tests { assert_eq!(d.kind_name(10), Some("water")); assert_eq!(d.kind_name(17), Some("national_park")); assert_eq!(d.kind_name(45), Some("highway"));- assert_eq!(d.kind_name(52), Some("building_part"), "the last kind");+ assert_eq!(d.kind_name(52), Some("building_part"), "the last of the first draft");+ assert_eq!(d.kind_name(53), Some("earth"), "the first value appended after measuring"); assert_eq!(d.kind_name(NONE), None, "id 0 is `this feature has no kind`");- assert_eq!(d.kind_name(53), None, "past the table");+ assert_eq!(d.kind_name(u16::MAX), None, "past the table"); assert_eq!(d.detail_name(4), Some("service"));+ assert_eq!(d.detail_name(5), Some("motorway"), "the road classes follow"); assert_eq!(d.layer_name(LAYER_ROADS), Some("roads")); assert_eq!(d.layer_name(7), None); }
library/tilecodec/src/main/rust/src/mamaps/from_mvt.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/from_mvt.rs b/library/tilecodec/src/main/rust/src/mamaps/from_mvt.rsnew file mode 100644index 0000000000..70bcdb90e6--- /dev/null+++ b/library/tilecodec/src/main/rust/src/mamaps/from_mvt.rs@@ -0,0 +1,360 @@+//! Converting one MVT tile into a `.mamaps` body.+//!+//! The bridge between the two formats, and it exists for three callers rather than one:+//!+//! * `mamaps_from_pmtiles` converts a whole archive, which is how the container and the renderer+//! were first validated end to end — on data the tiler already produced and the app already+//! drew, before any tag→kind schema work existed to be wrong.+//! * `library/map`'s host probes read the published `v4.pmtiles` and need a body to tessellate.+//! * The differential harness compares a generated archive against upstream tile for tile, which+//! means putting both through the same decoder.+//!+//! # What is dropped, and why that is the point+//!+//! Points, every property but `kind`, and the per-tile string table. The renderer reads exactly+//! one property and throws points away, so this is not lossy in any sense that reaches a pixel —+//! it is the whole saving the format exists for.+//!+//! A `kind` this crate's schema does not know becomes [`dict::NONE`] rather than an error. The+//! upstream schema is not ours and it changes; a value we cannot name is a feature drawn by the+//! unfiltered fallback layer, which is what MapLibre does with it too. [`Stats`] counts them so a+//! conversion says how much it did not understand.++use crate::mamaps::body::{+ Body, Feature, Layer, Part, DEFAULT_EXTENT, GEOM_LINE, GEOM_POLYGON, WINDING_HOLE,+ WINDING_OUTER,+};+use crate::mamaps::dict;+use crate::mvt::{self, GeomType, Tile, Value};+use crate::proto::{err, Result};++/// What a conversion could not carry, so a caller can report it rather than discover it on screen.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct Stats {+ pub features: u64,+ /// Features whose `kind` is not in [`dict::KINDS`]. Drawn by an unfiltered layer, not lost.+ pub unknown_kinds: u64,+ /// Point features, which this format does not carry at all.+ pub points_dropped: u64,+ /// Source layers with no counterpart in [`dict::LAYERS`], skipped whole.+ pub layers_skipped: u64,+ /// Coordinates outside what an `i16` holds, clamped to its range.+ ///+ /// Should be zero: Protomaps buffers a tile by a few percent, so an `i16` has eight times the+ /// headroom needed. A non-zero count means the input is not what it claims and the geometry is+ /// no longer where it was.+ pub coords_clamped: u64,+}++/// Convert every layer of an MVT tile this format has a counterpart for.+pub fn from_tile(tile: &Tile) -> Result<(Body, Stats)> {+ let mut stats = Stats::default();+ let mut extent: Option<u32> = None;+ let mut layers = Vec::new();++ // Driven by the **schema's** layer order rather than the tile's, so the output is the same+ // whatever order a producer wrote its layers in.+ for (layer_id, name) in dict::LAYERS.iter().enumerate() {+ let Some(source) = tile.layer(name) else { continue };+ // One extent for the whole body: every layer of a Protomaps tile shares one, and carrying+ // a per-layer extent would mean a scale factor per draw for no benefit anyone has ever+ // needed.+ match extent {+ None => extent = Some(source.extent),+ Some(seen) if seen != source.extent => {+ return err(format!(+ "an MVT tile mixes extents ({seen} and {}), which a .mamaps body cannot carry",+ source.extent,+ ));+ }+ Some(_) => {}+ }+ let mut layer = Layer::new(layer_id as u8);+ for feature in &source.features {+ stats.features += 1;+ let kind = match feature.get("kind").and_then(as_str) {+ Some(name) => match kind_id(name) {+ Some(id) => id,+ None => {+ stats.unknown_kinds += 1;+ dict::NONE+ }+ },+ None => dict::NONE,+ };+ let detail = feature+ .get("kind_detail")+ .and_then(as_str)+ .and_then(detail_id)+ .unwrap_or(dict::NONE);+ match feature.geom_type {+ GeomType::Polygon => {+ let Some(polygons) = mvt::decode_polygons(&feature.geometry) else { continue };+ // One feature per polygon rather than one per multipolygon, so a feature's+ // parts are exactly one exterior and its holes. That is what the tessellator+ // wants, and it makes "one outer per feature" an invariant a test can state.+ for rings in &polygons {+ push_feature(&mut layer, kind, detail, GEOM_POLYGON, rings, &mut stats);+ }+ }+ GeomType::LineString => {+ let Some(lines) = mvt::decode_lines(&feature.geometry) else { continue };+ push_feature(&mut layer, kind, detail, GEOM_LINE, &lines, &mut stats);+ }+ // The renderer decoded points and threw them away, so they are not carried.+ GeomType::Point => stats.points_dropped += 1,+ GeomType::Unknown => {}+ }+ }+ if !layer.features.is_empty() {+ layers.push(layer);+ }+ }++ // Anything the tile carries that the schema has no id for.+ stats.layers_skipped = tile+ .layers+ .iter()+ .filter(|source| !dict::LAYERS.contains(&source.name.as_str()))+ .count() as u64;++ let extent = extent.unwrap_or(DEFAULT_EXTENT as u32);+ let extent = u16::try_from(extent).map_err(|_| {+ crate::proto::Error(format!("an MVT extent of {extent} does not fit a .mamaps body"))+ })?;+ Ok((Body { extent, layers }, stats))+}++/// Append one feature and its parts, skipping degenerate paths.+///+/// A part of fewer than two points is not a path: it cannot stroke and it cannot bound an area, and+/// keeping it would mean every consumer checking. If nothing survives, no feature is written.+fn push_feature(+ layer: &mut Layer,+ kind: u16,+ kind_detail: u16,+ geom_type: u8,+ parts: &[Vec<(i32, i32)>],+ stats: &mut Stats,+) {+ let parts_offset = layer.parts.len() as u32;+ for (index, points) in parts.iter().enumerate() {+ if points.len() < 2 {+ continue;+ }+ let coord_start = layer.coords.len() as u32;+ for &(x, y) in points {+ layer.coords.push((clamp(x, stats), clamp(y, stats)));+ }+ layer.parts.push(Part {+ coord_start,+ point_count: points.len() as u32,+ // MVT's own convention, which the decoder preserves: a polygon's first ring is its+ // exterior and the rest are holes. Winding is stated here rather than recovered from+ // the signed area, which is unreliable on a near-degenerate clipped ring.+ winding: if geom_type == GEOM_POLYGON && index > 0 { WINDING_HOLE } else { WINDING_OUTER },+ });+ }+ let part_count = layer.parts.len() as u32 - parts_offset;+ if part_count == 0 {+ return;+ }+ layer.features.push(Feature { kind, kind_detail, geom_type, flags: 0, parts_offset, part_count });+}++/// An extent-unit coordinate as an `i16`, counting anything that would not fit.+fn clamp(v: i32, stats: &mut Stats) -> i16 {+ match i16::try_from(v) {+ Ok(v) => v,+ Err(_) => {+ stats.coords_clamped += 1;+ v.clamp(i16::MIN as i32, i16::MAX as i32) as i16+ }+ }+}++/// A `kind` name's id, or `None` when the schema has no counterpart.+pub fn kind_id(name: &str) -> Option<u16> {+ dict::KINDS.iter().position(|k| *k == name).map(|i| i as u16 + 1)+}++/// A `kind_detail` name's id, or `None`.+pub fn detail_id(name: &str) -> Option<u16> {+ dict::DETAILS.iter().position(|d| *d == name).map(|i| i as u16 + 1)+}++fn as_str(value: &Value) -> Option<&str> {+ match value {+ Value::String(s) => Some(s.as_str()),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::mvt::{Feature as MvtFeature, Layer as MvtLayer};++ fn line_feature(kind: &str, points: &[(i32, i32)]) -> MvtFeature {+ MvtFeature {+ id: None,+ geom_type: GeomType::LineString,+ geometry: mvt::encode_lines(&[points.to_vec()]),+ props: vec![("kind".to_string(), Value::String(kind.to_string()))],+ }+ }++ fn tile_with(layers: Vec<MvtLayer>) -> Tile {+ Tile { layers }+ }++ fn layer_of(name: &str, features: Vec<MvtFeature>) -> MvtLayer {+ MvtLayer { features, ..MvtLayer::new(name) }+ }++ fn roads_layer(features: Vec<MvtFeature>) -> MvtLayer {+ layer_of("roads", features)+ }++ #[test]+ fn a_line_feature_converts_with_its_kind_interned() {+ let tile = tile_with(vec![roads_layer(vec![line_feature(+ "highway",+ &[(0, 0), (100, 100), (200, 50)],+ )])]);+ let (body, stats) = from_tile(&tile).expect("convert");+ assert_eq!(body.extent, 4096);+ let layer = body.layer(dict::LAYER_ROADS).expect("roads");+ assert_eq!(layer.features.len(), 1);+ assert_eq!(layer.features[0].kind, kind_id("highway").expect("highway"));+ assert_eq!(layer.features[0].geom_type, GEOM_LINE);+ assert_eq!(layer.points(&layer.parts_of(&layer.features[0])[0]).len(), 3);+ assert_eq!(stats.features, 1);+ assert_eq!(stats.unknown_kinds, 0);+ }++ /// A `kind` the schema has no id for is drawn by the unfiltered fallback rather than dropped,+ /// which is what MapLibre does with it too. Counted so a conversion can report it.+ #[test]+ fn an_unknown_kind_becomes_none_and_is_counted() {+ let tile = tile_with(vec![roads_layer(vec![line_feature(+ "hyperloop",+ &[(0, 0), (10, 10)],+ )])]);+ let (body, stats) = from_tile(&tile).expect("convert");+ let layer = body.layer(dict::LAYER_ROADS).expect("roads");+ assert_eq!(layer.features[0].kind, dict::NONE);+ assert_eq!(stats.unknown_kinds, 1);+ }++ /// A source layer the schema does not carry is skipped whole and counted, not an error: the+ /// upstream archive has 20-odd layers and this format draws seven.+ #[test]+ fn a_layer_the_schema_does_not_carry_is_skipped_and_counted() {+ let tile = tile_with(vec![+ layer_of("places", vec![line_feature("locality", &[(0, 0), (1, 1)])]),+ roads_layer(vec![line_feature("highway", &[(0, 0), (1, 1)])]),+ ]);+ let (body, stats) = from_tile(&tile).expect("convert");+ assert_eq!(body.layers.len(), 1, "only roads");+ assert_eq!(stats.layers_skipped, 1);+ }++ #[test]+ fn a_point_feature_is_dropped_because_the_format_has_none() {+ let point = MvtFeature {+ id: None,+ geom_type: GeomType::Point,+ geometry: mvt::encode_points(&[(10, 20)]),+ props: vec![("kind".to_string(), Value::String("peak".to_string()))],+ };+ let tile = tile_with(vec![roads_layer(vec![point])]);+ let (body, stats) = from_tile(&tile).expect("convert");+ assert!(body.layers.is_empty(), "nothing survives");+ assert_eq!(stats.points_dropped, 1);+ }++ /// A part of fewer than two points is not a path: it cannot stroke and cannot bound an area, so+ /// dropping it here means no consumer has to check.+ #[test]+ fn a_degenerate_part_is_dropped_and_takes_its_feature_with_it_if_nothing_is_left() {+ let tile = tile_with(vec![roads_layer(vec![line_feature("highway", &[(5, 5)])])]);+ let (body, _) = from_tile(&tile).expect("convert");+ assert!(body.layers.is_empty());+ }++ /// Layers come out in the **schema's** order, so the same tile written with its layers in any+ /// order converts to the same body. Half of why a conversion is reproducible.+ #[test]+ fn output_order_is_the_schemas_not_the_tiles() {+ let roads = roads_layer(vec![line_feature("highway", &[(0, 0), (1, 1)])]);+ let water = layer_of("water", vec![line_feature("lake", &[(0, 0), (1, 1)])]);+ let forward = from_tile(&tile_with(vec![water.clone(), roads.clone()])).expect("a").0;+ let reverse = from_tile(&tile_with(vec![roads, water])).expect("b").0;+ assert_eq!(forward, reverse);+ assert_eq!(+ forward.layers.iter().map(|l| l.layer_id).collect::<Vec<_>>(),+ vec![dict::LAYER_WATER, dict::LAYER_ROADS],+ "water precedes roads, as the schema lists them",+ );+ }++ #[test]+ fn a_tile_mixing_extents_is_refused_rather_than_silently_rescaled() {+ let tile = tile_with(vec![+ roads_layer(vec![line_feature("highway", &[(0, 0), (1, 1)])]),+ MvtLayer {+ extent: 512,+ features: vec![line_feature("lake", &[(0, 0), (1, 1)])],+ ..MvtLayer::new("water")+ },+ ]);+ assert!(from_tile(&tile).is_err());+ }++ #[test]+ fn a_coordinate_too_large_for_an_i16_is_clamped_and_counted() {+ // Should never happen: a Protomaps tile is buffered by a few percent and an `i16` has+ // eight times the headroom. A count above zero means the input is not what it claims.+ let tile =+ tile_with(vec![roads_layer(vec![line_feature("highway", &[(0, 0), (99_999, 0)])])]);+ let (body, stats) = from_tile(&tile).expect("convert");+ assert_eq!(stats.coords_clamped, 1);+ let layer = body.layer(dict::LAYER_ROADS).expect("roads");+ assert_eq!(layer.coords[1].0, i16::MAX);+ }++ #[test]+ fn an_empty_tile_converts_to_an_empty_body() {+ let (body, stats) = from_tile(&Tile::new()).expect("convert");+ assert!(body.layers.is_empty());+ assert_eq!(stats, Stats::default());+ }++ /// The real published z0 tile, which is the one the format has to survive: it is the ocean+ /// polygon with 105 holes, and it is where every ring pathology in the archive lives.+ #[test]+ fn the_published_z0_tile_converts_and_re_encodes() {+ let raw = include_bytes!("../../tests/fixtures/v4_z0_tile.mvt");+ let tile = Tile::decode(raw).expect("the fixture should decode");+ let (body, stats) = from_tile(&tile).expect("convert");+ assert!(stats.features > 0, "the z0 tile has features");+ assert_eq!(stats.coords_clamped, 0, "a buffered tile stays inside an i16");+ assert!(!body.layers.is_empty());+ // Round-trips through the container, which is the thing this bridge exists to feed.+ let bytes = crate::mamaps::body::serialize(&body).expect("serialize");+ assert_eq!(Body::parse(&bytes).expect("parse"), body);+ // **A size regression guard, not a claim to be smaller.** Measured on this tile: MVT+ // 93 228 raw / 67 722 deflated, `.mamaps` 111 007 / 81 691 — 1.19x and 1.21x. The format is+ // not a saving in bytes; what it wins is the decode, and z0 is its worst case because the+ // ocean polygon is 42 000 points against 54 features, so almost nothing is attributes.+ // Reverting the arena to flat `i16` pairs would put this at 192 692 (2.01x deflated), which+ // is what this bound exists to catch.+ assert!(+ bytes.len() < raw.len() * 3 / 2,+ "{} bytes of .mamaps against {} of MVT: the arena encoding has regressed",+ bytes.len(),+ raw.len(),+ );+ }+}
library/tilecodec/src/main/rust/src/mamaps/index.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/index.rs b/library/tilecodec/src/main/rust/src/mamaps/index.rsindex 7b2bb07b46..8789026c6b 100644--- a/library/tilecodec/src/main/rust/src/mamaps/index.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/index.rs@@ -8,9 +8,9 @@ //! //! # The prefix budget //!-//! A reader opens with one 16 KiB read. Header (128) plus dictionary (under 1 KiB) leaves about-//! 15 KiB, which is 476 root entries; at 4096 tiles each that addresses 1.95 M tiles without a-//! second request. California needs under 100 leaves. Past 1.95 M,+//! A reader opens with one 16 KiB read. Header (128) plus dictionary (1092 as measured) leaves+//! 15 164 bytes, which is 473 root entries; at 4096 tiles each that addresses 1.94 M tiles without+//! a second request. California needs under 100 leaves. Past 1.94 M, //! [`Header::leaf_entry_capacity`](super::header::Header::leaf_entry_capacity) doubles rather //! than the root growing — the same trick `pmtiles::split_entries` uses, and for the same reason. //!@@ -240,14 +240,14 @@ mod tests { /// **Invariant 1 of the plan's verification list.** Header plus dictionary plus root must fit /// the one 16 KiB read a reader opens with, at a scale well past California. #[test]- fn a_root_addressing_two_million_tiles_fits_the_opening_prefix() {+ fn a_root_addressing_nearly_two_million_tiles_fits_the_opening_prefix() { let prefix = crate::stream::OPEN_PREFIX_BYTES as usize; let dictionary = super::super::dict::Dictionary::schema().serialize().len(); let budget = prefix - super::super::header::HEADER_LEN - dictionary; let entries = budget / ROOT_ENTRY_LEN;- assert!(entries >= 476, "only {entries} root entries fit the prefix");+ assert!(entries >= 470, "only {entries} root entries fit the prefix"); assert!(- entries * 4096 >= 1_950_000,+ entries * 4096 >= 1_900_000, "{} tiles addressable in one request", entries * 4096, );
library/tilecodec/src/main/rust/src/mamaps/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/mod.rsindex 17c93580f0..779b9fe44c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/mod.rs@@ -44,6 +44,8 @@ pub mod header; pub mod index; pub mod read; +#[cfg(feature = "write")]+pub mod from_mvt; #[cfg(feature = "write")] pub mod write;