Skip to main content

voxel_framework/audio/
mod.rs

1//! Decoupled sound-effect system for the voxel framework.
2//!
3//! # Design
4//!
5//! The audio module is deliberately split into two layers:
6//!
7//! * **Request layer** ([`SfxPlugin`]) — framework systems translate world
8//!   events (voxel broken, voxel placed, …) into [`SfxRequest`] messages. The
9//!   convenience [`crate::VoxelPlugin`] includes this layer, so it generates
10//!   requests but does not play them.
11//! * **Playback layer** ([`DefaultAudioPlugin`]) — consumes [`SfxRequest`]
12//!   messages, resolves registered paths through [`SfxConfig`], loads the
13//!   assets, and spawns Bevy [`AudioPlayer`] entities. Games can replace this
14//!   plugin with a custom playback backend.
15//!
16//! `voxel-framework` enables Bevy's `bevy_audio` and `vorbis` features, so the
17//! default playback layer supports Ogg Vorbis assets. The request layer remains
18//! separate so games can omit [`DefaultAudioPlugin`] or supply another handler.
19//!
20//! # Integration
21//!
22//! 1. Add Bevy's asset and audio plugins, normally through `DefaultPlugins`.
23//! 2. Put Ogg Vorbis files in the configured Bevy asset source (normally the
24//!    `assets/` directory) and populate [`SfxConfig`] with their asset-relative
25//!    paths.
26//! 3. Add [`SfxPlugin`] directly, or add [`crate::VoxelPlugin`], to register the
27//!    request channel and framework request-producing systems.
28//! 4. Add [`DefaultAudioPlugin`] for Bevy audio playback, or add a custom plugin
29//!    that consumes [`SfxRequest`] messages. [`crate::VoxelPlugin`] does not add
30//!    a playback plugin.
31//!
32//! # Pitch and low-pass filter
33//!
34//! * [`PitchedSfxRequest`] is a second request message that also carries a
35//!   playback speed. [`SfxRequest`] is unchanged and always plays at normal
36//!   speed.
37//! * [`SfxFilter`] is a resource that low-pass filters ("muffles") the sound
38//!   effects played by [`DefaultAudioPlugin`]. It is off by default.
39//!
40//! ## Example
41//!
42//! ```no_run
43//! use bevy::prelude::*;
44//! use voxel_framework::audio::{DefaultAudioPlugin, SfxConfig, SfxEvent, SfxPlugin};
45//!
46//! fn main() {
47//!     let mut sfx_config = SfxConfig::new();
48//!     sfx_config.register(SfxEvent::BlockPlace, vec!["sounds/place1.ogg"]);
49//!     sfx_config.register(SfxEvent::MiningComplete, vec!["sounds/break1.ogg"]);
50//!
51//!     App::new()
52//!         .add_plugins(DefaultPlugins)
53//!         .insert_resource(sfx_config)
54//!         .add_plugins(SfxPlugin)
55//!         .add_plugins(DefaultAudioPlugin)
56//!         .run();
57//! }
58//! ```
59
60use 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// ─── SfxEvent ─────────────────────────────────────────────────────────────────
72
73/// A category of sound effect that the framework can request.
74///
75/// Each variant corresponds to a distinct gameplay moment.  Framework systems
76/// emit these through [`SfxRequest`]; games map them to asset paths via
77/// [`SfxConfig`].
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub enum SfxEvent {
80    /// Emitted repeatedly while the player is actively mining a voxel (e.g.
81    /// for a continuous digging sound loop or per-hit chip).
82    Mining,
83    /// Emitted once when a voxel is fully broken and removed from the world.
84    /// Triggered by the `VoxelBroken` message.
85    MiningComplete,
86    /// Emitted when a voxel is successfully placed into the world.
87    /// Triggered by the `VoxelPlaced` message.
88    BlockPlace,
89    /// Emitted when the player picks up an item from the world.
90    ItemPickup,
91    /// Emitted when the player scrolls the hotbar slot selection.
92    HotbarScroll,
93    /// Emitted when the pause menu is opened.
94    PauseOpen,
95    /// Emitted when the pause menu is closed.
96    PauseClose,
97    /// Emitted on each footstep when the player moves while grounded.
98    ///
99    /// The inner value is the byte representation of the voxel type underfoot,
100    /// allowing games to map different surface types to different sounds.
101    Footstep(u8),
102    /// Escape hatch for game-specific sounds not covered by the framework
103    /// variants.  The inner string is an arbitrary identifier chosen by the
104    /// game and must match the key used in [`SfxConfig`].
105    Custom(String),
106}
107
108impl SfxEvent {
109    /// Returns a stable string key for this event used as the `HashMap` key in
110    /// [`SfxConfig`].
111    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// ─── SfxRequest ───────────────────────────────────────────────────────────────
127
128/// A request for a sound effect to be played, emitted by framework systems.
129///
130/// [`SfxPlugin`] adds systems that produce these messages in response to world
131/// events.  A playback plugin (e.g. [`DefaultAudioPlugin`] or a custom one)
132/// reads them and drives the audio backend.
133#[derive(Message, Debug, Clone)]
134pub struct SfxRequest {
135    /// The sound effect category to play.
136    pub event: SfxEvent,
137    /// World-space position for spatial (3-D) audio, or `None` for a 2-D / UI
138    /// sound that has no position.
139    ///
140    /// When `Some`, the playback system may attenuate volume and apply panning
141    /// based on the listener's position.  When `None`, the sound should be
142    /// played at a fixed volume regardless of the camera position.
143    pub position: Option<Vec3>,
144}
145
146// ─── PitchedSfxRequest ────────────────────────────────────────────────────────
147
148/// A request for a sound effect played at a chosen pitch.
149///
150/// This is the pitched counterpart of [`SfxRequest`]: the same event and
151/// optional position, plus a playback-speed multiplier. It is a separate
152/// message so that [`SfxRequest`] keeps its two fields; code that builds or
153/// reads [`SfxRequest`] is unaffected. The framework itself never writes this
154/// message.
155///
156/// [`SfxPlugin`] and [`DefaultAudioPlugin`] both register the message.
157/// [`DefaultAudioPlugin`] plays it exactly like an [`SfxRequest`] for the same
158/// event (same [`SfxConfig`] paths, same round-robin counter, same volume),
159/// with the playback speed set to [`PitchedSfxRequest::effective_pitch`]. A
160/// custom playback backend that wants pitched sounds must read this message
161/// too.
162///
163/// Pitch is implemented as playback speed: `2.0` plays one octave higher and
164/// in half the time, `0.5` one octave lower and twice as long. Pitch cannot be
165/// changed without changing the duration.
166///
167/// The struct is `#[non_exhaustive]`: build it with [`PitchedSfxRequest::new`]
168/// and [`PitchedSfxRequest::at`]. The fields can still be read and assigned.
169///
170/// # Examples
171///
172/// A sound that rises in pitch on consecutive uses:
173///
174/// ```no_run
175/// use bevy::prelude::*;
176/// use voxel_framework::prelude::*;
177///
178/// fn rising_sound(mut streak: Local<u32>, mut sfx: MessageWriter<PitchedSfxRequest>) {
179///     let pitch = 1.0 + 0.05 * (*streak).min(12) as f32;
180///     *streak += 1;
181///     sfx.write(PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch));
182/// }
183/// ```
184#[derive(Message, Debug, Clone)]
185#[non_exhaustive]
186pub struct PitchedSfxRequest {
187    /// The sound effect category to play.
188    pub event: SfxEvent,
189    /// World-space position, or `None` for a sound without a position. Same
190    /// meaning as [`SfxRequest::position`].
191    pub position: Option<Vec3>,
192    /// Playback-speed multiplier; `1.0` is the unmodified sound.
193    ///
194    /// The stored value is not validated. Playback uses
195    /// [`PitchedSfxRequest::effective_pitch`].
196    pub pitch: f32,
197}
198
199impl PitchedSfxRequest {
200    /// Lowest playback speed [`PitchedSfxRequest::effective_pitch`] returns.
201    pub const MIN_PITCH: f32 = 0.1;
202    /// Highest playback speed [`PitchedSfxRequest::effective_pitch`] returns.
203    pub const MAX_PITCH: f32 = 8.0;
204
205    /// Creates a request without a position.
206    pub fn new(event: SfxEvent, pitch: f32) -> Self {
207        Self {
208            event,
209            position: None,
210            pitch,
211        }
212    }
213
214    /// Sets the world-space position of the sound.
215    pub fn at(mut self, position: Vec3) -> Self {
216        self.position = Some(position);
217        self
218    }
219
220    /// The playback speed a backend should use for this request.
221    ///
222    /// A pitch that is NaN, infinite, zero or negative yields `1.0`, so an
223    /// invalid value plays the sound unmodified instead of silencing or
224    /// breaking it. Any other value is clamped to
225    /// [`PitchedSfxRequest::MIN_PITCH`]..=[`PitchedSfxRequest::MAX_PITCH`].
226    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// ─── SfxFilter ────────────────────────────────────────────────────────────────
236
237/// Global low-pass filter ("muffle") for sound effects.
238///
239/// [`DefaultAudioPlugin`] initializes this resource with the filter off, which
240/// leaves playback exactly as it is without the resource. Set
241/// [`SfxFilter::low_pass_hz`] to muffle sound effects, for example while a
242/// game state is active, and set it back to `None` to return to normal.
243///
244/// # What is filtered
245///
246/// * Only sounds played by [`DefaultAudioPlugin`] from [`SfxRequest`] and
247///   [`PitchedSfxRequest`] messages. Audio the game spawns itself is not
248///   touched, and a custom playback backend has to read this resource itself.
249/// * The filter is chosen when a sound starts. A sound that starts while the
250///   filter is on follows later changes of the cutoff, including being turned
251///   off, while it plays. A sound that starts while the filter is off stays
252///   unfiltered until it ends. Sound effects are short, so in practice the
253///   change is heard on the next sounds.
254/// * The filter needs Bevy's `AudioPlugin` and `AssetPlugin` (both part of
255///   `DefaultPlugins`). Without them the resource is ignored and sounds are
256///   requested unfiltered.
257///
258/// The filter is a second-order (12 dB per octave) low-pass applied per
259/// channel. It is implemented in this crate on top of Bevy's audio decoding;
260/// no other effects (reverb, high-pass, per-sound filters) are provided.
261///
262/// While the filter is on, a sound's entity carries an `AudioPlayer` of a
263/// private filtered asset type instead of `AudioPlayer<AudioSource>`.
264/// `PlaybackSettings`, the optional `Transform` and Bevy's `AudioSink` are
265/// the same in both cases.
266///
267/// The struct is `#[non_exhaustive]`: create it with [`SfxFilter::NONE`],
268/// [`SfxFilter::low_pass`] or `default()`, then assign fields.
269///
270/// # Examples
271///
272/// ```no_run
273/// use bevy::prelude::*;
274/// use voxel_framework::prelude::*;
275///
276/// fn muffle(mut filter: ResMut<SfxFilter>) {
277///     filter.low_pass_hz = Some(700.0);
278/// }
279///
280/// fn unmuffle(mut filter: ResMut<SfxFilter>) {
281///     *filter = SfxFilter::NONE;
282/// }
283///
284/// fn pitched_sound(mut sfx: MessageWriter<PitchedSfxRequest>) {
285///     sfx.write(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.25));
286/// }
287///
288/// App::new()
289///     .add_plugins(DefaultPlugins)
290///     .add_plugins(SfxPlugin)
291///     .add_plugins(DefaultAudioPlugin)
292///     .add_systems(Startup, muffle)
293///     .add_systems(Update, (pitched_sound, unmuffle))
294///     .run();
295/// ```
296#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
297#[non_exhaustive]
298pub struct SfxFilter {
299    /// Cutoff frequency of the low-pass filter in hertz, or `None` for no
300    /// filter. Lower values sound more muffled.
301    ///
302    /// The stored value is not validated. Playback uses
303    /// [`SfxFilter::effective_low_pass_hz`].
304    pub low_pass_hz: Option<f32>,
305}
306
307impl SfxFilter {
308    /// No filter. Same as `SfxFilter::default()`.
309    pub const NONE: Self = Self { low_pass_hz: None };
310
311    /// Lowest cutoff [`SfxFilter::effective_low_pass_hz`] returns, in hertz.
312    pub const MIN_LOW_PASS_HZ: f32 = 20.0;
313    /// Highest cutoff [`SfxFilter::effective_low_pass_hz`] returns, in hertz.
314    pub const MAX_LOW_PASS_HZ: f32 = 20_000.0;
315
316    /// A low-pass filter with the given cutoff frequency in hertz.
317    pub const fn low_pass(cutoff_hz: f32) -> Self {
318        Self {
319            low_pass_hz: Some(cutoff_hz),
320        }
321    }
322
323    /// The cutoff a backend should apply, or `None` when nothing is filtered.
324    ///
325    /// A cutoff that is NaN, infinite, zero or negative yields `None`, so an
326    /// invalid value never silences sound effects. Any other value is clamped
327    /// to [`SfxFilter::MIN_LOW_PASS_HZ`]..=[`SfxFilter::MAX_LOW_PASS_HZ`].
328    /// During playback, a cutoff at or above 45 % of a sound's sample rate is
329    /// skipped for that sound, because nothing audible would be removed.
330    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    /// Whether [`SfxFilter::effective_low_pass_hz`] is `Some`.
340    pub fn is_active(&self) -> bool {
341        self.effective_low_pass_hz().is_some()
342    }
343}
344
345// ─── SfxConfig ────────────────────────────────────────────────────────────────
346
347/// Maps [`SfxEvent`] categories to lists of asset paths.
348///
349/// Each category can hold multiple paths so the game can register variant
350/// sounds (e.g. several digging sounds) and play them in round-robin order.
351/// A specific path is selected deterministically by `pick_path` using a
352/// caller-supplied seed, making the selection reproducible across frames.
353///
354/// `SfxConfig` is registered as a `Resource` by [`SfxPlugin`]; insert your
355/// populated instance before adding the plugin, or mutate the resource after
356/// `App::run` via a startup system.
357///
358/// # Examples
359///
360/// ```no_run
361/// use voxel_framework::audio::{SfxConfig, SfxEvent};
362///
363/// let mut config = SfxConfig::new();
364/// config.register(SfxEvent::BlockPlace, vec!["sounds/place1.ogg", "sounds/place2.ogg"]);
365/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 0), Some("sounds/place1.ogg"));
366/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 1), Some("sounds/place2.ogg"));
367/// // Seeds wrap around: seed 2 → index 0 again for a two-entry list.
368/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 2), Some("sounds/place1.ogg"));
369/// ```
370#[derive(Resource, Debug, Clone)]
371pub struct SfxConfig {
372    /// Maps the string key of each [`SfxEvent`] to its registered asset paths.
373    ///
374    /// Keys are produced by [`SfxEvent::key`].  Prefer using
375    /// [`SfxConfig::register`] rather than inserting into this map directly.
376    pub sounds: HashMap<String, Vec<String>>,
377    /// Master playback volume applied to all sounds, in the range `[0.0, 1.0]`.
378    ///
379    /// `0.0` is silent; `1.0` is full volume.  Default: `1.0`.  Values outside
380    /// `[0.0, 1.0]` are not clamped by the framework — the audio backend
381    /// determines how they are handled.
382    pub volume: f32,
383}
384
385impl SfxConfig {
386    /// Creates an empty [`SfxConfig`] with master volume `1.0`.
387    pub fn new() -> Self {
388        Self {
389            sounds: HashMap::new(),
390            volume: 1.0,
391        }
392    }
393
394    /// Registers one or more asset paths for the given event category.
395    ///
396    /// Calling this a second time for the same event **replaces** the
397    /// existing path list.
398    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    /// Returns all registered paths for an event, or `None` if unregistered.
406    pub fn get_paths(&self, event: &SfxEvent) -> Option<&Vec<String>> {
407        self.sounds.get(&event.key())
408    }
409
410    /// Deterministically picks one path for `event` using `seed`.
411    ///
412    /// The selection is `paths[seed % paths.len()]`, so the same seed always
413    /// produces the same result. Returns `None` if the event has no paths.
414    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
430// ─── Systems ──────────────────────────────────────────────────────────────────
431
432/// Translates `VoxelBroken` messages into [`SfxRequest`] messages with event
433/// [`SfxEvent::MiningComplete`].
434///
435/// The request carries the broken voxel's world position so that a spatial
436/// audio handler can place the sound in 3-D space.  This system is added by
437/// [`SfxPlugin`] and runs in the [`Update`] schedule.
438pub 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
450/// Translates `VoxelPlaced` messages into [`SfxRequest`] messages with event
451/// [`SfxEvent::BlockPlace`].
452///
453/// The request carries the placed voxel's world position so that a spatial
454/// audio handler can place the sound in 3-D space.  This system is added by
455/// [`SfxPlugin`] and runs in the [`Update`] schedule.
456pub 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
468// ─── SfxPlugin ────────────────────────────────────────────────────────────────
469
470/// Core plugin for the framework sound-effect system.
471///
472/// # What it registers
473///
474/// * [`SfxConfig`] — initialized as a default resource (all categories empty,
475///   volume `1.0`).  Insert a pre-populated instance before adding this plugin
476///   to override the defaults.
477/// * The [`SfxRequest`] message channel so framework systems can emit requests
478///   and game systems can read them.
479/// * The [`PitchedSfxRequest`] message channel, which only the game writes.
480/// * [`mining_sfx_system`] and [`placement_sfx_system`] in the [`Update`]
481///   schedule.
482///
483/// # What it does NOT do
484///
485/// `SfxPlugin` never loads audio assets, never creates audio entities, and
486/// never calls into any audio backend. Actual playback is the responsibility
487/// of a separate plugin — either [`DefaultAudioPlugin`], which uses Bevy audio,
488/// or a custom plugin that reads [`SfxRequest`] events. [`crate::VoxelPlugin`]
489/// includes `SfxPlugin`, but it does not include a playback plugin.
490pub 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// ─── DefaultAudioPlugin ───────────────────────────────────────────────────────
502
503/// A round-robin counter per SFX key so successive identical events cycle
504/// through registered variant paths rather than always picking the same one.
505#[derive(Resource, Default)]
506struct SfxCounter(HashMap<String, u64>);
507
508/// Ready-to-use audio plugin that plays [`SfxRequest`] and
509/// [`PitchedSfxRequest`] messages via Bevy's built-in `bevy_audio` backend.
510///
511/// For each incoming request, this plugin:
512/// 1. Resolves the event key through [`SfxConfig::pick_path`] (round-robin
513///    across registered variants).
514/// 2. Loads the asset with `AssetServer::load`.
515/// 3. Spawns an `(AudioPlayer, PlaybackSettings::ONCE)` entity that Bevy's
516///    audio system plays once. The entity is not despawned when the sound
517///    ends. The volume comes from [`SfxConfig::volume`] and, for a
518///    [`PitchedSfxRequest`], the speed comes from
519///    [`PitchedSfxRequest::effective_pitch`].
520///
521/// The plugin also initializes [`SfxFilter`] (off by default). While that
522/// filter is on, new sounds are played through a low-pass filter; see
523/// [`SfxFilter`] for what is and is not filtered.
524///
525/// # Setup
526///
527/// Register asset paths with [`SfxConfig`] before adding the plugin, or
528/// populate them in a startup system:
529///
530/// ```no_run
531/// use bevy::prelude::*;
532/// use voxel_framework::audio::{DefaultAudioPlugin, SfxConfig, SfxEvent, SfxPlugin};
533///
534/// App::new()
535///     .add_plugins(DefaultPlugins)
536///     .add_plugins(SfxPlugin)
537///     .add_plugins(DefaultAudioPlugin)
538///     .add_systems(Startup, |mut cfg: ResMut<SfxConfig>| {
539///         cfg.register(SfxEvent::MiningComplete, vec!["sounds/break.ogg"]);
540///         cfg.register(SfxEvent::BlockPlace,     vec!["sounds/place.ogg"]);
541///     })
542///     .run();
543/// ```
544///
545/// # Missing files
546///
547/// If an asset path is not found on disk, Bevy logs a warning and skips
548/// playback — no panic, no crash.
549///
550/// # Spatial audio
551///
552/// When the [`SfxRequest::position`] field is `Some`, the plugin attaches a
553/// [`SpatialListener`]-compatible [`Transform`] to the audio entity so Bevy
554/// can attenuate volume by distance.  Requires a [`SpatialListener`] on the
555/// camera/player entity.
556pub 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    /// Registers the low-pass playback path once every plugin is built, so
567    /// the order in which this plugin and Bevy's plugins are added does not
568    /// matter. Without Bevy's audio and asset plugins nothing is registered
569    /// and [`SfxFilter`] has no effect.
570    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
578/// Adds the resources and systems of the low-pass playback path. The
579/// `LowPassSfx` asset type must already be registered.
580fn 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// ─── Low-pass playback path ───────────────────────────────────────────────────
636
637/// The cutoff every playing filtered sound reads: the bits of an `f32` in
638/// hertz, where `0.0` means "no filter". Its presence also tells
639/// `play_sfx_system` that the low-pass path is installed.
640#[derive(Resource, Default)]
641struct SfxFilterShared(Arc<AtomicU32>);
642
643/// Filtered asset per source, so repeated sounds reuse one asset. The source
644/// handle is kept so the source's id stays valid for as long as the entry.
645#[derive(Resource, Default)]
646struct LowPassSfxCache(HashMap<AssetId<AudioSource>, (Handle<AudioSource>, Handle<LowPassSfx>)>);
647
648/// A sound waiting for its source to load before it can be played filtered.
649#[derive(Component)]
650struct PendingLowPassSfx(Handle<AudioSource>);
651
652/// An [`AudioSource`] decoded through `LowPassSource`.
653#[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/// Normalized biquad coefficients of a second-order Butterworth low-pass.
709#[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    /// Returns `None` when nothing should be filtered: an invalid cutoff or
720    /// sample rate, or a cutoff at or above 45 % of the sample rate.
721    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/// The last two inputs and outputs of one channel.
744#[derive(Debug, Clone, Copy, Default)]
745struct LowPassHistory {
746    x1: f32,
747    x2: f32,
748    y1: f32,
749    y2: f32,
750}
751
752impl LowPassHistory {
753    /// Filters one sample. Without coefficients the sample is returned as it
754    /// came, but the history keeps running so that switching the filter on in
755    /// the middle of a sound does not start from silence.
756    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
771/// Low-pass filters `inner`, reading the cutoff from a value shared with
772/// [`SfxFilter`] so it can change while the sound plays.
773struct 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// ─── Tests ────────────────────────────────────────────────────────────────────
859
860#[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        // 3 paths; seed 5 → 5 % 3 = 2 → "sounds/place3.ogg"
889        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    // ── Pitch and filter values ──────────────────────────────────────────────
917
918    #[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    // ── Playback entities ────────────────────────────────────────────────────
985
986    /// An app that can run the playback systems without an audio device:
987    /// Bevy's `AudioPlugin` is not added, so nothing is ever decoded or played.
988    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    /// Installs what `DefaultAudioPlugin::finish` installs next to Bevy's
1002    /// `AudioPlugin`, minus Bevy's own playback systems.
1003    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        // The path does not exist, so the source never loads and the sound
1129        // must not fall back to unfiltered playback.
1130        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        // The load fails on a background task; give it a bounded time.
1150        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        // `finish` must not register the low-pass path without `AudioPlugin`.
1258        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    // ── Low-pass signal processing ───────────────────────────────────────────
1274
1275    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    /// Root mean square of the second half, after the filter has settled.
1329    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        // A cutoff the sample rate cannot represent is skipped as well.
1358        assert_eq!(filter_mono(input.clone(), cutoff_cell(20_000.0)), input);
1359        // The cell is trusted to hold a sanitized value, but must not break.
1360        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        // Left: a constant level. Right: the fastest possible alternation.
1389        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}