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