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
//! What a game sends *to* a pad: rumble, the adaptive triggers, the lightbar.
//!
//! A DualSense has no rumble motors. It has two voice-coil actuators in the
//! grips, and what looks like rumble from outside is the pad driving them
//! with a shape of its own -- the "compatible vibration" of the old motors,
//! as the report calls it. The same actuators can be played like speakers,
//! which is another story ([`crate::audio::pads`]); this is the cheap one, a
//! few bytes a frame over the same HID pipe the sticks come in on.
//!
//! Everything here is pure: a [`Feedback`] and a [`Bus`] in, bytes out. The
//! layout is the one the Linux `hid-playstation` driver documents, with the
//! trigger effects from the community's reverse engineering on top, since the
//! kernel does not do triggers.

/// A shape for a trigger to hold: what the finger feels on the way down.
///
/// Positions are tenths of the travel, nought at rest and nine fully in;
/// strengths run one to eight. Anything outside is clamped rather than
/// refused, because the pad refuses by ignoring the whole effect, which is
/// harder to notice than a slightly firmer trigger.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Trigger {
    /// A plain trigger.
    #[default]
    Free,
    /// Pushes back from `from` onwards, the whole way down: a stiff spring.
    Resist { from: u8, strength: u8 },
    /// Resists from `from` and gives way at `to`, which is a gun: a wall the
    /// finger goes through, and nothing behind it.
    Weapon { from: u8, to: u8, strength: u8 },
    /// Pushes back harder the further in the finger goes -- next to nothing
    /// at `from`, climbing a zone at a time to `peak` at `to` -- and not at
    /// all past `to`. A spring the finger breaks through, which is the other
    /// way of making a gun: where [`Trigger::Weapon`] is a wall at a
    /// position, this is a squeeze that gets harder and then is not there.
    /// The break is the end of the last zone that pushes, so a game that
    /// reads its pull at the same point gets the two as one thing.
    Spring { from: u8, to: u8, peak: u8 },
    /// Shakes from `from` onwards, at `frequency` hertz or so: a thing that
    /// is running.
    Vibrate { from: u8, strength: u8, frequency: u8 },
}

/// Everything a game can tell a pad in one go.
///
/// Sent whole every time rather than as a difference: the report has a flag
/// per thing it carries, and every one is set, so the pad is always told all
/// of it and nothing is left over from the frame before. `Default` is a pad
/// doing nothing, which is also what it is told when the game lets go.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Feedback {
    /// The heavy actuator, nought to one.
    pub strong: f32,
    /// The light one.
    pub weak: f32,
    pub left: Trigger,
    pub right: Trigger,
    /// The bar on the front, as red, green and blue; `None` leaves it to the
    /// pad.
    pub lightbar: Option<[u8; 3]>,
    /// The little lights under the touchpad: which player this is, one to
    /// five, the way the console shows it.
    pub player: Option<u8>,
    /// The pad's own speaker, nought to one, for the games that put sound
    /// through it. `None` leaves the volume where it was.
    pub speaker: Option<f32>,
}

/// How a pad is plugged in, which decides the shape of the report.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Bus {
    Usb,
    Bluetooth,
}

/// The DualSense report over USB: an id and the common body.
const DUALSENSE_USB: usize = 48;
/// Over Bluetooth: id, a sequence byte, a tag, the body, padding and a CRC.
const DUALSENSE_BT: usize = 78;
/// Where the common body starts in each.
const USB_BODY: usize = 1;
const BT_BODY: usize = 3;

/// The seed the pad mixes into every Bluetooth CRC, so a report meant for
/// something else cannot pass for one of its own.
const CRC_SEED: u8 = 0xA2;

