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
// Author: Tom Olsson <tom.olsson@embark-studios.com>
// Copyright © 2019, Embark Studios, all rights reserved.
// Created: 10 April 2019

#![warn(clippy::all)]
#![warn(rust_2018_idioms)]
#![allow(clippy::missing_safety_doc)]

/*!
Wrapper for PhysX Scene
 */

use super::{
    articulation_reduced_coordinate::*,
    body::*,
    controller::*,
    physics::Physics,
    rigid_actor::RigidActor,
    rigid_dynamic::RigidDynamic,
    rigid_static::*,
    traits::*,
    transform::{gl_to_px_v3, px_to_gl_v3},
    user_data::UserData,
    visual_debugger::*,
};
use enumflags2::BitFlags;
use glam::Vec3;

use physx_sys::*;
use std::ops::{Deref, DerefMut};
use std::ptr::{null, null_mut};
use std::sync::RwLock;

pub struct Scene {
    px_scene: RwLock<Option<*mut PxScene>>,
    bodies: Vec<ArticulationReducedCoordinate>,
    statics: Vec<RigidStatic>,
    dynamics: Vec<RigidDynamic>,
    simulation_callback: Option<*mut PxSimulationEventCallback>,
    controller_manager: Option<ControllerManager>,
}

////////////////////////////////////////////////////////////////////////////////
// #[physx_type]
impl Scene {
    pub fn new(scene: *mut PxScene) -> Self {
        let mut _self = Self {
            px_scene: RwLock::new(Some(scene)),
            bodies: Vec::new(),
            dynamics: Vec::new(),
            statics: Vec::new(),
            simulation_callback: None,
            controller_manager: None,
        };
        _self.allocate_user_data();
        _self
    }

    fn allocate_user_data(&mut self) {
        let userdata = Box::new(UserData::new_scene());
        let scene = self.px_scene.write().unwrap().unwrap();
        unsafe {
            (*scene).userData = Box::into_raw(userdata) as *mut std::ffi::c_void;
        }
    }

    pub unsafe fn release(&mut self) {
        self.bodies.drain(..).for_each(|mut e| e.release());
        self.statics.drain(..).for_each(|mut e| e.release());
        self.dynamics.drain(..).for_each(|mut e| e.release());

        // destroy simulation callback if we have one
        if let Some(callback) = self.simulation_callback.take() {
            destroy_contact_callback(callback);
        }

        if let Some(manager) = self.controller_manager.take() {
            manager.release();
        }

        // Release the scene object
        let mut scene = self.px_scene.write().unwrap();
        let scene = scene.take().expect("scene already released");
        let b: Box<UserData> = Box::from_raw((*scene).userData as *mut _);

        drop(b);
        PxScene_release_mut(scene);
    }

    /// Get the visual debugger client
    pub fn get_pvd_client(&self) -> PvdSceneClient {
        PvdSceneClient::from_ptr(unsafe {
            PxScene_getScenePvdClient_mut(
                self.px_scene.write().unwrap().expect("accessing null ptr"),
            )
        })
    }

    pub fn add_capsule_controller(
        &mut self,
        desc: &CapsuleControllerDesc,
    ) -> Result<Controller, ControllerError> {
        if self.controller_manager.is_none() {
            return Err(ControllerError::NoControllerManager);
        }

        let mut controller = self
            .controller_manager
            .as_ref()
            .unwrap()
            .create_controller(desc);

        Ok(Controller::new(controller.get_raw_mut()))
    }

    pub fn add_actor(&mut self, mut actor: RigidStatic) -> BodyHandle {
        unsafe {
            PxScene_addActor_mut(
                self.px_scene.write().unwrap().expect("accessing null ptr"),
                actor.get_raw_mut() as *mut PxActor,
                null(),
            );
        }

        let handle = BodyHandle(actor.get_raw() as usize);
        self.statics.push(actor);
        handle
    }

    pub fn add_dynamic(&mut self, mut actor: RigidDynamic) -> BodyHandle {
        unsafe {
            PxScene_addActor_mut(
                self.px_scene.write().unwrap().expect("accessing null ptr"),
                actor.get_raw_mut() as *mut PxActor,
                null(),
            );
        }

        let handle = BodyHandle(actor.get_raw() as usize);
        self.dynamics.push(actor);
        handle
    }

