1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
//! World resource that handles all user input.

use std::borrow::Borrow;
use std::hash::Hash;

use amethyst_core::shrev::EventChannel;
use smallvec::SmallVec;
use winit::{DeviceEvent, ElementState, Event, KeyboardInput, MouseButton, VirtualKeyCode,
            WindowEvent};

use super::event::InputEvent;
use super::event::InputEvent::*;
use super::*;

/// This struct holds state information about input devices.
///
/// For example, if a key is pressed on the keyboard, this struct will record
/// that the key is pressed until it is released again.
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct InputHandler<AX, AC>
where
    AX: Hash + Eq,
    AC: Hash + Eq,
{
    /// Maps inputs to actions and axes.
    pub bindings: Bindings<AX, AC>,
    /// Encodes the VirtualKeyCode and corresponding scancode.
    pressed_keys: SmallVec<[(VirtualKeyCode, u32); 12]>,
    pressed_mouse_buttons: SmallVec<[MouseButton; 12]>,
    mouse_position: Option<(f64, f64)>,
}

impl<AX, AC> InputHandler<AX, AC>
where
    AX: Hash + Eq,
    AC: Hash + Eq,
{
    /// Creates a new input handler.
    pub fn new() -> Self {
        Default::default()
    }
}

impl<AX, AC> InputHandler<AX, AC>
where
    AX: Hash + Eq + Clone + Send + Sync + 'static,
    AC: Hash + Eq + Clone + Send + Sync + 'static,
{
    /// Updates the input handler with a new engine event.
    ///
    /// The Amethyst game engine will automatically call this if the InputHandler is attached to
    /// the world as a resource with id 0.
    pub fn send_event(&mut self, event: &Event, event_handler: &mut EventChannel<InputEvent<AC>>) {
        match *event {
            Event::WindowEvent { ref event, .. } => match *event {
                WindowEvent::ReceivedCharacter(c) => {
                    event_handler.single_write(KeyTyped(c));
                }
                WindowEvent::KeyboardInput {
                    input:
                        KeyboardInput {
                            state: ElementState::Pressed,
                            virtual_keycode: Some(key_code),
                            scancode,
                            ..
                        },
                    ..
                } => if self.pressed_keys.iter().all(|&k| k.0 != key_code) {
                    self.pressed_keys.push((key_code, scancode));
                    event_handler.iter_write(
                        [
                            KeyPressed { key_code, scancode },
                            ButtonPressed(Button::Key(key_code)),
                            ButtonPressed(Button::ScanCode(scancode)),
                        ].iter()
                            .cloned(),
                    );
                    for (k, v) in self.bindings.actions.iter() {
                        for &button in v {
                            if Button::Key(key_code) == button {
                                event_handler.single_write(ActionPressed(k.clone()));
                            }
                            if Button::ScanCode(scancode) == button {
                                event_handler.single_write(ActionPressed(k.clone()));
                            }
                        }
                    }
                },
                WindowEvent::KeyboardInput {
                    input:
                        KeyboardInput {
                            state: ElementState::Released,
                            virtual_keycode: Some(key_code),
                            scancode,
                            ..
                        },
                    ..
                } => {
                    let index = self.pressed_keys.iter().position(|&k| k.0 == key_code);
                    if let Some(i) = index {
                        self.pressed_keys.swap_remove(i);
                        event_handler.iter_write(
                            [
                                KeyReleased { key_code, scancode },
                                ButtonReleased(Button::Key(key_code)),
                                ButtonReleased(Button::ScanCode(scancode)),
                            ].iter()
                                .cloned(),
                        );
                        for (k, v) in self.bindings.actions.iter() {
                            for &button in v {
                                if Button::Key(key_code) == button {
                                    event_handler.single_write(ActionReleased(k.clone()));
                                }
                                if Button::ScanCode(scancode) == button {
                                    event_handler.single_write(ActionReleased(k.clone()));
                                }
                            }
                        }
                    }
                }
                WindowEvent::MouseInput {
                    state: ElementState::Pressed,
                    button,
                    ..
                } => {
                    let mouse_button = button;
                    if self.pressed_mouse_buttons
                        .iter()
                        .all(|&b| b != mouse_button)
                    {
                        self.pressed_mouse_buttons.push(mouse_button);
                        event_handler.iter_write(
                            [
                                MouseButtonPressed(mouse_button),
                                ButtonPressed(Button::Mouse(mouse_button)),
                            ].iter()
                                .cloned(),
                        );
                        for (k, v) in self.bindings.actions.iter() {
                            for &button in v {
                                if Button::Mouse(mouse_button) == button {
                                    event_handler.single_write(ActionPressed(k.clone()));
                                }
                            }
                        }
                    }
                }
                WindowEvent::MouseInput {
                    state: ElementState::Released,
                    button,
                    ..
                } => {
                    let mouse_button = button;
                    let index = self.pressed_mouse_buttons
                        .iter()
                        .position(|&b| b == mouse_button);
                    if let Some(i) = index {
                        self.pressed_mouse_buttons.swap_remove(i);
                        event_handler.iter_write(
                            [
                                MouseButtonReleased(mouse_button),
                                ButtonReleased(Button::Mouse(mouse_button)),
                            ].iter()
                                .cloned(),
                        );
                        for (k, v) in self.bindings.actions.iter() {
                            for &button in v {
                                if Button::Mouse(mouse_button) == button {
                                    event_handler.single_write(ActionReleased(k.clone()));
                                }
                            }
                        }
                    }
                }
                WindowEvent::CursorMoved {
                    position: (x, y), ..
                } => {
                    if let Some((old_x, old_y)) = self.mouse_position {
                        event_handler.single_write(CursorMoved {
                            delta_x: x - old_x,
                            delta_y: y - old_y,
                        });
                    }
                    self.mouse_position = Some((x, y));
                }
                WindowEvent::Focused(false) => {
                    self.pressed_keys.clear();
                    self.pressed_mouse_buttons.clear();
                    self.mouse_position = None;
                }
                _ => {}
            },
            Event::DeviceEvent { ref event, .. } => match *event {
                DeviceEvent::MouseMotion {
                    delta: (delta_x, delta_y),
                } => {
                    event_handler.single_write(MouseMoved { delta_x, delta_y });
                }
                _ => {}
            },
            _ => {}
        }
    }

    /// Returns an iterator over all keys that are down.
    pub fn keys_that_are_down(&self) -> KeyCodes {
        self.pressed_keys
            .iter()
            .map((|k| k.0) as fn(&(VirtualKeyCode, u32)) -> VirtualKeyCode)
    }

    /// Checks if a key is down.
    pub fn key_is_down(&self, key: VirtualKeyCode) -> bool {
        self.pressed_keys.iter().any(|&k| k.0 == key)
    }

    /// Returns an iterator over all pressed mouse buttons
    pub fn mouse_buttons_that_are_down(&self) -> MouseButtons {
        self.pressed_mouse_buttons.iter()
    }

    /// Checks if a mouse button is down.
    pub fn mouse_button_is_down(&self, mouse_button: MouseButton) -> bool {
        self.pressed_mouse_buttons
            .iter()
            .any(|&mb| mb == mouse_button)
    }

    /// Returns an iterator over all pressed scan codes
    pub fn scan_codes_that_are_down(&self) -> ScanCodes {
        self.pressed_keys
            .iter()
            .map((|k| k.1) as fn(&(VirtualKeyCode, u32)) -> u32)
    }

    /// Checks if the key corresponding to a scan code is down.
    pub fn scan_code_is_down(&self, scan_code: u32) -> bool {
        self.pressed_keys.iter().any(|&k| k.1 == scan_code)
    }

    /// Gets the current mouse position.
    ///
    /// this method can return None, either if no mouse is connected, or if no mouse events have
    /// been recorded
    pub fn mouse_position(&self) -> Option<(f64, f64)> {
        self.mouse_position
    }

    /// Returns an iterator over all buttons that are down.
    pub fn buttons_that_are_down<'a>(&self) -> Buttons {
        let mouse_buttons = self.pressed_mouse_buttons
            .iter()
            .map((|&mb| Button::Mouse(mb)) as fn(&MouseButton) -> Button);
        let keys = self.pressed_keys.iter().flat_map(
            (|v| KeyThenCode::new(v.clone())) as fn(&(VirtualKeyCode, u32)) -> KeyThenCode,
        );
        Buttons {
            iterator: mouse_buttons.chain(keys),
        }
    }

    /// Checks if a button is down.
    pub fn button_is_down(&self, button: Button) -> bool {
        match button {
            Button::Key(k) => self.key_is_down(k),
            Button::Mouse(b) => self.mouse_button_is_down(b),
            Button::ScanCode(s) => self.scan_code_is_down(s),
        }
    }

    /// Returns the value of an axis by the string id, if the id doesn't exist this returns None.
    pub fn axis_value<T: Hash + Eq + ?Sized>(&self, id: &T) -> Option<f64>
    where
        AX: Borrow<T>,
    {
        self.bindings.axes.get(id).map(|a| {
            let pos = self.button_is_down(a.pos);
            let neg = self.button_is_down(a.neg);
            if pos == neg {
                0.0
            } else if pos {
                1.0
            } else {
                -1.0
            }
        })
    }

    /// Returns true if any of the action keys are down.
    pub fn action_is_down<T: Hash + Eq + ?Sized>(&self, action: &T) -> Option<bool>
    where
        AC: Borrow<T>,
    {
        self.bindings
            .actions
            .get(action)
            .map(|ref buttons| buttons.iter().any(|&b| self.button_is_down(b)))
    }
}