mirage-engine 0.2.0

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
Documentation
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Device controls, and the typed bindings that turn them into a game's
//! actions.

use core::fmt;

use winit::keyboard::KeyCode;

use crate::math::Vec2;

/// The deepest a deadzone may be, so that a control keeps a range to
/// read in.
const MOST_DEADZONE: f32 = 0.95;

/// One device's controls: the values, the text a controls menu shows, and
/// the names the store writes.
macro_rules! controls {
    (
        $(#[$meta:meta])*
        $name:ident, $noun:literal { $($variant:ident $text:literal),* $(,)? }
    ) => {
        $(#[$meta])*
        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
        #[repr(u8)]
        pub enum $name {
            $(
                #[doc = concat!("The `", stringify!($variant), "` ", $noun, ".")]
                $variant,
            )*
        }

        impl $name {
            pub(crate) fn token(self) -> &'static str {
                match self {
                    $(Self::$variant => stringify!($variant),)*
                }
            }

            pub(crate) fn from_token(token: &str) -> Option<Self> {
                match token {
                    $(stringify!($variant) => Some(Self::$variant),)*
                    _ => None,
                }
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(match self {
                    $(Self::$variant => $text,)*
                })
            }
        }
    };
}

/// The same, plus the list capture walks looking for what the player moved.
macro_rules! listed {
    (
        $(#[$meta:meta])*
        $name:ident, $noun:literal { $($variant:ident $text:literal),* $(,)? }
    ) => {
        controls! { $(#[$meta])* $name, $noun { $($variant $text),* } }

        impl $name {
            pub(crate) const ALL: &'static [Self] = &[$(Self::$variant),*];
        }
    };
}

/// The same, plus a place of its own in a reading for each control.
macro_rules! indexed {
    (
        $(#[$meta:meta])*
        $name:ident, $noun:literal { $($variant:ident $text:literal),* $(,)? }
    ) => {
        listed! { $(#[$meta])* $name, $noun { $($variant $text),* } }

        impl $name {
            pub(crate) const COUNT: usize = Self::ALL.len();

            pub(crate) fn index(self) -> usize {
                self as usize
            }
        }
    };
}

// One list keeps the key vocabulary and its winit mapping from drifting apart.
macro_rules! keys {
    ($($variant:ident $text:literal $code:ident),* $(,)?) => {
        indexed! {
            /// A key by physical position, independent of the layout in use:
            /// [`Key::W`] is the key at the `W` position on a US keyboard.
            ///
            /// Text entry belongs to the UI layer, not here. A key is also a
            /// button vocabulary of its own, which is what a prototype binds
            /// through before it declares its actions.
            Key, "key position" { $($variant $text),* }
        }

        impl Key {
            pub(crate) fn from_code(code: KeyCode) -> Option<Self> {
                match code {
                    $(KeyCode::$code => Some(Self::$variant),)*
                    _ => None,
                }
            }
        }
    };
}

keys! {
    A "A" KeyA, B "B" KeyB, C "C" KeyC, D "D" KeyD, E "E" KeyE, F "F" KeyF,
    G "G" KeyG, H "H" KeyH, I "I" KeyI, J "J" KeyJ, K "K" KeyK, L "L" KeyL,
    M "M" KeyM, N "N" KeyN, O "O" KeyO, P "P" KeyP, Q "Q" KeyQ, R "R" KeyR,
    S "S" KeyS, T "T" KeyT, U "U" KeyU, V "V" KeyV, W "W" KeyW, X "X" KeyX,
    Y "Y" KeyY, Z "Z" KeyZ,
    Digit0 "0" Digit0, Digit1 "1" Digit1, Digit2 "2" Digit2, Digit3 "3" Digit3,
    Digit4 "4" Digit4, Digit5 "5" Digit5, Digit6 "6" Digit6, Digit7 "7" Digit7,
    Digit8 "8" Digit8, Digit9 "9" Digit9,
    Left "Left Arrow" ArrowLeft, Right "Right Arrow" ArrowRight,
    Up "Up Arrow" ArrowUp, Down "Down Arrow" ArrowDown,
    Space "Space" Space, Enter "Enter" Enter, Escape "Escape" Escape,
    Tab "Tab" Tab, Backspace "Backspace" Backspace,
    LeftShift "Left Shift" ShiftLeft, RightShift "Right Shift" ShiftRight,
    LeftControl "Left Control" ControlLeft, RightControl "Right Control" ControlRight,
    LeftAlt "Left Alt" AltLeft, RightAlt "Right Alt" AltRight,
    F1 "F1" F1, F2 "F2" F2, F3 "F3" F3, F4 "F4" F4, F5 "F5" F5, F6 "F6" F6,
    F7 "F7" F7, F8 "F8" F8, F9 "F9" F9, F10 "F10" F10, F11 "F11" F11,
    F12 "F12" F12,
    Minus "-" Minus, Equal "=" Equal,
    BracketLeft "[" BracketLeft, BracketRight "]" BracketRight,
    Semicolon ";" Semicolon, Quote "'" Quote, Backquote "`" Backquote,
    Backslash "\\" Backslash, Comma "," Comma, Period "." Period,
    Slash "/" Slash,
    Home "Home" Home, End "End" End,
    PageUp "Page Up" PageUp, PageDown "Page Down" PageDown,
    Insert "Insert" Insert, Delete "Delete" Delete,
    CapsLock "Caps Lock" CapsLock,
    Numpad0 "Numpad 0" Numpad0, Numpad1 "Numpad 1" Numpad1,
    Numpad2 "Numpad 2" Numpad2, Numpad3 "Numpad 3" Numpad3,
    Numpad4 "Numpad 4" Numpad4, Numpad5 "Numpad 5" Numpad5,
    Numpad6 "Numpad 6" Numpad6, Numpad7 "Numpad 7" Numpad7,
    Numpad8 "Numpad 8" Numpad8, Numpad9 "Numpad 9" Numpad9,
    NumpadAdd "Numpad +" NumpadAdd,
    NumpadSubtract "Numpad -" NumpadSubtract,
    NumpadMultiply "Numpad *" NumpadMultiply,
    NumpadDivide "Numpad /" NumpadDivide,
    NumpadDecimal "Numpad ." NumpadDecimal,
    NumpadEnter "Numpad Enter" NumpadEnter,
    NumLock "Num Lock" NumLock,
}

indexed! {
    /// A mouse button. The first touch of a touch screen presses
    /// [`MouseButton::Left`], wherever it lands.
    MouseButton, "mouse button" {
        Left "Left Mouse",
        Right "Right Mouse",
        Middle "Middle Mouse",
    }
}

indexed! {
    /// A button of the standard gamepad layout, by its position rather than
    /// by what a maker prints on it.
    Pad, "pad button" {
        South "Pad South",
        East "Pad East",
        West "Pad West",
        North "Pad North",
        LeftBumper "Left Bumper",
        RightBumper "Right Bumper",
        LeftTrigger "Left Trigger",
        RightTrigger "Right Trigger",
        Select "Select",
        Start "Start",
        Guide "Guide",
        LeftStick "Left Stick Press",
        RightStick "Right Stick Press",
        DPadUp "D-Pad Up",
        DPadDown "D-Pad Down",
        DPadLeft "D-Pad Left",
        DPadRight "D-Pad Right",
    }
}

indexed! {
    /// One lane of the standard gamepad layout: positive is right and up,
    /// and a trigger reads `0..=1` of the range.
    PadAxis, "pad axis" {
        LeftX "Left Stick Sideways",
        LeftY "Left Stick Up",
        RightX "Right Stick Sideways",
        RightY "Right Stick Up",
        LeftTrigger "Left Trigger",
        RightTrigger "Right Trigger",
    }
}

listed! {
    /// A stick of the standard gamepad layout, read as both its lanes at
    /// once.
    Stick, "stick" {
        Left "Left Stick",
        Right "Right Stick",
    }
}

controls! {
    /// One lane of the pointer, reporting how far it moved since the last
    /// frame rather than where it is, so its range is open and
    /// [`AxisBinding::scale`] is what bounds it.
    PointerDelta, "pointer lane" {
        Sideways "Pointer Sideways",
        Up "Pointer Up",
    }
}

impl PointerDelta {
    /// `pixels` along this lane as a movement of the whole pointer,
    /// counted right and up.
    #[cfg(feature = "offscreen")]
    pub(crate) fn moving(self, pixels: f32) -> Vec2 {
        match self {
            Self::Sideways => Vec2::new(pixels, 0.0),
            Self::Up => Vec2::new(0.0, pixels),
        }
    }
}

controls! {
    /// One lane of the wheel, reporting the notches it turned since the
    /// last frame, so its range is open and [`AxisBinding::scale`] is what
    /// bounds it.
    ///
    /// One notch of a mouse wheel is `1` on every target. [`WheelDelta::Up`]
    /// counts a roll away from the player and [`WheelDelta::Sideways`] a
    /// tilt to the right: right and away, as [`PointerDelta`] counts right
    /// and up.
    WheelDelta, "wheel lane" {
        Sideways "Wheel Sideways",
        Up "Wheel Up",
    }
}

impl WheelDelta {
    /// `notches` along this lane as a turn of the whole wheel, counted
    /// right and away.
    #[cfg(feature = "offscreen")]
    pub(crate) fn turning(self, notches: f32) -> Vec2 {
        match self {
            Self::Sideways => Vec2::new(notches, 0.0),
            Self::Up => Vec2::new(0.0, notches),
        }
    }
}

impl Key {
    /// This key as the UI names it, `None` where the UI names no key in
    /// this position. Only a session passes a key to the UI: a window's
    /// keys reach it through `egui-winit` instead.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn ui_key(self) -> Option<egui::Key> {
        use egui::Key as Ui;

        Some(match self {
            Self::A => Ui::A,
            Self::B => Ui::B,
            Self::C => Ui::C,
            Self::D => Ui::D,
            Self::E => Ui::E,
            Self::F => Ui::F,
            Self::G => Ui::G,
            Self::H => Ui::H,
            Self::I => Ui::I,
            Self::J => Ui::J,
            Self::K => Ui::K,
            Self::L => Ui::L,
            Self::M => Ui::M,
            Self::N => Ui::N,
            Self::O => Ui::O,
            Self::P => Ui::P,
            Self::Q => Ui::Q,
            Self::R => Ui::R,
            Self::S => Ui::S,
            Self::T => Ui::T,
            Self::U => Ui::U,
            Self::V => Ui::V,
            Self::W => Ui::W,
            Self::X => Ui::X,
            Self::Y => Ui::Y,
            Self::Z => Ui::Z,
            Self::Digit0 | Self::Numpad0 => Ui::Num0,
            Self::Digit1 | Self::Numpad1 => Ui::Num1,
            Self::Digit2 | Self::Numpad2 => Ui::Num2,
            Self::Digit3 | Self::Numpad3 => Ui::Num3,
            Self::Digit4 | Self::Numpad4 => Ui::Num4,
            Self::Digit5 | Self::Numpad5 => Ui::Num5,
            Self::Digit6 | Self::Numpad6 => Ui::Num6,
            Self::Digit7 | Self::Numpad7 => Ui::Num7,
            Self::Digit8 | Self::Numpad8 => Ui::Num8,
            Self::Digit9 | Self::Numpad9 => Ui::Num9,
            Self::Left => Ui::ArrowLeft,
            Self::Right => Ui::ArrowRight,
            Self::Up => Ui::ArrowUp,
            Self::Down => Ui::ArrowDown,
            Self::Space => Ui::Space,
            Self::Enter | Self::NumpadEnter => Ui::Enter,
            Self::Escape => Ui::Escape,
            Self::Tab => Ui::Tab,
            Self::Backspace => Ui::Backspace,
            Self::F1 => Ui::F1,
            Self::F2 => Ui::F2,
            Self::F3 => Ui::F3,
            Self::F4 => Ui::F4,
            Self::F5 => Ui::F5,
            Self::F6 => Ui::F6,
            Self::F7 => Ui::F7,
            Self::F8 => Ui::F8,
            Self::F9 => Ui::F9,
            Self::F10 => Ui::F10,
            Self::F11 => Ui::F11,
            Self::F12 => Ui::F12,
            Self::Minus | Self::NumpadSubtract => Ui::Minus,
            Self::Equal => Ui::Equals,
            Self::NumpadAdd => Ui::Plus,
            Self::BracketLeft => Ui::OpenBracket,
            Self::BracketRight => Ui::CloseBracket,
            Self::Semicolon => Ui::Semicolon,
            Self::Quote => Ui::Quote,
            Self::Backquote => Ui::Backtick,
            Self::Backslash => Ui::Backslash,
            Self::Comma => Ui::Comma,
            Self::Period | Self::NumpadDecimal => Ui::Period,
            Self::Slash | Self::NumpadDivide => Ui::Slash,
            Self::Home => Ui::Home,
            Self::End => Ui::End,
            Self::PageUp => Ui::PageUp,
            Self::PageDown => Ui::PageDown,
            Self::Insert => Ui::Insert,
            Self::Delete => Ui::Delete,
            Self::LeftShift
            | Self::RightShift
            | Self::LeftControl
            | Self::RightControl
            | Self::LeftAlt
            | Self::RightAlt
            | Self::CapsLock
            | Self::NumLock
            | Self::NumpadMultiply => return None,
        })
    }
}

impl MouseButton {
    /// This button as the UI names it, for the session that passes it; a
    /// window's buttons reach the UI through `egui-winit` instead.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn ui_button(self) -> egui::PointerButton {
        match self {
            Self::Left => egui::PointerButton::Primary,
            Self::Right => egui::PointerButton::Secondary,
            Self::Middle => egui::PointerButton::Middle,
        }
    }

    pub(crate) fn from_winit(button: winit::event::MouseButton) -> Option<Self> {
        match button {
            winit::event::MouseButton::Left => Some(Self::Left),
            winit::event::MouseButton::Right => Some(Self::Right),
            winit::event::MouseButton::Middle => Some(Self::Middle),
            _ => None,
        }
    }
}

impl Stick {
    /// The two lanes this stick reads through, sideways then up.
    pub(crate) fn lanes(self) -> (PadAxis, PadAxis) {
        match self {
            Self::Left => (PadAxis::LeftX, PadAxis::LeftY),
            Self::Right => (PadAxis::RightX, PadAxis::RightY),
        }
    }
}

/// One control that reads back `true` while it is held.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ButtonBinding {
    /// A key, by physical position.
    Key(Key),
    /// A mouse button, which the first touch of a touch screen also presses.
    Mouse(MouseButton),
    /// A button of the standard gamepad layout.
    Pad(Pad),
    /// A button of a device with no standard layout, by the number its
    /// platform reports for it; capture one rather than writing one.
    Joystick(JoystickControl),
}

impl From<Key> for ButtonBinding {
    fn from(key: Key) -> Self {
        Self::Key(key)
    }
}

impl From<MouseButton> for ButtonBinding {
    fn from(button: MouseButton) -> Self {
        Self::Mouse(button)
    }
}

impl From<Pad> for ButtonBinding {
    fn from(button: Pad) -> Self {
        Self::Pad(button)
    }
}

impl fmt::Display for ButtonBinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Key(key) => key.fmt(f),
            Self::Mouse(button) => button.fmt(f),
            Self::Pad(button) => button.fmt(f),
            Self::Joystick(control) => write!(f, "Joystick {control}"),
        }
    }
}

/// A control of a device with no standard layout, by the number its
/// platform reports for it: captured rather than written, and usable only on
/// the machine that captured it.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct JoystickControl(u32);

impl JoystickControl {
    pub(crate) const fn new(control: u32) -> Self {
        Self(control)
    }
}

impl fmt::Display for JoystickControl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// One control that reads back a number, and the knobs it reads through.
///
/// A pad lane, a trigger, a joystick axis and a button composite read in
/// `-1..=1`. A [`PointerDelta`] lane and a [`WheelDelta`] lane read how far
/// they moved through [`scale`](Self::scale), which nothing clamps.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AxisBinding {
    pub(crate) source: AxisSource,
    pub(crate) knobs: Knobs,
}