    /// Add a multibody articulation to the world
    /// TODO: Make this take a boxed-trait object or similar instead
    pub fn add_articulation<T: FnOnce(&mut ArticulationReducedCoordinate)>(
        &mut self,
        mut mb: ArticulationReducedCoordinate,
        func: T,
    ) -> PartHandle {
        let handle = mb.root_handle();
        func(&mut mb);

        let scene = self.px_scene.write().unwrap();
        unsafe {
            PxScene_addArticulation_mut(
                scene.expect("accessing null ptr"),
                mb.deref_mut().get_raw_mut(),
            );
        }
        mb.common_init();
        self.bodies.push(mb);
        handle
    }

    /// Remove an articulation from the world
    pub fn remove_articulation(&mut self, handle: BodyHandle) {
        unsafe {
            let articulation = handle.0 as *const PxArticulationBase;
            PxScene_removeArticulation_mut(
                self.px_scene.write().unwrap().expect("accessing null ptr"),
                articulation as *mut PxArticulationBase,
                false,
            );

            if let Some(idx) = self
                .bodies
                .iter()
                .position(|b| b.deref().get_raw() == articulation)
            {
                let mut body = self.bodies.swap_remove(idx);
                body.release();
            }
        }
    }

    ////////////////////////////////////////////////////////////////////////////////

    pub fn simulate(&mut self, duration: f32) {
        let scene = self.px_scene.write().unwrap();
        unsafe {
            PxScene_simulate_mut(
                scene.expect("accessing null ptr"),
                duration,
                null_mut(),
                null_mut(),
                0,
                true,
            );
        }
    }

    ////////////////////////////////////////////////////////////////////////////////

    pub fn fetch_results(&mut self, block: bool) -> Result<(), u32> {
        let scene = self.px_scene.write().unwrap();
        unsafe {
            let mut error: u32 = 0;
            PxScene_fetchResults_mut(scene.expect("accessing null ptr"), block, &mut error);
            if error == 0 {
                Ok(())
            } else {
                Err(error)
            }
        }
    }
    //    fn read(self) -> std::sync::RwLockReadGuard<Px>

    pub fn get_multibody(&self, handle: BodyHandle) -> Option<&ArticulationReducedCoordinate> {
        self.bodies.iter().find(|bod| bod.handle() == handle)
    }

    pub fn get_multibody_mut(
        &mut self,
        handle: BodyHandle,
    ) -> Option<&mut ArticulationReducedCoordinate> {
        self.bodies.iter_mut().find(|bod| bod.handle() == handle)
    }

    pub fn sample_height(
        &self,
        position: Vec3,
        ignored: Option<&RigidActor>,
        ignore_dynamic: bool,
    ) -> Option<Vec3> {
        // todo[tolsson]: clean this up
        let ignored_body = if let Some(body) = ignored {
            body.get_raw()
        } else {
            null_mut()
        };

        let down = -Vec3::unit_y();
        let max_dist = 1e5;

        unsafe {
            let mut filter_data = PxQueryFilterData_new_2(PxQueryFlags {
                mBits: (PxQueryFlag::ePREFILTER | PxQueryFlag::eSTATIC) as u16,
            });

            if !ignore_dynamic {
                filter_data.flags.mBits |= PxQueryFlag::eDYNAMIC as u16;
            }

            let filter_callback = create_raycast_filter_callback(ignored_body);
            let mut hit = std::mem::MaybeUninit::uninit();

            let hit_anything = PxSceneQueryExt_raycastSingle_mut(
                self.px_scene
                    .read()
                    .expect("failed reading from scene")
                    .expect("accessing null ptr"),
                &gl_to_px_v3(position),
                &gl_to_px_v3(down),
                max_dist,
                PxSceneQueryFlags {
                    mBits: PxHitFlag::ePOSITION as u16,
                },
                hit.as_mut_ptr(),
                &filter_data as *const PxQueryFilterData as *const PxSceneQueryFilterData,
                filter_callback as *mut PxQueryFilterCallback as *mut PxSceneQueryFilterCallback,
                null_mut(),
            );

            let hit = hit.assume_init();

            PxQueryFilterCallback_delete(filter_callback);

            if hit_anything {
                Some(px_to_gl_v3(hit.position))
            } else {
                None
            }
        }
    }

