Skip to main content

euv_core/game/audio/
impl.rs

1use super::*;
2
3/// Default unmuted audio bus at `0.85` master volume.
4impl Default for AudioBus {
5    /// Creates a default `AudioBus`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Ready audio bus.
10    fn default() -> Self {
11        Self {
12            master_volume: 0.85,
13            muted: false,
14            queue: Vec::new(),
15            total_played: 0,
16        }
17    }
18}
19
20/// Sound cue scheduling and frame draining for `AudioBus`.
21impl AudioBus {
22    /// Queues a sound cue with normalized volume, pan, and pitch.
23    ///
24    /// # Arguments
25    ///
26    /// - `&Self` - Mutable audio bus.
27    /// - `SoundCue` - Sound cue to play.
28    /// - `f32` - Linear volume `[0.0, 1.0]`.
29    /// - `f32` - Stereo pan `[-1.0, 1.0]`.
30    /// - `f32` - Pitch multiplier `[0.25, 4.0]`.
31    pub fn play(&mut self, cue: SoundCue, volume: f32, pan: f32, pitch: f32) {
32        if self.get_muted() {
33            return;
34        }
35        let eff_vol: f32 = (volume.clamp(0.0, 1.0) * self.get_master_volume()).clamp(0.0, 1.0);
36        if eff_vol <= 0.001 {
37            return;
38        }
39        self.get_mut_queue().push(AudioCommand::new(
40            cue,
41            eff_vol,
42            pan.clamp(-1.0, 1.0),
43            pitch.clamp(0.25, 4.0),
44        ));
45        let next_total: u64 = self.get_total_played().saturating_add(1);
46        self.set_total_played(next_total);
47    }
48
49    /// Drains all queued audio commands for platform audio playback while preserving backing queue capacity.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Self` - Mutable audio bus.
54    ///
55    /// # Returns
56    ///
57    /// - `Vec<AudioCommand>` - Ordered commands emitted since the previous drain.
58    pub fn drain(&mut self) -> Vec<AudioCommand> {
59        let q: &mut Vec<AudioCommand> = self.get_mut_queue();
60        if q.is_empty() {
61            return Vec::new();
62        }
63        let out: Vec<AudioCommand> = q.clone();
64        q.clear();
65        out
66    }
67
68    /// Drains all queued audio commands into caller-provided `out` preserving capacity on both buffers (zero steady-state allocations).
69    ///
70    /// # Arguments
71    ///
72    /// - `&Self` - Mutable audio bus.
73    /// - `&mut Vec<AudioCommand>` - Reusable destination buffer cleared and populated in place.
74    pub fn drain_into(&mut self, out: &mut Vec<AudioCommand>) {
75        out.clear();
76        let q: &mut Vec<AudioCommand> = self.get_mut_queue();
77        out.extend_from_slice(q.as_slice());
78        q.clear();
79    }
80
81    /// Clears all queued audio commands in place while preserving allocated capacity.
82    ///
83    /// # Arguments
84    ///
85    /// - `&Self` - Mutable audio bus.
86    pub fn clear_queue(&mut self) {
87        self.get_mut_queue().clear();
88    }
89
90    /// Spatializes a 3D sound emitter relative to `listener` with inverse-distance attenuation, stereo ear panning, and Doppler shift.
91    ///
92    /// # Arguments
93    ///
94    /// - `&Self` - Mutable audio bus.
95    /// - `&AudioListener3D` - Active 3D listener pose.
96    /// - `&SpatialAudioSource3D` - World-space sound source parameters.
97    pub fn play_spatial_3d(&mut self, listener: &AudioListener3D, source: &SpatialAudioSource3D) {
98        let delta: Vec3 = source.get_position().sub(listener.get_position());
99        let dist: f32 = delta.length();
100        let max_d: f32 = source.get_max_distance().max(1.0);
101        if dist >= max_d {
102            return;
103        }
104        let min_d: f32 = source.get_min_distance().clamp(0.25, max_d);
105        let atten: f32 = if dist <= min_d {
106            1.0
107        } else {
108            let norm: f32 = ((dist - min_d) / (max_d - min_d).max(0.01)).clamp(0.0, 1.0);
109            (1.0 - norm) * (1.0 - norm)
110        };
111        let to_src: Vec3 = if dist > 1e-4 {
112            delta.scale(1.0 / dist)
113        } else {
114            Vec3::zero()
115        };
116        let pan: f32 = to_src.dot(listener.get_right()).clamp(-1.0, 1.0);
117        let rel_vel: f32 = source
118            .get_velocity()
119            .sub(listener.get_velocity())
120            .dot(to_src);
121        let speed_of_sound: f32 = 343.0;
122        let doppler: f32 =
123            (speed_of_sound / (speed_of_sound + rel_vel).clamp(120.0, 680.0)).clamp(0.5, 2.0);
124        self.play(
125            source.get_cue(),
126            source.get_volume() * atten,
127            pan,
128            source.get_pitch() * doppler,
129        );
130    }
131}
132
133/// Camera-based listener builder for `AudioListener3D`.
134impl AudioListener3D {
135    /// Builds an `AudioListener3D` from a `Camera3D` and optional linear velocity.
136    ///
137    /// # Arguments
138    ///
139    /// - `&Camera3D` - Active 3D perspective camera.
140    /// - `Vec3` - Listener linear velocity in meters/sec.
141    ///
142    /// # Returns
143    ///
144    /// - `Self` - Positioned and oriented 3D audio listener.
145    #[must_use]
146    pub fn from_camera(camera: &Camera3D, velocity: Vec3) -> Self {
147        Self::new(camera.get_position(), velocity, camera.right())
148    }
149}
150
151/// Fluent constructor for `SpatialAudioSource3D`.
152impl SpatialAudioSource3D {
153    /// Creates a `SpatialAudioSource3D` at `position` with default `[2.0m, 80.0m]` attenuation radius.
154    ///
155    /// # Arguments
156    ///
157    /// - `SoundCue` - Sound cue identifier.
158    /// - `Vec3` - World-space position in meters.
159    ///
160    /// # Returns
161    ///
162    /// - `Self` - Ready 3D spatial audio emitter.
163    #[must_use]
164    pub fn new(cue: SoundCue, position: Vec3) -> Self {
165        Self {
166            cue,
167            position,
168            velocity: Vec3::zero(),
169            volume: 1.0,
170            pitch: 1.0,
171            min_distance: 2.0,
172            max_distance: 80.0,
173        }
174    }
175
176    /// Sets linear velocity for Doppler pitch calculation.
177    ///
178    /// # Arguments
179    ///
180    /// - `Self` - Source emitter.
181    /// - `Vec3` - Velocity in meters/sec.
182    ///
183    /// # Returns
184    ///
185    /// - `Self` - Updated spatial audio source.
186    #[must_use]
187    pub fn with_velocity(mut self, velocity: Vec3) -> Self {
188        self.set_velocity(velocity);
189        self
190    }
191
192    /// Sets nominal volume and audible `[min_distance, max_distance]` range.
193    ///
194    /// # Arguments
195    ///
196    /// - `Self` - Source emitter.
197    /// - `f32` - Nominal volume `[0.0, 1.0]`.
198    /// - `f32` - Reference full-volume distance in meters.
199    /// - `f32` - Maximum audible radius in meters.
200    ///
201    /// # Returns
202    ///
203    /// - `Self` - Updated spatial audio source.
204    #[must_use]
205    pub fn with_range(mut self, volume: f32, min_distance: f32, max_distance: f32) -> Self {
206        self.set_volume(volume.clamp(0.0, 1.0));
207        self.set_min_distance(min_distance.max(0.25));
208        self.set_max_distance(max_distance.max(min_distance + 0.5));
209        self
210    }
211}