impl AxisBinding {
    /// Distance a pad or joystick control moves before it reads at all.
    pub const DEFAULT_DEADZONE: f32 = 0.15;

    /// One lane of the standard gamepad layout.
    pub fn pad(axis: PadAxis) -> Self {
        Self::of(AxisSource::Pad(axis))
    }

    /// One axis of a device with no standard layout, by the number its
    /// platform reports for it; capture one rather than writing one.
    pub fn joystick(control: JoystickControl) -> Self {
        Self::of(AxisSource::Joystick(control))
    }

    /// Pixels one lane of the pointer moved this frame, read through
    /// [`scale`](Self::scale) alone: nothing clamps what it reads.
    pub fn pointer_delta(lane: PointerDelta) -> Self {
        Self::of(AxisSource::Pointer(lane))
    }

    /// Notches `lane` of the wheel turned this frame, read through
    /// [`scale`](Self::scale) alone: nothing clamps what it reads.
    pub fn wheel(lane: WheelDelta) -> Self {
        Self::of(AxisSource::Wheel(lane))
    }

    /// `raw` as this binding reads it: the knobs applied, then the range
    /// the source reads in.
    pub(crate) fn resolve(&self, raw: f32) -> f32 {
        self.knobs.applied(raw, self.source.reach())
    }

