logo
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! Input handling for applets.
//!
//! This module provides an improved abstraction over the applet input functions.

use crate::applet::{self, EventEnum, VirtualKeyCode};
use crate::{Ray3, Vec2};
use std::collections::HashSet;

// TODO: create a new `enum Key` that only supports a few of the keys.
pub use applet::Axis;
pub use applet::GamepadButton;
pub use applet::VirtualKeyCode as Key;

/// Current input state.
///
/// Sent along with each `Event` so you can, for instance,
/// spawn something along the world ray when a button is pressed,
/// or check which modifier keys were down then the user pressed `Key::U`.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct State {
    /// Which modifier keys are pressed?
    pub modifiers: Modifiers,

    /// State of the primary pointer (mouse or first touch).
    pub pointer: PointerState,

    /// Number of seconds since start of module (`applet.real_time_since_start()`).
    pub wall_time: f64,
}

/// The state of the pointer (mouse or touch).
#[derive(Copy, Clone, Default, PartialEq)]
pub struct PointerState {
    /// Logical point position of the pointer (mouse or touch).
    /// Can be `None` if mouse is not on screen, or if there are no touches.
    /// In case of multiple simultaneous touches, this will correspond to the first touch.
    pub pos: Option<Vec2>,

    /// World-space ray of the pointer (mouse or touch).
    /// Can be `None` if mouse is not on screen, or if there are no touches.
    /// In case of multiple simultaneous touches, this will correspond to the first touch.
    pub ray: Option<Ray3>,

    /// True if the primary button is currently down.
    /// Left mouse button on most mice.
    /// This is also set to `true` for the primary touch.
    pub primary: bool,

    /// True if the secondary button is currently down.
    /// Left mouse button on most mice.
    pub secondary: bool,

    /// True if the middle mouse button is currently down.
    pub middle: bool,

    /// The id of the first touch that went down (in case there are several touches).
    /// This is the touch that is being represented by `PointerState`.
    pub touch_id: Option<TouchId>,
}

impl PointerState {
    /// Any mouse button is down (always `true` for primary touches).
    pub fn any_button(&self) -> bool {
        self.primary || self.secondary || self.middle
    }
}

/// Represents the state of modifier keys.
#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)]
pub struct Modifiers {
    /// True if the cmd key is pressed.
    /// Command key on Mac, ctrl on Windows/Linux.
    /// Use this for e.g. `cmd+A` (select all).
    pub cmd: bool,

    /// True if any shift key is pressed.
    pub shift: bool,

    /// True if any ctrl key is pressed.
    pub ctrl: bool,

    /// True if any alt key is pressed.
    pub alt: bool,
}

/// An input event (e.g. a key press).
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Event {
    /// Keyboard key
    Key {
        /// pressed or released?
        pressed: bool,
        /// the key in question
        key: Key,
    },
    /// A single character (presumably due to a key press)
    Char(char),
    /// Absolute movement (won't happen when mouse grabbing is on).
    PointerMove {
        /// What kind of pointer (Mouse or Touch)?
        pointer: Pointer,
        /// Screen-space position (in logical pixels).
        pos: Vec2,
        /// World-coordinate ray.
        ray: Ray3,
        /// `true` for mice and first touch point.
        /// If `false` this is a secondary touch of some sort.
        /// You almost always want to filter on `primary: true`.
        primary: bool,
    },
    /// Relative movement (also happens when mouse grabbing is on).
    PointerDelta {
        /// What kind of pointer (Mouse or Touch)?
        pointer: Pointer,
        /// Rotation, taking into account mouse sensitivity and optional invert y axis.
        delta_angle: Vec2,
        /// Number of logical points of movement
        delta_points: Vec2,
        /// Delta as fraction of screen width,
        /// so a delta.x=1 mean the mouse moved from one screen edge to the other.
        delta_normalized: Vec2,
        /// `true` for mice and first touch point.
        /// If `false` this is a secondary touch of some sort.
        /// You almost always want to filter on `primary: true`.
        primary: bool,
    },
    /// Mouse button press/release or touch down/up
    PointerButton {
        /// `true` if this was a press, `false` if this was a release.
        pressed: bool,
        /// What kind of pointer (Mouse or Touch)?
        pointer: Pointer,
        /// The button being pressed or released.
        button: PointerButton,
        /// Screen-space position (in logical pixels).
        pos: Vec2,
        /// World-coordinate ray.
        ray: Ray3,
        /// `true` for mice and first touch point.
        /// If `false` this is a secondary touch of some sort.
        /// You almost always want to filter on `primary: true`.
        primary: bool,
    },
    /// Mouse scroll
    Scroll {
        /// In logical pixels.
        delta: Vec2,
    },
    /// A command, e.g. undo
    Command(Command),

    /// General axis input, mainly used for gamepads.
    Axis {
        /// The axis that moved.
        axis: Axis,
        /// The new value of the axis.
        value: f32,
    },

    /// Gamepad button input event.
    GamepadButton {
        /// Which gamepad button was pressed or released
        button: GamepadButton,
        /// True = pressed, false = released
        press: bool,
    },

    /// Raw MIDI event
    RawMidi {
        /// MIDI timestamp
        timestamp: u64,
        /// Raw MIDI data, needs to be parsed
        data: [u8; 8],
        /// Length of the valid MIDI bytes in the `data` buffer.
        len: u32,
        /// Device ID
        device_id: u32,
    },
}

