2
0

replay.rs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. //! The frame recorder and replayer on the PC's own adapter (skipped without
  2. //! one): a small program with clears, indirect draws of textures picked from
  3. //! a heap, compute, buffers the CPU changes between submissions, descriptors
  4. //! replaced between them, and textures that share memory. It runs without
  5. //! the recorder, then with it, then one frame of it is replayed; every
  6. //! picture and buffer must be the same.
  7. //!
  8. //! `VICTORY_TEST_D3D_DEBUG=1` runs it under the debug layer.
  9. #![cfg(all(windows, feature = "diagnostics"))]
  10. use std::mem::ManuallyDrop;
  11. use victory_gpu::replay::play::{self, Buffers, Options, Player};
  12. use victory_gpu::replay::record::{self, At, Settings};
  13. use windows::Win32::Foundation::{HANDLE, HWND, RECT};
  14. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  15. use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob};
  16. use windows::Win32::Graphics::Direct3D12::*;
  17. use windows::Win32::Graphics::Dxgi::Common::*;
  18. use windows::Win32::Graphics::Dxgi::*;
  19. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  20. use windows::Win32::UI::WindowsAndMessaging::*;
  21. use windows::core::{Interface, PCSTR, s, w};
  22. const SIZE: u32 = 128;
  23. const DRAW: &str = r#"
  24. #define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), DescriptorTable(Sampler(s0))"
  25. cbuffer Pick : register(b0) { uint pick; uint pad; };
  26. cbuffer Place : register(b1) { float4 place; };
  27. Texture2D all[] : register(t0);
  28. SamplerState point_sampler : register(s0);
  29. struct V { float4 at : SV_Position; float2 uv : UV; };
  30. [RootSignature(RS)]
  31. V vs(uint i : SV_VertexID) {
  32. float2 c = float2(i & 1, (i >> 1) & 1);
  33. if (i == 3) c = float2(1, 0);
  34. if (i == 4) c = float2(0, 1);
  35. if (i == 5) c = float2(1, 1);
  36. V v;
  37. v.uv = c;
  38. v.at = float4(place.xy + c * place.zw, 0.5, 1);
  39. return v;
  40. }
  41. float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); }
  42. "#;
  43. /// Triangles of vertices and indices.
  44. const PLAIN: &str = r#"
  45. #define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)"
  46. struct V { float4 at : SV_Position; float3 color : COLOR; };
  47. [RootSignature(RS)]
  48. V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, 1); v.color = color; return v; }
  49. float4 ps(V v) : SV_Target { return float4(v.color, 1); }
  50. "#;
  51. /// Writes the arguments of indirect draws (two records: six vertices, and
  52. /// one far too many that the clamp cuts to none).
  53. const ARGS: &str = r#"
  54. #define RS "SRV(t0), UAV(u0)"
  55. ByteAddressBuffer from : register(t0);
  56. RWByteAddressBuffer args : register(u0);
  57. [RootSignature(RS)]
  58. [numthreads(1, 1, 1)]
  59. void main() {
  60. args.Store4(0, uint4(from.Load(0), 1, 0, 0));
  61. args.Store4(16, uint4(4000000000u, 1, 0, 0));
  62. }
  63. "#;
  64. /// The argument clamp's parameters, with a simple bound.
  65. const CLAMP: &str = r#"
  66. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  67. cbuffer C : register(b0) { uint kind; uint stride; uint records; uint args_offset; uint has_count; uint count_offset; };
  68. ByteAddressBuffer from : register(t0);
  69. ByteAddressBuffer count : register(t1);
  70. RWByteAddressBuffer to : register(u0);
  71. RWByteAddressBuffer budget : register(u1);
  72. [RootSignature(RS)]
  73. [numthreads(64, 1, 1)]
  74. void main(uint3 id : SV_DispatchThreadID) {
  75. if (id.x >= records) return;
  76. uint4 a = from.Load4(args_offset + id.x * stride);
  77. if (a.x > 1000) a.x = 0;
  78. to.Store4(id.x * stride, a);
  79. uint was;
  80. budget.InterlockedAdd(0, a.x, was);
  81. }
  82. "#;
  83. /// Adds what the CPU gives to what was there, and writes it on.
  84. const ADD: &str = r#"
  85. #define RS "SRV(t0), DescriptorTable(UAV(u0)), UAV(u1)"
  86. ByteAddressBuffer from : register(t0);
  87. RWTexture2D<float4> image : register(u0);
  88. RWByteAddressBuffer sum : register(u1);
  89. [RootSignature(RS)]
  90. [numthreads(8, 8, 1)]
  91. void main(uint3 id : SV_DispatchThreadID) {
  92. uint at = (id.y * 16 + id.x) * 4;
  93. uint v = from.Load(at) + sum.Load(at) * 3;
  94. sum.Store(at, v);
  95. image[id.xy] = image[id.xy] + float4((v & 15) / 255.0, 0, 1 / 255.0, 1);
  96. }
  97. "#;
  98. struct Made {
  99. root: ID3D12RootSignature,
  100. pso: ID3D12PipelineState,
  101. }
  102. fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec<u8> {
  103. let (mut code, mut errors): (Option<ID3DBlob>, Option<ID3DBlob>) = (None, None);
  104. // SAFETY: the source and names live through the call; the blobs' own
  105. // bytes.
  106. unsafe {
  107. let r = D3DCompile(source.as_ptr().cast(), source.len(), None, None, None, entry, target, 1 << 20, 0, &mut code, Some(&mut errors));
  108. if r.is_err() {
  109. let e = errors.unwrap();
  110. let text = std::slice::from_raw_parts(e.GetBufferPointer().cast::<u8>(), e.GetBufferSize());
  111. panic!("{}", String::from_utf8_lossy(text));
  112. }
  113. let code = code.unwrap();
  114. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize()).to_vec()
  115. }
  116. }
  117. fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
  118. D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }
  119. }
  120. fn compute(device: &ID3D12Device, source: &str) -> Made {
  121. let cs = compile(source, s!("main"), s!("cs_5_1"));
  122. // SAFETY: plain creation.
  123. unsafe {
  124. let root: ID3D12RootSignature = device.CreateRootSignature(0, &cs).unwrap();
  125. let pso = device
  126. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  127. pRootSignature: std::mem::transmute_copy(&root),
  128. CS: code(&cs),
  129. ..Default::default()
  130. })
  131. .unwrap();
  132. Made { root, pso }
  133. }
  134. }
  135. fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
  136. D3D12_RESOURCE_DESC {
  137. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  138. Width: size,
  139. Height: 1,
  140. DepthOrArraySize: 1,
  141. MipLevels: 1,
  142. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  143. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  144. Flags: flags,
  145. ..Default::default()
  146. }
  147. }
  148. fn texture_desc(size: u32, format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
  149. D3D12_RESOURCE_DESC {
  150. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  151. Width: u64::from(size),
  152. Height: size,
  153. DepthOrArraySize: 1,
  154. MipLevels: 1,
  155. Format: format,
  156. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  157. Flags: flags,
  158. ..Default::default()
  159. }
  160. }
  161. #[derive(Clone, Copy, PartialEq)]
  162. enum In {
  163. Card,
  164. Upload,
  165. Back,
  166. /// The PC's memory, mapped, that shaders write too.
  167. Shared,
  168. }
  169. fn committed(device: &ID3D12Device, place: In, desc: &D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES) -> (ID3D12Resource, *mut u8) {
  170. let heap = match place {
  171. In::Card => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
  172. In::Upload => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() },
  173. In::Back => D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() },
  174. In::Shared => D3D12_HEAP_PROPERTIES {
  175. Type: D3D12_HEAP_TYPE_CUSTOM,
  176. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  177. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  178. ..Default::default()
  179. },
  180. };
  181. let mut made: Option<ID3D12Resource> = None;
  182. let mut data = std::ptr::null_mut();
  183. // SAFETY: plain creation and mapping.
  184. unsafe {
  185. device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made).unwrap();
  186. let made = made.unwrap();
  187. if place != In::Card {
  188. made.Map(0, None, Some(&mut data)).unwrap();
  189. }
  190. (made, data.cast())
  191. }
  192. }
  193. fn moved(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
  194. D3D12_RESOURCE_BARRIER {
  195. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  196. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  197. Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  198. // SAFETY: a borrowed pointer never released.
  199. pResource: unsafe { std::mem::transmute_copy(res) },
  200. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  201. StateBefore: before,
  202. StateAfter: after,
  203. }),
  204. },
  205. ..Default::default()
  206. }
  207. }
  208. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  209. D3D12_RESOURCE_BARRIER {
  210. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  211. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  212. UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }),
  213. },
  214. ..Default::default()
  215. }
  216. }
  217. fn aliased(before: &ID3D12Resource, after: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER {
  218. D3D12_RESOURCE_BARRIER {
  219. Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
  220. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  221. Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
  222. // SAFETY: borrowed pointers never released.
  223. pResourceBefore: unsafe { std::mem::transmute_copy(before) },
  224. // SAFETY: as above.
  225. pResourceAfter: unsafe { std::mem::transmute_copy(after) },
  226. }),
  227. },
  228. ..Default::default()
  229. }
  230. }
  231. const COMMON: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COMMON;
  232. const TARGET: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_RENDER_TARGET;
  233. const READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  234. const UAV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  235. const TO: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST;
  236. const FROM: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_SOURCE;
  237. const ARGUMENTS: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  238. /// A texture the frames do not touch: what each subresource holds, row by
  239. /// row, with the rows' distance in its copyable layout.
  240. #[derive(PartialEq, Debug, Clone)]
  241. struct Still {
  242. name: &'static str,
  243. subs: Vec<(usize, Vec<Vec<u8>>)>,
  244. }
  245. /// What the program ends with.
  246. #[derive(PartialEq, Debug)]
  247. struct Outcome {
  248. still: Vec<Still>,
  249. picture: Vec<u8>,
  250. image: Vec<u8>,
  251. sum: Vec<u8>,
  252. shared: Vec<u8>,
  253. }
  254. struct Scene {
  255. device: ID3D12Device,
  256. queue: ID3D12CommandQueue,
  257. fence: ID3D12Fence,
  258. event: HANDLE,
  259. value: u64,
  260. lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
  261. draw: Made,
  262. plain: Made,
  263. vertices: (ID3D12Resource, *mut u8),
  264. samplers: ID3D12DescriptorHeap,
  265. still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>,
  266. copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList),
  267. args: Made,
  268. clamp: Made,
  269. add: Made,
  270. signature: ID3D12CommandSignature,
  271. views: ID3D12DescriptorHeap,
  272. step: usize,
  273. rtvs: ID3D12DescriptorHeap,
  274. dsvs: ID3D12DescriptorHeap,
  275. target: ID3D12Resource,
  276. _depth: ID3D12Resource,
  277. fixed: ID3D12Resource,
  278. one: ID3D12Resource,
  279. other: ID3D12Resource,
  280. _heap: ID3D12Heap,
  281. image: ID3D12Resource,
  282. sum: ID3D12Resource,
  283. arguments: ID3D12Resource,
  284. scratch: ID3D12Resource,
  285. budget: ID3D12Resource,
  286. shared: (ID3D12Resource, *mut u8),
  287. constants: (ID3D12Resource, *mut u8),
  288. texels: (ID3D12Resource, *mut u8),
  289. back: (ID3D12Resource, *mut u8),
  290. swap: Option<(IDXGISwapChain3, HWND)>,
  291. }
  292. impl Scene {
  293. fn new(device: &ID3D12Device, window: bool) -> Scene {
  294. // SAFETY: plain creation throughout.
  295. unsafe {
  296. let queue: ID3D12CommandQueue = device
  297. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })
  298. .unwrap();
  299. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
  300. let lists = (0..3)
  301. .map(|_| {
  302. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
  303. let list: ID3D12GraphicsCommandList =
  304. device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap();
  305. list.Close().unwrap();
  306. (allocator, list)
  307. })
  308. .collect();
  309. let (vs, ps) = (compile(DRAW, s!("vs"), s!("vs_5_1")), compile(DRAW, s!("ps"), s!("ps_5_1")));
  310. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
  311. let mut blend = D3D12_BLEND_DESC::default();
  312. blend.RenderTarget[0].RenderTargetWriteMask = 15;
  313. let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  314. pRootSignature: std::mem::transmute_copy(&root),
  315. VS: code(&vs),
  316. PS: code(&ps),
  317. BlendState: blend,
  318. SampleMask: u32::MAX,
  319. RasterizerState: D3D12_RASTERIZER_DESC {
  320. FillMode: D3D12_FILL_MODE_SOLID,
  321. CullMode: D3D12_CULL_MODE_NONE,
  322. DepthClipEnable: true.into(),
  323. ..Default::default()
  324. },
  325. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  326. DepthEnable: true.into(),
  327. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  328. DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
  329. ..Default::default()
  330. },
  331. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  332. NumRenderTargets: 1,
  333. DSVFormat: DXGI_FORMAT_D32_FLOAT,
  334. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  335. ..Default::default()
  336. };
  337. desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  338. let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
  339. record::name(&pso, "a drawing pipeline");
  340. let draw = Made { root, pso };
  341. let (vs, ps) = (compile(PLAIN, s!("vs"), s!("vs_5_1")), compile(PLAIN, s!("ps"), s!("ps_5_1")));
  342. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
  343. let element = |name, index, format, at| D3D12_INPUT_ELEMENT_DESC {
  344. SemanticName: name,
  345. SemanticIndex: index,
  346. Format: format,
  347. InputSlot: 0,
  348. AlignedByteOffset: at,
  349. InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
  350. InstanceDataStepRate: 0,
  351. };
  352. let elements = [
  353. element(s!("POSITION"), 0, DXGI_FORMAT_R32G32_FLOAT, 0),
  354. element(s!("COLOR"), 1, DXGI_FORMAT_R32G32B32_FLOAT, 8),
  355. ];
  356. desc.pRootSignature = std::mem::transmute_copy(&root);
  357. (desc.VS, desc.PS) = (code(&vs), code(&ps));
  358. desc.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elements.as_ptr(), NumElements: 2 };
  359. let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
  360. let plain = Made { root, pso };
  361. let clamp = compute(device, CLAMP);
  362. record::name(&clamp.pso, play::CLAMP);
  363. let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, ..Default::default() };
  364. let mut signature: Option<ID3D12CommandSignature> = None;
  365. let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 16, NumArgumentDescs: 1, pArgumentDescs: &argument, NodeMask: 0 };
  366. device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature).unwrap();
  367. let heap = |kind, count, flags| -> ID3D12DescriptorHeap {
  368. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: count, Flags: flags, NodeMask: 0 }).unwrap()
  369. };
  370. let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
  371. let sampler = D3D12_SAMPLER_DESC {
  372. Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
  373. AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  374. AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  375. AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  376. MaxLOD: 8.0,
  377. ..Default::default()
  378. };
  379. let mut at = samplers.GetCPUDescriptorHandleForHeapStart();
  380. at.ptr += 2 * device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize;
  381. device.CreateSampler(&sampler, at);
  382. let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5000, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE);
  383. let rtvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
  384. let dsvs = heap(D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
  385. let rgba = DXGI_FORMAT_R8G8B8A8_UNORM;
  386. let (target, _) = committed(device, In::Card, &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), FROM);
  387. let (depth, _) = committed(
  388. device,
  389. In::Card,
  390. &texture_desc(SIZE, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL),
  391. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  392. );
  393. let (fixed, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE), TO);
  394. let (image, _) = committed(device, In::Card, &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), UAV);
  395. let mut memory: Option<ID3D12Heap> = None;
  396. let desc = D3D12_HEAP_DESC {
  397. SizeInBytes: 4 << 20,
  398. Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
  399. Alignment: 0,
  400. Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
  401. };
  402. device.CreateHeap(&desc, &mut memory).unwrap();
  403. let memory = memory.unwrap();
  404. let placed = || {
  405. let mut made: Option<ID3D12Resource> = None;
  406. let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE);
  407. device.CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made).unwrap();
  408. made.unwrap()
  409. };
  410. // Two textures in one place.
  411. let (one, other) = (placed(), placed());
  412. let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  413. let card = |size| committed(device, In::Card, &buffer_desc(size, uav), COMMON).0;
  414. let (sum, arguments, scratch, budget) = (card(1024), card(4096), card(4096), card(256));
  415. let shared = committed(device, In::Shared, &buffer_desc(70_000, uav), COMMON);
  416. let constants = committed(
  417. device,
  418. In::Upload,
  419. &buffer_desc(8192, D3D12_RESOURCE_FLAG_NONE),
  420. D3D12_RESOURCE_STATE_GENERIC_READ,
  421. );
  422. let texels = committed(
  423. device,
  424. In::Upload,
  425. &buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE),
  426. D3D12_RESOURCE_STATE_GENERIC_READ,
  427. );
  428. let back = committed(device, In::Back, &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE), TO);
  429. let vertices = committed(
  430. device,
  431. In::Upload,
  432. &buffer_desc(4096, D3D12_RESOURCE_FLAG_NONE),
  433. D3D12_RESOURCE_STATE_GENERIC_READ,
  434. );
  435. let still = {
  436. let blocks = D3D12_RESOURCE_DESC {
  437. MipLevels: 5,
  438. DepthOrArraySize: 3,
  439. ..texture_desc(64, DXGI_FORMAT_BC7_UNORM, D3D12_RESOURCE_FLAG_NONE)
  440. };
  441. let volume = D3D12_RESOURCE_DESC {
  442. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D,
  443. DepthOrArraySize: 8,
  444. MipLevels: 3,
  445. ..texture_desc(16, DXGI_FORMAT_R16_FLOAT, D3D12_RESOURCE_FLAG_NONE)
  446. };
  447. let stencil = texture_desc(32, DXGI_FORMAT_R32G8X24_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL);
  448. let (write, read) = (D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
  449. [("blocks", blocks, TO, READ), ("volume", volume, TO, read), ("stencil", stencil, write, write)].map(|(name, d, made_in, ends)| {
  450. let (t, _) = committed(device, In::Card, &d, made_in);
  451. record::name(&t, name);
  452. (name, t, ends)
  453. })
  454. };
  455. let copies: (ID3D12CommandQueue, ID3D12CommandAllocator, ID3D12GraphicsCommandList) = {
  456. let queue = device
  457. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() })
  458. .unwrap();
  459. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).unwrap();
  460. let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None).unwrap();
  461. list.Close().unwrap();
  462. (queue, allocator, list)
  463. };
  464. for (r, n) in [(&sum, "sum"), (&image, "image"), (&target, "target"), (&shared.0, "shared"), (&one, "one"), (&other, "other")] {
  465. record::name(r, n);
  466. }
  467. device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart());
  468. device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart());
  469. let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize;
  470. let swap = window.then(|| swap_chain(&queue));
  471. let scene = Scene {
  472. device: device.clone(),
  473. queue,
  474. fence,
  475. event: CreateEventW(None, false, false, None).unwrap(),
  476. value: 0,
  477. lists,
  478. draw,
  479. plain,
  480. vertices,
  481. samplers,
  482. still: still.to_vec(),
  483. copies,
  484. args: compute(device, ARGS),
  485. clamp,
  486. add: compute(device, ADD),
  487. signature: signature.unwrap(),
  488. views,
  489. step,
  490. rtvs,
  491. dsvs,
  492. target,
  493. _depth: depth,
  494. fixed,
  495. one,
  496. other,
  497. _heap: memory,
  498. image,
  499. sum,
  500. arguments,
  501. scratch,
  502. budget,
  503. shared,
  504. constants,
  505. texels,
  506. back,
  507. swap,
  508. };
  509. // Null views everywhere, by copies of a slot made elsewhere.
  510. let block = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE);
  511. let null = D3D12_SHADER_RESOURCE_VIEW_DESC {
  512. Format: rgba,
  513. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  514. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  515. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } },
  516. };
  517. let from = block.GetCPUDescriptorHandleForHeapStart();
  518. for i in 0..16 {
  519. let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + i * step };
  520. device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at);
  521. }
  522. for i in (0..4992).step_by(16) {
  523. device.CopyDescriptorsSimple(16, scene.cpu(i), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  524. }
  525. // The rest with the other copying method, in unlike pieces.
  526. let to = [scene.cpu(4992), scene.cpu(4994)];
  527. let sources = [from, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.ptr + 4 * step }];
  528. device.CopyDescriptors(
  529. 2,
  530. to.as_ptr(),
  531. Some([2u32, 6].as_ptr()),
  532. 2,
  533. sources.as_ptr(),
  534. Some([4u32, 4].as_ptr()),
  535. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  536. );
  537. scene.show(4001, &scene.other);
  538. scene.show(4002, &scene.one);
  539. device.CreateUnorderedAccessView(&scene.image, None::<&ID3D12Resource>, None, scene.cpu(7));
  540. scene
  541. }
  542. }
  543. fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  544. // SAFETY: a slot of the heap.
  545. let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() };
  546. D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * self.step }
  547. }
  548. /// Slot `i` shows `texture`.
  549. fn show(&self, i: usize, texture: &ID3D12Resource) {
  550. // SAFETY: a slot of the heap and a live texture.
  551. unsafe { self.device.CreateShaderResourceView(texture, None, self.cpu(i)) };
  552. }
  553. fn wait(&mut self) {
  554. self.value += 1;
  555. // SAFETY: our queue, fence and event.
  556. unsafe {
  557. self.queue.Signal(&self.fence, self.value).unwrap();
  558. self.fence.SetEventOnCompletion(self.value, self.event).unwrap();
  559. WaitForSingleObject(self.event, INFINITE);
  560. self.device.GetDeviceRemovedReason().unwrap();
  561. }
  562. }
  563. fn open(&self, i: usize) -> ID3D12GraphicsCommandList {
  564. let (allocator, list) = &self.lists[i];
  565. // SAFETY: its last run was waited for.
  566. unsafe {
  567. allocator.Reset().unwrap();
  568. list.Reset(allocator, None).unwrap();
  569. }
  570. list.clone()
  571. }
  572. fn send(&self, lists: &[&ID3D12GraphicsCommandList]) {
  573. let all: Vec<Option<ID3D12CommandList>> = lists.iter().map(|l| Some(l.cast().unwrap())).collect();
  574. // SAFETY: closed lists.
  575. unsafe { self.queue.ExecuteCommandLists(&all) };
  576. }
  577. /// Fills rows of a 16x16 texture in the upload buffer at `at`.
  578. fn fill(&self, at: usize, color: [u8; 4]) {
  579. for y in 0..16 {
  580. for x in 0..16 {
  581. let mut c = color;
  582. c[1] = c[1].wrapping_add((x * 8 + y) as u8);
  583. // SAFETY: inside the mapping (16 rows of 256 bytes).
  584. unsafe { self.texels.1.add(at + y * 256 + x * 4).cast::<[u8; 4]>().write(c) };
  585. }
  586. }
  587. }
  588. fn texture_copy(&self, l: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, at: u64) {
  589. let from = D3D12_TEXTURE_COPY_LOCATION {
  590. // SAFETY: a borrowed pointer never released.
  591. pResource: unsafe { std::mem::transmute_copy(&self.texels.0) },
  592. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  593. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, 16) },
  594. };
  595. let to = D3D12_TEXTURE_COPY_LOCATION {
  596. // SAFETY: as above.
  597. pResource: unsafe { std::mem::transmute_copy(texture) },
  598. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  599. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
  600. };
  601. // SAFETY: an open list; live resources.
  602. unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
  603. }
  604. /// A quad of the texture in slot `pick`, at the constants at `at`.
  605. fn quad(&self, l: &ID3D12GraphicsCommandList, pick: u32, at: u64, record: u64) {
  606. // SAFETY: an open list; live objects.
  607. unsafe {
  608. l.SetGraphicsRootSignature(&self.draw.root);
  609. l.SetPipelineState(&self.draw.pso);
  610. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  611. l.SetGraphicsRoot32BitConstant(0, pick, 0);
  612. l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at);
  613. l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart());
  614. let step = self.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  615. let first = self.samplers.GetGPUDescriptorHandleForHeapStart().ptr;
  616. l.SetGraphicsRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: first + 2 * u64::from(step) });
  617. l.ExecuteIndirect(&self.signature, 1, &self.scratch, record * 16, None::<&ID3D12Resource>, 0);
  618. }
  619. }
  620. /// The arguments made and clamped, as the host layer does it.
  621. fn arguments(&self, l: &ID3D12GraphicsCommandList, before: D3D12_RESOURCE_STATES) {
  622. // SAFETY: an open list; live objects.
  623. unsafe {
  624. l.SetComputeRootSignature(&self.args.root);
  625. l.SetPipelineState(&self.args.pso);
  626. l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536);
  627. l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress());
  628. l.Dispatch(1, 1, 1);
  629. l.ResourceBarrier(&[uav_barrier(), moved(&self.arguments, UAV, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]);
  630. l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]);
  631. l.SetComputeRootSignature(&self.clamp.root);
  632. l.SetPipelineState(&self.clamp.pso);
  633. let constants = [0u32, 16, 2, 0, 0, 0];
  634. l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  635. l.SetComputeRootShaderResourceView(1, self.arguments.GetGPUVirtualAddress());
  636. l.SetComputeRootShaderResourceView(2, self.arguments.GetGPUVirtualAddress());
  637. l.SetComputeRootUnorderedAccessView(3, self.scratch.GetGPUVirtualAddress());
  638. l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress());
  639. l.Dispatch(1, 1, 1);
  640. l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]);
  641. l.ResourceBarrier(&[moved(&self.arguments, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, UAV)]);
  642. }
  643. }
  644. fn place(&self, at: usize, place: [f32; 4]) {
  645. // SAFETY: inside the mapping.
  646. unsafe { self.constants.1.add(at).cast::<[f32; 4]>().write(place) };
  647. }
  648. fn give(&self, at: usize, value: u32) {
  649. // SAFETY: inside the mapping.
  650. unsafe { self.shared.1.add(at).cast::<u32>().write(value) };
  651. }
  652. fn targets(&self, l: &ID3D12GraphicsCommandList) {
  653. // SAFETY: an open list; live objects.
  654. unsafe {
  655. let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart());
  656. l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv));
  657. let size = SIZE as f32;
  658. l.RSSetViewports(&[D3D12_VIEWPORT { Width: size, Height: size, MaxDepth: 1.0, ..Default::default() }]);
  659. l.RSSetScissorRects(&[RECT { left: 0, top: 0, right: SIZE as i32, bottom: SIZE as i32 }]);
  660. l.SetDescriptorHeaps(&[Some(self.views.clone()), Some(self.samplers.clone())]);
  661. }
  662. }
  663. /// A triangle with vertices and indices.
  664. fn triangle(&self, l: &ID3D12GraphicsCommandList, n: u32) {
  665. // SAFETY: an open list; live objects; inside the mapping, which the
  666. // card does not use now.
  667. unsafe {
  668. let x = 0.5 + 0.05 * n as f32;
  669. 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]];
  670. self.vertices.1.cast::<[[f32; 5]; 3]>().write(vertices);
  671. self.vertices.1.add(1024).cast::<[u16; 4]>().write([9, 2, 0, 1]);
  672. let at = self.vertices.0.GetGPUVirtualAddress();
  673. l.SetGraphicsRootSignature(&self.plain.root);
  674. l.SetPipelineState(&self.plain.pso);
  675. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  676. l.IASetVertexBuffers(0, Some(&[D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: 60, StrideInBytes: 20 }]));
  677. let indices = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at + 1024, SizeInBytes: 8, Format: DXGI_FORMAT_R16_UINT };
  678. l.IASetIndexBuffer(Some(&indices));
  679. l.DrawIndexedInstanced(3, 1, 1, 0, 0);
  680. }
  681. }
  682. /// Fills the textures no frame touches.
  683. fn fill_still(&mut self) {
  684. // SAFETY: an open list; live objects; mappings written inside their
  685. // bounds.
  686. unsafe {
  687. let (up, data) = committed(
  688. &self.device,
  689. In::Upload,
  690. &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE),
  691. D3D12_RESOURCE_STATE_GENERIC_READ,
  692. );
  693. for i in 0..1 << 20 {
  694. data.add(i).write((i * 31 + i / 251) as u8 & 0x3b);
  695. }
  696. let l = self.open(0);
  697. let mut at = 0;
  698. for (name, t, ends) in &self.still {
  699. if *name == "stencil" {
  700. let view = D3D12_DEPTH_STENCIL_VIEW_DESC {
  701. Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
  702. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  703. ..Default::default()
  704. };
  705. let heap: ID3D12DescriptorHeap = self
  706. .device
  707. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  708. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  709. NumDescriptors: 1,
  710. ..Default::default()
  711. })
  712. .unwrap();
  713. let dsv = heap.GetCPUDescriptorHandleForHeapStart();
  714. self.device.CreateDepthStencilView(t, Some(&view), dsv);
  715. let both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL;
  716. l.ClearDepthStencilView(dsv, both, 0.75, 3, None);
  717. let part = RECT { left: 5, top: 6, right: 20, bottom: 17 };
  718. l.ClearDepthStencilView(dsv, both, 0.25, 200, Some(&[part]));
  719. continue;
  720. }
  721. let desc = t.GetDesc();
  722. let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize };
  723. for sub in 0..u32::from(layers * desc.MipLevels) {
  724. let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  725. let mut total = 0;
  726. self.device.GetCopyableFootprints(&desc, sub, 1, at, Some(&mut f), None, None, Some(&mut total));
  727. at = (at + total).next_multiple_of(512);
  728. let from = D3D12_TEXTURE_COPY_LOCATION {
  729. pResource: std::mem::transmute_copy(&up),
  730. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  731. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
  732. };
  733. l.CopyTextureRegion(&sub_of(t, sub), 0, 0, 0, &from, None);
  734. }
  735. l.ResourceBarrier(&[moved(t, TO, *ends)]);
  736. }
  737. l.Close().unwrap();
  738. self.send(&[&l]);
  739. self.wait();
  740. }
  741. }
  742. /// What they hold.
  743. fn read_still(&mut self) -> Vec<Still> {
  744. let mut all = Vec::new();
  745. for (name, t, state) in self.still.clone() {
  746. // SAFETY: as above.
  747. unsafe {
  748. let desc = t.GetDesc();
  749. let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { desc.DepthOrArraySize };
  750. let planes = if name == "stencil" { 2 } else { 1 };
  751. let mut subs = Vec::new();
  752. for sub in 0..u32::from(layers * desc.MipLevels) * planes {
  753. let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  754. let (mut rows, mut len) = (0, 0);
  755. self.device.GetCopyableFootprints(&desc, sub, 1, 0, Some(&mut f), Some(&mut rows), Some(&mut len), None);
  756. let l = self.open(0);
  757. l.ResourceBarrier(&[moved(&t, state, FROM)]);
  758. let to = D3D12_TEXTURE_COPY_LOCATION {
  759. pResource: std::mem::transmute_copy(&self.back.0),
  760. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  761. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
  762. };
  763. l.CopyTextureRegion(&to, 0, 0, 0, &sub_of(&t, sub), None);
  764. l.ResourceBarrier(&[moved(&t, FROM, state)]);
  765. l.Close().unwrap();
  766. self.send(&[&l]);
  767. self.wait();
  768. let pitch = f.Footprint.RowPitch as usize;
  769. let rows = (0..rows as usize * f.Footprint.Depth as usize)
  770. .map(|r| std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize).to_vec())
  771. .collect();
  772. subs.push((pitch, rows));
  773. }
  774. all.push(Still { name, subs });
  775. }
  776. }
  777. all
  778. }
  779. fn frame(&mut self, n: u32) {
  780. // SAFETY: open lists of ours, live objects; memory is written while
  781. // the card does not use it.
  782. unsafe {
  783. self.wait();
  784. if n == 0 {
  785. self.fill_still();
  786. self.fill(0, [200, 10, 30, 255]);
  787. self.fill(8192, [10, 40, 220, 255]);
  788. let l = self.open(0);
  789. self.texture_copy(&l, &self.fixed, 0);
  790. self.texture_copy(&l, &self.other, 8192);
  791. l.ResourceBarrier(&[moved(&self.fixed, TO, READ), moved(&self.other, TO, READ)]);
  792. l.Close().unwrap();
  793. self.send(&[&l]);
  794. self.wait();
  795. }
  796. // The first submission.
  797. self.show(4000, &self.fixed);
  798. self.place(0, [-1.0 + 0.1 * n as f32, -1.0, 0.5, 0.5]);
  799. self.place(256, [0.0, 0.0, 0.5, 0.5]);
  800. self.give(65536, 6);
  801. self.give(40, 7 + n);
  802. let l = self.open(0);
  803. l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]);
  804. let (rtv, dsv) = (self.rtvs.GetCPUDescriptorHandleForHeapStart(), self.dsvs.GetCPUDescriptorHandleForHeapStart());
  805. l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None);
  806. l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None);
  807. self.arguments(&l, COMMON);
  808. self.targets(&l);
  809. self.quad(&l, 4000, 0, 0);
  810. self.quad(&l, 4001, 256, 0);
  811. self.triangle(&l, n);
  812. // Nothing: the clamp cut it to no vertices.
  813. self.quad(&l, 4001, 0, 1);
  814. l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
  815. l.Close().unwrap();
  816. self.send(&[&l]);
  817. self.wait();
  818. // The second: other constants and another texture in the same
  819. // places, and the second texture in the memory of the first.
  820. self.show(4000, &self.other);
  821. self.place(0, [-0.9, 0.3, 0.6, 0.6]);
  822. self.place(256, [0.3, -0.8, 0.6, 0.5]);
  823. self.give(40, 100 + n);
  824. self.give(65536, 3);
  825. self.fill(16384, [30, 200, 10 + 5 * n as u8, 255]);
  826. let l = self.open(1);
  827. self.targets(&l);
  828. self.arguments(&l, COMMON);
  829. self.quad(&l, 4000, 0, 0);
  830. l.ResourceBarrier(&[moved(&self.other, READ, TO)]);
  831. l.ResourceBarrier(&[aliased(&self.other, &self.one)]);
  832. self.texture_copy(&l, &self.one, 16384);
  833. l.ResourceBarrier(&[moved(&self.one, TO, READ)]);
  834. self.arguments(&l, ARGUMENTS);
  835. self.quad(&l, 4002, 256, 0);
  836. l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
  837. // And back, for the next frame.
  838. l.ResourceBarrier(&[moved(&self.one, READ, TO)]);
  839. l.ResourceBarrier(&[aliased(&self.one, &self.other)]);
  840. self.texture_copy(&l, &self.other, 8192);
  841. l.ResourceBarrier(&[moved(&self.other, TO, READ)]);
  842. l.Close().unwrap();
  843. let second = l;
  844. let l = self.open(2);
  845. l.SetDescriptorHeaps(&[Some(self.views.clone())]);
  846. l.SetComputeRootSignature(&self.add.root);
  847. l.SetPipelineState(&self.add.pso);
  848. l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress());
  849. let table = self.views.GetGPUDescriptorHandleForHeapStart().ptr + 7 * self.step as u64;
  850. l.SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table });
  851. l.SetComputeRootUnorderedAccessView(2, self.sum.GetGPUVirtualAddress());
  852. for _ in 0..3 {
  853. l.Dispatch(2, 2, 1);
  854. l.ResourceBarrier(&[uav_barrier()]);
  855. }
  856. // The card writes memory the CPU sees.
  857. l.ResourceBarrier(&[moved(&self.sum, UAV, FROM)]);
  858. l.CopyBufferRegion(&self.shared.0, 30_000, &self.sum, 0, 1024);
  859. l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]);
  860. l.Close().unwrap();
  861. self.send(&[&second, &l]);
  862. self.wait();
  863. // Another queue fetches a result, as the host layer's relay does.
  864. let (queue, allocator, list) = &self.copies;
  865. allocator.Reset().unwrap();
  866. list.Reset(allocator, None).unwrap();
  867. list.CopyBufferRegion(&self.back.0, 1 << 18, &self.sum, 0, 1024);
  868. list.Close().unwrap();
  869. queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
  870. self.value += 1;
  871. queue.Signal(&self.fence, self.value).unwrap();
  872. self.fence.SetEventOnCompletion(self.value, self.event).unwrap();
  873. WaitForSingleObject(self.event, INFINITE);
  874. if let Some((swap, _)) = &self.swap {
  875. swap.Present(0, DXGI_PRESENT(0)).unwrap();
  876. }
  877. record::present(&self.target, FROM);
  878. }
  879. }
  880. /// What everything holds now.
  881. fn outcome(&mut self) -> Outcome {
  882. self.wait();
  883. let still = self.read_still();
  884. let l = self.open(0);
  885. // SAFETY: an open list; live objects.
  886. unsafe {
  887. let to = |at: u64, size| D3D12_TEXTURE_COPY_LOCATION {
  888. pResource: std::mem::transmute_copy(&self.back.0),
  889. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  890. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(at, size) },
  891. };
  892. let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION {
  893. pResource: std::mem::transmute_copy(t),
  894. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  895. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
  896. };
  897. l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]);
  898. l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None);
  899. l.CopyTextureRegion(&to(1 << 18, 16), 0, 0, 0, &of(&self.image), None);
  900. l.ResourceBarrier(&[moved(&self.image, FROM, UAV)]);
  901. l.CopyBufferRegion(&self.back.0, 1 << 19, &self.sum, 0, 1024);
  902. l.Close().unwrap();
  903. self.send(&[&l]);
  904. self.wait();
  905. let at = |from: usize, n: usize| std::slice::from_raw_parts(self.back.1.add(from), n).to_vec();
  906. Outcome {
  907. still,
  908. picture: at(0, (SIZE * 512) as usize),
  909. image: rows(&at(1 << 18, 4096)),
  910. sum: at(1 << 19, 1024),
  911. shared: std::slice::from_raw_parts(self.shared.1, 70_000).to_vec(),
  912. }
  913. }
  914. }
  915. }
  916. fn sub_of(t: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION {
  917. D3D12_TEXTURE_COPY_LOCATION {
  918. // SAFETY: a borrowed pointer never released.
  919. pResource: unsafe { std::mem::transmute_copy(t) },
  920. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  921. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub },
  922. }
  923. }
  924. /// The 64 bytes of each row of a 16x16 texture.
  925. fn rows(bytes: &[u8]) -> Vec<u8> {
  926. bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect()
  927. }
  928. fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  929. D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  930. Offset: at,
  931. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  932. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  933. Width: size,
  934. Height: size,
  935. Depth: 1,
  936. RowPitch: (size * 4).next_multiple_of(256),
  937. },
  938. }
  939. }
  940. /// A swap chain of a window that is never shown.
  941. fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) {
  942. // SAFETY: plain creation.
  943. unsafe {
  944. let hwnd =
  945. CreateWindowExW(WINDOW_EX_STYLE(0), w!("STATIC"), w!("replay test"), WS_POPUP, 0, 0, 64, 64, None, None, None, None).unwrap();
  946. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
  947. let desc = DXGI_SWAP_CHAIN_DESC1 {
  948. Width: 64,
  949. Height: 64,
  950. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  951. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  952. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  953. BufferCount: 2,
  954. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  955. ..Default::default()
  956. };
  957. let chain = factory.CreateSwapChainForHwnd(queue, hwnd, &desc, None, None).unwrap().cast().unwrap();
  958. (chain, hwnd)
  959. }
  960. }
  961. fn table_of(device: &ID3D12Device) -> usize {
  962. // SAFETY: a live COM object starts with its table's address.
  963. unsafe { *device.as_raw().cast::<usize>() }
  964. }
  965. fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) -> play::Report {
  966. let report = player.run(options).unwrap();
  967. println!("{}", report.text(what));
  968. assert_eq!(report.frame_ms.len(), options.loops as usize);
  969. assert!(report.median_ms() > 0.0);
  970. let (db, same) = report.picture.unwrap();
  971. assert!(same && db.is_infinite(), "{what}: the picture differs ({db} dB)");
  972. let mut get = |name: &str| {
  973. let id = player.named(name).unwrap();
  974. player.contents(id).unwrap().unwrap()
  975. };
  976. assert_eq!(get("sum"), expected.sum, "{what}: sum");
  977. assert_eq!(rows(&get("image")), expected.image, "{what}: image");
  978. assert_eq!(get("target"), expected.picture, "{what}: target");
  979. assert!(get("shared") == expected.shared, "{what}: memory the CPU sees");
  980. for still in &expected.still {
  981. let id = player.named(still.name).unwrap();
  982. for (sub, (pitch, rows)) in still.subs.iter().enumerate() {
  983. let have = player.contents_of(id, sub as u32).unwrap().unwrap();
  984. for (r, row) in rows.iter().enumerate() {
  985. assert_eq!(&have[r * pitch..][..row.len()], &row[..], "{what}: {} subresource {sub} row {r}", still.name);
  986. }
  987. }
  988. }
  989. // Nothing was left out but what another queue ran.
  990. let known = ["submissions,", "waits of the drawing queue", "lists sent to a queue other than"];
  991. assert!(!report.notes.iter().any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))), "{what}: {:?}", report.notes);
  992. assert!(report.notes.iter().any(|n| n.contains(known[2])));
  993. report
  994. }
  995. #[test]
  996. fn a_frame_is_recorded_and_replayed() {
  997. let debug = std::env::var_os("VICTORY_TEST_D3D_DEBUG").is_some();
  998. let mut device: Option<ID3D12Device> = None;
  999. // SAFETY: plain creation.
  1000. unsafe {
  1001. if debug {
  1002. let mut layer: Option<ID3D12Debug> = None;
  1003. D3D12GetDebugInterface(&mut layer).unwrap();
  1004. layer.unwrap().EnableDebugLayer();
  1005. }
  1006. let _ = D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device);
  1007. }
  1008. let Some(device) = device else {
  1009. eprintln!("no adapter: skipped");
  1010. return;
  1011. };
  1012. let own = table_of(&device);
  1013. // Without the recorder.
  1014. let without = {
  1015. let mut scene = Scene::new(&device, false);
  1016. (0..5).for_each(|n| scene.frame(n));
  1017. scene.outcome()
  1018. };
  1019. eprintln!("ran without the recorder");
  1020. // Something is in the picture.
  1021. assert!(without.sum.iter().any(|&b| b != 0));
  1022. for s in &without.still {
  1023. assert!(s.subs.iter().all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)), "{}", s.name);
  1024. }
  1025. assert_eq!(without.still.iter().map(|s| s.subs.len()).collect::<Vec<_>>(), [15, 3, 2]);
  1026. let colors: std::collections::HashSet<[u8; 4]> =
  1027. without.picture.chunks_exact(4).map(|c| [c[0], c[1], c[2], c[3]]).collect();
  1028. assert!(colors.len() > 30, "{}", colors.len());
  1029. // With it: armed at the first present, the fourth frame is captured (a
  1030. // frame whose lists are all recorded comes first).
  1031. assert!(!record::on());
  1032. let dir = tempfile::tempdir().unwrap();
  1033. let settings = Settings { folder: dir.path().to_owned(), at: At::Frame(1), frames: 1, always: false };
  1034. let folder = record::start(settings, &device).unwrap();
  1035. assert!(record::on());
  1036. assert_ne!(table_of(&device), own, "the device is hooked");
  1037. assert!(
  1038. record::start(Settings { folder: dir.path().to_owned(), at: At::Trigger, frames: 1, always: false }, &device).is_err(),
  1039. "one recorder a process"
  1040. );
  1041. eprintln!("recorder on");
  1042. let mut scene = Scene::new(&device, true);
  1043. eprintln!("scene made");
  1044. (0..4).for_each(|n| scene.frame(n));
  1045. assert_eq!(record::finished(), Some(folder.clone()), "see {}", folder.display());
  1046. let expected = scene.outcome();
  1047. // It goes on as it did without the recorder.
  1048. scene.frame(4);
  1049. let after = scene.outcome();
  1050. assert!(after == without, "the recorder changed what the program makes");
  1051. drop(scene);
  1052. record::unhook(&device);
  1053. assert_eq!(table_of(&device), own, "the device is as it was");
  1054. for name in ["frame.bin", "contents.bin", "deltas.bin", "shaders.bin", "present.bin", "notes.txt", "frame-0.png"] {
  1055. assert!(folder.join(name).exists(), "{name}");
  1056. }
  1057. println!("{}", std::fs::read_to_string(folder.join("notes.txt")).unwrap());
  1058. let plain = Options { loops: 3, ..Default::default() };
  1059. let mut player = Player::load(dir.path(), &plain).unwrap();
  1060. check(&mut player, &plain, &expected, "unchanged");
  1061. let detailed = Options { detailed: true, ..plain.clone() };
  1062. let report = check(&mut player, &detailed, &expected, "detailed");
  1063. let count = |kind: &str| report.categories.iter().find(|c| c.0 == kind).map_or(0, |c| c.2);
  1064. assert_eq!(count("argument clamps (ours)"), 3);
  1065. assert_eq!(count("indirect draws"), 5);
  1066. assert_eq!(count("dispatches"), 6);
  1067. assert_eq!(count("clears"), 2);
  1068. assert!(report.shaders.iter().any(|s| s.2.starts_with("a drawing pipeline (DXIL ")), "{:?}", report.shaders);
  1069. let merged = Options { merge_barriers: true, ..plain.clone() };
  1070. check(&mut player, &merged, &expected, "merged barriers");
  1071. let clamps = Options { skip_clamps: true, ..plain.clone() };
  1072. let report = check(&mut player, &clamps, &expected, "without clamps");
  1073. assert!(report.notes.iter().any(|n| n.contains("3 clamp passes")), "{:?}", report.notes);
  1074. let one = Options { one_submit: true, ..plain.clone() };
  1075. check(&mut player, &one, &expected, "one submission");
  1076. let hash = Options { skip_hash_passes: true, ..plain.clone() };
  1077. check(&mut player, &hash, &expected, "without hash passes (there are none)");
  1078. // These change what is drawn: they run, and then the frame is as before.
  1079. let no_barriers = Options { no_barriers: true, ..plain.clone() };
  1080. player.run(&no_barriers).unwrap();
  1081. let some = Options { only: Some((0, 1)), ..plain.clone() };
  1082. player.run(&some).unwrap();
  1083. let skip = Options { skip_shaders: vec!["a drawing".into()], ..plain.clone() };
  1084. let report = player.run(&skip).unwrap();
  1085. assert!(!report.picture.unwrap().1, "without its draws the picture is another");
  1086. assert!(report.notes.iter().any(|n| n.contains("1 pipelines match")) && report.notes.iter().any(|n| n.contains("left out 5 commands")));
  1087. let kept = Options { restore: false, ..plain.clone() };
  1088. player.run(&kept).unwrap();
  1089. check(&mut player, &plain, &expected, "unchanged again");
  1090. drop(player);
  1091. for buffers in [Buffers::Card, Buffers::Pc] {
  1092. let o = Options { buffers, ..plain.clone() };
  1093. let mut player = Player::load(dir.path(), &o).unwrap();
  1094. check(&mut player, &o, &expected, &format!("buffers {buffers:?}"));
  1095. }
  1096. let o = Options { compare: true, merge_barriers: true, loops: 2, ..Default::default() };
  1097. let both = play::replay(dir.path(), &o).unwrap();
  1098. assert_eq!(both.len(), 2);
  1099. assert!(both.iter().all(|(_, r)| r.picture.unwrap().1));
  1100. assert!(folder.join("replay.png").exists() && folder.join("replay-unchanged.png").exists());
  1101. if debug {
  1102. let q = device.cast::<ID3D12InfoQueue>().unwrap();
  1103. // SAFETY: plain queries; messages read into buffers of their size.
  1104. unsafe {
  1105. for i in 0..q.GetNumStoredMessages() {
  1106. let mut size = 0;
  1107. let _ = q.GetMessage(i, None, &mut size);
  1108. let mut buffer = vec![0u64; size.div_ceil(8)];
  1109. let m = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  1110. if q.GetMessage(i, Some(m), &mut size).is_ok() && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0 {
  1111. let text = std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength);
  1112. println!("D3D12 {} {}: {}", (*m).Severity.0, (*m).ID.0, String::from_utf8_lossy(text));
  1113. }
  1114. }
  1115. }
  1116. }
  1117. }