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
//! Sounds made from arithmetic rather than recordings.
//!
//! A tank game needs a gun, a shell landing, a hit on armour and something
//! blowing up, and it needs them before anyone has sat down with a
//! microphone. Everything here is a pure function of the sample rate and a
//! seed, so a clip is rendered at the device's own rate — no resampling — and
//! two takes from two seeds are not quite the same, which is what stops a
//! volley sounding like one sample on a loop.
//!
//! None of it runs when a sound is played. The explosion is a second and a
//! half of `exp`, `sin` and `tanh` on every sample, which is a few
//! milliseconds in a debug build, and a few milliseconds in the middle of a
//! frame is a hitch. So [`super::Audio`] renders a handful of takes of each
//! effect once, when it opens, and a play is a copy of one of them.
use std::f32::consts::TAU;

/// Gunshot: a crack and a thump, and the crack is over almost at once.
const GUNSHOT_SECONDS: f32 = 0.25;
/// Explosion: long enough for the rumble to roll off rather than cut.
const EXPLOSION_SECONDS: f32 = 1.5;
/// Impact: a shell hitting dirt is a tick and not much after it.
const IMPACT_SECONDS: f32 = 0.12;
/// Clank: metal rings for a moment and then stops.
const CLANK_SECONDS: f32 = 0.12;
/// Shield: a whoomp takes its time to arrive and longer to go, and the
/// sweep in it has run its four tenths well before the end.
const SHIELD_SECONDS: f32 = 0.7;

/// How long the front of a burst of noise takes to reach full level.
///
/// A step from silence to full noise puts a DC edge in the buffer, which
/// some outputs turn into a pop of their own. A millisecond is far shorter
/// than the ear resolves as an attack, so the crack is as sharp as ever and
/// the edge is gone.
const NOISE_ATTACK: f32 = 0.001;

/// How long the very end of every clip takes to fade to nothing.
///
/// A decay gets a clip quiet, but not to zero, and the mixer dropping a
/// buffer at whatever value it happened to end on is a click. Twenty
/// milliseconds is under the decays' own tails, so it changes nothing that
/// can be heard.
const RELEASE: f32 = 0.02;

/// One step of a 32-bit xorshift: as much randomness as a sound needs, from
/// three shifts. A state of zero stays zero forever; every other state
/// cycles through every other value.
pub(super) fn xorshift(state: &mut u32) -> u32 {
    *state ^= *state << 13;
    *state ^= *state >> 17;
    *state ^= *state << 5;
    *state
}

/// White noise from a xorshift, in -1..1.
///
/// The same generator as [`super::Audio::roll`], carried separately because a
/// clip wants tens of thousands of draws from one seed and the audio's own
/// sequence should only move on once per play.
pub(super) struct Noise(u32);

impl Noise {
    pub(super) fn new(seed: u32) -> Self {
        Self(seed.max(1))
    }

    fn bits(&mut self) -> u32 {
        xorshift(&mut self.0)
    }

    /// One sample of noise.
    pub(super) fn sample(&mut self) -> f32 {
        // The top 24 bits: as many as an f32 can hold exactly.
        (self.bits() >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0
    }

    /// A factor within `spread` of one, for making one play differ from the
    /// last: a shot pitched a few percent up or down is still that gun.
    fn vary(&mut self, spread: f32) -> f32 {
        1.0 + self.sample() * spread
    }
}

/// A one-pole low-pass — the simplest filter there is, and enough to turn
/// white noise into a rumble or take the edge off a saw.
pub(super) struct OnePole {
    rate: f32,
    value: f32,
    coefficient: f32,
}

impl OnePole {
    pub(super) fn new(rate: f32, cutoff: f32) -> Self {
        let mut filter = Self {
            rate,
            value: 0.0,
            coefficient: 0.0,
        };
        filter.set_cutoff(cutoff);
        filter
    }

    /// Moves the corner, which is how a filter sweeps: a crack that starts
    /// bright and dulls is the cutoff falling, sample by sample.
    pub(super) fn set_cutoff(&mut self, cutoff: f32) {
        self.coefficient = 1.0 - (-TAU * cutoff / self.rate).exp();
    }

