From 59a556e4b0285ced37b16b29b93dc2fdc97698ca Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:00:23 -0600 Subject: [PATCH 1/3] Record and replay a frame's D3D12 work (diagnostics builds) Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/capture.rs | 29 +- crates/victory-gpu/src/host.rs | 15 +- crates/victory-gpu/src/indirect.rs | 2 + crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/replay/edit.rs | 327 ++++ crates/victory-gpu/src/replay/gpu.rs | 392 +++++ crates/victory-gpu/src/replay/hook.rs | 290 ++++ crates/victory-gpu/src/replay/mod.rs | 17 + crates/victory-gpu/src/replay/play.rs | 2042 ++++++++++++++++++++++ crates/victory-gpu/src/replay/pso.rs | 317 ++++ crates/victory-gpu/src/replay/record.rs | 2079 +++++++++++++++++++++++ crates/victory-gpu/src/replay/snap.rs | 923 ++++++++++ crates/victory-gpu/src/replay/states.rs | 192 +++ crates/victory-gpu/src/replay/wire.rs | 741 ++++++++ crates/victory-gpu/tests/replay.rs | 909 ++++++++++ 15 files changed, 8270 insertions(+), 7 deletions(-) create mode 100644 crates/victory-gpu/src/replay/edit.rs create mode 100644 crates/victory-gpu/src/replay/gpu.rs create mode 100644 crates/victory-gpu/src/replay/hook.rs create mode 100644 crates/victory-gpu/src/replay/mod.rs create mode 100644 crates/victory-gpu/src/replay/play.rs create mode 100644 crates/victory-gpu/src/replay/pso.rs create mode 100644 crates/victory-gpu/src/replay/record.rs create mode 100644 crates/victory-gpu/src/replay/snap.rs create mode 100644 crates/victory-gpu/src/replay/states.rs create mode 100644 crates/victory-gpu/src/replay/wire.rs create mode 100644 crates/victory-gpu/tests/replay.rs diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index 19947f3..b4010f8 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -178,6 +178,27 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: } } } + let png = encode(w, h, &raw); + let path = folder.join(format!("{name}.png")); + match std::fs::write(&path, png) { + Ok(()) => tracing::info!(path = %path.display(), "frame saved"), + Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"), + } +} + +/// A PNG of `width * height` pixels of 8-bit RGB. +pub(crate) fn png(width: u32, height: u32, rgb: &[u8]) -> Vec { + let row = width as usize * 3; + let mut raw = Vec::with_capacity((row + 1) * height as usize); + for line in rgb.chunks_exact(row.max(1)) { + raw.push(0); + raw.extend_from_slice(line); + } + encode(width, height, &raw) +} + +/// A PNG of rows of RGB, each behind its filter byte. +fn encode(w: u32, h: u32, raw: &[u8]) -> Vec { let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); let mut header = Vec::new(); header.extend(w.to_be_bytes()); @@ -185,15 +206,11 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: header.extend([8, 2, 0, 0, 0]); // 8-bit RGB chunk(&mut png, b"IHDR", &header); let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; - let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3)); + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, raw, zlib_rs::DeflateConfig::new(3)); debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); chunk(&mut png, b"IDAT", idat); chunk(&mut png, b"IEND", &[]); - let path = folder.join(format!("{name}.png")); - match std::fs::write(&path, png) { - Ok(()) => tracing::info!(path = %path.display(), "frame saved"), - Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"), - } + png } fn chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7c6448a..332ebee 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -602,6 +602,9 @@ fn create() -> windows::core::Result { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } let device = device.ok_or_else(windows::core::Error::empty)?; + // Before anything is made with it (`VICTORY_RECORD`). + #[cfg(feature = "diagnostics")] + crate::replay::record::from_env(&device); // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the // driver compiling shaders again on the "D3D Background Thread"s, // for minutes after pipelines were made or loaded) is switched off. @@ -1295,8 +1298,14 @@ fn timing() -> bool { } /// Names a host object for the device-removed report, which names the -/// allocations a page fault hit (only with device-removed data on). +/// allocations a page fault hit (only with device-removed data on), or for +/// the frame recorder (`VICTORY_RECORD`). 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()); + return; + } if dred_on() && let Ok(object) = object.cast::() { @@ -3126,6 +3135,8 @@ impl Host { }, ..Default::default() })?; + #[cfg(feature = "diagnostics")] + name(&pso, || crate::replay::play::COMPARE.into()); Ok(CardWork { sync: vec![list()?], check: vec![list()?], @@ -6353,6 +6364,8 @@ impl Host { if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); } + #[cfg(feature = "diagnostics")] + crate::replay::record::present(texture, state); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); p.meter.frame(p.hwnd); #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index fbc9805..af7f010 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -279,6 +279,8 @@ fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result, psos: &HashSet) -> (Vec, u32) { + let mut bound = NONE; + let mut dropped = 0; + let out = cmds + .into_iter() + .filter(|c| { + if let Cmd::Pipeline { pso } = c { + bound = *pso; + } + let drop = c.runs_shaders() && psos.contains(&bound); + dropped += u32::from(drop); + !drop + }) + .collect(); + (out, dropped) +} + +/// Drops unordered-access barriers; how many. +pub fn no_uav_barriers(cmds: Vec) -> (Vec, u32) { + let mut dropped = 0; + let out = cmds + .into_iter() + .filter_map(|c| match c { + Cmd::Barriers { mut all } => { + let n = all.len(); + all.retain(|b| !matches!(b, Barrier::Uav { .. })); + dropped += (n - all.len()) as u32; + (!all.is_empty()).then_some(Cmd::Barriers { all }) + } + c => Some(c), + }) + .collect(); + (out, dropped) +} + +/// Barriers only: what a list left out still does to the states of +/// resources. +pub fn barriers_only(cmds: Vec) -> Vec { + cmds.into_iter().filter(|c| matches!(c, Cmd::Barriers { .. })).collect() +} + +/// Joins the barrier calls with no work between them into one; how many +/// calls that saved. +pub fn merge_barriers(cmds: Vec) -> (Vec, u32) { + let mut out: Vec = Vec::with_capacity(cmds.len()); + let mut open: Option = None; + let mut saved = 0; + for c in cmds { + match c { + Cmd::Barriers { all } => { + if let Some(i) = open + && let Cmd::Barriers { all: have } = &mut out[i] + { + for b in all { + join(have, b); + } + saved += 1; + } else { + open = Some(out.len()); + let mut have = Vec::new(); + for b in all { + join(&mut have, b); + } + out.push(Cmd::Barriers { all: have }); + } + } + c => { + if c.works() || matches!(c, Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }) { + open = None; + } + out.push(c); + } + } + } + out.retain(|c| !matches!(c, Cmd::Barriers { all } if all.is_empty())); + (out, saved) +} + +/// Adds a barrier to a call's. +fn join(have: &mut Vec, b: Barrier) { + match b { + Barrier::Uav { res, .. } => { + let covered = have.iter().any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE)); + if covered { + return; + } + if res == NONE { + have.retain(|h| !matches!(h, Barrier::Uav { .. })); + } + have.push(b); + } + Barrier::Transition { flags: 0, res, sub, before, after } => { + // The last one of this resource, if it is of the same part of it. + let last = have.iter().rposition(|h| matches!(h, Barrier::Transition { res: r, .. } if *r == res)); + if let Some(i) = last + && let Barrier::Transition { flags: 0, sub: s, before: first, after: until, .. } = have[i] + && s == sub + && until == before + { + if first != after { + have[i] = Barrier::Transition { flags: 0, res, sub, before: first, after }; + } else { + have.remove(i); + if after == UNORDERED_ACCESS { + // Still a wait for the writes before. + join(have, Barrier::Uav { flags: 0, res }); + } + } + return; + } + have.push(b); + } + b => have.push(b), + } +} + +/// A clamp pass of ours found in a list. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clamp { + /// The command that dispatches it. + pub at: usize, + /// The scratch buffer it writes the arguments to, from its start. + pub scratch: u32, + pub bytes: u64, + /// Where its arguments are in [`RESULTS`]. + pub result: u64, +} + +/// The clamp passes of a list (`psos`: the clamp's pipelines), given places +/// in the results from `next` on. +pub fn find_clamps(cmds: &[Cmd], psos: &HashSet, next: &mut u64) -> Vec { + let (mut bound, mut constants, mut to) = (NONE, [0u32; 6], None); + let mut found = Vec::new(); + for (at, c) in cmds.iter().enumerate() { + match c { + Cmd::Pipeline { pso } => bound = *pso, + Cmd::Constants { graphics: false, param: 0, offset, values } => { + for (i, v) in values.iter().enumerate() { + if let Some(c) = constants.get_mut(*offset as usize + i) { + *c = *v; + } + } + } + // The clamp's parameters: constants (kind, stride, records, + // ...), arguments, count, then where it writes. + Cmd::RootView { graphics: false, param: 3, va: Va::At { res, offset: 0 }, .. } => to = Some(*res), + Cmd::Dispatch { .. } if psos.contains(&bound) => { + if let Some(scratch) = to { + let bytes = u64::from(constants[1]) * u64::from(constants[2]); + found.push(Clamp { at, scratch, bytes, result: *next }); + *next += bytes.next_multiple_of(256); + } + } + _ => {} + } + } + found +} + +/// The list with a copy of what each clamp wrote into the results. +pub fn keep_clamped(cmds: Vec, clamps: &[Clamp]) -> Vec { + let mut out = Vec::with_capacity(cmds.len() + 3 * clamps.len()); + let mut open: Option = None; + for (at, c) in cmds.into_iter().enumerate() { + if let Some(clamp) = clamps.iter().find(|c| c.at == at) { + open = Some(*clamp); + } + let readable = |b: &Barrier, scratch: u32| matches!(b, Barrier::Transition { res, after: INDIRECT_ARGUMENT, .. } if *res == scratch); + let done = match (&c, open) { + (Cmd::Barriers { all }, Some(clamp)) => all.iter().any(|b| readable(b, clamp.scratch)), + _ => false, + }; + out.push(c); + if done && let Some(clamp) = open.take() { + let moved = |before, after| Cmd::Barriers { + all: vec![Barrier::Transition { flags: 0, res: clamp.scratch, sub: ALL, before, after }], + }; + out.push(moved(INDIRECT_ARGUMENT, COPY_SOURCE)); + out.push(Cmd::CopyBuffer { dst: RESULTS, dst_at: clamp.result, src: clamp.scratch, src_at: 0, len: clamp.bytes }); + out.push(moved(COPY_SOURCE, INDIRECT_ARGUMENT)); + } + } + out +} + +/// The list without its clamp passes and the barriers of their scratch +/// buffers; what they bounded is read from the results instead. +pub fn skip_clamps(cmds: Vec, clamps: &[Clamp]) -> Vec { + let scratches: HashSet = clamps.iter().map(|c| c.scratch).collect(); + let by_at: HashMap = clamps.iter().map(|c| (c.at, c)).collect(); + let mut last: HashMap = HashMap::new(); + let mut out = Vec::with_capacity(cmds.len()); + for (at, c) in cmds.into_iter().enumerate() { + if let Some(clamp) = by_at.get(&at) { + last.insert(clamp.scratch, clamp.result); + continue; + } + match c { + Cmd::Barriers { mut all } => { + let of_scratch = |b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res)); + if all.iter().any(of_scratch) { + // The waits made with the scratch buffer's moves are the + // clamp's too. + all.retain(|b| !of_scratch(b) && !matches!(b, Barrier::Uav { res: NONE, .. })); + } + if !all.is_empty() { + out.push(Cmd::Barriers { all }); + } + } + Cmd::Indirect { signature, most, args, at, count, count_at } if last.contains_key(&args) => { + let result = last.get(&args).copied().unwrap_or(0); + out.push(Cmd::Indirect { signature, most, args: RESULTS, at: result + at, count, count_at }); + } + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pso(pso: u32) -> Cmd { + Cmd::Pipeline { pso } + } + fn go() -> Cmd { + Cmd::Dispatch { groups: [1, 1, 1] } + } + fn uav(res: u32) -> Barrier { + Barrier::Uav { flags: 0, res } + } + fn moved(res: u32, before: i32, after: i32) -> Barrier { + Barrier::Transition { flags: 0, res, sub: ALL, before, after } + } + fn barriers(all: &[Barrier]) -> Cmd { + Cmd::Barriers { all: all.to_vec() } + } + + #[test] + fn pipelines_are_skipped() { + let list = vec![pso(1), go(), pso(2), go(), go(), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]; + let (out, n) = skip_pipelines(list.clone(), &HashSet::from([2])); + assert_eq!(n, 2); + assert_eq!(out, vec![pso(1), go(), pso(2), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]); + assert_eq!(skip_pipelines(list.clone(), &HashSet::new()), (list, 0)); + } + + #[test] + fn uav_barriers_are_dropped() { + let list = vec![barriers(&[uav(0)]), go(), barriers(&[uav(1), moved(1, 8, 4)])]; + assert_eq!(no_uav_barriers(list.clone()), (vec![go(), barriers(&[moved(1, 8, 4)])], 2)); + assert_eq!(barriers_only(list.clone()), vec![list[0].clone(), list[2].clone()]); + } + + #[test] + fn barriers_are_merged() { + let list = vec![ + barriers(&[moved(1, 0, 8)]), + pso(1), + barriers(&[uav(2), moved(1, 8, 64)]), + barriers(&[uav(0), uav(3)]), + go(), + // There and back again: nothing is left but the wait. + barriers(&[moved(1, 8, 64)]), + barriers(&[moved(1, 64, 8)]), + go(), + barriers(&[moved(4, 4, 128)]), + barriers(&[moved(4, 128, 4)]), + ]; + let (out, saved) = merge_barriers(list); + assert_eq!(saved, 4); + assert_eq!(out, vec![barriers(&[moved(1, 0, 64), uav(0)]), pso(1), go(), barriers(&[uav(1)]), go()]); + // Parts of a resource are not mixed up. + let part = |sub, before, after| Barrier::Transition { flags: 0, res: 1, sub, before, after }; + let list = vec![barriers(&[part(0, 4, 8)]), barriers(&[part(1, 4, 8)]), barriers(&[part(ALL, 8, 64)])]; + assert_eq!(merge_barriers(list).0, vec![barriers(&[part(0, 4, 8), part(1, 4, 8), part(ALL, 8, 64)])]); + } + + #[test] + fn clamps_are_found_kept_and_skipped() { + let clamp = |scratch, stride, records| { + vec![ + barriers(&[uav(0), moved(scratch, 0, 8)]), + pso(9), + Cmd::Constants { graphics: false, param: 0, offset: 0, values: vec![10, stride, records, 0, 0, 0] }, + Cmd::RootView { graphics: false, kind: 3, param: 3, va: Va::At { res: scratch, offset: 0 } }, + go(), + barriers(&[uav(0), moved(scratch, 8, 0x200)]), + ] + }; + let run = |args, at| Cmd::Indirect { signature: 1, most: 1, args, at, count: 0, count_at: 0 }; + let mut list = clamp(5, 12, 2); + list.extend([pso(1), run(5, 12), run(5, 0), run(6, 0)]); + list.extend(clamp(5, 12, 100)); + list.extend([pso(1), run(5, 24), barriers(&[moved(5, 0x200, 0)])]); + let mut next = 0; + let found = find_clamps(&list, &HashSet::from([9]), &mut next); + assert_eq!(found.iter().map(|c| (c.scratch, c.bytes, c.result)).collect::>(), [(5, 24, 0), (5, 1200, 256)]); + assert_eq!(next, 256 + 1280); + let kept = keep_clamped(list.clone(), &found); + assert_eq!(kept.len(), list.len() + 6); + assert_eq!(kept[7], Cmd::CopyBuffer { dst: RESULTS, dst_at: 0, src: 5, src_at: 0, len: 24 }); + assert_eq!(kept.iter().filter(|c| matches!(c, Cmd::CopyBuffer { .. })).count(), 2); + let skipped = skip_clamps(list, &found); + assert!(!skipped.iter().any(|c| matches!(c, Cmd::Dispatch { .. } | Cmd::Barriers { .. }))); + let runs: Vec<(u32, u64)> = + skipped.iter().filter_map(|c| if let Cmd::Indirect { args, at, .. } = c { Some((*args, *at)) } else { None }).collect(); + assert_eq!(runs, [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]); + } +} diff --git a/crates/victory-gpu/src/replay/gpu.rs b/crates/victory-gpu/src/replay/gpu.rs new file mode 100644 index 0000000..61ed472 --- /dev/null +++ b/crates/victory-gpu/src/replay/gpu.rs @@ -0,0 +1,392 @@ +//! Small D3D12 helpers the recorder and the replayer share. + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::{Interface, Result}; + +use super::wire; + +/// Lists of our own on a queue, with a fence. +pub(super) struct Worker { + pub(super) device: ID3D12Device, + pub(super) queue: ID3D12CommandQueue, + fence: ID3D12Fence, + event: HANDLE, + value: u64, + /// Allocator, list, and the fence value its last run ends with. + lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u64)>, +} + +// SAFETY: D3D12 objects are free-threaded; a worker is used by one thread +// at a time (`&mut self`). +unsafe impl Send for Worker {} + +impl Worker { + pub(super) fn new(device: &ID3D12Device, queue: &ID3D12CommandQueue) -> Result { + // SAFETY: plain object creation. + unsafe { + Ok(Worker { + device: device.clone(), + queue: queue.clone(), + fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + event: CreateEventW(None, false, false, None)?, + value: 0, + lists: Vec::new(), + }) + } + } + + /// Records a list and sends it; the value [`Worker::wait`] takes. + pub(super) fn send(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> Result { + // SAFETY: lists and allocators of ours whose last run has finished. + unsafe { + let done = self.fence.GetCompletedValue(); + let i = match self.lists.iter().position(|l| l.2 <= done) { + Some(i) => i, + None => { + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + self.lists.push((allocator, list, 0)); + self.lists.len() - 1 + } + }; + let (allocator, list, last) = &mut self.lists[i]; + allocator.Reset()?; + list.Reset(&*allocator, None)?; + record(list); + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + self.value += 1; + *last = self.value; + self.queue.Signal(&self.fence, self.value)?; + } + Ok(self.value) + } + + /// Everything sent to the queue so far has run. + pub(super) fn idle(&mut self) -> Result<()> { + self.value += 1; + // SAFETY: our queue and fence. + unsafe { self.queue.Signal(&self.fence, self.value)? }; + self.wait(self.value) + } + + pub(super) fn wait(&self, value: u64) -> Result<()> { + // SAFETY: our fence and event. + unsafe { + if self.fence.GetCompletedValue() < value { + self.fence.SetEventOnCompletion(value, self.event)?; + WaitForSingleObject(self.event, INFINITE); + } + self.device.GetDeviceRemovedReason() + } + } + + /// Sends and waits. + pub(super) fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> Result<()> { + let value = self.send(record)?; + self.wait(value) + } +} + +pub(super) fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A buffer of ours; heap types that are mapped come with their mapping. +pub(super) fn buffer( + device: &ID3D12Device, + kind: D3D12_HEAP_TYPE, + size: u64, + flags: D3D12_RESOURCE_FLAGS, +) -> Result<(ID3D12Resource, *mut u8)> { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let state = match kind { + D3D12_HEAP_TYPE_UPLOAD => D3D12_RESOURCE_STATE_GENERIC_READ, + D3D12_HEAP_TYPE_READBACK => D3D12_RESOURCE_STATE_COPY_DEST, + _ => D3D12_RESOURCE_STATE_COMMON, + }; + let mut made: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping. + unsafe { + device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, flags), state, None, &mut made)?; + let made = made.ok_or_else(windows::core::Error::empty)?; + if kind == D3D12_HEAP_TYPE_UPLOAD || kind == D3D12_HEAP_TYPE_READBACK { + made.Map(0, None, Some(&mut data))?; + } + Ok((made, data.cast())) + } +} + +/// Planes of a format (depth and stencil, or a video format's). +pub(super) fn planes(format: i32) -> u32 { + match format { + 19..=22 | 44..=47 | 103..=106 => 2, + _ => 1, + } +} + +/// Subresources of a texture (1 for a buffer). +pub(super) fn subresources(d: &wire::Desc) -> u32 { + if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + return 1; + } + let layers = if d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { 1 } else { u32::from(d.depth) }; + u32::from(d.mips.max(1)) * layers.max(1) * planes(d.format) +} + +/// The layout of `count` subresources from `first` in a buffer, and its +/// size. +pub(super) fn footprints( + device: &ID3D12Device, + desc: &D3D12_RESOURCE_DESC, + first: u32, + count: u32, +) -> (Vec, u64) { + let mut all = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; + let mut total = 0; + // SAFETY: outputs for `count` subresources. + unsafe { device.GetCopyableFootprints(desc, first, count, 0, Some(all.as_mut_ptr()), None, None, Some(&mut total)) }; + (all, total) +} + +/// A location naming a subresource; no reference is taken. +pub(super) fn sub_location(res: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(res) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub }, + } +} + +/// A location naming bytes of a buffer; no reference is taken. +pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(res) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f }, + } +} + +/// A transition; no reference is taken. +pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(res) }, + Subresource: sub, + StateBefore: D3D12_RESOURCE_STATES(before as i32), + StateAfter: D3D12_RESOURCE_STATES(after as i32), + }), + }, + } +} + +/// The barriers that move a texture from `from` (one state, or one for each +/// subresource) to `to`. +pub(super) fn moves(res: &ID3D12Resource, from: &[u32], to: &[u32], out: &mut Vec) { + let n = from.len().max(to.len()); + if n == 1 { + if from[0] != to[0] { + out.push(transition(res, wire::ALL, from[0], to[0])); + } + return; + } + for i in 0..n { + let (a, b) = (from[i.min(from.len() - 1)], to[i.min(to.len() - 1)]); + if a != b { + out.push(transition(res, i as u32, a, b)); + } + } +} + +pub(super) fn to_desc(d: &wire::Desc) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION(d.dimension), + Alignment: d.alignment, + Width: d.width, + Height: d.height, + DepthOrArraySize: d.depth, + MipLevels: d.mips, + Format: DXGI_FORMAT(d.format), + SampleDesc: DXGI_SAMPLE_DESC { Count: d.samples[0], Quality: d.samples[1] }, + Layout: D3D12_TEXTURE_LAYOUT(d.layout), + Flags: D3D12_RESOURCE_FLAGS(d.flags), + } +} + +pub(super) fn from_desc(d: &D3D12_RESOURCE_DESC) -> wire::Desc { + wire::Desc { + dimension: d.Dimension.0, + alignment: d.Alignment, + width: d.Width, + height: d.Height, + depth: d.DepthOrArraySize, + mips: d.MipLevels, + format: d.Format.0, + samples: [d.SampleDesc.Count, d.SampleDesc.Quality], + layout: d.Layout.0, + flags: d.Flags.0, + } +} + +pub(super) fn to_props(p: &wire::HeapProps) -> D3D12_HEAP_PROPERTIES { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE(p.kind), + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY(p.cpu), + MemoryPoolPreference: D3D12_MEMORY_POOL(p.pool), + ..Default::default() + } +} + +pub(super) fn from_props(p: &D3D12_HEAP_PROPERTIES) -> wire::HeapProps { + wire::HeapProps { kind: p.Type.0, cpu: p.CPUPageProperty.0, pool: p.MemoryPoolPreference.0 } +} + +/// How the CPU sees memory of a heap. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Seen { + /// Not at all: the card's own. + No, + /// Cached, read and written. + Cached, + /// Write-combined: slow to read. + Combined, + /// A read-back heap: the CPU only reads. + ReadBack, +} + +pub(super) fn seen(p: &wire::HeapProps) -> Seen { + match D3D12_HEAP_TYPE(p.kind) { + D3D12_HEAP_TYPE_DEFAULT => Seen::No, + D3D12_HEAP_TYPE_UPLOAD => Seen::Combined, + D3D12_HEAP_TYPE_READBACK => Seen::ReadBack, + D3D12_HEAP_TYPE_CUSTOM => match D3D12_CPU_PAGE_PROPERTY(p.cpu) { + D3D12_CPU_PAGE_PROPERTY_WRITE_BACK => Seen::Cached, + D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE => Seen::Combined, + _ => Seen::No, + }, + // GPU upload heaps (type 5). + _ => Seen::Combined, + } +} + +/// 8-bit RGB of a presented texture's rows (and the greatest channel value +/// of the format, for the signal-to-noise ratio). `None` for formats not +/// shown. +pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) -> Option> { + let mut out = Vec::with_capacity((width * height * 3) as usize); + let half = |b: &[u8]| { + let h = u16::from_le_bytes([b[0], b[1]]); + let (s, e, m) = (h >> 15, (h >> 10) & 31, f32::from(h & 1023)); + let v = match e { + 0 => m * 2f32.powi(-24), + 31 => 65536.0, + e => (1.0 + m / 1024.0) * 2f32.powi(i32::from(e) - 15), + }; + if s == 1 { 0 } else { (v.min(1.0) * 255.0) as u8 } + }; + for y in 0..height as usize { + let row = rows.get(y * pitch as usize..)?; + for x in 0..width as usize { + match format { + 27..=32 => out.extend_from_slice(row.get(x * 4..x * 4 + 3)?), + 87 | 88 | 90..=93 => { + let p = row.get(x * 4..x * 4 + 3)?; + out.extend([p[2], p[1], p[0]]); + } + 23..=25 => { + let p = row.get(x * 4..x * 4 + 4)?; + let v = u32::from_le_bytes([p[0], p[1], p[2], p[3]]); + out.extend([(v >> 2) as u8, (v >> 12) as u8, (v >> 22) as u8]); + } + 9..=14 => { + let p = row.get(x * 8..x * 8 + 6)?; + out.extend([half(p), half(&p[2..]), half(&p[4..])]); + } + _ => return None, + } + } + } + Some(out) +} + +/// Peak signal-to-noise ratio of two pictures of 8-bit channels, in dB +/// (infinite if equal). +pub(super) fn psnr(a: &[u8], b: &[u8]) -> f64 { + let sum: u64 = a.iter().zip(b).map(|(&x, &y)| u64::from(x.abs_diff(y)).pow(2)).sum(); + if sum == 0 && a.len() == b.len() { + return f64::INFINITY; + } + let mean = sum as f64 / a.len().min(b.len()).max(1) as f64; + 10.0 * (255.0 * 255.0 / mean).log10() +} + +/// The adapter a device is on: name, vendor and device number. +pub(super) fn adapter(device: &ID3D12Device) -> (String, u32, u32) { + use windows::Win32::Graphics::Dxgi::*; + // SAFETY: plain queries. + let desc = unsafe { + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(device.GetAdapterLuid())) + .and_then(|a| a.GetDesc1()) + }; + match desc { + Ok(d) => { + let name = String::from_utf16_lossy(&d.Description); + (name.trim_end_matches('\0').to_owned(), d.VendorId, d.DeviceId) + } + Err(_) => ("unknown".into(), 0, 0), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pictures() { + assert_eq!(rgb(1, 1, 4, 28, &[1, 2, 3, 4]).unwrap(), [1, 2, 3]); + assert_eq!(rgb(1, 1, 4, 87, &[1, 2, 3, 4]).unwrap(), [3, 2, 1]); + let v = (1023u32 | 512 << 10).to_le_bytes(); + assert_eq!(rgb(1, 1, 4, 24, &v).unwrap(), [255, 128, 0]); + // 1.0, 0.5 and -1.0 as halves. + assert_eq!(rgb(1, 1, 8, 10, &[0, 0x3c, 0, 0x38, 0, 0xbc, 0, 0]).unwrap(), [255, 127, 0]); + assert!(rgb(1, 1, 4, 41, &[0; 4]).is_none()); + assert!(rgb(2, 2, 8, 28, &[0; 12]).is_none(), "too few rows"); + assert_eq!(psnr(&[1, 2], &[1, 2]), f64::INFINITY); + assert!((psnr(&[0; 4], &[255; 4])).abs() < 1e-9); + } + + #[test] + fn states_of_subresources() { + assert_eq!(planes(44), 2); + let mut d = from_desc(&buffer_desc(10, D3D12_RESOURCE_FLAG_NONE)); + assert_eq!(subresources(&d), 1); + assert_eq!(from_desc(&to_desc(&d)), d); + (d.dimension, d.depth, d.mips, d.format) = (3, 6, 4, 19); + assert_eq!(subresources(&d), 48); + d.dimension = 4; + assert_eq!(subresources(&d), 8); + } +} diff --git a/crates/victory-gpu/src/replay/hook.rs b/crates/victory-gpu/src/replay/hook.rs new file mode 100644 index 0000000..e4ceca4 --- /dev/null +++ b/crates/victory-gpu/src/replay/hook.rs @@ -0,0 +1,290 @@ +//! Methods of single COM objects replaced: an object's method table pointer +//! is set to a copy of its table ([`Shim`]) with some entries changed. Other +//! objects of the class keep theirs, so what is not asked for is untouched. + +use std::collections::BTreeSet; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Methods in a copied table: more than any D3D12 interface has (an +/// interface's private methods may follow its public ones). +pub(super) const SLOTS: usize = 192; +/// Entries copied from before the table (type information). +const PRE: usize = 4; + +/// A copied method table. Objects point at `table`; what we keep for them +/// lies before it. Never freed: an object may still use it while it dies. +#[repr(C)] +struct Shim { + state: *const c_void, + orig: *const usize, + pre: [usize; PRE], + table: [usize; SLOTS], +} + +const TO_ORIG: usize = std::mem::offset_of!(Shim, table) - std::mem::offset_of!(Shim, orig); + +/// The shims made, by the address objects point at. +static MADE: Mutex> = Mutex::new(BTreeSet::new()); + +unsafe fn shim(this: *mut c_void) -> *const Shim { + // SAFETY: the caller's object points into a shim. + unsafe { + let table = *this.cast::<*const u8>(); + table.sub(std::mem::offset_of!(Shim, table)).cast() + } +} + +/// The object's own method table, as `T` (an interface's `_Vtbl`). +/// +/// # Safety +/// `this` is an object [`install`] was called for, of an interface `T` is +/// the table of. +pub(super) unsafe fn orig(this: *mut c_void) -> &'static T { + // SAFETY: the caller's. + unsafe { &*(*shim(this)).orig.cast::() } +} + +/// What [`install`] was given for the object. +/// +/// # Safety +/// As [`orig`]; `T` is what `state` pointed at. +pub(super) unsafe fn state(this: *mut c_void) -> &'static T { + // SAFETY: the caller's. + unsafe { &*(*shim(this)).state.cast::() } +} + +/// Bytes readable from `at` on (up to a limit): what is copied of a table +/// must not run past its module's data. +fn readable(at: usize, most: usize) -> usize { + use windows_sys::Win32::System::Memory::*; + let mut end = at; + while end < at + most { + // SAFETY: a plain query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: as above. + let n = unsafe { VirtualQuery(end as *const c_void, &mut info, size_of::()) }; + const READ: u32 = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + if n == 0 || info.State != MEM_COMMIT || info.Protect & READ == 0 || info.Protect & PAGE_GUARD != 0 { + break; + } + end = info.BaseAddress as usize + info.RegionSize; + } + end.min(at + most) - at +} + +/// Gives the object a table of its own, changed by `patch`. `state` is what +/// [`state`] answers; it must live for good. False if the object has one +/// already (then nothing changes). +/// +/// # Safety +/// `this` is a live COM object no other thread uses yet; what `patch` puts +/// into the table are functions of the methods' types. +pub(super) unsafe fn install(this: *mut c_void, state: *const c_void, patch: impl FnOnce(&mut [usize; SLOTS])) -> bool { + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a live COM object starts with its table's address. + let at = unsafe { *this.cast::() }; + if made.contains(&at) { + return false; + } + let mut new = Box::new(Shim { state, orig: at as *const usize, pre: [0; PRE], table: [0; SLOTS] }); + let have = readable(at, SLOTS * 8) / 8; + // SAFETY: `have` entries are readable; the object's table is at least + // as long as its interface, and what lies behind it is only copied. + unsafe { std::ptr::copy_nonoverlapping(at as *const usize, new.table.as_mut_ptr(), have) }; + if readable(at - PRE * 8, PRE * 8) == PRE * 8 { + // SAFETY: as above. + unsafe { std::ptr::copy_nonoverlapping((at as *const usize).sub(PRE), new.pre.as_mut_ptr(), PRE) }; + } + patch(&mut new.table); + let new: &'static Shim = Box::leak(new); + made.insert(new.table.as_ptr() as usize); + // SAFETY: the object's first word, its table's address. + unsafe { this.cast::<*const usize>().write(new.table.as_ptr()) }; + true +} + +/// The table the object points at. +/// +/// # Safety +/// `this` is a live COM object. +pub(super) unsafe fn table(this: *mut c_void) -> usize { + // SAFETY: the caller's. + unsafe { *this.cast::() } +} + +/// Whether the object points at a shim of ours. +/// +/// # Safety +/// `this` is a live COM object. +pub(super) unsafe fn ours(this: *mut c_void) -> bool { + // SAFETY: the caller's. + let at = unsafe { table(this) }; + MADE.lock().unwrap_or_else(|e| e.into_inner()).contains(&at) +} + +/// After a method that may have set the object's table pointer anew: it +/// points at its shim (`before`, where it pointed) again. A table it did +/// not have before gets a shim of its own. +/// +/// # Safety +/// As [`install`]; `before` is a shim's table. +pub(super) unsafe fn again(this: *mut c_void, before: usize, patch: impl FnOnce(&mut [usize; SLOTS])) { + // SAFETY: the caller's. + unsafe { + let now = table(this); + if now == before { + return; + } + let shim = (before as *const u8).sub(std::mem::offset_of!(Shim, table)).cast::(); + if (*shim).orig as usize == now { + this.cast::().write(before); + } else { + install(this, (*shim).state, patch); + } + } +} + +/// Gives the object its own table back, if it points at a shim of ours +/// (tests). +/// +/// # Safety +/// `this` is a live object, used by no other thread now. +pub(super) unsafe fn remove(this: *mut c_void) { + let made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: as in `install`. + unsafe { + let at = *this.cast::(); + if made.contains(&at) { + let own = (*shim(this)).orig; + this.cast::<*const usize>().write(own); + } + } +} + +/// Classes of [`uncounted`] calls. +pub(super) const LIST: usize = 0; +pub(super) const DEVICE: usize = 1; +pub(super) const QUEUE: usize = 2; +const CLASSES: usize = 3; + +#[allow(clippy::declare_interior_mutable_const)] +const ZERO: AtomicU64 = AtomicU64::new(0); +static COUNTS: [AtomicU64; CLASSES * SLOTS] = [ZERO; CLASSES * SLOTS]; + +/// How often a method the recorder does not record was called. +pub(super) fn count(class: usize, slot: usize) -> u64 { + COUNTS[class * SLOTS + slot].load(Ordering::Relaxed) +} + +/// A method the recorder does not know how to record: counts the call in +/// [`COUNTS`] and goes on to the object's own. Any arguments pass as they +/// are: only the scratch register `rax` is used. +#[unsafe(naked)] +unsafe extern "system" fn noted() { + core::arch::naked_asm!( + "lock inc qword ptr [rip + {counts} + {at} * 8]", + "mov rax, [rcx]", + "mov rax, [rax - {orig}]", + "jmp qword ptr [rax + ({at} % {slots}) * 8]", + counts = sym COUNTS, + at = const AT, + orig = const TO_ORIG, + slots = const SLOTS, + ) +} + +/// [`noted`] for method `SLOT` of a class, `AT` being `class * SLOTS + slot`. +pub(super) fn noted_entry() -> usize { + noted:: as *const () as usize +} + +/// The slot of a method in its table. +macro_rules! method { + ($vtbl:ident . $name:ident) => { + std::mem::offset_of!(windows::Win32::Graphics::Direct3D12::$vtbl, $name) / 8 + }; +} +pub(super) use method; + +#[cfg(test)] +mod tests { + use super::*; + + #[repr(C)] + struct Vtbl { + methods: [usize; 8], + } + + #[repr(C)] + struct Object { + vtbl: *const Vtbl, + value: u64, + } + + unsafe extern "system" fn add(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + // SAFETY: one of the test's objects. + unsafe { (*this.cast::()).value + a + b + c + d + e as u64 } + } + + type Add = unsafe extern "system" fn(*mut c_void, u64, u64, u64, u64, f64) -> u64; + + unsafe extern "system" fn double(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + // SAFETY: an object with a shim whose first method is `add`. + unsafe { + let first = orig::<[Add; 1]>(this)[0]; + first(this, a, b, c, d, e) * 2 + *state::(this) + } + } + + unsafe fn call(object: &mut Object, slot: usize) -> u64 { + // SAFETY: an entry of `Add`'s type. + unsafe { + let f: Add = std::mem::transmute((*object.vtbl).methods[slot]); + f((&raw mut *object).cast(), 1, 2, 3, 4, 5.0) + } + } + + #[test] + fn one_object_is_changed_and_changed_back() { + static STATE: u64 = 1000; + let vtbl = Vtbl { methods: [add as *const () as usize; 8] }; + let mut a = Object { vtbl: &vtbl, value: 100 }; + let mut b = Object { vtbl: &vtbl, value: 200 }; + // SAFETY: the test's objects; entries of `Add`'s type. + unsafe { + let this: *mut c_void = (&raw mut a).cast(); + let patch = |t: &mut [usize; SLOTS]| { + t[0] = double as *const () as usize; + t[2] = noted_entry::<{ QUEUE * SLOTS + 2 }>(); + }; + assert!(install(this, (&raw const STATE).cast(), patch)); + assert!(!install(this, (&raw const STATE).cast(), patch), "only once"); + assert_eq!(call(&mut a, 0), 230 + 1000); + assert_eq!(call(&mut a, 1), 115); + assert_eq!(call(&mut b, 0), 215, "other objects are untouched"); + // Counted, and passed on with all its arguments. + let before = count(QUEUE, 2); + assert_eq!(call(&mut a, 2), 115); + assert_eq!(call(&mut a, 2), 115); + assert_eq!(count(QUEUE, 2), before + 2); + // A method that set the table pointer anew. + let shim = table(this); + assert!(ours(this)); + a.vtbl = &vtbl; + assert!(!ours(this)); + again(this, shim, patch); + assert_eq!(table(this), shim); + // Or to another table. + let other = Vtbl { methods: [add as *const () as usize; 8] }; + a.vtbl = &other; + again(this, shim, patch); + assert!(ours(this) && table(this) != shim); + assert_eq!(call(&mut a, 0), 230 + 1000); + remove(this); + assert!(std::ptr::eq(a.vtbl, &other)); + assert_eq!(call(&mut a, 0), 115); + } + } +} diff --git a/crates/victory-gpu/src/replay/mod.rs b/crates/victory-gpu/src/replay/mod.rs new file mode 100644 index 0000000..5fd0b06 --- /dev/null +++ b/crates/victory-gpu/src/replay/mod.rs @@ -0,0 +1,17 @@ +//! One frame's D3D12 work recorded and run again, to find out what it costs +//! the card and to try changes on it in seconds (docs/replay.md). +//! +//! [`record`] hooks the host's D3D12 objects (`hook`) and keeps what a frame +//! needs; `snap` writes one frame down; [`play`] runs it. `wire` is what a +//! capture holds, `pso` pipeline descriptions, `states` the states textures +//! are in, `edit` the experiments, `gpu` helpers. + +mod edit; +mod gpu; +mod hook; +pub mod play; +mod pso; +pub mod record; +mod snap; +mod states; +mod wire; diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs new file mode 100644 index 0000000..9f09a0d --- /dev/null +++ b/crates/victory-gpu/src/replay/play.rs @@ -0,0 +1,2042 @@ +//! The replayer: makes a captured frame's objects again, puts their +//! contents back, and runs the frame as often as asked, with its time on +//! the card and experiments on it (`super::edit`). + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt::Write as _; +use std::fs::File; +use std::os::windows::fs::FileExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Instant; + +use anyhow::{Context, Result, anyhow, bail}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::Interface; + +use super::edit::{self, Clamp, RESULTS}; +use super::gpu::{self, Seen, Worker}; +use super::snap::read_sub; +use super::states::{self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, UNORDERED_ACCESS}; +use super::wire::{self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot}; + +/// The name of the argument clamp's pipeline, by which its passes are +/// recognised. +pub const CLAMP: &str = "victory: argument clamp"; +/// The name of the pipeline that compares and hashes card buffers. +pub const COMPARE: &str = "victory: card compare"; + +/// An upload buffer contents come back through. +const STAGING: u64 = 256 << 20; + +/// Where buffers the CPU saw lie in a replay. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Buffers { + /// Where they lay. + #[default] + AsRecorded, + /// All in the card's memory. + Card, + /// All in the PC's memory, the card's own buffers too. + Pc, +} + +#[derive(Clone, Debug)] +pub struct Options { + pub loops: u32, + /// Put back, before each run, what the run before changed. + pub restore: bool, + /// Time every command, not only lists. + pub detailed: bool, + /// Shaders listed. + pub top: usize, + /// Where the picture goes (default: `replay.png` in the capture). + pub image: Option, + pub buffers: Buffers, + pub no_barriers: bool, + pub merge_barriers: bool, + pub skip_clamps: bool, + pub skip_hash_passes: bool, + pub one_submit: 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 + /// these in it. + pub skip_shaders: Vec, + /// Run the frame unchanged first, and compare. + pub compare: bool, + /// The debug layer, if it is installed. + pub debug: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { + loops: 5, + restore: true, + detailed: false, + top: 20, + image: None, + buffers: Buffers::AsRecorded, + no_barriers: false, + merge_barriers: false, + skip_clamps: false, + skip_hash_passes: false, + one_submit: false, + only: None, + skip_shaders: Vec::new(), + compare: false, + debug: false, + } + } +} + +impl Options { + fn edited(&self) -> bool { + self.no_barriers + || self.merge_barriers + || self.skip_clamps + || self.skip_hash_passes + || self.one_submit + || self.only.is_some() + || !self.skip_shaders.is_empty() + } + + /// The same without the experiments. + fn plain(&self) -> Options { + Options { + no_barriers: false, + merge_barriers: false, + skip_clamps: false, + skip_hash_passes: false, + one_submit: false, + only: None, + skip_shaders: Vec::new(), + ..self.clone() + } + } +} + +/// How a run went. +#[derive(Clone, Debug, Default)] +pub struct Report { + /// Per loop: from the first list's start to the last one's end, in ms. + pub frame_ms: Vec, + /// Per loop: how long the lists of submissions ran. + pub busy_ms: Vec, + /// Per loop: copies of ours that stand for what the CPU wrote. + pub delta_ms: Vec, + /// Of the last loop, by submission: lists, ms. + pub submits: Vec<(usize, f64)>, + /// With detailed timing, of the last loop: ms and count by category. + pub categories: Vec<(String, f64, u32)>, + /// With detailed timing: ms, count and name of the costliest pipelines. + pub shaders: Vec<(f64, u32, String)>, + /// Against the presented picture: dB (infinite: the same), and whether + /// its bytes are the same. + pub picture: Option<(f64, bool)>, + /// Things to know: from the capture and the replay. + pub notes: Vec, +} + +impl Report { + pub fn median_ms(&self) -> f64 { + median(&self.frame_ms) + } + + /// The report as text. + pub fn text(&self, what: &str) -> String { + let mut t = String::new(); + let ms = |v: &[f64]| v.iter().map(|x| format!("{x:.2}")).collect::>().join(" "); + let _ = writeln!(t, "{what}: {:.2} ms on the card (median of {})", self.median_ms(), self.frame_ms.len()); + let _ = writeln!(t, " loops, ms: {}", ms(&self.frame_ms)); + let (busy, delta) = (median(&self.busy_ms), median(&self.delta_ms)); + let idle = (self.median_ms() - busy - delta).max(0.0); + let _ = writeln!(t, " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms"); + let _ = writeln!(t, " by submission (lists: ms): {}", { + self.submits.iter().enumerate().map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")).collect::>().join(", ") + }); + if !self.categories.is_empty() { + let _ = writeln!(t, " by kind of command, ms (commands):"); + for (name, ms, n) in &self.categories { + let _ = writeln!(t, " {ms:8.2} {n:6} {name}"); + } + } + if !self.shaders.is_empty() { + let _ = writeln!(t, " costliest pipelines, ms (commands):"); + for (ms, n, name) in &self.shaders { + let _ = writeln!(t, " {ms:8.2} {n:6} {name}"); + } + } + match self.picture { + Some((_, true)) => drop(writeln!(t, " picture: the same bytes as presented")), + Some((db, false)) => drop(writeln!(t, " picture: differs from the presented one, PSNR {db:.1} dB")), + None => {} + } + for n in &self.notes { + let _ = writeln!(t, " note: {n}"); + } + t + } +} + +fn median(v: &[f64]) -> f64 { + let mut v = v.to_vec(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied().unwrap_or(0.0) +} + +/// The folder of a capture: `folder`, or the last `capture-` in it that +/// is complete. +pub fn find(folder: &Path) -> Result { + if folder.join("frame.bin").exists() { + return Ok(folder.to_owned()); + } + let mut best: Option<(u32, PathBuf)> = None; + for entry in std::fs::read_dir(folder).with_context(|| format!("{}", folder.display()))?.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { continue }; + if entry.path().join("frame.bin").exists() && best.as_ref().is_none_or(|b| b.0 < n) { + best = Some((n, entry.path())); + } + } + best.map(|b| b.1).ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) +} + +/// 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> { + let mut player = Player::load(folder, options)?; + let mut out = Vec::new(); + if options.compare && options.edited() { + let image = Some(player.folder.join("replay-unchanged.png")); + out.push(("unchanged".into(), player.run(&Options { image, ..options.plain() })?)); + } + let what = if options.edited() { "with the experiments" } else { "unchanged" }; + out.push((what.into(), player.run(options)?)); + Ok(out) +} + +struct Object { + res: ID3D12Resource, + va: u64, + /// In the capture's `resources`. + index: usize, + subs: u32, +} + +/// One version of a shader-visible descriptor heap. +struct Version { + heap: ID3D12DescriptorHeap, + gpu: u64, +} + +pub struct Player { + pub folder: PathBuf, + frame: Frame, + device: ID3D12Device, + worker: Worker, + info: Option, + frequency: f64, + objects: HashMap, + _heaps: HashMap, + roots: HashMap, + pipelines: HashMap, + signatures: HashMap, + queries: HashMap, + /// Descriptor heaps by id, in their versions; each submission's version. + descriptors: HashMap, u64)>, + version_of: Vec, + /// Render target and depth views by what they are of. + targets: HashMap, + _target_heaps: Vec, + /// Copies of what the frame changes, as at its start. + masters: Vec<(u32, ID3D12Resource)>, + /// What the CPU wrote between submissions, and for each submission + /// where in it. + deltas: Option, + delta_parts: Vec>, + /// States at the start of the frame and after it. + start: HashMap>, + end: HashMap>, + /// The results of clamp passes ([`RESULTS`]). + results: Option, + commands: Vec>, + /// Resources in the states of the start (not those of the end). + fresh: bool, + notes: Vec, +} + +/// What a command of a list is timed as. +type Stamp = (usize, &'static str, u32); + +/// A list made from commands, with what its timestamps are of. +struct Built { + _allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + /// The query of its start; its end is the one before the next list's. + first: u32, + last: u32, + stamps: Vec, +} + +impl Player { + pub fn load(folder: &Path, options: &Options) -> Result { + let folder = find(folder)?; + let began = Instant::now(); + let frame = Frame::read(&folder.join("frame.bin"))?; + let (device, info) = make_device(&frame, options.debug)?; + // SAFETY: plain creation and queries. + let (queue, frequency) = unsafe { + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let frequency = queue.GetTimestampFrequency()? as f64; + (queue, frequency) + }; + let commands: Vec> = frame.lists.iter().map(|l| Cmd::all(&l.commands.0)).collect::>()?; + let mut player = Player { + folder, + worker: Worker::new(&device, &queue)?, + device, + info, + frequency, + objects: HashMap::new(), + _heaps: HashMap::new(), + roots: HashMap::new(), + pipelines: HashMap::new(), + signatures: HashMap::new(), + queries: HashMap::new(), + descriptors: HashMap::new(), + version_of: Vec::new(), + targets: HashMap::new(), + _target_heaps: Vec::new(), + masters: Vec::new(), + deltas: None, + delta_parts: Vec::new(), + start: HashMap::new(), + end: HashMap::new(), + results: None, + commands, + fresh: true, + notes: frame.notes.iter().map(|n| format!("recorder: {n}")).collect(), + frame, + }; + player.check()?; + let mut steps: Vec<(&str, std::time::Duration)> = Vec::new(); + let mut step = |what: &'static str, at: &mut Instant| { + steps.push((what, at.elapsed())); + *at = Instant::now(); + }; + let mut at = Instant::now(); + player.make_resources(options.buffers)?; + step("resources", &mut at); + player.make_pipelines()?; + step("pipelines", &mut at); + player.make_descriptors()?; + step("descriptors", &mut at); + player.load_contents()?; + step("contents", &mut at); + player.make_masters()?; + step("copies to restore from", &mut at); + let steps: Vec = 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(", ")); + Ok(player) + } + + fn note(&mut self, n: String) { + tracing::warn!("{n}"); + self.notes.push(n); + } + + /// Says what of the frame is not there. + fn check(&mut self) -> Result<()> { + let missing = self.frame.submits.iter().flat_map(|s| &s.lists).filter(|&&l| l == MISSING).count(); + if missing > 0 { + self.note(format!("{missing} lists of the frame were not recorded: the frame is incomplete")); + } + if self.frame.submits.is_empty() { + bail!("the capture has no submission"); + } + let unknown = self.commands.iter().flatten().filter(|c| matches!(c, Cmd::RootView { va: Va::Unknown { .. }, .. })).count(); + if unknown > 0 { + self.note(format!("{unknown} root views name memory in no known buffer: they are null in the replay")); + } + Ok(()) + } + + fn resource(&self, id: u32) -> Option<&ID3D12Resource> { + if id == RESULTS { + return self.results.as_ref(); + } + self.objects.get(&id).map(|o| &o.res) + } + + fn va(&self, va: &Va) -> u64 { + match va { + Va::At { res, offset } => self.objects.get(res).map_or(0, |o| o.va + offset), + _ => 0, + } + } + + fn make_resources(&mut self, buffers: Buffers) -> Result<()> { + // A heap of memory the CPU sees becomes one the card may write too: + // what the CPU wrote is put back by the card. + let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES { + let pc = |page| D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: page, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let card = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + match (gpu::seen(p), buffers) { + (Seen::ReadBack, _) => gpu::to_props(p), + (_, Buffers::Card) if buffer => card, + (Seen::No, Buffers::Pc) if buffer => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK), + (Seen::Combined, _) if p.kind > D3D12_HEAP_TYPE_CUSTOM.0 => card, + (Seen::Combined, _) => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE), + _ => gpu::to_props(p), + } + }; + // Flags a replay has no use for: sharing, display, not zeroed. + const DROP: i32 = 0x1 | 0x8 | 0x20 | 0x1000; + let used_by_buffers_only: HashSet = { + let mut textures = HashSet::new(); + for r in &self.frame.resources { + if let Place::Placed { heap, .. } = r.place + && r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0 + { + textures.insert(heap); + } + } + self.frame.heaps.iter().map(|h| h.id).filter(|id| !textures.contains(id)).collect() + }; + for h in &self.frame.heaps { + let desc = D3D12_HEAP_DESC { + SizeInBytes: h.size, + Properties: props(&h.props, used_by_buffers_only.contains(&h.id)), + Alignment: h.alignment, + Flags: D3D12_HEAP_FLAGS(h.flags & !DROP), + }; + let mut heap: Option = None; + // SAFETY: plain creation. + unsafe { self.device.CreateHeap(&desc, &mut heap) }.with_context(|| format!("heap {}", h.id))?; + self._heaps.extend(heap.map(|heap| (h.id, heap))); + } + let mut failed = 0; + for (index, r) in self.frame.resources.iter().enumerate() { + let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + let desc = gpu::to_desc(&r.desc); + let mut made: Option = None; + let clear: Option = r.clear.map(|c| { + // SAFETY: 20 bytes that were a clear value. + unsafe { std::mem::transmute::<[u32; 5], D3D12_CLEAR_VALUE>(c) } + }); + let clear = clear.as_ref().map(|c| c as *const _); + // SAFETY: plain creation from a description the host took. + let result = unsafe { + match &r.place { + Place::Placed { heap, offset } => match self._heaps.get(heap) { + Some(h) => self.device.CreatePlacedResource(h, *offset, &desc, D3D12_RESOURCE_STATE_COMMON, clear, &mut made), + None => Err(windows::core::Error::empty()), + }, + Place::Committed { props: p, flags } => { + let p = props(p, is_buffer); + let state = if p.Type == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_COMMON }; + self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAGS(flags & !DROP), &desc, state, clear, &mut made) + } + Place::BackBuffer {} => { + let p = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + } + } + }; + match (result, made) { + (Ok(()), Some(res)) => { + // SAFETY: a live resource. + let va = if is_buffer { unsafe { res.GetGPUVirtualAddress() } } else { 0 }; + self.objects.insert(r.id, Object { res, va, index, subs: gpu::subresources(&r.desc) }); + } + (e, _) => { + if failed == 0 { + tracing::warn!("resource {} not made: {e:?}: {r:?}", r.id); + } + failed += 1; + } + } + if !is_buffer { + self.start.insert(r.id, r.state.clone()); + } + } + if failed > 0 { + self.note(format!("{failed} resources could not be made again")); + } + Ok(()) + } + + fn make_pipelines(&mut self) -> Result<()> { + for (id, blob) in &self.frame.roots { + // SAFETY: a blob the host took. + let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }.with_context(|| format!("root signature {id}"))?; + self.roots.insert(*id, root); + } + for s in &self.frame.signatures { + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: s.stride, + NumArgumentDescs: s.args.len() as u32, + pArgumentDescs: s.args.as_ptr().cast(), + NodeMask: 0, + }; + let mut made: Option = None; + // SAFETY: a description the host took. + unsafe { self.device.CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? }; + self.signatures.extend(made.map(|m| (s.id, m))); + } + for q in &self.frame.query_heaps { + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE(q.kind), Count: q.count, NodeMask: 0 }; + let mut made: Option = None; + // SAFETY: plain creation. + unsafe { self.device.CreateQueryHeap(&desc, &mut made)? }; + self.queries.extend(made.map(|m| (q.id, m))); + } + let file = File::open(self.folder.join("shaders.bin"))?; + let device: ID3D12Device2 = self.device.cast()?; + let next = AtomicUsize::new(0); + type Made = std::result::Result; + let made: std::sync::Mutex> = std::sync::Mutex::default(); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).max(1); + let (frame, roots) = (&self.frame, &self.roots); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + while let Some(p) = frame.pipelines.get(next.fetch_add(1, Ordering::Relaxed)) { + let code = |i: u32| { + let c = frame.codes.get(i as usize)?; + let mut bytes = vec![0; c.len as usize]; + read_at(&file, &mut bytes, c.at).ok()?; + Some(bytes) + }; + let m = super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); + made.lock().unwrap_or_else(|e| e.into_inner()).push((p.id, m)); + } + }); + } + }); + let mut refused = Vec::new(); + for (id, m) in made.into_inner().unwrap_or_else(|e| e.into_inner()) { + match m { + Ok(p) => drop(self.pipelines.insert(id, p)), + Err(e) => refused.push((id, e)), + } + } + if let Some((id, e)) = refused.first() { + let n = format!("{} pipelines could not be made again, first {}: {e}", refused.len(), self.pipeline_name(*id)); + self.note(n); + } + Ok(()) + } + + /// A pipeline's name for reports: what the host layer called it and the + /// hashes of its shaders. + fn pipeline_name(&self, id: u32) -> String { + let Some(p) = self.frame.pipelines.iter().find(|p| p.id == id) else { + return format!("pipeline {id}"); + }; + let code: Vec = self.hashes(p); + format!("{} (DXIL {})", if p.name.is_empty() { "unnamed" } else { &p.name }, code.join(" ")) + } + + fn hashes(&self, p: &wire::Pipeline) -> Vec { + p.parts + .iter() + .filter_map(|part| match part { + wire::Part::Code { blob, .. } => { + let c = self.frame.codes.get(*blob as usize)?; + Some(c.hash[..8].iter().map(|b| format!("{b:02x}")).collect()) + } + _ => None, + }) + .collect() + } + + /// Makes a view; one of a resource that is not there is null. + /// + /// # Safety + /// `at` is a slot of a heap of the view's type. + unsafe fn view(&self, s: &Slot, at: D3D12_CPU_DESCRIPTOR_HANDLE, sampler: bool) { + let gone = s.res != NONE && !self.objects.contains_key(&s.res); + let res = self.objects.get(&s.res).map(|o| &o.res); + let counter = self.objects.get(&s.counter).map(|o| &o.res); + // The descriptions lie in the slot unaligned. + // SAFETY: the slot's description is of its kind; the resources live. + unsafe { + match (s.kind, s.described != 0 && !gone) { + (slot::CBV, described) => { + let mut d: D3D12_CONSTANT_BUFFER_VIEW_DESC = Default::default(); + if described && let Some(o) = self.objects.get(&s.res) { + d = s.desc.as_ptr().cast::().read_unaligned(); + d.BufferLocation = o.va + s.address(); + } + self.device.CreateConstantBufferView(Some(&d), at); + } + (slot::SRV, true) => { + let d = s.desc.as_ptr().cast::().read_unaligned(); + self.device.CreateShaderResourceView(res, Some(&d), at); + } + (slot::SRV, false) if res.is_some() => self.device.CreateShaderResourceView(res, None, at), + (slot::UAV, true) => { + let d = s.desc.as_ptr().cast::().read_unaligned(); + self.device.CreateUnorderedAccessView(res, counter, Some(&d), at); + } + (slot::UAV, false) if res.is_some() => self.device.CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at), + (slot::SAMPLER, true) => { + let d = s.desc.as_ptr().cast::().read_unaligned(); + self.device.CreateSampler(&d, at); + } + _ if sampler => { + let d = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ..Default::default() + }; + self.device.CreateSampler(&d, at); + } + (slot::UAV, _) => { + let d = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(41), + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + }; + self.device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&d), at); + } + _ => { + let d = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(41), + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + self.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); + } + } + } + } + + fn make_descriptors(&mut self) -> Result<()> { + // A submission whose views replace ones that were in use gets a + // 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(); + 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))); + } + } + // What each version changes against the one before. + let mut versions: Vec> = vec![Vec::new()]; + let mut touched: HashSet<(u32, u32)> = HashSet::new(); + for s in &self.frame.submits { + let live = |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); + let news: Vec<&(u32, u32, Slot)> = s.views.iter().filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)).collect(); + if news.iter().any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) { + versions.push(Vec::new()); + touched.clear(); + } + for (h, i, v) in news { + now.insert((*h, *i), *v); + touched.insert((*h, *i)); + if let Some(last) = versions.last_mut() { + last.push((*h, *i, *v)); + } + } + self.version_of.push(versions.len() - 1); + } + let mut made = HashMap::new(); + 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); + let make = |flags| -> windows::core::Result { + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: h.count, Flags: flags, NodeMask: 0 }; + // SAFETY: plain creation. + unsafe { self.device.CreateDescriptorHeap(&d) } + }; + let cpu = make(D3D12_DESCRIPTOR_HEAP_FLAG_NONE)?; + // SAFETY: slots of the heap just made; threads write other ones. + unsafe { + let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize; + let start = cpu.GetCPUDescriptorHandleForHeapStart(); + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i as usize * step }; + self.view(&Slot::EMPTY, start, sampler); + let mut filled = 1; + while filled < h.count { + let n = filled.min(h.count - filled).min(1 << 16); + // Sources and destinations do not overlap. + self.device.CopyDescriptorsSimple(n, at(filled), start, kind); + filled += n; + } + for (first, n, s) in &h.runs { + self.view(s, at(*first), sampler); + for i in 1..*n { + self.device.CopyDescriptorsSimple(1, at(first + i), at(*first), kind); + } + } + let mut all = Vec::new(); + for changes in &versions { + let mine: Vec<&(u32, u32, Slot)> = changes.iter().filter(|(id, _, _)| *id == h.id).collect(); + for (_, i, s) in &mine { + if *i < h.count { + self.view(s, at(*i), sampler); + } + } + if mine.is_empty() + && let Some(Version { heap, gpu }) = all.last() + { + let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; + all.push(same); + continue; + } + let heap = make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)?; + self.device.CopyDescriptorsSimple(h.count, heap.GetCPUDescriptorHandleForHeapStart(), start, kind); + let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; + all.push(Version { heap, gpu }); + } + made.insert(h.id, (all, step as u64)); + } + } + self.descriptors = made; + // Render target and depth views. + let mut views: [HashSet; 2] = Default::default(); + for c in self.commands.iter().flatten() { + match c { + Cmd::Targets { colors, depth } => { + views[0].extend(colors); + views[1].extend(depth); + } + Cmd::ClearTarget { view, .. } => drop(views[0].insert(*view)), + Cmd::ClearDepth { view, .. } => drop(views[1].insert(*view)), + _ => {} + } + } + for (i, all) in views.iter().enumerate() { + if all.is_empty() { + continue; + } + let kind = [D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_TYPE_DSV][i]; + let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: all.len() as u32, ..Default::default() }; + // SAFETY: plain creation; slots of the heap just made. + unsafe { + let heap: ID3D12DescriptorHeap = self.device.CreateDescriptorHeap(&d)?; + let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize; + let mut at = heap.GetCPUDescriptorHandleForHeapStart(); + for s in all { + let res = self.objects.get(&s.res).map(|o| &o.res); + if i == 0 { + let d = s.desc.as_ptr().cast::().read_unaligned(); + // Without either there is nothing to make a view of. + let null = D3D12_RENDER_TARGET_VIEW_DESC { + Format: DXGI_FORMAT(28), + ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + self.device.CreateRenderTargetView(res, d, at); + } else { + let d = s.desc.as_ptr().cast::().read_unaligned(); + let null = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT(40), + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + self.device.CreateDepthStencilView(res, d, at); + } + self.targets.insert(*s, at); + at.ptr += step; + } + self._target_heaps.push(heap); + } + } + Ok(()) + } + + /// Reads parts of files into upload memory and has `copy` record what + /// is done with each. + fn upload( + &mut self, + parts: &[(T, u64, u64)], + file: &File, + mut copy: impl FnMut(&Player, &ID3D12GraphicsCommandList, &[(&T, u64, u64)], &ID3D12Resource), + ) -> Result<()> { + // Batches of parts with their place in the buffer. + let mut batches: Vec> = vec![Vec::new()]; + let (mut at, mut most) = (0u64, 0u64); + for (i, (_, len, _)) in parts.iter().enumerate() { + at = at.next_multiple_of(512); + if at + len > STAGING && at > 0 { + batches.push(Vec::new()); + at = 0; + } + if let Some(b) = batches.last_mut() { + b.push((i, at)); + } + at += len; + most = most.max(at); + } + if parts.is_empty() { + return Ok(()); + } + let mut stagings: Vec<(ID3D12Resource, usize, u64)> = Vec::new(); + for _ in 0..batches.len().min(2) { + let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_UPLOAD, most, D3D12_RESOURCE_FLAG_NONE)?; + stagings.push((b, data as usize, 0)); + } + for (n, batch) in batches.iter().enumerate() { + let k = n % stagings.len(); + self.worker.wait(stagings[k].2)?; + let map = stagings[k].1; + let next = AtomicUsize::new(0); + let failed: std::sync::Mutex> = std::sync::Mutex::default(); + std::thread::scope(|scope| { + for _ in 0..8.min(batch.len()) { + scope.spawn(|| { + while let Some(&(i, at)) = batch.get(next.fetch_add(1, Ordering::Relaxed)) { + let (_, len, from) = &parts[i]; + // SAFETY: this part's own bytes of the mapping. + let to = unsafe { std::slice::from_raw_parts_mut((map + at as usize) as *mut u8, *len as usize) }; + if *from == ZERO { + to.fill(0); + } else if let Err(e) = read_at(file, to, *from) { + failed.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(e); + } + } + }); + } + }); + if let Some(e) = failed.into_inner().unwrap_or_else(|e| e.into_inner()) { + return Err(e).context("the capture's contents"); + } + let list: Vec<(&T, u64, u64)> = batch.iter().map(|&(i, at)| (&parts[i].0, parts[i].1, at)).collect(); + let buffer = stagings[k].0.clone(); + // The worker is another part of the player than `copy` uses. + let other = Worker::new(&self.device, &self.worker.queue)?; + let mut worker = std::mem::replace(&mut self.worker, other); + let sent = worker.send(|l| copy(self, l, &list, &buffer)); + self.worker = worker; + stagings[k].2 = sent?; + } + self.worker.idle()?; + Ok(()) + } + + fn load_contents(&mut self) -> Result<()> { + // Idle aliases first: a change of their state may write memory the + // one in use holds. + 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); + 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 + .frame + .contents + .iter() + .filter(|c| self.objects.contains_key(&c.res)) + .map(|c| (c.clone(), c.len, c.file)) + .collect(); + let missing = self.frame.contents.len() - textures.len(); + self.worker.run(|list| { + // SAFETY: an open list; live resources. + unsafe { + for all in early.chunks(1000) { + list.ResourceBarrier(all); + } + list.ResourceBarrier(&[alias()]); + for all in into.chunks(1000) { + list.ResourceBarrier(all); + } + } + })?; + let file = File::open(self.folder.join("contents.bin"))?; + self.upload(&textures, &file, |player, list, parts, staging| { + for (c, len, at) in parts { + let Some(o) = player.objects.get(&c.res) else { continue }; + let r = &player.frame.resources[o.index]; + // SAFETY: an open list; live resources. + unsafe { + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + list.CopyBufferRegion(&o.res, c.first, staging, *at, *len); + continue; + } + let (all, _) = gpu::footprints(&player.device, &gpu::to_desc(&r.desc), c.first as u32, c.count); + for (i, mut f) in all.into_iter().enumerate() { + f.Offset += at; + let to = gpu::sub_location(&o.res, c.first as u32 + i as u32); + list.CopyTextureRegion(&to, 0, 0, 0, &gpu::placed_location(staging, f), None); + } + } + } + })?; + // To the states of the frame's start. + 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) { + gpu::moves(&o.res, &[COPY_DEST], state, &mut back); + } + } + self.worker.run(|list| { + for all in back.chunks(1000) { + // SAFETY: an open list; live resources. + unsafe { list.ResourceBarrier(all) }; + } + })?; + if missing > 0 { + self.note(format!("contents of {missing} parts of resources that could not be made are left out")); + } + // 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(); + self.upload(&first, &file, |player, list, parts, staging| { + for (d, len, at) in parts { + if let Some(o) = player.objects.get(&d.res) { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&o.res, d.at, staging, *at, *len) }; + } + } + })?; + // The later ones wait in a buffer of their own. + 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 { + later.push(((total, d.clone()), d.len, d.file)); + self.delta_parts[i].push((d.clone(), total)); + total += d.len; + } + } + if total > 0 { + let (buffer, _) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, total, D3D12_RESOURCE_FLAG_NONE)?; + self.deltas = Some(buffer.clone()); + self.upload(&later, &file, |_, list, parts, staging| { + for ((to, _), len, at) in parts { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&buffer, *to, staging, *at, *len) }; + } + })?; + } + Ok(()) + } + + /// Copies of what the frame changes; and the states it leaves. + fn make_masters(&mut self) -> Result<()> { + let mut states = States::default(); + for r in &self.frame.resources { + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + continue; + } + let subs = gpu::subresources(&r.desc); + let decays = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; + states.add(r.id, subs, r.state[0], decays); + if r.state.len() > 1 { + for (i, s) in r.state.iter().enumerate() { + states.change(&states::Change { res: r.id, sub: i as u32, after: *s, promoted: false, alias: false }); + } + } + } + // Resources in a state they are written in at some time, or written + // some other way. + const WRITE: u32 = RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; + let mut written: HashSet = + self.frame.resources.iter().filter(|r| r.state.iter().any(|s| s & WRITE != 0)).map(|r| r.id).collect(); + 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] { + let mut changes = Vec::new(); + states::changes(c, &mut changes); + for ch in &changes { + states.change(ch); + } + match c { + Cmd::Barriers { all } => { + for b in all { + if let Barrier::Transition { res, before, after, .. } = b + && (*before | *after) as u32 & WRITE != 0 + { + written.insert(*res); + } + } + } + Cmd::CopyBuffer { dst, .. } | Cmd::CopyResource { dst, .. } | Cmd::ResolveQuery { dst, .. } => drop(written.insert(*dst)), + Cmd::CopyTexture { dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, .. } => drop(written.insert(*res)), + Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => drop(written.insert(*dst)), + Cmd::RootView { kind: slot::UAV, va: Va::At { res, .. }, .. } => drop(written.insert(*res)), + Cmd::WriteImmediate { all } => { + written.extend(all.iter().filter_map(|(va, _, _)| if let Va::At { res, .. } = va { Some(*res) } else { None })); + } + _ => {} + } + } + } + states.decay(); + if i > 0 { + written.extend(s.deltas.iter().map(|d| d.res)); + } + } + // Buffers any unordered-access view names. + let is_buffer = + |id: u32| self.objects.get(&id).is_some_and(|o| self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0); + let simultaneous = |id: u32| { + self.objects.get(&id).is_some_and(|o| { + self.frame.resources[o.index].desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0 + }) + }; + let views = self.frame.descriptor_heaps.iter().flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); + let late = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|(_, _, s)| s)); + for s in views.chain(late).filter(|s| s.kind == slot::UAV) { + for id in [s.res, s.counter] { + if is_buffer(id) || simultaneous(id) { + written.insert(id); + } + } + } + for id in self.start.keys() { + self.end.insert(*id, states.get(*id).unwrap_or(vec![COMMON])); + } + let mut ids: Vec = written + .into_iter() + .filter(|id| { + self.objects.get(id).is_some_and(|o| { + let r = &self.frame.resources[o.index]; + let back = matches!(&r.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::ReadBack); + !r.idle && !back && !matches!(r.place, Place::BackBuffer {}) + }) + }) + .collect(); + ids.sort_unstable(); + let mut total = 0u64; + let mut in_pc = 0u64; + for id in ids { + let o = &self.objects[&id]; + let r = &self.frame.resources[o.index]; + let mut desc = gpu::to_desc(&r.desc); + desc.Alignment = 0; + // Copies are only copied to and from; a depth format needs its + // flag. + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + } + // SAFETY: a plain query. + 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)); + let props = if pc { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut made: Option = None; + // SAFETY: plain creation. + let result = unsafe { + self.device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + }; + match (result, made) { + (Ok(()), Some(m)) => { + total += size; + in_pc += if pc { size } else { 0 }; + self.masters.push((id, m)); + } + (e, _) => self.note(format!("no copy of resource {id} to restore it from ({e:?})")), + } + } + tracing::info!(resources = self.masters.len(), mb = total >> 20, in_pc_memory_mb = in_pc >> 20, "copies of what the frame changes"); + // Filled now: the resources are as at the frame's start. Masters + // stay in the copy-source state (buffers decay). + let (masters, objects, start) = (&self.masters, &self.objects, &self.start); + for some in masters.chunks(256) { + let (mut before, mut after) = (Vec::new(), Vec::new()); + for (id, m) in some { + let Some(state) = start.get(id) else { continue }; + let o = &objects[id]; + let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + gpu::moves(&o.res, state, &to, &mut before); + gpu::moves(&o.res, &to, state, &mut after); + before.push(gpu::transition(m, ALL, COMMON, COPY_DEST)); + after.push(gpu::transition(m, ALL, COPY_DEST, COPY_SOURCE)); + } + self.worker.run(|list| { + // SAFETY: an open list; live resources of one size. + unsafe { + barriers(list, &before); + for (id, m) in some { + list.CopyResource(m, &objects[id].res); + } + barriers(list, &after); + } + })?; + } + Ok(()) + } + + /// What is free of the card's memory budget. + fn room(&self) -> Option { + let mut own = 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()?; + } + Some(own.Budget.saturating_sub(own.CurrentUsage)) + } + + /// Puts back what a run changed. + fn restore(&mut self, contents: bool) -> Result<()> { + if self.fresh { + return Ok(()); + } + let restored: HashMap = if contents { self.masters.iter().map(|(id, m)| (*id, m)).collect() } else { HashMap::new() }; + let (mut idle, mut into, mut back, mut plain) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for (id, start) in &self.start { + let Some(o) = self.objects.get(id) else { continue }; + let end = self.end.get(id).unwrap_or(start); + if restored.contains_key(id) { + gpu::moves(&o.res, end, &[COPY_DEST], &mut into); + gpu::moves(&o.res, &[COPY_DEST], start, &mut back); + } else if self.frame.resources[o.index].idle { + gpu::moves(&o.res, end, start, &mut idle); + } else { + gpu::moves(&o.res, end, start, &mut plain); + } + } + let objects = &self.objects; + self.worker.run(|list| { + // SAFETY: an open list; live resources, each copied from one of + // its own description. + unsafe { + barriers(list, &idle); + barriers(list, &[alias()]); + barriers(list, &plain); + barriers(list, &into); + for (id, m) in &restored { + list.CopyResource(&objects[id].res, *m); + } + barriers(list, &back); + } + })?; + self.fresh = true; + Ok(()) + } + + fn pipelines_named(&self, name: &str) -> HashSet { + self.frame.pipelines.iter().filter(|p| p.name == name).map(|p| p.id).collect() + } + + /// The frame's lists, edited: for each submission, its lists' commands. + fn edited(&mut self, o: &Options, report: &mut Report, clamps: &[Vec]) -> Vec>> { + let skip: HashSet = self + .frame + .pipelines + .iter() + .filter(|p| { + let hashes = self.hashes(p); + o.skip_shaders.iter().any(|s| !s.is_empty() && (p.name.contains(s.as_str()) || hashes.iter().any(|h| h.contains(s.as_str())))) + }) + .map(|p| p.id) + .collect(); + if !o.skip_shaders.is_empty() { + report.notes.push(format!("{} pipelines match --skip-shader", skip.len())); + } + let hash = self.pipelines_named(COMPARE); + let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0); + let mut place = 0; + let mut out = Vec::new(); + for s in &self.frame.submits { + let mut lists = Vec::new(); + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let mut cmds = self.commands[l as usize].clone(); + let here = place; + place += 1; + if o.only.is_some_and(|(from, to)| here < from || here > to) { + lists.push(edit::barriers_only(cmds)); + continue; + } + if o.skip_clamps && let Some(c) = clamps.get(here as usize) { + cmds = edit::skip_clamps(cmds, c); + } + let mut n; + if !skip.is_empty() { + (cmds, n) = edit::skip_pipelines(cmds, &skip); + skipped += n; + } + if o.skip_hash_passes { + (cmds, n) = edit::skip_pipelines(cmds, &hash); + hashed += n; + } + if o.no_barriers { + (cmds, n) = edit::no_uav_barriers(cmds); + uavs += n; + } + if o.merge_barriers { + (cmds, n) = edit::merge_barriers(cmds); + merged += n; + } + lists.push(cmds); + } + out.push(lists); + } + if !skip.is_empty() { + report.notes.push(format!("--skip-shader left out {skipped} commands")); + } + if o.skip_hash_passes { + report.notes.push(format!("--skip-hash-passes left out {hashed} dispatches")); + } + if o.no_barriers { + report.notes.push(format!("--no-barriers left out {uavs} unordered-access barriers")); + } + if o.merge_barriers { + report.notes.push(format!("--merge-barriers joined {merged} barrier calls to ones before them")); + } + out + } + + /// The clamp passes of each list of the frame, in order, and their + /// results in [`RESULTS`] (by a run that keeps them). + fn clamp_results(&mut self, report: &mut Report) -> Result>> { + let psos = self.pipelines_named(CLAMP); + let mut next = 0; + let mut clamps = Vec::new(); + let mut submits = Vec::new(); + for s in &self.frame.submits { + let mut lists = Vec::new(); + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let cmds = self.commands[l as usize].clone(); + let found = edit::find_clamps(&cmds, &psos, &mut next); + lists.push(edit::keep_clamped(cmds, &found)); + clamps.push(found); + } + submits.push(lists); + } + let n: usize = clamps.iter().map(Vec::len).sum(); + report.notes.push(format!("--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", next >> 10)); + if n == 0 { + return Ok(clamps); + } + self.results = Some(gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, next, D3D12_RESOURCE_FLAG_NONE)?.0); + let built = self.build(&submits, &Options::default())?; + self.restore(true)?; + self.send(&built, false)?; + self.fresh = false; + Ok(clamps) + } + + /// Makes the lists of all submissions, and before each one's the copies + /// of what the CPU wrote. + fn build(&self, submits: &[Vec>], o: &Options) -> Result { + // Room for the timestamps of every command that has one. + let count: usize = submits + .iter() + .flatten() + .map(|c| 2 + if o.detailed { c.iter().filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })).count() } else { 0 }) + .sum::() + + 2 * submits.len(); + let mut heap: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: count.max(1) as u32, NodeMask: 0 }; + // SAFETY: plain creation. + unsafe { self.device.CreateQueryHeap(&desc, &mut heap)? }; + let heap = heap.context("no timestamps")?; + let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, count.max(1) as u64 * 8, D3D12_RESOURCE_FLAG_NONE)?; + let mut next = 0u32; + let mut steps = Vec::new(); + for (i, lists) in submits.iter().enumerate() { + let parts = self.delta_parts.get(i).filter(|p| !p.is_empty()); + let delta = match (parts, &self.deltas) { + (Some(parts), Some(from)) => { + let open = self.open(&heap, &mut next)?; + // SAFETY: an open list; live buffers. + unsafe { + let mut seen = HashSet::new(); + let mut after = Vec::new(); + for (d, at) in parts { + let Some(ob) = self.objects.get(&d.res) else { 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 + // lists in the same submission. + after.push(gpu::transition(&ob.res, ALL, COPY_DEST, COMMON)); + } + } + barriers(&open.1, &after); + } + Some(self.close(open, &heap, &mut next, Vec::new())?) + } + _ => None, + }; + 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))); + built.push(self.close(open, &heap, &mut next, stamps)?); + } + steps.push((delta, built)); + } + // Between submissions that are sent as one: everything waits. A list + // each: one cannot stand twice in a submission. + let mut joints = Vec::new(); + if o.one_submit { + for _ in 0..2 * submits.len() { + let open = self.plain_list()?; + // SAFETY: an open list. + unsafe { + self.wait_for_all(&open.1); + open.1.Close()?; + } + joints.push(open); + } + } + let resolve = { + let open = self.plain_list()?; + // SAFETY: an open list; `next` queries were written. + unsafe { + open.1.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, next.max(1), &back, 0); + open.1.Close()?; + } + open + }; + Ok(Sends { steps, joints, resolve, _heap: heap, _back: back, data: data as usize, count: next }) + } + + /// Records a wait for everything before, with all caches written out. + /// + /// # Safety + /// An open list. + unsafe fn wait_for_all(&self, list: &ID3D12GraphicsCommandList) { + // SAFETY: the caller's; a feature structure of its size. + unsafe { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); + let size = size_of::() as u32; + let known = self.device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size).is_ok(); + if known + && o.EnhancedBarriersSupported.as_bool() + && let Ok(list) = list.cast::() + { + let all = [D3D12_GLOBAL_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_ALL, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: D3D12_BARRIER_ACCESS_COMMON, + AccessAfter: D3D12_BARRIER_ACCESS_COMMON, + }]; + list.Barrier(&[D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_GLOBAL, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: all.as_ptr() }, + }]); + } else { + list.ResourceBarrier(&[alias(), uav_barrier(None)]); + } + } + } + + fn plain_list(&self) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> { + // SAFETY: plain creation. + unsafe { + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list = self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + Ok((allocator, list)) + } + } + + fn open(&self, heap: &ID3D12QueryHeap, next: &mut u32) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { + let (allocator, list) = self.plain_list()?; + // SAFETY: an open list; a query of the heap. + unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next) }; + *next += 1; + Ok((allocator, list, *next - 1)) + } + + fn close( + &self, + (allocator, list, first): (ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32), + heap: &ID3D12QueryHeap, + next: &mut u32, + stamps: Vec, + ) -> Result { + // SAFETY: as above. + unsafe { + list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next); + list.Close().context("a list of the frame could not be recorded again")?; + } + *next += 1; + Ok(Built { _allocator: allocator, list, first, last: *next - 1, stamps }) + } + + /// Records commands into a list, in submission `submit`. + fn translate( + &self, + list: &ID3D12GraphicsCommandList, + cmds: &[Cmd], + submit: usize, + mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>, + ) -> Vec { + let version = self.version_of.get(submit).copied().unwrap_or(0); + let clamps = self.pipelines_named(CLAMP); + let compares = self.pipelines_named(COMPARE); + let mesh: HashSet = self + .frame + .pipelines + .iter() + .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0))) + .map(|p| p.id) + .collect(); + let dispatches: HashSet = self + .frame + .signatures + .iter() + .filter(|s| s.args.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)) + .map(|s| s.id) + .collect(); + let mut stamps = Vec::new(); + let mut bound = NONE; + 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 timed = c.works() || matches!(c, Cmd::Barriers { .. }); + if timed && let Some((heap, next)) = &mut stamp { + // SAFETY: as above. + unsafe { list.EndQuery(*heap, D3D12_QUERY_TYPE_TIMESTAMP, **next) }; + let category = match c { + Cmd::Barriers { .. } => "barriers", + Cmd::Dispatch { .. } if clamps.contains(&bound) => "argument clamps (ours)", + Cmd::Dispatch { .. } if compares.contains(&bound) => "hash and compare passes (ours)", + Cmd::Dispatch { .. } => "dispatches", + Cmd::Indirect { signature, .. } if dispatches.contains(signature) => "indirect dispatches", + Cmd::Indirect { .. } if mesh.contains(&bound) => "indirect mesh draws", + Cmd::Indirect { .. } => "indirect draws", + Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => "draws", + Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => "clears", + Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves", + _ => "copies", + }; + let runs = if c.runs_shaders() { bound } else { NONE }; + stamps.push((**next as usize, category, runs)); + **next += 1; + } + } + stamps + } + + unsafe fn command(&self, l: &ID3D12GraphicsCommandList, c: &Cmd, version: usize) { + let res = |id: u32| self.resource(id); + let view = |s: &Slot| self.targets.get(s).copied().unwrap_or_default(); + // SAFETY: the caller's. + unsafe { + match c { + Cmd::Draw { vertices, instances, first, first_instance } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), + Cmd::DrawIndexed { indices, instances, first, base, first_instance } => { + l.DrawIndexedInstanced(*indices, *instances, *first, *base, *first_instance); + } + Cmd::Dispatch { groups } => l.Dispatch(groups[0], groups[1], groups[2]), + Cmd::DispatchMesh { groups } => { + if let Ok(l) = l.cast::() { + l.DispatchMesh(groups[0], groups[1], groups[2]); + } + } + Cmd::CopyBuffer { dst, dst_at, src, src_at, len } => { + if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { + l.CopyBufferRegion(dst, *dst_at, src, *src_at, *len); + } + } + Cmd::CopyTexture { dst, at, src, part } => { + let side = |loc: &Loc| match loc { + Loc::Sub { res: id, sub } => Some(gpu::sub_location(res(*id)?, *sub)), + Loc::Placed { res: id, offset, format, size, pitch } => { + let f = D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(*format), + Width: size[0], + Height: size[1], + Depth: size[2], + RowPitch: *pitch, + }; + Some(gpu::placed_location(res(*id)?, D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: *offset, Footprint: f })) + } + }; + if let (Some(dst), Some(src)) = (side(dst), side(src)) { + let part = part.map(|p| D3D12_BOX { left: p[0], top: p[1], front: p[2], right: p[3], bottom: p[4], back: p[5] }); + l.CopyTextureRegion(&dst, at[0], at[1], at[2], &src, part.as_ref().map(|p| p as *const _)); + } + } + Cmd::CopyResource { dst, src } => { + if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { + l.CopyResource(dst, src); + } + } + Cmd::Resolve { dst, dst_sub, src, src_sub, format } => { + if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { + l.ResolveSubresource(dst, *dst_sub, src, *src_sub, DXGI_FORMAT(*format)); + } + } + Cmd::ResolveRegion { dst, dst_sub, at, src, src_sub, part, format, mode } => { + if let (Some(dst), Some(src), Ok(l)) = (res(*dst), res(*src), l.cast::()) { + let part = part.map(to_rect); + let part = part.as_ref().map(|r| r as *const _); + l.ResolveSubresourceRegion(dst, *dst_sub, at[0], at[1], src, *src_sub, part, DXGI_FORMAT(*format), D3D12_RESOLVE_MODE(*mode)); + } + } + Cmd::Topology { kind } => l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(*kind)), + Cmd::Viewports { all } => { + let all: Vec = all + .iter() + .map(|v| D3D12_VIEWPORT { TopLeftX: v[0], TopLeftY: v[1], Width: v[2], Height: v[3], MinDepth: v[4], MaxDepth: v[5] }) + .collect(); + l.RSSetViewports(&all); + } + Cmd::Scissors { all } => l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()), + Cmd::BlendFactor { factor } => l.OMSetBlendFactor(factor.as_ref()), + Cmd::StencilRef { value } => l.OMSetStencilRef(*value), + Cmd::DepthBounds { min, max } => { + if let Ok(l) = l.cast::() { + l.OMSetDepthBounds(*min, *max); + } + } + Cmd::Pipeline { pso } => { + if let Some(p) = self.pipelines.get(pso) { + l.SetPipelineState(p); + } + } + Cmd::Barriers { all } => { + let all: Vec = all.iter().filter_map(|b| self.barrier(b)).collect(); + barriers(l, &all); + } + Cmd::Heaps { heaps } => { + let all: Vec> = + heaps.iter().filter_map(|id| Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone()))).collect(); + l.SetDescriptorHeaps(&all); + } + Cmd::RootSignature { graphics, root } => { + let root = self.roots.get(root); + if *graphics { l.SetGraphicsRootSignature(root) } else { l.SetComputeRootSignature(root) } + } + Cmd::Table { graphics, param, heap, slot } => { + if let Some((versions, step)) = self.descriptors.get(heap) + && let Some(v) = versions.get(version) + { + let at = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: v.gpu + u64::from(*slot) * step }; + if *graphics { l.SetGraphicsRootDescriptorTable(*param, at) } else { l.SetComputeRootDescriptorTable(*param, at) } + } + } + Cmd::Constants { graphics, param, offset, values } => { + let (n, data) = (values.len() as u32, values.as_ptr().cast()); + if *graphics { + l.SetGraphicsRoot32BitConstants(*param, n, data, *offset); + } else { + l.SetComputeRoot32BitConstants(*param, n, data, *offset); + } + } + Cmd::RootView { graphics, kind, param, va } => { + let va = self.va(va); + match (*kind, *graphics) { + (slot::CBV, true) => l.SetGraphicsRootConstantBufferView(*param, va), + (slot::CBV, false) => l.SetComputeRootConstantBufferView(*param, va), + (slot::SRV, true) => l.SetGraphicsRootShaderResourceView(*param, va), + (slot::SRV, false) => l.SetComputeRootShaderResourceView(*param, va), + (_, true) => l.SetGraphicsRootUnorderedAccessView(*param, va), + (_, false) => l.SetComputeRootUnorderedAccessView(*param, va), + } + } + Cmd::IndexBuffer { view } => { + let v = view.as_ref().map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { + BufferLocation: self.va(va), + SizeInBytes: *size, + Format: DXGI_FORMAT(*format), + }); + l.IASetIndexBuffer(v.as_ref().map(|v| v as *const _)); + } + Cmd::VertexBuffers { start, views, count } => match views { + Some(views) => { + let all: Vec = views + .iter() + .map(|(va, size, stride)| D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: self.va(va), + SizeInBytes: *size, + StrideInBytes: *stride, + }) + .collect(); + l.IASetVertexBuffers(*start, Some(&all)); + } + None => l.IASetVertexBuffers(*start, Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize])), + }, + Cmd::Targets { colors, depth } => { + let colors: Vec = colors.iter().map(view).collect(); + let depth = depth.as_ref().map(view); + l.OMSetRenderTargets( + colors.len() as u32, + (!colors.is_empty()).then_some(colors.as_ptr()), + false, + depth.as_ref().map(|d| d as *const _), + ); + } + Cmd::ClearDepth { view: v, flags, depth, stencil, rects } => { + let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); + let rects = (!rects.is_empty()).then_some(&rects[..]); + if self.objects.contains_key(&v.res) { + l.ClearDepthStencilView(view(v), D3D12_CLEAR_FLAGS(*flags), *depth, *stencil, rects); + } + } + Cmd::ClearTarget { view: v, color, rects } => { + let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); + let rects = (!rects.is_empty()).then_some(&rects[..]); + if self.objects.contains_key(&v.res) { + l.ClearRenderTargetView(view(v), color, rects); + } + } + Cmd::Discard { res: id, rects, subs } => { + if let Some(r) = res(*id) { + let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); + let region = subs.map(|s| D3D12_DISCARD_REGION { + NumRects: rects.len() as u32, + pRects: if rects.is_empty() { std::ptr::null() } else { rects.as_ptr() }, + FirstSubresource: s[0], + NumSubresources: s[1], + }); + l.DiscardResource(r, region.as_ref().map(|r| r as *const _)); + } + } + Cmd::BeginQuery { heap, kind, index } => { + if let Some(h) = self.queries.get(heap) { + l.BeginQuery(h, D3D12_QUERY_TYPE(*kind), *index); + } + } + Cmd::EndQuery { heap, kind, index } => { + if let Some(h) = self.queries.get(heap) { + l.EndQuery(h, D3D12_QUERY_TYPE(*kind), *index); + } + } + Cmd::ResolveQuery { heap, kind, first, count, dst, at } => { + if let (Some(h), Some(dst)) = (self.queries.get(heap), res(*dst)) { + l.ResolveQueryData(h, D3D12_QUERY_TYPE(*kind), *first, *count, dst, *at); + } + } + Cmd::Indirect { signature, most, args, at, count, count_at } => { + if let (Some(s), Some(a)) = (self.signatures.get(signature), res(*args)) { + l.ExecuteIndirect(s, *most, a, *at, res(*count), *count_at); + } + } + Cmd::WriteImmediate { all } => { + if let Ok(l) = l.cast::() { + let all: Vec<&(Va, u32, i32)> = all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); + let params: Vec = + all.iter().map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: self.va(va), Value: *v }).collect(); + let modes: Vec = all.iter().map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)).collect(); + if !params.is_empty() { + l.WriteBufferImmediate(params.len() as u32, params.as_ptr(), Some(modes.as_ptr())); + } + } + } + } + } + } + + fn barrier(&self, b: &Barrier) -> Option { + Some(match b { + Barrier::Transition { flags, res, sub, before, after } => { + let mut t = gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); + t.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); + t + } + Barrier::Uav { flags, res } => { + let mut u = uav_barrier(if *res == NONE { None } else { Some(self.resource(*res)?) }); + u.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); + u + } + Barrier::Alias { flags, before, after } => { + let side = |id: &u32| -> std::mem::ManuallyDrop> { + // SAFETY: a borrowed pointer (or none) never released. + self.resource(*id).map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }) + }; + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAGS(*flags), + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: side(before), + pResourceAfter: side(after), + }), + }, + } + } + }) + } + + /// Sends the frame, waits for it, and reads the timestamps. + fn send(&mut self, s: &Sends, one: bool) -> Result> { + let cast = |l: &ID3D12GraphicsCommandList| l.cast::().map(Some); + let mut submissions: Vec>> = Vec::new(); + for (delta, lists) in &s.steps { + if let Some(d) = delta { + submissions.push(vec![cast(&d.list)?]); + } + let mut all = Vec::new(); + for l in lists { + all.push(cast(&l.list)?); + } + if !all.is_empty() { + submissions.push(all); + } + } + if one { + let mut all = Vec::new(); + for (i, lists) in submissions.into_iter().enumerate() { + if i > 0 + && let Some(joint) = s.joints.get(i) + { + all.push(cast(&joint.1)?); + } + all.extend(lists); + } + submissions = vec![all]; + } + // SAFETY: closed lists whose last run has finished. + unsafe { + for all in &submissions { + self.worker.queue.ExecuteCommandLists(all); + } + self.worker.queue.ExecuteCommandLists(&[cast(&s.resolve.1)?]); + } + self.worker.idle().context("the card was lost running the frame")?; + // SAFETY: the mapping of `count` resolved timestamps. + Ok(unsafe { std::slice::from_raw_parts(s.data as *const u64, s.count as usize) }.to_vec()) + } + + /// Runs the frame as the options say. + pub fn run(&mut self, o: &Options) -> Result { + let mut report = Report { notes: self.notes.clone(), ..Default::default() }; + let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { Vec::new() }; + let submits = self.edited(o, &mut report, &clamps); + let built = self.build(&submits, o)?; + let mut stamps = Vec::new(); + for _ in 0..o.loops.max(1) { + self.restore(o.restore)?; + self.fresh = false; + stamps = self.send(&built, o.one_submit)?; + let ms = |a: u32, b: u32| stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency; + let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); + let (Some(first), Some(last)) = (lists.first(), lists.last()) else { + bail!("no lists to run"); + }; + let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); + report.delta_ms.push(delta.filter(|d| d.first > first.first).map(|d| ms(d.first, d.last)).sum()); + report.frame_ms.push(ms(first.first, last.last)); + let each = |l: &[Built]| match (l.first(), l.last()) { + (Some(a), Some(b)) => ms(a.first, b.last), + _ => 0.0, + }; + report.submits = built.steps.iter().map(|(_, l)| (l.len(), each(l))).collect(); + report.busy_ms.push(report.submits.iter().map(|s| s.1).sum()); + } + if o.detailed { + self.detail(&built, &stamps, o, &mut report); + } + 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")); + } + Ok(report) + } + + /// The last loop's time by command. + fn detail(&self, built: &Sends, stamps: &[u64], o: &Options, report: &mut Report) { + let mut kinds: BTreeMap<&str, (f64, u32)> = BTreeMap::new(); + let mut shaders: HashMap = HashMap::new(); + for l in built.steps.iter().flat_map(|(_, l)| l) { + let mut before = stamps[l.first as usize]; + for &(at, kind, pso) in &l.stamps { + let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency; + before = before.max(stamps[at]); + let k = kinds.entry(kind).or_default(); + *k = (k.0 + ms, k.1 + 1); + if pso != NONE { + let s = shaders.entry(pso).or_default(); + *s = (s.0 + ms, s.1 + 1); + } + } + } + report.categories = kinds.into_iter().map(|(k, (ms, n))| (k.to_owned(), ms, n)).collect(); + report.categories.sort_by(|a, b| b.1.total_cmp(&a.1)); + let mut all: Vec<(f64, u32, u32)> = shaders.into_iter().map(|(pso, (ms, n))| (ms, n, pso)).collect(); + all.sort_by(|a, b| b.0.total_cmp(&a.0)); + all.truncate(o.top); + report.shaders = all.into_iter().map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))).collect(); + } + + /// 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 { + report.notes.push("no picture was presented".into()); + return Ok(()); + }; + let Some(bytes) = self.contents(p.res)? else { + report.notes.push("the presented texture is not there".into()); + return Ok(()); + }; + let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else { + report.notes.push("the presented format is not shown".into()); + return Ok(()); + }; + let path = o.image.clone().unwrap_or_else(|| self.folder.join("replay.png")); + std::fs::write(&path, crate::capture::png(p.width, p.height, &rgb))?; + 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(); + report.picture = Some((gpu::psnr(&rgb, &was), rows_equal(&p, &bytes, &recorded))); + report.notes.push(format!( + "picture {} (blake3 {}; recorded {})", + path.display(), + &blake3::hash(&rgb).to_hex()[..16], + &blake3::hash(&was).to_hex()[..16] + )); + Ok(()) + } + + /// 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>> { + let Some(o) = self.objects.get(&id) else { + return Ok(None); + }; + let (res, r, subs) = (o.res.clone(), &self.frame.resources[o.index], o.subs); + let desc = gpu::to_desc(&r.desc); + 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 (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]); + } 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]); + // SAFETY: as above. + unsafe { barriers(list, &after) }; + } + })?; + // SAFETY: the buffer's mapping; the copy into it has run. + Ok(Some(unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec())) + } + + /// The id of the resource of a name (tests). + pub fn named(&self, name: &str) -> Option { + self.frame.resources.iter().find(|r| r.name == name).map(|r| r.id) + } +} + +/// Everything to send for a frame. +struct Sends { + /// For each submission: the copies of what the CPU wrote, its lists. + steps: Vec<(Option, Vec)>, + joints: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, + resolve: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), + _heap: ID3D12QueryHeap, + _back: ID3D12Resource, + data: usize, + count: u32, +} + +fn rows_equal(p: &wire::Present, a: &[u8], b: &[u8]) -> bool { + let texel = match p.format { + 9..=14 => 8, + _ => 4, + }; + (0..p.height as usize).all(|y| { + let from = y * p.pitch as usize; + let to = from + p.width as usize * texel; + a.get(from..to) == b.get(from..to) + }) +} + +fn to_rect(r: [i32; 4]) -> RECT { + RECT { left: r[0], top: r[1], right: r[2], bottom: r[3] } +} + +/// # Safety +/// An open list; barriers of live resources. +unsafe fn barriers(list: &ID3D12GraphicsCommandList, all: &[D3D12_RESOURCE_BARRIER]) { + for some in all.chunks(1000) { + // SAFETY: the caller's. + unsafe { list.ResourceBarrier(some) }; + } +} + +fn uav_barrier(res: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + // SAFETY: a borrowed pointer (or none) never released. + pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }), + }), + }, + } +} + +/// Any placed resource to any other: waits for all writes. +fn alias() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + pResourceAfter: std::mem::ManuallyDrop::new(None), + }), + }, + } +} + +fn read_at(file: &File, mut to: &mut [u8], mut at: u64) -> std::io::Result<()> { + while !to.is_empty() { + let n = file.seek_read(to, at)?; + if n == 0 { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + } + to = &mut to[n..]; + at += n as u64; + } + Ok(()) +} + +fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option)> { + // SAFETY: plain creation and queries. + unsafe { + if debug { + let mut layer: Option = None; + match D3D12GetDebugInterface(&mut layer) { + Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), + Err(e) => tracing::warn!("no debug layer: {e}"), + } + } + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let mut adapter = None; + for i in 0.. { + let Ok(a) = factory.EnumAdapters1(i) else { break }; + let d = a.GetDesc1()?; + if (d.VendorId, d.DeviceId) == (frame.vendor, frame.device) { + adapter = Some(a); + break; + } + } + if adapter.is_none() { + tracing::warn!("the adapter recorded on ({}) is not here: the default one is used", frame.adapter); + } + let mut device: Option = None; + match &adapter { + Some(a) => D3D12CreateDevice(a, D3D_FEATURE_LEVEL_12_0, &mut device)?, + None => D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?, + } + let device = device.context("no device")?; + let info = device.cast::().ok(); + Ok((device, info)) + } +} + +/// Logs the debug layer's messages; how many errors. +fn debug_messages(q: &ID3D12InfoQueue) -> usize { + let mut errors = 0; + let mut seen: HashMap = HashMap::new(); + // SAFETY: messages read into buffers of the size asked for. + unsafe { + for i in 0..q.GetNumStoredMessages() { + let mut size = 0; + if q.GetMessage(i, None, &mut size).is_err() { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if q.GetMessage(i, Some(message), &mut size).is_err() { + continue; + } + 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')); + } + } + } + q.ClearStoredMessages(); + } + errors +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn captures_are_found() { + let dir = tempfile::tempdir().unwrap(); + assert!(find(dir.path()).is_err()); + for n in [1, 2, 10, 11] { + std::fs::create_dir(dir.path().join(format!("capture-{n}"))).unwrap(); + } + for n in [1, 2, 10] { + std::fs::write(dir.path().join(format!("capture-{n}/frame.bin")), "").unwrap(); + } + // The last complete one; itself when named. + assert_eq!(find(dir.path()).unwrap(), dir.path().join("capture-10")); + assert_eq!(find(&dir.path().join("capture-2")).unwrap(), dir.path().join("capture-2")); + } + + #[test] + fn reports() { + assert_eq!(median(&[]), 0.0); + assert_eq!(median(&[3.0, 1.0, 2.0]), 2.0); + let r = Report { + frame_ms: vec![10.0, 12.0, 11.0], + busy_ms: vec![9.0; 3], + delta_ms: vec![0.5; 3], + submits: vec![(2, 9.0)], + picture: Some((40.0, false)), + ..Default::default() + }; + let t = r.text("a frame"); + assert!(t.contains("a frame: 11.00 ms"), "{t}"); + assert!(t.contains("between submissions 1.50 ms"), "{t}"); + assert!(t.contains("PSNR 40.0 dB"), "{t}"); + let o = Options { skip_clamps: true, buffers: Buffers::Card, ..Default::default() }; + assert!(o.edited() && !o.plain().edited() && o.plain().buffers == Buffers::Card); + } +} diff --git a/crates/victory-gpu/src/replay/pso.rs b/crates/victory-gpu/src/replay/pso.rs new file mode 100644 index 0000000..c1baa0d --- /dev/null +++ b/crates/victory-gpu/src/replay/pso.rs @@ -0,0 +1,317 @@ +//! Pipeline descriptions as parts: every form D3D12 takes them in (graphics, +//! compute, stream) is kept as the subobjects of a stream, and made again +//! from them as a stream. + +use std::ffi::{CString, c_void}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::{Interface, PCSTR}; + +use super::wire::{Blob, Part}; + +/// What a subobject holds, by its type: bytes, and whether it starts with a +/// pointer (aligned to 8). +enum Holds { + Root, + Code, + Layout, + /// Pointers the recorder does not follow. + Pointers(usize), + Plain(usize), +} + +fn holds(kind: i32) -> Option { + Some(match kind { + 0 => Holds::Root, + 1..=6 | 24 | 25 => Holds::Code, + 7 => Holds::Pointers(size_of::()), + 8 => Holds::Plain(size_of::()), + 9 | 13 | 14 | 16 | 18 | 20 => Holds::Plain(4), + 10 => Holds::Plain(size_of::()), + 11 => Holds::Plain(size_of::()), + 12 => Holds::Layout, + 15 => Holds::Plain(size_of::()), + 17 => Holds::Plain(size_of::()), + 19 => Holds::Pointers(size_of::()), + 21 => Holds::Plain(size_of::()), + 22 => Holds::Pointers(size_of::()), + 26 => Holds::Plain(size_of::()), + 27 => Holds::Plain(size_of::()), + 28 => Holds::Plain(size_of::()), + _ => return None, + }) +} + +/// What the parts need from the recorder. +pub(super) trait Keep { + fn root(&mut self, root: *mut c_void) -> u32; + fn code(&mut self, code: &[u8]) -> u32; + /// Something in a description that is not kept. + fn lost(&mut self, what: &str); +} + +/// # Safety +/// `at` points at a value of `size` bytes. +unsafe fn plain(kind: i32, at: *const c_void, size: usize) -> Part { + // SAFETY: the caller's. + Part::Plain { kind, data: Blob(unsafe { std::slice::from_raw_parts(at.cast::(), size) }.to_vec()) } +} + +unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Option { + if c.pShaderBytecode.is_null() || c.BytecodeLength == 0 { + return None; + } + // SAFETY: the description's own code. + let bytes = unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::(), c.BytecodeLength) }; + Some(Part::Code { kind, blob: keep.code(bytes) }) +} + +unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { + if l.pInputElementDescs.is_null() || l.NumElements == 0 { + return None; + } + // SAFETY: the description's own elements, with their names. + let elements = unsafe { std::slice::from_raw_parts(l.pInputElementDescs, l.NumElements as usize) } + .iter() + .map(|e| { + // SAFETY: as above. + let name = unsafe { e.SemanticName.to_string() }.unwrap_or_default(); + let rest = [ + e.SemanticIndex, + e.Format.0 as u32, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0 as u32, + e.InstanceDataStepRate, + ]; + (name, rest) + }) + .collect(); + Some(Part::Layout { elements }) +} + +/// # Safety +/// A valid description. +pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { + // SAFETY: the caller's description. + unsafe { + let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + parts.extend(code(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0, &d.CS, keep)); + if d.Flags.0 != 0 { + parts.push(plain(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0, (&raw const d.Flags).cast(), 4)); + } + parts + } +} + +/// # Safety +/// A valid description. +pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { + // SAFETY: the caller's description. + unsafe { + let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + for (kind, c) in [(1, &d.VS), (2, &d.PS), (3, &d.DS), (4, &d.HS), (5, &d.GS)] { + parts.extend(code(kind, c, keep)); + } + if d.StreamOutput.NumEntries != 0 { + keep.lost("a pipeline's stream output"); + } + parts.push(plain(8, (&raw const d.BlendState).cast(), size_of::())); + parts.push(plain(9, (&raw const d.SampleMask).cast(), 4)); + parts.push(plain(10, (&raw const d.RasterizerState).cast(), size_of::())); + parts.push(plain(11, (&raw const d.DepthStencilState).cast(), size_of::())); + parts.extend(layout(&d.InputLayout)); + parts.push(plain(13, (&raw const d.IBStripCutValue).cast(), 4)); + parts.push(plain(14, (&raw const d.PrimitiveTopologyType).cast(), 4)); + let targets = D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }; + parts.push(plain(15, (&raw const targets).cast(), size_of::())); + parts.push(plain(16, (&raw const d.DSVFormat).cast(), 4)); + parts.push(plain(17, (&raw const d.SampleDesc).cast(), size_of::())); + if d.Flags.0 != 0 { + parts.push(plain(20, (&raw const d.Flags).cast(), 4)); + } + parts + } +} + +/// # Safety +/// A valid description. +pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn Keep) -> Vec { + let base = d.pPipelineStateSubobjectStream.cast::().cast_const(); + let mut parts = Vec::new(); + let mut at = 0usize; + while at + 4 <= d.SizeInBytes { + // SAFETY: the caller's stream holds whole subobjects, each at a + // multiple of the size of a pointer. + unsafe { + let kind = base.add(at).cast::().read(); + let Some(h) = holds(kind) else { + keep.lost(&format!("a pipeline stream's subobject of type {kind}, and those after it")); + break; + }; + let (from, size) = match h { + Holds::Root => (8, 8), + Holds::Code | Holds::Layout => (8, 16), + Holds::Pointers(n) => (8, n), + Holds::Plain(n) => (4, n), + }; + let value = base.add(at + from); + match h { + Holds::Root => parts.push(Part::Root { root: keep.root(value.cast::<*mut c_void>().read()) }), + Holds::Code => parts.extend(code(kind, &*value.cast(), keep)), + Holds::Layout => parts.extend(layout(&*value.cast())), + Holds::Pointers(_) => { + // A cached blob is only a shortcut. + let empty = std::slice::from_raw_parts(value, size).iter().all(|&b| b == 0); + if kind != D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 && !empty { + keep.lost(&format!("a pipeline stream's subobject of type {kind}")); + } + } + Holds::Plain(n) => parts.push(plain(kind, value.cast(), n)), + } + at += (from + size).next_multiple_of(8); + } + } + parts +} + +/// A pipeline made again. +pub(super) fn make( + device: &ID3D12Device2, + parts: &[Part], + root: impl Fn(u32) -> Option, + code: impl Fn(u32) -> Option>, +) -> Result { + // Everything the stream points at, kept until the pipeline is made. + let mut codes: Vec> = Vec::new(); + let mut names: Vec = Vec::new(); + let mut elements: Vec> = Vec::new(); + let mut bytes: Vec = Vec::new(); + let mut roots = Vec::new(); + for part in parts { + bytes.resize(bytes.len().next_multiple_of(8), 0); + match part { + Part::Root { root: 0 } => {} + Part::Root { root: id } => { + let r = root(*id).ok_or_else(|| format!("root signature {id} is not in the capture"))?; + bytes.extend([0u8; 8]); + bytes.extend((r.as_raw() as usize).to_le_bytes()); + roots.push(r); + } + Part::Code { kind, blob } => { + let c = code(*blob).ok_or_else(|| format!("shader {blob} is not in the capture"))?; + bytes.extend(kind.to_le_bytes()); + bytes.extend([0u8; 4]); + bytes.extend((c.as_ptr() as usize).to_le_bytes()); + bytes.extend(c.len().to_le_bytes()); + codes.push(c); + } + Part::Plain { kind, data } => { + bytes.extend(kind.to_le_bytes()); + bytes.extend_from_slice(&data.0); + } + Part::Layout { elements: all } => { + let made: Vec = all + .iter() + .map(|(name, r)| { + names.push(CString::new(name.as_str()).unwrap_or_default()); + D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(names.last().map_or(std::ptr::null(), |n| n.as_ptr().cast())), + SemanticIndex: r[0], + Format: DXGI_FORMAT(r[1] as i32), + InputSlot: r[2], + AlignedByteOffset: r[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(r[4] as i32), + InstanceDataStepRate: r[5], + } + }) + .collect(); + bytes.extend(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0.to_le_bytes()); + bytes.extend([0u8; 4]); + bytes.extend((made.as_ptr() as usize).to_le_bytes()); + bytes.extend((made.len() as u64).to_le_bytes()); + elements.push(made); + } + } + } + bytes.resize(bytes.len().next_multiple_of(8), 0); + // Aligned for the pointers in it. + let mut words: Vec = bytes.chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: words.len() * 8, + pPipelineStateSubobjectStream: words.as_mut_ptr().cast(), + }; + // SAFETY: a stream of whole subobjects; all it points at is alive. + let made: windows::core::Result = unsafe { device.CreatePipelineState(&desc) }; + made.map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct Kept { + codes: Vec>, + lost: Vec, + } + + impl Keep for Kept { + fn root(&mut self, root: *mut c_void) -> u32 { + root as usize as u32 + } + fn code(&mut self, code: &[u8]) -> u32 { + self.codes.push(code.to_vec()); + self.codes.len() as u32 - 1 + } + fn lost(&mut self, what: &str) { + self.lost.push(what.into()); + } + } + + #[test] + fn a_stream_is_taken_apart() { + #[repr(C, align(8))] + struct Sub(i32, T); + #[repr(C)] + struct Stream { + root: Sub, + ms: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + unknown: Sub, + } + let bytes = [1u8, 2, 3]; + let mut s = Stream { + root: Sub(0, 77), + ms: Sub(25, D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: 3 }), + blend: Sub(8, D3D12_BLEND_DESC::default()), + mask: Sub(9, 5), + raster: Sub(10, D3D12_RASTERIZER_DESC { DepthBias: 6, ..Default::default() }), + depth: Sub(11, D3D12_DEPTH_STENCIL_DESC::default()), + targets: Sub(15, D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 3, ..Default::default() }), + dsv: Sub(16, DXGI_FORMAT(40)), + samples: Sub(17, DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }), + unknown: Sub(99, 0), + }; + let d = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::(), pPipelineStateSubobjectStream: (&raw mut s).cast() }; + let mut kept = Kept::default(); + // SAFETY: the stream above. + let parts = unsafe { stream(&d, &mut kept) }; + assert_eq!(kept.codes, [vec![1, 2, 3]]); + assert_eq!(kept.lost.len(), 1, "the unknown subobject is reported"); + assert_eq!(parts.len(), 9); + assert_eq!(parts[0], Part::Root { root: 77 }); + assert_eq!(parts[1], Part::Code { kind: 25, blob: 0 }); + assert_eq!(parts[3], Part::Plain { kind: 9, data: Blob(5u32.to_le_bytes().to_vec()) }); + let Part::Plain { kind: 10, data } = &parts[4] else { panic!("{:?}", parts[4]) }; + assert_eq!(data.0.len(), size_of::()); + assert_eq!(parts[7], Part::Plain { kind: 16, data: Blob(40u32.to_le_bytes().to_vec()) }); + } +} diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs new file mode 100644 index 0000000..ea9b6d9 --- /dev/null +++ b/crates/victory-gpu/src/replay/record.rs @@ -0,0 +1,2079 @@ +//! The recorder: what the host layer makes and records with D3D12, seen at +//! the D3D12 boundary (`super::hook`), and one frame of it written down +//! (`super::snap`). On with `VICTORY_RECORD=` only; without it +//! nothing is hooked. +//! +//! From the device's creation on it keeps what objects were made from and +//! what each descriptor slot holds, and follows the states of textures. +//! Lists are recorded only while it is armed: a few frames ahead of the one +//! captured, since the title records lists before they run. + +use std::cell::Cell; +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock}; + +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::core::{BOOL, GUID, HRESULT, IUnknown, Interface, PCWSTR}; + +use super::hook::{self, method, noted_entry, orig}; +use super::states::{self, Change, States}; +use super::wire::{self, ALL, Barrier, Cmd, Loc, NONE, Part, Place, Slot, Va, Wire, slot}; +use super::{gpu, pso, snap}; + +type Ptr = *mut c_void; +type Out = *mut *mut c_void; + +/// What to record. +#[derive(Clone, Debug)] +pub struct Settings { + /// Captures go to `capture-` in it. + pub folder: PathBuf, + pub at: At, + /// Frames to capture. + pub frames: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum At { + /// Seconds after the device was made. + Seconds(f64), + /// A number of presents. + Frame(u64), + /// When a file named `go` appears in the folder (this works in the + /// other cases too). + Trigger, +} + +impl Settings { + /// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f`) + /// and `VICTORY_RECORD_FRAMES`. + pub fn from_env() -> Option { + 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) }) + } +} + +fn parse_at(text: &str) -> At { + let text = text.trim(); + if let Some(frame) = text.strip_prefix('f').and_then(|n| n.parse().ok()) { + return At::Frame(frame); + } + match text.parse::() { + Ok(s) => At::Seconds(s), + Err(_) => At::Trigger, + } +} + +pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub(super) fn read(m: &RwLock) -> std::sync::RwLockReadGuard<'_, T> { + m.read().unwrap_or_else(|e| e.into_inner()) +} + +fn write(m: &RwLock) -> std::sync::RwLockWriteGuard<'_, T> { + m.write().unwrap_or_else(|e| e.into_inner()) +} + +/// A resource that lives. +pub(super) struct Res { + pub(super) id: u32, + pub(super) ptr: usize, + pub(super) place: Place, + pub(super) desc: wire::Desc, + pub(super) made_in: i32, + pub(super) clear: Option<[u32; 5]>, + pub(super) subs: u32, + pub(super) seen: gpu::Seen, + /// Made while a frame was being captured. + pub(super) late: bool, +} + +impl Res { + pub(super) fn is_buffer(&self) -> bool { + self.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 + } + + /// The object, without a reference of its own. + pub(super) fn object(&self) -> ManuallyDrop { + borrow(self.ptr as Ptr) + } +} + +/// A COM object named by its address, without a reference. +pub(super) fn borrow(p: Ptr) -> ManuallyDrop { + // SAFETY: the caller's live object; never released here. + ManuallyDrop::new(unsafe { T::from_raw(p) }) +} + +/// A descriptor heap: where it lies and what its slots hold. +pub(super) struct Heap { + pub(super) id: u32, + pub(super) kind: i32, + pub(super) count: u32, + pub(super) flags: i32, + cpu: usize, + gpu: u64, + step: usize, + slots: *mut Slot, +} + +// SAFETY: slots are written by the thread that writes the descriptor (the +// same rule as the descriptors': one writer at a time) and read as plain +// data. +unsafe impl Send for Heap {} +// SAFETY: as above. +unsafe impl Sync for Heap {} + +impl Heap { + fn new(id: u32, desc: &D3D12_DESCRIPTOR_HEAP_DESC, cpu: usize, gpu: u64, step: usize) -> Heap { + let layout = Self::layout(desc.NumDescriptors); + // SAFETY: a layout of at least one slot; a zeroed slot is an empty + // one. + let slots = unsafe { std::alloc::alloc_zeroed(layout) }.cast::(); + if slots.is_null() { + std::alloc::handle_alloc_error(layout); + } + Heap { id, kind: desc.Type.0, count: desc.NumDescriptors, flags: desc.Flags.0, cpu, gpu, step, slots } + } + + fn layout(count: u32) -> std::alloc::Layout { + std::alloc::Layout::array::(count.max(1) as usize).unwrap_or(std::alloc::Layout::new::()) + } + + pub(super) fn visible(&self) -> bool { + self.flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0 + } + + pub(super) fn get(&self, i: u32) -> Slot { + if i >= self.count { + return Slot::EMPTY; + } + // SAFETY: a slot of ours. + unsafe { self.slots.add(i as usize).read_volatile() } + } + + fn set(&self, i: u32, s: &Slot) { + if i < self.count { + // SAFETY: a slot of ours. + unsafe { self.slots.add(i as usize).write_volatile(*s) }; + } + } + + /// All slots, as they are now. + pub(super) fn all(&self) -> Vec { + let mut out = Vec::with_capacity(self.count as usize); + // SAFETY: `count` slots of ours. + unsafe { + std::ptr::copy_nonoverlapping(self.slots, out.as_mut_ptr(), self.count as usize); + out.set_len(self.count as usize); + } + out + } +} + +impl Drop for Heap { + fn drop(&mut self) { + // SAFETY: as allocated. + unsafe { std::alloc::dealloc(self.slots.cast(), Self::layout(self.count)) }; + } +} + +#[derive(Default)] +pub(super) struct Heaps { + by_cpu: BTreeMap>, + by_gpu: BTreeMap>, +} + +impl Heaps { + fn add(&mut self, heap: Arc) { + let end = heap.cpu + heap.count as usize * heap.step; + let gone: Vec = + self.by_cpu.range(..end).rev().take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu).map(|(&k, _)| k).collect(); + for k in gone { + self.by_cpu.remove(&k); + } + if heap.visible() { + self.by_gpu.insert(heap.gpu, heap.clone()); + } + self.by_cpu.insert(heap.cpu, heap); + } + + fn remove(&mut self, id: u32) { + self.by_cpu.retain(|_, h| h.id != id); + self.by_gpu.retain(|_, h| h.id != id); + } + + fn cpu(&self, at: usize) -> Option<(&Arc, u32)> { + let (_, h) = self.by_cpu.range(..=at).next_back()?; + let i = (at - h.cpu) / h.step; + (i < h.count as usize).then_some((h, i as u32)) + } + + fn gpu(&self, at: u64) -> Option<(&Arc, u32)> { + let (_, h) = self.by_gpu.range(..=at).next_back()?; + let i = (at - h.gpu) / h.step as u64; + (i < u64::from(h.count)).then_some((h, i as u32)) + } + + pub(super) fn visible(&self) -> impl Iterator> { + self.by_gpu.values() + } +} + +/// A command list's recording. +pub(super) struct ListState { + pub(super) kind: i32, + inner: Mutex, +} + +#[derive(Default)] +struct ListInner { + /// Recorded from its reset on. + whole: bool, + bytes: Vec, + changes: Vec, + closed: Option<(Option>>, Arc>)>, +} + +impl ListState { + fn push(&self, cmd: &Cmd) { + let mut inner = lock(&self.inner); + if inner.whole { + cmd.put(&mut inner.bytes); + } + } + + /// The recording closed last: its commands if it was recorded whole, + /// and the states it changes. None if it was not seen closed since its + /// reset. + pub(super) fn closed(&self) -> Option<(Option>>, Arc>)> { + lock(&self.inner).closed.clone() + } +} + +struct QueueState { + kind: i32, +} + +/// Shader code, written to `shaders.bin` as it is met, once each. +pub(super) struct Codes { + file: Option, + at: u64, + index: HashMap<[u8; 32], u32>, + pub(super) all: Vec, +} + +/// Objects by their address: ids. +#[derive(Default)] +struct Ids([RwLock>; 32]); + +impl Ids { + fn shard(&self, p: usize) -> &RwLock> { + &self.0[(p >> 5 ^ p >> 12) % 32] + } + fn get(&self, p: usize) -> Option { + read(self.shard(p)).get(&p).copied() + } + fn set(&self, p: usize, id: u32) { + write(self.shard(p)).insert(p, id); + } + fn remove(&self, p: usize, id: u32) { + let mut map = write(self.shard(p)); + if map.get(&p) == Some(&id) { + map.remove(&p); + } + } +} + +pub(super) struct Recorder { + pub(super) settings: Settings, + /// Where this process' capture goes. + pub(super) folder: PathBuf, + pub(super) began: std::time::Instant, + next: AtomicU32, + ids: Ids, + pub(super) resources: RwLock>>, + /// Buffers by their GPU address: size and id. + addresses: RwLock>, + pub(super) descriptors: RwLock, + lists: RwLock>>, + pub(super) heaps: Mutex>, + pub(super) roots: Mutex>>>, + pub(super) pipelines: Mutex>>>, + pub(super) signatures: Mutex>, + pub(super) queries: Mutex>, + pub(super) names: Mutex>, + pub(super) codes: Mutex, + pub(super) states: Mutex, + pub(super) queues: Mutex>, + device: Mutex>, + /// Lists are recorded. + armed: AtomicBool, + /// A frame is being captured: descriptor writes are noted, resources + /// made are kept alive. + pub(super) watching: AtomicBool, + pub(super) writes: Mutex>, + pub(super) held: Mutex>, + /// What could not be recorded, with how often. + problems: Mutex>, + /// Submissions and presents, one at a time. + pub(super) submits: Mutex, +} + +static RECORDER: OnceLock = OnceLock::new(); + +/// The recorder, if it is on. +pub(super) fn recorder() -> Option<&'static Recorder> { + RECORDER.get() +} + +/// Whether the recorder is on. +pub fn on() -> bool { + RECORDER.get().is_some() +} + +thread_local! { + static OURS: Cell = const { Cell::new(0) }; +} + +/// While it lives, this thread's D3D12 calls are our own: not recorded. +pub(super) struct Ours; + +impl Ours { + pub(super) fn new() -> Ours { + OURS.with(|o| o.set(o.get() + 1)); + Ours + } +} + +impl Drop for Ours { + fn drop(&mut self) { + OURS.with(|o| o.set(o.get() - 1)); + } +} + +fn ours() -> bool { + OURS.with(|o| o.get() > 0) +} + +impl Recorder { + fn new(settings: Settings) -> std::io::Result { + std::fs::create_dir_all(&settings.folder)?; + let mut n = 1; + let folder = loop { + let folder = settings.folder.join(format!("capture-{n}")); + match std::fs::create_dir(&folder) { + Ok(()) => break folder, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1, + Err(e) => return Err(e), + } + }; + let file = std::fs::File::create(folder.join("shaders.bin"))?; + Ok(Recorder { + settings, + folder, + began: std::time::Instant::now(), + next: AtomicU32::new(1), + ids: Ids::default(), + resources: RwLock::default(), + addresses: RwLock::default(), + descriptors: RwLock::default(), + lists: RwLock::default(), + heaps: Mutex::default(), + roots: Mutex::default(), + pipelines: Mutex::default(), + signatures: Mutex::default(), + queries: Mutex::default(), + names: Mutex::default(), + codes: Mutex::new(Codes { file: Some(file), at: 0, index: HashMap::new(), all: Vec::new() }), + states: Mutex::default(), + queues: Mutex::default(), + device: Mutex::default(), + armed: AtomicBool::new(false), + watching: AtomicBool::new(false), + writes: Mutex::default(), + held: Mutex::default(), + problems: Mutex::default(), + submits: Mutex::new(snap::Phase::default()), + }) + } + + fn id(&self) -> u32 { + self.next.fetch_add(1, Ordering::Relaxed) + } + + /// Notes something that is not in the capture. + pub(super) fn problem(&self, what: &str) { + self.problem_times(what, 1); + } + + pub(super) fn problem_times(&self, what: &str, n: u64) { + let mut problems = lock(&self.problems); + let seen = problems.entry(what.to_owned()).or_insert(0); + if *seen == 0 { + tracing::warn!("frame recorder: {what}"); + } + *seen += n; + } + + /// The problems so far. + pub(super) fn problems(&self) -> Vec { + lock(&self.problems).iter().map(|(what, n)| if *n == 1 { what.clone() } else { format!("{what} ({n} times)") }).collect() + } + + pub(super) fn arm(&self, on: bool) { + self.armed.store(on, Ordering::SeqCst); + } + + pub(super) fn device(&self) -> Option { + lock(&self.device).clone() + } + + /// The state of a list, if its methods are still ours. + pub(super) fn list(&self, p: Ptr) -> Option> { + let state = read(&self.lists).get(&(p as usize)).cloned()?; + // SAFETY: a live list: it is being submitted. + if !unsafe { hook::ours(p) } { + self.problem("a list lost its hooks"); + return None; + } + Some(state) + } + + /// The buffer an address lies in. + pub(super) fn va(&self, address: u64) -> Va { + if address == 0 { + return Va::Null {}; + } + match read(&self.addresses).range(..=address).next_back() { + Some((&start, &(size, res))) if address - start < size => Va::At { res, offset: address - start }, + _ => Va::Unknown { address }, + } + } + + /// The id of an object, [`NONE`] for null; an unknown one is a problem. + fn object(&self, p: Ptr, what: &str) -> u32 { + if p.is_null() { + return NONE; + } + self.ids.get(p as usize).unwrap_or_else(|| { + self.problem(&format!("{what} was used that was not seen made")); + NONE + }) + } + + /// The id of a resource; one not seen made (a swap chain's buffer) is + /// taken in now. + pub(super) fn resource(&self, p: Ptr) -> u32 { + if p.is_null() { + return NONE; + } + if let Some(id) = self.ids.get(p as usize) { + return id; + } + self.add(p, Place::BackBuffer {}, 0, None) + } + + /// Takes a new resource in. + fn add(&self, p: Ptr, place: Place, made_in: i32, clear: Option<[u32; 5]>) -> u32 { + let object = borrow::(p); + // SAFETY: a live resource. + let d = unsafe { object.GetDesc() }; + let desc = gpu::from_desc(&d); + let id = self.id(); + let seen = match &place { + Place::Committed { props, .. } => gpu::seen(props), + Place::Placed { heap, .. } => lock(&self.heaps).get(heap).map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), + Place::BackBuffer {} => gpu::Seen::No, + }; + let subs = gpu::subresources(&desc); + let is_buffer = desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + // SAFETY: a live buffer. + let va = if is_buffer { unsafe { object.GetGPUVirtualAddress() } } else { 0 }; + let placed = matches!(place, Place::Placed { .. }); + let late = self.watching.load(Ordering::SeqCst); + { + let mut states = lock(&self.states); + if !is_buffer { + let decays = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; + states.add(id, subs, made_in as u32, decays); + } + if placed { + states.in_use(id); + } + } + if va != 0 { + write(&self.addresses).insert(va, (desc.width, id)); + } + let res = Arc::new(Res { id, ptr: p as usize, place, desc, made_in, clear, subs, seen, late }); + write(&self.resources).insert(id, res); + self.ids.set(p as usize, id); + if late { + lock(&self.held).push(ID3D12Resource::clone(&object)); + } + self.tell_gone(&*object, Gone::Resource { id, ptr: p as usize, va }); + id + } + + fn gone(&self, what: &Gone) { + match *what { + Gone::Resource { id, ptr, va } => { + self.ids.remove(ptr, id); + write(&self.resources).remove(&id); + if va != 0 { + let mut all = write(&self.addresses); + if all.get(&va).is_some_and(|&(_, i)| i == id) { + all.remove(&va); + } + } + lock(&self.states).remove(id); + lock(&self.names).remove(&id); + } + Gone::List { ptr } => { + write(&self.lists).remove(&ptr); + } + Gone::Heap { id, ptr } => { + self.ids.remove(ptr, id); + write(&self.descriptors).remove(id); + } + } + } + + /// Has us told when an object dies. + fn tell_gone(&self, object: &impl Interface, what: Gone) { + const KEY: GUID = GUID::from_u128(0x3d0d5c1e_7a1b_4a53_9a3e_5f2b1e6b9c41); + let notice = Box::into_raw(Box::new(Notice { methods: &NOTICE, references: AtomicU32::new(1), what })); + // SAFETY: a COM object of ours with one reference, which this drops + // at the end; the object takes its own. + unsafe { + let notice = IUnknown::from_raw(notice.cast()); + let set = object.cast::().and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); + if set.is_err() { + self.problem("an object's end cannot be followed"); + std::mem::forget(notice); + } + } + } + + fn view(&self, at: usize) -> Slot { + match read(&self.descriptors).cpu(at) { + Some((h, i)) => h.get(i), + None => { + self.problem("a descriptor handle in no heap seen made"); + Slot::EMPTY + } + } + } + + fn set_view(&self, at: usize, s: &Slot) { + let all = read(&self.descriptors); + let Some((h, i)) = all.cpu(at) else { + drop(all); + self.problem("a view was made in no descriptor heap seen made"); + return; + }; + h.set(i, s); + self.wrote(h, i, 1); + } + + /// After slots were written: noted if a frame is being captured. + fn wrote(&self, h: &Heap, first: u32, n: u32) { + if h.visible() && self.watching.load(Ordering::SeqCst) { + lock(&self.writes).push((h.id, first, n)); + } + } + + fn copy_views(&self, to: usize, from: usize, n: u32) { + let all = read(&self.descriptors); + let (Some((a, i)), Some((b, j))) = (all.cpu(to), all.cpu(from)) else { + drop(all); + self.problem("descriptors were copied in no heap seen made"); + return; + }; + for k in 0..n { + a.set(i + k, &b.get(j + k)); + } + self.wrote(a, i, n); + } + + fn code(&self, bytes: &[u8]) -> u32 { + use std::io::Write; + let hash = *blake3::hash(bytes).as_bytes(); + let mut codes = lock(&self.codes); + if let Some(&i) = codes.index.get(&hash) { + return i; + } + let i = codes.all.len() as u32; + let at = codes.at; + let wrote = codes.file.as_mut().is_some_and(|f| f.write_all(bytes).is_ok()); + if !wrote { + drop(codes); + self.problem("shader code could not be written"); + return u32::MAX; + } + codes.at += bytes.len() as u64; + codes.all.push(wire::Code { at, len: bytes.len() as u64, hash }); + codes.index.insert(hash, i); + i + } + + fn pipeline(&self, p: Ptr, parts: Vec) { + let id = self.id(); + lock(&self.pipelines).insert(id, Arc::new(parts)); + self.ids.set(p as usize, id); + } + + /// `name` is an object's, for reports. + fn name(&self, p: Ptr, name: &str) { + if let Some(id) = self.ids.get(p as usize) { + lock(&self.names).insert(id, name.to_owned()); + } + } +} + +struct Keeper<'a>(&'a Recorder); + +impl pso::Keep for Keeper<'_> { + fn root(&mut self, root: Ptr) -> u32 { + self.0.object(root, "a root signature") + } + fn code(&mut self, code: &[u8]) -> u32 { + self.0.code(code) + } + fn lost(&mut self, what: &str) { + self.0.problem(what); + } +} + +/// Which object died. +enum Gone { + Resource { id: u32, ptr: usize, va: u64 }, + List { ptr: usize }, + Heap { id: u32, ptr: usize }, +} + +/// A COM object an object of D3D12's holds and lets go of when it dies. +#[repr(C)] +struct Notice { + methods: *const NoticeTable, + references: AtomicU32, + what: Gone, +} + +#[repr(C)] +struct NoticeTable { + query: unsafe extern "system" fn(Ptr, *const GUID, Out) -> HRESULT, + add: unsafe extern "system" fn(Ptr) -> u32, + release: unsafe extern "system" fn(Ptr) -> u32, +} +static NOTICE: NoticeTable = NoticeTable { query: notice_query, add: notice_add, release: notice_release }; + +unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: COM's rules: a valid id and place for the answer. + unsafe { + if *iid == IUnknown::IID { + notice_add(this); + *out = this; + return HRESULT(0); + } + *out = std::ptr::null_mut(); + } + HRESULT(0x8000_4002_u32 as i32) +} + +unsafe extern "system" fn notice_add(this: Ptr) -> u32 { + // SAFETY: one of ours, alive while a reference is. + unsafe { (*this.cast::()).references.fetch_add(1, Ordering::Relaxed) + 1 } +} + +unsafe extern "system" fn notice_release(this: Ptr) -> u32 { + // SAFETY: as above; the last reference frees the box it was made as. + unsafe { + let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + let notice = Box::from_raw(this.cast::()); + if let Some(r) = recorder() { + r.gone(¬ice.what); + } + } + left + } +} + +/// Starts the recorder if the environment asks for it, and hooks `device`. +/// Called right after the device was made. +pub(crate) fn from_env(device: &ID3D12Device) { + let Some(settings) = Settings::from_env() else { + return; + }; + match start(settings, device) { + Ok(folder) => tracing::info!(folder = %folder.display(), "frame recorder on"), + Err(e) => tracing::warn!(error = %e, "frame recorder not started"), + } +} + +/// Starts the recorder (once a process) and hooks `device`, which must have +/// made nothing the frame will use. Where the capture will be. +pub fn start(settings: Settings, device: &ID3D12Device) -> std::io::Result { + let r = Recorder::new(settings)?; + let folder = r.folder.clone(); + if RECORDER.set(r).is_err() { + return Err(std::io::Error::other("the recorder is already on")); + } + let r = recorder().ok_or_else(|| std::io::Error::other("no recorder"))?; + *lock(&r.device) = Some(device.clone()); + // The newer interfaces may be other pointers (they are the same one + // without the debug layer). + let mut all = vec![device.as_raw()]; + let mut more: Vec = Vec::new(); + for iid in [ + ID3D12Device1::IID, + ID3D12Device2::IID, + ID3D12Device3::IID, + ID3D12Device4::IID, + ID3D12Device5::IID, + ID3D12Device8::IID, + ID3D12Device10::IID, + ID3D12Device11::IID, + ID3D12Device13::IID, + ] { + if let Some(p) = query(device.as_raw(), &iid) { + all.push(p.as_raw()); + more.push(p); + } + } + for p in all { + // SAFETY: a live device; the entries below are of their methods' + // types (the compiler checks them). + unsafe { hook::install(p, std::ptr::null(), device_table) }; + } + Ok(folder) +} + +/// Unhooks `device` (tests). +pub fn unhook(device: &ID3D12Device) { + // SAFETY: a live device, used by no other thread (the caller's word). + unsafe { hook::remove(device.as_raw()) }; +} + +/// The object's interface `iid`. +fn query(p: Ptr, iid: &GUID) -> Option { + let object = borrow::(p); + let mut out = std::ptr::null_mut(); + // SAFETY: a live COM object. + unsafe { + object.query(iid, &mut out).ok().ok()?; + (!out.is_null()).then(|| IUnknown::from_raw(out)) + } +} + +/// Names an object for reports. +pub fn name(object: &impl Interface, text: &str) { + if let Some(r) = recorder() { + r.name(object.as_raw(), text); + } +} + +/// At the end of a frame, before the swap chain's present: `texture`, in +/// `state`, is shown. +pub fn present(texture: &ID3D12Resource, state: D3D12_RESOURCE_STATES) { + if let Some(r) = recorder() { + snap::present(r, texture, state.0 as u32); + } +} + +/// Where the capture is, once it is done. +pub fn finished() -> Option { + let r = recorder()?; + lock(&r.submits).done().then(|| r.folder.clone()) +} + +/// Sets a method of a table to a function of its type. +macro_rules! set { + ($t:ident, $vtbl:ident . $name:ident = $f:expr) => {{ + // The compiler checks the function's type here. + let _ = |v: &mut $vtbl| v.$name = $f; + $t[method!($vtbl.$name)] = $f as *const () as usize; + }}; +} + +/// The object's own method. +macro_rules! own { + ($this:ident, $vtbl:ident . $name:ident) => { + orig::<$vtbl>($this).$name + }; +} + +/// Entries for methods that are not recorded: counted, and named in the +/// capture's notes if they were called. +macro_rules! not_recorded { + ($t:ident, $class:ident, $names:ident: $($vtbl:ident . $name:ident),* $(,)?) => { + const $names: &[(usize, &str)] = &[$((method!($vtbl.$name), stringify!($name))),*]; + $($t[method!($vtbl.$name)] = noted_entry::<{ hook::$class * hook::SLOTS + method!($vtbl.$name) }>();)* + }; +} + +fn device_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12Device_Vtbl.CreateCommandQueue = create_queue); + set!(t, ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics); + set!(t, ID3D12Device_Vtbl.CreateComputePipelineState = create_compute); + set!(t, ID3D12Device_Vtbl.CreateCommandList = create_list); + set!(t, ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors); + set!(t, ID3D12Device_Vtbl.CreateRootSignature = create_root); + set!(t, ID3D12Device_Vtbl.CreateConstantBufferView = create_cbv); + set!(t, ID3D12Device_Vtbl.CreateShaderResourceView = create_srv); + set!(t, ID3D12Device_Vtbl.CreateUnorderedAccessView = create_uav); + set!(t, ID3D12Device_Vtbl.CreateRenderTargetView = create_rtv); + set!(t, ID3D12Device_Vtbl.CreateDepthStencilView = create_dsv); + set!(t, ID3D12Device_Vtbl.CreateSampler = create_sampler); + set!(t, ID3D12Device_Vtbl.CopyDescriptors = copy_descriptors); + set!(t, ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple); + set!(t, ID3D12Device_Vtbl.CreateCommittedResource = create_committed); + set!(t, ID3D12Device_Vtbl.CreateHeap = create_heap); + set!(t, ID3D12Device_Vtbl.CreatePlacedResource = create_placed); + set!(t, ID3D12Device_Vtbl.CreateQueryHeap = create_queries); + set!(t, ID3D12Device_Vtbl.CreateCommandSignature = create_signature); + set!(t, ID3D12Device1_Vtbl.CreatePipelineLibrary = create_library); + set!(t, ID3D12Device2_Vtbl.CreatePipelineState = create_stream); + let _ = device_rest(t); +} + +fn device_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] { + not_recorded!(t, DEVICE, NAMES: + ID3D12Device_Vtbl.CreateReservedResource, + ID3D12Device_Vtbl.OpenSharedHandle, + ID3D12Device4_Vtbl.CreateCommandList1, + ID3D12Device4_Vtbl.CreateCommittedResource1, + ID3D12Device4_Vtbl.CreateHeap1, + ID3D12Device4_Vtbl.CreateReservedResource1, + ID3D12Device5_Vtbl.CreateStateObject, + ID3D12Device8_Vtbl.CreateCommittedResource2, + ID3D12Device8_Vtbl.CreatePlacedResource1, + ID3D12Device8_Vtbl.CreateSamplerFeedbackUnorderedAccessView, + ID3D12Device10_Vtbl.CreateCommittedResource3, + ID3D12Device10_Vtbl.CreatePlacedResource2, + ID3D12Device10_Vtbl.CreateReservedResource2, + ID3D12Device11_Vtbl.CreateSampler2, + ); + NAMES +} + +fn queue_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12CommandQueue_Vtbl.ExecuteCommandLists = execute); + let _ = queue_rest(t); +} + +fn queue_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] { + not_recorded!(t, QUEUE, NAMES: + ID3D12CommandQueue_Vtbl.UpdateTileMappings, + ID3D12CommandQueue_Vtbl.CopyTileMappings, + ID3D12CommandQueue_Vtbl.Wait, + ); + NAMES +} + +fn library_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics); + set!(t, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute); + set!(t, ID3D12PipelineLibrary1_Vtbl.LoadPipeline = load_stream); +} + +fn list_table(t: &mut [usize; hook::SLOTS]) { + set!(t, ID3D12GraphicsCommandList_Vtbl.Close = list_close); + set!(t, ID3D12GraphicsCommandList_Vtbl.Reset = list_reset); + set!(t, ID3D12GraphicsCommandList_Vtbl.DrawInstanced = draw); + set!(t, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed); + set!(t, ID3D12GraphicsCommandList_Vtbl.Dispatch = dispatch); + set!(t, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer); + set!(t, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture); + set!(t, ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource); + set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve); + set!(t, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology); + set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetViewports = viewports); + set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors); + set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor); + set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline); + set!(t, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier = barrier); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute); + set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics); + set!(t, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer); + set!(t, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers); + set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets); + set!(t, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth); + set!(t, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target); + set!(t, ID3D12GraphicsCommandList_Vtbl.DiscardResource = discard); + set!(t, ID3D12GraphicsCommandList_Vtbl.BeginQuery = begin_query); + set!(t, ID3D12GraphicsCommandList_Vtbl.EndQuery = end_query); + set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query); + set!(t, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect = indirect); + set!(t, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region); + set!(t, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds); + set!(t, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate); + set!(t, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh); + let _ = list_rest(t); +} + +fn list_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] { + not_recorded!(t, LIST, NAMES: + ID3D12GraphicsCommandList_Vtbl.ClearState, + ID3D12GraphicsCommandList_Vtbl.CopyTiles, + ID3D12GraphicsCommandList_Vtbl.ExecuteBundle, + ID3D12GraphicsCommandList_Vtbl.SOSetTargets, + ID3D12GraphicsCommandList_Vtbl.ClearUnorderedAccessViewUint, + ID3D12GraphicsCommandList_Vtbl.ClearUnorderedAccessViewFloat, + ID3D12GraphicsCommandList_Vtbl.SetPredication, + ID3D12GraphicsCommandList1_Vtbl.AtomicCopyBufferUINT, + ID3D12GraphicsCommandList1_Vtbl.AtomicCopyBufferUINT64, + ID3D12GraphicsCommandList1_Vtbl.SetSamplePositions, + ID3D12GraphicsCommandList1_Vtbl.SetViewInstanceMask, + ID3D12GraphicsCommandList3_Vtbl.SetProtectedResourceSession, + ID3D12GraphicsCommandList4_Vtbl.BeginRenderPass, + ID3D12GraphicsCommandList4_Vtbl.EndRenderPass, + ID3D12GraphicsCommandList4_Vtbl.InitializeMetaCommand, + ID3D12GraphicsCommandList4_Vtbl.ExecuteMetaCommand, + ID3D12GraphicsCommandList4_Vtbl.BuildRaytracingAccelerationStructure, + ID3D12GraphicsCommandList4_Vtbl.EmitRaytracingAccelerationStructurePostbuildInfo, + ID3D12GraphicsCommandList4_Vtbl.CopyRaytracingAccelerationStructure, + ID3D12GraphicsCommandList4_Vtbl.SetPipelineState1, + ID3D12GraphicsCommandList4_Vtbl.DispatchRays, + ID3D12GraphicsCommandList5_Vtbl.RSSetShadingRate, + ID3D12GraphicsCommandList5_Vtbl.RSSetShadingRateImage, + ID3D12GraphicsCommandList7_Vtbl.Barrier, + ID3D12GraphicsCommandList8_Vtbl.OMSetFrontAndBackStencilRef, + ID3D12GraphicsCommandList9_Vtbl.RSSetDepthBias, + ID3D12GraphicsCommandList9_Vtbl.IASetIndexBufferStripCutValue, + ID3D12GraphicsCommandList10_Vtbl.SetProgram, + ID3D12GraphicsCommandList10_Vtbl.DispatchGraph, + ); + NAMES +} + +/// How often each method that is not recorded was called so far. +pub(super) fn not_recorded_calls() -> Vec<(String, u64)> { + let mut t = [0; hook::SLOTS]; + let mut all = Vec::new(); + for (class, of, names) in [ + (hook::LIST, "command list", list_rest(&mut t)), + (hook::DEVICE, "device", device_rest(&mut t)), + (hook::QUEUE, "queue", queue_rest(&mut t)), + ] { + for &(slot, name) in names { + let what = match (class, name) { + // Submissions are in order anyway: the replay has one queue. + (hook::QUEUE, "Wait") => "waits of the drawing queue (the swap chain makes some) are not replayed".to_owned(), + _ => format!("{of} method {name} is not recorded, and was called"), + }; + all.push((what, hook::count(class, slot))); + } + } + all +} + +/// The recorder, for a call that is the host layer's and not our own, which +/// succeeded. +fn made(hr: HRESULT, out: Out) -> Option<(&'static Recorder, Ptr)> { + if hr.is_err() || out.is_null() || ours() { + return None; + } + // SAFETY: the call's answer. + let p = unsafe { *out }; + (!p.is_null()).then_some(())?; + Some((recorder()?, p)) +} + +unsafe extern "system" fn create_queue(this: Ptr, desc: *const D3D12_COMMAND_QUEUE_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: the caller's arguments, passed on; then a new queue no other + // thread knows. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandQueue)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let kind = (*desc).Type.0; + let state = Box::leak(Box::new(QueueState { kind })); + hook::install(p, (&raw const *state).cast(), queue_table); + lock(&r.queues).push((ID3D12CommandQueue::clone(&borrow(p)), kind)); + } + hr + } +} + +unsafe extern "system" fn create_list( + this: Ptr, + nodes: u32, + kind: D3D12_COMMAND_LIST_TYPE, + allocator: Ptr, + pso: Ptr, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)(this, nodes, kind, allocator, pso, iid, out); + if let Some((r, p)) = made(hr, out) { + let state = Arc::new(ListState { kind: kind.0, inner: Mutex::default() }); + // Every interface of it we hook, and the one it is submitted as. + static ONE: OnceLock = OnceLock::new(); + let iids = [ + ID3D12CommandList::IID, + ID3D12GraphicsCommandList1::IID, + ID3D12GraphicsCommandList2::IID, + ID3D12GraphicsCommandList4::IID, + ID3D12GraphicsCommandList6::IID, + ]; + let same = *ONE.get_or_init(|| iids.iter().all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p))); + let mut all = vec![p]; + if !same { + all.extend(iids.iter().filter_map(|iid| query(p, iid)).map(|q| q.as_raw())); + } + { + let mut inner = lock(&state.inner); + inner.whole = r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; + begin(&mut inner, r, pso); + } + for q in all { + // The state's address is kept for good, as the table is. + hook::install(q, Arc::into_raw(state.clone()).cast(), list_table); + write(&r.lists).insert(q as usize, state.clone()); + r.tell_gone(&*borrow::(q), Gone::List { ptr: q as usize }); + } + } + hr + } +} + +/// A list is open again, with pipeline `pso`. +fn begin(inner: &mut ListInner, r: &Recorder, pso: Ptr) { + inner.bytes = Vec::new(); + inner.changes.clear(); + if inner.whole && !pso.is_null() { + Cmd::Pipeline { pso: r.object(pso, "a pipeline") }.put(&mut inner.bytes); + } +} + +unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device1_Vtbl.CreatePipelineLibrary)(this, blob, size, iid, out); + if let Some((_, p)) = made(hr, out) { + let mut all = vec![p]; + let newer = query(p, &ID3D12PipelineLibrary1::IID); + all.extend(newer.as_ref().map(|q| q.as_raw())); + for q in all { + hook::install(q, std::ptr::null(), library_table); + } + } + hr + } +} + +unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above; the description is valid, as it was accepted. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateGraphicsPipelineState)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateComputePipelineState)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::compute(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn create_stream(this: Ptr, desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device2_Vtbl.CreatePipelineState)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::stream(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn load_graphics( + this: Ptr, + name: PCWSTR, + desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn load_compute( + this: Ptr, + name: PCWSTR, + desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::compute(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn load_stream( + this: Ptr, + name: PCWSTR, + desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12PipelineLibrary1_Vtbl.LoadPipeline)(this, name, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + r.pipeline(p, pso::stream(&*desc, &mut Keeper(r))); + } + hr + } +} + +unsafe extern "system" fn create_root(this: Ptr, nodes: u32, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); + if let Some((r, p)) = made(hr, out) { + // D3D12 may answer with an object it made before. + let known = r.ids.get(p as usize).filter(|id| lock(&r.roots).contains_key(id)); + let bytes = std::slice::from_raw_parts(blob.cast::(), size).to_vec(); + let id = known.unwrap_or_else(|| r.id()); + lock(&r.roots).insert(id, Arc::new(bytes)); + r.ids.set(p as usize, id); + } + hr + } +} + +unsafe extern "system" fn create_signature( + this: Ptr, + desc: *const D3D12_COMMAND_SIGNATURE_DESC, + root: Ptr, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandSignature)(this, desc, root, iid, out); + if let Some((r, p)) = made(hr, out) { + let id = r.id(); + let d = &*desc; + let args: Vec<[u32; 4]> = + std::slice::from_raw_parts(d.pArgumentDescs.cast::<[u32; 4]>(), d.NumArgumentDescs as usize).to_vec(); + // Arguments that are GPU addresses lie in buffers; they are not + // rewritten for a replay. + let addresses = [ + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW, + D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, + ]; + if args.iter().any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) { + r.problem("a command signature with GPU addresses among its arguments: a replay reads the recorded addresses"); + } + let root = if root.is_null() { NONE } else { r.object(root, "a root signature") }; + lock(&r.signatures).insert(id, wire::Signature { id, stride: d.ByteStride, args, root }); + r.ids.set(p as usize, id); + } + hr + } +} + +unsafe extern "system" fn create_queries(this: Ptr, desc: *const D3D12_QUERY_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateQueryHeap)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let id = r.id(); + lock(&r.queries).insert(id, wire::QueryHeap { id, kind: (*desc).Type.0, count: (*desc).Count }); + r.ids.set(p as usize, id); + } + hr + } +} + +unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCRIPTOR_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateDescriptorHeap)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let heap = borrow::(p); + let d = &*desc; + let visible = d.Flags.0 & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0; + let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr; + let gpu = if visible { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 }; + let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) as usize; + let id = r.id(); + write(&r.descriptors).add(Arc::new(Heap::new(id, d, cpu, gpu, step.max(1)))); + r.ids.set(p as usize, id); + r.tell_gone(&*heap, Gone::Heap { id, ptr: p as usize }); + } + hr + } +} + +unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateHeap)(this, desc, iid, out); + if let Some((r, p)) = made(hr, out) { + let id = r.id(); + lock(&r.heaps).insert(id, heap_of(id, &*desc)); + r.ids.set(p as usize, id); + } + hr + } +} + +fn heap_of(id: u32, d: &D3D12_HEAP_DESC) -> wire::Heap { + wire::Heap { id, size: d.SizeInBytes, props: gpu::from_props(&d.Properties), alignment: d.Alignment, flags: d.Flags.0 } +} + +unsafe fn clear_of(clear: *const D3D12_CLEAR_VALUE) -> Option<[u32; 5]> { + const _: () = assert!(size_of::() == 20); + // SAFETY: null or a clear value, of 20 bytes. + (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read() }) +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn create_committed( + this: Ptr, + props: *const D3D12_HEAP_PROPERTIES, + flags: D3D12_HEAP_FLAGS, + desc: *const D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, + clear: *const D3D12_CLEAR_VALUE, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)(this, props, flags, desc, state, clear, iid, out); + if let Some((r, p)) = made(hr, out) { + let place = Place::Committed { props: gpu::from_props(&*props), flags: flags.0 }; + r.add(p, place, state.0, clear_of(clear)); + } + hr + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn create_placed( + this: Ptr, + heap: Ptr, + offset: u64, + desc: *const D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, + clear: *const D3D12_CLEAR_VALUE, + iid: *const GUID, + out: Out, +) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)(this, heap, offset, desc, state, clear, iid, out); + if let Some((r, p)) = made(hr, out) { + // One opened from memory was not seen made. + let heap = r.ids.get(heap as usize).unwrap_or_else(|| { + let id = r.id(); + let d = borrow::(heap).GetDesc(); + r.problem("a heap opened from existing memory: a replay makes one like it"); + lock(&r.heaps).insert(id, heap_of(id, &d)); + r.ids.set(heap as usize, id); + id + }); + r.add(p, Place::Placed { heap, offset }, state.0, clear_of(clear)); + } + hr + } +} + +unsafe extern "system" fn create_cbv(this: Ptr, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateConstantBufferView)(this, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + r.set_view(at.ptr, &Slot::new(slot::CBV, NONE, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_srv(this: Ptr, res: Ptr, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateShaderResourceView)(this, res, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let id = r.resource(res); + r.set_view(at.ptr, &Slot::new(slot::SRV, id, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_uav( + this: Ptr, + res: Ptr, + counter: Ptr, + desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateUnorderedAccessView)(this, res, counter, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let (id, counter) = (r.resource(res), r.resource(counter)); + r.set_view(at.ptr, &Slot::new(slot::UAV, id, counter, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_rtv(this: Ptr, res: Ptr, desc: *const D3D12_RENDER_TARGET_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateRenderTargetView)(this, res, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let id = r.resource(res); + r.set_view(at.ptr, &Slot::new(slot::RTV, id, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_dsv(this: Ptr, res: Ptr, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateDepthStencilView)(this, res, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + let id = r.resource(res); + r.set_view(at.ptr, &Slot::new(slot::DSV, id, NONE, desc.cast(), size_of::())); + } + } +} + +unsafe extern "system" fn create_sampler(this: Ptr, desc: *const D3D12_SAMPLER_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + const _: () = assert!(size_of::() == 52); + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CreateSampler)(this, desc, at); + if let Some(r) = recorder().filter(|_| !ours()) { + r.set_view(at.ptr, &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52)); + } + } +} + +unsafe extern "system" fn copy_descriptors_simple( + this: Ptr, + n: u32, + to: D3D12_CPU_DESCRIPTOR_HANDLE, + from: D3D12_CPU_DESCRIPTOR_HANDLE, + kind: D3D12_DESCRIPTOR_HEAP_TYPE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12Device_Vtbl.CopyDescriptorsSimple)(this, n, to, from, kind); + if let Some(r) = recorder().filter(|_| !ours()) { + r.copy_views(to.ptr, from.ptr, n); + } + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn copy_descriptors( + this: Ptr, + n_to: u32, + to: *const D3D12_CPU_DESCRIPTOR_HANDLE, + to_sizes: *const u32, + n_from: u32, + from: *const D3D12_CPU_DESCRIPTOR_HANDLE, + from_sizes: *const u32, + kind: D3D12_DESCRIPTOR_HEAP_TYPE, +) { + // SAFETY: as above; the arrays have as many entries as the counts say, + // and null sizes mean one descriptor each. + unsafe { + own!(this, ID3D12Device_Vtbl.CopyDescriptors)(this, n_to, to, to_sizes, n_from, from, from_sizes, kind); + let Some(r) = recorder().filter(|_| !ours()) else { + return; + }; + let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; + let size = |sizes: *const u32, i: u32| if sizes.is_null() { 1 } else { *sizes.add(i as usize) }; + let (mut i, mut j, mut done_to, mut done_from) = (0, 0, 0, 0); + while i < n_to && j < n_from { + let n = (size(to_sizes, i) - done_to).min(size(from_sizes, j) - done_from); + if n > 0 { + let a = (*to.add(i as usize)).ptr + done_to as usize * step; + let b = (*from.add(j as usize)).ptr + done_from as usize * step; + r.copy_views(a, b, n); + } + done_to += n; + done_from += n; + if done_to >= size(to_sizes, i) { + (i, done_to) = (i + 1, 0); + } + if done_from >= size(from_sizes, j) { + (j, done_from) = (j + 1, 0); + } + } + } +} + +unsafe extern "system" fn execute(this: Ptr, n: u32, lists: *const Ptr) { + // SAFETY: `n` closed lists, as D3D12 asks; the state is the queue's. + unsafe { + let go = || own!(this, ID3D12CommandQueue_Vtbl.ExecuteCommandLists)(this, n, lists); + let Some(r) = recorder().filter(|_| !ours()) else { + return go(); + }; + let kind = hook::state::(this).kind; + if kind != D3D12_COMMAND_LIST_TYPE_DIRECT.0 { + snap::other_queue(r, n); + return go(); + } + let all = std::slice::from_raw_parts(lists, n as usize); + snap::submit(r, &borrow::(this), all, go); + } +} + +/// A list's recorder and state, for a call of the host layer's. +unsafe fn of(this: Ptr) -> Option<(&'static Recorder, &'static ListState)> { + let r = recorder()?; + if ours() { + return None; + } + // SAFETY: a list with a shim; its state is a list's. + Some((r, unsafe { hook::state::(this) })) +} + +/// Records a command, if lists are recorded now. +unsafe fn note(this: Ptr, cmd: impl FnOnce(&Recorder) -> Cmd) { + // SAFETY: a list with a shim. + if let Some((r, state)) = unsafe { of(this) } + && r.armed.load(Ordering::Relaxed) + { + state.push(&cmd(r)); + } +} + +unsafe extern "system" fn list_close(this: Ptr) -> HRESULT { + // SAFETY: as above. + unsafe { + let hr = own!(this, ID3D12GraphicsCommandList_Vtbl.Close)(this); + if let Some((_, state)) = of(this) { + let mut inner = lock(&state.inner); + let bytes = std::mem::take(&mut inner.bytes); + let changes = Arc::new(std::mem::take(&mut inner.changes)); + inner.closed = Some((inner.whole.then(|| Arc::new(bytes)), changes)); + } + hr + } +} + +unsafe extern "system" fn list_reset(this: Ptr, allocator: Ptr, pso: Ptr) -> HRESULT { + // SAFETY: as above. + unsafe { + let table = hook::table(this); + let hr = own!(this, ID3D12GraphicsCommandList_Vtbl.Reset)(this, allocator, pso); + // A reset sets the list's table pointer anew. + hook::again(this, table, list_table); + if let Some((r, state)) = of(this) + && hr.is_ok() + { + let mut inner = lock(&state.inner); + inner.closed = None; + inner.whole = r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; + begin(&mut inner, r, pso); + } + hr + } +} + +unsafe extern "system" fn draw(this: Ptr, vertices: u32, instances: u32, first: u32, first_instance: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)(this, vertices, instances, first, first_instance); + note(this, |_| Cmd::Draw { vertices, instances, first, first_instance }); + } +} + +unsafe extern "system" fn draw_indexed(this: Ptr, indices: u32, instances: u32, first: u32, base: i32, first_instance: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)(this, indices, instances, first, base, first_instance); + note(this, |_| Cmd::DrawIndexed { indices, instances, first, base, first_instance }); + } +} + +unsafe extern "system" fn dispatch(this: Ptr, x: u32, y: u32, z: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.Dispatch)(this, x, y, z); + note(this, |_| Cmd::Dispatch { groups: [x, y, z] }); + } +} + +unsafe extern "system" fn dispatch_mesh(this: Ptr, x: u32, y: u32, z: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh)(this, x, y, z); + note(this, |_| Cmd::DispatchMesh { groups: [x, y, z] }); + } +} + +unsafe extern "system" fn copy_buffer(this: Ptr, dst: Ptr, dst_at: u64, src: Ptr, src_at: u64, len: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)(this, dst, dst_at, src, src_at, len); + note(this, |r| Cmd::CopyBuffer { dst: r.resource(dst), dst_at, src: r.resource(src), src_at, len }); + } +} + +unsafe fn location(r: &Recorder, l: &D3D12_TEXTURE_COPY_LOCATION) -> Loc { + // SAFETY: a copy's valid location. + unsafe { + let res = r.resource(std::mem::transmute_copy::<_, Ptr>(&l.pResource)); + if l.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { + return Loc::Sub { res, sub: l.Anonymous.SubresourceIndex }; + } + let p = l.Anonymous.PlacedFootprint; + let f = p.Footprint; + Loc::Placed { res, offset: p.Offset, format: f.Format.0, size: [f.Width, f.Height, f.Depth], pitch: f.RowPitch } + } +} + +/// A command that changes states whether lists are recorded or not. +unsafe fn note_change(this: Ptr, cmd: impl FnOnce(&Recorder) -> Cmd) { + // SAFETY: a list with a shim. + if let Some((r, state)) = unsafe { of(this) } { + let cmd = cmd(r); + let mut inner = lock(&state.inner); + states::changes(&cmd, &mut inner.changes); + if inner.whole { + cmd.put(&mut inner.bytes); + } + } +} + +unsafe extern "system" fn copy_texture( + this: Ptr, + dst: *const D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: *const D3D12_TEXTURE_COPY_LOCATION, + part: *const D3D12_BOX, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion)(this, dst, x, y, z, src, part); + note_change(this, |r| Cmd::CopyTexture { + dst: location(r, &*dst), + at: [x, y, z], + src: location(r, &*src), + part: part.as_ref().map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), + }); + } +} + +unsafe extern "system" fn copy_resource(this: Ptr, dst: Ptr, src: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyResource)(this, dst, src); + note_change(this, |r| Cmd::CopyResource { dst: r.resource(dst), src: r.resource(src) }); + } +} + +unsafe extern "system" fn resolve(this: Ptr, dst: Ptr, dst_sub: u32, src: Ptr, src_sub: u32, format: DXGI_FORMAT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)(this, dst, dst_sub, src, src_sub, format); + note(this, |r| Cmd::Resolve { dst: r.resource(dst), dst_sub, src: r.resource(src), src_sub, format: format.0 }); + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn resolve_region( + this: Ptr, + dst: Ptr, + dst_sub: u32, + x: u32, + y: u32, + src: Ptr, + src_sub: u32, + part: *const RECT, + format: DXGI_FORMAT, + mode: D3D12_RESOLVE_MODE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion)(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); + note(this, |r| Cmd::ResolveRegion { + dst: r.resource(dst), + dst_sub, + at: [x, y], + src: r.resource(src), + src_sub, + part: part.as_ref().map(rect), + format: format.0, + mode: mode.0, + }); + } +} + +fn rect(r: &RECT) -> [i32; 4] { + [r.left, r.top, r.right, r.bottom] +} + +unsafe fn rects(n: u32, all: *const RECT) -> Vec<[i32; 4]> { + if all.is_null() || n == 0 { + return Vec::new(); + } + // SAFETY: `n` rectangles. + unsafe { std::slice::from_raw_parts(all, n as usize) }.iter().map(rect).collect() +} + +unsafe extern "system" fn topology(this: Ptr, kind: D3D_PRIMITIVE_TOPOLOGY) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology)(this, kind); + note(this, |_| Cmd::Topology { kind: kind.0 }); + } +} + +unsafe extern "system" fn viewports(this: Ptr, n: u32, all: *const D3D12_VIEWPORT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetViewports)(this, n, all); + note(this, |_| Cmd::Viewports { all: (0..n as usize).map(|i| all.add(i).cast::<[f32; 6]>().read()).collect() }); + } +} + +unsafe extern "system" fn scissors(this: Ptr, n: u32, all: *const RECT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects)(this, n, all); + note(this, |_| Cmd::Scissors { all: rects(n, all) }); + } +} + +unsafe extern "system" fn blend_factor(this: Ptr, factor: *const f32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor)(this, factor); + note(this, |_| Cmd::BlendFactor { factor: factor.cast::<[f32; 4]>().as_ref().copied() }); + } +} + +unsafe extern "system" fn stencil_ref(this: Ptr, value: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef)(this, value); + note(this, |_| Cmd::StencilRef { value }); + } +} + +unsafe extern "system" fn depth_bounds(this: Ptr, min: f32, max: f32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds)(this, min, max); + note(this, |_| Cmd::DepthBounds { min, max }); + } +} + +unsafe extern "system" fn set_pipeline(this: Ptr, pso: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetPipelineState)(this, pso); + note(this, |r| Cmd::Pipeline { pso: r.object(pso, "a pipeline") }); + } +} + +unsafe extern "system" fn barrier(this: Ptr, n: u32, all: *const D3D12_RESOURCE_BARRIER) { + // SAFETY: as above; a barrier's type says which of its parts holds. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier)(this, n, all); + note_change(this, |r| { + let all = std::slice::from_raw_parts(all, n as usize) + .iter() + .map(|b| match b.Type { + D3D12_RESOURCE_BARRIER_TYPE_ALIASING => { + let a = &b.Anonymous.Aliasing; + Barrier::Alias { + flags: b.Flags.0, + before: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), + after: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), + } + } + D3D12_RESOURCE_BARRIER_TYPE_UAV => { + Barrier::Uav { flags: b.Flags.0, res: r.resource(std::mem::transmute_copy::<_, Ptr>(&b.Anonymous.UAV.pResource)) } + } + _ => { + let t = &b.Anonymous.Transition; + Barrier::Transition { + flags: b.Flags.0, + res: r.resource(std::mem::transmute_copy::<_, Ptr>(&t.pResource)), + sub: t.Subresource, + before: t.StateBefore.0, + after: t.StateAfter.0, + } + } + }) + .collect(); + Cmd::Barriers { all } + }); + } +} + +unsafe extern "system" fn set_heaps(this: Ptr, n: u32, all: *const Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps)(this, n, all); + note(this, |r| Cmd::Heaps { heaps: (0..n as usize).map(|i| r.object(*all.add(i), "a descriptor heap")).collect() }); + } +} + +unsafe extern "system" fn root_compute(this: Ptr, root: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature)(this, root); + note(this, |r| Cmd::RootSignature { graphics: false, root: r.object(root, "a root signature") }); + } +} + +unsafe extern "system" fn root_graphics(this: Ptr, root: Ptr) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature)(this, root); + note(this, |r| Cmd::RootSignature { graphics: true, root: r.object(root, "a root signature") }); + } +} + +fn table(r: &Recorder, graphics: bool, param: u32, at: u64) -> Cmd { + let (heap, slot) = match read(&r.descriptors).gpu(at) { + Some((h, i)) => (h.id, i), + None => (NONE, 0), + }; + if heap == NONE { + r.problem("a descriptor table in no heap seen made"); + } + Cmd::Table { graphics, param, heap, slot } +} + +unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable)(this, param, at); + note(this, |r| table(r, false, param, at.ptr)); + } +} + +unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable)(this, param, at); + note(this, |r| table(r, true, param, at.ptr)); + } +} + +unsafe extern "system" fn constant_compute(this: Ptr, param: u32, value: u32, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant)(this, param, value, offset); + note(this, |_| Cmd::Constants { graphics: false, param, offset, values: vec![value] }); + } +} + +unsafe extern "system" fn constant_graphics(this: Ptr, param: u32, value: u32, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant)(this, param, value, offset); + note(this, |_| Cmd::Constants { graphics: true, param, offset, values: vec![value] }); + } +} + +unsafe fn values(n: u32, data: *const c_void) -> Vec { + // SAFETY: `n` values, of any alignment. + (0..n as usize).map(|i| unsafe { data.cast::().add(i).read_unaligned() }).collect() +} + +unsafe extern "system" fn constants_compute(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants)(this, param, n, data, offset); + note(this, |_| Cmd::Constants { graphics: false, param, offset, values: values(n, data) }); + } +} + +unsafe extern "system" fn constants_graphics(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants)(this, param, n, data, offset); + note(this, |_| Cmd::Constants { graphics: true, param, offset, values: values(n, data) }); + } +} + +/// A root view's address, reported if it lies in no buffer. +fn address(r: &Recorder, at: u64) -> Va { + let va = r.va(at); + if matches!(va, Va::Unknown { .. }) { + r.problem("a GPU address in no buffer seen made"); + } + va +} + +macro_rules! root_views { + ($($name:ident, $method:ident, $graphics:literal, $kind:ident;)*) => {$( + unsafe extern "system" fn $name(this: Ptr, param: u32, at: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.$method)(this, param, at); + note(this, |r| Cmd::RootView { graphics: $graphics, kind: slot::$kind, param, va: address(r, at) }); + } + } + )*}; +} +root_views! { + cbv_compute, SetComputeRootConstantBufferView, false, CBV; + cbv_graphics, SetGraphicsRootConstantBufferView, true, CBV; + srv_compute, SetComputeRootShaderResourceView, false, SRV; + srv_graphics, SetGraphicsRootShaderResourceView, true, SRV; + uav_compute, SetComputeRootUnorderedAccessView, false, UAV; + uav_graphics, SetGraphicsRootUnorderedAccessView, true, UAV; +} + +unsafe extern "system" fn index_buffer(this: Ptr, view: *const D3D12_INDEX_BUFFER_VIEW) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer)(this, view); + note(this, |r| Cmd::IndexBuffer { view: view.as_ref().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)) }); + } +} + +unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: *const D3D12_VERTEX_BUFFER_VIEW) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers)(this, start, n, views); + note(this, |r| Cmd::VertexBuffers { + start, + count: n, + views: (!views.is_null()).then(|| { + let all = std::slice::from_raw_parts(views, n as usize); + all.iter().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)).collect() + }), + }); + } +} + +unsafe extern "system" fn targets( + this: Ptr, + n: u32, + colors: *const D3D12_CPU_DESCRIPTOR_HANDLE, + range: BOOL, + depth: *const D3D12_CPU_DESCRIPTOR_HANDLE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)(this, n, colors, range, depth); + note(this, |r| { + let colors = (0..n as usize) + .map(|i| { + if !range.as_bool() { + return r.view((*colors.add(i)).ptr); + } + let all = read(&r.descriptors); + all.cpu((*colors).ptr).map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) + }) + .collect(); + Cmd::Targets { colors, depth: depth.as_ref().map(|d| r.view(d.ptr)) } + }); + } +} + +#[allow(clippy::too_many_arguments)] +unsafe extern "system" fn clear_depth( + this: Ptr, + view: D3D12_CPU_DESCRIPTOR_HANDLE, + flags: D3D12_CLEAR_FLAGS, + depth: f32, + stencil: u8, + n: u32, + all: *const RECT, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)(this, view, flags, depth, stencil, n, all); + note(this, |r| Cmd::ClearDepth { view: r.view(view.ptr), flags: flags.0, depth, stencil, rects: rects(n, all) }); + } +} + +unsafe extern "system" fn clear_target(this: Ptr, view: D3D12_CPU_DESCRIPTOR_HANDLE, color: *const f32, n: u32, all: *const RECT) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView)(this, view, color, n, all); + note(this, |r| Cmd::ClearTarget { view: r.view(view.ptr), color: color.cast::<[f32; 4]>().read(), rects: rects(n, all) }); + } +} + +unsafe extern "system" fn discard(this: Ptr, res: Ptr, region: *const D3D12_DISCARD_REGION) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.DiscardResource)(this, res, region); + note(this, |r| Cmd::Discard { + res: r.resource(res), + rects: region.as_ref().map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), + subs: region.as_ref().map(|d| [d.FirstSubresource, d.NumSubresources]), + }); + } +} + +unsafe extern "system" fn begin_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, index: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.BeginQuery)(this, heap, kind, index); + note(this, |r| Cmd::BeginQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + } +} + +unsafe extern "system" fn end_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, index: u32) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.EndQuery)(this, heap, kind, index); + note(this, |r| Cmd::EndQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + } +} + +unsafe extern "system" fn resolve_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, first: u32, count: u32, dst: Ptr, at: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)(this, heap, kind, first, count, dst, at); + note(this, |r| Cmd::ResolveQuery { heap: r.object(heap, "a query heap"), kind: kind.0, first, count, dst: r.resource(dst), at }); + } +} + +unsafe extern "system" fn indirect(this: Ptr, signature: Ptr, most: u32, args: Ptr, at: u64, count: Ptr, count_at: u64) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)(this, signature, most, args, at, count, count_at); + note(this, |r| Cmd::Indirect { + signature: r.object(signature, "a command signature"), + most, + args: r.resource(args), + at, + count: r.resource(count), + count_at, + }); + } +} + +unsafe extern "system" fn write_immediate( + this: Ptr, + n: u32, + all: *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, + modes: *const D3D12_WRITEBUFFERIMMEDIATE_MODE, +) { + // SAFETY: as above. + unsafe { + own!(this, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate)(this, n, all, modes); + note(this, |r| Cmd::WriteImmediate { + all: (0..n as usize) + .map(|i| { + let p = all.add(i).read(); + let mode = if modes.is_null() { 0 } else { modes.add(i).read().0 }; + (address(r, p.Dest), p.Value, mode) + }) + .collect(), + }); + } +} + +/// The first subresources of all: what [`ALL`] means in a barrier. +const _: () = assert!(ALL == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn when_to_record() { + assert_eq!(parse_at("120"), At::Seconds(120.0)); + assert_eq!(parse_at(" 1.5 "), At::Seconds(1.5)); + assert_eq!(parse_at("f900"), At::Frame(900)); + assert_eq!(parse_at(""), At::Trigger); + assert_eq!(parse_at("later"), At::Trigger); + } + + #[test] + fn descriptor_heaps_are_found_by_address() { + let heap = |id, cpu, gpu, count| { + let d = D3D12_DESCRIPTOR_HEAP_DESC { + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }; + Arc::new(Heap::new(id, &d, cpu, gpu, 32)) + }; + let mut all = Heaps::default(); + all.add(heap(1, 0x1000, 0x10_0000, 4)); + all.add(heap(2, 0x2000, 0x20_0000, 8)); + let at = |all: &Heaps, p| all.cpu(p).map(|(h, i)| (h.id, i)); + assert_eq!(at(&all, 0x1000), Some((1, 0))); + assert_eq!(at(&all, 0x1060), Some((1, 3))); + assert_eq!(at(&all, 0x1080), None, "past its end"); + assert_eq!(at(&all, 0xfff), None); + assert_eq!(all.gpu(0x20_0040).map(|(h, i)| (h.id, i)), Some((2, 2))); + // A heap made where a dead one was takes its place. + all.add(heap(3, 0x1020, 0x30_0000, 4)); + assert_eq!(at(&all, 0x1000), None); + assert_eq!(at(&all, 0x1020), Some((3, 0))); + all.remove(2); + assert_eq!(at(&all, 0x2000), None); + let h = heap(4, 0, 0, 2); + let s = Slot { kind: slot::SRV, res: 5, ..Slot::EMPTY }; + h.set(1, &s); + h.set(2, &s); + assert_eq!(h.all(), [Slot::EMPTY, s]); + assert_eq!(h.get(9), Slot::EMPTY); + } +} diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs new file mode 100644 index 0000000..b5f7005 --- /dev/null +++ b/crates/victory-gpu/src/replay/snap.rs @@ -0,0 +1,923 @@ +//! One frame written down: what its submissions run, what the card's +//! memory held at its start, and what the CPU put into memory both see +//! before each submission. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fs::File; +use std::os::windows::fs::FileExt; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::time::Instant; + +use windows::Win32::Graphics::Direct3D12::*; +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}; + +type Fault = Box; + +/// A read-back buffer contents go through, and how many there are. +const STAGING: u64 = 256 << 20; +const STAGINGS: usize = 4; +/// The most of a buffer in one piece. +const PIECE: u64 = 32 << 20; +/// What the CPU changes is kept in units of. +const PAGE: usize = 4096; +/// What one thread compares at a time. +const CHUNK: usize = 1 << 20; +/// Frames waited, at the most, for one whose lists are all recorded. +const PATIENCE: u64 = 300; + +#[derive(Default)] +enum Stage { + #[default] + Waiting, + /// Lists are recorded, since this many presents. + Armed(u64), + Capturing(Box), + Done, +} + +/// Where the recorder is. +#[derive(Default)] +pub(super) struct Phase { + presents: u64, + stage: Stage, + /// Submissions of this frame so far, and lists among them that were not + /// recorded. + submits: u32, + missing: u32, +} + +impl Phase { + pub(super) fn done(&self) -> bool { + matches!(self.stage, Stage::Done) + } +} + +/// A submission to a queue other than the drawing one: left out. +pub(super) fn other_queue(r: &Recorder, lists: u32) { + if r.watching.load(Ordering::SeqCst) { + r.problem_times("lists sent to a queue other than the drawing one are not in the capture", u64::from(lists)); + } +} + +/// A submission to the drawing queue, made by `go`. +pub(super) fn submit(r: &Recorder, queue: &ID3D12CommandQueue, lists: &[*mut std::ffi::c_void], go: impl FnOnce()) { + let mut phase = lock(&r.submits); + type Closed = (Option>>, Arc>); + let closed: Vec> = lists.iter().map(|&p| r.list(p).and_then(|l| l.closed())).collect(); + phase.submits += 1; + phase.missing += closed.iter().filter(|c| c.as_ref().is_none_or(|c| c.0.is_none())).count() as u32; + if let Stage::Capturing(c) = &mut phase.stage { + let commands: Vec>>> = closed.iter().map(|c| c.as_ref().and_then(|c| c.0.clone())).collect(); + let _ours = Ours::new(); + if let Err(e) = c.submit(r, queue, &commands) { + stop(r, &mut phase, &*e); + } + } + go(); + let mut states = lock(&r.states); + for change in closed.iter().flatten().flat_map(|c| c.1.iter()) { + states.change(change); + } + states.decay(); +} + +/// The capture failed. +fn stop(r: &Recorder, phase: &mut Phase, e: &(dyn std::error::Error + Send + Sync)) { + tracing::error!("frame recorder: the capture failed: {e}"); + let _ = std::fs::write(r.folder.join("failed.txt"), e.to_string()); + phase.stage = Stage::Done; + r.watching.store(false, Ordering::SeqCst); + r.arm(false); + lock(&r.held).clear(); +} + +pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { + let mut phase = lock(&r.submits); + phase.presents += 1; + let presents = phase.presents; + let (submits, missing) = (std::mem::take(&mut phase.submits), std::mem::take(&mut phase.missing)); + let mut finished = None; + match &mut phase.stage { + Stage::Waiting => { + let due = match r.settings.at { + At::Seconds(s) => r.began.elapsed().as_secs_f64() >= s, + At::Frame(f) => presents >= f, + At::Trigger => false, + }; + if due || r.settings.folder.join("go").exists() { + tracing::info!(presents, "frame recorder: lists are recorded from now on"); + r.arm(true); + phase.stage = Stage::Armed(presents); + } + } + Stage::Armed(since) => { + let waited = presents - *since; + let whole = submits > 0 && missing == 0; + if waited >= 2 && (whole || waited > PATIENCE) { + if !whole { + r.problem("no frame was found whose lists were all recorded"); + } + tracing::info!(presents, waited, "frame recorder: the next frame is captured"); + match Capture::new(r) { + Ok(c) => phase.stage = Stage::Capturing(Box::new(c)), + Err(e) => stop(r, &mut phase, &*e), + } + } + } + Stage::Capturing(c) if c.started => { + let _ours = Ours::new(); + let done = c.present(r, texture, state).and_then(|()| { + if c.frame < r.settings.frames { + return Ok(false); + } + c.finish(r)?; + Ok(true) + }); + match done { + Ok(false) => {} + Ok(true) => { + r.watching.store(false, Ordering::SeqCst); + r.arm(false); + if let Stage::Capturing(c) = std::mem::replace(&mut phase.stage, Stage::Done) { + finished = Some((c, std::mem::take(&mut *lock(&r.held)))); + } + } + Err(e) => stop(r, &mut phase, &*e), + } + } + // A frame without a submission: the next one. + Stage::Capturing(_) | Stage::Done => {} + } + drop(phase); + // What was kept alive goes without a lock held. + drop(finished); +} + +/// A buffer the CPU sees. +struct CpuBuffer { + id: u32, + res: 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 + /// read. + through: Option<(usize, u64)>, + size: usize, + /// What it held at the submission before (zeros before the first). + kept: Vec, +} + +// SAFETY: the mapping is of a buffer the struct holds. +unsafe impl Send for CpuBuffer {} +// SAFETY: as above; the mapping is only read. +unsafe impl Sync for CpuBuffer {} + +struct Capture { + worker: Worker, + others: Vec, + /// Resources the frame can use, kept alive. + held: Vec, + started: bool, + frame: u32, + states: States, + idle: HashSet, + heaps: Vec<(Arc, Vec<(u32, u32, Slot)>)>, + contents: Vec, + buffers: Vec, + known: HashSet, + /// 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)>, + deltas: File, + delta_at: AtomicU64, + lists: Vec>>, + submits: Vec, + presents: Vec, + present_file: File, + present_at: u64, + calls: Vec<(String, u64)>, + began: Instant, + took: BTreeMap<&'static str, std::time::Duration>, +} + +impl Capture { + fn new(r: &Recorder) -> Result { + let _ours = Ours::new(); + let device = r.device().ok_or("no device")?; + let queues = lock(&r.queues).clone(); + let direct = queues.iter().find(|q| q.1 == D3D12_COMMAND_LIST_TYPE_DIRECT.0).ok_or("no drawing queue")?; + let mut others = Vec::new(); + for (queue, _) in queues.iter().filter(|q| q.0 != direct.0) { + others.push(Worker::new(&device, queue)?); + } + Ok(Capture { + worker: Worker::new(&device, &direct.0)?, + others, + held: Vec::new(), + started: false, + frame: 0, + states: States::default(), + idle: HashSet::new(), + heaps: Vec::new(), + contents: Vec::new(), + buffers: Vec::new(), + known: HashSet::new(), + blocks: Vec::new(), + deltas: File::create(r.folder.join("deltas.bin"))?, + delta_at: AtomicU64::new(0), + lists: Vec::new(), + submits: Vec::new(), + presents: Vec::new(), + present_file: File::create(r.folder.join("present.bin"))?, + present_at: 0, + calls: not_recorded_calls(), + began: Instant::now(), + took: BTreeMap::new(), + }) + } + + fn timed(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let began = Instant::now(); + let out = f(self); + *self.took.entry(what).or_default() += began.elapsed(); + out + } + + /// Before the first submission of the frame: what the card holds. + fn start(&mut self, r: &Recorder) -> Result<(), Fault> { + self.began = Instant::now(); + r.watching.store(true, Ordering::SeqCst); + self.started = true; + self.worker.idle()?; + for w in &mut self.others { + w.idle()?; + } + let mut all: Vec> = Vec::new(); + { + let live = read(&r.resources); + for res in live.values() { + let object = res.object(); + // SAFETY: a live resource, or one whose end waits for the + // lock held here (`Recorder::gone`): the count tells which. + let count = unsafe { (Interface::vtable(&*object).base__.base__.base__.base__.AddRef)(object.as_raw()) }; + if count <= 1 { + // Dying: the reference does not bring it back, and + // 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()) }); + all.push(res.clone()); + } + } + all.sort_by_key(|res| res.id); + self.states = lock(&r.states).clone(); + self.idle = self.find_idle(&all); + self.timed("contents of the card's memory", |c| c.snapshot(r, &all))?; + Ok(()) + } + + /// Of placed resources that overlap, those that are not the one used + /// last. + fn find_idle(&self, all: &[Arc]) -> HashSet { + let mut heaps: HashMap> = HashMap::new(); + for res in all { + if let Place::Placed { heap, offset } = res.place { + // SAFETY: a plain query. + let info = unsafe { self.worker.device.GetResourceAllocationInfo(0, &[gpu::to_desc(&res.desc)]) }; + let size = if info.SizeInBytes == u64::MAX { res.desc.width } else { info.SizeInBytes }; + let used = self.states.used.get(&res.id).copied().unwrap_or(0); + heaps.entry(heap).or_default().push((used, offset, offset + size, res.id)); + } + } + let mut idle = HashSet::new(); + for (_, mut list) in heaps { + list.sort_by(|a, b| b.cmp(a)); + let mut taken: BTreeMap = BTreeMap::new(); + for (_, from, to, id) in list { + let overlaps = taken.range(..to).next_back().is_some_and(|(_, &end)| end > from); + if overlaps { + idle.insert(id); + } else { + taken.insert(from, to); + } + } + } + idle + } + + fn snapshot(&mut self, r: &Recorder, all: &[Arc]) -> Result<(), Fault> { + let device = self.worker.device.clone(); + let mut pieces: Vec = Vec::new(); + for res in all.iter().filter(|res| res.seen == Seen::No) { + if matches!(res.place, Place::BackBuffer {}) || self.idle.contains(&res.id) { + continue; + } + if res.is_buffer() { + let mut at = 0; + while at < res.desc.width { + let len = PIECE.min(res.desc.width - at); + pieces.push(Piece { res: res.clone(), first: at, count: 1, len, at: 0 }); + at += len; + } + continue; + } + if res.desc.samples[0] > 1 { + r.problem("contents of multisampled textures are not in the capture"); + continue; + } + let desc = gpu::to_desc(&res.desc); + let (_, total) = gpu::footprints(&device, &desc, 0, res.subs); + if total == u64::MAX { + r.problem("contents of a texture without a copyable layout are not in the capture"); + } else if total <= STAGING { + pieces.push(Piece { res: res.clone(), first: 0, count: res.subs, len: total, at: 0 }); + } else { + for sub in 0..res.subs { + let (_, len) = gpu::footprints(&device, &desc, sub, 1); + if len <= STAGING { + pieces.push(Piece { res: res.clone(), first: u64::from(sub), count: 1, len, at: 0 }); + } else { + r.problem("contents of a texture level of over 256 MB are not in the capture"); + } + } + } + } + // Into batches, one read-back buffer each. + let mut batches: Vec> = vec![Vec::new()]; + let mut at = 0u64; + for mut p in pieces { + at = at.next_multiple_of(512); + if at + p.len > STAGING { + batches.push(Vec::new()); + at = 0; + } + p.at = at; + at += p.len; + if let Some(b) = batches.last_mut() { + b.push(p); + } + } + let mut stagings = Vec::new(); + for _ in 0..STAGINGS.min(batches.len()) { + stagings.push(gpu::buffer(&device, D3D12_HEAP_TYPE_READBACK, STAGING, D3D12_RESOURCE_FLAG_NONE)?); + } + let file = File::create(r.folder.join("contents.bin"))?; + let end = AtomicU64::new(0); + let contents: std::sync::Mutex> = std::sync::Mutex::default(); + let failed: std::sync::Mutex> = std::sync::Mutex::default(); + let (todo, work) = std::sync::mpsc::channel::<(usize, Vec)>(); + let work = std::sync::Mutex::new(work); + let (free, freed) = std::sync::mpsc::channel::(); + for i in 0..stagings.len() { + free.send(i)?; + } + let maps: Vec = stagings.iter().map(|s| s.1 as usize).collect(); + std::thread::scope(|scope| -> Result<(), Fault> { + for _ in 0..stagings.len() { + let (work, free, maps, file, end, contents, failed) = (&work, free.clone(), &maps, &file, &end, &contents, &failed); + scope.spawn(move || { + loop { + let next = lock(work).recv(); + let Ok((i, pieces)) = next else { break }; + for p in pieces { + // SAFETY: inside the buffer's mapping; the copy + // into it has run. + let bytes = unsafe { std::slice::from_raw_parts((maps[i] + p.at as usize) as *const u8, p.len as usize) }; + let at = if zero(bytes) { ZERO } else { end.fetch_add(p.len, Ordering::Relaxed) }; + if at != ZERO + && let Err(e) = write_at(file, bytes, at) + { + lock(failed).get_or_insert(e); + } + lock(contents).push(Content { res: p.res.id, first: p.first, count: p.count, len: p.len, file: at }); + } + let _ = free.send(i); + } + }); + } + // Moved in: the writers end when it goes. + let todo = todo; + for pieces in batches { + if pieces.is_empty() { + continue; + } + let i = freed.recv()?; + let value = self.worker.send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?; + self.worker.wait(value)?; + todo.send((i, pieces))?; + } + Ok(()) + })?; + if let Some(e) = lock(&failed).take() { + return Err(e.into()); + } + self.contents = contents.into_inner().unwrap_or_else(|e| e.into_inner()); + Ok(()) + } + + /// Buffers the CPU sees that were not known yet. + fn new_buffers(&mut self, r: &Recorder) -> Result<(), Fault> { + let fresh: Vec> = read(&r.resources) + .values() + .filter(|res| matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id)) + .cloned() + .collect(); + for res in fresh { + self.known.insert(res.id); + if !res.is_buffer() { + 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()); + let size = res.desc.width as usize; + let (live, through) = if res.seen == Seen::Cached { + let mut data = std::ptr::null_mut(); + // SAFETY: a live buffer in memory the CPU sees. + unsafe { object.Map(0, None, Some(&mut data))? }; + (data.cast::().cast_const(), None) + } else { + let room = self.blocks.iter().position(|b| b.3 + size as u64 <= b.2); + let i = match room { + Some(i) => i, + None => { + let len = STAGING.max(size as u64); + let (b, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + self.blocks.push((b, data as usize, len, 0)); + self.blocks.len() - 1 + } + }; + let b = &mut self.blocks[i]; + let at = b.3; + b.3 = (at + size as u64).next_multiple_of(256); + ((b.1 + at as usize) as *const u8, Some((i, at))) + }; + self.buffers.push(CpuBuffer { id: res.id, res: object, live, through, size, kept: vec![0; size] }); + } + Ok(()) + } + + /// What changed in buffers the CPU sees since the submission before. + fn changed(&mut self, r: &Recorder) -> Result, Fault> { + self.new_buffers(r)?; + if self.buffers.iter().any(|b| b.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 { + // SAFETY: an open list and live buffers. + unsafe { list.CopyBufferRegion(&blocks[i].0, at, &b.res, 0, b.size 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(); + // 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. + unsafe impl Sync for Kept {} + let kept: Vec = self.buffers.iter_mut().map(|b| Kept(b.kept.as_mut_ptr())).collect(); + let next = AtomicUsize::new(0); + let out: std::sync::Mutex> = std::sync::Mutex::default(); + let failed: std::sync::Mutex> = std::sync::Mutex::default(); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).clamp(1, 16).min(chunks.len().max(1)); + let (buffers, file, end) = (&self.buffers, &self.deltas, &self.delta_at); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + 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); + // 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. + let runs = unsafe { changed_runs(buffers[b].live.add(at), kept[b].0.add(at), len) }; + for (from, to) in runs { + // SAFETY: as above. + let bytes = unsafe { std::slice::from_raw_parts(kept[b].0.add(at + from), to - from) }; + let file_at = end.fetch_add(bytes.len() as u64, Ordering::Relaxed); + if let Err(e) = write_at(file, bytes, file_at) { + lock(&failed).get_or_insert(e); + } + mine.push(Delta { res: buffers[b].id, at: (at + from) as u64, len: bytes.len() as u64, file: file_at }); + } + } + lock(&out).extend(mine); + }); + } + }); + if let Some(e) = lock(&failed).take() { + return Err(e.into()); + } + let mut out = out.into_inner().unwrap_or_else(|e| e.into_inner()); + out.sort_by_key(|d| (d.res, d.at)); + Ok(out) + } + + fn submit(&mut self, r: &Recorder, _queue: &ID3D12CommandQueue, lists: &[Option>>]) -> Result<(), Fault> { + let first = !self.started; + if first { + self.start(r)?; + } 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. + let mut written = std::mem::take(&mut *lock(&r.writes)); + let mut views = Vec::new(); + if first { + let heaps: Vec> = read(&r.descriptors).visible().cloned().collect(); + for h in heaps { + let runs = runs_of(r, &h.all()); + self.heaps.push((h, runs)); + } + } else { + written.sort_unstable(); + let mut seen = HashSet::new(); + for (heap, at, n) in written { + let h = match self.heaps.iter().find(|(h, _)| h.id == heap) { + Some((h, _)) => h.clone(), + None => { + let found = read(&r.descriptors).visible().find(|h| h.id == heap).cloned(); + let Some(h) = found else { continue }; + self.heaps.push((h.clone(), Vec::new())); + h + } + }; + for i in at..at + n { + if seen.insert((heap, i)) { + views.push((heap, i, resolved(r, h.get(i)))); + } + } + } + } + let mut numbers = Vec::new(); + for l in lists { + numbers.push(match l { + None => { + r.problem("a list was submitted that was not recorded whole: its work is missing"); + MISSING + } + Some(commands) => match self.lists.iter().position(|have| Arc::ptr_eq(have, commands)) { + Some(i) => i as u32, + None => { + self.lists.push(commands.clone()); + self.lists.len() as u32 - 1 + } + }, + }); + } + self.submits.push(wire::Submit { frame: self.frame, lists: numbers, deltas, views }); + Ok(()) + } + + fn present(&mut self, r: &Recorder, texture: &ID3D12Resource, state: u32) -> Result<(), Fault> { + self.worker.idle()?; + // SAFETY: a live texture. + let desc = unsafe { texture.GetDesc() }; + let (f, total) = gpu::footprints(&self.worker.device, &desc, 0, 1); + let (back, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; + self.worker.run(|list| read_sub(list, texture, 0, state, &back, f[0]))?; + // SAFETY: the buffer's mapping; the copy into it has run. + let bytes = unsafe { std::slice::from_raw_parts(data, total as usize) }; + write_at(&self.present_file, bytes, self.present_at)?; + let id = r.resource(texture.as_raw()); + let (width, height, pitch) = (desc.Width as u32, desc.Height, f[0].Footprint.RowPitch); + self.presents.push(wire::Present { + submits: self.submits.len() as u32, + res: id, + width, + height, + format: desc.Format.0, + pitch, + file: self.present_at, + }); + self.present_at += total; + match gpu::rgb(width, height, pitch, desc.Format.0, bytes) { + Some(rgb) => std::fs::write(r.folder.join(format!("frame-{}.png", self.frame)), crate::capture::png(width, height, &rgb))?, + None => r.problem("the presented format is not shown in a PNG"), + } + self.frame += 1; + Ok(()) + } + + /// Writes `frame.bin`. + fn finish(&mut self, r: &Recorder) -> Result<(), Fault> { + let mut resources: Vec = Vec::new(); + { + let names = lock(&r.names); + for res in read(&r.resources).values() { + let state = match (res.is_buffer(), res.late) { + (true, _) => vec![COMMON], + (_, true) => vec![res.made_in as u32], + _ => self.states.get(res.id).unwrap_or(vec![COMMON]), + }; + resources.push(wire::Resource { + id: res.id, + place: res.place.clone(), + desc: res.desc.clone(), + made_in: res.made_in, + clear: res.clear, + state, + idle: self.idle.contains(&res.id), + late: res.late, + name: names.get(&res.id).cloned().unwrap_or_default(), + }); + } + } + resources.sort_by_key(|res| res.id); + let mut heaps: Vec = { + let all = lock(&r.heaps); + let used: HashSet = + resources.iter().filter_map(|res| if let Place::Placed { heap, .. } = res.place { Some(heap) } else { None }).collect(); + used.iter().filter_map(|id| all.get(id).cloned()).collect() + }; + heaps.sort_by_key(|h| h.id); + // What the lists name. + let (mut psos, mut roots, mut signatures, mut queries) = (HashSet::new(), HashSet::new(), HashSet::new(), HashSet::new()); + for l in &self.lists { + for c in Cmd::all(l)? { + match c { + Cmd::Pipeline { pso } => drop(psos.insert(pso)), + Cmd::RootSignature { root, .. } => drop(roots.insert(root)), + Cmd::Indirect { signature, .. } => drop(signatures.insert(signature)), + Cmd::BeginQuery { heap, .. } | Cmd::EndQuery { heap, .. } | Cmd::ResolveQuery { heap, .. } => drop(queries.insert(heap)), + _ => {} + } + } + } + let pipelines: Vec = { + let all = lock(&r.pipelines); + let names = lock(&r.names); + let mut out: Vec = psos + .iter() + .filter_map(|id| { + let parts = all.get(id)?; + Some(wire::Pipeline { id: *id, parts: parts.to_vec(), name: names.get(id).cloned().unwrap_or_default() }) + }) + .collect(); + out.sort_by_key(|p| p.id); + out + }; + roots.extend(pipelines.iter().flat_map(|p| &p.parts).filter_map(|p| if let wire::Part::Root { root } = p { Some(*root) } else { None })); + let signatures: Vec = { + let all = lock(&r.signatures); + signatures.iter().filter_map(|id| all.get(id).cloned()).collect() + }; + roots.extend(signatures.iter().map(|s| s.root)); + roots.remove(&NONE); + let roots: Vec<(u32, wire::Blob)> = { + let all = lock(&r.roots); + roots.iter().filter_map(|id| Some((*id, wire::Blob(all.get(id)?.to_vec())))).collect() + }; + for ((what, before), (_, now)) in self.calls.iter().zip(not_recorded_calls()) { + if now > *before { + r.problem_times(what, now - before); + } + } + let (adapter, vendor, device) = gpu::adapter(&self.worker.device); + let mut notes = r.problems(); + let bytes: u64 = self.contents.iter().filter(|c| c.file != ZERO).map(|c| c.len).sum(); + notes.push(format!( + "{} submissions, {} lists, {} resources, {} pipelines; {} MB of the card's memory, {} MB of changes by the CPU; {:.1} s: {}", + self.submits.len(), + self.lists.len(), + resources.len(), + pipelines.len(), + bytes >> 20, + self.delta_at.load(Ordering::Relaxed) >> 20, + self.began.elapsed().as_secs_f64(), + self.took.iter().map(|(what, d)| format!("{what} {:.1} s", d.as_secs_f64())).collect::>().join(", ") + )); + for n in ¬es { + tracing::info!("frame recorder: {n}"); + } + let frame = wire::Frame { + adapter, + vendor, + device, + notes: notes.clone(), + heaps, + resources, + roots, + codes: lock(&r.codes).all.clone(), + pipelines, + signatures, + descriptor_heaps: self + .heaps + .iter() + .map(|(h, runs)| wire::DescriptorHeap { id: h.id, kind: h.kind, count: h.count, flags: h.flags, runs: runs.clone() }) + .collect(), + query_heaps: { + let all = lock(&r.queries); + queries.iter().filter_map(|id| all.get(id).cloned()).collect() + }, + lists: self + .lists + .iter() + .map(|l| wire::List { kind: D3D12_COMMAND_LIST_TYPE_DIRECT.0, commands: wire::Blob(l.to_vec()) }) + .collect(), + submits: std::mem::take(&mut self.submits), + contents: std::mem::take(&mut self.contents), + presents: std::mem::take(&mut self.presents), + }; + frame.write(&r.folder.join("frame.bin"))?; + std::fs::write(r.folder.join("notes.txt"), notes.join("\n"))?; + tracing::info!(folder = %r.folder.display(), "frame recorder: the frame is captured"); + Ok(()) + } +} + +/// A part of a resource in a read-back buffer, `at` bytes in. +struct Piece { + res: Arc, + first: u64, + count: u32, + len: u64, + at: u64, +} + +/// Records the copies of `pieces` into `to`. Textures are moved to a state +/// they can be copied from and back. +fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &States, pieces: &[Piece], to: &ID3D12Resource) { + let (mut before, mut after) = (Vec::new(), Vec::new()); + let mut seen = HashSet::new(); + for p in pieces.iter().filter(|p| !p.res.is_buffer()) { + if !seen.insert(p.res.id) { + continue; + } + let from = states.get(p.res.id).unwrap_or(vec![COMMON]); + // From the common state a texture is promoted by the copy. + let to: Vec = from.iter().map(|&s| if s == COMMON || s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + gpu::moves(&p.res.object(), &from, &to, &mut before); + gpu::moves(&p.res.object(), &to, &from, &mut after); + } + // SAFETY: an open list; live resources. + unsafe { + if !before.is_empty() { + list.ResourceBarrier(&before); + } + for p in pieces { + let object = p.res.object(); + if p.res.is_buffer() { + list.CopyBufferRegion(to, p.at, &*object, p.first, p.len); + continue; + } + let (all, _) = gpu::footprints(device, &gpu::to_desc(&p.res.desc), p.first as u32, p.count); + for (i, mut f) in all.into_iter().enumerate() { + f.Offset += p.at; + list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(&object, p.first as u32 + i as u32), None); + } + } + if !after.is_empty() { + list.ResourceBarrier(&after); + } + } +} + +/// Records the copy of a texture's subresource, in `state`, into `to`. +pub(super) fn read_sub( + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, + sub: u32, + state: u32, + to: &ID3D12Resource, + f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +) { + let there = state == COMMON || state & COPY_SOURCE != 0; + // SAFETY: an open list; live resources. + unsafe { + if !there { + list.ResourceBarrier(&[gpu::transition(texture, ALL, state, COPY_SOURCE)]); + } + list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(texture, sub), None); + if !there { + list.ResourceBarrier(&[gpu::transition(texture, ALL, COPY_SOURCE, state)]); + } + } +} + +/// 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 { + if s.kind == slot::CBV && s.described != 0 { + match r.va(s.address()) { + Va::At { res, offset } => { + s.res = res; + s.set_address(offset); + } + Va::Null {} => {} + Va::Unknown { .. } => { + // Its buffer is gone: nothing may read it. + s = Slot { kind: slot::CBV, ..Slot::EMPTY }; + } + } + } + s +} + +/// The slots as runs of equal ones, empty ones left out. +fn runs_of(r: &Recorder, all: &[Slot]) -> Vec<(u32, u32, Slot)> { + let mut runs: Vec<(u32, u32, Slot)> = Vec::new(); + for (i, s) in all.iter().enumerate() { + if s.kind == slot::EMPTY { + continue; + } + match runs.last_mut() { + Some((first, n, same)) if *first + *n == i as u32 && same == s => *n += 1, + _ => runs.push((i as u32, 1, *s)), + } + } + for run in &mut runs { + run.2 = resolved(r, run.2); + } + runs +} + +/// Whether all bytes are zero. +fn zero(bytes: &[u8]) -> bool { + // SAFETY: any bytes are a number. + let (a, b, c) = unsafe { bytes.align_to::() }; + a.iter().chain(c).all(|&x| x == 0) && b.iter().all(|&x| x == 0) +} + +fn write_at(file: &File, mut bytes: &[u8], mut at: u64) -> std::io::Result<()> { + while !bytes.is_empty() { + let n = file.seek_write(bytes, at)?; + if n == 0 { + return Err(std::io::ErrorKind::WriteZero.into()); + } + bytes = &bytes[n..]; + at += n as u64; + } + Ok(()) +} + +/// Compares `len` bytes at `live` with those at `kept`, page by page, brings +/// the changed ones in `kept` up to date, and answers their runs. +/// +/// # Safety +/// Both are `len` bytes; `kept` is the caller's alone. +unsafe fn changed_runs(live: *const u8, kept: *mut u8, len: usize) -> Vec<(usize, usize)> { + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut at = 0; + while at < len { + let n = PAGE.min(len - at); + // SAFETY: the caller's. + unsafe { + let same = std::slice::from_raw_parts(live.add(at), n) == std::slice::from_raw_parts(kept.add(at), n); + if !same { + std::ptr::copy_nonoverlapping(live.add(at), kept.add(at), n); + match runs.last_mut() { + Some(last) if last.1 == at => last.1 = at + n, + _ => runs.push((at, at + n)), + } + } + } + at += n; + } + runs +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn changes_are_found_by_page() { + let mut live = vec![0u8; 5 * PAGE + 100]; + let mut kept = live.clone(); + let find = |live: &[u8], kept: &mut [u8]| { + // SAFETY: two arrays of one length. + unsafe { changed_runs(live.as_ptr(), kept.as_mut_ptr(), live.len()) } + }; + assert!(find(&live, &mut kept).is_empty()); + live[PAGE + 5] = 1; + live[2 * PAGE] = 2; + live[5 * PAGE + 99] = 3; + assert_eq!(find(&live, &mut kept), [(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)]); + assert_eq!(live, kept); + assert!(find(&live, &mut kept).is_empty()); + } + + #[test] + fn zeros() { + assert!(zero(&[])); + assert!(zero(&[0; 1001])); + for i in [0, 7, 500, 1000] { + let mut b = [0u8; 1001]; + b[i] = 1; + assert!(!zero(&b)); + } + } +} diff --git a/crates/victory-gpu/src/replay/states.rs b/crates/victory-gpu/src/replay/states.rs new file mode 100644 index 0000000..c159423 --- /dev/null +++ b/crates/victory-gpu/src/replay/states.rs @@ -0,0 +1,192 @@ +//! The states textures are in, as lists that ran left them: from the +//! barriers, the copies that promote a texture out of the common state, and +//! the decay at the end of a submission. Buffers are in the common state +//! between submissions, always, and are not kept here. + +use std::collections::HashMap; + +use super::wire::{ALL, Barrier, Cmd, Loc}; + +pub const COMMON: u32 = 0; +pub const RENDER_TARGET: u32 = 0x4; +pub const UNORDERED_ACCESS: u32 = 0x8; +pub const DEPTH_WRITE: u32 = 0x10; +pub const COPY_DEST: u32 = 0x400; +pub const COPY_SOURCE: u32 = 0x800; +pub const RESOLVE_DEST: u32 = 0x1000; + +/// A change of state a list makes, to apply when it runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Change { + pub res: u32, + pub sub: u32, + pub after: u32, + /// A copy into it: it is in the copy-destination state afterwards if it + /// was in the common state, else as it was. + pub promoted: bool, + /// An aliasing barrier made it the one in use. + pub alias: bool, +} + +#[derive(Clone, Debug)] +struct One { + subs: u32, + /// Decays to the common state after each submission. + decays: bool, + all: u32, + each: Vec, +} + +/// The states of textures, by id. +#[derive(Clone, Debug, Default)] +pub struct States { + map: HashMap, + touched: Vec, + /// When a placed resource was last the one in use (made, or named by an + /// aliasing barrier), by id; higher is later. + pub used: HashMap, + clock: u64, +} + +impl States { + /// A texture of `subs` subresources starts in `state`. + pub fn add(&mut self, res: u32, subs: u32, state: u32, decays: bool) { + self.map.insert(res, One { subs: subs.max(1), decays, all: state, each: Vec::new() }); + } + + /// A placed resource is the one in use now. + pub fn in_use(&mut self, res: u32) { + self.clock += 1; + self.used.insert(res, self.clock); + } + + pub fn remove(&mut self, res: u32) { + self.map.remove(&res); + self.used.remove(&res); + } + + /// One state, or one for each subresource. + pub fn get(&self, res: u32) -> Option> { + let one = self.map.get(&res)?; + Some(if one.each.is_empty() { vec![one.all] } else { one.each.clone() }) + } + + pub fn change(&mut self, c: &Change) { + if c.alias { + self.in_use(c.res); + return; + } + let Some(one) = self.map.get_mut(&c.res) else { + return; + }; + let new = |old: u32| match (c.promoted, old) { + (true, COMMON) => COPY_DEST, + (true, old) => old, + (false, _) => c.after, + }; + if c.sub == ALL || one.subs == 1 { + one.all = new(one.all); + if c.promoted { + one.each.iter_mut().for_each(|s| *s = new(*s)); + } else { + one.each.clear(); + } + } else if c.sub < one.subs { + if one.each.is_empty() { + one.each = vec![one.all; one.subs as usize]; + } + let s = &mut one.each[c.sub as usize]; + *s = new(*s); + if one.each.iter().all(|s| *s == one.each[0]) { + one.all = one.each[0]; + one.each.clear(); + } + } + if one.decays { + self.touched.push(c.res); + } + } + + /// The end of a submission (one `ExecuteCommandLists`). + pub fn decay(&mut self) { + for res in std::mem::take(&mut self.touched) { + if let Some(one) = self.map.get_mut(&res) { + one.all = COMMON; + one.each.clear(); + } + } + } +} + +/// The changes a command makes. +pub fn changes(cmd: &Cmd, out: &mut Vec) { + let promoted = |res, sub| Change { res, sub, after: COPY_DEST, promoted: true, alias: false }; + match cmd { + Cmd::Barriers { all } => { + for b in all { + match *b { + // The first half of a split barrier changes nothing yet. + Barrier::Transition { flags, res, sub, after, .. } if flags & 1 == 0 => { + out.push(Change { res, sub, after: after as u32, promoted: false, alias: false }); + } + Barrier::Alias { after, .. } if after != 0 => { + out.push(Change { res: after, sub: ALL, after: 0, promoted: false, alias: true }); + } + _ => {} + } + } + } + Cmd::CopyTexture { dst: Loc::Sub { res, sub }, .. } => out.push(promoted(*res, *sub)), + Cmd::CopyResource { dst, .. } => out.push(promoted(*dst, ALL)), + _ => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn set(res: u32, sub: u32, after: u32) -> Change { + Change { res, sub, after, promoted: false, alias: false } + } + + #[test] + fn states_are_followed() { + let mut s = States::default(); + s.add(1, 4, COPY_DEST, false); + s.add(2, 1, COMMON, false); + s.add(3, 2, COMMON, true); + assert_eq!(s.get(1), Some(vec![COPY_DEST])); + s.change(&set(1, 2, 0x80)); + assert_eq!(s.get(1), Some(vec![COPY_DEST, COPY_DEST, 0x80, COPY_DEST])); + for sub in [0, 1, 3] { + s.change(&set(1, sub, 0x80)); + } + assert_eq!(s.get(1), Some(vec![0x80]), "equal states are one again"); + // A copy into a texture in the common state leaves it a copy + // destination; one into a texture in another state changes nothing. + let copy = |res| Change { res, sub: ALL, after: COPY_DEST, promoted: true, alias: false }; + s.change(©(2)); + s.change(©(1)); + s.decay(); + assert_eq!(s.get(2), Some(vec![COPY_DEST])); + assert_eq!(s.get(1), Some(vec![0x80])); + // Simultaneous access decays. + s.change(&set(3, 1, UNORDERED_ACCESS)); + assert_eq!(s.get(3), Some(vec![COMMON, UNORDERED_ACCESS])); + s.decay(); + assert_eq!(s.get(3), Some(vec![COMMON])); + s.remove(3); + assert_eq!(s.get(3), None); + } + + #[test] + fn commands_change_states() { + let mut out = Vec::new(); + let t = |flags| Barrier::Transition { flags, res: 1, sub: 0, before: 4, after: 8 }; + changes(&Cmd::Barriers { all: vec![t(1), t(2), Barrier::Alias { flags: 0, before: 3, after: 4 }, Barrier::Uav { flags: 0, res: 1 }] }, &mut out); + assert_eq!(out.len(), 2); + assert_eq!(out[0], set(1, 0, 8)); + assert!(out[1].alias && out[1].res == 4); + } +} diff --git a/crates/victory-gpu/src/replay/wire.rs b/crates/victory-gpu/src/replay/wire.rs new file mode 100644 index 0000000..b82667f --- /dev/null +++ b/crates/victory-gpu/src/replay/wire.rs @@ -0,0 +1,741 @@ +//! What a capture holds and how it is written: plain little-endian bytes, +//! fields in order. Read on the machine that wrote it; nothing here is kept +//! compatible between versions beyond the number in [`VERSION`]. + +/// Changes with every change of the layout. +pub const VERSION: u32 = 1; +/// The first bytes of `frame.bin`. +pub const MAGIC: [u8; 8] = *b"VICFRAME"; + +/// Why bytes could not be read back. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Bad(pub &'static str); + +impl std::fmt::Display for Bad { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "the capture cannot be read: {}", self.0) + } +} + +impl std::error::Error for Bad {} + +/// Bytes being read. +pub struct Dec<'a> { + pub bytes: &'a [u8], +} + +impl<'a> Dec<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Dec { bytes } + } + + pub fn take(&mut self, n: usize) -> Result<&'a [u8], Bad> { + if self.bytes.len() < n { + return Err(Bad("it ends too early")); + } + let (head, tail) = self.bytes.split_at(n); + self.bytes = tail; + Ok(head) + } +} + +/// A value that can be written and read back. +pub trait Wire: Sized { + fn put(&self, out: &mut Vec); + fn get(from: &mut Dec) -> Result; +} + +macro_rules! numbers { + ($($t:ty),*) => {$( + impl Wire for $t { + fn put(&self, out: &mut Vec) { + out.extend_from_slice(&self.to_le_bytes()); + } + fn get(from: &mut Dec) -> Result { + let bytes = from.take(size_of::<$t>())?; + Ok(<$t>::from_le_bytes(bytes.try_into().map_err(|_| Bad("a number"))?)) + } + } + )*}; +} +numbers!(u8, u16, u32, i32, u64, f32); + +impl Wire for bool { + fn put(&self, out: &mut Vec) { + out.push(u8::from(*self)); + } + fn get(from: &mut Dec) -> Result { + Ok(u8::get(from)? != 0) + } +} + +impl Wire for Vec { + fn put(&self, out: &mut Vec) { + (self.len() as u32).put(out); + for x in self { + x.put(out); + } + } + fn get(from: &mut Dec) -> Result { + let n = u32::get(from)? as usize; + // At least a byte each: a wild count is refused, not allocated. + if n > from.bytes.len() { + return Err(Bad("a list longer than the file")); + } + (0..n).map(|_| T::get(from)).collect() + } +} + +impl Wire for Option { + fn put(&self, out: &mut Vec) { + self.is_some().put(out); + if let Some(x) = self { + x.put(out); + } + } + fn get(from: &mut Dec) -> Result { + Ok(if bool::get(from)? { Some(T::get(from)?) } else { None }) + } +} + +impl Wire for [T; N] { + fn put(&self, out: &mut Vec) { + for x in self { + x.put(out); + } + } + fn get(from: &mut Dec) -> Result { + let mut all = [T::default(); N]; + for x in &mut all { + *x = T::get(from)?; + } + Ok(all) + } +} + +impl Wire for String { + fn put(&self, out: &mut Vec) { + (self.len() as u32).put(out); + out.extend_from_slice(self.as_bytes()); + } + fn get(from: &mut Dec) -> Result { + let n = u32::get(from)? as usize; + String::from_utf8(from.take(n)?.to_vec()).map_err(|_| Bad("a name that is not text")) + } +} + +/// Bytes copied whole. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct Blob(pub Vec); + +impl Wire for Blob { + fn put(&self, out: &mut Vec) { + (self.0.len() as u64).put(out); + out.extend_from_slice(&self.0); + } + fn get(from: &mut Dec) -> Result { + let n = u64::get(from)? as usize; + Ok(Blob(from.take(n)?.to_vec())) + } +} + +macro_rules! tuples { + ($($t:ident $i:tt),*) => { + impl<$($t: Wire),*> Wire for ($($t,)*) { + fn put(&self, out: &mut Vec) { + $(self.$i.put(out);)* + } + fn get(from: &mut Dec) -> Result { + Ok(($($t::get(from)?,)*)) + } + } + }; +} +tuples!(A 0, B 1); +tuples!(A 0, B 1, C 2); + +macro_rules! wire_struct { + ($(#[$meta:meta])* $name:ident { $($(#[$fmeta:meta])* $f:ident : $t:ty),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub struct $name { $($(#[$fmeta])* pub $f: $t),* } + impl Wire for $name { + fn put(&self, out: &mut Vec) { + $(self.$f.put(out);)* + } + fn get(from: &mut Dec) -> Result { + Ok($name { $($f: <$t>::get(from)?),* }) + } + } + }; +} + +macro_rules! wire_enum { + ($(#[$meta:meta])* $name:ident { $($(#[$vmeta:meta])* $tag:literal $var:ident { $($f:ident : $t:ty),* $(,)? }),* $(,)? }) => { + $(#[$meta])* + #[derive(Clone, Debug, PartialEq)] + pub enum $name { $($(#[$vmeta])* $var { $($f: $t),* }),* } + impl Wire for $name { + fn put(&self, out: &mut Vec) { + match self { + $($name::$var { $($f),* } => { + out.push($tag); + $($f.put(out);)* + })* + } + } + fn get(from: &mut Dec) -> Result { + Ok(match u8::get(from)? { + $($tag => $name::$var { $($f: <$t>::get(from)?),* },)* + _ => return Err(Bad("a kind that does not exist")), + }) + } + } + }; +} + +/// No object. +pub const NONE: u32 = 0; +/// All subresources. +pub const ALL: u32 = u32::MAX; + +/// What a descriptor slot holds: the view last made in it. `res` and +/// `counter` are object ids; `desc` the view's description as D3D12 lays it +/// out (a sampler's is the longest: 52 bytes). In a capture file a constant +/// buffer view's buffer is in `res` and, in place of the address, the +/// offset in it. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Slot { + pub kind: u8, + /// Whether a description was given. + pub described: u8, + pub pad: u16, + pub res: u32, + pub counter: u32, + pub desc: [u8; 52], +} + +/// Kinds of [`Slot`]. +pub mod slot { + pub const EMPTY: u8 = 0; + pub const CBV: u8 = 1; + pub const SRV: u8 = 2; + pub const UAV: u8 = 3; + pub const SAMPLER: u8 = 4; + pub const RTV: u8 = 5; + pub const DSV: u8 = 6; +} + +impl Slot { + pub const EMPTY: Slot = Slot { kind: slot::EMPTY, described: 0, pad: 0, res: NONE, counter: NONE, desc: [0; 52] }; + + /// A slot of `kind` with the description at `desc` (`size` bytes), if any. + /// + /// # Safety + /// `desc` is null or points at a description of `size` bytes. + pub unsafe fn new(kind: u8, res: u32, counter: u32, desc: *const u8, size: usize) -> Slot { + let mut s = Slot { kind, res, counter, ..Slot::EMPTY }; + if !desc.is_null() { + s.described = 1; + // SAFETY: the caller's description, at most 52 bytes of it. + unsafe { std::ptr::copy_nonoverlapping(desc, s.desc.as_mut_ptr(), size.min(52)) }; + } + s + } + + /// A constant buffer view's address (or its offset, in a file). + pub fn address(&self) -> u64 { + u64::from_le_bytes([ + self.desc[0], self.desc[1], self.desc[2], self.desc[3], self.desc[4], self.desc[5], self.desc[6], self.desc[7], + ]) + } + + pub fn set_address(&mut self, address: u64) { + self.desc[..8].copy_from_slice(&address.to_le_bytes()); + } +} + +impl Wire for Slot { + fn put(&self, out: &mut Vec) { + out.push(self.kind); + out.push(self.described); + self.res.put(out); + self.counter.put(out); + // Most descriptions are 40 bytes or less. + let n = self.desc.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + out.push(n as u8); + out.extend_from_slice(&self.desc[..n]); + } + fn get(from: &mut Dec) -> Result { + let (kind, described) = (u8::get(from)?, u8::get(from)?); + let (res, counter) = (u32::get(from)?, u32::get(from)?); + let n = u8::get(from)? as usize; + if n > 52 { + return Err(Bad("a view's description")); + } + let mut desc = [0; 52]; + desc[..n].copy_from_slice(from.take(n)?); + Ok(Slot { kind, described, pad: 0, res, counter, desc }) + } +} + +wire_enum! { + /// A GPU address. + Va { + 0 Null {}, + 1 At { res: u32, offset: u64 }, + /// In no buffer the recorder knows. + 2 Unknown { address: u64 }, + } +} + +wire_enum! { + /// One side of a texture copy. + Loc { + 0 Sub { res: u32, sub: u32 }, + 1 Placed { res: u32, offset: u64, format: i32, size: [u32; 3], pitch: u32 }, + } +} + +wire_enum! { + /// One barrier of a `ResourceBarrier` call. + Barrier { + 0 Transition { flags: i32, res: u32, sub: u32, before: i32, after: i32 }, + 1 Alias { flags: i32, before: u32, after: u32 }, + 2 Uav { flags: i32, res: u32 }, + } +} + +wire_enum! { + /// A command of a list, objects by id, views by what they hold. + Cmd { + 1 Draw { vertices: u32, instances: u32, first: u32, first_instance: u32 }, + 2 DrawIndexed { indices: u32, instances: u32, first: u32, base: i32, first_instance: u32 }, + 3 Dispatch { groups: [u32; 3] }, + 4 DispatchMesh { groups: [u32; 3] }, + 5 CopyBuffer { dst: u32, dst_at: u64, src: u32, src_at: u64, len: u64 }, + 6 CopyTexture { dst: Loc, at: [u32; 3], src: Loc, part: Option<[u32; 6]> }, + 7 CopyResource { dst: u32, src: u32 }, + 8 Resolve { dst: u32, dst_sub: u32, src: u32, src_sub: u32, format: i32 }, + 9 ResolveRegion { dst: u32, dst_sub: u32, at: [u32; 2], src: u32, src_sub: u32, part: Option<[i32; 4]>, format: i32, mode: i32 }, + 10 Topology { kind: i32 }, + 11 Viewports { all: Vec<[f32; 6]> }, + 12 Scissors { all: Vec<[i32; 4]> }, + 13 BlendFactor { factor: Option<[f32; 4]> }, + 14 StencilRef { value: u32 }, + 15 Pipeline { pso: u32 }, + 16 Barriers { all: Vec }, + 17 Heaps { heaps: Vec }, + 18 RootSignature { graphics: bool, root: u32 }, + 19 Table { graphics: bool, param: u32, heap: u32, slot: u32 }, + 20 Constants { graphics: bool, param: u32, offset: u32, values: Vec }, + 21 RootView { graphics: bool, kind: u8, param: u32, va: Va }, + 22 IndexBuffer { view: Option<(Va, u32, i32)> }, + 23 VertexBuffers { start: u32, count: u32, views: Option> }, + 24 Targets { colors: Vec, depth: Option }, + 25 ClearDepth { view: Slot, flags: i32, depth: f32, stencil: u8, rects: Vec<[i32; 4]> }, + 26 ClearTarget { view: Slot, color: [f32; 4], rects: Vec<[i32; 4]> }, + 27 Discard { res: u32, rects: Vec<[i32; 4]>, subs: Option<[u32; 2]> }, + 28 BeginQuery { heap: u32, kind: i32, index: u32 }, + 29 EndQuery { heap: u32, kind: i32, index: u32 }, + 30 ResolveQuery { heap: u32, kind: i32, first: u32, count: u32, dst: u32, at: u64 }, + 31 Indirect { signature: u32, most: u32, args: u32, at: u64, count: u32, count_at: u64 }, + 32 WriteImmediate { all: Vec<(Va, u32, i32)> }, + 33 DepthBounds { min: f32, max: f32 }, + } +} + +/// The highest kind number of [`Cmd`]. +#[cfg(test)] +const LAST_CMD: u8 = 33; + +impl Cmd { + /// The commands of a list's bytes. + pub fn all(bytes: &[u8]) -> Result, Bad> { + let mut from = Dec::new(bytes); + let mut all = Vec::new(); + while !from.bytes.is_empty() { + all.push(Cmd::get(&mut from)?); + } + Ok(all) + } + + /// Whether it makes the card work (and is timed on its own). + pub fn works(&self) -> bool { + self.runs_shaders() + || matches!( + self, + Cmd::CopyBuffer { .. } + | Cmd::CopyTexture { .. } + | Cmd::CopyResource { .. } + | Cmd::Resolve { .. } + | Cmd::ResolveRegion { .. } + | Cmd::ClearDepth { .. } + | Cmd::ClearTarget { .. } + | Cmd::Discard { .. } + | Cmd::ResolveQuery { .. } + | Cmd::WriteImmediate { .. } + ) + } + + /// Whether it runs the pipeline bound. + pub fn runs_shaders(&self) -> bool { + matches!( + self, + Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::Dispatch { .. } | Cmd::DispatchMesh { .. } | Cmd::Indirect { .. } + ) + } +} + +wire_struct! { + HeapProps { kind: i32, cpu: i32, pool: i32 } +} + +wire_struct! { + /// A resource description (`D3D12_RESOURCE_DESC`). + Desc { + dimension: i32, + alignment: u64, + width: u64, + height: u32, + depth: u16, + mips: u16, + format: i32, + samples: [u32; 2], + layout: i32, + flags: i32, + } +} + +wire_struct! { + Heap { id: u32, size: u64, props: HeapProps, alignment: u64, flags: i32 } +} + +wire_enum! { + /// How a resource got its memory. + Place { + 0 Committed { props: HeapProps, flags: i32 }, + 1 Placed { heap: u32, offset: u64 }, + /// A swap chain's buffer. + 2 BackBuffer {}, + } +} + +wire_struct! { + Resource { + id: u32, + place: Place, + desc: Desc, + /// The state it was made in. + made_in: i32, + clear: Option<[u32; 5]>, + /// Its states at the start of the frame: one, or one for each + /// subresource. Buffers start in the common state. + state: Vec, + /// Not the one in use where placed resources overlap: its contents + /// are not in the capture. + idle: bool, + /// Made after the frame started. + late: bool, + name: String, + } +} + +wire_enum! { + /// A part of a pipeline description. + Part { + 0 Root { root: u32 }, + /// Shader code: the number of its blob ([`Frame::codes`]). + 1 Code { kind: i32, blob: u32 }, + /// Plain data. + 2 Plain { kind: i32, data: Blob }, + 3 Layout { elements: Vec<(String, [u32; 6])> }, + } +} + +wire_struct! { + Pipeline { id: u32, parts: Vec, name: String } +} + +wire_struct! { + /// Bytes in `shaders.bin`. + Code { at: u64, len: u64, hash: [u8; 32] } +} + +wire_struct! { + Signature { id: u32, stride: u32, args: Vec<[u32; 4]>, root: u32 } +} + +wire_struct! { + DescriptorHeap { id: u32, kind: i32, count: u32, flags: i32, runs: Vec<(u32, u32, Slot)> } +} + +wire_struct! { + QueryHeap { id: u32, kind: i32, count: u32 } +} + +wire_struct! { + List { kind: i32, commands: Blob } +} + +wire_struct! { + /// Bytes the CPU (or an earlier submission) put into a buffer the CPU + /// sees, by the time a submission went to the card (in `deltas.bin`). + Delta { res: u32, at: u64, len: u64, file: u64 } +} + +wire_struct! { + Submit { + frame: u32, + /// Lists by number; [`MISSING`] for one that was not recorded. + lists: Vec, + deltas: Vec, + /// Descriptor slots written since the submission before. + views: Vec<(u32, u32, Slot)>, + } +} + +/// In [`Submit::lists`]. +pub const MISSING: u32 = u32::MAX; + +wire_struct! { + /// Contents at the start of the frame, in `contents.bin`: of a buffer, + /// `len` bytes from `first`; of a texture, `count` subresources from + /// `first`, laid out as `GetCopyableFootprints` lays them out. + Content { + res: u32, + first: u64, + count: u32, + len: u64, + /// Where in the file; [`ZERO`] if all bytes are zero. + file: u64, + } +} + +/// In [`Content::file`]. +pub const ZERO: u64 = u64::MAX; + +wire_struct! { + /// A frame's picture: a texture as it was when presented (in + /// `present.bin`). + Present { submits: u32, res: u32, width: u32, height: u32, format: i32, pitch: u32, file: u64 } +} + +wire_struct! { + Frame { + adapter: String, + vendor: u32, + device: u32, + /// What the recorder could not record, and how it went. + notes: Vec, + heaps: Vec, + resources: Vec, + roots: Vec<(u32, Blob)>, + codes: Vec, + pipelines: Vec, + signatures: Vec, + descriptor_heaps: Vec, + query_heaps: Vec, + lists: Vec, + submits: Vec, + contents: Vec, + presents: Vec, + } +} + +impl Frame { + pub fn write(&self, path: &std::path::Path) -> std::io::Result<()> { + let mut out = MAGIC.to_vec(); + VERSION.put(&mut out); + self.put(&mut out); + std::fs::write(path, out) + } + + pub fn read(path: &std::path::Path) -> anyhow::Result { + let bytes = std::fs::read(path)?; + let mut from = Dec::new(&bytes); + if from.take(8)? != MAGIC { + return Err(Bad("it is not a frame").into()); + } + if u32::get(&mut from)? != VERSION { + return Err(Bad("it was made by another version of the recorder").into()); + } + let frame = Frame::get(&mut from)?; + if !from.bytes.is_empty() { + return Err(Bad("bytes after its end").into()); + } + Ok(frame) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + fn there_and_back(x: &T) { + let mut out = Vec::new(); + x.put(&mut out); + let mut from = Dec::new(&out); + assert_eq!(&T::get(&mut from).unwrap(), x); + assert!(from.bytes.is_empty(), "bytes left over"); + // Cut anywhere, it is refused and does not panic. + for n in 0..out.len() { + assert!(T::get(&mut Dec::new(&out[..n])).is_err()); + } + } + + fn view() -> Slot { + let mut desc = [0; 52]; + desc[3] = 7; + desc[51] = 9; + Slot { kind: slot::SAMPLER, described: 1, pad: 0, res: 4, counter: 5, desc } + } + + fn at() -> Va { + Va::At { res: 3, offset: 1 << 40 } + } + + pub(crate) fn every_command() -> Vec { + let placed = Loc::Placed { res: 5, offset: 512, format: 28, size: [4, 5, 6], pitch: 256 }; + let rects = vec![[1, 2, 3, 4]]; + vec![ + Cmd::Draw { vertices: 1, instances: 2, first: 3, first_instance: 4 }, + Cmd::DrawIndexed { indices: 1, instances: 2, first: 3, base: -4, first_instance: 5 }, + Cmd::Dispatch { groups: [1, 2, 3] }, + Cmd::DispatchMesh { groups: [4, 5, 6] }, + Cmd::CopyBuffer { dst: 1, dst_at: 2, src: 3, src_at: 4, len: 5 }, + Cmd::CopyTexture { dst: Loc::Sub { res: 1, sub: 2 }, at: [3, 4, 5], src: placed, part: Some([1, 2, 3, 4, 5, 6]) }, + Cmd::CopyResource { dst: 1, src: 2 }, + Cmd::Resolve { dst: 1, dst_sub: 2, src: 3, src_sub: 4, format: 28 }, + Cmd::ResolveRegion { dst: 1, dst_sub: 2, at: [3, 4], src: 5, src_sub: 6, part: Some([0, 1, 2, 3]), format: 28, mode: 1 }, + Cmd::Topology { kind: 4 }, + Cmd::Viewports { all: vec![[0.0, 1.0, 2.0, 3.0, 0.5, 1.0]; 2] }, + Cmd::Scissors { all: rects.clone() }, + Cmd::BlendFactor { factor: Some([0.1, 0.2, 0.3, 0.4]) }, + Cmd::BlendFactor { factor: None }, + Cmd::StencilRef { value: 255 }, + Cmd::Pipeline { pso: 9 }, + Cmd::Barriers { + all: vec![ + Barrier::Transition { flags: 1, res: 2, sub: ALL, before: 4, after: 8 }, + Barrier::Alias { flags: 0, before: 1, after: 2 }, + Barrier::Uav { flags: 0, res: 0 }, + ], + }, + Cmd::Heaps { heaps: vec![1, 2] }, + Cmd::RootSignature { graphics: true, root: 3 }, + Cmd::Table { graphics: false, param: 1, heap: 2, slot: 1 << 20 }, + Cmd::Constants { graphics: true, param: 1, offset: 2, values: vec![3, 4, 5] }, + Cmd::RootView { graphics: true, kind: slot::CBV, param: 1, va: at() }, + Cmd::IndexBuffer { view: Some((at(), 5, 42)) }, + Cmd::IndexBuffer { view: None }, + Cmd::VertexBuffers { start: 1, count: 1, views: Some(vec![(Va::Unknown { address: 5 }, 6, 7)]) }, + Cmd::VertexBuffers { start: 1, count: 3, views: None }, + Cmd::Targets { colors: vec![view(); 3], depth: Some(view()) }, + Cmd::ClearDepth { view: view(), flags: 3, depth: 0.5, stencil: 7, rects: rects.clone() }, + Cmd::ClearTarget { view: view(), color: [1.0, 2.0, 3.0, 4.0], rects: Vec::new() }, + Cmd::Discard { res: 1, rects, subs: Some([0, 2]) }, + Cmd::BeginQuery { heap: 1, kind: 0, index: 2 }, + Cmd::EndQuery { heap: 1, kind: 2, index: 3 }, + Cmd::ResolveQuery { heap: 1, kind: 2, first: 3, count: 4, dst: 5, at: 6 }, + Cmd::Indirect { signature: 1, most: 2, args: 3, at: 4, count: 5, count_at: 6 }, + Cmd::WriteImmediate { all: vec![(at(), 1, 2), (Va::Null {}, 3, 4)] }, + Cmd::DepthBounds { min: 0.25, max: 0.75 }, + ] + } + + #[test] + fn every_command_comes_back() { + let all = every_command(); + let mut bytes = Vec::new(); + for c in &all { + there_and_back(c); + c.put(&mut bytes); + } + assert_eq!(Cmd::all(&bytes).unwrap(), all); + assert!(Cmd::all(&[250]).is_err()); + // Every kind there is stands in the list above. + let kinds: std::collections::BTreeSet = all + .iter() + .map(|c| { + let mut out = Vec::new(); + c.put(&mut out); + out[0] + }) + .collect(); + assert_eq!(kinds.into_iter().collect::>(), (1..=LAST_CMD).collect::>()); + assert!(Cmd::all(&[LAST_CMD + 1]).is_err(), "a kind was added: bring LAST_CMD and the list above up to date"); + } + + #[test] + fn a_frame_comes_back() { + let props = HeapProps { kind: 4, cpu: 3, pool: 1 }; + let desc = Desc { + dimension: 3, + alignment: 65536, + width: 1 << 33, + height: 5, + depth: 6, + mips: 7, + format: 28, + samples: [1, 0], + layout: 1, + flags: 4, + }; + let resource = Resource { + id: 2, + place: Place::Placed { heap: 1, offset: 65536 }, + desc, + made_in: 4, + clear: Some([28, 1, 2, 3, 4]), + state: vec![1, 2, 3], + idle: false, + late: true, + name: "a texture".into(), + }; + let frame = Frame { + adapter: "a card".into(), + vendor: 0x1002, + device: 0x744c, + notes: vec!["nothing".into()], + heaps: vec![Heap { id: 1, size: 64 << 20, props: props.clone(), alignment: 65536, flags: 0x84 }], + resources: vec![ + resource.clone(), + Resource { place: Place::Committed { props, flags: 8 }, ..resource.clone() }, + Resource { place: Place::BackBuffer {}, clear: None, ..resource }, + ], + roots: vec![(3, Blob(vec![1, 2, 3]))], + codes: vec![Code { at: 1, len: 2, hash: [7; 32] }], + pipelines: vec![Pipeline { + id: 4, + parts: vec![ + Part::Root { root: 3 }, + Part::Code { kind: 25, blob: 0 }, + Part::Plain { kind: 8, data: Blob(vec![9; 20]) }, + Part::Layout { elements: vec![("POSITION".into(), [1, 2, 3, 4, 5, 6])] }, + ], + name: "a pipeline".into(), + }], + signatures: vec![Signature { id: 5, stride: 12, args: vec![[10, 0, 0, 0]], root: 0 }], + descriptor_heaps: vec![DescriptorHeap { id: 6, kind: 0, count: 10, flags: 1, runs: vec![(0, 9, Slot::EMPTY), (9, 1, view())] }], + query_heaps: vec![QueryHeap { id: 7, kind: 1, count: 8 }], + lists: vec![List { kind: 0, commands: Blob(vec![1, 2]) }], + submits: vec![Submit { + frame: 0, + lists: vec![0, MISSING], + deltas: vec![Delta { res: 2, at: 4096, len: 8192, file: 0 }], + views: vec![(6, 3, view())], + }], + contents: vec![Content { res: 2, first: 0, count: 3, len: 100, file: ZERO }], + presents: vec![Present { submits: 1, res: 2, width: 4, height: 5, format: 28, pitch: 256, file: 0 }], + }; + there_and_back(&frame); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("frame.bin"); + frame.write(&path).unwrap(); + assert_eq!(Frame::read(&path).unwrap(), frame); + std::fs::write(&path, b"VICFRAMEnothing at all").unwrap(); + assert!(Frame::read(&path).is_err()); + } +} diff --git a/crates/victory-gpu/tests/replay.rs b/crates/victory-gpu/tests/replay.rs new file mode 100644 index 0000000..e774e66 --- /dev/null +++ b/crates/victory-gpu/tests/replay.rs @@ -0,0 +1,909 @@ +//! The frame recorder and replayer on the PC's own adapter (skipped without +//! one): a small program with clears, indirect draws of textures picked from +//! a heap, compute, buffers the CPU changes between submissions, descriptors +//! replaced between them, and textures that share memory. It runs without +//! the recorder, then with it, then one frame of it is replayed; every +//! picture and buffer must be the same. +//! +//! `VICTORY_TEST_D3D_DEBUG=1` runs it under the debug layer. +#![cfg(all(windows, feature = "diagnostics"))] + +use std::mem::ManuallyDrop; + +use victory_gpu::replay::play::{self, Buffers, Options, Player}; +use victory_gpu::replay::record::{self, At, Settings}; +use windows::Win32::Foundation::{HANDLE, HWND, RECT}; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::Win32::UI::WindowsAndMessaging::*; +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)" +cbuffer Pick : register(b0) { uint pick; uint pad; }; +cbuffer Place : register(b1) { float4 place; }; +Texture2D all[] : register(t0); +SamplerState point_sampler : register(s0); +struct V { float4 at : SV_Position; float2 uv : UV; }; +[RootSignature(RS)] +V vs(uint i : SV_VertexID) { + float2 c = float2(i & 1, (i >> 1) & 1); + if (i == 3) c = float2(1, 0); + if (i == 4) c = float2(0, 1); + if (i == 5) c = float2(1, 1); + V v; + v.uv = c; + v.at = float4(place.xy + c * place.zw, 0.5, 1); + return v; +} +float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); } +"#; + +/// 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#" +#define RS "SRV(t0), UAV(u0)" +ByteAddressBuffer from : register(t0); +RWByteAddressBuffer args : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + args.Store4(0, uint4(from.Load(0), 1, 0, 0)); + args.Store4(16, uint4(4000000000u, 1, 0, 0)); +} +"#; + +/// The argument clamp's parameters, with a simple bound. +const CLAMP: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer C : register(b0) { uint kind; uint stride; uint records; uint args_offset; uint has_count; uint count_offset; }; +ByteAddressBuffer from : register(t0); +ByteAddressBuffer count : register(t1); +RWByteAddressBuffer to : register(u0); +RWByteAddressBuffer budget : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= records) return; + uint4 a = from.Load4(args_offset + id.x * stride); + if (a.x > 1000) a.x = 0; + to.Store4(id.x * stride, a); + uint was; + budget.InterlockedAdd(0, a.x, was); +} +"#; + +/// Adds what the CPU gives to what was there, and writes it on. +const ADD: &str = r#" +#define RS "SRV(t0), DescriptorTable(UAV(u0)), UAV(u1)" +ByteAddressBuffer from : register(t0); +RWTexture2D image : register(u0); +RWByteAddressBuffer sum : register(u1); +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint at = (id.y * 16 + id.x) * 4; + uint v = from.Load(at) + sum.Load(at) * 3; + sum.Store(at, v); + image[id.xy] = image[id.xy] + float4((v & 15) / 255.0, 0, 1 / 255.0, 1); +} +"#; + +struct Made { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { + let (mut code, mut errors): (Option, Option) = (None, None); + // SAFETY: the source and names live through the call; the blobs' own + // bytes. + unsafe { + let r = D3DCompile(source.as_ptr().cast(), source.len(), None, None, None, entry, target, 1 << 20, 0, &mut code, Some(&mut errors)); + if r.is_err() { + let e = errors.unwrap(); + let text = std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); + panic!("{}", String::from_utf8_lossy(text)); + } + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()).to_vec() + } +} + +fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { + D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() } +} + +fn compute(device: &ID3D12Device, source: &str) -> Made { + let cs = compile(source, s!("main"), s!("cs_5_1")); + // SAFETY: plain creation. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &cs).unwrap(); + let pso = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: code(&cs), + ..Default::default() + }) + .unwrap(); + Made { root, pso } + } +} + +fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_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() + } +} + +fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(size), + Height: size, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + } +} + +#[derive(Clone, Copy, PartialEq)] +enum In { + Card, + Upload, + Back, + /// The PC's memory, mapped, that shaders write too. + Shared, +} + +fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES) -> (ID3D12Resource, *mut u8) { + let heap = match place { + In::Card => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + In::Upload => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + In::Back => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + In::Shared => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }, + }; + let mut made: Option = 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 place != In::Card { + made.Map(0, None, Some(&mut data)).unwrap(); + } + (made, data.cast()) + } +} + +fn moved(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() + } +} + +fn uav_barrier() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }), + }, + ..Default::default() + } +} + +fn aliased(before: &ID3D12Resource, after: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + // SAFETY: borrowed pointers never released. + pResourceBefore: unsafe { std::mem::transmute_copy(before) }, + // SAFETY: as above. + pResourceAfter: unsafe { std::mem::transmute_copy(after) }, + }), + }, + ..Default::default() + } +} + +const COMMON: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COMMON; +const TARGET: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_RENDER_TARGET; +const READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; +const UAV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; +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; + +/// What the program ends with. +#[derive(PartialEq, Debug)] +struct Outcome { + picture: Vec, + image: Vec, + sum: Vec, + shared: Vec, +} + +struct Scene { + device: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + event: HANDLE, + value: u64, + lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, + draw: Made, + args: Made, + clamp: Made, + add: Made, + signature: ID3D12CommandSignature, + views: ID3D12DescriptorHeap, + step: usize, + rtvs: ID3D12DescriptorHeap, + dsvs: ID3D12DescriptorHeap, + target: ID3D12Resource, + _depth: ID3D12Resource, + fixed: ID3D12Resource, + one: ID3D12Resource, + other: ID3D12Resource, + _heap: ID3D12Heap, + image: ID3D12Resource, + sum: ID3D12Resource, + arguments: ID3D12Resource, + scratch: ID3D12Resource, + budget: ID3D12Resource, + shared: (ID3D12Resource, *mut u8), + constants: (ID3D12Resource, *mut u8), + texels: (ID3D12Resource, *mut u8), + back: (ID3D12Resource, *mut u8), + swap: Option<(IDXGISwapChain3, HWND)>, +} + +impl Scene { + fn new(device: &ID3D12Device, window: bool) -> Scene { + // SAFETY: plain creation throughout. + unsafe { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let lists = (0..3) + .map(|_| { + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + list.Close().unwrap(); + (allocator, list) + }) + .collect(); + let (vs, ps) = (compile(DRAW, s!("vs"), s!("vs_5_1")), compile(DRAW, s!("ps"), s!("ps_5_1"))); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 15; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs), + PS: code(&ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + record::name(&pso, "a drawing pipeline"); + let draw = 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() }; + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &argument, NodeMask: 0 }; + device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature).unwrap(); + let heap = |kind, count, flags| -> ID3D12DescriptorHeap { + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap() + }; + 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); + let rgba = DXGI_FORMAT_R8G8B8A8_UNORM; + let (target, _) = committed(device, In::Card, &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), FROM); + let (depth, _) = committed( + device, + In::Card, + &texture_desc(SIZE, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let (fixed, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), TO); + let (image, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), UAV); + let mut memory: Option = None; + let desc = D3D12_HEAP_DESC { + SizeInBytes: 4 << 20, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + device.CreateHeap(&desc, &mut memory).unwrap(); + let memory = memory.unwrap(); + let placed = || { + let mut made: Option = None; + let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE); + device.CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made).unwrap(); + made.unwrap() + }; + // Two textures in one place. + let (one, other) = (placed(), placed()); + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let card = |size| committed(device, In::Card, &buffer_desc(size, uav), COMMON).0; + let (sum, arguments, scratch, budget) = (card(1024), card(4096), card(4096), card(256)); + let shared = committed(device, In::Shared, &buffer_desc(70_000, uav), COMMON); + let constants = committed( + device, + In::Upload, + &buffer_desc(8192, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let texels = committed( + device, + In::Upload, + &buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + ); + let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO); + for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] { + record::name(r, n); + } + device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart()); + device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart()); + let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let swap = window.then(|| swap_chain(&queue)); + let scene = Scene { + device: device.clone(), + queue, + fence, + event: CreateEventW(None, false, false, None).unwrap(), + value: 0, + lists, + draw, + args: compute(device, ARGS), + clamp, + add: compute(device, ADD), + signature: signature.unwrap(), + views, + step, + rtvs, + dsvs, + target, + _depth: depth, + fixed, + one, + other, + _heap: memory, + image, + sum, + arguments, + scratch, + budget, + shared, + constants, + texels, + back, + swap, + }; + // Null views everywhere, by copies of a slot made elsewhere. + let block = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let null = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: rgba, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + }; + let from = block.GetCPUDescriptorHandleForHeapStart(); + for i in 0..16 { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + i * step }; + device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at); + } + for i in (0..4992).step_by(16) { + device.CopyDescriptorsSimple(16, scene.cpu(i), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + // The rest with the other copying method, in unlike pieces. + let to = [scene.cpu(4992), scene.cpu(4994)]; + let sources = [from, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + 4 * step }]; + device.CopyDescriptors( + 2, + to.as_ptr(), + Some([2u32, 6].as_ptr()), + 2, + sources.as_ptr(), + Some([4u32, 4].as_ptr()), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); + scene.show(4001, &scene.other); + scene.show(4002, &scene.one); + device.CreateUnorderedAccessView(&scene.image, None::<&ID3D12Resource>, None, scene.cpu(7)); + scene + } + } + + fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE { + // SAFETY: a slot of the heap. + let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() }; + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * self.step } + } + + /// Slot `i` shows `texture`. + fn show(&self, i: usize, texture: &ID3D12Resource) { + // SAFETY: a slot of the heap and a live texture. + unsafe { self.device.CreateShaderResourceView(texture, None, self.cpu(i)) }; + } + + fn wait(&mut self) { + self.value += 1; + // SAFETY: our queue, fence and event. + unsafe { + self.queue.Signal(&self.fence, self.value).unwrap(); + self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.device.GetDeviceRemovedReason().unwrap(); + } + } + + fn open(&self, i: usize) -> ID3D12GraphicsCommandList { + let (allocator, list) = &self.lists[i]; + // SAFETY: its last run was waited for. + unsafe { + allocator.Reset().unwrap(); + list.Reset(allocator, None).unwrap(); + } + list.clone() + } + + fn send(&self, lists: &[&ID3D12GraphicsCommandList]) { + let all: Vec> = lists.iter().map(|l| Some(l.cast().unwrap())).collect(); + // SAFETY: closed lists. + unsafe { self.queue.ExecuteCommandLists(&all) }; + } + + /// Fills rows of a 16x16 texture in the upload buffer at `at`. + fn fill(&self, at: usize, color: [u8; 4]) { + for y in 0..16 { + for x in 0..16 { + let mut c = color; + c[1] = c[1].wrapping_add((x * 8 + y) as u8); + // SAFETY: inside the mapping (16 rows of 256 bytes). + unsafe { self.texels.1.add(at + y * 256 + x * 4).cast::<[u8; 4]>().write(c) }; + } + } + } + + fn texture_copy(&self, l: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, at: u64) { + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer never released. + pResource: unsafe { std::mem::transmute_copy(&self.texels.0) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, 16) }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + // SAFETY: an open list; live resources. + unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + + /// A quad of the texture in slot `pick`, at the constants at `at`. + fn quad(&self, l: &ID3D12GraphicsCommandList, pick: u32, at: u64, record: u64) { + // SAFETY: an open list; live objects. + unsafe { + l.SetGraphicsRootSignature(&self.draw.root); + l.SetPipelineState(&self.draw.pso); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.SetGraphicsRoot32BitConstant(0, pick, 0); + l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at); + l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart()); + l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0); + } + } + + /// The arguments made and clamped, as the host layer does it. + fn arguments(&self, l: &ID3D12GraphicsCommandList, before: D3D12_RESOURCE_STATES) { + // SAFETY: an open list; live objects. + unsafe { + l.SetComputeRootSignature(&self.args.root); + l.SetPipelineState(&self.args.pso); + l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536); + l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + l.ResourceBarrier(&[uav_barrier(), moved(&self.arguments, UAV, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]); + l.SetComputeRootSignature(&self.clamp.root); + l.SetPipelineState(&self.clamp.pso); + let constants = [0u32, 16, 2, 0, 0, 0]; + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, self.arguments.GetGPUVirtualAddress()); + l.SetComputeRootShaderResourceView(2, self.arguments.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(3, self.scratch.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]); + l.ResourceBarrier(&[moved(&self.arguments, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, UAV)]); + } + } + + fn place(&self, at: usize, place: [f32; 4]) { + // SAFETY: inside the mapping. + unsafe { self.constants.1.add(at).cast::<[f32; 4]>().write(place) }; + } + + fn give(&self, at: usize, value: u32) { + // SAFETY: inside the mapping. + unsafe { self.shared.1.add(at).cast::().write(value) }; + } + + fn targets(&self, l: &ID3D12GraphicsCommandList) { + // SAFETY: an open list; live objects. + unsafe { + let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + 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())]); + } + } + + 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(0, [200, 10, 30, 255]); + self.fill(8192, [10, 40, 220, 255]); + let l = self.open(0); + self.texture_copy(&l, &self.fixed, 0); + self.texture_copy(&l, &self.other, 8192); + l.ResourceBarrier(&[moved(&self.fixed, TO, READ), moved(&self.other, TO, READ)]); + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + } + // The first submission. + self.show(4000, &self.fixed); + self.place(0, [-1.0 + 0.1 * n as f32, -1.0, 0.5, 0.5]); + self.place(256, [0.0, 0.0, 0.5, 0.5]); + self.give(65536, 6); + self.give(40, 7 + n); + let l = self.open(0); + l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]); + let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None); + l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + self.arguments(&l, COMMON); + self.targets(&l); + self.quad(&l, 4000, 0, 0); + self.quad(&l, 4001, 256, 0); + // Nothing: the clamp cut it to no vertices. + self.quad(&l, 4001, 0, 1); + l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + // The second: other constants and another texture in the same + // places, and the second texture in the memory of the first. + self.show(4000, &self.other); + self.place(0, [-0.9, 0.3, 0.6, 0.6]); + self.place(256, [0.3, -0.8, 0.6, 0.5]); + self.give(40, 100 + n); + self.give(65536, 3); + self.fill(16384, [30, 200, 10 + 5 * n as u8, 255]); + let l = self.open(1); + self.targets(&l); + self.arguments(&l, COMMON); + self.quad(&l, 4000, 0, 0); + l.ResourceBarrier(&[moved(&self.other, READ, TO)]); + l.ResourceBarrier(&[aliased(&self.other, &self.one)]); + self.texture_copy(&l, &self.one, 16384); + l.ResourceBarrier(&[moved(&self.one, TO, READ)]); + self.arguments(&l, ARGUMENTS); + self.quad(&l, 4002, 256, 0); + l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); + // And back, for the next frame. + l.ResourceBarrier(&[moved(&self.one, READ, TO)]); + l.ResourceBarrier(&[aliased(&self.one, &self.other)]); + self.texture_copy(&l, &self.other, 8192); + l.ResourceBarrier(&[moved(&self.other, TO, READ)]); + l.Close().unwrap(); + let second = l; + let l = self.open(2); + l.SetDescriptorHeaps(&[Some(self.views.clone())]); + l.SetComputeRootSignature(&self.add.root); + l.SetPipelineState(&self.add.pso); + l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress()); + let table = self.views.GetGPUDescriptorHandleForHeapStart().ptr + 7 * self.step as u64; + l.SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table }); + l.SetComputeRootUnorderedAccessView(2, self.sum.GetGPUVirtualAddress()); + for _ in 0..3 { + l.Dispatch(2, 2, 1); + l.ResourceBarrier(&[uav_barrier()]); + } + // The card writes memory the CPU sees. + l.ResourceBarrier(&[moved(&self.sum, UAV, FROM)]); + l.CopyBufferRegion(&self.shared.0, 30_000, &self.sum, 0, 1024); + l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]); + l.Close().unwrap(); + self.send(&[&second, &l]); + if let Some((swap, _)) = &self.swap { + swap.Present(0, DXGI_PRESENT(0)).unwrap(); + } + record::present(&self.target, FROM); + } + } + + /// What everything holds now. + fn outcome(&mut self) -> Outcome { + self.wait(); + let l = self.open(0); + // SAFETY: an open list; live objects. + unsafe { + let to = |at: u64, size| 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: footprint(at, size) }, + }; + let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(t), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]); + l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None); + l.CopyTextureRegion(&to(1 << 18, 16), 0, 0, 0, &of(&self.image), None); + l.ResourceBarrier(&[moved(&self.image, FROM, UAV)]); + l.CopyBufferRegion(&self.back.0, 1 << 19, &self.sum, 0, 1024); + l.Close().unwrap(); + self.send(&[&l]); + self.wait(); + let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec(); + Outcome { + picture: at(0, (SIZE * 512) as usize), + image: rows(&at(1 << 18, 4096)), + sum: at(1 << 19, 1024), + shared: std::slice::from_raw_parts(self.shared.1, 70_000).to_vec(), + } + } + } +} + +/// The 64 bytes of each row of a 16x16 texture. +fn rows(bytes: &[u8]) -> Vec { + bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect() +} + +fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: at, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: size, + Height: size, + Depth: 1, + RowPitch: (size * 4).next_multiple_of(256), + }, + } +} + +/// A swap chain of a window that is never shown. +fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) { + // SAFETY: plain creation. + unsafe { + let hwnd = + CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!("replay test"), WS_POPUP, 0, 0, 64, 64, None, None, None, None).unwrap(); + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: 64, + Height: 64, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: 2, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + ..Default::default() + }; + let chain = factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None).unwrap().cast().unwrap(); + (chain, hwnd) + } +} + +fn table_of(device: &ID3D12Device) -> usize { + // SAFETY: a live COM object starts with its table's address. + unsafe { *device.as_raw().cast::() } +} + +fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) -> play::Report { + let report = player.run(options).unwrap(); + println!("{}", report.text(what)); + assert_eq!(report.frame_ms.len(), options.loops as usize); + assert!(report.median_ms() > 0.0); + let (db, same) = report.picture.unwrap(); + assert!(same && db.is_infinite(), "{what}: the picture differs ({db} dB)"); + let mut get = |name: &str| { + let id = player.named(name).unwrap(); + player.contents(id).unwrap().unwrap() + }; + assert_eq!(get("sum"), expected.sum, "{what}: sum"); + 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); + report +} + +#[test] +fn a_frame_is_recorded_and_replayed() { + let debug = std::env::var_os("VICTORY_TEST_D3D_DEBUG").is_some(); + let mut device: Option = None; + // SAFETY: plain creation. + unsafe { + if debug { + let mut layer: Option = None; + D3D12GetDebugInterface(&mut layer).unwrap(); + layer.unwrap().EnableDebugLayer(); + } + let _ = D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device); + } + let Some(device) = device else { + eprintln!("no adapter: skipped"); + return; + }; + let own = table_of(&device); + // Without the recorder. + let without = { + let mut scene = Scene::new(&device, false); + (0..5).for_each(|n| scene.frame(n)); + scene.outcome() + }; + eprintln!("ran without the recorder"); + // Something is in the picture. + assert!(without.sum.iter().any(|&b| b != 0)); + 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()); + + // With it: armed at the first present, the fourth frame is captured (a + // 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 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(), + "one recorder a process" + ); + eprintln!("recorder on"); + let mut scene = Scene::new(&device, true); + eprintln!("scene made"); + (0..4).for_each(|n| scene.frame(n)); + assert_eq!(record::finished(), Some(folder.clone()), "see {}", folder.display()); + let expected = scene.outcome(); + // It goes on as it did without the recorder. + scene.frame(4); + let after = scene.outcome(); + assert!(after == without, "the recorder changed what the program makes"); + drop(scene); + record::unhook(&device); + assert_eq!(table_of(&device), own, "the device is as it was"); + for name in ["frame.bin", "contents.bin", "deltas.bin", "shaders.bin", "present.bin", "notes.txt", "frame-0.png"] { + assert!(folder.join(name).exists(), "{name}"); + } + println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + + let plain = Options { loops: 3, ..Default::default() }; + let mut player = Player::load(dir.path(), &plain).unwrap(); + check(&mut player, &plain, &expected, "unchanged"); + let detailed = Options { detailed: true, ..plain.clone() }; + let report = check(&mut player, &detailed, &expected, "detailed"); + let count = |kind: &str| report.categories.iter().find(|c| c.0 == kind).map_or(0, |c| c.2); + assert_eq!(count("argument clamps (ours)"), 3); + assert_eq!(count("indirect draws"), 5); + assert_eq!(count("dispatches"), 6); + assert_eq!(count("clears"), 2); + assert!(report.shaders.iter().any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), "{:?}", report.shaders); + let merged = Options { merge_barriers: true, ..plain.clone() }; + check(&mut player, &merged, &expected, "merged barriers"); + let clamps = Options { skip_clamps: true, ..plain.clone() }; + let report = check(&mut player, &clamps, &expected, "without clamps"); + assert!(report.notes.iter().any(|n| n.contains("3 clamp passes")), "{:?}", report.notes); + let one = Options { one_submit: true, ..plain.clone() }; + check(&mut player, &one, &expected, "one submission"); + let hash = Options { skip_hash_passes: true, ..plain.clone() }; + check(&mut player, &hash, &expected, "without hash passes (there are none)"); + // These change what is drawn: they run, and then the frame is as before. + let no_barriers = Options { no_barriers: true, ..plain.clone() }; + player.run(&no_barriers).unwrap(); + let some = Options { only: Some((0, 1)), ..plain.clone() }; + player.run(&some).unwrap(); + let skip = Options { skip_shaders: vec!["a drawing".into()], ..plain.clone() }; + let report = player.run(&skip).unwrap(); + assert!(!report.picture.unwrap().1, "without its draws the picture is another"); + assert!(report.notes.iter().any(|n| n.contains("1 pipelines match")) && report.notes.iter().any(|n| n.contains("left out 5 commands"))); + let kept = Options { restore: false, ..plain.clone() }; + player.run(&kept).unwrap(); + check(&mut player, &plain, &expected, "unchanged again"); + drop(player); + for buffers in [Buffers::Card, Buffers::Pc] { + let o = Options { buffers, ..plain.clone() }; + let mut player = Player::load(dir.path(), &o).unwrap(); + check(&mut player, &o, &expected, &format!("buffers {buffers:?}")); + } + let o = Options { compare: true, merge_barriers: true, loops: 2, ..Default::default() }; + let both = play::replay(dir.path(), &o).unwrap(); + assert_eq!(both.len(), 2); + assert!(both.iter().all(|(_, r)| r.picture.unwrap().1)); + assert!(folder.join("replay.png").exists() && folder.join("replay-unchanged.png").exists()); + if debug { + let q = device.cast::().unwrap(); + // SAFETY: plain queries; messages read into buffers of their size. + unsafe { + for i in 0..q.GetNumStoredMessages() { + let mut size = 0; + let _ = q.GetMessage(i, None, &mut size); + let mut buffer = vec![0u64; size.div_ceil(8)]; + let m = buffer.as_mut_ptr().cast::(); + if q.GetMessage(i, Some(m), &mut size).is_ok() && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 { + let text = std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); + println!("D3D12 {} {}: {}", (*m).Severity.0, (*m).ID.0, String::from_utf8_lossy(text)); + } + } + } + } +} From 048201b13cc38f366fe7d9b4f960cd82ddc9f023 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:09:57 -0600 Subject: [PATCH 2/3] victory replay, larger tests of it Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/main.rs | 8 + apps/victory/src/replay.rs | 131 ++++++++++++ crates/victory-gpu/src/host.rs | 9 +- crates/victory-gpu/src/replay/play.rs | 145 ++++++++++--- crates/victory-gpu/src/replay/record.rs | 11 +- crates/victory-gpu/src/replay/snap.rs | 145 +++++++++++-- crates/victory-gpu/tests/replay.rs | 268 ++++++++++++++++++++++- crates/victory-gpu/tests/replay_big.rs | 271 ++++++++++++++++++++++++ crates/victory-hle/src/lib.rs | 2 + 9 files changed, 938 insertions(+), 52 deletions(-) create mode 100644 apps/victory/src/replay.rs create mode 100644 crates/victory-gpu/tests/replay_big.rs diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index a04655c..99733b9 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -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, }, + /// 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(), } } diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs new file mode 100644 index 0000000..61de570 --- /dev/null +++ b/apps/victory/src/replay.rs @@ -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, + /// 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, + /// 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, + /// 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); + } +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 332ebee..643eab5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -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::() + { + // SAFETY: a plain call on a live object. + let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text)) }; + } return; } if dred_on() diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 9f09a0d..c7c7131 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -345,7 +345,7 @@ impl Player { player.make_masters()?; step("copies to restore from", &mut at); let steps: Vec = 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; 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 = 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::>(); + // 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 = 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::>(); + first.iter().for_each(|d| seen.extend(pages(d))); + let mut rest: Vec> = vec![Vec::new()]; + for s in self.frame.submits.iter().skip(1) { + let (early, late): (Vec, Vec) = + 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 { + 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>> { + 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>> { 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 usize { - let mut errors = 0; - let mut seen: HashMap = HashMap::new(); +/// The debug layer's errors: how many of each kind, and its first text. +fn debug_messages(q: &ID3D12InfoQueue) -> Vec { + let mut seen: BTreeMap = 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)] diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index ea9b6d9..799fe1e 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -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`) - /// and `VICTORY_RECORD_FRAMES`. + /// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f`), + /// `VICTORY_RECORD_FRAMES` and `VICTORY_RECORD_ALWAYS=1`. pub fn from_env() -> Option { 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; @@ -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, + parts: HashMap>, +} + +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, buffers: Vec, known: HashSet, + /// Resources descriptors name, or named during the frame. + viewed: HashSet, /// 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, 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, 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> = 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(&[])); diff --git a/crates/victory-gpu/tests/replay.rs b/crates/victory-gpu/tests/replay.rs index e774e66..3d5eb5a 100644 --- a/crates/victory-gpu/tests/replay.rs +++ b/crates/victory-gpu/tests/replay.rs @@ -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>)>, +} + /// What the program ends with. #[derive(PartialEq, Debug)] struct Outcome { + still: Vec, picture: Vec, image: Vec, sum: Vec, @@ -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 { + 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 { 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::>(), [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"); diff --git a/crates/victory-gpu/tests/replay_big.rs b/crates/victory-gpu/tests/replay_big.rs new file mode 100644 index 0000000..34a9b95 --- /dev/null +++ b/crates/victory-gpu/tests/replay_big.rs @@ -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 = 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::().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, + card: Vec, + 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 = 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 = (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 = 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)); + } +} diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index ed5b632..a61e988 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -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; From 94fe5d9dee10d254b2738da5645c6e04f9220b87 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 20:23:46 -0600 Subject: [PATCH 3/3] Frame replay: usage doc, mesh draws and a title's size in its tests Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 5 +- crates/victory-gpu/src/replay/edit.rs | 243 ++++- crates/victory-gpu/src/replay/gpu.rs | 115 ++- crates/victory-gpu/src/replay/hook.rs | 91 +- crates/victory-gpu/src/replay/play.rs | 1235 ++++++++++++++++++----- crates/victory-gpu/src/replay/pso.rs | 203 +++- crates/victory-gpu/src/replay/record.rs | 1035 +++++++++++++++---- crates/victory-gpu/src/replay/snap.rs | 496 +++++++-- crates/victory-gpu/src/replay/states.rs | 93 +- crates/victory-gpu/src/replay/wire.rs | 351 ++++++- crates/victory-gpu/tests/replay.rs | 948 ++++++++++++++--- crates/victory-gpu/tests/replay_big.rs | 185 +++- docs/replay.md | 102 ++ 13 files changed, 4274 insertions(+), 828 deletions(-) create mode 100644 docs/replay.md diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 61de570..cad167a 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -85,7 +85,10 @@ fn range(text: &str) -> Option<(u32, u32)> { 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)"))?), + 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 { diff --git a/crates/victory-gpu/src/replay/edit.rs b/crates/victory-gpu/src/replay/edit.rs index a49a343..08184a3 100644 --- a/crates/victory-gpu/src/replay/edit.rs +++ b/crates/victory-gpu/src/replay/edit.rs @@ -52,7 +52,9 @@ pub fn no_uav_barriers(cmds: Vec) -> (Vec, u32) { /// Barriers only: what a list left out still does to the states of /// resources. pub fn barriers_only(cmds: Vec) -> Vec { - cmds.into_iter().filter(|c| matches!(c, Cmd::Barriers { .. })).collect() + cmds.into_iter() + .filter(|c| matches!(c, Cmd::Barriers { .. })) + .collect() } /// Joins the barrier calls with no work between them into one; how many @@ -96,7 +98,9 @@ pub fn merge_barriers(cmds: Vec) -> (Vec, u32) { fn join(have: &mut Vec, b: Barrier) { match b { Barrier::Uav { res, .. } => { - let covered = have.iter().any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE)); + let covered = have + .iter() + .any(|h| matches!(h, Barrier::Uav { res: r, .. } if *r == res || *r == NONE)); if covered { return; } @@ -105,16 +109,36 @@ fn join(have: &mut Vec, b: Barrier) { } have.push(b); } - Barrier::Transition { flags: 0, res, sub, before, after } => { + Barrier::Transition { + flags: 0, + res, + sub, + before, + after, + } => { // The last one of this resource, if it is of the same part of it. - let last = have.iter().rposition(|h| matches!(h, Barrier::Transition { res: r, .. } if *r == res)); + let last = have + .iter() + .rposition(|h| matches!(h, Barrier::Transition { res: r, .. } if *r == res)); if let Some(i) = last - && let Barrier::Transition { flags: 0, sub: s, before: first, after: until, .. } = have[i] + && let Barrier::Transition { + flags: 0, + sub: s, + before: first, + after: until, + .. + } = have[i] && s == sub && until == before { if first != after { - have[i] = Barrier::Transition { flags: 0, res, sub, before: first, after }; + have[i] = Barrier::Transition { + flags: 0, + res, + sub, + before: first, + after, + }; } else { have.remove(i); if after == UNORDERED_ACCESS { @@ -150,7 +174,12 @@ pub fn find_clamps(cmds: &[Cmd], psos: &HashSet, next: &mut u64) -> Vec bound = *pso, - Cmd::Constants { graphics: false, param: 0, offset, values } => { + Cmd::Constants { + graphics: false, + param: 0, + offset, + values, + } => { for (i, v) in values.iter().enumerate() { if let Some(c) = constants.get_mut(*offset as usize + i) { *c = *v; @@ -159,11 +188,21 @@ pub fn find_clamps(cmds: &[Cmd], psos: &HashSet, next: &mut u64) -> Vec to = Some(*res), + Cmd::RootView { + graphics: false, + param: 3, + va: Va::At { res, offset: 0 }, + .. + } => to = Some(*res), Cmd::Dispatch { .. } if psos.contains(&bound) => { if let Some(scratch) = to { let bytes = u64::from(constants[1]) * u64::from(constants[2]); - found.push(Clamp { at, scratch, bytes, result: *next }); + found.push(Clamp { + at, + scratch, + bytes, + result: *next, + }); *next += bytes.next_multiple_of(256); } } @@ -189,10 +228,22 @@ pub fn keep_clamped(cmds: Vec, clamps: &[Clamp]) -> Vec { out.push(c); if done && let Some(clamp) = open.take() { let moved = |before, after| Cmd::Barriers { - all: vec![Barrier::Transition { flags: 0, res: clamp.scratch, sub: ALL, before, after }], + all: vec![Barrier::Transition { + flags: 0, + res: clamp.scratch, + sub: ALL, + before, + after, + }], }; out.push(moved(INDIRECT_ARGUMENT, COPY_SOURCE)); - out.push(Cmd::CopyBuffer { dst: RESULTS, dst_at: clamp.result, src: clamp.scratch, src_at: 0, len: clamp.bytes }); + out.push(Cmd::CopyBuffer { + dst: RESULTS, + dst_at: clamp.result, + src: clamp.scratch, + src_at: 0, + len: clamp.bytes, + }); out.push(moved(COPY_SOURCE, INDIRECT_ARGUMENT)); } } @@ -223,9 +274,23 @@ pub fn skip_clamps(cmds: Vec, clamps: &[Clamp]) -> Vec { out.push(Cmd::Barriers { all }); } } - Cmd::Indirect { signature, most, args, at, count, count_at } if last.contains_key(&args) => { + Cmd::Indirect { + signature, + most, + args, + at, + count, + count_at, + } if last.contains_key(&args) => { let result = last.get(&args).copied().unwrap_or(0); - out.push(Cmd::Indirect { signature, most, args: RESULTS, at: result + at, count, count_at }); + out.push(Cmd::Indirect { + signature, + most, + args: RESULTS, + at: result + at, + count, + count_at, + }); } c => out.push(c), } @@ -247,7 +312,13 @@ mod tests { Barrier::Uav { flags: 0, res } } fn moved(res: u32, before: i32, after: i32) -> Barrier { - Barrier::Transition { flags: 0, res, sub: ALL, before, after } + Barrier::Transition { + flags: 0, + res, + sub: ALL, + before, + after, + } } fn barriers(all: &[Barrier]) -> Cmd { Cmd::Barriers { all: all.to_vec() } @@ -255,18 +326,47 @@ mod tests { #[test] fn pipelines_are_skipped() { - let list = vec![pso(1), go(), pso(2), go(), go(), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]; + let list = vec![ + pso(1), + go(), + pso(2), + go(), + go(), + Cmd::CopyResource { dst: 1, src: 2 }, + pso(1), + go(), + ]; let (out, n) = skip_pipelines(list.clone(), &HashSet::from([2])); assert_eq!(n, 2); - assert_eq!(out, vec![pso(1), go(), pso(2), Cmd::CopyResource { dst: 1, src: 2 }, pso(1), go()]); + assert_eq!( + out, + vec![ + pso(1), + go(), + pso(2), + Cmd::CopyResource { dst: 1, src: 2 }, + pso(1), + go() + ] + ); assert_eq!(skip_pipelines(list.clone(), &HashSet::new()), (list, 0)); } #[test] fn uav_barriers_are_dropped() { - let list = vec![barriers(&[uav(0)]), go(), barriers(&[uav(1), moved(1, 8, 4)])]; - assert_eq!(no_uav_barriers(list.clone()), (vec![go(), barriers(&[moved(1, 8, 4)])], 2)); - assert_eq!(barriers_only(list.clone()), vec![list[0].clone(), list[2].clone()]); + let list = vec![ + barriers(&[uav(0)]), + go(), + barriers(&[uav(1), moved(1, 8, 4)]), + ]; + assert_eq!( + no_uav_barriers(list.clone()), + (vec![go(), barriers(&[moved(1, 8, 4)])], 2) + ); + assert_eq!( + barriers_only(list.clone()), + vec![list[0].clone(), list[2].clone()] + ); } #[test] @@ -286,11 +386,33 @@ mod tests { ]; let (out, saved) = merge_barriers(list); assert_eq!(saved, 4); - assert_eq!(out, vec![barriers(&[moved(1, 0, 64), uav(0)]), pso(1), go(), barriers(&[uav(1)]), go()]); + assert_eq!( + out, + vec![ + barriers(&[moved(1, 0, 64), uav(0)]), + pso(1), + go(), + barriers(&[uav(1)]), + go() + ] + ); // Parts of a resource are not mixed up. - let part = |sub, before, after| Barrier::Transition { flags: 0, res: 1, sub, before, after }; - let list = vec![barriers(&[part(0, 4, 8)]), barriers(&[part(1, 4, 8)]), barriers(&[part(ALL, 8, 64)])]; - assert_eq!(merge_barriers(list).0, vec![barriers(&[part(0, 4, 8), part(1, 4, 8), part(ALL, 8, 64)])]); + let part = |sub, before, after| Barrier::Transition { + flags: 0, + res: 1, + sub, + before, + after, + }; + let list = vec![ + barriers(&[part(0, 4, 8)]), + barriers(&[part(1, 4, 8)]), + barriers(&[part(ALL, 8, 64)]), + ]; + assert_eq!( + merge_barriers(list).0, + vec![barriers(&[part(0, 4, 8), part(1, 4, 8), part(ALL, 8, 64)])] + ); } #[test] @@ -299,29 +421,84 @@ mod tests { vec![ barriers(&[uav(0), moved(scratch, 0, 8)]), pso(9), - Cmd::Constants { graphics: false, param: 0, offset: 0, values: vec![10, stride, records, 0, 0, 0] }, - Cmd::RootView { graphics: false, kind: 3, param: 3, va: Va::At { res: scratch, offset: 0 } }, + Cmd::Constants { + graphics: false, + param: 0, + offset: 0, + values: vec![10, stride, records, 0, 0, 0], + }, + Cmd::RootView { + graphics: false, + kind: 3, + param: 3, + va: Va::At { + res: scratch, + offset: 0, + }, + }, go(), barriers(&[uav(0), moved(scratch, 8, 0x200)]), ] }; - let run = |args, at| Cmd::Indirect { signature: 1, most: 1, args, at, count: 0, count_at: 0 }; + let run = |args, at| Cmd::Indirect { + signature: 1, + most: 1, + args, + at, + count: 0, + count_at: 0, + }; let mut list = clamp(5, 12, 2); list.extend([pso(1), run(5, 12), run(5, 0), run(6, 0)]); list.extend(clamp(5, 12, 100)); list.extend([pso(1), run(5, 24), barriers(&[moved(5, 0x200, 0)])]); let mut next = 0; let found = find_clamps(&list, &HashSet::from([9]), &mut next); - assert_eq!(found.iter().map(|c| (c.scratch, c.bytes, c.result)).collect::>(), [(5, 24, 0), (5, 1200, 256)]); + assert_eq!( + found + .iter() + .map(|c| (c.scratch, c.bytes, c.result)) + .collect::>(), + [(5, 24, 0), (5, 1200, 256)] + ); assert_eq!(next, 256 + 1280); let kept = keep_clamped(list.clone(), &found); assert_eq!(kept.len(), list.len() + 6); - assert_eq!(kept[7], Cmd::CopyBuffer { dst: RESULTS, dst_at: 0, src: 5, src_at: 0, len: 24 }); - assert_eq!(kept.iter().filter(|c| matches!(c, Cmd::CopyBuffer { .. })).count(), 2); + assert_eq!( + kept[7], + Cmd::CopyBuffer { + dst: RESULTS, + dst_at: 0, + src: 5, + src_at: 0, + len: 24 + } + ); + assert_eq!( + kept.iter() + .filter(|c| matches!(c, Cmd::CopyBuffer { .. })) + .count(), + 2 + ); let skipped = skip_clamps(list, &found); - assert!(!skipped.iter().any(|c| matches!(c, Cmd::Dispatch { .. } | Cmd::Barriers { .. }))); - let runs: Vec<(u32, u64)> = - skipped.iter().filter_map(|c| if let Cmd::Indirect { args, at, .. } = c { Some((*args, *at)) } else { None }).collect(); - assert_eq!(runs, [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)]); + assert!( + !skipped + .iter() + .any(|c| matches!(c, Cmd::Dispatch { .. } | Cmd::Barriers { .. })) + ); + let runs: Vec<(u32, u64)> = skipped + .iter() + .filter_map(|c| { + if let Cmd::Indirect { args, at, .. } = c { + Some((*args, *at)) + } else { + None + } + }) + .collect(); + assert_eq!( + runs, + [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)] + ); } } diff --git a/crates/victory-gpu/src/replay/gpu.rs b/crates/victory-gpu/src/replay/gpu.rs index 61ed472..97ff62e 100644 --- a/crates/victory-gpu/src/replay/gpu.rs +++ b/crates/victory-gpu/src/replay/gpu.rs @@ -46,9 +46,15 @@ impl Worker { let i = match self.lists.iter().position(|l| l.2 <= done) { Some(i) => i, None => { - let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = - self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; list.Close()?; self.lists.push((allocator, list, 0)); self.lists.len() - 1 @@ -100,7 +106,10 @@ pub(super) fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOU Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() @@ -114,7 +123,10 @@ pub(super) fn buffer( size: u64, flags: D3D12_RESOURCE_FLAGS, ) -> Result<(ID3D12Resource, *mut u8)> { - let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; let state = match kind { D3D12_HEAP_TYPE_UPLOAD => D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_HEAP_TYPE_READBACK => D3D12_RESOURCE_STATE_COPY_DEST, @@ -124,7 +136,14 @@ pub(super) fn buffer( let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping. unsafe { - device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, flags), state, None, &mut made)?; + device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(size, flags), + state, + None, + &mut made, + )?; let made = made.ok_or_else(windows::core::Error::empty)?; if kind == D3D12_HEAP_TYPE_UPLOAD || kind == D3D12_HEAP_TYPE_READBACK { made.Map(0, None, Some(&mut data))?; @@ -146,7 +165,11 @@ pub(super) fn subresources(d: &wire::Desc) -> u32 { if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { return 1; } - let layers = if d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { 1 } else { u32::from(d.depth) }; + let layers = if d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + 1 + } else { + u32::from(d.depth) + }; u32::from(d.mips.max(1)) * layers.max(1) * planes(d.format) } @@ -161,7 +184,18 @@ pub(super) fn footprints( let mut all = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; let mut total = 0; // SAFETY: outputs for `count` subresources. - unsafe { device.GetCopyableFootprints(desc, first, count, 0, Some(all.as_mut_ptr()), None, None, Some(&mut total)) }; + unsafe { + device.GetCopyableFootprints( + desc, + first, + count, + 0, + Some(all.as_mut_ptr()), + None, + None, + Some(&mut total), + ) + }; (all, total) } @@ -171,12 +205,17 @@ pub(super) fn sub_location(res: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY // SAFETY: a borrowed pointer the location never releases. pResource: unsafe { std::mem::transmute_copy(res) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: sub, + }, } } /// A location naming bytes of a buffer; no reference is taken. -pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { +pub(super) fn placed_location( + res: &ID3D12Resource, + f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +) -> D3D12_TEXTURE_COPY_LOCATION { D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. pResource: unsafe { std::mem::transmute_copy(res) }, @@ -186,7 +225,12 @@ pub(super) fn placed_location(res: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_ } /// A transition; no reference is taken. -pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32) -> D3D12_RESOURCE_BARRIER { +pub(super) fn transition( + res: &ID3D12Resource, + sub: u32, + before: u32, + after: u32, +) -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -204,7 +248,12 @@ pub(super) fn transition(res: &ID3D12Resource, sub: u32, before: u32, after: u32 /// The barriers that move a texture from `from` (one state, or one for each /// subresource) to `to`. -pub(super) fn moves(res: &ID3D12Resource, from: &[u32], to: &[u32], out: &mut Vec) { +pub(super) fn moves( + res: &ID3D12Resource, + from: &[u32], + to: &[u32], + out: &mut Vec, +) { let n = from.len().max(to.len()); if n == 1 { if from[0] != to[0] { @@ -229,7 +278,10 @@ pub(super) fn to_desc(d: &wire::Desc) -> D3D12_RESOURCE_DESC { DepthOrArraySize: d.depth, MipLevels: d.mips, Format: DXGI_FORMAT(d.format), - SampleDesc: DXGI_SAMPLE_DESC { Count: d.samples[0], Quality: d.samples[1] }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: d.samples[0], + Quality: d.samples[1], + }, Layout: D3D12_TEXTURE_LAYOUT(d.layout), Flags: D3D12_RESOURCE_FLAGS(d.flags), } @@ -260,7 +312,11 @@ pub(super) fn to_props(p: &wire::HeapProps) -> D3D12_HEAP_PROPERTIES { } pub(super) fn from_props(p: &D3D12_HEAP_PROPERTIES) -> wire::HeapProps { - wire::HeapProps { kind: p.Type.0, cpu: p.CPUPageProperty.0, pool: p.MemoryPoolPreference.0 } + wire::HeapProps { + kind: p.Type.0, + cpu: p.CPUPageProperty.0, + pool: p.MemoryPoolPreference.0, + } } /// How the CPU sees memory of a heap. @@ -294,7 +350,13 @@ pub(super) fn seen(p: &wire::HeapProps) -> Seen { /// 8-bit RGB of a presented texture's rows (and the greatest channel value /// of the format, for the signal-to-noise ratio). `None` for formats not /// shown. -pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) -> Option> { +pub(super) fn rgb( + width: u32, + height: u32, + pitch: u32, + format: i32, + rows: &[u8], +) -> Option> { let mut out = Vec::with_capacity((width * height * 3) as usize); let half = |b: &[u8]| { let h = u16::from_le_bytes([b[0], b[1]]); @@ -304,7 +366,11 @@ pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) 31 => 65536.0, e => (1.0 + m / 1024.0) * 2f32.powi(i32::from(e) - 15), }; - if s == 1 { 0 } else { (v.min(1.0) * 255.0) as u8 } + if s == 1 { + 0 + } else { + (v.min(1.0) * 255.0) as u8 + } }; for y in 0..height as usize { let row = rows.get(y * pitch as usize..)?; @@ -334,7 +400,11 @@ pub(super) fn rgb(width: u32, height: u32, pitch: u32, format: i32, rows: &[u8]) /// Peak signal-to-noise ratio of two pictures of 8-bit channels, in dB /// (infinite if equal). pub(super) fn psnr(a: &[u8], b: &[u8]) -> f64 { - let sum: u64 = a.iter().zip(b).map(|(&x, &y)| u64::from(x.abs_diff(y)).pow(2)).sum(); + let sum: u64 = a + .iter() + .zip(b) + .map(|(&x, &y)| u64::from(x.abs_diff(y)).pow(2)) + .sum(); if sum == 0 && a.len() == b.len() { return f64::INFINITY; } @@ -354,7 +424,11 @@ pub(super) fn adapter(device: &ID3D12Device) -> (String, u32, u32) { match desc { Ok(d) => { let name = String::from_utf16_lossy(&d.Description); - (name.trim_end_matches('\0').to_owned(), d.VendorId, d.DeviceId) + ( + name.trim_end_matches('\0').to_owned(), + d.VendorId, + d.DeviceId, + ) } Err(_) => ("unknown".into(), 0, 0), } @@ -371,7 +445,10 @@ mod tests { let v = (1023u32 | 512 << 10).to_le_bytes(); assert_eq!(rgb(1, 1, 4, 24, &v).unwrap(), [255, 128, 0]); // 1.0, 0.5 and -1.0 as halves. - assert_eq!(rgb(1, 1, 8, 10, &[0, 0x3c, 0, 0x38, 0, 0xbc, 0, 0]).unwrap(), [255, 127, 0]); + assert_eq!( + rgb(1, 1, 8, 10, &[0, 0x3c, 0, 0x38, 0, 0xbc, 0, 0]).unwrap(), + [255, 127, 0] + ); assert!(rgb(1, 1, 4, 41, &[0; 4]).is_none()); assert!(rgb(2, 2, 8, 28, &[0; 12]).is_none(), "too few rows"); assert_eq!(psnr(&[1, 2], &[1, 2]), f64::INFINITY); diff --git a/crates/victory-gpu/src/replay/hook.rs b/crates/victory-gpu/src/replay/hook.rs index e4ceca4..e18c3c3 100644 --- a/crates/victory-gpu/src/replay/hook.rs +++ b/crates/victory-gpu/src/replay/hook.rs @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; /// Methods in a copied table: more than any D3D12 interface has (an /// interface's private methods may follow its public ones). -pub(super) const SLOTS: usize = 192; +pub(super) const SLOTS: usize = 512; /// Entries copied from before the table (type information). const PRE: usize = 4; @@ -64,9 +64,24 @@ fn readable(at: usize, most: usize) -> usize { // SAFETY: a plain query. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; // SAFETY: as above. - let n = unsafe { VirtualQuery(end as *const c_void, &mut info, size_of::()) }; - const READ: u32 = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; - if n == 0 || info.State != MEM_COMMIT || info.Protect & READ == 0 || info.Protect & PAGE_GUARD != 0 { + let n = unsafe { + VirtualQuery( + end as *const c_void, + &mut info, + size_of::(), + ) + }; + const READ: u32 = PAGE_READONLY + | PAGE_READWRITE + | PAGE_WRITECOPY + | PAGE_EXECUTE_READ + | PAGE_EXECUTE_READWRITE + | PAGE_EXECUTE_WRITECOPY; + if n == 0 + || info.State != MEM_COMMIT + || info.Protect & READ == 0 + || info.Protect & PAGE_GUARD != 0 + { break; } end = info.BaseAddress as usize + info.RegionSize; @@ -81,21 +96,32 @@ fn readable(at: usize, most: usize) -> usize { /// # Safety /// `this` is a live COM object no other thread uses yet; what `patch` puts /// into the table are functions of the methods' types. -pub(super) unsafe fn install(this: *mut c_void, state: *const c_void, patch: impl FnOnce(&mut [usize; SLOTS])) -> bool { +pub(super) unsafe fn install( + this: *mut c_void, + state: *const c_void, + patch: impl FnOnce(&mut [usize; SLOTS]), +) -> bool { let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: a live COM object starts with its table's address. let at = unsafe { *this.cast::() }; if made.contains(&at) { return false; } - let mut new = Box::new(Shim { state, orig: at as *const usize, pre: [0; PRE], table: [0; SLOTS] }); + let mut new = Box::new(Shim { + state, + orig: at as *const usize, + pre: [0; PRE], + table: [0; SLOTS], + }); let have = readable(at, SLOTS * 8) / 8; // SAFETY: `have` entries are readable; the object's table is at least // as long as its interface, and what lies behind it is only copied. unsafe { std::ptr::copy_nonoverlapping(at as *const usize, new.table.as_mut_ptr(), have) }; if readable(at - PRE * 8, PRE * 8) == PRE * 8 { // SAFETY: as above. - unsafe { std::ptr::copy_nonoverlapping((at as *const usize).sub(PRE), new.pre.as_mut_ptr(), PRE) }; + unsafe { + std::ptr::copy_nonoverlapping((at as *const usize).sub(PRE), new.pre.as_mut_ptr(), PRE) + }; } patch(&mut new.table); let new: &'static Shim = Box::leak(new); @@ -130,14 +156,20 @@ pub(super) unsafe fn ours(this: *mut c_void) -> bool { /// /// # Safety /// As [`install`]; `before` is a shim's table. -pub(super) unsafe fn again(this: *mut c_void, before: usize, patch: impl FnOnce(&mut [usize; SLOTS])) { +pub(super) unsafe fn again( + this: *mut c_void, + before: usize, + patch: impl FnOnce(&mut [usize; SLOTS]), +) { // SAFETY: the caller's. unsafe { let now = table(this); if now == before { return; } - let shim = (before as *const u8).sub(std::mem::offset_of!(Shim, table)).cast::(); + let shim = (before as *const u8) + .sub(std::mem::offset_of!(Shim, table)) + .cast::(); if (*shim).orig as usize == now { this.cast::().write(before); } else { @@ -223,14 +255,28 @@ mod tests { value: u64, } - unsafe extern "system" fn add(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + unsafe extern "system" fn add( + this: *mut c_void, + a: u64, + b: u64, + c: u64, + d: u64, + e: f64, + ) -> u64 { // SAFETY: one of the test's objects. unsafe { (*this.cast::()).value + a + b + c + d + e as u64 } } type Add = unsafe extern "system" fn(*mut c_void, u64, u64, u64, u64, f64) -> u64; - unsafe extern "system" fn double(this: *mut c_void, a: u64, b: u64, c: u64, d: u64, e: f64) -> u64 { + unsafe extern "system" fn double( + this: *mut c_void, + a: u64, + b: u64, + c: u64, + d: u64, + e: f64, + ) -> u64 { // SAFETY: an object with a shim whose first method is `add`. unsafe { let first = orig::<[Add; 1]>(this)[0]; @@ -249,9 +295,17 @@ mod tests { #[test] fn one_object_is_changed_and_changed_back() { static STATE: u64 = 1000; - let vtbl = Vtbl { methods: [add as *const () as usize; 8] }; - let mut a = Object { vtbl: &vtbl, value: 100 }; - let mut b = Object { vtbl: &vtbl, value: 200 }; + let vtbl = Vtbl { + methods: [add as *const () as usize; 8], + }; + let mut a = Object { + vtbl: &vtbl, + value: 100, + }; + let mut b = Object { + vtbl: &vtbl, + value: 200, + }; // SAFETY: the test's objects; entries of `Add`'s type. unsafe { let this: *mut c_void = (&raw mut a).cast(); @@ -260,7 +314,10 @@ mod tests { t[2] = noted_entry::<{ QUEUE * SLOTS + 2 }>(); }; assert!(install(this, (&raw const STATE).cast(), patch)); - assert!(!install(this, (&raw const STATE).cast(), patch), "only once"); + assert!( + !install(this, (&raw const STATE).cast(), patch), + "only once" + ); assert_eq!(call(&mut a, 0), 230 + 1000); assert_eq!(call(&mut a, 1), 115); assert_eq!(call(&mut b, 0), 215, "other objects are untouched"); @@ -277,7 +334,9 @@ mod tests { again(this, shim, patch); assert_eq!(table(this), shim); // Or to another table. - let other = Vtbl { methods: [add as *const () as usize; 8] }; + let other = Vtbl { + methods: [add as *const () as usize; 8], + }; a.vtbl = &other; again(this, shim, patch); assert!(ours(this) && table(this) != shim); diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index c7c7131..8543f6a 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -21,8 +21,13 @@ use windows::core::Interface; use super::edit::{self, Clamp, RESULTS}; use super::gpu::{self, Seen, Worker}; use super::snap::read_sub; -use super::states::{self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, UNORDERED_ACCESS}; -use super::wire::{self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot}; +use super::states::{ + self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States, + UNORDERED_ACCESS, +}; +use super::wire::{ + self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot, +}; /// The name of the argument clamp's pipeline, by which its passes are /// recognised. @@ -151,14 +156,32 @@ impl Report { /// The report as text. pub fn text(&self, what: &str) -> String { let mut t = String::new(); - let ms = |v: &[f64]| v.iter().map(|x| format!("{x:.2}")).collect::>().join(" "); - let _ = writeln!(t, "{what}: {:.2} ms on the card (median of {})", self.median_ms(), self.frame_ms.len()); + let ms = |v: &[f64]| { + v.iter() + .map(|x| format!("{x:.2}")) + .collect::>() + .join(" ") + }; + let _ = writeln!( + t, + "{what}: {:.2} ms on the card (median of {})", + self.median_ms(), + self.frame_ms.len() + ); let _ = writeln!(t, " loops, ms: {}", ms(&self.frame_ms)); let (busy, delta) = (median(&self.busy_ms), median(&self.delta_ms)); let idle = (self.median_ms() - busy - delta).max(0.0); - let _ = writeln!(t, " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms"); + let _ = writeln!( + t, + " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms" + ); let _ = writeln!(t, " by submission (lists: ms): {}", { - self.submits.iter().enumerate().map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")).collect::>().join(", ") + self.submits + .iter() + .enumerate() + .map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}")) + .collect::>() + .join(", ") }); if !self.categories.is_empty() { let _ = writeln!(t, " by kind of command, ms (commands):"); @@ -173,8 +196,13 @@ impl Report { } } match self.picture { - Some((_, true)) => drop(writeln!(t, " picture: the same bytes as presented")), - Some((db, false)) => drop(writeln!(t, " picture: differs from the presented one, PSNR {db:.1} dB")), + Some((_, true)) => _ = writeln!(t, " picture: the same bytes as presented"), + Some((db, false)) => { + _ = writeln!( + t, + " picture: differs from the presented one, PSNR {db:.1} dB" + ) + } None => {} } for n in &self.notes { @@ -197,14 +225,20 @@ pub fn find(folder: &Path) -> Result { return Ok(folder.to_owned()); } let mut best: Option<(u32, PathBuf)> = None; - for entry in std::fs::read_dir(folder).with_context(|| format!("{}", folder.display()))?.flatten() { + for entry in std::fs::read_dir(folder) + .with_context(|| format!("{}", folder.display()))? + .flatten() + { let name = entry.file_name().to_string_lossy().into_owned(); - let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { continue }; + let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else { + continue; + }; if entry.path().join("frame.bin").exists() && best.as_ref().is_none_or(|b| b.0 < n) { best = Some((n, entry.path())); } } - best.map(|b| b.1).ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) + best.map(|b| b.1) + .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) } /// Loads a capture and runs it: the whole of `victory replay`. The reports, @@ -214,9 +248,19 @@ pub fn replay(folder: &Path, options: &Options) -> Result> let mut out = Vec::new(); if options.compare && options.edited() { let image = Some(player.folder.join("replay-unchanged.png")); - out.push(("unchanged".into(), player.run(&Options { image, ..options.plain() })?)); + out.push(( + "unchanged".into(), + player.run(&Options { + image, + ..options.plain() + })?, + )); } - let what = if options.edited() { "with the experiments" } else { "unchanged" }; + let what = if options.edited() { + "with the experiments" + } else { + "unchanged" + }; out.push((what.into(), player.run(options)?)); Ok(out) } @@ -292,14 +336,19 @@ impl Player { let (device, info) = make_device(&frame, options.debug)?; // SAFETY: plain creation and queries. let (queue, frequency) = unsafe { - let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { - Type: D3D12_COMMAND_LIST_TYPE_DIRECT, - ..Default::default() - })?; + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; let frequency = queue.GetTimestampFrequency()? as f64; (queue, frequency) }; - let commands: Vec> = frame.lists.iter().map(|l| Cmd::all(&l.commands.0)).collect::>()?; + let commands: Vec> = frame + .lists + .iter() + .map(|l| Cmd::all(&l.commands.0)) + .collect::>()?; let mut player = Player { folder, worker: Worker::new(&device, &queue)?, @@ -324,7 +373,11 @@ impl Player { results: None, commands, fresh: true, - notes: frame.notes.iter().map(|n| format!("recorder: {n}")).collect(), + notes: frame + .notes + .iter() + .map(|n| format!("recorder: {n}")) + .collect(), frame, }; player.check()?; @@ -344,8 +397,15 @@ impl Player { step("contents", &mut at); player.make_masters()?; step("copies to restore from", &mut at); - let steps: Vec = steps.iter().map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())).collect(); - player.notes.push(format!("loaded in {:.1} s: {}", began.elapsed().as_secs_f64(), steps.join(", "))); + let steps: Vec = steps + .iter() + .map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())) + .collect(); + player.notes.push(format!( + "loaded in {:.1} s: {}", + began.elapsed().as_secs_f64(), + steps.join(", ") + )); Ok(player) } @@ -356,16 +416,39 @@ impl Player { /// Says what of the frame is not there. fn check(&mut self) -> Result<()> { - let missing = self.frame.submits.iter().flat_map(|s| &s.lists).filter(|&&l| l == MISSING).count(); + let missing = self + .frame + .submits + .iter() + .flat_map(|s| &s.lists) + .filter(|&&l| l == MISSING) + .count(); if missing > 0 { - self.note(format!("{missing} lists of the frame were not recorded: the frame is incomplete")); + self.note(format!( + "{missing} lists of the frame were not recorded: the frame is incomplete" + )); } if self.frame.submits.is_empty() { bail!("the capture has no submission"); } - let unknown = self.commands.iter().flatten().filter(|c| matches!(c, Cmd::RootView { va: Va::Unknown { .. }, .. })).count(); + let unknown = self + .commands + .iter() + .flatten() + .filter(|c| { + matches!( + c, + Cmd::RootView { + va: Va::Unknown { .. }, + .. + } + ) + }) + .count(); if unknown > 0 { - self.note(format!("{unknown} root views name memory in no known buffer: they are null in the replay")); + self.note(format!( + "{unknown} root views name memory in no known buffer: they are null in the replay" + )); } Ok(()) } @@ -394,7 +477,10 @@ impl Player { MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; - let card = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let card = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; match (gpu::seen(p), buffers) { (Seen::ReadBack, _) => gpu::to_props(p), (_, Buffers::Card) if buffer => card, @@ -415,7 +501,12 @@ impl Player { textures.insert(heap); } } - self.frame.heaps.iter().map(|h| h.id).filter(|id| !textures.contains(id)).collect() + self.frame + .heaps + .iter() + .map(|h| h.id) + .filter(|id| !textures.contains(id)) + .collect() }; for h in &self.frame.heaps { let desc = D3D12_HEAP_DESC { @@ -426,7 +517,8 @@ impl Player { }; let mut heap: Option = None; // SAFETY: plain creation. - unsafe { self.device.CreateHeap(&desc, &mut heap) }.with_context(|| format!("heap {}", h.id))?; + unsafe { self.device.CreateHeap(&desc, &mut heap) } + .with_context(|| format!("heap {}", h.id))?; self._heaps.extend(heap.map(|heap| (h.id, heap))); } let mut failed = 0; @@ -443,25 +535,65 @@ impl Player { let result = unsafe { match &r.place { Place::Placed { heap, offset } => match self._heaps.get(heap) { - Some(h) => self.device.CreatePlacedResource(h, *offset, &desc, D3D12_RESOURCE_STATE_COMMON, clear, &mut made), + Some(h) => self.device.CreatePlacedResource( + h, + *offset, + &desc, + D3D12_RESOURCE_STATE_COMMON, + clear, + &mut made, + ), None => Err(windows::core::Error::empty()), }, Place::Committed { props: p, flags } => { let p = props(p, is_buffer); - let state = if p.Type == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_COMMON }; - self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAGS(flags & !DROP), &desc, state, clear, &mut made) + let state = if p.Type == D3D12_HEAP_TYPE_READBACK { + D3D12_RESOURCE_STATE_COPY_DEST + } else { + D3D12_RESOURCE_STATE_COMMON + }; + self.device.CreateCommittedResource( + &p, + D3D12_HEAP_FLAGS(flags & !DROP), + &desc, + state, + clear, + &mut made, + ) } Place::BackBuffer {} => { - let p = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - self.device.CreateCommittedResource(&p, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + let p = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + self.device.CreateCommittedResource( + &p, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) } } }; match (result, made) { (Ok(()), Some(res)) => { // SAFETY: a live resource. - let va = if is_buffer { unsafe { res.GetGPUVirtualAddress() } } else { 0 }; - self.objects.insert(r.id, Object { res, va, index, subs: gpu::subresources(&r.desc) }); + let va = if is_buffer { + unsafe { res.GetGPUVirtualAddress() } + } else { + 0 + }; + self.objects.insert( + r.id, + Object { + res, + va, + index, + subs: gpu::subresources(&r.desc), + }, + ); } (e, _) => { if failed == 0 { @@ -483,7 +615,8 @@ impl Player { fn make_pipelines(&mut self) -> Result<()> { for (id, blob) in &self.frame.roots { // SAFETY: a blob the host took. - let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }.with_context(|| format!("root signature {id}"))?; + let root = unsafe { self.device.CreateRootSignature(0, &blob.0) } + .with_context(|| format!("root signature {id}"))?; self.roots.insert(*id, root); } for s in &self.frame.signatures { @@ -495,11 +628,18 @@ impl Player { }; let mut made: Option = None; // SAFETY: a description the host took. - unsafe { self.device.CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? }; + unsafe { + self.device + .CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)? + }; self.signatures.extend(made.map(|m| (s.id, m))); } for q in &self.frame.query_heaps { - let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE(q.kind), Count: q.count, NodeMask: 0 }; + let desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE(q.kind), + Count: q.count, + NodeMask: 0, + }; let mut made: Option = None; // SAFETY: plain creation. unsafe { self.device.CreateQueryHeap(&desc, &mut made)? }; @@ -510,7 +650,9 @@ impl Player { let next = AtomicUsize::new(0); type Made = std::result::Result; let made: std::sync::Mutex> = std::sync::Mutex::default(); - let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).max(1); + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get() / 2) + .max(1); let (frame, roots) = (&self.frame, &self.roots); std::thread::scope(|scope| { for _ in 0..threads { @@ -522,8 +664,11 @@ impl Player { read_at(&file, &mut bytes, c.at).ok()?; Some(bytes) }; - let m = super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); - made.lock().unwrap_or_else(|e| e.into_inner()).push((p.id, m)); + let m = + super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code); + made.lock() + .unwrap_or_else(|e| e.into_inner()) + .push((p.id, m)); } }); } @@ -536,7 +681,11 @@ impl Player { } } if let Some((id, e)) = refused.first() { - let n = format!("{} pipelines could not be made again, first {}: {e}", refused.len(), self.pipeline_name(*id)); + let n = format!( + "{} pipelines could not be made again, first {}: {e}", + refused.len(), + self.pipeline_name(*id) + ); self.note(n); } Ok(()) @@ -549,7 +698,15 @@ impl Player { return format!("pipeline {id}"); }; let code: Vec = self.hashes(p); - format!("{} (DXIL {})", if p.name.is_empty() { "unnamed" } else { &p.name }, code.join(" ")) + format!( + "{} (DXIL {})", + if p.name.is_empty() { + "unnamed" + } else { + &p.name + }, + code.join(" ") + ) } fn hashes(&self, p: &wire::Pipeline) -> Vec { @@ -580,23 +737,45 @@ impl Player { (slot::CBV, described) => { let mut d: D3D12_CONSTANT_BUFFER_VIEW_DESC = Default::default(); if described && let Some(o) = self.objects.get(&s.res) { - d = s.desc.as_ptr().cast::().read_unaligned(); + d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); d.BufferLocation = o.va + s.address(); } self.device.CreateConstantBufferView(Some(&d), at); } (slot::SRV, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); self.device.CreateShaderResourceView(res, Some(&d), at); } - (slot::SRV, false) if res.is_some() => self.device.CreateShaderResourceView(res, None, at), + (slot::SRV, false) if res.is_some() => { + self.device.CreateShaderResourceView(res, None, at) + } (slot::UAV, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); - self.device.CreateUnorderedAccessView(res, counter, Some(&d), at); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); + self.device + .CreateUnorderedAccessView(res, counter, Some(&d), at); + } + (slot::UAV, false) if res.is_some() => { + self.device + .CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at) } - (slot::UAV, false) if res.is_some() => self.device.CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at), (slot::SAMPLER, true) => { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); self.device.CreateSampler(&d, at); } _ if sampler => { @@ -615,7 +794,12 @@ impl Player { ViewDimension: D3D12_UAV_DIMENSION_BUFFER, ..Default::default() }; - self.device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&d), at); + self.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&d), + at, + ); } _ => { let d = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -624,7 +808,8 @@ impl Player { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; - self.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); + self.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at); } } } @@ -635,7 +820,12 @@ 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(); + 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 (id, i) in replaced.iter().filter(|k| k.0 == h.id) { let k = h.runs.partition_point(|run| run.0 <= *i); @@ -650,9 +840,17 @@ impl Player { let mut versions: Vec> = vec![Vec::new()]; let mut touched: HashSet<(u32, u32)> = HashSet::new(); for s in &self.frame.submits { - let live = |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); - let news: Vec<&(u32, u32, Slot)> = s.views.iter().filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)).collect(); - if news.iter().any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) { + let live = + |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE); + let news: Vec<&(u32, u32, Slot)> = s + .views + .iter() + .filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v)) + .collect(); + if news + .iter() + .any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i))) + { versions.push(Vec::new()); touched.clear(); } @@ -671,7 +869,12 @@ impl Player { let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0; let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind); let make = |flags| -> windows::core::Result { - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: h.count, Flags: flags, NodeMask: 0 }; + let d = D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: h.count, + Flags: flags, + NodeMask: 0, + }; // SAFETY: plain creation. unsafe { self.device.CreateDescriptorHeap(&d) } }; @@ -680,24 +883,29 @@ impl Player { unsafe { let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize; let start = cpu.GetCPUDescriptorHandleForHeapStart(); - let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i as usize * step }; + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + i as usize * step, + }; self.view(&Slot::EMPTY, start, sampler); let mut filled = 1; while filled < h.count { let n = filled.min(h.count - filled).min(1 << 16); // Sources and destinations do not overlap. - self.device.CopyDescriptorsSimple(n, at(filled), start, kind); + self.device + .CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } for (first, n, s) in &h.runs { self.view(s, at(*first), sampler); for i in 1..*n { - self.device.CopyDescriptorsSimple(1, at(first + i), at(*first), kind); + self.device + .CopyDescriptorsSimple(1, at(first + i), at(*first), kind); } } let mut all = Vec::new(); for changes in &versions { - let mine: Vec<&(u32, u32, Slot)> = changes.iter().filter(|(id, _, _)| *id == h.id).collect(); + let mine: Vec<&(u32, u32, Slot)> = + changes.iter().filter(|(id, _, _)| *id == h.id).collect(); for (_, i, s) in &mine { if *i < h.count { self.view(s, at(*i), sampler); @@ -706,7 +914,10 @@ impl Player { if mine.is_empty() && let Some(Version { heap, gpu }) = all.last() { - let same = Version { heap: ID3D12DescriptorHeap::clone(heap), gpu: *gpu }; + let same = Version { + heap: ID3D12DescriptorHeap::clone(heap), + gpu: *gpu, + }; all.push(same); continue; } @@ -716,15 +927,30 @@ impl Player { // 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); + 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); + self.device.CopyDescriptorsSimple( + h.count, + heap.GetCPUDescriptorHandleForHeapStart(), + start, + kind, + ); let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; all.push(Version { heap, gpu }); } @@ -733,10 +959,15 @@ 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())); + 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")); + 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; 2] = Default::default(); @@ -746,8 +977,8 @@ impl Player { views[0].extend(colors); views[1].extend(depth); } - Cmd::ClearTarget { view, .. } => drop(views[0].insert(*view)), - Cmd::ClearDepth { view, .. } => drop(views[1].insert(*view)), + Cmd::ClearTarget { view, .. } => _ = views[0].insert(*view), + Cmd::ClearDepth { view, .. } => _ = views[1].insert(*view), _ => {} } } @@ -755,8 +986,15 @@ impl Player { if all.is_empty() { continue; } - let kind = [D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_TYPE_DSV][i]; - let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: all.len() as u32, ..Default::default() }; + let kind = [ + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + ][i]; + let d = D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: all.len() as u32, + ..Default::default() + }; // SAFETY: plain creation; slots of the heap just made. unsafe { let heap: ID3D12DescriptorHeap = self.device.CreateDescriptorHeap(&d)?; @@ -765,23 +1003,43 @@ impl Player { for s in all { let res = self.objects.get(&s.res).map(|o| &o.res); if i == 0 { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); // Without either there is nothing to make a view of. let null = D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT(28), ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, ..Default::default() }; - let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + let d = if s.described != 0 { + Some(&d as *const _) + } else if res.is_none() { + Some(&null as *const _) + } else { + None + }; self.device.CreateRenderTargetView(res, d, at); } else { - let d = s.desc.as_ptr().cast::().read_unaligned(); + let d = s + .desc + .as_ptr() + .cast::() + .read_unaligned(); let null = D3D12_DEPTH_STENCIL_VIEW_DESC { Format: DXGI_FORMAT(40), ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, ..Default::default() }; - let d = if s.described != 0 { Some(&d as *const _) } else if res.is_none() { Some(&null as *const _) } else { None }; + let d = if s.described != 0 { + Some(&d as *const _) + } else if res.is_none() { + Some(&null as *const _) + } else { + None + }; self.device.CreateDepthStencilView(res, d, at); } self.targets.insert(*s, at); @@ -821,7 +1079,12 @@ impl Player { } let mut stagings: Vec<(ID3D12Resource, usize, u64)> = Vec::new(); for _ in 0..batches.len().min(2) { - let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_UPLOAD, most, D3D12_RESOURCE_FLAG_NONE)?; + let (b, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_UPLOAD, + most, + D3D12_RESOURCE_FLAG_NONE, + )?; stagings.push((b, data as usize, 0)); } for (n, batch) in batches.iter().enumerate() { @@ -836,11 +1099,19 @@ impl Player { while let Some(&(i, at)) = batch.get(next.fetch_add(1, Ordering::Relaxed)) { let (_, len, from) = &parts[i]; // SAFETY: this part's own bytes of the mapping. - let to = unsafe { std::slice::from_raw_parts_mut((map + at as usize) as *mut u8, *len as usize) }; + let to = unsafe { + std::slice::from_raw_parts_mut( + (map + at as usize) as *mut u8, + *len as usize, + ) + }; if *from == ZERO { to.fill(0); } else if let Err(e) = read_at(file, to, *from) { - failed.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(e); + failed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert(e); } } }); @@ -849,7 +1120,10 @@ impl Player { if let Some(e) = failed.into_inner().unwrap_or_else(|e| e.into_inner()) { return Err(e).context("the capture's contents"); } - let list: Vec<(&T, u64, u64)> = batch.iter().map(|&(i, at)| (&parts[i].0, parts[i].1, at)).collect(); + let list: Vec<(&T, u64, u64)> = batch + .iter() + .map(|&(i, at)| (&parts[i].0, parts[i].1, at)) + .collect(); let buffer = stagings[k].0.clone(); // The worker is another part of the player than `copy` uses. let other = Worker::new(&self.device, &self.worker.queue)?; @@ -869,9 +1143,16 @@ impl Player { 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 (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { + continue; + }; 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 }); + 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 .frame @@ -896,7 +1177,9 @@ impl Player { let file = File::open(self.folder.join("contents.bin"))?; self.upload(&textures, &file, |player, list, parts, staging| { for (c, len, at) in parts { - let Some(o) = player.objects.get(&c.res) else { continue }; + let Some(o) = player.objects.get(&c.res) else { + continue; + }; let r = &player.frame.resources[o.index]; // SAFETY: an open list; live resources. unsafe { @@ -904,11 +1187,23 @@ impl Player { list.CopyBufferRegion(&o.res, c.first, staging, *at, *len); continue; } - let (all, _) = gpu::footprints(&player.device, &gpu::to_desc(&r.desc), c.first as u32, c.count); + let (all, _) = gpu::footprints( + &player.device, + &gpu::to_desc(&r.desc), + c.first as u32, + c.count, + ); for (i, mut f) in all.into_iter().enumerate() { f.Offset += at; let to = gpu::sub_location(&o.res, c.first as u32 + i as u32); - list.CopyTextureRegion(&to, 0, 0, 0, &gpu::placed_location(staging, f), None); + list.CopyTextureRegion( + &to, + 0, + 0, + 0, + &gpu::placed_location(staging, f), + None, + ); } } } @@ -916,7 +1211,9 @@ impl Player { // To the states of the frame's start. 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 }; + let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else { + continue; + }; if !r.idle && known.contains(&r.id) { gpu::moves(&o.res, &[COPY_DEST], state, &mut back); } @@ -928,13 +1225,21 @@ impl Player { } })?; if missing > 0 { - self.note(format!("contents of {missing} parts of resources that could not be made are left out")); + self.note(format!( + "contents of {missing} parts of resources that could not be made are left out" + )); } // 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 named = self.named_buffers(); - let of = |s: &wire::Submit| s.deltas.iter().filter(|d| named.contains(&d.res)).cloned().collect::>(); + let of = |s: &wire::Submit| { + s.deltas + .iter() + .filter(|d| named.contains(&d.res)) + .cloned() + .collect::>() + }; // 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 = self @@ -946,17 +1251,25 @@ impl Player { .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::>(); + let pages = |d: &Delta| { + (d.at / 4096..(d.at + d.len).div_ceil(4096)) + .map(|p| (d.res, p)) + .collect::>() + }; first.iter().for_each(|d| seen.extend(pages(d))); let mut rest: Vec> = vec![Vec::new()]; for s in self.frame.submits.iter().skip(1) { - let (early, late): (Vec, Vec) = - of(s).into_iter().partition(|d| upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p))); + let (early, late): (Vec, Vec) = 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(); + 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) { @@ -977,7 +1290,12 @@ impl Player { } } if total > 0 { - let (buffer, _) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, total, D3D12_RESOURCE_FLAG_NONE)?; + let (buffer, _) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; self.deltas = Some(buffer.clone()); self.upload(&later, &file, |_, list, parts, staging| { for ((to, _), len, at) in parts { @@ -1001,22 +1319,28 @@ impl Player { 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::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::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)), + Cmd::ResolveQuery { dst, .. } => _ = named.insert(*dst), _ => {} } } @@ -1041,15 +1365,27 @@ impl Player { states.add(r.id, subs, r.state[0], decays); if r.state.len() > 1 { for (i, s) in r.state.iter().enumerate() { - states.change(&states::Change { res: r.id, sub: i as u32, after: *s, promoted: false, alias: false }); + states.change(&states::Change { + res: r.id, + sub: i as u32, + after: *s, + promoted: false, + alias: false, + }); } } } // Resources in a state they are written in at some time, or written // some other way. - const WRITE: u32 = RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; - let mut written: HashSet = - self.frame.resources.iter().filter(|r| r.state.iter().any(|s| s & WRITE != 0)).map(|r| r.id).collect(); + const WRITE: u32 = + RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST; + let mut written: HashSet = self + .frame + .resources + .iter() + .filter(|r| r.state.iter().any(|s| s & WRITE != 0)) + .map(|r| r.id) + .collect(); 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] { @@ -1061,19 +1397,38 @@ impl Player { match c { Cmd::Barriers { all } => { for b in all { - if let Barrier::Transition { res, before, after, .. } = b + if let Barrier::Transition { + res, before, after, .. + } = b && (*before | *after) as u32 & WRITE != 0 { written.insert(*res); } } } - Cmd::CopyBuffer { dst, .. } | Cmd::CopyResource { dst, .. } | Cmd::ResolveQuery { dst, .. } => drop(written.insert(*dst)), - Cmd::CopyTexture { dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, .. } => drop(written.insert(*res)), - Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => drop(written.insert(*dst)), - Cmd::RootView { kind: slot::UAV, va: Va::At { res, .. }, .. } => drop(written.insert(*res)), + Cmd::CopyBuffer { dst, .. } + | Cmd::CopyResource { dst, .. } + | Cmd::ResolveQuery { dst, .. } => _ = written.insert(*dst), + Cmd::CopyTexture { + dst: Loc::Sub { res, .. } | Loc::Placed { res, .. }, + .. + } => _ = written.insert(*res), + Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => { + _ = written.insert(*dst) + } + Cmd::RootView { + kind: slot::UAV, + va: Va::At { res, .. }, + .. + } => _ = written.insert(*res), Cmd::WriteImmediate { all } => { - written.extend(all.iter().filter_map(|(va, _, _)| if let Va::At { res, .. } = va { Some(*res) } else { None })); + written.extend(all.iter().filter_map(|(va, _, _)| { + if let Va::At { res, .. } = va { + Some(*res) + } else { + None + } + })); } _ => {} } @@ -1085,15 +1440,28 @@ impl Player { } } // Buffers any unordered-access view names. - let is_buffer = - |id: u32| self.objects.get(&id).is_some_and(|o| self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0); - let simultaneous = |id: u32| { + let is_buffer = |id: u32| { self.objects.get(&id).is_some_and(|o| { - self.frame.resources[o.index].desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0 + self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 }) }; - let views = self.frame.descriptor_heaps.iter().flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); - let late = self.frame.submits.iter().flat_map(|s| s.views.iter().map(|(_, _, s)| s)); + let simultaneous = |id: u32| { + self.objects.get(&id).is_some_and(|o| { + self.frame.resources[o.index].desc.flags + & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 + != 0 + }) + }; + let views = self + .frame + .descriptor_heaps + .iter() + .flat_map(|h| h.runs.iter().map(|(_, _, s)| s)); + let late = self + .frame + .submits + .iter() + .flat_map(|s| s.views.iter().map(|(_, _, s)| s)); for s in views.chain(late).filter(|s| s.kind == slot::UAV) { for id in [s.res, s.counter] { if is_buffer(id) || simultaneous(id) { @@ -1102,7 +1470,8 @@ impl Player { } } for id in self.start.keys() { - self.end.insert(*id, states.get(*id).unwrap_or(vec![COMMON])); + self.end + .insert(*id, states.get(*id).unwrap_or(vec![COMMON])); } let mut ids: Vec = written .into_iter() @@ -1140,12 +1509,22 @@ impl Player { ..Default::default() } } else { - D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + } }; let mut made: Option = None; // SAFETY: plain creation. let result = unsafe { - self.device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut made) + self.device.CreateCommittedResource( + &props, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut made, + ) }; match (result, made) { (Ok(()), Some(m)) => { @@ -1153,10 +1532,17 @@ impl Player { in_pc += if pc { size } else { 0 }; self.masters.push((id, m)); } - (e, _) => self.note(format!("no copy of resource {id} to restore it from ({e:?})")), + (e, _) => self.note(format!( + "no copy of resource {id} to restore it from ({e:?})" + )), } } - tracing::info!(resources = self.masters.len(), mb = total >> 20, in_pc_memory_mb = in_pc >> 20, "copies of what the frame changes"); + tracing::info!( + resources = self.masters.len(), + mb = total >> 20, + in_pc_memory_mb = in_pc >> 20, + "copies of what the frame changes" + ); // Filled now: the resources are as at the frame's start. Masters // stay in the copy-source state (buffers decay). let (masters, objects, start) = (&self.masters, &self.objects, &self.start); @@ -1165,7 +1551,10 @@ impl Player { for (id, m) in some { let Some(state) = start.get(id) else { continue }; let o = &objects[id]; - let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = state + .iter() + .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }) + .collect(); gpu::moves(&o.res, state, &to, &mut before); gpu::moves(&o.res, &to, state, &mut after); before.push(gpu::transition(m, ALL, COMMON, COPY_DEST)); @@ -1191,8 +1580,12 @@ impl Player { // 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()?; + let adapter: IDXGIAdapter3 = factory + .EnumAdapterByLuid(self.device.GetAdapterLuid()) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; } Some(own.Budget.saturating_sub(own.CurrentUsage)) } @@ -1202,10 +1595,17 @@ impl Player { if self.fresh { return Ok(()); } - let restored: HashMap = if contents { self.masters.iter().map(|(id, m)| (*id, m)).collect() } else { HashMap::new() }; - let (mut idle, mut into, mut back, mut plain) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let restored: HashMap = if contents { + self.masters.iter().map(|(id, m)| (*id, m)).collect() + } else { + HashMap::new() + }; + let (mut idle, mut into, mut back, mut plain) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new()); for (id, start) in &self.start { - let Some(o) = self.objects.get(id) else { continue }; + let Some(o) = self.objects.get(id) else { + continue; + }; let end = self.end.get(id).unwrap_or(start); if restored.contains_key(id) { gpu::moves(&o.res, end, &[COPY_DEST], &mut into); @@ -1236,23 +1636,39 @@ impl Player { } fn pipelines_named(&self, name: &str) -> HashSet { - self.frame.pipelines.iter().filter(|p| p.name == name).map(|p| p.id).collect() + self.frame + .pipelines + .iter() + .filter(|p| p.name == name) + .map(|p| p.id) + .collect() } /// The frame's lists, edited: for each submission, its lists' commands. - fn edited(&mut self, o: &Options, report: &mut Report, clamps: &[Vec]) -> Vec>> { + fn edited( + &mut self, + o: &Options, + report: &mut Report, + clamps: &[Vec], + ) -> Vec>> { let skip: HashSet = self .frame .pipelines .iter() .filter(|p| { let hashes = self.hashes(p); - o.skip_shaders.iter().any(|s| !s.is_empty() && (p.name.contains(s.as_str()) || hashes.iter().any(|h| h.contains(s.as_str())))) + o.skip_shaders.iter().any(|s| { + !s.is_empty() + && (p.name.contains(s.as_str()) + || hashes.iter().any(|h| h.contains(s.as_str()))) + }) }) .map(|p| p.id) .collect(); if !o.skip_shaders.is_empty() { - report.notes.push(format!("{} pipelines match --skip-shader", skip.len())); + report + .notes + .push(format!("{} pipelines match --skip-shader", skip.len())); } let hash = self.pipelines_named(COMPARE); let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0); @@ -1268,7 +1684,9 @@ impl Player { lists.push(edit::barriers_only(cmds)); continue; } - if o.skip_clamps && let Some(c) = clamps.get(here as usize) { + if o.skip_clamps + && let Some(c) = clamps.get(here as usize) + { cmds = edit::skip_clamps(cmds, c); } let mut n; @@ -1293,16 +1711,24 @@ impl Player { out.push(lists); } if !skip.is_empty() { - report.notes.push(format!("--skip-shader left out {skipped} commands")); + report + .notes + .push(format!("--skip-shader left out {skipped} commands")); } if o.skip_hash_passes { - report.notes.push(format!("--skip-hash-passes left out {hashed} dispatches")); + report + .notes + .push(format!("--skip-hash-passes left out {hashed} dispatches")); } if o.no_barriers { - report.notes.push(format!("--no-barriers left out {uavs} unordered-access barriers")); + report.notes.push(format!( + "--no-barriers left out {uavs} unordered-access barriers" + )); } if o.merge_barriers { - report.notes.push(format!("--merge-barriers joined {merged} barrier calls to ones before them")); + report.notes.push(format!( + "--merge-barriers joined {merged} barrier calls to ones before them" + )); } out } @@ -1325,11 +1751,22 @@ impl Player { submits.push(lists); } let n: usize = clamps.iter().map(Vec::len).sum(); - report.notes.push(format!("--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", next >> 10)); + report.notes.push(format!( + "--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run", + next >> 10 + )); if n == 0 { return Ok(clamps); } - self.results = Some(gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, next, D3D12_RESOURCE_FLAG_NONE)?.0); + self.results = Some( + gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + next, + D3D12_RESOURCE_FLAG_NONE, + )? + .0, + ); let built = self.build(&submits, &Options::default())?; self.restore(true)?; self.send(&built, false)?; @@ -1344,15 +1781,32 @@ impl Player { let count: usize = submits .iter() .flatten() - .map(|c| 2 + if o.detailed { c.iter().filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })).count() } else { 0 }) + .map(|c| { + 2 + if o.detailed { + c.iter() + .filter(|c| c.works() || matches!(c, Cmd::Barriers { .. })) + .count() + } else { + 0 + } + }) .sum::() + 2 * submits.len(); let mut heap: Option = None; - let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: count.max(1) as u32, NodeMask: 0 }; + let desc = D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: count.max(1) as u32, + NodeMask: 0, + }; // SAFETY: plain creation. unsafe { self.device.CreateQueryHeap(&desc, &mut heap)? }; let heap = heap.context("no timestamps")?; - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, count.max(1) as u64 * 8, D3D12_RESOURCE_FLAG_NONE)?; + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + count.max(1) as u64 * 8, + D3D12_RESOURCE_FLAG_NONE, + )?; let mut next = 0u32; let mut steps = Vec::new(); for (i, lists) in submits.iter().enumerate() { @@ -1365,7 +1819,9 @@ impl Player { let mut seen = HashSet::new(); let mut after = Vec::new(); for (d, at) in parts { - let Some(ob) = self.objects.get(&d.res) else { continue }; + let Some(ob) = self.objects.get(&d.res) else { + 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 @@ -1382,7 +1838,8 @@ 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))); built.push(self.close(open, &heap, &mut next, stamps)?); } steps.push((delta, built)); @@ -1405,12 +1862,27 @@ impl Player { let open = self.plain_list()?; // SAFETY: an open list; `next` queries were written. unsafe { - open.1.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, next.max(1), &back, 0); + open.1.ResolveQueryData( + &heap, + D3D12_QUERY_TYPE_TIMESTAMP, + 0, + next.max(1), + &back, + 0, + ); open.1.Close()?; } open }; - Ok(Sends { steps, joints, resolve, _heap: heap, _back: back, data: data as usize, count: next }) + Ok(Sends { + steps, + joints, + resolve, + _heap: heap, + _back: back, + data: data as usize, + count: next, + }) } /// Records a wait for everything before, with all caches written out. @@ -1422,7 +1894,10 @@ impl Player { unsafe { let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); let size = size_of::() as u32; - let known = self.device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size).is_ok(); + let known = self + .device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size) + .is_ok(); if known && o.EnhancedBarriersSupported.as_bool() && let Ok(list) = list.cast::() @@ -1436,7 +1911,9 @@ impl Player { list.Barrier(&[D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_GLOBAL, NumBarriers: 1, - Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: all.as_ptr() }, + Anonymous: D3D12_BARRIER_GROUP_0 { + pGlobalBarriers: all.as_ptr(), + }, }]); } else { list.ResourceBarrier(&[alias(), uav_barrier(None)]); @@ -1447,13 +1924,24 @@ impl Player { fn plain_list(&self) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> { // SAFETY: plain creation. unsafe { - let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list = self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; Ok((allocator, list)) } } - fn open(&self, heap: &ID3D12QueryHeap, next: &mut u32) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { + fn open( + &self, + heap: &ID3D12QueryHeap, + next: &mut u32, + ) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> { let (allocator, list) = self.plain_list()?; // SAFETY: an open list; a query of the heap. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next) }; @@ -1471,10 +1959,17 @@ impl Player { // SAFETY: as above. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next); - list.Close().context("a list of the frame could not be recorded again")?; + list.Close() + .context("a list of the frame could not be recorded again")?; } *next += 1; - Ok(Built { _allocator: allocator, list, first, last: *next - 1, stamps }) + Ok(Built { + _allocator: allocator, + list, + first, + last: *next - 1, + stamps, + }) } /// Records commands into a list, in submission `submit`. @@ -1499,7 +1994,11 @@ impl Player { .frame .signatures .iter() - .filter(|s| s.args.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)) + .filter(|s| { + s.args + .iter() + .any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32) + }) .map(|s| s.id) .collect(); let mut stamps = Vec::new(); @@ -1518,13 +2017,21 @@ impl Player { let category = match c { Cmd::Barriers { .. } => "barriers", Cmd::Dispatch { .. } if clamps.contains(&bound) => "argument clamps (ours)", - Cmd::Dispatch { .. } if compares.contains(&bound) => "hash and compare passes (ours)", + Cmd::Dispatch { .. } if compares.contains(&bound) => { + "hash and compare passes (ours)" + } Cmd::Dispatch { .. } => "dispatches", - Cmd::Indirect { signature, .. } if dispatches.contains(signature) => "indirect dispatches", + Cmd::Indirect { signature, .. } if dispatches.contains(signature) => { + "indirect dispatches" + } Cmd::Indirect { .. } if mesh.contains(&bound) => "indirect mesh draws", Cmd::Indirect { .. } => "indirect draws", - Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => "draws", - Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => "clears", + Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => { + "draws" + } + Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => { + "clears" + } Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves", _ => "copies", }; @@ -1542,8 +2049,19 @@ impl Player { // SAFETY: the caller's. unsafe { match c { - Cmd::Draw { vertices, instances, first, first_instance } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), - Cmd::DrawIndexed { indices, instances, first, base, first_instance } => { + Cmd::Draw { + vertices, + instances, + first, + first_instance, + } => l.DrawInstanced(*vertices, *instances, *first, *first_instance), + Cmd::DrawIndexed { + indices, + instances, + first, + base, + first_instance, + } => { l.DrawIndexedInstanced(*indices, *instances, *first, *base, *first_instance); } Cmd::Dispatch { groups } => l.Dispatch(groups[0], groups[1], groups[2]), @@ -1552,7 +2070,13 @@ impl Player { l.DispatchMesh(groups[0], groups[1], groups[2]); } } - Cmd::CopyBuffer { dst, dst_at, src, src_at, len } => { + Cmd::CopyBuffer { + dst, + dst_at, + src, + src_at, + len, + } => { if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { l.CopyBufferRegion(dst, *dst_at, src, *src_at, *len); } @@ -1560,7 +2084,13 @@ impl Player { Cmd::CopyTexture { dst, at, src, part } => { let side = |loc: &Loc| match loc { Loc::Sub { res: id, sub } => Some(gpu::sub_location(res(*id)?, *sub)), - Loc::Placed { res: id, offset, format, size, pitch } => { + Loc::Placed { + res: id, + offset, + format, + size, + pitch, + } => { let f = D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT(*format), Width: size[0], @@ -1568,12 +2098,32 @@ impl Player { Depth: size[2], RowPitch: *pitch, }; - Some(gpu::placed_location(res(*id)?, D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: *offset, Footprint: f })) + Some(gpu::placed_location( + res(*id)?, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: *offset, + Footprint: f, + }, + )) } }; if let (Some(dst), Some(src)) = (side(dst), side(src)) { - let part = part.map(|p| D3D12_BOX { left: p[0], top: p[1], front: p[2], right: p[3], bottom: p[4], back: p[5] }); - l.CopyTextureRegion(&dst, at[0], at[1], at[2], &src, part.as_ref().map(|p| p as *const _)); + let part = part.map(|p| D3D12_BOX { + left: p[0], + top: p[1], + front: p[2], + right: p[3], + bottom: p[4], + back: p[5], + }); + l.CopyTextureRegion( + &dst, + at[0], + at[1], + at[2], + &src, + part.as_ref().map(|p| p as *const _), + ); } } Cmd::CopyResource { dst, src } => { @@ -1581,27 +2131,63 @@ impl Player { l.CopyResource(dst, src); } } - Cmd::Resolve { dst, dst_sub, src, src_sub, format } => { + Cmd::Resolve { + dst, + dst_sub, + src, + src_sub, + format, + } => { if let (Some(dst), Some(src)) = (res(*dst), res(*src)) { l.ResolveSubresource(dst, *dst_sub, src, *src_sub, DXGI_FORMAT(*format)); } } - Cmd::ResolveRegion { dst, dst_sub, at, src, src_sub, part, format, mode } => { - if let (Some(dst), Some(src), Ok(l)) = (res(*dst), res(*src), l.cast::()) { + Cmd::ResolveRegion { + dst, + dst_sub, + at, + src, + src_sub, + part, + format, + mode, + } => { + if let (Some(dst), Some(src), Ok(l)) = + (res(*dst), res(*src), l.cast::()) + { let part = part.map(to_rect); let part = part.as_ref().map(|r| r as *const _); - l.ResolveSubresourceRegion(dst, *dst_sub, at[0], at[1], src, *src_sub, part, DXGI_FORMAT(*format), D3D12_RESOLVE_MODE(*mode)); + l.ResolveSubresourceRegion( + dst, + *dst_sub, + at[0], + at[1], + src, + *src_sub, + part, + DXGI_FORMAT(*format), + D3D12_RESOLVE_MODE(*mode), + ); } } Cmd::Topology { kind } => l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(*kind)), Cmd::Viewports { all } => { let all: Vec = all .iter() - .map(|v| D3D12_VIEWPORT { TopLeftX: v[0], TopLeftY: v[1], Width: v[2], Height: v[3], MinDepth: v[4], MaxDepth: v[5] }) + .map(|v| D3D12_VIEWPORT { + TopLeftX: v[0], + TopLeftY: v[1], + Width: v[2], + Height: v[3], + MinDepth: v[4], + MaxDepth: v[5], + }) .collect(); l.RSSetViewports(&all); } - Cmd::Scissors { all } => l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()), + Cmd::Scissors { all } => { + l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::>()) + } Cmd::BlendFactor { factor } => l.OMSetBlendFactor(factor.as_ref()), Cmd::StencilRef { value } => l.OMSetStencilRef(*value), Cmd::DepthBounds { min, max } => { @@ -1615,27 +2201,52 @@ impl Player { } } Cmd::Barriers { all } => { - let all: Vec = all.iter().filter_map(|b| self.barrier(b)).collect(); + let all: Vec = + all.iter().filter_map(|b| self.barrier(b)).collect(); barriers(l, &all); } Cmd::Heaps { heaps } => { - let all: Vec> = - heaps.iter().filter_map(|id| Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone()))).collect(); + let all: Vec> = heaps + .iter() + .filter_map(|id| { + Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone())) + }) + .collect(); l.SetDescriptorHeaps(&all); } Cmd::RootSignature { graphics, root } => { let root = self.roots.get(root); - if *graphics { l.SetGraphicsRootSignature(root) } else { l.SetComputeRootSignature(root) } + if *graphics { + l.SetGraphicsRootSignature(root) + } else { + l.SetComputeRootSignature(root) + } } - Cmd::Table { graphics, param, heap, slot } => { + Cmd::Table { + graphics, + param, + heap, + slot, + } => { if let Some((versions, step)) = self.descriptors.get(heap) && let Some(v) = versions.get(version) { - let at = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: v.gpu + u64::from(*slot) * step }; - if *graphics { l.SetGraphicsRootDescriptorTable(*param, at) } else { l.SetComputeRootDescriptorTable(*param, at) } + let at = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: v.gpu + u64::from(*slot) * step, + }; + if *graphics { + l.SetGraphicsRootDescriptorTable(*param, at) + } else { + l.SetComputeRootDescriptorTable(*param, at) + } } } - Cmd::Constants { graphics, param, offset, values } => { + Cmd::Constants { + graphics, + param, + offset, + values, + } => { let (n, data) = (values.len() as u32, values.as_ptr().cast()); if *graphics { l.SetGraphicsRoot32BitConstants(*param, n, data, *offset); @@ -1643,7 +2254,12 @@ impl Player { l.SetComputeRoot32BitConstants(*param, n, data, *offset); } } - Cmd::RootView { graphics, kind, param, va } => { + Cmd::RootView { + graphics, + kind, + param, + va, + } => { let va = self.va(va); match (*kind, *graphics) { (slot::CBV, true) => l.SetGraphicsRootConstantBufferView(*param, va), @@ -1655,14 +2271,20 @@ impl Player { } } Cmd::IndexBuffer { view } => { - let v = view.as_ref().map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { - BufferLocation: self.va(va), - SizeInBytes: *size, - Format: DXGI_FORMAT(*format), - }); + let v = view + .as_ref() + .map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW { + BufferLocation: self.va(va), + SizeInBytes: *size, + Format: DXGI_FORMAT(*format), + }); l.IASetIndexBuffer(v.as_ref().map(|v| v as *const _)); } - Cmd::VertexBuffers { start, views, count } => match views { + Cmd::VertexBuffers { + start, + views, + count, + } => match views { Some(views) => { let all: Vec = views .iter() @@ -1674,10 +2296,14 @@ impl Player { .collect(); l.IASetVertexBuffers(*start, Some(&all)); } - None => l.IASetVertexBuffers(*start, Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize])), + None => l.IASetVertexBuffers( + *start, + Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize]), + ), }, Cmd::Targets { colors, depth } => { - let colors: Vec = colors.iter().map(view).collect(); + let colors: Vec = + colors.iter().map(view).collect(); let depth = depth.as_ref().map(view); l.OMSetRenderTargets( colors.len() as u32, @@ -1686,26 +2312,50 @@ impl Player { depth.as_ref().map(|d| d as *const _), ); } - Cmd::ClearDepth { view: v, flags, depth, stencil, rects } => { + Cmd::ClearDepth { + view: v, + flags, + depth, + stencil, + rects, + } => { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let rects = (!rects.is_empty()).then_some(&rects[..]); if self.objects.contains_key(&v.res) { - l.ClearDepthStencilView(view(v), D3D12_CLEAR_FLAGS(*flags), *depth, *stencil, rects); + l.ClearDepthStencilView( + view(v), + D3D12_CLEAR_FLAGS(*flags), + *depth, + *stencil, + rects, + ); } } - Cmd::ClearTarget { view: v, color, rects } => { + Cmd::ClearTarget { + view: v, + color, + rects, + } => { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let rects = (!rects.is_empty()).then_some(&rects[..]); if self.objects.contains_key(&v.res) { l.ClearRenderTargetView(view(v), color, rects); } } - Cmd::Discard { res: id, rects, subs } => { + Cmd::Discard { + res: id, + rects, + subs, + } => { if let Some(r) = res(*id) { let rects: Vec = rects.iter().map(|r| to_rect(*r)).collect(); let region = subs.map(|s| D3D12_DISCARD_REGION { NumRects: rects.len() as u32, - pRects: if rects.is_empty() { std::ptr::null() } else { rects.as_ptr() }, + pRects: if rects.is_empty() { + std::ptr::null() + } else { + rects.as_ptr() + }, FirstSubresource: s[0], NumSubresources: s[1], }); @@ -1722,24 +2372,51 @@ impl Player { l.EndQuery(h, D3D12_QUERY_TYPE(*kind), *index); } } - Cmd::ResolveQuery { heap, kind, first, count, dst, at } => { + Cmd::ResolveQuery { + heap, + kind, + first, + count, + dst, + at, + } => { if let (Some(h), Some(dst)) = (self.queries.get(heap), res(*dst)) { l.ResolveQueryData(h, D3D12_QUERY_TYPE(*kind), *first, *count, dst, *at); } } - Cmd::Indirect { signature, most, args, at, count, count_at } => { + Cmd::Indirect { + signature, + most, + args, + at, + count, + count_at, + } => { if let (Some(s), Some(a)) = (self.signatures.get(signature), res(*args)) { l.ExecuteIndirect(s, *most, a, *at, res(*count), *count_at); } } Cmd::WriteImmediate { all } => { if let Ok(l) = l.cast::() { - let all: Vec<&(Va, u32, i32)> = all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); - let params: Vec = - all.iter().map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: self.va(va), Value: *v }).collect(); - let modes: Vec = all.iter().map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)).collect(); + let all: Vec<&(Va, u32, i32)> = + all.iter().filter(|(va, _, _)| self.va(va) != 0).collect(); + let params: Vec = all + .iter() + .map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: self.va(va), + Value: *v, + }) + .collect(); + let modes: Vec = all + .iter() + .map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m)) + .collect(); if !params.is_empty() { - l.WriteBufferImmediate(params.len() as u32, params.as_ptr(), Some(modes.as_ptr())); + l.WriteBufferImmediate( + params.len() as u32, + params.as_ptr(), + Some(modes.as_ptr()), + ); } } } @@ -1749,20 +2426,38 @@ impl Player { fn barrier(&self, b: &Barrier) -> Option { Some(match b { - Barrier::Transition { flags, res, sub, before, after } => { - let mut t = gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); + Barrier::Transition { + flags, + res, + sub, + before, + after, + } => { + let mut t = + gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32); t.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); t } Barrier::Uav { flags, res } => { - let mut u = uav_barrier(if *res == NONE { None } else { Some(self.resource(*res)?) }); + let mut u = uav_barrier(if *res == NONE { + None + } else { + Some(self.resource(*res)?) + }); u.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags); u } - Barrier::Alias { flags, before, after } => { + Barrier::Alias { + flags, + before, + after, + } => { let side = |id: &u32| -> std::mem::ManuallyDrop> { // SAFETY: a borrowed pointer (or none) never released. - self.resource(*id).map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }) + self.resource(*id) + .map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { + std::mem::transmute_copy(r) + }) }; D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, @@ -1811,17 +2506,28 @@ impl Player { for all in &submissions { self.worker.queue.ExecuteCommandLists(all); } - self.worker.queue.ExecuteCommandLists(&[cast(&s.resolve.1)?]); + self.worker + .queue + .ExecuteCommandLists(&[cast(&s.resolve.1)?]); } - self.worker.idle().context("the card was lost running the frame")?; + self.worker + .idle() + .context("the card was lost running the frame")?; // SAFETY: the mapping of `count` resolved timestamps. Ok(unsafe { std::slice::from_raw_parts(s.data as *const u64, s.count as usize) }.to_vec()) } /// Runs the frame as the options say. pub fn run(&mut self, o: &Options) -> Result { - let mut report = Report { notes: self.notes.clone(), ..Default::default() }; - let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { Vec::new() }; + let mut report = Report { + notes: self.notes.clone(), + ..Default::default() + }; + let clamps = if o.skip_clamps { + self.clamp_results(&mut report)? + } else { + Vec::new() + }; let submits = self.edited(o, &mut report, &clamps); let built = self.build(&submits, o)?; let mut stamps = Vec::new(); @@ -1829,20 +2535,33 @@ impl Player { self.restore(o.restore)?; self.fresh = false; stamps = self.send(&built, o.one_submit)?; - let ms = |a: u32, b: u32| stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency; + let ms = |a: u32, b: u32| { + stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency + }; let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); let (Some(first), Some(last)) = (lists.first(), lists.last()) else { bail!("no lists to run"); }; let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); - report.delta_ms.push(delta.filter(|d| d.first > first.first).map(|d| ms(d.first, d.last)).sum()); + report.delta_ms.push( + delta + .filter(|d| d.first > first.first) + .map(|d| ms(d.first, d.last)) + .sum(), + ); report.frame_ms.push(ms(first.first, last.last)); let each = |l: &[Built]| match (l.first(), l.last()) { (Some(a), Some(b)) => ms(a.first, b.last), _ => 0.0, }; - report.submits = built.steps.iter().map(|(_, l)| (l.len(), each(l))).collect(); - report.busy_ms.push(report.submits.iter().map(|s| s.1).sum()); + report.submits = built + .steps + .iter() + .map(|(_, l)| (l.len(), each(l))) + .collect(); + report + .busy_ms + .push(report.submits.iter().map(|s| s.1).sum()); } if o.detailed { self.detail(&built, &stamps, o, &mut report); @@ -1871,12 +2590,21 @@ impl Player { } } } - report.categories = kinds.into_iter().map(|(k, (ms, n))| (k.to_owned(), ms, n)).collect(); + report.categories = kinds + .into_iter() + .map(|(k, (ms, n))| (k.to_owned(), ms, n)) + .collect(); report.categories.sort_by(|a, b| b.1.total_cmp(&a.1)); - let mut all: Vec<(f64, u32, u32)> = shaders.into_iter().map(|(pso, (ms, n))| (ms, n, pso)).collect(); + let mut all: Vec<(f64, u32, u32)> = shaders + .into_iter() + .map(|(pso, (ms, n))| (ms, n, pso)) + .collect(); all.sort_by(|a, b| b.0.total_cmp(&a.0)); all.truncate(o.top); - report.shaders = all.into_iter().map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))).collect(); + report.shaders = all + .into_iter() + .map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))) + .collect(); } /// Saves the presented picture and compares it with the recorded one. @@ -1886,17 +2614,28 @@ impl Player { return Ok(()); }; let Some(bytes) = self.contents(p.res)? else { - report.notes.push("the presented texture is not there".into()); + report + .notes + .push("the presented texture is not there".into()); return Ok(()); }; let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else { - report.notes.push("the presented format is not shown".into()); + report + .notes + .push("the presented format is not shown".into()); return Ok(()); }; - let path = o.image.clone().unwrap_or_else(|| self.folder.join("replay.png")); + let path = o + .image + .clone() + .unwrap_or_else(|| self.folder.join("replay.png")); std::fs::write(&path, crate::capture::png(p.width, p.height, &rgb))?; let mut recorded = vec![0; bytes.len()]; - read_at(&File::open(self.folder.join("present.bin"))?, &mut recorded, p.file)?; + 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(); report.picture = Some((gpu::psnr(&rgb, &was), rows_equal(&p, &bytes, &recorded))); report.notes.push(format!( @@ -1924,8 +2663,17 @@ 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, sub, 1) }; - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; + 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. @@ -1944,12 +2692,18 @@ impl Player { } })?; // SAFETY: the buffer's mapping; the copy into it has run. - Ok(Some(unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec())) + Ok(Some( + unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec(), + )) } /// The id of the resource of a name (tests). pub fn named(&self, name: &str) -> Option { - self.frame.resources.iter().find(|r| r.name == name).map(|r| r.id) + self.frame + .resources + .iter() + .find(|r| r.name == name) + .map(|r| r.id) } } @@ -1978,7 +2732,12 @@ fn rows_equal(p: &wire::Present, a: &[u8], b: &[u8]) -> bool { } fn to_rect(r: [i32; 4]) -> RECT { - RECT { left: r[0], top: r[1], right: r[2], bottom: r[3] } + RECT { + left: r[0], + top: r[1], + right: r[2], + bottom: r[3], + } } /// # Safety @@ -1997,7 +2756,9 @@ fn uav_barrier(res: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER { Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { // SAFETY: a borrowed pointer (or none) never released. - pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { std::mem::transmute_copy(r) }), + pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe { + std::mem::transmute_copy(r) + }), }), }, } @@ -2042,7 +2803,9 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option Result<(ID3D12Device, Option = None; match &adapter { @@ -2081,13 +2847,19 @@ fn debug_messages(q: &ID3D12InfoQueue) -> Vec { let m = &*message; if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.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(); + 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(); } - seen.into_iter().map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")).collect() + seen.into_iter() + .map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}")) + .collect() } #[cfg(test)] @@ -2106,7 +2878,10 @@ mod tests { } // The last complete one; itself when named. assert_eq!(find(dir.path()).unwrap(), dir.path().join("capture-10")); - assert_eq!(find(&dir.path().join("capture-2")).unwrap(), dir.path().join("capture-2")); + assert_eq!( + find(&dir.path().join("capture-2")).unwrap(), + dir.path().join("capture-2") + ); } #[test] @@ -2125,7 +2900,11 @@ mod tests { assert!(t.contains("a frame: 11.00 ms"), "{t}"); assert!(t.contains("between submissions 1.50 ms"), "{t}"); assert!(t.contains("PSNR 40.0 dB"), "{t}"); - let o = Options { skip_clamps: true, buffers: Buffers::Card, ..Default::default() }; + let o = Options { + skip_clamps: true, + buffers: Buffers::Card, + ..Default::default() + }; assert!(o.edited() && !o.plain().edited() && o.plain().buffers == Buffers::Card); } } diff --git a/crates/victory-gpu/src/replay/pso.rs b/crates/victory-gpu/src/replay/pso.rs index c1baa0d..aec3fbc 100644 --- a/crates/victory-gpu/src/replay/pso.rs +++ b/crates/victory-gpu/src/replay/pso.rs @@ -55,7 +55,10 @@ pub(super) trait Keep { /// `at` points at a value of `size` bytes. unsafe fn plain(kind: i32, at: *const c_void, size: usize) -> Part { // SAFETY: the caller's. - Part::Plain { kind, data: Blob(unsafe { std::slice::from_raw_parts(at.cast::(), size) }.to_vec()) } + Part::Plain { + kind, + data: Blob(unsafe { std::slice::from_raw_parts(at.cast::(), size) }.to_vec()), + } } unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Option { @@ -63,8 +66,12 @@ unsafe fn code(kind: i32, c: &D3D12_SHADER_BYTECODE, keep: &mut dyn Keep) -> Opt return None; } // SAFETY: the description's own code. - let bytes = unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::(), c.BytecodeLength) }; - Some(Part::Code { kind, blob: keep.code(bytes) }) + let bytes = + unsafe { std::slice::from_raw_parts(c.pShaderBytecode.cast::(), c.BytecodeLength) }; + Some(Part::Code { + kind, + blob: keep.code(bytes), + }) } unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { @@ -72,34 +79,44 @@ unsafe fn layout(l: &D3D12_INPUT_LAYOUT_DESC) -> Option { return None; } // SAFETY: the description's own elements, with their names. - let elements = unsafe { std::slice::from_raw_parts(l.pInputElementDescs, l.NumElements as usize) } - .iter() - .map(|e| { - // SAFETY: as above. - let name = unsafe { e.SemanticName.to_string() }.unwrap_or_default(); - let rest = [ - e.SemanticIndex, - e.Format.0 as u32, - e.InputSlot, - e.AlignedByteOffset, - e.InputSlotClass.0 as u32, - e.InstanceDataStepRate, - ]; - (name, rest) - }) - .collect(); + let elements = + unsafe { std::slice::from_raw_parts(l.pInputElementDescs, l.NumElements as usize) } + .iter() + .map(|e| { + // SAFETY: as above. + let name = unsafe { e.SemanticName.to_string() }.unwrap_or_default(); + let rest = [ + e.SemanticIndex, + e.Format.0 as u32, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0 as u32, + e.InstanceDataStepRate, + ]; + (name, rest) + }) + .collect(); Some(Part::Layout { elements }) } /// # Safety /// A valid description. -pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { +pub(super) unsafe fn compute( + d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + keep: &mut dyn Keep, +) -> Vec { // SAFETY: the caller's description. unsafe { - let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + let mut parts = vec![Part::Root { + root: keep.root(std::mem::transmute_copy(&d.pRootSignature)), + }]; parts.extend(code(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0, &d.CS, keep)); if d.Flags.0 != 0 { - parts.push(plain(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0, (&raw const d.Flags).cast(), 4)); + parts.push(plain( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS.0, + (&raw const d.Flags).cast(), + 4, + )); } parts } @@ -107,27 +124,55 @@ pub(super) unsafe fn compute(d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, keep: &mut d /// # Safety /// A valid description. -pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut dyn Keep) -> Vec { +pub(super) unsafe fn graphics( + d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + keep: &mut dyn Keep, +) -> Vec { // SAFETY: the caller's description. unsafe { - let mut parts = vec![Part::Root { root: keep.root(std::mem::transmute_copy(&d.pRootSignature)) }]; + let mut parts = vec![Part::Root { + root: keep.root(std::mem::transmute_copy(&d.pRootSignature)), + }]; for (kind, c) in [(1, &d.VS), (2, &d.PS), (3, &d.DS), (4, &d.HS), (5, &d.GS)] { parts.extend(code(kind, c, keep)); } if d.StreamOutput.NumEntries != 0 { keep.lost("a pipeline's stream output"); } - parts.push(plain(8, (&raw const d.BlendState).cast(), size_of::())); + parts.push(plain( + 8, + (&raw const d.BlendState).cast(), + size_of::(), + )); parts.push(plain(9, (&raw const d.SampleMask).cast(), 4)); - parts.push(plain(10, (&raw const d.RasterizerState).cast(), size_of::())); - parts.push(plain(11, (&raw const d.DepthStencilState).cast(), size_of::())); + parts.push(plain( + 10, + (&raw const d.RasterizerState).cast(), + size_of::(), + )); + parts.push(plain( + 11, + (&raw const d.DepthStencilState).cast(), + size_of::(), + )); parts.extend(layout(&d.InputLayout)); parts.push(plain(13, (&raw const d.IBStripCutValue).cast(), 4)); parts.push(plain(14, (&raw const d.PrimitiveTopologyType).cast(), 4)); - let targets = D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }; - parts.push(plain(15, (&raw const targets).cast(), size_of::())); + let targets = D3D12_RT_FORMAT_ARRAY { + RTFormats: d.RTVFormats, + NumRenderTargets: d.NumRenderTargets, + }; + parts.push(plain( + 15, + (&raw const targets).cast(), + size_of::(), + )); parts.push(plain(16, (&raw const d.DSVFormat).cast(), 4)); - parts.push(plain(17, (&raw const d.SampleDesc).cast(), size_of::())); + parts.push(plain( + 17, + (&raw const d.SampleDesc).cast(), + size_of::(), + )); if d.Flags.0 != 0 { parts.push(plain(20, (&raw const d.Flags).cast(), 4)); } @@ -137,7 +182,10 @@ pub(super) unsafe fn graphics(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, keep: &mut /// # Safety /// A valid description. -pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn Keep) -> Vec { +pub(super) unsafe fn stream( + d: &D3D12_PIPELINE_STATE_STREAM_DESC, + keep: &mut dyn Keep, +) -> Vec { let base = d.pPipelineStateSubobjectStream.cast::().cast_const(); let mut parts = Vec::new(); let mut at = 0usize; @@ -147,7 +195,9 @@ pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn unsafe { let kind = base.add(at).cast::().read(); let Some(h) = holds(kind) else { - keep.lost(&format!("a pipeline stream's subobject of type {kind}, and those after it")); + keep.lost(&format!( + "a pipeline stream's subobject of type {kind}, and those after it" + )); break; }; let (from, size) = match h { @@ -158,12 +208,16 @@ pub(super) unsafe fn stream(d: &D3D12_PIPELINE_STATE_STREAM_DESC, keep: &mut dyn }; let value = base.add(at + from); match h { - Holds::Root => parts.push(Part::Root { root: keep.root(value.cast::<*mut c_void>().read()) }), + Holds::Root => parts.push(Part::Root { + root: keep.root(value.cast::<*mut c_void>().read()), + }), Holds::Code => parts.extend(code(kind, &*value.cast(), keep)), Holds::Layout => parts.extend(layout(&*value.cast())), Holds::Pointers(_) => { // A cached blob is only a shortcut. - let empty = std::slice::from_raw_parts(value, size).iter().all(|&b| b == 0); + let empty = std::slice::from_raw_parts(value, size) + .iter() + .all(|&b| b == 0); if kind != D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 && !empty { keep.lost(&format!("a pipeline stream's subobject of type {kind}")); } @@ -194,13 +248,15 @@ pub(super) fn make( match part { Part::Root { root: 0 } => {} Part::Root { root: id } => { - let r = root(*id).ok_or_else(|| format!("root signature {id} is not in the capture"))?; + let r = root(*id) + .ok_or_else(|| format!("root signature {id} is not in the capture"))?; bytes.extend([0u8; 8]); bytes.extend((r.as_raw() as usize).to_le_bytes()); roots.push(r); } Part::Code { kind, blob } => { - let c = code(*blob).ok_or_else(|| format!("shader {blob} is not in the capture"))?; + let c = + code(*blob).ok_or_else(|| format!("shader {blob} is not in the capture"))?; bytes.extend(kind.to_le_bytes()); bytes.extend([0u8; 4]); bytes.extend((c.as_ptr() as usize).to_le_bytes()); @@ -217,7 +273,9 @@ pub(super) fn make( .map(|(name, r)| { names.push(CString::new(name.as_str()).unwrap_or_default()); D3D12_INPUT_ELEMENT_DESC { - SemanticName: PCSTR(names.last().map_or(std::ptr::null(), |n| n.as_ptr().cast())), + SemanticName: PCSTR( + names.last().map_or(std::ptr::null(), |n| n.as_ptr().cast()), + ), SemanticIndex: r[0], Format: DXGI_FORMAT(r[1] as i32), InputSlot: r[2], @@ -227,7 +285,11 @@ pub(super) fn make( } }) .collect(); - bytes.extend(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0.to_le_bytes()); + bytes.extend( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT + .0 + .to_le_bytes(), + ); bytes.extend([0u8; 4]); bytes.extend((made.as_ptr() as usize).to_le_bytes()); bytes.extend((made.len() as u64).to_le_bytes()); @@ -237,13 +299,17 @@ pub(super) fn make( } bytes.resize(bytes.len().next_multiple_of(8), 0); // Aligned for the pointers in it. - let mut words: Vec = bytes.chunks_exact(8).map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let mut words: Vec = bytes + .chunks_exact(8) + .map(|c| u64::from_le_bytes(c.try_into().unwrap_or_default())) + .collect(); let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: words.len() * 8, pPipelineStateSubobjectStream: words.as_mut_ptr().cast(), }; // SAFETY: a stream of whole subobjects; all it points at is alive. - let made: windows::core::Result = unsafe { device.CreatePipelineState(&desc) }; + let made: windows::core::Result = + unsafe { device.CreatePipelineState(&desc) }; made.map_err(|e| e.to_string()) } @@ -290,17 +356,44 @@ mod tests { let bytes = [1u8, 2, 3]; let mut s = Stream { root: Sub(0, 77), - ms: Sub(25, D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: 3 }), + ms: Sub( + 25, + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: 3, + }, + ), blend: Sub(8, D3D12_BLEND_DESC::default()), mask: Sub(9, 5), - raster: Sub(10, D3D12_RASTERIZER_DESC { DepthBias: 6, ..Default::default() }), + raster: Sub( + 10, + D3D12_RASTERIZER_DESC { + DepthBias: 6, + ..Default::default() + }, + ), depth: Sub(11, D3D12_DEPTH_STENCIL_DESC::default()), - targets: Sub(15, D3D12_RT_FORMAT_ARRAY { NumRenderTargets: 3, ..Default::default() }), + targets: Sub( + 15, + D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: 3, + ..Default::default() + }, + ), dsv: Sub(16, DXGI_FORMAT(40)), - samples: Sub(17, DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }), + samples: Sub( + 17, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), unknown: Sub(99, 0), }; - let d = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: size_of::(), pPipelineStateSubobjectStream: (&raw mut s).cast() }; + let d = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut s).cast(), + }; let mut kept = Kept::default(); // SAFETY: the stream above. let parts = unsafe { stream(&d, &mut kept) }; @@ -309,9 +402,23 @@ mod tests { assert_eq!(parts.len(), 9); assert_eq!(parts[0], Part::Root { root: 77 }); assert_eq!(parts[1], Part::Code { kind: 25, blob: 0 }); - assert_eq!(parts[3], Part::Plain { kind: 9, data: Blob(5u32.to_le_bytes().to_vec()) }); - let Part::Plain { kind: 10, data } = &parts[4] else { panic!("{:?}", parts[4]) }; + assert_eq!( + parts[3], + Part::Plain { + kind: 9, + data: Blob(5u32.to_le_bytes().to_vec()) + } + ); + let Part::Plain { kind: 10, data } = &parts[4] else { + panic!("{:?}", parts[4]) + }; assert_eq!(data.0.len(), size_of::()); - assert_eq!(parts[7], Part::Plain { kind: 16, data: Blob(40u32.to_le_bytes().to_vec()) }); + assert_eq!( + parts[7], + Part::Plain { + kind: 16, + data: Blob(40u32.to_le_bytes().to_vec()) + } + ); } } diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index 799fe1e..c839d60 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -60,9 +60,17 @@ impl Settings { pub fn from_env() -> Option { 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); + let frames = std::env::var("VICTORY_RECORD_FRAMES") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(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 }) + Some(Settings { + folder, + at, + frames: std::cmp::max(frames, 1), + always, + }) } } @@ -148,11 +156,21 @@ impl Heap { if slots.is_null() { std::alloc::handle_alloc_error(layout); } - Heap { id, kind: desc.Type.0, count: desc.NumDescriptors, flags: desc.Flags.0, cpu, gpu, step, slots } + Heap { + id, + kind: desc.Type.0, + count: desc.NumDescriptors, + flags: desc.Flags.0, + cpu, + gpu, + step, + slots, + } } fn layout(count: u32) -> std::alloc::Layout { - std::alloc::Layout::array::(count.max(1) as usize).unwrap_or(std::alloc::Layout::new::()) + std::alloc::Layout::array::(count.max(1) as usize) + .unwrap_or(std::alloc::Layout::new::()) } pub(super) fn visible(&self) -> bool { @@ -202,8 +220,13 @@ pub(super) struct Heaps { impl Heaps { fn add(&mut self, heap: Arc) { let end = heap.cpu + heap.count as usize * heap.step; - let gone: Vec = - self.by_cpu.range(..end).rev().take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu).map(|(&k, _)| k).collect(); + let gone: Vec = self + .by_cpu + .range(..end) + .rev() + .take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu) + .map(|(&k, _)| k) + .collect(); for k in gone { self.by_cpu.remove(&k); } @@ -400,7 +423,12 @@ impl Recorder { signatures: Mutex::default(), queries: Mutex::default(), names: Mutex::default(), - codes: Mutex::new(Codes { file: Some(file), at: 0, index: HashMap::new(), all: Vec::new() }), + codes: Mutex::new(Codes { + file: Some(file), + at: 0, + index: HashMap::new(), + all: Vec::new(), + }), states: Mutex::default(), queues: Mutex::default(), device: Mutex::default(), @@ -433,7 +461,16 @@ impl Recorder { /// The problems so far. pub(super) fn problems(&self) -> Vec { - lock(&self.problems).iter().map(|(what, n)| if *n == 1 { what.clone() } else { format!("{what} ({n} times)") }).collect() + lock(&self.problems) + .iter() + .map(|(what, n)| { + if *n == 1 { + what.clone() + } else { + format!("{what} ({n} times)") + } + }) + .collect() } pub(super) fn arm(&self, on: bool) { @@ -444,6 +481,12 @@ impl Recorder { lock(&self.device).clone() } + /// Whether a list was made through the hooked device (the swap chain may + /// have others). + pub(super) fn knows(&self, p: Ptr) -> bool { + read(&self.lists).contains_key(&(p as usize)) + } + /// The state of a list, if its methods are still ours. pub(super) fn list(&self, p: Ptr) -> Option> { let state = read(&self.lists).get(&(p as usize)).cloned()?; @@ -461,7 +504,10 @@ impl Recorder { return Va::Null {}; } match read(&self.addresses).range(..=address).next_back() { - Some((&start, &(size, res))) if address - start < size => Va::At { res, offset: address - start }, + Some((&start, &(size, res))) if address - start < size => Va::At { + res, + offset: address - start, + }, _ => Va::Unknown { address }, } } @@ -498,13 +544,19 @@ impl Recorder { let id = self.id(); let seen = match &place { Place::Committed { props, .. } => gpu::seen(props), - Place::Placed { heap, .. } => lock(&self.heaps).get(heap).map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), + Place::Placed { heap, .. } => lock(&self.heaps) + .get(heap) + .map_or(gpu::Seen::No, |h| gpu::seen(&h.props)), Place::BackBuffer {} => gpu::Seen::No, }; let subs = gpu::subresources(&desc); let is_buffer = desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; // SAFETY: a live buffer. - let va = if is_buffer { unsafe { object.GetGPUVirtualAddress() } } else { 0 }; + let va = if is_buffer { + unsafe { object.GetGPUVirtualAddress() } + } else { + 0 + }; let placed = matches!(place, Place::Placed { .. }); let late = self.watching.load(Ordering::SeqCst); { @@ -520,13 +572,30 @@ impl Recorder { if va != 0 { write(&self.addresses).insert(va, (desc.width, id)); } - let res = Arc::new(Res { id, ptr: p as usize, place, desc, made_in, clear, subs, seen, late }); + let res = Arc::new(Res { + id, + ptr: p as usize, + place, + desc, + made_in, + clear, + subs, + seen, + late, + }); write(&self.resources).insert(id, res); self.ids.set(p as usize, id); if late { lock(&self.held).push(ID3D12Resource::clone(&object)); } - self.tell_gone(&*object, Gone::Resource { id, ptr: p as usize, va }); + self.tell_gone( + &*object, + Gone::Resource { + id, + ptr: p as usize, + va, + }, + ); id } @@ -557,12 +626,18 @@ impl Recorder { /// Has us told when an object dies. fn tell_gone(&self, object: &impl Interface, what: Gone) { const KEY: GUID = GUID::from_u128(0x3d0d5c1e_7a1b_4a53_9a3e_5f2b1e6b9c41); - let notice = Box::into_raw(Box::new(Notice { methods: &NOTICE, references: AtomicU32::new(1), what })); + let notice = Box::into_raw(Box::new(Notice { + methods: &NOTICE, + references: AtomicU32::new(1), + what, + })); // SAFETY: a COM object of ours with one reference, which this drops // at the end; the object takes its own. unsafe { let notice = IUnknown::from_raw(notice.cast()); - let set = object.cast::().and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); + let set = object + .cast::() + .and_then(|o| o.SetPrivateDataInterface(&KEY, ¬ice)); if set.is_err() { self.problem("an object's end cannot be followed"); std::mem::forget(notice); @@ -620,14 +695,21 @@ impl Recorder { } let i = codes.all.len() as u32; let at = codes.at; - let wrote = codes.file.as_mut().is_some_and(|f| f.write_all(bytes).is_ok()); + let wrote = codes + .file + .as_mut() + .is_some_and(|f| f.write_all(bytes).is_ok()); if !wrote { drop(codes); self.problem("shader code could not be written"); return u32::MAX; } codes.at += bytes.len() as u64; - codes.all.push(wire::Code { at, len: bytes.len() as u64, hash }); + codes.all.push(wire::Code { + at, + len: bytes.len() as u64, + hash, + }); codes.index.insert(hash, i); i } @@ -681,7 +763,11 @@ struct NoticeTable { add: unsafe extern "system" fn(Ptr) -> u32, release: unsafe extern "system" fn(Ptr) -> u32, } -static NOTICE: NoticeTable = NoticeTable { query: notice_query, add: notice_add, release: notice_release }; +static NOTICE: NoticeTable = NoticeTable { + query: notice_query, + add: notice_add, + release: notice_release, +}; unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> HRESULT { // SAFETY: COM's rules: a valid id and place for the answer. @@ -698,13 +784,21 @@ unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> unsafe extern "system" fn notice_add(this: Ptr) -> u32 { // SAFETY: one of ours, alive while a reference is. - unsafe { (*this.cast::()).references.fetch_add(1, Ordering::Relaxed) + 1 } + unsafe { + (*this.cast::()) + .references + .fetch_add(1, Ordering::Relaxed) + + 1 + } } unsafe extern "system" fn notice_release(this: Ptr) -> u32 { // SAFETY: as above; the last reference frees the box it was made as. unsafe { - let left = (*this.cast::()).references.fetch_sub(1, Ordering::AcqRel) - 1; + let left = (*this.cast::()) + .references + .fetch_sub(1, Ordering::AcqRel) + - 1; if left == 0 { let notice = Box::from_raw(this.cast::()); if let Some(r) = recorder() { @@ -831,10 +925,19 @@ macro_rules! not_recorded { fn device_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12Device_Vtbl.CreateCommandQueue = create_queue); - set!(t, ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics); - set!(t, ID3D12Device_Vtbl.CreateComputePipelineState = create_compute); + set!( + t, + ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics + ); + set!( + t, + ID3D12Device_Vtbl.CreateComputePipelineState = create_compute + ); set!(t, ID3D12Device_Vtbl.CreateCommandList = create_list); - set!(t, ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors); + set!( + t, + ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors + ); set!(t, ID3D12Device_Vtbl.CreateRootSignature = create_root); set!(t, ID3D12Device_Vtbl.CreateConstantBufferView = create_cbv); set!(t, ID3D12Device_Vtbl.CreateShaderResourceView = create_srv); @@ -843,12 +946,21 @@ fn device_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12Device_Vtbl.CreateDepthStencilView = create_dsv); set!(t, ID3D12Device_Vtbl.CreateSampler = create_sampler); set!(t, ID3D12Device_Vtbl.CopyDescriptors = copy_descriptors); - set!(t, ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple); - set!(t, ID3D12Device_Vtbl.CreateCommittedResource = create_committed); + set!( + t, + ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple + ); + set!( + t, + ID3D12Device_Vtbl.CreateCommittedResource = create_committed + ); set!(t, ID3D12Device_Vtbl.CreateHeap = create_heap); set!(t, ID3D12Device_Vtbl.CreatePlacedResource = create_placed); set!(t, ID3D12Device_Vtbl.CreateQueryHeap = create_queries); - set!(t, ID3D12Device_Vtbl.CreateCommandSignature = create_signature); + set!( + t, + ID3D12Device_Vtbl.CreateCommandSignature = create_signature + ); set!(t, ID3D12Device1_Vtbl.CreatePipelineLibrary = create_library); set!(t, ID3D12Device2_Vtbl.CreatePipelineState = create_stream); let _ = device_rest(t); @@ -889,8 +1001,14 @@ fn queue_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] } fn library_table(t: &mut [usize; hook::SLOTS]) { - set!(t, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics); - set!(t, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute); + set!( + t, + ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics + ); + set!( + t, + ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute + ); set!(t, ID3D12PipelineLibrary1_Vtbl.LoadPipeline = load_stream); } @@ -898,48 +1016,153 @@ fn list_table(t: &mut [usize; hook::SLOTS]) { set!(t, ID3D12GraphicsCommandList_Vtbl.Close = list_close); set!(t, ID3D12GraphicsCommandList_Vtbl.Reset = list_reset); set!(t, ID3D12GraphicsCommandList_Vtbl.DrawInstanced = draw); - set!(t, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed + ); set!(t, ID3D12GraphicsCommandList_Vtbl.Dispatch = dispatch); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture); - set!(t, ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource); - set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology + ); set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetViewports = viewports); - set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline + ); set!(t, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier = barrier); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute); - set!(t, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer); - set!(t, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers); - set!(t, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets); - set!(t, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth); - set!(t, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth + ); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target + ); set!(t, ID3D12GraphicsCommandList_Vtbl.DiscardResource = discard); set!(t, ID3D12GraphicsCommandList_Vtbl.BeginQuery = begin_query); set!(t, ID3D12GraphicsCommandList_Vtbl.EndQuery = end_query); - set!(t, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query); + set!( + t, + ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query + ); set!(t, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect = indirect); - set!(t, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region); - set!(t, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds); - set!(t, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate); - set!(t, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh); + set!( + t, + ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region + ); + set!( + t, + ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds + ); + set!( + t, + ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate + ); + set!( + t, + ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh + ); let _ = list_rest(t); } @@ -990,7 +1213,10 @@ pub(super) fn not_recorded_calls() -> Vec<(String, u64)> { for &(slot, name) in names { let what = match (class, name) { // Submissions are in order anyway: the replay has one queue. - (hook::QUEUE, "Wait") => "waits of the drawing queue (the swap chain makes some) are not replayed".to_owned(), + (hook::QUEUE, "Wait") => { + "waits of the drawing queue (the swap chain makes some) are not replayed" + .to_owned() + } _ => format!("{of} method {name} is not recorded, and was called"), }; all.push((what, hook::count(class, slot))); @@ -1011,7 +1237,12 @@ fn made(hr: HRESULT, out: Out) -> Option<(&'static Recorder, Ptr)> { Some((recorder()?, p)) } -unsafe extern "system" fn create_queue(this: Ptr, desc: *const D3D12_COMMAND_QUEUE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_queue( + this: Ptr, + desc: *const D3D12_COMMAND_QUEUE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: the caller's arguments, passed on; then a new queue no other // thread knows. unsafe { @@ -1037,9 +1268,14 @@ unsafe extern "system" fn create_list( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)(this, nodes, kind, allocator, pso, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)( + this, nodes, kind, allocator, pso, iid, out, + ); if let Some((r, p)) = made(hr, out) { - let state = Arc::new(ListState { kind: kind.0, inner: Mutex::default() }); + let state = Arc::new(ListState { + kind: kind.0, + inner: Mutex::default(), + }); // Every interface of it we hook, and the one it is submitted as. static ONE: OnceLock = OnceLock::new(); let iids = [ @@ -1049,21 +1285,32 @@ unsafe extern "system" fn create_list( ID3D12GraphicsCommandList4::IID, ID3D12GraphicsCommandList6::IID, ]; - let same = *ONE.get_or_init(|| iids.iter().all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p))); + let same = *ONE.get_or_init(|| { + iids.iter() + .all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p)) + }); let mut all = vec![p]; if !same { - all.extend(iids.iter().filter_map(|iid| query(p, iid)).map(|q| q.as_raw())); + all.extend( + iids.iter() + .filter_map(|iid| query(p, iid)) + .map(|q| q.as_raw()), + ); } { let mut inner = lock(&state.inner); - inner.whole = r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; + inner.whole = + r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT; begin(&mut inner, r, pso); } for q in all { // The state's address is kept for good, as the table is. hook::install(q, Arc::into_raw(state.clone()).cast(), list_table); write(&r.lists).insert(q as usize, state.clone()); - r.tell_gone(&*borrow::(q), Gone::List { ptr: q as usize }); + r.tell_gone( + &*borrow::(q), + Gone::List { ptr: q as usize }, + ); } } hr @@ -1075,11 +1322,20 @@ fn begin(inner: &mut ListInner, r: &Recorder, pso: Ptr) { inner.bytes = Vec::new(); inner.changes.clear(); if inner.whole && !pso.is_null() { - Cmd::Pipeline { pso: r.object(pso, "a pipeline") }.put(&mut inner.bytes); + Cmd::Pipeline { + pso: r.object(pso, "a pipeline"), + } + .put(&mut inner.bytes); } } -unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_library( + this: Ptr, + blob: *const c_void, + size: usize, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device1_Vtbl.CreatePipelineLibrary)(this, blob, size, iid, out); @@ -1095,7 +1351,12 @@ unsafe extern "system" fn create_library(this: Ptr, blob: *const c_void, size: u } } -unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_graphics( + this: Ptr, + desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above; the description is valid, as it was accepted. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateGraphicsPipelineState)(this, desc, iid, out); @@ -1106,7 +1367,12 @@ unsafe extern "system" fn create_graphics(this: Ptr, desc: *const D3D12_GRAPHICS } } -unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_compute( + this: Ptr, + desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateComputePipelineState)(this, desc, iid, out); @@ -1117,7 +1383,12 @@ unsafe extern "system" fn create_compute(this: Ptr, desc: *const D3D12_COMPUTE_P } } -unsafe extern "system" fn create_stream(this: Ptr, desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_stream( + this: Ptr, + desc: *const D3D12_PIPELINE_STATE_STREAM_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device2_Vtbl.CreatePipelineState)(this, desc, iid, out); @@ -1137,7 +1408,8 @@ unsafe extern "system" fn load_graphics( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); + let hr = + own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out); if let Some((r, p)) = made(hr, out) { r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r))); } @@ -1154,7 +1426,8 @@ unsafe extern "system" fn load_compute( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); + let hr = + own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out); if let Some((r, p)) = made(hr, out) { r.pipeline(p, pso::compute(&*desc, &mut Keeper(r))); } @@ -1179,13 +1452,24 @@ unsafe extern "system" fn load_stream( } } -unsafe extern "system" fn create_root(this: Ptr, nodes: u32, blob: *const c_void, size: usize, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_root( + this: Ptr, + nodes: u32, + blob: *const c_void, + size: usize, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); + let hr = + own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out); if let Some((r, p)) = made(hr, out) { // D3D12 may answer with an object it made before. - let known = r.ids.get(p as usize).filter(|id| lock(&r.roots).contains_key(id)); + let known = r + .ids + .get(p as usize) + .filter(|id| lock(&r.roots).contains_key(id)); let bytes = std::slice::from_raw_parts(blob.cast::(), size).to_vec(); let id = known.unwrap_or_else(|| r.id()); lock(&r.roots).insert(id, Arc::new(bytes)); @@ -1208,8 +1492,11 @@ unsafe extern "system" fn create_signature( if let Some((r, p)) = made(hr, out) { let id = r.id(); let d = &*desc; - let args: Vec<[u32; 4]> = - std::slice::from_raw_parts(d.pArgumentDescs.cast::<[u32; 4]>(), d.NumArgumentDescs as usize).to_vec(); + let args: Vec<[u32; 4]> = std::slice::from_raw_parts( + d.pArgumentDescs.cast::<[u32; 4]>(), + d.NumArgumentDescs as usize, + ) + .to_vec(); // Arguments that are GPU addresses lie in buffers; they are not // rewritten for a replay. let addresses = [ @@ -1219,31 +1506,63 @@ unsafe extern "system" fn create_signature( D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW, D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, ]; - if args.iter().any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) { + if args + .iter() + .any(|a| addresses.iter().any(|t| t.0 as u32 == a[0])) + { r.problem("a command signature with GPU addresses among its arguments: a replay reads the recorded addresses"); } - let root = if root.is_null() { NONE } else { r.object(root, "a root signature") }; - lock(&r.signatures).insert(id, wire::Signature { id, stride: d.ByteStride, args, root }); + let root = if root.is_null() { + NONE + } else { + r.object(root, "a root signature") + }; + lock(&r.signatures).insert( + id, + wire::Signature { + id, + stride: d.ByteStride, + args, + root, + }, + ); r.ids.set(p as usize, id); } hr } } -unsafe extern "system" fn create_queries(this: Ptr, desc: *const D3D12_QUERY_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_queries( + this: Ptr, + desc: *const D3D12_QUERY_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateQueryHeap)(this, desc, iid, out); if let Some((r, p)) = made(hr, out) { let id = r.id(); - lock(&r.queries).insert(id, wire::QueryHeap { id, kind: (*desc).Type.0, count: (*desc).Count }); + lock(&r.queries).insert( + id, + wire::QueryHeap { + id, + kind: (*desc).Type.0, + count: (*desc).Count, + }, + ); r.ids.set(p as usize, id); } hr } } -unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCRIPTOR_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_descriptors( + this: Ptr, + desc: *const D3D12_DESCRIPTOR_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateDescriptorHeap)(this, desc, iid, out); @@ -1252,18 +1571,34 @@ unsafe extern "system" fn create_descriptors(this: Ptr, desc: *const D3D12_DESCR let d = &*desc; let visible = d.Flags.0 & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0; let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr; - let gpu = if visible { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 }; - let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) as usize; + let gpu = if visible { + heap.GetGPUDescriptorHandleForHeapStart().ptr + } else { + 0 + }; + let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type) + as usize; let id = r.id(); write(&r.descriptors).add(Arc::new(Heap::new(id, d, cpu, gpu, step.max(1)))); r.ids.set(p as usize, id); - r.tell_gone(&*heap, Gone::Heap { id, ptr: p as usize }); + r.tell_gone( + &*heap, + Gone::Heap { + id, + ptr: p as usize, + }, + ); } hr } } -unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, iid: *const GUID, out: Out) -> HRESULT { +unsafe extern "system" fn create_heap( + this: Ptr, + desc: *const D3D12_HEAP_DESC, + iid: *const GUID, + out: Out, +) -> HRESULT { // SAFETY: as above. unsafe { let hr = own!(this, ID3D12Device_Vtbl.CreateHeap)(this, desc, iid, out); @@ -1277,7 +1612,13 @@ unsafe extern "system" fn create_heap(this: Ptr, desc: *const D3D12_HEAP_DESC, i } fn heap_of(id: u32, d: &D3D12_HEAP_DESC) -> wire::Heap { - wire::Heap { id, size: d.SizeInBytes, props: gpu::from_props(&d.Properties), alignment: d.Alignment, flags: d.Flags.0 } + wire::Heap { + id, + size: d.SizeInBytes, + props: gpu::from_props(&d.Properties), + alignment: d.Alignment, + flags: d.Flags.0, + } } unsafe fn clear_of(clear: *const D3D12_CLEAR_VALUE) -> Option<[u32; 5]> { @@ -1299,9 +1640,14 @@ unsafe extern "system" fn create_committed( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)(this, props, flags, desc, state, clear, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)( + this, props, flags, desc, state, clear, iid, out, + ); if let Some((r, p)) = made(hr, out) { - let place = Place::Committed { props: gpu::from_props(&*props), flags: flags.0 }; + let place = Place::Committed { + props: gpu::from_props(&*props), + flags: flags.0, + }; r.add(p, place, state.0, clear_of(clear)); } hr @@ -1321,7 +1667,9 @@ unsafe extern "system" fn create_placed( ) -> HRESULT { // SAFETY: as above. unsafe { - let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)(this, heap, offset, desc, state, clear, iid, out); + let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)( + this, heap, offset, desc, state, clear, iid, out, + ); if let Some((r, p)) = made(hr, out) { // One opened from memory was not seen made. let heap = r.ids.get(heap as usize).unwrap_or_else(|| { @@ -1338,23 +1686,50 @@ unsafe extern "system" fn create_placed( } } -unsafe extern "system" fn create_cbv(this: Ptr, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_cbv( + this: Ptr, + desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateConstantBufferView)(this, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { - r.set_view(at.ptr, &Slot::new(slot::CBV, NONE, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::CBV, + NONE, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_srv(this: Ptr, res: Ptr, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_srv( + this: Ptr, + res: Ptr, + desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateShaderResourceView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::SRV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::SRV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } @@ -1371,40 +1746,84 @@ unsafe extern "system" fn create_uav( own!(this, ID3D12Device_Vtbl.CreateUnorderedAccessView)(this, res, counter, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let (id, counter) = (r.resource(res), r.resource(counter)); - r.set_view(at.ptr, &Slot::new(slot::UAV, id, counter, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::UAV, + id, + counter, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_rtv(this: Ptr, res: Ptr, desc: *const D3D12_RENDER_TARGET_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_rtv( + this: Ptr, + res: Ptr, + desc: *const D3D12_RENDER_TARGET_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateRenderTargetView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::RTV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::RTV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_dsv(this: Ptr, res: Ptr, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_dsv( + this: Ptr, + res: Ptr, + desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateDepthStencilView)(this, res, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { let id = r.resource(res); - r.set_view(at.ptr, &Slot::new(slot::DSV, id, NONE, desc.cast(), size_of::())); + r.set_view( + at.ptr, + &Slot::new( + slot::DSV, + id, + NONE, + desc.cast(), + size_of::(), + ), + ); } } } -unsafe extern "system" fn create_sampler(this: Ptr, desc: *const D3D12_SAMPLER_DESC, at: D3D12_CPU_DESCRIPTOR_HANDLE) { +unsafe extern "system" fn create_sampler( + this: Ptr, + desc: *const D3D12_SAMPLER_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) { const _: () = assert!(size_of::() == 52); // SAFETY: as above. unsafe { own!(this, ID3D12Device_Vtbl.CreateSampler)(this, desc, at); if let Some(r) = recorder().filter(|_| !ours()) { - r.set_view(at.ptr, &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52)); + r.set_view( + at.ptr, + &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52), + ); } } } @@ -1439,12 +1858,21 @@ unsafe extern "system" fn copy_descriptors( // SAFETY: as above; the arrays have as many entries as the counts say, // and null sizes mean one descriptor each. unsafe { - own!(this, ID3D12Device_Vtbl.CopyDescriptors)(this, n_to, to, to_sizes, n_from, from, from_sizes, kind); + own!(this, ID3D12Device_Vtbl.CopyDescriptors)( + this, n_to, to, to_sizes, n_from, from, from_sizes, kind, + ); let Some(r) = recorder().filter(|_| !ours()) else { return; }; - let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; - let size = |sizes: *const u32, i: u32| if sizes.is_null() { 1 } else { *sizes.add(i as usize) }; + let step = + own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize; + let size = |sizes: *const u32, i: u32| { + if sizes.is_null() { + 1 + } else { + *sizes.add(i as usize) + } + }; let (mut i, mut j, mut done_to, mut done_from) = (0, 0, 0, 0); while i < n_to && j < n_from { let n = (size(to_sizes, i) - done_to).min(size(from_sizes, j) - done_from); @@ -1528,26 +1956,64 @@ unsafe extern "system" fn list_reset(this: Ptr, allocator: Ptr, pso: Ptr) -> HRE { let mut inner = lock(&state.inner); inner.closed = None; - inner.whole = r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; + inner.whole = + r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0; begin(&mut inner, r, pso); } hr } } -unsafe extern "system" fn draw(this: Ptr, vertices: u32, instances: u32, first: u32, first_instance: u32) { +unsafe extern "system" fn draw( + this: Ptr, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)(this, vertices, instances, first, first_instance); - note(this, |_| Cmd::Draw { vertices, instances, first, first_instance }); + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)( + this, + vertices, + instances, + first, + first_instance, + ); + note(this, |_| Cmd::Draw { + vertices, + instances, + first, + first_instance, + }); } } -unsafe extern "system" fn draw_indexed(this: Ptr, indices: u32, instances: u32, first: u32, base: i32, first_instance: u32) { +unsafe extern "system" fn draw_indexed( + this: Ptr, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)(this, indices, instances, first, base, first_instance); - note(this, |_| Cmd::DrawIndexed { indices, instances, first, base, first_instance }); + own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)( + this, + indices, + instances, + first, + base, + first_instance, + ); + note(this, |_| Cmd::DrawIndexed { + indices, + instances, + first, + base, + first_instance, + }); } } @@ -1567,11 +2033,26 @@ unsafe extern "system" fn dispatch_mesh(this: Ptr, x: u32, y: u32, z: u32) { } } -unsafe extern "system" fn copy_buffer(this: Ptr, dst: Ptr, dst_at: u64, src: Ptr, src_at: u64, len: u64) { +unsafe extern "system" fn copy_buffer( + this: Ptr, + dst: Ptr, + dst_at: u64, + src: Ptr, + src_at: u64, + len: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)(this, dst, dst_at, src, src_at, len); - note(this, |r| Cmd::CopyBuffer { dst: r.resource(dst), dst_at, src: r.resource(src), src_at, len }); + own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)( + this, dst, dst_at, src, src_at, len, + ); + note(this, |r| Cmd::CopyBuffer { + dst: r.resource(dst), + dst_at, + src: r.resource(src), + src_at, + len, + }); } } @@ -1580,11 +2061,20 @@ unsafe fn location(r: &Recorder, l: &D3D12_TEXTURE_COPY_LOCATION) -> Loc { unsafe { let res = r.resource(std::mem::transmute_copy::<_, Ptr>(&l.pResource)); if l.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { - return Loc::Sub { res, sub: l.Anonymous.SubresourceIndex }; + return Loc::Sub { + res, + sub: l.Anonymous.SubresourceIndex, + }; } let p = l.Anonymous.PlacedFootprint; let f = p.Footprint; - Loc::Placed { res, offset: p.Offset, format: f.Format.0, size: [f.Width, f.Height, f.Depth], pitch: f.RowPitch } + Loc::Placed { + res, + offset: p.Offset, + format: f.Format.0, + size: [f.Width, f.Height, f.Depth], + pitch: f.RowPitch, + } } } @@ -1617,7 +2107,9 @@ unsafe extern "system" fn copy_texture( dst: location(r, &*dst), at: [x, y, z], src: location(r, &*src), - part: part.as_ref().map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), + part: part + .as_ref() + .map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]), }); } } @@ -1626,15 +2118,33 @@ unsafe extern "system" fn copy_resource(this: Ptr, dst: Ptr, src: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.CopyResource)(this, dst, src); - note_change(this, |r| Cmd::CopyResource { dst: r.resource(dst), src: r.resource(src) }); + note_change(this, |r| Cmd::CopyResource { + dst: r.resource(dst), + src: r.resource(src), + }); } } -unsafe extern "system" fn resolve(this: Ptr, dst: Ptr, dst_sub: u32, src: Ptr, src_sub: u32, format: DXGI_FORMAT) { +unsafe extern "system" fn resolve( + this: Ptr, + dst: Ptr, + dst_sub: u32, + src: Ptr, + src_sub: u32, + format: DXGI_FORMAT, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)(this, dst, dst_sub, src, src_sub, format); - note(this, |r| Cmd::Resolve { dst: r.resource(dst), dst_sub, src: r.resource(src), src_sub, format: format.0 }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)( + this, dst, dst_sub, src, src_sub, format, + ); + note(this, |r| Cmd::Resolve { + dst: r.resource(dst), + dst_sub, + src: r.resource(src), + src_sub, + format: format.0, + }); } } @@ -1653,7 +2163,10 @@ unsafe extern "system" fn resolve_region( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion)(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); + own!( + this, + ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion + )(this, dst, dst_sub, x, y, src, src_sub, part, format, mode); note(this, |r| Cmd::ResolveRegion { dst: r.resource(dst), dst_sub, @@ -1676,7 +2189,10 @@ unsafe fn rects(n: u32, all: *const RECT) -> Vec<[i32; 4]> { return Vec::new(); } // SAFETY: `n` rectangles. - unsafe { std::slice::from_raw_parts(all, n as usize) }.iter().map(rect).collect() + unsafe { std::slice::from_raw_parts(all, n as usize) } + .iter() + .map(rect) + .collect() } unsafe extern "system" fn topology(this: Ptr, kind: D3D_PRIMITIVE_TOPOLOGY) { @@ -1691,7 +2207,11 @@ unsafe extern "system" fn viewports(this: Ptr, n: u32, all: *const D3D12_VIEWPOR // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetViewports)(this, n, all); - note(this, |_| Cmd::Viewports { all: (0..n as usize).map(|i| all.add(i).cast::<[f32; 6]>().read()).collect() }); + note(this, |_| Cmd::Viewports { + all: (0..n as usize) + .map(|i| all.add(i).cast::<[f32; 6]>().read()) + .collect(), + }); } } @@ -1707,7 +2227,9 @@ unsafe extern "system" fn blend_factor(this: Ptr, factor: *const f32) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor)(this, factor); - note(this, |_| Cmd::BlendFactor { factor: factor.cast::<[f32; 4]>().as_ref().copied() }); + note(this, |_| Cmd::BlendFactor { + factor: factor.cast::<[f32; 4]>().as_ref().copied(), + }); } } @@ -1731,7 +2253,9 @@ unsafe extern "system" fn set_pipeline(this: Ptr, pso: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetPipelineState)(this, pso); - note(this, |r| Cmd::Pipeline { pso: r.object(pso, "a pipeline") }); + note(this, |r| Cmd::Pipeline { + pso: r.object(pso, "a pipeline"), + }); } } @@ -1747,13 +2271,18 @@ unsafe extern "system" fn barrier(this: Ptr, n: u32, all: *const D3D12_RESOURCE_ let a = &b.Anonymous.Aliasing; Barrier::Alias { flags: b.Flags.0, - before: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), - after: r.resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), + before: r + .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)), + after: r + .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)), } } - D3D12_RESOURCE_BARRIER_TYPE_UAV => { - Barrier::Uav { flags: b.Flags.0, res: r.resource(std::mem::transmute_copy::<_, Ptr>(&b.Anonymous.UAV.pResource)) } - } + D3D12_RESOURCE_BARRIER_TYPE_UAV => Barrier::Uav { + flags: b.Flags.0, + res: r.resource(std::mem::transmute_copy::<_, Ptr>( + &b.Anonymous.UAV.pResource, + )), + }, _ => { let t = &b.Anonymous.Transition; Barrier::Transition { @@ -1775,7 +2304,11 @@ unsafe extern "system" fn set_heaps(this: Ptr, n: u32, all: *const Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps)(this, n, all); - note(this, |r| Cmd::Heaps { heaps: (0..n as usize).map(|i| r.object(*all.add(i), "a descriptor heap")).collect() }); + note(this, |r| Cmd::Heaps { + heaps: (0..n as usize) + .map(|i| r.object(*all.add(i), "a descriptor heap")) + .collect(), + }); } } @@ -1783,15 +2316,24 @@ unsafe extern "system" fn root_compute(this: Ptr, root: Ptr) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature)(this, root); - note(this, |r| Cmd::RootSignature { graphics: false, root: r.object(root, "a root signature") }); + note(this, |r| Cmd::RootSignature { + graphics: false, + root: r.object(root, "a root signature"), + }); } } unsafe extern "system" fn root_graphics(this: Ptr, root: Ptr) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature)(this, root); - note(this, |r| Cmd::RootSignature { graphics: true, root: r.object(root, "a root signature") }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature + )(this, root); + note(this, |r| Cmd::RootSignature { + graphics: true, + root: r.object(root, "a root signature"), + }); } } @@ -1803,13 +2345,21 @@ fn table(r: &Recorder, graphics: bool, param: u32, at: u64) -> Cmd { if heap == NONE { r.problem("a descriptor table in no heap seen made"); } - Cmd::Table { graphics, param, heap, slot } + Cmd::Table { + graphics, + param, + heap, + slot, + } } unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable)(this, param, at); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable + )(this, param, at); note(this, |r| table(r, false, param, at.ptr)); } } @@ -1817,7 +2367,10 @@ unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DES unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable)(this, param, at); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable + )(this, param, at); note(this, |r| table(r, true, param, at.ptr)); } } @@ -1825,37 +2378,83 @@ unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DE unsafe extern "system" fn constant_compute(this: Ptr, param: u32, value: u32, offset: u32) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant)(this, param, value, offset); - note(this, |_| Cmd::Constants { graphics: false, param, offset, values: vec![value] }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant + )(this, param, value, offset); + note(this, |_| Cmd::Constants { + graphics: false, + param, + offset, + values: vec![value], + }); } } unsafe extern "system" fn constant_graphics(this: Ptr, param: u32, value: u32, offset: u32) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant)(this, param, value, offset); - note(this, |_| Cmd::Constants { graphics: true, param, offset, values: vec![value] }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant + )(this, param, value, offset); + note(this, |_| Cmd::Constants { + graphics: true, + param, + offset, + values: vec![value], + }); } } unsafe fn values(n: u32, data: *const c_void) -> Vec { // SAFETY: `n` values, of any alignment. - (0..n as usize).map(|i| unsafe { data.cast::().add(i).read_unaligned() }).collect() + (0..n as usize) + .map(|i| unsafe { data.cast::().add(i).read_unaligned() }) + .collect() } -unsafe extern "system" fn constants_compute(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { +unsafe extern "system" fn constants_compute( + this: Ptr, + param: u32, + n: u32, + data: *const c_void, + offset: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants)(this, param, n, data, offset); - note(this, |_| Cmd::Constants { graphics: false, param, offset, values: values(n, data) }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants + )(this, param, n, data, offset); + note(this, |_| Cmd::Constants { + graphics: false, + param, + offset, + values: values(n, data), + }); } } -unsafe extern "system" fn constants_graphics(this: Ptr, param: u32, n: u32, data: *const c_void, offset: u32) { +unsafe extern "system" fn constants_graphics( + this: Ptr, + param: u32, + n: u32, + data: *const c_void, + offset: u32, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants)(this, param, n, data, offset); - note(this, |_| Cmd::Constants { graphics: true, param, offset, values: values(n, data) }); + own!( + this, + ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants + )(this, param, n, data, offset); + note(this, |_| Cmd::Constants { + graphics: true, + param, + offset, + values: values(n, data), + }); } } @@ -1892,11 +2491,20 @@ unsafe extern "system" fn index_buffer(this: Ptr, view: *const D3D12_INDEX_BUFFE // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer)(this, view); - note(this, |r| Cmd::IndexBuffer { view: view.as_ref().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)) }); + note(this, |r| Cmd::IndexBuffer { + view: view + .as_ref() + .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)), + }); } } -unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: *const D3D12_VERTEX_BUFFER_VIEW) { +unsafe extern "system" fn vertex_buffers( + this: Ptr, + start: u32, + n: u32, + views: *const D3D12_VERTEX_BUFFER_VIEW, +) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers)(this, start, n, views); @@ -1905,7 +2513,9 @@ unsafe extern "system" fn vertex_buffers(this: Ptr, start: u32, n: u32, views: * count: n, views: (!views.is_null()).then(|| { let all = std::slice::from_raw_parts(views, n as usize); - all.iter().map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)).collect() + all.iter() + .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes)) + .collect() }), }); } @@ -1920,7 +2530,9 @@ unsafe extern "system" fn targets( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)(this, n, colors, range, depth); + own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)( + this, n, colors, range, depth, + ); note(this, |r| { let colors = (0..n as usize) .map(|i| { @@ -1928,10 +2540,14 @@ unsafe extern "system" fn targets( return r.view((*colors.add(i)).ptr); } let all = read(&r.descriptors); - all.cpu((*colors).ptr).map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) + all.cpu((*colors).ptr) + .map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32)) }) .collect(); - Cmd::Targets { colors, depth: depth.as_ref().map(|d| r.view(d.ptr)) } + Cmd::Targets { + colors, + depth: depth.as_ref().map(|d| r.view(d.ptr)), + } }); } } @@ -1948,16 +2564,34 @@ unsafe extern "system" fn clear_depth( ) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)(this, view, flags, depth, stencil, n, all); - note(this, |r| Cmd::ClearDepth { view: r.view(view.ptr), flags: flags.0, depth, stencil, rects: rects(n, all) }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)( + this, view, flags, depth, stencil, n, all, + ); + note(this, |r| Cmd::ClearDepth { + view: r.view(view.ptr), + flags: flags.0, + depth, + stencil, + rects: rects(n, all), + }); } } -unsafe extern "system" fn clear_target(this: Ptr, view: D3D12_CPU_DESCRIPTOR_HANDLE, color: *const f32, n: u32, all: *const RECT) { +unsafe extern "system" fn clear_target( + this: Ptr, + view: D3D12_CPU_DESCRIPTOR_HANDLE, + color: *const f32, + n: u32, + all: *const RECT, +) { // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView)(this, view, color, n, all); - note(this, |r| Cmd::ClearTarget { view: r.view(view.ptr), color: color.cast::<[f32; 4]>().read(), rects: rects(n, all) }); + note(this, |r| Cmd::ClearTarget { + view: r.view(view.ptr), + color: color.cast::<[f32; 4]>().read(), + rects: rects(n, all), + }); } } @@ -1967,8 +2601,12 @@ unsafe extern "system" fn discard(this: Ptr, res: Ptr, region: *const D3D12_DISC own!(this, ID3D12GraphicsCommandList_Vtbl.DiscardResource)(this, res, region); note(this, |r| Cmd::Discard { res: r.resource(res), - rects: region.as_ref().map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), - subs: region.as_ref().map(|d| [d.FirstSubresource, d.NumSubresources]), + rects: region + .as_ref() + .map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)), + subs: region + .as_ref() + .map(|d| [d.FirstSubresource, d.NumSubresources]), }); } } @@ -1977,7 +2615,11 @@ unsafe extern "system" fn begin_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TY // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.BeginQuery)(this, heap, kind, index); - note(this, |r| Cmd::BeginQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + note(this, |r| Cmd::BeginQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + index, + }); } } @@ -1985,22 +2627,53 @@ unsafe extern "system" fn end_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE // SAFETY: as above. unsafe { own!(this, ID3D12GraphicsCommandList_Vtbl.EndQuery)(this, heap, kind, index); - note(this, |r| Cmd::EndQuery { heap: r.object(heap, "a query heap"), kind: kind.0, index }); + note(this, |r| Cmd::EndQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + index, + }); } } -unsafe extern "system" fn resolve_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, first: u32, count: u32, dst: Ptr, at: u64) { +unsafe extern "system" fn resolve_query( + this: Ptr, + heap: Ptr, + kind: D3D12_QUERY_TYPE, + first: u32, + count: u32, + dst: Ptr, + at: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)(this, heap, kind, first, count, dst, at); - note(this, |r| Cmd::ResolveQuery { heap: r.object(heap, "a query heap"), kind: kind.0, first, count, dst: r.resource(dst), at }); + own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)( + this, heap, kind, first, count, dst, at, + ); + note(this, |r| Cmd::ResolveQuery { + heap: r.object(heap, "a query heap"), + kind: kind.0, + first, + count, + dst: r.resource(dst), + at, + }); } } -unsafe extern "system" fn indirect(this: Ptr, signature: Ptr, most: u32, args: Ptr, at: u64, count: Ptr, count_at: u64) { +unsafe extern "system" fn indirect( + this: Ptr, + signature: Ptr, + most: u32, + args: Ptr, + at: u64, + count: Ptr, + count_at: u64, +) { // SAFETY: as above. unsafe { - own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)(this, signature, most, args, at, count, count_at); + own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)( + this, signature, most, args, at, count, count_at, + ); note(this, |r| Cmd::Indirect { signature: r.object(signature, "a command signature"), most, @@ -2025,7 +2698,11 @@ unsafe extern "system" fn write_immediate( all: (0..n as usize) .map(|i| { let p = all.add(i).read(); - let mode = if modes.is_null() { 0 } else { modes.add(i).read().0 }; + let mode = if modes.is_null() { + 0 + } else { + modes.add(i).read().0 + }; (address(r, p.Dest), p.Value, mode) }) .collect(), @@ -2075,7 +2752,11 @@ mod tests { all.remove(2); assert_eq!(at(&all, 0x2000), None); let h = heap(4, 0, 0, 2); - let s = Slot { kind: slot::SRV, res: 5, ..Slot::EMPTY }; + let s = Slot { + kind: slot::SRV, + res: 5, + ..Slot::EMPTY + }; h.set(1, &s); h.set(2, &s); assert_eq!(h.all(), [Slot::EMPTY, s]); diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs index 02b8a4f..d9832d2 100644 --- a/crates/victory-gpu/src/replay/snap.rs +++ b/crates/victory-gpu/src/replay/snap.rs @@ -15,7 +15,9 @@ 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, Loc, 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; @@ -29,7 +31,7 @@ const PAGE: usize = 4096; /// What one thread compares at a time. const CHUNK: usize = 1 << 20; /// Frames waited, at the most, for one whose lists are all recorded. -const PATIENCE: u64 = 300; +const PATIENCE: u64 = 100; #[derive(Default)] enum Stage { @@ -61,19 +63,38 @@ impl Phase { /// A submission to a queue other than the drawing one: left out. pub(super) fn other_queue(r: &Recorder, lists: u32) { if r.watching.load(Ordering::SeqCst) { - r.problem_times("lists sent to a queue other than the drawing one are not in the capture", u64::from(lists)); + r.problem_times( + "lists sent to a queue other than the drawing one are not in the capture", + u64::from(lists), + ); } } /// A submission to the drawing queue, made by `go`. -pub(super) fn submit(r: &Recorder, queue: &ID3D12CommandQueue, lists: &[*mut std::ffi::c_void], go: impl FnOnce()) { +pub(super) fn submit( + r: &Recorder, + queue: &ID3D12CommandQueue, + lists: &[*mut std::ffi::c_void], + go: impl FnOnce(), +) { let mut phase = lock(&r.submits); type Closed = (Option>>, Arc>); - let closed: Vec> = lists.iter().map(|&p| r.list(p).and_then(|l| l.closed())).collect(); + let closed: Vec> = lists + .iter() + .map(|&p| r.list(p).and_then(|l| l.closed())) + .collect(); phase.submits += 1; - phase.missing += closed.iter().filter(|c| c.as_ref().is_none_or(|c| c.0.is_none())).count() as u32; + let whole = |c: &Option| c.as_ref().is_some_and(|c| c.0.is_some()); + phase.missing += lists + .iter() + .zip(&closed) + .filter(|(p, c)| !whole(c) && r.knows(**p)) + .count() as u32; if let Stage::Capturing(c) = &mut phase.stage { - let commands: Vec>>> = closed.iter().map(|c| c.as_ref().and_then(|c| c.0.clone())).collect(); + let commands: Vec>>> = closed + .iter() + .map(|c| c.as_ref().and_then(|c| c.0.clone())) + .collect(); let _ours = Ours::new(); if let Err(e) = c.submit(r, queue, &commands) { stop(r, &mut phase, &*e); @@ -102,7 +123,10 @@ pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { let mut phase = lock(&r.submits); phase.presents += 1; let presents = phase.presents; - let (submits, missing) = (std::mem::take(&mut phase.submits), std::mem::take(&mut phase.missing)); + let (submits, missing) = ( + std::mem::take(&mut phase.submits), + std::mem::take(&mut phase.missing), + ); let mut finished = None; match &mut phase.stage { Stage::Waiting => { @@ -124,7 +148,11 @@ pub(super) fn present(r: &Recorder, texture: &ID3D12Resource, state: u32) { if !whole { r.problem("no frame was found whose lists were all recorded"); } - tracing::info!(presents, waited, "frame recorder: the next frame is captured"); + tracing::info!( + presents, + waited, + "frame recorder: the next frame is captured" + ); match Capture::new(r) { Ok(c) => phase.stage = Stage::Capturing(Box::new(c)), Err(e) => stop(r, &mut phase, &*e), @@ -178,16 +206,36 @@ impl Reads { }; 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::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, .. }, .. } => { + 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)); @@ -208,7 +256,12 @@ impl Reads { }; 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))) + .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(); @@ -277,7 +330,10 @@ impl Capture { let _ours = Ours::new(); let device = r.device().ok_or("no device")?; let queues = lock(&r.queues).clone(); - let direct = queues.iter().find(|q| q.1 == D3D12_COMMAND_LIST_TYPE_DIRECT.0).ok_or("no drawing queue")?; + let direct = queues + .iter() + .find(|q| q.1 == D3D12_COMMAND_LIST_TYPE_DIRECT.0) + .ok_or("no drawing queue")?; let mut others = Vec::new(); for (queue, _) in queues.iter().filter(|q| q.0 != direct.0) { others.push(Worker::new(&device, queue)?); @@ -309,7 +365,11 @@ impl Capture { }) } - fn timed(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result) -> Result { + fn timed( + &mut self, + what: &'static str, + f: impl FnOnce(&mut Self) -> Result, + ) -> Result { let began = Instant::now(); let out = f(self); *self.took.entry(what).or_default() += began.elapsed(); @@ -332,14 +392,22 @@ impl Capture { let object = res.object(); // SAFETY: a live resource, or one whose end waits for the // lock held here (`Recorder::gone`): the count tells which. - let count = unsafe { (Interface::vtable(&*object).base__.base__.base__.base__.AddRef)(object.as_raw()) }; + let count = unsafe { + (Interface::vtable(&*object) + .base__ + .base__ + .base__ + .base__ + .AddRef)(object.as_raw()) + }; if count <= 1 { // Dying: the reference does not bring it back, and // 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()) }); + self.held + .push(unsafe { ID3D12Resource::from_raw(object.as_raw()) }); all.push(res.clone()); } } @@ -357,10 +425,21 @@ impl Capture { for res in all { if let Place::Placed { heap, offset } = res.place { // SAFETY: a plain query. - let info = unsafe { self.worker.device.GetResourceAllocationInfo(0, &[gpu::to_desc(&res.desc)]) }; - let size = if info.SizeInBytes == u64::MAX { res.desc.width } else { info.SizeInBytes }; + let info = unsafe { + self.worker + .device + .GetResourceAllocationInfo(0, &[gpu::to_desc(&res.desc)]) + }; + let size = if info.SizeInBytes == u64::MAX { + res.desc.width + } else { + info.SizeInBytes + }; let used = self.states.used.get(&res.id).copied().unwrap_or(0); - heaps.entry(heap).or_default().push((used, offset, offset + size, res.id)); + heaps + .entry(heap) + .or_default() + .push((used, offset, offset + size, res.id)); } } let mut idle = HashSet::new(); @@ -368,7 +447,10 @@ impl Capture { list.sort_by(|a, b| b.cmp(a)); let mut taken: BTreeMap = BTreeMap::new(); for (_, from, to, id) in list { - let overlaps = taken.range(..to).next_back().is_some_and(|(_, &end)| end > from); + let overlaps = taken + .range(..to) + .next_back() + .is_some_and(|(_, &end)| end > from); if overlaps { idle.insert(id); } else { @@ -390,7 +472,13 @@ impl Capture { let mut at = 0; while at < res.desc.width { let len = PIECE.min(res.desc.width - at); - pieces.push(Piece { res: res.clone(), first: at, count: 1, len, at: 0 }); + pieces.push(Piece { + res: res.clone(), + first: at, + count: 1, + len, + at: 0, + }); at += len; } continue; @@ -404,14 +492,28 @@ impl Capture { if total == u64::MAX { r.problem("contents of a texture without a copyable layout are not in the capture"); } else if total <= STAGING { - pieces.push(Piece { res: res.clone(), first: 0, count: res.subs, len: total, at: 0 }); + pieces.push(Piece { + res: res.clone(), + first: 0, + count: res.subs, + len: total, + at: 0, + }); } else { for sub in 0..res.subs { let (_, len) = gpu::footprints(&device, &desc, sub, 1); if len <= STAGING { - pieces.push(Piece { res: res.clone(), first: u64::from(sub), count: 1, len, at: 0 }); + pieces.push(Piece { + res: res.clone(), + first: u64::from(sub), + count: 1, + len, + at: 0, + }); } else { - r.problem("contents of a texture level of over 256 MB are not in the capture"); + r.problem( + "contents of a texture level of over 256 MB are not in the capture", + ); } } } @@ -433,7 +535,12 @@ impl Capture { } let mut stagings = Vec::new(); for _ in 0..STAGINGS.min(batches.len()) { - stagings.push(gpu::buffer(&device, D3D12_HEAP_TYPE_READBACK, STAGING, D3D12_RESOURCE_FLAG_NONE)?); + stagings.push(gpu::buffer( + &device, + D3D12_HEAP_TYPE_READBACK, + STAGING, + D3D12_RESOURCE_FLAG_NONE, + )?); } let file = File::create(r.folder.join("contents.bin"))?; let end = AtomicU64::new(0); @@ -448,7 +555,8 @@ impl Capture { let maps: Vec = stagings.iter().map(|s| s.1 as usize).collect(); std::thread::scope(|scope| -> Result<(), Fault> { for _ in 0..stagings.len() { - let (work, free, maps, file, end, contents, failed) = (&work, free.clone(), &maps, &file, &end, &contents, &failed); + let (work, free, maps, file, end, contents, failed) = + (&work, free.clone(), &maps, &file, &end, &contents, &failed); scope.spawn(move || { loop { let next = lock(work).recv(); @@ -456,14 +564,29 @@ impl Capture { for p in pieces { // SAFETY: inside the buffer's mapping; the copy // into it has run. - let bytes = unsafe { std::slice::from_raw_parts((maps[i] + p.at as usize) as *const u8, p.len as usize) }; - let at = if zero(bytes) { ZERO } else { end.fetch_add(p.len, Ordering::Relaxed) }; + let bytes = unsafe { + std::slice::from_raw_parts( + (maps[i] + p.at as usize) as *const u8, + p.len as usize, + ) + }; + let at = if zero(bytes) { + ZERO + } else { + end.fetch_add(p.len, Ordering::Relaxed) + }; if at != ZERO && let Err(e) = write_at(file, bytes, at) { lock(failed).get_or_insert(e); } - lock(contents).push(Content { res: p.res.id, first: p.first, count: p.count, len: p.len, file: at }); + lock(contents).push(Content { + res: p.res.id, + first: p.first, + count: p.count, + len: p.len, + file: at, + }); } let _ = free.send(i); } @@ -476,7 +599,9 @@ impl Capture { continue; } let i = freed.recv()?; - let value = self.worker.send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?; + let value = self + .worker + .send(|list| copy_out(&device, list, &self.states, &pieces, &stagings[i].0))?; self.worker.wait(value)?; todo.send((i, pieces))?; } @@ -493,7 +618,9 @@ impl Capture { fn new_buffers(&mut self, r: &Recorder) -> Result<(), Fault> { let fresh: Vec> = read(&r.resources) .values() - .filter(|res| matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id)) + .filter(|res| { + matches!(res.seen, Seen::Cached | Seen::Combined) && !self.known.contains(&res.id) + }) .cloned() .collect(); for res in fresh { @@ -516,7 +643,12 @@ impl Capture { Some(i) => i, None => { let len = STAGING.max(size as u64); - let (b, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + let (b, data) = gpu::buffer( + &self.worker.device, + D3D12_HEAP_TYPE_READBACK, + len, + D3D12_RESOURCE_FLAG_NONE, + )?; self.blocks.push((b, data as usize, len, 0)); self.blocks.len() - 1 } @@ -526,7 +658,14 @@ impl Capture { b.3 = (at + size as u64).next_multiple_of(256); ((b.1 + at as usize) as *const u8, Some((i, at))) }; - self.buffers.push(CpuBuffer { id: res.id, res: object, live, through, size, kept: vec![0; size] }); + self.buffers.push(CpuBuffer { + id: res.id, + res: object, + live, + through, + size, + kept: vec![0; size], + }); } Ok(()) } @@ -540,7 +679,12 @@ impl Capture { .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))) + .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); @@ -549,24 +693,43 @@ impl Capture { let b = &buffers[i]; if let Some((block, at)) = b.through { // SAFETY: an open list and live buffers. - unsafe { list.CopyBufferRegion(&blocks[block].0, at + from as u64, &b.res, from as u64, (to - from) 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, usize)> = parts .iter() - .flat_map(|&(i, from, to)| (from..to).step_by(CHUNK).map(move |at| (i, at, CHUNK.min(to - at)))) + .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. unsafe impl Sync for Kept {} - let kept: Vec = self.buffers.iter_mut().map(|b| Kept(b.kept.as_mut_ptr())).collect(); + let kept: Vec = self + .buffers + .iter_mut() + .map(|b| Kept(b.kept.as_mut_ptr())) + .collect(); let next = AtomicUsize::new(0); let out: std::sync::Mutex> = std::sync::Mutex::default(); let failed: std::sync::Mutex> = std::sync::Mutex::default(); - let threads = std::thread::available_parallelism().map_or(4, |n| n.get() / 2).clamp(1, 16).min(chunks.len().max(1)); + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get() / 2) + .clamp(1, 16) + .min(chunks.len().max(1)); let (buffers, file, end) = (&self.buffers, &self.deltas, &self.delta_at); std::thread::scope(|scope| { for _ in 0..threads { @@ -574,19 +737,30 @@ impl Capture { let mut mine = Vec::new(); loop { let i = next.fetch_add(1, Ordering::Relaxed); - let Some(&(b, at, len)) = chunks.get(i) else { break }; + 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. - let runs = unsafe { changed_runs(buffers[b].live.add(at), kept[b].0.add(at), len) }; + let runs = unsafe { + changed_runs(buffers[b].live.add(at), kept[b].0.add(at), len) + }; for (from, to) in runs { // SAFETY: as above. - let bytes = unsafe { std::slice::from_raw_parts(kept[b].0.add(at + from), to - from) }; + let bytes = unsafe { + std::slice::from_raw_parts(kept[b].0.add(at + from), to - from) + }; let file_at = end.fetch_add(bytes.len() as u64, Ordering::Relaxed); if let Err(e) = write_at(file, bytes, file_at) { lock(&failed).get_or_insert(e); } - mine.push(Delta { res: buffers[b].id, at: (at + from) as u64, len: bytes.len() as u64, file: file_at }); + mine.push(Delta { + res: buffers[b].id, + at: (at + from) as u64, + len: bytes.len() as u64, + file: file_at, + }); } } lock(&out).extend(mine); @@ -601,7 +775,12 @@ impl Capture { Ok(out) } - fn submit(&mut self, r: &Recorder, _queue: &ID3D12CommandQueue, lists: &[Option>>]) -> Result<(), Fault> { + fn submit( + &mut self, + r: &Recorder, + _queue: &ID3D12CommandQueue, + lists: &[Option>>], + ) -> Result<(), Fault> { let first = !self.started; if first { self.start(r)?; @@ -615,7 +794,8 @@ impl Capture { let heaps: Vec> = 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.viewed + .extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter])); self.heaps.push((h, runs)); } } else { @@ -625,7 +805,10 @@ impl Capture { let h = match self.heaps.iter().find(|(h, _)| h.id == heap) { Some((h, _)) => h.clone(), None => { - let found = read(&r.descriptors).visible().find(|h| h.id == heap).cloned(); + let found = read(&r.descriptors) + .visible() + .find(|h| h.id == heap) + .cloned(); let Some(h) = found else { continue }; self.heaps.push((h.clone(), Vec::new())); h @@ -649,10 +832,16 @@ impl Capture { for l in lists { numbers.push(match l { None => { - r.problem("a list was submitted that was not recorded whole: its work is missing"); + r.problem( + "a list was submitted that was not recorded whole: its work is missing", + ); MISSING } - Some(commands) => match self.lists.iter().position(|have| Arc::ptr_eq(have, commands)) { + Some(commands) => match self + .lists + .iter() + .position(|have| Arc::ptr_eq(have, commands)) + { Some(i) => i as u32, None => { self.lists.push(commands.clone()); @@ -661,7 +850,12 @@ impl Capture { }, }); } - self.submits.push(wire::Submit { frame: self.frame, lists: numbers, deltas, views }); + self.submits.push(wire::Submit { + frame: self.frame, + lists: numbers, + deltas, + views, + }); Ok(()) } @@ -670,8 +864,14 @@ impl Capture { // SAFETY: a live texture. let desc = unsafe { texture.GetDesc() }; let (f, total) = gpu::footprints(&self.worker.device, &desc, 0, 1); - let (back, data) = gpu::buffer(&self.worker.device, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_FLAG_NONE)?; - self.worker.run(|list| read_sub(list, texture, 0, state, &back, f[0]))?; + let (back, data) = gpu::buffer( + &self.worker.device, + D3D12_HEAP_TYPE_READBACK, + total, + D3D12_RESOURCE_FLAG_NONE, + )?; + self.worker + .run(|list| read_sub(list, texture, 0, state, &back, f[0]))?; // SAFETY: the buffer's mapping; the copy into it has run. let bytes = unsafe { std::slice::from_raw_parts(data, total as usize) }; write_at(&self.present_file, bytes, self.present_at)?; @@ -688,7 +888,10 @@ impl Capture { }); self.present_at += total; match gpu::rgb(width, height, pitch, desc.Format.0, bytes) { - Some(rgb) => std::fs::write(r.folder.join(format!("frame-{}.png", self.frame)), crate::capture::png(width, height, &rgb))?, + Some(rgb) => std::fs::write( + r.folder.join(format!("frame-{}.png", self.frame)), + crate::capture::png(width, height, &rgb), + )?, None => r.problem("the presented format is not shown in a PNG"), } self.frame += 1; @@ -722,20 +925,35 @@ impl Capture { resources.sort_by_key(|res| res.id); let mut heaps: Vec = { let all = lock(&r.heaps); - let used: HashSet = - resources.iter().filter_map(|res| if let Place::Placed { heap, .. } = res.place { Some(heap) } else { None }).collect(); + let used: HashSet = resources + .iter() + .filter_map(|res| { + if let Place::Placed { heap, .. } = res.place { + Some(heap) + } else { + None + } + }) + .collect(); used.iter().filter_map(|id| all.get(id).cloned()).collect() }; heaps.sort_by_key(|h| h.id); // What the lists name. - let (mut psos, mut roots, mut signatures, mut queries) = (HashSet::new(), HashSet::new(), HashSet::new(), HashSet::new()); + let (mut psos, mut roots, mut signatures, mut queries) = ( + HashSet::new(), + HashSet::new(), + HashSet::new(), + HashSet::new(), + ); for l in &self.lists { for c in Cmd::all(l)? { match c { - Cmd::Pipeline { pso } => drop(psos.insert(pso)), - Cmd::RootSignature { root, .. } => drop(roots.insert(root)), - Cmd::Indirect { signature, .. } => drop(signatures.insert(signature)), - Cmd::BeginQuery { heap, .. } | Cmd::EndQuery { heap, .. } | Cmd::ResolveQuery { heap, .. } => drop(queries.insert(heap)), + Cmd::Pipeline { pso } => _ = psos.insert(pso), + Cmd::RootSignature { root, .. } => _ = roots.insert(root), + Cmd::Indirect { signature, .. } => _ = signatures.insert(signature), + Cmd::BeginQuery { heap, .. } + | Cmd::EndQuery { heap, .. } + | Cmd::ResolveQuery { heap, .. } => _ = queries.insert(heap), _ => {} } } @@ -747,22 +965,38 @@ impl Capture { .iter() .filter_map(|id| { let parts = all.get(id)?; - Some(wire::Pipeline { id: *id, parts: parts.to_vec(), name: names.get(id).cloned().unwrap_or_default() }) + Some(wire::Pipeline { + id: *id, + parts: parts.to_vec(), + name: names.get(id).cloned().unwrap_or_default(), + }) }) .collect(); out.sort_by_key(|p| p.id); out }; - roots.extend(pipelines.iter().flat_map(|p| &p.parts).filter_map(|p| if let wire::Part::Root { root } = p { Some(*root) } else { None })); + roots.extend(pipelines.iter().flat_map(|p| &p.parts).filter_map(|p| { + if let wire::Part::Root { root } = p { + Some(*root) + } else { + None + } + })); let signatures: Vec = { let all = lock(&r.signatures); - signatures.iter().filter_map(|id| all.get(id).cloned()).collect() + signatures + .iter() + .filter_map(|id| all.get(id).cloned()) + .collect() }; roots.extend(signatures.iter().map(|s| s.root)); roots.remove(&NONE); let roots: Vec<(u32, wire::Blob)> = { let all = lock(&r.roots); - roots.iter().filter_map(|id| Some((*id, wire::Blob(all.get(id)?.to_vec())))).collect() + roots + .iter() + .filter_map(|id| Some((*id, wire::Blob(all.get(id)?.to_vec())))) + .collect() }; for ((what, before), (_, now)) in self.calls.iter().zip(not_recorded_calls()) { if now > *before { @@ -771,7 +1005,12 @@ impl Capture { } let (adapter, vendor, device) = gpu::adapter(&self.worker.device); let mut notes = r.problems(); - let bytes: u64 = self.contents.iter().filter(|c| c.file != ZERO).map(|c| c.len).sum(); + let bytes: u64 = self + .contents + .iter() + .filter(|c| c.file != ZERO) + .map(|c| c.len) + .sum(); notes.push(format!( "{} submissions, {} lists, {} resources, {} pipelines; {} MB of the card's memory, {} MB of changes by the CPU; {:.1} s: {}", self.submits.len(), @@ -800,16 +1039,28 @@ impl Capture { descriptor_heaps: self .heaps .iter() - .map(|(h, runs)| wire::DescriptorHeap { id: h.id, kind: h.kind, count: h.count, flags: h.flags, runs: runs.clone() }) + .map(|(h, runs)| wire::DescriptorHeap { + id: h.id, + kind: h.kind, + count: h.count, + flags: h.flags, + runs: runs.clone(), + }) .collect(), query_heaps: { let all = lock(&r.queries); - queries.iter().filter_map(|id| all.get(id).cloned()).collect() + queries + .iter() + .filter_map(|id| all.get(id).cloned()) + .collect() }, lists: self .lists .iter() - .map(|l| wire::List { kind: D3D12_COMMAND_LIST_TYPE_DIRECT.0, commands: wire::Blob(l.to_vec()) }) + .map(|l| wire::List { + kind: D3D12_COMMAND_LIST_TYPE_DIRECT.0, + commands: wire::Blob(l.to_vec()), + }) .collect(), submits: std::mem::take(&mut self.submits), contents: std::mem::take(&mut self.contents), @@ -833,7 +1084,13 @@ struct Piece { /// Records the copies of `pieces` into `to`. Textures are moved to a state /// they can be copied from and back. -fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &States, pieces: &[Piece], to: &ID3D12Resource) { +fn copy_out( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + states: &States, + pieces: &[Piece], + to: &ID3D12Resource, +) { let (mut before, mut after) = (Vec::new(), Vec::new()); let mut seen = HashSet::new(); for p in pieces.iter().filter(|p| !p.res.is_buffer()) { @@ -842,7 +1099,16 @@ fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &St } let from = states.get(p.res.id).unwrap_or(vec![COMMON]); // From the common state a texture is promoted by the copy. - let to: Vec = from.iter().map(|&s| if s == COMMON || s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = from + .iter() + .map(|&s| { + if s == COMMON || s & COPY_SOURCE != 0 { + s + } else { + COPY_SOURCE + } + }) + .collect(); gpu::moves(&p.res.object(), &from, &to, &mut before); gpu::moves(&p.res.object(), &to, &from, &mut after); } @@ -857,10 +1123,18 @@ fn copy_out(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, states: &St list.CopyBufferRegion(to, p.at, &*object, p.first, p.len); continue; } - let (all, _) = gpu::footprints(device, &gpu::to_desc(&p.res.desc), p.first as u32, p.count); + let (all, _) = + gpu::footprints(device, &gpu::to_desc(&p.res.desc), p.first as u32, p.count); for (i, mut f) in all.into_iter().enumerate() { f.Offset += p.at; - list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(&object, p.first as u32 + i as u32), None); + list.CopyTextureRegion( + &gpu::placed_location(to, f), + 0, + 0, + 0, + &gpu::sub_location(&object, p.first as u32 + i as u32), + None, + ); } } if !after.is_empty() { @@ -884,7 +1158,14 @@ pub(super) fn read_sub( if !there { list.ResourceBarrier(&[gpu::transition(texture, ALL, state, COPY_SOURCE)]); } - list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(texture, sub), None); + list.CopyTextureRegion( + &gpu::placed_location(to, f), + 0, + 0, + 0, + &gpu::sub_location(texture, sub), + None, + ); if !there { list.ResourceBarrier(&[gpu::transition(texture, ALL, COPY_SOURCE, state)]); } @@ -895,9 +1176,15 @@ pub(super) fn read_sub( /// 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 { + 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 }; + return Slot { + kind: slot::SRV, + ..Slot::EMPTY + }; } if s.kind == slot::CBV && s.described != 0 { match r.va(s.address()) { @@ -908,7 +1195,10 @@ fn resolved(r: &Recorder, mut s: Slot) -> Slot { Va::Null {} => {} Va::Unknown { .. } => { // Its buffer is gone: nothing may read it. - s = Slot { kind: slot::CBV, ..Slot::EMPTY }; + s = Slot { + kind: slot::CBV, + ..Slot::EMPTY + }; } } } @@ -964,7 +1254,8 @@ unsafe fn changed_runs(live: *const u8, kept: *mut u8, len: usize) -> Vec<(usize let n = PAGE.min(len - at); // SAFETY: the caller's. unsafe { - let same = std::slice::from_raw_parts(live.add(at), n) == std::slice::from_raw_parts(kept.add(at), n); + let same = std::slice::from_raw_parts(live.add(at), n) + == std::slice::from_raw_parts(kept.add(at), n); if !same { std::ptr::copy_nonoverlapping(live.add(at), kept.add(at), n); match runs.last_mut() { @@ -994,7 +1285,10 @@ mod tests { live[PAGE + 5] = 1; live[2 * PAGE] = 2; live[5 * PAGE + 99] = 3; - assert_eq!(find(&live, &mut kept), [(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)]); + assert_eq!( + find(&live, &mut kept), + [(PAGE, 3 * PAGE), (5 * PAGE, 5 * PAGE + 100)] + ); assert_eq!(live, kept); assert!(find(&live, &mut kept).is_empty()); } @@ -1002,7 +1296,13 @@ mod tests { #[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 }; + 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), @@ -1010,18 +1310,44 @@ mod tests { 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 }, + 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 } }, + 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(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_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()); } diff --git a/crates/victory-gpu/src/replay/states.rs b/crates/victory-gpu/src/replay/states.rs index c159423..b7379f4 100644 --- a/crates/victory-gpu/src/replay/states.rs +++ b/crates/victory-gpu/src/replay/states.rs @@ -51,7 +51,15 @@ pub struct States { impl States { /// A texture of `subs` subresources starts in `state`. pub fn add(&mut self, res: u32, subs: u32, state: u32, decays: bool) { - self.map.insert(res, One { subs: subs.max(1), decays, all: state, each: Vec::new() }); + self.map.insert( + res, + One { + subs: subs.max(1), + decays, + all: state, + each: Vec::new(), + }, + ); } /// A placed resource is the one in use now. @@ -68,7 +76,11 @@ impl States { /// One state, or one for each subresource. pub fn get(&self, res: u32) -> Option> { let one = self.map.get(&res)?; - Some(if one.each.is_empty() { vec![one.all] } else { one.each.clone() }) + Some(if one.each.is_empty() { + vec![one.all] + } else { + one.each.clone() + }) } pub fn change(&mut self, c: &Change) { @@ -120,23 +132,50 @@ impl States { /// The changes a command makes. pub fn changes(cmd: &Cmd, out: &mut Vec) { - let promoted = |res, sub| Change { res, sub, after: COPY_DEST, promoted: true, alias: false }; + let promoted = |res, sub| Change { + res, + sub, + after: COPY_DEST, + promoted: true, + alias: false, + }; match cmd { Cmd::Barriers { all } => { for b in all { match *b { // The first half of a split barrier changes nothing yet. - Barrier::Transition { flags, res, sub, after, .. } if flags & 1 == 0 => { - out.push(Change { res, sub, after: after as u32, promoted: false, alias: false }); + Barrier::Transition { + flags, + res, + sub, + after, + .. + } if flags & 1 == 0 => { + out.push(Change { + res, + sub, + after: after as u32, + promoted: false, + alias: false, + }); } Barrier::Alias { after, .. } if after != 0 => { - out.push(Change { res: after, sub: ALL, after: 0, promoted: false, alias: true }); + out.push(Change { + res: after, + sub: ALL, + after: 0, + promoted: false, + alias: true, + }); } _ => {} } } } - Cmd::CopyTexture { dst: Loc::Sub { res, sub }, .. } => out.push(promoted(*res, *sub)), + Cmd::CopyTexture { + dst: Loc::Sub { res, sub }, + .. + } => out.push(promoted(*res, *sub)), Cmd::CopyResource { dst, .. } => out.push(promoted(*dst, ALL)), _ => {} } @@ -147,7 +186,13 @@ mod tests { use super::*; fn set(res: u32, sub: u32, after: u32) -> Change { - Change { res, sub, after, promoted: false, alias: false } + Change { + res, + sub, + after, + promoted: false, + alias: false, + } } #[test] @@ -165,7 +210,13 @@ mod tests { assert_eq!(s.get(1), Some(vec![0x80]), "equal states are one again"); // A copy into a texture in the common state leaves it a copy // destination; one into a texture in another state changes nothing. - let copy = |res| Change { res, sub: ALL, after: COPY_DEST, promoted: true, alias: false }; + let copy = |res| Change { + res, + sub: ALL, + after: COPY_DEST, + promoted: true, + alias: false, + }; s.change(©(2)); s.change(©(1)); s.decay(); @@ -183,8 +234,28 @@ mod tests { #[test] fn commands_change_states() { let mut out = Vec::new(); - let t = |flags| Barrier::Transition { flags, res: 1, sub: 0, before: 4, after: 8 }; - changes(&Cmd::Barriers { all: vec![t(1), t(2), Barrier::Alias { flags: 0, before: 3, after: 4 }, Barrier::Uav { flags: 0, res: 1 }] }, &mut out); + let t = |flags| Barrier::Transition { + flags, + res: 1, + sub: 0, + before: 4, + after: 8, + }; + changes( + &Cmd::Barriers { + all: vec![ + t(1), + t(2), + Barrier::Alias { + flags: 0, + before: 3, + after: 4, + }, + Barrier::Uav { flags: 0, res: 1 }, + ], + }, + &mut out, + ); assert_eq!(out.len(), 2); assert_eq!(out[0], set(1, 0, 8)); assert!(out[1].alias && out[1].res == 4); diff --git a/crates/victory-gpu/src/replay/wire.rs b/crates/victory-gpu/src/replay/wire.rs index b82667f..a5623c2 100644 --- a/crates/victory-gpu/src/replay/wire.rs +++ b/crates/victory-gpu/src/replay/wire.rs @@ -94,7 +94,11 @@ impl Wire for Option { } } fn get(from: &mut Dec) -> Result { - Ok(if bool::get(from)? { Some(T::get(from)?) } else { None }) + Ok(if bool::get(from)? { + Some(T::get(from)?) + } else { + None + }) } } @@ -228,14 +232,26 @@ pub mod slot { } impl Slot { - pub const EMPTY: Slot = Slot { kind: slot::EMPTY, described: 0, pad: 0, res: NONE, counter: NONE, desc: [0; 52] }; + pub const EMPTY: Slot = Slot { + kind: slot::EMPTY, + described: 0, + pad: 0, + res: NONE, + counter: NONE, + desc: [0; 52], + }; /// A slot of `kind` with the description at `desc` (`size` bytes), if any. /// /// # Safety /// `desc` is null or points at a description of `size` bytes. pub unsafe fn new(kind: u8, res: u32, counter: u32, desc: *const u8, size: usize) -> Slot { - let mut s = Slot { kind, res, counter, ..Slot::EMPTY }; + let mut s = Slot { + kind, + res, + counter, + ..Slot::EMPTY + }; if !desc.is_null() { s.described = 1; // SAFETY: the caller's description, at most 52 bytes of it. @@ -247,7 +263,14 @@ impl Slot { /// A constant buffer view's address (or its offset, in a file). pub fn address(&self) -> u64 { u64::from_le_bytes([ - self.desc[0], self.desc[1], self.desc[2], self.desc[3], self.desc[4], self.desc[5], self.desc[6], self.desc[7], + self.desc[0], + self.desc[1], + self.desc[2], + self.desc[3], + self.desc[4], + self.desc[5], + self.desc[6], + self.desc[7], ]) } @@ -276,7 +299,14 @@ impl Wire for Slot { } let mut desc = [0; 52]; desc[..n].copy_from_slice(from.take(n)?); - Ok(Slot { kind, described, pad: 0, res, counter, desc }) + Ok(Slot { + kind, + described, + pad: 0, + res, + counter, + desc, + }) } } @@ -383,7 +413,11 @@ impl Cmd { pub fn runs_shaders(&self) -> bool { matches!( self, - Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::Dispatch { .. } | Cmd::DispatchMesh { .. } | Cmd::Indirect { .. } + Cmd::Draw { .. } + | Cmd::DrawIndexed { .. } + | Cmd::Dispatch { .. } + | Cmd::DispatchMesh { .. } + | Cmd::Indirect { .. } ) } } @@ -589,59 +623,198 @@ pub(crate) mod tests { let mut desc = [0; 52]; desc[3] = 7; desc[51] = 9; - Slot { kind: slot::SAMPLER, described: 1, pad: 0, res: 4, counter: 5, desc } + Slot { + kind: slot::SAMPLER, + described: 1, + pad: 0, + res: 4, + counter: 5, + desc, + } } fn at() -> Va { - Va::At { res: 3, offset: 1 << 40 } + Va::At { + res: 3, + offset: 1 << 40, + } } pub(crate) fn every_command() -> Vec { - let placed = Loc::Placed { res: 5, offset: 512, format: 28, size: [4, 5, 6], pitch: 256 }; + let placed = Loc::Placed { + res: 5, + offset: 512, + format: 28, + size: [4, 5, 6], + pitch: 256, + }; let rects = vec![[1, 2, 3, 4]]; vec![ - Cmd::Draw { vertices: 1, instances: 2, first: 3, first_instance: 4 }, - Cmd::DrawIndexed { indices: 1, instances: 2, first: 3, base: -4, first_instance: 5 }, + Cmd::Draw { + vertices: 1, + instances: 2, + first: 3, + first_instance: 4, + }, + Cmd::DrawIndexed { + indices: 1, + instances: 2, + first: 3, + base: -4, + first_instance: 5, + }, Cmd::Dispatch { groups: [1, 2, 3] }, Cmd::DispatchMesh { groups: [4, 5, 6] }, - Cmd::CopyBuffer { dst: 1, dst_at: 2, src: 3, src_at: 4, len: 5 }, - Cmd::CopyTexture { dst: Loc::Sub { res: 1, sub: 2 }, at: [3, 4, 5], src: placed, part: Some([1, 2, 3, 4, 5, 6]) }, + Cmd::CopyBuffer { + dst: 1, + dst_at: 2, + src: 3, + src_at: 4, + len: 5, + }, + Cmd::CopyTexture { + dst: Loc::Sub { res: 1, sub: 2 }, + at: [3, 4, 5], + src: placed, + part: Some([1, 2, 3, 4, 5, 6]), + }, Cmd::CopyResource { dst: 1, src: 2 }, - Cmd::Resolve { dst: 1, dst_sub: 2, src: 3, src_sub: 4, format: 28 }, - Cmd::ResolveRegion { dst: 1, dst_sub: 2, at: [3, 4], src: 5, src_sub: 6, part: Some([0, 1, 2, 3]), format: 28, mode: 1 }, + Cmd::Resolve { + dst: 1, + dst_sub: 2, + src: 3, + src_sub: 4, + format: 28, + }, + Cmd::ResolveRegion { + dst: 1, + dst_sub: 2, + at: [3, 4], + src: 5, + src_sub: 6, + part: Some([0, 1, 2, 3]), + format: 28, + mode: 1, + }, Cmd::Topology { kind: 4 }, - Cmd::Viewports { all: vec![[0.0, 1.0, 2.0, 3.0, 0.5, 1.0]; 2] }, + Cmd::Viewports { + all: vec![[0.0, 1.0, 2.0, 3.0, 0.5, 1.0]; 2], + }, Cmd::Scissors { all: rects.clone() }, - Cmd::BlendFactor { factor: Some([0.1, 0.2, 0.3, 0.4]) }, + Cmd::BlendFactor { + factor: Some([0.1, 0.2, 0.3, 0.4]), + }, Cmd::BlendFactor { factor: None }, Cmd::StencilRef { value: 255 }, Cmd::Pipeline { pso: 9 }, Cmd::Barriers { all: vec![ - Barrier::Transition { flags: 1, res: 2, sub: ALL, before: 4, after: 8 }, - Barrier::Alias { flags: 0, before: 1, after: 2 }, + Barrier::Transition { + flags: 1, + res: 2, + sub: ALL, + before: 4, + after: 8, + }, + Barrier::Alias { + flags: 0, + before: 1, + after: 2, + }, Barrier::Uav { flags: 0, res: 0 }, ], }, Cmd::Heaps { heaps: vec![1, 2] }, - Cmd::RootSignature { graphics: true, root: 3 }, - Cmd::Table { graphics: false, param: 1, heap: 2, slot: 1 << 20 }, - Cmd::Constants { graphics: true, param: 1, offset: 2, values: vec![3, 4, 5] }, - Cmd::RootView { graphics: true, kind: slot::CBV, param: 1, va: at() }, - Cmd::IndexBuffer { view: Some((at(), 5, 42)) }, + Cmd::RootSignature { + graphics: true, + root: 3, + }, + Cmd::Table { + graphics: false, + param: 1, + heap: 2, + slot: 1 << 20, + }, + Cmd::Constants { + graphics: true, + param: 1, + offset: 2, + values: vec![3, 4, 5], + }, + Cmd::RootView { + graphics: true, + kind: slot::CBV, + param: 1, + va: at(), + }, + Cmd::IndexBuffer { + view: Some((at(), 5, 42)), + }, Cmd::IndexBuffer { view: None }, - Cmd::VertexBuffers { start: 1, count: 1, views: Some(vec![(Va::Unknown { address: 5 }, 6, 7)]) }, - Cmd::VertexBuffers { start: 1, count: 3, views: None }, - Cmd::Targets { colors: vec![view(); 3], depth: Some(view()) }, - Cmd::ClearDepth { view: view(), flags: 3, depth: 0.5, stencil: 7, rects: rects.clone() }, - Cmd::ClearTarget { view: view(), color: [1.0, 2.0, 3.0, 4.0], rects: Vec::new() }, - Cmd::Discard { res: 1, rects, subs: Some([0, 2]) }, - Cmd::BeginQuery { heap: 1, kind: 0, index: 2 }, - Cmd::EndQuery { heap: 1, kind: 2, index: 3 }, - Cmd::ResolveQuery { heap: 1, kind: 2, first: 3, count: 4, dst: 5, at: 6 }, - Cmd::Indirect { signature: 1, most: 2, args: 3, at: 4, count: 5, count_at: 6 }, - Cmd::WriteImmediate { all: vec![(at(), 1, 2), (Va::Null {}, 3, 4)] }, - Cmd::DepthBounds { min: 0.25, max: 0.75 }, + Cmd::VertexBuffers { + start: 1, + count: 1, + views: Some(vec![(Va::Unknown { address: 5 }, 6, 7)]), + }, + Cmd::VertexBuffers { + start: 1, + count: 3, + views: None, + }, + Cmd::Targets { + colors: vec![view(); 3], + depth: Some(view()), + }, + Cmd::ClearDepth { + view: view(), + flags: 3, + depth: 0.5, + stencil: 7, + rects: rects.clone(), + }, + Cmd::ClearTarget { + view: view(), + color: [1.0, 2.0, 3.0, 4.0], + rects: Vec::new(), + }, + Cmd::Discard { + res: 1, + rects, + subs: Some([0, 2]), + }, + Cmd::BeginQuery { + heap: 1, + kind: 0, + index: 2, + }, + Cmd::EndQuery { + heap: 1, + kind: 2, + index: 3, + }, + Cmd::ResolveQuery { + heap: 1, + kind: 2, + first: 3, + count: 4, + dst: 5, + at: 6, + }, + Cmd::Indirect { + signature: 1, + most: 2, + args: 3, + at: 4, + count: 5, + count_at: 6, + }, + Cmd::WriteImmediate { + all: vec![(at(), 1, 2), (Va::Null {}, 3, 4)], + }, + Cmd::DepthBounds { + min: 0.25, + max: 0.75, + }, ] } @@ -664,13 +837,23 @@ pub(crate) mod tests { out[0] }) .collect(); - assert_eq!(kinds.into_iter().collect::>(), (1..=LAST_CMD).collect::>()); - assert!(Cmd::all(&[LAST_CMD + 1]).is_err(), "a kind was added: bring LAST_CMD and the list above up to date"); + assert_eq!( + kinds.into_iter().collect::>(), + (1..=LAST_CMD).collect::>() + ); + assert!( + Cmd::all(&[LAST_CMD + 1]).is_err(), + "a kind was added: bring LAST_CMD and the list above up to date" + ); } #[test] fn a_frame_comes_back() { - let props = HeapProps { kind: 4, cpu: 3, pool: 1 }; + let props = HeapProps { + kind: 4, + cpu: 3, + pool: 1, + }; let desc = Desc { dimension: 3, alignment: 65536, @@ -685,7 +868,10 @@ pub(crate) mod tests { }; let resource = Resource { id: 2, - place: Place::Placed { heap: 1, offset: 65536 }, + place: Place::Placed { + heap: 1, + offset: 65536, + }, desc, made_in: 4, clear: Some([28, 1, 2, 3, 4]), @@ -699,36 +885,95 @@ pub(crate) mod tests { vendor: 0x1002, device: 0x744c, notes: vec!["nothing".into()], - heaps: vec![Heap { id: 1, size: 64 << 20, props: props.clone(), alignment: 65536, flags: 0x84 }], + heaps: vec![Heap { + id: 1, + size: 64 << 20, + props: props.clone(), + alignment: 65536, + flags: 0x84, + }], resources: vec![ resource.clone(), - Resource { place: Place::Committed { props, flags: 8 }, ..resource.clone() }, - Resource { place: Place::BackBuffer {}, clear: None, ..resource }, + Resource { + place: Place::Committed { props, flags: 8 }, + ..resource.clone() + }, + Resource { + place: Place::BackBuffer {}, + clear: None, + ..resource + }, ], roots: vec![(3, Blob(vec![1, 2, 3]))], - codes: vec![Code { at: 1, len: 2, hash: [7; 32] }], + codes: vec![Code { + at: 1, + len: 2, + hash: [7; 32], + }], pipelines: vec![Pipeline { id: 4, parts: vec![ Part::Root { root: 3 }, Part::Code { kind: 25, blob: 0 }, - Part::Plain { kind: 8, data: Blob(vec![9; 20]) }, - Part::Layout { elements: vec![("POSITION".into(), [1, 2, 3, 4, 5, 6])] }, + Part::Plain { + kind: 8, + data: Blob(vec![9; 20]), + }, + Part::Layout { + elements: vec![("POSITION".into(), [1, 2, 3, 4, 5, 6])], + }, ], name: "a pipeline".into(), }], - signatures: vec![Signature { id: 5, stride: 12, args: vec![[10, 0, 0, 0]], root: 0 }], - descriptor_heaps: vec![DescriptorHeap { id: 6, kind: 0, count: 10, flags: 1, runs: vec![(0, 9, Slot::EMPTY), (9, 1, view())] }], - query_heaps: vec![QueryHeap { id: 7, kind: 1, count: 8 }], - lists: vec![List { kind: 0, commands: Blob(vec![1, 2]) }], + signatures: vec![Signature { + id: 5, + stride: 12, + args: vec![[10, 0, 0, 0]], + root: 0, + }], + descriptor_heaps: vec![DescriptorHeap { + id: 6, + kind: 0, + count: 10, + flags: 1, + runs: vec![(0, 9, Slot::EMPTY), (9, 1, view())], + }], + query_heaps: vec![QueryHeap { + id: 7, + kind: 1, + count: 8, + }], + lists: vec![List { + kind: 0, + commands: Blob(vec![1, 2]), + }], submits: vec![Submit { frame: 0, lists: vec![0, MISSING], - deltas: vec![Delta { res: 2, at: 4096, len: 8192, file: 0 }], + deltas: vec![Delta { + res: 2, + at: 4096, + len: 8192, + file: 0, + }], views: vec![(6, 3, view())], }], - contents: vec![Content { res: 2, first: 0, count: 3, len: 100, file: ZERO }], - presents: vec![Present { submits: 1, res: 2, width: 4, height: 5, format: 28, pitch: 256, file: 0 }], + contents: vec![Content { + res: 2, + first: 0, + count: 3, + len: 100, + file: ZERO, + }], + presents: vec![Present { + submits: 1, + res: 2, + width: 4, + height: 5, + format: 28, + pitch: 256, + file: 0, + }], }; there_and_back(&frame); let dir = tempfile::tempdir().unwrap(); diff --git a/crates/victory-gpu/tests/replay.rs b/crates/victory-gpu/tests/replay.rs index 3d5eb5a..9f80bc9 100644 --- a/crates/victory-gpu/tests/replay.rs +++ b/crates/victory-gpu/tests/replay.rs @@ -14,7 +14,9 @@ use victory_gpu::replay::play::{self, Buffers, Options, Player}; use victory_gpu::replay::record::{self, At, Settings}; use windows::Win32::Foundation::{HANDLE, HWND, RECT}; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; -use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob}; +use windows::Win32::Graphics::Direct3D::{ + D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob, +}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::Win32::Graphics::Dxgi::*; @@ -54,6 +56,172 @@ V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, float4 ps(V v) : SV_Target { return float4(v.color, 1); } "#; +/// A quad from a mesh shader, its texture picked from the heap by index. +const MESH: &str = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=5, b0)" +cbuffer C : register(b0) { float4 place; uint pick; }; +struct V { float4 at : SV_Position; float2 uv : UV; }; +[RootSignature(RS)] +[numthreads(1, 1, 1)] +[outputtopology("triangle")] +void ms(out vertices V v[4], out indices uint3 t[2]) { + SetMeshOutputCounts(4, 2); + for (uint i = 0; i < 4; i++) { + float2 c = float2(i & 1, i >> 1); + v[i].at = float4(place.xy + c * place.zw, 0.3, 1); + v[i].uv = c; + } + t[0] = uint3(0, 1, 2); + t[1] = uint3(2, 1, 3); +} +[RootSignature(RS)] +float4 ps(V v) : SV_Target { + Texture2D t = ResourceDescriptorHeap[pick]; + return t.Load(int3(v.uv * 16, 0)) * 0.5 + float4(v.uv, 0, 0) * 0.5; +} +"#; + +/// Compiles with the Windows SDK's dxc, if there is one. +fn dxc(source: &str, entry: &str, target: &str) -> Option> { + let kits = std::fs::read_dir("C:/Program Files (x86)/Windows Kits/10/bin").ok()?; + let exe = kits + .flatten() + .map(|e| e.path().join("x64/dxc.exe")) + .filter(|p| p.exists()) + .max()?; + let dir = tempfile::tempdir().ok()?; + let (from, to) = (dir.path().join("a.hlsl"), dir.path().join("a.dxil")); + std::fs::write(&from, source).ok()?; + let out = std::process::Command::new(exe) + .args(["-T", target, "-E", entry, "-Fo"]) + .arg(&to) + .arg(&from) + .output() + .ok()?; + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + std::fs::read(to).ok() +} + +/// The mesh pipeline, from a stream, by way of a pipeline library; and the +/// signature of its indirect draws. `None` without dxc or mesh shaders. +fn mesh(device: &ID3D12Device, blend: D3D12_BLEND_DESC) -> Option<(Made, ID3D12CommandSignature)> { + #[repr(C, align(8))] + struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + topology: Sub, + } + let (ms, ps) = (dxc(MESH, "ms", "ms_6_6")?, dxc(MESH, "ps", "ps_6_6")?); + // SAFETY: plain queries and creation; the stream holds whole subobjects. + unsafe { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let size = size_of::() as u32; + device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, (&raw mut o).cast(), size) + .ok()?; + if o.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED { + return None; + } + let root: ID3D12RootSignature = device.CreateRootSignature(0, &ms).unwrap(); + let mut formats = D3D12_RT_FORMAT_ARRAY { + NumRenderTargets: 1, + ..Default::default() + }; + formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut stream = Stream { + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(&ms)), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(&ps)), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, u32::MAX), + raster: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + ..Default::default() + }, + ), + depth: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + D3D12_DEPTH_STENCIL_DESC::default(), + ), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + formats, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + DXGI_FORMAT_D32_FLOAT, + ), + samples: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let library: ID3D12PipelineLibrary1 = device + .cast::() + .unwrap() + .CreatePipelineLibrary::(&[]) + .unwrap() + .cast() + .unwrap(); + { + let made: ID3D12PipelineState = device + .cast::() + .unwrap() + .CreatePipelineState(&desc) + .unwrap(); + library.StorePipeline(w!("mesh"), &made).unwrap(); + } + let pso: ID3D12PipelineState = library.LoadPipeline(w!("mesh"), &desc).unwrap(); + record::name(&pso, "a mesh pipeline"); + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH, + ..Default::default() + }; + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 12, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature) + .unwrap(); + Some((Made { root, pso }, signature.unwrap())) + } +} + /// 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#" @@ -114,19 +282,36 @@ fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { // SAFETY: the source and names live through the call; the blobs' own // bytes. unsafe { - let r = D3DCompile(source.as_ptr().cast(), source.len(), None, None, None, entry, target, 1 << 20, 0, &mut code, Some(&mut errors)); + let r = D3DCompile( + source.as_ptr().cast(), + source.len(), + None, + None, + None, + entry, + target, + 1 << 20, + 0, + &mut code, + Some(&mut errors), + ); if r.is_err() { let e = errors.unwrap(); - let text = std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); + let text = + std::slice::from_raw_parts(e.GetBufferPointer().cast::(), e.GetBufferSize()); panic!("{}", String::from_utf8_lossy(text)); } let code = code.unwrap(); - std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()).to_vec() + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + .to_vec() } } fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { - D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() } + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + } } fn compute(device: &ID3D12Device, source: &str) -> Made { @@ -152,14 +337,21 @@ fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() } } -fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { +fn texture_desc( + size: u32, + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, +) -> D3D12_RESOURCE_DESC { D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: u64::from(size), @@ -167,7 +359,10 @@ fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> DepthOrArraySize: 1, MipLevels: 1, Format: format, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Flags: flags, ..Default::default() } @@ -182,11 +377,25 @@ enum In { Shared, } -fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES) -> (ID3D12Resource, *mut u8) { +fn committed( + device: &ID3D12Device, + place: In, + desc: &D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, +) -> (ID3D12Resource, *mut u8) { let heap = match place { - In::Card => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - In::Upload => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, - In::Back => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + In::Card => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + In::Upload => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }, + In::Back => D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }, In::Shared => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, @@ -198,7 +407,9 @@ fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state 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(); + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made) + .unwrap(); let made = made.unwrap(); if place != In::Card { made.Map(0, None, Some(&mut data)).unwrap(); @@ -207,7 +418,11 @@ fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state } } -fn moved(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { +fn moved( + 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 { @@ -227,7 +442,9 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }), + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: ManuallyDrop::new(None), + }), }, ..Default::default() } @@ -283,10 +500,15 @@ struct Scene { lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>, draw: Made, plain: Made, + mesh: Option<(Made, ID3D12CommandSignature)>, vertices: (ID3D12Resource, *mut u8), samplers: ID3D12DescriptorHeap, still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>, - copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList), + copies: ( + ID3D12CommandQueue, + ID3D12CommandAllocator, + ID3D12GraphicsCommandList, + ), args: Made, clamp: Made, add: Made, @@ -318,19 +540,28 @@ impl Scene { // SAFETY: plain creation throughout. unsafe { let queue: ID3D12CommandQueue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) .unwrap(); let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); let lists = (0..3) .map(|_| { - let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = - device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); list.Close().unwrap(); (allocator, list) }) .collect(); - let (vs, ps) = (compile(DRAW, s!("vs"), s!("vs_5_1")), compile(DRAW, s!("ps"), s!("ps_5_1"))); + let (vs, ps) = ( + compile(DRAW, s!("vs"), s!("vs_5_1")), + compile(DRAW, s!("ps"), s!("ps_5_1")), + ); let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); let mut blend = D3D12_BLEND_DESC::default(); blend.RenderTarget[0].RenderTargetWriteMask = 15; @@ -355,14 +586,20 @@ impl Scene { PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 1, DSVFormat: DXGI_FORMAT_D32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, ..Default::default() }; desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; 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 (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, @@ -379,19 +616,43 @@ impl Scene { ]; 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 }; + 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() }; - let mut signature: Option = None; - let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &argument, NodeMask: 0 }; - device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature).unwrap(); - let heap = |kind, count, flags| -> ID3D12DescriptorHeap { - device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap() + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() }; - let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + let mut signature: Option = None; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature) + .unwrap(); + 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, @@ -401,25 +662,61 @@ impl Scene { ..Default::default() }; let mut at = samplers.GetCPUDescriptorHandleForHeapStart(); - at.ptr += 2 * device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + 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); + 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, + ); let rgba = DXGI_FORMAT_R8G8B8A8_UNORM; - let (target, _) = committed(device, In::Card, &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), FROM); + let (target, _) = committed( + device, + In::Card, + &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + FROM, + ); let (depth, _) = committed( device, In::Card, - &texture_desc(SIZE, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), + &texture_desc( + SIZE, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ), D3D12_RESOURCE_STATE_DEPTH_WRITE, ); - let (fixed, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), TO); - let (image, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), UAV); + let (fixed, _) = committed( + device, + In::Card, + &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), + TO, + ); + let (image, _) = committed( + device, + In::Card, + &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + UAV, + ); let mut memory: Option = None; let desc = D3D12_HEAP_DESC { SizeInBytes: 4 << 20, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, Alignment: 0, Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, }; @@ -428,7 +725,9 @@ impl Scene { let placed = || { let mut made: Option = None; let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE); - device.CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made).unwrap(); + device + .CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made) + .unwrap(); made.unwrap() }; // Two textures in one place. @@ -449,7 +748,12 @@ impl Scene { &buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_GENERIC_READ, ); - let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO); + let back = committed( + device, + In::Back, + &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), + TO, + ); let vertices = committed( device, In::Upload, @@ -468,29 +772,61 @@ impl Scene { 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 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 copies: ( + ID3D12CommandQueue, + ID3D12CommandAllocator, + ID3D12GraphicsCommandList, + ) = { let queue = device - .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .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(); - 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")] { + for (r, n) in [ + (&sum, "sum"), + (&image, "image"), + (&target, "target"), + (&shared.0, "shared"), + (&one, "one"), + (&other, "other"), + ] { record::name(r, n); } device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart()); device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart()); - let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; let swap = window.then(|| swap_chain(&queue)); let scene = Scene { device: device.clone(), @@ -501,6 +837,7 @@ impl Scene { lists, draw, plain, + mesh: mesh(device, blend), vertices, samplers, still: still.to_vec(), @@ -531,24 +868,45 @@ impl Scene { swap, }; // Null views everywhere, by copies of a slot made elsewhere. - let block = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE); + let block = heap( + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + 16, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + ); let null = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: rgba, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, }; let from = block.GetCPUDescriptorHandleForHeapStart(); for i in 0..16 { - let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + i * step }; + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: from.ptr + i * step, + }; device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at); } for i in (0..4992).step_by(16) { - device.CopyDescriptorsSimple(16, scene.cpu(i), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + device.CopyDescriptorsSimple( + 16, + scene.cpu(i), + from, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); } // The rest with the other copying method, in unlike pieces. let to = [scene.cpu(4992), scene.cpu(4994)]; - let sources = [from, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + 4 * step }]; + let sources = [ + from, + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: from.ptr + 4 * step, + }, + ]; device.CopyDescriptors( 2, to.as_ptr(), @@ -560,7 +918,12 @@ impl Scene { ); scene.show(4001, &scene.other); scene.show(4002, &scene.one); - device.CreateUnorderedAccessView(&scene.image, None::<&ID3D12Resource>, None, scene.cpu(7)); + device.CreateUnorderedAccessView( + &scene.image, + None::<&ID3D12Resource>, + None, + scene.cpu(7), + ); scene } } @@ -568,13 +931,18 @@ impl Scene { fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE { // SAFETY: a slot of the heap. let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() }; - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * self.step } + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + i * self.step, + } } /// Slot `i` shows `texture`. fn show(&self, i: usize, texture: &ID3D12Resource) { // SAFETY: a slot of the heap and a live texture. - unsafe { self.device.CreateShaderResourceView(texture, None, self.cpu(i)) }; + unsafe { + self.device + .CreateShaderResourceView(texture, None, self.cpu(i)) + }; } fn wait(&mut self) { @@ -582,7 +950,9 @@ impl Scene { // SAFETY: our queue, fence and event. unsafe { self.queue.Signal(&self.fence, self.value).unwrap(); - self.fence.SetEventOnCompletion(self.value, self.event).unwrap(); + self.fence + .SetEventOnCompletion(self.value, self.event) + .unwrap(); WaitForSingleObject(self.event, INFINITE); self.device.GetDeviceRemovedReason().unwrap(); } @@ -599,7 +969,8 @@ impl Scene { } fn send(&self, lists: &[&ID3D12GraphicsCommandList]) { - let all: Vec> = lists.iter().map(|l| Some(l.cast().unwrap())).collect(); + let all: Vec> = + lists.iter().map(|l| Some(l.cast().unwrap())).collect(); // SAFETY: closed lists. unsafe { self.queue.ExecuteCommandLists(&all) }; } @@ -611,7 +982,13 @@ impl Scene { let mut c = color; c[1] = c[1].wrapping_add((x * 8 + y) as u8); // SAFETY: inside the mapping (16 rows of 256 bytes). - unsafe { self.texels.1.add(at + y * 256 + x * 4).cast::<[u8; 4]>().write(c) }; + unsafe { + self.texels + .1 + .add(at + y * 256 + x * 4) + .cast::<[u8; 4]>() + .write(c) + }; } } } @@ -621,13 +998,17 @@ impl Scene { // SAFETY: a borrowed pointer never released. pResource: unsafe { std::mem::transmute_copy(&self.texels.0) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, 16) }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint(at, 16), + }, }; let to = D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. pResource: unsafe { std::mem::transmute_copy(texture) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, }; // SAFETY: an open list; live resources. unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; @@ -643,10 +1024,24 @@ 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 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); + 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, + ); } } @@ -659,7 +1054,14 @@ impl Scene { l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536); l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress()); l.Dispatch(1, 1, 1); - l.ResourceBarrier(&[uav_barrier(), moved(&self.arguments, UAV, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + l.ResourceBarrier(&[ + uav_barrier(), + moved( + &self.arguments, + UAV, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ), + ]); l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]); l.SetComputeRootSignature(&self.clamp.root); l.SetPipelineState(&self.clamp.pso); @@ -671,7 +1073,11 @@ impl Scene { l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress()); l.Dispatch(1, 1, 1); l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]); - l.ResourceBarrier(&[moved(&self.arguments, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, UAV)]); + l.ResourceBarrier(&[moved( + &self.arguments, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + UAV, + )]); } } @@ -688,11 +1094,24 @@ impl Scene { fn targets(&self, l: &ID3D12GraphicsCommandList) { // SAFETY: an open list; live objects. unsafe { - let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + let (rtv, dsv) = ( + self.rtvs.GetCPUDescriptorHandleForHeapStart(), + self.dsvs.GetCPUDescriptorHandleForHeapStart(), + ); l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); 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.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()), Some(self.samplers.clone())]); } } @@ -703,15 +1122,34 @@ impl Scene { // 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]]; + 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]); + 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.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); } @@ -752,16 +1190,34 @@ impl Scene { 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 }; + 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 }; + 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)); + 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), @@ -785,13 +1241,26 @@ impl Scene { // SAFETY: as above. unsafe { let desc = t.GetDesc(); - let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize }; + 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); + 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 { @@ -806,7 +1275,10 @@ impl Scene { 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()) + .map(|r| { + std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize) + .to_vec() + }) .collect(); subs.push((pitch, rows)); } @@ -841,7 +1313,10 @@ impl Scene { self.give(40, 7 + n); let l = self.open(0); l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]); - let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart()); + let (rtv, dsv) = ( + self.rtvs.GetCPUDescriptorHandleForHeapStart(), + self.dsvs.GetCPUDescriptorHandleForHeapStart(), + ); l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None); l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); self.arguments(&l, COMMON); @@ -858,6 +1333,12 @@ impl Scene { // The second: other constants and another texture in the same // places, and the second texture in the memory of the first. self.show(4000, &self.other); + // Arguments of a mesh draw. + self.constants + .1 + .add(1024) + .cast::<[u32; 3]>() + .write([1, 1, 1]); self.place(0, [-0.9, 0.3, 0.6, 0.6]); self.place(256, [0.3, -0.8, 0.6, 0.5]); self.give(40, 100 + n); @@ -873,6 +1354,26 @@ impl Scene { l.ResourceBarrier(&[moved(&self.one, TO, READ)]); self.arguments(&l, ARGUMENTS); self.quad(&l, 4002, 256, 0); + if let Some((made, signature)) = &self.mesh { + l.SetGraphicsRootSignature(&made.root); + l.SetPipelineState(&made.pso); + let constants = [ + (-0.3f32).to_bits(), + (-0.9f32).to_bits(), + 0.5f32.to_bits(), + 0.4f32.to_bits(), + 4002, + ]; + l.SetGraphicsRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0); + l.ExecuteIndirect( + signature, + 1, + &self.constants.0, + 1024, + None::<&ID3D12Resource>, + 0, + ); + } l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]); // And back, for the next frame. l.ResourceBarrier(&[moved(&self.one, READ, TO)]); @@ -909,7 +1410,9 @@ impl Scene { queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); self.value += 1; queue.Signal(&self.fence, self.value).unwrap(); - self.fence.SetEventOnCompletion(self.value, self.event).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(); @@ -928,12 +1431,16 @@ impl Scene { let to = |at: u64, size| 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: footprint(at, size) }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint(at, size), + }, }; let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(t), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, }; l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]); l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None); @@ -943,7 +1450,9 @@ impl Scene { l.Close().unwrap(); self.send(&[&l]); self.wait(); - let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec(); + 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), @@ -960,7 +1469,9 @@ fn sub_of(t: &ID3D12Resource, sub: u32) -> 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 }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: sub, + }, } } @@ -986,20 +1497,40 @@ fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT { fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) { // SAFETY: plain creation. unsafe { - let hwnd = - CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!("replay test"), WS_POPUP, 0, 0, 64, 64, None, None, None, None).unwrap(); + let hwnd = CreateWindowExW( + WINDOW_EX_STYLE(0), + w!("STATIC"), + w!("replay test"), + WS_POPUP, + 0, + 0, + 64, + 64, + None, + None, + None, + None, + ) + .unwrap(); let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); let desc = DXGI_SWAP_CHAIN_DESC1 { Width: 64, Height: 64, Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, BufferCount: 2, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, ..Default::default() }; - let chain = factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None).unwrap().cast().unwrap(); + let chain = factory + .CreateSwapChainForHwnd(queue, hwnd, &desc, None, None) + .unwrap() + .cast() + .unwrap(); (chain, hwnd) } } @@ -1015,7 +1546,10 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) assert_eq!(report.frame_ms.len(), options.loops as usize); assert!(report.median_ms() > 0.0); let (db, same) = report.picture.unwrap(); - assert!(same && db.is_infinite(), "{what}: the picture differs ({db} dB)"); + assert!( + same && db.is_infinite(), + "{what}: the picture differs ({db} dB)" + ); let mut get = |name: &str| { let id = player.named(name).unwrap(); player.contents(id).unwrap().unwrap() @@ -1023,19 +1557,38 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) assert_eq!(get("sum"), expected.sum, "{what}: sum"); 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!( + get("shared") == expected.shared, + "{what}: memory the CPU sees" + ); 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); + 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); + 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 } @@ -1068,82 +1621,213 @@ fn a_frame_is_recorded_and_replayed() { // 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!( + 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::>(), [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_eq!( + without + .still + .iter() + .map(|s| s.subs.len()) + .collect::>(), + [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()); // With it: armed at the first present, the fourth frame is captured (a // 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, always: false }; + 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, always: false }, &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"); let mut scene = Scene::new(&device, true); eprintln!("scene made"); (0..4).for_each(|n| scene.frame(n)); - assert_eq!(record::finished(), Some(folder.clone()), "see {}", folder.display()); + assert_eq!( + record::finished(), + Some(folder.clone()), + "see {}", + folder.display() + ); let expected = scene.outcome(); // It goes on as it did without the recorder. scene.frame(4); let after = scene.outcome(); - assert!(after == without, "the recorder changed what the program makes"); + assert!( + after == without, + "the recorder changed what the program makes" + ); drop(scene); record::unhook(&device); assert_eq!(table_of(&device), own, "the device is as it was"); - for name in ["frame.bin", "contents.bin", "deltas.bin", "shaders.bin", "present.bin", "notes.txt", "frame-0.png"] { + for name in [ + "frame.bin", + "contents.bin", + "deltas.bin", + "shaders.bin", + "present.bin", + "notes.txt", + "frame-0.png", + ] { assert!(folder.join(name).exists(), "{name}"); } - println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap()); + println!( + "{}", + std::fs::read_to_string(folder.join("notes.txt")).unwrap() + ); - let plain = Options { loops: 3, ..Default::default() }; + let plain = Options { + loops: 3, + ..Default::default() + }; let mut player = Player::load(dir.path(), &plain).unwrap(); check(&mut player, &plain, &expected, "unchanged"); - let detailed = Options { detailed: true, ..plain.clone() }; + let detailed = Options { + detailed: true, + ..plain.clone() + }; let report = check(&mut player, &detailed, &expected, "detailed"); - let count = |kind: &str| report.categories.iter().find(|c| c.0 == kind).map_or(0, |c| c.2); + let count = |kind: &str| { + report + .categories + .iter() + .find(|c| c.0 == kind) + .map_or(0, |c| c.2) + }; assert_eq!(count("argument clamps (ours)"), 3); assert_eq!(count("indirect draws"), 5); + assert_eq!(count("draws"), 1); + let meshes = count("indirect mesh draws"); + println!("{meshes} mesh draws"); + if meshes > 0 { + assert!( + report + .shaders + .iter() + .any(|s| s.2.starts_with("a mesh pipeline (DXIL ")), + "{:?}", + report.shaders + ); + } assert_eq!(count("dispatches"), 6); assert_eq!(count("clears"), 2); - assert!(report.shaders.iter().any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), "{:?}", report.shaders); - let merged = Options { merge_barriers: true, ..plain.clone() }; + assert!( + report + .shaders + .iter() + .any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), + "{:?}", + report.shaders + ); + let merged = Options { + merge_barriers: true, + ..plain.clone() + }; check(&mut player, &merged, &expected, "merged barriers"); - let clamps = Options { skip_clamps: true, ..plain.clone() }; + let clamps = Options { + skip_clamps: true, + ..plain.clone() + }; let report = check(&mut player, &clamps, &expected, "without clamps"); - assert!(report.notes.iter().any(|n| n.contains("3 clamp passes")), "{:?}", report.notes); - let one = Options { one_submit: true, ..plain.clone() }; + assert!( + report.notes.iter().any(|n| n.contains("3 clamp passes")), + "{:?}", + report.notes + ); + let one = Options { + one_submit: true, + ..plain.clone() + }; check(&mut player, &one, &expected, "one submission"); - let hash = Options { skip_hash_passes: true, ..plain.clone() }; - check(&mut player, &hash, &expected, "without hash passes (there are none)"); + let hash = Options { + skip_hash_passes: true, + ..plain.clone() + }; + check( + &mut player, + &hash, + &expected, + "without hash passes (there are none)", + ); // These change what is drawn: they run, and then the frame is as before. - let no_barriers = Options { no_barriers: true, ..plain.clone() }; + let no_barriers = Options { + no_barriers: true, + ..plain.clone() + }; player.run(&no_barriers).unwrap(); - let some = Options { only: Some((0, 1)), ..plain.clone() }; + let some = Options { + only: Some((0, 1)), + ..plain.clone() + }; player.run(&some).unwrap(); - let skip = Options { skip_shaders: vec!["a drawing".into()], ..plain.clone() }; + let skip = Options { + skip_shaders: vec!["a drawing".into()], + ..plain.clone() + }; let report = player.run(&skip).unwrap(); - assert!(!report.picture.unwrap().1, "without its draws the picture is another"); - assert!(report.notes.iter().any(|n| n.contains("1 pipelines match")) && report.notes.iter().any(|n| n.contains("left out 5 commands"))); - let kept = Options { restore: false, ..plain.clone() }; + assert!( + !report.picture.unwrap().1, + "without its draws the picture is another" + ); + assert!( + report.notes.iter().any(|n| n.contains("1 pipelines match")) + && report + .notes + .iter() + .any(|n| n.contains("left out 5 commands")) + ); + let kept = Options { + restore: false, + ..plain.clone() + }; player.run(&kept).unwrap(); check(&mut player, &plain, &expected, "unchanged again"); drop(player); for buffers in [Buffers::Card, Buffers::Pc] { - let o = Options { buffers, ..plain.clone() }; + let o = Options { + buffers, + ..plain.clone() + }; let mut player = Player::load(dir.path(), &o).unwrap(); check(&mut player, &o, &expected, &format!("buffers {buffers:?}")); } - let o = Options { compare: true, merge_barriers: true, loops: 2, ..Default::default() }; + let o = Options { + compare: true, + merge_barriers: true, + loops: 2, + ..Default::default() + }; let both = play::replay(dir.path(), &o).unwrap(); assert_eq!(both.len(), 2); assert!(both.iter().all(|(_, r)| r.picture.unwrap().1)); @@ -1157,9 +1841,17 @@ fn a_frame_is_recorded_and_replayed() { let _ = q.GetMessage(i, None, &mut size); let mut buffer = vec![0u64; size.div_ceil(8)]; let m = buffer.as_mut_ptr().cast::(); - if q.GetMessage(i, Some(m), &mut size).is_ok() && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 { - let text = std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); - println!("D3D12 {} {}: {}", (*m).Severity.0, (*m).ID.0, String::from_utf8_lossy(text)); + if q.GetMessage(i, Some(m), &mut size).is_ok() + && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 + { + let text = + std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength); + println!( + "D3D12 {} {}: {}", + (*m).Severity.0, + (*m).ID.0, + String::from_utf8_lossy(text) + ); } } } diff --git a/crates/victory-gpu/tests/replay_big.rs b/crates/victory-gpu/tests/replay_big.rs index 34a9b95..9f60399 100644 --- a/crates/victory-gpu/tests/replay_big.rs +++ b/crates/victory-gpu/tests/replay_big.rs @@ -3,7 +3,8 @@ //! 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. +//! `BIG_TEXTURES` (17000), `BIG_CARD` (600 buffers of 1 MB in the card's +//! memory) and `BIG_FOLDER` (a temporary one) change it. #![cfg(all(windows, feature = "diagnostics"))] use std::mem::ManuallyDrop; @@ -24,12 +25,18 @@ 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_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_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE, ), @@ -50,7 +57,10 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() @@ -59,7 +69,9 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut 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(); + 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(); @@ -72,7 +84,11 @@ fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut } } -fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { +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 { @@ -88,6 +104,14 @@ fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RES } } +/// A number from the environment. +fn number(name: &str, otherwise: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(otherwise) +} + struct Big { device: ID3D12Device, queue: ID3D12CommandQueue, @@ -105,7 +129,10 @@ struct Big { 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 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), @@ -113,24 +140,45 @@ impl Big { DepthOrArraySize: 1, MipLevels: if size == 256 { 9 } else { 1 }, Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Flags: flags, ..Default::default() }; let mut made: Option = None; // SAFETY: plain creation. - unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap() }; + 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() }) + .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(); + 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) }) @@ -143,26 +191,47 @@ impl Big { NodeMask: 0, }) .unwrap(); - let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; let start = views.GetCPUDescriptorHandleForHeapStart().ptr; let textures: Vec = (0..textures) - .map(|_| texture(256, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE)) + .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 }; + 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(); + 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() }, + 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 }); + device.CreateShaderResourceView( + b, + Some(&desc), + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start + i * step, + }, + ); } Big { device: device.clone(), @@ -171,11 +240,17 @@ impl Big { value: 0, lists, _textures: textures, - card: (0..600).map(|_| buffer(device, 0, 1 << 20).0).collect(), + card: (0..number("BIG_CARD", 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), + target: texture( + 1024, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + ), } } } @@ -194,6 +269,21 @@ impl Big { } fn frame(&mut self, n: usize) { + if n == 0 { + // Nothing in the card's buffers is all zero, as in a title's. + // SAFETY: a list whose last run has finished; live buffers. + unsafe { + let (a, l) = &self.lists[0]; + a.Reset().unwrap(); + l.Reset(a, None).unwrap(); + for (i, card) in self.card.iter().enumerate() { + l.CopyBufferRegion(card, 0, &self.upload[i % self.upload.len()].0, 0, 1 << 20); + } + l.Close().unwrap(); + self.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]); + } + self.wait(); + } for s in 0..SUBMITS { // SAFETY: lists whose last run has finished; mappings written // inside their bounds. @@ -206,8 +296,16 @@ impl Big { 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.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(); @@ -231,8 +329,10 @@ fn a_frame_of_a_titles_size() { // 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 textures = number("BIG_TEXTURES", 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); @@ -245,7 +345,12 @@ fn a_frame_of_a_titles_size() { } 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 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); @@ -253,17 +358,39 @@ fn a_frame_of_a_titles_size() { 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); + 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()); + 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()); + 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(); + 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)); diff --git a/docs/replay.md b/docs/replay.md new file mode 100644 index 0000000..7333348 --- /dev/null +++ b/docs/replay.md @@ -0,0 +1,102 @@ +# Recording a frame and running it again + +A diagnostics build can write down one frame's D3D12 work (what the host +layer sends to the card, and the memory it reads) and run it again without +the title, to see where the card's time goes and to try changes in seconds. +Code: `crates/victory-gpu/src/replay`. + +## Recording + +Off unless `VICTORY_RECORD` is set. Build with +`cargo build --locked --profile diag -p victory --features diagnostics`. + +| variable | meaning | +|---|---| +| `VICTORY_RECORD=` | on; the capture goes to `\capture-` (outside the repository) | +| `VICTORY_RECORD_AT=` or `f` | when: seconds after the device was made, or a number of presents. Unset: only the trigger file | +| file `\go` | when it appears, the capture starts (always watched) | +| `VICTORY_RECORD_FRAMES=` | frames to capture (1) | +| `VICTORY_RECORD_ALWAYS=1` | record lists from the start: needed only if notes say lists were not recorded (a title that submits old lists again) | + +At the time given, lists are recorded for a few frames, until a frame's lists +were all recorded; the next frame is captured: everything sent to the drawing +queue between two presents (the first may be the swap chain's own work for +the frame before). One capture per process. At the frame's first submission +the card is drained and its memory copied out; before each later one the card +is drained again and what the CPU changed is written. The title stands still +meanwhile. `frame recorder: the frame is captured` in the log and `frame.bin` +in the folder mean it is done; `failed.txt` that it failed. + +**Read `notes.txt`**: everything that could not be recorded is listed there +(and in every replay's report). Only the line with the totals, waits of the +drawing queue and lists of another queue (the relay's copies) are expected. + +Measured on a made-up frame of a title's size (12,000 resources, 1.5 million +views, 30 submissions, 40,000 calls): a frame takes 3-10 ms more with the +recorder on, the capture stands still for 5.4 s and is 9 GB (8 GB of the card's +memory at 2.3 GB/s, 1 GB the CPU wrote). The recorder holds a copy of the +memory both sides see that the frame reads, and 1 GB or more of read-back +buffers, until it is done. + +## Running it + + victory replay [--loops 5] [--timing detailed] [experiments] + +`` is the one given as `VICTORY_RECORD` (its last capture) or a +capture. Each loop puts back what the one before changed and sends the frame +without waiting between submissions. Reported, from timestamps on the card: +the frame (first list's start to last list's end), each submission, copies +that stand for what the CPU wrote between submissions (not the title's cost), +and gaps. With `--timing detailed`, each command: sums by kind and the +costliest pipelines with the names the runtime logs and their DXIL hashes +(blake3). A command's time is from the end of the one before to its own end: +draws overlap, so it is a share of the list, not a cost alone; the extra +timestamps cost a little too. The picture goes to `replay.png` and is compared +with the presented one. + +| switch | does | +|---|---| +| `--compare` | runs the frame unchanged first and prints the difference | +| `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run | +| `--skip-hash-passes` | no compare/rehash passes over card buffers | +| `--no-barriers` | no unordered-access barriers | +| `--merge-barriers` | joins barrier calls with no work between them | +| `--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 | +| `--skip-shader ` | 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 | + +Use the median of several loops; the first is slower. An experiment that +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. + +## Limits + +- Not recorded, but reported when used: reserved (tiled) resources, bundles, + ray tracing, render passes, enhanced barriers, predication, stream output, + `ClearUnorderedAccessView`, shading rate, newer creation methods + (`CreateCommittedResource1` and on). +- Not kept: contents of multisampled textures, of textures in memory the CPU + sees, and of texture levels over 256 MB; resources of other queues' work. +- Texture states come from the barriers seen. A resource that overlaps the + one last used (aliasing) is taken as without contents. +- Addresses in memory are not rewritten: indirect arguments with addresses + (vertex buffers, root views) are reported, and would be wrong. Descriptors + and root arguments are. +- Views replaced during the frame get a heap of their own per submission in + the replay (64 MB for two million views). +- Upload heaps become custom write-combined ones in the replay, as the card + writes what the CPU wrote. +- What the CPU changes in memory both see is taken before each submission, by + pages of 4 KiB, of what that submission reads of it (all of a buffer that a + descriptor names). Pages the card wrote there are part of it: they count as + copies, and set the card's own results to the recorded ones. +- The card's clocks are the system's: other programs on the card change the + times. + +Tests: `cargo test -p victory-gpu --features diagnostics` (`tests/replay.rs` +runs a small program and compares every byte; `VICTORY_TEST_D3D_DEBUG=1` adds +the debug layer) and `tests/replay_big.rs` (`--ignored`).