Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,14 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window.
`XCL_PREPARE=0` leaves the preparation out: the game starts at once and builds the shaders it
uses as it goes (it stands still while they build).
- **`XCL_RT_LEAVE_OUT=<fragment>[,<fragment>…]`** (off by default): compute programs whose shader
container holds one of the fragments (at least 6 bytes each; a program name from the
container's debug data, found with `xcl rpf <pack> --find`) are left out: the title's pipeline
gets a dummy program, its dispatches are skipped, and the preparation and `--precompile` pass
them over. Meant for a title's ray-tracing hit-shading and ray-start programs while it builds
no acceleration structure (every ray misses). XCL warns once in the log when a structure a
view names gets a root node; from then on rays can hit, and the setting should be removed.
Ported from Vice-Tay (see `THIRD_PARTY.md`).
- For compute shaders that XCL can split, the runtime first tries the saved driver blob for
the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing
or the driver rejects it, XCL builds the split pieces.
Expand Down
1 change: 1 addition & 0 deletions THIRD_PARTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0
| [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables |
| [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation |
| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables |
| [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) (built on VIctory) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs`: port of the ray-tracing leave-out of its `crates/victory-gpu/src/pipeline/make.rs` (`left_out`, commit `1f69d67`; added in codec_d's `8cc31ab`), changed 2026-11-27 | port with annotation |
| [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts |
| [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only |
| [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification |
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/gpu/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub(crate) mod fence;
pub mod pack;
pub mod rdna2;
pub mod recomp;
pub mod rt_leave_out;
mod rdna2_spec;
mod rdna2_xbox;
pub mod shader;
Expand Down
183 changes: 183 additions & 0 deletions crates/xcl/src/gpu/rt_leave_out.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
//! `XCL_RT_LEAVE_OUT=<fragment>[,<fragment>…]` (off by default): compute programs whose shader
//! container holds one of the fragments are left out – the title's pipeline gets the dummy
//! compute program a console shader that cannot be translated gets, so its dispatches are
//! skipped, and the shader preparation and `xcl shaders --precompile` pass them over.
//!
//! What it is for: a title's ray-tracing programs that shade the hits of rays or start rays
//! (on a retail title about 1,000 programs, ~1 MB of DXIL each, the largest of its cold driver
//! compiles) do nothing while the title has built no acceleration structure: every ray misses.
//! The fragments name those programs (a name in the container's debug data; find it with
//! `xcl rpf <pack> --find`); XCL's source names no title's programs.
//!
//! So that leaving them out stays harmless, XCL watches the acceleration structures the
//! title's views name (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` in unified
//! memory) and warns once when one of them gets a root node: from then on rays can hit, and
//! the programs left out would have shaded those hits.
//!
//! Ported from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later), commit
//! `1f69d67`, `crates/victory-gpu/src/pipeline/make.rs` (`left_out`: `VICTORY_RT_RESOLVE`,
//! `VICTORY_ACTIVATE_RAYS`, `VICTORY_BVH_BUILDER`; there since codec_d's `8cc31ab`).
//! Changes (2026-11-27): the programs are named by the user's fragments instead of names in
//! the source; one switch; the structure watch and its warning are new; the preparation and
//! the precompile pass the programs over.

use std::collections::BTreeSet;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};

/// Fragments shorter than this are refused: they would match bytes of any container.
const SHORTEST: usize = 6;
/// Acceleration structures remembered for the watch (distinct addresses).
const MOST_STRUCTURES: usize = 4096;

/// The fragments of a `XCL_RT_LEAVE_OUT` value: comma-separated, trimmed, at least
/// [`SHORTEST`] bytes each (shorter ones are dropped).
pub fn fragments_of(value: &str) -> Vec<Vec<u8>> {
value.split(',').map(str::trim).filter(|f| f.len() >= SHORTEST).map(|f| f.as_bytes().to_vec()).collect()
}

/// Whether `container` holds one of `fragments`.
pub fn holds_any(container: &[u8], fragments: &[Vec<u8>]) -> bool {
fragments.iter().any(|f| container.windows(f.len()).any(|w| w == f.as_slice()))
}

fn fragments() -> &'static [Vec<u8>] {
static F: OnceLock<Vec<Vec<u8>>> = OnceLock::new();
F.get_or_init(|| {
let Ok(v) = std::env::var("XCL_RT_LEAVE_OUT") else { return Vec::new() };
let f = fragments_of(&v);
let dropped = v.split(',').map(str::trim).filter(|s| !s.is_empty() && s.len() < SHORTEST).count();
if f.is_empty() {
crate::xlog_warn!("XCL_RT_LEAVE_OUT: no fragment of at least {SHORTEST} bytes – nothing is left out");
} else {
crate::xlog_info!(
"XCL_RT_LEAVE_OUT: compute programs holding one of {} fragment(s) are left out while rays cannot hit{}",
f.len(),
if dropped > 0 { format!(" ({dropped} shorter than {SHORTEST} bytes ignored)") } else { String::new() }
);
}
f
})
}

/// Whether the switch is on (at least one usable fragment).
pub fn enabled() -> bool {
!fragments().is_empty()
}

static LEFT_OUT: AtomicU64 = AtomicU64::new(0);

/// Whether the compute program in `container` is left out; counts and logs the first few.
pub fn left_out(container: &[u8]) -> bool {
if !enabled() || !holds_any(container, fragments()) {
return false;
}
let n = LEFT_OUT.fetch_add(1, Ordering::Relaxed) + 1;
if n <= 3 || n.is_power_of_two() {
crate::xlog_info!(
"XCL_RT_LEAVE_OUT: compute program of record {:016x} left out (#{n}): its dispatches are skipped",
crate::gpu::shader::fnv64(container)
);
}
true
}

/// How many compute programs were left out so far.
pub fn left_out_count() -> u64 {
LEFT_OUT.load(Ordering::Relaxed)
}

static STRUCTURES: Mutex<BTreeSet<u64>> = Mutex::new(BTreeSet::new());

/// An acceleration structure in unified memory that a title's view names (only kept while the
/// switch is on).
pub fn note_structure(va: u64) {
if enabled() {
let mut s = STRUCTURES.lock().unwrap();
if s.len() < MOST_STRUCTURES {
s.insert(va);
}
}
}

/// The root node id in an acceleration structure's header: `None` while it has none (0 or
/// all ones, as before a build).
pub fn root_of(header: &[u8]) -> Option<u32> {
let at = crate::gpu::bvh::ROOT_AT;
let root = u32::from_le_bytes(header.get(at..at + 4)?.try_into().ok()?);
(root != 0 && root != u32::MAX).then_some(root)
}

/// Looks at the structures views named (called every few hundred frames): warns once when one
/// has a root node, since the programs left out would then have hits to shade.
pub fn check_structures() {
static WARNED: AtomicBool = AtomicBool::new(false);
if !enabled() || WARNED.load(Ordering::Relaxed) {
return;
}
let all: Vec<u64> = STRUCTURES.lock().unwrap().iter().copied().collect();
let header = crate::gpu::bvh::HEADER_BYTES;
for va in all {
let p = va as usize;
if !crate::gpu::shader::readable(p, header) {
continue;
}
// SAFETY: `readable` just checked the range; title memory, only read
let bytes = unsafe { std::slice::from_raw_parts(p as *const u8, header) };
if let Some(root) = root_of(bytes) {
if !WARNED.swap(true, Ordering::Relaxed) {
crate::xlog_warn!(
"XCL_RT_LEAVE_OUT: the acceleration structure at {va:#x} has a root node ({root:#x}) now – rays can hit, and the {} compute program(s) left out would shade those hits; run without XCL_RT_LEAVE_OUT for this title",
left_out_count()
);
}
return;
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn fragments_are_trimmed_and_short_ones_dropped() {
let f = fragments_of(" ResolveA ,abc, ,LongerName,");
assert_eq!(f, vec![b"ResolveA".to_vec(), b"LongerName".to_vec()]);
assert!(fragments_of("").is_empty());
assert!(fragments_of("short").is_empty());
}

#[test]
fn a_container_is_matched_by_any_fragment_anywhere() {
let mut container = vec![0u8; 64];
container.extend_from_slice(b"\x00prog_Example_Name_x\x00");
container.extend_from_slice(&[0xFF; 32]);
assert!(holds_any(&container, &fragments_of("Other_Name,Example_Name")));
assert!(!holds_any(&container, &fragments_of("Example_Names")));
assert!(!holds_any(&container, &[]));
// a fragment at the very end still matches
assert!(holds_any(b"xxxxEnd_of_it", &fragments_of("End_of_it")));
}

#[test]
fn a_header_without_a_root_has_none() {
let mut h = vec![0u8; crate::gpu::bvh::HEADER_BYTES];
assert_eq!(root_of(&h), None);
let at = crate::gpu::bvh::ROOT_AT;
h[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(root_of(&h), None);
h[at..at + 4].copy_from_slice(&0x25u32.to_le_bytes());
assert_eq!(root_of(&h), Some(0x25));
assert_eq!(root_of(&h[..at]), None, "a header too short to hold the root");
}

#[test]
fn a_built_structure_from_the_builder_has_a_root() {
// XCL's own builder writes the console layout the watch reads
let tris = crate::gpu::bvh::tests::random_tris(8, 3);
let b = crate::gpu::bvh::build(&tris, 0);
let root = root_of(&b.data).expect("a built structure has a root id");
assert_eq!(root, b.root);
}
}
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u
if let Some(t) = LAST.lock().unwrap().replace(now) {
crate::xlog_info!("D3D12.X: {frames} frames presented, {:.1} fps over the last 300", 300.0 / (now - t).as_secs_f64());
}
crate::gpu::rt_leave_out::check_structures();
}
super::real::stop_if_device_removed();
if !PRESENTX.swap(true, Ordering::Relaxed) {
Expand Down
32 changes: 30 additions & 2 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2266,6 +2266,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void,
let va = v.Anonymous.RaytracingAccelerationStructure.Location;
let in_uma = va != 0 && crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize));
if in_uma {
crate::gpu::rt_leave_out::note_structure(va);
let w = crate::gpu::desc::bvh_words(va, true);
return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]);
}
Expand Down Expand Up @@ -5766,10 +5767,27 @@ unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) {
}
}

