Ralith / openxrs

OpenXR bindings for Rust
Apache License 2.0
282 stars 59 forks source link

Support drop guard for session #86

Closed zmerp closed 3 years ago

zmerp commented 3 years ago

This PR allows to pass a custom object to Instance::create_session() used to force a specific drop order. In particular, in case the graphics device and instance is kept around in a clonable object (with a proper impl Drop) and its time of destruction is unknown, the drop_guard argument should be set to a clone of this object. For context, here is a related PR: https://github.com/gfx-rs/wgpu/pull/1609

This is needed for OpenXR support in bevy. Until now this solution was used:

#[derive(Clone)]
pub struct OpenXrSession {
    inner: Option<xr::Session<xr::AnyGraphics>>,
    _wgpu_device: Arc<wgpu::Device>,
}

impl Deref for OpenXrSession {
    type Target = xr::Session<xr::AnyGraphics>;

    fn deref(&self) -> &Self::Target {
        self.inner.as_ref().unwrap()
    }
}

impl Drop for OpenXrSession {
    fn drop(&mut self) {
        // Drop OpenXR session before wgpu::Device.
        self.inner.take();
    }
}

Instead of exposing openxr::Session to the user directly, this OpenXrSession object is used. But the underlying openxr::Session is still cloned by the bevy plugin implementation (for interop with graphics), and this makes it tricky to ensure safety.

The vulkan example is updated, but it passes None as the drop guard since the drop order is already enforced and the example is linear.

zmerp commented 3 years ago

Thank you for the suggestion! I updated the PR.