    pub(super) fn step(&mut self, input: f32) -> f32 {
        self.value += (input - self.value) * self.coefficient;
        self.value
    }
}

/// Scales a clip so its loudest sample is exactly one.
///
/// The callers set gain in one place — [`super::Effect::gain`] — and that
/// only means anything if every clip starts from the same level, whatever
/// its filters and decays happened to leave.
fn normalise(samples: &mut [f32]) {
    let peak = samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs()));
    if peak > 0.0 {
        for sample in samples {
            *sample /= peak;
        }
    }
}

/// A linear ramp from nothing to full over `seconds`, then one.
fn attack(t: f32, seconds: f32) -> f32 {
    (t / seconds).min(1.0)
}

/// One until the last `seconds` of a clip `total` long, then a ramp to
/// nothing.
fn release(t: f32, total: f32, seconds: f32) -> f32 {
    ((total - t) / seconds).clamp(0.0, 1.0)
}

/// Runs a per-sample function over a clip's length, then normalises.
fn render(rate: u32, seconds: f32, mut sample: impl FnMut(f32) -> f32) -> Vec<f32> {
    let count = (rate as f32 * seconds).round() as usize;
    let mut samples: Vec<f32> = (0..count)
        .map(|i| {
            let t = i as f32 / rate as f32;
            sample(t) * release(t, seconds, RELEASE)
        })
        .collect();
    normalise(&mut samples);
    samples
}

/// A tank gun: a crack of noise that dulls as fast as it fades, over a thump
/// that starts around 90 Hz and sags to 40 as it dies away.
pub(super) fn gunshot(rate: u32, seed: u32) -> Vec<f32> {
    let mut noise = Noise::new(seed);
    let brightness = noise.vary(0.15);
    let weight = noise.vary(0.1);
    let mut crack = OnePole::new(rate as f32, 8000.0);
    let mut thump_phase = 0.0f32;

    render(rate, GUNSHOT_SECONDS, |t| {
        let decay = (-30.0 * t).exp();
        crack.set_cutoff(300.0 + 9000.0 * brightness * decay);
        let crack = crack.step(noise.sample()) * decay * attack(t, NOISE_ATTACK);

        let thump = (TAU * thump_phase).sin() * (-15.0 * t).exp();
        let frequency = (40.0 + 50.0 * (-20.0 * t).exp()) * weight;
        thump_phase += frequency / rate as f32;

        crack + 0.8 * thump
    })
}

/// Something blowing up: a rumble of low-passed noise whose corner keeps
/// falling as it decays, under a 35 Hz sub, pushed through a soft clip so the
/// loud start sounds pressed rather than cut.
pub(super) fn explosion(rate: u32, seed: u32) -> Vec<f32> {
    let mut noise = Noise::new(seed);
    let depth = noise.vary(0.2);
    let mut rumble = OnePole::new(rate as f32, 250.0);
    let mut sub_phase = 0.0f32;

    render(rate, EXPLOSION_SECONDS, |t| {
        let decay = (-3.0 * t).exp();
        rumble.set_cutoff(40.0 + 250.0 * depth * (-1.5 * t).exp());
        let rumble = rumble.step(noise.sample()) * decay;

        let sub = (TAU * sub_phase).sin() * decay;
        sub_phase += 35.0 * depth / rate as f32;

        // The rumble is quiet after the filter; the drive brings it up to
        // where the clip presses against the soft clip in its first moments.
        ((6.0 * rumble + 0.8 * sub) * attack(t, 0.01)).tanh()
    })
}

/// A shell hitting the ground: a tick of noise, and a dull 500 Hz ring that
/// is gone almost at once.
pub(super) fn impact(rate: u32, seed: u32) -> Vec<f32> {
    let mut noise = Noise::new(seed);
    let tone = noise.vary(0.1);
    let mut tick = OnePole::new(rate as f32, 3000.0);
    let mut ping_phase = 0.0f32;

    render(rate, IMPACT_SECONDS, |t| {
        let tick = tick.step(noise.sample()) * (-80.0 * t).exp() * attack(t, NOISE_ATTACK);

        let ping = (TAU * ping_phase).sin() * (-35.0 * t).exp();
        ping_phase += 500.0 * tone / rate as f32;

        tick + 0.6 * ping
    })
}

