mod.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. //! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute
  2. //! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts.
  3. //! Compute shaders keep the console's thread-group size; one that depends
  4. //! on the lane layout (cross-lane operations) declares the console's wave
  5. //! size (`WaveSize`), so the host device must support it.
  6. //!
  7. //! What the host binds for a translated shader ([`HostShader`]):
  8. //!
  9. //! * **User data** at `b0, space 0` (32-bit root constants or a constant
  10. //! buffer, per stage): dword `index` holds a root parameter's value, as
  11. //! [`UserData`] lists. A root-constant dword is the constant. A
  12. //! descriptor table is the byte offset of its first descriptor in its
  13. //! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16
  14. //! for sampler tables (the console's descriptor sizes; the code adds
  15. //! offsets in those units). The heap bases of dynamic resources are 0
  16. //! and not listed.
  17. //! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and
  18. //! `SamplerDescriptorHeap[]`, at the index the console address gives, so
  19. //! the host heaps keep the title's descriptor order. The root signature
  20. //! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and
  21. //! `SAMPLER_HEAP_DIRECTLY_INDEXED`.
  22. //! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the
  23. //! position in [`HostShader::samplers`] (the console sampler words) and
  24. //! [`HostShader::static_samplers`] (the same decoded into a D3D12 static
  25. //! sampler description). Comparison sampling (added 2026-11-23): an
  26. //! immediate sampler it uses has a comparison filter there (bit 0x80);
  27. //! a heap sampler it uses must be a comparison sampler on the host.
  28. //! * **Root CBVs and root SRVs** (raw buffers) as root descriptors
  29. //! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter
  30. //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the
  31. //! address the title sets is the buffer's.
  32. //! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and
  33. //! vertex programs fetch vertices themselves with typed-format loads
  34. //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm,
  35. //! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the
  36. //! instruction, so the translation reads raw bytes and converts them
  37. //! itself. Their descriptors are built around a root SRV (stride 1, no
  38. //! record limit): the host binds the root SRV `t<slot>` above with the
  39. //! address the title sets, nothing more. The vertex index, the stride
  40. //! and the attribute offset are the shader's own arithmetic on data in
  41. //! that buffer (per-stream headers), not descriptor fields.
  42. //! * **Buffer views in the heap** are declared by how the shader reads
  43. //! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and
  44. //! typed-format loads without an index; structured with the used-resource
  45. //! entry's stride when indexed; typed with four 32-bit float channels for
  46. //! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at
  47. //! that index must be of that kind and start at the console descriptor's
  48. //! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the
  49. //! title's view description says. Typed-format loads from heap
  50. //! descriptors (1,024 world compute programs, ray-tracing material
  51. //! resolves) read raw views this way.
  52. //!
  53. //! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
  54. //! atomically is declared a 32-bit unsigned single-channel view; the
  55. //! host's view at that index must be an R32 integer view (64-bit atomics
  56. //! stop the translation). Global loads from a root SRV read it raw.
  57. //!
  58. //! Entry points: [`translate`] (container bytes as the title passes them
  59. //! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
  60. //! earlier stages already run). The root constants of each stage must
  61. //! cover [`HostShader::user_data_dwords`]. Stability: these types and the
  62. //! binding scheme are what pipeline creation builds on; changes are
  63. //! announced.
  64. //! * **Signatures** as the console container has them (same semantics,
  65. //! registers and masks), so the input layout and stage linking are the
  66. //! title's; pixel outputs are plain 32-bit values.
  67. //! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and
  68. //! descriptors as above (the root constants visible to the mesh stage);
  69. //! the pipeline is a mesh pipeline (pipeline-state stream, no input
  70. //! layout) with the title's pixel shader. The thread group is the
  71. //! console's in lanes (`[numthreads]` in the DXIL), the vertex and
  72. //! primitive maxima its own, triangles only, no wave size required. The
  73. //! console numbers groups in x only: the draw path passes the title's
  74. //! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
  75. //! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
  76. //! console never exports them).
  77. mod bitcode;
  78. mod container;
  79. #[cfg(all(test, windows))]
  80. mod diff_tests;
  81. #[cfg(all(windows, any(test, feature = "host")))]
  82. pub mod host;
  83. mod lower;
  84. mod sampler;
  85. mod shader;
  86. #[cfg(windows)]
  87. pub mod validator;
  88. #[cfg(all(test, windows))]
  89. mod valu_tests;
  90. #[cfg(all(test, windows))]
  91. mod waterfall_tests;
  92. mod wave;
  93. use crate::dxbc::{Container, FourCC};
  94. use crate::native::{HwStage, NativeProgram, RootType};
  95. use crate::{ShaderError, io, ir, resource, structure};
  96. pub use sampler::StaticSampler;
  97. pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
  98. /// The loop limit without an override: 2^20.
  99. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
  100. /// The iteration count after which a translated loop is left, per lane and
  101. /// per entry into the loop: [`DEFAULT_LOOP_LIMIT`].
  102. ///
  103. /// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or
  104. /// `0x` hex, at least 1) sets it instead. A loop that hits the limit in
  105. /// every lane of a full-screen pass still runs for seconds (2^20 times a
  106. /// 4K screen is about 10^13 iterations); a much lower limit shows whether
  107. /// such loops are what makes a frame slow. The value is part of the
  108. /// translation, so the shader cache must key on it (`victory-gpu`'s does).
  109. pub fn loop_limit() -> u32 {
  110. static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  111. *LIMIT.get_or_init(|| {
  112. if cfg!(feature = "diagnostics") {
  113. parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref())
  114. } else {
  115. lower::LOOP_LIMIT
  116. }
  117. })
  118. }
  119. /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
  120. /// unreadable or 0. Pure, for testing.
  121. fn parse_loop_limit(value: Option<&str>) -> u32 {
  122. let parsed = value
  123. .map(str::trim)
  124. .and_then(|v| match v.strip_prefix("0x") {
  125. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  126. None => v.parse().ok(),
  127. });
  128. match parsed {
  129. Some(n) if n > 0 => n,
  130. _ => lower::LOOP_LIMIT,
  131. }
  132. }
  133. /// A translated shader and what the host binds for it.
  134. #[derive(Debug, Clone, PartialEq, Eq)]
  135. pub struct HostShader {
  136. pub stage: HwStage,
  137. /// The DXIL container, hashed as D3D12 expects.
  138. pub dxil: Vec<u8>,
  139. /// The user-data dwords the shader reads.
  140. pub user_data: Vec<UserData>,
  141. /// Immediate samplers: the four sampler words of `s<n>`.
  142. pub samplers: Vec<[u32; 4]>,
  143. /// The same samplers decoded, `s<n>` at position n: the static sampler
  144. /// descriptions the host's root signature declares.
  145. pub static_samplers: Vec<StaticSampler>,
  146. /// Root CBVs the shader reads: root parameter indices, each bound as
  147. /// `b<index>` in [`ROOT_CBV_SPACE`].
  148. pub root_cbvs: Vec<u8>,
  149. /// Root SRVs (raw buffers) the shader reads: `t<index>` in
  150. /// [`ROOT_CBV_SPACE`].
  151. pub root_srvs: Vec<u8>,
  152. }
  153. impl HostShader {
  154. /// Size of the user-data buffer the shader declares, in dwords (a
  155. /// multiple of 4; 0 when it reads none). Root constants must cover it.
  156. pub fn user_data_dwords(&self) -> u32 {
  157. let n = self
  158. .user_data
  159. .iter()
  160. .map(|u| u.index + 1)
  161. .max()
  162. .unwrap_or(0);
  163. n.next_multiple_of(4)
  164. }
  165. }
  166. /// One dword of user data and the root parameter that fills it.
  167. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  168. pub struct UserData {
  169. /// Dword in the user-data buffer (the console's user-data index).
  170. pub index: u32,
  171. /// Root parameter index in the title's root signature.
  172. pub slot: u8,
  173. /// `Constants` or `Table` (see the module notes for the value).
  174. pub root: RootType,
  175. /// Dword within the parameter.
  176. pub dword: u32,
  177. }
  178. /// Translates the vertex, pixel, compute or mesh program of a console
  179. /// shader container.
  180. pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
  181. let c = Container::parse(container)?;
  182. let dxil = c
  183. .part(FourCC::DXIL)
  184. .ok_or(ShaderError::Malformed("no DXIL part"))?;
  185. let native = crate::native_programs(dxil.data)?
  186. .into_iter()
  187. .find(|p| {
  188. matches!(
  189. p.stage,
  190. HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
  191. )
  192. })
  193. .ok_or(ShaderError::Unsupported {
  194. offset: 0,
  195. what: "a container without a vertex, pixel, compute or mesh program",
  196. })?;
  197. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  198. // Structurisation first: tracing per-lane descriptors needs it (its
  199. // failure is reported after the earlier stages').
  200. let st = structure::structure(&p);
  201. let res = resource::track(&p, &native.layout, native.stage, st.as_ref().ok())?;
  202. let io = io::raise(&p, &native)?;
  203. let st = st?;
  204. emit(&c, &native, &p, &st, &io, &res)
  205. }
  206. /// Emits a program whose earlier stages already ran.
  207. pub fn emit(
  208. c: &Container,
  209. native: &NativeProgram,
  210. p: &ir::Program,
  211. st: &structure::Structured,
  212. io: &io::Io,
  213. res: &resource::Resources,
  214. ) -> Result<HostShader, ShaderError> {
  215. let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
  216. match c.part(fourcc) {
  217. Some(part) => signature(part.data),
  218. None => Ok(Vec::new()),
  219. }
  220. };
  221. let pixel = native.stage == HwStage::Ps;
  222. let mut inputs = sig(FourCC::ISG1)?;
  223. let mut outputs = sig(FourCC::OSG1)?;
  224. // Interpolation as DXC declares it by default; pixel inputs that are
  225. // read get the mode their barycentrics say.
  226. let interpolated = if pixel { &mut inputs } else { &mut outputs };
  227. for e in interpolated {
  228. e.interp = match (e.kind, e.comp) {
  229. (3, _) => 4,
  230. // Constant, as DXC declares it (the AMD compiler crashed on a
  231. // front face without a mode).
  232. (13, _) => 1,
  233. (0 | 6 | 7, 9) => 2,
  234. (0, _) => 1,
  235. _ => 0,
  236. };
  237. }
  238. // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL
  239. // wants the position centroid (or per sample), as DXC declares it then.
  240. if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) {
  241. for e in inputs.iter_mut().filter(|e| e.kind == 3) {
  242. e.interp = 5;
  243. }
  244. }
  245. // Per-primitive outputs are constant. The console never exports a
  246. // primitive id or cull flag a mesh shader writes (it culls with the
  247. // primitive export), so those rows are left out.
  248. let mut prims = sig(FourCC::PSG1)?;
  249. prims.retain(|e| !matches!(e.kind, 10 | 30));
  250. for e in &mut prims {
  251. e.interp = 1;
  252. }
  253. // A mesh group's id arrives multiplied by max(threads, vertices,
  254. // primitives) (the code divides by that); the thread count is in PSV0
  255. // from runtime info version 2 on.
  256. // shortcut: older containers fall back to the group's lane count, right
  257. // when the HLSL group fills its waves (Grand Theft Auto VI's do).
  258. let mesh_stride = match &native.io {
  259. crate::native::StageIo::Ms(ms) => {
  260. let psv = c.part(FourCC::PSV0).map(|p| p.data);
  261. let threads = psv
  262. .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
  263. .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
  264. threads.map_or(ms.threads, |t| {
  265. t.max(ms.max_vertices).max(ms.max_primitives)
  266. })
  267. }
  268. _ => 0,
  269. };
  270. let l = lower::lower(&lower::Parts {
  271. native,
  272. p,
  273. st,
  274. io,
  275. res,
  276. inputs,
  277. outputs,
  278. prims,
  279. mesh_stride,
  280. })?;
  281. Ok(HostShader {
  282. stage: native.stage,
  283. dxil: l.dxil,
  284. user_data: l.user_data,
  285. static_samplers: l
  286. .samplers
  287. .iter()
  288. .enumerate()
  289. .map(|(n, &w)| {
  290. let mut s = StaticSampler::from_words(w);
  291. if l.cmp_samplers >> n & 1 != 0 {
  292. s.filter |= 0x80;
  293. }
  294. s
  295. })
  296. .collect(),
  297. samplers: l.samplers,
  298. root_cbvs: l.root_cbvs,
  299. root_srvs: l.root_srvs,
  300. })
  301. }
  302. /// The rows of an `ISG1`/`OSG1` part.
  303. fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
  304. use crate::dxbc::u32_at;
  305. let count = u32_at(part, 0)? as usize;
  306. let base = u32_at(part, 4)? as usize;
  307. let mut out = Vec::with_capacity(count);
  308. for i in 0..count {
  309. let at = base + 32 * i;
  310. let name_at = u32_at(part, at + 4)? as usize;
  311. let name = part
  312. .get(name_at..)
  313. .and_then(|s| s.split(|&b| b == 0).next())
  314. .ok_or(ShaderError::Malformed("signature name out of bounds"))?;
  315. let mask = *part
  316. .get(at + 24)
  317. .ok_or(ShaderError::Malformed("truncated"))?;
  318. if u32_at(part, at + 28)? != 0 {
  319. return Err(ShaderError::Unsupported {
  320. offset: 0,
  321. what: "a minimum-precision signature element",
  322. });
  323. }
  324. if u32_at(part, at)? != 0 {
  325. return Err(ShaderError::Unsupported {
  326. offset: 0,
  327. what: "a signature element of another stream",
  328. });
  329. }
  330. let kind = match u32_at(part, at + 12)? {
  331. 0 => 0,
  332. 1 => 3,
  333. 2 => 6,
  334. 3 => 7,
  335. 4 => 4,
  336. 5 => 5,
  337. 6 => 1,
  338. 7 => 10,
  339. 8 => 2,
  340. 9 => 13,
  341. 10 => 12,
  342. 64 => 16,
  343. 65 => 17,
  344. 66 => 14,
  345. 67 => 19,
  346. 68 => 18,
  347. 69 => 20,
  348. 70 => 15,
  349. 25 => 30, // cull primitive
  350. _ => {
  351. return Err(ShaderError::Unsupported {
  352. offset: 0,
  353. what: "a system value in the signature",
  354. });
  355. }
  356. };
  357. // 16-bit elements are declared 32-bit; reading or writing one
  358. // converts (16-bit values travel packed on the console).
  359. let raw = u32_at(part, at + 16)?;
  360. let comp = match (kind, raw) {
  361. // DXIL declares the front face a uint (the validator insists).
  362. (13, _) => 5,
  363. (_, 1 | 4) => 5,
  364. (_, 2 | 5) => 4,
  365. (_, 3 | 6) => 9,
  366. (_, c) => {
  367. return Err(ShaderError::Unsupported {
  368. offset: 0,
  369. what: match c {
  370. 0 => "a signature element of unknown type",
  371. _ => "a 64-bit signature element",
  372. },
  373. });
  374. }
  375. };
  376. let register = u32_at(part, at + 20)?;
  377. out.push(container::SigElement {
  378. name: String::from_utf8_lossy(name).into_owned(),
  379. index: u32_at(part, at + 8)?,
  380. kind,
  381. comp,
  382. interp: 0,
  383. row: (register != u32::MAX).then_some(register),
  384. col: mask.trailing_zeros().min(3) as u8,
  385. cols: mask.count_ones().max(1) as u8,
  386. usage: 0,
  387. half: (4..=6).contains(&raw),
  388. });
  389. }
  390. Ok(out)
  391. }
  392. #[cfg(test)]
  393. mod tests {
  394. use super::bitcode::Attr;
  395. use super::lower::LOOP_LIMIT;
  396. use super::parse_loop_limit;
  397. #[test]
  398. fn the_loop_limit_switch_parses_or_falls_back() {
  399. assert_eq!(parse_loop_limit(None), LOOP_LIMIT);
  400. assert_eq!(parse_loop_limit(Some("4096")), 4096);
  401. assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096);
  402. assert_eq!(parse_loop_limit(Some("1")), 1);
  403. for bad in ["", "0", "-5", "lots", "0x", "4294967296"] {
  404. assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}");
  405. }
  406. }
  407. use super::container::SigElement;
  408. use super::shader::Shader;
  409. use super::*;
  410. use crate::native::{ComputeIo, StageIo};
  411. /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`).
  412. /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose
  413. /// output signature has SV_StencilRef, and the feature bit
  414. /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks
  415. /// both against the module.
  416. #[test]
  417. fn a_stencil_export_declares_the_stencil_ref_feature() {
  418. let words = [
  419. 0x7E00_02F2u32, // v_mov_b32 v0, 1.0
  420. 0x7E02_0285, // v_mov_b32 v1, 5
  421. 0xF800_1883,
  422. 0x0000_0100, // exp mrtz v0, v1, off, off done vm
  423. 0xBF81_0000,
  424. ];
  425. let native = NativeProgram {
  426. stage: HwStage::Ps,
  427. wave64: false,
  428. vgprs: 2,
  429. layout: vec![],
  430. used: vec![],
  431. io: StageIo::Ps {
  432. inputs: vec![],
  433. input_addr: 0,
  434. db_shader_control: 0,
  435. patches: vec![],
  436. },
  437. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  438. };
  439. let el = |name: &str, kind, comp| SigElement {
  440. name: name.into(),
  441. index: 0,
  442. kind,
  443. comp,
  444. interp: 0,
  445. row: None,
  446. col: 0,
  447. cols: 1,
  448. usage: 1,
  449. half: false,
  450. };
  451. let osg1 =
  452. container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false);
  453. let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]);
  454. let c = Container::parse(&bytes).unwrap();
  455. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  456. let st = structure::structure(&p).unwrap();
  457. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  458. let io = io::raise(&p, &native).unwrap();
  459. let out = emit(&c, &native, &p, &st, &io, &res).unwrap();
  460. // dxil.dll, where there is one, checks the flags against the module.
  461. #[cfg(windows)]
  462. if let Ok(mut v) = super::validator::Validator::load(
  463. super::validator::Validator::default_path().as_deref(),
  464. ) {
  465. v.validate(&mut out.dxil.clone()).unwrap();
  466. }
  467. let host = Container::parse(&out.dxil).unwrap();
  468. let sfi0 = host.part(FourCC::SFI0).unwrap().data;
  469. let features = u64::from_le_bytes(sfi0.try_into().unwrap());
  470. assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef");
  471. }
  472. /// A wave64 compute program that writes only EXEC's high dword
  473. /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is
  474. /// opaque and keyed by the unchanged low dword, so building its lane bit
  475. /// needed the mask's own value: lowering recursed until the stack
  476. /// overflowed, which takes the whole process down (found by
  477. /// random-input testing). Now the instruction fails like any other that
  478. /// cannot be expressed: its result is missing, and only a side effect
  479. /// that uses it would stop the translation.
  480. #[test]
  481. fn an_exec_high_write_does_not_overflow_the_stack() {
  482. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm
  483. let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000];
  484. let native = NativeProgram {
  485. stage: HwStage::Cs,
  486. wave64: true,
  487. vgprs: 2,
  488. layout: vec![],
  489. used: vec![],
  490. io: StageIo::Cs(ComputeIo {
  491. rsrc2: 0,
  492. threads: [64, 1, 1],
  493. }),
  494. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  495. };
  496. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  497. let st = structure::structure(&p).unwrap();
  498. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  499. let io = io::raise(&p, &native).unwrap();
  500. let container = crate::dxbc::build(&[]);
  501. let c = Container::parse(&container).unwrap();
  502. if let Err(e) = emit(&c, &native, &p, &st, &io, &res) {
  503. assert!(e.to_string().contains("its own value"), "{e}");
  504. }
  505. }
  506. /// A pixel shader writing a constant colour.
  507. #[cfg(windows)]
  508. fn constant_color() -> Vec<u8> {
  509. let mut s = Shader::new(true);
  510. s.outputs.push(SigElement {
  511. name: "SV_Target".into(),
  512. index: 0,
  513. kind: 16,
  514. comp: 9,
  515. interp: 0,
  516. row: Some(0),
  517. col: 0,
  518. cols: 4,
  519. usage: 15,
  520. half: false,
  521. });
  522. let b = s.entry;
  523. for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
  524. let args = [
  525. s.m.i32(0),
  526. s.m.i32(0),
  527. s.m.i8(c as u8),
  528. s.m.f32(v.to_bits()),
  529. ];
  530. s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
  531. }
  532. s.m.terminate(b, super::bitcode::Term::Ret);
  533. s.finish()
  534. }
  535. #[test]
  536. #[cfg(windows)]
  537. fn stub_pipeline_is_created() {
  538. let Ok(host) = super::host::Host::new(false) else {
  539. eprintln!("no SM 6.6 device; skipped");
  540. return;
  541. };
  542. let ps = super::HostShader {
  543. stage: crate::HwStage::Ps,
  544. dxil: constant_color(),
  545. user_data: Vec::new(),
  546. samplers: Vec::new(),
  547. static_samplers: Vec::new(),
  548. root_cbvs: Vec::new(),
  549. root_srvs: Vec::new(),
  550. };
  551. let file = |var: &str, stage| {
  552. std::env::var(var).ok().map(|p| super::HostShader {
  553. stage,
  554. dxil: std::fs::read(p).unwrap(),
  555. user_data: Vec::new(),
  556. samplers: Vec::new(),
  557. static_samplers: Vec::new(),
  558. root_cbvs: Vec::new(),
  559. root_srvs: Vec::new(),
  560. })
  561. };
  562. let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
  563. let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
  564. .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
  565. if let Ok(mut v) = super::validator::Validator::load(
  566. super::validator::Validator::default_path().as_deref(),
  567. ) {
  568. v.validate(&mut vs.dxil.clone()).unwrap();
  569. }
  570. host.pipeline(&vs, &ps).unwrap();
  571. // The runtime checks the container hash: no hash or a wrong one is
  572. // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
  573. // value; ours works with older ones too.)
  574. let mut wrong = ps.dxil[4..20].to_vec();
  575. wrong[0] ^= 1;
  576. for digest in [&[0u8; 16][..], &wrong] {
  577. let mut other = ps.clone();
  578. other.dxil[4..20].copy_from_slice(digest);
  579. assert!(
  580. host.pipeline(&vs, &other).is_err(),
  581. "digest {digest:02x?} accepted"
  582. );
  583. }
  584. }
  585. #[test]
  586. #[cfg(windows)]
  587. fn constant_color_validates() {
  588. let mut c = constant_color();
  589. let path = super::validator::Validator::default_path();
  590. let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
  591. eprintln!("no dxil.dll; skipped");
  592. return;
  593. };
  594. let ours = c[4..20].to_vec();
  595. v.validate(&mut c).unwrap();
  596. assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
  597. }
  598. /// A pixel shader interpolating at sample positions (PERSP_SAMPLE
  599. /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency:
  600. /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1)
  601. /// whenever an input is interpolated per sample.
  602. #[test]
  603. fn sample_interpolated_inputs_set_psv_sample_frequency() {
  604. let words = [
  605. 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x
  606. 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
  607. 0xF800_180F,
  608. 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm
  609. 0xBF81_0000,
  610. ];
  611. let psv_of = |input_addr: u32| {
  612. let native = super::NativeProgram {
  613. stage: super::HwStage::Ps,
  614. wave64: false,
  615. vgprs: 4,
  616. layout: vec![],
  617. used: vec![],
  618. io: crate::native::StageIo::Ps {
  619. inputs: vec![crate::native::PsInput {
  620. usage: crate::native::Usage::Generic,
  621. row: 0,
  622. mask: 0b1111,
  623. attr: 0,
  624. flat: false,
  625. fp16: false,
  626. pack2: false,
  627. row2: 0,
  628. }],
  629. input_addr,
  630. db_shader_control: 0,
  631. patches: vec![],
  632. },
  633. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  634. };
  635. let el = |name: &str, kind, usage| SigElement {
  636. name: name.into(),
  637. index: 0,
  638. kind,
  639. comp: 9,
  640. interp: 0,
  641. row: Some(0),
  642. col: 0,
  643. cols: 4,
  644. usage,
  645. half: false,
  646. };
  647. let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true);
  648. let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false);
  649. let bytes =
  650. crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]);
  651. let c = super::Container::parse(&bytes).unwrap();
  652. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  653. let st = crate::structure::structure(&p).unwrap();
  654. let res =
  655. crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  656. let io = crate::io::raise(&p, &native).unwrap();
  657. let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap();
  658. // dxil.dll, where there is one, checks PSV0 against the module.
  659. #[cfg(windows)]
  660. if let Ok(mut v) = super::validator::Validator::load(
  661. super::validator::Validator::default_path().as_deref(),
  662. ) {
  663. v.validate(&mut out.dxil.clone()).unwrap();
  664. }
  665. let host = super::Container::parse(&out.dxil).unwrap();
  666. host.part(super::FourCC::PSV0).unwrap().data.to_vec()
  667. };
  668. // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}.
  669. let center = psv_of(1 << 1);
  670. assert_eq!(center[4 + 1], 0, "center interpolation is per pixel");
  671. let sample = psv_of(1 << 0);
  672. assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency");
  673. }
  674. /// A pixel shader reading channel z of an input whose element starts at
  675. /// w. Looking the channel up subtracted the element's first channel
  676. /// before checking the channel lies in it, so in a build with overflow
  677. /// checks (tests, debug) any read below an element that starts at z or
  678. /// w panicked, whichever row it was in (found by random-input testing).
  679. #[test]
  680. fn reading_a_channel_below_an_input_element_does_not_underflow() {
  681. // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm
  682. let words = [0xC80E_0202u32, 0xBF81_0000];
  683. let native = super::NativeProgram {
  684. stage: super::HwStage::Ps,
  685. wave64: false,
  686. vgprs: 4,
  687. layout: vec![],
  688. used: vec![],
  689. io: crate::native::StageIo::Ps {
  690. inputs: vec![crate::native::PsInput {
  691. usage: crate::native::Usage::Generic,
  692. row: 0,
  693. mask: 0b1000,
  694. attr: 0,
  695. flat: false,
  696. fp16: false,
  697. pack2: false,
  698. row2: 0,
  699. }],
  700. input_addr: 0,
  701. db_shader_control: 0,
  702. patches: vec![],
  703. },
  704. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  705. };
  706. let w_only = SigElement {
  707. name: "TEXCOORD".into(),
  708. index: 0,
  709. kind: 0,
  710. comp: 9,
  711. interp: 0,
  712. row: Some(0),
  713. col: 3,
  714. cols: 1,
  715. usage: 0,
  716. half: false,
  717. };
  718. let isg1 = super::container::signature(&[w_only], true);
  719. let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]);
  720. let c = super::Container::parse(&bytes).unwrap();
  721. let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  722. let st = crate::structure::structure(&p).unwrap();
  723. let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap();
  724. let io = crate::io::raise(&p, &native).unwrap();
  725. // Translated or refused with a reason; it must not panic.
  726. let _ = super::emit(&c, &native, &p, &st, &io, &res);
  727. }
  728. }