From bd4d9a99b65083a6b1018a7f35f08edaec223d02 Mon Sep 17 00:00:00 2001 From: AdrianEddy Date: Tue, 30 Jun 2026 05:18:58 +0200 Subject: [PATCH] [WebGPU] Add the ability to interop with external textures (#9530) Co-authored-by: Kevin Reid --- CHANGELOG.md | 5 +++ wgpu/src/api/buffer.rs | 11 ++++- wgpu/src/api/device.rs | 68 +++++++++++++++++++++++++++++ wgpu/src/api/queue.rs | 11 +++++ wgpu/src/api/texture.rs | 18 +++++++- wgpu/src/api/texture_view.rs | 14 +++++- wgpu/src/backend/webgpu.rs | 83 ++++++++++++++++++++++++++++++++++-- wgpu/src/lib.rs | 18 ++++++++ 8 files changed, 219 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24126c72b..47c8f25db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -305,6 +305,11 @@ By @stuartparmenter in [#9658](https://github.com/gfx-rs/wgpu/pull/9658). - Fixed structure field names incorrectly ignoring reserved keywords in the Metal (MSL) backend. By @39ali [#9379](https://github.com/gfx-rs/wgpu/pull/9379). - Restore the `Queue::as_raw` method, which was removed without good reason in v29. It now returns `&ProtocolObject`. By @andyleiserson in [#9560](https://github.com/gfx-rs/wgpu/pull/9560). +#### WebGPU + +- Expose the underlying JS handles of WebGPU-backed resources via new `as_webgpu` accessors on `Texture`, `TextureView`, `Buffer`, `Queue`, and `Device`, returning `Option<&wgpu::webgpu::Gpu*>`. This is the WebGPU counterpart of `as_hal` (which returns `None` on the WebGPU backend, since WebGPU is not a `wgpu_hal` API). The vendored handle types are re-exported under the new `wgpu::webgpu` module. By @AdrianEddy in [#9530](https://github.com/gfx-rs/wgpu/pull/9530) +- Add `Device::create_texture_from_webgpu_handle(texture, desc, drop_callback)` for wrapping a foreign `webgpu::GpuTexture` (e.g. a canvas `getCurrentTexture()` result) as a `wgpu::Texture` without copy. Use the `drop_callback` to decide if you want to call `GpuTexture.destroy()` when wgpu is done with the texture. By @AdrianEddy in [#9530](https://github.com/gfx-rs/wgpu/pull/9530) + ### Dependency Updates #### WebGPU diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index 2619f9df3..57cf5f731 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -273,7 +273,9 @@ impl Buffer { /// /// This method will return None if: /// - The buffer is not from the backend specified by `A`. - /// - The buffer is from the `webgpu` or `custom` backend. + /// - The buffer is from [`Backend::BrowserWebGpu`]. + /// (Use `Buffer::as_webgpu()` instead.) + /// - The buffer is from a custom backend. /// - The buffer has had [`Self::destroy()`] called on it. /// /// # Safety @@ -455,6 +457,13 @@ impl Buffer { pub fn as_custom(&self) -> Option<&T> { self.inner.as_custom() } + + /// Returns the underlying [`webgpu::GpuBuffer`] handle if this `Buffer` + /// is on the WebGPU backend, otherwise `None`. + #[cfg(webgpu)] + pub fn as_webgpu(&self) -> Option<&webgpu::GpuBuffer> { + self.inner.as_webgpu_opt().map(|wb| &wb.inner) + } } /// A slice of a [`Buffer`], to be mapped, used for vertex or index data, or the like. diff --git a/wgpu/src/api/device.rs b/wgpu/src/api/device.rs index 8832b9a13..276b1c01b 100644 --- a/wgpu/src/api/device.rs +++ b/wgpu/src/api/device.rs @@ -315,6 +315,8 @@ impl Device { #[doc = crate::macros::hal_type_dx12!("Texture")] #[doc = crate::macros::hal_type_gles!("Texture")] /// + /// On [`Backend::BrowserWebGpu`], use `Device::create_texture_from_webgpu_handle()` instead. + /// /// # `initial_state` /// /// If the resource has already been initialized, `initial_state` should be @@ -361,6 +363,70 @@ impl Device { } } + /// Wraps a foreign [`webgpu::GpuTexture`] (e.g. a canvas `getCurrentTexture()` result) + /// as a [`Texture`] without any copy. + /// + /// The wrapped texture is *external*: dropping the returned `Texture` (or + /// calling [`Texture::destroy`] on it) does **not** call `GpuTexture.destroy()` + /// on the underlying handle - its lifetime is the caller's responsibility. + /// + /// If `drop_callback` is `Some`, it fires when wgpu releases its last + /// reference to the wrapped handle. wgpu never calls `GpuTexture.destroy()` + /// itself on a wrapped texture; to hand the handle's lifetime to wgpu, + /// supply a callback that calls `GpuTexture.destroy()`. The callback can + /// also be used to free a pool slot or notify dependent code that wgpu is + /// done with the handle. Pass `None` if the caller manages the handle's + /// lifetime entirely on their own. + /// + /// This is the WebGPU counterpart of [`Self::create_texture_from_hal`]. + /// A `Some` `drop_callback` plays the same role as `wgpu_hal::DropCallback` + /// does on the Vulkan backend. The `None` case differs: here the texture is + /// always external and wgpu never destroys it, whereas on Vulkan a `None` + /// callback means wgpu takes ownership of the image and destroys it. + /// + /// The caller must guarantee: + /// + /// 1. `texture` was produced by the same underlying `GpuDevice` that this `Device` wraps. + /// 2. `desc.format`, `desc.size`, `desc.usage`, `desc.dimension`, + /// `desc.mip_level_count`, and `desc.sample_count` match the actual + /// `GPUTexture`'s reflected values. wgpu stores these verbatim and + /// returns them from [`Texture::size`], [`Texture::format`], etc. + /// without re-checking the handle; a mismatch yields silently incorrect + /// metadata and, downstream, `GPUValidationError`s rather than memory + /// unsafety (the browser bounds every access). + /// 3. The underlying `GpuTexture` must remain alive for as long as wgpu + /// may use it (e.g. until any submitted command buffer that references + /// it has finished executing). If `drop_callback` is `Some`, it is + /// sufficient to keep the handle alive until the callback fires. + #[cfg(webgpu)] + #[must_use] + pub fn create_texture_from_webgpu_handle( + &self, + texture: webgpu::GpuTexture, + desc: &TextureDescriptor<'_>, + drop_callback: Option, + ) -> Texture { + let inner = self + .inner + .as_webgpu() + .wrap_external_texture(texture, drop_callback); + Texture { + inner, + descriptor: TextureDescriptor { + label: None, + view_formats: &[], + ..desc.clone() + }, + } + } + + /// Returns the underlying [`webgpu::GpuDevice`] handle if this `Device` + /// is on the WebGPU backend, otherwise `None`. + #[cfg(webgpu)] + pub fn as_webgpu(&self) -> Option<&webgpu::GpuDevice> { + self.inner.as_webgpu_opt().map(|wd| &wd.inner) + } + /// Creates a new [`ExternalTexture`]. #[must_use] pub fn create_external_texture( @@ -588,6 +654,8 @@ impl Device { /// - The device is not from the backend specified by `A`. /// - The device is from the `webgpu` or `custom` backend. /// + /// On the `webgpu` backend, use `as_webgpu` instead. + /// /// # Safety /// /// - The returned resource must not be destroyed unless the guard diff --git a/wgpu/src/api/queue.rs b/wgpu/src/api/queue.rs index 18832e444..13b4a2660 100644 --- a/wgpu/src/api/queue.rs +++ b/wgpu/src/api/queue.rs @@ -34,6 +34,15 @@ impl Queue { inner: dispatch::DispatchQueue::custom(queue), } } + + /// Returns the underlying [`webgpu::GpuQueue`] handle if this `Queue` + /// is on the WebGPU backend, otherwise `None`. + /// + /// [`webgpu::GpuQueue`]: crate::webgpu::GpuQueue + #[cfg(webgpu)] + pub fn as_webgpu(&self) -> Option<&webgpu::GpuQueue> { + self.inner.as_webgpu_opt().map(|wq| &wq.inner) + } } /// Identifier for a particular call to [`Queue::submit`]. Can be used @@ -337,6 +346,8 @@ impl Queue { /// - The queue is not from the backend specified by `A`. /// - The queue is from the `webgpu` or `custom` backend. /// + /// On the `webgpu` backend, use `as_webgpu` instead. + /// /// # Safety /// /// - The returned resource must not be destroyed unless the guard diff --git a/wgpu/src/api/texture.rs b/wgpu/src/api/texture.rs index a2be922bb..08a4e01d4 100644 --- a/wgpu/src/api/texture.rs +++ b/wgpu/src/api/texture.rs @@ -46,8 +46,9 @@ impl Texture { /// /// This method will return None if: /// - The texture is not from the backend specified by `A`. - /// - The texture is from the `webgpu` or `custom` backend. - /// - The texture has had [`Self::destroy()`] called on it. + /// - The texture is from [`Backend::BrowserWebGpu`]. + /// (Use `Texture::as_webgpu()` instead.) + /// - The texture is from a custom backend. /// /// # Safety /// @@ -63,6 +64,19 @@ impl Texture { unsafe { texture.context.texture_as_hal::(texture) } } + /// Returns the underlying [`webgpu::GpuTexture`] handle if this `Texture` + /// is on the WebGPU backend. + /// + /// Use this on the WebGPU backend instead of [`Self::as_hal`]. + /// + /// The returned handle is the same JS object wgpu uses internally; it can + /// be passed to other WebGPU-aware JS APIs, used for identity comparison, + /// or fed back into [`Device::create_texture_from_webgpu_handle`]. + #[cfg(webgpu)] + pub fn as_webgpu(&self) -> Option<&webgpu::GpuTexture> { + self.inner.as_webgpu_opt().map(|wt| &wt.inner) + } + #[cfg(custom)] /// Returns custom implementation of Texture (if custom backend and is internally T) pub fn as_custom(&self) -> Option<&T> { diff --git a/wgpu/src/api/texture_view.rs b/wgpu/src/api/texture_view.rs index 62aa45c46..c46d42f6d 100644 --- a/wgpu/src/api/texture_view.rs +++ b/wgpu/src/api/texture_view.rs @@ -58,8 +58,9 @@ impl TextureView { /// /// This method will return None if: /// - The texture view is not from the backend specified by `A`. - /// - The texture view is from the `webgpu` or `custom` backend. - /// - The texture this view points to has had [`Texture::destroy()`] called on it. + /// - The texture view is from [`Backend::BrowserWebGpu`]. + /// (Use `TextureView::as_webgpu()` instead.) + /// - The texture view is from a custom backend. /// /// # Safety /// @@ -75,6 +76,15 @@ impl TextureView { unsafe { view.context.texture_view_as_hal::(view) } } + /// Returns the underlying [`webgpu::GpuTextureView`] handle if this view + /// is on the WebGPU backend, otherwise `None`. + /// + /// [`webgpu::GpuTextureView`]: crate::webgpu::GpuTextureView + #[cfg(webgpu)] + pub fn as_webgpu(&self) -> Option<&webgpu::GpuTextureView> { + self.inner.as_webgpu_opt().map(|wv| &wv.inner) + } + #[cfg(custom)] /// Returns custom implementation of TextureView (if custom backend and is internally T) pub fn as_custom(&self) -> Option<&T> { diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index a914767dd..e1a71120a 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -3,7 +3,7 @@ mod defined_non_null_js_value; mod ext_bindings; #[allow(clippy::allow_attributes)] -mod webgpu_sys; +pub(crate) mod webgpu_sys; use alloc::{ boxed::Box, @@ -87,6 +87,37 @@ impl crate::Error { } } +/// A callback invoked when wgpu releases its reference to an externally +/// owned WebGPU resource (e.g. a `GpuTexture` passed to +/// [`crate::Device::create_texture_from_webgpu_handle`]). +/// +/// This is the WebGPU counterpart of [`wgpu_hal::DropCallback`]. +pub type DropCallback = Box; + +pub(crate) struct DropGuard { + callback: Option, +} + +impl DropGuard { + fn new(callback: Option) -> Self { + Self { callback } + } +} + +impl Drop for DropGuard { + fn drop(&mut self) { + if let Some(cb) = self.callback.take() { + cb(); + } + } +} + +impl fmt::Debug for DropGuard { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DropGuard").finish() + } +} + #[derive(Debug, Clone)] pub struct WebShaderModule { module: webgpu_sys::GpuShaderModule, @@ -1293,7 +1324,7 @@ struct WebBufferMapState { #[derive(Debug, Clone)] pub struct WebBuffer { /// The associated GPU buffer. - inner: webgpu_sys::GpuBuffer, + pub(crate) inner: webgpu_sys::GpuBuffer, /// The mapped array buffer and mapped range. mapping: Rc>, /// Unique identifier for this Buffer. @@ -1347,6 +1378,17 @@ impl WebBuffer { #[derive(Debug, Clone)] pub struct WebTexture { pub(crate) inner: webgpu_sys::GpuTexture, + /// Lifetime management for the underlying `GpuTexture`. + /// + /// - `None` means wgpu owns the handle: [`Self::destroy`] forwards to + /// `GpuTexture.destroy()`. (This is the case for textures created via + /// `device.createTexture` or `surface.getCurrentTexture`.) + /// - `Some(_)` means the handle is externally owned (wrapped via + /// [`WebDevice::wrap_external_texture`]). `destroy()` is a no-op, and + /// the wrapped [`DropCallback`], if any, fires when the last clone of + /// this `WebTexture` is dropped, signalling that wgpu is done with the + /// handle. + drop_guard: Option>, /// Unique identifier for this Texture. ident: crate::cmp::Identifier, } @@ -1810,6 +1852,34 @@ impl Drop for WebAdapter { } } +impl WebDevice { + /// Wrap a foreign `webgpu_sys::GpuTexture` (e.g. from a canvas `getCurrentTexture()`) as a + /// dispatch-level `WebTexture` without calling `device.createTexture(...)`. + /// + /// The resulting texture is *external*: its `destroy()` is a no-op, since + /// the JS handle's lifetime is the caller's responsibility. + /// + /// If `drop_callback` is `Some`, it fires when the last clone of the + /// returned `WebTexture` is dropped, signalling that wgpu is done with + /// the handle (e.g. so the caller can call `GpuTexture.destroy()` + /// themselves, release a pool slot, etc.). + /// + /// The caller is responsible for asserting that `texture` was produced by + /// the same underlying `GpuDevice` as `self`. + pub(crate) fn wrap_external_texture( + &self, + texture: webgpu_sys::GpuTexture, + drop_callback: Option, + ) -> dispatch::DispatchTexture { + WebTexture { + inner: texture, + drop_guard: Some(Rc::new(DropGuard::new(drop_callback))), + ident: crate::cmp::Identifier::create(), + } + .into() + } +} + impl dispatch::DeviceInterface for WebDevice { fn features(&self) -> crate::Features { map_wgt_features(self.inner.features()) @@ -2415,6 +2485,7 @@ impl dispatch::DeviceInterface for WebDevice { let texture = self.inner.create_texture(&mapped_desc).unwrap(); WebTexture { inner: texture, + drop_guard: None, ident: crate::cmp::Identifier::create(), } .into() @@ -2943,12 +3014,15 @@ impl dispatch::TextureInterface for WebTexture { } fn destroy(&self) { - self.inner.destroy(); + if self.drop_guard.is_none() { + self.inner.destroy(); + } } } impl Drop for WebTexture { fn drop(&mut self) { - // no-op + // The drop callback for external textures is fired by `DropGuard`'s + // own `Drop` impl when the last `Rc` clone is released. } } @@ -4282,6 +4356,7 @@ impl dispatch::SurfaceInterface for WebSurface { let web_surface_texture = WebTexture { inner: surface_texture, + drop_guard: None, ident: crate::cmp::Identifier::create(), }; diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 1e6209725..6e4d8fe91 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -333,5 +333,23 @@ pub use raw_window_handle as rwh; #[cfg(web)] pub use web_sys; +/// Vendored WebGPU JS-handle types used by the WebGPU backend. +/// +/// They are exposed publicly so that interop crates can read the JS handle +/// behind a [`Texture`] / [`Buffer`] / etc. (via [`Texture::as_webgpu`] and +/// siblings), and pass a foreign handle in (via +/// [`Device::create_texture_from_webgpu_handle`]). +/// +/// A `web_sys::GpuTexture` from a consumer's own `web-sys` dependency wraps +/// the same JS object as a `wgpu::webgpu::GpuTexture`; convert between them +/// with [`wasm_bindgen::JsCast::unchecked_into`]. +#[cfg(webgpu)] +pub mod webgpu { + pub use crate::backend::webgpu::webgpu_sys::{ + GpuBuffer, GpuDevice, GpuQueue, GpuTexture, GpuTextureView, + }; + pub use crate::backend::webgpu::DropCallback; +} + #[doc(hidden)] pub use macros::helpers as __macro_helpers;