test: Extend ReadbackBuffers to mips, depth slices, and arrays

This commit is contained in:
Andy Leiserson committed 2026-08-25 12:51:23 -07:00
1 parent 0f02d4b200
commit 088f101d30
2 files changed
+325 -225

No files matched your search

+3 -3
View File
@@ -6,12 +6,12 @@ var<storage, read_write> output: array<{{type}}>;
@compute @workgroup_size(1)
fn copy_texture_to_buffer() {
let layers = i32(textureNumLayers(texture));
let layers = textureNumLayers(texture);
let dim = textureDimensions(texture);
for (var l = 0; l < layers; l++) {
for (var l = 0u; l < layers; l++) {
for (var y = 0u; y < dim.y; y++) {
for (var x = 0u; x < dim.x; x++) {
output[x + y * dim.x] = textureLoad(texture, vec2(x, y), l, 0).x;
output[(l * dim.y + y) * dim.x + x] = textureLoad(texture, vec2(x, y), l, 0).x;
}
}
}
+322 -222
View File
@@ -275,13 +275,131 @@ fn sanitize_for_path(s: &str) -> String {
.collect()
}
/// Value that readback buffers are filled with before use, so that a copy that fails to
/// happen is not mistaken for zeroed memory.
const POISON: u8 = 255;
/// Layout of one mip level of one aspect of a texture within a readback buffer.
///
/// The array layers (for `D2` textures) or depth slices (for `D3`) of a mip level are laid
/// out consecutively within its region, each `bytes_per_row * rows_per_image` bytes long.
#[derive(Clone, Copy, Debug)]
struct MipLayout {
/// Byte offset of this mip level's region within the buffer. A multiple of
/// [`COPY_BYTES_PER_ROW_ALIGNMENT`], which satisfies every alignment requirement that
/// applies: copy offsets, storage binding offsets, and buffer mapping.
offset: u64,
/// Row stride within the buffer. Aligned to [`COPY_BYTES_PER_ROW_ALIGNMENT`], which
/// `copy_texture_to_buffer` requires, except on the compute shader path, whose shader
/// writes tightly packed rows.
bytes_per_row: u32,
/// Bytes of texel data in each row, without the padding included in `bytes_per_row`.
unpadded_bytes_per_row: u32,
/// Number of block rows in each array layer or depth slice.
rows_per_image: u32,
/// Physical (block aligned) extent of this mip level.
size: Extent3d,
/// Bytes reserved for this mip level, including the padding that keeps the offset of
/// the next mip level aligned.
region_size: u64,
}
impl MipLayout {
/// Bytes of texel data in one array layer or depth slice, excluding row padding.
fn unpadded_subresource_size(&self) -> usize {
self.unpadded_bytes_per_row as usize * self.rows_per_image as usize
}
/// Bytes of texel data in this mip level, excluding all padding.
fn unpadded_size(&self) -> usize {
self.unpadded_subresource_size() * self.size.depth_or_array_layers as usize
}
}
/// Whether the readable aspect of `format` has to be read with a compute shader because it
/// cannot be the source of a `copy_texture_to_buffer`.
fn needs_compute_readback(format: TextureFormat) -> bool {
matches!(
format,
TextureFormat::Depth24Plus | TextureFormat::Depth24PlusStencil8
)
}
/// Compute the layout of every mip level of one aspect of `texture`.
///
/// When `dense_rows` is `true`, computes a layout with tightly packed rows for
/// the compute shader path. When false, computes a layout with padding to
/// `COPY_BYTES_PER_ROW_ALIGNMENT` for `copy_texture_to_buffer`.
fn mip_layouts(
texture: &Texture,
aspect: Option<TextureAspect>,
dense_rows: bool,
) -> Vec<MipLayout> {
let format = texture.format();
let (block_width, block_height) = format.block_dimensions();
// `block_copy_size` returns `None` for the aspects that are read with a compute
// shader, which writes one `f32` or `u32` per texel.
let block_size = format.block_copy_size(aspect).unwrap_or(4);
let mut offset = 0;
(0..texture.mip_level_count())
.map(|mip_level| {
// The physical size is what a copy of a whole mip level must use, and it is
// what the buffer has to hold: for a compressed format, the last row or
// column of blocks extends past the logical size.
let size = texture
.size()
.mip_level_size(mip_level, texture.dimension())
.physical_size(format);
let unpadded_bytes_per_row = (size.width / block_width) * block_size;
let bytes_per_row = if dense_rows {
unpadded_bytes_per_row
} else {
align_to(unpadded_bytes_per_row, COPY_BYTES_PER_ROW_ALIGNMENT)
};
let rows_per_image = size.height / block_height;
let layout = MipLayout {
offset,
bytes_per_row,
unpadded_bytes_per_row,
rows_per_image,
size,
region_size: align_to(
u64::from(bytes_per_row)
* u64::from(rows_per_image)
* u64::from(size.depth_or_array_layers),
u64::from(COPY_BYTES_PER_ROW_ALIGNMENT),
),
};
offset += layout.region_size;
layout
})
.collect()
}
fn create_readback_buffer(device: &Device, label: &str, layouts: &[MipLayout]) -> Buffer {
let size = layouts.last().map_or(0, |l| l.offset + l.region_size);
device.create_buffer_init(&util::BufferInitDescriptor {
label: Some(label),
usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
contents: &vec![POISON; size as usize],
})
}
fn copy_via_compute(
device: &Device,
encoder: &mut CommandEncoder,
texture: &Texture,
buffer: &Buffer,
layouts: &[MipLayout],
aspect: TextureAspect,
) {
assert_eq!(
texture.dimension(),
TextureDimension::D2,
"the compute shader readback path binds the texture as `D2Array`"
);
let bgl = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: None,
entries: &[
@@ -312,37 +430,47 @@ fn copy_via_compute(
],
});
let view = texture.create_view(&TextureViewDescriptor {
aspect,
dimension: Some(TextureViewDimension::D2Array),
..Default::default()
});
let output_buffer = device.create_buffer(&BufferDescriptor {
// The shader writes one texel at a time, so anything it fails to cover keeps the
// poison value rather than reading back as zero.
let output_buffer = device.create_buffer_init(&util::BufferInitDescriptor {
label: Some("output buffer"),
size: buffer.size(),
usage: BufferUsages::COPY_SRC | BufferUsages::STORAGE,
mapped_at_creation: false,
contents: &vec![POISON; buffer.size() as usize],
});
let bg = device.create_bind_group(&BindGroupDescriptor {
label: None,
layout: &bgl,
entries: &[
BindGroupEntry {
binding: 0,
resource: BindingResource::TextureView(&view),
},
BindGroupEntry {
binding: 1,
resource: BindingResource::Buffer(BufferBinding {
buffer: &output_buffer,
offset: 0,
size: None,
}),
},
],
});
// A view of a single mip level rebases mip level 0 onto it, so the shader reads the
// right level without knowing which one it is.
let bind_groups: Vec<BindGroup> = layouts
.iter()
.enumerate()
.map(|(mip_level, layout)| {
let view = texture.create_view(&TextureViewDescriptor {
aspect,
dimension: Some(TextureViewDimension::D2Array),
base_mip_level: mip_level as u32,
mip_level_count: Some(1),
..Default::default()
});
device.create_bind_group(&BindGroupDescriptor {
label: None,
layout: &bgl,
entries: &[
BindGroupEntry {
binding: 0,
resource: BindingResource::TextureView(&view),
},
BindGroupEntry {
binding: 1,
resource: BindingResource::Buffer(BufferBinding {
buffer: &output_buffer,
offset: layout.offset,
size: BufferSize::new(layout.region_size),
}),
},
],
})
})
.collect();
let pll = device.create_pipeline_layout(&PipelineLayoutDescriptor {
label: None,
@@ -379,241 +507,180 @@ fn copy_via_compute(
let mut pass = encoder.begin_compute_pass(&ComputePassDescriptor::default());
pass.set_pipeline(&pipeline_copy);
pass.set_bind_group(0, &bg, &[]);
pass.dispatch_workgroups(1, 1, 1);
for bind_group in &bind_groups {
pass.set_bind_group(0, bind_group, &[]);
pass.dispatch_workgroups(1, 1, 1);
}
}
encoder.copy_buffer_to_buffer(&output_buffer, 0, buffer, 0, buffer.size());
encoder.copy_buffer_to_buffer(&output_buffer, 0, buffer, 0, output_buffer.size());
}
fn copy_texture_to_buffer_with_aspect(
encoder: &mut CommandEncoder,
texture: &Texture,
buffer: &Buffer,
buffer_stencil: &Option<Buffer>,
layouts: &[MipLayout],
aspect: TextureAspect,
) {
let (block_width, block_height) = texture.format().block_dimensions();
let block_size = texture.format().block_copy_size(Some(aspect)).unwrap();
let bytes_per_row = align_to(
(texture.width() / block_width) * block_size,
COPY_BYTES_PER_ROW_ALIGNMENT,
);
let mip_level = 0;
encoder.copy_texture_to_buffer(
TexelCopyTextureInfo {
texture,
mip_level,
origin: Origin3d::ZERO,
aspect,
},
TexelCopyBufferInfo {
buffer: match aspect {
TextureAspect::StencilOnly => buffer_stencil.as_ref().unwrap(),
_ => buffer,
for (mip_level, layout) in layouts.iter().enumerate() {
encoder.copy_texture_to_buffer(
TexelCopyTextureInfo {
texture,
mip_level: mip_level as u32,
origin: Origin3d::ZERO,
aspect,
},
layout: TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(bytes_per_row),
rows_per_image: Some(texture.height() / block_height),
TexelCopyBufferInfo {
buffer,
layout: TexelCopyBufferLayout {
offset: layout.offset,
bytes_per_row: Some(layout.bytes_per_row),
rows_per_image: Some(layout.rows_per_image),
},
},
},
texture
.size()
.mip_level_size(mip_level, texture.dimension()),
);
}
fn copy_texture_to_buffer(
device: &Device,
encoder: &mut CommandEncoder,
texture: &Texture,
buffer: &Buffer,
buffer_stencil: &Option<Buffer>,
) {
match texture.format() {
TextureFormat::Depth24Plus => {
copy_via_compute(device, encoder, texture, buffer, TextureAspect::DepthOnly);
}
TextureFormat::Depth24PlusStencil8 => {
copy_via_compute(device, encoder, texture, buffer, TextureAspect::DepthOnly);
copy_texture_to_buffer_with_aspect(
encoder,
texture,
buffer,
buffer_stencil,
TextureAspect::StencilOnly,
);
}
TextureFormat::Depth32FloatStencil8 => {
copy_texture_to_buffer_with_aspect(
encoder,
texture,
buffer,
buffer_stencil,
TextureAspect::DepthOnly,
);
copy_texture_to_buffer_with_aspect(
encoder,
texture,
buffer,
buffer_stencil,
TextureAspect::StencilOnly,
);
}
_ => {
copy_texture_to_buffer_with_aspect(
encoder,
texture,
buffer,
buffer_stencil,
TextureAspect::All,
);
}
layout.size,
);
}
}
/// Buffers holding a readback of every mip level and every array layer or depth slice of a
/// texture.
pub struct ReadbackBuffers {
/// texture format
/// format of the texture this was created for
texture_format: TextureFormat,
/// texture width
texture_width: u32,
/// texture height
texture_height: u32,
/// texture depth or array layer count
texture_depth_or_array_layers: u32,
/// buffer for color or depth aspects
buffer: Buffer,
/// layout of `buffer`, one entry per mip level
layouts: Vec<MipLayout>,
/// buffer for stencil aspect
buffer_stencil: Option<Buffer>,
/// layout of `buffer_stencil`, empty if there is none
stencil_layouts: Vec<MipLayout>,
}
impl ReadbackBuffers {
pub fn new(device: &Device, texture: &Texture) -> Self {
let (block_width, block_height) = texture.format().block_dimensions();
const SKIP_ALIGNMENT_FORMATS: [TextureFormat; 2] = [
TextureFormat::Depth24Plus,
TextureFormat::Depth24PlusStencil8,
];
let should_align_buffer_size = !SKIP_ALIGNMENT_FORMATS.contains(&texture.format());
if texture.format().is_combined_depth_stencil_format() {
let mut buffer_depth_bytes_per_row = (texture.width() / block_width)
* texture
.format()
.block_copy_size(Some(TextureAspect::DepthOnly))
.unwrap_or(4);
if should_align_buffer_size {
buffer_depth_bytes_per_row =
align_to(buffer_depth_bytes_per_row, COPY_BYTES_PER_ROW_ALIGNMENT);
}
let buffer_size = buffer_depth_bytes_per_row
* (texture.height() / block_height)
* texture.depth_or_array_layers();
let texture_format = texture.format();
let combined = texture_format.is_combined_depth_stencil_format();
let buffer_stencil_bytes_per_row = align_to(
(texture.width() / block_width)
* texture
.format()
.block_copy_size(Some(TextureAspect::StencilOnly))
.unwrap_or(4),
COPY_BYTES_PER_ROW_ALIGNMENT,
);
let buffer_stencil_size = buffer_stencil_bytes_per_row
* (texture.height() / block_height)
* texture.depth_or_array_layers();
// When using the compute shader path (`depth24plus` and
// `depth24plus-stencil8`), rows are packed tightly instead of padded to
// `COPY_BYTES_PER_ROW_ALIGNMENT`.
let layouts = mip_layouts(
texture,
combined.then_some(TextureAspect::DepthOnly),
needs_compute_readback(texture_format),
);
let buffer = create_readback_buffer(device, "Texture Readback", &layouts);
let buffer = device.create_buffer_init(&util::BufferInitDescriptor {
label: Some("Texture Readback"),
usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
contents: &vec![255; buffer_size as usize],
});
let buffer_stencil = device.create_buffer_init(&util::BufferInitDescriptor {
label: Some("Texture Stencil-Aspect Readback"),
usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
contents: &vec![255; buffer_stencil_size as usize],
});
ReadbackBuffers {
texture_format: texture.format(),
texture_width: texture.width(),
texture_height: texture.height(),
texture_depth_or_array_layers: texture.depth_or_array_layers(),
buffer,
buffer_stencil: Some(buffer_stencil),
}
let (buffer_stencil, stencil_layouts) = if combined {
let layouts = mip_layouts(texture, Some(TextureAspect::StencilOnly), false);
let buffer =
create_readback_buffer(device, "Texture Stencil-Aspect Readback", &layouts);
(Some(buffer), layouts)
} else {
let mut bytes_per_row = (texture.width() / block_width)
* texture.format().block_copy_size(None).unwrap_or(4);
if should_align_buffer_size {
bytes_per_row = align_to(bytes_per_row, COPY_BYTES_PER_ROW_ALIGNMENT);
}
let buffer_size =
bytes_per_row * (texture.height() / block_height) * texture.depth_or_array_layers();
let buffer = device.create_buffer_init(&util::BufferInitDescriptor {
label: Some("Texture Readback"),
usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
contents: &vec![255; buffer_size as usize],
});
ReadbackBuffers {
texture_format: texture.format(),
texture_width: texture.width(),
texture_height: texture.height(),
texture_depth_or_array_layers: texture.depth_or_array_layers(),
buffer,
buffer_stencil: None,
}
(None, Vec::new())
};
ReadbackBuffers {
texture_format,
buffer,
layouts,
buffer_stencil,
stencil_layouts,
}
}
// TODO: also copy and check mips
pub fn copy_from(&self, device: &Device, encoder: &mut CommandEncoder, texture: &Texture) {
copy_texture_to_buffer(device, encoder, texture, &self.buffer, &self.buffer_stencil);
assert_eq!(
(texture.format(), texture.mip_level_count() as usize),
(self.texture_format, self.layouts.len()),
"texture does not match the one this `ReadbackBuffers` was created for"
);
if needs_compute_readback(self.texture_format) {
copy_via_compute(
device,
encoder,
texture,
&self.buffer,
&self.layouts,
TextureAspect::DepthOnly,
);
} else {
let aspect = if self.buffer_stencil.is_some() {
TextureAspect::DepthOnly
} else {
TextureAspect::All
};
copy_texture_to_buffer_with_aspect(
encoder,
texture,
&self.buffer,
&self.layouts,
aspect,
);
}
if let Some(buffer_stencil) = &self.buffer_stencil {
copy_texture_to_buffer_with_aspect(
encoder,
texture,
buffer_stencil,
&self.stencil_layouts,
TextureAspect::StencilOnly,
);
}
}
/// Map `buffer` and return its texel data, tightly packed, with the row padding that
/// `layouts` describes removed. Mip level 0 comes first.
///
/// The caller is responsible for unmapping `buffer`.
async fn retrieve_buffer(
&self,
ctx: &TestingContext,
buffer: &Buffer,
aspect: Option<TextureAspect>,
layouts: &[MipLayout],
) -> Vec<u8> {
let buffer_slice = buffer.slice(..);
buffer_slice.map_async(MapMode::Read, |_| ());
ctx.async_poll(PollType::wait_indefinitely()).await.unwrap();
let (block_width, block_height) = self.texture_format.block_dimensions();
let expected_bytes_per_row = (self.texture_width / block_width)
* self.texture_format.block_copy_size(aspect).unwrap_or(4);
let expected_buffer_size = expected_bytes_per_row
* (self.texture_height / block_height)
* self.texture_depth_or_array_layers;
let data: BufferView = buffer_slice.get_mapped_range().unwrap();
if expected_buffer_size as usize == data.len() {
data.to_vec()
} else {
bytemuck::cast_slice(&data)
.chunks_exact(
align_to(expected_bytes_per_row, COPY_BYTES_PER_ROW_ALIGNMENT) as usize,
)
.flat_map(|x| x.iter().take(expected_bytes_per_row as usize))
.copied()
.collect()
let mut result = Vec::with_capacity(layouts.iter().map(MipLayout::unpadded_size).sum());
for layout in layouts {
let start = layout.offset as usize;
let rows = layout.rows_per_image as usize * layout.size.depth_or_array_layers as usize;
let region = &data[start..start + layout.bytes_per_row as usize * rows];
for row in region.chunks_exact(layout.bytes_per_row as usize) {
result.extend_from_slice(&row[..layout.unpadded_bytes_per_row as usize]);
}
}
result
}
/// Read back one aspect of the texture.
///
/// Reads the stencil buffer if `aspect` is [`TextureAspect::StencilOnly`] and the
/// texture has a separate stencil aspect, and the color or depth buffer otherwise.
pub async fn retrieve(&self, ctx: &TestingContext, aspect: TextureAspect) -> ReadbackData {
let (buffer, layouts) = match (aspect, &self.buffer_stencil) {
(TextureAspect::StencilOnly, Some(buffer)) => (buffer, &self.stencil_layouts),
_ => (&self.buffer, &self.layouts),
};
let data = self.retrieve_buffer(ctx, buffer, layouts).await;
buffer.unmap();
ReadbackData {
data,
layouts: layouts.clone(),
}
}
fn buffer_aspect(&self) -> Option<TextureAspect> {
if self.texture_format.is_combined_depth_stencil_format() {
Some(TextureAspect::DepthOnly)
} else {
None
}
}
async fn is_zero(
&self,
ctx: &TestingContext,
buffer: &Buffer,
aspect: Option<TextureAspect>,
) -> bool {
async fn is_zero(&self, ctx: &TestingContext, buffer: &Buffer, layouts: &[MipLayout]) -> bool {
let is_zero = self
.retrieve_buffer(ctx, buffer, aspect)
.retrieve_buffer(ctx, buffer, layouts)
.await
.iter()
.all(|b| *b == 0);
@@ -622,16 +689,18 @@ impl ReadbackBuffers {
}
pub async fn are_zero(&self, ctx: &TestingContext) -> bool {
let buffer_zero = self.is_zero(ctx, &self.buffer, self.buffer_aspect()).await;
let buffer_zero = self.is_zero(ctx, &self.buffer, &self.layouts).await;
let mut stencil_buffer_zero = true;
if let Some(buffer) = &self.buffer_stencil {
stencil_buffer_zero = self
.is_zero(ctx, buffer, Some(TextureAspect::StencilOnly))
.await;
stencil_buffer_zero = self.is_zero(ctx, buffer, &self.stencil_layouts).await;
};
buffer_zero && stencil_buffer_zero
}
/// Assert that the color or depth aspect starts with `expected_data`.
///
/// Only a prefix of the readback is checked, so for a texture with more than one mip
/// level this covers mip level 0 alone unless `expected_data` holds every mip level.
pub async fn assert_buffer_contents(&self, ctx: &TestingContext, expected_data: &[u8]) {
self.assert_buffer_contents_imprecise(ctx, expected_data, 0)
.await;
@@ -643,9 +712,7 @@ impl ReadbackBuffers {
expected_data: &[u8],
max_diff: u8,
) {
let result_buffer = self
.retrieve_buffer(ctx, &self.buffer, self.buffer_aspect())
.await;
let result_buffer = self.retrieve_buffer(ctx, &self.buffer, &self.layouts).await;
assert!(
result_buffer.len() >= expected_data.len(),
"Result buffer ({}) smaller than expected buffer ({})",
@@ -660,3 +727,36 @@ impl ReadbackBuffers {
self.buffer.unmap();
}
}
/// Tightly packed contents of one aspect of a texture, as read back by
/// [`ReadbackBuffers::retrieve`].
pub struct ReadbackData {
data: Vec<u8>,
layouts: Vec<MipLayout>,
}
impl ReadbackData {
/// Every mip level, tightly packed, mip level 0 first.
pub fn all(&self) -> &[u8] {
&self.data
}
/// Contents of one array layer (for a `D2` texture) or depth slice (for `D3`) of one
/// mip level, tightly packed.
pub fn subresource(&self, mip_level: u32, index: u32) -> &[u8] {
let layouts = &self.layouts[..mip_level as usize + 1];
let (layout, preceding) = layouts.split_last().unwrap();
assert!(
index < layout.size.depth_or_array_layers,
"mip level {mip_level} has {} array layers or depth slices, asked for {index}",
layout.size.depth_or_array_layers,
);
let size = layout.unpadded_subresource_size();
let start = preceding
.iter()
.map(MipLayout::unpadded_size)
.sum::<usize>()
+ index as usize * size;
&self.data[start..start + size]
}
}