mod.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. mod wave;
  89. use crate::dxbc::{Container, FourCC};
  90. use crate::native::{HwStage, NativeProgram, RootType};
  91. use crate::{ShaderError, io, ir, resource, structure};
  92. pub use sampler::StaticSampler;
  93. pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
  94. /// A translated shader and what the host binds for it.
  95. #[derive(Debug, Clone, PartialEq, Eq)]
  96. pub struct HostShader {
  97. pub stage: HwStage,
  98. /// The DXIL container, hashed as D3D12 expects.
  99. pub dxil: Vec<u8>,
  100. /// The user-data dwords the shader reads.
  101. pub user_data: Vec<UserData>,
  102. /// Immediate samplers: the four sampler words of `s<n>`.
  103. pub samplers: Vec<[u32; 4]>,
  104. /// The same samplers decoded, `s<n>` at position n: the static sampler
  105. /// descriptions the host's root signature declares.
  106. pub static_samplers: Vec<StaticSampler>,
  107. /// Root CBVs the shader reads: root parameter indices, each bound as
  108. /// `b<index>` in [`ROOT_CBV_SPACE`].
  109. pub root_cbvs: Vec<u8>,
  110. /// Root SRVs (raw buffers) the shader reads: `t<index>` in
  111. /// [`ROOT_CBV_SPACE`].
  112. pub root_srvs: Vec<u8>,
  113. }
  114. impl HostShader {
  115. /// Size of the user-data buffer the shader declares, in dwords (a
  116. /// multiple of 4; 0 when it reads none). Root constants must cover it.
  117. pub fn user_data_dwords(&self) -> u32 {
  118. let n = self
  119. .user_data
  120. .iter()
  121. .map(|u| u.index + 1)
  122. .max()
  123. .unwrap_or(0);
  124. n.next_multiple_of(4)
  125. }
  126. }
  127. /// One dword of user data and the root parameter that fills it.
  128. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  129. pub struct UserData {
  130. /// Dword in the user-data buffer (the console's user-data index).
  131. pub index: u32,
  132. /// Root parameter index in the title's root signature.
  133. pub slot: u8,
  134. /// `Constants` or `Table` (see the module notes for the value).
  135. pub root: RootType,
  136. /// Dword within the parameter.
  137. pub dword: u32,
  138. }
  139. /// Translates the vertex, pixel, compute or mesh program of a console
  140. /// shader container.
  141. pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
  142. let c = Container::parse(container)?;
  143. let dxil = c
  144. .part(FourCC::DXIL)
  145. .ok_or(ShaderError::Malformed("no DXIL part"))?;
  146. let native = crate::native_programs(dxil.data)?
  147. .into_iter()
  148. .find(|p| {
  149. matches!(
  150. p.stage,
  151. HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
  152. )
  153. })
  154. .ok_or(ShaderError::Unsupported {
  155. offset: 0,
  156. what: "a container without a vertex, pixel, compute or mesh program",
  157. })?;
  158. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  159. let res = resource::track(&p, &native.layout, native.stage)?;
  160. let io = io::raise(&p, &native)?;
  161. let st = structure::structure(&p)?;
  162. emit(&c, &native, &p, &st, &io, &res)
  163. }
  164. /// Emits a program whose earlier stages already ran.
  165. pub fn emit(
  166. c: &Container,
  167. native: &NativeProgram,
  168. p: &ir::Program,
  169. st: &structure::Structured,
  170. io: &io::Io,
  171. res: &resource::Resources,
  172. ) -> Result<HostShader, ShaderError> {
  173. let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
  174. match c.part(fourcc) {
  175. Some(part) => signature(part.data),
  176. None => Ok(Vec::new()),
  177. }
  178. };
  179. let pixel = native.stage == HwStage::Ps;
  180. let mut inputs = sig(FourCC::ISG1)?;
  181. let mut outputs = sig(FourCC::OSG1)?;
  182. // Interpolation as DXC declares it by default; pixel inputs that are
  183. // read get the mode their barycentrics say.
  184. let interpolated = if pixel { &mut inputs } else { &mut outputs };
  185. for e in interpolated {
  186. e.interp = match (e.kind, e.comp) {
  187. (3, _) => 4,
  188. // Constant, as DXC declares it (the AMD compiler crashed on a
  189. // front face without a mode).
  190. (13, _) => 1,
  191. (0 | 6 | 7, 9) => 2,
  192. (0, _) => 1,
  193. _ => 0,
  194. };
  195. }
  196. // Per-primitive outputs are constant. The console never exports a
  197. // primitive id or cull flag a mesh shader writes (it culls with the
  198. // primitive export), so those rows are left out.
  199. let mut prims = sig(FourCC::PSG1)?;
  200. prims.retain(|e| !matches!(e.kind, 10 | 30));
  201. for e in &mut prims {
  202. e.interp = 1;
  203. }
  204. // A mesh group's id arrives multiplied by max(threads, vertices,
  205. // primitives) (the code divides by that); the thread count is in PSV0
  206. // from runtime info version 2 on.
  207. // shortcut: older containers fall back to the group's lane count, right
  208. // when the HLSL group fills its waves (Grand Theft Auto VI's do).
  209. let mesh_stride = match &native.io {
  210. crate::native::StageIo::Ms(ms) => {
  211. let psv = c.part(FourCC::PSV0).map(|p| p.data);
  212. let threads = psv
  213. .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
  214. .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
  215. threads.map_or(ms.threads, |t| {
  216. t.max(ms.max_vertices).max(ms.max_primitives)
  217. })
  218. }
  219. _ => 0,
  220. };
  221. let l = lower::lower(&lower::Parts {
  222. native,
  223. p,
  224. st,
  225. io,
  226. res,
  227. inputs,
  228. outputs,
  229. prims,
  230. mesh_stride,
  231. })?;
  232. Ok(HostShader {
  233. stage: native.stage,
  234. dxil: l.dxil,
  235. user_data: l.user_data,
  236. static_samplers: l
  237. .samplers
  238. .iter()
  239. .enumerate()
  240. .map(|(n, &w)| {
  241. let mut s = StaticSampler::from_words(w);
  242. if l.cmp_samplers >> n & 1 != 0 {
  243. s.filter |= 0x80;
  244. }
  245. s
  246. })
  247. .collect(),
  248. samplers: l.samplers,
  249. root_cbvs: l.root_cbvs,
  250. root_srvs: l.root_srvs,
  251. })
  252. }
  253. /// The rows of an `ISG1`/`OSG1` part.
  254. fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
  255. use crate::dxbc::u32_at;
  256. let count = u32_at(part, 0)? as usize;
  257. let base = u32_at(part, 4)? as usize;
  258. let mut out = Vec::with_capacity(count);
  259. for i in 0..count {
  260. let at = base + 32 * i;
  261. let name_at = u32_at(part, at + 4)? as usize;
  262. let name = part
  263. .get(name_at..)
  264. .and_then(|s| s.split(|&b| b == 0).next())
  265. .ok_or(ShaderError::Malformed("signature name out of bounds"))?;
  266. let mask = *part
  267. .get(at + 24)
  268. .ok_or(ShaderError::Malformed("truncated"))?;
  269. if u32_at(part, at + 28)? != 0 {
  270. return Err(ShaderError::Unsupported {
  271. offset: 0,
  272. what: "a minimum-precision signature element",
  273. });
  274. }
  275. if u32_at(part, at)? != 0 {
  276. return Err(ShaderError::Unsupported {
  277. offset: 0,
  278. what: "a signature element of another stream",
  279. });
  280. }
  281. let kind = match u32_at(part, at + 12)? {
  282. 0 => 0,
  283. 1 => 3,
  284. 2 => 6,
  285. 3 => 7,
  286. 4 => 4,
  287. 5 => 5,
  288. 6 => 1,
  289. 7 => 10,
  290. 8 => 2,
  291. 9 => 13,
  292. 10 => 12,
  293. 64 => 16,
  294. 65 => 17,
  295. 66 => 14,
  296. 67 => 19,
  297. 68 => 18,
  298. 69 => 20,
  299. 70 => 15,
  300. 25 => 30, // cull primitive
  301. _ => {
  302. return Err(ShaderError::Unsupported {
  303. offset: 0,
  304. what: "a system value in the signature",
  305. });
  306. }
  307. };
  308. // 16-bit elements are declared 32-bit; reading or writing one
  309. // converts (16-bit values travel packed on the console).
  310. let raw = u32_at(part, at + 16)?;
  311. let comp = match (kind, raw) {
  312. // DXIL declares the front face a uint (the validator insists).
  313. (13, _) => 5,
  314. (_, 1 | 4) => 5,
  315. (_, 2 | 5) => 4,
  316. (_, 3 | 6) => 9,
  317. (_, c) => {
  318. return Err(ShaderError::Unsupported {
  319. offset: 0,
  320. what: match c {
  321. 0 => "a signature element of unknown type",
  322. _ => "a 64-bit signature element",
  323. },
  324. });
  325. }
  326. };
  327. let register = u32_at(part, at + 20)?;
  328. out.push(container::SigElement {
  329. name: String::from_utf8_lossy(name).into_owned(),
  330. index: u32_at(part, at + 8)?,
  331. kind,
  332. comp,
  333. interp: 0,
  334. row: (register != u32::MAX).then_some(register),
  335. col: mask.trailing_zeros().min(3) as u8,
  336. cols: mask.count_ones().max(1) as u8,
  337. usage: 0,
  338. half: (4..=6).contains(&raw),
  339. });
  340. }
  341. Ok(out)
  342. }
  343. #[cfg(test)]
  344. mod tests {
  345. use super::bitcode::Attr;
  346. use super::container::SigElement;
  347. use super::shader::Shader;
  348. use super::*;
  349. use crate::native::{ComputeIo, StageIo};
  350. /// A wave64 compute program that writes only EXEC's high dword
  351. /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is
  352. /// opaque and keyed by the unchanged low dword, so building its lane bit
  353. /// needed the mask's own value: lowering recursed until the stack
  354. /// overflowed, which takes the whole process down (found by
  355. /// random-input testing). Now the instruction fails like any other that
  356. /// cannot be expressed: its result is missing, and only a side effect
  357. /// that uses it would stop the translation.
  358. #[test]
  359. fn an_exec_high_write_does_not_overflow_the_stack() {
  360. // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm
  361. let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000];
  362. let native = NativeProgram {
  363. stage: HwStage::Cs,
  364. wave64: true,
  365. vgprs: 2,
  366. layout: vec![],
  367. used: vec![],
  368. io: StageIo::Cs(ComputeIo {
  369. rsrc2: 0,
  370. threads: [64, 1, 1],
  371. }),
  372. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  373. };
  374. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
  375. let res = resource::track(&p, &native.layout, native.stage).unwrap();
  376. let io = io::raise(&p, &native).unwrap();
  377. let st = structure::structure(&p).unwrap();
  378. let container = crate::dxbc::build(&[]);
  379. let c = Container::parse(&container).unwrap();
  380. if let Err(e) = emit(&c, &native, &p, &st, &io, &res) {
  381. assert!(e.to_string().contains("its own value"), "{e}");
  382. }
  383. }
  384. /// A pixel shader writing a constant colour.
  385. fn constant_color() -> Vec<u8> {
  386. let mut s = Shader::new(true);
  387. s.outputs.push(SigElement {
  388. name: "SV_Target".into(),
  389. index: 0,
  390. kind: 16,
  391. comp: 9,
  392. interp: 0,
  393. row: Some(0),
  394. col: 0,
  395. cols: 4,
  396. usage: 15,
  397. half: false,
  398. });
  399. let b = s.entry;
  400. for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
  401. let args = [
  402. s.m.i32(0),
  403. s.m.i32(0),
  404. s.m.i8(c as u8),
  405. s.m.f32(v.to_bits()),
  406. ];
  407. s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
  408. }
  409. s.m.terminate(b, super::bitcode::Term::Ret);
  410. s.finish()
  411. }
  412. #[test]
  413. #[cfg(windows)]
  414. fn stub_pipeline_is_created() {
  415. let Ok(host) = super::host::Host::new(false) else {
  416. eprintln!("no SM 6.6 device; skipped");
  417. return;
  418. };
  419. let ps = super::HostShader {
  420. stage: crate::HwStage::Ps,
  421. dxil: constant_color(),
  422. user_data: Vec::new(),
  423. samplers: Vec::new(),
  424. static_samplers: Vec::new(),
  425. root_cbvs: Vec::new(),
  426. root_srvs: Vec::new(),
  427. };
  428. let file = |var: &str, stage| {
  429. std::env::var(var).ok().map(|p| super::HostShader {
  430. stage,
  431. dxil: std::fs::read(p).unwrap(),
  432. user_data: Vec::new(),
  433. samplers: Vec::new(),
  434. static_samplers: Vec::new(),
  435. root_cbvs: Vec::new(),
  436. root_srvs: Vec::new(),
  437. })
  438. };
  439. let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
  440. let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
  441. .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
  442. if let Ok(mut v) = super::validator::Validator::load(
  443. super::validator::Validator::default_path().as_deref(),
  444. ) {
  445. v.validate(&mut vs.dxil.clone()).unwrap();
  446. }
  447. host.pipeline(&vs, &ps).unwrap();
  448. // The runtime checks the container hash: no hash or a wrong one is
  449. // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
  450. // value; ours works with older ones too.)
  451. let mut wrong = ps.dxil[4..20].to_vec();
  452. wrong[0] ^= 1;
  453. for digest in [&[0u8; 16][..], &wrong] {
  454. let mut other = ps.clone();
  455. other.dxil[4..20].copy_from_slice(digest);
  456. assert!(
  457. host.pipeline(&vs, &other).is_err(),
  458. "digest {digest:02x?} accepted"
  459. );
  460. }
  461. }
  462. #[test]
  463. #[cfg(windows)]
  464. fn constant_color_validates() {
  465. let mut c = constant_color();
  466. let path = super::validator::Validator::default_path();
  467. let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
  468. eprintln!("no dxil.dll; skipped");
  469. return;
  470. };
  471. let ours = c[4..20].to_vec();
  472. v.validate(&mut c).unwrap();
  473. assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
  474. }
  475. }