victory replay, larger tests of it

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

No files matched your search

+263 -5
View File
@@ -25,7 +25,7 @@ use windows::core::{Interface, PCSTR, s, w};
const SIZE: u32 = 128;
const DRAW: &str = r#"
#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT)"
#define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), DescriptorTable(Sampler(s0))"
cbuffer Pick : register(b0) { uint pick; uint pad; };
cbuffer Place : register(b1) { float4 place; };
Texture2D all[] : register(t0);
@@ -45,6 +45,15 @@ V vs(uint i : SV_VertexID) {
float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); }
"#;
/// Triangles of vertices and indices.
const PLAIN: &str = r#"
#define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)"
struct V { float4 at : SV_Position; float3 color : COLOR; };
[RootSignature(RS)]
V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, 1); v.color = color; return v; }
float4 ps(V v) : SV_Target { return float4(v.color, 1); }
"#;
/// Writes the arguments of indirect draws (two records: six vertices, and
/// one far too many that the clamp cuts to none).
const ARGS: &str = r#"
@@ -247,9 +256,18 @@ const TO: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST;
const FROM: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_SOURCE;
const ARGUMENTS: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
/// A texture the frames do not touch: what each subresource holds, row by
/// row, with the rows' distance in its copyable layout.
#[derive(PartialEq, Debug, Clone)]
struct Still {
name: &'static str,
subs: Vec<(usize, Vec<Vec<u8>>)>,
}
/// What the program ends with.
#[derive(PartialEq, Debug)]
struct Outcome {
still: Vec<Still>,
picture: Vec<u8>,
image: Vec<u8>,
sum: Vec<u8>,
@@ -264,6 +282,11 @@ struct Scene {
value: u64,
lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
draw: Made,
plain: Made,
vertices: (ID3D12Resource, *mut u8),
samplers: ID3D12DescriptorHeap,
still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>,
copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList),
args: Made,
clamp: Made,
add: Made,
@@ -339,6 +362,26 @@ impl Scene {
let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
record::name(&pso, "a drawing pipeline");
let draw = Made { root, pso };
let (vs, ps) = (compile(PLAIN, s!("vs"), s!("vs_5_1")), compile(PLAIN, s!("ps"), s!("ps_5_1")));
let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
let element = |name, index, format, at| D3D12_INPUT_ELEMENT_DESC {
SemanticName: name,
SemanticIndex: index,
Format: format,
InputSlot: 0,
AlignedByteOffset: at,
InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
InstanceDataStepRate: 0,
};
let elements = [
element(s!("POSITION"), 0, DXGI_FORMAT_R32G32_FLOAT, 0),
element(s!("COLOR"), 1, DXGI_FORMAT_R32G32B32_FLOAT, 8),
];
desc.pRootSignature = std::mem::transmute_copy(&root);
(desc.VS, desc.PS) = (code(&vs), code(&ps));
desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elements.as_ptr(), NumElements: 2 };
let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
let plain = Made { root, pso };
let clamp = compute(device, CLAMP);
record::name(&clamp.pso, play::CLAMP);
let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() };
@@ -348,6 +391,18 @@ impl Scene {
let heap = |kind, count, flags| -> ID3D12DescriptorHeap {
device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap()
};
let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
let sampler = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
MaxLOD: 8.0,
..Default::default()
};
let mut at = samplers.GetCPUDescriptorHandleForHeapStart();
at.ptr += 2 * device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize;
device.CreateSampler(&sampler, at);
let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
@@ -395,6 +450,41 @@ impl Scene {
D3D12_RESOURCE_STATE_GENERIC_READ,
);
let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO);
let vertices = committed(
device,
In::Upload,
&buffer_desc(4096, D3D12_RESOURCE_FLAG_NONE),
D3D12_RESOURCE_STATE_GENERIC_READ,
);
let still = {
let blocks = D3D12_RESOURCE_DESC {
MipLevels: 5,
DepthOrArraySize: 3,
..texture_desc(64, DXGI_FORMAT_BC7_UNORM, D3D12_RESOURCE_FLAG_NONE)
};
let volume = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D,
DepthOrArraySize: 8,
MipLevels: 3,
..texture_desc(16, DXGI_FORMAT_R16_FLOAT, D3D12_RESOURCE_FLAG_NONE)
};
let stencil = texture_desc(32, DXGI_FORMAT_R32G8X24_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
let (write, read) = (D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
[("blocks", blocks, TO, READ), ("volume", volume, TO, read), ("stencil", stencil, write, write)].map(|(name, d, made_in, ends)| {
let (t, _) = committed(device, In::Card, &d, made_in);
record::name(&t, name);
(name, t, ends)
})
};
let copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList) = {
let queue = device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() })
.unwrap();
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).unwrap();
let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None).unwrap();
list.Close().unwrap();
(queue, allocator, list)
};
for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] {
record::name(r, n);
}
@@ -410,6 +500,11 @@ impl Scene {
value: 0,
lists,
draw,
plain,
vertices,
samplers,
still: still.to_vec(),
copies,
args: compute(device, ARGS),
clamp,
add: compute(device, ADD),
@@ -548,6 +643,9 @@ impl Scene {
l.SetGraphicsRoot32BitConstant(0, pick, 0);
l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at);
l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart());
let step = self.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
let first = self.samplers.GetGPUDescriptorHandleForHeapStart().ptr;
l.SetGraphicsRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: first + 2 * u64::from(step) });
l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0);
}
}
@@ -595,16 +693,136 @@ impl Scene {
let size = SIZE as f32;
l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]);
l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]);
l.SetDescriptorHeaps(&[Some(self.views.clone())]);
l.SetDescriptorHeaps(&[Some(self.views.clone()), Some(self.samplers.clone())]);
}
}
/// A triangle with vertices and indices.
fn triangle(&self, l: &ID3D12GraphicsCommandList, n: u32) {
// SAFETY: an open list; live objects; inside the mapping, which the
// card does not use now.
unsafe {
let x = 0.5 + 0.05 * n as f32;
let vertices = [[x, 0.4, 1.0, 0.0, 0.0], [x + 0.3, 0.4, 0.0, 1.0, 0.0], [x, 0.9, 0.0, 0.0, 1.0f32]];
self.vertices.1.cast::<[[f32; 5]; 3]>().write(vertices);
self.vertices.1.add(1024).cast::<[u16; 4]>().write([9, 2, 0, 1]);
let at = self.vertices.0.GetGPUVirtualAddress();
l.SetGraphicsRootSignature(&self.plain.root);
l.SetPipelineState(&self.plain.pso);
l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
l.IASetVertexBuffers(0, Some(&[D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: 60, StrideInBytes: 20 }]));
let indices = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at + 1024, SizeInBytes: 8, Format: DXGI_FORMAT_R16_UINT };
l.IASetIndexBuffer(Some(&indices));
l.DrawIndexedInstanced(3, 1, 1, 0, 0);
}
}
/// Fills the textures no frame touches.
fn fill_still(&mut self) {
// SAFETY: an open list; live objects; mappings written inside their
// bounds.
unsafe {
let (up, data) = committed(
&self.device,
In::Upload,
&buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE),
D3D12_RESOURCE_STATE_GENERIC_READ,
);
for i in 0..1 << 20 {
data.add(i).write((i * 31 + i / 251) as u8 & 0x3b);
}
let l = self.open(0);
let mut at = 0;
for (name, t, ends) in &self.still {
if *name == "stencil" {
let view = D3D12_DEPTH_STENCIL_VIEW_DESC {
Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
..Default::default()
};
let heap: ID3D12DescriptorHeap = self
.device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
NumDescriptors: 1,
..Default::default()
})
.unwrap();
let dsv = heap.GetCPUDescriptorHandleForHeapStart();
self.device.CreateDepthStencilView(t, Some(&view), dsv);
let both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL;
l.ClearDepthStencilView(dsv, both, 0.75, 3, None);
let part = RECT { left: 5, top: 6, right: 20, bottom: 17 };
l.ClearDepthStencilView(dsv, both, 0.25, 200, Some(&[part]));
continue;
}
let desc = t.GetDesc();
let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize };
for sub in 0..u32::from(layers * desc.MipLevels) {
let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let mut total = 0;
self.device.GetCopyableFootprints(&desc, sub, 1, at, Some(&mut f), None, None, Some(&mut total));
at = (at + total).next_multiple_of(512);
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&up),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
};
l.CopyTextureRegion(&sub_of(t, sub), 0, 0, 0, &from, None);
}
l.ResourceBarrier(&[moved(t, TO, *ends)]);
}
l.Close().unwrap();
self.send(&[&l]);
self.wait();
}
}
/// What they hold.
fn read_still(&mut self) -> Vec<Still> {
let mut all = Vec::new();
for (name, t, state) in self.still.clone() {
// SAFETY: as above.
unsafe {
let desc = t.GetDesc();
let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize };
let planes = if name == "stencil" { 2 } else { 1 };
let mut subs = Vec::new();
for sub in 0..u32::from(layers * desc.MipLevels) * planes {
let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let (mut rows, mut len) = (0, 0);
self.device.GetCopyableFootprints(&desc, sub, 1, 0, Some(&mut f), Some(&mut rows), Some(&mut len), None);
let l = self.open(0);
l.ResourceBarrier(&[moved(&t, state, FROM)]);
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&self.back.0),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
};
l.CopyTextureRegion(&to, 0, 0, 0, &sub_of(&t, sub), None);
l.ResourceBarrier(&[moved(&t, FROM, state)]);
l.Close().unwrap();
self.send(&[&l]);
self.wait();
let pitch = f.Footprint.RowPitch as usize;
let rows = (0..rows as usize * f.Footprint.Depth as usize)
.map(|r| std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize).to_vec())
.collect();
subs.push((pitch, rows));
}
all.push(Still { name, subs });
}
}
all
}
fn frame(&mut self, n: u32) {
// SAFETY: open lists of ours, live objects; memory is written while
// the card does not use it.
unsafe {
self.wait();
if n == 0 {
self.fill_still();
self.fill(0, [200, 10, 30, 255]);
self.fill(8192, [10, 40, 220, 255]);
let l = self.open(0);
@@ -630,6 +848,7 @@ impl Scene {
self.targets(&l);
self.quad(&l, 4000, 0, 0);
self.quad(&l, 4001, 256, 0);
self.triangle(&l, n);
// Nothing: the clamp cut it to no vertices.
self.quad(&l, 4001, 0, 1);
l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
@@ -680,6 +899,18 @@ impl Scene {
l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]);
l.Close().unwrap();
self.send(&[&second, &l]);
self.wait();
// Another queue fetches a result, as the host layer's relay does.
let (queue, allocator, list) = &self.copies;
allocator.Reset().unwrap();
list.Reset(allocator, None).unwrap();
list.CopyBufferRegion(&self.back.0, 1 << 18, &self.sum, 0, 1024);
list.Close().unwrap();
queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
self.value += 1;
queue.Signal(&self.fence, self.value).unwrap();
self.fence.SetEventOnCompletion(self.value, self.event).unwrap();
WaitForSingleObject(self.event, INFINITE);
if let Some((swap, _)) = &self.swap {
swap.Present(0, DXGI_PRESENT(0)).unwrap();
}
@@ -690,6 +921,7 @@ impl Scene {
/// What everything holds now.
fn outcome(&mut self) -> Outcome {
self.wait();
let still = self.read_still();
let l = self.open(0);
// SAFETY: an open list; live objects.
unsafe {
@@ -713,6 +945,7 @@ impl Scene {
self.wait();
let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec();
Outcome {
still,
picture: at(0, (SIZE * 512) as usize),
image: rows(&at(1 << 18, 4096)),
sum: at(1 << 19, 1024),
@@ -722,6 +955,15 @@ impl Scene {
}
}
fn sub_of(t: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION {
D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer never released.
pResource: unsafe { std::mem::transmute_copy(t) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub },
}
}
/// The 64 bytes of each row of a 16x16 texture.
fn rows(bytes: &[u8]) -> Vec<u8> {
bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect()
@@ -782,7 +1024,19 @@ fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str)
assert_eq!(rows(&get("image")), expected.image, "{what}: image");
assert_eq!(get("target"), expected.picture, "{what}: target");
assert!(get("shared") == expected.shared, "{what}: memory the CPU sees");
assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !n.contains("submissions,") && !n.contains("waits of the")), "{what}: {:?}", report.notes);
for still in &expected.still {
let id = player.named(still.name).unwrap();
for (sub, (pitch, rows)) in still.subs.iter().enumerate() {
let have = player.contents_of(id, sub as u32).unwrap().unwrap();
for (r, row) in rows.iter().enumerate() {
assert_eq!(&have[r * pitch..][..row.len()], &row[..], "{what}: {} subresource {sub} row {r}", still.name);
}
}
}
// Nothing was left out but what another queue ran.
let known = ["submissions,", "waits of the drawing queue", "lists sent to a queue other than"];
assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), "{what}: {:?}", report.notes);
assert!(report.notes.iter().any(|n| n.contains(known[2])));
report
}
@@ -813,6 +1067,10 @@ fn a_frame_is_recorded_and_replayed() {
eprintln!("ran without the recorder");
// Something is in the picture.
assert!(without.sum.iter().any(|&b| b != 0));
for s in &without.still {
assert!(s.subs.iter().all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), "{}", s.name);
}
assert_eq!(without.still.iter().map(|s| s.subs.len()).collect::<Vec<_>>(), [15, 3, 2]);
let colors: std::collections::HashSet<[u8; 4]> =
without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect();
assert!(colors.len() > 30, "{}", colors.len());
@@ -821,12 +1079,12 @@ fn a_frame_is_recorded_and_replayed() {
// frame whose lists are all recorded comes first).
assert!(!record::on());
let dir = tempfile::tempdir().unwrap();
let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1 };
let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1, always: false };
let folder = record::start(settings, &device).unwrap();
assert!(record::on());
assert_ne!(table_of(&device), own, "the device is hooked");
assert!(
record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1 }, &device).is_err(),
record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1, always: false }, &device).is_err(),
"one recorder a process"
);
eprintln!("recorder on");
+271
View File
@@ -0,0 +1,271 @@
//! How the frame recorder and replayer do at the size of a title's frame
//! (not run by default: `cargo test --release ... -- --ignored --nocapture`):
//! thousands of textures and buffers, a view heap of 1.5 million slots, 30
//! submissions of 40,000 calls.
//!
//! `BIG_TEXTURES` (17000) and `BIG_FOLDER` (a temporary one) change it.
#![cfg(all(windows, feature = "diagnostics"))]
use std::mem::ManuallyDrop;
use std::time::Instant;
use victory_gpu::replay::play::{self, Options};
use victory_gpu::replay::record::{self, At, Settings};
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::Interface;
const SUBMITS: usize = 30;
const CALLS: usize = 40_000;
const VIEWS: u32 = 1_500_000;
fn buffer(device: &ID3D12Device, kind: u32, size: u64) -> (ID3D12Resource, *mut u8) {
let (heap, state, flags) = match kind {
0 => (
D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
),
1 => (
D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() },
D3D12_RESOURCE_STATE_GENERIC_READ,
D3D12_RESOURCE_FLAG_NONE,
),
_ => (
D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_CUSTOM,
CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
..Default::default()
},
D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
),
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: flags,
..Default::default()
};
let mut made: Option<ID3D12Resource> = None;
let mut data = std::ptr::null_mut();
// SAFETY: plain creation and mapping.
unsafe {
device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap();
let made = made.unwrap();
if kind > 0 {
made.Map(0, None, Some(&mut data)).unwrap();
// Not all zero, as real data is.
for at in (0..size as usize).step_by(4096) {
data.cast::<u8>().add(at).write(at as u8 | 1);
}
}
(made, data.cast())
}
}
fn barrier(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
// SAFETY: a borrowed pointer never released.
pResource: unsafe { std::mem::transmute_copy(res) },
Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
StateBefore: before,
StateAfter: after,
}),
},
..Default::default()
}
}
struct Big {
device: ID3D12Device,
queue: ID3D12CommandQueue,
fence: ID3D12Fence,
value: u64,
lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
_textures: Vec<ID3D12Resource>,
card: Vec<ID3D12Resource>,
shared: Vec<(ID3D12Resource, *mut u8)>,
upload: Vec<(ID3D12Resource, *mut u8)>,
views: ID3D12DescriptorHeap,
target: ID3D12Resource,
}
impl Big {
fn new(device: &ID3D12Device, textures: usize) -> Big {
let texture = |size: u32, flags, state| {
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: u64::from(size),
Height: size,
DepthOrArraySize: 1,
MipLevels: if size == 256 { 9 } else { 1 },
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Flags: flags,
..Default::default()
};
let mut made: Option<ID3D12Resource> = None;
// SAFETY: plain creation.
unsafe { device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut made).unwrap() };
made.unwrap()
};
// SAFETY: plain creation; slots of the heap just made.
unsafe {
let queue: ID3D12CommandQueue = device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })
.unwrap();
let lists = (0..SUBMITS)
.map(|_| {
let a: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let l: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).unwrap();
l.Close().unwrap();
(a, l)
})
.collect();
let views: ID3D12DescriptorHeap = device
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: VIEWS,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
})
.unwrap();
let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
let start = views.GetCPUDescriptorHandleForHeapStart().ptr;
let textures: Vec<ID3D12Resource> = (0..textures)
.map(|_| texture(256, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE))
.collect();
for i in 0..VIEWS as usize {
let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step };
device.CreateShaderResourceView(&textures[i % textures.len()], None, at);
}
let shared: Vec<(ID3D12Resource, *mut u8)> = (0..1000).map(|_| buffer(device, 2, 1 << 20)).collect();
for (i, (b, _)) in shared.iter().enumerate() {
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32_TYPELESS,
ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_SRV { NumElements: 1 << 18, Flags: D3D12_BUFFER_SRV_FLAG_RAW, ..Default::default() },
},
};
device.CreateShaderResourceView(b, Some(&desc), D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start + i * step });
}
Big {
device: device.clone(),
queue,
fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(),
value: 0,
lists,
_textures: textures,
card: (0..600).map(|_| buffer(device, 0, 1 << 20).0).collect(),
shared,
upload: (0..1000).map(|_| buffer(device, 1, 1 << 20)).collect(),
views,
target: texture(1024, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE),
}
}
}
fn wait(&mut self) {
self.value += 1;
// SAFETY: our queue and fence.
unsafe {
let event = CreateEventW(None, false, false, None).unwrap();
self.queue.Signal(&self.fence, self.value).unwrap();
self.fence.SetEventOnCompletion(self.value, event).unwrap();
WaitForSingleObject(event, INFINITE);
let _ = windows::Win32::Foundation::CloseHandle(event);
self.device.GetDeviceRemovedReason().unwrap();
}
}
fn frame(&mut self, n: usize) {
for s in 0..SUBMITS {
// SAFETY: lists whose last run has finished; mappings written
// inside their bounds.
unsafe {
let (a, l) = &self.lists[s];
a.Reset().unwrap();
l.Reset(a, None).unwrap();
l.SetDescriptorHeaps(&[Some(self.views.clone())]);
for i in 0..CALLS / SUBMITS / 4 {
let card = &self.card[(i * 7 + s) % self.card.len()];
let from = &self.upload[(i + s * 31) % self.upload.len()].0;
l.CopyBufferRegion(card, (i % 1000 * 1000) as u64 & !3, from, 0, 256);
l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]);
l.ResourceBarrier(&[barrier(card, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST)]);
l.SetMarker(1, None, 0);
}
l.Close().unwrap();
for i in 0..60 {
let at = (n * 97 + s * 13 + i * 7) % 1000;
self.shared[at].1.add(i * 4096).write((n + s) as u8);
self.upload[at].1.add(i * 8192).write((n + s) as u8);
}
self.queue.ExecuteCommandLists(&[Some(l.cast().unwrap())]);
}
self.wait();
}
record::present(&self.target, D3D12_RESOURCE_STATE_COPY_SOURCE);
}
}
#[test]
#[ignore = "takes gigabytes of the card's memory and the disk"]
fn a_frame_of_a_titles_size() {
let mut device: Option<ID3D12Device> = None;
// SAFETY: plain creation.
unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).unwrap() };
let device = device.unwrap();
let textures = std::env::var("BIG_TEXTURES").ok().and_then(|v| v.parse().ok()).unwrap_or(17_000);
let timed = |what: &str, began: Instant| println!("{what}: {:.1} ms", began.elapsed().as_secs_f64() * 1e3);
let began = Instant::now();
{
let mut big = Big::new(&device, textures);
timed("made, without the recorder", began);
for n in 0..4 {
let began = Instant::now();
big.frame(n);
timed("frame, without the recorder", began);
}
}
let dir = tempfile::tempdir().unwrap();
let folder = std::env::var_os("BIG_FOLDER").map_or(dir.path().to_owned(), Into::into);
let settings = Settings { folder, at: At::Frame(4), frames: 1, always: false };
let folder = record::start(settings, &device).unwrap();
let began = Instant::now();
let mut big = Big::new(&device, textures);
timed("made, with the recorder", began);
for n in 0..8 {
let began = Instant::now();
big.frame(n);
timed(["frame", "frame, lists recorded", "frame, captured", "frame, after"][[0, 0, 0, 0, 1, 1, 2, 3][n]], began);
}
assert_eq!(record::finished(), Some(folder.clone()));
drop(big);
record::unhook(&device);
println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap());
for f in std::fs::read_dir(&folder).unwrap().flatten() {
println!("{:>8} MB {}", f.metadata().unwrap().len() >> 20, f.file_name().to_string_lossy());
}
let began = Instant::now();
let reports = play::replay(&folder, &Options { loops: 3, ..Default::default() }).unwrap();
timed("loaded and replayed", began);
for (what, r) in &reports {
println!("{}", r.text(what));
}
}