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//! ## Example
33//!
34//! ```no_run
35//! use bevy::prelude::*;
36//! use voxel_framework::audio::{DefaultAudioPlugin, SfxConfig, SfxEvent, SfxPlugin};
37//!
38//! fn main() {
39//!     let mut sfx_config = SfxConfig::new();
40//!     sfx_config.register(SfxEvent::BlockPlace, vec!["sounds/place1.ogg"]);
41//!     sfx_config.register(SfxEvent::MiningComplete, vec!["sounds/break1.ogg"]);
42//!
43//!     App::new()
44//!         .add_plugins(DefaultPlugins)
45//!         .insert_resource(sfx_config)
46//!         .add_plugins(SfxPlugin)
47//!         .add_plugins(DefaultAudioPlugin)
48//!         .run();
49//! }
50//! ```
51
52use std::collections::HashMap;
53
54use bevy::prelude::*;
55
56use crate::world::{VoxelBroken, VoxelPlaced};
57
58// ─── SfxEvent ─────────────────────────────────────────────────────────────────
59
60/// A category of sound effect that the framework can request.
61///
62/// Each variant corresponds to a distinct gameplay moment.  Framework systems
63/// emit these through [`SfxRequest`]; games map them to asset paths via
64/// [`SfxConfig`].
65#[derive(Debug, Clone, PartialEq, Eq, Hash)]
66pub enum SfxEvent {
67    /// Emitted repeatedly while the player is actively mining a voxel (e.g.
68    /// for a continuous digging sound loop or per-hit chip).
69    Mining,
70    /// Emitted once when a voxel is fully broken and removed from the world.
71    /// Triggered by the `VoxelBroken` message.
72    MiningComplete,
73    /// Emitted when a voxel is successfully placed into the world.
74    /// Triggered by the `VoxelPlaced` message.
75    BlockPlace,
76    /// Emitted when the player picks up an item from the world.
77    ItemPickup,
78    /// Emitted when the player scrolls the hotbar slot selection.
79    HotbarScroll,
80    /// Emitted when the pause menu is opened.
81    PauseOpen,
82    /// Emitted when the pause menu is closed.
83    PauseClose,
84    /// Emitted on each footstep when the player moves while grounded.
85    ///
86    /// The inner value is the byte representation of the voxel type underfoot,
87    /// allowing games to map different surface types to different sounds.
88    Footstep(u8),
89    /// Escape hatch for game-specific sounds not covered by the framework
90    /// variants.  The inner string is an arbitrary identifier chosen by the
91    /// game and must match the key used in [`SfxConfig`].
92    Custom(String),
93}
94
95impl SfxEvent {
96    /// Returns a stable string key for this event used as the `HashMap` key in
97    /// [`SfxConfig`].
98    pub fn key(&self) -> String {
99        match self {
100            SfxEvent::Mining => "Mining".to_string(),
101            SfxEvent::MiningComplete => "MiningComplete".to_string(),
102            SfxEvent::BlockPlace => "BlockPlace".to_string(),
103            SfxEvent::ItemPickup => "ItemPickup".to_string(),
104            SfxEvent::HotbarScroll => "HotbarScroll".to_string(),
105            SfxEvent::PauseOpen => "PauseOpen".to_string(),
106            SfxEvent::PauseClose => "PauseClose".to_string(),
107            SfxEvent::Footstep(surface) => format!("Footstep:{surface}"),
108            SfxEvent::Custom(s) => format!("Custom:{s}"),
109        }
110    }
111}
112
113// ─── SfxRequest ───────────────────────────────────────────────────────────────
114
115/// A request for a sound effect to be played, emitted by framework systems.
116///
117/// [`SfxPlugin`] adds systems that produce these messages in response to world
118/// events.  A playback plugin (e.g. [`DefaultAudioPlugin`] or a custom one)
119/// reads them and drives the audio backend.
120#[derive(Message, Debug, Clone)]
121pub struct SfxRequest {
122    /// The sound effect category to play.
123    pub event: SfxEvent,
124    /// World-space position for spatial (3-D) audio, or `None` for a 2-D / UI
125    /// sound that has no position.
126    ///
127    /// When `Some`, the playback system may attenuate volume and apply panning
128    /// based on the listener's position.  When `None`, the sound should be
129    /// played at a fixed volume regardless of the camera position.
130    pub position: Option<Vec3>,
131}
132
133// ─── SfxConfig ────────────────────────────────────────────────────────────────
134
135/// Maps [`SfxEvent`] categories to lists of asset paths.
136///
137/// Each category can hold multiple paths so the game can register variant
138/// sounds (e.g. several digging sounds) and play them in round-robin order.
139/// A specific path is selected deterministically by `pick_path` using a
140/// caller-supplied seed, making the selection reproducible across frames.
141///
142/// `SfxConfig` is registered as a `Resource` by [`SfxPlugin`]; insert your
143/// populated instance before adding the plugin, or mutate the resource after
144/// `App::run` via a startup system.
145///
146/// # Examples
147///
148/// ```no_run
149/// use voxel_framework::audio::{SfxConfig, SfxEvent};
150///
151/// let mut config = SfxConfig::new();
152/// config.register(SfxEvent::BlockPlace, vec!["sounds/place1.ogg", "sounds/place2.ogg"]);
153/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 0), Some("sounds/place1.ogg"));
154/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 1), Some("sounds/place2.ogg"));
155/// // Seeds wrap around: seed 2 → index 0 again for a two-entry list.
156/// assert_eq!(config.pick_path(&SfxEvent::BlockPlace, 2), Some("sounds/place1.ogg"));
157/// ```
158#[derive(Resource, Debug, Clone)]
159pub struct SfxConfig {
160    /// Maps the string key of each [`SfxEvent`] to its registered asset paths.
161    ///
162    /// Keys are produced by [`SfxEvent::key`].  Prefer using
163    /// [`SfxConfig::register`] rather than inserting into this map directly.
164    pub sounds: HashMap<String, Vec<String>>,
165    /// Master playback volume applied to all sounds, in the range `[0.0, 1.0]`.
166    ///
167    /// `0.0` is silent; `1.0` is full volume.  Default: `1.0`.  Values outside
168    /// `[0.0, 1.0]` are not clamped by the framework — the audio backend
169    /// determines how they are handled.
170    pub volume: f32,
171}
172
173impl SfxConfig {
174    /// Creates an empty [`SfxConfig`] with master volume `1.0`.
175    pub fn new() -> Self {
176        Self {
177            sounds: HashMap::new(),
178            volume: 1.0,
179        }
180    }
181
182    /// Registers one or more asset paths for the given event category.
183    ///
184    /// Calling this a second time for the same event **replaces** the
185    /// existing path list.
186    pub fn register(&mut self, event: SfxEvent, paths: Vec<&str>) {
187        self.sounds.insert(
188            event.key(),
189            paths.into_iter().map(|p| p.to_string()).collect(),
190        );
191    }
192
193    /// Returns all registered paths for an event, or `None` if unregistered.
194    pub fn get_paths(&self, event: &SfxEvent) -> Option<&Vec<String>> {
195        self.sounds.get(&event.key())
196    }
197
198    /// Deterministically picks one path for `event` using `seed`.
199    ///
200    /// The selection is `paths[seed % paths.len()]`, so the same seed always
201    /// produces the same result. Returns `None` if the event has no paths.
202    pub fn pick_path(&self, event: &SfxEvent, seed: u64) -> Option<&str> {
203        let paths = self.get_paths(event)?;
204        if paths.is_empty() {
205            return None;
206        }
207        let index = (seed % paths.len() as u64) as usize;
208        Some(paths[index].as_str())
209    }
210}
211
212impl Default for SfxConfig {
213    fn default() -> Self {
214        Self::new()
215    }
216}
217
218// ─── Systems ──────────────────────────────────────────────────────────────────
219
220/// Translates `VoxelBroken` messages into [`SfxRequest`] messages with event
221/// [`SfxEvent::MiningComplete`].
222///
223/// The request carries the broken voxel's world position so that a spatial
224/// audio handler can place the sound in 3-D space.  This system is added by
225/// [`SfxPlugin`] and runs in the [`Update`] schedule.
226pub fn mining_sfx_system(
227    mut broken_reader: MessageReader<VoxelBroken>,
228    mut sfx_writer: MessageWriter<SfxRequest>,
229) {
230    for broken in broken_reader.read() {
231        sfx_writer.write(SfxRequest {
232            event: SfxEvent::MiningComplete,
233            position: Some(broken.world_pos),
234        });
235    }
236}
237
238/// Translates `VoxelPlaced` messages into [`SfxRequest`] messages with event
239/// [`SfxEvent::BlockPlace`].
240///
241/// The request carries the placed voxel's world position so that a spatial
242/// audio handler can place the sound in 3-D space.  This system is added by
243/// [`SfxPlugin`] and runs in the [`Update`] schedule.
244pub fn placement_sfx_system(
245    mut placed_reader: MessageReader<VoxelPlaced>,
246    mut sfx_writer: MessageWriter<SfxRequest>,
247) {
248    for placed in placed_reader.read() {
249        sfx_writer.write(SfxRequest {
250            event: SfxEvent::BlockPlace,
251            position: Some(placed.world_pos),
252        });
253    }
254}
255
256// ─── SfxPlugin ────────────────────────────────────────────────────────────────
257
258/// Core plugin for the framework sound-effect system.
259///
260/// # What it registers
261///
262/// * [`SfxConfig`] — initialized as a default resource (all categories empty,
263///   volume `1.0`).  Insert a pre-populated instance before adding this plugin
264///   to override the defaults.
265/// * The [`SfxRequest`] message channel so framework systems can emit requests
266///   and game systems can read them.
267/// * [`mining_sfx_system`] and [`placement_sfx_system`] in the [`Update`]
268///   schedule.
269///
270/// # What it does NOT do
271///
272/// `SfxPlugin` never loads audio assets, never creates audio entities, and
273/// never calls into any audio backend. Actual playback is the responsibility
274/// of a separate plugin — either [`DefaultAudioPlugin`], which uses Bevy audio,
275/// or a custom plugin that reads [`SfxRequest`] events. [`crate::VoxelPlugin`]
276/// includes `SfxPlugin`, but it does not include a playback plugin.
277pub struct SfxPlugin;
278
279impl Plugin for SfxPlugin {
280    fn build(&self, app: &mut App) {
281        app.init_resource::<SfxConfig>();
282        app.add_message::<SfxRequest>();
283        app.add_systems(Update, (mining_sfx_system, placement_sfx_system));
284    }
285}
286
287// ─── DefaultAudioPlugin ───────────────────────────────────────────────────────
288
289/// A round-robin counter per SFX key so successive identical events cycle
290/// through registered variant paths rather than always picking the same one.
291#[derive(Resource, Default)]
292struct SfxCounter(HashMap<String, u64>);
293
294/// Ready-to-use audio plugin that plays [`SfxRequest`] messages via
295/// Bevy's built-in `bevy_audio` backend.
296///
297/// For each incoming [`SfxRequest`], this plugin:
298/// 1. Resolves the event key through [`SfxConfig::pick_path`] (round-robin
299///    across registered variants).
300/// 2. Loads the asset with `AssetServer::load`.
301/// 3. Spawns an `(AudioPlayer, PlaybackSettings::ONCE)` entity that Bevy's
302///    audio system will play and automatically despawn when finished.
303///
304/// # Setup
305///
306/// Register asset paths with [`SfxConfig`] before adding the plugin, or
307/// populate them in a startup system:
308///
309/// ```no_run
310/// use bevy::prelude::*;
311/// use voxel_framework::audio::{DefaultAudioPlugin, SfxConfig, SfxEvent, SfxPlugin};
312///
313/// App::new()
314///     .add_plugins(DefaultPlugins)
315///     .add_plugins(SfxPlugin)
316///     .add_plugins(DefaultAudioPlugin)
317///     .add_systems(Startup, |mut cfg: ResMut<SfxConfig>| {
318///         cfg.register(SfxEvent::MiningComplete, vec!["sounds/break.ogg"]);
319///         cfg.register(SfxEvent::BlockPlace,     vec!["sounds/place.ogg"]);
320///     })
321///     .run();
322/// ```
323///
324/// # Missing files
325///
326/// If an asset path is not found on disk, Bevy logs a warning and skips
327/// playback — no panic, no crash.
328///
329/// # Spatial audio
330///
331/// When the [`SfxRequest::position`] field is `Some`, the plugin attaches a
332/// [`SpatialListener`]-compatible [`Transform`] to the audio entity so Bevy
333/// can attenuate volume by distance.  Requires a [`SpatialListener`] on the
334/// camera/player entity.
335pub struct DefaultAudioPlugin;
336
337impl Plugin for DefaultAudioPlugin {
338    fn build(&self, app: &mut App) {
339        app.init_resource::<SfxCounter>();
340        app.add_systems(Update, play_sfx_system);
341    }
342}
343
344fn play_sfx_system(
345    mut sfx_reader: MessageReader<SfxRequest>,
346    config: Res<SfxConfig>,
347    asset_server: Res<AssetServer>,
348    mut counter: ResMut<SfxCounter>,
349    mut commands: Commands,
350) {
351    for request in sfx_reader.read() {
352        let key = request.event.key();
353        let seed = {
354            let c = counter.0.entry(key.clone()).or_insert(0);
355            let s = *c;
356            *c = c.wrapping_add(1);
357            s
358        };
359        let Some(path) = config.pick_path(&request.event, seed).map(|p| p.to_owned()) else {
360            continue;
361        };
362        let source: Handle<AudioSource> = asset_server.load(path);
363        let mut settings = PlaybackSettings::ONCE;
364        settings.volume = bevy::audio::Volume::Linear(config.volume);
365        let mut entity = commands.spawn((AudioPlayer(source), settings));
366        if let Some(pos) = request.position {
367            entity.insert(Transform::from_translation(pos));
368        }
369    }
370}
371
372// ─── Tests ────────────────────────────────────────────────────────────────────
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377
378    fn config_with_paths() -> SfxConfig {
379        let mut cfg = SfxConfig::new();
380        cfg.register(
381            SfxEvent::BlockPlace,
382            vec![
383                "sounds/place1.ogg",
384                "sounds/place2.ogg",
385                "sounds/place3.ogg",
386            ],
387        );
388        cfg
389    }
390
391    #[test]
392    fn test_sfx_config_pick_deterministic() {
393        let cfg = config_with_paths();
394        let first = cfg.pick_path(&SfxEvent::BlockPlace, 0);
395        let second = cfg.pick_path(&SfxEvent::BlockPlace, 0);
396        assert_eq!(first, second, "same seed must always produce the same path");
397    }
398
399    #[test]
400    fn test_sfx_config_pick_wraps() {
401        let cfg = config_with_paths();
402        // 3 paths; seed 5 → 5 % 3 = 2 → "sounds/place3.ogg"
403        let path = cfg.pick_path(&SfxEvent::BlockPlace, 5);
404        assert!(
405            path.is_some(),
406            "seed > paths.len() must still return a valid path"
407        );
408        assert_eq!(path.unwrap(), "sounds/place3.ogg");
409    }
410
411    #[test]
412    fn test_sfx_config_returns_none_for_unregistered_event() {
413        let cfg = SfxConfig::new();
414        assert!(cfg.pick_path(&SfxEvent::Mining, 0).is_none());
415    }
416
417    #[test]
418    fn test_sfx_config_get_paths() {
419        let cfg = config_with_paths();
420        let paths = cfg.get_paths(&SfxEvent::BlockPlace).unwrap();
421        assert_eq!(paths.len(), 3);
422    }
423
424    #[test]
425    fn test_sfx_event_key_custom() {
426        let event = SfxEvent::Custom("footstep".to_string());
427        assert_eq!(event.key(), "Custom:footstep");
428    }
429}