codecraft 0.1.1

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, an immediate-mode UI, audio and gamepad haptics
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
//! PlayStation controller input over raw HID.
//!
//! Merged in from the `bluetoothtest` project, which worked out the report
//! layouts by dumping bytes (`crates/radcas/examples/gamepad_dump.rs` is the tool it used).
//! The decoding is the same; what changed is the shape around it. That program
//! blocked on a read and printed state changes, which a render loop cannot do:
//! here the device is opened non-blocking and every pending report is drained
//! each frame, because only the newest one describes where the sticks are now.
//!
//! Buttons are a bitmask rather than a list of names, so polling allocates
//! nothing at sixty frames a second.

use glam::Vec2;
use std::ffi::{CStr, CString};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use hidapi::{BusType, HidApi, HidDevice};

use super::output::{self, Bus, Feedback};
use crate::audio::PadKey;

const VID_SONY: u16 = 0x054C;

const PID_DUALSENSE: u16 = 0x0CE6;
const PID_DUALSENSE_EDGE: u16 = 0x0DF2;
const PID_DUALSHOCK4: u16 = 0x05C4;
const PID_DUALSHOCK4_V2: u16 = 0x09CC;

/// Fraction of a stick's travel around centre that reads as no input.
///
/// The sticks idle with a couple of least significant bits of noise, and a worn
/// pad drifts further than that. Past the edge the response is rescaled from
/// zero rather than starting at `DEADZONE`, so there is no jump as it engages.
const DEADZONE: f32 = 0.12;

/// Same, for the analog triggers, which rest at zero and only need enough to
/// ignore a resting finger.
const TRIGGER_DEADZONE: f32 = 0.06;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Model {
    DualSense,
    DualShock4,
}

impl Model {
    fn from_pid(pid: u16) -> Option<Model> {
        match pid {
            PID_DUALSENSE | PID_DUALSENSE_EDGE => Some(Model::DualSense),
            PID_DUALSHOCK4 | PID_DUALSHOCK4_V2 => Some(Model::DualShock4),
            _ => None,
        }
    }

    pub fn name(self) -> &'static str {
        match self {
            Model::DualSense => "DUALSENSE",
            Model::DualShock4 => "DUALSHOCK 4",
        }
    }

    /// The touchpad's extent, in the units its reports count in. Both pads
    /// report a finger as a pair of 12-bit numbers over an area this big.
    pub fn touch_resolution(self) -> Vec2 {
        match self {
            Model::DualSense => Vec2::new(1920.0, 1080.0),
            Model::DualShock4 => Vec2::new(1920.0, 942.0),
        }
    }

    /// Where the first touch point starts in the long USB report.
    ///
    /// Both pads put the pad's state after the motion sensors, but not in the
    /// same place: the DualSense follows its sensor timestamp with a spare
    /// byte and then the points, while the DualShock 4 counts its touch
    /// reports first and stamps each one.
    fn touch_offset(self) -> usize {
        match self {
            Model::DualSense => 33,
            Model::DualShock4 => 35,
        }
    }
}

/// A finger on the touchpad, where the pad says it is.
///
/// The id counts contacts rather than naming a slot: it changes when a finger
/// is lifted and put back down, which is how a drag knows it is a new one
/// rather than a very fast move.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Touch {
    pub id: u8,
    pub x: u16,
    pub y: u16,
}

impl Touch {
    /// Four bytes: a contact byte, then x and y as 12 bits each, sharing the
    /// nibbles of the byte between them.
    fn parse(bytes: &[u8]) -> Option<Touch> {
        let [contact, x_lo, split, y_hi] = bytes else {
            return None;
        };
        // The top bit is set while nothing is touching this slot; the rest is
        // the contact's id.
        if contact & 0x80 != 0 {
            return None;
        }
        Some(Touch {
            id: contact & 0x7F,
            x: u16::from(*x_lo) | (u16::from(split & 0x0F) << 8),
            y: u16::from(split >> 4) | (u16::from(*y_hi) << 4),
        })
    }
}

