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
#![warn(clippy::all)]

use crate::{
    material::Material,
    math::{PxExtendedVec3, PxVec3},
    owner::Owner,
    traits::{Class, UserData},
};

use std::{ffi::c_void, marker::PhantomData, mem::size_of, ptr::drop_in_place};

use thiserror::Error;

use physx_sys::{
    PxBoxControllerDesc_delete,
    PxBoxControllerDesc_isValid,
    PxBoxControllerDesc_new_alloc,
    PxBoxController_getHalfForwardExtent,
    PxBoxController_getHalfHeight,
    PxBoxController_getHalfSideExtent,
    PxBoxController_setHalfForwardExtent_mut,
    PxBoxController_setHalfHeight_mut,
    PxBoxController_setHalfSideExtent_mut,
    PxCapsuleControllerDesc_delete,
    PxCapsuleControllerDesc_isValid,
    PxCapsuleControllerDesc_new_alloc,
    //PxController_getActor,
    PxCapsuleController_getClimbingMode,
    PxCapsuleController_getHeight,
    PxCapsuleController_getRadius,
    PxCapsuleController_setClimbingMode_mut,
    PxCapsuleController_setHeight_mut,
    PxCapsuleController_setRadius_mut,
    PxController,
    PxController_getPosition,
    PxController_getUserData,
    PxController_release_mut,
    PxController_setPosition_mut,
    PxController_setUserData_mut,
};

pub trait Controller: Class<PxController> + Sized {
    type UserData;
    type Descriptor: Class<physx_sys::PxControllerDesc>;

    /// Retrieve the user data from the controller.
    // Due to the size trick employed and the API decision to expose this userData via method calls,
    // get_user_data_mut will not work for small sizes of U, since getUserData returns a copy of the field,
    // rather than being able to write a method that returns a pointer to the field or the field itself.
    fn get_user_data(&self) -> &Self::UserData {
        unsafe {
            if size_of::<Self::UserData>() > size_of::<*mut c_void>() {
                // Cast *mut c_void to appropriate type and reborrow
                &*(PxController_getUserData(self.as_ptr()) as *const Self::UserData)
            } else {
                // DATA_SIZE < VOID_SIZE
                // The data is packed into the "*mut c_void"
                &*(&PxController_getUserData(self.as_ptr()) as *const *mut c_void
                    as *const Self::UserData)
            }
        }
    }

    /// Sets the controllers user data.  If U is larger than a *mut _, it is heap allocated in a box.
    /// Otherwise, it is packed directly into the *mut c_void userData field.
    fn set_user_data(&mut self, user_data: Self::UserData) -> &mut Self {
        unsafe {
            let user_data: *mut c_void = if size_of::<Self::UserData>() > size_of::<*mut c_void>() {
                // Allocate on heap since it is too large to pack into *mut c_void field
                let user_data = Box::new(user_data);
                // Cast to *mut c_void
                Box::into_raw(user_data) as *mut c_void
            } else {
                // DATA_SIZE < VOID_SIZE
                // The data is small enough to be packed directly into the "*mut c_void"
                *(&user_data as *const Self::UserData as *const *mut c_void)
            };
            PxController_setUserData_mut(self.as_mut_ptr(), user_data);
        }
        self
    }

    /// Set the position of teh controller
    fn set_position(&mut self, position: impl Into<PxExtendedVec3>) {
        unsafe {
            let position: PxExtendedVec3 = position.into();
            PxController_setPosition_mut(self.as_mut_ptr(), position.as_ptr());
        }
    }

    /// Get the position of the controller.
    fn get_position(&self) -> PxVec3 {
        unsafe { (*PxController_getPosition(self.as_ptr())).into() }
    }
}

#[repr(transparent)]
pub struct PxCapsuleController<U> {
    obj: physx_sys::PxCapsuleController,
    phantom_user_data: PhantomData<U>,
}