/// Whether `desc`'s console compute program is one `XCL_RT_LEAVE_OUT` leaves out.
unsafe fn rt_left_out(desc: *const c_void) -> bool {
if !crate::gpu::rt_leave_out::enabled() || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_COMPUTE_PIPELINE_STATE_DESC>()) {
return false;
}
let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC);
shader_bytes(&d.CS).is_some_and(|cs| crate::gpu::recomp::pso::is_console(cs) && crate::gpu::rt_leave_out::left_out(cs))
}

unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
super::null::capture_compute_desc(desc as *const u8);
let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState")));
let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) };
// `XCL_RT_LEAVE_OUT`: not translated or built; the dummy program below, its dispatches skipped
let left_out = rt_left_out(desc);
let (mut console, missed) = if left_out {
(Some(Err(())), false)
} else if super::pso_async::enabled() {
attempt(|| translated_compute_pso(this, f, desc, riid, ppv))
} else {
(translated_compute_pso(this, f, desc, riid, ppv), false)
};
if missed {
if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, compute_key, build_compute)) {
// a console program the worker is translating (its root signature comes with it);
Expand All @@ -5796,8 +5814,18 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const
let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC);
copy.CS = bytecode(&dummy().cs);
copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
// a program left out of a desc without a root signature (its console container carries its
// own): the dummy, which binds nothing, gets XCL's ABI root signature – the driver refuses a
// compute pipeline without one
if left_out && std::mem::transmute_copy::<_, usize>(&copy.pRootSignature) == 0 {
if let Some(rs) = abi_rs_for(this, &[]) {
copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs);
}
}
let hr2 = finish_pso(this, f, &copy as *const _ as *const c_void, riid, ppv);
note_fallback("compute PSO", hr, hr2 >= 0);
if !left_out || hr2 < 0 {
note_fallback("compute PSO", hr, hr2 >= 0);
}
if console.is_some() {
note_console_compute(hr2, ppv);
}
Expand Down
8 changes: 8 additions & 0 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1884,6 +1884,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
// a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`):
// into the translation cache too, so the title does not translate it again
if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) {
// the title's pipeline would leave it out too (`gpu::rt_leave_out`)
if crate::gpu::rt_leave_out::left_out(&blob) {
record_done();
continue;
}
match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) {
Ok(c) => {
if let Some(p) = pipelines {
Expand Down Expand Up @@ -1981,6 +1986,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
skipped.into_inner(),
t0.elapsed().as_secs_f64()
);
if crate::gpu::rt_leave_out::enabled() {
println!("compute programs passed over (XCL_RT_LEAVE_OUT): {}", crate::gpu::rt_leave_out::left_out_count());
}
if let Some(p) = pipelines {
if startup.is_none() {
make_pipelines(p, pipeline_jobs.into_inner().unwrap());
Expand Down
Loading
Loading