1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! Audio-Physics Integration
//!
//! Generates physically-based audio parameters from collision events.
//! Maps impact velocity, material, surface area, and contact duration
//! to audio parameters (volume, pitch, decay, timbre).
//!
//! # Output
//!
// LIMITATION(COV-ACOUS-085): This module does NOT generate audio samples. It computes parameters that an audio engine can use to trigger and modulate sounds.
//! This module does NOT generate audio samples. It computes parameters
//! that an audio engine can use to trigger and modulate sounds.
//!
//! Author: Moroya Sakamoto
use crate::collider::Contact;
use crate::math::{Fix128, Vec3Fix};
#[cfg(not(feature = "std"))]
use alloc::vec;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
// ============================================================================
// Material
// ============================================================================
/// Physical material properties for audio synthesis
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AudioMaterial {
/// Material type identifier
pub material_type: MaterialType,
/// Density (kg/m^3) — affects pitch/resonance
pub density: Fix128,
/// Hardness (0..1) — affects attack/brightness
pub hardness: Fix128,
/// Resonance (0..1) — how much the material rings
pub resonance: Fix128,
/// Damping (0..1) — how quickly sound decays
pub damping: Fix128,
}
/// Material type for sound bank selection
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MaterialType {
/// Metal (bright, ringing)
Metal,
/// Wood (warm, short decay)
Wood,
/// Glass (bright, fragile)
Glass,
/// Stone/Concrete (dull, heavy)
Stone,
/// Rubber (soft, muffled)
Rubber,
/// Fabric/Cloth (very soft)
Fabric,
/// Water/Liquid (splash)
Liquid,
/// Custom material
Custom(u32),
}
impl AudioMaterial {
/// Metal preset
pub const METAL: Self = Self {
material_type: MaterialType::Metal,
density: Fix128 { hi: 7800, lo: 0 },
hardness: Fix128 {
hi: 0,
lo: 0xCCCCCCCCCCCCCCCC,
}, // 0.8
resonance: Fix128 {
hi: 0,
lo: 0xCCCCCCCCCCCCCCCC,
}, // 0.8
damping: Fix128 {
hi: 0,
lo: 0x3333333333333333,
}, // 0.2
};
/// Wood preset
pub const WOOD: Self = Self {
material_type: MaterialType::Wood,
density: Fix128 { hi: 600, lo: 0 },
hardness: Fix128 {
hi: 0,
lo: 0x999999999999999A,
}, // 0.6
resonance: Fix128 {
hi: 0,
lo: 0x6666666666666666,
}, // 0.4
damping: Fix128 {
hi: 0,
lo: 0x999999999999999A,
}, // 0.6
};
/// Stone preset
pub const STONE: Self = Self {
material_type: MaterialType::Stone,
density: Fix128 { hi: 2500, lo: 0 },
hardness: Fix128 {
hi: 0,
lo: 0xE666666666666666,
}, // 0.9
resonance: Fix128 {
hi: 0,
lo: 0x3333333333333333,
}, // 0.2
damping: Fix128 {
hi: 0,
lo: 0xB333333333333333,
}, // 0.7
};
/// Rubber preset
pub const RUBBER: Self = Self {
material_type: MaterialType::Rubber,
density: Fix128 { hi: 1100, lo: 0 },
hardness: Fix128 {
hi: 0,
lo: 0x3333333333333333,
}, // 0.2
resonance: Fix128 {
hi: 0,
lo: 0x1999999999999999,
}, // 0.1
damping: Fix128 {
hi: 0,
lo: 0xE666666666666666,
}, // 0.9
};
}
// ============================================================================
// Audio Event
// ============================================================================
/// Audio parameters generated from a physics event
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AudioEvent {
/// World-space position for 3D spatialization
pub position: Vec3Fix,
/// Volume (0..1, linear)
pub volume: Fix128,
/// Pitch multiplier (1.0 = normal, 0.5 = octave down, 2.0 = octave up)
pub pitch: Fix128,
/// Decay time in seconds
pub decay: Fix128,
/// Brightness (0..1, controls high-frequency content)
pub brightness: Fix128,
/// Roughness (0..1, 0 = clean, 1 = gritty/textured)
pub roughness: Fix128,
/// Impact type
pub event_type: AudioEventType,
/// Material A
pub material_a: MaterialType,
/// Material B
pub material_b: MaterialType,
}
/// Type of audio event
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AudioEventType {
/// Single impact (collision begin)
Impact,
/// Sliding contact (persistent)
Slide,
/// Rolling contact
Roll,
/// Scraping (high-friction slide)
Scrape,
/// Breaking/fracture
Break,
/// Splash (fluid)
Splash,
}
// ============================================================================
// Audio Generator
// ============================================================================
/// Audio event generator configuration
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AudioConfig {
/// Minimum impact velocity to generate sound
pub min_velocity: Fix128,
/// Maximum volume impact velocity (velocities above this = max volume)
pub max_velocity: Fix128,
/// Velocity to pitch mapping factor
pub velocity_pitch_factor: Fix128,
/// Minimum volume threshold (events below this are discarded)
pub min_volume: Fix128,
/// Sliding sound velocity threshold
pub slide_velocity_threshold: Fix128,
/// Maximum simultaneous audio events per frame
pub max_events_per_frame: usize,
}
impl Default for AudioConfig {
fn default() -> Self {
Self {
min_velocity: Fix128::from_ratio(1, 10),
max_velocity: Fix128::from_int(20),
velocity_pitch_factor: Fix128::from_ratio(1, 20),
min_volume: Fix128::from_ratio(1, 100),
slide_velocity_threshold: Fix128::from_ratio(1, 2),
max_events_per_frame: 32,
}
}
}
/// Audio event generator
pub struct AudioGenerator {
/// Configuration
pub config: AudioConfig,
/// Per-body material (indexed by body ID)
pub materials: Vec<AudioMaterial>,
/// Generated audio events this frame
pub events: Vec<AudioEvent>,
}
impl AudioGenerator {
/// Create a new audio generator for N bodies
#[must_use]
pub fn new(num_bodies: usize, config: AudioConfig) -> Self {
Self {
config,
materials: vec![AudioMaterial::WOOD; num_bodies],
events: Vec::new(),
}
}
/// Set material for a body
pub fn set_material(&mut self, body_idx: usize, material: AudioMaterial) {
if body_idx >= self.materials.len() {
self.materials.resize(body_idx + 1, AudioMaterial::WOOD);
}
self.materials[body_idx] = material;
}
/// Clear events for new frame
pub fn begin_frame(&mut self) {
self.events.clear();
}
/// Process a collision contact and generate audio event
pub fn process_contact(
&mut self,
body_a: usize,
body_b: usize,
contact: &Contact,
relative_velocity: Vec3Fix,
is_new_contact: bool,
) {
if self.events.len() >= self.config.max_events_per_frame {
return;
}
let speed = relative_velocity.length();
if speed < self.config.min_velocity {
return;
}
let mat_a = self.get_material(body_a);
let mat_b = self.get_material(body_b);
// Determine event type
let normal_speed = relative_velocity.dot(contact.normal).abs();
let tangential_sq = speed * speed - normal_speed * normal_speed;
let tangential_speed = if tangential_sq > Fix128::ZERO {
tangential_sq.sqrt()
} else {
Fix128::ZERO
};
let event_type = if is_new_contact {
AudioEventType::Impact
} else if tangential_speed > self.config.slide_velocity_threshold {
AudioEventType::Slide
} else {
AudioEventType::Roll
};
// Compute audio parameters
let volume = self.compute_volume(speed, &mat_a, &mat_b);
let pitch = self.compute_pitch(speed, &mat_a, &mat_b);
let decay = self.compute_decay(&mat_a, &mat_b);
let brightness = self.compute_brightness(speed, &mat_a, &mat_b);
let roughness = self.compute_roughness(tangential_speed, &mat_a, &mat_b);
if volume < self.config.min_volume {
return;
}
self.events.push(AudioEvent {
position: contact.point_a,
volume,
pitch,
decay,
brightness,
roughness,
event_type,
material_a: mat_a.material_type,
material_b: mat_b.material_type,
});
}
fn get_material(&self, body_idx: usize) -> AudioMaterial {
if body_idx < self.materials.len() {
self.materials[body_idx]
} else {
AudioMaterial::WOOD
}
}
/// `speed / max_velocity` clamped to `[0, 1]`; a `max_velocity <= 0` puts
/// every positive speed above the maximum (ratio 1), as the field's doc
/// reads, rather than dividing by zero.
fn speed_ratio(&self, speed: Fix128) -> Fix128 {
let max = self.config.max_velocity;
if max <= Fix128::ZERO {
return if speed > Fix128::ZERO {
Fix128::ONE
} else {
Fix128::ZERO
};
}
let ratio = speed / max;
if ratio > Fix128::ONE {
Fix128::ONE
} else {
ratio
}
}
/// Volume: impact velocity mapped to 0..1 with sqrt curve
fn compute_volume(
&self,
speed: Fix128,
_mat_a: &AudioMaterial,
_mat_b: &AudioMaterial,
) -> Fix128 {
self.speed_ratio(speed).sqrt()
}
/// Pitch: higher velocity = slightly higher pitch, adjusted by material density
fn compute_pitch(&self, speed: Fix128, mat_a: &AudioMaterial, mat_b: &AudioMaterial) -> Fix128 {
let base = Fix128::ONE + speed * self.config.velocity_pitch_factor;
// Denser materials = lower pitch
let avg_density = (mat_a.density + mat_b.density).half();
if avg_density.is_zero() {
return base;
}
let density_factor = Fix128::from_int(1000) / avg_density;
let density_factor = if density_factor > Fix128::from_int(2) {
Fix128::from_int(2)
} else if density_factor < Fix128::from_ratio(1, 2) {
Fix128::from_ratio(1, 2)
} else {
density_factor
};
base * density_factor
}
/// Decay: based on material resonance and damping
#[allow(clippy::unused_self)]
fn compute_decay(&self, mat_a: &AudioMaterial, mat_b: &AudioMaterial) -> Fix128 {
let avg_resonance = (mat_a.resonance + mat_b.resonance).half();
let avg_damping = (mat_a.damping + mat_b.damping).half();
// High resonance + low damping = long decay
let base_decay = Fix128::from_ratio(1, 10); // 0.1s minimum
let resonance_bonus = avg_resonance * Fix128::from_int(2);
let damping_reduction = avg_damping;
base_decay + resonance_bonus * (Fix128::ONE - damping_reduction)
}
/// Brightness: hardness and impact speed
fn compute_brightness(
&self,
speed: Fix128,
mat_a: &AudioMaterial,
mat_b: &AudioMaterial,
) -> Fix128 {
let avg_hardness = (mat_a.hardness + mat_b.hardness).half();
let speed_factor = self.speed_ratio(speed);
avg_hardness * (Fix128::from_ratio(1, 2) + speed_factor.half())
}
/// Roughness: tangential velocity and surface hardness
fn compute_roughness(
&self,
tangential_speed: Fix128,
mat_a: &AudioMaterial,
mat_b: &AudioMaterial,
) -> Fix128 {
let avg_hardness = (mat_a.hardness + mat_b.hardness).half();
let speed_factor = self.speed_ratio(tangential_speed);
speed_factor * avg_hardness
}
/// Get all audio events for this frame
#[must_use]
pub fn get_events(&self) -> &[AudioEvent] {
&self.events
}
}
// ============================================================================
// World view
// ============================================================================
impl crate::solver::PhysicsWorld {
/// Feed every contact of the last step to `generator`
/// ([`AudioGenerator::process_contact`]), in the order of
/// [`contact_events`](Self::contact_events), which is deterministic.
///
/// One call per touching pair (a pair is reported once per step): a
/// [`Begin`](crate::event::ContactEventType::Begin) event is a new contact, a
/// [`Persist`](crate::event::ContactEventType::Persist) event a continuing one,
/// and an [`End`](crate::event::ContactEventType::End) event is skipped. The
/// relative velocity passed is the event's normal speed
/// ([`ContactEvent::relative_velocity`](crate::event::ContactEvent::relative_velocity),
/// measured when the contact was detected, before the solver removed it) along
/// the event normal, plus the tangential part of the bodies' current linear
/// velocity difference `v_a − v_b`. The contact passed has the event's point as
/// `point_a` and `point_a + normal·depth` as `point_b`.
///
/// The generator's events are appended to; call
/// [`AudioGenerator::begin_frame`] first to start a new frame.
pub fn emit_contact_audio(&self, generator: &mut AudioGenerator) {
use crate::event::ContactEventType;
for e in self.contact_events() {
let is_new = match e.event_type {
ContactEventType::Begin => true,
ContactEventType::Persist => false,
ContactEventType::End => continue,
};
let (Some(a), Some(b)) = (self.bodies.get(e.body_a), self.bodies.get(e.body_b)) else {
continue;
};
let rel = a.velocity - b.velocity;
let tangential = rel - e.normal * rel.dot(e.normal);
let contact = Contact {
depth: e.depth,
normal: e.normal,
point_a: e.point,
point_b: e.point + e.normal * e.depth,
};
generator.process_contact(
e.body_a,
e.body_b,
&contact,
e.normal * e.relative_velocity + tangential,
is_new,
);
}
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_audio_generator() {
let mut gen = AudioGenerator::new(2, AudioConfig::default());
gen.set_material(0, AudioMaterial::METAL);
gen.set_material(1, AudioMaterial::STONE);
gen.begin_frame();
let contact = Contact {
depth: Fix128::from_ratio(1, 10),
normal: Vec3Fix::UNIT_Y,
point_a: Vec3Fix::ZERO,
point_b: Vec3Fix::ZERO,
};
gen.process_contact(0, 1, &contact, Vec3Fix::from_f32(0.0, -5.0, 0.0), true);
assert_eq!(gen.events.len(), 1);
let event = &gen.events[0];
assert_eq!(event.event_type, AudioEventType::Impact);
assert!(event.volume > Fix128::ZERO);
}
#[test]
fn test_material_presets() {
let metal = AudioMaterial::METAL;
let rubber = AudioMaterial::RUBBER;
// Metal should be harder and more resonant than rubber
assert!(metal.hardness > rubber.hardness);
assert!(metal.resonance > rubber.resonance);
}
#[test]
fn test_volume_scaling() {
let gen = AudioGenerator::new(2, AudioConfig::default());
let mat = AudioMaterial::WOOD;
let soft = gen.compute_volume(Fix128::from_int(1), &mat, &mat);
let hard = gen.compute_volume(Fix128::from_int(10), &mat, &mat);
assert!(hard > soft, "Harder impact should be louder");
}
#[test]
fn test_below_threshold() {
let mut gen = AudioGenerator::new(2, AudioConfig::default());
gen.begin_frame();
let contact = Contact {
depth: Fix128::from_ratio(1, 100),
normal: Vec3Fix::UNIT_Y,
point_a: Vec3Fix::ZERO,
point_b: Vec3Fix::ZERO,
};
// Very slow impact (below threshold)
gen.process_contact(0, 1, &contact, Vec3Fix::from_f32(0.0, -0.01, 0.0), true);
assert!(
gen.events.is_empty(),
"Below-threshold impacts should be silent"
);
}
#[test]
fn test_slide_detection() {
let mut gen = AudioGenerator::new(2, AudioConfig::default());
gen.begin_frame();
let contact = Contact {
depth: Fix128::from_ratio(1, 10),
normal: Vec3Fix::UNIT_Y,
point_a: Vec3Fix::ZERO,
point_b: Vec3Fix::ZERO,
};
// Tangential velocity (sliding)
gen.process_contact(
0,
1,
&contact,
Vec3Fix::from_f32(5.0, 0.0, 0.0), // X velocity, Y normal = sliding
false, // not new contact
);
assert_eq!(gen.events.len(), 1);
assert_eq!(gen.events[0].event_type, AudioEventType::Slide);
}
#[test]
fn get_events_returns_this_frames_events_in_order_and_respects_cap() {
let config = AudioConfig {
max_events_per_frame: 2,
..AudioConfig::default()
};
let mut gen = AudioGenerator::new(3, config);
gen.set_material(1, AudioMaterial::METAL);
assert!(gen.get_events().is_empty());
gen.begin_frame();
let contact_at = |x: i64| Contact {
depth: Fix128::from_ratio(1, 10),
normal: Vec3Fix::UNIT_Y,
point_a: Vec3Fix::from_int(x, 0, 0),
point_b: Vec3Fix::from_int(x, -1, 0),
};
// 1: impact、speed 5 → volume = sqrt(5/20) = 1/2
gen.process_contact(0, 1, &contact_at(1), Vec3Fix::from_int(0, -5, 0), true);
// 2: slide (接線 5 > 1/2)、材質 WOOD × WOOD (body 2 は default)
gen.process_contact(0, 2, &contact_at(2), Vec3Fix::from_int(5, 0, 0), false);
// 3: cap (2) 超過で捨てられる
gen.process_contact(1, 2, &contact_at(3), Vec3Fix::from_int(0, -9, 0), true);
let events = gen.get_events();
assert_eq!(events.len(), 2);
assert_eq!(events, gen.events.as_slice());
// 挿入順 (position = contact.point_a)
assert_eq!(events[0].position, Vec3Fix::from_int(1, 0, 0));
assert_eq!(events[1].position, Vec3Fix::from_int(2, 0, 0));
assert_eq!(events[0].event_type, AudioEventType::Impact);
assert_eq!(events[1].event_type, AudioEventType::Slide);
assert_eq!(
(events[0].material_a, events[0].material_b),
(MaterialType::Wood, MaterialType::Metal)
);
assert_eq!(
(events[1].material_a, events[1].material_b),
(MaterialType::Wood, MaterialType::Wood)
);
let vol_err = (events[0].volume - Fix128::from_ratio(1, 2)).abs();
assert!(
vol_err < Fix128::from_ratio(1, 1_000_000),
"volume {:?}",
events[0].volume
);
// slide の roughness = (5/20) * avg_hardness、impact (接線 0) は 0
assert_eq!(events[0].roughness, Fix128::ZERO);
let wood = AudioMaterial::WOOD;
assert_eq!(
events[1].roughness,
Fix128::from_ratio(1, 4) * wood.hardness
);
// 次 frame で空になり、再度 process すれば新しい slice
gen.begin_frame();
assert!(gen.get_events().is_empty());
gen.process_contact(1, 2, &contact_at(3), Vec3Fix::from_int(0, -9, 0), true);
assert_eq!(gen.get_events().len(), 1);
assert_eq!(gen.get_events()[0].position, Vec3Fix::from_int(3, 0, 0));
}
fn custom(density: i64, hardness: Fix128) -> AudioMaterial {
AudioMaterial {
material_type: MaterialType::Custom(7),
density: Fix128::from_int(density),
hardness,
resonance: Fix128::ZERO,
damping: Fix128::ZERO,
}
}
/// oracle: `set_material` past the table grows it with wood; a body
/// never given a material is wood.
#[test]
fn set_material_grows_with_wood() {
let mut gen = AudioGenerator::new(1, AudioConfig::default());
gen.set_material(4, AudioMaterial::METAL);
assert_eq!(gen.materials.len(), 5);
assert_eq!(gen.materials[2], AudioMaterial::WOOD);
assert_eq!(gen.get_material(4), AudioMaterial::METAL);
assert_eq!(gen.get_material(99), AudioMaterial::WOOD);
}
/// `v/20` is not a dyadic number, so pitches are compared to 1e-15
fn assert_near(got: Fix128, want: Fix128) {
assert!(
(got - want).abs() < Fix128::from_ratio(1, 1_000_000_000_000_000),
"{got:?} vs {want:?}"
);
}
/// oracle: pitch is `1 + v/20` times the density factor `1000/ρ̄` clamped
/// to `[1/2, 2]`: for `v = 2` that is `11/10` for `ρ̄ = 0` (no factor),
/// `11/5` for `ρ̄ = 100` (factor 10 → 2), `11/20` for `ρ̄ = 4000` (factor
/// 1/4 → 1/2). Volume, brightness and roughness saturate at
/// `v ≥ v_max = 20`: volume 1, brightness `h̄·(1/2 + 1/2) = h̄`,
/// roughness `h̄`.
#[test]
fn pitch_density_clamp_and_saturation() {
let gen = AudioGenerator::new(2, AudioConfig::default());
let v = Fix128::from_int(2);
let h = Fix128::from_ratio(1, 2);
let zero = custom(0, h);
assert_near(
gen.compute_pitch(v, &zero, &zero),
Fix128::from_ratio(11, 10),
);
let light = custom(100, h);
assert_near(
gen.compute_pitch(v, &light, &light),
Fix128::from_ratio(11, 5),
);
let heavy = custom(4000, h);
assert_near(
gen.compute_pitch(v, &heavy, &heavy),
Fix128::from_ratio(11, 20),
);
let fast = Fix128::from_int(40);
assert_eq!(gen.compute_volume(fast, &light, &light), Fix128::ONE);
assert_eq!(gen.compute_brightness(fast, &light, &light), h);
assert_eq!(gen.compute_roughness(fast, &light, &light), h);
}
/// oracle: a persisting contact whose relative velocity is along the
/// normal (no tangential part) rolls; an event whose volume
/// `sqrt(v/20)` is below `min_volume` is dropped (`v = 1`: `0.22 < 1/2`).
#[test]
fn roll_and_quiet_events() {
let contact = Contact {
depth: Fix128::from_ratio(1, 10),
normal: Vec3Fix::UNIT_Y,
point_a: Vec3Fix::ZERO,
point_b: Vec3Fix::ZERO,
};
let mut gen = AudioGenerator::new(2, AudioConfig::default());
gen.process_contact(0, 1, &contact, Vec3Fix::from_int(0, -2, 0), false);
assert_eq!(gen.events.len(), 1);
assert_eq!(gen.events[0].event_type, AudioEventType::Roll);
assert_eq!(gen.events[0].roughness, Fix128::ZERO);
let mut quiet = AudioGenerator::new(
2,
AudioConfig {
min_volume: Fix128::from_ratio(1, 2),
..AudioConfig::default()
},
);
quiet.process_contact(0, 1, &contact, Vec3Fix::from_int(0, -1, 0), true);
assert!(quiet.events.is_empty());
}
/// oracle: from the world's contact events, `emit_contact_audio` sends a
/// begin as an impact and a persist as a slide (the bodies' tangential
/// velocity `(3, 0, 0)` exceeds 1/2), at the event point, with relative
/// velocity `n·v_rel + tangential = (3, −5, 0)`: volume
/// `sqrt(√34 / 20)`. An end event and an event naming a body that does not
/// exist make no sound.
#[test]
fn world_contact_events_become_audio() {
use crate::event::{ContactEvent, ContactEventType};
let mut world = crate::solver::PhysicsWorld::new(crate::solver::SolverConfig::default());
let mut a = crate::solver::RigidBody::new(Vec3Fix::ZERO, Fix128::ONE);
a.velocity = Vec3Fix::from_int(3, 0, 0);
world.add_body(a);
world.add_body(crate::solver::RigidBody::new_static(Vec3Fix::from_int(
0, -1, 0,
)));
let ev = |event_type, body_b| ContactEvent {
body_a: 0,
body_b,
event_type,
normal: Vec3Fix::UNIT_Y,
point: Vec3Fix::from_int(1, 2, 3),
depth: Fix128::from_ratio(1, 10),
relative_velocity: Fix128::from_int(-5),
};
world.events.contact_events = vec![
ev(ContactEventType::Begin, 1),
ev(ContactEventType::End, 1),
ev(ContactEventType::Begin, 9),
ev(ContactEventType::Persist, 1),
];
let mut gen = AudioGenerator::new(2, AudioConfig::default());
gen.begin_frame();
world.emit_contact_audio(&mut gen);
assert_eq!(gen.events.len(), 2);
assert_eq!(gen.events[0].event_type, AudioEventType::Impact);
assert_eq!(gen.events[1].event_type, AudioEventType::Slide);
let want = (34.0_f64.sqrt() / 20.0).sqrt();
for e in &gen.events {
assert_eq!(e.position, Vec3Fix::from_int(1, 2, 3));
assert!((e.volume.to_f64() - want).abs() < 1e-9, "{:?}", e.volume);
}
}
}