Skip to main content

wgpu_core/command/
mod.rs

1//! # Command Encoding
2//!
3//! TODO: High-level description of command encoding.
4//!
5//! The convention in this module is that functions accepting a [`&mut dyn
6//! hal::DynCommandEncoder`] are low-level helpers and may assume the encoder is
7//! in the open state, ready to encode commands. Encoders that are not open
8//! should be nested within some other container that provides additional
9//! state tracking, like [`InnerCommandEncoder`].
10
11mod allocator;
12mod bind;
13mod bundle;
14mod clear;
15mod compute;
16mod compute_command;
17mod draw;
18mod encoder;
19mod encoder_command;
20mod memory_init;
21mod pass;
22mod query;
23mod ray_tracing;
24mod ray_tracing_pass;
25mod ray_tracing_pass_commands;
26mod render;
27mod render_command;
28mod timestamp_writes;
29mod transfer;
30mod transition_resources;
31
32use alloc::{borrow::ToOwned as _, boxed::Box, string::String, sync::Arc, vec::Vec};
33use core::convert::Infallible;
34use core::mem::{self, ManuallyDrop};
35use core::{ops, panic};
36
37#[cfg(feature = "serde")]
38pub(crate) use self::encoder_command::serde_object_reference_struct;
39#[cfg(any(feature = "trace", feature = "replay"))]
40#[doc(hidden)]
41pub use self::encoder_command::PointerReferences;
42// This module previously did `pub use *` for some of the submodules. When that
43// was removed, every type that was previously public via `use *` was listed
44// here. Some types (in particular `CopySide`) may be exported unnecessarily.
45pub use self::{
46    bundle::{
47        CreateRenderBundleError, ExecutionError, RenderBundle, RenderBundleDescriptor,
48        RenderBundleEncoder, RenderBundleEncoderDescriptor, RenderBundleError,
49        RenderBundleErrorInner,
50    },
51    clear::ClearError,
52    compute::{
53        ComputeBasePass, ComputePass, ComputePassDescriptor, ComputePassError,
54        ComputePassErrorInner, DispatchError,
55    },
56    compute_command::ArcComputeCommand,
57    draw::{DrawError, Rect, RenderCommandError},
58    encoder_command::{ArcCommand, ArcReferences, Command, ReferenceType},
59    query::{QueryError, QueryUseError, ResolveError, SimplifiedQueryType},
60    ray_tracing_pass::{
61        RayTracingBasePass, RayTracingPass, RayTracingPassDescriptor, RayTracingPassError,
62        RayTracingPassErrorInner, TraceRayError,
63    },
64    ray_tracing_pass_commands::ArcRayTracingCommand,
65    render::{
66        AttachmentError, AttachmentErrorLocation, ColorAttachmentError, ColorAttachments, LoadOp,
67        PassChannel, RenderBasePass, RenderPass, RenderPassColorAttachment,
68        RenderPassDepthStencilAttachment, RenderPassError, RenderPassErrorInner,
69        ResolvedPassChannel, ResolvedRenderPassDepthStencilAttachment,
70        ResolvedRenderPassDescriptor, StoreOp,
71    },
72    render_command::ArcRenderCommand,
73    transfer::{CopySide, TransferError},
74    transition_resources::TransitionResourcesError,
75};
76pub(crate) use self::{
77    clear::clear_texture,
78    encoder::EncodingState,
79    memory_init::CommandBufferTextureMemoryActions,
80    ray_tracing_pass::max_trace_rays_dimensions,
81    render::{get_dst_stride_of_indirect_args, get_src_stride_of_indirect_args, VertexState},
82    transfer::{
83        validate_linear_texture_data, validate_texture_buffer_copy,
84        validate_texture_copy_dst_format, validate_texture_copy_range, CopyRange,
85    },
86};
87
88pub(crate) use allocator::CommandAllocator;
89
90/// cbindgen:ignore
91pub use self::{
92    compute_command::ComputeCommand, ray_tracing_pass_commands::RayTracingCommand,
93    render_command::RenderCommand,
94};
95
96pub use timestamp_writes::PassTimestampWrites;
97
98use crate::binding_model::{BindGroup, BindingError};
99use crate::device::queue::TempResource;
100use crate::device::{Device, DeviceError, MissingFeatures};
101use crate::lock::{rank, Mutex};
102use crate::snatch::SnatchGuard;
103
104use crate::init_tracker::BufferInitTrackerAction;
105use crate::ray_tracing::{AsAction, BuildAccelerationStructureError};
106use crate::resource::{
107    DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError, Labeled,
108    ParentDevice as _, QuerySet,
109};
110use crate::track::{DeviceTracker, ResourceUsageCompatibilityError, Tracker, UsageScope};
111use crate::{api_log, resource_log, Label};
112use crate::{hal_label, LabelHelpers};
113
114use wgt::error::{ErrorType, WebGpuError};
115
116use thiserror::Error;
117
118pub(crate) struct EncoderErrorState {
119    error: CommandEncoderError,
120
121    #[cfg(feature = "trace")]
122    trace_commands: Option<Vec<Command<PointerReferences>>>,
123}
124
125/// Construct an `EncoderErrorState` with only a `CommandEncoderError` (without
126/// any traced commands).
127///
128/// This is used in cases where pass begin/end were mismatched, if the same
129/// encoder was finished multiple times, or in the status of a command buffer
130/// (in which case the commands were already saved to the trace). In some of
131/// these cases there may be commands that could be saved to the trace, but if
132/// the application is that confused about using encoders, it's not clear
133/// whether it's worth the effort to try and preserve the commands.
134fn make_error_state<E: Into<CommandEncoderError>>(error: E) -> CommandEncoderStatus {
135    CommandEncoderStatus::Error(EncoderErrorState {
136        error: error.into(),
137
138        #[cfg(feature = "trace")]
139        trace_commands: None,
140    })
141}
142
143/// The current state of a command or pass encoder.
144///
145/// In the WebGPU spec, the state of an encoder (open, locked, or ended) is
146/// orthogonal to the validity of the encoder. However, this enum does not
147/// represent the state of an invalid encoder.
148pub(crate) enum CommandEncoderStatus {
149    /// Ready to record commands. An encoder's initial state.
150    ///
151    /// Command building methods like [`CommandEncoder::clear_buffer`] and
152    /// [`ComputePass::end`] require the encoder to be in this
153    /// state.
154    ///
155    /// This corresponds to WebGPU's "open" state.
156    /// See <https://www.w3.org/TR/webgpu/#encoder-state-open>
157    Recording(CommandBufferMutable),
158
159    /// Locked by a render or compute pass.
160    ///
161    /// This state is entered when a render/compute pass is created,
162    /// and exited when the pass is ended.
163    ///
164    /// As long as the command encoder is locked, any command building operation
165    /// on it will fail and put the encoder into the [`Self::Error`] state. See
166    /// <https://www.w3.org/TR/webgpu/#encoder-state-locked>
167    Locked(CommandBufferMutable),
168
169    Consumed,
170
171    /// Command recording is complete, and the buffer is ready for submission.
172    ///
173    /// [`CommandEncoder::finish`] transitions a
174    /// `CommandBuffer` from the `Recording` state into this state.
175    ///
176    /// [`Queue::submit`] requires that command buffers are
177    /// in this state.
178    ///
179    /// This corresponds to WebGPU's "ended" state.
180    /// See <https://www.w3.org/TR/webgpu/#encoder-state-ended>
181    ///
182    /// [`Queue::submit`]: crate::device::queue::Queue::submit
183    Finished(CommandBufferMutable),
184
185    /// The command encoder is invalid.
186    ///
187    /// The error that caused the invalidation is stored here, and will
188    /// be raised by `CommandEncoder.finish()`.
189    Error(EncoderErrorState),
190
191    /// Temporary state used internally by methods on `CommandEncoderStatus`.
192    /// Encoder should never be left in this state.
193    Transitioning,
194}
195
196impl CommandEncoderStatus {
197    #[doc(hidden)]
198    fn replay(&mut self, commands: Vec<Command<ArcReferences>>) {
199        let Self::Recording(cmd_buf_data) = self else {
200            panic!("encoder should be in the recording state");
201        };
202        cmd_buf_data.commands.extend(commands);
203    }
204
205    /// Push a command provided by a closure onto the encoder.
206    ///
207    /// If the encoder is in the [`Self::Recording`] state, calls the closure to
208    /// obtain a command, and pushes it onto the encoder. If the closure returns
209    /// an error, stores that error in the encoder for later reporting when
210    /// `finish()` is called. Returns `Ok(())` even if the closure returned an
211    /// error.
212    ///
213    /// If the encoder is not in the [`Self::Recording`] state, the closure will
214    /// not be called and nothing will be recorded. The encoder will be
215    /// invalidated (if it is not already). If the error is a [validation error
216    /// that should be raised immediately][ves], returns it in `Err`, otherwise,
217    /// returns `Ok(())`.
218    ///
219    /// [ves]: https://www.w3.org/TR/webgpu/#abstract-opdef-validate-the-encoder-state
220    fn push_with<F: FnOnce() -> Result<ArcCommand, E>, E: Clone + Into<CommandEncoderError>>(
221        &mut self,
222        f: F,
223    ) -> Result<(), EncoderStateError> {
224        match self {
225            Self::Recording(cmd_buf_data) => {
226                cmd_buf_data.encoder.api.set(EncodingApi::Wgpu);
227                match f() {
228                    Ok(cmd) => cmd_buf_data.commands.push(cmd),
229                    Err(err) => {
230                        self.invalidate(err);
231                    }
232                }
233                Ok(())
234            }
235            Self::Locked(_) => {
236                // Invalidate the encoder and do not record anything, but do not
237                // return an immediate validation error.
238                self.invalidate(EncoderStateError::Locked);
239                Ok(())
240            }
241            // Encoder is ended. Invalidate the encoder, do not record anything,
242            // and return an immediate validation error.
243            Self::Finished(_) => Err(self.invalidate(EncoderStateError::Ended)),
244            Self::Consumed => Err(EncoderStateError::Ended),
245            // Encoder is already invalid. Do not record anything, but do not
246            // return an immediate validation error.
247            Self::Error(_) => Ok(()),
248            Self::Transitioning => unreachable!(),
249        }
250    }
251
252    /// Call a closure with the inner command buffer structure.
253    ///
254    /// If the encoder is in the [`Self::Recording`] state, calls the provided
255    /// closure. If the closure returns an error, stores that error in the
256    /// encoder for later reporting when `finish()` is called. Returns `Ok(())`
257    /// even if the closure returned an error.
258    ///
259    /// If the encoder is not in the [`Self::Recording`] state, the closure will
260    /// not be called. The encoder will be invalidated (if it is not already).
261    /// If the error is a [validation error that should be raised
262    /// immediately][ves], returns it in `Err`, otherwise, returns `Ok(())`.
263    ///
264    /// [ves]: https://www.w3.org/TR/webgpu/#abstract-opdef-validate-the-encoder-state
265    fn with_buffer<
266        F: FnOnce(&mut CommandBufferMutable) -> Result<(), E>,
267        E: Clone + Into<CommandEncoderError>,
268    >(
269        &mut self,
270        api: EncodingApi,
271        f: F,
272    ) -> Result<(), EncoderStateError> {
273        match self {
274            Self::Recording(inner) => {
275                inner.encoder.api.set(api);
276                RecordingGuard { inner: self }.record(f);
277                Ok(())
278            }
279            Self::Locked(_) => {
280                // Invalidate the encoder and do not record anything, but do not
281                // return an immediate validation error.
282                self.invalidate(EncoderStateError::Locked);
283                Ok(())
284            }
285            // Encoder is ended. Invalidate the encoder, do not record anything,
286            // and return an immediate validation error.
287            Self::Finished(_) => Err(self.invalidate(EncoderStateError::Ended)),
288            Self::Consumed => Err(EncoderStateError::Ended),
289            // Encoder is already invalid. Do not record anything, but do not
290            // return an immediate validation error.
291            Self::Error(_) => Ok(()),
292            Self::Transitioning => unreachable!(),
293        }
294    }
295
296    /// Special version of record used by `command_encoder_as_hal_mut`. This
297    /// differs from the regular version in two ways:
298    ///
299    /// 1. The recording closure is infallible.
300    /// 2. The recording closure takes `Option<&mut CommandBufferMutable>`, and
301    ///    in the case that the encoder is not in a valid state for recording, the
302    ///    closure is still called, with `None` as its argument.
303    pub(crate) fn record_as_hal_mut<T, F: FnOnce(Option<&mut CommandBufferMutable>) -> T>(
304        &mut self,
305        f: F,
306    ) -> T {
307        match self {
308            Self::Recording(inner) => {
309                inner.encoder.api.set(EncodingApi::Raw);
310                RecordingGuard { inner: self }.record_as_hal_mut(f)
311            }
312            Self::Locked(_) => {
313                self.invalidate(EncoderStateError::Locked);
314                f(None)
315            }
316            Self::Finished(_) => {
317                self.invalidate(EncoderStateError::Ended);
318                f(None)
319            }
320            Self::Consumed => f(None),
321            Self::Error(_) => f(None),
322            Self::Transitioning => unreachable!(),
323        }
324    }
325
326    /// Locks the encoder by putting it in the [`Self::Locked`] state.
327    ///
328    /// Render or compute passes call this on start. At the end of the pass,
329    /// they call [`Self::unlock_encoder`] to put the [`CommandBuffer`] back
330    /// into the [`Self::Recording`] state.
331    fn lock_encoder(&mut self) -> Result<(), EncoderStateError> {
332        match mem::replace(self, Self::Transitioning) {
333            Self::Recording(inner) => {
334                *self = Self::Locked(inner);
335                Ok(())
336            }
337            st @ Self::Finished(_) => {
338                // Attempting to open a pass on a finished encoder raises a
339                // validation error but does not invalidate the encoder. This is
340                // related to https://github.com/gpuweb/gpuweb/issues/5207.
341                *self = st;
342                Err(EncoderStateError::Ended)
343            }
344            Self::Locked(_) => Err(self.invalidate(EncoderStateError::Locked)),
345            st @ Self::Consumed => {
346                *self = st;
347                Err(EncoderStateError::Ended)
348            }
349            st @ Self::Error(_) => {
350                *self = st;
351                Err(EncoderStateError::Invalid)
352            }
353            Self::Transitioning => unreachable!(),
354        }
355    }
356
357    /// Unlocks the encoder and puts it back into the [`Self::Recording`] state.
358    ///
359    /// This function is the unlocking counterpart to [`Self::lock_encoder`]. It
360    /// is only valid to call this function if the encoder is in the
361    /// [`Self::Locked`] state.
362    ///
363    /// If the encoder is in a state other than [`Self::Locked`] and a
364    /// validation error should be raised immediately, returns it in `Err`,
365    /// otherwise, stores the error in the encoder and returns `Ok(())`.
366    fn unlock_encoder(&mut self) -> Result<(), EncoderStateError> {
367        match mem::replace(self, Self::Transitioning) {
368            Self::Locked(inner) => {
369                *self = Self::Recording(inner);
370                Ok(())
371            }
372            st @ Self::Finished(_) => {
373                *self = st;
374                Err(EncoderStateError::Ended)
375            }
376            Self::Recording(_) => {
377                *self = make_error_state(EncoderStateError::Unlocked);
378                Err(EncoderStateError::Unlocked)
379            }
380            st @ Self::Consumed => {
381                *self = st;
382                Err(EncoderStateError::Ended)
383            }
384            st @ Self::Error(_) => {
385                // Encoder is already invalid. The error will be reported by
386                // `CommandEncoder.finish`.
387                *self = st;
388                Ok(())
389            }
390            Self::Transitioning => unreachable!(),
391        }
392    }
393
394    fn finish(&mut self) -> Self {
395        // Replace our state with `Consumed`, and return either the inner
396        // state or an error, to be transferred to the command buffer.
397        match mem::replace(self, Self::Consumed) {
398            Self::Recording(inner) => {
399                // Raw encoding leaves the encoder open in `command_encoder_as_hal_mut`.
400                // Otherwise, nothing should have opened it yet.
401                if inner.encoder.api != EncodingApi::Raw {
402                    assert!(!inner.encoder.is_open);
403                }
404                Self::Finished(inner)
405            }
406            Self::Consumed | Self::Finished(_) => make_error_state(EncoderStateError::Ended),
407            Self::Locked(_) => make_error_state(EncoderStateError::Locked),
408            st @ Self::Error(_) => st,
409            Self::Transitioning => unreachable!(),
410        }
411    }
412
413    /// Invalidate the command encoder due to an error.
414    ///
415    /// The error `err` is stored so that it can be reported when the encoder is
416    /// finished. If tracing is enabled, the traced commands are also stored.
417    ///
418    /// Since we do not track the state of an invalid encoder, it is not
419    /// necessary to unlock an encoder that has been invalidated.
420    fn invalidate<E: Clone + Into<CommandEncoderError>>(&mut self, err: E) -> E {
421        #[cfg(feature = "trace")]
422        let trace_commands = match self {
423            Self::Recording(cmd_buf_data) => Some(
424                mem::take(&mut cmd_buf_data.commands)
425                    .into_iter()
426                    .map(crate::device::trace::IntoTrace::into_trace)
427                    .collect(),
428            ),
429            _ => None,
430        };
431
432        let enc_err = err.clone().into();
433        api_log!("Invalidating command encoder: {enc_err:?}");
434        *self = Self::Error(EncoderErrorState {
435            error: enc_err,
436            #[cfg(feature = "trace")]
437            trace_commands,
438        });
439        err
440    }
441}
442
443/// A guard to enforce error reporting, for a [`CommandBuffer`] in the [`Recording`] state.
444///
445/// An [`RecordingGuard`] holds a mutable reference to a [`CommandEncoderStatus`] that
446/// has been verified to be in the [`Recording`] state. The [`RecordingGuard`] dereferences
447/// mutably to the [`CommandBufferMutable`] that the status holds.
448///
449/// Dropping an [`RecordingGuard`] sets the [`CommandBuffer`]'s state to
450/// [`CommandEncoderStatus::Error`]. If your use of the guard was
451/// successful, call its [`mark_successful`] method to dispose of it.
452///
453/// [`Recording`]: CommandEncoderStatus::Recording
454/// [`mark_successful`]: Self::mark_successful
455pub(crate) struct RecordingGuard<'a> {
456    inner: &'a mut CommandEncoderStatus,
457}
458
459impl<'a> RecordingGuard<'a> {
460    pub(crate) fn mark_successful(self) {
461        mem::forget(self)
462    }
463
464    fn record<
465        F: FnOnce(&mut CommandBufferMutable) -> Result<(), E>,
466        E: Clone + Into<CommandEncoderError>,
467    >(
468        mut self,
469        f: F,
470    ) {
471        match f(&mut self) {
472            Ok(()) => self.mark_successful(),
473            Err(err) => {
474                self.inner.invalidate(err);
475            }
476        }
477    }
478
479    /// Special version of record used by `command_encoder_as_hal_mut`. This
480    /// version takes an infallible recording closure.
481    pub(crate) fn record_as_hal_mut<T, F: FnOnce(Option<&mut CommandBufferMutable>) -> T>(
482        mut self,
483        f: F,
484    ) -> T {
485        let res = f(Some(&mut self));
486        self.mark_successful();
487        res
488    }
489}
490
491impl<'a> Drop for RecordingGuard<'a> {
492    fn drop(&mut self) {
493        if matches!(*self.inner, CommandEncoderStatus::Error(_)) {
494            // Don't overwrite an error that is already present.
495            return;
496        }
497        self.inner.invalidate(EncoderStateError::Invalid);
498    }
499}
500
501impl<'a> ops::Deref for RecordingGuard<'a> {
502    type Target = CommandBufferMutable;
503
504    fn deref(&self) -> &Self::Target {
505        match &*self.inner {
506            CommandEncoderStatus::Recording(command_buffer_mutable) => command_buffer_mutable,
507            _ => unreachable!(),
508        }
509    }
510}
511
512impl<'a> ops::DerefMut for RecordingGuard<'a> {
513    fn deref_mut(&mut self) -> &mut Self::Target {
514        match self.inner {
515            CommandEncoderStatus::Recording(command_buffer_mutable) => command_buffer_mutable,
516            _ => unreachable!(),
517        }
518    }
519}
520
521pub struct CommandEncoder {
522    pub(crate) device: Arc<Device>,
523
524    pub(crate) label: String,
525
526    /// The mutable state of this command encoder.
527    pub(crate) data: Mutex<CommandEncoderStatus>,
528}
529
530crate::impl_resource_type!(CommandEncoder);
531crate::impl_labeled!(CommandEncoder);
532crate::impl_parent_device!(CommandEncoder);
533crate::impl_storage_item!(CommandEncoder);
534
535impl Drop for CommandEncoder {
536    #[allow(trivial_casts)]
537    fn drop(&mut self) {
538        profiling::scope!("CommandEncoder::drop");
539        api_log!("CommandEncoder::drop {:?}", self as *const _);
540        resource_log!("Drop {}", self.error_ident());
541    }
542}
543
544/// The encoding API being used with a `CommandEncoder`.
545///
546/// Mixing APIs on the same encoder is not allowed.
547#[derive(Copy, Clone, Debug, Eq, PartialEq)]
548pub enum EncodingApi {
549    // The regular wgpu encoding APIs are being used.
550    Wgpu,
551
552    // The raw hal encoding API is being used.
553    Raw,
554
555    // Neither encoding API has been called yet.
556    Undecided,
557
558    // The encoder is used internally by wgpu.
559    InternalUse,
560}
561
562impl EncodingApi {
563    pub(crate) fn set(&mut self, api: EncodingApi) {
564        match *self {
565            EncodingApi::Undecided => {
566                *self = api;
567            }
568            self_api if self_api != api => {
569                panic!("Mixing the wgpu encoding API with the raw encoding API is not permitted");
570            }
571            _ => {}
572        }
573    }
574}
575
576/// A raw [`CommandEncoder`][rce], and the raw [`CommandBuffer`][rcb]s built from it.
577///
578/// Each wgpu-core [`CommandBuffer`] owns an instance of this type, which is
579/// where the commands are actually stored.
580///
581/// This holds a `Vec` of raw [`CommandBuffer`][rcb]s, not just one. We are not
582/// always able to record commands in the order in which they must ultimately be
583/// submitted to the queue, but raw command buffers don't permit inserting new
584/// commands into the middle of a recorded stream. However, hal queue submission
585/// accepts a series of command buffers at once, so we can simply break the
586/// stream up into multiple buffers, and then reorder the buffers. See
587/// [`InnerCommandEncoder::close_and_swap`] for a specific example of this.
588///
589/// [rce]: hal::Api::CommandEncoder
590/// [rcb]: hal::Api::CommandBuffer
591pub(crate) struct InnerCommandEncoder {
592    /// The underlying `wgpu_hal` [`CommandEncoder`].
593    ///
594    /// Successfully executed command buffers' encoders are saved in a
595    /// [`CommandAllocator`] for recycling.
596    ///
597    /// [`CommandEncoder`]: hal::Api::CommandEncoder
598    /// [`CommandAllocator`]: crate::command::CommandAllocator
599    pub(crate) raw: ManuallyDrop<Box<dyn hal::DynCommandEncoder>>,
600
601    /// All the raw command buffers for our owning [`CommandBuffer`], in
602    /// submission order.
603    ///
604    /// These command buffers were all constructed with `raw`. The
605    /// [`wgpu_hal::CommandEncoder`] trait forbids these from outliving `raw`,
606    /// and requires that we provide all of these when we call
607    /// [`raw.reset_all()`][CE::ra], so the encoder and its buffers travel
608    /// together.
609    ///
610    /// [CE::ra]: hal::CommandEncoder::reset_all
611    /// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
612    pub(crate) list: Vec<Box<dyn hal::DynCommandBuffer>>,
613
614    pub(crate) device: Arc<Device>,
615
616    /// True if `raw` is in the "recording" state.
617    ///
618    /// See the documentation for [`wgpu_hal::CommandEncoder`] for
619    /// details on the states `raw` can be in.
620    ///
621    /// [`wgpu_hal::CommandEncoder`]: hal::CommandEncoder
622    pub(crate) is_open: bool,
623
624    /// Tracks which API is being used to encode commands.
625    ///
626    /// Mixing the wgpu encoding API with access to the raw hal encoder via
627    /// `as_hal_mut` is not supported. this field tracks which API is being used
628    /// in order to detect and reject invalid usage.
629    pub(crate) api: EncodingApi,
630
631    pub(crate) label: String,
632}
633
634impl InnerCommandEncoder {
635    /// Finish the current command buffer and insert it just before
636    /// the last element in [`self.list`][l].
637    ///
638    /// On return, the underlying hal encoder is closed.
639    ///
640    /// What is this for?
641    ///
642    /// The `wgpu_hal` contract requires that each render or compute pass's
643    /// commands be preceded by calls to [`transition_buffers`] and
644    /// [`transition_textures`], to put the resources the pass operates on in
645    /// the appropriate state. Unfortunately, we don't know which transitions
646    /// are needed until we're done recording the pass itself. Rather than
647    /// iterating over the pass twice, we note the necessary transitions as we
648    /// record its commands, finish the raw command buffer for the actual pass,
649    /// record a new raw command buffer for the transitions, and jam that buffer
650    /// in just before the pass's. This is the function that jams in the
651    /// transitions' command buffer.
652    ///
653    /// # Panics
654    ///
655    /// - If the encoder is not open.
656    ///
657    /// # Warning
658    ///
659    /// Any [`DeferredQuerySetResolve::insertion_point`] pointing to the
660    /// last element will be invalidated.
661    ///
662    /// [l]: InnerCommandEncoder::list
663    /// [`transition_buffers`]: hal::CommandEncoder::transition_buffers
664    /// [`transition_textures`]: hal::CommandEncoder::transition_textures
665    /// [`DeferredQuerySetResolve::insertion_point`]: query::DeferredQuerySetResolve::insertion_point
666    fn close_and_swap(&mut self) -> Result<(), DeviceError> {
667        self.close_and_insert_at(self.list.len() - 1)
668    }
669
670    /// Finish the current command buffer and insert it at the beginning
671    /// of [`self.list`][l].
672    ///
673    /// On return, the underlying hal encoder is closed.
674    ///
675    /// # Panics
676    ///
677    /// - If the encoder is not open.
678    ///
679    /// # Warning
680    ///
681    /// All existing [`DeferredQuerySetResolve::insertion_point`] values
682    /// will be invalidated.
683    ///
684    /// [l]: InnerCommandEncoder::list
685    /// [`DeferredQuerySetResolve::insertion_point`]: query::DeferredQuerySetResolve::insertion_point
686    pub(crate) fn close_and_push_front(&mut self) -> Result<(), DeviceError> {
687        self.close_and_insert_at(0)
688    }
689
690    /// Finish the current command buffer and insert it at the given index
691    /// in [`self.list`][l].
692    ///
693    /// On return, the underlying hal encoder is closed.
694    ///
695    /// # Panics
696    ///
697    /// - If the encoder is not open.
698    ///
699    /// # Warning
700    ///
701    /// Any [`DeferredQuerySetResolve::insertion_point`] value that is
702    /// >= `index` will be invalidated.
703    ///
704    /// [l]: InnerCommandEncoder::list
705    /// [`DeferredQuerySetResolve::insertion_point`]: query::DeferredQuerySetResolve::insertion_point
706    pub(crate) fn close_and_insert_at(&mut self, index: usize) -> Result<(), DeviceError> {
707        assert!(self.is_open);
708        self.is_open = false;
709
710        let cmd_buf =
711            unsafe { self.raw.end_encoding() }.map_err(|e| self.device.handle_hal_error(e))?;
712        self.list.insert(index, cmd_buf);
713
714        Ok(())
715    }
716
717    /// Finish the current command buffer, and push it onto
718    /// the end of [`self.list`][l].
719    ///
720    /// On return, the underlying hal encoder is closed.
721    ///
722    /// # Panics
723    ///
724    /// - If the encoder is not open.
725    ///
726    /// [l]: InnerCommandEncoder::list
727    pub(crate) fn close(&mut self) -> Result<(), DeviceError> {
728        assert!(self.is_open);
729        self.is_open = false;
730
731        let cmd_buf =
732            unsafe { self.raw.end_encoding() }.map_err(|e| self.device.handle_hal_error(e))?;
733        self.list.push(cmd_buf);
734
735        Ok(())
736    }
737
738    /// Finish the current command buffer, if any, and add it to the
739    /// end of [`self.list`][l].
740    ///
741    /// If we have opened this command encoder, finish its current
742    /// command buffer, and push it onto the end of [`self.list`][l].
743    /// If this command buffer is closed, do nothing.
744    ///
745    /// On return, the underlying hal encoder is closed.
746    ///
747    /// [l]: InnerCommandEncoder::list
748    fn close_if_open(&mut self) -> Result<(), DeviceError> {
749        if self.is_open {
750            self.is_open = false;
751            let cmd_buf =
752                unsafe { self.raw.end_encoding() }.map_err(|e| self.device.handle_hal_error(e))?;
753            self.list.push(cmd_buf);
754        }
755
756        Ok(())
757    }
758
759    /// If the command encoder is not open, begin recording a new command buffer.
760    ///
761    /// If the command encoder was already open, does nothing.
762    ///
763    /// In both cases, returns a reference to the raw encoder.
764    fn open_if_closed(&mut self) -> Result<&mut dyn hal::DynCommandEncoder, DeviceError> {
765        if !self.is_open {
766            let hal_label = hal_label(Some(self.label.as_str()), self.device.instance_flags);
767            unsafe { self.raw.begin_encoding(hal_label) }
768                .map_err(|e| self.device.handle_hal_error(e))?;
769            self.is_open = true;
770        }
771
772        Ok(self.raw.as_mut())
773    }
774
775    /// Begin recording a new command buffer, if we haven't already.
776    ///
777    /// The underlying hal encoder is put in the "recording" state.
778    pub(crate) fn open(&mut self) -> Result<&mut dyn hal::DynCommandEncoder, DeviceError> {
779        if !self.is_open {
780            let hal_label = hal_label(Some(self.label.as_str()), self.device.instance_flags);
781            unsafe { self.raw.begin_encoding(hal_label) }
782                .map_err(|e| self.device.handle_hal_error(e))?;
783            self.is_open = true;
784        }
785
786        Ok(self.raw.as_mut())
787    }
788
789    /// Begin recording a new command buffer for a render or compute pass, with
790    /// its own label.
791    ///
792    /// The underlying hal encoder is put in the "recording" state.
793    ///
794    /// # Panics
795    ///
796    /// - If the encoder is already open.
797    pub(crate) fn open_pass(
798        &mut self,
799        label: Option<&str>,
800    ) -> Result<&mut dyn hal::DynCommandEncoder, DeviceError> {
801        assert!(!self.is_open);
802
803        let hal_label = hal_label(label, self.device.instance_flags);
804        unsafe { self.raw.begin_encoding(hal_label) }
805            .map_err(|e| self.device.handle_hal_error(e))?;
806        self.is_open = true;
807
808        Ok(self.raw.as_mut())
809    }
810}
811
812impl Drop for InnerCommandEncoder {
813    fn drop(&mut self) {
814        if self.is_open {
815            unsafe { self.raw.discard_encoding() };
816        }
817        unsafe {
818            self.raw.reset_all(mem::take(&mut self.list));
819        }
820        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
821        let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
822        self.device.command_allocator.release_encoder(raw);
823    }
824}
825
826/// Look at the documentation for [`CommandBufferMutable`] for an explanation of
827/// the fields in this struct. This is the "built" counterpart to that type.
828pub(crate) struct BakedCommands {
829    pub(crate) encoder: InnerCommandEncoder,
830    pub(crate) trackers: Tracker,
831    pub(crate) temp_resources: Vec<TempResource>,
832    pub(crate) indirect_draw_validation_resources: crate::indirect_validation::DrawResources,
833    buffer_memory_init_actions: Vec<BufferInitTrackerAction>,
834    texture_memory_actions: CommandBufferTextureMemoryActions,
835    pub(crate) query_set_writes: query::QuerySetWrites,
836    pub(crate) deferred_query_set_resolves: Vec<query::DeferredQuerySetResolve>,
837}
838
839/// The mutable state of a [`CommandBuffer`].
840pub struct CommandBufferMutable {
841    /// The [`wgpu_hal::Api::CommandBuffer`]s we've built so far, and the encoder
842    /// they belong to.
843    ///
844    /// [`wgpu_hal::Api::CommandBuffer`]: hal::Api::CommandBuffer
845    pub(crate) encoder: InnerCommandEncoder,
846
847    /// All the resources that the commands recorded so far have referred to.
848    pub(crate) trackers: Tracker,
849
850    /// The regions of buffers and textures these commands will read and write.
851    ///
852    /// This is used to determine which portions of which
853    /// buffers/textures we actually need to initialize. If we're
854    /// definitely going to write to something before we read from it,
855    /// we don't need to clear its contents.
856    buffer_memory_init_actions: Vec<BufferInitTrackerAction>,
857    texture_memory_actions: CommandBufferTextureMemoryActions,
858
859    as_actions: Vec<AsAction>,
860    temp_resources: Vec<TempResource>,
861
862    indirect_draw_validation_resources: crate::indirect_validation::DrawResources,
863
864    pub(crate) commands: Vec<Command<ArcReferences>>,
865
866    /// If tracing, `command_encoder_finish` replaces the `Arc`s in `commands`
867    /// with integer pointers, and moves them into `trace_commands`.
868    #[cfg(feature = "trace")]
869    pub(crate) trace_commands: Option<Vec<Command<PointerReferences>>>,
870
871    /// Tracks which query slots have been written by commands in this encoder.
872    pub(crate) query_set_writes: query::QuerySetWrites,
873    /// Query set resolves that had to be deferred to submit time.
874    pub(crate) deferred_query_set_resolves: Vec<query::DeferredQuerySetResolve>,
875}
876
877impl CommandBufferMutable {
878    pub(crate) fn into_baked_commands(self) -> BakedCommands {
879        BakedCommands {
880            encoder: self.encoder,
881            trackers: self.trackers,
882            temp_resources: self.temp_resources,
883            indirect_draw_validation_resources: self.indirect_draw_validation_resources,
884            buffer_memory_init_actions: self.buffer_memory_init_actions,
885            texture_memory_actions: self.texture_memory_actions,
886            query_set_writes: self.query_set_writes,
887            deferred_query_set_resolves: self.deferred_query_set_resolves,
888        }
889    }
890}
891
892/// A buffer of commands to be submitted to the GPU for execution.
893///
894/// Once a command buffer is submitted to the queue, its contents are taken
895/// to construct a [`BakedCommands`], whose contents eventually become the
896/// property of the submission queue.
897pub struct CommandBuffer {
898    pub(crate) device: Arc<Device>,
899    /// The `label` from the descriptor used to create the resource.
900    label: String,
901
902    /// The mutable state of this command buffer.
903    pub(crate) data: Mutex<CommandEncoderStatus>,
904}
905
906impl Drop for CommandBuffer {
907    #[allow(trivial_casts)]
908    fn drop(&mut self) {
909        profiling::scope!("CommandBuffer::drop");
910        api_log!("CommandBuffer::drop {:?}", self as *const _);
911        resource_log!("Drop {}", self.error_ident());
912    }
913}
914
915impl CommandEncoder {
916    pub(crate) fn new(
917        encoder: Box<dyn hal::DynCommandEncoder>,
918        device: &Arc<Device>,
919        label: &Label,
920    ) -> Self {
921        CommandEncoder {
922            device: device.clone(),
923            label: label.to_string(),
924            data: Mutex::new(
925                rank::COMMAND_BUFFER_DATA,
926                CommandEncoderStatus::Recording(CommandBufferMutable {
927                    encoder: InnerCommandEncoder {
928                        raw: ManuallyDrop::new(encoder),
929                        list: Vec::new(),
930                        device: device.clone(),
931                        is_open: false,
932                        api: EncodingApi::Undecided,
933                        label: label.to_string(),
934                    },
935                    trackers: Tracker::new(
936                        device.ordered_buffer_usages,
937                        device.ordered_texture_usages,
938                    ),
939                    buffer_memory_init_actions: Default::default(),
940                    texture_memory_actions: Default::default(),
941                    as_actions: Default::default(),
942                    temp_resources: Default::default(),
943                    indirect_draw_validation_resources:
944                        crate::indirect_validation::DrawResources::new(device.clone()),
945                    commands: Vec::new(),
946                    query_set_writes: Default::default(),
947                    deferred_query_set_resolves: Default::default(),
948                    #[cfg(feature = "trace")]
949                    trace_commands: if device.trace.lock().is_some() {
950                        Some(Vec::new())
951                    } else {
952                        None
953                    },
954                }),
955            ),
956        }
957    }
958
959    pub(crate) fn new_invalid(
960        device: &Arc<Device>,
961        label: &Label,
962        err: CommandEncoderError,
963    ) -> Arc<Self> {
964        Arc::new(CommandEncoder {
965            device: device.clone(),
966            label: label.to_string(),
967            data: Mutex::new(rank::COMMAND_BUFFER_DATA, make_error_state(err)),
968        })
969    }
970
971    pub(crate) fn validate_pass_timestamp_writes<E>(
972        device: &Device,
973        timestamp_writes: &PassTimestampWrites<Arc<QuerySet>>,
974    ) -> Result<PassTimestampWrites, E>
975    where
976        E: From<TimestampWritesError>
977            + From<QueryUseError>
978            + From<DeviceError>
979            + From<MissingFeatures>
980            + From<InvalidResourceError>,
981    {
982        let &PassTimestampWrites {
983            ref query_set,
984            beginning_of_pass_write_index,
985            end_of_pass_write_index,
986        } = timestamp_writes;
987
988        device.require_features(wgt::Features::TIMESTAMP_QUERY)?;
989
990        query_set.check_is_valid()?;
991        query_set.same_device(device)?;
992
993        for idx in [beginning_of_pass_write_index, end_of_pass_write_index]
994            .into_iter()
995            .flatten()
996        {
997            query_set.validate_query(SimplifiedQueryType::Timestamp, idx, None)?;
998        }
999
1000        if let Some((begin, end)) = beginning_of_pass_write_index.zip(end_of_pass_write_index) {
1001            if begin == end {
1002                return Err(TimestampWritesError::IndicesEqual { idx: begin }.into());
1003            }
1004        }
1005
1006        if beginning_of_pass_write_index
1007            .or(end_of_pass_write_index)
1008            .is_none()
1009        {
1010            return Err(TimestampWritesError::IndicesMissing.into());
1011        }
1012
1013        Ok(PassTimestampWrites {
1014            query_set: query_set.clone(),
1015            beginning_of_pass_write_index,
1016            end_of_pass_write_index,
1017        })
1018    }
1019
1020    pub(crate) fn insert_barriers_from_tracker(
1021        raw: &mut dyn hal::DynCommandEncoder,
1022        base: &mut Tracker,
1023        head: &Tracker,
1024        snatch_guard: &SnatchGuard,
1025    ) {
1026        profiling::scope!("insert_barriers");
1027
1028        base.buffers.set_from_tracker(&head.buffers);
1029        base.textures.set_from_tracker(&head.textures);
1030
1031        Self::drain_barriers(raw, base, snatch_guard);
1032    }
1033
1034    pub(crate) fn insert_barriers_from_scope(
1035        raw: &mut dyn hal::DynCommandEncoder,
1036        base: &mut Tracker,
1037        head: &UsageScope,
1038        snatch_guard: &SnatchGuard,
1039    ) {
1040        profiling::scope!("insert_barriers");
1041
1042        base.buffers.set_from_usage_scope(&head.buffers);
1043        base.textures.set_from_usage_scope(&head.textures);
1044
1045        Self::drain_barriers(raw, base, snatch_guard);
1046    }
1047
1048    pub(crate) fn drain_barriers(
1049        raw: &mut dyn hal::DynCommandEncoder,
1050        base: &mut Tracker,
1051        snatch_guard: &SnatchGuard,
1052    ) {
1053        profiling::scope!("drain_barriers");
1054
1055        let buffer_barriers = base
1056            .buffers
1057            .drain_transitions(snatch_guard)
1058            .collect::<Vec<_>>();
1059        let (transitions, textures) = base.textures.drain_transitions(snatch_guard);
1060        let texture_barriers = transitions
1061            .into_iter()
1062            .enumerate()
1063            .map(|(i, p)| p.into_hal(textures[i].unwrap().raw()))
1064            .collect::<Vec<_>>();
1065
1066        unsafe {
1067            raw.transition_buffers(&buffer_barriers);
1068            raw.transition_textures(&texture_barriers);
1069        }
1070    }
1071
1072    pub(crate) fn insert_barriers_from_device_tracker(
1073        raw: &mut dyn hal::DynCommandEncoder,
1074        base: &mut DeviceTracker,
1075        head: &Tracker,
1076        snatch_guard: &SnatchGuard,
1077    ) {
1078        profiling::scope!("insert_barriers_from_device_tracker");
1079
1080        let buffer_barriers = base
1081            .buffers
1082            .set_from_tracker_and_drain_transitions(&head.buffers, snatch_guard)
1083            .collect::<Vec<_>>();
1084
1085        let texture_barriers = base
1086            .textures
1087            .set_from_tracker_and_drain_transitions(&head.textures, snatch_guard)
1088            .collect::<Vec<_>>();
1089
1090        unsafe {
1091            raw.transition_buffers(&buffer_barriers);
1092            raw.transition_textures(&texture_barriers);
1093        }
1094    }
1095
1096    fn encode_commands(
1097        device: &Arc<Device>,
1098        cmd_buf_data: &mut CommandBufferMutable,
1099    ) -> Result<(), CommandEncoderError> {
1100        device.check_is_valid()?;
1101        let snatch_guard = device.snatchable_lock.read();
1102        let mut debug_scope_depth = 0;
1103
1104        if cmd_buf_data.encoder.api == EncodingApi::Raw {
1105            // Should have panicked on the first call that switched APIs,
1106            // but lets be sure.
1107            assert!(cmd_buf_data.commands.is_empty());
1108        }
1109
1110        let commands = mem::take(&mut cmd_buf_data.commands);
1111
1112        #[cfg(feature = "trace")]
1113        if device.trace.lock().is_some() {
1114            cmd_buf_data.trace_commands = Some(
1115                commands
1116                    .iter()
1117                    .map(crate::device::trace::IntoTrace::to_trace)
1118                    .collect(),
1119            );
1120        }
1121
1122        for command in commands {
1123            if matches!(
1124                command,
1125                ArcCommand::RunRenderPass { .. }
1126                    | ArcCommand::RunComputePass { .. }
1127                    | ArcCommand::ResolveQuerySet { .. }
1128                    | ArcCommand::RunRayTracingPass { .. }
1129            ) {
1130                // Compute passes and render passes can accept either an
1131                // open or closed encoder. Resolving query sets needs to
1132                // potentially close and open the encoder. This state
1133                // object holds an `InnerCommandEncoder`. See the
1134                // documentation of [`EncodingState`].
1135                let mut state = EncodingState {
1136                    device,
1137                    raw_encoder: &mut cmd_buf_data.encoder,
1138                    tracker: &mut cmd_buf_data.trackers,
1139                    buffer_memory_init_actions: &mut cmd_buf_data.buffer_memory_init_actions,
1140                    texture_memory_actions: &mut cmd_buf_data.texture_memory_actions,
1141                    as_actions: &mut cmd_buf_data.as_actions,
1142                    temp_resources: &mut cmd_buf_data.temp_resources,
1143                    indirect_draw_validation_resources: &mut cmd_buf_data
1144                        .indirect_draw_validation_resources,
1145                    snatch_guard: &snatch_guard,
1146                    debug_scope_depth: &mut debug_scope_depth,
1147                    query_set_writes: &mut cmd_buf_data.query_set_writes,
1148                    deferred_query_set_resolves: &mut cmd_buf_data.deferred_query_set_resolves,
1149                };
1150
1151                match command {
1152                    ArcCommand::RunRenderPass {
1153                        pass,
1154                        color_attachments,
1155                        depth_stencil_attachment,
1156                        timestamp_writes,
1157                        occlusion_query_set,
1158                        multiview_mask,
1159                    } => {
1160                        api_log!(
1161                            "Begin encoding render pass with '{}' label",
1162                            pass.label.as_deref().unwrap_or("")
1163                        );
1164                        let res = render::encode_render_pass(
1165                            &mut state,
1166                            pass,
1167                            color_attachments,
1168                            depth_stencil_attachment,
1169                            timestamp_writes,
1170                            occlusion_query_set,
1171                            multiview_mask,
1172                        );
1173                        match res.as_ref() {
1174                            Err(err) => {
1175                                api_log!("Finished encoding render pass ({err:?})")
1176                            }
1177                            Ok(_) => {
1178                                api_log!("Finished encoding render pass (success)")
1179                            }
1180                        }
1181                        res?;
1182                    }
1183                    ArcCommand::RunComputePass {
1184                        pass,
1185                        timestamp_writes,
1186                    } => {
1187                        api_log!(
1188                            "Begin encoding compute pass with '{}' label",
1189                            pass.label.as_deref().unwrap_or("")
1190                        );
1191                        let res = compute::encode_compute_pass(&mut state, pass, timestamp_writes);
1192                        match res.as_ref() {
1193                            Err(err) => {
1194                                api_log!("Finished encoding compute pass ({err:?})")
1195                            }
1196                            Ok(_) => {
1197                                api_log!("Finished encoding compute pass (success)")
1198                            }
1199                        }
1200                        res?;
1201                    }
1202                    ArcCommand::ResolveQuerySet {
1203                        query_set,
1204                        start_query,
1205                        query_count,
1206                        destination,
1207                        destination_offset,
1208                    } => {
1209                        query::resolve_query_set(
1210                            &mut state,
1211                            query_set,
1212                            start_query,
1213                            query_count,
1214                            destination,
1215                            destination_offset,
1216                        )?;
1217                    }
1218                    ArcCommand::RunRayTracingPass { pass } => {
1219                        api_log!(
1220                            "Begin encoding ray tracing pass with '{}' label",
1221                            pass.label.as_deref().unwrap_or("")
1222                        );
1223                        let res = ray_tracing_pass::encode_ray_tracing_pass(&mut state, pass);
1224                        match res.as_ref() {
1225                            Err(err) => {
1226                                api_log!("Finished encoding ray tracing pass ({err:?})")
1227                            }
1228                            Ok(_) => {
1229                                api_log!("Finished encoding ray tracing pass (success)")
1230                            }
1231                        }
1232                        res?;
1233                    }
1234                    _ => unreachable!(),
1235                }
1236            } else {
1237                // All the other non-pass encoding routines assume the
1238                // encoder is open, so open it if necessary. This state
1239                // object holds an `&mut dyn hal::DynCommandEncoder`. By
1240                // convention, a bare HAL encoder reference in
1241                // [`EncodingState`] must always be an open encoder.
1242                let raw_encoder = cmd_buf_data.encoder.open_if_closed()?;
1243                let mut state = EncodingState {
1244                    device,
1245                    raw_encoder,
1246                    tracker: &mut cmd_buf_data.trackers,
1247                    buffer_memory_init_actions: &mut cmd_buf_data.buffer_memory_init_actions,
1248                    texture_memory_actions: &mut cmd_buf_data.texture_memory_actions,
1249                    as_actions: &mut cmd_buf_data.as_actions,
1250                    temp_resources: &mut cmd_buf_data.temp_resources,
1251                    indirect_draw_validation_resources: &mut cmd_buf_data
1252                        .indirect_draw_validation_resources,
1253                    snatch_guard: &snatch_guard,
1254                    debug_scope_depth: &mut debug_scope_depth,
1255                    query_set_writes: &mut cmd_buf_data.query_set_writes,
1256                    deferred_query_set_resolves: &mut cmd_buf_data.deferred_query_set_resolves,
1257                };
1258                match command {
1259                    ArcCommand::CopyBufferToBuffer {
1260                        src,
1261                        src_offset,
1262                        dst,
1263                        dst_offset,
1264                        size,
1265                    } => {
1266                        transfer::copy_buffer_to_buffer(
1267                            &mut state, &src, src_offset, &dst, dst_offset, size,
1268                        )?;
1269                    }
1270                    ArcCommand::CopyBufferToTexture { src, dst, size } => {
1271                        transfer::copy_buffer_to_texture(&mut state, &src, &dst, &size)?;
1272                    }
1273                    ArcCommand::CopyTextureToBuffer { src, dst, size } => {
1274                        transfer::copy_texture_to_buffer(&mut state, &src, &dst, &size)?;
1275                    }
1276                    ArcCommand::CopyTextureToTexture { src, dst, size } => {
1277                        transfer::copy_texture_to_texture(&mut state, &src, &dst, &size)?;
1278                    }
1279                    ArcCommand::ClearBuffer { dst, offset, size } => {
1280                        clear::clear_buffer(&mut state, dst, offset, size)?;
1281                    }
1282                    ArcCommand::ClearTexture {
1283                        dst,
1284                        subresource_range,
1285                    } => {
1286                        clear::clear_texture_cmd(&mut state, dst, &subresource_range)?;
1287                    }
1288                    ArcCommand::WriteTimestamp {
1289                        query_set,
1290                        query_index,
1291                    } => {
1292                        query::write_timestamp(&mut state, query_set, query_index)?;
1293                    }
1294                    ArcCommand::PushDebugGroup(label) => {
1295                        push_debug_group(&mut state, &label)?;
1296                    }
1297                    ArcCommand::PopDebugGroup => {
1298                        pop_debug_group(&mut state)?;
1299                    }
1300                    ArcCommand::InsertDebugMarker(label) => {
1301                        insert_debug_marker(&mut state, &label)?;
1302                    }
1303                    ArcCommand::BuildAccelerationStructures { blas, tlas } => {
1304                        ray_tracing::build_acceleration_structures(&mut state, blas, tlas)?;
1305                    }
1306                    ArcCommand::TransitionResources {
1307                        buffer_transitions,
1308                        texture_transitions,
1309                    } => {
1310                        transition_resources::transition_resources(
1311                            &mut state,
1312                            buffer_transitions,
1313                            texture_transitions,
1314                        )?;
1315                    }
1316                    ArcCommand::RunComputePass { .. }
1317                    | ArcCommand::RunRenderPass { .. }
1318                    | ArcCommand::ResolveQuerySet { .. }
1319                    | ArcCommand::RunRayTracingPass { .. } => {
1320                        unreachable!()
1321                    }
1322                }
1323            }
1324        }
1325
1326        if debug_scope_depth > 0 {
1327            Err(CommandEncoderError::DebugGroupError(
1328                DebugGroupError::MissingPop,
1329            ))?;
1330        }
1331
1332        // Close the encoder, unless it was closed already by a render or compute pass.
1333        cmd_buf_data.encoder.close_if_open()?;
1334
1335        // Note: if we want to stop tracking the swapchain texture view,
1336        // this is the place to do it.
1337
1338        Ok(())
1339    }
1340
1341    /// Finishes a command encoder, creating a command buffer and returning errors that were
1342    /// deferred until now.
1343    fn finish_inner(
1344        self: &Arc<Self>,
1345        desc: &wgt::CommandBufferDescriptor<Label>,
1346    ) -> (Arc<CommandBuffer>, Option<CommandEncoderError>) {
1347        profiling::scope!("CommandEncoder::finish");
1348
1349        let status = self.data.lock().finish();
1350
1351        let res = match status {
1352            CommandEncoderStatus::Finished(mut cmd_buf_data) => {
1353                match Self::encode_commands(&self.device, &mut cmd_buf_data) {
1354                    Ok(()) => Ok(cmd_buf_data),
1355                    Err(error) => Err(EncoderErrorState {
1356                        error,
1357                        #[cfg(feature = "trace")]
1358                        trace_commands: mem::take(&mut cmd_buf_data.trace_commands),
1359                    }),
1360                }
1361            }
1362            CommandEncoderStatus::Error(error_state) => Err(error_state),
1363            _ => unreachable!(),
1364        };
1365
1366        let (data, error) = match res {
1367            Err(EncoderErrorState {
1368                error,
1369                #[cfg(feature = "trace")]
1370                trace_commands,
1371            }) => {
1372                // Normally, commands are added to the trace when submitted, but
1373                // since this command buffer won't be submitted, add it to the
1374                // trace now.
1375                #[cfg(feature = "trace")]
1376                if let Some(trace) = self.device.trace.lock().as_mut() {
1377                    use alloc::string::ToString;
1378
1379                    trace.add(crate::device::trace::Action::FailedCommands {
1380                        commands: trace_commands,
1381                        failed_at_submit: None,
1382                        error: error.to_string(),
1383                    });
1384                }
1385
1386                if error.is_destroyed_error() {
1387                    // Errors related to destroyed resources are not reported until the
1388                    // command buffer is submitted.
1389                    (make_error_state(error), None)
1390                } else {
1391                    (make_error_state(error.clone()), Some(error))
1392                }
1393            }
1394
1395            Ok(data) => (CommandEncoderStatus::Finished(data), None),
1396        };
1397
1398        let cmd_buf = Arc::new(CommandBuffer {
1399            device: self.device.clone(),
1400            label: desc.label.to_string(),
1401            data: Mutex::new(rank::COMMAND_BUFFER_DATA, data),
1402        });
1403
1404        (cmd_buf, error)
1405    }
1406
1407    pub fn finish(
1408        self: &Arc<Self>,
1409        desc: &wgt::CommandBufferDescriptor<Label>,
1410    ) -> Arc<CommandBuffer> {
1411        let (cmd_buf, error) = self.finish_inner(desc);
1412        if let Some(error) = error {
1413            self.device
1414                .handle_error(error, Some(self.label()), "CommandEncoder::finish");
1415        }
1416        cmd_buf
1417    }
1418}
1419
1420impl CommandBuffer {
1421    /// Replay commands from a trace.
1422    ///
1423    /// This is exposed for the `player` crate only. It is not a public API.
1424    /// It is not guaranteed to apply all of the validation that the original
1425    /// entrypoints provide.
1426    #[doc(hidden)]
1427    pub fn from_trace(device: &Arc<Device>, commands: Vec<Command<ArcReferences>>) -> Arc<Self> {
1428        let encoder = device.create_command_encoder(&wgt::CommandEncoderDescriptor { label: None });
1429        let mut cmd_enc_status = encoder.data.lock();
1430        cmd_enc_status.replay(commands);
1431        drop(cmd_enc_status);
1432
1433        encoder.finish(&wgt::CommandBufferDescriptor { label: None })
1434    }
1435
1436    pub fn take_finished(&self) -> Result<CommandBufferMutable, CommandEncoderError> {
1437        use CommandEncoderStatus as St;
1438        match mem::replace(
1439            &mut *self.data.lock(),
1440            make_error_state(EncoderStateError::Submitted),
1441        ) {
1442            St::Finished(command_buffer_mutable) => Ok(command_buffer_mutable),
1443            St::Error(EncoderErrorState {
1444                #[cfg(feature = "trace")]
1445                    trace_commands: _,
1446                error,
1447            }) => Err(error),
1448            St::Recording(_) | St::Locked(_) | St::Consumed | St::Transitioning => unreachable!(),
1449        }
1450    }
1451}
1452
1453crate::impl_resource_type!(CommandBuffer);
1454crate::impl_labeled!(CommandBuffer);
1455crate::impl_parent_device!(CommandBuffer);
1456crate::impl_storage_item!(CommandBuffer);
1457
1458/// A stream of commands for a render pass or compute pass.
1459///
1460/// This also contains side tables referred to by certain commands,
1461/// like dynamic offsets for [`SetBindGroup`] or string data for
1462/// [`InsertDebugMarker`].
1463///
1464/// Render passes use `BasePass<RenderCommand>`, whereas compute
1465/// passes use `BasePass<ComputeCommand>`.
1466///
1467/// [`SetBindGroup`]: RenderCommand::SetBindGroup
1468/// [`InsertDebugMarker`]: RenderCommand::InsertDebugMarker
1469#[doc(hidden)]
1470#[derive(Debug, Clone)]
1471#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1472pub struct BasePass<C, E> {
1473    pub label: Option<String>,
1474
1475    /// If the pass is invalid, contains the error that caused the invalidation.
1476    ///
1477    /// If the pass is valid, this is `None`.
1478    ///
1479    /// Passes are serialized into traces. but we don't support doing so for
1480    /// passes containing errors. These serde attributes allow `E` to be
1481    /// `Infallible`.
1482    #[cfg_attr(feature = "serde", serde(skip, default = "Option::default"))]
1483    pub error: Option<E>,
1484
1485    /// The stream of commands.
1486    ///
1487    /// The commands are moved out of this vector when the pass is ended (i.e.
1488    /// at the same time that `parent` is taken out of the
1489    /// `ComputePass`/`RenderPass`).
1490    pub commands: Vec<C>,
1491
1492    /// Dynamic offsets consumed by [`SetBindGroup`] commands in `commands`.
1493    ///
1494    /// Each successive `SetBindGroup` consumes the next
1495    /// [`num_dynamic_offsets`] values from this list.
1496    pub dynamic_offsets: Vec<wgt::DynamicOffset>,
1497
1498    /// Strings used by debug instructions.
1499    ///
1500    /// Each successive [`PushDebugGroup`] or [`InsertDebugMarker`]
1501    /// instruction consumes the next `len` bytes from this vector.
1502    pub string_data: Vec<u8>,
1503}
1504
1505impl<C: Clone, E: Clone> BasePass<C, E> {
1506    fn new(label: &Label) -> Self {
1507        Self {
1508            label: label.as_deref().map(str::to_owned),
1509            error: None,
1510            commands: Vec::new(),
1511            dynamic_offsets: Vec::new(),
1512            string_data: Vec::new(),
1513        }
1514    }
1515
1516    fn new_invalid(label: &Label, err: E) -> Self {
1517        Self {
1518            label: label.as_deref().map(str::to_owned),
1519            error: Some(err),
1520            commands: Vec::new(),
1521            dynamic_offsets: Vec::new(),
1522            string_data: Vec::new(),
1523        }
1524    }
1525
1526    /// Takes the commands from the pass, or returns an error if the pass is
1527    /// invalid.
1528    ///
1529    /// This is called when the pass is ended, at the same time that the
1530    /// `parent` member of the `ComputePass` or `RenderPass` containing the pass
1531    /// is taken.
1532    fn take(&mut self) -> Result<BasePass<C, Infallible>, E> {
1533        match self.error.as_ref() {
1534            Some(err) => Err(err.clone()),
1535            None => Ok(BasePass {
1536                label: self.label.clone(),
1537                error: None,
1538                commands: mem::take(&mut self.commands),
1539                dynamic_offsets: mem::take(&mut self.dynamic_offsets),
1540                string_data: mem::take(&mut self.string_data),
1541            }),
1542        }
1543    }
1544}
1545
1546/// Checks the state of a [`compute::ComputePass`] or [`render::RenderPass`] and
1547/// evaluates to a mutable reference to the [`BasePass`], if the pass is open and
1548/// valid.
1549///
1550/// If the pass is ended or not valid, **returns from the invoking function**,
1551/// like the `?` operator.
1552///
1553/// If the pass is ended (i.e. the application is attempting to record a command
1554/// on a finished pass), returns `Err(EncoderStateError::Ended)` from the
1555/// invoking function, for immediate propagation as a validation error.
1556///
1557/// If the pass is open but invalid (i.e. a previous command encountered an
1558/// error), returns `Ok(())` from the invoking function. The pass should already
1559/// have stored the previous error, which will be transferred to the parent
1560/// encoder when the pass is ended, and then raised as a validation error when
1561/// `finish()` is called for the parent).
1562///
1563/// Although in many cases the functionality of `pass_base!` could be achieved
1564/// by combining a helper method on the passes with the `pass_try!` macro,
1565/// taking the mutable reference to the base pass in a macro avoids borrowing
1566/// conflicts when a reference to some other member of the pass struct is
1567/// needed simultaneously with the base pass reference.
1568macro_rules! pass_base {
1569    ($pass:expr, $scope:expr $(,)?) => {
1570        match (&$pass.parent, &$pass.base.error) {
1571            // Pass is ended
1572            (&None, _) => return Err(EncoderStateError::Ended).map_pass_err($scope),
1573            // Pass is invalid
1574            (&Some(_), &Some(_)) => return Ok(()),
1575            // Pass is open and valid
1576            (&Some(_), &None) => &mut $pass.base,
1577        }
1578    };
1579}
1580pub(crate) use pass_base;
1581
1582/// Handles the error case in an expression of type `Result<T, E>`.
1583///
1584/// This macro operates like the `?` operator (or, in early Rust versions, the
1585/// `try!` macro, hence the name `pass_try`). **When there is an error, the
1586/// macro returns from the invoking function.** However, `Ok(())`, and not the
1587/// error itself, is returned. The error is stored in the pass and will later be
1588/// transferred to the parent encoder when the pass ends, and then raised as a
1589/// validation error when `finish()` is called for the parent.
1590///
1591/// `pass_try!` also calls [`MapPassErr::map_pass_err`] to annotate the error
1592/// with the command being encoded at the time it occurred.
1593macro_rules! pass_try {
1594    ($base:expr, $scope:expr, $res:expr $(,)?) => {
1595        match $res.map_pass_err($scope) {
1596            Ok(val) => val,
1597            Err(err) => {
1598                $base.error.get_or_insert(err);
1599                return Ok(());
1600            }
1601        }
1602    };
1603}
1604pub(crate) use pass_try;
1605
1606/// Errors related to the state of a command or pass encoder.
1607///
1608/// The exact behavior of these errors may change based on the resolution of
1609/// <https://github.com/gpuweb/gpuweb/issues/5207>.
1610#[derive(Clone, Debug, Error)]
1611#[non_exhaustive]
1612pub enum EncoderStateError {
1613    /// Used internally by wgpu functions to indicate the encoder already
1614    /// contained an error. This variant should usually not be seen by users of
1615    /// the API, since an effort should be made to provide the caller with a
1616    /// more specific reason for the encoder being invalid.
1617    #[error("Encoder is invalid")]
1618    Invalid,
1619
1620    /// Returned immediately when an attempt is made to encode a command using
1621    /// an encoder that has already finished.
1622    #[error("Encoding must not have ended")]
1623    Ended,
1624
1625    /// Returned by a subsequent call to `encoder.finish()`, if there was an
1626    /// attempt to open a second pass on the encoder while it was locked for
1627    /// a first pass (i.e. the first pass was still open).
1628    ///
1629    /// Note: only command encoders can be locked (not pass encoders).
1630    #[error("Encoder is locked by a previously created render/compute pass. Before recording any new commands, the pass must be ended.")]
1631    Locked,
1632
1633    /// Returned when attempting to end a pass if the parent encoder is not
1634    /// locked. This can only happen if pass begin/end calls are mismatched.
1635    #[error(
1636        "Encoder is not currently locked. A pass can only be ended while the encoder is locked."
1637    )]
1638    Unlocked,
1639
1640    /// The command buffer has already been submitted.
1641    ///
1642    /// Although command encoders and command buffers are distinct WebGPU
1643    /// objects, we use `CommandEncoderStatus` for both.
1644    #[error("This command buffer has already been submitted.")]
1645    Submitted,
1646}
1647
1648impl WebGpuError for EncoderStateError {
1649    fn webgpu_error_type(&self) -> ErrorType {
1650        match self {
1651            EncoderStateError::Invalid
1652            | EncoderStateError::Ended
1653            | EncoderStateError::Locked
1654            | EncoderStateError::Unlocked
1655            | EncoderStateError::Submitted => ErrorType::Validation,
1656        }
1657    }
1658}
1659
1660#[derive(Clone, Debug, Error)]
1661#[non_exhaustive]
1662pub enum CommandEncoderError {
1663    #[error(transparent)]
1664    State(#[from] EncoderStateError),
1665    #[error(transparent)]
1666    Device(#[from] DeviceError),
1667    #[error(transparent)]
1668    InvalidResource(#[from] InvalidResourceError),
1669    #[error(transparent)]
1670    DestroyedResource(#[from] DestroyedResourceError),
1671    #[error(transparent)]
1672    ResourceUsage(#[from] ResourceUsageCompatibilityError),
1673    #[error(transparent)]
1674    DebugGroupError(#[from] DebugGroupError),
1675    #[error(transparent)]
1676    MissingFeatures(#[from] MissingFeatures),
1677    #[error(transparent)]
1678    Transfer(#[from] TransferError),
1679    #[error(transparent)]
1680    Clear(#[from] ClearError),
1681    #[error(transparent)]
1682    Query(#[from] QueryError),
1683    #[error(transparent)]
1684    BuildAccelerationStructure(#[from] BuildAccelerationStructureError),
1685    #[error(transparent)]
1686    TransitionResources(#[from] TransitionResourcesError),
1687    #[error(transparent)]
1688    ComputePass(#[from] ComputePassError),
1689    #[error(transparent)]
1690    RenderPass(#[from] RenderPassError),
1691    #[error(transparent)]
1692    RayTracingPass(#[from] RayTracingPassError),
1693}
1694
1695impl From<InvalidOrDestroyedResourceError> for CommandEncoderError {
1696    fn from(err: InvalidOrDestroyedResourceError) -> Self {
1697        match err {
1698            InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
1699            InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
1700        }
1701    }
1702}
1703
1704impl CommandEncoderError {
1705    fn is_destroyed_error(&self) -> bool {
1706        matches!(
1707            self,
1708            Self::DestroyedResource(_)
1709                | Self::Clear(ClearError::DestroyedResource(_))
1710                | Self::Query(QueryError::DestroyedResource(_))
1711                | Self::ComputePass(ComputePassError {
1712                    inner: ComputePassErrorInner::DestroyedResource(_),
1713                    ..
1714                })
1715        ) || if let Self::RenderPass(pass_error) = self {
1716            matches!(
1717                pass_error.inner.as_ref(),
1718                RenderPassErrorInner::DestroyedResource(_)
1719                    | RenderPassErrorInner::RenderCommand(RenderCommandError::DestroyedResource(_))
1720                    | RenderPassErrorInner::RenderCommand(RenderCommandError::BindingError(
1721                        BindingError::DestroyedResource(_),
1722                    ))
1723            )
1724        } else {
1725            false
1726        }
1727    }
1728}
1729
1730impl WebGpuError for CommandEncoderError {
1731    fn webgpu_error_type(&self) -> ErrorType {
1732        match self {
1733            Self::Device(e) => e.webgpu_error_type(),
1734            Self::InvalidResource(e) => e.webgpu_error_type(),
1735            Self::DebugGroupError(e) => e.webgpu_error_type(),
1736            Self::MissingFeatures(e) => e.webgpu_error_type(),
1737            Self::State(e) => e.webgpu_error_type(),
1738            Self::DestroyedResource(e) => e.webgpu_error_type(),
1739            Self::Transfer(e) => e.webgpu_error_type(),
1740            Self::Clear(e) => e.webgpu_error_type(),
1741            Self::Query(e) => e.webgpu_error_type(),
1742            Self::BuildAccelerationStructure(e) => e.webgpu_error_type(),
1743            Self::TransitionResources(e) => e.webgpu_error_type(),
1744            Self::ResourceUsage(e) => e.webgpu_error_type(),
1745            Self::ComputePass(e) => e.webgpu_error_type(),
1746            Self::RenderPass(e) => e.webgpu_error_type(),
1747            Self::RayTracingPass(e) => e.webgpu_error_type(),
1748        }
1749    }
1750}
1751
1752#[derive(Clone, Debug, Error)]
1753#[non_exhaustive]
1754pub enum DebugGroupError {
1755    #[error("Cannot pop debug group, because number of pushed debug groups is zero")]
1756    InvalidPop,
1757    #[error("A debug group was not popped before the encoder was finished")]
1758    MissingPop,
1759}
1760
1761impl WebGpuError for DebugGroupError {
1762    fn webgpu_error_type(&self) -> ErrorType {
1763        match self {
1764            Self::InvalidPop | Self::MissingPop => ErrorType::Validation,
1765        }
1766    }
1767}
1768
1769#[derive(Clone, Debug, Error)]
1770#[non_exhaustive]
1771pub enum TimestampWritesError {
1772    #[error(
1773        "begin and end indices of pass timestamp writes are both set to {idx}, which is not allowed"
1774    )]
1775    IndicesEqual { idx: u32 },
1776    #[error("no begin or end indices were specified for pass timestamp writes, expected at least one to be set")]
1777    IndicesMissing,
1778}
1779
1780impl WebGpuError for TimestampWritesError {
1781    fn webgpu_error_type(&self) -> ErrorType {
1782        match self {
1783            Self::IndicesEqual { .. } | Self::IndicesMissing => ErrorType::Validation,
1784        }
1785    }
1786}
1787
1788impl CommandEncoder {
1789    fn push_debug_group_inner(self: &Arc<Self>, label: &str) -> Result<(), EncoderStateError> {
1790        profiling::scope!("CommandEncoder::push_debug_group");
1791        api_log!("CommandEncoder::push_debug_group {label}");
1792
1793        let mut cmd_buf_data = self.data.lock();
1794
1795        cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> {
1796            Ok(ArcCommand::PushDebugGroup(label.to_owned()))
1797        })
1798    }
1799
1800    pub fn push_debug_group(self: &Arc<Self>, label: &str) {
1801        if let Err(err) = self.push_debug_group_inner(label) {
1802            self.device
1803                .handle_error(err, Some(self.label()), "CommandEncoder::push_debug_group");
1804        }
1805    }
1806
1807    fn insert_debug_marker_inner(self: &Arc<Self>, label: &str) -> Result<(), EncoderStateError> {
1808        profiling::scope!("CommandEncoder::insert_debug_marker");
1809        api_log!("CommandEncoder::insert_debug_marker {label}");
1810
1811        let mut cmd_buf_data = self.data.lock();
1812
1813        cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> {
1814            Ok(ArcCommand::InsertDebugMarker(label.to_owned()))
1815        })
1816    }
1817
1818    pub fn insert_debug_marker(self: &Arc<Self>, label: &str) {
1819        if let Err(err) = self.insert_debug_marker_inner(label) {
1820            self.device.handle_error(
1821                err,
1822                Some(self.label()),
1823                "CommandEncoder::insert_debug_marker",
1824            );
1825        }
1826    }
1827
1828    fn pop_debug_group_inner(self: &Arc<Self>) -> Result<(), EncoderStateError> {
1829        profiling::scope!("CommandEncoder::pop_debug_marker");
1830        api_log!("CommandEncoder::pop_debug_group");
1831
1832        let mut cmd_buf_data = self.data.lock();
1833
1834        cmd_buf_data
1835            .push_with(|| -> Result<_, CommandEncoderError> { Ok(ArcCommand::PopDebugGroup) })
1836    }
1837
1838    pub fn pop_debug_group(self: &Arc<Self>) {
1839        if let Err(err) = self.pop_debug_group_inner() {
1840            self.device
1841                .handle_error(err, Some(self.label()), "CommandEncoder::pop_debug_group");
1842        }
1843    }
1844}
1845
1846pub(crate) fn push_debug_group(
1847    state: &mut EncodingState,
1848    label: &str,
1849) -> Result<(), CommandEncoderError> {
1850    *state.debug_scope_depth += 1;
1851
1852    if !state
1853        .device
1854        .instance_flags
1855        .contains(wgt::InstanceFlags::DISCARD_HAL_LABELS)
1856    {
1857        unsafe { state.raw_encoder.begin_debug_marker(label) };
1858    }
1859
1860    Ok(())
1861}
1862
1863pub(crate) fn insert_debug_marker(
1864    state: &mut EncodingState,
1865    label: &str,
1866) -> Result<(), CommandEncoderError> {
1867    if !state
1868        .device
1869        .instance_flags
1870        .contains(wgt::InstanceFlags::DISCARD_HAL_LABELS)
1871    {
1872        unsafe { state.raw_encoder.insert_debug_marker(label) };
1873    }
1874
1875    Ok(())
1876}
1877
1878pub(crate) fn pop_debug_group(state: &mut EncodingState) -> Result<(), CommandEncoderError> {
1879    if *state.debug_scope_depth == 0 {
1880        return Err(DebugGroupError::InvalidPop.into());
1881    }
1882    *state.debug_scope_depth -= 1;
1883
1884    if !state
1885        .device
1886        .instance_flags
1887        .contains(wgt::InstanceFlags::DISCARD_HAL_LABELS)
1888    {
1889        unsafe { state.raw_encoder.end_debug_marker() };
1890    }
1891
1892    Ok(())
1893}
1894
1895#[derive(Debug, Copy, Clone)]
1896struct StateChange<T> {
1897    last_state: Option<T>,
1898}
1899
1900impl<T: Clone + PartialEq_> StateChange<T> {
1901    const fn new() -> Self {
1902        Self { last_state: None }
1903    }
1904
1905    fn set_and_check_redundant(&mut self, new_state: &T) -> bool {
1906        let already_set = self.last_state.as_ref().is_some_and(|s| s.eq(new_state));
1907        if !already_set {
1908            self.last_state = Some(new_state.clone());
1909        }
1910        already_set
1911    }
1912
1913    fn reset(&mut self) {
1914        self.last_state = None;
1915    }
1916}
1917
1918impl<T: Clone + PartialEq_> Default for StateChange<T> {
1919    fn default() -> Self {
1920        Self::new()
1921    }
1922}
1923
1924trait PartialEq_ {
1925    fn eq(&self, other: &Self) -> bool;
1926}
1927
1928impl<T> PartialEq_ for Arc<T> {
1929    fn eq(&self, other: &Self) -> bool {
1930        Arc::ptr_eq(self, other)
1931    }
1932}
1933
1934impl<T: PartialEq_> PartialEq_ for Option<T> {
1935    fn eq(&self, other: &Self) -> bool {
1936        match (self, other) {
1937            (Some(a), Some(b)) => a.eq(b),
1938            (None, None) => true,
1939            _ => false,
1940        }
1941    }
1942}
1943
1944#[derive(Debug)]
1945struct BindGroupStateChange {
1946    last_states: [StateChange<Option<Arc<BindGroup>>>; hal::MAX_BIND_GROUPS],
1947}
1948
1949impl BindGroupStateChange {
1950    fn new() -> Self {
1951        Self {
1952            last_states: [const { StateChange::new() }; hal::MAX_BIND_GROUPS],
1953        }
1954    }
1955
1956    fn set_and_check_redundant(
1957        &mut self,
1958        bind_group: &Option<Arc<BindGroup>>,
1959        index: u32,
1960        dynamic_offsets: &mut Vec<u32>,
1961        offsets: &[wgt::DynamicOffset],
1962    ) -> bool {
1963        // For now never deduplicate bind groups with dynamic offsets.
1964        if offsets.is_empty() {
1965            // If this get returns None, that means we're well over the limit,
1966            // so let the call through to get a proper error
1967            if let Some(current_bind_group) = self.last_states.get_mut(index as usize) {
1968                // Bail out if we're binding the same bind group.
1969                if current_bind_group.set_and_check_redundant(bind_group) {
1970                    return true;
1971                }
1972            }
1973        } else {
1974            // We intentionally remove the memory of this bind group if we have dynamic offsets,
1975            // such that if you try to bind this bind group later with _no_ dynamic offsets it
1976            // tries to bind it again and gives a proper validation error.
1977            if let Some(current_bind_group) = self.last_states.get_mut(index as usize) {
1978                current_bind_group.reset();
1979            }
1980            dynamic_offsets.extend_from_slice(offsets);
1981        }
1982        false
1983    }
1984    fn reset(&mut self) {
1985        self.last_states = [const { StateChange::new() }; hal::MAX_BIND_GROUPS];
1986    }
1987}
1988
1989impl Default for BindGroupStateChange {
1990    fn default() -> Self {
1991        Self::new()
1992    }
1993}
1994
1995/// Helper to attach [`PassErrorScope`] to errors.
1996trait MapPassErr<T> {
1997    fn map_pass_err(self, scope: PassErrorScope) -> T;
1998}
1999
2000impl<T, E, F> MapPassErr<Result<T, F>> for Result<T, E>
2001where
2002    E: MapPassErr<F>,
2003{
2004    fn map_pass_err(self, scope: PassErrorScope) -> Result<T, F> {
2005        self.map_err(|err| err.map_pass_err(scope))
2006    }
2007}
2008
2009impl MapPassErr<PassStateError> for EncoderStateError {
2010    fn map_pass_err(self, scope: PassErrorScope) -> PassStateError {
2011        PassStateError { scope, inner: self }
2012    }
2013}
2014
2015#[derive(Clone, Copy, Debug)]
2016pub enum DrawKind {
2017    Draw,
2018    DrawIndirect,
2019    MultiDrawIndirect,
2020    MultiDrawIndirectCount,
2021}
2022
2023/// The type of draw command(indexed or not, or mesh shader)
2024#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2025#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2026pub enum DrawCommandFamily {
2027    Draw,
2028    DrawIndexed,
2029    DrawMeshTasks,
2030}
2031
2032/// A command that can be recorded in a pass or bundle.
2033///
2034/// This is used to provide context for errors during command recording.
2035/// [`MapPassErr`] is used as a helper to attach a `PassErrorScope` to
2036/// an error.
2037///
2038/// The [`PassErrorScope::Bundle`] and [`PassErrorScope::Pass`] variants
2039/// are used when the error occurs during the opening or closing of the
2040/// pass or bundle.
2041#[derive(Clone, Copy, Debug, Error)]
2042pub enum PassErrorScope {
2043    // TODO: Extract out the 2 error variants below so that we can always
2044    // include the ResourceErrorIdent of the pass around all inner errors
2045    #[error("In a bundle parameter")]
2046    Bundle,
2047    #[error("In a pass parameter")]
2048    Pass,
2049    #[error("In a set_bind_group command")]
2050    SetBindGroup,
2051    #[error("In a set_pipeline command")]
2052    SetPipelineRender,
2053    #[error("In a set_pipeline command")]
2054    SetPipelineCompute,
2055    #[error("In a set_pipeline command")]
2056    SetPipelineRayTracing,
2057    #[error("In a set_immediates command")]
2058    SetImmediate,
2059    #[error("In a set_vertex_buffer command")]
2060    SetVertexBuffer,
2061    #[error("In a set_index_buffer command")]
2062    SetIndexBuffer,
2063    #[error("In a set_blend_constant command")]
2064    SetBlendConstant,
2065    #[error("In a set_stencil_reference command")]
2066    SetStencilReference,
2067    #[error("In a set_viewport command")]
2068    SetViewport,
2069    #[error("In a set_scissor_rect command")]
2070    SetScissorRect,
2071    #[error("In a draw command, kind: {kind:?}")]
2072    Draw {
2073        kind: DrawKind,
2074        family: DrawCommandFamily,
2075    },
2076    #[error("In a write_timestamp command")]
2077    WriteTimestamp,
2078    #[error("In a begin_occlusion_query command")]
2079    BeginOcclusionQuery,
2080    #[error("In a end_occlusion_query command")]
2081    EndOcclusionQuery,
2082    #[error("In a begin_pipeline_statistics_query command")]
2083    BeginPipelineStatisticsQuery,
2084    #[error("In a end_pipeline_statistics_query command")]
2085    EndPipelineStatisticsQuery,
2086    #[error("In a transition_resources command")]
2087    TransitionResources,
2088    #[error("In a execute_bundle command")]
2089    ExecuteBundle,
2090    #[error("In a dispatch command, indirect:{indirect}")]
2091    Dispatch { indirect: bool },
2092    #[error("In a push_debug_group command")]
2093    PushDebugGroup,
2094    #[error("In a pop_debug_group command")]
2095    PopDebugGroup,
2096    #[error("In a insert_debug_marker command")]
2097    InsertDebugMarker,
2098    #[error("In a trace rays command, indirect:{indirect}")]
2099    TraceRays { indirect: bool },
2100}
2101
2102/// Variant of `EncoderStateError` that includes the pass scope.
2103#[derive(Clone, Debug, Error)]
2104#[error("{scope}")]
2105pub struct PassStateError {
2106    pub scope: PassErrorScope,
2107    #[source]
2108    pub(super) inner: EncoderStateError,
2109}
2110
2111impl WebGpuError for PassStateError {
2112    fn webgpu_error_type(&self) -> ErrorType {
2113        let Self { scope: _, inner } = self;
2114        inner.webgpu_error_type()
2115    }
2116}