/// Both touch slots, from a report long enough to carry them.
fn touch_points(model: Model, buf: &[u8]) -> [Option<Touch>; 2] {
    let at = model.touch_offset();
    [
        buf.get(at..at + 4).and_then(Touch::parse),
        buf.get(at + 4..at + 8).and_then(Touch::parse),
    ]
}

/// Button bits, in the order the reports pack them.
pub mod button {
    pub const SQUARE: u32 = 1 << 0;
    pub const CROSS: u32 = 1 << 1;
    pub const CIRCLE: u32 = 1 << 2;
    pub const TRIANGLE: u32 = 1 << 3;
    pub const L1: u32 = 1 << 4;
    pub const R1: u32 = 1 << 5;
    pub const L2: u32 = 1 << 6;
    pub const R2: u32 = 1 << 7;
    pub const CREATE: u32 = 1 << 8;
    pub const OPTIONS: u32 = 1 << 9;
    pub const L3: u32 = 1 << 10;
    pub const R3: u32 = 1 << 11;
    pub const PS: u32 = 1 << 12;
    pub const TOUCHPAD: u32 = 1 << 13;
    pub const MUTE: u32 = 1 << 14;

    /// For readouts. Uppercase and ASCII, since the overlay font is a 3x5
    /// bitmap with no room for the shape glyphs the pad is printed with.
    pub const NAMES: [(u32, &str); 15] = [
        (SQUARE, "SQR"),
        (CROSS, "X"),
        (CIRCLE, "CIRC"),
        (TRIANGLE, "TRI"),
        (L1, "L1"),
        (R1, "R1"),
        (L2, "L2"),
        (R2, "R2"),
        (CREATE, "CREATE"),
        (OPTIONS, "OPTIONS"),
        (L3, "L3"),
        (R3, "R3"),
        (PS, "PS"),
        (TOUCHPAD, "PAD"),
        (MUTE, "MUTE"),
    ];
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Charge {
    Discharging,
    Charging,
    Full,
    Error,
}

/// Battery state. Only present in the long (64-byte) USB report - the
/// DualSense's default Bluetooth report 0x01 is 10 bytes and omits battery,
/// IMU and touchpad.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Battery {
    pub percent: u8,
    pub charge: Charge,
}

impl Battery {
    fn parse(model: Model, buf: &[u8]) -> Option<Battery> {
        // Levels are reported in coarse steps; the +5 centres each step in its
        // bucket, matching the Linux hid-playstation / hid-sony drivers.
        let pct = |level: u8| (level.saturating_mul(10) + 5).min(100);
        match model {
            Model::DualSense => {
                let b = *buf.get(53)?;
                let (level, status) = (b & 0x0F, b >> 4);
                Some(match status {
                    0x0 => Battery {
                        percent: pct(level),
                        charge: Charge::Discharging,
                    },
                    0x1 => Battery {
                        percent: pct(level),
                        charge: Charge::Charging,
                    },
                    0x2 => Battery {
                        percent: 100,
                        charge: Charge::Full,
                    },
                    _ => Battery {
                        percent: 0,
                        charge: Charge::Error,
                    },
                })
            }
            Model::DualShock4 => {
                let b = *buf.get(30)?;
                let (level, cabled) = (b & 0x0F, b & 0x10 != 0);
                Some(match (cabled, level) {
                    (true, 11..) => Battery {
                        percent: 100,
                        charge: Charge::Full,
                    },
                    (true, _) => Battery {
                        percent: pct(level),
                        charge: Charge::Charging,
                    },
                    (false, _) => Battery {
                        percent: pct(level),
                        charge: Charge::Discharging,
                    },
                })
            }
        }
    }
}

