wgpu/api/device.rs
1use alloc::{boxed::Box, string::String, sync::Arc, vec};
2#[cfg(wgpu_core)]
3use core::ops::Deref;
4use core::{error, fmt, future::Future, marker::PhantomData};
5use hashbrown::HashSet;
6
7use crate::api::blas::{Blas, BlasGeometrySizeDescriptors, CreateBlasDescriptor};
8use crate::api::ray_tracing_pipeline::{RayTracingPipeline, RayTracingPipelineDescriptor};
9use crate::api::tlas::{CreateTlasDescriptor, Tlas};
10use crate::util::Mutex;
11use crate::*;
12pub use wgt::error::*;
13
14/// Open connection to a graphics and/or compute device.
15///
16/// Responsible for the creation of most rendering and compute resources.
17/// These are then used in commands, which are submitted to a [`Queue`].
18///
19/// A device may be requested from an adapter with [`Adapter::request_device`].
20///
21/// Corresponds to [WebGPU `GPUDevice`](https://gpuweb.github.io/gpuweb/#gpu-device).
22#[derive(Debug, Clone)]
23pub struct Device {
24 pub(crate) inner: dispatch::DispatchDevice,
25 /// The set of buffers that are currently alive on the device.
26 /// This is used to ensure that all buffers are unmapped before the device is destroyed.
27 pub(crate) buffers: Arc<Mutex<HashSet<WeakMapContext>>>,
28}
29#[cfg(send_sync)]
30static_assertions::assert_impl_all!(Device: Send, Sync);
31
32crate::cmp::impl_eq_ord_hash_proxy!(Device => .inner);
33
34/// Describes a [`Device`].
35///
36/// For use with [`Adapter::request_device`].
37///
38/// Corresponds to [WebGPU `GPUDeviceDescriptor`](
39/// https://gpuweb.github.io/gpuweb/#dictdef-gpudevicedescriptor).
40pub type DeviceDescriptor<'a> = wgt::DeviceDescriptor<Label<'a>>;
41static_assertions::assert_impl_all!(DeviceDescriptor<'_>: Send, Sync);
42
43/// Describes a [`Queue`].
44///
45/// For use within a [`DeviceDescriptor`].
46///
47/// Corresponds to [WebGPU `GPUQueueDescriptor`](
48/// https://gpuweb.github.io/gpuweb/#dictdef-gpuqueuedescriptor).
49pub type QueueDescriptor<'a> = wgt::QueueDescriptor<Label<'a>>;
50static_assertions::assert_impl_all!(QueueDescriptor<'_>: Send, Sync);
51
52impl Device {
53 #[cfg(custom)]
54 /// Returns custom implementation of Device (if custom backend and is internally T)
55 pub fn as_custom<T: custom::DeviceInterface>(&self) -> Option<&T> {
56 self.inner.as_custom()
57 }
58
59 #[cfg(custom)]
60 /// Creates Device from custom implementation
61 pub fn from_custom<T: custom::DeviceInterface>(device: T) -> Self {
62 Self {
63 inner: dispatch::DispatchDevice::custom(device),
64 buffers: Arc::new(Mutex::new(HashSet::new())),
65 }
66 }
67
68 /// Constructs a stub device for testing using [`Backend::Noop`].
69 ///
70 /// This is a convenience function which avoids the configuration, `async`, and fallibility
71 /// aspects of constructing a device through `Instance`.
72 #[cfg(feature = "noop")]
73 pub fn noop(desc: &DeviceDescriptor<'_>) -> (Device, Queue) {
74 use core::future::Future as _;
75 use core::pin::pin;
76 use core::task;
77 let ctx = &mut task::Context::from_waker(task::Waker::noop());
78
79 let instance = Instance::new(InstanceDescriptor {
80 backends: Backends::NOOP,
81 backend_options: BackendOptions {
82 noop: NoopBackendOptions::enabled(),
83 ..Default::default()
84 },
85 ..InstanceDescriptor::new_without_display_handle()
86 });
87
88 // Both of these futures are trivial and should complete instantaneously,
89 // so we do not need an executor and can just poll them once.
90 let task::Poll::Ready(Ok(adapter)) =
91 pin!(instance.request_adapter(&RequestAdapterOptions::default())).poll(ctx)
92 else {
93 unreachable!()
94 };
95 let task::Poll::Ready(Ok(device_and_queue)) = pin!(adapter.request_device(desc)).poll(ctx)
96 else {
97 unreachable!()
98 };
99 device_and_queue
100 }
101
102 /// Check for resource cleanups and mapping callbacks. Will block if [`PollType::Wait`] is passed.
103 ///
104 /// (Note that, unless access to the [`Queue`] is coordinated somehow,
105 /// the returned [`PollStatus`] could be out of date by the time the caller
106 /// receives it. `Queue`s can be shared between threads, so other threads
107 /// could submit new work at any time.)
108 ///
109 /// On the WebGPU backend, a call with [`PollType::Poll`] is a no-op since `Device`s are automatically polled. A call with [`PollType::Wait`] is not supported (always returns [`crate::PollError::CantWait`]).
110 pub fn poll(&self, poll_type: PollType) -> Result<crate::PollStatus, crate::PollError> {
111 self.inner.poll(poll_type.map_index(|s| s.index))
112 }
113
114 /// The [features][Features] which can be used on this device.
115 ///
116 /// This will be equal to the [`required_features`][DeviceDescriptor::required_features]
117 /// specified when creating the device.
118 /// No additional features can be used, even if the underlying adapter can support them.
119 #[must_use]
120 pub fn features(&self) -> Features {
121 self.inner.features()
122 }
123
124 /// The limits which can be used on this device.
125 ///
126 /// This will be equal to the [`required_limits`][DeviceDescriptor::required_limits]
127 /// specified when creating the device.
128 /// No better limits can be used, even if the underlying adapter can support them.
129 #[must_use]
130 pub fn limits(&self) -> Limits {
131 self.inner.limits()
132 }
133
134 /// Returns whether this adapter may present to the passed surface.
135 pub fn is_surface_supported(&self, surface: &Surface<'_>) -> bool {
136 self.inner.is_surface_supported(&surface.inner)
137 }
138
139 /// Get info about the adapter that this device was created from.
140 pub fn adapter_info(&self) -> AdapterInfo {
141 self.inner.adapter_info()
142 }
143
144 /// Get a primary [Queue] for this device
145 pub fn queue(&self) -> Queue {
146 Queue {
147 inner: self.inner.queue(),
148 }
149 }
150
151 /// Creates a shader module.
152 ///
153 /// <div class="warning">
154 // NOTE: Keep this in sync with `naga::front::wgsl::parse_str`!
155 // NOTE: Keep this in sync with `wgpu_core::Global::device_create_shader_module`!
156 ///
157 /// This function may consume a lot of stack space. Compiler-enforced limits for parsing
158 /// recursion exist; if shader compilation runs into them, it will return an error gracefully.
159 /// However, on some build profiles and platforms, the default stack size for a thread may be
160 /// exceeded before this limit is reached during parsing. Callers should ensure that there is
161 /// enough stack space for this, particularly if calls to this method are exposed to user
162 /// input.
163 ///
164 /// </div>
165 #[must_use]
166 pub fn create_shader_module(&self, desc: ShaderModuleDescriptor<'_>) -> ShaderModule {
167 let module = self
168 .inner
169 .create_shader_module(desc, wgt::ShaderRuntimeChecks::checked());
170 ShaderModule { inner: module }
171 }
172
173 /// Deprecated: Use [`create_shader_module_trusted`][csmt] instead.
174 ///
175 /// # Safety
176 ///
177 /// See [`create_shader_module_trusted`][csmt].
178 ///
179 /// [csmt]: Self::create_shader_module_trusted
180 #[deprecated(
181 since = "24.0.0",
182 note = "Use `Device::create_shader_module_trusted(desc, wgpu::ShaderRuntimeChecks::unchecked())` instead."
183 )]
184 #[must_use]
185 pub unsafe fn create_shader_module_unchecked(
186 &self,
187 desc: ShaderModuleDescriptor<'_>,
188 ) -> ShaderModule {
189 unsafe { self.create_shader_module_trusted(desc, crate::ShaderRuntimeChecks::unchecked()) }
190 }
191
192 /// Creates a shader module with flags to dictate runtime checks.
193 ///
194 /// When running on WebGPU, this will merely call [`create_shader_module`][csm].
195 ///
196 /// # Safety
197 ///
198 /// In contrast with [`create_shader_module`][csm] this function
199 /// creates a shader module with user-customizable runtime checks which allows shaders to
200 /// perform operations which can lead to undefined behavior like indexing out of bounds,
201 /// thus it's the caller responsibility to pass a shader which doesn't perform any of this
202 /// operations.
203 ///
204 /// See the documentation for [`ShaderRuntimeChecks`] for more information about specific checks.
205 ///
206 /// [csm]: Self::create_shader_module
207 #[must_use]
208 pub unsafe fn create_shader_module_trusted(
209 &self,
210 desc: ShaderModuleDescriptor<'_>,
211 runtime_checks: crate::ShaderRuntimeChecks,
212 ) -> ShaderModule {
213 let module = self.inner.create_shader_module(desc, runtime_checks);
214 ShaderModule { inner: module }
215 }
216
217 /// Creates a shader module which will bypass wgpu's shader tooling and validation and be used directly by the backend.
218 ///
219 /// # Safety
220 ///
221 /// This function passes data to the backend as-is and can potentially result in a
222 /// driver crash or bogus behaviour. No attempt is made to ensure that data is valid.
223 #[must_use]
224 pub unsafe fn create_shader_module_passthrough(
225 &self,
226 desc: ShaderModuleDescriptorPassthrough<'_>,
227 ) -> ShaderModule {
228 let module = unsafe { self.inner.create_shader_module_passthrough(&desc) };
229 ShaderModule { inner: module }
230 }
231
232 /// Creates an empty [`CommandEncoder`].
233 #[must_use]
234 pub fn create_command_encoder(&self, desc: &CommandEncoderDescriptor<'_>) -> CommandEncoder {
235 let encoder = self.inner.create_command_encoder(desc);
236 // Each encoder starts with its own deferred-action store that travels
237 // with the CommandBuffer produced by finish().
238 CommandEncoder {
239 inner: encoder,
240 actions: Default::default(),
241 }
242 }
243
244 /// Creates an empty [`RenderBundleEncoder`].
245 pub fn create_render_bundle_encoder<'a>(
246 &self,
247 desc: &RenderBundleEncoderDescriptor<'_>,
248 ) -> RenderBundleEncoder<'a> {
249 let encoder = self.inner.create_render_bundle_encoder(desc);
250 RenderBundleEncoder {
251 inner: encoder,
252 _p: PhantomData,
253 }
254 }
255
256 /// Creates a new [`BindGroup`].
257 #[must_use]
258 pub fn create_bind_group(&self, desc: &BindGroupDescriptor<'_>) -> BindGroup {
259 let group = self.inner.create_bind_group(desc);
260 BindGroup { inner: group }
261 }
262
263 /// Creates a [`BindGroupLayout`].
264 #[must_use]
265 pub fn create_bind_group_layout(
266 &self,
267 desc: &BindGroupLayoutDescriptor<'_>,
268 ) -> BindGroupLayout {
269 let layout = self.inner.create_bind_group_layout(desc);
270 BindGroupLayout { inner: layout }
271 }
272
273 /// Creates a [`PipelineLayout`].
274 #[must_use]
275 pub fn create_pipeline_layout(&self, desc: &PipelineLayoutDescriptor<'_>) -> PipelineLayout {
276 let layout = self.inner.create_pipeline_layout(desc);
277 PipelineLayout { inner: layout }
278 }
279
280 /// Creates a [`RenderPipeline`].
281 #[must_use]
282 pub fn create_render_pipeline(&self, desc: &RenderPipelineDescriptor<'_>) -> RenderPipeline {
283 let pipeline = self.inner.create_render_pipeline(desc);
284 RenderPipeline { inner: pipeline }
285 }
286
287 /// Creates a mesh shader based [`RenderPipeline`].
288 #[must_use]
289 pub fn create_mesh_pipeline(&self, desc: &MeshPipelineDescriptor<'_>) -> RenderPipeline {
290 let pipeline = self.inner.create_mesh_pipeline(desc);
291 RenderPipeline { inner: pipeline }
292 }
293
294 /// Creates a [`ComputePipeline`].
295 #[must_use]
296 pub fn create_compute_pipeline(&self, desc: &ComputePipelineDescriptor<'_>) -> ComputePipeline {
297 let pipeline = self.inner.create_compute_pipeline(desc);
298 ComputePipeline { inner: pipeline }
299 }
300
301 /// Creates a [`RayTracingPipeline`].
302 #[must_use]
303 pub fn create_ray_tracing_pipeline(
304 &self,
305 desc: &RayTracingPipelineDescriptor<'_>,
306 ) -> RayTracingPipeline {
307 let pipeline = self.inner.create_ray_tracing_pipeline(desc);
308 RayTracingPipeline { inner: pipeline }
309 }
310
311 /// Creates a [`Buffer`].
312 #[must_use]
313 pub fn create_buffer(&self, desc: &BufferDescriptor<'_>) -> Buffer {
314 let map_context = MapContext::new(
315 desc.mapped_at_creation.then_some(MappingInfo {
316 range: 0..desc.size,
317 kind: MapMode::Write,
318 }),
319 &self.buffers,
320 );
321
322 let buffer = self.inner.create_buffer(desc);
323
324 Buffer {
325 inner: buffer,
326 map_context,
327 }
328 }
329
330 /// Creates a new [`Texture`].
331 ///
332 /// `desc` specifies the general format of the texture.
333 #[must_use]
334 pub fn create_texture(&self, desc: &TextureDescriptor<'_>) -> Texture {
335 let texture = self.inner.create_texture(desc);
336
337 Texture { inner: texture }
338 }
339
340 /// Creates a [`Texture`] from a wgpu-hal Texture.
341 ///
342 /// # Types
343 ///
344 /// The type of `A::Texture` depends on the backend:
345 ///
346 #[doc = crate::macros::hal_type_vulkan!("Texture")]
347 #[doc = crate::macros::hal_type_metal!("Texture")]
348 #[doc = crate::macros::hal_type_dx12!("Texture")]
349 #[doc = crate::macros::hal_type_gles!("Texture")]
350 ///
351 /// On [`Backend::BrowserWebGpu`], use `Device::create_texture_from_webgpu_handle()` instead.
352 ///
353 /// # `initial_state`
354 ///
355 /// If the resource has already been initialized, `initial_state` should be
356 /// set to the [`wgt::TextureUses`] state of the wrapped resource. It will
357 /// be used as the source state (`oldLayout` / `StateBefore`) of the first
358 /// barrier emitted on the texture.
359 ///
360 /// If the resource has not been initialized (or if the existing contents
361 /// may be discarded), `initial_state` may be set to
362 /// `TextureUses::UNINITIALIZED`.
363 ///
364 /// # `cleared`
365 ///
366 /// Whether the wrapped resource's contents are already valid/defined.
367 /// This drives wgpu's lazy-clear tracking, which otherwise clears a
368 /// texture's subresources on first use to avoid exposing undefined
369 /// memory. Set `cleared` to `true` if the contents are already valid
370 /// (e.g. just cleared or written to on the driver side), or `false` if
371 /// they're undefined, so wgpu clears them before they are read. Falsely
372 /// passing `true` skips that clear and exposes uninitialized/stale GPU
373 /// memory to subsequent reads.
374 ///
375 /// This is unrelated to `initial_state`, which only describes the
376 /// tracker's usage state, not the validity of the contents.
377 ///
378 /// # Safety
379 ///
380 /// - `hal_texture` must be created from this device internal handle
381 /// - `hal_texture` must be created respecting `desc`
382 /// - `hal_texture` must be initialized
383 /// - `initial_state`, if it is not `TextureUses::UNINITIALIZED`, must
384 /// match the actual driver-side layout/state of the wrapped resource at
385 /// the moment of wrap.
386 /// - `cleared` must not be `true` unless the resource's contents are
387 /// actually valid/defined
388 /// - On devices without [`ARBITRARY_BINDING_VIEW_DIMENSIONS`](crate::DownlevelFlags::ARBITRARY_BINDING_VIEW_DIMENSIONS),
389 /// `hal_texture`'s GL target must match `desc.texture_binding_view_dimension`, or the
390 /// one inferred from the texture's dimension and layer count if it is `None`.
391 #[cfg(wgpu_core)]
392 #[must_use]
393 pub unsafe fn create_texture_from_hal<A: hal::Api>(
394 &self,
395 hal_texture: A::Texture,
396 desc: &TextureDescriptor<'_>,
397 initial_state: wgt::TextureUses,
398 cleared: bool,
399 ) -> Texture {
400 let texture = unsafe {
401 let core_device = self.inner.as_core();
402 core_device.create_texture_from_hal::<A>(hal_texture, desc, initial_state, cleared)
403 };
404 Texture {
405 inner: texture.into(),
406 }
407 }
408
409 /// Wraps a foreign [`webgpu::GpuTexture`] (e.g. a canvas `getCurrentTexture()` result)
410 /// as a [`Texture`] without any copy.
411 ///
412 /// The wrapped texture is *external*: dropping the returned `Texture` (or
413 /// calling [`Texture::destroy`] on it) does **not** call `GpuTexture.destroy()`
414 /// on the underlying handle - its lifetime is the caller's responsibility.
415 ///
416 /// If `drop_callback` is `Some`, it fires when wgpu releases its last
417 /// reference to the wrapped handle. wgpu never calls `GpuTexture.destroy()`
418 /// itself on a wrapped texture; to hand the handle's lifetime to wgpu,
419 /// supply a callback that calls `GpuTexture.destroy()`. The callback can
420 /// also be used to free a pool slot or notify dependent code that wgpu is
421 /// done with the handle. Pass `None` if the caller manages the handle's
422 /// lifetime entirely on their own.
423 ///
424 /// This is the WebGPU counterpart of [`Self::create_texture_from_hal`].
425 /// A `Some` `drop_callback` plays the same role as `wgpu_hal::DropCallback`
426 /// does on the Vulkan backend. The `None` case differs: here the texture is
427 /// always external and wgpu never destroys it, whereas on Vulkan a `None`
428 /// callback means wgpu takes ownership of the image and destroys it.
429 ///
430 /// The caller must guarantee:
431 ///
432 /// 1. `texture` was produced by the same underlying `GpuDevice` that this `Device` wraps.
433 /// 2. `desc.format`, `desc.size`, `desc.usage`, `desc.dimension`,
434 /// `desc.mip_level_count`, and `desc.sample_count` match the actual
435 /// `GPUTexture`'s reflected values. wgpu stores these verbatim and
436 /// returns them from [`Texture::size`], [`Texture::format`], etc.
437 /// without re-checking the handle; a mismatch yields silently incorrect
438 /// metadata and, downstream, `GPUValidationError`s rather than memory
439 /// unsafety (the browser bounds every access).
440 /// 3. The underlying `GpuTexture` must remain alive for as long as wgpu
441 /// may use it (e.g. until any submitted command buffer that references
442 /// it has finished executing). If `drop_callback` is `Some`, it is
443 /// sufficient to keep the handle alive until the callback fires.
444 #[cfg(webgpu)]
445 #[must_use]
446 pub fn create_texture_from_webgpu_handle(
447 &self,
448 texture: webgpu::GpuTexture,
449 desc: &TextureDescriptor<'_>,
450 drop_callback: Option<webgpu::DropCallback>,
451 ) -> Texture {
452 let inner = self
453 .inner
454 .as_webgpu()
455 .wrap_external_texture(texture, desc, drop_callback);
456 Texture { inner }
457 }
458
459 /// Returns the underlying [`webgpu::GpuDevice`] handle if this `Device`
460 /// is on the WebGPU backend, otherwise `None`.
461 #[cfg(webgpu)]
462 pub fn as_webgpu(&self) -> Option<&webgpu::GpuDevice> {
463 self.inner.as_webgpu_opt().map(|wd| &wd.inner)
464 }
465
466 /// Wrap an existing `web_sys::WebGlTexture` as a [`Texture`], without
467 /// copying. WebGL counterpart of
468 /// [`Self::create_texture_from_webgpu_handle`].
469 ///
470 /// `view_dimension` names the WebGL texture type of `texture` ([`D2`] →
471 /// `TEXTURE_2D`, [`D2Array`] → `TEXTURE_2D_ARRAY`, [`Cube`] →
472 /// `TEXTURE_CUBE_MAP`, [`D3`] → `TEXTURE_3D`); it cannot be inferred from
473 /// `desc`.
474 ///
475 /// Fails with [`NotWebGlBackendError`] if this device is not using the
476 /// GLES backend on WebGL.
477 ///
478 /// `texture` must have been created by the `WebGl2RenderingContext`
479 /// backing this device, match `desc` and `view_dimension`, and stay valid
480 /// until wgpu is done with it (or until `drop_callback` fires, if one is
481 /// supplied). Violations yield GL errors rather than memory unsafety,
482 /// which is why this method is not `unsafe`.
483 ///
484 /// The handle is always externally owned — wgpu never deletes it — and
485 /// `drop_callback` is purely a notification. To delete the texture once
486 /// wgpu is done with it, do so in the callback.
487 ///
488 /// [`D2`]: wgt::TextureViewDimension::D2
489 /// [`D2Array`]: wgt::TextureViewDimension::D2Array
490 /// [`Cube`]: wgt::TextureViewDimension::Cube
491 /// [`D3`]: wgt::TextureViewDimension::D3
492 #[cfg(webgl)]
493 pub fn create_texture_from_webgl_handle(
494 &self,
495 texture: web_sys::WebGlTexture,
496 desc: &TextureDescriptor<'_>,
497 view_dimension: wgt::TextureViewDimension,
498 drop_callback: Option<hal::DropCallback>,
499 ) -> Result<Texture, NotWebGlBackendError> {
500 use hal::api::Gles;
501
502 // `texture_from_webgl_handle` reads only format / dimension / size / mip
503 // from the hal descriptor; `usage` / `memory_flags` are placeholders
504 // (the real usage flows through `create_texture_from_hal`'s frontend
505 // `desc`).
506 let hal_desc = hal::TextureDescriptor {
507 label: desc.label,
508 size: desc.size,
509 mip_level_count: desc.mip_level_count,
510 sample_count: desc.sample_count,
511 dimension: desc.dimension,
512 format: desc.format,
513 usage: wgt::TextureUses::empty(),
514 memory_flags: hal::MemoryFlags::empty(),
515 view_formats: desc.view_formats.to_vec(),
516 texture_binding_view_dimension: Some(view_dimension),
517 };
518
519 let hal_texture = {
520 // SAFETY: the raw device is only borrowed to register the handle,
521 // never destroyed through the guard.
522 let hal_device = unsafe { self.as_hal::<Gles>() }.ok_or(NotWebGlBackendError)?;
523 hal_device.texture_from_webgl_handle(texture, &hal_desc, view_dimension, drop_callback)
524 };
525
526 // SAFETY: `hal_texture` was created on this device's raw handle
527 // respecting `desc` just above, carries no initial state, and WebGL
528 // guarantees that observable texture contents are initialized.
529 Ok(unsafe {
530 self.create_texture_from_hal::<Gles>(hal_texture, desc, wgt::TextureUses::empty(), true)
531 })
532 }
533
534 /// Borrow the underlying `web_sys::WebGlTexture` for a texture on the GLES
535 /// backend (WebGL platform), or `None` on other backends / non-GL textures
536 /// / textures that were not created on this device.
537 ///
538 /// WebGL counterpart of [`Texture::as_webgpu`]. Unlike WebGPU — where the
539 /// texture directly holds the JS handle — a GLES texture holds a glow
540 /// resource key, so resolving it to a `WebGlTexture` needs this device's
541 /// glow context. Hence this lives on [`Device`] and takes the texture,
542 /// rather than being a `&self` method on [`Texture`].
543 #[cfg(webgl)]
544 pub fn as_webgl_texture(&self, texture: &Texture) -> Option<web_sys::WebGlTexture> {
545 use hal::api::Gles;
546
547 // A glow resource key is only meaningful inside the glow context that
548 // issued it: a foreign texture's key could resolve to an unrelated
549 // `WebGlTexture` in this device's tracker, so reject textures that were
550 // not created on this device.
551 let core_device = self.inner.as_core_opt()?;
552 let core_texture = texture.inner.as_core_opt()?;
553 if !core_device.texture_belongs_to_device(core_texture) {
554 return None;
555 }
556
557 let hal_device = unsafe { self.as_hal::<Gles>() }?;
558 let hal_texture = unsafe { texture.as_hal::<Gles>() }?;
559 hal_device.webgl_texture_handle(&hal_texture)
560 }
561
562 /// Returns the underlying `web_sys::WebGl2RenderingContext` if this `Device`
563 /// is on the GLES backend (WebGL platform), otherwise `None`.
564 ///
565 /// WebGL counterpart of [`Self::as_webgpu`]. Unlike WebGPU — where the
566 /// device directly holds its JS `GPUDevice` — a GLES device holds a glow
567 /// context, so this reflects the `WebGl2RenderingContext` backing it: the
568 /// handle to `Object.is`-compare against a foreign context when deciding
569 /// whether a `WebGlTexture` can be wrapped same-context.
570 #[cfg(webgl)]
571 pub fn as_webgl_context(&self) -> Option<web_sys::WebGl2RenderingContext> {
572 use hal::api::Gles;
573 let hal_device = unsafe { self.as_hal::<Gles>() }?;
574 Some(hal_device.context().webgl2_context.clone())
575 }
576
577 /// Creates a new [`ExternalTexture`] from plane textures the caller
578 /// already has.
579 ///
580 /// The planes and the [`ExternalTextureDescriptor`]'s conversion
581 /// parameters (YCbCr matrix, gamut and transfer functions) are supplied by
582 /// the caller, and wgpu performs the conversion when the texture is
583 /// sampled. Works on every backend.
584 ///
585 /// Use this when the video data already lives in wgpu textures, e.g.
586 /// frames you decoded yourself. To bind a web media source directly on the
587 /// WebGPU backend, use `Device::import_external_texture` instead.
588 #[must_use]
589 pub fn create_external_texture(
590 &self,
591 desc: &ExternalTextureDescriptor<'_>,
592 planes: &[&TextureView],
593 ) -> ExternalTexture {
594 let external_texture = self.inner.create_external_texture(desc, planes);
595
596 ExternalTexture {
597 inner: external_texture,
598 }
599 }
600
601 /// Imports a video source as an [`ExternalTexture`] on the WebGPU backend,
602 /// without a copy.
603 ///
604 /// Unlike [`Self::create_external_texture`] — where the caller supplies
605 /// plane textures and conversion parameters — this hands `source` to the
606 /// browser's `importExternalTexture`, which performs the color conversion
607 /// internally. Use it whenever the frames come from a web media source
608 /// rather than from data you decoded yourself.
609 ///
610 /// The result is valid only while `source` is: a `VideoFrame` until it is
611 /// closed, an `HTMLVideoElement` for the current task.
612 /// [`ExternalTexture::destroy`] is a no-op.
613 ///
614 /// Returns an error if this device is not on the WebGPU backend.
615 #[cfg(webgpu)]
616 pub fn import_external_texture(
617 &self,
618 source: &webgpu::ExternalTextureSource,
619 ) -> Result<ExternalTexture, NotWebGpuBackendError> {
620 let inner = self
621 .inner
622 .as_webgpu_opt()
623 .ok_or(NotWebGpuBackendError)?
624 .import_external_texture(source);
625 Ok(ExternalTexture { inner })
626 }
627
628 /// Creates a [`Buffer`] from a wgpu-hal Buffer.
629 ///
630 /// # Types
631 ///
632 /// The type of `A::Buffer` depends on the backend:
633 ///
634 #[doc = crate::macros::hal_type_vulkan!("Buffer")]
635 #[doc = crate::macros::hal_type_metal!("Buffer")]
636 #[doc = crate::macros::hal_type_dx12!("Buffer")]
637 #[doc = crate::macros::hal_type_gles!("Buffer")]
638 ///
639 /// # Safety
640 ///
641 /// - `hal_buffer` must be created from this device internal handle
642 /// - `hal_buffer` must be created respecting `desc`
643 /// - `hal_buffer` must be initialized
644 /// - `hal_buffer` must not have zero size
645 #[cfg(wgpu_core)]
646 #[must_use]
647 pub unsafe fn create_buffer_from_hal<A: hal::Api>(
648 &self,
649 hal_buffer: A::Buffer,
650 desc: &BufferDescriptor<'_>,
651 ) -> Buffer {
652 let map_context = MapContext::new(
653 desc.mapped_at_creation.then_some(MappingInfo {
654 range: 0..desc.size,
655 kind: MapMode::Write,
656 }),
657 &self.buffers,
658 );
659
660 let buffer = unsafe {
661 let core_device = self.inner.as_core();
662 core_device.create_buffer_from_hal::<A>(hal_buffer, desc)
663 };
664
665 Buffer {
666 inner: buffer.into(),
667 map_context,
668 }
669 }
670
671 /// Creates a new [`Sampler`].
672 ///
673 /// `desc` specifies the behavior of the sampler.
674 #[must_use]
675 pub fn create_sampler(&self, desc: &SamplerDescriptor<'_>) -> Sampler {
676 let sampler = self.inner.create_sampler(desc);
677 Sampler { inner: sampler }
678 }
679
680 /// Creates a new [`QuerySet`].
681 #[must_use]
682 pub fn create_query_set(&self, desc: &QuerySetDescriptor<'_>) -> QuerySet {
683 let query_set = self.inner.create_query_set(desc);
684 QuerySet { inner: query_set }
685 }
686
687 /// Set a callback which will be called for all errors that are not handled in error scopes.
688 ///
689 /// Detailed shader creation errors will not be provided to handler;
690 /// they can be inspected via [`ShaderModule::get_compilation_info`].
691 pub fn on_uncaptured_error(&self, handler: Arc<dyn UncapturedErrorHandler>) {
692 self.inner.on_uncaptured_error(handler)
693 }
694
695 /// Push an error scope on this device's thread-local error scope
696 /// stack. All operations on this device, or on resources created
697 /// from this device, will have their errors captured by this scope
698 /// until the scope is popped.
699 ///
700 /// Scopes must be popped in reverse order to their creation. If
701 /// a guard is dropped without being `pop()`ped, the scope will be
702 /// popped, and the captured errors will be dropped.
703 ///
704 /// Multiple error scopes may be active at one time, forming a stack.
705 /// Each error will be reported to the inner-most scope that matches
706 /// its filter.
707 ///
708 /// With the `std` feature enabled, this stack is **thread-local**.
709 /// Without, this is **global** to all threads.
710 ///
711 /// ```rust
712 /// # async move {
713 /// # let device: wgpu::Device = unreachable!();
714 /// let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
715 ///
716 /// // ...
717 /// // do work that may produce validation errors
718 /// // ...
719 ///
720 /// // pop the error scope and get a future for the result
721 /// let error_future = error_scope.pop();
722 ///
723 /// // await the future to get the error, if any
724 /// let error = error_future.await;
725 /// # };
726 /// ```
727 pub fn push_error_scope(&self, filter: ErrorFilter) -> ErrorScopeGuard {
728 let index = self.inner.push_error_scope(filter);
729 ErrorScopeGuard {
730 device: self.inner.clone(),
731 index,
732 popped: false,
733 _phantom: PhantomData,
734 }
735 }
736
737 /// Starts a capture in the attached graphics debugger.
738 ///
739 /// This behaves differently depending on which graphics debugger is attached:
740 ///
741 /// - Renderdoc: Calls [`StartFrameCapture(device, NULL)`][rd].
742 /// - Xcode: Creates a capture with [`MTLCaptureManager`][xcode].
743 /// - None: No action is taken.
744 ///
745 /// # Safety
746 ///
747 /// - There should not be any other captures currently active.
748 /// - All other safety rules are defined by the graphics debugger, see the
749 /// documentation for the specific debugger.
750 /// - In general, graphics debuggers can easily cause crashes, so this isn't
751 /// ever guaranteed to be sound.
752 ///
753 /// # Tips
754 ///
755 /// - Debuggers need to capture both the recording of the commands and the
756 /// submission of the commands to the GPU. Try to wrap all of your
757 /// gpu work in a capture.
758 /// - If you encounter issues, try waiting for the GPU to finish all work
759 /// before stopping the capture.
760 ///
761 /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv417StartFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle
762 /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager
763 #[doc(alias = "start_renderdoc_capture")]
764 #[doc(alias = "start_xcode_capture")]
765 pub unsafe fn start_graphics_debugger_capture(&self) {
766 unsafe { self.inner.start_graphics_debugger_capture() }
767 }
768
769 /// Stops the current capture in the attached graphics debugger.
770 ///
771 /// This behaves differently depending on which graphics debugger is attached:
772 ///
773 /// - Renderdoc: Calls [`EndFrameCapture(device, NULL)`][rd].
774 /// - Xcode: Stops the capture with [`MTLCaptureManager`][xcode].
775 /// - None: No action is taken.
776 ///
777 /// # Safety
778 ///
779 /// - There should be a capture currently active.
780 /// - All other safety rules are defined by the graphics debugger, see the
781 /// documentation for the specific debugger.
782 /// - In general, graphics debuggers can easily cause crashes, so this isn't
783 /// ever guaranteed to be sound.
784 ///
785 /// # Tips
786 ///
787 /// - If you encounter issues, try to submit all work to the GPU, and waiting
788 /// for that work to finish before stopping the capture.
789 ///
790 /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv415EndFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle
791 /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager
792 #[doc(alias = "stop_renderdoc_capture")]
793 #[doc(alias = "stop_xcode_capture")]
794 pub unsafe fn stop_graphics_debugger_capture(&self) {
795 unsafe { self.inner.stop_graphics_debugger_capture() }
796 }
797
798 /// Query internal counters from the native backend for debugging purposes.
799 ///
800 /// Some backends may not set all counters, or may not set any counter at all.
801 /// The `counters` cargo feature must be enabled for any counter to be set.
802 ///
803 /// If a counter is not set, its contains its default value (zero).
804 #[must_use]
805 pub fn get_internal_counters(&self) -> wgt::InternalCounters {
806 self.inner.get_internal_counters()
807 }
808
809 /// Generate an GPU memory allocation report if the underlying backend supports it.
810 ///
811 /// Backends that do not support producing these reports return `None`. A backend may
812 /// Support it and still return `None` if it is not using performing sub-allocation,
813 /// for example as a workaround for driver issues.
814 #[must_use]
815 pub fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
816 self.inner.generate_allocator_report()
817 }
818
819 /// Get the [`wgpu_hal`] device from this `Device`.
820 ///
821 /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
822 /// and pass that struct to the to the `A` type parameter.
823 ///
824 /// Returns a guard that dereferences to the type of the hal backend
825 /// which implements [`A::Device`].
826 ///
827 /// # Types
828 ///
829 /// The returned type depends on the backend:
830 ///
831 #[doc = crate::macros::hal_type_vulkan!("Device")]
832 #[doc = crate::macros::hal_type_metal!("Device")]
833 #[doc = crate::macros::hal_type_dx12!("Device")]
834 #[doc = crate::macros::hal_type_gles!("Device")]
835 ///
836 /// # Errors
837 ///
838 /// This method will return None if:
839 /// - The device is not from the backend specified by `A`.
840 /// - The device is from the `webgpu` or `custom` backend.
841 ///
842 /// On the `webgpu` backend, use `as_webgpu` instead.
843 ///
844 /// # Safety
845 ///
846 /// - The returned resource must not be destroyed unless the guard
847 /// is the last reference to it and it is not in use by the GPU.
848 /// The guard and handle may be dropped at any time however.
849 /// - All the safety requirements of wgpu-hal must be upheld.
850 ///
851 /// [`A::Device`]: hal::Api::Device
852 #[cfg(wgpu_core)]
853 pub unsafe fn as_hal<A: hal::Api>(
854 &self,
855 ) -> Option<impl Deref<Target = A::Device> + WasmNotSendSync> {
856 let device = self.inner.as_core_opt()?;
857 unsafe { device.as_hal::<A>() }
858 }
859
860 /// Destroy this device.
861 ///
862 /// Panics if there is any [`BufferView`] or [`BufferViewMut`] alive.
863 pub fn destroy(&self) {
864 for buffer in self.buffers.lock().drain() {
865 buffer.unmap();
866 }
867 self.inner.destroy()
868 }
869
870 /// Set a DeviceLostCallback on this device.
871 pub fn set_device_lost_callback(
872 &self,
873 callback: impl Fn(DeviceLostReason, String) + Send + 'static,
874 ) {
875 self.inner.set_device_lost_callback(Box::new(callback))
876 }
877
878 /// Create a [`PipelineCache`] with initial data
879 ///
880 /// This can be passed to [`Device::create_compute_pipeline`]
881 /// and [`Device::create_render_pipeline`] to either accelerate these
882 /// or add the cache results from those.
883 ///
884 /// # Safety
885 ///
886 /// If the `data` field of `desc` is set, it must have previously been returned from a call
887 /// to [`PipelineCache::get_data`][^saving]. This `data` will only be used if it came
888 /// from an adapter with the same [`util::pipeline_cache_key`].
889 /// This *is* compatible across wgpu versions, as any data format change will
890 /// be accounted for.
891 ///
892 /// It is *not* supported to bring caches from previous direct uses of backend APIs
893 /// into this method.
894 ///
895 /// # Errors
896 ///
897 /// Returns an error value if:
898 /// * the [`PIPELINE_CACHE`](wgt::Features::PIPELINE_CACHE) feature is not enabled
899 /// * this device is invalid; or
900 /// * the device is out of memory
901 ///
902 /// This method also returns an error value if:
903 /// * The `fallback` field on `desc` is false; and
904 /// * the `data` provided would not be used[^data_not_used]
905 ///
906 /// If an error value is used in subsequent calls, default caching will be used.
907 ///
908 /// [^saving]: We do recognise that saving this data to disk means this condition
909 /// is impossible to fully prove. Consider the risks for your own application in this case.
910 ///
911 /// [^data_not_used]: This data may be not used if: the data was produced by a prior
912 /// version of wgpu; or was created for an incompatible adapter, or there was a GPU driver
913 /// update. In some cases, the data might not be used and a real value is returned,
914 /// this is left to the discretion of GPU drivers.
915 #[must_use]
916 pub unsafe fn create_pipeline_cache(
917 &self,
918 desc: &PipelineCacheDescriptor<'_>,
919 ) -> PipelineCache {
920 let cache = unsafe { self.inner.create_pipeline_cache(desc) };
921 PipelineCache { inner: cache }
922 }
923}
924
925/// [`Features::EXPERIMENTAL_RAY_QUERY`] must be enabled on the device in order to call these functions.
926impl Device {
927 /// Create a bottom level acceleration structure, used inside a top level acceleration structure for ray tracing.
928 /// - `desc`: The descriptor of the acceleration structure.
929 /// - `sizes`: Size descriptor limiting what can be built into the acceleration structure.
930 ///
931 /// # Validation
932 /// If any of the following is not satisfied a validation error is generated
933 ///
934 /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled.
935 /// if `sizes` is [`BlasGeometrySizeDescriptors::Triangles`] then the following must be satisfied
936 /// - For every geometry descriptor (for the purposes this is called `geo_desc`) of `sizes.descriptors` the following must be satisfied:
937 /// - `geo_desc.vertex_format` must be within allowed formats (allowed formats for a given feature set
938 /// may be queried with [`Features::allowed_vertex_formats_for_blas`]).
939 /// - Both or neither of `geo_desc.index_format` and `geo_desc.index_count` must be provided.
940 ///
941 /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
942 /// [`Features::allowed_vertex_formats_for_blas`]: wgt::Features::allowed_vertex_formats_for_blas
943 #[must_use]
944 pub fn create_blas(
945 &self,
946 desc: &CreateBlasDescriptor<'_>,
947 sizes: BlasGeometrySizeDescriptors,
948 ) -> Blas {
949 let (handle, blas) = self.inner.create_blas(desc, sizes);
950
951 Blas {
952 inner: blas,
953 handle,
954 }
955 }
956
957 /// Create a top level acceleration structure, used for ray tracing.
958 /// - `desc`: The descriptor of the acceleration structure.
959 ///
960 /// # Validation
961 /// If any of the following is not satisfied a validation error is generated
962 ///
963 /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled.
964 ///
965 /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
966 #[must_use]
967 pub fn create_tlas(&self, desc: &CreateTlasDescriptor<'_>) -> Tlas {
968 let tlas = self.inner.create_tlas(desc);
969
970 Tlas {
971 inner: tlas,
972 instances: vec![None; desc.max_instances as usize],
973 lowest_unmodified: 0,
974 }
975 }
976}
977
978#[cfg(wgpu_core)]
979impl Device {
980 /// Create a new device of wgpu from a wgpu-core device.
981 ///
982 /// Error scopes, the [uncaptured error handler](Device::on_uncaptured_error)
983 /// and the single [device lost callback](Device::set_device_lost_callback)
984 /// belong to the wgpu-core device, so they are shared with every other user
985 /// of `core_device`.
986 ///
987 /// # Arguments
988 ///
989 /// - `core_device` - wgpu-core device.
990 pub fn from_core(core_device: alloc::sync::Arc<wgc::device::Device>) -> Self {
991 Self {
992 inner: crate::backend::wgpu_core::CoreDevice::from_core(core_device).into(),
993 buffers: Default::default(),
994 }
995 }
996
997 /// Returns the underlying wgpu-core device if this `Device` is on the wgpu-core backend, otherwise `None`.
998 pub fn as_core(&self) -> Option<alloc::sync::Arc<wgc::device::Device>> {
999 self.inner.as_core_opt().map(|cd| cd.as_core())
1000 }
1001}
1002
1003/// The operation requires the GLES backend on WebGL, but this [`Device`] is
1004/// using a different backend.
1005///
1006/// Returned by [`Device::create_texture_from_webgl_handle`]. With both the
1007/// `webgpu` and `webgl` features enabled, the backend is chosen at runtime.
1008#[cfg(webgl)]
1009#[derive(Clone, Debug)]
1010#[non_exhaustive]
1011pub struct NotWebGlBackendError;
1012
1013#[cfg(webgl)]
1014impl fmt::Display for NotWebGlBackendError {
1015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1016 write!(f, "this device is not using the WebGL (GLES) backend")
1017 }
1018}
1019
1020#[cfg(webgl)]
1021impl error::Error for NotWebGlBackendError {}
1022/// The [`Device`] is not on the WebGPU backend.
1023#[cfg(webgpu)]
1024#[derive(Clone, Debug)]
1025#[non_exhaustive]
1026pub struct NotWebGpuBackendError;
1027
1028#[cfg(webgpu)]
1029impl fmt::Display for NotWebGpuBackendError {
1030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1031 write!(f, "this device is not using the WebGPU backend")
1032 }
1033}
1034
1035#[cfg(webgpu)]
1036impl error::Error for NotWebGpuBackendError {}
1037
1038/// Requesting a device from an [`Adapter`] failed.
1039#[derive(Clone, Debug)]
1040pub struct RequestDeviceError {
1041 pub(crate) inner: RequestDeviceErrorKind,
1042}
1043
1044impl RequestDeviceError {
1045 /// Construct an error from a custom backend message. This is mainly useful for custom backends.
1046 #[cfg(custom)]
1047 pub fn from_message(message: String) -> Self {
1048 RequestDeviceError {
1049 inner: RequestDeviceErrorKind::Custom(message),
1050 }
1051 }
1052}
1053
1054#[derive(Clone, Debug)]
1055pub(crate) enum RequestDeviceErrorKind {
1056 /// Error from [`wgpu_core`].
1057 // must match dependency cfg
1058 #[cfg(wgpu_core)]
1059 Core(wgc::instance::RequestDeviceError),
1060
1061 /// Error from web API that was called by `wgpu` to request a device.
1062 ///
1063 /// (This is currently never used by the webgl backend, but it could be.)
1064 #[cfg(webgpu)]
1065 WebGpu(String),
1066
1067 /// Error from a custom backend.
1068 #[cfg(custom)]
1069 Custom(String),
1070}
1071
1072static_assertions::assert_impl_all!(RequestDeviceError: Send, Sync);
1073
1074impl fmt::Display for RequestDeviceError {
1075 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
1076 match &self.inner {
1077 #[cfg(wgpu_core)]
1078 RequestDeviceErrorKind::Core(error) => error.fmt(_f),
1079 #[cfg(webgpu)]
1080 RequestDeviceErrorKind::WebGpu(error) => {
1081 write!(_f, "{error}")
1082 }
1083 #[cfg(custom)]
1084 RequestDeviceErrorKind::Custom(msg) => write!(_f, "{msg}"),
1085 #[cfg(not(any(webgpu, wgpu_core)))]
1086 _ => unimplemented!("unknown `RequestDeviceErrorKind`"),
1087 }
1088 }
1089}
1090
1091impl error::Error for RequestDeviceError {
1092 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1093 match &self.inner {
1094 #[cfg(wgpu_core)]
1095 RequestDeviceErrorKind::Core(error) => error.source(),
1096 #[cfg(webgpu)]
1097 RequestDeviceErrorKind::WebGpu(_) => None,
1098 #[cfg(custom)]
1099 RequestDeviceErrorKind::Custom(_) => None,
1100 #[cfg(not(any(webgpu, wgpu_core)))]
1101 _ => unimplemented!("unknown `RequestDeviceErrorKind`"),
1102 }
1103 }
1104}
1105
1106#[cfg(wgpu_core)]
1107impl From<wgc::instance::RequestDeviceError> for RequestDeviceError {
1108 fn from(error: wgc::instance::RequestDeviceError) -> Self {
1109 Self {
1110 inner: RequestDeviceErrorKind::Core(error),
1111 }
1112 }
1113}
1114
1115/// Guard for an error scope pushed with [`Device::push_error_scope()`].
1116///
1117/// Call [`pop()`] to pop the scope and get a future for the result. If
1118/// the guard is dropped without being popped explicitly, the scope will still be popped,
1119/// and the captured errors will be dropped.
1120///
1121/// This guard is neither `Send` nor `Sync`, as error scopes are handled
1122/// on a per-thread basis when the `std` feature is enabled.
1123///
1124/// [`pop()`]: ErrorScopeGuard::pop
1125#[must_use = "Error scopes must be explicitly popped to retrieve errors they catch"]
1126pub struct ErrorScopeGuard {
1127 device: dispatch::DispatchDevice,
1128 index: u32,
1129 popped: bool,
1130 // Ensure the guard is !Send and !Sync
1131 _phantom: PhantomData<*mut ()>,
1132}
1133
1134static_assertions::assert_not_impl_any!(ErrorScopeGuard: Send, Sync);
1135
1136impl ErrorScopeGuard {
1137 /// Pops the error scope.
1138 ///
1139 /// Returns a future which resolves to the error captured by this scope, if any.
1140 /// The pop takes effect immediately; the future does not need to be awaited before doing work that is outside of this error scope.
1141 ///
1142 /// Detailed shader creation errors are not returned via this function;
1143 /// they can be inspected via [`ShaderModule::get_compilation_info`].
1144 pub fn pop(mut self) -> impl Future<Output = Option<Error>> + WasmNotSend {
1145 self.popped = true;
1146 self.device.pop_error_scope(self.index)
1147 }
1148}
1149
1150impl Drop for ErrorScopeGuard {
1151 fn drop(&mut self) {
1152 if !self.popped {
1153 drop(self.device.pop_error_scope(self.index));
1154 }
1155 }
1156}
1157
1158impl fmt::Debug for ErrorScopeGuard {
1159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1160 let ErrorScopeGuard {
1161 device,
1162 index,
1163 popped,
1164 _phantom: _,
1165 } = self;
1166 f.debug_struct("ErrorScopeGuard")
1167 .field("device", device)
1168 .field("index", index)
1169 .field("popped", popped)
1170 .finish()
1171 }
1172}