physxx 0.3.1

Wrapper around the PhysX C++ API that aims to preserve the original API as much as possible.
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
// TODO: reconsider this allow - we should look into the flags and fix them and/or
// switch to bitflags 2
#![allow(clippy::bad_bit_mask)]

use std::ptr::null_mut;

use glam::Vec3;
use physx_sys::{
    create_overlap_buffer, create_raycast_buffer, create_sweep_buffer, delete_overlap_callback,
    delete_raycast_callback,
};
use serde::{Deserialize, Serialize};

use crate::{
    sweep::PxSweepHit, to_glam_vec3, to_physx_vec3, AsArticulationBase, AsPxActor, PxActorRef,
    PxAggregateRef, PxCollectionRef, PxConstraintRef, PxDefaultCpuDispatcherRef, PxGeometry,
    PxHitFlags, PxPhysicsRef, PxPvdSceneClientRef, PxRaycastHit, PxRigidActorRef, PxShape,
    PxTransform,
};

pub fn extract_contact_points(
    iter: &physx_sys::PxContactStreamIterator,
) -> Result<Vec<PxContactPoint>, &'static str> {
    if iter.contact.is_null() || iter.patch.is_null() {
        return Err("Null pointer detected in PxContactStreamIterator");
    }

    let mut contact_points = Vec::new();

    let mut local_iter = *iter; // Create a mutable copy of iter

    unsafe {
        let patches =
            std::slice::from_raw_parts(local_iter.patch, local_iter.totalPatches as usize);
        let contacts =
            std::slice::from_raw_parts(local_iter.contact, local_iter.totalContacts as usize);

        for patch in patches {
            for _ in 0..patch.nbContacts {
                let contact = contacts[local_iter.nextContactIndex as usize];

                contact_points.push(PxContactPoint {
                    position: to_glam_vec3(&contact.contact),
                    separation: contact.separation,
                    normal: to_glam_vec3(&patch.normal),
                });

                local_iter.nextContactIndex += 1;
            }

            local_iter.nextPatchIndex += 1;
        }
    }

    Ok(contact_points)
}

