Fleshed out the controller
[kaka/rust-sdl-test.git] / src / core / controller.rs
index fb56465..127c309 100644 (file)
-use std::collections::HashMap;
-use std::cell::RefCell;
-use sdl2::haptic::Haptic;
+use sdl2::JoystickSubsystem;
+use common::Nanoseconds;
+use common::Radians;
+use common::Point2D;
 use sdl2::HapticSubsystem;
-pub use sdl2::GameControllerSubsystem;
 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;
 
-//#[derive(Debug)]
-pub struct ControllerManager {
-    pub ctrl: GameControllerSubsystem,
-    haptic: Rc<HapticSubsystem>,
-    pub controllers: HashMap<u32, Rc<RefCell<Controller>>>,
+#[derive(Debug, Default)]
+pub struct Button {
+    pub time_pressed: Nanoseconds,
+    pub time_released: Nanoseconds,
+    pub is_pressed: bool,
+    pub was_pressed: bool,
+    pub toggle: bool,
+}
+
+impl Button {
+    fn update(&mut self, device: &Joystick, dt: Nanoseconds, btn: u8) {
+       self.was_pressed = self.is_pressed;
+       self.is_pressed = match device.button(btn as u32) {
+           Ok(true) => {
+               if !self.was_pressed {
+                   self.time_pressed = 0;
+                   self.toggle = !self.toggle;
+               }
+               self.time_pressed += dt;
+               true
+           }
+           Ok(false) => {
+               if self.was_pressed {
+                   self.time_released = 0;
+               }
+               self.time_released += dt;
+               false
+           }
+           Err(_) => { panic!("invalid button {}", btn) }
+       }
+    }
+}
+
+#[derive(Debug, Default)]
+pub struct Axis {
+    pub val: f32,
+}
+
+impl Axis {
+    #[allow(dead_code)]
+    fn update(&mut self, device: &Joystick, _dt: Nanoseconds, axis: u8) {
+       self.val = match device.axis(axis as u32) {
+           Ok(val) => val as f32 / 32768.0,
+           Err(_) => panic!("invalid axis {}", axis),
+       }
+    }
+}
+
+#[derive(Debug, Default)]
+pub struct Stick {
+    pub x: f32,
+    pub y: f32,
+    pub a: Radians,
+    pub len: f32,
+}
+
+impl Stick {
+    fn update(&mut self, device: &Joystick, _dt: Nanoseconds, x_axis: u8, y_axis: u8) {
+       self.x = match device.axis(x_axis as u32) {
+           Ok(val) => val as f32 / 32768.0,
+           Err(_) => panic!("invalid x axis {}", x_axis),
+       };
+       self.y = match device.axis(y_axis as u32) {
+           Ok(val) => val as f32 / 32768.0,
+           Err(_) => panic!("invalid y axis {}", y_axis),
+       };
+       self.a = Radians(self.y.atan2(self.x) as f64);
+       self.len = {
+           let x = (self.x / self.y).abs().min(1.0);
+           let y = (self.y / self.x).abs().min(1.0);
+           (self.x.powi(2) + self.y.powi(2)).sqrt() / (x.powi(2) + y.powi(2)).sqrt()
+       }
+    }
+
+    #[inline(always)] #[allow(dead_code)] fn up(&self) -> bool { self.y > 0.99 }
+    #[inline(always)] #[allow(dead_code)] fn down(&self) -> bool { self.y < -0.99 }
+    #[inline(always)] #[allow(dead_code)] fn left(&self) -> bool { self.x < -0.99 }
+    #[inline(always)] #[allow(dead_code)] fn right(&self) -> bool { self.x > 0.99 }
+
+    pub fn to_point(&self) -> Point2D<f64> {
+       Point2D {
+           x: self.x as f64,
+           y: self.y as f64,
+       }
+    }
+
+    pub fn to_adjusted_point(&self) -> Point2D<f64> {
+       Point2D::from(self.a) * self.len as f64
+    }
+}
+
+impl From<&Stick> for Point2D<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(Debug)]
 pub struct Controller {
-    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 {
+       Controller {
+           device,
+           haptic,
+           mov: Default::default(),
+           aim: Default::default(),
+           jump: Default::default(),
+           start: Default::default(),
+           shoot: Default::default(),
+       }
+    }
+
+    pub fn update(&mut self, dt: Nanoseconds) {
+       self.mov.update(&self.device, dt, 0, 1); // left stick
+       self.aim.update(&self.device, dt, 3, 4); // right stick
+       self.jump.update(&self.device, dt, 4);   // left shoulder
+       self.shoot.update(&self.device, dt, 5); // right shoulder
+       self.start.update(&self.device, dt, 9);  // start
+    }
+
+    /// 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);
+       }
+    }
+}
+
+//#[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 {
+    pub fn new(joystick: JoystickSubsystem, haptic: HapticSubsystem) -> Self {
+       joystick.set_event_state(true);
        let mut c = ControllerManager {
-           ctrl,
+           joystick,
            haptic: Rc::new(haptic),
            controllers: HashMap::new(),
        };
@@ -32,34 +177,37 @@ impl ControllerManager {
     }
 
     fn init(&mut self) {
-       for i in 0..self.ctrl.num_joysticks().unwrap() {
+       for i in 0..self.joystick.num_joysticks().unwrap() {
            self.add_device(i);
        }
     }
 
+    pub fn update(&mut self, dt: Nanoseconds) {
+       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::ControllerDeviceRemapped { which, .. } => { println!("device remapped ({})!", *which) }
-           Event::ControllerButtonDown { button, .. } => { println!("button {} down!", button.string()) }
-           Event::ControllerButtonUp { button, .. } => { println!("button {} up!", button.string()) }
-           Event::ControllerAxisMotion { axis, .. } => { println!("axis motion {}!", axis.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 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 ctrl.set_rumble(0, 256, 100) {
+       let haptic = match device.set_rumble(0, 256, 100) {
            Ok(_) => self.haptic.open_from_joystick_id(id).ok(),
            Err(_) => None
        };
@@ -68,31 +216,22 @@ impl ControllerManager {
            return;
        }
 
-       let detached = self.controllers.values().find(|c| !c.borrow().ctrl.attached());
+       let detached = self.controllers.values().find(|c| !c.borrow().device.attached());
        match detached {
            Some(c) => {
                let mut c = c.borrow_mut();
-               c.ctrl = ctrl;
+               c.device = device;
                c.haptic = haptic.map(|h| Rc::new(RefCell::new(h)));
            }
            None => {
-               let c = Rc::new(RefCell::new(Controller {ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))}));
+               let c = Rc::new(RefCell::new(Controller::new(device, haptic.map(|h| Rc::new(RefCell::new(h))))));
                self.controllers.insert(id, c);
            }
        };
     }
 
-    pub fn remove_device(&mut self, id: i32) {
+    fn remove_device(&mut self, id: i32) {
        println!("device removed ({})!", id);
        // TODO
     }
 }
-
-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);
-       }
-    }
-}