    fn of(source: AxisSource) -> Self {
        Self {
            source,
            knobs: source.knobs(),
        }
    }
}

impl From<PadAxis> for AxisBinding {
    fn from(axis: PadAxis) -> Self {
        Self::pad(axis)
    }
}

impl From<PointerDelta> for AxisBinding {
    fn from(lane: PointerDelta) -> Self {
        Self::pointer_delta(lane)
    }
}

impl From<WheelDelta> for AxisBinding {
    fn from(lane: WheelDelta) -> Self {
        Self::wheel(lane)
    }
}

impl fmt::Display for AxisBinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.source {
            AxisSource::Pad(axis) => axis.fmt(f),
            AxisSource::Joystick(control) => write!(f, "Joystick Axis {control}"),
            AxisSource::Pointer(lane) => lane.fmt(f),
            AxisSource::Wheel(lane) => lane.fmt(f),
            AxisSource::Buttons { negative, positive } => write!(f, "{negative} / {positive}"),
        }
    }
}

/// A pair of controls that read back a vector, and the knobs they read
/// through.
///
/// A stick and a button composite read no longer than `1`. The pointer and
/// the wheel read how far they moved through [`scale`](Self::scale), which
/// nothing clamps.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Axis2Binding {
    pub(crate) source: Axis2Source,
    pub(crate) knobs: Knobs,
}

