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/// * The `VoxelBroken` and `VoxelPlaced` message channels its systems read,
481///   so the plugin works in an app without the mining or placement plugins.
482/// * [`mining_sfx_system`] and [`placement_sfx_system`] in the [`Update`]
483///   schedule.
484///
485/// # What it does NOT do
486///
487/// `SfxPlugin` never loads audio assets, never creates audio entities, and
488/// never calls into any audio backend. Actual playback is the responsibility
489/// of a separate plugin — either [`DefaultAudioPlugin`], which uses Bevy audio,
490/// or a custom plugin that reads [`SfxRequest`] events. [`crate::VoxelPlugin`]
491/// includes `SfxPlugin`, but it does not include a playback plugin.
492pub struct SfxPlugin;
493
494impl Plugin for SfxPlugin {
495    fn build(&self, app: &mut App) {
496        app.init_resource::<SfxConfig>();
497        app.add_message::<SfxRequest>();
498        app.add_message::<PitchedSfxRequest>();
499        // The two systems below read these. The mining and placement plugins
500        // register them too, but this plugin must also run without them.
501        app.add_message::<VoxelBroken>();
502        app.add_message::<VoxelPlaced>();
503        app.add_systems(Update, (mining_sfx_system, placement_sfx_system));
504    }
505}
506
507// ─── DefaultAudioPlugin ───────────────────────────────────────────────────────
508
509/// A round-robin counter per SFX key so successive identical events cycle
510/// through registered variant paths rather than always picking the same one.
511#[derive(Resource, Default)]
512struct SfxCounter(HashMap<String, u64>);
513
514/// Ready-to-use audio plugin that plays [`SfxRequest`] and
515/// [`PitchedSfxRequest`] messages via Bevy's built-in `bevy_audio` backend.
516///
517/// For each incoming request, this plugin:
518/// 1. Resolves the event key through [`SfxConfig::pick_path`] (round-robin
519///    across registered variants).
520/// 2. Loads the asset with `AssetServer::load`.
521/// 3. Spawns an `(AudioPlayer, PlaybackSettings::ONCE)` entity that Bevy's
522///    audio system plays once. The entity is not despawned when the sound
523///    ends. The volume comes from [`SfxConfig::volume`] and, for a
524///    [`PitchedSfxRequest`], the speed comes from
525///    [`PitchedSfxRequest::effective_pitch`].
526///
527/// The plugin also initializes [`SfxFilter`] (off by default). While that
528/// filter is on, new sounds are played through a low-pass filter; see
529/// [`SfxFilter`] for what is and is not filtered.
530///
531/// # Setup
532///
533/// Register asset paths with [`SfxConfig`] before adding the plugin, or
534/// populate them in a startup system:
535///
536/// ```no_run
537/// use bevy::prelude::*;
538/// use voxel_framework::audio::{DefaultAudioPlugin, SfxConfig, SfxEvent, SfxPlugin};
539///
540/// App::new()
541///     .add_plugins(DefaultPlugins)
542///     .add_plugins(SfxPlugin)
543///     .add_plugins(DefaultAudioPlugin)
544///     .add_systems(Startup, |mut cfg: ResMut<SfxConfig>| {
545///         cfg.register(SfxEvent::MiningComplete, vec!["sounds/break.ogg"]);
546///         cfg.register(SfxEvent::BlockPlace,     vec!["sounds/place.ogg"]);
547///     })
548///     .run();
549/// ```
550///
551/// # Missing files
552///
553/// If an asset path is not found on disk, Bevy logs a warning and skips
554/// playback — no panic, no crash.
555///
556/// # Spatial audio
557///
558/// When the [`SfxRequest::position`] field is `Some`, the plugin attaches a
559/// [`SpatialListener`]-compatible [`Transform`] to the audio entity so Bevy
560/// can attenuate volume by distance.  Requires a [`SpatialListener`] on the
561/// camera/player entity.
562pub struct DefaultAudioPlugin;
563
564impl Plugin for DefaultAudioPlugin {
565    fn build(&self, app: &mut App) {
566        app.init_resource::<SfxCounter>();
567        app.init_resource::<SfxFilter>();
568        app.add_message::<PitchedSfxRequest>();
569        app.add_systems(Update, play_sfx_system);
570    }
571
572    /// Registers the low-pass playback path once every plugin is built, so
573    /// the order in which this plugin and Bevy's plugins are added does not
574    /// matter. Without Bevy's audio and asset plugins nothing is registered
575    /// and [`SfxFilter`] has no effect.
576    fn finish(&self, app: &mut App) {
577        if app.is_plugin_added::<AudioPlugin>() && app.world().contains_resource::<AssetServer>() {
578            app.add_audio_source::<LowPassSfx>();
579            install_low_pass_backend(app);
580        }
581    }
582}
583
584/// Adds the resources and systems of the low-pass playback path. The
585/// `LowPassSfx` asset type must already be registered.
586fn install_low_pass_backend(app: &mut App) {
587    app.init_resource::<SfxFilterShared>()
588        .init_resource::<LowPassSfxCache>()
589        .add_systems(
590            Update,
591            (
592                sync_sfx_filter_system.before(play_sfx_system),
593                resolve_low_pass_sfx_system.after(play_sfx_system),
594            ),
595        );
596}
597
598fn play_sfx_system(
599    mut sfx_reader: MessageReader<SfxRequest>,
600    mut pitched_reader: MessageReader<PitchedSfxRequest>,
601    config: Res<SfxConfig>,
602    asset_server: Res<AssetServer>,
603    mut counter: ResMut<SfxCounter>,
604    (filter, low_pass_backend): (Option<Res<SfxFilter>>, Option<Res<SfxFilterShared>>),
605    mut commands: Commands,
606) {
607    let low_pass = low_pass_backend.is_some() && filter.is_some_and(|filter| filter.is_active());
608
609    let plain = sfx_reader
610        .read()
611        .map(|request| (&request.event, request.position, 1.0_f32));
612    let pitched = pitched_reader
613        .read()
614        .map(|request| (&request.event, request.position, request.effective_pitch()));
615
616    for (event, position, speed) in plain.chain(pitched) {
617        let seed = {
618            let c = counter.0.entry(event.key()).or_insert(0);
619            let s = *c;
620            *c = c.wrapping_add(1);
621            s
622        };
623        let Some(path) = config.pick_path(event, seed).map(|p| p.to_owned()) else {
624            continue;
625        };
626        let source: Handle<AudioSource> = asset_server.load(path);
627        let mut settings = PlaybackSettings::ONCE;
628        settings.volume = bevy::audio::Volume::Linear(config.volume);
629        settings.speed = speed;
630        let mut entity = if low_pass {
631            commands.spawn((PendingLowPassSfx(source), settings))
632        } else {
633            commands.spawn((AudioPlayer(source), settings))
634        };
635        if let Some(pos) = position {
636            entity.insert(Transform::from_translation(pos));
637        }
638    }
639}
640
641// ─── Low-pass playback path ───────────────────────────────────────────────────
642
643/// The cutoff every playing filtered sound reads: the bits of an `f32` in
644/// hertz, where `0.0` means "no filter". Its presence also tells
645/// `play_sfx_system` that the low-pass path is installed.
646#[derive(Resource, Default)]
647struct SfxFilterShared(Arc<AtomicU32>);
648
649/// Filtered asset per source, so repeated sounds reuse one asset. The source
650/// handle is kept so the source's id stays valid for as long as the entry.
651#[derive(Resource, Default)]
652struct LowPassSfxCache(HashMap<AssetId<AudioSource>, (Handle<AudioSource>, Handle<LowPassSfx>)>);
653
654/// A sound waiting for its source to load before it can be played filtered.
655#[derive(Component)]
656struct PendingLowPassSfx(Handle<AudioSource>);
657
658/// An [`AudioSource`] decoded through `LowPassSource`.
659#[derive(Asset, TypePath)]
660struct LowPassSfx {
661    source: AudioSource,
662    cutoff: Arc<AtomicU32>,
663}
664
665impl Decodable for LowPassSfx {
666    type DecoderItem = f32;
667    type Decoder = LowPassSource<<AudioSource as Decodable>::Decoder>;
668
669    fn decoder(&self) -> Self::Decoder {
670        LowPassSource::new(self.source.decoder(), self.cutoff.clone())
671    }
672}
673
674fn sync_sfx_filter_system(filter: Option<Res<SfxFilter>>, shared: Res<SfxFilterShared>) {
675    let cutoff_hz = filter
676        .and_then(|filter| filter.effective_low_pass_hz())
677        .unwrap_or(0.0);
678    shared.0.store(cutoff_hz.to_bits(), Ordering::Relaxed);
679}
680
681fn resolve_low_pass_sfx_system(
682    pending: Query<(Entity, &PendingLowPassSfx)>,
683    sources: Res<Assets<AudioSource>>,
684    mut filtered: ResMut<Assets<LowPassSfx>>,
685    asset_server: Res<AssetServer>,
686    shared: Res<SfxFilterShared>,
687    mut cache: ResMut<LowPassSfxCache>,
688    mut commands: Commands,
689) {
690    for (entity, pending) in &pending {
691        let id = pending.0.id();
692        if let Some(source) = sources.get(id) {
693            let handle = match cache.0.get(&id) {
694                Some((_, handle)) => handle.clone(),
695                None => {
696                    let handle = filtered.add(LowPassSfx {
697                        source: source.clone(),
698                        cutoff: shared.0.clone(),
699                    });
700                    cache.0.insert(id, (pending.0.clone(), handle.clone()));
701                    handle
702                }
703            };
704            commands
705                .entity(entity)
706                .insert(AudioPlayer::<LowPassSfx>(handle))
707                .remove::<PendingLowPassSfx>();
708        } else if asset_server.load_state(id).is_failed() {
709            commands.entity(entity).despawn();
710        }
711    }
712}
713
714/// Normalized biquad coefficients of a second-order Butterworth low-pass.
715#[derive(Debug, Clone, Copy, PartialEq)]
716struct LowPassCoefficients {
717    b0: f32,
718    b1: f32,
719    b2: f32,
720    a1: f32,
721    a2: f32,
722}
723
724impl LowPassCoefficients {
725    /// Returns `None` when nothing should be filtered: an invalid cutoff or
726    /// sample rate, or a cutoff at or above 45 % of the sample rate.
727    fn new(cutoff_hz: f32, sample_rate: u32) -> Option<Self> {
728        if !cutoff_hz.is_finite() || cutoff_hz <= 0.0 || sample_rate == 0 {
729            return None;
730        }
731        let sample_rate = sample_rate as f32;
732        if cutoff_hz >= sample_rate * 0.45 {
733            return None;
734        }
735        let w0 = std::f32::consts::TAU * cutoff_hz / sample_rate;
736        let (sin, cos) = w0.sin_cos();
737        let alpha = sin / (2.0 * std::f32::consts::FRAC_1_SQRT_2);
738        let a0 = 1.0 + alpha;
739        Some(Self {
740            b0: (1.0 - cos) * 0.5 / a0,
741            b1: (1.0 - cos) / a0,
742            b2: (1.0 - cos) * 0.5 / a0,
743            a1: -2.0 * cos / a0,
744            a2: (1.0 - alpha) / a0,
745        })
746    }
747}
748
749/// The last two inputs and outputs of one channel.
750#[derive(Debug, Clone, Copy, Default)]
751struct LowPassHistory {
752    x1: f32,
753    x2: f32,
754    y1: f32,
755    y2: f32,
756}
757
758impl LowPassHistory {
759    /// Filters one sample. Without coefficients the sample is returned as it
760    /// came, but the history keeps running so that switching the filter on in
761    /// the middle of a sound does not start from silence.
762    fn process(&mut self, coefficients: Option<LowPassCoefficients>, input: f32) -> f32 {
763        let x = if input.is_finite() { input } else { 0.0 };
764        let filtered = coefficients.map(|c| {
765            let y = c.b0 * x + c.b1 * self.x1 + c.b2 * self.x2 - c.a1 * self.y1 - c.a2 * self.y2;
766            if y.is_finite() { y.clamp(-1.0, 1.0) } else { x }
767        });
768        let y = filtered.unwrap_or(x);
769        self.x2 = self.x1;
770        self.x1 = x;
771        self.y2 = self.y1;
772        self.y1 = y;
773        filtered.unwrap_or(input)
774    }
775}
776
777/// Low-pass filters `inner`, reading the cutoff from a value shared with
778/// [`SfxFilter`] so it can change while the sound plays.
779struct LowPassSource<S> {
780    inner: S,
781    cutoff: Arc<AtomicU32>,
782    cutoff_bits: u32,
783    sample_rate: u32,
784    coefficients: Option<LowPassCoefficients>,
785    history: Vec<LowPassHistory>,
786    channel: usize,
787}
788
789impl<S> LowPassSource<S>
790where
791    S: RodioSource,
792    S::Item: RodioSample,
793{
794    fn new(inner: S, cutoff: Arc<AtomicU32>) -> Self {
795        Self {
796            inner,
797            cutoff,
798            cutoff_bits: 0,
799            sample_rate: 0,
800            coefficients: None,
801            history: Vec::new(),
802            channel: 0,
803        }
804    }
805}
806
807impl<S> Iterator for LowPassSource<S>
808where
809    S: RodioSource,
810    S::Item: RodioSample,
811{
812    type Item = f32;
813
814    fn next(&mut self) -> Option<f32> {
815        let channels = usize::from(self.inner.channels().max(1));
816        let sample_rate = self.inner.sample_rate();
817        let sample = RodioSample::to_f32(self.inner.next()?);
818
819        if self.history.len() != channels {
820            self.history.clear();
821            self.history.resize(channels, LowPassHistory::default());
822            self.channel = 0;
823        }
824        let cutoff_bits = self.cutoff.load(Ordering::Relaxed);
825        if cutoff_bits != self.cutoff_bits || sample_rate != self.sample_rate {
826            self.cutoff_bits = cutoff_bits;
827            self.sample_rate = sample_rate;
828            self.coefficients = LowPassCoefficients::new(f32::from_bits(cutoff_bits), sample_rate);
829        }
830
831        let channel = self.channel;
832        self.channel = (channel + 1) % channels;
833        let coefficients = self.coefficients;
834        Some(self.history[channel].process(coefficients, sample))
835    }
836
837    fn size_hint(&self) -> (usize, Option<usize>) {
838        self.inner.size_hint()
839    }
840}
841
842impl<S> RodioSource for LowPassSource<S>
843where
844    S: RodioSource,
845    S::Item: RodioSample,
846{
847    fn current_frame_len(&self) -> Option<usize> {
848        self.inner.current_frame_len()
849    }
850
851    fn channels(&self) -> u16 {
852        self.inner.channels()
853    }
854
855    fn sample_rate(&self) -> u32 {
856        self.inner.sample_rate()
857    }
858
859    fn total_duration(&self) -> Option<Duration> {
860        self.inner.total_duration()
861    }
862}
863
864// ─── Tests ────────────────────────────────────────────────────────────────────
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    fn config_with_paths() -> SfxConfig {
871        let mut cfg = SfxConfig::new();
872        cfg.register(
873            SfxEvent::BlockPlace,
874            vec![
875                "sounds/place1.ogg",
876                "sounds/place2.ogg",
877                "sounds/place3.ogg",
878            ],
879        );
880        cfg
881    }
882
883    #[test]
884    fn test_sfx_config_pick_deterministic() {
885        let cfg = config_with_paths();
886        let first = cfg.pick_path(&SfxEvent::BlockPlace, 0);
887        let second = cfg.pick_path(&SfxEvent::BlockPlace, 0);
888        assert_eq!(first, second, "same seed must always produce the same path");
889    }
890
891    #[test]
892    fn sfx_plugin_runs_without_the_mining_and_placement_plugins() {
893        let mut app = App::new();
894        app.add_plugins(MinimalPlugins).add_plugins(SfxPlugin);
895
896        // Its systems read `VoxelBroken` and `VoxelPlaced`; an unregistered
897        // message makes the first update panic.
898        app.update();
899    }
900
901    #[test]
902    fn sfx_plugin_turns_world_messages_into_requests_on_its_own() {
903        let mut app = App::new();
904        app.add_plugins(MinimalPlugins).add_plugins(SfxPlugin);
905
906        app.world_mut().write_message(VoxelPlaced {
907            chunk_coord: IVec3::ZERO,
908            local: (0, 0, 0),
909            world_pos: Vec3::new(1.0, 2.0, 3.0),
910            face_normal: IVec3::Y,
911        });
912        app.update();
913
914        let requests = app.world().resource::<Messages<SfxRequest>>();
915        let mut cursor = requests.get_cursor();
916        let read: Vec<_> = cursor.read(requests).collect();
917        assert_eq!(read.len(), 1);
918        assert_eq!(read[0].event, SfxEvent::BlockPlace);
919        assert_eq!(read[0].position, Some(Vec3::new(1.0, 2.0, 3.0)));
920    }
921
922    #[test]
923    fn test_sfx_config_pick_wraps() {
924        let cfg = config_with_paths();
925        // 3 paths; seed 5 → 5 % 3 = 2 → "sounds/place3.ogg"
926        let path = cfg.pick_path(&SfxEvent::BlockPlace, 5);
927        assert!(
928            path.is_some(),
929            "seed > paths.len() must still return a valid path"
930        );
931        assert_eq!(path.unwrap(), "sounds/place3.ogg");
932    }
933
934    #[test]
935    fn test_sfx_config_returns_none_for_unregistered_event() {
936        let cfg = SfxConfig::new();
937        assert!(cfg.pick_path(&SfxEvent::Mining, 0).is_none());
938    }
939
940    #[test]
941    fn test_sfx_config_get_paths() {
942        let cfg = config_with_paths();
943        let paths = cfg.get_paths(&SfxEvent::BlockPlace).unwrap();
944        assert_eq!(paths.len(), 3);
945    }
946
947    #[test]
948    fn test_sfx_event_key_custom() {
949        let event = SfxEvent::Custom("footstep".to_string());
950        assert_eq!(event.key(), "Custom:footstep");
951    }
952
953    // ── Pitch and filter values ──────────────────────────────────────────────
954
955    #[test]
956    fn pitched_request_builder_sets_fields() {
957        let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5);
958        assert_eq!(request.event, SfxEvent::ItemPickup);
959        assert_eq!(request.position, None);
960        assert_eq!(request.effective_pitch(), 1.5);
961
962        let positioned = request.at(Vec3::new(1.0, 2.0, 3.0));
963        assert_eq!(positioned.position, Some(Vec3::new(1.0, 2.0, 3.0)));
964    }
965
966    #[test]
967    fn invalid_pitch_plays_at_normal_speed() {
968        for pitch in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -0.0, -2.0] {
969            let request = PitchedSfxRequest::new(SfxEvent::ItemPickup, pitch);
970            assert_eq!(request.effective_pitch(), 1.0, "pitch {pitch}");
971        }
972    }
973
974    #[test]
975    fn extreme_pitch_is_clamped() {
976        let low = PitchedSfxRequest::new(SfxEvent::ItemPickup, 0.0001);
977        let high = PitchedSfxRequest::new(SfxEvent::ItemPickup, 1000.0);
978        assert_eq!(low.effective_pitch(), PitchedSfxRequest::MIN_PITCH);
979        assert_eq!(high.effective_pitch(), PitchedSfxRequest::MAX_PITCH);
980    }
981
982    #[test]
983    fn filter_is_off_by_default() {
984        assert_eq!(SfxFilter::default(), SfxFilter::NONE);
985        assert_eq!(SfxFilter::default().effective_low_pass_hz(), None);
986        assert!(!SfxFilter::default().is_active());
987    }
988
989    #[test]
990    fn invalid_cutoff_disables_the_filter() {
991        for hz in [
992            f32::NAN,
993            f32::INFINITY,
994            f32::NEG_INFINITY,
995            0.0,
996            -0.0,
997            -500.0,
998        ] {
999            let filter = SfxFilter::low_pass(hz);
1000            assert_eq!(filter.effective_low_pass_hz(), None, "cutoff {hz}");
1001            assert!(!filter.is_active(), "cutoff {hz}");
1002        }
1003    }
1004
1005    #[test]
1006    fn valid_cutoff_is_kept_and_clamped() {
1007        assert_eq!(
1008            SfxFilter::low_pass(800.0).effective_low_pass_hz(),
1009            Some(800.0)
1010        );
1011        assert_eq!(
1012            SfxFilter::low_pass(1.0).effective_low_pass_hz(),
1013            Some(SfxFilter::MIN_LOW_PASS_HZ)
1014        );
1015        assert_eq!(
1016            SfxFilter::low_pass(1.0e9).effective_low_pass_hz(),
1017            Some(SfxFilter::MAX_LOW_PASS_HZ)
1018        );
1019    }
1020
1021    // ── Playback entities ────────────────────────────────────────────────────
1022
1023    /// An app that can run the playback systems without an audio device:
1024    /// Bevy's `AudioPlugin` is not added, so nothing is ever decoded or played.
1025    fn headless_app() -> App {
1026        let mut app = App::new();
1027        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
1028        app.init_asset::<AudioSource>();
1029        app.add_message::<SfxRequest>();
1030        let mut config = SfxConfig::new();
1031        config.register(SfxEvent::ItemPickup, vec!["sounds/pickup.ogg"]);
1032        config.volume = 0.5;
1033        app.insert_resource(config);
1034        app.add_plugins(DefaultAudioPlugin);
1035        app
1036    }
1037
1038    /// Installs what `DefaultAudioPlugin::finish` installs next to Bevy's
1039    /// `AudioPlugin`, minus Bevy's own playback systems.
1040    fn headless_app_with_low_pass() -> App {
1041        let mut app = headless_app();
1042        app.init_asset::<LowPassSfx>();
1043        install_low_pass_backend(&mut app);
1044        app
1045    }
1046
1047    struct Spawned {
1048        settings: PlaybackSettings,
1049        plain: bool,
1050        pending: bool,
1051        filtered: bool,
1052        translation: Option<Vec3>,
1053    }
1054
1055    fn spawned_sounds(app: &mut App) -> Vec<Spawned> {
1056        let world = app.world_mut();
1057        let mut query = world.query::<(
1058            &PlaybackSettings,
1059            Has<AudioPlayer<AudioSource>>,
1060            Has<PendingLowPassSfx>,
1061            Has<AudioPlayer<LowPassSfx>>,
1062            Option<&Transform>,
1063        )>();
1064        query
1065            .iter(world)
1066            .map(|(settings, plain, pending, filtered, transform)| Spawned {
1067                settings: *settings,
1068                plain,
1069                pending,
1070                filtered,
1071                translation: transform.map(|transform| transform.translation),
1072            })
1073            .collect()
1074    }
1075
1076    fn shared_cutoff(app: &App) -> f32 {
1077        f32::from_bits(
1078            app.world()
1079                .resource::<SfxFilterShared>()
1080                .0
1081                .load(Ordering::Relaxed),
1082        )
1083    }
1084
1085    #[test]
1086    fn sfx_plugin_registers_pitched_requests() {
1087        let mut app = App::new();
1088        app.add_message::<VoxelBroken>();
1089        app.add_message::<VoxelPlaced>();
1090        app.add_plugins(SfxPlugin);
1091        assert!(
1092            app.world()
1093                .contains_resource::<bevy::ecs::message::Messages<PitchedSfxRequest>>()
1094        );
1095    }
1096
1097    #[test]
1098    fn plain_request_plays_with_unchanged_settings() {
1099        let mut app = headless_app_with_low_pass();
1100        assert_eq!(*app.world().resource::<SfxFilter>(), SfxFilter::NONE);
1101
1102        app.world_mut().write_message(SfxRequest {
1103            event: SfxEvent::ItemPickup,
1104            position: Some(Vec3::new(4.0, 5.0, 6.0)),
1105        });
1106        app.update();
1107
1108        let sounds = spawned_sounds(&mut app);
1109        assert_eq!(sounds.len(), 1);
1110        let sound = &sounds[0];
1111        assert!(sound.plain && !sound.pending && !sound.filtered);
1112        assert_eq!(sound.settings.speed, 1.0);
1113        assert_eq!(sound.settings.volume, bevy::audio::Volume::Linear(0.5));
1114        assert!(matches!(
1115            sound.settings.mode,
1116            bevy::audio::PlaybackMode::Once
1117        ));
1118        assert!(!sound.settings.spatial);
1119        assert_eq!(sound.translation, Some(Vec3::new(4.0, 5.0, 6.0)));
1120    }
1121
1122    #[test]
1123    fn pitched_request_sets_playback_speed() {
1124        let mut app = headless_app();
1125        app.world_mut()
1126            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.5));
1127        app.world_mut()
1128            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, f32::NAN).at(Vec3::X));
1129        app.update();
1130
1131        let sounds = spawned_sounds(&mut app);
1132        assert_eq!(sounds.len(), 2);
1133        let pitched = sounds
1134            .iter()
1135            .find(|sound| sound.translation.is_none())
1136            .expect("the request without a position");
1137        let invalid = sounds
1138            .iter()
1139            .find(|sound| sound.translation == Some(Vec3::X))
1140            .expect("the request with a position");
1141        assert!(pitched.plain);
1142        assert_eq!(pitched.settings.speed, 1.5);
1143        assert_eq!(pitched.settings.volume, bevy::audio::Volume::Linear(0.5));
1144        assert!(invalid.plain);
1145        assert_eq!(invalid.settings.speed, 1.0);
1146    }
1147
1148    #[test]
1149    fn pitched_request_for_unregistered_event_plays_nothing() {
1150        let mut app = headless_app();
1151        app.world_mut()
1152            .write_message(PitchedSfxRequest::new(SfxEvent::Mining, 1.5));
1153        app.update();
1154        assert!(spawned_sounds(&mut app).is_empty());
1155    }
1156
1157    #[test]
1158    fn active_filter_holds_the_sound_for_the_low_pass_path() {
1159        let mut app = headless_app_with_low_pass();
1160        app.insert_resource(SfxFilter::low_pass(800.0));
1161        app.world_mut()
1162            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 2.0).at(Vec3::Y));
1163        app.update();
1164
1165        // The path does not exist, so the source never loads and the sound
1166        // must not fall back to unfiltered playback.
1167        let sounds = spawned_sounds(&mut app);
1168        assert_eq!(sounds.len(), 1);
1169        let sound = &sounds[0];
1170        assert!(!sound.plain && !sound.filtered);
1171        assert!(sound.pending);
1172        assert_eq!(sound.settings.speed, 2.0);
1173        assert_eq!(sound.translation, Some(Vec3::Y));
1174        assert_eq!(shared_cutoff(&app), 800.0);
1175    }
1176
1177    #[test]
1178    fn filtered_sound_whose_source_fails_to_load_is_despawned() {
1179        let mut app = headless_app_with_low_pass();
1180        app.insert_resource(SfxFilter::low_pass(800.0));
1181        app.world_mut()
1182            .write_message(PitchedSfxRequest::new(SfxEvent::ItemPickup, 1.0));
1183        app.update();
1184        assert_eq!(spawned_sounds(&mut app).len(), 1);
1185
1186        // The load fails on a background task; give it a bounded time.
1187        for _ in 0..500 {
1188            if spawned_sounds(&mut app).is_empty() {
1189                break;
1190            }
1191            std::thread::sleep(Duration::from_millis(10));
1192            app.update();
1193        }
1194        assert!(
1195            spawned_sounds(&mut app).is_empty(),
1196            "a sound that can never be decoded must not wait forever"
1197        );
1198    }
1199
1200    #[test]
1201    fn loaded_source_is_played_through_the_filtered_asset() {
1202        let mut app = headless_app_with_low_pass();
1203        let bytes: Arc<[u8]> = Arc::from(vec![1_u8, 2, 3]);
1204        let source = app
1205            .world_mut()
1206            .resource_mut::<Assets<AudioSource>>()
1207            .add(AudioSource {
1208                bytes: bytes.clone(),
1209            });
1210        let settings = PlaybackSettings::ONCE.with_speed(1.5);
1211        let first = app
1212            .world_mut()
1213            .spawn((PendingLowPassSfx(source.clone()), settings))
1214            .id();
1215        let second = app
1216            .world_mut()
1217            .spawn((PendingLowPassSfx(source.clone()), settings))
1218            .id();
1219        app.update();
1220
1221        let sounds = spawned_sounds(&mut app);
1222        assert_eq!(sounds.len(), 2);
1223        for sound in &sounds {
1224            assert!(sound.filtered && !sound.pending && !sound.plain);
1225            assert_eq!(sound.settings.speed, 1.5);
1226        }
1227
1228        let first_handle = app
1229            .world()
1230            .get::<AudioPlayer<LowPassSfx>>(first)
1231            .expect("filtered player")
1232            .0
1233            .clone();
1234        let second_handle = app
1235            .world()
1236            .get::<AudioPlayer<LowPassSfx>>(second)
1237            .expect("filtered player")
1238            .0
1239            .clone();
1240        assert_eq!(first_handle, second_handle, "one filtered asset per source");
1241
1242        let shared = app.world().resource::<SfxFilterShared>().0.clone();
1243        let filtered = app
1244            .world()
1245            .resource::<Assets<LowPassSfx>>()
1246            .get(&first_handle)
1247            .expect("filtered asset");
1248        assert!(Arc::ptr_eq(&filtered.source.bytes, &bytes));
1249        assert!(Arc::ptr_eq(&filtered.cutoff, &shared));
1250    }
1251
1252    #[test]
1253    fn invalid_cutoff_plays_unfiltered() {
1254        for hz in [f32::NAN, -100.0, 0.0] {
1255            let mut app = headless_app_with_low_pass();
1256            app.insert_resource(SfxFilter::low_pass(hz));
1257            app.world_mut().write_message(SfxRequest {
1258                event: SfxEvent::ItemPickup,
1259                position: None,
1260            });
1261            app.update();
1262
1263            let sounds = spawned_sounds(&mut app);
1264            assert_eq!(sounds.len(), 1, "cutoff {hz}");
1265            assert!(sounds[0].plain && !sounds[0].pending, "cutoff {hz}");
1266            assert_eq!(shared_cutoff(&app), 0.0, "cutoff {hz}");
1267        }
1268    }
1269
1270    #[test]
1271    fn missing_filter_resource_plays_unfiltered() {
1272        let mut app = headless_app_with_low_pass();
1273        app.insert_resource(SfxFilter::low_pass(800.0));
1274        app.update();
1275        assert_eq!(shared_cutoff(&app), 800.0);
1276
1277        app.world_mut().remove_resource::<SfxFilter>();
1278        app.world_mut().write_message(SfxRequest {
1279            event: SfxEvent::ItemPickup,
1280            position: None,
1281        });
1282        app.update();
1283
1284        let sounds = spawned_sounds(&mut app);
1285        assert_eq!(sounds.len(), 1);
1286        assert!(sounds[0].plain && !sounds[0].pending);
1287        assert_eq!(shared_cutoff(&app), 0.0);
1288    }
1289
1290    #[test]
1291    fn filter_without_audio_backend_plays_unfiltered() {
1292        let mut app = headless_app();
1293        app.insert_resource(SfxFilter::low_pass(800.0));
1294        // `finish` must not register the low-pass path without `AudioPlugin`.
1295        app.finish();
1296        app.cleanup();
1297        assert!(!app.world().contains_resource::<SfxFilterShared>());
1298
1299        app.world_mut().write_message(SfxRequest {
1300            event: SfxEvent::ItemPickup,
1301            position: None,
1302        });
1303        app.update();
1304
1305        let sounds = spawned_sounds(&mut app);
1306        assert_eq!(sounds.len(), 1);
1307        assert!(sounds[0].plain && !sounds[0].pending);
1308    }
1309
1310    // ── Low-pass signal processing ───────────────────────────────────────────
1311
1312    struct TestSignal {
1313        samples: std::vec::IntoIter<f32>,
1314        channels: u16,
1315        sample_rate: u32,
1316    }
1317
1318    impl Iterator for TestSignal {
1319        type Item = f32;
1320
1321        fn next(&mut self) -> Option<f32> {
1322            self.samples.next()
1323        }
1324    }
1325
1326    impl RodioSource for TestSignal {
1327        fn current_frame_len(&self) -> Option<usize> {
1328            None
1329        }
1330
1331        fn channels(&self) -> u16 {
1332            self.channels
1333        }
1334
1335        fn sample_rate(&self) -> u32 {
1336            self.sample_rate
1337        }
1338
1339        fn total_duration(&self) -> Option<Duration> {
1340            None
1341        }
1342    }
1343
1344    const TEST_RATE: u32 = 44_100;
1345
1346    fn sine(frequency_hz: f32, samples: usize) -> Vec<f32> {
1347        (0..samples)
1348            .map(|i| (std::f32::consts::TAU * frequency_hz * i as f32 / TEST_RATE as f32).sin())
1349            .collect()
1350    }
1351
1352    fn cutoff_cell(cutoff_hz: f32) -> Arc<AtomicU32> {
1353        Arc::new(AtomicU32::new(cutoff_hz.to_bits()))
1354    }
1355
1356    fn filter_mono(samples: Vec<f32>, cutoff: Arc<AtomicU32>) -> Vec<f32> {
1357        let signal = TestSignal {
1358            samples: samples.into_iter(),
1359            channels: 1,
1360            sample_rate: TEST_RATE,
1361        };
1362        LowPassSource::new(signal, cutoff).collect()
1363    }
1364
1365    /// Root mean square of the second half, after the filter has settled.
1366    fn settled_rms(samples: &[f32]) -> f32 {
1367        let tail = &samples[samples.len() / 2..];
1368        (tail.iter().map(|sample| sample * sample).sum::<f32>() / tail.len() as f32).sqrt()
1369    }
1370
1371    #[test]
1372    fn low_pass_attenuates_high_frequencies_and_keeps_low_ones() {
1373        let high = sine(8_000.0, 8_820);
1374        let low = sine(100.0, 8_820);
1375        let high_out = filter_mono(high.clone(), cutoff_cell(500.0));
1376        let low_out = filter_mono(low.clone(), cutoff_cell(500.0));
1377
1378        assert_eq!(high_out.len(), high.len());
1379        assert!(
1380            settled_rms(&high_out) < 0.05 * settled_rms(&high),
1381            "8 kHz must be strongly attenuated by a 500 Hz low-pass"
1382        );
1383        let low_ratio = settled_rms(&low_out) / settled_rms(&low);
1384        assert!(
1385            (0.9..=1.05).contains(&low_ratio),
1386            "100 Hz must pass a 500 Hz low-pass, got ratio {low_ratio}"
1387        );
1388    }
1389
1390    #[test]
1391    fn low_pass_without_cutoff_is_the_identity() {
1392        let input = sine(8_000.0, 512);
1393        assert_eq!(filter_mono(input.clone(), cutoff_cell(0.0)), input);
1394        // A cutoff the sample rate cannot represent is skipped as well.
1395        assert_eq!(filter_mono(input.clone(), cutoff_cell(20_000.0)), input);
1396        // The cell is trusted to hold a sanitized value, but must not break.
1397        assert_eq!(filter_mono(input.clone(), cutoff_cell(f32::NAN)), input);
1398    }
1399
1400    #[test]
1401    fn low_pass_follows_cutoff_changes_while_playing() {
1402        let input = sine(8_000.0, 8_820);
1403        let cutoff = cutoff_cell(0.0);
1404        let signal = TestSignal {
1405            samples: input.clone().into_iter(),
1406            channels: 1,
1407            sample_rate: TEST_RATE,
1408        };
1409        let mut source = LowPassSource::new(signal, cutoff.clone());
1410
1411        let unfiltered: Vec<f32> = source.by_ref().take(2_940).collect();
1412        assert_eq!(unfiltered, input[..2_940]);
1413
1414        cutoff.store(500.0_f32.to_bits(), Ordering::Relaxed);
1415        let filtered: Vec<f32> = source.by_ref().take(2_940).collect();
1416        assert!(settled_rms(&filtered) < 0.05 * settled_rms(&input));
1417
1418        cutoff.store(0.0_f32.to_bits(), Ordering::Relaxed);
1419        let restored: Vec<f32> = source.collect();
1420        assert_eq!(restored, input[5_880..]);
1421    }
1422
1423    #[test]
1424    fn low_pass_filters_each_channel_separately() {
1425        // Left: a constant level. Right: the fastest possible alternation.
1426        let frames = 4_410;
1427        let samples: Vec<f32> = (0..frames)
1428            .flat_map(|frame| [0.5, if frame % 2 == 0 { 1.0 } else { -1.0 }])
1429            .collect();
1430        let signal = TestSignal {
1431            samples: samples.into_iter(),
1432            channels: 2,
1433            sample_rate: TEST_RATE,
1434        };
1435        let output: Vec<f32> = LowPassSource::new(signal, cutoff_cell(500.0)).collect();
1436
1437        assert_eq!(output.len(), frames * 2);
1438        let left = output[output.len() - 2];
1439        let right = output[output.len() - 1];
1440        assert!(
1441            (left - 0.5).abs() < 0.01,
1442            "constant level must pass, got {left}"
1443        );
1444        assert!(
1445            right.abs() < 0.01,
1446            "alternation must be removed, got {right}"
1447        );
1448    }
1449
1450    #[test]
1451    fn low_pass_output_stays_finite_for_bad_input() {
1452        let mut input = sine(100.0, 256);
1453        input[10] = f32::NAN;
1454        input[20] = f32::INFINITY;
1455        let output = filter_mono(input, cutoff_cell(500.0));
1456        assert!(output.iter().all(|sample| sample.is_finite()));
1457        assert!(output.iter().all(|sample| (-1.0..=1.0).contains(sample)));
1458    }
1459
1460    #[test]
1461    fn low_pass_reports_the_inner_format() {
1462        let signal = TestSignal {
1463            samples: vec![0.0; 4].into_iter(),
1464            channels: 2,
1465            sample_rate: 22_050,
1466        };
1467        let source = LowPassSource::new(signal, cutoff_cell(500.0));
1468        assert_eq!(source.channels(), 2);
1469        assert_eq!(source.sample_rate(), 22_050);
1470        assert_eq!(source.current_frame_len(), None);
1471        assert_eq!(source.total_duration(), None);
1472    }
1473
1474    #[test]
1475    fn coefficients_reject_values_that_cannot_filter() {
1476        assert!(LowPassCoefficients::new(500.0, TEST_RATE).is_some());
1477        assert_eq!(LowPassCoefficients::new(500.0, 0), None);
1478        assert_eq!(LowPassCoefficients::new(0.0, TEST_RATE), None);
1479        assert_eq!(LowPassCoefficients::new(-1.0, TEST_RATE), None);
1480        assert_eq!(LowPassCoefficients::new(f32::NAN, TEST_RATE), None);
1481        assert_eq!(LowPassCoefficients::new(f32::INFINITY, TEST_RATE), None);
1482        assert_eq!(LowPassCoefficients::new(22_050.0, TEST_RATE), None);
1483    }
1484}