Skip to main content

wgpu_types/
lib.rs

1//! This library describes the API surface of WebGPU that is agnostic of the backend.
2//! This API is used for targeting both Web and Native.
3
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![allow(
6    clippy::match_like_matches_macro,
7    reason = "we don't use syntax sugar where it's not necessary"
8)]
9#![warn(
10    clippy::ptr_as_ptr,
11    missing_docs,
12    unsafe_op_in_unsafe_fn,
13    unused_qualifications
14)]
15#![no_std]
16
17#[cfg(any(feature = "std", test))]
18extern crate std;
19
20extern crate alloc;
21
22extern crate naga_types as nt;
23
24use core::{fmt, hash::Hash, time::Duration};
25
26#[cfg(any(feature = "serde", test))]
27use serde::{Deserialize, Serialize};
28
29mod adapter;
30pub mod assertions;
31mod backend;
32mod binding;
33mod bitflags_array;
34mod buffer;
35mod cast_utils;
36mod compilation_info;
37mod counters;
38mod device;
39mod env;
40pub mod error;
41mod features;
42pub mod instance;
43mod limits;
44mod macros;
45#[doc(hidden)] // for use in wgpu-core,wgpu-core-remote-types
46pub mod markers;
47pub mod math;
48mod origin_extent;
49mod ray_tracing;
50mod render;
51#[doc(hidden)] // without this we get spurious missing_docs warnings
52mod send_sync;
53mod shader;
54mod surface;
55mod texture;
56mod tokens;
57mod transfers;
58mod vertex;
59mod write_only;
60
61pub use nt::VertexFormat;
62
63pub use adapter::*;
64pub use backend::*;
65pub use binding::*;
66pub use buffer::*;
67pub use compilation_info::*;
68pub use counters::*;
69pub use device::*;
70pub use features::*;
71pub use instance::*;
72pub use limits::*;
73pub use origin_extent::*;
74pub use ray_tracing::*;
75pub use render::*;
76#[doc(hidden)]
77pub use send_sync::*;
78pub use shader::*;
79pub use surface::*;
80pub use texture::*;
81pub use tokens::*;
82pub use transfers::*;
83pub use vertex::*;
84pub use write_only::*;
85
86pub(crate) use bitflags_array::*;
87
88pub(crate) use macros::ConstDefault;
89
90/// Create a Markdown link definition referring to the `wgpu` crate.
91///
92/// This macro should be used inside a `#[doc = ...]` attribute.
93/// The two arguments should be string literals or macros that expand to string literals.
94/// If the module in which the item using this macro is located is not the crate root,
95/// use the `../` syntax.
96///
97/// We cannot simply use rustdoc links to `wgpu` because it is one of our dependents.
98/// This link adapts to work in locally generated documentation (`cargo doc`) by default,
99/// and work with `docs.rs` URL structure when building for `docs.rs`.
100///
101/// Note: This macro cannot be used outside this crate, because `cfg(docsrs)` will not apply.
102#[cfg(not(docsrs))]
103#[macro_export]
104macro_rules! link_to_wgpu_docs {
105    ([$reference:expr]: $url_path:expr) => {
106        concat!("[", $reference, "]: ../wgpu/", $url_path)
107    };
108
109    (../ [$reference:expr]: $url_path:expr) => {
110        concat!("[", $reference, "]: ../../wgpu/", $url_path)
111    };
112}
113#[cfg(docsrs)]
114#[macro_export]
115macro_rules! link_to_wgpu_docs {
116    ($(../)? [$reference:expr]: $url_path:expr) => {
117        concat!(
118            "[",
119            $reference,
120            // URL path will have a base URL of https://docs.rs/
121            "]: /wgpu/",
122            // The version of wgpu-types is not necessarily the same as the version of wgpu
123            // if a patch release of either has been published, so we cannot use the full version
124            // number. docs.rs will interpret this single number as a Cargo-style version
125            // requirement and redirect to the latest compatible version.
126            //
127            // This technique would break if `wgpu` and `wgpu-types` ever switch to having distinct
128            // major version numbering. An alternative would be to hardcode the corresponding `wgpu`
129            // version, but that would give us another thing to forget to update.
130            env!("CARGO_PKG_VERSION_MAJOR"),
131            "/wgpu/",
132            $url_path
133        )
134    };
135}
136
137/// Create a Markdown link definition referring to an item in the `wgpu` crate.
138///
139/// This macro should be used inside a `#[doc = ...]` attribute.
140/// See [`link_to_wgpu_docs`] for more details.
141#[macro_export]
142macro_rules! link_to_wgpu_item {
143    ($kind:ident $name:ident) => {
144        $crate::link_to_wgpu_docs!(
145            [concat!("`", stringify!($name), "`")]: concat!(stringify!($kind), ".", stringify!($name), ".html")
146        )
147    };
148}
149
150/// Create a Markdown link definition referring to the `wgpu_core` crate.
151///
152/// This macro should be used inside a `#[doc = ...]` attribute.
153/// See [`link_to_wgpu_docs`] for more details.
154#[cfg(not(docsrs))]
155#[macro_export]
156macro_rules! link_to_wgc_docs {
157    ([$reference:expr]: $url_path:expr) => {
158        concat!("[", $reference, "]: ../wgpu_core/", $url_path)
159    };
160
161    (../ [$reference:expr]: $url_path:expr) => {
162        concat!("[", $reference, "]: ../../wgpu_core/", $url_path)
163    };
164}
165#[cfg(docsrs)]
166#[macro_export]
167macro_rules! link_to_wgc_docs {
168    ($(../)? [$reference:expr]: $url_path:expr) => {
169        concat!(
170            "[",
171            $reference,
172            // URL path will have a base URL of https://docs.rs/
173            "]: /wgpu_core/",
174            // The version of wgpu-types is not necessarily the same as the version of wgpu_core
175            // if a patch release of either has been published, so we cannot use the full version
176            // number. docs.rs will interpret this single number as a Cargo-style version
177            // requirement and redirect to the latest compatible version.
178            //
179            // This technique would break if `wgpu_core` and `wgpu-types` ever switch to having
180            // distinct major version numbering. An alternative would be to hardcode the
181            // corresponding `wgpu_core` version, but that would give us another thing to forget
182            // to update.
183            env!("CARGO_PKG_VERSION_MAJOR"),
184            "/wgpu_core/",
185            $url_path
186        )
187    };
188}
189
190/// Integral type used for [`Buffer`] offsets and sizes.
191///
192#[doc = link_to_wgpu_item!(struct Buffer)]
193pub type BufferAddress = u64;
194
195/// Integral type used for [`BufferSlice`] sizes.
196///
197/// Note that while this type is non-zero, a [`Buffer`] *per se* can have a size of zero,
198/// but no slice or mapping can be created from it.
199///
200#[doc = link_to_wgpu_item!(struct Buffer)]
201#[doc = link_to_wgpu_item!(struct BufferSlice)]
202pub type BufferSize = core::num::NonZeroU64;
203
204/// Integral type used for binding locations in shaders.
205///
206/// Used in [`VertexAttribute`]s and errors.
207///
208#[doc = link_to_wgpu_item!(struct VertexAttribute)]
209pub type ShaderLocation = u32;
210
211/// Integral type used for
212/// [dynamic bind group offsets](../wgpu/struct.RenderPass.html#method.set_bind_group).
213pub type DynamicOffset = u32;
214
215/// Buffer-texture copies must have [`bytes_per_row`] aligned to this number, unless
216/// [`Features::UNRESTRICTED_BYTES_PER_ROW`] is enabled.
217///
218/// This doesn't apply to [`Queue::write_texture`][Qwt], only to [`copy_buffer_to_texture()`]
219/// and [`copy_texture_to_buffer()`].
220///
221/// [`bytes_per_row`]: TexelCopyBufferLayout::bytes_per_row
222#[doc = link_to_wgpu_docs!(["`copy_buffer_to_texture()`"]: "struct.Queue.html#method.copy_buffer_to_texture")]
223#[doc = link_to_wgpu_docs!(["`copy_texture_to_buffer()`"]: "struct.Queue.html#method.copy_texture_to_buffer")]
224#[doc = link_to_wgpu_docs!(["Qwt"]: "struct.Queue.html#method.write_texture")]
225pub const COPY_BYTES_PER_ROW_ALIGNMENT: u32 = 256;
226
227/// An [offset into the query resolve buffer] has to be aligned to this.
228///
229#[doc = link_to_wgpu_docs!(["offset into the query resolve buffer"]: "struct.CommandEncoder.html#method.resolve_query_set")]
230pub const QUERY_RESOLVE_BUFFER_ALIGNMENT: BufferAddress = 256;
231
232/// Buffer to buffer copy as well as buffer clear offsets and sizes must be aligned to this number.
233pub const COPY_BUFFER_ALIGNMENT: BufferAddress = 4;
234
235/// Minimum alignment of buffer mappings.
236///
237/// The range passed to [`map_async()`] or [`get_mapped_range()`] must be at least this aligned.
238///
239#[doc = link_to_wgpu_docs!(["`map_async()`"]: "struct.Buffer.html#method.map_async")]
240#[doc = link_to_wgpu_docs!(["`get_mapped_range()`"]: "struct.Buffer.html#method.get_mapped_range")]
241pub const MAP_ALIGNMENT: BufferAddress = 8;
242
243/// [Vertex buffer offsets] and [strides] have to be a multiple of this number.
244///
245#[doc = link_to_wgpu_docs!(["Vertex buffer offsets"]: "util/trait.RenderEncoder.html#tymethod.set_vertex_buffer")]
246#[doc = link_to_wgpu_docs!(["strides"]: "struct.VertexBufferLayout.html#structfield.array_stride")]
247pub const VERTEX_ALIGNMENT: BufferAddress = 4;
248
249/// [Vertex buffer strides] have to be a multiple of this number.
250///
251#[doc = link_to_wgpu_docs!(["Vertex buffer strides"]: "struct.VertexBufferLayout.html#structfield.array_stride")]
252#[deprecated(note = "Use `VERTEX_ALIGNMENT` instead", since = "27.0.0")]
253pub const VERTEX_STRIDE_ALIGNMENT: BufferAddress = 4;
254
255/// Ranges of [writes to immediate data] must be at least this aligned.
256///
257#[doc = link_to_wgpu_docs!(["writes to immediate data"]: "struct.RenderPass.html#method.set_immediates")]
258pub const IMMEDIATE_DATA_ALIGNMENT: u32 = 4;
259
260/// Storage buffer binding sizes must be multiples of this value.
261#[doc(hidden)]
262pub const STORAGE_BINDING_SIZE_ALIGNMENT: u32 = 4;
263
264/// Maximum number of query result slots that can be requested in a [`QuerySetDescriptor`].
265pub const QUERY_SET_MAX_QUERIES: u32 = 4096;
266
267/// Size in bytes of a single piece of [query] data.
268///
269#[doc = link_to_wgpu_docs!(["query"]: "struct.QuerySet.html")]
270pub const QUERY_SIZE: u32 = 8;
271
272/// The minimum allowed value for [`AdapterInfo::subgroup_min_size`].
273///
274/// See <https://gpuweb.github.io/gpuweb/#gpuadapterinfo>
275/// where you can always use these values on all devices
276pub const MINIMUM_SUBGROUP_MIN_SIZE: u32 = 4;
277/// The maximum allowed value for [`AdapterInfo::subgroup_max_size`].
278///
279/// See <https://gpuweb.github.io/gpuweb/#gpuadapterinfo>
280/// where you can always use these values on all devices.
281pub const MAXIMUM_SUBGROUP_MAX_SIZE: u32 = 128;
282
283/// Passed to `Device::poll` to control how and if it should block.
284#[derive(Clone, Debug)]
285pub enum PollType<T> {
286    /// On wgpu-core based backends, block until the given submission has
287    /// completed execution, and any callbacks have been invoked.
288    ///
289    /// On WebGPU, this has no effect. Callbacks are invoked from the
290    /// window event loop.
291    Wait {
292        /// Submission index to wait for.
293        ///
294        /// If not specified, will wait for the most recent submission at the time of the poll.
295        /// By the time the method returns, more submissions may have taken place.
296        submission_index: Option<T>,
297
298        /// Max time to wait for the submission to complete.
299        ///
300        /// If not specified, will wait indefinitely (or until an error is detected).
301        /// If waiting for the GPU device takes this long or longer, the poll will return [`PollError::Timeout`].
302        timeout: Option<Duration>,
303    },
304
305    /// Check the device for a single time without blocking.
306    Poll,
307}
308
309impl<T> PollType<T> {
310    /// Wait indefinitely until for the most recent submission to complete.
311    ///
312    /// This is a convenience function that creates a [`Self::Wait`] variant with
313    /// no timeout and no submission index.
314    #[must_use]
315    pub const fn wait_indefinitely() -> Self {
316        Self::Wait {
317            submission_index: None,
318            timeout: None,
319        }
320    }
321
322    /// This `PollType` represents a wait of some kind.
323    #[must_use]
324    pub fn is_wait(&self) -> bool {
325        match *self {
326            Self::Wait { .. } => true,
327            Self::Poll => false,
328        }
329    }
330
331    /// Map on the wait index type.
332    #[must_use]
333    pub fn map_index<U, F>(self, func: F) -> PollType<U>
334    where
335        F: FnOnce(T) -> U,
336    {
337        match self {
338            Self::Wait {
339                submission_index,
340                timeout,
341            } => PollType::Wait {
342                submission_index: submission_index.map(func),
343                timeout,
344            },
345            Self::Poll => PollType::Poll,
346        }
347    }
348}
349
350/// Error states after a device poll.
351#[derive(Debug)]
352pub enum PollError {
353    /// The requested Wait timed out before the submission was completed.
354    Timeout,
355    /// The requested Wait was given a wrong submission index.
356    WrongSubmissionIndex(u64, u64),
357    /// The backend doesn't support synchronously waiting.
358    CantWait,
359}
360
361// This impl could be derived by `thiserror`, but by not doing so, we can reduce the number of
362// dependencies this early in the dependency graph, which may improve build parallelism.
363impl fmt::Display for PollError {
364    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365        match self {
366            PollError::Timeout => {
367                f.write_str("The requested Wait timed out before the submission was completed.")
368            }
369            PollError::WrongSubmissionIndex(requested, successful) => write!(
370                f,
371                "Tried to wait using a submission index ({requested}) \
372                that has not been returned by a successful submission \
373                (last successful submission: {successful}"
374            ),
375            PollError::CantWait => {
376                f.write_str("The backend doesn't support synchronously waiting.")
377            }
378        }
379    }
380}
381
382impl core::error::Error for PollError {}
383
384/// Status of device poll operation.
385#[derive(Debug, PartialEq, Eq)]
386pub enum PollStatus {
387    /// There are no active submissions in flight as of the beginning of the poll call.
388    /// Other submissions may have been queued on other threads during the call.
389    ///
390    /// This implies that the given Wait was satisfied before the timeout.
391    QueueEmpty,
392
393    /// The requested Wait was satisfied before the timeout.
394    WaitSucceeded,
395
396    /// This was a poll.
397    Poll,
398}
399
400impl PollStatus {
401    /// Returns true if the result is [`Self::QueueEmpty`].
402    #[must_use]
403    pub fn is_queue_empty(&self) -> bool {
404        matches!(self, Self::QueueEmpty)
405    }
406
407    /// Returns true if the result is either [`Self::WaitSucceeded`] or [`Self::QueueEmpty`].
408    #[must_use]
409    pub fn wait_finished(&self) -> bool {
410        matches!(self, Self::WaitSucceeded | Self::QueueEmpty)
411    }
412}
413
414/// Describes a [`CommandEncoder`](../wgpu/struct.CommandEncoder.html).
415///
416/// Corresponds to [WebGPU `GPUCommandEncoderDescriptor`](
417/// https://gpuweb.github.io/gpuweb/#dictdef-gpucommandencoderdescriptor).
418#[repr(C)]
419#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
420#[derive(Clone, Debug, PartialEq, Eq, Hash)]
421pub struct CommandEncoderDescriptor<L> {
422    /// Debug label for the command encoder. This will show up in graphics debuggers for easy identification.
423    pub label: L,
424}
425
426impl<L> CommandEncoderDescriptor<L> {
427    /// Takes a closure and maps the label of the command encoder descriptor into another.
428    #[must_use]
429    pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> CommandEncoderDescriptor<K> {
430        CommandEncoderDescriptor {
431            label: fun(&self.label),
432        }
433    }
434}
435
436impl<T> Default for CommandEncoderDescriptor<Option<T>> {
437    fn default() -> Self {
438        Self { label: None }
439    }
440}
441
442/// RGBA double precision color.
443///
444/// This is not to be used as a generic color type, only for specific wgpu interfaces.
445#[repr(C)]
446#[derive(Clone, Copy, Debug, Default, PartialEq)]
447#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
448#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
449pub struct Color {
450    /// Red component of the color
451    pub r: f64,
452    /// Green component of the color
453    pub g: f64,
454    /// Blue component of the color
455    pub b: f64,
456    /// Alpha component of the color
457    pub a: f64,
458}
459
460#[expect(missing_docs, reason = "the color constants are self-explanatory")]
461impl Color {
462    pub const TRANSPARENT: Self = Self {
463        r: 0.0,
464        g: 0.0,
465        b: 0.0,
466        a: 0.0,
467    };
468    pub const BLACK: Self = Self {
469        r: 0.0,
470        g: 0.0,
471        b: 0.0,
472        a: 1.0,
473    };
474    pub const WHITE: Self = Self {
475        r: 1.0,
476        g: 1.0,
477        b: 1.0,
478        a: 1.0,
479    };
480    pub const RED: Self = Self {
481        r: 1.0,
482        g: 0.0,
483        b: 0.0,
484        a: 1.0,
485    };
486    pub const GREEN: Self = Self {
487        r: 0.0,
488        g: 1.0,
489        b: 0.0,
490        a: 1.0,
491    };
492    pub const BLUE: Self = Self {
493        r: 0.0,
494        g: 0.0,
495        b: 1.0,
496        a: 1.0,
497    };
498}
499
500/// Describes a [`CommandBuffer`](../wgpu/struct.CommandBuffer.html).
501///
502/// Corresponds to [WebGPU `GPUCommandBufferDescriptor`](
503/// https://gpuweb.github.io/gpuweb/#dictdef-gpucommandbufferdescriptor).
504#[repr(C)]
505#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
507pub struct CommandBufferDescriptor<L> {
508    /// Debug label of this command buffer.
509    pub label: L,
510}
511
512impl<L> CommandBufferDescriptor<L> {
513    /// Takes a closure and maps the label of the command buffer descriptor into another.
514    #[must_use]
515    pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> CommandBufferDescriptor<K> {
516        CommandBufferDescriptor {
517            label: fun(&self.label),
518        }
519    }
520}
521
522/// Describes how to create a `QuerySet`.
523///
524/// Corresponds to [WebGPU `GPUQuerySetDescriptor`](
525/// https://gpuweb.github.io/gpuweb/#dictdef-gpuquerysetdescriptor).
526#[derive(Clone, Debug)]
527#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
528pub struct QuerySetDescriptor<L> {
529    /// Debug label for the query set.
530    pub label: L,
531    /// Kind of query that this query set should contain.
532    pub ty: QueryType,
533    /// Total number of query result slots the set contains. Must not be zero.
534    /// Must not be greater than [`QUERY_SET_MAX_QUERIES`].
535    pub count: u32,
536}
537
538impl<L> QuerySetDescriptor<L> {
539    /// Takes a closure and maps the label of the query set descriptor into another.
540    #[must_use]
541    pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> QuerySetDescriptor<K> {
542        QuerySetDescriptor {
543            label: fun(&self.label),
544            ty: self.ty,
545            count: self.count,
546        }
547    }
548}
549
550/// Type of queries contained in a [`QuerySet`].
551///
552/// Each query set may contain any number of queries, but they must all be of the same type.
553///
554/// Corresponds to [WebGPU `GPUQueryType`](
555/// https://gpuweb.github.io/gpuweb/#enumdef-gpuquerytype).
556///
557#[doc = link_to_wgpu_item!(struct QuerySet)]
558#[derive(Copy, Clone, Debug)]
559#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
560pub enum QueryType {
561    /// An occlusion query reports whether any of the fragments drawn within the scope of the query
562    /// passed all per-fragment tests (i.e. were not occluded).
563    ///
564    /// Occlusion queries are performed by setting [`RenderPassDescriptor::occlusion_query_set`],
565    /// then calling [`RenderPass::begin_occlusion_query()`] and
566    /// [`RenderPass::end_occlusion_query()`].
567    /// The query writes to a single result slot in the query set, whose value will be either 0 or 1
568    /// as a boolean.
569    ///
570    #[doc = link_to_wgpu_docs!(["`RenderPassDescriptor::occlusion_query_set`"]: "struct.RenderPassDescriptor.html#structfield.occlusion_query_set")]
571    #[doc = link_to_wgpu_docs!(["`RenderPass::begin_occlusion_query()`"]: "struct.RenderPass.html#structfield.begin_occlusion_query")]
572    #[doc = link_to_wgpu_docs!(["`RenderPass::end_occlusion_query()`"]: "struct.RenderPass.html#structfield.end_occlusion_query")]
573    Occlusion,
574
575    /// A timestamp query records a GPU-timestamp value
576    /// at which a certain command started or finished executing.
577    ///
578    /// Timestamp queries are performed by any one of:
579    /// * Setting [`ComputePassDescriptor::timestamp_writes`]
580    /// * Setting [`RenderPassDescriptor::timestamp_writes`]
581    /// * Calling [`CommandEncoder::write_timestamp()`]
582    /// * Calling [`RenderPass::write_timestamp()`]
583    /// * Calling [`ComputePass::write_timestamp()`]
584    ///
585    /// Each timestamp query writes to a single result slot in the query set.
586    /// The timestamp value must be multiplied by [`Queue::get_timestamp_period()`][Qgtp] to get
587    /// the time in nanoseconds.
588    /// Absolute values have no meaning, but timestamps can be subtracted to get the time it takes
589    /// for a string of operations to complete.
590    /// Timestamps may overflow and wrap to 0, resulting in occasional spurious negative deltas.
591    ///
592    /// Additionally, passes may be executed in parallel or out of the order they were submitted;
593    /// this does not affect their results but is observable via these timestamps.
594    ///
595    /// [`Features::TIMESTAMP_QUERY`] must be enabled to use this query type.
596    ///
597    #[doc = link_to_wgpu_docs!(["`CommandEncoder::write_timestamp()`"]: "struct.CommandEncoder.html#method.write_timestamp")]
598    #[doc = link_to_wgpu_docs!(["`ComputePass::write_timestamp()`"]: "struct.ComputePass.html#method.write_timestamp")]
599    #[doc = link_to_wgpu_docs!(["`RenderPass::write_timestamp()`"]: "struct.RenderPass.html#method.write_timestamp")]
600    #[doc = link_to_wgpu_docs!(["`ComputePassDescriptor::timestamp_writes`"]: "struct.ComputePassDescriptor.html#structfield.timestamp_writes")]
601    #[doc = link_to_wgpu_docs!(["`RenderPassDescriptor::timestamp_writes`"]: "struct.RenderPassDescriptor.html#structfield.timestamp_writes")]
602    #[doc = link_to_wgpu_docs!(["Qgtp"]: "struct.Queue.html#method.get_timestamp_period")]
603    Timestamp,
604
605    /// A pipeline statistics query records information about the execution of pipelines;
606    /// see [`PipelineStatisticsTypes`]'s documentation for details.
607    ///
608    /// Pipeline statistics queries are performed by:
609    ///
610    /// * [`ComputePass::begin_pipeline_statistics_query()`]
611    /// * [`RenderPass::begin_pipeline_statistics_query()`]
612    ///
613    /// A single query may occupy up to 5 result slots in the query set, based on the flags given
614    /// here.
615    ///
616    /// [`Features::PIPELINE_STATISTICS_QUERY`] must be enabled to use this query type.
617    ///
618    #[doc = link_to_wgpu_docs!(["`ComputePass::begin_pipeline_statistics_query()`"]: "struct.ComputePass.html#method.begin_pipeline_statistics_query")]
619    #[doc = link_to_wgpu_docs!(["`RenderPass::begin_pipeline_statistics_query()`"]: "struct.RenderPass.html#method.begin_pipeline_statistics_query")]
620    PipelineStatistics(PipelineStatisticsTypes),
621}
622
623impl fmt::Display for QueryType {
624    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625        match self {
626            Self::Occlusion => f.write_str("occlusion"),
627            Self::Timestamp => f.write_str("timestamp"),
628            Self::PipelineStatistics(_) => f.write_str("pipeline-statistics"),
629        }
630    }
631}
632
633bitflags::bitflags! {
634    /// Flags for which pipeline data should be recorded in a query.
635    ///
636    /// Used in [`QueryType`].
637    ///
638    /// The amount of values written when resolved depends
639    /// on the amount of flags set. For example, if 3 flags are set, 3
640    /// 64-bit values will be written per query.
641    ///
642    /// The order they are written is the order they are declared
643    /// in these bitflags. For example, if you enabled `CLIPPER_PRIMITIVES_OUT`
644    /// and `COMPUTE_SHADER_INVOCATIONS`, it would write 16 bytes,
645    /// the first 8 bytes being the primitive out value, the last 8
646    /// bytes being the compute shader invocation count.
647    #[repr(transparent)]
648    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
649    #[cfg_attr(feature = "serde", serde(transparent))]
650    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
651    pub struct PipelineStatisticsTypes : u8 {
652        /// Amount of times the vertex shader is ran. Accounts for
653        /// the vertex cache when doing indexed rendering.
654        const VERTEX_SHADER_INVOCATIONS = 1 << 0;
655        /// Amount of times the clipper is invoked. This
656        /// is also the amount of triangles output by the vertex shader.
657        const CLIPPER_INVOCATIONS = 1 << 1;
658        /// Amount of primitives that are not culled by the clipper.
659        /// This is the amount of triangles that are actually on screen
660        /// and will be rasterized and rendered.
661        const CLIPPER_PRIMITIVES_OUT = 1 << 2;
662        /// Amount of times the fragment shader is ran. Accounts for
663        /// fragment shaders running in 2x2 blocks in order to get
664        /// derivatives.
665        const FRAGMENT_SHADER_INVOCATIONS = 1 << 3;
666        /// Amount of times a compute shader is invoked. This will
667        /// be equivalent to the dispatch count times the workgroup size.
668        const COMPUTE_SHADER_INVOCATIONS = 1 << 4;
669    }
670}
671
672/// Corresponds to a [`GPUDeviceLostReason`].
673///
674/// [`GPUDeviceLostReason`]: https://www.w3.org/TR/webgpu/#enumdef-gpudevicelostreason
675#[repr(u8)]
676#[derive(Debug, Copy, Clone, Eq, PartialEq)]
677#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
678pub enum DeviceLostReason {
679    /// The device was lost for an unspecific reason, including driver errors.
680    Unknown = 0,
681    /// The device's `destroy` method was called.
682    Destroyed = 1,
683}