impl Axis2Binding {
    /// Both lanes of one stick of the standard gamepad layout.
    pub fn stick(stick: Stick) -> Self {
        Self::of(Axis2Source::Stick(stick))
    }

    /// Pixels the pointer moved this frame, read through
    /// [`scale`](Self::scale) alone: nothing clamps what it reads.
    pub fn pointer() -> Self {
        Self::of(Axis2Source::Pointer)
    }

    /// Notches the wheel turned this frame, both lanes as one vector:
    /// [`WheelDelta::Sideways`] is `x` and [`WheelDelta::Up`] is `y`. Read
    /// through [`scale`](Self::scale) alone, so nothing clamps what it reads.
    pub fn wheel() -> Self {
        Self::of(Axis2Source::Wheel)
    }

    /// `raw` as this binding reads it: the knobs applied, then the range
    /// the source reads in.
    pub(crate) fn resolve(&self, raw: Vec2) -> Vec2 {
        self.knobs.applied2(raw, self.source.reach())
    }

    fn of(source: Axis2Source) -> Self {
        Self {
            source,
            knobs: source.knobs(),
        }
    }
}

impl<L, R, D, U> From<ButtonAxis2<L, R, D, U>> for Axis2Binding
where
    L: Into<ButtonBinding>,
    R: Into<ButtonBinding>,
    D: Into<ButtonBinding>,
    U: Into<ButtonBinding>,
{
    /// Four buttons around a center, the way `WASD` is laid out; a diagonal
    /// reads as long as a straight direction, never longer. The vector is
    /// `x` right minus left, `y` up minus down; what that means in the
    /// world is the game's call.
    fn from(quad: ButtonAxis2<L, R, D, U>) -> Self {
        Self::of(Axis2Source::Buttons {
            left: quad.left.into(),
            right: quad.right.into(),
            down: quad.down.into(),
            up: quad.up.into(),
        })
    }
}

