Modern Apps git

← Modern-Apps.git

voxels: swipe-to-look by default, with a setting to keep the stick (#ux-audit)

Commit
6a294f663f36cd9b34d3f3e20568ecf4617d58fd
Author
Vayun Mathur <[email protected]>
When
2026-11-13 01:41 UTC (23 days ago)
Parents
baa7240
Symptom: looking around used a floating rate stick: the camera kept
turning for as long as the thumb rested off-centre, so small aim
corrections overshot and stopping meant lifting the finger. A second
finger also couldn't place or break while the first was looking.

Root cause: ui/Joystick.kt's FloatingLookJoystick only reported a
normalized displacement as an angular *rate*, and its tap detector was
one screen-wide gesture, so any second touch was swallowed by the
running drag.

Fix:
- Swipe-to-look is the new default: the look pointer reports pixel
  deltas; MainActivity converts them to radians (a full view-width
  swipe = 180 degrees, finger direction = camera direction, invert Y
  honoured) and sends them through a new native onLookDelta. The
  engine accumulates them per frame in input.rs (consumed exactly
  once per frame, NaN-safe) and applies them scaled by the look
  sensitivity setting.
- Settings gets "Look with a stick instead of swiping"
  (GameSettings.stickLook, off by default) for players who prefer the
  old rate stick, which still works as before.
- Per-pointer handling: the world layer already tracks every finger
  separately since the hold-to-mine change (domain/WorldTouchTracker),
  so a second finger taps/holds while the first looks; this change
  makes that the default experience with swipe-look.
- Rust tests that drive the shared input/engine statics are
  serialised with one test lock to stay deterministic.

User-visible effect: the camera follows your thumb and stops when it
stops; you can look and build at the same time.

Verification: new Rust test swipe_look_deltas_are_consumed_once;
GameSettingsTest covers the default and persistence of stickLook;
WorldTouchTrackerTest already covers look deltas and second-finger
taps.

Diff

games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex 1a6e82b06f..d12977e189 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -98,6 +98,7 @@ import com.vayunmathur.library.util.GameHubComposeHook import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch+import kotlin.math.PI  class MainActivity : ComponentActivity() {     // Pause-menu state lives on the activity so onStop can pause the game: coming back from Home or@@ -369,14 +370,25 @@ class MainActivity : ComponentActivity() {                         }                     } -                    // Fullscreen world interaction + floating look: drag on the right half looks around;-                    // tap places a block, hold mines/attacks (repeating) — on either half of the screen.+                    // Fullscreen world interaction: a drag that starts on the right half looks around+                    // (swipe by default, or the floating stick); tap places a block, hold mines/attacks+                    // (repeating) — on either half of the screen, with any finger, even while looking.                     if (VoxelsNative.isAvailable) {                         FloatingLookJoystick(                             modifier = Modifier.fillMaxSize().onSizeChanged { worldSize = it },                             onLookRate = { ry, rp ->                                 if (!paused) try { VoxelsNative.onLookInput(ry, if (settings.invertY) -rp else rp) } catch (_: Exception) {}                             },+                            // Swipe-look: the camera follows the finger; a swipe across the whole+                            // view width turns 180 degrees (before the sensitivity setting).+                            swipeLook = !settings.stickLook,+                            onLookDelta = { dx, dy ->+                                val w = worldSize.width.coerceAtLeast(1).toFloat()+                                val k = PI.toFloat() / w+                                if (!paused) try {+                                    VoxelsNative.onLookDelta(-dx * k, (if (settings.invertY) -dy else dy) * k)+                                } catch (_: Exception) {}+                            },                             onPlace = { off -> if (!paused) try {                                 val code = VoxelsNative.placeBlockAt(off.x, off.y)                                 when (code) {
games/voxels/src/main/java/com/vayunmathur/games/voxels/data/GameSettings.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/GameSettings.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/GameSettings.ktindex a72aa385bf..a9a8a1c54a 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/GameSettings.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/data/GameSettings.kt@@ -1,6 +1,7 @@ package com.vayunmathur.games.voxels.data  import android.content.Context+import androidx.core.content.edit  /** Player preferences from the in-game settings sheet. */ data class GameSettings(@@ -16,6 +17,8 @@ data class GameSettings(     val hudScale: Float = 1f,     /** Show the engine's debug readout (fps, position, chunk counts). Off by default. */     val showDebug: Boolean = false,+    /** Look with the old floating rate stick instead of swiping (swipe-to-look is the default). */+    val stickLook: Boolean = false, ) {     /** Bounds for the sliders. */     companion object {@@ -53,19 +56,21 @@ object GameSettingsStore {             sfxVolume = p.getFloat("sfx_volume", d.sfxVolume),             hudScale = p.getFloat("hud_scale", d.hudScale),             showDebug = p.getBoolean("show_debug", d.showDebug),+            stickLook = p.getBoolean("stick_look", d.stickLook),         ).sanitized()     }      /** Saves [s] (asynchronously). */     fun save(ctx: Context, s: GameSettings) {         val v = s.sanitized()-        ctx.getSharedPreferences(FILE, Context.MODE_PRIVATE).edit()-            .putFloat("look_sensitivity", v.lookSensitivity)-            .putBoolean("invert_y", v.invertY)-            .putFloat("music_volume", v.musicVolume)-            .putFloat("sfx_volume", v.sfxVolume)-            .putFloat("hud_scale", v.hudScale)-            .putBoolean("show_debug", v.showDebug)-            .apply()+        ctx.getSharedPreferences(FILE, Context.MODE_PRIVATE).edit {+            putFloat("look_sensitivity", v.lookSensitivity)+            putBoolean("invert_y", v.invertY)+            putFloat("music_volume", v.musicVolume)+            putFloat("sfx_volume", v.sfxVolume)+            putFloat("hud_scale", v.hudScale)+            putBoolean("show_debug", v.showDebug)+            putBoolean("stick_look", v.stickLook)+        }     } }
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.ktindex dd5f171953..d0a0536e9d 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt@@ -36,6 +36,8 @@ object VoxelsNative {     external fun nativeSetCreative(creative: Boolean)     external fun onMoveInput(moveX: Float, moveY: Float)     external fun onLookInput(lookYawRate: Float, lookPitchRate: Float)+    // Swipe-look: rotation in radians since the last call (scaled by the look sensitivity natively).+    external fun onLookDelta(dyaw: Float, dpitch: Float)     // Camera turn-speed multiplier from the settings sheet (0.25..3).     external fun setLookSensitivity(sensitivity: Float)     external fun setJump(held: Boolean)
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FloatingLookJoystick.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FloatingLookJoystick.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FloatingLookJoystick.ktindex ce9752e6b5..e50c6e8495 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FloatingLookJoystick.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/FloatingLookJoystick.kt@@ -44,8 +44,14 @@ fun FloatingLookJoystick(     onLookRate: (Float, Float) -> Unit,     onPlace: (Offset) -> Unit,     onBreak: (Offset) -> Unit,+    // Swipe-to-look (default): the camera follows the finger, reported as pixel deltas. Off: the+    // classic floating rate stick that keeps turning while held off-centre.+    swipeLook: Boolean = true,+    onLookDelta: (dx: Float, dy: Float) -> Unit = { _, _ -> }, ) {     val look by rememberUpdatedState(onLookRate)+    val lookDelta by rememberUpdatedState(onLookDelta)+    val swipe by rememberUpdatedState(swipeLook)     val place by rememberUpdatedState(onPlace)     val act by rememberUpdatedState(onBreak)     var origin by remember { mutableStateOf(Offset.Zero) }@@ -63,8 +69,10 @@ fun FloatingLookJoystick(                     is WorldTouch.Tap -> place(Offset(e.x, e.y))                     is WorldTouch.Act -> act(Offset(e.x, e.y))                     WorldTouch.ActEnd -> hold = null-                    is WorldTouch.LookStart -> { origin = Offset(e.x, e.y); knob = Offset.Zero; active = true; look(0f, 0f) }-                    is WorldTouch.LookMove -> {+                    is WorldTouch.LookStart -> {+                        origin = Offset(e.x, e.y); knob = Offset.Zero; active = !swipe; look(0f, 0f)+                    }+                    is WorldTouch.LookMove -> if (swipe) lookDelta(e.dx, e.dy) else {                         val nk = Offset(e.x, e.y) - origin                         val dist = hypot(nk.x, nk.y)                         knob = if (dist > maxR && dist > 0.001f) nk * (maxR / dist) else nk
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/SettingsSheet.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/SettingsSheet.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/SettingsSheet.ktindex 1977dabc08..5d1e5723f4 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/SettingsSheet.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/SettingsSheet.kt@@ -53,6 +53,7 @@ fun SettingsSheet(settings: GameSettings, onChange: (GameSettings) -> Unit, onCl             SliderRow(stringResource(R.string.settings_look_sensitivity), settings.lookSensitivity,                 GameSettings.MIN_SENSITIVITY..GameSettings.MAX_SENSITIVITY) { onChange(settings.copy(lookSensitivity = it)) }             SwitchRow(stringResource(R.string.settings_invert_y), settings.invertY) { onChange(settings.copy(invertY = it)) }+            SwitchRow(stringResource(R.string.settings_stick_look), settings.stickLook) { onChange(settings.copy(stickLook = it)) }             SliderRow(stringResource(R.string.settings_music_volume), settings.musicVolume, 0f..1f) { onChange(settings.copy(musicVolume = it)) }             SliderRow(stringResource(R.string.settings_sfx_volume), settings.sfxVolume, 0f..1f) { onChange(settings.copy(sfxVolume = it)) }             SliderRow(stringResource(R.string.settings_hud_scale), settings.hudScale,
games/voxels/src/main/res/values/strings.xml
diff --git a/games/voxels/src/main/res/values/strings.xml b/games/voxels/src/main/res/values/strings.xmlindex 94d9dfb54c..12e99ea727 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -122,6 +122,7 @@     <string name="settings">Settings</string>     <string name="settings_look_sensitivity">Look sensitivity</string>     <string name="settings_invert_y">Invert look up/down</string>+    <string name="settings_stick_look">Look with a stick instead of swiping</string>     <string name="settings_music_volume">Music volume</string>     <string name="settings_sfx_volume">Sound effects volume</string>     <string name="settings_hud_scale">Controls size</string>
games/voxels/src/main/rust/src/engine_lifecycle.rs
diff --git a/games/voxels/src/main/rust/src/engine_lifecycle.rs b/games/voxels/src/main/rust/src/engine_lifecycle.rsindex 0fbfcfedec..3b7fe53116 100644--- a/games/voxels/src/main/rust/src/engine_lifecycle.rs+++ b/games/voxels/src/main/rust/src/engine_lifecycle.rs@@ -276,6 +276,6 @@ mod lifecycle_tests {     }) } } -/// Serialises tests that touch the global engine / load-phase statics.+/// Serialises tests that touch global statics (engine, load phase, the shared input state). #[cfg(test)]-static GLOBAL_ENGINE_TEST: Mutex<()> = Mutex::new(());+pub(crate) static GLOBAL_ENGINE_TEST: Mutex<()> = Mutex::new(());
games/voxels/src/main/rust/src/engine_part1.rs
diff --git a/games/voxels/src/main/rust/src/engine_part1.rs b/games/voxels/src/main/rust/src/engine_part1.rsindex e85d517ff2..faa4166a42 100644--- a/games/voxels/src/main/rust/src/engine_part1.rs+++ b/games/voxels/src/main/rust/src/engine_part1.rs@@ -59,6 +59,9 @@ fn simulate(state: &mut EngineState, dt: f32) {         let look_speed = 3.2 * crate::input::look_sensitivity();         state.player.yaw += input.look_yaw_rate * look_speed * dt;         state.player.pitch += input.look_pitch_rate * look_speed * dt;+        // Swipe-look: the drag since last frame, applied directly (sensitivity scales it too).+        state.player.yaw += input.look_dyaw * crate::input::look_sensitivity();+        state.player.pitch += input.look_dpitch * crate::input::look_sensitivity();         state.player.pitch = state.player.pitch.clamp(-1.55, 1.55);          let mut input_mut = input;
games/voxels/src/main/rust/src/engine_part6.rs
diff --git a/games/voxels/src/main/rust/src/engine_part6.rs b/games/voxels/src/main/rust/src/engine_part6.rsindex a9558158b5..f5798298ab 100644--- a/games/voxels/src/main/rust/src/engine_part6.rs+++ b/games/voxels/src/main/rust/src/engine_part6.rs@@ -75,6 +75,7 @@ mod state_tests {     // while unpausing resumes exactly where it left off.     #[test]     fn a_paused_world_does_not_simulate() { big_stack(|| {+        let _serial = GLOBAL_ENGINE_TEST.lock();         let mut s = small_state("paused");         s.player.flying = false;         s.player.pos = vec3(0.5, 120.0, 0.5);@@ -92,6 +93,7 @@ mod state_tests {     // and the clock persists through a save.     #[test]     fn the_world_clock_only_advances_with_simulation() { big_stack(|| {+        let _serial = GLOBAL_ENGINE_TEST.lock();         let mut s = small_state("clock");         let t0 = s.world_secs;         for _ in 0..20 { step(&mut s, 0.05, true); }
games/voxels/src/main/rust/src/input.rs
diff --git a/games/voxels/src/main/rust/src/input.rs b/games/voxels/src/main/rust/src/input.rsindex e3afdf7df5..449aa8a80d 100644--- a/games/voxels/src/main/rust/src/input.rs+++ b/games/voxels/src/main/rust/src/input.rs@@ -9,11 +9,18 @@ pub struct InputState {     pub sneak: bool,     // walking sneak mode (toggle); disables jumping and prevents walking off edges     pub sprint: bool,     pub toggle_fly: bool, // edge-triggered+    // Swipe-look: radians of yaw/pitch accumulated from drags since the last frame (consumed per frame).+    pub look_dyaw: f32, pub look_dpitch: f32, } static INPUT: OnceLock<Mutex<InputState>> = OnceLock::new(); fn mutex() -> &'static Mutex<InputState> { INPUT.get_or_init(|| Mutex::new(InputState::default())) } pub fn set_move(x: f32, y: f32) { if let Ok(mut g)=mutex().lock() { g.move_right=x.clamp(-1.0,1.0); g.move_forward=y.clamp(-1.0,1.0); } } pub fn set_look_rate(rx: f32, ry: f32) { if let Ok(mut g)=mutex().lock() { g.look_yaw_rate=rx.clamp(-1.0,1.0); g.look_pitch_rate=ry.clamp(-1.0,1.0); } }+/// Swipe-look: add a drag's worth of rotation (radians, before sensitivity) for the next frame.+pub fn add_look_delta(dyaw: f32, dpitch: f32) {+    if !dyaw.is_finite() || !dpitch.is_finite() { return; }+    if let Ok(mut g)=mutex().lock() { g.look_dyaw += dyaw; g.look_dpitch += dpitch; }+} pub fn set_jump(held: bool) { if let Ok(mut g)=mutex().lock() { g.jump_held=held; } } pub fn set_down(held: bool) { if let Ok(mut g)=mutex().lock() { g.down_held=held; } } pub fn set_sneak(on: bool) { if let Ok(mut g)=mutex().lock() { g.sneak=on; } }@@ -21,14 +28,14 @@ pub fn set_sneak(on: bool) { if let Ok(mut g)=mutex().lock() { g.sneak=on; } } pub fn release_all() {     if let Ok(mut g)=mutex().lock() {         g.move_forward=0.0; g.move_right=0.0; g.look_yaw_rate=0.0; g.look_pitch_rate=0.0;-        g.jump_held=false; g.down_held=false; g.toggle_fly=false;+        g.jump_held=false; g.down_held=false; g.toggle_fly=false; g.look_dyaw=0.0; g.look_dpitch=0.0;     } } pub fn request_toggle_fly() { if let Ok(mut g)=mutex().lock() { g.toggle_fly=true; } } pub fn snapshot_and_clear_look() -> InputState {-    // Held/persistent values (move, look, jump, down, sneak) stay set until the UI reports a change;-    // only the edge-triggered fly toggle is consumed here.-    if let Ok(mut g)=mutex().lock() { let c=*g; g.toggle_fly=false; return c; }+    // Held/persistent values (move, look rate, jump, down, sneak) stay set until the UI reports a+    // change; the edge-triggered fly toggle and the accumulated swipe-look deltas are consumed here.+    if let Ok(mut g)=mutex().lock() { let c=*g; g.toggle_fly=false; g.look_dyaw=0.0; g.look_dpitch=0.0; return c; }     InputState::default() } // Camera turn-speed multiplier from the settings sheet (f32 bits; 1.0 by default).@@ -45,10 +52,25 @@ pub fn look_sensitivity() -> f32 { f32::from_bits(LOOK_SENS.load(Ordering::Relax mod tests {     #[test]     fn look_sensitivity_defaults_to_one_and_clamps() {+        let _serial = crate::engine::GLOBAL_ENGINE_TEST.lock();         assert!((super::look_sensitivity() - 1.0).abs() < 1e-6 || (0.25..=3.0).contains(&super::look_sensitivity()));         super::set_look_sensitivity(10.0);         assert!((super::look_sensitivity() - 3.0).abs() < 1e-6);         super::set_look_sensitivity(f32::NAN);         assert!((super::look_sensitivity() - 1.0).abs() < 1e-6);     }++    // Swipe deltas accumulate between frames and are consumed exactly once.+    #[test]+    fn swipe_look_deltas_are_consumed_once() {+        let _serial = crate::engine::GLOBAL_ENGINE_TEST.lock();+        let _ = super::snapshot_and_clear_look();+        super::add_look_delta(0.1, -0.05);+        super::add_look_delta(0.2, 0.0);+        super::add_look_delta(f32::NAN, 1.0);+        let a = super::snapshot_and_clear_look();+        assert!((a.look_dyaw - 0.3).abs() < 1e-5 && (a.look_dpitch + 0.05).abs() < 1e-5);+        let b = super::snapshot_and_clear_look();+        assert_eq!((b.look_dyaw, b.look_dpitch), (0.0, 0.0));+    } }
games/voxels/src/main/rust/src/lib_jni_input.rs
diff --git a/games/voxels/src/main/rust/src/lib_jni_input.rs b/games/voxels/src/main/rust/src/lib_jni_input.rsindex 610b8eb888..d1f56dc0bf 100644--- a/games/voxels/src/main/rust/src/lib_jni_input.rs+++ b/games/voxels/src/main/rust/src/lib_jni_input.rs@@ -94,3 +94,14 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_setLo ) {     input::set_look_sensitivity(sensitivity); }++/// JNI bridge for `VoxelsNative#onLookDelta`: swipe-look rotation in radians since the last call.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_onLookDelta<'l>(+    _env: EnvUnowned<'l>,+    _class: JClass<'l>,+    dyaw: jfloat,+    dpitch: jfloat,+) {+    input::add_look_delta(dyaw, dpitch);+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/data/GameSettingsTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/data/GameSettingsTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/data/GameSettingsTest.ktindex 134d9a8878..95577c320b 100644--- a/games/voxels/src/test/java/com/vayunmathur/games/voxels/data/GameSettingsTest.kt+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/data/GameSettingsTest.kt@@ -19,13 +19,14 @@ class GameSettingsTest {     @get:Rule val rule = createComposeRule()     private val ctx get() = ApplicationProvider.getApplicationContext<Context>() -    @Test fun `the debug readout is off by default`() {+    @Test fun `the debug readout is off and swipe-look is on by default`() {         assertFalse(GameSettings().showDebug)+        assertFalse(GameSettings().stickLook)         assertFalse(GameSettingsStore.load(ctx).showDebug)     }      @Test fun `settings round-trip and are clamped`() {-        val s = GameSettings(lookSensitivity = 2f, invertY = true, musicVolume = 0.3f, sfxVolume = 0.6f, hudScale = 1.25f, showDebug = true)+        val s = GameSettings(lookSensitivity = 2f, invertY = true, musicVolume = 0.3f, sfxVolume = 0.6f, hudScale = 1.25f, showDebug = true, stickLook = true)         GameSettingsStore.save(ctx, s)         assertEquals(s, GameSettingsStore.load(ctx))         GameSettingsStore.save(ctx, GameSettings(lookSensitivity = 99f, hudScale = 0f, musicVolume = -1f))