Skip to main content

euv_core/game/input/
impl.rs

1use super::*;
2
3/// Per-frame input ingestion and real-time polling helpers for `InputState`.
4impl InputState {
5    /// Clears transient per-frame edge states (`just_pressed`, `just_released`, deltas) after a frame step.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable input state.
10    pub fn begin_frame(&mut self) {
11        self.get_mut_keys_just_pressed().clear();
12        self.get_mut_keys_just_released().clear();
13        self.set_pointer_delta(Point::new(0.0, 0.0));
14        self.set_scroll_delta(Point::new(0.0, 0.0));
15    }
16
17    /// Updates continuous and edge-triggered states from a platform `WindowEvent`.
18    ///
19    /// # Arguments
20    ///
21    /// - `&Self` - Mutable input state.
22    /// - `&WindowEvent` - Incoming OS or test event.
23    pub fn ingest(&mut self, event: &WindowEvent) {
24        match event {
25            WindowEvent::KeyDown(_, key) => {
26                let code: KeyCode = key.get_code();
27                if self.get_mut_keys_down().insert(code) {
28                    let _: bool = self.get_mut_keys_just_pressed().insert(code);
29                }
30            }
31            WindowEvent::KeyUp(_, key) => {
32                let code: KeyCode = key.get_code();
33                if self.get_mut_keys_down().remove(&code) {
34                    let _: bool = self.get_mut_keys_just_released().insert(code);
35                }
36            }
37            WindowEvent::PointerMove(_, ptr) => {
38                let prev: Point = self.get_pointer_position();
39                let next: Point = ptr.get_position();
40                let delta: Point = self.get_pointer_delta();
41                self.set_pointer_delta(Point::new(
42                    delta.get_x() + (next.get_x() - prev.get_x()),
43                    delta.get_y() + (next.get_y() - prev.get_y()),
44                ));
45                self.set_pointer_position(next);
46            }
47            WindowEvent::PointerDown(_, ptr) => {
48                self.set_pointer_position(ptr.get_position());
49                let _: bool = self.get_mut_buttons_down().insert(ptr.get_button());
50            }
51            WindowEvent::PointerUp(_, ptr) => {
52                self.set_pointer_position(ptr.get_position());
53                let _: bool = self.get_mut_buttons_down().remove(&ptr.get_button());
54            }
55            WindowEvent::Scroll(_, delta) => {
56                let cur: Point = self.get_scroll_delta();
57                self.set_scroll_delta(Point::new(
58                    cur.get_x() + delta.get_x(),
59                    cur.get_y() + delta.get_y(),
60                ));
61            }
62            WindowEvent::Focused(_, false) => {
63                self.get_mut_keys_down().clear();
64                self.get_mut_buttons_down().clear();
65            }
66            _ => {}
67        }
68    }
69
70    /// Returns `true` while `key` is held down.
71    ///
72    /// # Arguments
73    ///
74    /// - `&Self` - Input state reference.
75    /// - `KeyCode` - Key to query.
76    ///
77    /// # Returns
78    ///
79    /// - `bool` - Whether the key is held.
80    #[must_use]
81    pub fn is_key_down(&self, key: KeyCode) -> bool {
82        self.get_keys_down().contains(&key)
83    }
84
85    /// Returns `true` if `key` transitioned from up to down during the current frame.
86    ///
87    /// # Arguments
88    ///
89    /// - `&Self` - Input state reference.
90    /// - `KeyCode` - Key to query.
91    ///
92    /// # Returns
93    ///
94    /// - `bool` - Whether the key was just pressed.
95    #[must_use]
96    pub fn is_key_just_pressed(&self, key: KeyCode) -> bool {
97        self.get_keys_just_pressed().contains(&key)
98    }
99
100    /// Returns `true` while pointer `button` is held down.
101    ///
102    /// # Arguments
103    ///
104    /// - `&Self` - Input state reference.
105    /// - `PointerButton` - Button to query.
106    ///
107    /// # Returns
108    ///
109    /// - `bool` - Whether the button is held.
110    #[must_use]
111    pub fn is_button_down(&self, button: PointerButton) -> bool {
112        self.get_buttons_down().contains(&button)
113    }
114
115    /// Computes a normalized `-1.0..=1.0` movement axis from negative and positive key bindings.
116    ///
117    /// # Arguments
118    ///
119    /// - `&Self` - Input state reference.
120    /// - `KeyCode` - Negative direction key.
121    /// - `KeyCode` - Positive direction key.
122    ///
123    /// # Returns
124    ///
125    /// - `f32` - Axis value in `{-1.0, 0.0, 1.0}`.
126    #[must_use]
127    pub fn axis(&self, negative: KeyCode, positive: KeyCode) -> f32 {
128        let mut value: f32 = 0.0;
129        if self.is_key_down(negative) {
130            value -= 1.0;
131        }
132        if self.is_key_down(positive) {
133            value += 1.0;
134        }
135        value
136    }
137
138    /// Sets the normalized analog virtual stick vector `(dx, dy)` for mobile touch joysticks or gamepads.
139    ///
140    /// # Arguments
141    ///
142    /// - `&Self` - Mutable input state.
143    /// - `f32` - Horizontal axis in `[-1.0, 1.0]`.
144    /// - `f32` - Vertical axis in `[-1.0, 1.0]`.
145    pub fn set_virtual_stick(&mut self, dx: f32, dy: f32) {
146        self.set_virtual_axis(Point::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)));
147    }
148
149    /// Resets the virtual analog stick to neutral `(0.0, 0.0)`.
150    ///
151    /// # Arguments
152    ///
153    /// - `&Self` - Mutable input state.
154    pub fn clear_virtual_stick(&mut self) {
155        self.set_virtual_axis(Point::new(0.0, 0.0));
156    }
157}
158
159/// Default arcade action map binding WASD + Arrows, Space/Click fire, Shift/E dash, and P/Esc pause.
160impl Default for ActionMap {
161    /// Creates an `ActionMap` pre-populated with standard desktop/web arcade controls.
162    ///
163    /// # Returns
164    ///
165    /// - `Self` - Standard arcade action map.
166    fn default() -> Self {
167        let mut map: Self = Self {
168            key_bindings: HashMap::new(),
169            button_bindings: HashMap::new(),
170        };
171        map.bind_key(GameAction::MoveLeft, KeyCode::ArrowLeft);
172        map.bind_key(GameAction::MoveLeft, KeyCode::Character('a'));
173        map.bind_key(GameAction::MoveLeft, KeyCode::Character('A'));
174        map.bind_key(GameAction::MoveRight, KeyCode::ArrowRight);
175        map.bind_key(GameAction::MoveRight, KeyCode::Character('d'));
176        map.bind_key(GameAction::MoveRight, KeyCode::Character('D'));
177        map.bind_key(GameAction::MoveUp, KeyCode::ArrowUp);
178        map.bind_key(GameAction::MoveUp, KeyCode::Character('w'));
179        map.bind_key(GameAction::MoveUp, KeyCode::Character('W'));
180        map.bind_key(GameAction::MoveDown, KeyCode::ArrowDown);
181        map.bind_key(GameAction::MoveDown, KeyCode::Character('s'));
182        map.bind_key(GameAction::MoveDown, KeyCode::Character('S'));
183        map.bind_key(GameAction::Fire, KeyCode::Space);
184        map.bind_key(GameAction::Fire, KeyCode::Character('j'));
185        map.bind_button(GameAction::Fire, PointerButton::Primary);
186        map.bind_key(GameAction::Dash, KeyCode::Character('e'));
187        map.bind_key(GameAction::Dash, KeyCode::Character('E'));
188        map.bind_key(GameAction::Jump, KeyCode::Space);
189        map.bind_key(GameAction::Pause, KeyCode::Escape);
190        map.bind_key(GameAction::Pause, KeyCode::Character('p'));
191        map.bind_key(GameAction::ActionAlt, KeyCode::Character('r'));
192        map.bind_key(GameAction::ActionAlt, KeyCode::Character('R'));
193        map
194    }
195}
196
197/// Binding registration and real-time input queries for `ActionMap`.
198impl ActionMap {
199    /// Binds a `KeyCode` to `action`.
200    ///
201    /// # Arguments
202    ///
203    /// - `&Self` - Mutable action map.
204    /// - `GameAction` - Semantic game action.
205    /// - `KeyCode` - Keyboard key to bind.
206    pub fn bind_key(&mut self, action: GameAction, key: KeyCode) {
207        self.get_mut_key_bindings()
208            .entry(action)
209            .or_default()
210            .push(key);
211    }
212
213    /// Binds a `PointerButton` to `action`.
214    ///
215    /// # Arguments
216    ///
217    /// - `&Self` - Mutable action map.
218    /// - `GameAction` - Semantic game action.
219    /// - `PointerButton` - Mouse/touch button to bind.
220    pub fn bind_button(&mut self, action: GameAction, button: PointerButton) {
221        self.get_mut_button_bindings()
222            .entry(action)
223            .or_default()
224            .push(button);
225    }
226
227    /// Returns `true` while any key or button bound to `action` is held in `input`.
228    ///
229    /// # Arguments
230    ///
231    /// - `&Self` - Action map reference.
232    /// - `GameAction` - Action to query.
233    /// - `&InputState` - Current polled input snapshot.
234    ///
235    /// # Returns
236    ///
237    /// - `bool` - Whether `action` is currently active.
238    #[must_use]
239    pub fn is_active(&self, action: GameAction, input: &InputState) -> bool {
240        if action == GameAction::Fire && input.get_virtual_fire() {
241            return true;
242        }
243        if action == GameAction::Dash && input.get_virtual_dash() {
244            return true;
245        }
246        let key_hit: bool = self
247            .get_key_bindings()
248            .get(&action)
249            .map(|keys: &Vec<KeyCode>| keys.iter().copied().any(|k: KeyCode| input.is_key_down(k)))
250            .unwrap_or(false);
251        if key_hit {
252            return true;
253        }
254        self.get_button_bindings()
255            .get(&action)
256            .map(|btns: &Vec<PointerButton>| {
257                btns.iter()
258                    .copied()
259                    .any(|b: PointerButton| input.is_button_down(b))
260            })
261            .unwrap_or(false)
262    }
263
264    /// Returns `true` when any key bound to `action` transitioned down on this frame.
265    ///
266    /// # Arguments
267    ///
268    /// - `&Self` - Action map reference.
269    /// - `GameAction` - Action to query.
270    /// - `&InputState` - Current polled input snapshot.
271    ///
272    /// # Returns
273    ///
274    /// - `bool` - Whether `action` was just triggered.
275    #[must_use]
276    pub fn is_just_pressed(&self, action: GameAction, input: &InputState) -> bool {
277        self.get_key_bindings()
278            .get(&action)
279            .map(|keys: &Vec<KeyCode>| {
280                keys.iter()
281                    .copied()
282                    .any(|k: KeyCode| input.is_key_just_pressed(k))
283            })
284            .unwrap_or(false)
285    }
286
287    /// Computes a normalized 2D movement vector `(dx, dy)` from directional action bindings.
288    ///
289    /// # Arguments
290    ///
291    /// - `&Self` - Action map reference.
292    /// - `&InputState` - Current polled input snapshot.
293    ///
294    /// # Returns
295    ///
296    /// - `Point` - Normalized movement vector with length `<= 1.0`.
297    #[must_use]
298    pub fn movement_vector(&self, input: &InputState) -> Point {
299        let mut dx: f32 = input.get_virtual_axis().get_x();
300        let mut dy: f32 = input.get_virtual_axis().get_y();
301        if self.is_active(GameAction::MoveLeft, input) {
302            dx -= 1.0;
303        }
304        if self.is_active(GameAction::MoveRight, input) {
305            dx += 1.0;
306        }
307        if self.is_active(GameAction::MoveUp, input) {
308            dy -= 1.0;
309        }
310        if self.is_active(GameAction::MoveDown, input) {
311            dy += 1.0;
312        }
313        let len: f32 = (dx * dx + dy * dy).sqrt();
314        if len > 1.0 {
315            Point::new(dx / len, dy / len)
316        } else {
317            Point::new(dx, dy)
318        }
319    }
320}