/// Raw stick and trigger bytes are kept as reported - sticks centred at 128,
/// triggers 0..=255 - and normalised on demand, so a readout can show what the
/// pad actually sent.
#[derive(Clone, Copy, Default, Debug)]
pub struct State {
    pub lx: u8,
    pub ly: u8,
    pub rx: u8,
    pub ry: u8,
    pub l2: u8,
    pub r2: u8,
    /// Hat switch, 0 = north through 7 = north-west, 8 = centred.
    pub dpad: u8,
    pub buttons: u32,
    pub battery: Option<Battery>,
    /// The two fingers the pad can track, in the slots it reports them in.
    /// Empty on the short Bluetooth report, which omits the touchpad along
    /// with the battery and the IMU.
    pub touch: [Option<Touch>; 2],
}

/// Centred axis in [-1, 1], with the deadzone removed and the remainder
/// rescaled so it still reaches full deflection.
fn axis(v: u8) -> f32 {
    let n = ((v as f32 - 128.0) / 127.0).clamp(-1.0, 1.0);
    let m = n.abs();
    if m < DEADZONE {
        return 0.0;
    }
    n.signum() * (m - DEADZONE) / (1.0 - DEADZONE)
}

fn trigger(v: u8) -> f32 {
    let n = v as f32 / 255.0;
    if n < TRIGGER_DEADZONE {
        return 0.0;
    }
    (n - TRIGGER_DEADZONE) / (1.0 - TRIGGER_DEADZONE)
}

impl State {
    /// Both pads use report id 0x01 over USB, but lay the bytes out
    /// differently.
    fn parse(model: Model, buf: &[u8]) -> Option<State> {
        // Over Bluetooth a DualSense that has been written to switches to its
        // long report, 0x31, which is the USB one with a sequence byte pushed
        // in after the id -- so it is read as the USB one from a byte later.
        let buf = match (model, buf.first()) {
            (_, Some(0x01)) => buf,
            (Model::DualSense, Some(0x31)) if buf.len() > 1 => &buf[1..],
            _ => return None,
        };
        let (sticks, l2, r2, b0, b1, b2) = match model {
            Model::DualSense if buf.len() >= 11 => (
                [buf[1], buf[2], buf[3], buf[4]],
                buf[5],
                buf[6],
                buf[8],
                buf[9],
                buf[10],
            ),
            Model::DualShock4 if buf.len() >= 10 => (
                [buf[1], buf[2], buf[3], buf[4]],
                buf[8],
                buf[9],
                buf[5],
                buf[6],
                buf[7],
            ),
            _ => return None,
        };

        // The face buttons share a byte with the hat switch in its low nibble.
        let mut buttons = 0u32;
        for (mask, bit) in [
            (0x10, button::SQUARE),
            (0x20, button::CROSS),
            (0x40, button::CIRCLE),
            (0x80, button::TRIANGLE),
        ] {
            if b0 & mask != 0 {
                buttons |= bit;
            }
        }
        for (mask, bit) in [
            (0x01, button::L1),
            (0x02, button::R1),
            (0x04, button::L2),
            (0x08, button::R2),
            (0x10, button::CREATE),
            (0x20, button::OPTIONS),
            (0x40, button::L3),
            (0x80, button::R3),
        ] {
            if b1 & mask != 0 {
                buttons |= bit;
            }
        }
        for (mask, bit) in [
            (0x01, button::PS),
            (0x02, button::TOUCHPAD),
            (0x04, button::MUTE),
        ] {
            if b2 & mask != 0 {
                buttons |= bit;
            }
        }

        Some(State {
            lx: sticks[0],
            ly: sticks[1],
            rx: sticks[2],
            ry: sticks[3],
            l2,
            r2,
            dpad: b0 & 0x0F,
            buttons,
            battery: Battery::parse(model, buf),
            touch: touch_points(model, buf),
        })
    }

    pub fn held(&self, mask: u32) -> bool {
        self.buttons & mask != 0
    }

    /// Left stick as ground movement: x strafes right, y walks forward. The
    /// report counts y downward, hence the negation.
    pub fn move_axis(&self) -> Vec2 {
        Vec2::new(axis(self.lx), -axis(self.ly))
    }