/// The DualSense's report, as the bytes to hand to `HidDevice::write`.
///
/// `seq` is only used over Bluetooth, where every report carries a number
/// the pad uses to drop repeats; the caller counts, four bits' worth.
pub fn dualsense(feedback: &Feedback, bus: Bus, seq: u8) -> Vec<u8> {
    let (mut report, body) = match bus {
        Bus::Usb => {
            let mut report = vec![0u8; DUALSENSE_USB];
            report[0] = 0x02;
            (report, USB_BODY)
        }
        Bus::Bluetooth => {
            let mut report = vec![0u8; DUALSENSE_BT];
            report[0] = 0x31;
            report[1] = (seq & 0x0F) << 4;
            report[2] = 0x10;
            (report, BT_BODY)
        }
    };
    fill_dualsense(&mut report[body..], feedback);
    if bus == Bus::Bluetooth {
        let over = DUALSENSE_BT - 4;
        let crc = crc32(std::iter::once(CRC_SEED).chain(report[..over].iter().copied()));
        report[over..].copy_from_slice(&crc.to_le_bytes());
    }
    report
}

/// The forty-seven bytes both transports share, laid out as the kernel names
/// them: two flag bytes saying what is being set, then the things themselves.
fn fill_dualsense(body: &mut [u8], feedback: &Feedback) {
    // Rumble, both ways the firmware has understood it. Old firmware wants
    // the first flag and new firmware the one in the third flag byte, and
    // each ignores the other's, so both are set and the pad takes the one it
    // knows.
    body[0] |= 0x01 | 0x02;
    body[38] |= 0x04;
    body[2] = level(feedback.weak);
    body[3] = level(feedback.strong);

    body[0] |= 0x04 | 0x08;
    trigger(&mut body[10..21], feedback.right);
    trigger(&mut body[21..32], feedback.left);

    if let Some(speaker) = feedback.speaker {
        body[0] |= 0x20;
        body[5] = level(speaker);
    }
    if let Some([r, g, b]) = feedback.lightbar {
        body[1] |= 0x04;
        body[44] = r;
        body[45] = g;
        body[46] = b;
    }
    if let Some(player) = feedback.player {
        body[1] |= 0x10;
        body[43] = player_leds(player);
    }
}

/// The DualShock 4's report over USB: motors and lightbar, nothing else it
/// can do that a game here would want.
///
/// Thirty-two bytes with a flags byte saying the motors and the light are
/// both meant, then the weak motor, the strong one, and the colour. The
/// flash times after the colour are left at nought, which is a steady light.
pub fn dualshock4(feedback: &Feedback) -> Vec<u8> {
    let mut report = vec![0u8; 32];
    report[0] = 0x05;
    report[1] = 0x07;
    report[4] = level(feedback.weak);
    report[5] = level(feedback.strong);
    if let Some([r, g, b]) = feedback.lightbar {
        report[6] = r;
        report[7] = g;
        report[8] = b;
    }
    report
}

/// Nought to one as a byte, with anything outside brought in.
fn level(value: f32) -> u8 {
    (value.clamp(0.0, 1.0) * 255.0).round() as u8
}

/// The five lights under the touchpad, lit the way the console lights them:
/// outwards from the middle, so player one is the centre light and player
/// two the pair either side of it.
fn player_leds(player: u8) -> u8 {
    match player {
        1 => 0b00100,
        2 => 0b01010,
        3 => 0b10101,
        4 => 0b11011,
        _ => 0b11111,
    }
}

