From 8b1d60b40906ec66e9dd9d1d73eea61401acd229 Mon Sep 17 00:00:00 2001 From: David Cristofaro Date: Sat, 3 Oct 2026 15:05:48 +1000 Subject: [PATCH 1/4] Add native and browser gamepad controls including stickless pads Use analog sticks for movement/look and D-pad/bumpers for stickless play. Bind jump, hold/toggle crouch and automap; Y swaps D-pad and bumper roles. Queue action edges once, cap diagonal speed and clear held input on interruption. Support platform mappings natively and standard plus eight-button SNES profiles on web. Co-authored-by: Xeno --- .github/workflows/ci-cd.yml | 9 +- Cargo.lock | 116 +++++++++++ Cargo.toml | 5 + DESIGN.md | 6 + README.md | 10 + TODO.md | 2 + src/bin/sector/controller.rs | 373 +++++++++++++++++++++++++++++++++++ src/bin/sector/main.rs | 33 +++- src/game/player.rs | 36 ++-- tests/gamepad.test.mjs | 68 +++++++ wasm/gamepad.mjs | 54 +++++ wasm/index.js | 2 + 12 files changed, 684 insertions(+), 30 deletions(-) create mode 100644 src/bin/sector/controller.rs create mode 100644 tests/gamepad.test.mjs create mode 100644 wasm/gamepad.mjs diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 824f009..6b54fe4 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -13,6 +13,11 @@ jobs: - name: Checkout uses: actions/checkout@v4 + - name: Install native gamepad dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libudev-dev + - name: Setup Rust run: | rustup toolchain install stable --profile minimal @@ -36,8 +41,8 @@ jobs: - name: Install wasm-bindgen run: cargo install wasm-bindgen-cli --version 0.2.127 --locked - - name: Test touch gestures - run: node --test tests/touch.test.mjs + - name: Test browser controls + run: node --test tests/touch.test.mjs tests/gamepad.test.mjs - name: Check formatting run: cargo fmt --all --check diff --git a/Cargo.lock b/Cargo.lock index 3531649..bd21e95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1053,6 +1053,22 @@ dependencies = [ "encase_derive_impl", ] +[[package]] +name = "bevy_gilrs" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8215d166d5c4a9f821713a1a549a57c5f8bdf404745c84f7a8b920b7b7d92b2" +dependencies = [ + "bevy_app", + "bevy_ecs", + "bevy_input", + "bevy_platform", + "bevy_time", + "gilrs", + "thiserror 2.0.18", + "tracing", +] + [[package]] name = "bevy_gizmos" version = "0.19.1" @@ -2865,6 +2881,12 @@ dependencies = [ "spin 0.9.8", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.1.5" @@ -3214,6 +3236,40 @@ dependencies = [ "weezl", ] +[[package]] +name = "gilrs" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fa85c2e35dc565c90511917897ea4eae16b77f2773d5223536f7b602536d462" +dependencies = [ + "fnv", + "gilrs-core", + "log", + "uuid", + "vec_map", +] + +[[package]] +name = "gilrs-core" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d23f2cc5144060a7f8d9e02d3fce5d06705376568256a509cdbc3c24d47e4f04" +dependencies = [ + "inotify", + "js-sys", + "libc", + "libudev-sys", + "log", + "nix 0.30.1", + "objc2-core-foundation", + "objc2-io-kit", + "uuid", + "vec_map", + "wasm-bindgen", + "web-sys", + "windows", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -3712,6 +3768,26 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.11.0", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + [[package]] name = "integer-encoding" version = "3.0.4" @@ -3974,6 +4050,16 @@ dependencies = [ "redox_syscall 0.7.4", ] +[[package]] +name = "libudev-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -4250,6 +4336,18 @@ dependencies = [ "memoffset 0.6.5", ] +[[package]] +name = "nix" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6" +dependencies = [ + "bitflags 2.11.0", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nix" version = "0.31.2" @@ -4528,6 +4626,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "bitflags 2.11.0", + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-link-presentation" version = "0.2.2" @@ -5651,6 +5760,7 @@ version = "0.1.0" dependencies = [ "bevy", "bevy_egui", + "bevy_gilrs", "bevy_pixels", "console_error_panic_hook", "earcutr 0.5.0", @@ -6458,6 +6568,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + [[package]] name = "vello_common" version = "0.0.6" diff --git a/Cargo.toml b/Cargo.toml index 48ad08b..c32ab3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,9 @@ bevy_egui = { version = "0.40", optional = true } egui_plot = { version = "0.35", optional = true } rfd = { version = "0.15", optional = true } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +bevy_gilrs = { version = "0.19", optional = true } + [target.'cfg(target_arch = "wasm32")'.dependencies] console_error_panic_hook = "0.1" wasm-bindgen = "=0.2.127" @@ -47,6 +50,8 @@ protoc-bin-vendored = "3.2.0" [features] sector = [ + "bevy/gamepad", + "dep:bevy_gilrs", "bevy/bevy_state", "bevy_pixels", "image" diff --git a/DESIGN.md b/DESIGN.md index 2da00e4..da5faf8 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -272,3 +272,9 @@ The working conventions tied to the current design are: `wasm/touch.mjs` tracks at most two pointer contacts with independent movement/look owners, assigned to the left or right half at contact start. Left displacement drives movement with a 16 CSS pixel dead zone. Right movement accumulates horizontal look, scaled to viewport width. Double taps require a short, stationary first tap followed by a nearby contact within 300 ms. Left double-tap holds crouch, right double-tap queues one jump. A stationary two-finger tap within 250 ms queues an automap cycle, including when both fingers start on the same half. Movement, cancellation, or a third finger invalidates that gesture. Pointer capture preserves contact ownership across the center seam. Cancellation, lost capture, resize, blur, and page hiding clear held controls. `src/bin/sector/touch.rs` samples browser state in `PreUpdate`, before fixed simulation. Jump edges stay queued until one fixed tick consumes them. Touch activates simulation without pointer lock and uses the existing player physics. Only keyboard Space taps feed the flight toggle. Native builds use empty touch state. Gesture processing is bounded to two contacts and does no work per rendered pixel. + +## Gamepad input + +`src/bin/sector/controller.rs` consumes a common snapshot from native Bevy gamepad components or the browser Gamepad API bridge in `wasm/gamepad.mjs`. Native builds install Gilrs with its controller mapping database; browser builds poll directly, including a fallback for eight-button, two-axis SNES USB pads. The native backend is excluded from WASM. One active controller owns input; an idle controller can yield to another controller with input. + +Snapshots are sampled after Bevy input processing in `PreUpdate`. The shared state applies a radial 20% movement dead zone and a rescaled turn dead zone. Analog movement adds to keyboard/touch input and caps combined speed, including diagonals. Stick and bumper turning use elapsed time at 2.5 radians per second. Jump and automap edges remain queued until consumed once; only keyboard Space feeds the flight toggle. Y swaps horizontal D-pad and bumper roles without changing stick bindings. Focus loss and disconnect clear held state and crouch toggles while retaining the chosen D-pad layout. Refocusing requires neutral input before accepting held controls again. diff --git a/README.md b/README.md index b37752c..191e3bf 100644 --- a/README.md +++ b/README.md @@ -179,3 +179,13 @@ Touch controls have no buttons. On the left half, drag up/down to walk forward/b A short hint appears on touch devices and disappears after your first interaction. Turning the phone or leaving the page clears held gestures. Desktop keyboard and mouse controls remain available. Run the fast gesture regression tests with `node --test tests/touch.test.mjs`. + +### Gamepad controls + +Native and browser play support gamepads without mouse capture. Press a controller button or move a stick to start. Left stick walks and strafes with analog speed; right stick turns horizontally. A jumps, B holds crouch, left-stick click toggles crouch, and Select cycles the automap. Jump never toggles flight. + +Stickless controllers use D-pad up/down to walk, left/right to strafe, and L/R bumpers to turn. Press Y to swap the horizontal bindings: D-pad left/right turns and bumpers strafe. Up/down and the sticks keep their original roles. Y toggles once per press and the selected layout lasts until Y is pressed again or the runtime restarts. + +Native input uses platform controller mappings. Browsers support standard-mapped controllers and a common unmapped eight-button USB SNES profile: Y, B, A, X, L, R, Select, Start at button indices 0 through 7, with D-pad axes 0 and 1. USB adapters with other raw layouts need a matching profile. Release controls after returning from another window; focus loss and disconnect clear held movement, crouch and queued actions. + +Run browser input tests with `node --test tests/touch.test.mjs tests/gamepad.test.mjs`. diff --git a/TODO.md b/TODO.md index 1caa724..8c636ff 100644 --- a/TODO.md +++ b/TODO.md @@ -2,6 +2,8 @@ ## Runtime and gameplay +- Test controller feel on physical modern and USB SNES pads; add browser profiles for other unmapped adapters as needed. + - Tune touch sensitivity and gesture thresholds from physical iOS/Android playtesting. - Add interactive doors, lifts, and other moving sector boundaries instead of baking them open into maps. diff --git a/src/bin/sector/controller.rs b/src/bin/sector/controller.rs new file mode 100644 index 0000000..568efeb --- /dev/null +++ b/src/bin/sector/controller.rs @@ -0,0 +1,373 @@ +use bevy::prelude::*; +use bevy::window::PrimaryWindow; +use sector::game::PlayerInput; + +const DEAD_ZONE: f32 = 0.2; +const TURN_SPEED: f32 = 2.5; +const JUMP: u32 = 1; +const CROUCH: u32 = 2; +const SWAP_DPAD: u32 = 4; +const TOGGLE_CROUCH: u32 = 8; +const AUTOMAP: u32 = 16; +const LEFT_BUMPER: u32 = 32; +const RIGHT_BUMPER: u32 = 64; + +#[derive(Default, Clone, Copy)] +struct ControllerSnapshot { + id: u64, + left_stick: Vec2, + right_x: f32, + dpad: Vec2, + buttons: u32, +} + +impl ControllerSnapshot { + fn has_input(self) -> bool { + self.buttons != 0 + || self.left_stick.length() > DEAD_ZONE + || self.right_x.abs() > DEAD_ZONE + || self.dpad != Vec2::ZERO + } + + #[cfg(not(target_arch = "wasm32"))] + fn from_gamepad(entity: Entity, pad: &Gamepad) -> Self { + let button = |button, mask| if pad.pressed(button) { mask } else { 0 }; + Self { + id: entity.to_bits(), + left_stick: pad.left_stick(), + right_x: pad.right_stick().x, + dpad: Vec2::new( + f32::from(pad.pressed(GamepadButton::DPadRight)) + - f32::from(pad.pressed(GamepadButton::DPadLeft)), + f32::from(pad.pressed(GamepadButton::DPadUp)) + - f32::from(pad.pressed(GamepadButton::DPadDown)), + ), + buttons: button(GamepadButton::South, JUMP) + | button(GamepadButton::East, CROUCH) + | button(GamepadButton::North, SWAP_DPAD) + | button(GamepadButton::LeftThumb, TOGGLE_CROUCH) + | button(GamepadButton::Select, AUTOMAP) + | button(GamepadButton::LeftTrigger, LEFT_BUMPER) + | button(GamepadButton::RightTrigger, RIGHT_BUMPER), + } + } +} + +#[derive(Resource, Default)] +pub struct ControllerInput { + pub active: bool, + pub map_pending: bool, + pub dpad_turns: bool, + id: Option, + last_buttons: u32, + movement: Vec2, + turn: f32, + jump_pending: bool, + crouch_toggle: bool, + crouch_held: bool, + jump_held: bool, + waiting_for_neutral: bool, +} + +impl ControllerInput { + fn clear(&mut self) { + let dpad_turns = self.dpad_turns; + *self = Self { + dpad_turns, + ..default() + }; + } + + fn sample(&mut self, snapshot: Option) { + let Some(snapshot) = snapshot else { + self.clear(); + return; + }; + if self.waiting_for_neutral { + if snapshot.has_input() { + return; + } + self.waiting_for_neutral = false; + } + if self.id != Some(snapshot.id) { + self.clear(); + self.id = Some(snapshot.id); + } + let pressed = snapshot.buttons & !self.last_buttons; + self.last_buttons = snapshot.buttons; + self.active |= snapshot.has_input(); + if pressed & SWAP_DPAD != 0 { + self.dpad_turns = !self.dpad_turns; + } + if pressed & TOGGLE_CROUCH != 0 { + self.crouch_toggle = !self.crouch_toggle; + } + self.jump_pending |= pressed & JUMP != 0; + self.map_pending |= pressed & AUTOMAP != 0; + self.crouch_held = snapshot.buttons & CROUCH != 0; + self.jump_held = snapshot.buttons & JUMP != 0; + let bumper = f32::from(snapshot.buttons & RIGHT_BUMPER != 0) + - f32::from(snapshot.buttons & LEFT_BUMPER != 0); + let stick = radial_dead_zone(snapshot.left_stick); + let (strafe, turn) = if self.dpad_turns { + (bumper, snapshot.dpad.x) + } else { + (snapshot.dpad.x, bumper) + }; + self.movement = (stick + Vec2::new(strafe, snapshot.dpad.y)).clamp_length_max(1.0); + self.turn = (axis_dead_zone(snapshot.right_x) + turn).clamp(-1.0, 1.0); + } + + pub fn turn_delta(&self, dt: f32) -> f32 { + self.turn * TURN_SPEED * dt + } + + pub fn merge(&mut self, mut input: PlayerInput) -> PlayerInput { + input.movement_axes += self.movement; + input.jump_pressed |= std::mem::take(&mut self.jump_pending); + input.crouch_pressed |= self.crouch_held || self.crouch_toggle; + input.ascend |= self.jump_held; + input.descend |= self.crouch_held; + input + } +} + +fn axis_dead_zone(axis: f32) -> f32 { + if !axis.is_finite() { + return 0.0; + } + axis.signum() * ((axis.abs().min(1.0) - DEAD_ZONE).max(0.0) / (1.0 - DEAD_ZONE)) +} + +fn radial_dead_zone(stick: Vec2) -> Vec2 { + let length = stick.length(); + if !length.is_finite() || length <= DEAD_ZONE { + return Vec2::ZERO; + } + stick / length * axis_dead_zone(length) +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen::prelude::wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = window, js_name = sectorGamepadPoll)] + fn poll_gamepad() -> u32; + #[wasm_bindgen(js_namespace = window, js_name = sectorGamepadId)] + fn gamepad_id() -> u32; + #[wasm_bindgen(js_namespace = window, js_name = sectorGamepadAxis)] + fn gamepad_axis(index: u32) -> f32; +} + +pub fn sample_controller_input( + mut input: ResMut, + windows: Query<&Window, With>, + #[cfg(not(target_arch = "wasm32"))] gamepads: Query<(Entity, &Gamepad)>, +) { + if windows.iter().any(|window| !window.focused) { + input.clear(); + input.waiting_for_neutral = true; + return; + } + #[cfg(target_arch = "wasm32")] + let snapshot = { + let buttons = poll_gamepad(); + (buttons & 128 != 0).then(|| ControllerSnapshot { + id: u64::from(gamepad_id()), + buttons: buttons & 127, + left_stick: Vec2::new(gamepad_axis(0), gamepad_axis(1)), + right_x: gamepad_axis(2), + dpad: Vec2::new(gamepad_axis(3), gamepad_axis(4)), + }) + }; + #[cfg(not(target_arch = "wasm32"))] + let snapshot = { + let mut retained = None; + let mut candidate = None; + for (entity, pad) in &gamepads { + let snapshot = ControllerSnapshot::from_gamepad(entity, pad); + if input.id == Some(snapshot.id) { + retained = Some(snapshot); + } + if candidate.is_none() + || snapshot.has_input() && !candidate.is_some_and(ControllerSnapshot::has_input) + { + candidate = Some(snapshot); + } + } + retained + .filter(|snapshot| snapshot.has_input()) + .or(candidate.filter(|snapshot| snapshot.has_input())) + .or(retained) + .or(candidate) + }; + input.sample(snapshot); +} + +#[cfg(test)] +mod tests { + use super::*; + use sector::game::{desired_horizontal_velocity, Player, PLAYER_WALK_SPEED_MPS}; + + fn snapshot(buttons: u32, dpad: Vec2) -> ControllerSnapshot { + ControllerSnapshot { + id: 1, + buttons, + dpad, + ..default() + } + } + + #[test] + fn stickless_dpad_moves_and_bumpers_turn_then_y_swaps_horizontal_roles() { + let mut input = ControllerInput::default(); + input.sample(Some(snapshot(RIGHT_BUMPER, Vec2::new(1.0, 1.0)))); + assert!(input.active); + assert_eq!(input.movement, Vec2::ONE.normalize()); + assert_eq!(input.turn_delta(1.0), TURN_SPEED); + input.sample(Some(snapshot( + SWAP_DPAD | RIGHT_BUMPER, + Vec2::new(-1.0, 1.0), + ))); + assert!(input.dpad_turns); + assert_eq!(input.movement, Vec2::ONE.normalize()); + assert_eq!(input.turn_delta(1.0), -TURN_SPEED); + input.sample(Some(snapshot(SWAP_DPAD, Vec2::ZERO))); + assert!(input.dpad_turns, "holding Y must not toggle every frame"); + input.sample(Some(snapshot(0, Vec2::ZERO))); + input.sample(Some(snapshot(SWAP_DPAD, Vec2::ZERO))); + assert!(!input.dpad_turns); + } + + #[test] + fn analog_movement_keeps_partial_speed_and_digital_diagonals_are_capped() { + let mut input = ControllerInput::default(); + input.sample(Some(ControllerSnapshot { + id: 1, + left_stick: Vec2::new(0.0, 0.6), + ..default() + })); + let movement = input.merge(PlayerInput::default()); + let velocity = desired_horizontal_velocity(&Player::default(), movement); + assert!((velocity.length() - PLAYER_WALK_SPEED_MPS * 0.5).abs() < 0.0001); + input.sample(Some(snapshot(0, Vec2::ONE))); + let velocity = desired_horizontal_velocity( + &Player::default(), + input.merge(PlayerInput { + forward: true, + strafe_right: true, + ..default() + }), + ); + assert!((velocity.length() - PLAYER_WALK_SPEED_MPS).abs() < 0.0001); + } + + #[test] + fn sticks_are_unaffected_by_y_and_turning_is_independent_of_frame_rate() { + let mut input = ControllerInput::default(); + input.sample(Some(ControllerSnapshot { + id: 1, + buttons: SWAP_DPAD, + left_stick: Vec2::X, + right_x: 1.0, + ..default() + })); + assert_eq!(input.movement, Vec2::X); + let turn_30: f32 = (0..30).map(|_| input.turn_delta(1.0 / 30.0)).sum(); + let turn_120: f32 = (0..120).map(|_| input.turn_delta(1.0 / 120.0)).sum(); + assert!((turn_30 - turn_120).abs() < 0.0001); + } + + #[test] + fn dead_zones_ignore_drift_and_non_finite_values() { + assert_eq!(radial_dead_zone(Vec2::new(0.1, 0.1)), Vec2::ZERO); + assert_eq!(radial_dead_zone(Vec2::new(f32::NAN, 0.0)), Vec2::ZERO); + assert_eq!(axis_dead_zone(f32::INFINITY), 0.0); + assert_eq!(axis_dead_zone(0.1), 0.0); + assert_eq!(axis_dead_zone(-1.0), -1.0); + } + + #[test] + fn jump_and_automap_edges_wait_for_consumption_without_repeating() { + let mut input = ControllerInput::default(); + input.sample(Some(snapshot(JUMP | AUTOMAP, Vec2::ZERO))); + input.sample(Some(snapshot(JUMP | AUTOMAP, Vec2::ZERO))); + assert!(input.map_pending); + assert!(input.merge(PlayerInput::default()).jump_pressed); + assert!(!input.merge(PlayerInput::default()).jump_pressed); + input.map_pending = false; + input.sample(Some(snapshot(JUMP | AUTOMAP, Vec2::ZERO))); + assert!(!input.map_pending); + input.sample(Some(snapshot(0, Vec2::ZERO))); + input.sample(Some(snapshot(JUMP, Vec2::ZERO))); + assert!(input.merge(PlayerInput::default()).jump_pressed); + } + + #[test] + fn crouch_hold_and_toggle_clear_on_disconnect_while_layout_stays_selected() { + let mut input = ControllerInput::default(); + input.sample(Some(snapshot(CROUCH | TOGGLE_CROUCH | SWAP_DPAD, Vec2::X))); + assert!(input.merge(PlayerInput::default()).crouch_pressed); + input.sample(Some(snapshot(0, Vec2::ZERO))); + assert!(input.merge(PlayerInput::default()).crouch_pressed); + input.sample(None); + assert!(!input.active); + assert!(input.dpad_turns); + assert_eq!(input.merge(PlayerInput::default()), PlayerInput::default()); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn refocusing_requires_release_before_held_buttons_can_trigger_again() { + let mut app = App::new(); + app.init_resource::() + .add_systems(Update, sample_controller_input); + let mut pad = Gamepad::default(); + pad.digital_mut().press(GamepadButton::South); + let pad_entity = app.world_mut().spawn(pad).id(); + let window = app + .world_mut() + .spawn((Window::default(), PrimaryWindow)) + .id(); + app.update(); + assert!(app.world().resource::().jump_pending); + app.world_mut().get_mut::(window).unwrap().focused = false; + app.update(); + app.world_mut().get_mut::(window).unwrap().focused = true; + app.update(); + assert!(!app.world().resource::().active); + assert!(!app.world().resource::().jump_pending); + app.world_mut() + .get_mut::(pad_entity) + .unwrap() + .digital_mut() + .release_all(); + app.update(); + app.world_mut() + .get_mut::(pad_entity) + .unwrap() + .digital_mut() + .press(GamepadButton::South); + app.update(); + assert!(app.world().resource::().jump_pending); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn native_gamepad_component_drives_the_shared_input_pipeline() { + let mut app = App::new(); + app.init_resource::() + .add_systems(Update, sample_controller_input); + let mut pad = Gamepad::default(); + pad.digital_mut().press(GamepadButton::DPadUp); + pad.digital_mut().press(GamepadButton::DPadLeft); + pad.digital_mut().press(GamepadButton::RightTrigger); + let entity = app.world_mut().spawn(pad).id(); + app.update(); + let input = app.world().resource::(); + assert_eq!(input.movement, Vec2::new(-1.0, 1.0).normalize()); + assert_eq!(input.turn, 1.0); + app.world_mut().despawn(entity); + app.update(); + assert!(!app.world().resource::().active); + } +} diff --git a/src/bin/sector/main.rs b/src/bin/sector/main.rs index 83d3103..5fd1f50 100644 --- a/src/bin/sector/main.rs +++ b/src/bin/sector/main.rs @@ -1,3 +1,7 @@ +mod controller; + +use controller::{sample_controller_input, ControllerInput}; + mod touch; use touch::{sample_touch_input, TouchInput}; @@ -144,6 +148,11 @@ impl Plugin for SectorRuntimePlugin { .insert_resource(RendererTimingState::default()) .insert_resource(FlyToggleTracker::default()) .init_resource::() + .init_resource::() + .add_systems( + PreUpdate, + sample_controller_input.after(bevy::input::InputSystems), + ) .add_systems(PreUpdate, sample_touch_input) .insert_resource(WindowTitleTimer(Timer::new( Duration::from_millis(500), @@ -250,6 +259,9 @@ fn main() { ) .add_plugins(FrameTimeDiagnosticsPlugin::default()); + #[cfg(not(target_arch = "wasm32"))] + app.add_plugins(bevy_gilrs::GilrsPlugin); + configure_runtime_plugins(&mut app); app.run(); @@ -551,8 +563,11 @@ fn switch_automap_system( mut automap: ResMut, key: Res>, mut touch: ResMut, + mut controller: ResMut, ) { - if std::mem::take(&mut touch.map_pending) || key.just_pressed(KeyCode::Tab) { + let controller_map = std::mem::take(&mut controller.map_pending); + let touch_map = std::mem::take(&mut touch.map_pending); + if controller_map || touch_map || key.just_pressed(KeyCode::Tab) { automap.0 = automap.0.next(); } } @@ -785,8 +800,12 @@ fn vec3_components(vector: Vec3) -> [f32; 3] { [vector.x, vector.y, vector.z] } -fn player_controls_active(cursor: Res>, touch: Res) -> bool { - *cursor.get() == CursorCaptureState::Captured || touch.active +fn player_controls_active( + cursor: Res>, + touch: Res, + controller: Res, +) -> bool { + *cursor.get() == CursorCaptureState::Captured || touch.active || controller.active } fn player_look_system( @@ -795,6 +814,8 @@ fn player_look_system( key: Res>, cursor_capture_state: Res>, touch: Res, + controller: Res, + time: Res