1mod 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;
42pub 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
90pub 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
125fn 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
143pub(crate) enum CommandEncoderStatus {
149 Recording(CommandBufferMutable),
158
159 Locked(CommandBufferMutable),
168
169 Consumed,
170
171 Finished(CommandBufferMutable),
184
185 Error(EncoderErrorState),
190
191 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 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 self.invalidate(EncoderStateError::Locked);
239 Ok(())
240 }
241 Self::Finished(_) => Err(self.invalidate(EncoderStateError::Ended)),
244 Self::Consumed => Err(EncoderStateError::Ended),
245 Self::Error(_) => Ok(()),
248 Self::Transitioning => unreachable!(),
249 }
250 }
251
252 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 self.invalidate(EncoderStateError::Locked);
283 Ok(())
284 }
285 Self::Finished(_) => Err(self.invalidate(EncoderStateError::Ended)),
288 Self::Consumed => Err(EncoderStateError::Ended),
289 Self::Error(_) => Ok(()),
292 Self::Transitioning => unreachable!(),
293 }
294 }
295
296 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 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 *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 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 *self = st;
388 Ok(())
389 }
390 Self::Transitioning => unreachable!(),
391 }
392 }
393
394 fn finish(&mut self) -> Self {
395 match mem::replace(self, Self::Consumed) {
398 Self::Recording(inner) => {
399 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 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
443pub(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 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 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 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
548pub enum EncodingApi {
549 Wgpu,
551
552 Raw,
554
555 Undecided,
557
558 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
576pub(crate) struct InnerCommandEncoder {
592 pub(crate) raw: ManuallyDrop<Box<dyn hal::DynCommandEncoder>>,
600
601 pub(crate) list: Vec<Box<dyn hal::DynCommandBuffer>>,
613
614 pub(crate) device: Arc<Device>,
615
616 pub(crate) is_open: bool,
623
624 pub(crate) api: EncodingApi,
630
631 pub(crate) label: String,
632}
633
634impl InnerCommandEncoder {
635 fn close_and_swap(&mut self) -> Result<(), DeviceError> {
667 self.close_and_insert_at(self.list.len() - 1)
668 }
669
670 pub(crate) fn close_and_push_front(&mut self) -> Result<(), DeviceError> {
687 self.close_and_insert_at(0)
688 }
689
690 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 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 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 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 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 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 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
822 self.device.command_allocator.release_encoder(raw);
823 }
824}
825
826pub(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
839pub struct CommandBufferMutable {
841 pub(crate) encoder: InnerCommandEncoder,
846
847 pub(crate) trackers: Tracker,
849
850 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 #[cfg(feature = "trace")]
869 pub(crate) trace_commands: Option<Vec<Command<PointerReferences>>>,
870
871 pub(crate) query_set_writes: query::QuerySetWrites,
873 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
892pub struct CommandBuffer {
898 pub(crate) device: Arc<Device>,
899 label: String,
901
902 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 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 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 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 cmd_buf_data.encoder.close_if_open()?;
1334
1335 Ok(())
1339 }
1340
1341 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 #[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 (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 #[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#[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 #[cfg_attr(feature = "serde", serde(skip, default = "Option::default"))]
1483 pub error: Option<E>,
1484
1485 pub commands: Vec<C>,
1491
1492 pub dynamic_offsets: Vec<wgt::DynamicOffset>,
1497
1498 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 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
1546macro_rules! pass_base {
1569 ($pass:expr, $scope:expr $(,)?) => {
1570 match (&$pass.parent, &$pass.base.error) {
1571 (&None, _) => return Err(EncoderStateError::Ended).map_pass_err($scope),
1573 (&Some(_), &Some(_)) => return Ok(()),
1575 (&Some(_), &None) => &mut $pass.base,
1577 }
1578 };
1579}
1580pub(crate) use pass_base;
1581
1582macro_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#[derive(Clone, Debug, Error)]
1611#[non_exhaustive]
1612pub enum EncoderStateError {
1613 #[error("Encoder is invalid")]
1618 Invalid,
1619
1620 #[error("Encoding must not have ended")]
1623 Ended,
1624
1625 #[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 #[error(
1636 "Encoder is not currently locked. A pass can only be ended while the encoder is locked."
1637 )]
1638 Unlocked,
1639
1640 #[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 if offsets.is_empty() {
1965 if let Some(current_bind_group) = self.last_states.get_mut(index as usize) {
1968 if current_bind_group.set_and_check_redundant(bind_group) {
1970 return true;
1971 }
1972 }
1973 } else {
1974 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
1995trait 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#[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#[derive(Clone, Copy, Debug, Error)]
2042pub enum PassErrorScope {
2043 #[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#[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}