unsafe impl<T, U> Class<T> for PxCapsuleController<U>
where
    physx_sys::PxCapsuleController: Class<T>,
{
    fn as_ptr(&self) -> *const T {
        self.obj.as_ptr()
    }

    fn as_mut_ptr(&mut self) -> *mut T {
        self.obj.as_mut_ptr()
    }
}

impl<U> Drop for PxCapsuleController<U> {
    fn drop(&mut self) {
        unsafe {
            if size_of::<U>() > size_of::<*mut c_void>() {
                drop_in_place(PxController_getUserData(self.as_ptr()) as *mut U);
            } else {
                drop_in_place(
                    (&mut PxController_getUserData(self.as_ptr())) as *mut *mut c_void as *mut U,
                );
            };
            PxController_release_mut(self.as_mut_ptr())
        }
    }
}

unsafe impl<U: Send> Send for PxCapsuleController<U> {}
unsafe impl<U: Sync> Sync for PxCapsuleController<U> {}

impl<U> Controller for PxCapsuleController<U> {
    type UserData = U;
    type Descriptor = PxCapsuleControllerDesc<U>;
}

impl<U> CapsuleController for PxCapsuleController<U> {}

pub trait CapsuleController: Class<physx_sys::PxCapsuleController> + Controller {
    /// Get the climbing mode of the capsule controller.
    fn get_climbing_mode(&self) -> CapsuleClimbingMode {
        unsafe { PxCapsuleController_getClimbingMode(self.as_ptr()).into() }
    }

    /// Get the height of the capsule.
    fn get_height(&self) -> f32 {
        unsafe { PxCapsuleController_getHeight(self.as_ptr()) }
    }

    /// Get the radius of the capsule.
    fn get_radius(&self) -> f32 {
        unsafe { PxCapsuleController_getRadius(self.as_ptr()) }
    }

    /// Set the climbing mode of the capsule controller.
    fn set_climbing_mode(&mut self, mode: CapsuleClimbingMode) -> bool {
        unsafe { PxCapsuleController_setClimbingMode_mut(self.as_mut_ptr(), mode.into()) }
    }

    /// Set the height of the capsule.
    fn set_height(&mut self, height: f32) -> bool {
        unsafe { PxCapsuleController_setHeight_mut(self.as_mut_ptr(), height) }
    }

    /// Set the radius of the capsule.
    fn set_radius(&mut self, radius: f32) -> bool {
        unsafe { PxCapsuleController_setRadius_mut(self.as_mut_ptr(), radius) }
    }
}

/// A new type wrapper for `physx_sys::PxCapsuleControllerDesc`, parametrized by the user data type.
#[repr(transparent)]
pub struct PxCapsuleControllerDesc<U> {
    pub(crate) obj: physx_sys::PxCapsuleControllerDesc,
    phantom_user_data: PhantomData<U>,
}

unsafe impl<T, U> Class<T> for PxCapsuleControllerDesc<U>
where
    physx_sys::PxCapsuleControllerDesc: Class<T>,
{
    fn as_ptr(&self) -> *const T {
        self.obj.as_ptr()
    }

    fn as_mut_ptr(&mut self) -> *mut T {
        self.obj.as_mut_ptr()
    }
}

impl<U> PxCapsuleControllerDesc<U> {
    /// Create a new capsule controller descriptor.
    pub fn new<M: Material>(
        height: f32,
        radius: f32,
        step_offset: f32,
        material: &mut M,
        user_data: U,
        position: PxExtendedVec3,
    ) -> Option<Owner<Self>> {
        unsafe {
            let mut desc =
                PxCapsuleControllerDesc::from_raw(PxCapsuleControllerDesc_new_alloc(), user_data)?;
            desc.obj.height = height;
            desc.obj.radius = radius;
            desc.obj.stepOffset = step_offset;
            desc.obj.material = material.as_mut_ptr();
            desc.obj.upDirection = PxVec3::new(0.0, 1.0, 0.0).into();
            desc.obj.position = position.into();

            if PxCapsuleControllerDesc_isValid(desc.as_ptr()) {
                Some(desc)
            } else {
                None
            }
        }
    }