    pub fn set_simulation_event_callback<T>(
        &mut self,
        callback: physx_sys::CollisionCallback,
        userdata: *mut T,
    ) {
        unsafe {
            let callback =
                physx_sys::create_contact_callback(callback, userdata as *mut std::ffi::c_void);
            self.simulation_callback = Some(callback);
            PxScene_setSimulationEventCallback_mut(
                self.px_scene
                    .write()
                    .expect("failed reading scene")
                    .expect("accessing null ptr"),
                callback,
            );
        }
    }

    /// Lookup and retrieve a RigidStatic reference for this handle
    pub fn get_static(&self, handle: BodyHandle) -> Option<&RigidStatic> {
        self.statics.iter().find(|elem| handle == elem.handle())
    }

    /// Lookup and retrieve a RigidStatic reference for this handle
    pub fn get_static_mut(&mut self, handle: BodyHandle) -> Option<&mut RigidStatic> {
        self.statics.iter_mut().find(|elem| handle == elem.handle())
    }

    /// Lookup and retrieve a RigidDynamic reference for this handle
    pub fn get_dynamic(&self, handle: BodyHandle) -> Option<&RigidDynamic> {
        self.dynamics.iter().find(|elem| handle == elem.handle())
    }

    /// Lookup and retrieve a RigidDynamic reference for this handle
    pub fn get_dynamic_mut(&mut self, handle: BodyHandle) -> Option<&mut RigidDynamic> {
        self.dynamics
            .iter_mut()
            .find(|elem| handle == elem.handle())
    }

    /// Lookup and retrieve a RigidActor reference for this handle
    pub fn get_rigid_actor(&self, handle: BodyHandle) -> Option<&RigidActor> {
        if let Some(dynamic) = self.get_dynamic(handle) {
            Some(dynamic)
        } else if let Some(static_) = self.get_static(handle) {
            Some(static_)
        } else {
            for body in &self.bodies {
                let art_handle = body.handle();
                let part_handle = PartHandle(art_handle.0, handle.0);
                let part = body.part_from_handle(part_handle);
                if part.is_some() {
                    return part.map(|link| link.deref().deref());
                }
            }
            None
        }
    }

    /// Retrieve a RigidActor based on the bodyhandle. Note: This API is unsafe
    /// and bypasses a lot of safety checks for lifetimes and ownership.
    pub unsafe fn get_rigid_actor_unchecked(&self, handle: &BodyHandle) -> &RigidActor {
        // Clippy this is the right way to do it instead of a transmute...
        &*(handle as *const BodyHandle as *const super::px_type::PxType<PxRigidActor>)
    }

    pub fn find_matching_rigid_actor_mut(
        &mut self,
        actor: *const PxRigidActor,
    ) -> Option<&mut RigidActor> {
        if let Some(rigid) = self
            .statics
            .iter_mut()
            .find(|elem| actor == elem.get_raw() as *const PxRigidActor)
        {
            return Some(rigid);
        } else if let Some(rigid) = self
            .dynamics
            .iter_mut()
            .find(|elem| actor == elem.get_raw() as *const PxRigidActor)
        {
            return Some(rigid);
        };

        for body in &mut self.bodies {
            let handle = body.handle();
            let handle = PartHandle(handle.0, actor as usize);
            let part = body.part_from_handle_mut(handle);
            if part.is_some() {
                return part.map(|link| link.deref_mut().deref_mut());
            }
        }

        None
    }

    // pub fn find_matching_rigid_actor(&self, actor: *const PxRigidActor) -> Option<&RigidActor> {
    //     if let Some(rigid) = self.statics.iter().find_map(|elem| {
    //         let actor_ptr = elem.get_raw() as *const PxRigidActor;
    //         if actor == actor_ptr {
    //             Some(elem)
    //         } else {
    //             None
    //         }
    //     }) {
    //         return Some(rigid);
    //     };

    //     for body in &self.bodies {
    //         let handle = body.handle();
    //         let handle = PartHandle(handle.0, actor as usize);
    //         let part = body.part_from_handle(handle);
    //         if part.is_some() {
    //             return part.map(|link| link.deref().deref());
    //         }
    //     }

    //     None
    // }

