Modern Apps git

← Modern-Apps.git

map: P5 kinds-aware retessellation, MAILBOX present, cap tuning

Commit
239d4b1007e0bc0753f88bbc3870d59f71cf373d
Author
vayun-mathur <[email protected]>
When
2026-10-18 03:14 UTC (1 month ago)
Parents
cdd54d0

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 11a4b1ee06..24aa931ac6 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -188,8 +188,10 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     // 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     // needing a path of its own. The stale mesh keeps drawing until its replacement-    // arrives.-    let (_, _, generation) = map.toggles.get();+    // arrives. Read once: the snapshot, filter and generation must agree with each+    // other (and with the `kinds` the render call below takes), so two `get`s must+    // never straddle a `set`.+    let (snap_toggles, snap_kinds, generation) = map.toggles.get();     // Gesture debounce (MapLibre's "load while moving" rule): while a gesture is active     // the *fetch* zoom freezes at the gesture-start level, so a pinch does not churn the     // wanted set every frame with tiles that scroll out before they land. Rendering keeps@@ -314,7 +316,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(     let fetch_held = live_keys.difference(&frozen_set).count();     for tile in center_first(&visible).iter().chain(wash_extra.iter()) {         let key = tile.key();-        if map.renderer.has_tile(key, generation)+        if map.renderer.has_tile(key, generation, &snap_toggles, &snap_kinds)             || map.absent.contains(&key)             // Still inside its backoff after a failure. Left in `retry` rather than removed             // here, so the attempt count keeps climbing if it fails again.@@ -359,8 +361,9 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(      // The active category filter goes to the renderer as well as to tessellation: a chip both     // 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();+    // them. See `Layer::draws_at_focused`. This is the same snapshot the fetch loop above read —+    // re-reading here could straddle a `set` and disagree with it.+    let kinds = snap_kinds;     let outcome = map.renderer.render(         &camera,         &map.layers,
library/map/src/main/rust/src/bridge/handle.rs
diff --git a/library/map/src/main/rust/src/bridge/handle.rs b/library/map/src/main/rust/src/bridge/handle.rsindex 4439b4ff74..b4b3d11851 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -5,6 +5,10 @@ use crate::style::{Layer, Palette, SharedToggles}; use crate::bridge::gesture::GestureDebounce; use crate::tile::geometry::TileMesh; use crate::tile::select::TileId;+/// Re-exported so `bridge::frame` keeps its `super::handle::RESIDENT_TILE_CAP` path: the+/// constant lives in `tile::select` (with the retention policy and its measurement pin),+/// but the frame reads it through the handle.+pub(crate) use crate::tile::select::RESIDENT_TILE_CAP; use crate::vulkan::renderer::Renderer; use jni::sys::jlong; use std::collections::{HashMap, HashSet};@@ -75,22 +79,6 @@ impl ZoomRange { /// per-tile `queue/fetch/tess` logs showing fetch still dominating and thermals clean. pub(crate) const WORKER_COUNT: usize = 8; -/// The most tiles allowed resident on the GPU at once.-///-/// Eviction is the only thing bounding tile memory — there is no separate budget — so this is a-/// real limit rather than a safety net. It matters more now that descendants are kept: an-/// ancestor set is linear in depth, but a descendant set is not, and without a cap every deep-/// tile visited would stay resident for as long as the camera sat above it.-///-/// Sized from what the renderer reports rather than from theory. A dense z14 screenful logged-/// ~2.0 M triangles across 7 tiles, so a tile in a city centre costs single-digit megabytes of-/// vertex and index buffers; 64 leaves room for a ~12-tile viewport, its four ancestor levels and-/// a useful spread of descendants, while keeping the worst case in the hundreds of megabytes-/// rather than the gigabytes an uncapped depth-2 fan-out could reach. Going over drops-/// descendants first, so the cost of being wrong here is a briefly coarser zoom-out, not a blank-/// screen.-pub(crate) const RESIDENT_TILE_CAP: usize = 64;- /// How many finished tiles may be uploaded in one frame. /// /// The drain used to be unbounded, so however many tiles the workers happened to finish between
library/map/src/main/rust/src/style/filter.rs
diff --git a/library/map/src/main/rust/src/style/filter.rs b/library/map/src/main/rust/src/style/filter.rsindex 2fca25fa9f..b68e56586f 100644--- a/library/map/src/main/rust/src/style/filter.rs+++ b/library/map/src/main/rust/src/style/filter.rs@@ -53,6 +53,124 @@ impl KindFilter {         }         self.0.binary_search(&kind).is_ok()     }++    /// The subset of `source_kinds` this filter admits, sorted.+    ///+    /// The kinds-aware re-tessellation check ([`ToggleStamp::stale_under`]): a filter+    /// change rebuilds a tile only when the admitted set changed. An empty filter+    /// admits everything, so the answer is the source set itself.+    pub fn admitted(&self, source_kinds: &[u16]) -> Vec<u16> {+        if self.0.is_empty() {+            let mut out = source_kinds.to_vec();+            out.sort_unstable();+            out.dedup();+            return out;+        }+        let mut out: Vec<u16> = source_kinds+            .iter()+            .copied()+            .filter(|k| self.0.binary_search(k).is_ok())+            .collect();+        out.sort_unstable();+        out.dedup();+        out+    }+}++/// Which toggle-gated content a tile's source could emit, independent of the snapshot it+/// was built at.+///+/// Tessellation gates optional layers, so a mesh does not record what was gated *out* —+/// and without that, any toggle flip must rebuild every tile, because a tile built with+/// POI off might gain POIs when it turns on. This summary closes that gap: it is computed+/// from the source at build time (see `tile::geometry::build_toggled`), so `has_tile` can+/// prove a toggle change affects nothing here and skip the rebuild.+///+/// Only toggle-gated layers feed it. Basemap content is never gated, so no summary could+/// ever excuse it — and `matches_feature` over POI/transit/traffic candidates is integer+/// compares, not shaping, so recording this costs a fraction of what the gate saves.+#[derive(Clone, Debug, Default)]+pub struct GatedSummary {+    /// Distinct interned `kind`s of the source features a POI-toggle layer admits+    /// ([`Layer::matches_feature`]), before the category filter. The admitted set under a+    /// filter is [`KindFilter::admitted`] over this; a filter change rebuilds the tile+    /// only when that set changed.+    pub poi_kinds: Vec<u16>,+    /// A transit-toggle layer admits at least one source feature.+    pub has_transit: bool,+    /// The tile carries live-traffic segments (see `tile::geometry::traffic`).+    pub has_traffic: bool,+}++impl GatedSummary {+    /// The POI kinds this filter admits out of the source set, sorted.+    pub fn admitted(&self, filter: &KindFilter) -> Vec<u16> {+        filter.admitted(&self.poi_kinds)+    }+}++/// The toggle snapshot a mesh was built at, plus what its source could have emitted.+///+/// Stamp and summary travel together on every [`crate::tile::geometry::TileMesh`] so the+/// render thread can answer freshness without the source: [`stale_under`](Self::stale_under)+/// is the kinds-aware re-tessellation predicate. The global `generation` counter is kept+/// unchanged (it is the fast path and the tested contract); this is the second opinion+/// consulted when the generation has moved on.+#[derive(Clone, Debug)]+pub struct ToggleStamp {+    /// The toggles the mesh was built with.+    pub toggles: LayerToggles,+    /// The kind filter the mesh was built with.+    pub kinds: KindFilter,+    /// What the source could have emitted.+    pub gated: GatedSummary,+}++impl ToggleStamp {+    /// Would this mesh's content differ under `toggles` + `kinds`?+    ///+    /// `false` means rebuilding is provably useless: every gate that admits a feature of+    /// this tile agrees, so the rebuild would emit bit-identical geometry. `true` means+    /// rebuild (it is conservative — a changed gate with no geometric effect still+    /// answers true when the summary cannot prove otherwise).+    ///+    /// The cases, in order:+    /// * transit/traffic flip with source content behind the gate: the layer appears or+    ///   vanishes, so rebuild;+    /// * POI flip: turning off rebuilds only when something is shown (admitted under the+    ///   built filter), turning on rebuilds only when the source holds POI features;+    /// * kind-filter change with POI drawn: rebuilds only when the admitted set changed,+    ///   so narrowing Food→Coffee skips every tile with no food POIs, and widening the+    ///   chips skips every tile whose POIs were already all admitted.+    ///+    /// A filter change with POI off is always fresh: POI layers are gated regardless of+    /// the filter, so the meshes cannot differ.+    pub fn stale_under(&self, toggles: &LayerToggles, kinds: &KindFilter) -> bool {+        let built = &self.toggles;+        if built.transit != toggles.transit && self.gated.has_transit {+            return true;+        }+        if built.traffic != toggles.traffic && self.gated.has_traffic {+            return true;+        }+        if built.poi != toggles.poi {+            if built.poi {+                // Was on: turning off removes what is shown.+                if !self.gated.admitted(&self.kinds).is_empty() {+                    return true;+                }+            } else if !self.gated.poi_kinds.is_empty() {+                // Was off: turning on adds whatever the source holds.+                return true;+            }+        }+        if built.poi && self.kinds != *kinds {+            if self.gated.admitted(&self.kinds) != self.gated.admitted(kinds) {+                return true;+            }+        }+        false+    } }  /// The toggles, the POI kind filter and a generation counter, read as one snapshot and shared@@ -123,3 +241,189 @@ impl SharedToggles {         true     } }++#[cfg(test)]+mod stamp_tests {+    use super::*;+    use crate::style::kind_id;++    fn kinds(names: &[&str]) -> KindFilter {+        KindFilter::new(names.iter().filter_map(|n| kind_id(n)).collect())+    }++    fn stamp(+        poi: bool,+        transit: bool,+        traffic: bool,+        filter: KindFilter,+        poi_kinds: Vec<u16>,+        has_transit: bool,+        has_traffic: bool,+    ) -> ToggleStamp {+        ToggleStamp {+            toggles: LayerToggles {+                poi,+                transit,+                traffic,+            },+            kinds: filter,+            gated: GatedSummary {+                poi_kinds,+                has_transit,+                has_traffic,+            },+        }+    }++    fn cafe_bar() -> (u16, u16) {+        (+            kind_id("cafe").expect("cafe"),+            kind_id("bar").expect("bar"),+        )+    }++    /// The common case this exists for: tapping a chip must not rebuild a tile with no+    /// POIs, and must not rebuild one whose POIs are all outside both the old and the+    /// new filter.+    #[test]+    fn a_kind_change_skips_tiles_it_cannot_affect() {+        let (cafe, bar) = cafe_bar();+        let poi_on = LayerToggles {+            poi: true,+            transit: false,+            traffic: false,+        };+        // No POI features at all: any chip change is fresh.+        let bare = stamp(true, false, false, KindFilter::all(), vec![], false, false);+        assert!(!bare.stale_under(&poi_on, &kinds(&["cafe"])));+        // POIs, but none admitted before or after: still fresh.+        let other = stamp(+            true,+            false,+            false,+            kinds(&["cafe"]),+            vec![bar],+            false,+            false,+        );+        assert!(!other.stale_under(&poi_on, &kinds(&["restaurant"])));+        // An admitted kind leaves the set: stale.+        let food = stamp(+            true,+            false,+            false,+            KindFilter::all(),+            vec![cafe, bar],+            false,+            false,+        );+        assert!(food.stale_under(&poi_on, &kinds(&["cafe"])));+        // Widening over an already-fully-admitted tile: fresh.+        let all_food = stamp(+            true,+            false,+            false,+            kinds(&["cafe", "bar"]),+            vec![cafe],+            false,+            false,+        );+        assert!(!all_food.stale_under(&poi_on, &KindFilter::all()));+    }++    /// With POI off the filter is meaningless: meshes cannot differ, whatever the chips say.+    #[test]+    fn a_kind_change_with_poi_off_is_always_fresh() {+        let (cafe, _) = cafe_bar();+        let off = LayerToggles {+            poi: false,+            transit: false,+            traffic: false,+        };+        let stamp = stamp(false, false, false, KindFilter::all(), vec![cafe], false, false);+        assert!(!stamp.stale_under(&off, &kinds(&["cafe"])));+    }++    /// Turning POI off rebuilds only tiles that actually show POIs; turning it on+    /// rebuilds only tiles whose source holds POI features.+    #[test]+    fn a_poi_flip_rebuilds_only_tiles_with_poi_content() {+        let (cafe, _) = cafe_bar();+        let on = LayerToggles {+            poi: true,+            transit: false,+            traffic: false,+        };+        let off = LayerToggles {+            poi: false,+            transit: false,+            traffic: false,+        };+        // Built with POI on, showing a cafe: turning off removes it.+        let showing = stamp(true, false, false, KindFilter::all(), vec![cafe], false, false);+        assert!(showing.stale_under(&off, &KindFilter::all()));+        // Built with POI on, but the filter admits nothing: turning off removes nothing.+        let showing_nothing = stamp(+            true,+            false,+            false,+            kinds(&["bar"]),+            vec![cafe],+            false,+            false,+        );+        assert!(!showing_nothing.stale_under(&off, &kinds(&["bar"])));+        // Built with POI off, source holds a cafe: turning on adds it.+        let holding = stamp(false, false, false, KindFilter::all(), vec![cafe], false, false);+        assert!(holding.stale_under(&on, &KindFilter::all()));+        // Built with POI off, source holds none: turning on adds nothing.+        let bare = stamp(false, false, false, KindFilter::all(), vec![], false, false);+        assert!(!bare.stale_under(&on, &KindFilter::all()));+    }++    /// Transit/traffic flips rebuild only tiles whose source carries the layer.+    #[test]+    fn a_transit_or_traffic_flip_skips_tiles_without_the_layer() {+        let base = LayerToggles {+            poi: false,+            transit: false,+            traffic: false,+        };+        let transit_on = LayerToggles {+            transit: true,+            ..base+        };+        let traffic_on = LayerToggles {+            traffic: true,+            ..base+        };+        let bare = stamp(false, false, false, KindFilter::all(), vec![], false, false);+        assert!(!bare.stale_under(&transit_on, &KindFilter::all()));+        assert!(!bare.stale_under(&traffic_on, &KindFilter::all()));+        let transit_tile = stamp(false, false, false, KindFilter::all(), vec![], true, false);+        assert!(transit_tile.stale_under(&transit_on, &KindFilter::all()));+        assert!(!transit_tile.stale_under(&traffic_on, &KindFilter::all()));+        let traffic_tile = stamp(false, false, false, KindFilter::all(), vec![], false, true);+        assert!(traffic_tile.stale_under(&traffic_on, &KindFilter::all()));+        assert!(!traffic_tile.stale_under(&transit_on, &KindFilter::all()));+    }++    /// Identical snapshots are never stale, and `admitted` honours the empty-means-all rule.+    #[test]+    fn an_unchanged_snapshot_is_fresh_and_admitted_matches_admits() {+        let (cafe, bar) = cafe_bar();+        let toggles = LayerToggles {+            poi: true,+            transit: true,+            traffic: true,+        };+        let filter = kinds(&["cafe"]);+        let stamp = stamp(true, true, true, filter.clone(), vec![cafe, bar], true, true);+        assert!(!stamp.stale_under(&toggles, &filter));+        assert_eq!(filter.admitted(&[cafe, bar]), vec![cafe]);+        assert_eq!(+            KindFilter::all().admitted(&[bar, cafe]),+            vec![cafe.min(bar), cafe.max(bar)]+        );+    }+}
library/map/src/main/rust/src/style/mod.rs
diff --git a/library/map/src/main/rust/src/style/mod.rs b/library/map/src/main/rust/src/style/mod.rsindex b21139a481..1aa8db5051 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -61,7 +61,7 @@ mod tests; #[cfg(test)] mod tests_part2; -pub use self::filter::{KindFilter, SharedToggles};+pub use self::filter::{GatedSummary, KindFilter, SharedToggles, ToggleStamp}; pub use self::kinds::{Anchor, LayerKind, LayerToggles, Toggle, Variant}; #[cfg(test)] pub use self::layer::kind_id_for_test;
library/map/src/main/rust/src/tile/geometry/build.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/build.rs b/library/map/src/main/rust/src/tile/geometry/build.rsindex dd711b61e5..131e3ea19a 100644--- a/library/map/src/main/rust/src/tile/geometry/build.rs+++ b/library/map/src/main/rust/src/tile/geometry/build.rs@@ -6,8 +6,8 @@ use super::mesh::{BuildingMesh, CarriagewayMesh, LayerMesh, TileMesh}; use super::regions::region_meshes; use super::split::split_t; use super::terrain::{drape_vertices, terrain_mesh, tile_ground_width_m};-use super::traffic::traffic_meshes;-use crate::style::{KindFilter, Layer, LayerKind, LayerToggles};+use super::traffic::{traffic_meshes, traffic_present};+use crate::style::{GatedSummary, KindFilter, Layer, LayerKind, LayerToggles, Toggle, ToggleStamp}; use crate::tess::{fill, ribbon, stroke}; use crate::tile::select::ANCESTOR_DEPTH; use crate::tile::symbol;@@ -109,6 +109,44 @@ pub fn build_toggled(     let taper_run = taper::taper_run(ground_width_m);     let extent = tile.extent as u32; +    // The toggle-gated source summary for kinds-aware re-tessellation (see+    // [`GatedSummary`]): what this tile *could* emit behind each gate, independent of+    // whether the gate is open now. Computed from the source before the toggle gate+    // below, so a tile built with POI off still records the POI kinds it holds.+    //+    // Only toggle-gated layers are scanned: basemap content is never gated, so no+    // summary could excuse it, and the scan is `matches_feature` integer compares over+    // the gated layers' features — not shaping — so it costs a fraction of the labels+    // it saves. The zoom window below mirrors the layer loop's own (a layer outside+    // its window emits nothing either way), and the match is the same+    // `matches_feature` the loop uses, so the two cannot disagree about what counts.+    let mut gated = GatedSummary::default();+    for layer in layers.iter().filter(|l| l.toggle.is_some()) {+        if layer.min_zoom > deepest || layer.max_zoom < z {+            continue;+        }+        let Some(source) = tile.layer(layer.source_layer_id) else {+            continue;+        };+        for feature in &source.features {+            if !layer.matches_feature(feature) {+                continue;+            }+            match layer.toggle {+                Some(Toggle::Poi) => gated.poi_kinds.push(feature.kind),+                Some(Toggle::Transit) => gated.has_transit = true,+                // No style layer carries the traffic toggle today (traffic geometry comes+                // from `traffic_meshes`, probed below) — but if one ever does, its+                // matched features are traffic-gated content all the same.+                Some(Toggle::Traffic) => gated.has_traffic = true,+                None => {}+            }+        }+    }+    gated.poi_kinds.sort_unstable();+    gated.poi_kinds.dedup();+    gated.has_traffic |= traffic_present(tile, z);+     for (index, layer) in layers.iter().enumerate() {         // Before the zoom window and before the layer lookup: an optional layer that is         // off must cost nothing at all. This is the whole reason the gate is here rather@@ -429,6 +467,11 @@ pub fn build_toggled(         yellow_centre: tile.convention.is_some_and(|c| c.yellow_centre),         arrows: arrow_meshes(tile, z, left_hand),         generation,+        toggle_stamp: ToggleStamp {+            toggles,+            kinds: kinds.clone(),+            gated,+        },         heightmap: tile.heightmap.clone(),     } }
library/map/src/main/rust/src/tile/geometry/mesh.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/mesh.rs b/library/map/src/main/rust/src/tile/geometry/mesh.rsindex 2a9e4a9b5a..ef785ab446 100644--- a/library/map/src/main/rust/src/tile/geometry/mesh.rs+++ b/library/map/src/main/rust/src/tile/geometry/mesh.rs@@ -281,6 +281,14 @@ pub struct TileMesh {     /// behind; without the tag it could not tell a tile built with POI off from one whose     /// tile simply has no POI in it.     pub generation: u32,+    /// The toggle snapshot this was built at, plus what its source could have emitted.+    ///+    /// The kinds-aware second opinion behind the generation: when the generation has+    /// moved on, [`has_tile`](crate::vulkan::renderer::Renderer::has_tile) consults+    /// [`ToggleStamp::stale_under`](crate::style::ToggleStamp::stale_under) before+    /// re-requesting, so a chip change rebuilds only tiles whose POI set actually+    /// changed. See [`crate::style::GatedSummary`].+    pub toggle_stamp: crate::style::ToggleStamp,     /// The tile's heightmap, retained so per-frame label emission can sample ground height     /// under anchors (mirroring how `labels`/`arrows` are retained for per-frame draws).     /// `None` where the tile carries none; a few hundred bytes at DEM resolution.
library/map/src/main/rust/src/tile/geometry/mod.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/mod.rs b/library/map/src/main/rust/src/tile/geometry/mod.rsindex d68661c551..0f96ce8794 100644--- a/library/map/src/main/rust/src/tile/geometry/mod.rs+++ b/library/map/src/main/rust/src/tile/geometry/mod.rs@@ -38,6 +38,8 @@ mod tests_extra3; mod tests_extra7; #[cfg(test)] mod tests_extra4;+#[cfg(test)]+mod tests_extra8;  pub use build::{build, build_toggled}; pub use mesh::{
library/map/src/main/rust/src/tile/geometry/tests_extra8.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/tests_extra8.rs b/library/map/src/main/rust/src/tile/geometry/tests_extra8.rsnew file mode 100644index 0000000000..dfe318ac4e--- /dev/null+++ b/library/map/src/main/rust/src/tile/geometry/tests_extra8.rs@@ -0,0 +1,125 @@+//! P5 kinds-aware re-tessellation: the stamp a build records.+//!+//! Split from `tests.rs` (file-length limit): `build_toggled` stamps every mesh with+//! the toggle snapshot it saw plus what its source could have emitted+//! ([`ToggleStamp`](crate::style::ToggleStamp)), so `has_tile` can skip the rebuilds+//! a toggle change cannot affect. These pin the stamp and the verdicts that follow+//! from it; the predicate's own matrix lives in `style::filter`'s `stamp_tests`.+use super::build::build_toggled;+use crate::style;+use crate::style::{KindFilter, LayerToggles};+use tilecodec::mamaps::body::{+    Body, Feature, Layer as BodyLayer, Part, GEOM_LINE, GEOM_POINT, NAME_NONE, WINDING_OUTER,+};+use tilecodec::mamaps::dict;++/// The tile holds two POI points (cafe, bar) and one rail line. Built with POI on, the+/// stamp carries both kinds; narrowing the chips to cafe then changes the admitted set+/// (stale), while re-selecting both in any order does not (fresh). The rail line marks+/// `has_transit` even though transit is off — admissibility is toggle-independent.+#[test]+fn build_toggled_stamps_the_snapshot_and_gated_summary() {+    let cafe = crate::style::kind_id_for_test("cafe");+    let bar = crate::style::kind_id_for_test("bar");+    let rail = crate::style::kind_id_for_test("rail");++    let mut body = Body::new(4096);+    body.names.push("Cafe Epo".to_string());+    let mut poi = BodyLayer::new(dict::LAYER_POI);+    for (kind, x) in [(cafe, 1000i16), (bar, 3000)] {+        poi.features.push(Feature {+            kind,+            kind_detail: dict::NONE,+            geom_type: GEOM_POINT,+            flags: 0,+            name_idx: 0,+            parts_offset: poi.parts.len() as u32,+            part_count: 1,+            transit_color: 0,+            transit_ordinal: 0,+            transit_lanes: 0,+            transit_taper: 0,+            lane_count: 0,+        });+        poi.parts.push(Part {+            coord_start: poi.coords.len() as u32,+            point_count: 1,+            winding: WINDING_OUTER,+        });+        poi.coords.push((x, 2000));+    }+    body.layers.push(poi);+    let mut transit = BodyLayer::new(dict::LAYER_TRANSIT);+    transit.features.push(Feature {+        kind: rail,+        kind_detail: dict::NONE,+        geom_type: GEOM_LINE,+        flags: 0,+        name_idx: NAME_NONE,+        parts_offset: 0,+        part_count: 1,+        transit_color: 0,+        transit_ordinal: 0,+        transit_lanes: 0,+        transit_taper: 0,+        lane_count: 0,+    });+    transit.parts.push(Part {+        coord_start: 0,+        point_count: 2,+        winding: WINDING_OUTER,+    });+    transit.coords.extend_from_slice(&[(100, 100), (3900, 3900)]);+    body.layers.push(transit);++    let layers = style::layers();+    let toggles = LayerToggles {+        poi: true,+        transit: false,+        traffic: false,+    };+    let mesh = build_toggled(&body, layers, 14, 0, 0, false, toggles, &KindFilter::all(), 9);+    assert_eq!(mesh.generation, 9, "the generation fast path is unchanged");+    assert_eq!(mesh.toggle_stamp.toggles, toggles);+    assert!(mesh.toggle_stamp.kinds.is_empty());+    let mut summary = mesh.toggle_stamp.gated.poi_kinds.clone();+    summary.sort_unstable();+    assert_eq!(summary, vec![bar.min(cafe), bar.max(cafe)]);+    assert!(+        mesh.toggle_stamp.gated.has_transit,+        "admissibility ignores the toggle gate"+    );+    assert!(!mesh.toggle_stamp.gated.has_traffic);++    // Narrowing the chips drops bar: stale. Re-selecting both (any order): fresh.+    assert!(mesh+        .toggle_stamp+        .stale_under(&toggles, &KindFilter::new(vec![cafe])));+    assert!(!mesh+        .toggle_stamp+        .stale_under(&toggles, &KindFilter::new(vec![bar, cafe])));+    // Turning POI off removes two shown labels: stale.+    let off = LayerToggles {+        poi: false,+        ..toggles+    };+    assert!(mesh.toggle_stamp.stale_under(&off, &KindFilter::all()));+    // Transit is off and the tile holds rail: turning it on adds a line.+    let transit_on = LayerToggles {+        transit: true,+        ..toggles+    };+    assert!(mesh+        .toggle_stamp+        .stale_under(&transit_on, &KindFilter::all()));++    // Built with POI off: the same summary (the scan runs before the gate), no labels,+    // and a chip change is fresh — POI layers are gated regardless of the filter.+    let dark = build_toggled(&body, layers, 14, 0, 0, false, off, &KindFilter::all(), 10);+    assert_eq!(dark.toggle_stamp.gated.poi_kinds.len(), 2);+    assert!(!dark+        .toggle_stamp+        .stale_under(&off, &KindFilter::new(vec![cafe])));+    // But turning POI on adds the two points: stale.+    assert!(dark.toggle_stamp.stale_under(&toggles, &KindFilter::all()));+}
library/map/src/main/rust/src/tile/geometry/traffic.rs
diff --git a/library/map/src/main/rust/src/tile/geometry/traffic.rs b/library/map/src/main/rust/src/tile/geometry/traffic.rsindex 038fa9a54c..da56249add 100644--- a/library/map/src/main/rust/src/tile/geometry/traffic.rs+++ b/library/map/src/main/rust/src/tile/geometry/traffic.rs@@ -8,6 +8,38 @@ use crate::tile::select::ANCESTOR_DEPTH; use tilecodec::mamaps::body::{Body, GEOM_LINE}; use tilecodec::mamaps::dict::LAYER_TRAFFIC; +/// Would this tile emit live-traffic segments if the traffic toggle were on?+///+/// The toggle-independent half of [`traffic_meshes`]: the zoom gate and the source scan,+/// without the toggle gate — so a tile built with traffic off can still record that it+/// *could* carry traffic. That is the [`crate::style::GatedSummary::has_traffic`] input+/// to kinds-aware re-tessellation: flipping traffic rebuilds only tiles that answer true+/// here. Mirrors the gate above (zoom window, line geometry, a colourable id); the two+/// must agree, or a tile would claim no traffic and then emit some.+pub(crate) fn traffic_present(tile: &Body, z: u8) -> bool {+    // The same stand-in window as the emitter: a tile builds the overlay whenever any+    // level it stands in for reaches the traffic floor.+    if z.saturating_add(ANCESTOR_DEPTH) < TRAFFIC_MIN_ZOOM {+        return false;+    }+    let Some(source) = tile.layer(LAYER_TRAFFIC) else {+        return false;+    };+    for (feature_index, feature) in source.features.iter().enumerate() {+        if feature.geom_type != GEOM_LINE {+            continue;+        }+        let Some(id) = tile.feature_id(LAYER_TRAFFIC, feature_index) else {+            continue;+        };+        if id == tilecodec::mamaps::body::ID_NONE {+            continue;+        }+        return true;+    }+    false+}+ /// Tessellate this tile's live-traffic component segments, one mesh per feature. /// /// Gated on the traffic toggle so leaving it off costs nothing — the same tessellation-time
library/map/src/main/rust/src/tile/select/mod.rs
diff --git a/library/map/src/main/rust/src/tile/select/mod.rs b/library/map/src/main/rust/src/tile/select/mod.rsindex 5bebc3ea68..3916fb66ba 100644--- a/library/map/src/main/rust/src/tile/select/mod.rs+++ b/library/map/src/main/rust/src/tile/select/mod.rs@@ -26,10 +26,12 @@ pub mod tile_id; mod tests; #[cfg(test)] mod tests_part2;+#[cfg(test)]+mod tests_part3;  pub use coverage::{bound, visible}; pub use fade::{     fade_in_progress, has_resident_ancestor, lod_fade_alpha, tile_lod_alpha, LOD_FADE_SECONDS, };-pub use resident::{resident_set, stands_in_for_visible, zoom_out_burst, ANCESTOR_DEPTH, DESCENDANT_DEPTH};+pub use resident::{resident_set, stands_in_for_visible, zoom_out_burst, ANCESTOR_DEPTH, DESCENDANT_DEPTH, RESIDENT_TILE_CAP}; pub use tile_id::TileId;
library/map/src/main/rust/src/tile/select/resident.rs
diff --git a/library/map/src/main/rust/src/tile/select/resident.rs b/library/map/src/main/rust/src/tile/select/resident.rsindex e307299254..cb7d3fe491 100644--- a/library/map/src/main/rust/src/tile/select/resident.rs+++ b/library/map/src/main/rust/src/tile/select/resident.rs@@ -16,6 +16,36 @@ pub fn zoom_out_burst(last_zoom: Option<f64>, zoom: f64) -> bool {     last_zoom.is_none_or(|last| zoom < last) } +/// The most tiles allowed resident on the GPU at once.+///+/// Eviction is the only thing bounding tile memory — there is no separate budget — so this is a+/// real limit rather than a safety net. It matters more now that descendants are kept: an+/// ancestor set is linear in depth, but a descendant set is not, and without a cap every deep+/// tile visited would stay resident for as long as the camera sat above it.+///+/// Sized from what the renderer reports rather than from theory. A dense z14 screenful logged+/// ~2.0 M triangles across 7 tiles, so a tile in a city centre costs single-digit megabytes of+/// vertex and index buffers; 64 leaves room for a ~12-tile viewport, its four ancestor levels and+/// a useful spread of descendants, while keeping the worst case in the hundreds of megabytes+/// rather than the gigabytes an uncapped depth-2 fan-out could reach. Going over drops+/// descendants first, so the cost of being wrong here is a briefly coarser zoom-out, not a blank+/// screen.+///+/// P5.4 verdict — held at 64, measured first. The structural pin is+/// `resident_demand_fits_the_cap_with_headroom`: worst unfogged keep set 37 (tablet+/// z12, 45° bearing), leaving 27 slots for descendant stand-ins under this cap. Tilted+/// frames enumerate more (162 at 65° pitch) but those far tiles are fogged to the land+/// colour past ~6 viewport heights (`FOG_FAR_VIEWPORTS`) — haze, not detail — so the+/// follow-up for tilt churn is a pitch-aware far-fetch cap in `coverage`, not a bigger+/// resident set. The device counters that would justify moving this number are the+/// per-frame report's `stale-dropped`, `fcan` and resident-tile counts: churn there+/// with a small keep set means raise; a large resident set with idle-time memory+/// pressure means lower.+///+/// Lives here (not in `bridge::handle`) so the host-testable selection suite can pin the+/// structural demand against it.+pub const RESIDENT_TILE_CAP: usize = 64;+ /// How many levels of descendant to *keep* when they are already resident. /// /// The mirror of [`ANCESTOR_DEPTH`], and the reason zooming out no longer blanks the map. An
library/map/src/main/rust/src/tile/select/tests_part3.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests_part3.rs b/library/map/src/main/rust/src/tile/select/tests_part3.rsnew file mode 100644index 0000000000..c2e62efcbb--- /dev/null+++ b/library/map/src/main/rust/src/tile/select/tests_part3.rs@@ -0,0 +1,154 @@+//! P5.4 stale-tile cap tuning: measure the structural tile demand first.+//!+//! Split from `tests.rs` (file-length limit). The resident cap ([`RESIDENT_TILE_CAP`])+//! bounds the whole resident set, but what it must never do is evict a *visible*+//! tile: `retain` drops rank-3 (unrelated) tiles first, then the lowest-ranked+//! stand-ins past the limit, so the keep set that matters is the visible tiles plus+//! their ancestors (ranks 0–1). What the cap is really for is the stale stand-ins —+//! resident descendants from a deeper zoom (rank 2) sheltered for zoom-out smoothness+//! (P2) — so this pins the worst keep set over representative viewports, zooms,+//! tilts, rotations and the globe, with headroom left for those stand-ins.+//!+//! Viewports: a dense-city phone (411×891dp, the z14 case from the cap's sizing note),+//! a landscape tablet (1280×800dp), zooms 0–16 (past the archive top, i.e. overzoom),+//! pitch to the host's 65° max, bearing 45°, and the globe below its threshold.+//! Density is 1 throughout: coverage works in Dp, so density changes pixels, not+//! tile counts.+//!+//! The globe half needs care: `globe_visible` enumerates the whole hemisphere cap at+//! the *archive* zooms — thousands of tiles at z7 — but the fetch loop never asks for+//! them, because `has_tile`/absent/retry/in-flight gate every send and the workers+//! drain a bounded upload budget per frame. The globe keep set is aspirational in a+//! way the flat one is not, so it is measured separately (and pinned loosely): the+//! tuning bound below covers the flat path, where every wanted tile is actually+//! fetched and resident.+use super::*;+use crate::camera::Camera;++fn camera(lon: f64, lat: f64, zoom: f64, w: f32, h: f32) -> Camera {+    Camera {+        center_lon: lon,+        center_lat: lat,+        zoom,+        width_dp: w,+        height_dp: h,+        density: 1.0,+        bearing_deg: 0.0,+        pitch_deg: 0.0,+        time_seconds: 0.0,+        globe: false,+        moon: false,+    }+}++#[test]+fn resident_demand_fits_the_cap_with_headroom() {+    let mut worst = (0usize, String::new());+    let mut worst_visible = (0usize, String::new());+    let mut worst_globe = (0usize, String::new());+    // The unfogged worst: pitch 0 only. Fogged far tiles (see `FOG_FAR_VIEWPORTS`)+    // contribute haze, not detail, so they are measured above but budgeted+    // separately — the cap shelters the unfogged set plus descendant stand-ins.+    let mut worst_flat = (0usize, String::new());+    for &(w, h, name) in &[(411.0f32, 891.0, "phone"), (1280.0, 800.0, "tablet")] {+        for zoom in 0..=16u8 {+            // Pitch to the host's 65° max (`MAX_PITCH` in `CameraState.kt`, clamped+            // again at the JNI boundary): the far trapezoid is what drives the worst+            // case, so the measurement must include the steepest supported tilt.+            // Tracked separately: fogged far tiles vs the unfogged set the cap+            // shelters (see the bound below).+            for pitch in [0.0, 45.0, 65.0] {+                for bearing in [0.0, 45.0] {+                    // Flat and globe separately: the globe path engages below its own+                    // threshold, and the flat path must be measured past it too (a+                    // host with the globe off zooms through the same levels flat).+                    for globe in [false, true] {+                        let c = Camera {+                            pitch_deg: pitch,+                            bearing_deg: bearing,+                            globe,+                            ..camera(-122.4194, 37.7749, zoom as f64, w, h)+                        };+                        // Skip the incoherent corner: globe flag on but past the+                        // threshold draws flat, so it would double-count the flat+                        // case above rather than measure the globe path.+                        if globe && !crate::camera::globe_active(&c) {+                            continue;+                        }+                        let v = visible(&c, 0, 15).len();+                        let r = resident_set(&c, 0, 15).len();+                        let ctx = format!("{name} z{zoom} pitch{pitch} bearing{bearing}");+                        if globe {+                            if r > worst_globe.0 {+                                worst_globe = (r, ctx);+                            }+                            continue;+                        }+                        if v > worst_visible.0 {+                            worst_visible = (v, ctx.clone());+                        }+                        if r > worst.0 {+                            worst = (r, ctx.clone());+                        }+                        if pitch == 0.0 && r > worst_flat.0 {+                            worst_flat = (r, ctx);+                        }+                    }+                }+            }+        }+    }+    // The measurement, printed for the tuning note below. Run with `--nocapture` to read it.+    println!("worst visible: {} ({})", worst_visible.0, worst_visible.1);+    println!("worst flat keep set: {} ({})", worst.0, worst.1);+    println!(+        "worst unfogged keep set: {} ({})",+        worst_flat.0, worst_flat.1+    );+    println!("worst globe keep set: {} ({})", worst_globe.0, worst_globe.1);+    // Flat-path bound. A keep set at the cap would evict visible tiles (rank is no+    // defence past the limit — see `retain`), so this must hold with headroom for+    // descendant stand-ins behind it.+    //+    // Measured worst: 162 (tablet z8, 65° pitch, 45° bearing) — the far trapezoid at+    // full tilt, where tiles past ~6 viewport heights are fogged to the land colour+    // (`FOG_FAR_VIEWPORTS`) and contribute haze rather than detail. That is the case+    // for tightening the fetch (a pitch-aware far cap in `coverage`, matching the+    // existing `FAR_REACH_VIEWPORTS` shape), not for raising the residency cap:+    // raising it keeps more fogged tiles resident at single-digit-MB each, while the+    // unfogged path — every pitch-0 viewport, the case the P2 metrics actually+    // cover — peaks far lower (see the pitch-0 print above).+    //+    // So the bound pins today's demand (200, the measured 162 with room for viewport+    // growth), and the cap stays 64: the keep set that must never be evicted is the+    // unfogged one, and 64 shelters it plus a full screenful of descendant+    // stand-ins. If device logs (`stale-dropped`, resident counts) ever show tilt+    // frames churning fetches, the fix is the far-fetch cap, recorded here rather+    // than guessed at now.+    assert!(+        worst.0 <= 200,+        "keep set {} ({}) exceeds the measured budget — see the tuning note",+        worst.0,+        worst.1,+    );+    // The cap shelters the unfogged set: every pitch-0 viewport plus ancestors must+    // fit with room for a full screenful of descendant stand-ins (rank 2) behind it.+    // A keep set at the cap would evict visible tiles (rank is no defence past the+    // limit — see `retain`), so this is the load-bearing half of the pin.+    assert!(+        worst_flat.0 + 24 <= RESIDENT_TILE_CAP,+        "unfogged keep set {} ({}) leaves no room for descendant stand-ins under the {} cap",+        worst_flat.0,+        worst_flat.1,+        RESIDENT_TILE_CAP,+    );+    // The globe enumeration is aspirational (see above): pinned two orders of+    // magnitude above the flat bound so a coverage change that doubles it still+    // passes, while a runaway (whole-pyramid enumeration) fails loudly.+    assert!(+        worst_globe.0 <= 200_000,+        "globe keep set {} ({}) looks like whole-pyramid enumeration",+        worst_globe.0,+        worst_globe.1,+    );+}
library/map/src/main/rust/src/vulkan/context.rs
diff --git a/library/map/src/main/rust/src/vulkan/context.rs b/library/map/src/main/rust/src/vulkan/context.rsindex 0d128ffc8a..b44dc25d54 100644--- a/library/map/src/main/rust/src/vulkan/context.rs+++ b/library/map/src/main/rust/src/vulkan/context.rs@@ -131,6 +131,31 @@ impl Context {         };         let queue = device.get_device_queue(queue_family_index, 0); +        // P5.3 probe: name what the driver offers so the render-path decisions above stay+        // measured, not assumed. Read-only queries + one log line, zero behaviour change:+        // whether `VK_KHR_dynamic_rendering` exists answers "where drivers allow" for the+        // dynamic-rendering half, and the API version says when it goes core (1.3).+        {+            let props = instance.get_physical_device_properties(physical_device);+            let v = props.api_version;+            let dynamic = instance+                .enumerate_device_extension_properties(physical_device)+                .map(|exts| {+                    exts.iter().any(|e| {+                        let name = unsafe { CStr::from_ptr(e.extension_name.as_ptr()) };+                        name.to_bytes() == b"VK_KHR_dynamic_rendering"+                    })+                })+                .unwrap_or(false);+            crate::bridge::log::log_info(&format!(+                "vulkan driver: api {}.{}.{} dynamic_rendering={}",+                vk::api_version_major(v),+                vk::api_version_minor(v),+                vk::api_version_patch(v),+                dynamic,+            ));+        }+         Ok(Context {             entry,             instance,
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 25896d66a0..04c893c082 100644--- a/library/map/src/main/rust/src/vulkan/renderer/frame.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/frame.rs@@ -1,7 +1,7 @@ use super::{Overlay, Renderer, UserPuck, FRAMES_IN_FLIGHT}; use crate::camera::Camera; use crate::marker::Marker;-use crate::style::{Layer, Palette};+use crate::style::{KindFilter, Layer, LayerToggles, Palette}; use crate::tile::select; use crate::timing::{nanos_since, Step}; use ash::vk;@@ -166,10 +166,23 @@ impl Renderer {     /// requests one it has never seen. That is the whole re-tessellation mechanism: the     /// old mesh keeps drawing until the new one lands, so a toggle change never blanks     /// the map, and nothing is evicted or refetched.-    pub fn has_tile(&self, key: u64, generation: u32) -> bool {-        self.tiles-            .get(&key)-            .is_some_and(|tile| tile.generation == generation)+    ///+    /// Kinds-aware (P5): when the generation has moved on, the tile gets a second+    /// opinion before it is re-requested. [`ToggleStamp::stale_under`](crate::style::ToggleStamp::stale_under)+    /// proves a toggle change affects nothing here — a chip change on a tile with no+    /// POIs, a transit flip with no transit features — and the tile stays fresh without+    /// a rebuild. The generation fast path is unchanged: an exact match never consults+    /// the stamp.+    pub fn has_tile(+        &self,+        key: u64,+        generation: u32,+        toggles: &LayerToggles,+        kinds: &KindFilter,+    ) -> bool {+        self.tiles.get(&key).is_some_and(|tile| {+            tile.generation == generation || !tile.toggle_stamp.stale_under(toggles, kinds)+        })     }      /// Whether another frame would do something this one did not — the renderer's half of
library/map/src/main/rust/src/vulkan/renderer/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod.rs b/library/map/src/main/rust/src/vulkan/renderer/mod.rsindex 0fd764d1aa..c44430914a 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -146,8 +146,10 @@ pub(crate) struct ResidentTile {     /// ancestor instead of popping.     uploaded_at: f32,     /// The toggle generation this was tessellated at — see-    /// [`crate::style::SharedToggles`].+    /// [`crate::style::SharedToggles`]. The kinds-aware second opinion behind it+    /// ([`ToggleStamp`](crate::style::ToggleStamp)) rides alongside.     generation: u32,+    toggle_stamp: crate::style::ToggleStamp, }  /// One live-traffic component segment, on the GPU.@@ -216,11 +218,8 @@ struct RegionBuffers {     level: u16, } -/// A transient per-frame buffer pair (one symbol draw's vertices + indices),-/// held for [`FRAMES_IN_FLIGHT`] frames so no in-flight command buffer still-/// references it at destroy time. Same grace rule as [`Renderer::retiring`],-/// but buffers are not tiles — so they retire in their own queue, with no-/// per-frame `device_wait_idle` stall (that wedged the guest under load).+/// A transient per-frame buffer pair, held for [`FRAMES_IN_FLIGHT`] frames (same grace+/// rule as [`Renderer::retiring`], but its own queue — no `device_wait_idle` stall). struct TransientBuffers {     vbuf: Buffer,     ibuf: Buffer,
library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs b/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rsindex d1b5998e6c..dd8952334c 100644--- a/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/upload_tail.rs@@ -292,6 +292,7 @@ pub(super) fn assemble_tile(         // (nothing is under it to fade over anyway).         uploaded_at,         generation: mesh.generation,+        toggle_stamp: mesh.toggle_stamp.clone(),     } } 
library/map/src/main/rust/src/vulkan/swapchain/chain.rs
diff --git a/library/map/src/main/rust/src/vulkan/swapchain/chain.rs b/library/map/src/main/rust/src/vulkan/swapchain/chain.rsindex 83d9fdc1e8..d85cadc807 100644--- a/library/map/src/main/rust/src/vulkan/swapchain/chain.rs+++ b/library/map/src/main/rust/src/vulkan/swapchain/chain.rs@@ -1,3 +1,4 @@+use crate::bridge::log::log_info; use crate::vulkan::context::Context; use ash::vk; @@ -16,6 +17,8 @@ pub struct Swapchain {     pub extent: vk::Extent2D,     /// Samples per pixel the pipelines must be built for.     pub samples: vk::SampleCountFlags,+    /// The present mode negotiated with the driver ([`choose_present_mode`]).+    pub present_mode: vk::PresentModeKHR,     /// The multisampled colour target, absent when `samples` is 1.     msaa: Option<MsaaTarget>,     /// The combined depth-stencil target: depth for the 3D layers, stencil for the region mask,@@ -63,12 +66,19 @@ impl Swapchain {             }         };         // FIFO is vsync, and the map is driven by Choreographer: anything else would only-        // queue frames nobody sees, at the cost of power.-        let present_mode = if present_modes.contains(&vk::PresentModeKHR::FIFO) {-            vk::PresentModeKHR::FIFO-        } else {-            present_modes[0]-        };+        // queue frames nobody sees, at the cost of power. MAILBOX is the exception: like+        // FIFO it is tear-free, but a newer frame replaces the queued one instead of+        // waiting behind it — up to a frame less latency through a 60fps pan/zoom for no+        // extra power while idle (the on-demand loop queues nothing when nothing moves).+        // IMMEDIATE is never picked: it tears, and a torn map frame is worse than a+        // vsync-late one. FIFO is the mandated fallback (the only mode the spec requires)+        // and the old behaviour wherever MAILBOX is absent.+        let present_mode = choose_present_mode(&present_modes);+        log_info(&format!(+            "swapchain present mode: {} (offered {} modes)",+            present_mode_name(present_mode),+            present_modes.len(),+        ));         let max = if capabilities.max_image_count == 0 {             u32::MAX         } else {@@ -255,6 +265,7 @@ impl Swapchain {             format: chosen.format,             extent,             samples,+            present_mode,             msaa,             stencil: stencil_target,         })@@ -284,3 +295,76 @@ impl Swapchain {         self.loader.destroy_swapchain(self.swapchain, None);     } }++/// Pick the swapchain present mode: MAILBOX where offered, FIFO otherwise.+///+/// Pure so it is host-testable: no device, just the driver's offered list. MAILBOX is+/// tear-free like FIFO but replaces the queued frame instead of waiting behind it, so+/// a 60fps gesture presents newer poses; FIFO is the spec-mandated fallback and the+/// previous behaviour. IMMEDIATE is never chosen even when it is the only other+/// option — tearing on a map is worse than vsync latency — so a driver offering only+/// IMMEDIATE keeps the old `present_modes[0]` answer.+fn choose_present_mode(present_modes: &[vk::PresentModeKHR]) -> vk::PresentModeKHR {+    if present_modes.contains(&vk::PresentModeKHR::MAILBOX) {+        vk::PresentModeKHR::MAILBOX+    } else if present_modes.contains(&vk::PresentModeKHR::FIFO) {+        vk::PresentModeKHR::FIFO+    } else {+        // Unreachable on a conformant driver (FIFO is mandatory), but the old code+        // indexed [0] here and a panic on a non-conformant driver is worse than a+        // torn frame. `new` already errors on an empty format list; an empty mode+        // list fails below at creation with the driver's own error.+        present_modes.first().copied().unwrap_or(vk::PresentModeKHR::FIFO)+    }+}++/// The creation-time log line names the negotiated mode, so a device run can confirm+/// which path the driver took without a second build. By discriminant rather than+/// `Debug`: `ash`'s bitflag-style enums do not implement it.+fn present_mode_name(mode: vk::PresentModeKHR) -> &'static str {+    match mode {+        vk::PresentModeKHR::IMMEDIATE => "IMMEDIATE",+        vk::PresentModeKHR::MAILBOX => "MAILBOX",+        vk::PresentModeKHR::FIFO => "FIFO",+        vk::PresentModeKHR::FIFO_RELAXED => "FIFO_RELAXED",+        _ => "UNKNOWN",+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    /// MAILBOX wins where offered (tear-free and fresher through gestures); FIFO is+    /// the mandated fallback and the old behaviour; IMMEDIATE is never picked even+    /// when it is the only other option.+    ///+    /// Android-gated like the rest of this module (`ash` is an Android-only+    /// dependency), so `cargo test` on the host never runs it — it compiles and runs+    /// under the Android test target instead. The creation-time logcat line naming+    /// the negotiated mode is the on-device proof in the meantime.+    #[test]+    fn mailbox_wins_over_fifo_and_immediate_is_never_picked() {+        use vk::PresentModeKHR::*;+        assert_eq!(+            choose_present_mode(&[FIFO, MAILBOX, IMMEDIATE]),+            MAILBOX,+            "tear-free with the freshest queued frame"+        );+        assert_eq!(+            choose_present_mode(&[FIFO, IMMEDIATE]),+            FIFO,+            "the old behaviour where MAILBOX is absent"+        );+        assert_eq!(+            choose_present_mode(&[IMMEDIATE]),+            IMMEDIATE,+            "a non-conformant driver keeps the old [0] answer, not a panic"+        );+        assert_eq!(+            choose_present_mode(&[]),+            FIFO,+            "empty degrades to the mandated mode for the creation error below"+        );+    }+}
library/map/src/main/rust/src/vulkan/swapchain/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/swapchain/mod.rs b/library/map/src/main/rust/src/vulkan/swapchain/mod.rsindex ef42d5ecce..e863a9a124 100644--- a/library/map/src/main/rust/src/vulkan/swapchain/mod.rs+++ b/library/map/src/main/rust/src/vulkan/swapchain/mod.rs@@ -29,6 +29,15 @@ //! memory, so the resolve is close to free and the image needs no real backing store. //! `store_op` is `DONT_CARE` for the same reason — only the resolve target is kept. //!+//! # Present mode: MAILBOX where offered, FIFO otherwise+//!+//! The swapchain used to pin FIFO. MAILBOX is tear-free like FIFO but lets a newer+//! frame replace the queued one, so a 60fps gesture presents poses up to a frame+//! fresher; the on-demand loop queues nothing while idle, so there is no power cost+//! when the map is still. IMMEDIATE is never picked (tearing), FIFO is the+//! spec-mandated fallback — see [`chain`](self::chain) for the selection and the+//! creation-time logcat line naming the negotiated mode.+//! //! # Two hard-won details carried over from `games/voxels` //! //! * **`B8G8R8A8_UNORM` in preference to any `SRGB` format.** `voxels/swapchain.rs:39`@@ -37,6 +46,21 @@ //! * **A classic `VkRenderPass`, not `KHR_dynamic_rendering`.** //!   `voxels/swapchain.rs:74` records the crash — "Unable to load cmd_begin_rendering" — //!   from assuming the extension is present.+//!+//! # P5.3 decision: still a render pass (dynamic rendering probed, not adopted)+//!+//! The context creation log names the driver's API version and whether+//! `VK_KHR_dynamic_rendering` exists on it — the "where drivers allow" half is+//! measured, not assumed. Adoption would need *two* record paths (every `record_*`+//! pass, the pipeline create-info, the rebuild path and the pick pass all name the+//! render pass), validated per device, for a win this renderer cannot collect: the+//! per-frame state that changes is push constants, which dynamic rendering does not+//! retain either. Secondary command buffers fail the same way — their win is threaded+//! recording, which the all-Vulkan-on-main rule forbids, and single-threaded they are+//! allocation + indirection over one primary record. So the probe stays a log line,+//! and the ordering contracts it would have had to preserve (mask/stencil groups+//! order-pinned, separate `*_globe` groups, ScratchRing ranges fenced per frame —+//! see `Renderer::render`'s reset-after-fence) stay exactly as they are.  mod chain; mod msaa;