1use super::{Clip, Sound, VoiceParams};
4use ferravex_math::Vec3;
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub struct AcousticProfile {
7 pub gain: f32,
8 pub low_pass_hz: f32,
9}
10impl Default for AcousticProfile {
11 fn default() -> Self {
12 Self {
13 gain: 1.,
14 low_pass_hz: 24000.,
15 }
16 }
17}
18impl AcousticProfile {
19 pub fn valid(self) -> bool {
20 self.gain.is_finite()
21 && (0. ..=1.).contains(&self.gain)
22 && self.low_pass_hz.is_finite()
23 && (80. ..=24000.).contains(&self.low_pass_hz)
24 }
25 pub fn apply(self, mut voice: VoiceParams) -> VoiceParams {
26 voice.gain *= self.gain;
27 voice.low_pass_hz = voice.low_pass_hz.min(self.low_pass_hz);
28 voice
29 }
30}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum AcousticTransitionError {
41 InvalidProfile,
43 InvalidDuration,
45 InvalidDelta,
47}
48impl std::fmt::Display for AcousticTransitionError {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 f.write_str(match self {
51 Self::InvalidProfile => "acoustic gain must be in 0..=1 and cutoff in 80..=24000 Hz",
52 Self::InvalidDuration => "acoustic transition duration must be finite and nonnegative",
53 Self::InvalidDelta => "acoustic elapsed time must be finite and nonnegative",
54 })
55 }
56}
57impl std::error::Error for AcousticTransitionError {}
58
59#[derive(Clone, Copy, Debug, PartialEq)]
91pub struct AcousticTransition {
92 start: AcousticProfile,
93 target: AcousticProfile,
94 duration_seconds: f64,
95 elapsed_seconds: f64,
96}
97impl Default for AcousticTransition {
98 fn default() -> Self {
99 let profile = AcousticProfile::default();
100 Self {
101 start: profile,
102 target: profile,
103 duration_seconds: 0.,
104 elapsed_seconds: 0.,
105 }
106 }
107}
108impl AcousticTransition {
109 pub fn new(profile: AcousticProfile) -> Result<Self, AcousticTransitionError> {
121 if !profile.valid() {
122 return Err(AcousticTransitionError::InvalidProfile);
123 }
124 Ok(Self {
125 start: profile,
126 target: profile,
127 duration_seconds: 0.,
128 elapsed_seconds: 0.,
129 })
130 }
131
132 pub fn current(&self) -> AcousticProfile {
134 if !self.is_transitioning() {
135 return self.target;
136 }
137 let fraction = self.elapsed_seconds / self.duration_seconds;
138 let blend = |start: f32, target: f32| {
139 (f64::from(start) + (f64::from(target) - f64::from(start)) * fraction) as f32
140 };
141 AcousticProfile {
142 gain: blend(self.start.gain, self.target.gain),
143 low_pass_hz: blend(self.start.low_pass_hz, self.target.low_pass_hz),
144 }
145 }
146
147 pub fn target(&self) -> AcousticProfile {
149 self.target
150 }
151
152 pub fn is_transitioning(&self) -> bool {
154 self.elapsed_seconds < self.duration_seconds
155 }
156
157 pub fn transition_to(
177 &mut self,
178 target: AcousticProfile,
179 duration_seconds: f64,
180 ) -> Result<(), AcousticTransitionError> {
181 if !target.valid() {
182 return Err(AcousticTransitionError::InvalidProfile);
183 }
184 if !duration_seconds.is_finite() || duration_seconds < 0. {
185 return Err(AcousticTransitionError::InvalidDuration);
186 }
187 if duration_seconds == 0. {
188 return self.reset(target);
189 }
190 if target == self.target {
191 return Ok(());
192 }
193 let start = self.current();
194 if start == target {
195 return self.reset(target);
196 }
197 *self = Self {
198 start,
199 target,
200 duration_seconds,
201 elapsed_seconds: 0.,
202 };
203 Ok(())
204 }
205
206 pub fn advance(
214 &mut self,
215 elapsed_seconds: f64,
216 ) -> Result<AcousticProfile, AcousticTransitionError> {
217 if !elapsed_seconds.is_finite() || elapsed_seconds < 0. {
218 return Err(AcousticTransitionError::InvalidDelta);
219 }
220 if elapsed_seconds >= self.duration_seconds - self.elapsed_seconds {
222 self.elapsed_seconds = self.duration_seconds;
223 } else {
224 self.elapsed_seconds += elapsed_seconds;
225 }
226 Ok(self.current())
227 }
228
229 pub fn reset(&mut self, profile: AcousticProfile) -> Result<(), AcousticTransitionError> {
243 *self = Self::new(profile)?;
244 Ok(())
245 }
246}
247
248#[derive(Clone, Copy, Debug)]
249pub struct AcousticZone {
250 pub min: Vec3,
251 pub max: Vec3,
252 pub feather: f32,
253 pub profile: AcousticProfile,
254}
255pub struct AcousticScene<const N: usize> {
256 zones: [AcousticZone; N],
257}
258impl<const N: usize> AcousticScene<N> {
259 pub fn new(zones: [AcousticZone; N]) -> Option<Self> {
260 if N > 32
261 || zones.iter().any(|z| {
262 !z.min.is_finite()
263 || !z.max.is_finite()
264 || (z.max - z.min).min_element() <= 0.
265 || !z.feather.is_finite()
266 || !(0. ..=1000.).contains(&z.feather)
267 || !z.profile.valid()
268 })
269 {
270 None
271 } else {
272 Some(Self { zones })
273 }
274 }
275 pub fn sample(&self, listener: Vec3, occluded: bool) -> Option<AcousticProfile> {
277 if !listener.is_finite() {
278 return None;
279 }
280 let mut result = AcousticProfile::default();
281 for z in self.zones {
282 let margin = (listener - z.min).min(z.max - listener).min_element();
283 if margin >= 0. {
284 let weight = if z.feather == 0. {
285 1.
286 } else {
287 (margin / z.feather).clamp(0., 1.)
288 };
289 result.gain = result.gain.min(1. + (z.profile.gain - 1.) * weight);
290 result.low_pass_hz = result
291 .low_pass_hz
292 .min(24000. + (z.profile.low_pass_hz - 24000.) * weight);
293 }
294 }
295 if occluded {
296 result.gain *= 0.45;
297 result.low_pass_hz = result.low_pass_hz.min(900.);
298 }
299 Some(result)
300 }
301}
302#[derive(Clone, Copy, Debug)]
303pub struct MusicFrame {
304 pub beat: f32,
305 pub bar_changed: bool,
306 pub gains: [f32; 2],
307}
308#[derive(Clone, Copy, Debug)]
309pub struct MusicConductor {
310 bpm: f64,
311 beat: f64,
312 intensity: f32,
313 layer: f32,
314}
315impl MusicConductor {
316 pub fn new(bpm: u16) -> Option<Self> {
317 if !(40..=240).contains(&bpm) {
318 None
319 } else {
320 Some(Self {
321 bpm: f64::from(bpm),
322 beat: 0.,
323 intensity: 0.,
324 layer: 0.,
325 })
326 }
327 }
328 pub fn update(&mut self, dt: f32, requested: f32) -> Option<MusicFrame> {
329 if !dt.is_finite()
330 || !(0. ..=0.25).contains(&dt)
331 || !requested.is_finite()
332 || !(0. ..=1.).contains(&requested)
333 {
334 return None;
335 }
336 let next = self.beat + f64::from(dt) * self.bpm / 60.;
337 let bar_changed = next >= 4.;
338 self.beat = next % 4.;
339 if bar_changed {
340 self.intensity = requested;
341 }
342 self.layer += (self.intensity - self.layer) * (1. - (-dt * 5.).exp());
343 Some(MusicFrame {
344 beat: self.beat as f32,
345 bar_changed,
346 gains: [0.22, 0.2 * self.layer],
347 })
348 }
349}
350pub fn music_stems(sample_rate: u32, bpm: u16, mut seed: u32) -> Option<[Sound; 2]> {
352 if !(8000..=96000).contains(&sample_rate) || !(40..=240).contains(&bpm) {
353 return None;
354 }
355 seed = seed.max(1);
356 let beat = (f64::from(sample_rate) * 60. / f64::from(bpm)).round() as usize;
357 let frames = beat * 4;
358 let mut bed = Vec::with_capacity(frames);
359 let mut pulse = Vec::with_capacity(frames);
360 for i in 0..frames {
361 let phase = (i % beat) as f32 / beat as f32;
362 let seconds = (i % beat) as f32 / sample_rate as f32;
363 let hz = [110., 130.8128, 146.8324, 98.][i / beat];
364 let env = (std::f32::consts::PI * phase).sin().powi(2);
365 let bass = (std::f32::consts::TAU * hz * seconds).sin() * env * 0.2;
366 seed ^= seed << 13;
367 seed ^= seed >> 17;
368 seed ^= seed << 5;
369 let noise = (seed as f64 / u32::MAX as f64 * 2. - 1.) as f32;
370 let tap = noise * phase.min(0.01) * 100. * (-phase * 28.).exp() * 0.12;
371 bed.push([bass; 2]);
372 pulse.push([tap; 2]);
373 }
374 Some([
375 Sound::new(Clip {
376 sample_rate,
377 samples: bed.into(),
378 })?,
379 Sound::new(Clip {
380 sample_rate,
381 samples: pulse.into(),
382 })?,
383 ])
384}
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 fn muffled() -> AcousticProfile {
390 AcousticProfile {
391 gain: 0.,
392 low_pass_hz: 80.,
393 }
394 }
395
396 fn assert_profile_near(actual: AcousticProfile, expected: AcousticProfile) {
397 assert!((actual.gain - expected.gain).abs() < 1e-6);
398 assert!((actual.low_pass_hz - expected.low_pass_hz).abs() < 0.002);
399 assert!(actual.valid());
400 }
401
402 #[test]
403 fn transition_interpolates_both_controls_and_settles_exactly() {
404 let initial = AcousticProfile::default();
405 let mut transition = AcousticTransition::default();
406 assert_eq!(transition.current(), initial);
407 assert_eq!(transition.target(), initial);
408 assert!(!transition.is_transitioning());
409 transition.transition_to(muffled(), 2.).unwrap();
410 assert!(transition.is_transitioning());
411 assert_eq!(transition.current(), initial);
412 assert_eq!(transition.target(), muffled());
413 assert_eq!(transition.advance(0.).unwrap(), initial);
414 assert_eq!(
415 transition.advance(0.5).unwrap(),
416 AcousticProfile {
417 gain: 0.75,
418 low_pass_hz: 18020.,
419 }
420 );
421 assert_eq!(
422 transition.advance(0.5).unwrap(),
423 AcousticProfile {
424 gain: 0.5,
425 low_pass_hz: 12040.,
426 }
427 );
428 assert_eq!(transition.advance(1.).unwrap(), muffled());
429 assert!(!transition.is_transitioning());
430 let settled = transition;
431 assert_eq!(transition.advance(f64::MAX).unwrap(), muffled());
432 assert_eq!(transition, settled);
433 }
434
435 #[test]
436 fn retargeting_is_continuous_and_repeated_targets_do_not_restart() {
437 let mut transition = AcousticTransition::default();
438 transition.transition_to(muffled(), 1.).unwrap();
439 let partial = transition.advance(0.25).unwrap();
440 let before = transition;
441 transition.transition_to(muffled(), 10.).unwrap();
442 assert_eq!(
443 transition, before,
444 "same target keeps the original timeline"
445 );
446 transition
447 .transition_to(AcousticProfile::default(), 0.5)
448 .unwrap();
449 assert_eq!(transition.current(), partial);
450 assert!(transition.advance(0.25).unwrap().gain > partial.gain);
451 assert_eq!(
452 transition.advance(0.25).unwrap(),
453 AcousticProfile::default()
454 );
455 assert!(!transition.is_transitioning());
456 for _ in 0..4 {
457 transition.transition_to(muffled(), 1.).unwrap();
458 transition.advance(0.25).unwrap();
459 }
460 assert_eq!(transition.current(), muffled());
461 assert!(!transition.is_transitioning());
462 }
463
464 #[test]
465 fn reset_immediate_targets_and_zero_time_have_explicit_semantics() {
466 let mut transition = AcousticTransition::default();
467 transition.transition_to(muffled(), 1.).unwrap();
468 let current = transition.advance(0.25).unwrap();
469 let before = transition;
470 assert_eq!(transition.advance(0.).unwrap(), current);
471 assert_eq!(transition, before);
472
473 transition.transition_to(current, 5.).unwrap();
474 assert_eq!(transition, AcousticTransition::new(current).unwrap());
475 transition.transition_to(muffled(), 1.).unwrap();
476 transition.advance(0.25).unwrap();
477 transition.transition_to(muffled(), 0.).unwrap();
478 assert_eq!(transition, AcousticTransition::new(muffled()).unwrap());
479 transition
480 .transition_to(AcousticProfile::default(), 1.)
481 .unwrap();
482 transition.advance(0.25).unwrap();
483 transition.reset(current).unwrap();
484 assert_eq!(transition, AcousticTransition::new(current).unwrap());
485 assert_eq!(transition.advance(100.).unwrap(), current);
486
487 transition.reset(AcousticProfile::default()).unwrap();
488 assert_eq!(transition, AcousticTransition::default());
489 transition.transition_to(muffled(), 1.).unwrap();
490 assert_eq!(transition.advance(100.).unwrap(), muffled());
491 transition
492 .transition_to(AcousticProfile::default(), 1.)
493 .unwrap();
494 assert_eq!(transition.advance(0.).unwrap(), muffled());
495 assert_eq!(transition.advance(0.5).unwrap().gain, 0.5);
496 }
497
498 #[test]
499 fn invalid_profiles_are_transactional_for_construction_retarget_and_reset() {
500 let mut transition = AcousticTransition::default();
501 transition.transition_to(muffled(), 1.).unwrap();
502 transition.advance(0.25).unwrap();
503 let before = transition;
504 for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 1.1] {
505 let profile = AcousticProfile {
506 gain: invalid,
507 ..AcousticProfile::default()
508 };
509 assert_eq!(
510 AcousticTransition::new(profile),
511 Err(AcousticTransitionError::InvalidProfile)
512 );
513 assert_eq!(
514 transition.transition_to(profile, 1.),
515 Err(AcousticTransitionError::InvalidProfile)
516 );
517 assert_eq!(
518 transition.reset(profile),
519 Err(AcousticTransitionError::InvalidProfile)
520 );
521 assert_eq!(transition, before);
522 }
523 for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 79., 24001.] {
524 let profile = AcousticProfile {
525 low_pass_hz: invalid,
526 ..AcousticProfile::default()
527 };
528 assert_eq!(
529 AcousticTransition::new(profile),
530 Err(AcousticTransitionError::InvalidProfile)
531 );
532 assert_eq!(
533 transition.transition_to(profile, 0.),
534 Err(AcousticTransitionError::InvalidProfile)
535 );
536 assert_eq!(
537 transition.reset(profile),
538 Err(AcousticTransitionError::InvalidProfile)
539 );
540 assert_eq!(transition, before);
541 }
542 assert_eq!(transition.advance(0.75).unwrap(), muffled());
543 }
544
545 #[test]
546 fn invalid_times_are_rejected_even_for_unchanged_or_settled_targets() {
547 let mut active = AcousticTransition::default();
548 active.transition_to(muffled(), 1.).unwrap();
549 active.advance(0.25).unwrap();
550 for mut transition in [active, AcousticTransition::default()] {
551 let before = transition;
552 for invalid in [
553 f64::NAN,
554 f64::INFINITY,
555 f64::NEG_INFINITY,
556 -1.,
557 -f64::MIN_POSITIVE,
558 ] {
559 for target in [transition.target(), transition.current()] {
560 assert_eq!(
561 transition.transition_to(target, invalid),
562 Err(AcousticTransitionError::InvalidDuration)
563 );
564 assert_eq!(transition, before);
565 }
566 assert_eq!(
567 transition.advance(invalid),
568 Err(AcousticTransitionError::InvalidDelta)
569 );
570 assert_eq!(transition, before);
571 }
572 }
573 }
574
575 #[test]
576 fn elapsed_seconds_are_independent_of_sample_rates_and_update_partitioning() {
577 let mut reference = AcousticTransition::default();
578 reference.transition_to(muffled(), 2.).unwrap();
579 let expected = reference.advance(1.).unwrap();
580 for rate in [8000, 44100, 48000, 96000] {
581 for block in [1, 127, 512] {
582 let mut transition = AcousticTransition::default();
583 transition.transition_to(muffled(), 2.).unwrap();
584 let mut remaining = rate;
585 while remaining > 0 {
586 let frames = remaining.min(block);
587 transition
588 .advance(f64::from(frames) / f64::from(rate))
589 .unwrap();
590 remaining -= frames;
591 }
592 assert_profile_near(transition.current(), expected);
593 for _ in 0..480 {
595 transition.advance(50. / 48000.).unwrap();
596 }
597 assert_profile_near(
598 transition.current(),
599 AcousticProfile {
600 gain: 0.25,
601 low_pass_hz: 6060.,
602 },
603 );
604 assert_eq!(transition.advance(1.).unwrap(), muffled());
605 assert!(!transition.is_transitioning());
606 }
607 }
608 }
609
610 #[test]
611 fn extreme_finite_times_and_repeated_reversals_keep_profiles_bounded() {
612 for duration in [f64::from_bits(1), f64::MIN_POSITIVE, 1., f64::MAX] {
613 let mut transition = AcousticTransition::default();
614 transition.transition_to(muffled(), duration).unwrap();
615 assert!(transition.advance(duration * 0.25).unwrap().valid());
616 assert_eq!(transition.advance(duration).unwrap(), muffled());
617 assert!(!transition.is_transitioning());
618 assert!(transition.duration_seconds.is_finite());
619 assert!(transition.elapsed_seconds.is_finite());
620 }
621 let mut transition = AcousticTransition::default();
622 for i in 0..1000 {
623 let previous = transition.current();
624 let target = if i % 2 == 0 {
625 muffled()
626 } else {
627 AcousticProfile::default()
628 };
629 transition.transition_to(target, 0.25).unwrap();
630 assert_eq!(transition.current(), previous);
631 let current = transition.advance(1. / 60.).unwrap();
632 assert!(current.valid());
633 assert!(
634 (previous.gain.min(target.gain)..=previous.gain.max(target.gain))
635 .contains(¤t.gain)
636 );
637 assert!(
638 (previous.low_pass_hz.min(target.low_pass_hz)
639 ..=previous.low_pass_hz.max(target.low_pass_hz))
640 .contains(¤t.low_pass_hz)
641 );
642 }
643 }
644
645 #[test]
646 fn sampled_occlusion_enters_and_clears_gradually_without_changing_authored_values() {
647 let authored = AcousticProfile {
648 gain: 0.8,
649 low_pass_hz: 2500.,
650 };
651 let scene = AcousticScene::new([AcousticZone {
652 min: Vec3::splat(-10.),
653 max: Vec3::splat(10.),
654 feather: 2.,
655 profile: authored,
656 }])
657 .unwrap();
658 let clear = scene.sample(Vec3::ZERO, false).unwrap();
659 assert_eq!(clear, authored);
660 let occluded = scene.sample(Vec3::ZERO, true).unwrap();
661 assert_eq!(occluded.gain, authored.gain * 0.45);
662 assert_eq!(occluded.low_pass_hz, 900.);
663 let mut transition = AcousticTransition::new(clear).unwrap();
664 transition.transition_to(occluded, 0.5).unwrap();
665 let current = transition.advance(0.25).unwrap();
666 assert!(current.gain > occluded.gain && current.gain < clear.gain);
667 assert_eq!(current.low_pass_hz, 1700.);
668 let before = transition;
669 assert!(scene.sample(Vec3::splat(f32::NAN), false).is_none());
670 assert_eq!(transition, before);
671 assert_eq!(transition.advance(0.25).unwrap(), occluded);
672 transition.transition_to(clear, 0.5).unwrap();
673 assert_profile_near(transition.advance(0.25).unwrap(), current);
674 assert_eq!(transition.advance(0.25).unwrap(), clear);
675
676 let voice = VoiceParams {
678 gain: 0.5,
679 low_pass_hz: 500.,
680 bus: super::super::Bus::Ambience,
681 ramp_frames: 37,
682 looping: true,
683 priority: 3,
684 pitch: 1.2,
685 ..Default::default()
686 };
687 assert_eq!(
688 current.apply(voice),
689 VoiceParams {
690 gain: current.gain * voice.gain,
691 ..voice
692 }
693 );
694 assert_eq!(AcousticProfile::default().apply(voice), voice);
695 }
696
697 #[test]
698 fn zones_feather_and_occlusion_is_explicit() {
699 let s = AcousticScene::new([AcousticZone {
700 min: Vec3::splat(-10.),
701 max: Vec3::splat(10.),
702 feather: 2.,
703 profile: AcousticProfile {
704 gain: 0.8,
705 low_pass_hz: 2500.,
706 },
707 }])
708 .unwrap();
709 assert_eq!(
710 s.sample(Vec3::X * 11., false),
711 Some(AcousticProfile::default())
712 );
713 assert_eq!(s.sample(Vec3::ZERO, true).unwrap().low_pass_hz, 900.);
714 assert!(s.sample(Vec3::X * 9., false).unwrap().low_pass_hz > 2500.);
715 }
716 #[test]
717 fn score_waits_for_bar_and_stems_share_length() {
718 let mut c = MusicConductor::new(120).unwrap();
719 for _ in 0..7 {
720 assert_eq!(c.update(0.25, 1.).unwrap().gains[1], 0.);
721 }
722 let f = c.update(0.25, 1.).unwrap();
723 assert!(f.bar_changed && f.gains[1] > 0.);
724 let stems = music_stems(8000, 120, 9).unwrap();
725 assert_eq!(stems[0].clip().samples.len(), stems[1].clip().samples.len());
726 assert!(c.update(f32::NAN, 0.).is_none());
727 }
728}