audionimbus 0.13.0

A safe wrapper around Steam Audio that provides spatial audio capabilities with realistic occlusion, reverb, and HRTF effects, accounting for physical attributes and scene geometry.
Documentation
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
//! Callback definitions.

use crate::geometry::{Hit, Ray, Vector3};
use std::cell::Cell;
use std::ffi::c_void;

#[cfg(doc)]
use crate::simulation::Simulator;

/// Internal macro to generate callback wrapper types.
macro_rules! callback {
    (
        $(#[$meta:meta])*
        $vis:vis $name:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret:ty)?
    ) => {
        $(#[$meta])*
        $vis struct $name {
            callback: Box<dyn FnMut($($arg_ty),*) $(-> $ret)? + Send>,
        }

        impl $name {
            pub fn new<F>(f: F) -> Self
            where
                F: FnMut($($arg_ty),*) $(-> $ret)? + Send + 'static,
            {
                Self {
                    callback: Box::new(f),
                }
            }

            unsafe extern "C" fn trampoline(
                $($arg: <$arg_ty as $crate::callback::FfiConvert>::FfiType,)*
                user_data: *mut c_void,
            ) $(-> <$ret as $crate::callback::FfiConvert>::FfiType)? {
                let callback = &mut *(user_data as *mut Box<dyn FnMut($($arg_ty),*) $(-> $ret)? + Send>);

                $(let $arg = <$arg_ty as $crate::callback::FfiConvert>::from_ffi($arg);)*

                #[allow(unused_variables)]
                let result = callback($($arg),*);

                $(return <$ret as $crate::callback::FfiConvert>::to_ffi(result);)?
            }

            #[allow(dead_code)]
            pub(crate) fn as_raw_parts(&self) -> (
                unsafe extern "C" fn($(<$arg_ty as $crate::callback::FfiConvert>::FfiType,)* *mut c_void) $(-> <$ret as $crate::callback::FfiConvert>::FfiType)?,
                *mut c_void,
            ) {
                (
                    Self::trampoline,
                    &self.callback as *const _ as *mut c_void,
                )
            }
        }

        impl std::fmt::Debug for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(stringify!($name))
                    .field("callback", &"<closure>")
                    .finish()
            }
        }
    };
}

pub(crate) use callback;

/// Trait for types that can be converted to/from FFI representations.
pub(crate) trait FfiConvert {
    type FfiType;

    #[allow(dead_code)]
    fn to_ffi(self) -> Self::FfiType;

    #[allow(dead_code)]
    fn from_ffi(ffi: Self::FfiType) -> Self;
}

/// Marker trait for types that pass through to FFI unchanged.
pub(crate) trait FfiPassthrough: Copy + 'static {}

impl<T: FfiPassthrough> FfiConvert for T {
    type FfiType = T;

    fn to_ffi(self) -> Self::FfiType {
        self
    }

    fn from_ffi(ffi: Self::FfiType) -> Self {
        ffi
    }
}

impl FfiPassthrough for f32 {}
impl FfiPassthrough for usize {}
impl FfiPassthrough for std::ffi::c_int {}

impl FfiConvert for Vector3 {
    type FfiType = audionimbus_sys::IPLVector3;

    fn to_ffi(self) -> Self::FfiType {
        audionimbus_sys::IPLVector3 {
            x: self.x,
            y: self.y,
            z: self.z,
        }
    }

    fn from_ffi(ffi: Self::FfiType) -> Self {
        Vector3 {
            x: ffi.x,
            y: ffi.y,
            z: ffi.z,
        }
    }
}

impl FfiConvert for bool {
    type FfiType = audionimbus_sys::IPLbool;

    fn to_ffi(self) -> Self::FfiType {
        if self {
            audionimbus_sys::IPLbool::IPL_TRUE
        } else {
            audionimbus_sys::IPLbool::IPL_FALSE
        }
    }

    fn from_ffi(ffi: Self::FfiType) -> Self {
        match ffi {
            audionimbus_sys::IPLbool::IPL_TRUE => true,
            audionimbus_sys::IPLbool::IPL_FALSE => false,
        }
    }
}

