Skip to main content

rusting_core/
input.rs

1//! Runtime-side input capture and named action mapping.
2//!
3//! `RuntimeInput` holds raw keyboard and mouse state for gameplay systems.
4//! Window integrations record raw events into it and clear edge state once per
5//! rendered frame after gameplay systems have had a chance to read it.
6
7use std::collections::{HashMap, HashSet};
8
9use bevy_ecs::prelude::Resource;
10pub use winit::event::MouseButton;
11pub use winit::keyboard::KeyCode;
12
13/// Held keys, mouse buttons, and cursor position for the current frame.
14///
15/// `just_pressed`/`just_released` sets are edge-triggered: they hold exactly
16/// the keys or buttons that changed state since the last call to
17/// [`RuntimeInput::clear_frame_edges`]. Runtime integrations call that method
18/// once per rendered frame after gameplay systems have had a chance to read
19/// them.
20#[derive(Resource, Default)]
21pub struct RuntimeInput {
22    keys_held: HashSet<KeyCode>,
23    keys_just_pressed: HashSet<KeyCode>,
24    keys_just_released: HashSet<KeyCode>,
25    mouse_held: HashSet<MouseButton>,
26    mouse_just_pressed: HashSet<MouseButton>,
27    mouse_just_released: HashSet<MouseButton>,
28    cursor_position: Option<[f32; 2]>,
29    viewport_size: [f32; 2],
30}
31
32impl RuntimeInput {
33    #[must_use]
34    pub fn key_held(&self, key: KeyCode) -> bool {
35        self.keys_held.contains(&key)
36    }
37    #[must_use]
38    pub fn key_just_pressed(&self, key: KeyCode) -> bool {
39        self.keys_just_pressed.contains(&key)
40    }
41    #[must_use]
42    pub fn key_just_released(&self, key: KeyCode) -> bool {
43        self.keys_just_released.contains(&key)
44    }
45    #[must_use]
46    pub fn mouse_held(&self, button: MouseButton) -> bool {
47        self.mouse_held.contains(&button)
48    }
49    #[must_use]
50    pub fn mouse_just_pressed(&self, button: MouseButton) -> bool {
51        self.mouse_just_pressed.contains(&button)
52    }
53    #[must_use]
54    pub fn mouse_just_released(&self, button: MouseButton) -> bool {
55        self.mouse_just_released.contains(&button)
56    }
57    #[must_use]
58    pub fn cursor_position(&self) -> Option<[f32; 2]> {
59        self.cursor_position
60    }
61
62    /// Current window/render-viewport size in pixels, used to convert cursor
63    /// positions into normalized device coordinates for gameplay picking.
64    #[must_use]
65    pub fn viewport_size(&self) -> [f32; 2] {
66        self.viewport_size
67    }
68
69    /// Records one keyboard `WindowEvent`. Ignores OS auto-repeat: repeated
70    /// presses do not re-fire `just_pressed`.
71    pub fn record_key(&mut self, key: KeyCode, pressed: bool) {
72        if pressed {
73            if self.keys_held.insert(key) {
74                self.keys_just_pressed.insert(key);
75            }
76        } else if self.keys_held.remove(&key) {
77            self.keys_just_released.insert(key);
78        }
79    }
80
81    /// Records one mouse button `WindowEvent`.
82    pub fn record_mouse_button(&mut self, button: MouseButton, pressed: bool) {
83        if pressed {
84            if self.mouse_held.insert(button) {
85                self.mouse_just_pressed.insert(button);
86            }
87        } else if self.mouse_held.remove(&button) {
88            self.mouse_just_released.insert(button);
89        }
90    }
91
92    /// Releases every held key and button, reporting each as just released.
93    /// Call it when the window loses focus, because the matching release
94    /// events then go to another window.
95    pub fn release_all(&mut self) {
96        self.keys_just_released.extend(self.keys_held.drain());
97        self.mouse_just_released.extend(self.mouse_held.drain());
98    }
99
100    /// Records the latest cursor position from a `CursorMoved` event.
101    pub fn record_cursor_position(&mut self, position: [f32; 2]) {
102        self.cursor_position = Some(position);
103    }
104    /// Records the current window/render-viewport size in pixels.
105    pub fn record_viewport_size(&mut self, size: [f32; 2]) {
106        self.viewport_size = size;
107    }
108
109    /// Clears this frame's edge sets. Runtime integrations call this once per
110    /// rendered frame after gameplay systems have read them, so the next frame
111    /// starts empty.
112    pub fn clear_frame_edges(&mut self) {
113        self.keys_just_pressed.clear();
114        self.keys_just_released.clear();
115        self.mouse_just_pressed.clear();
116        self.mouse_just_released.clear();
117    }
118}
119
120/// A raw input source which can satisfy a named gameplay action.
121///
122/// The enum deliberately leaves room for a future `Gamepad(GamepadButton)`
123/// variant without changing the [`ActionMap`] API.
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
125pub enum InputBinding {
126    Key(KeyCode),
127    Mouse(MouseButton),
128}
129
130/// Maps action names to one or more raw input bindings (any bound input
131/// satisfies the action).
132#[derive(Resource, Default)]
133pub struct ActionMap {
134    bindings: HashMap<String, Vec<InputBinding>>,
135}
136
137impl ActionMap {
138    pub fn bind(
139        &mut self,
140        action: impl Into<String>,
141        binding: InputBinding,
142    ) -> &mut Self {
143        self.bindings
144            .entry(action.into())
145            .or_default()
146            .push(binding);
147        self
148    }
149    #[must_use]
150    pub fn held(&self, input: &RuntimeInput, action: &str) -> bool {
151        self.bindings_for(action).any(|binding| match binding {
152            InputBinding::Key(key) => input.key_held(*key),
153            InputBinding::Mouse(button) => input.mouse_held(*button),
154        })
155    }
156    #[must_use]
157    pub fn just_pressed(&self, input: &RuntimeInput, action: &str) -> bool {
158        self.bindings_for(action).any(|binding| match binding {
159            InputBinding::Key(key) => input.key_just_pressed(*key),
160            InputBinding::Mouse(button) => input.mouse_just_pressed(*button),
161        })
162    }
163    #[must_use]
164    pub fn just_released(&self, input: &RuntimeInput, action: &str) -> bool {
165        self.bindings_for(action).any(|binding| match binding {
166            InputBinding::Key(key) => input.key_just_released(*key),
167            InputBinding::Mouse(button) => input.mouse_just_released(*button),
168        })
169    }
170    fn bindings_for(
171        &self,
172        action: &str,
173    ) -> impl Iterator<Item = &InputBinding> {
174        self.bindings.get(action).into_iter().flatten()
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use bevy_ecs::prelude::Resource;
182
183    #[test]
184    fn release_all_clears_held_input_as_releases() {
185        let mut input = RuntimeInput::default();
186        input.record_key(KeyCode::KeyW, true);
187        input.record_mouse_button(MouseButton::Right, true);
188        input.clear_frame_edges();
189        input.release_all();
190        assert!(!input.key_held(KeyCode::KeyW));
191        assert!(input.key_just_released(KeyCode::KeyW));
192        assert!(input.mouse_just_released(MouseButton::Right));
193    }
194
195    #[test]
196    fn runtime_input_and_action_map_are_ecs_resources() {
197        fn assert_resource<T: Resource>() {}
198        assert_resource::<RuntimeInput>();
199        assert_resource::<ActionMap>();
200    }
201    #[test]
202    fn keyboard_edges_and_auto_repeat_are_tracked() {
203        let mut input = RuntimeInput::default();
204        input.record_key(KeyCode::Space, true);
205        assert!(input.key_held(KeyCode::Space));
206        assert!(input.key_just_pressed(KeyCode::Space));
207        input.record_key(KeyCode::Space, true);
208        input.clear_frame_edges();
209        assert!(input.key_held(KeyCode::Space));
210        assert!(!input.key_just_pressed(KeyCode::Space));
211        input.record_key(KeyCode::Space, false);
212        assert!(input.key_just_released(KeyCode::Space));
213    }
214    #[test]
215    fn mouse_cursor_and_viewport_are_tracked() {
216        let mut input = RuntimeInput::default();
217        input.record_mouse_button(MouseButton::Left, true);
218        input.record_cursor_position([12.0, 34.0]);
219        input.record_viewport_size([800.0, 600.0]);
220        assert!(input.mouse_held(MouseButton::Left));
221        assert!(input.mouse_just_pressed(MouseButton::Left));
222        assert_eq!(input.cursor_position(), Some([12.0, 34.0]));
223        assert_eq!(input.viewport_size(), [800.0, 600.0]);
224        input.clear_frame_edges();
225        input.record_mouse_button(MouseButton::Left, false);
226        assert!(input.mouse_just_released(MouseButton::Left));
227        assert!(!input.mouse_held(MouseButton::Left));
228    }
229    #[test]
230    fn actions_cover_keyboard_mouse_and_edge_clearing() {
231        let mut map = ActionMap::default();
232        map.bind("jump", InputBinding::Key(KeyCode::Space))
233            .bind("jump", InputBinding::Mouse(MouseButton::Left));
234        let mut input = RuntimeInput::default();
235        input.record_key(KeyCode::Space, true);
236        assert!(map.just_pressed(&input, "jump"));
237        assert!(map.held(&input, "jump"));
238        input.clear_frame_edges();
239        assert!(!map.just_pressed(&input, "jump"));
240        assert!(map.held(&input, "jump"));
241        input.record_key(KeyCode::Space, false);
242        assert!(map.just_released(&input, "jump"));
243        input.clear_frame_edges();
244        input.record_mouse_button(MouseButton::Left, true);
245        assert!(map.just_pressed(&input, "jump"));
246        assert!(map.held(&input, "jump"));
247        assert!(!map.held(&input, "unbound_action"));
248    }
249}