fn store_hal_ops(store: StoreOp) -> hal::AttachmentOps { match store {
StoreOp::Store => hal::AttachmentOps::STORE,
StoreOp::Discard => hal::AttachmentOps::empty(),
}
}
/// Describes an individual channel within a render pass, such as color, depth, or stencil. #[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 a color attachment to a render pass. #[repr(C)] #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pubstruct RenderPassColorAttachment { /// The view to use as an attachment. pub view: id::TextureViewId, /// The view that will receive the resolved output if multisampling is used. pub resolve_target: Option<id::TextureViewId>, /// 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,
}
/// Describes a color attachment to a render pass. #[derive(Debug)] struct ArcRenderPassColorAttachment { /// The view to use as an attachment. pub view: Arc<TextureView>, /// The view that will receive the resolved output if multisampling is used. pub resolve_target: Option<Arc<TextureView>>, /// 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,
} impl ArcRenderPassColorAttachment { fn hal_ops(&self) -> hal::AttachmentOps {
load_hal_ops(self.load_op) | store_hal_ops(self.store_op)
}
/// Describes a depth/stencil attachment to a render pass. #[repr(C)] #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pubstruct RenderPassDepthStencilAttachment { /// The view to use as an attachment. pub view: id::TextureViewId, /// 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. #[derive(Debug)] pubstruct ArcRenderPassDepthStencilAttachment { /// The view to use as an attachment. pub view: Arc<TextureView>, /// 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>, /// 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>,
}
/// 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<ArcRenderPassDepthStencilAttachment>, /// 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>>,
}
pubstruct RenderPass { /// All pass data & records is stored here. /// /// If this is `None`, the pass is in the 'ended' state and can no longer be used. /// Any attempt to record more commands will result in a validation error.
base: Option<BasePass<ArcRenderCommand>>,
/// Parent command buffer that this pass records commands into. /// /// If it is none, this pass is invalid and any operation on it will return an error.
parent: Option<Arc<CommandBuffer>>,
impl RenderPass { /// If the parent command buffer is invalid, the returned pass will be invalid. fn new(parent: Option<Arc<CommandBuffer>>, desc: ArcRenderPassDescriptor) -> Self { let ArcRenderPassDescriptor {
label,
timestamp_writes,
color_attachments,
depth_stencil_attachment,
occlusion_query_set,
} = desc;
#[derive(Debug, Default)] struct VertexState {
inputs: ArrayVec<VertexBufferState, { hal::MAX_VERTEX_BUFFERS }>, /// Length of the shortest vertex rate vertex buffer
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
instance_limit: u64, /// Buffer slot which the shortest instance rate vertex buffer is bound to
instance_limit_slot: u32,
}
impl VertexState { fn update_limits(&mutself) { // 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. self.vertex_limit = u32::MAX as u64; self.instance_limit = u32::MAX as u64; for (idx, vbs) inself.inputs.iter().enumerate() { if !vbs.bound { continue;
}
let limit = if vbs.total_size < vbs.step.last_stride { // The buffer cannot fit the last vertex. 0
} else { if vbs.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.
(vbs.total_size - vbs.step.last_stride) / vbs.step.stride + 1
};
match vbs.step.mode {
VertexStepMode::Vertex => { if limit < self.vertex_limit { self.vertex_limit = limit; self.vertex_limit_slot = idx as _;
}
}
VertexStepMode::Instance => { if limit < self.instance_limit { self.instance_limit = limit; self.instance_limit_slot = idx as _;
}
}
}
}
}
// Determine how many vertex buffers have already been bound let vertex_buffer_count = self.vertex.inputs.iter().take_while(|v| v.bound).count() as u32; // Compare with the needed quantity if vertex_buffer_count < pipeline.vertex_steps.len() as u32 { return Err(DrawError::MissingVertexBuffer {
pipeline: pipeline.error_ident(),
index: vertex_buffer_count,
});
}
if indexed { // Pipeline expects an index buffer iflet Some(pipeline_index_format) = pipeline.strip_index_format { // We have a buffer bound let buffer_index_format = self
.index
.buffer_format
.ok_or(DrawError::MissingIndexBuffer)?;
// The buffers are different formats if pipeline_index_format != buffer_index_format { return Err(DrawError::UnmatchedIndexFormats {
pipeline: pipeline.error_ident(),
pipeline_format: pipeline_index_format,
buffer_format: buffer_index_format,
});
}
}
}
Ok(())
} else {
Err(DrawError::MissingPipeline)
}
}
/// Reset the `RenderBundle`-related states. fn reset_bundle(&mutself) { self.binder.reset(); self.pipeline = None; self.index.reset(); self.vertex.reset();
}
}
/// 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 },
}
#[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("Read-only attachment with load")]
ReadOnlyWithLoad, #[error("Read-only attachment with store")]
ReadOnlyWithStore, #[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 encountered when performing a render pass. #[derive(Clone, Debug, Error)] pubenum RenderPassErrorInner { #[error(transparent)]
Device(DeviceError), #[error(transparent)]
ColorAttachment(#[from] ColorAttachmentError), #[error(transparent)]
Encoder(#[from] CommandEncoderError), #[error("Parent encoder is invalid")]
InvalidParentEncoder, #[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("Setting `values_offset` to be `None` is only for internal use in render bundles")]
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 uses bytes {offset}..{end_offset} using count {count} which overruns indirect buffer of size {buffer_size}")]
IndirectBufferOverrun {
count: u32,
offset: u64,
end_offset: u64,
buffer_size: u64,
}, #[error("Indirect draw uses bytes {begin_count_offset}..{end_count_offset} which overruns indirect buffer of size {count_buffer_size}")]
IndirectCountBufferOverrun {
begin_count_offset: u64,
end_count_offset: u64,
count_buffer_size: u64,
}, #[error("Cannot pop debug group, because number of pushed debug groups is zero")]
InvalidPopDebugGroup, #[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("Push constant offset must be aligned to 4 bytes")]
PushConstantOffsetAlignment, #[error("Push constant size must be aligned to 4 bytes")]
PushConstantSizeAlignment, #[error("Ran out of push constant space. Don't set 4gb of push constants per ComputePass.")]
PushConstantOutOfMemory, #[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("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),
}
impl<'d> RenderPassInfo<'d> { 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 if this_multiview.is_some() {
device.require_features(wgt::Features::MULTIVIEW)?;
}
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,
&mut 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,
&mut 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 extent = extent.ok_or(RenderPassErrorInner::MissingAttachments)?; let multiview = detected_multiview.expect("Multiview was not detected, no attachments");
let hal_desc = hal::RenderPassDescriptor {
label: hal_label,
extent,
sample_count,
color_attachments: &color_attachments_hal,
depth_stencil_attachment: depth_stencil,
multiview,
timestamp_writes: timestamp_writes_hal,
occlusion_query_set: occlusion_query_set_hal,
}; unsafe {
encoder.raw.begin_render_pass(&hal_desc);
};
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.into_iter().flatten() {
trackers.views.insert_single(at.view.clone()); iflet Some(resolve_target) = at.resolve_target {
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 { self.usage_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::STORE, // clear depth
hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
)
} else {
(
hal::AttachmentOps::LOAD | hal::AttachmentOps::STORE, // unchanged stencil
hal::AttachmentOps::STORE, // clear depth
)
}; let desc = hal::RenderPassDescriptor::<'_, _, dyn hal::DynTextureView> {
label: Some("(wgpu internal) Zero init discarded depth/stencil aspect"),
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: hal::TextureUses::DEPTH_STENCIL_WRITE,
},
depth_ops,
stencil_ops,
clear_value: (0.0, 0),
}),
multiview: self.multiview,
timestamp_writes: None,
occlusion_query_set: None,
}; unsafe {
raw.begin_render_pass(&desc);
raw.end_render_pass();
}
}
impl Global { /// Creates a render pass. /// /// If creation fails, an invalid pass is returned. /// Any operation on an invalid pass will return an error. /// /// If successful, puts the encoder into the [`Locked`] state. /// /// [`Locked`]: crate::command::CommandEncoderStatus::Locked pubfn command_encoder_create_render_pass(
&self,
encoder_id: id::CommandEncoderId,
desc: &RenderPassDescriptor<'_>,
) -> (RenderPass, Option<CommandEncoderError>) { fn fill_arc_desc(
hub: &crate::hub::Hub,
desc: &RenderPassDescriptor<'_>,
arc_desc: &mut ArcRenderPassDescriptor,
device: &Device,
) -> Result<(), CommandEncoderError> { let query_sets = hub.query_sets.read(); let texture_views = hub.texture_views.read();
let max_color_attachments = device.limits.max_color_attachments as usize; if desc.color_attachments.len() > max_color_attachments { return Err(CommandEncoderError::InvalidColorAttachment(
ColorAttachmentError::TooMany {
given: desc.color_attachments.len(),
limit: max_color_attachments,
},
));
}
for color_attachment in desc.color_attachments.iter() { iflet Some(RenderPassColorAttachment {
view: view_id,
resolve_target,
load_op,
store_op,
}) = color_attachment
{ let view = texture_views.get(*view_id).get()?;
view.same_device(device)?;
let resolve_target = iflet Some(resolve_target_id) = resolve_target { let rt_arc = texture_views.get(*resolve_target_id).get()?;
rt_arc.same_device(device)?;
let format = view.desc.format; if !format.is_depth_stencil_format() { return Err(CommandEncoderError::InvalidAttachment(AttachmentError::InvalidDepthStencilAttachmentFormat(
view.desc.format,
)));
}
Some(ArcRenderPassDepthStencilAttachment {
view,
depth: if format.has_depth_aspect() {
depth_stencil_attachment.depth.resolve(|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 {
ResolvedPassChannel::ReadOnly
},
stencil: if format.has_stencil_aspect() {
depth_stencil_attachment.stencil.resolve(|clear| Ok(clear.unwrap_or_default()))?
} else {
ResolvedPassChannel::ReadOnly
},
})
} else {
None
};
let err = fill_arc_desc(hub, desc, &mut arc_desc, &cmd_buf.device).err();
(RenderPass::new(Some(cmd_buf), arc_desc), err)
}
/// Note that this differs from [`Self::render_pass_end`], it will /// create a new pass, replay the commands and end the pass. #[doc(hidden)] #[cfg(any(feature = "serde", feature = "replay"))] pubfn render_pass_end_with_unresolved_commands(
&self,
encoder_id: id::CommandEncoderId,
base: BasePass<super::RenderCommand>,
color_attachments: &[Option<RenderPassColorAttachment>],
depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
timestamp_writes: Option<&PassTimestampWrites>,
occlusion_query_set: Option<id::QuerySetId>,
) -> Result<(), RenderPassError> { let pass_scope = PassErrorScope::Pass;
#[cfg(feature = "trace")]
{ let cmd_buf = self
.hub
.command_buffers
.get(encoder_id.into_command_buffer_id()); letmut cmd_buf_data = cmd_buf.data.lock(); let cmd_buf_data = cmd_buf_data.get_inner().map_pass_err(pass_scope)?;
let device = &cmd_buf.device; let snatch_guard = &device.snatchable_lock.read();
let (scope, pending_discard_init_fixups) = {
device.check_is_valid().map_pass_err(pass_scope)?;
let encoder = &mut cmd_buf_data.encoder; let tracker = &mut cmd_buf_data.trackers; let buffer_memory_init_actions = &mut cmd_buf_data.buffer_memory_init_actions; let texture_memory_actions = &mut cmd_buf_data.texture_memory_actions; let pending_query_resets = &mut cmd_buf_data.pending_query_resets;
// 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.
encoder.close_if_open().map_pass_err(pass_scope)?;
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),
pass.color_attachments.take(),
pass.depth_stencil_attachment.take(),
pass.timestamp_writes.take(), // Still needed down the line. // TODO(wumpf): by restructuring the code, we could get rid of some of this Arc clone.
pass.occlusion_query_set.clone(),
encoder,
tracker,
texture_memory_actions,
pending_query_resets,
snatch_guard,
)
.map_pass_err(pass_scope)?;
let indices = &device.tracker_indices;
tracker.buffers.set_size(indices.buffers.size());
tracker.textures.set_size(indices.textures.size());
// merge the resource tracker in unsafe {
state.info.usage_scope.merge_bind_group(&bind_group.used)?;
} //Note: stateless trackers are not merged: the lifetime reference // is held to the bind group itself.
state
.buffer_memory_init_actions
.extend(bind_group.used_buffer_ranges.iter().filter_map(|action| {
action
.buffer
.initialization_status
.read()
.check_action(action)
})); for action in bind_group.used_texture_ranges.iter() {
state
.info
.pending_discard_init_fixups
.extend(state.texture_memory_actions.register_init_action(action));
}
let pipeline_layout = state.binder.pipeline_layout.clone(); let entries = state
.binder
.assign_group(index as usize, bind_group, &state.temp_offsets); if !entries.is_empty() && pipeline_layout.is_some() { let pipeline_layout = pipeline_layout.as_ref().unwrap().raw(); for (i, e) in entries.iter().enumerate() { iflet Some(group) = e.group.as_ref() { let raw_bg = group.try_raw(state.snatch_guard)?; unsafe {
state.raw_encoder.set_bind_group(
pipeline_layout,
index + i as u32,
Some(raw_bg),
&e.dynamic_offsets,
);
}
}
}
}
Ok(())
}
if pipeline.flags.contains(PipelineFlags::STENCIL_REFERENCE) { unsafe {
state
.raw_encoder
.set_stencil_reference(state.stencil_reference);
}
}
// Rebind resource if state.binder.pipeline_layout.is_none()
|| !state
.binder
.pipeline_layout
.as_ref()
.unwrap()
.is_equal(&pipeline.layout)
{ let (start_index, entries) = state
.binder
.change_pipeline_layout(&pipeline.layout, &pipeline.late_sized_buffer_groups); if !entries.is_empty() { for (i, e) in entries.iter().enumerate() { iflet Some(group) = e.group.as_ref() { let raw_bg = group.try_raw(state.snatch_guard)?; unsafe {
state.raw_encoder.set_bind_group(
pipeline.layout.raw(),
start_index as u32 + i as u32,
Some(raw_bg),
&e.dynamic_offsets,
);
}
}
}
}
// Clear push constant ranges let non_overlapping = super::bind::compute_nonoverlapping_ranges(&pipeline.layout.push_constant_ranges); for range in non_overlapping { let offset = range.range.start; let size_bytes = range.range.end - offset; super::push_constant_clear(offset, size_bytes, |clear_offset, clear_data| unsafe {
state.raw_encoder.set_push_constants(
pipeline.layout.raw(),
range.stages,
clear_offset,
clear_data,
);
});
}
}
// Initialize each `vertex.inputs[i].step` from // `pipeline.vertex_steps[i]`. Enlarge `vertex.inputs` // as necessary to accommodate all slots in the // pipeline. If `vertex.inputs` is longer, fill the // extra entries with default `VertexStep`s. while state.vertex.inputs.len() < pipeline.vertex_steps.len() {
state.vertex.inputs.push(VertexBufferState::EMPTY);
}
// This is worse as a `zip`, but it's close. letmut steps = pipeline.vertex_steps.iter(); for input in state.vertex.inputs.iter_mut() {
input.step = steps.next().cloned().unwrap_or_default();
}
state
.info
.usage_scope
.buffers
.merge_single(&buffer, hal::BufferUses::VERTEX)?;
buffer.same_device_as(cmd_buf.as_ref())?;
let max_vertex_buffers = state.device.limits.max_vertex_buffers; if slot >= max_vertex_buffers { return Err(RenderCommandError::VertexBufferIndexOutOfRange {
index: slot,
max: max_vertex_buffers,
}
.into());
}
buffer.check_usage(BufferUsages::VERTEX)?; let buf_raw = buffer.try_raw(state.snatch_guard)?;
let empty_slots = (1 + slot as usize).saturating_sub(state.vertex.inputs.len());
state
.vertex
.inputs
.extend(iter::repeat(VertexBufferState::EMPTY).take(empty_slots)); let vertex_state = &mut state.vertex.inputs[slot as usize]; //TODO: where are we checking that the offset is in bound?
vertex_state.total_size = match size {
Some(s) => s.get(),
None => buffer.size - offset,
};
vertex_state.bound = true;
state
.buffer_memory_init_actions
.extend(buffer.initialization_status.read().create_action(
&buffer,
offset..(offset + vertex_state.total_size),
MemoryInitKind::NeedsInitializedMemory,
));
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.raw_encoder.set_blend_constants(&array);
}
}
let values_offset = values_offset.ok_or(RenderPassErrorInner::InvalidValuesOffset)?;
let end_offset_bytes = offset + size_bytes; let values_end_offset = (values_offset + size_bytes / wgt::PUSH_CONSTANT_ALIGNMENT) as usize; let data_slice = &push_constant_data[(values_offset as usize)..values_end_offset];
let pipeline_layout = state
.binder
.pipeline_layout
.as_ref()
.ok_or(DrawError::MissingPipeline)?;
let stride = match indexed { false => size_of::<wgt::DrawIndirectArgs>(), true => size_of::<wgt::DrawIndexedIndirectArgs>(),
};
if count != 1 {
state
.device
.require_features(wgt::Features::MULTI_DRAW_INDIRECT)?;
}
state
.device
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
let stride = match indexed { false => size_of::<wgt::DrawIndirectArgs>(), true => size_of::<wgt::DrawIndexedIndirectArgs>(),
} as u64;
state
.device
.require_features(wgt::Features::MULTI_DRAW_INDIRECT_COUNT)?;
state
.device
.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
impl Global { fn resolve_render_pass_buffer_id(
&self,
scope: PassErrorScope,
buffer_id: id::Id<id::markers::Buffer>,
) -> Result<Arc<crate::resource::Buffer>, RenderPassError> { let hub = &self.hub; let buffer = hub.buffers.get(buffer_id).get().map_pass_err(scope)?;
Ok(buffer)
}
fn resolve_render_pass_query_set(
&self,
scope: PassErrorScope,
query_set_id: id::Id<id::markers::QuerySet>,
) -> Result<Arc<QuerySet>, RenderPassError> { let hub = &self.hub; let query_set = hub.query_sets.get(query_set_id).get().map_pass_err(scope)?;
Ok(query_set)
}
pubfn render_pass_set_bind_group(
&self,
pass: &mut RenderPass,
index: u32,
bind_group_id: Option<id::BindGroupId>,
offsets: &[DynamicOffset],
) -> Result<(), RenderPassError> { let scope = PassErrorScope::SetBindGroup; let base = pass
.base
.as_mut()
.ok_or(RenderPassErrorInner::PassEnded)
.map_pass_err(scope)?;
if pass.current_bind_groups.set_and_check_redundant(
bind_group_id,
index,
&mut base.dynamic_offsets,
offsets,
) { // Do redundant early-out **after** checking whether the pass is ended or not. return Ok(());
}
letmut bind_group = None; if bind_group_id.is_some() { let bind_group_id = bind_group_id.unwrap();
let hub = &self.hub; let bg = hub
.bind_groups
.get(bind_group_id)
.get()
.map_pass_err(scope)?;
bind_group = Some(bg);
}
¤ 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.0.87Bemerkung:
(vorverarbeitet am 2026-06-23)
¤
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.