replay.rs 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  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::{
  16. D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob,
  17. };
  18. use windows::Win32::Graphics::Direct3D12::*;
  19. use windows::Win32::Graphics::Dxgi::Common::*;
  20. use windows::Win32::Graphics::Dxgi::*;
  21. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  22. use windows::Win32::UI::WindowsAndMessaging::*;
  23. use windows::core::{Interface, PCSTR, s, w};
  24. const SIZE: u32 = 128;
  25. const DRAW: &str = r#"
  26. #define RS "RootConstants(num32BitConstants=2, b0), CBV(b1), DescriptorTable(SRV(t0, numDescriptors=unbounded)), DescriptorTable(Sampler(s0))"
  27. cbuffer Pick : register(b0) { uint pick; uint pad; };
  28. cbuffer Place : register(b1) { float4 place; };
  29. Texture2D all[] : register(t0);
  30. SamplerState point_sampler : register(s0);
  31. struct V { float4 at : SV_Position; float2 uv : UV; };
  32. [RootSignature(RS)]
  33. V vs(uint i : SV_VertexID) {
  34. float2 c = float2(i & 1, (i >> 1) & 1);
  35. if (i == 3) c = float2(1, 0);
  36. if (i == 4) c = float2(0, 1);
  37. if (i == 5) c = float2(1, 1);
  38. V v;
  39. v.uv = c;
  40. v.at = float4(place.xy + c * place.zw, 0.5, 1);
  41. return v;
  42. }
  43. float4 ps(V v) : SV_Target { return all[NonUniformResourceIndex(pick)].SampleLevel(point_sampler, v.uv, 0); }
  44. "#;
  45. /// Triangles of vertices and indices.
  46. const PLAIN: &str = r#"
  47. #define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT)"
  48. struct V { float4 at : SV_Position; float3 color : COLOR; };
  49. [RootSignature(RS)]
  50. V vs(float2 at : POSITION, float3 color : COLOR1) { V v; v.at = float4(at, 0.4, 1); v.color = color; return v; }
  51. float4 ps(V v) : SV_Target { return float4(v.color, 1); }
  52. "#;
  53. /// A quad from a mesh shader, its texture picked from the heap by index.
  54. const MESH: &str = r#"
  55. #define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), RootConstants(num32BitConstants=5, b0)"
  56. cbuffer C : register(b0) { float4 place; uint pick; };
  57. struct V { float4 at : SV_Position; float2 uv : UV; };
  58. [RootSignature(RS)]
  59. [numthreads(1, 1, 1)]
  60. [outputtopology("triangle")]
  61. void ms(out vertices V v[4], out indices uint3 t[2]) {
  62. SetMeshOutputCounts(4, 2);
  63. for (uint i = 0; i < 4; i++) {
  64. float2 c = float2(i & 1, i >> 1);
  65. v[i].at = float4(place.xy + c * place.zw, 0.3, 1);
  66. v[i].uv = c;
  67. }
  68. t[0] = uint3(0, 1, 2);
  69. t[1] = uint3(2, 1, 3);
  70. }
  71. [RootSignature(RS)]
  72. float4 ps(V v) : SV_Target {
  73. Texture2D<float4> t = ResourceDescriptorHeap[pick];
  74. return t.Load(int3(v.uv * 16, 0)) * 0.5 + float4(v.uv, 0, 0) * 0.5;
  75. }
  76. "#;
  77. /// Compiles with the Windows SDK's dxc, if there is one.
  78. fn dxc(source: &str, entry: &str, target: &str) -> Option<Vec<u8>> {
  79. let kits = std::fs::read_dir("C:/Program Files (x86)/Windows Kits/10/bin").ok()?;
  80. let exe = kits
  81. .flatten()
  82. .map(|e| e.path().join("x64/dxc.exe"))
  83. .filter(|p| p.exists())
  84. .max()?;
  85. let dir = tempfile::tempdir().ok()?;
  86. let (from, to) = (dir.path().join("a.hlsl"), dir.path().join("a.dxil"));
  87. std::fs::write(&from, source).ok()?;
  88. let out = std::process::Command::new(exe)
  89. .args(["-T", target, "-E", entry, "-Fo"])
  90. .arg(&to)
  91. .arg(&from)
  92. .output()
  93. .ok()?;
  94. assert!(
  95. out.status.success(),
  96. "{}",
  97. String::from_utf8_lossy(&out.stderr)
  98. );
  99. std::fs::read(to).ok()
  100. }
  101. /// The mesh pipeline, from a stream, by way of a pipeline library; and the
  102. /// signature of its indirect draws. `None` without dxc or mesh shaders.
  103. fn mesh(device: &ID3D12Device, blend: D3D12_BLEND_DESC) -> Option<(Made, ID3D12CommandSignature)> {
  104. #[repr(C, align(8))]
  105. struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T);
  106. #[repr(C)]
  107. struct Stream {
  108. root: Sub<*mut std::ffi::c_void>,
  109. ms: Sub<D3D12_SHADER_BYTECODE>,
  110. ps: Sub<D3D12_SHADER_BYTECODE>,
  111. blend: Sub<D3D12_BLEND_DESC>,
  112. mask: Sub<u32>,
  113. raster: Sub<D3D12_RASTERIZER_DESC>,
  114. depth: Sub<D3D12_DEPTH_STENCIL_DESC>,
  115. targets: Sub<D3D12_RT_FORMAT_ARRAY>,
  116. dsv: Sub<DXGI_FORMAT>,
  117. samples: Sub<DXGI_SAMPLE_DESC>,
  118. topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>,
  119. }
  120. let (ms, ps) = (dxc(MESH, "ms", "ms_6_6")?, dxc(MESH, "ps", "ps_6_6")?);
  121. // SAFETY: plain queries and creation; the stream holds whole subobjects.
  122. unsafe {
  123. let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  124. let size = size_of::<D3D12_FEATURE_DATA_D3D12_OPTIONS7>() as u32;
  125. device
  126. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, (&raw mut o).cast(), size)
  127. .ok()?;
  128. if o.MeshShaderTier == D3D12_MESH_SHADER_TIER_NOT_SUPPORTED {
  129. return None;
  130. }
  131. let root: ID3D12RootSignature = device.CreateRootSignature(0, &ms).unwrap();
  132. let mut formats = D3D12_RT_FORMAT_ARRAY {
  133. NumRenderTargets: 1,
  134. ..Default::default()
  135. };
  136. formats.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  137. let mut stream = Stream {
  138. root: Sub(
  139. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE,
  140. root.as_raw(),
  141. ),
  142. ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(&ms)),
  143. ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(&ps)),
  144. blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend),
  145. mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, u32::MAX),
  146. raster: Sub(
  147. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER,
  148. D3D12_RASTERIZER_DESC {
  149. FillMode: D3D12_FILL_MODE_SOLID,
  150. CullMode: D3D12_CULL_MODE_NONE,
  151. ..Default::default()
  152. },
  153. ),
  154. depth: Sub(
  155. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL,
  156. D3D12_DEPTH_STENCIL_DESC::default(),
  157. ),
  158. targets: Sub(
  159. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS,
  160. formats,
  161. ),
  162. dsv: Sub(
  163. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT,
  164. DXGI_FORMAT_D32_FLOAT,
  165. ),
  166. samples: Sub(
  167. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC,
  168. DXGI_SAMPLE_DESC {
  169. Count: 1,
  170. Quality: 0,
  171. },
  172. ),
  173. topology: Sub(
  174. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY,
  175. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  176. ),
  177. };
  178. let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
  179. SizeInBytes: size_of::<Stream>(),
  180. pPipelineStateSubobjectStream: (&raw mut stream).cast(),
  181. };
  182. let library: ID3D12PipelineLibrary1 = device
  183. .cast::<ID3D12Device1>()
  184. .unwrap()
  185. .CreatePipelineLibrary::<ID3D12PipelineLibrary>(&[])
  186. .unwrap()
  187. .cast()
  188. .unwrap();
  189. {
  190. let made: ID3D12PipelineState = device
  191. .cast::<ID3D12Device2>()
  192. .unwrap()
  193. .CreatePipelineState(&desc)
  194. .unwrap();
  195. library.StorePipeline(w!("mesh"), &made).unwrap();
  196. }
  197. let pso: ID3D12PipelineState = library.LoadPipeline(w!("mesh"), &desc).unwrap();
  198. record::name(&pso, "a mesh pipeline");
  199. let argument = D3D12_INDIRECT_ARGUMENT_DESC {
  200. Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH,
  201. ..Default::default()
  202. };
  203. let mut signature: Option<ID3D12CommandSignature> = None;
  204. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  205. ByteStride: 12,
  206. NumArgumentDescs: 1,
  207. pArgumentDescs: &argument,
  208. NodeMask: 0,
  209. };
  210. device
  211. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature)
  212. .unwrap();
  213. Some((Made { root, pso }, signature.unwrap()))
  214. }
  215. }
  216. /// Writes the arguments of indirect draws (two records: six vertices, and
  217. /// one far too many that the clamp cuts to none).
  218. const ARGS: &str = r#"
  219. #define RS "SRV(t0), UAV(u0)"
  220. ByteAddressBuffer from : register(t0);
  221. RWByteAddressBuffer args : register(u0);
  222. [RootSignature(RS)]
  223. [numthreads(1, 1, 1)]
  224. void main() {
  225. args.Store4(0, uint4(from.Load(0), 1, 0, 0));
  226. args.Store4(16, uint4(4000000000u, 1, 0, 0));
  227. }
  228. "#;
  229. /// The argument clamp's parameters, with a simple bound.
  230. const CLAMP: &str = r#"
  231. #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)"
  232. cbuffer C : register(b0) { uint kind; uint stride; uint records; uint args_offset; uint has_count; uint count_offset; };
  233. ByteAddressBuffer from : register(t0);
  234. ByteAddressBuffer count : register(t1);
  235. RWByteAddressBuffer to : register(u0);
  236. RWByteAddressBuffer budget : register(u1);
  237. [RootSignature(RS)]
  238. [numthreads(64, 1, 1)]
  239. void main(uint3 id : SV_DispatchThreadID) {
  240. if (id.x >= records) return;
  241. uint4 a = from.Load4(args_offset + id.x * stride);
  242. if (a.x > 1000) a.x = 0;
  243. to.Store4(id.x * stride, a);
  244. uint was;
  245. budget.InterlockedAdd(0, a.x, was);
  246. }
  247. "#;
  248. /// Adds what the CPU gives to what was there, and writes it on.
  249. const ADD: &str = r#"
  250. #define RS "SRV(t0), DescriptorTable(UAV(u0)), UAV(u1)"
  251. ByteAddressBuffer from : register(t0);
  252. RWTexture2D<float4> image : register(u0);
  253. RWByteAddressBuffer sum : register(u1);
  254. [RootSignature(RS)]
  255. [numthreads(8, 8, 1)]
  256. void main(uint3 id : SV_DispatchThreadID) {
  257. uint at = (id.y * 16 + id.x) * 4;
  258. uint v = from.Load(at) + sum.Load(at) * 3;
  259. sum.Store(at, v);
  260. image[id.xy] = image[id.xy] + float4((v & 15) / 255.0, 0, 1 / 255.0, 1);
  261. }
  262. "#;
  263. struct Made {
  264. root: ID3D12RootSignature,
  265. pso: ID3D12PipelineState,
  266. }
  267. fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec<u8> {
  268. let (mut code, mut errors): (Option<ID3DBlob>, Option<ID3DBlob>) = (None, None);
  269. // SAFETY: the source and names live through the call; the blobs' own
  270. // bytes.
  271. unsafe {
  272. let r = D3DCompile(
  273. source.as_ptr().cast(),
  274. source.len(),
  275. None,
  276. None,
  277. None,
  278. entry,
  279. target,
  280. 1 << 20,
  281. 0,
  282. &mut code,
  283. Some(&mut errors),
  284. );
  285. if r.is_err() {
  286. let e = errors.unwrap();
  287. let text =
  288. std::slice::from_raw_parts(e.GetBufferPointer().cast::<u8>(), e.GetBufferSize());
  289. panic!("{}", String::from_utf8_lossy(text));
  290. }
  291. let code = code.unwrap();
  292. std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize())
  293. .to_vec()
  294. }
  295. }
  296. fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
  297. D3D12_SHADER_BYTECODE {
  298. pShaderBytecode: bytes.as_ptr().cast(),
  299. BytecodeLength: bytes.len(),
  300. }
  301. }
  302. fn compute(device: &ID3D12Device, source: &str) -> Made {
  303. let cs = compile(source, s!("main"), s!("cs_5_1"));
  304. // SAFETY: plain creation.
  305. unsafe {
  306. let root: ID3D12RootSignature = device.CreateRootSignature(0, &cs).unwrap();
  307. let pso = device
  308. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  309. pRootSignature: std::mem::transmute_copy(&root),
  310. CS: code(&cs),
  311. ..Default::default()
  312. })
  313. .unwrap();
  314. Made { root, pso }
  315. }
  316. }
  317. fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC {
  318. D3D12_RESOURCE_DESC {
  319. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  320. Width: size,
  321. Height: 1,
  322. DepthOrArraySize: 1,
  323. MipLevels: 1,
  324. SampleDesc: DXGI_SAMPLE_DESC {
  325. Count: 1,
  326. Quality: 0,
  327. },
  328. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  329. Flags: flags,
  330. ..Default::default()
  331. }
  332. }
  333. fn texture_desc(
  334. size: u32,
  335. format: DXGI_FORMAT,
  336. flags: D3D12_RESOURCE_FLAGS,
  337. ) -> D3D12_RESOURCE_DESC {
  338. D3D12_RESOURCE_DESC {
  339. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  340. Width: u64::from(size),
  341. Height: size,
  342. DepthOrArraySize: 1,
  343. MipLevels: 1,
  344. Format: format,
  345. SampleDesc: DXGI_SAMPLE_DESC {
  346. Count: 1,
  347. Quality: 0,
  348. },
  349. Flags: flags,
  350. ..Default::default()
  351. }
  352. }
  353. #[derive(Clone, Copy, PartialEq)]
  354. enum In {
  355. Card,
  356. Upload,
  357. Back,
  358. /// The PC's memory, mapped, that shaders write too.
  359. Shared,
  360. }
  361. fn committed(
  362. device: &ID3D12Device,
  363. place: In,
  364. desc: &D3D12_RESOURCE_DESC,
  365. state: D3D12_RESOURCE_STATES,
  366. ) -> (ID3D12Resource, *mut u8) {
  367. let heap = match place {
  368. In::Card => D3D12_HEAP_PROPERTIES {
  369. Type: D3D12_HEAP_TYPE_DEFAULT,
  370. ..Default::default()
  371. },
  372. In::Upload => D3D12_HEAP_PROPERTIES {
  373. Type: D3D12_HEAP_TYPE_UPLOAD,
  374. ..Default::default()
  375. },
  376. In::Back => D3D12_HEAP_PROPERTIES {
  377. Type: D3D12_HEAP_TYPE_READBACK,
  378. ..Default::default()
  379. },
  380. In::Shared => D3D12_HEAP_PROPERTIES {
  381. Type: D3D12_HEAP_TYPE_CUSTOM,
  382. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  383. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  384. ..Default::default()
  385. },
  386. };
  387. let mut made: Option<ID3D12Resource> = None;
  388. let mut data = std::ptr::null_mut();
  389. // SAFETY: plain creation and mapping.
  390. unsafe {
  391. device
  392. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, desc, state, None, &mut made)
  393. .unwrap();
  394. let made = made.unwrap();
  395. if place != In::Card {
  396. made.Map(0, None, Some(&mut data)).unwrap();
  397. }
  398. (made, data.cast())
  399. }
  400. }
  401. fn moved(
  402. res: &ID3D12Resource,
  403. before: D3D12_RESOURCE_STATES,
  404. after: D3D12_RESOURCE_STATES,
  405. ) -> D3D12_RESOURCE_BARRIER {
  406. D3D12_RESOURCE_BARRIER {
  407. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  408. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  409. Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  410. // SAFETY: a borrowed pointer never released.
  411. pResource: unsafe { std::mem::transmute_copy(res) },
  412. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  413. StateBefore: before,
  414. StateAfter: after,
  415. }),
  416. },
  417. ..Default::default()
  418. }
  419. }
  420. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  421. D3D12_RESOURCE_BARRIER {
  422. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  423. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  424. UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  425. pResource: ManuallyDrop::new(None),
  426. }),
  427. },
  428. ..Default::default()
  429. }
  430. }
  431. fn aliased(before: &ID3D12Resource, after: &ID3D12Resource) -> D3D12_RESOURCE_BARRIER {
  432. D3D12_RESOURCE_BARRIER {
  433. Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
  434. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  435. Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
  436. // SAFETY: borrowed pointers never released.
  437. pResourceBefore: unsafe { std::mem::transmute_copy(before) },
  438. // SAFETY: as above.
  439. pResourceAfter: unsafe { std::mem::transmute_copy(after) },
  440. }),
  441. },
  442. ..Default::default()
  443. }
  444. }
  445. const COMMON: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COMMON;
  446. const TARGET: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_RENDER_TARGET;
  447. const READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
  448. const UAV: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  449. const TO: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_DEST;
  450. const FROM: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_COPY_SOURCE;
  451. const ARGUMENTS: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
  452. /// A texture the frames do not touch: what each subresource holds, row by
  453. /// row, with the rows' distance in its copyable layout.
  454. #[derive(PartialEq, Debug, Clone)]
  455. struct Still {
  456. name: &'static str,
  457. subs: Vec<(usize, Vec<Vec<u8>>)>,
  458. }
  459. /// What the program ends with.
  460. #[derive(PartialEq, Debug)]
  461. struct Outcome {
  462. still: Vec<Still>,
  463. picture: Vec<u8>,
  464. image: Vec<u8>,
  465. sum: Vec<u8>,
  466. shared: Vec<u8>,
  467. }
  468. struct Scene {
  469. device: ID3D12Device,
  470. queue: ID3D12CommandQueue,
  471. fence: ID3D12Fence,
  472. event: HANDLE,
  473. value: u64,
  474. lists: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
  475. draw: Made,
  476. plain: Made,
  477. mesh: Option<(Made, ID3D12CommandSignature)>,
  478. vertices: (ID3D12Resource, *mut u8),
  479. samplers: ID3D12DescriptorHeap,
  480. still: Vec<(&'static str, ID3D12Resource, D3D12_RESOURCE_STATES)>,
  481. copies: (
  482. ID3D12CommandQueue,
  483. ID3D12CommandAllocator,
  484. ID3D12GraphicsCommandList,
  485. ),
  486. args: Made,
  487. clamp: Made,
  488. add: Made,
  489. signature: ID3D12CommandSignature,
  490. views: ID3D12DescriptorHeap,
  491. step: usize,
  492. rtvs: ID3D12DescriptorHeap,
  493. dsvs: ID3D12DescriptorHeap,
  494. target: ID3D12Resource,
  495. _depth: ID3D12Resource,
  496. fixed: ID3D12Resource,
  497. one: ID3D12Resource,
  498. other: ID3D12Resource,
  499. _heap: ID3D12Heap,
  500. image: ID3D12Resource,
  501. sum: ID3D12Resource,
  502. arguments: ID3D12Resource,
  503. scratch: ID3D12Resource,
  504. budget: ID3D12Resource,
  505. shared: (ID3D12Resource, *mut u8),
  506. constants: (ID3D12Resource, *mut u8),
  507. texels: (ID3D12Resource, *mut u8),
  508. back: (ID3D12Resource, *mut u8),
  509. swap: Option<(IDXGISwapChain3, HWND)>,
  510. }
  511. impl Scene {
  512. fn new(device: &ID3D12Device, window: bool) -> Scene {
  513. // SAFETY: plain creation throughout.
  514. unsafe {
  515. let queue: ID3D12CommandQueue = device
  516. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  517. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  518. ..Default::default()
  519. })
  520. .unwrap();
  521. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
  522. let lists = (0..3)
  523. .map(|_| {
  524. let allocator: ID3D12CommandAllocator = device
  525. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)
  526. .unwrap();
  527. let list: ID3D12GraphicsCommandList = device
  528. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)
  529. .unwrap();
  530. list.Close().unwrap();
  531. (allocator, list)
  532. })
  533. .collect();
  534. let (vs, ps) = (
  535. compile(DRAW, s!("vs"), s!("vs_5_1")),
  536. compile(DRAW, s!("ps"), s!("ps_5_1")),
  537. );
  538. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
  539. let mut blend = D3D12_BLEND_DESC::default();
  540. blend.RenderTarget[0].RenderTargetWriteMask = 15;
  541. let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  542. pRootSignature: std::mem::transmute_copy(&root),
  543. VS: code(&vs),
  544. PS: code(&ps),
  545. BlendState: blend,
  546. SampleMask: u32::MAX,
  547. RasterizerState: D3D12_RASTERIZER_DESC {
  548. FillMode: D3D12_FILL_MODE_SOLID,
  549. CullMode: D3D12_CULL_MODE_NONE,
  550. DepthClipEnable: true.into(),
  551. ..Default::default()
  552. },
  553. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  554. DepthEnable: true.into(),
  555. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  556. DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL,
  557. ..Default::default()
  558. },
  559. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  560. NumRenderTargets: 1,
  561. DSVFormat: DXGI_FORMAT_D32_FLOAT,
  562. SampleDesc: DXGI_SAMPLE_DESC {
  563. Count: 1,
  564. Quality: 0,
  565. },
  566. ..Default::default()
  567. };
  568. desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  569. let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
  570. record::name(&pso, "a drawing pipeline");
  571. let draw = Made { root, pso };
  572. let (vs, ps) = (
  573. compile(PLAIN, s!("vs"), s!("vs_5_1")),
  574. compile(PLAIN, s!("ps"), s!("ps_5_1")),
  575. );
  576. let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap();
  577. let element = |name, index, format, at| D3D12_INPUT_ELEMENT_DESC {
  578. SemanticName: name,
  579. SemanticIndex: index,
  580. Format: format,
  581. InputSlot: 0,
  582. AlignedByteOffset: at,
  583. InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
  584. InstanceDataStepRate: 0,
  585. };
  586. let elements = [
  587. element(s!("POSITION"), 0, DXGI_FORMAT_R32G32_FLOAT, 0),
  588. element(s!("COLOR"), 1, DXGI_FORMAT_R32G32B32_FLOAT, 8),
  589. ];
  590. desc.pRootSignature = std::mem::transmute_copy(&root);
  591. (desc.VS, desc.PS) = (code(&vs), code(&ps));
  592. desc.InputLayout = D3D12_INPUT_LAYOUT_DESC {
  593. pInputElementDescs: elements.as_ptr(),
  594. NumElements: 2,
  595. };
  596. let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap();
  597. let plain = Made { root, pso };
  598. let clamp = compute(device, CLAMP);
  599. record::name(&clamp.pso, play::CLAMP);
  600. let argument = D3D12_INDIRECT_ARGUMENT_DESC {
  601. Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW,
  602. ..Default::default()
  603. };
  604. let mut signature: Option<ID3D12CommandSignature> = None;
  605. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  606. ByteStride: 16,
  607. NumArgumentDescs: 1,
  608. pArgumentDescs: &argument,
  609. NodeMask: 0,
  610. };
  611. device
  612. .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut signature)
  613. .unwrap();
  614. let heap = |kind, count, flags| -> ID3D12DescriptorHeap {
  615. device
  616. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  617. Type: kind,
  618. NumDescriptors: count,
  619. Flags: flags,
  620. NodeMask: 0,
  621. })
  622. .unwrap()
  623. };
  624. let samplers = heap(
  625. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
  626. 4,
  627. D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  628. );
  629. let sampler = D3D12_SAMPLER_DESC {
  630. Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
  631. AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  632. AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  633. AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP,
  634. MaxLOD: 8.0,
  635. ..Default::default()
  636. };
  637. let mut at = samplers.GetCPUDescriptorHandleForHeapStart();
  638. at.ptr += 2 * device
  639. .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)
  640. as usize;
  641. device.CreateSampler(&sampler, at);
  642. let views = heap(
  643. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  644. 5000,
  645. D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  646. );
  647. let rtvs = heap(
  648. D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  649. 1,
  650. D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
  651. );
  652. let dsvs = heap(
  653. D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  654. 1,
  655. D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
  656. );
  657. let rgba = DXGI_FORMAT_R8G8B8A8_UNORM;
  658. let (target, _) = committed(
  659. device,
  660. In::Card,
  661. &texture_desc(SIZE, rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET),
  662. FROM,
  663. );
  664. let (depth, _) = committed(
  665. device,
  666. In::Card,
  667. &texture_desc(
  668. SIZE,
  669. DXGI_FORMAT_D32_FLOAT,
  670. D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
  671. ),
  672. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  673. );
  674. let (fixed, _) = committed(
  675. device,
  676. In::Card,
  677. &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE),
  678. TO,
  679. );
  680. let (image, _) = committed(
  681. device,
  682. In::Card,
  683. &texture_desc(16, rgba, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
  684. UAV,
  685. );
  686. let mut memory: Option<ID3D12Heap> = None;
  687. let desc = D3D12_HEAP_DESC {
  688. SizeInBytes: 4 << 20,
  689. Properties: D3D12_HEAP_PROPERTIES {
  690. Type: D3D12_HEAP_TYPE_DEFAULT,
  691. ..Default::default()
  692. },
  693. Alignment: 0,
  694. Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
  695. };
  696. device.CreateHeap(&desc, &mut memory).unwrap();
  697. let memory = memory.unwrap();
  698. let placed = || {
  699. let mut made: Option<ID3D12Resource> = None;
  700. let d = texture_desc(16, rgba, D3D12_RESOURCE_FLAG_NONE);
  701. device
  702. .CreatePlacedResource(&memory, 65536, &d, TO, None, &mut made)
  703. .unwrap();
  704. made.unwrap()
  705. };
  706. // Two textures in one place.
  707. let (one, other) = (placed(), placed());
  708. let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  709. let card = |size| committed(device, In::Card, &buffer_desc(size, uav), COMMON).0;
  710. let (sum, arguments, scratch, budget) = (card(1024), card(4096), card(4096), card(256));
  711. let shared = committed(device, In::Shared, &buffer_desc(70_000, uav), COMMON);
  712. let constants = committed(
  713. device,
  714. In::Upload,
  715. &buffer_desc(8192, D3D12_RESOURCE_FLAG_NONE),
  716. D3D12_RESOURCE_STATE_GENERIC_READ,
  717. );
  718. let texels = committed(
  719. device,
  720. In::Upload,
  721. &buffer_desc(65536, D3D12_RESOURCE_FLAG_NONE),
  722. D3D12_RESOURCE_STATE_GENERIC_READ,
  723. );
  724. let back = committed(
  725. device,
  726. In::Back,
  727. &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE),
  728. TO,
  729. );
  730. let vertices = committed(
  731. device,
  732. In::Upload,
  733. &buffer_desc(4096, D3D12_RESOURCE_FLAG_NONE),
  734. D3D12_RESOURCE_STATE_GENERIC_READ,
  735. );
  736. let still = {
  737. let blocks = D3D12_RESOURCE_DESC {
  738. MipLevels: 5,
  739. DepthOrArraySize: 3,
  740. ..texture_desc(64, DXGI_FORMAT_BC7_UNORM, D3D12_RESOURCE_FLAG_NONE)
  741. };
  742. let volume = D3D12_RESOURCE_DESC {
  743. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D,
  744. DepthOrArraySize: 8,
  745. MipLevels: 3,
  746. ..texture_desc(16, DXGI_FORMAT_R16_FLOAT, D3D12_RESOURCE_FLAG_NONE)
  747. };
  748. let stencil = texture_desc(
  749. 32,
  750. DXGI_FORMAT_R32G8X24_TYPELESS,
  751. D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
  752. );
  753. let (write, read) = (
  754. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  755. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  756. );
  757. [
  758. ("blocks", blocks, TO, READ),
  759. ("volume", volume, TO, read),
  760. ("stencil", stencil, write, write),
  761. ]
  762. .map(|(name, d, made_in, ends)| {
  763. let (t, _) = committed(device, In::Card, &d, made_in);
  764. record::name(&t, name);
  765. (name, t, ends)
  766. })
  767. };
  768. let copies: (
  769. ID3D12CommandQueue,
  770. ID3D12CommandAllocator,
  771. ID3D12GraphicsCommandList,
  772. ) = {
  773. let queue = device
  774. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  775. Type: D3D12_COMMAND_LIST_TYPE_COPY,
  776. ..Default::default()
  777. })
  778. .unwrap();
  779. let allocator: ID3D12CommandAllocator = device
  780. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)
  781. .unwrap();
  782. let list: ID3D12GraphicsCommandList = device
  783. .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)
  784. .unwrap();
  785. list.Close().unwrap();
  786. (queue, allocator, list)
  787. };
  788. for (r, n) in [
  789. (&sum, "sum"),
  790. (&image, "image"),
  791. (&target, "target"),
  792. (&shared.0, "shared"),
  793. (&one, "one"),
  794. (&other, "other"),
  795. ] {
  796. record::name(r, n);
  797. }
  798. device.CreateRenderTargetView(&target, None, rtvs.GetCPUDescriptorHandleForHeapStart());
  799. device.CreateDepthStencilView(&depth, None, dsvs.GetCPUDescriptorHandleForHeapStart());
  800. let step = device
  801. .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)
  802. as usize;
  803. let swap = window.then(|| swap_chain(&queue));
  804. let scene = Scene {
  805. device: device.clone(),
  806. queue,
  807. fence,
  808. event: CreateEventW(None, false, false, None).unwrap(),
  809. value: 0,
  810. lists,
  811. draw,
  812. plain,
  813. mesh: mesh(device, blend),
  814. vertices,
  815. samplers,
  816. still: still.to_vec(),
  817. copies,
  818. args: compute(device, ARGS),
  819. clamp,
  820. add: compute(device, ADD),
  821. signature: signature.unwrap(),
  822. views,
  823. step,
  824. rtvs,
  825. dsvs,
  826. target,
  827. _depth: depth,
  828. fixed,
  829. one,
  830. other,
  831. _heap: memory,
  832. image,
  833. sum,
  834. arguments,
  835. scratch,
  836. budget,
  837. shared,
  838. constants,
  839. texels,
  840. back,
  841. swap,
  842. };
  843. // Null views everywhere, by copies of a slot made elsewhere.
  844. let block = heap(
  845. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  846. 16,
  847. D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
  848. );
  849. let null = D3D12_SHADER_RESOURCE_VIEW_DESC {
  850. Format: rgba,
  851. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  852. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  853. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  854. Texture2D: D3D12_TEX2D_SRV {
  855. MipLevels: 1,
  856. ..Default::default()
  857. },
  858. },
  859. };
  860. let from = block.GetCPUDescriptorHandleForHeapStart();
  861. for i in 0..16 {
  862. let at = D3D12_CPU_DESCRIPTOR_HANDLE {
  863. ptr: from.ptr + i * step,
  864. };
  865. device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), at);
  866. }
  867. for i in (0..4992).step_by(16) {
  868. device.CopyDescriptorsSimple(
  869. 16,
  870. scene.cpu(i),
  871. from,
  872. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  873. );
  874. }
  875. // The rest with the other copying method, in unlike pieces.
  876. let to = [scene.cpu(4992), scene.cpu(4994)];
  877. let sources = [
  878. from,
  879. D3D12_CPU_DESCRIPTOR_HANDLE {
  880. ptr: from.ptr + 4 * step,
  881. },
  882. ];
  883. device.CopyDescriptors(
  884. 2,
  885. to.as_ptr(),
  886. Some([2u32, 6].as_ptr()),
  887. 2,
  888. sources.as_ptr(),
  889. Some([4u32, 4].as_ptr()),
  890. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  891. );
  892. scene.show(4001, &scene.other);
  893. scene.show(4002, &scene.one);
  894. device.CreateUnorderedAccessView(
  895. &scene.image,
  896. None::<&ID3D12Resource>,
  897. None,
  898. scene.cpu(7),
  899. );
  900. scene
  901. }
  902. }
  903. fn cpu(&self, i: usize) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  904. // SAFETY: a slot of the heap.
  905. let start = unsafe { self.views.GetCPUDescriptorHandleForHeapStart() };
  906. D3D12_CPU_DESCRIPTOR_HANDLE {
  907. ptr: start.ptr + i * self.step,
  908. }
  909. }
  910. /// Slot `i` shows `texture`.
  911. fn show(&self, i: usize, texture: &ID3D12Resource) {
  912. // SAFETY: a slot of the heap and a live texture.
  913. unsafe {
  914. self.device
  915. .CreateShaderResourceView(texture, None, self.cpu(i))
  916. };
  917. }
  918. fn wait(&mut self) {
  919. self.value += 1;
  920. // SAFETY: our queue, fence and event.
  921. unsafe {
  922. self.queue.Signal(&self.fence, self.value).unwrap();
  923. self.fence
  924. .SetEventOnCompletion(self.value, self.event)
  925. .unwrap();
  926. WaitForSingleObject(self.event, INFINITE);
  927. self.device.GetDeviceRemovedReason().unwrap();
  928. }
  929. }
  930. fn open(&self, i: usize) -> ID3D12GraphicsCommandList {
  931. let (allocator, list) = &self.lists[i];
  932. // SAFETY: its last run was waited for.
  933. unsafe {
  934. allocator.Reset().unwrap();
  935. list.Reset(allocator, None).unwrap();
  936. }
  937. list.clone()
  938. }
  939. fn send(&self, lists: &[&ID3D12GraphicsCommandList]) {
  940. let all: Vec<Option<ID3D12CommandList>> =
  941. lists.iter().map(|l| Some(l.cast().unwrap())).collect();
  942. // SAFETY: closed lists.
  943. unsafe { self.queue.ExecuteCommandLists(&all) };
  944. }
  945. /// Fills rows of a 16x16 texture in the upload buffer at `at`.
  946. fn fill(&self, at: usize, color: [u8; 4]) {
  947. for y in 0..16 {
  948. for x in 0..16 {
  949. let mut c = color;
  950. c[1] = c[1].wrapping_add((x * 8 + y) as u8);
  951. // SAFETY: inside the mapping (16 rows of 256 bytes).
  952. unsafe {
  953. self.texels
  954. .1
  955. .add(at + y * 256 + x * 4)
  956. .cast::<[u8; 4]>()
  957. .write(c)
  958. };
  959. }
  960. }
  961. }
  962. fn texture_copy(&self, l: &ID3D12GraphicsCommandList, texture: &ID3D12Resource, at: u64) {
  963. let from = D3D12_TEXTURE_COPY_LOCATION {
  964. // SAFETY: a borrowed pointer never released.
  965. pResource: unsafe { std::mem::transmute_copy(&self.texels.0) },
  966. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  967. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  968. PlacedFootprint: footprint(at, 16),
  969. },
  970. };
  971. let to = D3D12_TEXTURE_COPY_LOCATION {
  972. // SAFETY: as above.
  973. pResource: unsafe { std::mem::transmute_copy(texture) },
  974. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  975. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  976. SubresourceIndex: 0,
  977. },
  978. };
  979. // SAFETY: an open list; live resources.
  980. unsafe { l.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
  981. }
  982. /// A quad of the texture in slot `pick`, at the constants at `at`.
  983. fn quad(&self, l: &ID3D12GraphicsCommandList, pick: u32, at: u64, record: u64) {
  984. // SAFETY: an open list; live objects.
  985. unsafe {
  986. l.SetGraphicsRootSignature(&self.draw.root);
  987. l.SetPipelineState(&self.draw.pso);
  988. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  989. l.SetGraphicsRoot32BitConstant(0, pick, 0);
  990. l.SetGraphicsRootConstantBufferView(1, self.constants.0.GetGPUVirtualAddress() + at);
  991. l.SetGraphicsRootDescriptorTable(2, self.views.GetGPUDescriptorHandleForHeapStart());
  992. let step = self
  993. .device
  994. .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  995. let first = self.samplers.GetGPUDescriptorHandleForHeapStart().ptr;
  996. l.SetGraphicsRootDescriptorTable(
  997. 3,
  998. D3D12_GPU_DESCRIPTOR_HANDLE {
  999. ptr: first + 2 * u64::from(step),
  1000. },
  1001. );
  1002. l.ExecuteIndirect(
  1003. &self.signature,
  1004. 1,
  1005. &self.scratch,
  1006. record * 16,
  1007. None::<&ID3D12Resource>,
  1008. 0,
  1009. );
  1010. }
  1011. }
  1012. /// The arguments made and clamped, as the host layer does it.
  1013. fn arguments(&self, l: &ID3D12GraphicsCommandList, before: D3D12_RESOURCE_STATES) {
  1014. // SAFETY: an open list; live objects.
  1015. unsafe {
  1016. l.SetComputeRootSignature(&self.args.root);
  1017. l.SetPipelineState(&self.args.pso);
  1018. l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress() + 65536);
  1019. l.SetComputeRootUnorderedAccessView(1, self.arguments.GetGPUVirtualAddress());
  1020. l.Dispatch(1, 1, 1);
  1021. l.ResourceBarrier(&[
  1022. uav_barrier(),
  1023. moved(
  1024. &self.arguments,
  1025. UAV,
  1026. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  1027. ),
  1028. ]);
  1029. l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, before, UAV)]);
  1030. l.SetComputeRootSignature(&self.clamp.root);
  1031. l.SetPipelineState(&self.clamp.pso);
  1032. let constants = [0u32, 16, 2, 0, 0, 0];
  1033. l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0);
  1034. l.SetComputeRootShaderResourceView(1, self.arguments.GetGPUVirtualAddress());
  1035. l.SetComputeRootShaderResourceView(2, self.arguments.GetGPUVirtualAddress());
  1036. l.SetComputeRootUnorderedAccessView(3, self.scratch.GetGPUVirtualAddress());
  1037. l.SetComputeRootUnorderedAccessView(4, self.budget.GetGPUVirtualAddress());
  1038. l.Dispatch(1, 1, 1);
  1039. l.ResourceBarrier(&[uav_barrier(), moved(&self.scratch, UAV, ARGUMENTS)]);
  1040. l.ResourceBarrier(&[moved(
  1041. &self.arguments,
  1042. D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
  1043. UAV,
  1044. )]);
  1045. }
  1046. }
  1047. fn place(&self, at: usize, place: [f32; 4]) {
  1048. // SAFETY: inside the mapping.
  1049. unsafe { self.constants.1.add(at).cast::<[f32; 4]>().write(place) };
  1050. }
  1051. fn give(&self, at: usize, value: u32) {
  1052. // SAFETY: inside the mapping.
  1053. unsafe { self.shared.1.add(at).cast::<u32>().write(value) };
  1054. }
  1055. fn targets(&self, l: &ID3D12GraphicsCommandList) {
  1056. // SAFETY: an open list; live objects.
  1057. unsafe {
  1058. let (rtv, dsv) = (
  1059. self.rtvs.GetCPUDescriptorHandleForHeapStart(),
  1060. self.dsvs.GetCPUDescriptorHandleForHeapStart(),
  1061. );
  1062. l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv));
  1063. let size = SIZE as f32;
  1064. l.RSSetViewports(&[D3D12_VIEWPORT {
  1065. Width: size,
  1066. Height: size,
  1067. MaxDepth: 1.0,
  1068. ..Default::default()
  1069. }]);
  1070. l.RSSetScissorRects(&[RECT {
  1071. left: 0,
  1072. top: 0,
  1073. right: SIZE as i32,
  1074. bottom: SIZE as i32,
  1075. }]);
  1076. l.SetDescriptorHeaps(&[Some(self.views.clone()), Some(self.samplers.clone())]);
  1077. }
  1078. }
  1079. /// A triangle with vertices and indices.
  1080. fn triangle(&self, l: &ID3D12GraphicsCommandList, n: u32) {
  1081. // SAFETY: an open list; live objects; inside the mapping, which the
  1082. // card does not use now.
  1083. unsafe {
  1084. let x = 0.5 + 0.05 * n as f32;
  1085. let vertices = [
  1086. [x, 0.4, 1.0, 0.0, 0.0],
  1087. [x + 0.3, 0.4, 0.0, 1.0, 0.0],
  1088. [x, 0.9, 0.0, 0.0, 1.0f32],
  1089. ];
  1090. self.vertices.1.cast::<[[f32; 5]; 3]>().write(vertices);
  1091. self.vertices
  1092. .1
  1093. .add(1024)
  1094. .cast::<[u16; 4]>()
  1095. .write([9, 2, 0, 1]);
  1096. let at = self.vertices.0.GetGPUVirtualAddress();
  1097. l.SetGraphicsRootSignature(&self.plain.root);
  1098. l.SetPipelineState(&self.plain.pso);
  1099. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  1100. l.IASetVertexBuffers(
  1101. 0,
  1102. Some(&[D3D12_VERTEX_BUFFER_VIEW {
  1103. BufferLocation: at,
  1104. SizeInBytes: 60,
  1105. StrideInBytes: 20,
  1106. }]),
  1107. );
  1108. let indices = D3D12_INDEX_BUFFER_VIEW {
  1109. BufferLocation: at + 1024,
  1110. SizeInBytes: 8,
  1111. Format: DXGI_FORMAT_R16_UINT,
  1112. };
  1113. l.IASetIndexBuffer(Some(&indices));
  1114. l.DrawIndexedInstanced(3, 1, 1, 0, 0);
  1115. }
  1116. }
  1117. /// Fills the textures no frame touches.
  1118. fn fill_still(&mut self) {
  1119. // SAFETY: an open list; live objects; mappings written inside their
  1120. // bounds.
  1121. unsafe {
  1122. let (up, data) = committed(
  1123. &self.device,
  1124. In::Upload,
  1125. &buffer_desc(1 << 20, D3D12_RESOURCE_FLAG_NONE),
  1126. D3D12_RESOURCE_STATE_GENERIC_READ,
  1127. );
  1128. for i in 0..1 << 20 {
  1129. data.add(i).write((i * 31 + i / 251) as u8 & 0x3b);
  1130. }
  1131. let l = self.open(0);
  1132. let mut at = 0;
  1133. for (name, t, ends) in &self.still {
  1134. if *name == "stencil" {
  1135. let view = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1136. Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
  1137. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  1138. ..Default::default()
  1139. };
  1140. let heap: ID3D12DescriptorHeap = self
  1141. .device
  1142. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1143. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  1144. NumDescriptors: 1,
  1145. ..Default::default()
  1146. })
  1147. .unwrap();
  1148. let dsv = heap.GetCPUDescriptorHandleForHeapStart();
  1149. self.device.CreateDepthStencilView(t, Some(&view), dsv);
  1150. let both = D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL;
  1151. l.ClearDepthStencilView(dsv, both, 0.75, 3, None);
  1152. let part = RECT {
  1153. left: 5,
  1154. top: 6,
  1155. right: 20,
  1156. bottom: 17,
  1157. };
  1158. l.ClearDepthStencilView(dsv, both, 0.25, 200, Some(&[part]));
  1159. continue;
  1160. }
  1161. let desc = t.GetDesc();
  1162. let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
  1163. 1
  1164. } else {
  1165. desc.DepthOrArraySize
  1166. };
  1167. for sub in 0..u32::from(layers * desc.MipLevels) {
  1168. let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  1169. let mut total = 0;
  1170. self.device.GetCopyableFootprints(
  1171. &desc,
  1172. sub,
  1173. 1,
  1174. at,
  1175. Some(&mut f),
  1176. None,
  1177. None,
  1178. Some(&mut total),
  1179. );
  1180. at = (at + total).next_multiple_of(512);
  1181. let from = D3D12_TEXTURE_COPY_LOCATION {
  1182. pResource: std::mem::transmute_copy(&up),
  1183. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1184. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
  1185. };
  1186. l.CopyTextureRegion(&sub_of(t, sub), 0, 0, 0, &from, None);
  1187. }
  1188. l.ResourceBarrier(&[moved(t, TO, *ends)]);
  1189. }
  1190. l.Close().unwrap();
  1191. self.send(&[&l]);
  1192. self.wait();
  1193. }
  1194. }
  1195. /// What they hold.
  1196. fn read_still(&mut self) -> Vec<Still> {
  1197. let mut all = Vec::new();
  1198. for (name, t, state) in self.still.clone() {
  1199. // SAFETY: as above.
  1200. unsafe {
  1201. let desc = t.GetDesc();
  1202. let layers = if desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
  1203. 1
  1204. } else {
  1205. desc.DepthOrArraySize
  1206. };
  1207. let planes = if name == "stencil" { 2 } else { 1 };
  1208. let mut subs = Vec::new();
  1209. for sub in 0..u32::from(layers * desc.MipLevels) * planes {
  1210. let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  1211. let (mut rows, mut len) = (0, 0);
  1212. self.device.GetCopyableFootprints(
  1213. &desc,
  1214. sub,
  1215. 1,
  1216. 0,
  1217. Some(&mut f),
  1218. Some(&mut rows),
  1219. Some(&mut len),
  1220. None,
  1221. );
  1222. let l = self.open(0);
  1223. l.ResourceBarrier(&[moved(&t, state, FROM)]);
  1224. let to = D3D12_TEXTURE_COPY_LOCATION {
  1225. pResource: std::mem::transmute_copy(&self.back.0),
  1226. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1227. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
  1228. };
  1229. l.CopyTextureRegion(&to, 0, 0, 0, &sub_of(&t, sub), None);
  1230. l.ResourceBarrier(&[moved(&t, FROM, state)]);
  1231. l.Close().unwrap();
  1232. self.send(&[&l]);
  1233. self.wait();
  1234. let pitch = f.Footprint.RowPitch as usize;
  1235. let rows = (0..rows as usize * f.Footprint.Depth as usize)
  1236. .map(|r| {
  1237. std::slice::from_raw_parts(self.back.1.add(r * pitch), len as usize)
  1238. .to_vec()
  1239. })
  1240. .collect();
  1241. subs.push((pitch, rows));
  1242. }
  1243. all.push(Still { name, subs });
  1244. }
  1245. }
  1246. all
  1247. }
  1248. fn frame(&mut self, n: u32) {
  1249. // SAFETY: open lists of ours, live objects; memory is written while
  1250. // the card does not use it.
  1251. unsafe {
  1252. self.wait();
  1253. if n == 0 {
  1254. self.fill_still();
  1255. self.fill(0, [200, 10, 30, 255]);
  1256. self.fill(8192, [10, 40, 220, 255]);
  1257. let l = self.open(0);
  1258. self.texture_copy(&l, &self.fixed, 0);
  1259. self.texture_copy(&l, &self.other, 8192);
  1260. l.ResourceBarrier(&[moved(&self.fixed, TO, READ), moved(&self.other, TO, READ)]);
  1261. l.Close().unwrap();
  1262. self.send(&[&l]);
  1263. self.wait();
  1264. }
  1265. // The first submission.
  1266. self.show(4000, &self.fixed);
  1267. self.place(0, [-1.0 + 0.1 * n as f32, -1.0, 0.5, 0.5]);
  1268. self.place(256, [0.0, 0.0, 0.5, 0.5]);
  1269. self.give(65536, 6);
  1270. self.give(40, 7 + n);
  1271. let l = self.open(0);
  1272. l.ResourceBarrier(&[moved(&self.target, FROM, TARGET)]);
  1273. let (rtv, dsv) = (
  1274. self.rtvs.GetCPUDescriptorHandleForHeapStart(),
  1275. self.dsvs.GetCPUDescriptorHandleForHeapStart(),
  1276. );
  1277. l.ClearRenderTargetView(rtv, &[0.1 * n as f32, 0.2, 0.3, 1.0], None);
  1278. l.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None);
  1279. self.arguments(&l, COMMON);
  1280. self.targets(&l);
  1281. self.quad(&l, 4000, 0, 0);
  1282. self.quad(&l, 4001, 256, 0);
  1283. self.triangle(&l, n);
  1284. // Nothing: the clamp cut it to no vertices.
  1285. self.quad(&l, 4001, 0, 1);
  1286. l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
  1287. l.Close().unwrap();
  1288. self.send(&[&l]);
  1289. self.wait();
  1290. // The second: other constants and another texture in the same
  1291. // places, and the second texture in the memory of the first.
  1292. self.show(4000, &self.other);
  1293. // Arguments of a mesh draw.
  1294. self.constants
  1295. .1
  1296. .add(1024)
  1297. .cast::<[u32; 3]>()
  1298. .write([1, 1, 1]);
  1299. self.place(0, [-0.9, 0.3, 0.6, 0.6]);
  1300. self.place(256, [0.3, -0.8, 0.6, 0.5]);
  1301. self.give(40, 100 + n);
  1302. self.give(65536, 3);
  1303. self.fill(16384, [30, 200, 10 + 5 * n as u8, 255]);
  1304. let l = self.open(1);
  1305. self.targets(&l);
  1306. self.arguments(&l, COMMON);
  1307. self.quad(&l, 4000, 0, 0);
  1308. l.ResourceBarrier(&[moved(&self.other, READ, TO)]);
  1309. l.ResourceBarrier(&[aliased(&self.other, &self.one)]);
  1310. self.texture_copy(&l, &self.one, 16384);
  1311. l.ResourceBarrier(&[moved(&self.one, TO, READ)]);
  1312. self.arguments(&l, ARGUMENTS);
  1313. self.quad(&l, 4002, 256, 0);
  1314. if let Some((made, signature)) = &self.mesh {
  1315. l.SetGraphicsRootSignature(&made.root);
  1316. l.SetPipelineState(&made.pso);
  1317. let constants = [
  1318. (-0.3f32).to_bits(),
  1319. (-0.9f32).to_bits(),
  1320. 0.5f32.to_bits(),
  1321. 0.4f32.to_bits(),
  1322. 4002,
  1323. ];
  1324. l.SetGraphicsRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0);
  1325. l.ExecuteIndirect(
  1326. signature,
  1327. 1,
  1328. &self.constants.0,
  1329. 1024,
  1330. None::<&ID3D12Resource>,
  1331. 0,
  1332. );
  1333. }
  1334. l.ResourceBarrier(&[moved(&self.scratch, ARGUMENTS, COMMON)]);
  1335. // And back, for the next frame.
  1336. l.ResourceBarrier(&[moved(&self.one, READ, TO)]);
  1337. l.ResourceBarrier(&[aliased(&self.one, &self.other)]);
  1338. self.texture_copy(&l, &self.other, 8192);
  1339. l.ResourceBarrier(&[moved(&self.other, TO, READ)]);
  1340. l.Close().unwrap();
  1341. let second = l;
  1342. let l = self.open(2);
  1343. l.SetDescriptorHeaps(&[Some(self.views.clone())]);
  1344. l.SetComputeRootSignature(&self.add.root);
  1345. l.SetPipelineState(&self.add.pso);
  1346. l.SetComputeRootShaderResourceView(0, self.shared.0.GetGPUVirtualAddress());
  1347. let table = self.views.GetGPUDescriptorHandleForHeapStart().ptr + 7 * self.step as u64;
  1348. l.SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table });
  1349. l.SetComputeRootUnorderedAccessView(2, self.sum.GetGPUVirtualAddress());
  1350. for _ in 0..3 {
  1351. l.Dispatch(2, 2, 1);
  1352. l.ResourceBarrier(&[uav_barrier()]);
  1353. }
  1354. // The card writes memory the CPU sees.
  1355. l.ResourceBarrier(&[moved(&self.sum, UAV, FROM)]);
  1356. l.CopyBufferRegion(&self.shared.0, 30_000, &self.sum, 0, 1024);
  1357. l.ResourceBarrier(&[moved(&self.target, TARGET, FROM)]);
  1358. l.Close().unwrap();
  1359. self.send(&[&second, &l]);
  1360. self.wait();
  1361. // Another queue fetches a result, as the host layer's relay does.
  1362. let (queue, allocator, list) = &self.copies;
  1363. allocator.Reset().unwrap();
  1364. list.Reset(allocator, None).unwrap();
  1365. list.CopyBufferRegion(&self.back.0, 1 << 18, &self.sum, 0, 1024);
  1366. list.Close().unwrap();
  1367. queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
  1368. self.value += 1;
  1369. queue.Signal(&self.fence, self.value).unwrap();
  1370. self.fence
  1371. .SetEventOnCompletion(self.value, self.event)
  1372. .unwrap();
  1373. WaitForSingleObject(self.event, INFINITE);
  1374. if let Some((swap, _)) = &self.swap {
  1375. swap.Present(0, DXGI_PRESENT(0)).unwrap();
  1376. }
  1377. record::present(&self.target, FROM);
  1378. }
  1379. }
  1380. /// What everything holds now.
  1381. fn outcome(&mut self) -> Outcome {
  1382. self.wait();
  1383. let still = self.read_still();
  1384. let l = self.open(0);
  1385. // SAFETY: an open list; live objects.
  1386. unsafe {
  1387. let to = |at: u64, size| D3D12_TEXTURE_COPY_LOCATION {
  1388. pResource: std::mem::transmute_copy(&self.back.0),
  1389. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1390. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1391. PlacedFootprint: footprint(at, size),
  1392. },
  1393. };
  1394. let of = |t: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION {
  1395. pResource: std::mem::transmute_copy(t),
  1396. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1397. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1398. SubresourceIndex: 0,
  1399. },
  1400. };
  1401. l.ResourceBarrier(&[moved(&self.image, UAV, FROM)]);
  1402. l.CopyTextureRegion(&to(0, SIZE), 0, 0, 0, &of(&self.target), None);
  1403. l.CopyTextureRegion(&to(1 << 18, 16), 0, 0, 0, &of(&self.image), None);
  1404. l.ResourceBarrier(&[moved(&self.image, FROM, UAV)]);
  1405. l.CopyBufferRegion(&self.back.0, 1 << 19, &self.sum, 0, 1024);
  1406. l.Close().unwrap();
  1407. self.send(&[&l]);
  1408. self.wait();
  1409. let at = |from: usize, n: usize| {
  1410. std::slice::from_raw_parts(self.back.1.add(from), n).to_vec()
  1411. };
  1412. Outcome {
  1413. still,
  1414. picture: at(0, (SIZE * 512) as usize),
  1415. image: rows(&at(1 << 18, 4096)),
  1416. sum: at(1 << 19, 1024),
  1417. shared: std::slice::from_raw_parts(self.shared.1, 70_000).to_vec(),
  1418. }
  1419. }
  1420. }
  1421. }
  1422. fn sub_of(t: &ID3D12Resource, sub: u32) -> D3D12_TEXTURE_COPY_LOCATION {
  1423. D3D12_TEXTURE_COPY_LOCATION {
  1424. // SAFETY: a borrowed pointer never released.
  1425. pResource: unsafe { std::mem::transmute_copy(t) },
  1426. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1427. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1428. SubresourceIndex: sub,
  1429. },
  1430. }
  1431. }
  1432. /// The 64 bytes of each row of a 16x16 texture.
  1433. fn rows(bytes: &[u8]) -> Vec<u8> {
  1434. bytes.chunks(256).flat_map(|r| r[..64].to_vec()).collect()
  1435. }
  1436. fn footprint(at: u64, size: u32) -> D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  1437. D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  1438. Offset: at,
  1439. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  1440. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  1441. Width: size,
  1442. Height: size,
  1443. Depth: 1,
  1444. RowPitch: (size * 4).next_multiple_of(256),
  1445. },
  1446. }
  1447. }
  1448. /// A swap chain of a window that is never shown.
  1449. fn swap_chain(queue: &ID3D12CommandQueue) -> (IDXGISwapChain3, HWND) {
  1450. // SAFETY: plain creation.
  1451. unsafe {
  1452. let hwnd = CreateWindowExW(
  1453. WINDOW_EX_STYLE(0),
  1454. w!("STATIC"),
  1455. w!("replay test"),
  1456. WS_POPUP,
  1457. 0,
  1458. 0,
  1459. 64,
  1460. 64,
  1461. None,
  1462. None,
  1463. None,
  1464. None,
  1465. )
  1466. .unwrap();
  1467. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap();
  1468. let desc = DXGI_SWAP_CHAIN_DESC1 {
  1469. Width: 64,
  1470. Height: 64,
  1471. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  1472. SampleDesc: DXGI_SAMPLE_DESC {
  1473. Count: 1,
  1474. Quality: 0,
  1475. },
  1476. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  1477. BufferCount: 2,
  1478. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  1479. ..Default::default()
  1480. };
  1481. let chain = factory
  1482. .CreateSwapChainForHwnd(queue, hwnd, &desc, None, None)
  1483. .unwrap()
  1484. .cast()
  1485. .unwrap();
  1486. (chain, hwnd)
  1487. }
  1488. }
  1489. fn table_of(device: &ID3D12Device) -> usize {
  1490. // SAFETY: a live COM object starts with its table's address.
  1491. unsafe { *device.as_raw().cast::<usize>() }
  1492. }
  1493. fn check(player: &mut Player, options: &Options, expected: &Outcome, what: &str) -> play::Report {
  1494. let report = player.run(options).unwrap();
  1495. println!("{}", report.text(what));
  1496. assert_eq!(report.frame_ms.len(), options.loops as usize);
  1497. assert!(report.median_ms() > 0.0);
  1498. let (db, same) = report.picture.unwrap();
  1499. assert!(
  1500. same && db.is_infinite(),
  1501. "{what}: the picture differs ({db} dB)"
  1502. );
  1503. let mut get = |name: &str| {
  1504. let id = player.named(name).unwrap();
  1505. player.contents(id).unwrap().unwrap()
  1506. };
  1507. assert_eq!(get("sum"), expected.sum, "{what}: sum");
  1508. assert_eq!(rows(&get("image")), expected.image, "{what}: image");
  1509. assert_eq!(get("target"), expected.picture, "{what}: target");
  1510. assert!(
  1511. get("shared") == expected.shared,
  1512. "{what}: memory the CPU sees"
  1513. );
  1514. for still in &expected.still {
  1515. let id = player.named(still.name).unwrap();
  1516. for (sub, (pitch, rows)) in still.subs.iter().enumerate() {
  1517. let have = player.contents_of(id, sub as u32).unwrap().unwrap();
  1518. for (r, row) in rows.iter().enumerate() {
  1519. assert_eq!(
  1520. &have[r * pitch..][..row.len()],
  1521. &row[..],
  1522. "{what}: {} subresource {sub} row {r}",
  1523. still.name
  1524. );
  1525. }
  1526. }
  1527. }
  1528. // Nothing was left out but what another queue ran.
  1529. let known = [
  1530. "submissions,",
  1531. "waits of the drawing queue",
  1532. "lists sent to a queue other than",
  1533. ];
  1534. assert!(
  1535. !report
  1536. .notes
  1537. .iter()
  1538. .any(|n| n.contains("recorder:") && !known.iter().any(|k| n.contains(k))),
  1539. "{what}: {:?}",
  1540. report.notes
  1541. );
  1542. assert!(report.notes.iter().any(|n| n.contains(known[2])));
  1543. report
  1544. }
  1545. #[test]
  1546. fn a_frame_is_recorded_and_replayed() {
  1547. let debug = std::env::var_os("VICTORY_TEST_D3D_DEBUG").is_some();
  1548. let mut device: Option<ID3D12Device> = None;
  1549. // SAFETY: plain creation.
  1550. unsafe {
  1551. if debug {
  1552. let mut layer: Option<ID3D12Debug> = None;
  1553. D3D12GetDebugInterface(&mut layer).unwrap();
  1554. layer.unwrap().EnableDebugLayer();
  1555. }
  1556. let _ = D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device);
  1557. }
  1558. let Some(device) = device else {
  1559. eprintln!("no adapter: skipped");
  1560. return;
  1561. };
  1562. let own = table_of(&device);
  1563. // Without the recorder.
  1564. let without = {
  1565. let mut scene = Scene::new(&device, false);
  1566. (0..5).for_each(|n| scene.frame(n));
  1567. scene.outcome()
  1568. };
  1569. eprintln!("ran without the recorder");
  1570. // Something is in the picture.
  1571. assert!(without.sum.iter().any(|&b| b != 0));
  1572. for s in &without.still {
  1573. assert!(
  1574. s.subs
  1575. .iter()
  1576. .all(|(_, rows)| rows.iter().flatten().any(|&b| b != 0)),
  1577. "{}",
  1578. s.name
  1579. );
  1580. }
  1581. assert_eq!(
  1582. without
  1583. .still
  1584. .iter()
  1585. .map(|s| s.subs.len())
  1586. .collect::<Vec<_>>(),
  1587. [15, 3, 2]
  1588. );
  1589. let colors: std::collections::HashSet<[u8; 4]> = without
  1590. .picture
  1591. .chunks_exact(4)
  1592. .map(|c| [c[0], c[1], c[2], c[3]])
  1593. .collect();
  1594. assert!(colors.len() > 30, "{}", colors.len());
  1595. // With it: armed at the first present, the fourth frame is captured (a
  1596. // frame whose lists are all recorded comes first).
  1597. assert!(!record::on());
  1598. let dir = tempfile::tempdir().unwrap();
  1599. let settings = Settings {
  1600. folder: dir.path().to_owned(),
  1601. at: At::Frame(1),
  1602. frames: 1,
  1603. always: false,
  1604. };
  1605. let folder = record::start(settings, &device).unwrap();
  1606. assert!(record::on());
  1607. assert_ne!(table_of(&device), own, "the device is hooked");
  1608. assert!(
  1609. record::start(
  1610. Settings {
  1611. folder: dir.path().to_owned(),
  1612. at: At::Trigger,
  1613. frames: 1,
  1614. always: false
  1615. },
  1616. &device
  1617. )
  1618. .is_err(),
  1619. "one recorder a process"
  1620. );
  1621. eprintln!("recorder on");
  1622. let mut scene = Scene::new(&device, true);
  1623. eprintln!("scene made");
  1624. (0..4).for_each(|n| scene.frame(n));
  1625. assert_eq!(
  1626. record::finished(),
  1627. Some(folder.clone()),
  1628. "see {}",
  1629. folder.display()
  1630. );
  1631. let expected = scene.outcome();
  1632. // It goes on as it did without the recorder.
  1633. scene.frame(4);
  1634. let after = scene.outcome();
  1635. assert!(
  1636. after == without,
  1637. "the recorder changed what the program makes"
  1638. );
  1639. drop(scene);
  1640. record::unhook(&device);
  1641. assert_eq!(table_of(&device), own, "the device is as it was");
  1642. for name in [
  1643. "frame.bin",
  1644. "contents.bin",
  1645. "deltas.bin",
  1646. "shaders.bin",
  1647. "present.bin",
  1648. "notes.txt",
  1649. "frame-0.png",
  1650. ] {
  1651. assert!(folder.join(name).exists(), "{name}");
  1652. }
  1653. println!(
  1654. "{}",
  1655. std::fs::read_to_string(folder.join("notes.txt")).unwrap()
  1656. );
  1657. let plain = Options {
  1658. loops: 3,
  1659. ..Default::default()
  1660. };
  1661. let mut player = Player::load(dir.path(), &plain).unwrap();
  1662. check(&mut player, &plain, &expected, "unchanged");
  1663. let detailed = Options {
  1664. detailed: true,
  1665. ..plain.clone()
  1666. };
  1667. let report = check(&mut player, &detailed, &expected, "detailed");
  1668. let count = |kind: &str| {
  1669. report
  1670. .categories
  1671. .iter()
  1672. .find(|c| c.0 == kind)
  1673. .map_or(0, |c| c.2)
  1674. };
  1675. assert_eq!(count("argument clamps (ours)"), 3);
  1676. assert_eq!(count("indirect draws"), 5);
  1677. assert_eq!(count("draws"), 1);
  1678. let meshes = count("indirect mesh draws");
  1679. println!("{meshes} mesh draws");
  1680. if meshes > 0 {
  1681. assert!(
  1682. report
  1683. .shaders
  1684. .iter()
  1685. .any(|s| s.2.starts_with("a mesh pipeline (DXIL ")),
  1686. "{:?}",
  1687. report.shaders
  1688. );
  1689. }
  1690. assert_eq!(count("dispatches"), 6);
  1691. assert_eq!(count("clears"), 2);
  1692. assert!(
  1693. report
  1694. .shaders
  1695. .iter()
  1696. .any(|s| s.2.starts_with("a drawing pipeline (DXIL ")),
  1697. "{:?}",
  1698. report.shaders
  1699. );
  1700. let merged = Options {
  1701. merge_barriers: true,
  1702. ..plain.clone()
  1703. };
  1704. check(&mut player, &merged, &expected, "merged barriers");
  1705. let clamps = Options {
  1706. skip_clamps: true,
  1707. ..plain.clone()
  1708. };
  1709. let report = check(&mut player, &clamps, &expected, "without clamps");
  1710. assert!(
  1711. report.notes.iter().any(|n| n.contains("3 clamp passes")),
  1712. "{:?}",
  1713. report.notes
  1714. );
  1715. let one = Options {
  1716. one_submit: true,
  1717. ..plain.clone()
  1718. };
  1719. check(&mut player, &one, &expected, "one submission");
  1720. let hash = Options {
  1721. skip_hash_passes: true,
  1722. ..plain.clone()
  1723. };
  1724. check(
  1725. &mut player,
  1726. &hash,
  1727. &expected,
  1728. "without hash passes (there are none)",
  1729. );
  1730. // These change what is drawn: they run, and then the frame is as before.
  1731. let no_barriers = Options {
  1732. no_barriers: true,
  1733. ..plain.clone()
  1734. };
  1735. player.run(&no_barriers).unwrap();
  1736. let some = Options {
  1737. only: Some((0, 1)),
  1738. ..plain.clone()
  1739. };
  1740. player.run(&some).unwrap();
  1741. let skip = Options {
  1742. skip_shaders: vec!["a drawing".into()],
  1743. ..plain.clone()
  1744. };
  1745. let report = player.run(&skip).unwrap();
  1746. assert!(
  1747. !report.picture.unwrap().1,
  1748. "without its draws the picture is another"
  1749. );
  1750. assert!(
  1751. report.notes.iter().any(|n| n.contains("1 pipelines match"))
  1752. && report
  1753. .notes
  1754. .iter()
  1755. .any(|n| n.contains("left out 5 commands"))
  1756. );
  1757. let kept = Options {
  1758. restore: false,
  1759. ..plain.clone()
  1760. };
  1761. player.run(&kept).unwrap();
  1762. check(&mut player, &plain, &expected, "unchanged again");
  1763. drop(player);
  1764. for buffers in [Buffers::Card, Buffers::Pc] {
  1765. let o = Options {
  1766. buffers,
  1767. ..plain.clone()
  1768. };
  1769. let mut player = Player::load(dir.path(), &o).unwrap();
  1770. check(&mut player, &o, &expected, &format!("buffers {buffers:?}"));
  1771. }
  1772. let o = Options {
  1773. compare: true,
  1774. merge_barriers: true,
  1775. loops: 2,
  1776. ..Default::default()
  1777. };
  1778. let both = play::replay(dir.path(), &o).unwrap();
  1779. assert_eq!(both.len(), 2);
  1780. assert!(both.iter().all(|(_, r)| r.picture.unwrap().1));
  1781. assert!(folder.join("replay.png").exists() && folder.join("replay-unchanged.png").exists());
  1782. if debug {
  1783. let q = device.cast::<ID3D12InfoQueue>().unwrap();
  1784. // SAFETY: plain queries; messages read into buffers of their size.
  1785. unsafe {
  1786. for i in 0..q.GetNumStoredMessages() {
  1787. let mut size = 0;
  1788. let _ = q.GetMessage(i, None, &mut size);
  1789. let mut buffer = vec![0u64; size.div_ceil(8)];
  1790. let m = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  1791. if q.GetMessage(i, Some(m), &mut size).is_ok()
  1792. && (*m).Severity.0 <= D3D12_MESSAGE_SEVERITY_WARNING.0
  1793. {
  1794. let text =
  1795. std::slice::from_raw_parts((*m).pDescription, (*m).DescriptionByteLength);
  1796. println!(
  1797. "D3D12 {} {}: {}",
  1798. (*m).Severity.0,
  1799. (*m).ID.0,
  1800. String::from_utf8_lossy(text)
  1801. );
  1802. }
  1803. }
  1804. }
  1805. }
  1806. }