impl FfiConvert for Ray {
    type FfiType = audionimbus_sys::IPLRay;

    fn to_ffi(self) -> Self::FfiType {
        self.into()
    }

    fn from_ffi(ffi: Self::FfiType) -> Self {
        ffi.into()
    }
}

callback! {
    /// A progress callback for long-running operations.
    ///
    /// # Callback arguments
    ///
    /// - `progress`: Fraction of the function work that has been completed, between 0.0 and 1.0.
    pub ProgressCallback(progress: f32)
}

callback! {
    /// Callback for visualizing valid path segments during the call to [`Simulator::run_pathing`].
    ///
    /// You can use this to provide the user with visual feedback, like drawing each segment of a path.
    ///
    /// # Callback arguments
    ///
    /// - `from`: position of the starting probe.
    /// - `to`: position of the ending probe.
    /// - `occluded`: occlusion status of the ray segment between `from` to `to`.
    pub PathingVisualizationCallback(
        from: Vector3,
        to: Vector3,
        occluded: bool,
    )
}

callback! {
    /// Callback for calculating how much to attenuate sound in a given frequency band based on the angle of deviation when the sound path bends around a corner as it propagated from the source to the listener.
    ///
    /// # Callback arguments
    ///
    /// - `angle`: angle (in radians) that the sound path deviates (bends) by.
    /// - `band`: index of the frequency band for which to calculate air absorption.
    ///
    /// # Returns
    ///
    /// The frequency-dependent attenuation to apply, between 0.0 and 1.0.
    /// 0.0 = sound in the frequency band is not audible; 1.0 = sound in the frequency band is not attenuated.
    pub DeviationCallback(
        angle: f32,
        band: std::ffi::c_int,
    ) -> f32
}

callback! {
    /// Callback for calculating how much attenuation should be applied to a sound based on its distance from the listener.
    ///
    /// # Callback arguments
    ///
    /// - `distance`: the distance (in meters) between the source and the listener.
    ///
    /// # Returns
    ///
    /// The distance attenuation to apply, between 0.0 and 1.0.
    /// 0.0 = the sound is not audible, 1.0 = the sound is as loud as it would be if it were emitted from the listener’s position.
    pub DistanceAttenuationCallback(distance: f32) -> f32
}

// BUG: Steam Audio has a bug where the `userData` pointer passed to directivity callbacks
// is corrupted and does not match the originally provided pointer. This causes segfaults
// when attempting to dereference the pointer to access our closure.
//
// See: https://github.com/ValveSoftware/steam-audio/issues/526
//
// This absolutely unholy hack consists in storing the callback pointer in a static cell local to
// the thread instead of relying on Steam Audio to pass it back to us. It is safe because only one
// directivity calculation can execute at a time per thread.
//
// TODO: the this workaround and use `callback!` macro once the Steam Audio bug is fixed.
thread_local! {
    static DIRECTIVITY_CALLBACK_PTR: Cell<*mut c_void> = const { Cell::new(std::ptr::null_mut()) };
}

/// Callback for calculating how much to attenuate a sound based on its directivity pattern and orientation in world space.
///
/// # Callback arguments
///
/// - `direction`: unit vector (in world space) pointing forwards from the source. This is the direction that the source is “pointing towards”.
///
/// # Returns
///
/// The directivity value to apply, between 0.0 and 1.0.
/// 0.0 = the sound is not audible, 1.0 = the sound is as loud as it would be if it had a uniform (omnidirectional) directivity pattern.
pub struct DirectivityCallback {
    callback: Box<dyn FnMut(Vector3) -> f32 + Send>,
}

impl DirectivityCallback {
    pub fn new<F>(f: F) -> Self
    where
        F: FnMut(Vector3) -> f32 + Send + 'static,
    {
        Self {
            callback: Box::new(f),
        }
    }

