From 09cd68feac9813b82f0c73e7c0429ddf0f719117 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Tomas=20Wenstr=C3=B6m?= Date: Thu, 18 Feb 2021 18:27:22 +0100 Subject: [PATCH] Use GameControllers instead of Joysticks --- src/core/app.rs | 2 +- src/core/controller.rs | 206 ++++++++++++++++++++----------------------------- src/core/game.rs | 13 ---- 3 files changed, 83 insertions(+), 138 deletions(-) diff --git a/src/core/app.rs b/src/core/app.rs index 808277f..97679df 100644 --- a/src/core/app.rs +++ b/src/core/app.rs @@ -73,7 +73,7 @@ impl AppBuilder { event_pump, sprites, states: vec!(self.state.unwrap_or_else(|| Box::new(ActiveState::new(screen)))), - ctrl_man: ControllerManager::new(context.joystick()?, context.haptic()?), + ctrl_man: ControllerManager::new(context.game_controller()?, context.haptic()?), }) } diff --git a/src/core/controller.rs b/src/core/controller.rs index de91928..2373cb5 100644 --- a/src/core/controller.rs +++ b/src/core/controller.rs @@ -1,18 +1,18 @@ -use geometry::{Angle, Point}; -use {hashmap, point}; +use geometry::{Angle, ToAngle, Point}; +use sdl2::GameControllerSubsystem; use sdl2::HapticSubsystem; -use sdl2::JoystickSubsystem; +use sdl2::controller::{GameController, Axis as SDLAxis, Button as SDLButton}; use sdl2::event::Event; use sdl2::haptic::Haptic; -use sdl2::joystick::Joystick; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use time::{Duration, prelude::*}; +use {hashmap, point}; -#[derive(Debug, Default)] +#[derive(Debug)] pub struct Button { - id: u8, + id: SDLButton, pub time_pressed: Duration, pub time_released: Duration, pub is_pressed: bool, @@ -21,10 +21,21 @@ pub struct Button { } impl Button { - fn update(&mut self, device: &Joystick, dt: Duration) { + pub fn new(id: SDLButton) -> Self { + Button { + id, + time_pressed: Duration::zero(), + time_released: Duration::zero(), + is_pressed: false, + was_pressed: false, + toggle: false, + } + } + + fn update(&mut self, device: &GameController, dt: Duration) { self.was_pressed = self.is_pressed; - self.is_pressed = match device.button(self.id as u32) { - Ok(true) => { + self.is_pressed = match device.button(self.id) { + true => { if !self.was_pressed { self.time_pressed = 0.seconds(); self.toggle = !self.toggle; @@ -32,53 +43,51 @@ impl Button { self.time_pressed += dt; true } - Ok(false) => { + false => { if self.was_pressed { self.time_released = 0.seconds(); } self.time_released += dt; false } - Err(_) => { panic!("invalid button {}", self.id) } } } } -#[derive(Debug, Default)] +#[derive(Debug)] pub struct Axis { - id: u8, + id: SDLAxis, pub val: f32, } impl Axis { #[allow(dead_code)] - fn update(&mut self, device: &Joystick, _dt: Duration) { - self.val = match device.axis(self.id as u32) { - Ok(val) => val as f32 / 32768.0, - Err(_) => panic!("invalid axis {}", self.id), - } + fn update(&mut self, device: &GameController, _dt: Duration) { + self.val = device.axis(self.id) as f32 / 32768.0; } } -#[derive(Debug, Default)] +#[derive(Debug)] pub struct Stick { - idx: u8, - idy: u8, + id: (SDLAxis, SDLAxis), pub x: f32, pub y: f32, pub a: Angle, } impl Stick { - fn update(&mut self, device: &Joystick, _dt: Duration) { - self.x = match device.axis(self.idx as u32) { - Ok(val) => val as f32 / 32768.0, - Err(_) => panic!("invalid x axis {}", self.idx), - }; - self.y = match device.axis(self.idy as u32) { - Ok(val) => val as f32 / 32768.0, - Err(_) => panic!("invalid y axis {}", self.idy), - }; + pub fn new(idx: SDLAxis, idy: SDLAxis) -> Self { + Stick { + id: (idx, idy), + x: 0.0, + y: 0.0, + a: 0.radians(), + } + } + + fn update(&mut self, device: &GameController, _dt: Duration) { + self.x = device.axis(self.id.0) as f32 / 32768.0; + self.y = device.axis(self.id.1) as f32 / 32768.0; self.a = point!(self.x as f64, self.y as f64).to_angle(); } @@ -117,34 +126,6 @@ impl From<&Stick> for (f64, f64) { } #[derive(Eq, PartialEq, Hash)] -enum DeviceControls { - AxisLX, - AxisLY, - AxisRX, - AxisRY, - AxisL2, - AxisR2, - ButtonA, - ButtonB, - ButtonY, - ButtonX, - ButtonSelect, - ButtonStart, - ButtonHome, - ButtonL3, - ButtonR3, - ButtonL1, - ButtonR1, - ButtonL2, - ButtonR2, - ButtonUp, - ButtonDown, - ButtonLeft, - ButtonRight, -} -use self::DeviceControls::*; - -#[derive(Eq, PartialEq, Hash)] enum ActionControls { MovementX, MovementY, @@ -158,7 +139,7 @@ use self::ActionControls::*; //#[derive(Debug)] pub struct Controller { - pub device: Joystick, + pub device: GameController, haptic: Option>>, pub mov: Stick, @@ -169,30 +150,29 @@ pub struct Controller { } impl Controller { - pub fn new(device: Joystick, haptic: Option>>) -> Self { - let action_map = get_action_mapping(); - let device_map = get_device_mapping(&device.name()); + pub fn new(device: GameController, haptic: Option>>) -> Self { + let map = get_action_mapping(); let mut ctrl = Controller { device, haptic, - mov: Default::default(), - aim: Default::default(), - jump: Default::default(), - start: Default::default(), - shoot: Default::default(), + mov: Stick::new(*map.axes.get(&MovementX).unwrap(), *map.axes.get(&MovementY).unwrap()), + aim: Stick::new(*map.axes.get(&AimX).unwrap(), *map.axes.get(&AimY).unwrap()), + jump: Button::new(*map.buttons.get(&Jump).unwrap()), + start: Button::new(*map.buttons.get(&Start).unwrap()), + shoot: Button::new(*map.buttons.get(&Shoot).unwrap()), }; - ctrl.set_mapping(&action_map, &device_map); + ctrl.set_mapping(&map); ctrl } - fn set_mapping(&mut self, action: &HashMap, device: &HashMap) { - self.mov.idx = *action.get(&MovementX).map(|i| device.get(i)).flatten().unwrap(); - self.mov.idy = *action.get(&MovementY).map(|i| device.get(i)).flatten().unwrap(); - self.aim.idx = *action.get(&AimX).map(|i| device.get(i)).flatten().unwrap(); - self.aim.idy = *action.get(&AimY).map(|i| device.get(i)).flatten().unwrap(); - self.jump.id = *action.get(&Jump).map(|i| device.get(i)).flatten().unwrap(); - self.shoot.id = *action.get(&Shoot).map(|i| device.get(i)).flatten().unwrap(); - self.start.id = *action.get(&Start).map(|i| device.get(i)).flatten().unwrap(); + fn set_mapping(&mut self, map: &ActionMapping) { + self.mov.id.0 = *map.axes.get(&MovementX).unwrap(); + self.mov.id.1 = *map.axes.get(&MovementY).unwrap(); + self.aim.id.0 = *map.axes.get(&AimX).unwrap(); + self.aim.id.1 = *map.axes.get(&AimY).unwrap(); + self.jump.id = *map.buttons.get(&Jump).unwrap(); + self.shoot.id = *map.buttons.get(&Shoot).unwrap(); + self.start.id = *map.buttons.get(&Start).unwrap(); } pub fn update(&mut self, dt: Duration) { @@ -211,61 +191,39 @@ impl Controller { } } -fn get_action_mapping() -> HashMap { - hashmap!( - MovementX => AxisLX, - MovementY => AxisLY, - AimX => AxisRX, - AimY => AxisRY, - Jump => ButtonA, - Shoot => ButtonR1, - Start => ButtonStart - ) +struct ActionMapping { + axes: HashMap, + buttons: HashMap, } -fn get_device_mapping(device_name: &str) -> HashMap { - match device_name { - "Sony PLAYSTATION(R)3 Controller" => hashmap!( - AxisLX => 0, - AxisLY => 1, - AxisRX => 3, - AxisRY => 4, - AxisL2 => 2, - AxisR2 => 5, - ButtonA => 0, - ButtonB => 1, - ButtonY => 3, - ButtonX => 2, - ButtonSelect => 8, - ButtonStart => 9, - ButtonHome => 10, - ButtonL3 => 11, - ButtonR3 => 12, - ButtonL1 => 4, - ButtonR1 => 5, - ButtonL2 => 6, - ButtonR2 => 7, - ButtonUp => 13, - ButtonDown => 14, - ButtonLeft => 15, - ButtonRight => 16 +fn get_action_mapping() -> ActionMapping { + ActionMapping { + axes: hashmap!( + MovementX => SDLAxis::LeftX, + MovementY => SDLAxis::LeftY, + AimX => SDLAxis::RightX, + AimY => SDLAxis::RightY ), - _ => panic!("No controller mapping for device '{}'", device_name) + buttons: hashmap!( + Jump => SDLButton::A, + Shoot => SDLButton::RightShoulder, + Start => SDLButton::Start + ) } } //#[derive(Debug)] pub struct ControllerManager { - pub joystick: JoystickSubsystem, + pub subsystem: GameControllerSubsystem, haptic: Rc, pub controllers: HashMap>>, } impl ControllerManager { - pub fn new(joystick: JoystickSubsystem, haptic: HapticSubsystem) -> Self { - joystick.set_event_state(true); + pub fn new(subsystem: GameControllerSubsystem, haptic: HapticSubsystem) -> Self { + subsystem.set_event_state(true); let mut c = ControllerManager { - joystick, + subsystem, haptic: Rc::new(haptic), controllers: HashMap::new(), }; @@ -274,7 +232,7 @@ impl ControllerManager { } fn init(&mut self) { - for i in 0..self.joystick.num_joysticks().unwrap() { + for i in 0..self.subsystem.num_joysticks().unwrap() { self.add_device(i); } } @@ -285,18 +243,18 @@ impl ControllerManager { pub fn handle_event(&mut self, event: &Event) { match event { - Event::JoyDeviceAdded { which, .. } => { self.add_device(*which) } - Event::JoyDeviceRemoved { which, .. } => { self.remove_device(*which) } - // Event::JoyButtonDown { which, button_idx, .. } => { println!("device {} button {} down!", which, button_idx) } - // Event::JoyButtonUp { which, button_idx, .. } => { println!("device {} button {} up!", which, button_idx) } - // Event::JoyAxisMotion { which, axis_idx, .. } => { println!("device {} axis motion {}!", which, axis_idx) } + Event::ControllerDeviceAdded { which, .. } => { self.add_device(*which) } + Event::ControllerDeviceRemoved { which, .. } => { self.remove_device(*which) } + // Event::ControllerButtonDown { which, button_idx, .. } => { println!("device {} button {} down!", which, button_idx) } + // Event::ControllerButtonUp { which, button_idx, .. } => { println!("device {} button {} up!", which, button_idx) } + // Event::ControllerAxisMotion { which, axis_idx, .. } => { println!("device {} axis motion {}!", which, axis_idx) } _ => {} } } fn add_device(&mut self, id: u32) { println!("device added ({})!", id); - let mut device = self.joystick.open(id).unwrap(); + let mut device = self.subsystem.open(id).unwrap(); println!("opened {}", device.name()); /* diff --git a/src/core/game.rs b/src/core/game.rs index 8caf6ab..d9df53a 100644 --- a/src/core/game.rs +++ b/src/core/game.rs @@ -7,7 +7,6 @@ use core::render::Renderer; use geometry::{Point, ToAngle}; use point; use sdl2::event::Event; -use sdl2::joystick::PowerLevel; use sdl2::keyboard::Keycode; use sdl2::rect::Rect; use sprites::SpriteManager; @@ -228,18 +227,6 @@ impl Object for Character { self.vel -= direction * 0.1; } - if ctrl.start.is_pressed && !ctrl.start.was_pressed { - match ctrl.device.power_level() { - Ok(PowerLevel::Unknown) => { println!("power level unknown"); } - Ok(PowerLevel::Empty) => { println!("power level empty"); } - Ok(PowerLevel::Low) => { println!("power level low"); } - Ok(PowerLevel::Medium) => { println!("power level medium"); } - Ok(PowerLevel::Full) => { println!("power level full"); } - Ok(PowerLevel::Wired) => { println!("power level wired"); } - Err(_) => {} - }; - } - Alive } -- 2.11.0