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