victory-gta6: this fork's changes on top of VIctory main (ffe310e)

World rendering, lighting, frame-rate and memory work for Grand Theft Auto VI
(Xbox Series X profile) on one Windows PC with an NVIDIA RTX 4070. The README
describes the state, the changes and the credits. Based on VIctory by Marvisak
and contributors (GPL-3.0-or-later); XCL by ivall and contributors was used as
a reference. No game files are included.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
fxcelessandClaude Fable 5.2 committed 2026-11-24 13:02:18 -05:00
1 parent ffe310eb20
commit 578d459c34
61 files changed
+32259 -1274

No files matched your search

+828 -10
View File
@@ -50,10 +50,9 @@
//! descriptors (1,024 world compute programs, ray-tracing material
//! resolves) read raw views this way.
//!
//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
//! atomically is declared a 32-bit unsigned single-channel view; the
//! host's view at that index must be an R32 integer view (64-bit atomics
//! stop the translation). Global loads from a root SRV read it raw.
//! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT
//! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter
//! require SM 6.6 atomic support on typed and descriptor-heap resources.
//!
//! Entry points: [`translate`] (container bytes as the title passes them
//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
@@ -74,16 +73,26 @@
//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
//! console never exports them).
//! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a
//! rectangle from three vertices; the host has no such topology. A
//! pipeline the title makes for rectangles (topology type 19) gets a
//! geometry shader of ours between the translated vertex and pixel
//! shaders and draws triangle lists with the title's own vertex counts.
//! It binds nothing.
mod bitcode;
mod container;
#[cfg(all(test, windows))]
mod diff_tests;
#[cfg(all(test, windows))]
mod intersect_tests;
#[cfg(all(windows, any(test, feature = "host")))]
pub mod host;
mod lower;
mod rect;
mod sampler;
mod shader;
mod threading;
#[cfg(windows)]
pub mod validator;
#[cfg(all(test, windows))]
@@ -97,7 +106,13 @@ use crate::native::{HwStage, NativeProgram, RootType};
use crate::{ShaderError, io, ir, resource, structure};
pub use sampler::StaticSampler;
pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
pub use lower::set_host_max_wave;
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
set_view_heap_limit,
};
/// The loop limit without an override: 2^20.
pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
@@ -122,6 +137,33 @@ pub fn loop_limit() -> u32 {
})
}
/// Which of a translated program's group barriers wait for the whole
/// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory
/// fence and lose the wait. A wait that some thread of the group never
/// reaches is undefined on the host, and NVIDIA's wait is for every
/// thread: the group stands until Windows resets the card. (The console's
/// barrier is the wave's, whatever lanes are live, and a wave that ended
/// is not waited for.) `VICTORY_GROUP_SYNC`:
/// - unset or `2`: every barrier waits, as before.
/// - `1`: the title's `s_barrier` waits only in a block every lane runs,
/// in a program no lane can be cut out of at the iteration limit.
/// - `0`: no barrier waits, neither the title's nor the ones the
/// translation adds (wave64 programs in two host waves exchange through
/// them, so such programs compute wrong values). For one run that tells
/// whether a barrier is what stops the card: with it no run can stand in
/// a barrier.
///
/// Part of the translation: the shader cache keys on it (`victory-gpu`'s
/// does).
pub fn group_sync() -> u8 {
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*MODE.get_or_init(|| match std::env::var("VICTORY_GROUP_SYNC").ok().as_deref().map(str::trim) {
Some("0") => 0,
Some("1") => 1,
_ => 2,
})
}
/// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
/// unreadable or 0. Pure, for testing.
fn parse_loop_limit(value: Option<&str>) -> u32 {
@@ -156,6 +198,11 @@ pub struct HostShader {
/// Root SRVs (raw buffers) the shader reads: `t<index>` in
/// [`ROOT_CBV_SPACE`].
pub root_srvs: Vec<u8>,
/// Root UAVs (raw buffers) the shader reads or writes: `u<index>` in
/// [`ROOT_CBV_SPACE`].
pub root_uavs: Vec<u8>,
/// Heap descriptors that can be selected from root state at bind time.
pub root_indexed_views: Vec<crate::resource::RootIndexedView>,
}
impl HostShader {
@@ -204,7 +251,7 @@ pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
offset: 0,
what: "a container without a vertex, pixel, compute or mesh program",
})?;
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
let p = crate::spill::build(&native)?;
// Structurisation first: tracing per-lane descriptors needs it (its
// failure is reported after the earlier stages').
let st = structure::structure(&p);
@@ -223,6 +270,139 @@ pub fn emit(
io: &io::Io,
res: &resource::Resources,
) -> Result<HostShader, ShaderError> {
let original = emit_program(c, native, p, st, io, res);
// A console wave64 compute program on a host of 32-lane waves that
// still needs 64 lanes, or whose cross-lane code sits where not every
// lane runs: once more with its early-outs left out
// ([`ir::without_early_outs`]), which is what usually keeps the whole
// body from being a block every lane runs.
let stuck = match &original {
Ok((_, wave)) => *wave == Some(64),
Err(ShaderError::Unsupported { what, .. }) => what.ends_with("where not every lane runs"),
Err(_) => false,
};
if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| {
if why {
match r {
Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"),
Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"),
}
}
};
let done = |r: &Result<(HostShader, Option<u32>), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64));
// Each host wave as a wave of its own (`lower::with_local_waves`),
// for programs still stopped where not every lane runs.
let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0");
// Where the wave operations are the allocation idiom
// ([`lower::wave_local`]) that is exact. Other programs are taken
// the same way last of all, each half-wave giving its own results
// (approximate: a tile-wide result becomes two half-tile ones);
// `VICTORY_WAVE_LOCAL=idiom` refuses those instead.
let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom");
let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) {
Ok(()) => true,
Err((offset, what)) => {
if why {
eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}");
}
false
}
};
// The program in two other forms: without its early-outs, and
// without any branch that only skips code no lane is left for.
let form = |p: Option<ir::Program>| {
p.and_then(|p| {
let st = structure::structure(&p).ok()?;
let io = io::raise(&p, native).ok()?;
let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?;
Some((p, st, io, res))
})
};
let forms = [
("without early-outs", form(ir::without_early_outs(p))),
("without skips", form(ir::without_skips(p))),
];
for (name, f) in &forms {
if let Some((p, st, io, res)) = f {
let again = emit_program(c, native, p, st, io, res);
report(name, &again);
if done(&again) {
return again.map(|(shader, _)| shader);
}
}
}
if local_on {
// exact first (every form), then approximate
for exact in [true, false] {
if !exact && strict {
break;
}
for (name, f) in &forms {
if let Some((p, st, io, res)) = f
&& idiom(p, st) == exact
{
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
if done(&local) {
return local.map(|(shader, _)| shader);
}
}
}
if idiom(p, st) == exact {
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
if done(&local) {
return local.map(|(shader, _)| shader);
}
}
}
// Last: every mask and lane read per host wave.
if !strict {
for (name, f) in &forms {
if let Some((p, st, io, res)) = f {
let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local);
if done(&local) {
return local.map(|(shader, _)| shader);
}
}
}
let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res));
report("local waves (APPROXIMATE, any mask)", &local);
if done(&local) {
return local.map(|(shader, _)| shader);
}
}
}
}
let original = original.map(|(shader, _)| shader);
// Retry unsupported programs only. Threading can separate an unknown
// register value from its apparent use on a mutually exclusive path.
if !matches!(original, Err(ShaderError::Unsupported { .. })) {
return original;
}
let edges = threading::constant_edges(p, st);
if edges.is_empty() {
return original;
}
let p = ir::thread_edges(p, &edges)?;
let st = structure::structure(&p)?;
let io = io::raise(&p, native)?;
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
}
/// The translated program, and the wave size it requires of the host.
fn emit_program(
c: &Container,
native: &NativeProgram,
p: &ir::Program,
st: &structure::Structured,
io: &io::Io,
res: &resource::Resources,
) -> Result<(HostShader, Option<u32>), ShaderError> {
let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
match c.part(fourcc) {
Some(part) => signature(part.data),
@@ -241,6 +421,8 @@ pub fn emit(
// Constant, as DXC declares it (the AMD compiler crashed on a
// front face without a mode).
(13, _) => 1,
// Until a read says which mode (`lower`).
(28, _) => 2,
(0 | 6 | 7, 9) => 2,
(0, _) => 1,
_ => 0,
@@ -289,7 +471,8 @@ pub fn emit(
prims,
mesh_stride,
})?;
Ok(HostShader {
let wave_size = l.wave_size;
let shader = HostShader {
stage: native.stage,
dxil: l.dxil,
user_data: l.user_data,
@@ -308,7 +491,10 @@ pub fn emit(
samplers: l.samplers,
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
})
root_uavs: l.root_uavs,
root_indexed_views: res.root_indexed_views.clone(),
};
Ok((shader, wave_size))
}
/// The rows of an `ISG1`/`OSG1` part.
@@ -358,6 +544,7 @@ fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
68 => 18,
69 => 20,
70 => 15,
23 => 28, // barycentrics
25 => 30, // cull primitive
_ => {
return Err(ShaderError::Unsupported {
@@ -486,11 +673,12 @@ mod tests {
}
/// A wave64 compute program that writes only EXEC's high dword
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask is
/// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was
/// opaque and keyed by the unchanged low dword, so building its lane bit
/// needed the mask's own value: lowering recursed until the stack
/// overflowed, which takes the whole process down (found by
/// random-input testing). Now the instruction fails like any other that
/// random-input testing). Now that low dword, seen with two high
/// dwords, has no mask, and the instruction fails like any other that
/// cannot be expressed: its result is missing, and only a side effect
/// that uses it would stop the translation.
#[test]
@@ -520,6 +708,108 @@ mod tests {
}
}
/// A wave64 compute program: `body`, then a store of v1 to a UAV.
fn stores_v1(body: &[u32]) -> Result<(), ShaderError> {
use crate::native::RootParam;
use crate::{ResourceType, RootType, UsedResource};
// s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0
let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000];
words.extend_from_slice(body);
// v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen;
// s_endpgm
words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]);
let native = NativeProgram {
stage: HwStage::Cs,
wave64: true,
vgprs: 4,
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 0,
slot: 0,
}],
used: vec![UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 4,
user_data: 0,
slot: 0,
}],
io: StageIo::Cs(ComputeIo {
rsrc2: 2,
threads: [64, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap();
let res = resource::track(&p, &native.layout, native.stage, None).unwrap();
let io = io::raise(&p, &native).unwrap();
let st = structure::structure(&p).unwrap();
let container = crate::dxbc::build(&[]);
let c = Container::parse(&container).unwrap();
emit(&c, &native, &p, &st, &io, &res).map(|_| ())
}
/// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi`
/// or `exec_hi`): lanes 32-63 took the mask the low dword was first
/// written with (the compare's, EXEC's on entry). Now the store refuses;
/// without the write it translates.
#[test]
fn a_mask_whose_high_dword_is_rewritten_is_refused() {
// v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc
let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480];
// The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc.
let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480];
// v_mov_b32 v1, 7
let mov = [0x7E02_0287];
for body in [&select[..], &carry, &mov] {
stores_v1(body).unwrap();
}
// s_mov_b32 vcc_hi, 0 after the compare.
let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480];
let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480];
// s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after
// s_mov_b64 s[2:3], exec.
let exec_hi = [0xBEFF_0380, 0x7E02_0287];
let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287];
for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] {
assert!(stores_v1(body).is_err(), "{body:x?}");
}
}
/// `ds_bpermute_b32` stores nothing: each lane reads the lane its address
/// names. It stopped as "LDS the program does not allocate" (sticky lips)
/// or "an LDS operation" (the checkerboard shadow masks).
#[test]
fn a_backward_permute_reads_the_lane_its_address_names() {
// v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2
stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap();
}
/// A carry-in reading a join of compares after a divergent branch. A
/// lane that skipped the inner compare has VCC clear there (VOPC clears
/// inactive lanes), not the first compare's bit, so the join is no
/// per-lane phi: lowering refuses it.
#[test]
fn a_carry_in_from_a_divergent_join_is_refused() {
let body = [
0x7E04_028B, // v_mov_b32 v2, 11
0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0
0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc
0xBF88_0001, // s_cbranch_execz 1
0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0
0x88FE_027E, // s_or_b64 exec, exec, s[2:3]
0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc
];
let e = stores_v1(&body).unwrap_err().to_string();
assert!(e.contains("a carry-in from an untracked mask"), "{e}");
}
/// A pixel shader writing a constant colour.
#[cfg(windows)]
fn constant_color() -> Vec<u8> {
@@ -565,6 +855,8 @@ mod tests {
static_samplers: Vec::new(),
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
};
let file = |var: &str, stage| {
std::env::var(var).ok().map(|p| super::HostShader {
@@ -575,6 +867,8 @@ mod tests {
static_samplers: Vec::new(),
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
root_uavs: Vec::new(),
root_indexed_views: Vec::new(),
})
};
let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
@@ -746,4 +1040,528 @@ mod tests {
// Translated or refused with a reason; it must not panic.
let _ = super::emit(&c, &native, &p, &st, &io, &res);
}
#[test]
fn valu_div_f32_sequence_executes_on_gpu() {
let words: &[u32] = &[
0xBE85_0380, // s_mov_b32 s5, 0
0xF408_0202,
0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
0xF408_0302,
0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
0x340E_0083, // v_lshlrev_b32 v7, 3, v0
0xE034_1000,
0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen
0xD56D_6A03,
0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1
0xD56D_1008,
0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1
0x7E08_5503, // v_rcp_f32 v4, v3
0xD54B_0005,
0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0
0xD54B_0004,
0x0412_0905, // v_fma_f32 v4, v5, v4, v4
0x100A_0908, // v_mul_f32 v5, v8, v4
0xD54B_0006,
0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8
0xD56F_0004,
0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5
0xD55F_0001,
0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
0xE070_1000,
0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen
0xBF81_0000, // s_endpgm
];
let native = super::NativeProgram {
stage: super::HwStage::Cs,
wave64: false,
vgprs: 9,
layout: vec![
crate::RootParam {
root: crate::RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
crate::RootParam {
root: crate::RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![
crate::UsedResource {
kind: crate::ResourceType::Srv,
root: crate::RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
},
crate::UsedResource {
kind: crate::ResourceType::Uav,
root: crate::RootType::Table,
table_offset_dwords: 8,
lower_bound: 0,
stride: 4,
dwords: 4,
user_data: 4,
slot: 1,
},
],
io: crate::native::StageIo::Cs(crate::native::ComputeIo {
rsrc2: 5 << 1,
threads: [7, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap();
let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap();
let io = crate::io::raise(&p, &native).unwrap();
let st = crate::structure::structure(&p).unwrap();
let l = super::lower::lower(&super::lower::Parts {
native: &native,
p: &p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
})
.unwrap();
let mut dxil = l.dxil;
#[cfg(windows)]
if let Ok(mut v) = super::validator::Validator::load(
super::validator::Validator::default_path().as_deref(),
) {
v.validate(&mut dxil).unwrap();
}
#[cfg(windows)]
if let Ok(host) = super::host::Host::new(false) {
let cs = super::HostShader {
stage: super::HwStage::Cs,
dxil,
user_data: l.user_data,
samplers: Vec::new(),
static_samplers: Vec::new(),
root_cbvs: l.root_cbvs,
root_srvs: l.root_srvs,
root_uavs: l.root_uavs,
root_indexed_views: Vec::new(),
};
let (root, pso) = host.compute_pipeline(&cs).unwrap();
let inputs: Vec<u32> = [
7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35,
]
.into_iter()
.map(f32::to_bits)
.collect();
let out = host
.dispatch(
&root,
&pso,
&super::host::Dispatch {
roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))],
views: &[
super::host::View::Buffer {
data: &inputs,
stride: super::host::Stride::Raw,
},
super::host::View::RawUav(64),
],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap();
let got: Vec<f32> = out[0][..7].iter().copied().map(f32::from_bits).collect();
assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got);
assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits());
assert!(
(got[2] - 1e-35).abs() <= 1e-40,
"lane 2 got {:?} ({:#x})",
got[2],
out[0][2]
);
assert!(
(got[3] - 10.0).abs() < 1e-5,
"lane 3 got {:?} ({:#x})",
got[3],
out[0][3]
);
assert_eq!(out[0][4], 0xFFC0_0000);
assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits());
assert!(
(got[6] - (-1.0)).abs() < 1e-6,
"lane 6 got {:?} ({:#x})",
got[6],
out[0][6]
);
}
}
}
#[cfg(test)]
mod atomic_tests {
use super::*;
use crate::native::{ComputeIo, RootParam, StageIo};
#[test]
fn heap_texture_atomic_widths() {
// A synthetic compute shader loads a 2D UAV from a root table,
// compares or adds at (0, 0), then uses the returned register(s).
for (opcode, mask, wide) in [
(16u32, 3, false),
(16, 15, true),
(17, 1, false),
(17, 3, true),
] {
let words = [
0xBE81_0380, // s_mov_b32 s1, 0 (table address high)
0xF40C_0200,
0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0
0x7E00_0280,
0x7E02_0280, // v0, v1 = coordinates
0x7E04_0281,
0x7E06_0282,
0x7E08_0283,
0x7E0A_0284, // v2..v5 = 1..4
0xF000_2008 | opcode << 18 | mask << 8,
0x0002_0200,
// Use the old value in a second atomic at the same location.
0xF044_0008 | (if wide { 3 } else { 1 }) << 8,
0x0002_0200,
0xBF81_0000,
];
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 6,
layout: vec![RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 0,
slot: 0,
}],
used: vec![],
io: StageIo::Cs(ComputeIo {
rsrc2: 2,
threads: [32, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let p = ir::build(&native.code, false, native.vgprs).unwrap();
let bytes = crate::dxbc::build(&[]);
let shader = emit(
&Container::parse(&bytes).unwrap(),
&native,
&p,
&structure::structure(&p).unwrap(),
&io::raise(&p, &native).unwrap(),
&resource::track(&p, &native.layout, native.stage, None).unwrap(),
)
.unwrap();
let container = Container::parse(&shader.dxil).unwrap();
let features = u64::from_le_bytes(
container
.part(FourCC::SFI0)
.unwrap()
.data
.try_into()
.unwrap(),
);
let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops
assert_eq!(features & required, if wide { required } else { 0 });
#[cfg(windows)]
if let Ok(mut v) =
validator::Validator::load(validator::Validator::default_path().as_deref())
{
v.validate(&mut shader.dxil.clone()).unwrap();
}
}
}
}
#[cfg(test)]
mod barycentric_tests {
use super::container::SigElement;
use super::*;
use crate::native::{PsInput, StageIo, Usage};
/// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER.
const PERSP_CENTER: u32 = 1 << 1;
const LINEAR_CENTER: u32 = 1 << 5;
/// `exp mrt0, v<r>, v<r>, v<r>, v<r> done vm`.
fn exp_mrt0(r: u32) -> [u32; 2] {
[0xF800_180F, r * 0x0101_0101]
}
/// VOP2 `v_add_f32 v<dst>, v<a>, v<b>`.
fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 {
3 << 25 | dst << 17 | b << 9 | (256 + a)
}
fn element(name: &str, kind: u8, row: u32) -> SigElement {
SigElement {
name: name.into(),
index: 0,
kind,
comp: 9,
interp: 0,
row: Some(row),
col: 0,
cols: 4,
usage: 0,
half: false,
}
}
/// Translates a pixel program with the input VGPRs `input_addr`
/// enables and one float4 TEXCOORD0 attribute (attr 0, row 0).
fn pixel(words: &[u32], input_addr: u32) -> Result<HostShader, ShaderError> {
let native = NativeProgram {
stage: HwStage::Ps,
wave64: false,
vgprs: 8,
layout: vec![],
used: vec![],
io: StageIo::Ps {
inputs: vec![PsInput {
usage: Usage::Generic,
row: 0,
mask: 0b1111,
attr: 0,
flat: false,
fp16: false,
pack2: false,
row2: 0,
}],
input_addr,
db_shader_control: 0,
patches: vec![],
},
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
};
let mut target = element("SV_Target", 16, 0);
target.usage = 15;
let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true);
let osg1 = container::signature(&[target], false);
let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]);
let c = Container::parse(&bytes).unwrap();
let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
let res = resource::track(&p, &native.layout, native.stage, None)?;
let io = io::raise(&p, &native)?;
let st = structure::structure(&p)?;
emit(&c, &native, &p, &st, &io, &res)
}
/// The translation's `SFI0` features and `ISG1` rows.
fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) {
let c = Container::parse(&shader.dxil).unwrap();
let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap();
(
u64::from_le_bytes(sfi0),
signature(c.part(FourCC::ISG1).unwrap().data).unwrap(),
)
}
fn validate(shader: &HostShader) {
#[cfg(windows)]
if let Ok(mut v) =
validator::Validator::load(validator::Validator::default_path().as_deref())
{
v.validate(&mut shader.dxil.clone()).unwrap();
}
let _ = shader;
}
/// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as
/// plain floats: they are channels y and z of `SV_Barycentrics`, the
/// weights of vertices 1 and 2.
#[test]
fn barycentrics_read_as_values_are_sv_barycentrics() {
let [e0, e1] = exp_mrt0(2);
let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000];
let shader = pixel(&words, PERSP_CENTER).unwrap();
let (features, inputs) = parts(&shader);
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect();
assert_eq!(bary.len(), 1, "{inputs:?}");
assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3));
// Not packed: the validator wants packing location -1.
assert_eq!(bary[0].row, None);
// Only y and z (I and J) are read.
let isg1 = Container::parse(&shader.dxil).unwrap();
let isg1 = isg1.part(FourCC::ISG1).unwrap().data;
let rw: Vec<u8> = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect();
assert!(rw.contains(&0b110), "{rw:?}");
validate(&shader);
}
/// Two kinds of barycentrics read directly: one element per mode.
#[test]
fn two_barycentric_modes_get_two_elements() {
// v0-v1 perspective i, j; v2-v3 linear i, j.
let [e0, e1] = exp_mrt0(4);
let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000];
let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap();
let (_, inputs) = parts(&shader);
let mut indices: Vec<u32> = inputs
.iter()
.filter(|e| e.kind == 28)
.map(|e| e.index)
.collect();
indices.sort();
assert_eq!(indices, [0, 1], "{inputs:?}");
validate(&shader);
}
/// I and J only fed to `v_interp_*` stay host interpolation: no
/// barycentrics are declared.
#[test]
fn interpolation_alone_declares_no_barycentrics() {
let [e0, e1] = exp_mrt0(2);
let words = [
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
e0,
e1,
0xBF81_0000,
];
let shader = pixel(&words, PERSP_CENTER).unwrap();
let (features, inputs) = parts(&shader);
assert_eq!(features & 0x2_0000, 0);
assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
validate(&shader);
}
/// Both: the attribute is interpolated and J is used as a value.
#[test]
fn interpolation_and_a_barycentric_value_together() {
let [e0, e1] = exp_mrt0(3);
let words = [
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
v_add_f32(3, 2, 1), // v3 = attribute + j
e0,
e1,
0xBF81_0000,
];
let shader = pixel(&words, PERSP_CENTER).unwrap();
let (features, inputs) = parts(&shader);
assert_ne!(features & 0x2_0000, 0);
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
validate(&shader);
}
/// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float).
fn texcoord_mode(shader: &HostShader) -> u8 {
let c = Container::parse(&shader.dxil).unwrap();
let psv = c.part(FourCC::PSV0).unwrap().data;
let row = [1, 0, 0x44, 0, 3];
let at = psv.windows(5).position(|w| w == row).unwrap();
psv[at + 5]
}
const S_ENDPGM: u32 = 0xBF81_0000;
/// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads
/// the attribute's vertices: TEXCOORD0 becomes constant, read with
/// `attributeAtVertex`; i and j are `SV_Barycentrics` values.
#[test]
fn computed_barycentrics_read_the_vertices() {
let [e0, e1] = exp_mrt0(2);
let words = [
0x1006_00F0, // v_mul_f32 v3, 0.5, v0
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
e0,
e1,
S_ENDPGM,
];
let shader = pixel(&words, PERSP_CENTER).unwrap();
let (features, inputs) = parts(&shader);
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
assert_eq!(texcoord_mode(&shader), 1);
validate(&shader);
}
/// Weights from constants alone: the vertices, no `SV_Barycentrics`.
#[test]
fn constant_weights_need_no_barycentrics() {
let [e0, e1] = exp_mrt0(2);
let words = [
0x7E06_02F0, // v_mov_b32 v3, 0.5
0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x
0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
e0,
e1,
S_ENDPGM,
];
let shader = pixel(&words, PERSP_CENTER).unwrap();
let (features, inputs) = parts(&shader);
assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature");
assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}");
assert_eq!(texcoord_mode(&shader), 1);
validate(&shader);
}
/// The same attribute interpolated with the loaded i and j and with a
/// computed j: both from its vertices, the first weighed with
/// `SV_Barycentrics`.
#[test]
fn computed_and_loaded_barycentrics_on_one_attribute() {
let [e0, e1] = exp_mrt0(2);
let words = [
0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y
0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y
0x1006_02F0, // v_mul_f32 v3, 0.5, v1
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x
v_add_f32(2, 2, 4),
e0,
e1,
S_ENDPGM,
];
let shader = pixel(&words, PERSP_CENTER).unwrap();
let (_, inputs) = parts(&shader);
assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1);
assert_eq!(texcoord_mode(&shader), 1);
validate(&shader);
}
/// P10 of an attribute the program interpolates is P1 - P0.
#[test]
fn p10_of_an_interpolated_attribute() {
let [e0, e1] = exp_mrt0(2);
let words = [
0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x
0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x
0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x
v_add_f32(2, 2, 4),
e0,
e1,
S_ENDPGM,
];
let shader = pixel(&words, PERSP_CENTER).unwrap();
assert_eq!(texcoord_mode(&shader), 1);
validate(&shader);
// Alone, what the hardware holds is not known.
let [e0, e1] = exp_mrt0(4);
let words = [0xC812_0000, e0, e1, S_ENDPGM];
assert!(pixel(&words, PERSP_CENTER).is_err());
}
}