Re-introduce the device manager, only fire keypress events if the key is held

This commit is contained in:
Dane Johnson 2022-04-21 11:49:14 -05:00
parent 1af2795e7d
commit eab7630c85
3 changed files with 48 additions and 4 deletions

34
src/device.rs Normal file
View File

@ -0,0 +1,34 @@
use std::collections::HashMap;
pub enum KeyEvent {
Pressed(u32),
Released(u32),
}
pub struct DeviceManager {
key_map: HashMap<u32, bool>,
key_event: Option<KeyEvent>,
}
impl DeviceManager {
pub fn new() -> Self {
DeviceManager {
key_map: HashMap::new(),
key_event: None
}
}
pub fn update_key_event(&mut self, scancode: u32, pressed: bool) {
let old = *self.key_map.get(&scancode).unwrap_or(&false);
if old != pressed {
self.key_map.insert(scancode, pressed);
if pressed {
self.key_event = Some(KeyEvent::Pressed(scancode));
} else {
self.key_event = Some(KeyEvent::Released(scancode));
}
}
}
pub fn handle_key_event(&mut self) -> Option<KeyEvent> {
std::mem::replace(&mut self.key_event, None)
}
}

View File

@ -1,3 +1,6 @@
mod device;
use device::*;
mod model;
use model::Model;
@ -25,6 +28,8 @@ fn main() {
let display = glium::Display::new(wb, cb, &events_loop).unwrap();
let mut device_manager = DeviceManager::new();
let vertex_shader_src = include_str!("flat.vert");
let fragment_shader_src = include_str!("flat.frag");
let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None).unwrap();
@ -63,9 +68,14 @@ fn main() {
glutin::event::KeyboardInput { scancode, state, .. }
) = event {
match state {
glutin::event::ElementState::Pressed => script_lang.key_pressed(scancode),
glutin::event::ElementState::Released => script_lang.key_released(scancode),
}
glutin::event::ElementState::Pressed => device_manager.update_key_event(scancode, true),
glutin::event::ElementState::Released => device_manager.update_key_event(scancode, false),
};
match device_manager.handle_key_event() {
Some(KeyEvent::Pressed(x)) => script_lang.key_pressed(x),
Some(KeyEvent::Released(x)) => script_lang.key_released(x),
None => (),
};
};
},
glutin::event::Event::MainEventsCleared => {