/// One trigger's eleven bytes: a mode, then ten of parameters.
///
/// The parameters are mostly zones. A trigger's travel is ten zones, and an
/// effect says which of them it applies to in a sixteen-bit mask, and how
/// hard in three bits a zone, packed into thirty-two.
fn trigger(bytes: &mut [u8], effect: Trigger) {
    bytes.fill(0);
    match effect {
        Trigger::Free => bytes[0] = 0x05,
        Trigger::Resist { from, strength } => {
            bytes[0] = 0x21;
            let (active, force) = zones(from, 9, |_| strength);
            bytes[1..3].copy_from_slice(&active.to_le_bytes());
            bytes[3..7].copy_from_slice(&force.to_le_bytes());
        }
        Trigger::Spring { from, to, peak } => {
            // The same mode as a resistance -- a strength per zone -- with
            // the strengths climbing instead of level, and the zones past
            // the end left out, which is what the pad reads as nothing
            // there. A straight line from one to the peak, rounded to the
            // eight steps the pad has; a spring one zone long is its peak.
            bytes[0] = 0x21;
            let peak = peak.clamp(1, 8) as f32;
            let (active, force) = zones(from, to, |along| (1.0 + (peak - 1.0) * along).round() as u8);
            bytes[1..3].copy_from_slice(&active.to_le_bytes());
            bytes[3..7].copy_from_slice(&force.to_le_bytes());
        }
        Trigger::Weapon { from, to, strength } => {
            bytes[0] = 0x25;
            let from = from.clamp(2, 7);
            let to = to.clamp(from + 1, 8);
            let ends = (1u16 << from) | (1u16 << to);
            bytes[1..3].copy_from_slice(&ends.to_le_bytes());
            bytes[3] = strength.clamp(1, 8) - 1;
        }
        Trigger::Vibrate {
            from,
            strength,
            frequency,
        } => {
            bytes[0] = 0x26;
            let (active, amplitude) = zones(from, 9, |_| strength);
            bytes[1..3].copy_from_slice(&active.to_le_bytes());
            bytes[3..7].copy_from_slice(&amplitude.to_le_bytes());
            bytes[9] = frequency;
        }
    }
}

/// The zones from `from` to `to`, each at whatever `strength` says for how
/// far along the pair it lies -- nought at `from`, one at `to`, and one
/// for a pair that is a single zone, which is all end -- packed the way
/// the pad reads them: a bit per zone in the mask, and three bits per zone
/// in the word, one to eight sent as nought to seven. An end past the last
/// zone is brought back to it and an end before its start is the start,
/// and zones outside the pair are left out of both, which the pad takes as
/// nothing there.
fn zones(from: u8, to: u8, strength: impl Fn(f32) -> u8) -> (u16, u32) {
    let from = from.min(9);
    let to = to.clamp(from, 9);
    let mut active = 0u16;
    let mut packed = 0u32;
    for zone in from..=to {
        let along = match to > from {
            true => (zone - from) as f32 / (to - from) as f32,
            false => 1.0,
        };
        active |= 1 << zone;
        packed |= ((strength(along).clamp(1, 8) - 1) as u32) << (3 * zone);
    }
    (active, packed)
}

