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