impl From<Stick> for Axis2Binding {
    fn from(stick: Stick) -> Self {
        Self::stick(stick)
    }
}

impl fmt::Display for Axis2Binding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.source {
            Axis2Source::Stick(stick) => stick.fmt(f),
            Axis2Source::Pointer => f.write_str("Pointer"),
            Axis2Source::Wheel => f.write_str("Wheel"),
            Axis2Source::Buttons {
                left,
                right,
                down,
                up,
            } => write!(f, "{left} / {right} / {down} / {up}"),
        }
    }
}

/// Source one axis takes its number from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum AxisSource {
    Pad(PadAxis),
    Joystick(JoystickControl),
    Pointer(PointerDelta),
    Wheel(WheelDelta),
    Buttons {
        negative: ButtonBinding,
        positive: ButtonBinding,
    },
}

impl AxisSource {
    /// Range a binding over this source reads in.
    fn reach(self) -> Reach {
        match self {
            Self::Pointer(_) | Self::Wheel(_) => Reach::Open,
            Self::Pad(_) | Self::Joystick(_) | Self::Buttons { .. } => Reach::Unit,
        }
    }

    /// The knobs a binding over this source starts at.
    fn knobs(self) -> Knobs {
        match self {
            Self::Pad(_) | Self::Joystick(_) => Knobs::at(AxisBinding::DEFAULT_DEADZONE),
            Self::Pointer(_) | Self::Wheel(_) | Self::Buttons { .. } => Knobs::at(0.0),
        }
    }
}

