diff --git a/tests/tests/wgpu-gpu/zero_init.rs b/tests/tests/wgpu-gpu/zero_init.rs index 9b6dd9090..22a624e21 100644 --- a/tests/tests/wgpu-gpu/zero_init.rs +++ b/tests/tests/wgpu-gpu/zero_init.rs @@ -9,8 +9,9 @@ use core::num::NonZeroU64; use wgpu::util::DeviceExt as _; use wgpu::*; use wgpu_test::{ - apply, gpu_test, image::ReadbackBuffers, FailureCase, GpuTestConfiguration, GpuTestInitializer, - TestParameters, TestingContext, + apply, gpu_test, + image::{ReadbackBuffers, ReadbackData}, + FailureCase, GpuTestConfiguration, GpuTestInitializer, TestParameters, TestingContext, }; /// A way to write data into a texture. @@ -52,10 +53,22 @@ pub fn all_tests(vec: &mut Vec) { vec.extend([ COPY_BUFFER_TO_TEXTURE_PLANE0_LEAVES_PLANE1_UNINIT_NV12, COPY_BUFFER_TO_TEXTURE_STENCIL_LEAVES_DEPTH_UNINIT_DEPTH32FLOAT_STENCIL8, - DISCARDING_COLOR_TARGET_RESETS_TEXTURE_INIT_STATE_CHECK_VISIBLE_ON_COPY_AFTER_SUBMIT, - DISCARDING_COLOR_TARGET_RESETS_TEXTURE_INIT_STATE_CHECK_VISIBLE_ON_COPY_IN_SAME_ENCODER, - DISCARDING_DEPTH_TARGET_RESETS_TEXTURE_INIT_STATE_CHECK_VISIBLE_ON_COPY_IN_SAME_ENCODER, + DISCARDING_3D_DEPTH_SLICE_PRESERVES_OTHER_SLICES, + DISCARDING_BOTH_DEPTH_AND_STENCIL_WITH_DIVERGING_LOAD_OPS, + DISCARDING_COLOR_TARGET_AT_NONZERO_MIP_AND_LAYER, + DISCARDING_COLOR_TARGET_RESETS_TEXTURE_INIT_STATE, + DISCARDING_COLOR_TARGET_THEN_LOADING_IT_IN_SAME_ENCODER, + DISCARDING_DEPTH_TARGET_AT_NONZERO_MIP_AND_LAYER, + DISCARDING_DEPTH_TARGET_AT_NONZERO_MIP_AND_LAYER_DEPTH32FLOAT_STENCIL8, + DISCARDING_DEPTH_TARGET_RESETS_TEXTURE_INIT_STATE, + DISCARDING_DEPTH_TARGET_RESETS_TEXTURE_INIT_STATE_DEPTH32FLOAT_STENCIL8, + DISCARDING_EITHER_DEPTH_OR_STENCIL_ASPECT_AT_NONZERO_MIP_AND_LAYER, DISCARDING_EITHER_DEPTH_OR_STENCIL_ASPECT_TEST, + RENDER_PASS_LOAD_INITS_WHOLE_3D_MIP, + RENDER_PASS_STORE_INITS_ONLY_TARGET_3D_MIP, + RENDER_PASS_STORE_INITS_ONLY_TARGET_COLOR_SUBRESOURCE, + RENDER_PASS_STORE_INITS_ONLY_TARGET_DEPTH_STENCIL_SUBRESOURCE, + RENDER_PASS_STORE_TO_3D_DEPTH_SLICE_INITS_OTHER_SLICES, WRITE_TEXTURE_PLANE0_LEAVES_PLANE1_UNINIT_NV12, WRITE_TEXTURE_PLANE0_LEAVES_PLANE1_UNINIT_P010, WRITE_TEXTURE_PLANE1_LEAVES_PLANE0_UNINIT_NV12, @@ -76,64 +89,47 @@ pub fn all_tests(vec: &mut Vec) { ]); } -// Checks if discarding a color target resets its init state, causing a zero read of this texture when copied in after submit of the encoder. +// Checks if discarding a color target resets its init state, causing a zero read of this texture +// when copied in the same encoder as the discarding pass, or in a later one. #[apply(gpu_test!)] -static DISCARDING_COLOR_TARGET_RESETS_TEXTURE_INIT_STATE_CHECK_VISIBLE_ON_COPY_AFTER_SUBMIT: - GpuTestConfiguration = GpuTestConfiguration::new() - .parameters(TestParameters::default().expect_fail(FailureCase::webgl2())) - .run_async(|mut ctx| async move { - let mut case = DiscardTestCase::new(&mut ctx, TextureFormat::Rgba8UnormSrgb); - case.create_command_encoder(); - case.discard(); - case.submit_command_encoder(); - - case.create_command_encoder(); - case.copy_texture_to_buffer(); - case.submit_command_encoder(); - - case.assert_buffers_are_zero().await; - }); +static DISCARDING_COLOR_TARGET_RESETS_TEXTURE_INIT_STATE: GpuTestConfiguration = + GpuTestConfiguration::new() + // https://github.com/gfx-rs/wgpu/issues/10162 + .parameters(TestParameters::default().expect_fail(FailureCase::webgl2())) + .run_async(|ctx| async move { + check_discard_resets_whole_texture(&ctx, TextureFormat::Rgba8UnormSrgb).await; + }); +// As above, for depth/stencil targets. #[apply(gpu_test!)] -static DISCARDING_COLOR_TARGET_RESETS_TEXTURE_INIT_STATE_CHECK_VISIBLE_ON_COPY_IN_SAME_ENCODER: - GpuTestConfiguration = GpuTestConfiguration::new() - .parameters(TestParameters::default().expect_fail(FailureCase::webgl2())) - .run_async(|mut ctx| async move { - let mut case = DiscardTestCase::new(&mut ctx, TextureFormat::Rgba8UnormSrgb); - case.create_command_encoder(); - case.discard(); - case.copy_texture_to_buffer(); - case.submit_command_encoder(); - - case.assert_buffers_are_zero().await; - }); +static DISCARDING_DEPTH_TARGET_RESETS_TEXTURE_INIT_STATE: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .downlevel_flags( + DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES + | DownlevelFlags::COMPUTE_SHADERS, + ) + .limits(Limits::downlevel_defaults()), + ) + .run_async(|ctx| async move { + for &format in CORE_DEPTH_STENCIL_FORMATS { + check_discard_resets_whole_texture(&ctx, format).await; + } + }); +// As above, for the depth/stencil format that is behind an optional feature. #[apply(gpu_test!)] -static DISCARDING_DEPTH_TARGET_RESETS_TEXTURE_INIT_STATE_CHECK_VISIBLE_ON_COPY_IN_SAME_ENCODER: +static DISCARDING_DEPTH_TARGET_RESETS_TEXTURE_INIT_STATE_DEPTH32FLOAT_STENCIL8: GpuTestConfiguration = GpuTestConfiguration::new() .parameters( TestParameters::default() - .downlevel_flags( - DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES | DownlevelFlags::COMPUTE_SHADERS, - ) + .features(Features::DEPTH32FLOAT_STENCIL8) + .downlevel_flags(DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES) .limits(Limits::downlevel_defaults()), ) - .run_async(|mut ctx| async move { - for format in [ - TextureFormat::Stencil8, - TextureFormat::Depth16Unorm, - TextureFormat::Depth24Plus, - TextureFormat::Depth24PlusStencil8, - TextureFormat::Depth32Float, - ] { - let mut case = DiscardTestCase::new(&mut ctx, format); - case.create_command_encoder(); - case.discard(); - case.copy_texture_to_buffer(); - case.submit_command_encoder(); - - case.assert_buffers_are_zero().await; - } + .run_async(|ctx| async move { + check_discard_resets_whole_texture(&ctx, TextureFormat::Depth32FloatStencil8).await; }); #[apply(gpu_test!)] @@ -147,21 +143,21 @@ static DISCARDING_EITHER_DEPTH_OR_STENCIL_ASPECT_TEST: GpuTestConfiguration = ) .limits(Limits::downlevel_defaults()), ) - .run_async(|mut ctx| async move { - for format in [ - TextureFormat::Stencil8, - TextureFormat::Depth16Unorm, - TextureFormat::Depth24Plus, - TextureFormat::Depth24PlusStencil8, - TextureFormat::Depth32Float, - ] { - let mut case = DiscardTestCase::new(&mut ctx, format); + .run_async(|ctx| async move { + for &format in CORE_DEPTH_STENCIL_FORMATS { + let mut case = discard_case(&ctx, format, false); case.create_command_encoder(); - case.discard_depth(); + case.pass( + RenderTarget::Array { mip: 0, layer: 0 }, + PassOps::discard_depth_keep_stencil(), + ); case.submit_command_encoder(); case.create_command_encoder(); - case.discard_stencil(); + case.pass( + RenderTarget::Array { mip: 0, layer: 0 }, + PassOps::discard_stencil_keep_depth(), + ); case.submit_command_encoder(); case.create_command_encoder(); @@ -172,112 +168,514 @@ static DISCARDING_EITHER_DEPTH_OR_STENCIL_ASPECT_TEST: GpuTestConfiguration = } }); -struct DiscardTestCase<'ctx> { - ctx: &'ctx mut TestingContext, +/// A single-mip, single-layer render target, as used by the +/// `DISCARDING_*_RESETS_TEXTURE_INIT_STATE_*` tests. +fn discard_case( + ctx: &TestingContext, format: TextureFormat, - texture: Texture, - readback_buffers: ReadbackBuffers, - encoder: Option, + readback_in_same_encoder: bool, +) -> RenderTargetInitCase<'_> { + RenderTargetInitCase::new( + ctx, + TextureSpec { + format, + dimension: TextureDimension::D2, + size: Extent3d { + width: SUBRESOURCE_WIDTH, + height: SUBRESOURCE_HEIGHT, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + }, + TextureViewDimension::D2, + PreInit::Sentinel, + format!( + "{format:?} target discard{}", + if readback_in_same_encoder { + ", read back in the same encoder" + } else { + "" + } + ), + ) } -impl<'ctx> DiscardTestCase<'ctx> { - pub fn new(ctx: &'ctx mut TestingContext, format: TextureFormat) -> Self { - let extra_usages = match format { +/// Discards the only subresource of a `format` texture and checks that the whole texture +/// reads back as zero, both when the readback copy is in the same encoder as the discarding +/// pass and when it is in a later one. +async fn check_discard_resets_whole_texture(ctx: &TestingContext, format: TextureFormat) { + for readback_in_same_encoder in [false, true] { + let mut case = discard_case(ctx, format, readback_in_same_encoder); + case.create_command_encoder(); + case.pass( + RenderTarget::Array { mip: 0, layer: 0 }, + PassOps::load_discard(), + ); + if !readback_in_same_encoder { + case.submit_command_encoder(); + case.create_command_encoder(); + } + case.copy_texture_to_buffer(); + case.submit_command_encoder(); + + case.assert_buffers_are_zero().await; + } +} + +/// The texture used by a render-target initialization test case. +#[derive(Clone, Copy)] +struct TextureSpec { + format: TextureFormat, + /// Either `D2` or `D3`. + dimension: TextureDimension, + size: Extent3d, + mip_level_count: u32, +} + +impl TextureSpec { + fn mip_size(&self, mip_level: u32) -> Extent3d { + self.size.mip_level_size(mip_level, self.dimension) + } + + /// Number of array layers (`D2`) or depth slices (`D3`) at `mip_level`. + fn subresources_at(&self, mip_level: u32) -> u32 { + self.mip_size(mip_level).depth_or_array_layers + } + + /// The aspects whose exact contents are checked. [`ReadbackBuffers`] reads a combined + /// depth/stencil format into one buffer per aspect, and both of them are checked. + fn readback_aspects(&self) -> &'static [TextureAspect] { + match self.format { + TextureFormat::Depth24PlusStencil8 | TextureFormat::Depth32FloatStencil8 => { + &[TextureAspect::DepthOnly, TextureAspect::StencilOnly] + } + TextureFormat::Depth24Plus => &[TextureAspect::DepthOnly], + _ => &[TextureAspect::All], + } + } + + fn texel_size(&self, aspect: TextureAspect) -> u32 { + match (self.format, aspect) { + // Read back by a compute shader, which writes one `f32` per texel. + ( + TextureFormat::Depth24Plus | TextureFormat::Depth24PlusStencil8, + TextureAspect::DepthOnly, + ) => 4, + _ => self + .format + .block_copy_size(Some(aspect)) + .expect("aspect is not directly readable"), + } + } + + /// Row stride of a tightly packed image of `mip_level`, for `write_texture`, which + /// imposes no row alignment requirement. Only used for the single-aspect color formats. + fn bytes_per_row(&self, mip_level: u32) -> u32 { + self.mip_size(mip_level).width * self.texel_size(TextureAspect::All) + } + + fn create(&self, ctx: &TestingContext) -> Texture { + // `ReadbackBuffers` reads the depth aspect of these formats with a compute shader. + let extra_usages = match self.format { TextureFormat::Depth24Plus | TextureFormat::Depth24PlusStencil8 => { TextureUsages::TEXTURE_BINDING } _ => TextureUsages::empty(), }; - let texture = ctx.device.create_texture(&TextureDescriptor { + assert!(!self.format.is_compressed()); + + ctx.device.create_texture(&TextureDescriptor { label: Some("RenderTarget"), - size: Extent3d { - width: COPY_BYTES_PER_ROW_ALIGNMENT, - height: COPY_BYTES_PER_ROW_ALIGNMENT, - depth_or_array_layers: 1, - }, - mip_level_count: 1, + size: self.size, + mip_level_count: self.mip_level_count, sample_count: 1, - dimension: TextureDimension::D2, - format, + dimension: self.dimension, + format: self.format, usage: TextureUsages::COPY_DST | TextureUsages::COPY_SRC | TextureUsages::RENDER_ATTACHMENT | extra_usages, view_formats: &[], - }); + }) + } +} - // Clear using a write_texture operation. We could also clear using a render_pass clear. - // However, when making this test intentionally fail (by breaking wgpu impl), it shows that at least on the tested Vulkan driver, - // the later following discard pass in the test (i.e. internally vk::AttachmentStoreOp::DONT_CARE) will yield different depending on the operation we take here: - // * clearing white -> discard will cause it to become black! - // * clearing red -> discard will keep it red - // * write_texture -> discard will keep buffer - // This behavior is curious, but does not violate any spec - it is wgpu's job to pass this test no matter what a render target discard does. +/// The single subresource that the render pass under test targets. +#[derive(Clone, Copy)] +enum RenderTarget { + /// A (mip level, array layer) of a 2D texture. + Array { mip: u32, layer: u32 }, + /// A (mip level, depth slice) of a 3D texture. + Volume { mip: u32, depth_slice: u32 }, +} - // ... but that said, for depth/stencil textures we need to do a clear. - if format.is_depth_stencil_format() { - let mut encoder = ctx - .device - .create_command_encoder(&CommandEncoderDescriptor::default()); - encoder.begin_render_pass(&RenderPassDescriptor { - label: Some("Depth/Stencil setup"), - color_attachments: &[], - depth_stencil_attachment: Some(RenderPassDepthStencilAttachment { - view: &texture.create_view(&TextureViewDescriptor::default()), - depth_ops: format.has_depth_aspect().then_some(Operations { - load: LoadOp::Clear(1.0), - store: StoreOp::Store, - }), - stencil_ops: format.has_stencil_aspect().then_some(Operations { - load: LoadOp::Clear(0xFFFFFFFF), - store: StoreOp::Store, - }), - }), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - ctx.queue.submit([encoder.finish()]); - } else { - let block_size = format.block_copy_size(None).unwrap(); - let bytes_per_row = texture.width() * block_size; - - // Size for tests is chosen so that we don't need to care about buffer alignments. - assert!(!format.is_compressed()); - assert_eq!(bytes_per_row % COPY_BYTES_PER_ROW_ALIGNMENT, 0); - - let buffer_size = texture.height() * bytes_per_row; - let data = vec![255; buffer_size as usize]; - ctx.queue.write_texture( - TexelCopyTextureInfo { - texture: &texture, - mip_level: 0, - origin: Origin3d { x: 0, y: 0, z: 0 }, - aspect: TextureAspect::All, - }, - &data, - TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(bytes_per_row), - rows_per_image: None, - }, - texture.size(), - ); - } - - let readback_buffers = ReadbackBuffers::new(&ctx.device, &texture); - - Self { - ctx, - format, - texture, - readback_buffers, - encoder: None, +impl RenderTarget { + fn mip(&self) -> u32 { + match *self { + Self::Array { mip, .. } | Self::Volume { mip, .. } => mip, } } - pub fn create_command_encoder(&mut self) { + /// Index of this target within the readback of its mip level. + fn subresource_index(&self) -> u32 { + match *self { + Self::Array { layer, .. } => layer, + Self::Volume { depth_slice, .. } => depth_slice, + } + } +} + +impl core::fmt::Display for RenderTarget { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match *self { + Self::Array { mip, layer } => write!(f, "mip {mip}, layer {layer}"), + Self::Volume { mip, depth_slice } => write!(f, "mip {mip}, slice {depth_slice}"), + } + } +} + +/// Operations for the render pass under test. Depth and stencil are kept separate so that +/// passes with diverging depth/stencil operations can be constructed. +#[derive(Clone, Copy)] +struct PassOps { + color: Operations, + depth: Operations, + stencil: Operations, +} + +impl PassOps { + /// Write the sentinel value into the target. + fn clear_store(sentinel: Sentinel) -> Self { + Self { + color: Operations { + load: LoadOp::Clear(sentinel.color), + store: StoreOp::Store, + }, + depth: Operations { + load: LoadOp::Clear(sentinel.depth), + store: StoreOp::Store, + }, + stencil: Operations { + load: LoadOp::Clear(sentinel.stencil), + store: StoreOp::Store, + }, + } + } + + /// Clear the target to the sentinel value, then discard it. + fn clear_discard(sentinel: Sentinel) -> Self { + let mut ops = Self::clear_store(sentinel); + ops.color.store = StoreOp::Discard; + ops.depth.store = StoreOp::Discard; + ops.stencil.store = StoreOp::Discard; + ops + } + + fn load_store() -> Self { + Self { + color: Operations { + load: LoadOp::Load, + store: StoreOp::Store, + }, + depth: Operations { + load: LoadOp::Load, + store: StoreOp::Store, + }, + stencil: Operations { + load: LoadOp::Load, + store: StoreOp::Store, + }, + } + } + + fn load_discard() -> Self { + let mut ops = Self::load_store(); + ops.color.store = StoreOp::Discard; + ops.depth.store = StoreOp::Discard; + ops.stencil.store = StoreOp::Discard; + ops + } + + /// Discard the depth aspect while storing a zeroed stencil aspect. + fn discard_depth_keep_stencil() -> Self { + let mut ops = Self::load_discard(); + ops.stencil = Operations { + load: LoadOp::Clear(0), + store: StoreOp::Store, + }; + ops + } + + /// Discard the stencil aspect while storing a zeroed depth aspect. + fn discard_stencil_keep_depth() -> Self { + let mut ops = Self::load_discard(); + ops.depth = Operations { + load: LoadOp::Clear(0.0), + store: StoreOp::Store, + }; + ops + } + + /// Discard both aspects, loading only one of them and clearing the other to zero, so + /// that the load operations diverge while the store operations match. + fn discard_both_with_diverging_load(load_depth: bool) -> Self { + let mut ops = Self::load_discard(); + if load_depth { + ops.stencil.load = LoadOp::Clear(0); + } else { + ops.depth.load = LoadOp::Clear(0.0); + } + ops + } +} + +/// A non-zero value written into a render target, and the bytes it must read back as. +#[derive(Clone, Copy)] +struct Sentinel { + color: Color, + depth: f32, + stencil: u32, + /// Bytes that the color aspect, or the depth aspect of a depth/stencil format, must read + /// back as. + texel: [u8; 4], + texel_size: usize, + /// Byte that the stencil aspect must read back as, for a format that has one that is + /// read separately. + stencil_texel: [u8; 1], +} + +impl Sentinel { + /// Bytes that one texel of `aspect` must read back as. + fn texel(&self, aspect: TextureAspect) -> &[u8] { + match aspect { + TextureAspect::StencilOnly => &self.stencil_texel, + _ => &self.texel[..self.texel_size], + } + } +} + +/// Clear values are chosen to be exactly representable in the target format, and non-zero, +/// so that a zero-filled subresource is distinguishable from the sentinel. +/// +/// Most are also distinct from the byte that [`ReadbackBuffers`] poisons its buffers with, so +/// that a readback that never happened is distinguishable too. [`TextureFormat::Rgba8UnormSrgb`] +/// is the exception: 1.0 is the only non-zero value that the linear to sRGB clear value +/// conversion is guaranteed to reproduce exactly, and it is all-ones, like the poison byte. +/// That is harmless, because the tests that use the format only assert that the texture reads +/// back as zero. +fn sentinel_for(format: TextureFormat) -> Sentinel { + // 0.75 * 65535 = 49151.25 is far enough from a rounding boundary that any + // implementation produces 49151 (0xBFFF) for `Depth16Unorm`. + let mut depth = 0.75; + let stencil = 0xAB; + + let (color, texel, texel_size) = match format { + // Integer clear values are not subject to any conversion. + TextureFormat::Rgba8Uint => ( + Color { + r: f64::from(0x11_u8), + g: f64::from(0x22_u8), + b: f64::from(0x33_u8), + a: f64::from(0x44_u8), + }, + [0x11, 0x22, 0x33, 0x44], + 4, + ), + TextureFormat::Rgba8UnormSrgb => (Color::WHITE, [0xFF; 4], 4), + TextureFormat::Stencil8 => (Color::TRANSPARENT, [stencil as u8, 0, 0, 0], 1), + TextureFormat::Depth16Unorm => (Color::TRANSPARENT, [0xFF, 0xBF, 0, 0], 2), + TextureFormat::Depth32Float | TextureFormat::Depth32FloatStencil8 => { + (Color::TRANSPARENT, 0.75_f32.to_le_bytes(), 4) + } + TextureFormat::Depth24Plus | TextureFormat::Depth24PlusStencil8 => { + // The depth aspect of these formats is read back as `f32` by a compute shader, + // and a backend may give it either 24 bit unorm or `f32` precision. 1.0 is the + // only non-zero value that both of those represent exactly. + depth = 1.0; + (Color::TRANSPARENT, 1.0_f32.to_le_bytes(), 4) + } + _ => unimplemented!("no sentinel value defined for {format:?}"), + }; + + Sentinel { + color, + depth, + stencil, + texel, + texel_size, + stencil_texel: [stencil as u8], + } +} + +/// Expected contents of a single mip level / array layer / depth slice. +#[derive(Clone, Copy, Debug)] +enum Expected { + Zero, + Sentinel, +} + +/// Contents of the texture before the render pass under test. +#[derive(Clone, Copy)] +enum PreInit { + /// Leave the texture untouched, i.e. uninitialized. + Fresh, + /// Write the sentinel value into every mip level and array layer / depth slice. + Sentinel, +} + +struct RenderTargetInitCase<'ctx> { + ctx: &'ctx TestingContext, + spec: TextureSpec, + sentinel: Sentinel, + view_dimension: TextureViewDimension, + texture: Texture, + readback: ReadbackBuffers, + encoder: Option, + /// Prefix of every assertion message, identifying the case. + desc: String, +} + +impl<'ctx> RenderTargetInitCase<'ctx> { + fn new( + ctx: &'ctx TestingContext, + spec: TextureSpec, + view_dimension: TextureViewDimension, + pre_init: PreInit, + desc: String, + ) -> Self { + let texture = spec.create(ctx); + let sentinel = sentinel_for(spec.format); + let readback = ReadbackBuffers::new(&ctx.device, &texture); + + let case = Self { + ctx, + spec, + sentinel, + view_dimension, + texture, + readback, + encoder: None, + desc, + }; + if matches!(pre_init, PreInit::Sentinel) { + case.write_sentinel(); + } + case + } + + /// Fill every mip level and array layer / depth slice with the sentinel value. + fn write_sentinel(&self) { + // Color textures are filled with `write_texture` rather than a render pass clear, + // to maximize the chance that these tests detect a missing zero-init. On at least + // one Vulkan driver, what the discard pass leaves behind depends on how the texture + // is filled here: + // * clear to white -> the discarded texture reads back as black, which is what the + // test asserts, so a wgpu that never zero-initialized any discarded texture would + // still pass + // * clear to red -> the discarded texture stays red + // * write_texture -> the discarded texture keeps its contents + // None of that violates any spec: it is wgpu's job to zero-fill the texture, no + // matter what the discard does or does not do. + // + // Depth/stencil textures have to use a clear regardless, because their depth aspect + // cannot be the destination of a `write_texture`, so they remain exposed to this + // possibility of a false-negative. + if self.spec.format.is_depth_stencil_format() { + let mut encoder = self + .ctx + .device + .create_command_encoder(&CommandEncoderDescriptor { + label: Some("Depth/Stencil setup"), + }); + for mip_level in 0..self.spec.mip_level_count { + for layer in 0..self.spec.subresources_at(mip_level) { + self.record_pass( + &mut encoder, + RenderTarget::Array { + mip: mip_level, + layer, + }, + PassOps::clear_store(self.sentinel), + ); + } + } + self.ctx.queue.submit([encoder.finish()]); + } else { + for mip_level in 0..self.spec.mip_level_count { + let mip_size = self.spec.mip_size(mip_level); + let bytes_per_row = self.spec.bytes_per_row(mip_level); + let texels = mip_size.height * mip_size.depth_or_array_layers * mip_size.width; + let texel = self.sentinel.texel(TextureAspect::All); + let data: Vec = texel + .iter() + .copied() + .cycle() + .take(texels as usize * texel.len()) + .collect(); + self.ctx.queue.write_texture( + TexelCopyTextureInfo { + texture: &self.texture, + mip_level, + origin: Origin3d::ZERO, + aspect: TextureAspect::All, + }, + &data, + TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(bytes_per_row), + rows_per_image: Some(mip_size.height), + }, + mip_size, + ); + } + self.ctx.queue.submit(None); + } + } + + /// Record a render pass whose only attachment is `target`. The pass has no pipeline and + /// issues no draws; its load and store operations are the entire point. + fn record_pass(&self, encoder: &mut CommandEncoder, target: RenderTarget, ops: PassOps) { + let format = self.spec.format; + let (base_array_layer, depth_slice) = match target { + RenderTarget::Array { layer, .. } => (layer, None), + RenderTarget::Volume { depth_slice, .. } => (0, Some(depth_slice)), + }; + let view = self.texture.create_view(&TextureViewDescriptor { + label: None, + format: Some(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, + array_layer_count: Some(1), + }); + encoder.begin_render_pass(&RenderPassDescriptor { + label: Some("Render target under test"), + color_attachments: &[format + .has_color_aspect() + .then_some(RenderPassColorAttachment { + view: &view, + depth_slice, + resolve_target: None, + ops: ops.color, + })], + depth_stencil_attachment: format.is_depth_stencil_format().then_some( + RenderPassDepthStencilAttachment { + view: &view, + depth_ops: format.has_depth_aspect().then_some(ops.depth), + stencil_ops: format.has_stencil_aspect().then_some(ops.stencil), + }, + ), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + } + + fn create_command_encoder(&mut self) { self.encoder = Some( self.ctx .device @@ -285,116 +683,694 @@ impl<'ctx> DiscardTestCase<'ctx> { ) } - pub fn submit_command_encoder(&mut self) { + fn submit_command_encoder(&mut self) { self.ctx .queue .submit([self.encoder.take().unwrap().finish()]); } - pub fn discard(&mut self) { - self.encoder - .as_mut() - .unwrap() - .begin_render_pass(&RenderPassDescriptor { - label: Some("Discard"), - color_attachments: &[self.format.has_color_aspect().then_some( - RenderPassColorAttachment { - view: &self.texture.create_view(&TextureViewDescriptor::default()), - depth_slice: None, - resolve_target: None, - ops: Operations { - load: LoadOp::Load, - store: StoreOp::Discard, - }, - }, - )], - depth_stencil_attachment: self.format.is_depth_stencil_format().then_some( - RenderPassDepthStencilAttachment { - view: &self.texture.create_view(&TextureViewDescriptor::default()), - depth_ops: self.format.has_depth_aspect().then_some(Operations { - load: LoadOp::Load, - store: StoreOp::Discard, - }), - stencil_ops: self.format.has_stencil_aspect().then_some(Operations { - load: LoadOp::Load, - store: StoreOp::Discard, - }), - }, - ), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); + fn pass(&mut self, target: RenderTarget, ops: PassOps) { + let mut encoder = self.encoder.take().unwrap(); + self.record_pass(&mut encoder, target, ops); + self.encoder = Some(encoder); } - pub fn discard_depth(&mut self) { - self.encoder - .as_mut() - .unwrap() - .begin_render_pass(&RenderPassDescriptor { - label: Some("Discard Depth"), - color_attachments: &[], - depth_stencil_attachment: self.format.is_depth_stencil_format().then_some( - RenderPassDepthStencilAttachment { - view: &self.texture.create_view(&TextureViewDescriptor::default()), - depth_ops: self.format.has_depth_aspect().then_some(Operations { - load: LoadOp::Load, - store: StoreOp::Discard, - }), - stencil_ops: self.format.has_stencil_aspect().then_some(Operations { - load: LoadOp::Clear(0), - store: StoreOp::Store, - }), - }, - ), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); + fn copy_texture_to_buffer(&mut self) { + let mut encoder = self.encoder.take().unwrap(); + self.readback + .copy_from(&self.ctx.device, &mut encoder, &self.texture); + self.encoder = Some(encoder); } - pub fn discard_stencil(&mut self) { - self.encoder - .as_mut() - .unwrap() - .begin_render_pass(&RenderPassDescriptor { - label: Some("Discard Stencil"), - color_attachments: &[], - depth_stencil_attachment: self.format.is_depth_stencil_format().then_some( - RenderPassDepthStencilAttachment { - view: &self.texture.create_view(&TextureViewDescriptor::default()), - depth_ops: self.format.has_depth_aspect().then_some(Operations { - load: LoadOp::Clear(0.0), - store: StoreOp::Store, - }), - stencil_ops: self.format.has_stencil_aspect().then_some(Operations { - load: LoadOp::Load, - store: StoreOp::Discard, - }), - }, - ), - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); + /// Compare every texel of every mip level and array layer / depth slice, of every aspect + /// that [`TextureSpec::readback_aspects`] selects, against `expected`, which is called + /// with (mip level, array layer or depth slice). + async fn assert_contents(&self, expected: impl Fn(u32, u32) -> Expected) { + let aspects = self.spec.readback_aspects(); + let mut failure = None; + + for &aspect in aspects { + // Naming the aspect is noise for a format that has only one. + let aspect_note = match aspect { + _ if aspects.len() == 1 => "", + TextureAspect::DepthOnly => ", depth aspect", + _ => ", stencil aspect", + }; + let data = self.readback.retrieve(self.ctx, aspect).await; + let aspect_failure = self.check_aspect(aspect, aspect_note, &data, &expected); + if failure.is_none() { + failure = aspect_failure; + } + } + + if let Some(failure) = failure { + panic!("{failure}"); + } } - pub fn copy_texture_to_buffer(&mut self) { - self.readback_buffers.copy_from( - &self.ctx.device, - self.encoder.as_mut().unwrap(), - &self.texture, - ); + /// Check one aspect of a readback, logging the result for every subresource and + /// returning a message describing the first mismatch, if there was one. + fn check_aspect( + &self, + aspect: TextureAspect, + aspect_note: &str, + data: &ReadbackData, + expected: &impl Fn(u32, u32) -> Expected, + ) -> Option { + let texel_size = self.spec.texel_size(aspect) as usize; + assert_eq!(texel_size, self.sentinel.texel(aspect).len()); + let case_desc = &self.desc; + let subresource_name = match self.spec.dimension { + TextureDimension::D3 => "slice", + _ => "layer", + }; + let zero = [0_u8; 4]; + let mut failure = None; + + for mip_level in 0..self.spec.mip_level_count { + let width = self.spec.mip_size(mip_level).width; + + for index in 0..self.spec.subresources_at(mip_level) { + let expected = expected(mip_level, index); + let want = match expected { + Expected::Zero => &zero[..texel_size], + Expected::Sentinel => self.sentinel.texel(aspect), + }; + + let texels = data.subresource(mip_level, index).chunks_exact(texel_size); + let texel_count = texels.len(); + let mut wrong = 0; + let mut first_wrong = None; + for (i, texel) in texels.enumerate() { + if texel != want { + wrong += 1; + if first_wrong.is_none() { + first_wrong = Some((i, texel)); + } + } + } + + if wrong == 0 { + log::info!( + "{case_desc}: mip {mip_level}, {subresource_name} {index}{aspect_note}: ok" + ); + continue; + } + log::info!( + "{case_desc}: mip {mip_level}, {subresource_name} {index}{aspect_note}: \ + {wrong}/{texel_count} texels wrong" + ); + + let (i, texel) = first_wrong.unwrap(); + if failure.is_none() { + let problem = match expected { + Expected::Zero => "read back non-zero", + Expected::Sentinel => "lost its contents", + }; + failure = Some(format!( + "{case_desc}: mip {mip_level}, {subresource_name} \ + {index}{aspect_note} {problem} at x={x} y={y}: \ + expected {want:02x?}, got {texel:02x?}", + x = i as u32 % width, + y = i as u32 / width, + )); + } + } + } + + failure } - pub async fn assert_buffers_are_zero(&mut self) { - assert!( - self.readback_buffers.are_zero(self.ctx).await, - "texture was not fully cleared" - ); + /// Assert that `target` holds `target_expected` and every other subresource holds the + /// opposite. + async fn assert_only_target(&self, target: RenderTarget, target_expected: Expected) { + let other = match target_expected { + Expected::Zero => Expected::Sentinel, + Expected::Sentinel => Expected::Zero, + }; + self.assert_contents(|mip_level, index| { + if mip_level == target.mip() && index == target.subresource_index() { + target_expected + } else { + other + } + }) + .await + } + + async fn assert_buffers_are_zero(&self) { + self.assert_contents(|_, _| Expected::Zero).await } } +// Tests of initialization tracking for textures used as render targets. +// +// Init tracking is per (mip level, array layer), and a render pass attachment is always a +// view of a single mip level and a single array layer. Depth slices of 3D textures are not +// tracked at all: for a 3D texture, one mip level is a single tracking unit covering all of +// its slices. + +/// Mip level count and array layer count of the textures used by the subresource tests. +/// Every combination of a mip level and an array layer is a distinct tracking unit. +const SUBRESOURCE_MIPS: u32 = 3; +const SUBRESOURCE_LAYERS: u32 = 3; +/// Size of mip level 0 of the textures used by these tests. Non-square, so a width/height +/// swap is caught. Deliberately small: the depth aspect of `Depth24Plus` and +/// `Depth24PlusStencil8` is read back by a single-invocation compute shader in +/// [`ReadbackBuffers`]. +const SUBRESOURCE_WIDTH: u32 = 256; +const SUBRESOURCE_HEIGHT: u32 = 4; + +fn color_2d_spec() -> TextureSpec { + TextureSpec { + format: TextureFormat::Rgba8Uint, + dimension: TextureDimension::D2, + size: Extent3d { + width: SUBRESOURCE_WIDTH, + height: SUBRESOURCE_HEIGHT, + depth_or_array_layers: SUBRESOURCE_LAYERS, + }, + mip_level_count: SUBRESOURCE_MIPS, + } +} + +/// Mip level 0 has four depth slices and mip level 1 has two, so a single-slice attachment +/// covers only part of the tracking unit. Mip level 2 has a single slice, which one +/// attachment covers completely. +fn color_3d_spec() -> TextureSpec { + TextureSpec { + format: TextureFormat::Rgba8Uint, + dimension: TextureDimension::D3, + size: Extent3d { + width: SUBRESOURCE_WIDTH, + height: SUBRESOURCE_HEIGHT, + depth_or_array_layers: 4, + }, + mip_level_count: SUBRESOURCE_MIPS, + } +} + +/// Depth/stencil formats other than [`TextureFormat::Depth32FloatStencil8`], +/// which requires [`Features::DEPTH32FLOAT_STENCIL8`]. +const CORE_DEPTH_STENCIL_FORMATS: &[TextureFormat] = &[ + TextureFormat::Stencil8, + TextureFormat::Depth16Unorm, + TextureFormat::Depth24Plus, + TextureFormat::Depth24PlusStencil8, + TextureFormat::Depth32Float, +]; + +fn depth_stencil_2d_spec(format: TextureFormat) -> TextureSpec { + TextureSpec { + format, + dimension: TextureDimension::D2, + size: Extent3d { + width: SUBRESOURCE_WIDTH, + height: SUBRESOURCE_HEIGHT, + depth_or_array_layers: SUBRESOURCE_LAYERS, + }, + mip_level_count: SUBRESOURCE_MIPS, + } +} + +/// Renders the sentinel value into `target` with `StoreOp::Store` and checks that only +/// `target` holds it, and that every other subresource of the texture reads back as zero. +/// +/// The sentinel check fails deterministically if the store is tracked as initializing too +/// little; the zero checks only fail if the underlying allocation is not already zero (see +/// the comment at the top of this file). +async fn check_store_inits_only_target( + ctx: &TestingContext, + spec: TextureSpec, + view_dimension: TextureViewDimension, + target: RenderTarget, + readback_in_same_encoder: bool, +) { + let mut case = RenderTargetInitCase::new( + ctx, + spec, + view_dimension, + PreInit::Fresh, + format!( + "{:?} store to {target} of a {view_dimension:?} view{}", + spec.format, + if readback_in_same_encoder { + ", read back in the same encoder" + } else { + "" + } + ), + ); + + let ops = PassOps::clear_store(case.sentinel); + case.create_command_encoder(); + case.pass(target, ops); + if !readback_in_same_encoder { + case.submit_command_encoder(); + case.create_command_encoder(); + } + case.copy_texture_to_buffer(); + case.submit_command_encoder(); + + case.assert_only_target(target, Expected::Sentinel).await; +} + +/// Discards `target` and checks that only `target` was reset to zero, and that every other +/// subresource of the texture kept the sentinel value. +async fn check_discard_resets_only_target( + ctx: &TestingContext, + spec: TextureSpec, + view_dimension: TextureViewDimension, + target: RenderTarget, + load: LoadOp<()>, + readback_in_same_encoder: bool, +) { + let mut case = RenderTargetInitCase::new( + ctx, + spec, + view_dimension, + PreInit::Sentinel, + format!( + "{:?} {} + discard of {target}{}", + spec.format, + if matches!(load, LoadOp::Load) { + "load" + } else { + "clear" + }, + if readback_in_same_encoder { + ", read back in the same encoder" + } else { + "" + } + ), + ); + + let ops = if matches!(load, LoadOp::Load) { + PassOps::load_discard() + } else { + PassOps::clear_discard(case.sentinel) + }; + case.create_command_encoder(); + case.pass(target, ops); + if !readback_in_same_encoder { + case.submit_command_encoder(); + case.create_command_encoder(); + } + case.copy_texture_to_buffer(); + case.submit_command_encoder(); + + case.assert_only_target(target, Expected::Zero).await; +} + +/// Discards a subresource of a mipmapped, layered `format` texture that is neither the first +/// mip level nor the first array layer, and checks that no other subresource was affected. +async fn check_depth_discard_at_nonzero_mip_and_layer(ctx: &TestingContext, format: TextureFormat) { + for target in [ + RenderTarget::Array { mip: 1, layer: 1 }, + RenderTarget::Array { mip: 2, layer: 2 }, + ] { + for readback_in_same_encoder in [false, true] { + check_discard_resets_only_target( + ctx, + depth_stencil_2d_spec(format), + TextureViewDimension::D2, + target, + LoadOp::Load, + readback_in_same_encoder, + ) + .await; + } + } +} + +// A `StoreOp::Store` pass must mark only the (mip level, array layer) that it targets as +// initialized. +#[apply(gpu_test!)] +static RENDER_PASS_STORE_INITS_ONLY_TARGET_COLOR_SUBRESOURCE: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters(TestParameters::default()) + .run_async(|ctx| async move { + for view_dimension in [TextureViewDimension::D2, TextureViewDimension::D2Array] { + for target in [ + RenderTarget::Array { mip: 0, layer: 0 }, + RenderTarget::Array { mip: 1, layer: 1 }, + RenderTarget::Array { mip: 2, layer: 2 }, + RenderTarget::Array { mip: 2, layer: 0 }, + ] { + for readback_in_same_encoder in [false, true] { + check_store_inits_only_target( + &ctx, + color_2d_spec(), + view_dimension, + target, + readback_in_same_encoder, + ) + .await; + } + } + } + }); + +#[apply(gpu_test!)] +static RENDER_PASS_STORE_INITS_ONLY_TARGET_DEPTH_STENCIL_SUBRESOURCE: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + // `ReadbackBuffers` reads the depth aspect of `Depth24PlusStencil8` with a + // compute shader. + .downlevel_flags( + DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES + | DownlevelFlags::COMPUTE_SHADERS, + ) + .limits(Limits::downlevel_defaults()), + ) + .run_async(|ctx| async move { + for &format in CORE_DEPTH_STENCIL_FORMATS { + for target in [ + RenderTarget::Array { mip: 0, layer: 0 }, + RenderTarget::Array { mip: 1, layer: 1 }, + RenderTarget::Array { mip: 2, layer: 2 }, + ] { + check_store_inits_only_target( + &ctx, + depth_stencil_2d_spec(format), + TextureViewDimension::D2, + target, + false, + ) + .await; + } + } + }); + +// Rendering to the last mip level of the 3D texture, which has a single depth slice, covers +// its whole tracking unit, so it must behave like any other fully covered render target. +#[apply(gpu_test!)] +static RENDER_PASS_STORE_INITS_ONLY_TARGET_3D_MIP: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + // 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 { + check_store_inits_only_target( + &ctx, + color_3d_spec(), + TextureViewDimension::D3, + RenderTarget::Volume { + mip: SUBRESOURCE_MIPS - 1, + depth_slice: 0, + }, + false, + ) + .await; + }); + +// `LoadOp::Load` of a single depth slice must initialize the whole mip level, because the +// slices of a 3D mip level are not tracked separately. +#[apply(gpu_test!)] +static RENDER_PASS_LOAD_INITS_WHOLE_3D_MIP: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + // 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 { + for pre_init in [PreInit::Fresh, PreInit::Sentinel] { + for target in [ + RenderTarget::Volume { + mip: 0, + depth_slice: 2, + }, + RenderTarget::Volume { + mip: 1, + depth_slice: 1, + }, + ] { + // A freshly created texture must read back as zero everywhere. A texture + // that was fully written must keep its contents everywhere, including the + // slices that the pass did not target. + let expected = match pre_init { + PreInit::Fresh => Expected::Zero, + PreInit::Sentinel => Expected::Sentinel, + }; + + let mut case = RenderTargetInitCase::new( + &ctx, + color_3d_spec(), + TextureViewDimension::D3, + pre_init, + format!("load of {target} of a 3D texture ({expected:?})"), + ); + case.create_command_encoder(); + case.pass(target, PassOps::load_store()); + case.submit_command_encoder(); + + case.create_command_encoder(); + case.copy_texture_to_buffer(); + case.submit_command_encoder(); + + case.assert_contents(|_, _| expected).await; + } + } + }); + +// Discarding a (mip level, array layer) must reset only that subresource, whether the +// discarded contents are read in the same encoder or after a submit. +#[apply(gpu_test!)] +static DISCARDING_COLOR_TARGET_AT_NONZERO_MIP_AND_LAYER: GpuTestConfiguration = + GpuTestConfiguration::new() + // https://github.com/gfx-rs/wgpu/issues/10162 + .parameters(TestParameters::default().expect_fail(FailureCase::webgl2())) + .run_async(|ctx| async move { + for target in [ + RenderTarget::Array { mip: 1, layer: 1 }, + RenderTarget::Array { mip: 2, layer: 2 }, + ] { + for load in [LoadOp::Load, LoadOp::Clear(())] { + for readback_in_same_encoder in [false, true] { + check_discard_resets_only_target( + &ctx, + color_2d_spec(), + TextureViewDimension::D2, + target, + load, + readback_in_same_encoder, + ) + .await; + } + } + } + }); + +#[apply(gpu_test!)] +static DISCARDING_DEPTH_TARGET_AT_NONZERO_MIP_AND_LAYER: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .downlevel_flags( + DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES + | DownlevelFlags::COMPUTE_SHADERS, + ) + .limits(Limits::downlevel_defaults()), + ) + .run_async(|ctx| async move { + for &format in CORE_DEPTH_STENCIL_FORMATS { + check_depth_discard_at_nonzero_mip_and_layer(&ctx, format).await; + } + }); + +// As above, for the depth/stencil format that is behind an optional feature. +#[apply(gpu_test!)] +static DISCARDING_DEPTH_TARGET_AT_NONZERO_MIP_AND_LAYER_DEPTH32FLOAT_STENCIL8: + GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::DEPTH32FLOAT_STENCIL8) + .downlevel_flags(DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES) + .limits(Limits::downlevel_defaults()), + ) + .run_async(|ctx| async move { + check_depth_discard_at_nonzero_mip_and_layer(&ctx, TextureFormat::Depth32FloatStencil8) + .await; + }); + +// Init state is not tracked per aspect, so discarding one aspect of a combined +// depth/stencil texture must still leave the discarded aspect of that subresource +// initialized, and must not affect any other subresource. +#[apply(gpu_test!)] +static DISCARDING_EITHER_DEPTH_OR_STENCIL_ASPECT_AT_NONZERO_MIP_AND_LAYER: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .downlevel_flags( + DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES + | DownlevelFlags::COMPUTE_SHADERS, + ) + .limits(Limits::downlevel_defaults()), + ) + .run_async(|ctx| async move { + let target = RenderTarget::Array { mip: 1, layer: 1 }; + let mut case = RenderTargetInitCase::new( + &ctx, + depth_stencil_2d_spec(TextureFormat::Depth24PlusStencil8), + TextureViewDimension::D2, + PreInit::Sentinel, + format!("diverging depth/stencil discard of {target}"), + ); + + case.create_command_encoder(); + case.pass(target, PassOps::discard_depth_keep_stencil()); + case.submit_command_encoder(); + + case.create_command_encoder(); + case.pass(target, PassOps::discard_stencil_keep_depth()); + case.submit_command_encoder(); + + case.create_command_encoder(); + case.copy_texture_to_buffer(); + case.submit_command_encoder(); + + case.assert_only_target(target, Expected::Zero).await; + }); + +// Discarding both aspects of a combined depth/stencil texture must reset the whole +// subresource, even when the load operations of the two aspects diverge. This is a +// regression test for an error in the handling of divergent depth/stencil usage within a +// render pass, which takes a dedicated path for handling the store ops, even when they do +// not differ. +#[apply(gpu_test!)] +static DISCARDING_BOTH_DEPTH_AND_STENCIL_WITH_DIVERGING_LOAD_OPS: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .downlevel_flags( + DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES + | DownlevelFlags::COMPUTE_SHADERS, + ) + .limits(Limits::downlevel_defaults()), + ) + .run_async(|ctx| async move { + let target = RenderTarget::Array { mip: 1, layer: 1 }; + let mut case = RenderTargetInitCase::new( + &ctx, + depth_stencil_2d_spec(TextureFormat::Depth24PlusStencil8), + TextureViewDimension::D2, + PreInit::Sentinel, + format!("discard of both aspects of {target}, loading stencil"), + ); + + case.create_command_encoder(); + case.pass( + target, + PassOps::discard_both_with_diverging_load(/* load_depth */ false), + ); + case.submit_command_encoder(); + + case.create_command_encoder(); + case.copy_texture_to_buffer(); + case.submit_command_encoder(); + + case.assert_only_target(target, Expected::Zero).await; + }); + +// A discarded subresource that is loaded by a later render pass in the same encoder must be +// initialized before that pass runs. +#[apply(gpu_test!)] +static DISCARDING_COLOR_TARGET_THEN_LOADING_IT_IN_SAME_ENCODER: GpuTestConfiguration = + GpuTestConfiguration::new() + // https://github.com/gfx-rs/wgpu/issues/10162 + .parameters(TestParameters::default().expect_fail(FailureCase::webgl2())) + .run_async(|ctx| async move { + let target = RenderTarget::Array { mip: 1, layer: 1 }; + let mut case = RenderTargetInitCase::new( + &ctx, + color_2d_spec(), + TextureViewDimension::D2, + PreInit::Sentinel, + format!("discard then load of {target}"), + ); + + case.create_command_encoder(); + case.pass(target, PassOps::load_discard()); + case.pass(target, PassOps::load_store()); + case.copy_texture_to_buffer(); + case.submit_command_encoder(); + + case.assert_only_target(target, Expected::Zero).await; + }); + +// The slices of a 3D mip level are not tracked separately, so a `StoreOp::Store` pass that +// covers a single slice of a multi-slice mip level must trigger initialization of the +// complete texture uninitialized. +#[apply(gpu_test!)] +static RENDER_PASS_STORE_TO_3D_DEPTH_SLICE_INITS_OTHER_SLICES: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + // 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 { + check_store_inits_only_target( + &ctx, + color_3d_spec(), + TextureViewDimension::D3, + RenderTarget::Volume { + mip: 0, + depth_slice: 2, + }, + false, + ) + .await; + }); + +// Discarding a single slice of a multi-slice 3D mip level must reset only that slice. Since +// the init tracker cannot represent a discarded slice, the slice has to be reinitialized +// immediately instead. +#[apply(gpu_test!)] +static DISCARDING_3D_DEPTH_SLICE_PRESERVES_OTHER_SLICES: 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 { + for load in [LoadOp::Load, LoadOp::Clear(())] { + for readback_in_same_encoder in [false, true] { + check_discard_resets_only_target( + &ctx, + color_3d_spec(), + TextureViewDimension::D3, + RenderTarget::Volume { + mip: 0, + depth_slice: 2, + }, + load, + readback_in_same_encoder, + ) + .await; + } + } + }); + // Tests that a full-extent, single-aspect `write_texture` does not cause // *other* aspects of a multi-aspect texture to be considered initialized.