    // WORKAROUND: This function ignores the `_user_data` parameter (which Steam Audio
    // corrupts) and instead retrieves the callback pointer from thread-local storage.
    unsafe extern "C" fn trampoline(
        direction: audionimbus_sys::IPLVector3,
        _user_data: *mut c_void,
    ) -> f32 {
        let callback_ptr = DIRECTIVITY_CALLBACK_PTR.get();
        let callback = &mut *(callback_ptr as *mut Box<dyn FnMut(Vector3) -> f32 + Send>);
        let direction = Vector3::from_ffi(direction);
        callback(direction)
    }

    // WORKAROUND: This stores the callback pointer in thread-local storage rather than
    // passing it through Steam Audio's userData parameter (which is corrupted by a bug).
    pub(crate) fn as_raw_parts(
        &self,
    ) -> (
        unsafe extern "C" fn(audionimbus_sys::IPLVector3, *mut c_void) -> f32,
        *mut c_void,
    ) {
        let callback_ptr = &self.callback as *const _ as *mut c_void;
        DIRECTIVITY_CALLBACK_PTR.set(callback_ptr);
        (Self::trampoline, callback_ptr)
    }
}

impl std::fmt::Debug for DirectivityCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DirectivityCallback")
            .field("callback", &"<closure>")
            .finish()
    }
}

callback! {
    /// Callback for calculating how much air absorption should be applied to a sound based on its distance from the listener.
    ///
    /// # Callback arguments
    ///
    /// - `distance`: the distance (in meters) between the source and the listener.
    /// - `band`: index of the frequency band for which to calculate air absorption. 0.0 = low frequencies, 1.0 = middle frequencies, 2.0 = high frequencies.
    ///
    /// # Returns
    ///
    /// The air absorption to apply, between 0.0 and 1.0.
    /// 0.0 = sound in the frequency band `band` is not audible, 1.0 = sound in the frequency band `band` is not attenuated.
    pub AirAbsorptionCallback(distance: f32, band: i32) -> f32
}

/// Callbacks used for a custom ray tracer.
pub struct CustomRayTracingCallbacks {
    /// Callback for calculating the closest hit along a ray.
    closest_hit_callback: ClosestHitCallback,

    /// Callback for calculating whether a ray hits any geometry.
    any_hit_callback: AnyHitCallback,

    /// Callback for calculating the closest hit along a batch of rays.
    batched_closest_hit_callback: BatchedClosestHitCallback,

    /// Callback for calculating for each ray in a batch of rays, whether the ray hits any geometry.
    batched_any_hit_callback: BatchedAnyHitCallback,
}

impl CustomRayTracingCallbacks {
    /// Creates new custom callbacks.
    ///
    /// # Arguments
    ///
    /// - `closest_hit_callback`: Callback for calculating the closest hit along a ray
    /// - `any_hit_callback`: Callback for calculating whether a ray hits any geometry
    /// - `batched_closest_hit_callback`: Callback for calculating the closest hit along a batch of rays
    /// - `batched_any_hit_callback`: Callback for calculating for each ray in a batch of rays, whether the ray hits any geometry
    pub fn new(
        closest_hit: ClosestHitCallback,
        any_hit: AnyHitCallback,
        batched_closest_hit: BatchedClosestHitCallback,
        batched_any_hit: BatchedAnyHitCallback,
    ) -> Self {
        Self {
            closest_hit_callback: closest_hit,
            any_hit_callback: any_hit,
            batched_closest_hit_callback: batched_closest_hit,
            batched_any_hit_callback: batched_any_hit,
        }
    }

