1use std::collections::HashMap;
61use std::sync::Arc;
62use std::sync::atomic::{AtomicU32, Ordering};
63use std::time::Duration;
64
65use bevy::audio::{AddAudioSource, AudioPlugin, Sample as RodioSample, Source as RodioSource};
66use bevy::prelude::*;
67use bevy::reflect::TypePath;
68
69use crate::world::{VoxelBroken, VoxelPlaced};
70
71#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum SfxEvent {
80 Mining,
83 MiningComplete,
86 BlockPlace,
89 ItemPickup,
91 HotbarScroll,
93 PauseOpen,
95 PauseClose,
97 Footstep(u8),
102 Custom(String),
106}
107
108impl SfxEvent {
109 pub fn key(&self) -> String {
112 match self {
113 SfxEvent::Mining => "Mining".to_string(),
114 SfxEvent::MiningComplete => "MiningComplete".to_string(),
115 SfxEvent::BlockPlace => "BlockPlace".to_string(),
116 SfxEvent::ItemPickup => "ItemPickup".to_string(),
117 SfxEvent::HotbarScroll => "HotbarScroll".to_string(),
118 SfxEvent::PauseOpen => "PauseOpen".to_string(),
119 SfxEvent::PauseClose => "PauseClose".to_string(),
120 SfxEvent::Footstep(surface) => format!("Footstep:{surface}"),
121 SfxEvent::Custom(s) => format!("Custom:{s}"),
122 }
123 }
124}
125
126#[derive(Message, Debug, Clone)]
134pub struct SfxRequest {
135 pub event: SfxEvent,
137 pub position: Option<Vec3>,
144}
145
146#[derive(Message, Debug, Clone)]
185#[non_exhaustive]
186pub struct PitchedSfxRequest {
187 pub event: SfxEvent,
189 pub position: Option<Vec3>,
192 pub pitch: f32,
197}
198
199impl PitchedSfxRequest {
200 pub const MIN_PITCH: f32 = 0.1;
202 pub const MAX_PITCH: f32 = 8.0;
204
205 pub fn new(event: SfxEvent, pitch: f32) -> Self {
207 Self {
208 event,
209 position: None,
210 pitch,
211 }
212 }
213
214 pub fn at(mut self, position: Vec3) -> Self {
216 self.position = Some(position);
217 self
218 }
219
220 pub fn effective_pitch(&self) -> f32 {
227 if self.pitch.is_finite() && self.pitch > 0.0 {
228 self.pitch.clamp(Self::MIN_PITCH, Self::MAX_PITCH)
229 } else {
230 1.0
231 }
232 }
233}
234
235#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
297#[non_exhaustive]
298pub struct SfxFilter {
299 pub low_pass_hz: Option<f32>,
305}
306
307impl SfxFilter {
308 pub const NONE: Self = Self { low_pass_hz: None };
310
311 pub const MIN_LOW_PASS_HZ: f32 = 20.0;
313 pub const MAX_LOW_PASS_HZ: f32 = 20_000.0;
315
316 pub const fn low_pass(cutoff_hz: f32) -> Self {
318 Self {
319 low_pass_hz: Some(cutoff_hz),
320 }
321 }
322
323 pub fn effective_low_pass_hz(&self) -> Option<f32> {
331 let hz = self.low_pass_hz?;
332 if hz.is_finite() && hz > 0.0 {
333 Some(hz.clamp(Self::MIN_LOW_PASS_HZ, Self::MAX_LOW_PASS_HZ))
334 } else {
335 None
336 }
337 }
338
339 pub fn is_active(&self) -> bool {
341 self.effective_low_pass_hz().is_some()
342 }
343}
344
345#[derive(Resource, Debug, Clone)]
371pub struct SfxConfig {
372 pub sounds: HashMap<String, Vec<String>>,
377 pub volume: f32,
383}
384
385impl SfxConfig {
386 pub fn new() -> Self {
388 Self {
389 sounds: HashMap::new(),
390 volume: 1.0,
391 }
392 }
393
394 pub fn register(&mut self, event: SfxEvent, paths: Vec<&str>) {
399 self.sounds.insert(
400 event.key(),
401 paths.into_iter().map(|p| p.to_string()).collect(),
402 );
403 }
404
405 pub fn get_paths(&self, event: &SfxEvent) -> Option<&Vec<String>> {
407 self.sounds.get(&event.key())
408 }
409
410 pub fn pick_path(&self, event: &SfxEvent, seed: u64) -> Option<&str> {
415 let paths = self.get_paths(event)?;
416 if paths.is_empty() {
417 return None;
418 }
419 let index = (seed % paths.len() as u64) as usize;
420 Some(paths[index].as_str())
421 }
422}
423
424impl Default for SfxConfig {
425 fn default() -> Self {
426 Self::new()
427 }
428}
429
430pub fn mining_sfx_system(
439 mut broken_reader: MessageReader<VoxelBroken>,
440 mut sfx_writer: MessageWriter<SfxRequest>,
441) {
442 for broken in broken_reader.read() {
443 sfx_writer.write(SfxRequest {
444 event: SfxEvent::MiningComplete,
445 position: Some(broken.world_pos),
446 });
447 }
448}
449
450pub fn placement_sfx_system(
457 mut placed_reader: MessageReader<VoxelPlaced>,
458 mut sfx_writer: MessageWriter<SfxRequest>,
459) {
460 for placed in placed_reader.read() {
461 sfx_writer.write(SfxRequest {
462 event: SfxEvent::BlockPlace,
463 position: Some(placed.world_pos),
464 });
465 }
466}
467
468pub struct SfxPlugin;
491
492impl Plugin for SfxPlugin {
493 fn build(&self, app: &mut App) {
494 app.init_resource::<SfxConfig>();
495 app.add_message::<SfxRequest>();
496 app.add_message::<PitchedSfxRequest>();
497 app.add_systems(Update, (mining_sfx_system, placement_sfx_system));
498 }
499}
500
501#[derive(Resource, Default)]
506struct SfxCounter(HashMap<String, u64>);
507
508pub struct DefaultAudioPlugin;
557
558impl Plugin for DefaultAudioPlugin {
559 fn build(&self, app: &mut App) {
560 app.init_resource::<SfxCounter>();
561 app.init_resource::<SfxFilter>();
562 app.add_message::<PitchedSfxRequest>();
563 app.add_systems(Update, play_sfx_system);
564 }
565
566 fn finish(&self, app: &mut App) {
571 if app.is_plugin_added::<AudioPlugin>() && app.world().contains_resource::<AssetServer>() {
572 app.add_audio_source::<LowPassSfx>();
573 install_low_pass_backend(app);
574 }
575 }
576}
577
578fn install_low_pass_backend(app: &mut App) {
581 app.init_resource::<SfxFilterShared>()
582 .init_resource::<LowPassSfxCache>()
583 .add_systems(
584 Update,
585 (
586 sync_sfx_filter_system.before(play_sfx_system),
587 resolve_low_pass_sfx_system.after(play_sfx_system),
588 ),
589 );
590}
591
592fn play_sfx_system(
593 mut sfx_reader: MessageReader<SfxRequest>,
594 mut pitched_reader: MessageReader<PitchedSfxRequest>,
595 config: Res<SfxConfig>,
596 asset_server: Res<AssetServer>,
597 mut counter: ResMut<SfxCounter>,
598 (filter, low_pass_backend): (Option<Res<SfxFilter>>, Option<Res<SfxFilterShared>>),
599 mut commands: Commands,
600) {
601 let low_pass = low_pass_backend.is_some() && filter.is_some_and(|filter| filter.is_active());
602
603 let plain = sfx_reader
604 .read()
605 .map(|request| (&request.event, request.position, 1.0_f32));
606 let pitched = pitched_reader
607 .read()
608 .map(|request| (&request.event, request.position, request.effective_pitch()));
609
610 for (event, position, speed) in plain.chain(pitched) {
611 let seed = {
612 let c = counter.0.entry(event.key()).or_insert(0);
613 let s = *c;
614 *c = c.wrapping_add(1);
615 s
616 };
617 let Some(path) = config.pick_path(event, seed).map(|p| p.to_owned()) else {
618 continue;
619 };
620 let source: Handle<AudioSource> = asset_server.load(path);
621 let mut settings = PlaybackSettings::ONCE;
622 settings.volume = bevy::audio::Volume::Linear(config.volume);
623 settings.speed = speed;
624 let mut entity = if low_pass {
625 commands.spawn((PendingLowPassSfx(source), settings))
626 } else {
627 commands.spawn((AudioPlayer(source), settings))
628 };
629 if let Some(pos) = position {
630 entity.insert(Transform::from_translation(pos));
631 }
632 }
633}
634
635#[derive(Resource, Default)]
641struct SfxFilterShared(Arc<AtomicU32>);
642
643#[derive(Resource, Default)]
646struct LowPassSfxCache(HashMap<AssetId<AudioSource>, (Handle<AudioSource>, Handle<LowPassSfx>)>);
647
648#[derive(Component)]
650struct PendingLowPassSfx(Handle<AudioSource>);
651
652#[derive(Asset, TypePath)]
654struct LowPassSfx {
655 source: AudioSource,
656 cutoff: Arc<AtomicU32>,
657}
658
659impl Decodable for LowPassSfx {
660 type DecoderItem = f32;
661 type Decoder = LowPassSource<<AudioSource as Decodable>::Decoder>;
662
663 fn decoder(&self) -> Self::Decoder {
664 LowPassSource::new(self.source.decoder(), self.cutoff.clone())
665 }
666}
667
668fn sync_sfx_filter_system(filter: Option<Res<SfxFilter>>, shared: Res<SfxFilterShared>) {
669 let cutoff_hz = filter
670 .and_then(|filter| filter.effective_low_pass_hz())
671 .unwrap_or(0.0);
672 shared.0.store(cutoff_hz.to_bits(), Ordering::Relaxed);
673}
674
675fn resolve_low_pass_sfx_system(
676 pending: Query<(Entity, &PendingLowPassSfx)>,
677 sources: Res<Assets<AudioSource>>,
678 mut filtered: ResMut<Assets<LowPassSfx>>,
679 asset_server: Res<AssetServer>,
680 shared: Res<SfxFilterShared>,
681 mut cache: ResMut<LowPassSfxCache>,
682 mut commands: Commands,
683) {
684 for (entity, pending) in &pending {
685 let id = pending.0.id();
686 if let Some(source) = sources.get(id) {
687 let handle = match cache.0.get(&id) {
688 Some((_, handle)) => handle.clone(),
689 None => {
690 let handle = filtered.add(LowPassSfx {
691 source: source.clone(),
692 cutoff: shared.0.clone(),
693 });
694 cache.0.insert(id, (pending.0.clone(), handle.clone()));
695 handle
696 }
697 };
698 commands
699 .entity(entity)
700 .insert(AudioPlayer::<LowPassSfx>(handle))
701 .remove::<PendingLowPassSfx>();
702 } else if asset_server.load_state(id).is_failed() {
703 commands.entity(entity).despawn();
704 }
705 }
706}
707
708#[derive(Debug, Clone, Copy, PartialEq)]
710struct LowPassCoefficients {
711 b0: f32,
712 b1: f32,
713 b2: f32,
714 a1: f32,
715 a2: f32,
716}
717
718impl LowPassCoefficients {
719 fn new(cutoff_hz: f32, sample_rate: u32) -> Option<Self> {
722 if !cutoff_hz.is_finite() || cutoff_hz <= 0.0 || sample_rate == 0 {
723 return None;
724 }
725 let sample_rate = sample_rate as f32;
726 if cutoff_hz >= sample_rate * 0.45 {
727 return None;
728 }
729 let w0 = std::f32::consts::TAU * cutoff_hz / sample_rate;
730 let (sin, cos) = w0.sin_cos();
731 let alpha = sin / (2.0 * std::f32::consts::FRAC_1_SQRT_2);
732 let a0 = 1.0 + alpha;
733 Some(Self {
734 b0: (1.0 - cos) * 0.5 / a0,
735 b1: (1.0 - cos) / a0,
736 b2: (1.0 - cos) * 0.5 / a0,
737 a1: -2.0 * cos / a0,
738 a2: (1.0 - alpha) / a0,
739 })
740 }
741}
742
743#[derive(Debug, Clone, Copy, Default)]
745struct LowPassHistory {
746 x1: f32,
747 x2: f32,
748 y1: f32,
749 y2: f32,
750}
751
752impl LowPassHistory {
753 fn process(&mut self, coefficients: Option<LowPassCoefficients>, input: f32) -> f32 {
757 let x = if input.is_finite() { input } else { 0.0 };
758 let filtered = coefficients.map(|c| {
759 let y = c.b0 * x + c.b1 * self.x1 + c.b2 * self.x2 - c.a1 * self.y1 - c.a2 * self.y2;
760 if y.is_finite() { y.clamp(-1.0, 1.0) } else { x }
761 });
762 let y = filtered.unwrap_or(x);
763 self.x2 = self.x1;
764 self.x1 = x;
765 self.y2 = self.y1;
766 self.y1 = y;
767 filtered.unwrap_or(input)
768 }
769}
770
771struct LowPassSource<S> {
774 inner: S,
775 cutoff: Arc<AtomicU32>,
776 cutoff_bits: u32,
777 sample_rate: u32,
778 coefficients: Option<LowPassCoefficients>,
779 history: Vec<LowPassHistory>,
780 channel: usize,
781}
782
783impl<S> LowPassSource<S>
784where
785 S: RodioSource,
786 S::Item: RodioSample,
787{
788 fn new(inner: S, cutoff: Arc<AtomicU32>) -> Self {
789 Self {
790 inner,
791 cutoff,
792 cutoff_bits: 0,
793 sample_rate: 0,
794 coefficients: None,
795 history: Vec::new(),
796 channel: 0,
797 }
798 }
799}
800
801impl<S> Iterator for LowPassSource<S>
802where
803 S: RodioSource,
804 S::Item: RodioSample,
805{
806 type Item = f32;
807
808 fn next(&mut self) -> Option<f32> {
809 let channels = usize::from(self.inner.channels().max(1));
810 let sample_rate = self.inner.sample_rate();
811 let sample = RodioSample::to_f32(self.inner.next()?);
812
813 if self.history.len() != channels {
814 self.history.clear();
815 self.history.resize(channels, LowPassHistory::default());
816 self.channel = 0;
817 }
818 let cutoff_bits = self.cutoff.load(Ordering::Relaxed);
819 if cutoff_bits != self.cutoff_bits || sample_rate != self.sample_rate {
820 self.cutoff_bits = cutoff_bits;
821 self.sample_rate = sample_rate;
822 self.coefficients = LowPassCoefficients::new(f32::from_bits(cutoff_bits), sample_rate);
823 }
824
825 let channel = self.channel;
826 self.channel = (channel + 1) % channels;
827 let coefficients = self.coefficients;
828 Some(self.history[channel].process(coefficients, sample))
829 }
830
831 fn size_hint(&self) -> (usize, Option<usize>) {
832 self.inner.size_hint()
833 }
834}
835
836impl<S> RodioSource for LowPassSource<S>
837where
838 S: RodioSource,
839 S::Item: RodioSample,
840{
841 fn current_frame_len(&self) -> Option<usize> {
842 self.inner.current_frame_len()
843 }
844
845 fn channels(&self) -> u16 {
846 self.inner.channels()
847 }
848
849 fn sample_rate(&self) -> u32 {
850 self.inner.sample_rate()
851 }
852
853 fn total_duration(&self) -> Option<Duration> {
854 self.inner.total_duration()
855 }
856}
857
858#[cfg(test)]
861mod tests {
862 use super::*;
863
864 fn config_with_paths() -> SfxConfig {
865 let mut cfg = SfxConfig::new();
866 cfg.register(
867 SfxEvent::BlockPlace,
868 vec![
869 "sounds/place1.ogg",
870 "sounds/place2.ogg",
871 "sounds/place3.ogg",
872 ],
873 );
874 cfg
875 }
876
877 #[test]
878 fn test_sfx_config_pick_deterministic() {
879 let cfg = config_with_paths();
880 let first = cfg.pick_path(&SfxEvent::BlockPlace, 0);
881 let second = cfg.pick_path(&SfxEvent::BlockPlace, 0);
882 assert_eq!(first, second, "same seed must always produce the same path");
883 }
884
885 #[test]
886 fn test_sfx_config_pick_wraps() {
887 let cfg = config_with_paths();
888 let path = cfg.pick_path(&SfxEvent::BlockPlace, 5);
890 assert!(
891 path.is_some(),
892 "seed > paths.len() must still return a valid path"
893 );
894 assert_eq!(path.unwrap(), "sounds/place3.ogg");
895 }
896
897 #[test]
898 fn test_sfx_config_returns_none_for_unregistered_event() {
899 let cfg = SfxConfig::new();
900 assert!(cfg.pick_path(&SfxEvent::Mining, 0).is_none());
901 }
902
903 #[test]
904 fn test_sfx_config_get_paths() {
905 let cfg = config_with_paths();
906 let paths = cfg.get_paths(&SfxEvent::BlockPlace).unwrap();
907 assert_eq!(paths.len(), 3);
908 }
909
910 #[test]
911 fn test_sfx_event_key_custom() {
912 let event = SfxEvent::Custom("footstep".to_string());
913 assert_eq!(event.key(), "Custom:footstep");
914 }
915
916 #[test]
919 fn pitched_request_builder_sets_fields() {
920 let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5);
921 assert_eq!(request.event, SfxEvent::ItemPickup);
922 assert_eq!(request.position, None);
923 assert_eq!(request.effective_pitch(), 1.5);
924
925 let positioned = request.at(Vec3::new(1.0, 2.0, 3.0));
926 assert_eq!(positioned.position, Some(Vec3::new(1.0, 2.0, 3.0)));
927 }
928
929 #[test]
930 fn invalid_pitch_plays_at_normal_speed() {
931 for pitch in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -0.0, -2.0] {
932 let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch);
933 assert_eq!(request.effective_pitch(), 1.0, "pitch {pitch}");
934 }
935 }
936
937 #[test]
938 fn extreme_pitch_is_clamped() {
939 let low = PitchedSfxRequest::new(SfxEvent::ItemPickup, 0.0001);
940 let high = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1000.0);
941 assert_eq!(low.effective_pitch(), PitchedSfxRequest::MIN_PITCH);
942 assert_eq!(high.effective_pitch(), PitchedSfxRequest::MAX_PITCH);
943 }
944
945 #[test]
946 fn filter_is_off_by_default() {
947 assert_eq!(SfxFilter::default(), SfxFilter::NONE);
948 assert_eq!(SfxFilter::default().effective_low_pass_hz(), None);
949 assert!(!SfxFilter::default().is_active());
950 }
951
952 #[test]
953 fn invalid_cutoff_disables_the_filter() {
954 for hz in [
955 f32::NAN,
956 f32::INFINITY,
957 f32::NEG_INFINITY,
958 0.0,
959 -0.0,
960 -500.0,
961 ] {
962 let filter = SfxFilter::low_pass(hz);
963 assert_eq!(filter.effective_low_pass_hz(), None, "cutoff {hz}");
964 assert!(!filter.is_active(), "cutoff {hz}");
965 }
966 }
967
968 #[test]
969 fn valid_cutoff_is_kept_and_clamped() {
970 assert_eq!(
971 SfxFilter::low_pass(800.0).effective_low_pass_hz(),
972 Some(800.0)
973 );
974 assert_eq!(
975 SfxFilter::low_pass(1.0).effective_low_pass_hz(),
976 Some(SfxFilter::MIN_LOW_PASS_HZ)
977 );
978 assert_eq!(
979 SfxFilter::low_pass(1.0e9).effective_low_pass_hz(),
980 Some(SfxFilter::MAX_LOW_PASS_HZ)
981 );
982 }
983
984 fn headless_app() -> App {
989 let mut app = App::new();
990 app.add_plugins((MinimalPlugins, AssetPlugin::default()));
991 app.init_asset::<AudioSource>();
992 app.add_message::<SfxRequest>();
993 let mut config = SfxConfig::new();
994 config.register(SfxEvent::ItemPickup, vec!["sounds/pickup.ogg"]);
995 config.volume = 0.5;
996 app.insert_resource(config);
997 app.add_plugins(DefaultAudioPlugin);
998 app
999 }
1000
1001 fn headless_app_with_low_pass() -> App {
1004 let mut app = headless_app();
1005 app.init_asset::<LowPassSfx>();
1006 install_low_pass_backend(&mut app);
1007 app
1008 }
1009
1010 struct Spawned {
1011 settings: PlaybackSettings,
1012 plain: bool,
1013 pending: bool,
1014 filtered: bool,
1015 translation: Option<Vec3>,
1016 }
1017
1018 fn spawned_sounds(app: &mut App) -> Vec<Spawned> {
1019 let world = app.world_mut();
1020 let mut query = world.query::<(
1021 &PlaybackSettings,
1022 Has<AudioPlayer<AudioSource>>,
1023 Has<PendingLowPassSfx>,
1024 Has<AudioPlayer<LowPassSfx>>,
1025 Option<&Transform>,
1026 )>();
1027 query
1028 .iter(world)
1029 .map(|(settings, plain, pending, filtered, transform)| Spawned {
1030 settings: *settings,
1031 plain,
1032 pending,
1033 filtered,
1034 translation: transform.map(|transform| transform.translation),
1035 })
1036 .collect()
1037 }
1038
1039 fn shared_cutoff(app: &App) -> f32 {
1040 f32::from_bits(
1041 app.world()
1042 .resource::<SfxFilterShared>()
1043 .0
1044 .load(Ordering::Relaxed),
1045 )
1046 }
1047
1048 #[test]
1049 fn sfx_plugin_registers_pitched_requests() {
1050 let mut app = App::new();
1051 app.add_message::<VoxelBroken>();
1052 app.add_message::<VoxelPlaced>();
1053 app.add_plugins(SfxPlugin);
1054 assert!(
1055 app.world()
1056 .contains_resource::<bevy::ecs::message::Messages<PitchedSfxRequest>>()
1057 );
1058 }
1059
1060 #[test]
1061 fn plain_request_plays_with_unchanged_settings() {
1062 let mut app = headless_app_with_low_pass();
1063 assert_eq!(*app.world().resource::<SfxFilter>(), SfxFilter::NONE);
1064
1065 app.world_mut().write_message(SfxRequest {
1066 event: SfxEvent::ItemPickup,
1067 position: Some(Vec3::new(4.0, 5.0, 6.0)),
1068 });
1069 app.update();
1070
1071 let sounds = spawned_sounds(&mut app);
1072 assert_eq!(sounds.len(), 1);
1073 let sound = &sounds[0];
1074 assert!(sound.plain && !sound.pending && !sound.filtered);
1075 assert_eq!(sound.settings.speed, 1.0);
1076 assert_eq!(sound.settings.volume, bevy::audio::Volume::Linear(0.5));
1077 assert!(matches!(
1078 sound.settings.mode,
1079 bevy::audio::PlaybackMode::Once
1080 ));
1081 assert!(!sound.settings.spatial);
1082 assert_eq!(sound.translation, Some(Vec3::new(4.0, 5.0, 6.0)));
1083 }
1084
1085 #[test]
1086 fn pitched_request_sets_playback_speed() {
1087 let mut app = headless_app();
1088 app.world_mut()
1089 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5));
1090 app.world_mut()
1091 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, f32::NAN).at(Vec3::X));
1092 app.update();
1093
1094 let sounds = spawned_sounds(&mut app);
1095 assert_eq!(sounds.len(), 2);
1096 let pitched = sounds
1097 .iter()
1098 .find(|sound| sound.translation.is_none())
1099 .expect("the request without a position");
1100 let invalid = sounds
1101 .iter()
1102 .find(|sound| sound.translation == Some(Vec3::X))
1103 .expect("the request with a position");
1104 assert!(pitched.plain);
1105 assert_eq!(pitched.settings.speed, 1.5);
1106 assert_eq!(pitched.settings.volume, bevy::audio::Volume::Linear(0.5));
1107 assert!(invalid.plain);
1108 assert_eq!(invalid.settings.speed, 1.0);
1109 }
1110
1111 #[test]
1112 fn pitched_request_for_unregistered_event_plays_nothing() {
1113 let mut app = headless_app();
1114 app.world_mut()
1115 .write_message(PitchedSfxRequest::new(SfxEvent::Mining, 1.5));
1116 app.update();
1117 assert!(spawned_sounds(&mut app).is_empty());
1118 }
1119
1120 #[test]
1121 fn active_filter_holds_the_sound_for_the_low_pass_path() {
1122 let mut app = headless_app_with_low_pass();
1123 app.insert_resource(SfxFilter::low_pass(800.0));
1124 app.world_mut()
1125 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 2.0).at(Vec3::Y));
1126 app.update();
1127
1128 let sounds = spawned_sounds(&mut app);
1131 assert_eq!(sounds.len(), 1);
1132 let sound = &sounds[0];
1133 assert!(!sound.plain && !sound.filtered);
1134 assert!(sound.pending);
1135 assert_eq!(sound.settings.speed, 2.0);
1136 assert_eq!(sound.translation, Some(Vec3::Y));
1137 assert_eq!(shared_cutoff(&app), 800.0);
1138 }
1139
1140 #[test]
1141 fn filtered_sound_whose_source_fails_to_load_is_despawned() {
1142 let mut app = headless_app_with_low_pass();
1143 app.insert_resource(SfxFilter::low_pass(800.0));
1144 app.world_mut()
1145 .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.0));
1146 app.update();
1147 assert_eq!(spawned_sounds(&mut app).len(), 1);
1148
1149 for _ in 0..500 {
1151 if spawned_sounds(&mut app).is_empty() {
1152 break;
1153 }
1154 std::thread::sleep(Duration::from_millis(10));
1155 app.update();
1156 }
1157 assert!(
1158 spawned_sounds(&mut app).is_empty(),
1159 "a sound that can never be decoded must not wait forever"
1160 );
1161 }
1162
1163 #[test]
1164 fn loaded_source_is_played_through_the_filtered_asset() {
1165 let mut app = headless_app_with_low_pass();
1166 let bytes: Arc<[u8]> = Arc::from(vec![1_u8, 2, 3]);
1167 let source = app
1168 .world_mut()
1169 .resource_mut::<Assets<AudioSource>>()
1170 .add(AudioSource {
1171 bytes: bytes.clone(),
1172 });
1173 let settings = PlaybackSettings::ONCE.with_speed(1.5);
1174 let first = app
1175 .world_mut()
1176 .spawn((PendingLowPassSfx(source.clone()), settings))
1177 .id();
1178 let second = app
1179 .world_mut()
1180 .spawn((PendingLowPassSfx(source.clone()), settings))
1181 .id();
1182 app.update();
1183
1184 let sounds = spawned_sounds(&mut app);
1185 assert_eq!(sounds.len(), 2);
1186 for sound in &sounds {
1187 assert!(sound.filtered && !sound.pending && !sound.plain);
1188 assert_eq!(sound.settings.speed, 1.5);
1189 }
1190
1191 let first_handle = app
1192 .world()
1193 .get::<AudioPlayer<LowPassSfx>>(first)
1194 .expect("filtered player")
1195 .0
1196 .clone();
1197 let second_handle = app
1198 .world()
1199 .get::<AudioPlayer<LowPassSfx>>(second)
1200 .expect("filtered player")
1201 .0
1202 .clone();
1203 assert_eq!(first_handle, second_handle, "one filtered asset per source");
1204
1205 let shared = app.world().resource::<SfxFilterShared>().0.clone();
1206 let filtered = app
1207 .world()
1208 .resource::<Assets<LowPassSfx>>()
1209 .get(&first_handle)
1210 .expect("filtered asset");
1211 assert!(Arc::ptr_eq(&filtered.source.bytes, &bytes));
1212 assert!(Arc::ptr_eq(&filtered.cutoff, &shared));
1213 }
1214
1215 #[test]
1216 fn invalid_cutoff_plays_unfiltered() {
1217 for hz in [f32::NAN, -100.0, 0.0] {
1218 let mut app = headless_app_with_low_pass();
1219 app.insert_resource(SfxFilter::low_pass(hz));
1220 app.world_mut().write_message(SfxRequest {
1221 event: SfxEvent::ItemPickup,
1222 position: None,
1223 });
1224 app.update();
1225
1226 let sounds = spawned_sounds(&mut app);
1227 assert_eq!(sounds.len(), 1, "cutoff {hz}");
1228 assert!(sounds[0].plain && !sounds[0].pending, "cutoff {hz}");
1229 assert_eq!(shared_cutoff(&app), 0.0, "cutoff {hz}");
1230 }
1231 }
1232
1233 #[test]
1234 fn missing_filter_resource_plays_unfiltered() {
1235 let mut app = headless_app_with_low_pass();
1236 app.insert_resource(SfxFilter::low_pass(800.0));
1237 app.update();
1238 assert_eq!(shared_cutoff(&app), 800.0);
1239
1240 app.world_mut().remove_resource::<SfxFilter>();
1241 app.world_mut().write_message(SfxRequest {
1242 event: SfxEvent::ItemPickup,
1243 position: None,
1244 });
1245 app.update();
1246
1247 let sounds = spawned_sounds(&mut app);
1248 assert_eq!(sounds.len(), 1);
1249 assert!(sounds[0].plain && !sounds[0].pending);
1250 assert_eq!(shared_cutoff(&app), 0.0);
1251 }
1252
1253 #[test]
1254 fn filter_without_audio_backend_plays_unfiltered() {
1255 let mut app = headless_app();
1256 app.insert_resource(SfxFilter::low_pass(800.0));
1257 app.finish();
1259 app.cleanup();
1260 assert!(!app.world().contains_resource::<SfxFilterShared>());
1261
1262 app.world_mut().write_message(SfxRequest {
1263 event: SfxEvent::ItemPickup,
1264 position: None,
1265 });
1266 app.update();
1267
1268 let sounds = spawned_sounds(&mut app);
1269 assert_eq!(sounds.len(), 1);
1270 assert!(sounds[0].plain && !sounds[0].pending);
1271 }
1272
1273 struct TestSignal {
1276 samples: std::vec::IntoIter<f32>,
1277 channels: u16,
1278 sample_rate: u32,
1279 }
1280
1281 impl Iterator for TestSignal {
1282 type Item = f32;
1283
1284 fn next(&mut self) -> Option<f32> {
1285 self.samples.next()
1286 }
1287 }
1288
1289 impl RodioSource for TestSignal {
1290 fn current_frame_len(&self) -> Option<usize> {
1291 None
1292 }
1293
1294 fn channels(&self) -> u16 {
1295 self.channels
1296 }
1297
1298 fn sample_rate(&self) -> u32 {
1299 self.sample_rate
1300 }
1301
1302 fn total_duration(&self) -> Option<Duration> {
1303 None
1304 }
1305 }
1306
1307 const TEST_RATE: u32 = 44_100;
1308
1309 fn sine(frequency_hz: f32, samples: usize) -> Vec<f32> {
1310 (0..samples)
1311 .map(|i| (std::f32::consts::TAU * frequency_hz * i as f32 / TEST_RATE as f32).sin())
1312 .collect()
1313 }
1314
1315 fn cutoff_cell(cutoff_hz: f32) -> Arc<AtomicU32> {
1316 Arc::new(AtomicU32::new(cutoff_hz.to_bits()))
1317 }
1318
1319 fn filter_mono(samples: Vec<f32>, cutoff: Arc<AtomicU32>) -> Vec<f32> {
1320 let signal = TestSignal {
1321 samples: samples.into_iter(),
1322 channels: 1,
1323 sample_rate: TEST_RATE,
1324 };
1325 LowPassSource::new(signal, cutoff).collect()
1326 }
1327
1328 fn settled_rms(samples: &[f32]) -> f32 {
1330 let tail = &samples[samples.len() / 2..];
1331 (tail.iter().map(|sample| sample * sample).sum::<f32>() / tail.len() as f32).sqrt()
1332 }
1333
1334 #[test]
1335 fn low_pass_attenuates_high_frequencies_and_keeps_low_ones() {
1336 let high = sine(8_000.0, 8_820);
1337 let low = sine(100.0, 8_820);
1338 let high_out = filter_mono(high.clone(), cutoff_cell(500.0));
1339 let low_out = filter_mono(low.clone(), cutoff_cell(500.0));
1340
1341 assert_eq!(high_out.len(), high.len());
1342 assert!(
1343 settled_rms(&high_out) < 0.05 * settled_rms(&high),
1344 "8 kHz must be strongly attenuated by a 500 Hz low-pass"
1345 );
1346 let low_ratio = settled_rms(&low_out) / settled_rms(&low);
1347 assert!(
1348 (0.9..=1.05).contains(&low_ratio),
1349 "100 Hz must pass a 500 Hz low-pass, got ratio {low_ratio}"
1350 );
1351 }
1352
1353 #[test]
1354 fn low_pass_without_cutoff_is_the_identity() {
1355 let input = sine(8_000.0, 512);
1356 assert_eq!(filter_mono(input.clone(), cutoff_cell(0.0)), input);
1357 assert_eq!(filter_mono(input.clone(), cutoff_cell(20_000.0)), input);
1359 assert_eq!(filter_mono(input.clone(), cutoff_cell(f32::NAN)), input);
1361 }
1362
1363 #[test]
1364 fn low_pass_follows_cutoff_changes_while_playing() {
1365 let input = sine(8_000.0, 8_820);
1366 let cutoff = cutoff_cell(0.0);
1367 let signal = TestSignal {
1368 samples: input.clone().into_iter(),
1369 channels: 1,
1370 sample_rate: TEST_RATE,
1371 };
1372 let mut source = LowPassSource::new(signal, cutoff.clone());
1373
1374 let unfiltered: Vec<f32> = source.by_ref().take(2_940).collect();
1375 assert_eq!(unfiltered, input[..2_940]);
1376
1377 cutoff.store(500.0_f32.to_bits(), Ordering::Relaxed);
1378 let filtered: Vec<f32> = source.by_ref().take(2_940).collect();
1379 assert!(settled_rms(&filtered) < 0.05 * settled_rms(&input));
1380
1381 cutoff.store(0.0_f32.to_bits(), Ordering::Relaxed);
1382 let restored: Vec<f32> = source.collect();
1383 assert_eq!(restored, input[5_880..]);
1384 }
1385
1386 #[test]
1387 fn low_pass_filters_each_channel_separately() {
1388 let frames = 4_410;
1390 let samples: Vec<f32> = (0..frames)
1391 .flat_map(|frame| [0.5, if frame % 2 == 0 { 1.0 } else { -1.0 }])
1392 .collect();
1393 let signal = TestSignal {
1394 samples: samples.into_iter(),
1395 channels: 2,
1396 sample_rate: TEST_RATE,
1397 };
1398 let output: Vec<f32> = LowPassSource::new(signal, cutoff_cell(500.0)).collect();
1399
1400 assert_eq!(output.len(), frames * 2);
1401 let left = output[output.len() - 2];
1402 let right = output[output.len() - 1];
1403 assert!(
1404 (left - 0.5).abs() < 0.01,
1405 "constant level must pass, got {left}"
1406 );
1407 assert!(
1408 right.abs() < 0.01,
1409 "alternation must be removed, got {right}"
1410 );
1411 }
1412
1413 #[test]
1414 fn low_pass_output_stays_finite_for_bad_input() {
1415 let mut input = sine(100.0, 256);
1416 input[10] = f32::NAN;
1417 input[20] = f32::INFINITY;
1418 let output = filter_mono(input, cutoff_cell(500.0));
1419 assert!(output.iter().all(|sample| sample.is_finite()));
1420 assert!(output.iter().all(|sample| (-1.0..=1.0).contains(sample)));
1421 }
1422
1423 #[test]
1424 fn low_pass_reports_the_inner_format() {
1425 let signal = TestSignal {
1426 samples: vec![0.0; 4].into_iter(),
1427 channels: 2,
1428 sample_rate: 22_050,
1429 };
1430 let source = LowPassSource::new(signal, cutoff_cell(500.0));
1431 assert_eq!(source.channels(), 2);
1432 assert_eq!(source.sample_rate(), 22_050);
1433 assert_eq!(source.current_frame_len(), None);
1434 assert_eq!(source.total_duration(), None);
1435 }
1436
1437 #[test]
1438 fn coefficients_reject_values_that_cannot_filter() {
1439 assert!(LowPassCoefficients::new(500.0, TEST_RATE).is_some());
1440 assert_eq!(LowPassCoefficients::new(500.0, 0), None);
1441 assert_eq!(LowPassCoefficients::new(0.0, TEST_RATE), None);
1442 assert_eq!(LowPassCoefficients::new(-1.0, TEST_RATE), None);
1443 assert_eq!(LowPassCoefficients::new(f32::NAN, TEST_RATE), None);
1444 assert_eq!(LowPassCoefficients::new(f32::INFINITY, TEST_RATE), None);
1445 assert_eq!(LowPassCoefficients::new(22_050.0, TEST_RATE), None);
1446 }
1447}