Debian Codegraph @

third_party/rust/wgpu-core/src/command/render.rs

raw
1 use alloc::{borrow::Cow, sync::Arc, vec::Vec};
2 use core::{fmt, num::NonZeroU32, ops::Range, str};
3
4 use arrayvec::ArrayVec;
5 use thiserror::Error;
6 use wgt::{
7 BufferAddress, BufferSize, BufferUsages, Color, DynamicOffset, IndexFormat, ShaderStages,
8 TextureSelector, TextureUsages, TextureViewDimension, VertexStepMode,
9 };
10
11 use crate::binding_model::BindGroup;
12 use crate::command::{
13 validate_and_begin_occlusion_query, validate_and_begin_pipeline_statistics_query,
14 };
15 use crate::init_tracker::BufferInitTrackerAction;
16 use crate::pipeline::{RenderPipeline, VertexStep};
17 use crate::resource::{InvalidResourceError, ResourceErrorIdent};
18 use crate::snatch::SnatchGuard;
19 use crate::{
20 api_log,
21 binding_model::BindError,
22 command::{
23 bind::Binder,
24 end_occlusion_query, end_pipeline_statistics_query,
25 memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState},
26 ArcPassTimestampWrites, BasePass, BindGroupStateChange, CommandBuffer, CommandEncoderError,
27 DrawError, ExecutionError, MapPassErr, PassErrorScope, PassTimestampWrites, QueryUseError,
28 RenderCommandError, StateChange,
29 },
30 device::{
31 AttachmentData, Device, DeviceError, MissingDownlevelFlags, MissingFeatures,
32 RenderPassCompatibilityError, RenderPassContext,
33 },
34 global::Global,
35 hal_label, id,
36 init_tracker::{MemoryInitKind, TextureInitRange, TextureInitTrackerAction},
37 pipeline::PipelineFlags,
38 resource::{
39 DestroyedResourceError, Labeled, MissingBufferUsageError, MissingTextureUsageError,
40 ParentDevice, QuerySet, Texture, TextureView, TextureViewNotRenderableReason,
41 },
42 track::{ResourceUsageCompatibilityError, Tracker, UsageScope},
43 Label,
44 };
45
46 #[cfg(feature = "serde")]
47 use serde::Deserialize;
48 #[cfg(feature = "serde")]
49 use serde::Serialize;
50
51 use super::render_command::ArcRenderCommand;
52 use super::{
53 memory_init::TextureSurfaceDiscard, CommandBufferTextureMemoryActions, CommandEncoder,
54 QueryResetMap,
55 };
56 use super::{DrawKind, Rect};
57
58 pub use wgt::{LoadOp, StoreOp};
59
60 fn load_hal_ops<V>(load: LoadOp<V>) -> hal::AttachmentOps {
61 match load {
62 LoadOp::Load => hal::AttachmentOps::LOAD,
63 LoadOp::Clear(_) => hal::AttachmentOps::empty(),
64 }
65 }
66
67 fn store_hal_ops(store: StoreOp) -> hal::AttachmentOps {
68 match store {
69 StoreOp::Store => hal::AttachmentOps::STORE,
70 StoreOp::Discard => hal::AttachmentOps::empty(),
71 }
72 }
73
74 /// Describes an individual channel within a render pass, such as color, depth, or stencil.
75 #[repr(C)]
76 #[derive(Clone, Debug, Eq, PartialEq)]
77 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
78 pub struct PassChannel<V> {
79 /// Operation to perform to the output attachment at the start of a
80 /// renderpass.
81 ///
82 /// This must be clear if it is the first renderpass rendering to a swap
83 /// chain image.
84 pub load_op: Option<LoadOp<V>>,
85 /// Operation to perform to the output attachment at the end of a renderpass.
86 pub store_op: Option<StoreOp>,
87 /// If true, the relevant channel is not changed by a renderpass, and the
88 /// corresponding attachment can be used inside the pass by other read-only
89 /// usages.
90 pub read_only: bool,
91 }
92
93 impl<V: Copy + Default> PassChannel<Option<V>> {
94 fn resolve(
95 &self,
96 handle_clear: impl Fn(Option<V>) -> Result<V, AttachmentError>,
97 ) -> Result<ResolvedPassChannel<V>, AttachmentError> {
98 if self.read_only {
99 if self.load_op.is_some() {
100 return Err(AttachmentError::ReadOnlyWithLoad);
101 }
102 if self.store_op.is_some() {
103 return Err(AttachmentError::ReadOnlyWithStore);
104 }
105 Ok(ResolvedPassChannel::ReadOnly)
106 } else {
107 Ok(ResolvedPassChannel::Operational(wgt::Operations {
108 load: match self.load_op.ok_or(AttachmentError::NoLoad)? {
109 LoadOp::Clear(clear_value) => LoadOp::Clear(handle_clear(clear_value)?),
110 LoadOp::Load => LoadOp::Load,
111 },
112 store: self.store_op.ok_or(AttachmentError::NoStore)?,
113 }))
114 }
115 }
116 }
117
118 #[derive(Debug)]
119 pub enum ResolvedPassChannel<V> {
120 ReadOnly,
121 Operational(wgt::Operations<V>),
122 }
123
124 impl<V: Copy + Default> ResolvedPassChannel<V> {
125 fn load_op(&self) -> LoadOp<V> {
126 match self {
127 ResolvedPassChannel::ReadOnly => LoadOp::Load,
128 ResolvedPassChannel::Operational(wgt::Operations { load, .. }) => *load,
129 }
130 }
131
132 fn store_op(&self) -> StoreOp {
133 match self {
134 ResolvedPassChannel::ReadOnly => StoreOp::Store,
135 ResolvedPassChannel::Operational(wgt::Operations { store, .. }) => *store,
136 }
137 }
138
139 fn clear_value(&self) -> V {
140 match self {
141 Self::Operational(wgt::Operations {
142 load: LoadOp::Clear(clear_value),
143 ..
144 }) => *clear_value,
145 _ => Default::default(),
146 }
147 }
148
149 fn is_readonly(&self) -> bool {
150 matches!(self, Self::ReadOnly)
151 }
152
153 fn hal_ops(&self) -> hal::AttachmentOps {
154 load_hal_ops(self.load_op()) | store_hal_ops(self.store_op())
155 }
156 }
157
158 /// Describes a color attachment to a render pass.
159 #[repr(C)]
160 #[derive(Clone, Debug, PartialEq)]
161 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
162 pub struct RenderPassColorAttachment<TV = id::TextureViewId> {
163 /// The view to use as an attachment.
164 pub view: TV,
165 /// The depth slice index of a 3D view. It must not be provided if the view is not 3D.
166 pub depth_slice: Option<u32>,
167 /// The view that will receive the resolved output if multisampling is used.
168 pub resolve_target: Option<TV>,
169 /// Operation to perform to the output attachment at the start of a
170 /// renderpass.
171 ///
172 /// This must be clear if it is the first renderpass rendering to a swap
173 /// chain image.
174 pub load_op: LoadOp<Color>,
175 /// Operation to perform to the output attachment at the end of a renderpass.
176 pub store_op: StoreOp,
177 }
178
179 pub type ArcRenderPassColorAttachment = RenderPassColorAttachment<Arc<TextureView>>;
180
181 impl ArcRenderPassColorAttachment {
182 fn hal_ops(&self) -> hal::AttachmentOps {
183 load_hal_ops(self.load_op) | store_hal_ops(self.store_op)
184 }
185
186 fn clear_value(&self) -> Color {
187 match self.load_op {
188 LoadOp::Clear(clear_value) => clear_value,
189 LoadOp::Load => Color::default(),
190 }
191 }
192 }
193
194 /// Describes a depth/stencil attachment to a render pass.
195 #[repr(C)]
196 #[derive(Clone, Debug, PartialEq)]
197 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
198 pub struct RenderPassDepthStencilAttachment {
199 /// The view to use as an attachment.
200 pub view: id::TextureViewId,
201 /// What operations will be performed on the depth part of the attachment.
202 pub depth: PassChannel<Option<f32>>,
203 /// What operations will be performed on the stencil part of the attachment.
204 pub stencil: PassChannel<Option<u32>>,
205 }
206
207 /// Describes a depth/stencil attachment to a render pass.
208 #[derive(Debug)]
209 pub struct ArcRenderPassDepthStencilAttachment {
210 /// The view to use as an attachment.
211 pub view: Arc<TextureView>,
212 /// What operations will be performed on the depth part of the attachment.
213 pub depth: ResolvedPassChannel<f32>,
214 /// What operations will be performed on the stencil part of the attachment.
215 pub stencil: ResolvedPassChannel<u32>,
216 }
217
218 /// Describes the attachments of a render pass.
219 #[derive(Clone, Debug, Default, PartialEq)]
220 pub struct RenderPassDescriptor<'a> {
221 pub label: Label<'a>,
222 /// The color attachments of the render pass.
223 pub color_attachments: Cow<'a, [Option<RenderPassColorAttachment>]>,
224 /// The depth and stencil attachment of the render pass, if any.
225 pub depth_stencil_attachment: Option<&'a RenderPassDepthStencilAttachment>,
226 /// Defines where and when timestamp values will be written for this pass.
227 pub timestamp_writes: Option<&'a PassTimestampWrites>,
228 /// Defines where the occlusion query results will be stored for this pass.
229 pub occlusion_query_set: Option<id::QuerySetId>,
230 }
231
232 /// Describes the attachments of a render pass.
233 struct ArcRenderPassDescriptor<'a> {
234 pub label: &'a Label<'a>,
235 /// The color attachments of the render pass.
236 pub color_attachments:
237 ArrayVec<Option<ArcRenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>,
238 /// The depth and stencil attachment of the render pass, if any.
239 pub depth_stencil_attachment: Option<ArcRenderPassDepthStencilAttachment>,
240 /// Defines where and when timestamp values will be written for this pass.
241 pub timestamp_writes: Option<ArcPassTimestampWrites>,
242 /// Defines where the occlusion query results will be stored for this pass.
243 pub occlusion_query_set: Option<Arc<QuerySet>>,
244 }
245
246 pub struct RenderPass {
247 /// All pass data & records is stored here.
248 ///
249 /// If this is `None`, the pass is in the 'ended' state and can no longer be used.
250 /// Any attempt to record more commands will result in a validation error.
251 base: Option<BasePass<ArcRenderCommand>>,
252
253 /// Parent command buffer that this pass records commands into.
254 ///
255 /// If it is none, this pass is invalid and any operation on it will return an error.
256 parent: Option<Arc<CommandBuffer>>,
257
258 color_attachments:
259 ArrayVec<Option<ArcRenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>,
260 depth_stencil_attachment: Option<ArcRenderPassDepthStencilAttachment>,
261 timestamp_writes: Option<ArcPassTimestampWrites>,
262 occlusion_query_set: Option<Arc<QuerySet>>,
263
264 // Resource binding dedupe state.
265 current_bind_groups: BindGroupStateChange,
266 current_pipeline: StateChange<id::RenderPipelineId>,
267 }
268
269 impl RenderPass {
270 /// If the parent command buffer is invalid, the returned pass will be invalid.
271 fn new(parent: Option<Arc<CommandBuffer>>, desc: ArcRenderPassDescriptor) -> Self {
272 let ArcRenderPassDescriptor {
273 label,
274 timestamp_writes,
275 color_attachments,
276 depth_stencil_attachment,
277 occlusion_query_set,
278 } = desc;
279
280 Self {
281 base: Some(BasePass::new(label)),
282 parent,
283 color_attachments,
284 depth_stencil_attachment,
285 timestamp_writes,
286 occlusion_query_set,
287
288 current_bind_groups: BindGroupStateChange::new(),
289 current_pipeline: StateChange::new(),
290 }
291 }
292
293 #[inline]
294 pub fn label(&self) -> Option<&str> {
295 self.base.as_ref().and_then(|base| base.label.as_deref())
296 }
297
298 fn base_mut<'a>(
299 &'a mut self,
300 scope: PassErrorScope,
301 ) -> Result<&'a mut BasePass<ArcRenderCommand>, RenderPassError> {
302 self.base
303 .as_mut()
304 .ok_or(RenderPassErrorInner::PassEnded)
305 .map_pass_err(scope)
306 }
307 }
308
309 impl fmt::Debug for RenderPass {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 f.debug_struct("RenderPass")
312 .field("label", &self.label())
313 .field("color_attachments", &self.color_attachments)
314 .field("depth_stencil_target", &self.depth_stencil_attachment)
315 .field(
316 "command count",
317 &self.base.as_ref().map_or(0, |base| base.commands.len()),
318 )
319 .field(
320 "dynamic offset count",
321 &self
322 .base
323 .as_ref()
324 .map_or(0, |base| base.dynamic_offsets.len()),
325 )
326 .field(
327 "push constant u32 count",
328 &self
329 .base
330 .as_ref()
331 .map_or(0, |base| base.push_constant_data.len()),
332 )
333 .finish()
334 }
335 }
336
337 #[derive(Debug, PartialEq)]
338 enum OptionalState {
339 Unused,
340 Required,
341 Set,
342 }
343
344 impl OptionalState {
345 fn require(&mut self, require: bool) {
346 if require && *self == Self::Unused {
347 *self = Self::Required;
348 }
349 }
350 }
351
352 #[derive(Debug, Default)]
353 struct IndexState {
354 buffer_format: Option<IndexFormat>,
355 limit: u64,
356 }
357
358 impl IndexState {
359 fn update_buffer(&mut self, range: Range<BufferAddress>, format: IndexFormat) {
360 self.buffer_format = Some(format);
361 let shift = match format {
362 IndexFormat::Uint16 => 1,
363 IndexFormat::Uint32 => 2,
364 };
365 self.limit = (range.end - range.start) >> shift;
366 }
367
368 fn reset(&mut self) {
369 self.buffer_format = None;
370 self.limit = 0;
371 }
372 }
373
374 #[derive(Debug, Default)]
375 pub(crate) struct VertexLimits {
376 /// Length of the shortest vertex rate vertex buffer
377 pub(crate) vertex_limit: u64,
378 /// Buffer slot which the shortest vertex rate vertex buffer is bound to
379 vertex_limit_slot: u32,
380 /// Length of the shortest instance rate vertex buffer
381 pub(crate) instance_limit: u64,
382 /// Buffer slot which the shortest instance rate vertex buffer is bound to
383 instance_limit_slot: u32,
384 }
385
386 impl VertexLimits {
387 pub(crate) fn new(
388 buffer_sizes: impl Iterator<Item = Option<BufferAddress>>,
389 pipeline_steps: &[VertexStep],
390 ) -> Self {
391 // Implements the validation from https://gpuweb.github.io/gpuweb/#dom-gpurendercommandsmixin-draw
392 // Except that the formula is shuffled to extract the number of vertices in order
393 // to carry the bulk of the computation when changing states instead of when producing
394 // draws. Draw calls tend to happen at a higher frequency. Here we determine vertex
395 // limits that can be cheaply checked for each draw call.
396
397 let mut vertex_limit = u64::MAX;
398 let mut vertex_limit_slot = 0;
399 let mut instance_limit = u64::MAX;
400 let mut instance_limit_slot = 0;
401
402 for (idx, (buffer_size, step)) in buffer_sizes.zip(pipeline_steps).enumerate() {
403 let Some(buffer_size) = buffer_size else {
404 // Missing required vertex buffer
405 return Self::default();
406 };
407
408 let limit = if buffer_size < step.last_stride {
409 // The buffer cannot fit the last vertex.
410 0
411 } else {
412 if step.stride == 0 {
413 // We already checked that the last stride fits, the same
414 // vertex will be repeated so this slot can accommodate any number of
415 // vertices.
416 continue;
417 }
418
419 // The general case.
420 (buffer_size - step.last_stride) / step.stride + 1
421 };
422
423 match step.mode {
424 VertexStepMode::Vertex => {
425 if limit < vertex_limit {
426 vertex_limit = limit;
427 vertex_limit_slot = idx as _;
428 }
429 }
430 VertexStepMode::Instance => {
431 if limit < instance_limit {
432 instance_limit = limit;
433 instance_limit_slot = idx as _;
434 }
435 }
436 }
437 }
438
439 Self {
440 vertex_limit,
441 vertex_limit_slot,
442 instance_limit,
443 instance_limit_slot,
444 }
445 }
446
447 pub(crate) fn validate_vertex_limit(
448 &self,
449 first_vertex: u32,
450 vertex_count: u32,
451 ) -> Result<(), DrawError> {
452 let last_vertex = first_vertex as u64 + vertex_count as u64;
453 let vertex_limit = self.vertex_limit;
454 if last_vertex > vertex_limit {
455 return Err(DrawError::VertexBeyondLimit {
456 last_vertex,
457 vertex_limit,
458 slot: self.vertex_limit_slot,
459 });
460 }
461
462 Ok(())
463 }
464
465 pub(crate) fn validate_instance_limit(
466 &self,
467 first_instance: u32,
468 instance_count: u32,
469 ) -> Result<(), DrawError> {
470 let last_instance = first_instance as u64 + instance_count as u64;
471 let instance_limit = self.instance_limit;
472 if last_instance > instance_limit {
473 return Err(DrawError::InstanceBeyondLimit {
474 last_instance,
475 instance_limit,
476 slot: self.instance_limit_slot,
477 });
478 }
479
480 Ok(())
481 }
482 }
483
484 #[derive(Debug, Default)]
485 struct VertexState {
486 buffer_sizes: [Option<BufferAddress>; hal::MAX_VERTEX_BUFFERS],
487 limits: VertexLimits,
488 }
489
490 impl VertexState {
491 fn update_limits(&mut self, pipeline_steps: &[VertexStep]) {
492 self.limits = VertexLimits::new(self.buffer_sizes.iter().copied(), pipeline_steps);
493 }
494 }
495
496 struct State<'scope, 'snatch_guard, 'cmd_buf, 'raw_encoder> {
497 pipeline_flags: PipelineFlags,
498 binder: Binder,
499 blend_constant: OptionalState,
500 stencil_reference: u32,
501 pipeline: Option<Arc<RenderPipeline>>,
502 index: IndexState,
503 vertex: VertexState,
504 debug_scope_depth: u32,
505
506 info: RenderPassInfo<'scope>,
507
508 snatch_guard: &'snatch_guard SnatchGuard<'snatch_guard>,
509
510 device: &'cmd_buf Arc<Device>,
511
512 raw_encoder: &'raw_encoder mut dyn hal::DynCommandEncoder,
513
514 tracker: &'cmd_buf mut Tracker,
515 buffer_memory_init_actions: &'cmd_buf mut Vec<BufferInitTrackerAction>,
516 texture_memory_actions: &'cmd_buf mut CommandBufferTextureMemoryActions,
517
518 temp_offsets: Vec<u32>,
519 dynamic_offset_count: usize,
520 string_offset: usize,
521
522 active_occlusion_query: Option<(Arc<QuerySet>, u32)>,
523 active_pipeline_statistics_query: Option<(Arc<QuerySet>, u32)>,
524 }
525
526 impl<'scope, 'snatch_guard, 'cmd_buf, 'raw_encoder>
527 State<'scope, 'snatch_guard, 'cmd_buf, 'raw_encoder>
528 {
529 fn is_ready(&self, indexed: bool) -> Result<(), DrawError> {
530 if let Some(pipeline) = self.pipeline.as_ref() {
531 self.binder.check_compatibility(pipeline.as_ref())?;
532 self.binder.check_late_buffer_bindings()?;
533
534 if self.blend_constant == OptionalState::Required {
535 return Err(DrawError::MissingBlendConstant);
536 }
537
538 // Determine how many vertex buffers have already been bound
539 let vertex_buffer_count = self
540 .vertex
541 .buffer_sizes
542 .iter()
543 .take_while(|v| v.is_some())
544 .count() as u32;
545 // Compare with the needed quantity
546 if vertex_buffer_count < pipeline.vertex_steps.len() as u32 {
547 return Err(DrawError::MissingVertexBuffer {
548 pipeline: pipeline.error_ident(),
549 index: vertex_buffer_count,
550 });
551 }
552
553 if indexed {
554 // Pipeline expects an index buffer
555 if let Some(pipeline_index_format) = pipeline.strip_index_format {
556 // We have a buffer bound
557 let buffer_index_format = self
558 .index
559 .buffer_format
560 .ok_or(DrawError::MissingIndexBuffer)?;
561
562 // The buffers are different formats
563 if pipeline_index_format != buffer_index_format {
564 return Err(DrawError::UnmatchedIndexFormats {
565 pipeline: pipeline.error_ident(),
566 pipeline_format: pipeline_index_format,
567 buffer_format: buffer_index_format,
568 });
569 }
570 }
571 }
572 Ok(())
573 } else {
574 Err(DrawError::MissingPipeline)
575 }
576 }
577
578 /// Reset the `RenderBundle`-related states.
579 fn reset_bundle(&mut self) {
580 self.binder.reset();
581 self.pipeline = None;
582 self.index.reset();
583 self.vertex = Default::default();
584 }
585 }
586
587 /// Describes an attachment location in words.
588 ///
589 /// Can be used as "the {loc} has..." or "{loc} has..."
590 #[derive(Debug, Copy, Clone)]
591 pub enum AttachmentErrorLocation {
592 Color { index: usize, resolve: bool },
593 Depth,
594 }
595
596 impl fmt::Display for AttachmentErrorLocation {
597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598 match *self {
599 AttachmentErrorLocation::Color {
600 index,
601 resolve: false,
602 } => write!(f, "color attachment at index {index}'s texture view"),
603 AttachmentErrorLocation::Color {
604 index,
605 resolve: true,
606 } => write!(
607 f,
608 "color attachment at index {index}'s resolve texture view"
609 ),
610 AttachmentErrorLocation::Depth => write!(f, "depth attachment's texture view"),
611 }
612 }
613 }
614
615 #[derive(Clone, Debug, Error)]
616 #[non_exhaustive]
617 pub enum ColorAttachmentError {
618 #[error("Attachment format {0:?} is not a color format")]
619 InvalidFormat(wgt::TextureFormat),
620 #[error("The number of color attachments {given} exceeds the limit {limit}")]
621 TooMany { given: usize, limit: usize },
622 #[error("The total number of bytes per sample in color attachments {total} exceeds the limit {limit}")]
623 TooManyBytesPerSample { total: u32, limit: u32 },
624 #[error("Depth slice must be less than {limit} but is {given}")]
625 DepthSliceLimit { given: u32, limit: u32 },
626 #[error("Color attachment's view is 3D and requires depth slice to be provided")]
627 MissingDepthSlice,
628 #[error("Depth slice was provided but the color attachment's view is not 3D")]
629 UnneededDepthSlice,
630 #[error("{view}'s subresource at mip {mip_level} and depth/array layer {depth_or_array_layer} is already attached to this render pass")]
631 SubresourceOverlap {
632 view: ResourceErrorIdent,
633 mip_level: u32,
634 depth_or_array_layer: u32,
635 },
636 }
637
638 #[derive(Clone, Debug, Error)]
639 #[non_exhaustive]
640 pub enum AttachmentError {
641 #[error("The format of the depth-stencil attachment ({0:?}) is not a depth-or-stencil format")]
642 InvalidDepthStencilAttachmentFormat(wgt::TextureFormat),
643 #[error("Read-only attachment with load")]
644 ReadOnlyWithLoad,
645 #[error("Read-only attachment with store")]
646 ReadOnlyWithStore,
647 #[error("Attachment without load")]
648 NoLoad,
649 #[error("Attachment without store")]
650 NoStore,
651 #[error("LoadOp is `Clear` but no clear value was provided")]
652 NoClearValue,
653 #[error("Clear value ({0}) must be between 0.0 and 1.0, inclusive")]
654 ClearValueOutOfRange(f32),
655 }
656
657 /// Error encountered when performing a render pass.
658 #[derive(Clone, Debug, Error)]
659 pub enum RenderPassErrorInner {
660 #[error(transparent)]
661 Device(DeviceError),
662 #[error(transparent)]
663 ColorAttachment(#[from] ColorAttachmentError),
664 #[error(transparent)]
665 Encoder(#[from] CommandEncoderError),
666 #[error("Parent encoder is invalid")]
667 InvalidParentEncoder,
668 #[error("The format of the {location} ({format:?}) is not resolvable")]
669 UnsupportedResolveTargetFormat {
670 location: AttachmentErrorLocation,
671 format: wgt::TextureFormat,
672 },
673 #[error("No color attachments or depth attachments were provided, at least one attachment of any kind must be provided")]
674 MissingAttachments,
675 #[error("The {location} is not renderable:")]
676 TextureViewIsNotRenderable {
677 location: AttachmentErrorLocation,
678 #[source]
679 reason: TextureViewNotRenderableReason,
680 },
681 #[error("Attachments have differing sizes: the {expected_location} has extent {expected_extent:?} but is followed by the {actual_location} which has {actual_extent:?}")]
682 AttachmentsDimensionMismatch {
683 expected_location: AttachmentErrorLocation,
684 expected_extent: wgt::Extent3d,
685 actual_location: AttachmentErrorLocation,
686 actual_extent: wgt::Extent3d,
687 },
688 #[error("Attachments have differing sample counts: the {expected_location} has count {expected_samples:?} but is followed by the {actual_location} which has count {actual_samples:?}")]
689 AttachmentSampleCountMismatch {
690 expected_location: AttachmentErrorLocation,
691 expected_samples: u32,
692 actual_location: AttachmentErrorLocation,
693 actual_samples: u32,
694 },
695 #[error("The resolve source, {location}, must be multi-sampled (has {src} samples) while the resolve destination must not be multisampled (has {dst} samples)")]
696 InvalidResolveSampleCounts {
697 location: AttachmentErrorLocation,
698 src: u32,
699 dst: u32,
700 },
701 #[error(
702 "Resource source, {location}, format ({src:?}) must match the resolve destination format ({dst:?})"
703 )]
704 MismatchedResolveTextureFormat {
705 location: AttachmentErrorLocation,
706 src: wgt::TextureFormat,
707 dst: wgt::TextureFormat,
708 },
709 #[error("Unable to clear non-present/read-only depth")]
710 InvalidDepthOps,
711 #[error("Unable to clear non-present/read-only stencil")]
712 InvalidStencilOps,
713 #[error("Setting `values_offset` to be `None` is only for internal use in render bundles")]
714 InvalidValuesOffset,
715 #[error(transparent)]
716 MissingFeatures(#[from] MissingFeatures),
717 #[error(transparent)]
718 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
719 #[error("Indirect buffer offset {0:?} is not a multiple of 4")]
720 UnalignedIndirectBufferOffset(BufferAddress),
721 #[error("Indirect draw uses bytes {offset}..{end_offset} using count {count} which overruns indirect buffer of size {buffer_size}")]
722 IndirectBufferOverrun {
723 count: u32,
724 offset: u64,
725 end_offset: u64,
726 buffer_size: u64,
727 },
728 #[error("Indirect draw uses bytes {begin_count_offset}..{end_count_offset} which overruns indirect buffer of size {count_buffer_size}")]
729 IndirectCountBufferOverrun {
730 begin_count_offset: u64,
731 end_count_offset: u64,
732 count_buffer_size: u64,
733 },
734 #[error("Cannot pop debug group, because number of pushed debug groups is zero")]
735 InvalidPopDebugGroup,
736 #[error(transparent)]
737 ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
738 #[error("Render bundle has incompatible targets, {0}")]
739 IncompatibleBundleTargets(#[from] RenderPassCompatibilityError),
740 #[error(
741 "Render bundle has incompatible read-only flags: \
742 bundle has flags depth = {bundle_depth} and stencil = {bundle_stencil}, \
743 while the pass has flags depth = {pass_depth} and stencil = {pass_stencil}. \
744 Read-only renderpasses are only compatible with read-only bundles for that aspect."
745 )]
746 IncompatibleBundleReadOnlyDepthStencil {
747 pass_depth: bool,
748 pass_stencil: bool,
749 bundle_depth: bool,
750 bundle_stencil: bool,
751 },
752 #[error(transparent)]
753 RenderCommand(#[from] RenderCommandError),
754 #[error(transparent)]
755 Draw(#[from] DrawError),
756 #[error(transparent)]
757 Bind(#[from] BindError),
758 #[error("Push constant offset must be aligned to 4 bytes")]
759 PushConstantOffsetAlignment,
760 #[error("Push constant size must be aligned to 4 bytes")]
761 PushConstantSizeAlignment,
762 #[error("Ran out of push constant space. Don't set 4gb of push constants per ComputePass.")]
763 PushConstantOutOfMemory,
764 #[error(transparent)]
765 QueryUse(#[from] QueryUseError),
766 #[error("Multiview layer count must match")]
767 MultiViewMismatch,
768 #[error(
769 "Multiview pass texture views with more than one array layer must have D2Array dimension"
770 )]
771 MultiViewDimensionMismatch,
772 #[error("missing occlusion query set")]
773 MissingOcclusionQuerySet,
774 #[error(transparent)]
775 DestroyedResource(#[from] DestroyedResourceError),
776 #[error("The compute pass has already been ended and no further commands can be recorded")]
777 PassEnded,
778 #[error(transparent)]
779 InvalidResource(#[from] InvalidResourceError),
780 }
781
782 impl From<MissingBufferUsageError> for RenderPassErrorInner {
783 fn from(error: MissingBufferUsageError) -> Self {
784 Self::RenderCommand(error.into())
785 }
786 }
787
788 impl From<MissingTextureUsageError> for RenderPassErrorInner {
789 fn from(error: MissingTextureUsageError) -> Self {
790 Self::RenderCommand(error.into())
791 }
792 }
793
794 impl From<DeviceError> for RenderPassErrorInner {
795 fn from(error: DeviceError) -> Self {
796 Self::Device(error)
797 }
798 }
799
800 /// Error encountered when performing a render pass.
801 #[derive(Clone, Debug, Error)]
802 #[error("{scope}")]
803 pub struct RenderPassError {
804 pub scope: PassErrorScope,
805 #[source]
806 pub(super) inner: RenderPassErrorInner,
807 }
808
809 impl<T, E> MapPassErr<T, RenderPassError> for Result<T, E>
810 where
811 E: Into<RenderPassErrorInner>,
812 {
813 fn map_pass_err(self, scope: PassErrorScope) -> Result<T, RenderPassError> {
814 self.map_err(|inner| RenderPassError {
815 scope,
816 inner: inner.into(),
817 })
818 }
819 }
820
821 struct RenderAttachment {
822 texture: Arc<Texture>,
823 selector: TextureSelector,
824 usage: wgt::TextureUses,
825 }
826
827 impl TextureView {
828 fn to_render_attachment(&self, usage: wgt::TextureUses) -> RenderAttachment {
829 RenderAttachment {
830 texture: self.parent.clone(),
831 selector: self.selector.clone(),
832 usage,
833 }
834 }
835 }
836
837 const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_ATTACHMENTS + hal::MAX_COLOR_ATTACHMENTS + 1;
838 type AttachmentDataVec<T> = ArrayVec<T, MAX_TOTAL_ATTACHMENTS>;
839
840 struct RenderPassInfo<'d> {
841 context: RenderPassContext,
842 usage_scope: UsageScope<'d>,
843 /// All render attachments, including depth/stencil
844 render_attachments: AttachmentDataVec<RenderAttachment>,
845 is_depth_read_only: bool,
846 is_stencil_read_only: bool,
847 extent: wgt::Extent3d,
848
849 pending_discard_init_fixups: SurfacesInDiscardState,
850 divergent_discarded_depth_stencil_aspect: Option<(wgt::TextureAspect, Arc<TextureView>)>,
851 multiview: Option<NonZeroU32>,
852 }
853
854 impl<'d> RenderPassInfo<'d> {
855 fn add_pass_texture_init_actions<V>(
856 load_op: LoadOp<V>,
857 store_op: StoreOp,
858 texture_memory_actions: &mut CommandBufferTextureMemoryActions,
859 view: &TextureView,
860 pending_discard_init_fixups: &mut SurfacesInDiscardState,
861 ) {
862 if matches!(load_op, LoadOp::Load) {
863 pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
864 &TextureInitTrackerAction {
865 texture: view.parent.clone(),
866 range: TextureInitRange::from(view.selector.clone()),
867 // Note that this is needed even if the target is discarded,
868 kind: MemoryInitKind::NeedsInitializedMemory,
869 },
870 ));
871 } else if store_op == StoreOp::Store {
872 // Clear + Store
873 texture_memory_actions.register_implicit_init(
874 &view.parent,
875 TextureInitRange::from(view.selector.clone()),
876 );
877 }
878 if store_op == StoreOp::Discard {
879 // the discard happens at the *end* of a pass, but recording the
880 // discard right away be alright since the texture can't be used
881 // during the pass anyways
882 texture_memory_actions.discard(TextureSurfaceDiscard {
883 texture: view.parent.clone(),
884 mip_level: view.selector.mips.start,
885 layer: view.selector.layers.start,
886 });
887 }
888 }
889
890 fn start(
891 device: &'d Arc<Device>,
892 hal_label: Option<&str>,
893 color_attachments: ArrayVec<
894 Option<ArcRenderPassColorAttachment>,
895 { hal::MAX_COLOR_ATTACHMENTS },
896 >,
897 mut depth_stencil_attachment: Option<ArcRenderPassDepthStencilAttachment>,
898 mut timestamp_writes: Option<ArcPassTimestampWrites>,
899 mut occlusion_query_set: Option<Arc<QuerySet>>,
900 encoder: &mut CommandEncoder,
901 trackers: &mut Tracker,
902 texture_memory_actions: &mut CommandBufferTextureMemoryActions,
903 pending_query_resets: &mut QueryResetMap,
904 snatch_guard: &SnatchGuard<'_>,
905 ) -> Result<Self, RenderPassErrorInner> {
906 profiling::scope!("RenderPassInfo::start");
907
908 // We default to false intentionally, even if depth-stencil isn't used at all.
909 // This allows us to use the primary raw pipeline in `RenderPipeline`,
910 // instead of the special read-only one, which would be `None`.
911 let mut is_depth_read_only = false;
912 let mut is_stencil_read_only = false;
913
914 let mut render_attachments = AttachmentDataVec::<RenderAttachment>::new();
915 let mut discarded_surfaces = AttachmentDataVec::new();
916 let mut pending_discard_init_fixups = SurfacesInDiscardState::new();
917 let mut divergent_discarded_depth_stencil_aspect = None;
918
919 let mut attachment_location = AttachmentErrorLocation::Color {
920 index: usize::MAX,
921 resolve: false,
922 };
923 let mut extent = None;
924 let mut sample_count = 0;
925
926 let mut detected_multiview: Option<Option<NonZeroU32>> = None;
927
928 let mut check_multiview = |view: &TextureView| {
929 // Get the multiview configuration for this texture view
930 let layers = view.selector.layers.end - view.selector.layers.start;
931 let this_multiview = if layers >= 2 {
932 // Trivially proven by the if above
933 Some(unsafe { NonZeroU32::new_unchecked(layers) })
934 } else {
935 None
936 };
937
938 // Make sure that if this view is a multiview, it is set to be an array
939 if this_multiview.is_some() && view.desc.dimension != TextureViewDimension::D2Array {
940 return Err(RenderPassErrorInner::MultiViewDimensionMismatch);
941 }
942
943 // Validate matching first, or store the first one
944 if let Some(multiview) = detected_multiview {
945 if multiview != this_multiview {
946 return Err(RenderPassErrorInner::MultiViewMismatch);
947 }
948 } else {
949 // Multiview is only supported if the feature is enabled
950 if this_multiview.is_some() {
951 device.require_features(wgt::Features::MULTIVIEW)?;
952 }
953
954 detected_multiview = Some(this_multiview);
955 }
956
957 Ok(())
958 };
959 let mut add_view = |view: &TextureView, location| {
960 let render_extent = view.render_extent.map_err(|reason| {
961 RenderPassErrorInner::TextureViewIsNotRenderable { location, reason }
962 })?;
963 if let Some(ex) = extent {
964 if ex != render_extent {
965 return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
966 expected_location: attachment_location,
967 expected_extent: ex,
968 actual_location: location,
969 actual_extent: render_extent,
970 });
971 }
972 } else {
973 extent = Some(render_extent);
974 }
975 if sample_count == 0 {
976 sample_count = view.samples;
977 } else if sample_count != view.samples {
978 return Err(RenderPassErrorInner::AttachmentSampleCountMismatch {
979 expected_location: attachment_location,
980 expected_samples: sample_count,
981 actual_location: location,
982 actual_samples: view.samples,
983 });
984 }
985 attachment_location = location;
986 Ok(())
987 };
988
989 let mut depth_stencil = None;
990
991 if let Some(at) = depth_stencil_attachment.as_ref() {
992 let view = &at.view;
993 check_multiview(view)?;
994 add_view(view, AttachmentErrorLocation::Depth)?;
995
996 let ds_aspects = view.desc.aspects();
997
998 if !ds_aspects.contains(hal::FormatAspects::STENCIL)
999 || (at.stencil.load_op().eq_variant(at.depth.load_op())
1000 && at.stencil.store_op() == at.depth.store_op())
1001 {
1002 Self::add_pass_texture_init_actions(
1003 at.depth.load_op(),
1004 at.depth.store_op(),
1005 texture_memory_actions,
1006 view,
1007 &mut pending_discard_init_fixups,
1008 );
1009 } else if !ds_aspects.contains(hal::FormatAspects::DEPTH) {
1010 Self::add_pass_texture_init_actions(
1011 at.stencil.load_op(),
1012 at.stencil.store_op(),
1013 texture_memory_actions,
1014 view,
1015 &mut pending_discard_init_fixups,
1016 );
1017 } else {
1018 // This is the only place (anywhere in wgpu) where Stencil &
1019 // Depth init state can diverge.
1020 //
1021 // To safe us the overhead of tracking init state of texture
1022 // aspects everywhere, we're going to cheat a little bit in
1023 // order to keep the init state of both Stencil and Depth
1024 // aspects in sync. The expectation is that we hit this path
1025 // extremely rarely!
1026 //
1027 // Diverging LoadOp, i.e. Load + Clear:
1028 //
1029 // Record MemoryInitKind::NeedsInitializedMemory for the entire
1030 // surface, a bit wasteful on unit but no negative effect!
1031 //
1032 // Rationale: If the loaded channel is uninitialized it needs
1033 // clearing, the cleared channel doesn't care. (If everything is
1034 // already initialized nothing special happens)
1035 //
1036 // (possible minor optimization: Clear caused by
1037 // NeedsInitializedMemory should know that it doesn't need to
1038 // clear the aspect that was set to C)
1039 let need_init_beforehand =
1040 at.depth.load_op() == LoadOp::Load || at.stencil.load_op() == LoadOp::Load;
1041 if need_init_beforehand {
1042 pending_discard_init_fixups.extend(
1043 texture_memory_actions.register_init_action(&TextureInitTrackerAction {
1044 texture: view.parent.clone(),
1045 range: TextureInitRange::from(view.selector.clone()),
1046 kind: MemoryInitKind::NeedsInitializedMemory,
1047 }),
1048 );
1049 }
1050
1051 // Diverging Store, i.e. Discard + Store:
1052 //
1053 // Immediately zero out channel that is set to discard after
1054 // we're done with the render pass. This allows us to set the
1055 // entire surface to MemoryInitKind::ImplicitlyInitialized (if
1056 // it isn't already set to NeedsInitializedMemory).
1057 //
1058 // (possible optimization: Delay and potentially drop this zeroing)
1059 if at.depth.store_op() != at.stencil.store_op() {
1060 if !need_init_beforehand {
1061 texture_memory_actions.register_implicit_init(
1062 &view.parent,
1063 TextureInitRange::from(view.selector.clone()),
1064 );
1065 }
1066 divergent_discarded_depth_stencil_aspect = Some((
1067 if at.depth.store_op() == StoreOp::Discard {
1068 wgt::TextureAspect::DepthOnly
1069 } else {
1070 wgt::TextureAspect::StencilOnly
1071 },
1072 view.clone(),
1073 ));
1074 } else if at.depth.store_op() == StoreOp::Discard {
1075 // Both are discarded using the regular path.
1076 discarded_surfaces.push(TextureSurfaceDiscard {
1077 texture: view.parent.clone(),
1078 mip_level: view.selector.mips.start,
1079 layer: view.selector.layers.start,
1080 });
1081 }
1082 }
1083
1084 is_depth_read_only = at.depth.is_readonly();
1085 is_stencil_read_only = at.stencil.is_readonly();
1086
1087 let usage = if is_depth_read_only
1088 && is_stencil_read_only
1089 && device
1090 .downlevel
1091 .flags
1092 .contains(wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL)
1093 {
1094 wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::RESOURCE
1095 } else {
1096 wgt::TextureUses::DEPTH_STENCIL_WRITE
1097 };
1098 render_attachments.push(view.to_render_attachment(usage));
1099
1100 depth_stencil = Some(hal::DepthStencilAttachment {
1101 target: hal::Attachment {
1102 view: view.try_raw(snatch_guard)?,
1103 usage,
1104 },
1105 depth_ops: at.depth.hal_ops(),
1106 stencil_ops: at.stencil.hal_ops(),
1107 clear_value: (at.depth.clear_value(), at.stencil.clear_value()),
1108 });
1109 }
1110
1111 let mut attachment_set = crate::FastHashSet::default();
1112
1113 let mut color_attachments_hal =
1114 ArrayVec::<Option<hal::ColorAttachment<_>>, { hal::MAX_COLOR_ATTACHMENTS }>::new();
1115 for (index, attachment) in color_attachments.iter().enumerate() {
1116 let at = if let Some(attachment) = attachment.as_ref() {
1117 attachment
1118 } else {
1119 color_attachments_hal.push(None);
1120 continue;
1121 };
1122 let color_view: &TextureView = &at.view;
1123 color_view.same_device(device)?;
1124 check_multiview(color_view)?;
1125 add_view(
1126 color_view,
1127 AttachmentErrorLocation::Color {
1128 index,
1129 resolve: false,
1130 },
1131 )?;
1132
1133 if !color_view
1134 .desc
1135 .aspects()
1136 .contains(hal::FormatAspects::COLOR)
1137 {
1138 return Err(RenderPassErrorInner::ColorAttachment(
1139 ColorAttachmentError::InvalidFormat(color_view.desc.format),
1140 ));
1141 }
1142
1143 if color_view.desc.dimension == TextureViewDimension::D3 {
1144 if let Some(depth_slice) = at.depth_slice {
1145 let mip = color_view.desc.range.base_mip_level;
1146 let mip_size = color_view
1147 .parent
1148 .desc
1149 .size
1150 .mip_level_size(mip, color_view.parent.desc.dimension);
1151 let limit = mip_size.depth_or_array_layers;
1152 if depth_slice >= limit {
1153 return Err(RenderPassErrorInner::ColorAttachment(
1154 ColorAttachmentError::DepthSliceLimit {
1155 given: depth_slice,
1156 limit,
1157 },
1158 ));
1159 }
1160 } else {
1161 return Err(RenderPassErrorInner::ColorAttachment(
1162 ColorAttachmentError::MissingDepthSlice,
1163 ));
1164 }
1165 } else if at.depth_slice.is_some() {
1166 return Err(RenderPassErrorInner::ColorAttachment(
1167 ColorAttachmentError::UnneededDepthSlice,
1168 ));
1169 }
1170
1171 fn check_attachment_overlap(
1172 attachment_set: &mut crate::FastHashSet<(crate::track::TrackerIndex, u32, u32)>,
1173 view: &TextureView,
1174 depth_slice: Option<u32>,
1175 ) -> Result<(), ColorAttachmentError> {
1176 let mut insert = |slice| {
1177 let mip_level = view.desc.range.base_mip_level;
1178 if attachment_set.insert((view.tracking_data.tracker_index(), mip_level, slice))
1179 {
1180 Ok(())
1181 } else {
1182 Err(ColorAttachmentError::SubresourceOverlap {
1183 view: view.error_ident(),
1184 mip_level,
1185 depth_or_array_layer: slice,
1186 })
1187 }
1188 };
1189 match view.desc.dimension {
1190 TextureViewDimension::D2 => {
1191 insert(view.desc.range.base_array_layer)?;
1192 }
1193 TextureViewDimension::D2Array => {
1194 for layer in view.selector.layers.clone() {
1195 insert(layer)?;
1196 }
1197 }
1198 TextureViewDimension::D3 => {
1199 insert(depth_slice.unwrap())?;
1200 }
1201 _ => unreachable!(),
1202 };
1203 Ok(())
1204 }
1205
1206 check_attachment_overlap(&mut attachment_set, color_view, at.depth_slice)?;
1207
1208 Self::add_pass_texture_init_actions(
1209 at.load_op,
1210 at.store_op,
1211 texture_memory_actions,
1212 color_view,
1213 &mut pending_discard_init_fixups,
1214 );
1215 render_attachments
1216 .push(color_view.to_render_attachment(wgt::TextureUses::COLOR_TARGET));
1217
1218 let mut hal_resolve_target = None;
1219 if let Some(resolve_view) = &at.resolve_target {
1220 resolve_view.same_device(device)?;
1221 check_multiview(resolve_view)?;
1222
1223 check_attachment_overlap(&mut attachment_set, resolve_view, None)?;
1224
1225 let resolve_location = AttachmentErrorLocation::Color {
1226 index,
1227 resolve: true,
1228 };
1229
1230 let render_extent = resolve_view.render_extent.map_err(|reason| {
1231 RenderPassErrorInner::TextureViewIsNotRenderable {
1232 location: resolve_location,
1233 reason,
1234 }
1235 })?;
1236 if color_view.render_extent.unwrap() != render_extent {
1237 return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
1238 expected_location: attachment_location,
1239 expected_extent: extent.unwrap_or_default(),
1240 actual_location: resolve_location,
1241 actual_extent: render_extent,
1242 });
1243 }
1244 if color_view.samples == 1 || resolve_view.samples != 1 {
1245 return Err(RenderPassErrorInner::InvalidResolveSampleCounts {
1246 location: resolve_location,
1247 src: color_view.samples,
1248 dst: resolve_view.samples,
1249 });
1250 }
1251 if color_view.desc.format != resolve_view.desc.format {
1252 return Err(RenderPassErrorInner::MismatchedResolveTextureFormat {
1253 location: resolve_location,
1254 src: color_view.desc.format,
1255 dst: resolve_view.desc.format,
1256 });
1257 }
1258 if !resolve_view
1259 .format_features
1260 .flags
1261 .contains(wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE)
1262 {
1263 return Err(RenderPassErrorInner::UnsupportedResolveTargetFormat {
1264 location: resolve_location,
1265 format: resolve_view.desc.format,
1266 });
1267 }
1268
1269 texture_memory_actions.register_implicit_init(
1270 &resolve_view.parent,
1271 TextureInitRange::from(resolve_view.selector.clone()),
1272 );
1273 render_attachments
1274 .push(resolve_view.to_render_attachment(wgt::TextureUses::COLOR_TARGET));
1275
1276 hal_resolve_target = Some(hal::Attachment {
1277 view: resolve_view.try_raw(snatch_guard)?,
1278 usage: wgt::TextureUses::COLOR_TARGET,
1279 });
1280 }
1281
1282 color_attachments_hal.push(Some(hal::ColorAttachment {
1283 target: hal::Attachment {
1284 view: color_view.try_raw(snatch_guard)?,
1285 usage: wgt::TextureUses::COLOR_TARGET,
1286 },
1287 depth_slice: at.depth_slice,
1288 resolve_target: hal_resolve_target,
1289 ops: at.hal_ops(),
1290 clear_value: at.clear_value(),
1291 }));
1292 }
1293
1294 let extent = extent.ok_or(RenderPassErrorInner::MissingAttachments)?;
1295 let multiview = detected_multiview.expect("Multiview was not detected, no attachments");
1296
1297 let attachment_formats = AttachmentData {
1298 colors: color_attachments
1299 .iter()
1300 .map(|at| at.as_ref().map(|at| at.view.desc.format))
1301 .collect(),
1302 resolves: color_attachments
1303 .iter()
1304 .filter_map(|at| {
1305 at.as_ref().and_then(|at| {
1306 at.resolve_target
1307 .as_ref()
1308 .map(|resolve| resolve.desc.format)
1309 })
1310 })
1311 .collect(),
1312 depth_stencil: depth_stencil_attachment
1313 .as_ref()
1314 .map(|at| at.view.desc.format),
1315 };
1316
1317 let context = RenderPassContext {
1318 attachments: attachment_formats,
1319 sample_count,
1320 multiview,
1321 };
1322
1323 let timestamp_writes_hal = if let Some(tw) = timestamp_writes.as_ref() {
1324 let query_set = &tw.query_set;
1325 query_set.same_device(device)?;
1326
1327 if let Some(index) = tw.beginning_of_pass_write_index {
1328 pending_query_resets.use_query_set(query_set, index);
1329 }
1330 if let Some(index) = tw.end_of_pass_write_index {
1331 pending_query_resets.use_query_set(query_set, index);
1332 }
1333
1334 Some(hal::PassTimestampWrites {
1335 query_set: query_set.raw(),
1336 beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
1337 end_of_pass_write_index: tw.end_of_pass_write_index,
1338 })
1339 } else {
1340 None
1341 };
1342
1343 let occlusion_query_set_hal = if let Some(query_set) = occlusion_query_set.as_ref() {
1344 query_set.same_device(device)?;
1345 Some(query_set.raw())
1346 } else {
1347 None
1348 };
1349
1350 let hal_desc = hal::RenderPassDescriptor {
1351 label: hal_label,
1352 extent,
1353 sample_count,
1354 color_attachments: &color_attachments_hal,
1355 depth_stencil_attachment: depth_stencil,
1356 multiview,
1357 timestamp_writes: timestamp_writes_hal,
1358 occlusion_query_set: occlusion_query_set_hal,
1359 };
1360 unsafe {
1361 encoder
1362 .raw
1363 .begin_render_pass(&hal_desc)
1364 .map_err(|e| device.handle_hal_error(e))?;
1365 };
1366 drop(color_attachments_hal); // Drop, so we can consume `color_attachments` for the tracker.
1367
1368 // Can't borrow the tracker more than once, so have to add to the tracker after the `begin_render_pass` hal call.
1369 if let Some(tw) = timestamp_writes.take() {
1370 trackers.query_sets.insert_single(tw.query_set);
1371 };
1372 if let Some(occlusion_query_set) = occlusion_query_set.take() {
1373 trackers.query_sets.insert_single(occlusion_query_set);
1374 };
1375 if let Some(at) = depth_stencil_attachment.take() {
1376 trackers.views.insert_single(at.view.clone());
1377 }
1378 for at in color_attachments.into_iter().flatten() {
1379 trackers.views.insert_single(at.view.clone());
1380 if let Some(resolve_target) = at.resolve_target {
1381 trackers.views.insert_single(resolve_target);
1382 }
1383 }
1384
1385 Ok(Self {
1386 context,
1387 usage_scope: device.new_usage_scope(),
1388 render_attachments,
1389 is_depth_read_only,
1390 is_stencil_read_only,
1391 extent,
1392 pending_discard_init_fixups,
1393 divergent_discarded_depth_stencil_aspect,
1394 multiview,
1395 })
1396 }
1397
1398 fn finish(
1399 mut self,
1400 device: &Device,
1401 raw: &mut dyn hal::DynCommandEncoder,
1402 snatch_guard: &SnatchGuard,
1403 ) -> Result<(UsageScope<'d>, SurfacesInDiscardState), RenderPassErrorInner> {
1404 profiling::scope!("RenderPassInfo::finish");
1405 unsafe {
1406 raw.end_render_pass();
1407 }
1408
1409 for ra in self.render_attachments {
1410 let texture = &ra.texture;
1411 texture.check_usage(TextureUsages::RENDER_ATTACHMENT)?;
1412
1413 // the tracker set of the pass is always in "extend" mode
1414 unsafe {
1415 self.usage_scope.textures.merge_single(
1416 texture,
1417 Some(ra.selector.clone()),
1418 ra.usage,
1419 )?
1420 };
1421 }
1422
1423 // If either only stencil or depth was discarded, we put in a special
1424 // clear pass to keep the init status of the aspects in sync. We do this
1425 // so we don't need to track init state for depth/stencil aspects
1426 // individually.
1427 //
1428 // Note that we don't go the usual route of "brute force" initializing
1429 // the texture when need arises here, since this path is actually
1430 // something a user may genuinely want (where as the other cases are
1431 // more seen along the lines as gracefully handling a user error).
1432 if let Some((aspect, view)) = self.divergent_discarded_depth_stencil_aspect {
1433 let (depth_ops, stencil_ops) = if aspect == wgt::TextureAspect::DepthOnly {
1434 (
1435 hal::AttachmentOps::STORE, // clear depth
1436 hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
1437 )
1438 } else {
1439 (
1440 hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
1441 hal::AttachmentOps::STORE, // clear depth
1442 )
1443 };
1444 let desc = hal::RenderPassDescriptor::<'_, _, dyn hal::DynTextureView> {
1445 label: Some("(wgpu internal) Zero init discarded depth/stencil aspect"),
1446 extent: view.render_extent.unwrap(),
1447 sample_count: view.samples,
1448 color_attachments: &[],
1449 depth_stencil_attachment: Some(hal::DepthStencilAttachment {
1450 target: hal::Attachment {
1451 view: view.try_raw(snatch_guard)?,
1452 usage: wgt::TextureUses::DEPTH_STENCIL_WRITE,
1453 },
1454 depth_ops,
1455 stencil_ops,
1456 clear_value: (0.0, 0),
1457 }),
1458 multiview: self.multiview,
1459 timestamp_writes: None,
1460 occlusion_query_set: None,
1461 };
1462 unsafe {
1463 raw.begin_render_pass(&desc)
1464 .map_err(|e| device.handle_hal_error(e))?;
1465 raw.end_render_pass();
1466 }
1467 }
1468
1469 Ok((self.usage_scope, self.pending_discard_init_fixups))
1470 }
1471 }
1472
1473 impl Global {
1474 /// Creates a render pass.
1475 ///
1476 /// If creation fails, an invalid pass is returned.
1477 /// Any operation on an invalid pass will return an error.
1478 ///
1479 /// If successful, puts the encoder into the [`Locked`] state.
1480 ///
1481 /// [`Locked`]: crate::command::CommandEncoderStatus::Locked
1482 pub fn command_encoder_begin_render_pass(
1483 &self,
1484 encoder_id: id::CommandEncoderId,
1485 desc: &RenderPassDescriptor<'_>,
1486 ) -> (RenderPass, Option<CommandEncoderError>) {
1487 fn fill_arc_desc(
1488 hub: &crate::hub::Hub,
1489 desc: &RenderPassDescriptor<'_>,
1490 arc_desc: &mut ArcRenderPassDescriptor,
1491 device: &Device,
1492 ) -> Result<(), CommandEncoderError> {
1493 let query_sets = hub.query_sets.read();
1494 let texture_views = hub.texture_views.read();
1495
1496 let max_color_attachments = device.limits.max_color_attachments as usize;
1497 if desc.color_attachments.len() > max_color_attachments {
1498 return Err(CommandEncoderError::InvalidColorAttachment(
1499 ColorAttachmentError::TooMany {
1500 given: desc.color_attachments.len(),
1501 limit: max_color_attachments,
1502 },
1503 ));
1504 }
1505
1506 for color_attachment in desc.color_attachments.iter() {
1507 if let Some(RenderPassColorAttachment {
1508 view: view_id,
1509 depth_slice,
1510 resolve_target,
1511 load_op,
1512 store_op,
1513 }) = color_attachment
1514 {
1515 let view = texture_views.get(*view_id).get()?;
1516 view.same_device(device)?;
1517
1518 let resolve_target = if let Some(resolve_target_id) = resolve_target {
1519 let rt_arc = texture_views.get(*resolve_target_id).get()?;
1520 rt_arc.same_device(device)?;
1521
1522 Some(rt_arc)
1523 } else {
1524 None
1525 };
1526
1527 arc_desc
1528 .color_attachments
1529 .push(Some(ArcRenderPassColorAttachment {
1530 view,
1531 depth_slice: *depth_slice,
1532 resolve_target,
1533 load_op: *load_op,
1534 store_op: *store_op,
1535 }));
1536 } else {
1537 arc_desc.color_attachments.push(None);
1538 }
1539 }
1540
1541 arc_desc.depth_stencil_attachment =
1542 // https://gpuweb.github.io/gpuweb/#abstract-opdef-gpurenderpassdepthstencilattachment-gpurenderpassdepthstencilattachment-valid-usage
1543 if let Some(depth_stencil_attachment) = desc.depth_stencil_attachment {
1544 let view = texture_views.get(depth_stencil_attachment.view).get()?;
1545 view.same_device(device)?;
1546
1547 let format = view.desc.format;
1548 if !format.is_depth_stencil_format() {
1549 return Err(CommandEncoderError::InvalidAttachment(AttachmentError::InvalidDepthStencilAttachmentFormat(
1550 view.desc.format,
1551 )));
1552 }
1553
1554 Some(ArcRenderPassDepthStencilAttachment {
1555 view,
1556 depth: if format.has_depth_aspect() {
1557 depth_stencil_attachment.depth.resolve(|clear| if let Some(clear) = clear {
1558 // If this.depthLoadOp is "clear", this.depthClearValue must be provided and must be between 0.0 and 1.0, inclusive.
1559 if !(0.0..=1.0).contains(&clear) {
1560 Err(AttachmentError::ClearValueOutOfRange(clear))
1561 } else {
1562 Ok(clear)
1563 }
1564 } else {
1565 Err(AttachmentError::NoClearValue)
1566 })?
1567 } else {
1568 ResolvedPassChannel::ReadOnly
1569 },
1570 stencil: if format.has_stencil_aspect() {
1571 depth_stencil_attachment.stencil.resolve(|clear| Ok(clear.unwrap_or_default()))?
1572 } else {
1573 ResolvedPassChannel::ReadOnly
1574 },
1575 })
1576 } else {
1577 None
1578 };
1579
1580 arc_desc.timestamp_writes = desc
1581 .timestamp_writes
1582 .map(|tw| Global::validate_pass_timestamp_writes(device, &query_sets, tw))
1583 .transpose()?;
1584
1585 arc_desc.occlusion_query_set =
1586 if let Some(occlusion_query_set) = desc.occlusion_query_set {
1587 let query_set = query_sets.get(occlusion_query_set).get()?;
1588 query_set.same_device(device)?;
1589
1590 Some(query_set)
1591 } else {
1592 None
1593 };
1594
1595 Ok(())
1596 }
1597
1598 let hub = &self.hub;
1599 let mut arc_desc = ArcRenderPassDescriptor {
1600 label: &desc.label,
1601 timestamp_writes: None,
1602 color_attachments: ArrayVec::new(),
1603 depth_stencil_attachment: None,
1604 occlusion_query_set: None,
1605 };
1606
1607 let make_err = |e, arc_desc| (RenderPass::new(None, arc_desc), Some(e));
1608
1609 let cmd_buf = hub.command_buffers.get(encoder_id.into_command_buffer_id());
1610
1611 match cmd_buf.data.lock().lock_encoder() {
1612 Ok(_) => {}
1613 Err(e) => return make_err(e, arc_desc),
1614 };
1615
1616 let err = fill_arc_desc(hub, desc, &mut arc_desc, &cmd_buf.device).err();
1617
1618 (RenderPass::new(Some(cmd_buf), arc_desc), err)
1619 }
1620
1621 /// Note that this differs from [`Self::render_pass_end`], it will
1622 /// create a new pass, replay the commands and end the pass.
1623 #[doc(hidden)]
1624 #[cfg(any(feature = "serde", feature = "replay"))]
1625 pub fn render_pass_end_with_unresolved_commands(
1626 &self,
1627 encoder_id: id::CommandEncoderId,
1628 base: BasePass<super::RenderCommand>,
1629 color_attachments: &[Option<RenderPassColorAttachment>],
1630 depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
1631 timestamp_writes: Option<&PassTimestampWrites>,
1632 occlusion_query_set: Option<id::QuerySetId>,
1633 ) -> Result<(), RenderPassError> {
1634 let pass_scope = PassErrorScope::Pass;
1635
1636 #[cfg(feature = "trace")]
1637 {
1638 let cmd_buf = self
1639 .hub
1640 .command_buffers
1641 .get(encoder_id.into_command_buffer_id());
1642 let mut cmd_buf_data = cmd_buf.data.lock();
1643 let cmd_buf_data = cmd_buf_data.get_inner().map_pass_err(pass_scope)?;
1644
1645 if let Some(ref mut list) = cmd_buf_data.commands {
1646 list.push(crate::device::trace::Command::RunRenderPass {
1647 base: BasePass {
1648 label: base.label.clone(),
1649 commands: base.commands.clone(),
1650 dynamic_offsets: base.dynamic_offsets.clone(),
1651 string_data: base.string_data.clone(),
1652 push_constant_data: base.push_constant_data.clone(),
1653 },
1654 target_colors: color_attachments.to_vec(),
1655 target_depth_stencil: depth_stencil_attachment.cloned(),
1656 timestamp_writes: timestamp_writes.cloned(),
1657 occlusion_query_set_id: occlusion_query_set,
1658 });
1659 }
1660 }
1661
1662 let BasePass {
1663 label,
1664 commands,
1665 dynamic_offsets,
1666 string_data,
1667 push_constant_data,
1668 } = base;
1669
1670 let (mut render_pass, encoder_error) = self.command_encoder_begin_render_pass(
1671 encoder_id,
1672 &RenderPassDescriptor {
1673 label: label.as_deref().map(Cow::Borrowed),
1674 color_attachments: Cow::Borrowed(color_attachments),
1675 depth_stencil_attachment,
1676 timestamp_writes,
1677 occlusion_query_set,
1678 },
1679 );
1680 if let Some(err) = encoder_error {
1681 return Err(RenderPassError {
1682 scope: pass_scope,
1683 inner: err.into(),
1684 });
1685 };
1686
1687 render_pass.base = Some(BasePass {
1688 label,
1689 commands: super::RenderCommand::resolve_render_command_ids(&self.hub, &commands)?,
1690 dynamic_offsets,
1691 string_data,
1692 push_constant_data,
1693 });
1694
1695 self.render_pass_end(&mut render_pass)
1696 }
1697
1698 pub fn render_pass_end(&self, pass: &mut RenderPass) -> Result<(), RenderPassError> {
1699 let pass_scope = PassErrorScope::Pass;
1700
1701 let cmd_buf = pass
1702 .parent
1703 .as_ref()
1704 .ok_or(RenderPassErrorInner::InvalidParentEncoder)
1705 .map_pass_err(pass_scope)?;
1706
1707 let base = pass
1708 .base
1709 .take()
1710 .ok_or(RenderPassErrorInner::PassEnded)
1711 .map_pass_err(pass_scope)?;
1712
1713 profiling::scope!(
1714 "CommandEncoder::run_render_pass {}",
1715 base.label.as_deref().unwrap_or("")
1716 );
1717
1718 let mut cmd_buf_data = cmd_buf.data.lock();
1719 let mut cmd_buf_data_guard = cmd_buf_data.unlock_encoder().map_pass_err(pass_scope)?;
1720 let cmd_buf_data = &mut *cmd_buf_data_guard;
1721
1722 let device = &cmd_buf.device;
1723 let snatch_guard = &device.snatchable_lock.read();
1724
1725 let mut indirect_draw_validation_batcher = crate::indirect_validation::DrawBatcher::new();
1726
1727 let (scope, pending_discard_init_fixups) = {
1728 device.check_is_valid().map_pass_err(pass_scope)?;
1729
1730 let encoder = &mut cmd_buf_data.encoder;
1731 let tracker = &mut cmd_buf_data.trackers;
1732 let buffer_memory_init_actions = &mut cmd_buf_data.buffer_memory_init_actions;
1733 let texture_memory_actions = &mut cmd_buf_data.texture_memory_actions;
1734 let pending_query_resets = &mut cmd_buf_data.pending_query_resets;
1735 let indirect_draw_validation_resources =
1736 &mut cmd_buf_data.indirect_draw_validation_resources;
1737
1738 // We automatically keep extending command buffers over time, and because
1739 // we want to insert a command buffer _before_ what we're about to record,
1740 // we need to make sure to close the previous one.
1741 encoder.close_if_open().map_pass_err(pass_scope)?;
1742 encoder
1743 .open_pass(base.label.as_deref())
1744 .map_pass_err(pass_scope)?;
1745
1746 let info = RenderPassInfo::start(
1747 device,
1748 hal_label(base.label.as_deref(), device.instance_flags),
1749 pass.color_attachments.take(),
1750 pass.depth_stencil_attachment.take(),
1751 pass.timestamp_writes.take(),
1752 // Still needed down the line.
1753 // TODO(wumpf): by restructuring the code, we could get rid of some of this Arc clone.
1754 pass.occlusion_query_set.clone(),
1755 encoder,
1756 tracker,
1757 texture_memory_actions,
1758 pending_query_resets,
1759 snatch_guard,
1760 )
1761 .map_pass_err(pass_scope)?;
1762
1763 let indices = &device.tracker_indices;
1764 tracker.buffers.set_size(indices.buffers.size());
1765 tracker.textures.set_size(indices.textures.size());
1766
1767 let mut state = State {
1768 pipeline_flags: PipelineFlags::empty(),
1769 binder: Binder::new(),
1770 blend_constant: OptionalState::Unused,
1771 stencil_reference: 0,
1772 pipeline: None,
1773 index: IndexState::default(),
1774 vertex: VertexState::default(),
1775 debug_scope_depth: 0,
1776
1777 info,
1778
1779 snatch_guard,
1780
1781 device,
1782 raw_encoder: encoder.raw.as_mut(),
1783 tracker,
1784 buffer_memory_init_actions,
1785 texture_memory_actions,
1786
1787 temp_offsets: Vec::new(),
1788 dynamic_offset_count: 0,
1789 string_offset: 0,
1790
1791 active_occlusion_query: None,
1792 active_pipeline_statistics_query: None,
1793 };
1794
1795 for command in base.commands {
1796 match command {
1797 ArcRenderCommand::SetBindGroup {
1798 index,
1799 num_dynamic_offsets,
1800 bind_group,
1801 } => {
1802 let scope = PassErrorScope::SetBindGroup;
1803 set_bind_group(
1804 &mut state,
1805 cmd_buf,
1806 &base.dynamic_offsets,
1807 index,
1808 num_dynamic_offsets,
1809 bind_group,
1810 )
1811 .map_pass_err(scope)?;
1812 }
1813 ArcRenderCommand::SetPipeline(pipeline) => {
1814 let scope = PassErrorScope::SetPipelineRender;
1815 set_pipeline(&mut state, cmd_buf, pipeline).map_pass_err(scope)?;
1816 }
1817 ArcRenderCommand::SetIndexBuffer {
1818 buffer,
1819 index_format,
1820 offset,
1821 size,
1822 } => {
1823 let scope = PassErrorScope::SetIndexBuffer;
1824 set_index_buffer(&mut state, cmd_buf, buffer, index_format, offset, size)
1825 .map_pass_err(scope)?;
1826 }
1827 ArcRenderCommand::SetVertexBuffer {
1828 slot,
1829 buffer,
1830 offset,
1831 size,
1832 } => {
1833 let scope = PassErrorScope::SetVertexBuffer;
1834 set_vertex_buffer(&mut state, cmd_buf, slot, buffer, offset, size)
1835 .map_pass_err(scope)?;
1836 }
1837 ArcRenderCommand::SetBlendConstant(ref color) => {
1838 set_blend_constant(&mut state, color);
1839 }
1840 ArcRenderCommand::SetStencilReference(value) => {
1841 set_stencil_reference(&mut state, value);
1842 }
1843 ArcRenderCommand::SetViewport {
1844 rect,
1845 depth_min,
1846 depth_max,
1847 } => {
1848 let scope = PassErrorScope::SetViewport;
1849 set_viewport(&mut state, rect, depth_min, depth_max).map_pass_err(scope)?;
1850 }
1851 ArcRenderCommand::SetPushConstant {
1852 stages,
1853 offset,
1854 size_bytes,
1855 values_offset,
1856 } => {
1857 let scope = PassErrorScope::SetPushConstant;
1858 set_push_constant(
1859 &mut state,
1860 &base.push_constant_data,
1861 stages,
1862 offset,
1863 size_bytes,
1864 values_offset,
1865 )
1866 .map_pass_err(scope)?;
1867 }
1868 ArcRenderCommand::SetScissor(rect) => {
1869 let scope = PassErrorScope::SetScissorRect;
1870 set_scissor(&mut state, rect).map_pass_err(scope)?;
1871 }
1872 ArcRenderCommand::Draw {
1873 vertex_count,
1874 instance_count,
1875 first_vertex,
1876 first_instance,
1877 } => {
1878 let scope = PassErrorScope::Draw {
1879 kind: DrawKind::Draw,
1880 indexed: false,
1881 };
1882 draw(
1883 &mut state,
1884 vertex_count,
1885 instance_count,
1886 first_vertex,
1887 first_instance,
1888 )
1889 .map_pass_err(scope)?;
1890 }
1891 ArcRenderCommand::DrawIndexed {
1892 index_count,
1893 instance_count,
1894 first_index,
1895 base_vertex,
1896 first_instance,
1897 } => {
1898 let scope = PassErrorScope::Draw {
1899 kind: DrawKind::Draw,
1900 indexed: true,
1901 };
1902 draw_indexed(
1903 &mut state,
1904 index_count,
1905 instance_count,
1906 first_index,
1907 base_vertex,
1908 first_instance,
1909 )
1910 .map_pass_err(scope)?;
1911 }
1912 ArcRenderCommand::DrawIndirect {
1913 buffer,
1914 offset,
1915 count,
1916 indexed,
1917
1918 vertex_or_index_limit: _,
1919 instance_limit: _,
1920 } => {
1921 let scope = PassErrorScope::Draw {
1922 kind: if count != 1 {
1923 DrawKind::MultiDrawIndirect
1924 } else {
1925 DrawKind::DrawIndirect
1926 },
1927 indexed,
1928 };
1929 multi_draw_indirect(
1930 &mut state,
1931 indirect_draw_validation_resources,
1932 &mut indirect_draw_validation_batcher,
1933 cmd_buf,
1934 buffer,
1935 offset,
1936 count,
1937 indexed,
1938 )
1939 .map_pass_err(scope)?;
1940 }
1941 ArcRenderCommand::MultiDrawIndirectCount {
1942 buffer,
1943 offset,
1944 count_buffer,
1945 count_buffer_offset,
1946 max_count,
1947 indexed,
1948 } => {
1949 let scope = PassErrorScope::Draw {
1950 kind: DrawKind::MultiDrawIndirectCount,
1951 indexed,
1952 };
1953 multi_draw_indirect_count(
1954 &mut state,
1955 cmd_buf,
1956 buffer,
1957 offset,
1958 count_buffer,
1959 count_buffer_offset,
1960 max_count,
1961 indexed,
1962 )
1963 .map_pass_err(scope)?;
1964 }
1965 ArcRenderCommand::PushDebugGroup { color: _, len } => {
1966 push_debug_group(&mut state, &base.string_data, len);
1967 }
1968 ArcRenderCommand::PopDebugGroup => {
1969 let scope = PassErrorScope::PopDebugGroup;
1970 pop_debug_group(&mut state).map_pass_err(scope)?;
1971 }
1972 ArcRenderCommand::InsertDebugMarker { color: _, len } => {
1973 insert_debug_marker(&mut state, &base.string_data, len);
1974 }
1975 ArcRenderCommand::WriteTimestamp {
1976 query_set,
1977 query_index,
1978 } => {
1979 let scope = PassErrorScope::WriteTimestamp;
1980 write_timestamp(
1981 &mut state,
1982 cmd_buf,
1983 &mut cmd_buf_data.pending_query_resets,
1984 query_set,
1985 query_index,
1986 )
1987 .map_pass_err(scope)?;
1988 }
1989 ArcRenderCommand::BeginOcclusionQuery { query_index } => {
1990 api_log!("RenderPass::begin_occlusion_query {query_index}");
1991 let scope = PassErrorScope::BeginOcclusionQuery;
1992
1993 let query_set = pass
1994 .occlusion_query_set
1995 .clone()
1996 .ok_or(RenderPassErrorInner::MissingOcclusionQuerySet)
1997 .map_pass_err(scope)?;
1998
1999 validate_and_begin_occlusion_query(
2000 query_set,
2001 state.raw_encoder,
2002 &mut state.tracker.query_sets,
2003 query_index,
2004 Some(&mut cmd_buf_data.pending_query_resets),
2005 &mut state.active_occlusion_query,
2006 )
2007 .map_pass_err(scope)?;
2008 }
2009 ArcRenderCommand::EndOcclusionQuery => {
2010 api_log!("RenderPass::end_occlusion_query");
2011 let scope = PassErrorScope::EndOcclusionQuery;
2012
2013 end_occlusion_query(state.raw_encoder, &mut state.active_occlusion_query)
2014 .map_pass_err(scope)?;
2015 }
2016 ArcRenderCommand::BeginPipelineStatisticsQuery {
2017 query_set,
2018 query_index,
2019 } => {
2020 api_log!(
2021 "RenderPass::begin_pipeline_statistics_query {query_index} {}",
2022 query_set.error_ident()
2023 );
2024 let scope = PassErrorScope::BeginPipelineStatisticsQuery;
2025
2026 validate_and_begin_pipeline_statistics_query(
2027 query_set,
2028 state.raw_encoder,
2029 &mut state.tracker.query_sets,
2030 cmd_buf.as_ref(),
2031 query_index,
2032 Some(&mut cmd_buf_data.pending_query_resets),
2033 &mut state.active_pipeline_statistics_query,
2034 )
2035 .map_pass_err(scope)?;
2036 }
2037 ArcRenderCommand::EndPipelineStatisticsQuery => {
2038 api_log!("RenderPass::end_pipeline_statistics_query");
2039 let scope = PassErrorScope::EndPipelineStatisticsQuery;
2040
2041 end_pipeline_statistics_query(
2042 state.raw_encoder,
2043 &mut state.active_pipeline_statistics_query,
2044 )
2045 .map_pass_err(scope)?;
2046 }
2047 ArcRenderCommand::ExecuteBundle(bundle) => {
2048 let scope = PassErrorScope::ExecuteBundle;
2049 execute_bundle(
2050 &mut state,
2051 indirect_draw_validation_resources,
2052 &mut indirect_draw_validation_batcher,
2053 cmd_buf,
2054 bundle,
2055 )
2056 .map_pass_err(scope)?;
2057 }
2058 }
2059 }
2060
2061 let (trackers, pending_discard_init_fixups) = state
2062 .info
2063 .finish(device, state.raw_encoder, state.snatch_guard)
2064 .map_pass_err(pass_scope)?;
2065
2066 encoder.close().map_pass_err(pass_scope)?;
2067 (trackers, pending_discard_init_fixups)
2068 };
2069
2070 let encoder = &mut cmd_buf_data.encoder;
2071 let tracker = &mut cmd_buf_data.trackers;
2072
2073 {
2074 let transit = encoder
2075 .open_pass(Some("(wgpu internal) Pre Pass"))
2076 .map_pass_err(pass_scope)?;
2077
2078 fixup_discarded_surfaces(
2079 pending_discard_init_fixups.into_iter(),
2080 transit,
2081 &mut tracker.textures,
2082 &cmd_buf.device,
2083 snatch_guard,
2084 );
2085
2086 cmd_buf_data.pending_query_resets.reset_queries(transit);
2087
2088 CommandBuffer::insert_barriers_from_scope(transit, tracker, &scope, snatch_guard);
2089
2090 if let Some(ref indirect_validation) = device.indirect_validation {
2091 indirect_validation
2092 .draw
2093 .inject_validation_pass(
2094 device,
2095 snatch_guard,
2096 &mut cmd_buf_data.indirect_draw_validation_resources,
2097 &mut cmd_buf_data.temp_resources,
2098 transit,
2099 indirect_draw_validation_batcher,
2100 )
2101 .map_pass_err(pass_scope)?;
2102 }
2103 }
2104
2105 encoder.close_and_swap().map_pass_err(pass_scope)?;
2106 cmd_buf_data_guard.mark_successful();
2107
2108 Ok(())
2109 }
2110 }
2111
2112 fn set_bind_group(
2113 state: &mut State,
2114 cmd_buf: &Arc<CommandBuffer>,
2115 dynamic_offsets: &[DynamicOffset],
2116 index: u32,
2117 num_dynamic_offsets: usize,
2118 bind_group: Option<Arc<BindGroup>>,
2119 ) -> Result<(), RenderPassErrorInner> {
2120 if bind_group.is_none() {
2121 api_log!("RenderPass::set_bind_group {index} None");
2122 } else {
2123 api_log!(
2124 "RenderPass::set_bind_group {index} {}",
2125 bind_group.as_ref().unwrap().error_ident()
2126 );
2127 }
2128
2129 let max_bind_groups = state.device.limits.max_bind_groups;
2130 if index >= max_bind_groups {
2131 return Err(RenderCommandError::BindGroupIndexOutOfRange {
2132 index,
2133 max: max_bind_groups,
2134 }
2135 .into());
2136 }
2137
2138 state.temp_offsets.clear();
2139 state.temp_offsets.extend_from_slice(
2140 &dynamic_offsets
2141 [state.dynamic_offset_count..state.dynamic_offset_count + num_dynamic_offsets],
2142 );
2143 state.dynamic_offset_count += num_dynamic_offsets;
2144
2145 if bind_group.is_none() {
2146 // TODO: Handle bind_group None.
2147 return Ok(());
2148 }
2149
2150 let bind_group = bind_group.unwrap();
2151 let bind_group = state.tracker.bind_groups.insert_single(bind_group);
2152
2153 bind_group.same_device_as(cmd_buf.as_ref())?;
2154
2155 bind_group.validate_dynamic_bindings(index, &state.temp_offsets)?;
2156
2157 // merge the resource tracker in
2158 unsafe {
2159 state.info.usage_scope.merge_bind_group(&bind_group.used)?;
2160 }
2161 //Note: stateless trackers are not merged: the lifetime reference
2162 // is held to the bind group itself.
2163
2164 state
2165 .buffer_memory_init_actions
2166 .extend(bind_group.used_buffer_ranges.iter().filter_map(|action| {
2167 action
2168 .buffer
2169 .initialization_status
2170 .read()
2171 .check_action(action)
2172 }));
2173 for action in bind_group.used_texture_ranges.iter() {
2174 state
2175 .info
2176 .pending_discard_init_fixups
2177 .extend(state.texture_memory_actions.register_init_action(action));
2178 }
2179
2180 let pipeline_layout = state.binder.pipeline_layout.clone();
2181 let entries = state
2182 .binder
2183 .assign_group(index as usize, bind_group, &state.temp_offsets);
2184 if !entries.is_empty() && pipeline_layout.is_some() {
2185 let pipeline_layout = pipeline_layout.as_ref().unwrap().raw();
2186 for (i, e) in entries.iter().enumerate() {
2187 if let Some(group) = e.group.as_ref() {
2188 let raw_bg = group.try_raw(state.snatch_guard)?;
2189 unsafe {
2190 state.raw_encoder.set_bind_group(
2191 pipeline_layout,
2192 index + i as u32,
2193 Some(raw_bg),
2194 &e.dynamic_offsets,
2195 );
2196 }
2197 }
2198 }
2199 }
2200 Ok(())
2201 }
2202
2203 fn set_pipeline(
2204 state: &mut State,
2205 cmd_buf: &Arc<CommandBuffer>,
2206 pipeline: Arc<RenderPipeline>,
2207 ) -> Result<(), RenderPassErrorInner> {
2208 api_log!("RenderPass::set_pipeline {}", pipeline.error_ident());
2209
2210 state.pipeline = Some(pipeline.clone());
2211
2212 let pipeline = state.tracker.render_pipelines.insert_single(pipeline);
2213
2214 pipeline.same_device_as(cmd_buf.as_ref())?;
2215
2216 state
2217 .info
2218 .context
2219 .check_compatible(&pipeline.pass_context, pipeline.as_ref())
2220 .map_err(RenderCommandError::IncompatiblePipelineTargets)?;
2221
2222 state.pipeline_flags = pipeline.flags;
2223
2224 if pipeline.flags.contains(PipelineFlags::WRITES_DEPTH) && state.info.is_depth_read_only {
2225 return Err(RenderCommandError::IncompatibleDepthAccess(pipeline.error_ident()).into());
2226 }
2227 if pipeline.flags.contains(PipelineFlags::WRITES_STENCIL) && state.info.is_stencil_read_only {
2228 return Err(RenderCommandError::IncompatibleStencilAccess(pipeline.error_ident()).into());
2229 }
2230
2231 state
2232 .blend_constant
2233 .require(pipeline.flags.contains(PipelineFlags::BLEND_CONSTANT));
2234
2235 unsafe {
2236 state.raw_encoder.set_render_pipeline(pipeline.raw());
2237 }
2238
2239 if pipeline.flags.contains(PipelineFlags::STENCIL_REFERENCE) {
2240 unsafe {
2241 state
2242 .raw_encoder
2243 .set_stencil_reference(state.stencil_reference);
2244 }
2245 }
2246
2247 // Rebind resource
2248 if state.binder.pipeline_layout.is_none()
2249 || !state
2250 .binder
2251 .pipeline_layout
2252 .as_ref()
2253 .unwrap()
2254 .is_equal(&pipeline.layout)
2255 {
2256 let (start_index, entries) = state
2257 .binder
2258 .change_pipeline_layout(&pipeline.layout, &pipeline.late_sized_buffer_groups);
2259 if !entries.is_empty() {
2260 for (i, e) in entries.iter().enumerate() {
2261 if let Some(group) = e.group.as_ref() {
2262 let raw_bg = group.try_raw(state.snatch_guard)?;
2263 unsafe {
2264 state.raw_encoder.set_bind_group(
2265 pipeline.layout.raw(),
2266 start_index as u32 + i as u32,
2267 Some(raw_bg),
2268 &e.dynamic_offsets,
2269 );
2270 }
2271 }
2272 }
2273 }
2274
2275 // Clear push constant ranges
2276 let non_overlapping =
2277 super::bind::compute_nonoverlapping_ranges(&pipeline.layout.push_constant_ranges);
2278 for range in non_overlapping {
2279 let offset = range.range.start;
2280 let size_bytes = range.range.end - offset;
2281 super::push_constant_clear(offset, size_bytes, |clear_offset, clear_data| unsafe {
2282 state.raw_encoder.set_push_constants(
2283 pipeline.layout.raw(),
2284 range.stages,
2285 clear_offset,
2286 clear_data,
2287 );
2288 });
2289 }
2290 }
2291
2292 // Update vertex buffer limits.
2293 state.vertex.update_limits(&pipeline.vertex_steps);
2294 Ok(())
2295 }
2296
2297 fn set_index_buffer(
2298 state: &mut State,
2299 cmd_buf: &Arc<CommandBuffer>,
2300 buffer: Arc<crate::resource::Buffer>,
2301 index_format: IndexFormat,
2302 offset: u64,
2303 size: Option<BufferSize>,
2304 ) -> Result<(), RenderPassErrorInner> {
2305 api_log!("RenderPass::set_index_buffer {}", buffer.error_ident());
2306
2307 state
2308 .info
2309 .usage_scope
2310 .buffers
2311 .merge_single(&buffer, wgt::BufferUses::INDEX)?;
2312
2313 buffer.same_device_as(cmd_buf.as_ref())?;
2314
2315 buffer.check_usage(BufferUsages::INDEX)?;
2316 let buf_raw = buffer.try_raw(state.snatch_guard)?;
2317
2318 let end = match size {
2319 Some(s) => offset + s.get(),
2320 None => buffer.size,
2321 };
2322 state.index.update_buffer(offset..end, index_format);
2323
2324 state
2325 .buffer_memory_init_actions
2326 .extend(buffer.initialization_status.read().create_action(
2327 &buffer,
2328 offset..end,
2329 MemoryInitKind::NeedsInitializedMemory,
2330 ));
2331
2332 let bb = hal::BufferBinding {
2333 buffer: buf_raw,
2334 offset,
2335 size,
2336 };
2337 unsafe {
2338 hal::DynCommandEncoder::set_index_buffer(state.raw_encoder, bb, index_format);
2339 }
2340 Ok(())
2341 }
2342
2343 fn set_vertex_buffer(
2344 state: &mut State,
2345 cmd_buf: &Arc<CommandBuffer>,
2346 slot: u32,
2347 buffer: Arc<crate::resource::Buffer>,
2348 offset: u64,
2349 size: Option<BufferSize>,
2350 ) -> Result<(), RenderPassErrorInner> {
2351 api_log!(
2352 "RenderPass::set_vertex_buffer {slot} {}",
2353 buffer.error_ident()
2354 );
2355
2356 state
2357 .info
2358 .usage_scope
2359 .buffers
2360 .merge_single(&buffer, wgt::BufferUses::VERTEX)?;
2361
2362 buffer.same_device_as(cmd_buf.as_ref())?;
2363
2364 let max_vertex_buffers = state.device.limits.max_vertex_buffers;
2365 if slot >= max_vertex_buffers {
2366 return Err(RenderCommandError::VertexBufferIndexOutOfRange {
2367 index: slot,
2368 max: max_vertex_buffers,
2369 }
2370 .into());
2371 }
2372
2373 buffer.check_usage(BufferUsages::VERTEX)?;
2374 let buf_raw = buffer.try_raw(state.snatch_guard)?;
2375
2376 //TODO: where are we checking that the offset is in bound?
2377 let buffer_size = match size {
2378 Some(s) => s.get(),
2379 None => buffer.size - offset,
2380 };
2381 state.vertex.buffer_sizes[slot as usize] = Some(buffer_size);
2382
2383 state
2384 .buffer_memory_init_actions
2385 .extend(buffer.initialization_status.read().create_action(
2386 &buffer,
2387 offset..(offset + buffer_size),
2388 MemoryInitKind::NeedsInitializedMemory,
2389 ));
2390
2391 let bb = hal::BufferBinding {
2392 buffer: buf_raw,
2393 offset,
2394 size,
2395 };
2396 unsafe {
2397 hal::DynCommandEncoder::set_vertex_buffer(state.raw_encoder, slot, bb);
2398 }
2399 if let Some(pipeline) = state.pipeline.as_ref() {
2400 state.vertex.update_limits(&pipeline.vertex_steps);
2401 }
2402 Ok(())
2403 }
2404
2405 fn set_blend_constant(state: &mut State, color: &Color) {
2406 api_log!("RenderPass::set_blend_constant");
2407
2408 state.blend_constant = OptionalState::Set;
2409 let array = [
2410 color.r as f32,
2411 color.g as f32,
2412 color.b as f32,
2413 color.a as f32,
2414 ];
2415 unsafe {
2416 state.raw_encoder.set_blend_constants(&array);
2417 }
2418 }
2419
2420 fn set_stencil_reference(state: &mut State, value: u32) {
2421 api_log!("RenderPass::set_stencil_reference {value}");
2422
2423 state.stencil_reference = value;
2424 if state
2425 .pipeline_flags
2426 .contains(PipelineFlags::STENCIL_REFERENCE)
2427 {
2428 unsafe {
2429 state.raw_encoder.set_stencil_reference(value);
2430 }
2431 }
2432 }
2433
2434 fn set_viewport(
2435 state: &mut State,
2436 rect: Rect<f32>,
2437 depth_min: f32,
2438 depth_max: f32,
2439 ) -> Result<(), RenderPassErrorInner> {
2440 api_log!("RenderPass::set_viewport {rect:?}");
2441
2442 if rect.w < 0.0
2443 || rect.h < 0.0
2444 || rect.w > state.device.limits.max_texture_dimension_2d as f32
2445 || rect.h > state.device.limits.max_texture_dimension_2d as f32
2446 {
2447 return Err(RenderCommandError::InvalidViewportRectSize {
2448 w: rect.w,
2449 h: rect.h,
2450 max: state.device.limits.max_texture_dimension_2d,
2451 }
2452 .into());
2453 }
2454
2455 let max_viewport_range = state.device.limits.max_texture_dimension_2d as f32 * 2.0;
2456
2457 if rect.x < -max_viewport_range
2458 || rect.y < -max_viewport_range
2459 || rect.x + rect.w > max_viewport_range - 1.0
2460 || rect.y + rect.h > max_viewport_range - 1.0
2461 {
2462 return Err(RenderCommandError::InvalidViewportRectPosition {
2463 rect,
2464 min: -max_viewport_range,
2465 max: max_viewport_range - 1.0,
2466 }
2467 .into());
2468 }
2469 if !(0.0..=1.0).contains(&depth_min) || !(0.0..=1.0).contains(&depth_max) {
2470 return Err(RenderCommandError::InvalidViewportDepth(depth_min, depth_max).into());
2471 }
2472 let r = hal::Rect {
2473 x: rect.x,
2474 y: rect.y,
2475 w: rect.w,
2476 h: rect.h,
2477 };
2478 unsafe {
2479 state.raw_encoder.set_viewport(&r, depth_min..depth_max);
2480 }
2481 Ok(())
2482 }
2483
2484 fn set_push_constant(
2485 state: &mut State,
2486 push_constant_data: &[u32],
2487 stages: ShaderStages,
2488 offset: u32,
2489 size_bytes: u32,
2490 values_offset: Option<u32>,
2491 ) -> Result<(), RenderPassErrorInner> {
2492 api_log!("RenderPass::set_push_constants");
2493
2494 let values_offset = values_offset.ok_or(RenderPassErrorInner::InvalidValuesOffset)?;
2495
2496 let end_offset_bytes = offset + size_bytes;
2497 let values_end_offset = (values_offset + size_bytes / wgt::PUSH_CONSTANT_ALIGNMENT) as usize;
2498 let data_slice = &push_constant_data[(values_offset as usize)..values_end_offset];
2499
2500 let pipeline_layout = state
2501 .binder
2502 .pipeline_layout
2503 .as_ref()
2504 .ok_or(DrawError::MissingPipeline)?;
2505
2506 pipeline_layout
2507 .validate_push_constant_ranges(stages, offset, end_offset_bytes)
2508 .map_err(RenderCommandError::from)?;
2509
2510 unsafe {
2511 state
2512 .raw_encoder
2513 .set_push_constants(pipeline_layout.raw(), stages, offset, data_slice)
2514 }
2515 Ok(())
2516 }
2517
2518 fn set_scissor(state: &mut State, rect: Rect<u32>) -> Result<(), RenderPassErrorInner> {
2519 api_log!("RenderPass::set_scissor_rect {rect:?}");
2520
2521 if rect.x.saturating_add(rect.w) > state.info.extent.width
2522 || rect.y.saturating_add(rect.h) > state.info.extent.height
2523 {
2524 return Err(RenderCommandError::InvalidScissorRect(rect, state.info.extent).into());
2525 }
2526 let r = hal::Rect {
2527 x: rect.x,
2528 y: rect.y,
2529 w: rect.w,
2530 h: rect.h,
2531 };
2532 unsafe {
2533 state.raw_encoder.set_scissor_rect(&r);
2534 }
2535 Ok(())
2536 }
2537
2538 fn draw(
2539 state: &mut State,
2540 vertex_count: u32,
2541 instance_count: u32,
2542 first_vertex: u32,
2543 first_instance: u32,
2544 ) -> Result<(), DrawError> {
2545 api_log!("RenderPass::draw {vertex_count} {instance_count} {first_vertex} {first_instance}");
2546
2547 state.is_ready(false)?;
2548
2549 state
2550 .vertex
2551 .limits
2552 .validate_vertex_limit(first_vertex, vertex_count)?;
2553 state
2554 .vertex
2555 .limits
2556 .validate_instance_limit(first_instance, instance_count)?;
2557
2558 unsafe {
2559 if instance_count > 0 && vertex_count > 0 {
2560 state
2561 .raw_encoder
2562 .draw(first_vertex, vertex_count, first_instance, instance_count);
2563 }
2564 }
2565 Ok(())
2566 }
2567
2568 fn draw_indexed(
2569 state: &mut State,
2570 index_count: u32,
2571 instance_count: u32,
2572 first_index: u32,
2573 base_vertex: i32,
2574 first_instance: u32,
2575 ) -> Result<(), DrawError> {
2576 api_log!("RenderPass::draw_indexed {index_count} {instance_count} {first_index} {base_vertex} {first_instance}");
2577
2578 state.is_ready(true)?;
2579
2580 let last_index = first_index as u64 + index_count as u64;
2581 let index_limit = state.index.limit;
2582 if last_index > index_limit {
2583 return Err(DrawError::IndexBeyondLimit {
2584 last_index,
2585 index_limit,
2586 });
2587 }
2588 state
2589 .vertex
2590 .limits
2591 .validate_instance_limit(first_instance, instance_count)?;
2592
2593 unsafe {
2594 if instance_count > 0 && index_count > 0 {
2595 state.raw_encoder.draw_indexed(
2596 first_index,
2597 index_count,
2598 base_vertex,
2599 first_instance,
2600 instance_count,
2601 );
2602 }
2603 }
2604 Ok(())
2605 }
2606
2607 fn multi_draw_indirect(
2608 state: &mut State,
2609 indirect_draw_validation_resources: &mut crate::indirect_validation::DrawResources,
2610 indirect_draw_validation_batcher: &mut crate::indirect_validation::DrawBatcher,
2611 cmd_buf: &Arc<CommandBuffer>,
2612 indirect_buffer: Arc<crate::resource::Buffer>,
2613 offset: u64,
2614 count: u32,
2615 indexed: bool,
2616 ) -> Result<(), RenderPassErrorInner> {
2617 api_log!(
2618 "RenderPass::draw_indirect (indexed:{indexed}) {} {offset} {count:?}",
2619 indirect_buffer.error_ident()
2620 );
2621
2622 state.is_ready(indexed)?;
2623
2624 if count != 1 {
2625 state
2626 .device
2627 .require_features(wgt::Features::MULTI_DRAW_INDIRECT)?;
2628 }
2629
2630 state
2631 .device
2632 .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
2633
2634 indirect_buffer.same_device_as(cmd_buf.as_ref())?;
2635 indirect_buffer.check_usage(BufferUsages::INDIRECT)?;
2636 indirect_buffer.check_destroyed(state.snatch_guard)?;
2637
2638 if offset % 4 != 0 {
2639 return Err(RenderPassErrorInner::UnalignedIndirectBufferOffset(offset));
2640 }
2641
2642 let stride = get_stride_of_indirect_args(indexed);
2643
2644 let end_offset = offset + stride * count as u64;
2645 if end_offset > indirect_buffer.size {
2646 return Err(RenderPassErrorInner::IndirectBufferOverrun {
2647 count,
2648 offset,
2649 end_offset,
2650 buffer_size: indirect_buffer.size,
2651 });
2652 }
2653
2654 state.buffer_memory_init_actions.extend(
2655 indirect_buffer.initialization_status.read().create_action(
2656 &indirect_buffer,
2657 offset..end_offset,
2658 MemoryInitKind::NeedsInitializedMemory,
2659 ),
2660 );
2661
2662 fn draw(
2663 raw_encoder: &mut dyn hal::DynCommandEncoder,
2664 indexed: bool,
2665 indirect_buffer: &dyn hal::DynBuffer,
2666 offset: u64,
2667 count: u32,
2668 ) {
2669 match indexed {
2670 false => unsafe {
2671 raw_encoder.draw_indirect(indirect_buffer, offset, count);
2672 },
2673 true => unsafe {
2674 raw_encoder.draw_indexed_indirect(indirect_buffer, offset, count);
2675 },
2676 }
2677 }
2678
2679 if state.device.indirect_validation.is_some() {
2680 state
2681 .info
2682 .usage_scope
2683 .buffers
2684 .merge_single(&indirect_buffer, wgt::BufferUses::STORAGE_READ_ONLY)?;
2685
2686 struct DrawData {
2687 buffer_index: usize,
2688 offset: u64,
2689 count: u32,
2690 }
2691
2692 struct DrawContext<'a> {
2693 raw_encoder: &'a mut dyn hal::DynCommandEncoder,
2694 device: &'a Device,
2695
2696 indirect_draw_validation_resources: &'a mut crate::indirect_validation::DrawResources,
2697 indirect_draw_validation_batcher: &'a mut crate::indirect_validation::DrawBatcher,
2698
2699 indirect_buffer: Arc<crate::resource::Buffer>,
2700 indexed: bool,
2701 vertex_or_index_limit: u64,
2702 instance_limit: u64,
2703 }
2704
2705 impl<'a> DrawContext<'a> {
2706 fn add(&mut self, offset: u64) -> Result<DrawData, DeviceError> {
2707 let (dst_resource_index, dst_offset) = self.indirect_draw_validation_batcher.add(
2708 self.indirect_draw_validation_resources,
2709 self.device,
2710 &self.indirect_buffer,
2711 offset,
2712 self.indexed,
2713 self.vertex_or_index_limit,
2714 self.instance_limit,
2715 )?;
2716 Ok(DrawData {
2717 buffer_index: dst_resource_index,
2718 offset: dst_offset,
2719 count: 1,
2720 })
2721 }
2722 fn draw(&mut self, draw_data: DrawData) {
2723 let dst_buffer = self
2724 .indirect_draw_validation_resources
2725 .get_dst_buffer(draw_data.buffer_index);
2726 draw(
2727 self.raw_encoder,
2728 self.indexed,
2729 dst_buffer,
2730 draw_data.offset,
2731 draw_data.count,
2732 );
2733 }
2734 }
2735
2736 let mut draw_ctx = DrawContext {
2737 raw_encoder: state.raw_encoder,
2738 device: state.device,
2739 indirect_draw_validation_resources,
2740 indirect_draw_validation_batcher,
2741 indirect_buffer,
2742 indexed,
2743 vertex_or_index_limit: if indexed {
2744 state.index.limit
2745 } else {
2746 state.vertex.limits.vertex_limit
2747 },
2748 instance_limit: state.vertex.limits.instance_limit,
2749 };
2750
2751 let mut current_draw_data = draw_ctx.add(offset)?;
2752
2753 for i in 1..count {
2754 let draw_data = draw_ctx.add(offset + stride * i as u64)?;
2755
2756 if draw_data.buffer_index == current_draw_data.buffer_index {
2757 debug_assert_eq!(
2758 draw_data.offset,
2759 current_draw_data.offset + stride * current_draw_data.count as u64
2760 );
2761 current_draw_data.count += 1;
2762 } else {
2763 draw_ctx.draw(current_draw_data);
2764 current_draw_data = draw_data;
2765 }
2766 }
2767
2768 draw_ctx.draw(current_draw_data);
2769 } else {
2770 state
2771 .info
2772 .usage_scope
2773 .buffers
2774 .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?;
2775
2776 draw(
2777 state.raw_encoder,
2778 indexed,
2779 indirect_buffer.try_raw(state.snatch_guard)?,
2780 offset,
2781 count,
2782 );
2783 };
2784
2785 Ok(())
2786 }
2787
2788 fn multi_draw_indirect_count(
2789 state: &mut State,
2790 cmd_buf: &Arc<CommandBuffer>,
2791 indirect_buffer: Arc<crate::resource::Buffer>,
2792 offset: u64,
2793 count_buffer: Arc<crate::resource::Buffer>,
2794 count_buffer_offset: u64,
2795 max_count: u32,
2796 indexed: bool,
2797 ) -> Result<(), RenderPassErrorInner> {
2798 api_log!(
2799 "RenderPass::multi_draw_indirect_count (indexed:{indexed}) {} {offset} {} {count_buffer_offset:?} {max_count:?}",
2800 indirect_buffer.error_ident(),
2801 count_buffer.error_ident()
2802 );
2803
2804 state.is_ready(indexed)?;
2805
2806 let stride = get_stride_of_indirect_args(indexed);
2807
2808 state
2809 .device
2810 .require_features(wgt::Features::MULTI_DRAW_INDIRECT_COUNT)?;
2811 state
2812 .device
2813 .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
2814
2815 indirect_buffer.same_device_as(cmd_buf.as_ref())?;
2816 count_buffer.same_device_as(cmd_buf.as_ref())?;
2817
2818 state
2819 .info
2820 .usage_scope
2821 .buffers
2822 .merge_single(&indirect_buffer, wgt::BufferUses::INDIRECT)?;
2823
2824 indirect_buffer.check_usage(BufferUsages::INDIRECT)?;
2825 let indirect_raw = indirect_buffer.try_raw(state.snatch_guard)?;
2826
2827 state
2828 .info
2829 .usage_scope
2830 .buffers
2831 .merge_single(&count_buffer, wgt::BufferUses::INDIRECT)?;
2832
2833 count_buffer.check_usage(BufferUsages::INDIRECT)?;
2834 let count_raw = count_buffer.try_raw(state.snatch_guard)?;
2835
2836 if offset % 4 != 0 {
2837 return Err(RenderPassErrorInner::UnalignedIndirectBufferOffset(offset));
2838 }
2839
2840 let end_offset = offset + stride * max_count as u64;
2841 if end_offset > indirect_buffer.size {
2842 return Err(RenderPassErrorInner::IndirectBufferOverrun {
2843 count: 1,
2844 offset,
2845 end_offset,
2846 buffer_size: indirect_buffer.size,
2847 });
2848 }
2849 state.buffer_memory_init_actions.extend(
2850 indirect_buffer.initialization_status.read().create_action(
2851 &indirect_buffer,
2852 offset..end_offset,
2853 MemoryInitKind::NeedsInitializedMemory,
2854 ),
2855 );
2856
2857 let begin_count_offset = count_buffer_offset;
2858 let end_count_offset = count_buffer_offset + 4;
2859 if end_count_offset > count_buffer.size {
2860 return Err(RenderPassErrorInner::IndirectCountBufferOverrun {
2861 begin_count_offset,
2862 end_count_offset,
2863 count_buffer_size: count_buffer.size,
2864 });
2865 }
2866 state.buffer_memory_init_actions.extend(
2867 count_buffer.initialization_status.read().create_action(
2868 &count_buffer,
2869 count_buffer_offset..end_count_offset,
2870 MemoryInitKind::NeedsInitializedMemory,
2871 ),
2872 );
2873
2874 match indexed {
2875 false => unsafe {
2876 state.raw_encoder.draw_indirect_count(
2877 indirect_raw,
2878 offset,
2879 count_raw,
2880 count_buffer_offset,
2881 max_count,
2882 );
2883 },
2884 true => unsafe {
2885 state.raw_encoder.draw_indexed_indirect_count(
2886 indirect_raw,
2887 offset,
2888 count_raw,
2889 count_buffer_offset,
2890 max_count,
2891 );
2892 },
2893 }
2894 Ok(())
2895 }
2896
2897 fn push_debug_group(state: &mut State, string_data: &[u8], len: usize) {
2898 state.debug_scope_depth += 1;
2899 if !state
2900 .device
2901 .instance_flags
2902 .contains(wgt::InstanceFlags::DISCARD_HAL_LABELS)
2903 {
2904 let label =
2905 str::from_utf8(&string_data[state.string_offset..state.string_offset + len]).unwrap();
2906
2907 api_log!("RenderPass::push_debug_group {label:?}");
2908 unsafe {
2909 state.raw_encoder.begin_debug_marker(label);
2910 }
2911 }
2912 state.string_offset += len;
2913 }
2914
2915 fn pop_debug_group(state: &mut State) -> Result<(), RenderPassErrorInner> {
2916 api_log!("RenderPass::pop_debug_group");
2917
2918 if state.debug_scope_depth == 0 {
2919 return Err(RenderPassErrorInner::InvalidPopDebugGroup);
2920 }
2921 state.debug_scope_depth -= 1;
2922 if !state
2923 .device
2924 .instance_flags
2925 .contains(wgt::InstanceFlags::DISCARD_HAL_LABELS)
2926 {
2927 unsafe {
2928 state.raw_encoder.end_debug_marker();
2929 }
2930 }
2931 Ok(())
2932 }
2933
2934 fn insert_debug_marker(state: &mut State, string_data: &[u8], len: usize) {
2935 if !state
2936 .device
2937 .instance_flags
2938 .contains(wgt::InstanceFlags::DISCARD_HAL_LABELS)
2939 {
2940 let label =
2941 str::from_utf8(&string_data[state.string_offset..state.string_offset + len]).unwrap();
2942 api_log!("RenderPass::insert_debug_marker {label:?}");
2943 unsafe {
2944 state.raw_encoder.insert_debug_marker(label);
2945 }
2946 }
2947 state.string_offset += len;
2948 }
2949
2950 fn write_timestamp(
2951 state: &mut State,
2952 cmd_buf: &CommandBuffer,
2953 pending_query_resets: &mut QueryResetMap,
2954 query_set: Arc<QuerySet>,
2955 query_index: u32,
2956 ) -> Result<(), RenderPassErrorInner> {
2957 api_log!(
2958 "RenderPass::write_timestamps {query_index} {}",
2959 query_set.error_ident()
2960 );
2961
2962 query_set.same_device_as(cmd_buf)?;
2963
2964 state
2965 .device
2966 .require_features(wgt::Features::TIMESTAMP_QUERY_INSIDE_PASSES)?;
2967
2968 let query_set = state.tracker.query_sets.insert_single(query_set);
2969
2970 query_set.validate_and_write_timestamp(
2971 state.raw_encoder,
2972 query_index,
2973 Some(pending_query_resets),
2974 )?;
2975 Ok(())
2976 }
2977
2978 fn execute_bundle(
2979 state: &mut State,
2980 indirect_draw_validation_resources: &mut crate::indirect_validation::DrawResources,
2981 indirect_draw_validation_batcher: &mut crate::indirect_validation::DrawBatcher,
2982 cmd_buf: &Arc<CommandBuffer>,
2983 bundle: Arc<super::RenderBundle>,
2984 ) -> Result<(), RenderPassErrorInner> {
2985 api_log!("RenderPass::execute_bundle {}", bundle.error_ident());
2986
2987 let bundle = state.tracker.bundles.insert_single(bundle);
2988
2989 bundle.same_device_as(cmd_buf.as_ref())?;
2990
2991 state
2992 .info
2993 .context
2994 .check_compatible(&bundle.context, bundle.as_ref())
2995 .map_err(RenderPassErrorInner::IncompatibleBundleTargets)?;
2996
2997 if (state.info.is_depth_read_only && !bundle.is_depth_read_only)
2998 || (state.info.is_stencil_read_only && !bundle.is_stencil_read_only)
2999 {
3000 return Err(
3001 RenderPassErrorInner::IncompatibleBundleReadOnlyDepthStencil {
3002 pass_depth: state.info.is_depth_read_only,
3003 pass_stencil: state.info.is_stencil_read_only,
3004 bundle_depth: bundle.is_depth_read_only,
3005 bundle_stencil: bundle.is_stencil_read_only,
3006 },
3007 );
3008 }
3009
3010 state
3011 .buffer_memory_init_actions
3012 .extend(
3013 bundle
3014 .buffer_memory_init_actions
3015 .iter()
3016 .filter_map(|action| {
3017 action
3018 .buffer
3019 .initialization_status
3020 .read()
3021 .check_action(action)
3022 }),
3023 );
3024 for action in bundle.texture_memory_init_actions.iter() {
3025 state
3026 .info
3027 .pending_discard_init_fixups
3028 .extend(state.texture_memory_actions.register_init_action(action));
3029 }
3030
3031 unsafe {
3032 bundle.execute(
3033 state.raw_encoder,
3034 indirect_draw_validation_resources,
3035 indirect_draw_validation_batcher,
3036 state.snatch_guard,
3037 )
3038 }
3039 .map_err(|e| match e {
3040 ExecutionError::Device(e) => RenderPassErrorInner::Device(e),
3041 ExecutionError::DestroyedResource(e) => {
3042 RenderPassErrorInner::RenderCommand(RenderCommandError::DestroyedResource(e))
3043 }
3044 ExecutionError::Unimplemented(what) => {
3045 RenderPassErrorInner::RenderCommand(RenderCommandError::Unimplemented(what))
3046 }
3047 })?;
3048
3049 unsafe {
3050 state.info.usage_scope.merge_render_bundle(&bundle.used)?;
3051 };
3052 state.reset_bundle();
3053 Ok(())
3054 }
3055
3056 impl Global {
3057 fn resolve_render_pass_buffer_id(
3058 &self,
3059 scope: PassErrorScope,
3060 buffer_id: id::Id<id::markers::Buffer>,
3061 ) -> Result<Arc<crate::resource::Buffer>, RenderPassError> {
3062 let hub = &self.hub;
3063 let buffer = hub.buffers.get(buffer_id).get().map_pass_err(scope)?;
3064
3065 Ok(buffer)
3066 }
3067
3068 fn resolve_render_pass_query_set(
3069 &self,
3070 scope: PassErrorScope,
3071 query_set_id: id::Id<id::markers::QuerySet>,
3072 ) -> Result<Arc<QuerySet>, RenderPassError> {
3073 let hub = &self.hub;
3074 let query_set = hub.query_sets.get(query_set_id).get().map_pass_err(scope)?;
3075
3076 Ok(query_set)
3077 }
3078
3079 pub fn render_pass_set_bind_group(
3080 &self,
3081 pass: &mut RenderPass,
3082 index: u32,
3083 bind_group_id: Option<id::BindGroupId>,
3084 offsets: &[DynamicOffset],
3085 ) -> Result<(), RenderPassError> {
3086 let scope = PassErrorScope::SetBindGroup;
3087 let base = pass
3088 .base
3089 .as_mut()
3090 .ok_or(RenderPassErrorInner::PassEnded)
3091 .map_pass_err(scope)?;
3092
3093 if pass.current_bind_groups.set_and_check_redundant(
3094 bind_group_id,
3095 index,
3096 &mut base.dynamic_offsets,
3097 offsets,
3098 ) {
3099 // Do redundant early-out **after** checking whether the pass is ended or not.
3100 return Ok(());
3101 }
3102
3103 let mut bind_group = None;
3104 if bind_group_id.is_some() {
3105 let bind_group_id = bind_group_id.unwrap();
3106
3107 let hub = &self.hub;
3108 let bg = hub
3109 .bind_groups
3110 .get(bind_group_id)
3111 .get()
3112 .map_pass_err(scope)?;
3113 bind_group = Some(bg);
3114 }
3115
3116 base.commands.push(ArcRenderCommand::SetBindGroup {
3117 index,
3118 num_dynamic_offsets: offsets.len(),
3119 bind_group,
3120 });
3121
3122 Ok(())
3123 }
3124
3125 pub fn render_pass_set_pipeline(
3126 &self,
3127 pass: &mut RenderPass,
3128 pipeline_id: id::RenderPipelineId,
3129 ) -> Result<(), RenderPassError> {
3130 let scope = PassErrorScope::SetPipelineRender;
3131
3132 let redundant = pass.current_pipeline.set_and_check_redundant(pipeline_id);
3133 let base = pass.base_mut(scope)?;
3134
3135 if redundant {
3136 // Do redundant early-out **after** checking whether the pass is ended or not.
3137 return Ok(());
3138 }
3139
3140 let hub = &self.hub;
3141 let pipeline = hub
3142 .render_pipelines
3143 .get(pipeline_id)
3144 .get()
3145 .map_pass_err(scope)?;
3146
3147 base.commands.push(ArcRenderCommand::SetPipeline(pipeline));
3148
3149 Ok(())
3150 }
3151
3152 pub fn render_pass_set_index_buffer(
3153 &self,
3154 pass: &mut RenderPass,
3155 buffer_id: id::BufferId,
3156 index_format: IndexFormat,
3157 offset: BufferAddress,
3158 size: Option<BufferSize>,
3159 ) -> Result<(), RenderPassError> {
3160 let scope = PassErrorScope::SetIndexBuffer;
3161 let base = pass.base_mut(scope)?;
3162
3163 base.commands.push(ArcRenderCommand::SetIndexBuffer {
3164 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3165 index_format,
3166 offset,
3167 size,
3168 });
3169
3170 Ok(())
3171 }
3172
3173 pub fn render_pass_set_vertex_buffer(
3174 &self,
3175 pass: &mut RenderPass,
3176 slot: u32,
3177 buffer_id: id::BufferId,
3178 offset: BufferAddress,
3179 size: Option<BufferSize>,
3180 ) -> Result<(), RenderPassError> {
3181 let scope = PassErrorScope::SetVertexBuffer;
3182 let base = pass.base_mut(scope)?;
3183
3184 base.commands.push(ArcRenderCommand::SetVertexBuffer {
3185 slot,
3186 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3187 offset,
3188 size,
3189 });
3190
3191 Ok(())
3192 }
3193
3194 pub fn render_pass_set_blend_constant(
3195 &self,
3196 pass: &mut RenderPass,
3197 color: Color,
3198 ) -> Result<(), RenderPassError> {
3199 let scope = PassErrorScope::SetBlendConstant;
3200 let base = pass.base_mut(scope)?;
3201
3202 base.commands
3203 .push(ArcRenderCommand::SetBlendConstant(color));
3204
3205 Ok(())
3206 }
3207
3208 pub fn render_pass_set_stencil_reference(
3209 &self,
3210 pass: &mut RenderPass,
3211 value: u32,
3212 ) -> Result<(), RenderPassError> {
3213 let scope = PassErrorScope::SetStencilReference;
3214 let base = pass.base_mut(scope)?;
3215
3216 base.commands
3217 .push(ArcRenderCommand::SetStencilReference(value));
3218
3219 Ok(())
3220 }
3221
3222 pub fn render_pass_set_viewport(
3223 &self,
3224 pass: &mut RenderPass,
3225 x: f32,
3226 y: f32,
3227 w: f32,
3228 h: f32,
3229 depth_min: f32,
3230 depth_max: f32,
3231 ) -> Result<(), RenderPassError> {
3232 let scope = PassErrorScope::SetViewport;
3233 let base = pass.base_mut(scope)?;
3234
3235 base.commands.push(ArcRenderCommand::SetViewport {
3236 rect: Rect { x, y, w, h },
3237 depth_min,
3238 depth_max,
3239 });
3240
3241 Ok(())
3242 }
3243
3244 pub fn render_pass_set_scissor_rect(
3245 &self,
3246 pass: &mut RenderPass,
3247 x: u32,
3248 y: u32,
3249 w: u32,
3250 h: u32,
3251 ) -> Result<(), RenderPassError> {
3252 let scope = PassErrorScope::SetScissorRect;
3253 let base = pass.base_mut(scope)?;
3254
3255 base.commands
3256 .push(ArcRenderCommand::SetScissor(Rect { x, y, w, h }));
3257
3258 Ok(())
3259 }
3260
3261 pub fn render_pass_set_push_constants(
3262 &self,
3263 pass: &mut RenderPass,
3264 stages: ShaderStages,
3265 offset: u32,
3266 data: &[u8],
3267 ) -> Result<(), RenderPassError> {
3268 let scope = PassErrorScope::SetPushConstant;
3269 let base = pass.base_mut(scope)?;
3270
3271 if offset & (wgt::PUSH_CONSTANT_ALIGNMENT - 1) != 0 {
3272 return Err(RenderPassErrorInner::PushConstantOffsetAlignment).map_pass_err(scope);
3273 }
3274 if data.len() as u32 & (wgt::PUSH_CONSTANT_ALIGNMENT - 1) != 0 {
3275 return Err(RenderPassErrorInner::PushConstantSizeAlignment).map_pass_err(scope);
3276 }
3277
3278 let value_offset = base
3279 .push_constant_data
3280 .len()
3281 .try_into()
3282 .map_err(|_| RenderPassErrorInner::PushConstantOutOfMemory)
3283 .map_pass_err(scope)?;
3284
3285 base.push_constant_data.extend(
3286 data.chunks_exact(wgt::PUSH_CONSTANT_ALIGNMENT as usize)
3287 .map(|arr| u32::from_ne_bytes([arr[0], arr[1], arr[2], arr[3]])),
3288 );
3289
3290 base.commands.push(ArcRenderCommand::SetPushConstant {
3291 stages,
3292 offset,
3293 size_bytes: data.len() as u32,
3294 values_offset: Some(value_offset),
3295 });
3296
3297 Ok(())
3298 }
3299
3300 pub fn render_pass_draw(
3301 &self,
3302 pass: &mut RenderPass,
3303 vertex_count: u32,
3304 instance_count: u32,
3305 first_vertex: u32,
3306 first_instance: u32,
3307 ) -> Result<(), RenderPassError> {
3308 let scope = PassErrorScope::Draw {
3309 kind: DrawKind::Draw,
3310 indexed: false,
3311 };
3312 let base = pass.base_mut(scope)?;
3313
3314 base.commands.push(ArcRenderCommand::Draw {
3315 vertex_count,
3316 instance_count,
3317 first_vertex,
3318 first_instance,
3319 });
3320
3321 Ok(())
3322 }
3323
3324 pub fn render_pass_draw_indexed(
3325 &self,
3326 pass: &mut RenderPass,
3327 index_count: u32,
3328 instance_count: u32,
3329 first_index: u32,
3330 base_vertex: i32,
3331 first_instance: u32,
3332 ) -> Result<(), RenderPassError> {
3333 let scope = PassErrorScope::Draw {
3334 kind: DrawKind::Draw,
3335 indexed: true,
3336 };
3337 let base = pass.base_mut(scope)?;
3338
3339 base.commands.push(ArcRenderCommand::DrawIndexed {
3340 index_count,
3341 instance_count,
3342 first_index,
3343 base_vertex,
3344 first_instance,
3345 });
3346
3347 Ok(())
3348 }
3349
3350 pub fn render_pass_draw_indirect(
3351 &self,
3352 pass: &mut RenderPass,
3353 buffer_id: id::BufferId,
3354 offset: BufferAddress,
3355 ) -> Result<(), RenderPassError> {
3356 let scope = PassErrorScope::Draw {
3357 kind: DrawKind::DrawIndirect,
3358 indexed: false,
3359 };
3360 let base = pass.base_mut(scope)?;
3361
3362 base.commands.push(ArcRenderCommand::DrawIndirect {
3363 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3364 offset,
3365 count: 1,
3366 indexed: false,
3367
3368 vertex_or_index_limit: 0,
3369 instance_limit: 0,
3370 });
3371
3372 Ok(())
3373 }
3374
3375 pub fn render_pass_draw_indexed_indirect(
3376 &self,
3377 pass: &mut RenderPass,
3378 buffer_id: id::BufferId,
3379 offset: BufferAddress,
3380 ) -> Result<(), RenderPassError> {
3381 let scope = PassErrorScope::Draw {
3382 kind: DrawKind::DrawIndirect,
3383 indexed: true,
3384 };
3385 let base = pass.base_mut(scope)?;
3386
3387 base.commands.push(ArcRenderCommand::DrawIndirect {
3388 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3389 offset,
3390 count: 1,
3391 indexed: true,
3392
3393 vertex_or_index_limit: 0,
3394 instance_limit: 0,
3395 });
3396
3397 Ok(())
3398 }
3399
3400 pub fn render_pass_multi_draw_indirect(
3401 &self,
3402 pass: &mut RenderPass,
3403 buffer_id: id::BufferId,
3404 offset: BufferAddress,
3405 count: u32,
3406 ) -> Result<(), RenderPassError> {
3407 let scope = PassErrorScope::Draw {
3408 kind: DrawKind::MultiDrawIndirect,
3409 indexed: false,
3410 };
3411 let base = pass.base_mut(scope)?;
3412
3413 base.commands.push(ArcRenderCommand::DrawIndirect {
3414 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3415 offset,
3416 count,
3417 indexed: false,
3418
3419 vertex_or_index_limit: 0,
3420 instance_limit: 0,
3421 });
3422
3423 Ok(())
3424 }
3425
3426 pub fn render_pass_multi_draw_indexed_indirect(
3427 &self,
3428 pass: &mut RenderPass,
3429 buffer_id: id::BufferId,
3430 offset: BufferAddress,
3431 count: u32,
3432 ) -> Result<(), RenderPassError> {
3433 let scope = PassErrorScope::Draw {
3434 kind: DrawKind::MultiDrawIndirect,
3435 indexed: true,
3436 };
3437 let base = pass.base_mut(scope)?;
3438
3439 base.commands.push(ArcRenderCommand::DrawIndirect {
3440 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3441 offset,
3442 count,
3443 indexed: true,
3444
3445 vertex_or_index_limit: 0,
3446 instance_limit: 0,
3447 });
3448
3449 Ok(())
3450 }
3451
3452 pub fn render_pass_multi_draw_indirect_count(
3453 &self,
3454 pass: &mut RenderPass,
3455 buffer_id: id::BufferId,
3456 offset: BufferAddress,
3457 count_buffer_id: id::BufferId,
3458 count_buffer_offset: BufferAddress,
3459 max_count: u32,
3460 ) -> Result<(), RenderPassError> {
3461 let scope = PassErrorScope::Draw {
3462 kind: DrawKind::MultiDrawIndirectCount,
3463 indexed: false,
3464 };
3465 let base = pass.base_mut(scope)?;
3466
3467 base.commands
3468 .push(ArcRenderCommand::MultiDrawIndirectCount {
3469 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3470 offset,
3471 count_buffer: self.resolve_render_pass_buffer_id(scope, count_buffer_id)?,
3472 count_buffer_offset,
3473 max_count,
3474 indexed: false,
3475 });
3476
3477 Ok(())
3478 }
3479
3480 pub fn render_pass_multi_draw_indexed_indirect_count(
3481 &self,
3482 pass: &mut RenderPass,
3483 buffer_id: id::BufferId,
3484 offset: BufferAddress,
3485 count_buffer_id: id::BufferId,
3486 count_buffer_offset: BufferAddress,
3487 max_count: u32,
3488 ) -> Result<(), RenderPassError> {
3489 let scope = PassErrorScope::Draw {
3490 kind: DrawKind::MultiDrawIndirectCount,
3491 indexed: true,
3492 };
3493 let base = pass.base_mut(scope)?;
3494
3495 base.commands
3496 .push(ArcRenderCommand::MultiDrawIndirectCount {
3497 buffer: self.resolve_render_pass_buffer_id(scope, buffer_id)?,
3498 offset,
3499 count_buffer: self.resolve_render_pass_buffer_id(scope, count_buffer_id)?,
3500 count_buffer_offset,
3501 max_count,
3502 indexed: true,
3503 });
3504
3505 Ok(())
3506 }
3507
3508 pub fn render_pass_push_debug_group(
3509 &self,
3510 pass: &mut RenderPass,
3511 label: &str,
3512 color: u32,
3513 ) -> Result<(), RenderPassError> {
3514 let base = pass.base_mut(PassErrorScope::PushDebugGroup)?;
3515
3516 let bytes = label.as_bytes();
3517 base.string_data.extend_from_slice(bytes);
3518
3519 base.commands.push(ArcRenderCommand::PushDebugGroup {
3520 color,
3521 len: bytes.len(),
3522 });
3523
3524 Ok(())
3525 }
3526
3527 pub fn render_pass_pop_debug_group(
3528 &self,
3529 pass: &mut RenderPass,
3530 ) -> Result<(), RenderPassError> {
3531 let base = pass.base_mut(PassErrorScope::PopDebugGroup)?;
3532
3533 base.commands.push(ArcRenderCommand::PopDebugGroup);
3534
3535 Ok(())
3536 }
3537
3538 pub fn render_pass_insert_debug_marker(
3539 &self,
3540 pass: &mut RenderPass,
3541 label: &str,
3542 color: u32,
3543 ) -> Result<(), RenderPassError> {
3544 let base = pass.base_mut(PassErrorScope::InsertDebugMarker)?;
3545
3546 let bytes = label.as_bytes();
3547 base.string_data.extend_from_slice(bytes);
3548
3549 base.commands.push(ArcRenderCommand::InsertDebugMarker {
3550 color,
3551 len: bytes.len(),
3552 });
3553
3554 Ok(())
3555 }
3556
3557 pub fn render_pass_write_timestamp(
3558 &self,
3559 pass: &mut RenderPass,
3560 query_set_id: id::QuerySetId,
3561 query_index: u32,
3562 ) -> Result<(), RenderPassError> {
3563 let scope = PassErrorScope::WriteTimestamp;
3564 let base = pass.base_mut(scope)?;
3565
3566 base.commands.push(ArcRenderCommand::WriteTimestamp {
3567 query_set: self.resolve_render_pass_query_set(scope, query_set_id)?,
3568 query_index,
3569 });
3570
3571 Ok(())
3572 }
3573
3574 pub fn render_pass_begin_occlusion_query(
3575 &self,
3576 pass: &mut RenderPass,
3577 query_index: u32,
3578 ) -> Result<(), RenderPassError> {
3579 let scope = PassErrorScope::BeginOcclusionQuery;
3580 let base = pass.base_mut(scope)?;
3581
3582 base.commands
3583 .push(ArcRenderCommand::BeginOcclusionQuery { query_index });
3584
3585 Ok(())
3586 }
3587
3588 pub fn render_pass_end_occlusion_query(
3589 &self,
3590 pass: &mut RenderPass,
3591 ) -> Result<(), RenderPassError> {
3592 let scope = PassErrorScope::EndOcclusionQuery;
3593 let base = pass.base_mut(scope)?;
3594
3595 base.commands.push(ArcRenderCommand::EndOcclusionQuery);
3596
3597 Ok(())
3598 }
3599
3600 pub fn render_pass_begin_pipeline_statistics_query(
3601 &self,
3602 pass: &mut RenderPass,
3603 query_set_id: id::QuerySetId,
3604 query_index: u32,
3605 ) -> Result<(), RenderPassError> {
3606 let scope = PassErrorScope::BeginPipelineStatisticsQuery;
3607 let base = pass.base_mut(scope)?;
3608
3609 base.commands
3610 .push(ArcRenderCommand::BeginPipelineStatisticsQuery {
3611 query_set: self.resolve_render_pass_query_set(scope, query_set_id)?,
3612 query_index,
3613 });
3614
3615 Ok(())
3616 }
3617
3618 pub fn render_pass_end_pipeline_statistics_query(
3619 &self,
3620 pass: &mut RenderPass,
3621 ) -> Result<(), RenderPassError> {
3622 let scope = PassErrorScope::EndPipelineStatisticsQuery;
3623 let base = pass.base_mut(scope)?;
3624
3625 base.commands
3626 .push(ArcRenderCommand::EndPipelineStatisticsQuery);
3627
3628 Ok(())
3629 }
3630
3631 pub fn render_pass_execute_bundles(
3632 &self,
3633 pass: &mut RenderPass,
3634 render_bundle_ids: &[id::RenderBundleId],
3635 ) -> Result<(), RenderPassError> {
3636 let scope = PassErrorScope::ExecuteBundle;
3637 let base = pass.base_mut(scope)?;
3638
3639 let hub = &self.hub;
3640 let bundles = hub.render_bundles.read();
3641
3642 for &bundle_id in render_bundle_ids {
3643 let bundle = bundles.get(bundle_id).get().map_pass_err(scope)?;
3644
3645 base.commands.push(ArcRenderCommand::ExecuteBundle(bundle));
3646 }
3647 pass.current_pipeline.reset();
3648 pass.current_bind_groups.reset();
3649
3650 Ok(())
3651 }
3652 }
3653
3654 pub(crate) const fn get_stride_of_indirect_args(indexed: bool) -> u64 {
3655 match indexed {
3656 false => size_of::<wgt::DrawIndirectArgs>() as u64,
3657 true => size_of::<wgt::DrawIndexedIndirectArgs>() as u64,
3658 }
3659 }