    /// Returns FFI scene settings with custom callbacks and the user data box.
    /// The caller must ensure the returned Box<CustomRayTracingUserData> lives as long as the settings are in use.
    pub(crate) fn as_ffi_settings(
        &self,
    ) -> (
        audionimbus_sys::IPLSceneSettings,
        Box<CustomRayTracingUserData>,
    ) {
        let user_data = Box::new(CustomRayTracingUserData {
            closest_hit: &self.closest_hit_callback.callback as *const _ as *mut _,
            any_hit: &self.any_hit_callback.callback as *const _ as *mut _,
            batched_closest_hit: &self.batched_closest_hit_callback.callback as *const _ as *mut _,
            batched_any_hit: &self.batched_any_hit_callback.callback as *const _ as *mut _,
        });

        let user_data_ptr = &*user_data as *const _ as *mut c_void;

        let settings = audionimbus_sys::IPLSceneSettings {
            type_: audionimbus_sys::IPLSceneType::IPL_SCENETYPE_CUSTOM,
            closestHitCallback: Some(
                ClosestHitCallback::trampoline as unsafe extern "C" fn(_, _, _, _, _),
            ),
            anyHitCallback: Some(AnyHitCallback::trampoline as unsafe extern "C" fn(_, _, _, _, _)),
            batchedClosestHitCallback: Some(
                BatchedClosestHitCallback::trampoline as unsafe extern "C" fn(_, _, _, _, _, _),
            ),
            batchedAnyHitCallback: Some(
                BatchedAnyHitCallback::trampoline as unsafe extern "C" fn(_, _, _, _, _, _),
            ),
            userData: user_data_ptr,
            embreeDevice: std::ptr::null_mut(),
            radeonRaysDevice: std::ptr::null_mut(),
        };

        (settings, user_data)
    }
}

type ClosestHitFn = dyn FnMut(Ray, f32, f32) -> Option<Hit> + Send;
type AnyHitFn = dyn FnMut(Ray, f32, f32) -> bool + Send;
type BatchedClosestHitFn = dyn FnMut(&[Ray], &[f32], &[f32]) -> Vec<Option<Hit>> + Send;
type BatchedAnyHitFn = dyn FnMut(&[Ray], &[f32], &[f32]) -> Vec<bool> + Send;

/// Internal struct holding pointers to all callback closures.
#[derive(Debug)]
pub(crate) struct CustomRayTracingUserData {
    closest_hit: *mut Box<ClosestHitFn>,
    any_hit: *mut Box<AnyHitFn>,
    batched_closest_hit: *mut Box<BatchedClosestHitFn>,
    batched_any_hit: *mut Box<BatchedAnyHitFn>,
}

/// Callback for calculating the closest hit along a ray.
///
/// Strictly speaking, the intersection is calculated with a ray interval (equivalent to a line segment).
/// Any ray interval may have multiple points of intersection with scene geometry; this function must return information about the point of intersection that is closest to the ray’s origin.
///
/// # Callback arguments
///
/// - `ray`: The ray to trace.
/// - `min_mistance`: The minimum distance from the origin at which an intersection may occur for it to be considered.
///   This function must not return any intersections closer to the origin than this value.
/// - `max_distance`: The maximum distance from the origin at which an intersection may occur for it to be considered.
///   This function must not return any intersections farther from the origin than this value.
///   If this value is less than or equal to `min_distance`, the function should ignore the ray, and return immediately.
///
/// # Returns
///
/// Information describing the ray’s intersection with geometry, if any.
pub struct ClosestHitCallback {
    callback: Box<ClosestHitFn>,
}

impl ClosestHitCallback {
    /// Creates a new [`ClosestHitCallback`].
    pub fn new<F>(f: F) -> Self
    where
        F: FnMut(Ray, f32, f32) -> Option<Hit> + Send + 'static,
    {
        Self {
            callback: Box::new(f),
        }
    }

    unsafe extern "C" fn trampoline(
        ray: *const audionimbus_sys::IPLRay,
        min_distance: f32,
        max_distance: f32,
        hit: *mut audionimbus_sys::IPLHit,
        user_data: *mut c_void,
    ) {
        let all_callbacks = &*(user_data as *const CustomRayTracingUserData);
        let callback = &mut *all_callbacks.closest_hit;
        let ray = if ray.is_null() {
            Ray::default()
        } else {
            Ray::from(*ray)
        };
        let result = callback(ray, min_distance, max_distance);

        if let Some(hit_result) = result {
            if !hit.is_null() {
                *hit = audionimbus_sys::IPLHit {
                    distance: hit_result.distance,
                    triangleIndex: hit_result.triangle_index.map(|i| i as i32).unwrap_or(-1),
                    objectIndex: hit_result.object_index.map(|i| i as i32).unwrap_or(-1),
                    materialIndex: hit_result.material_index.map(|i| i as i32).unwrap_or(-1),
                    normal: hit_result.normal.into(),
                    material: std::ptr::null_mut(),
                };
            }
        }
    }
}

