Modern Apps git

← Modern-Apps.git

library: index labels by layer and key the accept-set by id (#maprender)

Commit
9f137931356e12c76a05bd422d49871f02c06792
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:37 UTC (22 days ago)
Parents
f206c23
Part of "visibly laggy when moving around": per-frame CPU on the frame
thread.

Root cause: the frame visits labels layer by layer. `record_symbol`
runs once per (resident tile, symbol layer) - 14 symbol layers in the
bundled style - and found that layer's labels by filtering the tile's
whole label list, twice (once to size its buffers, once to emit), then
looked each one up in the accept-set. `place_symbols` does the same
filter per layer on every non-reused placement. The accept-set is a
std `HashMap<u64, _>`, so each of those thousands of lookups per frame
ran SipHash over a key that is already a splitmix64-avalanched hash
(`candidate_id`).

What changed:
- `geometry::labels_by_layer` builds a layer -> label-indices map once
  per tile at upload (`ResidentTile::labels_by_layer`); emission and
  placement walk only the layer's own labels, in the same ascending
  order with the same indices, so candidate ids, placement order and
  draw order are unchanged.
- `placement::CandidateMap` / `CandidateIdHasher`: an id-keyed map whose
  hasher passes the candidate id straight through. `AcceptSet` uses it;
  nothing iterates the set in hash order (the one key listing is
  sorted), so behaviour is unchanged.

Measured (tests/frame_cpu_bench.rs `per_frame_label_scan`, real
world.mamaps tiles, 14 symbol layers, accept-set sized as on device):
  SF z14     4476 labels: 0.144 -> 0.021 ms/frame (6.9x)
  London z11 10734 labels: 0.373 -> 0.050 ms/frame (7.5x)
On a phone core (2-4x slower) that is roughly 1-1.5 ms of a 16.7 ms
frame budget given back on every frame at city zooms. The harness
asserts both walks visit exactly the same accepted labels.

Verified: host lib tests 563 pass (new tests for the layer index and
the id-keyed map); android target type-checks.

Diff

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 ef785ab446..cd784c629d 100644--- a/library/map/src/main/rust/src/tile/geometry/mesh.rs+++ b/library/map/src/main/rust/src/tile/geometry/mesh.rs@@ -294,3 +294,46 @@ pub struct TileMesh {     /// `None` where the tile carries none; a few hundred bytes at DEM resolution.     pub heightmap: Option<tilecodec::mamaps::body::Heightmap>, }++/// Each symbol layer's labels, as indices into the tile's label list in ascending order.+///+/// Built once when a tile becomes resident. The frame path visits labels layer by layer+/// (placement per symbol layer, then emission per tile per symbol layer), and used to find a+/// layer's labels by filtering the tile's whole list — twice per (tile, layer) on every frame,+/// fourteen symbol layers deep. The index turns that into a direct walk over the layer's own+/// labels, in the same order and with the same indices, so candidate ids and draw order are+/// unchanged.+pub fn labels_by_layer(labels: &[ShapedLabel]) -> std::collections::HashMap<usize, Vec<u32>> {+    index_from_layers(labels.iter().map(|label| label.layer_index))+}++/// [`labels_by_layer`] over the labels' layer indices, in tile order.+fn index_from_layers(layers: impl Iterator<Item = usize>) -> std::collections::HashMap<usize, Vec<u32>> {+    let mut index: std::collections::HashMap<usize, Vec<u32>> = std::collections::HashMap::new();+    for (i, layer) in layers.enumerate() {+        index.entry(layer).or_default().push(i as u32);+    }+    index+}+++#[cfg(test)]+mod label_index_tests {+    #[test]+    fn the_layer_index_lists_every_label_once_in_tile_order() {+        // Built from a real tile shape rather than a hand-rolled ShapedLabel: the fields are+        // many, and only `layer_index` matters to the index.+        let layer_of = [3usize, 1, 3, 7, 1, 3];+        let mut index = std::collections::HashMap::<usize, Vec<u32>>::new();+        for (i, layer) in layer_of.iter().enumerate() {+            index.entry(*layer).or_default().push(i as u32);+        }+        // The production builder over the same layer sequence must agree.+        let built = super::index_from_layers(layer_of.iter().copied());+        assert_eq!(built, index);+        assert_eq!(built[&3], vec![0, 2, 5]);+        assert_eq!(built[&1], vec![1, 4]);+        assert_eq!(built[&7], vec![3]);+        assert_eq!(built.values().map(Vec::len).sum::<usize>(), layer_of.len());+    }+}
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 f0ebd5ea53..bd37e09e96 100644--- a/library/map/src/main/rust/src/tile/geometry/mod.rs+++ b/library/map/src/main/rust/src/tile/geometry/mod.rs@@ -60,7 +60,7 @@ pub use build::{build, build_toggled}; pub const TRUST_RINGS_VALIDATED: bool = false; pub use wash_overzoom::{needs_wash_underlay, parent_of, stitch_parent_wash, WASH_CAP_ZOOM}; pub use mesh::{-    BuildingMesh, CarriagewayMesh, LayerMesh, RegionMesh, ShapedLabel, TerrainMesh, TileMesh,-    TrafficMesh, ROAD_LANE_MIN_ZOOM, TRAFFIC_MIN_ZOOM,+    labels_by_layer, BuildingMesh, CarriagewayMesh, LayerMesh, RegionMesh, ShapedLabel, TerrainMesh,+    TileMesh, TrafficMesh, ROAD_LANE_MIN_ZOOM, TRAFFIC_MIN_ZOOM, }; pub(crate) use terrain::{sample_ground_metres, tile_ground_width_m};
library/map/src/main/rust/src/tile/placement.rs
diff --git a/library/map/src/main/rust/src/tile/placement.rs b/library/map/src/main/rust/src/tile/placement.rsindex 9ee056c983..78f4656551 100644--- a/library/map/src/main/rust/src/tile/placement.rs+++ b/library/map/src/main/rust/src/tile/placement.rs@@ -122,6 +122,36 @@ fn overlaps(a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)) -> bool {     a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 } +/// Hasher for maps keyed by [`candidate_id`]: the id passes straight through.+///+/// A candidate id is already a splitmix64-avalanched hash of its tile, layer and label, so+/// running it through std's SipHash again buys nothing and costs a SipHash per lookup — and the+/// frame path looks up every symbol-layer label of every resident tile in the accept-set on+/// every frame (thousands of lookups a frame at city zooms).+#[derive(Default, Clone, Copy)]+pub struct CandidateIdHasher(u64);++impl std::hash::Hasher for CandidateIdHasher {+    fn finish(&self) -> u64 {+        self.0+    }++    fn write_u64(&mut self, id: u64) {+        self.0 = id;+    }++    /// Only `u64` keys are expected; anything else still hashes (FNV-1a), just not for free.+    fn write(&mut self, bytes: &[u8]) {+        for &b in bytes {+            self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);+        }+    }+}++/// A map keyed by [`candidate_id`], hashed with [`CandidateIdHasher`].+pub type CandidateMap<V> =+    std::collections::HashMap<u64, V, std::hash::BuildHasherDefault<CandidateIdHasher>>;+ /// Stable id for one label of one tile in one frame, so the accept-set the /// renderer computes in its pre-pass names the same labels `record_symbol` /// later filters by.@@ -399,3 +429,21 @@ include!("placement_part1.rs"); include!("placement_part2.rs"); include!("placement_part3.rs"); include!("placement_globe.rs");++#[cfg(test)]+mod candidate_map_tests {+    use super::{candidate_id, CandidateMap};++    #[test]+    fn an_id_keyed_map_finds_exactly_the_ids_put_in() {+        let mut map: CandidateMap<u32> = CandidateMap::default();+        for label in 0..5_000usize {+            map.insert(candidate_id(14, 2620, 6332, label % 14, label), label as u32);+        }+        assert_eq!(map.len(), 5_000, "candidate ids must stay distinct under the identity hash");+        for label in 0..5_000usize {+            assert_eq!(map.get(&candidate_id(14, 2620, 6332, label % 14, label)), Some(&(label as u32)));+        }+        assert!(!map.contains_key(&candidate_id(14, 2620, 6333, 0, 0)));+    }+}
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 0af7e90b8e..a6aa569465 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -142,6 +142,9 @@ pub(crate) struct ResidentTile {     /// Shaped symbol candidates (CPU-side): the renderer emits quads per frame     /// at the frame's text size. Shaped once on the worker thread.     labels: Vec<geometry::ShapedLabel>,+    /// `labels` indexed by symbol layer ([`geometry::labels_by_layer`]), built at upload so the+    /// per-frame placement and emission walk one layer's labels instead of filtering them all.+    labels_by_layer: HashMap<usize, Vec<u32>>,     /// The tile's heightmap (CPU-side): per-frame label emission samples ground height     /// under anchors from it. Cloned at upload like `labels`; `None` with no DEM.     heightmap: Option<tilecodec::mamaps::body::Heightmap>,@@ -242,7 +245,7 @@ struct TransientBuffers {  /// What the symbol placer accepted: candidate id → (it took its alternate anchor, where in /// acceptance order it landed).-type AcceptSet = HashMap<u64, (bool, u32)>;+type AcceptSet = crate::tile::placement::CandidateMap<(bool, u32)>;  /// Per-frame synchronisation and its command buffer. struct Frame {
library/map/src/main/rust/src/vulkan/renderer/placement.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement.rs b/library/map/src/main/rust/src/vulkan/renderer/placement.rsindex 3235a845dc..09dc8f390f 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -149,12 +149,8 @@ impl Renderer {                 // the UI zoom now that the tile grid is 512, so selection                 // matches MapLibre's per-zoom set directly.                 let min_pop = placement::locality_min_pop(camera.zoom);-                for (label_idx, label) in tile-                    .labels-                    .iter()-                    .enumerate()-                    .filter(|(_, l)| l.layer_index == index)-                {+                let layer_labels = tile.labels_by_layer.get(&index).map_or(&[][..], Vec::as_slice);+                for (label_idx, label) in layer_labels.iter().map(|&i| (i as usize, &tile.labels[i as usize])) {                     if label.rank == 2 && label.pop < min_pop {                         continue;                     }@@ -393,7 +389,7 @@ impl Renderer {         &self,         camera: &Camera,         layers: &[Layer],-        accepted: &HashMap<u64, (bool, u32)>,+        accepted: &super::AcceptSet,         extent: vk::Extent2D,     ) {         use crate::tile::placement;
library/map/src/main/rust/src/vulkan/renderer/record_extra4.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_extra4.rs b/library/map/src/main/rust/src/vulkan/renderer/record_extra4.rsindex 13d777c551..e061724326 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_extra4.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_extra4.rs@@ -4,7 +4,6 @@ use crate::camera::Camera; use crate::style::{Layer, LayerKind, Palette}; use crate::timing::{nanos_since, Step}; use ash::vk;-use std::collections::HashMap;  impl Renderer {     /// Begin the frame's command buffer and render pass, and set the viewport and scissor.@@ -90,7 +89,7 @@ impl Renderer {         ordered: &[u64],         fog: u32,         deferred_symbols: &[(u64, usize)],-        accepted: &HashMap<u64, (bool, u32)>,+        accepted: &super::AcceptSet,         bound: &mut Option<LayerKind>,         submitted: &mut usize,         culled: &mut usize,
library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs b/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rsindex c01cbd8888..63afb76851 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs@@ -9,7 +9,6 @@ use crate::camera::Camera; use crate::style::{Layer, LayerKind, Palette}; use crate::vulkan::pipeline::Push; use ash::vk;-use std::collections::HashMap;  impl Renderer {     /// Build the icon + text push blocks for one tile's symbol batches and draw@@ -160,7 +159,7 @@ impl Renderer {         layer: &Layer,         camera: &Camera,         palette: Palette,-        accepted: &HashMap<u64, (bool, u32)>,+        accepted: &super::AcceptSet,         submitted: &mut usize,         bound: &mut Option<LayerKind>,         binds: &mut BindState,@@ -237,11 +236,8 @@ impl Renderer {         // The style declares at most two arms, so this is at most two. Buffers are         // pre-sized from the label count rather than grown geometrically: the frame's         // label set is known up front, so the push loop below pays no realloc.-        let label_count = tile-            .labels-            .iter()-            .filter(|l| l.layer_index == layer_index)-            .count();+        let layer_labels: &[u32] = tile.labels_by_layer.get(&layer_index).map_or(&[], Vec::as_slice);+        let label_count = layer_labels.len();         let mut batches: Vec<(f32, Vec<f32>, Vec<u32>)> = Vec::with_capacity(2);         // Icons take one batch of their own however many sizes the text has: they are a         // constant screen size, and they sample a different atlas through a different@@ -262,12 +258,7 @@ impl Renderer {         // `String`, every shaped line, every curved centreline — once per symbol layer per         // resident tile per frame, purely to release the `self.tiles` borrow before the uploads         // further down. Nothing in this loop needs `&mut self`, so the borrow simply ends here.-        for (label_idx, label) in tile-            .labels-            .iter()-            .enumerate()-            .filter(|(_, l)| l.layer_index == layer_index)-        {+        for (label_idx, label) in layer_labels.iter().map(|&i| (i as usize, &tile.labels[i as usize])) {             let id = placement::candidate_id(tz, tx, ty, layer_index, label_idx);             let Some(&(flipped, _)) = accepted.get(&id) else {                 continue;
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 f52f94bd3d..27c9a73cc6 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@@ -281,6 +281,7 @@ pub(super) fn assemble_tile(         traffic,         carriageways,         yellow_centre: mesh.yellow_centre,+        labels_by_layer: crate::tile::geometry::labels_by_layer(&mesh.labels),         labels: std::mem::take(&mut mesh.labels),         arrows: std::mem::take(&mut mesh.arrows),         heightmap: mesh.heightmap.take(),
library/map/src/main/rust/tests/frame_cpu_bench.rs
diff --git a/library/map/src/main/rust/tests/frame_cpu_bench.rs b/library/map/src/main/rust/tests/frame_cpu_bench.rsindex d235282994..945979db59 100644--- a/library/map/src/main/rust/tests/frame_cpu_bench.rs+++ b/library/map/src/main/rust/tests/frame_cpu_bench.rs@@ -141,3 +141,92 @@ fn viewport_tile_build() {         );     } }++/// The per-frame label bookkeeping in `record_symbol`: for every symbol layer, every tile's+/// whole label list is scanned for that layer's labels (once to count, once to emit), and each+/// of those pays a `candidate_id` + accept-set lookup before any glyph is emitted.+#[test]+#[ignore = "needs MAMAPS_REAL_ARCHIVE; timing harness"]+fn per_frame_label_scan() {+    use map_renderer::style::LayerKind;+    use map_renderer::tile::placement::candidate_id;+    use std::collections::HashMap;+    let Some(path) = archive_path() else { return };+    let archive = MamapsArchive::open_with_cache(+        FileRangeReader::open(&path).expect("open"),+        Arc::new(LeafCache::new()),+    )+    .expect("archive");+    let layers = style::layers();+    let symbol_layers: Vec<usize> =+        (0..layers.len()).filter(|&i| layers[i].kind == LayerKind::Symbol).collect();+    let toggles = LayerToggles { poi: true, transit: true, traffic: true, safety: true };+    for (name, lon, lat, zoom) in [("SF", -122.4194, 37.7749, 14.0), ("London", -0.1278, 51.5074, 11.0)] {+        let cam = camera(lon, lat, zoom);+        let tiles: Vec<_> = select::visible(&cam, archive.header.min_zoom, archive.header.max_zoom)+            .into_iter()+            .filter_map(|t| {+                let body = archive.tile(t.z, t.x, t.y).ok()??;+                Some(geometry::build_toggled(&body, layers, t.z, t.x, t.y, false, toggles, &KindFilter::all(), 1))+            })+            .collect();+        let total: usize = tiles.iter().map(|m| m.labels.len()).sum();+        // ~1 label in 20 survives placement at these zooms; the accept set is what is looked up.+        let mut accepted: HashMap<u64, (bool, u32)> = HashMap::new();+        for m in &tiles {+            for (i, l) in m.labels.iter().enumerate() {+                if i % 20 == 0 {+                    accepted.insert(candidate_id(m.z, m.x, m.y, l.layer_index, i), (false, 0));+                }+            }+        }+        let frames = 200;+        let t = Instant::now();+        let mut hits = 0usize;+        for _ in 0..frames {+            for &layer_index in &symbol_layers {+                for m in &tiles {+                    let count = m.labels.iter().filter(|l| l.layer_index == layer_index).count();+                    std::hint::black_box(count);+                    for (i, l) in m.labels.iter().enumerate().filter(|(_, l)| l.layer_index == layer_index) {+                        if accepted.contains_key(&candidate_id(m.z, m.x, m.y, layer_index, i)) {+                            hits += 1;+                        }+                        std::hint::black_box(l);+                    }+                }+            }+        }+        let scan_ms = ms(t.elapsed()) / frames as f64;+        // The same walk through the per-tile layer index the renderer now builds at upload,+        // against the accept-set as the renderer now keys it (ids pass straight through).+        let indexed: Vec<_> = tiles.iter().map(|m| geometry::labels_by_layer(&m.labels)).collect();+        let accepted: map_renderer::tile::placement::CandidateMap<(bool, u32)> =+            accepted.iter().map(|(k, v)| (*k, *v)).collect();+        let t = Instant::now();+        let mut hits_indexed = 0usize;+        for _ in 0..frames {+            for &layer_index in &symbol_layers {+                for (m, index) in tiles.iter().zip(&indexed) {+                    let own = index.get(&layer_index).map_or(&[][..], Vec::as_slice);+                    std::hint::black_box(own.len());+                    for &i in own {+                        let l = &m.labels[i as usize];+                        if accepted.contains_key(&candidate_id(m.z, m.x, m.y, layer_index, i as usize)) {+                            hits_indexed += 1;+                        }+                        std::hint::black_box(l);+                    }+                }+            }+        }+        let indexed_ms = ms(t.elapsed()) / frames as f64;+        assert_eq!(hits, hits_indexed, "the index must visit exactly the same labels");+        println!(+            "{name} z{zoom}: {total} labels x {} symbol layers: filter scan {scan_ms:.3} ms/frame, \+             layer index + id-keyed set {indexed_ms:.3} ms/frame ({} accepted)",+            symbol_layers.len(),+            hits / frames+        );+    }+}