victory replay, larger tests of it

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 20:09:57 -06:00
1 parent 59a556e4b0
commit 048201b13c
9 files changed
+938 -52

No files matched your search

+8
View File
@@ -5,6 +5,8 @@
mod census;
mod inspect;
#[cfg(all(windows, feature = "diagnostics"))]
mod replay;
mod run;
mod shader;
mod translate;
@@ -114,6 +116,10 @@ enum Command {
#[arg(last = true)]
title_args: Vec<String>,
},
/// Run a captured frame's GPU work again (diagnostics builds; see
/// docs/replay.md).
#[cfg(all(windows, feature = "diagnostics"))]
Replay(replay::Replay),
/// Show the resolved configuration and check it.
Config,
}
@@ -181,6 +187,8 @@ fn main() -> Result<()> {
console,
title_args: _,
} => run::run(&exe, unimplemented, strict, execute, console),
#[cfg(all(windows, feature = "diagnostics"))]
Command::Replay(options) => replay::run(options),
Command::Config => show_config(),
}
}
+131
View File
@@ -0,0 +1,131 @@
//! `victory replay`: a captured frame run again (docs/replay.md).
use std::path::PathBuf;
use anyhow::{Context, Result};
use clap::{Args, ValueEnum};
use victory_hle::replay::play::{self, Options};
#[derive(Clone, Copy, ValueEnum)]
enum Timing {
/// Each list.
Lists,
/// Each command (adds some time of its own).
Detailed,
}
#[derive(Clone, Copy, ValueEnum)]
enum Buffers {
AsRecorded,
/// All in the card's memory.
Vram,
/// All in the PC's memory.
Sysmem,
}
#[derive(Args)]
pub(crate) struct Replay {
/// The folder given as VICTORY_RECORD (its last capture) or a capture.
folder: PathBuf,
/// How often the frame is run.
#[arg(long, default_value_t = 5)]
loops: u32,
/// Do not put back, between runs, what a run changed.
#[arg(long)]
no_restore: bool,
#[arg(long, value_enum, default_value_t = Timing::Lists)]
timing: Timing,
/// Pipelines listed with detailed timing.
#[arg(long, default_value_t = 20)]
top: usize,
/// Where the picture goes (default: replay.png in the capture).
#[arg(long)]
image: Option<PathBuf>,
/// Run the frame unchanged first, and print both.
#[arg(long)]
compare: bool,
/// Leave out unordered-access barriers.
#[arg(long)]
no_barriers: bool,
/// Join barrier calls with no work between them.
#[arg(long)]
merge_barriers: bool,
/// Leave out the argument clamps: what they bound is kept from a first run.
#[arg(long)]
skip_clamps: bool,
/// Leave out the hash and compare passes over card buffers.
#[arg(long)]
skip_hash_passes: bool,
/// Where buffers lie.
#[arg(long, value_enum, default_value_t = Buffers::AsRecorded)]
buffers: Buffers,
/// One ExecuteCommandLists for the whole frame.
#[arg(long)]
one_submit: bool,
/// Run only these lists, by their place in the frame (`3..7`, or `5`);
/// of the others only barriers.
#[arg(long)]
only: Option<String>,
/// Leave out what runs a pipeline whose name or DXIL hash has this in it
/// (may be given several times).
#[arg(long = "skip-shader")]
skip_shader: Vec<String>,
/// Use the D3D12 debug layer (slow).
#[arg(long)]
debug_layer: bool,
}
/// `3..7` (both included) or `5`.
fn range(text: &str) -> Option<(u32, u32)> {
match text.split_once("..") {
Some((a, b)) => Some((a.trim().parse().ok()?, b.trim().parse().ok()?)),
None => text.trim().parse().ok().map(|n| (n, n)),
}
}
pub(crate) fn run(r: Replay) -> Result<()> {
let only = match &r.only {
Some(text) => Some(range(text).with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?),
None => None,
};
let options = Options {
loops: r.loops.max(1),
restore: !r.no_restore,
detailed: matches!(r.timing, Timing::Detailed),
top: r.top,
image: r.image,
buffers: match r.buffers {
Buffers::AsRecorded => play::Buffers::AsRecorded,
Buffers::Vram => play::Buffers::Card,
Buffers::Sysmem => play::Buffers::Pc,
},
no_barriers: r.no_barriers,
merge_barriers: r.merge_barriers,
skip_clamps: r.skip_clamps,
skip_hash_passes: r.skip_hash_passes,
one_submit: r.one_submit,
only,
skip_shaders: r.skip_shader,
compare: r.compare,
debug: r.debug_layer,
};
let reports = play::replay(&r.folder, &options)?;
for (what, report) in &reports {
println!("{}", report.text(what));
}
if let [(_, before), (_, after)] = &reports[..] {
println!("{:+.2} ms", after.median_ms() - before.median_ms());
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn ranges() {
assert_eq!(super::range("3..7"), Some((3, 7)));
assert_eq!(super::range("5"), Some((5, 5)));
assert_eq!(super::range("x"), None);
assert_eq!(super::range("1..x"), None);
}
}
+8 -1
View File
@@ -1303,7 +1303,14 @@ fn timing() -> bool {
pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
#[cfg(feature = "diagnostics")]
if crate::replay::record::on() {
crate::replay::record::name(object, &text());
let text = text();
crate::replay::record::name(object, &text);
if dred_on()
&& let Ok(object) = object.cast::<ID3D12Object>()
{
// SAFETY: a plain call on a live object.
let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) };
}
return;
}
if dred_on()
+117 -28
View File
@@ -345,7 +345,7 @@ impl Player {
player.make_masters()?;
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();
tracing::info!(seconds = began.elapsed().as_secs_f64(), "capture loaded: {}", steps.join(", "));
player.notes.push(format!("loaded in {:.1} s: {}", began.elapsed().as_secs_f64(), steps.join(", ")));
Ok(player)
}
@@ -635,9 +635,15 @@ impl Player {
// version of the heaps of its own: lists are sent without waiting,
// so a heap cannot be written between them.
let mut now: HashMap<(u32, u32), Slot> = HashMap::new();
let replaced: HashSet<(u32, u32)> = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|v| (v.0, v.1))).collect();
for h in &self.frame.descriptor_heaps {
for (first, n, s) in &h.runs {
now.extend((*first..first + n).map(|i| ((h.id, i), *s)));
for (id, i) in replaced.iter().filter(|k| k.0 == h.id) {
let k = h.runs.partition_point(|run| run.0 <= *i);
if let Some((first, n, s)) = k.checked_sub(1).and_then(|k| h.runs.get(k))
&& i - first < *n
{
now.insert((*id, *i), *s);
}
}
}
// What each version changes against the one before.
@@ -660,6 +666,7 @@ impl Player {
self.version_of.push(versions.len() - 1);
}
let mut made = HashMap::new();
let mut full = 0;
for h in &self.frame.descriptor_heaps {
let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0;
let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind);
@@ -703,7 +710,20 @@ impl Player {
all.push(same);
continue;
}
let heap = make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)?;
let heap = match make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) {
Ok(heap) => heap,
// Room for no more of them: the changes go into the
// last one, and lists before see them too.
Err(_) if !all.is_empty() => {
full += 1;
let Some(Version { heap, gpu }) = all.last() else { break };
let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu };
self.device.CopyDescriptorsSimple(h.count, same.heap.GetCPUDescriptorHandleForHeapStart(), start, kind);
all.push(same);
continue;
}
Err(e) => return Err(e.into()),
};
self.device.CopyDescriptorsSimple(h.count, heap.GetCPUDescriptorHandleForHeapStart(), start, kind);
let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr;
all.push(Version { heap, gpu });
@@ -712,6 +732,12 @@ impl Player {
}
}
self.descriptors = made;
if versions.len() > 1 {
self.notes.push(format!("{} versions of the descriptor heaps (views replaced during the frame)", versions.len()));
}
if full > 0 {
self.note(format!("{full} versions of descriptor heaps had no room: earlier lists see later views"));
}
// Render target and depth views.
let mut views: [HashSet<Slot>; 2] = Default::default();
for c in self.commands.iter().flatten() {
@@ -839,11 +865,12 @@ impl Player {
fn load_contents(&mut self) -> Result<()> {
// Idle aliases first: a change of their state may write memory the
// one in use holds.
let known: HashSet<u32> = self.frame.contents.iter().map(|c| c.res).collect();
let mut early = Vec::new();
let mut into = Vec::new();
for r in &self.frame.resources {
let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue };
let loaded = !r.idle && self.frame.contents.iter().any(|c| c.res == r.id);
let loaded = !r.idle && known.contains(&r.id);
gpu::moves(&o.res, &[COMMON], if loaded { &[COPY_DEST] } else { state }, if loaded { &mut into } else { &mut early });
}
let textures: Vec<(Content, u64, u64)> = self
@@ -890,7 +917,7 @@ impl Player {
let mut back = Vec::new();
for r in &self.frame.resources {
let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { continue };
if !r.idle && self.frame.contents.iter().any(|c| c.res == r.id) {
if !r.idle && known.contains(&r.id) {
gpu::moves(&o.res, &[COPY_DEST], state, &mut back);
}
}
@@ -906,7 +933,30 @@ impl Player {
// What the CPU had put into the memory both see by the first
// submission: part of the start of the frame.
let file = File::open(self.folder.join("deltas.bin"))?;
let first: Vec<(Delta, u64, u64)> = self.frame.submits[0].deltas.iter().map(|d| (d.clone(), d.len, d.file)).collect();
let named = self.named_buffers();
let of = |s: &wire::Submit| s.deltas.iter().filter(|d| named.contains(&d.res)).cloned().collect::<Vec<Delta>>();
// In memory the card cannot write, bytes looked at first when a
// later submission read them can stand there from the start.
let upload: HashSet<u32> = self
.frame
.resources
.iter()
.filter(|r| matches!(&r.place, Place::Committed { props, .. } if props.kind == D3D12_HEAP_TYPE_UPLOAD.0))
.map(|r| r.id)
.collect();
let mut first = of(&self.frame.submits[0]);
let mut seen: HashSet<(u32, u64)> = HashSet::new();
let pages = |d: &Delta| (d.at / 4096..(d.at + d.len).div_ceil(4096)).map(|p| (d.res, p)).collect::<Vec<_>>();
first.iter().for_each(|d| seen.extend(pages(d)));
let mut rest: Vec<Vec<Delta>> = vec![Vec::new()];
for s in self.frame.submits.iter().skip(1) {
let (early, late): (Vec<Delta>, Vec<Delta>) =
of(s).into_iter().partition(|d| upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p)));
early.iter().for_each(|d| seen.extend(pages(d)));
first.extend(early);
rest.push(late);
}
let first: Vec<(Delta, u64, u64)> = first.into_iter().map(|d| (d.clone(), d.len, d.file)).collect();
self.upload(&first, &file, |player, list, parts, staging| {
for (d, len, at) in parts {
if let Some(o) = player.objects.get(&d.res) {
@@ -919,11 +969,11 @@ impl Player {
let mut later: Vec<((u64, Delta), u64, u64)> = Vec::new();
let mut total = 0u64;
self.delta_parts = vec![Vec::new(); self.frame.submits.len()];
for (i, s) in self.frame.submits.iter().enumerate().skip(1) {
for d in &s.deltas {
for (i, all) in rest.into_iter().enumerate() {
for d in all {
later.push(((total, d.clone()), d.len, d.file));
self.delta_parts[i].push((d.clone(), total));
total += d.len;
self.delta_parts[i].push((d, total - later.last().map_or(0, |l| l.1)));
}
}
if total > 0 {
@@ -939,6 +989,46 @@ impl Player {
Ok(())
}
/// The buffers the frame names, in commands or descriptors: what the CPU
/// writes to others (buffers it has results fetched to) is of no use.
fn named_buffers(&self) -> HashSet<u32> {
let mut named = HashSet::new();
let mut va = |va: &Va| {
if let Va::At { res, .. } = va {
named.insert(*res);
}
};
for c in self.commands.iter().flatten() {
match c {
Cmd::RootView { va: v, .. } => va(v),
Cmd::IndexBuffer { view: Some((v, _, _)) } => va(v),
Cmd::VertexBuffers { views: Some(all), .. } => all.iter().for_each(|(v, _, _)| va(v)),
Cmd::WriteImmediate { all } => all.iter().for_each(|(v, _, _)| va(v)),
_ => {}
}
}
for c in self.commands.iter().flatten() {
match c {
Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => named.extend([*dst, *src]),
Cmd::CopyTexture { dst, src, .. } => {
for Loc::Sub { res, .. } | Loc::Placed { res, .. } in [dst, src] {
named.insert(*res);
}
}
Cmd::Indirect { args, count, .. } => named.extend([*args, *count]),
Cmd::ResolveQuery { dst, .. } => drop(named.insert(*dst)),
_ => {}
}
}
for h in &self.frame.descriptor_heaps {
named.extend(h.runs.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
}
for s in &self.frame.submits {
named.extend(s.views.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
}
named
}
/// Copies of what the frame changes; and the states it leaves.
fn make_masters(&mut self) -> Result<()> {
let mut states = States::default();
@@ -991,7 +1081,7 @@ impl Player {
}
states.decay();
if i > 0 {
written.extend(s.deltas.iter().map(|d| d.res));
written.extend(self.delta_parts[i].iter().map(|(d, _)| d.res));
}
}
// Buffers any unordered-access view names.
@@ -1759,8 +1849,7 @@ impl Player {
}
self.picture(o, &mut report)?;
if let Some(q) = &self.info {
let n = debug_messages(q);
report.notes.push(format!("{n} errors from the debug layer"));
report.notes.extend(debug_messages(q));
}
Ok(report)
}
@@ -1822,6 +1911,11 @@ impl Player {
/// What a resource holds now (after a run): a buffer's bytes, or a
/// texture's first subresource in its copyable layout.
pub fn contents(&mut self, id: u32) -> Result<Option<Vec<u8>>> {
self.contents_of(id, 0)
}
/// As [`Player::contents`], of a texture's subresource `sub`.
pub fn contents_of(&mut self, id: u32, sub: u32) -> Result<Option<Vec<u8>>> {
let Some(o) = self.objects.get(&id) else {
return Ok(None);
};
@@ -1830,21 +1924,21 @@ impl Player {
let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
let states = if self.fresh { &self.start } else { &self.end };
let state = states.get(&id).cloned().unwrap_or(vec![COMMON]);
let (f, total) = if is_buffer { (Vec::new(), r.desc.width) } else { gpu::footprints(&self.device, &desc, 0, 1) };
let (f, total) = if is_buffer { (Vec::new(), r.desc.width) } else { gpu::footprints(&self.device, &desc, sub, 1) };
let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?;
self.worker.run(|list| {
if is_buffer {
// SAFETY: an open list; live buffers.
unsafe { list.CopyBufferRegion(&back, 0, &res, 0, total) };
} else if state.len() == 1 || subs == 1 {
read_sub(list, &res, 0, state[0], &back, f[0]);
read_sub(list, &res, sub, state[0], &back, f[0]);
} else {
let (mut before, mut after) = (Vec::new(), Vec::new());
gpu::moves(&res, &state, &[COPY_SOURCE], &mut before);
gpu::moves(&res, &[COPY_SOURCE], &state, &mut after);
// SAFETY: an open list; live resources.
unsafe { barriers(list, &before) };
read_sub(list, &res, 0, COPY_SOURCE, &back, f[0]);
read_sub(list, &res, sub, COPY_SOURCE, &back, f[0]);
// SAFETY: as above.
unsafe { barriers(list, &after) };
}
@@ -1969,10 +2063,9 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option<ID3D1
}
}
/// Logs the debug layer's messages; how many errors.
fn debug_messages(q: &ID3D12InfoQueue) -> usize {
let mut errors = 0;
let mut seen: HashMap<i32, u32> = HashMap::new();
/// The debug layer's errors: how many of each kind, and its first text.
fn debug_messages(q: &ID3D12InfoQueue) -> Vec<String> {
let mut seen: BTreeMap<i32, (u32, String)> = BTreeMap::new();
// SAFETY: messages read into buffers of the size asked for.
unsafe {
for i in 0..q.GetNumStoredMessages() {
@@ -1987,18 +2080,14 @@ fn debug_messages(q: &ID3D12InfoQueue) -> usize {
}
let m = &*message;
if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 {
errors += 1;
let n = seen.entry(m.ID.0).or_default();
*n += 1;
if *n <= 3 {
let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
tracing::warn!("D3D12 {}: {}", m.ID.0, String::from_utf8_lossy(text).trim_end_matches('\0'));
}
let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
let text = || String::from_utf8_lossy(text).trim_end_matches('\0').to_owned();
seen.entry(m.ID.0).or_insert_with(|| (0, text())).0 += 1;
}
}
q.ClearStoredMessages();
}
errors
seen.into_iter().map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")).collect()
}
#[cfg(test)]
+8 -3
View File
@@ -38,6 +38,9 @@ pub struct Settings {
pub at: At,
/// Frames to capture.
pub frames: u32,
/// Record lists from the start on, not only once a capture is near: for
/// a title that submits lists it recorded long before.
pub always: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -52,13 +55,14 @@ pub enum At {
}
impl Settings {
/// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f<frame>`)
/// and `VICTORY_RECORD_FRAMES`.
/// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f<frame>`),
/// `VICTORY_RECORD_FRAMES` and `VICTORY_RECORD_ALWAYS=1`.
pub fn from_env() -> Option<Settings> {
let folder = PathBuf::from(std::env::var_os("VICTORY_RECORD").filter(|v| !v.is_empty())?);
let at = parse_at(&std::env::var("VICTORY_RECORD_AT").unwrap_or_default());
let frames = std::env::var("VICTORY_RECORD_FRAMES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1);
Some(Settings { folder, at, frames: std::cmp::max(frames, 1) })
let always = std::env::var_os("VICTORY_RECORD_ALWAYS").is_some_and(|v| v == "1");
Some(Settings { folder, at, frames: std::cmp::max(frames, 1), always })
}
}
@@ -733,6 +737,7 @@ pub fn start(settings: Settings, device: &ID3D12Device) -> std::io::Result<PathB
}
let r = recorder().ok_or_else(|| std::io::Error::other("no recorder"))?;
*lock(&r.device) = Some(device.clone());
r.arm(r.settings.always);
// The newer interfaces may be other pointers (they are the same one
// without the debug layer).
let mut all = vec![device.as_raw()];
+130 -15
View File
@@ -15,7 +15,7 @@ use windows::core::Interface;
use super::gpu::{self, Seen, Worker};
use super::record::{At, Heap, Ours, Recorder, Res, lock, not_recorded_calls, read};
use super::states::{COMMON, COPY_SOURCE, Change, States};
use super::wire::{self, ALL, Cmd, Content, Delta, MISSING, NONE, Place, Slot, Va, ZERO, slot};
use super::wire::{self, ALL, Cmd, Content, Delta, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot};
type Fault = Box<dyn std::error::Error + Send + Sync>;
@@ -94,7 +94,8 @@ fn stop(r: &Recorder, phase: &mut Phase, e: &(dyn std::error::Error + Send + Syn
phase.stage = Stage::Done;
r.watching.store(false, Ordering::SeqCst);
r.arm(false);
lock(&r.held).clear();
let held = std::mem::take(&mut *lock(&r.held));
drop(held);
}
pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) {
@@ -159,6 +160,69 @@ pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) {
drop(finished);
}
/// What a submission reads of buffers, by id: parts of them (copied from),
/// or all (read some other way).
#[derive(Default)]
struct Reads {
all: HashSet<u32>,
parts: HashMap<u32, Vec<(u64, u64)>>,
}
impl Reads {
fn note(&mut self, cmds: &[Cmd]) {
let (all, parts) = (&mut self.all, &mut self.parts);
let mut whole = |va: &Va| {
if let Va::At { res, .. } = va {
all.insert(*res);
}
};
for c in cmds {
match c {
Cmd::RootView { va, .. } | Cmd::IndexBuffer { view: Some((va, _, _)) } => whole(va),
Cmd::VertexBuffers { views: Some(views), .. } => views.iter().for_each(|(va, _, _)| whole(va)),
Cmd::Indirect { args, count, .. } => {
for res in [*args, *count] {
whole(&Va::At { res, offset: 0 });
}
}
Cmd::CopyResource { src, .. } => whole(&Va::At { res: *src, offset: 0 }),
Cmd::CopyBuffer { src, src_at, len, .. } => parts.entry(*src).or_default().push((*src_at, src_at + len)),
Cmd::CopyTexture { src: Loc::Placed { res, offset, size, pitch, .. }, .. } => {
// At the most: compressed formats have fewer rows.
let len = u64::from(*pitch) * u64::from(size[1]) * u64::from(size[2].max(1));
parts.entry(*res).or_default().push((*offset, offset + len));
}
_ => {}
}
}
}
/// The whole pages read of a buffer of `size` bytes; `viewed` by a
/// descriptor, all of it is.
fn pages(&self, id: u32, size: usize, viewed: bool) -> Vec<(usize, usize)> {
if viewed || self.all.contains(&id) {
return vec![(0, size)];
}
let Some(parts) = self.parts.get(&id) else {
return Vec::new();
};
let mut pages: Vec<(usize, usize)> = parts
.iter()
.map(|&(from, to)| (from as usize / PAGE * PAGE, (to as usize).next_multiple_of(PAGE).min(size)))
.filter(|(from, to)| from < to)
.collect();
pages.sort_unstable();
let mut out: Vec<(usize, usize)> = Vec::new();
for (from, to) in pages {
match out.last_mut() {
Some(last) if from <= last.1 => last.1 = last.1.max(to),
_ => out.push((from, to)),
}
}
out
}
}
/// A buffer the CPU sees.
struct CpuBuffer {
id: u32,
@@ -191,6 +255,8 @@ struct Capture {
contents: Vec<Content>,
buffers: Vec<CpuBuffer>,
known: HashSet<u32>,
/// Resources descriptors name, or named during the frame.
viewed: HashSet<u32>,
/// Read-back buffers for the slow ones: the buffer, its mapping, size,
/// and how much of it is taken.
blocks: Vec<(ID3D12Resource, usize, u64, u64)>,
@@ -228,6 +294,7 @@ impl Capture {
contents: Vec::new(),
buffers: Vec::new(),
known: HashSet::new(),
viewed: HashSet::new(),
blocks: Vec::new(),
deltas: File::create(r.folder.join("deltas.bin"))?,
delta_at: AtomicU64::new(0),
@@ -464,22 +531,33 @@ impl Capture {
Ok(())
}
/// What changed in buffers the CPU sees since the submission before.
fn changed(&mut self, r: &Recorder) -> Result<Vec<Delta>, Fault> {
/// What changed in the buffers the CPU sees, of what a submission reads
/// of them, since they were last looked at (the first time: what is not
/// zero).
fn changed(&mut self, r: &Recorder, reads: &Reads) -> Result<Vec<Delta>, Fault> {
self.new_buffers(r)?;
if self.buffers.iter().any(|b| b.through.is_some()) {
let parts: Vec<(usize, usize, usize)> = self
.buffers
.iter()
.enumerate()
.flat_map(|(i, b)| reads.pages(b.id, b.size, self.viewed.contains(&b.id)).into_iter().map(move |(from, to)| (i, from, to)))
.collect();
if parts.iter().any(|p| self.buffers[p.0].through.is_some()) {
let (buffers, blocks) = (&self.buffers, &self.blocks);
self.worker.run(|list| {
for b in buffers {
if let Some((i, at)) = b.through {
for &(i, from, to) in &parts {
let b = &buffers[i];
if let Some((block, at)) = b.through {
// SAFETY: an open list and live buffers.
unsafe { list.CopyBufferRegion(&blocks[i].0, at, &b.res, 0, b.size as u64) };
unsafe { list.CopyBufferRegion(&blocks[block].0, at + from as u64, &b.res, from as u64, (to - from) as u64) };
}
}
})?;
}
let chunks: Vec<(usize, usize)> =
self.buffers.iter().enumerate().flat_map(|(i, b)| (0..b.size).step_by(CHUNK).map(move |at| (i, at))).collect();
let chunks: Vec<(usize, usize, usize)> = parts
.iter()
.flat_map(|&(i, from, to)| (from..to).step_by(CHUNK).map(move |at| (i, at, CHUNK.min(to - at))))
.collect();
// Each chunk is one thread's; threads share what is kept by parts.
struct Kept(*mut u8);
// SAFETY: parts of it are used by one thread each.
@@ -496,8 +574,7 @@ impl Capture {
let mut mine = Vec::new();
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
let Some(&(b, at)) = chunks.get(i) else { break };
let len = CHUNK.min(buffers[b].size - at);
let Some(&(b, at, len)) = chunks.get(i) else { break };
// SAFETY: a chunk of the buffer's memory (it may
// change meanwhile: what is kept is what was read)
// and of what is kept, which no other thread has.
@@ -531,14 +608,14 @@ impl Capture {
} else {
self.timed("waiting for the card", |c| Ok(c.worker.idle()?))?;
}
let deltas = self.timed("what the CPU changed", |c| c.changed(r))?;
// Descriptors last: their memory is ready now.
// Descriptors first: what they name is looked at below.
let mut written = std::mem::take(&mut *lock(&r.writes));
let mut views = Vec::new();
if first {
let heaps: Vec<Arc<Heap>> = read(&r.descriptors).visible().cloned().collect();
for h in heaps {
let runs = runs_of(r, &h.all());
self.viewed.extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
self.heaps.push((h, runs));
}
} else {
@@ -556,11 +633,18 @@ impl Capture {
};
for i in at..at + n {
if seen.insert((heap, i)) {
views.push((heap, i, resolved(r, h.get(i))));
let s = resolved(r, h.get(i));
self.viewed.extend([s.res, s.counter]);
views.push((heap, i, s));
}
}
}
}
let mut reads = Reads::default();
for l in lists.iter().flatten() {
reads.note(&Cmd::all(l)?);
}
let deltas = self.timed("what the CPU changed", |c| c.changed(r, &reads))?;
let mut numbers = Vec::new();
for l in lists {
numbers.push(match l {
@@ -810,6 +894,11 @@ pub(super) fn read_sub(
/// A slot as it goes into the file: a constant buffer view's address as
/// buffer and offset.
fn resolved(r: &Recorder, mut s: Slot) -> Slot {
let kind = i32::from_le_bytes([s.desc[4], s.desc[5], s.desc[6], s.desc[7]]);
if s.kind == slot::SRV && s.described != 0 && kind == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 {
r.problem("views of acceleration structures are null in the capture");
return Slot { kind: slot::SRV, ..Slot::EMPTY };
}
if s.kind == slot::CBV && s.described != 0 {
match r.va(s.address()) {
Va::At { res, offset } => {
@@ -910,6 +999,32 @@ mod tests {
assert!(find(&live, &mut kept).is_empty());
}
#[test]
fn what_a_submission_reads() {
let mut reads = Reads::default();
let part = |from, len| Cmd::CopyBuffer { dst: 9, dst_at: 0, src: 1, src_at: from, len };
reads.note(&[
part(100, 50),
part(4000, 200),
part(20_000, 1),
Cmd::CopyTexture {
dst: Loc::Sub { res: 9, sub: 0 },
at: [0; 3],
src: Loc::Placed { res: 2, offset: 4096, format: 28, size: [16, 16, 1], pitch: 256 },
part: None,
},
Cmd::Indirect { signature: 1, most: 1, args: 3, at: 8, count: 0, count_at: 0 },
Cmd::RootView { graphics: true, kind: slot::CBV, param: 0, va: Va::At { res: 4, offset: 5 } },
]);
assert_eq!(reads.pages(1, 1 << 20, false), [(0, 8192), (16384, 20480)]);
assert_eq!(reads.pages(1, 20_100, false), [(0, 8192), (16384, 20_100)], "its end");
assert_eq!(reads.pages(2, 1 << 20, false), [(4096, 8192)]);
assert_eq!(reads.pages(3, 100, false), [(0, 100)]);
assert_eq!(reads.pages(4, 100, false), [(0, 100)]);
assert_eq!(reads.pages(5, 100, true), [(0, 100)], "a descriptor names it");
assert!(reads.pages(5, 100, false).is_empty() && reads.pages(9, 100, false).is_empty());
}
#[test]
fn zeros() {
assert!(zero(&[]));
+263 -5
View File
@@ -25,7 +25,7 @@ use windows::core::{Interface, PCSTR, s, w};
const SIZE: u32 = 128;
const DRAW: &str = r#"
#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT)"
#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), DescriptorTable(Sampler(s0))"
cbuffer Pick : register(b0) { uint pick; uint pad; };
cbuffer Place : register(b1) { float4 place; };
Texture2D all[] : register(t0);
@@ -45,6 +45,15 @@ V vs(uint i : SV_VertexID) {
float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); }
"#;
/// Triangles of vertices and indices.
const PLAIN: &str = r#"
#define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)"
struct V { float4 at : SV_Position; float3 color : COLOR; };
[RootSignature(RS)]
V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, 1); v.color = color; return v; }
float4 ps(V v) : SV_Target { return float4(v.color, 1); }
"#;
/// Writes the arguments of indirect draws (two records: six vertices, and
/// one far too many that the clamp cuts to none).
const ARGS: &str = r#"
@@ -247,9 +256,18 @@ const TO: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST;
const FROM: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_SOURCE;
const ARGUMENTS: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
/// A texture the frames do not touch: what each subresource holds, row by
/// row, with the rows' distance in its copyable layout.
#[derive(PartialEq, Debug, Clone)]
struct Still {
name: &'static str,
subs: Vec<(usize, Vec<Vec<u8>>)>,
}
/// What the program ends with.
#[derive(PartialEq, Debug)]
struct Outcome {
still: Vec<Still>,
picture: Vec<u8>,
image: Vec<u8>,
sum: Vec<u8>,
@@ -264,6 +282,11 @@ struct Scene {
value: u64,
lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
draw: Made,
plain: Made,
vertices: (ID3D12Resource, *mut u8),
samplers: ID3D12DescriptorHeap,
still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>,
copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList),
args: Made,
clamp: Made,
add: Made,
@@ -339,6 +362,26 @@ impl Scene {
let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
record::name(&pso, "a drawing pipeline");
let draw = Made { root, pso };
let (vs, ps) = (compile(PLAIN, s!("vs"), s!("vs_5_1")), compile(PLAIN, s!("ps"), s!("ps_5_1")));
let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
let element = |name, index, format, at| D3D12_INPUT_ELEMENT_DESC {
SemanticName: name,
SemanticIndex: index,
Format: format,
InputSlot: 0,
AlignedByteOffset: at,
InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
InstanceDataStepRate: 0,
};
let elements = [
element(s!("POSITION"), 0, DXGI_FORMAT_R32G32_FLOAT, 0),
element(s!("COLOR"), 1, DXGI_FORMAT_R32G32B32_FLOAT, 8),
];
desc.pRootSignature = std::mem::transmute_copy(&root);
(desc.VS, desc.PS) = (code(&vs), code(&ps));
desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elements.as_ptr(), NumElements: 2 };
let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
let plain = Made { root, pso };
let clamp = compute(device, CLAMP);
record::name(&clamp.pso, play::CLAMP);
let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() };
@@ -348,6 +391,18 @@ impl Scene {
let heap = |kind, count, flags| -> ID3D12DescriptorHeap {
device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap()
};
let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
let sampler = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
MaxLOD: 8.0,
..Default::default()
};
let mut at = samplers.GetCPUDescriptorHandleForHeapStart();
at.ptr += 2 * device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize;
device.CreateSampler(&sampler, at);
let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
@@ -395,6 +450,41 @@ impl Scene {
D3D12_RESOURCE_STATE_GENERIC_READ,
);
let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO);
let vertices = committed(
device,
In::Upload,
&buffer_desc(4096, D3D12_RESOURCE_FLAG_NONE),
D3D12_RESOURCE_STATE_GENERIC_READ,
);
let still = {
let blocks = D3D12_RESOURCE_DESC {
MipLevels: 5,
DepthOrArraySize: 3,
..texture_desc(64, DXGI_FORMAT_BC7_UNORM, D3D12_RESOURCE_FLAG_NONE)
};
let volume = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D,
DepthOrArraySize: 8,
MipLevels: 3,
..texture_desc(16, DXGI_FORMAT_R16_FLOAT, D3D12_RESOURCE_FLAG_NONE)
};
let stencil = texture_desc(32, DXGI_FORMAT_R32G8X24_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
let (write, read) = (D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
[("blocks", blocks, TO, READ), ("volume", volume, TO, read), ("stencil", stencil, write, write)].map(|(name, d, made_in, ends)| {
let (t, _) = committed(device, In::Card, &d, made_in);
record::name(&t, name);
(name, t, ends)
})
};
let copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList) = {
let queue = device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() })
.unwrap();
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).unwrap();
let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None).unwrap();
list.Close().unwrap();
(queue, allocator, list)
};
for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] {
record::name(r, n);
}
@@ -410,6 +500,11 @@ impl Scene {
value: 0,
lists,
draw,
plain,
vertices,
samplers,
still: still.to_vec(),
copies,
args: compute(device, ARGS),
clamp,
add: compute(device, ADD),
@@ -548,6 +643,9 @@ impl Scene {
l.SetGraphicsRoot32BitConstant(0, pick, 0);
l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at);
l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart());
let step = self.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
let first = self.samplers.GetGPUDescriptorHandleForHeapStart().ptr;
l.SetGraphicsRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: first + 2 * u64::from(step) });
l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0);
}
}
@@ -595,16 +693,136 @@ impl Scene {
let size = SIZE as f32;
l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]);
l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]);
l.SetDescriptorHeaps(&[Some(self.views.clone())]);
l.SetDescriptorHeaps(&[Some(self.views.clone()), Some(self.samplers.clone())]);
}
}
/// A triangle with vertices and indices.
fn triangle(&self, l: &ID3D12GraphicsCommandList, n: u32) {
// SAFETY: an open list; live objects; inside the mapping, which the
// card does not use now.
unsafe {
let x = 0.5 + 0.05 * n as f32;
let vertices = [[x, 0.4, 1.0, 0.0, 0.0], [x + 0.3, 0.4, 0.0, 1.0, 0.0], [x, 0.9, 0.0, 0.0, 1.0f32]];
self.vertices.1.cast::<[[f32; 5]; 3]>().write(vertices);
self.vertices.1.add(1024).cast::<[u16; 4]>().write([9, 2, 0, 1]);
let at = self.vertices.0.GetGPUVirtualAddress();
l.SetGraphicsRootSignature(&self.plain.root);
l.SetPipelineState(&self.plain.pso);
l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
l.IASetVertexBuffers(0, Some(&[D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: 60, StrideInBytes: 20 }]));
let indices = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at + 1024, SizeInBytes: 8, Format: DXGI_FORMAT_R16_UINT };
l.IASetIndexBuffer(Some(&indices));
l.DrawIndexedInstanced(3, 1, 1, 0, 0);
}
}
/// Fills the textures no frame touches.
fn fill_still(&mut self) {
// SAFETY: an open list; live objects; mappings written inside their
// bounds.
unsafe {
let (up, data) = committed(
&self.device,
In::Upload,
&buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE),
D3D12_RESOURCE_STATE_GENERIC_READ,
);
for i in 0..1 << 20 {
data.add(i).write((i * 31 + i / 251) as u8 & 0x3b);
}
let l = self.open(0);
let mut at = 0;
for (name, t, ends) in &self.still {
if *name == "stencil" {
let view = D3D12_DEPTH_STENCIL_VIEW_DESC {
Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
..Default::default()
};
let heap: ID3D12DescriptorHeap = self
.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
NumDescriptors: 1,
..Default::default()
})
.unwrap();
let dsv = heap.GetCPUDescriptorHandleForHeapStart();
self.device.CreateDepthStencilView(t, Some(&view), dsv);
let both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL;
l.ClearDepthStencilView(dsv, both, 0.75, 3, None);
let part = RECT { left: 5, top: 6, right: 20, bottom: 17 };
l.ClearDepthStencilView(dsv, both, 0.25, 200, Some(&[part]));
continue;
}
let desc = t.GetDesc();
let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize };
for sub in 0..u32::from(layers * desc.MipLevels) {
let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let mut total = 0;
self.device.GetCopyableFootprints(&desc, sub, 1, at, Some(&mut f), None, None, Some(&mut total));
at = (at + total).next_multiple_of(512);
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&up),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
};
l.CopyTextureRegion(&sub_of(t, sub), 0, 0, 0, &from, None);
}
l.ResourceBarrier(&[moved(t, TO, *ends)]);
}
l.Close().unwrap();
self.send(&[&l]);
self.wait();
}
}
/// What they hold.
fn read_still(&mut self) -> Vec<Still> {
let mut all = Vec::new();
for (name, t, state) in self.still.clone() {
// SAFETY: as above.
unsafe {
let desc = t.GetDesc();
let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize };
let planes = if name == "stencil" { 2 } else { 1 };
let mut subs = Vec::new();
for sub in 0..u32::from(layers * desc.MipLevels) * planes {
let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let (mut rows, mut len) = (0, 0);
self.device.GetCopyableFootprints(&desc, sub, 1, 0, Some(&mut f), Some(&mut rows), Some(&mut len), None);
let l = self.open(0);
l.ResourceBarrier(&[moved(&t, state, FROM)]);
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&self.back.0),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
};
l.CopyTextureRegion(&to, 0, 0, 0, &sub_of(&t, sub), None);
l.ResourceBarrier(&[moved(&t, FROM, state)]);
l.Close().unwrap();
self.send(&[&l]);
self.wait();
let pitch = f.Footprint.RowPitch as usize;
let rows = (0..rows as usize * f.Footprint.Depth as usize)
.map(|r| std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize).to_vec())
.collect();
subs.push((pitch, rows));
}
all.push(Still { name, subs });
}
}
all
}
fn frame(&mut self, n: u32) {
// SAFETY: open lists of ours, live objects; memory is written while
// the card does not use it.
unsafe {
self.wait();
if n == 0 {
self.fill_still();
self.fill(0, [200, 10, 30, 255]);
self.fill(8192, [10, 40, 220, 255]);
let l = self.open(0);
@@ -630,6 +848,7 @@ impl Scene {
self.targets(&l);
self.quad(&l, 4000, 0, 0);
self.quad(&l, 4001, 256, 0);
self.triangle(&l, n);
// Nothing: the clamp cut it to no vertices.
self.quad(&l, 4001, 0, 1);
l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
@@ -680,6 +899,18 @@ impl Scene {
l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]);
l.Close().unwrap();
self.send(&[&second, &l]);
self.wait();
// Another queue fetches a result, as the host layer's relay does.
let (queue, allocator, list) = &self.copies;
allocator.Reset().unwrap();
list.Reset(allocator, None).unwrap();
list.CopyBufferRegion(&self.back.0, 1 << 18, &self.sum, 0, 1024);
list.Close().unwrap();
queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
self.value += 1;
queue.Signal(&self.fence, self.value).unwrap();
self.fence.SetEventOnCompletion(self.value, self.event).unwrap();
WaitForSingleObject(self.event, INFINITE);
if let Some((swap, _)) = &self.swap {
swap.Present(0, DXGI_PRESENT(0)).unwrap();
}
@@ -690,6 +921,7 @@ impl Scene {
/// What everything holds now.
fn outcome(&mut self) -> Outcome {
self.wait();
let still = self.read_still();
let l = self.open(0);
// SAFETY: an open list; live objects.
unsafe {
@@ -713,6 +945,7 @@ impl Scene {
self.wait();
let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec();
Outcome {
still,
picture: at(0, (SIZE * 512) as usize),
image: rows(&at(1 << 18, 4096)),
sum: at(1 << 19, 1024),
@@ -722,6 +955,15 @@ impl Scene {
}
}
fn sub_of(t: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION {
D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer never released.
pResource: unsafe { std::mem::transmute_copy(t) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub },
}
}
/// The 64 bytes of each row of a 16x16 texture.
fn rows(bytes: &[u8]) -> Vec<u8> {
bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect()
@@ -782,7 +1024,19 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str)
assert_eq!(rows(&get("image")), expected.image, "{what}: image");
assert_eq!(get("target"), expected.picture, "{what}: target");
assert!(get("shared") == expected.shared, "{what}: memory the CPU sees");
assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !n.contains("submissions,") && !n.contains("waits of the")), "{what}: {:?}", report.notes);
for still in &expected.still {
let id = player.named(still.name).unwrap();
for (sub, (pitch, rows)) in still.subs.iter().enumerate() {
let have = player.contents_of(id, sub as u32).unwrap().unwrap();
for (r, row) in rows.iter().enumerate() {
assert_eq!(&have[r * pitch..][..row.len()], &row[..], "{what}: {} subresource {sub} row {r}", still.name);
}
}
}
// Nothing was left out but what another queue ran.
let known = ["submissions,", "waits of the drawing queue", "lists sent to a queue other than"];
assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), "{what}: {:?}", report.notes);
assert!(report.notes.iter().any(|n| n.contains(known[2])));
report
}
@@ -813,6 +1067,10 @@ fn a_frame_is_recorded_and_replayed() {
eprintln!("ran without the recorder");
// Something is in the picture.
assert!(without.sum.iter().any(|&b| b != 0));
for s in &without.still {
assert!(s.subs.iter().all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), "{}", s.name);
}
assert_eq!(without.still.iter().map(|s| s.subs.len()).collect::<Vec<_>>(), [15, 3, 2]);
let colors: std::collections::HashSet<[u8; 4]> =
without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect();
assert!(colors.len() > 30, "{}", colors.len());
@@ -821,12 +1079,12 @@ fn a_frame_is_recorded_and_replayed() {
// frame whose lists are all recorded comes first).
assert!(!record::on());
let dir = tempfile::tempdir().unwrap();
let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1 };
let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1, always: false };
let folder = record::start(settings, &device).unwrap();
assert!(record::on());
assert_ne!(table_of(&device), own, "the device is hooked");
assert!(
record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1 }, &device).is_err(),
record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1, always: false }, &device).is_err(),
"one recorder a process"
);
eprintln!("recorder on");
+271
View File
@@ -0,0 +1,271 @@
//! How the frame recorder and replayer do at the size of a title's frame
//! (not run by default: `cargo test --release ... -- --ignored --nocapture`):
//! thousands of textures and buffers, a view heap of 1.5 million slots, 30
//! submissions of 40,000 calls.
//!
//! `BIG_TEXTURES` (17000) and `BIG_FOLDER` (a temporary one) change it.
#![cfg(all(windows, feature = "diagnostics"))]
use std::mem::ManuallyDrop;
use std::time::Instant;
use victory_gpu::replay::play::{self, Options};
use victory_gpu::replay::record::{self, At, Settings};
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::Interface;
const SUBMITS: usize = 30;
const CALLS: usize = 40_000;
const VIEWS: u32 = 1_500_000;
fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut u8) {
let (heap, state, flags) = match kind {
0 => (
D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
),
1 => (
D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() },
D3D12_RESOURCE_STATE_GENERIC_READ,
D3D12_RESOURCE_FLAG_NONE,
),
_ => (
D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
..Default::default()
},
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
),
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: flags,
..Default::default()
};
let mut made: Option<ID3D12Resource> = None;
let mut data = std::ptr::null_mut();
// SAFETY: plain creation and mapping.
unsafe {
device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap();
let made = made.unwrap();
if kind > 0 {
made.Map(0, None, Some(&mut data)).unwrap();
// Not all zero, as real data is.
for at in (0..size as usize).step_by(4096) {
data.cast::<u8>().add(at).write(at as u8 | 1);
}
}
(made, data.cast())
}
}
fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
// SAFETY: a borrowed pointer never released.
pResource: unsafe { std::mem::transmute_copy(res) },
Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
StateBefore: before,
StateAfter: after,
}),
},
..Default::default()
}
}
struct Big {
device: ID3D12Device,
queue: ID3D12CommandQueue,
fence: ID3D12Fence,
value: u64,
lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
_textures: Vec<ID3D12Resource>,
card: Vec<ID3D12Resource>,
shared: Vec<(ID3D12Resource, *mut u8)>,
upload: Vec<(ID3D12Resource, *mut u8)>,
views: ID3D12DescriptorHeap,
target: ID3D12Resource,
}
impl Big {
fn new(device: &ID3D12Device, textures: usize) -> Big {
let texture = |size: u32, flags, state| {
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: u64::from(size),
Height: size,
DepthOrArraySize: 1,
MipLevels: if size == 256 { 9 } else { 1 },
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Flags: flags,
..Default::default()
};
let mut made: Option<ID3D12Resource> = None;
// SAFETY: plain creation.
unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap() };
made.unwrap()
};
// SAFETY: plain creation; slots of the heap just made.
unsafe {
let queue: ID3D12CommandQueue = device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })
.unwrap();
let lists = (0..SUBMITS)
.map(|_| {
let a: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let l: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).unwrap();
l.Close().unwrap();
(a, l)
})
.collect();
let views: ID3D12DescriptorHeap = device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: VIEWS,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
.unwrap();
let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
let start = views.GetCPUDescriptorHandleForHeapStart().ptr;
let textures: Vec<ID3D12Resource> = (0..textures)
.map(|_| texture(256, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE))
.collect();
for i in 0..VIEWS as usize {
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step };
device.CreateShaderResourceView(&textures[i % textures.len()], None, at);
}
let shared: Vec<(ID3D12Resource, *mut u8)> = (0..1000).map(|_| buffer(device, 2, 1 << 20)).collect();
for (i, (b, _)) in shared.iter().enumerate() {
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32_TYPELESS,
ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_SRV { NumElements: 1 << 18, Flags: D3D12_BUFFER_SRV_FLAG_RAW, ..Default::default() },
},
};
device.CreateShaderResourceView(b, Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step });
}
Big {
device: device.clone(),
queue,
fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(),
value: 0,
lists,
_textures: textures,
card: (0..600).map(|_| buffer(device, 0, 1 << 20).0).collect(),
shared,
upload: (0..1000).map(|_| buffer(device, 1, 1 << 20)).collect(),
views,
target: texture(1024, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE),
}
}
}
fn wait(&mut self) {
self.value += 1;
// SAFETY: our queue and fence.
unsafe {
let event = CreateEventW(None, false, false, None).unwrap();
self.queue.Signal(&self.fence, self.value).unwrap();
self.fence.SetEventOnCompletion(self.value, event).unwrap();
WaitForSingleObject(event, INFINITE);
let _ = windows::Win32::Foundation::CloseHandle(event);
self.device.GetDeviceRemovedReason().unwrap();
}
}
fn frame(&mut self, n: usize) {
for s in 0..SUBMITS {
// SAFETY: lists whose last run has finished; mappings written
// inside their bounds.
unsafe {
let (a, l) = &self.lists[s];
a.Reset().unwrap();
l.Reset(a, None).unwrap();
l.SetDescriptorHeaps(&[Some(self.views.clone())]);
for i in 0..CALLS / SUBMITS / 4 {
let card = &self.card[(i * 7 + s) % self.card.len()];
let from = &self.upload[(i + s * 31) % self.upload.len()].0;
l.CopyBufferRegion(card, (i % 1000 * 1000) as u64 & !3, from, 0, 256);
l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]);
l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST)]);
l.SetMarker(1, None, 0);
}
l.Close().unwrap();
for i in 0..60 {
let at = (n * 97 + s * 13 + i * 7) % 1000;
self.shared[at].1.add(i * 4096).write((n + s) as u8);
self.upload[at].1.add(i * 8192).write((n + s) as u8);
}
self.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]);
}
self.wait();
}
record::present(&self.target, D3D12_RESOURCE_STATE_COPY_SOURCE);
}
}
#[test]
#[ignore = "takes gigabytes of the card's memory and the disk"]
fn a_frame_of_a_titles_size() {
let mut device: Option<ID3D12Device> = None;
// SAFETY: plain creation.
unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).unwrap() };
let device = device.unwrap();
let textures = std::env::var("BIG_TEXTURES").ok().and_then(|v| v.parse().ok()).unwrap_or(17_000);
let timed = |what: &str, began: Instant| println!("{what}: {:.1} ms", began.elapsed().as_secs_f64() * 1e3);
let began = Instant::now();
{
let mut big = Big::new(&device, textures);
timed("made, without the recorder", began);
for n in 0..4 {
let began = Instant::now();
big.frame(n);
timed("frame, without the recorder", began);
}
}
let dir = tempfile::tempdir().unwrap();
let folder = std::env::var_os("BIG_FOLDER").map_or(dir.path().to_owned(), Into::into);
let settings = Settings { folder, at: At::Frame(4), frames: 1, always: false };
let folder = record::start(settings, &device).unwrap();
let began = Instant::now();
let mut big = Big::new(&device, textures);
timed("made, with the recorder", began);
for n in 0..8 {
let began = Instant::now();
big.frame(n);
timed(["frame", "frame, lists recorded", "frame, captured", "frame, after"][[0, 0, 0, 0, 1, 1, 2, 3][n]], began);
}
assert_eq!(record::finished(), Some(folder.clone()));
drop(big);
record::unhook(&device);
println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap());
for f in std::fs::read_dir(&folder).unwrap().flatten() {
println!("{:>8} MB {}", f.metadata().unwrap().len() >> 20, f.file_name().to_string_lossy());
}
let began = Instant::now();
let reports = play::replay(&folder, &Options { loops: 3, ..Default::default() }).unwrap();
timed("loaded and replayed", began);
for (what, r) in &reports {
println!("{}", r.text(what));
}
}
+2
View File
@@ -19,6 +19,8 @@ pub mod runtime;
pub use host::HostPolicy;
pub use registry::{HleExport, HleModule, registry};
pub use victory_gpu::console;
#[cfg(all(windows, feature = "diagnostics"))]
pub use victory_gpu::replay;
use victory_loader::{ImportResolver, Provenance, Resolution};
use victory_pe::ImportSymbol;