Modern Apps git

← Modern-Apps.git

tilecodec: add region_links side table linking places labels to boundaries

Commit
b75ff30ea803338df9be0fdfb2bd5360111a26b3
Author
vayun-mathur <[email protected]>
When
2026-09-21 23:16 UTC (2 months ago)
Parents
b01a587

Diff

library/tilecodec/src/main/rust/src/mamaps/body/codec.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rsindex c1cf78e2a9..efb8b376ec 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/codec.rs@@ -1,6 +1,6 @@-use super::consts::{BODY_FLAG_BUILDING_TABLE, BODY_FLAG_EXTENDED_COUNTS, BODY_FLAG_HEIGHTMAP, BODY_FLAG_ID_TABLE, BODY_FLAG_LANE_TABLE, BODY_FLAG_NAME_TABLE, BODY_FLAG_ROAD_LANES, BODY_HEADER_LEN, FEATURE_RECORD_LEN, GEOM_LINE, GEOM_POINT, GEOM_POLYGON, KNOWN_BODY_FLAGS, KNOWN_FEATURE_FLAGS, LAYER_INDEX_LEN, PART_ENTRY_LEN, WINDING_HOLE, WINDING_OUTER};+use super::consts::{BODY_FLAG_BUILDING_TABLE, BODY_FLAG_EXTENDED_COUNTS, BODY_FLAG_HEIGHTMAP, BODY_FLAG_ID_TABLE, BODY_FLAG_LANE_TABLE, BODY_FLAG_NAME_TABLE, BODY_FLAG_REGION_LINKS, BODY_FLAG_ROAD_LANES, BODY_HEADER_LEN, FEATURE_RECORD_LEN, GEOM_LINE, GEOM_POINT, GEOM_POLYGON, KNOWN_BODY_FLAGS, KNOWN_FEATURE_FLAGS, LAYER_INDEX_LEN, PART_ENTRY_LEN, WINDING_HOLE, WINDING_OUTER}; use super::model::{Body, BuildingAttrs, Carriageway, Feature, LaneTurns, Layer, NAME_NONE, Part};-use super::tables::{align4, parse_carriageways, parse_heightmap, parse_ids, parse_lanes, parse_names, payloads_end};+use super::tables::{align4, parse_carriageways, parse_heightmap, parse_ids, parse_lanes, parse_names, parse_region_links, payloads_end}; use super::tables_extra::parse_buildings; use crate::proto::{Result, err}; @@ -16,6 +16,7 @@ impl Body {             heightmap: None,             carriageways: Vec::new(),             convention: None,+            region_links: Vec::new(),         }     } @@ -56,6 +57,18 @@ impl Body {             .and_then(|(_, ids)| ids.get(index).copied())     } +    /// The tagged OSM relation id of the admin boundary the `index`-th feature of `layer_id` names,+    /// or `None` when the layer carries no region-link table.+    ///+    /// [`REGION_NONE`](super::model::REGION_NONE) when the layer has a table but this label links to+    /// no region. Only the `places` layer ever carries one.+    pub fn region_link(&self, layer_id: u8, index: usize) -> Option<u64> {+        self.region_links+            .iter()+            .find(|(id, _)| *id == layer_id)+            .and_then(|(_, links)| links.get(index).copied())+    }+     /// This feature's S3DB attributes, or `None` when its layer carries no building table. A     /// feature in a layer that has one but with no S3DB tags of its own reads back as a default     /// [`BuildingAttrs`], not `None`.@@ -178,6 +191,7 @@ impl Body {         let mut heightmap = None;         let mut carriageways = Vec::new();         let mut convention = None;+        let mut region_links = Vec::new();         let payloads_end = payloads_end(buf, layer_count, index_end)?;         let has_names = body_flags & BODY_FLAG_NAME_TABLE != 0;         let has_ids = body_flags & BODY_FLAG_ID_TABLE != 0;@@ -185,12 +199,14 @@ impl Body {         let has_buildings = body_flags & BODY_FLAG_BUILDING_TABLE != 0;         let has_heightmap = body_flags & BODY_FLAG_HEIGHTMAP != 0;         let has_carriageways = body_flags & BODY_FLAG_ROAD_LANES != 0;+        let has_region_links = body_flags & BODY_FLAG_REGION_LINKS != 0;         if !has_names             && !has_ids             && !has_lanes             && !has_buildings             && !has_heightmap             && !has_carriageways+            && !has_region_links         {             // The body is exactly its payloads, unpadded. Anything else is trailing garbage.             if payloads_end != buf.len() {@@ -235,6 +251,11 @@ impl Body {                 carriageways = table;                 convention = Some(marking);             }+            if has_region_links {+                let (table, used) = parse_region_links(&buf[at..], &layers)?;+                at += used;+                region_links = table;+            }             if at != buf.len() {                 return err(format!(                     "a .mamaps body has {} trailing byte(s) past its trailing sections",@@ -252,6 +273,7 @@ impl Body {             heightmap,             carriageways,             convention,+            region_links,         })     } }
library/tilecodec/src/main/rust/src/mamaps/body/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/body/consts.rsindex f32ec37a40..79b9a89201 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/consts.rs@@ -50,6 +50,14 @@ pub const BODY_FLAG_HEIGHTMAP: u8 = 0x20; /// traffic keeps left in the UK, Japan and Australia. One byte per tile rather than per road, /// because a tile never spans two conventions in any way that matters. v7. pub const BODY_FLAG_ROAD_LANES: u8 = 0x40;+/// A per-feature region-link table follows the carriageway table. See [`Body::region_links`].+///+/// The last available body-flag bit (`0x80`). A `places` label carries the tagged OSM relation id+/// of the admin boundary it names, so a tap on the label can outline that exact region without the+/// point+level containment guess the renderer used to make. Keyed by layer id and dense-parallel to+/// that layer's features exactly like the id table, with `0` for a label that has no linked region;+/// only the `places` layer populates it, so every other tile carries nothing. v8.+pub const BODY_FLAG_REGION_LINKS: u8 = 0x80;  pub(crate) const KNOWN_BODY_FLAGS: u8 = BODY_FLAG_EXTENDED_COUNTS     | BODY_FLAG_ID_TABLE@@ -57,7 +65,8 @@ pub(crate) const KNOWN_BODY_FLAGS: u8 = BODY_FLAG_EXTENDED_COUNTS     | BODY_FLAG_LANE_TABLE     | BODY_FLAG_BUILDING_TABLE     | BODY_FLAG_HEIGHTMAP-    | BODY_FLAG_ROAD_LANES;+    | BODY_FLAG_ROAD_LANES+    | BODY_FLAG_REGION_LINKS;  /// A feature whose geometry is one or more open paths. pub const GEOM_LINE: u8 = 1;
library/tilecodec/src/main/rust/src/mamaps/body/emit.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rsindex e1ed06e643..d93f0c7ee1 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/emit.rs@@ -1,9 +1,9 @@-use super::consts::{BODY_FLAG_BUILDING_TABLE, BODY_FLAG_EXTENDED_COUNTS, BODY_FLAG_HEIGHTMAP, BODY_FLAG_ID_TABLE, BODY_FLAG_LANE_TABLE, BODY_FLAG_NAME_TABLE, BODY_FLAG_ROAD_LANES, BODY_HEADER_LEN, LAYER_INDEX_LEN};+use super::consts::{BODY_FLAG_BUILDING_TABLE, BODY_FLAG_EXTENDED_COUNTS, BODY_FLAG_HEIGHTMAP, BODY_FLAG_ID_TABLE, BODY_FLAG_LANE_TABLE, BODY_FLAG_NAME_TABLE, BODY_FLAG_REGION_LINKS, BODY_FLAG_ROAD_LANES, BODY_HEADER_LEN, LAYER_INDEX_LEN}; use super::model::{     Body, Layer, NAME_NONE, ROOF_ORIENT_MAX, ROOF_SHAPE_MAX, }; use super::emit_extra::write_full_layer_payload;-use super::tables::{serialize_carriageways, serialize_heightmap, serialize_ids, serialize_lanes, serialize_names, align4};+use super::tables::{serialize_carriageways, serialize_heightmap, serialize_ids, serialize_lanes, serialize_names, serialize_region_links, align4}; use super::tables_extra::serialize_buildings; use crate::proto::{Result, err}; @@ -224,6 +224,29 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [         }     } +    // The region-link table is validated exactly as the id table is: keyed and ascending by layer+    // id and dense-parallel to that layer's features, so a caller that built it against a different+    // layer set is refused rather than linking every label to the wrong region.+    let mut previous: Option<u8> = None;+    for (layer_id, entries) in &body.region_links {+        if previous.is_some_and(|p| *layer_id <= p) {+            return err("a .mamaps body's region-link table is not ordered by layer id");+        }+        previous = Some(*layer_id);+        let Some(layer) = layers.iter().find(|l| l.layer_id == *layer_id) else {+            return err(format!(+                "a .mamaps region-link table names layer {layer_id}, which the body does not carry"+            ));+        };+        if entries.len() != layer.features.len() {+            return err(format!(+                "a .mamaps region-link table gives layer {layer_id} {} link(s) for {} feature(s)",+                entries.len(),+                layer.features.len(),+            ));+        }+    }+     let mut index_end = BODY_HEADER_LEN + layers.len() * LAYER_INDEX_LEN;     if needs_extended {         index_end += layers.len() * 4;@@ -270,6 +293,9 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [     if !body.carriageways.is_empty() {         body_flags |= BODY_FLAG_ROAD_LANES;     }+    if !body.region_links.is_empty() {+        body_flags |= BODY_FLAG_REGION_LINKS;+    }     assembled.push(body_flags);     assembled.extend_from_slice(&0u32.to_le_bytes());     for (i, (layer_id, feature_count)) in meta.iter().enumerate() {@@ -308,6 +334,7 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [         || !body.buildings.is_empty()         || body.heightmap.is_some()         || !body.carriageways.is_empty()+        || !body.region_links.is_empty()     {         while assembled.len() % 4 != 0 {             assembled.push(0);@@ -337,6 +364,9 @@ pub fn serialize_into<'s>(body: &Body, scratch: &'s mut Scratch) -> Result<&'s [             assembled,         );     }+    if !body.region_links.is_empty() {+        serialize_region_links(&body.region_links, assembled);+    }     let raw_len = assembled.len() as u32;     assembled[4..8].copy_from_slice(&raw_len.to_le_bytes());     Ok(assembled)
library/tilecodec/src/main/rust/src/mamaps/body/model.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/model.rs b/library/tilecodec/src/main/rust/src/mamaps/body/model.rsindex 03e9f7da2e..df454b57b4 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/model.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/model.rs@@ -139,6 +139,11 @@ pub const NAME_NONE: u16 = 0; /// to should cost zero bytes of entropy rather than a sentinel the reader has to know about. pub const ID_NONE: u64 = 0; +/// `region_link` for "this label names no admin region". Zero for the same reason [`ID_NONE`] is:+/// the table is dense-parallel to the layer's features, and a label with no linked boundary should+/// cost no entropy rather than a sentinel the reader must special-case.+pub const REGION_NONE: u64 = 0;+ /// One road feature's per-lane turn indications, from OSM `turn:lanes[:forward|:backward]`. /// /// Each `u16` is a lane's [`LANE_*`](super::super) bit set — the same scheme the routing graph@@ -428,6 +433,13 @@ impl Heightmap { /// Only the `roads` layer carries one. It exists because [`Feature::lane_count`] is a total and the /// surface renderer needs the directional split to place a centre line. `convention` rides with it /// as a single per-tile byte; it is `None` exactly when the table is absent.+///+/// `region_links` is the optional per-layer region-link table (v8), the same shape as `ids`: keyed+/// by `layer_id`, ascending, and dense-parallel to that layer's `features`. Only the `places` layer+/// carries one, and only when some label in the tile links to an admin boundary; a label with none+/// holds [`REGION_NONE`]. Each entry is the tagged OSM relation id of the boundary the label names+/// (the same id space as the `boundaries` id table), so a tap on the label can outline that region+/// directly. A side table for the same reason `ids` is. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Body {     pub extent: u16,@@ -439,4 +451,5 @@ pub struct Body {     pub heightmap: Option<Heightmap>,     pub carriageways: Vec<(u8, Vec<Carriageway>)>,     pub convention: Option<MarkingConvention>,+    pub region_links: Vec<(u8, Vec<u64>)>, }
library/tilecodec/src/main/rust/src/mamaps/body/tables.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tables.rsindex 2691b036ec..c2e88be74a 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tables.rs@@ -206,6 +206,100 @@ pub fn serialize_ids(ids: &[(u8, Vec<u64>)], out: &mut Vec<u8>) {     } } +/// Parse the region-link table. Byte-identical in shape to the id table (see [`parse_ids`]): a+/// `u32` entry count, then per entry a `u8` layer id, three reserved bytes, a `u32` link count and+/// that many `u64` tagged relation ids. Kept a separate section (its own body flag) so the two are+/// independent — a `places` layer carries both an id table (node ids) and a region-link table+/// (boundary relation ids), and neither implies the other. Same validation as [`parse_ids`].+pub(crate) fn parse_region_links(+    buf: &[u8],+    layers: &[Layer],+) -> Result<(Vec<(u8, Vec<u64>)>, usize)> {+    if buf.len() < 4 {+        return err("a .mamaps region-link table ends before its count");+    }+    let count = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;+    if count > layers.len() {+        return err(format!(+            "a .mamaps region-link table has {count} entries for a body with {} layer(s)",+            layers.len(),+        ));+    }+    let mut at = 4usize;+    let mut table = Vec::with_capacity(count);+    let mut previous: Option<u8> = None;+    for _ in 0..count {+        if at + 8 > buf.len() {+            return err("a .mamaps region-link table ends inside an entry header");+        }+        let layer_id = buf[at];+        if buf[at + 1] != 0 || u16::from_le_bytes([buf[at + 2], buf[at + 3]]) != 0 {+            return err("a .mamaps region-link table entry has non-zero reserved bytes");+        }+        let links_len =+            u32::from_le_bytes([buf[at + 4], buf[at + 5], buf[at + 6], buf[at + 7]]) as usize;+        at += 8;+        if previous.is_some_and(|p| layer_id <= p) {+            return err("a .mamaps region-link table's entries are not ordered by layer id");+        }+        previous = Some(layer_id);+        let Some(layer) = layers.iter().find(|l| l.layer_id == layer_id) else {+            return err(format!(+                "a .mamaps region-link table names layer {layer_id}, which the body does not carry"+            ));+        };+        if links_len != layer.features.len() {+            return err(format!(+                "a .mamaps region-link table gives layer {layer_id} {links_len} link(s) for {} feature(s)",+                layer.features.len(),+            ));+        }+        let bytes = links_len.checked_mul(8).ok_or_else(|| {+            crate::proto::Error("a .mamaps region-link table's entry overflows".to_string())+        })?;+        if at + bytes > buf.len() {+            return err("a .mamaps region-link table's links run past the table");+        }+        let mut links = Vec::with_capacity(links_len);+        for i in 0..links_len {+            let o = at + i * 8;+            links.push(u64::from_le_bytes([+                buf[o],+                buf[o + 1],+                buf[o + 2],+                buf[o + 3],+                buf[o + 4],+                buf[o + 5],+                buf[o + 6],+                buf[o + 7],+            ]));+        }+        at += bytes;+        table.push((layer_id, links));+    }+    let aligned = align4(at);+    if aligned > buf.len() {+        return err("a .mamaps region-link table's padding runs past the body");+    }+    Ok((table, aligned))+}++/// Serialise a region-link table, 4-byte aligned. The inverse of [`parse_region_links`].+pub fn serialize_region_links(links: &[(u8, Vec<u64>)], out: &mut Vec<u8>) {+    out.extend_from_slice(&(links.len() as u32).to_le_bytes());+    for (layer_id, entries) in links {+        out.push(*layer_id);+        out.extend_from_slice(&[0u8; 3]);+        out.extend_from_slice(&(entries.len() as u32).to_le_bytes());+        for id in entries {+            out.extend_from_slice(&id.to_le_bytes());+        }+    }+    while out.len() % 4 != 0 {+        out.push(0);+    }+}+ /// Parse the turn-lane table: `u32` entry count, then per entry a `u8` layer id, three reserved /// bytes, a `u32` feature count and that many per-feature records. A per-feature record is a `u8` /// forward lane count, a `u8` backward lane count, then that many `u16` masks each (forward then
library/tilecodec/src/main/rust/src/mamaps/body/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tests.rsindex e6bbd5fb27..1e2d67c2b3 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tests.rs@@ -50,7 +50,7 @@ fn sample() -> Body {     roads.parts.push(Part { coord_start: 0, point_count: 3, winding: WINDING_OUTER });     roads.coords = vec![(-64, 10), (2048, 2048), (4160, 4000)]; -    Body { extent: DEFAULT_EXTENT, layers: vec![roads, water], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }+    Body { extent: DEFAULT_EXTENT, layers: vec![roads, water], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() } }  #[test]@@ -128,7 +128,7 @@ fn the_arena_costs_far_less_than_a_fixed_four_bytes_a_point() {     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], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None};+    let body = Body { extent: DEFAULT_EXTENT, layers: vec![roads], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() };     let bytes = serialize(&body).expect("serialize");     // Two bytes a point rather than four: each delta is (3, 2), a single varint byte each.     assert!(@@ -164,7 +164,7 @@ fn each_part_restarts_its_deltas_from_the_origin() {     // 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], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None};+    let body = Body { extent: DEFAULT_EXTENT, layers: vec![layer], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() };     let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");     assert_eq!(parsed, body); }@@ -191,15 +191,15 @@ fn parts_that_do_not_tile_the_arena_are_refused() {     });     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()], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None};+    let gapped = Body { extent: DEFAULT_EXTENT, layers: vec![layer.clone()], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() };     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()], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None};+    let over = Body { extent: DEFAULT_EXTENT, layers: vec![layer.clone()], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() };     assert!(serialize(&over).is_err(), "an arena longer than its parts cover");      layer.coords.pop();-    assert!(serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![layer], names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }).is_ok());+    assert!(serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![layer], names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() }).is_ok()); }  #[test]@@ -221,7 +221,7 @@ fn a_feature_indexing_parts_it_does_not_have_is_refused_by_the_encoder() {     });     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], names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }).is_err());+    assert!(serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![layer], names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() }).is_err()); }  #[test]@@ -266,7 +266,7 @@ fn a_numeric_detail_is_a_number_and_an_interned_one_is_not() {     });     boundaries.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });     boundaries.coords = vec![(0, 0), (100, 100)];-    let bytes = serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![boundaries], names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None })+    let bytes = serialize(&Body { extent: DEFAULT_EXTENT, layers: vec![boundaries], names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() })         .expect("serialize");     let body = Body::parse(&bytes).expect("parse");     let feature = &body.layer(dict::LAYER_BOUNDARIES).expect("boundaries").features[0];@@ -284,7 +284,7 @@ fn an_empty_body_is_valid_and_is_what_an_ocean_tile_costs() {  #[test] fn a_layer_with_no_features_still_round_trips() {-    let body = Body { extent: DEFAULT_EXTENT, layers: vec![Layer::new(dict::LAYER_LANDTYPE)], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None};+    let body = Body { extent: DEFAULT_EXTENT, layers: vec![Layer::new(dict::LAYER_LANDTYPE)], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() };     let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");     assert_eq!(parsed, body); }@@ -298,7 +298,7 @@ fn a_body_carrying_two_layers_with_one_id_is_refused() {         ids: Vec::new(),         turn_lanes: Vec::new(),         buildings: Vec::new(),-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     assert!(serialize(&body).is_err()); }@@ -364,7 +364,7 @@ fn an_unknown_geometry_type_is_refused_but_points_round_trip() {     poi.parts.push(Part { coord_start: 0, point_count: 1, winding: WINDING_OUTER });     poi.coords = vec![(100, 200)];     let body =-        Body { extent: DEFAULT_EXTENT, layers: vec![poi], names: vec!["Cafe".to_string()], ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None};+        Body { extent: DEFAULT_EXTENT, layers: vec![poi], names: vec!["Cafe".to_string()], ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() };     let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");     assert_eq!(parsed, body);     let feature = &parsed.layer(dict::LAYER_POI).expect("poi").features[0];@@ -419,7 +419,7 @@ fn the_id_table_round_trips_beside_the_name_table() {         ids: vec![(dict::LAYER_POI, vec![12_345_678_901, ID_NONE])],         turn_lanes: Vec::new(),         buildings: Vec::new(),-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     let bytes = serialize(&body).expect("serialize");     let parsed = Body::parse(&bytes).expect("parse");
library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rsindex eb96eaad36..f5d9c69597 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra.rs@@ -50,7 +50,7 @@ fn sample() -> Body {     roads.parts.push(Part { coord_start: 0, point_count: 3, winding: WINDING_OUTER });     roads.coords = vec![(-64, 10), (2048, 2048), (4160, 4000)]; -    Body { extent: DEFAULT_EXTENT, layers: vec![roads, water], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }+    Body { extent: DEFAULT_EXTENT, layers: vec![roads, water], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() } }  /// The turn-lane table rides beside the id and name tables, dense-parallel to a layer's@@ -91,7 +91,7 @@ fn the_turn_lane_table_round_trips_dense_parallel_to_features() {         ids: Vec::new(),         turn_lanes: vec![(dict::LAYER_ROADS, turns)],         buildings: Vec::new(),-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");     assert_eq!(parsed, body);@@ -131,7 +131,7 @@ fn a_turn_lane_table_that_does_not_match_its_layer_is_refused() {         // Two records for one feature.         turn_lanes: vec![(dict::LAYER_ROADS, vec![LaneTurns::default(), LaneTurns::default()])],         buildings: Vec::new(),-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     assert!(serialize(&body).is_err(), "a turn table longer than its layer's features"); }@@ -165,7 +165,7 @@ fn an_id_table_parses_without_a_name_table() {         ids: vec![(dict::LAYER_POI, vec![7])],         turn_lanes: Vec::new(),         buildings: Vec::new(),-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");     assert_eq!(parsed, body);@@ -183,7 +183,7 @@ fn an_id_table_that_does_not_match_its_layer_is_refused() {         ids,         turn_lanes: Vec::new(),         buildings: Vec::new(),-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     assert!(         serialize(&body(vec![(dict::LAYER_LANDTYPE, vec![1])])).is_err(),@@ -200,6 +200,64 @@ fn an_id_table_that_does_not_match_its_layer_is_refused() {     ); } +/// A place label's baked boundary link round-trips through the region-link table, and a vector+/// that does not match its layer's feature count is refused exactly as the id table is.+#[test]+fn the_region_link_table_round_trips_and_is_validated() {+    let mut layer = Layer::new(dict::LAYER_PLACES);+    for i in 0..2u32 {+        layer.parts.push(Part {+            coord_start: i,+            point_count: 1,+            winding: WINDING_OUTER,+        });+        layer.coords.push((i as i16 * 10, i as i16 * 10));+        layer.features.push(Feature {+            kind: 1,+            kind_detail: 0,+            geom_type: GEOM_POINT,+            flags: 0,+            name_idx: NAME_NONE,+            parts_offset: i,+            part_count: 1,+            transit_color: 0,+            transit_ordinal: 0,+            transit_lanes: 0,+            transit_taper: 0,+            lane_count: 0,+        });+    }+    // First label links to boundary relation 42 (tagged as a relation: (42 << 2) | 3); second+    // links to nothing (REGION_NONE).+    let linked = (42u64 << 2) | 3;+    let body = |links| Body {+        extent: DEFAULT_EXTENT,+        layers: vec![layer.clone()],+        names: Vec::new(),+        ids: Vec::new(),+        turn_lanes: Vec::new(),+        buildings: Vec::new(),+        heightmap: None,+        carriageways: Vec::new(),+        convention: None,+        region_links: links,+    };+    let good = body(vec![(dict::LAYER_PLACES, vec![linked, 0])]);+    let parsed = Body::parse(&serialize(&good).expect("serialize")).expect("parse");+    assert_eq!(parsed, good);+    assert_eq!(parsed.region_link(dict::LAYER_PLACES, 0), Some(linked));+    assert_eq!(parsed.region_link(dict::LAYER_PLACES, 1), Some(0));+    assert_eq!(parsed.region_link(dict::LAYER_ROADS, 0), None, "layer with no table");+    assert!(+        serialize(&body(vec![(dict::LAYER_PLACES, vec![linked])])).is_err(),+        "one link for a layer with two features"+    );+    assert!(+        serialize(&body(vec![(dict::LAYER_POI, vec![])])).is_err(),+        "an entry for a layer the body does not carry"+    );+}+ /// The lane inputs ride in bytes the v2 record already reserved, so they round-trip with no /// version bump. The last byte of the record stays reserved zero. #[test]@@ -333,7 +391,7 @@ fn a_layer_with_more_than_65535_features_round_trips_via_extended_encoding() {         layer.coords.push((0, 0));         layer.coords.push((1, 1));     }-    let body = Body { extent: DEFAULT_EXTENT, layers: vec![layer], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None};+    let body = Body { extent: DEFAULT_EXTENT, layers: vec![layer], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() };     let bytes = serialize(&body).expect("extended tile must serialize");     assert_eq!(bytes[11], BODY_FLAG_EXTENDED_COUNTS, "extended flag set");     let parsed = Body::parse(&bytes).expect("must parse extended");@@ -353,7 +411,7 @@ fn a_layer_with_more_than_65535_features_round_trips_via_extended_encoding() {         ids: Vec::new(),         turn_lanes: Vec::new(),         buildings: Vec::new(),-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     let small_bytes = serialize(&small_body).expect("small tile");     assert_eq!(small_bytes[11], 0, "common path no flag, byte-identical");@@ -421,7 +479,7 @@ fn the_building_table_round_trips_dense_parallel_to_features() {         ids: Vec::new(),         turn_lanes: Vec::new(),         buildings: vec![(dict::LAYER_BUILDINGS, attrs.clone())],-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     let bytes = serialize(&body).expect("serialize");     // The body carries the reader's own version byte, so an older reader rejects it cleanly.
library/tilecodec/src/main/rust/src/mamaps/body/tests_extra2.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra2.rs b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra2.rsindex 1d51f2718e..506b90cca7 100644--- a/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra2.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/body/tests_extra2.rs@@ -54,6 +54,7 @@ fn the_carriageway_table_round_trips_with_its_convention() {         heightmap: None,         carriageways: vec![(dict::LAYER_ROADS, rows.clone())],         convention: Some(convention),+        region_links: Vec::new(),     };     let bytes = serialize(&body).expect("serialize");     assert_ne!(bytes[11] & BODY_FLAG_ROAD_LANES, 0, "the carriageway flag is set");@@ -85,6 +86,7 @@ fn a_body_with_no_carriageway_table_carries_neither_flag_nor_convention() {         heightmap: None,         carriageways: Vec::new(),         convention: None,+        region_links: Vec::new(),     };     let bytes = serialize(&body).expect("serialize");     assert_eq!(bytes[11] & BODY_FLAG_ROAD_LANES, 0, "no carriageway flag");@@ -108,6 +110,7 @@ fn a_convention_without_a_carriageway_table_is_refused() {         heightmap: None,         carriageways: Vec::new(),         convention: Some(MarkingConvention { left_hand: true, yellow_centre: false }),+        region_links: Vec::new(),     };     assert!(serialize(&body).is_err()); }@@ -127,6 +130,7 @@ fn a_carriageway_table_that_does_not_match_its_layer_is_refused() {         heightmap: None,         carriageways: vec![(dict::LAYER_ROADS, vec![Carriageway::default()])],         convention: Some(MarkingConvention::default()),+        region_links: Vec::new(),     };     assert!(serialize(&body).is_err()); }@@ -160,6 +164,7 @@ fn the_oneway_flag_round_trips_and_keeps_its_bit() {         heightmap: None,         carriageways: Vec::new(),         convention: None,+        region_links: Vec::new(),     };     let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");     let feature = &parsed.layers[0].features[0];@@ -201,7 +206,7 @@ fn a_building_table_that_does_not_match_its_layer_is_refused() {             dict::LAYER_BUILDINGS,             vec![BuildingAttrs::default(), BuildingAttrs::default()],         )],-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     assert!(serialize(&body).is_err(), "a building table longer than its layer's features"); }@@ -235,7 +240,7 @@ fn an_out_of_range_roof_value_is_refused_on_parse() {         ids: Vec::new(),         turn_lanes: Vec::new(),         buildings: vec![(dict::LAYER_BUILDINGS, vec![BuildingAttrs::default()])],-        heightmap: None, carriageways: Vec::new(), convention: None,+        heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),     };     let good = serialize(&body).expect("serialize");     assert!(Body::parse(&good).is_ok(), "the default record is otherwise fine");@@ -280,6 +285,7 @@ fn the_heightmap_round_trips_and_ocean_tiles_omit_it() {         heightmap: Some(grid.clone()),         carriageways: Vec::new(),         convention: None,+        region_links: Vec::new(),     };     let bytes = serialize(&body).expect("serialize");     assert_ne!(bytes[11] & BODY_FLAG_HEIGHTMAP, 0, "the heightmap flag is set");@@ -333,6 +339,7 @@ fn the_building_table_and_heightmap_round_trip_together() {         heightmap: Some(Heightmap { dim: 3, samples: vec![32768; 9] }),         carriageways: Vec::new(),         convention: None,+        region_links: Vec::new(),     };     let parsed = Body::parse(&serialize(&body).expect("serialize")).expect("parse");     assert_eq!(parsed, body);
library/tilecodec/src/main/rust/src/mamaps/tests.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests.rs b/library/tilecodec/src/main/rust/src/mamaps/tests.rsindex 8f6840f76f..b687f1a3ed 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests.rs@@ -45,7 +45,7 @@ fn body_for(seed: i16) -> Body {     });     roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });     roads.coords = vec![(0, 0), (seed, seed)];-    Body { extent: DEFAULT_EXTENT, layers: vec![roads], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }+    Body { extent: DEFAULT_EXTENT, layers: vec![roads], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() } }  /// An archive of `(z, x, y, seed)` tiles, fed in ascending id order as the writer requires.@@ -133,7 +133,7 @@ fn wide_body_for(seed: i16) -> Body {             ((state >> 33) as i16, (state >> 17) as i16)         })         .collect();-    Body { extent: DEFAULT_EXTENT, layers: vec![roads], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }+    Body { extent: DEFAULT_EXTENT, layers: vec![roads], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() } }  #[test]
library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rsindex 8926c19df5..d7eb5dcfb1 100644--- a/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/tests_extra.rs@@ -44,7 +44,7 @@ fn body_for(seed: i16) -> Body {     });     roads.parts.push(Part { coord_start: 0, point_count: 2, winding: WINDING_OUTER });     roads.coords = vec![(0, 0), (seed, seed)];-    Body { extent: DEFAULT_EXTENT, layers: vec![roads], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }+    Body { extent: DEFAULT_EXTENT, layers: vec![roads], names: Vec::new(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() } }  /// An archive of `(z, x, y, seed)` tiles, fed in ascending id order as the writer requires.@@ -275,7 +275,7 @@ fn a_leaf_whose_data_span_would_exceed_u32_max_is_split_and_common_case_stays_by         l.parts.push(crate::mamaps::body::Part{coord_start:0,point_count:2,winding:0});         l.coords = vec![(0,0),(seed,seed)];         vec![l]-    }, names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None }).expect("append"); }+    }, names: Vec::new(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new() }).expect("append"); }     let bytes = w.finish().expect("finish");     let hdr = crate::mamaps::Header::parse(&bytes).expect("hdr");     assert_eq!(hdr.leaf_count as usize, (5000+4096-1)/4096);
scripts/maps/mamaps_build/src/rings_part1.rs
diff --git a/scripts/maps/mamaps_build/src/rings_part1.rs b/scripts/maps/mamaps_build/src/rings_part1.rsindex 9165a7eb2b..e42fa02aa8 100644--- a/scripts/maps/mamaps_build/src/rings_part1.rs+++ b/scripts/maps/mamaps_build/src/rings_part1.rs@@ -238,7 +238,7 @@ mod tests {             ids: Vec::new(),             turn_lanes: Vec::new(),             buildings: Vec::new(),-            heightmap: None, carriageways: Vec::new(), convention: None,+            heightmap: None, carriageways: Vec::new(), convention: None, region_links: Vec::new(),         };         // The encoder's own contiguity check, which is the real proof.         assert!(tilecodec::mamaps::body::serialize(&body).is_ok());
scripts/maps/mamaps_build/src/tiler_part5.rs
diff --git a/scripts/maps/mamaps_build/src/tiler_part5.rs b/scripts/maps/mamaps_build/src/tiler_part5.rsindex 025dafb020..1f6d32bf1b 100644--- a/scripts/maps/mamaps_build/src/tiler_part5.rs+++ b/scripts/maps/mamaps_build/src/tiler_part5.rs@@ -255,6 +255,8 @@ fn encode_tile(         heightmap: dem.heightmap_for(z, x, y),         carriageways,         convention,+        // Populated in the region-link phase; empty here keeps the section absent.+        region_links: Vec::new(),     };     let encoded_body = timed(on, &SERIALIZE_NANOS, || {         tilecodec::mamaps::body::serialize_into(&body, scratch)