Modern Apps git

← Modern-Apps.git

maps P5a: rust router emits lane info

Commit
db731e3dd003073369b9ae0be9cf5ebb4fb317db
Author
vayun-mathur <[email protected]>
When
2026-08-16 23:25 UTC (3 months ago)
Parents
fdc79a3

Diff

maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex da8e6ffe2f..8276c1aef9 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -198,7 +198,9 @@ object OfflineRouter {             val gtfsFeed: String?,             val stopCode: String?,             val endStopCode: String?,-            val stopCount: Int+            val stopCount: Int,+            /** Packed turn lanes: one int per lane, `maneuverOrdinal * 2 + valid`. */+            val lanePacked: IntArray     )      private var isInitialized = false@@ -312,6 +314,20 @@ object OfflineRouter {                                     RouteService.API.Maneuver.entries.getOrElse(raw.maneuverId) {                                         RouteService.API.Maneuver.MANEUVER_UNSPECIFIED                                     }+                            // Decode packed turn lanes (dir * 2 + valid) into+                            // ordered left→right lane guidance.+                            val lanes = raw.lanePacked.map { code ->+                                val dir = code shr 1+                                val active = (code and 1) == 1+                                RouteService.API.Lane(+                                        directions = listOf(+                                                RouteService.API.Maneuver.entries.getOrElse(dir) {+                                                    RouteService.API.Maneuver.MANEUVER_UNSPECIFIED+                                                }+                                        ),+                                        active = active,+                                )+                            }                             val hasName = raw.roadName.isNotBlank()                             val instructionText =                                     when (maneuver) {@@ -507,6 +523,7 @@ object OfflineRouter {                                     else if (mode == RouteService.TravelMode.TRANSIT) RouteService.TravelMode.WALK                                     else mode,                                     speedRatio = raw.speedRatio,+                                    lanes = lanes,                                     transitDetails = if (raw.isTransit && raw.gtfsFeed != null && raw.stopCode != null) {                                         RouteService.API.TransitDetails(                                             headsign = "", // Not stored yet
maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.ktindex 2932774a91..8db586c92b 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt@@ -14,9 +14,16 @@ object RouteService {         @Serializable data class TransitLine(val name: String, val nameShort: String? = null, val color: String)         @Serializable data class NavInstruction(val maneuver: Maneuver = Maneuver.MANEUVER_UNSPECIFIED, val instructions: String = "")         @Serializable enum class Maneuver { MANEUVER_UNSPECIFIED, TURN_SLIGHT_LEFT, TURN_SHARP_LEFT, UTURN_LEFT, TURN_LEFT, TURN_SLIGHT_RIGHT, TURN_SHARP_RIGHT, UTURN_RIGHT, TURN_RIGHT, STRAIGHT, RAMP_LEFT, RAMP_RIGHT, MERGE, FORK_LEFT, FORK_RIGHT, FERRY, FERRY_TRAIN, ROUNDABOUT_LEFT, ROUNDABOUT_RIGHT, DEPART, NAME_CHANGE, WAIT, RIDE }+        /**+         * One available turn lane at the maneuver's junction. [directions] are the+         * turn indications the lane offers (currently one per lane, derived from+         * the Rust router's junction topology); [active] marks a lane that leads+         * onto the taken route (highlighted in the lane-guidance UI).+         */+        @Serializable data class Lane(val directions: List<Maneuver>, val active: Boolean)     }     data class Route(override val duration: Duration, override val distanceMeters: Double, val polyline: List<Position>, val step: List<Step>): RouteType-    data class Step(val distanceMeters: Double, val staticDuration: Duration, val polyline: List<Position>, val navInstruction: API.NavInstruction, val travelMode: TravelMode, val transitDetails: API.TransitDetails? = null, val speedRatio: Double = 1.0)+    data class Step(val distanceMeters: Double, val staticDuration: Duration, val polyline: List<Position>, val navInstruction: API.NavInstruction, val travelMode: TravelMode, val transitDetails: API.TransitDetails? = null, val speedRatio: Double = 1.0, val lanes: List<API.Lane> = emptyList())     interface RouteType { val duration: Duration; val distanceMeters: Double }     class EmptyRoute: RouteType { override val duration: Duration = 0.seconds; override val distanceMeters: Double = 0.0 } }
maps/src/main/rust/src/lib.rs
diff --git a/maps/src/main/rust/src/lib.rs b/maps/src/main/rust/src/lib.rsindex f84b0fc103..0d11cb3841 100644--- a/maps/src/main/rust/src/lib.rs+++ b/maps/src/main/rust/src/lib.rs@@ -219,7 +219,7 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNat         Ok(c) => c,         Err(_) => return null,     };-    let ctor = "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V";+    let ctor = "(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[I)V";      let array = match env.new_object_array(steps.len() as i32, &class, JObject::null()) {         Ok(a) => a,@@ -254,6 +254,18 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNat         let jcode = make_opt_string(&mut env, step.code_off);         let jend = make_opt_string(&mut env, step.end_code_off); +        // Packed turn-lane guidance: one int per lane (dir * 2 + valid).+        let jlanes = match env.new_int_array(step.lanes.len() as i32) {+            Ok(a) => a,+            Err(_) => return null,+        };+        if !step.lanes.is_empty()+            && env.set_int_array_region(&jlanes, 0, &step.lanes).is_err()+        {+            return null;+        }+        let jlanes_obj: JObject = jlanes.into();+         let obj = match env.new_object(             &class,             ctor,@@ -269,6 +281,7 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNat                 JValue::Object(&jcode),                 JValue::Object(&jend),                 JValue::Int(step.stop_count),+                JValue::Object(&jlanes_obj),             ],         ) {             Ok(o) => o,
maps/src/main/rust/src/routing.rs
diff --git a/maps/src/main/rust/src/routing.rs b/maps/src/main/rust/src/routing.rsindex db0d415b9c..12de2809de 100644--- a/maps/src/main/rust/src/routing.rs+++ b/maps/src/main/rust/src/routing.rs@@ -64,6 +64,95 @@ pub struct StepData {     pub code_off: u32,     pub end_code_off: u32,     pub stop_count: i32,+    /// Derived turn-lane guidance for this step's maneuver. Each entry is one+    /// available turn lane at the junction, packed as `dir * 2 + valid` where+    /// `dir` is a maneuver-enum ordinal (see `get_maneuver`) and `valid` is 1+    /// when that lane leads onto the taken route. Empty when the junction has+    /// no meaningful choice (single continuation) or no node context.+    pub lanes: Vec<i32>,+}++/// Sentinel for "no junction node" in [`StepBuilder::add_segment`].+const INVALID_NODE: u32 = 0xFFFF_FFFF;++/// Derive the available turn lanes at `junction` for a maneuver taken with the+/// given `incoming_bearing`. Purely topological: enumerates the junction's+/// outgoing driveable edges, classifies each by turn direction relative to the+/// incoming heading, and marks the one(s) matching `taken`. Returns packed+/// `dir * 2 + valid` entries sorted left→right, or empty when there is no+/// real choice (<= 1 option).+fn junction_lanes(+    g: &Graph,+    junction: u32,+    prev_node: u32,+    incoming_bearing: f64,+    taken: i32,+) -> Vec<i32> {+    if junction >= g.node_count {+        return Vec::new();+    }+    let jnode = g.node(junction);+    let s = jnode.edge_ptr;+    let e_ptr = g.node(junction + 1).edge_ptr; // sentinel valid+    let jlat = jnode.lat_e7;+    let jlon = jnode.lon_e7;++    let mut coords = [LatLon { lat_e7: 0, lon_e7: 0 }; 256];+    // (signed angle diff for sorting, turn direction code)+    let mut opts: Vec<(f64, i32)> = Vec::new();++    for k in s..e_ptr {+        let edge = g.edge(k);+        if edge.type_ & TRANSIT_FLAG != 0 {+            continue;+        }+        if !is_mode_allowed(edge.type_, DRIVING) {+            continue;+        }+        if edge.target >= g.node_count {+            continue;+        }+        // Skip the edge back the way we came — that's a U-turn, not a lane.+        if edge.target == prev_node {+            continue;+        }++        // Outgoing heading: junction -> first vertex leaving the junction.+        let (nlat, nlon) = match g.get_edge_coordinates(k, &mut coords) {+            Some((count, is_rev)) if count >= 2 => {+                let p1 = get_pt_at(&coords, count, is_rev, 1);+                (p1.lat_e7, p1.lon_e7)+            }+            _ => {+                let n = g.get_node(edge.target);+                (n.lat_e7, n.lon_e7)+            }+        };++        let out_bearing = get_bearing(jlat, jlon, nlat, nlon);+        let mut ad = out_bearing - incoming_bearing;+        while ad < -180.0 {+            ad += 360.0;+        }+        while ad > 180.0 {+            ad -= 360.0;+        }+        let dir = get_maneuver(incoming_bearing, out_bearing);+        if !opts.iter().any(|&(_, d)| d == dir) {+            opts.push((ad, dir));+        }+        if opts.len() >= 8 {+            break;+        }+    }++    if opts.len() <= 1 {+        return Vec::new();+    }+    opts.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));+    opts.iter()+        .map(|&(_, dir)| dir * 2 + if dir == taken { 1 } else { 0 })+        .collect() }  /// Snap a WGS84 point to the nearest routable edge for `mode`.@@ -348,6 +437,10 @@ struct StepBuilder<'a> {     last_bearing: f64,     current_elapsed_10ms: u32,     last_was_transit: bool,+    /// Junction node for the next segment's maneuver (or [`INVALID_NODE`]).+    pending_junction: u32,+    /// Node we arrive from at that junction, to exclude the U-turn lane.+    pending_prev: u32, }  impl<'a> StepBuilder<'a> {@@ -367,6 +460,12 @@ impl<'a> StepBuilder<'a> {         code_off: u32,         target_code_off: u32,     ) {+        // Junction context for lane derivation is set on the builder before the+        // first segment of a main-path edge and consumed (then cleared) here.+        let junction_node = self.pending_junction;+        let prev_node = self.pending_prev;+        self.pending_junction = INVALID_NODE;+        self.pending_prev = INVALID_NODE;         let mut ratio = 1.0;         if edge_idx != INVALID_EDGE {             let traffic_speed = *self.traffic.get(&edge_idx).unwrap_or(&0);@@ -412,6 +511,7 @@ impl<'a> StepBuilder<'a> {                         code_off,                         end_code_off: 0xFFFF_FFFF,                         stop_count: 0,+                        lanes: Vec::new(),                     });                     self.current_elapsed_10ms += wait + penalty;                     time_10ms = transit_move;@@ -466,6 +566,11 @@ impl<'a> StepBuilder<'a> {             }         };         if push_new {+            let lanes = if junction_node != INVALID_NODE {+                junction_lanes(self.g, junction_node, prev_node, self.last_bearing, maneuver)+            } else {+                Vec::new()+            };             self.steps.push(StepData {                 name_off,                 dist_mm: 0,@@ -478,6 +583,7 @@ impl<'a> StepBuilder<'a> {                 code_off,                 end_code_off: 0xFFFF_FFFF,                 stop_count: 0,+                lanes,             });         } @@ -527,6 +633,8 @@ pub fn reconstruct_path(         last_bearing: 0.0,         current_elapsed_10ms: 0,         last_was_transit: false,+        pending_junction: INVALID_NODE,+        pending_prev: INVALID_NODE,     };      let mut coords = [LatLon { lat_e7: 0, lon_e7: 0 }; 256];@@ -646,6 +754,14 @@ pub fn reconstruct_path(         let code_u = g.get_node_stop_code_off(u);         let code_v = g.get_node_stop_code_off(v); +        // Lane guidance is derived at the junction where this edge begins+        // (node u), excluding the node we arrived from. Set it just before the+        // edge's first segment; add_segment consumes and clears it so only the+        // maneuver segment picks up lanes.+        let prev_node = if i > 0 { path_nodes[i - 1] } else { INVALID_NODE };+        b.pending_junction = u;+        b.pending_prev = prev_node;+         if let Some((count, is_reversed)) =             g.get_edge_coordinates(best_e_idx, &mut coords).filter(|&(c, _)| c >= 2)         {