/// Source one vector takes its two numbers from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Axis2Source {
    Stick(Stick),
    Pointer,
    Wheel,
    Buttons {
        left: ButtonBinding,
        right: ButtonBinding,
        down: ButtonBinding,
        up: ButtonBinding,
    },
}

impl Axis2Source {
    /// Range a binding over this source reads in.
    fn reach(self) -> Reach {
        match self {
            Self::Pointer | Self::Wheel => Reach::Open,
            Self::Stick(_) | Self::Buttons { .. } => Reach::Unit,
        }
    }

    /// The knobs a binding over this source starts at.
    fn knobs(self) -> Knobs {
        match self {
            Self::Stick(_) => Knobs::at(AxisBinding::DEFAULT_DEADZONE),
            Self::Pointer | Self::Wheel | Self::Buttons { .. } => Knobs::at(0.0),
        }
    }
}

/// Range a source's readings lie in, which the source itself decides: a pad
/// or joystick control, a stick and a button composite each have a range of
/// their own, and a pointer lane or a wheel lane reports a distance with
/// none.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Reach {
    /// The whole of a control's own range, `-1..=1`.
    Unit,
    /// However far the control moved, which its scale multiplies.
    Open,
}

impl Reach {
    /// `value` held to this range. A value that is not finite reads as
    /// nothing, which is what keeps every query total.
    fn hold(self, value: f32) -> f32 {
        match (self, value.is_finite()) {
            (_, false) => 0.0,
            (Self::Unit, true) => value.clamp(-1.0, 1.0),
            (Self::Open, true) => value,
        }
    }
}

/// Two buttons that make an axis: `negative` counts down, `positive` counts
/// up.
#[derive(Clone, Copy, Debug)]
pub struct ButtonAxis<
    N: Into<ButtonBinding> = ButtonBinding,
    P: Into<ButtonBinding> = ButtonBinding,
> {
    /// The button counting down.
    pub negative: N,
    /// The button counting up.
    pub positive: P,
}

/// Four buttons that make a vector, the way `WASD` is laid out.
#[derive(Clone, Copy, Debug)]
pub struct ButtonAxis2<
    L: Into<ButtonBinding> = ButtonBinding,
    R: Into<ButtonBinding> = ButtonBinding,
    D: Into<ButtonBinding> = ButtonBinding,
    U: Into<ButtonBinding> = ButtonBinding,
> {
    /// The button counting left.
    pub left: L,
    /// The button counting right.
    pub right: R,
    /// The button counting down.
    pub down: D,
    /// The button counting up.
    pub up: U,
}

/// Distance a control must move before it reads at all, held to the range a
/// control keeps to read in.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Deadzone(f32);

impl Deadzone {
    /// `deadzone`, held to the range a control keeps to read in; one that is
    /// not a number opens the range whole, which `clamp` would not.
    pub(crate) fn new(deadzone: f32) -> Self {
        Self(MOST_DEADZONE.min(deadzone.max(0.0)))
    }

    /// The amount of `magnitude` that lies past this deadzone, stretched so
    /// that a control leaves it at nothing and covers the whole range at
    /// one.
    fn past(self, magnitude: f32) -> f32 {
        ((magnitude - self.0) / (1.0 - self.0)).max(0.0)
    }

    /// The deadzone as the number a game set, or the store reads back.
    pub(crate) fn get(self) -> f32 {
        self.0
    }
}

/// Distance a control must move before it reads at all, how much of it
/// the action reads, and which way round.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Knobs {
    pub(crate) deadzone: Deadzone,
    pub(crate) scale: f32,
    pub(crate) inverted: bool,
}

impl Knobs {
    /// The knobs a binding starts at, reading nothing until the control has
    /// moved `deadzone` of its way and the whole of it after that.
    fn at(deadzone: f32) -> Self {
        Self {
            deadzone: Deadzone::new(deadzone),
            scale: 1.0,
            inverted: false,
        }
    }

    /// The knobs one stored line reads back as, clamped like the ones a
    /// game sets by hand.
    pub(crate) fn stored(deadzone: Deadzone, scale: f32, inverted: bool) -> Self {
        Self {
            deadzone,
            scale,
            inverted,
        }
    }

