1use std::collections::{HashMap, HashSet};
8
9use bevy_ecs::prelude::Resource;
10pub use winit::event::MouseButton;
11pub use winit::keyboard::KeyCode;
12
13#[derive(Resource, Default)]
21pub struct RuntimeInput {
22 keys_held: HashSet<KeyCode>,
23 keys_just_pressed: HashSet<KeyCode>,
24 keys_just_released: HashSet<KeyCode>,
25 mouse_held: HashSet<MouseButton>,
26 mouse_just_pressed: HashSet<MouseButton>,
27 mouse_just_released: HashSet<MouseButton>,
28 cursor_position: Option<[f32; 2]>,
29 viewport_size: [f32; 2],
30}
31
32impl RuntimeInput {
33 #[must_use]
34 pub fn key_held(&self, key: KeyCode) -> bool {
35 self.keys_held.contains(&key)
36 }
37 #[must_use]
38 pub fn key_just_pressed(&self, key: KeyCode) -> bool {
39 self.keys_just_pressed.contains(&key)
40 }
41 #[must_use]
42 pub fn key_just_released(&self, key: KeyCode) -> bool {
43 self.keys_just_released.contains(&key)
44 }
45 #[must_use]
46 pub fn mouse_held(&self, button: MouseButton) -> bool {
47 self.mouse_held.contains(&button)
48 }
49 #[must_use]
50 pub fn mouse_just_pressed(&self, button: MouseButton) -> bool {
51 self.mouse_just_pressed.contains(&button)
52 }
53 #[must_use]
54 pub fn mouse_just_released(&self, button: MouseButton) -> bool {
55 self.mouse_just_released.contains(&button)
56 }
57 #[must_use]
58 pub fn cursor_position(&self) -> Option<[f32; 2]> {
59 self.cursor_position
60 }
61
62 #[must_use]
65 pub fn viewport_size(&self) -> [f32; 2] {
66 self.viewport_size
67 }
68
69 pub fn record_key(&mut self, key: KeyCode, pressed: bool) {
72 if pressed {
73 if self.keys_held.insert(key) {
74 self.keys_just_pressed.insert(key);
75 }
76 } else if self.keys_held.remove(&key) {
77 self.keys_just_released.insert(key);
78 }
79 }
80
81 pub fn record_mouse_button(&mut self, button: MouseButton, pressed: bool) {
83 if pressed {
84 if self.mouse_held.insert(button) {
85 self.mouse_just_pressed.insert(button);
86 }
87 } else if self.mouse_held.remove(&button) {
88 self.mouse_just_released.insert(button);
89 }
90 }
91
92 pub fn record_cursor_position(&mut self, position: [f32; 2]) {
94 self.cursor_position = Some(position);
95 }
96 pub fn record_viewport_size(&mut self, size: [f32; 2]) {
98 self.viewport_size = size;
99 }
100
101 pub fn clear_frame_edges(&mut self) {
105 self.keys_just_pressed.clear();
106 self.keys_just_released.clear();
107 self.mouse_just_pressed.clear();
108 self.mouse_just_released.clear();
109 }
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117pub enum InputBinding {
118 Key(KeyCode),
119 Mouse(MouseButton),
120}
121
122#[derive(Resource, Default)]
125pub struct ActionMap {
126 bindings: HashMap<String, Vec<InputBinding>>,
127}
128
129impl ActionMap {
130 pub fn bind(
131 &mut self,
132 action: impl Into<String>,
133 binding: InputBinding,
134 ) -> &mut Self {
135 self.bindings
136 .entry(action.into())
137 .or_default()
138 .push(binding);
139 self
140 }
141 #[must_use]
142 pub fn held(&self, input: &RuntimeInput, action: &str) -> bool {
143 self.bindings_for(action).any(|binding| match binding {
144 InputBinding::Key(key) => input.key_held(*key),
145 InputBinding::Mouse(button) => input.mouse_held(*button),
146 })
147 }
148 #[must_use]
149 pub fn just_pressed(&self, input: &RuntimeInput, action: &str) -> bool {
150 self.bindings_for(action).any(|binding| match binding {
151 InputBinding::Key(key) => input.key_just_pressed(*key),
152 InputBinding::Mouse(button) => input.mouse_just_pressed(*button),
153 })
154 }
155 #[must_use]
156 pub fn just_released(&self, input: &RuntimeInput, action: &str) -> bool {
157 self.bindings_for(action).any(|binding| match binding {
158 InputBinding::Key(key) => input.key_just_released(*key),
159 InputBinding::Mouse(button) => input.mouse_just_released(*button),
160 })
161 }
162 fn bindings_for(
163 &self,
164 action: &str,
165 ) -> impl Iterator<Item = &InputBinding> {
166 self.bindings.get(action).into_iter().flatten()
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173 use bevy_ecs::prelude::Resource;
174 #[test]
175 fn runtime_input_and_action_map_are_ecs_resources() {
176 fn assert_resource<T: Resource>() {}
177 assert_resource::<RuntimeInput>();
178 assert_resource::<ActionMap>();
179 }
180 #[test]
181 fn keyboard_edges_and_auto_repeat_are_tracked() {
182 let mut input = RuntimeInput::default();
183 input.record_key(KeyCode::Space, true);
184 assert!(input.key_held(KeyCode::Space));
185 assert!(input.key_just_pressed(KeyCode::Space));
186 input.record_key(KeyCode::Space, true);
187 input.clear_frame_edges();
188 assert!(input.key_held(KeyCode::Space));
189 assert!(!input.key_just_pressed(KeyCode::Space));
190 input.record_key(KeyCode::Space, false);
191 assert!(input.key_just_released(KeyCode::Space));
192 }
193 #[test]
194 fn mouse_cursor_and_viewport_are_tracked() {
195 let mut input = RuntimeInput::default();
196 input.record_mouse_button(MouseButton::Left, true);
197 input.record_cursor_position([12.0, 34.0]);
198 input.record_viewport_size([800.0, 600.0]);
199 assert!(input.mouse_held(MouseButton::Left));
200 assert!(input.mouse_just_pressed(MouseButton::Left));
201 assert_eq!(input.cursor_position(), Some([12.0, 34.0]));
202 assert_eq!(input.viewport_size(), [800.0, 600.0]);
203 input.clear_frame_edges();
204 input.record_mouse_button(MouseButton::Left, false);
205 assert!(input.mouse_just_released(MouseButton::Left));
206 assert!(!input.mouse_held(MouseButton::Left));
207 }
208 #[test]
209 fn actions_cover_keyboard_mouse_and_edge_clearing() {
210 let mut map = ActionMap::default();
211 map.bind("jump", InputBinding::Key(KeyCode::Space))
212 .bind("jump", InputBinding::Mouse(MouseButton::Left));
213 let mut input = RuntimeInput::default();
214 input.record_key(KeyCode::Space, true);
215 assert!(map.just_pressed(&input, "jump"));
216 assert!(map.held(&input, "jump"));
217 input.clear_frame_edges();
218 assert!(!map.just_pressed(&input, "jump"));
219 assert!(map.held(&input, "jump"));
220 input.record_key(KeyCode::Space, false);
221 assert!(map.just_released(&input, "jump"));
222 input.clear_frame_edges();
223 input.record_mouse_button(MouseButton::Left, true);
224 assert!(map.just_pressed(&input, "jump"));
225 assert!(map.held(&input, "jump"));
226 assert!(!map.held(&input, "unbound_action"));
227 }
228}