/// The ordinary CRC-32 -- the one zip files use -- which is what the pad
/// checks a Bluetooth report against.
pub fn crc32(bytes: impl IntoIterator<Item = u8>) -> u32 {
    let mut crc = 0xFFFF_FFFFu32;
    for byte in bytes {
        crc ^= byte as u32;
        for _ in 0..8 {
            let low = crc & 1;
            crc >>= 1;
            if low != 0 {
                crc ^= 0xEDB8_8320;
            }
        }
    }
    !crc
}

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

    fn body(report: &[u8], bus: Bus) -> &[u8] {
        match bus {
            Bus::Usb => &report[USB_BODY..USB_BODY + 47],
            Bus::Bluetooth => &report[BT_BODY..BT_BODY + 47],
        }
    }

    /// The CRC is the one everybody else's is, or the pad would drop every
    /// report and nothing would ever rumble over Bluetooth.
    #[test]
    fn the_crc_is_the_ordinary_one() {
        assert_eq!(crc32(b"123456789".iter().copied()), 0xCBF4_3926);
        assert_eq!(crc32(std::iter::empty()), 0);
    }

    /// Over USB the report is the id and the body; over Bluetooth it is
    /// wrapped, numbered and signed, and the body is the same bytes.
    #[test]
    fn the_two_transports_carry_the_same_body() {
        let feedback = Feedback {
            strong: 1.0,
            weak: 0.5,
            lightbar: Some([10, 20, 30]),
            player: Some(2),
            right: Trigger::Weapon {
                from: 2,
                to: 6,
                strength: 8,
            },
            ..Feedback::default()
        };
        let usb = dualsense(&feedback, Bus::Usb, 0);
        let bt = dualsense(&feedback, Bus::Bluetooth, 5);

        assert_eq!(usb.len(), 48);
        assert_eq!(usb[0], 0x02);
        assert_eq!(bt.len(), 78);
        assert_eq!(bt[0], 0x31);
        assert_eq!(bt[1], 5 << 4, "the sequence number sits in the high bits");
        assert_eq!(bt[2], 0x10);
        assert_eq!(body(&usb, Bus::Usb), body(&bt, Bus::Bluetooth));

        let over = bt.len() - 4;
        let crc = crc32(std::iter::once(CRC_SEED).chain(bt[..over].iter().copied()));
        assert_eq!(&bt[over..], &crc.to_le_bytes(), "signed over the seed and the rest");
    }

    /// Rumble goes in both the places firmware has looked for it.
    #[test]
    fn rumble_is_set_for_old_and_new_firmware_alike() {
        let report = dualsense(
            &Feedback {
                strong: 1.0,
                weak: 0.25,
                ..Feedback::default()
            },
            Bus::Usb,
            0,
        );
        let body = body(&report, Bus::Usb);
        assert_eq!(body[0] & 0x03, 0x03, "compatible vibration, and haptics selected");
        assert_eq!(body[38] & 0x04, 0x04, "and the newer flag");
        assert_eq!(body[3], 255, "the strong actuator is the 'left motor'");
        assert_eq!(body[2], 64, "and the weak one the 'right'");
    }

    /// Nothing asked for is nothing sent: a default feedback leaves the
    /// lightbar and player lights to the pad and turns the rest off.
    #[test]
    fn a_default_feedback_is_a_pad_at_rest() {
        let report = dualsense(&Feedback::default(), Bus::Usb, 0);
        let body = body(&report, Bus::Usb);
        assert_eq!(body[2], 0);
        assert_eq!(body[3], 0);
        assert_eq!(body[1], 0, "no lightbar, no player lights");
        assert_eq!(body[10], 0x05, "the triggers are told to be free");
        assert_eq!(body[21], 0x05);
        assert!(body[11..21].iter().all(|b| *b == 0));
    }

    /// A trigger effect is a mode and its zones, packed the way the pad reads
    /// them.
    #[test]
    fn a_resisting_trigger_covers_every_zone_from_its_start() {
        let mut bytes = [0xFFu8; 11];
        trigger(&mut bytes, Trigger::Resist { from: 3, strength: 8 });
        assert_eq!(bytes[0], 0x21);
        let active = u16::from_le_bytes([bytes[1], bytes[2]]);
        assert_eq!(active, 0b11_1111_1000, "zones three to nine");
        let force = u32::from_le_bytes([bytes[3], bytes[4], bytes[5], bytes[6]]);
        for zone in 0..10u32 {
            let expected = if zone >= 3 { 7 } else { 0 };
            assert_eq!((force >> (3 * zone)) & 7, expected, "zone {zone}");
        }
        assert!(bytes[7..].iter().all(|b| *b == 0), "and nothing after");
    }

    /// A spring is a slope: the strength climbs a zone at a time from one at
    /// its start to the peak at its end, and past the end there is nothing
    /// -- which is what lets a finger break through it. The pad reads it
    /// as a resistance with a different strength in each zone.
    #[test]
    fn a_spring_climbs_to_its_peak_and_is_gone_past_it() {
        let mut bytes = [0xFFu8; 11];
        trigger(
            &mut bytes,
            Trigger::Spring {
                from: 0,
                to: 4,
                peak: 8,
            },
        );
        assert_eq!(bytes[0], 0x21, "a strength per zone, like a resistance");
        let active = u16::from_le_bytes([bytes[1], bytes[2]]);
        assert_eq!(active, 0b1_1111, "zones nought to four, and none past");
        let force = u32::from_le_bytes([bytes[3], bytes[4], bytes[5], bytes[6]]);
        let strengths: Vec<u32> = (0..10).map(|zone| (force >> (3 * zone)) & 7).collect();
        assert_eq!(
            strengths,
            [0, 2, 4, 5, 7, 0, 0, 0, 0, 0],
            "one, three, five, six, eight, sent as nought to seven",
        );
        assert!(bytes[7..].iter().all(|b| *b == 0), "and nothing after");
    }

    /// A spring one zone long is its peak in that zone alone, and the
    /// strength is held to what the pad has like every other effect's.
    #[test]
    fn a_spring_of_one_zone_is_its_peak() {
        let mut bytes = [0u8; 11];
        trigger(
            &mut bytes,
            Trigger::Spring {
                from: 5,
                to: 5,
                peak: 40,
            },
        );
        assert_eq!(u16::from_le_bytes([bytes[1], bytes[2]]), 1 << 5);
        let force = u32::from_le_bytes([bytes[3], bytes[4], bytes[5], bytes[6]]);
        assert_eq!(force, 7 << 15, "the one zone, at the most the pad does");
    }

    #[test]
    fn a_weapon_trigger_is_two_ends_and_a_strength() {
        let mut bytes = [0u8; 11];
        trigger(
            &mut bytes,
            Trigger::Weapon {
                from: 2,
                to: 5,
                strength: 6,
            },
        );
        assert_eq!(bytes[0], 0x25);
        assert_eq!(u16::from_le_bytes([bytes[1], bytes[2]]), (1 << 2) | (1 << 5));
        assert_eq!(bytes[3], 5, "strength one to eight is sent as nought to seven");
    }

    /// The pad ignores an effect it cannot make sense of, which is worse than
    /// a clamped one: a weapon whose end is before its start is made to end
    /// after it.
    #[test]
    fn impossible_triggers_are_brought_within_reach() {
        let mut bytes = [0u8; 11];
        trigger(
            &mut bytes,
            Trigger::Weapon {
                from: 9,
                to: 1,
                strength: 40,
            },
        );
        assert_eq!(u16::from_le_bytes([bytes[1], bytes[2]]), (1 << 7) | (1 << 8));
        assert_eq!(bytes[3], 7);

        trigger(
            &mut bytes,
            Trigger::Vibrate {
                from: 12,
                strength: 0,
                frequency: 40,
            },
        );
        assert_eq!(bytes[0], 0x26);
        assert_eq!(u16::from_le_bytes([bytes[1], bytes[2]]), 1 << 9, "the last zone at least");
        assert_eq!(bytes[9], 40);

        // A spring whose end is before its start is a spring of one zone,
        // at its start.
        trigger(
            &mut bytes,
            Trigger::Spring {
                from: 7,
                to: 2,
                peak: 3,
            },
        );
        assert_eq!(u16::from_le_bytes([bytes[1], bytes[2]]), 1 << 7);
        let force = u32::from_le_bytes([bytes[3], bytes[4], bytes[5], bytes[6]]);
        assert_eq!(force, 2 << 21, "zone seven at three");
    }

    #[test]
    fn the_player_lights_count_outwards_from_the_middle() {
        assert_eq!(player_leds(1), 0b00100);
        assert_eq!(player_leds(2), 0b01010);
        assert_eq!(player_leds(3), 0b10101);
        let report = dualsense(
            &Feedback {
                player: Some(2),
                ..Feedback::default()
            },
            Bus::Usb,
            0,
        );
        let body = body(&report, Bus::Usb);
        assert_eq!(body[1] & 0x10, 0x10);
        assert_eq!(body[43], 0b01010);
    }

    #[test]
    fn levels_are_bytes_with_the_ends_held() {
        assert_eq!(level(-1.0), 0);
        assert_eq!(level(0.5), 128);
        assert_eq!(level(2.0), 255);
    }
}