| 1 | |
| 2 | |
| 3 | |
| 4 | use std::f32::consts::TAU; |
| 5 | use std::sync::Arc; |
| 6 | |
| 7 | use bevy::audio::{ |
| 8 | AudioPlayer, AudioSink, AudioSinkPlayback, AudioSource, PlaybackSettings, Volume, |
| 9 | }; |
| 10 | use bevy::prelude::*; |
| 11 | use bevy::ui_widgets::Activate; |
| 12 | |
| 13 | use crate::model::Notify; |
| 14 | use crate::settings::Settings; |
| 15 | |
| 16 | const RATE: u32 = 44_100; |
| 17 | const RATE_F: f32 = 44_100.0; |
| 18 | |
| 19 | const DEFAULT_GAP: f64 = 0.15; |
| 20 | |
| 21 | const WHISTLE_GAP: f64 = 1.5; |
| 22 | |
| 23 | const TELEGRAPH_GAP: f64 = 2.0; |
| 24 | |
| 25 | |
| 26 | #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)] |
| 27 | pub enum SoundEvent { |
| 28 | Click, |
| 29 | TrackLaid, |
| 30 | TrainDeparts, |
| 31 | Raid, |
| 32 | Telegraph, |
| 33 | Victory, |
| 34 | Defeat, |
| 35 | } |
| 36 | |
| 37 | const SOUND_COUNT: usize = 7; |
| 38 | |
| 39 | impl 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 | |
| 52 | pub struct GameAudioPlugin; |
| 53 | |
| 54 | impl 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 | |
| 66 | #[derive(Resource)] |
| 67 | struct 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 | |
| 78 | #[derive(Component)] |
| 79 | struct AmbientBed; |
| 80 | |
| 81 | |
| 82 | #[derive(Resource)] |
| 83 | struct SoundLimiter { |
| 84 | last: [f64; SOUND_COUNT], |
| 85 | telegraph: f64, |
| 86 | } |
| 87 | |
| 88 | impl 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 | |
| 97 | fn on_activate(_: On<Activate>, mut sounds: MessageWriter<SoundEvent>) { |
| 98 | sounds.write(SoundEvent::Click); |
| 99 | } |
| 100 | |
| 101 | fn build_sfx(mut commands: Commands, sources: Option<ResMut<Assets<AudioSource>>>) { |
| 102 | |
| 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 | |
| 130 | fn 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 | |
| 143 | |
| 144 | fn 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 | |
| 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 | |
| 199 | |
| 200 | |
| 201 | fn samples(secs: f32) -> usize { |
| 202 | (secs * RATE_F).round() as usize |
| 203 | } |
| 204 | |
| 205 | fn sine(freq: f32, t: f32) -> f32 { |
| 206 | (TAU * freq * t).sin() |
| 207 | } |
| 208 | |
| 209 | |
| 210 | fn 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 | |
| 221 | fn 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 | |
| 235 | fn 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 | |
| 246 | struct Noise(u32); |
| 247 | |
| 248 | impl 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 | |
| 260 | |
| 261 | fn 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 | |
| 275 | fn 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 | |
| 289 | fn 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 | |
| 304 | fn 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 | |
| 321 | fn 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 | |
| 339 | fn 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 | |
| 351 | fn 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 | |
| 361 | fn 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 | |
| 374 | fn victory() -> Vec<f32> { |
| 375 | fanfare([523.25, 659.25, 783.99], [523.25, 659.25, 783.99]) |
| 376 | } |
| 377 | |
| 378 | |
| 379 | fn defeat() -> Vec<f32> { |
| 380 | fanfare([392.0, 311.13, 261.63], [130.81, 155.56, 196.0]) |
| 381 | } |
| 382 | |
| 383 | |
| 384 | |
| 385 | fn 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 | |
| 406 | fn thud(t: f32) -> f32 { |
| 407 | sine(45.0, t) * (-t * 3.0).exp() * env(t, 2.0, 0.003, 0.5) |
| 408 | } |
| 409 | |
| 410 | |
| 411 | fn 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()); |
| 420 | out.extend_from_slice(&1u16.to_le_bytes()); |
| 421 | out.extend_from_slice(&RATE.to_le_bytes()); |
| 422 | out.extend_from_slice(&(RATE * 2).to_le_bytes()); |
| 423 | out.extend_from_slice(&2u16.to_le_bytes()); |
| 424 | out.extend_from_slice(&16u16.to_le_bytes()); |
| 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 | } |