psx_sfx/space.rs
1//! Where a sound is, and what that does to its two ears.
2//!
3//! Four games spatialise sound today with four hand-written formulas, and
4//! three of them have a private square root. This module is the shared version:
5//! a [`Curve`] turns distance into a level, a [`PanLaw`] splits the level over
6//! the two ears, a [`ListenerRule`] picks which of several listeners (a split
7//! screen) a sound is heard from, and [`gains`] runs the whole chain.
8//!
9//! Everything is `i32`. Distances are clamped per axis before they are squared,
10//! so the sum of squares stays below `2^31` and no 64-bit arithmetic is needed
11//! (the PS1 has none, and a 64-bit divide costs hundreds of cycles).
12//!
13//! # Coordinates
14//!
15//! The horizontal plane is `x` and `z`; `y` is up and only adds to distance.
16//! A listener with heading `0` faces `+z` with its right ear toward `+x`, and a
17//! positive heading turns toward `+x`. A game with the other handedness negates
18//! the `x` axis (or the heading) once when it builds its [`Listener`] and
19//! [`Emitter`] values.
20//!
21//! # Example
22//!
23//! ```
24//! use psx_sfx::space::*;
25//!
26//! let space = Space::new(0, PanLaw::EqualPower(Center::Unity));
27//! let ears = Listeners::new([Listener::new([0, 0, 0], 0)]);
28//! // A sound 400 units ahead and 400 to the right.
29//! let source = Emitter::new([400, 0, 400]);
30//! let curve = Curve::linear_clip(0x3FFF, 2000);
31//! let g = gains(&space, &ears, ListenerRule::Loudest, &source, &curve).unwrap();
32//! assert!(g.right > g.left);
33//! ```
34
35use crate::{SPU_LEVEL_MAX, SPU_LEVEL_MIN};
36use psx_math::int32::isqrt_i32;
37use psx_math::{cos_q12, sin_q12, SIN_TABLE};
38
39/// Largest per-axis distance, after the world shift, that is squared as is.
40/// Three of these squared sum to less than `2^31`.
41pub const AXIS_LIMIT: i32 = 16383;
42
43/// Full right in [`PanLaw`] input: Q12 one.
44pub const PAN_RIGHT: i32 = 4096;
45
46/// Quake's attenuation classes, as the `Curve` constructors take them.
47///
48/// # Example
49///
50/// ```
51/// use psx_sfx::space::{Attn, Curve};
52///
53/// // A static ambient hears half as far as an idle one in Quake terms.
54/// let c = Curve::quake(Attn::Static, 0x3FFF);
55/// assert_eq!(c.level(0), 0x3FFF);
56/// ```
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum Attn {
59 /// Quake `ATTN_NORM` (1.0): silent at 1000 units.
60 Norm,
61 /// Quake `ATTN_IDLE` (2.0): silent at 500 units.
62 Idle,
63 /// Quake `ATTN_STATIC` (3.0): silent at 333 units.
64 Static,
65}
66
67impl Attn {
68 /// The attenuation in thousandths.
69 pub const fn milli(self) -> u32 {
70 match self {
71 Attn::Norm => 1000,
72 Attn::Idle => 2000,
73 Attn::Static => 3000,
74 }
75 }
76}
77
78/// GoldSrc `ATTN_NORM`, in thousandths, for [`Curve::goldsrc`].
79pub const GOLDSRC_NORM: u32 = 800;
80/// GoldSrc `ATTN_IDLE`, in thousandths.
81pub const GOLDSRC_IDLE: u32 = 2000;
82/// GoldSrc `ATTN_STATIC`, in thousandths.
83pub const GOLDSRC_STATIC: u32 = 1250;
84
85/// Distance to level.
86///
87/// The level domain is the SPU's own, so the output of
88/// [`level`](Self::level) can go straight into a [`PanLaw`] and then to the
89/// chip. `dist` is the distance after the world shift, `0` or more.
90///
91/// # Example
92///
93/// ```
94/// use psx_sfx::space::Curve;
95///
96/// let c = Curve::linear_clip(10000, 1000);
97/// assert_eq!(c.level(0), 10000);
98/// assert!(c.level(500).abs_diff(5000) <= 8);
99/// assert_eq!(c.level(1000), 0);
100/// assert_eq!(c.level(5000), 0);
101/// ```
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum Curve {
104 /// `peak - (max(d - start, 0) * slope >> shift)`, clamped to
105 /// `floor..=peak`. The shape of Quake, GoldSrc and WipEout attenuation.
106 Ramp {
107 /// Level at and inside `start`.
108 peak: i16,
109 /// Distance the fall-off begins at.
110 start: i32,
111 /// Level lost per unit of distance, in units of `1 / 2^shift`. Sixteen
112 /// bits so the product with a distance (under `2^15`) cannot overflow
113 /// and needs no saturating multiply, which on the R3000 is a library
114 /// call.
115 slope: u16,
116 /// Fixed-point shift for `slope`; below 32.
117 shift: u8,
118 /// Lowest level the curve returns.
119 floor: i16,
120 },
121 /// `peak * unit / (unit + d)`: the inverse-distance law, one divide.
122 /// `unit` is the distance at which the level has halved; keep it under
123 /// 131071 so the product fits `i32`.
124 Hyper {
125 /// Level at distance zero.
126 peak: i16,
127 /// Distance of the half-level point.
128 unit: i32,
129 },
130 /// Sixteen linear segments of `2^step_shift` distance units, no divide.
131 /// `pts[i]` is the level at `i << step_shift`; past the last point the
132 /// level stays at `pts[16]`. `step_shift` is at most 14.
133 Table {
134 /// log2 of the segment length.
135 step_shift: u8,
136 /// Levels at the segment boundaries.
137 pts: [u16; 17],
138 },
139 /// The same level at any distance.
140 Flat(i16),
141}
142
143impl Curve {
144 /// A ramp from `peak` that reaches silence at distance `clip`, with the
145 /// slope computed once at construction.
146 ///
147 /// ```
148 /// # use psx_sfx::space::Curve;
149 /// assert_eq!(Curve::linear_clip(8000, 2000).level(0), 8000);
150 /// assert_eq!(Curve::linear_clip(8000, 2000).level(2000), 0);
151 /// ```
152 ///
153 /// The slope is held in 16 bits, so clips under 256 units fall off at the
154 /// steepest slope there is (the level is gone in 256 units) rather than at
155 /// their true rate. Distances are in the curve's own units after the world
156 /// shift, so a clip that short is a shift away from being useful anyway.
157 pub const fn linear_clip(peak: i16, clip: i32) -> Self {
158 let clip = if clip < 1 { 1 } else { clip };
159 // Rounded up, so the level is exactly zero at `clip`, not 1.
160 let slope = (((peak as i32) << 10) + clip - 1) / clip;
161 let slope = if slope > u16::MAX as i32 {
162 u16::MAX
163 } else if slope < 0 {
164 0
165 } else {
166 slope as u16
167 };
168 Curve::Ramp {
169 peak,
170 start: 0,
171 slope,
172 shift: 10,
173 floor: 0,
174 }
175 }
176
177 /// The Quake and GoldSrc law: `peak * (1 - d * attn / 1000)`, so silence at
178 /// `1000 / attn` units. `attn_milli` is the attenuation in thousandths;
179 /// `0` is "no attenuation" and gives a [`Curve::Flat`].
180 ///
181 /// ```
182 /// # use psx_sfx::space::Curve;
183 /// // Attenuation 2.0: silent at 500 units.
184 /// assert_eq!(Curve::attenuated(8000, 2000).level(500), 0);
185 /// assert_eq!(Curve::attenuated(8000, 0), Curve::Flat(8000));
186 /// ```
187 pub const fn attenuated(peak: i16, attn_milli: u32) -> Self {
188 if attn_milli == 0 {
189 return Curve::Flat(peak);
190 }
191 Self::linear_clip(peak, (1_000_000 / attn_milli) as i32)
192 }
193
194 /// Quake `S_Spatialize`'s distance scale for an attenuation class.
195 ///
196 /// ```
197 /// # use psx_sfx::space::{Attn, Curve};
198 /// assert_eq!(Curve::quake(Attn::Idle, 8000).level(500), 0);
199 /// ```
200 pub const fn quake(attn: Attn, peak: i16) -> Self {
201 Self::attenuated(peak, attn.milli())
202 }
203
204 /// GoldSrc's linear gain. `attn_milli` is the attenuation in thousandths
205 /// ([`GOLDSRC_NORM`], [`GOLDSRC_IDLE`], [`GOLDSRC_STATIC`], or any other);
206 /// `0` is `ATTN_NONE`.
207 ///
208 /// ```
209 /// # use psx_sfx::space::{Curve, GOLDSRC_NORM};
210 /// // ATTN_NORM 0.8: silent at 1250 units.
211 /// assert_eq!(Curve::goldsrc(8000, GOLDSRC_NORM).level(1250), 0);
212 /// ```
213 pub const fn goldsrc(peak: i16, attn_milli: u32) -> Self {
214 Self::attenuated(peak, attn_milli)
215 }
216
217 /// WipEout's one-shot law: `0x2FFF - d`, with `d` in the game's own
218 /// eighth-of-a-unit distance.
219 ///
220 /// ```
221 /// # use psx_sfx::space::Curve;
222 /// assert_eq!(Curve::wipeout().level(1000), 0x2FFF - 1000);
223 /// ```
224 pub const fn wipeout() -> Self {
225 Curve::Ramp {
226 peak: 0x2fff,
227 start: 0,
228 slope: 1,
229 shift: 0,
230 floor: 0,
231 }
232 }
233
234 /// WipEout's crowd law: `0x2FFF - 4 * d`.
235 ///
236 /// ```
237 /// # use psx_sfx::space::Curve;
238 /// assert_eq!(Curve::wipeout_crowd().level(1000), 0x2FFF - 4000);
239 /// ```
240 pub const fn wipeout_crowd() -> Self {
241 Curve::Ramp {
242 peak: 0x2fff,
243 start: 0,
244 slope: 4,
245 shift: 0,
246 floor: 0,
247 }
248 }
249
250 /// The inverse-distance law with its half-level point at `unit`.
251 ///
252 /// ```
253 /// # use psx_sfx::space::Curve;
254 /// assert_eq!(Curve::inverse(8000, 300).level(300), 4000);
255 /// ```
256 pub const fn inverse(peak: i16, unit: i32) -> Self {
257 let unit = if unit < 1 {
258 1
259 } else if unit > 131_071 {
260 131_071
261 } else {
262 unit
263 };
264 Curve::Hyper { peak, unit }
265 }
266
267 /// The level at distance `dist`.
268 ///
269 /// ```
270 /// # use psx_sfx::space::Curve;
271 /// assert_eq!(Curve::Flat(500).level(12345), 500);
272 /// ```
273 #[inline]
274 pub fn level(&self, dist: i32) -> i16 {
275 let dist = dist.max(0);
276 match *self {
277 Curve::Ramp {
278 peak,
279 start,
280 slope,
281 shift,
282 floor,
283 } => {
284 // dist is at most 28376 and slope under 2^16: no overflow.
285 let beyond = (dist - start).clamp(0, 32767);
286 let fall = (beyond * slope as i32) >> (shift & 31);
287 let v = peak as i32 - fall;
288 v.clamp(floor as i32, peak as i32) as i16
289 }
290 Curve::Hyper { peak, unit } => {
291 // peak < 2^14 and unit <= 131071 (see `Curve::inverse`).
292 ((peak as i32 * unit) / (unit + dist)) as i16
293 }
294 Curve::Table { step_shift, pts } => {
295 let s = (step_shift as u32).min(14);
296 let seg = (dist >> s) as usize;
297 if seg >= 16 {
298 return pts[16].min(SPU_LEVEL_MAX as u16) as i16;
299 }
300 let a = pts[seg] as i32;
301 let b = pts[seg + 1] as i32;
302 let frac = dist & ((1 << s) - 1);
303 (a + (((b - a) * frac) >> s)) as i16
304 }
305 Curve::Flat(v) => v,
306 }
307 }
308}
309
310/// Which centre loss a [`PanLaw::EqualPower`] has.
311///
312/// # Example
313///
314/// ```
315/// use psx_sfx::space::{Center, PanLaw};
316///
317/// let (l, r) = PanLaw::EqualPower(Center::Unity).apply(8000, 0);
318/// assert_eq!((l, r), (8000, 8000));
319/// let (l, _) = PanLaw::EqualPower(Center::Minus3Db).apply(8000, 0);
320/// assert!(l < 8000);
321/// ```
322#[derive(Clone, Copy, Debug, PartialEq, Eq)]
323pub enum Center {
324 /// A centred sound keeps its full level on both ears and the louder side of
325 /// an off-centre sound clamps at that level: a loud mono sound loses
326 /// nothing, but power is no longer exactly constant near the middle.
327 Unity,
328 /// The textbook law: a centred sound is 3 dB down on each ear, and the sum
329 /// of squares is constant across the whole pan range.
330 Minus3Db,
331}
332
333/// How a level is split over two ears.
334///
335/// `pan` is Q12 from [`-PAN_RIGHT`](PAN_RIGHT) (hard left) to `PAN_RIGHT` (hard
336/// right).
337///
338/// # Example
339///
340/// ```
341/// use psx_sfx::space::{PanLaw, PAN_RIGHT};
342///
343/// // Quake's law: each ear gets (1 -+ pan) of the level.
344/// let (l, r) = PanLaw::Dot.apply(1000, PAN_RIGHT / 2);
345/// assert_eq!((l, r), (500, 1500));
346/// ```
347#[derive(Clone, Copy, Debug)]
348pub enum PanLaw {
349 /// Both ears get the level: a mono source.
350 Off,
351 /// WipEout's constant-sum law. The ears get `v + d` and `v - d` with
352 /// `d = (v * -pan) >> 13`, so a pan of `PAN_RIGHT` is a quarter turn and
353 /// moves half the level across. With `pan = -4a` this is bit for bit the
354 /// retail `v * a >> 11` split, including the floor rounding.
355 Sum,
356 /// Quake's law: the left ear gets `v * (1 - pan)`, the right `v * (1 + pan)`.
357 Dot,
358 /// Constant power: `left = cos`, `right = sin` of a quarter turn swept by
359 /// the pan, from the 256-entry sine table in `psx-math`.
360 EqualPower(Center),
361 /// The caller's own law, for retail-exact reproduction. Receives the level
362 /// and the pan and returns the two ear levels.
363 Custom(fn(i32, i32) -> (i32, i32)),
364}
365
366impl PanLaw {
367 /// Split `level` over two ears for `pan`. The result is not clamped to the
368 /// SPU range; [`gains`] does that.
369 ///
370 /// ```
371 /// # use psx_sfx::space::PanLaw;
372 /// assert_eq!(PanLaw::Off.apply(900, 4096), (900, 900));
373 /// ```
374 pub fn apply(&self, level: i32, pan: i32) -> (i32, i32) {
375 let pan = pan.clamp(-PAN_RIGHT, PAN_RIGHT);
376 match *self {
377 PanLaw::Off => (level, level),
378 PanLaw::Sum => {
379 let d = (level * -pan) >> 13;
380 (level + d, level - d)
381 }
382 PanLaw::Dot => (
383 (level * (PAN_RIGHT - pan)) >> 12,
384 (level * (PAN_RIGHT + pan)) >> 12,
385 ),
386 PanLaw::EqualPower(centre) => {
387 // Pan -4096..4096 sweeps a quarter turn of the sine table, 64
388 // entries of 128 pan units each: left = cos, right = sin of the
389 // swept angle, read straight from the table with one linear
390 // interpolation each (the table's entries are the angles
391 // 0, 16, 32, ... in Q0.12, so index i is pan 128 * i - 4096).
392 let p = pan + PAN_RIGHT;
393 let i = (p >> 7) as usize;
394 let f = p & 127;
395 let lerp = |a: i16, b: i16| a as i32 + (((b as i32 - a as i32) * f) >> 7);
396 let mut cl = lerp(SIN_TABLE[(i + 64) & 255], SIN_TABLE[(i + 65) & 255]);
397 let mut cr = lerp(SIN_TABLE[i], SIN_TABLE[i + 1]);
398 if centre == Center::Unity {
399 // sqrt(2) in Q12, rounded up (5793 would leave the table's
400 // 2896 at 4095): lifts the centre from -3 dB to exactly
401 // unity and lets the louder side clamp.
402 cl = ((cl * 5794) >> 12).min(4096);
403 cr = ((cr * 5794) >> 12).min(4096);
404 }
405 ((level * cl) >> 12, (level * cr) >> 12)
406 }
407 PanLaw::Custom(f) => f(level, pan),
408 }
409 }
410}
411
412/// How a world position becomes a distance: one place for the world unit to
413/// ear unit shift, the pan law and the cull threshold.
414///
415/// # Example
416///
417/// ```
418/// use psx_sfx::space::{PanLaw, Space};
419///
420/// // World units are 1/8 of the unit the curve is written in, and sounds
421/// // under 100 are not worth a voice.
422/// let space = Space::new(3, PanLaw::Off).with_cull(100);
423/// assert_eq!(space.cull(), 100);
424/// ```
425#[derive(Clone, Copy, Debug)]
426pub struct Space {
427 shift: u8,
428 law: PanLaw,
429 cull: i16,
430}
431
432impl Space {
433 /// Distances are `(emitter - listener) >> shift` per axis.
434 pub const fn new(shift: u8, law: PanLaw) -> Self {
435 Self {
436 shift,
437 law,
438 cull: 0,
439 }
440 }
441
442 /// Sounds whose curve level is at or below `cull` are reported as
443 /// inaudible ([`gains`] returns `None`) before any pan work is done.
444 ///
445 /// ```
446 /// # use psx_sfx::space::{PanLaw, Space};
447 /// assert_eq!(Space::new(0, PanLaw::Off).with_cull(40).cull(), 40);
448 /// ```
449 pub const fn with_cull(mut self, cull: i16) -> Self {
450 self.cull = cull;
451 self
452 }
453
454 /// The cull threshold.
455 pub const fn cull(&self) -> i16 {
456 self.cull
457 }
458}
459
460/// Where the ears are.
461///
462/// # Example
463///
464/// ```
465/// use psx_sfx::space::Listener;
466///
467/// let l = Listener::new([10, 0, 20], 1024); // facing +x
468/// assert_eq!(l.heading_q12(), 1024);
469/// ```
470#[derive(Clone, Copy, Debug, PartialEq, Eq)]
471pub struct Listener {
472 pos: [i32; 3],
473 heading_q12: u16,
474 // sin and cos of the heading, Q12, worked out once here rather than for
475 // every emitter placed against this listener.
476 sin: i16,
477 cos: i16,
478}
479
480impl Listener {
481 /// A listener at `pos` facing `heading_q12` (4096 to a turn, see the module
482 /// docs for the direction convention). Works out the heading's sine and
483 /// cosine once, so build it when the camera moves, not per emitter.
484 pub fn new(pos: [i32; 3], heading_q12: u16) -> Self {
485 Self {
486 pos,
487 heading_q12,
488 sin: sin_q12(heading_q12) as i16,
489 cos: cos_q12(heading_q12) as i16,
490 }
491 }
492
493 /// World position.
494 pub const fn pos(&self) -> [i32; 3] {
495 self.pos
496 }
497
498 /// Yaw, Q12 turns.
499 pub const fn heading_q12(&self) -> u16 {
500 self.heading_q12
501 }
502}
503
504/// Where a sound comes from.
505///
506/// # Example
507///
508/// ```
509/// use psx_sfx::space::Emitter;
510///
511/// assert_eq!(Emitter::new([1, 2, 3]).pos(), [1, 2, 3]);
512/// ```
513#[derive(Clone, Copy, Debug, PartialEq, Eq)]
514pub struct Emitter {
515 pos: [i32; 3],
516}
517
518impl Emitter {
519 /// An emitter at `pos`.
520 pub const fn new(pos: [i32; 3]) -> Self {
521 Self { pos }
522 }
523
524 /// World position.
525 pub const fn pos(&self) -> [i32; 3] {
526 self.pos
527 }
528}
529
530/// The listeners in a scene: one, or two for a split screen.
531///
532/// # Example
533///
534/// ```
535/// use psx_sfx::space::{Listener, Listeners};
536///
537/// let ears = Listeners::new([Listener::new([0; 3], 0), Listener::new([50, 0, 0], 0)]);
538/// assert_eq!(ears.len(), 2);
539/// ```
540#[derive(Clone, Copy, Debug)]
541pub struct Listeners<const N: usize>([Listener; N]);
542
543impl<const N: usize> Listeners<N> {
544 /// Wrap `listeners`.
545 pub const fn new(listeners: [Listener; N]) -> Self {
546 Self(listeners)
547 }
548
549 /// How many listeners there are.
550 pub const fn len(&self) -> usize {
551 N
552 }
553
554 /// Is there no listener at all?
555 pub const fn is_empty(&self) -> bool {
556 N == 0
557 }
558
559 /// Replace listener `index`, for a camera that moved this frame.
560 ///
561 /// ```
562 /// # use psx_sfx::space::{Listener, Listeners};
563 /// let mut ears = Listeners::new([Listener::new([0; 3], 0)]);
564 /// ears.set(0, Listener::new([5, 0, 5], 1024));
565 /// ```
566 pub fn set(&mut self, index: usize, listener: Listener) {
567 self.0[index] = listener;
568 }
569}
570
571/// Which listener a sound is heard from when there are several. There is one
572/// television and one stereo image, so there is no true answer, only a policy.
573///
574/// # Example
575///
576/// ```
577/// use psx_sfx::space::*;
578///
579/// let space = Space::new(0, PanLaw::Off);
580/// let ears = Listeners::new([Listener::new([0; 3], 0), Listener::new([1000, 0, 0], 0)]);
581/// let curve = Curve::linear_clip(0x3FFF, 4000);
582/// let near_second = Emitter::new([900, 0, 0]);
583/// let g = gains(&space, &ears, ListenerRule::Nearest, &near_second, &curve).unwrap();
584/// assert_eq!(g.listener, 1);
585/// ```
586#[derive(Clone, Copy, Debug, PartialEq, Eq)]
587pub enum ListenerRule {
588 /// Evaluate every listener and keep the one the sound is loudest to
589 /// (`left + right`; ties go to the first). WipEout's rule for one-shots.
590 Loudest,
591 /// The nearest listener decides. Keeps a loop's pan stable instead of
592 /// flipping between listeners as their levels cross.
593 Nearest,
594 /// A virtual listener at the mean position and heading of all of them, for
595 /// scene-wide events (a goal, a crowd roar) that neither player owns.
596 Centroid,
597}
598
599/// The result of placing a sound: the two ear levels and where they came from.
600///
601/// # Example
602///
603/// ```
604/// use psx_sfx::space::*;
605///
606/// let space = Space::new(0, PanLaw::Off);
607/// let ears = Listeners::new([Listener::new([0; 3], 0)]);
608/// let g = gains(&space, &ears, ListenerRule::Loudest, &Emitter::new([0, 0, 100]), &Curve::Flat(900)).unwrap();
609/// assert_eq!((g.left, g.right, g.dist), (900, 900, 100));
610/// ```
611#[derive(Clone, Copy, Debug, PartialEq, Eq)]
612pub struct Gains {
613 /// Left ear level, SPU range.
614 pub left: i16,
615 /// Right ear level, SPU range.
616 pub right: i16,
617 /// Index of the listener the sound is heard from (`0` for a centroid).
618 pub listener: u8,
619 /// Distance to that listener, after the world shift.
620 pub dist: i32,
621}
622
623impl Gains {
624 /// The louder ear, floored at zero: what a voice allocator ranks by.
625 ///
626 /// ```
627 /// # use psx_sfx::space::Gains;
628 /// let g = Gains { left: -3, right: 700, listener: 0, dist: 10 };
629 /// assert_eq!(g.audibility(), 700);
630 /// ```
631 pub fn audibility(&self) -> i32 {
632 (self.left.max(self.right) as i32).max(0)
633 }
634}
635
636/// Clamp one axis difference into the range that can be squared safely.
637#[inline(always)]
638fn axis(a: i32, b: i32, shift: u8) -> i32 {
639 (a.wrapping_sub(b) >> (shift & 31)).clamp(-AXIS_LIMIT, AXIS_LIMIT)
640}
641
642#[inline(always)]
643fn clamp_spu(v: i32) -> i16 {
644 v.clamp(SPU_LEVEL_MIN as i32, SPU_LEVEL_MAX as i32) as i16
645}
646
647#[inline(always)]
648fn offsets(space: &Space, l: &Listener, e: &Emitter) -> [i32; 3] {
649 [
650 axis(e.pos[0], l.pos[0], space.shift),
651 axis(e.pos[1], l.pos[1], space.shift),
652 axis(e.pos[2], l.pos[2], space.shift),
653 ]
654}
655
656/// Place `emitter` for one listener.
657#[inline(always)]
658fn evaluate(
659 space: &Space,
660 index: u8,
661 listener: &Listener,
662 emitter: &Emitter,
663 curve: &Curve,
664) -> Option<Gains> {
665 let d = offsets(space, listener, emitter);
666 let dist = isqrt_i32(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
667 let level = curve.level(dist);
668 if level <= space.cull {
669 return None;
670 }
671 let pan = match space.law {
672 PanLaw::Off => 0,
673 _ if dist == 0 => 0,
674 _ => {
675 // right = (cos h, -sin h) in (x, z); pan = right . (d / |d|), Q12.
676 let dot = d[0] * listener.cos as i32 - d[2] * listener.sin as i32;
677 dot / dist
678 }
679 };
680 let (l, r) = space.law.apply(level as i32, pan);
681 Some(Gains {
682 left: clamp_spu(l),
683 right: clamp_spu(r),
684 listener: index,
685 dist,
686 })
687}
688
689/// Place `emitter` for a scene of listeners under `rule`, returning the ear
690/// levels, or `None` when the sound is inaudible and should not take a voice.
691///
692/// Cost is one full placement per listener for [`ListenerRule::Loudest`], and
693/// one placement plus a squared-distance scan for the other two rules.
694///
695/// # Example
696///
697/// ```
698/// use psx_sfx::space::*;
699///
700/// let space = Space::new(0, PanLaw::Dot).with_cull(50);
701/// let ears = Listeners::new([Listener::new([0; 3], 0)]);
702/// let curve = Curve::quake(Attn::Norm, 0x3FFF);
703/// // Beyond 1000 units a Norm sound is gone.
704/// assert!(gains(&space, &ears, ListenerRule::Loudest, &Emitter::new([0, 0, 1200]), &curve).is_none());
705/// ```
706pub fn gains<const N: usize>(
707 space: &Space,
708 listeners: &Listeners<N>,
709 rule: ListenerRule,
710 emitter: &Emitter,
711 curve: &Curve,
712) -> Option<Gains> {
713 if N == 0 {
714 return None;
715 }
716 let ls = &listeners.0;
717 if N == 1 {
718 return evaluate(space, 0, &ls[0], emitter, curve);
719 }
720 match rule {
721 ListenerRule::Loudest => {
722 let mut best: Option<Gains> = None;
723 for (i, l) in ls.iter().enumerate() {
724 if let Some(g) = evaluate(space, i as u8, l, emitter, curve) {
725 let better = match best {
726 None => true,
727 Some(b) => g.left as i32 + g.right as i32 > b.left as i32 + b.right as i32,
728 };
729 if better {
730 best = Some(g);
731 }
732 }
733 }
734 best
735 }
736 ListenerRule::Nearest => {
737 let mut at = 0usize;
738 let mut best = i32::MAX;
739 for (i, l) in ls.iter().enumerate() {
740 let d = offsets(space, l, emitter);
741 let sq = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
742 if sq < best {
743 best = sq;
744 at = i;
745 }
746 }
747 evaluate(space, at as u8, &ls[at], emitter, curve)
748 }
749 ListenerRule::Centroid => {
750 // Offsets from the first listener, so the sum cannot overflow for
751 // listeners that are near each other in world terms.
752 let base = ls[0].pos;
753 let mut sum = [0i32; 3];
754 let (mut sx, mut sz) = (0i32, 0i32);
755 for l in ls.iter() {
756 for (s, (p, b)) in sum.iter_mut().zip(l.pos.iter().zip(base.iter())) {
757 *s = s.wrapping_add(p.wrapping_sub(*b));
758 }
759 sx += sin_q12(l.heading_q12);
760 sz += cos_q12(l.heading_q12);
761 }
762 let n = N as i32;
763 let mean = Listener::new(
764 [
765 base[0].wrapping_add(sum[0] / n),
766 base[1].wrapping_add(sum[1] / n),
767 base[2].wrapping_add(sum[2] / n),
768 ],
769 psx_math::atan2_q12(sx, sz),
770 );
771 evaluate(space, 0, &mean, emitter, curve)
772 }
773 }
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779
780 fn one(law: PanLaw) -> (Space, Listeners<1>) {
781 (
782 Space::new(0, law),
783 Listeners::new([Listener::new([0, 0, 0], 0)]),
784 )
785 }
786
787 fn place(law: PanLaw, at: [i32; 3], curve: &Curve) -> Option<Gains> {
788 let (sp, ls) = one(law);
789 gains(&sp, &ls, ListenerRule::Loudest, &Emitter::new(at), curve)
790 }
791
792 #[test]
793 fn distance_is_euclidean() {
794 let g = place(PanLaw::Off, [3000, 4000, 0], &Curve::Flat(1)).unwrap();
795 assert_eq!(g.dist, 5000);
796 let g = place(PanLaw::Off, [1000, 2000, 2000], &Curve::Flat(1)).unwrap();
797 assert_eq!(g.dist, 3000);
798 assert_eq!(
799 place(PanLaw::Off, [0, 0, 0], &Curve::Flat(1)).unwrap().dist,
800 0
801 );
802 }
803
804 #[test]
805 fn the_world_shift_scales_distance_before_the_curve() {
806 let space = Space::new(3, PanLaw::Off);
807 let ls = Listeners::new([Listener::new([0; 3], 0)]);
808 let g = gains(
809 &space,
810 &ls,
811 ListenerRule::Loudest,
812 &Emitter::new([8000, 0, 0]),
813 &Curve::Flat(1),
814 );
815 assert_eq!(g.unwrap().dist, 1000);
816 }
817
818 #[test]
819 fn extreme_positions_neither_overflow_nor_wrap_into_nearness() {
820 let space = Space::new(0, PanLaw::EqualPower(Center::Unity));
821 let ls = Listeners::new([Listener::new([i32::MAX, i32::MIN, 0], 0)]);
822 for far in [
823 [i32::MIN, i32::MAX, i32::MAX],
824 [i32::MAX, i32::MAX, i32::MIN],
825 [0, 0, 0],
826 ] {
827 let g = gains(
828 &space,
829 &ls,
830 ListenerRule::Loudest,
831 &Emitter::new(far),
832 &Curve::linear_clip(0x3fff, 20000),
833 );
834 // Whatever the answer, it is a valid, finite one.
835 if let Some(g) = g {
836 assert!(g.dist <= 28_377);
837 }
838 }
839 // Per-axis clamping: 100000 away on one axis is no further than 16383.
840 let g = place(PanLaw::Off, [100_000, 0, 0], &Curve::Flat(1)).unwrap();
841 assert_eq!(g.dist, AXIS_LIMIT);
842 }
843
844 #[test]
845 fn ramp_matches_wipeouts_retail_law() {
846 let one_shot = Curve::wipeout();
847 let crowd = Curve::wipeout_crowd();
848 for d in [0, 1, 500, 1144, 5000, 12287, 12288, 30000] {
849 assert_eq!(
850 one_shot.level(d),
851 (0x2fff - d).max(0) as i16,
852 "one-shot {d}"
853 );
854 assert_eq!(crowd.level(d), (0x2fff - 4 * d).max(0) as i16, "crowd {d}");
855 }
856 }
857
858 #[test]
859 fn quake_attenuation_follows_the_linear_law_for_every_class() {
860 for (attn, clip) in [
861 (Attn::Norm, 1000.0f64),
862 (Attn::Idle, 500.0),
863 (Attn::Static, 1000.0 / 3.0),
864 ] {
865 let c = Curve::quake(attn, 0x3fff);
866 for d in (0..1500).step_by(7) {
867 let scale = (1.0 - d as f64 / clip).max(0.0);
868 let want = 16383.0 * scale;
869 let got = c.level(d) as f64;
870 assert!(
871 (got - want).abs() <= 24.0,
872 "{attn:?} at {d}: {got} vs {want}"
873 );
874 }
875 assert_eq!(c.level(0), 0x3fff);
876 assert_eq!(c.level(clip as i32 + 2), 0);
877 }
878 }
879
880 #[test]
881 fn goldsrc_attenuation_follows_vol_times_one_minus_dist_att_over_1000() {
882 for att in [GOLDSRC_NORM, GOLDSRC_IDLE, GOLDSRC_STATIC, 300] {
883 let c = Curve::goldsrc(0x3000, att);
884 for d in (0..3500).step_by(11) {
885 let scale = (1.0 - d as f64 * att as f64 / 1_000_000.0).max(0.0);
886 let want = 12288.0 * scale;
887 assert!((c.level(d) as f64 - want).abs() <= 20.0, "att {att} at {d}");
888 }
889 }
890 assert_eq!(
891 Curve::goldsrc(0x3000, 0).level(30000),
892 0x3000,
893 "ATTN_NONE is flat"
894 );
895 }
896
897 #[test]
898 fn the_inverse_law_halves_at_its_unit_and_never_rises() {
899 let c = Curve::inverse(8000, 400);
900 assert_eq!(c.level(0), 8000);
901 assert_eq!(c.level(400), 4000);
902 let mut last = i16::MAX;
903 for d in 0..5000 {
904 let v = c.level(d);
905 assert!(v <= last);
906 last = v;
907 }
908 }
909
910 #[test]
911 fn a_table_curve_interpolates_between_its_points_and_holds_past_the_end() {
912 let mut pts = [0u16; 17];
913 for (i, p) in pts.iter_mut().enumerate() {
914 *p = 1600 - 100 * i as u16;
915 }
916 let c = Curve::Table { step_shift: 6, pts };
917 assert_eq!(c.level(0), 1600);
918 assert_eq!(c.level(64), 1500);
919 assert_eq!(c.level(32), 1550);
920 assert_eq!(c.level(64 * 16), 0);
921 assert_eq!(c.level(100_000), 0);
922 }
923
924 #[test]
925 fn an_empty_or_negative_clip_cannot_divide_by_zero() {
926 // A clip under 256 units is held to the steepest slope: gone by 256.
927 assert_eq!(Curve::linear_clip(1000, 0).level(300), 0);
928 assert_eq!(Curve::linear_clip(1000, -5).level(0), 1000);
929 assert_eq!(Curve::inverse(1000, 0).level(0), 1000);
930 }
931
932 #[test]
933 fn a_sound_to_the_right_is_louder_in_the_right_ear_and_follows_the_heading() {
934 let curve = Curve::Flat(8000);
935 let g = place(PanLaw::Dot, [500, 0, 0], &curve).unwrap();
936 assert!(g.right > g.left);
937 assert_eq!((g.left, g.right), (0, 16000));
938 // Dead ahead is centred; dead behind too.
939 let g = place(PanLaw::Dot, [0, 0, 500], &curve).unwrap();
940 assert_eq!(g.left, g.right);
941 let g = place(PanLaw::Dot, [0, 0, -500], &curve).unwrap();
942 assert_eq!(g.left, g.right);
943 // Facing +x (a quarter turn right), the +x sound is dead ahead and the
944 // +z sound is now on the left.
945 let space = Space::new(0, PanLaw::Dot);
946 let ls = Listeners::new([Listener::new([0; 3], 1024)]);
947 let ahead = gains(
948 &space,
949 &ls,
950 ListenerRule::Loudest,
951 &Emitter::new([500, 0, 0]),
952 &curve,
953 )
954 .unwrap();
955 assert!(ahead.left.abs_diff(ahead.right) <= 4);
956 let side = gains(
957 &space,
958 &ls,
959 ListenerRule::Loudest,
960 &Emitter::new([0, 0, 500]),
961 &curve,
962 )
963 .unwrap();
964 assert!(side.left > side.right);
965 }
966
967 #[test]
968 fn a_sound_overhead_is_centred() {
969 let g = place(PanLaw::Dot, [0, 800, 0], &Curve::Flat(8000)).unwrap();
970 assert_eq!(g.left, g.right);
971 }
972
973 #[test]
974 fn equal_power_keeps_the_sum_of_squares_constant_at_minus_3_db_centre() {
975 let level = 10000i32;
976 for pan in (-4096..=4096).step_by(128) {
977 let (l, r) = PanLaw::EqualPower(Center::Minus3Db).apply(level, pan);
978 let power = (l as f64).powi(2) + (r as f64).powi(2);
979 let want = (level as f64).powi(2);
980 assert!(
981 (power / want - 1.0).abs() < 0.02,
982 "pan {pan}: {power} vs {want}"
983 );
984 }
985 let (l, r) = PanLaw::EqualPower(Center::Minus3Db).apply(level, 0);
986 assert_eq!(l, r);
987 assert!((l as f64 / level as f64 - core::f64::consts::FRAC_1_SQRT_2).abs() < 0.01);
988 }
989
990 #[test]
991 fn equal_power_at_unity_centre_loses_nothing_for_a_centred_sound() {
992 let law = PanLaw::EqualPower(Center::Unity);
993 assert_eq!(law.apply(9000, 0), (9000, 9000));
994 let (l, r) = law.apply(9000, -4096);
995 assert_eq!((l, r), (9000, 0));
996 let (l, r) = law.apply(9000, 4096);
997 assert_eq!((l, r), (0, 9000));
998 // Monotone: moving right never makes the right ear quieter.
999 let mut last = -1;
1000 for pan in (-4096..=4096).step_by(64) {
1001 let (_, r) = law.apply(9000, pan);
1002 assert!(r >= last);
1003 last = r;
1004 }
1005 }
1006
1007 #[test]
1008 fn the_dot_law_gives_each_ear_one_minus_or_plus_pan() {
1009 assert_eq!(PanLaw::Dot.apply(1000, 0), (1000, 1000));
1010 assert_eq!(PanLaw::Dot.apply(1000, 4096), (0, 2000));
1011 assert_eq!(PanLaw::Dot.apply(1000, -2048), (1500, 500));
1012 }
1013
1014 #[test]
1015 fn the_sum_law_is_wipeouts_retail_split_for_every_level_and_bearing() {
1016 // WipEout `panned`: delta = v * a >> 11, left v + delta, right v - delta,
1017 // with a the bearing (positive to the left). Here pan = -4a.
1018 for v in (0..=0x2fffi32).step_by(37) {
1019 for a in -1024..=1024i32 {
1020 let delta = v.wrapping_mul(a) >> 11;
1021 let want = (v + delta, v - delta);
1022 assert_eq!(PanLaw::Sum.apply(v, -4 * a), want, "v {v} a {a}");
1023 }
1024 }
1025 }
1026
1027 #[test]
1028 fn the_sum_law_reproduces_wipeouts_golden_placement() {
1029 // audio_placement_tests.rs: a sound at [4096, 0, 8192] from the origin is
1030 // magnitude 1144 in the game's units, bearing -302, and places at
1031 // (2374, 3195) after the sample-level scale 8190 >> 15.
1032 let v = 0x2fff - 1144;
1033 let (l, r) = PanLaw::Sum.apply(v, -4 * -302);
1034 assert_eq!(((l * 8190) >> 15, (r * 8190) >> 15), (2374, 3195));
1035 }
1036
1037 #[test]
1038 fn a_custom_law_is_called_with_the_level_and_clamped_pan() {
1039 fn swap(level: i32, pan: i32) -> (i32, i32) {
1040 (pan, level)
1041 }
1042 assert_eq!(PanLaw::Custom(swap).apply(7, 99999), (4096, 7));
1043 }
1044
1045 #[test]
1046 fn output_levels_are_clamped_to_the_spu_range() {
1047 let g = place(PanLaw::Sum, [0, 0, 100], &Curve::Flat(0x3fff)).unwrap();
1048 assert_eq!((g.left, g.right), (0x3fff, 0x3fff));
1049 fn inverted(level: i32, _: i32) -> (i32, i32) {
1050 (-level * 4, level * 4)
1051 }
1052 let g = place(PanLaw::Custom(inverted), [0, 0, 100], &Curve::Flat(0x3fff)).unwrap();
1053 assert_eq!((g.left, g.right), (-0x4000, 0x3fff));
1054 }
1055
1056 #[test]
1057 fn a_sound_at_or_below_the_cull_level_is_inaudible_before_any_pan_work() {
1058 let space = Space::new(0, PanLaw::Dot).with_cull(100);
1059 let ls = Listeners::new([Listener::new([0; 3], 0)]);
1060 let curve = Curve::linear_clip(0x3fff, 1000);
1061 let near = Emitter::new([0, 0, 900]); // level 1638
1062 let far = Emitter::new([0, 0, 990]); // level about 163
1063 let gone = Emitter::new([0, 0, 995]); // level about 82
1064 assert!(gains(&space, &ls, ListenerRule::Loudest, &near, &curve).is_some());
1065 assert!(gains(&space, &ls, ListenerRule::Loudest, &far, &curve).is_some());
1066 assert!(gains(&space, &ls, ListenerRule::Loudest, &gone, &curve).is_none());
1067 }
1068
1069 fn two() -> (Space, Listeners<2>) {
1070 (
1071 Space::new(0, PanLaw::EqualPower(Center::Minus3Db)),
1072 Listeners::new([Listener::new([0, 0, 0], 0), Listener::new([4000, 0, 0], 0)]),
1073 )
1074 }
1075
1076 #[test]
1077 fn split_screen_loudest_hears_a_sound_from_the_listener_it_is_louder_to() {
1078 let (sp, ls) = two();
1079 let curve = Curve::linear_clip(0x3fff, 6000);
1080 let by_p1 = gains(
1081 &sp,
1082 &ls,
1083 ListenerRule::Loudest,
1084 &Emitter::new([300, 0, 100]),
1085 &curve,
1086 )
1087 .unwrap();
1088 assert_eq!(by_p1.listener, 0);
1089 let by_p2 = gains(
1090 &sp,
1091 &ls,
1092 ListenerRule::Loudest,
1093 &Emitter::new([3700, 0, 100]),
1094 &curve,
1095 )
1096 .unwrap();
1097 assert_eq!(by_p2.listener, 1);
1098 // A tie goes to the first listener, as WipEout's strict `>` does.
1099 let mid = gains(
1100 &sp,
1101 &ls,
1102 ListenerRule::Loudest,
1103 &Emitter::new([2000, 0, 300]),
1104 &curve,
1105 )
1106 .unwrap();
1107 assert_eq!(mid.listener, 0);
1108 }
1109
1110 #[test]
1111 fn nearest_listener_decides_even_when_the_other_one_would_hear_it_louder() {
1112 let (sp, ls) = two();
1113 // Close to listener 1 (dist 100) but on a flat curve both hear the same.
1114 let flat = Curve::Flat(5000);
1115 let g = gains(
1116 &sp,
1117 &ls,
1118 ListenerRule::Nearest,
1119 &Emitter::new([3900, 0, 0]),
1120 &flat,
1121 )
1122 .unwrap();
1123 assert_eq!(g.listener, 1);
1124 assert_eq!(g.dist, 100);
1125 let g = gains(
1126 &sp,
1127 &ls,
1128 ListenerRule::Nearest,
1129 &Emitter::new([100, 0, 0]),
1130 &flat,
1131 )
1132 .unwrap();
1133 assert_eq!(g.listener, 0);
1134 // A loop sitting between them keeps the same listener as it moves a
1135 // little, where Loudest on an uneven curve could flip.
1136 let mut last = None;
1137 for x in 2001..2010 {
1138 let g = gains(
1139 &sp,
1140 &ls,
1141 ListenerRule::Nearest,
1142 &Emitter::new([x, 0, 0]),
1143 &flat,
1144 )
1145 .unwrap();
1146 if let Some(prev) = last {
1147 assert_eq!(g.listener, prev);
1148 }
1149 last = Some(g.listener);
1150 }
1151 assert_eq!(last, Some(1));
1152 }
1153
1154 #[test]
1155 fn centroid_hears_a_sound_from_the_mean_position_so_neither_player_is_privileged() {
1156 let (sp, ls) = two();
1157 let curve = Curve::linear_clip(0x3fff, 6000);
1158 // Straight ahead of the midpoint (2000, 0, 0): centred and 1000 away.
1159 let g = gains(
1160 &sp,
1161 &ls,
1162 ListenerRule::Centroid,
1163 &Emitter::new([2000, 0, 1000]),
1164 &curve,
1165 )
1166 .unwrap();
1167 assert_eq!(g.dist, 1000);
1168 assert!(g.left.abs_diff(g.right) <= 8, "{g:?}");
1169 // Loudest, by contrast, picks a side.
1170 let l = gains(
1171 &sp,
1172 &ls,
1173 ListenerRule::Loudest,
1174 &Emitter::new([2000, 0, 1000]),
1175 &curve,
1176 )
1177 .unwrap();
1178 assert!(l.dist > 1000);
1179 }
1180
1181 #[test]
1182 fn a_scene_with_no_listener_hears_nothing() {
1183 let sp = Space::new(0, PanLaw::Off);
1184 let none = Listeners::<0>::new([]);
1185 assert!(none.is_empty());
1186 assert!(gains(
1187 &sp,
1188 &none,
1189 ListenerRule::Nearest,
1190 &Emitter::new([0; 3]),
1191 &Curve::Flat(9)
1192 )
1193 .is_none());
1194 }
1195
1196 #[test]
1197 fn audibility_is_the_louder_ear_floored_at_zero() {
1198 let g = Gains {
1199 left: -500,
1200 right: -100,
1201 listener: 0,
1202 dist: 0,
1203 };
1204 assert_eq!(g.audibility(), 0);
1205 let g = Gains {
1206 left: 300,
1207 right: 900,
1208 listener: 0,
1209 dist: 0,
1210 };
1211 assert_eq!(g.audibility(), 900);
1212 }
1213}