    /// # Safety
    /// Owner's own the pointer they wrap, using the pointer after dropping the Owner,
    /// or creating multiple Owners from the same pointer will cause UB.  Use `into_ptr` to
    /// retrieve the pointer and consume the Owner without dropping the pointee.
    unsafe fn from_raw(
        ptr: *mut physx_sys::PxCapsuleControllerDesc,
        user_data: U,
    ) -> Option<Owner<Self>> {
        Owner::from_raw((ptr as *mut Self).as_mut()?.init_user_data(user_data))
    }
}

unsafe impl<U> UserData for PxCapsuleControllerDesc<U> {
    type UserData = U;

    fn user_data_ptr(&self) -> &*mut c_void {
        &self.obj.userData
    }

    fn user_data_ptr_mut(&mut self) -> &mut *mut c_void {
        &mut self.obj.userData
    }
}

impl<U> Drop for PxCapsuleControllerDesc<U> {
    fn drop(&mut self) {
        unsafe {
            drop_in_place(UserData::get_user_data_mut(self) as *mut _);
            PxCapsuleControllerDesc_delete(self.as_mut_ptr());
        }
    }
}

#[repr(transparent)]
pub struct PxBoxController<U> {
    obj: physx_sys::PxBoxController,
    phantom_user_data: PhantomData<U>,
}

unsafe impl<T, U> Class<T> for PxBoxController<U>
where
    physx_sys::PxBoxController: Class<T>,
{
    fn as_ptr(&self) -> *const T {
        self.obj.as_ptr()
    }

    fn as_mut_ptr(&mut self) -> *mut T {
        self.obj.as_mut_ptr()
    }
}

impl<U> Drop for PxBoxController<U> {
    fn drop(&mut self) {
        unsafe {
            if size_of::<U>() > size_of::<*mut c_void>() {
                drop_in_place(PxController_getUserData(self.as_ptr()) as *mut U);
            } else {
                drop_in_place(
                    (&mut PxController_getUserData(self.as_ptr())) as *mut *mut c_void as *mut U,
                );
            };
            PxController_release_mut(self.as_mut_ptr())
        }
    }
}

unsafe impl<U: Send> Send for PxBoxController<U> {}
unsafe impl<U: Sync> Sync for PxBoxController<U> {}

impl<U> Controller for PxBoxController<U> {
    type UserData = U;
    type Descriptor = PxBoxControllerDesc<U>;
}

impl<U> BoxController for PxBoxController<U> {}

pub trait BoxController: Class<physx_sys::PxBoxController> + Controller {
    /// Get the half forward extent.
    fn get_half_forward_extent(&self) -> f32 {
        unsafe { PxBoxController_getHalfForwardExtent(self.as_ptr()) }
    }

    /// Get the half height.
    fn get_half_height(&self) -> f32 {
        unsafe { PxBoxController_getHalfHeight(self.as_ptr()) }
    }

    /// Get the half side extent.
    fn get_half_side_extent(&self) -> f32 {
        unsafe { PxBoxController_getHalfSideExtent(self.as_ptr()) }
    }

    /// Set the half forward extent.
    fn set_half_forward_extent(&mut self, extent: f32) -> bool {
        unsafe { PxBoxController_setHalfForwardExtent_mut(self.as_mut_ptr(), extent) }
    }

    /// Set the half height.
    fn set_half_height(&mut self, height: f32) -> bool {
        unsafe { PxBoxController_setHalfHeight_mut(self.as_mut_ptr(), height) }
    }

    /// Set the half side extent.
    fn set_half_side_extent(&mut self, extent: f32) -> bool {
        unsafe { PxBoxController_setHalfSideExtent_mut(self.as_mut_ptr(), extent) }
    }
}

/// A new type wrapper for `physx_sys::PxBoxControllerDesc`, parametrized by the user data type.
#[repr(transparent)]
pub struct PxBoxControllerDesc<U> {
    obj: physx_sys::PxBoxControllerDesc,
    phantom_user_data: PhantomData<U>,
}

