euv_core/game/input/impl.rs
1use super::*;
2
3/// Zero-allocation 256-bit keyboard state operations for `KeyBitset`.
4impl KeyBitset {
5 /// Maps a `KeyCode` into a deterministic bit index in `0..256`.
6 ///
7 /// # Arguments
8 ///
9 /// - `KeyCode` - Keyboard key code to encode.
10 ///
11 /// # Returns
12 ///
13 /// - `usize` - Bit index in `0..256`.
14 #[inline(always)]
15 #[must_use]
16 pub const fn key_bit_index(key: KeyCode) -> usize {
17 match key {
18 KeyCode::Unknown => 0,
19 KeyCode::Enter => 1,
20 KeyCode::Escape => 2,
21 KeyCode::Back => 3,
22 KeyCode::Tab => 4,
23 KeyCode::Backspace => 5,
24 KeyCode::Delete => 6,
25 KeyCode::Space => 7,
26 KeyCode::ArrowUp => 8,
27 KeyCode::ArrowDown => 9,
28 KeyCode::ArrowLeft => 10,
29 KeyCode::ArrowRight => 11,
30 KeyCode::Home => 12,
31 KeyCode::End => 13,
32 KeyCode::PageUp => 14,
33 KeyCode::PageDown => 15,
34 KeyCode::Character(ch) => {
35 let code: u32 = ch as u32;
36 if code < 128 {
37 32 + (code as usize)
38 } else {
39 160 + ((code as usize) % 96)
40 }
41 }
42 }
43 }
44
45 /// Clears all recorded key bits in O(1).
46 ///
47 /// # Arguments
48 ///
49 /// - `&Self` - Mutable key bitset.
50 #[inline(always)]
51 pub fn clear(&mut self) {
52 self.set_words([0; 4]);
53 }
54
55 /// Returns `true` when zero key bits are set.
56 ///
57 /// # Arguments
58 ///
59 /// - `&Self` - Key bitset reference.
60 ///
61 /// # Returns
62 ///
63 /// - `bool` - `true` when empty.
64 #[inline(always)]
65 #[must_use]
66 pub fn is_empty(&self) -> bool {
67 let w: [u64; 4] = self.get_words();
68 let lo: u64 = w[0] | w[1];
69 let hi: u64 = w[2] | w[3];
70 (lo | hi) == 0
71 }
72
73 /// Sets the bit for `key`, returning `true` if the bit transitioned from `0` to `1`.
74 ///
75 /// # Arguments
76 ///
77 /// - `&Self` - Mutable key bitset.
78 /// - `KeyCode` - Key code to mark set.
79 ///
80 /// # Returns
81 ///
82 /// - `bool` - `true` if `key` was not already set.
83 #[inline(always)]
84 pub fn insert(&mut self, key: KeyCode) -> bool {
85 let idx: usize = Self::key_bit_index(key);
86 let word_idx: usize = idx >> 6;
87 let bit_mask: u64 = 1_u64 << (idx & 63);
88 let mut w: [u64; 4] = self.get_words();
89 let was_set: bool = (w[word_idx] & bit_mask) != 0;
90 w[word_idx] |= bit_mask;
91 self.set_words(w);
92 !was_set
93 }
94
95 /// Clears the bit for `key`, returning `true` if the bit transitioned from `1` to `0`.
96 ///
97 /// # Arguments
98 ///
99 /// - `&Self` - Mutable key bitset.
100 /// - `&KeyCode` - Key code to clear.
101 ///
102 /// # Returns
103 ///
104 /// - `bool` - `true` if `key` was previously set.
105 #[inline(always)]
106 pub fn remove(&mut self, key: &KeyCode) -> bool {
107 let idx: usize = Self::key_bit_index(*key);
108 let word_idx: usize = idx >> 6;
109 let bit_mask: u64 = 1_u64 << (idx & 63);
110 let mut w: [u64; 4] = self.get_words();
111 let was_set: bool = (w[word_idx] & bit_mask) != 0;
112 w[word_idx] &= !bit_mask;
113 self.set_words(w);
114 was_set
115 }
116
117 /// Returns `true` when the bit for `key` is set.
118 ///
119 /// # Arguments
120 ///
121 /// - `&Self` - Key bitset reference.
122 /// - `&KeyCode` - Key code to query.
123 ///
124 /// # Returns
125 ///
126 /// - `bool` - `true` if set.
127 #[inline(always)]
128 #[must_use]
129 pub fn contains(&self, key: &KeyCode) -> bool {
130 let idx: usize = Self::key_bit_index(*key);
131 let word_idx: usize = idx >> 6;
132 let bit_mask: u64 = 1_u64 << (idx & 63);
133 (self.get_words()[word_idx] & bit_mask) != 0
134 }
135}
136
137/// Zero-allocation 16-bit pointer button operations for `ButtonBitset`.
138impl ButtonBitset {
139 /// Maps a `PointerButton` into a deterministic bit mask in `u16`.
140 ///
141 /// # Arguments
142 ///
143 /// - `PointerButton` - Pointer button to encode.
144 ///
145 /// # Returns
146 ///
147 /// - `u16` - Single-bit mask for the button.
148 #[inline(always)]
149 #[must_use]
150 pub const fn button_mask(button: PointerButton) -> u16 {
151 match button {
152 PointerButton::Primary => 1_u16 << 0,
153 PointerButton::Secondary => 1_u16 << 1,
154 PointerButton::Auxiliary => 1_u16 << 2,
155 }
156 }
157
158 /// Clears all recorded button bits in O(1).
159 ///
160 /// # Arguments
161 ///
162 /// - `&Self` - Mutable button bitset.
163 #[inline(always)]
164 pub fn clear(&mut self) {
165 self.set_mask(0);
166 }
167
168 /// Returns `true` when zero button bits are set.
169 ///
170 /// # Arguments
171 ///
172 /// - `&Self` - Button bitset reference.
173 ///
174 /// # Returns
175 ///
176 /// - `bool` - `true` when empty.
177 #[inline(always)]
178 #[must_use]
179 pub fn is_empty(&self) -> bool {
180 self.get_mask() == 0
181 }
182
183 /// Sets the bit for `button`, returning `true` if the bit transitioned from `0` to `1`.
184 ///
185 /// # Arguments
186 ///
187 /// - `&Self` - Mutable button bitset.
188 /// - `PointerButton` - Button to mark set.
189 ///
190 /// # Returns
191 ///
192 /// - `bool` - `true` if `button` was not already set.
193 #[inline(always)]
194 pub fn insert(&mut self, button: PointerButton) -> bool {
195 let bit: u16 = Self::button_mask(button);
196 let cur: u16 = self.get_mask();
197 let was_set: bool = (cur & bit) != 0;
198 self.set_mask(cur | bit);
199 !was_set
200 }
201
202 /// Clears the bit for `button`, returning `true` if the bit transitioned from `1` to `0`.
203 ///
204 /// # Arguments
205 ///
206 /// - `&Self` - Mutable button bitset.
207 /// - `&PointerButton` - Button to clear.
208 ///
209 /// # Returns
210 ///
211 /// - `bool` - `true` if `button` was previously set.
212 #[inline(always)]
213 pub fn remove(&mut self, button: &PointerButton) -> bool {
214 let bit: u16 = Self::button_mask(*button);
215 let cur: u16 = self.get_mask();
216 let was_set: bool = (cur & bit) != 0;
217 self.set_mask(cur & !bit);
218 was_set
219 }
220
221 /// Returns `true` when the bit for `button` is set.
222 ///
223 /// # Arguments
224 ///
225 /// - `&Self` - Button bitset reference.
226 /// - `&PointerButton` - Button to query.
227 ///
228 /// # Returns
229 ///
230 /// - `bool` - `true` if set.
231 #[inline(always)]
232 #[must_use]
233 pub fn contains(&self, button: &PointerButton) -> bool {
234 (self.get_mask() & Self::button_mask(*button)) != 0
235 }
236}
237
238/// Per-frame input ingestion and real-time polling helpers for `InputState`.
239impl InputState {
240 /// Clears transient per-frame edge states (`just_pressed`, `just_released`, deltas) after a frame step.
241 ///
242 /// # Arguments
243 ///
244 /// - `&Self` - Mutable input state.
245 pub fn begin_frame(&mut self) {
246 self.get_mut_keys_just_pressed().clear();
247 self.get_mut_keys_just_released().clear();
248 self.get_mut_buttons_just_pressed().clear();
249 self.get_mut_buttons_just_released().clear();
250 self.set_pointer_delta(Point::new(0.0, 0.0));
251 self.set_scroll_delta(Point::new(0.0, 0.0));
252 }
253
254 /// Returns a zero-allocation `Copy` snapshot containing held keys/buttons and axes with all transient edge events cleared.
255 ///
256 /// Used when executing subsequent fixed-timestep substeps so press/release edges are consumed exactly once.
257 ///
258 /// # Arguments
259 ///
260 /// - `&Self` - Input state reference.
261 ///
262 /// # Returns
263 ///
264 /// - `Self` - Edge-cleared input snapshot preserving held state.
265 #[must_use]
266 pub fn without_edges(&self) -> Self {
267 let mut copy: Self = *self;
268 copy.begin_frame();
269 copy
270 }
271
272 /// Returns `true` when any transient edge (`just_pressed`, `just_released`, pointer/scroll delta) is latched.
273 ///
274 /// # Arguments
275 ///
276 /// - `&Self` - Input state reference.
277 ///
278 /// # Returns
279 ///
280 /// - `bool` - Whether pending edge events remain unconsumed.
281 #[must_use]
282 pub fn has_pending_edges(&self) -> bool {
283 let key_edges: bool =
284 !self.get_keys_just_pressed().is_empty() || !self.get_keys_just_released().is_empty();
285 let btn_edges: bool = !self.get_buttons_just_pressed().is_empty()
286 || !self.get_buttons_just_released().is_empty();
287 let p_delta: Point = self.get_pointer_delta();
288 let s_delta: Point = self.get_scroll_delta();
289 let motion_edges: bool = p_delta.get_x() != 0.0
290 || p_delta.get_y() != 0.0
291 || s_delta.get_x() != 0.0
292 || s_delta.get_y() != 0.0;
293 if key_edges || btn_edges {
294 true
295 } else {
296 motion_edges
297 }
298 }
299
300 /// Updates continuous and edge-triggered states from a platform `WindowEvent`.
301 ///
302 /// # Arguments
303 ///
304 /// - `&Self` - Mutable input state.
305 /// - `&WindowEvent` - Incoming OS or test event.
306 pub fn ingest(&mut self, event: &WindowEvent) {
307 match event {
308 WindowEvent::KeyDown(_, key) => {
309 self.set_modifiers(key.get_modifiers());
310 let code: KeyCode = key.get_code();
311 if self.get_mut_keys_down().insert(code) {
312 let _: bool = self.get_mut_keys_just_pressed().insert(code);
313 }
314 }
315 WindowEvent::KeyUp(_, key) => {
316 self.set_modifiers(key.get_modifiers());
317 let code: KeyCode = key.get_code();
318 if self.get_mut_keys_down().remove(&code) {
319 let _: bool = self.get_mut_keys_just_released().insert(code);
320 }
321 }
322 WindowEvent::PointerMove(_, ptr) => {
323 self.set_modifiers(ptr.get_modifiers());
324 let prev: Point = self.get_pointer_position();
325 let next: Point = ptr.get_position();
326 let delta: Point = self.get_pointer_delta();
327 self.set_pointer_delta(Point::new(
328 delta.get_x() + (next.get_x() - prev.get_x()),
329 delta.get_y() + (next.get_y() - prev.get_y()),
330 ));
331 self.set_pointer_position(next);
332 }
333 WindowEvent::PointerDown(_, ptr) => {
334 self.set_modifiers(ptr.get_modifiers());
335 self.set_pointer_position(ptr.get_position());
336 let btn: PointerButton = ptr.get_button();
337 if self.get_mut_buttons_down().insert(btn) {
338 let _: bool = self.get_mut_buttons_just_pressed().insert(btn);
339 }
340 }
341 WindowEvent::PointerUp(_, ptr) => {
342 self.set_modifiers(ptr.get_modifiers());
343 self.set_pointer_position(ptr.get_position());
344 let btn: PointerButton = ptr.get_button();
345 if self.get_mut_buttons_down().remove(&btn) {
346 let _: bool = self.get_mut_buttons_just_released().insert(btn);
347 }
348 }
349 WindowEvent::Scroll(_, delta) => {
350 let cur: Point = self.get_scroll_delta();
351 self.set_scroll_delta(Point::new(
352 cur.get_x() + delta.get_x(),
353 cur.get_y() + delta.get_y(),
354 ));
355 }
356 WindowEvent::Focused(_, false) => {
357 self.get_mut_keys_down().clear();
358 self.get_mut_buttons_down().clear();
359 self.set_modifiers(Modifiers::default());
360 }
361 _ => {}
362 }
363 }
364
365 /// Returns `true` while `key` is held down.
366 ///
367 /// # Arguments
368 ///
369 /// - `&Self` - Input state reference.
370 /// - `KeyCode` - Key to query.
371 ///
372 /// # Returns
373 ///
374 /// - `bool` - Whether the key is held.
375 #[inline(always)]
376 #[must_use]
377 pub fn is_key_down(&self, key: KeyCode) -> bool {
378 self.get_keys_down().contains(&key)
379 }
380
381 /// Returns `true` if `key` transitioned from up to down during the current frame.
382 ///
383 /// # Arguments
384 ///
385 /// - `&Self` - Input state reference.
386 /// - `KeyCode` - Key to query.
387 ///
388 /// # Returns
389 ///
390 /// - `bool` - Whether the key was just pressed.
391 #[inline(always)]
392 #[must_use]
393 pub fn is_key_just_pressed(&self, key: KeyCode) -> bool {
394 self.get_keys_just_pressed().contains(&key)
395 }
396
397 /// Returns `true` if `key` transitioned from down to up during the current frame.
398 ///
399 /// # Arguments
400 ///
401 /// - `&Self` - Input state reference.
402 /// - `KeyCode` - Key to query.
403 ///
404 /// # Returns
405 ///
406 /// - `bool` - Whether the key was just released.
407 #[inline(always)]
408 #[must_use]
409 pub fn is_key_just_released(&self, key: KeyCode) -> bool {
410 self.get_keys_just_released().contains(&key)
411 }
412
413 /// Returns `true` while pointer `button` is held down.
414 ///
415 /// # Arguments
416 ///
417 /// - `&Self` - Input state reference.
418 /// - `PointerButton` - Button to query.
419 ///
420 /// # Returns
421 ///
422 /// - `bool` - Whether the button is held.
423 #[inline(always)]
424 #[must_use]
425 pub fn is_button_down(&self, button: PointerButton) -> bool {
426 self.get_buttons_down().contains(&button)
427 }
428
429 /// Returns `true` if pointer `button` transitioned from up to down during the current frame.
430 ///
431 /// # Arguments
432 ///
433 /// - `&Self` - Input state reference.
434 /// - `PointerButton` - Button to query.
435 ///
436 /// # Returns
437 ///
438 /// - `bool` - Whether the button was just pressed.
439 #[inline(always)]
440 #[must_use]
441 pub fn is_button_just_pressed(&self, button: PointerButton) -> bool {
442 self.get_buttons_just_pressed().contains(&button)
443 }
444
445 /// Returns `true` if pointer `button` transitioned from down to up during the current frame.
446 ///
447 /// # Arguments
448 ///
449 /// - `&Self` - Input state reference.
450 /// - `PointerButton` - Button to query.
451 ///
452 /// # Returns
453 ///
454 /// - `bool` - Whether the button was just released.
455 #[inline(always)]
456 #[must_use]
457 pub fn is_button_just_released(&self, button: PointerButton) -> bool {
458 self.get_buttons_just_released().contains(&button)
459 }
460
461 /// Computes a normalized `-1.0..=1.0` movement axis from negative and positive key bindings.
462 ///
463 /// # Arguments
464 ///
465 /// - `&Self` - Input state reference.
466 /// - `KeyCode` - Negative direction key.
467 /// - `KeyCode` - Positive direction key.
468 ///
469 /// # Returns
470 ///
471 /// - `f32` - Axis value in `{-1.0, 0.0, 1.0}`.
472 #[must_use]
473 pub fn axis(&self, negative: KeyCode, positive: KeyCode) -> f32 {
474 let mut value: f32 = 0.0;
475 if self.is_key_down(negative) {
476 value -= 1.0;
477 }
478 if self.is_key_down(positive) {
479 value += 1.0;
480 }
481 value
482 }
483
484 /// Sets the normalized analog virtual stick vector `(dx, dy)` for mobile touch joysticks or gamepads.
485 ///
486 /// # Arguments
487 ///
488 /// - `&Self` - Mutable input state.
489 /// - `f32` - Horizontal axis in `[-1.0, 1.0]`.
490 /// - `f32` - Vertical axis in `[-1.0, 1.0]`.
491 pub fn set_virtual_stick(&mut self, dx: f32, dy: f32) {
492 self.set_virtual_axis(Point::new(dx.clamp(-1.0, 1.0), dy.clamp(-1.0, 1.0)));
493 }
494
495 /// Resets the virtual analog stick to neutral `(0.0, 0.0)`.
496 ///
497 /// # Arguments
498 ///
499 /// - `&Self` - Mutable input state.
500 pub fn clear_virtual_stick(&mut self) {
501 self.set_virtual_axis(Point::new(0.0, 0.0));
502 }
503}
504
505/// Default arcade action map binding WASD + Arrows, Space/Click fire, Shift/E dash, and P/Esc pause.
506impl Default for ActionMap {
507 /// Creates an `ActionMap` pre-populated with standard desktop/web arcade controls.
508 ///
509 /// # Returns
510 ///
511 /// - `Self` - Standard arcade action map.
512 fn default() -> Self {
513 let mut map: Self = Self {
514 key_bindings: HashMap::new(),
515 button_bindings: HashMap::new(),
516 };
517 map.bind_key(GameAction::MoveLeft, KeyCode::ArrowLeft);
518 map.bind_key(GameAction::MoveLeft, KeyCode::Character('a'));
519 map.bind_key(GameAction::MoveLeft, KeyCode::Character('A'));
520 map.bind_key(GameAction::MoveRight, KeyCode::ArrowRight);
521 map.bind_key(GameAction::MoveRight, KeyCode::Character('d'));
522 map.bind_key(GameAction::MoveRight, KeyCode::Character('D'));
523 map.bind_key(GameAction::MoveUp, KeyCode::ArrowUp);
524 map.bind_key(GameAction::MoveUp, KeyCode::Character('w'));
525 map.bind_key(GameAction::MoveUp, KeyCode::Character('W'));
526 map.bind_key(GameAction::MoveDown, KeyCode::ArrowDown);
527 map.bind_key(GameAction::MoveDown, KeyCode::Character('s'));
528 map.bind_key(GameAction::MoveDown, KeyCode::Character('S'));
529 map.bind_key(GameAction::Fire, KeyCode::Space);
530 map.bind_key(GameAction::Fire, KeyCode::Character('j'));
531 map.bind_button(GameAction::Fire, PointerButton::Primary);
532 map.bind_key(GameAction::Dash, KeyCode::Character('e'));
533 map.bind_key(GameAction::Dash, KeyCode::Character('E'));
534 map.bind_key(GameAction::Jump, KeyCode::Space);
535 map.bind_key(GameAction::Pause, KeyCode::Escape);
536 map.bind_key(GameAction::Pause, KeyCode::Character('p'));
537 map.bind_key(GameAction::ActionAlt, KeyCode::Character('r'));
538 map.bind_key(GameAction::ActionAlt, KeyCode::Character('R'));
539 map
540 }
541}
542
543/// Binding registration and real-time input queries for `ActionMap`.
544impl ActionMap {
545 /// Binds a `KeyCode` to `action`.
546 ///
547 /// # Arguments
548 ///
549 /// - `&Self` - Mutable action map.
550 /// - `GameAction` - Semantic game action.
551 /// - `KeyCode` - Keyboard key to bind.
552 pub fn bind_key(&mut self, action: GameAction, key: KeyCode) {
553 self.get_mut_key_bindings()
554 .entry(action)
555 .or_default()
556 .push(key);
557 }
558
559 /// Binds a `PointerButton` to `action`.
560 ///
561 /// # Arguments
562 ///
563 /// - `&Self` - Mutable action map.
564 /// - `GameAction` - Semantic game action.
565 /// - `PointerButton` - Mouse/touch button to bind.
566 pub fn bind_button(&mut self, action: GameAction, button: PointerButton) {
567 self.get_mut_button_bindings()
568 .entry(action)
569 .or_default()
570 .push(button);
571 }
572
573 /// Returns `true` while any key or button bound to `action` is held in `input`.
574 ///
575 /// # Arguments
576 ///
577 /// - `&Self` - Action map reference.
578 /// - `GameAction` - Action to query.
579 /// - `&InputState` - Current polled input snapshot.
580 ///
581 /// # Returns
582 ///
583 /// - `bool` - Whether `action` is currently active.
584 #[must_use]
585 pub fn is_active(&self, action: GameAction, input: &InputState) -> bool {
586 if action == GameAction::Fire && input.get_virtual_fire() {
587 return true;
588 }
589 if action == GameAction::Dash && input.get_virtual_dash() {
590 return true;
591 }
592 let key_hit: bool = self
593 .get_key_bindings()
594 .get(&action)
595 .map(|keys: &Vec<KeyCode>| keys.iter().copied().any(|k: KeyCode| input.is_key_down(k)))
596 .unwrap_or(false);
597 if key_hit {
598 return true;
599 }
600 self.get_button_bindings()
601 .get(&action)
602 .map(|btns: &Vec<PointerButton>| {
603 btns.iter()
604 .copied()
605 .any(|b: PointerButton| input.is_button_down(b))
606 })
607 .unwrap_or(false)
608 }
609
610 /// Returns `true` when any key bound to `action` transitioned down on this frame.
611 ///
612 /// # Arguments
613 ///
614 /// - `&Self` - Action map reference.
615 /// - `GameAction` - Action to query.
616 /// - `&InputState` - Current polled input snapshot.
617 ///
618 /// # Returns
619 ///
620 /// - `bool` - Whether `action` was just triggered.
621 #[must_use]
622 pub fn is_just_pressed(&self, action: GameAction, input: &InputState) -> bool {
623 self.get_key_bindings()
624 .get(&action)
625 .map(|keys: &Vec<KeyCode>| {
626 keys.iter()
627 .copied()
628 .any(|k: KeyCode| input.is_key_just_pressed(k))
629 })
630 .unwrap_or(false)
631 }
632
633 /// Computes a normalized 2D movement vector `(dx, dy)` from directional action bindings.
634 ///
635 /// # Arguments
636 ///
637 /// - `&Self` - Action map reference.
638 /// - `&InputState` - Current polled input snapshot.
639 ///
640 /// # Returns
641 ///
642 /// - `Point` - Normalized movement vector with length `<= 1.0`.
643 #[must_use]
644 pub fn movement_vector(&self, input: &InputState) -> Point {
645 let mut dx: f32 = input.get_virtual_axis().get_x();
646 let mut dy: f32 = input.get_virtual_axis().get_y();
647 if self.is_active(GameAction::MoveLeft, input) {
648 dx -= 1.0;
649 }
650 if self.is_active(GameAction::MoveRight, input) {
651 dx += 1.0;
652 }
653 if self.is_active(GameAction::MoveUp, input) {
654 dy -= 1.0;
655 }
656 if self.is_active(GameAction::MoveDown, input) {
657 dy += 1.0;
658 }
659 let len: f32 = (dx * dx + dy * dy).sqrt();
660 if len > 1.0 {
661 Point::new(dx / len, dy / len)
662 } else {
663 Point::new(dx, dy)
664 }
665 }
666}