ferravex_render/audio/
game.rs

1//! Small reusable helpers; games still decide which simulation event made a sound.
2use super::*;
3use std::rc::Weak;
4
5const CADENCE_SEED: u32 = 0x71da51;
6// Mixer accepts at most 128 voices. Keep ownership bounded even as old handles
7// expire or are stolen; no allocation is needed to accept or discard a cue.
8const TRACKED_VOICES: usize = 128;
9
10/// Local gameplay audio with explicit suspension, independent of simulation time.
11///
12/// Pause/reset discard only this instance's gameplay voices. Non-positional
13/// [`Cue::Click`] voices use the UI bus and remain independent of this lifecycle,
14/// as do other instances, music and the user's mute/bus/master settings. There
15/// is no pending-cue queue. Admission describes the mixer, not device audibility.
16/// Runtime replacement discards stale voice ownership and cadence history.
17/// Controllers belong to their creating thread, like the runtime mixer:
18///
19/// ```compile_fail
20/// let audio = ferravex_render::audio::GameAudio::new();
21/// std::thread::spawn(move || drop(audio));
22/// ```
23///
24/// ```
25/// use ferravex_render::audio::{Cue, GameAudio};
26/// let mut audio = GameAudio::new();
27/// audio.pause();
28/// assert!(audio.is_paused());
29/// assert_eq!(audio.cue_with_outcome(Cue::Jump, 0.5), None);
30/// audio.reset(); // Reset during a menu stays paused.
31/// assert!(audio.is_paused());
32/// audio.resume();
33/// assert!(!audio.is_paused());
34/// assert!(audio.cue_with_outcome(Cue::Jump, 0.5).unwrap().handle().is_some());
35/// ```
36pub struct GameAudio {
37    runtime: Weak<()>,
38    motor: Option<VoiceHandle>,
39    voices: [Option<VoiceHandle>; TRACKED_VOICES],
40    paused: bool,
41    last: Option<Vec3>,
42    travel: f32,
43    grounded: bool,
44    seed: u32,
45    acoustics: AcousticProfile,
46}
47impl Default for GameAudio {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52impl GameAudio {
53    /// Preload the shared bank and start unpaused. See [`Self`].
54    pub fn new() -> Self {
55        preload_cues();
56        Self {
57            runtime: AUDIO.with(|cell| Rc::downgrade(&cell.borrow().as_ref().unwrap().identity)),
58            motor: None,
59            voices: [None; TRACKED_VOICES],
60            paused: false,
61            last: None,
62            travel: 0.,
63            grounded: false,
64            seed: CADENCE_SEED,
65            acoustics: AcousticProfile::default(),
66        }
67    }
68    /// Immediately discard this instance's gameplay voices and restart its
69    /// footfall history/pitch sequence, retaining acoustics and pause state.
70    /// UI clicks and shared mixer settings are unchanged. See [`Self`].
71    pub fn reset(&mut self) {
72        self.clear_gameplay();
73        self.seed = CADENCE_SEED;
74    }
75    /// Immediately discard gameplay voices (including releasing motors) and
76    /// footfall history, then suppress new gameplay cues until [`Self::resume`].
77    /// Repeated calls are harmless; UI clicks remain usable. See [`Self`].
78    pub fn pause(&mut self) {
79        if !self.paused {
80            self.clear_gameplay();
81            self.paused = true;
82        }
83    }
84    /// Accept fresh gameplay cues again. Does not replay suppressed events or
85    /// restart the motor: the next active [`Self::motor`] call supplies its state.
86    /// The first valid walk sample establishes a new origin. See [`Self`].
87    pub fn resume(&mut self) {
88        self.paused = false;
89    }
90    /// Whether gameplay cues are locally suspended, regardless of device or
91    /// user mute state. See [`Self`].
92    pub fn is_paused(&self) -> bool {
93        self.paused
94    }
95    fn bind_runtime(&mut self, runtime: Weak<()>) {
96        if !Weak::ptr_eq(&self.runtime, &runtime) {
97            self.runtime = runtime;
98            self.voices.fill(None);
99            self.motor = None;
100            self.last = None;
101            self.travel = 0.;
102            self.grounded = false;
103            self.seed = CADENCE_SEED;
104        }
105    }
106    fn sync_runtime(&mut self) {
107        // A weak identity keeps its allocation reserved while a stale owner
108        // exists, preventing address reuse from aliasing a replacement mixer.
109        // try_with also permits controllers to drop after audio TLS teardown.
110        let runtime = AUDIO
111            .try_with(|cell| {
112                cell.borrow()
113                    .as_ref()
114                    .map(|audio| Rc::downgrade(&audio.identity))
115            })
116            .ok()
117            .flatten()
118            .unwrap_or_default();
119        self.bind_runtime(runtime);
120    }
121    fn clear_gameplay(&mut self) {
122        self.sync_runtime();
123        for voice in &mut self.voices {
124            if let Some(handle) = voice.take() {
125                stop(handle, 0);
126            }
127        }
128        self.motor = None;
129        self.last = None;
130        self.travel = 0.;
131        self.grounded = false;
132    }
133    pub fn set_acoustics(&mut self, profile: AcousticProfile) -> bool {
134        if !profile.valid() {
135            return false;
136        }
137        self.acoustics = profile;
138        true
139    }
140    /// Play a cue, discarding its admission result for compatibility.
141    /// See [`Self::cue_with_outcome`] for validation and suspension semantics.
142    pub fn cue(&mut self, cue: Cue, gain: f32) {
143        let _ = self.cue_with_outcome(cue, gain);
144    }
145    /// Submit a non-positional cue using the existing mixer admission policy.
146    ///
147    /// `None` means local pause suppressed the cue without touching the mixer.
148    /// Otherwise the result distinguishes a start, a steal and a rejection.
149    /// The mixer validates the resulting parameters, including the gain after
150    /// acoustics (finite, in `0..=4`). Clicks bypass acoustics and local pause.
151    /// Muted, zero-gain and device-unavailable playback can still be admitted;
152    /// the host continues to render/skip these voices normally.
153    ///
154    /// ```
155    /// use ferravex_render::audio::{Cue, GameAudio, VoiceAdmission, VoiceRejection};
156    /// let mut audio = GameAudio::new();
157    /// assert_eq!(audio.cue_with_outcome(Cue::Fire, f32::NAN),
158    ///     Some(VoiceAdmission::Rejected(VoiceRejection::InvalidParams)));
159    /// let admission = audio.cue_with_outcome(Cue::Fire, 0.5).unwrap();
160    /// assert!(admission.handle().is_some());
161    /// audio.pause();
162    /// assert_eq!(audio.cue_with_outcome(Cue::Fire, 0.5), None);
163    /// assert!(audio.cue_with_outcome(Cue::Click, 0.2).unwrap().handle().is_some());
164    /// ```
165    #[must_use]
166    pub fn cue_with_outcome(&mut self, cue: Cue, gain: f32) -> Option<VoiceAdmission> {
167        let profile = if matches!(cue, Cue::Click) {
168            AcousticProfile::default()
169        } else {
170            self.acoustics
171        };
172        self.start(
173            cue,
174            VoiceParams {
175                gain: gain * profile.gain,
176                low_pass_hz: profile.low_pass_hz,
177                priority: if matches!(cue, Cue::Fire | Cue::Failure) {
178                    5
179                } else {
180                    2
181                },
182                bus: if matches!(cue, Cue::Click) {
183                    Bus::Ui
184                } else {
185                    Bus::Effects
186                },
187                ..Default::default()
188            },
189        )
190    }
191    /// Play a positional gameplay cue, discarding its admission result.
192    /// See [`Self::at_with_outcome`].
193    pub fn at(&mut self, cue: Cue, position: Vec3, gain: f32) {
194        let _ = self.at_with_outcome(cue, position, gain);
195    }
196    /// Submit a positional gameplay cue. All positional cues, including Click,
197    /// retain the original effects-bus/acoustics behavior and obey local pause.
198    /// Invalid positions or resulting gains are rejected without a voice change.
199    /// Outcomes have the same meaning as [`Self::cue_with_outcome`].
200    ///
201    /// ```
202    /// use ferravex_render::{audio::{Cue, GameAudio, VoiceAdmission, VoiceRejection},
203    ///     prelude::Vec3};
204    /// let mut audio = GameAudio::new();
205    /// assert_eq!(audio.at_with_outcome(Cue::Fire, Vec3::splat(f32::NAN), 0.5),
206    ///     Some(VoiceAdmission::Rejected(VoiceRejection::InvalidParams)));
207    /// assert!(audio.at_with_outcome(Cue::Fire, Vec3::ZERO, 0.5)
208    ///     .unwrap().handle().is_some());
209    /// audio.pause();
210    /// assert_eq!(audio.at_with_outcome(Cue::Click, Vec3::ZERO, 0.2), None);
211    /// ```
212    #[must_use]
213    pub fn at_with_outcome(
214        &mut self,
215        cue: Cue,
216        position: Vec3,
217        gain: f32,
218    ) -> Option<VoiceAdmission> {
219        self.start(
220            cue,
221            VoiceParams {
222                position: position.to_array(),
223                gain: gain * self.acoustics.gain,
224                low_pass_hz: self.acoustics.low_pass_hz,
225                spatial: Spatial::Attenuated {
226                    min_distance: 1.,
227                    max_distance: 65.,
228                    rolloff: 0.04,
229                },
230                priority: 3,
231                ..Default::default()
232            },
233        )
234    }
235    fn start(&mut self, cue: Cue, params: VoiceParams) -> Option<VoiceAdmission> {
236        if self.paused && params.bus != Bus::Ui {
237            return None;
238        }
239        initialize();
240        Some(AUDIO.with(|cell| {
241            let mut state = cell.borrow_mut();
242            let audio = state.as_mut().unwrap();
243            self.bind_runtime(Rc::downgrade(&audio.identity));
244            let Audio { mixer, bank, .. } = audio;
245            let bank = bank.get_or_insert_with(|| SoundBank::procedural(24000).unwrap());
246            let admission = mixer.start_with_outcome(bank.get(cue), params);
247            if params.bus != Bus::Ui
248                && let Some(handle) = admission.handle()
249            {
250                // A successful admission must leave a free/stale entry: the
251                // mixer cannot have more live handles than this fixed array.
252                let slot = self
253                    .voices
254                    .iter_mut()
255                    .find(|voice| voice.is_none_or(|voice| mixer.params(voice).is_none()))
256                    .expect("admitted voice fits the mixer's 128-voice bound");
257                *slot = Some(handle);
258            }
259            admission
260        }))
261    }
262    /// Local footfall cadence follows actual ground travel, avoiding sounds from
263    /// pushing into a wall. Teleports, air motion and menus reset accumulated travel.
264    /// Local pause ignores samples; resume establishes a fresh origin.
265    pub fn walk(
266        &mut self,
267        position: Vec3,
268        grounded: bool,
269        active: bool,
270        surface: Surface,
271        stride: f32,
272    ) {
273        self.sync_runtime();
274        if self.paused
275            || !position.is_finite()
276            || !stride.is_finite()
277            || !(0.1..=1000.).contains(&stride)
278        {
279            return;
280        }
281        let previous = self.last.replace(position);
282        let was_grounded = self.grounded;
283        self.grounded = grounded;
284        if !active || !grounded {
285            self.travel = 0.;
286            return;
287        }
288        let Some(previous) = previous else {
289            return;
290        };
291        let delta = position - previous;
292        if delta.length() > stride * 4. {
293            self.travel = 0.;
294            return;
295        }
296        if !was_grounded && delta.y < -0.04 {
297            self.cue(Cue::Impact(surface), 0.55);
298        }
299        self.travel += vec3(delta.x, 0., delta.z).length();
300        for _ in 0..2 {
301            if self.travel < stride {
302                break;
303            }
304            self.travel -= stride;
305            self.seed ^= self.seed << 13;
306            self.seed ^= self.seed >> 17;
307            self.seed ^= self.seed << 5;
308            let pitch = 0.94 + (self.seed % 1024) as f32 / 1024. * 0.12;
309            let _ = self.start(
310                Cue::Footstep(surface),
311                VoiceParams {
312                    gain: 0.55 * self.acoustics.gain,
313                    pitch,
314                    low_pass_hz: self.acoustics.low_pass_hz,
315                    priority: 1,
316                    ..Default::default()
317                },
318            );
319        }
320    }
321    /// Local continuous motor/propeller loop. Speed changes pitch and loudness;
322    /// inactive/invalid input releases the voice over 128 output frames. Explicit
323    /// [`Self::pause`] discards it immediately, even without an output callback.
324    pub fn motor(&mut self, speed: f32, max_speed: f32, active: bool) {
325        self.sync_runtime();
326        if self.paused || !active || !speed.is_finite() || !max_speed.is_finite() || max_speed <= 0.
327        {
328            if let Some(h) = self.motor.take() {
329                stop(h, 128);
330            }
331            return;
332        }
333        let amount = (speed.abs() / max_speed).clamp(0., 1.);
334        let params = VoiceParams {
335            gain: (0.12 + amount * 0.28) * self.acoustics.gain,
336            low_pass_hz: self.acoustics.low_pass_hz,
337            pitch: 0.6 + amount * 2.2,
338            looping: true,
339            bus: Bus::Ambience,
340            priority: 1,
341            ..Default::default()
342        };
343        if let Some(h) = self.motor
344            && set_params(h, params)
345        {
346            return;
347        }
348        self.motor = self
349            .start(Cue::Engine, params)
350            .and_then(VoiceAdmission::handle);
351    }
352}
353impl Drop for GameAudio {
354    fn drop(&mut self) {
355        self.sync_runtime();
356        if let Some(h) = self.motor.take() {
357            stop(h, 128);
358        }
359    }
360}
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    fn fresh() -> GameAudio {
366        crate::edit(|s| *s = crate::State::default());
367        super::super::reset();
368        set_muted(false);
369        set_master_gain(0.7);
370        GameAudio::new()
371    }
372
373    fn params(handle: VoiceHandle) -> VoiceParams {
374        AUDIO.with(|cell| {
375            cell.borrow()
376                .as_ref()
377                .unwrap()
378                .mixer
379                .params(handle)
380                .unwrap()
381        })
382    }
383
384    fn mixer_limit(limit: usize) {
385        AUDIO.with(|cell| {
386            cell.borrow_mut().as_mut().unwrap().mixer = Mixer::new(SAMPLE_RATE, limit).unwrap();
387        });
388    }
389
390    #[test]
391    fn old_controller_pause_and_reset_cannot_stop_replacement_runtime_voices() {
392        for pause in [false, true] {
393            let mut old = fresh();
394            let old_voice = old
395                .cue_with_outcome(Cue::Jump, 0.5)
396                .unwrap()
397                .handle()
398                .unwrap();
399            crate::start(Default::default(), async {});
400            let mut new = GameAudio::new();
401            let new_voice = new
402                .cue_with_outcome(Cue::Fire, 0.5)
403                .unwrap()
404                .handle()
405                .unwrap();
406            assert_eq!(
407                old_voice, new_voice,
408                "raw handles are intentionally mixer-local"
409            );
410            if pause {
411                old.pause();
412            } else {
413                old.reset();
414            }
415            assert!(playing(new_voice));
416            assert_eq!(stats().active, 1);
417        }
418    }
419
420    #[test]
421    fn motor_updates_release_and_drop_ignore_replaced_runtime_handles() {
422        for active in [false, true] {
423            let mut old = fresh();
424            old.motor(10., 40., true);
425            let old_voice = old.motor.unwrap();
426            super::super::reset();
427            let mut new = GameAudio::new();
428            new.motor(20., 40., true);
429            let new_voice = new.motor.unwrap();
430            let new_params = params(new_voice);
431            assert_eq!(old_voice, new_voice);
432            old.motor(30., 40., active);
433            assert_eq!(params(new_voice), new_params);
434            drop(old);
435            render(&mut [[0.; 2]; 128], SAMPLE_RATE);
436            assert!(playing(new_voice));
437            assert_eq!(params(new_voice), new_params);
438        }
439        let mut old = fresh();
440        old.motor(10., 40., true);
441        super::super::reset();
442        let mut new = GameAudio::new();
443        new.motor(20., 40., true);
444        let new_voice = new.motor.unwrap();
445        drop(old);
446        render(&mut [[0.; 2]; 128], SAMPLE_RATE);
447        assert!(
448            playing(new_voice),
449            "drop without another method must also rebase ownership"
450        );
451    }
452
453    #[test]
454    fn replacement_reuses_tracking_and_resets_walk_history() {
455        let mut old = fresh();
456        mixer_limit(TRACKED_VOICES);
457        for _ in 0..TRACKED_VOICES {
458            assert!(
459                old.cue_with_outcome(Cue::Jump, 0.5)
460                    .unwrap()
461                    .handle()
462                    .is_some()
463            );
464        }
465        old.walk(Vec3::ZERO, true, true, Surface::Stone, 1.5);
466        old.walk(vec3(1.4, 0., 0.), true, true, Surface::Stone, 1.5);
467        super::super::reset();
468        let mut new = GameAudio::new();
469        let new_voice = new
470            .cue_with_outcome(Cue::Fire, 0.5)
471            .unwrap()
472            .handle()
473            .unwrap();
474        old.walk(vec3(1.6, 0., 0.), true, true, Surface::Stone, 1.5);
475        assert_eq!(
476            stats().active,
477            1,
478            "replacement establishes a new walking origin"
479        );
480        let admitted = old
481            .cue_with_outcome(Cue::Jump, 0.5)
482            .unwrap()
483            .handle()
484            .unwrap();
485        assert_ne!(admitted, new_voice);
486        old.reset();
487        assert!(!playing(admitted));
488        assert!(playing(new_voice));
489    }
490
491    #[test]
492    fn controller_drop_after_audio_thread_local_teardown_is_harmless() {
493        std::thread::spawn(|| {
494            thread_local! { static OWNER: RefCell<Option<GameAudio>> = const { RefCell::new(None) }; }
495            OWNER.with(|owner| {
496                let mut audio = GameAudio::new();
497                audio.motor(10., 40., true);
498                *owner.borrow_mut() = Some(audio);
499            });
500        }).join().unwrap();
501    }
502
503    #[test]
504    fn cadence_uses_ground_travel_and_motor_reuses_its_voice() {
505        crate::edit(|s| *s = crate::State::default());
506        super::super::reset();
507        let mut sound = GameAudio::new();
508        sound.walk(Vec3::ZERO, true, true, Surface::Stone, 1.5);
509        sound.walk(vec3(0.5, 0., 0.), true, true, Surface::Stone, 1.5);
510        assert_eq!(stats().active, 0);
511        sound.walk(vec3(1.6, 0., 0.), true, true, Surface::Stone, 1.5);
512        assert_eq!(stats().active, 1);
513        sound.walk(vec3(100., 0., 0.), true, true, Surface::Stone, 1.5);
514        assert_eq!(stats().active, 1, "teleport is not a footstep");
515        sound.walk(vec3(101., 0., 0.), false, true, Surface::Stone, 1.5);
516        assert_eq!(stats().active, 1);
517        stop_all();
518        sound.motor(10., 40., true);
519        let voice = sound.motor.unwrap();
520        sound.motor(20., 40., true);
521        assert_eq!(sound.motor, Some(voice));
522        assert_eq!(stats().active, 1);
523        sound.motor(20., 40., false);
524        assert!(sound.motor.is_none());
525        render(&mut [[0.; 2]; 128], 48000);
526        assert_eq!(stats().active, 0);
527    }
528
529    #[test]
530    fn pause_discards_owned_gameplay_but_preserves_ui_and_other_owners() {
531        let mut sound = fresh();
532        let mut other = GameAudio::new();
533        let other_cue = other
534            .cue_with_outcome(Cue::Fire, 0.5)
535            .unwrap()
536            .handle()
537            .unwrap();
538        let music = play(
539            Cue::Engine,
540            VoiceParams {
541                looping: true,
542                bus: Bus::Music,
543                ..Default::default()
544            },
545        )
546        .unwrap();
547        let click = sound
548            .cue_with_outcome(Cue::Click, 0.2)
549            .unwrap()
550            .handle()
551            .unwrap();
552        let cue = sound
553            .cue_with_outcome(Cue::Jump, 0.5)
554            .unwrap()
555            .handle()
556            .unwrap();
557        let positional = sound
558            .at_with_outcome(Cue::Click, Vec3::ZERO, 0.2)
559            .unwrap()
560            .handle()
561            .unwrap();
562        sound.walk(Vec3::ZERO, true, true, Surface::Stone, 1.);
563        sound.walk(vec3(1., 0., 0.), true, true, Surface::Stone, 1.);
564        sound.motor(10., 40., true);
565        let motor = sound.motor.unwrap();
566        assert_eq!(stats().active, 7);
567        set_master_gain(0.3);
568        set_bus_gain(Bus::Effects, 0.4);
569        let buses = bus_gains();
570
571        sound.pause();
572        sound.pause();
573        assert!(sound.is_paused());
574        assert!(!playing(cue));
575        assert!(!playing(positional));
576        assert!(!playing(motor));
577        assert!(playing(click) && playing(other_cue) && playing(music));
578        assert_eq!(
579            stats().active,
580            3,
581            "owned footsteps must also stop immediately"
582        );
583        assert_eq!(master_gain(), 0.3);
584        assert_eq!(bus_gains(), buses);
585        assert!(!muted());
586
587        let before = stats();
588        assert_eq!(sound.cue_with_outcome(Cue::Fire, 0.5), None);
589        assert_eq!(sound.at_with_outcome(Cue::Click, Vec3::ZERO, 0.2), None);
590        assert_eq!(sound.cue_with_outcome(Cue::Jump, f32::NAN), None);
591        sound.cue(Cue::Jump, 0.5);
592        sound.at(Cue::Fire, Vec3::ZERO, 0.5);
593        sound.walk(vec3(2., 0., 0.), true, true, Surface::Stone, 1.);
594        sound.motor(20., 40., true);
595        assert_eq!(stats(), before);
596        let menu = sound
597            .cue_with_outcome(Cue::Click, 0.2)
598            .unwrap()
599            .handle()
600            .unwrap();
601        sound.reset();
602        assert!(playing(menu) && playing(click) && playing(other_cue) && playing(music));
603        assert!(sound.is_paused());
604        assert_eq!(master_gain(), 0.3);
605        assert_eq!(bus_gains(), buses);
606    }
607
608    #[test]
609    fn resume_discards_paused_travel_and_waits_for_fresh_motor_input() {
610        let mut sound = fresh();
611        sound.walk(Vec3::ZERO, true, true, Surface::Stone, 1.);
612        sound.walk(vec3(0.75, 0., 0.), true, true, Surface::Stone, 1.);
613        sound.motor(10., 40., true);
614        sound.pause();
615        sound.walk(vec3(2., 1., 0.), false, true, Surface::Stone, 1.);
616        sound.motor(40., 40., true);
617        sound.resume();
618        sound.resume();
619        assert_eq!(
620            stats().active,
621            0,
622            "resume has no queued events or cached motor"
623        );
624        sound.walk(vec3(2., 0., 0.), true, true, Surface::Stone, 1.);
625        sound.walk(vec3(2.5, 0., 0.), true, true, Surface::Stone, 1.);
626        assert_eq!(
627            stats().active,
628            0,
629            "no landing or partial stride from before pause"
630        );
631        sound.resume(); // An already resumed controller keeps its current stride.
632        sound.walk(vec3(3., 0., 0.), true, true, Surface::Stone, 1.);
633        assert_eq!(stats().active, 1);
634        sound.motor(20., 40., true);
635        let motor = sound.motor.unwrap();
636        sound.motor(30., 40., true);
637        assert_eq!(sound.motor, Some(motor));
638        assert_eq!(stats().active, 2);
639    }
640
641    #[test]
642    fn reset_clears_release_tails_and_repeats_cadence_without_changing_acoustics() {
643        let mut sound = fresh();
644        let profile = AcousticProfile {
645            gain: 0.4,
646            low_pass_hz: 1200.,
647        };
648        assert!(sound.set_acoustics(profile));
649        sound.walk(Vec3::ZERO, true, true, Surface::Stone, 1.);
650        sound.walk(vec3(1., 0., 0.), true, true, Surface::Stone, 1.);
651        let first = sound.voices.iter().flatten().copied().next().unwrap();
652        let first_params = params(first);
653        sound.walk(vec3(2., 0., 0.), true, true, Surface::Stone, 1.);
654        sound.motor(10., 40., true);
655        sound.motor(10., 40., false);
656        assert!(sound.motor.is_none());
657        assert_eq!(stats().active, 3);
658        sound.reset();
659        sound.reset();
660        assert_eq!(stats().active, 0, "reset does not need an output callback");
661        assert!(!sound.is_paused());
662        assert_eq!(sound.acoustics, profile);
663        sound.walk(vec3(10., 0., 0.), true, true, Surface::Stone, 1.);
664        assert_eq!(stats().active, 0);
665        sound.walk(vec3(11., 0., 0.), true, true, Surface::Stone, 1.);
666        let repeated = sound.voices.iter().flatten().copied().next().unwrap();
667        assert_eq!(params(repeated), first_params);
668        sound.motor(20., 40., true);
669        sound.motor(20., 40., false);
670        sound.pause();
671        assert_eq!(
672            stats().active,
673            0,
674            "pause also clears detached release tails"
675        );
676        sound.reset();
677        assert!(sound.is_paused());
678        sound.resume();
679        assert_eq!(stats().active, 0);
680    }
681
682    #[test]
683    fn outcomes_preserve_mixer_reservation_stealing_and_rejection_reasons() {
684        let mut sound = fresh();
685        mixer_limit(2);
686        AUDIO.with(|cell| {
687            assert!(
688                cell.borrow_mut()
689                    .as_mut()
690                    .unwrap()
691                    .mixer
692                    .set_voice_policy(Some(VoicePolicy {
693                        critical_priority: 5,
694                        reserved_critical: 1
695                    },))
696            );
697        });
698        let cosmetic = sound
699            .cue_with_outcome(Cue::Jump, 0.5)
700            .unwrap()
701            .handle()
702            .unwrap();
703        assert_eq!(
704            sound.cue_with_outcome(Cue::Jump, 0.5),
705            Some(VoiceAdmission::Rejected(
706                VoiceRejection::ReservedForCritical
707            ))
708        );
709        let critical = sound
710            .cue_with_outcome(Cue::Fire, 0.5)
711            .unwrap()
712            .handle()
713            .unwrap();
714        let replacement = sound.cue_with_outcome(Cue::Failure, 0.5).unwrap();
715        assert_eq!(
716            replacement,
717            VoiceAdmission::Stolen {
718                handle: replacement.handle().unwrap(),
719                replaced: cosmetic,
720            }
721        );
722        assert!(!playing(cosmetic));
723        assert!(playing(critical));
724        assert_eq!(
725            sound.cue_with_outcome(Cue::Fire, 0.5),
726            Some(VoiceAdmission::Rejected(VoiceRejection::NoLowerPriority))
727        );
728        assert_eq!(stats().dropped, 2);
729        assert_eq!(stats().stolen, 1);
730        sound.pause();
731        assert_eq!(stats().active, 0);
732    }
733
734    #[test]
735    fn invalid_cues_leave_existing_voices_and_admission_counters_unchanged() {
736        let mut sound = fresh();
737        let handle = sound
738            .cue_with_outcome(Cue::Jump, 0.5)
739            .unwrap()
740            .handle()
741            .unwrap();
742        let before = stats();
743        let rejected = Some(VoiceAdmission::Rejected(VoiceRejection::InvalidParams));
744        for gain in [f32::NAN, f32::INFINITY, -1., 4.1] {
745            assert_eq!(sound.cue_with_outcome(Cue::Fire, gain), rejected);
746            assert_eq!(sound.at_with_outcome(Cue::Fire, Vec3::ZERO, gain), rejected);
747        }
748        for position in [Vec3::splat(f32::NAN), vec3(0., f32::INFINITY, 0.)] {
749            assert_eq!(sound.at_with_outcome(Cue::Fire, position, 0.5), rejected);
750        }
751        assert_eq!(stats(), before);
752        assert!(playing(handle));
753    }
754
755    #[test]
756    fn compatibility_wrappers_keep_gain_bus_spatial_and_priority_settings() {
757        let mut sound = fresh();
758        sound.set_acoustics(AcousticProfile {
759            gain: 0.5,
760            low_pass_hz: 1200.,
761        });
762        sound.cue(Cue::Fire, 0.6);
763        let fire = sound.voices.iter().flatten().copied().next().unwrap();
764        assert_eq!(
765            params(fire),
766            VoiceParams {
767                gain: 0.3,
768                low_pass_hz: 1200.,
769                priority: 5,
770                ..Default::default()
771            }
772        );
773        sound.at(Cue::Click, vec3(1., 2., 3.), 0.4);
774        let spatial = sound.voices.iter().flatten().copied().nth(1).unwrap();
775        assert_eq!(
776            params(spatial),
777            VoiceParams {
778                position: [1., 2., 3.],
779                gain: 0.2,
780                low_pass_hz: 1200.,
781                priority: 3,
782                spatial: Spatial::Attenuated {
783                    min_distance: 1.,
784                    max_distance: 65.,
785                    rolloff: 0.04
786                },
787                ..Default::default()
788            }
789        );
790        let click = sound
791            .cue_with_outcome(Cue::Click, 0.4)
792            .unwrap()
793            .handle()
794            .unwrap();
795        assert_eq!(
796            params(click),
797            VoiceParams {
798                gain: 0.4,
799                priority: 2,
800                bus: Bus::Ui,
801                ..Default::default()
802            }
803        );
804    }
805
806    #[test]
807    fn stale_owned_handles_do_not_stop_other_owners_replacement_voices() {
808        let mut sound = fresh();
809        mixer_limit(1);
810        sound.motor(10., 40., true);
811        let stale = sound.motor.unwrap();
812        let replacement = play(
813            Cue::Fire,
814            VoiceParams {
815                priority: 5,
816                ..Default::default()
817            },
818        )
819        .unwrap();
820        assert!(!playing(stale));
821        sound.pause();
822        sound.reset();
823        assert!(playing(replacement));
824        assert_eq!(stats().active, 1);
825        sound.resume();
826        sound.motor(10., 40., true);
827        assert!(sound.motor.is_none());
828        stop(replacement, 0);
829        sound.motor(10., 40., true);
830        assert!(sound.motor.is_some_and(playing));
831    }
832
833    #[test]
834    fn tracking_reuses_finished_slots_and_handles_the_full_mixer_bound() {
835        let mut sound = fresh();
836        mixer_limit(TRACKED_VOICES);
837        for _ in 0..TRACKED_VOICES * 2 {
838            let voice = sound
839                .cue_with_outcome(Cue::Jump, 0.5)
840                .unwrap()
841                .handle()
842                .unwrap();
843            assert!(stop(voice, 0));
844        }
845        for _ in 0..TRACKED_VOICES {
846            assert!(
847                sound
848                    .cue_with_outcome(Cue::Jump, 0.5)
849                    .unwrap()
850                    .handle()
851                    .is_some()
852            );
853        }
854        assert_eq!(stats().active, TRACKED_VOICES);
855        assert!(
856            sound
857                .cue_with_outcome(Cue::Fire, 0.5)
858                .unwrap()
859                .replaced()
860                .is_some()
861        );
862        sound.reset();
863        assert_eq!(stats().active, 0);
864    }
865
866    #[test]
867    fn muted_or_absent_output_does_not_turn_admission_into_an_audibility_claim() {
868        let mut sound = fresh();
869        assert!(!output_stats().ready, "test never opens a device");
870        let absent = sound
871            .cue_with_outcome(Cue::Jump, 0.5)
872            .unwrap()
873            .handle()
874            .unwrap();
875        super::super::end_frame(0.1);
876        super::super::end_frame(0.1);
877        assert!(
878            !playing(absent),
879            "absent output still skips elapsed samples"
880        );
881        set_muted(true);
882        let muted = sound
883            .cue_with_outcome(Cue::Fire, 0.5)
884            .unwrap()
885            .handle()
886            .unwrap();
887        let mut output = [[1.; 2]; 256];
888        assert!(render(&mut output, SAMPLE_RATE));
889        assert!(output.iter().flatten().all(|sample| *sample == 0.));
890        assert!(playing(muted));
891        sound.pause();
892        sound.reset();
893        sound.resume();
894        assert!(super::super::muted());
895        assert_eq!(stats().active, 0);
896        set_muted(false);
897        let zero_gain = sound
898            .cue_with_outcome(Cue::Jump, 0.)
899            .unwrap()
900            .handle()
901            .unwrap();
902        assert!(playing(zero_gain));
903        assert!(render(&mut output, SAMPLE_RATE));
904        assert!(output.iter().flatten().all(|sample| *sample == 0.));
905    }
906}