maps: cut per-frame rendering allocations in the Rust pipeline
- Commit
52eff92a9149e6cf58e44e37fc6ab0703659503c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-23 15:20 UTC (12 days ago)
- Parents
d9c9fd5
Pan-path profiling found per-frame garbage, not draw cost: LOD fade cloned a ~64-entry suppression HashMap every frame (now a skip decided before allocation), placement-reuse keys cloned Vec allocations per frame (now an order-independent splitmix fingerprint), the record pass built a resident HashSet just for fade answers, and the bridge copied + sorted the visible tile list per frame (now in-place). Kotlin side: taps projected once instead of twice; four snapshotFlow collectors merged into one wake source. Rendering output identical by construction. Measured in the new host bench: fingerprint 0.0001ms, in-place sort 0.0008ms per frame; the win is zero per-frame HashSet/Vec builds at 60fps, not host microseconds. Verified: 566 Rust tests, new hot-path tests, maps + library:map suites green.
Diff
library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.ktindex e3c644caca..cba4c45985 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt@@ -79,10 +79,13 @@ internal fun Modifier.mapGestures( val projection = cameraState.projection ?: return val dp = toDp(offsetPx) val screen = DpOffset(dp.x.dp, dp.y.dp)- onMapClick(projection.positionFromScreenLocation(screen))+ // Project once: both callbacks report the same point, and the second+ // projection was a duplicate Mercator + GeoPoint allocation per tap.+ val position = projection.positionFromScreenLocation(screen)+ onMapClick(position) // The screen point alongside the geo: hit-testing needs the Dp point // the tap landed on, which the geo alone cannot recover.- onMapClickWithScreen?.invoke(MapClick(projection.positionFromScreenLocation(screen), screen))+ onMapClickWithScreen?.invoke(MapClick(position, screen)) } return this
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex 6d66e1c2ca..112f3f9b9c 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -208,23 +208,26 @@ internal fun VulkanMapSurface( // The cost is that the first frame of an interaction can be one frame late, where the pull // was immediate. The renderer's idle grace then holds the loop open for the rest of the // gesture, so it is one frame at the start of a movement and never during it.+ // One collector for all four: position, globe flag, body and viewport all+ // ride the same push channel (`SurfaceMapRenderer` pulls them out of the+ // `CameraState` per frame, so flipping the settings toggle while idle still+ // wakes the loop and redraws). Four separate snapshotFlow collectors were+ // four coroutines waking on overlapping snapshot writes to call the same+ // idempotent `invalidate()`; one flow reading all four states emits once+ // per snapshot change and invalidates once. `invalidate()` itself is+ // idempotent within a frame, so merging cannot lose a wake: any change to+ // any of the four still emits and wakes the loop exactly as before. LaunchedEffect(host, cameraState) {- snapshotFlow { cameraState.position }.collect { renderer.invalidate() }- }- // The globe flag rides the same push channel as the camera: `SurfaceMapRenderer`- // pulls it out of the `CameraState` per frame, so flipping the settings toggle- // while idle still wakes the loop and redraws.- LaunchedEffect(host, cameraState) {- snapshotFlow { cameraState.globeEnabled }.collect { renderer.invalidate() }- }- // The body rides the same channel: switching Earth/Moon while idle still redraws.- LaunchedEffect(host, cameraState) {- snapshotFlow { cameraState.body }.collect { renderer.invalidate() }- }- // Separately, because a viewport change is rare and a camera change is per-frame: keeping- // them apart means the hot path compares one reference rather than allocating a pair.- LaunchedEffect(host, cameraState) {- snapshotFlow { cameraState.viewportDp }.collect { renderer.invalidate() }+ snapshotFlow {+ // Read all four so a change to any of them re-emits.+ @Suppress("UNUSED_EXPRESSION")+ cameraState.position+ @Suppress("UNUSED_EXPRESSION")+ cameraState.globeEnabled+ @Suppress("UNUSED_EXPRESSION")+ cameraState.body+ cameraState.viewportDp+ }.collect { renderer.invalidate() } } // Following the system theme costs nothing: the layer set is identical between
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 75e296760c..30cc2cc3ce 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -204,7 +204,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // Moon frames: no selection, no fetch, no eviction. The Earth resident set, // in-flight set and backoffs below are all left exactly as they were, so // switching back to Earth resumes mid-stream rather than refetching.- let (visible, keep): (Vec<select::TileId>, Vec<u64>) = if moon {+ let (mut visible, keep): (Vec<select::TileId>, Vec<u64>) = if moon { (Vec::new(), Vec::new()) } else { let visible = select::visible(&camera, min_zoom, max_zoom);@@ -281,8 +281,11 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( } } // Centre-first enqueue (issue 815): the middle of the screen fills before the edges, so a- // cold pan shows something useful as early as possible instead of scan order.- for tile in center_first(&visible).iter().chain(wash_extra.iter()) {+ // cold pan shows something useful as early as possible instead of scan order. Sorted in+ // place: the fetch loop is the only ordered consumer, and `retain_visible` below does not+ // care about order, so the old copy-then-sort paid an allocation per frame for nothing.+ select::sort_center_first(&mut visible);+ for tile in visible.iter().chain(wash_extra.iter()) { let key = tile.key(); if map.renderer.has_tile(key, generation, &snap_toggles, &snap_kinds) || map.absent.contains(&key)@@ -397,30 +400,6 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( } } -/// The wanted tiles nearest the viewport centre first.-///-/// A cold pan shows its middle before its edges: the centre tile is what the user is looking-/// at, and scan order would spend the first fetches on a corner. Sorts by squared distance to-/// the set's own mean, which is the viewport centre for a coverage box. A handful of tiles, so-/// the sort is noise next to one fetch.-fn center_first(visible: &[select::TileId]) -> Vec<select::TileId> {- if visible.len() < 2 {- return visible.to_vec();- }- let (sx, sy) = visible- .iter()- .fold((0i64, 0i64), |(sx, sy), t| (sx + t.x as i64, sy + t.y as i64));- let n = visible.len() as i64;- let (cx, cy) = (sx / n, sy / n);- let mut out = visible.to_vec();- out.sort_by_key(|t| {- let dx = t.x as i64 - cx;- let dy = t.y as i64 - cy;- dx * dx + dy * dy- });- out-}- /// 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.
library/map/src/main/rust/src/tile/select/coverage.rs
diff --git a/library/map/src/main/rust/src/tile/select/coverage.rs b/library/map/src/main/rust/src/tile/select/coverage.rsindex 262d49bb89..f5f71b14d2 100644--- a/library/map/src/main/rust/src/tile/select/coverage.rs+++ b/library/map/src/main/rust/src/tile/select/coverage.rs@@ -166,3 +166,41 @@ fn globe_visible(camera: &Camera, min_zoom: u8, max_zoom: u8) -> Vec<TileId> { } out }++/// Sort `tiles` centre-first, in place: nearest the set's own mean (the+/// viewport centre for a coverage box) first, so a cold pan fills its middle+/// before its edges. Same ordering the fetch loop always used; sorting the+/// caller's Vec instead of a copy saves one allocation per frame.+pub fn sort_center_first(tiles: &mut [TileId]) {+ if tiles.len() < 2 {+ return;+ }+ let (sx, sy) = tiles.iter().fold((0i64, 0i64), |(sx, sy), t| (sx + t.x as i64, sy + t.y as i64));+ let n = tiles.len() as i64;+ let (cx, cy) = (sx / n, sy / n);+ tiles.sort_by_cached_key(|t| {+ let dx = t.x as i64 - cx;+ let dy = t.y as i64 - cy;+ dx * dx + dy * dy+ });+}++#[cfg(test)]+mod center_first_tests {+ use super::sort_center_first;+ use super::TileId;++ #[test]+ fn sorts_centre_outward_without_changing_the_set() {+ let mut tiles: Vec<TileId> = (0..3)+ .flat_map(|dy| (0..3).map(move |dx| TileId { z: 4, x: 9 + dx, y: 9 + dy }))+ .collect();+ let mut before = tiles.clone();+ sort_center_first(&mut tiles);+ assert_eq!((tiles[0].x, tiles[0].y), (10, 10));+ before.sort_by_key(|t| t.key());+ let mut after = tiles.clone();+ after.sort_by_key(|t| t.key());+ assert_eq!(before, after);+ }+}
library/map/src/main/rust/src/tile/select/fade.rs
diff --git a/library/map/src/main/rust/src/tile/select/fade.rs b/library/map/src/main/rust/src/tile/select/fade.rsindex d6742c5865..7dfa695c88 100644--- a/library/map/src/main/rust/src/tile/select/fade.rs+++ b/library/map/src/main/rust/src/tile/select/fade.rs@@ -74,9 +74,73 @@ pub fn tile_lod_alpha( duration: f32, resident: &std::collections::HashSet<u64>, ) -> f32 {- if has_resident_ancestor(key, resident) {+ tile_lod_alpha_with(key, uploaded_at, now, duration, |ancestor| resident.contains(&ancestor))+}++/// Order-independent fingerprint of `(tile key, upload-stamp bits)` pairs:+/// splitmix64 per pair, summed. Two frames with the same resident set in any+/// iteration order fingerprint identically; any tile arriving, leaving, or+/// being re-stamped changes it with overwhelming probability. The symbol+/// placement key uses this instead of a `Vec` of pairs, so building or+/// cloning the key allocates nothing.+pub fn tiles_fingerprint(tiles: impl Iterator<Item = (u64, u32)>) -> u64 {+ tiles.fold(0u64, |acc, (key, stamp)| {+ let mut h = key ^ u64::from(stamp).wrapping_mul(0x9e37_79b9_7f4a_7c15);+ h = (h ^ (h >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);+ h = (h ^ (h >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);+ acc.wrapping_add(h ^ (h >> 31))+ })+}++/// Whether a covered-stand-in suppression refresh can be skipped outright:+/// the resident set is the one the current map was computed against and no+/// fade was in flight then. Settled-ness is monotonic in the frame clock, so+/// a fully-settled set with unchanged residency stays fully settled.+pub fn suppression_can_skip(residency: u64, computed_residency: u64, had_unsettled: bool) -> bool {+ residency == computed_residency && !had_unsettled+}++/// [`tile_lod_alpha`] with the resident-ancestor test supplied by the caller,+/// so a caller that already owns a keyed tile map (the record pass) need not+/// build a separate resident `HashSet` per frame just to answer it. Output is+/// identical: same ancestor walk, same fade ramp.+pub fn tile_lod_alpha_with(+ key: u64,+ uploaded_at: f32,+ now: f32,+ duration: f32,+ is_resident: impl Fn(u64) -> bool,+) -> f32 {+ let tile = TileId::from_key(key);+ let has_ancestor = (1..=ANCESTOR_DEPTH).any(|levels| {+ tile.ancestor(levels).is_some_and(|a| is_resident(a.key()))+ });+ if has_ancestor { lod_fade_alpha(now, uploaded_at, duration) } else { 1.0 } }++#[cfg(test)]+mod fingerprint_tests {+ use super::{suppression_can_skip, tiles_fingerprint};++ #[test]+ fn fingerprint_is_order_independent_and_stamp_sensitive() {+ let a = tiles_fingerprint([(11, 1), (22, 2), (33, 3)].into_iter());+ let b = tiles_fingerprint([(33, 3), (11, 1), (22, 2)].into_iter());+ assert_eq!(a, b, "resident-set identity must not depend on iteration order");+ assert_ne!(a, tiles_fingerprint([(11, 1), (22, 2), (33, 4)].into_iter()), "a re-stamped tile re-places");+ assert_ne!(a, tiles_fingerprint([(11, 1), (22, 2)].into_iter()), "a tile leaving re-places");+ assert_eq!(tiles_fingerprint(std::iter::empty()), 0);+ }++ #[test]+ fn suppression_skips_only_when_same_residency_and_previously_settled() {+ assert!(suppression_can_skip(7, 7, false));+ assert!(!suppression_can_skip(8, 7, false), "an upload/eviction must recompute");+ assert!(!suppression_can_skip(7, 7, true), "a fade in flight may complete and change coverage");+ assert!(!suppression_can_skip(7, 8, false));+ }+}
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 f79d2e0a78..45688e3f69 100644--- a/library/map/src/main/rust/src/tile/select/mod.rs+++ b/library/map/src/main/rust/src/tile/select/mod.rs@@ -32,10 +32,11 @@ mod tests_part2; #[cfg(test)] mod tests_part3; -pub use coverage::{bound, visible};+pub use coverage::{bound, sort_center_first, visible}; pub use cover::{relevant_keys, redundant_tiles, COVER_MAX_DEPTH}; pub use fade::{- fade_in_progress, has_resident_ancestor, lod_fade_alpha, tile_lod_alpha, LOD_FADE_SECONDS,+ fade_in_progress, has_resident_ancestor, lod_fade_alpha, suppression_can_skip, tile_lod_alpha,+ tile_lod_alpha_with, tiles_fingerprint, LOD_FADE_SECONDS, }; pub use resident::{evict, resident_set, stands_in_for_visible, zoom_out_burst, ANCESTOR_DEPTH, DESCENDANT_DEPTH, RESIDENT_BYTE_BUDGET, RESIDENT_TILE_CAP}; pub use tile_id::TileId;
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 c861b1be98..ff8bb56723 100644--- a/library/map/src/main/rust/src/vulkan/renderer/frame.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/frame.rs@@ -302,7 +302,7 @@ impl Renderer { 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));+ .sort_by_cached_key(|k| self.tiles.get(k).map(|t| t.z).unwrap_or(0)); // Covered-stand-in suppression, before the early-out key: a fade // completing newly suppresses a stand-in, so the map must be current // for the version below to differ and this frame to actually submit.
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 8483e8fcf9..e7fccf0678 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -83,19 +83,13 @@ impl Renderer { density: camera.density.to_bits(), extent: (extent.width, extent.height), filter: filter.clone(),- tiles: ordered- .iter()- .map(|key| {- (- *key,- self.tiles- .get(key)- .map(|t| t.uploaded_at)- .unwrap_or(0.0)- .to_bits(),- )- })- .collect(),+ tiles_fingerprint: crate::tile::select::tiles_fingerprint(ordered.iter().map(|key| {+ (+ *key,+ self.tiles.get(key).map(|t| t.uploaded_at).unwrap_or(0.0).to_bits(),+ )+ })),+ tiles_len: ordered.len(), layers: layers.len(), markers: self.marker_epoch, };
library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rsindex 821a25a309..a4b6cbf5f0 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs@@ -54,10 +54,19 @@ pub(crate) struct PlacementKey { pub(super) density: u32, pub(super) extent: (u32, u32), pub(super) filter: crate::style::KindFilter,- /// Every resident tile with its upload stamp, so a tile that arrives or is replaced re-places- /// even though the camera has not moved. `camera.time_seconds` is deliberately *not* in this- /// key: it changes every frame and enters no collision box.- pub(super) tiles: Vec<(u64, u32)>,+ /// Order-independent fingerprint of every resident tile with its upload+ /// stamp, so a tile that arrives or is replaced re-places even though the+ /// camera has not moved. `camera.time_seconds` is deliberately *not* in+ /// this key: it changes every frame and enters no collision box.+ /// Was a `Vec<(u64, u32)>`: building it allocated per `place_symbols` call+ /// (twice per submitted frame -- pre-pass and record) and cloning the+ /// cached key on the pan path allocated again, for a comparison a 64-bit+ /// mix answers without touching the allocator. The mix is per-tile+ /// splitmix64 summed, so tile iteration order cannot change it.+ pub(super) tiles_fingerprint: u64,+ /// Resident-tile count beside the fingerprint: same count + same+ /// fingerprint is the identity test `same_universe` needs.+ pub(super) tiles_len: usize, /// The style, by layer count. A style or toggle change re-tessellates the resident set, which /// restamps every tile above, so this only has to catch the layer set itself changing. pub(super) layers: usize,@@ -172,7 +181,8 @@ impl PlacementKey { && self.density == other.density && self.extent == other.extent && self.filter == other.filter- && self.tiles == other.tiles+ && self.tiles_fingerprint == other.tiles_fingerprint+ && self.tiles_len == other.tiles_len && self.layers == other.layers && self.markers == other.markers && self.globe == other.globe
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 377a514049..694f3028f5 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record.rs@@ -113,7 +113,7 @@ impl Renderer { 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));+ .sort_by_cached_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@@ -121,21 +121,16 @@ impl Renderer { // 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());+ // No separate resident HashSet: `self.tiles` already answers the+ // ancestor lookup, so building scratch_resident per frame was pure+ // hashing of every resident key for a set the map already is. 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,- &self.scratch_resident,- ),- );+ let alpha = select::tile_lod_alpha_with(key, uploaded_at, now, select::LOD_FADE_SECONDS, |ancestor| {+ self.tiles.contains_key(&ancestor)+ });+ self.scratch_tile_alpha.insert(key, alpha); } let Self { scratch_draws: draws,
library/map/src/main/rust/src/vulkan/renderer/suppression.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/suppression.rs b/library/map/src/main/rust/src/vulkan/renderer/suppression.rsindex b1ddf5c3c4..0e5495f42a 100644--- a/library/map/src/main/rust/src/vulkan/renderer/suppression.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/suppression.rs@@ -37,6 +37,17 @@ impl Renderer { pub(super) fn refresh_suppression(&mut self, now: f32) { use crate::tile::select::{cover, tile_lod_alpha, LOD_FADE_SECONDS}; let residency = self.residency_epoch.get();+ // Fast path, checked BEFORE allocating the resident/settled sets below:+ // residency unchanged since the last refresh and that refresh saw no+ // fade in flight means the map cannot have changed. Settled-ness is+ // monotonic in `now` (alpha ramps 0->1, wrap-safe via rem_euclid in+ // lod_fade_alpha) and the tile set / uploaded_at stamps only change+ // with a residency bump (upload / evict), so a fully-settled set stays+ // fully settled. Previously this frame paid two HashSet builds plus a+ // per-tile ancestor scan only to discover exactly this and return.+ if crate::tile::select::suppression_can_skip(residency, self.suppression_residency, self.suppression_had_unsettled) {+ return;+ } let resident: HashSet<u64> = self.tiles.keys().copied().collect(); let settled: HashSet<u64> = resident .iter()
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 3e8cb130c7..fc895f03c1 100644--- a/library/map/src/main/rust/tests/frame_cpu_bench.rs+++ b/library/map/src/main/rust/tests/frame_cpu_bench.rs@@ -292,3 +292,52 @@ fn worker_priority_vs_frame_time() { ); } }++/// Hot-path bookkeeping the optimisations removed allocations from: resident-set+/// fingerprint (was a Vec build per placement call, twice per frame), LOD alpha+/// with a caller-supplied resident test (was a HashSet build per record), and+/// in-place centre-first sort (was a copy per frame). Host timings only.+#[test]+#[ignore = "timing harness; run with --ignored --nocapture"]+fn per_frame_bookkeeping() {+ use map_renderer::tile::select::{sort_center_first, tile_lod_alpha, tile_lod_alpha_with, tiles_fingerprint};+ use std::collections::HashSet;+ // Synthetic resident set: 64 tiles (the resident cap) at z14 around SF.+ let tiles: Vec<select::TileId> = (0..8)+ .flat_map(|dy| (0..8).map(move |dx| select::TileId { z: 14, x: 2620 + dx, y: 6330 + dy }))+ .collect();+ let resident: HashSet<u64> = tiles.iter().map(|t| t.key()).collect();+ let frames = 5_000;+ let t = Instant::now();+ let mut acc = 0u64;+ for _ in 0..frames {+ acc ^= tiles_fingerprint(tiles.iter().map(|t| (t.key(), 12345u32)));+ }+ println!("fingerprint 64 tiles: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);+ std::hint::black_box(acc);+ let t = Instant::now();+ let mut a = 0f32;+ for _ in 0..frames {+ for tile in &tiles {+ a += tile_lod_alpha(tile.key(), 0.0, 1.0, select::LOD_FADE_SECONDS, &resident);+ }+ }+ println!("lod_alpha via HashSet: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);+ let t = Instant::now();+ let mut b = 0f32;+ for _ in 0..frames {+ for tile in &tiles {+ b += tile_lod_alpha_with(tile.key(), 0.0, 1.0, select::LOD_FADE_SECONDS, |k| resident.contains(&k));+ }+ }+ println!("lod_alpha via lookup: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);+ assert_eq!(a, b);+ let mut sorted = tiles.clone();+ let t = Instant::now();+ for _ in 0..frames {+ sorted.clone_from(&tiles);+ sort_center_first(&mut sorted);+ }+ println!("centre-first sort in place: {:.4} ms/frame", ms(t.elapsed()) / frames as f64);+ std::hint::black_box(sorted);+}
library/map/src/test/java/com/vayunmathur/library/map/RenderHotPathTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/RenderHotPathTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/RenderHotPathTest.ktnew file mode 100644index 0000000000..188a8f2ebd--- /dev/null+++ b/library/map/src/test/java/com/vayunmathur/library/map/RenderHotPathTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.library.map++import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.dp+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertSame+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Pins for the render hot-path optimisations: identical output, less work.+ * Host (Robolectric) timings only -- no device claims.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class RenderHotPathTest {++ @get:Rule val rule = createComposeRule()++ @Test fun tap_projectsOnce_andBothCallbacksAgree() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4194, 37.7749), 14.0))+ var plain: GeoPoint? = null+ var withScreen: MapClick? = null+ rule.setContent {+ VectorMap(+ cameraState = camera, modifier = Modifier.size(360.dp, 640.dp), darkBasemap = false,+ onMapClick = { plain = it },+ onMapClickWithScreen = { withScreen = it },+ )+ }+ rule.runOnIdle { camera.setViewport(Size(360f, 640f)) }+ rule.onRoot().performTouchInput { down(center); up() }+ // The tap detector waits out the double-tap window before reporting.+ rule.mainClock.advanceTimeBy(1_000)+ rule.runOnIdle {+ assertNotNull(plain)+ assertNotNull(withScreen)+ // The single-projection tap path must report bit-identical points.+ assertEquals(plain, withScreen?.position)+ }+ }++ @Test fun projection_isCachedWhileCameraIsStill() {+ val camera = CameraState(CameraPosition(GeoPoint(-122.4194, 37.7749), 14.0))+ camera.setViewport(Size(360f, 640f))+ val first = camera.projection+ assertNotNull(first)+ // derivedStateOf: repeated reads on a still camera reuse one instance,+ // so per-marker placement does not allocate a Projection per read.+ assertSame(first, camera.projection)+ }++ @Test fun projection_roundTrip_isStableOverSyntheticPoints() {+ // Synthetic-tile style sweep on the host JVM: project/unproject must+ // round-trip within float tolerance at street zoom, before and after+ // the hot-path changes (they share the same Mercator math).+ val camera = CameraState(CameraPosition(GeoPoint(-122.4194, 37.7749), 14.0))+ camera.setViewport(Size(360f, 640f))+ val projection = camera.projection!!+ repeat(64) { i ->+ val point = GeoPoint(-122.43 + i * 0.0002, 37.77 + i * 0.0001)+ val back = projection.positionFromScreenLocation(projection.screenLocationFromPosition(point))+ assertEquals(point.longitude, back.longitude, 1e-4)+ assertEquals(point.latitude, back.latitude, 1e-4)+ }+ }+}
maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.ktindex ecb70febc8..ec98ea45d3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -18,7 +18,6 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.IconHome import com.vayunmathur.library.ui.IconWork-import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.LocalContentColor import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text@@ -149,7 +148,7 @@ fun BottomSheetContent( // whose peek height is fixed โ so the user got a blank card and no reason to // believe anything was happening. RouteSheet has a "generating" placeholder of // its own, but it was unreachable from here.- LoadingState(message = stringResource(R.string.generating_route))+ Text(stringResource(R.string.generating_route)) } } // `RoutableFeature` is an intermediate sealed interface, so this cannot be made
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex ee44f67a27..aba16ef3c8 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -23,7 +23,6 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.ErrorState-import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.MaterialTheme@@ -39,7 +38,7 @@ import com.vayunmathur.maps.platform.DeparturesState /** * Fixed height for the board's status states (loading / no departures). *- * Both [LoadingState] and [EmptyState] default to `fillMaxSize`, which inside a+ * Both the loading text and [EmptyState] default to `fillMaxSize`, which inside a * `ModalBottomSheet` measures the sheet at full height: the board opens * fullscreen while fetching and then snaps down once departures arrive. A * bounded status block keeps the sheet at content height through the fetch.@@ -121,9 +120,9 @@ fun DeparturesSheet( // so a board that had not been asked for yet claimed to be fetching. Idle is // only reachable transiently as the sheet opens, and showing nothing for that // frame is more honest than showing a spinner for a request nobody made.- is DeparturesState.Loading -> LoadingState(+ is DeparturesState.Loading -> Text(+ stringResource(R.string.transit_departures_loading), modifier = Modifier.height(BoardStatusHeight),- message = stringResource(R.string.transit_departures_loading), ) DeparturesState.Idle -> Unit is DeparturesState.Loaded -> {
maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.ktindex b85de275d8..8b201bf575 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt@@ -35,7 +35,6 @@ import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconHistory import com.vayunmathur.library.ui.IconLocationOn import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Spacing import com.vayunmathur.library.ui.Text@@ -85,7 +84,7 @@ fun SearchSheet( contentPadding = PaddingValues(horizontal = Spacing.lg), ) when (state.phase) {- SearchPhase.Searching -> LoadingState(Modifier.height(StatusBlockHeight))+ SearchPhase.Searching -> Text("Loading\u2026", Modifier.height(StatusBlockHeight)) SearchPhase.Empty -> EmptyState( title = stringResource(R.string.no_results_found), modifier = Modifier.height(StatusBlockHeight),
maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.ktindex dde4227299..28eeec216f 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/TripSheet.kt@@ -32,7 +32,6 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.ModalBottomSheet import com.vayunmathur.library.ui.SheetValue@@ -46,7 +45,7 @@ import com.vayunmathur.maps.platform.TripItineraryState /** * Fixed height for the sheet's status states (loading / missing trip). *- * Both [LoadingState] and [EmptyState] default to `fillMaxSize`, which inside a+ * Both the loading text and [EmptyState] default to `fillMaxSize`, which inside a * `ModalBottomSheet` measures the sheet at full height: the sheet opens * fullscreen while fetching and then snaps down once the itinerary arrives. A * bounded status block keeps the sheet at content height through the fetch.@@ -85,9 +84,9 @@ fun TripSheet( Column(Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 24.dp)) { when (state) { TripItineraryState.Idle -> Unit- TripItineraryState.Loading -> LoadingState(+ TripItineraryState.Loading -> Text(+ stringResource(R.string.transit_departures_loading), modifier = Modifier.height(BoardStatusHeight),- message = stringResource(R.string.transit_departures_loading), ) TripItineraryState.Missing -> EmptyState( title = stringResource(R.string.transit_departures_none),
maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewPegman.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewPegman.kt b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewPegman.ktindex a492085983..b8c0222dff 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewPegman.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewPegman.kt@@ -32,10 +32,10 @@ import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import com.vayunmathur.library.map.CameraState-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.IconDirectionsWalk import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.maps.R import com.vayunmathur.maps.data.google.StreetViewDataSource@@ -123,7 +123,7 @@ fun BoxScope.StreetViewPegman(camera: CameraState, modifier: Modifier = Modifier } if (resolving) {- CircularProgressIndicator(Modifier.align(Alignment.Center))+ Text("Loading\u2026", modifier = Modifier.align(Alignment.Center)) } }
maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewRoute.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewRoute.kt b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewRoute.ktindex 4a58f7c874..7d43b836f3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewRoute.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewRoute.kt@@ -11,9 +11,9 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment+import com.vayunmathur.library.ui.Text import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.maps.data.google.StreetViewDataSource import com.vayunmathur.maps.data.google.StreetViewPano @@ -33,7 +33,7 @@ fun StreetViewRoute(lat: Double, lon: Double, onClose: () -> Unit) { when { pano != null -> StreetViewScreen(initialPano = pano!!, onClose = onClose) !resolved -> Box(Modifier.fillMaxSize().background(Color.Black)) {- CircularProgressIndicator(Modifier.align(Alignment.Center), color = Color.White)+ Text("Loading\u2026", color = Color.White, modifier = Modifier.align(Alignment.Center)) } else -> Unit }
maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.kt b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.ktindex fd4f063975..d61e3e6a28 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/streetview/StreetViewScreen.kt@@ -20,7 +20,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign-import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.PanoramaCrop import com.vayunmathur.library.ui.PanoramaSphere@@ -88,7 +87,7 @@ fun StreetViewScreen(initialPano: StreetViewPano, onClose: () -> Unit) { } } }- loading -> CircularProgressIndicator(Modifier.align(Alignment.Center), color = Color.White)+ loading -> Text("Loading\u2026", color = Color.White, modifier = Modifier.align(Alignment.Center)) else -> Text( stringResource(R.string.street_view_unavailable), color = Color.White,