Merge local/replay

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 21:41:29 -06:00
commit dd281166f9
7 files changed
+2111 -29

No files matched your search

+121
View File
@@ -62,6 +62,16 @@ pub(crate) struct Replay {
/// One ExecuteCommandLists for the whole frame.
#[arg(long)]
one_submit: bool,
/// Let copies of what the CPU wrote also overwrite what the card wrote in
/// the replay (as the recorded commands say).
#[arg(long)]
no_merge: bool,
/// A full wait after every draw, dispatch, copy and clear.
#[arg(long)]
wait_all: bool,
/// Each list sent on its own, and waited for.
#[arg(long)]
wait_lists: bool,
/// Run only these lists, by their place in the frame (`3..7`, or `5`);
/// of the others only barriers.
#[arg(long)]
@@ -70,6 +80,45 @@ pub(crate) struct Replay {
/// (may be given several times).
#[arg(long = "skip-shader")]
skip_shader: Vec<String>,
/// Find the commands that make identical runs differ: each list is run
/// this often from the same memory.
#[arg(long, num_args = 0..=1, default_missing_value = "3")]
diverge: Option<u32>,
/// Find where the picture's variants are decided: from each list on, the
/// rest of the frame is run this often from the same memory.
#[arg(long, num_args = 0..=1, default_missing_value = "5")]
diverge_picture: Option<u32>,
/// Run each draw of one list (--lists) whose pipeline's name has this in
/// it alone, --diverge times: how many outcomes it has.
#[arg(long)]
draws: Option<String>,
/// Say which lists (with --lists: commands) change words of buffers:
/// `<resource>:<offset>:<bytes>` (hexadecimal; repeatable).
#[arg(long)]
watch: Vec<String>,
/// With --diverge-picture and one list in --lists: its commands (`0..900`)
/// and how many are stepped over at a time.
#[arg(long)]
commands: Option<String>,
#[arg(long, default_value_t = 1)]
step: usize,
/// With --diverge and --diverge-picture: only these lists (`3..7`).
#[arg(long)]
lists: Option<String>,
/// With --diverge: the most commands named of one list.
#[arg(long, default_value_t = 4)]
roots: u32,
/// Name resources the frame changes that the replay does not put back.
#[arg(long)]
check_written: bool,
/// Name what the heap slots hold that a command's constants name:
/// `<list>:<command>`.
#[arg(long)]
slots: Option<String>,
/// Only write the DXIL of pipelines with this in their name to the
/// capture's `shaders` folder.
#[arg(long)]
dump: Option<String>,
/// Use the D3D12 debug layer (slow).
#[arg(long)]
debug_layer: bool,
@@ -84,6 +133,12 @@ fn range(text: &str) -> Option<(u32, u32)> {
}
pub(crate) fn run(r: Replay) -> Result<()> {
if let Some(text) = &r.dump {
for line in play::dump(&r.folder, text)? {
println!("{line}");
}
return Ok(());
}
let only = match &r.only {
Some(text) => Some(
range(text)
@@ -107,11 +162,77 @@ pub(crate) fn run(r: Replay) -> Result<()> {
skip_clamps: r.skip_clamps,
skip_hash_passes: r.skip_hash_passes,
one_submit: r.one_submit,
merge: !r.no_merge,
wait_all: r.wait_all,
wait_lists: r.wait_lists,
only,
skip_shaders: r.skip_shader,
compare: r.compare,
debug: r.debug_layer,
};
if let Some(text) = &r.slots {
let (list, command) = text
.split_once(':')
.and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?)))
.with_context(|| format!("--slots {text}: not <list>:<command>"))?;
let player = play::Player::load(&r.folder, &options)?;
return player.slots(list, command, &mut |line| println!("{line}"));
}
if r.check_written {
let mut player = play::Player::load(&r.folder, &options)?;
return player.check_written(&mut |line| println!("{line}"));
}
let mut watched = Vec::new();
for text in &r.watch {
let mut n = text
.split(':')
.map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16));
let mut next = || {
n.next()
.and_then(Result::ok)
.with_context(|| format!("--watch {text}"))
};
let id = text
.split(':')
.next()
.and_then(|p| p.parse().ok())
.with_context(|| format!("--watch {text}"))?;
let _ = next();
watched.push((id, next()?, next()?));
}
if let Some(runs) = r
.diverge
.or(r.diverge_picture)
.or((!watched.is_empty()).then_some(2))
{
let lists = match &r.lists {
Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?),
None => None,
};
let search = play::diverge::Search {
runs: runs.max(2),
lists,
roots: r.roots,
wait_all: options.wait_all,
options: options.clone(),
};
let mut player = play::Player::load(&r.folder, &options)?;
if !watched.is_empty() {
return player.watch(&search, &watched, &mut |line| println!("{line}"));
}
if let Some(text) = &r.draws {
return player.diverge_draws(&search, text, &mut |line| println!("{line}"));
}
if r.diverge_picture.is_some() {
let commands = match &r.commands {
Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?),
None => None,
};
return player
.diverge_picture(&search, commands, r.step, &mut |line| println!("{line}"));
}
return player.diverge(&search, &mut |line| println!("{line}"));
}
let reports = play::replay(&r.folder, &options)?;
for (what, report) in &reports {
println!("{}", report.text(what));
+253 -15
View File
@@ -29,6 +29,9 @@ use super::wire::{
self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot,
};
pub mod diverge;
mod merge;
/// The name of the argument clamp's pipeline, by which its passes are
/// recognised.
pub const CLAMP: &str = "victory: argument clamp";
@@ -67,6 +70,13 @@ pub struct Options {
pub skip_clamps: bool,
pub skip_hash_passes: bool,
pub one_submit: bool,
/// Copies of what the CPU wrote leave alone what the card wrote in this
/// run (`merge`).
pub merge: bool,
/// A full wait after every command that works.
pub wait_all: bool,
/// Each list sent on its own, and waited for.
pub wait_lists: bool,
/// Run only these lists (by their place in the frame).
pub only: Option<(u32, u32)>,
/// Skip what runs a pipeline whose name or shader hash has one of
@@ -92,6 +102,9 @@ impl Default for Options {
skip_clamps: false,
skip_hash_passes: false,
one_submit: false,
merge: true,
wait_all: false,
wait_lists: false,
only: None,
skip_shaders: Vec::new(),
compare: false,
@@ -107,6 +120,8 @@ impl Options {
|| self.skip_clamps
|| self.skip_hash_passes
|| self.one_submit
|| self.wait_all
|| self.wait_lists
|| self.only.is_some()
|| !self.skip_shaders.is_empty()
}
@@ -119,6 +134,8 @@ impl Options {
skip_clamps: false,
skip_hash_passes: false,
one_submit: false,
wait_all: false,
wait_lists: false,
only: None,
skip_shaders: Vec::new(),
..self.clone()
@@ -144,6 +161,8 @@ pub struct Report {
/// Against the presented picture: dB (infinite: the same), and whether
/// its bytes are the same.
pub picture: Option<(f64, bool)>,
/// Of each loop's picture: dB against the presented one, and its hash.
pub pictures: Vec<(f64, String)>,
/// Things to know: from the capture and the replay.
pub notes: Vec<String>,
}
@@ -205,6 +224,20 @@ impl Report {
}
None => {}
}
if self.pictures.len() > 1 {
let all: Vec<String> = self
.pictures
.iter()
.map(|(db, hash)| format!("{db:.1} dB {}", &hash[..8]))
.collect();
let kinds: HashSet<&String> = self.pictures.iter().map(|p| &p.1).collect();
let _ = writeln!(
t,
" pictures of the loops: {} different: {}",
kinds.len(),
all.join(", ")
);
}
for n in &self.notes {
let _ = writeln!(t, " note: {n}");
}
@@ -241,6 +274,43 @@ pub fn find(folder: &Path) -> Result<PathBuf> {
.ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display()))
}
/// Writes the DXIL of the pipelines whose name has `text` in it to `shaders`
/// in the capture, and the pipelines' descriptions; what was written.
pub fn dump(folder: &Path, text: &str) -> Result<Vec<String>> {
let folder = find(folder)?;
let frame = Frame::read(&folder.join("frame.bin"))?;
let file = File::open(folder.join("shaders.bin"))?;
let to = folder.join("shaders");
std::fs::create_dir_all(&to)?;
let mut out = Vec::new();
for p in frame.pipelines.iter().filter(|p| p.name.contains(text)) {
let mut line = format!("pipeline {} {}:", p.id, p.name);
for part in &p.parts {
match part {
wire::Part::Code { kind, blob } => {
let c = &frame.codes[*blob as usize];
let mut bytes = vec![0; c.len as usize];
read_at(&file, &mut bytes, c.at)?;
let name: String = c.hash[..8].iter().map(|b| format!("{b:02x}")).collect();
std::fs::write(to.join(format!("{name}.dxil")), bytes)?;
let _ = write!(line, " {kind}={name}.dxil");
}
wire::Part::Root { root } => {
if let Some((_, blob)) = frame.roots.iter().find(|r| r.0 == *root) {
std::fs::write(to.join(format!("root-{root}.bin")), &blob.0)?;
}
let _ = write!(line, " root-{root}.bin");
}
other => {
let _ = write!(line, " {other:?}");
}
}
}
out.push(line);
}
Ok(out)
}
/// Loads a capture and runs it: the whole of `victory replay`. The reports,
/// with what each is of.
pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>> {
@@ -307,11 +377,18 @@ pub struct Player {
/// States at the start of the frame and after it.
start: HashMap<u32, Vec<u32>>,
end: HashMap<u32, Vec<u32>>,
/// For `Options::merge`.
merger: Option<merge::Merger>,
merging: bool,
/// Resources the card may write in the frame.
card_writes: HashSet<u32>,
/// The results of clamp passes ([`RESULTS`]).
results: Option<ID3D12Resource>,
commands: Vec<Vec<Cmd>>,
/// Resources in the states of the start (not those of the end).
fresh: bool,
/// States as the last run left them (`diverge`).
at: States,
notes: Vec<String>,
}
@@ -370,9 +447,13 @@ impl Player {
delta_parts: Vec::new(),
start: HashMap::new(),
end: HashMap::new(),
merger: None,
merging: false,
card_writes: HashSet::new(),
results: None,
commands,
fresh: true,
at: States::default(),
notes: frame
.notes
.iter()
@@ -395,12 +476,22 @@ impl Player {
step("descriptors", &mut at);
player.load_contents()?;
step("contents", &mut at);
player.make_masters()?;
player.make_masters(options.buffers)?;
step("copies to restore from", &mut at);
let steps: Vec<String> = steps
.iter()
.map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64()))
.collect();
if let Some([budget, used, pc]) = player.memory() {
let over = if used + 256 > budget {
": over the budget, so the system moves memory to the PC's and the times are not the card's"
} else {
""
};
player.notes.push(format!(
"{used} MB of the card's memory used, budget {budget} MB; {pc} MB of the PC's{over}"
));
}
player.notes.push(format!(
"loaded in {:.1} s: {}",
began.elapsed().as_secs_f64(),
@@ -1354,7 +1445,7 @@ impl Player {
}
/// Copies of what the frame changes; and the states it leaves.
fn make_masters(&mut self) -> Result<()> {
fn make_masters(&mut self, buffers: Buffers) -> Result<()> {
let mut states = States::default();
for r in &self.frame.resources {
if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
@@ -1386,6 +1477,7 @@ impl Player {
.filter(|r| r.state.iter().any(|s| s & WRITE != 0))
.map(|r| r.id)
.collect();
let mut by_cpu: HashSet<u32> = HashSet::new();
for (i, s) in self.frame.submits.iter().enumerate() {
for &l in s.lists.iter().filter(|&&l| l != MISSING) {
for c in &self.commands[l as usize] {
@@ -1436,7 +1528,7 @@ impl Player {
}
states.decay();
if i > 0 {
written.extend(self.delta_parts[i].iter().map(|(d, _)| d.res));
by_cpu.extend(self.delta_parts[i].iter().map(|(d, _)| d.res));
}
}
// Buffers any unordered-access view names.
@@ -1469,6 +1561,8 @@ impl Player {
}
}
}
self.card_writes = written.clone();
written.extend(by_cpu);
for id in self.start.keys() {
self.end
.insert(*id, states.get(*id).unwrap_or(vec![COMMON]));
@@ -1500,7 +1594,10 @@ impl Player {
let size = unsafe { self.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes;
let room = self.room();
let buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
let pc = buffer && room.is_some_and(|room| room < size + (1 << 30));
// With all buffers in the card's memory there is no room for
// their copies as well.
let pc = buffer
&& (buffers == Buffers::Card || room.is_some_and(|room| room < size + (1 << 30)));
let props = if pc {
D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
@@ -1574,6 +1671,31 @@ impl Player {
Ok(())
}
/// The card's memory budget and use, and the use of the PC's memory, in
/// MB.
fn memory(&self) -> Option<[u64; 3]> {
let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
let mut pc = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
// SAFETY: plain queries.
unsafe {
let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
let adapter: IDXGIAdapter3 = factory
.EnumAdapterByLuid(self.device.GetAdapterLuid())
.ok()?;
adapter
.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
.ok()?;
adapter
.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut pc)
.ok()?;
}
Some([
own.Budget >> 20,
own.CurrentUsage >> 20,
pc.CurrentUsage >> 20,
])
}
/// What is free of the card's memory budget.
fn room(&self) -> Option<u64> {
let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
@@ -1628,6 +1750,13 @@ impl Player {
for (id, m) in &restored {
list.CopyResource(&objects[id].res, *m);
}
if let Some(merger) = &self.merger {
for (id, base) in &merger.bases {
if let Some((_, m)) = self.masters.iter().find(|m| m.0 == *id) {
list.CopyResource(base, m);
}
}
}
barriers(list, &back);
}
})?;
@@ -1769,7 +1898,7 @@ impl Player {
);
let built = self.build(&submits, &Options::default())?;
self.restore(true)?;
self.send(&built, false)?;
self.send(&built, &Options::default())?;
self.fresh = false;
Ok(clamps)
}
@@ -1818,10 +1947,15 @@ impl Player {
unsafe {
let mut seen = HashSet::new();
let mut after = Vec::new();
let mut merges = Vec::new();
for (d, at) in parts {
let Some(ob) = self.objects.get(&d.res) else {
continue;
};
if self.merging && self.card_writes.contains(&d.res) {
merges.push((d.res, d.at, *at, d.len));
continue;
}
open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len);
if seen.insert(d.res) {
// Back to the common state by itself, for
@@ -1830,6 +1964,11 @@ impl Player {
}
}
barriers(&open.1, &after);
if !merges.is_empty() {
self.wait_for_all(&open.1);
self.merge_all(&open.1, from.GetGPUVirtualAddress(), &merges);
self.wait_for_all(&open.1);
}
}
Some(self.close(open, &heap, &mut next, Vec::new())?)
}
@@ -1838,8 +1977,13 @@ impl Player {
let mut built = Vec::new();
for cmds in lists {
let open = self.open(&heap, &mut next)?;
let stamps =
self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next)));
let stamps = self.translate(
&open.1,
cmds,
i,
o.detailed.then_some((&heap, &mut next)),
o.wait_all,
);
built.push(self.close(open, &heap, &mut next, stamps)?);
}
steps.push((delta, built));
@@ -1979,6 +2123,7 @@ impl Player {
cmds: &[Cmd],
submit: usize,
mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>,
wait: bool,
) -> Vec<Stamp> {
let version = self.version_of.get(submit).copied().unwrap_or(0);
let clamps = self.pipelines_named(CLAMP);
@@ -2003,13 +2148,55 @@ impl Player {
.collect();
let mut stamps = Vec::new();
let mut bound = NONE;
// What the compute side has bound.
let mut compute: Vec<Cmd> = Vec::new();
for c in cmds {
if let Cmd::Pipeline { pso } = c {
bound = *pso;
}
// SAFETY: an open list; the objects are the frame's, alive with
// the player; commands the host recorded the same way.
unsafe { self.command(list, c, version) };
let merged = self.merged_copy(c);
if let Some((from, what)) = merged {
// SAFETY: an open list; live buffers; what the compute side
// of it had bound is bound again.
unsafe {
self.wait_for_all(list);
self.merge_all(list, from, &[what]);
self.wait_for_all(list);
for c in &compute {
self.command(list, c, version);
}
}
} else {
// SAFETY: an open list; the objects are the frame's, alive
// with the player; commands the host recorded the same way.
unsafe { self.command(list, c, version) };
}
match c {
Cmd::RootSignature {
graphics: false, ..
} => {
compute.retain(|c| matches!(c, Cmd::Pipeline { .. }));
compute.push(c.clone());
}
Cmd::Pipeline { .. } => {
compute.retain(|c| !matches!(c, Cmd::Pipeline { .. }));
compute.push(c.clone());
}
Cmd::Table {
graphics: false, ..
}
| Cmd::Constants {
graphics: false, ..
}
| Cmd::RootView {
graphics: false, ..
} => compute.push(c.clone()),
_ => {}
}
if wait && c.works() {
// SAFETY: an open list.
unsafe { self.wait_for_all(list) };
}
let timed = c.works() || matches!(c, Cmd::Barriers { .. });
if timed && let Some((heap, next)) = &mut stamp {
// SAFETY: as above.
@@ -2474,7 +2661,7 @@ impl Player {
}
/// Sends the frame, waits for it, and reads the timestamps.
fn send(&mut self, s: &Sends, one: bool) -> Result<Vec<u64>> {
fn send(&mut self, s: &Sends, o: &Options) -> Result<Vec<u64>> {
let cast = |l: &ID3D12GraphicsCommandList| l.cast::<ID3D12CommandList>().map(Some);
let mut submissions: Vec<Vec<Option<ID3D12CommandList>>> = Vec::new();
for (delta, lists) in &s.steps {
@@ -2489,7 +2676,7 @@ impl Player {
submissions.push(all);
}
}
if one {
if o.one_submit {
let mut all = Vec::new();
for (i, lists) in submissions.into_iter().enumerate() {
if i > 0
@@ -2504,7 +2691,14 @@ impl Player {
// SAFETY: closed lists whose last run has finished.
unsafe {
for all in &submissions {
self.worker.queue.ExecuteCommandLists(all);
if !o.wait_lists {
self.worker.queue.ExecuteCommandLists(all);
continue;
}
for l in all {
self.worker.queue.ExecuteCommandLists(&[l.clone()]);
self.worker.idle()?;
}
}
self.worker
.queue
@@ -2523,6 +2717,7 @@ impl Player {
notes: self.notes.clone(),
..Default::default()
};
self.set_merging(o.merge)?;
let clamps = if o.skip_clamps {
self.clamp_results(&mut report)?
} else {
@@ -2534,7 +2729,10 @@ impl Player {
for _ in 0..o.loops.max(1) {
self.restore(o.restore)?;
self.fresh = false;
stamps = self.send(&built, o.one_submit)?;
stamps = self.send(&built, o)?;
if let Some((db, _, hash, _)) = self.picture_now()? {
report.pictures.push((db, hash));
}
let ms = |a: u32, b: u32| {
stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
};
@@ -2566,6 +2764,10 @@ impl Player {
if o.detailed {
self.detail(&built, &stamps, o, &mut report);
}
if self.merging {
let notes = self.merge_notes(o.loops)?;
report.notes.extend(notes);
}
self.picture(o, &mut report)?;
if let Some(q) = &self.info {
report.notes.extend(debug_messages(q));
@@ -2607,6 +2809,34 @@ impl Player {
.collect();
}
/// The presented picture as it is now: dB against the recorded one,
/// whether its bytes are the same, its hash, and its pixels.
fn picture_now(&mut self) -> Result<Option<(f64, bool, String, Vec<u8>)>> {
let Some(p) = self.frame.presents.last().cloned() else {
return Ok(None);
};
let Some(bytes) = self.contents(p.res)? else {
return Ok(None);
};
let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else {
return Ok(None);
};
let mut recorded = vec![0; bytes.len()];
read_at(
&File::open(self.folder.join("present.bin"))?,
&mut recorded,
p.file,
)?;
let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default();
let hash = blake3::hash(&rgb).to_hex().to_string();
Ok(Some((
gpu::psnr(&rgb, &was),
rows_equal(&p, &bytes, &recorded),
hash,
rgb,
)))
}
/// Saves the presented picture and compares it with the recorded one.
fn picture(&mut self, o: &Options, report: &mut Report) -> Result<()> {
let Some(p) = self.frame.presents.last().cloned() else {
@@ -2796,7 +3026,15 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option<ID3D1
if debug {
let mut layer: Option<ID3D12Debug> = None;
match D3D12GetDebugInterface(&mut layer) {
Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
Ok(()) => layer.iter().for_each(|l| {
l.EnableDebugLayer();
// Every shader access checked on the card: very slow.
if std::env::var_os("VICTORY_REPLAY_GBV").is_some()
&& let Ok(l) = l.cast::<ID3D12Debug1>()
{
l.SetEnableGPUBasedValidation(true);
}
}),
Err(e) => tracing::warn!("no debug layer: {e}"),
}
}
File diff suppressed because it is too large. Load diff
+291
View File
@@ -0,0 +1,291 @@
//! What the CPU wrote, put in without what the card wrote.
//!
//! The host layer brings results of shaders back to title memory, and sends
//! pieces of title memory up again (64 KiB at a time) when the title changed
//! some of them. What goes up therefore holds results of the recorded frame.
//! Shaders that give out places with atomics give other places in every run:
//! the recorded results put over a replay's own leave lists and what points
//! into them of two different frames. So where a copy brings memory of the
//! CPU to a buffer the card writes, words the card has written since the
//! start of the frame (which are not what was last put there) stay.
use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
use windows::Win32::Graphics::Direct3D::ID3DBlob;
use super::*;
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)"
cbuffer C : register(b0) { uint words; uint call; };
ByteAddressBuffer from : register(t0);
RWByteAddressBuffer to : register(u0);
RWByteAddressBuffer base : register(u1);
// For each call: words put, words of the card's left that were to get
// another value, and of those the ones that were to get back what stood
// there before the card wrote.
RWByteAddressBuffer counts : register(u2);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= words) return;
uint at = id.x * 4;
uint v = from.Load(at), now = to.Load(at), was = base.Load(at), n;
if (now != was) {
if (v == now) return;
counts.InterlockedAdd(call * 12 + 4, 1, n);
if (v == was) counts.InterlockedAdd(call * 12 + 8, 1, n);
return;
}
if (v == now) return;
counts.InterlockedAdd(call * 12, 1, n);
to.Store(at, v);
base.Store(at, v);
}
"#;
pub(super) struct Merger {
root: ID3D12RootSignature,
pso: ID3D12PipelineState,
/// For each buffer: what was last put there (at first, what it held at
/// the frame's start).
pub(super) bases: HashMap<u32, ID3D12Resource>,
pub(super) counts: ID3D12Resource,
/// The merges recorded: buffer, offset, length (in `CALLS` at the most).
pub(super) calls: std::cell::RefCell<Vec<(u32, u64, u64)>>,
}
const CALLS: u64 = 1 << 16;
impl Player {
/// The copy of a piece of a card buffer's CPU side to it: its source's
/// address, then the buffer, offset, 0 and length.
pub(super) fn merged_copy(&self, c: &Cmd) -> Option<(u64, (u32, u64, u64, u64))> {
let Cmd::CopyBuffer {
dst,
dst_at,
src,
src_at,
len,
} = c
else {
return None;
};
if !self.merging
|| !self.pairs(*src, *dst)
|| dst_at != src_at
|| dst_at % 4 != 0
|| len % 4 != 0
{
return None;
}
self.merger.as_ref()?.bases.get(dst)?;
let from = self.objects.get(src)?.va + src_at;
Some((from, (*dst, *dst_at, 0, *len)))
}
/// Whether `src` is the CPU's side of card buffer `dst`.
fn pairs(&self, src: u32, dst: u32) -> bool {
let (Some(a), Some(b)) = (self.objects.get(&src), self.objects.get(&dst)) else {
return false;
};
let (a, b) = (
&self.frame.resources[a.index],
&self.frame.resources[b.index],
);
let cpu =
matches!(&a.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::Cached);
cpu && b.name.ends_with("on the card")
&& a.desc.width == b.desc.width
&& self.card_writes.contains(&dst)
}
/// Records merges: (buffer, offset in it, offset from `from`, length).
///
/// # Safety
/// An open list; `from` is the address of memory that holds the bytes.
pub(super) unsafe fn merge_all(
&self,
list: &ID3D12GraphicsCommandList,
from: u64,
all: &[(u32, u64, u64, u64)],
) {
let Some(m) = &self.merger else { return };
// SAFETY: the caller's; live buffers.
unsafe {
list.SetComputeRootSignature(&m.root);
list.SetPipelineState(&m.pso);
for (id, at, source, len) in all {
let (Some(o), Some(base)) = (self.objects.get(id), m.bases.get(id)) else {
continue;
};
let base = base.GetGPUVirtualAddress();
// At most 65,535 groups in a dispatch.
const MOST: u64 = 8 << 20;
let mut done = 0;
while done < *len {
let n = MOST.min(len - done);
let words = (n / 4) as u32;
let mut calls = m.calls.borrow_mut();
let call = (calls.len() as u64).min(CALLS - 1) as u32;
if calls.len() < CALLS as usize {
calls.push((*id, at + done, n));
}
drop(calls);
list.SetComputeRoot32BitConstants(0, 2, [words, call].as_ptr().cast(), 0);
list.SetComputeRootUnorderedAccessView(4, m.counts.GetGPUVirtualAddress());
list.SetComputeRootShaderResourceView(1, from + source + done);
list.SetComputeRootUnorderedAccessView(2, o.va + at + done);
list.SetComputeRootUnorderedAccessView(3, base + at + done);
list.Dispatch(words.div_ceil(64), 1, 1);
done += n;
}
}
}
}
/// Switches merging on or off; makes what it needs at first.
pub(super) fn set_merging(&mut self, on: bool) -> Result<()> {
self.merging = on;
if let Some(m) = &self.merger {
m.calls.borrow_mut().clear();
}
if !on || self.merger.is_some() {
return Ok(());
}
let mut code: Option<ID3DBlob> = None;
// SAFETY: the source and names live through the call; the blob's own
// bytes.
let (root, pso) = unsafe {
D3DCompile(
SOURCE.as_ptr().cast(),
SOURCE.len(),
None,
None,
None,
windows::core::s!("main"),
windows::core::s!("cs_5_1"),
0,
0,
&mut code,
None,
)?;
let code = code.context("no merge shader")?;
let bytes = std::slice::from_raw_parts(
code.GetBufferPointer().cast::<u8>(),
code.GetBufferSize(),
);
let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
let pso =
self.device
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: bytes.as_ptr().cast(),
BytecodeLength: bytes.len(),
},
..Default::default()
})?;
(root, pso)
};
let mut ids: HashSet<u32> = HashSet::new();
for c in self.commands.iter().flatten() {
if let Cmd::CopyBuffer { dst, src, .. } = c
&& self.pairs(*src, *dst)
{
ids.insert(*dst);
}
}
ids.extend(
self.delta_parts
.iter()
.flatten()
.map(|(d, _)| d.res)
.filter(|id| self.card_writes.contains(id)),
);
let mut bases = HashMap::new();
let mut total = 0;
for id in ids {
if !self.masters.iter().any(|m| m.0 == id) {
continue;
}
let size = self.frame.resources[self.objects[&id].index].desc.width;
let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
bases.insert(
id,
gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, size, flags)?.0,
);
total += size;
}
let masters: HashMap<u32, ID3D12Resource> = self.masters.iter().cloned().collect();
self.worker.run(|list| {
for (id, base) in &bases {
// SAFETY: an open list; live buffers of one size.
unsafe { list.CopyResource(base, &masters[id]) };
}
})?;
tracing::info!(
buffers = bases.len(),
mb = total >> 20,
"bases of merged copies"
);
let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
let counts = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, CALLS * 12, flags)?.0;
self.merger = Some(Merger {
root,
pso,
bases,
counts,
calls: Default::default(),
});
Ok(())
}
/// What the merges of the last run (of `loops`, which add up) found.
pub(super) fn merge_notes(&mut self, loops: u32) -> Result<Vec<String>> {
let Some(m) = &self.merger else {
return Ok(Vec::new());
};
let (counts, calls) = (m.counts.clone(), m.calls.borrow().clone());
let (back, data) = gpu::buffer(
&self.device,
D3D12_HEAP_TYPE_READBACK,
CALLS * 12,
D3D12_RESOURCE_FLAG_NONE,
)?;
self.worker.run(|list| {
// SAFETY: an open list; live buffers.
unsafe { list.CopyBufferRegion(&back, 0, &counts, 0, CALLS * 12) };
})?;
// SAFETY: the mapping; the copy into it has run.
let all = unsafe { std::slice::from_raw_parts(data.cast::<u32>(), CALLS as usize * 3) };
let each = |k: usize| {
all.iter()
.skip(k)
.step_by(3)
.map(|&n| u64::from(n))
.sum::<u64>()
/ u64::from(loops.max(1))
};
let mut out = vec![format!(
"{} copies of what the CPU wrote to memory the card writes: {} words put; {} left as the card wrote them in this run, where other values were to go ({} of them the values from before the card wrote)",
calls.len(),
each(0),
each(1),
each(2)
)];
let mut worst: Vec<(u32, usize)> = (0..calls.len())
.map(|i| (all[i * 3 + 2], i))
.filter(|w| w.0 > 0)
.collect();
worst.sort_by(|a, b| b.0.cmp(&a.0));
for (n, i) in worst.into_iter().take(8) {
let (id, at, len) = calls[i];
out.push(format!(
" values from before the card wrote: {} words, {} +{at:#x} {len:#x} bytes",
n / loops.max(1),
self.called(id)
));
}
Ok(out)
}
}
+13 -2
View File
@@ -351,7 +351,10 @@ pub(super) struct Recorder {
/// made are kept alive.
pub(super) watching: AtomicBool,
pub(super) writes: Mutex<Vec<(u32, u32, u32)>>,
pub(super) held: Mutex<Vec<ID3D12Resource>>,
/// Resources kept alive for a capture, by id. One that dies all the same
/// (its last reference was going when ours was taken) is taken out: see
/// `Recorder::gone`.
pub(super) held: Mutex<HashMap<u32, ID3D12Resource>>,
/// What could not be recorded, with how often.
problems: Mutex<BTreeMap<String, u64>>,
/// Submissions and presents, one at a time.
@@ -586,7 +589,7 @@ impl Recorder {
write(&self.resources).insert(id, res);
self.ids.set(p as usize, id);
if late {
lock(&self.held).push(ID3D12Resource::clone(&object));
lock(&self.held).insert(id, ID3D12Resource::clone(&object));
}
self.tell_gone(
&*object,
@@ -602,6 +605,14 @@ impl Recorder {
fn gone(&self, what: &Gone) {
match *what {
Gone::Resource { id, ptr, va } => {
// The memory goes whatever we hold: letting go of it later
// would be a call into what is there then.
if let Some(dead) = lock(&self.held).remove(&id) {
std::mem::forget(dead);
self.problem(
"a resource died as the frame started: its contents may be missing",
);
}
self.ids.remove(ptr, id);
write(&self.resources).remove(&id);
if va != 0 {
+23 -12
View File
@@ -279,7 +279,8 @@ impl Reads {
/// A buffer the CPU sees.
struct CpuBuffer {
id: u32,
res: ID3D12Resource,
/// Held by the recorder, not by this.
res: std::mem::ManuallyDrop<ID3D12Resource>,
/// Where it is read: its mapping, or the read-back copy of it.
live: *const u8,
/// The read-back buffer and the offset in it, for one that is slow to
@@ -298,8 +299,6 @@ unsafe impl Sync for CpuBuffer {}
struct Capture {
worker: Worker,
others: Vec<Worker>,
/// Resources the frame can use, kept alive.
held: Vec<ID3D12Resource>,
started: bool,
frame: u32,
states: States,
@@ -341,7 +340,6 @@ impl Capture {
Ok(Capture {
worker: Worker::new(&device, &direct.0)?,
others,
held: Vec::new(),
started: false,
frame: 0,
states: States::default(),
@@ -388,7 +386,8 @@ impl Capture {
let mut all: Vec<Arc<Res>> = Vec::new();
{
let live = read(&r.resources);
for res in live.values() {
let mut held = lock(&r.held);
for res in live.values().filter(|res| !res.late) {
let object = res.object();
// SAFETY: a live resource, or one whose end waits for the
// lock held here (`Recorder::gone`): the count tells which.
@@ -405,9 +404,9 @@ impl Capture {
// giving it back would end it a second time.
continue;
}
// SAFETY: the reference just taken.
self.held
.push(unsafe { ID3D12Resource::from_raw(object.as_raw()) });
// SAFETY: the reference just taken. (The count does not tell
// all that are dying: `Recorder::gone` takes those out.)
held.insert(res.id, unsafe { ID3D12Resource::from_raw(object.as_raw()) });
all.push(res.clone());
}
}
@@ -594,7 +593,11 @@ impl Capture {
}
// Moved in: the writers end when it goes.
let todo = todo;
for pieces in batches {
for mut pieces in batches {
{
let held = lock(&r.held);
pieces.retain(|p| held.contains_key(&p.res.id));
}
if pieces.is_empty() {
continue;
}
@@ -629,8 +632,12 @@ impl Capture {
r.problem("contents of textures in memory the CPU sees are not in the capture");
continue;
}
// Those alive at the start are held, those made since too.
let object = ID3D12Resource::clone(&res.object());
// Those alive at the start are held, those made since too; what
// is not is dying.
if !lock(&r.held).contains_key(&res.id) {
continue;
}
let object = res.object();
let size = res.desc.width as usize;
let (live, through) = if res.seen == Seen::Cached {
let mut data = std::ptr::null_mut();
@@ -675,6 +682,10 @@ impl Capture {
/// zero).
fn changed(&mut self, r: &Recorder, reads: &Reads) -> Result<Vec<Delta>, Fault> {
self.new_buffers(r)?;
{
let held = lock(&r.held);
self.buffers.retain(|b| held.contains_key(&b.id));
}
let parts: Vec<(usize, usize, usize)> = self
.buffers
.iter()
@@ -697,7 +708,7 @@ impl Capture {
list.CopyBufferRegion(
&blocks[block].0,
at + from as u64,
&b.res,
&*b.res,
from as u64,
(to - from) as u64,
)
+24
View File
@@ -64,6 +64,7 @@ with the presented one.
| `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory |
| `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones |
| `--only 3..7` | runs these lists; of the others only barriers |
| `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |
| `--skip-shader <text>` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) |
| `--no-restore` | leaves what a loop changed |
| `--debug-layer` | D3D12's debug layer; its errors in the report |
@@ -73,6 +74,29 @@ leaves out waits or work can draw another picture and, with wild data, lose
the device: save work in other programs first. Do not run the title at the
same time.
## Runs that differ
Shaders that give out places with atomics (the title's culling) give other
ones in every run. The host layer brings such results to title memory and
sends 64 KiB pieces of it up again, so the recorded copies hold the recorded
run's results. Put over a replay's own, lists and what points into them are of
two runs, and things are drawn from other things' lists. So copies of what the
CPU wrote leave alone words the card has written in this run (`merge.rs`; the
report counts them). `--no-merge` runs the copies as recorded.
| switch | does |
|---|---|
| `--wait-all` / `--wait-lists` | a full wait after every command / each list sent alone and waited for: if pictures still differ, waits are not what is missing |
| `--diverge [runs]` | runs each list this often from the very same memory, finds the first commands that make different memory of it, and says what differs (same values in another order: places given out); contents go to `diverge` in the capture |
| `--diverge-picture [runs]` | from each list on, runs the rest this often from the same memory: where the pictures start to agree, what lies before decides. `--lists 76 --commands 0..900 --step 8` goes into one list |
| `--diverge 10 --lists 76 --draws <text>` | each draw of the pipelines named, alone, this often: how many outcomes, and what it reads |
| `--watch <id>:<offset>:<bytes>` | which lists (with `--lists`: commands) change those words |
| `--slots <list>:<command>` | the heap slots its constants name |
| `--check-written` | that everything the frame changes is put back |
| `--dump <text>` | the DXIL of the pipelines named, in `shaders` |
The `--diverge` family runs the recorded copies without the merge.
## Limits
- Not recorded, but reported when used: reserved (tiled) resources, bundles,