Added a basic gamestate with a controlled mario
[kaka/rust-sdl-test.git] / src / core / controller.rs
index f565070..fb56465 100644 (file)
@@ -1,31 +1,39 @@
+use std::collections::HashMap;
 use std::cell::RefCell;
 use sdl2::haptic::Haptic;
 use sdl2::HapticSubsystem;
-use sdl2::GameControllerSubsystem;
+pub use sdl2::GameControllerSubsystem;
 use sdl2::event::Event;
 use sdl2::controller::GameController;
 use std::rc::Rc;
 
 //#[derive(Debug)]
 pub struct ControllerManager {
-    ctrl: GameControllerSubsystem,
+    pub ctrl: GameControllerSubsystem,
     haptic: Rc<HapticSubsystem>,
-    pub controllers: Vec<Rc<RefCell<Controller>>>,
+    pub controllers: HashMap<u32, Rc<RefCell<Controller>>>,
 }
 
 //#[derive(Debug)]
 pub struct Controller {
-    id: u32,
     pub ctrl: GameController,
     haptic: Option<Rc<RefCell<Haptic>>>,
 }
 
 impl ControllerManager {
     pub fn new(ctrl: GameControllerSubsystem, haptic: HapticSubsystem) -> Self {
-       ControllerManager {
+       let mut c = ControllerManager {
            ctrl,
            haptic: Rc::new(haptic),
-           controllers: vec![],
+           controllers: HashMap::new(),
+       };
+       c.init();
+       c
+    }
+
+    fn init(&mut self) {
+       for i in 0..self.ctrl.num_joysticks().unwrap() {
+           self.add_device(i);
        }
     }
 
@@ -56,7 +64,11 @@ impl ControllerManager {
            Err(_) => None
        };
 
-       let detached = self.controllers.iter().find(|c| !c.borrow().ctrl.attached());
+       if self.controllers.contains_key(&id) {
+           return;
+       }
+
+       let detached = self.controllers.values().find(|c| !c.borrow().ctrl.attached());
        match detached {
            Some(c) => {
                let mut c = c.borrow_mut();
@@ -64,8 +76,8 @@ impl ControllerManager {
                c.haptic = haptic.map(|h| Rc::new(RefCell::new(h)));
            }
            None => {
-               let c = Rc::new(RefCell::new(Controller {id, ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))}));
-               self.controllers.push(c);
+               let c = Rc::new(RefCell::new(Controller {ctrl, haptic: haptic.map(|h| Rc::new(RefCell::new(h)))}));
+               self.controllers.insert(id, c);
            }
        };
     }