Frame replay: usage doc, mesh draws and a title's size in its tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 20:23:46 -06:00
1 parent d7ecfd2bba
commit af481877f3
13 files changed
+4274 -828

No files matched your search

+411 -85
View File
@@ -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<dyn std::error::Error + Send + Sync>;
@@ -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<Vec<u8>>>, Arc<Vec<Change>>);
let closed: Vec<Option<Closed>> = lists.iter().map(|&p| r.list(p).and_then(|l| l.closed())).collect();
let closed: Vec<Option<Closed>> = 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<Closed>| 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<Option<Arc<Vec<u8>>>> = closed.iter().map(|c| c.as_ref().and_then(|c| c.0.clone())).collect();
let commands: Vec<Option<Arc<Vec<u8>>>> = 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<T>(&mut self, what: &'static str, f: impl FnOnce(&mut Self) -> Result<T, Fault>) -> Result<T, Fault> {
fn timed<T>(
&mut self,
what: &'static str,
f: impl FnOnce(&mut Self) -> Result<T, Fault>,
) -> Result<T, Fault> {
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<u64, u64> = 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<usize> = 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<Arc<Res>> = 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<Kept> = self.buffers.iter_mut().map(|b| Kept(b.kept.as_mut_ptr())).collect();
let kept: Vec<Kept> = self
.buffers
.iter_mut()
.map(|b| Kept(b.kept.as_mut_ptr()))
.collect();
let next = AtomicUsize::new(0);
let out: std::sync::Mutex<Vec<Delta>> = std::sync::Mutex::default();
let failed: std::sync::Mutex<Option<std::io::Error>> = 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<Arc<Vec<u8>>>]) -> Result<(), Fault> {
fn submit(
&mut self,
r: &Recorder,
_queue: &ID3D12CommandQueue,
lists: &[Option<Arc<Vec<u8>>>],
) -> Result<(), Fault> {
let first = !self.started;
if first {
self.start(r)?;
@@ -615,7 +794,8 @@ impl Capture {
let heaps: Vec<Arc<Heap>> = read(&r.descriptors).visible().cloned().collect();
for h in heaps {
let runs = runs_of(r, &h.all());
self.viewed.extend(runs.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
self.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<wire::Heap> = {
let all = lock(&r.heaps);
let used: HashSet<u32> =
resources.iter().filter_map(|res| if let Place::Placed { heap, .. } = res.place { Some(heap) } else { None }).collect();
let used: HashSet<u32> = 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<wire::Signature> = {
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<u32> = from.iter().map(|&s| if s == COMMON || s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect();
let to: Vec<u32> = 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());
}