maps: pack rail lines overlay plus tappable vehicle trip sheets
- Commit
cb22ad80ae7059e39caa840d0c9d4bc30825fd6b- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 06:30 UTC (2 months ago)
- Parents
f3cea8a
Diff
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex 6dc8f28790..dc600e7d67 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -296,6 +296,27 @@ internal object MapNative { /** Take the route away: navigation ended, or the host cleared it. */ external fun clearRoute(handle: Long) + /**+ * Draw the pack-driven rail-lines network under the navigation route.+ *+ * Same bulk arrays as [setRoute] — flat lon/lat pairs, per-run point+ * counts and ARGB colours, plus the style widths — into the separate rail+ * slot, so the network and a selected route coexist. An empty push draws+ * nothing, like [clearRailLines].+ */+ external fun setRailLines(+ handle: Long,+ points: FloatArray,+ segmentLengths: IntArray,+ segmentColors: IntArray,+ widthDp: Float,+ casingDp: Float,+ casingColor: Int,+ )++ /** Take the rail network away: the transit toggle went off, or the host cleared it. */+ external fun clearRailLines(handle: Long)+ /** * Dim everything outside the region containing [lon]/[lat], and return which region * that is.
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.ktindex 03b848002a..4b0f0f0df9 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt@@ -94,6 +94,19 @@ internal fun SurfaceMapRenderer.setOverlayRoute(overlay: RouteOverlay?) { invalidate() } +/**+ * Draw the pack-driven rail-lines network under the navigation route (see+ * [RouteOverlay]). `null` or an all-empty overlay draws nothing, which is how+ * the network is cleared (transit toggle off, or the pack carries no shapes+ * for the viewport). One tessellation per push, like the route.+ */+internal fun SurfaceMapRenderer.setRailLines(overlay: RouteOverlay?) {+ railSegments = overlay?.segments+ railStyle = overlay?.style ?: RouteStyle()+ applyRailLines()+ invalidate()+}+ /** * Push the live-traffic colour table: [ids] holds each segment's `component_id` and * [argbColors] the fully-resolved ARGB to draw it, index for index. The host owns the@@ -206,6 +219,39 @@ internal fun SurfaceMapRenderer.applyRoute() { ) } +internal fun SurfaceMapRenderer.applyRailLines() {+ if (handle == 0L) return+ // Drawable segments only, like the route: fewer than two points strokes+ // nothing, and dropping them keeps the native per-segment ranges aligned.+ val drawable = railSegments?.filter { it.points.size >= 2 }+ if (drawable.isNullOrEmpty()) {+ MapNative.clearRailLines(handle)+ return+ }+ val flat = FloatArray(drawable.sumOf { it.points.size } * 2)+ val lengths = IntArray(drawable.size)+ val colors = IntArray(drawable.size)+ var at = 0+ drawable.forEachIndexed { i, segment ->+ lengths[i] = segment.points.size+ colors[i] = segment.color.toArgb()+ for (point in segment.points) {+ flat[at * 2] = point.longitude.toFloat()+ flat[at * 2 + 1] = point.latitude.toFloat()+ at+++ }+ }+ MapNative.setRailLines(+ handle,+ flat,+ lengths,+ colors,+ railStyle.width.value,+ railStyle.casingWidth.value,+ railStyle.casingColor.toArgb(),+ )+}+ internal fun SurfaceMapRenderer.applyTraffic() { if (handle == 0L) return val speeds = trafficSpeeds
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex f2d7e5ac3c..02e2cdd1d9 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -229,6 +229,15 @@ class SurfaceMapRenderer( internal var routeSegments: List<RouteSegment>? = null internal var routeStyle = RouteStyle() + /**+ * The pack-driven rail-lines network to draw, and how — a second coloured+ * overlay beside the navigation route so the network and a selected route+ * coexist. Remembered on the same terms as [routeSegments] so a push that+ * arrived before the surface existed is re-applied in the first frame.+ */+ internal var railSegments: List<RouteSegment>? = null+ internal var railStyle = RouteStyle()+ /** * The last-pushed live-traffic colour table (`component_id`s and their ARGB), remembered so * a push that arrived before the surface existed — or that has to outlive the surface being@@ -294,6 +303,7 @@ class SurfaceMapRenderer( MapNative.setTrafficEnabled(handle, layers.traffic) applyUserPuck() applyRoute()+ applyRailLines() applyRegionMask() applyTraffic() applyMarkers()
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex 8687594070..7737315f64 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -97,6 +97,11 @@ fun VectorMap( regionMask: RegionMask? = null, trafficColors: TrafficColorTable? = null, route: RouteOverlay? = null,+ /**+ * The pack-driven rail-lines network, drawn under [route] in its own+ * slot so the two coexist. `null` draws nothing.+ */+ railLines: RouteOverlay? = null, /** * App pins the renderer draws inside its own frame, glued to the ground so they pan and tilt * in lock-step with the basemap instead of trailing it the way a Compose overlay does (see@@ -188,6 +193,7 @@ fun VectorMap( regionMask = regionMask, trafficColors = trafficColors, route = route,+ railLines = railLines, markers = markers, vehicles = vehicles, modifier = Modifier.fillMaxSize(),
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex ad82127946..7ebc2dfe16 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -67,6 +67,13 @@ internal fun VulkanMapSurface( * it pans in lock-step with the basemap. */ route: RouteOverlay? = null,+ /**+ * The pack-driven rail-lines network to draw under [route]. `null` or an+ * all-empty overlay draws nothing. Pushed like [route] but on the+ * viewport's cadence (re-fetched when the camera outgrows the covered+ * bbox), into the separate rail slot so the two coexist.+ */+ railLines: RouteOverlay? = null, /** App pins the renderer draws as billboarded sprites; empty draws none. */ markers: List<MapMarker> = emptyList(), /**@@ -184,6 +191,10 @@ internal fun VulkanMapSurface( // recomposition does not re-tessellate. `null` or an all-empty overlay clears it. LaunchedEffect(route, host) { renderer.setRoute(route) } + // The rail network: pushed like the route, into the separate rail slot so+ // the two coexist. Keyed on the overlay's value for the same reason.+ LaunchedEffect(railLines, host) { renderer.setRailLines(railLines) }+ // App pins: pushed like the puck, out of band from the frame loop, so they pan and tilt in // lock-step with the basemap. Keyed on the list's value so an identical set rebuilt on // recomposition does not re-push; an empty list clears them.
library/map/src/main/rust/src/bridge/route.rs
diff --git a/library/map/src/main/rust/src/bridge/route.rs b/library/map/src/main/rust/src/bridge/route.rsindex 262e52f036..5548413b19 100644--- a/library/map/src/main/rust/src/bridge/route.rs+++ b/library/map/src/main/rust/src/bridge/route.rs@@ -112,3 +112,81 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearRoute<'l> } } }++/// Draw the pack-driven rail-lines network under the navigation route.+///+/// Same bulk arrays and tessellation as+/// [`setRoute`](Java_com_vayunmathur_library_map_MapNative_setRoute) — a+/// list of coloured runs with one casing — into the separate rail slot, so+/// the network and a selected route coexist. Uploaded once per push like the+/// route; the host re-pushes when the viewport outgrows the covered bbox or+/// the toggle flips. Empty draws nothing, like [`clearRailLines`].+#[no_mangle]+#[allow(clippy::too_many_arguments)]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setRailLines<'l>(+ env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ points: JFloatArray<'l>,+ segment_lengths: JIntArray<'l>,+ segment_colors: JIntArray<'l>,+ width_dp: jfloat,+ casing_dp: jfloat,+ casing_color: jint,+) {+ let Some(map) = handle_mut(handle) else { return };+ let point_floats = match env.get_array_length(&points) {+ Ok(length) => length.max(0) as usize,+ Err(_) => {+ log("the rail points array could not be measured; leaving the network unchanged");+ return;+ }+ };+ let segment_count = env.get_array_length(&segment_lengths).unwrap_or(0).max(0) as usize;+ let color_count = env.get_array_length(&segment_colors).unwrap_or(0).max(0) as usize;+ let segment_count = segment_count.min(color_count);+ let mut flat = vec![0f32; point_floats];+ if env.get_float_array_region(&points, 0, &mut flat).is_err() {+ log("the rail points array could not be read; leaving the network unchanged");+ return;+ }+ let mut lengths = vec![0i32; segment_count];+ let mut colors = vec![0i32; segment_count];+ if segment_count > 0+ && (env.get_int_array_region(&segment_lengths, 0, &mut lengths).is_err()+ || env.get_int_array_region(&segment_colors, 0, &mut colors).is_err())+ {+ log("the rail segment arrays could not be read; leaving the network unchanged");+ return;+ }+ let mut segments: Vec<RouteSegment> = Vec::with_capacity(segment_count);+ let mut cursor = 0usize;+ for (len, color) in lengths.into_iter().zip(colors) {+ let count = len.max(0) as usize;+ let end = (cursor + count * 2).min(flat.len());+ let run: Vec<(f64, f64)> =+ flat[cursor..end].chunks_exact(2).map(|pair| (pair[0] as f64, pair[1] as f64)).collect();+ cursor = end;+ segments.push(RouteSegment { points: run, color: color as u32 });+ }++ let style = RouteStyle { width_dp, casing_dp, casing_color: casing_color as u32 };+ let mesh = crate::overlay::tessellate(&segments, style);+ if let Err(e) = map.renderer.set_rail_lines(mesh.as_ref()) {+ log(&format!("uploading the rail network failed: {e}"));+ }+}++/// Take the rail network away: the transit toggle went off, or the host cleared it.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearRailLines<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if let Some(map) = handle_mut(handle) {+ if let Err(e) = map.renderer.set_rail_lines(None) {+ log(&format!("clearing the rail network failed: {e}"));+ }+ }+}
library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rsindex d6be23e67e..a5a2b48f2f 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs@@ -87,6 +87,12 @@ pub struct Renderer { pub(crate) selected_region: Option<u64>, /// The navigation route line, or `None` when no route is set. pub(crate) route: Option<RouteBuffers>,+ /// The pack-driven rail-lines overlay, or `None` when the transit layer+ /// is off or the pack carries no shapes for the viewport. A second+ /// `RouteBuffers` slot beside the navigation route (same mesh, upload and+ /// draw path) so the network and a selected route coexist — the network+ /// draws first, the route over it.+ pub(crate) rail_lines: Option<RouteBuffers>, /// The live-traffic colour table: `component_id → ARGB`, pushed from the host each update. /// /// The device owns the theme and palette, so it sends fully-resolved colours; the renderer
library/map/src/main/rust/src/vulkan/renderer/rebuild.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs b/library/map/src/main/rust/src/vulkan/renderer/rebuild.rsindex b1d4bec796..a23ace9fd7 100644--- a/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/rebuild.rs@@ -94,6 +94,10 @@ impl Drop for Renderer { route.vertices.destroy(&self.context.device); route.indices.destroy(&self.context.device); }+ if let Some(rails) = &self.rail_lines {+ rails.vertices.destroy(&self.context.device);+ rails.indices.destroy(&self.context.device);+ } for transient in &self.transients { transient.vbuf.destroy(&self.context.device); transient.ibuf.destroy(&self.context.device);
library/map/src/main/rust/src/vulkan/renderer/record.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record.rs b/library/map/src/main/rust/src/vulkan/renderer/record.rsindex 93f6a794f0..36af435bbd 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record.rs@@ -67,6 +67,8 @@ impl Renderer { /// 4. **`record_arrows`** — lane turn arrows over the roads. /// 5. **`record_region_mask`** — stencil + scrim; dims 1–4, not the route/puck. /// 6. **`record_route`** — over the scrim (a followed route must not dim), under the puck.+ /// **`record_rail_lines`** draws immediately before it: same mesh path, so the+ /// pack-driven rail network sits under a selected route. /// 7. **`record_overlays`** — markers (app pins; WS-F vehicles) billboarded upright under tilt, /// then the puck on top; last. ///@@ -415,6 +417,7 @@ impl Renderer { self.record_traffic(command_buffer, camera, &mut submitted); self.record_arrows(command_buffer, camera, layers, &mut submitted); self.record_region_mask(command_buffer, camera, &mut submitted);+ self.record_rail_lines(command_buffer, camera, &mut submitted); self.record_route(command_buffer, camera, &mut submitted); self.record_overlays(command_buffer, camera, palette, &mut submitted);
library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rsindex 792d4242ba..063b4d95cf 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra2.rs@@ -1,8 +1,8 @@ use super::{ ARROW_COLOR, ARROW_DP, BUILDINGS_DRAW_MIN_ZOOM, IDENTITY, Overlay, PUCK_COLOR, PUCK_CONE_DP, PUCK_CONE_HALF_STROKE_DP, PUCK_DOT_DP, PUCK_QUAD_DP, PUCK_RIM_DP, QUAD_INDICES, Renderer,- SCRIM_COLOR, TRAFFIC_WIDTH_DP, UserPuck, VEHICLE_RING_DP, VEHICLE_RING_QUAD_DP, anchors_for,- argb_to_rgba, scale_alpha,+ RouteBuffers, SCRIM_COLOR, TRAFFIC_WIDTH_DP, UserPuck, VEHICLE_RING_DP, VEHICLE_RING_QUAD_DP,+ anchors_for, argb_to_rgba, scale_alpha, }; use crate::camera::Camera; use crate::marker::{Marker, MARKER_SIZE_DP};@@ -206,20 +206,46 @@ impl Renderer { camera: &Camera, submitted: &mut usize, ) {- let Some(route) = &self.route else { return };- let device = &self.context.device;+ if let Some(route) = &self.route {+ Self::record_route_buffers(self, command_buffer, camera, route, submitted);+ }+ }++ /// Draw the pack-driven rail-lines network under the navigation route.+ ///+ /// Same mesh, pipeline and casing/fill structure as [`record_route`](Self::record_route);+ /// the network draws first so a selected route reads over it.+ pub(super) unsafe fn record_rail_lines(+ &self,+ command_buffer: vk::CommandBuffer,+ camera: &Camera,+ submitted: &mut usize,+ ) {+ if let Some(rails) = &self.rail_lines {+ Self::record_route_buffers(self, command_buffer, camera, rails, submitted);+ }+ }++ unsafe fn record_route_buffers(+ renderer: &Renderer,+ command_buffer: vk::CommandBuffer,+ camera: &Camera,+ route: &RouteBuffers,+ submitted: &mut usize,+ ) {+ let device = &renderer.context.device; let (origin, span) = route.placement.at_zoom(camera.zoom); let matrix = camera.world_quad_to_clip(origin, span); // What `line.vert` divides a pixel offset by to reach local units. The route's // square stands in for a tile here, which is the whole reason the two share a // vertex format. let span_px = (span * camera.density as f64) as f32;- let edge_aa = f32::from(self.swapchain.samples == vk::SampleCountFlags::TYPE_1);+ let edge_aa = f32::from(renderer.swapchain.samples == vk::SampleCountFlags::TYPE_1); device.cmd_bind_pipeline( command_buffer, vk::PipelineBindPoint::GRAPHICS,- self.pipelines.line,+ renderer.pipelines.line, ); device.cmd_bind_vertex_buffers(command_buffer, 0, &[route.vertices.buffer], &[0]); device.cmd_bind_index_buffer(@@ -252,7 +278,7 @@ impl Renderer { }; device.cmd_push_constants( command_buffer,- self.pipelines.layout,+ renderer.pipelines.layout, vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT, 0, push.as_bytes(),
library/map/src/main/rust/src/vulkan/renderer/upload.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload.rs b/library/map/src/main/rust/src/vulkan/renderer/upload.rsindex d6f68e0c57..1607f4193f 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload.rs@@ -14,17 +14,10 @@ use std::collections::HashSet; impl Renderer { /// Draw `mesh` as the navigation route, or take the route away with `None`. ///- /// Pure state like [`set_user_puck`](Self::set_user_puck), and for a stronger reason:- /// a route arrives once when the driver starts navigating and then does not change- /// for the rest of the trip, so it has no business being an argument on- /// [`render`](Self::render).- ///- /// The old buffers go through the same frames-in-flight grace queue the transient- /// symbol buffers use — a command buffer submitted last frame may still be reading- /// them, and freeing a live vertex buffer is the classic Vulkan use-after-free.- ///- /// On upload failure the route is left cleared rather than half-set, so a device that- /// cannot allocate draws no route instead of a route with no indices.+ /// Pure state: a route arrives once and then does not change, so it has+ /// no business being an argument on [`render`](Self::render). Old buffers+ /// retire through the frames-in-flight grace queue; on upload failure the+ /// route is left cleared rather than half-set. pub fn set_route(&mut self, mesh: Option<&RouteMesh>) -> Result<(), String> { if let Some(previous) = self.route.take() { self.transients.push(TransientBuffers {@@ -37,37 +30,67 @@ impl Renderer { if mesh.indices.is_empty() { return Ok(()); }- unsafe {- let vertices = Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::VERTEX_BUFFER,- &mesh.vertices,- )?;- let indices = match Buffer::upload(- &self.context.instance,- self.context.physical_device,- &self.context.device,- vk::BufferUsageFlags::INDEX_BUFFER,- &mesh.indices,- ) {- Ok(buffer) => buffer,- Err(e) => {- vertices.destroy(&self.context.device);- return Err(e);- }- };- self.route = Some(RouteBuffers {- placement: mesh.placement,- vertices,- indices,- index_count: mesh.indices.len() as u32,- segments: mesh.segments.clone(),+ // SAFETY: uploading fresh GPU buffers; the old ones retired above.+ let buffers = unsafe { self.upload_route_buffers(mesh)? };+ self.route = Some(buffers);+ Ok(())+ }++ /// Draw `mesh` as the pack-driven rail-lines overlay, or take it away+ /// with `None`. Same mesh, grace queue and cleared-on-failure contract+ /// as [`set_route`](Self::set_route); a frame does nothing but draw.+ pub fn set_rail_lines(&mut self, mesh: Option<&RouteMesh>) -> Result<(), String> {+ if let Some(previous) = self.rail_lines.take() {+ self.transients.push(TransientBuffers {+ vbuf: previous.vertices,+ ibuf: previous.indices,+ frames: FRAMES_IN_FLIGHT, }); }+ let Some(mesh) = mesh else { return Ok(()) };+ if mesh.indices.is_empty() {+ return Ok(());+ }+ // SAFETY: uploading fresh GPU buffers; the old ones retired above.+ let buffers = unsafe { self.upload_route_buffers(mesh)? };+ self.rail_lines = Some(buffers); Ok(()) }+ /// Upload a [`RouteMesh`] into GPU [`RouteBuffers`], shared by the route+ /// and rail-lines slots. On failure the vertices are destroyed and the+ /// slot stays cleared rather than half-set.+ ///+ /// # Safety: call only after retiring the slot's previous buffers — a+ /// command buffer submitted last frame may still be reading them.+ unsafe fn upload_route_buffers(&self, mesh: &RouteMesh) -> Result<RouteBuffers, String> {+ let vertices = Buffer::upload(+ &self.context.instance,+ self.context.physical_device,+ &self.context.device,+ vk::BufferUsageFlags::VERTEX_BUFFER,+ &mesh.vertices,+ )?;+ let indices = match Buffer::upload(+ &self.context.instance,+ self.context.physical_device,+ &self.context.device,+ vk::BufferUsageFlags::INDEX_BUFFER,+ &mesh.indices,+ ) {+ Ok(buffer) => buffer,+ Err(e) => {+ vertices.destroy(&self.context.device);+ return Err(e);+ }+ };+ Ok(RouteBuffers {+ placement: mesh.placement,+ vertices,+ indices,+ index_count: mesh.indices.len() as u32,+ segments: mesh.segments.clone(),+ })+ } /// Upload a tile's geometry, replacing anything already resident for it. pub fn upload(&mut self, key: u64, mesh: &TileMesh) -> Result<(), String> {
library/map/src/main/rust/src/vulkan/renderer/upload_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/upload_extra.rsindex bc1be81f25..c76dc2e5ba 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload_extra.rs@@ -173,6 +173,7 @@ impl Renderer { quad, selected_region: None, route: None,+ rail_lines: None, traffic_colors: HashMap::new(), traffic_enabled: false, pick,
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.ktindex ff670ff704..7089587d82 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt@@ -1,5 +1,6 @@ package com.vayunmathur.maps.data.transit +import com.vayunmathur.library.map.GeoPoint import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -36,6 +37,47 @@ data class TransitStop( val lon: Double, ) +/**+ * One stop on a trip's itinerary, for the vehicle-details sheet. Times are+ * epoch millis like [Departure], so the sheet countdown shares its logic;+ * [arrivesMillis]/[departsMillis] already include any realtime shift.+ */+data class TripStop(+ val name: String,+ val lat: Double,+ val lon: Double,+ val arrivesMillis: Long,+ val departsMillis: Long,+ /** Baked MOTIS id when the pack carries one, else empty. */+ val motisId: String,+)++/**+ * A trip's full run for the vehicle-details sheet: header plus one [TripStop]+ * per stop in travel order.+ */+data class TripItinerary(+ val routeName: String,+ val headsign: String,+ /** GTFS route colour as a 6-digit hex WITHOUT a leading `#`, or null. */+ val routeColor: String?,+ val mode: String,+ val cancelled: Boolean,+ val stops: List<TripStop>,+)++/**+ * One drawable rail line for the pack-driven lines overlay: the route's full+ * GTFS-shape polyline with its agency colour.+ */+data class RailLine(+ val name: String,+ /** GTFS route colour as a 6-digit hex WITHOUT a leading `#`, or null. */+ val color: String?,+ val mode: String,+ val points: List<GeoPoint>,+)+ /** * One upcoming departure at a stop. Times are epoch millis so the sheet can run * a purely client-side live countdown; [delayMinutes] is realtime − scheduled@@ -60,6 +102,13 @@ data class Departure( * cannot be used to join realtime onto the offline schedule. */ val tripId: String? = null,+ /**+ * The pack trip behind this departure, packed like a vehicle id+ * (`(route_idx << 32) | (trip_index << 1) | prev_day`). Set on offline+ * board entries so tapping one opens the same trip sheet a tapped+ * vehicle opens; null on online-only entries.+ */+ val tripVehicleId: Long? = null, ) // --- MOTIS v1 wire DTOs ----------------------------------------------------
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex 91f3c4e35a..89aaa3ab67 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -1,5 +1,6 @@ package com.vayunmathur.maps.ui +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row@@ -62,6 +63,7 @@ fun DeparturesSheet( state: DeparturesState, onDismiss: () -> Unit, onRefresh: () -> Unit,+ onTrainTap: (Departure) -> Unit = {}, ) { val stop: TransitStop? = when (state) { is DeparturesState.Loading -> state.stop@@ -126,7 +128,7 @@ fun DeparturesSheet( if (state.departures.isEmpty()) { EmptyState(title = stringResource(R.string.transit_departures_none)) } else {- DepartureList(state.departures, now)+ DepartureList(state.departures, now, onTrainTap) } } }@@ -151,7 +153,12 @@ fun DeparturesSheet( * for cannot answer it. Anything further out is next week's timetable. */ @Composable-private fun DepartureList(departures: List<Departure>, now: Long, modifier: Modifier = Modifier) {+private fun DepartureList(+ departures: List<Departure>,+ now: Long,+ onTrainTap: (Departure) -> Unit,+ modifier: Modifier = Modifier,+) { // Keyed on the departures rather than on `now`: `now` ticks every 15 s and re-sorting the // board on every tick would be wasted work and would fight the scroll position. val shown = remember(departures) {@@ -175,16 +182,26 @@ private fun DepartureList(departures: List<Departure>, now: Long, modifier: Modi LazyColumn(modifier.fillMaxWidth().heightIn(max = 420.dp), state = listState) { items(shown, key = { "${it.line}|${it.headsign}|${it.scheduledMillis}" }) { dep ->- DepartureRow(dep, now)+ DepartureRow(dep, now, onTrainTap) HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) } } } @Composable-private fun DepartureRow(dep: Departure, now: Long, modifier: Modifier = Modifier) {+private fun DepartureRow(+ dep: Departure,+ now: Long,+ onTrainTap: (Departure) -> Unit,+ modifier: Modifier = Modifier,+) {+ // A row with a pack trip behind it opens that trip's sheet: the same+ // trip a tapped vehicle sprite opens. Online-only rows (no pack trip)+ // stay inert.+ val tap = dep.tripVehicleId?.let { { onTrainTap(dep) } } Row(- modifier.fillMaxWidth().padding(vertical = 6.dp).alpha(departedAlpha(dep.realtimeMillis, now)),+ (if (tap == null) modifier else modifier.clickable(onClick = tap))+ .fillMaxWidth().padding(vertical = 6.dp).alpha(departedAlpha(dep.realtimeMillis, now)), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) {
maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.ktindex 51683a545f..9b8de48c60 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt@@ -283,6 +283,29 @@ internal fun MapPageScope.MapContentBox( departures = departuresState, onCloseStop = { transitViewModel.closeStop() }, onRefreshDepartures = { transitViewModel.refresh() },+ // A tapped train opens its trip sheet, replacing the+ // board (one tap, one back): the board's stop stays+ // selected underneath so dismissing the trip returns+ // to it rather than to the bare map.+ onTrainTap = { dep ->+ transitViewModel.openTripForDeparture(+ dep,+ selectedTransitStop?.lat ?: 0.0,+ selectedTransitStop?.lon ?: 0.0,+ )+ },+ tripSheet = tripItineraryState,+ onCloseTrip = { transitViewModel.closeTrip() },+ // A tapped station opens its departure board,+ // replacing the trip sheet (one tap, one back).+ onTripStopTap = { stop ->+ transitViewModel.closeTrip()+ transitViewModel.openNearestStop(+ stop.lat,+ stop.lon,+ stop.name.ifBlank { null },+ )+ }, ) } }
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 7d238a82c7..560cee73b8 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -149,6 +149,7 @@ fun MapPage( val searching by searchViewModel.searching.collectAsState() val selectedTransitStop by transitViewModel.selected.collectAsState() val departuresState by transitViewModel.departures.collectAsState()+ val tripItineraryState by transitViewModel.tripItinerary.collectAsState() // The findfamily service is bound only while this screen is composed, so this is empty when // findfamily is absent.@@ -263,6 +264,7 @@ fun MapPage( searchRecents = searchRecents, selectedTransitStop = selectedTransitStop, departuresState = departuresState,+ tripItineraryState = tripItineraryState, familyMembers = familyMembers, trafficEnabled = trafficEnabled, satelliteEnabled = satelliteEnabled,
maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.ktindex bd8c477e86..dc96b016c2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt@@ -17,6 +17,7 @@ import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.ipc.FamilyMember import com.vayunmathur.maps.ui.map.MapChromeState import com.vayunmathur.maps.util.DeparturesState+import com.vayunmathur.maps.util.TripItineraryState import com.vayunmathur.maps.util.MapSettingsViewModel import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.NavigationProgress@@ -121,6 +122,7 @@ internal class MapPageScope( val searchRecents: List<String>, val selectedTransitStop: TransitStop?, val departuresState: DeparturesState,+ val tripItineraryState: TripItineraryState, val familyMembers: List<FamilyMember>, val trafficEnabled: Boolean, val satelliteEnabled: Boolean,
maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.ktnew file mode 100644index 0000000000..c5e3a9a8d7--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt@@ -0,0 +1,211 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.ReadOnlyComposable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alpha+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextDecoration+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.LoadingState+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalBottomSheet+import com.vayunmathur.library.ui.SheetValue+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberBottomSheetState+import com.vayunmathur.maps.R+import com.vayunmathur.maps.data.transit.TripItinerary+import com.vayunmathur.maps.data.transit.TripStop+import com.vayunmathur.maps.util.TripItineraryState++/**+ * A vehicle's full run: every station it was at or will be at, and when.+ *+ * Opened by tapping a vehicle sprite on the map, or a train on a departure+ * board (both resolve to the same pack trip). Times are countdowns like the+ * board, so no timezone applies. Tapping a station opens its departure+ * board; the trip sheet is replaced rather than stacked (one tap, one back).+ *+ * Mirrors [DeparturesSheet]: the same [ModalBottomSheet], the same 15 s+ * countdown ticker, the same cancelled styling.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun TripSheet(+ state: TripItineraryState,+ onDismiss: () -> Unit,+ onStopTap: (TripStop) -> Unit,+) {+ val itinerary: TripItinerary? = (state as? TripItineraryState.Loaded)?.itinerary++ var now by remember { mutableLongStateOf(System.currentTimeMillis()) }+ DeparturesTicker { now = it }++ val sheetState = rememberBottomSheetState(+ initialValue = SheetValue.Hidden,+ enabledValues = setOf(SheetValue.Hidden, SheetValue.Expanded),+ )++ ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {+ Column(Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 24.dp)) {+ when (state) {+ TripItineraryState.Idle -> Unit+ TripItineraryState.Loading -> LoadingState(+ message = stringResource(R.string.transit_departures_loading),+ )+ TripItineraryState.Missing -> EmptyState(+ title = stringResource(R.string.transit_departures_none)+ )+ is TripItineraryState.Loaded -> {+ val itin = state.itinerary+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ LineBadge(itin.routeName, itin.routeColor)+ Spacer(Modifier.width(8.dp))+ Text(+ itin.headsign.ifBlank { itin.routeName },+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.primary,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ }+ Text(+ stringResource(R.string.transit_trip_title),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ if (itin.cancelled) {+ Text(+ stringResource(R.string.transit_cancelled),+ style = MaterialTheme.typography.labelMedium,+ fontWeight = FontWeight.Bold,+ color = MaterialTheme.colorScheme.error,+ )+ }+ }+ Spacer(Modifier.height(8.dp))+ TripStopList(itin, now, onStopTap)+ }+ }+ }+ }+}++/**+ * Every station on the run in travel order, scrolled to the next one the+ * trip has not yet served. Past stations dim; the one being served reads+ * "now". A tap opens that station's departure board.+ */+@Composable+private fun TripStopList(+ itinerary: TripItinerary,+ now: Long,+ onStopTap: (TripStop) -> Unit,+ modifier: Modifier = Modifier,+) {+ val stops = itinerary.stops+ val listState = rememberLazyListState()+ androidx.compose.runtime.LaunchedEffect(stops) {+ if (stops.isNotEmpty()) {+ val next = stops.indexOfFirst { it.departsMillis >= now }.coerceAtLeast(0)+ listState.scrollToItem(next.coerceAtMost(stops.lastIndex))+ }+ }+ LazyColumn(modifier.fillMaxWidth().heightIn(max = 420.dp), state = listState) {+ items(stops, key = { "${it.name}|${it.departsMillis}" }) { stop ->+ TripStopRow(stop, now, onStopTap)+ HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)+ }+ }+}++@Composable+private fun TripStopRow(+ stop: TripStop,+ now: Long,+ onStopTap: (TripStop) -> Unit,+ modifier: Modifier = Modifier,+) {+ Row(+ modifier.fillMaxWidth().clickable { onStopTap(stop) }.padding(vertical = 6.dp)+ .alpha(departedStopAlpha(stop.departsMillis, now)),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(+ stop.name.ifBlank { "—" },+ style = MaterialTheme.typography.bodyMedium,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Text(+ tripStopTime(stop, now),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+}++/** Arrival when dwelling or done, departure when still to come. */+@Composable+@ReadOnlyComposable+private fun tripStopTime(stop: TripStop, now: Long): String {+ val target = if (now < stop.departsMillis) stop.departsMillis else stop.arrivesMillis+ return when (val label = DepartureTime.label(target, now)) {+ DepartureTime.Label.Now -> stringResource(R.string.transit_now)+ is DepartureTime.Label.InMinutes ->+ stringResource(R.string.transit_minutes, label.minutes.toInt())+ is DepartureTime.Label.MinutesAgo ->+ stringResource(R.string.transit_minutes_ago, label.minutes.toInt())+ is DepartureTime.Label.Clock -> label.text+ }+}++/** A stop already served dims, so the eye lands on the next one to catch. */+@Composable+@ReadOnlyComposable+private fun departedStopAlpha(target: Long, now: Long): Float = if (target < now) 0.5f else 1f++/** The 15 s countdown ticker, shared with the departure board's cadence. */+@Composable+private fun DeparturesTicker(onTick: (Long) -> Unit) {+ androidx.compose.runtime.LaunchedEffect(Unit) {+ while (true) {+ onTick(System.currentTimeMillis())+ kotlinx.coroutines.delay(15_000L)+ }+ }+}
maps/src/main/java/com/vayunmathur/maps/ui/map/MapOverlays.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapOverlays.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapOverlays.ktindex 5214d21df7..931d89b383 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapOverlays.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapOverlays.kt@@ -3,10 +3,14 @@ package com.vayunmathur.maps.ui.map import androidx.compose.runtime.Composable import com.vayunmathur.maps.data.ParkingSpot import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.data.transit.TripStop+import com.vayunmathur.maps.data.transit.Departure import com.vayunmathur.maps.ui.DeparturesSheet import com.vayunmathur.maps.ui.LayersSheet import com.vayunmathur.maps.ui.ParkingSheet+import com.vayunmathur.maps.ui.TripSheet import com.vayunmathur.maps.util.DeparturesState+import com.vayunmathur.maps.util.TripItineraryState /** The layer toggles, grouped so the signature does not carry eight loose parameters. */ class LayerToggles(@@ -44,6 +48,10 @@ fun MapOverlays( departures: DeparturesState, onCloseStop: () -> Unit, onRefreshDepartures: () -> Unit,+ onTrainTap: (Departure) -> Unit,+ tripSheet: TripItineraryState,+ onCloseTrip: () -> Unit,+ onTripStopTap: (TripStop) -> Unit, ) { when (overlay) { MapOverlay.None -> Unit@@ -75,12 +83,28 @@ fun MapOverlays( } // Departure board (P10): opened by tapping a transit stop. Live board from Transitous- // (online-only); dismiss clears the selection.+ // (online-only); dismiss clears the selection. A tapped train opens its+ // trip sheet, replacing the board (one tap, one back). if (selectedStop != null) { DeparturesSheet( state = departures, onDismiss = onCloseStop, onRefresh = onRefreshDepartures,+ onTrainTap = onTrainTap,+ )+ }++ // Vehicle trip sheet: opened by tapping a vehicle sprite or a train on a+ // board. A tapped station opens its departure board, replacing this sheet.+ // Shown whenever a trip is selected, including over the board it came from.+ if (tripSheet is TripItineraryState.Loaded ||+ tripSheet is TripItineraryState.Loading ||+ tripSheet is TripItineraryState.Missing+ ) {+ TripSheet(+ state = tripSheet,+ onDismiss = onCloseTrip,+ onStopTap = onTripStopTap, ) } }
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.ktindex 41abef9fd4..7f37f973e3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt@@ -2,12 +2,10 @@ package com.vayunmathur.maps.ui.map import android.app.Activity import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.DpRect@@ -37,9 +35,6 @@ import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SearchResult import com.vayunmathur.maps.util.SelectedFeatureViewModel import com.vayunmathur.maps.util.TransitStopsViewModel-import com.vayunmathur.maps.util.visibleBoundsOrWorld-import kotlinx.coroutines.delay-import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch /**@@ -159,24 +154,11 @@ fun MapSurface( // transit is off, the map is hidden, or the viewport is too wide to enumerate cheaply. val vehicles = rememberTransitVehicles(camera, transitEnabled) - // Prefetch traffic for the visible 1° squares once the camera settles, so the overlay has- // data independent of route search (today traffic is fetched only during a route search).- // The native side dedups squares for the session, so a re-pan over an already-fetched- // square is a cheap no-op and the fetched data is kept. Keyed on the toggle so it stops- // when traffic is off. `collectLatest { delay() }` is the repo's debounce idiom (see- // GooglePoiMapViewModel): a newer camera position cancels the pending delay, so the fetch- // only fires after the camera stops moving.- LaunchedEffect(camera, trafficEnabled) {- if (!trafficEnabled) return@LaunchedEffect- snapshotFlow { camera.position }.collectLatest {- delay(TRAFFIC_PREFETCH_DEBOUNCE_MS)- // The component overlay is dense and zoom-gated in the archive/renderer, and a- // world-zoom viewport would enumerate hundreds of 1° squares, so only prefetch- // once zoomed in enough for it to be useful.- if (camera.position.zoom < TRAFFIC_MIN_ZOOM) return@collectLatest- prefetchTrafficSquares(camera.visibleBoundsOrWorld())- }- }+ // Pack-driven rail network for the viewport, drawn in the separate rail+ // slot under the navigation route.+ val railLines = rememberRailLines(camera, transitEnabled, tokens)++ TrafficPrefetchEffect(camera, trafficEnabled) VectorMap( cameraState = camera,@@ -204,6 +186,8 @@ fun MapSurface( // The route line, coloured per segment (traffic/transit/travelled) and drawn inside // the renderer's frame so it stays glued to the basemap on a pan. Null draws nothing. route = routeOverlay,+ // The pack-driven rail network, drawn under the route in its own slot.+ railLines = railLines, // The app's pins, drawn by the renderer as billboarded sprites so they pan/tilt in // lock-step with the basemap. Their taps resolve through the id buffer below. markers = markers,@@ -321,6 +305,16 @@ fun MapSurface( return@launch } + // A tapped vehicle sprite opens its trip sheet (CPU nearest+ // check; vehicles sit outside the GPU pick path).+ if (openVehicleTrip(+ vehicles, projection, offset,+ viewModel, transitViewModel, sheetState,+ )+ ) {+ return@launch+ }+ // Nothing hit: reverse-geocode the point ("what's here?"). Online-only. val geo = click.position searchViewModel.reverseGeocode(geo.latitude, geo.longitude) { place ->
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.ktindex 2cea759836..945fd94d58 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt@@ -23,6 +23,9 @@ import com.vayunmathur.maps.ui.toSelectedSearchResult import com.vayunmathur.maps.ui.theme.MapTokens import com.vayunmathur.maps.util.MapTileCache import com.vayunmathur.maps.util.OfflineRouter+import com.vayunmathur.maps.util.OfflineRouterTraffic+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.TransitStopsViewModel import com.vayunmathur.maps.util.PoiCategories import com.vayunmathur.maps.util.SearchResult import kotlin.math.floor@@ -118,7 +121,7 @@ internal fun prefetchTrafficSquares(bounds: GeoBounds) { * only looks them up. Returns null when nothing is left to draw. */ internal fun buildTrafficColorTable(- components: OfflineRouter.TrafficComponents,+ components: OfflineRouterTraffic.TrafficComponents, tokens: MapTokens, ): TrafficColorTable? { val n = components.ids.size@@ -228,3 +231,61 @@ internal fun buildMarkers( } return markers to hits }++/**+ * The vehicle sprite under [offset], or null.+ *+ * Vehicles are deliberately outside the GPU pick path (a moving simulated+ * sprite is not a pin tap target), so this projects each pushed vehicle to+ * the screen on the CPU and takes the nearest inside the same tolerance box+ * the pin picker uses ([MapChromeMetrics.hitSlop]). Ranked below the app's+ * own pins by the caller.+ */+internal fun pickVehicle(+ vehicles: List<MapMarker>,+ projection: com.vayunmathur.library.map.Projection,+ offset: androidx.compose.ui.unit.DpOffset,+ slop: androidx.compose.ui.unit.Dp = com.vayunmathur.maps.ui.theme.MapChromeMetrics.hitSlop,+): MapMarker? {+ var best: MapMarker? = null+ var bestDist = slop.value * slop.value+ for (marker in vehicles) {+ val screen = try {+ projection.screenLocationFromPosition(marker.position)+ } catch (_: Exception) {+ continue+ }+ val dx = screen.x.value - offset.x.value+ val dy = screen.y.value - offset.y.value+ val dist = dx * dx + dy * dy+ if (dist <= bestDist) {+ bestDist = dist+ best = marker+ }+ }+ return best+}++/**+ * Open the trip sheet for the vehicle sprite under [offset]. True when a+ * sprite was hit (the caller returns from the tap); false to fall through to+ * ambient furniture. Replaces any place sheet rather than stacking it.+ */+internal suspend fun openVehicleTrip(+ vehicles: List<MapMarker>,+ projection: com.vayunmathur.library.map.Projection,+ offset: androidx.compose.ui.unit.DpOffset,+ viewModel: SelectedFeatureViewModel,+ transitViewModel: TransitStopsViewModel,+ sheetState: com.vayunmathur.library.ui.FreeHeightSheetState?,+): Boolean {+ val marker = pickVehicle(vehicles, projection, offset) ?: return false+ viewModel.set(null)+ transitViewModel.openTrip(+ marker.id,+ marker.position.latitude,+ marker.position.longitude,+ )+ sheetState?.partialExpand()+ return true+}
maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.ktnew file mode 100644index 0000000000..da2d162f46--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/RailLines.kt@@ -0,0 +1,143 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.RouteOverlay+import com.vayunmathur.library.map.RouteSegment+import com.vayunmathur.library.map.RouteStyle+import com.vayunmathur.maps.ui.theme.MapTokens+import com.vayunmathur.maps.util.OfflineRouter+import com.vayunmathur.maps.util.visibleBoundsOrWorld+import kotlinx.coroutines.FlowPreview+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.debounce++/**+ * How long the camera must sit still before the rail network refetches: the+ * repo's debounce idiom (see the traffic prefetch in [MapSurface]). A pan+ * across the city would otherwise fire a pack query per frame.+ */+private const val RAIL_FETCH_DEBOUNCE_MS = 500L++/**+ * Below this zoom a viewport spans far more track than a lines overlay can+ * usefully draw (and the native query caps at 1500 lines). The pack's own+ * floor is z8; one step in keeps the fetch to the metro in view.+ */+private const val RAIL_MIN_ZOOM = 9.0++/**+ * How far the viewport centre may drift (degrees) before the network+ * refetches. A degree is ~111 km, so this is ~2 km: pans inside the covered+ * bbox reuse the last fetch rather than re-querying per nudge.+ */+private const val RAIL_RECENTER_DEGREES = 0.02++/**+ * Parse a 6-digit `RRGGBB` pack colour, or null when absent/malformed. The+ * pack stores colour without a `#`; [parseHexColor] in RouteOverlayBuilder+ * wants the hash, so it is added here.+ */+private fun packHexColor(hex: String?): Color? =+ hex?.takeIf { it.length == 6 }?.let {+ runCatching { Color(android.graphics.Color.parseColor("#$it")) }.getOrNull()+ }++/**+ * The pack-driven rail-lines network for the viewport, as a [RouteOverlay+ * ], or null when the transit layer is off, zoomed too far out, or the pack+ * carries no shapes for the area.+ *+ * Fetched from the on-device timetable pack (GTFS-shape polylines per route),+ * not the tile layer that needs an archive rebuild. Drawn in the separate+ * rail slot under the navigation route, in each line's agency colour with the+ * route fallback where the pack carries none. Re-fetched on settle when the+ * viewport outgrows the covered bbox; the native side caps the enumeration.+ */+@OptIn(FlowPreview::class)+@Composable+fun rememberRailLines(+ camera: CameraState,+ transitEnabled: Boolean,+ tokens: MapTokens,+): RouteOverlay? {+ val context = LocalContext.current+ var overlay by remember { mutableStateOf<RouteOverlay?>(null) }+ // Last fetch footprint: reused while the camera stays inside it.+ var fetchedCentre by remember { mutableStateOf<Pair<Double, Double>?>(null) }+ var fetchedZoom by remember { mutableStateOf(Double.NaN) }++ LaunchedEffect(transitEnabled) {+ if (!transitEnabled) {+ overlay = null+ fetchedCentre = null+ fetchedZoom = Double.NaN+ }+ }++ LaunchedEffect(camera, transitEnabled) {+ if (!transitEnabled) return@LaunchedEffect+ snapshotFlow { camera.position }+ .debounce(RAIL_FETCH_DEBOUNCE_MS)+ .collectLatest {+ val bounds = camera.visibleBoundsOrWorld()+ val zoom = camera.position.zoom+ if (zoom < RAIL_MIN_ZOOM) {+ overlay = null+ return@collectLatest+ }+ val centre = (bounds.south + bounds.north) / 2.0 to+ (bounds.west + bounds.east) / 2.0+ val last = fetchedCentre+ if (last != null &&+ kotlin.math.abs(centre.first - last.first) < RAIL_RECENTER_DEGREES &&+ kotlin.math.abs(centre.second - last.second) < RAIL_RECENTER_DEGREES &&+ kotlin.math.abs(zoom - fetchedZoom) < 1.0+ ) {+ return@collectLatest+ }+ // Pad the query past the viewport so small pans stay covered.+ val padLat = (bounds.north - bounds.south) * 0.25 + 0.05+ val padLon = (bounds.east - bounds.west) * 0.25 + 0.05+ val lines = try {+ OfflineRouter.railLines(+ context,+ minLat = bounds.south - padLat,+ minLon = bounds.west - padLon,+ maxLat = bounds.north + padLat,+ maxLon = bounds.east + padLon,+ )+ } catch (_: Exception) {+ emptyList()+ }+ fetchedCentre = centre+ fetchedZoom = zoom+ overlay = if (lines.isEmpty()) {+ null+ } else {+ RouteOverlay(+ segments = lines.map { line ->+ RouteSegment(+ points = line.points,+ color = packHexColor(line.color)+ ?: tokens.routeTransitFallback,+ )+ },+ // Thinner than the 8 dp navigation route with no+ // casing: a network backdrop, not a followed line.+ style = RouteStyle(width = 4.dp, casingWidth = 0.dp),+ )+ }+ }+ }+ return overlay+}
maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.ktnew file mode 100644index 0000000000..b32fccd715--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/TrafficPrefetchEffect.kt@@ -0,0 +1,36 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.snapshotFlow+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.maps.util.visibleBoundsOrWorld+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.collectLatest++/**+ * Prefetch traffic for the visible 1° squares once the camera settles, so the+ * overlay has data independent of route search (today traffic is fetched only+ * during a route search). The native side dedups squares for the session, so+ * a re-pan over an already-fetched square is a cheap no-op and the fetched+ * data is kept. Keyed on the toggle so it stops when traffic is off.+ * `collectLatest { delay() }` is the repo's debounce idiom (see+ * GooglePoiMapViewModel): a newer camera position cancels the pending delay,+ * so the fetch only fires after the camera stops moving.+ *+ * Extracted from MapSurface so no ui file exceeds the [FileLength] limit.+ */+@Composable+fun TrafficPrefetchEffect(camera: CameraState, trafficEnabled: Boolean) {+ LaunchedEffect(camera, trafficEnabled) {+ if (!trafficEnabled) return@LaunchedEffect+ snapshotFlow { camera.position }.collectLatest {+ delay(TRAFFIC_PREFETCH_DEBOUNCE_MS)+ // The component overlay is dense and zoom-gated in the archive/renderer, and a+ // world-zoom viewport would enumerate hundreds of 1° squares, so only prefetch+ // once zoomed in enough for it to be useful.+ if (camera.position.zoom < TRAFFIC_MIN_ZOOM) return@collectLatest+ prefetchTrafficSquares(camera.visibleBoundsOrWorld())+ }+ }+}
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 5b95ab2947..068c740d67 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -12,10 +12,7 @@ import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.concurrent.Executors import kotlin.time.Duration.Companion.seconds-import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import com.vayunmathur.library.map.GeoPoint @@ -210,6 +207,45 @@ object OfflineRouter { lat: Double, lon: Double ): String?+ /**+ * Drawable rail lines serving the bbox, read from the timetable pack's+ * GTFS-shape sections (no tile rebuild needed). `coords` is flat+ * `[lon0, lat0, ...]`; `routeColor` is 0xRRGGBB (`0` when absent).+ * Empty array (not null) when the pack is absent; null on JNI failure.+ *+ * [JvmName] keeps the JVM name JNI-visible; see [findTransitRouteNative].+ */+ @JvmName("getRailLinesNative")+ internal external fun getRailLinesNative(+ basePath: String,+ feed: String,+ minLat: Double,+ minLon: Double,+ maxLat: Double,+ maxLon: Double+ ): Array<RawRailLine>?+ /**+ * A trip's stop-by-stop itinerary for the vehicle-details sheet, decoded+ * from the stable per-trip id `activeVehiclesNative` returns. Times are+ * feed-local-midnight seconds in the query-day frame, like board times.+ * Null when the id does not resolve or the trip does not run today; a+ * cancelled trip still returns with `cancelled` set.+ *+ * [JvmName] keeps the JVM name JNI-visible; see [findTransitRouteNative].+ */+ @JvmName("getTripItineraryNative")+ internal external fun getTripItineraryNative(+ basePath: String,+ feed: String,+ vehicleId: Long,+ weekday: Int,+ date: Int,+ prevWeekday: Int,+ prevDate: Int,+ overlayCoords: DoubleArray,+ overlayRoutes: Array<String>,+ overlayTimes: IntArray+ ): RawTripItinerary? /** * Simulated in-service transit vehicles for the visible bbox (WS-F): every * trip in `<basePath>/<feed>.transit` running at `nowSecs` (seconds since@@ -250,95 +286,18 @@ object OfflineRouter { private external fun notifyTrafficFetchFinishedNative(packedSquare: Int) external fun getTrafficTileNative(z: Int, x: Int, y: Int): ByteArray? - private val _trafficVersion = kotlinx.coroutines.flow.MutableStateFlow(0)- val trafficVersion = _trafficVersion.asStateFlow()+ /** Display-traffic version counter — see [OfflineRouterTraffic]. */+ val trafficVersion get() = OfflineRouterTraffic.trafficVersion - /**- * Live per-component traffic for **display**, as a flat id→ratio table.- *- * Separate from the big-edge speeds that feed [updateTrafficNative] (routing/ETA, which- * stay entirely native): these component-level values are pushed to the renderer as an- * id→colour table by the map layer, which resolves the colour from the theme. [ids] and- * [ratioPct] are parallel; [ratioPct] is the wire's `u8 = round(speedRatio*100)`, where- * `0` means "no data" (the consumer skips those). The renderer draws a colour only for- * ids present here and present in a resident tile, so ids for squares that scrolled off- * are harmless — which is why this is an accumulating session cache rather than something- * pruned on every pan (see [trafficComponents]).- */- class TrafficComponents(val ids: LongArray, val ratioPct: ByteArray) {- companion object {- val EMPTY = TrafficComponents(LongArray(0), ByteArray(0))- }- }-- /**- * Component traffic keyed by the packed 1° square it was fetched for (the same- * `packedSquare` [fetchTrafficData] receives). The native prefetch dedups squares for the- * whole session ([ensureTrafficLoadedNative] never re-asks for a square it already- * requested), so a square is fetched once and kept: dropping it here would leave a- * re-panned area permanently uncoloured with no way to refetch. Cleared only on [reload]- * (a graph swap can renumber ids).- */- private val componentBySquare = java.util.concurrent.ConcurrentHashMap<Int, TrafficComponents>()- /**- * Last published merge, for the unchanged-content skip in- * [republishComponents]. Volatile (not confined): fetches complete on- * IO threads, so the read-modify-publish must tolerate races — the worst- * case is one redundant publish, never a missed one.- */- @Volatile- private var lastPublishedComponents: TrafficComponents? = null- private val _trafficComponents =- kotlinx.coroutines.flow.MutableStateFlow(TrafficComponents.EMPTY)+ /** Merged per-component display table — see [OfflineRouterTraffic]. */+ internal val trafficComponents get() = OfflineRouterTraffic.trafficComponents - /**- * The merged component table across every fetched square, republished whenever a fetch- * lands. The map layer collects this, converts each ratio to an ARGB colour against the- * current palette, and pushes `id→colour` to the renderer.- */- val trafficComponents = _trafficComponents.asStateFlow()-- /** Concatenate the per-square tables into one flat id/ratio snapshot and publish it. */- private fun republishComponents() {- val squares = componentBySquare.values.toList()- val total = squares.sumOf { it.ids.size }- val ids = LongArray(total)- val ratios = ByteArray(total)- var off = 0- for (s in squares) {- System.arraycopy(s.ids, 0, ids, off, s.ids.size)- System.arraycopy(s.ratioPct, 0, ratios, off, s.ratioPct.size)- off += s.ids.size- }- // Skip the publish when the merged content is unchanged: every fetch- // lands here, and a fresh object wakes the trafficComponents- // collectors (table rebuild + renderer re-push) even when a refetch- // returned identical bytes. Content-compare is O(n) against the same- // concat that already ran, far cheaper than the downstream rebuild.- val last = lastPublishedComponents- if (last != null && last.ids.contentEquals(ids) && last.ratioPct.contentEquals(ratios)) {- return- }- val snapshot = TrafficComponents(ids, ratios)- lastPublishedComponents = snapshot- _trafficComponents.value = snapshot- }+ /** Bump the display-traffic version — see [OfflineRouterTraffic]. */+ fun notifyTrafficUpdated() = OfflineRouterTraffic.notifyTrafficUpdated() private var cacheDirPath: String? = null- private var trafficUpdateJob: kotlinx.coroutines.Job? = null-- fun notifyTrafficUpdated() {- trafficUpdateJob?.cancel()- trafficUpdateJob = trafficScope.launch {- _trafficVersion.value++- }- } external fun ensureTrafficLoadedNative(lat: Double, lon: Double, forceAsync: Boolean)-- private val trafficScope = CoroutineScope(Dispatchers.IO)-- @Keep private fun fetchTrafficData( minLat: Double, minLon: Double,@@ -409,8 +368,10 @@ object OfflineRouter { "fetchTrafficData PROCESSING: $nBigI big edges, $nComponentI components" ) updateTrafficNative(edgeIds, speeds, packedSquare)- componentBySquare[packedSquare] = TrafficComponents(compIds, compRatios)- republishComponents()+ OfflineRouterTraffic.storeSquare(+ packedSquare,+ OfflineRouterTraffic.TrafficComponents(compIds, compRatios),+ ) notifyTrafficUpdated() } else { Log.w("TRAFFIC_DATA", "fetchTrafficData NO DATA: status=$status")@@ -424,7 +385,7 @@ object OfflineRouter { } if (forceAsync) {- trafficScope.launch { block() }+ OfflineRouterTraffic.launch(block) } else { // Previously called runBlocking(Dispatchers.IO) which blocked the // native caller's thread (often a Dispatchers.Default worker via@@ -432,7 +393,7 @@ object OfflineRouter { // Default pool. Always async; the native side reacts to // notifyTrafficUpdated / notifyTrafficFetchFinishedNative when the // HTTP response is processed.- trafficScope.launch { block() }+ OfflineRouterTraffic.launch(block) } } @@ -504,7 +465,12 @@ object OfflineRouter { val delaySecs: Int, val cancelled: Boolean, /** Whether the realtime overlay covered this departure. */- val realTime: Boolean+ val realTime: Boolean,+ // The trip behind this departure, packed like a vehicle id+ // (`(route_idx << 32) | (trip_index << 1) | prev_day`) so a tap+ // opens the same trip sheet. Kept LAST so the shared descriptor+ // never renumbers the arguments above.+ val tripId: Long, ) /**@@ -541,6 +507,57 @@ object OfflineRouter { val id: Long, ) + /**+ * One drawable rail line as it crosses the JNI boundary: the route's full+ * GTFS-shape polyline with its agency colour. Flat like [RawVehicle].+ */+ class RawRailLine+ @Keep+ constructor(+ val name: String,+ /** GTFS `route_color` packed as 0xRRGGBB, or 0 when absent. */+ val color: Int,+ /** GTFS `route_type`. */+ val routeType: Int,+ val feed: String,+ /** Flat `[lon0, lat0, ...]`, like a [RawStep] geometry. */+ val coords: DoubleArray,+ )++ /**+ * One itinerary stop as it crosses the JNI boundary. Times are+ * feed-local-midnight seconds in the query-day frame, converted by+ * callers exactly like board times.+ */+ class RawTripStop+ @Keep+ constructor(+ val name: String,+ val lat: Double,+ val lon: Double,+ val arrSecs: Int,+ val depSecs: Int,+ /** Baked MOTIS id when the pack carries one, else empty. */+ val motisId: String,+ /** Set on every stop when the trip is cancelled. */+ val cancelled: Boolean,+ )++ /** A trip's full run: header plus one [RawTripStop] per stop, in order. */+ class RawTripItinerary+ @Keep+ constructor(+ val routeName: String,+ val headsign: String,+ /** GTFS `route_color` packed as 0xRRGGBB, or 0 when absent. */+ val color: Int,+ /** GTFS `route_type`. */+ val routeType: Int,+ val feed: String,+ val cancelled: Boolean,+ val stops: Array<RawTripStop>,+ )+ private var isInitialized = false /** Base dir (external files) holding the downloaded `basemap.mamaps` archive and legacy `*.transit` packs. */ private var basePath: String? = null@@ -576,11 +593,7 @@ object OfflineRouter { fun reload(context: Context) { isInitialized = false OfflineRouterTransit.onReload()- // A new graph vintage can renumber edge/component ids, so the display cache from the- // old graph must not survive the swap.- componentBySquare.clear()- lastPublishedComponents = null- _trafficComponents.value = TrafficComponents.EMPTY+ OfflineRouterTraffic.onReload() initialize(context) } @@ -707,6 +720,25 @@ object OfflineRouter { maxLon: Double, ): List<Vehicle> = OfflineRouterTransit.activeVehicles(context, minLat, minLon, maxLat, maxLon) + /** Drawable rail lines — see [OfflineRouterTransit.railLines]. */+ suspend fun railLines(+ context: Context,+ minLat: Double,+ minLon: Double,+ maxLat: Double,+ maxLon: Double,+ ): List<com.vayunmathur.maps.data.transit.RailLine> =+ OfflineRouterTransit.railLines(context, minLat, minLon, maxLat, maxLon)++ /** Trip itinerary for the vehicle sheet — see [OfflineRouterTransit.tripItinerary]. */+ suspend fun tripItinerary(+ context: Context,+ vehicleId: Long,+ lat: Double,+ lon: Double,+ ): com.vayunmathur.maps.data.transit.TripItinerary? =+ OfflineRouterTransit.tripItinerary(context, vehicleId, lat, lon)+ /** * Departure board from the on-device transit index for the stop nearest * `(lat,lon)` — see [OfflineRouterTransit.getStopDeparturesOffline] for the
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.ktnew file mode 100644index 0000000000..57d4ad7370--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.kt@@ -0,0 +1,126 @@+package com.vayunmathur.maps.util++import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++/**+ * Live-traffic display state, extracted from [OfflineRouter] to keep that+ * file under the length limit.+ *+ * The native side owns routing speeds entirely ([OfflineRouter.updateTrafficNative]);+ * this object owns only what the renderer draws: the per-component colour+ * table plus the version counter the prefetch path bumps. [OfflineRouter]+ * keeps the JNI surface (native methods, `fetchTrafficData` reverse+ * callback) — native code resolves those by class and member name — and+ * delegates here for everything pure Kotlin.+ */+internal object OfflineRouterTraffic {+ /**+ * Live per-component traffic for **display**, as a flat id→ratio table.+ *+ * Separate from the big-edge speeds that feed the native updater+ * (routing/ETA, which stay entirely native): these component-level values+ * are pushed to the renderer as an id→colour table by the map layer,+ * which resolves the colour from the theme. [ids] and [ratioPct] are+ * parallel; [ratioPct] is the wire's `u8 = round(speedRatio*100)`, where+ * `0` means "no data" (the consumer skips those). The renderer draws a+ * colour only for ids present here and present in a resident tile, so ids+ * for squares that scrolled off are harmless — which is why this is an+ * accumulating session cache rather than something pruned on every pan+ * (see [trafficComponents]).+ */+ class TrafficComponents(val ids: LongArray, val ratioPct: ByteArray) {+ companion object {+ val EMPTY = TrafficComponents(LongArray(0), ByteArray(0))+ }+ }++ /**+ * Component traffic keyed by the packed 1° square it was fetched for. The+ * native prefetch dedups squares for the whole session, so a square is+ * fetched once and kept: dropping it here would leave a re-panned area+ * permanently uncoloured with no way to refetch. Cleared only on+ * [onReload] (a graph swap can renumber ids).+ */+ private val componentBySquare =+ java.util.concurrent.ConcurrentHashMap<Int, TrafficComponents>()++ /**+ * Last published merge, for the unchanged-content skip in [republish].+ * Volatile (not confined): fetches complete on IO threads, so the+ * read-modify-publish must tolerate races — the worst case is one+ * redundant publish, never a missed one.+ */+ @Volatile+ private var lastPublished: TrafficComponents? = null++ private val _trafficComponents = MutableStateFlow(TrafficComponents.EMPTY)++ /**+ * The merged component table across every fetched square, republished+ * whenever a fetch lands. The map layer collects this, converts each+ * ratio to an ARGB colour against the current palette, and pushes+ * `id→colour` to the renderer.+ */+ val trafficComponents = _trafficComponents.asStateFlow()++ private val _trafficVersion = MutableStateFlow(0)+ val trafficVersion = _trafficVersion.asStateFlow()++ private var trafficUpdateJob: kotlinx.coroutines.Job? = null+ private val trafficScope = CoroutineScope(Dispatchers.IO)++ /** Run [block] on the traffic IO scope (fetch completions live here). */+ fun launch(block: suspend () -> Unit) {+ trafficScope.launch { block() }+ }++ /** Store one square's component table and republish the merge. */+ fun storeSquare(packedSquare: Int, components: TrafficComponents) {+ componentBySquare[packedSquare] = components+ republish()+ }++ /** Concatenate the per-square tables into one flat snapshot and publish it. */+ private fun republish() {+ val squares = componentBySquare.values.toList()+ val total = squares.sumOf { it.ids.size }+ val ids = LongArray(total)+ val ratios = ByteArray(total)+ var off = 0+ for (s in squares) {+ System.arraycopy(s.ids, 0, ids, off, s.ids.size)+ System.arraycopy(s.ratioPct, 0, ratios, off, s.ratioPct.size)+ off += s.ids.size+ }+ // Skip the publish when the merged content is unchanged: every fetch+ // lands here, and a fresh object wakes the trafficComponents+ // collectors (table rebuild + renderer re-push) even when a refetch+ // returned identical bytes. Content-compare is O(n) against the same+ // concat that already ran, far cheaper than the downstream rebuild.+ val last = lastPublished+ if (last != null && last.ids.contentEquals(ids) && last.ratioPct.contentEquals(ratios)) {+ return+ }+ val snapshot = TrafficComponents(ids, ratios)+ lastPublished = snapshot+ _trafficComponents.value = snapshot+ }++ fun notifyTrafficUpdated() {+ trafficUpdateJob?.cancel()+ trafficUpdateJob = trafficScope.launch {+ _trafficVersion.value+++ }+ }++ /** Drops the display cache; called by [OfflineRouter.reload]. */+ fun onReload() {+ componentBySquare.clear()+ lastPublished = null+ _trafficComponents.value = TrafficComponents.EMPTY+ }+}
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.ktindex 5f13cb2606..afb05b8a71 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt@@ -5,8 +5,11 @@ import android.util.Log import com.vayunmathur.library.map.GeoPoint import com.vayunmathur.library.util.ConnectivityMonitor import com.vayunmathur.maps.data.transit.Departure+import com.vayunmathur.maps.data.transit.RailLine import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.data.transit.TransitousDataSource+import com.vayunmathur.maps.data.transit.TripItinerary+import com.vayunmathur.maps.data.transit.TripStop import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async@@ -306,6 +309,125 @@ internal object OfflineRouterTransit { out } + /**+ * Drawable rail lines serving the bbox, read straight from the on-device+ * timetable pack (GTFS-shape polylines per route) rather than the tile+ * layer that needs an archive rebuild. Colours are the agencies' own+ * `route_color`. Empty when no pack covers the bbox.+ */+ suspend fun railLines(+ context: Context,+ minLat: Double,+ minLon: Double,+ maxLat: Double,+ maxLon: Double,+ ): List<RailLine> = withContext(Dispatchers.Default) {+ val base = OfflineRouter.transitBase(context) ?: return@withContext emptyList()+ val feeds = transitFeeds(base)+ if (feeds.isEmpty()) return@withContext emptyList()++ val out = mutableListOf<RailLine>()+ for (feed in feeds) {+ val raw = try {+ OfflineRouter.getRailLinesNative(+ base, feed, minLat, minLon, maxLat, maxLon+ )+ } catch (_: Exception) {+ null+ } ?: continue+ for (line in raw) {+ if (line.coords.size < 4) continue+ val points = mutableListOf<GeoPoint>()+ var i = 0+ while (i + 1 < line.coords.size) {+ // Native emits [lon, lat] pairs like a RawStep geometry.+ points.add(GeoPoint(line.coords[i], line.coords[i + 1]))+ i += 2+ }+ if (points.size < 2) continue+ out.add(+ RailLine(+ name = line.name,+ color = if (line.color == 0) null+ else String.format("%06X", line.color and 0xFFFFFF),+ mode = gtfsRouteTypeToMode(line.routeType),+ points = points,+ )+ )+ }+ }+ out+ }++ /**+ * A trip's full stop-by-stop itinerary for the vehicle-details sheet,+ * decoded from the stable per-trip id `activeVehicles` returns. Runs the+ * same two-pass pattern as the route planner: a schedule-only fetch+ * names the stops (with baked MOTIS ids), then, when online, a replan+ * against the MOTIS boards for those stops folds realtime in. Null when+ * the id does not resolve or the trip does not run today.+ *+ * [lat]/[lon] is the vehicle's tapped position, used only to resolve the+ * feed timezone the query times must be expressed in.+ */+ suspend fun tripItinerary(+ context: Context,+ vehicleId: Long,+ lat: Double,+ lon: Double,+ ): TripItinerary? = withContext(Dispatchers.Default) {+ val base = OfflineRouter.transitBase(context) ?: return@withContext null+ val feeds = transitFeeds(base)+ for (feed in feeds) {+ val zoneId = runCatching {+ OfflineRouter.getFeedTimezoneNative(base, feed, lat, lon)+ }.getOrNull()+ val clock = transitClock(zoneId)+ val pass = { overlay: Overlay ->+ try {+ OfflineRouter.getTripItineraryNative(+ base, feed, vehicleId,+ clock.weekday, clock.date,+ clock.prevWeekday, clock.prevDate,+ overlay.coords, overlay.routes, overlay.times+ )+ } catch (_: Exception) {+ null+ }+ }+ val scheduled = pass(Overlay.EMPTY) ?: continue+ val overlay = realtimeOverlay(+ context,+ scheduled.stops.mapNotNull { s ->+ s.motisId.ifBlank { null }?.let { GeoPoint(s.lon, s.lat) to it }+ },+ clock,+ )+ val raw = if (overlay.isEmpty) scheduled else pass(overlay) ?: scheduled+ return@withContext TripItinerary(+ routeName = raw.routeName,+ headsign = raw.headsign,+ routeColor = if (raw.color == 0) null+ else String.format("%06X", raw.color and 0xFFFFFF),+ mode = gtfsRouteTypeToMode(raw.routeType),+ cancelled = raw.cancelled,+ stops = raw.stops.map { s ->+ val arr = clock.midnightMillis + s.arrSecs.toLong() * 1000L+ val dep = clock.midnightMillis + s.depSecs.toLong() * 1000L+ TripStop(+ name = s.name,+ lat = s.lat,+ lon = s.lon,+ arrivesMillis = arr,+ departsMillis = dep,+ motisId = s.motisId,+ )+ },+ )+ }+ null+ }+ /** * Departure board from the on-device transit index for the stop nearest * `(lat,lon)`. Scheduled times come from the pack; when the device is online@@ -400,6 +522,7 @@ internal object OfflineRouterTransit { routeColor = if (d.routeColor == 0) null else String.format("%06X", d.routeColor and 0xFFFFFF), cancelled = d.cancelled,+ tripVehicleId = d.tripId, ) ) }
maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.ktindex 620a229822..3c20db106e 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt@@ -7,6 +7,7 @@ import com.vayunmathur.library.util.ConnectivityMonitor import com.vayunmathur.maps.data.transit.Departure import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.data.transit.TransitousDataSource+import com.vayunmathur.maps.data.transit.TripItinerary import java.time.Duration import java.time.Instant import kotlinx.coroutines.Dispatchers@@ -162,6 +163,69 @@ class TransitStopsViewModel(application: Application) : AndroidViewModel(applica fun refresh() { if (_selected.value != null) _refreshTick.value += 1 }++ // --- Trip details ------------------------------------------------------++ /**+ * The vehicle whose trip sheet is open: the stable per-trip id from+ * `activeVehicles` plus where it was tapped (resolving the feed timezone+ * needs a coordinate on the trip). Null when no trip sheet is open.+ */+ private val _selectedTrip = MutableStateFlow<TripSelection?>(null)+ val selectedTrip: StateFlow<TripSelection?> = _selectedTrip.asStateFlow()++ private val _tripItinerary = MutableStateFlow<TripItineraryState>(TripItineraryState.Idle)+ val tripItinerary: StateFlow<TripItineraryState> = _tripItinerary.asStateFlow()++ /** Open the trip sheet for a tapped vehicle sprite. */+ fun openTrip(vehicleId: Long, lat: Double, lon: Double) {+ _selectedTrip.value = TripSelection(vehicleId, lat, lon)+ viewModelScope.launch {+ _tripItinerary.value = TripItineraryState.Loading+ val itin = withContext(Dispatchers.IO) {+ runCatching {+ OfflineRouter.tripItinerary(getApplication(), vehicleId, lat, lon)+ }.getOrNull()+ }+ // The selection may have moved on while the fetch ran.+ if (_selectedTrip.value?.vehicleId == vehicleId) {+ _tripItinerary.value = if (itin == null) TripItineraryState.Missing+ else TripItineraryState.Loaded(itin)+ }+ }+ }++ /**+ * Open the trip sheet for a departure tapped on a board. The board's+ * departures carry the pack trip identity ([Departure.tripVehicleId]),+ * resolved at the board's own coordinate.+ */+ fun openTripForDeparture(departure: Departure, lat: Double, lon: Double) {+ val id = departure.tripVehicleId ?: return+ openTrip(id, lat, lon)+ }++ /** Close the trip sheet. */+ fun closeTrip() {+ _selectedTrip.value = null+ _tripItinerary.value = TripItineraryState.Idle+ }+}++/** Which vehicle the trip sheet names: stable trip id + tap coordinate. */+data class TripSelection(+ val vehicleId: Long,+ val lat: Double,+ val lon: Double,+)++/** UI state for the vehicle trip sheet. */+sealed interface TripItineraryState {+ data object Idle : TripItineraryState+ data object Loading : TripItineraryState+ /** The id did not resolve or the trip does not run today. */+ data object Missing : TripItineraryState+ data class Loaded(val itinerary: TripItinerary) : TripItineraryState } /** UI state for the departure board. */
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 62778a10e6..10bc11fe00 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -332,6 +332,8 @@ <!-- Departure board: section subtitle under the stop name. Noun. --> <string name="transit_departures_title">Departures</string>+ <!-- Vehicle trip sheet: section subtitle under the line headsign. Noun. -->+ <string name="transit_trip_title">Trip stops</string> <!-- Departure board: shown while the live board is loading. --> <string name="transit_departures_loading">Loading departures\u2026</string> <!-- Departure board: shown when no upcoming departures were found. -->
maps/src/main/rust/src/jni/transit_jni.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni.rs b/maps/src/main/rust/src/jni/transit_jni.rsindex 209a701fb9..65df16e92e 100644--- a/maps/src/main/rust/src/jni/transit_jni.rs+++ b/maps/src/main/rust/src/jni/transit_jni.rs@@ -11,6 +11,8 @@ pub mod cache; pub mod departures;+pub mod itinerary;+pub mod lines; pub mod lookups; pub mod overlay; pub mod route;
maps/src/main/rust/src/jni/transit_jni/departures.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/departures.rs b/maps/src/main/rust/src/jni/transit_jni/departures.rsindex 28c7fac41a..a7c7eaab5c 100644--- a/maps/src/main/rust/src/jni/transit_jni/departures.rs+++ b/maps/src/main/rust/src/jni/transit_jni/departures.rs@@ -86,8 +86,10 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getStopDepar Ok(c) => c, Err(_) => return null, };+ // MUST match the RawDeparture ctor: 4 strings, 4 ints, 2 bools, then the+ // packed trip id (J) LAST so older descriptors never renumber. let ctor =- "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIZZ)V";+ "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIZZJ)V"; let array = match env.new_object_array(deps.len() as i32, &class, JObject::null()) { Ok(a) => a, Err(_) => return null,@@ -124,6 +126,7 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getStopDepar JValue::Int(d.delay_secs), JValue::Bool(d.cancelled as u8), JValue::Bool(d.real_time as u8),+ JValue::Long(d.trip_id), ], ) { Ok(o) => o,
maps/src/main/rust/src/jni/transit_jni/itinerary.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/itinerary.rs b/maps/src/main/rust/src/jni/transit_jni/itinerary.rsnew file mode 100644index 0000000000..e073c8e6f2--- /dev/null+++ b/maps/src/main/rust/src/jni/transit_jni/itinerary.rs@@ -0,0 +1,157 @@+//! Trip-itinerary JNI: `getTripItineraryNative`.+//!+//! Decodes a vehicle id back to its trip and returns the full stop-by-stop+//! run for the vehicle-details sheet.++use jni::objects::{JDoubleArray, JIntArray, JObject, JObjectArray, JString, JValue};+use jni::sys::{jint, jlong, jobject, jobjectArray};+use jni::JNIEnv;++use super::cache::transit_index;+use super::overlay::read_delay_entries;++// ---------------------------------------------------------------------------+// JNI: getTripItineraryNative (a trip's full stop list + times)+// ---------------------------------------------------------------------------++/// The itinerary of the trip `vehicle_id` names: header+/// `(route_name, headsign, color, route_type, feed, cancelled)` plus one+/// `RawTripStop` per stop `(name, lat, lon, arr_secs, dep_secs, motis_id)`.+/// Times are seconds since feed-local midnight in the query-day frame with+/// the realtime overlay applied — the same frame as departure-board times,+/// so Kotlin converts them identically. Returns null when the id does not+/// resolve or the trip does not run on the query service day.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getTripItineraryNative<'local>(+ mut env: JNIEnv<'local>,+ _thiz: JObject<'local>,+ base_path: JString<'local>,+ feed: JString<'local>,+ vehicle_id: jlong,+ weekday: jint,+ date: jint,+ prev_weekday: jint,+ prev_date: jint,+ overlay_coords: JDoubleArray<'local>,+ overlay_routes: JObjectArray<'local>,+ overlay_times: JIntArray<'local>,+) -> jobject {+ let null = std::ptr::null_mut();+ let base: String = match env.get_string(&base_path) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let feed_name: String = match env.get_string(&feed) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };++ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return null,+ };++ let entries =+ read_delay_entries(&mut env, &overlay_coords, &overlay_routes, &overlay_times);+ let overlay = if entries.is_empty() {+ None+ } else {+ Some(crate::transit::DelayOverlay::build(&index, &entries))+ };++ let itin = match crate::transit::trip_itinerary(+ &index,+ vehicle_id,+ crate::transit::Schedule {+ day: crate::transit::QueryDay {+ weekday: weekday.max(0) as u32,+ date: date.max(0) as u32,+ prev_weekday: prev_weekday.max(0) as u32,+ prev_date: prev_date.max(0) as u32,+ },+ overlay: overlay.as_ref(),+ },+ ) {+ Some(t) => t,+ None => return null,+ };++ let stop_class = match env.find_class("com/vayunmathur/maps/util/OfflineRouter$RawTripStop") {+ Ok(c) => c,+ Err(_) => return null,+ };+ // MUST match the RawTripStop ctor: name, lat, lon (D), arr, dep (I), motisId, cancelled (Z).+ let stop_ctor = "(Ljava/lang/String;DDIILjava/lang/String;Z)V";+ let stop_array = match env.new_object_array(itin.stops.len() as i32, &stop_class, JObject::null())+ {+ Ok(a) => a,+ Err(_) => return null,+ };+ for (i, s) in itin.stops.iter().enumerate() {+ let jname: JObject = match env.new_string(&s.name) {+ Ok(x) => x.into(),+ Err(_) => return null,+ };+ let jmotis: JObject = match env.new_string(&s.motis_id) {+ Ok(x) => x.into(),+ Err(_) => return null,+ };+ let obj = match env.new_object(+ &stop_class,+ stop_ctor,+ &[+ JValue::Object(&jname),+ JValue::Double(s.lat),+ JValue::Double(s.lon),+ JValue::Int(s.arr_secs as i32),+ JValue::Int(s.dep_secs as i32),+ JValue::Object(&jmotis),+ JValue::Bool(itin.cancelled as u8),+ ],+ ) {+ Ok(o) => o,+ Err(_) => return null,+ };+ if env.set_object_array_element(&stop_array, i as i32, &obj).is_err() {+ return null;+ }+ }++ let itin_class =+ match env.find_class("com/vayunmathur/maps/util/OfflineRouter$RawTripItinerary") {+ Ok(c) => c,+ Err(_) => return null,+ };+ // MUST match the RawTripItinerary ctor: route, headsign, color, type (I),+ // feed, cancelled (Z), stops ([L...RawTripStop;).+ let itin_ctor = "(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;Z[Lcom/vayunmathur/maps/util/OfflineRouter$RawTripStop;)V";+ let jroute: JObject = match env.new_string(&itin.route_name) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let jhead: JObject = match env.new_string(&itin.headsign) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let jfeed: JObject = match env.new_string(&itin.feed) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let jobjs: JObject = stop_array.into();+ match env.new_object(+ &itin_class,+ itin_ctor,+ &[+ JValue::Object(&jroute),+ JValue::Object(&jhead),+ JValue::Int(itin.color as i32),+ JValue::Int(itin.route_type as i32),+ JValue::Object(&jfeed),+ JValue::Bool(itin.cancelled as u8),+ JValue::Object(&jobjs),+ ],+ ) {+ Ok(o) => o.into_raw(),+ Err(_) => null,+ }+}
maps/src/main/rust/src/jni/transit_jni/lines.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/lines.rs b/maps/src/main/rust/src/jni/transit_jni/lines.rsnew file mode 100644index 0000000000..acf5e5ddfe--- /dev/null+++ b/maps/src/main/rust/src/jni/transit_jni/lines.rs@@ -0,0 +1,102 @@+//! Rail-line shapes JNI: `getRailLinesNative`.+//!+//! Reads the drawable polylines straight from the on-device timetable pack+//! (sections 20-22), bypassing the tile layer that needs an archive rebuild.++use jni::objects::{JDoubleArray, JObject, JString, JValue};+use jni::sys::{jdouble, jobjectArray};+use jni::JNIEnv;++use super::cache::transit_index;++// ---------------------------------------------------------------------------+// JNI: getRailLinesNative (drawable rail polylines + agency colours)+// ---------------------------------------------------------------------------++/// Every rail line serving the bbox, with its agency colour and GTFS+/// `route_type`: `(name, color, route_type, feed, coords)`. `coords` is a flat+/// `[lon0, lat0, ...]` like a `RawStep` geometry. Returns an empty array (not+/// null) when the pack is absent — no lines is a valid answer — and null only+/// on a JNI failure. Bounded natively (`MAX_RAIL_LINES`).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getRailLinesNative<'local>(+ mut env: JNIEnv<'local>,+ _thiz: JObject<'local>,+ base_path: JString<'local>,+ feed: JString<'local>,+ min_lat: jdouble,+ min_lon: jdouble,+ max_lat: jdouble,+ max_lon: jdouble,+) -> jobjectArray {+ let null = std::ptr::null_mut();+ let base: String = match env.get_string(&base_path) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let feed_name: String = match env.get_string(&feed) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };++ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return null,+ };++ // No covers() gate: a line serves the bbox when any of its stops does,+ // and the bbox centre may be nowhere near a stop. The stop-based cull in+ // `rail_lines` is the coverage check.+ let lines = crate::transit::rail_lines(&index, min_lat, min_lon, max_lat, max_lon);++ let class = match env.find_class("com/vayunmathur/maps/util/OfflineRouter$RawRailLine") {+ Ok(c) => c,+ Err(_) => return null,+ };+ // MUST match the RawRailLine ctor: name, color, routeType (I), feed, coords ([D).+ let ctor = "(Ljava/lang/String;IILjava/lang/String;[D)V";+ let array = match env.new_object_array(lines.len() as i32, &class, JObject::null()) {+ Ok(a) => a,+ Err(_) => return null,+ };++ for (i, l) in lines.iter().enumerate() {+ let jname: JObject = match env.new_string(&l.name) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let jfeed: JObject = match env.new_string(&l.feed) {+ Ok(s) => s.into(),+ Err(_) => return null,+ };+ let jcoords = match env.new_double_array(l.coords.len() as i32) {+ Ok(a) => a,+ Err(_) => return null,+ };+ if !l.coords.is_empty()+ && env.set_double_array_region(&jcoords, 0, &l.coords).is_err()+ {+ return null;+ }+ let jcoords_obj: JObject = jcoords.into();+ let obj = match env.new_object(+ &class,+ ctor,+ &[+ JValue::Object(&jname),+ JValue::Int(l.color as i32),+ JValue::Int(l.route_type as i32),+ JValue::Object(&jfeed),+ JValue::Object(&jcoords_obj),+ ],+ ) {+ Ok(o) => o,+ Err(_) => return null,+ };+ if env.set_object_array_element(&array, i as i32, &obj).is_err() {+ return null;+ }+ }++ array.into_raw()+}
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 2cbc659c4c..e788e51e73 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -317,6 +317,7 @@ include!("transit_part3.rs"); include!("transit_part4.rs"); include!("transit_part5.rs"); include!("transit_part10.rs");+include!("transit_part11.rs"); #[cfg(test)] mod tests { include!("transit_part6.rs");
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.rsnew file mode 100644index 0000000000..e038a93034--- /dev/null+++ b/maps/src/main/rust/src/transit_part11.rs@@ -0,0 +1,240 @@+// Rail-line shapes + trip itineraries, read straight from the on-device pack.+//+// The tile layer the renderer draws (`transit`, kind `rail`) needs an archive+// rebuild to populate, but the timetable pack already carries everything a+// lines overlay and a vehicle-details sheet need: full GTFS-shape polylines+// per route (sections 20-22), per-route colour/type/name, and the factored+// trip/profile tables a stop-by-stop itinerary reconstructs from. No format+// change — this only reads through the same helpers the planner, the board+// and the vehicle simulation already use.+//+// Included into `transit.rs`, so `TransitIndex`'s private helpers (`route`,+// `trips_for`, `route_shape_off`, `shape_slice`, `stop_ll`, `stop_label`,+// `motis_stop_id`, `read_str`, `feed_name_of`, `get_profile`, `service_runs`+// via `Schedule::runs`, `delayed`, `abs_time_on`) and the `HashMap` import+// are all in scope without qualification, exactly as in `transit_part10.rs`.++/// One drawable rail line: the route's full shape with its agency colour.+pub struct RailLine {+ pub name: String,+ pub color: u32,+ pub route_type: u32,+ pub feed: String,+ /// Interleaved `[lon0, lat0, lon1, lat1, ...]`, like a `RawStep` geometry.+ pub coords: Vec<f64>,+}++/// Bound on lines per query: a metro bbox holds dozens of rail routes, but an+/// unbounded world-zoom enumeration would serialize thousands of polylines.+pub const MAX_RAIL_LINES: usize = 1500;++/// Margin (degrees) matching the vehicle enumeration, so a line whose stops+/// sit just off-screen still draws to the viewport edge.+const RAIL_BBOX_MARGIN_DEG: f64 = 0.02;++/// Whether a GTFS `route_type` draws as a rail line. Mirrors the Kotlin+/// `gtfsRouteTypeToMode` split inversely: everything except the bus family.+/// Buses have shapes too, but drawing every bus polyline would bury the rail+/// network this overlay is for.+fn is_rail_line(t: u32) -> bool {+ !matches!(t, 3 | 800 | 200..=299 | 700..=799)+}++/// Every rail line serving the bbox, with agency colours.+///+/// Shape-first: the route's fitted GTFS polyline (`route_shape_off` ++/// full-span `shape_slice`); routes the ingester could not fit fall back to+/// stop-to-stop, the same fallback the ride legs use. Direction variants of+/// one GTFS route are distinct RAPTOR routes and both enumerate — the caller+/// dedups by name when it wants one line per named route.+pub fn rail_lines(+ idx: &TransitIndex,+ min_lat: f64,+ min_lon: f64,+ max_lat: f64,+ max_lon: f64,+) -> Vec<RailLine> {+ let mut out = Vec::new();+ if idx.stop_count == 0 {+ return out;+ }+ let m = RAIL_BBOX_MARGIN_DEG;+ let near_bbox = |lat: f64, lon: f64| {+ lat >= min_lat - m && lat <= max_lat + m && lon >= min_lon - m && lon <= max_lon + m+ };+ for r in 0..idx.route_count {+ let route = idx.route(r);+ if route.n_stops < 2 || !is_rail_line(route.route_type) {+ continue;+ }+ let mut serves_bbox = false;+ for pos in 0..route.n_stops {+ let (lat, lon) = idx.stop_ll(idx.route_stop(route.first_route_stop + pos));+ if near_bbox(lat, lon) {+ serves_bbox = true;+ break;+ }+ }+ if !serves_bbox {+ continue;+ }+ let first = route.first_route_stop;+ let last = first + route.n_stops - 1;+ let coords: Vec<f64> = match idx.route_shape_off(r) {+ Some(off) => {+ let fv = idx.route_stop_shape(first);+ let tv = idx.route_stop_shape(last);+ if fv == NONE || tv == NONE || tv < fv {+ stop_to_stop(idx, &route)+ } else {+ idx.shape_slice(off, fv, tv)+ .into_iter()+ .flat_map(|(lat, lon)| [lon, lat])+ .collect()+ }+ }+ None => stop_to_stop(idx, &route),+ };+ if coords.len() < 4 {+ continue;+ }+ out.push(RailLine {+ name: idx.read_str(route.name_off),+ color: route.color,+ route_type: route.route_type,+ feed: idx.feed_name_of(route.feed_idx),+ coords,+ });+ if out.len() >= MAX_RAIL_LINES {+ break;+ }+ }+ out+}++/// A route's stops joined straight, for routes with no fitted shape.+fn stop_to_stop(idx: &TransitIndex, route: &RouteRec) -> Vec<f64> {+ let mut coords = Vec::with_capacity(route.n_stops as usize * 2);+ for pos in 0..route.n_stops {+ let (lat, lon) = idx.stop_ll(idx.route_stop(route.first_route_stop + pos));+ coords.push(lon);+ coords.push(lat);+ }+ coords+}++/// One stop on a trip's itinerary, with query-day-frame times.+pub struct TripStop {+ pub name: String,+ pub lat: f64,+ pub lon: f64,+ /// Seconds since feed-local midnight, realtime-adjusted when the overlay+ /// covers this trip. Same frame as departure-board `depSecs`.+ pub arr_secs: u32,+ pub dep_secs: u32,+ /// Baked MOTIS id when the pack carries one (v5+ with a known feed+ /// prefix); empty otherwise.+ pub motis_id: String,+}++/// A trip's full run: what the vehicle-details sheet lists.+pub struct TripItinerary {+ pub route_name: String,+ pub headsign: String,+ pub color: u32,+ pub route_type: u32,+ pub feed: String,+ pub cancelled: bool,+ pub stops: Vec<TripStop>,+}++/// Decode a vehicle id back to `(route_idx, trip_index, prev_day)`. Inverse of+/// the packing in [`active_vehicles`](crate::transit::active_vehicles):+/// `id = (r << 32) | (ti << 1) | prev_day`.+fn decode_vehicle_id(id: i64) -> (u32, usize, bool) {+ (+ (id >> 32) as u32,+ ((id >> 1) & 0x7FFF_FFFF) as usize,+ (id & 1) != 0,+ )+}++/// The full stop-by-stop itinerary of the trip a vehicle id names.+///+/// Reuses the vehicle simulation's own math (profile rel-times,+/// previous-day frame shift, first-match trip-wide delay, cancellation), so+/// the sheet agrees with where the sprite is. Returns `None` when the id+/// does not resolve (stale sprite from a previous pack) or the trip does not+/// run on the query service day. A cancelled trip still returns its schedule+/// with `cancelled` set — the sheet shows it as cancelled rather than blank.+pub fn trip_itinerary(+ idx: &TransitIndex,+ vehicle_id: i64,+ schedule: Schedule,+) -> Option<TripItinerary> {+ let (r, ti, prev_day) = decode_vehicle_id(vehicle_id);+ if r >= idx.route_count {+ return None;+ }+ let route = idx.route(r);+ let trips = idx.trips_for(r, &route);+ let td = trips.get(ti)?;+ if !schedule.runs(idx, td.service_idx, prev_day) {+ return None;+ }+ let mut prof_cache = HashMap::new();+ let p = get_profile(&mut prof_cache, idx, td.profile_id);+ let n = (route.n_stops as usize).min(p.arr_rel.len()).min(p.dep_rel.len());+ if n < 2 {+ return None;+ }+ let day_shift = if prev_day { SECS_PER_DAY as i64 } else { 0 };+ // Same trip-wide realtime resolution as the vehicle simulation: the first+ // overlay match applies to the whole run; any cancellation marks it.+ let mut cancelled = false;+ let mut delay_secs = 0i32;+ let mut found_delay = false;+ for pos in 0..n {+ let sched_dep = td.start_time as i64 + p.dep_rel[pos] as i64 - day_shift;+ if sched_dep < 0 {+ continue;+ }+ if let Some(adj) = schedule.adjustment(r, pos as u32, sched_dep as u32) {+ if adj.cancelled {+ cancelled = true;+ }+ if !found_delay {+ delay_secs = adj.delay_secs;+ found_delay = true;+ }+ }+ }+ let mut stops = Vec::with_capacity(n);+ for pos in 0..n {+ let stop_idx = idx.route_stop(route.first_route_stop + pos as u32);+ let (lat, lon) = idx.stop_ll(stop_idx);+ stops.push(TripStop {+ name: idx.stop_label(stop_idx),+ lat,+ lon,+ arr_secs: delayed(+ abs_time_on(td.start_time, p.arr_rel[pos], prev_day),+ delay_secs,+ ),+ dep_secs: delayed(+ abs_time_on(td.start_time, p.dep_rel[pos], prev_day),+ delay_secs,+ ),+ motis_id: idx.motis_stop_id(stop_idx).unwrap_or_default(),+ });+ }+ Some(TripItinerary {+ route_name: idx.read_str(route.name_off),+ headsign: idx.read_str(td.headsign_off),+ color: route.color,+ route_type: route.route_type,+ feed: idx.feed_name_of(route.feed_idx),+ cancelled,+ stops,+ })+}
maps/src/main/rust/src/transit_part3.rs
diff --git a/maps/src/main/rust/src/transit_part3.rs b/maps/src/main/rust/src/transit_part3.rsindex 5fd52da468..7de124bc9e 100644--- a/maps/src/main/rust/src/transit_part3.rs+++ b/maps/src/main/rust/src/transit_part3.rs@@ -319,6 +319,10 @@ pub struct StopDeparture { pub cancelled: bool, /// Whether the overlay had live data for this departure at all. pub real_time: bool,+ /// The trip behind this departure, packed exactly like [`Vehicle::id`]:+ /// `(route_idx << 32) | (trip_index << 1) | prev_day`. Lets a tapped+ /// departure open the same trip sheet a tapped vehicle opens.+ pub trip_id: i64, } /// A simulated in-service vehicle: a point interpolated along a trip's shape at@@ -417,6 +421,8 @@ pub fn stop_departures( delay_secs: adj.map_or(0, |a| a.delay_secs), cancelled: adj.is_some_and(|a| a.cancelled), real_time: adj.is_some(),+ trip_id: ((r as i64) << 32) | ((ti as i64) << 1)+ | prev_day as i64, }); } }
maps/src/main/rust/src/transit_part9.rs
diff --git a/maps/src/main/rust/src/transit_part9.rs b/maps/src/main/rust/src/transit_part9.rsindex 6ca96f85f7..f9682113b3 100644--- a/maps/src/main/rust/src/transit_part9.rs+++ b/maps/src/main/rust/src/transit_part9.rs@@ -5,6 +5,66 @@ /// -122.400 meridian between 37.700 and 37.720). const VEH_BBOX: (f64, f64, f64, f64) = (37.69, -122.41, 37.73, -122.39); + // --- `transit_part11`: pack-driven rail lines + trip itineraries ---++ #[test]+ fn rail_lines_serve_a_shaped_route_with_its_colour() {+ let idx = shaped_route_pack().index();+ let lines = rail_lines(&idx, 37.69, -122.41, 37.73, -122.39);+ assert_eq!(lines.len(), 1, "the one shaped route serves the bbox");+ let l = &lines[0];+ assert_eq!(l.name, "N");+ assert_eq!(l.color, 0x0000FF);+ assert_eq!(l.feed, "sfmuni");+ // The fitted shape detours east: 5 vertices = 10 doubles, and the+ // second point must swing off the stops' shared meridian.+ assert_eq!(l.coords.len(), 10);+ assert!(l.coords[2] > -122.400, "on the eastward detour");+ }++ #[test]+ fn rail_lines_skip_a_bbox_no_stop_serves() {+ let idx = shaped_route_pack().index();+ let lines = rail_lines(&idx, 40.0, -75.0, 41.0, -74.0);+ assert!(lines.is_empty(), "far from the SF stops: nothing to draw");+ }++ #[test]+ fn trip_itinerary_lists_every_stop_with_times() {+ let idx = one_route_pack().index();+ // Vehicle id for route 0, trip 0, today: the packing active_vehicles uses.+ let id = (0i64 << 32) | (0i64 << 1) | 0;+ let itin =+ trip_itinerary(&idx, id, sched(wednesday())).expect("trip 0 runs Wednesday");+ assert_eq!(itin.route_name, "N");+ assert_eq!(itin.headsign, "Downtown");+ assert!(!itin.cancelled);+ assert_eq!(itin.stops.len(), 3);+ assert_eq!(itin.stops[0].name, "Alpha");+ assert_eq!(itin.stops[2].name, "Gamma");+ assert_eq!(+ (itin.stops[0].dep_secs, itin.stops[2].arr_secs),+ (28_800, 29_400)+ );+ // Dwell at Beta: arrives 29_100, departs 29_160.+ assert_eq!(+ (itin.stops[1].arr_secs, itin.stops[1].dep_secs),+ (29_100, 29_160)+ );+ }++ #[test]+ fn trip_itinerary_refuses_an_unknown_trip() {+ let idx = one_route_pack().index();+ // Route 9 does not exist; trip 99 neither.+ assert!(+ trip_itinerary(&idx, (9i64 << 32) | (0i64 << 1), sched(wednesday())).is_none()+ );+ assert!(+ trip_itinerary(&idx, (0i64 << 32) | (99i64 << 1), sched(wednesday())).is_none()+ );+ }+ #[test] fn a_vehicle_sits_exactly_on_a_stop_at_its_scheduled_time() { let idx = one_route_pack().index();