use geometry::{Angle, ToAngle, Point}; use sdl2::GameControllerSubsystem; use sdl2::HapticSubsystem; use sdl2::controller::{GameController, Axis as SDLAxis, Button as SDLButton}; use sdl2::event::Event; use sdl2::haptic::Haptic; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use time::{Duration, prelude::*}; use {hashmap, point}; #[derive(Debug)] pub struct Button { id: SDLButton, pub time_pressed: Duration, pub time_released: Duration, pub is_pressed: bool, pub was_pressed: bool, pub toggle: bool, } impl Button { 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) { true => { if !self.was_pressed { self.time_pressed = 0.seconds(); self.toggle = !self.toggle; } self.time_pressed += dt; true } false => { if self.was_pressed { self.time_released = 0.seconds(); } self.time_released += dt; false } } } } #[derive(Debug)] pub struct Axis { id: SDLAxis, pub val: f32, } impl Axis { #[allow(dead_code)] fn update(&mut self, device: &GameController, _dt: Duration) { self.val = device.axis(self.id) as f32 / 32768.0; } } #[derive(Debug)] pub struct Stick { id: (SDLAxis, SDLAxis), pub x: f32, pub y: f32, pub a: Angle, } impl Stick { 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(); } #[inline(always)] #[allow(dead_code)] pub fn up(&self) -> bool { self.y < -0.99 } #[inline(always)] #[allow(dead_code)] pub fn down(&self) -> bool { self.y > 0.99 } #[inline(always)] #[allow(dead_code)] pub fn left(&self) -> bool { self.x < -0.99 } #[inline(always)] #[allow(dead_code)] pub fn right(&self) -> bool { self.x > 0.99 } pub fn to_axis_point(&self) -> Point { point!(self.x as f64, self.y as f64) } pub fn to_point(&self) -> Point { let p = point!(self.x as f64, self.y as f64); if p.length() > 1.0 { p.normalized() } else { p } } } impl From<&Stick> for Point { fn from(item: &Stick) -> Self { Self { x: item.x as f64, y: item.y as f64, } } } impl From<&Stick> for (f64, f64) { fn from(item: &Stick) -> Self { (item.x as f64, item.y as f64) } } #[derive(Eq, PartialEq, Hash)] enum ActionControls { MovementX, MovementY, AimX, AimY, Jump, Shoot, Start, } use self::ActionControls::*; //#[derive(Debug)] pub struct Controller { pub device: GameController, haptic: Option>>, pub mov: Stick, pub aim: Stick, pub jump: Button, pub start: Button, pub shoot: Button, } impl Controller { pub fn new(device: GameController, haptic: Option>>) -> Self { let map = get_action_mapping(); let mut ctrl = Controller { device, haptic, 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(&map); ctrl } 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) { self.mov.update(&self.device, dt); self.aim.update(&self.device, dt); self.jump.update(&self.device, dt); self.shoot.update(&self.device, dt); self.start.update(&self.device, dt); } /// strength [0 - 1] pub fn rumble(&self, strength: f32, duration: Duration) { if let Some(h) = &self.haptic { h.borrow_mut().rumble_play(strength, duration.whole_milliseconds() as u32); } } } struct ActionMapping { axes: HashMap, buttons: HashMap, } fn get_action_mapping() -> ActionMapping { ActionMapping { axes: hashmap!( MovementX => SDLAxis::LeftX, MovementY => SDLAxis::LeftY, AimX => SDLAxis::RightX, AimY => SDLAxis::RightY ), buttons: hashmap!( Jump => SDLButton::A, Shoot => SDLButton::RightShoulder, Start => SDLButton::Start ) } } //#[derive(Debug)] pub struct ControllerManager { pub subsystem: GameControllerSubsystem, haptic: Rc, pub controllers: HashMap>>, } impl ControllerManager { pub fn new(subsystem: GameControllerSubsystem, haptic: HapticSubsystem) -> Self { subsystem.set_event_state(true); let mut c = ControllerManager { subsystem, haptic: Rc::new(haptic), controllers: HashMap::new(), }; c.init(); c } fn init(&mut self) { for i in 0..self.subsystem.num_joysticks().unwrap() { self.add_device(i); } } pub fn update(&mut self, dt: Duration) { self.controllers.iter().for_each(|(_, v)| v.borrow_mut().update(dt)); } pub fn handle_event(&mut self, event: &Event) { match event { 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.subsystem.open(id).unwrap(); println!("opened {}", device.name()); /* note about set_rumble (for dualshock 3 at least): the active range for the low frequency is from 65536/4 to 65536 and escalates in large steps throughout the range the active range for the high frequency is from 256 to 65536 and effect is the same throughout the whole range */ let haptic = match device.set_rumble(0, 256, 100) { Ok(_) => self.haptic.open_from_joystick_id(id).ok(), Err(_) => None }; if self.controllers.contains_key(&id) { return; } let detached = self.controllers.values().find(|c| !c.borrow().device.attached()); match detached { Some(c) => { let mut c = c.borrow_mut(); c.device = device; c.haptic = haptic.map(|h| Rc::new(RefCell::new(h))); } None => { let c = Rc::new(RefCell::new(Controller::new(device, haptic.map(|h| Rc::new(RefCell::new(h)))))); self.controllers.insert(id, c); } }; } fn remove_device(&mut self, id: i32) { println!("device removed ({})!", id); // TODO } }