2024-11-10 19:05:10 +00:00
|
|
|
use std::sync::{Arc, RwLock};
|
2024-11-05 05:07:48 +00:00
|
|
|
|
2024-11-10 19:05:10 +00:00
|
|
|
use winit::event::{ElementState, KeyEvent};
|
|
|
|
|
2024-11-11 05:50:57 +00:00
|
|
|
use crate::{
|
|
|
|
emulator::{SimId, VBKey},
|
|
|
|
input::InputMapper,
|
|
|
|
};
|
2024-11-05 05:07:48 +00:00
|
|
|
|
|
|
|
pub struct ControllerState {
|
2024-11-10 19:05:10 +00:00
|
|
|
input_mapper: Arc<RwLock<InputMapper>>,
|
2024-11-11 05:50:57 +00:00
|
|
|
pressed: Vec<VBKey>,
|
2024-11-05 05:07:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ControllerState {
|
2024-11-10 19:05:10 +00:00
|
|
|
pub fn new(input_mapper: Arc<RwLock<InputMapper>>) -> Self {
|
2024-11-05 05:07:48 +00:00
|
|
|
Self {
|
2024-11-10 19:05:10 +00:00
|
|
|
input_mapper,
|
2024-11-11 05:50:57 +00:00
|
|
|
pressed: vec![VBKey::SGN; 2],
|
2024-11-05 05:07:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-11 05:50:57 +00:00
|
|
|
pub fn key_event(&mut self, event: &KeyEvent) -> Option<(SimId, VBKey)> {
|
|
|
|
let (sim_id, input) = self.key_event_to_input(event)?;
|
|
|
|
let pressed = &mut self.pressed[sim_id.to_index()];
|
2024-11-05 05:07:48 +00:00
|
|
|
match event.state {
|
|
|
|
ElementState::Pressed => {
|
2024-11-11 05:50:57 +00:00
|
|
|
if pressed.contains(input) {
|
|
|
|
return None;
|
2024-11-05 05:07:48 +00:00
|
|
|
}
|
2024-11-11 05:50:57 +00:00
|
|
|
pressed.insert(input);
|
|
|
|
Some((sim_id, *pressed))
|
2024-11-05 05:07:48 +00:00
|
|
|
}
|
|
|
|
ElementState::Released => {
|
2024-11-11 05:50:57 +00:00
|
|
|
if !pressed.contains(input) {
|
|
|
|
return None;
|
2024-11-05 05:07:48 +00:00
|
|
|
}
|
2024-11-11 05:50:57 +00:00
|
|
|
pressed.remove(input);
|
|
|
|
Some((sim_id, *pressed))
|
2024-11-05 05:07:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-11 05:50:57 +00:00
|
|
|
fn key_event_to_input(&self, event: &KeyEvent) -> Option<(SimId, VBKey)> {
|
2024-11-10 19:05:10 +00:00
|
|
|
let mapper = self.input_mapper.read().unwrap();
|
|
|
|
mapper.key_event(event)
|
2024-11-05 05:07:48 +00:00
|
|
|
}
|
|
|
|
}
|