pub struct PxSceneDesc(physx_sys::PxSceneDesc);
impl PxSceneDesc {
    pub fn new(physics: PxPhysicsRef) -> Self {
        Self(unsafe {
            let mut scene_desc =
                physx_sys::PxSceneDesc_new(physx_sys::PxPhysics_getTolerancesScale(physics.0));

            scene_desc.filterShader = physx_sys::get_default_simulation_filter_shader();
            scene_desc.solverType = physx_sys::PxSolverType::eTGS;

            scene_desc
        })
    }
    pub fn set_gravity(&mut self, gravity: glam::Vec3) {
        self.0.gravity = to_physx_vec3(gravity);
    }
    pub fn get_gravity(&self) -> glam::Vec3 {
        to_glam_vec3(&self.0.gravity)
    }
    pub fn set_cpu_dispatcher(&mut self, dispatcher: &PxDefaultCpuDispatcherRef) {
        self.0.cpuDispatcher = dispatcher.0 as *mut physx_sys::PxCpuDispatcher;
    }
    pub fn set_filter_shader(
        &mut self,
        shader: physx_sys::SimulationFilterShader,
        call_default_filter_shader_first: bool,
    ) {
        unsafe {
            physx_sys::enable_custom_filter_shader(
                &mut self.0,
                shader,
                call_default_filter_shader_first as u32,
            );
        }
    }
    pub fn set_simulation_event_callbacks<C: FnMut(&PxContactPairHeader, Vec<PxContactPoint>)>(
        &mut self,
        callbacks: PxSimulationEventCallback<C>,
    ) {
        unsafe {
            unsafe extern "C" fn collision_callback_trampoline<
                C: FnMut(&PxContactPairHeader, Vec<PxContactPoint>),
            >(
                user_data: *mut std::ffi::c_void,
                pair_header: *const physx_sys::PxContactPairHeader,
                pairs: *const physx_sys::PxContactPair,
                _nb_pairs: u32,
            ) {
                let mut cb: Box<C> = Box::from_raw(user_data as _);
                let pair_header_flags =
                    PxContactPairHeaderFlag::from_bits((*pair_header).flags.mBits).unwrap();
                let mut contact_points_vec = Vec::new();

                // Check for a valid contact stream
                if let Some(pair) = pairs.as_ref() {
                    // Create the PxContactStreamIterator from the contact pair data
                    let contact_stream_iterator = unsafe {
                        physx_sys::PxContactStreamIterator_new(
                            pair.contactPatches,
                            pair.contactPoints,
                            std::ptr::null(), // Assuming we don't have the contactFaceIndices, passing a null pointer.
                            pair.patchCount as u32,
                            pair.contactCount as u32,
                        )
                    };

                    if let Ok(points) = extract_contact_points(&contact_stream_iterator) {
                        contact_points_vec = points;
                    } else {
                        // Handle the error
                        println!("Error extracting contact points");
                    }
                }

                cb(
                    &PxContactPairHeader {
                        actors: [
                            if pair_header_flags.contains(PxContactPairHeaderFlag::REMOVED_ACTOR_0)
                            {
                                None
                            } else {
                                PxRigidActorRef::from_ptr((*pair_header).actors[0])
                            },
                            if pair_header_flags.contains(PxContactPairHeaderFlag::REMOVED_ACTOR_1)
                            {
                                None
                            } else {
                                PxRigidActorRef::from_ptr((*pair_header).actors[1])
                            },
                        ],
                    },
                    contact_points_vec,
                );

                Box::into_raw(cb); // Convert the box back into a raw pointer.
            }

            let mut cbs = physx_sys::SimulationEventCallbackInfo {
                ..Default::default()
            };
            if let Some(cb) = callbacks.collision_callback {
                cbs.collision_callback = Some(collision_callback_trampoline::<C>);
                cbs.collision_user_data = Box::into_raw(cb) as _;
            }
            self.0.simulationEventCallback = physx_sys::create_simulation_event_callbacks(&cbs);
        }
    }
    pub fn get_flags(&mut self) -> PxSceneFlags {
        PxSceneFlags::from_bits(self.0.flags.mBits).unwrap()
    }
    pub fn set_flags(&mut self, flags: PxSceneFlags) {
        self.0.flags = physx_sys::PxSceneFlags { mBits: flags.bits };
    }
    pub fn update_flags(&mut self, update: impl Fn(PxSceneFlags) -> PxSceneFlags) {
        let flags = self.get_flags();
        let flags = update(flags);
        self.set_flags(flags);
    }
}

#[derive(Debug, Clone)]
pub struct PxContactPoint {
    pub position: glam::Vec3,
    pub normal: glam::Vec3,
    pub separation: f32,
}

pub struct PxContactPairHeader {
    pub actors: [Option<PxRigidActorRef>; 2],
}

pub struct PxSimulationEventCallback<C: FnMut(&PxContactPairHeader, Vec<PxContactPoint>)> {
    pub collision_callback: Option<Box<C>>,
}

bitflags! {
    pub struct PxContactPairHeaderFlag: u16 {
        const REMOVED_ACTOR_0 = physx_sys::PxContactPairHeaderFlag::eREMOVED_ACTOR_0 as u16;
        const REMOVED_ACTOR_1 = physx_sys::PxContactPairHeaderFlag::eREMOVED_ACTOR_1 as u16;
    }
}

