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

#![warn(clippy::all)]

/*!

*/

use super::{foundation::Foundation, owner::Owner, traits::Class};

use enumflags2::{bitflags, BitFlags};

use physx_sys::{
    phys_PxCreatePvd, phys_PxDefaultPvdSocketTransportCreate, PxPvdInstrumentationFlag,
    PxPvdInstrumentationFlags, PxPvdSceneClient_setScenePvdFlags_mut, PxPvdSceneFlags,
    PxPvdTransport_release_mut, PxPvd_connect_mut, PxPvd_disconnect_mut, PxPvd_getTransport_mut,
    PxPvd_isConnected_mut, PxPvd_release_mut,
};

#[bitflags]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum VisualDebuggerSceneFlag {
    TransmitContacts = 1,
    TransmitSceneQueries = 2,
    TransmitConstraints = 4,
}

/// Combines the Pvd and it's current `PvdTransport`, if there is one.
pub struct VisualDebugger {
    pvd: Owner<Pvd>,
    transport: Option<Owner<PvdTransport>>,
    // Need to keep this field alive as the PvdTransport doesn't take ownership of the string.
    _host: std::ffi::CString,
}

unsafe impl Class<physx_sys::PxPvd> for VisualDebugger {
    fn as_ptr(&self) -> *const physx_sys::PxPvd {
        self.pvd.as_ptr()
    }

    fn as_mut_ptr(&mut self) -> *mut physx_sys::PxPvd {
        self.pvd.as_mut_ptr()
    }
}

impl VisualDebugger {
    /// Create a new `VisualDebugger` instance, a utility class that
    /// combines the TCP setup and the Pvd into one object. The port
    /// default for the PVD program is port 5425, so it is suggested to use this
    /// unless you're explicitly changing the other one as well.
    ///
    /// This function internally calls `new_with_timeout` with a default timeout
    /// of 10 ms.
    pub fn new(foundation: &mut impl Foundation, port: i32) -> Option<Self> {
        VisualDebugger::new_with_timeout(foundation, "localhost", port, 10)
    }

    /// Create a new `VisualDebugger` instance, a utility class that
    /// combines the TCP setup and the Pvd into one object. The port
    /// default for the PVD program is port 5425, so it is suggested to use this
    /// unless you're explicitly changing the other one as well.
    ///
    /// This function internally calls `new_with_timeout` with a default timeout
    /// of 10 ms.
    pub fn new_remote(foundation: &mut impl Foundation, host: &str, port: i32) -> Option<Self> {
        VisualDebugger::new_with_timeout(foundation, host, port, 10)
    }

    /// See description of `new`
    pub fn new_with_timeout(
        foundation: &mut impl Foundation,
        host: &str,
        port: i32,
        timeout: u32,
    ) -> Option<Self> {
        use std::ffi::CString;

        let flags = PxPvdInstrumentationFlags {
            mBits: PxPvdInstrumentationFlag::eDEBUG as u8,
        };
        let oshost = CString::new(host).ok()?;
        let pvd = unsafe { Pvd::from_raw(phys_PxCreatePvd(foundation.as_mut_ptr()))? };
        let transport = unsafe {
            PvdTransport::from_raw(phys_PxDefaultPvdSocketTransportCreate(
                oshost.as_ptr() as _,
                port,
                timeout,
            ))
        };

        let mut visual_debugger = Self {
            pvd,
            transport,
            _host: oshost,
        };

        if !visual_debugger.connect(flags) {
            return None;
        };
        Some(visual_debugger)
    }

    /// Connect the Pvd to the `PvdTransport`.
    pub fn connect(&mut self, flags: PxPvdInstrumentationFlags) -> bool {
        if let Some(transport) = self.transport.as_mut() {
            self.pvd.connect(transport.as_mut(), flags)
        } else {
            false
        }
    }

    /// Disconnect the Pvd it's transport.
    pub fn disconnect(&mut self) {
        self.pvd.disconnect();
    }

    /// Check if the Pvd is connected.  The cached status may be up to one frame out of date.
    /// When `use_cached_status` is false, the low-level status is checked which requires locking
    /// the network stream.
    pub fn is_connected(&mut self, use_cached_status: bool) -> bool {
        self.pvd.is_connected(use_cached_status)
    }

