Debian Codegraph @

third_party/rust/wgpu-hal/src/lib.rs

raw
1 //! A cross-platform unsafe graphics abstraction.
2 //!
3 //! This crate defines a set of traits abstracting over modern graphics APIs,
4 //! with implementations ("backends") for Vulkan, Metal, Direct3D, and GL.
5 //!
6 //! `wgpu-hal` is a spiritual successor to
7 //! [gfx-hal](https://github.com/gfx-rs/gfx), but with reduced scope, and
8 //! oriented towards WebGPU implementation goals. It has no overhead for
9 //! validation or tracking, and the API translation overhead is kept to the bare
10 //! minimum by the design of WebGPU. This API can be used for resource-demanding
11 //! applications and engines.
12 //!
13 //! The `wgpu-hal` crate's main design choices:
14 //!
15 //! - Our traits are meant to be *portable*: proper use
16 //! should get equivalent results regardless of the backend.
17 //!
18 //! - Our traits' contracts are *unsafe*: implementations perform minimal
19 //! validation, if any, and incorrect use will often cause undefined behavior.
20 //! This allows us to minimize the overhead we impose over the underlying
21 //! graphics system. If you need safety, the [`wgpu-core`] crate provides a
22 //! safe API for driving `wgpu-hal`, implementing all necessary validation,
23 //! resource state tracking, and so on. (Note that `wgpu-core` is designed for
24 //! use via FFI; the [`wgpu`] crate provides more idiomatic Rust bindings for
25 //! `wgpu-core`.) Or, you can do your own validation.
26 //!
27 //! - In the same vein, returned errors *only cover cases the user can't
28 //! anticipate*, like running out of memory or losing the device. Any errors
29 //! that the user could reasonably anticipate are their responsibility to
30 //! avoid. For example, `wgpu-hal` returns no error for mapping a buffer that's
31 //! not mappable: as the buffer creator, the user should already know if they
32 //! can map it.
33 //!
34 //! - We use *static dispatch*. The traits are not
35 //! generally object-safe. You must select a specific backend type
36 //! like [`vulkan::Api`] or [`metal::Api`], and then use that
37 //! according to the main traits, or call backend-specific methods.
38 //!
39 //! - We use *idiomatic Rust parameter passing*,
40 //! taking objects by reference, returning them by value, and so on,
41 //! unlike `wgpu-core`, which refers to objects by ID.
42 //!
43 //! - We map buffer contents *persistently*. This means that the buffer can
44 //! remain mapped on the CPU while the GPU reads or writes to it. You must
45 //! explicitly indicate when data might need to be transferred between CPU and
46 //! GPU, if [`Device::map_buffer`] indicates that this is necessary.
47 //!
48 //! - You must record *explicit barriers* between different usages of a
49 //! resource. For example, if a buffer is written to by a compute
50 //! shader, and then used as and index buffer to a draw call, you
51 //! must use [`CommandEncoder::transition_buffers`] between those two
52 //! operations.
53 //!
54 //! - Pipeline layouts are *explicitly specified* when setting bind groups.
55 //! Incompatible layouts disturb groups bound at higher indices.
56 //!
57 //! - The API *accepts collections as iterators*, to avoid forcing the user to
58 //! store data in particular containers. The implementation doesn't guarantee
59 //! that any of the iterators are drained, unless stated otherwise by the
60 //! function documentation. For this reason, we recommend that iterators don't
61 //! do any mutating work.
62 //!
63 //! Unfortunately, `wgpu-hal`'s safety requirements are not fully documented.
64 //! Ideally, all trait methods would have doc comments setting out the
65 //! requirements users must meet to ensure correct and portable behavior. If you
66 //! are aware of a specific requirement that a backend imposes that is not
67 //! ensured by the traits' documented rules, please file an issue. Or, if you are
68 //! a capable technical writer, please file a pull request!
69 //!
70 //! [`wgpu-core`]: https://crates.io/crates/wgpu-core
71 //! [`wgpu`]: https://crates.io/crates/wgpu
72 //! [`vulkan::Api`]: vulkan/struct.Api.html
73 //! [`metal::Api`]: metal/struct.Api.html
74 //!
75 //! ## Primary backends
76 //!
77 //! The `wgpu-hal` crate has full-featured backends implemented on the following
78 //! platform graphics APIs:
79 //!
80 //! - Vulkan, available on Linux, Android, and Windows, using the [`ash`] crate's
81 //! Vulkan bindings. It's also available on macOS, if you install [MoltenVK].
82 //!
83 //! - Metal on macOS, using the [`metal`] crate's bindings.
84 //!
85 //! - Direct3D 12 on Windows, using the [`windows`] crate's bindings.
86 //!
87 //! [`ash`]: https://crates.io/crates/ash
88 //! [MoltenVK]: https://github.com/KhronosGroup/MoltenVK
89 //! [`metal`]: https://crates.io/crates/metal
90 //! [`windows`]: https://crates.io/crates/windows
91 //!
92 //! ## Secondary backends
93 //!
94 //! The `wgpu-hal` crate has a partial implementation based on the following
95 //! platform graphics API:
96 //!
97 //! - The GL backend is available anywhere OpenGL, OpenGL ES, or WebGL are
98 //! available. See the [`gles`] module documentation for details.
99 //!
100 //! [`gles`]: gles/index.html
101 //!
102 //! You can see what capabilities an adapter is missing by checking the
103 //! [`DownlevelCapabilities`][tdc] in [`ExposedAdapter::capabilities`], available
104 //! from [`Instance::enumerate_adapters`].
105 //!
106 //! The API is generally designed to fit the primary backends better than the
107 //! secondary backends, so the latter may impose more overhead.
108 //!
109 //! [tdc]: wgt::DownlevelCapabilities
110 //!
111 //! ## Traits
112 //!
113 //! The `wgpu-hal` crate defines a handful of traits that together
114 //! represent a cross-platform abstraction for modern GPU APIs.
115 //!
116 //! - The [`Api`] trait represents a `wgpu-hal` backend. It has no methods of its
117 //! own, only a collection of associated types.
118 //!
119 //! - [`Api::Instance`] implements the [`Instance`] trait. [`Instance::init`]
120 //! creates an instance value, which you can use to enumerate the adapters
121 //! available on the system. For example, [`vulkan::Api::Instance::init`][Ii]
122 //! returns an instance that can enumerate the Vulkan physical devices on your
123 //! system.
124 //!
125 //! - [`Api::Adapter`] implements the [`Adapter`] trait, representing a
126 //! particular device from a particular backend. For example, a Vulkan instance
127 //! might have a Lavapipe software adapter and a GPU-based adapter.
128 //!
129 //! - [`Api::Device`] implements the [`Device`] trait, representing an active
130 //! link to a device. You get a device value by calling [`Adapter::open`], and
131 //! then use it to create buffers, textures, shader modules, and so on.
132 //!
133 //! - [`Api::Queue`] implements the [`Queue`] trait, which you use to submit
134 //! command buffers to a given device.
135 //!
136 //! - [`Api::CommandEncoder`] implements the [`CommandEncoder`] trait, which you
137 //! use to build buffers of commands to submit to a queue. This has all the
138 //! methods for drawing and running compute shaders, which is presumably what
139 //! you're here for.
140 //!
141 //! - [`Api::Surface`] implements the [`Surface`] trait, which represents a
142 //! swapchain for presenting images on the screen, via interaction with the
143 //! system's window manager.
144 //!
145 //! The [`Api`] trait has various other associated types like [`Api::Buffer`] and
146 //! [`Api::Texture`] that represent resources the rest of the interface can
147 //! operate on, but these generally do not have their own traits.
148 //!
149 //! [Ii]: Instance::init
150 //!
151 //! ## Validation is the calling code's responsibility, not `wgpu-hal`'s
152 //!
153 //! As much as possible, `wgpu-hal` traits place the burden of validation,
154 //! resource tracking, and state tracking on the caller, not on the trait
155 //! implementations themselves. Anything which can reasonably be handled in
156 //! backend-independent code should be. A `wgpu_hal` backend's sole obligation is
157 //! to provide portable behavior, and report conditions that the calling code
158 //! can't reasonably anticipate, like device loss or running out of memory.
159 //!
160 //! The `wgpu` crate collection is intended for use in security-sensitive
161 //! applications, like web browsers, where the API is available to untrusted
162 //! code. This means that `wgpu-core`'s validation is not simply a service to
163 //! developers, to be provided opportunistically when the performance costs are
164 //! acceptable and the necessary data is ready at hand. Rather, `wgpu-core`'s
165 //! validation must be exhaustive, to ensure that even malicious content cannot
166 //! provoke and exploit undefined behavior in the platform's graphics API.
167 //!
168 //! Because graphics APIs' requirements are complex, the only practical way for
169 //! `wgpu` to provide exhaustive validation is to comprehensively track the
170 //! lifetime and state of all the resources in the system. Implementing this
171 //! separately for each backend is infeasible; effort would be better spent
172 //! making the cross-platform validation in `wgpu-core` legible and trustworthy.
173 //! Fortunately, the requirements are largely similar across the various
174 //! platforms, so cross-platform validation is practical.
175 //!
176 //! Some backends have specific requirements that aren't practical to foist off
177 //! on the `wgpu-hal` user. For example, properly managing macOS Objective-C or
178 //! Microsoft COM reference counts is best handled by using appropriate pointer
179 //! types within the backend.
180 //!
181 //! A desire for "defense in depth" may suggest performing additional validation
182 //! in `wgpu-hal` when the opportunity arises, but this must be done with
183 //! caution. Even experienced contributors infer the expectations their changes
184 //! must meet by considering not just requirements made explicit in types, tests,
185 //! assertions, and comments, but also those implicit in the surrounding code.
186 //! When one sees validation or state-tracking code in `wgpu-hal`, it is tempting
187 //! to conclude, "Oh, `wgpu-hal` checks for this, so `wgpu-core` needn't worry
188 //! about it - that would be redundant!" The responsibility for exhaustive
189 //! validation always rests with `wgpu-core`, regardless of what may or may not
190 //! be checked in `wgpu-hal`.
191 //!
192 //! To this end, any "defense in depth" validation that does appear in `wgpu-hal`
193 //! for requirements that `wgpu-core` should have enforced should report failure
194 //! via the `unreachable!` macro, because problems detected at this stage always
195 //! indicate a bug in `wgpu-core`.
196 //!
197 //! ## Debugging
198 //!
199 //! Most of the information on the wiki [Debugging wgpu Applications][wiki-debug]
200 //! page still applies to this API, with the exception of API tracing/replay
201 //! functionality, which is only available in `wgpu-core`.
202 //!
203 //! [wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications
204
205 #![no_std]
206 #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
207 #![allow(
208 // this happens on the GL backend, where it is both thread safe and non-thread safe in the same code.
209 clippy::arc_with_non_send_sync,
210 // We don't use syntax sugar where it's not necessary.
211 clippy::match_like_matches_macro,
212 // Redundant matching is more explicit.
213 clippy::redundant_pattern_matching,
214 // Explicit lifetimes are often easier to reason about.
215 clippy::needless_lifetimes,
216 // No need for defaults in the internal types.
217 clippy::new_without_default,
218 // Matches are good and extendable, no need to make an exception here.
219 clippy::single_match,
220 // Push commands are more regular than macros.
221 clippy::vec_init_then_push,
222 // We unsafe impl `Send` for a reason.
223 clippy::non_send_fields_in_send_ty,
224 // TODO!
225 clippy::missing_safety_doc,
226 // It gets in the way a lot and does not prevent bugs in practice.
227 clippy::pattern_type_mismatch,
228 )]
229 #![warn(
230 clippy::alloc_instead_of_core,
231 clippy::ptr_as_ptr,
232 clippy::std_instead_of_alloc,
233 clippy::std_instead_of_core,
234 trivial_casts,
235 trivial_numeric_casts,
236 unsafe_op_in_unsafe_fn,
237 unused_extern_crates,
238 unused_qualifications
239 )]
240
241 extern crate alloc;
242 extern crate wgpu_types as wgt;
243 // Each of these backends needs `std` in some fashion; usually `std::thread` functions.
244 #[cfg(any(dx12, gles_with_std, metal, vulkan))]
245 #[macro_use]
246 extern crate std;
247
248 /// DirectX12 API internals.
249 #[cfg(dx12)]
250 pub mod dx12;
251 /// GLES API internals.
252 #[cfg(gles)]
253 pub mod gles;
254 /// Metal API internals.
255 #[cfg(metal)]
256 pub mod metal;
257 /// A dummy API implementation.
258 // TODO(https://github.com/gfx-rs/wgpu/issues/7120): this should have a cfg
259 pub mod noop;
260 /// Vulkan API internals.
261 #[cfg(vulkan)]
262 pub mod vulkan;
263
264 pub mod auxil;
265 pub mod api {
266 #[cfg(dx12)]
267 pub use super::dx12::Api as Dx12;
268 #[cfg(gles)]
269 pub use super::gles::Api as Gles;
270 #[cfg(metal)]
271 pub use super::metal::Api as Metal;
272 pub use super::noop::Api as Noop;
273 #[cfg(vulkan)]
274 pub use super::vulkan::Api as Vulkan;
275 }
276
277 mod dynamic;
278
279 pub(crate) use dynamic::impl_dyn_resource;
280 pub use dynamic::{
281 DynAccelerationStructure, DynAcquiredSurfaceTexture, DynAdapter, DynBindGroup,
282 DynBindGroupLayout, DynBuffer, DynCommandBuffer, DynCommandEncoder, DynComputePipeline,
283 DynDevice, DynExposedAdapter, DynFence, DynInstance, DynOpenDevice, DynPipelineCache,
284 DynPipelineLayout, DynQuerySet, DynQueue, DynRenderPipeline, DynResource, DynSampler,
285 DynShaderModule, DynSurface, DynSurfaceTexture, DynTexture, DynTextureView,
286 };
287
288 #[allow(unused)]
289 use alloc::boxed::Box;
290 use alloc::{borrow::Cow, string::String, sync::Arc, vec::Vec};
291 use core::{
292 borrow::Borrow,
293 error::Error,
294 fmt,
295 num::NonZeroU32,
296 ops::{Range, RangeInclusive},
297 ptr::NonNull,
298 };
299
300 use bitflags::bitflags;
301 use parking_lot::Mutex;
302 use thiserror::Error;
303 use wgt::WasmNotSendSync;
304
305 // - Vertex + Fragment
306 // - Compute
307 // Task + Mesh + Fragment
308 pub const MAX_CONCURRENT_SHADER_STAGES: usize = 3;
309 pub const MAX_ANISOTROPY: u8 = 16;
310 pub const MAX_BIND_GROUPS: usize = 8;
311 pub const MAX_VERTEX_BUFFERS: usize = 16;
312 pub const MAX_COLOR_ATTACHMENTS: usize = 8;
313 pub const MAX_MIP_LEVELS: u32 = 16;
314 /// Size of a single occlusion/timestamp query, when copied into a buffer, in bytes.
315 /// cbindgen:ignore
316 pub const QUERY_SIZE: wgt::BufferAddress = 8;
317
318 pub type Label<'a> = Option<&'a str>;
319 pub type MemoryRange = Range<wgt::BufferAddress>;
320 pub type FenceValue = u64;
321 #[cfg(supports_64bit_atomics)]
322 pub type AtomicFenceValue = core::sync::atomic::AtomicU64;
323 #[cfg(not(supports_64bit_atomics))]
324 pub type AtomicFenceValue = portable_atomic::AtomicU64;
325
326 /// A callback to signal that wgpu is no longer using a resource.
327 #[cfg(any(gles, vulkan))]
328 pub type DropCallback = Box<dyn FnOnce() + Send + Sync + 'static>;
329
330 #[cfg(any(gles, vulkan))]
331 pub struct DropGuard {
332 callback: Option<DropCallback>,
333 }
334
335 #[cfg(all(any(gles, vulkan), any(native, Emscripten)))]
336 impl DropGuard {
337 fn from_option(callback: Option<DropCallback>) -> Option<Self> {
338 callback.map(|callback| Self {
339 callback: Some(callback),
340 })
341 }
342 }
343
344 #[cfg(any(gles, vulkan))]
345 impl Drop for DropGuard {
346 fn drop(&mut self) {
347 if let Some(cb) = self.callback.take() {
348 (cb)();
349 }
350 }
351 }
352
353 #[cfg(any(gles, vulkan))]
354 impl fmt::Debug for DropGuard {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.debug_struct("DropGuard").finish()
357 }
358 }
359
360 #[derive(Clone, Debug, PartialEq, Eq, Error)]
361 pub enum DeviceError {
362 #[error("Out of memory")]
363 OutOfMemory,
364 #[error("Device is lost")]
365 Lost,
366 #[error("Creation of a resource failed for a reason other than running out of memory.")]
367 ResourceCreationFailed,
368 #[error("Unexpected error variant (driver implementation is at fault)")]
369 Unexpected,
370 }
371
372 #[allow(dead_code)] // may be unused on some platforms
373 #[cold]
374 fn hal_usage_error<T: fmt::Display>(txt: T) -> ! {
375 panic!("wgpu-hal invariant was violated (usage error): {txt}")
376 }
377
378 #[allow(dead_code)] // may be unused on some platforms
379 #[cold]
380 fn hal_internal_error<T: fmt::Display>(txt: T) -> ! {
381 panic!("wgpu-hal ran into a preventable internal error: {txt}")
382 }
383
384 #[derive(Clone, Debug, Eq, PartialEq, Error)]
385 pub enum ShaderError {
386 #[error("Compilation failed: {0:?}")]
387 Compilation(String),
388 #[error(transparent)]
389 Device(#[from] DeviceError),
390 }
391
392 #[derive(Clone, Debug, Eq, PartialEq, Error)]
393 pub enum PipelineError {
394 #[error("Linkage failed for stage {0:?}: {1}")]
395 Linkage(wgt::ShaderStages, String),
396 #[error("Entry point for stage {0:?} is invalid")]
397 EntryPoint(naga::ShaderStage),
398 #[error(transparent)]
399 Device(#[from] DeviceError),
400 #[error("Pipeline constant error for stage {0:?}: {1}")]
401 PipelineConstants(wgt::ShaderStages, String),
402 }
403
404 #[derive(Clone, Debug, Eq, PartialEq, Error)]
405 pub enum PipelineCacheError {
406 #[error(transparent)]
407 Device(#[from] DeviceError),
408 }
409
410 #[derive(Clone, Debug, Eq, PartialEq, Error)]
411 pub enum SurfaceError {
412 #[error("Surface is lost")]
413 Lost,
414 #[error("Surface is outdated, needs to be re-created")]
415 Outdated,
416 #[error(transparent)]
417 Device(#[from] DeviceError),
418 #[error("Other reason: {0}")]
419 Other(&'static str),
420 }
421
422 /// Error occurring while trying to create an instance, or create a surface from an instance;
423 /// typically relating to the state of the underlying graphics API or hardware.
424 #[derive(Clone, Debug, Error)]
425 #[error("{message}")]
426 pub struct InstanceError {
427 /// These errors are very platform specific, so do not attempt to encode them as an enum.
428 ///
429 /// This message should describe the problem in sufficient detail to be useful for a
430 /// user-to-developer “why won't this work on my machine” bug report, and otherwise follow
431 /// <https://rust-lang.github.io/api-guidelines/interoperability.html#error-types-are-meaningful-and-well-behaved-c-good-err>.
432 message: String,
433
434 /// Underlying error value, if any is available.
435 #[source]
436 source: Option<Arc<dyn Error + Send + Sync + 'static>>,
437 }
438
439 impl InstanceError {
440 #[allow(dead_code)] // may be unused on some platforms
441 pub(crate) fn new(message: String) -> Self {
442 Self {
443 message,
444 source: None,
445 }
446 }
447 #[allow(dead_code)] // may be unused on some platforms
448 pub(crate) fn with_source(message: String, source: impl Error + Send + Sync + 'static) -> Self {
449 Self {
450 message,
451 source: Some(Arc::new(source)),
452 }
453 }
454 }
455
456 pub trait Api: Clone + fmt::Debug + Sized {
457 type Instance: DynInstance + Instance<A = Self>;
458 type Surface: DynSurface + Surface<A = Self>;
459 type Adapter: DynAdapter + Adapter<A = Self>;
460 type Device: DynDevice + Device<A = Self>;
461
462 type Queue: DynQueue + Queue<A = Self>;
463 type CommandEncoder: DynCommandEncoder + CommandEncoder<A = Self>;
464
465 /// This API's command buffer type.
466 ///
467 /// The only thing you can do with `CommandBuffer`s is build them
468 /// with a [`CommandEncoder`] and then pass them to
469 /// [`Queue::submit`] for execution, or destroy them by passing
470 /// them to [`CommandEncoder::reset_all`].
471 ///
472 /// [`CommandEncoder`]: Api::CommandEncoder
473 type CommandBuffer: DynCommandBuffer;
474
475 type Buffer: DynBuffer;
476 type Texture: DynTexture;
477 type SurfaceTexture: DynSurfaceTexture + Borrow<Self::Texture>;
478 type TextureView: DynTextureView;
479 type Sampler: DynSampler;
480 type QuerySet: DynQuerySet;
481
482 /// A value you can block on to wait for something to finish.
483 ///
484 /// A `Fence` holds a monotonically increasing [`FenceValue`]. You can call
485 /// [`Device::wait`] to block until a fence reaches or passes a value you
486 /// choose. [`Queue::submit`] can take a `Fence` and a [`FenceValue`] to
487 /// store in it when the submitted work is complete.
488 ///
489 /// Attempting to set a fence to a value less than its current value has no
490 /// effect.
491 ///
492 /// Waiting on a fence returns as soon as the fence reaches *or passes* the
493 /// requested value. This implies that, in order to reliably determine when
494 /// an operation has completed, operations must finish in order of
495 /// increasing fence values: if a higher-valued operation were to finish
496 /// before a lower-valued operation, then waiting for the fence to reach the
497 /// lower value could return before the lower-valued operation has actually
498 /// finished.
499 type Fence: DynFence;
500
501 type BindGroupLayout: DynBindGroupLayout;
502 type BindGroup: DynBindGroup;
503 type PipelineLayout: DynPipelineLayout;
504 type ShaderModule: DynShaderModule;
505 type RenderPipeline: DynRenderPipeline;
506 type ComputePipeline: DynComputePipeline;
507 type PipelineCache: DynPipelineCache;
508
509 type AccelerationStructure: DynAccelerationStructure + 'static;
510 }
511
512 pub trait Instance: Sized + WasmNotSendSync {
513 type A: Api;
514
515 unsafe fn init(desc: &InstanceDescriptor) -> Result<Self, InstanceError>;
516 unsafe fn create_surface(
517 &self,
518 display_handle: raw_window_handle::RawDisplayHandle,
519 window_handle: raw_window_handle::RawWindowHandle,
520 ) -> Result<<Self::A as Api>::Surface, InstanceError>;
521 /// `surface_hint` is only used by the GLES backend targeting WebGL2
522 unsafe fn enumerate_adapters(
523 &self,
524 surface_hint: Option<&<Self::A as Api>::Surface>,
525 ) -> Vec<ExposedAdapter<Self::A>>;
526 }
527
528 pub trait Surface: WasmNotSendSync {
529 type A: Api;
530
531 /// Configure `self` to use `device`.
532 ///
533 /// # Safety
534 ///
535 /// - All GPU work using `self` must have been completed.
536 /// - All [`AcquiredSurfaceTexture`]s must have been destroyed.
537 /// - All [`Api::TextureView`]s derived from the [`AcquiredSurfaceTexture`]s must have been destroyed.
538 /// - The surface `self` must not currently be configured to use any other [`Device`].
539 unsafe fn configure(
540 &self,
541 device: &<Self::A as Api>::Device,
542 config: &SurfaceConfiguration,
543 ) -> Result<(), SurfaceError>;
544
545 /// Unconfigure `self` on `device`.
546 ///
547 /// # Safety
548 ///
549 /// - All GPU work that uses `surface` must have been completed.
550 /// - All [`AcquiredSurfaceTexture`]s must have been destroyed.
551 /// - All [`Api::TextureView`]s derived from the [`AcquiredSurfaceTexture`]s must have been destroyed.
552 /// - The surface `self` must have been configured on `device`.
553 unsafe fn unconfigure(&self, device: &<Self::A as Api>::Device);
554
555 /// Return the next texture to be presented by `self`, for the caller to draw on.
556 ///
557 /// On success, return an [`AcquiredSurfaceTexture`] representing the
558 /// texture into which the caller should draw the image to be displayed on
559 /// `self`.
560 ///
561 /// If `timeout` elapses before `self` has a texture ready to be acquired,
562 /// return `Ok(None)`. If `timeout` is `None`, wait indefinitely, with no
563 /// timeout.
564 ///
565 /// # Using an [`AcquiredSurfaceTexture`]
566 ///
567 /// On success, this function returns an [`AcquiredSurfaceTexture`] whose
568 /// [`texture`] field is a [`SurfaceTexture`] from which the caller can
569 /// [`borrow`] a [`Texture`] to draw on. The [`AcquiredSurfaceTexture`] also
570 /// carries some metadata about that [`SurfaceTexture`].
571 ///
572 /// All calls to [`Queue::submit`] that draw on that [`Texture`] must also
573 /// include the [`SurfaceTexture`] in the `surface_textures` argument.
574 ///
575 /// When you are done drawing on the texture, you can display it on `self`
576 /// by passing the [`SurfaceTexture`] and `self` to [`Queue::present`].
577 ///
578 /// If you do not wish to display the texture, you must pass the
579 /// [`SurfaceTexture`] to [`self.discard_texture`], so that it can be reused
580 /// by future acquisitions.
581 ///
582 /// # Portability
583 ///
584 /// Some backends can't support a timeout when acquiring a texture. On these
585 /// backends, `timeout` is ignored.
586 ///
587 /// # Safety
588 ///
589 /// - The surface `self` must currently be configured on some [`Device`].
590 ///
591 /// - The `fence` argument must be the same [`Fence`] passed to all calls to
592 /// [`Queue::submit`] that used [`Texture`]s acquired from this surface.
593 ///
594 /// - You may only have one texture acquired from `self` at a time. When
595 /// `acquire_texture` returns `Ok(Some(ast))`, you must pass the returned
596 /// [`SurfaceTexture`] `ast.texture` to either [`Queue::present`] or
597 /// [`Surface::discard_texture`] before calling `acquire_texture` again.
598 ///
599 /// [`texture`]: AcquiredSurfaceTexture::texture
600 /// [`SurfaceTexture`]: Api::SurfaceTexture
601 /// [`borrow`]: alloc::borrow::Borrow::borrow
602 /// [`Texture`]: Api::Texture
603 /// [`Fence`]: Api::Fence
604 /// [`self.discard_texture`]: Surface::discard_texture
605 unsafe fn acquire_texture(
606 &self,
607 timeout: Option<core::time::Duration>,
608 fence: &<Self::A as Api>::Fence,
609 ) -> Result<Option<AcquiredSurfaceTexture<Self::A>>, SurfaceError>;
610
611 /// Relinquish an acquired texture without presenting it.
612 ///
613 /// After this call, the texture underlying [`SurfaceTexture`] may be
614 /// returned by subsequent calls to [`self.acquire_texture`].
615 ///
616 /// # Safety
617 ///
618 /// - The surface `self` must currently be configured on some [`Device`].
619 ///
620 /// - `texture` must be a [`SurfaceTexture`] returned by a call to
621 /// [`self.acquire_texture`] that has not yet been passed to
622 /// [`Queue::present`].
623 ///
624 /// [`SurfaceTexture`]: Api::SurfaceTexture
625 /// [`self.acquire_texture`]: Surface::acquire_texture
626 unsafe fn discard_texture(&self, texture: <Self::A as Api>::SurfaceTexture);
627 }
628
629 pub trait Adapter: WasmNotSendSync {
630 type A: Api;
631
632 unsafe fn open(
633 &self,
634 features: wgt::Features,
635 limits: &wgt::Limits,
636 memory_hints: &wgt::MemoryHints,
637 ) -> Result<OpenDevice<Self::A>, DeviceError>;
638
639 /// Return the set of supported capabilities for a texture format.
640 unsafe fn texture_format_capabilities(
641 &self,
642 format: wgt::TextureFormat,
643 ) -> TextureFormatCapabilities;
644
645 /// Returns the capabilities of working with a specified surface.
646 ///
647 /// `None` means presentation is not supported for it.
648 unsafe fn surface_capabilities(
649 &self,
650 surface: &<Self::A as Api>::Surface,
651 ) -> Option<SurfaceCapabilities>;
652
653 /// Creates a [`PresentationTimestamp`] using the adapter's WSI.
654 ///
655 /// [`PresentationTimestamp`]: wgt::PresentationTimestamp
656 unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp;
657 }
658
659 /// A connection to a GPU and a pool of resources to use with it.
660 ///
661 /// A `wgpu-hal` `Device` represents an open connection to a specific graphics
662 /// processor, controlled via the backend [`Device::A`]. A `Device` is mostly
663 /// used for creating resources. Each `Device` has an associated [`Queue`] used
664 /// for command submission.
665 ///
666 /// On Vulkan a `Device` corresponds to a logical device ([`VkDevice`]). Other
667 /// backends don't have an exact analog: for example, [`ID3D12Device`]s and
668 /// [`MTLDevice`]s are owned by the backends' [`wgpu_hal::Adapter`]
669 /// implementations, and shared by all [`wgpu_hal::Device`]s created from that
670 /// `Adapter`.
671 ///
672 /// A `Device`'s life cycle is generally:
673 ///
674 /// 1) Obtain a `Device` and its associated [`Queue`] by calling
675 /// [`Adapter::open`].
676 ///
677 /// Alternatively, the backend-specific types that implement [`Adapter`] often
678 /// have methods for creating a `wgpu-hal` `Device` from a platform-specific
679 /// handle. For example, [`vulkan::Adapter::device_from_raw`] can create a
680 /// [`vulkan::Device`] from an [`ash::Device`].
681 ///
682 /// 1) Create resources to use on the device by calling methods like
683 /// [`Device::create_texture`] or [`Device::create_shader_module`].
684 ///
685 /// 1) Call [`Device::create_command_encoder`] to obtain a [`CommandEncoder`],
686 /// which you can use to build [`CommandBuffer`]s holding commands to be
687 /// executed on the GPU.
688 ///
689 /// 1) Call [`Queue::submit`] on the `Device`'s associated [`Queue`] to submit
690 /// [`CommandBuffer`]s for execution on the GPU. If needed, call
691 /// [`Device::wait`] to wait for them to finish execution.
692 ///
693 /// 1) Free resources with methods like [`Device::destroy_texture`] or
694 /// [`Device::destroy_shader_module`].
695 ///
696 /// 1) Drop the device.
697 ///
698 /// [`vkDevice`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkDevice
699 /// [`ID3D12Device`]: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12device
700 /// [`MTLDevice`]: https://developer.apple.com/documentation/metal/mtldevice
701 /// [`wgpu_hal::Adapter`]: Adapter
702 /// [`wgpu_hal::Device`]: Device
703 /// [`vulkan::Adapter::device_from_raw`]: vulkan/struct.Adapter.html#method.device_from_raw
704 /// [`vulkan::Device`]: vulkan/struct.Device.html
705 /// [`ash::Device`]: https://docs.rs/ash/latest/ash/struct.Device.html
706 /// [`CommandBuffer`]: Api::CommandBuffer
707 ///
708 /// # Safety
709 ///
710 /// As with other `wgpu-hal` APIs, [validation] is the caller's
711 /// responsibility. Here are the general requirements for all `Device`
712 /// methods:
713 ///
714 /// - Any resource passed to a `Device` method must have been created by that
715 /// `Device`. For example, a [`Texture`] passed to [`Device::destroy_texture`] must
716 /// have been created with the `Device` passed as `self`.
717 ///
718 /// - Resources may not be destroyed if they are used by any submitted command
719 /// buffers that have not yet finished execution.
720 ///
721 /// [validation]: index.html#validation-is-the-calling-codes-responsibility-not-wgpu-hals
722 /// [`Texture`]: Api::Texture
723 pub trait Device: WasmNotSendSync {
724 type A: Api;
725
726 /// Creates a new buffer.
727 ///
728 /// The initial usage is `wgt::BufferUses::empty()`.
729 unsafe fn create_buffer(
730 &self,
731 desc: &BufferDescriptor,
732 ) -> Result<<Self::A as Api>::Buffer, DeviceError>;
733
734 /// Free `buffer` and any GPU resources it owns.
735 ///
736 /// Note that backends are allowed to allocate GPU memory for buffers from
737 /// allocation pools, and this call is permitted to simply return `buffer`'s
738 /// storage to that pool, without making it available to other applications.
739 ///
740 /// # Safety
741 ///
742 /// - The given `buffer` must not currently be mapped.
743 unsafe fn destroy_buffer(&self, buffer: <Self::A as Api>::Buffer);
744
745 /// A hook for when a wgpu-core buffer is created from a raw wgpu-hal buffer.
746 unsafe fn add_raw_buffer(&self, buffer: &<Self::A as Api>::Buffer);
747
748 /// Return a pointer to CPU memory mapping the contents of `buffer`.
749 ///
750 /// Buffer mappings are persistent: the buffer may remain mapped on the CPU
751 /// while the GPU reads or writes to it. (Note that `wgpu_core` does not use
752 /// this feature: when a `wgpu_core::Buffer` is unmapped, the underlying
753 /// `wgpu_hal` buffer is also unmapped.)
754 ///
755 /// If this function returns `Ok(mapping)`, then:
756 ///
757 /// - `mapping.ptr` is the CPU address of the start of the mapped memory.
758 ///
759 /// - If `mapping.is_coherent` is `true`, then CPU writes to the mapped
760 /// memory are immediately visible on the GPU, and vice versa.
761 ///
762 /// # Safety
763 ///
764 /// - The given `buffer` must have been created with the [`MAP_READ`] or
765 /// [`MAP_WRITE`] flags set in [`BufferDescriptor::usage`].
766 ///
767 /// - The given `range` must fall within the size of `buffer`.
768 ///
769 /// - The caller must avoid data races between the CPU and the GPU. A data
770 /// race is any pair of accesses to a particular byte, one of which is a
771 /// write, that are not ordered with respect to each other by some sort of
772 /// synchronization operation.
773 ///
774 /// - If this function returns `Ok(mapping)` and `mapping.is_coherent` is
775 /// `false`, then:
776 ///
777 /// - Every CPU write to a mapped byte followed by a GPU read of that byte
778 /// must have at least one call to [`Device::flush_mapped_ranges`]
779 /// covering that byte that occurs between those two accesses.
780 ///
781 /// - Every GPU write to a mapped byte followed by a CPU read of that byte
782 /// must have at least one call to [`Device::invalidate_mapped_ranges`]
783 /// covering that byte that occurs between those two accesses.
784 ///
785 /// Note that the data race rule above requires that all such access pairs
786 /// be ordered, so it is meaningful to talk about what must occur
787 /// "between" them.
788 ///
789 /// - Zero-sized mappings are not allowed.
790 ///
791 /// - The returned [`BufferMapping::ptr`] must not be used after a call to
792 /// [`Device::unmap_buffer`].
793 ///
794 /// [`MAP_READ`]: wgt::BufferUses::MAP_READ
795 /// [`MAP_WRITE`]: wgt::BufferUses::MAP_WRITE
796 unsafe fn map_buffer(
797 &self,
798 buffer: &<Self::A as Api>::Buffer,
799 range: MemoryRange,
800 ) -> Result<BufferMapping, DeviceError>;
801
802 /// Remove the mapping established by the last call to [`Device::map_buffer`].
803 ///
804 /// # Safety
805 ///
806 /// - The given `buffer` must be currently mapped.
807 unsafe fn unmap_buffer(&self, buffer: &<Self::A as Api>::Buffer);
808
809 /// Indicate that CPU writes to mapped buffer memory should be made visible to the GPU.
810 ///
811 /// # Safety
812 ///
813 /// - The given `buffer` must be currently mapped.
814 ///
815 /// - All ranges produced by `ranges` must fall within `buffer`'s size.
816 unsafe fn flush_mapped_ranges<I>(&self, buffer: &<Self::A as Api>::Buffer, ranges: I)
817 where
818 I: Iterator<Item = MemoryRange>;
819
820 /// Indicate that GPU writes to mapped buffer memory should be made visible to the CPU.
821 ///
822 /// # Safety
823 ///
824 /// - The given `buffer` must be currently mapped.
825 ///
826 /// - All ranges produced by `ranges` must fall within `buffer`'s size.
827 unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &<Self::A as Api>::Buffer, ranges: I)
828 where
829 I: Iterator<Item = MemoryRange>;
830
831 /// Creates a new texture.
832 ///
833 /// The initial usage for all subresources is `wgt::TextureUses::UNINITIALIZED`.
834 unsafe fn create_texture(
835 &self,
836 desc: &TextureDescriptor,
837 ) -> Result<<Self::A as Api>::Texture, DeviceError>;
838 unsafe fn destroy_texture(&self, texture: <Self::A as Api>::Texture);
839
840 /// A hook for when a wgpu-core texture is created from a raw wgpu-hal texture.
841 unsafe fn add_raw_texture(&self, texture: &<Self::A as Api>::Texture);
842
843 unsafe fn create_texture_view(
844 &self,
845 texture: &<Self::A as Api>::Texture,
846 desc: &TextureViewDescriptor,
847 ) -> Result<<Self::A as Api>::TextureView, DeviceError>;
848 unsafe fn destroy_texture_view(&self, view: <Self::A as Api>::TextureView);
849 unsafe fn create_sampler(
850 &self,
851 desc: &SamplerDescriptor,
852 ) -> Result<<Self::A as Api>::Sampler, DeviceError>;
853 unsafe fn destroy_sampler(&self, sampler: <Self::A as Api>::Sampler);
854
855 /// Create a fresh [`CommandEncoder`].
856 ///
857 /// The new `CommandEncoder` is in the "closed" state.
858 unsafe fn create_command_encoder(
859 &self,
860 desc: &CommandEncoderDescriptor<<Self::A as Api>::Queue>,
861 ) -> Result<<Self::A as Api>::CommandEncoder, DeviceError>;
862
863 /// Creates a bind group layout.
864 unsafe fn create_bind_group_layout(
865 &self,
866 desc: &BindGroupLayoutDescriptor,
867 ) -> Result<<Self::A as Api>::BindGroupLayout, DeviceError>;
868 unsafe fn destroy_bind_group_layout(&self, bg_layout: <Self::A as Api>::BindGroupLayout);
869 unsafe fn create_pipeline_layout(
870 &self,
871 desc: &PipelineLayoutDescriptor<<Self::A as Api>::BindGroupLayout>,
872 ) -> Result<<Self::A as Api>::PipelineLayout, DeviceError>;
873 unsafe fn destroy_pipeline_layout(&self, pipeline_layout: <Self::A as Api>::PipelineLayout);
874
875 #[allow(clippy::type_complexity)]
876 unsafe fn create_bind_group(
877 &self,
878 desc: &BindGroupDescriptor<
879 <Self::A as Api>::BindGroupLayout,
880 <Self::A as Api>::Buffer,
881 <Self::A as Api>::Sampler,
882 <Self::A as Api>::TextureView,
883 <Self::A as Api>::AccelerationStructure,
884 >,
885 ) -> Result<<Self::A as Api>::BindGroup, DeviceError>;
886 unsafe fn destroy_bind_group(&self, group: <Self::A as Api>::BindGroup);
887
888 unsafe fn create_shader_module(
889 &self,
890 desc: &ShaderModuleDescriptor,
891 shader: ShaderInput,
892 ) -> Result<<Self::A as Api>::ShaderModule, ShaderError>;
893 unsafe fn destroy_shader_module(&self, module: <Self::A as Api>::ShaderModule);
894
895 #[allow(clippy::type_complexity)]
896 unsafe fn create_render_pipeline(
897 &self,
898 desc: &RenderPipelineDescriptor<
899 <Self::A as Api>::PipelineLayout,
900 <Self::A as Api>::ShaderModule,
901 <Self::A as Api>::PipelineCache,
902 >,
903 ) -> Result<<Self::A as Api>::RenderPipeline, PipelineError>;
904 #[allow(clippy::type_complexity)]
905 unsafe fn create_mesh_pipeline(
906 &self,
907 desc: &MeshPipelineDescriptor<
908 <Self::A as Api>::PipelineLayout,
909 <Self::A as Api>::ShaderModule,
910 <Self::A as Api>::PipelineCache,
911 >,
912 ) -> Result<<Self::A as Api>::RenderPipeline, PipelineError>;
913 unsafe fn destroy_render_pipeline(&self, pipeline: <Self::A as Api>::RenderPipeline);
914
915 #[allow(clippy::type_complexity)]
916 unsafe fn create_compute_pipeline(
917 &self,
918 desc: &ComputePipelineDescriptor<
919 <Self::A as Api>::PipelineLayout,
920 <Self::A as Api>::ShaderModule,
921 <Self::A as Api>::PipelineCache,
922 >,
923 ) -> Result<<Self::A as Api>::ComputePipeline, PipelineError>;
924 unsafe fn destroy_compute_pipeline(&self, pipeline: <Self::A as Api>::ComputePipeline);
925
926 unsafe fn create_pipeline_cache(
927 &self,
928 desc: &PipelineCacheDescriptor<'_>,
929 ) -> Result<<Self::A as Api>::PipelineCache, PipelineCacheError>;
930 fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> {
931 None
932 }
933 unsafe fn destroy_pipeline_cache(&self, cache: <Self::A as Api>::PipelineCache);
934
935 unsafe fn create_query_set(
936 &self,
937 desc: &wgt::QuerySetDescriptor<Label>,
938 ) -> Result<<Self::A as Api>::QuerySet, DeviceError>;
939 unsafe fn destroy_query_set(&self, set: <Self::A as Api>::QuerySet);
940 unsafe fn create_fence(&self) -> Result<<Self::A as Api>::Fence, DeviceError>;
941 unsafe fn destroy_fence(&self, fence: <Self::A as Api>::Fence);
942 unsafe fn get_fence_value(
943 &self,
944 fence: &<Self::A as Api>::Fence,
945 ) -> Result<FenceValue, DeviceError>;
946
947 /// Wait for `fence` to reach `value`.
948 ///
949 /// Operations like [`Queue::submit`] can accept a [`Fence`] and a
950 /// [`FenceValue`] to store in it, so you can use this `wait` function
951 /// to wait for a given queue submission to finish execution.
952 ///
953 /// The `value` argument must be a value that some actual operation you have
954 /// already presented to the device is going to store in `fence`. You cannot
955 /// wait for values yet to be submitted. (This restriction accommodates
956 /// implementations like the `vulkan` backend's [`FencePool`] that must
957 /// allocate a distinct synchronization object for each fence value one is
958 /// able to wait for.)
959 ///
960 /// Calling `wait` with a lower [`FenceValue`] than `fence`'s current value
961 /// returns immediately.
962 ///
963 /// Returns `Ok(true)` on success and `Ok(false)` on timeout.
964 ///
965 /// [`Fence`]: Api::Fence
966 /// [`FencePool`]: vulkan/enum.Fence.html#variant.FencePool
967 unsafe fn wait(
968 &self,
969 fence: &<Self::A as Api>::Fence,
970 value: FenceValue,
971 timeout_ms: u32,
972 ) -> Result<bool, DeviceError>;
973
974 /// Start a graphics debugger capture.
975 ///
976 /// # Safety
977 ///
978 /// See [`wgpu::Device::start_graphics_debugger_capture`][api] for more details.
979 ///
980 /// [api]: ../wgpu/struct.Device.html#method.start_graphics_debugger_capture
981 unsafe fn start_graphics_debugger_capture(&self) -> bool;
982
983 /// Stop a graphics debugger capture.
984 ///
985 /// # Safety
986 ///
987 /// See [`wgpu::Device::stop_graphics_debugger_capture`][api] for more details.
988 ///
989 /// [api]: ../wgpu/struct.Device.html#method.stop_graphics_debugger_capture
990 unsafe fn stop_graphics_debugger_capture(&self);
991
992 #[allow(unused_variables)]
993 unsafe fn pipeline_cache_get_data(
994 &self,
995 cache: &<Self::A as Api>::PipelineCache,
996 ) -> Option<Vec<u8>> {
997 None
998 }
999
1000 unsafe fn create_acceleration_structure(
1001 &self,
1002 desc: &AccelerationStructureDescriptor,
1003 ) -> Result<<Self::A as Api>::AccelerationStructure, DeviceError>;
1004 unsafe fn get_acceleration_structure_build_sizes(
1005 &self,
1006 desc: &GetAccelerationStructureBuildSizesDescriptor<<Self::A as Api>::Buffer>,
1007 ) -> AccelerationStructureBuildSizes;
1008 unsafe fn get_acceleration_structure_device_address(
1009 &self,
1010 acceleration_structure: &<Self::A as Api>::AccelerationStructure,
1011 ) -> wgt::BufferAddress;
1012 unsafe fn destroy_acceleration_structure(
1013 &self,
1014 acceleration_structure: <Self::A as Api>::AccelerationStructure,
1015 );
1016 fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8>;
1017
1018 fn get_internal_counters(&self) -> wgt::HalCounters;
1019
1020 fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
1021 None
1022 }
1023
1024 fn check_if_oom(&self) -> Result<(), DeviceError>;
1025 }
1026
1027 pub trait Queue: WasmNotSendSync {
1028 type A: Api;
1029
1030 /// Submit `command_buffers` for execution on GPU.
1031 ///
1032 /// Update `fence` to `value` when the operation is complete. See
1033 /// [`Fence`] for details.
1034 ///
1035 /// A `wgpu_hal` queue is "single threaded": all command buffers are
1036 /// executed in the order they're submitted, with each buffer able to see
1037 /// previous buffers' results. Specifically:
1038 ///
1039 /// - If two calls to `submit` on a single `Queue` occur in a particular
1040 /// order (that is, they happen on the same thread, or on two threads that
1041 /// have synchronized to establish an ordering), then the first
1042 /// submission's commands all complete execution before any of the second
1043 /// submission's commands begin. All results produced by one submission
1044 /// are visible to the next.
1045 ///
1046 /// - Within a submission, command buffers execute in the order in which they
1047 /// appear in `command_buffers`. All results produced by one buffer are
1048 /// visible to the next.
1049 ///
1050 /// If two calls to `submit` on a single `Queue` from different threads are
1051 /// not synchronized to occur in a particular order, they must pass distinct
1052 /// [`Fence`]s. As explained in the [`Fence`] documentation, waiting for
1053 /// operations to complete is only trustworthy when operations finish in
1054 /// order of increasing fence value, but submissions from different threads
1055 /// cannot determine how to order the fence values if the submissions
1056 /// themselves are unordered. If each thread uses a separate [`Fence`], this
1057 /// problem does not arise.
1058 ///
1059 /// # Safety
1060 ///
1061 /// - Each [`CommandBuffer`][cb] in `command_buffers` must have been created
1062 /// from a [`CommandEncoder`][ce] that was constructed from the
1063 /// [`Device`][d] associated with this [`Queue`].
1064 ///
1065 /// - Each [`CommandBuffer`][cb] must remain alive until the submitted
1066 /// commands have finished execution. Since command buffers must not
1067 /// outlive their encoders, this implies that the encoders must remain
1068 /// alive as well.
1069 ///
1070 /// - All resources used by a submitted [`CommandBuffer`][cb]
1071 /// ([`Texture`][t]s, [`BindGroup`][bg]s, [`RenderPipeline`][rp]s, and so
1072 /// on) must remain alive until the command buffer finishes execution.
1073 ///
1074 /// - Every [`SurfaceTexture`][st] that any command in `command_buffers`
1075 /// writes to must appear in the `surface_textures` argument.
1076 ///
1077 /// - No [`SurfaceTexture`][st] may appear in the `surface_textures`
1078 /// argument more than once.
1079 ///
1080 /// - Each [`SurfaceTexture`][st] in `surface_textures` must be configured
1081 /// for use with the [`Device`][d] associated with this [`Queue`],
1082 /// typically by calling [`Surface::configure`].
1083 ///
1084 /// - All calls to this function that include a given [`SurfaceTexture`][st]
1085 /// in `surface_textures` must use the same [`Fence`].
1086 ///
1087 /// - The [`Fence`] passed as `signal_fence.0` must remain alive until
1088 /// all submissions that will signal it have completed.
1089 ///
1090 /// [`Fence`]: Api::Fence
1091 /// [cb]: Api::CommandBuffer
1092 /// [ce]: Api::CommandEncoder
1093 /// [d]: Api::Device
1094 /// [t]: Api::Texture
1095 /// [bg]: Api::BindGroup
1096 /// [rp]: Api::RenderPipeline
1097 /// [st]: Api::SurfaceTexture
1098 unsafe fn submit(
1099 &self,
1100 command_buffers: &[&<Self::A as Api>::CommandBuffer],
1101 surface_textures: &[&<Self::A as Api>::SurfaceTexture],
1102 signal_fence: (&mut <Self::A as Api>::Fence, FenceValue),
1103 ) -> Result<(), DeviceError>;
1104 unsafe fn present(
1105 &self,
1106 surface: &<Self::A as Api>::Surface,
1107 texture: <Self::A as Api>::SurfaceTexture,
1108 ) -> Result<(), SurfaceError>;
1109 unsafe fn get_timestamp_period(&self) -> f32;
1110 }
1111
1112 /// Encoder and allocation pool for `CommandBuffer`s.
1113 ///
1114 /// A `CommandEncoder` not only constructs `CommandBuffer`s but also
1115 /// acts as the allocation pool that owns the buffers' underlying
1116 /// storage. Thus, `CommandBuffer`s must not outlive the
1117 /// `CommandEncoder` that created them.
1118 ///
1119 /// The life cycle of a `CommandBuffer` is as follows:
1120 ///
1121 /// - Call [`Device::create_command_encoder`] to create a new
1122 /// `CommandEncoder`, in the "closed" state.
1123 ///
1124 /// - Call `begin_encoding` on a closed `CommandEncoder` to begin
1125 /// recording commands. This puts the `CommandEncoder` in the
1126 /// "recording" state.
1127 ///
1128 /// - Call methods like `copy_buffer_to_buffer`, `begin_render_pass`,
1129 /// etc. on a "recording" `CommandEncoder` to add commands to the
1130 /// list. (If an error occurs, you must call `discard_encoding`; see
1131 /// below.)
1132 ///
1133 /// - Call `end_encoding` on a recording `CommandEncoder` to close the
1134 /// encoder and construct a fresh `CommandBuffer` consisting of the
1135 /// list of commands recorded up to that point.
1136 ///
1137 /// - Call `discard_encoding` on a recording `CommandEncoder` to drop
1138 /// the commands recorded thus far and close the encoder. This is
1139 /// the only safe thing to do on a `CommandEncoder` if an error has
1140 /// occurred while recording commands.
1141 ///
1142 /// - Call `reset_all` on a closed `CommandEncoder`, passing all the
1143 /// live `CommandBuffers` built from it. All the `CommandBuffer`s
1144 /// are destroyed, and their resources are freed.
1145 ///
1146 /// # Safety
1147 ///
1148 /// - The `CommandEncoder` must be in the states described above to
1149 /// make the given calls.
1150 ///
1151 /// - A `CommandBuffer` that has been submitted for execution on the
1152 /// GPU must live until its execution is complete.
1153 ///
1154 /// - A `CommandBuffer` must not outlive the `CommandEncoder` that
1155 /// built it.
1156 ///
1157 /// It is the user's responsibility to meet this requirements. This
1158 /// allows `CommandEncoder` implementations to keep their state
1159 /// tracking to a minimum.
1160 pub trait CommandEncoder: WasmNotSendSync + fmt::Debug {
1161 type A: Api;
1162
1163 /// Begin encoding a new command buffer.
1164 ///
1165 /// This puts this `CommandEncoder` in the "recording" state.
1166 ///
1167 /// # Safety
1168 ///
1169 /// This `CommandEncoder` must be in the "closed" state.
1170 unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError>;
1171
1172 /// Discard the command list under construction.
1173 ///
1174 /// If an error has occurred while recording commands, this
1175 /// is the only safe thing to do with the encoder.
1176 ///
1177 /// This puts this `CommandEncoder` in the "closed" state.
1178 ///
1179 /// # Safety
1180 ///
1181 /// This `CommandEncoder` must be in the "recording" state.
1182 ///
1183 /// Callers must not assume that implementations of this
1184 /// function are idempotent, and thus should not call it
1185 /// multiple times in a row.
1186 unsafe fn discard_encoding(&mut self);
1187
1188 /// Return a fresh [`CommandBuffer`] holding the recorded commands.
1189 ///
1190 /// The returned [`CommandBuffer`] holds all the commands recorded
1191 /// on this `CommandEncoder` since the last call to
1192 /// [`begin_encoding`].
1193 ///
1194 /// This puts this `CommandEncoder` in the "closed" state.
1195 ///
1196 /// # Safety
1197 ///
1198 /// This `CommandEncoder` must be in the "recording" state.
1199 ///
1200 /// The returned [`CommandBuffer`] must not outlive this
1201 /// `CommandEncoder`. Implementations are allowed to build
1202 /// `CommandBuffer`s that depend on storage owned by this
1203 /// `CommandEncoder`.
1204 ///
1205 /// [`CommandBuffer`]: Api::CommandBuffer
1206 /// [`begin_encoding`]: CommandEncoder::begin_encoding
1207 unsafe fn end_encoding(&mut self) -> Result<<Self::A as Api>::CommandBuffer, DeviceError>;
1208
1209 /// Reclaim all resources belonging to this `CommandEncoder`.
1210 ///
1211 /// # Safety
1212 ///
1213 /// This `CommandEncoder` must be in the "closed" state.
1214 ///
1215 /// The `command_buffers` iterator must produce all the live
1216 /// [`CommandBuffer`]s built using this `CommandEncoder` --- that
1217 /// is, every extant `CommandBuffer` returned from `end_encoding`.
1218 ///
1219 /// [`CommandBuffer`]: Api::CommandBuffer
1220 unsafe fn reset_all<I>(&mut self, command_buffers: I)
1221 where
1222 I: Iterator<Item = <Self::A as Api>::CommandBuffer>;
1223
1224 unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
1225 where
1226 T: Iterator<Item = BufferBarrier<'a, <Self::A as Api>::Buffer>>;
1227
1228 unsafe fn transition_textures<'a, T>(&mut self, barriers: T)
1229 where
1230 T: Iterator<Item = TextureBarrier<'a, <Self::A as Api>::Texture>>;
1231
1232 // copy operations
1233
1234 unsafe fn clear_buffer(&mut self, buffer: &<Self::A as Api>::Buffer, range: MemoryRange);
1235
1236 unsafe fn copy_buffer_to_buffer<T>(
1237 &mut self,
1238 src: &<Self::A as Api>::Buffer,
1239 dst: &<Self::A as Api>::Buffer,
1240 regions: T,
1241 ) where
1242 T: Iterator<Item = BufferCopy>;
1243
1244 /// Copy from an external image to an internal texture.
1245 /// Works with a single array layer.
1246 /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1247 /// Note: the copy extent is in physical size (rounded to the block size)
1248 #[cfg(webgl)]
1249 unsafe fn copy_external_image_to_texture<T>(
1250 &mut self,
1251 src: &wgt::CopyExternalImageSourceInfo,
1252 dst: &<Self::A as Api>::Texture,
1253 dst_premultiplication: bool,
1254 regions: T,
1255 ) where
1256 T: Iterator<Item = TextureCopy>;
1257
1258 /// Copy from one texture to another.
1259 /// Works with a single array layer.
1260 /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1261 /// Note: the copy extent is in physical size (rounded to the block size)
1262 unsafe fn copy_texture_to_texture<T>(
1263 &mut self,
1264 src: &<Self::A as Api>::Texture,
1265 src_usage: wgt::TextureUses,
1266 dst: &<Self::A as Api>::Texture,
1267 regions: T,
1268 ) where
1269 T: Iterator<Item = TextureCopy>;
1270
1271 /// Copy from buffer to texture.
1272 /// Works with a single array layer.
1273 /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1274 /// Note: the copy extent is in physical size (rounded to the block size)
1275 unsafe fn copy_buffer_to_texture<T>(
1276 &mut self,
1277 src: &<Self::A as Api>::Buffer,
1278 dst: &<Self::A as Api>::Texture,
1279 regions: T,
1280 ) where
1281 T: Iterator<Item = BufferTextureCopy>;
1282
1283 /// Copy from texture to buffer.
1284 /// Works with a single array layer.
1285 /// Note: the copy extent is in physical size (rounded to the block size)
1286 unsafe fn copy_texture_to_buffer<T>(
1287 &mut self,
1288 src: &<Self::A as Api>::Texture,
1289 src_usage: wgt::TextureUses,
1290 dst: &<Self::A as Api>::Buffer,
1291 regions: T,
1292 ) where
1293 T: Iterator<Item = BufferTextureCopy>;
1294
1295 unsafe fn copy_acceleration_structure_to_acceleration_structure(
1296 &mut self,
1297 src: &<Self::A as Api>::AccelerationStructure,
1298 dst: &<Self::A as Api>::AccelerationStructure,
1299 copy: wgt::AccelerationStructureCopy,
1300 );
1301 // pass common
1302
1303 /// Sets the bind group at `index` to `group`.
1304 ///
1305 /// If this is not the first call to `set_bind_group` within the current
1306 /// render or compute pass:
1307 ///
1308 /// - If `layout` contains `n` bind group layouts, then any previously set
1309 /// bind groups at indices `n` or higher are cleared.
1310 ///
1311 /// - If the first `m` bind group layouts of `layout` are equal to those of
1312 /// the previously passed layout, but no more, then any previously set
1313 /// bind groups at indices `m` or higher are cleared.
1314 ///
1315 /// It follows from the above that passing the same layout as before doesn't
1316 /// clear any bind groups.
1317 ///
1318 /// # Safety
1319 ///
1320 /// - This [`CommandEncoder`] must be within a render or compute pass.
1321 ///
1322 /// - `index` must be the valid index of some bind group layout in `layout`.
1323 /// Call this the "relevant bind group layout".
1324 ///
1325 /// - The layout of `group` must be equal to the relevant bind group layout.
1326 ///
1327 /// - The length of `dynamic_offsets` must match the number of buffer
1328 /// bindings [with dynamic offsets][hdo] in the relevant bind group
1329 /// layout.
1330 ///
1331 /// - If those buffer bindings are ordered by increasing [`binding` number]
1332 /// and paired with elements from `dynamic_offsets`, then each offset must
1333 /// be a valid offset for the binding's corresponding buffer in `group`.
1334 ///
1335 /// [hdo]: wgt::BindingType::Buffer::has_dynamic_offset
1336 /// [`binding` number]: wgt::BindGroupLayoutEntry::binding
1337 unsafe fn set_bind_group(
1338 &mut self,
1339 layout: &<Self::A as Api>::PipelineLayout,
1340 index: u32,
1341 group: &<Self::A as Api>::BindGroup,
1342 dynamic_offsets: &[wgt::DynamicOffset],
1343 );
1344
1345 /// Sets a range in push constant data.
1346 ///
1347 /// IMPORTANT: while the data is passed as words, the offset is in bytes!
1348 ///
1349 /// # Safety
1350 ///
1351 /// - `offset_bytes` must be a multiple of 4.
1352 /// - The range of push constants written must be valid for the pipeline layout at draw time.
1353 unsafe fn set_push_constants(
1354 &mut self,
1355 layout: &<Self::A as Api>::PipelineLayout,
1356 stages: wgt::ShaderStages,
1357 offset_bytes: u32,
1358 data: &[u32],
1359 );
1360
1361 unsafe fn insert_debug_marker(&mut self, label: &str);
1362 unsafe fn begin_debug_marker(&mut self, group_label: &str);
1363 unsafe fn end_debug_marker(&mut self);
1364
1365 // queries
1366
1367 /// # Safety:
1368 ///
1369 /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter.
1370 unsafe fn begin_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1371 /// # Safety:
1372 ///
1373 /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter.
1374 unsafe fn end_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1375 unsafe fn write_timestamp(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1376 unsafe fn reset_queries(&mut self, set: &<Self::A as Api>::QuerySet, range: Range<u32>);
1377 unsafe fn copy_query_results(
1378 &mut self,
1379 set: &<Self::A as Api>::QuerySet,
1380 range: Range<u32>,
1381 buffer: &<Self::A as Api>::Buffer,
1382 offset: wgt::BufferAddress,
1383 stride: wgt::BufferSize,
1384 );
1385
1386 // render passes
1387
1388 /// Begin a new render pass, clearing all active bindings.
1389 ///
1390 /// This clears any bindings established by the following calls:
1391 ///
1392 /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1393 /// - [`set_push_constants`](CommandEncoder::set_push_constants)
1394 /// - [`begin_query`](CommandEncoder::begin_query)
1395 /// - [`set_render_pipeline`](CommandEncoder::set_render_pipeline)
1396 /// - [`set_index_buffer`](CommandEncoder::set_index_buffer)
1397 /// - [`set_vertex_buffer`](CommandEncoder::set_vertex_buffer)
1398 ///
1399 /// # Safety
1400 ///
1401 /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1402 /// by a call to [`end_render_pass`].
1403 ///
1404 /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1405 /// by a call to [`end_compute_pass`].
1406 ///
1407 /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1408 /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1409 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1410 /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1411 unsafe fn begin_render_pass(
1412 &mut self,
1413 desc: &RenderPassDescriptor<<Self::A as Api>::QuerySet, <Self::A as Api>::TextureView>,
1414 ) -> Result<(), DeviceError>;
1415
1416 /// End the current render pass.
1417 ///
1418 /// # Safety
1419 ///
1420 /// - There must have been a prior call to [`begin_render_pass`] on this [`CommandEncoder`]
1421 /// that has not been followed by a call to [`end_render_pass`].
1422 ///
1423 /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1424 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1425 unsafe fn end_render_pass(&mut self);
1426
1427 unsafe fn set_render_pipeline(&mut self, pipeline: &<Self::A as Api>::RenderPipeline);
1428
1429 unsafe fn set_index_buffer<'a>(
1430 &mut self,
1431 binding: BufferBinding<'a, <Self::A as Api>::Buffer>,
1432 format: wgt::IndexFormat,
1433 );
1434 unsafe fn set_vertex_buffer<'a>(
1435 &mut self,
1436 index: u32,
1437 binding: BufferBinding<'a, <Self::A as Api>::Buffer>,
1438 );
1439 unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>);
1440 unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>);
1441 unsafe fn set_stencil_reference(&mut self, value: u32);
1442 unsafe fn set_blend_constants(&mut self, color: &[f32; 4]);
1443
1444 unsafe fn draw(
1445 &mut self,
1446 first_vertex: u32,
1447 vertex_count: u32,
1448 first_instance: u32,
1449 instance_count: u32,
1450 );
1451 unsafe fn draw_indexed(
1452 &mut self,
1453 first_index: u32,
1454 index_count: u32,
1455 base_vertex: i32,
1456 first_instance: u32,
1457 instance_count: u32,
1458 );
1459 unsafe fn draw_indirect(
1460 &mut self,
1461 buffer: &<Self::A as Api>::Buffer,
1462 offset: wgt::BufferAddress,
1463 draw_count: u32,
1464 );
1465 unsafe fn draw_indexed_indirect(
1466 &mut self,
1467 buffer: &<Self::A as Api>::Buffer,
1468 offset: wgt::BufferAddress,
1469 draw_count: u32,
1470 );
1471 unsafe fn draw_indirect_count(
1472 &mut self,
1473 buffer: &<Self::A as Api>::Buffer,
1474 offset: wgt::BufferAddress,
1475 count_buffer: &<Self::A as Api>::Buffer,
1476 count_offset: wgt::BufferAddress,
1477 max_count: u32,
1478 );
1479 unsafe fn draw_indexed_indirect_count(
1480 &mut self,
1481 buffer: &<Self::A as Api>::Buffer,
1482 offset: wgt::BufferAddress,
1483 count_buffer: &<Self::A as Api>::Buffer,
1484 count_offset: wgt::BufferAddress,
1485 max_count: u32,
1486 );
1487 unsafe fn draw_mesh_tasks(
1488 &mut self,
1489 group_count_x: u32,
1490 group_count_y: u32,
1491 group_count_z: u32,
1492 );
1493 unsafe fn draw_mesh_tasks_indirect(
1494 &mut self,
1495 buffer: &<Self::A as Api>::Buffer,
1496 offset: wgt::BufferAddress,
1497 draw_count: u32,
1498 );
1499 unsafe fn draw_mesh_tasks_indirect_count(
1500 &mut self,
1501 buffer: &<Self::A as Api>::Buffer,
1502 offset: wgt::BufferAddress,
1503 count_buffer: &<Self::A as Api>::Buffer,
1504 count_offset: wgt::BufferAddress,
1505 max_count: u32,
1506 );
1507
1508 // compute passes
1509
1510 /// Begin a new compute pass, clearing all active bindings.
1511 ///
1512 /// This clears any bindings established by the following calls:
1513 ///
1514 /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1515 /// - [`set_push_constants`](CommandEncoder::set_push_constants)
1516 /// - [`begin_query`](CommandEncoder::begin_query)
1517 /// - [`set_compute_pipeline`](CommandEncoder::set_compute_pipeline)
1518 ///
1519 /// # Safety
1520 ///
1521 /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1522 /// by a call to [`end_render_pass`].
1523 ///
1524 /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1525 /// by a call to [`end_compute_pass`].
1526 ///
1527 /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1528 /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1529 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1530 /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1531 unsafe fn begin_compute_pass(
1532 &mut self,
1533 desc: &ComputePassDescriptor<<Self::A as Api>::QuerySet>,
1534 );
1535
1536 /// End the current compute pass.
1537 ///
1538 /// # Safety
1539 ///
1540 /// - There must have been a prior call to [`begin_compute_pass`] on this [`CommandEncoder`]
1541 /// that has not been followed by a call to [`end_compute_pass`].
1542 ///
1543 /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1544 /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1545 unsafe fn end_compute_pass(&mut self);
1546
1547 unsafe fn set_compute_pipeline(&mut self, pipeline: &<Self::A as Api>::ComputePipeline);
1548
1549 unsafe fn dispatch(&mut self, count: [u32; 3]);
1550 unsafe fn dispatch_indirect(
1551 &mut self,
1552 buffer: &<Self::A as Api>::Buffer,
1553 offset: wgt::BufferAddress,
1554 );
1555
1556 /// To get the required sizes for the buffer allocations use `get_acceleration_structure_build_sizes` per descriptor
1557 /// All buffers must be synchronized externally
1558 /// All buffer regions, which are written to may only be passed once per function call,
1559 /// with the exception of updates in the same descriptor.
1560 /// Consequences of this limitation:
1561 /// - scratch buffers need to be unique
1562 /// - a tlas can't be build in the same call with a blas it contains
1563 unsafe fn build_acceleration_structures<'a, T>(
1564 &mut self,
1565 descriptor_count: u32,
1566 descriptors: T,
1567 ) where
1568 Self::A: 'a,
1569 T: IntoIterator<
1570 Item = BuildAccelerationStructureDescriptor<
1571 'a,
1572 <Self::A as Api>::Buffer,
1573 <Self::A as Api>::AccelerationStructure,
1574 >,
1575 >;
1576
1577 unsafe fn place_acceleration_structure_barrier(
1578 &mut self,
1579 barrier: AccelerationStructureBarrier,
1580 );
1581 // modeled off dx12, because this is able to be polyfilled in vulkan as opposed to the other way round
1582 unsafe fn read_acceleration_structure_compact_size(
1583 &mut self,
1584 acceleration_structure: &<Self::A as Api>::AccelerationStructure,
1585 buf: &<Self::A as Api>::Buffer,
1586 );
1587 }
1588
1589 bitflags!(
1590 /// Pipeline layout creation flags.
1591 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1592 pub struct PipelineLayoutFlags: u32 {
1593 /// D3D12: Add support for `first_vertex` and `first_instance` builtins
1594 /// via push constants for direct execution.
1595 const FIRST_VERTEX_INSTANCE = 1 << 0;
1596 /// D3D12: Add support for `num_workgroups` builtins via push constants
1597 /// for direct execution.
1598 const NUM_WORK_GROUPS = 1 << 1;
1599 /// D3D12: Add support for the builtins that the other flags enable for
1600 /// indirect execution.
1601 const INDIRECT_BUILTIN_UPDATE = 1 << 2;
1602 }
1603 );
1604
1605 bitflags!(
1606 /// Pipeline layout creation flags.
1607 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1608 pub struct BindGroupLayoutFlags: u32 {
1609 /// Allows for bind group binding arrays to be shorter than the array in the BGL.
1610 const PARTIALLY_BOUND = 1 << 0;
1611 }
1612 );
1613
1614 bitflags!(
1615 /// Texture format capability flags.
1616 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1617 pub struct TextureFormatCapabilities: u32 {
1618 /// Format can be sampled.
1619 const SAMPLED = 1 << 0;
1620 /// Format can be sampled with a linear sampler.
1621 const SAMPLED_LINEAR = 1 << 1;
1622 /// Format can be sampled with a min/max reduction sampler.
1623 const SAMPLED_MINMAX = 1 << 2;
1624
1625 /// Format can be used as storage with read-only access.
1626 const STORAGE_READ_ONLY = 1 << 3;
1627 /// Format can be used as storage with write-only access.
1628 const STORAGE_WRITE_ONLY = 1 << 4;
1629 /// Format can be used as storage with both read and write access.
1630 const STORAGE_READ_WRITE = 1 << 5;
1631 /// Format can be used as storage with atomics.
1632 const STORAGE_ATOMIC = 1 << 6;
1633
1634 /// Format can be used as color and input attachment.
1635 const COLOR_ATTACHMENT = 1 << 7;
1636 /// Format can be used as color (with blending) and input attachment.
1637 const COLOR_ATTACHMENT_BLEND = 1 << 8;
1638 /// Format can be used as depth-stencil and input attachment.
1639 const DEPTH_STENCIL_ATTACHMENT = 1 << 9;
1640
1641 /// Format can be multisampled by x2.
1642 const MULTISAMPLE_X2 = 1 << 10;
1643 /// Format can be multisampled by x4.
1644 const MULTISAMPLE_X4 = 1 << 11;
1645 /// Format can be multisampled by x8.
1646 const MULTISAMPLE_X8 = 1 << 12;
1647 /// Format can be multisampled by x16.
1648 const MULTISAMPLE_X16 = 1 << 13;
1649
1650 /// Format can be used for render pass resolve targets.
1651 const MULTISAMPLE_RESOLVE = 1 << 14;
1652
1653 /// Format can be copied from.
1654 const COPY_SRC = 1 << 15;
1655 /// Format can be copied to.
1656 const COPY_DST = 1 << 16;
1657 }
1658 );
1659
1660 bitflags!(
1661 /// Texture format capability flags.
1662 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1663 pub struct FormatAspects: u8 {
1664 const COLOR = 1 << 0;
1665 const DEPTH = 1 << 1;
1666 const STENCIL = 1 << 2;
1667 const PLANE_0 = 1 << 3;
1668 const PLANE_1 = 1 << 4;
1669 const PLANE_2 = 1 << 5;
1670
1671 const DEPTH_STENCIL = Self::DEPTH.bits() | Self::STENCIL.bits();
1672 }
1673 );
1674
1675 impl FormatAspects {
1676 pub fn new(format: wgt::TextureFormat, aspect: wgt::TextureAspect) -> Self {
1677 let aspect_mask = match aspect {
1678 wgt::TextureAspect::All => Self::all(),
1679 wgt::TextureAspect::DepthOnly => Self::DEPTH,
1680 wgt::TextureAspect::StencilOnly => Self::STENCIL,
1681 wgt::TextureAspect::Plane0 => Self::PLANE_0,
1682 wgt::TextureAspect::Plane1 => Self::PLANE_1,
1683 wgt::TextureAspect::Plane2 => Self::PLANE_2,
1684 };
1685 Self::from(format) & aspect_mask
1686 }
1687
1688 /// Returns `true` if only one flag is set
1689 pub fn is_one(&self) -> bool {
1690 self.bits().is_power_of_two()
1691 }
1692
1693 pub fn map(&self) -> wgt::TextureAspect {
1694 match *self {
1695 Self::COLOR => wgt::TextureAspect::All,
1696 Self::DEPTH => wgt::TextureAspect::DepthOnly,
1697 Self::STENCIL => wgt::TextureAspect::StencilOnly,
1698 Self::PLANE_0 => wgt::TextureAspect::Plane0,
1699 Self::PLANE_1 => wgt::TextureAspect::Plane1,
1700 Self::PLANE_2 => wgt::TextureAspect::Plane2,
1701 _ => unreachable!(),
1702 }
1703 }
1704 }
1705
1706 impl From<wgt::TextureFormat> for FormatAspects {
1707 fn from(format: wgt::TextureFormat) -> Self {
1708 match format {
1709 wgt::TextureFormat::Stencil8 => Self::STENCIL,
1710 wgt::TextureFormat::Depth16Unorm
1711 | wgt::TextureFormat::Depth32Float
1712 | wgt::TextureFormat::Depth24Plus => Self::DEPTH,
1713 wgt::TextureFormat::Depth32FloatStencil8 | wgt::TextureFormat::Depth24PlusStencil8 => {
1714 Self::DEPTH_STENCIL
1715 }
1716 wgt::TextureFormat::NV12 => Self::PLANE_0 | Self::PLANE_1,
1717 _ => Self::COLOR,
1718 }
1719 }
1720 }
1721
1722 bitflags!(
1723 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1724 pub struct MemoryFlags: u32 {
1725 const TRANSIENT = 1 << 0;
1726 const PREFER_COHERENT = 1 << 1;
1727 }
1728 );
1729
1730 //TODO: it's not intuitive for the backends to consider `LOAD` being optional.
1731
1732 bitflags!(
1733 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1734 pub struct AttachmentOps: u8 {
1735 const LOAD = 1 << 0;
1736 const STORE = 1 << 1;
1737 }
1738 );
1739
1740 #[derive(Clone, Debug)]
1741 pub struct InstanceDescriptor<'a> {
1742 pub name: &'a str,
1743 pub flags: wgt::InstanceFlags,
1744 pub memory_budget_thresholds: wgt::MemoryBudgetThresholds,
1745 pub backend_options: wgt::BackendOptions,
1746 }
1747
1748 #[derive(Clone, Debug)]
1749 pub struct Alignments {
1750 /// The alignment of the start of the buffer used as a GPU copy source.
1751 pub buffer_copy_offset: wgt::BufferSize,
1752
1753 /// The alignment of the row pitch of the texture data stored in a buffer that is
1754 /// used in a GPU copy operation.
1755 pub buffer_copy_pitch: wgt::BufferSize,
1756
1757 /// The finest alignment of bound range checking for uniform buffers.
1758 ///
1759 /// When `wgpu_hal` restricts shader references to the [accessible
1760 /// region][ar] of a [`Uniform`] buffer, the size of the accessible region
1761 /// is the bind group binding's stated [size], rounded up to the next
1762 /// multiple of this value.
1763 ///
1764 /// We don't need an analogous field for storage buffer bindings, because
1765 /// all our backends promise to enforce the size at least to a four-byte
1766 /// alignment, and `wgpu_hal` requires bound range lengths to be a multiple
1767 /// of four anyway.
1768 ///
1769 /// [ar]: struct.BufferBinding.html#accessible-region
1770 /// [`Uniform`]: wgt::BufferBindingType::Uniform
1771 /// [size]: BufferBinding::size
1772 pub uniform_bounds_check_alignment: wgt::BufferSize,
1773
1774 /// The size of the raw TLAS instance
1775 pub raw_tlas_instance_size: usize,
1776
1777 /// What the scratch buffer for building an acceleration structure must be aligned to
1778 pub ray_tracing_scratch_buffer_alignment: u32,
1779 }
1780
1781 #[derive(Clone, Debug)]
1782 pub struct Capabilities {
1783 pub limits: wgt::Limits,
1784 pub alignments: Alignments,
1785 pub downlevel: wgt::DownlevelCapabilities,
1786 }
1787
1788 #[derive(Debug)]
1789 pub struct ExposedAdapter<A: Api> {
1790 pub adapter: A::Adapter,
1791 pub info: wgt::AdapterInfo,
1792 pub features: wgt::Features,
1793 pub capabilities: Capabilities,
1794 }
1795
1796 /// Describes information about what a `Surface`'s presentation capabilities are.
1797 /// Fetch this with [Adapter::surface_capabilities].
1798 #[derive(Debug, Clone)]
1799 pub struct SurfaceCapabilities {
1800 /// List of supported texture formats.
1801 ///
1802 /// Must be at least one.
1803 pub formats: Vec<wgt::TextureFormat>,
1804
1805 /// Range for the number of queued frames.
1806 ///
1807 /// This adjusts either the swapchain frame count to value + 1 - or sets SetMaximumFrameLatency to the value given,
1808 /// or uses a wait-for-present in the acquire method to limit rendering such that it acts like it's a value + 1 swapchain frame set.
1809 ///
1810 /// - `maximum_frame_latency.start` must be at least 1.
1811 /// - `maximum_frame_latency.end` must be larger or equal to `maximum_frame_latency.start`.
1812 pub maximum_frame_latency: RangeInclusive<u32>,
1813
1814 /// Current extent of the surface, if known.
1815 pub current_extent: Option<wgt::Extent3d>,
1816
1817 /// Supported texture usage flags.
1818 ///
1819 /// Must have at least `wgt::TextureUses::COLOR_TARGET`
1820 pub usage: wgt::TextureUses,
1821
1822 /// List of supported V-sync modes.
1823 ///
1824 /// Must be at least one.
1825 pub present_modes: Vec<wgt::PresentMode>,
1826
1827 /// List of supported alpha composition modes.
1828 ///
1829 /// Must be at least one.
1830 pub composite_alpha_modes: Vec<wgt::CompositeAlphaMode>,
1831 }
1832
1833 #[derive(Debug)]
1834 pub struct AcquiredSurfaceTexture<A: Api> {
1835 pub texture: A::SurfaceTexture,
1836 /// The presentation configuration no longer matches
1837 /// the surface properties exactly, but can still be used to present
1838 /// to the surface successfully.
1839 pub suboptimal: bool,
1840 }
1841
1842 #[derive(Debug)]
1843 pub struct OpenDevice<A: Api> {
1844 pub device: A::Device,
1845 pub queue: A::Queue,
1846 }
1847
1848 #[derive(Clone, Debug)]
1849 pub struct BufferMapping {
1850 pub ptr: NonNull<u8>,
1851 pub is_coherent: bool,
1852 }
1853
1854 #[derive(Clone, Debug)]
1855 pub struct BufferDescriptor<'a> {
1856 pub label: Label<'a>,
1857 pub size: wgt::BufferAddress,
1858 pub usage: wgt::BufferUses,
1859 pub memory_flags: MemoryFlags,
1860 }
1861
1862 #[derive(Clone, Debug)]
1863 pub struct TextureDescriptor<'a> {
1864 pub label: Label<'a>,
1865 pub size: wgt::Extent3d,
1866 pub mip_level_count: u32,
1867 pub sample_count: u32,
1868 pub dimension: wgt::TextureDimension,
1869 pub format: wgt::TextureFormat,
1870 pub usage: wgt::TextureUses,
1871 pub memory_flags: MemoryFlags,
1872 /// Allows views of this texture to have a different format
1873 /// than the texture does.
1874 pub view_formats: Vec<wgt::TextureFormat>,
1875 }
1876
1877 impl TextureDescriptor<'_> {
1878 pub fn copy_extent(&self) -> CopyExtent {
1879 CopyExtent::map_extent_to_copy_size(&self.size, self.dimension)
1880 }
1881
1882 pub fn is_cube_compatible(&self) -> bool {
1883 self.dimension == wgt::TextureDimension::D2
1884 && self.size.depth_or_array_layers % 6 == 0
1885 && self.sample_count == 1
1886 && self.size.width == self.size.height
1887 }
1888
1889 pub fn array_layer_count(&self) -> u32 {
1890 match self.dimension {
1891 wgt::TextureDimension::D1 | wgt::TextureDimension::D3 => 1,
1892 wgt::TextureDimension::D2 => self.size.depth_or_array_layers,
1893 }
1894 }
1895 }
1896
1897 /// TextureView descriptor.
1898 ///
1899 /// Valid usage:
1900 ///. - `format` has to be the same as `TextureDescriptor::format`
1901 ///. - `dimension` has to be compatible with `TextureDescriptor::dimension`
1902 ///. - `usage` has to be a subset of `TextureDescriptor::usage`
1903 ///. - `range` has to be a subset of parent texture
1904 #[derive(Clone, Debug)]
1905 pub struct TextureViewDescriptor<'a> {
1906 pub label: Label<'a>,
1907 pub format: wgt::TextureFormat,
1908 pub dimension: wgt::TextureViewDimension,
1909 pub usage: wgt::TextureUses,
1910 pub range: wgt::ImageSubresourceRange,
1911 }
1912
1913 #[derive(Clone, Debug)]
1914 pub struct SamplerDescriptor<'a> {
1915 pub label: Label<'a>,
1916 pub address_modes: [wgt::AddressMode; 3],
1917 pub mag_filter: wgt::FilterMode,
1918 pub min_filter: wgt::FilterMode,
1919 pub mipmap_filter: wgt::FilterMode,
1920 pub lod_clamp: Range<f32>,
1921 pub compare: Option<wgt::CompareFunction>,
1922 // Must in the range [1, 16].
1923 //
1924 // Anisotropic filtering must be supported if this is not 1.
1925 pub anisotropy_clamp: u16,
1926 pub border_color: Option<wgt::SamplerBorderColor>,
1927 }
1928
1929 /// BindGroupLayout descriptor.
1930 ///
1931 /// Valid usage:
1932 /// - `entries` are sorted by ascending `wgt::BindGroupLayoutEntry::binding`
1933 #[derive(Clone, Debug)]
1934 pub struct BindGroupLayoutDescriptor<'a> {
1935 pub label: Label<'a>,
1936 pub flags: BindGroupLayoutFlags,
1937 pub entries: &'a [wgt::BindGroupLayoutEntry],
1938 }
1939
1940 #[derive(Clone, Debug)]
1941 pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> {
1942 pub label: Label<'a>,
1943 pub flags: PipelineLayoutFlags,
1944 pub bind_group_layouts: &'a [&'a B],
1945 pub push_constant_ranges: &'a [wgt::PushConstantRange],
1946 }
1947
1948 /// A region of a buffer made visible to shaders via a [`BindGroup`].
1949 ///
1950 /// [`BindGroup`]: Api::BindGroup
1951 ///
1952 /// ## Accessible region
1953 ///
1954 /// `wgpu_hal` guarantees that shaders compiled with
1955 /// [`ShaderModuleDescriptor::runtime_checks`] set to `true` cannot read or
1956 /// write data via this binding outside the *accessible region* of [`buffer`]:
1957 ///
1958 /// - The accessible region starts at [`offset`].
1959 ///
1960 /// - For [`Storage`] bindings, the size of the accessible region is [`size`],
1961 /// which must be a multiple of 4.
1962 ///
1963 /// - For [`Uniform`] bindings, the size of the accessible region is [`size`]
1964 /// rounded up to the next multiple of
1965 /// [`Alignments::uniform_bounds_check_alignment`].
1966 ///
1967 /// Note that this guarantee is stricter than WGSL's requirements for
1968 /// [out-of-bounds accesses][woob], as WGSL allows them to return values from
1969 /// elsewhere in the buffer. But this guarantee is necessary anyway, to permit
1970 /// `wgpu-core` to avoid clearing uninitialized regions of buffers that will
1971 /// never be read by the application before they are overwritten. This
1972 /// optimization consults bind group buffer binding regions to determine which
1973 /// parts of which buffers shaders might observe. This optimization is only
1974 /// sound if shader access is bounds-checked.
1975 ///
1976 /// [`buffer`]: BufferBinding::buffer
1977 /// [`offset`]: BufferBinding::offset
1978 /// [`size`]: BufferBinding::size
1979 /// [`Storage`]: wgt::BufferBindingType::Storage
1980 /// [`Uniform`]: wgt::BufferBindingType::Uniform
1981 /// [woob]: https://gpuweb.github.io/gpuweb/wgsl/#out-of-bounds-access-sec
1982 #[derive(Debug)]
1983 pub struct BufferBinding<'a, B: DynBuffer + ?Sized> {
1984 /// The buffer being bound.
1985 pub buffer: &'a B,
1986
1987 /// The offset at which the bound region starts.
1988 ///
1989 /// This must be less than the size of the buffer. Some back ends
1990 /// cannot tolerate zero-length regions; for example, see
1991 /// [VUID-VkDescriptorBufferInfo-offset-00340][340] and
1992 /// [VUID-VkDescriptorBufferInfo-range-00341][341], or the
1993 /// documentation for GLES's [glBindBufferRange][bbr].
1994 ///
1995 /// [340]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-offset-00340
1996 /// [341]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-range-00341
1997 /// [bbr]: https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glBindBufferRange.xhtml
1998 pub offset: wgt::BufferAddress,
1999
2000 /// The size of the region bound, in bytes.
2001 ///
2002 /// If `None`, the region extends from `offset` to the end of the
2003 /// buffer. Given the restrictions on `offset`, this means that
2004 /// the size is always greater than zero.
2005 pub size: Option<wgt::BufferSize>,
2006 }
2007
2008 impl<'a, T: DynBuffer + ?Sized> Clone for BufferBinding<'a, T> {
2009 fn clone(&self) -> Self {
2010 BufferBinding {
2011 buffer: self.buffer,
2012 offset: self.offset,
2013 size: self.size,
2014 }
2015 }
2016 }
2017
2018 #[derive(Debug)]
2019 pub struct TextureBinding<'a, T: DynTextureView + ?Sized> {
2020 pub view: &'a T,
2021 pub usage: wgt::TextureUses,
2022 }
2023
2024 impl<'a, T: DynTextureView + ?Sized> Clone for TextureBinding<'a, T> {
2025 fn clone(&self) -> Self {
2026 TextureBinding {
2027 view: self.view,
2028 usage: self.usage,
2029 }
2030 }
2031 }
2032
2033 /// cbindgen:ignore
2034 #[derive(Clone, Debug)]
2035 pub struct BindGroupEntry {
2036 pub binding: u32,
2037 pub resource_index: u32,
2038 pub count: u32,
2039 }
2040
2041 /// BindGroup descriptor.
2042 ///
2043 /// Valid usage:
2044 ///. - `entries` has to be sorted by ascending `BindGroupEntry::binding`
2045 ///. - `entries` has to have the same set of `BindGroupEntry::binding` as `layout`
2046 ///. - each entry has to be compatible with the `layout`
2047 ///. - each entry's `BindGroupEntry::resource_index` is within range
2048 /// of the corresponding resource array, selected by the relevant
2049 /// `BindGroupLayoutEntry`.
2050 #[derive(Clone, Debug)]
2051 pub struct BindGroupDescriptor<
2052 'a,
2053 Bgl: DynBindGroupLayout + ?Sized,
2054 B: DynBuffer + ?Sized,
2055 S: DynSampler + ?Sized,
2056 T: DynTextureView + ?Sized,
2057 A: DynAccelerationStructure + ?Sized,
2058 > {
2059 pub label: Label<'a>,
2060 pub layout: &'a Bgl,
2061 pub buffers: &'a [BufferBinding<'a, B>],
2062 pub samplers: &'a [&'a S],
2063 pub textures: &'a [TextureBinding<'a, T>],
2064 pub entries: &'a [BindGroupEntry],
2065 pub acceleration_structures: &'a [&'a A],
2066 }
2067
2068 #[derive(Clone, Debug)]
2069 pub struct CommandEncoderDescriptor<'a, Q: DynQueue + ?Sized> {
2070 pub label: Label<'a>,
2071 pub queue: &'a Q,
2072 }
2073
2074 /// Naga shader module.
2075 #[derive(Default)]
2076 pub struct NagaShader {
2077 /// Shader module IR.
2078 pub module: Cow<'static, naga::Module>,
2079 /// Analysis information of the module.
2080 pub info: naga::valid::ModuleInfo,
2081 /// Source codes for debug
2082 pub debug_source: Option<DebugSource>,
2083 }
2084
2085 // Custom implementation avoids the need to generate Debug impl code
2086 // for the whole Naga module and info.
2087 impl fmt::Debug for NagaShader {
2088 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2089 write!(formatter, "Naga shader")
2090 }
2091 }
2092
2093 /// Shader input.
2094 #[allow(clippy::large_enum_variant)]
2095 pub enum ShaderInput<'a> {
2096 Naga(NagaShader),
2097 Msl {
2098 shader: String,
2099 entry_point: String,
2100 num_workgroups: (u32, u32, u32),
2101 },
2102 SpirV(&'a [u32]),
2103 }
2104
2105 pub struct ShaderModuleDescriptor<'a> {
2106 pub label: Label<'a>,
2107
2108 /// # Safety
2109 ///
2110 /// See the documentation for each flag in [`ShaderRuntimeChecks`][src].
2111 ///
2112 /// [src]: wgt::ShaderRuntimeChecks
2113 pub runtime_checks: wgt::ShaderRuntimeChecks,
2114 }
2115
2116 #[derive(Debug, Clone)]
2117 pub struct DebugSource {
2118 pub file_name: Cow<'static, str>,
2119 pub source_code: Cow<'static, str>,
2120 }
2121
2122 /// Describes a programmable pipeline stage.
2123 #[derive(Debug)]
2124 pub struct ProgrammableStage<'a, M: DynShaderModule + ?Sized> {
2125 /// The compiled shader module for this stage.
2126 pub module: &'a M,
2127 /// The name of the entry point in the compiled shader. There must be a function with this name
2128 /// in the shader.
2129 pub entry_point: &'a str,
2130 /// Pipeline constants
2131 pub constants: &'a naga::back::PipelineConstants,
2132 /// Whether workgroup scoped memory will be initialized with zero values for this stage.
2133 ///
2134 /// This is required by the WebGPU spec, but may have overhead which can be avoided
2135 /// for cross-platform applications
2136 pub zero_initialize_workgroup_memory: bool,
2137 }
2138
2139 impl<M: DynShaderModule + ?Sized> Clone for ProgrammableStage<'_, M> {
2140 fn clone(&self) -> Self {
2141 Self {
2142 module: self.module,
2143 entry_point: self.entry_point,
2144 constants: self.constants,
2145 zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory,
2146 }
2147 }
2148 }
2149
2150 /// Describes a compute pipeline.
2151 #[derive(Clone, Debug)]
2152 pub struct ComputePipelineDescriptor<
2153 'a,
2154 Pl: DynPipelineLayout + ?Sized,
2155 M: DynShaderModule + ?Sized,
2156 Pc: DynPipelineCache + ?Sized,
2157 > {
2158 pub label: Label<'a>,
2159 /// The layout of bind groups for this pipeline.
2160 pub layout: &'a Pl,
2161 /// The compiled compute stage and its entry point.
2162 pub stage: ProgrammableStage<'a, M>,
2163 /// The cache which will be used and filled when compiling this pipeline
2164 pub cache: Option<&'a Pc>,
2165 }
2166
2167 pub struct PipelineCacheDescriptor<'a> {
2168 pub label: Label<'a>,
2169 pub data: Option<&'a [u8]>,
2170 }
2171
2172 /// Describes how the vertex buffer is interpreted.
2173 #[derive(Clone, Debug)]
2174 pub struct VertexBufferLayout<'a> {
2175 /// The stride, in bytes, between elements of this buffer.
2176 pub array_stride: wgt::BufferAddress,
2177 /// How often this vertex buffer is "stepped" forward.
2178 pub step_mode: wgt::VertexStepMode,
2179 /// The list of attributes which comprise a single vertex.
2180 pub attributes: &'a [wgt::VertexAttribute],
2181 }
2182
2183 /// Describes a render (graphics) pipeline.
2184 #[derive(Clone, Debug)]
2185 pub struct RenderPipelineDescriptor<
2186 'a,
2187 Pl: DynPipelineLayout + ?Sized,
2188 M: DynShaderModule + ?Sized,
2189 Pc: DynPipelineCache + ?Sized,
2190 > {
2191 pub label: Label<'a>,
2192 /// The layout of bind groups for this pipeline.
2193 pub layout: &'a Pl,
2194 /// The format of any vertex buffers used with this pipeline.
2195 pub vertex_buffers: &'a [VertexBufferLayout<'a>],
2196 /// The vertex stage for this pipeline.
2197 pub vertex_stage: ProgrammableStage<'a, M>,
2198 /// The properties of the pipeline at the primitive assembly and rasterization level.
2199 pub primitive: wgt::PrimitiveState,
2200 /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
2201 pub depth_stencil: Option<wgt::DepthStencilState>,
2202 /// The multi-sampling properties of the pipeline.
2203 pub multisample: wgt::MultisampleState,
2204 /// The fragment stage for this pipeline.
2205 pub fragment_stage: Option<ProgrammableStage<'a, M>>,
2206 /// The effect of draw calls on the color aspect of the output target.
2207 pub color_targets: &'a [Option<wgt::ColorTargetState>],
2208 /// If the pipeline will be used with a multiview render pass, this indicates how many array
2209 /// layers the attachments will have.
2210 pub multiview: Option<NonZeroU32>,
2211 /// The cache which will be used and filled when compiling this pipeline
2212 pub cache: Option<&'a Pc>,
2213 }
2214 pub struct MeshPipelineDescriptor<
2215 'a,
2216 Pl: DynPipelineLayout + ?Sized,
2217 M: DynShaderModule + ?Sized,
2218 Pc: DynPipelineCache + ?Sized,
2219 > {
2220 pub label: Label<'a>,
2221 /// The layout of bind groups for this pipeline.
2222 pub layout: &'a Pl,
2223 pub task_stage: Option<ProgrammableStage<'a, M>>,
2224 pub mesh_stage: ProgrammableStage<'a, M>,
2225 /// The properties of the pipeline at the primitive assembly and rasterization level.
2226 pub primitive: wgt::PrimitiveState,
2227 /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
2228 pub depth_stencil: Option<wgt::DepthStencilState>,
2229 /// The multi-sampling properties of the pipeline.
2230 pub multisample: wgt::MultisampleState,
2231 /// The fragment stage for this pipeline.
2232 pub fragment_stage: Option<ProgrammableStage<'a, M>>,
2233 /// The effect of draw calls on the color aspect of the output target.
2234 pub color_targets: &'a [Option<wgt::ColorTargetState>],
2235 /// If the pipeline will be used with a multiview render pass, this indicates how many array
2236 /// layers the attachments will have.
2237 pub multiview: Option<NonZeroU32>,
2238 /// The cache which will be used and filled when compiling this pipeline
2239 pub cache: Option<&'a Pc>,
2240 }
2241
2242 #[derive(Debug, Clone)]
2243 pub struct SurfaceConfiguration {
2244 /// Maximum number of queued frames. Must be in
2245 /// `SurfaceCapabilities::maximum_frame_latency` range.
2246 pub maximum_frame_latency: u32,
2247 /// Vertical synchronization mode.
2248 pub present_mode: wgt::PresentMode,
2249 /// Alpha composition mode.
2250 pub composite_alpha_mode: wgt::CompositeAlphaMode,
2251 /// Format of the surface textures.
2252 pub format: wgt::TextureFormat,
2253 /// Requested texture extent. Must be in
2254 /// `SurfaceCapabilities::extents` range.
2255 pub extent: wgt::Extent3d,
2256 /// Allowed usage of surface textures,
2257 pub usage: wgt::TextureUses,
2258 /// Allows views of swapchain texture to have a different format
2259 /// than the texture does.
2260 pub view_formats: Vec<wgt::TextureFormat>,
2261 }
2262
2263 #[derive(Debug, Clone)]
2264 pub struct Rect<T> {
2265 pub x: T,
2266 pub y: T,
2267 pub w: T,
2268 pub h: T,
2269 }
2270
2271 #[derive(Debug, Clone, PartialEq)]
2272 pub struct StateTransition<T> {
2273 pub from: T,
2274 pub to: T,
2275 }
2276
2277 #[derive(Debug, Clone)]
2278 pub struct BufferBarrier<'a, B: DynBuffer + ?Sized> {
2279 pub buffer: &'a B,
2280 pub usage: StateTransition<wgt::BufferUses>,
2281 }
2282
2283 #[derive(Debug, Clone)]
2284 pub struct TextureBarrier<'a, T: DynTexture + ?Sized> {
2285 pub texture: &'a T,
2286 pub range: wgt::ImageSubresourceRange,
2287 pub usage: StateTransition<wgt::TextureUses>,
2288 }
2289
2290 #[derive(Clone, Copy, Debug)]
2291 pub struct BufferCopy {
2292 pub src_offset: wgt::BufferAddress,
2293 pub dst_offset: wgt::BufferAddress,
2294 pub size: wgt::BufferSize,
2295 }
2296
2297 #[derive(Clone, Debug)]
2298 pub struct TextureCopyBase {
2299 pub mip_level: u32,
2300 pub array_layer: u32,
2301 /// Origin within a texture.
2302 /// Note: for 1D and 2D textures, Z must be 0.
2303 pub origin: wgt::Origin3d,
2304 pub aspect: FormatAspects,
2305 }
2306
2307 #[derive(Clone, Copy, Debug)]
2308 pub struct CopyExtent {
2309 pub width: u32,
2310 pub height: u32,
2311 pub depth: u32,
2312 }
2313
2314 #[derive(Clone, Debug)]
2315 pub struct TextureCopy {
2316 pub src_base: TextureCopyBase,
2317 pub dst_base: TextureCopyBase,
2318 pub size: CopyExtent,
2319 }
2320
2321 #[derive(Clone, Debug)]
2322 pub struct BufferTextureCopy {
2323 pub buffer_layout: wgt::TexelCopyBufferLayout,
2324 pub texture_base: TextureCopyBase,
2325 pub size: CopyExtent,
2326 }
2327
2328 #[derive(Clone, Debug)]
2329 pub struct Attachment<'a, T: DynTextureView + ?Sized> {
2330 pub view: &'a T,
2331 /// Contains either a single mutating usage as a target,
2332 /// or a valid combination of read-only usages.
2333 pub usage: wgt::TextureUses,
2334 }
2335
2336 #[derive(Clone, Debug)]
2337 pub struct ColorAttachment<'a, T: DynTextureView + ?Sized> {
2338 pub target: Attachment<'a, T>,
2339 pub depth_slice: Option<u32>,
2340 pub resolve_target: Option<Attachment<'a, T>>,
2341 pub ops: AttachmentOps,
2342 pub clear_value: wgt::Color,
2343 }
2344
2345 #[derive(Clone, Debug)]
2346 pub struct DepthStencilAttachment<'a, T: DynTextureView + ?Sized> {
2347 pub target: Attachment<'a, T>,
2348 pub depth_ops: AttachmentOps,
2349 pub stencil_ops: AttachmentOps,
2350 pub clear_value: (f32, u32),
2351 }
2352
2353 #[derive(Clone, Debug)]
2354 pub struct PassTimestampWrites<'a, Q: DynQuerySet + ?Sized> {
2355 pub query_set: &'a Q,
2356 pub beginning_of_pass_write_index: Option<u32>,
2357 pub end_of_pass_write_index: Option<u32>,
2358 }
2359
2360 #[derive(Clone, Debug)]
2361 pub struct RenderPassDescriptor<'a, Q: DynQuerySet + ?Sized, T: DynTextureView + ?Sized> {
2362 pub label: Label<'a>,
2363 pub extent: wgt::Extent3d,
2364 pub sample_count: u32,
2365 pub color_attachments: &'a [Option<ColorAttachment<'a, T>>],
2366 pub depth_stencil_attachment: Option<DepthStencilAttachment<'a, T>>,
2367 pub multiview: Option<NonZeroU32>,
2368 pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>,
2369 pub occlusion_query_set: Option<&'a Q>,
2370 }
2371
2372 #[derive(Clone, Debug)]
2373 pub struct ComputePassDescriptor<'a, Q: DynQuerySet + ?Sized> {
2374 pub label: Label<'a>,
2375 pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>,
2376 }
2377
2378 /// Stores the text of any validation errors that have occurred since
2379 /// the last call to `get_and_reset`.
2380 ///
2381 /// Each value is a validation error and a message associated with it,
2382 /// or `None` if the error has no message from the api.
2383 ///
2384 /// This is used for internal wgpu testing only and _must not_ be used
2385 /// as a way to check for errors.
2386 ///
2387 /// This works as a static because `cargo nextest` runs all of our
2388 /// tests in separate processes, so each test gets its own canary.
2389 ///
2390 /// This prevents the issue of one validation error terminating the
2391 /// entire process.
2392 pub static VALIDATION_CANARY: ValidationCanary = ValidationCanary {
2393 inner: Mutex::new(Vec::new()),
2394 };
2395
2396 /// Flag for internal testing.
2397 pub struct ValidationCanary {
2398 inner: Mutex<Vec<String>>,
2399 }
2400
2401 impl ValidationCanary {
2402 #[allow(dead_code)] // in some configurations this function is dead
2403 fn add(&self, msg: String) {
2404 self.inner.lock().push(msg);
2405 }
2406
2407 /// Returns any API validation errors that have occurred in this process
2408 /// since the last call to this function.
2409 pub fn get_and_reset(&self) -> Vec<String> {
2410 self.inner.lock().drain(..).collect()
2411 }
2412 }
2413
2414 #[test]
2415 fn test_default_limits() {
2416 let limits = wgt::Limits::default();
2417 assert!(limits.max_bind_groups <= MAX_BIND_GROUPS as u32);
2418 }
2419
2420 #[derive(Clone, Debug)]
2421 pub struct AccelerationStructureDescriptor<'a> {
2422 pub label: Label<'a>,
2423 pub size: wgt::BufferAddress,
2424 pub format: AccelerationStructureFormat,
2425 pub allow_compaction: bool,
2426 }
2427
2428 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
2429 pub enum AccelerationStructureFormat {
2430 TopLevel,
2431 BottomLevel,
2432 }
2433
2434 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
2435 pub enum AccelerationStructureBuildMode {
2436 Build,
2437 Update,
2438 }
2439
2440 /// Information of the required size for a corresponding entries struct (+ flags)
2441 #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
2442 pub struct AccelerationStructureBuildSizes {
2443 pub acceleration_structure_size: wgt::BufferAddress,
2444 pub update_scratch_size: wgt::BufferAddress,
2445 pub build_scratch_size: wgt::BufferAddress,
2446 }
2447
2448 /// Updates use source_acceleration_structure if present, else the update will be performed in place.
2449 /// For updates, only the data is allowed to change (not the meta data or sizes).
2450 #[derive(Clone, Debug)]
2451 pub struct BuildAccelerationStructureDescriptor<
2452 'a,
2453 B: DynBuffer + ?Sized,
2454 A: DynAccelerationStructure + ?Sized,
2455 > {
2456 pub entries: &'a AccelerationStructureEntries<'a, B>,
2457 pub mode: AccelerationStructureBuildMode,
2458 pub flags: AccelerationStructureBuildFlags,
2459 pub source_acceleration_structure: Option<&'a A>,
2460 pub destination_acceleration_structure: &'a A,
2461 pub scratch_buffer: &'a B,
2462 pub scratch_buffer_offset: wgt::BufferAddress,
2463 }
2464
2465 /// - All buffers, buffer addresses and offsets will be ignored.
2466 /// - The build mode will be ignored.
2467 /// - Reducing the amount of Instances, Triangle groups or AABB groups (or the number of Triangles/AABBs in corresponding groups),
2468 /// may result in reduced size requirements.
2469 /// - Any other change may result in a bigger or smaller size requirement.
2470 #[derive(Clone, Debug)]
2471 pub struct GetAccelerationStructureBuildSizesDescriptor<'a, B: DynBuffer + ?Sized> {
2472 pub entries: &'a AccelerationStructureEntries<'a, B>,
2473 pub flags: AccelerationStructureBuildFlags,
2474 }
2475
2476 /// Entries for a single descriptor
2477 /// * `Instances` - Multiple instances for a top level acceleration structure
2478 /// * `Triangles` - Multiple triangle meshes for a bottom level acceleration structure
2479 /// * `AABBs` - List of list of axis aligned bounding boxes for a bottom level acceleration structure
2480 #[derive(Debug)]
2481 pub enum AccelerationStructureEntries<'a, B: DynBuffer + ?Sized> {
2482 Instances(AccelerationStructureInstances<'a, B>),
2483 Triangles(Vec<AccelerationStructureTriangles<'a, B>>),
2484 AABBs(Vec<AccelerationStructureAABBs<'a, B>>),
2485 }
2486
2487 /// * `first_vertex` - offset in the vertex buffer (as number of vertices)
2488 /// * `indices` - optional index buffer with attributes
2489 /// * `transform` - optional transform
2490 #[derive(Clone, Debug)]
2491 pub struct AccelerationStructureTriangles<'a, B: DynBuffer + ?Sized> {
2492 pub vertex_buffer: Option<&'a B>,
2493 pub vertex_format: wgt::VertexFormat,
2494 pub first_vertex: u32,
2495 pub vertex_count: u32,
2496 pub vertex_stride: wgt::BufferAddress,
2497 pub indices: Option<AccelerationStructureTriangleIndices<'a, B>>,
2498 pub transform: Option<AccelerationStructureTriangleTransform<'a, B>>,
2499 pub flags: AccelerationStructureGeometryFlags,
2500 }
2501
2502 /// * `offset` - offset in bytes
2503 #[derive(Clone, Debug)]
2504 pub struct AccelerationStructureAABBs<'a, B: DynBuffer + ?Sized> {
2505 pub buffer: Option<&'a B>,
2506 pub offset: u32,
2507 pub count: u32,
2508 pub stride: wgt::BufferAddress,
2509 pub flags: AccelerationStructureGeometryFlags,
2510 }
2511
2512 pub struct AccelerationStructureCopy {
2513 pub copy_flags: wgt::AccelerationStructureCopy,
2514 pub type_flags: wgt::AccelerationStructureType,
2515 }
2516
2517 /// * `offset` - offset in bytes
2518 #[derive(Clone, Debug)]
2519 pub struct AccelerationStructureInstances<'a, B: DynBuffer + ?Sized> {
2520 pub buffer: Option<&'a B>,
2521 pub offset: u32,
2522 pub count: u32,
2523 }
2524
2525 /// * `offset` - offset in bytes
2526 #[derive(Clone, Debug)]
2527 pub struct AccelerationStructureTriangleIndices<'a, B: DynBuffer + ?Sized> {
2528 pub format: wgt::IndexFormat,
2529 pub buffer: Option<&'a B>,
2530 pub offset: u32,
2531 pub count: u32,
2532 }
2533
2534 /// * `offset` - offset in bytes
2535 #[derive(Clone, Debug)]
2536 pub struct AccelerationStructureTriangleTransform<'a, B: DynBuffer + ?Sized> {
2537 pub buffer: &'a B,
2538 pub offset: u32,
2539 }
2540
2541 pub use wgt::AccelerationStructureFlags as AccelerationStructureBuildFlags;
2542 pub use wgt::AccelerationStructureGeometryFlags;
2543
2544 bitflags::bitflags! {
2545 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2546 pub struct AccelerationStructureUses: u8 {
2547 // For blas used as input for tlas
2548 const BUILD_INPUT = 1 << 0;
2549 // Target for acceleration structure build
2550 const BUILD_OUTPUT = 1 << 1;
2551 // Tlas used in a shader
2552 const SHADER_INPUT = 1 << 2;
2553 // Blas used to query compacted size
2554 const QUERY_INPUT = 1 << 3;
2555 // BLAS used as a src for a copy operation
2556 const COPY_SRC = 1 << 4;
2557 // BLAS used as a dst for a copy operation
2558 const COPY_DST = 1 << 5;
2559 }
2560 }
2561
2562 #[derive(Debug, Clone)]
2563 pub struct AccelerationStructureBarrier {
2564 pub usage: StateTransition<AccelerationStructureUses>,
2565 }
2566
2567 #[derive(Debug, Copy, Clone)]
2568 pub struct TlasInstance {
2569 pub transform: [f32; 12],
2570 pub custom_data: u32,
2571 pub mask: u8,
2572 pub blas_address: u64,
2573 }