    /// Right stick as a look rate: x turns right, y looks up.
    pub fn look_axis(&self) -> Vec2 {
        Vec2::new(axis(self.rx), -axis(self.ry))
    }

    /// Vertical movement from the triggers, right up and left down.
    pub fn lift(&self) -> f32 {
        trigger(self.r2) - trigger(self.l2)
    }

    /// The finger a drag should follow: the first slot with something in it.
    ///
    /// Lifting one of two fingers hands the drag to the other, which arrives
    /// with its own id, so the gesture restarts rather than jumping across
    /// the pad to wherever the remaining finger happens to be.
    pub fn touch(&self) -> Option<Touch> {
        self.touch[0].or(self.touch[1])
    }

    pub fn dpad_name(&self) -> &'static str {
        match self.dpad {
            0 => "N",
            1 => "NE",
            2 => "E",
            3 => "SE",
            4 => "S",
            5 => "SW",
            6 => "W",
            7 => "NW",
            _ => "-",
        }
    }

    /// One line for a readout: raw axes, then whatever is held.
    pub fn render(&self) -> String {
        let mut s = format!(
            "L({:3},{:3}) R({:3},{:3}) L2:{:3} R2:{:3} DPAD:{:2}",
            self.lx,
            self.ly,
            self.rx,
            self.ry,
            self.l2,
            self.r2,
            self.dpad_name()
        );
        if let Some(b) = self.battery {
            let tag = match b.charge {
                Charge::Discharging => "",
                Charge::Charging => "+",
                Charge::Full => " FULL",
                Charge::Error => " ERR",
            };
            s.push_str(&format!(" BATT:{}%{}", b.percent, tag));
        }
        for (slot, touch) in self.touch.iter().enumerate() {
            if let Some(touch) = touch {
                s.push_str(&format!(" T{}:{},{}", slot + 1, touch.x, touch.y));
            }
        }
        for (mask, name) in button::NAMES {
            if self.held(mask) {
                s.push(' ');
                s.push_str(name);
            }
        }
        s
    }
}

pub struct Gamepad {
    device: HidDevice,
    /// Where the system says this device is. Stable while it stays plugged
    /// in, and what tells a pad already open from one just arrived.
    path: CString,
    model: Model,
    state: State,
    buf: [u8; 64],
    bus: Bus,
    /// Counts the reports sent over Bluetooth, which the pad wants numbered.
    seq: u8,
    /// What it was last told, so it is not told again.
    felt: Option<Feedback>,
    /// Whether a write has failed, after which none are tried.
    deaf: bool,
    /// The pad's own sound card, when it has one that could be told apart
    /// from the rest: see [`PadKey`].
    key: Option<PadKey>,
}

impl Gamepad {
    pub fn model(&self) -> Model {
        self.model
    }

    pub fn state(&self) -> &State {
        &self.state
    }

    /// Where the system says this device is.
    pub fn path(&self) -> &CStr {
        &self.path
    }

    /// Drain every report waiting and keep the last one. Reports queue while
    /// the frame renders, and only the newest says where the sticks are now -
    /// consuming one per frame would run progressively further behind.
    ///
    /// `None` once the device has gone: a read against an unplugged pad
    /// fails, and there is nothing to be done about it but let it go.
    pub fn poll(&mut self) -> Option<&State> {
        loop {
            match self.device.read(&mut self.buf) {
                Ok(0) => break,
                Ok(n) => {
                    if let Some(s) = State::parse(self.model, &self.buf[..n]) {
                        self.state = s;
                    }
                }
                Err(e) => {
                    log::info!("{} unplugged: {e}", self.model.name());
                    return None;
                }
            }
        }
        Some(&self.state)
    }
}

impl Gamepad {
    /// How it is plugged in.
    pub fn bus(&self) -> Bus {
        self.bus
    }

    /// Which sound card is this pad's, if any: what [`crate::audio::Audio`]
    /// wants to play something in the player's hands.
    pub fn key(&self) -> Option<PadKey> {
        self.key
    }

