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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use crate::*;

use riddle_common::{
    define_handles,
    eventpub::{EventPub, EventSub},
};
use riddle_platform_common::{LogicalPosition, PlatformEvent, WindowId};

use std::{collections::HashMap, sync::Mutex};

struct WindowInputState {
    mouse: MouseState,
    keyboard: KeyboardState,
}

/// The Riddle input system core state, along with [`InputMainThreadState`].
///
/// This stores the thread safe input state which can be queried to inspect the
/// status of input devices. It is updated by [`InputMainThreadState::process_input`].
pub struct InputSystem {
    weak_self: InputSystemWeak,

    window_states: Mutex<HashMap<WindowId, WindowInputState>>,
    gamepad_states: Mutex<GamePadStateMap>,

    outgoing_input_events: Mutex<Vec<InputEvent>>,
}

define_handles!(<InputSystem>::weak_self, pub InputSystemHandle, pub InputSystemWeak);

impl InputSystem {
    /// Query the cursor position with respect to a given window.
    ///
    /// If no mouse position infomation is available for the given window, the
    /// position will be (0,0)
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_input::{ext::*, *}; use riddle_common::eventpub::*; use riddle_platform_common::*;
    /// # fn main() -> Result<(), InputError> {
    /// # let platform_events: EventPub<PlatformEvent> = EventPub::new();
    /// # let (input_system, mut main_thread_state) = InputSystem::new_shared(&platform_events)?;
    /// # let window = WindowId::new(0);
    /// // The initial mouse position is (0,0)
    /// assert_eq!(LogicalPosition{ x: 0, y: 0}, input_system.mouse_pos(window));
    ///
    /// // The platform system emits cursor move events
    /// // [..]
    /// # platform_events.dispatch(PlatformEvent::CursorMove {
    /// #     window: WindowId::new(0),
    /// #     position: LogicalPosition{ x: 10, y: 10}});
    /// # main_thread_state.process_input();
    ///
    /// // The reported mouse position has changed
    /// assert_ne!(LogicalPosition{ x: 0, y: 0}, input_system.mouse_pos(window));
    /// # Ok(()) }
    /// ```
    pub fn mouse_pos(&self, window: WindowId) -> LogicalPosition {
        self.with_window_state(window, |w| w.mouse.position())
    }

    /// Check if the specified mouse button is down with respect to a given window.
    ///
    /// If there is no state recorded for the mouse for the given window the result will
    /// be false
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_input::{ext::*, *}; use riddle_common::eventpub::*; use riddle_platform_common::*;
    /// # fn main() -> Result<(), InputError> {
    /// # let platform_events: EventPub<PlatformEvent> = EventPub::new();
    /// # let (input_system, mut main_thread_state) = InputSystem::new_shared(&platform_events)?;
    /// # let window = WindowId::new(0);
    /// // The initial mouse position is (0,0)
    /// assert_eq!(false, input_system.is_mouse_button_down(window, MouseButton::Left));
    ///
    /// // The platform system emits cursor move events
    /// // [..]
    /// # platform_events.dispatch(PlatformEvent::MouseButtonDown {
    /// #     window: WindowId::new(0),
    /// #     button: MouseButton::Left});
    /// # main_thread_state.process_input();
    ///
    /// // The reported mouse position has changed
    /// assert_eq!(true, input_system.is_mouse_button_down(window, MouseButton::Left));
    /// # Ok(()) }
    /// ```
    pub fn is_mouse_button_down(&self, window: WindowId, button: MouseButton) -> bool {
        self.with_window_state(window, |w| w.mouse.is_button_down(button))
    }

    /// Query the keyboard scancode state with respect to a given window. See
    /// [`Scancode`] for details on what a scancode represents.
    ///
    /// If no keyboard infomation is available for the given window, the button
    /// will be considered to not be down.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_input::{ext::*, *}; use riddle_common::eventpub::*; use riddle_platform_common::*;
    /// # fn main() -> Result<(), InputError> {
    /// # let platform_events: EventPub<PlatformEvent> = EventPub::new();
    /// # let (input_system, mut main_thread_state) = InputSystem::new_shared(&platform_events)?;
    /// # let window = WindowId::new(0);
    /// // The initial key state is that the button is unpressed
    /// assert_eq!(false, input_system.is_key_down(window, Scancode::Escape));
    ///
    /// // The platform system emits key press event
    /// // [..]
    /// # platform_events.dispatch(PlatformEvent::KeyDown {
    /// #     window: WindowId::new(0),
    /// #     vkey: Some(VirtualKey::Escape),
    /// #     scancode: Scancode::Escape,
    /// #     platform_scancode: 0});
    /// # main_thread_state.process_input();
    ///
    /// // The reported key state has changed
    /// assert_eq!(true, input_system.is_key_down(window, Scancode::Escape));
    /// # Ok(()) }
    /// ```
    pub fn is_key_down(&self, window: WindowId, scancode: Scancode) -> bool {
        self.with_window_state(window, |w| w.keyboard.is_key_down(scancode))
    }