impl std::fmt::Debug for ClosestHitCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClosestHitCallback")
            .field("callback", &"<closure>")
            .finish()
    }
}

/// Callback for calculating whether a ray hits any geometry.
///
/// Strictly speaking, the intersection is calculated with a ray interval (equivalent to a line segment).
///
/// # Callback arguments
///
/// - `ray`: The ray to trace.
/// - `min_distance`: The minimum distance from the origin at which an intersection may occur for it to be considered.
///   This function must not return any intersections closer to the origin than this value.
/// - `max_distance`: The maximum distance from the origin at which an intersection may occur for it to be considered.
///   This function must not return any intersections farther from the origin than this value.
///   If this value is less than or equal to `min_distance`, the function should ignore the ray and return immediately with `true`.
///
/// # Returns
///
/// A boolean indicating whether the ray intersects any geometry.
///
/// `false` indicates no intersection, `true` indicates that an intersection exists.
pub struct AnyHitCallback {
    callback: Box<AnyHitFn>,
}

impl AnyHitCallback {
    /// Creates a new [`AnyHitCallback`].
    pub fn new<F>(f: F) -> Self
    where
        F: FnMut(Ray, f32, f32) -> bool + Send + 'static,
    {
        Self {
            callback: Box::new(f),
        }
    }

    unsafe extern "C" fn trampoline(
        ray: *const audionimbus_sys::IPLRay,
        min_distance: f32,
        max_distance: f32,
        occluded: *mut u8,
        user_data: *mut c_void,
    ) {
        let all_callbacks = &*(user_data as *const CustomRayTracingUserData);
        let callback = &mut *all_callbacks.any_hit;
        let ray = if ray.is_null() {
            Ray::default()
        } else {
            Ray::from(*ray)
        };
        let result = callback(ray, min_distance, max_distance);

        if !occluded.is_null() {
            *occluded = if result { 1 } else { 0 };
        }
    }
}

impl std::fmt::Debug for AnyHitCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AnyHitCallback")
            .field("callback", &"<closure>")
            .finish()
    }
}

/// Callback for calculating the closest hit along a batch of rays.
///
/// Strictly speaking, the intersection is calculated with a ray interval (equivalent to a line segment).
/// Any ray interval may have multiple points of intersection with scene geometry; this function must return information about the point of intersection that is closest to the ray’s origin.
///
/// # Callback arguments
///
/// - `numRays`: The number of rays to trace.
/// - `rays`: Array containing the rays.
/// - `min_distances`: Array containing, for each ray, the minimum distance from the origin at which an intersection may occur for it to be considered.
/// - `max_distances`: Array containing, for each ray, the maximum distance from the origin at which an intersection may occur for it to be considered.
///   If, for some ray with index `i`, `max_distances[i]` is less than `min_distances[i]`, the function should ignore the ray.
///
/// # Returns
///
/// Information describing each ray’s intersection with geometry, if any.
pub struct BatchedClosestHitCallback {
    callback: Box<BatchedClosestHitFn>,
}

impl BatchedClosestHitCallback {
    /// Creates a new [`BatchedClosestHitCallback`].
    pub fn new<F>(f: F) -> Self
    where
        F: FnMut(&[Ray], &[f32], &[f32]) -> Vec<Option<Hit>> + Send + 'static,
    {
        Self {
            callback: Box::new(f),
        }
    }

