host.rs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523
  1. //! Host pipelines for title pipelines (decision 0007, step 3): the
  2. //! title's graphics state with the translated shaders, under a root
  3. //! signature of our own that the translated shaders' bindings define
  4. //! (`victory_shader::emit`): per stage one block of root constants for the
  5. //! user data, root views for the title's root views, static samplers for
  6. //! the immediate samplers, and directly indexed heaps.
  7. use std::ffi::{CStr, CString};
  8. use std::sync::Arc;
  9. use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
  10. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  11. use windows::Win32::Graphics::Direct3D12::*;
  12. use windows::Win32::Graphics::Dxgi::Common::*;
  13. use windows::core::PCSTR;
  14. use super::{Shader, Translated};
  15. use crate::host::host;
  16. /// A stream's graphics state, owned (the title's stream lives only for the
  17. /// creation call). Subobjects the stream leaves out keep D3D12's defaults.
  18. pub(crate) struct GraphicsState {
  19. pub(super) blend: D3D12_BLEND_DESC,
  20. pub(super) sample_mask: u32,
  21. pub(super) rasterizer: D3D12_RASTERIZER_DESC,
  22. pub(super) depth: D3D12_DEPTH_STENCIL_DESC,
  23. pub(super) depth_bounds: bool,
  24. /// Input elements, their names pointing into `names`.
  25. pub(super) inputs: Vec<D3D12_INPUT_ELEMENT_DESC>,
  26. pub(super) names: Vec<CString>,
  27. pub(super) strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
  28. pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE,
  29. pub(crate) targets: D3D12_RT_FORMAT_ARRAY,
  30. pub(super) depth_format: DXGI_FORMAT,
  31. pub(super) samples: DXGI_SAMPLE_DESC,
  32. }
  33. impl Default for GraphicsState {
  34. fn default() -> Self {
  35. let target = D3D12_RENDER_TARGET_BLEND_DESC {
  36. SrcBlend: D3D12_BLEND_ONE,
  37. DestBlend: D3D12_BLEND_ZERO,
  38. BlendOp: D3D12_BLEND_OP_ADD,
  39. SrcBlendAlpha: D3D12_BLEND_ONE,
  40. DestBlendAlpha: D3D12_BLEND_ZERO,
  41. BlendOpAlpha: D3D12_BLEND_OP_ADD,
  42. LogicOp: D3D12_LOGIC_OP_NOOP,
  43. RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8,
  44. ..Default::default()
  45. };
  46. let keep = D3D12_DEPTH_STENCILOP_DESC {
  47. StencilFailOp: D3D12_STENCIL_OP_KEEP,
  48. StencilDepthFailOp: D3D12_STENCIL_OP_KEEP,
  49. StencilPassOp: D3D12_STENCIL_OP_KEEP,
  50. StencilFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  51. };
  52. GraphicsState {
  53. blend: D3D12_BLEND_DESC {
  54. RenderTarget: [target; 8],
  55. ..Default::default()
  56. },
  57. sample_mask: u32::MAX,
  58. rasterizer: D3D12_RASTERIZER_DESC {
  59. FillMode: D3D12_FILL_MODE_SOLID,
  60. CullMode: D3D12_CULL_MODE_BACK,
  61. DepthClipEnable: true.into(),
  62. ..Default::default()
  63. },
  64. depth: D3D12_DEPTH_STENCIL_DESC {
  65. DepthEnable: true.into(),
  66. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
  67. DepthFunc: D3D12_COMPARISON_FUNC_LESS,
  68. StencilReadMask: 0xff,
  69. StencilWriteMask: 0xff,
  70. FrontFace: keep,
  71. BackFace: keep,
  72. ..Default::default()
  73. },
  74. depth_bounds: false,
  75. inputs: Vec::new(),
  76. names: Vec::new(),
  77. strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED,
  78. topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED,
  79. targets: D3D12_RT_FORMAT_ARRAY::default(),
  80. depth_format: DXGI_FORMAT_UNKNOWN,
  81. samples: DXGI_SAMPLE_DESC {
  82. Count: 1,
  83. Quality: 0,
  84. },
  85. }
  86. }
  87. }
  88. /// Integer render target formats: D3D12 cannot blend into them.
  89. fn integer_format(f: DXGI_FORMAT) -> bool {
  90. matches!(
  91. f,
  92. DXGI_FORMAT_R32G32B32A32_UINT
  93. | DXGI_FORMAT_R32G32B32A32_SINT
  94. | DXGI_FORMAT_R32G32B32_UINT
  95. | DXGI_FORMAT_R32G32B32_SINT
  96. | DXGI_FORMAT_R16G16B16A16_UINT
  97. | DXGI_FORMAT_R16G16B16A16_SINT
  98. | DXGI_FORMAT_R32G32_UINT
  99. | DXGI_FORMAT_R32G32_SINT
  100. | DXGI_FORMAT_R10G10B10A2_UINT
  101. | DXGI_FORMAT_R8G8B8A8_UINT
  102. | DXGI_FORMAT_R8G8B8A8_SINT
  103. | DXGI_FORMAT_R16G16_UINT
  104. | DXGI_FORMAT_R16G16_SINT
  105. | DXGI_FORMAT_R32_UINT
  106. | DXGI_FORMAT_R32_SINT
  107. | DXGI_FORMAT_R8G8_UINT
  108. | DXGI_FORMAT_R8G8_SINT
  109. | DXGI_FORMAT_R16_UINT
  110. | DXGI_FORMAT_R16_SINT
  111. | DXGI_FORMAT_R8_UINT
  112. | DXGI_FORMAT_R8_SINT
  113. )
  114. }
  115. /// The title's blend state as the host takes it: blending off on integer
  116. /// render targets. The console ignores blending there, and titles leave it
  117. /// on (the world sets it on an `R8_UINT` target), but D3D12 does not allow
  118. /// it: vkd3d-proton refuses such a pipeline with `E_INVALIDARG` ("using
  119. /// integer format is not supported"), and its draws are lost. With one
  120. /// description for every target, each target gets its own copy so the
  121. /// others keep theirs.
  122. fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D12_BLEND_DESC {
  123. let count = (targets.NumRenderTargets as usize).min(8);
  124. let per_target = blend.IndependentBlendEnable.as_bool();
  125. let blends = |i: usize| {
  126. blend.RenderTarget[if per_target { i } else { 0 }]
  127. .BlendEnable
  128. .as_bool()
  129. };
  130. if !(0..count).any(|i| integer_format(targets.RTFormats[i]) && blends(i)) {
  131. return *blend;
  132. }
  133. let mut host = *blend;
  134. if !per_target {
  135. host.IndependentBlendEnable = true.into();
  136. host.RenderTarget = [blend.RenderTarget[0]; 8];
  137. }
  138. for i in 0..count {
  139. if integer_format(targets.RTFormats[i]) {
  140. host.RenderTarget[i].BlendEnable = false.into();
  141. }
  142. }
  143. host
  144. }
  145. impl GraphicsState {
  146. /// Whether the draws are a pass over the screen: no vertex input, no
  147. /// depth or stencil, a target. Such passes fill tables once; their shaders
  148. /// are few. (After Belobug/VIctory-Belobug-AMD 18e57db8.)
  149. pub(crate) fn screen_pass(&self) -> bool {
  150. self.inputs.is_empty()
  151. && (self.depth_format == DXGI_FORMAT_UNKNOWN
  152. || !self.depth.DepthEnable.as_bool() && !self.depth.StencilEnable.as_bool())
  153. && self.targets.NumRenderTargets > 0
  154. && self.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE
  155. }
  156. /// Takes in one subobject of a stream: its type, then its data at +4
  157. /// (+8 for those holding pointers).
  158. ///
  159. /// # Safety
  160. /// `at` points at a whole subobject of type `kind`.
  161. pub(crate) unsafe fn read(&mut self, kind: u32, at: *const u8) {
  162. // SAFETY: the caller passes a whole subobject.
  163. unsafe {
  164. let data = at.add(4);
  165. match kind {
  166. 8 => self.blend = data.cast::<D3D12_BLEND_DESC>().read_unaligned(),
  167. 9 => self.sample_mask = data.cast::<u32>().read_unaligned(),
  168. 10 => self.rasterizer = data.cast::<D3D12_RASTERIZER_DESC>().read_unaligned(),
  169. 11 => {
  170. self.depth = data.cast::<D3D12_DEPTH_STENCIL_DESC>().read_unaligned();
  171. self.depth_bounds = false;
  172. }
  173. 21 => {
  174. let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned();
  175. self.depth_bounds = d.DepthBoundsTestEnable.as_bool();
  176. self.depth = D3D12_DEPTH_STENCIL_DESC {
  177. DepthEnable: d.DepthEnable,
  178. DepthWriteMask: d.DepthWriteMask,
  179. DepthFunc: d.DepthFunc,
  180. StencilEnable: d.StencilEnable,
  181. StencilReadMask: d.StencilReadMask,
  182. StencilWriteMask: d.StencilWriteMask,
  183. FrontFace: d.FrontFace,
  184. BackFace: d.BackFace,
  185. };
  186. }
  187. 12 => {
  188. let layout = at.add(8).cast::<D3D12_INPUT_LAYOUT_DESC>().read_unaligned();
  189. if layout.pInputElementDescs.is_null() {
  190. return;
  191. }
  192. let elements = std::slice::from_raw_parts(
  193. layout.pInputElementDescs,
  194. layout.NumElements as usize,
  195. );
  196. self.names = elements
  197. .iter()
  198. .map(|e| CStr::from_ptr(e.SemanticName.0.cast()).to_owned())
  199. .collect();
  200. self.inputs = elements
  201. .iter()
  202. .zip(&self.names)
  203. .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC {
  204. SemanticName: PCSTR(name.as_ptr().cast()),
  205. Format: DXGI_FORMAT(
  206. crate::resource::pc_format(e.Format.0 as u32) as i32
  207. ),
  208. ..*e
  209. })
  210. .collect();
  211. }
  212. 13 => {
  213. self.strip_cut =
  214. D3D12_INDEX_BUFFER_STRIP_CUT_VALUE(data.cast::<i32>().read_unaligned())
  215. }
  216. 14 => {
  217. self.topology =
  218. D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::<i32>().read_unaligned())
  219. }
  220. 15 => {
  221. self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned();
  222. for f in &mut self.targets.RTFormats {
  223. f.0 = crate::resource::target_format(crate::resource::pc_format(
  224. f.0 as u32,
  225. )) as i32;
  226. }
  227. }
  228. 16 => {
  229. let f = data.cast::<u32>().read_unaligned();
  230. self.depth_format = DXGI_FORMAT(crate::resource::pc_format(f) as i32);
  231. }
  232. 17 => self.samples = data.cast::<DXGI_SAMPLE_DESC>().read_unaligned(),
  233. _ => {}
  234. }
  235. }
  236. }
  237. /// Everything the state holds, as text: part of a pipeline's name in
  238. /// the library and of the key a title pipeline is started early by.
  239. pub(crate) fn describe(&self) -> String {
  240. let inputs: Vec<String> = self
  241. .inputs
  242. .iter()
  243. .zip(&self.names)
  244. .map(|(e, name)| {
  245. format!(
  246. "{name:?} {} {} {} {} {} {}",
  247. e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate
  248. )
  249. })
  250. .collect();
  251. let bounds = if self.depth_bounds {
  252. " depth-bounds"
  253. } else {
  254. ""
  255. };
  256. format!(
  257. "{:?} {} {:?} {:?}{bounds} {inputs:?} {} {} {:?} {} {:?}",
  258. self.blend,
  259. self.sample_mask,
  260. self.rasterizer,
  261. self.depth,
  262. self.strip_cut.0,
  263. self.topology.0,
  264. self.targets,
  265. self.depth_format.0,
  266. self.samples
  267. )
  268. }
  269. fn depth1(&self) -> D3D12_DEPTH_STENCIL_DESC1 {
  270. let d = &self.depth;
  271. D3D12_DEPTH_STENCIL_DESC1 {
  272. DepthEnable: d.DepthEnable,
  273. DepthWriteMask: d.DepthWriteMask,
  274. DepthFunc: d.DepthFunc,
  275. StencilEnable: d.StencilEnable,
  276. StencilReadMask: d.StencilReadMask,
  277. StencilWriteMask: d.StencilWriteMask,
  278. FrontFace: d.FrontFace,
  279. BackFace: d.BackFace,
  280. DepthBoundsTestEnable: self.depth_bounds.into(),
  281. }
  282. }
  283. /// The vertex buffer slots the input layout reads.
  284. fn slots(&self) -> u32 {
  285. self.inputs
  286. .iter()
  287. .fold(0, |m, e| m | 1 << e.InputSlot.min(31))
  288. }
  289. /// The input elements with their byte offsets worked out.
  290. fn elements(&self) -> Vec<Input> {
  291. let mut next = [0u32; 32];
  292. self.inputs
  293. .iter()
  294. .map(|e| {
  295. let slot = e.InputSlot.min(31) as usize;
  296. let format = e.Format.0 as u32;
  297. let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32);
  298. // An appended element starts at the next multiple of
  299. // min(4, its size) after the previous one, where D3D12 (and
  300. // vkd3d) place it; the host pipeline gets the title's
  301. // descriptions, so the offsets read here must match.
  302. let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT {
  303. next[slot]
  304. .checked_next_multiple_of(bytes.clamp(1, 4))
  305. .unwrap_or(u32::MAX)
  306. } else {
  307. e.AlignedByteOffset
  308. };
  309. next[slot] = offset.saturating_add(bytes);
  310. Input {
  311. slot: slot as u32,
  312. offset,
  313. format,
  314. per_instance: e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA,
  315. }
  316. })
  317. .collect()
  318. }
  319. }
  320. /// One input element: vertex buffer slot, byte offset, format.
  321. #[derive(Debug, Clone, Copy)]
  322. pub(crate) struct Input {
  323. pub(crate) slot: u32,
  324. pub(crate) offset: u32,
  325. pub(crate) format: u32,
  326. pub(crate) per_instance: bool,
  327. }
  328. /// The console's own primitive topology types.
  329. const RECTANGLES: i32 = 19;
  330. const QUADS: i32 = 32;
  331. /// Whether the title's root SRVs are bound as one-view tables of the
  332. /// buffer's host copy, whose reads past its end return zeros, rather than
  333. /// as root descriptors, which have no size: a mesh shader's vertex fetch
  334. /// has no record limit, and a read past the copy reaches whatever the host
  335. /// placed after it (memory it has freed: the device is removed, upstream
  336. /// PR #493). `VICTORY_ROOT_SRV_DIRECT=1` goes back to root descriptors.
  337. pub(crate) fn bounded_root_srvs() -> bool {
  338. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  339. *ON.get_or_init(|| std::env::var_os("VICTORY_ROOT_SRV_DIRECT").is_none())
  340. }
  341. /// One stage of a host pipeline and where its bindings go.
  342. pub(crate) struct Stage {
  343. pub(crate) shader: Arc<Shader>,
  344. /// The root parameter of its user data, and its size in dwords.
  345. pub(crate) user_data: Option<(u32, u32)>,
  346. /// Root parameters of its root views: (title root parameter, ours).
  347. pub(crate) root_cbvs: Vec<(u8, u32)>,
  348. pub(crate) root_srvs: Vec<(u8, u32)>,
  349. /// Root UAVs: one-view tables like the SRVs (or root descriptors with
  350. /// `VICTORY_ROOT_SRV_DIRECT=1`).
  351. pub(crate) root_uavs: Vec<(u8, u32)>,
  352. }
  353. impl Stage {
  354. pub(crate) fn translated(&self) -> &Translated {
  355. self.shader
  356. .translated()
  357. .expect("host pipelines are made from translated shaders")
  358. }
  359. }
  360. pub(crate) struct HostPipeline {
  361. /// A compute pipeline (else graphics).
  362. pub(crate) compute: bool,
  363. /// A mesh pipeline (graphics without vertex input).
  364. pub(crate) mesh: bool,
  365. pub(crate) pso: ID3D12PipelineState,
  366. pub(crate) root: ID3D12RootSignature,
  367. /// Vertex, then pixel stage, or the compute stage.
  368. pub(crate) stages: Vec<Stage>,
  369. /// The vertex buffer slots it reads (bit per slot).
  370. pub(crate) slots: u32,
  371. pub(crate) inputs: Vec<Input>,
  372. /// Has the geometry stage that completes the console's rectangles
  373. /// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out
  374. /// as the title gives them, three vertices a rectangle.
  375. pub(crate) rects: bool,
  376. /// Its shaders, for reports of slow submissions.
  377. pub(crate) name: String,
  378. /// Its depth, stencil, cull and blend state in short, for the frame
  379. /// listing (empty for compute).
  380. #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
  381. pub(crate) state: String,
  382. }
  383. /// Logs a pipeline that gets no host pipeline, once per reason.
  384. fn refuse(reason: &'static str, shaders: &[Arc<Shader>]) -> Option<HostPipeline> {
  385. static SEEN: std::sync::Mutex<Vec<&str>> = std::sync::Mutex::new(Vec::new());
  386. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  387. if !seen.contains(&reason) {
  388. seen.push(reason);
  389. tracing::warn!(?shaders, "no host pipeline: {reason} (logged once)");
  390. }
  391. None
  392. }
  393. impl HostPipeline {
  394. /// A host pipeline for vertex and pixel shaders with the graphics
  395. /// state `g`, or for one compute shader.
  396. pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> {
  397. // For the report when the host device is removed: what this thread
  398. // has in the library from here on.
  399. super::library::label(format!("{shaders:?}"));
  400. let find = |stage| shaders.iter().find(|s| s.stage == stage);
  401. let compute = match shaders {
  402. [cs] if cs.stage == "compute" => Some(cs),
  403. _ => None,
  404. };
  405. if compute.is_none()
  406. && shaders
  407. .iter()
  408. .any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh"))
  409. {
  410. return refuse(
  411. "only vertex, mesh, pixel and compute stages are translated",
  412. shaders,
  413. );
  414. }
  415. let mesh = find("mesh");
  416. let stages = if let Some(cs) = compute {
  417. vec![(cs, D3D12_SHADER_VISIBILITY_ALL)]
  418. } else {
  419. let first = match (mesh, find("vertex")) {
  420. (Some(ms), _) => (ms, D3D12_SHADER_VISIBILITY_MESH),
  421. (None, Some(vs)) => (vs, D3D12_SHADER_VISIBILITY_VERTEX),
  422. (None, None) => return refuse("no vertex or mesh shader", shaders),
  423. };
  424. let mut stages = vec![first];
  425. stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL)));
  426. stages
  427. };
  428. if mesh.is_some() && !host()?.mesh_shaders() {
  429. return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders);
  430. }
  431. for (s, _) in &stages {
  432. s.translated()?;
  433. }
  434. let host = host()?;
  435. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default();
  436. // SAFETY: the feature query writes the structure of the given size.
  437. // Older runtimes may not recognize OPTIONS19; that means no support.
  438. let aniso_point_mip_supported = unsafe {
  439. host.device.CheckFeatureSupport(
  440. D3D12_FEATURE_D3D12_OPTIONS19,
  441. (&raw mut options).cast(),
  442. size_of_val(&options) as u32,
  443. )
  444. }
  445. .is_ok()
  446. && options.AnisoFilterWithPointMipSupported.as_bool();
  447. // The root signature the translated shaders' bindings define.
  448. let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
  449. // The ranges table parameters point at, alive until the root
  450. // signature is made.
  451. let mut ranges: Vec<Box<D3D12_DESCRIPTOR_RANGE1>> = Vec::new();
  452. let mut samplers = Vec::new();
  453. let mut bound = Vec::new();
  454. for &(shader, visibility) in &stages {
  455. let t = &shader.translated()?.host;
  456. let mut stage = Stage {
  457. shader: shader.clone(),
  458. user_data: None,
  459. root_cbvs: Vec::new(),
  460. root_srvs: Vec::new(),
  461. root_uavs: Vec::new(),
  462. };
  463. let dwords = t.user_data_dwords();
  464. if dwords > 0 {
  465. stage.user_data = Some((params.len() as u32, dwords));
  466. params.push(D3D12_ROOT_PARAMETER1 {
  467. ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
  468. Anonymous: D3D12_ROOT_PARAMETER1_0 {
  469. Constants: D3D12_ROOT_CONSTANTS {
  470. ShaderRegister: 0,
  471. RegisterSpace: USER_DATA_SPACE,
  472. Num32BitValues: dwords,
  473. },
  474. },
  475. ShaderVisibility: visibility,
  476. });
  477. }
  478. for (slots, kind, out) in [
  479. (
  480. &t.root_cbvs,
  481. D3D12_ROOT_PARAMETER_TYPE_CBV,
  482. &mut stage.root_cbvs,
  483. ),
  484. (
  485. &t.root_srvs,
  486. D3D12_ROOT_PARAMETER_TYPE_SRV,
  487. &mut stage.root_srvs,
  488. ),
  489. (
  490. &t.root_uavs,
  491. D3D12_ROOT_PARAMETER_TYPE_UAV,
  492. &mut stage.root_uavs,
  493. ),
  494. ] {
  495. for &slot in slots {
  496. let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV;
  497. // Ours, not the title's, stay root descriptors: the
  498. // table of strides, the directory of title memory by
  499. // address and its fault notes.
  500. let ours = if uav {
  501. slot == victory_shader::emit::SLOT_FAULTS
  502. } else {
  503. slot == victory_shader::emit::SLOT_STRIDES
  504. || slot == victory_shader::emit::SLOT_MEMORY
  505. };
  506. if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
  507. // A one-view table: the view's size bounds the
  508. // reads (and a root UAV's writes), which a root
  509. // descriptor leaves unbounded.
  510. // (Our own table of strides stays a descriptor.)
  511. ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 {
  512. RangeType: if uav {
  513. D3D12_DESCRIPTOR_RANGE_TYPE_UAV
  514. } else {
  515. D3D12_DESCRIPTOR_RANGE_TYPE_SRV
  516. },
  517. NumDescriptors: 1,
  518. BaseShaderRegister: u32::from(slot),
  519. RegisterSpace: ROOT_CBV_SPACE,
  520. Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE
  521. | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE,
  522. OffsetInDescriptorsFromTableStart: 0,
  523. }));
  524. let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?;
  525. out.push((slot, params.len() as u32));
  526. params.push(D3D12_ROOT_PARAMETER1 {
  527. ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
  528. Anonymous: D3D12_ROOT_PARAMETER1_0 {
  529. DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 {
  530. NumDescriptorRanges: 1,
  531. pDescriptorRanges: range,
  532. },
  533. },
  534. ShaderVisibility: visibility,
  535. });
  536. continue;
  537. }
  538. out.push((slot, params.len() as u32));
  539. params.push(D3D12_ROOT_PARAMETER1 {
  540. ParameterType: kind,
  541. Anonymous: D3D12_ROOT_PARAMETER1_0 {
  542. Descriptor: D3D12_ROOT_DESCRIPTOR1 {
  543. ShaderRegister: u32::from(slot),
  544. RegisterSpace: ROOT_CBV_SPACE,
  545. Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE,
  546. },
  547. },
  548. ShaderVisibility: visibility,
  549. });
  550. }
  551. }
  552. for (n, s) in t.static_samplers.iter().enumerate() {
  553. samplers.push(D3D12_STATIC_SAMPLER_DESC {
  554. Filter: D3D12_FILTER(s.filter_for_host(aniso_point_mip_supported) as i32),
  555. AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32),
  556. AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32),
  557. AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32),
  558. MipLODBias: s.mip_lod_bias,
  559. MaxAnisotropy: s.max_anisotropy,
  560. ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32),
  561. BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32),
  562. MinLOD: s.min_lod,
  563. MaxLOD: s.max_lod,
  564. ShaderRegister: n as u32,
  565. RegisterSpace: SAMPLER_SPACE,
  566. ShaderVisibility: visibility,
  567. });
  568. }
  569. bound.push(stage);
  570. }
  571. let (root, root_blob) = match root_signature(&host.device, &params, &samplers, compute.is_some()) {
  572. Ok(root) => root,
  573. Err(e) => {
  574. tracing::warn!(error = %e, ?shaders, "host root signature refused");
  575. return None;
  576. }
  577. };
  578. let code = |i: usize| {
  579. stages.get(i).and_then(|(s, _)| s.translated()).map_or(
  580. D3D12_SHADER_BYTECODE::default(),
  581. |t| D3D12_SHADER_BYTECODE {
  582. pShaderBytecode: t.host.dxil.as_ptr().cast(),
  583. BytecodeLength: t.host.dxil.len(),
  584. },
  585. )
  586. };
  587. if compute.is_some() {
  588. let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
  589. // SAFETY: a borrowed pointer the description never releases.
  590. pRootSignature: unsafe { std::mem::transmute_copy(&root) },
  591. CS: code(0),
  592. ..Default::default()
  593. };
  594. let name = super::library::name("compute", &root_blob, &[&code_bytes(&code(0))], "");
  595. let made = super::library::pipeline(
  596. &name,
  597. // SAFETY: the description points at live data.
  598. |library, name| unsafe { library.LoadComputePipeline(name, &desc) },
  599. // SAFETY: as above.
  600. || unsafe { host.device.CreateComputePipelineState(&desc) },
  601. );
  602. let pso = match made {
  603. Ok(pso) => pso,
  604. Err(e) => {
  605. tracing::warn!(error = %e, ?shaders, "host pipeline refused");
  606. host.log_messages();
  607. return None;
  608. }
  609. };
  610. tracing::info!(?shaders, "host pipeline");
  611. crate::host::name(&pso, || format!("{shaders:?}"));
  612. return Some(HostPipeline {
  613. compute: true,
  614. mesh: false,
  615. pso,
  616. root,
  617. stages: bound,
  618. name: format!("{shaders:?}"),
  619. slots: 0,
  620. inputs: Vec::new(),
  621. rects: false,
  622. state: String::new(),
  623. });
  624. }
  625. let Some(g) = g else {
  626. return refuse("graphics state not kept (plain description)", shaders);
  627. };
  628. let depth_bounds = if g.depth_bounds {
  629. if host.depth_bounds() {
  630. true
  631. } else {
  632. static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  633. if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
  634. tracing::warn!(
  635. "a pipeline enables the depth bounds test, which the host GPU does not support: its draws pass at every depth"
  636. );
  637. }
  638. false
  639. }
  640. } else {
  641. false
  642. };
  643. let state = g.describe();
  644. if mesh.is_some() {
  645. // "triangles": the stream names its topology since it did not
  646. // load from the library without one (see `mesh_pipeline`); a
  647. // new name keeps such entries, stored before, from being
  648. // looked up again.
  649. let name = super::library::name(
  650. "mesh triangles",
  651. &root_blob,
  652. &[&code_bytes(&code(0)), &code_bytes(&code(1))],
  653. &state,
  654. );
  655. let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, depth_bounds, &name) {
  656. Ok(pso) => pso,
  657. Err(e) => {
  658. tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused");
  659. host.log_messages();
  660. return None;
  661. }
  662. };
  663. tracing::info!(?shaders, "host mesh pipeline");
  664. crate::host::name(&pso, || format!("{shaders:?}"));
  665. return Some(HostPipeline {
  666. compute: false,
  667. mesh: true,
  668. pso,
  669. root,
  670. stages: bound,
  671. name: format!("{shaders:?}"),
  672. slots: 0,
  673. inputs: Vec::new(),
  674. rects: false,
  675. state: String::new(),
  676. });
  677. }
  678. // A pipeline the title makes for rectangles gets a geometry stage
  679. // that completes each one from the three vertices the vertex
  680. // shader made. Without it (refused here or by the host) the draws
  681. // fall back on what `draw` does for rectangles.
  682. let mut rect_gs = None;
  683. if g.topology.0 == RECTANGLES {
  684. let ps = stages.get(1).and_then(|(s, _)| s.translated());
  685. let vs = &stages[0].0.translated()?.host.dxil;
  686. match victory_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) {
  687. Ok(gs) => rect_gs = Some(gs),
  688. Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"),
  689. }
  690. }
  691. let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  692. // SAFETY: a borrowed pointer the description never releases.
  693. pRootSignature: unsafe { std::mem::transmute_copy(&root) },
  694. VS: code(0),
  695. PS: code(1),
  696. GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| {
  697. D3D12_SHADER_BYTECODE {
  698. pShaderBytecode: gs.as_ptr().cast(),
  699. BytecodeLength: gs.len(),
  700. }
  701. }),
  702. BlendState: host_blend(&g.blend, &g.targets),
  703. SampleMask: g.sample_mask,
  704. RasterizerState: g.rasterizer,
  705. DepthStencilState: g.depth,
  706. InputLayout: D3D12_INPUT_LAYOUT_DESC {
  707. pInputElementDescs: g.inputs.as_ptr(),
  708. NumElements: g.inputs.len() as u32,
  709. },
  710. IBStripCutValue: g.strip_cut,
  711. // The console's rectangle and quad types draw as triangles on
  712. // the host (see `draw`).
  713. PrimitiveTopologyType: match g.topology.0 {
  714. RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  715. _ => g.topology,
  716. },
  717. NumRenderTargets: g.targets.NumRenderTargets,
  718. RTVFormats: g.targets.RTFormats,
  719. DSVFormat: g.depth_format,
  720. SampleDesc: g.samples,
  721. ..Default::default()
  722. };
  723. // A pipeline with the geometry stage has a name of its own in the
  724. // library; the others keep theirs.
  725. let name = |gs: Option<&Vec<u8>>| match gs {
  726. Some(gs) => super::library::name(
  727. "graphics rectangles",
  728. &root_blob,
  729. &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]],
  730. &state,
  731. ),
  732. None => super::library::name(
  733. "graphics",
  734. &root_blob,
  735. &[&code_bytes(&code(0)), &code_bytes(&code(1))],
  736. &state,
  737. ),
  738. };
  739. let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| {
  740. if depth_bounds {
  741. return graphics_depth_bounds_pipeline(&host.device, &root, desc, g.depth1(), name);
  742. }
  743. super::library::pipeline(
  744. name,
  745. // SAFETY: the description points at live data.
  746. |library, name| unsafe { library.LoadGraphicsPipeline(name, desc) },
  747. // SAFETY: as above.
  748. || unsafe { host.device.CreateGraphicsPipelineState(desc) },
  749. )
  750. };
  751. let mut made = make(&desc, &name(rect_gs.as_ref()));
  752. if made.is_err() && rect_gs.is_some() {
  753. // The host refused the geometry stage: once more without it.
  754. tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage");
  755. host.log_messages();
  756. desc.GS = D3D12_SHADER_BYTECODE::default();
  757. rect_gs = None;
  758. made = make(&desc, &name(None));
  759. }
  760. let pso = match made {
  761. Ok(pso) => pso,
  762. Err(e) => {
  763. tracing::warn!(error = %e, ?shaders, "host pipeline refused");
  764. host.log_messages();
  765. return None;
  766. }
  767. };
  768. tracing::info!(?shaders, "host pipeline");
  769. crate::host::name(&pso, || format!("{shaders:?}"));
  770. tracing::debug!(
  771. ?shaders,
  772. depth = ?g.depth,
  773. depth_bounds,
  774. dsv = g.depth_format.0,
  775. targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize],
  776. blend = ?g.blend.RenderTarget[0],
  777. cull = g.rasterizer.CullMode.0,
  778. "host graphics state"
  779. );
  780. Some(HostPipeline {
  781. compute: false,
  782. mesh: false,
  783. pso,
  784. root,
  785. stages: bound,
  786. name: format!("{shaders:?}"),
  787. slots: g.slots(),
  788. inputs: g.elements(),
  789. rects: rect_gs.is_some(),
  790. state: {
  791. let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]);
  792. let face = |f: &D3D12_DEPTH_STENCILOP_DESC| {
  793. format!(
  794. "fail {} depth-fail {} pass {} func {}",
  795. f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0
  796. )
  797. };
  798. let bounds = if depth_bounds { " bounds true" } else { "" };
  799. format!(
  800. "depth {} write {} func {}{bounds}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}",
  801. d.DepthEnable.as_bool(),
  802. d.DepthWriteMask.0,
  803. d.DepthFunc.0,
  804. d.StencilEnable.as_bool(),
  805. d.StencilReadMask,
  806. d.StencilWriteMask,
  807. face(&d.FrontFace),
  808. face(&d.BackFace),
  809. r.CullMode.0,
  810. r.FrontCounterClockwise.as_bool(),
  811. b.BlendEnable.as_bool(),
  812. b.SrcBlend.0,
  813. b.DestBlend.0,
  814. b.BlendOp.0,
  815. b.RenderTargetWriteMask
  816. )
  817. },
  818. })
  819. }
  820. }
  821. /// A stream subobject: its type, then its description, pointer-aligned.
  822. #[repr(C, align(8))]
  823. struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T);
  824. fn stream_pipeline<S>(
  825. device: &ID3D12Device,
  826. stream: &mut S,
  827. name: &str,
  828. ) -> windows::core::Result<ID3D12PipelineState> {
  829. use windows::core::Interface;
  830. let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
  831. SizeInBytes: size_of::<S>(),
  832. pPipelineStateSubobjectStream: std::ptr::from_mut(stream).cast(),
  833. };
  834. let device = device.cast::<ID3D12Device2>()?;
  835. super::library::pipeline(
  836. name,
  837. // SAFETY: the stream holds whole subobjects pointing at live data.
  838. |library, name| unsafe { library.LoadPipeline(name, &desc) },
  839. // SAFETY: as above.
  840. || unsafe { device.CreatePipelineState(&desc) },
  841. )
  842. }
  843. /// A graphics pipeline enabling the depth bounds test: `D3D12_GRAPHICS_PIPELINE_STATE_DESC`
  844. /// has no field for `DepthBoundsTestEnable`, so it is created and loaded as a
  845. /// pipeline-state stream with `DEPTH_STENCIL1`.
  846. fn graphics_depth_bounds_pipeline(
  847. device: &ID3D12Device,
  848. root: &ID3D12RootSignature,
  849. d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC,
  850. depth: D3D12_DEPTH_STENCIL_DESC1,
  851. name: &str,
  852. ) -> windows::core::Result<ID3D12PipelineState> {
  853. use windows::core::Interface;
  854. #[repr(C)]
  855. struct Stream {
  856. root: Sub<*mut std::ffi::c_void>,
  857. vs: Sub<D3D12_SHADER_BYTECODE>,
  858. ps: Sub<D3D12_SHADER_BYTECODE>,
  859. blend: Sub<D3D12_BLEND_DESC>,
  860. mask: Sub<u32>,
  861. raster: Sub<D3D12_RASTERIZER_DESC>,
  862. depth: Sub<D3D12_DEPTH_STENCIL_DESC1>,
  863. input: Sub<D3D12_INPUT_LAYOUT_DESC>,
  864. strip_cut: Sub<D3D12_INDEX_BUFFER_STRIP_CUT_VALUE>,
  865. topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>,
  866. targets: Sub<D3D12_RT_FORMAT_ARRAY>,
  867. dsv: Sub<DXGI_FORMAT>,
  868. samples: Sub<DXGI_SAMPLE_DESC>,
  869. }
  870. #[repr(C)]
  871. struct StreamGs {
  872. base: Stream,
  873. gs: Sub<D3D12_SHADER_BYTECODE>,
  874. }
  875. let targets = D3D12_RT_FORMAT_ARRAY {
  876. RTFormats: d.RTVFormats,
  877. NumRenderTargets: d.NumRenderTargets,
  878. };
  879. let base = Stream {
  880. root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
  881. vs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, d.VS),
  882. ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, d.PS),
  883. blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, d.BlendState),
  884. mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, d.SampleMask),
  885. raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, d.RasterizerState),
  886. depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, depth),
  887. input: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, d.InputLayout),
  888. strip_cut: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, d.IBStripCutValue),
  889. topology: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, d.PrimitiveTopologyType),
  890. targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, targets),
  891. dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, d.DSVFormat),
  892. samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, d.SampleDesc),
  893. };
  894. if d.GS.pShaderBytecode.is_null() {
  895. let mut stream = base;
  896. stream_pipeline(device, &mut stream, name)
  897. } else {
  898. let mut stream = StreamGs {
  899. base,
  900. gs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, d.GS),
  901. };
  902. stream_pipeline(device, &mut stream, name)
  903. }
  904. }
  905. /// A mesh pipeline from the title's graphics state: the pipeline-state
  906. /// stream form (no input layout).
  907. ///
  908. /// The stream names a triangle topology, which D3D12 does not need for a
  909. /// mesh shader: without it the pipeline library refuses to load a stored
  910. /// pipeline with the very stream it was made from (`E_INVALIDARG`; debug
  911. /// layer message 972, "does not match the one used to create the PSO"), so
  912. /// every mesh pipeline was compiled again, and its store then refused (970,
  913. /// "already exists"). The translation makes triangle mesh shaders only
  914. /// (`mesh_prologue` refuses others), and the debug layer wants the two to
  915. /// agree (1323).
  916. fn mesh_pipeline(
  917. device: &ID3D12Device,
  918. root: &ID3D12RootSignature,
  919. ms: D3D12_SHADER_BYTECODE,
  920. ps: D3D12_SHADER_BYTECODE,
  921. g: &GraphicsState,
  922. depth_bounds: bool,
  923. name: &str,
  924. ) -> windows::core::Result<ID3D12PipelineState> {
  925. use windows::core::Interface;
  926. #[repr(C)]
  927. struct Stream<D> {
  928. root: Sub<*mut std::ffi::c_void>,
  929. ms: Sub<D3D12_SHADER_BYTECODE>,
  930. ps: Sub<D3D12_SHADER_BYTECODE>,
  931. blend: Sub<D3D12_BLEND_DESC>,
  932. mask: Sub<u32>,
  933. raster: Sub<D3D12_RASTERIZER_DESC>,
  934. depth: Sub<D>,
  935. targets: Sub<D3D12_RT_FORMAT_ARRAY>,
  936. dsv: Sub<DXGI_FORMAT>,
  937. samples: Sub<DXGI_SAMPLE_DESC>,
  938. topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>,
  939. }
  940. let build = |depth: Sub<_>| {
  941. let mut stream = Stream {
  942. root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
  943. ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms),
  944. ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps),
  945. blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, host_blend(&g.blend, &g.targets)),
  946. mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask),
  947. raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer),
  948. depth,
  949. targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
  950. dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
  951. samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
  952. topology: Sub(
  953. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY,
  954. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  955. ),
  956. };
  957. stream_pipeline(device, &mut stream, name)
  958. };
  959. if depth_bounds {
  960. let mut stream = Stream {
  961. root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
  962. ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms),
  963. ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps),
  964. blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, host_blend(&g.blend, &g.targets)),
  965. mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask),
  966. raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer),
  967. depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()),
  968. targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
  969. dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
  970. samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
  971. topology: Sub(
  972. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY,
  973. D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  974. ),
  975. };
  976. stream_pipeline(device, &mut stream, name)
  977. } else {
  978. build(Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth))
  979. }
  980. }
  981. /// The bytes of shader code (none for an absent stage).
  982. fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec<u8> {
  983. if code.pShaderBytecode.is_null() {
  984. return Vec::new();
  985. }
  986. // SAFETY: a translation's own bytes, alive while its shader is.
  987. unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::<u8>(), code.BytecodeLength) }.to_vec()
  988. }
  989. fn root_signature(
  990. device: &ID3D12Device,
  991. params: &[D3D12_ROOT_PARAMETER1],
  992. samplers: &[D3D12_STATIC_SAMPLER_DESC],
  993. compute: bool,
  994. ) -> windows::core::Result<(ID3D12RootSignature, Vec<u8>)> {
  995. let input = if compute {
  996. D3D12_ROOT_SIGNATURE_FLAG_NONE
  997. } else {
  998. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT
  999. };
  1000. let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC {
  1001. Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1,
  1002. Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 {
  1003. Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 {
  1004. NumParameters: params.len() as u32,
  1005. pParameters: params.as_ptr(),
  1006. NumStaticSamplers: samplers.len() as u32,
  1007. pStaticSamplers: samplers.as_ptr(),
  1008. Flags: input
  1009. | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED
  1010. | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED,
  1011. },
  1012. },
  1013. };
  1014. // SAFETY: the description points at live arrays; the blob is read in
  1015. // full before it is released.
  1016. unsafe {
  1017. let mut blob: Option<ID3DBlob> = None;
  1018. let mut error: Option<ID3DBlob> = None;
  1019. if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) {
  1020. if let Some(error) = error {
  1021. let text = std::slice::from_raw_parts(
  1022. error.GetBufferPointer().cast::<u8>(),
  1023. error.GetBufferSize(),
  1024. );
  1025. tracing::warn!("root signature: {}", String::from_utf8_lossy(text));
  1026. }
  1027. return Err(e);
  1028. }
  1029. let blob = blob.ok_or_else(windows::core::Error::empty)?;
  1030. let bytes =
  1031. std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
  1032. Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec()))
  1033. }
  1034. }
  1035. #[cfg(test)]
  1036. mod tests {
  1037. use std::path::{Path, PathBuf};
  1038. use std::sync::atomic::Ordering;
  1039. use super::*;
  1040. /// A triangle mesh shader of our own and a pixel shader for it.
  1041. const MS: &str = "struct V { float4 p : SV_Position; };
  1042. [outputtopology(\"triangle\")] [numthreads(1, 1, 1)]
  1043. void main(out vertices V v[3], out indices uint3 t[1]) {
  1044. SetMeshOutputCounts(3, 1);
  1045. v[0].p = float4(0, 0, 0, 1);
  1046. v[1].p = float4(1, 0, 0, 1);
  1047. v[2].p = float4(0, 1, 0, 1);
  1048. t[0] = uint3(0, 1, 2);
  1049. }";
  1050. const PS: &str = "float4 main() : SV_Target { return 1; }";
  1051. /// The PC `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's).
  1052. fn dxc() -> Option<PathBuf> {
  1053. let dxc = match std::env::var_os("VICTORY_PC_DXC") {
  1054. Some(p) => PathBuf::from(p),
  1055. None => victory_shader::emit::validator::Validator::default_path()?
  1056. .with_file_name("dxc.exe"),
  1057. };
  1058. dxc.exists().then_some(dxc)
  1059. }
  1060. fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec<u8> {
  1061. let (hlsl, out) = (
  1062. dir.join(format!("{profile}.hlsl")),
  1063. dir.join(format!("{profile}.dxil")),
  1064. );
  1065. std::fs::write(&hlsl, src).unwrap();
  1066. let status = std::process::Command::new(dxc)
  1067. .args(["-nologo", "-T", profile, "-E", "main", "-Fo"])
  1068. .arg(&out)
  1069. .arg(&hlsl)
  1070. .status()
  1071. .unwrap();
  1072. assert!(status.success(), "dxc failed for {profile}");
  1073. std::fs::read(out).unwrap()
  1074. }
  1075. fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
  1076. D3D12_SHADER_BYTECODE {
  1077. pShaderBytecode: bytes.as_ptr().cast(),
  1078. BytecodeLength: bytes.len(),
  1079. }
  1080. }
  1081. /// A mesh pipeline made once is loaded from the library the next time,
  1082. /// not compiled again (a stream without a topology never loads).
  1083. #[test]
  1084. fn a_mesh_pipeline_loads_from_the_library() {
  1085. let Some(host) = host() else {
  1086. return; // no host GPU here
  1087. };
  1088. if !host.mesh_shaders() {
  1089. eprintln!("no host mesh shader support; skipped");
  1090. return;
  1091. }
  1092. let Some(dxc) = dxc() else {
  1093. eprintln!("no PC dxc.exe; skipped");
  1094. return;
  1095. };
  1096. let dir = tempfile::tempdir().unwrap();
  1097. let ms = compile(&dxc, dir.path(), MS, "ms_6_5");
  1098. let ps = compile(&dxc, dir.path(), PS, "ps_6_5");
  1099. let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap();
  1100. let mut g = GraphicsState::default();
  1101. // This pipeline has only a color target, with no depth buffer.
  1102. g.depth.DepthEnable = false.into();
  1103. g.targets.NumRenderTargets = 1;
  1104. g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  1105. let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe());
  1106. mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made");
  1107. let loaded = super::super::library::LOADED.load(Ordering::Relaxed);
  1108. mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made again");
  1109. assert!(
  1110. super::super::library::LOADED.load(Ordering::Relaxed) > loaded,
  1111. "the mesh pipeline was compiled again instead of loaded from the library"
  1112. );
  1113. }
  1114. fn targets(formats: &[DXGI_FORMAT]) -> D3D12_RT_FORMAT_ARRAY {
  1115. let mut t = D3D12_RT_FORMAT_ARRAY {
  1116. NumRenderTargets: formats.len() as u32,
  1117. ..Default::default()
  1118. };
  1119. t.RTFormats[..formats.len()].copy_from_slice(formats);
  1120. t
  1121. }
  1122. fn blending(independent: bool) -> D3D12_BLEND_DESC {
  1123. let mut b = GraphicsState::default().blend;
  1124. b.IndependentBlendEnable = independent.into();
  1125. for t in &mut b.RenderTarget {
  1126. t.BlendEnable = true.into();
  1127. t.SrcBlend = D3D12_BLEND_SRC_ALPHA;
  1128. t.DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
  1129. }
  1130. b
  1131. }
  1132. #[test]
  1133. fn integer_targets_do_not_blend() {
  1134. let t = targets(&[
  1135. DXGI_FORMAT_R8G8B8A8_UNORM,
  1136. DXGI_FORMAT_R16G16B16A16_FLOAT,
  1137. DXGI_FORMAT_R8_UINT,
  1138. ]);
  1139. for independent in [false, true] {
  1140. let host = host_blend(&blending(independent), &t);
  1141. assert!(host.IndependentBlendEnable.as_bool());
  1142. assert!(host.RenderTarget[0].BlendEnable.as_bool());
  1143. assert!(host.RenderTarget[1].BlendEnable.as_bool());
  1144. assert!(!host.RenderTarget[2].BlendEnable.as_bool());
  1145. // The rest of the target's state is the title's.
  1146. assert_eq!(host.RenderTarget[2].SrcBlend, D3D12_BLEND_SRC_ALPHA);
  1147. assert_eq!(host.RenderTarget[0].DestBlend, D3D12_BLEND_INV_SRC_ALPHA);
  1148. }
  1149. }
  1150. #[test]
  1151. fn blend_states_without_integer_blending_are_kept() {
  1152. // No integer target.
  1153. let b = blending(false);
  1154. let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R11G11B10_FLOAT]);
  1155. assert_eq!(host_blend(&b, &t), b);
  1156. // An integer target that does not blend.
  1157. let mut b = blending(true);
  1158. b.RenderTarget[1].BlendEnable = false.into();
  1159. let t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT]);
  1160. assert_eq!(host_blend(&b, &t), b);
  1161. // Integer formats past the targets in use.
  1162. let mut t = targets(&[DXGI_FORMAT_R8G8B8A8_UNORM]);
  1163. t.RTFormats[1] = DXGI_FORMAT_R8_UINT;
  1164. assert_eq!(host_blend(&blending(false), &t), blending(false));
  1165. }
  1166. const VS: &str = "float4 main(uint i : SV_VertexID) : SV_Position {
  1167. float2 p = float2((i << 1) & 2, i & 2);
  1168. return float4(p * 2.0 - 1.0, 0.5, 1.0);
  1169. }";
  1170. /// A graphics pipeline with `DepthBoundsTestEnable` loads back from the
  1171. /// pipeline library and culls or passes fragments according to
  1172. /// `OMSetDepthBounds` (including across a command-list cut).
  1173. #[test]
  1174. fn depth_bounds_pipeline_loads_and_filters_draws() {
  1175. let Some(host) = host() else {
  1176. return;
  1177. };
  1178. if !host.depth_bounds() {
  1179. eprintln!("no host depth bounds support; skipped");
  1180. return;
  1181. }
  1182. let Some(dxc) = dxc() else {
  1183. eprintln!("no PC dxc.exe; skipped");
  1184. return;
  1185. };
  1186. let dir = tempfile::tempdir().unwrap();
  1187. let vs = compile(&dxc, dir.path(), VS, "vs_6_5");
  1188. let ps = compile(&dxc, dir.path(), PS, "ps_6_5");
  1189. let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap();
  1190. let mut g = GraphicsState::default();
  1191. // Subobject 21 (`DEPTH_STENCIL1`) with `DepthBoundsTestEnable = true`,
  1192. // depth test itself off so only depth bounds gates the draw.
  1193. #[repr(C, align(8))]
  1194. struct Sub21(u32, D3D12_DEPTH_STENCIL_DESC1);
  1195. let sub = Sub21(
  1196. 21,
  1197. D3D12_DEPTH_STENCIL_DESC1 {
  1198. DepthEnable: false.into(),
  1199. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
  1200. DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS,
  1201. DepthBoundsTestEnable: true.into(),
  1202. ..Default::default()
  1203. },
  1204. );
  1205. // SAFETY: `sub` is a complete subobject 21.
  1206. unsafe { g.read(21, (&raw const sub).cast()) };
  1207. assert!(g.depth_bounds);
  1208. assert!(g.describe().contains("depth-bounds"));
  1209. g.rasterizer.CullMode = D3D12_CULL_MODE_NONE;
  1210. g.targets.NumRenderTargets = 1;
  1211. g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  1212. g.depth_format = DXGI_FORMAT_D32_FLOAT;
  1213. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  1214. // SAFETY: borrowed pointer, never released by the descriptor.
  1215. pRootSignature: unsafe { std::mem::transmute_copy(&root) },
  1216. VS: code(&vs),
  1217. PS: code(&ps),
  1218. BlendState: g.blend,
  1219. SampleMask: g.sample_mask,
  1220. RasterizerState: g.rasterizer,
  1221. DepthStencilState: g.depth,
  1222. IBStripCutValue: g.strip_cut,
  1223. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  1224. NumRenderTargets: 1,
  1225. RTVFormats: g.targets.RTFormats,
  1226. DSVFormat: g.depth_format,
  1227. SampleDesc: g.samples,
  1228. ..Default::default()
  1229. };
  1230. let name = super::super::library::name(
  1231. "graphics depth-bounds test",
  1232. &root_blob,
  1233. &[&vs, &ps],
  1234. &g.describe(),
  1235. );
  1236. let pso = graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name)
  1237. .expect("depth-bounds PSO made");
  1238. let loaded = super::super::library::LOADED.load(Ordering::Relaxed);
  1239. graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name)
  1240. .expect("depth-bounds PSO made again");
  1241. assert!(
  1242. super::super::library::LOADED.load(Ordering::Relaxed) > loaded,
  1243. "the depth-bounds pipeline was compiled again instead of loaded from the library"
  1244. );
  1245. // Execute two draws against a depth buffer cleared to 0.5:
  1246. // 1) bounds [0.6, 1.0] -> rejected (target stays 0)
  1247. // 2) bounds [0.4, 0.6] replayed onto a fresh HostList -> passes (target becomes 255)
  1248. let make_tex = |format, flags, state, clear: D3D12_CLEAR_VALUE| {
  1249. let heap = D3D12_HEAP_PROPERTIES {
  1250. Type: D3D12_HEAP_TYPE_DEFAULT,
  1251. ..Default::default()
  1252. };
  1253. let rd = D3D12_RESOURCE_DESC {
  1254. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  1255. Width: 4,
  1256. Height: 4,
  1257. DepthOrArraySize: 1,
  1258. MipLevels: 1,
  1259. Format: format,
  1260. SampleDesc: DXGI_SAMPLE_DESC {
  1261. Count: 1,
  1262. Quality: 0,
  1263. },
  1264. Flags: flags,
  1265. ..Default::default()
  1266. };
  1267. let mut out: Option<ID3D12Resource> = None;
  1268. // SAFETY: valid heap and resource descriptions.
  1269. unsafe {
  1270. host.device
  1271. .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rd, state, Some(&clear), &mut out)
  1272. .unwrap();
  1273. }
  1274. out.unwrap()
  1275. };
  1276. let color = make_tex(
  1277. DXGI_FORMAT_R8G8B8A8_UNORM,
  1278. D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
  1279. D3D12_RESOURCE_STATE_RENDER_TARGET,
  1280. D3D12_CLEAR_VALUE {
  1281. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  1282. Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] },
  1283. },
  1284. );
  1285. let depth = make_tex(
  1286. DXGI_FORMAT_D32_FLOAT,
  1287. D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL,
  1288. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  1289. D3D12_CLEAR_VALUE {
  1290. Format: DXGI_FORMAT_D32_FLOAT,
  1291. Anonymous: D3D12_CLEAR_VALUE_0 {
  1292. DepthStencil: D3D12_DEPTH_STENCIL_VALUE {
  1293. Depth: 0.5,
  1294. Stencil: 0,
  1295. },
  1296. },
  1297. },
  1298. );
  1299. let readback = {
  1300. let heap = D3D12_HEAP_PROPERTIES {
  1301. Type: D3D12_HEAP_TYPE_READBACK,
  1302. ..Default::default()
  1303. };
  1304. let rd = D3D12_RESOURCE_DESC {
  1305. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1306. Width: 1024,
  1307. Height: 1,
  1308. DepthOrArraySize: 1,
  1309. MipLevels: 1,
  1310. SampleDesc: DXGI_SAMPLE_DESC {
  1311. Count: 1,
  1312. Quality: 0,
  1313. },
  1314. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1315. ..Default::default()
  1316. };
  1317. let mut out: Option<ID3D12Resource> = None;
  1318. // SAFETY: valid readback buffer description.
  1319. unsafe {
  1320. host.device
  1321. .CreateCommittedResource(
  1322. &heap,
  1323. D3D12_HEAP_FLAG_NONE,
  1324. &rd,
  1325. D3D12_RESOURCE_STATE_COPY_DEST,
  1326. None,
  1327. &mut out,
  1328. )
  1329. .unwrap();
  1330. }
  1331. out.unwrap()
  1332. };
  1333. let run_draw = |min: f32, max: f32| -> u8 {
  1334. let mut state = crate::draw::State::default();
  1335. let first_list = host.new_list().unwrap();
  1336. state.set_depth_bounds(&first_list, min, max);
  1337. first_list.close();
  1338. // Replay onto a second host list, exercising `State::replay`.
  1339. let list = host.new_list().unwrap();
  1340. state.replay(&list);
  1341. let rtv = host.rtv(Some(&color), None);
  1342. let dsv = host.dsv(&depth, None);
  1343. let vp = D3D12_VIEWPORT {
  1344. TopLeftX: 0.0,
  1345. TopLeftY: 0.0,
  1346. Width: 4.0,
  1347. Height: 4.0,
  1348. MinDepth: 0.0,
  1349. MaxDepth: 1.0,
  1350. };
  1351. let rect = windows::Win32::Foundation::RECT {
  1352. left: 0,
  1353. top: 0,
  1354. right: 4,
  1355. bottom: 4,
  1356. };
  1357. // SAFETY: open command list, live resources and views.
  1358. unsafe {
  1359. list.list.ClearRenderTargetView(rtv, &[0.0; 4], None);
  1360. list.list.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 0.5, 0, None);
  1361. list.list.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv));
  1362. list.list.RSSetViewports(&[vp]);
  1363. list.list.RSSetScissorRects(&[rect]);
  1364. list.list.SetGraphicsRootSignature(&root);
  1365. list.list.SetPipelineState(&pso);
  1366. list.list
  1367. .IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  1368. list.list.DrawInstanced(3, 1, 0, 0);
  1369. list.list.ResourceBarrier(&[crate::host::transition(
  1370. &color,
  1371. D3D12_RESOURCE_STATE_RENDER_TARGET,
  1372. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1373. )]);
  1374. let dst = D3D12_TEXTURE_COPY_LOCATION {
  1375. pResource: std::mem::transmute_copy(&readback),
  1376. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  1377. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  1378. PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  1379. Offset: 0,
  1380. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  1381. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  1382. Width: 4,
  1383. Height: 4,
  1384. Depth: 1,
  1385. RowPitch: 256,
  1386. },
  1387. },
  1388. },
  1389. };
  1390. let src = D3D12_TEXTURE_COPY_LOCATION {
  1391. pResource: std::mem::transmute_copy(&color),
  1392. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  1393. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
  1394. };
  1395. list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
  1396. list.list.ResourceBarrier(&[crate::host::transition(
  1397. &color,
  1398. D3D12_RESOURCE_STATE_COPY_SOURCE,
  1399. D3D12_RESOURCE_STATE_RENDER_TARGET,
  1400. )]);
  1401. }
  1402. list.close();
  1403. host.execute(&[&list]);
  1404. let mut ptr = std::ptr::null_mut();
  1405. // SAFETY: `execute` waited for the GPU; readback holds 1024 bytes.
  1406. unsafe {
  1407. readback.Map(0, None, Some(&mut ptr)).unwrap();
  1408. let pixel = *ptr.cast::<u8>();
  1409. readback.Unmap(0, None);
  1410. pixel
  1411. }
  1412. };
  1413. assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected");
  1414. assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass");
  1415. }
  1416. fn element(format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC {
  1417. D3D12_INPUT_ELEMENT_DESC {
  1418. SemanticName: PCSTR(c"TEXCOORD".as_ptr().cast()),
  1419. SemanticIndex: 0,
  1420. Format: format,
  1421. InputSlot: 0,
  1422. AlignedByteOffset: offset,
  1423. InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
  1424. InstanceDataStepRate: 0,
  1425. }
  1426. }
  1427. fn offsets(inputs: &[D3D12_INPUT_ELEMENT_DESC]) -> Vec<u32> {
  1428. let state = GraphicsState {
  1429. inputs: inputs.to_vec(),
  1430. ..GraphicsState::default()
  1431. };
  1432. state.elements().iter().map(|e| e.offset).collect()
  1433. }
  1434. /// An appended element after one of 1 or 2 bytes started right after
  1435. /// it; D3D12 aligns it to min(4, its size), so the rectangle expansion
  1436. /// read its vertices from the wrong bytes.
  1437. #[test]
  1438. fn appended_elements_are_aligned() {
  1439. const APPEND: u32 = D3D12_APPEND_ALIGNED_ELEMENT;
  1440. // RG8 (2 bytes) then RG32 float: 4, not 2.
  1441. let a = [
  1442. element(DXGI_FORMAT_R8G8_UNORM, 0),
  1443. element(DXGI_FORMAT_R32G32_FLOAT, APPEND),
  1444. ];
  1445. assert_eq!(offsets(&a), [0, 4]);
  1446. // R8 then R16 float: 2, not 1; then R8 packs right after it.
  1447. let b = [
  1448. element(DXGI_FORMAT_R8_UNORM, 0),
  1449. element(DXGI_FORMAT_R16_FLOAT, APPEND),
  1450. element(DXGI_FORMAT_R8_UNORM, APPEND),
  1451. ];
  1452. assert_eq!(offsets(&b), [0, 2, 4]);
  1453. // Already aligned layouts are unchanged.
  1454. let c = [
  1455. element(DXGI_FORMAT_R8G8B8A8_UNORM, 0),
  1456. element(DXGI_FORMAT_R32G32_FLOAT, APPEND),
  1457. element(DXGI_FORMAT_R32G32B32_FLOAT, APPEND),
  1458. ];
  1459. assert_eq!(offsets(&c), [0, 4, 12]);
  1460. }
  1461. /// An explicit offset near 4 GiB overflowed the next appended offset
  1462. /// (a panic in debug builds).
  1463. #[test]
  1464. fn a_huge_explicit_offset_does_not_overflow() {
  1465. let inputs = [
  1466. element(DXGI_FORMAT_R32G32B32A32_FLOAT, u32::MAX - 8),
  1467. element(DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT),
  1468. ];
  1469. let _ = offsets(&inputs);
  1470. }
  1471. }