    /// Query the keyboard virtual key state with respect to a given window. See
    /// [`VirtualKey`] for details on what a virtual key represents.
    ///
    /// If no keyboard infomation is available for the given window, the button
    /// will be considered to not be down.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_input::{ext::*, *}; use riddle_common::eventpub::*; use riddle_platform_common::*;
    /// # fn main() -> Result<(), InputError> {
    /// # let platform_events: EventPub<PlatformEvent> = EventPub::new();
    /// # let (input_system, mut main_thread_state) = InputSystem::new_shared(&platform_events)?;
    /// # let window = WindowId::new(0);
    /// // The initial key state is that the button is unpressed
    /// assert_eq!(false, input_system.is_vkey_down(window, VirtualKey::Escape));
    ///
    /// // The platform system emits key press event
    /// // [..]
    /// # platform_events.dispatch(PlatformEvent::KeyDown {
    /// #     window: WindowId::new(0),
    /// #     vkey: Some(VirtualKey::Escape),
    /// #     scancode: Scancode::Escape,
    /// #     platform_scancode: 0});
    /// # main_thread_state.process_input();
    ///
    /// // The reported key state has changed
    /// assert_eq!(true, input_system.is_vkey_down(window, VirtualKey::Escape));
    /// # Ok(()) }
    /// ```
    pub fn is_vkey_down(&self, window: WindowId, vkey: VirtualKey) -> bool {
        self.with_window_state(window, |w| w.keyboard.is_vkey_down(vkey))
    }

    /// The current state of keyboard modifiers with respect to a given window.
    ///
    /// If no state has been set all modifiers are considered unset.
    ///
    /// # Example
    ///
    /// ```
    /// # use riddle_input::{ext::*, *}; use riddle_common::eventpub::*; use riddle_platform_common::*;
    /// # fn main() -> Result<(), InputError> {
    /// # let platform_events: EventPub<PlatformEvent> = EventPub::new();
    /// # let (input_system, mut main_thread_state) = InputSystem::new_shared(&platform_events)?;
    /// # let window = WindowId::new(0);
    /// // The initial mouse position is (0,0)
    /// assert_eq!(false, input_system.keyboard_modifiers(window).ctrl);
    ///
    /// // The platform system emits key down event for Ctrl key
    /// // [..]
    /// # platform_events.dispatch(PlatformEvent::KeyDown {
    /// #     window: WindowId::new(0),
    /// #     vkey: Some(VirtualKey::LeftControl),
    /// #     scancode: Scancode::LeftControl,
    /// #     platform_scancode: 0});
    /// # main_thread_state.process_input();
    ///
    /// // The reported mouse position has changed
    /// assert_eq!(true, input_system.keyboard_modifiers(window).ctrl);
    /// # Ok(()) }
    /// ```
    pub fn keyboard_modifiers(&self, window: WindowId) -> KeyboardModifiers {
        self.with_window_state(window, |w| w.keyboard.modifiers())
    }

    /// Get the [`GamePadId`] of the last gamepad which issued any event.
    ///
    /// Can be used a very simple way to pick a gamepad to consider the "active"
    /// gamepad. Handling [`InputEvent::GamePadConnected`] and similar events
    /// allows for more fine grained control.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use riddle_input::{ext::*, *}; use riddle_common::eventpub::*; use riddle_platform_common::*;
    /// # fn main() -> Result<(), InputError> {
    /// # let platform_events: EventPub<PlatformEvent> = EventPub::new();
    /// # let (input_system, mut main_thread_state) = InputSystem::new_shared(&platform_events)?;
    /// # let window = WindowId::new(0);
    /// // The initial gamepad is None
    /// assert_eq!(None, input_system.last_active_gamepad());
    ///
    /// // Controller button press events are processed
    /// // [..]
    /// # // Currently no support for faking a controller event
    /// # panic!();
    ///
    /// // The reported active controller has changed
    /// assert_ne!(None, input_system.last_active_gamepad());
    /// # Ok(()) }
    /// ```
    pub fn last_active_gamepad(&self) -> Option<GamePadId> {
        self.gamepad_states.lock().unwrap().last_active_pad()
    }

