maps: dedupe transit lines per route-direction, fix line colours
- Commit
76108569870a99396cdc763441e497767bb38054- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 03:11 UTC (4 days ago)
- Parents
de572f3
The transit layer drew every GTFS shape variant it was handed: a route's two directions, its short-turn and branch patterns, and republished feeds' copies of one alignment all arrived as separate features a few metres apart. The tile tessellator stroked every one and the pack overlay fanned every pattern, so one line became a bundle of vaguely parallel lines that separated further on zoom-in. Colourless routes (GTFS route_color absent) fell into the basemap grey mesh in the tile renderer and into one generic red fallback in the pack overlay, so not every place drew its lines coloured. Fix, at each of the three places the lines are drawn: - library/map tile renderer: a transit feature whose length is already drawn in its colour (95% within 30 m, direction-insensitive) is dropped at tessellation; a feature with transit_color 0 takes the per-mode GTFS fallback colour for its kind_detail instead of the layer grey. - maps pack layer (Rust): serving patterns are collapsed to one geometry per route+direction (feed, name, colour, ordered termini; longest wins), and the whole-line cover rule now considers the longest lines first so subset/short-turn patterns drop instead of redrawing the shared trunk. - maps Kotlin: raw rail lines get the same per-mode fallback when the pack colour is 0 (never null into a single generic colour), and converted lines are deduped per route+direction across feeds. Tests: new Rust tests in tile/geometry/tests_transit.rs (duplicate in one colour draws once, another colour still draws, colourless subway/train take mode colours, route_color wins); a Rust pack test pinning one path per route+direction; Kotlin TransitLineDedupeColourTest pinning dedupe and the colour table. Two existing tile fixtures moved to an equatorial tile so their 100-unit spacing is ~60 m of ground rather than ~5 m at the pole. Verified: cargo test -p map_renderer -p offlinerouter green (578 + 127), cargo fmt --check clean, :maps:testDevUnitTest green (incl. the new test, 4/4), :library:map:lint and :library:map:lintVitalRelease green. NOT green at this HEAD, pre-existing and untouched by this change: :maps:lint (41 errors) and :maps:lintVitalRelease (14 errors), all in files this change does not touch (DialogAsRoute in ContactAddressButton/SearchSheet/SavedPlacesPage, screenshot and fixture lints in tests); ktlintCheck is likewise red module-wide at baseline. Parent: please re-run maps lint after the in-flight lint fixes land before merging.
Diff
library/map/src/main/rust/src/tile/geometry/build.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/build.rs b/library/map/src/main/rust/src/tile/geometry/build.rsindex b90922f39d..4f750cfea4 100644--- a/library/map/src/main/rust/src/tile/geometry/build.rs+++ b/library/map/src/main/rust/src/tile/geometry/build.rs@@ -13,7 +13,7 @@ use crate::tile::select::ANCESTOR_DEPTH; use crate::tile::symbol; use crate::tile::taper; use tilecodec::mamaps::body::{Body, GEOM_LINE, GEOM_POINT, GEOM_POLYGON};-use tilecodec::mamaps::dict::{LAYER_BUILDINGS, LAYER_JUNCTION};+use tilecodec::mamaps::dict::{LAYER_BUILDINGS, LAYER_JUNCTION, LAYER_TRANSIT}; /// Tessellate every layer of `tile` that could be drawn while this tile is on screen. ///@@ -166,6 +166,12 @@ pub fn build_toggled( // path below keeps it off the hot road path entirely. #[allow(clippy::type_complexity)] let mut coloured: Vec<((u32, u8, u8, u8), Vec<f32>, Vec<u32>)> = Vec::new();+ // One geometry per (colour, alignment) on the transit layer: per-trip /+ // per-pattern / republished copies of one line are dropped here, not+ // stroked into a parallel bundle (see `transit.rs`).+ let is_transit_layer = layer.source_layer_id == LAYER_TRANSIT;+ let mut kept_transit = super::transit::KeptLines::default();+ let (transit_tol, transit_step) = super::transit::tolerance_units(extent, ground_width_m); for (feature_index, feature) in source.features.iter().enumerate() { // Kind, then the road flag/detail filters: one call, so a surface layer never@@ -292,13 +298,27 @@ pub fn build_toggled( &mut mesh.indices, ); }- } else if feature.transit_color != 0 {- // A transit line carries its own colour: split into one sub-mesh per+ } else if is_transit_layer {+ // A transit line carries its own colour (the GTFS+ // `route_color`, or the per-mode fallback when the+ // feature carries none): split into one sub-mesh per // distinct (colour, ordinal, lanes, taper), because two routes of one // colour on different ordinals draw as two parallel lines and one mesh- // can only take one lateral offset.- let key = (+ // can only take one lateral offset. A line already+ // drawn in this colour is not stroked again.+ let polylines = super::transit::polylines_of(source, parts);+ let Some(color) = super::transit::accept(+ &mut kept_transit, feature.transit_color,+ feature.kind_detail,+ polylines,+ transit_tol,+ transit_step,+ ) else {+ continue;+ };+ let key = (+ color, feature.transit_ordinal, feature.transit_lanes, feature.transit_taper,
library/map/src/main/rust/src/tile/geometry/mod.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/mod.rs b/library/map/src/main/rust/src/tile/geometry/mod.rsindex a1bd6525e5..f93bdebaa3 100644--- a/library/map/src/main/rust/src/tile/geometry/mod.rs+++ b/library/map/src/main/rust/src/tile/geometry/mod.rs@@ -19,6 +19,7 @@ mod regions; mod split; mod terrain; mod traffic;+mod transit; mod wash_overzoom; #[cfg(test)]@@ -42,6 +43,8 @@ mod tests_extra7; #[cfg(test)] mod tests_extra8; #[cfg(test)]+mod tests_transit;+#[cfg(test)] mod tests_wash; pub use build::{build, build_toggled};
library/map/src/main/rust/src/tile/geometry/tests.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests.rs b/library/map/src/main/rust/src/tile/geometry/tests.rsindex 21c40554a5..fb96460137 100644--- a/library/map/src/main/rust/src/tile/geometry/tests.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests.rs@@ -376,7 +376,9 @@ fn transit_lines_split_into_one_mesh_per_colour() { ); let on = LayerToggles { poi: false, transit: true, traffic: false, safety: false };- let mesh = build_toggled(&body, only, 14, 0, 0, false, on, &KindFilter::all(), 7);+ // An equatorial tile (y = 2^13), so the fixture's 100-unit spacing is+ // ~60 m of ground: three distinct lines, not three copies of one.+ let mesh = build_toggled(&body, only, 14, 0, 8192, false, on, &KindFilter::all(), 7); assert_eq!(mesh.generation, 7, "the mesh records the generation it was built at"); let colours: Vec<Option<u32>> = mesh.meshes.iter().map(|m| m.color_override).collect(); assert_eq!(
library/map/src/main/rust/src/tile/geometry/tests_extra2.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra2.rsindex efae1a4d21..90e6fb0638 100644--- a/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra2.rs@@ -292,7 +292,8 @@ fn transit_lines_of_one_colour_split_again_on_their_corridor_ordinal() { let at = all.iter().position(|l| l.id == "transit-rail").expect("the transit layer"); let Some(only) = all.get(at..=at) else { panic!("a one-layer slice") }; let on = LayerToggles { poi: false, transit: true, traffic: false, safety: false };- let mesh = build_toggled(&body, only, 14, 0, 0, false, on, &KindFilter::all(), 0);+ // Equatorial tile, as in `transit_lines_split_into_one_mesh_per_colour`.+ let mesh = build_toggled(&body, only, 14, 0, 8192, false, on, &KindFilter::all(), 0); assert_eq!( mesh.meshes.iter().map(|m| m.lane).collect::<Vec<(u8, u8, u8)>>(), vec![(0, 2, 255), (1, 2, 255)],
library/map/src/main/rust/src/tile/geometry/tests_transit.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_transit.rs b/library/map/src/main/rust/src/tile/geometry/tests_transit.rsnew file mode 100644index 0000000000..cc308de585--- /dev/null+++ b/library/map/src/main/rust/src/tile/geometry/tests_transit.rs@@ -0,0 +1,100 @@+use super::build::build_toggled;+use super::transit::effective_color;+use crate::style;+use crate::style::{KindFilter, LayerToggles};+use tilecodec::mamaps::body::{+ Body, Feature, Layer as BodyLayer, Part, GEOM_LINE, NAME_NONE, WINDING_OUTER,+};+use tilecodec::mamaps::dict;++fn transit_body(lines: &[(u32, u16, i16, i16)]) -> Body {+ // (color, kind_detail, y, x_end) — a horizontal line from (0, y) to (x_end, y).+ let mut body = Body::new(4096);+ let mut source = BodyLayer::new(dict::LAYER_TRANSIT);+ for &(color, detail, y, x_end) in lines {+ let parts_offset = source.parts.len() as u32;+ source.parts.push(Part {+ coord_start: source.coords.len() as u32,+ point_count: 2,+ winding: WINDING_OUTER,+ });+ source.coords.extend_from_slice(&[(0, y), (x_end, y)]);+ source.features.push(Feature {+ kind: crate::style::kind_id_for_test("rail"),+ kind_detail: detail,+ geom_type: GEOM_LINE,+ flags: 0,+ name_idx: NAME_NONE,+ parts_offset,+ part_count: 1,+ transit_color: color,+ transit_ordinal: 0,+ transit_lanes: 1,+ transit_taper: 255,+ lane_count: 0,+ });+ }+ body.layers.push(source);+ body+}++fn transit_meshes(body: &Body) -> Vec<(Option<u32>, usize)> {+ let all = style::layers();+ let at = all.iter().position(|l| l.id == "transit-rail").expect("the transit layer");+ let only = &all[at..=at];+ let on = LayerToggles { poi: false, transit: true, traffic: false, safety: false };+ // z14 at the equator: the tile spans ~2.4 km, so the 30 m corridor+ // tolerance is ~50 tile units and a 5-unit offset is the same line.+ let mesh = build_toggled(body, only, 14, 0, 8192, false, on, &KindFilter::all(), 0);+ mesh.meshes.iter().map(|m| (m.color_override, m.indices.len())).collect()+}++fn detail(name: &str) -> u16 {+ dict::DETAILS.iter().position(|d| *d == name).map(|i| i as u16 + 1).unwrap_or(0)+}++#[test]+fn a_duplicate_line_in_the_same_colour_draws_once() {+ // The same alignment republished a few tile units apart (two surveys of+ // one route): one rendered path, not a parallel pair.+ let body = transit_body(&[(0x0000FF, 0, 100, 3000), (0x0000FF, 0, 105, 3000)]);+ let colours = transit_meshes(&body);+ assert_eq!(colours.len(), 1, "one blue mesh: {colours:?}");+ assert_eq!(colours[0].0, Some(0xFF00_00FF));+ // And it holds one line's indices, not two stroked copies of it.+ let single = transit_meshes(&transit_body(&[(0x0000FF, 0, 100, 3000)]));+ assert_eq!(colours[0].1, single[0].1, "the duplicate added no geometry");+}++#[test]+fn a_duplicate_line_in_another_colour_still_draws() {+ // Two operators over one track are two services: dedup is per colour.+ let body = transit_body(&[(0x0000FF, 0, 100, 3000), (0xFF0000, 0, 105, 3000)]);+ let colours = transit_meshes(&body);+ assert_eq!(colours.len(), 2, "both colours draw: {colours:?}");+}++#[test]+fn a_colourless_line_takes_its_mode_fallback_colour() {+ // No GTFS route_color: the feature must not fall into the generic grey+ // mesh — a subway draws subway red, a train draws train blue.+ let body = transit_body(&[(0, detail("subway"), 100, 3000), (0, detail("train"), 500, 3000)]);+ let colours: Vec<Option<u32>> = transit_meshes(&body).into_iter().map(|(c, _)| c).collect();+ assert_eq!(+ colours,+ vec![Some(0xFFE4_002B), Some(0xFF00_57A8)],+ "mode fallback colours, not basemap grey: {colours:?}"+ );+}++#[test]+fn effective_color_prefers_the_gtfs_route_color() {+ assert_eq!(effective_color(0x0054A5, detail("subway")), 0x0054A5);+ assert_eq!(effective_color(0, detail("subway")), 0xE4002B);+ assert_eq!(effective_color(0, detail("light_rail")), 0x00985F);+ assert_eq!(effective_color(0, detail("tram")), 0xFFD200);+ assert_eq!(effective_color(0, detail("train")), 0x0057A8);+ assert_eq!(effective_color(0, detail("intercity")), 0x0057A8);+ assert_eq!(effective_color(0, detail("monorail")), 0x9D9D9D);+ assert_eq!(effective_color(0, 0), 0x666666, "unknown mode keeps the neutral fallback");+}
library/map/src/main/rust/src/tile/geometry/transit.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/transit.rs b/library/map/src/main/rust/src/tile/geometry/transit.rsnew file mode 100644index 0000000000..2c08bb8641--- /dev/null+++ b/library/map/src/main/rust/src/tile/geometry/transit.rs@@ -0,0 +1,183 @@+//! Transit-line colouring and duplicate suppression at tessellation time.+//!+//! The archive's transit layer carries one feature per GTFS shape the build+//! emitted: a route's two directions, its short-turn and branch patterns, and+//! every republished feed's copy of the same alignment all arrive as separate+//! features whose surveys differ by a few metres. Stroking every one of them+//! (the old behaviour) draws a bundle of vaguely parallel lines, and the+//! corridor lane fan then separates the bundle further as the zoom rises.+//!+//! So a tile keeps one geometry per (colour, alignment): a feature whose+//! length is already drawn in its colour — at least [`MOSTLY_DRAWN`] of its+//! sampled length within [`CORRIDOR_M`] of a kept line, direction-insensitive+//! because a route's other direction is the same line — is dropped before it+//! is stroked. This mirrors the pack overlay's whole-line rule in+//! `maps`' `corridor_spans::Covered`, at tile scale.+//!+//! Colour: a feature's `transit_color` is the GTFS `route_color`. Zero means+//! the feed (or an older archive) carried none, and such features used to+//! fall into the layer's generic mesh and draw in the basemap's grey — "not+//! all places have coloured lines". They now take the per-mode fallback the+//! GTFS build tools use (`gtfs_ingest::rail::fallback_color`), keyed off the+//! feature's mode detail, so a colourless subway draws subway red everywhere+//! rather than grey in one city and red in another.++use tilecodec::mamaps::dict;++/// How much of a line must already be drawn in its colour for it to count+/// as a duplicate. A genuine branch shares well under this; a republished+/// or short-turn copy shares well over it.+pub const MOSTLY_DRAWN: f64 = 0.95;++/// Corridor half-width in metres: sampled points within this of a kept+/// line, running along it, count as drawn. Matches the pack overlay.+const CORRIDOR_M: f64 = 30.0;++/// Sampling step in metres along a candidate line.+const SAMPLE_M: f64 = 10.0;++/// The colour a transit feature draws in: its GTFS `route_color` when it+/// carries one, else the per-mode fallback for its `kind_detail` mode.+pub fn effective_color(transit_color: u32, kind_detail: u16) -> u32 {+ if transit_color != 0 {+ return transit_color;+ }+ let detail = dict::DETAILS.get(kind_detail.saturating_sub(1) as usize).copied().unwrap_or("");+ match detail {+ "subway" => 0xE4_002B,+ "light_rail" => 0x00_985F,+ "tram" => 0xFF_D200,+ // `intercity` names long-distance rail rather than a mode.+ "train" | "intercity" => 0x00_57A8,+ "monorail" => 0x9D_9D9D,+ _ => 0x66_6666,+ }+}++/// Lines already kept in one tile, by colour, for duplicate suppression.+#[derive(Default)]+pub struct KeptLines {+ kept: Vec<(u32, Vec<Vec<(i32, i32)>>)>,+}++impl KeptLines {+ /// Whether `parts` (tile-coordinate polylines) is a duplicate of a kept+ /// line of the same `color`: at least [`MOSTLY_DRAWN`] of its sampled+ /// length lies within `tol` tile units of a kept segment. `step` is the+ /// sampling step in the same units. Too short to sample draws, so it is+ /// never a duplicate.+ pub fn is_duplicate(&self, color: u32, parts: &[Vec<(i32, i32)>], tol: f64, step: f64) -> bool {+ let samples = sample_parts(parts, step);+ if samples.is_empty() {+ return false;+ }+ let mut drawn = 0usize;+ for p in &samples {+ let near = self+ .kept+ .iter()+ .filter(|(c, _)| *c == color)+ .any(|(_, lines)| lines.iter().any(|line| dist_to_polyline(*p, line) <= tol));+ if near {+ drawn += 1;+ }+ }+ drawn as f64 / samples.len() as f64 >= MOSTLY_DRAWN+ }++ /// Record `parts` as drawn in `color`.+ pub fn add(&mut self, color: u32, parts: Vec<Vec<(i32, i32)>>) {+ self.kept.push((color, parts));+ }+}++/// Sample points every `step` tile units along every part.+fn sample_parts(parts: &[Vec<(i32, i32)>], step: f64) -> Vec<(f64, f64)> {+ let mut out = Vec::new();+ let step = if step > 0.0 { step } else { 1.0 };+ for part in parts {+ for seg in part.windows(2) {+ let (ax, ay) = (f64::from(seg[0].0), f64::from(seg[0].1));+ let (bx, by) = (f64::from(seg[1].0), f64::from(seg[1].1));+ let len = ((bx - ax).powi(2) + (by - ay).powi(2)).sqrt();+ let n = (len / step).ceil() as usize;+ for i in 0..=n {+ let t = if n == 0 { 0.0 } else { i as f64 / n as f64 };+ out.push((ax + (bx - ax) * t, ay + (by - ay) * t));+ }+ }+ if part.len() == 1 {+ out.push((f64::from(part[0].0), f64::from(part[0].1)));+ }+ }+ out+}++/// Distance from `p` to the nearest segment of `line`, in tile units.+fn dist_to_polyline(p: (f64, f64), line: &[(i32, i32)]) -> f64 {+ let mut best = f64::INFINITY;+ for seg in line.windows(2) {+ let a = (f64::from(seg[0].0), f64::from(seg[0].1));+ let b = (f64::from(seg[1].0), f64::from(seg[1].1));+ best = best.min(dist_to_segment(p, a, b));+ }+ if line.len() == 1 {+ let a = (f64::from(line[0].0), f64::from(line[0].1));+ best = best.min(((p.0 - a.0).powi(2) + (p.1 - a.1).powi(2)).sqrt());+ }+ best+}++fn dist_to_segment(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);+ let len2 = dx * dx + dy * dy;+ let t = if len2 <= 0.0 {+ 0.0+ } else {+ (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0)+ };+ let (x, y) = (a.0 + t * dx, a.1 + t * dy);+ ((p.0 - x).powi(2) + (p.1 - y).powi(2)).sqrt()+}++/// `(tolerance, step)` in tile units for a tile `extent` units wide spanning+/// `ground_width_m` metres.+pub fn tolerance_units(extent: u32, ground_width_m: f64) -> (f64, f64) {+ if ground_width_m <= 0.0 || extent == 0 {+ return (0.0, 1.0);+ }+ let per_m = f64::from(extent) / ground_width_m;+ (CORRIDOR_M * per_m, SAMPLE_M * per_m)+}++/// A feature's parts as `(i32, i32)` polylines, in tile coordinates.+pub fn polylines_of(+ source: &tilecodec::mamaps::body::Layer,+ parts: &[tilecodec::mamaps::body::Part],+) -> Vec<Vec<(i32, i32)>> {+ parts+ .iter()+ .map(|part| {+ source.points(part).iter().map(|&(px, py)| (i32::from(px), i32::from(py))).collect()+ })+ .collect()+}++/// The colour to draw one transit feature in, or `None` when it is a+/// duplicate of a line already kept in that colour (in which case nothing+/// is recorded; a kept feature records its geometry as drawn).+pub fn accept(+ kept: &mut KeptLines,+ transit_color: u32,+ kind_detail: u16,+ polylines: Vec<Vec<(i32, i32)>>,+ tol: f64,+ step: f64,+) -> Option<u32> {+ let color = effective_color(transit_color, kind_detail);+ if kept.is_duplicate(color, &polylines, tol, step) {+ return None;+ }+ kept.add(color, polylines);+ Some(color)+}
maps/src/main/java/com/vayunmathur/maps/data/OfflineRouterTransit.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/OfflineRouterTransit.kt b/maps/src/main/java/com/vayunmathur/maps/data/OfflineRouterTransit.ktindex a0f19e82b6..122aacf921 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/OfflineRouterTransit.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/OfflineRouterTransit.kt@@ -439,17 +439,62 @@ internal object OfflineRouterTransit { for (line in raw) { lineToRailLine(line)?.let { out.add(it) } }- return out+ return dedupeRailLines(out) } + /**+ * One rendered path per route and direction.+ *+ * The native side already collapses same-termini pattern variants, but+ * lines arriving from several feeds (the legacy sidecar list) can repeat+ * a route the world pack also carries. Two lines are the same+ * route-direction when name, mode, colour and the ordered termini+ * (first and last points) agree; only the longest geometry survives.+ * Corridor spans of one route have distinct termini, so they are not+ * merged away — only true re-draws of one run are.+ */+ internal fun dedupeRailLines(lines: List<RailLine>): List<RailLine> {+ val best = LinkedHashMap<List<Any?>, RailLine>()+ for (line in lines) {+ val key = listOf<Any?>(+ line.name, line.mode, line.color,+ line.points.firstOrNull(), line.points.lastOrNull(),+ )+ val kept = best[key]+ if (kept == null || line.points.size > kept.points.size) {+ best[key] = line+ }+ }+ return best.values.toList()+ }++ /**+ * The hex colour a rail line draws in: the GTFS `route_color` when the+ * pack carries one, else the per-mode fallback the native+ * `fallback_color` uses, so a colourless route draws in its mode's+ * colour here exactly as it does natively — never in one generic+ * fallback colour for every mode.+ */+ internal fun railLineColorHex(color: Int, routeType: Int): String =+ if (color != 0) {+ String.format("%06X", color and RGB_MASK)+ } else {+ when {+ routeType == 1 || routeType in 400..499 -> "E4002B"+ routeType == 0 || routeType == 5 || routeType == 900 -> "FFD200"+ routeType == 2 || routeType in 100..199 -> "0057A8"+ routeType == 12 -> "9D9D9D"+ else -> "666666"+ }+ }+ private fun lineToRailLine(line: OfflineRouter.RawRailLine): RailLine? { if (line.coords.size < MIN_RAIL_COORDS) return null val points = linePoints(line.coords) if (points.size < MIN_RAIL_POINTS) return null return RailLine( name = line.name,- color = if (line.color == 0) null- else String.format("%06X", line.color and RGB_MASK),+ color = railLineColorHex(line.color, line.routeType), mode = gtfsRouteTypeToMode(line.routeType), points = points, ordinal = line.ordinal,
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex 13f88c0ec3..ef117713e3 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -335,6 +335,7 @@ include!("transit_part4.rs"); include!("transit_part5.rs"); include!("transit_part10.rs"); include!("transit_part11.rs");+include!("transit_dedupe.rs"); include!("transit_part13.rs"); #[cfg(test)] mod tests {
maps/src/main/rust/src/transit_dedupe.rs
diff --git a/maps/src/main/rust/src/transit_dedupe.rs b/maps/src/main/rust/src/transit_dedupe.rsnew file mode 100644index 0000000000..166d5371a4--- /dev/null+++ b/maps/src/main/rust/src/transit_dedupe.rs@@ -0,0 +1,65 @@+// Route-direction dedup for the drawable rail lines, split out of+// `transit_part11.rs` for the file-length limit. Included into `transit.rs`+// after that file, so `Serving` is in scope unqualified.++/// One geometry per route and direction.+///+/// A GTFS route is many RAPTOR routes in the pack: one per stop pattern, and+/// each pattern carries its own fitted shape — per-trip shape variants,+/// short-turns and republished copies of the same run therefore arrive as+/// several near-identical polylines under one route name. Drawing them all+/// is the "fifteen vaguely parallel lines" bundle: each survey sits a few+/// metres off the next, and the corridor fan separates them further.+///+/// Two patterns are the same route-direction when feed, name, colour and+/// the ordered termini (first and last shape points) agree; only the+/// longest geometry of each such group survives. The reverse run has the+/// termini swapped, so it is a different direction and survives on its own+/// merits (the whole-line cover rule in [`fan_corridors`] may still merge+/// it into the outbound line when both share one track, which is wanted).+/// Short-turns share a terminus but not both, so they remain candidates+/// here and are dropped by the cover rule once the full run is drawn.+fn dedupe_route_directions(serving: Vec<Serving>) -> Vec<Serving> {+ let mut best: std::collections::HashMap<(String, String, u32, (i32, i32), (i32, i32)), usize> =+ std::collections::HashMap::new();+ let mut out: Vec<Serving> = Vec::with_capacity(serving.len());+ for s in serving {+ let key = (+ s.feed.clone(),+ s.name.clone(),+ s.color,+ s.points.first().copied().unwrap_or_default(),+ s.points.last().copied().unwrap_or_default(),+ );+ match best.get(&key) {+ Some(&at) => {+ // Longest geometry wins; ties keep the first (lowest route+ // index, by `sort_serving`), so the choice is deterministic.+ if s.points.len() > out[at].points.len() {+ out[at] = s;+ }+ }+ None => {+ best.insert(key, out.len());+ out.push(s);+ }+ }+ }+ out+}+++/// Indices into `serving`, longest geometry first (stable by index): the+/// order the cover rule in `fan_corridors` should consider lines, so a+/// full run is drawn before the short-turns and subsets it shadows.+fn longest_first_order(serving: &[Serving]) -> Vec<usize> {+ let mut order: Vec<usize> = (0..serving.len()).collect();+ order.sort_by(|&a, &b| {+ serving[b]+ .points+ .len()+ .cmp(&serving[a].points.len())+ .then(a.cmp(&b))+ });+ order+}
maps/src/main/rust/src/transit_part11.rs
diff --git a/maps/src/main/rust/src/transit_part11.rs b/maps/src/main/rust/src/transit_part11.rsindex 93b3f847a2..3f1e537122 100644--- a/maps/src/main/rust/src/transit_part11.rs+++ b/maps/src/main/rust/src/transit_part11.rs@@ -188,6 +188,7 @@ pub fn rail_lines( } } sort_serving(&mut serving);+ let mut serving = dedupe_route_directions(serving); // Dedup: whole lines only. A line 95% drawn in its colour adds nothing; // past four services over one metre the track is fully said.@@ -203,7 +204,9 @@ fn fan_corridors(serving: &mut [Serving]) -> Vec<RailLine> { std::collections::HashMap::new(); let mut mode_cover: std::collections::HashMap<u32, crate::corridor_spans::Covered> = std::collections::HashMap::new();- for (at, s) in serving.iter().enumerate() {+ let longest_first = longest_first_order(serving);+ for at in longest_first {+ let s = &serving[at]; let color_cover = by_color.entry(s.color).or_default(); if color_cover.covered_fraction(&s.points) >= MOSTLY_DRAWN { continue;@@ -217,6 +220,7 @@ fn fan_corridors(serving: &mut [Serving]) -> Vec<RailLine> { color_cover.add_tagged(&s.points, 0); kept.push(at); }+ kept.sort_unstable(); // Corridor assignment over the survivors. let candidates: Vec<crate::corridor_group::Candidate> = kept@@ -337,6 +341,7 @@ pub fn routes_for_stop(idx: &TransitIndex, lat: f64, lon: f64) -> Vec<RailLine> } } sort_serving(&mut serving);+ let mut serving = dedupe_route_directions(serving); fan_corridors(&mut serving) }
maps/src/main/rust/src/transit_part12.rs
diff --git a/maps/src/main/rust/src/transit_part12.rs b/maps/src/main/rust/src/transit_part12.rsindex c468a6363b..268f7f8bf2 100644--- a/maps/src/main/rust/src/transit_part12.rs+++ b/maps/src/main/rust/src/transit_part12.rs@@ -158,6 +158,71 @@ assert_eq!(blue.len(), 1, "one blue line, not two: {lines:?}"); } + #[test]+ fn same_route_same_direction_patterns_draw_once() {+ // A second pattern of the same route in the same direction, with a+ // wider eastward detour (a per-pattern shape variant): the same+ // route-direction, so only one geometry may draw.+ let mut pack = shaped_route_pack();+ pack.routes.push(Route {+ name: "N",+ color: 0x0000FF,+ route_type: 0,+ feed: 0,+ pattern: vec![0, 1, 2],+ trips: vec![Trip {+ start: 36_000,+ stoptimes: vec![(36_000, 36_000), (36_300, 36_360), (36_600, 36_600)],+ service: 0,+ headsign: "Downtown",+ }],+ shape: Some(Shape {+ points: vec![+ (37.700, -122.400),+ (37.705, -122.380),+ (37.710, -122.400),+ (37.715, -122.380),+ (37.720, -122.400),+ ],+ stop_vertices: vec![0, 2, 4],+ }),+ });+ // And the reverse direction on its own alignment 200 m north: a+ // different direction, so it keeps its own path.+ pack.routes.push(Route {+ name: "N",+ color: 0x0000FF,+ route_type: 0,+ feed: 0,+ pattern: vec![2, 1, 0],+ trips: vec![Trip {+ start: 39_600,+ stoptimes: vec![(39_600, 39_600), (39_900, 39_960), (40_200, 40_200)],+ service: 0,+ headsign: "Outbound",+ }],+ shape: Some(Shape {+ points: vec![+ (37.722, -122.400),+ (37.717, -122.390),+ (37.712, -122.400),+ (37.707, -122.390),+ (37.702, -122.400),+ ],+ stop_vertices: vec![0, 2, 4],+ }),+ });+ let idx = pack.index();+ let lines = rail_lines(&idx, 37.69, -122.41, 37.73, -122.39);+ let blue: Vec<_> = lines.iter().filter(|l| l.color == 0x0000FF).collect();+ assert_eq!(+ blue.len(),+ 2,+ "one path per route+direction, not per pattern: {:?}",+ lines.iter().map(|l| (l.name.as_str(), l.coords.len())).collect::<Vec<_>>()+ );+ }+ #[test] fn stop_lines_name_only_serving_routes_and_keep_buses() { // The shaped tram plus a crosstown line through the same stops and a
maps/src/test/java/com/vayunmathur/maps/data/TransitLineDedupeColourTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/TransitLineDedupeColourTest.kt b/maps/src/test/java/com/vayunmathur/maps/data/TransitLineDedupeColourTest.ktnew file mode 100644index 0000000000..3e5e8e17de--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/TransitLineDedupeColourTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.maps.data++import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.transit.RailLine+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * The pack overlay's last line of defence: one rendered path per+ * route+direction, and GTFS `route_color` with the per-mode fallback when+ * a route carries none.+ */+class TransitLineDedupeColourTest {+ private fun line(+ name: String = "N",+ color: String? = "0000FF",+ mode: String = "TRAM",+ points: List<GeoPoint> = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.39, 37.71), GeoPoint(-122.4, 37.72)),+ ordinal: Int = 0,+ ) = RailLine(name = name, color = color, mode = mode, points = points, ordinal = ordinal, lanes = 1, taper = 255)++ @Test+ fun `same route and direction keeps only the longest geometry`() {+ val short = line(points = listOf(GeoPoint(-122.4, 37.7), GeoPoint(-122.4, 37.72)))+ val out = OfflineRouterTransit.dedupeRailLines(listOf(short, line()))+ assertEquals(1, out.size)+ assertEquals(3, out.single().points.size, "the longest survey wins")+ }++ @Test+ fun `reverse direction is a different route-direction`() {+ val forward = line()+ val reverse = line(points = forward.points.reversed())+ val out = OfflineRouterTransit.dedupeRailLines(listOf(forward, reverse))+ assertEquals(2, out.size, "inbound and outbound each keep one path")+ }++ @Test+ fun `different colour or name is a different line`() {+ val out = OfflineRouterTransit.dedupeRailLines(+ listOf(line(), line(color = "FF0000"), line(name = "M")),+ )+ assertEquals(3, out.size)+ }++ @Test+ fun `gtfs route colour wins and missing colour falls back per mode`() {+ assertEquals("0054A5", OfflineRouterTransit.railLineColorHex(0x0054A5, 1))+ // No route_color (0): the mode fallback, matching the native table.+ assertEquals("E4002B", OfflineRouterTransit.railLineColorHex(0, 1), "subway")+ assertEquals("E4002B", OfflineRouterTransit.railLineColorHex(0, 402), "extended subway")+ assertEquals("FFD200", OfflineRouterTransit.railLineColorHex(0, 0), "tram")+ assertEquals("0057A8", OfflineRouterTransit.railLineColorHex(0, 2), "rail")+ assertEquals("0057A8", OfflineRouterTransit.railLineColorHex(0, 102), "extended rail")+ assertEquals("9D9D9D", OfflineRouterTransit.railLineColorHex(0, 12), "monorail")+ assertEquals("666666", OfflineRouterTransit.railLineColorHex(0, 3), "bus / unknown")+ }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsTransitLinesC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsTransitLinesC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsTransitLinesC5Test.ktindex 9f2773cbc3..76de4062b9 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/MapsTransitLinesC5Test.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsTransitLinesC5Test.kt@@ -58,11 +58,12 @@ class MapsTransitLinesC5Test { } @Test- fun `zero colour becomes null and odd coords drop the tail`() {+ fun `zero colour becomes the mode fallback and odd coords drop the tail`() { val line = invoke("lineToRailLine", rawLine(color = 0, coords = doubleArrayOf(-122.0, 37.0, -122.1, 37.1, 5.0))) assertTrue(line != null) line as com.vayunmathur.maps.data.transit.RailLine- assertNull(line.color)+ // routeType 0 is a tram in the fixture: the per-mode fallback, not null.+ assertEquals("FFD200", line.color) assertEquals(2, line.points.size) }