maps: remove gesture fetch freeze from tile fetching
- Commit
e0459bc27e1daea0410e0dbea88ac2e1b4b40244- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-08 18:35 UTC (27 days ago)
- Parents
090e7a7
The gesture fetch freeze held tile fetching at the session's start zoom while a pinch or camera animation ran, advancing only as the live zoom crossed integer levels; rendering always tracked the live camera with resident overzoom cover. Tile selection now keys on the live camera zoom every frame, so a pinch fetches each intermediate level as it crosses it. Kotlin (:library:map): delete GestureFreeze and its test; drop the VulkanMapSurface gesture-session quiet-timeout loop; drop the mapGestures touch-end observer; remove CameraState gestureEndHandler and animationActive; remove SurfaceMapRenderer/MapNative setGestureActive; drop the RendererStateTest freeze call. Rust (:library:map bridge): delete gesture.rs (GestureDebounce); remove the MapHandle gesture field and setter, the setGestureActive JNI entry, and the frame.rs frozen-fetch-zoom selection, fetch camera, and debounce-hold queue block. Step::FetchCancelled (fcan) is kept: drain-and-replace discards still report through it. Behaviour note: the freeze lived in shared :library:map, so weather, taxi, and fooddelivery pick up the same live-zoom fetching. No permission or manifest changes. Verified: :library:map:compileDebugKotlin + :maps:compileDevKotlin green, :library:map:lint green, cargo check clean (only pre-existing warnings), :maps:checkDevAarMetadata green. :maps:lintDev still reports 44 pre-existing errors in untouched files, none in the touched paths.
Diff
library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.ktindex c234d79950..929b891bd6 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt@@ -114,28 +114,6 @@ class CameraState(initial: CameraPosition = CameraPosition()) { */ internal var markerPickProvider: ((Float, Float) -> Long)? by mutableStateOf(null) - /**- * Touch-end rendezvous for the gesture-freeze release: the touch-end observer in- * `mapGestures` reports every pointer lift here, and `VulkanMapSurface` registers- * the release into it the same way it registers the pick providers above (cleared- * on dispose). Plain `var`, not snapshot state — it is written once per composition- * and read imperatively from pointer-input handlers, so no reader needs reactivity- * and a state read would only add wakes to the gesture path.- *- * Null until a surface registers: car and other non-Compose hosts never do, and- * keep today's quiet-timeout release with no behavior change.- */- internal var gestureEndHandler: (() -> Unit)? = null-- /**- * True while [animateTo] or [animateZoomBy] is driving the camera. Read by the- * touch-end observer to gate the explicit release: a tap landing mid-animation- * must not release the animation's freeze, which would churn fetches at- * intermediate zooms. Plain `var` for the same reason as [gestureEndHandler] —- * written and read on the main thread with no reactive reader.- */- internal var animationActive = false- /** * Sets the measured viewport and enforces the minimum "fill" zoom so the map * always covers the viewport (no blank margins when zoomed all the way out),@@ -187,24 +165,17 @@ class CameraState(initial: CameraPosition = CameraPosition()) { // Longitude likewise: a flight from 179 E to 179 W hops the antimeridian rather than // sweeping across the whole planet. val lonStep = angleDelta(start.target.longitude, target.target.longitude)- // try/finally: cancellation must clear the flag or the touch-end observer would- // gate every later release on a dead animation and the freeze would stick.- animationActive = true- try {- Animatable(0f).animateTo(1f, tween(durationMs)) {- val t = value.toDouble()- position = CameraPosition(- target = GeoPoint(- wrapLongitude(start.target.longitude + lonStep * t),- lerp(start.target.latitude, target.target.latitude, t),- ),- zoom = lerp(start.zoom, target.zoom, t),- bearing = start.bearing + turn * t,- pitch = lerp(start.pitch, target.pitch, t),- )- }- } finally {- animationActive = false+ Animatable(0f).animateTo(1f, tween(durationMs)) {+ val t = value.toDouble()+ position = CameraPosition(+ target = GeoPoint(+ wrapLongitude(start.target.longitude + lonStep * t),+ lerp(start.target.latitude, target.target.latitude, t),+ ),+ zoom = lerp(start.zoom, target.zoom, t),+ bearing = start.bearing + turn * t,+ pitch = lerp(start.pitch, target.pitch, t),+ ) } } @@ -227,14 +198,8 @@ class CameraState(initial: CameraPosition = CameraPosition()) { val start = position val target = clampZoom(start.zoom + deltaZoom, vp, minZoom, maxZoom) if (target == start.zoom) return- // try/finally for the same gate the touch-end observer reads in `animateTo`.- animationActive = true- try {- Animatable(0f).animateTo(1f, tween(durationMs)) {- position = anchoredZoom(start, lerp(start.zoom, target, value.toDouble()), anchorDp, vp)- }- } finally {- animationActive = false+ Animatable(0f).animateTo(1f, tween(durationMs)) {+ position = anchoredZoom(start, lerp(start.zoom, target, value.toDouble()), anchorDp, vp) } }
library/map/src/main/java/com/vayunmathur/library/map/GestureFreeze.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/GestureFreeze.kt b/library/map/src/main/java/com/vayunmathur/library/map/GestureFreeze.ktdeleted file mode 100644index 079c152cc1..0000000000--- a/library/map/src/main/java/com/vayunmathur/library/map/GestureFreeze.kt+++ /dev/null@@ -1,42 +0,0 @@-package com.vayunmathur.library.map--/**- * Single owner of the native fetch-freeze engaged flag.- *- * While a pinch or camera animation drives the zoom, the Rust side freezes tile- * fetching at the session's start zoom so intermediate zooms do not churn the- * wanted set; the freeze releases when the motion settles and the final zoom- * fetches. Two producers can end a session — the touch-end observer in- * `mapGestures` (via `CameraState.gestureEndHandler`) and the quiet timeout in- * the `VulkanMapSurface` gesture-session loop — and both must funnel through- * this one object. If the explicit release cleared native state while the loop- * still believed itself frozen, the next gesture's rising edge would skip- * `markActive` and run unfrozen; if the loop cleared it behind the observer's- * back, the symmetric desync would freeze a gesture that already ended. The- * `engaged` flag here is the only copy of that truth.- *- * `release` wakes the frame loop because the settled zoom still needs its- * fetch-and-draw pass; `markActive` deliberately does not- * ([SurfaceMapRenderer.setGestureActive] never wakes — the gesture frames- * themselves already do).- */-internal class GestureFreeze(private val renderer: SurfaceMapRenderer) {- private var engaged = false-- /** Freeze fetching at [zoom] on the session's rising edge; later calls are no-ops. */- fun markActive(zoom: Float) {- if (engaged) return- engaged = true- renderer.setGestureActive(true, zoom)- }-- /** Release the freeze and wake the loop; idempotent so both end signals can call it. */- fun release() {- if (!engaged) return- engaged = false- renderer.setGestureActive(false, 0f)- // Wake the loop: if the idle grace already lapsed, nothing else would draw- // the frame that lets the native side settle and fetch the final zoom.- renderer.invalidate()- }-}
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 f4fe857729..e3c644caca 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@@ -161,35 +161,6 @@ internal fun Modifier.mapGestures( ) } }- // Touch-end observer for the gesture-freeze release, declared last so it sees- // events after the detectors above. It never consumes anything, so it cannot- // steal a gesture from them — it only watches every touch end and reports it- // through `CameraState.gestureEndHandler`, releasing the fetch freeze the- // instant the finger lifts instead of waiting out the quiet timeout in- // `VulkanMapSurface`.- //- // Deliberately a raw `awaitPointerEvent` up-wait rather than- // `waitForUpOrCancellation`: the siblings above consume the up (tap consumes- // the first-tap up, quick-zoom the second), and consumption cancels that- // helper — but the up event itself is still delivered to every handler, so- // this loop sees the lift regardless. If dispatch ever swallows one, the- // quiet timeout in `VulkanMapSurface` remains as the backstop, unchanged.- //- // The release is gated on no camera animation driving the position: a tap- // landing mid-`animateTo` must not release the animation's freeze. When the- // gate holds, the quiet timeout still releases on the animation's last frame.- .pointerInput(cameraState) {- awaitEachGesture {- awaitFirstDown(requireUnconsumed = false)- var lifted = false- while (!lifted) {- if (awaitPointerEvent().changes.none { it.pressed }) lifted = true- }- if (!cameraState.animationActive) {- cameraState.gestureEndHandler?.invoke()- }- }- } } /**
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex c242acc474..7b4494e53a 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -223,18 +223,6 @@ internal object MapNative { */ external fun setOnline(handle: Long, online: Boolean) - /**- * Tell the renderer a gesture is active. While [active] the *fetch* zoom freezes at- * [zoom], so a pinch does not churn the wanted tile set every frame with tiles that- * scroll out before they land — rendering keeps tracking the live camera and resident- * ancestors/descendants cover the gap with overzoom, and the real zoom fetches once- * the camera settles. Pan-only motion never freezes (the zoom is unchanged).- *- * Driven from the gesture channel that already invalidates the frame loop; this only- * steers *fetch*, never frames, so a missing signal degrades to today's behaviour.- */- external fun setGestureActive(handle: Long, active: Boolean, zoom: Float)- /** * Show the user-location puck at [lon]/[lat], drawn by the renderer inside the same * frame as the basemap.
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex 566df88ac3..eb0434311b 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -711,21 +711,6 @@ class SurfaceMapRenderer( invalidate() } - /**- * Tell the renderer a gesture is active. While active the native fetch zoom freezes,- * so a pinch does not churn the wanted tile set every frame — rendering keeps tracking- * the live camera. Driven from the gesture channel in `VulkanMapSurface`; safe to call- * redundantly (the native side ignores no-change sets), and safe to never call (the- * native settle timer releases the freeze on its own).- */- fun setGestureActive(active: Boolean, zoom: Float) {- if (handle != 0L) {- MapNative.setGestureActive(handle, active, zoom)- }- // No invalidate: the camera motion that accompanies the gesture already wakes the- // loop through the position push channel; a bare release signal needs no frame.- }- /** * Show the user's location, drawn inside the renderer's own frame so it stays glued to * the ground while the map moves. `null` draws nothing.
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 361374167c..9d7a6e69e1 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@@ -25,20 +25,6 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.isActive-import kotlinx.coroutines.withTimeoutOrNull--/**- * How long the position flow may go quiet before the gesture counts as released.- *- * Matches the native settle window ([GestureDebounce] settles after 15 still frames ≈- * 250ms) with margin: the Kotlin side releases first, so the native side never has to- * rely on its own timeout while the host is driving. Short enough that the settled zoom- * fetches promptly after the finger lifts; long enough that a slow gesture with pauses- * does not flap the freeze on and off mid-pinch.- */-private const val GESTURE_QUIET_MILLIS = 200L /** * Hosts the Vulkan renderer in Compose.@@ -141,10 +127,6 @@ internal fun VulkanMapSurface( MapSurfaceHost(context, cameraState, density, tileSource) { currentOnFrame() } } val renderer = host.renderer- // Single owner of the fetch-freeze engaged flag, shared by the touch-end observer- // (registered below) and the quiet-timeout loop further down — one flag means the- // two end signals cannot desync the session state between them.- val freeze = remember(host) { GestureFreeze(renderer) } // The renderer pulls its camera from here every frame; a new CameraState must replace the // one the host was built with, or the map keeps drawing the old camera. LaunchedEffect(host, cameraState) {@@ -164,15 +146,9 @@ internal fun VulkanMapSurface( // buffer. Cleared on dispose so a projection without a live renderer answers 0, not a dead // handle. cameraState.markerPickProvider = { xDp: Float, yDp: Float -> renderer.pickAt(xDp, yDp) }- // The freeze-release counterpart: the touch-end observer in `mapGestures`- // reports every pointer lift here so the fetch freeze releases the instant- // the finger lifts, ~200ms before the quiet timeout below would. Cleared on- // dispose so a projection without a live renderer holds no dead renderer.- cameraState.gestureEndHandler = { freeze.release() } onDispose { cameraState.labelQueryProvider = null cameraState.markerPickProvider = null- cameraState.gestureEndHandler = null } } @@ -240,49 +216,6 @@ internal fun VulkanMapSurface( LaunchedEffect(host, cameraState) { snapshotFlow { cameraState.body }.collect { renderer.invalidate() } }- // The gesture signal rides alongside the camera push channel: while any gesture or- // camera animation is driving the position, the native fetch zoom freezes so a pinch- // does not churn the wanted tile set — and releases on settle, so the final zoom- // fetches. `position` changes on every gesture frame; the release detector below- // watches the same flow go quiet, which means the finger lifted (or the animation- // ended). A host that never gestures never freezes. Animations freeze fetch too,- // deliberately: a 500ms `animateTo` crosses the same intermediate zooms a pinch does.- //- // Two end signals share one session through [GestureFreeze]: the touch-end observer- // releases the instant the finger lifts (fast path, ~200ms before the timeout), and- // the `withTimeoutOrNull` below fires the same release after- // [GESTURE_QUIET_MILLIS] of quiet as the backstop — covering animation ends, hosts- // without the observer, and any lift dispatch swallows. A fresh emission cancels- // the timeout and re-arms it; the loop exits only when the effect leaves the- // composition, releasing on the way out. No ticker coroutine, no new thread — and- // the release path never touches the frame loop beyond the wake the freeze owes.- LaunchedEffect(host, cameraState) {- // The last position already consumed: `snapshotFlow.first()` replays the current- // value immediately, so without this the loop would spin on a stale position- // instead of waiting for a new one. Seeded to the current position (which the- // original position effect below already invalidates for).- var last = cameraState.position- while (isActive) {- // A fresh flow per iteration, filtered to genuine changes: `first()` on an- // unfiltered flow returns the current value at once, which would defeat the- // quiet timeout below. Consecutive duplicates are impossible here — the- // filter holds until the position actually moves again.- val position = withTimeoutOrNull(GESTURE_QUIET_MILLIS) {- snapshotFlow { cameraState.position }.first { it != last }- }- if (position == null) {- // Quiet: the finger lifted or the animation ended. The freeze funnels- // both end signals through one flag, so this is a no-op when the- // touch-end observer already released.- freeze.release()- continue- }- last = position- freeze.markActive(position.zoom.toFloat())- renderer.invalidate()- }- freeze.release()- } // 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) {
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 018f8de2c7..cf662800cb 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -192,35 +192,18 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // 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, so a pinch does not churn the wanted set every frame- // with tiles that scroll out before they land. The freeze is per integer tile- // level — it advances as the live zoom crosses into a new level, so the entered- // level's wave starts mid-gesture rather than waiting for release (see- // `GestureDebounce::fetch_zoom`: that wait is the zoom-lags-while-pan-is-instant- // asymmetry). Rendering keeps the live camera — resident ancestors/descendants- // cover the gap with overzoom — and the settled zoom fetches once the camera- // settles. Pan-only motion never freezes (the zoom is unchanged, so ideal and- // fetch agree). Skipped on Moon frames with the selection below.+ // Tile selection keys on the live camera zoom every frame, including mid-gesture:+ // a pinch fetches each intermediate level as it crosses it. Skipped on Moon+ // frames with the selection below. let moon = crate::camera::moon_active(&camera);- let fetch_zoom = if moon {- camera.zoom- } else {- map.gesture.fetch_zoom(camera.zoom)- };+ let fetch_zoom = camera.zoom; // 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 { (Vec::new(), Vec::new()) } else {- // The fetch camera shares everything but the zoom: selection at the frozen level- // keeps the wanted set stable while the draw camera tracks the finger.- let fetch_camera = Camera {- zoom: fetch_zoom,- ..camera- };- let visible = select::visible(&fetch_camera, min_zoom, max_zoom);+ let visible = select::visible(&camera, min_zoom, max_zoom); let keep: Vec<u64> = select::resident_set(&camera, min_zoom, max_zoom) .iter() .map(|t| t.key())@@ -275,12 +258,8 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // keys a worker already took stay marked and are never duplicated. Skipped while the // wanted set is steady (the common case) and before the first Earth frame. //- // The debounce counts here too: while the fetch zoom is frozen, keys that fell out of- // the frozen set are dropped without fetching (they belong to an intermediate zoom the- // gesture already left behind), and the count lands in `Step::FetchCancelled` below.- // `fetch_held` counts the debounce holds below; drain-and-replace discards count- // too. Both are "wanted, never fetched" — the `Step::FetchCancelled` proof that the- // gesture path is holding back storms rather than issuing them.+ // Drain-and-replace discards are "wanted, never fetched" — the+ // `Step::FetchCancelled` count of storms held back rather than issued. let mut fetch_cancelled = 0usize; if !moon && !map.last_visible.is_empty() && wanted_keys != map.last_visible { if let Ok(queue) = map.wanted_queue.try_lock() {@@ -297,26 +276,6 @@ 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.- //- // Debounce hold: while the fetch zoom is frozen, tiles at the *live* zoom that are not- // in the frozen set are held back, not fetched. They belong to an intermediate level the- // gesture is passing through; fetching them spends a worker on bytes that scroll out- // before they land. The frozen set plus resident overzoom covers the screen instead.- // Held keys never enter `in_flight`, so they are re-considered (not retried) next frame.- let frozen_set: std::collections::HashSet<u64> = wanted_keys.clone();- let live_keys: std::collections::HashSet<u64> = if (fetch_zoom - camera.zoom).abs() > f64::EPSILON- && !moon- {- let live_camera = camera;- select::visible(&live_camera, min_zoom, max_zoom)- .iter()- .map(|t| t.key())- .collect()- } else {- std::collections::HashSet::new()- };- // Held keys never enter `in_flight`, so they are re-considered (not retried) next frame.- 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, &snap_toggles, &snap_kinds)@@ -350,10 +309,8 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( .retain(&keep, &visible, RESIDENT_TILE_CAP, RESIDENT_BYTE_BUDGET); map.last_visible = wanted_keys; }- // `fetch_held` (the hold count from the live-set diff above) plus the drain count- // from the drain-and-replace above both land here. Recorded every frame (including- // zero) so the overlay row tracks holds rather than going stale.- fetch_cancelled += fetch_held;+ // The drain count from the drain-and-replace above lands here. Recorded every+ // frame (including zero) so the overlay row tracks discards rather than going stale. map.renderer .step_times .borrow_mut()
library/map/src/main/rust/src/bridge/gesture.rs
diff --git a/library/map/src/main/rust/src/bridge/gesture.rs b/library/map/src/main/rust/src/bridge/gesture.rsdeleted file mode 100644index d28d8aa14f..0000000000--- a/library/map/src/main/rust/src/bridge/gesture.rs+++ /dev/null@@ -1,247 +0,0 @@-//! Fetch zoom debouncing across an active gesture (MapLibre's "load while moving" rule).-//!-//! Split from `bridge::handle` (file-length limit). A pinch changes the ideal zoom every-//! frame; fetching every intermediate level storms the workers with tiles that scroll out-//! before they land. While a gesture is active the *fetch* zoom freezes at the-//! gesture-start level and rendering overzooms the resident set (which costs nothing —-//! tessellation is zoom-independent), and the real zoom is fetched once the camera-//! settles. Pan-only motion never freezes: the zoom is unchanged, so the ideal and fetch-//! zooms agree and this is a no-op.-//!-//! The freeze advances as the live zoom crosses integer tile levels (see-//! [`fetch_zoom`](GestureDebounce::fetch_zoom)): selection keys on the floored zoom, so-//! within one level the wanted set only shifts with pan — which the fetch camera already-//! tracks live — while crossing into a new level changes every key. Holding the whole-//! gesture pinned the withhold at gesture length plus the host quiet timeout, which is-//! the zoom-lags-while-pan-is-instant asymmetry: pan fetches live the whole time, a-//! pinch fetched nothing new until release. Advancing per crossed level starts the-//! destination level's wave mid-gesture while churn stays bounded at one wanted-set-//! change per level crossed.-//!-//! Fed by [`set_gesture_active`](crate::bridge::handle::MapHandle::set_gesture_active)-//! from the host's gesture channel; the settle timer runs on frame time so no extra thread-//! or callback is needed.-pub(crate) struct GestureDebounce {- /// Whether the host reports an active gesture (finger down / fling running).- active: bool,- /// The zoom fetches are pinned to while `active`, or `None` outside a gesture.- frozen_zoom: Option<f64>,- /// Last frame's camera zoom, for the settle detector when the host hint is absent.- last_zoom: Option<f64>,- /// Consecutive settled frames (zoom unchanged within epsilon) while active.- settled_frames: u32,-}--impl GestureDebounce {- pub(crate) fn new() -> GestureDebounce {- GestureDebounce {- active: false,- frozen_zoom: None,- last_zoom: None,- settled_frames: 0,- }- }-- /// How many settled frames end a gesture without a host signal: at 60fps this is- /// ~250ms of a still camera, matching the Kotlin idle grace. Longer would hold- /// blurry overzoom after the finger lifts; shorter would unfreeze mid-pinch.- const SETTLE_FRAMES: u32 = 15;- /// Zoom changes below this count as settled: Choreographer jitter and float- /// round-trips through JNI move the zoom by dust, not by levels.- const SETTLE_EPSILON: f64 = 1e-6;-- /// The host's gesture signal. `true` on finger-down (or fling start), `false` on- /// release. Freezing starts on the rising edge at the current zoom; the falling- /// edge releases immediately so the settled zoom fetches on the next frame.- pub(crate) fn set_active(&mut self, active: bool, zoom: f64) {- if active && !self.active {- self.frozen_zoom = Some(zoom);- self.settled_frames = 0;- } else if !active {- self.frozen_zoom = None;- self.settled_frames = 0;- }- self.active = active;- }-- /// The zoom to select tiles at this frame: the frozen zoom while a gesture is- /// mid-flight, the live zoom otherwise. Rendering still uses the live camera —- /// only the *fetch* set freezes, and resident ancestors/descendants cover the gap.- ///- /// The freeze is per integer tile level, not per gesture: selection keys on the- /// floored zoom, so when the live zoom crosses into a new level the freeze- /// advances to it and that level's wave starts mid-gesture. Within a level the- /// frozen zoom holds (fractional movement changes no key), so a pinch issues at- /// most one wanted-set change per level crossed — the same crossings an- /// unfrozen fetch would issue — instead of withholding every new level until- /// release plus the host quiet timeout. That withhold is the zoom-lags-while-- /// pan-is-instant asymmetry: pan fetches its (same-level) tiles live throughout- /// the gesture, while a fully pinned pinch fetched nothing new until release.- ///- /// When the host never signals (car path, older hosts), a still camera settles the- /// freeze by itself after [`SETTLE_FRAMES`](Self::SETTLE_FRAMES) unchanged frames,- /// so a stuck-active hint cannot pin the map on overzoom forever.- pub(crate) fn fetch_zoom(&mut self, zoom: f64) -> f64 {- let settled = self- .last_zoom- .is_some_and(|last| (zoom - last).abs() < Self::SETTLE_EPSILON);- self.last_zoom = Some(zoom);- let Some(frozen) = self.frozen_zoom else {- self.settled_frames = 0;- return zoom;- };- // Level crossing advances the freeze (see above): a new integer level means- // a wholly new wanted set, and starting its fetch now rather than at release- // is what closes the zoom-vs-pan gap. Resets the settle count — the camera- // is moving by definition — and returns the live zoom, which selects exactly- // the entered level.- if zoom.floor() != frozen.floor() {- self.frozen_zoom = Some(zoom);- self.settled_frames = 0;- return zoom;- }- if settled {- self.settled_frames += 1;- if self.settled_frames >= Self::SETTLE_FRAMES {- self.frozen_zoom = None;- self.settled_frames = 0;- return zoom;- }- } else {- self.settled_frames = 0;- }- frozen- }-- /// Whether a fetch freeze is currently holding the zoom back. For tests and the- /// frame log; the fetch path itself reads [`fetch_zoom`](Self::fetch_zoom).- #[cfg(test)]- pub(crate) fn is_frozen(&self) -> bool {- self.frozen_zoom.is_some()- }-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn idle_never_freezes() {- let mut g = GestureDebounce::new();- assert_eq!(g.fetch_zoom(14.0), 14.0);- assert_eq!(g.fetch_zoom(14.5), 14.5);- assert!(!g.is_frozen());- }-- #[test]- fn gesture_freezes_at_start_zoom_until_release() {- let mut g = GestureDebounce::new();- g.set_active(true, 14.0);- // The pinch moves through intermediate zooms; fetches stay pinned.- assert_eq!(g.fetch_zoom(14.2), 14.0);- assert_eq!(g.fetch_zoom(14.7), 14.0);- assert!(g.is_frozen());- // Release fetches the settled zoom on the very next frame.- g.set_active(false, 15.0);- assert_eq!(g.fetch_zoom(15.0), 15.0);- assert!(!g.is_frozen());- }-- #[test]- fn pan_only_motion_never_freezes() {- // Same zoom in, same zoom out even while "active": a pan carries no new level- // to fetch, so the freeze is a no-op by construction.- let mut g = GestureDebounce::new();- g.set_active(true, 14.0);- for _ in 0..30 {- assert_eq!(g.fetch_zoom(14.0), 14.0);- }- // …but 30 settled frames release the freeze itself (the settle timer), so a- // stuck-active hint cannot pin overzoom forever.- assert!(!g.is_frozen());- }-- #[test]- fn stuck_active_settles_by_itself() {- // The host signalled active and never released (car path, dropped signal):- // crossing into z15 advances the freeze to the entered level, then 15- // settled frames at the *moved* zoom release it.- let mut g = GestureDebounce::new();- g.set_active(true, 14.0);- assert_eq!(g.fetch_zoom(15.0), 15.0);- for _ in 0..15 {- g.fetch_zoom(15.0);- }- assert_eq!(g.fetch_zoom(15.0), 15.0);- assert!(!g.is_frozen());- }-- #[test]- fn jitter_does_not_reset_the_settle() {- // Sub-epsilon zoom dust (JNI float round-trips) counts as settled.- let mut g = GestureDebounce::new();- g.set_active(true, 14.0);- g.fetch_zoom(15.0);- for i in 0..15 {- g.fetch_zoom(15.0 + (i as f64) * 1e-9);- }- assert_eq!(g.fetch_zoom(15.0), 15.0);- }-- #[test]- fn crossing_a_level_fetches_it_mid_gesture() {- // Zoom-in through z15: the freeze holds within z14, then advances to the- // entered level so its wave starts mid-pinch instead of at release.- let mut g = GestureDebounce::new();- g.set_active(true, 14.0);- assert_eq!(g.fetch_zoom(14.5), 14.0);- assert_eq!(g.fetch_zoom(14.9), 14.0);- assert!(g.is_frozen());- assert_eq!(g.fetch_zoom(15.1), 15.1);- // Within the entered level the freeze holds again at the advanced zoom.- assert_eq!(g.fetch_zoom(15.6), 15.1);- assert!(g.is_frozen());- // Release still fetches the settled zoom on the very next frame.- g.set_active(false, 15.6);- assert_eq!(g.fetch_zoom(15.6), 15.6);- assert!(!g.is_frozen());- }-- #[test]- fn zoom_out_crossing_advances_too() {- // Zoom-out 15 -> 14: the ancestor level starts fetching at the crossing,- // which is what the zoom-out upload burst then drains.- let mut g = GestureDebounce::new();- g.set_active(true, 15.5);- assert_eq!(g.fetch_zoom(15.2), 15.5);- assert_eq!(g.fetch_zoom(14.8), 14.8);- assert!(g.is_frozen());- g.set_active(false, 14.2);- assert_eq!(g.fetch_zoom(14.2), 14.2);- assert!(!g.is_frozen());- }-- #[test]- fn multi_level_pinch_advances_one_level_at_a_time() {- // A fast 14 -> 16 pinch issues one wanted-set change per crossed level —- // the same crossings an unfrozen fetch would issue — never per-frame churn.- let mut g = GestureDebounce::new();- g.set_active(true, 14.0);- assert_eq!(g.fetch_zoom(15.2), 15.2);- assert_eq!(g.fetch_zoom(15.9), 15.2);- assert_eq!(g.fetch_zoom(16.1), 16.1);- assert!(g.is_frozen());- }-- #[test]- fn oscillation_re_freezes_but_stays_live() {- // Hovering on a boundary re-freezes on each crossing, but the returned- // zoom is always the live level — selection never lags the finger by more- // than the in-level hold, which changes no key.- let mut g = GestureDebounce::new();- g.set_active(true, 14.0);- assert_eq!(g.fetch_zoom(15.1), 15.1);- assert_eq!(g.fetch_zoom(14.9), 14.9);- assert_eq!(g.fetch_zoom(15.1), 15.1);- }-}
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 04ed5ff2c9..238b2e2fb5 100644--- a/library/map/src/main/rust/src/bridge/handle.rs+++ b/library/map/src/main/rust/src/bridge/handle.rs@@ -2,7 +2,6 @@ //! //! Pure move out of `bridge.rs`; no logic changes. 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@@ -211,9 +210,6 @@ pub(crate) struct MapHandle { /// frame; `None` after a Moon frame, so returning from the Moon always takes the /// burst path once rather than comparing against a stale Earth zoom. pub(crate) last_zoom: Option<f64>,- /// Gesture-debounce fetch state: while a gesture is active the fetch zoom freezes- /// (see `GestureDebounce`), so a pinch does not churn the wanted set every frame.- pub(crate) gesture: GestureDebounce, } impl MapHandle {@@ -245,16 +241,6 @@ impl MapHandle { pub(crate) fn forget_zoom(&mut self) { self.last_zoom = None; }-- /// The host's gesture signal: `true` while a finger is down or a fling runs.- ///- /// Freezes the *fetch* zoom at the current level until release (see- /// [`GestureDebounce`]); rendering keeps tracking the live camera. Cheap and- /// idempotent — the Kotlin gesture channel drives this, and a redundant set is a- /// comparison, not a fetch.- pub(crate) fn set_gesture_active(&mut self, active: bool, zoom: f64) {- self.gesture.set_active(active, zoom);- } } /// Shared so Kotlin's connectivity callback can reach the reader on the worker thread.
library/map/src/main/rust/src/bridge/lifecycle.rs
diff --git a/library/map/src/main/rust/src/bridge/lifecycle.rs b/library/map/src/main/rust/src/bridge/lifecycle.rsindex e7878ce46f..28f921d88e 100644--- a/library/map/src/main/rust/src/bridge/lifecycle.rs+++ b/library/map/src/main/rust/src/bridge/lifecycle.rs@@ -4,7 +4,6 @@ use super::handle::{ handle_mut, AbsentSet, MapHandle, OnlineFlag, RetryMap, TileResult, ZoomRange, WORKER_COUNT, };-use super::gesture::GestureDebounce; use super::log::log; use super::workers::spawn_worker; use crate::style::{self, LayerToggles, Palette, SharedToggles};@@ -13,7 +12,7 @@ use crate::tile::source::BASEMAP_ARCHIVE_URL; use crate::vulkan::context::{ANativeWindow_acquire, ANativeWindow_fromSurface}; use crate::vulkan::renderer::Renderer; use jni::objects::{JClass, JObject, JString};-use jni::sys::{jfloat, jint, jlong};+use jni::sys::{jint, jlong}; use jni::EnvUnowned; use std::collections::HashSet; use std::os::raw::c_void;@@ -156,7 +155,6 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_create<'l>( density: 1.0, last_zoom: None, absent_build_id: 0,- gesture: GestureDebounce::new(), }); Box::into_raw(handle) as jlong }@@ -249,26 +247,6 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setOnline<'l>( } } -/// The host's gesture signal: `true` while a finger is down or a fling runs.-///-/// Feeds [`GestureDebounce`](super::handle::GestureDebounce): while active the fetch zoom-/// freezes at the passed level, so a pinch does not churn the wanted set every frame.-/// Driven from the existing gesture channel (`MapGestures` → `VulkanMapSurface`), which-/// already invalidates the frame loop on gesture motion — this only steers *fetch*, never-/// frames, so a missing or late signal degrades to today's behaviour, never to a freeze.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setGestureActive<'l>(- _env: EnvUnowned<'l>,- _class: JClass<'l>,- handle: jlong,- active: bool,- zoom: jfloat,-) {- if let Some(map) = handle_mut(handle) {- map.set_gesture_active(active, zoom as f64);- }-}- /// Destroy the renderer and release its window. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_destroy<'l>(
library/map/src/main/rust/src/bridge/mod.rs
diff --git a/library/map/src/main/rust/src/bridge/mod.rs b/library/map/src/main/rust/src/bridge/mod.rsindex 2fa241ce47..62d4eaac28 100644--- a/library/map/src/main/rust/src/bridge/mod.rs+++ b/library/map/src/main/rust/src/bridge/mod.rs@@ -17,7 +17,6 @@ //! //! Split by domain; each module header names what it holds. mod frame;-mod gesture; mod handle; mod layers; mod lifecycle;
library/map/src/main/rust/src/timing.rs
diff --git a/library/map/src/main/rust/src/timing.rs b/library/map/src/main/rust/src/timing.rsindex c220891aaf..a4495dd559 100644--- a/library/map/src/main/rust/src/timing.rs+++ b/library/map/src/main/rust/src/timing.rs@@ -83,7 +83,7 @@ pub(crate) enum Step { /// working, not a gap in the report. PipelineBinds, /// Wanted-set keys dropped without fetching: drain-and-replace queue- /// discards plus gesture-debounce holds (see `bridge::frame`).+ /// discards (see `bridge::frame`). FetchCancelled, /// Fresh `vkAllocateMemory` calls the upload drain issued this frame: the /// proof the pooled staging path (see `upload_pool`) is working. Reads zero
library/map/src/test/java/com/vayunmathur/library/map/GestureFreezeTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/GestureFreezeTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/GestureFreezeTest.ktdeleted file mode 100644index a52f8384c3..0000000000--- a/library/map/src/test/java/com/vayunmathur/library/map/GestureFreezeTest.kt+++ /dev/null@@ -1,98 +0,0 @@-package com.vayunmathur.library.map--import android.app.Application-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertTrue--/**- * The gesture-freeze release contract.- *- * While a pinch drives the zoom, the Rust side freezes tile fetching at the session's- * start zoom; the freeze must release the instant the finger lifts so the settled zoom- * fetches without waiting out the quiet timeout. Two producers can end a session — the- * touch-end observer and the quiet-timeout loop — so a single [GestureFreeze] owns the- * engaged flag and both end signals funnel through it. That sharing is what these tests- * pin:- *- * - an unengaged release wakes nothing (a tap that never moved the camera owes no frame);- * - mark-then-release wakes exactly once, and a second release is a silent no-op- * (the observer and the timeout both firing must not double-release);- * - engaging freezes once no matter how many frames mark it, and the next session- * re-arms cleanly (no desync where a later gesture runs unfrozen or a dead one sticks).- *- * Runs on plain JVM unit tests with no Robolectric, like [FrameLoopWakeTest]: with no- * surface attached (`handle == 0`) `setGestureActive` is a native no-op and `invalidate`- * only bumps [SurfaceMapRenderer.wakeCount], so the whole contract is observable as- * wake counts. `Application()` is enough of a `Context` for that.- */-class GestureFreezeTest {-- private fun freezeOn(renderer: SurfaceMapRenderer) = GestureFreeze(renderer)-- private fun renderer() = SurfaceMapRenderer(Application(), density = 3f)-- /** An unengaged release wakes nothing: taps that never froze owe no frame. */- @Test- fun release_without_engage_wakes_nothing() {- val r = renderer()- val before = r.wakeCount- freezeOn(r).release()- assertEquals(before, r.wakeCount, "release without markActive must not wake the loop")- }-- /** Engaging freezes without waking: the gesture frames themselves already wake. */- @Test- fun mark_active_wakes_nothing() {- val r = renderer()- val before = r.wakeCount- freezeOn(r).markActive(12f)- assertEquals(before, r.wakeCount, "markActive must not wake the loop")- }-- /** Mark-then-release wakes exactly once, and the repeat release is silent. */- @Test- fun mark_then_release_wakes_exactly_once() {- val r = renderer()- val freeze = freezeOn(r)- freeze.markActive(12f)- val before = r.wakeCount- freeze.release()- assertEquals(before + 1, r.wakeCount, "release must wake the loop exactly once")- freeze.release()- assertEquals(before + 1, r.wakeCount, "the second end signal must be a silent no-op")- }-- /** Repeated marks freeze once, and the next session re-arms cleanly. */- @Test- fun sessions_rearm_cleanly() {- val r = renderer()- val freeze = freezeOn(r)- // Every gesture frame marks; only the rising edge may engage.- freeze.markActive(12f)- freeze.markActive(12.5f)- val before = r.wakeCount- freeze.release()- assertEquals(before + 1, r.wakeCount, "one session releases exactly one wake")- // The next gesture is a new session, not a desync: it freezes and releases again.- freeze.markActive(13f)- freeze.release()- assertEquals(before + 2, r.wakeCount, "the next session must re-arm and release again")- }-- /** The animation gate starts clear: a fresh camera reports no animation running. */- @Test- fun animation_gate_starts_clear() {- assertFalse(CameraState().animationActive, "no animation is running on a fresh camera")- }-- /** The end rendezvous starts null: hosts without a surface keep the old behavior. */- @Test- fun end_rendezvous_starts_null() {- assertTrue(- CameraState().gestureEndHandler == null,- "no end signal fires until a surface registers",- )- }-}
library/map/src/test/java/com/vayunmathur/library/map/RendererStateTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/RendererStateTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/RendererStateTest.ktindex deae1fcecb..66826f3593 100644--- a/library/map/src/test/java/com/vayunmathur/library/map/RendererStateTest.kt+++ b/library/map/src/test/java/com/vayunmathur/library/map/RendererStateTest.kt@@ -29,7 +29,6 @@ class RendererStateTest { r.setPalette(dark = true, muted = true) r.setLayers(LayerOptions(poi = true, transit = true)) r.setOnline(false)- r.setGestureActive(true, 1.5f) r.setUserPuck(UserPuck(GeoPoint(1.0, 2.0), bearing = 45f)) r.setMarkers(listOf(MapMarker(1L, GeoPoint(0.0, 0.0), MarkerIcon.SEARCH))) r.setVehicles(listOf(MapMarker(2L, GeoPoint(1.0, 1.0), MarkerIcon.VEHICLE_BUS)))