diff --git a/README.md b/README.md index c086a8e64e..456e8faed1 100644 --- a/README.md +++ b/README.md @@ -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=[,…]`** (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 --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. diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..76b910929a 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -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 | diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 0264fdb555..13c6d68bce 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -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; diff --git a/crates/xcl/src/gpu/rt_leave_out.rs b/crates/xcl/src/gpu/rt_leave_out.rs new file mode 100644 index 0000000000..762acb7114 --- /dev/null +++ b/crates/xcl/src/gpu/rt_leave_out.rs @@ -0,0 +1,183 @@ +//! `XCL_RT_LEAVE_OUT=[,…]` (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 --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> { + 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]) -> bool { + fragments.iter().any(|f| container.windows(f.len()).any(|w| w == f.as_slice())) +} + +fn fragments() -> &'static [Vec] { + static F: OnceLock>> = 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> = 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 { + 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 = 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); + } +} diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 482f2d1ec2..2b4b3c7eff 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -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) { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 19eedfe6ac..60bfc91260 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -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]); } @@ -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::()) { + 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); @@ -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>(©.pRootSignature) == 0 { + if let Some(rs) = abi_rs_for(this, &[]) { + copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + } + } let hr2 = finish_pso(this, f, © 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); } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 91441570eb..7cfd5d1b18 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1884,6 +1884,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, 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 { @@ -1981,6 +1986,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, 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()); diff --git a/crates/xcl/tests/gpu_compute_e2e.rs b/crates/xcl/tests/gpu_compute_e2e.rs index 5ffa519a96..7963d018d6 100644 --- a/crates/xcl/tests/gpu_compute_e2e.rs +++ b/crates/xcl/tests/gpu_compute_e2e.rs @@ -412,6 +412,114 @@ fn mirror_program_through_the_hook(dev: &ID3D12Device) { } } +/// The fragment `rt_leave_out_skips_the_named_program_and_builds_the_other` names its program by. +const LEAVE_OUT_MARK: &[u8; 16] = b"XCLTEST_LEAVEOUT"; + +/// The mirror program's container with `LEAVE_OUT_MARK` in its XDAT hash entry (16 bytes no +/// translation reads): the same program, now holding the fragment. +fn named_for_leave_out() -> Vec { + let mut blob = console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1]); + let at = blob.windows(16).position(|w| w == [0x5a; 16]).expect("the XDAT hash entry"); + blob[at..at + 16].copy_from_slice(LEAVE_OUT_MARK); + blob +} + +/// The CreateComputePipelineState hook with the mirror program's root layout (or, `with_rs` +/// false, no root signature in the desc, as a title whose containers carry theirs passes it); +/// the pipeline after a background build. +fn compute_pso_through_the_hook(dev: &ID3D12Device, blob: &[u8], with_rs: bool) -> usize { + let game_rs: ID3D12RootSignature = unsafe { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + }; + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(with_rs.then_some(game_rs)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: blob.as_ptr() as _, BytecodeLength: blob.len() }, + ..Default::default() + }; + let pso: Result = unsafe { dev.CreateComputePipelineState(&desc) }; + unsafe { std::mem::ManuallyDrop::drop(&mut desc.pRootSignature) }; + let pso = pso.expect("CreateComputePipelineState through the backend hook"); + let resolved = xcl::hle::d3d12x::pso_async::resolve_wait(pso.as_raw() as usize); + std::mem::forget(pso); // kept for the process, as a title keeps its pipelines + resolved +} + +/// `XCL_RT_LEAVE_OUT` (#3011, C3) on the paths it changes. Of two console compute programs, the +/// one whose container holds the fragment is left out: +/// - in the CreateComputePipelineState hook it gets the dummy program a console shader that +/// cannot be translated gets (a console compute pipeline, not a translated one), and is not +/// translated, also from a desc without a root signature; +/// - `xcl shaders --precompile --pipelines` passes it over. +/// The other program is translated and built as without the switch. The switch is read once +/// per process, so each path runs in a child process that has it set. +#[test] +fn rt_leave_out_skips_the_named_program_and_builds_the_other() { + use std::{fs, process::Command}; + let fragment = std::str::from_utf8(LEAVE_OUT_MARK).unwrap(); + if std::env::var("XCL_TEST_RT_LEAVE_OUT").is_ok_and(|v| v == "hook") { + assert_eq!(std::env::var("XCL_RT_LEAVE_OUT").as_deref(), Ok(fragment)); + assert_eq!(xcl::hle::d3d12x::backend(), xcl::hle::d3d12x::Backend::Real); + let raw = real::device_raw(); + let dev = unsafe { ID3D12Device::from_raw_borrowed(&raw) }.unwrap().clone(); + let named = named_for_leave_out(); + let plain = console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1]); + assert!(xcl::gpu::rt_leave_out::holds_any(&named, &xcl::gpu::rt_leave_out::fragments_of(fragment))); + assert!(!xcl::gpu::rt_leave_out::holds_any(&plain, &xcl::gpu::rt_leave_out::fragments_of(fragment))); + + let before = real::stats(); + let left = compute_pso_through_the_hook(&dev, &named, true); + let after_named = real::stats(); + assert_eq!(xcl::gpu::rt_leave_out::left_out_count(), 1, "the named program is left out"); + assert_eq!(after_named.translated_pipelines, before.translated_pipelines, "the named program was translated"); + assert!(real::is_console_compute(left), "the named program's pipeline is a console compute pipeline"); + assert!(!real::is_translated_compute(left), "the named program's pipeline is the dummy, not a translated one"); + // a desc without a root signature: the dummy gets one of XCL's, the driver refuses none + let left_bare = compute_pso_through_the_hook(&dev, &named, false); + assert_eq!(xcl::gpu::rt_leave_out::left_out_count(), 2, "the named program is left out without a root signature too"); + assert!(real::is_console_compute(left_bare) && !real::is_translated_compute(left_bare)); + + let built = compute_pso_through_the_hook(&dev, &plain, true); + let after_plain = real::stats(); + assert_eq!(xcl::gpu::rt_leave_out::left_out_count(), 2, "the other program is not left out"); + assert_eq!(after_plain.translated_pipelines, before.translated_pipelines + 1, "the other program was not translated: {:?}", after_plain.translation_errors); + assert!(real::is_translated_compute(built), "the other program's pipeline is a translated one"); + return; + } + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if xcl::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + if runner::wave64_programs_supported() != Ok(true) { + return runner::skip_test("no GPU with 32- or 64-lane waves"); + } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("xcl-rt-leave-out-{}-{nonce}", std::process::id())); + let input = dir.join("input"); + fs::create_dir_all(&input).unwrap(); + fs::write(input.join("named.bin"), named_for_leave_out()).unwrap(); + fs::write(input.join("plain.bin"), console_cs(&program(), 2 << 1 | 1 << 7 | 1 << 8 | 1 << 11, [16, 8, 1])).unwrap(); + + // the precompile: one pipeline made, one program passed over + let out = Command::new(env!("CARGO_BIN_EXE_xcl")).arg("shaders").arg(&input).args(["--precompile", "--pipelines"]) + .env("XCL_DXIL_CACHE", dir.join("cache-precompile")).env("XCL_PSO_DISK_CACHE", "0") + .env("XCL_RT_LEAVE_OUT", fragment).env("TMP", &dir).env("TEMP", &dir).output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!(out.status.success(), "{text}\n{}", String::from_utf8_lossy(&out.stderr)); + assert!(text.contains("pipelines made on the GPU 1, refused 0"), "{text}"); + assert!(text.contains("compute programs passed over (XCL_RT_LEAVE_OUT): 1"), "{text}"); + + // the hook, in a process of its own with the switch set and a cold DXIL cache + let out = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "rt_leave_out_skips_the_named_program_and_builds_the_other", "--nocapture"]) + .env("XCL_TEST_RT_LEAVE_OUT", "hook").env("XCL_RT_LEAVE_OUT", fragment) + .env("XCL_DXIL_CACHE", dir.join("cache-hook")).env("XCL_PSO_DISK_CACHE", "0").output().unwrap(); + assert!(out.status.success(), "{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + let _ = fs::remove_dir_all(&dir); +} + /// A driver that refuses a pipeline with heap windows (E_OUTOFMEMORY, as NVIDIA 616.92 does /// with some big retail programs, #156) gets the program again in the switch form, and the /// pipeline from it runs correctly. The refusals are injected (`real::inject_heap_window_oom`).