    /// Get the transport connected to the Pvd, if there is one.
    pub fn get_transport(&mut self) -> Option<&mut PvdTransport> {
        self.pvd.get_transport()
    }

    /// Connect to a new transport, disconnecting from and dropping the old one.
    /// Returns true if the connection succeeded.
    pub fn set_transport(
        &mut self,
        transport: Owner<PvdTransport>,
        flags: PxPvdInstrumentationFlags,
    ) -> bool {
        if self.is_connected(false) {
            self.disconnect();
        };
        self.transport.replace(transport);
        self.connect(flags)
    }
}

impl Drop for VisualDebugger {
    fn drop(&mut self) {
        if self.is_connected(false) {
            self.disconnect();
        };
    }
}

#[repr(transparent)]
pub struct PvdTransport {
    obj: physx_sys::PxPvdTransport,
}

crate::DeriveClassForNewType!(PvdTransport: PxPvdTransport);

impl PvdTransport {
    /// # 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.
    pub(crate) unsafe fn from_raw(
        ptr: *mut physx_sys::PxPvdTransport,
    ) -> Option<Owner<PvdTransport>> {
        Owner::from_raw(ptr as *mut Self)
    }
}

unsafe impl Send for PvdTransport {}
unsafe impl Sync for PvdTransport {}

impl Drop for PvdTransport {
    fn drop(&mut self) {
        unsafe {
            PxPvdTransport_release_mut(self.as_mut_ptr());
        }
    }
}

/// A new type wrapper for `PxPvd`.
#[repr(transparent)]
pub struct Pvd {
    obj: physx_sys::PxPvd,
}

crate::DeriveClassForNewType!(Pvd: PxPvd);

impl Pvd {
    /// # 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.
    pub(crate) unsafe fn from_raw(ptr: *mut physx_sys::PxPvd) -> Option<Owner<Self>> {
        Owner::from_raw(ptr as *mut Self)
    }

    /// Connect the visual debugger over the provided transport. Returns `true`
    /// if the connection succeded.
    pub fn connect(
        &mut self,
        transport: &mut PvdTransport,
        flags: PxPvdInstrumentationFlags,
    ) -> bool {
        unsafe { PxPvd_connect_mut(self.as_mut_ptr(), transport.as_mut_ptr(), flags) }
    }

    /// Disconnect from the transport.
    pub fn disconnect(&mut self) {
        unsafe { PxPvd_disconnect_mut(self.as_mut_ptr()) }
    }

    /// Check if the Pvd is connected.  The cached status may be up to one frame out of date.
    /// When `use_cached_status` is false, the low-level status is checked which requires locking
    /// the network stream.
    pub fn is_connected(&mut self, use_cached_status: bool) -> bool {
        unsafe { PxPvd_isConnected_mut(self.as_mut_ptr(), use_cached_status) }
    }

    /// Get the transport connected to the Pvd, if there is one.
    pub fn get_transport(&mut self) -> Option<&mut PvdTransport> {
        unsafe { (PxPvd_getTransport_mut(self.as_mut_ptr()) as *mut PvdTransport).as_mut() }
    }
}

unsafe impl Send for Pvd {}
unsafe impl Sync for Pvd {}

impl Drop for Pvd {
    fn drop(&mut self) {
        unsafe {
            PxPvd_release_mut(self.as_mut_ptr());
        }
    }
}

/// A new type wrapper for `PxPvdSceneClient`.
pub struct PvdSceneClient {
    obj: physx_sys::PxPvdSceneClient,
}

crate::DeriveClassForNewType!(PvdSceneClient: PxPvdSceneClient);

impl PvdSceneClient {
    /// # 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.
    #[allow(dead_code)]
    pub(crate) unsafe fn from_raw(ptr: *mut physx_sys::PxPvdSceneClient) -> Option<Owner<Self>> {
        Owner::from_raw(ptr as *mut Self)
    }

    /// Enable and disable what should be transmitted to the visual debugger
    /// instance.
    pub fn set_scene_flags(&mut self, flags: BitFlags<VisualDebuggerSceneFlag>) {
        unsafe {
            PxPvdSceneClient_setScenePvdFlags_mut(
                self.as_mut_ptr(),
                PxPvdSceneFlags {
                    mBits: flags.bits(),
                },
            )
        }
    }
}

unsafe impl Send for PvdSceneClient {}
unsafe impl Sync for PvdSceneClient {}