-use std::cell::RefCell;
-use sdl2::haptic::Haptic;
+use common::Point;
+use {hashmap, point};
+use common::Radians;
use sdl2::HapticSubsystem;
-use sdl2::GameControllerSubsystem;
+use sdl2::JoystickSubsystem;
use sdl2::event::Event;
-use sdl2::controller::GameController;
+use sdl2::haptic::Haptic;
+use sdl2::joystick::Joystick;
+use std::cell::RefCell;
+use std::collections::HashMap;
use std::rc::Rc;
+use time::{Duration, prelude::*};
-//#[derive(Debug)]
-pub struct ControllerManager {
- ctrl: GameControllerSubsystem,
- haptic: Rc<HapticSubsystem>,
- pub controllers: Vec<Rc<Controller>>,
+#[derive(Debug, Default)]
+pub struct Button {
+ id: u8,
+ pub time_pressed: Duration,
+ pub time_released: Duration,
+ pub is_pressed: bool,
+ pub was_pressed: bool,
+ pub toggle: bool,
+}
+
+impl Button {
+ fn update(&mut self, device: &Joystick, dt: Duration) {
+ self.was_pressed = self.is_pressed;
+ self.is_pressed = match device.button(self.id as u32) {
+ Ok(true) => {
+ if !self.was_pressed {
+ self.time_pressed = 0.seconds();
+ self.toggle = !self.toggle;
+ }
+ self.time_pressed += dt;
+ true
+ }
+ Ok(false) => {
+ if self.was_pressed {
+ self.time_released = 0.seconds();
+ }
+ self.time_released += dt;
+ false
+ }
+ Err(_) => { panic!("invalid button {}", self.id) }
+ }
+ }
+}
+
+#[derive(Debug, Default)]
+pub struct Axis {
+ id: u8,
+ 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),
+ }
+ }
+}
+
+#[derive(Debug, Default)]
+pub struct Stick {
+ idx: u8,
+ idy: u8,
+ pub x: f32,
+ pub y: f32,
+ pub a: Radians,
+}
+
+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),
+ };
+ self.a = Radians(self.y.atan2(self.x) as f64);
+ }
+
+ #[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<f64> {
+ point!(self.x as f64, self.y as f64)
+ }
+
+ pub fn to_point(&self) -> Point<f64> {
+ 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<f64> {
+ 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 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,
+ AimX,
+ AimY,
+ Jump,
+ Shoot,
+ Start,
}
+use self::ActionControls::*;
//#[derive(Debug)]
pub struct Controller {
- id: u32,
- pub ctrl: GameController,
+ pub device: Joystick,
haptic: Option<Rc<RefCell<Haptic>>>,
+
+ pub mov: Stick,
+ pub aim: Stick,
+ pub jump: Button,
+ pub start: Button,
+ pub shoot: Button,
+}
+
+impl Controller {
+ pub fn new(device: Joystick, haptic: Option<Rc<RefCell<Haptic>>>) -> Self {
+ let action_map = get_action_mapping();
+ let device_map = get_device_mapping(&device.name());
+ let mut ctrl = Controller {
+ device,
+ haptic,
+ mov: Default::default(),
+ aim: Default::default(),
+ jump: Default::default(),
+ start: Default::default(),
+ shoot: Default::default(),
+ };
+ ctrl.set_mapping(&action_map, &device_map);
+ ctrl
+ }
+
+ fn set_mapping(&mut self, action: &HashMap<ActionControls, DeviceControls>, device: &HashMap<DeviceControls, u8>) {
+ 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();
+ }
+
+ 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);
+ }
+ }
+}
+
+fn get_action_mapping() -> HashMap<ActionControls, DeviceControls> {
+ hashmap!(
+ MovementX => AxisLX,
+ MovementY => AxisLY,
+ AimX => AxisRX,
+ AimY => AxisRY,
+ Jump => ButtonA,
+ Shoot => ButtonR1,
+ Start => ButtonStart
+ )
+}
+
+fn get_device_mapping(device_name: &str) -> HashMap<DeviceControls, u8> {
+ 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
+ ),
+ _ => panic!("No controller mapping for device '{}'", device_name)
+ }
+}
+
+//#[derive(Debug)]
+pub struct ControllerManager {
+ pub joystick: JoystickSubsystem,
+ haptic: Rc<HapticSubsystem>,
+ pub controllers: HashMap<u32, Rc<RefCell<Controller>>>,
}
impl ControllerManager {
- pub fn new(ctrl: GameControllerSubsystem, haptic: HapticSubsystem) -> Self {
- ControllerManager {
- ctrl,
+ pub fn new(joystick: JoystickSubsystem, haptic: HapticSubsystem) -> Self {
+ joystick.set_event_state(true);
+ let mut c = ControllerManager {
+ joystick,
haptic: Rc::new(haptic),
- controllers: vec![],
+ controllers: HashMap::new(),
+ };
+ c.init();
+ c
+ }
+
+ fn init(&mut self) {
+ for i in 0..self.joystick.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: id, .. } => { self.add_device(*id) }
- Event::ControllerDeviceRemoved { which: id, .. } => { self.remove_device(*id) }
- Event::ControllerDeviceRemapped { which: id, .. } => { println!("device remapped ({})!", *id) }
- Event::ControllerButtonDown { button: btn, .. } => { println!("button {} down!", btn.string()) }
- Event::ControllerButtonUp { button: btn, .. } => { println!("button {} up!", btn.string()) }
- Event::ControllerAxisMotion { axis: ax, .. } => { println!("axis motion {}!", ax.string()) }
+ 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) }
_ => {}
}
}
- pub fn add_device(&mut self, id: u32) {
+ fn add_device(&mut self, id: u32) {
println!("device added ({})!", id);
- let mut ctrl = self.ctrl.open(id).unwrap();
- println!("opened {}", ctrl.name());
- let haptic = match ctrl.set_rumble(500, 1000, 500) {
+ let mut device = self.joystick.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
};
- let c = Rc::new(Controller {id, ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))});
- c.rumble(0.5, 300);
- self.controllers.push(c);
- }
+ if self.controllers.contains_key(&id) {
+ return;
+ }
- pub fn remove_device(&mut self, id: i32) {
- println!("device removed ({})!", id);
+ 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);
+ }
+ };
}
-}
-impl Controller {
- /// strength [0 - 1]
- pub fn rumble(&self, strength: f32, duration_ms: u32) {
- if let Some(h) = &self.haptic {
- h.borrow_mut().rumble_play(strength, duration_ms);
- }
+ fn remove_device(&mut self, id: i32) {
+ println!("device removed ({})!", id);
+ // TODO
}
}