fix(core): Init tracking for pass with multiple depth slice attachments

(cherry picked from commit f0704423c9)
This commit is contained in:
Andy Leiserson committed 2026-09-08 11:35:07 -07:00
1 parent 2f9a1f1780
commit 259cbd0227
5 files changed
+217 -56

No files matched your search

+137
View File
@@ -53,6 +53,7 @@ pub fn all_tests(vec: &mut Vec<GpuTestInitializer>) {
vec.extend([
COPY_BUFFER_TO_TEXTURE_PLANE0_LEAVES_PLANE1_UNINIT_NV12,
COPY_BUFFER_TO_TEXTURE_STENCIL_LEAVES_DEPTH_UNINIT_DEPTH32FLOAT_STENCIL8,
DISCARDING_3D_DEPTH_SLICE_ALONGSIDE_ANOTHER_SLICE_IN_SAME_PASS,
DISCARDING_3D_DEPTH_SLICE_PRESERVES_OTHER_SLICES,
DISCARDING_BOTH_DEPTH_AND_STENCIL_WITH_DIVERGING_LOAD_OPS,
DISCARDING_COLOR_TARGET_AT_NONZERO_MIP_AND_LAYER,
@@ -675,6 +676,51 @@ impl<'ctx> RenderTargetInitCase<'ctx> {
});
}
/// Record a render pass with one color attachment per entry of `targets`, which must all
/// be distinct depth slices of the same mip level of a 3D texture.
fn record_multi_slice_pass(
&self,
encoder: &mut CommandEncoder,
targets: &[(RenderTarget, PassOps)],
) {
let views: Vec<TextureView> = targets
.iter()
.map(|(target, _)| {
self.texture.create_view(&TextureViewDescriptor {
label: None,
format: Some(self.spec.format),
dimension: Some(self.view_dimension),
usage: Some(TextureUsages::RENDER_ATTACHMENT),
aspect: TextureAspect::All,
base_mip_level: target.mip(),
mip_level_count: Some(1),
base_array_layer: 0,
array_layer_count: Some(1),
})
})
.collect();
let attachments: Vec<Option<RenderPassColorAttachment<'_>>> = targets
.iter()
.zip(&views)
.map(|((target, ops), view)| {
Some(RenderPassColorAttachment {
view,
depth_slice: Some(target.subresource_index()),
resolve_target: None,
ops: ops.color,
})
})
.collect();
encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("Render targets under test"),
color_attachments: &attachments,
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
}
fn create_command_encoder(&mut self) {
self.encoder = Some(
self.ctx
@@ -695,6 +741,12 @@ impl<'ctx> RenderTargetInitCase<'ctx> {
self.encoder = Some(encoder);
}
fn multi_slice_pass(&mut self, targets: &[(RenderTarget, PassOps)]) {
let mut encoder = self.encoder.take().unwrap();
self.record_multi_slice_pass(&mut encoder, targets);
self.encoder = Some(encoder);
}
fn copy_texture_to_buffer(&mut self) {
let mut encoder = self.encoder.take().unwrap();
self.readback
@@ -1371,6 +1423,91 @@ static DISCARDING_3D_DEPTH_SLICE_PRESERVES_OTHER_SLICES: GpuTestConfiguration =
}
});
// Distinct depth slices of one 3D mip level do not overlap, so a single render pass may
// attach several of them at once. Those attachments are processed by successive calls to
// [`CommandBufferTextureMemoryActions::register_init_action`]. Global init tracking for 3D
// textures operates per mip level, but pending discards within a single command buffer
// _are_ tracked per depth slice, and it is important that they be matched that way against
// init actions, due to the following case.
//
// A pending discard of a slice is repaired by clearing it ahead of a subsequent operation in
// the same command buffer that needs the mip level initialized, or otherwise at the end of
// the command buffer. Doing that without checking depth slices is correct when the discard
// came from an earlier pass, but not when it came from another attachment to the same
// pass:
//
// - attachment 0: mip 0, depth_slice 0, `LoadOp::Clear` / `StoreOp::Discard`
// - attachment 1: mip 0, depth_slice 1, `LoadOp::Load` / `StoreOp::Store`
//
// Attachment 1 needs mip 0 initialized, so if depth slices were not considered, it would
// repair slice 0's discard. But that clear would be emitted ahead of the pass, so slice 0
// would be left holding the discarded contents with the mip level recorded as initialized.
// The repair has to be deferred to the end of the command buffer instead. We test both
// `Load` and `Clear` for attachment 1 (`other`). Either requires that the whole mip level
// be initialized, because a mip level is the finest granularity the init tracker can record
// (after the command buffer concludes).
//
// Attachment 0 clears to the sentinel value so that slice 0 holds something other than zero
// when the discard takes effect. Under `LoadOp::Load` the pass would write nothing there,
// and a misplaced pre-pass clear to zero would coincidentally match the expected result,
// leaving the test unable to tell whether the discard was correctly tracked.
#[apply(gpu_test!)]
static DISCARDING_3D_DEPTH_SLICE_ALONGSIDE_ANOTHER_SLICE_IN_SAME_PASS: GpuTestConfiguration =
GpuTestConfiguration::new()
.parameters(
TestParameters::default()
// https://github.com/gfx-rs/wgpu/issues/10162
.expect_fail(FailureCase::webgl2())
// https://github.com/gfx-rs/wgpu/issues/9184
.expect_fail(
FailureCase::molten_vk()
.validation_error("VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT"),
),
)
.run_async(|ctx| async move {
let discarded = RenderTarget::Volume {
mip: 0,
depth_slice: 0,
};
let other = RenderTarget::Volume {
mip: 0,
depth_slice: 1,
};
for (other_ops, other_desc) in [
(
PassOps::clear_store(sentinel_for(color_3d_spec().format)),
"clear + store",
),
(PassOps::load_store(), "load + store"),
] {
let mut case = RenderTargetInitCase::new(
&ctx,
color_3d_spec(),
TextureViewDimension::D3,
PreInit::Sentinel,
format!("clear + discard of {discarded} alongside {other_desc} of {other}"),
);
let sentinel = case.sentinel;
case.create_command_encoder();
case.multi_slice_pass(&[
(discarded, PassOps::clear_discard(sentinel)),
(other, other_ops),
]);
case.submit_command_encoder();
case.create_command_encoder();
case.copy_texture_to_buffer();
case.submit_command_encoder();
// Every slice the pass did not discard holds the sentinel: the ones it did not
// touch keep what `PreInit::Sentinel` wrote, and the other attachment either
// cleared its slice to the sentinel or loaded and stored it unchanged.
case.assert_only_target(discarded, Expected::Zero).await;
}
});
// Tests that a full-extent, single-aspect `write_texture` does not cause
// *other* aspects of a multi-aspect texture to be considered initialized.
+57 -44
View File
@@ -62,14 +62,29 @@ impl CommandBufferTextureMemoryActions {
self.discards.push(discard);
}
// Registers a TextureInitTrackerAction.
// Returns previously discarded surface that need to be initialized *immediately* now.
// Only returns a non-empty list if action is MemoryInitKind::NeedsInitializedMemory.
/// Registers a [`TextureInitTrackerAction`].
///
/// Returns previously discarded surfaces that need to be initialized
/// *immediately*. Only returns a non-empty list if `action.kind` is
/// [`MemoryInitKind::NeedsInitializedMemory`]. These surfaces are removed
/// from the pending discard list, so the caller takes on the obligation to
/// clear them (via [`fixup_discarded_surfaces`]).
///
/// `depth_slices` is the range of depth slices that `action` physically
/// accesses, or `None` if the access is to all slices of a 3D texture or
/// to some other texture type. The depth slice information does not flow to
/// the global init tracker, whose granularity is a whole mip level, but it
/// is important in deciding which pending discards have to be repaired
/// ahead of this action, as opposed to at the end of the command buffer.
#[must_use]
pub(crate) fn register_init_action(
&mut self,
action: &TextureInitTrackerAction,
depth_slices: Option<Range<u32>>,
) -> SurfacesInDiscardState {
let is_3d = action.texture.desc.dimension == wgt::TextureDimension::D3;
debug_assert!(depth_slices.is_none() || is_3d);
// Texture subresources from `self.discards` that were discarded earlier in this
// command buffer and which the present `action` requires be initialized. These
// require inline initialization, which will be done by `fixup_discarded_surfaces`.
@@ -95,23 +110,41 @@ impl CommandBufferTextureMemoryActions {
// self.discards is empty!)
let init_actions = &mut self.init_actions;
self.discards.retain(|discarded_surface| {
if discarded_surface.texture.is_equal(&action.texture)
&& discarded_surface.texture.desc.dimension != wgt::TextureDimension::D3
&& action
.range
.layer_range
.contains(&discarded_surface.layer_or_depth_slice)
&& action
if !discarded_surface.texture.is_equal(&action.texture)
|| !action
.range
.mip_range
.contains(&discarded_surface.mip_level)
{
if let MemoryInitKind::NeedsInitializedMemory = action.kind {
immediately_necessary_clears.push(discarded_surface.clone());
return true;
}
// Mark surface as implicitly initialized (this is relevant
// because it might have been uninitialized prior to
// discarding
let overlaps_discard = if is_3d {
// The `layer_range` for a `TextureInitTrackerAction` does not identify
// depth slices, so the caller passed that information separately.
depth_slices
.as_ref()
.is_none_or(|slices| slices.contains(&discarded_surface.layer_or_depth_slice))
} else {
action
.range
.layer_range
.contains(&discarded_surface.layer_or_depth_slice)
};
if !overlaps_discard {
return true;
}
if let MemoryInitKind::NeedsInitializedMemory = action.kind {
immediately_necessary_clears.push(discarded_surface.clone());
// Mark surface as implicitly initialized. This matters for non-3D textures
// where the discarded layer range may differ from the action layer range,
// and may have been uninitialized prior to discarding. For 3D textures,
// init state does not vary per layer, so we either emitted an init action
// above for the whole mip level, or it was already initialized and none
// is necessary.
if !is_3d {
let layer = discarded_surface.layer_or_depth_slice;
init_actions.push(TextureInitTrackerAction {
texture: discarded_surface.texture.clone(),
@@ -123,31 +156,8 @@ impl CommandBufferTextureMemoryActions {
kind: MemoryInitKind::ImplicitlyInitialized,
});
}
false
} else if discarded_surface.texture.is_equal(&action.texture)
&& discarded_surface.texture.desc.dimension == wgt::TextureDimension::D3
&& action
.range
.mip_range
.contains(&discarded_surface.mip_level)
{
if let MemoryInitKind::NeedsInitializedMemory = action.kind {
immediately_necessary_clears.push(discarded_surface.clone());
// Init tracking of 3D textures is for mip levels only (not depth
// slices). If a mip was uninitialized at the start of the
// command buffer, we recorded an init action above. We don't need
// to additionally record `ImplicitlyInitialized` for it here.
// When the actual initialization commands are prepared in
// [`Queue::submit`], `initialize_texture_memory` collects a list of any
// slices remaining in `self.discards` and returns it, and they will be
// reinitialized before the conclusion of the command buffer by
// `initialize_discarded_depth_slices`.
}
false
} else {
true
}
false
});
immediately_necessary_clears
@@ -160,11 +170,14 @@ impl CommandBufferTextureMemoryActions {
texture: &Arc<Texture>,
range: TextureInitRange,
) {
let must_be_empty = self.register_init_action(&TextureInitTrackerAction {
texture: texture.clone(),
range,
kind: MemoryInitKind::ImplicitlyInitialized,
});
let must_be_empty = self.register_init_action(
&TextureInitTrackerAction {
texture: texture.clone(),
range,
kind: MemoryInitKind::ImplicitlyInitialized,
},
None,
);
assert!(must_be_empty.is_empty());
}
}
+1 -1
View File
@@ -161,7 +161,7 @@ pub(super) fn flush_bindings_helper(state: &mut PassState) -> Result<(), Destroy
state
.base
.texture_memory_actions
.register_init_action(action),
.register_init_action(action, None),
);
}
+11 -6
View File
@@ -1162,6 +1162,7 @@ impl RenderPassInfo {
// Note that this is needed for `Load` even if the target has `StoreOp::Discard`.
kind: MemoryInitKind::NeedsInitializedMemory,
},
depth_slice.map(|slice| slice..slice + 1),
));
} else if store_op == StoreOp::Store {
if partial_z {
@@ -1172,6 +1173,7 @@ impl RenderPassInfo {
range: TextureInitRange::from(view),
kind: MemoryInitKind::NeedsInitializedMemory,
},
depth_slice.map(|slice| slice..slice + 1),
));
} else {
// Clear + Store
@@ -1356,11 +1358,14 @@ impl RenderPassInfo {
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.as_ref()),
kind: MemoryInitKind::NeedsInitializedMemory,
}),
texture_memory_actions.register_init_action(
&TextureInitTrackerAction {
texture: view.parent.clone(),
range: TextureInitRange::from(view.as_ref()),
kind: MemoryInitKind::NeedsInitializedMemory,
},
None, // depth/stencil textures are never 3D
),
);
}
@@ -3419,7 +3424,7 @@ fn execute_bundle(
.pass
.base
.texture_memory_actions
.register_init_action(action),
.register_init_action(action, None),
);
}
+11 -5
View File
@@ -669,13 +669,19 @@ fn handle_texture_init(
kind: init_kind,
};
// Record the initialization action. Simultaneously, collect a list of any
// ranges of the texture that were discarded within the current command
// buffer, for immediate initialization. (The analogous case for passes is
// in `fixup_discarded_surfaces`.)
// Record the initialization action. Simultaneously, collect a list of any ranges of the
// texture that were discarded within the current command buffer, for immediate
// initialization. (The analogous case for passes is in `fixup_discarded_surfaces`.)
//
// Depth slices are only relevant to deciding which pending discards (in a command
// buffer with prior render passes) have to be repaired ahead of this copy. Any
// initialization that gets generated covers the whole mip level, because that is the
// granularity of the init tracker.
let accessed_depth_slices = (texture.desc.dimension == wgt::TextureDimension::D3)
.then(|| copy_texture.origin.z..copy_texture.origin.z + copy_size.depth_or_array_layers);
let immediate_inits = state
.texture_memory_actions
.register_init_action(&{ init_action });
.register_init_action(&{ init_action }, accessed_depth_slices);
// In rare cases we may need to insert an init operation immediately onto the command buffer.
if !immediate_inits.is_empty() {