Modern Apps git

← Modern-Apps.git

maps: bake lane split, oneway and marking convention into tiles

Commit
ff12bb46fa6fc569a28bec6e3b81e8380a0d5e52
Author
vayun-mathur <[email protected]>
When
2026-09-10 05:50 UTC (2 months ago)
Parents
86fc726

Diff

scripts/maps/mamaps_build/src/coalesce.rs
diff --git a/scripts/maps/mamaps_build/src/coalesce.rs b/scripts/maps/mamaps_build/src/coalesce.rsindex 8d7edcb561..a127b5d510 100644--- a/scripts/maps/mamaps_build/src/coalesce.rs+++ b/scripts/maps/mamaps_build/src/coalesce.rs@@ -56,6 +56,12 @@ //! different corridor ordinals are drawn as two parallel lines, and merging them would put both //! on whichever ordinal came first. //!+//! The carriageway joins the key too, and it is the one part of the key that is **not** on the+//! feature: the directional split lives in a side table because it is present on a minority of+//! roads. It has to be in the key all the same, because two four-lane roads that divide 3/1 and+//! 1/3 are drawn as different surfaces with the centre line in different places. A one-way and a+//! two-way are already separated for free, because that one is a flag.+//! //! Direction is not preserved through a join and does not need to be: nothing in //! [`tilecodec::mamaps::body`]'s flag set reads a line's direction, so `A -> B` and `B -> A` draw //! the same. Joins are made head-to-tail only, so a part is never reversed anyway.@@ -70,7 +76,9 @@  use std::collections::HashMap; -use tilecodec::mamaps::body::{BuildingAttrs, LaneTurns, Layer, Part, GEOM_LINE, WINDING_OUTER};+use tilecodec::mamaps::body::{+    BuildingAttrs, Carriageway, LaneTurns, Layer, Part, GEOM_LINE, WINDING_OUTER,+};  /// What coalescing a build saved, for the report. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]@@ -93,7 +101,12 @@ impl Stats { /// What makes two line features interchangeable to a renderer. The trailing `name_idx` keeps two /// differently-named roads or rivers of the same class apart, so a curved label is never attached /// to a line that merged with a neighbour of another name; same-named fragments still merge.-type Class = (u16, u16, u8, u32, u8, u8, u8, u8, u16);+///+/// The last three come from the carriageway side table rather than from the feature, and they are+/// in the key for the same reason `transit_color` is: two four-lane roads of one class that divide+/// 3/1 and 1/3 are drawn as different surfaces, and merging them would put both on whichever split+/// came first. `flags` already separates a one-way from a two-way, because that is a flag.+type Class = (u16, u16, u8, u32, u8, u8, u8, u8, u16, u8, u8, u32);  /// One line part, as `(coord_start, point_count)` into a layer's existing arena. ///@@ -109,11 +122,11 @@ type Run = Vec<Span>; /// Polygon features are left exactly as they were, in place; only the parts table and the arena are /// rebuilt around them, which [`crate::rings::normalise`] does immediately afterwards anyway. pub fn coalesce_lines(layer: &mut Layer) -> Stats {-    coalesce_lines_with_ids(layer, None, None, None)+    coalesce_lines_with_ids(layer, None, None, None, None) } -/// As [`coalesce_lines`], but also rewrites an id side table and a turn-lane side table so they-/// stay parallel to the features.+/// As [`coalesce_lines`], but also rewrites an id side table, a turn-lane side table and a+/// carriageway side table so they stay parallel to the features. /// /// The tables are indexed by feature position, so merging lines without rewriting them leaves more /// entries than features and the encoder rejects the tile. A merged line takes the id of the first@@ -121,11 +134,14 @@ pub fn coalesce_lines(layer: &mut Layer) -> Stats { /// are *not* lines populate the id table at all (see `extract::tracks_ids`). Turn masks are the /// opposite: they belong to a *road* line, so a line that carries any is held out of merging /// entirely (each becomes its own survivor) rather than folded into a neighbour and losing them.+/// A carriageway takes the third route: it is part of the merge key, so a survivor's split is by+/// construction the split every line it absorbed had. pub fn coalesce_lines_with_ids(     layer: &mut Layer,     ids: Option<&mut Vec<u64>>,     turns: Option<&mut Vec<LaneTurns>>,     buildings: Option<&mut Vec<BuildingAttrs>>,+    carriageways: Option<&mut Vec<Carriageway>>, ) -> Stats {     let mut stats = Stats {         features_before: layer.features.len() as u64,@@ -151,6 +167,12 @@ pub fn coalesce_lines_with_ids(         None => vec![false; layer.features.len()],     }; +    // The split a feature's key carries, read out before the tables are borrowed mutably below.+    // Default when the layer has no carriageway table, which is every layer but `roads`.+    let split = |at: usize| -> Carriageway {+        carriageways.as_deref().and_then(|c| c.get(at).copied()).unwrap_or_default()+    };+     // Every line part, grouped by class, in feature-then-part order.     let mut order: Vec<Class> = Vec::new();     let mut group_of: HashMap<Class, usize> = HashMap::new();@@ -159,7 +181,7 @@ pub fn coalesce_lines_with_ids(         if feature.geom_type != GEOM_LINE || unmergeable[index] {             continue;         }-        let class = class_of(feature);+        let class = class_of(feature, split(index));         let at = *group_of.entry(class).or_insert_with(|| {             order.push(class);             groups.push(Vec::new());@@ -203,7 +225,7 @@ pub fn coalesce_lines_with_ids(             kept.push(index);             continue;         }-        let class = class_of(feature);+        let class = class_of(feature, split(index));         let at = group_of[&class];         if emitted[at] {             continue;@@ -250,6 +272,11 @@ pub fn coalesce_lines_with_ids(             *buildings = kept.iter().map(|&at| buildings[at]).collect();         }     }+    if let Some(carriageways) = carriageways {+        if !carriageways.is_empty() {+            *carriageways = kept.iter().map(|&at| carriageways[at]).collect();+        }+    }      layer.features = features;     layer.parts = parts;@@ -259,7 +286,7 @@ pub fn coalesce_lines_with_ids(     stats } -fn class_of(feature: &tilecodec::mamaps::body::Feature) -> Class {+fn class_of(feature: &tilecodec::mamaps::body::Feature, carriageway: Carriageway) -> Class {     (         feature.kind,         feature.kind_detail,@@ -270,6 +297,9 @@ fn class_of(feature: &tilecodec::mamaps::body::Feature) -> Class {         feature.transit_taper,         feature.lane_count,         feature.name_idx,+        carriageway.forward,+        carriageway.backward,+        carriageway.solid_dividers,     ) } @@ -590,6 +620,79 @@ mod tests {         assert_eq!(all_parts(&layer), vec![vec![(0, 0), (1, 0)], vec![(1, 0), (2, 0)]]);     } +    /// **The one part of the merge key that is not on the feature.** Two four-lane roads of the+    /// same class that divide 3/1 and 1/3 are drawn as different surfaces with the centre line in+    /// different places, and the split lives in a side table rather than on the feature — so+    /// without it in the key they would touch end to end, splice, and both come out on whichever+    /// division happened to come first.+    #[test]+    fn a_differing_directional_split_keeps_two_roads_of_one_class_apart() {+        let mut layer = layer_of(&[+            (7, GEOM_LINE, vec![vec![(0, 0), (1, 0)]]),+            (7, GEOM_LINE, vec![vec![(1, 0), (2, 0)]]),+        ]);+        for feature in &mut layer.features {+            feature.lane_count = 4;+        }+        let mut carriageways = vec![+            Carriageway { forward: 3, backward: 1, solid_dividers: 0 },+            Carriageway { forward: 1, backward: 3, solid_dividers: 0 },+        ];+        coalesce_lines_with_ids(&mut layer, None, None, None, Some(&mut carriageways));+        assert_arena_is_tiled(&layer);+        assert_eq!(layer.features.len(), 2, "two splits, two features");+        assert_eq!(+            all_parts(&layer),+            vec![vec![(0, 0), (1, 0)], vec![(1, 0), (2, 0)]],+            "they touch end to end, so without the split in the key they would be spliced",+        );+        // And the side table still describes the features it is parallel to, in order.+        assert_eq!(+            carriageways,+            vec![+                Carriageway { forward: 3, backward: 1, solid_dividers: 0 },+                Carriageway { forward: 1, backward: 3, solid_dividers: 0 },+            ],+        );+    }++    /// The counterpart, so the key is not simply always-distinct: roads that agree on their split+    /// still merge, and the survivor's entry is the split both of them had.+    #[test]+    fn an_equal_directional_split_still_merges() {+        let mut layer = layer_of(&[+            (7, GEOM_LINE, vec![vec![(0, 0), (1, 0)]]),+            (7, GEOM_LINE, vec![vec![(1, 0), (2, 0)]]),+        ]);+        for feature in &mut layer.features {+            feature.lane_count = 4;+        }+        let split = Carriageway { forward: 3, backward: 1, solid_dividers: 0b10 };+        let mut carriageways = vec![split, split];+        coalesce_lines_with_ids(&mut layer, None, None, None, Some(&mut carriageways));+        assert_arena_is_tiled(&layer);+        assert_eq!(layer.features.len(), 1);+        assert_eq!(all_parts(&layer), vec![vec![(0, 0), (1, 0), (2, 0)]]);+        assert_eq!(carriageways, vec![split], "the side table shrinks with the features");+    }++    /// Solid dividers are part of the split, so a road where a lane change is prohibited does not+    /// merge with one where it is allowed — the difference is a solid line against a dashed one.+    #[test]+    fn a_solid_divider_separates_two_otherwise_identical_carriageways() {+        let mut layer = layer_of(&[+            (7, GEOM_LINE, vec![vec![(0, 0), (1, 0)]]),+            (7, GEOM_LINE, vec![vec![(1, 0), (2, 0)]]),+        ]);+        let mut carriageways = vec![+            Carriageway { forward: 2, backward: 2, solid_dividers: 0 },+            Carriageway { forward: 2, backward: 2, solid_dividers: 0b1 },+        ];+        coalesce_lines_with_ids(&mut layer, None, None, None, Some(&mut carriageways));+        assert_arena_is_tiled(&layer);+        assert_eq!(layer.features.len(), 2);+    }+     /// The point of the whole module, in the shape the real data has: thousands of two-point     /// fragments of one class laid end to end.     #[test]
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex f6057b2960..947fd6cb31 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -56,7 +56,7 @@ use rayon::prelude::*;  use crate::schema::{self, Class, Layers}; use crate::store::{Sink, Store, WayCounts, WayReader, WaySink};-use tilecodec::mamaps::body::BuildingAttrs;+use tilecodec::mamaps::body::{BuildingAttrs, Carriageway}; use tilecodec::mamaps::dict::LAYER_BUILDINGS;  /// One classified feature, in lon/lat, ready to tile.@@ -90,6 +90,11 @@ pub struct Feature {     /// draw per-lane arrows at junctions. See [`crate::schema::roads::turn_masks`].     pub turn_fwd: Vec<u16>,     pub turn_bwd: Vec<u16>,+    /// How a road's lanes divide between the two directions, and which dividers between them may+    /// not be crossed. Default for every other layer and for a road whose split was never+    /// surveyed. Baked into the body's carriageway side table so the renderer can put the centre+    /// line where it belongs rather than down the middle. See [`crate::schema::roads::carriageway`].+    pub carriageway: Carriageway,     /// A building's OSM Simple 3D Buildings attributes (height, roof, colours), `None` for every     /// non-building feature. Baked into the body's building side table so the renderer can extrude     /// the footprint in 3D. See [`crate::schema::buildings::attrs`].@@ -151,6 +156,9 @@ struct Way {     /// [`crate::schema::roads::turn_masks`].     turn_fwd: Vec<u16>,     turn_bwd: Vec<u16>,+    /// A road's directional lane split and solid dividers; default otherwise. See+    /// [`crate::schema::roads::carriageway`].+    carriageway: Carriageway,     /// A building's S3DB attributes, `None` for every non-building. See     /// [`crate::schema::buildings::attrs`].     building: Option<BuildingAttrs>,@@ -172,6 +180,9 @@ struct Relation {     id: i64,     /// A building relation's S3DB attributes (a multipolygon `building=*`), `None` otherwise.     building: Option<BuildingAttrs>,+    /// The ISO 3166-1 code of an `admin_level=2` relation, `None` for every other relation. What+    /// the tile's marking convention is resolved from — see [`crate::schema::boundaries::Conventions`].+    iso: Option<String>, }  /// Read `input` and spill every feature the schema classifies to `spill_path`.@@ -258,9 +269,10 @@ pub fn extract(                                 }                             }                             let name = schema::display_name(&way.tags, class.layer);-                            // A road's carriageway lane count and per-lane turn masks, baked so the-                            // renderer can draw the lanes individually and place turn arrows. Zero-                            // and empty for every other layer.+                            // A road's carriageway lane count, per-lane turn masks and directional+                            // split, baked so the renderer can draw the lanes individually, place+                            // turn arrows and put the centre line where the traffic divides. Zero,+                            // empty and default for every other layer.                             let is_road =                                 class.layer == tilecodec::mamaps::dict::LAYER_ROADS;                             let lane_count = if is_road {@@ -273,6 +285,11 @@ pub fn extract(                             } else {                                 (Vec::new(), Vec::new())                             };+                            let carriageway = if is_road {+                                schema::roads::carriageway(&way.tags)+                            } else {+                                Carriageway::default()+                            };                             // A building's S3DB attributes, parsed once here beside its class.                             // Zero-cost for the overwhelming majority of ways, which are not                             // buildings.@@ -290,6 +307,7 @@ pub fn extract(                                     lane_count,                                     turn_fwd,                                     turn_bwd,+                                    carriageway,                                     building,                                 },                             ));@@ -327,6 +345,10 @@ pub fn extract(                             } else {                                 None                             };+                            // A country's code, kept so the region shape below can stamp its+                            // driving side and centre-line colour onto the tiles it covers.+                            let iso = schema::boundaries::country_code(&relation.tags)+                                .map(str::to_string);                             // An administrative relation yields *two* features: the border, which                             // is a line and is what the basemap draws, and the region's shape,                             // which nothing draws and the region mask reads. They cannot be one@@ -343,6 +365,7 @@ pub fn extract(                                         name: name.clone(),                                         id: relation.id,                                         building: None,+                                        iso: iso.clone(),                                     });                                 }                             }@@ -353,6 +376,7 @@ pub fn extract(                                 name,                                 id: relation.id,                                 building,+                                iso: None,                             });                         }                     }@@ -375,6 +399,7 @@ pub fn extract(                     way.lane_count,                     &way.turn_fwd,                     &way.turn_bwd,+                    way.carriageway,                     way.building,                 )?;             }@@ -556,12 +581,24 @@ pub fn extract(     // 64 Ki ways at ~10 nodes each is a few tens of MB of geometry in flight, against a build that     // peaks near 7 GB.     const MATERIALISE_BATCH: usize = 64 * 1024;-    let mut batch: Vec<(Class, Option<String>, Vec<i64>, u64, u8, Vec<u16>, Vec<u16>, Option<BuildingAttrs>)> =-        Vec::with_capacity(MATERIALISE_BATCH);+    #[allow(clippy::type_complexity)]+    let mut batch: Vec<(+        Class,+        Option<String>,+        Vec<i64>,+        u64,+        u8,+        Vec<u16>,+        Vec<u16>,+        Carriageway,+        Option<BuildingAttrs>,+    )> = Vec::with_capacity(MATERIALISE_BATCH);     let mut built: Vec<Option<Geometry<(f64, f64)>>> = Vec::with_capacity(MATERIALISE_BATCH);     loop {         let more = reader.next(&mut refs)?;-        if let Some((id, class, name, lane_count, turn_fwd, turn_bwd, building)) = more.as_ref() {+        if let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) =+            more.as_ref()+        {             let mut class = *class;             // The corridor's zoom, where it is shallower than this way's own.             if let Ok(at) = promoted.binary_search_by_key(id, |(id, _)| *id) {@@ -583,6 +620,7 @@ pub fn extract(                 *lane_count,                 turn_fwd.clone(),                 turn_bwd.clone(),+                *carriageway,                 *building,             ));         }@@ -592,7 +630,7 @@ pub fn extract(             par::install(|| {                 batch                     .par_iter()-                    .map(|(class, _, refs, _, _, _, _, _)| {+                    .map(|(class, _, refs, _, _, _, _, _, _)| {                         let line = table.line(refs);                         // A label layer's ways are centroided to points: a town mapped as an area                         // is still one label, not a loop. Everything else keeps its geometry.@@ -604,8 +642,10 @@ pub fn extract(                     })                     .collect_into_vec(&mut built);             });-            for ((class, name, _, id, lane_count, turn_fwd, turn_bwd, building), geometry) in-                batch.iter().zip(built.drain(..))+            for (+                (class, name, _, id, lane_count, turn_fwd, turn_bwd, carriageway, building),+                geometry,+            ) in batch.iter().zip(built.drain(..))             {                 match geometry {                     Some(geometry) => {@@ -613,7 +653,11 @@ pub fn extract(                         // those; everything else — and a plain road — goes the plain, named way.                         if let Some(b) = building {                             sink.push_building(class, &geometry, name.as_deref(), *b)?;-                        } else if *lane_count > 0 || !turn_fwd.is_empty() || !turn_bwd.is_empty() {+                        } else if *lane_count > 0+                            || !turn_fwd.is_empty()+                            || !turn_bwd.is_empty()+                            || !carriageway.is_empty()+                        {                             sink.push_road(                                 class,                                 &geometry,@@ -621,6 +665,7 @@ pub fn extract(                                 *lane_count,                                 turn_fwd,                                 turn_bwd,+                                *carriageway,                             )?;                         } else {                             sink.push_named(class, &geometry, name.as_deref(), *id)?;@@ -649,6 +694,11 @@ pub fn extract(         "relation(s)",         true,     );+    // Which driving side and centre-line colour applies where, accumulated as the country shapes+    // go past. Empty on a build with `boundaries` switched off, because nothing classifies an+    // administrative relation then and there is no country geometry to resolve against — such a+    // build's tiles carry no convention and the renderer falls back to right-hand and white.+    let mut conventions = schema::boundaries::Conventions::default();     for relation in &relations {         bar.tick("relation(s)");         // A `places` relation (a country, a region) is labelled at its centroid: one point, not@@ -716,6 +766,12 @@ pub fn extract(         if let Some(building) = relation.building {             sink.push_building(&relation.class, &Geometry::Polygons(polygons), None, building)?;         } else {+            // The country's own shape is also what says how its roads are marked. Stamped before+            // the shape is moved into the sink, from the assembled rings rather than from a+            // separate geometry, so the grid and the border line agree about where the country is.+            if let Some(iso) = &relation.iso {+                conventions.add(iso, &polygons);+            }             sink.push_named(&relation.class, &Geometry::Polygons(polygons), None, id)?;         }         stats.features += 1;@@ -771,6 +827,7 @@ pub fn extract(         println!("  {} drivable component segment(s)", stats.traffic_segments);     }     let store = sink.finish(spill_path)?;+    let store = store.with_conventions(conventions);     // The one phase that had no mark after it, and it turned out to be the largest single item in the     // build outside tiling: ~25 s of a 136 s California run. It is 170 M coordinate lookups through     // the mapped node table plus 3.3 GB of spill written, all on one thread.@@ -1089,7 +1146,8 @@ mod tests {         // Ascending way ids, as pass 1 produces; overlapping refs, as real ways have.         for way in 0..64i64 {             let refs: Vec<i64> = (0..8).map(|i| way * 5 + i).collect();-            sink.push(way + 1, &class, &refs, None, 0, &[], &[], None).expect("push");+            sink.push(way + 1, &class, &refs, None, 0, &[], &[], Carriageway::default(), None)+                .expect("push");         }         let counts = sink.finish().expect("finish"); 
scripts/maps/mamaps_build/src/rings.rs
diff --git a/scripts/maps/mamaps_build/src/rings.rs b/scripts/maps/mamaps_build/src/rings.rsindex 4443ff8d5b..a171b0a00e 100644--- a/scripts/maps/mamaps_build/src/rings.rs+++ b/scripts/maps/mamaps_build/src/rings.rs@@ -684,6 +684,7 @@ mod tests {                 name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),+                carriageway: tilecodec::mamaps::body::Carriageway::default(),                 building: None,             },             crate::extract::Feature {@@ -696,6 +697,7 @@ mod tests {                 name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),+                carriageway: tilecodec::mamaps::body::Carriageway::default(),                 building: None,             },         ];
scripts/maps/mamaps_build/src/schema/boundaries.rs
diff --git a/scripts/maps/mamaps_build/src/schema/boundaries.rs b/scripts/maps/mamaps_build/src/schema/boundaries.rsindex 43356c085a..ef7cff11de 100644--- a/scripts/maps/mamaps_build/src/schema/boundaries.rs+++ b/scripts/maps/mamaps_build/src/schema/boundaries.rs@@ -26,8 +26,18 @@ //! Whatever eventually feeds a region mask therefore needs somewhere the boundary style does not //! reach — a kind the layer excludes, or a layer of its own — decided together with the mask //! rather than guessed at here.+//!+//! # The marking convention rides on this layer too+//!+//! Which side traffic keeps and what colour separates the directions are properties of the+//! *country*, and the only country geometry this build has is the `admin_level=2` relations it+//! already streams for the border lines. [`Conventions`] turns those into a coarse grid the tiler+//! stamps onto each tile's body, so the renderer never has to carry a polygon set to answer a+//! question that never changes for a given tile.++use std::collections::HashMap; -use tilecodec::mamaps::body::FLAG_DETAIL_NUMERIC;+use tilecodec::mamaps::body::{MarkingConvention, FLAG_DETAIL_NUMERIC}; use tilecodec::mamaps::dict::LAYER_BOUNDARIES;  use super::{kind, Class, TagSource};@@ -126,6 +136,250 @@ fn min_zoom_for(level: u16) -> u8 {     } } +/// The ISO 3166-1 alpha-2 code of a country relation, or `None` for anything that is not one.+///+/// `admin_level=2` and nothing else: level 4 is a state, and a state has no traffic convention of+/// its own anywhere this build covers. The code is read verbatim rather than matched against a+/// list, because [`convention_for`] is the only thing that looks at it and an unknown code there+/// is already the default rather than an error.+pub fn country_code(tags: &(impl TagSource + ?Sized)) -> Option<&str> {+    if tags.get("boundary") != Some("administrative") || tags.get("admin_level")?.trim() != "2" {+        return None;+    }+    tags.get("ISO3166-1").map(str::trim).filter(|code| code.len() == 2)+}++/// Countries where traffic keeps left.+///+/// The list is what it is: there is no rule to derive it from, and the ones missing from it get+/// right-hand traffic, which is most of the world by land area and the safer thing to be wrong+/// about. British overseas territories are here individually because OSM gives each its own+/// `admin_level=2` relation and its own code.+const LEFT_HAND: &[&str] = &[+    "AG", "AI", "AU", "BB", "BD", "BM", "BN", "BS", "BT", "BW", "CC", "CK", "CX", "CY", "DM", "FJ",+    "FK", "GB", "GD", "GG", "GY", "HK", "ID", "IE", "IM", "IN", "JE", "JM", "JP", "KE", "KI", "KN",+    "KY", "LC", "LK", "LS", "MO", "MS", "MT", "MU", "MV", "MW", "MY", "MZ", "NA", "NF", "NP", "NR",+    "NU", "NZ", "PG", "PK", "PN", "SB", "SC", "SG", "SH", "SR", "SZ", "TC", "TH", "TL", "TO", "TT",+    "TV", "TZ", "UG", "VC", "VG", "VI", "WS", "ZA", "ZM", "ZW",+];++/// Countries where a **yellow** line separates opposing directions.+///+/// The Americas, plus Japan and South Korea. Everywhere else the centre line is white and only its+/// style distinguishes it from a lane divider, which is what [`MarkingConvention`]'s default says.+const YELLOW_CENTRE: &[&str] = &[+    "AR", "BO", "BR", "BS", "BZ", "CA", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "GY", "HN", "HT",+    "JM", "JP", "KR", "MX", "NI", "PA", "PE", "PR", "PY", "SR", "SV", "TT", "US", "UY", "VE",+];++/// The convention a country's roads are marked to.+///+/// An unlisted code is right-hand traffic with a white centre line, which is+/// [`MarkingConvention`]'s own default and what the renderer falls back to when a tile carries no+/// convention at all — so an unrecognised country and an unresolved tile draw the same, rather+/// than differently for no reason a reader could see.+pub fn convention_for(code: &str) -> MarkingConvention {+    let listed = |list: &[&str]| list.iter().any(|entry| entry.eq_ignore_ascii_case(code));+    MarkingConvention { left_hand: listed(LEFT_HAND), yellow_centre: listed(YELLOW_CENTRE) }+}++/// The zoom the country under a tile is resolved at.+///+/// **This is the whole affordability argument.** A California build is 12.7 M z14 tiles and a+/// planet build is billions, and a point-in-polygon test against every country for each of them is+/// not a cost this build can carry — while the answer is identical across enormous stretches of+/// them, because a convention is a property of a country rather than of a street. So it is+/// resolved once per z6 tile (4096 of them for the whole world, a few hundred kilometres each) and+/// every tile below inherits its ancestor's.+///+/// The error that buys is confined to z6 tiles a border runs through, and only where the two+/// countries either side disagree — the United States and Mexico agree, so do France and Germany;+/// Thailand and Cambodia do not. A handful of tiles drawing a centre line on the wrong side is the+/// price of not projecting a polygon set per tile.+pub const COARSE_ZOOM: u8 = 6;++/// Which convention applies where, as a sparse grid of [`COARSE_ZOOM`] tiles.+///+/// Sparse because most of the grid is ocean, and because a build of one state has no opinion about+/// the rest of the world: an unclaimed tile reads back as [`MarkingConvention::default`], which is+/// exactly what a tile with no convention at all means to the renderer.+#[derive(Debug, Default, Clone, PartialEq, Eq)]+pub struct Conventions {+    /// `(convention, was claimed by an interior tile)`, keyed by `y * 2^COARSE_ZOOM + x`.+    ///+    /// The flag is what settles a coastal or border tile. A country claims a tile twice over: once+    /// for covering its centre, which is unambiguous, and once for merely having a boundary vertex+    /// in it, which several countries can do at once. An interior claim therefore overrides a+    /// border claim, and between two claims of the same standing the first wins — which is+    /// relation order, which is the PBF's order, which is what keeps the archive reproducible.+    at: HashMap<u32, (MarkingConvention, bool)>,+}++impl Conventions {+    /// Stamp one country's shape onto the grid.+    ///+    /// `polygons` is the relation's assembled rings in lon/lat, exactly as the `boundaries` region+    /// shape carries them — outer first, then holes, which is what makes the even-odd fill below+    /// treat an enclave as a hole rather than as more of the country.+    pub fn add(&mut self, code: &str, polygons: &[Vec<Vec<(f64, f64)>>]) {+        let convention = convention_for(code);+        let side = (1u32 << COARSE_ZOOM) as f64;+        for rings in polygons {+            // Projected once per ring rather than per scanline: this is the same+            // [`tile_build::geom::project`] the tiler places every feature with, so a country's+            // edge lands where its border line does.+            let projected: Vec<Vec<(f64, f64)>> = rings+                .iter()+                .map(|ring| {+                    ring.iter()+                        .map(|&(lon, lat)| tile_build::geom::project(lon, lat, COARSE_ZOOM))+                        .collect()+                })+                .collect();+            for ring in &projected {+                for &(x, y) in ring {+                    self.claim(x, y, convention, false);+                }+            }+            self.fill(&projected, convention, side);+        }+    }++    /// Claim every coarse tile whose centre the polygon covers, one row at a time.+    ///+    /// A scanline rather than a test per tile: the crossings of one horizontal line against every+    /// ring cost one pass over the vertices, and there are only 64 rows in the whole world. Testing+    /// each candidate tile instead would walk a country's rings once per tile, and a country's+    /// rings run to hundreds of thousands of points.+    fn fill(&mut self, rings: &[Vec<(f64, f64)>], convention: MarkingConvention, side: f64) {+        let (mut top, mut bottom) = (f64::MAX, f64::MIN);+        for ring in rings {+            for &(_, y) in ring {+                top = top.min(y);+                bottom = bottom.max(y);+            }+        }+        if top > bottom {+            return;+        }+        let first = top.floor().max(0.0) as u32;+        let last = bottom.floor().min(side - 1.0) as u32;+        let mut crossings: Vec<f64> = Vec::new();+        for row in first..=last {+            let at = row as f64 + 0.5;+            crossings.clear();+            for ring in rings {+                // Wrapping rather than `windows(2)`, so a ring that arrived unclosed still gets its+                // closing edge. A closed one's wrap edge is degenerate and crosses nothing.+                for i in 0..ring.len() {+                    let (ax, ay) = ring[i];+                    let (bx, by) = ring[(i + 1) % ring.len()];+                    // Half-open in `y`, so a vertex exactly on the scanline is counted once rather+                    // than zero or twice — the usual even-odd rule.+                    if (ay <= at) == (by <= at) {+                        continue;+                    }+                    crossings.push(ax + (at - ay) * (bx - ax) / (by - ay));+                }+            }+            crossings.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+            for span in crossings.chunks(2) {+                let [from, to] = span else { continue };+                // A tile is inside when its *centre* is, which is `tx + 0.5` in `from..=to`.+                let low = (from - 0.5).ceil().max(0.0);+                let high = (to - 0.5).floor().min(side - 1.0);+                let mut tx = low;+                while tx <= high {+                    self.claim(tx, row as f64, convention, true);+                    tx += 1.0;+                }+            }+        }+    }++    fn claim(&mut self, x: f64, y: f64, convention: MarkingConvention, interior: bool) {+        let side = 1u32 << COARSE_ZOOM;+        if !(x.is_finite() && y.is_finite()) {+            return;+        }+        let (tx, ty) = (+            (x.floor().max(0.0) as u32).min(side - 1),+            (y.floor().max(0.0) as u32).min(side - 1),+        );+        let held = self.at.entry(ty * side + tx).or_insert((convention, interior));+        // An interior claim outranks the border claim of whichever country reached the tile first.+        if interior && !held.1 {+            *held = (convention, true);+        }+    }++    /// The convention for a tile, or the default where nothing claimed its coarse ancestor.+    ///+    /// A tile at or below [`COARSE_ZOOM`] inherits the grid cell it sits in; one above it takes+    /// the cell at its own centre, which is the only sensible answer when a tile spans several+    /// countries and is drawn at a zoom where no lane marking is visible anyway.+    pub fn at_tile(&self, z: u8, x: u64, y: u64) -> MarkingConvention {+        let side = 1u64 << COARSE_ZOOM;+        let (cx, cy) = if z >= COARSE_ZOOM {+            let shift = z - COARSE_ZOOM;+            (x >> shift, y >> shift)+        } else {+            let step = 1u64 << (COARSE_ZOOM - z);+            ((x * step) + step / 2, (y * step) + step / 2)+        };+        let key = (cy.min(side - 1) * side + cx.min(side - 1)) as u32;+        self.at.get(&key).map(|(convention, _)| *convention).unwrap_or_default()+    }++    /// Does the grid know anything at all? Empty for a build with the `boundaries` layer switched+    /// off, or one whose extract holds no country relation.+    pub fn is_empty(&self) -> bool {+        self.at.is_empty()+    }++    /// The grid as the store index carries it: a `u32` count, then a `u32` cell key and a+    /// [`MarkingConvention`] byte each, ascending by key so a reused store reproduces the run that+    /// built it byte for byte.+    pub fn to_bytes(&self) -> Vec<u8> {+        let mut keys: Vec<&u32> = self.at.keys().collect();+        keys.sort_unstable();+        let mut out = Vec::with_capacity(4 + keys.len() * 5);+        out.extend_from_slice(&(keys.len() as u32).to_le_bytes());+        for key in keys {+            out.extend_from_slice(&key.to_le_bytes());+            out.push(self.at[key].0.to_byte());+        }+        out+    }++    /// The inverse of [`Conventions::to_bytes`], returning the grid and the bytes it consumed.+    pub fn from_bytes(raw: &[u8]) -> osm_ingest::proto::Result<(Conventions, usize)> {+        if raw.len() < 4 {+            return osm_ingest::proto::err(+                "a store index's convention grid is truncated".to_string(),+            );+        }+        let count = u32::from_le_bytes(raw[..4].try_into().expect("four bytes")) as usize;+        let end = 4 + count * 5;+        if raw.len() < end {+            return osm_ingest::proto::err(format!(+                "a store index claims {count} convention cell(s) and holds {}",+                (raw.len() - 4) / 5,+            ));+        }+        let mut at = HashMap::with_capacity(count);+        for cell in raw[4..end].chunks_exact(5) {+            let key = u32::from_le_bytes(cell[..4].try_into().expect("four bytes"));+            let convention = MarkingConvention::from_byte(cell[4])+                .map_err(|e| osm_ingest::proto::Error(e.to_string()))?;+            // Resolved already, so every reloaded cell counts as an interior claim — nothing adds+            // to a grid that came off disk.+            at.insert(key, (convention, true));+        }+        Ok((Conventions { at }, end))+    }+}+ #[cfg(test)] mod tests {     use super::*;@@ -262,6 +516,146 @@ mod tests {         );     } +    /// The convention is a property of a *country*, so nothing below level 2 carries one: a state+    /// has no driving side of its own anywhere this build covers.+    #[test]+    fn only_a_level_two_relation_with_an_iso_code_is_a_country() {+        let code = |pairs: &[(&str, &str)]| super::country_code(pairs).map(str::to_string);+        assert_eq!(+            code(&[("boundary", "administrative"), ("admin_level", "2"), ("ISO3166-1", "JP")]),+            Some("JP".to_string()),+        );+        // Whitespace around a level is common in real data, as `classify` already allows.+        assert_eq!(+            code(&[("boundary", "administrative"), ("admin_level", " 2 "), ("ISO3166-1", "GB")]),+            Some("GB".to_string()),+        );+        for tags in [+            // A state, which has no convention of its own.+            vec![("boundary", "administrative"), ("admin_level", "4"), ("ISO3166-1", "US")],+            // A country with no code to look up.+            vec![("boundary", "administrative"), ("admin_level", "2")],+            // A three-letter code is the alpha-3 field under the wrong key.+            vec![("boundary", "administrative"), ("admin_level", "2"), ("ISO3166-1", "JPN")],+            vec![("boundary", "protected_area"), ("admin_level", "2"), ("ISO3166-1", "JP")],+            vec![("ISO3166-1", "JP")],+        ] {+            assert!(super::country_code(&tags[..]).is_none(), "{tags:?} is not a country");+        }+    }++    #[test]+    fn the_convention_table_carries_the_driving_side_and_the_centre_line_colour() {+        let at = super::convention_for;+        assert_eq!(at("GB"), MarkingConvention { left_hand: true, yellow_centre: false });+        assert_eq!(at("JP"), MarkingConvention { left_hand: true, yellow_centre: true });+        assert_eq!(at("US"), MarkingConvention { left_hand: false, yellow_centre: true });+        assert_eq!(at("FR"), MarkingConvention::default(), "right-hand and white");+        // An unrecognised code draws the same as an unresolved tile, rather than differently for+        // no reason a reader could see.+        assert_eq!(at("ZZ"), MarkingConvention::default());+        assert_eq!(at("gb"), at("GB"), "OSM's own casing is not the only casing in the wild");+    }++    /// A square degree box as the relation assembler would hand one over: one polygon, one closed+    /// outer ring, lon/lat.+    fn box_over(west: f64, south: f64, east: f64, north: f64) -> Vec<Vec<Vec<(f64, f64)>>> {+        vec![vec![vec![+            (west, south),+            (east, south),+            (east, north),+            (west, north),+            (west, south),+        ]]]+    }++    /// The tile a lon/lat falls in at `z`.+    fn tile_at(lon: f64, lat: f64, z: u8) -> (u64, u64) {+        let (x, y) = tile_build::geom::project(lon, lat, z);+        (x as u64, y as u64)+    }++    /// **Resolved coarse, inherited downward.** A California build is 12.7 M z14 tiles and the+    /// answer is the same across all of them, so the country is decided once per z6 cell and every+    /// tile below reads its ancestor's.+    #[test]+    fn a_country_claims_the_coarse_tiles_it_covers_and_every_tile_below_inherits() {+        let mut grid = Conventions::default();+        grid.add("JP", &box_over(130.0, 30.0, 145.0, 45.0));++        let inside = MarkingConvention { left_hand: true, yellow_centre: true };+        let (x, y) = tile_at(137.0, 37.0, 14);+        assert_eq!(grid.at_tile(14, x, y), inside, "a z14 tile reads its z6 ancestor");+        // Its neighbour is a different z14 tile in the same coarse cell, so it must agree.+        assert_eq!(grid.at_tile(14, x + 1, y + 1), inside);+        let (cx, cy) = tile_at(137.0, 37.0, COARSE_ZOOM);+        assert_eq!(grid.at_tile(COARSE_ZOOM, cx, cy), inside, "and so does the cell itself");+    }++    /// Nothing claimed it, so it draws right-hand and white — which is most of the world by land+    /// area and the safer thing to be wrong about.+    #[test]+    fn an_unclaimed_tile_falls_back_to_right_hand_and_white() {+        let mut grid = Conventions::default();+        grid.add("JP", &box_over(130.0, 30.0, 145.0, 45.0));+        let (x, y) = tile_at(-100.0, 40.0, 14);+        assert_eq!(grid.at_tile(14, x, y), MarkingConvention::default());+        assert!(!Conventions::default().at_tile(14, 0, 0).left_hand, "and so does an empty grid");+    }++    /// A coastal or border cell is claimed by every country with a boundary vertex in it, and only+    /// one of them covers its centre. Covering the centre is the unambiguous claim, so it wins+    /// whatever order the relations arrived in.+    #[test]+    fn covering_a_cells_centre_outranks_merely_having_a_border_in_it() {+        let mut grid = Conventions::default();+        // A shape too small to cover any cell centre: it can only ever be a border claim.+        grid.add("JP", &box_over(-100.02, 40.0, -100.0, 40.02));+        // And a shape that swallows it whole.+        grid.add("US", &box_over(-110.0, 35.0, -95.0, 45.0));+        let (x, y) = tile_at(-100.01, 40.01, 14);+        assert_eq!(+            grid.at_tile(14, x, y),+            MarkingConvention { left_hand: false, yellow_centre: true },+            "the interior claim came second and still won",+        );+    }++    /// `--reuse-store` has to reproduce the run that built the spill. A grid that did not survive+    /// the index would leave a reused build drawing every road right-hand and white, which is not+    /// a difference anything downstream could see.+    #[test]+    fn the_grid_survives_the_store_index() {+        let mut grid = Conventions::default();+        grid.add("JP", &box_over(130.0, 30.0, 145.0, 45.0));+        grid.add("GB", &box_over(-8.0, 50.0, 2.0, 59.0));+        assert!(!grid.is_empty());++        let bytes = grid.to_bytes();+        let (back, used) = Conventions::from_bytes(&bytes).expect("read the grid back");+        assert_eq!(used, bytes.len(), "the whole grid was consumed");+        for (lon, lat) in [(137.0, 37.0), (-3.0, 54.0), (-100.0, 40.0)] {+            let (x, y) = tile_at(lon, lat, 14);+            assert_eq!(back.at_tile(14, x, y), grid.at_tile(14, x, y), "at {lon},{lat}");+        }+        // Ascending by cell key, so two runs of the same build write the same index bytes.+        assert_eq!(bytes, back.to_bytes());+    }++    #[test]+    fn a_truncated_convention_grid_is_an_error_rather_than_a_short_read() {+        let mut grid = Conventions::default();+        grid.add("GB", &box_over(-8.0, 50.0, 2.0, 59.0));+        let bytes = grid.to_bytes();+        assert!(Conventions::from_bytes(&bytes[..bytes.len() - 1]).is_err(), "a cut cell");+        assert!(Conventions::from_bytes(&bytes[..2]).is_err(), "a cut count");+        // And the empty grid, which is what a build with no country relation writes.+        let (empty, used) = Conventions::from_bytes(&Conventions::default().to_bytes())+            .expect("an empty grid is readable");+        assert!(empty.is_empty());+        assert_eq!(used, 4);+    }+     #[test]     fn only_an_administrative_boundary_with_a_readable_level_counts() {         for tags in [
scripts/maps/mamaps_build/src/schema/roads.rs
diff --git a/scripts/maps/mamaps_build/src/schema/roads.rs b/scripts/maps/mamaps_build/src/schema/roads.rsindex 8ec4ecb839..153b8ed0ac 100644--- a/scripts/maps/mamaps_build/src/schema/roads.rs+++ b/scripts/maps/mamaps_build/src/schema/roads.rs@@ -21,7 +21,9 @@ //! street at z8 is not detail, it is a grey wash — and it is also most of the bytes. The `min_zoom` //! column below is the single most consequential table in this crate. -use tilecodec::mamaps::body::{FLAG_IS_BRIDGE, FLAG_IS_LINK, FLAG_IS_TUNNEL};+use tilecodec::mamaps::body::{+    Carriageway, FLAG_IS_BRIDGE, FLAG_IS_LINK, FLAG_IS_ONEWAY, FLAG_IS_TUNNEL,+}; use tilecodec::mamaps::dict::LAYER_ROADS;  use super::{detail, kind, Class, TagSource};@@ -181,11 +183,16 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {     None } -/// The three booleans, and the reason this layer was worth redoing.+/// The four booleans, and the reason this layer was worth redoing. /// /// `is_link` is derived from the class name rather than read from a tag, because OSM spells a slip /// road as `highway=motorway_link` and there is no `link=yes`. That matches what upstream emits and /// what the style filters with `!has is_link`.+///+/// `is_oneway` is a flag rather than side-table data because it is what decides whether a+/// carriageway has a centre line at all, and because a flag is part of `coalesce`'s merge key —+/// so a one-way and a two-way of the same class cannot collapse into one feature wearing+/// whichever direction came first. fn flags(tags: &(impl TagSource + ?Sized), value: &str) -> u8 {     let mut flags = 0u8;     // `tunnel=building_passage` is a tunnel; only `no` is not. Same for a bridge tagged `viaduct`@@ -199,6 +206,12 @@ fn flags(tags: &(impl TagSource + ?Sized), value: &str) -> u8 {     if value.ends_with("_link") {         flags |= FLAG_IS_LINK;     }+    // `oneway=yes` and only that, which is the test [`osm_ingest::roads::is_oneway`] applies, so a+    // road cannot be one-way to the router and two-way to the carriageway drawn under it.+    // `oneway=-1` is a direction rather than a flag and neither models it.+    if tags.get("oneway") == Some("yes") {+        flags |= FLAG_IS_ONEWAY;+    }     flags } @@ -243,6 +256,79 @@ pub fn turn_masks(tags: &(impl TagSource + ?Sized)) -> (Vec<u16>, Vec<u16>) {     osm_ingest::roads::lane_masks(&rt) } +/// How a road's lanes divide between the two directions, and which of the dividers between them+/// may not be crossed.+///+/// [`lane_count`] is the total; this is what the surface renderer needs on top of it to put the+/// centre line anywhere but the middle. `forward` runs toward the way's last point and `backward`+/// toward its first, the same convention [`turn_masks`] uses, and `oneway` is decided by+/// [`osm_ingest::roads::is_oneway`] so the split agrees with how the router traverses the road.+///+/// **An absent split stays absent.** A two-way road tagged only `lanes=4` comes back all-zero+/// rather than as 2/2, because 2/2 is a guess dressed as a survey — the renderer already draws an+/// unknown split down the middle, and on an odd total the guess would be wrong rather than+/// unhelpful. All-zero is also what lets a tile of untagged residential streets carry no+/// carriageway table at all.+pub fn carriageway(tags: &(impl TagSource + ?Sized)) -> Carriageway {+    let total = lane_count(tags) as u32;+    let forward = osm_ingest::tags::parse_int_tag(tags.get("lanes:forward"));+    let backward = osm_ingest::tags::parse_int_tag(tags.get("lanes:backward"));+    let (forward, backward) = if tags.get("oneway") == Some("yes") {+        // Every lane runs one way, so the total is the forward count even when the way also+        // carries a `lanes:forward` that agrees with it.+        (if forward > 0 { forward } else { total }, 0)+    } else {+        // One side tagged implies the other, and the pair is the more common tagging than either+        // alone. Saturating rather than wrapping: `lanes=2` with `lanes:backward=3` is a mistagged+        // road, and the answer to it is "nothing known about the other side".+        (+            if forward > 0 { forward } else { total.saturating_sub(backward) },+            if backward > 0 { backward } else { total.saturating_sub(forward) },+        )+    };+    // A split that does not add up to the total is not a split: the renderer reads the two+    // together, so 3 forward and 4 backward of five lanes would be a shape it cannot draw. The+    // dividers survive it — they are a property of the total, not of the division.+    let (forward, backward) = if forward + backward == total { (forward, backward) } else { (0, 0) };+    Carriageway {+        forward: forward.min(osm_ingest::tags::MAX_LANES) as u8,+        backward: backward.min(osm_ingest::tags::MAX_LANES) as u8,+        solid_dividers: solid_dividers(tags.get("change:lanes"), total),+    }+}++/// The interior dividers a lane change is prohibited across, a bit each from the leftmost.+///+/// Only the unsuffixed `change:lanes` is read. The `:forward`/`:backward` pair describes each+/// direction's lanes in *that direction's* left-to-right order, so stitching the two into one+/// carriageway-wide ordering needs the driving side — which is a property of the tile rather than+/// of the way and is not known here. The plain tag is already ordered the way this field is.+///+/// A divider is solid when either lane it separates forbids crossing it: lane `k` tagged+/// `not_right` or `no`, or lane `k + 1` tagged `not_left` or `no`.+fn solid_dividers(spec: Option<&str>, lanes: u32) -> u32 {+    let Some(spec) = spec.filter(|s| !s.is_empty()) else {+        return 0;+    };+    let values: Vec<&str> = spec.split('|').map(str::trim).collect();+    // A list that does not describe this road's lanes describes some other road's, and half of it+    // applied to this one would draw solid lines down the wrong gaps.+    if values.len() as u32 != lanes {+        return 0;+    }+    let mut bits = 0u32;+    // A road with more than 32 interior dividers has none recorded past the 32nd, which no real+    // road reaches.+    for k in 0..values.len().saturating_sub(1).min(32) {+        let blocked = matches!(values[k], "no" | "not_right")+            || matches!(values[k + 1], "no" | "not_left");+        if blocked {+            bits |= 1 << k;+        }+    }+    bits+}+ #[cfg(test)] mod tests {     use super::*;@@ -395,6 +481,108 @@ mod tests {         assert!(fwd.is_empty() && bwd.is_empty());     } +    /// A one-way is a flag rather than side-table data: it is what decides whether the carriageway+    /// has a centre line at all, and `coalesce` keys on flags — so a one-way and a two-way of the+    /// same class cannot merge into one feature wearing whichever direction came first.+    #[test]+    fn a_oneway_is_flagged_and_only_oneway_yes_counts() {+        let oneway = classify_tags(&[("highway", "primary"), ("oneway", "yes")]).expect("oneway");+        assert_eq!(oneway.flags, FLAG_IS_ONEWAY);+        // The same test the routing graph applies: `-1` is a direction rather than a flag, and+        // neither models it.+        for value in ["no", "-1", "reversible", "alternating", ""] {+            let class = classify_tags(&[("highway", "primary"), ("oneway", value)]).expect(value);+            assert_eq!(class.flags, 0, "oneway={value} is not a one-way here");+        }+        // And it combines with the other three.+        let ramp = classify_tags(&[("highway", "motorway_link"), ("oneway", "yes"), ("bridge", "yes")])+            .expect("ramp");+        assert_eq!(ramp.flags, FLAG_IS_LINK | FLAG_IS_BRIDGE | FLAG_IS_ONEWAY);+    }++    /// The directional split the surface renderer places a centre line from. A one-way puts every+    /// lane forward; a two-way needs one side tagged and infers the other from the total.+    #[test]+    fn the_carriageway_divides_the_lane_total_between_the_directions() {+        let split = |pairs: &[(&str, &str)]| carriageway(pairs);+        assert_eq!(+            split(&[("highway", "motorway"), ("oneway", "yes"), ("lanes", "3")]),+            Carriageway { forward: 3, backward: 0, solid_dividers: 0 },+            "every lane of a one-way runs forward",+        );+        assert_eq!(+            split(&[("highway", "primary"), ("lanes", "4"), ("lanes:backward", "1")]),+            Carriageway { forward: 3, backward: 1, solid_dividers: 0 },+            "one side tagged implies the other",+        );+        assert_eq!(+            split(&[+                ("highway", "primary"),+                ("lanes", "5"),+                ("lanes:forward", "3"),+                ("lanes:backward", "2"),+            ]),+            Carriageway { forward: 3, backward: 2, solid_dividers: 0 },+        );+    }++    /// **An absent split stays absent.** 2/2 for a road tagged only `lanes=4` would be a guess+    /// dressed as a survey, and the renderer already draws an unknown split down the middle. It is+    /// also what lets a tile of untagged residential streets carry no carriageway table at all.+    #[test]+    fn a_split_that_was_never_surveyed_or_does_not_add_up_is_left_unknown() {+        let split = |pairs: &[(&str, &str)]| carriageway(pairs);+        assert_eq!(+            split(&[("highway", "primary"), ("lanes", "4")]),+            Carriageway::default(),+            "a bare total says nothing about the division",+        );+        assert_eq!(split(&[("highway", "residential")][..]), Carriageway::default());+        // Mistagged: three forward and three backward of four lanes is a shape nothing can draw.+        assert_eq!(+            split(&[+                ("highway", "primary"),+                ("lanes", "4"),+                ("lanes:forward", "3"),+                ("lanes:backward", "3"),+            ]),+            Carriageway::default(),+        );+    }++    /// `change:lanes` marks the gaps a lane change is prohibited across, one bit per interior+    /// divider from the leftmost. Either lane can forbid the crossing.+    #[test]+    fn a_prohibited_lane_change_becomes_a_solid_divider() {+        let dividers = |pairs: &[(&str, &str)]| carriageway(pairs).solid_dividers;+        // Four lanes, three interior dividers. `not_right` on lane 0 makes divider 0 solid, `no`+        // on lane 2 makes dividers 1 and 2 solid.+        assert_eq!(+            dividers(&[+                ("highway", "primary"),+                ("lanes", "4"),+                ("change:lanes", "not_right|yes|no|yes"),+            ]),+            0b111,+        );+        assert_eq!(+            dividers(&[("highway", "primary"), ("lanes", "2"), ("change:lanes", "yes|yes")]),+            0,+            "a road nothing is prohibited on has no solid dividers",+        );+        // A list that does not describe this road's lanes describes some other road's, and half of+        // it applied here would draw solid lines down the wrong gaps.+        assert_eq!(+            dividers(&[("highway", "primary"), ("lanes", "4"), ("change:lanes", "no|no")]),+            0,+        );+        // The dividers are a property of the total, so they survive an unusable split.+        assert_eq!(+            dividers(&[("highway", "primary"), ("lanes", "3"), ("change:lanes", "yes|no|yes")]),+            0b11,+        );+    }+     #[test]     fn an_unrecognised_value_is_not_a_road() {         for tags in [
scripts/maps/mamaps_build/src/store.rs
diff --git a/scripts/maps/mamaps_build/src/store.rs b/scripts/maps/mamaps_build/src/store.rsindex 920f566aba..708d9cd392 100644--- a/scripts/maps/mamaps_build/src/store.rs+++ b/scripts/maps/mamaps_build/src/store.rs@@ -49,7 +49,7 @@ use tile_build::spill::{  use crate::extract::Feature; use crate::schema::Class;-use tilecodec::mamaps::body::BuildingAttrs;+use tilecodec::mamaps::body::{BuildingAttrs, Carriageway};  /// The property key the packed [`Class`] travels under. ///@@ -98,6 +98,29 @@ const LANE_COUNT_KEY: &str = "l"; const TURN_FWD_KEY: &str = "tf"; const TURN_BWD_KEY: &str = "tb"; +/// The property key a road's carriageway travels under, as a `Uint` packing the forward and+/// backward lane counts a byte each and the solid-divider bits above them (see+/// [`pack_carriageway`]).+///+/// Only a road whose split was actually surveyed sets it. Absent (not zero) otherwise, so the+/// spill pays nothing for the roads whose division is unknown — which is most of them, and the+/// same bargain [`NAME_KEY`] and [`LANE_COUNT_KEY`] make.+const CARRIAGEWAY_KEY: &str = "cw";++/// A [`Carriageway`] as the single `Uint` the spill carries it as: forward in bits 0..8, backward+/// in 8..16, the divider bits in 16..48. Lossless, and the inverse is [`unpack_carriageway`].+fn pack_carriageway(c: Carriageway) -> u64 {+    (c.forward as u64) | ((c.backward as u64) << 8) | ((c.solid_dividers as u64) << 16)+}++fn unpack_carriageway(bits: u64) -> Carriageway {+    Carriageway {+        forward: bits as u8,+        backward: (bits >> 8) as u8,+        solid_dividers: (bits >> 16) as u32,+    }+}+ /// The property keys a building's S3DB attributes travel under, three `Uint`s packing the eight /// [`BuildingAttrs`] fields (see [`pack_building`]). Only `buildings` features set them, and every /// building sets all three — even one with no S3DB tags, whose attributes are all zero — so a@@ -300,11 +323,12 @@ impl Sink {         self.write_record(class, geometry)     } -    /// Push a road with its carriageway lane count and per-lane turn masks: like [`Sink::push`],-    /// plus the optional display name (so a road's label survives even when it carries lane data)-    /// and the lane count (body `lane_count`) and forward/backward `turn:lanes` masks (body-    /// turn-lane table). Refused with no name and all lane data empty — a plain, nameless road goes-    /// through [`Sink::push`] and carries no extra property at all, so the spill pays nothing for it.+    /// Push a road with its carriageway lane count, per-lane turn masks and directional split:+    /// like [`Sink::push`], plus the optional display name (so a road's label survives even when it+    /// carries lane data), the lane count (body `lane_count`), the forward/backward `turn:lanes`+    /// masks (body turn-lane table) and the [`Carriageway`] (body carriageway table). Refused with+    /// no name and all lane data empty — a plain, nameless road goes through [`Sink::push`] and+    /// carries no extra property at all, so the spill pays nothing for it.     pub fn push_road(         &mut self,         class: &Class,@@ -313,8 +337,14 @@ impl Sink {         lane_count: u8,         turn_fwd: &[u16],         turn_bwd: &[u16],+        carriageway: Carriageway,     ) -> Result<()> {-        if name.is_none() && lane_count == 0 && turn_fwd.is_empty() && turn_bwd.is_empty() {+        if name.is_none()+            && lane_count == 0+            && turn_fwd.is_empty()+            && turn_bwd.is_empty()+            && carriageway.is_empty()+        {             return err("a road pushed with no lane data".to_string());         }         self.props[0].1 = Value::Uint(pack(class)?);@@ -333,6 +363,10 @@ impl Sink {             self.props                 .push((TURN_BWD_KEY.to_string(), Value::String(osm_ingest::roads::pack_lanes(turn_bwd))));         }+        if !carriageway.is_empty() {+            self.props+                .push((CARRIAGEWAY_KEY.to_string(), Value::Uint(pack_carriageway(carriageway))));+        }         self.write_record(class, geometry)     } @@ -424,6 +458,7 @@ impl Sink {             bbox: bbox.unwrap_or((0, 0, 0, 0)),             chunks,             chunk_mins,+            conventions: crate::schema::boundaries::Conventions::default(),         })     } @@ -452,6 +487,14 @@ pub struct Store {     chunk_mins: Vec<u8>,     count: u64,     bbox: (i32, i32, i32, i32),+    /// Which marking convention applies where, resolved once from the extract's country relations.+    ///+    /// Not a property of the features and so not in the spill: it is one small grid for the whole+    /// build, read by the tiler once per tile. It rides on the `Store` because that is the one+    /// thing stage A already hands the tiler, and because `--reuse-store` has to reproduce it — a+    /// reused build that silently drew every road right-hand would be the kind of difference+    /// nothing downstream could see.+    conventions: crate::schema::boundaries::Conventions, }  /// What a spill was built from, so reusing one cannot silently build the wrong archive.@@ -520,6 +563,13 @@ impl Provenance { /// Magic and version of the sidecar index. Bumped whenever the layout below changes, so an index /// written by an older build is refused rather than misread. ///+/// v7: `roads` features carry a directional carriageway split under the `cw` property key, and the+/// index gained the marking-convention grid stage A resolves from the country relations. A v6+/// spill has neither, and `--reuse-store` over one would feed a tiler that now builds a carriageway+/// side table and bakes the tile's marking convention beside it with a spill that carries neither+/// — an archive whose roads all draw as an undivided stroke, which is exactly what v7 exists to+/// stop.+/// /// v6: `buildings` features carry S3DB attributes (height, roof, colours) under the `ba`/`bb`/`bc` /// property keys, and road/river names now ride on `roads`/`water` line features. A v5 spill has /// neither, and `--reuse-store` over one would feed a tiler that now builds a building side table@@ -540,7 +590,7 @@ impl Provenance { /// v2: `layers` widened to `u16` (ten layers) and the spill's packed class widened its layer /// field to 4 bits, so a v1 spill would misdecode every feature. Refused here, not there. const INDEX_MAGIC: &[u8; 8] = b"MAMASTOR";-const INDEX_VERSION: u32 = 6;+const INDEX_VERSION: u32 = 7;  impl Store {     /// Write the sidecar that lets [`Store::open`] skip stage A.@@ -575,6 +625,7 @@ impl Store {         }         out.extend_from_slice(&(self.chunk_mins.len() as u64).to_le_bytes());         out.extend_from_slice(&self.chunk_mins);+        out.extend_from_slice(&self.conventions.to_bytes());         std::fs::write(&path, &out)             .map_err(|e| osm_ingest::proto::Error(format!("cannot write {}: {e}", path.display())))?;         Ok(path)@@ -657,6 +708,10 @@ impl Store {         }         let min_count = u64::from_le_bytes(take(8)?.try_into().expect("eight bytes")) as usize;         let chunk_mins = take(min_count)?.to_vec();+        // The convention grid trails the chunk index, so it is whatever is left. Last, because it+        // is the only variable-length section whose length is not known before the one before it+        // has been read.+        let (conventions, _) = crate::schema::boundaries::Conventions::from_bytes(&raw[at..])?;         // The same cross-check `WaySink::finish` makes, for the same reason: two indexes that         // disagree silently drop real features from a handful of tiles at one zoom.         if chunk_mins.len() != chunks.len().saturating_sub(1) {@@ -674,6 +729,7 @@ impl Store {                 bbox: (bbox[0], bbox[1], bbox[2], bbox[3]),                 chunks,                 chunk_mins,+                conventions,             },             features,         ))@@ -745,7 +801,28 @@ impl Store {     }      pub fn from_parts(path: PathBuf, chunks: Vec<u64>, chunk_mins: Vec<u8>) -> Self {-        Self { path, chunks, chunk_mins, count: 0, bbox: (0, 0, 0, 0) }+        Self {+            path,+            chunks,+            chunk_mins,+            count: 0,+            bbox: (0, 0, 0, 0),+            conventions: crate::schema::boundaries::Conventions::default(),+        }+    }++    /// Take the marking-convention grid stage A resolved from the country relations.+    pub fn with_conventions(+        mut self,+        conventions: crate::schema::boundaries::Conventions,+    ) -> Self {+        self.conventions = conventions;+        self+    }++    /// Which marking convention applies where, for the tiler to stamp onto each tile.+    pub fn conventions(&self) -> &crate::schema::boundaries::Conventions {+        &self.conventions     }      pub fn reader_for_wanted(&self, wanted: Vec<usize>, z: u8) -> Result<ZoomReader> {@@ -805,6 +882,7 @@ impl Store {             } else if feature.lane_count != 0                 || !feature.turn_fwd.is_empty()                 || !feature.turn_bwd.is_empty()+                || !feature.carriageway.is_empty()             {                 sink.push_road(                     &feature.class,@@ -813,6 +891,7 @@ impl Store {                     feature.lane_count,                     &feature.turn_fwd,                     &feature.turn_bwd,+                    feature.carriageway,                 )?;             } else {                 sink.push_named(&feature.class, &feature.geometry, feature.name.as_deref(), feature.id)?;@@ -843,6 +922,7 @@ fn feature_of(record: tile_build::spill::NormalizedFeature) -> Result<Feature> {     let mut lane_count: u8 = 0;     let mut turn_fwd: Vec<u16> = Vec::new();     let mut turn_bwd: Vec<u16> = Vec::new();+    let mut carriageway = Carriageway::default();     let mut bld_a: Option<u64> = None;     let mut bld_b: Option<u64> = None;     let mut bld_c: Option<u64> = None;@@ -878,6 +958,9 @@ fn feature_of(record: tile_build::spill::NormalizedFeature) -> Result<Feature> {             (TURN_BWD_KEY, Value::String(packed)) => {                 turn_bwd = unpack_lanes(packed)?;             }+            (CARRIAGEWAY_KEY, Value::Uint(bits)) => {+                carriageway = unpack_carriageway(*bits);+            }             (BLD_A_KEY, Value::Uint(v)) => bld_a = Some(*v),             (BLD_B_KEY, Value::Uint(v)) => bld_b = Some(*v),             (BLD_C_KEY, Value::Uint(v)) => bld_c = Some(*v),@@ -904,6 +987,7 @@ fn feature_of(record: tile_build::spill::NormalizedFeature) -> Result<Feature> {         lane_count,         turn_fwd,         turn_bwd,+        carriageway,         building: match (bld_a, bld_b, bld_c) {             (Some(a), Some(b), Some(c)) => Some(unpack_building(a, b, c)),             (None, None, None) => None,@@ -1213,6 +1297,10 @@ impl Reader { /// | ref count | unsigned varint | /// | refs | zigzag varint of each ref's gap from the one before it, the first from zero | /// | name | unsigned varint byte length, then that many UTF-8 bytes (zero when nameless) |+/// | lane count | unsigned varint |+/// | turn masks | a count then each `u16`, forward then backward |+/// | carriageway | unsigned varint of the packed forward/backward/divider word |+/// | building | a presence byte, then three packed varints when set | /// /// Delta coding earns its keep rather than being a flourish. The refs are ~150 M ids on California /// and the file is read twice — once to collect the node ids pass 3 must resolve, once to build@@ -1251,9 +1339,11 @@ impl WaySink {     ///     /// `name` is the display label for `places`/`poi` ways, `None` for every other layer. Written     /// as a length-prefixed string per record — zero bytes for the nameless, which is nearly all-    /// of them. `lane_count`, `turn_fwd` and `turn_bwd` are a road's carriageway lane count and-    /// per-lane turn masks, empty for every other layer and for a road with no lane tags; a handful-    /// of trailing varints per record, which the scratch file (removed after materialise) affords.+    /// of them. `lane_count`, `turn_fwd`, `turn_bwd` and `carriageway` are a road's lane count,+    /// per-lane turn masks and directional split, empty for every other layer and for a road with+    /// no lane tags; a handful of trailing varints per record, which the scratch file (removed+    /// after materialise) affords.+    #[allow(clippy::too_many_arguments)]     pub fn push(         &mut self,         id: i64,@@ -1263,6 +1353,7 @@ impl WaySink {         lane_count: u8,         turn_fwd: &[u16],         turn_bwd: &[u16],+        carriageway: Carriageway,         building: Option<BuildingAttrs>,     ) -> Result<()> {         if self.count > 0 && id <= self.last_id {@@ -1298,6 +1389,9 @@ impl WaySink {                 put_uvarint(&mut self.record, m as u64);             }         }+        // The directional split, as one packed varint. Zero — one byte — for the roads whose+        // division was never surveyed, which is most of them.+        put_uvarint(&mut self.record, pack_carriageway(carriageway));         // The building attributes: a presence byte, then the three packed words when present. A         // non-building writes one zero byte; a building — even one with no S3DB tags — writes its         // (usually all-zero) words so the tiler's side table stays dense-parallel to the layer.@@ -1363,8 +1457,8 @@ impl WayReader {         })     } -    /// The next way's id, class, display name, lane count and per-lane turn masks, with its node-    /// refs written into `refs`.+    /// The next way's id, class, display name, lane count, per-lane turn masks and carriageway,+    /// with its node refs written into `refs`.     ///     /// `refs` belongs to the caller and is cleared here, so one allocation serves the whole file.     /// Returning a fresh `Vec` instead would be one allocation per classified way, several million@@ -1379,8 +1473,18 @@ impl WayReader {     pub fn next(         &mut self,         refs: &mut Vec<i64>,-    ) -> Result<Option<(i64, Class, Option<String>, u8, Vec<u16>, Vec<u16>, Option<BuildingAttrs>)>>-    {+    ) -> Result<+        Option<(+            i64,+            Class,+            Option<String>,+            u8,+            Vec<u16>,+            Vec<u16>,+            Carriageway,+            Option<BuildingAttrs>,+        )>,+    > {         refs.clear();         let Some(delta) = self.uvarint_or_end()? else {             return Ok(None);@@ -1439,6 +1543,7 @@ impl WayReader {         };         let turn_fwd = read_masks()?;         let turn_bwd = read_masks()?;+        let carriageway = unpack_carriageway(self.uvarint()?);         // The building attributes: a presence byte, then three packed words when set.         let building = if self.uvarint()? != 0 {             let a = self.uvarint()?;@@ -1448,7 +1553,7 @@ impl WayReader {         } else {             None         };-        Ok(Some((id, class, name, lane_count, turn_fwd, turn_bwd, building)))+        Ok(Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)))     }      /// One varint, or `None` if the file ended cleanly on a record boundary.@@ -1737,15 +1842,24 @@ mod tests {         let road = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);         // Refs chosen to exercise the delta coding: a large first id, a run of neighbours, a jump         // backwards, and a way with none at all.-        let cases: Vec<(i64, Class, Vec<i64>, u8, Vec<u16>, Vec<u16>)> = vec![-            (1, lake, vec![10_000_000_001, 10_000_000_002, 10_000_000_003, 9_000_000_000], 0, vec![], vec![]),-            // A four-lane road with forward and backward turn masks, both surviving the spill.-            (2, road, vec![], 4, vec![4u16, 2, 2, 34], vec![1, 2]),-            (i64::MAX, lake, vec![-5, 0, 5, i64::MAX, i64::MIN], 0, vec![], vec![]),+        let cases: Vec<(i64, Class, Vec<i64>, u8, Vec<u16>, Vec<u16>, Carriageway)> = vec![+            (1, lake, vec![10_000_000_001, 10_000_000_002, 10_000_000_003, 9_000_000_000], 0, vec![], vec![], Carriageway::default()),+            // A four-lane road with forward and backward turn masks and a 3/1 split, all surviving+            // the spill.+            (+                2,+                road,+                vec![],+                4,+                vec![4u16, 2, 2, 34],+                vec![1, 2],+                Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 },+            ),+            (i64::MAX, lake, vec![-5, 0, 5, i64::MAX, i64::MIN], 0, vec![], vec![], Carriageway::default()),         ];         let mut sink = WaySink::create(&path).expect("create");-        for (id, class, refs, lanes, fwd, bwd) in &cases {-            sink.push(*id, class, refs, None, *lanes, fwd, bwd, None).expect("push");+        for (id, class, refs, lanes, fwd, bwd, carriageway) in &cases {+            sink.push(*id, class, refs, None, *lanes, fwd, bwd, *carriageway, None).expect("push");         }         let counts = sink.finish().expect("finish");         assert_eq!(counts.ways, 3, "one record per push");@@ -1753,8 +1867,8 @@ mod tests {          let mut reader = WayReader::open(&path).expect("open");         let mut refs: Vec<i64> = Vec::new();-        for (id, class, expected, lanes, fwd, bwd) in &cases {-            let (got_id, got_class, got_name, got_lanes, got_fwd, got_bwd, _got_building) =+        for (id, class, expected, lanes, fwd, bwd, carriageway) in &cases {+            let (got_id, got_class, got_name, got_lanes, got_fwd, got_bwd, got_cw, _got_building) =                 reader.next(&mut refs).expect("read").expect("a way");             assert_eq!(got_id, *id);             assert_eq!(got_class, *class);@@ -1762,6 +1876,7 @@ mod tests {             assert_eq!(got_lanes, *lanes, "a road's lane count survives the spill");             assert_eq!(&got_fwd, fwd, "forward turn masks survive the spill");             assert_eq!(&got_bwd, bwd, "backward turn masks survive the spill");+            assert_eq!(got_cw, *carriageway, "the directional split survives the spill");             assert_eq!(&refs, expected);         }         assert!(reader.next(&mut refs).expect("read").is_none(), "and then the end");@@ -1778,10 +1893,11 @@ mod tests {         let path = temp("ways_unsorted");         let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);         let mut sink = WaySink::create(&path).expect("create");-        sink.push(100, &class, &[1, 2], None, 0, &[], &[], None).expect("push");-        assert!(sink.push(99, &class, &[3], None, 0, &[], &[], None).is_err(), "an id going backwards");-        assert!(sink.push(100, &class, &[3], None, 0, &[], &[], None).is_err(), "and the same id twice");-        sink.push(101, &class, &[3], None, 0, &[], &[], None).expect("but forwards is fine");+        let none = Carriageway::default();+        sink.push(100, &class, &[1, 2], None, 0, &[], &[], none, None).expect("push");+        assert!(sink.push(99, &class, &[3], None, 0, &[], &[], none, None).is_err(), "an id going backwards");+        assert!(sink.push(100, &class, &[3], None, 0, &[], &[], none, None).is_err(), "and the same id twice");+        sink.push(101, &class, &[3], None, 0, &[], &[], none, None).expect("but forwards is fine");         let _ = std::fs::remove_file(&path);     } @@ -1792,8 +1908,9 @@ mod tests {         let path = temp("ways_truncated");         let class = Class::area(dict::LAYER_WATER, schema::kind("lake"), 6);         let mut sink = WaySink::create(&path).expect("create");-        sink.push(1, &class, &[7, 8, 9], None, 0, &[], &[], None).expect("push");-        sink.push(2, &class, &[11, 12, 13], Some("named"), 0, &[], &[], None).expect("push");+        let none = Carriageway::default();+        sink.push(1, &class, &[7, 8, 9], None, 0, &[], &[], none, None).expect("push");+        sink.push(2, &class, &[11, 12, 13], Some("named"), 0, &[], &[], none, None).expect("push");         sink.finish().expect("finish");          let whole = std::fs::read(&path).expect("read");@@ -1814,7 +1931,7 @@ mod tests {         let class = Class::line(dict::LAYER_ROADS, schema::kind("highway"), 3);         let refs: Vec<i64> = (0..1000).map(|i| 10_000_000_000 + i).collect();         let mut sink = WaySink::create(&path).expect("create");-        sink.push(1, &class, &refs, None, 0, &[], &[], None).expect("push");+        sink.push(1, &class, &refs, None, 0, &[], &[], Carriageway::default(), None).expect("push");         sink.finish().expect("finish");         let bytes = std::fs::metadata(&path).expect("metadata").len();         // The first ref is a full-width id; every one after it is a delta of 1, one byte.@@ -1828,14 +1945,15 @@ mod tests {         let path = temp("ways_named");         let class = Class::line(dict::LAYER_POI, schema::kind("cafe"), 15);         let mut sink = WaySink::create(&path).expect("create");-        sink.push(1, &class, &[7, 8], Some("Café"), 0, &[], &[], None).expect("push");-        sink.push(2, &class, &[9], None, 0, &[], &[], None).expect("push");+        let none = Carriageway::default();+        sink.push(1, &class, &[7, 8], Some("Café"), 0, &[], &[], none, None).expect("push");+        sink.push(2, &class, &[9], None, 0, &[], &[], none, None).expect("push");         sink.finish().expect("finish");         let mut reader = WayReader::open(&path).expect("open");         let mut refs: Vec<i64> = Vec::new();-        let (_, _, name, _, _, _, _) = reader.next(&mut refs).expect("read").expect("a way");+        let (_, _, name, _, _, _, _, _) = reader.next(&mut refs).expect("read").expect("a way");         assert_eq!(name.as_deref(), Some("Café"), "UTF-8 survives the spill");-        let (_, _, name, _, _, _, _) = reader.next(&mut refs).expect("read").expect("a way");+        let (_, _, name, _, _, _, _, _) = reader.next(&mut refs).expect("read").expect("a way");         assert_eq!(name, None);         let _ = std::fs::remove_file(&path);     }
scripts/maps/mamaps_build/src/tiler.rs
diff --git a/scripts/maps/mamaps_build/src/tiler.rs b/scripts/maps/mamaps_build/src/tiler.rsindex ad82b3b3d5..52386f2ac1 100644--- a/scripts/maps/mamaps_build/src/tiler.rs+++ b/scripts/maps/mamaps_build/src/tiler.rs@@ -285,6 +285,11 @@ pub struct ChunkEntry {     /// remapped alongside it when `coalesce` and stage C rebuild the feature vector, so the body's     /// building side table stays aligned to the features it describes.     pub buildings: Vec<BuildingAttrs>,+    /// The per-feature directional carriageway split, dense-parallel to `layer.features` on the+    /// `roads` layer and empty on every other. Rides the merge like `ids` (concatenated, not+    /// remapped) and is remapped alongside it when `coalesce` rebuilds the feature vector. Stage C+    /// is not given it: a road is a line, and `rings::normalise` never drops one.+    pub carriageways: Vec<tilecodec::mamaps::body::Carriageway>, }  impl ChunkEntry {@@ -295,6 +300,7 @@ impl ChunkEntry {             ids: Vec::new(),             turn_lanes: Vec::new(),             buildings: Vec::new(),+            carriageways: Vec::new(),         }     } @@ -407,7 +413,7 @@ pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomSta                 break;             }             let encoding = std::time::Instant::now();-            let done = encode_batch(batch, settings.dem.as_ref())?;+            let done = encode_batch(batch, settings.dem.as_ref(), store.conventions())?;             stats.encode_ms += encoding.elapsed().as_millis() as u64;             let appending = std::time::Instant::now();             for (id, encoded, rings, lines) in done {@@ -1029,6 +1035,8 @@ fn concatenate(into: &mut ChunkEntry, from: ChunkEntry) {     into.turn_lanes.extend(from.turn_lanes);     // The building attrs ride the same way, dense-parallel to the buildings layer's features.     into.buildings.extend(from.buildings);+    // And the carriageways, dense-parallel to the roads layer's.+    into.carriageways.extend(from.carriageways); }  /// Stage C and body encoding for a batch of merged tiles, in parallel, results in tile order.@@ -1250,7 +1258,11 @@ fn add_ocean(layers: &mut Vec<ChunkEntry>) {     // the sea has no OSM element to name anyway. } -fn encode_batch(batch: Vec<(u64, Vec<ChunkEntry>)>, dem: Option<&crate::dem::Dem>) -> Result<Vec<Encoded>> {+fn encode_batch(+    batch: Vec<(u64, Vec<ChunkEntry>)>,+    dem: Option<&crate::dem::Dem>,+    conventions: &crate::schema::boundaries::Conventions,+) -> Result<Vec<Encoded>> {     let min_len = par::min_task_len(batch.len());     let on = timing();     par::install(|| {@@ -1284,6 +1296,7 @@ fn encode_batch(batch: Vec<(u64, Vec<ChunkEntry>)>, dem: Option<&crate::dem::Dem                             Some(&mut entry.ids),                             Some(&mut entry.turn_lanes),                             Some(&mut entry.buildings),+                            Some(&mut entry.carriageways),                         ));                     }                     // **The sea.** There is no `natural=ocean` in OpenStreetMap — water is defined@@ -1427,6 +1440,42 @@ fn encode_batch(batch: Vec<(u64, Vec<ChunkEntry>)>, dem: Option<&crate::dem::Dem                         buildings                             .push((entry.layer.layer_id, std::mem::take(&mut entry.buildings)));                     }+                    // The carriageway side table, built like the two above and checked against the+                    // feature count for the same reason.+                    //+                    // A tile where no road's split was ever surveyed usually emits no table at all,+                    // so it costs nothing for lane data that does not exist. The exception is a+                    // tile whose country is not the default one: the convention only reaches the+                    // wire alongside a table, and a tile of untagged residential streets in Tokyo+                    // still has to say that traffic keeps left. So an all-default table is kept+                    // exactly when there is a non-default convention to carry with it.+                    let (z, x, y) = tilecodec::pmtiles::tile_zxy(id);+                    let convention = conventions.at_tile(z, x, y);+                    let mut carriageways: Vec<(u8, Vec<tilecodec::mamaps::body::Carriageway>)> =+                        Vec::new();+                    for entry in &mut layers {+                        if entry.carriageways.is_empty() {+                            continue;+                        }+                        if entry.carriageways.len() != entry.layer.features.len() {+                            return err(format!(+                                "layer {} has {} carriageway record(s) for {} feature(s) after \+                                 coalesce and stage C",+                                entry.layer.layer_id,+                                entry.carriageways.len(),+                                entry.layer.features.len(),+                            ));+                        }+                        if convention == tilecodec::mamaps::body::MarkingConvention::default()+                            && entry.carriageways.iter().all(|c| c.is_empty())+                        {+                            entry.carriageways.clear();+                            continue;+                        }+                        carriageways+                            .push((entry.layer.layer_id, std::mem::take(&mut entry.carriageways)));+                    }+                    let convention = (!carriageways.is_empty()).then_some(convention);                     let body = Body {                         extent: EXTENT as u16,                         layers: layers.into_iter().map(|entry| entry.layer).collect(),@@ -1438,15 +1487,9 @@ fn encode_batch(batch: Vec<(u64, Vec<ChunkEntry>)>, dem: Option<&crate::dem::Dem                         // not from OSM geometry. When a dataset was given, sample its grid onto this                         // tile's z/x/y; a tile with no DEM under it (ocean, off-coverage) gets None                         // and stays 16-byte. Without a dataset every tile stays None.-                        heightmap: dem.and_then(|d| {-                            let (z, x, y) = tilecodec::pmtiles::tile_zxy(id);-                            d.heightmap_for(z, x, y)-                        }),-                        // The carriageway table and its marking convention are not wired into the-                        // tiler yet; every tile stays without one, which the renderer reads as-                        // "nothing known beyond the lane count" and falls back to a plain stroke.-                        carriageways: Vec::new(),-                        convention: None,+                        heightmap: dem.and_then(|d| d.heightmap_for(z, x, y)),+                        carriageways,+                        convention,                     };                     let encoded = timed(on, &SERIALIZE_NANOS, || {                         tilecodec::mamaps::body::serialize_into(&body, scratch)@@ -1588,6 +1631,7 @@ fn push(entry: &mut ChunkEntry, feature: &Feature, geometry: &IntGeometry) -> (u                         forward: feature.turn_fwd.clone(),                         backward: feature.turn_bwd.clone(),                     });+                    entry.carriageways.push(feature.carriageway);                 }                 added.0 += 1;             }@@ -1710,6 +1754,7 @@ mod tests {             turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         }     } @@ -1733,6 +1778,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let features = vec![poi, lake(-120.0, 35.0, 0.01, 0)];         let (bytes, _) = build(&spilled(&features), &settings(14, 14)).expect("build");@@ -1774,6 +1820,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let (bytes, _) = build(&spilled(&[road]), &settings(14, 14)).expect("build");         // The reader's own version byte, so an older reader rejects the archive cleanly.@@ -1824,6 +1871,7 @@ mod tests {             turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: Some(attrs),+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let (bytes, _) = build(&spilled(&[building]), &settings(14, 14)).expect("build");         assert_eq!(@@ -1866,6 +1914,7 @@ mod tests {             turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: Some(BuildingAttrs::default()),+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let (bytes, _) = build(&spilled(&[building]), &settings(14, 14)).expect("build");         for (_, _, body) in &tilecodec::mamaps::read::read_all(&bytes).expect("read") {@@ -1909,6 +1958,7 @@ mod tests {             turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         // A ramp grid: sample(col, row) = 32768 + row*10 + col, so a read-back names its cell.         let mut grid = Vec::with_capacity(dim as usize * dim as usize);@@ -1967,6 +2017,7 @@ mod tests {             turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let river = Feature {             class: Class::line(dict::LAYER_WATER, crate::schema::kind("river"), 12),@@ -1981,6 +2032,7 @@ mod tests {             turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let (bytes, _) = build(&spilled(&[road, river]), &settings(14, 14)).expect("build");         let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");@@ -2025,6 +2077,7 @@ mod tests {             turn_fwd: fwd,             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let (bytes, _) = build(&spilled(&[road]), &settings(14, 14)).expect("build");         let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");@@ -2074,6 +2127,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             });         }         let (bytes, _) = build(&spilled(&features), &settings(14, 14)).expect("build");@@ -2126,6 +2180,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let traffic = |c: i32, r: i32, i: u64| Feature {             class: traffic_class(),@@ -2140,6 +2195,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };          let mut base = Vec::new();@@ -2201,6 +2257,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let border = Feature {             class: Class::line(@@ -2223,6 +2280,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         let (bytes, _) = build(&spilled(&[region, border]), &settings(14, 14)).expect("build");         let entries = tilecodec::mamaps::read::read_all(&bytes).expect("read");@@ -2276,6 +2334,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         };         // One patch of land, and a lake sitting on it so the water layer already exists. Plus a         // marine protected area out at sea with no land under it at all — a real `landuse` polygon@@ -2295,6 +2354,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             },             Feature {                 class: Class::area(@@ -2313,6 +2373,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             },         ];         let store = spilled(&features);@@ -2381,6 +2442,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         }];         let store = spilled(&features);         let (bytes, _) = build(&store, &settings(8, 8)).expect("build");@@ -2492,6 +2554,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             },         ];         let first = build(&spilled(&features), &settings(0, 8)).expect("first").0;@@ -2520,6 +2583,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             },         ];         let (bytes, _) = build(&spilled(&features), &settings(14, 14)).expect("build");@@ -2553,6 +2617,7 @@ mod tests {                     turn_fwd: Vec::new(),             turn_bwd: Vec::new(),             building: None,+            carriageway: tilecodec::mamaps::body::Carriageway::default(),         }];         let (_, stats) = build(&spilled(&features), &settings(6, 14)).expect("build");         let at = |z: u8| stats.iter().find(|s| s.zoom == z).expect("zoom").points;@@ -2574,6 +2639,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             });             // A line as well, so the merge has to rebase a `GEOM_LINE` feature's parts too, and a             // long one so it crosses tiles rather than sitting inside one.@@ -2586,6 +2652,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             });         }         features@@ -2675,6 +2742,7 @@ mod tests {                             turn_fwd: Vec::new(),                 turn_bwd: Vec::new(),                 building: None,+                carriageway: tilecodec::mamaps::body::Carriageway::default(),             })             .collect();         let store = spilled(&features);@@ -2705,7 +2773,7 @@ mod tests {     #[test]     fn concatenating_two_chunks_of_a_layer_is_one_layer() {         let class = Class::area(dict::LAYER_WATER, crate::schema::kind("lake"), 0);-        let feature = Feature { class, geometry: square(0.0, 0.0, 1.0), name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0, turn_fwd: Vec::new(), turn_bwd: Vec::new(), building: None };+        let feature = Feature { class, geometry: square(0.0, 0.0, 1.0), name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0, turn_fwd: Vec::new(), turn_bwd: Vec::new(), building: None, carriageway: tilecodec::mamaps::body::Carriageway::default() };         // Tile-local already, so the fixture is about the arenas rather than about projection, and         // big enough that no minimum-area floor can drop it.         let box_at = |x: i32| {@@ -2824,6 +2892,7 @@ mod tests {                                     turn_fwd: Vec::new(),                     turn_bwd: Vec::new(),                     building: None,+                    carriageway: tilecodec::mamaps::body::Carriageway::default(),                 });             }             let store = spilled(&features);
scripts/maps/mamaps_build/src/tilespill.rs
diff --git a/scripts/maps/mamaps_build/src/tilespill.rs b/scripts/maps/mamaps_build/src/tilespill.rsindex c91c3737c1..a3990119c4 100644--- a/scripts/maps/mamaps_build/src/tilespill.rs+++ b/scripts/maps/mamaps_build/src/tilespill.rs@@ -73,7 +73,10 @@ use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; -use tilecodec::mamaps::body::{BuildingAttrs, Feature as BodyFeature, Layer as BodyLayer, Part};+use tilecodec::mamaps::body::{+    BuildingAttrs, Carriageway, Feature as BodyFeature, Layer as BodyLayer, Part,+    CARRIAGEWAY_RECORD_LEN,+}; use tilecodec::proto::{err, Error, Result};  use crate::tiler::ChunkEntry;@@ -460,6 +463,27 @@ impl ChunkReader<'_> {                 consumed += BUILDING_BYTES;             }         }+        // The carriageway section, last, when the flag is set: one [`CARRIAGEWAY_RECORD_LEN`]+        // record per feature, dense.+        if header.has_carriageways {+            entry.carriageways = Vec::with_capacity(header.features);+            for _ in 0..header.features {+                self.fill(CARRIAGEWAY_RECORD_LEN)?;+                let o = self.used;+                entry.carriageways.push(Carriageway {+                    forward: self.buf[o],+                    backward: self.buf[o + 1],+                    solid_dividers: u32::from_le_bytes([+                        self.buf[o + 2],+                        self.buf[o + 3],+                        self.buf[o + 4],+                        self.buf[o + 5],+                    ]),+                });+                self.used += CARRIAGEWAY_RECORD_LEN;+                consumed += CARRIAGEWAY_RECORD_LEN;+            }+        }         self.left -= 1;         self.spill.read.fetch_add(consumed as u64, Ordering::Relaxed);         self.spill.read_entries.fetch_add(1, Ordering::Relaxed);@@ -524,11 +548,18 @@ fn entry_bytes(entry: &ChunkEntry) -> Result<u64> {     } else {         entry.buildings.len() as u64 * BUILDING_BYTES as u64     };+    // And the carriageway section, likewise fixed-width and one per feature.+    let carriageways_bytes = if entry.carriageways.is_empty() {+        0+    } else {+        entry.carriageways.len() as u64 * CARRIAGEWAY_RECORD_LEN as u64+    };     Ok(ENTRY_HEADER_BYTES as u64         + payload_bytes(features, parts, coords, ids)         + names_bytes         + turns_bytes-        + buildings_bytes)+        + buildings_bytes+        + carriageways_bytes) }  /// The payload width implied by an entry's four counts. A pure function of the header, which is@@ -551,13 +582,19 @@ fn encode_entry(tile: u64, layer_id: u8, entry: &ChunkEntry, out: &mut Vec<u8>)     out[base + 16..base + 20].copy_from_slice(&(layer.coords.len() as u32).to_le_bytes());     out[base + 20] = layer_id;     // Byte 21 flags a turn-lane section after the names; byte 22 a building section after that;-    // byte 23 stays reserved zero. The building section is `features` records (one per feature,-    // dense), each a BUILDING_BYTES packed [`BuildingAttrs`]. Present only for a `buildings` tile-    // that had S3DB attributes in it.+    // byte 23 a carriageway section after that. The building section is `features` records (one per+    // feature, dense), each a BUILDING_BYTES packed [`BuildingAttrs`]. Present only for a+    // `buildings` tile that had S3DB attributes in it.+    //+    // The carriageway section is the same shape for the `roads` layer. It has to be here rather+    // than reconstructed later: a side table that never reaches the spill is dropped on every+    // build that spills a zoom, and the archive comes back with no lane markings and no error.     let has_turns = !entry.turn_lanes.is_empty();     let has_buildings = !entry.buildings.is_empty();+    let has_carriageways = !entry.carriageways.is_empty();     out[base + 21] = has_turns as u8;     out[base + 22] = has_buildings as u8;+    out[base + 23] = has_carriageways as u8;     out[base + 24..base + 28].copy_from_slice(&(entry.names.len() as u32).to_le_bytes());     out[base + 28..base + 32].copy_from_slice(&(entry.ids.len() as u32).to_le_bytes());     for feature in &layer.features {@@ -616,6 +653,15 @@ fn encode_entry(tile: u64, layer_id: u8, entry: &ChunkEntry, out: &mut Vec<u8>)             out.extend_from_slice(&a.roof_colour.to_le_bytes());         }     }+    // The carriageway section, last, when present. One record per feature, in the same field order+    // the body's own [`CARRIAGEWAY_RECORD_LEN`] record uses.+    if has_carriageways {+        for c in &entry.carriageways {+            out.push(c.forward);+            out.push(c.backward);+            out.extend_from_slice(&c.solid_dividers.to_le_bytes());+        }+    } }  struct EntryHeader {@@ -628,21 +674,22 @@ struct EntryHeader {     ids: usize,     has_turns: bool,     has_buildings: bool,+    has_carriageways: bool, }  fn entry_header(head: &[u8; ENTRY_HEADER_BYTES]) -> Result<EntryHeader> {-    // Byte 23 must be zero: a newer writer would use it, so a nonzero value there means the reader-    // is the wrong version for the file. Bytes 21 (turn-lane flag) and 22 (building flag) are 0 or-    // 1; anything else is likewise a version mismatch. Guessing would decode a field that moved.-    if head[23] != 0 {-        return err("a tile chunk entry has a nonzero reserved tail");-    }+    // Bytes 21 (turn-lane flag), 22 (building flag) and 23 (carriageway flag) are 0 or 1; anything+    // else means the reader is the wrong version for the file, because a newer writer would be+    // using the spare values. Guessing would decode a field that moved.     if head[21] > 1 {         return err("a tile chunk entry has an unknown turn-lane flag");     }     if head[22] > 1 {         return err("a tile chunk entry has an unknown building flag");     }+    if head[23] > 1 {+        return err("a tile chunk entry has an unknown carriageway flag");+    }     let u32_at =         |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes")) as usize;     let header = EntryHeader {@@ -655,6 +702,7 @@ fn entry_header(head: &[u8; ENTRY_HEADER_BYTES]) -> Result<EntryHeader> {         ids: u32_at(28),         has_turns: head[21] == 1,         has_buildings: head[22] == 1,+        has_carriageways: head[23] == 1,     };     // A layer either has an id per feature or none at all. Checked before the length so a garbled     // count is refused as the desync it is rather than as a size that happens not to fit.@@ -737,6 +785,7 @@ fn decode_fixed(header: &EntryHeader, payload: &[u8]) -> Result<ChunkEntry> {         ids,         turn_lanes: Vec::new(),         buildings: Vec::new(),+        carriageways: Vec::new(),     }) } @@ -829,7 +878,7 @@ mod tests {         for (i, feature) in layer.features.iter_mut().enumerate() {             feature.parts_offset = i as u32;         }-        ChunkEntry { layer, names: names.iter().map(|s| s.to_string()).collect(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new() }+        ChunkEntry { layer, names: names.iter().map(|s| s.to_string()).collect(), ids: Vec::new(), turn_lanes: Vec::new(), buildings: Vec::new(), carriageways: Vec::new() }     }      /// Every shape an entry can take, including the empty ones that a naive length check would let@@ -842,6 +891,7 @@ mod tests {             ids: Vec::new(),             turn_lanes: Vec::new(),             buildings: Vec::new(),+            carriageways: Vec::new(),         };         vec![             // Empty layer: no features, no parts, no coords.@@ -866,6 +916,7 @@ mod tests {                     ids: Vec::new(),                     turn_lanes: Vec::new(),                     buildings: Vec::new(),+                    carriageways: Vec::new(),                 },             ),             // The extremes of every field: `u16::MAX` kinds, `i16` at both ends, a hole.@@ -895,6 +946,7 @@ mod tests {                     ids: Vec::new(),                     turn_lanes: Vec::new(),                     buildings: Vec::new(),+                    carriageways: Vec::new(),                 },             ),             // Several layers on one tile, which is what the merge collapses.@@ -916,6 +968,7 @@ mod tests {                     ids: Vec::new(),                     turn_lanes: Vec::new(),                     buildings: Vec::new(),+                    carriageways: Vec::new(),                 },             ),             ((5, 10), ChunkEntry::new(10)),@@ -935,6 +988,20 @@ mod tests {                     ..entry(8, vec![named(3, 1), named(5, 0), named(7, 0)], &["Bar"])                 },             ),+            // The carriageway arena, which only `roads` carries: a divided road, a one-way with+            // every lane forward, and a road whose split was never surveyed — all three in one+            // entry, because the section is dense and the unsurveyed one still needs its slot.+            (+                (8, 4),+                ChunkEntry {+                    carriageways: vec![+                        Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 },+                        Carriageway { forward: 2, backward: 0, solid_dividers: u32::MAX },+                        Carriageway::default(),+                    ],+                    ..entry(4, vec![named(1, 0), named(2, 0), named(3, 0)], &[])+                },+            ),         ]     } @@ -958,6 +1025,59 @@ mod tests {         spill.check_books().expect("the books balance");     } +    /// **The silent one.** A `ChunkEntry.carriageways` that never reaches the spill is dropped on+    /// every build that spills chunks — which is every real build — and the archive comes out with+    /// no carriageway table, no lane markings and no error anywhere. Nothing else in this module+    /// would notice: the books balance, the features are all there, and the map merely looks like+    /// the renderer is at fault.+    ///+    /// So the section is asserted on its own rather than only inside `every_layer`: a road with a+    /// divided carriageway, a one-way with every lane forward, and one whose split was never+    /// surveyed — the last because the section is dense and its slot has to survive too.+    #[test]+    fn a_carriageway_section_survives_the_scratch_file() {+        let spill = ChunkSpill::create(tmp("carriageways")).expect("create");+        let want = ChunkEntry {+            carriageways: vec![+                Carriageway { forward: 3, backward: 1, solid_dividers: 0b101 },+                Carriageway { forward: 2, backward: 0, solid_dividers: u32::MAX },+                Carriageway::default(),+            ],+            ..entry(4, vec![named(1, 0), named(2, 0), named(3, 0)], &[])+        };+        let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();+        map.insert((1, 4), want.clone());+        let at = spill.write_chunk(map).expect("write");+        let got = drain(&spill, &at, 1 << 16);+        assert_eq!(got, vec![((1u64, 4u8), want)]);+        // And the books, which are what would catch a section written but not accounted for.+        spill.check_books().expect("the books balance");+    }++    /// A layer with no surveyed split writes no section at all, so a `boundaries` or `water` tile+    /// pays nothing for a table that only roads ever have.+    #[test]+    fn an_entry_with_no_carriageways_writes_no_section() {+        let spill = ChunkSpill::create(tmp("nocarriageways")).expect("create");+        let bare = entry(4, vec![named(1, 0), named(2, 0)], &[]);+        let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();+        map.insert((1, 4), bare.clone());+        let at = spill.write_chunk(map).expect("write");+        let with = ChunkEntry {+            carriageways: vec![Carriageway::default(); 2],+            ..entry(4, vec![named(1, 0), named(2, 0)], &[])+        };+        let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();+        map.insert((1, 4), with);+        let at_with = spill.write_chunk(map).expect("write");+        assert_eq!(+            at_with.len - at.len,+            2 * CARRIAGEWAY_RECORD_LEN as u64,+            "the section costs exactly one record per feature and nothing when absent",+        );+        assert_eq!(drain(&spill, &at, 1 << 16), vec![((1u64, 4u8), bare)]);+    }+     /// The read accounting survives a buffer compaction mid-entry. Names are pulled one inline     /// length at a time, so a narrow window tops the buffer up (compacting it) halfway through     /// an entry's names — and the bytes-read counter used to difference two offsets across that@@ -996,7 +1116,7 @@ mod tests {             layer.coords.push((i as i16, 0));         }         let mut map: BTreeMap<(u64, u8), ChunkEntry> = BTreeMap::new();-        map.insert((7, 8), ChunkEntry { layer, names: names.clone(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new() });+        map.insert((7, 8), ChunkEntry { layer, names: names.clone(), ids: Vec::new() , turn_lanes: Vec::new(), buildings: Vec::new(), carriageways: Vec::new() });         let at = spill.write_chunk(map).expect("write");         // Window of one header: every name tops up (and compacts) mid-entry.         let read = drain(&spill, &at, ENTRY_HEADER_BYTES);@@ -1095,12 +1215,21 @@ mod tests {         assert!(reader.next().is_err(), "a chunk with bytes past its last entry read as complete");     } +    /// Byte 23 was the reserved tail and is now the carriageway flag, so the three section flags+    /// are the whole of bytes 21..24. Each is 0 or 1: a spare value there means a newer writer put+    /// something in it, and guessing would decode a section that moved.     #[test]-    fn a_dirty_reserved_tail_errors() {-        let mut head = [0u8; ENTRY_HEADER_BYTES];+    fn an_unknown_section_flag_errors() {+        let head = [0u8; ENTRY_HEADER_BYTES];         entry_header(&head).expect("a zero header is legal");-        head[23] = 1;-        assert!(entry_header(&head).is_err(), "a nonzero reserved tail decoded");+        for flag in 21..24 {+            let mut set = head;+            set[flag] = 1;+            entry_header(&set).unwrap_or_else(|e| panic!("byte {flag} set is legal: {e:?}"));+            let mut spare = head;+            spare[flag] = 2;+            assert!(entry_header(&spare).is_err(), "byte {flag} decoded a spare value");+        }     }      /// The word that was the second reserved tail is now the id count, and an id count that is