    /// Tells the pad what to do with itself: rumble, triggers, lights.
    ///
    /// Written only when it differs from what the pad was last told, since
    /// the pad keeps doing the last thing it was told until it hears
    /// otherwise -- and over Bluetooth every report is a packet on a shared
    /// radio. A game setting the same feedback every frame costs nothing; a
    /// rumble that fades costs a report a frame, which is what it should.
    ///
    /// A pad that will not take a write is not a pad that has gone -- it is
    /// read, not written, to find that out -- so the failure is logged once
    /// and the writes stop, rather than the log filling at sixty a second.
    pub fn feel(&mut self, feedback: &Feedback) {
        if self.deaf || self.felt.as_ref() == Some(feedback) {
            return;
        }
        let report = match self.model {
            Model::DualSense => output::dualsense(feedback, self.bus, self.seq),
            // The DualShock 4 has real motors and a simpler report, and no
            // triggers to shape. Only over USB: its Bluetooth report needs
            // the same signing as the DualSense's and has not been worked
            // out here.
            Model::DualShock4 => match self.bus {
                Bus::Usb => output::dualshock4(feedback),
                Bus::Bluetooth => return,
            },
        };
        self.seq = self.seq.wrapping_add(1) & 0x0F;
        match self.device.write(&report) {
            Ok(_) => self.felt = Some(*feedback),
            Err(e) => {
                log::warn!("{} will not take feedback: {e}", self.model.name());
                self.deaf = true;
            }
        }
    }
}

/// A pad let go of is a pad at rest: whatever it was last told -- a rumble
/// mid-fade, a lightbar in a player's colour -- would otherwise outlive the
/// game, since nothing else is going to tell it to stop.
impl Drop for Gamepad {
    fn drop(&mut self) {
        if self.felt.is_some() {
            self.felt = None;
            self.feel(&Feedback::default());
        }
    }
}

/// How often the device list is walked again, looking for pads that have
/// arrived since.
///
/// This is done on a thread of its own, and it has to be: asking Windows to
/// enumerate its HID devices measures at about **a hundred milliseconds** on
/// this machine -- six frames at sixty a second. Doing it in the frame loop
/// produced exactly the stutter it was meant to prevent a restart for: the
/// picture froze for a few frames every half second, over and over.
///
/// Half a second is fine once it costs the frame nothing. It is faster than
/// anyone can plug a controller in and look up at the screen.
const RESCAN: Duration = Duration::from_millis(500);

/// A pad found by the scanning thread, on its way to the frame loop.
struct Found {
    device: HidDevice,
    path: CString,
    model: Model,
    bus: Bus,
    key: Option<PadKey>,
}

/// Every pad plugged into the machine, opened as they arrive and dropped as
/// they go.
///
/// One hub rather than one open pad, because a second player turning up is
/// exactly the case worth handling: pads are found again while the game runs,
/// so plugging one in mid-game gives you a controller rather than requiring a
/// restart.
///
/// The *looking* happens on its own thread and the frame loop only picks up
/// what it found -- see [`RESCAN`] for why. Reading the pads themselves stays
/// on the frame thread, where it belongs: a read is non-blocking and costs
/// nothing, and it has to happen between one frame and the next to be worth
/// anything.
pub struct Hub {
    pads: Vec<Gamepad>,
    /// Pads the scanning thread has opened and not yet handed over.
    arrivals: Receiver<Found>,
    /// What is open now, so the scanning thread does not open one twice.
    /// Shared rather than sent, because the frame thread is what notices a
    /// pad has gone.
    open: Arc<Mutex<Vec<CString>>>,
}

impl Default for Hub {
    fn default() -> Self {
        Self::new()
    }
}