    unsafe extern "C" fn trampoline(
        num_rays: i32,
        rays: *const audionimbus_sys::IPLRay,
        min_distances: *const f32,
        max_distances: *const f32,
        hits: *mut audionimbus_sys::IPLHit,
        user_data: *mut c_void,
    ) {
        let all_callbacks = &*(user_data as *const CustomRayTracingUserData);
        let callback = &mut *all_callbacks.batched_closest_hit;

        if num_rays <= 0
            || rays.is_null()
            || min_distances.is_null()
            || max_distances.is_null()
            || hits.is_null()
        {
            return;
        }

        let num_rays = num_rays as usize;
        let rays_slice = std::slice::from_raw_parts(rays, num_rays)
            .iter()
            .map(|&r| Ray::from(r))
            .collect::<Vec<_>>();
        let min_distances_slice = std::slice::from_raw_parts(min_distances, num_rays);
        let max_distances_slice = std::slice::from_raw_parts(max_distances, num_rays);

        let results = callback(&rays_slice, min_distances_slice, max_distances_slice);

        for (i, result) in results.iter().enumerate().take(num_rays) {
            if let Some(hit_result) = result {
                *hits.add(i) = audionimbus_sys::IPLHit {
                    distance: hit_result.distance,
                    triangleIndex: hit_result
                        .triangle_index
                        .map(|idx| idx as i32)
                        .unwrap_or(-1),
                    objectIndex: hit_result.object_index.map(|idx| idx as i32).unwrap_or(-1),
                    materialIndex: hit_result
                        .material_index
                        .map(|idx| idx as i32)
                        .unwrap_or(-1),
                    normal: hit_result.normal.into(),
                    material: std::ptr::null_mut(),
                };
            }
        }
    }
}

impl std::fmt::Debug for BatchedClosestHitCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BatchedClosestHitCallback")
            .field("callback", &"<closure>")
            .finish()
    }
}

/// Callback for calculating for each ray in a batch of rays, whether the ray hits any geometry.
///
/// Strictly speaking, the intersection is calculated with a ray interval (equivalent to a line segment).
///
/// # Callback arguments
///
/// - `num_rays`: The number of rays to trace.
/// - `rays`: Array containing the rays.
/// - `min_distances`: Array containing, for each ray, the minimum distance from the origin at which an intersection may occur for it to be considered.
/// - `max_distances`: Array containing, for each ray, the maximum distance from the origin at which an intersection may occur for it to be considered.
///   If, for some ray with index `i`, `max_distances[i]` is less than `min_distances[i]`, the function should ignore the ray and set the result to `true`.
///
/// # Returns
///
/// Array of integers indicating, for each ray, whether the ray intersects any geometry.
/// `false` indicates no intersection, `true` indicates that an intersection exists.
pub struct BatchedAnyHitCallback {
    callback: Box<BatchedAnyHitFn>,
}

impl BatchedAnyHitCallback {
    /// Creates a new [`BatchedAnyHitCallback`].
    pub fn new<F>(f: F) -> Self
    where
        F: FnMut(&[Ray], &[f32], &[f32]) -> Vec<bool> + Send + 'static,
    {
        Self {
            callback: Box::new(f),
        }
    }

    unsafe extern "C" fn trampoline(
        num_rays: i32,
        rays: *const audionimbus_sys::IPLRay,
        min_distances: *const f32,
        max_distances: *const f32,
        occluded: *mut u8,
        user_data: *mut c_void,
    ) {
        let all_callbacks = &*(user_data as *const CustomRayTracingUserData);
        let callback = &mut *all_callbacks.batched_any_hit;

        if num_rays <= 0
            || rays.is_null()
            || min_distances.is_null()
            || max_distances.is_null()
            || occluded.is_null()
        {
            return;
        }

        let num_rays = num_rays as usize;
        let rays_slice = std::slice::from_raw_parts(rays, num_rays)
            .iter()
            .map(|&r| Ray::from(r))
            .collect::<Vec<_>>();
        let min_distances_slice = std::slice::from_raw_parts(min_distances, num_rays);
        let max_distances_slice = std::slice::from_raw_parts(max_distances, num_rays);

        let results = callback(&rays_slice, min_distances_slice, max_distances_slice);

        for (i, &result) in results.iter().enumerate().take(num_rays) {
            *occluded.add(i) = if result { 1 } else { 0 };
        }
    }
}

impl std::fmt::Debug for BatchedAnyHitCallback {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BatchedAnyHitCallback")
            .field("callback", &"<closure>")
            .finish()
    }
}