/// Common keyboard commands such at copy, cut and paste.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Command {
    /// cmd-C
    Copy,
    /// cmd-X
    Cut,
    /// cmd-V
    Paste,
    /// cmd-Z
    Undo,
    /// cmd-shift-Z
    Redo,
    /// cmd-S
    Save,
    /// cmd-N
    New,
}

/// A mouse button
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum PointerButton {
    /// Left mouse button on most mice.
    /// The only thing valid for touch input.
    Primary,
    /// Right mouse button on most mice.
    Secondary,
    /// Middle mouse button
    Middle,
}

/// What kind of pointer (Mouse or Touch)
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Pointer {
    /// We only support a single mouse
    Mouse,
    /// When there are several touches at once, you can use `TouchId` to keep track of their movements.
    Touch(TouchId),
}

/// If several touches are detected, they all come with a unique ID.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct TouchId(u32);

/// Use this in your module to help with input filtering and tracking.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InputManager {
    state: State,
    down_keys: HashSet<VirtualKeyCode>,
    down_gamepad_buttons: HashSet<GamepadButton>,
    events: Vec<(State, Event)>,
}

// ----------------------------------------------------------------------------

impl Command {
    /// Human-readable key combination for this command.
    pub fn shortcut_str(self) -> &'static str {
        match self {
            Self::Copy => "Cmd + C",
            Self::Cut => "Cmd + X",
            Self::Paste => "Cmd + V",
            Self::Undo => "Cmd + Z",
            Self::Redo => "Cmd + Shift + Z",
            Self::Save => "Cmd + S",
            Self::New => "Cmd + N",
        }
    }
}

impl std::fmt::Debug for PointerState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self {
            pos,
            ray,
            primary,
            secondary,
            middle,
            touch_id,
        } = self;

        f.debug_struct("State")
            .field(
                "pos",
                &match pos {
                    None => "None".to_string(),
                    Some(p) => format!("{:.3} {:.3}", p.x, p.y),
                },
            )
            .field(
                "ray",
                &match ray {
                    None => "None".to_string(),
                    Some(_ray) => "Ray3 { ... }".to_string(),
                },
            )
            .field(
                "touch_id",
                &match touch_id {
                    None => "None".to_string(),
                    Some(touch_id) => format!("{:?}", touch_id),
                },
            )
            .field(
                "buttons",
                &format!(
                    "{}{}{}",
                    if *primary { "primary " } else { "" },
                    if *secondary { "secondary " } else { "" },
                    if *middle { "middle " } else { "" },
                ),
            )
            .finish()
    }
}

impl Modifiers {
    /// No modifiers.
    pub fn none() -> Self {
        Self::default()
    }

    /// Are no modifiers down?
    pub fn is_none(&self) -> bool {
        self == &Default::default()
    }

    /// Are any modifier down?
    pub fn is_any(&self) -> bool {
        !self.is_none()
    }

    /// Is only the cmd key pressed?
    pub fn is_cmd(&self) -> bool {
        // NOTE: we ignore ctrl here because ctrl==cmd on windows/linux
        self.cmd && !self.shift && !self.alt
    }