    /// `raw` once the deadzone, the scale and the direction are applied,
    /// held to `reach`.
    fn applied(self, raw: f32, reach: Reach) -> f32 {
        reach.hold(self.deadzone.past(raw.abs()).copysign(raw) * self.scale * self.turned())
    }

    /// The same for a vector, whose deadzone is over its length rather
    /// than over either lane.
    fn applied2(self, raw: Vec2, reach: Reach) -> Vec2 {
        let raw = Vec2::new(raw.x, raw.y * self.turned());
        let length = raw.length();
        if !length.is_finite() || length <= f32::EPSILON {
            return Vec2::ZERO;
        }
        raw / length * reach.hold(self.deadzone.past(length) * self.scale)
    }

    fn turned(self) -> f32 {
        match self.inverted {
            true => -1.0,
            false => 1.0,
        }
    }
}

/// The knobs every analog binding holds.
macro_rules! knobs {
    ($name:ident, $lane:literal) => {
        impl $name {
            /// Reads nothing until the control has moved `deadzone` of its
            /// way, then stretches what is left over the whole range;
            /// [`AxisBinding::DEFAULT_DEADZONE`] for a pad or joystick
            /// control, and nothing for the rest.
            ///
            /// Clamped into `0.0..=0.95`, a fraction of that way, so a
            /// control always keeps a range to read in.
            #[must_use]
            pub fn deadzone(mut self, deadzone: f32) -> Self {
                self.knobs.deadzone = Deadzone::new(deadzone);
                self
            }

            /// Multiplies what the control reads, as a fraction of it;
            /// `1.0` until set.
            ///
            /// A control with a range of its own keeps to it whatever
            /// this is set to. A pointer lane or a wheel lane has none, so
            /// it reads its own distance times this: pixels for a pointer
            /// lane, notches for a wheel lane.
            #[must_use]
            pub fn scale(mut self, scale: f32) -> Self {
                self.knobs.scale = scale;
                self
            }

            #[doc = concat!("Flips ", $lane, ", for a control that reads the other way round.")]
            #[must_use]
            pub fn invert(mut self) -> Self {
                self.knobs.inverted = true;
                self
            }
        }
    };
}

knobs!(AxisBinding, "which way the control counts");
knobs!(Axis2Binding, "the upward lane");

