fn store_hal_ops(store: StoreOp) -> hal::AttachmentOps { match store {
StoreOp::Store => hal::AttachmentOps::STORE,
StoreOp::Discard => hal::AttachmentOps::STORE_DISCARD,
}
}
// Stencil clear and reference value should take the LSBs. fn convert_stencil_value(value: u32, format: Option<wgt::TextureFormat>) -> u32 { let Some(format) = format else { return value;
}; let Some(stencil_format) = format.aspect_specific_format(wgt::TextureAspect::StencilOnly) else { return value;
}; // Currently only 8-bit stencil formats are supported
assert_eq!(stencil_format, wgt::TextureFormat::Stencil8);
value & 255
}
/// Describes an individual channel within a render pass, such as color, depth, or stencil. /// /// A channel must either be read-only, or it must specify both load and store /// operations. See [`ResolvedPassChannel`] for a validated version. #[repr(C)] #[derive(Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pubstruct PassChannel<V> { /// Operation to perform to the output attachment at the start of a /// renderpass. /// /// This must be clear if it is the first renderpass rendering to a swap /// chain image. pub load_op: Option<LoadOp<V>>, /// Operation to perform to the output attachment at the end of a renderpass. pub store_op: Option<StoreOp>, /// If true, the relevant channel is not changed by a renderpass, and the /// corresponding attachment can be used inside the pass by other read-only /// usages. pub read_only: bool,
}
/// Describes an individual channel within a render pass, such as color, depth, or stencil. /// /// Unlike [`PassChannel`], this version uses the Rust type system to guarantee /// a valid specification. #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pubenum ResolvedPassChannel<V> {
ReadOnly,
Operational(wgt::Operations<V>),
}
/// Describes a color attachment to a render pass. #[repr(C)] #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pubstruct RenderPassColorAttachment<TV = id::TextureViewId> { /// The view to use as an attachment. pub view: TV, /// The depth slice index of a 3D view. It must not be provided if the view is not 3D. pub depth_slice: Option<u32>, /// The view that will receive the resolved output if multisampling is used. pub resolve_target: Option<TV>, /// Operation to perform to the output attachment at the start of a /// renderpass. /// /// This must be clear if it is the first renderpass rendering to a swap /// chain image. pub load_op: LoadOp<Color>, /// Operation to perform to the output attachment at the end of a renderpass. pub store_op: StoreOp,
}
// Avoid allocation in the common case that there is only one color attachment, // but don't bloat `ArcCommand::RunRenderPass` excessively. pubtype ColorAttachments<TV = Arc<TextureView>> =
SmallVec<[Option<RenderPassColorAttachment<TV>>; 1]>;
/// Describes a depth/stencil attachment to a render pass. /// /// This version uses the unvalidated [`PassChannel`]. #[repr(C)] #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pubstruct RenderPassDepthStencilAttachment<TV> { /// The view to use as an attachment. pub view: TV, /// What operations will be performed on the depth part of the attachment. pub depth: PassChannel<Option<f32>>, /// What operations will be performed on the stencil part of the attachment. pub stencil: PassChannel<Option<u32>>,
}
/// Describes a depth/stencil attachment to a render pass. /// /// This version uses the validated [`ResolvedPassChannel`]. #[derive(Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pubstruct ResolvedRenderPassDepthStencilAttachment<TV> { /// The view to use as an attachment. pub view: TV, /// What operations will be performed on the depth part of the attachment. pub depth: ResolvedPassChannel<f32>, /// What operations will be performed on the stencil part of the attachment. pub stencil: ResolvedPassChannel<u32>,
}
/// Describes the attachments of a render pass. #[derive(Clone, Debug, Default, PartialEq)] pubstruct RenderPassDescriptor<'a> { pub label: Label<'a>, /// The color attachments of the render pass. pub color_attachments: Cow<'a, [Option<RenderPassColorAttachment>]>, /// The depth and stencil attachment of the render pass, if any. pub depth_stencil_attachment: Option<&'a RenderPassDepthStencilAttachment<id::TextureViewId>>, /// Defines where and when timestamp values will be written for this pass. pub timestamp_writes: Option<&'a PassTimestampWrites>, /// Defines where the occlusion query results will be stored for this pass. pub occlusion_query_set: Option<id::QuerySetId>, /// The multiview array layers that will be used pub multiview_mask: Option<NonZeroU32>,
}
/// Describes the attachments of a render pass. struct ArcRenderPassDescriptor<'a> { pub label: &'a Label<'a>, /// The color attachments of the render pass. pub color_attachments:
ArrayVec<Option<ArcRenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>, /// The depth and stencil attachment of the render pass, if any. pub depth_stencil_attachment:
Option<ResolvedRenderPassDepthStencilAttachment<Arc<TextureView>>>, /// Defines where and when timestamp values will be written for this pass. pub timestamp_writes: Option<ArcPassTimestampWrites>, /// Defines where the occlusion query results will be stored for this pass. pub occlusion_query_set: Option<Arc<QuerySet>>, /// The multiview array layers that will be used pub multiview_mask: Option<NonZeroU32>,
}
/// A pass's [encoder state](https://www.w3.org/TR/webgpu/#encoder-state) and /// its validity are two distinct conditions, i.e., the full matrix of /// (open, ended) x (valid, invalid) is possible. /// /// The presence or absence of the `parent` `Option` indicates the pass's state. /// The presence or absence of an error in `base.error` indicates the pass's /// validity. pubstruct RenderPass { /// All pass data & records is stored here.
base: BasePass<ArcRenderCommand, RenderPassError>,
/// Parent command encoder that this pass records commands into. /// /// If this is `Some`, then the pass is in WebGPU's "open" state. If it is /// `None`, then the pass is in the "ended" state. /// See <https://www.w3.org/TR/webgpu/#encoder-state>
parent: Option<Arc<CommandEncoder>>,
impl RenderPass { /// If the parent command encoder is invalid, the returned pass will be invalid. fn new(parent: Arc<CommandEncoder>, desc: ArcRenderPassDescriptor) -> Self { let ArcRenderPassDescriptor {
label,
timestamp_writes,
color_attachments,
depth_stencil_attachment,
occlusion_query_set,
multiview_mask,
} = desc;
#[derive(Debug, Default)] pub(crate) struct VertexLimits { /// Length of the shortest vertex rate vertex buffer pub(crate) vertex_limit: u64, /// Buffer slot which the shortest vertex rate vertex buffer is bound to
vertex_limit_slot: u32, /// Length of the shortest instance rate vertex buffer pub(crate) instance_limit: u64, /// Buffer slot which the shortest instance rate vertex buffer is bound to
instance_limit_slot: u32,
}
impl VertexLimits { pub(crate) fn new(
buffer_sizes: impl ExactSizeIterator<Item = Option<BufferAddress>>,
pipeline_steps: &[Option<VertexStep>],
) -> Self { // Implements the validation from https://gpuweb.github.io/gpuweb/#dom-gpurendercommandsmixin-draw // Except that the formula is shuffled to extract the number of vertices in order // to carry the bulk of the computation when changing states instead of when producing // draws. Draw calls tend to happen at a higher frequency. Here we determine vertex // limits that can be cheaply checked for each draw call.
let limit = if buffer_size < step.last_stride { // The buffer cannot fit the last vertex. 0
} else { if step.stride == 0 { // We already checked that the last stride fits, the same // vertex will be repeated so this slot can accommodate any number of // vertices. continue;
}
// The general case.
(buffer_size - step.last_stride) / step.stride + 1
};
match step.mode {
VertexStepMode::Vertex => { if limit < vertex_limit {
vertex_limit = limit;
vertex_limit_slot = idx as _;
}
}
VertexStepMode::Instance => { if limit < instance_limit {
instance_limit = limit;
instance_limit_slot = idx as _;
}
}
}
}
pub(crate) fn validate_vertex_limit(
&self,
first_vertex: u32,
vertex_count: u32,
) -> Result<(), DrawError> { let last_vertex = first_vertex as u64 + vertex_count as u64; let vertex_limit = self.vertex_limit; if last_vertex > vertex_limit { return Err(DrawError::VertexBeyondLimit {
last_vertex,
vertex_limit,
slot: self.vertex_limit_slot,
});
}
Ok(())
}
pub(crate) fn validate_instance_limit(
&self,
first_instance: u32,
instance_count: u32,
) -> Result<(), DrawError> { let last_instance = first_instance as u64 + instance_count as u64; let instance_limit = self.instance_limit; if last_instance > instance_limit { return Err(DrawError::InstanceBeyondLimit {
last_instance,
instance_limit,
slot: self.instance_limit_slot,
});
}
Ok(())
}
}
/// State of a single vertex buffer slot. #[derive(Debug)] pub(crate) struct VertexSlot { pub(crate) buffer: Arc<Buffer>, pub(crate) range: Range<BufferAddress>, pub(crate) is_dirty: bool,
}
/// Vertex buffer tracking state, shared between render passes and render bundles. /// /// Tracks which vertex buffer slots are set, and caches the vertex and instance limits /// derived from those buffers and the current pipeline, avoiding recomputation on each draw. #[derive(Debug, Default)] pub(crate) struct VertexState {
slots: [Option<VertexSlot>; hal::MAX_VERTEX_BUFFERS], pub(crate) limits: VertexLimits,
}
/// Recompute the cached vertex and instance limits based on the current slots and pipeline. pub(crate) fn update_limits(&mutself, pipeline_steps: &[Option<VertexStep>]) { self.limits = VertexLimits::new( self.slots
.iter()
.map(|s| s.as_ref().map(|s| s.range.end - s.range.start)),
pipeline_steps,
);
}
pub(super) fn validate(
&self,
pipeline: &RenderPipeline,
binder: &Binder,
) -> Result<(), DrawError> { // Check all needed vertex buffers have been bound for index in pipeline
.vertex_steps
.iter()
.enumerate()
.filter_map(|(index, step)| step.map(|_| index))
{ ifself.slots[index].is_none() { return Err(DrawError::MissingVertexBuffer {
pipeline: pipeline.error_ident(),
index,
});
}
}
let bind_group_space_used = binder.last_assigned_index().map_or(0, |i| i + 1); let vertex_buffer_space_used = self.last_assigned_index().map_or(0, |i| i + 1);
let bind_groups_plus_vertex_buffers =
u32::try_from(bind_group_space_used + vertex_buffer_space_used).unwrap(); if bind_groups_plus_vertex_buffers
> pipeline.device.limits.max_bind_groups_plus_vertex_buffers
{ return Err(DrawError::TooManyBindGroupsPlusVertexBuffers {
given: bind_groups_plus_vertex_buffers,
limit: pipeline.device.limits.max_bind_groups_plus_vertex_buffers,
});
}
Ok(())
}
/// Call `f` for each dirty slot with `(slot_index, buffer, offset, size)` and mark them clean. pub(crate) fn flush<F>(&mutself, mut f: F) where
F: FnMut(u32, &Arc<Buffer>, BufferAddress, Option<BufferSize>),
{ for (i, slot) inself.slots.iter_mut().enumerate() { let Some(slot) = slot.as_mut() else { continue }; if !slot.is_dirty { continue;
}
slot.is_dirty = false; let size = slot.range.end - slot.range.start;
f(
i as u32,
&slot.buffer,
slot.range.start,
BufferSize::new(size),
);
}
}
}
/// A bitmask, tracking which 4-byte slots have been written via `set_immediates`. /// Checked against the pipeline's required slots before each draw call.
immediate_slots_set: naga::valid::ImmediateSlots,
if family == DrawCommandFamily::DrawIndexed { // Pipeline expects an index buffer // We have a buffer bound let buffer_index_format = self
.index
.buffer_format
.ok_or(DrawError::MissingIndexBuffer)?;
/// Flush binding state in preparation for a draw call. /// /// See the compute pass version for an explanation of some ways that /// `flush_bindings` differs between the two types of passes. fn flush_bindings(&mutself) -> Result<(), RenderPassErrorInner> {
flush_bindings_helper(&mutself.pass)?;
Ok(())
}
/// Reset the `RenderBundle`-related states. fn reset_bundle(&mutself) { self.pass.binder.reset(); self.pipeline = None; self.index.reset(); self.vertex = Default::default(); self.immediate_slots_set = Default::default();
}
/// Flush dirty vertex buffer slots to the HAL encoder in preparation for a draw call. fn flush_vertex_buffers(&mutself) -> Result<(), RenderPassErrorInner> { let vertex = &mutself.vertex; let raw_encoder: &mutdyn hal::DynCommandEncoder = self.pass.base.raw_encoder; let snatch_guard = self.pass.base.snatch_guard; letmut result = Ok(());
vertex.flush(|slot, buffer, offset, size| { if result.is_err() { return;
} match buffer.try_raw(snatch_guard) {
Ok(raw) => unsafe { // SAFETY: The offset and size were validated in set_vertex_buffer.
raw_encoder.set_vertex_buffer(
slot,
hal::BufferBinding::new_unchecked(raw, offset, size),
);
},
Err(e) => result = Err(e.into()),
}
});
result
}
}
/// Describes an attachment location in words. /// /// Can be used as "the {loc} has..." or "{loc} has..." #[derive(Debug, Copy, Clone)] pubenum AttachmentErrorLocation {
Color { index: usize, resolve: bool },
Depth,
}
impl fmt::Display for AttachmentErrorLocation { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self {
AttachmentErrorLocation::Color {
index,
resolve: false,
} => write!(f, "color attachment at index {index}'s texture view"),
AttachmentErrorLocation::Color {
index,
resolve: true,
} => write!(
f, "color attachment at index {index}'s resolve texture view"
),
AttachmentErrorLocation::Depth => write!(f, "depth attachment's texture view"),
}
}
}
#[derive(Clone, Debug, Error)] #[non_exhaustive] pubenum ColorAttachmentError { #[error("Attachment format {0:?} is not a color format")]
InvalidFormat(wgt::TextureFormat), #[error("The number of color attachments {given} exceeds the limit {limit}")]
TooMany { given: usize, limit: usize }, #[error("The total number of bytes per sample in color attachments {total} exceeds the limit {limit}")]
TooManyBytesPerSample { total: u32, limit: u32 }, #[error("Depth slice must be less than {limit} but is {given}")]
DepthSliceLimit { given: u32, limit: u32 }, #[error("Color attachment's view is 3D and requires depth slice to be provided")]
MissingDepthSlice, #[error("Depth slice was provided but the color attachment's view is not 3D")]
UnneededDepthSlice, #[error("{view}'s subresource at mip {mip_level} and depth/array layer {depth_or_array_layer} is already attached to this render pass")]
SubresourceOverlap {
view: ResourceErrorIdent,
mip_level: u32,
depth_or_array_layer: u32,
}, #[error("Color attachment's usage contains {0:?}. This can only be used with StoreOp::{1:?}, but StoreOp::{2:?} was provided")]
InvalidUsageForStoreOp(TextureUsages, StoreOp, StoreOp), #[error("Color attachment's load op is `LoadOp::DontCare` but `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` is set")]
LoadOpDontCareUnderStrictWebgpuCompliance,
}
#[derive(Clone, Debug, Error)] #[non_exhaustive] pubenum AttachmentError { #[error("The format of the depth-stencil attachment ({0:?}) is not a depth-or-stencil format")]
InvalidDepthStencilAttachmentFormat(wgt::TextureFormat), #[error("LoadOp must be None for read-only attachments")]
ReadOnlyWithLoad, #[error("StoreOp must be None for read-only attachments")]
ReadOnlyWithStore, #[error("Depth `LoadOp` and `StoreOp` (`{ops:?}`) must be `None` for attachments (`{format:?}`) without depth aspect")]
DepthOpsWithoutAspect {
format: wgt::TextureFormat,
ops: (Option<LoadOp<Option<f32>>>, Option<StoreOp>),
}, #[error("Stencil `LoadOp` and `StoreOp` (`{ops:?}`) must be `None` for attachments (`{format:?}`) without stencil aspect")]
StencilOpsWithoutAspect {
format: wgt::TextureFormat,
ops: (Option<LoadOp<Option<u32>>>, Option<StoreOp>),
}, #[error("Attachment without load")]
NoLoad, #[error("Attachment without store")]
NoStore, #[error("LoadOp is `Clear` but no clear value was provided")]
NoClearValue, #[error("Clear value ({0}) must be between 0.0 and 1.0, inclusive")]
ClearValueOutOfRange(f32), #[error("Load op is `DontCare` but `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` is set")]
LoadOpDontCareUnderStrictWebgpuCompliance,
}
/// Error encountered when performing a render pass. #[derive(Clone, Debug, Error)] pubenum RenderPassErrorInner { #[error(transparent)]
Device(#[from] DeviceError), #[error(transparent)]
ColorAttachment(#[from] ColorAttachmentError), #[error(transparent)]
InvalidAttachment(#[from] AttachmentError), #[error(transparent)]
EncoderState(#[from] EncoderStateError), #[error("Parent encoder is invalid")]
InvalidParentEncoder, #[error(transparent)]
DebugGroupError(#[from] DebugGroupError), #[error("The format of the {location} ({format:?}) is not resolvable")]
UnsupportedResolveTargetFormat {
location: AttachmentErrorLocation,
format: wgt::TextureFormat,
}, #[error("No color attachments or depth attachments were provided, at least one attachment of any kind must be provided")]
MissingAttachments, #[error("The {location} is not renderable:")]
TextureViewIsNotRenderable {
location: AttachmentErrorLocation, #[source]
reason: TextureViewNotRenderableReason,
}, #[error("Attachments have differing sizes: the {expected_location} has extent {expected_extent:?} but is followed by the {actual_location} which has {actual_extent:?}")]
AttachmentsDimensionMismatch {
expected_location: AttachmentErrorLocation,
expected_extent: wgt::Extent3d,
actual_location: AttachmentErrorLocation,
actual_extent: wgt::Extent3d,
}, #[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:?}")]
AttachmentSampleCountMismatch {
expected_location: AttachmentErrorLocation,
expected_samples: u32,
actual_location: AttachmentErrorLocation,
actual_samples: u32,
}, #[error("The resolve source, {location}, must be multi-sampled (has {src} samples) while the resolve destination must not be multisampled (has {dst} samples)")]
InvalidResolveSampleCounts {
location: AttachmentErrorLocation,
src: u32,
dst: u32,
}, #[error( "Resource source, {location}, format ({src:?}) must match the resolve destination format ({dst:?})"
)]
MismatchedResolveTextureFormat {
location: AttachmentErrorLocation,
src: wgt::TextureFormat,
dst: wgt::TextureFormat,
}, #[error("Unable to clear non-present/read-only depth")]
InvalidDepthOps, #[error("Unable to clear non-present/read-only stencil")]
InvalidStencilOps, #[error(transparent)]
InvalidValuesOffset(#[from] pass::InvalidValuesOffset), #[error(transparent)]
MissingFeatures(#[from] MissingFeatures), #[error(transparent)]
MissingDownlevelFlags(#[from] MissingDownlevelFlags), #[error("Indirect buffer offset {0:?} is not a multiple of 4")]
UnalignedIndirectBufferOffset(BufferAddress), #[error("Indirect draw arguments of {args_size} bytes (count = {count}) starting at {offset} would overrun buffer size of {buffer_size}")]
IndirectBufferOverrun {
count: u32,
offset: u64,
args_size: u64,
buffer_size: u64,
}, #[error("Indirect draw count of {count_bytes} bytes starting at {begin_count_offset} would overrun buffer of size {count_buffer_size}")]
IndirectCountBufferOverrun {
count_bytes: u64,
begin_count_offset: u64,
count_buffer_size: u64,
}, #[error(transparent)]
ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError), #[error("Render bundle has incompatible targets, {0}")]
IncompatibleBundleTargets(#[from] RenderPassCompatibilityError), #[error( "Render bundle has incompatible read-only flags: \
bundle has flags depth = {bundle_depth} and stencil = {bundle_stencil}, \ while the pass has flags depth = {pass_depth} and stencil = {pass_stencil}. \
Read-only renderpasses are only compatible with read-only bundles for that aspect."
)]
IncompatibleBundleReadOnlyDepthStencil {
pass_depth: bool,
pass_stencil: bool,
bundle_depth: bool,
bundle_stencil: bool,
}, #[error(transparent)]
RenderCommand(#[from] RenderCommandError), #[error(transparent)]
Draw(#[from] DrawError), #[error(transparent)]
Bind(#[from] BindError), #[error("Immediate data offset must be aligned to 4 bytes")]
ImmediateOffsetAlignment, #[error("Immediate data size must be aligned to 4 bytes")]
ImmediateDataizeAlignment, #[error("Ran out of immediate data space. Don't set 4gb of immediates per ComputePass.")]
ImmediateOutOfMemory, #[error(transparent)]
QueryUse(#[from] QueryUseError), #[error("Multiview layer count must match")]
MultiViewMismatch, #[error( "Multiview pass texture views with more than one array layer must have D2Array dimension"
)]
MultiViewDimensionMismatch, #[error("Multiview view count limit violated")]
TooManyMultiviewViews, #[error("missing occlusion query set")]
MissingOcclusionQuerySet, #[error(transparent)]
DestroyedResource(#[from] DestroyedResourceError), #[error("The compute pass has already been ended and no further commands can be recorded")]
PassEnded, #[error(transparent)]
InvalidResource(#[from] InvalidResourceError), #[error(transparent)]
TimestampWrites(#[from] TimestampWritesError),
}
impl RenderPassInfo { fn add_pass_texture_init_actions<V>(
load_op: LoadOp<V>,
store_op: StoreOp,
texture_memory_actions: &mut CommandBufferTextureMemoryActions,
view: &TextureView,
pending_discard_init_fixups: &mut SurfacesInDiscardState,
) { if matches!(load_op, LoadOp::Load) {
pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
&TextureInitTrackerAction {
texture: view.parent.clone(),
range: TextureInitRange::from(view.selector.clone()), // Note that this is needed even if the target is discarded,
kind: MemoryInitKind::NeedsInitializedMemory,
},
));
} elseif store_op == StoreOp::Store { // Clear + Store
texture_memory_actions.register_implicit_init(
&view.parent,
TextureInitRange::from(view.selector.clone()),
);
} if store_op == StoreOp::Discard { // the discard happens at the *end* of a pass, but recording the // discard right away be alright since the texture can't be used // during the pass anyways
texture_memory_actions.discard(TextureSurfaceDiscard {
texture: view.parent.clone(),
mip_level: view.selector.mips.start,
layer: view.selector.layers.start,
});
}
}
// We default to false intentionally, even if depth-stencil isn't used at all. // This allows us to use the primary raw pipeline in `RenderPipeline`, // instead of the special read-only one, which would be `None`. letmut is_depth_read_only = false; letmut is_stencil_read_only = false;
letmut check_multiview = |view: &TextureView| { // Get the multiview configuration for this texture view let layers = view.selector.layers.end - view.selector.layers.start; let this_multiview = if layers >= 2 { // Trivially proven by the if above
Some(unsafe { NonZeroU32::new_unchecked(layers) })
} else {
None
};
// Make sure that if this view is a multiview, it is set to be an array if this_multiview.is_some() && view.desc.dimension != TextureViewDimension::D2Array { return Err(RenderPassErrorInner::MultiViewDimensionMismatch);
}
// Validate matching first, or store the first one iflet Some(multiview) = detected_multiview { if multiview != this_multiview { return Err(RenderPassErrorInner::MultiViewMismatch);
}
} else { // Multiview is only supported if the feature is enabled iflet Some(this_multiview) = this_multiview {
device.require_features(wgt::Features::MULTIVIEW)?; if this_multiview.get() > device.limits.max_multiview_view_count { return Err(RenderPassErrorInner::TooManyMultiviewViews);
}
}
if !ds_aspects.contains(hal::FormatAspects::STENCIL)
|| (at.stencil.load_op().eq_variant(at.depth.load_op())
&& at.stencil.store_op() == at.depth.store_op())
{ Self::add_pass_texture_init_actions(
at.depth.load_op(),
at.depth.store_op(),
texture_memory_actions,
view,
pending_discard_init_fixups,
);
} elseif !ds_aspects.contains(hal::FormatAspects::DEPTH) { Self::add_pass_texture_init_actions(
at.stencil.load_op(),
at.stencil.store_op(),
texture_memory_actions,
view,
pending_discard_init_fixups,
);
} else { // This is the only place (anywhere in wgpu) where Stencil & // Depth init state can diverge. // // To safe us the overhead of tracking init state of texture // aspects everywhere, we're going to cheat a little bit in // order to keep the init state of both Stencil and Depth // aspects in sync. The expectation is that we hit this path // extremely rarely! // // Diverging LoadOp, i.e. Load + Clear: // // Record MemoryInitKind::NeedsInitializedMemory for the entire // surface, a bit wasteful on unit but no negative effect! // // Rationale: If the loaded channel is uninitialized it needs // clearing, the cleared channel doesn't care. (If everything is // already initialized nothing special happens) // // (possible minor optimization: Clear caused by // NeedsInitializedMemory should know that it doesn't need to // clear the aspect that was set to C) let need_init_beforehand =
at.depth.load_op() == LoadOp::Load || at.stencil.load_op() == LoadOp::Load; if need_init_beforehand {
pending_discard_init_fixups.extend(
texture_memory_actions.register_init_action(&TextureInitTrackerAction {
texture: view.parent.clone(),
range: TextureInitRange::from(view.selector.clone()),
kind: MemoryInitKind::NeedsInitializedMemory,
}),
);
}
// Diverging Store, i.e. Discard + Store: // // Immediately zero out channel that is set to discard after // we're done with the render pass. This allows us to set the // entire surface to MemoryInitKind::ImplicitlyInitialized (if // it isn't already set to NeedsInitializedMemory). // // (possible optimization: Delay and potentially drop this zeroing) if at.depth.store_op() != at.stencil.store_op() { if !need_init_beforehand {
texture_memory_actions.register_implicit_init(
&view.parent,
TextureInitRange::from(view.selector.clone()),
);
}
divergent_discarded_depth_stencil_aspect = Some(( if at.depth.store_op() == StoreOp::Discard {
wgt::TextureAspect::DepthOnly
} else {
wgt::TextureAspect::StencilOnly
},
view.clone(),
));
} elseif at.depth.store_op() == StoreOp::Discard { // Both are discarded using the regular path.
discarded_surfaces.push(TextureSurfaceDiscard {
texture: view.parent.clone(),
mip_level: view.selector.mips.start,
layer: view.selector.layers.start,
});
}
}
let usage = if is_depth_read_only
&& is_stencil_read_only
&& device
.downlevel
.flags
.contains(wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL)
{ // If the texture supports TEXTURE_BINDING, it can be used as a shader // resource and a read-only depth attachment simultaneously. But if it // doesn't support TEXTURE_BINDING, don't attempt to transition it to a // shader resource state, because DX12 will raise an error. if view.desc.usage.contains(TextureUsages::TEXTURE_BINDING) {
wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::RESOURCE
} else {
wgt::TextureUses::DEPTH_STENCIL_READ
}
} else {
wgt::TextureUses::DEPTH_STENCIL_WRITE
};
render_attachments.push(view.to_render_attachment(usage));
let extent = extent.ok_or(RenderPassErrorInner::MissingAttachments)?;
let detected_multiview =
detected_multiview.expect("Multiview was not detected, no attachments"); iflet Some(mask) = multiview_mask { // 0x01 will have msb 0 let mask_msb = 31 - mask.leading_zeros(); let detected_mv = detected_multiview.map(NonZeroU32::get).unwrap_or(1); if mask_msb >= detected_mv { return Err(RenderPassErrorInner::MultiViewMismatch);
} if mask.get() != (1 << detected_mv) - 1 {
device.require_features(wgt::Features::SELECTIVE_MULTIVIEW)?;
}
}
let hal_desc = hal::RenderPassDescriptor {
label: hal_label,
extent,
sample_count,
color_attachments: &color_attachments_hal,
depth_stencil_attachment: depth_stencil,
multiview_mask,
timestamp_writes: timestamp_writes_hal,
occlusion_query_set: occlusion_query_set_hal,
}; unsafe {
encoder
.begin_render_pass(&hal_desc)
.map_err(|e| device.handle_hal_error(e))?;
};
drop(color_attachments_hal); // Drop, so we can consume `color_attachments` for the tracker.
// Can't borrow the tracker more than once, so have to add to the tracker after the `begin_render_pass` hal call. iflet Some(tw) = timestamp_writes.take() {
trackers.query_sets.insert_single(tw.query_set);
}; iflet Some(occlusion_query_set) = occlusion_query_set.take() {
trackers.query_sets.insert_single(occlusion_query_set);
}; iflet Some(at) = depth_stencil_attachment.take() {
trackers.views.insert_single(at.view.clone());
} for at in color_attachments.iter().flatten() {
trackers.views.insert_single(at.view.clone()); iflet Some(resolve_target) = at.resolve_target.clone() {
trackers.views.insert_single(resolve_target);
}
}
for ra inself.render_attachments { let texture = &ra.texture;
texture.check_usage(TextureUsages::RENDER_ATTACHMENT)?;
// the tracker set of the pass is always in "extend" mode unsafe {
scope
.textures
.merge_single(texture, Some(ra.selector.clone()), ra.usage)?
};
}
// If either only stencil or depth was discarded, we put in a special // clear pass to keep the init status of the aspects in sync. We do this // so we don't need to track init state for depth/stencil aspects // individually. // // Note that we don't go the usual route of "brute force" initializing // the texture when need arises here, since this path is actually // something a user may genuinely want (where as the other cases are // more seen along the lines as gracefully handling a user error). iflet Some((aspect, view)) = self.divergent_discarded_depth_stencil_aspect { let (depth_ops, stencil_ops) = if aspect == wgt::TextureAspect::DepthOnly {
(
hal::AttachmentOps::LOAD_CLEAR | hal::AttachmentOps::STORE, // clear depth
hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
)
} else {
(
hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
hal::AttachmentOps::LOAD_CLEAR | hal::AttachmentOps::STORE, // clear depth
)
}; let desc = hal::RenderPassDescriptor::<'_, _, dyn hal::DynTextureView> {
label: hal_label(
Some("(wgpu internal) Zero init discarded depth/stencil aspect"),
instance_flags,
),
extent: view.render_extent.unwrap(),
sample_count: view.samples,
color_attachments: &[],
depth_stencil_attachment: Some(hal::DepthStencilAttachment {
target: hal::Attachment {
view: view.try_raw(snatch_guard)?,
usage: wgt::TextureUses::DEPTH_STENCIL_WRITE,
},
depth_ops,
stencil_ops,
clear_value: (0.0, 0),
}),
multiview_mask: self.multiview_mask,
timestamp_writes: None,
occlusion_query_set: None,
}; unsafe {
raw.begin_render_pass(&desc)
.map_err(|e| device.handle_hal_error(e))?;
raw.end_render_pass();
}
}
Ok(())
}
}
impl Global { /// Creates a render pass. /// /// If creation fails, an invalid pass is returned. Attempting to record /// commands into an invalid pass is permitted, but a validation error will /// ultimately be generated when the parent encoder is finished, and it is /// not possible to run any commands from the invalid pass. /// /// If successful, puts the encoder into the [`Locked`] state. /// /// [`Locked`]: crate::command::CommandEncoderStatus::Locked pubfn command_encoder_begin_render_pass(
&self,
encoder_id: id::CommandEncoderId,
desc: &RenderPassDescriptor<'_>,
) -> (RenderPass, Option<CommandEncoderError>) { use EncoderStateError as SErr;
let format = view.desc.format; if !format.is_depth_stencil_format() { return Err(RenderPassErrorInner::InvalidAttachment(AttachmentError::InvalidDepthStencilAttachmentFormat(
view.desc.format,
)));
}
Some(ResolvedRenderPassDepthStencilAttachment {
view,
depth: if format.has_depth_aspect() {
depth_stencil_attachment.depth.resolve(device.instance_flags, |clear| iflet Some(clear) = clear { // If this.depthLoadOp is "clear", this.depthClearValue must be provided and must be between 0.0 and 1.0, inclusive. if !(0.0..=1.0).contains(&clear) {
Err(AttachmentError::ClearValueOutOfRange(clear))
} else {
Ok(clear)
}
} else {
Err(AttachmentError::NoClearValue)
})?
} else { if depth_stencil_attachment.depth.load_op.is_some() || depth_stencil_attachment.depth.store_op.is_some() { return Err(RenderPassErrorInner::InvalidAttachment(AttachmentError::DepthOpsWithoutAspect {
format,
ops: (depth_stencil_attachment.depth.load_op, depth_stencil_attachment.depth.store_op)
}));
}
ResolvedPassChannel::ReadOnly
},
stencil: if format.has_stencil_aspect() {
depth_stencil_attachment.stencil.resolve(device.instance_flags, |clear| {
Ok(convert_stencil_value(clear.unwrap_or_default(), Some(format)))
})?
} else { if depth_stencil_attachment.stencil.load_op.is_some() || depth_stencil_attachment.stencil.store_op.is_some() { return Err(RenderPassErrorInner::InvalidAttachment(AttachmentError::StencilOpsWithoutAspect {
format,
ops: (depth_stencil_attachment.stencil.load_op, depth_stencil_attachment.stencil.store_op)
}));
}
ResolvedPassChannel::ReadOnly
},
})
} else {
None
};
let scope = PassErrorScope::Pass; let hub = &self.hub;
let cmd_enc = hub.command_encoders.get(encoder_id); letmut cmd_buf_data = cmd_enc.data.lock();
match cmd_buf_data.lock_encoder() {
Ok(()) => {
drop(cmd_buf_data); letmut arc_desc = ArcRenderPassDescriptor {
label: &desc.label,
timestamp_writes: None,
color_attachments: ArrayVec::new(),
depth_stencil_attachment: None,
occlusion_query_set: None,
multiview_mask: None,
}; match fill_arc_desc(hub, desc, &mut arc_desc, &cmd_enc.device) {
Ok(()) => (RenderPass::new(cmd_enc, arc_desc), None),
Err(err) => (
RenderPass::new_invalid(cmd_enc, &desc.label, err.map_pass_err(scope)),
None,
),
}
}
Err(err @ SErr::Locked) => { // Attempting to open a new pass while the encoder is locked // invalidates the encoder, but does not generate a validation // error.
cmd_buf_data.invalidate(err.clone());
drop(cmd_buf_data);
(
RenderPass::new_invalid(cmd_enc, &desc.label, err.map_pass_err(scope)),
None,
)
}
Err(err @ (SErr::Ended | SErr::Submitted)) => { // Attempting to open a new pass after the encode has ended // generates an immediate validation error.
drop(cmd_buf_data);
(
RenderPass::new_invalid(cmd_enc, &desc.label, err.clone().map_pass_err(scope)),
Some(err.into()),
)
}
Err(err @ SErr::Invalid) => { // Passes can be opened even on an invalid encoder. Such passes // are even valid, but since there's no visible side-effect of // the pass being valid and there's no point in storing recorded // commands that will ultimately be discarded, we open an // invalid pass to save that work.
drop(cmd_buf_data);
(
RenderPass::new_invalid(cmd_enc, &desc.label, err.map_pass_err(scope)),
None,
)
}
Err(SErr::Unlocked) => {
unreachable!("lock_encoder cannot fail due to the encoder being unlocked")
}
}
}
let cmd_enc = pass.parent.take().ok_or(EncoderStateError::Ended)?; letmut cmd_buf_data = cmd_enc.data.lock();
cmd_buf_data.unlock_encoder()?;
let base = pass.base.take();
iflet Err(RenderPassError {
inner:
RenderPassErrorInner::EncoderState(
err @ (EncoderStateError::Locked | EncoderStateError::Ended),
),
scope: _,
}) = base
{ // Most encoding errors are detected and raised within `finish()`. // // However, we raise a validation error here if the pass was opened // within another pass, or on a finished encoder. The latter is // particularly important, because in that case reporting errors via // `CommandEncoder::finish` is not possible. return Err(err.clone());
}
// We automatically keep extending command buffers over time, and because // we want to insert a command buffer _before_ what we're about to record, // we need to make sure to close the previous one.
parent_state
.raw_encoder
.close_if_open()
.map_pass_err(pass_scope)?; let raw_encoder = parent_state
.raw_encoder
.open_pass(base.label.as_deref())
.map_pass_err(pass_scope)?;
let info = RenderPassInfo::start(
device,
hal_label(base.label.as_deref(), device.instance_flags),
&color_attachments,
depth_stencil_attachment.take(),
timestamp_writes.take(), // Still needed down the line. // TODO(wumpf): by restructuring the code, we could get rid of some of this Arc clone.
occlusion_query_set.clone(),
raw_encoder,
parent_state.tracker,
parent_state.texture_memory_actions,
&mut pending_query_resets,
&mut pending_discard_init_fixups,
parent_state.snatch_guard,
parent_state.query_set_writes,
multiview_mask,
)
.map_pass_err(pass_scope)?;
let indices = &device.tracker_indices;
parent_state
.tracker
.buffers
.set_size(indices.buffers.size());
parent_state
.tracker
.textures
.set_size(indices.textures.size());
letmut debug_scope_depth = 0;
letmut state = State {
pipeline_flags: PipelineFlags::empty(),
blend_constant: OptionalState::Unused,
stencil_reference: 0,
pipeline: None,
index: IndexState::default(),
vertex: VertexState::default(),
state.blend_constant = OptionalState::Set; let array = [
color.r as f32,
color.g as f32,
color.b as f32,
color.a as f32,
]; unsafe {
state.pass.base.raw_encoder.set_blend_constants(&array);
}
}
state
.vertex
.limits
.validate_vertex_limit(first_vertex, vertex_count)?;
state
.vertex
.limits
.validate_instance_limit(first_instance, instance_count)?;
if state.pass.base.device.indirect_validation.is_some()
&& family != DrawCommandFamily::DrawMeshTasks
{
state
.pass
.scope
.buffers
.merge_single(&indirect_buffer, wgt::BufferUses::STORAGE_READ_ONLY)?;
if family == DrawCommandFamily::DrawMeshTasks {
validate_mesh_draw_multiview(state)?;
}
let stride = get_src_stride_of_indirect_args(family);
state
.pass
.base
.device
.require_features(wgt::Features::MULTI_DRAW_INDIRECT_COUNT)?;
state
.pass
.base
.device
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
// Recording a render pass. // // The only error that should be returned from these methods is // `EncoderStateError::Ended`, when the pass has already ended and an immediate // validation error is raised. // // All other errors should be stored in the pass for later reporting when // `CommandEncoder.finish()` is called. // // The `pass_try!` macro should be used to handle errors appropriately. Note // that the `pass_try!` and `pass_base!` macros may return early from the // function that invokes them, like the `?` operator. impl Global { pubfn render_pass_set_bind_group(
&self,
pass: &mut RenderPass,
index: u32,
bind_group_id: Option<id::BindGroupId>,
offsets: &[DynamicOffset],
) -> Result<(), PassStateError> { let scope = PassErrorScope::SetBindGroup;
// This statement will return an error if the pass is ended. It's // important the error check comes before the early-out for // `set_and_check_redundant`. let base = pass_base!(pass, scope);
let redundant = pass.current_pipeline.set_and_check_redundant(pipeline_id);
// This statement will return an error if the pass is ended. // Its important the error check comes before the early-out for `redundant`. let base = pass_base!(pass, scope);
if redundant { return Ok(());
}
let hub = &self.hub; let pipeline = pass_try!(base, scope, hub.render_pipelines.get(pipeline_id).get());
pub(crate) constfn get_src_stride_of_indirect_args(family: DrawCommandFamily) -> u64 { match family {
DrawCommandFamily::Draw => size_of::<wgt::DrawIndirectArgs>() as u64,
DrawCommandFamily::DrawIndexed => size_of::<wgt::DrawIndexedIndirectArgs>() as u64,
DrawCommandFamily::DrawMeshTasks => size_of::<wgt::DispatchIndirectArgs>() as u64,
}
}
pub(crate) constfn get_dst_stride_of_indirect_args(
backend: wgt::Backend,
family: DrawCommandFamily,
) -> u64 { // space for D3D12 special constants let extra = if matches!(backend, wgt::Backend::Dx12) { 3 * size_of::<u32>() as u64
} else { 0
};
extra + get_src_stride_of_indirect_args(family)
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.82 Sekunden
(vorverarbeitet am 2026-10-01)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.