From d65ae604ba81ee66132028b96c4e4a8dffd3565f Mon Sep 17 00:00:00 2001 From: CowboyBingus <267457386+CowboyBingus@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:24:42 -0800 Subject: [PATCH] Shaders: make static-sampler root signatures first, in one order `xcl shaders --precompile --pipelines` now translates the compute programs first, writes the distinct static-sampler sets of the programs it translated (and those of an earlier file), sorted, to `sampler-sets.txt` in the DXIL cache, and makes those root signatures before any pipeline, in the file's order. At device creation the runtime reads the same file from its DXIL cache, makes the same root signatures in the same order, and keeps them in `ABI_RS_SAMPLERS`, so pipelines with one of these sets use them. A set that is not in the file is still made when a pipeline first needs it. Measured on an RTX 5070 Ti with XCL's blob files off (XCL_PSO_DISK_CACHE=0), with an earlier local version of this change (XCL_SAMPLER_REGISTRY=, on main 689f2db plus three other PRs and local changes, largest-first pipeline order): after a full prebuild and two title runs that all made these root signatures in one order, two prebuilds were each stopped early. With that order, six compute pipelines with three static samplers took 14.9-33.9 ms each; with the reverse order, the same six took 27.9-73.2 s each. Part of #2088. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +++ crates/xcl/src/gpu/recomp/pso.rs | 73 ++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 23 +++++++- crates/xcl/src/shaders.rs | 97 +++++++++++++++++++++++++++++-- 4 files changed, 194 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0af03d753c..1ed8839967 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,14 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` sets the cap in KiB (0 turns it off). +- **`--pipelines` static-sampler sets**: the pass writes the static-sampler sets of the + compute programs it translates (and those of an earlier file), sorted, to `sampler-sets.txt` + in the DXIL cache and makes their root signatures before any pipeline, in that order; a run + whose DXIL cache has the file makes the same root signatures first, in the same order, at + device creation. On an RTX 5070 Ti with XCL's blob files off (`XCL_PSO_DISK_CACHE=0`), six + compute pipelines with static samplers that an earlier pass had compiled took 28–73 s to + create again when these root signatures were made in the reverse order, and 15–34 ms in the + earlier pass's order. - **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the window stays open until Enter. diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 00ac0a064b..351ab6bbe2 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -5,8 +5,8 @@ //! directly indexed descriptor heaps (images / samplers). Mapping the title's root arguments //! onto that ABI at draw time is the next step (needs the console runtime's user-data layout). -use std::collections::{HashMap, VecDeque}; -use std::path::PathBuf; +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::Win32::Graphics::Direct3D::ID3DBlob; @@ -1177,6 +1177,75 @@ pub fn static_sampler_desc(k: u32, (w, comparison): &StaticSampler) -> D3D12_STA } } +/// The DXIL cache's list of the static-sampler sets of a pack's compute programs, written by +/// `xcl shaders --precompile --pipelines`: one set per line, sorted by `sampler_key`, each +/// sampler `w0 w1 w2 w3 cmp` in hex, samplers separated by `;`. That pass and a title's run make +/// these root signatures first, in this order (`sampler_set_signatures`). On an RTX 5070 Ti, +/// with XCL's blob files off, six compute pipelines with static samplers that took 15-34 ms to +/// create took 28-73 s when these root signatures had been made in the reverse order. +pub const SAMPLER_SETS_FILE: &str = "sampler-sets.txt"; + +/// The key a static-sampler set's root signature is kept under (`real::abi_rs_for`, +/// `xcl shaders --pipelines`). +pub fn sampler_key(samplers: &[StaticSampler]) -> Vec { + samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect() +} + +/// `SAMPLER_SETS_FILE`'s text for these sets: sorted by `sampler_key`, each once, without the +/// empty set (that one is the plain ABI root signature). +pub fn sampler_sets_text(sets: impl IntoIterator>) -> String { + let sorted: BTreeMap, Vec> = sets.into_iter().filter(|s| !s.is_empty()).map(|s| (sampler_key(&s), s)).collect(); + sorted + .values() + .map(|set| set.iter().map(|(w, c)| format!("{:x} {:x} {:x} {:x} {}", w[0], w[1], w[2], w[3], *c as u32)).collect::>().join(";") + "\n") + .collect() +} + +/// The sets of a `SAMPLER_SETS_FILE` text, in file order. A line that does not parse is left out. +pub fn parse_sampler_sets(text: &str) -> Vec> { + let sampler = |s: &str| -> Option { + let v: Vec = s.split_whitespace().map(|x| u32::from_str_radix(x, 16)).collect::>().ok()?; + match v[..] { + [a, b, c, d, cmp @ (0 | 1)] => Some(([a, b, c, d], cmp == 1)), + _ => None, + } + }; + text.lines().filter(|l| !l.trim().is_empty()).filter_map(|l| l.split(';').map(sampler).collect()).collect() +} + +/// The root signatures of the sets in `dir`'s `SAMPLER_SETS_FILE`, made on `dev` one after +/// another in file order, with their `sampler_key`s (none when there is no file). +pub fn sampler_set_signatures(dev: &ID3D12Device, dir: &Path) -> Result, ID3D12RootSignature)>, String> { + let path = dir.join(SAMPLER_SETS_FILE); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(format!("{}: {e}", path.display())), + }; + parse_sampler_sets(&text).iter().map(|set| abi_root_signature_with(dev, true, set).map(|rs| (sampler_key(set), rs))).collect() +} + +#[cfg(test)] +mod sampler_sets_tests { + use super::{parse_sampler_sets, sampler_key, sampler_sets_text, StaticSampler}; + + #[test] + fn sampler_sets_are_written_sorted_once_and_read_back_in_file_order() { + let a: Vec = vec![([0x3092, 0xc00000, 0x18500000, 0], true)]; + let b: Vec = vec![([0x92, 0xc00000, 0x14500000, 0], false), ([0x3092, 0xc00000, 0x18500000, 0], true)]; + let c: Vec = vec![([0, 0xc00000, 0x18500000, 0], false)]; + let text = sampler_sets_text([a.clone(), vec![], b.clone(), c.clone(), a.clone()]); + assert_eq!(text, "0 c00000 18500000 0 0\n92 c00000 14500000 0 0;3092 c00000 18500000 0 1\n3092 c00000 18500000 0 1\n"); + // the order does not depend on the order the sets were found in + assert_eq!(sampler_sets_text([c.clone(), a.clone(), b.clone()]), text); + let sets = parse_sampler_sets(&text); + assert_eq!(sets, vec![c, b, a]); + assert!(sets.windows(2).all(|w| sampler_key(&w[0]) < sampler_key(&w[1]))); + // a line that does not parse is left out, the others keep their order + assert_eq!(parse_sampler_sets("1 2 3 4 0\n1 2 3 4 2\nzz 2 3 4 0\n\n5 6 7 8 1\n"), vec![vec![([1, 2, 3, 4], false)], vec![([5, 6, 7, 8], true)]]); + } +} + /// The ABI root signature with the pipeline's static samplers (registers 0.., space 1). pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler]) -> Result { abi_signature(dev, graphics, samplers, false) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4ea6374885..ca262176f4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -545,6 +545,7 @@ pub fn init() -> Result { let _ = q.RegisterMessageCallback(Some(debug_message), D3D12_MESSAGE_CALLBACK_FLAG_NONE, std::ptr::null_mut(), &mut cookie); } } + make_sampler_set_signatures(&device); open_uma(&device); super::device_x::probe_dynamic_depth_bias(&device); let raw = device.into_raw(); // one reference kept for the process lifetime @@ -3872,12 +3873,32 @@ pub fn pso_root_signature(pso: usize) -> Option { /// ABI root signatures with static samplers, by sampler set (owned here, never released). static ABI_RS_SAMPLERS: Mutex, usize>>> = Mutex::new(None); +/// At device creation, before any pipeline: the root signatures of the DXIL cache's +/// `SAMPLER_SETS_FILE` (`xcl shaders --precompile --pipelines`) made in its order, as that pass +/// made them, and used for every pipeline with one of these sets (`abi_rs_for`). +fn make_sampler_set_signatures(device: &ID3D12Device) { + use crate::gpu::recomp::{dxc, pso}; + match pso::sampler_set_signatures(device, &dxc::cache_dir()) { + Ok(made) if made.is_empty() => {} + Ok(made) => { + let n = made.len(); + let mut g = ABI_RS_SAMPLERS.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + for (key, rs) in made { + map.entry(key).or_insert(rs.into_raw() as usize); + } + crate::xlog_info!("D3D12.X: {n} static-sampler root signatures made first, in the order of {}", pso::SAMPLER_SETS_FILE); + } + Err(e) => crate::xlog_warn!("D3D12.X: static-sampler root signatures of {}: {e}", pso::SAMPLER_SETS_FILE), + } +} + /// The XCL ABI root signature with a pipeline's static samplers (the plain one without). unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> Option<*mut c_void> { if samplers.is_empty() { return abi_rs_raw(this); } - let key: Vec = samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect(); + let key = crate::gpu::recomp::pso::sampler_key(samplers); let mut g = ABI_RS_SAMPLERS.lock().unwrap(); let map = g.get_or_insert_with(HashMap::new); if let Some(&rs) = map.get(&key) { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ff9ac68b2e..b4d6469cce 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1117,7 +1117,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl /// mesh pass-through, which the runtime builds for its pixel shader. /// `--pipelines`: each compute program's pipeline made on the GPU as a title's would be (XCL's /// ABI root signature with its static samplers). Save the driver's compiled blob in the same -/// cache the runtime reads at startup. Nothing runs on the GPU. +/// cache the runtime reads at startup. Nothing runs on the GPU. The pipelines are made once every +/// program is translated, after the root signatures of their static-sampler sets, in the order +/// the runtime makes them in too (`Pipelines::first_signatures`). /// Programs whose DXIL is over `XCL_PIPELINE_MAX_KB` (8 MiB by default; 0 turns the cap off) /// and that have no blob yet are counted as capped and left to the runtime: their driver /// compile takes tens of minutes and gigabytes, and stopped the pass on the biggest programs @@ -1202,6 +1204,50 @@ mod pipeline_cap_tests { } } +#[cfg(test)] +mod sampler_set_tests { + use super::{recomp, Pipelines}; + use recomp::pso::{sampler_key, Compiled, StaticSampler}; + + #[test] + fn prebuild_and_runtime_make_the_sampler_set_root_signatures_in_one_order() { + struct Scratch(std::path::PathBuf); + impl Drop for Scratch { + fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } + } + let pipelines = match Pipelines::new() { + Ok(pipelines) => pipelines, + Err(reason) => { + recomp::runner::skip_test(&format!("no D3D12 device: {reason}")); + return; + } + }; + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let scratch = Scratch(std::env::temp_dir().join(format!("xcl-sampler-sets-{}-{nonce}", std::process::id()))); + let a: Vec = vec![([0x3092, 0xc00000, 0x18500000, 0], true)]; + let b: Vec = vec![([0x92, 0xc00000, 0x14500000, 0], false), ([0x3092, 0xc00000, 0x18500000, 0], true)]; + let c: Vec = vec![([0, 0xc00000, 0x18500000, 0], false)]; + let program = |samplers: &Vec| Compiled { dispatch_chain: None, dxil: Vec::new(), samplers: samplers.clone() }; + let sorted = vec![sampler_key(&c), sampler_key(&b), sampler_key(&a)]; + + // the pass, in the order the programs were translated, with one set twice and one program without samplers + let made = pipelines.first_signatures(&scratch.0, &[program(&a), program(&vec![]), program(&b), program(&a), program(&c)]).expect("first signatures"); + assert_eq!(made, sorted); + let text = std::fs::read_to_string(scratch.0.join(recomp::pso::SAMPLER_SETS_FILE)).expect("sampler-sets file"); + assert_eq!(text, recomp::pso::sampler_sets_text([c.clone(), b.clone(), a.clone()])); + assert_eq!(pipelines.signatures.lock().unwrap().len(), 3); + + // a later pass over fewer programs keeps the earlier sets and their order + assert_eq!(pipelines.first_signatures(&scratch.0, &[program(&b)]).expect("second pass"), sorted); + + // the runtime at device creation (`real::make_sampler_set_signatures`): the same sets, in the same order + let runtime: Vec> = recomp::pso::sampler_set_signatures(&pipelines.dev, &scratch.0).expect("runtime signatures").into_iter().map(|(key, _)| key).collect(); + assert_eq!(runtime, sorted); + // no file: nothing made + assert!(recomp::pso::sampler_set_signatures(&pipelines.dev, &scratch.0.join("none")).expect("no file").is_empty()); + } +} + // D3D12 devices and root signatures are free-threaded unsafe impl Sync for Pipelines {} @@ -1227,7 +1273,7 @@ impl Pipelines { fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { use windows::Win32::Graphics::Direct3D12::*; - let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); + let key = recomp::pso::sampler_key(&c.samplers); let rs = { let mut g = self.signatures.lock().unwrap(); match g.get(&key) { @@ -1318,6 +1364,38 @@ impl Pipelines { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } } + + /// The static-sampler sets of `compiled`, and those of `dir`'s earlier `SAMPLER_SETS_FILE`, + /// written to that file sorted, and their root signatures made first, in the file's order: the + /// order a title's run makes them in at device creation (`real::make_sampler_set_signatures`). + /// The keys, in the order they were made. + fn first_signatures(&self, dir: &Path, compiled: &[recomp::pso::Compiled]) -> Result>, String> { + let path = dir.join(recomp::pso::SAMPLER_SETS_FILE); + let earlier = match std::fs::read_to_string(&path) { + Ok(text) => recomp::pso::parse_sampler_sets(&text), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(), + Err(e) => return Err(format!("{}: {e}", path.display())), + }; + let text = recomp::pso::sampler_sets_text(earlier.into_iter().chain(compiled.iter().map(|c| c.samplers.clone()))); + std::fs::create_dir_all(dir).and_then(|()| std::fs::write(&path, text)).map_err(|e| format!("{}: {e}", path.display()))?; + let made = recomp::pso::sampler_set_signatures(&self.dev, dir)?; + let mut g = self.signatures.lock().unwrap(); + Ok(made.into_iter().map(|(key, rs)| { g.entry(key.clone()).or_insert(rs); key }).collect()) + } + + /// The compute pipelines of `compiled`, on `most` threads. + fn make_all(&self, compiled: &[recomp::pso::Compiled]) { + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..self.most { + s.spawn(|| { + while let Some(c) = compiled.get(next.fetch_add(1, Ordering::Relaxed)) { + self.make(c); + } + }); + } + }); + } } /// A compute program a title used in an earlier run (`--used-only`): its pipeline's key, as the @@ -1344,6 +1422,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let errors: Mutex> = Mutex::new(Vec::new()); let unused = AtomicUsize::new(0); + // `--pipelines`: made once every program is translated, after their static-sampler root + // signatures (`Pipelines::first_signatures`) + let to_make: Mutex> = Mutex::new(Vec::new()); if let Some(u) = used { println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len()); } @@ -1387,8 +1468,8 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { - if let Some(p) = pipelines { - p.make(&c); + if pipelines.is_some() { + to_make.lock().unwrap().push(c); } compiled.fetch_add(1, Ordering::Relaxed) } @@ -1450,6 +1531,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }); } }); + if let Some(p) = pipelines { + let to_make = to_make.into_inner().unwrap(); + match p.first_signatures(&recomp::dxc::cache_dir(), &to_make) { + Ok(keys) => println!("static-sampler root signatures made first: {} (in the order of {})", keys.len(), recomp::pso::SAMPLER_SETS_FILE), + Err(e) => eprintln!("xcl shaders --pipelines: static-sampler root signatures: {e}"), + } + p.make_all(&to_make); + } println!( "compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}, time {:.1} s", compiled.into_inner(),