Modern Apps git

← Modern-Apps.git

maps: per-step frame timing with logcat rollup

Commit
80d55901557bfc7df3a042f2eb720bb4214bb8c2
Author
vayun-mathur <[email protected]>
When
2026-09-16 04:54 UTC (2 months ago)
Parents
a06186f

Diff

library/map/src/main/rust/src/bridge/frame.rs
diff --git a/library/map/src/main/rust/src/bridge/frame.rs b/library/map/src/main/rust/src/bridge/frame.rsindex a34642fdee..62e18fbdfd 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -5,6 +5,7 @@ use crate::camera::Camera; use crate::style; use crate::tile::select; use crate::tile::source::retry_delay_ms;+use crate::timing::{Step, nanos_since}; use jni::objects::JClass; use jni::sys::{jboolean, jfloat, jlong}; use jni::JNIEnv;@@ -28,6 +29,9 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     frame_time_nanos: jlong, ) -> jboolean {     let Some(map) = handle_mut(handle) else { return 0 };+    // Per-step timing for the `%60` rollup: `Instant` deltas only, never the camera clock+    // (which wraps hourly). The render thread is the only writer.+    let jni_start = std::time::Instant::now();      // The camera zoom crosses the boundary untouched. MapLibre parity is     // `camera::TILE_SIZE` being 512, the convention the archives are authored on, so@@ -63,6 +67,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // Upload whatever the workers finished, up to `UPLOADS_PER_FRAME`. Doing it here rather than     // on a worker keeps every Vulkan call on one thread; bounding it keeps a burst of finished     // tiles from landing in a single frame.+    let drain_start = std::time::Instant::now();     let mut uploads = 0usize;     while uploads < UPLOADS_PER_FRAME {         let Ok((key, result)) = map.finished.try_recv() else { break };@@ -107,6 +112,11 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // `visible` goes to `retain` as well as to the fetch loop, because the other half of the     // fallback — already-resident *descendants*, which are what stops a zoom-out blanking the     // map — cannot be named in a keep list without enumerating tiles that were never fetched.+    //+    // The drain sample lands here rather than right after the loop: it covers the channel+    // receives and the uploads, not the select below.+    map.renderer.step_times.borrow_mut().record(Step::UploadDrain, nanos_since(drain_start));+    let select_start = std::time::Instant::now();     let (min_zoom, max_zoom) = map.zoom_range.get();     // A tile is "had" only if it was tessellated at the current toggle generation, so a     // toggle change re-requests the resident set through this same loop rather than@@ -143,6 +153,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         map.retry.retain(|key, _| visible.iter().any(|t| t.key() == *key));     }     map.renderer.retain(&keep, &visible, RESIDENT_TILE_CAP);+    map.renderer.step_times.borrow_mut().record(Step::Select, nanos_since(select_start));      // Once a second, state what the renderer actually has. Every bug in this file so far has     // been invisible from the outside: a viewport nobody measured, a zoom level the archive@@ -155,9 +166,13 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         // `meshes` is what is resident, `draws` what the last frame actually submitted. They         // differ wherever the authored style ramps a layer's width to zero, so reporting only         // the first would claim roads are being drawn at zooms where they are gated out.+        //+        // The step rollup is built (and its window reset) only on this frame: every other+        // frame pays integer stores only. `avg/max` per step in ms over the last 60 frames.+        let steps = map.renderer.step_times.borrow_mut().report(60);         log_info(&format!(             "z{:.2} @{:.4},{:.4} b{:.0} vp {}x{}dp {}x{}px msaa {}x | resident {} tiles, {} meshes, \-             {} draws, {} tris | {} in flight, {} absent | archive z{}..{}",+             {} draws, {} tris | {} in flight, {} absent | archive z{}..{} | {}",             camera.zoom,             camera.center_lon,             camera.center_lat,@@ -175,6 +190,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(             map.absent.len(),             min_zoom,             max_zoom,+            steps,         ));     } @@ -182,13 +198,17 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // narrows which POIs are drawn and pulls its own kinds in earlier than the ambient map shows     // them. See `Layer::draws_at_focused`.     let (_, kinds, _) = map.toggles.get();-    match map.renderer.render(+    let outcome = map.renderer.render(         &camera,         &map.layers,         map.palette,         style::background(map.palette.variant),         &kinds,-    ) {+    );+    // The JNI-entry sample closes here: it covers drain + select + render, which is the whole+    // native half of the frame the host asked for.+    map.renderer.step_times.borrow_mut().record(Step::JniEntry, nanos_since(jni_start));+    match outcome {         Ok(drawn) => jboolean::from(drawn),         Err(e) => {             log(&format!("frame failed: {e}"));@@ -196,3 +216,31 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         }     } }++/// The last frame's per-step times in nanos, in [`Step::ALL`](crate::timing::Step) order.+///+/// For the debug overlay's slow poll (~2–4 Hz): a copy, so the render thread never blocks on it.+/// A dead handle (or a JNI failure) answers an empty array rather than crashing — the overlay+/// reads that as "no data yet". Must never drive `needs_frame` or alter the frame loop.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_lastFrameStepTimesNanos<'l>(+    env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+) -> jni::sys::jlongArray {+    let empty = env.new_long_array(0).expect("step-times empty array");+    let Some(map) = handle_mut(handle) else { return empty.into_raw() };+    let last = map.renderer.step_times.borrow();+    let nanos = last.last_nanos();+    let out = match env.new_long_array(nanos.len() as i32) {+        Ok(a) => a,+        Err(_) => return empty.into_raw(),+    };+    // `i64` is only the JNI carrier: the samples are `u64` nanos, and no step of a frame can+    // reach the sign bit, so the cast is exact.+    let wide: Vec<i64> = nanos.iter().map(|&n| n as i64).collect();+    if env.set_long_array_region(&out, 0, &wide).is_err() {+        return empty.into_raw();+    }+    out.into_raw()+}
library/map/src/main/rust/src/lib.rs
diff --git a/library/map/src/main/rust/src/lib.rs b/library/map/src/main/rust/src/lib.rsindex 1b1adaa7db..82eb42ad63 100644--- a/library/map/src/main/rust/src/lib.rs+++ b/library/map/src/main/rust/src/lib.rs@@ -13,6 +13,8 @@ //! * [`camera`] — a camera snapshot from Kotlin to a per-tile clip matrix. //! * [`overlay`] — geographic polylines that are not tile data: the navigation route. //! * [`tile`] — the streaming mamaps reader, its range cache, and tile selection.+//! * [`timing`] — per-step frame timing: `Instant` deltas on the render thread, no Vulkan, no+//!   JNI, host-testable. //! * `vulkan` — device, swapchain, pipelines, frame. Android only. //! //! # The JNI boundary@@ -42,6 +44,7 @@ pub mod pipeline_cache; pub mod style; pub mod tess; pub mod tile;+pub mod timing;  #[cfg(target_os = "android")] pub mod vulkan;
library/map/src/main/rust/src/timing.rs
diff --git a/library/map/src/main/rust/src/timing.rs b/library/map/src/main/rust/src/timing.rsnew file mode 100644index 0000000000..d37ef13555--- /dev/null+++ b/library/map/src/main/rust/src/timing.rs@@ -0,0 +1,241 @@+//! Per-step frame timing: `Instant` deltas on the render thread, nothing else.+//!+//! The frame log used to say only how many draws and triangles the last frame submitted, so a+//! janky pan or tilt could not be attributed to a stage — upload drain, tile select, fence wait,+//! each record sub-pass, submit, present. This module times each of those steps separately, so+//! the once-a-second `%60` rollup can say *which* one owns the tail.+//!+//! # Cost model+//!+//! Every frame pays one [`Instant::now`](std::time::Instant::now) pair per step and three integer+//! array stores in [`StepTimes::record`] — no allocation, no formatting. The rollup string is+//! built only on report frames (every 60th), in [`StepTimes::report`], which also resets the+//! window. A slow UI poll reads the last frame's array through [`StepTimes::last_nanos`] for the+//! debug overlay; the render thread never blocks on it.+//!+//! # Clocks+//!+//! [`Instant`](std::time::Instant), never the camera's `time_seconds`: that clock wraps hourly+//! (see [`CLOCK_WRAP_NANOS`](crate::camera::CLOCK_WRAP_NANOS)) and a delta across a wrap would+//! read as an hour. `Instant` is monotonic and the whole chain runs on one thread, so a pair of+//! reads around a step is exact.+//!+//! Host-testable: no Vulkan, no JNI, pure integer math over injected samples.++/// One timed step of a frame, in the order the frame runs them.+///+/// Short names are the `%60` logcat labels; [`Step::ALL`] fixes the order the JNI getter and the+/// Kotlin overlay mirror, so adding a step means appending here *and* there (the overlay+/// size-checks the array and shows `n/a` on drift rather than mislabelling rows).+#[derive(Clone, Copy)]+pub(crate) enum Step {+    /// The whole JNI `render` call, entry to return.+    JniEntry,+    /// Draining finished worker tiles into uploads (bounded by `UPLOADS_PER_FRAME`).+    UploadDrain,+    /// Visible-tile select plus the fetch loop and resident-set retain.+    Select,+    /// Waiting on the frame slot's in-flight fence.+    FenceWait,+    /// Freeing retired buffers plus the scratch-ring reset.+    CollectRetired,+    /// Acquiring the next swapchain image.+    Acquire,+    /// The whole `record` (command-buffer build), entry to end.+    RecordTotal,+    /// The global symbol collision pre-pass plus the pick snapshot refresh.+    PlaceSymbols,+    /// The DEM ground-grid pass.+    RecordTerrain,+    /// The flat fill/line layer loop.+    RecordFlat,+    /// The road-carriageway ribbon pass.+    RecordCarriageways,+    /// The extruded-buildings pass.+    RecordBuildings,+    /// The deferred per-tile symbol draws.+    RecordSymbols,+    /// The live-traffic overlay pass.+    RecordTraffic,+    /// The lane-arrow batch builds and draws.+    RecordArrows,+    /// The region-mask stencil plus scrim.+    RecordRegion,+    /// The rail-lines network under the route.+    RecordRail,+    /// Markers, vehicles and the puck.+    RecordOverlays,+    /// The `queue_submit`.+    Submit,+    /// The `queue_present`.+    Present,+}++impl Step {+    /// Every step, in frame order. The JNI getter returns [`StepTimes::last_nanos`] in this+    /// order; the Kotlin overlay labels rows from its mirror of it.+    pub(crate) const ALL: [Step; 20] = [+        Step::JniEntry,+        Step::UploadDrain,+        Step::Select,+        Step::FenceWait,+        Step::CollectRetired,+        Step::Acquire,+        Step::RecordTotal,+        Step::PlaceSymbols,+        Step::RecordTerrain,+        Step::RecordFlat,+        Step::RecordCarriageways,+        Step::RecordBuildings,+        Step::RecordSymbols,+        Step::RecordTraffic,+        Step::RecordArrows,+        Step::RecordRegion,+        Step::RecordRail,+        Step::RecordOverlays,+        Step::Submit,+        Step::Present,+    ];++    /// Steps timed per frame.+    pub(crate) const COUNT: usize = Self::ALL.len();++    /// The `%60` logcat label: short, fixed-width-ish, unambiguous at a glance.+    pub(crate) fn short_name(self) -> &'static str {+        match self {+            Step::JniEntry => "jni",+            Step::UploadDrain => "upl",+            Step::Select => "sel",+            Step::FenceWait => "fen",+            Step::CollectRetired => "ret",+            Step::Acquire => "acq",+            Step::RecordTotal => "rec",+            Step::PlaceSymbols => "plc",+            Step::RecordTerrain => "ter",+            Step::RecordFlat => "flt",+            Step::RecordCarriageways => "car",+            Step::RecordBuildings => "bld",+            Step::RecordSymbols => "sym",+            Step::RecordTraffic => "trf",+            Step::RecordArrows => "arw",+            Step::RecordRegion => "msk",+            Step::RecordRail => "ral",+            Step::RecordOverlays => "ovl",+            Step::Submit => "sub",+            Step::Present => "prs",+        }+    }+}++/// The per-step timing state for one renderer.+///+/// Three fixed arrays plus the window length: the last frame's steps (for the JNI getter), and+/// the rolling sum/max the `%60` rollup reports. Fixed-size and allocation-free by construction —+/// [`record`](Self::record) is three integer stores, and only [`report`](Self::report) formats.+pub(crate) struct StepTimes {+    last: [u64; Step::COUNT],+    sum: [u64; Step::COUNT],+    max: [u64; Step::COUNT],+}++impl StepTimes {+    /// Empty: every step reads 0 until its first frame.+    pub(crate) fn new() -> Self {+        StepTimes { last: [0; Step::COUNT], sum: [0; Step::COUNT], max: [0; Step::COUNT] }+    }++    /// Time one step's sample: the index is the step's position in [`Step::ALL`].+    ///+    /// Integer adds/stores only — this runs twenty times a frame, so it must not allocate, format+    /// or branch on anything but the max.+    pub(crate) fn record(&mut self, step: Step, nanos: u64) {+        let at = step as usize;+        self.last[at] = nanos;+        self.sum[at] = self.sum[at].saturating_add(nanos);+        if nanos > self.max[at] {+            self.max[at] = nanos;+        }+    }++    /// The last frame's step times in [`Step::ALL`] order, for the JNI getter's copy.+    pub(crate) fn last_nanos(&self) -> &[u64; Step::COUNT] {+        &self.last+    }++    /// The `avg/max` rollup over the last `frames` frames, in ms with one decimal, then reset the+    /// window. Called only on report frames, so this is the one place that formats.+    ///+    /// `frames` is the window length (60 on the `%60` cadence), not read from here, so a frame+    /// that never ran a step still divides correctly.+    pub(crate) fn report(&mut self, frames: u32) -> String {+        let frames = frames.max(1) as u64;+        let mut out = String::from("steps");+        for step in Step::ALL {+            let at = step as usize;+            let avg_ms = self.sum[at] as f64 / frames as f64 / 1_000_000.0;+            let max_ms = self.max[at] as f64 / 1_000_000.0;+            out.push_str(&format!(" {} {avg_ms:.1}/{max_ms:.1}", step.short_name()));+            self.sum[at] = 0;+            self.max[at] = 0;+        }+        out+    }+}++/// Nanos between two `Instant` reads, saturating rather than wrapping on absurd values.+pub(crate) fn nanos_since(start: std::time::Instant) -> u64 {+    u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn a_fresh_timer_reads_zero() {+        let t = StepTimes::new();+        assert!(t.last_nanos().iter().all(|&n| n == 0));+    }++    #[test]+    fn record_keeps_last_sum_and_max() {+        let mut t = StepTimes::new();+        t.record(Step::Select, 100);+        t.record(Step::Select, 300);+        assert_eq!(t.last_nanos()[Step::Select as usize], 300);+        // Avg over a 2-frame window is 200 ns; max is the worst sample.+        let line = t.report(2);+        assert!(line.contains("sel 0.0/0.0"), "200ns rounds to 0.0ms, got {line}");+        // A millisecond-scale sample to check the decimals are real.+        t.record(Step::Present, 2_500_000);+        let line = t.report(1);+        assert!(line.contains("prs 2.5/2.5"), "got {line}");+    }++    #[test]+    fn report_resets_the_window() {+        let mut t = StepTimes::new();+        t.record(Step::Submit, 1_000_000);+        let _ = t.report(1);+        let line = t.report(1);+        assert!(line.contains("sub 0.0/0.0"), "the window must reset after a report, got {line}");+        // But the last-frame array survives for the JNI getter.+        assert_eq!(t.last_nanos()[Step::Submit as usize], 1_000_000);+    }++    #[test]+    fn every_step_has_a_distinct_short_name() {+        let mut names: Vec<&str> = Step::ALL.iter().map(|s| s.short_name()).collect();+        names.sort_unstable();+        names.dedup();+        assert_eq!(names.len(), Step::COUNT, "short names must be unambiguous in logcat");+    }++    #[test]+    fn step_discriminants_match_all_order() {+        // `record` indexes by `as usize`: the enum order and ALL order must agree.+        for (at, step) in Step::ALL.iter().enumerate() {+            assert_eq!(*step as usize, at, "Step::{:?} sits at the wrong index", step.short_name());+        }+    }+}
library/map/src/main/rust/src/vulkan/renderer/frame.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/frame.rs b/library/map/src/main/rust/src/vulkan/renderer/frame.rsindex 9e24b15640..7536bbb768 100644--- a/library/map/src/main/rust/src/vulkan/renderer/frame.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/frame.rs@@ -3,6 +3,7 @@ use crate::camera::Camera; use crate::marker::Marker; use crate::style::{Layer, Palette}; use crate::tile::select;+use crate::timing::{Step, nanos_since}; use ash::vk;  impl Renderer {@@ -223,18 +224,26 @@ impl Renderer {          let frame = &self.frames[self.frame_index];         let device = &self.context.device;+        let fence_start = std::time::Instant::now();         unsafe {             device                 .wait_for_fences(std::slice::from_ref(&frame.in_flight), true, u64::MAX)                 .map_err(|e| format!("wait_for_fences {e:?}"))?;         }+        let fence_nanos = nanos_since(fence_start);         // Only now is it safe to free what previous frames referenced.+        let retire_start = std::time::Instant::now();         self.collect_retired();         // Same fence, same reason: it says this frame slot's previous commands have retired, so         // nothing is still reading the scratch they drew from.         unsafe { self.scratch[self.frame_index].reset() };+        let retire_nanos = nanos_since(retire_start);+        let fence_sample = fence_nanos;+        self.step_times.borrow_mut().record(Step::FenceWait, fence_sample);+        self.step_times.borrow_mut().record(Step::CollectRetired, retire_nanos);          let frame = &self.frames[self.frame_index];+        let acquire_start = std::time::Instant::now();         let acquired = unsafe {             self.swapchain.loader.acquire_next_image(                 self.swapchain.swapchain,@@ -243,6 +252,7 @@ impl Renderer {                 vk::Fence::null(),             )         };+        self.step_times.borrow_mut().record(Step::Acquire, nanos_since(acquire_start));         let image_index = match acquired {             Ok((index, _suboptimal)) => index,             Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => {@@ -271,7 +281,10 @@ impl Renderer {             device                 .reset_fences(std::slice::from_ref(&in_flight))                 .map_err(|e| format!("reset_fences {e:?}"))?;-            self.record(command_buffer, image_index as usize, camera, layers, palette, clear, filter)?;+            let record_start = std::time::Instant::now();+            let record_outcome = self.record(command_buffer, image_index as usize, camera, layers, palette, clear, filter);+            self.step_times.borrow_mut().record(Step::RecordTotal, nanos_since(record_start));+            record_outcome?;              let wait_stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];             let submit = vk::SubmitInfo::default()@@ -282,9 +295,11 @@ impl Renderer {             let queue = self.context.queue;             let swapchain = self.swapchain.swapchain;             let loader = self.swapchain.loader.clone();+            let submit_start = std::time::Instant::now();             device                 .queue_submit(queue, std::slice::from_ref(&submit), in_flight)                 .map_err(|e| format!("queue_submit {e:?}"))?;+            self.step_times.borrow_mut().record(Step::Submit, nanos_since(submit_start));              let swapchains = [swapchain];             let indices = [image_index];@@ -292,7 +307,10 @@ impl Renderer {                 .wait_semaphores(std::slice::from_ref(&render_finished))                 .swapchains(&swapchains)                 .image_indices(&indices);-            match loader.queue_present(queue, &present) {+            let present_start = std::time::Instant::now();+            let present_outcome = loader.queue_present(queue, &present);+            self.step_times.borrow_mut().record(Step::Present, nanos_since(present_start));+            match present_outcome {                 Ok(false) => {}                 // `VK_SUBOPTIMAL_KHR` is a success code, not an error: the swapchain still                 // presents correctly, it just no longer matches the surface's ideal properties.
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 a5a2b48f2f..40d2fb9fd5 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@@ -14,6 +14,7 @@ use super::{     AcceptSet, Frame, Overlay, PlacedHit, PlacementKey, Quad, ResidentTile, RouteBuffers,     TransientBuffers, };+use crate::style::LayerKind;  pub struct Renderer {     pub(crate) context: Context,@@ -31,6 +32,33 @@ pub struct Renderer {     pub(crate) sprite_atlas: Option<SampledImage>,     pub(crate) sprite_set: Option<vk::DescriptorSet>,     pub(crate) command_pool: vk::CommandPool,+    /// Per-frame scratch, reused across frames rather than reallocated per record.+    ///+    /// `record_inner` runs on every frame on the Choreographer callback; allocating its working+    /// sets (`draws`, `ordered`, `resident`, `tile_alpha`, `deferred_symbols`) fresh each time+    /// is allocator traffic for values that are recomputed wholesale. These live on the renderer+    /// and are cleared at the top of each record instead.+    pub(crate) scratch_draws: Vec<(+        u8,+        u32,+        u32,+        LayerKind,+        ash::vk::Buffer,+        ash::vk::Buffer,+        u32,+        u32,+        Option<u32>,+        (u8, u8, u8),+    )>,+    /// Resident-tile keys sorted coarsest-first for draw order (see `record_inner`).+    pub(crate) scratch_ordered: Vec<u64>,+    /// Resident-tile key set for the LOD cross-fade + placement key.+    pub(crate) scratch_resident: std::collections::HashSet<u64>,+    /// Per-tile LOD opacity for the frame (see `tile_lod_alpha`).+    pub(crate) scratch_tile_alpha: std::collections::HashMap<u64, f32>,+    /// `(tile key, layer index)` symbol draws deferred past the buildings pass.+    pub(crate) scratch_deferred_symbols: Vec<(u64, usize)>,+    /// Per-frame synchronisation and its command buffer.     pub(crate) frames: Vec<Frame>,     pub(crate) frame_index: usize,     pub(crate) tiles: HashMap<u64, ResidentTile>,@@ -64,18 +92,29 @@ pub struct Renderer {     /// A `Cell` because `record` takes `&self`; the frame path is single-threaded, as the     /// module docs of [`crate::bridge`] set out.     pub(crate) submitted_draws: Cell<usize>,+    /// Per-step frame timing (see [`crate::timing`]): last-frame steps plus the rolling+    /// sum/max the `%60` rollup reports. A `RefCell` because the record sub-passes take `&self`+    /// — the same reason `placed` is one — and each record is a short leaf borrow.+    pub(crate) step_times: std::cell::RefCell<crate::timing::StepTimes>,     /// Task-17 pick state: the last frame's PLACED labels — accept-set id,     /// screen box in DEVICE px, layer index, display name, kind string, and     /// anchor lon/lat — so `pick_labels` answers without re-tessellating.-    /// Refreshed by `record_inner` every frame; read by the JNI pick path.+    /// Refreshed by `record_inner` only when the accept-set changes (see the+    /// `last_accept_ids` guard there); read by the JNI pick path.     pub(crate) placed: std::cell::RefCell<Vec<PlacedHit>>,+    /// Sorted accept-set ids of the last `refresh_placed`, so `record_inner` can skip the+    /// per-frame String clones when the placement was reused (see `PLACE_REUSE_MS`).+    pub(crate) last_accept_ids: std::cell::RefCell<Option<Vec<u64>>>,     /// The last symbol placement and the state it was computed from.     ///     /// [`place_symbols`](Self::place_symbols) projects a collision box for every glyph of every     /// curved label and then runs a solver that is quadratic in accepted boxes, all of it on the     /// Choreographer callback. None of that depends on the frame clock, so a camera that has not-    /// moved gets last frame's answer instead of the same computation again.-    pub(crate) placement_cache: std::cell::RefCell<Option<(PlacementKey, AcceptSet)>>,+    /// moved gets last frame's answer instead of the same computation again — and a camera that+    /// has only *panned* within [`PLACE_REUSE_MS`](super::PLACE_REUSE_MS) reuses it+    /// too, which is what keeps panning from re-placing every frame.+    pub(crate) placement_cache:+        std::cell::RefCell<Option<(PlacementKey, AcceptSet, std::time::Instant)>>,     /// What this frame draws on top of every tile, in order. See [`Overlay`].     pub(crate) overlays: Vec<Overlay>,     /// The geometry every overlay shares, uploaded once.
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 36af435bbd..98ea24ff12 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record.rs@@ -3,14 +3,16 @@ use super::{     PUCK_CONE_HALF_STROKE_DP, PUCK_DOT_DP, PUCK_QUAD_DP, PUCK_RIM_DP, QUAD_INDICES, Renderer,     SCRIM_COLOR, TRAFFIC_WIDTH_DP, UserPuck, anchors_for, argb_to_rgba, scale_alpha, };+use super::fog::{apply_fog, fog_factor}; use crate::camera::Camera; use crate::marker::{Marker, MARKER_SIZE_DP}; use crate::style::paint::Stroke; use crate::style::{Layer, LayerKind, Palette}; use crate::tile::select;+use crate::timing::{Step, nanos_since}; use crate::vulkan::pipeline::{MORPH_NONE, NO_MARKINGS, Push}; use ash::vk;-use std::collections::{HashMap, HashSet};+use std::collections::HashMap; use tilecodec::mamaps::dict::LAYER_JUNCTION;  impl Renderer {@@ -144,82 +146,110 @@ impl Renderer {          let mut bound: Option<LayerKind> = None;         let mut submitted = 0usize;-        // One tile-layer's draws, reused across the whole frame.+        // One tile-layer's draws, reused across the whole frame — and across frames: the+        // buffer lives on the renderer (`scratch_draws`) and is only cleared per tile below,+        // so a frame pays no allocation for it.         //         // A layer used to have at most one mesh per tile, so the draw could be a single         // `find`. Transit breaks that: a tile holding two route colours emits two meshes         // for one layer, and a `find` would silently draw only the first line. Copying the         // handles out (rather than iterating `self.tiles` in place) is what keeps-        // `record_symbol`'s `&mut self` call legal in the sibling arm below; hoisting the-        // `Vec` out of the loop and clearing it keeps that free of allocation.-        #[allow(clippy::type_complexity)]-        let mut draws: Vec<(-            u8,-            u32,-            u32,-            LayerKind,-            vk::Buffer,-            vk::Buffer,-            u32,-            Option<u32>,-            (u8, u8, u8),-        )> = Vec::new();-        // Coarsest tiles first, so an ancestor standing in for a tile that has not arrived-        // is drawn *under* its descendants and gets covered as they load. A HashMap's-        // iteration order is arbitrary, so without this a stale parent can land on top of-        // the sharp child. Keys (not refs) so `record_symbol` can take `&mut self`.-        let mut ordered: Vec<u64> = self.tiles.keys().copied().collect();-        ordered.sort_by_key(|k| self.tiles.get(k).map(|t| t.z).unwrap_or(0));--        // WS-D LOD cross-fade: one opacity per resident tile for this frame, written into each-        // tile draw's `Push.morph.x` below. A finer tile ramps 0→1 over `LOD_FADE_SECONDS` from-        // its `uploaded_at` stamp *while* a coarse ancestor is resident to stand in under the gap-        // (see `tile_lod_alpha`); a tile with nothing beneath it stays fully opaque, so a freshly-        // fetched area never fades up from the background. Computed once here, not per layer.-        let now = camera.time_seconds;-        let resident: HashSet<u64> = self.tiles.keys().copied().collect();-        let tile_alpha: HashMap<u64, f32> = ordered-            .iter()-            .map(|&key| {+        // `record_symbol`'s `&mut self` call legal in the sibling arm below; reusing the+        // buffer keeps that free of allocation.+        //+        // Borrowed out once here (not per tile below): `draws`/`ordered`/`tile_alpha` are+        // disjoint fields from `self.tiles`, and the loop's `&mut self` symbol call needs+        // the compiler to see that. Split at the top, rejoined after the loop.+        let (draws, ordered, tile_alpha) = {+            self.scratch_draws.clear();+            self.scratch_ordered.clear();+            self.scratch_ordered.extend(self.tiles.keys().copied());+            self.scratch_ordered+                .sort_by_key(|k| self.tiles.get(k).map(|t| t.z).unwrap_or(0));+            // WS-D LOD cross-fade: one opacity per resident tile for this frame, written into+            // each tile draw's `Push.morph.x` below. A finer tile ramps 0→1 over+            // `LOD_FADE_SECONDS` from its `uploaded_at` stamp *while* a coarse ancestor is+            // resident to stand in under the gap (see `tile_lod_alpha`); a tile with nothing+            // beneath it stays fully opaque, so a freshly fetched area never fades up from the+            // background. Computed once here, not per layer.+            let now = camera.time_seconds;+            self.scratch_resident.clear();+            self.scratch_resident.extend(self.tiles.keys().copied());+            self.scratch_tile_alpha.clear();+            for &key in &self.scratch_ordered {                 let uploaded_at = self.tiles.get(&key).map(|t| t.uploaded_at).unwrap_or(0.0);-                (+                self.scratch_tile_alpha.insert(                     key,                     select::tile_lod_alpha(                         key,                         uploaded_at,                         now,                         select::LOD_FADE_SECONDS,-                        &resident,+                        &self.scratch_resident,                     ),-                )-            })-            .collect();+                );+            }+            let Self {+                scratch_draws: draws,+                scratch_ordered: ordered,+                scratch_tile_alpha: tile_alpha,+                tiles: _,+                ..+            } = self;+            (draws as *mut _, ordered as *const _, tile_alpha as *const _)+        };+        // SAFETY: the three pointers name disjoint fields; `tiles` (shared through `self`+        // below) overlaps none of them. They are only used for the draw loop's duration.+        let (draws, ordered, tile_alpha): (+            &mut Vec<(u8, u32, u32, LayerKind, vk::Buffer, vk::Buffer, u32, u32, Option<u32>, (u8, u8, u8))>,+            &Vec<u64>,+            &HashMap<u64, f32>,+        ) = unsafe { (&mut *draws, &*ordered, &*tile_alpha) };          // Symbol pre-pass: collision runs GLOBALLY across tiles and layers, but         // draws stay per (tile, layer) below. Build one candidate per shaped         // label with its screen box at this frame's text size, run the greedy         // rank-ordered placer once, and hand the accept-set to `record_symbol`.         // Without this every shaped label draws and z10 is an unreadable pile.+        let place_start = std::time::Instant::now();         let accepted = self.place_symbols(camera, layers, &ordered, extent, filter);+        self.step_times.borrow_mut().record(Step::PlaceSymbols, nanos_since(place_start));         // Task-17 pick snapshot: the accepted labels with their screen boxes,-        // names, kinds and anchor geo — refreshed every frame so pickLabels-        // answers the frame the user sees, not a stale one.-        self.refresh_placed(camera, layers, &accepted, extent);+        // names, kinds and anchor geo — refreshed only when the accept-set is new, so a+        // reused placement (see PLACE_REUSE_MS) does not re-clone every name/kind String+        // per frame. Boxes still track the camera because the projection inputs are the+        // current frame's; only the *collision outcome* (which labels are in) lags.+        let mut accept_ids: Vec<u64> = accepted.keys().copied().collect();+        accept_ids.sort_unstable();+        if self.last_accept_ids.borrow().as_ref() != Some(&accept_ids) {+            self.refresh_placed(camera, layers, &accepted, extent);+            *self.last_accept_ids.borrow_mut() = Some(accept_ids);+        }          // 3D terrain (WS-G): the DEM-displaced ground, drawn first (step 0) with depth on so it is         // the ground the flat layers below sit over. A tile with no heightmap draws nothing here and         // keeps its flat `earth` fill in the loop; at pitch 0 the grid collapses to the flat         // footprint, so the overhead map is unchanged.-        self.record_terrain(command_buffer, camera, layers, palette, &mut submitted);+        let step_start = std::time::Instant::now();+        self.record_terrain(command_buffer, camera, layers, palette, clear, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordTerrain, nanos_since(step_start));          // Symbol layers are collected here and drawn after the buildings pass rather than inside         // the loop. Buildings have no depth interaction with symbols (the symbol pipelines are         // `Depth::Off`, so they can never *fail* a test) — whichever is issued last simply paints         // over the other, and issuing buildings last hid every tile-baked POI icon and label         // behind them. `(key, layer index)`, replayed in the same order the loop met them.-        let mut deferred_symbols: Vec<(u64, usize)> = Vec::new();+        // Reused across frames on the renderer like the draw buffers above.+        let deferred_symbols = {+            self.scratch_deferred_symbols.clear();+            let Self { scratch_deferred_symbols: deferred, tiles: _, .. } = self;+            deferred as *mut _+        };+        // SAFETY: same disjoint-field split as the draw buffers above.+        let deferred_symbols: &mut Vec<(u64, usize)> = unsafe { &mut *deferred_symbols };          let camera_z = camera.zoom.floor().clamp(0.0, 22.0) as u8;+        let flat_start = std::time::Instant::now();         for (index, layer) in layers.iter().enumerate() {             // `min_zoom`/`max_zoom` are a data-and-cost gate, not paint: they say which zooms             // the archive is worth asking for this layer at. Paint is the ramp below.@@ -266,7 +296,7 @@ impl Renderer {                     (Stroke::NONE, layer.opacity_at(camera.zoom))                 }             };-            for key in &ordered {+            for key in ordered.iter() {                 // Symbol layers emit per frame at the frame's text size from the                 // tile's shaped candidates (see above): deferred to after the buildings                 // pass so labels are not painted over, then drawn with `&mut self` for@@ -283,17 +313,33 @@ impl Renderer {                 }                 // Copy the draw's inputs out, then issue them through the owned `device`                 // clone: `record_symbol` above takes `&mut self`, so this path must not-                // hold a `self.tiles` borrow either.+                // hold a `self.tiles` borrow either. Draws read from the tile's pooled+                // buffers (bound once per tile below), so only the pool pair plus the+                // slice's firstIndex ride here.                 draws.clear();                 if let Some(tile) = self.tiles.get(key) {+                    let pool = match layer.kind {+                        LayerKind::Fill => tile.flat.as_ref().map(|(v, i)| (v.buffer, i.buffer)),+                        LayerKind::Line => tile.lines.as_ref().map(|(v, i)| (v.buffer, i.buffer)),+                        LayerKind::Symbol => None,+                    };+                    let Some((pool_vbuf, pool_ibuf)) = pool else {+                        // No pool means no mesh of this format packed — nothing to draw.+                        // (Symbols never take this path; see the deferred arm above.)+                        if layer.kind == LayerKind::Symbol {+                            continue;+                        }+                        continue;+                    };                     for mesh in tile.layers.iter().filter(|l| l.layer_index == index) {                         draws.push((                             tile.z,                             tile.x,                             tile.y,                             mesh.kind,-                            mesh.vertices.buffer,-                            mesh.indices.buffer,+                            pool_vbuf,+                            pool_ibuf,+                            mesh.first_index,                             mesh.index_count,                             mesh.color_override,                             mesh.lane,@@ -305,7 +351,8 @@ impl Renderer {                 // (owned by WS-B's `line.frag`) ignores `morph.x`, so road casings stay crisp                 // while the fill fades — the fade reads as the flat basemap ramping in.                 let tile_fade = tile_alpha.get(key).copied().unwrap_or(1.0);-                for &(tz, tx, ty, kind, vbuf, ibuf, count, color_override, lane) in &draws+                for &(tz, tx, ty, kind, vbuf, ibuf, first_index, count, color_override, lane)+                    in draws.iter()                 {                     if bound != Some(kind) {                         let pipeline = match kind {@@ -339,6 +386,10 @@ impl Renderer {                     // whatever the dark basemap thinks red should be. The opacity ramp still                     // applies, because that is per-frame paint rather than palette.                     let base = color_override.unwrap_or_else(|| layer.color(palette));+                    // Distance fog: haze the draw toward the background with its tile's+                    // distance, so tilted far tiles dissolve instead of ending at a hard+                    // ground edge. Zero at pitch 0 — the flat map is unchanged.+                    let base = apply_fog(base, clear, fog_factor(camera, tz, tx, ty));                     // How far this mesh's whole band shifts sideways, in device pixels. The                     // feature carries its colour's ordinal and its corridor's colour count,                     // not an offset: how many lanes the corridor actually draws is a step@@ -371,9 +422,10 @@ impl Renderer {                     device.cmd_bind_vertex_buffers(command_buffer, 0, &[vbuf], &[0]);                     // Uint32 rather than Uint16: a dense z14 tile can exceed 65535 vertices in                     // one layer, and overflowing folds geometry back on itself rather than-                    // failing loudly.+                    // failing loudly. Indices are rebased to absolute at upload, so the slice+                    // draws from its firstIndex inside the shared pool.                     device.cmd_bind_index_buffer(command_buffer, ibuf, 0, vk::IndexType::UINT32);-                    device.cmd_draw_indexed(command_buffer, count, 1, 0, 0, 0);+                    device.cmd_draw_indexed(command_buffer, count, 1, first_index, 0, 0);                     submitted += 1;                 }             }@@ -395,13 +447,19 @@ impl Renderer {         // Road carriageways: over the flat layer loop, because the surface and its markings         // replace the road fills at this zoom, and under the buildings and deferred symbols         // below, because a carriageway is flat basemap like every other road layer.-        self.record_carriageways(command_buffer, camera, layers, palette, &ordered, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordFlat, nanos_since(flat_start));+        let step_start = std::time::Instant::now();+        self.record_carriageways(command_buffer, camera, layers, palette, &ordered, clear, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordCarriageways, nanos_since(step_start));         // 3D buildings: after the flat basemap so they paint over it, depth-tested so they occlude         // one another. Gated to z14+; at pitch 0 the building matrix collapses height to the         // footprint, so the flat overhead map is unchanged. Before the deferred symbols, so POI         // icons and labels are not buried behind a tower.+        let step_start = std::time::Instant::now();         self.record_buildings(command_buffer, camera, layers, palette, &mut submitted);-        for (key, index) in deferred_symbols {+        self.step_times.borrow_mut().record(Step::RecordBuildings, nanos_since(step_start));+        let step_start = std::time::Instant::now();+        for &(key, index) in deferred_symbols.iter() {             self.record_symbol(                 command_buffer,                 key,@@ -414,12 +472,25 @@ impl Renderer {                 &mut bound,             );         }+        self.step_times.borrow_mut().record(Step::RecordSymbols, nanos_since(step_start));+        let step_start = std::time::Instant::now();         self.record_traffic(command_buffer, camera, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordTraffic, nanos_since(step_start));+        let step_start = std::time::Instant::now();         self.record_arrows(command_buffer, camera, layers, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordArrows, nanos_since(step_start));+        let step_start = std::time::Instant::now();         self.record_region_mask(command_buffer, camera, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordRegion, nanos_since(step_start));+        let rail_start = std::time::Instant::now();         self.record_rail_lines(command_buffer, camera, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordRail, nanos_since(rail_start));+        // No route slot: it shares `record_route_buffers` with the rail lines, so its cost+        // rides on `RecordRail` rather than a slot that reads zero on route-less frames.         self.record_route(command_buffer, camera, &mut submitted);+        let step_start = std::time::Instant::now();         self.record_overlays(command_buffer, camera, palette, &mut submitted);+        self.step_times.borrow_mut().record(Step::RecordOverlays, nanos_since(step_start));          self.submitted_draws.set(submitted);         device.cmd_end_render_pass(command_buffer);
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 c76dc2e5ba..3d29fe240f 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@@ -1,4 +1,5 @@-use super::{FRAMES_IN_FLIGHT, Frame, QUAD_INDICES, QUAD_VERTICES, Quad, Renderer};+use super::{FRAMES_IN_FLIGHT, Frame, QUAD_INDICES, QUAD_VERTICES, Quad, Renderer, RouteBuffers, TransientBuffers};+use crate::overlay::RouteMesh; use crate::vulkan::buffers::{Buffer, ScratchRing}; use crate::vulkan::cache::ShaderCache; use crate::vulkan::context::{ANativeWindow, Context};@@ -8,7 +9,7 @@ use crate::vulkan::pipeline::Pipelines; use crate::vulkan::swapchain::Swapchain; use ash::vk; use std::cell::Cell;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};  impl Renderer {     /// # Safety@@ -167,7 +168,14 @@ impl Renderer {             height,             needs_rebuild: false,             submitted_draws: Cell::new(0),+            step_times: std::cell::RefCell::new(crate::timing::StepTimes::new()),             placed: std::cell::RefCell::new(Vec::new()),+            last_accept_ids: std::cell::RefCell::new(None),+            scratch_draws: Vec::new(),+            scratch_ordered: Vec::new(),+            scratch_resident: HashSet::new(),+            scratch_tile_alpha: HashMap::new(),+            scratch_deferred_symbols: Vec::new(),             placement_cache: std::cell::RefCell::new(None),             overlays: Vec::new(),             quad,@@ -181,3 +189,86 @@ impl Renderer {         })     } }++impl Renderer {+    /// Draw `mesh` as the navigation route, or take the route away with `None`.+    ///+    /// 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 {+                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.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(),+        })+    }+}