/// Log level of messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum LogLevel {
    Info,
    Warning,
    Error,
    Debug,
}

impl From<audionimbus_sys::IPLLogLevel> for LogLevel {
    fn from(level: audionimbus_sys::IPLLogLevel) -> Self {
        match level {
            audionimbus_sys::IPLLogLevel::IPL_LOGLEVEL_INFO => LogLevel::Info,
            audionimbus_sys::IPLLogLevel::IPL_LOGLEVEL_WARNING => LogLevel::Warning,
            audionimbus_sys::IPLLogLevel::IPL_LOGLEVEL_ERROR => LogLevel::Error,
            audionimbus_sys::IPLLogLevel::IPL_LOGLEVEL_DEBUG => LogLevel::Debug,
        }
    }
}

/// Creates a log callback.
///
/// This macro generates a C-compatible callback function that converts C types to idiomatic Rust
/// types before invoking the closure.
///
/// # Parameters
///
/// The callback receives:
/// - `level`: [`LogLevel`] - The log level
/// - `message`: [`&str`] - The log message
///
/// # Usage
///
/// ## Named callback
///
/// Creates a named function that can be reused:
///
/// ```
/// # use audionimbus::{log_callback, Context, ContextSettings, LogLevel};
/// log_callback!(my_logger, |level, message| {
///     println!("{level:?}: {message}");
/// });
///
/// let settings = ContextSettings::new().with_log_callback(my_logger);
/// let context = Context::try_new(&settings)?;
/// # Ok::<(), audionimbus::SteamAudioError>(())
/// ```
///
/// ## Anonymous callback
///
/// Creates an inline callback without a name:
///
/// ```
/// # use audionimbus::{log_callback, Context, ContextSettings};
/// let settings = ContextSettings::new().with_log_callback(log_callback!(|level, message| {
///     println!("{level:?}: {message}");
/// }));
/// let context = Context::try_new(&settings)?;
/// # Ok::<(), audionimbus::SteamAudioError>(())
/// ```
#[macro_export]
macro_rules! log_callback {
    ($name:ident, $closure:expr) => {
        $crate::log_callback!(@impl $name, $closure);
    };

    ($closure:expr) => {{
        $crate::log_callback!(@impl __log_callback_impl, $closure);
        __log_callback_impl
    }};

    (@impl $name:ident, $closure:expr) => {
        unsafe extern "C" fn $name(
            level: audionimbus_sys::IPLLogLevel,
            message: *const ::std::os::raw::c_char,
        ) {
            let rust_level = $crate::callback::LogLevel::from(level);
            let rust_message = if !message.is_null() {
                ::std::ffi::CStr::from_ptr(message)
                    .to_str()
                    .unwrap_or("<invalid UTF-8>")
            } else {
                "<null>"
            };

            let closure: fn($crate::callback::LogLevel, &str) = $closure;
            closure(rust_level, rust_message);
        }
    };
}