    /// Looking
    pub fn collide_raw_pair(
        &mut self,
        first_px_actor: *mut PxRigidActor,
        second_px_actor: *mut PxRigidActor,
        pairs: &[PxContactPair],
    ) {
        // This function is really unrustic, but I can't find a nice way to do it
        // since the lookup of either collision member will take a mutable borrow on the scene...
        // However doing it with two pointers bypasses this, disgustingly enough. The NonNull
        // probably adds a bit of overhead, but in comparison to the search it's likely fine.
        if first_px_actor != second_px_actor {
            unsafe {
                // Since each lookup might traverse a lot of pointers we verify each lookup directly.
                let first_actor = self
                    .find_matching_rigid_actor_mut(first_px_actor)
                    .map(|val| val as *mut RigidActor);

                if let Some(first) = first_actor {
                    #[allow(clippy::transmute_ptr_to_ref)]
                    let first: &mut RigidActor = std::mem::transmute(first);
                    let second_actor = self
                        .find_matching_rigid_actor_mut(second_px_actor)
                        .map(|val| val as *mut RigidActor);

                    if let Some(second) = second_actor {
                        #[allow(clippy::transmute_ptr_to_ref)]
                        let second: &mut RigidActor = std::mem::transmute(second);
                        first.on_collide(second, pairs);
                        second.on_collide(first, pairs);
                    }
                }
            }
        }
    }

    pub fn get_bodies(&self) -> &Vec<ArticulationReducedCoordinate> {
        &self.bodies
    }

    ////////////////////////////////////////////////////////////////////////////////

    pub fn step(&mut self, step: f32, block: bool) {
        let scene = self.px_scene.write().unwrap();
        unsafe {
            PxScene_simulate_mut(
                scene.expect("accessing null ptr"),
                step,
                null_mut(),
                null_mut(),
                0,
                true,
            );
            PxScene_fetchResults_mut(scene.expect("accessing null ptr"), block, null_mut());
        }
    }

    fn add_controller_manager(&mut self, locking_enabled: bool) {
        if self.controller_manager.is_none() {
            self.controller_manager = Some(ControllerManager::new(
                self.px_scene.write().unwrap().expect("accessing null ptr"),
                locking_enabled,
            ))
        }
    }
}

#[derive(Debug, Clone, Copy, BitFlags)]
#[repr(u32)]
pub enum BroadPhaseType {
    SweepAndPrune = 1,
    MultiBoxPruning = 2,
    AutomaticBoxPruning = 4,
    GPU = 8,
}

impl Into<PxBroadPhaseType::Enum> for BroadPhaseType {
    fn into(self) -> PxBroadPhaseType::Enum {
        match self {
            BroadPhaseType::SweepAndPrune => 0,
            BroadPhaseType::MultiBoxPruning => 1,
            BroadPhaseType::AutomaticBoxPruning => 2,
            BroadPhaseType::GPU => 3,
        }
    }
}

pub enum SimulationThreadType {
    Dedicated(u32),
    Shared(*mut PxCpuDispatcher),
    Default,
}

pub struct SceneBuilder {
    pub(crate) gravity: Vec3,
    pub(crate) simulation_filter_shader: Option<SimulationFilterShader>,
    pub(crate) simulation_threading: Option<SimulationThreadType>,
    pub(crate) broad_phase_type: BroadPhaseType,
    pub(crate) use_controller_manager: bool,
    pub(crate) controller_manager_locking: bool,
    pub(crate) call_default_filter_shader_first: bool,
    pub(crate) use_ccd: bool,
    pub(crate) enable_ccd_resweep: bool,
}

impl Default for SceneBuilder {
    fn default() -> Self {
        Self {
            gravity: Vec3::new(0.0, -9.80665, 0.0), // standard gravity value
            call_default_filter_shader_first: true,
            simulation_filter_shader: None,
            simulation_threading: None,
            broad_phase_type: BroadPhaseType::SweepAndPrune,
            use_controller_manager: false,
            controller_manager_locking: false,
            use_ccd: false,
            enable_ccd_resweep: false,
        }
    }
}

impl SceneBuilder {
    /// Set the gravity for the scene.
    ///
    /// Default: [0.0, -9.80665, 0.0] (standard gravity)
    pub fn set_gravity(&mut self, gravity: Vec3) -> &mut Self {
        self.gravity = gravity;
        self
    }

