Modern Apps git

← Modern-Apps.git

maps: bake intercity rail into transit tiles from z3

Commit
8b5c9ecd5beac8f4b6a902cb5020161e311862c9
Author
vayun-mathur <[email protected]>
When
2026-10-25 07:37 UTC (1 month ago)
Parents
28190e4

Diff

library/map/src/main/rust/src/style/paint_extra3.rs
diff --git a/library/map/src/main/rust/src/style/paint_extra3.rs b/library/map/src/main/rust/src/style/paint_extra3.rsindex 471de6f829..b301089b7c 100644--- a/library/map/src/main/rust/src/style/paint_extra3.rs+++ b/library/map/src/main/rust/src/style/paint_extra3.rs@@ -65,7 +65,8 @@ fn the_vendored_flat_style_parses() {             count(LayerKind::Line, true),             count(LayerKind::Symbol, true)         ),-        (0, 1, 7),+        // Two toggled lines: `transit-rail`, and `transit-intercity` below its floor.+        (0, 2, 7),         "the optional layer set",     );     assert_eq!(style.background, (0xFF80DEEA, 0xFF0D1B2A));
library/map/src/main/rust/src/style/paint_extra5.rs
diff --git a/library/map/src/main/rust/src/style/paint_extra5.rs b/library/map/src/main/rust/src/style/paint_extra5.rsindex 7c5cf60367..00b32f2876 100644--- a/library/map/src/main/rust/src/style/paint_extra5.rs+++ b/library/map/src/main/rust/src/style/paint_extra5.rs@@ -350,6 +350,23 @@ fn transit_lanes_step_with_zoom_over_a_constant_spacing() {     } } +/// Long-distance rail draws at country zoom, where it is the only transit in the archive+/// (`schema::transit::INTERCITY_MIN_ZOOM`), and hands over to `transit-rail` at its floor so the+/// two never draw the same line twice.+#[test]+fn intercity_rail_covers_the_zooms_below_the_network() {+    let intercity = find("transit-intercity");+    let rail = find("transit-rail");+    assert_eq!(intercity.min_zoom, 3);+    assert_eq!(intercity.max_zoom + 1, rail.min_zoom, "hands over exactly at the network floor");+    assert_eq!(intercity.toggle, Some(Toggle::Transit), "only with the transit layer on");+    assert_eq!(intercity.detail_ids, vec![super::detail_id("intercity").expect("an interned detail")]);+    for zoom in [3.0, 5.0, 7.0] {+        let width = intercity.width.at(zoom);+        assert!(width > 0.0 && width <= rail.width.at(zoom), "z{zoom}: {width} Dp");+    }+}+ /// The road carriageway: `roads-carriageway` is the road layer drawn as a surface, it only /// appears once the camera is close enough to make lane markings legible, and its width ramp is /// **one lane** rather than a whole road — the renderer multiplies by the feature's lane count,
library/map/src/main/rust/style/basemap.flat.json
diff --git a/library/map/src/main/rust/style/basemap.flat.json b/library/map/src/main/rust/style/basemap.flat.jsonindex 3157d2212f..7349ee58cb 100644--- a/library/map/src/main/rust/style/basemap.flat.json+++ b/library/map/src/main/rust/style/basemap.flat.json@@ -683,6 +683,20 @@       "width": 0.7,       "dash": [2, 0]     },+    {+      "id": "transit-intercity",+      "authored": "roads_rail",+      "source": "transit",+      "type": "line",+      "kinds": ["rail"],+      "details": ["intercity"],+      "toggle": "transit",+      "minzoom": 3,+      "maxzoom": 7,+      "light": "#8b93a8",+      "dark": "#4b5468",+      "width": { "interpolate": "linear", "stops": [[3, 1.5], [7, 2.5]] }+    },     {       "id": "transit-rail",       "authored": "roads_rail",
library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs b/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rsindex 56c99729cd..5055c6859f 100644--- a/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/dict/tables.rs@@ -310,4 +310,7 @@ pub const DETAILS: &[&str] = &[     "monorail",     // buildings     "yes",+    // transit lines: long-distance rail, carried from z3 so the intercity network reads at+    // country zoom. Appended, so every earlier id is unchanged.+    "intercity", ];
scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rsindex 0046388297..c268a1a517 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs@@ -33,6 +33,9 @@ #[path = "transit_shapes_extra2.rs"] mod extra2; +#[path = "transit_shapes_intercity.rs"]+mod intercity;+ #[path = "transit_shapes_extra.rs"] #[cfg(test)] mod extra;@@ -151,6 +154,8 @@ struct Line {     lanes: u8,     /// How far into its lane this piece sits, over 255. See [`bundle`].     taper: u8,+    /// Long-distance rail, carried from country zoom. See [`intercity`].+    intercity: bool, }  /// What one feed contributes, before the cross-feed passes.@@ -280,7 +285,7 @@ fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> {      let mut out = FeedLines { routes_kept: rail.len(), ..FeedLines::default() };     for (route_id, shape_ids) in &by_route {-        let (mode, color, fallback, route) = &rail[route_id.as_str()];+        let (mode, color, fallback, route, long_type) = &rail[route_id.as_str()];         let before = out.lines.len();         // Every distinct shape, whole. What a route publishes is one alignment per         // direction plus a short-turn or a branch variant or two, all of them overlapping,@@ -293,13 +298,11 @@ fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> {                 continue;             }             out.shapes_read += 1;+            let points: Vec<(i32, i32)> =+                shape.lat_e7.iter().zip(&shape.lon_e7).map(|(&lat, &lon)| (lat, lon)).collect();             out.lines.push(Line {-                points: shape-                    .lat_e7-                    .iter()-                    .zip(&shape.lon_e7)-                    .map(|(&lat, &lon)| (lat, lon))-                    .collect(),+                intercity: intercity::is_intercity(*long_type, &points),+                points,                 color: *color,                 mode,                 fallback: *fallback,@@ -319,9 +322,9 @@ fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> {     Ok(out) } -/// `route_id` → `(mode, colour, is a fallback colour, display name)` for every-/// rail route in the feed. Everything else, bus included, is dropped here.-fn rail_routes(routes: &Csv) -> HashMap<String, (&'static str, u32, bool, String)> {+/// `route_id` → `(mode, colour, is a fallback colour, display name, is long-distance by type)`+/// for every rail route in the feed. Everything else, bus included, is dropped here.+fn rail_routes(routes: &Csv) -> HashMap<String, (&'static str, u32, bool, String, bool)> {     let mut out = HashMap::new();     for row in &routes.rows {         let id = routes.get(row, "route_id");@@ -337,7 +340,10 @@ fn rail_routes(routes: &Csv) -> HashMap<String, (&'static str, u32, bool, String         let short = routes.get(row, "route_short_name").trim();         let long = routes.get(row, "route_long_name").trim();         let name = if short.is_empty() { long } else { short };-        out.insert(id.to_string(), (mode, color, fallback, name.to_string()));+        out.insert(+            id.to_string(),+            (mode, color, fallback, name.to_string(), intercity::is_long_distance_type(route_type)),+        );     }     out }@@ -351,7 +357,7 @@ fn rail_routes(routes: &Csv) -> HashMap<String, (&'static str, u32, bool, String /// pair, because the output has to be byte-identical between runs. fn shape_ids_by_route(     trips: &Csv,-    rail: &HashMap<String, (&'static str, u32, bool, String)>,+    rail: &HashMap<String, (&'static str, u32, bool, String, bool)>, ) -> BTreeMap<String, BTreeSet<String>> {     let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();     for row in &trips.rows {
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rsindex 9715a8c55a..ff5138c1ad 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs@@ -143,7 +143,11 @@ pub(crate) fn run_with_timer(             //             // A ceiling rather than a ban, so the two-services-on-one-track case the tests             // pin still works. Above it the track is already saying everything it can.-            if mode_cover.crowd_reaches_walked(&walked, MAX_SERVICES_PER_TRACK) {+            //+            // Intercity lines are exempt: at country zoom they are the only transit drawn, so+            // losing one to a crowded shared corridor (the Northeast Corridor carries a dozen+            // commuter services) would cut a gap in the national network.+            if !line.intercity && mode_cover.crowd_reaches_walked(&walked, MAX_SERVICES_PER_TRACK) {                 crowded += 1;                 continue;             }@@ -199,8 +203,14 @@ pub(crate) fn run_with_timer(         write!(             buf,             "]}},\"properties\":{{\"color\":\"{:06X}\",\"mode\":\"{}\",\"ordinal\":{},\-             \"lanes\":{},\"taper\":{},\"route\":\"",-            line.color, line.mode, line.ordinal, line.lanes, line.taper,+             \"lanes\":{},\"taper\":{},{}\"route\":\"",+            intercity::drawn_color(line.color, line.intercity, fallback_color(line.mode)),+            line.mode,+            line.ordinal,+            line.lanes,+            line.taper,+            // Only when set, so every other line is written exactly as before.+            if line.intercity { "\"intercity\":1," } else { "" },         )         .map_err(io_err)?;         json_escape(line.route.as_bytes(), &mut buf);@@ -219,11 +229,12 @@ pub(crate) fn run_with_timer(          {without_shape} with no usable shape, {shapes_read} shape(s) read, \          {deduped} republished byte-for-byte, {merged} already drawn in their colour, \          {crowded} over track already carrying {MAX_SERVICES_PER_TRACK} services, \-         {} line(s), {bundled} in a shared corridor, \+         {} line(s), {} intercity, {bundled} in a shared corridor, \          {fell_back} on a per-mode fallback colour)",         out_path.display(),         specs.len(),         lines.len(),+        lines.iter().filter(|l| l.intercity).count(),     );     Ok(()) }
scripts/maps/gtfs_ingest/src/bin/transit_shapes_intercity.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_intercity.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_intercity.rsnew file mode 100644index 0000000000..a6bbeb514c--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_intercity.rs@@ -0,0 +1,62 @@+//! Which rail lines are intercity, and the colour they draw in at country zoom.+//!+//! An intercity line is carried from z3 (`mamaps_build`'s `schema::transit`), where it is the+//! only transit drawn, so it has to be both correctly picked out and readable on its own.++use gtfs_ingest::shapes::distance_m;++/// A rail shape at least this long, end to end along its path, is intercity whatever its+/// `route_type`: Amtrak, VIA and Brightline all publish plain `2`. Commuter rail stays under it.+pub(crate) const INTERCITY_LENGTH_M: f64 = 150_000.0;++/// Relative luminance (0..1) above which an intercity line takes the train fallback colour.+/// Amtrak publishes `#CAE4F1` (about 0.74), which vanishes on the light basemap at country+/// zoom; VIA's `#FFCB06` (about 0.63) still reads and is kept.+const MAX_LUMINANCE: f64 = 0.7;++/// GTFS extended types that name long-distance rail outright: high speed, long distance,+/// inter-regional and sleeper.+pub(crate) fn is_long_distance_type(route_type: u32) -> bool {+    matches!(route_type, 101 | 102 | 103 | 105)+}++pub(crate) fn is_intercity(long_distance_type: bool, points: &[(i32, i32)]) -> bool {+    long_distance_type+        || points.windows(2).map(|w| distance_m(w[0], w[1])).sum::<f64>() >= INTERCITY_LENGTH_M+}++/// The colour a line is written with: its own, unless it is intercity and too pale to read.+pub(crate) fn drawn_color(color: u32, intercity: bool, fallback: u32) -> u32 {+    if intercity && luminance(color) > MAX_LUMINANCE { fallback } else { color }+}++fn luminance(color: u32) -> f64 {+    let channel = |shift: u32| {+        let c = f64::from((color >> shift) & 0xFF) / 255.0;+        if c <= 0.039_28 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }+    };+    0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0)+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn long_or_typed_rail_is_intercity() {+        // ~1.1 degrees of latitude per step: 2 steps is ~222 km.+        let long = [(370_000_000, -1_220_000_000), (380_000_000, -1_220_000_000), (390_000_000, -1_220_000_000)];+        let short = [(370_000_000, -1_220_000_000), (375_000_000, -1_220_000_000)];+        assert!(is_intercity(false, &long), "222 km of plain type-2 rail");+        assert!(!is_intercity(false, &short), "a 56 km commuter line");+        assert!(is_intercity(is_long_distance_type(102), &short), "type 102 is long distance");+        assert!(!is_long_distance_type(2) && !is_long_distance_type(109));+    }++    #[test]+    fn pale_intercity_colours_take_the_fallback() {+        assert_eq!(drawn_color(0xCAE4F1, true, 0x0057A8), 0x0057A8, "Amtrak's published colour");+        assert_eq!(drawn_color(0xFFCB06, true, 0x0057A8), 0xFFCB06, "VIA yellow reads");+        assert_eq!(drawn_color(0xCAE4F1, false, 0x0057A8), 0xCAE4F1, "only intercity lines change");+    }+}
scripts/maps/mamaps_build/src/schema/transit.rs
diff --git a/scripts/maps/mamaps_build/src/schema/transit.rs b/scripts/maps/mamaps_build/src/schema/transit.rsindex 13958cdbe2..3dd51a7624 100644--- a/scripts/maps/mamaps_build/src/schema/transit.rs+++ b/scripts/maps/mamaps_build/src/schema/transit.rs@@ -49,22 +49,29 @@ const MODES: &[&str] = &["subway", "light_rail", "tram", "train", "monorail"]; /// whole network first reads, and that is the trunk's. const MIN_ZOOM: u8 = 8; +/// The zoom long-distance rail surfaces at.+///+/// The one exception to the single floor: an Amtrak or VIA line is the network at country zoom,+/// where nothing else on this layer would read. `transit_shapes` marks these lines `intercity`.+const INTERCITY_MIN_ZOOM: u8 = 3;+ /// A transit line's class: layer `transit`, kind `rail`, detail naming the mode. /// /// The kind stays `rail` (what the reference style's `roads_rail` matches) while the detail /// distinguishes a subway from a tram — which is what lets the renderer vary width by mode-/// while keying colour off `transit_color`.-pub fn transit_class(mode: &str) -> Option<Class> {+/// while keying colour off `transit_color`. An intercity line's detail is `intercity` rather+/// than its mode, which is what the style's country-zoom `transit-intercity` filters on.+pub fn transit_class(mode: &str, intercity: bool) -> Option<Class> {     if !MODES.contains(&mode) {         return None;     }     Some(Class {         layer: LAYER_TRANSIT,         kind: kind("rail"),-        kind_detail: detail(mode),+        kind_detail: detail(if intercity { "intercity" } else { mode }),         flags: 0,         area: false,-        min_zoom: MIN_ZOOM,+        min_zoom: if intercity { INTERCITY_MIN_ZOOM } else { MIN_ZOOM },         min_area_px: 0.0,     }) }@@ -130,7 +137,11 @@ pub fn stream_routes(         let Some(mode) = prop(&feature.props, "mode") else {             return Err(at("no `mode` property"));         };-        let Some(class) = transit_class(&mode) else {+        // Absent is an ordinary line, like the lane inputs below; present and not 0/1 is an error.+        let Some(intercity) = byte_prop(&feature.props, "intercity", 0).filter(|v| *v <= 1) else {+            return Err(at("an `intercity` property that is not 0 or 1"));+        };+        let Some(class) = transit_class(&mode, intercity == 1) else {             return Err(at(&format!("`{mode}` is not a mode this layer carries")));         };         let Some(color) = prop(&feature.props, "color").as_deref().and_then(hex_rrggbb) else {@@ -270,7 +281,7 @@ mod tests {     #[test]     fn every_mode_has_a_class_and_they_all_share_one_floor() {         for mode in MODES {-            let class = transit_class(mode).expect("a class");+            let class = transit_class(mode, false).expect("a class");             assert_eq!(class.layer, dict::LAYER_TRANSIT);             assert_eq!(dict::KINDS[class.kind as usize - 1], "rail");             assert_eq!(dict::DETAILS[class.kind_detail as usize - 1], *mode);@@ -280,7 +291,42 @@ mod tests {             // features the archive does not hold.             assert_eq!(class.min_zoom, 8, "{mode}");         }-        assert!(transit_class("bus").is_none());+        assert!(transit_class("bus", false).is_none());+    }++    #[test]+    fn an_intercity_line_surfaces_at_country_zoom() {+        let class = transit_class("train", true).expect("a class");+        assert_eq!(dict::DETAILS[class.kind_detail as usize - 1], "intercity");+        assert_eq!(class.min_zoom, 3);+        assert_eq!(dict::KINDS[class.kind as usize - 1], "rail", "still drawn by transit-rail");+        assert!(transit_class("bus", true).is_none(), "still only the rail modes");++        let path = scratch("intercity.geojsonseq");+        let coords = "[-122.4,37.7],[-118.2,34.0]";+        std::fs::write(+            &path,+            format!(+                "{}\n{}\n",+                feature("0057A8", "train", coords).replace("\"mode\":\"train\"", "\"mode\":\"train\",\"intercity\":1"),+                feature("0057A8", "train", coords),+            ),+        )+        .expect("write");+        let spill = scratch("intercity.features");+        let mut sink = crate::store::Sink::create(&spill).expect("sink");+        assert_eq!(stream_routes(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).expect("read"), 2);+        let store = sink.finish(&spill).expect("finish");+        let mut reader = store.reader().expect("reader");+        let floors: Vec<u8> = std::iter::from_fn(|| reader.next().expect("read")).map(|f| f.class.min_zoom).collect();+        assert_eq!(floors, vec![3, 8], "flagged, then an ordinary line");++        std::fs::write(&path, feature("0057A8", "train", coords).replace("\"mode\":\"train\"", "\"mode\":\"train\",\"intercity\":2") + "\n")+            .expect("write");+        let mut sink = crate::store::Sink::create(&spill).expect("sink");+        assert!(stream_routes(&path, (-180.0, -90.0, 180.0, 90.0), &mut sink).is_err(), "2 is not a flag");+        let _ = std::fs::remove_file(&path);+        let _ = std::fs::remove_file(&spill);     }      #[test]