Player: a dump holds each colour attachment its command buffer's render passes stored

A play asked to dump command buffers (--dump-command-buffers) wrote only
the buffers their encoders named, so a draw's output reached no dump. It
now writes, once a listed command buffer completed, each colour
attachment its render passes stored, as cbC-objT.bin beside the buffers'
dumps, with a cover of "-", so compare-dumps reads them unchanged: a
texture an attachment names under MTLStoreActionStore or
StoreAndMultisampleResolve, a resolve texture under MultisampleResolve or
that one, and an Unknown store action as the encoder's
setColorStoreAction:atIndex: decides it. The dump holds the parts the
passes stored (level, slice and depth plane, or the resolve's), one after
another, each laid out as a check reads a texture's first level and
slice; a part the backend cannot read (a multisample texture stored
without its resolve) is an .unread file.

Colour only: a texture of a combined depth and stencil format reads back
one aspect at a time, through a copy with that aspect's blit option,
which this read does not make. The stream doc and the command's help say
so.

The backend gains Backend::read_texture_part; the runtime's backend reads
a part as its check reads level 0 (the CPU's read, or a blit's copy of a
Private texture), the check's read unchanged.

Verified: by the jobs named in the landing report.
This commit is contained in:
Anees Iqbal committed 2026-11-23 10:20:31 -08:00
1 parent d4ca79589e
commit acda405b30
8 files changed
+462 -59

No files matched your search

@@ -76,8 +76,10 @@
//!
//! With `--dump-command-buffers LIST --dump-dir DIR`, the play also writes into `DIR`, once each
//! command buffer whose stream id `LIST` holds completed, every buffer its encoders named, with
//! the ranges of it the cover rule held covered then (`docs/REPLAY-STREAM.md`, section 10).
//! `LIST` is `FIRST..LAST` ranges (both ends held) and single ids, joined by commas.
//! the ranges of it the cover rule held covered then, and every colour attachment its render
//! passes stored, the parts of it they stored; no depth or stencil attachment
//! (`docs/REPLAY-STREAM.md`, section 10). `LIST` is `FIRST..LAST` ranges (both ends held) and
//! single ids, joined by commas.
//!
//! A check or dump of a buffer the play keeps two copies of (a Managed buffer of a stream recorded
//! without unified memory) names the copy it read: its CPU copy, as Metal's `contents` answers, or
@@ -1,13 +1,17 @@
//! The per-command-buffer compare of two plays (`docs/REPLAY-STREAM.md`, section 10).
//!
//! A play asked to dump command buffers ([`Player::dumping`](super::player::Player::dumping))
//! writes, once each listed command buffer completed, every buffer its encoders named, as three
//! kinds of file in its directory:
//! - `cb<C>-obj<O>.bin`: the buffer's bytes;
//! writes, once each listed command buffer completed, every buffer its encoders named and every
//! colour attachment its render passes stored ([`Stores`]), as these kinds of file in its
//! directory:
//! - `cb<C>-obj<O>.bin`: the buffer's bytes; a texture's, the parts of it the command buffer's
//! passes stored (a level, a slice and a depth plane each), in the order of [`Part`], each laid
//! out as a check reads a texture's first level and slice;
//! - `cb<C>-obj<O>.cover`: the ranges of it the player's cover rule (`covers.rs`) held covered
//! then, as `start..end` byte offsets joined by commas, or `-` for none;
//! - `cb<C>-obj<O>.unread`: where the backend could not read the buffer, why, in place of its
//! bytes;
//! then, as `start..end` byte offsets joined by commas, or `-` for none (always `-` for a
//! texture);
//! - `cb<C>-obj<O>.unread`: where the backend could not read the buffer or texture, why, in place
//! of its bytes (a multisample texture a pass stores without resolving it, for one);
//! - `cb<C>-obj<O>.copy`: for a buffer the play keeps two copies of, which one the bytes are
//! ([`ReadCopy::label`]): its CPU copy, or its device copy, read back.
//!
@@ -20,9 +24,15 @@
//! other are no compare of either. The summary counts the buffers compared by the copy both read.
//! A whole-object checksum is no such compare: one word under a cover would make a buffer differ,
//! and one word outside it would hide behind a cover elsewhere in the buffer.
//!
//! A dump holds colour attachments only. A depth or stencil attachment is none: a texture of a
//! combined depth and stencil format reads back only one aspect at a time, through a copy with
//! that aspect's blit option, which the dump's read of a texture part does not make.
use super::player::ReadCopy;
use std::collections::BTreeMap;
use super::stream::Call;
use super::value::{Name, Value};
use std::collections::{BTreeMap, HashMap};
use std::io;
use std::path::{Path, PathBuf};
@@ -102,6 +112,125 @@ pub(super) fn write(
std::fs::write(base.with_extension("cover"), text)
}
/// A level, slice and depth plane of a texture: the part of it a render pass attachment names
/// (`level`, `slice` and `depthPlane`, or `resolveLevel`, `resolveSlice` and
/// `resolveDepthPlane`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Part {
pub level: u64,
pub slice: u64,
pub plane: u64,
}
/// A render pass descriptor's colour attachment, as its setter records set it: its texture and
/// part, its resolve texture and part (0 for none), and its store action (`MTLStoreAction`'s raw
/// value; 0, `MTLStoreActionDontCare`, until set).
#[derive(Clone, Copy, Debug, Default)]
struct Colour {
texture: u64,
part: Part,
resolve: u64,
resolve_part: Part,
store: u64,
}
impl Colour {
/// The texture parts the attachment stores under store action `store`: its texture's under
/// `MTLStoreActionStore` and `MTLStoreActionStoreAndMultisampleResolve`, its resolve
/// texture's under `MTLStoreActionMultisampleResolve` and that one.
fn stored(&self, store: u64, out: &mut Vec<(u64, Part)>) {
if matches!(store, 1 | 3) && self.texture != 0 {
out.push((self.texture, self.part));
}
if matches!(store, 2 | 3) && self.resolve != 0 {
out.push((self.resolve, self.resolve_part));
}
}
/// `f`, a `m2v.setColorAttachment` record's map, set on the attachment: each property it
/// names; a nil one keeps what the attachment had.
fn set(&mut self, f: &[(Name, Value)]) {
for (key, value) in f {
let (object, uint) = (value.as_object(), value.as_uint());
match (&**key, object, uint) {
("texture", Some(id), _) => self.texture = id,
("resolveTexture", Some(id), _) => self.resolve = id,
("level", _, Some(v)) => self.part.level = v,
("slice", _, Some(v)) => self.part.slice = v,
("depthPlane", _, Some(v)) => self.part.plane = v,
("resolveLevel", _, Some(v)) => self.resolve_part.level = v,
("resolveSlice", _, Some(v)) => self.resolve_part.slice = v,
("resolveDepthPlane", _, Some(v)) => self.resolve_part.plane = v,
("storeAction", _, Some(v)) => self.store = v,
_ => {}
}
}
}
}
/// The colour attachments a play's render passes store: each render pass descriptor's, as its
/// `m2v.setColorAttachment` records set them (`docs/REPLAY-STREAM.md`, section 9), and each
/// render encoder's whose store action is `MTLStoreActionUnknown`, until the encoder's
/// `setColorStoreAction:atIndex:` names the action.
#[derive(Default)]
pub(super) struct Stores {
passes: HashMap<u64, BTreeMap<u64, Colour>>,
unknown: HashMap<u64, BTreeMap<u64, Colour>>,
}
impl Stores {
/// `call`, played: a colour attachment's setter record on a render pass descriptor, kept. The
/// texture parts a render pass stores where `call` makes its encoder
/// (`renderCommandEncoderWithDescriptor:`) or names an attachment's store action left unknown
/// (`setColorStoreAction:atIndex:`), into `out`.
pub(super) fn saw(&mut self, call: &Call, out: &mut Vec<(u64, Part)>) {
let uint = |at: usize| call.args.get(at).and_then(Value::as_uint);
match &*call.selector {
"m2v.setColorAttachment" => {
let (Some(at), Some(f)) = (uint(0), call.args.get(1).and_then(Value::as_map))
else {
return;
};
let pass = self.passes.entry(call.receiver).or_default();
pass.entry(at).or_default().set(f);
}
"renderCommandEncoderWithDescriptor:" if call.result != 0 => {
let pass = call.args.first().and_then(Value::as_object);
let Some(pass) = pass.and_then(|pass| self.passes.get(&pass)) else {
return;
};
for (&at, colour) in pass {
match colour.store {
4 => {
let unknown = self.unknown.entry(call.result).or_default();
unknown.insert(at, *colour);
}
store => colour.stored(store, out),
}
}
}
"setColorStoreAction:atIndex:" => {
let (Some(store), Some(at)) = (uint(0), uint(1)) else {
return;
};
let unknown = self.unknown.get_mut(&call.receiver);
if let Some(colour) = unknown.and_then(|unknown| unknown.remove(&at)) {
colour.stored(store, out);
}
}
"endEncoding" => {
self.unknown.remove(&call.receiver);
}
_ => {}
}
}
/// Object `id` released: a render pass descriptor's attachments are dropped.
pub(super) fn released(&mut self, id: u64) {
self.passes.remove(&id);
}
}
/// One buffer's dump in two plays that differ outside every cover, or in length.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Difference {
@@ -20,7 +20,7 @@ mod value;
pub use compare::{compare_plays, shown_differences};
pub use covers::SlotStage;
pub use dumps::{compare_dumps, CommandBufferList, Comparison, Difference};
pub use dumps::{compare_dumps, CommandBufferList, Comparison, Difference, Part};
pub use new_runtime::{judged_records, Ended, ManagedCopies, NewRuntime, VideoHandle};
pub use pixels::Shape;
pub use player::WAIT_COMPLETED;
@@ -33,6 +33,7 @@ pub use judged::judged_records;
use super::args::{arg, data, metal, option_sets, refuse, uint, variant, Fields};
use super::covers::SlotStage;
use super::dumps::Part;
use super::pixels::Shape;
use super::player::{Backend, Counters, Made, PlayError, ReadCopy};
use super::prepass::{Ahead, AheadGrid};
@@ -1304,15 +1305,44 @@ impl NewRuntime {
copied
}
/// The texels of `texture`, a Private texture, which the CPU does not reach: a blit copies
/// its first level's first slice into a Shared buffer of the play's own, laid out as
/// `texture_bytes` reads a texture the CPU reaches, on the play's read queue (`reads`), and
/// the read waits for it.
fn private_texture_bytes(&mut self, texture: &rt::Texture) -> Result<Vec<u8>, rt::Error> {
let d = texture.descriptor();
let raw = u64::from(d.pixel_format.as_raw());
let query = rt::TextureLevelQuery::plane_2d(raw, d.width.into(), d.height.into());
let level = self.device.texture_level_info(&query);
/// The texels of `part` of `texture`, for `selector`'s read: a blit's copy of a Private
/// texture's (`private_texture_bytes`), the CPU's read of any other's (`texture_bytes`).
fn texture_part(
&mut self,
texture: &rt::Texture,
part: Part,
selector: &str,
) -> Result<Vec<u8>, PlayError> {
let narrow = |v: u64| {
u32::try_from(v).map_err(|_| PlayError::Refused {
selector: selector.into(),
why: format!("a texture part past u32: {part:?}"),
})
};
let part = [
narrow(part.level)?,
narrow(part.slice)?,
narrow(part.plane)?,
];
let bytes = match texture.descriptor().storage_mode {
rt::StorageMode::Private => self.private_texture_bytes(texture, part),
_ => texture_bytes(&self.device, texture, part),
};
bytes.map_err(|error| PlayError::Runtime {
selector: selector.into(),
error: error.to_string(),
})
}
/// The texels of `part` of `texture`, a Private texture, which the CPU does not reach: a blit
/// copies them into a Shared buffer of the play's own, laid out as `texture_bytes` reads a
/// texture the CPU reaches, on the play's read queue (`reads`), and the read waits for it.
fn private_texture_bytes(
&mut self,
texture: &rt::Texture,
part: [u32; 3],
) -> Result<Vec<u8>, rt::Error> {
let (level, place, size) = part_layout(&self.device, texture, part);
let length = level.bytes_per_image;
if length == 0 {
return Ok(Vec::new());
@@ -1326,17 +1356,12 @@ impl NewRuntime {
let into = self.device.new_buffer(block.id, 0, length, None)?;
let command_buffer = queue.command_buffer()?;
let mut blit = command_buffer.blit_command_encoder()?;
let from = rt::TexturePlace {
slice: 0,
level: 0,
origin: [0; 3],
};
let layout = rt::BufferLayout {
offset: 0,
bytes_per_row: level.bytes_per_row,
bytes_per_image: level.bytes_per_image,
};
blit.copy_from_texture_to_buffer(texture, from, [d.width, d.height, 1], &into, layout)?;
blit.copy_from_texture_to_buffer(texture, place, size, &into, layout)?;
blit.end_encoding();
command_buffer.commit()?;
command_buffer.wait_until_completed()?;
@@ -2497,23 +2522,56 @@ impl NewRuntime {
}
}
/// A texture's bytes for a check: its first level and slice, the rows and the image as far apart as
/// Metal's level info puts them, the bytes between rows zero.
fn texture_bytes(device: &rt::Device, texture: &rt::Texture) -> Result<Vec<u8>, rt::Error> {
let d = texture.descriptor();
let raw = u64::from(d.pixel_format.as_raw());
let query = rt::TextureLevelQuery::plane_2d(raw, d.width.into(), d.height.into());
let level = device.texture_level_info(&query);
/// A texture's bytes of `part`, its level, slice and depth plane (its first level and slice for a
/// check): the part's rows and image as far apart as Metal's level info puts them, the bytes
/// between rows zero.
fn texture_bytes(
device: &rt::Device,
texture: &rt::Texture,
part: [u32; 3],
) -> Result<Vec<u8>, rt::Error> {
let (level, place, size) = part_layout(device, texture, part);
let mut bytes = vec![0; level.bytes_per_image as usize];
let region = rt::Region {
origin: [0; 3],
size: [d.width, d.height, 1],
origin: place.origin,
size,
};
let (row, image) = (level.bytes_per_row, level.bytes_per_image);
texture.get_bytes(&mut bytes, row, image, region, 0, 0)?;
texture.get_bytes(&mut bytes, row, image, region, place.level, place.slice)?;
Ok(bytes)
}
/// How `[level, slice, plane]` of `texture` lies: Metal's level info of the level, one image
/// deep, and the place and size of its texels, the depth plane as the place's `z`.
fn part_layout(
device: &rt::Device,
texture: &rt::Texture,
[level, slice, plane]: [u32; 3],
) -> (rt::TextureLevelInfo, rt::TexturePlace, [u32; 3]) {
let d = texture.descriptor();
let query = rt::TextureLevelQuery {
level: level.into(),
..rt::TextureLevelQuery::plane_2d(
u64::from(d.pixel_format.as_raw()),
d.width.into(),
d.height.into(),
)
};
let info = device.texture_level_info(&query);
let place = rt::TexturePlace {
slice,
level,
origin: [0, 0, plane],
};
// A level is no wider or taller than the texture.
let size = [
u32::try_from(info.width).unwrap_or(d.width),
u32::try_from(info.height).unwrap_or(d.height),
1,
];
(info, place, size)
}
/// `bytes` into `buffer` at `offset`, through its mapping.
fn write_into(buffer: &rt::Buffer, offset: u64, bytes: &[u8]) -> Result<(), PlayError> {
if bytes.is_empty() {
@@ -2929,14 +2987,7 @@ impl Backend for NewRuntime {
};
if let Some(Object::Texture(texture)) = self.objects.get(&object) {
let texture = texture.clone();
let bytes = match texture.descriptor().storage_mode {
rt::StorageMode::Private => self.private_texture_bytes(&texture),
_ => texture_bytes(&self.device, &texture),
};
return bytes.map_err(|error| PlayError::Runtime {
selector: "m2v.check".into(),
error: error.to_string(),
});
return self.texture_part(&texture, Part::default(), "m2v.check");
}
// The CPU's bytes of a buffer with a second copy, as Metal's `contents` answers them: its
// aside from a read-back of a stream that records its announced bytes to its next
@@ -2977,6 +3028,19 @@ impl Backend for NewRuntime {
Ok(unsafe { std::slice::from_raw_parts(contents.as_ptr(), length) }.to_vec())
}
fn read_texture_part(&mut self, object: u64, part: Part) -> Result<Vec<u8>, PlayError> {
match self.objects.get(&object) {
Some(Object::Texture(texture)) => {
let texture = texture.clone();
self.texture_part(&texture, part, "m2v.dump")
}
_ => Err(PlayError::Refused {
selector: "m2v.dump".into(),
why: "no texture".into(),
}),
}
}
fn read_copy(&self, object: u64) -> Option<ReadCopy> {
// A Managed buffer of a two-copy stream: the runtime's device copy and the consumer's
// bytes, or the player's own CPU copy beside the device's one copy.
@@ -7,7 +7,7 @@
use super::addresses::AddressMap;
use super::covers::{self, Covers, SlotStage};
use super::dumps;
use super::dumps::{self, Part};
use super::heaps::{placement_heap, placement_offset, places_texture, relay, Layout, Placements};
use super::pixels::Shape;
use super::prepass::{Ahead, Prepass};
@@ -102,6 +102,15 @@ pub trait Backend {
fn read_copy(&self, _object: u64) -> Option<ReadCopy> {
None
}
/// The bytes of `part` of texture `object`, laid out as [`read`](Self::read) lays out a
/// texture's first level and slice: what a render pass attachment stored there, for a dump
/// ([`Player::dumping`]). Refused on a backend that reads no part of a texture.
fn read_texture_part(&mut self, object: u64, part: Part) -> Result<Vec<u8>, PlayError> {
Err(PlayError::Refused {
selector: "m2v.dump".into(),
why: format!("no read of a texture's part (#{object}, {part:?})"),
})
}
/// The pixel format and size of texture `object` as the backend made it, which a picture
/// of its bytes (`read`) is read by; none for an object that is no texture of the backend's.
fn texture_shape(&mut self, _object: u64) -> Option<Shape> {
@@ -999,6 +1008,10 @@ struct Dump {
encoders: HashMap<u64, u64>,
/// The buffers each listed command buffer's encoders named, until it completes.
named: HashMap<u64, BTreeSet<u64>>,
/// The colour attachments the play's render passes store.
stores: dumps::Stores,
/// The texture parts each listed command buffer's render passes stored, until it completes.
stored: HashMap<u64, BTreeMap<u64, BTreeSet<Part>>>,
/// The listed command buffers that completed and are not yet written out.
completed: Vec<u64>,
}
@@ -1253,7 +1266,8 @@ impl<'b, B: Backend> Player<'b, B> {
/// The player that, once each command buffer whose stream id `command_buffers` holds
/// completed, writes every buffer its encoders named into `dir`, with the ranges of it the
/// cover rule held covered then (`dumps.rs`): the per-command-buffer compare of two plays
/// cover rule held covered then, and every colour attachment its render passes stored, the
/// parts of it they stored (`dumps.rs`): the per-command-buffer compare of two plays
/// ([`compare_dumps`](super::compare_dumps)) reads them. A listed command buffer's buffers are
/// read after the wait that saw it complete, before the next call plays.
pub fn dumping(mut self, command_buffers: dumps::CommandBufferList, dir: PathBuf) -> Self {
@@ -1263,6 +1277,8 @@ impl<'b, B: Backend> Player<'b, B> {
buffers: HashSet::new(),
encoders: HashMap::new(),
named: HashMap::new(),
stores: dumps::Stores::default(),
stored: HashMap::new(),
completed: Vec::new(),
});
self
@@ -1656,6 +1672,7 @@ impl<'b, B: Backend> Player<'b, B> {
self.stale.released(call.receiver);
if let Some(dump) = &mut self.dump {
dump.buffers.remove(&call.receiver);
dump.stores.released(call.receiver);
}
self.release(call.receiver)
}
@@ -1663,12 +1680,15 @@ impl<'b, B: Backend> Player<'b, B> {
}
}
/// What a dump (`dumping`) keeps of `call`, played: a buffer it made, an encoder a listed
/// command buffer made, and the buffers such an encoder's call names.
/// What a dump (`dumping`) keeps of `call`, played: a buffer it made, a render pass
/// descriptor's colour attachment it set, an encoder a listed command buffer made, the
/// buffers such an encoder's call names and the texture parts its render pass stores.
fn dump_saw(&mut self, call: &Call) {
let Some(dump) = &mut self.dump else {
return;
};
let mut stored = Vec::new();
dump.stores.saw(call, &mut stored);
let selector = &*call.selector;
// The host's padded and exported buffers reach here as `newBufferWithLength:options:`
// (`plain`); a buffer in a block is `m2v.newBufferInBlock:offset:length:options:`.
@@ -1695,32 +1715,54 @@ impl<'b, B: Backend> Player<'b, B> {
covers::named(&call.args, &mut objects);
let named = dump.named.entry(command_buffer).or_default();
named.extend(objects.into_iter().filter(|o| dump.buffers.contains(o)));
if !stored.is_empty() {
let parts = dump.stored.entry(command_buffer).or_default();
for (texture, part) in stored {
parts.entry(texture).or_default().insert(part);
}
}
}
/// Write out the listed command buffers that completed (`dumping`): each buffer they named,
/// read now, and its covered ranges now.
/// read now, and its covered ranges now; each colour attachment their render passes stored,
/// the parts of it they stored, read now.
fn dump_completed(&mut self, left_out: &mut Counters) -> Result<(), PlayError> {
let Some(dump) = &mut self.dump else {
return Ok(());
};
let dir = dump.dir.clone();
let mut buffers = Vec::new();
let mut textures = Vec::new();
while let Some(command_buffer) = dump.completed.pop() {
dump.encoders.retain(|_, of| *of != command_buffer);
let named = dump.named.remove(&command_buffer).unwrap_or_default();
buffers.extend(named.into_iter().map(|object| (command_buffer, object)));
let stored = dump.stored.remove(&command_buffer).unwrap_or_default();
textures.extend(
stored
.into_iter()
.map(|(t, parts)| (command_buffer, t, parts)),
);
}
let failed = |command_buffer: u64, object: u64| {
let dir = dir.display();
move |error: std::io::Error| {
PlayError::Dump(format!("{dir}: cb #{command_buffer} #{object}: {error}"))
}
};
for (command_buffer, object) in buffers {
let covered = self.covers.ranges(object);
let bytes = self.uncounted(left_out, |player| player.read_back(object));
let bytes = bytes.as_deref().map_err(|error| error.to_string());
let copy = self.backend.read_copy(object);
dumps::write(&dir, command_buffer, object, bytes, &covered, copy).map_err(|error| {
PlayError::Dump(format!(
"{}: cb #{command_buffer} #{object}: {error}",
dir.display()
))
})?;
dumps::write(&dir, command_buffer, object, bytes, &covered, copy)
.map_err(failed(command_buffer, object))?;
}
for (command_buffer, texture, parts) in textures {
let bytes = self.uncounted(left_out, |player| player.read_parts(texture, &parts));
let bytes = bytes.as_deref().map_err(|error| error.to_string());
dumps::write(&dir, command_buffer, texture, bytes, &[], None)
.map_err(failed(command_buffer, texture))?;
}
Ok(())
}
@@ -2193,6 +2235,20 @@ impl<'b, B: Backend> Player<'b, B> {
bytes
}
/// The bytes of `parts` of texture `texture` on the backend, one after another in their
/// order, timed (`Times::read`).
fn read_parts(&mut self, texture: u64, parts: &BTreeSet<Part>) -> Result<Vec<u8>, PlayError> {
let began = std::time::Instant::now();
let mut bytes = Vec::new();
let read = (parts.iter()).try_for_each(|&part| {
let read = self.backend.read_texture_part(texture, part)?;
bytes.extend(read);
Ok(())
});
self.times.read += since(began);
read.map(|()| bytes)
}
/// The runtime's counters now, timed (`Times::count`).
fn counters(&mut self) -> Counters {
let began = std::time::Instant::now();
@@ -112,14 +112,16 @@
//! digests on, each modules line ends in its state's content digest: three contents, three
//! digests, which a second play on a device of its own, on two threads, writes again; without
//! them, no modules line carries one.
//! - A dump of a listed command buffer holds the colour attachment its pass stored: the draw's
//! Private target, read back through a blit, green at every texel, and covering nothing.
//!
//! The runtime's device is opened behind the hang tripwire, as every device open in this crate
//! is (`gpu.rs`), its kernels kept in a cache the test owns ([`ScratchCache`]).
use crate::gpu::{self, DeviceType};
use crate::replay::{
Backend, NewRuntime, PlayError, Player, ReadCopy, Report, StreamReader, StreamWriter, Value,
WAIT_COMPLETED,
Backend, CommandBufferList, NewRuntime, PlayError, Player, ReadCopy, Report, StreamReader,
StreamWriter, Value, WAIT_COMPLETED,
};
use crate::ScratchDir;
use metal2vulkan_devtools::metallib::{metallib, wrap, MtlbFunction};
@@ -529,6 +531,30 @@ fn a_draw_into_a_pass_plays_on_the_new_runtime() {
assert_eq!(report.first_skip, None);
}
/// A dump of the draw's command buffer (#12) holds its pass's colour attachment (#7, stored), a
/// Private texture the play reads back through a blit: the triangle's green at every texel, its
/// rows 16 bytes apart as a check reads them, and no cover.
#[test]
fn a_dump_holds_the_colour_attachment_a_pass_stored() {
let dir = ScratchDir::new("rt-replay-dump-colour").unwrap();
let green: Vec<u8> = [0u8, 255, 0, 255].repeat(16);
let path = draw_into_a_pass(&dir, &green, Then::Nothing);
let dumps = ScratchDir::new("rt-replay-dump-colour-out").unwrap();
let cache = ScratchCache::new().unwrap();
let mut backend = NewRuntime::new(rt_device(cache.path()), gpu::TEST_DEVICE).unwrap();
let mut reader = StreamReader::open(&[path], None).unwrap();
let listed = CommandBufferList::parse("12").unwrap();
let player = Player::new(&mut backend).dumping(listed, dumps.path().to_path_buf());
let (report, ended) = player.play(&mut reader);
for line in report.lines() {
eprintln!("REPLAY dump-colour {line}");
}
ended.unwrap();
let read = |name: &str| std::fs::read(dumps.path().join(name)).unwrap();
assert_eq!(read("cb12-obj7.bin"), green);
assert_eq!(read("cb12-obj7.cover"), b"-");
}
/// A play's report carries the runtime's stage sums among its executed counters, with the part
/// from scheduling to GPU start under earlier spans and the completion thread's steps, which add
/// up to the span from GPU end to handlers, and its stage histograms as each frame ended and at
@@ -4,7 +4,7 @@
use super::addresses::AddressMap;
use super::compare::{compare_plays, shown_differences};
use super::covers::SlotStage;
use super::dumps::{compare_dumps, CommandBufferList, Difference};
use super::dumps::{compare_dumps, CommandBufferList, Difference, Part};
use super::new_runtime::indices::Indices;
use super::new_runtime::places::Waiting;
use super::new_runtime::second::merge;
@@ -579,6 +579,11 @@ impl Backend for Kept {
self.read_copies.get(&object).copied()
}
fn read_texture_part(&mut self, object: u64, part: Part) -> Result<Vec<u8>, PlayError> {
let words = [object, part.level, part.slice, part.plane];
Ok(words.iter().flat_map(|word| word.to_le_bytes()).collect())
}
fn resource_id(&mut self, object: u64) -> Result<Option<u64>, PlayError> {
self.asked.push(object);
Ok(self.ids.get(&object).copied())
@@ -3401,6 +3406,117 @@ fn a_listed_command_buffer_dumps_every_buffer_it_names_whatever_made_it() {
assert_eq!(names, wanted);
}
/// A listed command buffer's dump holds each colour attachment its render passes stored, the parts
/// of it they stored one after another, and no other attachment: of command buffer #20's two
/// passes, the first stores texture #8 (attachment 0, `MTLStoreActionStore`), not #9 (1,
/// `MTLStoreActionDontCare`), the resolve texture #11's level 1 and slice 2 of multisample #10,
/// not #10 itself (2, `MTLStoreActionMultisampleResolve`), #12's level 1 by the encoder's
/// `setColorStoreAction:atIndex:` (3, `MTLStoreActionUnknown`), and no depth attachment (#13);
/// the second stores #8's level 2 and depth plane 3. A texture's dump covers nothing.
#[test]
fn a_listed_command_buffer_dumps_the_colour_attachments_its_render_passes_store() {
let dir = ScratchDir::new("dumps-stores").unwrap();
let (_, ended) = dumped(&mut Kept::default(), dir.path(), |w| {
w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?;
w.call("newCommandQueue", 1, 6, &[], &[])?;
w.call("m2v.textureDescriptor", 0, 7, &[map(&[])], &[])?;
for texture in 8..=13 {
w.call(
"newTextureWithDescriptor:",
1,
texture,
&[Value::Object(7)],
&[],
)?;
}
let colour = |w: &mut StreamWriter<File>, pass, at, set: &[(&str, Value)]| {
let args = [Value::Uint(at), map(set)];
w.call("m2v.setColorAttachment", pass, 0, &args, &[])
};
w.call("MTLRenderPassDescriptor.new", 0, 30, &[], &[])?;
let stored = [
("texture", Value::Object(8)),
("storeAction", Value::Uint(1)),
];
colour(w, 30, 0, &stored)?;
let dropped = [
("texture", Value::Object(9)),
("storeAction", Value::Uint(0)),
];
colour(w, 30, 1, &dropped)?;
let resolved = [
("texture", Value::Object(10)),
("resolveTexture", Value::Object(11)),
("resolveLevel", Value::Uint(1)),
("resolveSlice", Value::Uint(2)),
("storeAction", Value::Uint(2)),
];
colour(w, 30, 2, &resolved)?;
let unknown = [
("texture", Value::Object(12)),
("level", Value::Uint(1)),
("storeAction", Value::Uint(4)),
];
colour(w, 30, 3, &unknown)?;
let depth = map(&[
("texture", Value::Object(13)),
("storeAction", Value::Uint(1)),
]);
w.call("m2v.setDepthAttachment", 30, 0, &[depth], &[])?;
w.call("MTLRenderPassDescriptor.new", 0, 31, &[], &[])?;
let level = [
("texture", Value::Object(8)),
("level", Value::Uint(2)),
("depthPlane", Value::Uint(3)),
("storeAction", Value::Uint(1)),
];
colour(w, 31, 0, &level)?;
w.call("commandBuffer", 6, 20, &[], &[])?;
w.call(
"renderCommandEncoderWithDescriptor:",
20,
21,
&[Value::Object(30)],
&[],
)?;
let store = [Value::Uint(1), Value::Uint(3)];
w.call("setColorStoreAction:atIndex:", 21, 0, &store, &[])?;
w.call("endEncoding", 21, 0, &[], &[])?;
w.call(
"renderCommandEncoderWithDescriptor:",
20,
22,
&[Value::Object(31)],
&[],
)?;
w.call("endEncoding", 22, 0, &[], &[])?;
w.call("commit", 20, 0, &[], &[])
});
ended.unwrap();
let mut names: Vec<String> = std::fs::read_dir(dir.path())
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
let dumps = ["cb20-obj11", "cb20-obj12", "cb20-obj8"];
let wanted: Vec<String> = (dumps.iter())
.flat_map(|dump| [format!("{dump}.bin"), format!("{dump}.cover")])
.collect();
assert_eq!(names, wanted);
let read = |name: &str| std::fs::read(dir.path().join(name)).unwrap();
let parts = |parts: &[[u64; 4]]| -> Vec<u8> {
(parts.iter().flatten())
.flat_map(|word| word.to_le_bytes())
.collect()
};
assert_eq!(read("cb20-obj8.bin"), parts(&[[8, 0, 0, 0], [8, 2, 0, 3]]));
assert_eq!(read("cb20-obj11.bin"), parts(&[[11, 1, 2, 0]]));
assert_eq!(read("cb20-obj12.bin"), parts(&[[12, 1, 0, 0]]));
for dump in dumps {
assert_eq!(read(&format!("{dump}.cover")), b"-");
}
}
/// Two plays alike agree; a dump one play has alone is reported.
#[test]
fn the_dump_compare_agrees_on_alike_plays_and_reports_a_dump_one_play_lacks() {
+12 -2
View File
@@ -1127,8 +1127,18 @@ it covered then (as above, `start..end` byte offsets joined by commas, or `-`),
`cbC-objO.unread` in place of the bytes where the backend could not read it, and for a buffer with
two copies `cbC-objO.copy`, which copy the bytes are: `CPU copy` or `device copy, read back`
(above). `LIST` is `FIRST..LAST` ranges (both ends held) and single ids, joined by commas, such as
`20..29,31`; anything else stops the play before it starts. `command-replay
compare-dumps --a DIR --b DIR` compares two plays' dumps word by word (4 bytes), leaving out a word
`20..29,31`; anything else stops the play before it starts. It writes too each colour attachment
the command buffer's render passes stored: a texture its attachment names under
`MTLStoreActionStore` or `MTLStoreActionStoreAndMultisampleResolve`, and a resolve texture under
`MTLStoreActionMultisampleResolve` or that one, an `MTLStoreActionUnknown` decided by the
encoder's `setColorStoreAction:atIndex:`. `cbC-objT.bin` holds the texture's parts the passes
stored, each a level, a slice and a depth plane (`level`, `slice` and `depthPlane`, or the
resolve's), one after another by level, then slice, then plane, each laid out as a check reads a
texture's first level and slice; its `cbC-objT.cover` is `-`, and `cbC-objT.unread` replaces the
bytes where the backend could not read a part (a multisample texture stored without its resolve,
for one). A depth or stencil attachment is not written: a texture of a combined depth and
stencil format reads back one aspect at a time, through a copy with that aspect's blit option,
which this read does not make. `command-replay compare-dumps --a DIR --b DIR` compares two plays' dumps word by word (4 bytes), leaving out a word
wholly inside a range either play held covered, and prints `differs cb #C obj #O: N words outside every cover, the first word
W; M covered; lengths A and B` for each buffer that differs outside every cover, `only in a|b:
cbC-objO` for a dump one play lacks, `unread in a|b: cbC-objO: WHY`, `copies differ: cbC-objO: a