forge
Explore
Log in

Don't you dare go Hollow

game_cargo

Clone
★ 0

0 watching0 forksRust201.2 KiB5226b95Tahinli1 month ago1 commit

audio.rs432 lines, 13.2 KiBHistoryRawDownload
1//! Placeholder sound. Every effect is synthesised at startup as a 16-bit mono WAV
2//! held in memory, so no asset files ship with the game.
3
4use std::f32::consts::TAU;
5use std::sync::Arc;
6
7use bevy::audio::{
8 AudioPlayer, AudioSink, AudioSinkPlayback, AudioSource, PlaybackSettings, Volume,
9};
10use bevy::prelude::*;
11use bevy::ui_widgets::Activate;
12
13use crate::model::Notify;
14use crate::settings::Settings;
15
16const RATE: u32 = 44_100;
17const RATE_F: f32 = 44_100.0;
18/// Minimum gap between two plays of the same sound.
19const DEFAULT_GAP: f64 = 0.15;
20/// Whistles are long, so they get their own, wider gap.
21const WHISTLE_GAP: f64 = 1.5;
22/// Telegraph news beeps are at most this often.
23const TELEGRAPH_GAP: f64 = 2.0;
24
25/// A sound the game asks for. Gameplay systems write these, `play_sounds` plays them.
26#[derive(Message, Debug, Clone, Copy, PartialEq, Eq)]
27pub enum SoundEvent {
28 Click,
29 TrackLaid,
30 TrainDeparts,
31 Raid,
32 Telegraph,
33 Victory,
34 Defeat,
35}
36
37const SOUND_COUNT: usize = 7;
38
39impl SoundEvent {
40 fn slot(self) -> usize {
41 self as usize
42 }
43
44 fn min_gap(self) -> f64 {
45 match self {
46 SoundEvent::TrainDeparts => WHISTLE_GAP,
47 _ => DEFAULT_GAP,
48 }
49 }
50}
51
52pub struct GameAudioPlugin;
53
54impl Plugin for GameAudioPlugin {
55 fn build(&self, app: &mut App) {
56 app.add_message::<SoundEvent>()
57 .init_resource::<SoundLimiter>()
58 .add_observer(on_activate)
59 .add_systems(Startup, build_sfx)
60 .add_systems(Update, sync_ambient)
61 .add_systems(PostUpdate, play_sounds);
62 }
63}
64
65/// Handles for every one-shot sound.
66#[derive(Resource)]
67struct Sfx {
68 click: Handle<AudioSource>,
69 track_laid: Handle<AudioSource>,
70 train_departs: Handle<AudioSource>,
71 raid: Handle<AudioSource>,
72 telegraph: Handle<AudioSource>,
73 victory: Handle<AudioSource>,
74 defeat: Handle<AudioSource>,
75}
76
77/// Marks the looping ambient bed, whose volume follows the settings.
78#[derive(Component)]
79struct AmbientBed;
80
81/// Last play time per sound, and last telegraph time, in real seconds.
82#[derive(Resource)]
83struct SoundLimiter {
84 last: [f64; SOUND_COUNT],
85 telegraph: f64,
86}
87
88impl Default for SoundLimiter {
89 fn default() -> Self {
90 Self {
91 last: [f64::NEG_INFINITY; SOUND_COUNT],
92 telegraph: f64::NEG_INFINITY,
93 }
94 }
95}
96
97fn on_activate(_: On<Activate>, mut sounds: MessageWriter<SoundEvent>) {
98 sounds.write(SoundEvent::Click);
99}
100
101fn build_sfx(mut commands: Commands, sources: Option<ResMut<Assets<AudioSource>>>) {
102 // Without the audio plugin (harness runs) there is no asset type to fill, so stay silent.
103 let Some(mut sources) = sources else {
104 return;
105 };
106 let mut add_source = |samples: Vec<f32>| {
107 sources.add(AudioSource {
108 bytes: encode_wav(&samples),
109 })
110 };
111 let sfx = Sfx {
112 click: add_source(click()),
113 track_laid: add_source(track_laid()),
114 train_departs: add_source(train_departs()),
115 raid: add_source(raid()),
116 telegraph: add_source(telegraph()),
117 victory: add_source(victory()),
118 defeat: add_source(defeat()),
119 };
120 let ambient = add_source(ambient());
121 commands.spawn((
122 AudioPlayer(ambient),
123 PlaybackSettings::LOOP.with_volume(Volume::Linear(0.0)),
124 AmbientBed,
125 ));
126 commands.insert_resource(sfx);
127}
128
129/// Keeps the ambient bed at master * ambient, or silent when muted.
130fn sync_ambient(settings: Res<Settings>, mut beds: Query<&mut AudioSink, With<AmbientBed>>) {
131 let audio = &settings.audio;
132 let level = if audio.muted {
133 0.0
134 } else {
135 audio.master * audio.ambient
136 };
137 for mut sink in &mut beds {
138 sink.set_volume(Volume::Linear(level));
139 }
140}
141
142/// Plays queued sounds as one-shots. Runs after all Update systems, so a raid and the
143/// news from the same frame are both visible here.
144fn play_sounds(
145 mut commands: Commands,
146 sfx: Option<Res<Sfx>>,
147 settings: Res<Settings>,
148 time: Res<Time<Real>>,
149 mut limiter: ResMut<SoundLimiter>,
150 mut events: MessageReader<SoundEvent>,
151 mut notes: MessageReader<Notify>,
152) {
153 let now = time.elapsed_secs_f64();
154 let mut queue: Vec<SoundEvent> = events.read().copied().collect();
155
156 // News: one telegraph beep per window, and none in a frame that also has a raid.
157 let any_note = notes.read().next().is_some();
158 let raid_now = queue.contains(&SoundEvent::Raid);
159 if any_note && !raid_now && now - limiter.telegraph >= TELEGRAPH_GAP {
160 queue.push(SoundEvent::Telegraph);
161 }
162
163 let Some(sfx) = sfx else {
164 return;
165 };
166 let audio = &settings.audio;
167 if audio.muted || audio.master * audio.effects <= 0.0 {
168 return;
169 }
170 let volume = Volume::Linear(audio.master * audio.effects);
171
172 for sound in queue {
173 let slot = sound.slot();
174 if now - limiter.last[slot] < sound.min_gap() {
175 continue;
176 }
177 limiter.last[slot] = now;
178 let handle = match sound {
179 SoundEvent::Click => &sfx.click,
180 SoundEvent::TrackLaid => &sfx.track_laid,
181 SoundEvent::TrainDeparts => &sfx.train_departs,
182 SoundEvent::Raid => &sfx.raid,
183 SoundEvent::Telegraph => {
184 limiter.telegraph = now;
185 &sfx.telegraph
186 }
187 SoundEvent::Victory => &sfx.victory,
188 SoundEvent::Defeat => &sfx.defeat,
189 };
190 commands.spawn((
191 AudioPlayer::new(handle.clone()),
192 PlaybackSettings::DESPAWN.with_volume(volume),
193 ));
194 }
195}
196
197// ---------------------------------------------------------------------------
198// Synthesis. Each function returns mono samples in [-1, 1] at RATE.
199// ---------------------------------------------------------------------------
200
201fn samples(secs: f32) -> usize {
202 (secs * RATE_F).round() as usize
203}
204
205fn sine(freq: f32, t: f32) -> f32 {
206 (TAU * freq * t).sin()
207}
208
209/// Adds `sample(t)` into `buf` from `start` for `dur` seconds, where `t` is local time.
210fn add(buf: &mut [f32], start: f32, dur: f32, mut sample: impl FnMut(f32) -> f32) {
211 let first = (start * RATE_F).round() as usize;
212 for i in 0..samples(dur) {
213 let Some(slot) = buf.get_mut(first + i) else {
214 break;
215 };
216 *slot += sample(i as f32 / RATE_F);
217 }
218}
219
220/// Fade in over `attack` seconds and fade out over the last `release` seconds of `dur`.
221fn env(t: f32, dur: f32, attack: f32, release: f32) -> f32 {
222 let a = if attack > 0.0 {
223 (t / attack).min(1.0)
224 } else {
225 1.0
226 };
227 let r = if release > 0.0 {
228 ((dur - t) / release).clamp(0.0, 1.0)
229 } else {
230 1.0
231 };
232 a.min(r)
233}
234
235fn normalize(buf: &mut [f32], peak: f32) {
236 let max = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
237 if max > 0.0 {
238 let gain = peak / max;
239 for s in buf.iter_mut() {
240 *s *= gain;
241 }
242 }
243}
244
245/// Xorshift noise, so every run produces the same sounds.
246struct Noise(u32);
247
248impl Noise {
249 fn white(&mut self) -> f32 {
250 let mut x = self.0;
251 x ^= x << 13;
252 x ^= x >> 17;
253 x ^= x << 5;
254 self.0 = x;
255 x as f32 / u32::MAX as f32 * 2.0 - 1.0
256 }
257}
258
259/// One-pole low-pass run twice around the loop, so the filter state is already settled
260/// at the seam and the looped output is continuous.
261fn lowpass_loop(x: &[f32], alpha: f32) -> Vec<f32> {
262 let n = x.len();
263 let mut y = 0.0;
264 let mut out = Vec::with_capacity(n);
265 for i in 0..2 * n {
266 y += alpha * (x[i % n] - y);
267 if i >= n {
268 out.push(y);
269 }
270 }
271 out
272}
273
274/// Soft wooden tick, 40 ms.
275fn click() -> Vec<f32> {
276 const DUR: f32 = 0.04;
277 let mut buf = vec![0.0; samples(DUR)];
278 let mut noise = Noise(0x9E37_79B9);
279 add(&mut buf, 0.0, DUR, |t| {
280 let body =
281 sine(1400.0, t) * (-t * 110.0).exp() + 0.5 * sine(2900.0, t) * (-t * 200.0).exp();
282 let knock = noise.white() * (-t * 400.0).exp() * 0.3;
283 (0.5 * body + knock) * env(t, DUR, 0.001, 0.01)
284 });
285 buf
286}
287
288/// Two hammer clanks on rail: inharmonic partials plus a little noise.
289fn track_laid() -> Vec<f32> {
290 const DUR: f32 = 0.55;
291 let mut buf = vec![0.0; samples(DUR)];
292 let mut noise = Noise(0x2545_F491);
293 for start in [0.0, 0.2] {
294 add(&mut buf, start, 0.35, |t| {
295 let ring = 0.5 * sine(1250.0, t) + 0.3 * sine(1880.0, t) + 0.2 * sine(3140.0, t);
296 let clank = ring * (-t * 18.0).exp() * 0.35 + noise.white() * (-t * 70.0).exp() * 0.2;
297 clank * env(t, 0.35, 0.001, 0.08)
298 });
299 }
300 buf
301}
302
303/// Steam whistle, 0.8 s: two detuned sines around 650 Hz with vibrato, plus breath noise.
304fn train_departs() -> Vec<f32> {
305 const DUR: f32 = 0.8;
306 let mut buf = vec![0.0; samples(DUR)];
307 let mut noise = Noise(0x0BAD_5EED);
308 let (mut phase_a, mut phase_b, mut breath) = (0.0f32, 0.0f32, 0.0f32);
309 add(&mut buf, 0.0, DUR, |t| {
310 let freq = 650.0 * (1.0 + 0.015 * sine(5.5, t));
311 phase_a = (phase_a + TAU * freq / RATE_F) % TAU;
312 phase_b = (phase_b + TAU * freq * 1.012 / RATE_F) % TAU;
313 breath += 0.15 * (noise.white() - breath);
314 let whistle = 0.3 * phase_a.sin() + 0.2 * phase_b.sin();
315 (whistle + 0.4 * breath) * env(t, DUR, 0.08, 0.25)
316 });
317 buf
318}
319
320/// Distant explosion, about 1.2 s: low-passed noise burst over a 50-58 Hz thump.
321fn raid() -> Vec<f32> {
322 const DUR: f32 = 1.2;
323 let mut buf = vec![0.0; samples(DUR)];
324 let mut noise = Noise(0x1234_5678);
325 let (mut low, mut lower, mut thump_phase) = (0.0f32, 0.0f32, 0.0f32);
326 add(&mut buf, 0.0, DUR, |t| {
327 low += 0.05 * (noise.white() - low);
328 lower += 0.05 * (low - lower);
329 let blast = lower * 15.0 * (-t * 3.5).exp() * env(t, DUR, 0.01, 0.2);
330 thump_phase = (thump_phase + TAU * (50.0 + 8.0 * (-t * 8.0).exp()) / RATE_F) % TAU;
331 let thump = thump_phase.sin() * (-t * 5.0).exp();
332 blast + 0.8 * thump
333 });
334 normalize(&mut buf, 0.8);
335 buf
336}
337
338/// Morse-like telegraph: dot, dot, dash, dot at 800 Hz.
339fn telegraph() -> Vec<f32> {
340 const DUR: f32 = 0.6;
341 let mut buf = vec![0.0; samples(DUR)];
342 for (start, len) in [(0.0, 0.06), (0.11, 0.06), (0.22, 0.15), (0.42, 0.06)] {
343 add(&mut buf, start, len, |t| {
344 (0.3 * sine(800.0, t) + 0.1 * sine(1600.0, t)) * env(t, len, 0.004, 0.01)
345 });
346 }
347 buf
348}
349
350/// One decaying plucked tone with a soft octave overtone.
351fn chime(buf: &mut [f32], freq: f32, start: f32, dur: f32, amp: f32, decay: f32) {
352 add(buf, start, dur, |t| {
353 (sine(freq, t) + 0.15 * sine(2.0 * freq, t))
354 * amp
355 * (-t * decay).exp()
356 * env(t, dur, 0.008, dur * 0.3)
357 });
358}
359
360/// Three quick notes, then the chord held to 1.5 s in total.
361fn fanfare(run: [f32; 3], chord: [f32; 3]) -> Vec<f32> {
362 const DUR: f32 = 1.5;
363 let mut buf = vec![0.0; samples(DUR)];
364 for (i, freq) in run.into_iter().enumerate() {
365 chime(&mut buf, freq, i as f32 * 0.2, 0.6, 0.3, 4.0);
366 }
367 for freq in chord {
368 chime(&mut buf, freq, 0.6, 0.9, 0.16, 1.5);
369 }
370 buf
371}
372
373/// Rising major triad C-E-G.
374fn victory() -> Vec<f32> {
375 fanfare([523.25, 659.25, 783.99], [523.25, 659.25, 783.99])
376}
377
378/// Falling notes into a low C minor chord.
379fn defeat() -> Vec<f32> {
380 fanfare([392.0, 311.13, 261.63], [130.81, 155.56, 196.0])
381}
382
383/// Ten-second wind and rumble bed. Every component repeats exactly every 10 s, so the
384/// loop is seamless. Two distant artillery thuds sit inside the loop and decay before it ends.
385fn ambient() -> Vec<f32> {
386 const SECS: f32 = 10.0;
387 let n = samples(SECS);
388 let mut noise = Noise(0x7A3C_91E5);
389 let raw: Vec<f32> = (0..n).map(|_| noise.white()).collect();
390 let wind = lowpass_loop(&lowpass_loop(&raw, 0.03), 0.03);
391 let mut buf: Vec<f32> = wind
392 .iter()
393 .enumerate()
394 .map(|(i, w)| {
395 let t = i as f32 / RATE_F;
396 let swell = 0.7 + 0.2 * sine(1.0 / SECS, t) + 0.1 * (TAU * 2.0 * t / SECS + 1.0).sin();
397 w * swell
398 })
399 .collect();
400 normalize(&mut buf, 0.3);
401 add(&mut buf, 3.3, 2.0, |t| 0.25 * thud(t));
402 add(&mut buf, 7.1, 2.0, |t| 0.18 * thud(t));
403 buf
404}
405
406fn thud(t: f32) -> f32 {
407 sine(45.0, t) * (-t * 3.0).exp() * env(t, 2.0, 0.003, 0.5)
408}
409
410/// Encodes mono f32 samples as a 16-bit PCM WAV file in memory.
411fn encode_wav(samples: &[f32]) -> Arc<[u8]> {
412 let data_len = (samples.len() * 2) as u32;
413 let mut out = Vec::with_capacity(44 + data_len as usize);
414 out.extend_from_slice(b"RIFF");
415 out.extend_from_slice(&(36 + data_len).to_le_bytes());
416 out.extend_from_slice(b"WAVE");
417 out.extend_from_slice(b"fmt ");
418 out.extend_from_slice(&16u32.to_le_bytes());
419 out.extend_from_slice(&1u16.to_le_bytes()); // PCM
420 out.extend_from_slice(&1u16.to_le_bytes()); // mono
421 out.extend_from_slice(&RATE.to_le_bytes());
422 out.extend_from_slice(&(RATE * 2).to_le_bytes()); // byte rate
423 out.extend_from_slice(&2u16.to_le_bytes()); // block align
424 out.extend_from_slice(&16u16.to_le_bytes()); // bits per sample
425 out.extend_from_slice(b"data");
426 out.extend_from_slice(&data_len.to_le_bytes());
427 for &s in samples {
428 let v = (s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
429 out.extend_from_slice(&v.to_le_bytes());
430 }
431 Arc::from(out)
432}