    /// Are only the cmd and shift keys pressed?
    pub fn is_cmd_shift(&self) -> bool {
        // NOTE: we ignore ctrl here because ctrl==cmd on windows/linux
        self.cmd && self.shift && !self.alt
    }
}

impl PointerButton {
    fn from_mouse_button(button: applet::MouseButton) -> Self {
        match button {
            applet::MouseButton::Primary => Self::Primary,
            applet::MouseButton::Secondary => Self::Secondary,
            applet::MouseButton::Middle => Self::Middle,
        }
    }
}

impl InputManager {
    /// Current state of modifier keys etc.
    pub fn state(&self) -> State {
        self.state
    }

    /// Events that came in during the last call to `update`.
    /// Each event comes with a `State` which can be used to check
    /// e.g. modifier keys and mouse position at the time of the event.
    pub fn events(&self) -> impl Iterator<Item = &(State, Event)> {
        self.events.iter()
    }

    /// Keys that are currently down.
    pub fn down_keys(&self) -> impl Iterator<Item = &Key> + '_ {
        self.down_keys.iter()
    }

    /// Gamepad buttons that are currently down.
    pub fn down_gamepad_buttons(&self) -> impl Iterator<Item = &GamepadButton> + '_ {
        self.down_gamepad_buttons.iter()
    }

    /// Is the key currently down?
    pub fn is_key_down(&self, key: Key) -> bool {
        self.down_keys.contains(&key)
    }

    /// Is the gamepad button currently down?
    pub fn is_gamepad_button_down(&self, button: GamepadButton) -> bool {
        self.down_gamepad_buttons.contains(&button)
    }

    /// Did the key go from not down to down in this frame?
    /// Also filters on modifies so you can check for e.g. `Cmd` + `Key::U`.
    pub fn was_key_pressed(&self, modifiers: Modifiers, key_needle: Key) -> bool {
        self.events().any(|(state, e)| {
            state.modifiers == modifiers
                && matches!(e, Event::Key{pressed: true, key} if *key == key_needle)
        })
    }

    /// Was e.g. `Command::Paste` issued this frame?
    pub fn was_command_made(&self, command_needle: Command) -> bool {
        self.events()
            .any(|(_, e)| matches!(e, Event::Command(command) if *command == command_needle))
    }

    /// Call this or [`Self::update_for_player`] once at the start of each frame.
    pub fn update(&mut self, applet: &applet::Applet) {
        self.update_for_player(applet, 0);
    }

    /// Call this or [`Self::update`] once at the start of each frame.
    pub fn update_for_player(&mut self, applet: &applet::Applet, player_id: u64) {
        let Self {
            events,
            state,
            down_keys,
            down_gamepad_buttons,
        } = self;

        events.clear();
        state.wall_time = applet.real_time_since_start();

        let window_state_width = if let Some(window_state) = applet.window_state_player(player_id) {
            window_state.width
        } else {
            1.0
        };

        use applet::{KeyInput, MouseInput, TouchInput};

        for event in applet.input_events_player(player_id) {
            match event {
                EventEnum::Key(event) => match event {
                    KeyInput::KeyPress(key) => {
                        let _: bool = down_keys.insert(key);

                        state.modifiers.cmd |=
                            matches!(key, VirtualKeyCode::LCommand | VirtualKeyCode::RCommand);

                        state.modifiers.shift |=
                            matches!(key, VirtualKeyCode::LShift | VirtualKeyCode::RShift);

                        state.modifiers.ctrl |=
                            matches!(key, VirtualKeyCode::LControl | VirtualKeyCode::RControl);

                        state.modifiers.alt |=
                            matches!(key, VirtualKeyCode::LAlt | VirtualKeyCode::RAlt);

                        // VirtualKeyCode Copy, Cut and Paste aren't actually sent from Ark, at least not on Mac.
                        // It would be better if Ark sent these commands, but ark doesn't, so we do manual detection:

                        if state.modifiers.is_cmd() && key == VirtualKeyCode::C {
                            events.push((*state, Event::Command(Command::Copy)));
                        } else if state.modifiers.is_cmd() && key == VirtualKeyCode::X {
                            events.push((*state, Event::Command(Command::Cut)));
                        } else if state.modifiers.is_cmd() && key == VirtualKeyCode::V {
                            events.push((*state, Event::Command(Command::Paste)));
                        } else if state.modifiers.is_cmd() && key == VirtualKeyCode::Z {
                            events.push((*state, Event::Command(Command::Undo)));
                        } else if state.modifiers.is_cmd_shift() && key == VirtualKeyCode::Z {
                            events.push((*state, Event::Command(Command::Redo)));
                        } else if state.modifiers.is_cmd() && key == VirtualKeyCode::S {
                            events.push((*state, Event::Command(Command::Save)));
                        } else if state.modifiers.is_cmd() && key == VirtualKeyCode::N {
                            events.push((*state, Event::Command(Command::New)));
                        } else {
                            events.push((*state, Event::Key { pressed: true, key }));
                        }
                    }
                    KeyInput::KeyRelease(key) => {
                        let _: bool = down_keys.remove(&key);

                        state.modifiers.cmd &=
                            !matches!(key, VirtualKeyCode::LCommand | VirtualKeyCode::RCommand);
                        state.modifiers.shift &=
                            !matches!(key, VirtualKeyCode::LShift | VirtualKeyCode::RShift);
                        state.modifiers.ctrl &=
                            !matches!(key, VirtualKeyCode::LControl | VirtualKeyCode::RControl);
                        state.modifiers.alt &=
                            !matches!(key, VirtualKeyCode::LAlt | VirtualKeyCode::RAlt);

                        events.push((
                            *state,
                            Event::Key {
                                pressed: false,
                                key,
                            },
                        ));
                    }
                    KeyInput::Text(chr) => {
                        if !state.modifiers.ctrl && !state.modifiers.cmd {
                            // \r is nonsense. Nobody likes \r.
                            // But Ark sends \r when you press enter, so we fix that here.
                            let chr = if chr == '\r' { '\n' } else { chr };
                            events.push((*state, Event::Char(chr)));
                        }
                    }
                },

                EventEnum::Mouse(event) => match event {
                    MouseInput::ButtonPress {
                        button,
                        pos,
                        ray_origin,
                        ray_dir,
                    } => {
                        let ray = Ray3::from_origin_dir(ray_origin, ray_dir);
                        state.pointer.pos = Some(pos);
                        state.pointer.ray = Some(ray);
                        match button {
                            applet::MouseButton::Primary => {
                                state.pointer.primary = true;
                            }
                            applet::MouseButton::Secondary => {
                                state.pointer.secondary = true;
                            }
                            applet::MouseButton::Middle => {
                                state.pointer.middle = true;
                            }
                        }
                        events.push((
                            *state,
                            Event::PointerButton {
                                pressed: true,
                                pointer: Pointer::Mouse,
                                button: PointerButton::from_mouse_button(button),
                                pos,
                                ray,
                                primary: true,
                            },
                        ));
                    }
                    MouseInput::ButtonRelease {
                        button,
                        pos,
                        ray_origin,
                        ray_dir,
                    } => {
                        let ray = Ray3::from_origin_dir(ray_origin, ray_dir);
                        state.pointer.pos = Some(pos);
                        state.pointer.ray = Some(ray);
                        match button {
                            applet::MouseButton::Primary => {
                                state.pointer.primary = false;
                            }
                            applet::MouseButton::Secondary => {
                                state.pointer.secondary = false;
                            }
                            applet::MouseButton::Middle => {
                                state.pointer.middle = false;
                            }
                        }
                        events.push((
                            *state,
                            Event::PointerButton {
                                pressed: false,
                                pointer: Pointer::Mouse,
                                button: PointerButton::from_mouse_button(button),
                                pos,
                                ray,
                                primary: true,
                            },
                        ));
                    }
                    MouseInput::Move {
                        pos,
                        ray_origin,
                        ray_dir,
                    } => {
                        let ray = Ray3::from_origin_dir(ray_origin, ray_dir);
                        state.pointer.pos = Some(pos);
                        state.pointer.ray = Some(ray);
                        events.push((
                            *state,
                            Event::PointerMove {
                                pointer: Pointer::Mouse,
                                pos,
                                ray,
                                primary: true,
                            },
                        ));
                    }
                    MouseInput::RelativeMove {
                        delta_logical_pixels,
                        delta_angle,
                    } => {
                        events.push((
                            *state,
                            Event::PointerDelta {
                                pointer: Pointer::Mouse,
                                delta_angle,
                                delta_points: delta_logical_pixels,
                                delta_normalized: delta_logical_pixels
                                    / window_state_width.max(1.0),
                                primary: true,
                            },
                        ));
                    }
                    MouseInput::Scroll { delta } => {
                        events.push((*state, Event::Scroll { delta }));
                    }
                },
                EventEnum::Axis(event) => events.push((
                    *state,
                    Event::Axis {
                        axis: event.axis,
                        value: event.value,
                    },
                )),
                EventEnum::GamepadButton(event) => {
                    if event.is_pressed {
                        down_gamepad_buttons.insert(event.button);
                    } else {
                        down_gamepad_buttons.remove(&event.button);
                    }

                    events.push((
                        *state,
                        Event::GamepadButton {
                            button: event.button,
                            press: event.is_pressed,
                        },
                    ));
                }
                EventEnum::RawMidi(event) => events.push((
                    *state,
                    Event::RawMidi {
                        timestamp: event.timestamp,
                        data: event.data,
                        len: event.len,
                        device_id: event.device_id,
                    },
                )),
                EventEnum::Touch(event) => match event {
                    TouchInput::Started {
                        finger_id,
                        pos,
                        ray_origin,
                        ray_dir,
                    } => {
                        let touch_id = TouchId(finger_id);
                        let ray = Ray3::from_origin_dir(ray_origin, ray_dir);

                        state.pointer.touch_id = state.pointer.touch_id.or(Some(touch_id));

                        let primary = state.pointer.touch_id == Some(touch_id);
                        if primary {
                            state.pointer.pos = Some(pos);
                            state.pointer.ray = Some(ray);
                            state.pointer.primary = true;
                        }

                        events.push((
                            *state,
                            Event::PointerButton {
                                pressed: true,
                                pointer: Pointer::Touch(touch_id),
                                button: PointerButton::Primary,
                                pos,
                                ray,
                                primary,
                            },
                        ));
                    }
                    TouchInput::Move {
                        finger_id,
                        pos,
                        ray_origin,
                        ray_dir,
                    } => {
                        let touch_id = TouchId(finger_id);
                        let ray = Ray3::from_origin_dir(ray_origin, ray_dir);

                        let primary = state.pointer.touch_id == Some(touch_id);
                        if primary {
                            state.pointer.pos = Some(pos);
                            state.pointer.ray = Some(ray);
                        }

                        events.push((
                            *state,
                            Event::PointerMove {
                                pointer: Pointer::Touch(touch_id),
                                pos,
                                ray,
                                primary,
                            },
                        ));
                    }
                    TouchInput::RelativeMove {
                        finger_id,
                        delta_logical_pixels,
                        delta_angle,
                    } => {
                        let touch_id = TouchId(finger_id);
                        let primary = state.pointer.touch_id == Some(touch_id);
                        events.push((
                            *state,
                            Event::PointerDelta {
                                pointer: Pointer::Touch(touch_id),
                                delta_angle,
                                delta_points: delta_logical_pixels,
                                delta_normalized: delta_logical_pixels
                                    / window_state_width.max(1.0),
                                primary,
                            },
                        ));
                    }
                    TouchInput::Ended {
                        finger_id,
                        pos,
                        ray_origin,
                        ray_dir,
                    } => {
                        let touch_id = TouchId(finger_id);
                        let ray = Ray3::from_origin_dir(ray_origin, ray_dir);

                        let primary = state.pointer.touch_id == Some(touch_id);
                        if primary {
                            state.pointer.pos = Some(pos);
                            state.pointer.ray = Some(ray);
                            state.pointer.primary = false;
                        }

                        events.push((
                            *state,
                            Event::PointerButton {
                                pressed: false,
                                pointer: Pointer::Touch(touch_id),
                                button: PointerButton::Primary,
                                pos,
                                ray,
                                primary,
                            },
                        ));

                        if state.pointer.touch_id == Some(touch_id) {
                            state.pointer.touch_id = None;
                        }
                    }
                },
            }
        }
    }
}