/// Metal on metal — a part coming off, or a shell on armour: two sines at
/// pitches that are not harmonics of one another, which is what makes it
/// ring like a plate rather than sing like a bell, and a tick for the blow.
pub(super) fn clank(rate: u32, seed: u32) -> Vec<f32> {
    let mut noise = Noise::new(seed);
    let tone = noise.vary(0.08);
    let mut tick = OnePole::new(rate as f32, 4000.0);
    let mut low_phase = 0.0f32;
    let mut high_phase = 0.0f32;

    render(rate, CLANK_SECONDS, |t| {
        let tick = tick.step(noise.sample()) * (-150.0 * t).exp() * attack(t, NOISE_ATTACK);

        let low = (TAU * low_phase).sin() * (-40.0 * t).exp();
        let high = (TAU * high_phase).sin() * (-50.0 * t).exp();
        low_phase += 1200.0 * tone / rate as f32;
        high_phase += 1900.0 * tone / rate as f32;

        0.5 * tick + 0.6 * low + 0.4 * high
    })
}

/// A shield going up: a whoomp. A sine that starts at 180 Hz and sweeps
/// down to 50 over four tenths of a second -- the same fraction of an
/// octave in every hundredth of it, which is how a falling pitch is heard
/// to fall -- swelling in over its first few hundredths rather than
/// starting with a click, over a soft swell of low-passed noise that rises
/// with it and dies a little faster: the air being pushed out of the way.
/// A push rather than a bang, and the one sound here that is meant to be
/// felt more than heard, which is why it goes to the pad's actuators as
/// hard as the gun does.
pub(super) fn shield(rate: u32, seed: u32) -> Vec<f32> {
    let mut noise = Noise::new(seed);
    let depth = noise.vary(0.08);
    let mut swell = OnePole::new(rate as f32, 350.0);
    let mut phase = 0.0f32;

    render(rate, SHIELD_SECONDS, |t| {
        let along = (t / 0.4).min(1.0);
        let frequency = 180.0 * (50.0f32 / 180.0).powf(along) * depth;
        phase += frequency / rate as f32;
        let tone = (TAU * phase).sin() * attack(t, 0.04) * (-6.0 * t).exp();

        let swell = swell.step(noise.sample()) * attack(t, 0.08) * (-7.0 * t).exp();
        tone + 1.5 * swell
    })
}

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

    /// Every clip, with the length it was designed to.
    fn clips(rate: u32) -> [(&'static str, Vec<f32>, f32); 5] {
        [
            ("gunshot", gunshot(rate, 7), GUNSHOT_SECONDS),
            ("explosion", explosion(rate, 7), EXPLOSION_SECONDS),
            ("impact", impact(rate, 7), IMPACT_SECONDS),
            ("clank", clank(rate, 7), CLANK_SECONDS),
            ("shield", shield(rate, 7), SHIELD_SECONDS),
        ]
    }

    /// The clips that build rather than crack: an explosion, and the
    /// shield's whoomp.
    fn swells(name: &str) -> bool {
        matches!(name, "explosion" | "shield")
    }

    fn peak(samples: &[f32]) -> f32 {
        samples.iter().fold(0.0f32, |peak, s| peak.max(s.abs()))
    }

    #[test]
    fn every_clip_is_as_long_as_it_says_at_any_device_rate() {
        for rate in [44100, 48000] {
            for (name, samples, seconds) in clips(rate) {
                assert_eq!(
                    samples.len(),
                    (rate as f32 * seconds).round() as usize,
                    "{name} at {rate} Hz",
                );
            }
        }
    }

    #[test]
    fn every_clip_peaks_at_exactly_one() {
        // Gain is set in one place, which only works if the clips all start
        // from the same level.
        for (name, samples, _) in clips(48000) {
            let peak = peak(&samples);
            assert!((peak - 1.0).abs() < 1e-5, "{name} peaks at {peak}");
        }
    }

    #[test]
    fn every_clip_starts_from_near_silence() {
        // A first sample well off zero is a pop on top of the sound. The
        // gunshot is not exempt: its crack is a millisecond in, which is
        // sharper than anyone can hear and leaves no edge.
        for (name, samples, _) in clips(48000) {
            assert!(samples[0].abs() < 1e-3, "{name} opens at {}", samples[0]);
        }
    }

    #[test]
    fn the_transients_hit_within_a_millisecond_and_the_explosion_swells() {
        // A gun, a shell landing and a hit on metal are steps from nothing
        // to full: the millisecond they take is for the edge rather than the
        // ear, and one that eased in would be a cough. An explosion and the
        // shield's whoomp are the two things here that build, which is
        // what their attacks are for.
        for (name, samples, _) in clips(48000) {
            let first_millisecond = peak(&samples[..48]);
            if swells(name) {
                assert!(
                    first_millisecond < 0.3,
                    "the {name} pops: {first_millisecond}"
                );
            } else {
                assert!(
                    first_millisecond > 0.3,
                    "the {name} went soft: {first_millisecond}"
                );
            }
        }
    }

    #[test]
    fn every_clip_has_died_away_by_its_last_twentieth() {
        // A clip still audible when it ends is one that got cut off.
        for (name, samples, _) in clips(48000) {
            let tail = &samples[samples.len() * 19 / 20..];
            let tail = peak(tail);
            assert!(tail < 0.05, "{name} ends at {tail}");
            // The ramp reaches nothing one sample past the end; the last
            // sample it does write is a millionth of full scale.
            let last = samples.last().unwrap().abs();
            assert!(last < 1e-4, "{name} does not reach nothing: {last}");
        }
    }

    #[test]
    fn the_seed_makes_one_play_differ_from_the_next() {
        assert_ne!(gunshot(48000, 1), gunshot(48000, 2));
        assert_ne!(explosion(48000, 1), explosion(48000, 2));
        assert_ne!(impact(48000, 1), impact(48000, 2));
        assert_ne!(clank(48000, 1), clank(48000, 2));
        assert_ne!(shield(48000, 1), shield(48000, 2));
        assert_eq!(
            clank(48000, 5),
            clank(48000, 5),
            "and the same seed repeats"
        );
    }

    /// The pitch a stretch of a clip is loudest at, in hertz, to the
    /// nearest five: a Fourier sum at each candidate, which is slow and
    /// does not care about the noise laid over the tone, where counting
    /// zero crossings is quick and does.
    fn loudest_hz(samples: &[f32], rate: u32, from: f32, to: f32) -> f32 {
        let window = &samples[(from * rate as f32) as usize..(to * rate as f32) as usize];
        (30..=300)
            .step_by(5)
            .map(|hz| {
                let (mut re, mut im) = (0.0f32, 0.0f32);
                for (i, sample) in window.iter().enumerate() {
                    let phase = TAU * hz as f32 * i as f32 / rate as f32;
                    re += sample * phase.cos();
                    im += sample * phase.sin();
                }
                (hz as f32, re * re + im * im)
            })
            .max_by(|a, b| a.1.total_cmp(&b.1))
            .map(|(hz, _)| hz)
            .unwrap()
    }

    /// The whoomp is what it says: a pitch that falls from the top of the
    /// sweep to the bottom -- around a hundred and fifty over its first
    /// few hundredths, where it has already come off the hundred and
    /// eighty it starts at, and fifty or so once the four tenths have run
    /// -- with the loudest of it early.
    #[test]
    fn the_shield_sweeps_down_from_around_180_hz_to_around_50() {
        let rate = 48000;
        let samples = shield(rate, 7);
        let (high, low) = (
            loudest_hz(&samples, rate, 0.02, 0.08),
            loudest_hz(&samples, rate, 0.35, 0.5),
        );
        assert!(
            (120.0..=200.0).contains(&high),
            "near the top of the sweep to begin with: {high} Hz"
        );
        assert!(
            (40.0..=70.0).contains(&low),
            "and at the bottom once the sweep has run: {low} Hz"
        );
        let loudest = samples
            .iter()
            .enumerate()
            .max_by(|a, b| a.1.abs().total_cmp(&b.1.abs()))
            .map(|(i, _)| i as f32 / rate as f32)
            .unwrap();
        assert!(loudest < 0.2, "loudest early, as a whoomp is: {loudest} s");
    }

    #[test]
    fn noise_stays_within_a_sample_and_covers_both_signs() {
        let mut noise = Noise::new(42);
        let (mut low, mut high) = (0.0f32, 0.0f32);
        for _ in 0..10_000 {
            let sample = noise.sample();
            assert!((-1.0..=1.0).contains(&sample), "{sample}");
            low = low.min(sample);
            high = high.max(sample);
        }
        assert!(low < -0.9 && high > 0.9, "{low}..{high}");
    }

    #[test]
    fn a_zero_seed_still_makes_noise() {
        // Xorshift on zero is zero forever; the seed is nudged off it.
        let mut noise = Noise::new(0);
        assert!((0..100).any(|_| noise.sample() != -1.0));
    }
}