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