Skip to main content

roxlap_audio/
cavity.rs

1//! AU.1 — cavity estimation: reverb parameters from the space around
2//! the listener.
3//!
4//! A fixed golden-spiral fan of rays probes the free path in every
5//! direction ([`probe_cavity`], pure and deterministic); the mean free
6//! path reads as room size and the fraction of rays escaping the probe
7//! radius as openness. [`CavityEstimator`] wraps the probe with the
8//! heavy `(3·old + new) / 4`-style smoothing the prior art ships
9//! (Sound Filters, Teardown): the environment estimate converges over
10//! seconds and players read the lag as natural room acoustics, not as
11//! a parameter glitch.
12//!
13//! Cadence: the host calls [`CavityEstimator::update`] at a low rate
14//! (~2 Hz per the entry doc) — NOT per frame. Smoothing strength is
15//! per *update*, so a faster cadence converges faster.
16
17use glam::DVec3;
18use roxlap_scene::Scene;
19
20/// Tuning knobs for the cavity probe + the reverb mapping.
21#[derive(Debug, Clone, PartialEq)]
22pub struct CavityConfig {
23    /// Rays in the golden-spiral fan. Default `32` (the Sound Physics
24    /// bounce budget). Clamped to at least 4.
25    pub rays: u32,
26    /// Probe radius, world/voxel units: rays that reach it without a
27    /// hit count as *escaped* (open sky / huge space). Also the free
28    /// path a miss contributes to the mean. Deliberately SEPARATE from
29    /// the occlusion budget (`AcousticsConfig::max_distance`, default
30    /// 128): occlusion reaches as far as sources are audible, the
31    /// reverb probe only needs the local room.
32    pub max_ray_dist: f64,
33    /// Reverb feedback (decay) in the smallest enclosed space.
34    pub min_feedback: f32,
35    /// Reverb feedback when the **enclosed** free path (walls actually
36    /// hit — escaped rays don't inflate room size) reaches
37    /// [`max_ray_dist`](Self::max_ray_dist).
38    pub max_feedback: f32,
39    /// Wet mix in a fully enclosed space.
40    pub max_wet: f32,
41    /// Openness at (and beyond) which the wet mix reaches zero. A
42    /// listener standing on open ground always has ~half the fan in
43    /// the ground, so raw openness tops out near `0.5` outdoors — this
44    /// threshold makes that read as *fully dry* instead of half-wet.
45    /// Default `0.5`; a sealed cavern (openness `0`) is unaffected.
46    pub outdoor_openness: f32,
47    /// Reverb damping (high-frequency loss), passed through to the
48    /// backend unmodified. Per-material damping is future work.
49    pub damping: f32,
50    /// Fraction of the OLD smoothed value kept per
51    /// [`CavityEstimator::update`] — `0.75` is the prior art's
52    /// `(3·old + new) / 4`. `0` disables smoothing.
53    pub smoothing: f32,
54}
55
56impl Default for CavityConfig {
57    fn default() -> Self {
58        Self {
59            rays: 32,
60            max_ray_dist: 64.0,
61            min_feedback: 0.35,
62            max_feedback: 0.88,
63            max_wet: 0.5,
64            outdoor_openness: 0.5,
65            damping: 0.4,
66            smoothing: 0.75,
67        }
68    }
69}
70
71/// Raw (unsmoothed) result of one [`probe_cavity`] fan.
72#[derive(Debug, Clone, Copy, PartialEq)]
73pub struct CavityProbe {
74    /// Mean free path across the WHOLE fan, world/voxel units — escaped
75    /// rays contribute [`CavityConfig::max_ray_dist`]. Diagnostic; the
76    /// reverb mapping does not use it (an open sky would masquerade as
77    /// a huge room).
78    pub mean_free_path: f32,
79    /// Mean free path across the rays that actually HIT a wall — the
80    /// room-size signal driving reverb feedback. Escaped rays don't
81    /// inflate it: on open ground only the short ground hits count, so
82    /// the "room" reads tiny. [`CavityConfig::max_ray_dist`] when no
83    /// ray hit anything (unbounded space; the wet mix is zero there
84    /// anyway).
85    pub enclosed_free_path: f32,
86    /// Fraction of rays that escaped the probe radius, `0..=1` —
87    /// `0` = sealed cavern, `~0.5` = standing on open ground.
88    pub openness: f32,
89}
90
91/// Smoothed reverb parameters for the listener's surroundings,
92/// produced by [`CavityEstimator::update`]. Feed the reverb fields to
93/// the backend with long tweens (~1 s).
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct ListenerAcoustics {
96    /// Smoothed mean free path (room size), world/voxel units.
97    pub mean_free_path: f32,
98    /// Smoothed openness, `0..=1`.
99    pub openness: f32,
100    /// Reverb feedback (decay): bigger enclosed space ⇒ longer tail.
101    pub reverb_feedback: f32,
102    /// Reverb damping, straight from [`CavityConfig::damping`].
103    pub reverb_damping: f32,
104    /// Reverb wet mix, `0..=1`: scaled down by openness so outdoor
105    /// sound stays dry.
106    pub reverb_mix: f32,
107}
108
109/// Probe the space around `listener`: cast the golden-spiral fan and
110/// reduce it to a [`CavityProbe`]. Pure and deterministic — the fan is
111/// a fixed direction set, so tests pin exact values and the estimator
112/// can round-robin freely.
113///
114/// Two caveats:
115/// - A listener **inside solid** (camera clipped into rock) sees every
116///   ray hit at `t ≈ 0` and reads as a tiny sealed box (max wet, min
117///   feedback). Hosts whose listener can clip should guard or nudge
118///   the probe point out of solid first.
119/// - Rays go through `Scene::raycast`'s own march, NOT the
120///   chunk-borrow-cached thickness march `path_thickness` uses — when
121///   profiling, the fan's cost profile is `raycast`'s.
122#[must_use]
123pub fn probe_cavity(scene: &Scene, listener: DVec3, cfg: &CavityConfig) -> CavityProbe {
124    let rays = cfg.rays.max(4);
125    let mut path_sum = 0.0f64;
126    let mut hit_sum = 0.0f64;
127    let mut escaped = 0u32;
128    for k in 0..rays {
129        let dir = golden_spiral_dir(k, rays);
130        match scene.raycast(listener, dir, cfg.max_ray_dist) {
131            Some(hit) => {
132                path_sum += hit.t;
133                hit_sum += hit.t;
134            }
135            None => {
136                path_sum += cfg.max_ray_dist;
137                escaped += 1;
138            }
139        }
140    }
141    let hits = rays - escaped;
142    #[allow(clippy::cast_possible_truncation)]
143    CavityProbe {
144        mean_free_path: (path_sum / f64::from(rays)) as f32,
145        enclosed_free_path: if hits == 0 {
146            cfg.max_ray_dist as f32
147        } else {
148            (hit_sum / f64::from(hits)) as f32
149        },
150        openness: escaped as f32 / rays as f32,
151    }
152}
153
154/// Direction `k` of an `n`-point golden-spiral sphere covering — the
155/// standard even covering of the unit sphere (unit length by
156/// construction).
157fn golden_spiral_dir(k: u32, n: u32) -> DVec3 {
158    const GOLDEN_ANGLE: f64 = 2.399_963_229_728_653; // π(3 − √5)
159    let z = 1.0 - 2.0 * (f64::from(k) + 0.5) / f64::from(n);
160    let r = (1.0 - z * z).sqrt();
161    let phi = GOLDEN_ANGLE * f64::from(k);
162    DVec3::new(r * phi.cos(), r * phi.sin(), z)
163}
164
165/// Stateful cavity estimator: [`probe_cavity`] plus the prior-art
166/// exponential smoothing, mapped to reverb parameters. One per
167/// listener; call [`update`](Self::update) at ~2 Hz and
168/// [`reset`](Self::reset) on teleports.
169#[derive(Debug, Clone)]
170pub struct CavityEstimator {
171    cfg: CavityConfig,
172    smoothed: Option<CavityProbe>,
173}
174
175impl CavityEstimator {
176    /// A fresh estimator; the first [`update`](Self::update) seeds the
177    /// smoothed state from the raw probe (no fade-in from a wrong
178    /// initial guess).
179    #[must_use]
180    pub fn new(cfg: CavityConfig) -> Self {
181        Self {
182            cfg,
183            smoothed: None,
184        }
185    }
186
187    /// The configuration this estimator was built with.
188    #[must_use]
189    pub fn config(&self) -> &CavityConfig {
190        &self.cfg
191    }
192
193    /// Drop the smoothed state — the next [`update`](Self::update)
194    /// re-seeds from the raw probe. Call on listener teleports so a
195    /// cavern's tail doesn't follow the player through a menu warp.
196    pub fn reset(&mut self) {
197        self.smoothed = None;
198    }
199
200    /// Probe, smooth, and map to reverb parameters.
201    pub fn update(&mut self, scene: &Scene, listener: DVec3) -> ListenerAcoustics {
202        let raw = probe_cavity(scene, listener, &self.cfg);
203        let s = self.cfg.smoothing.clamp(0.0, 1.0);
204        let sm = match self.smoothed {
205            None => raw,
206            Some(prev) => CavityProbe {
207                mean_free_path: prev.mean_free_path * s + raw.mean_free_path * (1.0 - s),
208                enclosed_free_path: prev.enclosed_free_path * s
209                    + raw.enclosed_free_path * (1.0 - s),
210                openness: prev.openness * s + raw.openness * (1.0 - s),
211            },
212        };
213        self.smoothed = Some(sm);
214        self.params(sm)
215    }
216
217    /// Map a (smoothed) probe to reverb parameters — split out so the
218    /// mapping itself is testable without a scene.
219    ///
220    /// Room size comes from the **enclosed** free path only (escaped
221    /// rays must not read open sky as a huge hall), and the wet mix
222    /// hits zero at [`CavityConfig::outdoor_openness`] — a listener on
223    /// open ground (raw openness ~0.5, the ground owns the lower
224    /// hemisphere) is fully dry, not half-wet.
225    #[allow(clippy::cast_possible_truncation)]
226    fn params(&self, p: CavityProbe) -> ListenerAcoustics {
227        let size_norm =
228            (f64::from(p.enclosed_free_path) / self.cfg.max_ray_dist).clamp(0.0, 1.0) as f32;
229        let outdoor = self.cfg.outdoor_openness.max(1e-6);
230        let enclosure = ((outdoor - p.openness) / outdoor).clamp(0.0, 1.0);
231        ListenerAcoustics {
232            mean_free_path: p.mean_free_path,
233            openness: p.openness,
234            reverb_feedback: self.cfg.min_feedback
235                + (self.cfg.max_feedback - self.cfg.min_feedback) * size_norm,
236            reverb_damping: self.cfg.damping,
237            reverb_mix: self.cfg.max_wet * enclosure,
238        }
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245    use glam::IVec3;
246    use roxlap_scene::{GridTransform, VoxColor};
247
248    const STONE: VoxColor = VoxColor(0x80_66_77_88);
249
250    /// A hollow cubic room of inner side `side`, centred at `c` (cell
251    /// coords), inside one identity grid; returns the scene + the room
252    /// centre as a world point.
253    fn room(side: i32, c: IVec3) -> (Scene, DVec3) {
254        let mut scene = Scene::new();
255        let id = scene.add_grid(GridTransform::identity());
256        let g = scene.grid_mut(id).expect("grid just added");
257        let h = side / 2;
258        let shell = 2;
259        g.set_rect(
260            c - IVec3::splat(h + shell),
261            c + IVec3::splat(h + shell),
262            Some(STONE),
263        );
264        g.set_rect(c - IVec3::splat(h), c + IVec3::splat(h), None);
265        let centre = DVec3::new(
266            f64::from(c.x) + 0.5,
267            f64::from(c.y) + 0.5,
268            f64::from(c.z) + 0.5,
269        );
270        (scene, centre)
271    }
272
273    #[test]
274    fn empty_scene_is_fully_open() {
275        let scene = Scene::new();
276        let cfg = CavityConfig::default();
277        let p = probe_cavity(&scene, DVec3::new(64.0, 64.0, 128.0), &cfg);
278        assert_eq!(p.openness, 1.0);
279        #[allow(clippy::cast_possible_truncation)]
280        let cap = cfg.max_ray_dist as f32;
281        assert!((p.mean_free_path - cap).abs() < 1e-4);
282        assert!((p.enclosed_free_path - cap).abs() < 1e-4, "no-hit sentinel");
283        // Mapping: unbounded space is bone dry regardless of feedback.
284        let a = CavityEstimator::new(cfg).params(p);
285        assert_eq!(a.reverb_mix, 0.0);
286    }
287
288    #[test]
289    fn bigger_room_reads_bigger_and_both_are_sealed() {
290        let cfg = CavityConfig::default();
291        let (small, sc) = room(8, IVec3::new(64, 64, 128));
292        let (big, bc) = room(40, IVec3::new(64, 64, 128));
293        let ps = probe_cavity(&small, sc, &cfg);
294        let pb = probe_cavity(&big, bc, &cfg);
295        assert_eq!(ps.openness, 0.0, "small room is sealed");
296        assert_eq!(pb.openness, 0.0, "big room is sealed");
297        assert!(
298            pb.mean_free_path > ps.mean_free_path * 2.0,
299            "room size ordering: big {} vs small {}",
300            pb.mean_free_path,
301            ps.mean_free_path
302        );
303
304        // Mapping: bigger sealed room ⇒ longer decay; both fully wet.
305        let est = CavityEstimator::new(cfg.clone());
306        let a_small = est.params(ps);
307        let a_big = est.params(pb);
308        assert!(a_big.reverb_feedback > a_small.reverb_feedback);
309        assert!((a_small.reverb_mix - cfg.max_wet).abs() < 1e-6);
310        assert!(a_small.reverb_feedback >= cfg.min_feedback);
311        assert!(a_big.reverb_feedback <= cfg.max_feedback);
312    }
313
314    #[test]
315    fn open_ground_is_much_drier_than_a_cavern() {
316        let cfg = CavityConfig::default();
317        // Flat ground: solid below z = 200, listener standing on it.
318        let mut scene = Scene::new();
319        let id = scene.add_grid(GridTransform::identity());
320        let g = scene.grid_mut(id).expect("grid");
321        g.set_rect(
322            IVec3::new(0, 0, 200),
323            IVec3::new(255, 255, 220),
324            Some(STONE),
325        );
326        let outdoors = probe_cavity(&scene, DVec3::new(128.0, 128.0, 198.0), &cfg);
327        assert!(
328            outdoors.openness > 0.4,
329            "standing on open ground, roughly the upper hemisphere escapes: {}",
330            outdoors.openness
331        );
332        // The room-size signal must NOT be inflated by the sky: only
333        // the short ground hits count.
334        assert!(
335            outdoors.enclosed_free_path < outdoors.mean_free_path * 0.6,
336            "enclosed path ({}) must ignore escaped rays (mean {})",
337            outdoors.enclosed_free_path,
338            outdoors.mean_free_path
339        );
340
341        let (cavern, cc) = room(40, IVec3::new(64, 64, 128));
342        let inside = probe_cavity(&cavern, cc, &cfg);
343        let est = CavityEstimator::new(cfg.clone());
344        let dry = est.params(outdoors);
345        let wet = est.params(inside);
346        // ABSOLUTE bounds — a relative comparison would let "audibly
347        // reverberant outdoors" hide behind an even wetter cavern.
348        assert!(
349            dry.reverb_mix < 0.05,
350            "open ground must be bone dry, got mix {}",
351            dry.reverb_mix
352        );
353        assert!(
354            dry.reverb_feedback < cfg.min_feedback + 0.15,
355            "open ground must not read as a big hall: feedback {}",
356            dry.reverb_feedback
357        );
358        assert!(
359            wet.reverb_mix > cfg.max_wet * 0.8,
360            "sealed cavern stays wet: {}",
361            wet.reverb_mix
362        );
363    }
364
365    #[test]
366    fn smoothing_seeds_raw_then_converges_monotonically() {
367        let cfg = CavityConfig::default();
368        let (small, sc) = room(8, IVec3::new(64, 64, 128));
369        let (big, bc) = room(40, IVec3::new(64, 64, 128));
370
371        let mut est = CavityEstimator::new(cfg.clone());
372        // First update seeds from raw — no fade-in from zero.
373        let first = est.update(&big, bc);
374        let raw_big = probe_cavity(&big, bc, &cfg);
375        assert!((first.mean_free_path - raw_big.mean_free_path).abs() < 1e-6);
376
377        // "Teleport" into the small room WITHOUT reset: the estimate
378        // must walk down monotonically toward the small-room value.
379        let raw_small = probe_cavity(&small, sc, &cfg);
380        let mut prev = first.mean_free_path;
381        for step in 0..12 {
382            let a = est.update(&small, sc);
383            assert!(
384                a.mean_free_path < prev,
385                "step {step}: estimate must decrease ({} vs {prev})",
386                a.mean_free_path
387            );
388            prev = a.mean_free_path;
389        }
390        assert!(
391            (prev - raw_small.mean_free_path).abs() < 2.0,
392            "after 12 updates the estimate ({prev}) nears the raw small-room value ({})",
393            raw_small.mean_free_path
394        );
395
396        // reset() re-seeds instantly.
397        est.reset();
398        let after = est.update(&big, bc);
399        assert!((after.mean_free_path - raw_big.mean_free_path).abs() < 1e-6);
400    }
401
402    #[test]
403    fn deterministic() {
404        let cfg = CavityConfig::default();
405        let (scene, c) = room(16, IVec3::new(64, 64, 128));
406        assert_eq!(probe_cavity(&scene, c, &cfg), probe_cavity(&scene, c, &cfg));
407    }
408}