impl Hub {
    /// A hub with nothing open yet, and a thread looking for pads.
    ///
    /// Never fails: a machine whose HID library will not start is a machine
    /// with no controllers, which is the ordinary case rather than an error.
    pub fn new() -> Self {
        let (send, arrivals) = channel();
        let open = Arc::new(Mutex::new(Vec::new()));
        let known = open.clone();
        // Detached on purpose. It owns its own `HidApi` -- the library is not
        // shared with the frame thread, so neither side can block the other --
        // and it stops when the channel is dropped, which is when the game
        // is on its way out anyway.
        let spawned = std::thread::Builder::new()
            .name("gamepad scan".into())
            .spawn(move || scan_loop(send, known));
        if let Err(e) = &spawned {
            log::warn!("could not start the controller scan, no pads: {e}");
        }

        Self {
            pads: Vec::new(),
            arrivals,
            open,
        }
    }

    /// How many pads are open.
    pub fn len(&self) -> usize {
        self.pads.len()
    }

    pub fn is_empty(&self) -> bool {
        self.pads.is_empty()
    }

    pub fn iter(&self) -> impl Iterator<Item = &Gamepad> {
        self.pads.iter()
    }

    /// Tells the pad in a seat what to do with itself. Nothing happens for a
    /// seat with no pad in it, so a game can say it to every seat.
    pub fn feel(&mut self, index: usize, feedback: &Feedback) {
        if let Some(pad) = self.pads.get_mut(index) {
            pad.feel(feedback);
        }
    }

    /// The sound card of the pad in a seat, if it has one.
    pub fn key(&self, index: usize) -> Option<PadKey> {
        self.pads.get(index).and_then(Gamepad::key)
    }

    /// Reads every pad, drops the ones that have gone, and takes in any the
    /// scanning thread has found.
    ///
    /// Cheap, every frame: a read against an open device is non-blocking, and
    /// taking arrivals is a channel that is almost always empty. Nothing here
    /// enumerates anything.
    ///
    /// The dropping is how an unplug is noticed: hidapi has no event for it,
    /// and a read against a device that is not there fails.
    pub fn poll(&mut self) -> &[Gamepad] {
        let mut lost = Vec::new();
        self.pads.retain_mut(|pad| match pad.poll().is_some() {
            true => true,
            false => {
                lost.push(pad.path().to_owned());
                false
            }
        });
        for found in self.arrivals.try_iter() {
            log::info!("controller {}: {}", self.pads.len() + 1, found.model.name());
            self.pads.push(Gamepad {
                device: found.device,
                path: found.path,
                model: found.model,
                state: State::default(),
                buf: [0u8; 64],
                bus: found.bus,
                seq: 0,
                felt: None,
                deaf: false,
                key: found.key,
            });
        }

        // Told after the fact rather than before: a pad that has gone has to
        // stop being "already open" or the scanner will never offer it again
        // when it comes back.
        if !lost.is_empty() || !self.pads.is_empty() {
            if let Ok(mut open) = self.open.lock() {
                *open = self.pads.iter().map(|pad| pad.path().to_owned()).collect();
            }
        }
        &self.pads
    }
}

/// The scanning thread: look, open anything new, hand it over, wait.
///
/// Ends when the frame loop drops its end of the channel, which is when there
/// is nobody left to hand a pad to.
fn scan_loop(send: Sender<Found>, open: Arc<Mutex<Vec<CString>>>) {
    let mut api = match HidApi::new() {
        Ok(api) => api,
        Err(e) => {
            log::warn!("hidapi init failed, no controller input: {e}");
            return;
        }
    };

    loop {
        if let Err(e) = api.refresh_devices() {
            log::warn!("could not rescan for controllers: {e}");
        } else {
            let known = open.lock().map(|open| open.clone()).unwrap_or_default();
            for found in look(&api, &known) {
                if send.send(found).is_err() {
                    return;
                }
            }
        }
        std::thread::sleep(RESCAN);
    }
}

