Skip to main content

roxlap_audio/
lib.rs

1//! Voxel-aware acoustics for the roxlap engine (stage AU —
2//! `docs/porting/PORTING-AUDIO.md`).
3//!
4//! This crate computes **acoustic parameters** from the voxel world; it
5//! deliberately owns no audio device and spawns no audio thread. The
6//! host feeds the numbers into whatever playback stack it uses (the
7//! optional `kira` backend lands in AU.2): per sound source an
8//! occlusion-driven gain + lowpass cutoff + reverb send, and (AU.1) per
9//! listener a cavity-driven reverb feedback/mix.
10//!
11//! The occlusion model follows the convergent games recipe (Sound
12//! Physics, Teardown, Overwatch — see the entry doc): a small fan of
13//! rays from the source to the listener, each accumulating the **solid
14//! path length** it crosses (voxel units, exact segment lengths from a
15//! DDA march — not a boolean hit test), averaged into a `0..=1`
16//! *transmission*. Thickness matters: one voxel of wall muffles less
17//! than five, and a doorway passes some rays untouched, so sound leaks
18//! around corners instead of gating on/off.
19//!
20//! Everything here is pure and deterministic — the jitter fan is a
21//! fixed ring, not RNG — so tests pin exact values and hosts can call
22//! it from any thread.
23
24use glam::{DVec3, IVec3};
25use roxlap_scene::Scene;
26
27mod backend;
28mod cavity;
29pub mod synth;
30
31#[cfg(feature = "kira")]
32mod kira_out;
33
34pub use backend::{AudioOut, SoundKey, SourceId, SourcePool};
35pub use cavity::{probe_cavity, CavityConfig, CavityEstimator, CavityProbe, ListenerAcoustics};
36pub use synth::SoundBuffer;
37
38#[cfg(feature = "kira")]
39pub use kira_out::KiraAudio;
40
41/// Tuning knobs for [`source_acoustics`]. The defaults are the cave-demo
42/// tuning; every field is plain data so hosts can persist or lerp them.
43#[derive(Debug, Clone, PartialEq)]
44pub struct AcousticsConfig {
45    /// Jittered rays per source→listener query, **including** the direct
46    /// ray. `1` = direct only; the default `9` (direct + an 8-point ring)
47    /// matches the Sound Physics budget and gives soft doorway
48    /// transitions. Clamped to at least 1.
49    pub rays: u32,
50    /// Radius (world/voxel units) of the jitter ring around the source,
51    /// perpendicular to the source→listener axis. Roughly "how big is
52    /// the emitter": bigger radii leak more around thin edges.
53    pub jitter_radius: f64,
54    /// Per-voxel absorption: a ray crossing `t` voxels of solid keeps
55    /// `exp(-absorption · t)` of its energy. `0.25` ⇒ ~78% through a
56    /// 1-voxel wall, ~29% through 5.
57    pub absorption_per_voxel: f64,
58    /// Lowpass cutoff at full transmission (unoccluded), Hz.
59    pub open_cutoff_hz: f32,
60    /// Lowpass cutoff at zero transmission (fully buried), Hz.
61    pub occluded_cutoff_hz: f32,
62    /// Gain applied at zero transmission, decibels (negative). Scales
63    /// linearly with `1 - transmission`; distance attenuation is NOT
64    /// included (that is the spatial backend's job).
65    pub max_occlusion_db: f32,
66    /// Fraction of the occlusion gain also applied to the reverb send —
67    /// a buried source still excites the room, just less. `0.5` halves
68    /// the dB loss on the send relative to the dry path.
69    pub send_occlusion_frac: f32,
70    /// Hard cap on the marched source→listener distance (world units);
71    /// beyond it no rays are cast and the source reports
72    /// [`SourceAcoustics::clear`] — distance attenuation is the spatial
73    /// backend's job, and a far-away source in open air must NOT come
74    /// back muffled. Bounds the DDA cost.
75    pub max_distance: f64,
76}
77
78impl Default for AcousticsConfig {
79    fn default() -> Self {
80        Self {
81            rays: 9,
82            jitter_radius: 1.5,
83            absorption_per_voxel: 0.25,
84            open_cutoff_hz: 20_000.0,
85            occluded_cutoff_hz: 800.0,
86            max_occlusion_db: -24.0,
87            send_occlusion_frac: 0.5,
88            max_distance: 128.0,
89        }
90    }
91}
92
93/// Occlusion-driven playback parameters for one source→listener pair,
94/// produced by [`source_acoustics`]. Feed them to the playback layer
95/// with short tweens (~120 ms) — never as raw jumps.
96#[derive(Debug, Clone, Copy, PartialEq)]
97pub struct SourceAcoustics {
98    /// Average transmitted energy across the ray fan, `0..=1`
99    /// (`1` = clear line of sound, `0` = buried).
100    pub transmission: f32,
101    /// Occlusion gain, decibels (`0` when clear, down to
102    /// [`AcousticsConfig::max_occlusion_db`]). Excludes distance
103    /// attenuation.
104    pub gain_db: f32,
105    /// Lowpass cutoff for the muffling filter, Hz (log-interpolated
106    /// between the config's occluded and open cutoffs).
107    pub lowpass_cutoff_hz: f32,
108    /// Gain for this source's reverb send, decibels.
109    pub reverb_send_db: f32,
110}
111
112impl SourceAcoustics {
113    /// The parameters of a fully unoccluded source under `cfg`.
114    #[must_use]
115    pub fn clear(cfg: &AcousticsConfig) -> Self {
116        Self {
117            transmission: 1.0,
118            gain_db: 0.0,
119            lowpass_cutoff_hz: cfg.open_cutoff_hz,
120            reverb_send_db: 0.0,
121        }
122    }
123}
124
125/// Total **solid path length** (world/voxel units) the straight segment
126/// `a → b` crosses, summed over every grid in the scene. This is the
127/// thickness building block under [`source_acoustics`]: exact per-cell
128/// segment lengths from a voxel DDA against [`roxlap_scene::Grid::voxel_solid`]
129/// (a diagonal crossing of a 1-voxel wall correctly reports ~√2).
130///
131/// Grid transforms are honoured the same way `Scene::raycast` does it:
132/// the segment is rebased into each grid's local frame (rotation is an
133/// isometry, so lengths stay world-true). Cost is O(segment length in
134/// voxels) per grid — audio queries are short and infrequent, so no
135/// chunk-level skip is attempted (noted future optimisation).
136#[must_use]
137pub fn path_thickness(scene: &Scene, a: DVec3, b: DVec3) -> f64 {
138    let mut total = 0.0;
139    for (_, grid) in scene.grids() {
140        let inv = grid.transform.rotation.inverse();
141        let la = inv * (a - grid.transform.origin);
142        let lb = inv * (b - grid.transform.origin);
143        total += grid_thickness(grid, la, lb);
144    }
145    total
146}
147
148/// Solid path length of the grid-local segment `a → b` through one
149/// grid: an Amanatides–Woo cell walk accumulating the in-cell segment
150/// length wherever the voxel is solid. Consecutive steps share a
151/// one-entry chunk borrow (one HashMap probe per crossed chunk, not
152/// per voxel — the [`roxlap_scene::Grid::chunk_voxel_solid`] pattern).
153///
154/// Caveat: voxlap's bedrock placeholder plane (chunk-local z = 255 of
155/// otherwise-empty chunks) reads as solid, so a segment grazing the
156/// world bottom accumulates it as real thickness. Keep acoustic
157/// endpoints above the bedrock plane (every demo does).
158fn grid_thickness(grid: &roxlap_scene::Grid, a: DVec3, b: DVec3) -> f64 {
159    let seg = b - a;
160    let len = seg.length();
161    if len < 1e-9 {
162        return 0.0;
163    }
164    let dir = seg / len;
165
166    #[allow(clippy::cast_possible_truncation)]
167    let mut cell = IVec3::new(a.x.floor() as i32, a.y.floor() as i32, a.z.floor() as i32);
168
169    // Per-axis DDA state: t at the next cell boundary and t per cell.
170    let mut t_max = [f64::INFINITY; 3];
171    let mut t_delta = [f64::INFINITY; 3];
172    let mut step = [0i32; 3];
173    for ax in 0..3 {
174        let d = dir[ax];
175        if d.abs() < 1e-12 {
176            continue;
177        }
178        step[ax] = if d > 0.0 { 1 } else { -1 };
179        t_delta[ax] = 1.0 / d.abs();
180        let cell_f = f64::from(cell[ax]);
181        let next_boundary = if d > 0.0 { cell_f + 1.0 } else { cell_f };
182        t_max[ax] = (next_boundary - a[ax]) / d;
183    }
184
185    let mut thickness = 0.0;
186    let mut t_prev = 0.0;
187    // One-entry chunk cache: consecutive DDA cells overwhelmingly stay
188    // in the same 128×128×256 chunk, so the HashMap probe amortises to
189    // one per crossed chunk.
190    let mut cached_idx = IVec3::MAX;
191    // Inferred `Option<&Vxl>` (roxlap-scene doesn't re-export the type).
192    let mut cached_chunk = None;
193    // Step budget: a segment of length L crosses at most ~L+1 boundaries
194    // per axis. The +8 absorbs boundary-epsilon jitter.
195    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
196    let max_steps = (len * 3.0) as u32 + 8;
197    for _ in 0..max_steps {
198        let ax = min_axis(&t_max);
199        let t_next = t_max[ax].min(len);
200        let (chunk_idx, in_chunk) = roxlap_scene::voxel_split(cell);
201        if chunk_idx != cached_idx {
202            cached_idx = chunk_idx;
203            cached_chunk = grid.chunk(chunk_idx);
204        }
205        let solid =
206            cached_chunk.is_some_and(|vxl| roxlap_scene::Grid::chunk_voxel_solid(vxl, in_chunk));
207        if solid {
208            thickness += t_next - t_prev;
209        }
210        if t_max[ax] >= len {
211            break;
212        }
213        t_prev = t_next;
214        cell[ax] += step[ax];
215        t_max[ax] += t_delta[ax];
216    }
217    thickness
218}
219
220/// Index of the smallest component (the axis the DDA crosses next).
221fn min_axis(t: &[f64; 3]) -> usize {
222    if t[0] <= t[1] && t[0] <= t[2] {
223        0
224    } else if t[1] <= t[2] {
225        1
226    } else {
227        2
228    }
229}
230
231/// Occlusion parameters for one source heard from `listener`: a fan of
232/// [`AcousticsConfig::rays`] thickness rays (the direct segment plus a
233/// fixed jitter ring around the **source**, perpendicular to the
234/// source→listener axis), each converted to transmitted energy
235/// `exp(-absorption · thickness)` and averaged.
236///
237/// Deterministic — the ring is fixed 45° spokes, no RNG — and pure, so
238/// hosts may round-robin sources across ticks freely (the entry doc's
239/// ~4 Hz per source cadence).
240#[must_use]
241pub fn source_acoustics(
242    scene: &Scene,
243    source: DVec3,
244    listener: DVec3,
245    cfg: &AcousticsConfig,
246) -> SourceAcoustics {
247    let seg = listener - source;
248    let dist = seg.length();
249    // Beyond the march budget (or on top of the listener): report
250    // CLEAR, not buried — the backend's distance attenuation owns far
251    // sources, and clamping to "muffled" would put a step function at
252    // the boundary (a far source in open air is quiet, not lowpassed).
253    if dist > cfg.max_distance || dist < 1e-9 {
254        return SourceAcoustics::clear(cfg);
255    }
256    let dir = seg / dist;
257
258    // A stable perpendicular basis for the jitter ring.
259    let helper = if dir.x.abs() < 0.9 {
260        DVec3::X
261    } else {
262        DVec3::Y
263    };
264    let u = dir.cross(helper).normalize();
265    let v = dir.cross(u);
266
267    let rays = cfg.rays.max(1);
268    let mut energy = 0.0f64;
269    for i in 0..rays {
270        let origin = if i == 0 {
271            source
272        } else {
273            // Fixed ring: spoke k of (rays - 1) around the source.
274            let ang = std::f64::consts::TAU * f64::from(i - 1) / f64::from(rays - 1);
275            source + (u * ang.cos() + v * ang.sin()) * cfg.jitter_radius
276        };
277        let t = path_thickness(scene, origin, listener);
278        energy += (-cfg.absorption_per_voxel * t).exp();
279    }
280    #[allow(clippy::cast_possible_truncation)]
281    let transmission = (energy / f64::from(rays)).clamp(0.0, 1.0) as f32;
282
283    // Log-space cutoff interpolation: T = 1 ⇒ open, T = 0 ⇒ occluded.
284    let ratio = cfg.open_cutoff_hz / cfg.occluded_cutoff_hz;
285    let lowpass_cutoff_hz = cfg.occluded_cutoff_hz * ratio.powf(transmission);
286    let gain_db = cfg.max_occlusion_db * (1.0 - transmission);
287    SourceAcoustics {
288        transmission,
289        gain_db,
290        lowpass_cutoff_hz,
291        reverb_send_db: gain_db * cfg.send_occlusion_frac,
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use roxlap_scene::{GridTransform, VoxColor};
299
300    const STONE: VoxColor = VoxColor(0x80_66_77_88);
301
302    /// A scene with one identity grid; `build` shapes it.
303    fn scene_with(build: impl FnOnce(&mut roxlap_scene::Grid)) -> Scene {
304        let mut scene = Scene::new();
305        let id = scene.add_grid(GridTransform::identity());
306        build(scene.grid_mut(id).expect("grid just added"));
307        scene
308    }
309
310    /// A y/z-spanning wall of `thick` voxels starting at `x0`, with a
311    /// generous extent so jitter rays can't slip around the edges.
312    fn wall(grid: &mut roxlap_scene::Grid, x0: i32, thick: i32) {
313        grid.set_rect(
314            IVec3::new(x0, 0, 100),
315            IVec3::new(x0 + thick - 1, 127, 180),
316            Some(STONE),
317        );
318    }
319
320    #[test]
321    fn open_air_is_clear() {
322        let scene = scene_with(|_| {});
323        let cfg = AcousticsConfig::default();
324        let a = source_acoustics(
325            &scene,
326            DVec3::new(10.0, 40.0, 140.0),
327            DVec3::new(60.0, 40.0, 140.0),
328            &cfg,
329        );
330        assert_eq!(a, SourceAcoustics::clear(&cfg));
331    }
332
333    #[test]
334    fn thickness_is_exact_for_perpendicular_and_diagonal_crossings() {
335        let scene = scene_with(|g| wall(g, 30, 3));
336        // Perpendicular: exactly the wall's 3 voxels.
337        let t = path_thickness(
338            &scene,
339            DVec3::new(10.0, 40.5, 140.5),
340            DVec3::new(60.0, 40.5, 140.5),
341        );
342        assert!((t - 3.0).abs() < 1e-6, "perpendicular thickness: {t}");
343        // 45° in the xy plane: path length through 3 voxels of x-extent
344        // is 3·√2.
345        let t = path_thickness(
346            &scene,
347            DVec3::new(10.0, 20.5, 140.5),
348            DVec3::new(60.0, 70.5, 140.5),
349        );
350        assert!((t - 3.0 * 2.0f64.sqrt()).abs() < 1e-6, "diagonal: {t}");
351    }
352
353    #[test]
354    fn thicker_walls_muffle_monotonically() {
355        let cfg = AcousticsConfig::default();
356        let src = DVec3::new(10.0, 64.0, 140.5);
357        let dst = DVec3::new(60.0, 64.0, 140.5);
358        let mut prev = 1.0f32;
359        for thick in [1, 2, 5] {
360            let scene = scene_with(|g| wall(g, 30, thick));
361            let a = source_acoustics(&scene, src, dst, &cfg);
362            assert!(
363                a.transmission < prev,
364                "{thick}-voxel wall must transmit less than the previous ({} vs {prev})",
365                a.transmission
366            );
367            assert!(a.gain_db < 0.0 && a.gain_db >= cfg.max_occlusion_db);
368            assert!(a.lowpass_cutoff_hz < cfg.open_cutoff_hz);
369            assert!(a.lowpass_cutoff_hz > cfg.occluded_cutoff_hz);
370            prev = a.transmission;
371        }
372    }
373
374    #[test]
375    fn doorway_leaks_more_than_sealed_wall() {
376        let src = DVec3::new(10.0, 64.0, 140.5);
377        let dst = DVec3::new(60.0, 64.0, 140.5);
378        let cfg = AcousticsConfig::default();
379
380        let sealed = scene_with(|g| wall(g, 30, 2));
381        let sealed_a = source_acoustics(&sealed, src, dst, &cfg);
382
383        // Same wall with a slot punched just off the direct line. The
384        // ring converges toward the listener, so at the wall plane
385        // (40% of the way) the ±1.5 jitter has shrunk to ±0.9 voxels:
386        // the slot at cell y=63 (z 139..141) is inside that reach for
387        // the three −y spokes while the direct ray still hits rock.
388        let doorway = scene_with(|g| {
389            wall(g, 30, 2);
390            g.set_rect(IVec3::new(30, 63, 139), IVec3::new(31, 63, 141), None);
391        });
392        let door_a = source_acoustics(&doorway, src, dst, &cfg);
393        assert!(
394            door_a.transmission > sealed_a.transmission,
395            "doorway must leak: {} vs sealed {}",
396            door_a.transmission,
397            sealed_a.transmission
398        );
399        assert!(
400            door_a.transmission < 1.0,
401            "off-axis doorway is not fully clear"
402        );
403    }
404
405    #[test]
406    fn cross_chunk_wall_counts_once() {
407        // Wall straddling the x = 128 chunk seam: thickness must not
408        // double-count or drop the seam cell.
409        let scene = scene_with(|g| {
410            g.set_rect(
411                IVec3::new(126, 0, 100),
412                IVec3::new(129, 255, 180),
413                Some(STONE),
414            );
415        });
416        let t = path_thickness(
417            &scene,
418            DVec3::new(100.0, 64.5, 140.5),
419            DVec3::new(160.0, 64.5, 140.5),
420        );
421        assert!((t - 4.0).abs() < 1e-6, "seam-straddling wall: {t}");
422    }
423
424    #[test]
425    fn cross_grid_thickness_sums() {
426        // Two grids, one wall each, both crossed by the same segment.
427        let mut scene = Scene::new();
428        let id_a = scene.add_grid(GridTransform::identity());
429        wall(scene.grid_mut(id_a).expect("grid a"), 20, 2);
430        let id_b = scene.add_grid(GridTransform::at(DVec3::new(20.0, 0.0, 0.0)));
431        wall(scene.grid_mut(id_b).expect("grid b"), 20, 2); // world x = 40..42
432        let t = path_thickness(
433            &scene,
434            DVec3::new(10.0, 64.5, 140.5),
435            DVec3::new(60.0, 64.5, 140.5),
436        );
437        assert!((t - 4.0).abs() < 1e-6, "two 2-voxel walls: {t}");
438    }
439
440    #[test]
441    fn beyond_max_distance_reports_clear_not_buried() {
442        // Distance attenuation belongs to the spatial backend: past the
443        // march budget a source must NOT come back muffled (that would
444        // put a lowpass step function at the boundary).
445        let scene = scene_with(|g| wall(g, 30, 5));
446        let cfg = AcousticsConfig::default();
447        let a = source_acoustics(
448            &scene,
449            DVec3::new(10.0, 64.0, 140.5),
450            DVec3::new(10.0 + cfg.max_distance + 10.0, 64.0, 140.5),
451            &cfg,
452        );
453        assert_eq!(a, SourceAcoustics::clear(&cfg));
454    }
455
456    #[test]
457    fn rotated_grid_thickness_is_world_true() {
458        use glam::{DQuat, DVec3};
459        // A grid rotated 90° about world Z, placed so its local wall
460        // (3 voxels along local x) lands across the world-Y axis: the
461        // rebased segment must report the same world-true 3 voxels.
462        let mut scene = Scene::new();
463        let rot = DQuat::from_rotation_z(std::f64::consts::FRAC_PI_2);
464        let id = scene.add_grid(GridTransform {
465            origin: DVec3::new(0.0, 0.0, 0.0),
466            rotation: rot,
467            voxel_world_size: 1.0,
468        });
469        wall(scene.grid_mut(id).expect("rotated grid"), 30, 3);
470        // Local +x maps to world +y: the local x = 30..33 wall lies at
471        // world y = 30..33 (local y spans map to world -x). Probe along
472        // world +y through it; local y = 40 ⇒ world x = -40.
473        let t = path_thickness(
474            &scene,
475            DVec3::new(-40.5, 10.0, 140.5),
476            DVec3::new(-40.5, 60.0, 140.5),
477        );
478        assert!(
479            (t - 3.0).abs() < 1e-6,
480            "rotated-grid wall must stay 3 world voxels thick: {t}"
481        );
482        // Control: the same segment misses the wall in an identity grid.
483        let control = scene_with(|g| wall(g, 30, 3));
484        let t = path_thickness(
485            &control,
486            DVec3::new(-40.5, 10.0, 140.5),
487            DVec3::new(-40.5, 60.0, 140.5),
488        );
489        assert!(t.abs() < 1e-9, "identity control must miss: {t}");
490    }
491
492    #[test]
493    fn bedrock_plane_counts_as_solid_documented() {
494        // Voxlap's bedrock placeholder (chunk-local z = 255 of an
495        // otherwise-empty chunk) reads as solid — documented caveat on
496        // `grid_thickness`: keep acoustic endpoints above the world
497        // bottom. This test pins the current behaviour.
498        let scene = scene_with(|g| {
499            g.ensure_chunk(IVec3::ZERO);
500        });
501        let t = path_thickness(
502            &scene,
503            DVec3::new(10.0, 64.0, 255.5),
504            DVec3::new(20.0, 64.0, 255.5),
505        );
506        assert!(t > 9.0, "bedrock plane accumulates thickness: {t}");
507    }
508
509    #[test]
510    fn deterministic() {
511        let scene = scene_with(|g| wall(g, 30, 2));
512        let cfg = AcousticsConfig::default();
513        let src = DVec3::new(10.0, 64.0, 140.5);
514        let dst = DVec3::new(60.0, 64.0, 140.5);
515        let a = source_acoustics(&scene, src, dst, &cfg);
516        let b = source_acoustics(&scene, src, dst, &cfg);
517        assert_eq!(a, b);
518    }
519}