bitflags! {
    pub struct PxSceneFlags: u32 {
        const ADAPTIVE_FORCE = physx_sys::PxSceneFlag::eADAPTIVE_FORCE;
        const DISABLE_CCD_RESWEEP = physx_sys::PxSceneFlag::eDISABLE_CCD_RESWEEP;
        const DISABLE_CONTACT_CACHE = physx_sys::PxSceneFlag::eDISABLE_CONTACT_CACHE;
        const DISABLE_CONTACT_REPORT_BUFFER_RESIZE = physx_sys::PxSceneFlag::eDISABLE_CONTACT_REPORT_BUFFER_RESIZE;
        const ENABLE_ACTIVE_ACTORS = physx_sys::PxSceneFlag::eENABLE_ACTIVE_ACTORS;
        const ENABLE_AVERAGE_POINT = physx_sys::PxSceneFlag::eENABLE_AVERAGE_POINT;
        const ENABLE_CCD = physx_sys::PxSceneFlag::eENABLE_CCD;
        const ENABLE_ENHANCED_DETERMINISM = physx_sys::PxSceneFlag::eENABLE_ENHANCED_DETERMINISM;
        const ENABLE_FRICTION_EVERY_ITERATION = physx_sys::PxSceneFlag::eENABLE_FRICTION_EVERY_ITERATION;
        const ENABLE_GPU_DYNAMICS = physx_sys::PxSceneFlag::eENABLE_GPU_DYNAMICS;
        const ENABLE_PCM = physx_sys::PxSceneFlag::eENABLE_PCM;
        const ENABLE_STABILIZATION = physx_sys::PxSceneFlag::eENABLE_STABILIZATION;
        const EXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS = physx_sys::PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS;
        const MUTABLE_FLAGS = physx_sys::PxSceneFlag::eMUTABLE_FLAGS;
        const REQUIRE_RW_LOCK = physx_sys::PxSceneFlag::eREQUIRE_RW_LOCK;
    }
}

bitflags! {
    pub struct PxVisualizationParameter: u32 {
        const ACTOR_AXES = physx_sys::PxVisualizationParameter::eACTOR_AXES;
        const BODY_ANG_VELOCITY = physx_sys::PxVisualizationParameter::eBODY_ANG_VELOCITY;
        const BODY_AXES = physx_sys::PxVisualizationParameter::eBODY_AXES;
        const BODY_LIN_VELOCITY = physx_sys::PxVisualizationParameter::eBODY_LIN_VELOCITY;
        const BODY_MASS_AXES = physx_sys::PxVisualizationParameter::eBODY_MASS_AXES;
        const COLLISION_AABBS = physx_sys::PxVisualizationParameter::eCOLLISION_AABBS;
        const COLLISION_AXES = physx_sys::PxVisualizationParameter::eCOLLISION_AXES;
        const COLLISION_COMPOUNDS = physx_sys::PxVisualizationParameter::eCOLLISION_COMPOUNDS;
        const COLLISION_DYNAMIC = physx_sys::PxVisualizationParameter::eCOLLISION_DYNAMIC;
        const COLLISION_EDGES = physx_sys::PxVisualizationParameter::eCOLLISION_EDGES;
        const COLLISION_FNORMALS = physx_sys::PxVisualizationParameter::eCOLLISION_FNORMALS;
        const COLLISION_SHAPES = physx_sys::PxVisualizationParameter::eCOLLISION_SHAPES;
        const COLLISION_STATIC = physx_sys::PxVisualizationParameter::eCOLLISION_STATIC;
        const CONTACT_ERROR = physx_sys::PxVisualizationParameter::eCONTACT_ERROR;
        const CONTACT_FORCE = physx_sys::PxVisualizationParameter::eCONTACT_FORCE;
        const CONTACT_NORMAL = physx_sys::PxVisualizationParameter::eCONTACT_NORMAL;
        const CONTACT_POINT = physx_sys::PxVisualizationParameter::eCONTACT_POINT;
        const CULL_BOX = physx_sys::PxVisualizationParameter::eCULL_BOX;
        const DEPRECATED_COLLISION_PAIRS = physx_sys::PxVisualizationParameter::eDEPRECATED_COLLISION_PAIRS;
        const FORCE_DWORD = physx_sys::PxVisualizationParameter::eFORCE_DWORD;
        const JOINT_LIMITS = physx_sys::PxVisualizationParameter::eJOINT_LIMITS;
        const JOINT_LOCAL_FRAMES = physx_sys::PxVisualizationParameter::eJOINT_LOCAL_FRAMES;
        const MBP_REGIONS = physx_sys::PxVisualizationParameter::eMBP_REGIONS;
        const NUM_VALUES = physx_sys::PxVisualizationParameter::eNUM_VALUES;
        const SCALE = physx_sys::PxVisualizationParameter::eSCALE;
        const WORLD_AXES = physx_sys::PxVisualizationParameter::eWORLD_AXES;
    }
}