unsafe impl<T, U> Class<T> for PxBoxControllerDesc<U>
where
    physx_sys::PxBoxControllerDesc: Class<T>,
{
    fn as_ptr(&self) -> *const T {
        self.obj.as_ptr()
    }

    fn as_mut_ptr(&mut self) -> *mut T {
        self.obj.as_mut_ptr()
    }
}

impl<U> PxBoxControllerDesc<U> {
    /// Create a new box controller descriptor.
    pub fn new<M: Material>(
        half_height: f32,
        half_side_extent: f32,
        half_forward_extent: f32,
        step_offset: f32,
        material: &mut M,
        user_data: U,
        position: PxExtendedVec3,
    ) -> Option<Owner<Self>> {
        unsafe {
            let mut desc =
                PxBoxControllerDesc::from_raw(PxBoxControllerDesc_new_alloc(), user_data)?;
            desc.obj.halfHeight = half_height;
            desc.obj.halfSideExtent = half_side_extent;
            desc.obj.halfForwardExtent = half_forward_extent;
            desc.obj.stepOffset = step_offset;
            desc.obj.material = material.as_mut_ptr();
            desc.obj.upDirection = PxVec3::new(0.0, 1.0, 0.0).into();
            desc.obj.position = position.into();

            if PxBoxControllerDesc_isValid(desc.as_ptr()) {
                Some(desc)
            } else {
                None
            }
        }
    }

    /// # Safety
    /// Owner's own the pointer they wrap, using the pointer after dropping the Owner,
    /// or creating multiple Owners from the same pointer will cause UB.  Use `into_ptr` to
    /// retrieve the pointer and consume the Owner without dropping the pointee.
    unsafe fn from_raw(
        ptr: *mut physx_sys::PxBoxControllerDesc,
        user_data: U,
    ) -> Option<Owner<Self>> {
        Owner::from_raw((ptr as *mut Self).as_mut()?.init_user_data(user_data))
    }
}

unsafe impl<U> UserData for PxBoxControllerDesc<U> {
    type UserData = U;

    fn user_data_ptr(&self) -> &*mut c_void {
        &self.obj.userData
    }

    fn user_data_ptr_mut(&mut self) -> &mut *mut c_void {
        &mut self.obj.userData
    }
}

impl<U> Drop for PxBoxControllerDesc<U> {
    fn drop(&mut self) {
        unsafe {
            drop_in_place(UserData::get_user_data_mut(self) as *mut _);
            PxBoxControllerDesc_delete(self.as_mut_ptr())
        }
    }
}

#[derive(Error, Debug)]
pub enum ControllerError {
    #[error(
        "Controller description is invalid. height={}, radius={}, step_offset={}",
        height,
        radius,
        step_offset
    )]
    InvalidDescription {
        height: f32,
        radius: f32,
        step_offset: f32,
    },

    #[error("No controller manager present")]
    NoControllerManager,
}

#[derive(Copy, Clone)]
pub enum CapsuleClimbingMode {
    Easy,
    Constrained,
}

impl From<CapsuleClimbingMode> for physx_sys::PxCapsuleClimbingMode::Enum {
    fn from(value: CapsuleClimbingMode) -> Self {
        match value {
            CapsuleClimbingMode::Easy => physx_sys::PxCapsuleClimbingMode::eEASY,
            CapsuleClimbingMode::Constrained => physx_sys::PxCapsuleClimbingMode::eCONSTRAINED,
        }
    }
}

impl From<physx_sys::PxCapsuleClimbingMode::Enum> for CapsuleClimbingMode {
    fn from(mode: physx_sys::PxCapsuleClimbingMode::Enum) -> Self {
        match mode {
            physx_sys::PxCapsuleClimbingMode::eEASY => CapsuleClimbingMode::Easy,
            physx_sys::PxCapsuleClimbingMode::eCONSTRAINED => CapsuleClimbingMode::Constrained,
            _ => unreachable!("invalid PxCapsuleClimbingMode: {:?}", mode),
        }
    }
}