Skip to main content

rayengine_core/
input.rs

1//! Action input whose edges survive render frames and are consumed per tick.
2
3use glam::Vec2;
4
5/// Small numeric action key, normally declared as a game-level constant.
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub struct Action(pub u16);
8
9#[derive(Clone, Copy, Debug, Default)]
10struct State {
11    down: bool,
12    pressed: bool,
13    released: bool,
14}
15
16/// Contiguous action states; reads and sampling allocate nothing after setup.
17///
18/// Multiple physical bindings must be ORed before calling [`Self::set`].
19/// Consume edges after each fixed update, not after every render frame.
20///
21/// ```
22/// use rayengine_core::input::{Action, Input};
23/// const JUMP: Action = Action(0);
24/// let mut input = Input::with_capacity(1);
25/// input.set(JUMP, true);
26/// assert!(input.pressed(JUMP));
27/// input.consume_edges();
28/// assert!(input.down(JUMP));
29/// assert!(!input.pressed(JUMP));
30/// ```
31#[derive(Debug, Default)]
32pub struct Input {
33    states: Vec<State>,
34    pointer_delta: Vec2,
35    reset_pending: bool,
36}
37
38impl Input {
39    /// Borrows action input with explicit per-update masks, without changing the
40    /// original states or allocating. Block UI-owned actions and relative look
41    /// motion before passing this view to gameplay. Held actions resume when
42    /// unmasked; edges still follow the caller's normal tick consumption.
43    pub fn routed<'a>(&'a self, blocked: &'a [Action], block_motion: bool) -> InputView<'a> {
44        InputView {
45            input: self,
46            blocked,
47            block_motion,
48        }
49    }
50    /// Preallocates action slots to avoid allocation during input sampling.
51    pub fn with_capacity(actions: usize) -> Self {
52        Self {
53            states: vec![State::default(); actions],
54            pointer_delta: Vec2::ZERO,
55            reset_pending: false,
56        }
57    }
58
59    /// Samples a combined action state. Automatically grows for new action IDs.
60    pub fn set(&mut self, action: Action, down: bool) {
61        let index = usize::from(action.0);
62        if index >= self.states.len() {
63            self.states.resize(index + 1, State::default());
64        }
65        let state = &mut self.states[index];
66        state.pressed |= down && !state.down;
67        state.released |= !down && state.down;
68        state.down = down;
69    }
70
71    /// Whether an action is currently held.
72    pub fn down(&self, action: Action) -> bool {
73        self.states
74            .get(usize::from(action.0))
75            .is_some_and(|s| s.down)
76    }
77
78    /// Whether an action was pressed since the last consumed tick.
79    pub fn pressed(&self, action: Action) -> bool {
80        self.states
81            .get(usize::from(action.0))
82            .is_some_and(|s| s.pressed)
83    }
84
85    /// Whether an action was released since the last consumed tick.
86    pub fn released(&self, action: Action) -> bool {
87        self.states
88            .get(usize::from(action.0))
89            .is_some_and(|s| s.released)
90    }
91
92    /// Digital axis in `[-1, 1]`; opposing held actions cancel.
93    pub fn axis(&self, negative: Action, positive: Action) -> f32 {
94        f32::from(self.down(positive)) - f32::from(self.down(negative))
95    }
96
97    /// Accumulates relative pointer motion sampled between fixed updates.
98    /// The SDK supplies logical window units, independent of viewport scaling.
99    /// Panics for nonfinite motion.
100    pub fn add_pointer_delta(&mut self, delta: Vec2) {
101        assert!(delta.is_finite());
102        self.pointer_delta += delta;
103    }
104
105    /// Relative pointer motion since the previous consumed tick.
106    /// Apply sensitivity directly; this is displacement, not velocity.
107    pub fn pointer_delta(&self) -> Vec2 {
108        self.pointer_delta
109    }
110
111    /// Whether focus loss/reset occurred since the previous consumed tick.
112    /// Retained through paused render frames so UI capture can be cancelled
113    /// even if the window regains focus before simulation resumes.
114    pub fn reset_pending(&self) -> bool {
115        self.reset_pending
116    }
117
118    /// Clears transitions and pointer motion after one fixed update, preserving held actions.
119    pub fn consume_edges(&mut self) {
120        for state in &mut self.states {
121            state.pressed = false;
122            state.released = false;
123        }
124        self.pointer_delta = Vec2::ZERO;
125        self.reset_pending = false;
126    }
127
128    /// Releases every held action, e.g. on focus loss. Releases are observable.
129    pub fn release_all(&mut self) {
130        self.reset_pending = true;
131        for state in &mut self.states {
132            state.released |= state.down;
133            state.down = false;
134        }
135        self.pointer_delta = Vec2::ZERO;
136    }
137}
138
139/// Read-only gameplay input with game-chosen action and pointer-motion masks.
140#[derive(Clone, Copy, Debug)]
141pub struct InputView<'a> {
142    input: &'a Input,
143    blocked: &'a [Action],
144    block_motion: bool,
145}
146
147impl InputView<'_> {
148    /// Whether an unmasked action is held.
149    pub fn down(&self, action: Action) -> bool {
150        !self.blocked.contains(&action) && self.input.down(action)
151    }
152
153    /// Whether an unmasked action was pressed.
154    pub fn pressed(&self, action: Action) -> bool {
155        !self.blocked.contains(&action) && self.input.pressed(action)
156    }
157
158    /// Whether an unmasked action was released.
159    pub fn released(&self, action: Action) -> bool {
160        !self.blocked.contains(&action) && self.input.released(action)
161    }
162
163    /// Digital axis with masked actions contributing zero.
164    pub fn axis(&self, negative: Action, positive: Action) -> f32 {
165        f32::from(self.down(positive)) - f32::from(self.down(negative))
166    }
167
168    /// Relative look motion, or zero while the UI owns it.
169    pub fn pointer_delta(&self) -> Vec2 {
170        if self.block_motion {
171            Vec2::ZERO
172        } else {
173            self.input.pointer_delta()
174        }
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn transitions_survive_frames_but_only_fire_on_one_tick() {
184        let mut input = Input::default();
185        input.set(Action(2), true);
186        input.set(Action(2), true); // Another render frame before a simulation tick.
187        assert!(input.pressed(Action(2)));
188        input.consume_edges();
189        assert!(!input.pressed(Action(2)));
190        assert!(input.down(Action(2)));
191        input.set(Action(2), false);
192        assert!(input.released(Action(2)));
193    }
194
195    #[test]
196    fn quick_tap_keeps_both_edges() {
197        let mut input = Input::default();
198        input.set(Action(0), true);
199        input.set(Action(0), false);
200        assert!(input.pressed(Action(0)) && input.released(Action(0)));
201        assert!(!input.down(Action(0)));
202    }
203
204    #[test]
205    fn unknown_actions_and_focus_loss_are_safe() {
206        let mut input = Input::default();
207        assert_eq!(input.axis(Action(0), Action(1)), 0.0);
208        input.set(Action(1), true);
209        input.release_all();
210        assert!(!input.down(Action(1)));
211        assert!(input.released(Action(1)));
212    }
213
214    #[test]
215    fn relative_motion_accumulates_until_one_tick_and_is_not_repeated_during_catch_up() {
216        let mut input = Input::with_capacity(1);
217        input.set(Action(0), true);
218        input.add_pointer_delta(Vec2::new(4.0, -2.0));
219        input.add_pointer_delta(Vec2::new(3.0, 1.0));
220        assert_eq!(input.pointer_delta(), Vec2::new(7.0, -1.0));
221        input.consume_edges();
222        assert_eq!(input.pointer_delta(), Vec2::ZERO);
223        assert!(input.down(Action(0)));
224        input.consume_edges();
225        assert_eq!(input.pointer_delta(), Vec2::ZERO);
226        input.add_pointer_delta(Vec2::new(-2.0, 3.0));
227        input.release_all();
228        assert_eq!(input.pointer_delta(), Vec2::ZERO);
229    }
230}