From 754a4bad801064b2027cb0d9f26bcb574b796aeb Mon Sep 17 00:00:00 2001 From: Xiaopeng Li Date: Thu, 20 Oct 2022 04:06:23 +0800 Subject: [PATCH] Add Surface::as_hal_mut (#3123) --- wgpu-core/src/resource.rs | 19 +++++++++++++++++++ wgpu/src/backend/direct.rs | 14 ++++++++++++++ wgpu/src/lib.rs | 15 +++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 85d4d97157..bda619f5b0 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -428,6 +428,25 @@ impl Global { hal_device_callback(hal_device) } + + /// # Safety + /// - The raw surface handle must not be manually destroyed + pub unsafe fn surface_as_hal_mut) -> R, R>( + &self, + id: SurfaceId, + hal_surface_callback: F, + ) -> R { + profiling::scope!("Surface::as_hal_mut"); + + let mut token = Token::root(); + let (mut guard, _) = self.surfaces.write(&mut token); + let surface = guard.get_mut(id).ok(); + let hal_surface = surface + .and_then(|surface| A::get_surface_mut(surface)) + .map(|surface| &mut surface.raw); + + hal_surface_callback(hal_surface) + } } #[derive(Clone, Copy, Debug)] diff --git a/wgpu/src/backend/direct.rs b/wgpu/src/backend/direct.rs index 06fcbb6f36..6daab45c5d 100644 --- a/wgpu/src/backend/direct.rs +++ b/wgpu/src/backend/direct.rs @@ -154,6 +154,20 @@ impl Context { .device_as_hal::(device.id, hal_device_callback) } + #[cfg(any(not(target_arch = "wasm32"), feature = "emscripten"))] + pub unsafe fn surface_as_hal_mut< + A: wgc::hub::HalApi, + F: FnOnce(Option<&mut A::Surface>) -> R, + R, + >( + &self, + surface: &Surface, + hal_surface_callback: F, + ) -> R { + self.0 + .surface_as_hal_mut::(surface.id, hal_surface_callback) + } + #[cfg(any(not(target_arch = "wasm32"), feature = "emscripten"))] pub unsafe fn texture_as_hal)>( &self, diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 2804244573..d5b6a16aca 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -3773,6 +3773,21 @@ impl Surface { }) .ok_or(SurfaceError::Lost) } + + /// Returns the inner hal Surface using a callback. The hal surface will be `None` if the + /// backend type argument does not match with this wgpu Surface + /// + /// # Safety + /// + /// - The raw handle obtained from the hal Surface must not be manually destroyed + #[cfg(any(not(target_arch = "wasm32"), feature = "emscripten"))] + pub unsafe fn as_hal_mut) -> R, R>( + &mut self, + hal_surface_callback: F, + ) -> R { + self.context + .surface_as_hal_mut::(&self.id, hal_surface_callback) + } } /// Type for the callback of uncaptured error handler