bitflags! {
    pub struct PxHitFlag: u32 {
        const ASSUME_NO_INITIAL_OVERLAP = physx_sys::PxHitFlag::eASSUME_NO_INITIAL_OVERLAP;
        const DEFAULT = physx_sys::PxHitFlag::eDEFAULT;
        const FACE_INDEX = physx_sys::PxHitFlag::eFACE_INDEX;
        const MESH_ANY = physx_sys::PxHitFlag::eMESH_ANY;
        const MESH_BOTH_SIDES = physx_sys::PxHitFlag::eMESH_BOTH_SIDES;
        const MESH_MULTIPLE = physx_sys::PxHitFlag::eMESH_MULTIPLE;
        const MODIFIABLE_FLAGS = physx_sys::PxHitFlag::eMODIFIABLE_FLAGS;
        const MTD = physx_sys::PxHitFlag::eMTD;
        const NORMAL = physx_sys::PxHitFlag::eNORMAL;
        const POSITION = physx_sys::PxHitFlag::ePOSITION;
        const PRECISE_SWEEP = physx_sys::PxHitFlag::ePRECISE_SWEEP;
        const UV = physx_sys::PxHitFlag::eUV;
    }
}

bitflags! {
    pub struct PxActorTypeFlag: u32 {
        const RIGID_DYNAMIC = physx_sys::PxActorTypeFlag::eRIGID_DYNAMIC;
        const RIGID_STATIC = physx_sys::PxActorTypeFlag::eRIGID_STATIC;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PxSceneRef(pub(crate) *mut physx_sys::PxScene);
impl PxSceneRef {
    pub fn new(physics: &PxPhysicsRef, scene_desc: &PxSceneDesc) -> Self {
        Self(unsafe { physx_sys::PxPhysics_createScene_mut(physics.0, &scene_desc.0) })
    }

    pub fn add_actor(&self, actor: &dyn AsPxActor) {
        unsafe {
            physx_sys::PxScene_addActor_mut(self.0, actor.as_actor().0, null_mut());
        }
    }
    pub fn remove_actor(&self, actor: &dyn AsPxActor, wake_on_lost_touch: bool) {
        unsafe {
            physx_sys::PxScene_removeActor_mut(self.0, actor.as_actor().0, wake_on_lost_touch);
        }
    }

    pub fn add_aggregate(&self, aggregate: &PxAggregateRef) {
        unsafe {
            physx_sys::PxScene_addAggregate_mut(self.0, aggregate.0);
        }
    }
    pub fn remove_aggregate(&self, aggregate: &PxAggregateRef, wake_on_lost_touch: bool) {
        unsafe {
            physx_sys::PxScene_removeAggregate_mut(self.0, aggregate.0, wake_on_lost_touch);
        }
    }

    pub fn add_articulation(&self, articulation: &dyn AsArticulationBase) {
        unsafe {
            physx_sys::PxScene_addArticulation_mut(self.0, articulation.as_articulation_base_ptr());
        }
    }
    pub fn remove_articulation(
        &self,
        articulation: &dyn AsArticulationBase,
        wake_on_lost_touch: bool,
    ) {
        unsafe {
            physx_sys::PxScene_removeArticulation_mut(
                self.0,
                articulation.as_articulation_base_ptr(),
                wake_on_lost_touch,
            );
        }
    }

    pub fn add_collection(&self, collection: &PxCollectionRef) {
        unsafe {
            physx_sys::PxScene_addCollection_mut(self.0, collection.0);
        }
    }

    pub fn get_actors(&self, types: PxActorTypeFlag) -> Vec<PxActorRef> {
        unsafe {
            let types = physx_sys::PxActorTypeFlags {
                mBits: types.bits as u16,
            };
            let count = physx_sys::PxScene_getNbActors(self.0, types);
            let mut buffer: Vec<*mut physx_sys::PxActor> = Vec::with_capacity(count as usize);
            physx_sys::PxScene_getActors(self.0, types, buffer.as_mut_ptr() as _, count, 0);
            buffer.set_len(count as usize);
            buffer.into_iter().map(PxActorRef).collect()
        }
    }

    pub fn get_constraints(&self) -> Vec<PxConstraintRef> {
        unsafe {
            let count = physx_sys::PxScene_getNbConstraints(self.0);
            let mut buffer: Vec<*mut physx_sys::PxConstraint> = Vec::with_capacity(count as usize);
            physx_sys::PxScene_getConstraints(self.0, buffer.as_mut_ptr() as _, count, 0);
            buffer.set_len(count as usize);
            buffer.into_iter().map(PxConstraintRef).collect()
        }
    }

    pub fn get_visualization_parameter(&self, param: PxVisualizationParameter) -> f32 {
        unsafe { physx_sys::PxScene_getVisualizationParameter(self.0, param.bits) }
    }
    pub fn set_visualization_parameter(&self, param: PxVisualizationParameter, value: f32) -> bool {
        unsafe { physx_sys::PxScene_setVisualizationParameter_mut(self.0, param.bits, value) }
    }
    pub fn simulate(&self, delta_time: f32) {
        unsafe {
            physx_sys::PxScene_simulate_mut(self.0, delta_time, null_mut(), null_mut(), 0, true);
        }
    }
    pub fn fetch_results(&self, block: bool) -> bool {
        let mut error: u32 = 0;
        let fetched = unsafe { physx_sys::PxScene_fetchResults_mut(self.0, block, &mut error) };
        assert!(error == 0, "fetchResults has failed");
        fetched
    }
    pub fn get_scene_pvd_client(&self) -> PxPvdSceneClientRef {
        PxPvdSceneClientRef(unsafe { physx_sys::PxScene_getScenePvdClient_mut(self.0) })
    }
    pub fn get_gravity(&self) -> Vec3 {
        to_glam_vec3(&unsafe { physx_sys::PxScene_getGravity(self.0) })
    }
    pub fn set_gravity(&self, gravity: Vec3) {
        unsafe { physx_sys::PxScene_setGravity_mut(self.0, &to_physx_vec3(gravity)) }
    }
    pub fn raycast(
        &self,
        origin: Vec3,
        unit_dir: Vec3,
        distance: f32,
        hit_call: &mut PxRaycastCallback,
        hit_flags: Option<PxHitFlag>,
        filter_data: &PxQueryFilterData,
    ) -> bool {
        unsafe {
            physx_sys::PxScene_raycast(
                self.0,
                &to_physx_vec3(origin),
                &to_physx_vec3(unit_dir),
                distance,
                hit_call.0,
                physx_sys::PxHitFlags {
                    mBits: hit_flags.unwrap_or(PxHitFlag::DEFAULT).bits as u16,
                },
                &filter_data.0,
                null_mut(),
                null_mut(),
            )
        }
    }

    pub fn sweep(
        &self,
        geom: &dyn PxGeometry,
        pose: &PxTransform,
        dir: Vec3,
        max_dist: f32,
        filter: PxQueryFilterData,
    ) -> PxSweepCallback {
        let hit = PxSweepCallback::new(100);

        unsafe {
            physx_sys::PxScene_sweep(
                self.0,
                geom.as_geometry_ptr(),
                &pose.0 as *const _,
                &to_physx_vec3(dir),
                max_dist,
                hit.0,
                physx_sys::PxHitFlags {
                    mBits: (PxHitFlags::POSITION | PxHitFlags::DEFAULT).bits() as u16,
                },
                &filter.0,
                null_mut(),
                null_mut(),
                0.0,
            );
        }

        hit
    }
    pub fn overlap(
        &self,
        geometry: &dyn PxGeometry,
        pose: PxTransform,
        hit_call: &mut PxOverlapCallback,
        filter_data: &PxQueryFilterData,
    ) -> bool {
        unsafe {
            physx_sys::PxScene_overlap(
                self.0,
                geometry.as_geometry_ptr(),
                &pose.0,
                hit_call.0,
                &filter_data.0,
                null_mut(),
            )
        }
    }
    pub fn get_render_buffer(&self) -> PxRenderBuffer {
        unsafe {
            let buf = physx_sys::PxScene_getRenderBuffer_mut(self.0);

            let points = std::slice::from_raw_parts::<physx_sys::PxDebugPoint>(
                physx_sys::PxRenderBuffer_getPoints(buf),
                physx_sys::PxRenderBuffer_getNbPoints(buf) as usize,
            );
            let lines = std::slice::from_raw_parts::<physx_sys::PxDebugLine>(
                physx_sys::PxRenderBuffer_getLines(buf),
                physx_sys::PxRenderBuffer_getNbLines(buf) as usize,
            );
            PxRenderBuffer {
                points: points
                    .iter()
                    .map(|p| PxDebugPoint {
                        pos: to_glam_vec3(&p.pos),
                        color: p.color,
                    })
                    .collect(),
                lines: lines
                    .iter()
                    .map(|p| PxDebugLine {
                        pos0: to_glam_vec3(&p.pos0),
                        color0: p.color0,
                        pos1: to_glam_vec3(&p.pos1),
                        color1: p.color1,
                    })
                    .collect(),
            }
        }
    }
    pub fn release(self) {
        unsafe { physx_sys::PxScene_release_mut(self.0) }
    }
}

unsafe impl Sync for PxSceneRef {}
unsafe impl Send for PxSceneRef {}

pub struct PxQueryFilterData(physx_sys::PxQueryFilterData);
impl PxQueryFilterData {
    pub fn new() -> Self {
        Self(unsafe { physx_sys::PxQueryFilterData_new() })
    }
    pub fn set_flags(&mut self, flags: PxQueryFlag) {
        self.0.flags.mBits = flags.bits as u16;
    }
}
impl Default for PxQueryFilterData {
    fn default() -> Self {
        Self::new()
    }
}

bitflags! {
    pub struct PxQueryFlag: u32 {
        const ANY_HIT = physx_sys::PxQueryFlag::eANY_HIT;
        const DYNAMIC = physx_sys::PxQueryFlag::eDYNAMIC;
        const NO_BLOCK = physx_sys::PxQueryFlag::eNO_BLOCK;
        const POSTFILTER = physx_sys::PxQueryFlag::ePOSTFILTER;
        const PREFILTER = physx_sys::PxQueryFlag::ePREFILTER;
        const RESERVED = physx_sys::PxQueryFlag::eRESERVED;
        const STATIC = physx_sys::PxQueryFlag::eSTATIC;
    }
}
pub struct PxSweepCallback(*mut physx_sys::PxSweepCallback, Vec<physx_sys::PxSweepHit>);
impl PxSweepCallback {
    pub fn new(max_nb_touches: usize) -> Self {
        let mut s = unsafe {
            let p = create_sweep_buffer();
            let arr = (0..max_nb_touches).map(|_| (*p).block).collect::<Vec<_>>();
            Self(p, arr)
        };
        if max_nb_touches > 0 {
            unsafe {
                (*s.0).maxNbTouches = max_nb_touches as u32;
                (*s.0).touches = s.1.as_mut_ptr() as _;
            }
        }
        s
    }
    pub fn block(&self) -> Option<PxSweepHit> {
        unsafe {
            if (*self.0).hasBlock {
                Some((*self.0).block.into())
            } else {
                None
            }
        }
    }
    pub fn touches(&self) -> Vec<PxSweepHit> {
        self.1
            .iter()
            .take(unsafe { (*self.0).nbTouches as usize })
            .copied()
            .map(Into::into)
            .collect()
    }
}

pub struct PxRaycastCallback(
    *mut physx_sys::PxRaycastCallback,
    Vec<physx_sys::PxRaycastHit>,
);
impl PxRaycastCallback {
    pub fn new(max_nb_touches: usize) -> Self {
        let mut s = unsafe {
            let p = create_raycast_buffer();
            let arr = (0..max_nb_touches).map(|_| (*p).block).collect::<Vec<_>>();
            Self(p, arr)
        };
        if max_nb_touches > 0 {
            unsafe {
                (*s.0).maxNbTouches = max_nb_touches as u32;
                (*s.0).touches = s.1.as_mut_ptr() as _;
            }
        }
        s
    }
    pub fn block(&self) -> Option<PxRaycastHit> {
        unsafe {
            if (*self.0).hasBlock {
                Some(PxRaycastHit::from_px(&(*self.0).block))
            } else {
                None
            }
        }
    }
    pub fn touches(&self) -> Vec<PxRaycastHit> {
        self.1
            .iter()
            .take(unsafe { (*self.0).nbTouches as usize })
            .map(PxRaycastHit::from_px)
            .collect()
    }
}
impl Drop for PxRaycastCallback {
    fn drop(&mut self) {
        unsafe {
            delete_raycast_callback(self.0);
        }
    }
}

pub struct PxOverlapCallback(
    *mut physx_sys::PxOverlapCallback,
    Vec<physx_sys::PxOverlapHit>,
);
impl PxOverlapCallback {
    pub fn new(max_nb_touches: usize) -> Self {
        let mut s = unsafe {
            let p = create_overlap_buffer();
            let arr = (0..max_nb_touches).map(|_| (*p).block).collect::<Vec<_>>();
            Self(p, arr)
        };
        if max_nb_touches > 0 {
            unsafe {
                (*s.0).maxNbTouches = max_nb_touches as u32;
                (*s.0).touches = s.1.as_mut_ptr() as _;
            }
        }
        s
    }
    pub fn block(&self) -> Option<PxOverlapHit> {
        unsafe {
            if (*self.0).hasBlock {
                Some(PxOverlapHit::from_px(&(*self.0).block))
            } else {
                None
            }
        }
    }
    pub fn touches(&self) -> Vec<PxOverlapHit> {
        self.1
            .iter()
            .take(unsafe { (*self.0).nbTouches as usize })
            .map(PxOverlapHit::from_px)
            .collect()
    }
}
impl Drop for PxOverlapCallback {
    fn drop(&mut self) {
        unsafe {
            delete_overlap_callback(self.0);
        }
    }
}

#[derive(Debug, Clone)]
pub struct PxOverlapHit {
    pub actor: PxRigidActorRef,
    pub shape: PxShape,
    pub face_index: u32,
}
impl PxOverlapHit {
    pub(crate) fn from_px(hit: &physx_sys::PxOverlapHit) -> Self {
        Self {
            actor: PxRigidActorRef(hit.actor),
            shape: PxShape::from_ptr(hit.shape),
            face_index: hit.faceIndex,
        }
    }
}

#[derive(Deserialize, Serialize, Debug, Clone, Default)]
pub struct PxRenderBuffer {
    pub points: Vec<PxDebugPoint>,
    pub lines: Vec<PxDebugLine>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct PxDebugPoint {
    pub pos: Vec3,
    pub color: u32,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct PxDebugLine {
    pub pos0: Vec3,
    pub color0: u32,
    pub pos1: Vec3,
    pub color1: u32,
}