indirect.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. //! Indirect execution's arguments, bounded before the GPU reads them. The
  2. //! title's own compute passes write most of them; a pass we drop or
  3. //! translate wrongly leaves whatever the memory held, and a draw of four
  4. //! billion vertices or a dispatch past the host's limits runs until the
  5. //! host resets the display driver. So every record is clamped on the GPU,
  6. //! just before its execution, by a compute shader of ours (HLSL compiled by
  7. //! the system's compiler; a 5.1 shader with its root signature inside).
  8. //!
  9. //! Each list also has a budget (2^27 vertex instances or threads, groups
  10. //! counted as 64 threads, mesh groups as 128): records past it run empty,
  11. //! so a list of thousands of garbage records cannot run for seconds
  12. //! either.
  13. //!
  14. //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
  15. //! groups per dimension and 2^20 per dispatch, one-dimensional mesh
  16. //! dispatches, the budget) cut legitimate work beyond them; raise them if
  17. //! the title needs more.
  18. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  19. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  20. use windows::Win32::Graphics::Direct3D12::*;
  21. use windows::core::s;
  22. use crate::host::{HostList, host, transition};
  23. const SOURCE: &str = r#"
  24. #define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)"
  25. cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; };
  26. RWByteAddressBuffer args : register(u0);
  27. // The list's work so far (vertex instances, threads): past the budget,
  28. // records run empty.
  29. RWByteAddressBuffer budget : register(u1);
  30. static const uint BUDGET = 1u << 27;
  31. // Groups of one dispatch; more run empty.
  32. static const uint GROUPS = 1u << 20;
  33. [RootSignature(RS)]
  34. [numthreads(64, 1, 1)]
  35. void main(uint3 id : SV_DispatchThreadID) {
  36. if (id.x >= records) return;
  37. uint at = id.x * stride;
  38. uint cost;
  39. if (kind <= 1) {
  40. // Draws: vertex or index count, then instances.
  41. uint count = min(args.Load(at), 1u << 24);
  42. uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u));
  43. cost = count * instances;
  44. args.Store2(at, uint2(count, instances));
  45. } else if (kind == 2) {
  46. uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535));
  47. // x * y fits 32 bits; the whole count may not.
  48. if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
  49. g = uint3(0, 0, 0);
  50. }
  51. cost = g.x * g.y * g.z * 64;
  52. args.Store3(at, g);
  53. } else {
  54. // Mesh dispatches: the console's are one-dimensional.
  55. uint3 g = args.Load3(at);
  56. g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u));
  57. cost = g.x * g.y * g.z * 128;
  58. args.Store3(at, g);
  59. }
  60. uint before;
  61. budget.InterlockedAdd(0, cost, before);
  62. if (before >= BUDGET || before + cost > BUDGET) {
  63. // Draws keep their layout with no vertices; groups become zero.
  64. args.Store(at, 0);
  65. }
  66. }
  67. "#;
  68. struct Clamp {
  69. root: ID3D12RootSignature,
  70. pso: ID3D12PipelineState,
  71. }
  72. // SAFETY: D3D12 objects are free-threaded.
  73. unsafe impl Send for Clamp {}
  74. // SAFETY: as above.
  75. unsafe impl Sync for Clamp {}
  76. fn clamp() -> Option<&'static Clamp> {
  77. static CLAMP: std::sync::OnceLock<Option<Clamp>> = std::sync::OnceLock::new();
  78. CLAMP
  79. .get_or_init(|| match make() {
  80. Ok(c) => Some(c),
  81. Err(e) => {
  82. tracing::warn!(error = %e, "no argument clamp: indirect execution dropped");
  83. None
  84. }
  85. })
  86. .as_ref()
  87. }
  88. fn make() -> windows::core::Result<Clamp> {
  89. let device = &host().ok_or_else(windows::core::Error::empty)?.device;
  90. let mut code: Option<ID3DBlob> = None;
  91. let mut errors: Option<ID3DBlob> = None;
  92. // SAFETY: the source and names live through the call; out pointers ours.
  93. let compiled = unsafe {
  94. D3DCompile(
  95. SOURCE.as_ptr().cast(),
  96. SOURCE.len(),
  97. s!("clamp"),
  98. None,
  99. None,
  100. s!("main"),
  101. s!("cs_5_1"),
  102. 0,
  103. 0,
  104. &mut code,
  105. Some(&mut errors),
  106. )
  107. };
  108. if let Err(e) = compiled {
  109. if let Some(errors) = errors {
  110. // SAFETY: the blob's own bytes.
  111. let text = unsafe {
  112. std::slice::from_raw_parts(errors.GetBufferPointer().cast::<u8>(), errors.GetBufferSize())
  113. };
  114. tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text));
  115. }
  116. return Err(e);
  117. }
  118. let code = code.ok_or_else(windows::core::Error::empty)?;
  119. // SAFETY: the blob's own bytes; the root signature is inside the shader.
  120. unsafe {
  121. let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::<u8>(), code.GetBufferSize());
  122. let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?;
  123. let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  124. pRootSignature: std::mem::transmute_copy(&root),
  125. CS: D3D12_SHADER_BYTECODE {
  126. pShaderBytecode: bytes.as_ptr().cast(),
  127. BytecodeLength: bytes.len(),
  128. },
  129. ..Default::default()
  130. })?;
  131. Ok(Clamp { root, pso })
  132. }
  133. }
  134. /// Records, in `list`, the clamp of `records` records of `kind` (PC
  135. /// argument numbering) `stride` bytes apart at host address `gpu` in
  136. /// `buffer`, and leaves the buffer ready to be read as arguments. Replaces
  137. /// the list's compute root signature and pipeline (callers bind theirs
  138. /// after). False if the clamp is not available.
  139. pub(crate) fn bound(
  140. list: &HostList,
  141. buffer: &ID3D12Resource,
  142. gpu: u64,
  143. (kind, stride, records): (u32, u32, u32),
  144. ) -> bool {
  145. let (Some(c), Some(budget)) = (clamp(), list.budget()) else {
  146. return false;
  147. };
  148. if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) {
  149. return false;
  150. }
  151. let l = &list.list;
  152. let constants = [kind, stride, records, 0];
  153. // SAFETY: an open list; our root signature, pipeline and a live buffer
  154. // the caller's list holds.
  155. unsafe {
  156. // Earlier shader writes (the title's argument passes) first.
  157. l.ResourceBarrier(&[uav_barrier()]);
  158. l.SetComputeRootSignature(&c.root);
  159. l.SetPipelineState(&c.pso);
  160. l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0);
  161. l.SetComputeRootUnorderedAccessView(1, gpu);
  162. l.SetComputeRootUnorderedAccessView(2, budget);
  163. l.Dispatch(records.div_ceil(64), 1, 1);
  164. l.ResourceBarrier(&[
  165. uav_barrier(),
  166. transition(
  167. buffer,
  168. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  169. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  170. ),
  171. ]);
  172. }
  173. true
  174. }
  175. /// After the execution: the buffer back to unordered access, where the
  176. /// title's passes keep using it.
  177. pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) {
  178. // SAFETY: an open list and a live buffer.
  179. unsafe {
  180. list.list.ResourceBarrier(&[transition(
  181. buffer,
  182. D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT,
  183. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  184. )])
  185. };
  186. }
  187. fn uav_barrier() -> D3D12_RESOURCE_BARRIER {
  188. D3D12_RESOURCE_BARRIER {
  189. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  190. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  191. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  192. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }),
  193. },
  194. }
  195. }
  196. #[cfg(test)]
  197. mod tests {
  198. /// The clamp compiles with the system's compiler and the host takes it.
  199. #[test]
  200. fn argument_clamp_builds() {
  201. if super::host().is_none() {
  202. return; // no host GPU here
  203. }
  204. assert!(super::clamp().is_some());
  205. }
  206. }