//! Placeholder sound. Every effect is synthesised at startup as a 16-bit mono WAV //! held in memory, so no asset files ship with the game. use std::f32::consts::TAU; use std::sync::Arc; use bevy::audio::{ AudioPlayer, AudioSink, AudioSinkPlayback, AudioSource, PlaybackSettings, Volume, }; use bevy::prelude::*; use bevy::ui_widgets::Activate; use crate::model::Notify; use crate::settings::Settings; const RATE: u32 = 44_100; const RATE_F: f32 = 44_100.0; /// Minimum gap between two plays of the same sound. const DEFAULT_GAP: f64 = 0.15; /// Whistles are long, so they get their own, wider gap. const WHISTLE_GAP: f64 = 1.5; /// Telegraph news beeps are at most this often. const TELEGRAPH_GAP: f64 = 2.0; /// A sound the game asks for. Gameplay systems write these, `play_sounds` plays them. #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)] pub enum SoundEvent { Click, TrackLaid, TrainDeparts, Raid, Telegraph, Victory, Defeat, } const SOUND_COUNT: usize = 7; impl SoundEvent { fn slot(self) -> usize { self as usize } fn min_gap(self) -> f64 { match self { SoundEvent::TrainDeparts => WHISTLE_GAP, _ => DEFAULT_GAP, } } } pub struct GameAudioPlugin; impl Plugin for GameAudioPlugin { fn build(&self, app: &mut App) { app.add_message::() .init_resource::() .add_observer(on_activate) .add_systems(Startup, build_sfx) .add_systems(Update, sync_ambient) .add_systems(PostUpdate, play_sounds); } } /// Handles for every one-shot sound. #[derive(Resource)] struct Sfx { click: Handle, track_laid: Handle, train_departs: Handle, raid: Handle, telegraph: Handle, victory: Handle, defeat: Handle, } /// Marks the looping ambient bed, whose volume follows the settings. #[derive(Component)] struct AmbientBed; /// Last play time per sound, and last telegraph time, in real seconds. #[derive(Resource)] struct SoundLimiter { last: [f64; SOUND_COUNT], telegraph: f64, } impl Default for SoundLimiter { fn default() -> Self { Self { last: [f64::NEG_INFINITY; SOUND_COUNT], telegraph: f64::NEG_INFINITY, } } } fn on_activate(_: On, mut sounds: MessageWriter) { sounds.write(SoundEvent::Click); } fn build_sfx(mut commands: Commands, sources: Option>>) { // Without the audio plugin (harness runs) there is no asset type to fill, so stay silent. let Some(mut sources) = sources else { return; }; let mut add_source = |samples: Vec| { sources.add(AudioSource { bytes: encode_wav(&samples), }) }; let sfx = Sfx { click: add_source(click()), track_laid: add_source(track_laid()), train_departs: add_source(train_departs()), raid: add_source(raid()), telegraph: add_source(telegraph()), victory: add_source(victory()), defeat: add_source(defeat()), }; let ambient = add_source(ambient()); commands.spawn(( AudioPlayer(ambient), PlaybackSettings::LOOP.with_volume(Volume::Linear(0.0)), AmbientBed, )); commands.insert_resource(sfx); } /// Keeps the ambient bed at master * ambient, or silent when muted. fn sync_ambient(settings: Res, mut beds: Query<&mut AudioSink, With>) { let audio = &settings.audio; let level = if audio.muted { 0.0 } else { audio.master * audio.ambient }; for mut sink in &mut beds { sink.set_volume(Volume::Linear(level)); } } /// Plays queued sounds as one-shots. Runs after all Update systems, so a raid and the /// news from the same frame are both visible here. fn play_sounds( mut commands: Commands, sfx: Option>, settings: Res, time: Res>, mut limiter: ResMut, mut events: MessageReader, mut notes: MessageReader, ) { let now = time.elapsed_secs_f64(); let mut queue: Vec = events.read().copied().collect(); // News: one telegraph beep per window, and none in a frame that also has a raid. let any_note = notes.read().next().is_some(); let raid_now = queue.contains(&SoundEvent::Raid); if any_note && !raid_now && now - limiter.telegraph >= TELEGRAPH_GAP { queue.push(SoundEvent::Telegraph); } let Some(sfx) = sfx else { return; }; let audio = &settings.audio; if audio.muted || audio.master * audio.effects <= 0.0 { return; } let volume = Volume::Linear(audio.master * audio.effects); for sound in queue { let slot = sound.slot(); if now - limiter.last[slot] < sound.min_gap() { continue; } limiter.last[slot] = now; let handle = match sound { SoundEvent::Click => &sfx.click, SoundEvent::TrackLaid => &sfx.track_laid, SoundEvent::TrainDeparts => &sfx.train_departs, SoundEvent::Raid => &sfx.raid, SoundEvent::Telegraph => { limiter.telegraph = now; &sfx.telegraph } SoundEvent::Victory => &sfx.victory, SoundEvent::Defeat => &sfx.defeat, }; commands.spawn(( AudioPlayer::new(handle.clone()), PlaybackSettings::DESPAWN.with_volume(volume), )); } } // --------------------------------------------------------------------------- // Synthesis. Each function returns mono samples in [-1, 1] at RATE. // --------------------------------------------------------------------------- fn samples(secs: f32) -> usize { (secs * RATE_F).round() as usize } fn sine(freq: f32, t: f32) -> f32 { (TAU * freq * t).sin() } /// Adds `sample(t)` into `buf` from `start` for `dur` seconds, where `t` is local time. fn add(buf: &mut [f32], start: f32, dur: f32, mut sample: impl FnMut(f32) -> f32) { let first = (start * RATE_F).round() as usize; for i in 0..samples(dur) { let Some(slot) = buf.get_mut(first + i) else { break; }; *slot += sample(i as f32 / RATE_F); } } /// Fade in over `attack` seconds and fade out over the last `release` seconds of `dur`. fn env(t: f32, dur: f32, attack: f32, release: f32) -> f32 { let a = if attack > 0.0 { (t / attack).min(1.0) } else { 1.0 }; let r = if release > 0.0 { ((dur - t) / release).clamp(0.0, 1.0) } else { 1.0 }; a.min(r) } fn normalize(buf: &mut [f32], peak: f32) { let max = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); if max > 0.0 { let gain = peak / max; for s in buf.iter_mut() { *s *= gain; } } } /// Xorshift noise, so every run produces the same sounds. struct Noise(u32); impl Noise { fn white(&mut self) -> f32 { let mut x = self.0; x ^= x << 13; x ^= x >> 17; x ^= x << 5; self.0 = x; x as f32 / u32::MAX as f32 * 2.0 - 1.0 } } /// One-pole low-pass run twice around the loop, so the filter state is already settled /// at the seam and the looped output is continuous. fn lowpass_loop(x: &[f32], alpha: f32) -> Vec { let n = x.len(); let mut y = 0.0; let mut out = Vec::with_capacity(n); for i in 0..2 * n { y += alpha * (x[i % n] - y); if i >= n { out.push(y); } } out } /// Soft wooden tick, 40 ms. fn click() -> Vec { const DUR: f32 = 0.04; let mut buf = vec![0.0; samples(DUR)]; let mut noise = Noise(0x9E37_79B9); add(&mut buf, 0.0, DUR, |t| { let body = sine(1400.0, t) * (-t * 110.0).exp() + 0.5 * sine(2900.0, t) * (-t * 200.0).exp(); let knock = noise.white() * (-t * 400.0).exp() * 0.3; (0.5 * body + knock) * env(t, DUR, 0.001, 0.01) }); buf } /// Two hammer clanks on rail: inharmonic partials plus a little noise. fn track_laid() -> Vec { const DUR: f32 = 0.55; let mut buf = vec![0.0; samples(DUR)]; let mut noise = Noise(0x2545_F491); for start in [0.0, 0.2] { add(&mut buf, start, 0.35, |t| { let ring = 0.5 * sine(1250.0, t) + 0.3 * sine(1880.0, t) + 0.2 * sine(3140.0, t); let clank = ring * (-t * 18.0).exp() * 0.35 + noise.white() * (-t * 70.0).exp() * 0.2; clank * env(t, 0.35, 0.001, 0.08) }); } buf } /// Steam whistle, 0.8 s: two detuned sines around 650 Hz with vibrato, plus breath noise. fn train_departs() -> Vec { const DUR: f32 = 0.8; let mut buf = vec![0.0; samples(DUR)]; let mut noise = Noise(0x0BAD_5EED); let (mut phase_a, mut phase_b, mut breath) = (0.0f32, 0.0f32, 0.0f32); add(&mut buf, 0.0, DUR, |t| { let freq = 650.0 * (1.0 + 0.015 * sine(5.5, t)); phase_a = (phase_a + TAU * freq / RATE_F) % TAU; phase_b = (phase_b + TAU * freq * 1.012 / RATE_F) % TAU; breath += 0.15 * (noise.white() - breath); let whistle = 0.3 * phase_a.sin() + 0.2 * phase_b.sin(); (whistle + 0.4 * breath) * env(t, DUR, 0.08, 0.25) }); buf } /// Distant explosion, about 1.2 s: low-passed noise burst over a 50-58 Hz thump. fn raid() -> Vec { const DUR: f32 = 1.2; let mut buf = vec![0.0; samples(DUR)]; let mut noise = Noise(0x1234_5678); let (mut low, mut lower, mut thump_phase) = (0.0f32, 0.0f32, 0.0f32); add(&mut buf, 0.0, DUR, |t| { low += 0.05 * (noise.white() - low); lower += 0.05 * (low - lower); let blast = lower * 15.0 * (-t * 3.5).exp() * env(t, DUR, 0.01, 0.2); thump_phase = (thump_phase + TAU * (50.0 + 8.0 * (-t * 8.0).exp()) / RATE_F) % TAU; let thump = thump_phase.sin() * (-t * 5.0).exp(); blast + 0.8 * thump }); normalize(&mut buf, 0.8); buf } /// Morse-like telegraph: dot, dot, dash, dot at 800 Hz. fn telegraph() -> Vec { const DUR: f32 = 0.6; let mut buf = vec![0.0; samples(DUR)]; for (start, len) in [(0.0, 0.06), (0.11, 0.06), (0.22, 0.15), (0.42, 0.06)] { add(&mut buf, start, len, |t| { (0.3 * sine(800.0, t) + 0.1 * sine(1600.0, t)) * env(t, len, 0.004, 0.01) }); } buf } /// One decaying plucked tone with a soft octave overtone. fn chime(buf: &mut [f32], freq: f32, start: f32, dur: f32, amp: f32, decay: f32) { add(buf, start, dur, |t| { (sine(freq, t) + 0.15 * sine(2.0 * freq, t)) * amp * (-t * decay).exp() * env(t, dur, 0.008, dur * 0.3) }); } /// Three quick notes, then the chord held to 1.5 s in total. fn fanfare(run: [f32; 3], chord: [f32; 3]) -> Vec { const DUR: f32 = 1.5; let mut buf = vec![0.0; samples(DUR)]; for (i, freq) in run.into_iter().enumerate() { chime(&mut buf, freq, i as f32 * 0.2, 0.6, 0.3, 4.0); } for freq in chord { chime(&mut buf, freq, 0.6, 0.9, 0.16, 1.5); } buf } /// Rising major triad C-E-G. fn victory() -> Vec { fanfare([523.25, 659.25, 783.99], [523.25, 659.25, 783.99]) } /// Falling notes into a low C minor chord. fn defeat() -> Vec { fanfare([392.0, 311.13, 261.63], [130.81, 155.56, 196.0]) } /// Ten-second wind and rumble bed. Every component repeats exactly every 10 s, so the /// loop is seamless. Two distant artillery thuds sit inside the loop and decay before it ends. fn ambient() -> Vec { const SECS: f32 = 10.0; let n = samples(SECS); let mut noise = Noise(0x7A3C_91E5); let raw: Vec = (0..n).map(|_| noise.white()).collect(); let wind = lowpass_loop(&lowpass_loop(&raw, 0.03), 0.03); let mut buf: Vec = wind .iter() .enumerate() .map(|(i, w)| { let t = i as f32 / RATE_F; let swell = 0.7 + 0.2 * sine(1.0 / SECS, t) + 0.1 * (TAU * 2.0 * t / SECS + 1.0).sin(); w * swell }) .collect(); normalize(&mut buf, 0.3); add(&mut buf, 3.3, 2.0, |t| 0.25 * thud(t)); add(&mut buf, 7.1, 2.0, |t| 0.18 * thud(t)); buf } fn thud(t: f32) -> f32 { sine(45.0, t) * (-t * 3.0).exp() * env(t, 2.0, 0.003, 0.5) } /// Encodes mono f32 samples as a 16-bit PCM WAV file in memory. fn encode_wav(samples: &[f32]) -> Arc<[u8]> { let data_len = (samples.len() * 2) as u32; let mut out = Vec::with_capacity(44 + data_len as usize); out.extend_from_slice(b"RIFF"); out.extend_from_slice(&(36 + data_len).to_le_bytes()); out.extend_from_slice(b"WAVE"); out.extend_from_slice(b"fmt "); out.extend_from_slice(&16u32.to_le_bytes()); out.extend_from_slice(&1u16.to_le_bytes()); // PCM out.extend_from_slice(&1u16.to_le_bytes()); // mono out.extend_from_slice(&RATE.to_le_bytes()); out.extend_from_slice(&(RATE * 2).to_le_bytes()); // byte rate out.extend_from_slice(&2u16.to_le_bytes()); // block align out.extend_from_slice(&16u16.to_le_bytes()); // bits per sample out.extend_from_slice(b"data"); out.extend_from_slice(&data_len.to_le_bytes()); for &s in samples { let v = (s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16; out.extend_from_slice(&v.to_le_bytes()); } Arc::from(out) }