    /// Check if a specific button is pressed for a given gamepad.
    ///
    /// If no state has been set all buttons are considered not to be down.
    ///
    /// ```no_run
    /// # use riddle_input::{ext::*, *};
    /// # let input_system: InputSystemHandle = todo!();
    /// # let gamepad: GamePadId = todo!();
    /// // The initial button state is false
    /// assert_eq!(false, input_system.is_gamepad_button_down(gamepad, GamePadButton::North));
    ///
    /// // Controller button press events are processed
    /// // [..]
    /// # // Currently no support for faking a controller event
    /// # panic!();
    ///
    /// // The reported button state has changed
    /// assert_eq!(true, input_system.is_gamepad_button_down(gamepad, GamePadButton::North));
    /// ```
    pub fn is_gamepad_button_down(&self, gamepad: GamePadId, button: GamePadButton) -> bool {
        self.gamepad_states
            .lock()
            .unwrap()
            .is_button_down(gamepad, button)
    }

    /// Get the value of a specific axis for a specific gamepad
    ///
    /// If no state has been set all axes are considered to have value `0.0`.
    ///
    /// ```no_run
    /// # use riddle_input::{ext::*, *};
    /// # let input_system: InputSystemHandle = todo!();
    /// # let gamepad: GamePadId = todo!();
    /// // The initial button state is false
    /// assert_eq!(0.0, input_system.gamepad_axis_value(gamepad, GamePadAxis::LeftStickX));
    ///
    /// // Controller axis events are processed
    /// // [..]
    /// # // Currently no support for faking a controller event
    /// # panic!();
    ///
    /// // The reported axis value has changed
    /// assert_ne!(0.0, input_system.gamepad_axis_value(gamepad, GamePadAxis::LeftStickX));
    /// ```
    pub fn gamepad_axis_value(&self, gamepad: GamePadId, axis: GamePadAxis) -> f32 {
        self.gamepad_states
            .lock()
            .unwrap()
            .axis_value(gamepad, axis)
    }

    fn with_window_state<R, F>(&self, window: WindowId, f: F) -> R
    where
        F: FnOnce(&WindowInputState) -> R,
    {
        let mut ms = self.window_states.lock().unwrap();
        if !ms.contains_key(&window) {
            ms.insert(window, Default::default());
        }
        f(ms.get(&window).unwrap())
    }

    fn with_window_state_mut<R, F>(&self, window: WindowId, f: F) -> R
    where
        F: FnOnce(&mut WindowInputState) -> R,
    {
        let mut ms = self.window_states.lock().unwrap();
        if !ms.contains_key(&window) {
            ms.insert(window, Default::default());
        }
        f(ms.get_mut(&window).unwrap())
    }

    fn cursor_moved(&self, window: WindowId, logical_position: LogicalPosition) {
        self.with_window_state_mut(window, |w| w.mouse.set_position(logical_position));
        self.send_input_event(InputEvent::CursorMove {
            window,
            position: logical_position,
        });
    }

    fn mouse_down(&self, window: WindowId, button: MouseButton) {
        self.with_window_state_mut(window, |w| w.mouse.button_down(button));
        self.send_input_event(InputEvent::MouseButtonDown { window, button });
    }

    fn mouse_up(&self, window: WindowId, button: MouseButton) {
        self.with_window_state_mut(window, |w| w.mouse.button_up(button));
        self.send_input_event(InputEvent::MouseButtonUp { window, button });
    }

    fn key_down(&self, window: WindowId, scancode: Scancode, vkey: Option<VirtualKey>) {
        let modifiers = self.with_window_state_mut(window, |w| {
            w.keyboard.key_down(scancode, vkey);
            w.keyboard.modifiers()
        });
        self.send_input_event(InputEvent::KeyDown {
            window,
            scancode,
            vkey,
            modifiers,
        })
    }

    fn key_up(&self, window: WindowId, scancode: Scancode, vkey: Option<VirtualKey>) {
        let modifiers = self.with_window_state_mut(window, |w| {
            w.keyboard.key_up(scancode, vkey);
            w.keyboard.modifiers()
        });
        self.send_input_event(InputEvent::KeyUp {
            window,
            scancode,
            vkey,
            modifiers,
        })
    }

    fn event_filter(event: &PlatformEvent) -> bool {
        matches!(
            event,
            PlatformEvent::CursorMove { .. }
                | PlatformEvent::MouseButtonUp { .. }
                | PlatformEvent::MouseButtonDown { .. }
                | PlatformEvent::KeyUp { .. }
                | PlatformEvent::KeyDown { .. }
        )
    }

