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::{BTreeSet, HashMap};
8
9use bevy_ecs::entity::Entity;
10use bevy_ecs::prelude::Resource;
11use serde::{Deserialize, Serialize};
12pub use winit::event::MouseButton;
13pub use winit::keyboard::KeyCode;
14
15/// Fired the frame a mouse button is pressed over a renderable entity.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct ClickEvent {
18    pub entity: Entity,
19    pub button: MouseButton,
20    pub world_position: [f32; 3],
21}
22
23/// Held keys, mouse buttons, and cursor position for the current frame.
24///
25/// `just_pressed`/`just_released` sets are edge-triggered: they hold exactly
26/// the keys or buttons that changed state since the last call to
27/// [`RuntimeInput::clear_frame_edges`]. Runtime integrations call that method
28/// once per rendered frame after gameplay systems have had a chance to read
29/// them.
30///
31/// It serializes whole, so replays can record what each frame's systems saw.
32#[derive(
33    Resource, Clone, Debug, Default, PartialEq, Serialize, Deserialize,
34)]
35pub struct RuntimeInput {
36    keys_held: BTreeSet<KeyCode>,
37    keys_just_pressed: BTreeSet<KeyCode>,
38    keys_just_released: BTreeSet<KeyCode>,
39    mouse_held: BTreeSet<MouseButton>,
40    mouse_just_pressed: BTreeSet<MouseButton>,
41    mouse_just_released: BTreeSet<MouseButton>,
42    cursor_position: Option<[f32; 2]>,
43    viewport_size: [f32; 2],
44    mouse_motion: [f32; 2],
45    cursor_captured: bool,
46    #[serde(default)]
47    pad_held: BTreeSet<PadButton>,
48    #[serde(default)]
49    pad_just_pressed: BTreeSet<PadButton>,
50    #[serde(default)]
51    pad_just_released: BTreeSet<PadButton>,
52    #[serde(default)]
53    sticks: [[f32; 2]; 2],
54    /// When this frame's presses happened, in fractional fixed ticks.
55    #[serde(default)]
56    press_ticks: Vec<(InputBinding, f64)>,
57}
58
59/// A gamepad button, in the layout of an Xbox pad: `South` is A, `East` B.
60/// Every connected pad feeds the same state. Each stick also acts as four
61/// buttons (`LeftStickUp`, ...) that press past half tilt, so menus and
62/// digital actions can bind a stick.
63#[derive(
64    Clone,
65    Copy,
66    Debug,
67    PartialEq,
68    Eq,
69    PartialOrd,
70    Ord,
71    Hash,
72    Serialize,
73    Deserialize,
74)]
75pub enum PadButton {
76    South,
77    East,
78    West,
79    North,
80    LeftBumper,
81    RightBumper,
82    LeftTrigger,
83    RightTrigger,
84    Select,
85    Start,
86    LeftStick,
87    RightStick,
88    DpadUp,
89    DpadDown,
90    DpadLeft,
91    DpadRight,
92    LeftStickUp,
93    LeftStickDown,
94    LeftStickLeft,
95    LeftStickRight,
96    RightStickUp,
97    RightStickDown,
98    RightStickLeft,
99    RightStickRight,
100}
101
102/// Which stick [`RuntimeInput::stick`] reads.
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub enum Stick {
105    Left,
106    Right,
107}
108
109fn record_edge<T: Ord + Copy>(
110    held: &mut BTreeSet<T>,
111    pressed_now: &mut BTreeSet<T>,
112    released_now: &mut BTreeSet<T>,
113    item: T,
114    pressed: bool,
115) {
116    if pressed {
117        if held.insert(item) {
118            pressed_now.insert(item);
119        }
120    } else if held.remove(&item) {
121        released_now.insert(item);
122    }
123}
124
125impl RuntimeInput {
126    #[must_use]
127    pub fn key_held(&self, key: KeyCode) -> bool {
128        self.keys_held.contains(&key)
129    }
130    #[must_use]
131    pub fn key_just_pressed(&self, key: KeyCode) -> bool {
132        self.keys_just_pressed.contains(&key)
133    }
134    #[must_use]
135    pub fn key_just_released(&self, key: KeyCode) -> bool {
136        self.keys_just_released.contains(&key)
137    }
138    /// Keys pressed since the last [`Self::clear_frame_edges`], for a
139    /// "press any key" prompt.
140    pub fn keys_pressed(&self) -> impl Iterator<Item = KeyCode> + '_ {
141        self.keys_just_pressed.iter().copied()
142    }
143    /// Keys released since the last [`Self::clear_frame_edges`].
144    pub fn keys_released(&self) -> impl Iterator<Item = KeyCode> + '_ {
145        self.keys_just_released.iter().copied()
146    }
147    #[must_use]
148    pub fn mouse_held(&self, button: MouseButton) -> bool {
149        self.mouse_held.contains(&button)
150    }
151    #[must_use]
152    pub fn mouse_just_pressed(&self, button: MouseButton) -> bool {
153        self.mouse_just_pressed.contains(&button)
154    }
155    #[must_use]
156    pub fn mouse_just_released(&self, button: MouseButton) -> bool {
157        self.mouse_just_released.contains(&button)
158    }
159    #[must_use]
160    pub fn cursor_position(&self) -> Option<[f32; 2]> {
161        self.cursor_position
162    }
163
164    /// Raw mouse movement since the last [`Self::clear_frame_edges`]. It keeps
165    /// counting while the cursor is captured and cannot move.
166    #[must_use]
167    pub fn mouse_motion(&self) -> [f32; 2] {
168        self.mouse_motion
169    }
170
171    /// True when gameplay asked the window to hide and lock the cursor.
172    #[must_use]
173    pub fn cursor_captured(&self) -> bool {
174        self.cursor_captured
175    }
176
177    /// Asks the window to hide and lock the cursor, for mouse look. The
178    /// window runner applies the request after the frame's systems ran.
179    pub fn set_cursor_captured(&mut self, captured: bool) {
180        self.cursor_captured = captured;
181    }
182
183    /// Current window/render-viewport size in pixels, used to convert cursor
184    /// positions into normalized device coordinates for gameplay picking.
185    #[must_use]
186    pub fn viewport_size(&self) -> [f32; 2] {
187        self.viewport_size
188    }
189
190    /// Records one keyboard `WindowEvent`. Ignores OS auto-repeat: repeated
191    /// presses do not re-fire `just_pressed`.
192    pub fn record_key(&mut self, key: KeyCode, pressed: bool) {
193        if pressed {
194            if self.keys_held.insert(key) {
195                self.keys_just_pressed.insert(key);
196            }
197        } else if self.keys_held.remove(&key) {
198            self.keys_just_released.insert(key);
199        }
200    }
201
202    /// Records one mouse button `WindowEvent`.
203    pub fn record_mouse_button(&mut self, button: MouseButton, pressed: bool) {
204        if pressed {
205            if self.mouse_held.insert(button) {
206                self.mouse_just_pressed.insert(button);
207            }
208        } else if self.mouse_held.remove(&button) {
209            self.mouse_just_released.insert(button);
210        }
211    }
212
213    /// Releases every held key and button, reporting each as just released.
214    /// Call it when the window loses focus, because the matching release
215    /// events then go to another window.
216    pub fn release_all(&mut self) {
217        self.keys_just_released.append(&mut self.keys_held);
218        self.mouse_just_released.append(&mut self.mouse_held);
219        self.pad_just_released.append(&mut self.pad_held);
220        self.sticks = [[0.0; 2]; 2];
221    }
222
223    /// Records the latest cursor position from a `CursorMoved` event.
224    pub fn record_cursor_position(&mut self, position: [f32; 2]) {
225        self.cursor_position = Some(position);
226    }
227    /// Adds one raw `DeviceEvent::MouseMotion` delta.
228    pub fn record_mouse_motion(&mut self, delta: [f32; 2]) {
229        self.mouse_motion[0] += delta[0];
230        self.mouse_motion[1] += delta[1];
231    }
232    /// Records the current window/render-viewport size in pixels.
233    pub fn record_viewport_size(&mut self, size: [f32; 2]) {
234        self.viewport_size = size;
235    }
236
237    #[must_use]
238    pub fn pad_held(&self, button: PadButton) -> bool {
239        self.pad_held.contains(&button)
240    }
241    #[must_use]
242    pub fn pad_just_pressed(&self, button: PadButton) -> bool {
243        self.pad_just_pressed.contains(&button)
244    }
245    #[must_use]
246    pub fn pad_just_released(&self, button: PadButton) -> bool {
247        self.pad_just_released.contains(&button)
248    }
249    /// Pad buttons pressed since the last [`Self::clear_frame_edges`].
250    pub fn pads_pressed(&self) -> impl Iterator<Item = PadButton> + '_ {
251        self.pad_just_pressed.iter().copied()
252    }
253    /// Stick tilt, each axis -1..1; `[0, 1]` is pushed fully up.
254    #[must_use]
255    pub fn stick(&self, stick: Stick) -> [f32; 2] {
256        self.sticks[stick as usize]
257    }
258
259    /// Records one gamepad button press or release.
260    pub fn record_pad_button(&mut self, button: PadButton, pressed: bool) {
261        record_edge(
262            &mut self.pad_held,
263            &mut self.pad_just_pressed,
264            &mut self.pad_just_released,
265            button,
266            pressed,
267        );
268    }
269
270    /// Records a stick's tilt and presses or releases its four direction
271    /// buttons: pressed past 0.5, released below 0.3, so a stick resting
272    /// near the threshold does not flicker.
273    pub fn record_stick(&mut self, stick: Stick, tilt: [f32; 2]) {
274        use PadButton::*;
275        self.sticks[stick as usize] = tilt;
276        let [up, down, left, right] = match stick {
277            Stick::Left => {
278                [LeftStickUp, LeftStickDown, LeftStickLeft, LeftStickRight]
279            }
280            Stick::Right => [
281                RightStickUp,
282                RightStickDown,
283                RightStickLeft,
284                RightStickRight,
285            ],
286        };
287        for (button, amount) in [
288            (up, tilt[1]),
289            (down, -tilt[1]),
290            (left, -tilt[0]),
291            (right, tilt[0]),
292        ] {
293            if amount > 0.5 {
294                self.record_pad_button(button, true);
295            } else if amount < 0.3 {
296                self.record_pad_button(button, false);
297            }
298        }
299    }
300
301    /// Records when a press happened, in fractional fixed ticks. The
302    /// windowed runner calls it as key and mouse events arrive; the first
303    /// press of a binding in a frame wins.
304    pub fn record_press_tick(&mut self, binding: InputBinding, tick: f64) {
305        if self.press_tick(binding).is_none() {
306            self.press_ticks.push((binding, tick));
307        }
308    }
309
310    /// When `binding` was pressed this frame, if the runner recorded it.
311    #[must_use]
312    pub fn press_tick(&self, binding: InputBinding) -> Option<f64> {
313        self.press_ticks
314            .iter()
315            .find(|(bound, _)| *bound == binding)
316            .map(|(_, tick)| *tick)
317    }
318
319    /// Clears this frame's edge sets. Runtime integrations call this once per
320    /// rendered frame after gameplay systems have read them, so the next frame
321    /// starts empty.
322    pub fn clear_frame_edges(&mut self) {
323        self.keys_just_pressed.clear();
324        self.keys_just_released.clear();
325        self.mouse_just_pressed.clear();
326        self.mouse_just_released.clear();
327        self.pad_just_pressed.clear();
328        self.pad_just_released.clear();
329        self.press_ticks.clear();
330        self.mouse_motion = [0.0; 2];
331    }
332}
333
334/// A raw input source which can satisfy a named gameplay action.
335#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
336pub enum InputBinding {
337    Key(KeyCode),
338    Mouse(MouseButton),
339    Pad(PadButton),
340}
341
342/// Maps action names to one or more raw input bindings (any bound input
343/// satisfies the action).
344#[derive(Resource, Clone, Default)]
345pub struct ActionMap {
346    bindings: HashMap<String, Vec<InputBinding>>,
347}
348
349impl ActionMap {
350    pub fn bind(
351        &mut self,
352        action: impl Into<String>,
353        binding: InputBinding,
354    ) -> &mut Self {
355        self.bindings
356            .entry(action.into())
357            .or_default()
358            .push(binding);
359        self
360    }
361    /// Removes one binding of `action`; other bindings stay.
362    pub fn unbind(&mut self, action: &str, binding: InputBinding) {
363        if let Some(list) = self.bindings.get_mut(action) {
364            list.retain(|bound| *bound != binding);
365            if list.is_empty() {
366                self.bindings.remove(action);
367            }
368        }
369    }
370    #[must_use]
371    pub fn held(&self, input: &RuntimeInput, action: &str) -> bool {
372        self.bindings_for(action).any(|binding| match binding {
373            InputBinding::Key(key) => input.key_held(*key),
374            InputBinding::Mouse(button) => input.mouse_held(*button),
375            InputBinding::Pad(button) => input.pad_held(*button),
376        })
377    }
378    #[must_use]
379    pub fn just_pressed(&self, input: &RuntimeInput, action: &str) -> bool {
380        self.bindings_for(action).any(|binding| match binding {
381            InputBinding::Key(key) => input.key_just_pressed(*key),
382            InputBinding::Mouse(button) => input.mouse_just_pressed(*button),
383            InputBinding::Pad(button) => input.pad_just_pressed(*button),
384        })
385    }
386    #[must_use]
387    pub fn just_released(&self, input: &RuntimeInput, action: &str) -> bool {
388        self.bindings_for(action).any(|binding| match binding {
389            InputBinding::Key(key) => input.key_just_released(*key),
390            InputBinding::Mouse(button) => input.mouse_just_released(*button),
391            InputBinding::Pad(button) => input.pad_just_released(*button),
392        })
393    }
394    /// The earliest recorded time, in fractional fixed ticks, of a binding of
395    /// `action` pressed this frame.
396    #[must_use]
397    pub fn press_tick(
398        &self,
399        input: &RuntimeInput,
400        action: &str,
401    ) -> Option<f64> {
402        self.bindings_for(action)
403            .filter_map(|binding| input.press_tick(*binding))
404            .reduce(f64::min)
405    }
406    /// Inputs bound to `action`, in binding order; empty when unbound.
407    #[must_use]
408    pub fn bindings(&self, action: &str) -> &[InputBinding] {
409        self.bindings.get(action).map_or(&[], Vec::as_slice)
410    }
411    fn bindings_for(
412        &self,
413        action: &str,
414    ) -> impl Iterator<Item = &InputBinding> {
415        self.bindings.get(action).into_iter().flatten()
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use bevy_ecs::prelude::Resource;
423
424    #[test]
425    fn mouse_motion_adds_up_until_the_frame_ends() {
426        let mut input = RuntimeInput::default();
427        input.record_mouse_motion([1.0, -2.0]);
428        input.record_mouse_motion([0.5, 1.0]);
429        assert_eq!(input.mouse_motion(), [1.5, -1.0]);
430        input.clear_frame_edges();
431        assert_eq!(input.mouse_motion(), [0.0, 0.0]);
432    }
433
434    #[test]
435    fn release_all_clears_held_input_as_releases() {
436        let mut input = RuntimeInput::default();
437        input.record_key(KeyCode::KeyW, true);
438        input.record_mouse_button(MouseButton::Right, true);
439        input.clear_frame_edges();
440        input.release_all();
441        assert!(!input.key_held(KeyCode::KeyW));
442        assert!(input.key_just_released(KeyCode::KeyW));
443        assert!(input.mouse_just_released(MouseButton::Right));
444    }
445
446    #[test]
447    fn pad_buttons_and_stick_directions_drive_actions() {
448        let mut map = ActionMap::default();
449        map.bind("jump", InputBinding::Pad(PadButton::South))
450            .bind("up", InputBinding::Pad(PadButton::LeftStickUp));
451        let mut input = RuntimeInput::default();
452        input.record_pad_button(PadButton::South, true);
453        assert!(map.just_pressed(&input, "jump"));
454        input.record_stick(Stick::Left, [0.0, 0.6]);
455        assert!(map.just_pressed(&input, "up"));
456        assert_eq!(input.stick(Stick::Left), [0.0, 0.6]);
457        input.clear_frame_edges();
458        // Between the thresholds the direction stays held.
459        input.record_stick(Stick::Left, [0.0, 0.4]);
460        assert!(map.held(&input, "up"));
461        input.record_stick(Stick::Left, [0.0, 0.1]);
462        assert!(map.just_released(&input, "up"));
463        input.release_all();
464        assert!(map.just_released(&input, "jump"));
465    }
466
467    #[test]
468    fn runtime_input_and_action_map_are_ecs_resources() {
469        fn assert_resource<T: Resource>() {}
470        assert_resource::<RuntimeInput>();
471        assert_resource::<ActionMap>();
472    }
473    #[test]
474    fn keyboard_edges_and_auto_repeat_are_tracked() {
475        let mut input = RuntimeInput::default();
476        input.record_key(KeyCode::Space, true);
477        assert!(input.key_held(KeyCode::Space));
478        assert!(input.key_just_pressed(KeyCode::Space));
479        input.record_key(KeyCode::Space, true);
480        input.clear_frame_edges();
481        assert!(input.key_held(KeyCode::Space));
482        assert!(!input.key_just_pressed(KeyCode::Space));
483        input.record_key(KeyCode::Space, false);
484        assert!(input.key_just_released(KeyCode::Space));
485    }
486    #[test]
487    fn mouse_cursor_and_viewport_are_tracked() {
488        let mut input = RuntimeInput::default();
489        input.record_mouse_button(MouseButton::Left, true);
490        input.record_cursor_position([12.0, 34.0]);
491        input.record_viewport_size([800.0, 600.0]);
492        assert!(input.mouse_held(MouseButton::Left));
493        assert!(input.mouse_just_pressed(MouseButton::Left));
494        assert_eq!(input.cursor_position(), Some([12.0, 34.0]));
495        assert_eq!(input.viewport_size(), [800.0, 600.0]);
496        input.clear_frame_edges();
497        input.record_mouse_button(MouseButton::Left, false);
498        assert!(input.mouse_just_released(MouseButton::Left));
499        assert!(!input.mouse_held(MouseButton::Left));
500    }
501    #[test]
502    fn actions_cover_keyboard_mouse_and_edge_clearing() {
503        let mut map = ActionMap::default();
504        map.bind("jump", InputBinding::Key(KeyCode::Space))
505            .bind("jump", InputBinding::Mouse(MouseButton::Left));
506        let mut input = RuntimeInput::default();
507        input.record_key(KeyCode::Space, true);
508        assert!(map.just_pressed(&input, "jump"));
509        assert!(map.held(&input, "jump"));
510        input.clear_frame_edges();
511        assert!(!map.just_pressed(&input, "jump"));
512        assert!(map.held(&input, "jump"));
513        input.record_key(KeyCode::Space, false);
514        assert!(map.just_released(&input, "jump"));
515        input.clear_frame_edges();
516        input.record_mouse_button(MouseButton::Left, true);
517        assert!(map.just_pressed(&input, "jump"));
518        assert!(map.held(&input, "jump"));
519        assert!(!map.held(&input, "unbound_action"));
520    }
521}