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 { enable: true },
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 /// Creates an empty [`CommandEncoder`].
206 #[must_use]
207 pub fn create_command_encoder(&self, desc: &CommandEncoderDescriptor<'_>) -> CommandEncoder {
208 let encoder = self.inner.create_command_encoder(desc);
209 // Each encoder starts with its own deferred-action store that travels
210 // with the CommandBuffer produced by finish().
211 CommandEncoder {
212 inner: encoder,
213 actions: Default::default(),
214 }
215 }
216
217 /// Creates an empty [`RenderBundleEncoder`].
218 #[must_use]
219 pub fn create_render_bundle_encoder<'a>(
220 &self,
221 desc: &RenderBundleEncoderDescriptor<'_>,
222 ) -> RenderBundleEncoder<'a> {
223 let encoder = self.inner.create_render_bundle_encoder(desc);
224 RenderBundleEncoder {
225 inner: encoder,
226 _p: PhantomData,
227 }
228 }
229
230 /// Creates a new [`BindGroup`].
231 #[must_use]
232 pub fn create_bind_group(&self, desc: &BindGroupDescriptor<'_>) -> BindGroup {
233 let group = self.inner.create_bind_group(desc);
234 BindGroup { inner: group }
235 }
236
237 /// Creates a [`BindGroupLayout`].
238 #[must_use]
239 pub fn create_bind_group_layout(
240 &self,
241 desc: &BindGroupLayoutDescriptor<'_>,
242 ) -> BindGroupLayout {
243 let layout = self.inner.create_bind_group_layout(desc);
244 BindGroupLayout { inner: layout }
245 }
246
247 /// Creates a [`PipelineLayout`].
248 #[must_use]
249 pub fn create_pipeline_layout(&self, desc: &PipelineLayoutDescriptor<'_>) -> PipelineLayout {
250 let layout = self.inner.create_pipeline_layout(desc);
251 PipelineLayout { inner: layout }
252 }
253
254 /// Creates a [`RenderPipeline`].
255 #[must_use]
256 pub fn create_render_pipeline(&self, desc: &RenderPipelineDescriptor<'_>) -> RenderPipeline {
257 let pipeline = self.inner.create_render_pipeline(desc);
258 RenderPipeline { inner: pipeline }
259 }
260
261 /// Creates a mesh shader based [`RenderPipeline`].
262 #[must_use]
263 pub fn create_mesh_pipeline(&self, desc: &MeshPipelineDescriptor<'_>) -> RenderPipeline {
264 let pipeline = self.inner.create_mesh_pipeline(desc);
265 RenderPipeline { inner: pipeline }
266 }
267
268 /// Creates a [`ComputePipeline`].
269 #[must_use]
270 pub fn create_compute_pipeline(&self, desc: &ComputePipelineDescriptor<'_>) -> ComputePipeline {
271 let pipeline = self.inner.create_compute_pipeline(desc);
272 ComputePipeline { inner: pipeline }
273 }
274
275 /// Creates a [`ComputePipeline`] without occupying the GPU's submission
276 /// thread while it compiles, where the backend can.
277 ///
278 /// On the WebGPU backend this is `createComputePipelineAsync`: the
279 /// browser compiles on worker threads, so pipelines compile in parallel
280 /// and its GPU process keeps serving frames and other work meanwhile.
281 /// The browser starts compiling when this is called, not when the future
282 /// is first polled. Other backends create the pipeline synchronously.
283 ///
284 /// Corresponds to [WebGPU `GPUDevice.createComputePipelineAsync`](
285 /// https://gpuweb.github.io/gpuweb/#dom-gpudevice-createcomputepipelineasync).
286 pub fn create_compute_pipeline_async(
287 &self,
288 desc: &ComputePipelineDescriptor<'_>,
289 ) -> impl Future<Output = ComputePipeline> + WasmNotSend + 'static {
290 #[cfg(webgpu)]
291 let pending = match self.inner.as_webgpu_opt() {
292 Some(device) => Ok(device.create_compute_pipeline_async(desc)),
293 None => Err(self.create_compute_pipeline(desc)),
294 };
295 #[cfg(not(webgpu))]
296 let pending: Result<core::future::Pending<dispatch::DispatchComputePipeline>, _> =
297 Err(self.create_compute_pipeline(desc));
298 async move {
299 match pending {
300 Ok(pending) => ComputePipeline {
301 inner: pending.await,
302 },
303 Err(created) => created,
304 }
305 }
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 /// # Safety
352 ///
353 /// - `hal_texture` must be created from this device internal handle
354 /// - `hal_texture` must be created respecting `desc`
355 /// - `hal_texture` must be initialized
356 #[cfg(wgpu_core)]
357 #[must_use]
358 pub unsafe fn create_texture_from_hal<A: hal::Api>(
359 &self,
360 hal_texture: A::Texture,
361 desc: &TextureDescriptor<'_>,
362 ) -> Texture {
363 let texture = unsafe {
364 let core_device = self.inner.as_core();
365 core_device
366 .context
367 .create_texture_from_hal::<A>(hal_texture, core_device, desc)
368 };
369 Texture {
370 inner: texture.into(),
371 descriptor: TextureDescriptor {
372 label: None,
373 view_formats: &[],
374 ..desc.clone()
375 },
376 }
377 }
378
379 /// Creates a new [`ExternalTexture`].
380 #[must_use]
381 pub fn create_external_texture(
382 &self,
383 desc: &ExternalTextureDescriptor<'_>,
384 planes: &[&TextureView],
385 ) -> ExternalTexture {
386 let external_texture = self.inner.create_external_texture(desc, planes);
387
388 ExternalTexture {
389 inner: external_texture,
390 }
391 }
392
393 /// Creates a [`Buffer`] from a wgpu-hal Buffer.
394 ///
395 /// # Types
396 ///
397 /// The type of `A::Buffer` depends on the backend:
398 ///
399 #[doc = crate::macros::hal_type_vulkan!("Buffer")]
400 #[doc = crate::macros::hal_type_metal!("Buffer")]
401 #[doc = crate::macros::hal_type_dx12!("Buffer")]
402 #[doc = crate::macros::hal_type_gles!("Buffer")]
403 ///
404 /// # Safety
405 ///
406 /// - `hal_buffer` must be created from this device internal handle
407 /// - `hal_buffer` must be created respecting `desc`
408 /// - `hal_buffer` must be initialized
409 /// - `hal_buffer` must not have zero size
410 #[cfg(wgpu_core)]
411 #[must_use]
412 pub unsafe fn create_buffer_from_hal<A: hal::Api>(
413 &self,
414 hal_buffer: A::Buffer,
415 desc: &BufferDescriptor<'_>,
416 ) -> Buffer {
417 let map_context = MapContext::new(desc.mapped_at_creation.then_some(0..desc.size));
418
419 let buffer = unsafe {
420 let core_device = self.inner.as_core();
421 core_device
422 .context
423 .create_buffer_from_hal::<A>(hal_buffer, core_device, desc)
424 };
425
426 Buffer {
427 inner: buffer.into(),
428 map_context: Arc::new(Mutex::new(map_context)),
429 size: desc.size,
430 usage: desc.usage,
431 }
432 }
433
434 /// Creates a new [`Sampler`].
435 ///
436 /// `desc` specifies the behavior of the sampler.
437 #[must_use]
438 pub fn create_sampler(&self, desc: &SamplerDescriptor<'_>) -> Sampler {
439 let sampler = self.inner.create_sampler(desc);
440 Sampler { inner: sampler }
441 }
442
443 /// Creates a new [`QuerySet`].
444 #[must_use]
445 pub fn create_query_set(&self, desc: &QuerySetDescriptor<'_>) -> QuerySet {
446 let query_set = self.inner.create_query_set(desc);
447 QuerySet { inner: query_set }
448 }
449
450 /// Set a callback which will be called for all errors that are not handled in error scopes.
451 pub fn on_uncaptured_error(&self, handler: Arc<dyn UncapturedErrorHandler>) {
452 self.inner.on_uncaptured_error(handler)
453 }
454
455 /// Push an error scope on this device's thread-local error scope
456 /// stack. All operations on this device, or on resources created
457 /// from this device, will have their errors captured by this scope
458 /// until the scope is popped.
459 ///
460 /// Scopes must be popped in reverse order to their creation. If
461 /// a guard is dropped without being `pop()`ped, the scope will be
462 /// popped, and the captured errors will be dropped.
463 ///
464 /// Multiple error scopes may be active at one time, forming a stack.
465 /// Each error will be reported to the inner-most scope that matches
466 /// its filter.
467 ///
468 /// With the `std` feature enabled, this stack is **thread-local**.
469 /// Without, this is **global** to all threads.
470 ///
471 /// ```rust
472 /// # async move {
473 /// # let device: wgpu::Device = unreachable!();
474 /// let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
475 ///
476 /// // ...
477 /// // do work that may produce validation errors
478 /// // ...
479 ///
480 /// // pop the error scope and get a future for the result
481 /// let error_future = error_scope.pop();
482 ///
483 /// // await the future to get the error, if any
484 /// let error = error_future.await;
485 /// # };
486 /// ```
487 pub fn push_error_scope(&self, filter: ErrorFilter) -> ErrorScopeGuard {
488 let index = self.inner.push_error_scope(filter);
489 ErrorScopeGuard {
490 device: self.inner.clone(),
491 index,
492 popped: false,
493 _phantom: PhantomData,
494 }
495 }
496
497 /// Starts a capture in the attached graphics debugger.
498 ///
499 /// This behaves differently depending on which graphics debugger is attached:
500 ///
501 /// - Renderdoc: Calls [`StartFrameCapture(device, NULL)`][rd].
502 /// - Xcode: Creates a capture with [`MTLCaptureManager`][xcode].
503 /// - None: No action is taken.
504 ///
505 /// # Safety
506 ///
507 /// - There should not be any other captures currently active.
508 /// - All other safety rules are defined by the graphics debugger, see the
509 /// documentation for the specific debugger.
510 /// - In general, graphics debuggers can easily cause crashes, so this isn't
511 /// ever guaranteed to be sound.
512 ///
513 /// # Tips
514 ///
515 /// - Debuggers need to capture both the recording of the commands and the
516 /// submission of the commands to the GPU. Try to wrap all of your
517 /// gpu work in a capture.
518 /// - If you encounter issues, try waiting for the GPU to finish all work
519 /// before stopping the capture.
520 ///
521 /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv417StartFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle
522 /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager
523 #[doc(alias = "start_renderdoc_capture")]
524 #[doc(alias = "start_xcode_capture")]
525 pub unsafe fn start_graphics_debugger_capture(&self) {
526 unsafe { self.inner.start_graphics_debugger_capture() }
527 }
528
529 /// Stops the current capture in the attached graphics debugger.
530 ///
531 /// This behaves differently depending on which graphics debugger is attached:
532 ///
533 /// - Renderdoc: Calls [`EndFrameCapture(device, NULL)`][rd].
534 /// - Xcode: Stops the capture with [`MTLCaptureManager`][xcode].
535 /// - None: No action is taken.
536 ///
537 /// # Safety
538 ///
539 /// - There should be a capture currently active.
540 /// - All other safety rules are defined by the graphics debugger, see the
541 /// documentation for the specific debugger.
542 /// - In general, graphics debuggers can easily cause crashes, so this isn't
543 /// ever guaranteed to be sound.
544 ///
545 /// # Tips
546 ///
547 /// - If you encounter issues, try to submit all work to the GPU, and waiting
548 /// for that work to finish before stopping the capture.
549 ///
550 /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv415EndFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle
551 /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager
552 #[doc(alias = "stop_renderdoc_capture")]
553 #[doc(alias = "stop_xcode_capture")]
554 pub unsafe fn stop_graphics_debugger_capture(&self) {
555 unsafe { self.inner.stop_graphics_debugger_capture() }
556 }
557
558 /// Query internal counters from the native backend for debugging purposes.
559 ///
560 /// Some backends may not set all counters, or may not set any counter at all.
561 /// The `counters` cargo feature must be enabled for any counter to be set.
562 ///
563 /// If a counter is not set, its contains its default value (zero).
564 #[must_use]
565 pub fn get_internal_counters(&self) -> wgt::InternalCounters {
566 self.inner.get_internal_counters()
567 }
568
569 /// Generate an GPU memory allocation report if the underlying backend supports it.
570 ///
571 /// Backends that do not support producing these reports return `None`. A backend may
572 /// Support it and still return `None` if it is not using performing sub-allocation,
573 /// for example as a workaround for driver issues.
574 #[must_use]
575 pub fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
576 self.inner.generate_allocator_report()
577 }
578
579 /// Get the [`wgpu_hal`] device from this `Device`.
580 ///
581 /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
582 /// and pass that struct to the to the `A` type parameter.
583 ///
584 /// Returns a guard that dereferences to the type of the hal backend
585 /// which implements [`A::Device`].
586 ///
587 /// # Types
588 ///
589 /// The returned type depends on the backend:
590 ///
591 #[doc = crate::macros::hal_type_vulkan!("Device")]
592 #[doc = crate::macros::hal_type_metal!("Device")]
593 #[doc = crate::macros::hal_type_dx12!("Device")]
594 #[doc = crate::macros::hal_type_gles!("Device")]
595 ///
596 /// # Errors
597 ///
598 /// This method will return None if:
599 /// - The device is not from the backend specified by `A`.
600 /// - The device is from the `webgpu` or `custom` backend.
601 ///
602 /// # Safety
603 ///
604 /// - The returned resource must not be destroyed unless the guard
605 /// is the last reference to it and it is not in use by the GPU.
606 /// The guard and handle may be dropped at any time however.
607 /// - All the safety requirements of wgpu-hal must be upheld.
608 ///
609 /// [`A::Device`]: hal::Api::Device
610 #[cfg(wgpu_core)]
611 pub unsafe fn as_hal<A: hal::Api>(
612 &self,
613 ) -> Option<impl Deref<Target = A::Device> + WasmNotSendSync> {
614 let device = self.inner.as_core_opt()?;
615 unsafe { device.context.device_as_hal::<A>(device) }
616 }
617
618 /// Destroy this device.
619 pub fn destroy(&self) {
620 self.inner.destroy()
621 }
622
623 /// Set a DeviceLostCallback on this device.
624 pub fn set_device_lost_callback(
625 &self,
626 callback: impl Fn(DeviceLostReason, String) + Send + 'static,
627 ) {
628 self.inner.set_device_lost_callback(Box::new(callback))
629 }
630
631 /// Create a [`PipelineCache`] with initial data
632 ///
633 /// This can be passed to [`Device::create_compute_pipeline`]
634 /// and [`Device::create_render_pipeline`] to either accelerate these
635 /// or add the cache results from those.
636 ///
637 /// # Safety
638 ///
639 /// If the `data` field of `desc` is set, it must have previously been returned from a call
640 /// to [`PipelineCache::get_data`][^saving]. This `data` will only be used if it came
641 /// from an adapter with the same [`util::pipeline_cache_key`].
642 /// This *is* compatible across wgpu versions, as any data format change will
643 /// be accounted for.
644 ///
645 /// It is *not* supported to bring caches from previous direct uses of backend APIs
646 /// into this method.
647 ///
648 /// # Errors
649 ///
650 /// Returns an error value if:
651 /// * the [`PIPELINE_CACHE`](wgt::Features::PIPELINE_CACHE) feature is not enabled
652 /// * this device is invalid; or
653 /// * the device is out of memory
654 ///
655 /// This method also returns an error value if:
656 /// * The `fallback` field on `desc` is false; and
657 /// * the `data` provided would not be used[^data_not_used]
658 ///
659 /// If an error value is used in subsequent calls, default caching will be used.
660 ///
661 /// [^saving]: We do recognise that saving this data to disk means this condition
662 /// is impossible to fully prove. Consider the risks for your own application in this case.
663 ///
664 /// [^data_not_used]: This data may be not used if: the data was produced by a prior
665 /// version of wgpu; or was created for an incompatible adapter, or there was a GPU driver
666 /// update. In some cases, the data might not be used and a real value is returned,
667 /// this is left to the discretion of GPU drivers.
668 #[must_use]
669 pub unsafe fn create_pipeline_cache(
670 &self,
671 desc: &PipelineCacheDescriptor<'_>,
672 ) -> PipelineCache {
673 let cache = unsafe { self.inner.create_pipeline_cache(desc) };
674 PipelineCache { inner: cache }
675 }
676}
677
678/// [`Features::EXPERIMENTAL_RAY_QUERY`] must be enabled on the device in order to call these functions.
679impl Device {
680 /// Create a bottom level acceleration structure, used inside a top level acceleration structure for ray tracing.
681 /// - `desc`: The descriptor of the acceleration structure.
682 /// - `sizes`: Size descriptor limiting what can be built into the acceleration structure.
683 ///
684 /// # Validation
685 /// If any of the following is not satisfied a validation error is generated
686 ///
687 /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled.
688 /// if `sizes` is [`BlasGeometrySizeDescriptors::Triangles`] then the following must be satisfied
689 /// - For every geometry descriptor (for the purposes this is called `geo_desc`) of `sizes.descriptors` the following must be satisfied:
690 /// - `geo_desc.vertex_format` must be within allowed formats (allowed formats for a given feature set
691 /// may be queried with [`Features::allowed_vertex_formats_for_blas`]).
692 /// - Both or neither of `geo_desc.index_format` and `geo_desc.index_count` must be provided.
693 ///
694 /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
695 /// [`Features::allowed_vertex_formats_for_blas`]: wgt::Features::allowed_vertex_formats_for_blas
696 #[must_use]
697 pub fn create_blas(
698 &self,
699 desc: &CreateBlasDescriptor<'_>,
700 sizes: BlasGeometrySizeDescriptors,
701 ) -> Blas {
702 let (handle, blas) = self.inner.create_blas(desc, sizes);
703
704 Blas {
705 inner: blas,
706 handle,
707 }
708 }
709
710 /// Create a top level acceleration structure, used for ray tracing.
711 /// - `desc`: The descriptor of the acceleration structure.
712 ///
713 /// # Validation
714 /// If any of the following is not satisfied a validation error is generated
715 ///
716 /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled.
717 ///
718 /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
719 #[must_use]
720 pub fn create_tlas(&self, desc: &CreateTlasDescriptor<'_>) -> Tlas {
721 let tlas = self.inner.create_tlas(desc);
722
723 Tlas {
724 inner: tlas,
725 instances: vec![None; desc.max_instances as usize],
726 lowest_unmodified: 0,
727 }
728 }
729}
730
731/// Requesting a device from an [`Adapter`] failed.
732#[derive(Clone, Debug)]
733pub struct RequestDeviceError {
734 pub(crate) inner: RequestDeviceErrorKind,
735}
736#[derive(Clone, Debug)]
737pub(crate) enum RequestDeviceErrorKind {
738 /// Error from [`wgpu_core`].
739 // must match dependency cfg
740 #[cfg(wgpu_core)]
741 Core(wgc::instance::RequestDeviceError),
742
743 /// Error from web API that was called by `wgpu` to request a device.
744 ///
745 /// (This is currently never used by the webgl backend, but it could be.)
746 #[cfg(webgpu)]
747 WebGpu(String),
748}
749
750static_assertions::assert_impl_all!(RequestDeviceError: Send, Sync);
751
752impl fmt::Display for RequestDeviceError {
753 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
754 match &self.inner {
755 #[cfg(wgpu_core)]
756 RequestDeviceErrorKind::Core(error) => error.fmt(_f),
757 #[cfg(webgpu)]
758 RequestDeviceErrorKind::WebGpu(error) => {
759 write!(_f, "{error}")
760 }
761 #[cfg(not(any(webgpu, wgpu_core)))]
762 _ => unimplemented!("unknown `RequestDeviceErrorKind`"),
763 }
764 }
765}
766
767impl error::Error for RequestDeviceError {
768 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
769 match &self.inner {
770 #[cfg(wgpu_core)]
771 RequestDeviceErrorKind::Core(error) => error.source(),
772 #[cfg(webgpu)]
773 RequestDeviceErrorKind::WebGpu(_) => None,
774 #[cfg(not(any(webgpu, wgpu_core)))]
775 _ => unimplemented!("unknown `RequestDeviceErrorKind`"),
776 }
777 }
778}
779
780#[cfg(wgpu_core)]
781impl From<wgc::instance::RequestDeviceError> for RequestDeviceError {
782 fn from(error: wgc::instance::RequestDeviceError) -> Self {
783 Self {
784 inner: RequestDeviceErrorKind::Core(error),
785 }
786 }
787}
788
789/// The callback of [`Device::on_uncaptured_error()`].
790///
791/// It must be a function with this signature.
792pub trait UncapturedErrorHandler: Fn(Error) + Send + Sync + 'static {}
793impl<T> UncapturedErrorHandler for T where T: Fn(Error) + Send + Sync + 'static {}
794
795/// Kinds of [`Error`]s a [`Device::push_error_scope()`] may be configured to catch.
796#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
797pub enum ErrorFilter {
798 /// Catch only out-of-memory errors.
799 OutOfMemory,
800 /// Catch only validation errors.
801 Validation,
802 /// Catch only internal errors.
803 Internal,
804}
805static_assertions::assert_impl_all!(ErrorFilter: Send, Sync);
806
807/// Lower level source of the error.
808///
809/// `Send + Sync` varies depending on configuration.
810#[cfg(send_sync)]
811#[cfg_attr(docsrs, doc(cfg(all())))]
812pub type ErrorSource = Box<dyn error::Error + Send + Sync + 'static>;
813/// Lower level source of the error.
814///
815/// `Send + Sync` varies depending on configuration.
816#[cfg(not(send_sync))]
817#[cfg_attr(docsrs, doc(cfg(all())))]
818pub type ErrorSource = Box<dyn error::Error + 'static>;
819
820/// Errors resulting from usage of GPU APIs.
821///
822/// By default, errors translate into panics. Depending on the backend and circumstances,
823/// errors may occur synchronously or asynchronously. When errors need to be handled, use
824/// [`Device::push_error_scope()`] or [`Device::on_uncaptured_error()`].
825#[derive(Debug)]
826pub enum Error {
827 /// Out of memory.
828 OutOfMemory {
829 /// Lower level source of the error.
830 source: ErrorSource,
831 },
832 /// Validation error, signifying a bug in code or data provided to `wgpu`.
833 Validation {
834 /// Lower level source of the error.
835 source: ErrorSource,
836 /// Description of the validation error.
837 description: String,
838 },
839 /// Internal error. Used for signalling any failures not explicitly expected by WebGPU.
840 ///
841 /// These could be due to internal implementation or system limits being reached.
842 Internal {
843 /// Lower level source of the error.
844 source: ErrorSource,
845 /// Description of the internal GPU error.
846 description: String,
847 },
848}
849#[cfg(send_sync)]
850static_assertions::assert_impl_all!(Error: Send, Sync);
851
852impl error::Error for Error {
853 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
854 match self {
855 Error::OutOfMemory { source } => Some(source.as_ref()),
856 Error::Validation { source, .. } => Some(source.as_ref()),
857 Error::Internal { source, .. } => Some(source.as_ref()),
858 }
859 }
860}
861
862impl fmt::Display for Error {
863 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
864 match self {
865 Error::OutOfMemory { .. } => f.write_str("Out of Memory"),
866 Error::Validation { description, .. } => f.write_str(description),
867 Error::Internal { description, .. } => f.write_str(description),
868 }
869 }
870}
871
872/// Guard for an error scope pushed with [`Device::push_error_scope()`].
873///
874/// Call [`pop()`] to pop the scope and get a future for the result. If
875/// the guard is dropped without being popped explicitly, the scope will still be popped,
876/// and the captured errors will be dropped.
877///
878/// This guard is neither `Send` nor `Sync`, as error scopes are handled
879/// on a per-thread basis when the `std` feature is enabled.
880///
881/// [`pop()`]: ErrorScopeGuard::pop
882#[must_use = "Error scopes must be explicitly popped to retrieve errors they catch"]
883pub struct ErrorScopeGuard {
884 device: dispatch::DispatchDevice,
885 index: u32,
886 popped: bool,
887 // Ensure the guard is !Send and !Sync
888 _phantom: PhantomData<*mut ()>,
889}
890
891static_assertions::assert_not_impl_any!(ErrorScopeGuard: Send, Sync);
892
893impl ErrorScopeGuard {
894 /// Pops the error scope.
895 ///
896 /// Returns a future which resolves to the error captured by this scope, if any.
897 /// The pop takes effect immediately; the future does not need to be awaited before doing work that is outside of this error scope.
898 pub fn pop(mut self) -> impl Future<Output = Option<Error>> + WasmNotSend {
899 self.popped = true;
900 self.device.pop_error_scope(self.index)
901 }
902}
903
904impl Drop for ErrorScopeGuard {
905 fn drop(&mut self) {
906 if !self.popped {
907 drop(self.device.pop_error_scope(self.index));
908 }
909 }
910}