    /// Set a callback to be invoked on various simulation events. Note:
    /// Currently only handles collision events
    ///
    /// Default: not set
    pub fn set_simulation_filter_shader(
        &mut self,
        simulation_filter_shader: SimulationFilterShader,
    ) -> &mut Self {
        self.simulation_filter_shader = Some(simulation_filter_shader);
        self
    }

    /// Enable the controller manager on the scene.
    ///
    /// Default: false, false
    pub fn use_controller_manager(
        &mut self,
        use_controller_manager: bool,
        locking_enabled: bool,
    ) -> &mut Self {
        self.use_controller_manager = use_controller_manager;
        self.controller_manager_locking = locking_enabled;
        self
    }

    /// Sets whether the filter should begin by calling the default filter shader
    /// PxDefaultSimulationFilterShader that emulates the PhysX 2.8 rules.
    ///
    /// Default: true
    pub fn set_call_default_filter_shader_first(
        &mut self,
        call_default_filter_shader_first: bool,
    ) -> &mut Self {
        self.call_default_filter_shader_first = call_default_filter_shader_first;
        self
    }

    /// Set the number of threads to use for simulation
    ///
    /// Default: not set
    pub fn set_simulation_threading(
        &mut self,
        simulation_threading: SimulationThreadType,
    ) -> &mut Self {
        self.simulation_threading = Some(simulation_threading);
        self
    }

    /// Set collision detection type
    ///
    /// Default: Sweep and prune
    pub fn set_broad_phase_type(&mut self, broad_phase_type: BroadPhaseType) -> &mut Self {
        self.broad_phase_type = broad_phase_type;
        self
    }

    /// Set if CCD (continuous collision detection) should be available for use in the scene.
    /// Doesn't automatically enable it for all rigid bodies, they still need to be flagged.
    ///
    /// If you don't set enable_ccd_resweep to true, eDISABLE_CCD_RESWEEP is set, which improves performance
    /// at the cost of accuracy right after bounces.
    ///
    /// Default: false, false
    pub fn set_use_ccd(&mut self, use_ccd: bool, enable_ccd_resweep: bool) -> &mut Self {
        self.use_ccd = use_ccd;
        self.enable_ccd_resweep = enable_ccd_resweep;
        self
    }

    pub(super) fn build_desc(&self, physics: &mut Physics) -> PxSceneDesc {
        unsafe {
            let tolerances = physics.get_tolerances_scale();
            let mut scene_desc = PxSceneDesc_new(tolerances);

            let dispatcher = match self.simulation_threading.as_ref().expect("foo") {
                SimulationThreadType::Default => {
                    phys_PxDefaultCpuDispatcherCreate(1, null_mut()) as *mut _
                }
                SimulationThreadType::Dedicated(count) => {
                    phys_PxDefaultCpuDispatcherCreate(*count, null_mut()) as *mut _
                }
                SimulationThreadType::Shared(dispatcher) => *dispatcher as *mut _,
            };

            scene_desc.cpuDispatcher = dispatcher;
            scene_desc.gravity = gl_to_px_v3(self.gravity);
            if self.use_ccd {
                scene_desc.flags.mBits |= PxSceneFlag::eENABLE_CCD;
                if !self.enable_ccd_resweep {
                    scene_desc.flags.mBits |= PxSceneFlag::eDISABLE_CCD_RESWEEP;
                }
            }
            if let Some(filter_shader) = self.simulation_filter_shader {
                physx_sys::enable_custom_filter_shader(
                    &mut scene_desc as *mut PxSceneDesc,
                    filter_shader,
                    if self.call_default_filter_shader_first {
                        1
                    } else {
                        0
                    },
                );
            } else {
                scene_desc.filterShader = get_default_simulation_filter_shader();
            }
            scene_desc
        }
    }

    /// Build a new Scene from the provided parameters
    pub(super) fn build(&self, physics: &mut Physics) -> Scene {
        unsafe {
            let scene_desc = self.build_desc(physics);
            let px_scene = PxPhysics_createScene_mut(physics.get_raw_mut(), &scene_desc);
            let mut scene = Scene::new(px_scene);

            if self.use_controller_manager {
                scene.add_controller_manager(self.controller_manager_locking);
            }
            scene
        }
    }
}