    fn send_input_event(&self, event: InputEvent) {
        self.outgoing_input_events.lock().unwrap().push(event);
    }
}

impl ext::InputSystemExt for InputSystem {
    fn new_shared(
        sys_events: &EventPub<PlatformEvent>,
    ) -> Result<(InputSystemHandle, InputMainThreadState)> {
        let event_sub = EventSub::new_with_filter(Self::event_filter);
        sys_events.attach(&event_sub);

        let gilrs = gilrs::Gilrs::new().map_err(|_| InputError::InitError("Gilrs init failure"))?;

        let system = InputSystemHandle::new(|weak_self| InputSystem {
            weak_self,
            window_states: Mutex::new(HashMap::new()),
            gamepad_states: Mutex::new(GamePadStateMap::new()),
            outgoing_input_events: Mutex::new(vec![]),
        });

        let main_thread = InputMainThreadState {
            system: system.clone(),
            event_sub,
            gilrs,
        };

        Ok((system, main_thread))
    }

    fn take_input_events(&self) -> Vec<InputEvent> {
        std::mem::replace(&mut self.outgoing_input_events.lock().unwrap(), vec![])
    }
}

impl Default for WindowInputState {
    fn default() -> Self {
        Self {
            mouse: Default::default(),
            keyboard: Default::default(),
        }
    }
}

/// The portion of the input system that needs to remain on a single thread.
///
/// Constructed paired with its thread-safe counterpart via [`ext::InputSystemExt::new_shared`].
pub struct InputMainThreadState {
    system: InputSystemHandle,

    event_sub: EventSub<PlatformEvent>,
    gilrs: gilrs::Gilrs,
}

impl InputMainThreadState {
    /// Process all input sources, updating the static view of the known input
    /// devices.
    ///
    /// This may produce InputEvents which can be consumed via [`ext::InputSystemExt::take_input_events`].
    pub fn process_input(&mut self) {
        while let Some(gilrs::Event { event, id, .. }) = self.gilrs.next_event() {
            use std::convert::TryFrom;
            match event {
                gilrs::EventType::ButtonPressed(button, _) => {
                    if let Ok(button) = GamePadButton::try_from(button) {
                        self.system
                            .gamepad_states
                            .lock()
                            .unwrap()
                            .button_down(id.into(), button);
                        self.system.send_input_event(InputEvent::GamePadButtonDown {
                            gamepad: id.into(),
                            button,
                        });
                    }
                }
                gilrs::EventType::ButtonRepeated(_, _) => {}
                gilrs::EventType::ButtonReleased(button, _) => {
                    if let Ok(button) = GamePadButton::try_from(button) {
                        self.system
                            .gamepad_states
                            .lock()
                            .unwrap()
                            .button_up(id.into(), button);
                        self.system.send_input_event(InputEvent::GamePadButtonUp {
                            gamepad: id.into(),
                            button,
                        });
                    }
                }
                gilrs::EventType::ButtonChanged(_, _, _) => {}
                gilrs::EventType::AxisChanged(axis, value, _) => {
                    if let Ok(axis) = GamePadAxis::try_from(axis) {
                        self.system.gamepad_states.lock().unwrap().set_axis_value(
                            id.into(),
                            axis,
                            value,
                        );
                        self.system
                            .send_input_event(InputEvent::GamePadAxisChanged {
                                gamepad: id.into(),
                                axis,
                                value,
                            });
                    }
                }
                gilrs::EventType::Connected => {
                    self.system
                        .send_input_event(InputEvent::GamePadConnected(id.into()));
                }
                gilrs::EventType::Disconnected => {
                    self.system
                        .send_input_event(InputEvent::GamePadDisconnected(id.into()));
                }
                _ => {}
            }
        }

        self.process_platform_events();
    }

    fn process_platform_events(&self) {
        for event in self.event_sub.collect() {
            match event {
                PlatformEvent::CursorMove { window, position } => {
                    self.system.cursor_moved(window, position);
                }
                PlatformEvent::MouseButtonUp { window, button } => {
                    self.system.mouse_up(window, button);
                }
                PlatformEvent::MouseButtonDown { window, button } => {
                    self.system.mouse_down(window, button);
                }
                PlatformEvent::KeyUp {
                    window,
                    scancode,
                    vkey,
                    ..
                } => {
                    self.system.key_up(window, scancode, vkey);
                }
                PlatformEvent::KeyDown {
                    window,
                    scancode,
                    vkey,
                    ..
                } => {
                    self.system.key_down(window, scancode, vkey);
                }
                _ => (),
            }
        }
    }
}