impl<N: Into<ButtonBinding>, P: Into<ButtonBinding>> From<ButtonAxis<N, P>> for AxisBinding {
    /// A pair, `negative` counting down and `positive` counting up; a
    /// diagonal never reads longer than a straight direction.
    fn from(pair: ButtonAxis<N, P>) -> Self {
        Self::of(AxisSource::Buttons {
            negative: pair.negative.into(),
            positive: pair.positive.into(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn physical_positions_map_to_keys() {
        assert_eq!(Key::from_code(KeyCode::KeyW), Some(Key::W));
        assert_eq!(Key::from_code(KeyCode::ArrowLeft), Some(Key::Left));
        assert_eq!(Key::from_code(KeyCode::ShiftLeft), Some(Key::LeftShift));
        assert_eq!(
            Key::from_code(KeyCode::F13),
            None,
            "keys we skip are ignored"
        );
    }

    #[test]
    fn the_punctuation_and_pad_positions_read_and_show_like_the_rest() {
        assert_eq!(Key::from_code(KeyCode::BracketLeft), Some(Key::BracketLeft));
        assert_eq!(Key::BracketLeft.to_string(), "[");
        assert_eq!(Key::from_code(KeyCode::NumpadAdd), Some(Key::NumpadAdd));
        assert_eq!(Key::NumpadAdd.to_string(), "Numpad +");
    }

    #[test]
    fn a_control_answers_to_its_own_name_and_shows_a_readable_one() {
        assert_eq!(Key::from_token("LeftShift"), Some(Key::LeftShift));
        assert_eq!(Key::LeftShift.token(), "LeftShift");
        assert_eq!(Key::LeftShift.to_string(), "Left Shift");
        assert_eq!(PadAxis::from_token("Left Trigger"), None, "names are exact");
        assert_eq!(PadAxis::RightTrigger.to_string(), "Right Trigger");
    }

    #[test]
    fn a_deadzone_starts_the_range_where_it_ends() {
        let stick = AxisBinding::pad(PadAxis::LeftX).deadzone(0.5);

        assert_eq!(stick.resolve(0.5), 0.0, "the edge reads as nothing");
        assert_eq!(stick.resolve(0.25), 0.0, "and so does anything under");
        assert_eq!(stick.resolve(1.0), 1.0, "the far end still reaches");
        assert_eq!(stick.resolve(-0.75), -0.5, "in both directions");
    }

    #[test]
    fn a_control_with_a_range_of_its_own_keeps_to_it_however_the_knobs_are_set() {
        let lane = AxisBinding::pad(PadAxis::LeftX).deadzone(0.0).scale(100.0);
        assert_eq!(lane.resolve(1.0), 1.0);
        assert_eq!(lane.resolve(-1.0), -1.0);

        let quad = Axis2Binding::from(ButtonAxis2 {
            left: Key::A,
            right: Key::D,
            down: Key::S,
            up: Key::W,
        })
        .scale(100.0);
        assert_eq!(quad.resolve(Vec2::X), Vec2::X);

        let broken = AxisBinding::pad(PadAxis::LeftX).scale(f32::NAN);
        assert_eq!(broken.resolve(1.0), 0.0, "and stays a number");

        let deep = AxisBinding::pad(PadAxis::LeftX).deadzone(4.0);
        assert_eq!(deep.knobs.deadzone.get(), MOST_DEADZONE);
    }

    #[test]
    fn a_delta_binding_reads_the_whole_distance_its_scale_makes_of_it() {
        let look = AxisBinding::pointer_delta(PointerDelta::Sideways).scale(0.01);
        assert_eq!(look.resolve(500.0), 5.0);
        assert_eq!(look.resolve(-500.0), -5.0);

        let wheel = AxisBinding::wheel(WheelDelta::Up).scale(100.0);
        assert_eq!(wheel.resolve(4.0), 400.0);

        let pointer = Axis2Binding::pointer().scale(0.01);
        assert_eq!(pointer.resolve(Vec2::new(500.0, 0.0)), Vec2::new(5.0, 0.0));

        let broken = AxisBinding::pointer_delta(PointerDelta::Up).scale(f32::INFINITY);
        assert_eq!(broken.resolve(500.0), 0.0, "and stays a number");
    }

    #[test]
    fn inverting_turns_an_axis_round_and_a_vector_upside_down() {
        let axis = AxisBinding::pad(PadAxis::LeftY).deadzone(0.0).invert();
        assert_eq!(axis.resolve(0.5), -0.5);

        let stick = Axis2Binding::stick(Stick::Left).deadzone(0.0).invert();
        assert_eq!(stick.resolve(Vec2::new(1.0, 0.0)), Vec2::X);
        assert_eq!(stick.resolve(Vec2::new(0.0, 1.0)), Vec2::NEG_Y);
    }

    #[test]
    fn a_vector_reaches_no_further_than_one_however_far_it_is_pushed() {
        let quad = Axis2Binding::from(ButtonAxis2 {
            left: Key::A,
            right: Key::D,
            down: Key::S,
            up: Key::W,
        });
        let diagonal = quad.resolve(Vec2::ONE);

        assert!(
            (diagonal.length() - 1.0).abs() < 1e-6,
            "{diagonal} is one long"
        );
        assert!((diagonal.x - diagonal.y).abs() < 1e-6, "and still diagonal");
        assert_eq!(quad.resolve(Vec2::X), Vec2::X, "a straight one is whole");
        assert_eq!(quad.resolve(Vec2::ZERO), Vec2::ZERO);
    }

    #[test]
    fn a_binding_shows_the_control_a_menu_would_name() {
        assert_eq!(ButtonBinding::from(Key::Space).to_string(), "Space");
        assert_eq!(ButtonBinding::from(Pad::South).to_string(), "Pad South");
        assert_eq!(
            ButtonBinding::Joystick(JoystickControl::new(7)).to_string(),
            "Joystick 7"
        );
        assert_eq!(
            AxisBinding::from(ButtonAxis {
                negative: Key::A,
                positive: Key::D
            })
            .to_string(),
            "A / D"
        );
        assert_eq!(
            AxisBinding::from(PointerDelta::Sideways).to_string(),
            "Pointer Sideways"
        );
        assert_eq!(AxisBinding::from(WheelDelta::Up).to_string(), "Wheel Up");
        assert_eq!(
            AxisBinding::from(WheelDelta::Sideways).to_string(),
            "Wheel Sideways"
        );
        assert_eq!(Axis2Binding::from(Stick::Left).to_string(), "Left Stick");
        assert_eq!(
            Axis2Binding::from(ButtonAxis2 {
                left: Key::A,
                right: Key::D,
                down: Key::S,
                up: Key::W
            })
            .to_string(),
            "A / D / S / W"
        );
    }
}