1use thiserror::Error;
2use wgt::{
3 error::{ErrorType, WebGpuError},
4 BufferAddress, DynamicOffset,
5};
6
7use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec};
8use core::{convert::Infallible, fmt, str};
9
10use crate::{
11 api_log,
12 binding_model::{BindError, BindGroup, ImmediateUploadError},
13 command::{
14 bind::{Binder, BinderError},
15 compute_command::ArcComputeCommand,
16 encoder::EncodingState,
17 memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState},
18 pass::{self, flush_bindings_helper, ImmediateState},
19 pass_base, pass_try,
20 query::{
21 end_pipeline_statistics_query, record_pass_timestamp_writes,
22 validate_and_begin_pipeline_statistics_query,
23 },
24 ArcCommand, BasePass, BindGroupStateChange, CommandEncoder, CommandEncoderError,
25 DebugGroupError, EncoderStateError, InnerCommandEncoder, MapPassErr, PassErrorScope,
26 PassStateError, PassTimestampWrites, QueryUseError, StateChange, TimestampWritesError,
27 TransitionResourcesError,
28 },
29 device::{Device, DeviceError, MissingDownlevelFlags, MissingFeatures},
30 hal_label, id, impl_resource_type,
31 init_tracker::MemoryInitKind,
32 pipeline::ComputePipeline,
33 resource::{
34 Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError,
35 Labeled, MissingBufferUsageError, ParentDevice, QuerySet, RawResourceAccess, TextureView,
36 Trackable,
37 },
38 track::{ResourceUsageCompatibilityError, TextureViewBindGroupState, Tracker},
39 Label,
40};
41
42pub type ComputeBasePass = BasePass<ArcComputeCommand, ComputePassError>;
43
44pub struct ComputePass {
52 base: ComputeBasePass,
54
55 parent: Option<Arc<CommandEncoder>>,
61
62 device: Arc<Device>,
63
64 timestamp_writes: Option<PassTimestampWrites>,
65
66 current_bind_groups: BindGroupStateChange,
68 current_pipeline: StateChange<Arc<ComputePipeline>>,
69}
70
71impl_resource_type!(ComputePass);
72
73impl crate::storage::StorageItem for ComputePass {
74 type Marker = id::markers::ComputePassEncoder;
75}
76
77impl ComputePass {
78 fn new(parent: Arc<CommandEncoder>, desc: ComputePassDescriptor) -> Self {
80 let ComputePassDescriptor {
81 label,
82 timestamp_writes,
83 } = desc;
84
85 Self {
86 base: BasePass::new(&label),
87 device: parent.device().clone(),
88 parent: Some(parent),
89 timestamp_writes,
90
91 current_bind_groups: BindGroupStateChange::new(),
92 current_pipeline: StateChange::new(),
93 }
94 }
95
96 fn new_invalid(parent: Arc<CommandEncoder>, label: &Label, err: ComputePassError) -> Self {
97 Self {
98 base: BasePass::new_invalid(label, err),
99 device: parent.device().clone(),
100 parent: Some(parent),
101 timestamp_writes: None,
102 current_bind_groups: BindGroupStateChange::new(),
103 current_pipeline: StateChange::new(),
104 }
105 }
106
107 #[inline]
108 pub fn label(&self) -> Option<&str> {
109 self.base.label.as_deref()
110 }
111
112 pub fn device(&self) -> &Arc<Device> {
113 &self.device
114 }
115}
116
117impl fmt::Debug for ComputePass {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 match self.parent {
120 Some(ref cmd_enc) => write!(f, "ComputePass {{ parent: {} }}", cmd_enc.error_ident()),
121 None => write!(f, "ComputePass {{ parent: None }}"),
122 }
123 }
124}
125
126#[derive(Clone, Debug, Default)]
127#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
128pub struct ComputePassDescriptor<'a, PTW = PassTimestampWrites> {
130 pub label: Label<'a>,
131 pub timestamp_writes: Option<PTW>,
133}
134
135#[derive(Clone, Debug, Error)]
136#[non_exhaustive]
137pub enum DispatchError {
138 #[error("Compute pipeline must be set")]
139 MissingPipeline(pass::MissingPipeline),
140 #[error(transparent)]
141 IncompatibleBindGroup(#[from] Box<BinderError>),
142 #[error(
143 "Each current dispatch group size dimension ({current:?}) must be less or equal to {limit}"
144 )]
145 InvalidGroupSize { current: [u32; 3], limit: u32 },
146
147 #[error("Not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: {missing})")]
148 MissingImmediateData {
149 missing: naga::valid::ImmediateSlots,
150 },
151}
152
153impl WebGpuError for DispatchError {
154 fn webgpu_error_type(&self) -> ErrorType {
155 ErrorType::Validation
156 }
157}
158
159#[derive(Clone, Debug, Error)]
161pub enum ComputePassErrorInner {
162 #[error(transparent)]
163 Device(#[from] DeviceError),
164 #[error(transparent)]
165 EncoderState(#[from] EncoderStateError),
166 #[error("Parent encoder is invalid")]
167 InvalidParentEncoder,
168 #[error(transparent)]
169 DebugGroupError(#[from] DebugGroupError),
170 #[error(transparent)]
171 BindGroupIndexOutOfRange(#[from] pass::BindGroupIndexOutOfRange),
172 #[error(transparent)]
173 DestroyedResource(#[from] DestroyedResourceError),
174 #[error("Indirect buffer offset {0:?} is not a multiple of 4")]
175 UnalignedIndirectBufferOffset(BufferAddress),
176 #[error("Indirect buffer of {args_size} bytes starting at offset {offset} would overrun buffer of size {buffer_size}")]
177 IndirectBufferOverrun {
178 args_size: u64,
179 offset: u64,
180 buffer_size: u64,
181 },
182 #[error(transparent)]
183 ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
184 #[error(transparent)]
185 MissingBufferUsage(#[from] MissingBufferUsageError),
186 #[error(transparent)]
187 Dispatch(#[from] DispatchError),
188 #[error(transparent)]
189 Bind(#[from] BindError),
190 #[error(transparent)]
191 ImmediateData(#[from] ImmediateUploadError),
192 #[error(transparent)]
193 QueryUse(#[from] QueryUseError),
194 #[error(transparent)]
195 TransitionResources(#[from] TransitionResourcesError),
196 #[error(transparent)]
197 MissingFeatures(#[from] MissingFeatures),
198 #[error(transparent)]
199 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
200 #[error("The compute pass has already been ended and no further commands can be recorded")]
201 PassEnded,
202 #[error(transparent)]
203 InvalidResource(#[from] InvalidResourceError),
204 #[error(transparent)]
205 TimestampWrites(#[from] TimestampWritesError),
206}
207
208impl From<InvalidOrDestroyedResourceError> for ComputePassErrorInner {
209 fn from(value: InvalidOrDestroyedResourceError) -> Self {
210 match value {
211 InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
212 InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
213 }
214 }
215}
216
217#[derive(Clone, Debug, Error)]
220#[error("{scope}")]
221pub struct ComputePassError {
222 pub scope: PassErrorScope,
223 #[source]
224 pub(super) inner: ComputePassErrorInner,
225}
226
227impl From<pass::MissingPipeline> for ComputePassErrorInner {
228 fn from(value: pass::MissingPipeline) -> Self {
229 Self::Dispatch(DispatchError::MissingPipeline(value))
230 }
231}
232
233impl<E> MapPassErr<ComputePassError> for E
234where
235 E: Into<ComputePassErrorInner>,
236{
237 fn map_pass_err(self, scope: PassErrorScope) -> ComputePassError {
238 ComputePassError {
239 scope,
240 inner: self.into(),
241 }
242 }
243}
244
245impl WebGpuError for ComputePassError {
246 fn webgpu_error_type(&self) -> ErrorType {
247 let Self { scope: _, inner } = self;
248 match inner {
249 ComputePassErrorInner::Device(e) => e.webgpu_error_type(),
250 ComputePassErrorInner::EncoderState(e) => e.webgpu_error_type(),
251 ComputePassErrorInner::DebugGroupError(e) => e.webgpu_error_type(),
252 ComputePassErrorInner::DestroyedResource(e) => e.webgpu_error_type(),
253 ComputePassErrorInner::ResourceUsageCompatibility(e) => e.webgpu_error_type(),
254 ComputePassErrorInner::MissingBufferUsage(e) => e.webgpu_error_type(),
255 ComputePassErrorInner::Dispatch(e) => e.webgpu_error_type(),
256 ComputePassErrorInner::Bind(e) => e.webgpu_error_type(),
257 ComputePassErrorInner::ImmediateData(e) => e.webgpu_error_type(),
258 ComputePassErrorInner::QueryUse(e) => e.webgpu_error_type(),
259 ComputePassErrorInner::TransitionResources(e) => e.webgpu_error_type(),
260 ComputePassErrorInner::MissingFeatures(e) => e.webgpu_error_type(),
261 ComputePassErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(),
262 ComputePassErrorInner::InvalidResource(e) => e.webgpu_error_type(),
263 ComputePassErrorInner::TimestampWrites(e) => e.webgpu_error_type(),
264
265 ComputePassErrorInner::InvalidParentEncoder
266 | ComputePassErrorInner::BindGroupIndexOutOfRange { .. }
267 | ComputePassErrorInner::UnalignedIndirectBufferOffset(_)
268 | ComputePassErrorInner::IndirectBufferOverrun { .. }
269 | ComputePassErrorInner::PassEnded => ErrorType::Validation,
270 }
271 }
272}
273
274struct State<'scope, 'snatch_guard, 'cmd_enc> {
275 pipeline: Option<Arc<ComputePipeline>>,
276
277 pass: pass::PassState<'scope, 'snatch_guard, 'cmd_enc>,
278
279 active_query: Option<(Arc<QuerySet>, u32)>,
280
281 intermediate_trackers: Tracker,
282}
283
284impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> {
285 fn is_ready(&self) -> Result<(), DispatchError> {
286 if let Some(pipeline) = self.pipeline.as_ref() {
287 self.pass
288 .binder
289 .check_compatibility(pipeline.as_ref(), &pipeline.late_sized_buffer_groups)?;
290 if !self
291 .pass
292 .immediate_state
293 .immediate_slots_set
294 .contains(pipeline.immediate_slots_required)
295 {
296 return Err(DispatchError::MissingImmediateData {
297 missing: pipeline
298 .immediate_slots_required
299 .difference(self.pass.immediate_state.immediate_slots_set),
300 });
301 }
302 Ok(())
303 } else {
304 Err(DispatchError::MissingPipeline(pass::MissingPipeline))
305 }
306 }
307
308 fn flush_immediates(&mut self) {
309 let pipeline = self.pipeline.as_ref().unwrap();
310 let layout = pipeline.layout().unwrap();
311 self.pass
312 .immediate_state
313 .flush_immediates(layout, self.pass.base.raw_encoder);
314 }
315
316 fn flush_bindings(
355 &mut self,
356 indirect_buffer: Option<&Arc<Buffer>>,
357 track_indirect_buffer: bool,
358 ) -> Result<(), ComputePassErrorInner> {
359 for bind_group in self.pass.binder.list_active() {
360 unsafe { self.pass.scope.merge_bind_group(&bind_group.used)? };
361 }
362
363 if let Some(buffer) = indirect_buffer {
367 self.pass
368 .scope
369 .buffers
370 .merge_single(buffer, wgt::BufferUses::INDIRECT)?;
371 }
372
373 for bind_group in self.pass.binder.list_active() {
379 self.intermediate_trackers
380 .set_and_remove_from_usage_scope_sparse(&mut self.pass.scope, &bind_group.used);
381 }
382
383 if track_indirect_buffer {
384 self.intermediate_trackers
385 .buffers
386 .set_and_remove_from_usage_scope_sparse(
387 &mut self.pass.scope.buffers,
388 indirect_buffer.map(|buf| buf.tracker_index()),
389 );
390 } else if let Some(buffer) = indirect_buffer {
391 self.pass
392 .scope
393 .buffers
394 .remove_usage(buffer, wgt::BufferUses::INDIRECT);
395 }
396
397 flush_bindings_helper(&mut self.pass)?;
398
399 CommandEncoder::drain_barriers(
400 self.pass.base.raw_encoder,
401 &mut self.intermediate_trackers,
402 self.pass.base.snatch_guard,
403 );
404 Ok(())
405 }
406}
407
408fn transition_resources(
411 state: &mut State,
412 buffer_transitions: Vec<wgt::BufferTransition<Arc<Buffer>>>,
413 texture_transitions: Vec<wgt::TextureTransition<Arc<TextureView>>>,
414) -> Result<(), TransitionResourcesError> {
415 let indices = &state.pass.base.device.tracker_indices;
416 state.pass.scope.buffers.set_size(indices.buffers.size());
417 state.pass.scope.textures.set_size(indices.textures.size());
418
419 let mut buffer_ids = Vec::with_capacity(buffer_transitions.len());
420 let mut textures = TextureViewBindGroupState::new();
421
422 for buffer_transition in buffer_transitions {
424 buffer_transition
425 .buffer
426 .same_device(state.pass.base.device)?;
427
428 state
429 .pass
430 .scope
431 .buffers
432 .merge_single(&buffer_transition.buffer, buffer_transition.state)?;
433 buffer_ids.push(buffer_transition.buffer.tracker_index());
434 }
435
436 state
437 .intermediate_trackers
438 .buffers
439 .set_and_remove_from_usage_scope_sparse(&mut state.pass.scope.buffers, buffer_ids);
440
441 for texture_transition in texture_transitions {
443 texture_transition
444 .texture
445 .same_device(state.pass.base.device)?;
446
447 unsafe {
448 state.pass.scope.textures.merge_single(
449 &texture_transition.texture.parent,
450 texture_transition.selector,
451 texture_transition.state,
452 )
453 }?;
454
455 textures.insert_single(texture_transition.texture, texture_transition.state);
456 }
457
458 state
459 .intermediate_trackers
460 .textures
461 .set_and_remove_from_usage_scope_sparse(&mut state.pass.scope.textures, &textures);
462
463 CommandEncoder::drain_barriers(
465 state.pass.base.raw_encoder,
466 &mut state.intermediate_trackers,
467 state.pass.base.snatch_guard,
468 );
469 Ok(())
470}
471
472impl CommandEncoder {
473 fn begin_compute_pass_inner(
474 self: &Arc<Self>,
475 desc: &ComputePassDescriptor<'_, PassTimestampWrites<Arc<QuerySet>>>,
476 ) -> (ComputePass, Option<CommandEncoderError>) {
477 use EncoderStateError as SErr;
478
479 let scope = PassErrorScope::Pass;
480
481 let label = desc.label.as_deref().map(Cow::Borrowed);
482
483 let mut cmd_buf_data = self.data.lock();
484
485 match cmd_buf_data.lock_encoder() {
486 Ok(()) => {
487 drop(cmd_buf_data);
488 if let Err(err) = self.device.check_is_valid() {
489 return (
490 ComputePass::new_invalid(Arc::clone(self), &label, err.map_pass_err(scope)),
491 None,
492 );
493 }
494
495 match desc
496 .timestamp_writes
497 .as_ref()
498 .map(|tw| {
499 Self::validate_pass_timestamp_writes::<ComputePassErrorInner>(
500 &self.device,
501 tw,
502 )
503 })
504 .transpose()
505 {
506 Ok(timestamp_writes) => {
507 let arc_desc = ComputePassDescriptor {
508 label,
509 timestamp_writes,
510 };
511 (ComputePass::new(Arc::clone(self), arc_desc), None)
512 }
513 Err(err) => (
514 ComputePass::new_invalid(Arc::clone(self), &label, err.map_pass_err(scope)),
515 None,
516 ),
517 }
518 }
519 Err(err @ SErr::Locked) => {
520 cmd_buf_data.invalidate(err.clone());
524 drop(cmd_buf_data);
525 (
526 ComputePass::new_invalid(Arc::clone(self), &label, err.map_pass_err(scope)),
527 None,
528 )
529 }
530 Err(err @ (SErr::Ended | SErr::Submitted)) => {
531 drop(cmd_buf_data);
534 (
535 ComputePass::new_invalid(
536 Arc::clone(self),
537 &label,
538 err.clone().map_pass_err(scope),
539 ),
540 Some(err.into()),
541 )
542 }
543 Err(err @ SErr::Invalid) => {
544 drop(cmd_buf_data);
550 (
551 ComputePass::new_invalid(Arc::clone(self), &label, err.map_pass_err(scope)),
552 None,
553 )
554 }
555 Err(SErr::Unlocked) => {
556 unreachable!("lock_encoder cannot fail due to the encoder being unlocked")
557 }
558 }
559 }
560
561 pub fn begin_compute_pass(
562 self: &Arc<Self>,
563 desc: &ComputePassDescriptor<'_, PassTimestampWrites<Arc<QuerySet>>>,
564 ) -> ComputePass {
565 let (pass, err) = self.begin_compute_pass_inner(desc);
566 if let Some(err) = err {
567 self.device
568 .handle_error(err, pass.label(), "CommandEncoder::begin_compute_pass");
569 }
570 pass
571 }
572}
573
574impl ComputePass {
576 fn end_inner(&mut self) -> Result<(), EncoderStateError> {
577 profiling::scope!(
578 "CommandEncoder::run_compute_pass {}",
579 self.base.label.as_deref().unwrap_or("")
580 );
581
582 let cmd_enc = self.parent.take().ok_or(EncoderStateError::Ended)?;
583 let mut cmd_buf_data = cmd_enc.data.lock();
584
585 cmd_buf_data.unlock_encoder()?;
586
587 let base = self.base.take();
588
589 if let Err(ComputePassError {
590 inner:
591 ComputePassErrorInner::EncoderState(
592 err @ (EncoderStateError::Locked | EncoderStateError::Ended),
593 ),
594 scope: _,
595 }) = base
596 {
597 return Err(err.clone());
604 }
605
606 cmd_buf_data.push_with(|| -> Result<_, ComputePassError> {
607 Ok(ArcCommand::RunComputePass {
608 pass: base?,
609 timestamp_writes: self.timestamp_writes.take(),
610 })
611 })
612 }
613
614 pub fn end(&mut self) {
615 if let Err(err) = self.end_inner() {
616 self.device
617 .handle_error(err, self.label(), "ComputePass::end");
618 }
619 }
620}
621
622pub(super) fn encode_compute_pass(
623 parent_state: &mut EncodingState<InnerCommandEncoder>,
624 mut base: BasePass<ArcComputeCommand, Infallible>,
625 mut timestamp_writes: Option<PassTimestampWrites>,
626) -> Result<(), ComputePassError> {
627 let pass_scope = PassErrorScope::Pass;
628
629 let device = parent_state.device;
630
631 parent_state
635 .raw_encoder
636 .close_if_open()
637 .map_pass_err(pass_scope)?;
638 let raw_encoder = parent_state
639 .raw_encoder
640 .open_pass(base.label.as_deref())
641 .map_pass_err(pass_scope)?;
642
643 let mut debug_scope_depth = 0;
644
645 let mut state = State {
646 pipeline: None,
647
648 pass: pass::PassState {
649 base: EncodingState {
650 device,
651 raw_encoder,
652 tracker: parent_state.tracker,
653 buffer_memory_init_actions: parent_state.buffer_memory_init_actions,
654 texture_memory_actions: parent_state.texture_memory_actions,
655 as_actions: parent_state.as_actions,
656 temp_resources: parent_state.temp_resources,
657 indirect_draw_validation_resources: parent_state.indirect_draw_validation_resources,
658 snatch_guard: parent_state.snatch_guard,
659 debug_scope_depth: &mut debug_scope_depth,
660 query_set_writes: parent_state.query_set_writes,
661 deferred_query_set_resolves: parent_state.deferred_query_set_resolves,
662 },
663 binder: Binder::new(),
664 temp_offsets: Vec::new(),
665 dynamic_offset_count: 0,
666 pending_discard_init_fixups: SurfacesInDiscardState::new(),
667 scope: device.new_usage_scope(),
668 string_offset: 0,
669 immediate_state: ImmediateState::default(),
670 },
671 active_query: None,
672
673 intermediate_trackers: Tracker::new(
674 device.ordered_buffer_usages,
675 device.ordered_texture_usages,
676 ),
677 };
678
679 let indices = &device.tracker_indices;
680 state
681 .pass
682 .base
683 .tracker
684 .buffers
685 .set_size(indices.buffers.size());
686 state
687 .pass
688 .base
689 .tracker
690 .textures
691 .set_size(indices.textures.size());
692
693 let timestamp_writes: Option<hal::PassTimestampWrites<'_, dyn hal::DynQuerySet>> =
694 if let Some(tw) = timestamp_writes.take() {
695 tw.query_set.same_device(device).map_pass_err(pass_scope)?;
696
697 record_pass_timestamp_writes(&tw, state.pass.base.query_set_writes);
698
699 let query_set = state
700 .pass
701 .base
702 .tracker
703 .query_sets
704 .insert_single(tw.query_set);
705
706 let range = if let (Some(index_a), Some(index_b)) =
709 (tw.beginning_of_pass_write_index, tw.end_of_pass_write_index)
710 {
711 Some(index_a.min(index_b)..index_a.max(index_b) + 1)
712 } else {
713 tw.beginning_of_pass_write_index
714 .or(tw.end_of_pass_write_index)
715 .map(|i| i..i + 1)
716 };
717 let raw_query_set = query_set
718 .try_raw(parent_state.snatch_guard)
719 .map_pass_err(pass_scope)?;
720 if let Some(range) = range {
723 unsafe {
724 state
725 .pass
726 .base
727 .raw_encoder
728 .reset_queries(raw_query_set, range);
729 }
730 }
731
732 Some(hal::PassTimestampWrites {
733 query_set: raw_query_set,
734 beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
735 end_of_pass_write_index: tw.end_of_pass_write_index,
736 })
737 } else {
738 None
739 };
740
741 let hal_desc = hal::ComputePassDescriptor {
742 label: hal_label(base.label.as_deref(), device.instance_flags),
743 timestamp_writes,
744 };
745
746 unsafe {
747 state.pass.base.raw_encoder.begin_compute_pass(&hal_desc);
748 }
749
750 for command in base.commands.drain(..) {
751 match command {
752 ArcComputeCommand::SetBindGroup {
753 index,
754 num_dynamic_offsets,
755 bind_group,
756 } => {
757 let scope = PassErrorScope::SetBindGroup;
758 pass::set_bind_group::<ComputePassErrorInner>(
759 &mut state.pass,
760 device,
761 &base.dynamic_offsets,
762 index,
763 num_dynamic_offsets,
764 bind_group,
765 false,
766 )
767 .map_pass_err(scope)?;
768 }
769 ArcComputeCommand::SetPipeline(pipeline) => {
770 let scope = PassErrorScope::SetPipelineCompute;
771 set_pipeline(&mut state, device, pipeline).map_pass_err(scope)?;
772 }
773 ArcComputeCommand::SetImmediate { offset, data } => {
774 let scope = PassErrorScope::SetImmediate;
775 state
776 .pass
777 .immediate_state
778 .set_immediates::<ComputePassErrorInner>(
779 &state.pass.base.device.limits,
780 offset,
781 &data,
782 )
783 .map_pass_err(scope)?;
784 }
785 ArcComputeCommand::DispatchWorkgroups(groups) => {
786 let scope = PassErrorScope::Dispatch { indirect: false };
787 dispatch_workgroups(&mut state, groups).map_pass_err(scope)?;
788 }
789 ArcComputeCommand::DispatchWorkgroupsIndirect { buffer, offset } => {
790 let scope = PassErrorScope::Dispatch { indirect: true };
791 dispatch_workgroups_indirect(&mut state, device, buffer, offset)
792 .map_pass_err(scope)?;
793 }
794 ArcComputeCommand::PushDebugGroup { color: _, len } => {
795 pass::push_debug_group(&mut state.pass, &base.string_data, len);
796 }
797 ArcComputeCommand::PopDebugGroup => {
798 let scope = PassErrorScope::PopDebugGroup;
799 pass::pop_debug_group::<ComputePassErrorInner>(&mut state.pass)
800 .map_pass_err(scope)?;
801 }
802 ArcComputeCommand::InsertDebugMarker { color: _, len } => {
803 pass::insert_debug_marker(&mut state.pass, &base.string_data, len);
804 }
805 ArcComputeCommand::WriteTimestamp {
806 query_set,
807 query_index,
808 } => {
809 let scope = PassErrorScope::WriteTimestamp;
810 pass::write_timestamp::<ComputePassErrorInner>(
811 &mut state.pass,
812 device,
813 None, query_set,
815 query_index,
816 )
817 .map_pass_err(scope)?;
818 }
819 ArcComputeCommand::BeginPipelineStatisticsQuery {
820 query_set,
821 query_index,
822 } => {
823 let scope = PassErrorScope::BeginPipelineStatisticsQuery;
824 validate_and_begin_pipeline_statistics_query(
825 query_set,
826 state.pass.base.raw_encoder,
827 &mut state.pass.base.tracker.query_sets,
828 device,
829 query_index,
830 None,
831 &mut state.active_query,
832 state.pass.base.snatch_guard,
833 )
834 .map_pass_err(scope)?;
835 }
836 ArcComputeCommand::EndPipelineStatisticsQuery => {
837 let scope = PassErrorScope::EndPipelineStatisticsQuery;
838 end_pipeline_statistics_query(
839 state.pass.base.raw_encoder,
840 &mut state.active_query,
841 state.pass.base.snatch_guard,
842 state.pass.base.query_set_writes,
843 )
844 .map_pass_err(scope)?;
845 }
846 ArcComputeCommand::TransitionResources {
847 buffer_transitions,
848 texture_transitions,
849 } => {
850 let scope = PassErrorScope::TransitionResources;
851 transition_resources(&mut state, buffer_transitions, texture_transitions)
852 .map_pass_err(scope)?;
853 }
854 }
855 }
856
857 if *state.pass.base.debug_scope_depth > 0 {
858 Err(
859 ComputePassErrorInner::DebugGroupError(DebugGroupError::MissingPop)
860 .map_pass_err(pass_scope),
861 )?;
862 }
863
864 unsafe {
865 state.pass.base.raw_encoder.end_compute_pass();
866 }
867
868 let State {
869 pass: pass::PassState {
870 pending_discard_init_fixups,
871 ..
872 },
873 intermediate_trackers,
874 ..
875 } = state;
876
877 parent_state.raw_encoder.close().map_pass_err(pass_scope)?;
879
880 let transit = parent_state
884 .raw_encoder
885 .open_pass(hal_label(
886 Some("(wgpu internal) Pre Pass"),
887 device.instance_flags,
888 ))
889 .map_pass_err(pass_scope)?;
890 fixup_discarded_surfaces(
893 pending_discard_init_fixups.into_iter(),
894 transit,
895 &mut parent_state.tracker.textures,
896 device,
897 parent_state.snatch_guard,
898 );
899 CommandEncoder::insert_barriers_from_tracker(
900 transit,
901 parent_state.tracker,
902 &intermediate_trackers,
903 parent_state.snatch_guard,
904 );
905 parent_state
907 .raw_encoder
908 .close_and_swap()
909 .map_pass_err(pass_scope)?;
910
911 Ok(())
912}
913
914fn set_pipeline(
915 state: &mut State,
916 device: &Arc<Device>,
917 pipeline: Arc<ComputePipeline>,
918) -> Result<(), ComputePassErrorInner> {
919 pipeline.same_device(device)?;
920
921 state.pipeline = Some(pipeline.clone());
922
923 let pipeline = state
924 .pass
925 .base
926 .tracker
927 .compute_pipelines
928 .insert_single(pipeline)
929 .clone();
930
931 unsafe {
932 state
933 .pass
934 .base
935 .raw_encoder
936 .set_compute_pipeline(pipeline.raw()?);
937 }
938
939 let pipeline_layout = pipeline.layout()?;
941 pass::change_pipeline_layout::<ComputePassErrorInner>(&mut state.pass, pipeline_layout)
942}
943
944fn dispatch_workgroups(state: &mut State, groups: [u32; 3]) -> Result<(), ComputePassErrorInner> {
945 api_log!("ComputePass::dispatch {groups:?}");
946
947 state.is_ready()?;
948
949 state.flush_bindings(None, false)?;
950 state.flush_immediates();
951
952 let groups_size_limit = state
953 .pass
954 .base
955 .device
956 .limits
957 .max_compute_workgroups_per_dimension;
958
959 if groups.iter().copied().any(|g| g > groups_size_limit) {
960 return Err(ComputePassErrorInner::Dispatch(
961 DispatchError::InvalidGroupSize {
962 current: groups,
963 limit: groups_size_limit,
964 },
965 ));
966 }
967
968 unsafe {
969 state.pass.base.raw_encoder.dispatch_workgroups(groups);
970 }
971 Ok(())
972}
973
974fn dispatch_workgroups_indirect(
975 state: &mut State,
976 device: &Arc<Device>,
977 buffer: Arc<Buffer>,
978 offset: u64,
979) -> Result<(), ComputePassErrorInner> {
980 api_log!("ComputePass::dispatch_indirect");
981
982 buffer.same_device(device)?;
983
984 state.is_ready()?;
985
986 state
987 .pass
988 .base
989 .device
990 .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
991
992 buffer.check_usage(wgt::BufferUsages::INDIRECT)?;
993
994 if !offset.is_multiple_of(4) {
995 return Err(ComputePassErrorInner::UnalignedIndirectBufferOffset(offset));
996 }
997
998 let args_size = size_of::<wgt::DispatchIndirectArgs>() as u64;
999 if buffer.size < args_size || buffer.size - args_size < offset {
1000 return Err(ComputePassErrorInner::IndirectBufferOverrun {
1001 args_size,
1002 offset,
1003 buffer_size: buffer.size,
1004 });
1005 }
1006
1007 buffer.check_destroyed(state.pass.base.snatch_guard)?;
1008
1009 let stride = 3 * 4; state.pass.base.buffer_memory_init_actions.extend(
1011 buffer.initialization_status.read().create_action(
1012 &buffer,
1013 offset..(offset + stride),
1014 MemoryInitKind::NeedsInitializedMemory,
1015 ),
1016 );
1017
1018 if let Some(ref indirect_validation) = state.pass.base.device.indirect_validation {
1019 let params = indirect_validation.dispatch.params(
1020 &state.pass.base.device.limits,
1021 offset,
1022 buffer.size,
1023 );
1024
1025 unsafe {
1026 state
1027 .pass
1028 .base
1029 .raw_encoder
1030 .set_compute_pipeline(params.pipeline);
1031 }
1032
1033 unsafe {
1034 state.pass.base.raw_encoder.set_immediates(
1035 params.pipeline_layout,
1036 0,
1037 &[params.offset_remainder as u32 / 4],
1038 );
1039 }
1040
1041 unsafe {
1042 state.pass.base.raw_encoder.set_bind_group(
1043 params.pipeline_layout,
1044 0,
1045 params.dst_bind_group,
1046 &[],
1047 );
1048 }
1049 unsafe {
1050 state.pass.base.raw_encoder.set_bind_group(
1051 params.pipeline_layout,
1052 1,
1053 buffer
1054 .indirect_validation_bind_groups
1055 .get(state.pass.base.snatch_guard)
1056 .unwrap()
1057 .dispatch
1058 .as_ref(),
1059 &[params.aligned_offset as u32],
1060 );
1061 }
1062
1063 let src_transition = state
1064 .intermediate_trackers
1065 .buffers
1066 .set_single(&buffer, wgt::BufferUses::STORAGE_READ_ONLY);
1067 let src_barrier = src_transition
1068 .map(|transition| transition.into_hal(&buffer, state.pass.base.snatch_guard));
1069 unsafe {
1070 state
1071 .pass
1072 .base
1073 .raw_encoder
1074 .transition_buffers(src_barrier.as_slice());
1075 }
1076
1077 unsafe {
1078 state
1079 .pass
1080 .base
1081 .raw_encoder
1082 .transition_buffers(&[hal::BufferBarrier {
1083 buffer: params.dst_buffer,
1084 usage: hal::StateTransition {
1085 from: wgt::BufferUses::INDIRECT,
1086 to: wgt::BufferUses::STORAGE_READ_WRITE,
1087 },
1088 }]);
1089 }
1090
1091 unsafe {
1092 state.pass.base.raw_encoder.dispatch_workgroups([1, 1, 1]);
1093 }
1094
1095 {
1097 unsafe {
1098 state
1099 .pass
1100 .base
1101 .raw_encoder
1102 .set_compute_pipeline(state.pipeline.as_ref().unwrap().raw()?);
1103 }
1104
1105 state.pass.immediate_state.immediates_dirty = true;
1107 state.flush_immediates();
1108
1109 for (i, group, dynamic_offsets) in state.pass.binder.list_valid() {
1110 let raw_bg = group.try_raw(state.pass.base.snatch_guard)?;
1111 unsafe {
1112 state.pass.base.raw_encoder.set_bind_group(
1113 state.pipeline.as_ref().unwrap().layout()?.raw()?,
1114 i as u32,
1115 raw_bg,
1116 dynamic_offsets,
1117 );
1118 }
1119 }
1120 }
1121
1122 unsafe {
1123 state
1124 .pass
1125 .base
1126 .raw_encoder
1127 .transition_buffers(&[hal::BufferBarrier {
1128 buffer: params.dst_buffer,
1129 usage: hal::StateTransition {
1130 from: wgt::BufferUses::STORAGE_READ_WRITE,
1131 to: wgt::BufferUses::INDIRECT,
1132 },
1133 }]);
1134 }
1135
1136 state.flush_bindings(Some(&buffer), false)?;
1137 unsafe {
1138 state
1139 .pass
1140 .base
1141 .raw_encoder
1142 .dispatch_workgroups_indirect(params.dst_buffer, 0);
1143 }
1144 } else {
1145 state.flush_bindings(Some(&buffer), true)?;
1146 state.flush_immediates();
1147 let buf_raw = buffer.try_raw(state.pass.base.snatch_guard)?;
1148 unsafe {
1149 state
1150 .pass
1151 .base
1152 .raw_encoder
1153 .dispatch_workgroups_indirect(buf_raw, offset);
1154 }
1155 }
1156
1157 Ok(())
1158}
1159
1160impl ComputePass {
1173 fn set_bind_group_inner(
1174 &mut self,
1175 index: u32,
1176 bind_group: Option<Arc<BindGroup>>,
1177 offsets: &[DynamicOffset],
1178 ) -> Result<(), PassStateError> {
1179 let scope = PassErrorScope::SetBindGroup;
1180
1181 let base = pass_base!(self, scope);
1185
1186 if self.current_bind_groups.set_and_check_redundant(
1187 &bind_group,
1188 index,
1189 &mut base.dynamic_offsets,
1190 offsets,
1191 ) {
1192 return Ok(());
1193 }
1194
1195 let bind_group = if let Some(bind_group) = bind_group {
1196 pass_try!(base, scope, bind_group.check_is_valid());
1197 Some(bind_group)
1198 } else {
1199 None
1200 };
1201
1202 base.commands.push(ArcComputeCommand::SetBindGroup {
1203 index,
1204 num_dynamic_offsets: offsets.len(),
1205 bind_group,
1206 });
1207
1208 Ok(())
1209 }
1210
1211 pub fn set_bind_group(
1212 &mut self,
1213 index: u32,
1214 bind_group: Option<Arc<BindGroup>>,
1215 offsets: &[DynamicOffset],
1216 ) {
1217 if let Err(error) = self.set_bind_group_inner(index, bind_group, offsets) {
1218 self.device
1219 .handle_error(error, self.label(), "ComputePass::set_bind_group");
1220 }
1221 }
1222
1223 fn set_pipeline_inner(
1224 &mut self,
1225 compute_pipeline: Arc<ComputePipeline>,
1226 ) -> Result<(), PassStateError> {
1227 let redundant = self
1228 .current_pipeline
1229 .set_and_check_redundant(&compute_pipeline);
1230
1231 let scope = PassErrorScope::SetPipelineCompute;
1232
1233 let base = pass_base!(self, scope);
1236
1237 if redundant {
1238 return Ok(());
1239 }
1240
1241 pass_try!(base, scope, compute_pipeline.check_valid());
1242
1243 base.commands
1244 .push(ArcComputeCommand::SetPipeline(compute_pipeline));
1245
1246 Ok(())
1247 }
1248
1249 pub fn set_pipeline(&mut self, compute_pipeline: Arc<ComputePipeline>) {
1250 if let Err(error) = self.set_pipeline_inner(compute_pipeline) {
1251 self.device
1252 .handle_error(error, self.label(), "ComputePass::set_pipeline");
1253 }
1254 }
1255
1256 fn set_immediates_inner(&mut self, offset: u32, data: &[u8]) -> Result<(), PassStateError> {
1257 let scope = PassErrorScope::SetImmediate;
1258 let base = pass_base!(self, scope);
1259
1260 pass_try!(
1261 base,
1262 scope,
1263 pass::validate_immediates_alignment(offset, data.len())
1264 );
1265
1266 base.commands.push(ArcComputeCommand::SetImmediate {
1267 offset,
1268 data: data
1269 .chunks_exact(size_of::<u32>())
1270 .map(|ck| u32::from_le_bytes(ck.try_into().unwrap()))
1271 .collect(),
1272 });
1273
1274 Ok(())
1275 }
1276
1277 pub fn set_immediates(&mut self, offset: u32, data: &[u8]) {
1278 if let Err(error) = self.set_immediates_inner(offset, data) {
1279 self.device
1280 .handle_error(error, self.label(), "ComputePass::set_immediates");
1281 }
1282 }
1283
1284 fn dispatch_workgroups_inner(
1285 &mut self,
1286 groups_x: u32,
1287 groups_y: u32,
1288 groups_z: u32,
1289 ) -> Result<(), PassStateError> {
1290 let scope = PassErrorScope::Dispatch { indirect: false };
1291
1292 pass_base!(self, scope)
1293 .commands
1294 .push(ArcComputeCommand::DispatchWorkgroups([
1295 groups_x, groups_y, groups_z,
1296 ]));
1297
1298 Ok(())
1299 }
1300
1301 pub fn dispatch_workgroups(&mut self, groups_x: u32, groups_y: u32, groups_z: u32) {
1302 if let Err(error) = self.dispatch_workgroups_inner(groups_x, groups_y, groups_z) {
1303 self.device
1304 .handle_error(error, self.label(), "ComputePass::dispatch_workgroups");
1305 }
1306 }
1307
1308 fn dispatch_workgroups_indirect_inner(
1309 &mut self,
1310 buffer: Arc<Buffer>,
1311 offset: BufferAddress,
1312 ) -> Result<(), PassStateError> {
1313 let scope = PassErrorScope::Dispatch { indirect: true };
1314 let base = pass_base!(self, scope);
1315
1316 pass_try!(base, scope, buffer.check_is_valid());
1317
1318 base.commands
1319 .push(ArcComputeCommand::DispatchWorkgroupsIndirect { buffer, offset });
1320
1321 Ok(())
1322 }
1323
1324 pub fn dispatch_workgroups_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
1325 if let Err(error) = self.dispatch_workgroups_indirect_inner(buffer, offset) {
1326 self.device.handle_error(
1327 error,
1328 self.label(),
1329 "ComputePass::dispatch_workgroups_indirect",
1330 );
1331 }
1332 }
1333
1334 fn push_debug_group_inner(&mut self, label: &str, color: u32) -> Result<(), PassStateError> {
1335 let base = pass_base!(self, PassErrorScope::PushDebugGroup);
1336
1337 let bytes = label.as_bytes();
1338 base.string_data.extend_from_slice(bytes);
1339
1340 base.commands.push(ArcComputeCommand::PushDebugGroup {
1341 color,
1342 len: bytes.len(),
1343 });
1344
1345 Ok(())
1346 }
1347
1348 pub fn push_debug_group(&mut self, label: &str, color: u32) {
1349 if let Err(error) = self.push_debug_group_inner(label, color) {
1350 self.device
1351 .handle_error(error, self.label(), "ComputePass::push_debug_group");
1352 }
1353 }
1354
1355 fn pop_debug_group_inner(&mut self) -> Result<(), PassStateError> {
1356 let base = pass_base!(self, PassErrorScope::PopDebugGroup);
1357
1358 base.commands.push(ArcComputeCommand::PopDebugGroup);
1359
1360 Ok(())
1361 }
1362
1363 pub fn pop_debug_group(&mut self) {
1364 if let Err(error) = self.pop_debug_group_inner() {
1365 self.device
1366 .handle_error(error, self.label(), "ComputePass::pop_debug_group");
1367 }
1368 }
1369
1370 fn insert_debug_marker_inner(&mut self, label: &str, color: u32) -> Result<(), PassStateError> {
1371 let base = pass_base!(self, PassErrorScope::InsertDebugMarker);
1372
1373 let bytes = label.as_bytes();
1374 base.string_data.extend_from_slice(bytes);
1375
1376 base.commands.push(ArcComputeCommand::InsertDebugMarker {
1377 color,
1378 len: bytes.len(),
1379 });
1380
1381 Ok(())
1382 }
1383
1384 pub fn insert_debug_marker(&mut self, label: &str, color: u32) {
1385 if let Err(error) = self.insert_debug_marker_inner(label, color) {
1386 self.device
1387 .handle_error(error, self.label(), "ComputePass::insert_debug_marker");
1388 }
1389 }
1390
1391 fn write_timestamp_inner(
1392 &mut self,
1393 query_set: Arc<QuerySet>,
1394 query_index: u32,
1395 ) -> Result<(), PassStateError> {
1396 let scope = PassErrorScope::WriteTimestamp;
1397 let base = pass_base!(self, scope);
1398
1399 pass_try!(base, scope, query_set.check_is_valid());
1400
1401 base.commands.push(ArcComputeCommand::WriteTimestamp {
1402 query_set,
1403 query_index,
1404 });
1405
1406 Ok(())
1407 }
1408
1409 pub fn write_timestamp(&mut self, query_set: Arc<QuerySet>, query_index: u32) {
1410 if let Err(error) = self.write_timestamp_inner(query_set, query_index) {
1411 self.device
1412 .handle_error(error, self.label(), "ComputePass::write_timestamp");
1413 }
1414 }
1415
1416 fn begin_pipeline_statistics_query_inner(
1417 &mut self,
1418 query_set: Arc<QuerySet>,
1419 query_index: u32,
1420 ) -> Result<(), PassStateError> {
1421 let scope = PassErrorScope::BeginPipelineStatisticsQuery;
1422 let base = pass_base!(self, scope);
1423
1424 pass_try!(base, scope, query_set.check_is_valid());
1425
1426 base.commands
1427 .push(ArcComputeCommand::BeginPipelineStatisticsQuery {
1428 query_set,
1429 query_index,
1430 });
1431
1432 Ok(())
1433 }
1434
1435 pub fn begin_pipeline_statistics_query(&mut self, query_set: Arc<QuerySet>, query_index: u32) {
1436 if let Err(error) = self.begin_pipeline_statistics_query_inner(query_set, query_index) {
1437 self.device.handle_error(
1438 error,
1439 self.label(),
1440 "ComputePass::begin_pipeline_statistics_query",
1441 );
1442 }
1443 }
1444
1445 fn end_pipeline_statistics_query_inner(&mut self) -> Result<(), PassStateError> {
1446 pass_base!(self, PassErrorScope::EndPipelineStatisticsQuery)
1447 .commands
1448 .push(ArcComputeCommand::EndPipelineStatisticsQuery);
1449
1450 Ok(())
1451 }
1452
1453 pub fn end_pipeline_statistics_query(&mut self) {
1454 if let Err(error) = self.end_pipeline_statistics_query_inner() {
1455 self.device.handle_error(
1456 error,
1457 self.label(),
1458 "ComputePass::end_pipeline_statistics_query",
1459 );
1460 }
1461 }
1462
1463 fn transition_resources_inner(
1464 &mut self,
1465 buffer_transitions: impl Iterator<Item = wgt::BufferTransition<Arc<Buffer>>>,
1466 texture_transitions: impl Iterator<Item = wgt::TextureTransition<Arc<TextureView>>>,
1467 ) -> Result<(), PassStateError> {
1468 let scope = PassErrorScope::TransitionResources;
1469 let base = pass_base!(self, scope);
1470
1471 let buffer_transitions = pass_try!(
1472 base,
1473 scope,
1474 buffer_transitions
1475 .map(|buffer_transition| -> Result<_, InvalidResourceError> {
1476 let buffer = buffer_transition.buffer;
1477 buffer.check_is_valid()?;
1478 Ok(wgt::BufferTransition {
1479 buffer,
1480 state: buffer_transition.state,
1481 })
1482 })
1483 .collect::<Result<Vec<_>, _>>()
1484 );
1485
1486 let texture_transitions = pass_try!(
1487 base,
1488 scope,
1489 texture_transitions
1490 .map(|texture_transition| -> Result<_, InvalidResourceError> {
1491 let texture_view = texture_transition.texture;
1492 texture_view.check_valid()?;
1493 Ok(wgt::TextureTransition {
1494 texture: texture_view,
1495 selector: texture_transition.selector,
1496 state: texture_transition.state,
1497 })
1498 })
1499 .collect::<Result<Vec<_>, _>>()
1500 );
1501
1502 base.commands.push(ArcComputeCommand::TransitionResources {
1503 buffer_transitions,
1504 texture_transitions,
1505 });
1506
1507 Ok(())
1508 }
1509
1510 pub fn transition_resources(
1511 &mut self,
1512 buffer_transitions: impl Iterator<Item = wgt::BufferTransition<Arc<Buffer>>>,
1513 texture_transitions: impl Iterator<Item = wgt::TextureTransition<Arc<TextureView>>>,
1514 ) {
1515 if let Err(error) = self.transition_resources_inner(buffer_transitions, texture_transitions)
1516 {
1517 self.device
1518 .handle_error(error, self.label(), "ComputePass::transition_resources");
1519 }
1520 }
1521}