/// Creates a memory allocation callback.
///
/// This macro generates a C-compatible callback function to use a custom memory allocator.
///
/// # Parameters
///
/// The callback receives:
/// - `size`: [`usize`] - The number of bytes to allocate
/// - `alignment`: [`usize`] - The required alignment in bytes (must be a power of 2)
///
/// # Returns
///
/// [`*mut`] [`c_void`] - Pointer to the allocated memory, or null pointer on failure
///
/// # Usage
///
/// ## Named callback
///
/// ```
/// # use audionimbus::{allocate_callback, free_callback, Context, ContextSettings};
/// # free_callback!(my_free, |ptr| {
/// #   // ...
/// # });
/// use std::alloc::{alloc, Layout};
/// use std::ffi::c_void;
///
/// allocate_callback!(my_allocator, |size, alignment| {
///     unsafe {
///         let layout = Layout::from_size_align_unchecked(size, alignment);
///         alloc(layout) as *mut c_void
///     }
/// });
///
/// let settings = ContextSettings::new()
///     .with_allocate_callback(my_allocator)
///     .with_free_callback(my_free);
/// let context = Context::try_new(&settings)?;
/// # Ok::<(), audionimbus::SteamAudioError>(())
/// ```
///
/// ## Anonymous callback
///
/// ```
/// # use audionimbus::{allocate_callback, free_callback, Context, ContextSettings};
/// # free_callback!(my_free, |ptr| {
/// #   // ...
/// # });
/// use std::alloc::{alloc, Layout};
/// use std::ffi::c_void;
///
/// let settings = ContextSettings::new()
///     .with_allocate_callback(allocate_callback!(|size, alignment| {
///         unsafe {
///             let layout = Layout::from_size_align_unchecked(size, alignment);
///             alloc(layout) as *mut c_void
///         }
///     }))
///     .with_free_callback(my_free);
/// let context = Context::try_new(&settings)?;
/// # Ok::<(), audionimbus::SteamAudioError>(())
/// ```
///
/// # Safety
///
/// The returned pointer must:
/// - Point to valid memory of at least `size` bytes
/// - Be aligned to `alignment` bytes
/// - Remain valid until freed by the corresponding [`free_callback`](crate::free_callback)
#[macro_export]
macro_rules! allocate_callback {
    ($name:ident, $closure:expr) => {
        $crate::allocate_callback!(@impl $name, $closure);
    };

    ($closure:expr) => {{
        $crate::allocate_callback!(@impl __allocate_callback_impl, $closure);
        __allocate_callback_impl
    }};

    (@impl $name:ident, $closure:expr) => {
        unsafe extern "C" fn $name(
            size: usize,
            alignment: usize,
        ) -> *mut ::std::ffi::c_void {
            let closure: fn(usize, usize) -> *mut ::std::ffi::c_void = $closure;
            closure(size, alignment)
        }
    };
}

/// Creates a memory deallocation callback.
///
/// This macro generates a C-compatible callback function used to free memory previously allocated
/// by [`allocate_callback`](crate::allocate_callback).
///
/// # Parameters
///
/// The callback receives:
/// - `ptr`: [`*mut`] [`c_void`] - Pointer to memory previously allocated by the allocate callback
///
/// # Usage
///
/// ## Named callback
///
/// ```
/// # use audionimbus::{free_callback, allocate_callback, Context, ContextSettings};
/// # use std::alloc::{alloc, Layout};
/// # use std::ffi::c_void;
/// # allocate_callback!(my_allocator, |size, alignment| {
/// #     unsafe {
/// #         let layout = Layout::from_size_align_unchecked(size, alignment);
/// #         alloc(layout) as *mut c_void
/// #     }
/// # });
/// free_callback!(my_free, |ptr| {
///     // ...
/// });
///
/// let settings = ContextSettings::new()
///     .with_allocate_callback(my_allocator)
///     .with_free_callback(my_free);
/// let context = Context::try_new(&settings)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Anonymous callback
///
/// ```
/// # use audionimbus::{free_callback, allocate_callback, Context, ContextSettings};
/// # use std::alloc::{alloc, Layout};
/// # use std::ffi::c_void;
/// # allocate_callback!(my_allocator, |size, alignment| {
/// #     unsafe {
/// #         let layout = Layout::from_size_align_unchecked(size, alignment);
/// #         alloc(layout) as *mut c_void
/// #     }
/// # });
/// let settings = ContextSettings::new()
///     .with_allocate_callback(my_allocator)
///     .with_free_callback(free_callback!(|ptr| {
///         // ...
///     }));
/// let context = Context::try_new(&settings)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[macro_export]
macro_rules! free_callback {
    ($name:ident, $closure:expr) => {
        $crate::free_callback!(@impl $name, $closure);
    };

    ($closure:expr) => {{
        $crate::free_callback!(@impl __free_callback_impl, $closure);
        __free_callback_impl
    }};

    (@impl $name:ident, $closure:expr) => {
        unsafe extern "C" fn $name(ptr: *mut ::std::ffi::c_void) {
            let closure: fn(*mut ::std::ffi::c_void) = $closure;
            closure(ptr);
        }
    };
}