/// Every PlayStation pad the system will hand over that is not open already.
fn look(api: &HidApi, known: &[CString]) -> Vec<Found> {
    let mut found = Vec::new();
    for info in api.device_list() {
        if info.vendor_id() != VID_SONY {
            continue;
        }
        let Some(model) = Model::from_pid(info.product_id()) else {
            continue;
        };
        if known.iter().any(|path| path.as_c_str() == info.path())
            || found.iter().any(|f: &Found| f.path.as_c_str() == info.path())
        {
            continue;
        }
        // The composite device also exposes an audio interface, which will not
        // open as HID; keep walking the list rather than giving up.
        let device = match info.open_device(api) {
            Ok(device) => device,
            Err(e) => {
                log::debug!("  skipping interface: {e}");
                continue;
            }
        };
        // Never block the frame loop waiting for a report.
        if let Err(e) = device.set_blocking_mode(false) {
            log::warn!("could not set the controller non-blocking: {e}");
            continue;
        }
        log::info!(
            "found {} ({:04X}:{:04X}) {}",
            model.name(),
            info.vendor_id(),
            info.product_id(),
            info.product_string().unwrap_or("unnamed"),
        );
        found.push(Found {
            device,
            path: info.path().to_owned(),
            model,
            bus: match info.bus_type() {
                BusType::Bluetooth => Bus::Bluetooth,
                _ => Bus::Usb,
            },
            key: PadKey::of_hid_path(info.path()),
        });
    }
    found
}

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

    #[test]
    fn the_deadzone_starts_from_zero_and_still_reaches_full() {
        assert_eq!(axis(128), 0.0, "centred");
        assert_eq!(axis(131), 0.0, "idle noise stays inside the deadzone");
        // Just past the edge the response starts at zero rather than jumping.
        let edge = (128.0 + DEADZONE * 127.0).ceil() as u8;
        assert!(axis(edge) < 0.02, "no step as the deadzone lets go");
        assert!(
            (axis(255) - 1.0).abs() < 1e-3,
            "full deflection still reaches 1"
        );
        assert!((axis(0) + 1.0).abs() < 1e-3);
    }

    #[test]
    fn sticks_map_to_screen_directions() {
        // Reports count y downward, so a stick pushed away reads below centre
        // and has to come back as forward.
        let s = State {
            lx: 128,
            ly: 0,
            rx: 128,
            ry: 255,
            ..State::default()
        };
        assert!(s.move_axis().y > 0.9, "stick away from you is forward");
        assert!(s.look_axis().y < -0.9, "stick pulled back looks down");
    }

    #[test]
    fn triggers_lift_and_face_buttons_decode() {
        let s = State {
            r2: 255,
            ..State::default()
        };
        assert!((s.lift() - 1.0).abs() < 1e-3);

        let mut buf = [0u8; 64];
        buf[0] = 0x01;
        buf[8] = 0x20 | 0x03; // cross held, hat pointing south-east
        let parsed = State::parse(Model::DualSense, &buf).expect("report 0x01 parses");
        assert!(parsed.held(button::CROSS));
        assert!(!parsed.held(button::SQUARE));
        assert_eq!(parsed.dpad_name(), "SE");
    }

    /// Writes a touch point into `buf` at `at`, the way the pad packs one.
    fn put_touch(buf: &mut [u8], at: usize, id: u8, x: u16, y: u16) {
        buf[at] = id & 0x7F;
        buf[at + 1] = (x & 0xFF) as u8;
        buf[at + 2] = ((x >> 8) as u8 & 0x0F) | (((y & 0x0F) as u8) << 4);
        buf[at + 3] = (y >> 4) as u8;
    }

    #[test]
    fn a_finger_comes_back_where_it_was_put() {
        let mut buf = [0u8; 64];
        buf[0] = 0x01;
        // Both slots empty until something is written: the top bit of the
        // contact byte is what says "nothing here", so an all-zero report
        // reads as two fingers at the origin, not as none.
        for slot in [33, 37] {
            buf[slot] = 0x80;
        }

        put_touch(&mut buf, 33, 3, 1919, 1079);
        let state = State::parse(Model::DualSense, &buf).expect("a long report");
        assert_eq!(
            state.touch[0],
            Some(Touch {
                id: 3,
                x: 1919,
                y: 1079
            }),
            "the far corner survives the nibble it is split across",
        );
        assert_eq!(state.touch[1], None, "the second slot is still empty");
        assert_eq!(state.touch(), state.touch[0]);
    }

    #[test]
    fn a_lifted_finger_hands_the_drag_to_the_other_one() {
        let mut buf = [0u8; 64];
        buf[0] = 0x01;
        buf[33] = 0x80;
        put_touch(&mut buf, 37, 9, 400, 300);

        let state = State::parse(Model::DualSense, &buf).expect("a long report");
        assert_eq!(state.touch[0], None);
        let touch = state.touch().expect("the second finger is still down");
        assert_eq!((touch.id, touch.x, touch.y), (9, 400, 300));
    }

    #[test]
    fn the_two_pads_read_their_touchpads_from_different_places() {
        // A DualShock 4 counts its touch reports and stamps each one before
        // the points start, so the same finger sits two bytes further along.
        fn report(at: usize) -> [u8; 64] {
            let mut buf = [0u8; 64];
            buf[0] = 0x01;
            // Both slots empty, then one finger in the first.
            buf[at] = 0x80;
            buf[at + 4] = 0x80;
            put_touch(&mut buf, at, 1, 640, 480);
            buf
        }
        fn found(model: Model, buf: &[u8]) -> Option<(u16, u16)> {
            State::parse(model, buf)
                .expect("a long report")
                .touch()
                .map(|touch| (touch.x, touch.y))
        }

        let (dualsense, dualshock) = (report(33), report(35));
        assert_eq!(found(Model::DualSense, &dualsense), Some((640, 480)));
        assert_eq!(found(Model::DualShock4, &dualshock), Some((640, 480)));

        // Each reading the other's report finds whatever happens to be at its
        // own offset, which is not the finger that was put there.
        assert_ne!(found(Model::DualSense, &dualshock), Some((640, 480)));
        assert_ne!(found(Model::DualShock4, &dualsense), Some((640, 480)));
    }

    #[test]
    fn a_report_too_short_to_hold_the_touchpad_simply_has_none() {
        // The DualSense's default Bluetooth report stops after the buttons.
        let mut buf = [0u8; 11];
        buf[0] = 0x01;
        let state = State::parse(Model::DualSense, &buf).expect("the short report still parses");
        assert_eq!(state.touch, [None, None]);
    }

    #[test]
    fn a_report_that_is_not_input_is_rejected() {
        let buf = [0x02u8; 64];
        assert!(State::parse(Model::DualSense, &buf).is_none());
        assert!(State::parse(Model::DualSense, &[0x01]).is_none());
        assert!(State::parse(Model::DualSense, &[0x31]).is_none());
    }

    /// The long Bluetooth report is the USB one a byte later, so a pad that
    /// has been written to reads exactly as it did before it was.
    #[test]
    fn the_long_bluetooth_report_reads_like_the_usb_one() {
        let mut usb = [0u8; 64];
        usb[0] = 0x01;
        usb[1] = 200;
        usb[2] = 60;
        usb[5] = 90;
        usb[6] = 255;
        usb[8] = 0x20 | 0x02;
        let mut bt = [0u8; 65];
        bt[0] = 0x31;
        bt[1] = 0x17;
        bt[2..].copy_from_slice(&usb[1..]);

        let from_usb = State::parse(Model::DualSense, &usb).unwrap();
        let from_bt = State::parse(Model::DualSense, &bt).unwrap();
        assert_eq!((from_bt.lx, from_bt.ly, from_bt.l2, from_bt.r2), (200, 60, 90, 255));
        assert_eq!(from_bt.buttons, from_usb.buttons);
        assert_eq!(from_bt.dpad, from_usb.dpad);
        assert!(
            State::parse(Model::DualShock4, &bt).is_none(),
            "the DualShock 4 has a long report of its own that this is not",
        );
    }
}