From 88bc67da0332ece5d7cea5356c89bf34e79a7046 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:33:35 -0500 Subject: [PATCH 01/22] xcl run: a pack's compute pipelines are prepared by worker processes The driver builds about two pipelines at a time for one process, so the preparation before a title (#2555) stood for minutes on each stretch of large compute programs. The stages are still translated in the host; the compute pipelines are built by worker processes of the same program, each on its own slice of the records: the processors less two, 16 at most, 3 GB of the commit left for each (XCL_PREPARE_WORKERS; 1: as before). With a list of the pipelines an earlier run used, only those are built before the title starts. A worker that fails is logged and the title starts; a worker ends when the host does. A worker reports every record while a title waits on it, and the host logs its progress every 5 s. Measured on a retail title, RTX 5090, 32 threads: the first 92 % of the steps in 85 s (one process: 84 % of one pass after several minutes). Co-Authored-By: Claude Fable 5.2 --- .../xcl/src/hle/d3d12x/present/preparation.rs | 6 + crates/xcl/src/shaders.rs | 168 +++++++++++++++++- 2 files changed, 170 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index ba9f22257d..c29e20bf3b 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -59,7 +59,13 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { } else { None }; let result = std::thread::scope(|scope| { let worker = scope.spawn(|| prepare_for_launch(root, &progress)); + // (a line every 5 s: a log that stands still for long reads as a frozen process) + let (began, mut said) = (Instant::now(), Instant::now()); while !worker.is_finished() { + if said.elapsed() >= Duration::from_secs(5) { + said = Instant::now(); + crate::xlog_info!("Shader preparation: {} of {} steps after {} s", progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed), began.elapsed().as_secs()); + } if let Some(parent) = &parent { if unsafe { WaitForSingleObject(parent.as_raw_handle(), 80) } == WAIT_OBJECT_0 { // The launcher was stopped during preparation. Do not leave an orphan compile or start the title. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index b41799ec84..67ede5e96f 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1790,14 +1790,144 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R progress.total.store(inputs.iter().map(Input::len).sum(), Ordering::Relaxed); let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } + let workers = prepare_workers(); for input in inputs { if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + // a pack: its stages here, its compute pipelines in worker processes (the driver builds + // about two pipelines at a time for one process, whatever the processors) + if workers > 1 && matches!(input, Input::Pack { .. }) { + let n = input.len(); + progress.total.fetch_add(n, Ordering::Relaxed); + precompile(&input, usize::MAX, windows, None, None, false, None, None, std::time::Instant::now(), Some(progress))?; + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + pipelines_in_workers(&pack, windows, workers, n, progress)?; + continue; + } precompile(&input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress))?; } Ok(()) } +/// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title +/// starts (1: in this process, as before). Unset: the processors less two, 16 at most, and no +/// more than 3 GB of the commit the system has left for each. +fn prepare_workers() -> usize { + if let Some(n) = std::env::var("XCL_PREPARE_WORKERS").ok().and_then(|v| v.parse::().ok()) { + return n.clamp(1, 32); + } + let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + let (used, limit) = crate::host::system_commit(); + workers_for(cores, limit.saturating_sub(used)) +} + +/// The workers for `cores` processors and `free_mb` of commit left. +fn workers_for(cores: usize, free_mb: u64) -> usize { + cores.saturating_sub(2).min(16).min((free_mb / 3072) as usize).max(1) +} + +/// The record count of a builder's progress line (` 400/26503 (12 s)`). +fn progress_count(line: &str) -> Option { + let (d, rest) = line.trim().split_once('/')?; + let (n, rest) = rest.split_once(' ')?; + n.parse::().ok()?; + if !rest.starts_with('(') { return None; } + d.parse().ok() +} + +/// The compute pipelines of `pack` built by `workers` processes of this program, each on its own +/// slice of the records (`XCL_PRECOMPILE_SLICE`): only the ones an earlier run of the title used +/// when that list exists (the title builds another when it first uses it). Their records count +/// into `progress`. A worker that fails is noted and the title starts all the same: it builds +/// what is missing itself. +fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { + use std::io::BufRead; + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let me = std::env::current_exe().map_err(|e| e.to_string())?; + let used_only = !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); + let before = progress.done.load(Ordering::Relaxed); + let counts: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); + let t0 = std::time::Instant::now(); + crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); + let mut children = Vec::new(); + for i in 0..workers { + let mut c = std::process::Command::new(&me); + c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + if used_only { c.arg("--used-only"); } + // (not a host, not a launcher's child: a builder that ends when this process does) + for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS"] { c.env_remove(gone); } + c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")).env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()); + if std::env::var_os("XCL_DXC_THREADS").is_none() { c.env("XCL_DXC_THREADS", "2"); } + if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", "1"); } + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).creation_flags(CREATE_NO_WINDOW); + match c.spawn() { + Ok(child) => children.push((i, child)), + Err(e) => crate::xlog_warn!("Shader preparation: worker {i} did not start: {e}"), + } + } + let cancelled = std::thread::scope(|s| { + for (i, child) in children.iter_mut() { + let Some(err) = child.stderr.take() else { continue }; + let count = &counts[*i]; + s.spawn(move || { + // (a builder ends its progress lines with a line feed; others pass by) + let mut r = std::io::BufReader::new(err); + let mut buf = Vec::new(); + while r.read_until(b'\n', &mut buf).is_ok_and(|n| n > 0) { + for part in String::from_utf8_lossy(&buf).split(['\r', '\n']) { + if let Some(d) = progress_count(part) { count.store(d, Ordering::Relaxed); } + } + buf.clear(); + } + }); + } + loop { + // (a worker counts the records of its own slice) + let d: usize = counts.iter().map(|c| c.load(Ordering::Relaxed)).sum(); + progress.done.store(before + d.min(records), Ordering::Relaxed); + if progress.cancel.load(Ordering::Relaxed) { + for (_, child) in children.iter_mut() { let _ = child.kill(); } + return true; + } + if children.iter_mut().all(|(_, child)| !matches!(child.try_wait(), Ok(None))) { return false; } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + }); + let mut failed = 0; + for (i, child) in children.iter_mut() { + match child.wait() { + Ok(st) if st.success() => {} + Ok(st) => { failed += 1; crate::xlog_warn!("Shader preparation: worker {i} ended with {st}"); } + Err(e) => { failed += 1; crate::xlog_warn!("Shader preparation: worker {i}: {e}"); } + } + } + if cancelled { return Err("Shader preparation cancelled".into()); } + progress.done.store(before + records, Ordering::Relaxed); + crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); + Ok(()) +} + +/// `XCL_PRECOMPILE_PARENT=pid` (set for a title's preparation workers): this process ends when +/// that one does, so no builder is left on the GPU behind a title that was ended. +fn end_with_parent() { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenProcess, WaitForSingleObject, INFINITE, PROCESS_SYNCHRONIZE}; + let Some(pid) = std::env::var("XCL_PRECOMPILE_PARENT").ok().and_then(|v| v.parse::().ok()) else { return }; + let h = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + if h.is_null() { + // (gone already) + std::process::exit(3); + } + let h = h as usize; + std::thread::spawn(move || unsafe { + WaitForSingleObject(h as _, INFINITE); + CloseHandle(h as _); + std::process::exit(3); + }); +} + fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, selected: Option<&std::collections::HashSet>, pipeline_threads: Option, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { + if startup.is_none() { end_with_parent(); } let pipelines = if pipelines { let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; @@ -1813,6 +1943,15 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on }; let pipelines = pipelines.as_ref(); let n = input.len().min(limit); + // `XCL_PRECOMPILE_SLICE=i/n` (experiment): this process takes only every n-th shader, from the + // i-th, so n processes share the work and each has its own driver compiler + let slice: Option<(usize, usize)> = std::env::var("XCL_PRECOMPILE_SLICE").ok().and_then(|v| { + let (i, n) = v.split_once('/')?; + Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) + }); + // a progress line every 200 records; every record for a title waiting on this builder + // (`pipelines_in_workers` shows the count) + let every = if std::env::var_os("XCL_PRECOMPILE_PARENT").is_some() { 1 } else { 200 }; let next = AtomicUsize::new(0); 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()); @@ -1854,7 +1993,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let record_done = || { let d = done.fetch_add(1, Ordering::Relaxed) + 1; if let Some(p) = startup { p.done.fetch_add(1, Ordering::Relaxed); } - if d % 200 == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } + if d % every == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } }; let (name, blob) = input.get(i); let Some(blob) = blob else { @@ -2000,9 +2139,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on for e in &errors { println!(" {e}"); } if let Some(progress) = startup { if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - let p = pipelines.expect("startup requested pipelines"); - let refused = p.refused.load(Ordering::Relaxed); - let capped = p.capped.load(Ordering::Relaxed); + // (no pipelines here when worker processes build them: `pipelines_in_workers`) + let refused = pipelines.map_or(0, |p| p.refused.load(Ordering::Relaxed)); + let capped = pipelines.map_or(0, |p| p.capped.load(Ordering::Relaxed)); if failed + refused + capped > 0 { let cause = errors.first().map(String::as_str).unwrap_or( if capped > 0 { "Raise XCL_PIPELINE_MAX_KB or set it to 0 to prepare larger pipelines." } @@ -2340,6 +2479,27 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { + /// The workers of a title's shader preparation: two processors are left free, 16 at most, + /// 3 GB of commit for each, and one where there is no room. + #[test] + fn preparation_workers_leave_two_processors_and_follow_the_commit_left() { + assert_eq!(workers_for(32, 100_000), 16); + assert_eq!(workers_for(8, 100_000), 6); + assert_eq!(workers_for(32, 10_000), 3); + assert_eq!(workers_for(2, 100_000), 1); + assert_eq!(workers_for(32, 0), 1); + } + + /// A builder's progress line gives its record count; its other lines give none. + #[test] + fn a_builders_progress_line_gives_its_count() { + assert_eq!(progress_count(" 400/26503 (12 s)"), Some(400)); + assert_eq!(progress_count("26400/26503 (1339 s)"), Some(26400)); + assert_eq!(progress_count("xcl: [SHADER] direct DXIL fallback stage=CS reason=a/b (c)"), None); + assert_eq!(progress_count(" pipelines: 50 made, 0 refused"), None); + assert_eq!(progress_count("3/4"), None); + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] From 5584a82512be45581d460d41830ca58a54f1809c Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:40:39 -0500 Subject: [PATCH 02/22] xcl run: the preparation screen counts each pass by itself, and every record The two passes were added up (twice the records), and a worker's count moved every 200 records, so the screen stood on one number for many minutes. The workers' pass has its own heading and count, a worker reports every record, and the line under the bar says a large pipeline is compiling. Workers: the logical processors less four. Co-Authored-By: Claude Fable 5.2 --- .../xcl/src/hle/d3d12x/present/preparation.rs | 18 +++++++++--- crates/xcl/src/shaders.rs | 29 ++++++++++++------- 2 files changed, 33 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index c29e20bf3b..8ef1260687 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -64,7 +64,14 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { while !worker.is_finished() { if said.elapsed() >= Duration::from_secs(5) { said = Instant::now(); - crate::xlog_info!("Shader preparation: {} of {} steps after {} s", progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed), began.elapsed().as_secs()); + let workers = progress.workers.load(Ordering::Relaxed); + crate::xlog_info!( + "Shader preparation: {} of {} records {} after {} s", + progress.done.load(Ordering::Relaxed), + progress.total.load(Ordering::Relaxed), + if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, + began.elapsed().as_secs() + ); } if let Some(parent) = &parent { if unsafe { WaitForSingleObject(parent.as_raw_handle(), 80) } == WAIT_OBJECT_0 { @@ -159,7 +166,8 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { let total = s.progress.total.load(Ordering::Relaxed); let pct = percent(done, total, s.ready); let (quiet, last) = s.clock.sample(done, s.start.elapsed()); - let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else { "Preparing shaders" }; + let workers = s.progress.workers.load(Ordering::Relaxed); + let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; let mut title = row(0,48); title.right -= scale(84); text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); @@ -167,9 +175,11 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { let bar = row(65,72); fill(dc, bar, 0x4b4038); fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); - let count = if total == 0 { "Reading shader records…".into() } else { format!("{done} of {total} records processed") }; + let count = if total == 0 { "Reading shader records…".into() } + else if workers != 0 { format!("{done} of {total} records checked by {workers} worker processes") } + else { format!("{done} of {total} records processed") }; text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); - let mut times = format!("No shader progress for {quiet} s"); + let mut times = if workers != 0 { format!("Large pipelines compile in the driver: {quiet} s since the last record") } else { format!("No shader progress for {quiet} s") }; if let Some(ago) = last { times.push_str(&format!(" · Last stall ended {ago} s ago")); } text(dc, row(117,145), ×, scale(14), 400, 0xb4aaa4, DT_LEFT); BitBlt(dest, 0, 0, rc.right, rc.bottom, dc, 0, 0, SRCCOPY); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 67ede5e96f..3081ca1eaf 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1751,6 +1751,9 @@ pub(crate) struct LaunchPreparation { pub done: AtomicUsize, pub total: AtomicUsize, pub cancel: std::sync::atomic::AtomicBool, + /// The worker processes building compute pipelines (0: none; `done` and `total` then count + /// the records translated here, with them the records the workers have passed). + pub workers: AtomicUsize, } /// Unpacked shader containers in the title's shaders directory. Do not follow directory @@ -1797,7 +1800,6 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R // about two pipelines at a time for one process, whatever the processors) if workers > 1 && matches!(input, Input::Pack { .. }) { let n = input.len(); - progress.total.fetch_add(n, Ordering::Relaxed); precompile(&input, usize::MAX, windows, None, None, false, None, None, std::time::Instant::now(), Some(progress))?; if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } pipelines_in_workers(&pack, windows, workers, n, progress)?; @@ -1809,7 +1811,7 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R } /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title -/// starts (1: in this process, as before). Unset: the processors less two, 16 at most, and no +/// starts (1: in this process, as before). Unset: the logical processors less four, and no /// more than 3 GB of the commit the system has left for each. fn prepare_workers() -> usize { if let Some(n) = std::env::var("XCL_PREPARE_WORKERS").ok().and_then(|v| v.parse::().ok()) { @@ -1820,9 +1822,9 @@ fn prepare_workers() -> usize { workers_for(cores, limit.saturating_sub(used)) } -/// The workers for `cores` processors and `free_mb` of commit left. +/// The workers for `cores` logical processors (threads, not cores) and `free_mb` of commit left. fn workers_for(cores: usize, free_mb: u64) -> usize { - cores.saturating_sub(2).min(16).min((free_mb / 3072) as usize).max(1) + cores.saturating_sub(4).min(32).min((free_mb / 3072) as usize).max(1) } /// The record count of a builder's progress line (` 400/26503 (12 s)`). @@ -1845,7 +1847,11 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz const CREATE_NO_WINDOW: u32 = 0x0800_0000; let me = std::env::current_exe().map_err(|e| e.to_string())?; let used_only = !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); - let before = progress.done.load(Ordering::Relaxed); + // the workers' pass has its own count on the screen: the records they have passed + let (done_before, total_before) = (progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed)); + progress.done.store(0, Ordering::Relaxed); + progress.total.store(records, Ordering::Relaxed); + progress.workers.store(workers, Ordering::Relaxed); let counts: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); let t0 = std::time::Instant::now(); crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); @@ -1884,7 +1890,7 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz loop { // (a worker counts the records of its own slice) let d: usize = counts.iter().map(|c| c.load(Ordering::Relaxed)).sum(); - progress.done.store(before + d.min(records), Ordering::Relaxed); + progress.done.store(d.min(records), Ordering::Relaxed); if progress.cancel.load(Ordering::Relaxed) { for (_, child) in children.iter_mut() { let _ = child.kill(); } return true; @@ -1901,8 +1907,10 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz Err(e) => { failed += 1; crate::xlog_warn!("Shader preparation: worker {i}: {e}"); } } } + progress.workers.store(0, Ordering::Relaxed); + progress.total.store(total_before, Ordering::Relaxed); + progress.done.store(done_before, Ordering::Relaxed); if cancelled { return Err("Shader preparation cancelled".into()); } - progress.done.store(before + records, Ordering::Relaxed); crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); Ok(()) } @@ -2479,14 +2487,15 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { - /// The workers of a title's shader preparation: two processors are left free, 16 at most, + /// The workers of a title's shader preparation: four logical processors are left free, /// 3 GB of commit for each, and one where there is no room. #[test] fn preparation_workers_leave_two_processors_and_follow_the_commit_left() { - assert_eq!(workers_for(32, 100_000), 16); - assert_eq!(workers_for(8, 100_000), 6); + assert_eq!(workers_for(32, 100_000), 28); + assert_eq!(workers_for(8, 100_000), 4); assert_eq!(workers_for(32, 10_000), 3); assert_eq!(workers_for(2, 100_000), 1); + assert_eq!(workers_for(64, 1_000_000), 32); assert_eq!(workers_for(32, 0), 1); } From ad1ff9a6d4f2a75bdedec4b006b8f9338838aeee Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:54:10 -0500 Subject: [PATCH 03/22] xcl run: the preparation takes the shaders earlier runs used, or none A run keeps the shaders of the pipelines it uses, each by its own key (used-shaders.txt beside the DXIL cache). With that list the preparation before a title translates only those records; the title translates another when it first uses it. XCL_PREPARE_ALL=1: every record, as without the list. XCL_PREPARE=0: no preparation, the title builds what it uses as it goes. Co-Authored-By: Claude Fable 5.2 --- .../xcl/src/hle/d3d12x/present/preparation.rs | 7 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 71 +++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 21 +++++- crates/xcl/src/shaders.rs | 9 +++ 4 files changed, 99 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index 8ef1260687..3952e41b84 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -49,7 +49,12 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { crate::xlog_info!("Shader preparation left out (XCL_PREPARE=0): the title builds what it uses as it goes"); return Ok(()); } - let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); + let only = Some(crate::hle::d3d12x::pso_async::earlier_used_shaders()) + .filter(|used| !used.is_empty() && !std::env::var("XCL_PREPARE_ALL").is_ok_and(|v| v.trim() == "1")); + if let Some(used) = &only { + crate::xlog_info!("Shader preparation: only the {} shaders earlier runs used (XCL_PREPARE_ALL=1: every record)", used.len()); + } + let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), only, ..Default::default() }); let hwnd = if super::enabled() { *SCREEN.lock().unwrap() = Some(Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }); ACTIVE.store(true, Ordering::Release); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..c4df998bf9 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -416,6 +416,18 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { } } +/// The shaders of a pipeline's set, told when the set's key is made (`real::OwnedDesc`). +pub(crate) fn shaders_of(key: u64, shaders: Vec) { + used::parts(key, shaders); +} + +/// The shaders of the pipelines earlier runs used, each by its own key (`used-shaders.txt` +/// beside the DXIL cache): what a title's shader preparation translates. Empty before a run +/// with this list has used a pipeline. +pub fn earlier_used_shaders() -> std::collections::HashSet { + used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-shaders.txt")).unwrap_or_default()) +} + /// The keys of the pipelines earlier runs used (`used-pipelines.txt` beside the DXIL cache): /// what `xcl shaders --precompile --used-only` builds. pub fn earlier_used_keys() -> std::collections::HashSet { @@ -439,6 +451,10 @@ mod used { struct Used { earlier: RwLock>, now: Mutex<(HashSet, Option)>, + /// the shaders of each set made in this run, by the set's key; the shaders of the sets + /// used so far and `used-shaders.txt`, where they are kept for the next run + parts: Mutex>>, + shaders: Mutex<(HashSet, Option)>, } /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). @@ -451,7 +467,7 @@ mod used { U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { - return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; + return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)), parts: Default::default(), shaders: Mutex::new((HashSet::new(), None)) }; } let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); @@ -462,7 +478,10 @@ mod used { let _ = std::fs::create_dir_all(dir); } let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } + let shaders_path = path.with_file_name("used-shaders.txt"); + let shaders = parse(&std::fs::read_to_string(&shaders_path).unwrap_or_default()); + let shaders_file = std::fs::OpenOptions::new().create(true).append(true).open(&shaders_path).ok(); + Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier), parts: Default::default(), shaders: Mutex::new((shaders, shaders_file)) } }) } @@ -476,14 +495,40 @@ mod used { if key == 0 { return; } - let mut g = get().now.lock().unwrap(); - if g.0.insert(key) { - if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); + { + let mut g = get().now.lock().unwrap(); + if g.0.insert(key) { + if let Some(f) = g.1.as_mut() { + let _ = writeln!(f, "{key:016x}"); + } + } + } + // its shaders, each once (also those of a set an earlier run used: the list of + // shaders is younger than the list of sets) + let parts = get().parts.lock().unwrap().get(&key).cloned().unwrap_or_default(); + let mut g = get().shaders.lock().unwrap(); + for part in parts { + if g.0.insert(part) { + if let Some(f) = g.1.as_mut() { + let _ = writeln!(f, "{part:016x}"); + } } } } + /// The shaders of the set `key`, each by its own key (`real::shader_key`). + pub fn parts(key: u64, shaders: Vec) { + if key != 0 { + get().parts.lock().unwrap().entry(key).or_insert(shaders); + } + } + + /// (tests) This run used the shader `key`. + #[cfg(test)] + pub fn shader_noted(key: u64) -> bool { + get().shaders.lock().unwrap().0.contains(&key) + } + /// (tests) This run used a pipeline of these shaders. #[cfg(test)] pub fn noted(key: u64) -> bool { @@ -560,6 +605,20 @@ fn preload() -> Option<&'static Preload> { mod used_tests { use super::*; + /// The shaders of a set are kept when a pipeline of the set is used, each once, and not + /// before: a set that is only made keeps nothing. + #[test] + fn the_shaders_of_a_used_set_are_kept_for_the_next_run() { + let (set, other) = (0x5e70_0000_0000_0001u64, 0x5e70_0000_0000_0003u64); + let (vs, ps, cs) = (0x5e70_0000_0000_0011u64, 0x5e70_0000_0000_0013u64, 0x5e70_0000_0000_0015u64); + shaders_of(set, vec![vs, ps]); + shaders_of(other, vec![cs]); + assert!(!used::shader_noted(vs) && !used::shader_noted(ps), "made, not used yet"); + used::note(set); + assert!(used::shader_noted(vs) && used::shader_noted(ps), "the shaders of the used set"); + assert!(!used::shader_noted(cs), "the other set was not used"); + } + /// A PC call that has kept one of the title's threads for long holds the title, a short one /// does not, and the hold ends with the call. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 19eedfe6ac..9b4a50f8af 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5423,6 +5423,11 @@ unsafe impl Send for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. +/// `shaders_key` of the one shader `blob`. +pub(crate) fn shader_key(blob: &[u8]) -> u64 { + ((0xcbf2_9ce4_8422_2325u64 ^ crate::gpu::shader::fnv64(blob)).wrapping_mul(0x0000_0100_0000_01b3)) | 1 +} + pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { @@ -5433,6 +5438,13 @@ pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { #[cfg(test)] mod shaders_key_tests { + #[test] + fn the_key_of_one_shader_is_the_key_of_a_set_of_it() { + let a = vec![1u8, 2, 3]; + assert_eq!(super::shader_key(&a), super::shaders_key(&[a.clone()])); + assert_ne!(super::shader_key(&a), super::shader_key(&[4u8, 5])); + } + #[test] fn a_key_follows_the_shaders_and_their_order_and_is_never_zero() { let (a, b) = (vec![1u8, 2, 3], vec![4u8, 5]); @@ -5447,11 +5459,16 @@ mod shaders_key_tests { impl OwnedDesc { fn shaders_key(&self) -> u64 { - shaders_key(match self { + let blobs = match self { OwnedDesc::Compute(_, b) => b, OwnedDesc::Graphics(_, b, ..) => b, OwnedDesc::Stream(_, _, b) => b, - }) + }; + let key = shaders_key(blobs); + // each shader by itself too: what a title's shader preparation translates before the + // next run (`pso_async::earlier_used_shaders`) + super::pso_async::shaders_of(key, blobs.iter().map(|b| shader_key(b)).collect()); + key } fn ptr(&self) -> *const c_void { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 3081ca1eaf..7f9108066d 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1754,6 +1754,10 @@ pub(crate) struct LaunchPreparation { /// The worker processes building compute pipelines (0: none; `done` and `total` then count /// the records translated here, with them the records the workers have passed). pub workers: AtomicUsize, + /// The shaders earlier runs used (`pso_async::earlier_used_shaders`), when there are any: + /// only their records are translated before the title starts, and it translates another + /// when it first uses it. `XCL_PREPARE_ALL=1`: every record, as without the list. + pub only: Option>, } /// Unpacked shader containers in the title's shaders directory. Do not follow directory @@ -2028,6 +2032,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } + if startup.and_then(|p| p.only.as_ref()).is_some_and(|used| !used.contains(&crate::hle::d3d12x::real::shader_key(&blob))) { + unused.fetch_add(1, Ordering::Relaxed); + record_done(); + continue; + } // 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(_)))) { From f985c1cf174a7b5985ae0b554db1cf99d9079bd1 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:00:33 -0500 Subject: [PATCH 04/22] xcl run: one preparation worker builds a pipeline, the others leave it Records with the same program are in several workers' slices. Each worker found no driver blob and built the pipeline: the driver's compile of one took about twice as long in each of four workers that built it at once, and a worker that had waited for its turn built what another had written to the cache meanwhile. A worker claims a pipeline with a file beside the blob it will write (.claim) and removes it when the build ends; a worker that finds the claim leaves the pipeline, and the cache is read again after the wait. A claim left by a process that died is taken over after 30 minutes. The count of pipelines left to another process is printed with the others. Reported by a tester who logged what each worker compiled. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/shaders.rs | 83 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 7f9108066d..9a0a349347 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1256,6 +1256,8 @@ struct Pipelines { made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + /// pipelines another process of the same preparation was building (`Claim`): left to it + elsewhere: AtomicUsize, split_programs: AtomicUsize, split_pieces: AtomicUsize, /// programs over `max_dxil` with no blob yet, and their DXIL bytes @@ -1508,6 +1510,7 @@ impl Pipelines { made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), capped: AtomicUsize::new(0), @@ -1596,7 +1599,7 @@ impl Pipelines { } driver_cache::path_for(dxil, desc.Flags.0, chained) }); - let cached = path.as_deref().and_then(driver_cache::load); + let mut cached = path.as_deref().and_then(driver_cache::load); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1614,6 +1617,26 @@ impl Pipelines { } *n += 1; } + // (another process may have written the blob while this one waited for its turn) + if cached.is_none() { + cached = path.as_deref().and_then(driver_cache::load); + } + // not in the cache: the one process that claims the pipeline builds it. Records with the + // same program are in several workers' slices, and the driver's compile of one took + // twice as long in each of four workers that built it at once. + let claim = match (&cached, path.as_deref()) { + (None, Some(path)) => match Claim::take(path) { + Some(c) => Some(c), + None => { + *self.running.0.lock().unwrap() -= 1; + self.running.1.notify_one(); + self.elsewhere.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + }, + _ => None, + }; let from_cache = cached.as_ref().and_then(|bytes| { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; // a driver that cannot use the blob may compile from the DXIL itself and still @@ -1652,6 +1675,7 @@ impl Pipelines { } pso }; + drop(claim); *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); @@ -1840,6 +1864,62 @@ fn progress_count(line: &str) -> Option { d.parse().ok() } +/// A pipeline one process builds: a file beside the driver blob it will write (`.claim`), +/// made when the build starts and gone when it ends. A second process that finds it leaves the +/// pipeline to the first. One left behind by a process that died is taken over after `STALE`. +struct Claim(PathBuf); + +impl Claim { + const STALE: std::time::Duration = std::time::Duration::from_secs(30 * 60); + + /// None: another process has it. + fn take(blob: &std::path::Path) -> Option { + let mut name = blob.as_os_str().to_owned(); + name.push(".claim"); + let path = PathBuf::from(name); + let make = || std::fs::OpenOptions::new().write(true).create_new(true).open(&path); + match make() { + Ok(_) => Some(Claim(path)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let old = std::fs::metadata(&path).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > Self::STALE); + (old && std::fs::remove_file(&path).is_ok() && make().is_ok()).then(|| Claim(path)) + } + // (the folder cannot be written: nothing is shared through it either) + Err(_) => Some(Claim(PathBuf::new())), + } + } +} + +impl Drop for Claim { + fn drop(&mut self) { + if !self.0.as_os_str().is_empty() { + let _ = std::fs::remove_file(&self.0); + } + } +} + +#[cfg(test)] +mod claim_tests { + use super::Claim; + + /// The first process to ask builds a pipeline, a second one leaves it, and it is free again + /// when the first is done. + #[test] + fn a_pipeline_is_claimed_by_one_builder_at_a_time() { + let dir = std::env::temp_dir().join(format!("xcl-claim-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let blob = dir.join("0123.pso"); + let first = Claim::take(&blob).expect("free"); + assert!(dir.join("0123.pso.claim").exists()); + assert!(Claim::take(&blob).is_none(), "claimed"); + assert!(Claim::take(&dir.join("4567.pso")).is_some(), "another pipeline is free"); + drop(first); + assert!(!dir.join("0123.pso.claim").exists()); + assert!(Claim::take(&blob).is_some(), "free again"); + let _ = std::fs::remove_dir_all(&dir); + } +} + /// The compute pipelines of `pack` built by `workers` processes of this program, each on its own /// slice of the records (`XCL_PRECOMPILE_SLICE`): only the ones an earlier run of the title used /// when that list exists (the title builds another when it first uses it). Their records count @@ -2143,6 +2223,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); + println!("pipelines left to another process that was building them {}", p.elsewhere.load(Ordering::Relaxed)); let split_programs = p.split_programs.load(Ordering::Relaxed); if split_programs != 0 { println!("split compute programs: {} ({} pieces)", split_programs, p.split_pieces.load(Ordering::Relaxed)); From 53c1d28198bf0341f44985d03819c286a0f727c3 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:02:39 -0500 Subject: [PATCH 05/22] D3D12.X: record the graphics pipelines a run uses with their state The shader preparation before a title starts builds the compute pipelines earlier runs used, but no graphics pipeline: what is kept between runs is not enough to make one again. used-pipelines.txt holds only the key of a pipeline's shader set, and the driver cache holds blobs named after the translated DXIL and the description's hash. A retail title then builds ~6 000 graphics pipelines in its first minutes, with thousands of stand-ins that draw nothing meanwhile. A lazy graphics pipeline's description is now written down at its first use in a run (pso_async::on_first_use, told once, as used::note is): every field of the description but its pointers, its input layout, and the keys of its console shaders, ~200 bytes, under the key used-pipelines.txt has. The entry is made when the pipeline is (no shader copy is kept for it after its build) and written by a thread of its own, each description once, to used-graphics-pipelines.bin beside the DXIL cache (gfx_records: the format is in the module's comment). The file is versioned (another version reads as none and is started again), an entry cut short or damaged ends it, and it stops at XCL_GFX_RECORDS_MB (64) with a line in the log. No shader code is kept: the preparation finds the shaders in the title's shader files by key, as it does for used-shaders.txt. Mesh pipeline streams are not recorded. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/gfx_records.rs | 674 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 38 ++ crates/xcl/src/hle/d3d12x/real.rs | 32 +- crates/xcl/src/shaders.rs | 1 + 5 files changed, 741 insertions(+), 5 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/gfx_records.rs diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs new file mode 100644 index 0000000000..cb4b872354 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -0,0 +1,674 @@ +//! The graphics pipelines a title used, as it described them, kept for the shader preparation of +//! its next run (`shaders::prepare_for_launch`): it builds them before the title starts, the way +//! the title does (`real::prepare_graphics`), so the title finds their translations and the +//! driver's blobs on disk. `used-pipelines.txt` holds only the keys of the shader sets and the +//! driver cache only blobs named after the translated DXIL: neither is enough to make one again. +//! +//! `used-graphics-pipelines.bin` beside the DXIL cache: +//! +//! ```text +//! file = "XCLGFXP\0", version u32, entry* +//! entry = length u32, check u32 (the low half of fnv64 of the payload), payload +//! payload = 1 key u64 shaders [u64; 5] state input* a pipeline +//! | 2 key u64 bytes a shader (preparation job files only) +//! key = `real::shaders_key` of the set (as `used-pipelines.txt` has it); in a shader entry +//! `real::shader_key` of it +//! shaders = `real::shader_key` of the VS, PS, DS, HS, GS (0: none) +//! state = every field of the description but its pointers, in `state`'s order (varints) +//! input = count, then each element's semantic name (length, bytes), index, format, slot, +//! offset, class, step rate (varints) +//! ``` +//! +//! Integers little-endian, varints LEB128. A pipeline entry holds no shader code: the preparation +//! takes the shaders from the title's shader files by key, as it does those of `used-shaders.txt` +//! (~200 bytes a pipeline). A file of another version is read as none and started again; an entry +//! cut short or damaged ends the file there (the writer cuts it off before it appends). The title +//! side: a pipeline's description is noted at its first use in a run (`note`, from +//! `pso_async::on_first_use`), each once, written by a thread of its own, the file at most +//! `XCL_GFX_RECORDS_MB` (64). + +use std::collections::HashSet; +use std::ffi::CString; +use std::io::{Seek, Write}; +use std::path::{Path, PathBuf}; +use windows::Win32::Graphics::Direct3D12::*; + +const MAGIC: &[u8; 8] = b"XCLGFXP\0"; +/// The layout of an entry: a change makes every file of the older one read as none. +const VERSION: u32 = 1; +const HEADER: usize = 12; +const PIPELINE: u8 = 1; +const SHADER: u8 = 2; + +/// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). +pub(crate) fn path() -> PathBuf { + crate::gpu::recomp::dxc::cache_dir().join("used-graphics-pipelines.bin") +} + +/// `XCL_GFX_RECORDS_MB`: the most the records may take on disk (64 MB: ~300 000 pipelines). +fn cap_bytes() -> u64 { + cap_of(std::env::var("XCL_GFX_RECORDS_MB").ok().as_deref()) +} + +fn cap_of(v: Option<&str>) -> u64 { + v.and_then(|v| v.trim().parse::().ok()).unwrap_or(64) << 20 +} + +fn put_var(out: &mut Vec, mut v: u64) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } +} + +struct Reader<'a>(&'a [u8]); + +impl Reader<'_> { + fn var(&mut self) -> Option { + let mut v = 0u64; + for shift in (0..64).step_by(7) { + let (&b, rest) = self.0.split_first()?; + self.0 = rest; + v |= ((b & 0x7f) as u64) << shift; + if b & 0x80 == 0 { + return Some(v); + } + } + None + } + fn u32var(&mut self) -> Option { + self.var().and_then(|v| u32::try_from(v).ok()) + } + fn u64(&mut self) -> Option { + let (b, rest) = self.0.split_at_checked(8)?; + self.0 = rest; + Some(u64::from_le_bytes(b.try_into().ok()?)) + } + fn bytes(&mut self, n: usize) -> Option<&[u8]> { + let (b, rest) = self.0.split_at_checked(n)?; + self.0 = rest; + Some(b) + } +} + +/// Every field of `d` but its pointers (shaders, root signature, input layout, stream output, +/// cached blob), each as a u32 handed to `f`, which may change it: one order for writing and +/// reading. What the title's translated pipeline is made of beside its shaders +/// (`real::graphics_blob_key` hashes the same). +fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32)) { + macro_rules! int { + ($x:expr) => {{ + let mut v = $x as u32; + f(&mut v); + $x = v as i32; + }}; + } + macro_rules! byte { + ($x:expr) => {{ + let mut v = $x as u32; + f(&mut v); + $x = v as u8; + }}; + } + macro_rules! float { + ($x:expr) => {{ + let mut v = $x.to_bits(); + f(&mut v); + $x = f32::from_bits(v); + }}; + } + let b = &mut d.BlendState; + int!(b.AlphaToCoverageEnable.0); + int!(b.IndependentBlendEnable.0); + for rt in &mut b.RenderTarget { + int!(rt.BlendEnable.0); + int!(rt.LogicOpEnable.0); + int!(rt.SrcBlend.0); + int!(rt.DestBlend.0); + int!(rt.BlendOp.0); + int!(rt.SrcBlendAlpha.0); + int!(rt.DestBlendAlpha.0); + int!(rt.BlendOpAlpha.0); + int!(rt.LogicOp.0); + byte!(rt.RenderTargetWriteMask); + } + f(&mut d.SampleMask); + let r = &mut d.RasterizerState; + int!(r.FillMode.0); + int!(r.CullMode.0); + int!(r.FrontCounterClockwise.0); + int!(r.DepthBias); + float!(r.DepthBiasClamp); + float!(r.SlopeScaledDepthBias); + int!(r.DepthClipEnable.0); + int!(r.MultisampleEnable.0); + int!(r.AntialiasedLineEnable.0); + f(&mut r.ForcedSampleCount); + int!(r.ConservativeRaster.0); + let z = &mut d.DepthStencilState; + int!(z.DepthEnable.0); + int!(z.DepthWriteMask.0); + int!(z.DepthFunc.0); + int!(z.StencilEnable.0); + byte!(z.StencilReadMask); + byte!(z.StencilWriteMask); + for face in [&mut z.FrontFace, &mut z.BackFace] { + int!(face.StencilFailOp.0); + int!(face.StencilDepthFailOp.0); + int!(face.StencilPassOp.0); + int!(face.StencilFunc.0); + } + int!(d.IBStripCutValue.0); + int!(d.PrimitiveTopologyType.0); + f(&mut d.NumRenderTargets); + for format in &mut d.RTVFormats { + int!(format.0); + } + int!(d.DSVFormat.0); + f(&mut d.SampleDesc.Count); + f(&mut d.SampleDesc.Quality); + f(&mut d.NodeMask); + int!(d.Flags.0); +} + +/// The pipeline entry of `d` (a title's description, its input layout readable), of the shader +/// set `key` whose shaders are `shaders` (`Record::shaders`). +pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Vec { + let mut out = Vec::with_capacity(256); + out.push(PIPELINE); + out.extend_from_slice(&key.to_le_bytes()); + for s in shaders { + out.extend_from_slice(&s.to_le_bytes()); + } + // (a copy for `state`, which takes the fields by `&mut`; its pointers are not used) + let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); + state(&mut copy, &mut |v| put_var(&mut out, *v as u64)); + let il = &d.InputLayout; + let elems = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) } else { &[] }; + put_var(&mut out, elems.len() as u64); + for e in elems { + let name = if e.SemanticName.0.is_null() { &[][..] } else { std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char).to_bytes() }; + put_var(&mut out, name.len() as u64); + out.extend_from_slice(name); + for v in [e.SemanticIndex, e.Format.0 as u32, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0 as u32, e.InstanceDataStepRate] { + put_var(&mut out, v as u64); + } + } + out +} + +/// A shader entry (the preparation's job files): `bytes`, of `real::shader_key` `key`. +pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { + let mut out = Vec::with_capacity(9 + bytes.len()); + out.push(SHADER); + out.extend_from_slice(&key.to_le_bytes()); + out.extend_from_slice(bytes); + out +} + +/// A pipeline as a title described it, but its shaders and root signature (`desc` puts them in). +pub(crate) struct Record { + pub key: u64, + /// `real::shader_key` of the VS, PS, DS, HS, GS (0: none) + pub shaders: [u64; 5], + desc: Box, + inputs: Vec, + _names: Vec, +} + +// (only read once made; the names the inputs point at live as long) +unsafe impl Send for Record {} +unsafe impl Sync for Record {} + +impl Record { + /// The description with the shaders `code` (VS, PS, DS, HS, GS), pointing into `self` and + /// `code`, with no root signature (a translated pipeline gets XCL's). + pub(crate) fn desc(&self, code: [Option<&[u8]>; 5]) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // (no root signature in it: nothing is released twice) + let mut d: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::ptr::read(&*self.desc) }; + let bytecode = |c: Option<&[u8]>| c.map_or_else(D3D12_SHADER_BYTECODE::default, |c| D3D12_SHADER_BYTECODE { pShaderBytecode: c.as_ptr().cast(), BytecodeLength: c.len() }); + let [vs, ps, ds, hs, gs] = code; + (d.VS, d.PS, d.DS, d.HS, d.GS) = (bytecode(vs), bytecode(ps), bytecode(ds), bytecode(hs), bytecode(gs)); + if !self.inputs.is_empty() { + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: self.inputs.as_ptr(), NumElements: self.inputs.len() as u32 }; + } + d + } +} + +pub(crate) enum Entry { + Pipeline(Record), + Shader(u64, Vec), +} + +/// The entry of `payload` (None: not one this version writes). +pub(crate) fn decode(payload: &[u8]) -> Option { + let (&tag, rest) = payload.split_first()?; + let mut r = Reader(rest); + let key = r.u64()?; + if tag == SHADER { + return Some(Entry::Shader(key, r.0.to_vec())); + } + if tag != PIPELINE { + return None; + } + let mut shaders = [0u64; 5]; + for s in &mut shaders { + *s = r.u64()?; + } + let mut desc: Box = Box::new(unsafe { std::mem::zeroed() }); + let mut short = false; + state(&mut desc, &mut |v| match r.u32var() { + Some(x) => *v = x, + None => short = true, + }); + if short { + return None; + } + let n = r.var()? as usize; + let mut names = Vec::new(); + let mut fields = Vec::new(); + for _ in 0..n.min(64) { + let len = r.var()? as usize; + names.push(CString::new(r.bytes(len)?).ok()?); + let mut f = [0u32; 6]; + for v in &mut f { + *v = r.u32var()?; + } + fields.push(f); + } + if n > 64 || !r.0.is_empty() { + return None; + } + let inputs = names + .iter() + .zip(&fields) + .map(|(name, f)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(name.as_ptr().cast()), + SemanticIndex: f[0], + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f[1] as i32), + InputSlot: f[2], + AlignedByteOffset: f[3], + InputSlotClass: D3D12_INPUT_CLASSIFICATION(f[4] as i32), + InstanceDataStepRate: f[5], + }) + .collect(); + Some(Entry::Pipeline(Record { key, shaders, desc, inputs, _names: names })) +} + +fn header() -> [u8; HEADER] { + let mut h = [0u8; HEADER]; + h[..8].copy_from_slice(MAGIC); + h[8..].copy_from_slice(&VERSION.to_le_bytes()); + h +} + +fn check(payload: &[u8]) -> u32 { + crate::gpu::shader::fnv64(payload) as u32 +} + +/// The payloads of a file's whole entries and where the last of them ends. None: no file of this +/// version (another one, or not one at all). +fn payloads(file: &[u8]) -> Option<(Vec<&[u8]>, usize)> { + if file.len() < HEADER || file[..HEADER] != header() { + return None; + } + let (mut list, mut at) = (Vec::new(), HEADER); + while let Some(head) = file.get(at..at + 8) { + let len = u32::from_le_bytes(head[..4].try_into().unwrap()) as usize; + let Some(payload) = file.get(at + 8..at + 8 + len) else { break }; + if check(payload) != u32::from_le_bytes(head[4..].try_into().unwrap()) { + break; + } + list.push(payload); + at += 8 + len; + } + Some((list, at)) +} + +/// The entries of the file at `path` (none: no file, or one of another version). +pub(crate) fn read(path: &Path) -> Vec> { + let file = std::fs::read(path).unwrap_or_default(); + payloads(&file).map_or_else(Vec::new, |(list, _)| list.into_iter().map(<[u8]>::to_vec).collect()) +} + +/// What became of an entry handed to `Writer::add`. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Added { + New, + /// in the file already + Known, + /// not written: the file is at its cap + Full, +} + +/// Appends entries to a file of records, each once, up to `cap` bytes. +pub(crate) struct Writer { + file: std::fs::File, + len: u64, + cap: u64, + seen: HashSet, + full: bool, +} + +impl Writer { + /// The file at `path` for appending: its whole entries are kept (a cut-short tail is cut off), + /// one of another version is started again. + pub(crate) fn open(path: &Path, cap: u64) -> std::io::Result { + let old = std::fs::read(path).unwrap_or_default(); + let (seen, end) = match payloads(&old) { + Some((list, end)) => (list.iter().map(|p| crate::gpu::shader::fnv64(p)).collect(), end), + None => (HashSet::new(), 0), + }; + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let mut file = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(path)?; + let len = if end == 0 { + file.set_len(0)?; + file.write_all(&header())?; + HEADER as u64 + } else { + file.set_len(end as u64)?; + end as u64 + }; + file.seek(std::io::SeekFrom::Start(len))?; + Ok(Writer { file, len, cap, seen, full: false }) + } + + /// Entries in the file. + pub(crate) fn count(&self) -> usize { + self.seen.len() + } + + pub(crate) fn add(&mut self, payload: &[u8]) -> std::io::Result { + let id = crate::gpu::shader::fnv64(payload); + if self.seen.contains(&id) { + return Ok(Added::Known); + } + let n = 8 + payload.len() as u64; + if self.full || self.len + n > self.cap { + self.full = true; + return Ok(Added::Full); + } + let mut entry = Vec::with_capacity(n as usize); + entry.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + entry.extend_from_slice(&check(payload).to_le_bytes()); + entry.extend_from_slice(payload); + self.file.write_all(&entry)?; + self.len += n; + self.seen.insert(id); + Ok(Added::New) + } +} + +/// A graphics pipeline's first use in this run: its entry (`encode`) goes to the file on a thread +/// of its own, not the title's. +pub(crate) fn note(payload: Vec) { + use std::sync::{mpsc, Mutex, OnceLock}; + // (a test does not write the user's file) + if cfg!(test) { + return; + } + static TX: OnceLock>>> = OnceLock::new(); + let tx = TX.get_or_init(|| { + let (tx, rx) = mpsc::channel::>(); + let _ = std::thread::Builder::new().name("xcl-gfx-records".into()).spawn(move || { + let (path, cap) = (path(), cap_bytes()); + let mut w = match Writer::open(&path, cap) { + Ok(w) => w, + Err(e) => { + crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); + return; + } + }; + crate::xlog_info!("D3D12.X: graphics pipelines are recorded at their first use for the next run's preparation ({} from earlier runs)", w.count()); + for payload in rx.iter() { + match w.add(&payload) { + Ok(Added::Full) => { + crate::xlog_warn!("D3D12.X: the graphics pipeline records are at their cap of {} MB (XCL_GFX_RECORDS_MB): pipelines first used from here on are not prepared before the next run", cap >> 20); + // (the rest are dropped unread) + for _ in rx.iter() {} + return; + } + Ok(_) => {} + Err(e) => { + crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); + return; + } + } + } + }); + Mutex::new(tx) + }); + let _ = tx.lock().unwrap().send(payload); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + + struct Directory(PathBuf); + impl Drop for Directory { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn directory(name: &str) -> Directory { + let dir = std::env::temp_dir().join(format!("xcl-gfx-records-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Directory(dir) + } + + /// A description with every field set to a value of its own (none its default), written out + /// field by field here: a field `state` leaves out does not come back. + fn described() -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut n = 0x10; + let mut next = || { + n += 3; + n + }; + let b = &mut d.BlendState; + b.AlphaToCoverageEnable.0 = 1; + b.IndependentBlendEnable.0 = 1; + for rt in &mut b.RenderTarget { + rt.BlendEnable.0 = 1; + rt.LogicOpEnable.0 = 1; + rt.SrcBlend.0 = next(); + rt.DestBlend.0 = next(); + rt.BlendOp.0 = next(); + rt.SrcBlendAlpha.0 = next(); + rt.DestBlendAlpha.0 = next(); + rt.BlendOpAlpha.0 = next(); + rt.LogicOp.0 = next(); + rt.RenderTargetWriteMask = next() as u8; + } + d.SampleMask = 0xfedc_ba98; + let r = &mut d.RasterizerState; + r.FillMode.0 = next(); + r.CullMode.0 = next(); + r.FrontCounterClockwise.0 = 1; + r.DepthBias = -1234; + r.DepthBiasClamp = -0.25; + r.SlopeScaledDepthBias = 3.5; + r.DepthClipEnable.0 = 1; + r.MultisampleEnable.0 = 1; + r.AntialiasedLineEnable.0 = 1; + r.ForcedSampleCount = 8; + r.ConservativeRaster.0 = 1; + let z = &mut d.DepthStencilState; + z.DepthEnable.0 = 1; + z.DepthWriteMask.0 = 1; + z.DepthFunc.0 = next(); + z.StencilEnable.0 = 1; + z.StencilReadMask = 0x3c; + z.StencilWriteMask = 0xc3; + for face in [&mut z.FrontFace, &mut z.BackFace] { + face.StencilFailOp.0 = next(); + face.StencilDepthFailOp.0 = next(); + face.StencilPassOp.0 = next(); + face.StencilFunc.0 = next(); + } + d.IBStripCutValue.0 = 2; + d.PrimitiveTopologyType.0 = 3; + d.NumRenderTargets = 7; + for f in &mut d.RTVFormats { + *f = DXGI_FORMAT(next()); + } + d.DSVFormat = DXGI_FORMAT(next()); + d.SampleDesc.Count = 4; + d.SampleDesc.Quality = 9; + d.NodeMask = 0x5; + d.Flags.0 = 1; + d + } + + fn pipeline(payload: &[u8]) -> Record { + match decode(payload) { + Some(Entry::Pipeline(r)) => r, + _ => panic!("not a pipeline entry"), + } + } + + /// A description comes back with every field (as the key of its translated pipeline's driver + /// blob sees them), its input layout and its shaders' keys. + #[test] + fn a_description_comes_back_as_it_was_written() { + let names = [CString::new("POSITION").unwrap(), CString::new("TEXCOORD").unwrap()]; + let elems = [ + D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(names[0].as_ptr().cast()), SemanticIndex: 0, Format: DXGI_FORMAT(6), InputSlot: 0, AlignedByteOffset: 0, InputSlotClass: D3D12_INPUT_CLASSIFICATION(0), InstanceDataStepRate: 0 }, + D3D12_INPUT_ELEMENT_DESC { SemanticName: windows::core::PCSTR(names[1].as_ptr().cast()), SemanticIndex: 3, Format: DXGI_FORMAT(16), InputSlot: 2, AlignedByteOffset: u32::MAX, InputSlotClass: D3D12_INPUT_CLASSIFICATION(1), InstanceDataStepRate: 7 }, + ]; + let mut d = described(); + d.InputLayout = D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: elems.as_ptr(), NumElements: 2 }; + let shaders = [11, 22, 0, 0, 55]; + let payload = unsafe { encode(0xabcd_ef01, shaders, &d) }; + assert!(payload.len() < 400, "{} bytes", payload.len()); + let r = pipeline(&payload); + assert_eq!((r.key, r.shaders), (0xabcd_ef01, shaders)); + let (vs, ps, gs) = (b"vs".as_slice(), b"pixel".as_slice(), b"g".as_slice()); + let back = r.desc([Some(vs), Some(ps), None, None, Some(gs)]); + let key = |d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC| unsafe { super::super::real::graphics_blob_key(d, b"dxil", None, None, &[]) }; + assert_eq!(key(&back), key(&d), "the state and the input layout"); + assert_ne!(key(&back), key(&described()), "(the input layout is in the key)"); + assert_eq!(unsafe { encode(0xabcd_ef01, shaders, &back) }, payload); + assert_eq!((back.VS.BytecodeLength, back.PS.BytecodeLength, back.DS.BytecodeLength, back.GS.BytecodeLength), (2, 5, 0, 1)); + assert!(back.pRootSignature.is_none()); + // a description without an input layout + let plain = unsafe { encode(1, [1, 0, 0, 0, 0], &described()) }; + let back = pipeline(&plain).desc([None; 5]); + assert_eq!((back.InputLayout.NumElements, back.InputLayout.pInputElementDescs.is_null()), (0, true)); + assert_eq!(key(&back), key(&described())); + } + + #[test] + fn a_shader_entry_and_a_damaged_payload() { + match decode(&shader_entry(0x77, b"code")) { + Some(Entry::Shader(k, b)) => assert_eq!((k, b.as_slice()), (0x77, b"code".as_slice())), + _ => panic!("not a shader entry"), + } + let payload = unsafe { encode(9, [9, 0, 0, 0, 0], &described()) }; + assert!(decode(&payload[..payload.len() - 1]).is_none(), "cut short"); + assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none(), "a byte too many"); + assert!(decode(&[3, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + } + + /// Written, read back in order, each entry once; a file cut short in its last entry keeps the + /// ones before it and the writer goes on after them. + #[test] + fn entries_are_written_once_and_read_back() { + let dir = directory("round"); + let p = dir.0.join("cache").join("records.bin"); + let a = unsafe { encode(1, [1, 0, 0, 0, 0], &described()) }; + let b = shader_entry(2, b"shader"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!(w.add(&a).unwrap(), Added::New); + assert_eq!(w.add(&b).unwrap(), Added::New); + assert_eq!(w.add(&a).unwrap(), Added::Known); + drop(w); + assert_eq!(read(&p), vec![a.clone(), b.clone()]); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!((w.count(), w.add(&b).unwrap()), (2, Added::Known), "known from the file"); + drop(w); + // a run cut short in its third entry + let whole = std::fs::read(&p).unwrap(); + std::fs::write(&p, [whole.as_slice(), &[40, 0, 0, 0, 1, 2]].concat()).unwrap(); + assert_eq!(read(&p), vec![a.clone(), b.clone()]); + let c = shader_entry(3, b"another"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!(w.add(&c).unwrap(), Added::New); + drop(w); + assert_eq!(read(&p), vec![a.clone(), b.clone(), c.clone()]); + // a damaged entry ends the file there + let mut bytes = std::fs::read(&p).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 0xff; + std::fs::write(&p, &bytes).unwrap(); + assert_eq!(read(&p), vec![a, b]); + } + + /// A file of another version (or no file of records at all) is read as none, and the writer + /// starts it again. + #[test] + fn a_file_of_another_version_is_passed_over() { + let dir = directory("version"); + let p = dir.0.join("records.bin"); + let a = shader_entry(5, b"five"); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + w.add(&a).unwrap(); + drop(w); + let mut bytes = std::fs::read(&p).unwrap(); + bytes[8..12].copy_from_slice(&(VERSION + 1).to_le_bytes()); + std::fs::write(&p, &bytes).unwrap(); + assert!(read(&p).is_empty()); + let mut w = Writer::open(&p, 1 << 20).unwrap(); + assert_eq!((w.count(), w.add(&a).unwrap()), (0, Added::New)); + drop(w); + assert_eq!(read(&p), vec![a.clone()]); + assert_eq!(&std::fs::read(&p).unwrap()[8..12], &VERSION.to_le_bytes()); + std::fs::write(&p, b"not records").unwrap(); + assert!(read(&p).is_empty()); + assert!(read(&dir.0.join("none.bin")).is_empty()); + } + + /// An entry that would take the file past its cap is not written, nor any after it. + #[test] + fn the_file_stops_at_its_cap() { + assert_eq!(cap_of(None), 64 << 20); + assert_eq!(cap_of(Some(" 2 ")), 2 << 20); + assert_eq!(cap_of(Some("lots")), 64 << 20); + let dir = directory("cap"); + let p = dir.0.join("records.bin"); + let (a, b, small) = (shader_entry(1, &[1; 40]), shader_entry(2, &[2; 40]), shader_entry(3, &[])); + // (room for `small` after `a`, not for `b`) + let cap = (HEADER + 8 + a.len() + 8 + small.len()) as u64; + let mut w = Writer::open(&p, cap).unwrap(); + assert_eq!(w.add(&a).unwrap(), Added::New); + assert_eq!(w.add(&b).unwrap(), Added::Full); + assert_eq!(w.add(&small).unwrap(), Added::Full, "nothing after the cap was hit"); + assert_eq!(w.add(&a).unwrap(), Added::Known); + drop(w); + assert_eq!(read(&p), vec![a]); + assert!(std::fs::metadata(&p).unwrap().len() <= cap); + } + + #[test] + fn varints_round_trip() { + for v in [0u64, 1, 0x7f, 0x80, 0x3fff, 0x4000, u32::MAX as u64, u64::MAX] { + let mut out = Vec::new(); + put_var(&mut out, v); + let mut r = Reader(&out); + assert_eq!(r.var(), Some(v)); + assert!(r.0.is_empty()); + } + assert_eq!(Reader(&[0x80]).var(), None, "cut short"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index b7c2e38c14..c5fbb963a8 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -19,6 +19,7 @@ mod cpu_writes; pub mod dred; mod fence_x; pub mod frame; +pub(crate) mod gfx_records; pub mod guard; mod late_release; pub mod layout; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index c4df998bf9..59f2e81cc2 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -34,6 +34,8 @@ struct Pending { /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it spared: std::sync::atomic::AtomicBool, demand: Mutex, + /// what its first use tells besides `used::note` (`on_first_use`) + on_use: Mutex>, } /// Whether one of the title's threads waits for the pipeline, and the preload worker building it. @@ -112,6 +114,10 @@ impl Pending { fn note_use(&self) { if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); + let on_use = self.on_use.lock().unwrap().take(); + if let Some(f) = on_use { + f(); + } } } } @@ -400,6 +406,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { late: Default::default(), spared: Default::default(), demand: Default::default(), + on_use: Default::default(), }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); @@ -416,6 +423,18 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { } } +/// Run on the thread of a lazy pipeline's first use, once (it is to hand work to another). +pub type OnUse = Box; + +/// What the first use of lazy pipeline `standin` tells besides `used::note`: a graphics one's +/// description for the next run's preparation (`gfx_records::note`). Told before the title has +/// the stand-in. +pub(super) fn on_first_use(standin: usize, f: OnUse) { + if let Some(p) = entry(standin) { + *p.on_use.lock().unwrap() = Some(f); + } +} + /// The shaders of a pipeline's set, told when the set's key is made (`real::OwnedDesc`). pub(crate) fn shaders_of(key: u64, shaders: Vec) { used::parts(key, shaders); @@ -869,6 +888,25 @@ mod used_tests { released(unknown); } + /// What a pipeline's first use tells (a graphics one's description: `gfx_records`) is told + /// once, at that use, not when it is made or built. + #[test] + fn a_first_use_is_told_once() { + let (standin, key) = (0x7E57_7011usize, 0x5EED_0011u64); + let told = Arc::new(AtomicUsize::new(0)); + submit_lazy(standin, true, Box::new(|| 0x4331), key); + let t = told.clone(); + on_first_use(standin, Box::new(move || { t.fetch_add(1, Ordering::SeqCst); })); + assert_eq!(told.load(Ordering::SeqCst), 0, "not at its making"); + assert_eq!(resolve_wait(standin), 0x4331); + assert_eq!(told.load(Ordering::SeqCst), 1); + assert_eq!(resolve(standin), 0x4331); + assert_eq!(resolve_wait(standin), 0x4331); + assert_eq!(told.load(Ordering::SeqCst), 1, "once"); + on_first_use(0x7E57_7012, Box::new(|| unreachable!("no such pipeline"))); + released(standin); + } + static WORKER_SATURATION_LOCK: Mutex<()> = Mutex::new(()); /// A queued normal worker job whose stand-in was released before a worker starts it is diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9b4a50f8af..8038e8342f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4895,7 +4895,7 @@ fn remember_graphics_blob(key: (u64, usize), blob: std::sync::Arc>) { /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static /// samplers, blend/rasterizer/depth-stencil state, input layout, render target / depth formats, /// sample desc, topology, flags) for in-memory and on-disk driver blob caching. -unsafe fn graphics_blob_key( +pub(super) unsafe fn graphics_blob_key( copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs_dxil: &[u8], ps_dxil: Option<&[u8]>, @@ -5458,7 +5458,8 @@ mod shaders_key_tests { } impl OwnedDesc { - fn shaders_key(&self) -> u64 { + /// The key of its shaders, and each shader's (`shader_key`, in its own order). + fn shaders_key(&self) -> (u64, Vec) { let blobs = match self { OwnedDesc::Compute(_, b) => b, OwnedDesc::Graphics(_, b, ..) => b, @@ -5467,8 +5468,24 @@ impl OwnedDesc { let key = shaders_key(blobs); // each shader by itself too: what a title's shader preparation translates before the // next run (`pso_async::earlier_used_shaders`) - super::pso_async::shaders_of(key, blobs.iter().map(|b| shader_key(b)).collect()); - key + let parts: Vec = blobs.iter().map(|b| shader_key(b)).collect(); + super::pso_async::shaders_of(key, parts.clone()); + (key, parts) + } + + /// A graphics pipeline's entry for the next run's preparation (`gfx_records`), of the set + /// `key` whose shaders' keys are `parts`; None for any other. + unsafe fn record(&self, key: u64, parts: &[u64]) -> Option> { + let OwnedDesc::Graphics(d, ..) = self else { return None }; + // (`own_graphics` copied the stages it has, in this order) + let mut parts = parts.iter(); + let mut shaders = [0u64; 5]; + for (s, b) in shaders.iter_mut().zip([&d.VS, &d.PS, &d.DS, &d.HS, &d.GS]) { + if !b.pShaderBytecode.is_null() && b.BytecodeLength != 0 { + *s = *parts.next()?; + } + } + Some(super::gfx_records::encode(key, shaders, d)) } fn ptr(&self) -> *const c_void { @@ -5693,7 +5710,9 @@ unsafe fn go_background( return None; } let dev = Dev(this as usize, f as usize); - let key = owned.shaders_key(); + let (key, parts) = owned.shaders_key(); + // (a graphics pipeline used in this run is built before the next starts: `gfx_records`) + let described = if super::pso_async::lazy() { owned.record(key, &parts) } else { None }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); let job: super::pso_async::Job = Box::new(move || { @@ -5706,6 +5725,9 @@ unsafe fn go_background( }); if super::pso_async::lazy() { super::pso_async::submit_lazy(*ppv as usize, compute, job, key); + if let Some(entry) = described { + super::pso_async::on_first_use(*ppv as usize, Box::new(move || super::gfx_records::note(entry))); + } } else { super::pso_async::submit(*ppv as usize, compute, job); } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9a0a349347..1319b58bbd 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2047,6 +2047,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let next = AtomicUsize::new(0); 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); let matched: Mutex> = Mutex::new(Default::default()); let pipeline_jobs: Mutex> = Mutex::new(Vec::new()); let used_earlier = if pipelines.is_some() && startup.is_none() { From 192374ea0d9c89fb415e6db1adf3fb9b378b37cf Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:51:11 -0500 Subject: [PATCH 06/22] xcl run: the memory line and a device removal give the system's commit A retail title's world lost the device with reason 0x887A0005 (no driver error, DRED state 0, no list in flight) at 23 to 26 GB of video memory and 46 to 49 GB of process memory, on a PC whose other programs held 71 GB of commit under a 147 GB limit. The sum looked like the limit; nothing in the log could say. - The memory line ends with "system commit N of M MB", and a removal reports it too. Measured with it: 30.8 GB were left at the removal, and the system's commit follows the process's own memory, not its video memory - the commit limit is not what removes the device (it is the driver's 512 MiB range for the code of pipelines in use, xcl-dev/xcl#2403). - A warning when less than 8 GB of commit are left (once, then at each halving): there allocations start to fail for every program. Tests: the rule of the warning; the commit is known and under its limit. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/real.rs | 6 +++ crates/xcl/src/host.rs | 75 ++++++++++++++++++++++++++++++- 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 8038e8342f..6dc0fcc323 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7588,6 +7588,12 @@ pub fn log_device_removed() { return; } crate::xlog_error!("D3D12 device removed: {:#x} {}", e.code().0 as u32, e.message()); + // (to rule the system's memory in or out: a removal with no fault of the GPU's had 30 GB of + // commit left) + let (commit, limit) = crate::host::system_commit(); + if limit != 0 { + crate::xlog_error!("system commit at the removal: {} of {} MB ({} MB left)", commit >> 20, limit >> 20, limit.saturating_sub(commit) >> 20); + } unsafe { let Ok(dred) = dev.cast::() else { return }; if let Ok(pf) = dred.GetPageFaultAllocationOutput() { diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 1f5d3f4970..a73f8c8a85 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -8,6 +8,50 @@ use crate::config::Boot; pub static HOST_MODE: AtomicBool = AtomicBool::new(false); +/// The system's commit charge and its limit in bytes (RAM plus page files): what all programs' +/// memory, and all video memory, is counted against. (0, 0): not known. +pub fn system_commit() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{K32GetPerformanceInfo, PERFORMANCE_INFORMATION}; + unsafe { + let mut p: PERFORMANCE_INFORMATION = std::mem::zeroed(); + p.cb = std::mem::size_of_val(&p) as u32; + if K32GetPerformanceInfo(&mut p, p.cb) == 0 { + return (0, 0); + } + (p.CommitTotal as u64 * p.PageSize as u64, p.CommitLimit as u64 * p.PageSize as u64) + } +} + +/// Whether commit left over (`limit - commit`) is logged as low: under `LOW_COMMIT` the first +/// time, then each time it is half of what was logged last. +fn low_commit_logged(left: u64, last: u64) -> bool { + left < LOW_COMMIT && (last == 0 || left <= last / 2) +} + +/// Commit left under which the log warns: a retail title's world took the last 6 GB in seconds. +const LOW_COMMIT: u64 = 8 << 30; + +/// The system is running out of commit: said in the log (once, then at each halving). When it +/// runs out, allocations fail for every program. (Measured on a retail title's world, whose +/// process held 45 GB beside 71 GB of other programs under a 147 GB limit: the process's own +/// memory counts against the commit, its 24 GB of video memory do not.) +fn warn_low_commit(commit: u64, limit: u64, private: u64, video: u64) { + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let left = limit.saturating_sub(commit); + let last = LAST.load(Ordering::Relaxed); + if !low_commit_logged(left, last) { + return; + } + LAST.store(left.max(1), Ordering::Relaxed); + crate::xlog_warn!( + "memory: the system is running out of commit: {} MB left of {} MB (RAM + page file). This process holds {} MB (and {} MB of video memory, which do not count), other programs the rest. When it runs out allocations fail for every program: close other programs or give Windows a larger page file", + left >> 20, + limit >> 20, + private >> 20, + video >> 20 + ); +} + pub fn host_main(boot_path: &Path) -> i32 { let boot: Boot = match std::fs::read_to_string(boot_path).map_err(|e| e.to_string()).and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string())) { Ok(b) => b, @@ -77,8 +121,16 @@ pub fn host_main(boot_path: &Path) -> i32 { let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); let mb = |b: u64| b >> 20; + // the system's commit: this process's memory counts against it with every other + // program's (video memory does not), and where it ends allocations fail + let (commit, commit_limit) = system_commit(); + let mut commit_text = String::new(); + if commit_limit != 0 { + commit_text = format!("; system commit {} of {} MB", mb(commit), mb(commit_limit)); + warn_low_commit(commit, commit_limit, private as u64, local); + } crate::xlog_info!( - "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", + "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped){commit_text}", mb(private as u64), mb(local), mb(non_local), @@ -164,3 +216,24 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::log::flush(); code as i32 } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn low_commit_is_logged_under_the_mark_and_at_each_halving() { + assert!(!low_commit_logged(LOW_COMMIT, 0), "at the mark: not yet"); + assert!(low_commit_logged(LOW_COMMIT - 1, 0)); + assert!(!low_commit_logged(5 << 30, 7 << 30), "less, but not half of what was logged last"); + assert!(low_commit_logged(3 << 30, 7 << 30)); + assert!(low_commit_logged(0, 1), "none left"); + assert!(!low_commit_logged(9 << 30, 1 << 30), "back above the mark"); + } + + #[test] + fn the_system_commit_is_known_and_under_its_limit() { + let (commit, limit) = system_commit(); + assert!(commit > 0 && commit <= limit, "{commit} of {limit}"); + } +} From 8f906486d6596e1d54f2f25a603764baf926b59b Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:04:20 -0500 Subject: [PATCH 07/22] xcl run: build the graphics pipelines earlier runs used before the title After the compute pass, the shader preparation now reads the graphics pipeline records of earlier runs (used-graphics-pipelines.bin), finds their console shaders in the title's shader files by key, and builds each pipeline in worker processes, the way the title's background build makes it (real::prepare_graphics calls translated_graphics_pso, as build_graphics does): the translation, DXC and driver blob caches on disk then hold exactly what the title asks for, and the title makes these pipelines from the kept blob in milliseconds instead of compiling them while it draws stand-ins. Worker processes, as for the compute pipelines: the driver builds about two pipelines at a time for one process, and a driver that ends a worker ends no title. Nothing of the title's device is needed: a translated pipeline gets XCL's root signature, and what else its build reads of the process is the title's memory windows (given with --windows, no memory reserved: uma::leave_out, pso::set_title_windows) and the adapter (XCL_ADAPTER from the title's setting). Each worker gets a file of its part with the shaders it needs (gfx_records' format) in the temporary folder, removed after. The title did not keep the blob of most graphics pipelines: none of under 16 KB of DXIL and none built in under 250 ms (XCL_PSO_DISK_CACHE_MIN_MS), so most were compiled again in every run. A preparation worker keeps every blob, on disk only. The blob's file name is made of the description's state, the DXIL, the adapter and driver and the window count, no address, so the title's lookup finds the worker's file. The screen shows "Building graphics pipelines" with its own count, the 5 s line counts graphics pipelines, a failure is logged and skipped and the title starts regardless. XCL_PREPARE=0 skips it with the rest, XCL_PREPARE_GRAPHICS=0 skips this pass only. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- crates/xcl/src/gpu/recomp/pso.rs | 23 +- crates/xcl/src/gpu/uma.rs | 7 + .../xcl/src/hle/d3d12x/present/preparation.rs | 10 +- crates/xcl/src/hle/d3d12x/real.rs | 27 ++ crates/xcl/src/shaders.rs | 273 ++++++++++++++++-- 6 files changed, 320 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index c086a8e64e..2855754b5a 100644 --- a/README.md +++ b/README.md @@ -268,8 +268,11 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder processed records. The timer counts seconds since one finished (or preparation started); five seconds without progress counts as a stall, and the window shows when the last one ended. XCL prepares supported shader stages and compute pipelines, including - split pieces and their whole fallback. Graphics pipelines that need state supplied by the - title are created during play. Later launches reuse matching cache entries. + split pieces and their whole fallback. Graphics pipelines are created during play the first + time; the ones a run used are recorded with their state (`used-graphics-pipelines.bin` beside + the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts + on the next launch, with their driver blobs kept, so the title makes them from those in + milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Later launches reuse matching cache entries. Closing the window cancels the launch. A compiler or driver failure stops it and reports 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 diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..1af5dcc2ad 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -80,8 +80,29 @@ pub fn fspx(blob: &[u8]) -> Option> { /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when /// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { + let title = TITLE_WINDOWS.load(std::sync::atomic::Ordering::Relaxed); + if title != 0 { + return windows_for(title & !super::HEAP_WINDOWS, title & super::HEAP_WINDOWS != 0 && !SWITCH_FORM.with(|s| s.get())); + } let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); - if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { + windows_for(n, heap_windows() && !SWITCH_FORM.with(|s| s.get())) +} + +/// The title's windows (`mem_windows` with `HEAP_WINDOWS`) for a process without its memory: a +/// shader preparation worker builds the title's pipelines with them (0: none given). +static TITLE_WINDOWS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// `mem_windows` is `windows` from here on (a preparation worker: `uma::leave_out`). +pub fn set_title_windows(windows: u32) { + TITLE_WINDOWS.store(windows, std::sync::atomic::Ordering::Relaxed); +} + +/// `n` windows as shaders take them: from the descriptor heap (`heap`), or in the switch form +/// over the root UAVs – of which there are `MAX_WINDOWS`, so never more there (the HLSL path +/// refused a wider switch, and DXIL quietly made it 4: a 16-window run whose heap views could +/// not be made, or a pipeline the driver refused with them, lost every shader on HLSL). +fn windows_for(n: u32, heap: bool) -> u32 { + if n > 1 && heap { n | super::HEAP_WINDOWS } else { n diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 8341c61ed3..17872bd68d 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -788,6 +788,13 @@ impl Arena { static GLOBAL: OnceLock> = OnceLock::new(); +/// A process that holds no title memory (a shader preparation worker): `get` is None from here +/// on, and nothing is reserved or committed for it (a run's region commits its coherent window). +/// Before any `get`. +pub fn leave_out() { + let _ = GLOBAL.set(None); +} + /// The title's graphics memory XCL places in the coherent window (`note_coherent_need`) is /// known only once it asks for it, and the window is committed when it is made: its size is /// what the title asked for in its last run (`/cache/uma_coherent.txt`) and XCL's own diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index 3952e41b84..eafd05f1e7 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -70,11 +70,13 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { if said.elapsed() >= Duration::from_secs(5) { said = Instant::now(); let workers = progress.workers.load(Ordering::Relaxed); + let graphics = progress.graphics.load(Ordering::Relaxed); crate::xlog_info!( - "Shader preparation: {} of {} records {} after {} s", + "Shader preparation: {} of {} {} {} after {} s", progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed), - if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, + if graphics { "graphics pipelines" } else { "records" }, + if graphics { format!("built by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, began.elapsed().as_secs() ); } @@ -172,7 +174,8 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { let pct = percent(done, total, s.ready); let (quiet, last) = s.clock.sample(done, s.start.elapsed()); let workers = s.progress.workers.load(Ordering::Relaxed); - let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; + let graphics = workers != 0 && s.progress.graphics.load(Ordering::Relaxed); + let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; let mut title = row(0,48); title.right -= scale(84); text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); @@ -181,6 +184,7 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { fill(dc, bar, 0x4b4038); fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); let count = if total == 0 { "Reading shader records…".into() } + else if graphics { format!("{done} of {total} graphics pipelines built by {workers} worker processes") } else if workers != 0 { format!("{done} of {total} records checked by {workers} worker processes") } else { format!("{done} of {total} records processed") }; text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6dc0fcc323..5781f22adf 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5745,6 +5745,33 @@ unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(hr) if hr >= 0) } +/// This process is a shader preparation worker (`prepare_device`): it keeps the driver's blob of +/// every graphics pipeline it builds on disk, whatever its size and time, and none in memory. +static PREPARING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// A shader preparation worker's device (`shaders::graphics_worker`), made on the title's adapter: +/// adopted as the title's is, so `prepare_graphics` takes the title's path. Raw, kept for the +/// process. +pub(crate) fn prepare_device(device: ID3D12Device) -> usize { + PREPARING.store(true, Ordering::Relaxed); + let raw = device.into_raw(); + unsafe { adopt(raw, Kind::Device) }; + raw as usize +} + +/// A title's graphics pipeline `desc` (`gfx_records::Record::desc`) built on `device` +/// (`prepare_device`) as the title's background build makes it (`build_graphics`): the +/// translation, DXC and driver blob caches on disk get what the title will ask for. The pipeline +/// is released; false: not made (noted in the log as the title's would be). +pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> bool { + let this = device as *mut c_void; + let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); + let mut out: *mut c_void = std::ptr::null_mut(); + let made = matches!(translated_graphics_pso(this, f, desc as *const _ as *const c_void, &pc_iid(Kind::PipelineState), &mut out), Some(hr) if hr >= 0) && !out.is_null(); + super::pso_async::release(out as usize); + made +} + unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); matches!(translated_compute_pso(dev.0 as *mut c_void, std::mem::transmute::(dev.1), d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 1319b58bbd..82a3ee2a48 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -816,6 +816,8 @@ struct ShadersOptions { pipelines: bool, used_only: bool, records: Option, + /// `--graphics-records`: the path is a job file of `graphics_in_workers` (`graphics_worker`) + graphics_records: bool, direct: bool, sample: usize, seed: u64, @@ -852,6 +854,7 @@ fn parse_args(args: &[String]) -> Result { pipelines: false, used_only: false, records: None, + graphics_records: false, direct: false, sample: 200, seed: 1, @@ -891,6 +894,7 @@ fn parse_args(args: &[String]) -> Result { "--pipelines" => opts.pipelines = true, "--used-only" | "--used" => opts.used_only = true, "--records" => opts.records = Some(PathBuf::from(p.value("--records")?)), + "--graphics-records" => opts.graphics_records = true, "--direct" => opts.direct = true, "--sample" => opts.sample = p.parse_usize("--sample")?, "--seed" => opts.seed = p.parse_u64("--seed")?, @@ -954,6 +958,9 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let windows = opts.windows; if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } }; + if opts.graphics_records { + return graphics_worker(path, runtime_windows()); + } let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -1778,6 +1785,8 @@ pub(crate) struct LaunchPreparation { /// The worker processes building compute pipelines (0: none; `done` and `total` then count /// the records translated here, with them the records the workers have passed). pub workers: AtomicUsize, + /// The workers build graphics pipelines (`graphics_in_workers`): `done` and `total` count those. + pub graphics: std::sync::atomic::AtomicBool, /// The shaders earlier runs used (`pso_async::earlier_used_shaders`), when there are any: /// only their records are translated before the title starts, and it translates another /// when it first uses it. `XCL_PREPARE_ALL=1`: every record, as without the list. @@ -1822,20 +1831,26 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } let workers = prepare_workers(); - for input in inputs { + for input in &inputs { if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } // a pack: its stages here, its compute pipelines in worker processes (the driver builds // about two pipelines at a time for one process, whatever the processors) if workers > 1 && matches!(input, Input::Pack { .. }) { let n = input.len(); - precompile(&input, usize::MAX, windows, None, None, false, None, None, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, false, None, None, std::time::Instant::now(), Some(progress))?; if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } pipelines_in_workers(&pack, windows, workers, n, progress)?; continue; } - precompile(&input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress))?; } - Ok(()) + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + // `XCL_PREPARE_GRAPHICS=0`: the title builds the graphics pipelines it uses as it goes + if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { + crate::xlog_info!("Shader preparation: graphics pipelines left out (XCL_PREPARE_GRAPHICS=0)"); + return Ok(()); + } + graphics_in_workers(&inputs, windows, workers, progress) } /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title @@ -1926,31 +1941,52 @@ mod claim_tests { /// into `progress`. A worker that fails is noted and the title starts all the same: it builds /// what is missing itself. fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { - use std::io::BufRead; - use std::os::windows::process::CommandExt; - const CREATE_NO_WINDOW: u32 = 0x0800_0000; let me = std::env::current_exe().map_err(|e| e.to_string())?; let used_only = !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); + let t0 = std::time::Instant::now(); + crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); + let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { + let mut c = worker_command(&me); + c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + if used_only { c.arg("--used-only"); } + c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); + c + }); + if cancelled { return Err("Shader preparation cancelled".into()); } + crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); + Ok(()) +} + +/// A preparation worker: this program, not a host and not a launcher's child, a builder that +/// ends when this process does. +fn worker_command(me: &Path) -> std::process::Command { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut c = std::process::Command::new(me); + for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS"] { c.env_remove(gone); } + c.env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()); + if std::env::var_os("XCL_DXC_THREADS").is_none() { c.env("XCL_DXC_THREADS", "2"); } + if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", "1"); } + c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).creation_flags(CREATE_NO_WINDOW); + c +} + +/// `workers` worker processes (`command(i)`), their progress lines (`progress_count`, each of its +/// own part) the count of `records` in all on the screen while they run: whether preparation was +/// cancelled (they are ended then), how many failed, and the summary line each wrote last +/// (`graphics_summary`). +fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut command: impl FnMut(usize) -> std::process::Command) -> (bool, usize, Vec) { + use std::io::BufRead; // the workers' pass has its own count on the screen: the records they have passed let (done_before, total_before) = (progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed)); progress.done.store(0, Ordering::Relaxed); progress.total.store(records, Ordering::Relaxed); progress.workers.store(workers, Ordering::Relaxed); let counts: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); - let t0 = std::time::Instant::now(); - crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); + let summaries: Vec> = (0..workers).map(|_| Mutex::new(String::new())).collect(); let mut children = Vec::new(); for i in 0..workers { - let mut c = std::process::Command::new(&me); - c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); - if used_only { c.arg("--used-only"); } - // (not a host, not a launcher's child: a builder that ends when this process does) - for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS"] { c.env_remove(gone); } - c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")).env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()); - if std::env::var_os("XCL_DXC_THREADS").is_none() { c.env("XCL_DXC_THREADS", "2"); } - if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", "1"); } - c.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).creation_flags(CREATE_NO_WINDOW); - match c.spawn() { + match command(i).spawn() { Ok(child) => children.push((i, child)), Err(e) => crate::xlog_warn!("Shader preparation: worker {i} did not start: {e}"), } @@ -1958,7 +1994,7 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz let cancelled = std::thread::scope(|s| { for (i, child) in children.iter_mut() { let Some(err) = child.stderr.take() else { continue }; - let count = &counts[*i]; + let (count, summary) = (&counts[*i], &summaries[*i]); s.spawn(move || { // (a builder ends its progress lines with a line feed; others pass by) let mut r = std::io::BufReader::new(err); @@ -1966,6 +2002,7 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz while r.read_until(b'\n', &mut buf).is_ok_and(|n| n > 0) { for part in String::from_utf8_lossy(&buf).split(['\r', '\n']) { if let Some(d) = progress_count(part) { count.store(d, Ordering::Relaxed); } + if graphics_summary(part).is_some() { *summary.lock().unwrap() = part.to_string(); } } buf.clear(); } @@ -1994,11 +2031,165 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz progress.workers.store(0, Ordering::Relaxed); progress.total.store(total_before, Ordering::Relaxed); progress.done.store(done_before, Ordering::Relaxed); + (cancelled, failed, summaries.into_iter().map(|s| s.into_inner().unwrap()).collect()) +} + +/// The graphics pipelines earlier runs used (`gfx_records`), built before the title starts by +/// `workers` processes of this program (`graphics_worker`) the way the title builds them, so the +/// title finds their translations and driver blobs on disk and builds each in milliseconds. In +/// worker processes as the compute pipelines: the driver builds about two pipelines at a time for +/// one process, and a driver that ends a worker ends no title. Their shaders come from the title's +/// shader files (`inputs`) by key, as those of `used-shaders.txt`; each worker gets a file of its +/// part (`gfx_records`' format, with the shaders it needs). A failure is noted and the title +/// starts all the same: it builds what is missing itself. +fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { + use crate::hle::d3d12x::gfx_records::{self, Entry}; + let t0 = std::time::Instant::now(); + let payloads = gfx_records::read(&gfx_records::path()); + let records: Vec<(Vec, gfx_records::Record)> = payloads.into_iter().filter_map(|p| match gfx_records::decode(&p) { Some(Entry::Pipeline(r)) => Some((p, r)), _ => None }).collect(); + if records.is_empty() { + crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); + return Ok(()); + } + let shaders = shaders_by_key(inputs, records.iter().flat_map(|(_, r)| r.shaders).filter(|&k| k != 0).collect(), progress); + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); + if missing != 0 { + crate::xlog_info!("Shader preparation: {missing} of {} graphics pipelines left out (their shaders are not in the title's shader files)", records.len()); + } + if buildable.is_empty() { return Ok(()); } + let workers = workers.clamp(1, buildable.len()); + // each worker's part, with the shaders it needs (removed when they are done) + let mut jobs = Vec::new(); + for i in 0..workers { + let path = std::env::temp_dir().join(format!("xcl-prepare-{}-{i}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let mut w = gfx_records::Writer::open(&path, u64::MAX).map_err(|e| format!("{}: {e}", path.display()))?; + let part: Vec = buildable.iter().copied().skip(i).step_by(workers).collect(); + let mut keys = HashSet::new(); + for &k in &part { + w.add(&records[k].0).map_err(|e| format!("{}: {e}", path.display()))?; + keys.extend(records[k].1.shaders.into_iter().filter(|&s| s != 0)); + } + for key in keys { + w.add(&gfx_records::shader_entry(key, &shaders[&key])).map_err(|e| format!("{}: {e}", path.display()))?; + } + jobs.push((path, part.len())); + } + let me = std::env::current_exe().map_err(|e| e.to_string())?; + crate::xlog_info!("Shader preparation: the {} graphics pipelines earlier runs used, in {workers} worker processes", buildable.len()); + progress.graphics.store(true, Ordering::Relaxed); + let (cancelled, failed, summaries) = in_workers(workers, buildable.len(), progress, |i| { + let mut c = worker_command(&me); + c.arg("shaders").arg(&jobs[i].0).args(["--graphics-records", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + // (the title's adapter: its blobs are the ones it takes) + if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } + c + }); + progress.graphics.store(false, Ordering::Relaxed); + for (path, _) in &jobs { let _ = std::fs::remove_file(path); } if cancelled { return Err("Shader preparation cancelled".into()); } - crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); + let sum = summaries.iter().filter_map(|s| graphics_summary(s)).fold([0usize; 4], |a, b| std::array::from_fn(|k| a[k] + b[k])); + crate::xlog_info!( + "Shader preparation: graphics pipelines done in {:.0} s: {} made, {} failed; driver blobs: {} from disk, {} kept ({failed} of {workers} workers failed)", + t0.elapsed().as_secs_f64(), sum[0], sum[1], sum[2], sum[3] + ); Ok(()) } +/// The bytes of the shaders `wanted` (`real::shader_key`) in the title's shader files, looked +/// for on every processor. +fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPreparation) -> std::collections::HashMap> { + let found = Mutex::new(std::collections::HashMap::new()); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + for input in inputs { + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= input.len() || progress.cancel.load(Ordering::Relaxed) { break; } + let Some(blob) = input.get(i).1 else { continue }; + let key = crate::hle::d3d12x::real::shader_key(&blob); + if wanted.contains(&key) { found.lock().unwrap().insert(key, blob); } + }); + } + }); + } + found.into_inner().unwrap() +} + +/// The records (by their index) whose shaders are all in `shaders` and make their set's key, and +/// how many are not. +fn buildable<'a>(records: impl Iterator, shaders: &std::collections::HashMap>) -> (Vec, usize) { + let (mut ok, mut missing) = (Vec::new(), 0); + for (i, r) in records.enumerate() { + let blobs: Option>> = r.shaders.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).cloned()).collect(); + match blobs { + Some(b) if crate::hle::d3d12x::real::shaders_key(&b) == r.key => ok.push(i), + _ => missing += 1, + } + } + (ok, missing) +} + +/// The counts of a graphics worker's last line (`graphics pipelines: 5 made, 1 failed; driver +/// blobs: 2 from disk, 3 kept`): made, failed, blobs from disk, blobs kept. +fn graphics_summary(line: &str) -> Option<[usize; 4]> { + let rest = line.trim().strip_prefix("graphics pipelines: ")?; + let mut n = rest.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).map(|s| s.parse::()); + let out = [n.next()?.ok()?, n.next()?.ok()?, n.next()?.ok()?, n.next()?.ok()?]; + n.next().is_none().then_some(out) +} + +/// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics +/// pipelines of a job file built as the title builds them (`real::prepare_graphics`), with the +/// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` +/// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. +fn graphics_worker(job: &Path, windows: u32) -> i32 { + use crate::hle::d3d12x::gfx_records::{self, Entry}; + end_with_parent(); + // (no title memory here: its windows are given) + crate::gpu::uma::leave_out(); + recomp::pso::set_title_windows(windows); + recomp::dxc::set_memory_reserve(2); + let mut shaders = std::collections::HashMap::new(); + let mut records = Vec::new(); + for p in gfx_records::read(job) { + match gfx_records::decode(&p) { + Some(Entry::Pipeline(r)) => records.push(r), + Some(Entry::Shader(k, b)) => { shaders.insert(k, b); } + None => {} + } + } + let device = match Pipelines::for_adapter("auto") { + Ok(p) => crate::hle::d3d12x::real::prepare_device(p.dev), + Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } + }; + let n = records.len(); + let threads = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse::().ok()).unwrap_or(1).clamp(1, 8); + let (next, done, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let t0 = std::time::Instant::now(); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(r) = records.get(i) else { break }; + let code = r.shaders.map(|k| shaders.get(&k).map(Vec::as_slice)); + let desc = r.desc(code); + // (a pipeline that panics fails; the others are built) + let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { crate::hle::d3d12x::real::prepare_graphics(device, &desc) })).unwrap_or(false); + if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } + let d = done.fetch_add(1, Ordering::Relaxed) + 1; + eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + }); + } + }); + let (hits, _, stored) = crate::hle::d3d12x::real::driver_cache_stats(); + eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); + 0 +} + /// `XCL_PRECOMPILE_PARENT=pid` (set for a title's preparation workers): this process ends when /// that one does, so no builder is left on the GPU behind a title that was ended. fn end_with_parent() { @@ -2083,6 +2274,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if i >= n { break; } + if slice.is_some_and(|(part, count)| i % count != part) { + continue; + } let record_done = || { let d = done.fetch_add(1, Ordering::Relaxed) + 1; if let Some(p) = startup { p.done.fetch_add(1, Ordering::Relaxed); } @@ -2600,6 +2794,43 @@ mod tests { assert_eq!(progress_count("3/4"), None); } + /// A graphics worker's summary gives its counts; its progress lines and others give none. + #[test] + fn a_graphics_workers_summary_gives_its_counts() { + assert_eq!(graphics_summary("graphics pipelines: 512 made, 3 failed; driver blobs: 40 from disk, 470 kept"), Some([512, 3, 40, 470])); + assert_eq!(graphics_summary(" graphics pipelines: 0 made, 0 failed; driver blobs: 0 from disk, 0 kept\r"), Some([0; 4])); + assert_eq!(graphics_summary(" 12/512 (3 s)"), None); + assert_eq!(graphics_summary("graphics pipelines: 5 made"), None); + assert_eq!(graphics_summary("graphics pipelines: 1 made, 2 failed; driver blobs: 3 from disk, 4 kept, 5 more"), None); + assert_eq!(progress_count("graphics pipelines: 512 made, 3 failed; driver blobs: 40 from disk, 470 kept"), None); + } + + /// A graphics record is built when every shader it names is found and they make its set's + /// key (the key `used-pipelines.txt` has); one with a shader not in the title's files, or + /// other shaders under its keys, is left out. + #[test] + fn a_graphics_record_is_built_only_with_its_own_shaders() { + use crate::hle::d3d12x::gfx_records::{decode, encode, Entry}; + use crate::hle::d3d12x::real::{shader_key, shaders_key}; + let (vs, ps) = (b"vertex".to_vec(), b"pixel".to_vec()); + let record = |key: u64, shaders: [u64; 5]| { + let d = windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + match decode(&unsafe { encode(key, shaders, &d) }) { + Some(Entry::Pipeline(r)) => r, + _ => unreachable!(), + } + }; + let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; + let records = [ + record(shaders_key(&[vs.clone(), ps.clone()]), both), + record(shaders_key(&[vs.clone()]), [shader_key(&vs), 0, 0, 0, 0]), + record(shaders_key(&[vs.clone(), b"other".to_vec()]), [shader_key(&vs), shader_key(b"other"), 0, 0, 0]), + record(shaders_key(&[ps.clone(), vs.clone()]), both), + ]; + let shaders = std::collections::HashMap::from([(shader_key(&vs), vs.clone()), (shader_key(&ps), ps.clone())]); + assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1], 2)); + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] From 0a79e6cc818ac75cb852dc1ec09aa4573da21dd8 Mon Sep 17 00:00:00 2001 From: CryingLaughing <62956736+CryingLaughing@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:49:45 +0800 Subject: [PATCH 08/22] Shaders: replay compatible two-pass mesh pipelines at startup Record supported console mesh streams with their fixed-function state and source shader keys. Replay through the existing graphics worker and two-pass translator to populate the runtime driver caches. Keep legacy graphics history compatible and leave unsupported streams to the existing runtime path. --- README.md | 8 +- crates/xcl/src/hle/d3d12x/gfx_records.rs | 220 +++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 121 ++++++++++++- crates/xcl/src/shaders.rs | 97 +++++++--- 4 files changed, 398 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 2855754b5a..3fc900f7ef 100644 --- a/README.md +++ b/README.md @@ -269,10 +269,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder five seconds without progress counts as a stall, and the window shows when the last one ended. XCL prepares supported shader stages and compute pipelines, including split pieces and their whole fallback. Graphics pipelines are created during play the first - time; the ones a run used are recorded with their state (`used-graphics-pipelines.bin` beside - the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts - on the next launch, with their driver blobs kept, so the title makes them from those in - milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Later launches reuse matching cache entries. + time. The startup history records supported graphics descriptors and two-pass mesh streams with + their state (`used-graphics-pipelines.bin` beside the shader cache, capped by `XCL_GFX_RECORDS_MB` + at 64 MB by default). On the next launch, XCL builds the recorded pipelines before the title starts + and keeps their driver blobs for reuse. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Closing the window cancels the launch. A compiler or driver failure stops it and reports 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 diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index cb4b872354..552e0ecb46 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -11,9 +11,11 @@ //! entry = length u32, check u32 (the low half of fnv64 of the payload), payload //! payload = 1 key u64 shaders [u64; 5] state input* a pipeline //! | 2 key u64 bytes a shader (preparation job files only) -//! key = `real::shaders_key` of the set (as `used-pipelines.txt` has it); in a shader entry +//! | 3 key u64 shaders [u64; 2] layout state a mesh pipeline stream +//! key = `real::shaders_key` of the set, in mesh then PS order for mesh; in a shader entry, //! `real::shader_key` of it -//! shaders = `real::shader_key` of the VS, PS, DS, HS, GS (0: none) +//! shaders = `real::shader_key` of VS, PS, DS, HS, GS, or mesh, PS (0: none) +//! layout = subobject count (u8), then subobject types in stream order (u8 each) //! state = every field of the description but its pointers, in `state`'s order (varints) //! input = count, then each element's semantic name (length, bytes), index, format, slot, //! offset, class, step rate (varints) @@ -34,11 +36,13 @@ use std::path::{Path, PathBuf}; use windows::Win32::Graphics::Direct3D12::*; const MAGIC: &[u8; 8] = b"XCLGFXP\0"; -/// The layout of an entry: a change makes every file of the older one read as none. +/// The file format and existing entry layouts. Optional new tags keep earlier entries readable. const VERSION: u32 = 1; const HEADER: usize = 12; const PIPELINE: u8 = 1; const SHADER: u8 = 2; +const MESH_PIPELINE: u8 = 3; +const MAX_MESH_LAYOUT: usize = 14; // root, mesh (MS or AS), PS, and eleven scalar state types /// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). pub(crate) fn path() -> PathBuf { @@ -84,6 +88,12 @@ impl Reader<'_> { fn u32var(&mut self) -> Option { self.var().and_then(|v| u32::try_from(v).ok()) } + fn bounded_var(&mut self, max: u32) -> Option { + let before = self.0.len(); + let v = self.u32var()?; + let bits = (u32::BITS - v.leading_zeros()).max(1); + (before - self.0.len() == bits.div_ceil(7) as usize && v <= max).then_some(v) + } fn u64(&mut self) -> Option { let (b, rest) = self.0.split_at_checked(8)?; self.0 = rest; @@ -100,25 +110,25 @@ impl Reader<'_> { /// cached blob), each as a u32 handed to `f`, which may change it: one order for writing and /// reading. What the title's translated pipeline is made of beside its shaders /// (`real::graphics_blob_key` hashes the same). -fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32)) { +fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32, u32)) { macro_rules! int { ($x:expr) => {{ let mut v = $x as u32; - f(&mut v); + f(&mut v, u32::MAX); $x = v as i32; }}; } macro_rules! byte { ($x:expr) => {{ let mut v = $x as u32; - f(&mut v); + f(&mut v, u8::MAX.into()); $x = v as u8; }}; } macro_rules! float { ($x:expr) => {{ let mut v = $x.to_bits(); - f(&mut v); + f(&mut v, u32::MAX); $x = f32::from_bits(v); }}; } @@ -137,7 +147,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(rt.LogicOp.0); byte!(rt.RenderTargetWriteMask); } - f(&mut d.SampleMask); + f(&mut d.SampleMask, u32::MAX); let r = &mut d.RasterizerState; int!(r.FillMode.0); int!(r.CullMode.0); @@ -148,7 +158,7 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) int!(r.DepthClipEnable.0); int!(r.MultisampleEnable.0); int!(r.AntialiasedLineEnable.0); - f(&mut r.ForcedSampleCount); + f(&mut r.ForcedSampleCount, u32::MAX); int!(r.ConservativeRaster.0); let z = &mut d.DepthStencilState; int!(z.DepthEnable.0); @@ -165,14 +175,14 @@ fn state(d: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, f: &mut dyn FnMut(&mut u32) } int!(d.IBStripCutValue.0); int!(d.PrimitiveTopologyType.0); - f(&mut d.NumRenderTargets); + f(&mut d.NumRenderTargets, 8); for format in &mut d.RTVFormats { int!(format.0); } int!(d.DSVFormat.0); - f(&mut d.SampleDesc.Count); - f(&mut d.SampleDesc.Quality); - f(&mut d.NodeMask); + f(&mut d.SampleDesc.Count, u32::MAX); + f(&mut d.SampleDesc.Quality, u32::MAX); + f(&mut d.NodeMask, u32::MAX); int!(d.Flags.0); } @@ -187,7 +197,7 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE } // (a copy for `state`, which takes the fields by `&mut`; its pointers are not used) let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); - state(&mut copy, &mut |v| put_var(&mut out, *v as u64)); + state(&mut copy, &mut |v, _| put_var(&mut out, *v as u64)); let il = &d.InputLayout; let elems = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) } else { &[] }; put_var(&mut out, elems.len() as u64); @@ -202,6 +212,73 @@ pub(crate) unsafe fn encode(key: u64, shaders: [u64; 5], d: &D3D12_GRAPHICS_PIPE out } +fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { + if shaders[0] == 0 || layout.len() > MAX_MESH_LAYOUT { + return false; + } + let mut seen = 0u32; + for &id in layout { + match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(id as i32) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS => {} + _ => return false, + } + let bit = 1 << id; + if seen & bit != 0 { + return false; + } + seen |= bit; + } + let has = |kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| seen & (1 << kind.0) != 0; + (has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS) != has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS)) + && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS) == (shaders[1] != 0) +} + +/// A mesh stream entry with shader keys in mesh, PS order and subobjects in their original order. +pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option> { + if key == 0 || !valid_mesh_layout(shaders, layout) || d.NumRenderTargets > 8 { + return None; + } + let mut values = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + BlendState: d.BlendState, + SampleMask: d.SampleMask, + RasterizerState: d.RasterizerState, + DepthStencilState: d.DepthStencilState, + IBStripCutValue: d.IBStripCutValue, + PrimitiveTopologyType: d.PrimitiveTopologyType, + NumRenderTargets: d.NumRenderTargets, + RTVFormats: d.RTVFormats, + DSVFormat: d.DSVFormat, + SampleDesc: d.SampleDesc, + NodeMask: d.NodeMask, + Flags: d.Flags, + ..Default::default() + }; + let mut out = Vec::with_capacity(256); + out.push(MESH_PIPELINE); + out.extend_from_slice(&key.to_le_bytes()); + for shader in shaders { + out.extend_from_slice(&shader.to_le_bytes()); + } + out.push(layout.len() as u8); + out.extend(layout.iter().map(|&id| id as u8)); + state(&mut values, &mut |v, _| put_var(&mut out, (*v).into())); + Some(out) +} + /// A shader entry (the preparation's job files): `bytes`, of `real::shader_key` `key`. pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { let mut out = Vec::with_capacity(9 + bytes.len()); @@ -241,11 +318,48 @@ impl Record { } } +pub(crate) struct MeshRecord { + pub key: u64, + pub shaders: [u64; 2], + pub layout: Vec, + desc: Box, +} + +// The decoder starts with null pointers and only fills scalar fields. The descriptor is immutable. +unsafe impl Send for MeshRecord {} +unsafe impl Sync for MeshRecord {} + +impl MeshRecord { + pub(crate) fn state(&self) -> &D3D12_GRAPHICS_PIPELINE_STATE_DESC { + &self.desc + } +} + pub(crate) enum Entry { Pipeline(Record), + MeshPipeline(MeshRecord), Shader(u64, Vec), } +fn decode_mesh(key: u64, mut r: Reader<'_>) -> Option { + let shaders = [r.u64()?, r.u64()?]; + let n = *r.bytes(1)?.first()? as usize; + if key == 0 || n > MAX_MESH_LAYOUT { + return None; + } + let layout: Vec = r.bytes(n)?.iter().map(|&id| id.into()).collect(); + if !valid_mesh_layout(shaders, &layout) { + return None; + } + let mut desc = Box::::default(); + let mut valid = true; + state(&mut desc, &mut |v, max| match r.bounded_var(max) { + Some(x) => *v = x, + None => valid = false, + }); + (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc }) +} + /// The entry of `payload` (None: not one this version writes). pub(crate) fn decode(payload: &[u8]) -> Option { let (&tag, rest) = payload.split_first()?; @@ -254,6 +368,9 @@ pub(crate) fn decode(payload: &[u8]) -> Option { if tag == SHADER { return Some(Entry::Shader(key, r.0.to_vec())); } + if tag == MESH_PIPELINE { + return decode_mesh(key, r).map(Entry::MeshPipeline); + } if tag != PIPELINE { return None; } @@ -263,7 +380,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { } let mut desc: Box = Box::new(unsafe { std::mem::zeroed() }); let mut short = false; - state(&mut desc, &mut |v| match r.u32var() { + state(&mut desc, &mut |v, _| match r.u32var() { Some(x) => *v = x, None => short = true, }); @@ -578,7 +695,78 @@ mod tests { let payload = unsafe { encode(9, [9, 0, 0, 0, 0], &described()) }; assert!(decode(&payload[..payload.len() - 1]).is_none(), "cut short"); assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none(), "a byte too many"); - assert!(decode(&[3, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + assert!(decode(&[u8::MAX, 0, 0, 0, 0, 0, 0, 0, 0]).is_none(), "another kind of entry"); + } + + #[test] + fn a_mesh_entry_preserves_moved_shader_slot_order_and_state() { + let layout = [ + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, + ].map(|kind| kind.0 as u32); + let shaders = [0x13, 0x27]; + let mut desc = described(); + let ps = b"pixel"; + desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }; + let payload = encode_mesh(0x1234, shaders, &layout, &desc).unwrap(); + let Some(Entry::MeshPipeline(record)) = decode(&payload) else { panic!("expected a mesh entry") }; + assert_eq!((record.key, record.shaders), (0x1234, shaders)); + assert_eq!(record.layout, layout); + assert_eq!(record.state().RasterizerState.DepthBias, desc.RasterizerState.DepthBias); + assert_eq!(record.state().RTVFormats, desc.RTVFormats); + assert!(record.state().PS.pShaderBytecode.is_null()); + assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state()).unwrap(), payload); + } + + #[test] + fn mesh_entries_require_supported_unique_layout_and_exact_payload() { + let ms = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32; + let moved = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS.0 as u32; + let ps = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32; + let input = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32; + let d = described(); + for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps], vec![ms, input]] { + assert!(encode_mesh(1, [1, 0], &layout, &d).is_none(), "unsupported layout {layout:?}"); + } + assert!(encode_mesh(1, [1, 2], &[ms], &d).is_none()); + assert!(encode_mesh(1, [0, 0], &[ms], &d).is_none()); + let payload = encode_mesh(1, [1, 0], &[ms], &d).unwrap(); + assert!(decode(&payload[..payload.len() - 1]).is_none()); + assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none()); + + let count_at = 1 + 3 * std::mem::size_of::(); + let mut invalid = payload.clone(); + invalid[count_at] = MAX_MESH_LAYOUT as u8 + 1; + assert!(decode(&invalid).is_none()); + invalid[count_at] = 1; + invalid[count_at + 1] = input as u8; + assert!(decode(&invalid).is_none()); + let state_at = count_at + 2; + let overlong = [&payload[..state_at], &[0x81, 0], &payload[state_at + 1..]].concat(); + assert!(decode(&overlong).is_none()); + } + + #[test] + fn legacy_pipeline_and_mesh_entries_share_version_one_history() { + let dir = directory("mesh-version-one"); + let path = dir.0.join("records.bin"); + let legacy = unsafe { encode(3, [3, 0, 0, 0, 0], &described()) }; + let shader = shader_entry(5, b"mesh"); + let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described()).unwrap(); + let mut writer = Writer::open(&path, 1 << 20).unwrap(); + writer.add(&legacy).unwrap(); + writer.add(&mesh).unwrap(); + writer.add(&shader).unwrap(); + drop(writer); + assert_eq!(&std::fs::read(&path).unwrap()[8..HEADER], &1u32.to_le_bytes()); + assert_eq!(read(&path), vec![legacy.clone(), mesh.clone(), shader.clone()]); + assert_eq!(pipeline(&legacy).key, 3); + assert!(matches!(decode(&mesh), Some(Entry::MeshPipeline(_)))); + assert!(matches!(decode(&shader), Some(Entry::Shader(5, _)))); } /// Written, read back in order, each entry once; a file cut short in its last entry keeps the diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5781f22adf..c0e4549be7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5429,6 +5429,10 @@ pub(crate) fn shader_key(blob: &[u8]) -> u64 { } pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { + shader_set_key(blobs.iter().map(Vec::as_slice)) +} + +pub(crate) fn shader_set_key<'a>(blobs: impl IntoIterator) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); @@ -5474,8 +5478,11 @@ impl OwnedDesc { } /// A graphics pipeline's entry for the next run's preparation (`gfx_records`), of the set - /// `key` whose shaders' keys are `parts`; None for any other. + /// `key` whose shaders' keys are `parts`, or an eligible mesh stream's entry. unsafe fn record(&self, key: u64, parts: &[u64]) -> Option> { + if let OwnedDesc::Stream(_, stream, _) = self { + return record_mesh_stream(stream); + } let OwnedDesc::Graphics(d, ..) = self else { return None }; // (`own_graphics` copied the stages it has, in this order) let mut parts = parts.iter(); @@ -6027,6 +6034,118 @@ unsafe fn payload_shader<'a>(p: &[u8]) -> Option<&'a [u8]> { shader_bytes(&b) } +/// Keep the source states the mesh translator will use again during preparation. +unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { + let subs = stream_subobjects(stream)?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut layout = Vec::with_capacity(subs.len()); + let (mut ms, mut amplification, mut ps) = (None, None, None); + let (mut seen, mut size) = (0u32, 0usize); + + fn value(payload: &[u8]) -> Option { + (payload.len() == std::mem::size_of::()).then(|| unsafe { std::ptr::read_unaligned(payload.as_ptr().cast()) }) + } + + for (ty, payload) in subs { + let (_, align) = super::null::subobject_payload(ty)?; + size += (align + payload.len() + 7) & !7; + let bit = 1u32 << ty; + if seen & bit != 0 { + return None; + } + seen |= bit; + match ty { + 0 => {} // The translator supplies its own root signature. + 19 => continue, // The title's cache blob is never an input to translation. + 2 | 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 2 => ps = Some(payload_shader(payload)?), + 24 => amplification = Some(payload_shader(payload)?), + 25 => ms = Some(payload_shader(payload)?), + 8 => desc.BlendState = value(payload)?, + 9 => desc.SampleMask = value(payload)?, + 10 => desc.RasterizerState = value(payload)?, + 11 => desc.DepthStencilState = value(payload)?, + 13 => desc.IBStripCutValue = value(payload)?, + 14 => desc.PrimitiveTopologyType = value(payload)?, + 15 => { + let rt: D3D12_RT_FORMAT_ARRAY = value(payload)?; + if rt.NumRenderTargets > 8 { + return None; + } + desc.NumRenderTargets = rt.NumRenderTargets; + desc.RTVFormats = rt.RTFormats; + } + 16 => desc.DSVFormat = value(payload)?, + 17 => desc.SampleDesc = value(payload)?, + 18 => desc.NodeMask = value(payload)?, + 20 => desc.Flags = value(payload)?, + _ => return None, + } + layout.push(ty); + } + if size != stream.len() || (ms.is_some() && amplification.is_some()) { + return None; + } + let ms = ms.or(amplification)?; + if !crate::gpu::xbox::parse(ms).is_some_and(|shader| shader.stage == "MS") { + return None; + } + let shaders = [shader_key(ms), ps.map_or(0, shader_key)]; + let key = shader_set_key(std::iter::once(ms).chain(ps)); + super::gfx_records::encode_mesh(key, shaders, &layout, &desc) +} + +/// Build both recorded mesh passes on the adopted device from `prepare_device`. +/// +/// # Safety +/// `device` must be the live adopted device returned from `prepare_device`. +pub(crate) unsafe fn replay_mesh_record( + device: usize, + record: &super::gfx_records::MeshRecord, + shaders: [Option<&[u8]>; 2], +) -> Result<(), String> { + let [Some(ms), ps] = shaders else { return Err("mesh shader missing from the job".into()) }; + if record.shaders != [shader_key(ms), ps.map_or(0, shader_key)] || + record.key != shader_set_key(std::iter::once(ms).chain(ps)) + { + return Err("mesh shaders do not match the recorded keys".into()); + } + + let d = record.state(); + let mut stream = StreamOut::default(); + for &ty in &record.layout { + let subobject = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32); + match ty { + 0 => stream.put(subobject, &std::ptr::null::()), + 2 => stream.shader(subobject, ps.ok_or("pixel shader missing from the job")?), + 24 | 25 => stream.shader(subobject, ms), + 8 => stream.put(subobject, &d.BlendState), + 9 => stream.put(subobject, &d.SampleMask), + 10 => stream.put(subobject, &d.RasterizerState), + 11 => stream.put(subobject, &d.DepthStencilState), + 13 => stream.put(subobject, &d.IBStripCutValue), + 14 => stream.put(subobject, &d.PrimitiveTopologyType), + 15 => stream.put(subobject, &D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }), + 16 => stream.put(subobject, &d.DSVFormat), + 17 => stream.put(subobject, &d.SampleDesc), + 18 => stream.put(subobject, &d.NodeMask), + 20 => stream.put(subobject, &d.Flags), + _ => return Err(format!("unsupported mesh subobject {ty}")), + } + } + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + let mut out = std::ptr::null_mut(); + let hr = unsafe { + translated_mesh_stream(device as *mut c_void, desc.as_ptr().cast(), &pc_iid(Kind::PipelineState), &mut out) + }; + super::pso_async::release(out as usize); + match hr { + Some(hr) if hr >= 0 && !out.is_null() => Ok(()), + Some(hr) => Err(format!("mesh pipeline replay failed ({hr:#x})")), + None => Err("mesh pipeline record could not be translated".into()), + } +} + /// The passthrough mesh shader emits triangles for both translated MS and GS pipelines. fn two_pass_mesh_stream(rs: *mut c_void, ms: &[u8], ps: Option<&[u8]>) -> StreamOut { let mut out = StreamOut::default(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 82a3ee2a48..66ccb63bef 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -12,6 +12,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; +use crate::hle::d3d12x::gfx_records; /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). @@ -2043,15 +2044,19 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// part (`gfx_records`' format, with the shaders it needs). A failure is noted and the title /// starts all the same: it builds what is missing itself. fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { - use crate::hle::d3d12x::gfx_records::{self, Entry}; let t0 = std::time::Instant::now(); let payloads = gfx_records::read(&gfx_records::path()); - let records: Vec<(Vec, gfx_records::Record)> = payloads.into_iter().filter_map(|p| match gfx_records::decode(&p) { Some(Entry::Pipeline(r)) => Some((p, r)), _ => None }).collect(); + let records: Vec<_> = payloads.into_iter().filter_map(|payload| { + let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?; + Some((payload, record)) + }).collect(); if records.is_empty() { crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); return Ok(()); } - let shaders = shaders_by_key(inputs, records.iter().flat_map(|(_, r)| r.shaders).filter(|&k| k != 0).collect(), progress); + let wanted = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) + .filter(|&key| key != 0).collect(); + let shaders = shaders_by_key(inputs, wanted, progress); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); if missing != 0 { @@ -2069,7 +2074,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: let mut keys = HashSet::new(); for &k in &part { w.add(&records[k].0).map_err(|e| format!("{}: {e}", path.display()))?; - keys.extend(records[k].1.shaders.into_iter().filter(|&s| s != 0)); + keys.extend(records[k].1.identity().1.iter().copied().filter(|&key| key != 0)); } for key in keys { w.add(&gfx_records::shader_entry(key, &shaders[&key])).map_err(|e| format!("{}: {e}", path.display()))?; @@ -2119,14 +2124,37 @@ fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPrepa found.into_inner().unwrap() } +enum GraphicsHistoryRecord { + Legacy(gfx_records::Record), + Mesh(gfx_records::MeshRecord), +} + +impl GraphicsHistoryRecord { + fn from_entry(entry: gfx_records::Entry) -> Option { + match entry { + gfx_records::Entry::Pipeline(record) => Some(Self::Legacy(record)), + gfx_records::Entry::MeshPipeline(record) => Some(Self::Mesh(record)), + gfx_records::Entry::Shader(..) => None, + } + } + + fn identity(&self) -> (u64, &[u64]) { + match self { + Self::Legacy(record) => (record.key, &record.shaders), + Self::Mesh(record) => (record.key, &record.shaders), + } + } +} + /// The records (by their index) whose shaders are all in `shaders` and make their set's key, and /// how many are not. -fn buildable<'a>(records: impl Iterator, shaders: &std::collections::HashMap>) -> (Vec, usize) { +fn buildable<'a>(records: impl Iterator, shaders: &HashMap>) -> (Vec, usize) { let (mut ok, mut missing) = (Vec::new(), 0); - for (i, r) in records.enumerate() { - let blobs: Option>> = r.shaders.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).cloned()).collect(); + for (i, record) in records.enumerate() { + let (key, keys) = record.identity(); + let blobs: Option> = keys.iter().filter(|&&k| k != 0).map(|k| shaders.get(k).map(Vec::as_slice)).collect(); match blobs { - Some(b) if crate::hle::d3d12x::real::shaders_key(&b) == r.key => ok.push(i), + Some(blobs) if crate::hle::d3d12x::real::shader_set_key(blobs.iter().copied()) == key => ok.push(i), _ => missing += 1, } } @@ -2143,11 +2171,11 @@ fn graphics_summary(line: &str) -> Option<[usize; 4]> { } /// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics -/// pipelines of a job file built as the title builds them (`real::prepare_graphics`), with the +/// pipelines of a job file built as the title builds them, with the /// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` /// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. fn graphics_worker(job: &Path, windows: u32) -> i32 { - use crate::hle::d3d12x::gfx_records::{self, Entry}; + use crate::hle::d3d12x::real; end_with_parent(); // (no title memory here: its windows are given) crate::gpu::uma::leave_out(); @@ -2157,13 +2185,13 @@ fn graphics_worker(job: &Path, windows: u32) -> i32 { let mut records = Vec::new(); for p in gfx_records::read(job) { match gfx_records::decode(&p) { - Some(Entry::Pipeline(r)) => records.push(r), - Some(Entry::Shader(k, b)) => { shaders.insert(k, b); } + Some(gfx_records::Entry::Shader(key, code)) => { shaders.insert(key, code); } + Some(entry) => records.extend(GraphicsHistoryRecord::from_entry(entry)), None => {} } } let device = match Pipelines::for_adapter("auto") { - Ok(p) => crate::hle::d3d12x::real::prepare_device(p.dev), + Ok(p) => real::prepare_device(p.dev), Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } }; let n = records.len(); @@ -2175,17 +2203,24 @@ fn graphics_worker(job: &Path, windows: u32) -> i32 { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); let Some(r) = records.get(i) else { break }; - let code = r.shaders.map(|k| shaders.get(&k).map(Vec::as_slice)); - let desc = r.desc(code); + let code = |key| shaders.get(&key).map(Vec::as_slice); // (a pipeline that panics fails; the others are built) - let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { crate::hle::d3d12x::real::prepare_graphics(device, &desc) })).unwrap_or(false); + let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { + GraphicsHistoryRecord::Legacy(record) => { + let desc = record.desc(record.shaders.map(code)); + unsafe { real::prepare_graphics(device, &desc) } + } + GraphicsHistoryRecord::Mesh(record) => { + unsafe { real::replay_mesh_record(device, record, record.shaders.map(code)).is_ok() } + } + })).unwrap_or(false); if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } let d = done.fetch_add(1, Ordering::Relaxed) + 1; eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); }); } }); - let (hits, _, stored) = crate::hle::d3d12x::real::driver_cache_stats(); + let (hits, _, stored) = real::driver_cache_stats(); eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); 0 } @@ -2810,25 +2845,33 @@ mod tests { /// other shaders under its keys, is left out. #[test] fn a_graphics_record_is_built_only_with_its_own_shaders() { - use crate::hle::d3d12x::gfx_records::{decode, encode, Entry}; + use crate::hle::d3d12x::gfx_records::{decode, encode, encode_mesh}; use crate::hle::d3d12x::real::{shader_key, shaders_key}; - let (vs, ps) = (b"vertex".to_vec(), b"pixel".to_vec()); - let record = |key: u64, shaders: [u64; 5]| { - let d = windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); - match decode(&unsafe { encode(key, shaders, &d) }) { - Some(Entry::Pipeline(r)) => r, - _ => unreachable!(), - } + use windows::Win32::Graphics::Direct3D12::{ + D3D12_GRAPHICS_PIPELINE_STATE_DESC, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + }; + let (vs, ps, ms) = (b"vertex".to_vec(), b"pixel".to_vec(), b"mesh".to_vec()); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let record = |key, shaders| { + GraphicsHistoryRecord::from_entry(decode(&unsafe { encode(key, shaders, &desc) }).unwrap()).unwrap() }; let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; + let mesh = |key, shaders| { + let layout = [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32]; + let payload = encode_mesh(key, shaders, &layout, &desc).unwrap(); + GraphicsHistoryRecord::from_entry(decode(&payload).unwrap()).unwrap() + }; let records = [ record(shaders_key(&[vs.clone(), ps.clone()]), both), record(shaders_key(&[vs.clone()]), [shader_key(&vs), 0, 0, 0, 0]), record(shaders_key(&[vs.clone(), b"other".to_vec()]), [shader_key(&vs), shader_key(b"other"), 0, 0, 0]), record(shaders_key(&[ps.clone(), vs.clone()]), both), + mesh(shaders_key(&[ms.clone(), ps.clone()]), [shader_key(&ms), shader_key(&ps)]), + mesh(shaders_key(&[ps.clone(), ms.clone()]), [shader_key(&ms), shader_key(&ps)]), ]; - let shaders = std::collections::HashMap::from([(shader_key(&vs), vs.clone()), (shader_key(&ps), ps.clone())]); - assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1], 2)); + let shaders = HashMap::from([(shader_key(&vs), vs), (shader_key(&ps), ps), (shader_key(&ms), ms)]); + assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); } /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the From 4d78a9ba2061265984f9dccf3123fb0102a71e71 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:59:11 -0500 Subject: [PATCH 09/22] Shaders: discover and stage pipeline recipes from offline archives Resolve shader and fixed-state selectors using a local layout profile. Publish a deduplicated native preparation job only after its recipes and shader references have been validated. --- scripts/pso_corpus/archive-profile.md | 21 ++ scripts/pso_corpus/pso_archive.py | 181 +++++++++++++++ scripts/pso_corpus/pso_directory.py | 50 +++++ scripts/pso_corpus/stage.py | 267 +++++++++++++++++++++++ scripts/pso_corpus/test_pso_archive.py | 144 ++++++++++++ scripts/pso_corpus/test_pso_directory.py | 36 +++ scripts/pso_corpus/test_stage.py | 102 +++++++++ 7 files changed, 801 insertions(+) create mode 100644 scripts/pso_corpus/archive-profile.md create mode 100644 scripts/pso_corpus/pso_archive.py create mode 100644 scripts/pso_corpus/pso_directory.py create mode 100644 scripts/pso_corpus/stage.py create mode 100644 scripts/pso_corpus/test_pso_archive.py create mode 100644 scripts/pso_corpus/test_pso_directory.py create mode 100644 scripts/pso_corpus/test_stage.py diff --git a/scripts/pso_corpus/archive-profile.md b/scripts/pso_corpus/archive-profile.md new file mode 100644 index 0000000000..921bc483f0 --- /dev/null +++ b/scripts/pso_corpus/archive-profile.md @@ -0,0 +1,21 @@ +# Preparing a pipeline journal from an archive + +Run `python pso_archive.py profile.json archive.bin pipelines.bin` with Python 3.10 or newer. Use `--records tables.bin` when a locally extracted archive member contains the tables and the shader data remains in the original archive. The command reports the number of distinct sources and recipes. It replaces the destination after every record resolves and the journal has been written. + +A profile describes the local archive layout and how its selectors map to XCL wire records. The profile author must establish these mappings for the archive revision. Include optional `archive_sha256` to check the source archive. When the tables occupy compressed blocks, list their archive ranges in order under optional `record_chunks`, using the same range format as `sources`. Table offsets then address the concatenated decoded blocks. An absent selector raises an error. Use an explicitly empty variant list for an intentionally excluded record type. + +| Version 1 field | Meaning | +|---|---| +| `sources` | Named shader byte ranges with `offset` and `size`. For `encoding` equal to `deflate` (raw) or `zlib`, supply the exact compressed stream length and `raw_size`. | +| `stage_maps` | Named dictionaries mapping a decimal selector string to a named source, or `null` for an absent optional shader stage. | +| `states` | Named dictionaries mapping decimal selector strings to hex-encoded state fragments in XCL wire order. | +| `tables` | A list of fixed-stride tables with `offset`, `count`, `stride`, and named `fields` given as `[byte_offset, width]` within a record. Integers use 1, 2, 4 or 8 little-endian bytes. | +| `variants` | A table's list of wire templates. Optionally use `variant_field` to select between lists keyed by decimal field value. Each variant supplies `kind` (C, G or M), the XCL journal `windows` byte, and an ordered `parts` list. | + +A part is one of `{"hex":"..."}` for a literal, `{"field":["field name","state dictionary"]}` for a selected fragment, or `{"stage":["field name","stage dictionary"]}` for a shader identity computed from the selected local source. Templates must follow XCL's journal wire format, including any required zeroed fields and attachment layouts. The synthetic compute profile in `test_pso_archive.py` shows these parts in descriptor order. + +The generated XCLPJ001 journal carries each required shader source once, followed by unique recipes. The tool enumerates the record tables and variants in the supplied profile. Coverage of gameplay paths depends on what that profile models. + +If the archive contains its own dictionaries, define optional `shader_directories` and `state_directories` instead of listing entries by hand. Both take named directories with `offset`, `count`, `stride`, and an optional integer `id` field (defaults to the row ordinal). Offsets refer to the record file or decoded record chunks. A shader directory requires integer fields `location` and `size`, with optional `data_base`, `encoding` and integer `raw_size` field. Shader locations resolve against the original archive. A state directory requires `fragment: [offset, byte_length]` within the row. The named directory becomes a stage or state dictionary for the existing template operations. Conflicting entries raise an error. + +Run `python -m unittest -v test_pso_archive test_pso_directory` in the script directory. diff --git a/scripts/pso_corpus/pso_archive.py b/scripts/pso_corpus/pso_archive.py new file mode 100644 index 0000000000..23c4b0a785 --- /dev/null +++ b/scripts/pso_corpus/pso_archive.py @@ -0,0 +1,181 @@ +"""Expand archive selector tables into a self-contained XCL pipeline journal.""" + +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +from pathlib import Path +import shutil +import struct +import tempfile +import zlib + +from pso_directory import read_directories + +FRAME = struct.Struct(" len(record): + raise ValueError(f"invalid little-endian selector field {spec}") + return str(int.from_bytes(record[offset:offset + size], "little")) + + +def expand(profile, archive, records, shader_frames, recipe_frames): + if profile["version"] != 1: + raise ValueError("unknown profile version") + read_directories(profile, records) + sources = {} + for table in profile["tables"]: + stride = table["stride"] + if not 0 < stride <= LIMIT or table["count"] < 0 or table["offset"] < 0: + raise ValueError("invalid record table") + for index in range(table["count"]): + record = read_at(records, table["offset"] + stride * index, stride) + ids = {name: field(record, spec) for name, spec in table["fields"].items()} + variants = table["variants"] + if "variant_field" in table: + variants = variants[ids[table["variant_field"]]] + for variant in variants: + pieces = [] + stage_ids = [] + for part in variant["parts"]: + if len(part) != 1: + raise ValueError("wire fragment requires exactly one operation") + op, arg = next(iter(part.items())) + if op == "hex": + value = bytes.fromhex(arg) + elif op == "field": + name, state_map = arg + value = bytes.fromhex(profile["states"][state_map][ids[name]]) + elif op == "stage": + name, stage_map = arg + source = profile["stage_maps"][stage_map][ids[name]] + if source is None: + value = bytes(8) + else: + entry = profile["sources"][source] + region = (entry["offset"], entry["size"], entry.get("encoding", "raw"), entry.get("raw_size")) + if region not in sources: + blob = source_bytes(archive, entry) + key = f"{fnv64(blob):016x}" + shader_frames.add(key, "S", 0, blob) + sources[region] = key + key = sources[region] + value = struct.pack(" len(record): + raise ValueError("invalid directory integer field") + return int.from_bytes(record[offset:offset + width], "little") + + +def directory_entries(stream, directory): + offset, count, stride = (directory[k] for k in ("offset", "count", "stride")) + if offset < 0 or count < 0 or not 0 < stride <= 64 << 20: + raise ValueError("invalid directory range") + stream.seek(offset) + for row in range(count): + record = stream.read(stride) + if len(record) != stride: + raise ValueError(f"truncated directory at row {row}") + key = integer(record, directory["id"]) if "id" in directory else row + yield str(key), record + + +def add_entry(mapping, key, value): + if key in mapping and mapping[key] != value: + raise ValueError(f"ambiguous directory entry {key}") + mapping[key] = value + + +def read_directories(profile, records): + """Populate the maps for the ordinary profile expander from the record file.""" + for name, directory in profile.get("shader_directories", {}).items(): + stages = profile.setdefault("stage_maps", {}).setdefault(name, {}) + sources = profile.setdefault("sources", {}) + for key, record in directory_entries(records, directory): + offset = directory.get("data_base", 0) + integer(record, directory["location"]) + size = integer(record, directory["size"]) + source = f"{name}:{key}" + entry = {"offset": offset, "size": size, "encoding": directory.get("encoding", "raw")} + if "raw_size" in directory: + entry["raw_size"] = integer(record, directory["raw_size"]) + add_entry(sources, source, entry) + add_entry(stages, key, source) + for name, directory in profile.get("state_directories", {}).items(): + states = profile.setdefault("states", {}).setdefault(name, {}) + start, size = directory["fragment"] + if start < 0 or size <= 0 or start + size > directory["stride"]: + raise ValueError("invalid directory state fragment") + for key, record in directory_entries(records, directory): + add_entry(states, key, record[start:start + size].hex()) diff --git a/scripts/pso_corpus/stage.py b/scripts/pso_corpus/stage.py new file mode 100644 index 0000000000..2622477eaa --- /dev/null +++ b/scripts/pso_corpus/stage.py @@ -0,0 +1,267 @@ +"""Stage local XCLPJ001 journals for offline pipeline preparation. + +python scripts/pso_corpus/stage.py --title FOLDER JOURNAL [JOURNAL ...] +Use the same window configuration for all journals. The resulting .xcl/pso-corpus +contains local shader bytes. An existing different corpus is preserved. Compute +node masks 0 and 1 select the first node on the supported single-node adapter. +""" +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +import shutil +import struct +import tempfile + +OFFSET, PRIME, MASK = 0xcbf29ce484222325, 0x100000001b3, (1 << 64) - 1 +HEADER = struct.Struct("= 128: + result.append(128 | (value & 127)) + value >>= 7 + result.append(value) + return result + + +class Reader: + def __init__(self, data): + self.data = memoryview(data) + self.pos = 0 + + def take(self, size): + end = self.pos + size + require(end <= len(self.data), "short descriptor") + part = self.data[self.pos:end] + self.pos = end + return part + + def ints(self, fmt): + return struct.unpack(fmt, self.take(struct.calcsize(fmt))) + + def u32(self): + return self.ints(" Date: Thu, 26 Nov 2026 10:59:47 -0500 Subject: [PATCH 10/22] Shaders: prepare known native pipelines before releasing the game window Share native replay between an offline CLI and the launch gate. Count successful recipes, propagate driver failures and cancellation, and scope recorded history to each title. Draw progress in the presentation window while workers prepare graphics, mesh and compute pipelines. --- README.md | 35 ++- crates/xcl/src/hle/d3d12x/gfx_records.rs | 129 +++++++- .../xcl/src/hle/d3d12x/present/preparation.rs | 116 +++++--- crates/xcl/src/hle/d3d12x/real.rs | 93 +++++- crates/xcl/src/main.rs | 1 + crates/xcl/src/shaders.rs | 277 ++++++++++++++---- crates/xcl/src/shaders/pso_corpus.rs | 186 ++++++++++++ crates/xcl/tests/e2e.rs | 20 ++ 8 files changed, 719 insertions(+), 138 deletions(-) create mode 100644 crates/xcl/src/shaders/pso_corpus.rs diff --git a/README.md b/README.md index 3fc900f7ef..df94e5b106 100644 --- a/README.md +++ b/README.md @@ -262,21 +262,26 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
Switches, caches, logs and the files XCL writes -- When a game folder contains a `shaders.rpf` shader pack or loose `.dxbc` files under - `shaders/`, XCL shows shader preparation in the game window before executing title code. - The same window then presents the game. The percentage counts - processed records. The timer counts seconds since one finished (or preparation started); - five seconds without progress counts as a stall, and the window shows when the last one ended. - XCL prepares supported shader stages and compute pipelines, including - split pieces and their whole fallback. Graphics pipelines are created during play the first - time. The startup history records supported graphics descriptors and two-pass mesh streams with - their state (`used-graphics-pipelines.bin` beside the shader cache, capped by `XCL_GFX_RECORDS_MB` - at 64 MB by default). On the next launch, XCL builds the recorded pipelines before the title starts - and keeps their driver blobs for reuse. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. - Closing the window cancels the launch. A compiler or driver failure stops it and reports - 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 uses the game window to show preparation progress before executing title code. It prepares + supported shader packs, supported loose shaders under `shaders/`, recorded graphics history and + staged pipeline recipes. Closing the window cancels launch. A failed staged recipe stops launch. + With presentation disabled, preparation runs without a window. A staged corpus still gates + launch when the null renderer is selected. +- To prepare known graphics, two-pass mesh and compute recipes offline, use a local + [archive layout profile](scripts/pso_corpus/archive-profile.md) with the following commands. + The staging command accepts several journals and deduplicates their recipes. + + ```powershell + python scripts/pso_corpus/pso_archive.py profile.json archive.bin pipelines.bin + python scripts/pso_corpus/stage.py --title pipelines.bin + xcl shaders --prepare-corpus --threads 8 + ``` + + The offline command accepts up to 32 workers. Normal launch also prepares the staged corpus. + Use the same adapter and memory-window + configuration for offline preparation and play so the driver can reuse the results. + Graphics state combinations absent from the supplied recipes and local history can still + require a first-use compile during play. - 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/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 552e0ecb46..74b01fbb24 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -12,6 +12,7 @@ //! payload = 1 key u64 shaders [u64; 5] state input* a pipeline //! | 2 key u64 bytes a shader (preparation job files only) //! | 3 key u64 shaders [u64; 2] layout state a mesh pipeline stream +//! | 4 key u64 shaders [u64; 5] state input* a pipeline with depth bounds enabled //! key = `real::shaders_key` of the set, in mesh then PS order for mesh; in a shader entry, //! `real::shader_key` of it //! shaders = `real::shader_key` of VS, PS, DS, HS, GS, or mesh, PS (0: none) @@ -42,10 +43,16 @@ const HEADER: usize = 12; const PIPELINE: u8 = 1; const SHADER: u8 = 2; const MESH_PIPELINE: u8 = 3; -const MAX_MESH_LAYOUT: usize = 14; // root, mesh (MS or AS), PS, and eleven scalar state types +const DEPTH_BOUNDS_PIPELINE: u8 = 4; +const MAX_MESH_LAYOUT: usize = 19; // includes four inactive shader slots and an empty input layout -/// The records of this cache (beside the DXIL cache, as `used-pipelines.txt`). +/// New records belong to the active title. A shared translation cache can serve unrelated titles. pub(crate) fn path() -> PathBuf { + if let Some(boot) = crate::state::boot() { return boot.cache_dir().join("used-graphics-pipelines.bin"); } + shared_history_path() +} + +pub(crate) fn shared_history_path() -> PathBuf { crate::gpu::recomp::dxc::cache_dir().join("used-graphics-pipelines.bin") } @@ -223,10 +230,16 @@ fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY | D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS @@ -244,14 +257,17 @@ fn valid_mesh_layout(shaders: [u64; 2], layout: &[u32]) -> bool { } let has = |kind: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE| seen & (1 << kind.0) != 0; (has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS) != has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS)) - && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS) == (shaders[1] != 0) + && (shaders[1] == 0 || has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS)) + && !(has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL) && has(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1)) } /// A mesh stream entry with shader keys in mesh, PS order and subobjects in their original order. -pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option> { +pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, depth_bounds: bool) -> Option> { if key == 0 || !valid_mesh_layout(shaders, layout) || d.NumRenderTargets > 8 { return None; } + let depth1 = layout.contains(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32)); + if depth_bounds && !depth1 { return None; } let mut values = D3D12_GRAPHICS_PIPELINE_STATE_DESC { BlendState: d.BlendState, SampleMask: d.SampleMask, @@ -276,6 +292,7 @@ pub(crate) fn encode_mesh(key: u64, shaders: [u64; 2], layout: &[u32], d: &D3D12 out.push(layout.len() as u8); out.extend(layout.iter().map(|&id| id as u8)); state(&mut values, &mut |v, _| put_var(&mut out, (*v).into())); + if depth1 { put_var(&mut out, u64::from(depth_bounds)); } Some(out) } @@ -291,6 +308,7 @@ pub(crate) fn shader_entry(key: u64, bytes: &[u8]) -> Vec { /// A pipeline as a title described it, but its shaders and root signature (`desc` puts them in). pub(crate) struct Record { pub key: u64, + pub depth_bounds: bool, /// `real::shader_key` of the VS, PS, DS, HS, GS (0: none) pub shaders: [u64; 5], desc: Box, @@ -322,9 +340,18 @@ pub(crate) struct MeshRecord { pub key: u64, pub shaders: [u64; 2], pub layout: Vec, + pub depth_bounds: bool, desc: Box, } +pub(crate) fn depth_stencil1(d: &D3D12_DEPTH_STENCIL_DESC, bounds: bool) -> D3D12_DEPTH_STENCIL_DESC1 { + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, StencilReadMask: d.StencilReadMask, StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, BackFace: d.BackFace, DepthBoundsTestEnable: bounds.into(), + } +} + // The decoder starts with null pointers and only fills scalar fields. The descriptor is immutable. unsafe impl Send for MeshRecord {} unsafe impl Sync for MeshRecord {} @@ -357,7 +384,8 @@ fn decode_mesh(key: u64, mut r: Reader<'_>) -> Option { Some(x) => *v = x, None => valid = false, }); - (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc }) + let depth_bounds = layout.contains(&(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32)) && r.bounded_var(1)? != 0; + (valid && r.0.is_empty()).then_some(MeshRecord { key, shaders, layout, desc, depth_bounds }) } /// The entry of `payload` (None: not one this version writes). @@ -371,7 +399,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { if tag == MESH_PIPELINE { return decode_mesh(key, r).map(Entry::MeshPipeline); } - if tag != PIPELINE { + if !matches!(tag, PIPELINE | DEPTH_BOUNDS_PIPELINE) { return None; } let mut shaders = [0u64; 5]; @@ -415,7 +443,7 @@ pub(crate) fn decode(payload: &[u8]) -> Option { InstanceDataStepRate: f[5], }) .collect(); - Some(Entry::Pipeline(Record { key, shaders, desc, inputs, _names: names })) + Some(Entry::Pipeline(Record { key, shaders, depth_bounds: tag == DEPTH_BOUNDS_PIPELINE, desc, inputs, _names: names })) } fn header() -> [u8; HEADER] { @@ -454,6 +482,23 @@ pub(crate) fn read(path: &Path) -> Vec> { payloads(&file).map_or_else(Vec::new, |(list, _)| list.into_iter().map(<[u8]>::to_vec).collect()) } +/// A completed worker job must contain only whole, supported records. A history file +/// may be open for appends, so its reader above accepts a trailing partial entry. +fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { + let file = std::fs::read(path).map_err(|e| e.to_string())?; + let (payloads, end) = payloads(&file).ok_or("unrecognized graphics job header")?; + if end != file.len() { return Err(format!("damaged graphics job at byte {end}")); } + payloads.into_iter().enumerate().map(|(i, p)| decode(p).map(|entry| take(p, entry)).ok_or_else(|| format!("invalid graphics job entry {}", i + 1))).collect() +} + +pub(crate) fn read_complete_payloads(path: &Path) -> Result>, String> { + read_complete(path, |bytes, _| bytes.to_vec()) +} + +pub(crate) fn read_job(path: &Path) -> Result, String> { + read_complete(path, |_, entry| entry) +} + /// What became of an entry handed to `Writer::add`. #[derive(Debug, PartialEq, Eq)] pub(crate) enum Added { @@ -655,6 +700,20 @@ mod tests { } } + #[test] + fn classic_depth_bounds_record_keeps_version_one_state() { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut bytes = unsafe { encode(7, [9, 0, 0, 0, 0], &desc) }; + assert!(!pipeline(&bytes).depth_bounds); + bytes[0] = DEPTH_BOUNDS_PIPELINE; + let record = pipeline(&bytes); + assert!(record.depth_bounds); + assert_eq!(record.shaders, [9, 0, 0, 0, 0]); + assert_eq!(record.key, 7); + bytes.pop(); + assert!(decode(&bytes).is_none()); + } + /// A description comes back with every field (as the key of its translated pipeline's driver /// blob sees them), its input layout and its shaders' keys. #[test] @@ -712,14 +771,14 @@ mod tests { let mut desc = described(); let ps = b"pixel"; desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }; - let payload = encode_mesh(0x1234, shaders, &layout, &desc).unwrap(); + let payload = encode_mesh(0x1234, shaders, &layout, &desc, false).unwrap(); let Some(Entry::MeshPipeline(record)) = decode(&payload) else { panic!("expected a mesh entry") }; assert_eq!((record.key, record.shaders), (0x1234, shaders)); assert_eq!(record.layout, layout); assert_eq!(record.state().RasterizerState.DepthBias, desc.RasterizerState.DepthBias); assert_eq!(record.state().RTVFormats, desc.RTVFormats); assert!(record.state().PS.pShaderBytecode.is_null()); - assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state()).unwrap(), payload); + assert_eq!(encode_mesh(record.key, record.shaders, &record.layout, record.state(), record.depth_bounds).unwrap(), payload); } #[test] @@ -729,12 +788,13 @@ mod tests { let ps = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32; let input = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32; let d = described(); - for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps], vec![ms, input]] { - assert!(encode_mesh(1, [1, 0], &layout, &d).is_none(), "unsupported layout {layout:?}"); + let stream_output = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT.0 as u32; + for layout in [vec![], vec![ms, moved], vec![ms, ms], vec![ms, ps, ps], vec![ms, stream_output], vec![ms, 11, 21]] { + assert!(encode_mesh(1, [1, 0], &layout, &d, false).is_none(), "unsupported layout {layout:?}"); } - assert!(encode_mesh(1, [1, 2], &[ms], &d).is_none()); - assert!(encode_mesh(1, [0, 0], &[ms], &d).is_none()); - let payload = encode_mesh(1, [1, 0], &[ms], &d).unwrap(); + assert!(encode_mesh(1, [1, 2], &[ms], &d, false).is_none()); + assert!(encode_mesh(1, [0, 0], &[ms], &d, false).is_none()); + let payload = encode_mesh(1, [1, 0], &[ms], &d, false).unwrap(); assert!(decode(&payload[..payload.len() - 1]).is_none()); assert!(decode(&[payload.as_slice(), &[0]].concat()).is_none()); @@ -750,13 +810,52 @@ mod tests { assert!(decode(&overlong).is_none()); } + #[test] + fn mesh_bounds_and_empty_subobjects_survive_the_worker_job() { + let layout = [0, 25, 2, 3, 4, 5, 8, 9, 10, 21, 17, 12, 14, 15, 16]; + let desc = described(); + for bounds in [false, true] { + let job = encode_mesh(1, [1, 0], &layout, &desc, bounds).unwrap(); + let Some(Entry::MeshPipeline(record)) = decode(&job) else { panic!("mesh record missing") }; + assert_eq!(record.layout, layout); + assert_eq!(record.depth_bounds, bounds); + assert_eq!(record.shaders, [1, 0]); + let state = depth_stencil1(&record.state().DepthStencilState, record.depth_bounds); + assert_eq!(state.BackFace, desc.DepthStencilState.BackFace); + assert_eq!(state.DepthBoundsTestEnable.as_bool(), bounds); + assert!(decode(&job[..job.len() - 1]).is_none()); + let mut bad = job; *bad.last_mut().unwrap() = 2; + assert!(decode(&bad).is_none()); + } + assert!(encode_mesh(1, [1, 0], &[25, 11], &desc, true).is_none()); + } + + #[test] + fn complete_jobs_reject_damaged_or_unknown_entries() { + let dir = directory("complete-job"); + let path = dir.0.join("job.bin"); + assert!(read_job(&path).is_err()); + { + let mut writer = Writer::open(&path, u64::MAX).unwrap(); + writer.add(&shader_entry(5, b"shader")).unwrap(); + } + assert_eq!(read_job(&path).unwrap().len(), 1); + let original = std::fs::read(&path).unwrap(); + std::fs::write(&path, [&original[..], &[1, 2]].concat()).unwrap(); + assert!(read_job(&path).is_err()); + assert_eq!(read(&path).len(), 1); + std::fs::write(&path, original).unwrap(); + Writer::open(&path, u64::MAX).unwrap().add(&[0xff]).unwrap(); + assert!(read_job(&path).is_err()); + } + #[test] fn legacy_pipeline_and_mesh_entries_share_version_one_history() { let dir = directory("mesh-version-one"); let path = dir.0.join("records.bin"); let legacy = unsafe { encode(3, [3, 0, 0, 0, 0], &described()) }; let shader = shader_entry(5, b"mesh"); - let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described()).unwrap(); + let mesh = encode_mesh(5, [5, 0], &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32], &described(), false).unwrap(); let mut writer = Writer::open(&path, 1 << 20).unwrap(); writer.add(&legacy).unwrap(); writer.add(&mesh).unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index eafd05f1e7..baff972a85 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -25,7 +25,8 @@ struct Screen { impl Screen { fn release(&mut self) -> bool { - self.ready = !self.progress.cancel.load(Ordering::Relaxed); + self.ready = !self.progress.cancel.load(Ordering::Relaxed) && + (!self.progress.corpus.load(Ordering::Acquire) || self.progress.check_corpus_complete().is_ok()); self.ready } } @@ -41,24 +42,21 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { std::env::remove_var("XCL_PREPARATION_PARENT"); std::env::remove_var("XCL_PREPARATION_MENU"); let root = &boot.game_root; - if boot.config.graphics.eq_ignore_ascii_case("null") || - (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir()) { + let corpus = root.join(".xcl/pso-corpus").try_exists().map_err(|e| e.to_string())?; + if !corpus && (boot.config.graphics.eq_ignore_ascii_case("null") || + (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir() && + !crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?)) { return Ok(()); } - if left_out(std::env::var("XCL_PREPARE").ok().as_deref()) { - crate::xlog_info!("Shader preparation left out (XCL_PREPARE=0): the title builds what it uses as it goes"); - return Ok(()); - } - let only = Some(crate::hle::d3d12x::pso_async::earlier_used_shaders()) - .filter(|used| !used.is_empty() && !std::env::var("XCL_PREPARE_ALL").is_ok_and(|v| v.trim() == "1")); - if let Some(used) = &only { - crate::xlog_info!("Shader preparation: only the {} shaders earlier runs used (XCL_PREPARE_ALL=1: every record)", used.len()); - } - let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), only, ..Default::default() }); + let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); let hwnd = if super::enabled() { *SCREEN.lock().unwrap() = Some(Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }); ACTIVE.store(true, Ordering::Release); - let hwnd = super::ensure_window().ok_or("Could not create the presentation window for shader preparation")?; + let Some(hwnd) = super::ensure_window() else { + ACTIVE.store(false, Ordering::Release); + *SCREEN.lock().unwrap() = None; + return Err("Could not create the presentation window for pipeline preparation".into()); + }; crate::xlog_info!("Shader preparation window {:#x}", hwnd.0 as usize); Some(hwnd) } else { None }; @@ -71,12 +69,13 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { said = Instant::now(); let workers = progress.workers.load(Ordering::Relaxed); let graphics = progress.graphics.load(Ordering::Relaxed); + let corpus = progress.corpus.load(Ordering::Acquire); crate::xlog_info!( "Shader preparation: {} of {} {} {} after {} s", progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed), - if graphics { "graphics pipelines" } else { "records" }, - if graphics { format!("built by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, + if corpus { "pipeline recipes" } else if graphics { "graphics pipelines" } else { "records" }, + if corpus { "confirmed by the graphics driver".into() } else if graphics { format!("processed by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "processed".into() }, began.elapsed().as_secs() ); } @@ -153,6 +152,38 @@ unsafe fn text(dc: HDC, rect: RECT, value: &str, size: i32, weight: i32, color: DeleteObject(font); } +/// A projected wireframe whose illuminated columns follow confirmed progress. +unsafe fn draw_surface(dc: HDC, rect: RECT, pct: usize) { + use windows_sys::Win32::Foundation::POINT; + const COLS: i32 = 24; + const ROWS: i32 = 8; + let vertex = |col: i32, row: i32| { + let u = col as f64 / COLS as f64; + let v = row as f64 / ROWS as f64; + let hill = |x: f64, z: f64, height: f64| height * (-20.0*(u-x).powi(2) - 6.0*(v-z).powi(2)).exp(); + let elevation = hill(0.35, 0.41, 0.53) + hill(0.68, 0.55, 0.34); + POINT { x: rect.left + ((rect.right-rect.left) as f64*(0.80*u + 0.19*(1.0-v))) as i32, + y: rect.top + ((rect.bottom-rect.top) as f64*(0.42 + 0.55*v - elevation)) as i32 } + }; + let shadow = CreatePen(PS_SOLID, 1, 0x4d4734); + let lit = CreatePen(PS_SOLID, 1, 0x97cc86); + let base = CreateSolidBrush(0x28251b); + let old_pen = SelectObject(dc, shadow); + let old_brush = SelectObject(dc, base); + for row in 0..ROWS { + for col in 0..COLS { + let points = [vertex(col,row),vertex(col+1,row),vertex(col+1,row+1),vertex(col,row+1)]; + SelectObject(dc, if 100*(col+1) as usize <= COLS as usize*pct { lit } else { shadow }); + Polygon(dc, points.as_ptr(), points.len() as i32); + MoveToEx(dc, points[0].x, points[0].y, std::ptr::null_mut()); + LineTo(dc, points[2].x, points[2].y); + } + } + SelectObject(dc, old_brush); + SelectObject(dc, old_pen); + DeleteObject(base); DeleteObject(shadow); DeleteObject(lit); +} + unsafe fn paint(hwnd: HWND, s: &mut Screen) { let mut ps: PAINTSTRUCT = std::mem::zeroed(); let dest = BeginPaint(hwnd.0, &mut ps); @@ -167,28 +198,37 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { let scale = |px: i32| (px * GetDeviceCaps(dc, LOGPIXELSY as i32).max(96)) / 96; let width = scale(560).min((rc.right - scale(40)).max(1)); let x = (rc.right - width) / 2; - let y = ((rc.bottom - scale(150)) / 2).max(0); + let art = if rc.bottom >= scale(300) && width >= scale(300) { scale(132) } else { 0 }; + let top = ((rc.bottom - scale(150) - art) / 2).max(0); + let y = top + art; let row = |top, bottom| RECT { left: x, right: x+width, top: y+scale(top), bottom: y+scale(bottom) }; let done = s.progress.done.load(Ordering::Relaxed); let total = s.progress.total.load(Ordering::Relaxed); let pct = percent(done, total, s.ready); + if art != 0 { + draw_surface(dc, RECT { left: x, right: x+width, top, bottom: y-scale(14) }, pct); + } let (quiet, last) = s.clock.sample(done, s.start.elapsed()); let workers = s.progress.workers.load(Ordering::Relaxed); let graphics = workers != 0 && s.progress.graphics.load(Ordering::Relaxed); - let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; + let corpus = s.progress.corpus.load(Ordering::Acquire); + let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if s.ready { "Ready to launch" } + else if corpus { "Preparing pipeline cache" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; let mut title = row(0,48); title.right -= scale(84); text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); text(dc, row(0,48), &format!("{pct}%"), scale(27), 600, 0xdfd09a, DT_RIGHT); - let bar = row(65,72); + let bar = row(62,72); fill(dc, bar, 0x4b4038); fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); - let count = if total == 0 { "Reading shader records…".into() } - else if graphics { format!("{done} of {total} graphics pipelines built by {workers} worker processes") } + let count = if corpus { format!("{done} of {total} pipeline recipes confirmed by the driver") } + else if total == 0 { "Reading shader records…".into() } + else if graphics { format!("{done} of {total} graphics pipelines processed by {workers} worker processes") } else if workers != 0 { format!("{done} of {total} records checked by {workers} worker processes") } else { format!("{done} of {total} records processed") }; text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); - let mut times = if workers != 0 { format!("Large pipelines compile in the driver: {quiet} s since the last record") } else { format!("No shader progress for {quiet} s") }; + let elapsed = s.start.elapsed().as_secs(); + let mut times = format!("Elapsed {}:{:02} · {quiet} s since last progress", elapsed / 60, elapsed % 60); if let Some(ago) = last { times.push_str(&format!(" · Last stall ended {ago} s ago")); } text(dc, row(117,145), ×, scale(14), 400, 0xb4aaa4, DT_LEFT); BitBlt(dest, 0, 0, rc.right, rc.bottom, dc, 0, 0, SRCCOPY); @@ -223,23 +263,10 @@ fn percent(done: usize, total: usize, ready: bool) -> usize { if ready { 100 } else { done.saturating_mul(100).checked_div(total).unwrap_or(0).min(99) } } -/// `XCL_PREPARE=0` (`value`): the title starts at once and builds what it uses as it goes, -/// standing still for those builds, as before the preparation (the switch nvidia-dev has). -fn left_out(value: Option<&str>) -> bool { - value.is_some_and(|v| v.trim() == "0") -} - #[cfg(test)] mod tests { use super::*; - /// Only `XCL_PREPARE=0` leaves the preparation out; unset or any other value prepares. - #[test] - fn only_xcl_prepare_0_leaves_the_preparation_out() { - assert!(left_out(Some("0")) && left_out(Some(" 0 "))); - assert!(!left_out(None) && !left_out(Some("1")) && !left_out(Some("")) && !left_out(Some("no"))); - } - #[test] fn clock_advances_during_a_stall_and_remembers_recovery() { let mut clock = StallClock::default(); @@ -262,6 +289,25 @@ mod tests { assert!(!screen.ready); } + #[test] + fn corpus_handoff_requires_every_native_completion() { + let progress = Arc::new(LaunchPreparation::default()); + let mut screen = Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }; + assert!(progress.check_corpus_complete().is_err()); + progress.begin_corpus(0); + assert!(!screen.release()); + progress.begin_corpus(3); + progress.complete_corpus(2).unwrap(); + progress.complete_corpus(1).unwrap(); + assert_eq!(progress.done.load(Ordering::Acquire), 2); + assert!(progress.complete_corpus(4).is_err()); + assert!(!screen.release()); + progress.complete_corpus(3).unwrap(); + assert!(screen.release()); + progress.cancel.store(true, Ordering::Release); + assert!(!screen.release()); + } + #[test] fn only_a_successful_join_releases_the_last_percent() { assert_eq!(percent(0, 0, false), 0); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c0e4549be7..4a44ad1f46 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5014,6 +5014,23 @@ pub(super) unsafe fn graphics_blob_key( mod graphics_blob_tests { use super::*; + #[test] + fn classic_depth_bounds_record_preserves_native_state_and_cache_identity() { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + d.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_GREATER; + d.DepthStencilState.StencilReadMask = 0x5a; + let stream = depth_bounds_stream(&d); + let fields = stream_subobjects(&stream.0).unwrap(); + let (_, bytes) = fields.iter().find(|(ty, _)| *ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1.0 as u32).unwrap(); + let state = unsafe { std::ptr::read_unaligned(bytes.as_ptr().cast::()) }; + assert!(state.DepthBoundsTestEnable.as_bool()); + assert_eq!(state.DepthFunc, d.DepthStencilState.DepthFunc); + assert_eq!(state.StencilReadMask, 0x5a); + let key = (123, 456); + assert_eq!(depth_bounds_key(key, false), key); + assert_ne!(depth_bounds_key(key, true), key); + } + #[test] fn graphics_blob_key_tracks_shaders_samplers_and_state() { unsafe { @@ -5222,10 +5239,10 @@ fn create_graphics_pso_cached( } unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { - with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv, false)) } -unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, depth_bounds: bool) -> Option { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { return None; @@ -5299,7 +5316,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); - let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); + let gkey = depth_bounds_key(graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers), depth_bounds); let mut cached = graphics_blob(gkey); let disk = driver_cache::graphics_path(gkey.0, gkey.1); let from_disk = cached.is_none(); @@ -5319,7 +5336,12 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } }, |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), - |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), + |c| if depth_bounds { + let stream = depth_bounds_stream(c); + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream.0.len(), pPipelineStateSubobjectStream: stream.0.as_ptr() as _ }; + let create: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); + finish_pso(this, create, &desc as *const _ as _, riid, ppv) + } else { finish_pso(this, f, c as *const _ as *const c_void, riid, ppv) }, ); let hr = build.hr; if build.cache_eligible { @@ -5770,11 +5792,12 @@ pub(crate) fn prepare_device(device: ID3D12Device) -> usize { /// (`prepare_device`) as the title's background build makes it (`build_graphics`): the /// translation, DXC and driver blob caches on disk get what the title will ask for. The pipeline /// is released; false: not made (noted in the log as the title's would be). -pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> bool { +pub(crate) unsafe fn prepare_graphics(device: usize, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, depth_bounds: bool) -> bool { let this = device as *mut c_void; let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); let mut out: *mut c_void = std::ptr::null_mut(); - let made = matches!(translated_graphics_pso(this, f, desc as *const _ as *const c_void, &pc_iid(Kind::PipelineState), &mut out), Some(hr) if hr >= 0) && !out.is_null(); + let hr = with_switch_fallback(|| translated_graphics_pso_once(this, f, desc as *const _ as _, &pc_iid(Kind::PipelineState), &mut out, depth_bounds)); + let made = matches!(hr, Some(hr) if hr >= 0) && !out.is_null(); super::pso_async::release(out as usize); made } @@ -5993,6 +6016,40 @@ impl StreamOut { } } +fn depth_bounds_key(mut key: (u64, usize), enabled: bool) -> (u64, usize) { + if enabled { + for &byte in b"DB01" { key.0 = (key.0 ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3); } + } + key +} + +/// The richer depth-stencil descriptor can only be passed through a pipeline stream. +fn depth_bounds_stream(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> StreamOut { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &d.pRootSignature); + for (stage, code) in [(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &d.VS), + (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &d.PS), (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, &d.DS), + (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, &d.HS), (D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, &d.GS)] { + if code.BytecodeLength != 0 { out.put(stage, code); } + } + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, &super::gfx_records::depth_stencil1(&d.DepthStencilState, true)); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &d.BlendState); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &d.RasterizerState); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &d.SampleMask); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, &d.SampleDesc); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + &D3D12_RT_FORMAT_ARRAY { NumRenderTargets: d.NumRenderTargets, RTFormats: d.RTVFormats }); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, &d.DSVFormat); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &d.PrimitiveTopologyType); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, &d.IBStripCutValue); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &d.InputLayout); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, &d.StreamOutput); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, &d.NodeMask); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); + if d.CachedPSO.CachedBlobSizeInBytes != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &d.CachedPSO); } + out +} + /// The subobjects of a stream: (type, payload). fn stream_subobjects(buf: &[u8]) -> Option> { let mut out = Vec::new(); @@ -6040,6 +6097,7 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); let mut layout = Vec::with_capacity(subs.len()); let (mut ms, mut amplification, mut ps) = (None, None, None); + let mut depth_bounds = false; let (mut seen, mut size) = (0u32, 0usize); fn value(payload: &[u8]) -> Option { @@ -6057,7 +6115,8 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { match ty { 0 => {} // The translator supplies its own root signature. 19 => continue, // The title's cache blob is never an input to translation. - 2 | 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 24 | 25 if payload.iter().all(|&b| b == 0) => continue, + 1..=5 if payload.iter().all(|&b| b == 0) => {} 2 => ps = Some(payload_shader(payload)?), 24 => amplification = Some(payload_shader(payload)?), 25 => ms = Some(payload_shader(payload)?), @@ -6065,6 +6124,16 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { 9 => desc.SampleMask = value(payload)?, 10 => desc.RasterizerState = value(payload)?, 11 => desc.DepthStencilState = value(payload)?, + 12 if value::(payload).is_some_and(|d| d.NumElements == 0 && d.pInputElementDescs.is_null()) => {} + 21 => { + let d = value::(payload)?; + depth_bounds = d.DepthBoundsTestEnable.as_bool(); + desc.DepthStencilState = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: d.DepthEnable, DepthWriteMask: d.DepthWriteMask, DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, StencilReadMask: d.StencilReadMask, StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, BackFace: d.BackFace, + }; + } 13 => desc.IBStripCutValue = value(payload)?, 14 => desc.PrimitiveTopologyType = value(payload)?, 15 => { @@ -6092,7 +6161,7 @@ unsafe fn record_mesh_stream(stream: &[u8]) -> Option> { } let shaders = [shader_key(ms), ps.map_or(0, shader_key)]; let key = shader_set_key(std::iter::once(ms).chain(ps)); - super::gfx_records::encode_mesh(key, shaders, &layout, &desc) + super::gfx_records::encode_mesh(key, shaders, &layout, &desc, depth_bounds) } /// Build both recorded mesh passes on the adopted device from `prepare_device`. @@ -6117,12 +6186,18 @@ pub(crate) unsafe fn replay_mesh_record( let subobject = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32); match ty { 0 => stream.put(subobject, &std::ptr::null::()), - 2 => stream.shader(subobject, ps.ok_or("pixel shader missing from the job")?), + 2 => match ps { + Some(bytes) => stream.shader(subobject, bytes), + None => stream.put(subobject, &D3D12_SHADER_BYTECODE::default()), + }, + 1 | 3..=5 => stream.put(subobject, &D3D12_SHADER_BYTECODE::default()), 24 | 25 => stream.shader(subobject, ms), 8 => stream.put(subobject, &d.BlendState), 9 => stream.put(subobject, &d.SampleMask), 10 => stream.put(subobject, &d.RasterizerState), 11 => stream.put(subobject, &d.DepthStencilState), + 12 => stream.put(subobject, &D3D12_INPUT_LAYOUT_DESC::default()), + 21 => stream.put(subobject, &super::gfx_records::depth_stencil1(&d.DepthStencilState, record.depth_bounds)), 13 => stream.put(subobject, &d.IBStripCutValue), 14 => stream.put(subobject, &d.PrimitiveTopologyType), 15 => stream.put(subobject, &D3D12_RT_FORMAT_ARRAY { RTFormats: d.RTVFormats, NumRenderTargets: d.NumRenderTargets }), diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index e40b3e18ad..6fe7571fef 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -35,6 +35,7 @@ Usage: --recomp: translates every RDNA2 program → HLSL and shows what is missing; --compile N: additionally compiles N complete translations with DXC. --precompile [--only STAGE]: caches compiled shaders before a run (e.g. --only cs). + --prepare-corpus: builds every staged native pipeline recipe for a title folder. --pipelines also builds compute pipelines and caches them for the next run. --used-only skips compute shaders whose pipelines were not used in earlier runs. --export-hlsl DIR [--count N] [--min-kb N] [--record-hash HEX]: writes deterministic diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 66ccb63bef..08bba82667 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -13,6 +13,7 @@ use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; use crate::hle::d3d12x::gfx_records; +pub(crate) mod pso_corpus; /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). @@ -812,6 +813,7 @@ struct ShadersOptions { measure_pso: Option, repeat: usize, precompile: bool, + prepare_corpus: bool, limit: usize, only: Option, pipelines: bool, @@ -850,6 +852,7 @@ fn parse_args(args: &[String]) -> Result { measure_pso: None, repeat: 1, precompile: false, + prepare_corpus: false, limit: usize::MAX, only: None, pipelines: false, @@ -890,6 +893,7 @@ fn parse_args(args: &[String]) -> Result { "--measure-pso" => opts.measure_pso = Some(p.parse_hex_u64("--measure-pso")?), "--repeat" => opts.repeat = p.parse_usize("--repeat")?, "--precompile" => opts.precompile = true, + "--prepare-corpus" => opts.prepare_corpus = true, "--limit" => opts.limit = p.parse_usize("--limit")?, "--only" => opts.only = Some(p.value("--only")?.to_ascii_lowercase()), "--pipelines" => opts.pipelines = true, @@ -953,6 +957,17 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; + if opts.prepare_corpus { + let progress = LaunchPreparation { adapter: "auto".into(), ..Default::default() }; + let result = pso_corpus::discover(path) + .and_then(|c| c.ok_or_else(|| "No pipeline corpus found in this title folder".to_string())) + .and_then(|c| c.prepare_with_threads(&progress, opts.threads)) + .and_then(|_| progress.check_corpus_complete()); + return match result { + Ok(()) => { println!("Prepared all {} discovered pipeline recipes", progress.done.load(Ordering::Acquire)); 0 } + Err(e) => { eprintln!("xcl shaders: {e}"); 2 } + }; + } // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` // (`pso::mem_windows`), as `--precompile` let runtime_windows = || { @@ -960,7 +975,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } }; if opts.graphics_records { - return graphics_worker(path, runtime_windows()); + return graphics_worker(path, runtime_windows(), opts.threads); } let top = opts.top; let json = opts.json; @@ -1568,7 +1583,30 @@ impl Pipelines { self.make_one(&c.dxil, &c.samplers, false, path_override); } + fn prepare_compute(&self, blob: &[u8], windows: u32) -> Result<(), String> { + let split = recomp::pso::wave32_only_for_device(&self.dev); + let program = recomp::pso::console_to_dxil_in(blob, recomp::pso::Stage::Compute, 0, split, windows)?; + self.prepare_compiled_compute(&program) + } + + fn prepare_compiled_compute(&self, program: &recomp::pso::Compiled) -> Result<(), String> { + let make = |dxil: &[u8], chained| { + self.make_required(dxil, &program.samplers, chained, None, true) + }; + make(&program.dxil, false)?; + if let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) { + for piece in &chain.pieces { make(piece, true)?; } + make(&program.dxil, true)?; + } + Ok(()) + } + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option) { + let _ = self.make_required(dxil, samplers, chained, path_override, false); + } + + fn make_required(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, + path_override: Option, required: bool) -> Result<(), String> { use windows::Win32::Graphics::Direct3D12::*; let key: (bool, Vec) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); let rs = { @@ -1586,9 +1624,9 @@ impl Pipelines { g.insert(key, rs.clone()); rs } - Err(_) => { + Err(e) => { self.refused.fetch_add(1, Ordering::Relaxed); - return; + return Err(format!("Creating compute root signature: {e}")); } } } @@ -1616,7 +1654,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err(format!("Compute DXIL exceeds the native pipeline size limit ({} bytes)", dxil.len())); } { let mut n = self.running.0.lock().unwrap(); @@ -1635,12 +1673,14 @@ impl Pipelines { let claim = match (&cached, path.as_deref()) { (None, Some(path)) => match Claim::take(path) { Some(c) => Some(c), + // A mandatory job needs a native result even if another process owns the cache write. + None if required => None, None => { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); self.elsewhere.fetch_add(1, Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err("Another process is preparing this compute pipeline".into()); } }, _ => None, @@ -1664,7 +1704,7 @@ impl Pipelines { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - return; + return Err(format!("The cached compute pipeline was rejected and {} bytes of DXIL exceed the limit", dxil.len())); } let r = if let Some(pso) = from_cache { self.reused.fetch_add(1, Ordering::Relaxed); @@ -1672,7 +1712,7 @@ impl Pipelines { } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; - if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { + if let (Some(path), Ok(pso)) = (path.as_deref().filter(|_| claim.is_some() || cached.is_some()), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); let len = unsafe { blob.GetBufferSize() }; @@ -1687,13 +1727,14 @@ impl Pipelines { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); - let done = match r { + let done = match &r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, }; if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } + r.map(drop).map_err(|e| format!("Creating native compute pipeline ({} bytes of DXIL): {e}", dxil.len())) } } @@ -1788,10 +1829,35 @@ pub(crate) struct LaunchPreparation { pub workers: AtomicUsize, /// The workers build graphics pipelines (`graphics_in_workers`): `done` and `total` count those. pub graphics: std::sync::atomic::AtomicBool, - /// The shaders earlier runs used (`pso_async::earlier_used_shaders`), when there are any: - /// only their records are translated before the title starts, and it translates another - /// when it first uses it. `XCL_PREPARE_ALL=1`: every record, as without the list. - pub only: Option>, + /// While replaying the discovered corpus, only verified native successes advance `done`. + pub corpus: std::sync::atomic::AtomicBool, +} + +impl LaunchPreparation { + pub(crate) fn begin_corpus(&self, total: usize) { + self.done.store(0, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + self.corpus.store(true, Ordering::Release); + } + + pub(crate) fn complete_corpus(&self, count: usize) -> Result<(), String> { + if self.cancel.load(Ordering::Relaxed) { return Err("Pipeline preparation cancelled".into()); } + if !self.corpus.load(Ordering::Acquire) || count > self.total.load(Ordering::Relaxed) { + return Err("Native completion count exceeds the discovered corpus".into()); + } + self.done.fetch_max(count, Ordering::Release); + Ok(()) + } + + pub(crate) fn check_corpus_complete(&self) -> Result<(), String> { + if self.cancel.load(Ordering::Relaxed) { return Err("Pipeline preparation cancelled".into()); } + let done = self.done.load(Ordering::Acquire); + let total = self.total.load(Ordering::Relaxed); + if !self.corpus.load(Ordering::Acquire) || total == 0 || done != total { + return Err(format!("Native pipeline preparation incomplete: {done} of {total} recipes confirmed")); + } + Ok(()) + } } /// Unpacked shader containers in the title's shaders directory. Do not follow directory @@ -1813,6 +1879,16 @@ fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { } pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { + let corpus = pso_corpus::discover(root)?; + prepare_title_inputs(root, progress)?; + if let Some(corpus) = corpus { + corpus.prepare(progress)?; + progress.check_corpus_complete()?; + } + Ok(()) +} + +fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { let mut inputs = Vec::new(); let pack = root.join("shaders.rpf"); if pack.try_exists().map_err(|e| e.to_string())? { @@ -1846,11 +1922,6 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R precompile(input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress))?; } if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - // `XCL_PREPARE_GRAPHICS=0`: the title builds the graphics pipelines it uses as it goes - if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { - crate::xlog_info!("Shader preparation: graphics pipelines left out (XCL_PREPARE_GRAPHICS=0)"); - return Ok(()); - } graphics_in_workers(&inputs, windows, workers, progress) } @@ -1943,17 +2014,17 @@ mod claim_tests { /// what is missing itself. fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { let me = std::env::current_exe().map_err(|e| e.to_string())?; - let used_only = !crate::hle::d3d12x::pso_async::earlier_used_keys().is_empty(); let t0 = std::time::Instant::now(); - crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); + crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes"); let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { let mut c = worker_command(&me); c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); - if used_only { c.arg("--used-only"); } + if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); c }); if cancelled { return Err("Shader preparation cancelled".into()); } + if failed != 0 { return Err(format!("{failed} of {workers} compute pipeline workers failed")); } crate::xlog_info!("Shader preparation: compute pipelines done in {:.0} s ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64()); Ok(()) } @@ -2021,7 +2092,7 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut std::thread::sleep(std::time::Duration::from_millis(100)); } }); - let mut failed = 0; + let mut failed = workers - children.len(); for (i, child) in children.iter_mut() { match child.wait() { Ok(st) if st.success() => {} @@ -2045,23 +2116,44 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// starts all the same: it builds what is missing itself. fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { let t0 = std::time::Instant::now(); - let payloads = gfx_records::read(&gfx_records::path()); - let records: Vec<_> = payloads.into_iter().filter_map(|payload| { - let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?; - Some((payload, record)) - }).collect(); + let path = gfx_records::path(); + let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_complete_payloads(&path)? } else { Vec::new() }; + let mut records = Vec::new(); + let mut embedded = std::collections::HashMap::new(); + for payload in local { + match gfx_records::decode(&payload).ok_or("Unrecognized graphics history entry")? { + gfx_records::Entry::Shader(key, code) => { + if crate::hle::d3d12x::real::shader_key(&code) != key { + return Err(format!("Graphics history shader {key:016x} failed its identity check")); + } + embedded.insert(key, code); + } + entry => if let Some(record) = GraphicsHistoryRecord::from_entry(entry) { records.push((payload, record)); }, + } + } + let local_count = records.len(); + let legacy = gfx_records::shared_history_path(); + if !inputs.is_empty() && legacy != path { + let scoped: HashSet<_> = records.iter().map(|(bytes, _)| bytes.as_slice()).collect(); + let candidates: Vec<_> = gfx_records::read(&legacy).into_iter().filter(|bytes| !scoped.contains(bytes.as_slice())) + .filter_map(|payload| Some((GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload)?)?, payload))).collect(); + records.extend(candidates.into_iter().map(|(record, payload)| (payload, record))); + } if records.is_empty() { crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); return Ok(()); } let wanted = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) - .filter(|&key| key != 0).collect(); - let shaders = shaders_by_key(inputs, wanted, progress); + .filter(|&key| key != 0 && !embedded.contains_key(&key)).collect(); + let mut shaders = shaders_by_key(inputs, wanted, progress); + shaders.extend(embedded); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); - if missing != 0 { - crate::xlog_info!("Shader preparation: {missing} of {} graphics pipelines left out (their shaders are not in the title's shader files)", records.len()); + let local_missing = local_count - buildable.iter().take_while(|&&i| i < local_count).count(); + if local_missing != 0 { + return Err(format!("{local_missing} of {local_count} title graphics recipes lack matching shader sources")); } + if missing != 0 { crate::xlog_info!("Shader preparation: {missing} shared graphics recipes have no matching shaders in this title"); } if buildable.is_empty() { return Ok(()); } let workers = workers.clamp(1, buildable.len()); // each worker's part, with the shaders it needs (removed when they are done) @@ -2095,6 +2187,10 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: for (path, _) in &jobs { let _ = std::fs::remove_file(path); } if cancelled { return Err("Shader preparation cancelled".into()); } let sum = summaries.iter().filter_map(|s| graphics_summary(s)).fold([0usize; 4], |a, b| std::array::from_fn(|k| a[k] + b[k])); + if failed != 0 || sum[1] != 0 || sum[0] != buildable.len() { + return Err(format!("Graphics preparation incomplete: {} of {} confirmed, {} refused, {failed} workers failed", + sum[0], buildable.len(), sum[1])); + } crate::xlog_info!( "Shader preparation: graphics pipelines done in {:.0} s: {} made, {} failed; driver blobs: {} from disk, {} kept ({failed} of {workers} workers failed)", t0.elapsed().as_secs_f64(), sum[0], sum[1], sum[2], sum[3] @@ -2170,59 +2266,84 @@ fn graphics_summary(line: &str) -> Option<[usize; 4]> { n.next().is_none().then_some(out) } +fn corpus_threads(requested: Option, default: usize) -> usize { + requested.or_else(|| std::env::var("XCL_PIPELINE_THREADS").ok()?.parse().ok()).unwrap_or(default).clamp(1, 32) +} + /// `xcl shaders --graphics-records` (a worker of `graphics_in_workers`): the graphics /// pipelines of a job file built as the title builds them, with the /// title's memory windows (`windows`) and on its adapter (`XCL_ADAPTER`), `XCL_PIPELINE_THREADS` /// at a time. A progress line a pipeline, then the summary `graphics_summary` reads. -fn graphics_worker(job: &Path, windows: u32) -> i32 { +fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { use crate::hle::d3d12x::real; end_with_parent(); - // (no title memory here: its windows are given) - crate::gpu::uma::leave_out(); - recomp::pso::set_title_windows(windows); - recomp::dxc::set_memory_reserve(2); let mut shaders = std::collections::HashMap::new(); let mut records = Vec::new(); - for p in gfx_records::read(job) { - match gfx_records::decode(&p) { - Some(gfx_records::Entry::Shader(key, code)) => { shaders.insert(key, code); } - Some(entry) => records.extend(GraphicsHistoryRecord::from_entry(entry)), - None => {} + let entries = match gfx_records::read_job(job) { + Ok(entries) => entries, + Err(e) => { eprintln!("xcl shaders: {}: {e}", job.display()); return 2; } + }; + for entry in entries { + match entry { + gfx_records::Entry::Shader(key, code) => { + if real::shader_key(&code) != key || shaders.get(&key).is_some_and(|prior| prior != &code) { + eprintln!("xcl shaders: invalid or conflicting shader {key:016x} in {}", job.display()); + return 2; + } + shaders.insert(key, code); + } + entry => records.extend(GraphicsHistoryRecord::from_entry(entry)), } } + let n = records.len(); + let (ready, missing) = buildable(records.iter(), &shaders); + if missing != 0 { eprintln!("xcl shaders: {missing} graphics records have missing or mismatched shaders"); } + if ready.is_empty() { + eprintln!("graphics pipelines: 0 made, {missing} failed; driver blobs: 0 from disk, 0 kept"); + return if missing == 0 { 0 } else { 2 }; + } + // (no title memory here: its windows are given) + crate::gpu::uma::leave_out(); + recomp::pso::set_title_windows(windows); + recomp::dxc::set_memory_reserve(2); let device = match Pipelines::for_adapter("auto") { Ok(p) => real::prepare_device(p.dev), Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } }; - let n = records.len(); - let threads = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse::().ok()).unwrap_or(1).clamp(1, 8); - let (next, done, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let threads = corpus_threads(requested, 1).min(ready.len()); + let (next, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(missing)); let t0 = std::time::Instant::now(); std::thread::scope(|s| { for _ in 0..threads { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); - let Some(r) = records.get(i) else { break }; + let Some(&index) = ready.get(i) else { break }; + let r = &records[index]; let code = |key| shaders.get(&key).map(Vec::as_slice); // (a pipeline that panics fails; the others are built) let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { GraphicsHistoryRecord::Legacy(record) => { let desc = record.desc(record.shaders.map(code)); - unsafe { real::prepare_graphics(device, &desc) } + unsafe { real::prepare_graphics(device, &desc, record.depth_bounds) } } GraphicsHistoryRecord::Mesh(record) => { unsafe { real::replay_mesh_record(device, record, record.shaders.map(code)).is_ok() } } })).unwrap_or(false); - if ok { made.fetch_add(1, Ordering::Relaxed); } else { failed.fetch_add(1, Ordering::Relaxed); } - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + if ok { + let d = made.fetch_add(1, Ordering::Relaxed) + 1; + eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); + } else { + failed.fetch_add(1, Ordering::Relaxed); + eprintln!("xcl shaders: failed graphics record {} (shader set {:016x})", index + 1, r.identity().0); + } }); } }); let (hits, _, stored) = real::driver_cache_stats(); - eprintln!("graphics pipelines: {} made, {} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner(), failed.into_inner()); - 0 + let failed = failed.into_inner(); + eprintln!("graphics pipelines: {} made, {failed} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner()); + if failed == 0 { 0 } else { 2 } } /// `XCL_PRECOMPILE_PARENT=pid` (set for a title's preparation workers): this process ends when @@ -2246,13 +2367,14 @@ fn end_with_parent() { fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, selected: Option<&std::collections::HashSet>, pipeline_threads: Option, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { if startup.is_none() { end_with_parent(); } + let mandatory = startup.is_some() || std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(); let pipelines = if pipelines { let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; if let Some(threads) = pipeline_threads { p.most = threads.max(1); } - if startup.is_some() && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { + if mandatory && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { p.max_dxil = 0; } Some(p) @@ -2273,7 +2395,6 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let next = AtomicUsize::new(0); 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); let matched: Mutex> = Mutex::new(Default::default()); let pipeline_jobs: Mutex> = Mutex::new(Vec::new()); let used_earlier = if pipelines.is_some() && startup.is_none() { @@ -2342,21 +2463,19 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } - if startup.and_then(|p| p.only.as_ref()).is_some_and(|used| !used.contains(&crate::hle::d3d12x::real::shader_key(&blob))) { - unused.fetch_add(1, Ordering::Relaxed); - record_done(); - continue; - } // 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(_)))) { match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - if startup.is_some() { - p.make(&c); - if c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { - p.make_one(&c.dxil, &c.samplers, true, None); + if mandatory { + if let Err(e) = p.prepare_compiled_compute(&c) { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + record_done(); + continue; } } else { let used = used_earlier.contains(&pipeline_key(&blob)); @@ -2465,8 +2584,8 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } let errors = errors.into_inner().unwrap(); for e in &errors { println!(" {e}"); } - if let Some(progress) = startup { - if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + if mandatory { + if startup.is_some_and(|p| p.cancel.load(Ordering::Relaxed)) { return Err("Shader preparation cancelled".into()); } // (no pipelines here when worker processes build them: `pipelines_in_workers`) let refused = pipelines.map_or(0, |p| p.refused.load(Ordering::Relaxed)); let capped = pipelines.map_or(0, |p| p.capped.load(Ordering::Relaxed)); @@ -2859,7 +2978,7 @@ mod tests { let both = [shader_key(&vs), shader_key(&ps), 0, 0, 0]; let mesh = |key, shaders| { let layout = [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS.0 as u32, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0 as u32]; - let payload = encode_mesh(key, shaders, &layout, &desc).unwrap(); + let payload = encode_mesh(key, shaders, &layout, &desc, false).unwrap(); GraphicsHistoryRecord::from_entry(decode(&payload).unwrap()).unwrap() }; let records = [ @@ -2874,6 +2993,36 @@ mod tests { assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); } + #[test] + fn a_graphics_job_with_a_missing_or_incorrectly_named_shader_fails() { + use crate::hle::d3d12x::gfx_records::{encode_mesh, shader_entry, Writer}; + use crate::hle::d3d12x::real::shader_key; + let path = std::env::temp_dir().join(format!("xcl-graphics-missing-{}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let bytes = b"mesh"; + let key = shader_key(bytes); + { + let mut job = Writer::open(&path, u64::MAX).unwrap(); + job.add(&encode_mesh(key, [key, 0], &[25], &Default::default(), false).unwrap()).unwrap(); + } + assert_eq!(graphics_worker(&path, 1, Some(1)), 2); + { + let mut job = Writer::open(&path, u64::MAX).unwrap(); + job.add(&shader_entry(key, b"different mesh")).unwrap(); + } + assert_eq!(graphics_worker(&path, 1, Some(1)), 2); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn explicit_pipeline_worker_counts_can_use_all_thirty_two_slots() { + for count in [1, 2, 8, 16, 32] { + assert_eq!(corpus_threads(Some(count), 1), count); + } + assert_eq!(corpus_threads(Some(0), 1), 1); + assert_eq!(corpus_threads(Some(33), 1), 32); + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs new file mode 100644 index 0000000000..a2b564fe7b --- /dev/null +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -0,0 +1,186 @@ +//! A staged set of native graphics and compute recipes, shared by startup and offline preparation. +use super::{gfx_records, graphics_summary, progress_count, recomp, worker_command, LaunchPreparation, Pipelines}; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{mpsc, Mutex}; +use std::time::Duration; + +pub(crate) struct Corpus { + graphics: Option<(PathBuf, usize)>, + compute: Vec<(u64, PathBuf)>, + windows: u32, +} + +pub(crate) fn discover(root: &Path) -> Result, String> { + let dir = root.join(".xcl").join("pso-corpus"); + if !dir.try_exists().map_err(|e| e.to_string())? { return Ok(None); } + let marker = std::fs::read_to_string(dir.join("complete")).map_err(|e| format!("Incomplete pipeline corpus: {e}"))?; + let expected = marker.split_whitespace().map(str::parse::).collect::, _>>() + .map_err(|_| "Invalid pipeline corpus counts")?; + if expected.len() != 2 { return Err("Expected graphics and compute counts in the corpus marker".into()); } + let encoded = std::fs::read_to_string(dir.join("windows")).map_err(|e| e.to_string())?; + let encoded = encoded.trim().parse::().map_err(|_| "Invalid corpus memory window count")?; + let count = (encoded & 127) as usize; + let heap = encoded & 128 != 0; + if !recomp::valid_window_count(count, heap) || heap && count <= 1 { + return Err(format!("Invalid corpus memory window configuration {encoded}")); + } + let windows = count as u32 | if heap { recomp::HEAP_WINDOWS } else { 0 }; + let path = dir.join("graphics.bin"); + let graphics = if path.try_exists().map_err(|e| e.to_string())? { + let entries = gfx_records::read_job(&path)?; + let count = entries.iter().filter(|e| !matches!(e, gfx_records::Entry::Shader(..))).count(); + if count == 0 { return Err("Graphics job contains no pipeline records".into()); } + Some((path, count)) + } else { None }; + let mut compute = Vec::new(); + let folder = dir.join("compute"); + if folder.try_exists().map_err(|e| e.to_string())? { + for entry in std::fs::read_dir(&folder).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + let path = entry.path(); + let name = entry.file_name(); + let key = name.to_str().and_then(|s| s.strip_suffix(".dxbc")) + .filter(|s| s.len() == 16).and_then(|s| u64::from_str_radix(s, 16).ok()); + let key = key.ok_or_else(|| format!("Invalid compute entry {}", path.display()))?; + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { + return Err(format!("Expected a compute file at {}", path.display())); + } + compute.push((key, path)); + } + } + compute.sort_unstable(); + if expected != [graphics.as_ref().map_or(0, |(_, n)| *n), compute.len()] { + return Err("Pipeline corpus is missing records. Restage before launching.".into()); + } + if graphics.is_none() && compute.is_empty() { return Err("Published pipeline corpus is empty".into()); } + Ok(Some(Corpus { graphics, compute, windows })) +} + +impl Corpus { + pub(crate) fn prepare(&self, progress: &LaunchPreparation) -> Result<(), String> { + self.prepare_with_threads(progress, None) + } + + pub(super) fn prepare_with_threads(&self, progress: &LaunchPreparation, requested: Option) -> Result<(), String> { + let graphics_count = self.graphics.as_ref().map_or(0, |(_, n)| *n); + progress.begin_corpus(graphics_count + self.compute.len()); + let count = self.windows & !recomp::HEAP_WINDOWS; + let runtime = crate::gpu::uma::configured_runtime_windows(); + if count as usize != runtime || (self.windows & recomp::HEAP_WINDOWS != 0) != (runtime > 1 && recomp::pso::heap_windows()) { + return Err(format!("Pipeline corpus memory configuration differs from the runtime ({runtime} windows). Restage for the current configuration or select the matching XCL_UMA_WINDOWS and XCL_HEAP_WINDOWS.")); + } + let parallel = super::corpus_threads(requested, super::prepare_workers().min(8)); + if let Some((path, n)) = &self.graphics { + run_graphics(path, *n, count, parallel, progress)?; + } + if self.compute.is_empty() { return progress.check_corpus_complete(); } + let mut pipelines = Pipelines::for_adapter(&progress.adapter)?; + pipelines.max_dxil = 0; + pipelines.most = parallel; + let next = AtomicUsize::new(0); + let completed = Mutex::new(graphics_count); + let error = Mutex::new(None); + std::thread::scope(|scope| { + for _ in 0..parallel.min(self.compute.len()) { + scope.spawn(|| loop { + if progress.cancel.load(Ordering::Acquire) || error.lock().unwrap().is_some() { break; } + let i = next.fetch_add(1, Ordering::Relaxed); + let Some((key,path)) = self.compute.get(i) else { break }; + let result = std::fs::read(path).map_err(|e| e.to_string()).and_then(|code| { + if crate::gpu::shader::fnv64(&code) != *key || !super::is_compute_container(&code) { + return Err("Compute shader identity or stage differs from the staged recipe".into()); + } + pipelines.prepare_compute(&code, self.windows)?; + let mut done = completed.lock().unwrap(); + *done += 1; + progress.complete_corpus(*done) + }); + if let Err(e) = result { + error.lock().unwrap().get_or_insert_with(|| format!("{}: {e}", path.display())); + break; + } + }); + } + }); + if let Some(e) = error.into_inner().unwrap() { return Err(e); } + progress.check_corpus_complete() + } +} + +fn run_graphics(path: &Path, count: usize, windows: u32, parallel: usize, progress: &LaunchPreparation) -> Result<(), String> { + let me = std::env::current_exe().map_err(|e| e.to_string())?; + let mut command = worker_command(&me); + if std::env::var("XCL_ADAPTER").unwrap_or_default().trim().is_empty() && !progress.adapter.is_empty() { + command.env("XCL_ADAPTER", &progress.adapter); + } + let mut child = command.arg("shaders").arg(path).arg("--graphics-records") + .arg("--windows").arg(windows.to_string()).env("XCL_PIPELINE_THREADS", parallel.to_string()) + .spawn().map_err(|e| e.to_string())?; + let stderr = child.stderr.take().expect("worker_command pipes stderr"); + let (tx, rx) = mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in BufReader::new(stderr).lines() { + if tx.send(line).is_err() { break; } + } + }); + let mut summary = None; + let mut last = String::new(); + let mut made = 0; + let result = loop { + if progress.cancel.load(Ordering::Acquire) { break Err("Pipeline preparation cancelled".to_string()); } + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(Ok(line)) => { + if let Some(n) = progress_count(&line) { + // Independent workers can print their completion counters out of order. + made = made.max(n); + if let Err(e) = progress.complete_corpus(made) { break Err(e); } + } else { + if let Some(values) = graphics_summary(&line) { summary = Some(values); } + if !line.trim().is_empty() { last = line; } + } + } + Ok(Err(e)) => break Err(e.to_string()), + Err(mpsc::RecvTimeoutError::Timeout) => continue, + Err(mpsc::RecvTimeoutError::Disconnected) => break Ok(()), + } + }; + if result.is_err() { let _ = child.kill(); } + drop(rx); + let status = child.wait().map_err(|e| e.to_string())?; + reader.join().map_err(|_| "Could not read graphics worker output")?; + result?; + if !status.success() || !matches!(summary, Some([n, 0, _, _]) if n == count) { + return Err(format!("Graphics preparation incomplete ({status}): {last}")); + } + progress.complete_corpus(count) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn discovery_distinguishes_absent_incomplete_and_ready_compute_corpora() { + let root = std::env::temp_dir().join(format!("xcl-corpus-discovery-{}", std::process::id())); + let dir = root.join(".xcl/pso-corpus"); + struct Cleanup(PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } + } + let _cleanup = Cleanup(root.clone()); + assert!(discover(&root).unwrap().is_none()); + std::fs::create_dir_all(dir.join("compute")).unwrap(); + assert!(discover(&root).is_err()); + std::fs::write(dir.join("complete"), "0 1\n").unwrap(); + std::fs::write(dir.join("windows"), "1\n").unwrap(); + assert!(discover(&root).is_err()); + std::fs::write(dir.join("compute/0000000000000010.dxbc"), []).unwrap(); + let corpus = discover(&root).unwrap().unwrap(); + assert_eq!(corpus.compute[0].0, 16); + assert_eq!(corpus.windows, 1); + std::fs::write(dir.join("windows"), "255").unwrap(); + assert!(discover(&root).is_err()); + } +} diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 8e7109f622..2f5773130f 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -48,6 +48,26 @@ fn copy_dir(src: &Path, dst: &Path) { } } +#[test] +fn incomplete_discovered_corpus_blocks_headless_title_entry() { + let xcl = Path::new(env!("CARGO_BIN_EXE_xcl")); + let root = temp_dir("incomplete-corpus"); + let game = root.join("game"); + let data = root.join("data"); + copy_dir(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/testgame"), &game); + std::fs::copy(xcl.parent().unwrap().join("xcl_testtitle.exe"), game.join("xcl_testtitle.exe")).unwrap(); + std::fs::create_dir_all(game.join(".xcl/pso-corpus")).unwrap(); + let settings = data.join("XCL.TestTitle"); + std::fs::create_dir_all(&settings).unwrap(); + std::fs::write(settings.join("xcl.toml"), "graphics='null'\npresent='off'\n").unwrap(); + let out = Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) + .env("XCL_PREPARE", "0").env("XCL_PREPARE_GRAPHICS", "0").output().unwrap(); + assert!(!out.status.success(), "An incomplete corpus released the guest"); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(log.contains("Incomplete pipeline corpus"), "{log}"); + assert!(!log.contains("game entry point returned"), "{log}"); +} + struct TempDir(PathBuf); impl std::ops::Deref for TempDir { From 0600e8620e09f9634334828ff2141c722a1bb230 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:03:25 -0500 Subject: [PATCH 11/22] Shaders: stream staged graphics jobs and preserve mesh cache identities Avoid decoding the entire graphics job in both the launcher and worker. Validate the independent worker completion count and reject incompatible corpus configurations. Preserve cache reuse for inert mesh shader slots and cover the headless launch gate. --- crates/xcl/src/hle/d3d12x/gfx_records.rs | 32 ++++++++++++++++--- .../xcl/src/hle/d3d12x/present/preparation.rs | 6 ++-- .../src/hle/d3d12x/real/two_pass_identity.rs | 24 ++++++++++++-- crates/xcl/src/shaders.rs | 4 +++ crates/xcl/src/shaders/pso_corpus.rs | 17 ++++++---- crates/xcl/tests/e2e.rs | 10 +++++- scripts/pso_corpus/stage.py | 3 +- scripts/pso_corpus/test_stage.py | 1 + 8 files changed, 78 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 74b01fbb24..46a8c8f939 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -4,7 +4,7 @@ //! driver's blobs on disk. `used-pipelines.txt` holds only the keys of the shader sets and the //! driver cache only blobs named after the translated DXIL: neither is enough to make one again. //! -//! `used-graphics-pipelines.bin` beside the DXIL cache: +//! `used-graphics-pipelines.bin` in the title's cache (older runs used the shared DXIL cache): //! //! ```text //! file = "XCLGFXP\0", version u32, entry* @@ -485,10 +485,32 @@ pub(crate) fn read(path: &Path) -> Vec> { /// A completed worker job must contain only whole, supported records. A history file /// may be open for appends, so its reader above accepts a trailing partial entry. fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { - let file = std::fs::read(path).map_err(|e| e.to_string())?; - let (payloads, end) = payloads(&file).ok_or("unrecognized graphics job header")?; - if end != file.len() { return Err(format!("damaged graphics job at byte {end}")); } - payloads.into_iter().enumerate().map(|(i, p)| decode(p).map(|entry| take(p, entry)).ok_or_else(|| format!("invalid graphics job entry {}", i + 1))).collect() + use std::io::{BufReader, Read}; + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + let size = file.metadata().map_err(|e| e.to_string())?.len(); + let mut reader = BufReader::new(file); + let mut magic = [0; HEADER]; + if reader.read_exact(&mut magic).is_err() || magic != header() { + return Err("unrecognized graphics job header".into()); + } + let mut offset = HEADER as u64; + let mut entries = Vec::new(); + let mut payload = Vec::new(); + while offset < size { + let damaged = || format!("damaged graphics job at byte {offset}"); + let mut frame = [0; 8]; + if size - offset < 8 { return Err(damaged()); } + reader.read_exact(&mut frame).map_err(|_| damaged())?; + let len = u32::from_le_bytes(frame[..4].try_into().unwrap()) as usize; + if len as u64 > size - offset - 8 { return Err(damaged()); } + payload.resize(len, 0); + reader.read_exact(&mut payload).map_err(|_| damaged())?; + if check(&payload) != u32::from_le_bytes(frame[4..].try_into().unwrap()) { return Err(damaged()); } + let entry = decode(&payload).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; + entries.push(take(&payload, entry)); + offset += 8 + len as u64; + } + Ok(entries) } pub(crate) fn read_complete_payloads(path: &Path) -> Result>, String> { diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index baff972a85..bdd52d4ea3 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -43,9 +43,9 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { std::env::remove_var("XCL_PREPARATION_MENU"); let root = &boot.game_root; let corpus = root.join(".xcl/pso-corpus").try_exists().map_err(|e| e.to_string())?; - if !corpus && (boot.config.graphics.eq_ignore_ascii_case("null") || - (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir() && - !crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?)) { + let history = crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?; + if !corpus && !history && (boot.config.graphics.eq_ignore_ascii_case("null") || + (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir())) { return Ok(()); } let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index c1e7efddc3..6f9c86ad1c 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -221,8 +221,9 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp } } 1..=6 | 24 | 25 => { - let state = read_state::(payload)?; - if state.BytecodeLength == 0 && ty != 25 { + if matches!(ty, 1..=5) && payload.iter().all(|&byte| byte == 0) { + h.u32(ty); + h.u64(0); continue; } let code = payload_shader(payload)?; @@ -275,6 +276,25 @@ mod tests { use super::super::StreamOut; use std::ffi::c_void; + #[test] + fn inactive_shader_stages_keep_a_two_pass_driver_cache_key() { + let ms = [1u8, 2, 3, 4]; + let key = |stages: &[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE]| { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &ms); + for &stage in stages { stream.put(stage, &D3D12_SHADER_BYTECODE::default()); } + unsafe { two_pass_stream_key(&stream.0, &[], 7, 1) } + }; + let ds = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS; + let hs = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS; + let gs = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS; + let tagged = key(&[ds, hs, gs]).unwrap(); + assert_eq!(tagged.1, ms.len()); + assert_eq!(Some(tagged), key(&[gs, ds, hs])); + assert_ne!(Some(tagged), key(&[])); + assert_eq!(key(&[ds, ds]), None); + } + #[test] fn canonical_stream_key_distinguishes_state_samplers_and_driver() { let ms = [1u8, 2, 3, 4]; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 08bba82667..30f45ff550 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -958,6 +958,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } }; if opts.prepare_corpus { + if opts.windows.is_some() || opts.split.is_some() || opts.limit != usize::MAX || opts.only.is_some() || opts.used_only { + eprintln!("xcl shaders: --prepare-corpus requires all staged recipes and their recorded memory configuration"); + return 2; + } let progress = LaunchPreparation { adapter: "auto".into(), ..Default::default() }; let result = pso_corpus::discover(path) .and_then(|c| c.ok_or_else(|| "No pipeline corpus found in this title folder".to_string())) diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index a2b564fe7b..9accff8cd2 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -1,5 +1,5 @@ //! A staged set of native graphics and compute recipes, shared by startup and offline preparation. -use super::{gfx_records, graphics_summary, progress_count, recomp, worker_command, LaunchPreparation, Pipelines}; +use super::{graphics_summary, progress_count, recomp, worker_command, LaunchPreparation, Pipelines}; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -23,16 +23,16 @@ pub(crate) fn discover(root: &Path) -> Result, String> { let encoded = encoded.trim().parse::().map_err(|_| "Invalid corpus memory window count")?; let count = (encoded & 127) as usize; let heap = encoded & 128 != 0; - if !recomp::valid_window_count(count, heap) || heap && count <= 1 { + if count == 0 || !recomp::valid_window_count(count, heap) || heap && count <= 1 { return Err(format!("Invalid corpus memory window configuration {encoded}")); } let windows = count as u32 | if heap { recomp::HEAP_WINDOWS } else { 0 }; let path = dir.join("graphics.bin"); let graphics = if path.try_exists().map_err(|e| e.to_string())? { - let entries = gfx_records::read_job(&path)?; - let count = entries.iter().filter(|e| !matches!(e, gfx_records::Entry::Shader(..))).count(); - if count == 0 { return Err("Graphics job contains no pipeline records".into()); } - Some((path, count)) + if expected[0] == 0 { return Err("Unexpected graphics job in compute-only corpus".into()); } + // The worker validates and decodes the job. Require its independent native-success + // count to match the marker before handoff, without loading the job twice. + Some((path, expected[0])) } else { None }; let mut compute = Vec::new(); let folder = dir.join("compute"); @@ -65,7 +65,8 @@ impl Corpus { pub(super) fn prepare_with_threads(&self, progress: &LaunchPreparation, requested: Option) -> Result<(), String> { let graphics_count = self.graphics.as_ref().map_or(0, |(_, n)| *n); - progress.begin_corpus(graphics_count + self.compute.len()); + let total = graphics_count.checked_add(self.compute.len()).ok_or("Pipeline corpus count overflow")?; + progress.begin_corpus(total); let count = self.windows & !recomp::HEAP_WINDOWS; let runtime = crate::gpu::uma::configured_runtime_windows(); if count as usize != runtime || (self.windows & recomp::HEAP_WINDOWS != 0) != (runtime > 1 && recomp::pso::heap_windows()) { @@ -182,5 +183,7 @@ mod tests { assert_eq!(corpus.windows, 1); std::fs::write(dir.join("windows"), "255").unwrap(); assert!(discover(&root).is_err()); + std::fs::write(dir.join("windows"), "0").unwrap(); + assert!(discover(&root).is_err()); } } diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 2f5773130f..770dbbc5f1 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -60,12 +60,20 @@ fn incomplete_discovered_corpus_blocks_headless_title_entry() { let settings = data.join("XCL.TestTitle"); std::fs::create_dir_all(&settings).unwrap(); std::fs::write(settings.join("xcl.toml"), "graphics='null'\npresent='off'\n").unwrap(); - let out = Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) + let launch = || Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) .env("XCL_PREPARE", "0").env("XCL_PREPARE_GRAPHICS", "0").output().unwrap(); + let out = launch(); assert!(!out.status.success(), "An incomplete corpus released the guest"); let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); assert!(log.contains("Incomplete pipeline corpus"), "{log}"); assert!(!log.contains("game entry point returned"), "{log}"); + std::fs::remove_dir(game.join(".xcl/pso-corpus")).unwrap(); + std::fs::create_dir_all(settings.join("cache")).unwrap(); + std::fs::write(settings.join("cache/used-graphics-pipelines.bin"), b"bad history").unwrap(); + assert!(!launch().status.success()); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(log.contains("unrecognized graphics job header"), "{log}"); + assert!(!log.contains("game entry point returned"), "{log}"); } struct TempDir(PathBuf); diff --git a/scripts/pso_corpus/stage.py b/scripts/pso_corpus/stage.py index 2622477eaa..6e2723f486 100644 --- a/scripts/pso_corpus/stage.py +++ b/scripts/pso_corpus/stage.py @@ -181,7 +181,8 @@ def build(journals, dest, spool, records): if tag == "S": require(win == 0 and data, "invalid shader frame") else: - require(1 <= (win & 127) <= (16 if win & 128 else 4), "invalid window count") + count = win & 127 + require(count in ((2, 3, 4, 8, 16) if win & 128 else (1, 2, 3, 4)), "invalid window count") digest = hashlib.sha256(data).digest() identity = tag, key if identity in seen: diff --git a/scripts/pso_corpus/test_stage.py b/scripts/pso_corpus/test_stage.py index d89230f3f4..d9259eb4a3 100644 --- a/scripts/pso_corpus/test_stage.py +++ b/scripts/pso_corpus/test_stage.py @@ -87,6 +87,7 @@ def test_invalid_frames_never_publish(self): [self.src, frame("G", overflow)], [self.src, good, frame("G", graphic(self.key), 4)], [self.src[:-1] + b"X", good], [self.src, good[:-1] + b"X"], [self.src, frame("C", compute(self.key, 2))], + [self.src, frame("C", compute(self.key, 0), 133)], [self.src, frame("M", struct.pack(" Date: Thu, 26 Nov 2026 11:15:44 -0500 Subject: [PATCH 12/22] Shaders: prepare exact pack and history overlaps once at startup Match shader bytes and full graphics descriptors against the mandatory staged job. Keep distinct fixed-state variants and resolve their shader inputs from the staged corpus. A 48-recipe overlap fixture removed 48 redundant native submissions before the staged pass. --- README.md | 1 + crates/xcl/src/hle/d3d12x/gfx_records.rs | 27 ++- crates/xcl/src/shaders.rs | 237 +++++++++++++++++++++-- crates/xcl/src/shaders/pso_corpus.rs | 16 ++ 4 files changed, 254 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index df94e5b106..cd374b2035 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,7 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` The offline command accepts up to 32 workers. Normal launch also prepares the staged corpus. + When a shader pack or local history overlaps the corpus, XCL prepares each exact match once. Use the same adapter and memory-window configuration for offline preparation and play so the driver can reuse the results. Graphics state combinations absent from the supplied recipes and local history can still diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 46a8c8f939..da67c08765 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -484,7 +484,7 @@ pub(crate) fn read(path: &Path) -> Vec> { /// A completed worker job must contain only whole, supported records. A history file /// may be open for appends, so its reader above accepts a trailing partial entry. -fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { +pub(crate) fn visit_payloads(path: &Path, mut visit: impl FnMut(&[u8]) -> Result<(), String>) -> Result<(), String> { use std::io::{BufReader, Read}; let file = std::fs::File::open(path).map_err(|e| e.to_string())?; let size = file.metadata().map_err(|e| e.to_string())?.len(); @@ -494,7 +494,6 @@ fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Res return Err("unrecognized graphics job header".into()); } let mut offset = HEADER as u64; - let mut entries = Vec::new(); let mut payload = Vec::new(); while offset < size { let damaged = || format!("damaged graphics job at byte {offset}"); @@ -506,10 +505,26 @@ fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Res payload.resize(len, 0); reader.read_exact(&mut payload).map_err(|_| damaged())?; if check(&payload) != u32::from_le_bytes(frame[4..].try_into().unwrap()) { return Err(damaged()); } - let entry = decode(&payload).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; - entries.push(take(&payload, entry)); + visit(&payload)?; offset += 8 + len as u64; } + Ok(()) +} + +pub(crate) fn shader_payload(payload: &[u8]) -> Option<(u64, &[u8])> { + let (&tag, rest) = payload.split_first()?; + if tag != SHADER { return None; } + let mut r = Reader(rest); + Some((r.u64()?, r.0)) +} + +fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { + let mut entries = Vec::new(); + visit_payloads(path, |bytes| { + let entry = decode(bytes).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; + entries.push(take(bytes, entry)); + Ok(()) + })?; Ok(entries) } @@ -607,7 +622,7 @@ pub(crate) fn note(payload: Vec) { let mut w = match Writer::open(&path, cap) { Ok(w) => w, Err(e) => { - crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); + crate::xlog_warn!("D3D12.X: {}: {e} – the graphics pipelines of this run are not prepared before the next", path.display()); return; } }; @@ -622,7 +637,7 @@ pub(crate) fn note(payload: Vec) { } Ok(_) => {} Err(e) => { - crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); + crate::xlog_warn!("D3D12.X: {}: {e} – no more graphics pipelines are recorded in this run", path.display()); return; } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 30f45ff550..f78ad43564 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -958,7 +958,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } }; if opts.prepare_corpus { - if opts.windows.is_some() || opts.split.is_some() || opts.limit != usize::MAX || opts.only.is_some() || opts.used_only { + if opts.split.is_some() || opts.limit != usize::MAX || opts.only.is_some() || opts.used_only { eprintln!("xcl shaders: --prepare-corpus requires all staged recipes and their recorded memory configuration"); return 2; } @@ -1053,7 +1053,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, selected.as_ref(), opts.threads, t0, None) { + let coverage = match ComputeCoverage::worker() { + Ok(coverage) => coverage, + Err(e) => { eprintln!("xcl shaders: {e}"); return 2; } + }; + return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, selected.as_ref(), opts.threads, t0, None, coverage.as_ref()) { Ok(()) => 0, Err(e) => { eprintln!("xcl shaders: {e}"); 2 } }; @@ -1884,7 +1888,7 @@ fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { let corpus = pso_corpus::discover(root)?; - prepare_title_inputs(root, progress)?; + prepare_title_inputs(root, progress, corpus.as_ref())?; if let Some(corpus) = corpus { corpus.prepare(progress)?; progress.check_corpus_complete()?; @@ -1892,7 +1896,7 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R Ok(()) } -fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { +fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Option<&pso_corpus::Corpus>) -> Result<(), String> { let mut inputs = Vec::new(); let pack = root.join("shaders.rpf"); if pack.try_exists().map_err(|e| e.to_string())? { @@ -1913,20 +1917,95 @@ fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation) -> Result<(), if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } let workers = prepare_workers(); for input in &inputs { + let coverage = corpus.filter(|c| c.compute_directory().is_some()) + .map(|corpus| ComputeCoverage::Published(corpus, Mutex::default(), AtomicUsize::new(0))); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } // a pack: its stages here, its compute pipelines in worker processes (the driver builds // about two pipelines at a time for one process, whatever the processors) if workers > 1 && matches!(input, Input::Pack { .. }) { let n = input.len(); - precompile(input, usize::MAX, windows, None, None, false, None, None, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, false, None, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - pipelines_in_workers(&pack, windows, workers, n, progress)?; + if coverage.as_ref().is_some_and(ComputeCoverage::all_staged) { continue; } + pipelines_in_workers(&pack, windows, workers, n, progress, coverage.as_ref())?; continue; } - precompile(input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress))?; + precompile(input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; } if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - graphics_in_workers(&inputs, windows, workers, progress) + graphics_in_workers(&inputs, windows, workers, progress, corpus.and_then(|c| c.graphics_path())) +} + +/// Only records verified byte-for-byte against the discovered corpus may leave their native +/// preparation to that pass. A worker also checks the index, key and bytes of its own pack. +enum ComputeCoverage<'a> { + Published(&'a pso_corpus::Corpus, Mutex>, AtomicUsize), + Slice(PathBuf, BTreeMap), +} + +const COVERAGE_MAP: &str = "XCL_PRECOMPILE_COVERAGE_MAP"; +const COVERAGE_DIR: &str = "XCL_PRECOMPILE_COVERAGE_DIR"; + +struct CoverageFile(PathBuf); +impl Drop for CoverageFile { + fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } +} + +impl ComputeCoverage<'_> { + fn all_staged(&self) -> bool { + matches!(self, Self::Published(_, _, remaining) if remaining.load(Ordering::Relaxed) == 0) + } + + fn covers(&self, index: usize, blob: &[u8]) -> Result { + let key = shader::fnv64(blob); + let path = match self { + Self::Published(corpus, _, remaining) => match corpus.compute_path(key) { + Some(path) => path.to_path_buf(), + None => { remaining.fetch_add(1, Ordering::Relaxed); return Ok(false); } + }, + Self::Slice(dir, keys) if keys.get(&index) == Some(&key) => dir.join(format!("{key:016x}.dxbc")), + Self::Slice(..) => return Ok(false), + }; + let staged = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; + if blob != staged { + if shader::fnv64(&staged) != key { return Err(format!("Staged compute shader {key:016x} changed")); } + if let Self::Published(_, _, remaining) = self { remaining.fetch_add(1, Ordering::Relaxed); } + return Ok(false); + } + if let Self::Published(_, selected, _) = self { selected.lock().unwrap().insert(index, key); } + Ok(true) + } + + fn slice_file(&self) -> Result, String> { + use std::io::Write; + let Self::Published(corpus, selected, _) = self else { return Ok(None) }; + let Some(dir) = corpus.compute_directory() else { return Ok(None) }; + let selected = selected.lock().unwrap(); + if selected.is_empty() { return Ok(None); } + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos(); + let path = std::env::temp_dir().join(format!("xcl-compute-coverage-{}-{nonce}.bin", std::process::id())); + let mut file = std::fs::File::create_new(&path).map_err(|e| e.to_string())?; + let cleanup = CoverageFile(path); + let mut bytes = Vec::with_capacity(selected.len()*16); + for (&i, &key) in selected.iter() { bytes.extend_from_slice(&(i as u64).to_le_bytes()); bytes.extend_from_slice(&key.to_le_bytes()); } + file.write_all(&bytes).map_err(|e| e.to_string())?; + Ok(Some((cleanup, dir))) + } + + fn worker() -> Result, String> { + if std::env::var_os("XCL_PRECOMPILE_PARENT").is_none() { return Ok(None); } + let Some(path) = std::env::var_os(COVERAGE_MAP) else { return Ok(None) }; + let dir = std::env::var_os(COVERAGE_DIR).ok_or("Missing staged compute directory for worker")?; + Self::read_slice(Path::new(&path), PathBuf::from(dir)).map(Some) + } + + fn read_slice(path: &Path, dir: PathBuf) -> Result { + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + if bytes.len() % 16 != 0 { return Err("Incomplete compute worker coverage map".into()); } + let keys = bytes.chunks_exact(16).map(|b| (u64::from_le_bytes(b[..8].try_into().unwrap()) as usize, + u64::from_le_bytes(b[8..].try_into().unwrap()))).collect(); + Ok(Self::Slice(dir, keys)) + } } /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title @@ -2012,16 +2091,16 @@ mod claim_tests { } /// The compute pipelines of `pack` built by `workers` processes of this program, each on its own -/// slice of the records (`XCL_PRECOMPILE_SLICE`): only the ones an earlier run of the title used -/// when that list exists (the title builds another when it first uses it). Their records count -/// into `progress`. A worker that fails is noted and the title starts all the same: it builds -/// what is missing itself. -fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation) -> Result<(), String> { +/// slice of the records (`XCL_PRECOMPILE_SLICE`). A failed worker prevents guest entry. +fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usize, progress: &LaunchPreparation, + coverage: Option<&ComputeCoverage>) -> Result<(), String> { let me = std::env::current_exe().map_err(|e| e.to_string())?; + let map = coverage.map(|c| c.slice_file()).transpose()?.flatten(); let t0 = std::time::Instant::now(); crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes"); let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { let mut c = worker_command(&me); + if let Some((file, dir)) = &map { c.env(COVERAGE_MAP, &file.0).env(COVERAGE_DIR, dir); } c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); @@ -2039,7 +2118,7 @@ fn worker_command(me: &Path) -> std::process::Command { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; let mut c = std::process::Command::new(me); - for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS"] { c.env_remove(gone); } + for gone in ["XCL_HOST", "XCL_PREPARATION_PARENT", "XCL_PREPARATION_MENU", "XCL_RUN_SECONDS", COVERAGE_MAP, COVERAGE_DIR] { c.env_remove(gone); } c.env("XCL_PRECOMPILE_PARENT", std::process::id().to_string()); if std::env::var_os("XCL_DXC_THREADS").is_none() { c.env("XCL_DXC_THREADS", "2"); } if std::env::var_os("XCL_PIPELINE_THREADS").is_none() { c.env("XCL_PIPELINE_THREADS", "1"); } @@ -2116,9 +2195,8 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut /// worker processes as the compute pipelines: the driver builds about two pipelines at a time for /// one process, and a driver that ends a worker ends no title. Their shaders come from the title's /// shader files (`inputs`) by key, as those of `used-shaders.txt`; each worker gets a file of its -/// part (`gfx_records`' format, with the shaders it needs). A failure is noted and the title -/// starts all the same: it builds what is missing itself. -fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation) -> Result<(), String> { +/// part (`gfx_records`' format, with the shaders it needs). A worker must confirm every recipe. +fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation, staged_graphics: Option<&Path>) -> Result<(), String> { let t0 = std::time::Instant::now(); let path = gfx_records::path(); let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_complete_payloads(&path)? } else { Vec::new() }; @@ -2135,7 +2213,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: entry => if let Some(record) = GraphicsHistoryRecord::from_entry(entry) { records.push((payload, record)); }, } } - let local_count = records.len(); + let mut local_count = records.len(); let legacy = gfx_records::shared_history_path(); if !inputs.is_empty() && legacy != path { let scoped: HashSet<_> = records.iter().map(|(bytes, _)| bytes.as_slice()).collect(); @@ -2147,9 +2225,17 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: crate::xlog_info!("Shader preparation: no graphics pipelines of an earlier run to build"); return Ok(()); } - let wanted = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) + if let Some(staged) = staged_graphics { + let before = records.len(); + local_count = merge_staged_history(staged, &mut records, local_count, &mut embedded)?; + if before != records.len() { + crate::xlog_info!("Shader preparation: the mandatory staged job covers {} exact graphics history recipes", before - records.len()); + } + if records.is_empty() { return Ok(()); } + } + let wanted: HashSet<_> = records.iter().flat_map(|(_, record)| record.identity().1.iter().copied()) .filter(|&key| key != 0 && !embedded.contains_key(&key)).collect(); - let mut shaders = shaders_by_key(inputs, wanted, progress); + let mut shaders = if wanted.is_empty() { HashMap::new() } else { shaders_by_key(inputs, wanted, progress) }; shaders.extend(embedded); if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); @@ -2202,6 +2288,33 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: Ok(()) } +/// Only identical serialized descriptors can be left for the subsequent mandatory staged job. +fn merge_staged_history( + staged: &Path, records: &mut Vec<(Vec, GraphicsHistoryRecord)>, local_count: usize, + embedded: &mut HashMap>, +) -> Result { + let mut covered: HashMap<&[u8], bool> = records.iter().map(|(p, _)| (p.as_slice(), false)).collect(); + let wanted: HashSet = records.iter().flat_map(|(_, r)| r.identity().1.iter().copied()).filter(|k| *k != 0).collect(); + gfx_records::visit_payloads(staged, |payload| { + if let Some((key, code)) = gfx_records::shader_payload(payload) { + if wanted.contains(&key) { + if crate::hle::d3d12x::real::shader_key(code) != key || embedded.get(&key).is_some_and(|prior| prior.as_slice() != code) { + return Err(format!("Staged graphics shader {key:016x} failed its identity check")); + } + embedded.entry(key).or_insert_with(|| code.to_vec()); + } + } else if let Some(present) = covered.get_mut(payload) { + *present = true; + } + Ok(()) + })?; + let keep: Vec = records.iter().map(|(p, _)| !covered[p.as_slice()]).collect(); + let remaining_local = keep[..local_count].iter().filter(|&&k| k).count(); + let mut keep = keep.into_iter(); + records.retain(|_| keep.next().unwrap()); + Ok(remaining_local) +} + /// The bytes of the shaders `wanted` (`real::shader_key`) in the title's shader files, looked /// for on every processor. fn shaders_by_key(inputs: &[Input], wanted: HashSet, progress: &LaunchPreparation) -> std::collections::HashMap> { @@ -2369,7 +2482,7 @@ fn end_with_parent() { }); } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, selected: Option<&std::collections::HashSet>, pipeline_threads: Option, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, selected: Option<&std::collections::HashSet>, pipeline_threads: Option, t0: std::time::Instant, startup: Option<&LaunchPreparation>, coverage: Option<&ComputeCoverage>) -> Result<(), String> { if startup.is_none() { end_with_parent(); } let mandatory = startup.is_some() || std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(); let pipelines = if pipelines { @@ -2470,6 +2583,19 @@ 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(_)))) { + if let Some(coverage) = coverage { + match coverage.covers(i, &blob) { + Ok(true) => { record_done(); continue; } + Err(e) => { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + record_done(); + continue; + } + Ok(false) => {} + } + } match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { @@ -2562,6 +2688,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } let failed = failed.into_inner(); let skipped_reason = if startup.is_some() { "runtime pairing or unsupported translation" } else { "GS – paired at pipeline creation" }; + if let Some(ComputeCoverage::Published(_, selected, _)) = coverage { + let count = selected.lock().unwrap().len(); + if count != 0 { crate::xlog_info!("Shader preparation: {count} byte-matched compute records will be built by the staged corpus"); } + } println!( "compiled {}, already cached {}, errors {}, skipped ({skipped_reason}) {}, time {:.1} s", compiled.into_inner(), @@ -2997,6 +3127,40 @@ mod tests { assert_eq!(buildable(records.iter(), &shaders), (vec![0, 1, 4], 3)); } + #[test] + fn staged_history_defers_exact_recipes_and_supplies_sources_for_other_variants() { + use crate::hle::d3d12x::real::shader_key; + use windows::Win32::Graphics::Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC; + let path = std::env::temp_dir().join(format!("xcl-staged-history-{}.bin", std::process::id())); + let _ = std::fs::remove_file(&path); + let code = b"vertex source"; + let key = shader_key(code); + let pipeline = |mask| { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { SampleMask: mask, ..Default::default() }; + let payload = unsafe { gfx_records::encode(key, [key, 0, 0, 0, 0], &desc) }; + let record = GraphicsHistoryRecord::from_entry(gfx_records::decode(&payload).unwrap()).unwrap(); + (payload, record) + }; + let mut records = vec![pipeline(1), pipeline(2), pipeline(1), pipeline(3)]; + { + let mut staged = gfx_records::Writer::open(&path, u64::MAX).unwrap(); + staged.add(&records[0].0).unwrap(); + staged.add(&gfx_records::shader_entry(key, code)).unwrap(); + } + let mut sources = HashMap::new(); + assert_eq!(merge_staged_history(&path, &mut records, 2, &mut sources).unwrap(), 1); + assert_eq!(records.len(), 2); + assert_eq!(records[0].0, pipeline(2).0); + assert_eq!(records[1].0, pipeline(3).0); + assert_eq!(buildable(records.iter().map(|(_, r)| r), &sources), (vec![0, 1], 0)); + { + let mut staged = gfx_records::Writer::open(&path, u64::MAX).unwrap(); + staged.add(&gfx_records::shader_entry(key, b"wrong")).unwrap(); + } + assert!(merge_staged_history(&path, &mut records, 1, &mut sources).unwrap_err().contains("identity check")); + std::fs::remove_file(path).unwrap(); + } + #[test] fn a_graphics_job_with_a_missing_or_incorrectly_named_shader_fails() { use crate::hle::d3d12x::gfx_records::{encode_mesh, shader_entry, Writer}; @@ -3053,6 +3217,37 @@ mod tests { sample(5, &[compute]) } + #[test] + fn staged_compute_covers_only_its_exact_sources_in_loose_and_pack_passes() { + let name = format!("xcl-compute-membership-{}-{}", std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()); + let root = std::env::temp_dir().join(name); + let base = root.join(".xcl/pso-corpus"); + let dir = base.join("compute"); + std::fs::create_dir_all(&dir).unwrap(); + let blob = compute_sample(); + let file = dir.join(format!("{:016x}.dxbc", shader::fnv64(&blob))); + std::fs::write(&file, &blob).unwrap(); + std::fs::write(base.join("windows"), "4").unwrap(); + std::fs::write(base.join("complete"), "0 1").unwrap(); + let corpus = pso_corpus::discover(&root).unwrap().unwrap(); + let parent = ComputeCoverage::Published(&corpus, Mutex::default(), AtomicUsize::new(0)); + assert!(parent.covers(3, &blob).unwrap()); + assert!(parent.all_staged(), "no compute slice workers needed"); + assert!(!parent.covers(6, b"different source").unwrap()); + assert!(!parent.all_staged(), "uncovered compute records still need the slice"); + let (map, directory) = parent.slice_file().unwrap().unwrap(); + let child = ComputeCoverage::read_slice(&map.0, directory.to_owned()).unwrap(); + assert!(child.covers(3, &blob).unwrap()); + assert!(!child.covers(7, &blob).unwrap(), "index absent from the checked pack"); + assert!(!child.covers(3, b"changed input").unwrap(), "parent and child pack differ"); + std::fs::write(&file, b"changed after discovery").unwrap(); + assert!(child.covers(3, &blob).is_err(), "corrupt staged data cannot satisfy a recipe"); + std::fs::remove_file(&file).unwrap(); + assert!(parent.covers(3, &blob).is_err(), "missing staged data cannot satisfy a recipe"); + std::fs::remove_dir_all(root).unwrap(); + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index 9accff8cd2..bb361f2c35 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -59,6 +59,19 @@ pub(crate) fn discover(root: &Path) -> Result, String> { } impl Corpus { + pub(super) fn graphics_path(&self) -> Option<&Path> { + self.graphics.as_ref().map(|(path, _)| path.as_path()) + } + + pub(super) fn compute_path(&self, key: u64) -> Option<&Path> { + let i = self.compute.binary_search_by_key(&key, |(key, _)| *key).ok()?; + Some(self.compute[i].1.as_path()) + } + + pub(super) fn compute_directory(&self) -> Option<&Path> { + self.compute.first().and_then(|(_, path)| path.parent()) + } + pub(crate) fn prepare(&self, progress: &LaunchPreparation) -> Result<(), String> { self.prepare_with_threads(progress, None) } @@ -180,6 +193,9 @@ mod tests { std::fs::write(dir.join("compute/0000000000000010.dxbc"), []).unwrap(); let corpus = discover(&root).unwrap().unwrap(); assert_eq!(corpus.compute[0].0, 16); + assert_eq!(corpus.compute_path(16), Some(dir.join("compute/0000000000000010.dxbc").as_path())); + assert!(corpus.compute_path(17).is_none()); + assert!(corpus.graphics_path().is_none()); assert_eq!(corpus.windows, 1); std::fs::write(dir.join("windows"), "255").unwrap(); assert!(discover(&root).is_err()); From 02c66cad306fb3e427c2c31f831479aaa9209c15 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:19:32 -0500 Subject: [PATCH 13/22] Shaders: keep the launch owner responsible for the whole input Limit record slicing to offline workers. An inherited slice from an earlier CLI run must not make the launch gate overlook an unstaged shader. --- crates/xcl/src/shaders.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index f78ad43564..c3f5aab63a 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2482,6 +2482,12 @@ fn end_with_parent() { }); } +fn precompile_slice(startup_owner: bool, value: Option<&str>) -> Option<(usize, usize)> { + if startup_owner { return None; } + let (i, n) = value?.split_once('/')?; + Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) +} + fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, selected: Option<&std::collections::HashSet>, pipeline_threads: Option, t0: std::time::Instant, startup: Option<&LaunchPreparation>, coverage: Option<&ComputeCoverage>) -> Result<(), String> { if startup.is_none() { end_with_parent(); } let mandatory = startup.is_some() || std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(); @@ -2502,10 +2508,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let n = input.len().min(limit); // `XCL_PRECOMPILE_SLICE=i/n` (experiment): this process takes only every n-th shader, from the // i-th, so n processes share the work and each has its own driver compiler - let slice: Option<(usize, usize)> = std::env::var("XCL_PRECOMPILE_SLICE").ok().and_then(|v| { - let (i, n) = v.split_once('/')?; - Some((i.trim().parse().ok()?, n.trim().parse::().ok().filter(|n| *n > 0)?)) - }); + let slice = precompile_slice(startup.is_some(), std::env::var("XCL_PRECOMPILE_SLICE").ok().as_deref()); // a progress line every 200 records; every record for a title waiting on this builder // (`pipelines_in_workers` shows the count) let every = if std::env::var_os("XCL_PRECOMPILE_PARENT").is_some() { 1 } else { 200 }; @@ -3248,6 +3251,16 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn launch_owner_ignores_inherited_slices_and_workers_drop_foreign_coverage() { + assert_eq!(precompile_slice(true, Some("1/2")), None); + assert_eq!(precompile_slice(false, Some("1/2")), Some((1, 2))); + let command = worker_command(Path::new("xcl.exe")); + for name in [COVERAGE_MAP, COVERAGE_DIR] { + assert!(command.get_envs().any(|(key, value)| key == name && value.is_none())); + } + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); From 7659b88de9507fe0eb2f22ca93bfa2674d203e17 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:48:28 -0500 Subject: [PATCH 14/22] Shaders: recover usable graphics history after an interrupted append Use the intact prefix of optional history and defer records whose sources are still missing. Published worker jobs retain strict checks. Adapt the history reader regression contributed by thehollowedone. --- crates/xcl/src/hle/d3d12x/gfx_records.rs | 63 ++++++++++++++++++++---- crates/xcl/src/shaders.rs | 7 +-- 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index da67c08765..99dada1082 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -482,9 +482,9 @@ pub(crate) fn read(path: &Path) -> Vec> { payloads(&file).map_or_else(Vec::new, |(list, _)| list.into_iter().map(<[u8]>::to_vec).collect()) } -/// A completed worker job must contain only whole, supported records. A history file -/// may be open for appends, so its reader above accepts a trailing partial entry. -pub(crate) fn visit_payloads(path: &Path, mut visit: impl FnMut(&[u8]) -> Result<(), String>) -> Result<(), String> { +/// A completed worker job must contain only whole, supported records. A title history +/// may end inside an append after the previous run stopped. +fn visit_payloads_with_tail(path: &Path, allow_incomplete_tail: bool, mut visit: impl FnMut(&[u8]) -> Result<(), String>) -> Result<(), String> { use std::io::{BufReader, Read}; let file = std::fs::File::open(path).map_err(|e| e.to_string())?; let size = file.metadata().map_err(|e| e.to_string())?.len(); @@ -498,10 +498,16 @@ pub(crate) fn visit_payloads(path: &Path, mut visit: impl FnMut(&[u8]) -> Result while offset < size { let damaged = || format!("damaged graphics job at byte {offset}"); let mut frame = [0; 8]; - if size - offset < 8 { return Err(damaged()); } + if size - offset < 8 { + if allow_incomplete_tail { break; } + return Err(damaged()); + } reader.read_exact(&mut frame).map_err(|_| damaged())?; let len = u32::from_le_bytes(frame[..4].try_into().unwrap()) as usize; - if len as u64 > size - offset - 8 { return Err(damaged()); } + if len as u64 > size - offset - 8 { + if allow_incomplete_tail { break; } + return Err(damaged()); + } payload.resize(len, 0); reader.read_exact(&mut payload).map_err(|_| damaged())?; if check(&payload) != u32::from_le_bytes(frame[4..].try_into().unwrap()) { return Err(damaged()); } @@ -511,6 +517,10 @@ pub(crate) fn visit_payloads(path: &Path, mut visit: impl FnMut(&[u8]) -> Result Ok(()) } +pub(crate) fn visit_payloads(path: &Path, visit: impl FnMut(&[u8]) -> Result<(), String>) -> Result<(), String> { + visit_payloads_with_tail(path, false, visit) +} + pub(crate) fn shader_payload(payload: &[u8]) -> Option<(u64, &[u8])> { let (&tag, rest) = payload.split_first()?; if tag != SHADER { return None; } @@ -518,9 +528,13 @@ pub(crate) fn shader_payload(payload: &[u8]) -> Option<(u64, &[u8])> { Some((r.u64()?, r.0)) } -fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { +fn read_complete(path: &Path, allow_incomplete_tail: bool, mut take: impl FnMut(&[u8], Entry) -> T) -> Result, String> { let mut entries = Vec::new(); - visit_payloads(path, |bytes| { + visit_payloads_with_tail(path, allow_incomplete_tail, |bytes| { + // A newer recorder can add a tag without changing the frame format. + if allow_incomplete_tail && bytes.first().is_some_and(|tag| !matches!(*tag, PIPELINE | SHADER | MESH_PIPELINE | DEPTH_BOUNDS_PIPELINE)) { + return Ok(()); + } let entry = decode(bytes).ok_or_else(|| format!("invalid graphics job entry {}", entries.len() + 1))?; entries.push(take(bytes, entry)); Ok(()) @@ -528,12 +542,12 @@ fn read_complete(path: &Path, mut take: impl FnMut(&[u8], Entry) -> T) -> Res Ok(entries) } -pub(crate) fn read_complete_payloads(path: &Path) -> Result>, String> { - read_complete(path, |bytes, _| bytes.to_vec()) +pub(crate) fn read_history_payloads(path: &Path) -> Result>, String> { + read_complete(path, true, |bytes, _| bytes.to_vec()) } pub(crate) fn read_job(path: &Path) -> Result, String> { - read_complete(path, |_, entry| entry) + read_complete(path, false, |_, entry| entry) } /// What became of an entry handed to `Writer::add`. @@ -886,6 +900,35 @@ mod tests { assert!(read_job(&path).is_err()); } + #[test] + fn history_reader_keeps_verified_entries_after_an_incomplete_final_append() { + let dir = directory("history-tail"); + let path = dir.0.join("history.bin"); + let first = shader_entry(5, b"shader"); + let mut writer = Writer::open(&path, u64::MAX).unwrap(); + writer.add(&first).unwrap(); + drop(writer); + let original = std::fs::read(&path).unwrap(); + let mut writer = Writer::open(&path, u64::MAX).unwrap(); + writer.add(&shader_entry(6, b"next")).unwrap(); + drop(writer); + let complete = std::fs::read(&path).unwrap(); + let second = &complete[original.len()..]; + for tail in [&second[..3], &second[..second.len() - 2]] { + std::fs::write(&path, [original.as_slice(), tail].concat()).unwrap(); + assert_eq!(read_history_payloads(&path).unwrap(), vec![first.clone()]); + assert!(read_job(&path).is_err(), "worker jobs still require whole frames"); + } + let mut corrupt = original; + corrupt[HEADER + 8] ^= 1; + std::fs::write(&path, corrupt).unwrap(); + assert!(read_history_payloads(&path).is_err(), "a complete but corrupt frame is not a torn append"); + std::fs::write(&path, &complete).unwrap(); + Writer::open(&path, u64::MAX).unwrap().add(&[0xff]).unwrap(); + assert_eq!(read_history_payloads(&path).unwrap(), vec![first, shader_entry(6, b"next")]); + assert!(read_job(&path).is_err(), "an unsupported worker entry remains an error"); + } + #[test] fn legacy_pipeline_and_mesh_entries_share_version_one_history() { let dir = directory("mesh-version-one"); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index c3f5aab63a..24bdc4d312 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2199,7 +2199,7 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: &LaunchPreparation, staged_graphics: Option<&Path>) -> Result<(), String> { let t0 = std::time::Instant::now(); let path = gfx_records::path(); - let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_complete_payloads(&path)? } else { Vec::new() }; + let local = if path.try_exists().map_err(|e| e.to_string())? { gfx_records::read_history_payloads(&path)? } else { Vec::new() }; let mut records = Vec::new(); let mut embedded = std::collections::HashMap::new(); for payload in local { @@ -2241,9 +2241,10 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: let (buildable, missing) = buildable(records.iter().map(|(_, r)| r), &shaders); let local_missing = local_count - buildable.iter().take_while(|&&i| i < local_count).count(); if local_missing != 0 { - return Err(format!("{local_missing} of {local_count} title graphics recipes lack matching shader sources")); + crate::xlog_info!("Shader preparation: deferring {local_missing} of {local_count} recorded title graphics recipes until their shader sources are available"); } - if missing != 0 { crate::xlog_info!("Shader preparation: {missing} shared graphics recipes have no matching shaders in this title"); } + let shared_missing = missing - local_missing; + if shared_missing != 0 { crate::xlog_info!("Shader preparation: {shared_missing} shared graphics recipes have no matching shaders in this title"); } if buildable.is_empty() { return Ok(()); } let workers = workers.clamp(1, buildable.len()); // each worker's part, with the shaders it needs (removed when they are done) From 2d473dcd0cc48edbdfa8be25b5e6f7a741260498 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:48:38 -0500 Subject: [PATCH 15/22] Shaders: retain verified native preparations across rebuilds Bind startup proofs to the driver, translation and pipeline ABI. Reuse only matching DXIL and validated native files, including both mesh passes. Restore the opt-outs for optional history and unstaged startup preparation while requiring published jobs to finish. --- README.md | 5 +- crates/xcl/build.rs | 36 +++++ crates/xcl/src/gpu/recomp/dxc.rs | 2 +- crates/xcl/src/gpu/recomp/pso.rs | 4 +- crates/xcl/src/hle/d3d12x/gfx_records.rs | 7 +- .../xcl/src/hle/d3d12x/present/preparation.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 22 ++- crates/xcl/src/shaders.rs | 110 +++++++++++-- crates/xcl/src/shaders/pso_corpus.rs | 5 + crates/xcl/src/shaders/warm_blobs.rs | 93 +++++++++++ crates/xcl/src/shaders/warm_pack.rs | 101 ++++++++++++ crates/xcl/src/shaders/warm_replay.rs | 144 ++++++++++++++++++ crates/xcl/tests/e2e.rs | 11 +- 13 files changed, 522 insertions(+), 19 deletions(-) create mode 100644 crates/xcl/src/shaders/warm_blobs.rs create mode 100644 crates/xcl/src/shaders/warm_pack.rs create mode 100644 crates/xcl/src/shaders/warm_replay.rs diff --git a/README.md b/README.md index cd374b2035..6324896115 100644 --- a/README.md +++ b/README.md @@ -266,7 +266,10 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder supported shader packs, supported loose shaders under `shaders/`, recorded graphics history and staged pipeline recipes. Closing the window cancels launch. A failed staged recipe stops launch. With presentation disabled, preparation runs without a window. A staged corpus still gates - launch when the null renderer is selected. + launch when the null renderer is selected. For an unstaged title set `XCL_PREPARE=0` + to skip startup preparation, or `XCL_PREPARE_GRAPHICS=0` to skip optional graphics history. + Native recipes validated on this adapter and driver reuse their verified blobs across + rebuilds. Changes to translation, pipeline layout, settings or cache files trigger validation. - To prepare known graphics, two-pass mesh and compute recipes offline, use a local [archive layout profile](scripts/pso_corpus/archive-profile.md) with the following commands. The staging command accepts several journals and deduplicates their recipes. diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..c2d191e8f6 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -50,6 +50,41 @@ fn direct_sources(dir: &Path, out: &mut Vec) { mod source_hash; use source_hash::{add, add_source}; +// Bump when the native builder (including the D3D12.X glue in real.rs) changes the +// mapping from a journal recipe to driver descriptors or blob acceptance. Shader +// translator/toolchain, driver, adapter, settings and per-file stamps are keyed separately. +const NATIVE_PREPARATION_ABI: &[u8] = b"xcl-native-preparation-v1"; +const PREPARATION_LAYOUT_SOURCES: &[&str] = &[ + "src/gpu/recomp/pso.rs", // root signatures, translation glue, split pipeline layout + "src/hle/d3d12x/real/two_pass_identity.rs", // driver-blob identities for both mesh passes + "src/hle/d3d12x/gfx_records.rs", // normalized recipe fields and reconstruction +]; + +fn preparation_source_id(root: &Path) -> u64 { + let mut id = 0xcbf2_9ce4_8422_2325u64; + add(&mut id, NATIVE_PREPARATION_ABI); + for &relative in PREPARATION_LAYOUT_SOURCES { + println!("cargo:rerun-if-changed={relative}"); + add(&mut id, relative.as_bytes()); + add(&mut id, &[0]); + add_source(&mut id, &std::fs::read(root.join(relative)).expect("read pipeline layout input")); + add(&mut id, &[0]); + } + for name in ["TARGET", "PROFILE", "CARGO_ENCODED_RUSTFLAGS", "OPT_LEVEL", "DEBUG"] { + add(&mut id, name.as_bytes()); + add(&mut id, std::env::var(name).unwrap_or_default().as_bytes()); + add(&mut id, &[0]); + } + let rustc = std::process::Command::new(std::env::var_os("RUSTC").expect("rustc")) + .arg("-vV").output().expect("read compiler identity"); + assert!(rustc.status.success()); + add_source(&mut id, &rustc.stdout); + let mut features: Vec<_> = std::env::vars().filter(|(name,_)| name.starts_with("CARGO_FEATURE_")).collect(); + features.sort(); + for (name, value) in features { add(&mut id, name.as_bytes()); add(&mut id, value.as_bytes()); add(&mut id, &[0]); } + id +} + fn main() { // xcl.exe without high-entropy ASLR: the title's memory then lies under 2^40, which a // retail title's BVH builder requires of its GPU addresses (#585, PR #631) @@ -59,6 +94,7 @@ fn main() { _ => {} } let root = Path::new(env!("CARGO_MANIFEST_DIR")); + println!("cargo:rustc-env=XCL_NATIVE_PREPARATION_ID={:016x}", preparation_source_id(root)); let mut h = 0xcbf2_9ce4_8422_2325u64; add(&mut h, b"xcl-translator-source-v1\0"); add(&mut h, TRANSLATION_GLUE_REVISION.as_bytes()); diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 379bd8518f..ba07463d81 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -691,7 +691,7 @@ fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &st h } -fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { +pub(crate) fn cache_key(src: &str, entry: &str, profile: &str) -> u64 { cache_key_for_toolchain(src, entry, profile, toolchain_identity()) } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 1af5dcc2ad..6335faa475 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -199,6 +199,8 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa /// each at every start. Keyed by two hashes and the length of the bytes, the stage and the /// translation parameters; translator sources and the DXC toolchain identify compatible builds. /// `XCL_TRANSLATED_CACHE=0` turns it off. +pub(crate) fn translation_cache_identity() -> u64 { translated::identity() } + mod translated { use super::{Compiled, Stage}; use std::path::{Path, PathBuf}; @@ -266,7 +268,7 @@ mod translated { /// Translation semantics and the DXC DLLs, independent of link metadata and build profile. /// Zero means the disk cache is disabled. - fn identity() -> u64 { + pub(super) fn identity() -> u64 { static I: OnceLock = OnceLock::new(); *I.get_or_init(|| { if std::env::var("XCL_TRANSLATED_CACHE").is_ok_and(|v| v == "0") { diff --git a/crates/xcl/src/hle/d3d12x/gfx_records.rs b/crates/xcl/src/hle/d3d12x/gfx_records.rs index 99dada1082..8221bf7ad3 100644 --- a/crates/xcl/src/hle/d3d12x/gfx_records.rs +++ b/crates/xcl/src/hle/d3d12x/gfx_records.rs @@ -546,8 +546,11 @@ pub(crate) fn read_history_payloads(path: &Path) -> Result>, String> read_complete(path, true, |bytes, _| bytes.to_vec()) } -pub(crate) fn read_job(path: &Path) -> Result, String> { - read_complete(path, false, |_, entry| entry) +pub(crate) fn read_job(path: &Path) -> Result, String> { + read_complete(path, false, |bytes, entry| { + let recipe = if matches!(entry, Entry::Shader(_, _)) { 0 } else { crate::gpu::shader::fnv64(bytes) }; + (recipe, entry) + }) } /// What became of an entry handed to `Writer::add`. diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index bdd52d4ea3..725f5c593e 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -43,6 +43,7 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { std::env::remove_var("XCL_PREPARATION_MENU"); let root = &boot.game_root; let corpus = root.join(".xcl/pso-corpus").try_exists().map_err(|e| e.to_string())?; + if !corpus && std::env::var("XCL_PREPARE").is_ok_and(|v| v.trim() == "0") { return Ok(()); } let history = crate::hle::d3d12x::gfx_records::path().try_exists().map_err(|e| e.to_string())?; if !corpus && !history && (boot.config.graphics.eq_ignore_ascii_case("null") || (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir())) { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4a44ad1f46..c1c0aceb99 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4545,7 +4545,7 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } - fn enabled() -> bool { + pub(crate) fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) } @@ -5344,10 +5344,16 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else { finish_pso(this, f, c as *const _ as *const c_void, riid, ppv) }, ); let hr = build.hr; + if build.reused { + if let Some(blob) = cached.as_ref() { + crate::shaders::warm_replay::accepted(disk.as_deref(), blob); + } + } if build.cache_eligible { keep_graphics_blob(gkey, *ppv, bytes); if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { driver_cache::keep(p, &b, build.in_driver); + crate::shaders::warm_replay::accepted(Some(p), &b); } } else if build.reused && from_disk { driver_cache::note(true, None); @@ -6322,6 +6328,10 @@ fn two_pass_driver_id(device: *mut c_void) -> Option { }) } +pub(crate) fn preparation_driver_identity(dev: &ID3D12Device) -> Option { + two_pass_driver_id(dev.as_raw()) +} + /// Create the mesh pipeline (RS and shaders already in the stream) and its compute pass. #[allow(clippy::too_many_arguments)] unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, ps_samplers: &[crate::gpu::recomp::pso::StaticSampler], kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { @@ -6392,6 +6402,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: }; if let Some(key) = gkey { if greused { + if let Some(blob) = gcached.as_ref() { + crate::shaders::warm_replay::accepted(gdisk.as_deref(), blob); + } if let Some(blob) = gcached.filter(|_| gfrom_disk) { remember_graphics_blob(key, blob); driver_cache::note(true, None); @@ -6403,6 +6416,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: if let Some(blob) = blob { if let Some(path) = gdisk.as_deref().filter(|_| slow) { driver_cache::keep(path, &blob, gin_driver); + crate::shaders::warm_replay::accepted(Some(path), &blob); } remember_graphics_blob(key, blob); } @@ -6447,10 +6461,16 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: cin_driver += took; } let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; + if creused { + if let Some(blob) = ccached.as_ref() { + crate::shaders::warm_replay::accepted(cdisk.as_deref(), blob); + } + } if hc >= 0 && !creused && !compute.is_null() { keep_compute_blob(ckey, compute, tp.cs.len()); if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { driver_cache::keep(p, &b, cin_driver); + crate::shaders::warm_replay::accepted(Some(p), &b); } } else if creused && cfrom_disk { driver_cache::note(true, None); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 24bdc4d312..89609ecaf9 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -14,6 +14,24 @@ use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; use crate::hle::d3d12x::gfx_records; pub(crate) mod pso_corpus; +mod warm_blobs; +mod warm_pack; +pub(crate) mod warm_replay; + +pub(crate) fn warm_settings_key() -> u64 { + let mut settings: Vec<_> = std::env::vars_os().filter(|(k,_)| { + let k = k.to_string_lossy(); + k.starts_with("XCL_") && !matches!(k.as_ref(), "XCL_PRECOMPILE_PARENT" | "XCL_PREPARATION_PARENT" | "XCL_PREPARATION_MENU" | + "XCL_PRECOMPILE_SLICE" | "XCL_PRECOMPILE_COVERAGE_MAP" | "XCL_PRECOMPILE_COVERAGE_DIR" | + "XCL_PIPELINE_THREADS" | "XCL_PREPARE_WORKERS" | "XCL_PREPARE" | "XCL_PREPARE_GRAPHICS" | "XCL_PREPARE_ALL_LIVE" | "XCL_RUN_SECONDS" | + "XCL_PRESS_AT" | "XCL_PRESS_AFTER_POLL" | "XCL_ACTIVITY" | "XCL_SKIP_BINK" | + "XCL_FRAME_DUMP" | "XCL_FRAME_DUMP_FULL" | "XCL_GPU_CULPRIT" | "XCL_DSTORAGE_LATE_PAGE_MS" | "XCL_DISPATCH_TILE_AXIS") + }).collect(); + settings.sort(); + warm_blobs::digest(&settings) +} + + /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). @@ -1284,6 +1302,8 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, signatures: Mutex), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, + warm_blobs: Option, + verified: AtomicUsize, made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, @@ -1538,6 +1558,8 @@ impl Pipelines { Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), + warm_blobs: None, + verified: AtomicUsize::new(0), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), @@ -1617,6 +1639,7 @@ impl Pipelines { path_override: Option, required: bool) -> Result<(), String> { use windows::Win32::Graphics::Direct3D12::*; let key: (bool, Vec) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); + let layout = self.warm_blobs.as_ref().map(|_| warm_blobs::digest(&key)); let rs = { let mut g = self.signatures.lock().unwrap(); match g.get(&key) { @@ -1654,6 +1677,14 @@ impl Pipelines { driver_cache::path_for(dxil, desc.Flags.0, chained) }); let mut cached = path.as_deref().and_then(driver_cache::load); + let receipt = self.warm_blobs.as_ref().zip(layout).zip(path.as_deref()); + if let (Some(((book, layout), path)), Some(blob)) = (receipt, cached.as_ref()) { + if book.contains(&warm_blobs::stamp(path, layout, blob)) { + self.verified.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return Ok(()); + } + } let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1715,6 +1746,9 @@ impl Pipelines { return Err(format!("The cached compute pipeline was rejected and {} bytes of DXIL exceed the limit", dxil.len())); } let r = if let Some(pso) = from_cache { + if let (Some(((book, layout), path)), Some(blob)) = (receipt, cached.as_ref()) { + book.record(warm_blobs::stamp(path, layout, blob)); + } self.reused.fetch_add(1, Ordering::Relaxed); Ok(pso) } else { @@ -1725,7 +1759,10 @@ impl Pipelines { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); let len = unsafe { blob.GetBufferSize() }; if !bytes.is_null() && len != 0 { - driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }); + let bytes = unsafe { std::slice::from_raw_parts(bytes, len) }; + if driver_cache::write(path, bytes) { + if let Some(((book, layout), _)) = receipt { book.record(warm_blobs::stamp(path, layout, bytes)); } + } } } } @@ -1933,6 +1970,7 @@ fn prepare_title_inputs(root: &Path, progress: &LaunchPreparation, corpus: Optio precompile(input, usize::MAX, windows, None, None, true, None, None, std::time::Instant::now(), Some(progress), coverage.as_ref())?; } if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + if std::env::var("XCL_PREPARE_GRAPHICS").is_ok_and(|v| v.trim() == "0") { return Ok(()); } graphics_in_workers(&inputs, windows, workers, progress, corpus.and_then(|c| c.graphics_path())) } @@ -2401,7 +2439,8 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { Ok(entries) => entries, Err(e) => { eprintln!("xcl shaders: {}: {e}", job.display()); return 2; } }; - for entry in entries { + let mut recipe_keys = Vec::new(); + for (key, entry) in entries { match entry { gfx_records::Entry::Shader(key, code) => { if real::shader_key(&code) != key || shaders.get(&key).is_some_and(|prior| prior != &code) { @@ -2410,7 +2449,7 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { } shaders.insert(key, code); } - entry => records.extend(GraphicsHistoryRecord::from_entry(entry)), + entry => if let Some(record) = GraphicsHistoryRecord::from_entry(entry) { records.push(record); recipe_keys.push(key); }, } } let n = records.len(); @@ -2424,11 +2463,19 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { crate::gpu::uma::leave_out(); recomp::pso::set_title_windows(windows); recomp::dxc::set_memory_reserve(2); - let device = match Pipelines::for_adapter("auto") { - Ok(p) => real::prepare_device(p.dev), + let (device, book) = match Pipelines::for_adapter("auto") { + Ok(p) => { + let cache = recomp::dxc::cache_dir(); + let book = warm_replay::native_key(&p.dev).and_then(|key| { + let known = warm_replay::driver_files(&cache.join("driver")).unwrap_or_default(); + warm_replay::Index::open(&cache, &known, warm_blobs::digest(&(key, &recipe_keys)), windows) + }); + (real::prepare_device(p.dev), book) + }, Err(e) => { eprintln!("xcl shaders: no pipeline device: {e}"); return 2; } }; let threads = corpus_threads(requested, 1).min(ready.len()); + let verified = AtomicUsize::new(0); let (next, made, failed) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(missing)); let t0 = std::time::Instant::now(); std::thread::scope(|s| { @@ -2439,7 +2486,8 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { let r = &records[index]; let code = |key| shaders.get(&key).map(Vec::as_slice); // (a pipeline that panics fails; the others are built) - let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { + let key = recipe_keys[index]; + let run = || std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match r { GraphicsHistoryRecord::Legacy(record) => { let desc = record.desc(record.shaders.map(code)); unsafe { real::prepare_graphics(device, &desc, record.depth_bounds) } @@ -2448,6 +2496,16 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { unsafe { real::replay_mesh_record(device, record, record.shaders.map(code)).is_ok() } } })).unwrap_or(false); + let ok = if let Some(book) = &book { + if book.can_defer(key) { + verified.fetch_add(1, Ordering::Relaxed); + true + } else { + let (ok, files) = warm_replay::capture(run); + if ok { book.add(key, files, matches!(r, GraphicsHistoryRecord::Mesh(_))); } + ok + } + } else { run() }; if ok { let d = made.fetch_add(1, Ordering::Relaxed) + 1; eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); @@ -2458,6 +2516,8 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { }); } }); + if let Some(book) = book { book.save(); } + eprintln!("previously verified native graphics recipes: {}", verified.into_inner()); let (hits, _, stored) = real::driver_cache_stats(); let failed = failed.into_inner(); eprintln!("graphics pipelines: {} made, {failed} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner()); @@ -2498,6 +2558,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if let Some(threads) = pipeline_threads { p.most = threads.max(1); } + if mandatory { p.warm_blobs = warm_blobs::Verified::for_device(&p.dev); } if mandatory && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { p.max_dxil = 0; } @@ -2535,6 +2596,21 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let startup_device = pipelines.filter(|_| startup.is_some()); let graphics_split = split.unwrap_or_else(|| startup_device.map_or_else(recomp::runner::graphics_wave32, |p| recomp::pso::graphics_wave32_for_device(&p.dev))); let split = split.unwrap_or_else(|| startup_device.map_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w), |p| recomp::pso::wave32_only_for_device(&p.dev))); + // A graphics-stage proof skips translation only. Compute records still pass through + // coverage and native preparation, including a changed or newly staged compute job. + let pack_proof = startup.and_then(|owner| { + let Input::Pack { data, .. } = input else { return None }; + if n != input.len() || only.is_some() || selected.is_some() || slice.is_some() { return None; } + let extra_device; + let device = match pipelines { + Some(p) => &p.dev, + None => { + extra_device = Pipelines::for_adapter(&owner.adapter).ok()?; + &extra_device.dev + } + }; + warm_pack::Stages::open(warm_replay::native_key(device)?, data, n, windows, split, graphics_split) + }); println!( "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), @@ -2559,6 +2635,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if let Some(p) = startup { p.done.fetch_add(1, Ordering::Relaxed); } if d % every == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } }; + if pack_proof.as_ref().is_some_and(|p| p.covered(i)) { + record_done(); + continue; + } let (name, blob) = input.get(i); let Some(blob) = blob else { if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); } @@ -2629,6 +2709,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on record_done(); continue; } + let mut stage_outputs = Vec::new(); for f in &sh.fssm { let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; let jobs: Vec<(&str, Option)> = match &mode { @@ -2663,9 +2744,14 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } }; for (profile, src) in &jobs { - match recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile) { - Ok((_, true)) => cached.fetch_add(1, Ordering::Relaxed), - Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), + let src = src.as_deref().unwrap_or(&t.hlsl); + match recomp::dxc::compile_cached(src, "main", profile) { + Ok((bytes, hit)) => { + if pack_proof.is_some() { + stage_outputs.push((recomp::dxc::cache_key(src, "main", profile), bytes.len() as u64)); + } + if hit { &cached } else { &compiled }.fetch_add(1, Ordering::Relaxed) + } Err(e) => { let mut g = errors.lock().unwrap(); if g.len() < 10 { @@ -2677,6 +2763,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } } } + if let Some(proof) = &pack_proof { proof.record(i, stage_outputs); } record_done(); }); } @@ -2709,6 +2796,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on make_pipelines(p, pipeline_jobs.into_inner().unwrap()); } println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); + if let Some(book) = &p.warm_blobs { + book.save(); + println!("previously verified native compute pipelines {}", p.verified.load(Ordering::Relaxed)); + } println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); println!("pipelines left to another process that was building them {}", p.elsewhere.load(Ordering::Relaxed)); let split_programs = p.split_programs.load(Ordering::Relaxed); @@ -2734,6 +2825,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on return Err(format!("Shader preparation stopped: {failed} record failures, {refused} refused pipelines, {capped} over the size cap. {cause}")); } } + if let Some(proof) = pack_proof { proof.save(); } Ok(()) } diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index bb361f2c35..bf74215fc4 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -91,6 +91,7 @@ impl Corpus { } if self.compute.is_empty() { return progress.check_corpus_complete(); } let mut pipelines = Pipelines::for_adapter(&progress.adapter)?; + pipelines.warm_blobs = super::warm_blobs::Verified::for_device(&pipelines.dev); pipelines.max_dxil = 0; pipelines.most = parallel; let next = AtomicUsize::new(0); @@ -118,6 +119,10 @@ impl Corpus { }); } }); + if let Some(book) = &pipelines.warm_blobs { + book.save(); + eprintln!("previously verified native compute pipelines: {}", pipelines.verified.load(Ordering::Relaxed)); + } if let Some(e) = error.into_inner().unwrap() { return Err(e); } progress.check_corpus_complete() } diff --git a/crates/xcl/src/shaders/warm_blobs.rs b/crates/xcl/src/shaders/warm_blobs.rs new file mode 100644 index 0000000000..99acc05292 --- /dev/null +++ b/crates/xcl/src/shaders/warm_blobs.rs @@ -0,0 +1,93 @@ +//! Successful temporary-device validations. Live PSO creation on the render device +//! still supplies the driver blob and retries normally if the driver refuses it. +use std::collections::{hash_map::DefaultHasher, HashSet}; +use std::hash::{Hash, Hasher}; +use std::path::{Path, PathBuf}; +use std::sync::{atomic::{AtomicBool, Ordering}, Mutex}; +use windows::Win32::Graphics::Direct3D12::ID3D12Device; + +pub(super) fn digest(value: &impl Hash) -> u64 { + let mut h = DefaultHasher::new(); + value.hash(&mut h); + h.finish() +} + +pub(super) fn stamp(path: &Path, layout: u64, blob: &[u8]) -> [u64; 3] { + [digest(&path.file_name()), layout, digest(&blob)] +} + +pub(super) struct Verified { + path: PathBuf, + keys: Mutex>, + dirty: AtomicBool, +} + +impl Verified { + pub(super) fn for_device(dev: &ID3D12Device) -> Option { + let key = super::warm_replay::native_key(dev)?; + let slice = std::env::var("XCL_PRECOMPILE_SLICE").unwrap_or_default(); + let key = digest(&(key, slice)); + Some(Self::open(crate::gpu::recomp::dxc::cache_dir().join(format!("verified-compute-v1-{key:016x}.bin")))) + } + + fn open(path: PathBuf) -> Self { + let mut keys = HashSet::new(); + if let Ok(bytes) = std::fs::read(&path) { + if let Some((checksum, body)) = bytes.split_at_checked(8) { + if body.len() % 24 == 0 && checksum == digest(&body).to_le_bytes() { + for row in body.chunks_exact(24) { + keys.insert(std::array::from_fn(|i| u64::from_le_bytes(row[i*8..i*8+8].try_into().unwrap()))); + } + } + } + } + Self { path, keys: Mutex::new(keys), dirty: AtomicBool::new(false) } + } + + pub(super) fn contains(&self, stamp: &[u64; 3]) -> bool { + self.keys.lock().unwrap().contains(stamp) + } + + pub(super) fn record(&self, stamp: [u64; 3]) { + if self.keys.lock().unwrap().insert(stamp) { self.dirty.store(true, Ordering::Relaxed); } + } + + pub(super) fn save(&self) { + if !self.dirty.load(Ordering::Relaxed) { return; } + let keys = self.keys.lock().unwrap(); + let mut data = Vec::with_capacity(8 + 24 * keys.len()); + data.extend_from_slice(&[0; 8]); + for row in keys.iter() { + for v in row { data.extend_from_slice(&v.to_le_bytes()); } + } + let sum = digest(&&data[8..]).to_le_bytes(); + data[..8].copy_from_slice(&sum); + if !crate::hle::d3d12x::real::driver_cache::write(&self.path, &data) { + crate::xlog_warn!("Shader preparation: could not save verified compute blob list"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn warm_receipt_matches_only_the_validated_blob_and_layout() { + let path = std::env::temp_dir().join(format!("xcl-warm-receipt-{}.bin", std::process::id())); + let file = Path::new("123.chain.pso"); + let key = stamp(file, 1, &[3, 4]); + let book = Verified::open(path.clone()); + book.record(key); + book.save(); + let book = Verified::open(path.clone()); + assert!(book.contains(&key)); + assert!(!book.contains(&stamp(file, 2, &[3, 4]))); + assert!(!book.contains(&stamp(file, 1, &[3, 5]))); + assert!(!book.contains(&stamp(Path::new("123.pso"), 1, &[3, 4]))); + let mut contents = std::fs::read(&path).unwrap(); + contents[8] ^= 1; + std::fs::write(&path, contents).unwrap(); + assert!(!Verified::open(path.clone()).contains(&key)); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/xcl/src/shaders/warm_pack.rs b/crates/xcl/src/shaders/warm_pack.rs new file mode 100644 index 0000000000..ad9cddc216 --- /dev/null +++ b/crates/xcl/src/shaders/warm_pack.rs @@ -0,0 +1,101 @@ +//! Skip re-emitting graphics stages when their successful pack pass still has all its DXIL. +use super::{warm_blobs::digest, warm_replay::{read_receipt, write_receipt}}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; +use std::os::windows::fs::MetadataExt; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +type Stamp = [u64; 3]; + +#[derive(Default, Serialize, Deserialize)] +struct Receipt { + indices: BTreeSet, + outputs: BTreeMap, +} + +fn inventory(cache: &Path) -> Option> { + let mut outputs = BTreeMap::new(); + for entry in std::fs::read_dir(cache).ok()? { + let entry = entry.ok()?; + let path = entry.path(); + if path.extension().is_none_or(|ext| ext != "dxil") { continue; } + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { continue }; + if stem.len() != 16 { continue; } + let Ok(key) = u64::from_str_radix(stem, 16) else { continue }; + let m = entry.metadata().ok()?; + if m.is_file() && m.file_attributes() & 0x400 == 0 { + outputs.insert(key, [m.len(), m.creation_time(), m.last_write_time()]); + } + } + Some(outputs) +} + +impl Receipt { + fn valid(&self, count: usize, files: &BTreeMap) -> bool { + !self.indices.is_empty() && !self.outputs.is_empty() && self.indices.last().is_some_and(|i| *i < count) + && self.outputs.iter().all(|(key, stamp)| files.get(key) == Some(stamp)) + } +} + +pub(super) struct Stages { + cache: PathBuf, + path: PathBuf, + prior: Option, + fresh: Mutex)>>, +} + +impl Stages { + pub(super) fn open(native: u64, data: &[u8], count: usize, windows: u32, split: bool, graphics_split: bool) -> Option { + let cache = crate::gpu::recomp::dxc::cache_dir(); + let key = digest(&(native, digest(&data), count, windows, split, graphics_split)); + let path = cache.join(format!("pack-stages-v1-{key:016x}.bin")); + let prior = read_receipt::(&path).filter(|r| inventory(&cache).is_some_and(|files| r.valid(count, &files))); + if let Some(r) = &prior { + crate::xlog_info!("Shader preparation: reusing verified DXIL for {} graphics records in the pack", r.indices.len()); + } + Some(Self { cache, path, prior, fresh: Mutex::default() }) + } + + pub(super) fn covered(&self, i: usize) -> bool { + self.prior.as_ref().is_some_and(|r| r.indices.contains(&i)) + } + + pub(super) fn record(&self, index: usize, outputs: Vec<(u64, u64)>) { + if !outputs.is_empty() { self.fresh.lock().unwrap().push((index, outputs)); } + } + + pub(super) fn save(self) { + let newly = self.fresh.into_inner().unwrap(); + if newly.is_empty() { return; } + let Some(files) = inventory(&self.cache) else { return }; + let mut receipt = self.prior.unwrap_or_default(); + if receipt.outputs.iter().any(|(k, s)| files.get(k) != Some(s)) { return; } + for (index, stages) in newly { + for (key, len) in stages { + let Some(stamp) = files.get(&key).filter(|s| len != 0 && s[0] == len) else { return }; + receipt.outputs.insert(key, *stamp); + } + receipt.indices.insert(index); + } + write_receipt(&self.path, &receipt); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn graphics_pack_proof_requires_every_output_and_valid_indices() { + let receipt = Receipt { indices: BTreeSet::from([0, 3]), outputs: BTreeMap::from([(1, [30, 4, 5]), (9, [60, 7, 8])]) }; + let mut files = receipt.outputs.clone(); + files.insert(11, [40, 2, 3]); + assert!(receipt.valid(4, &files)); + assert!(!receipt.valid(3, &files)); + files.get_mut(&9).unwrap()[2] += 1; + assert!(!receipt.valid(4, &files)); + files.remove(&9); + assert!(!receipt.valid(4, &files)); + } +} diff --git a/crates/xcl/src/shaders/warm_replay.rs b/crates/xcl/src/shaders/warm_replay.rs new file mode 100644 index 0000000000..ccda319b9b --- /dev/null +++ b/crates/xcl/src/shaders/warm_replay.rs @@ -0,0 +1,144 @@ +//! A recipe can be left on disk only after a successful replay identified every +//! native blob it used. The render device still creates the live PSO on first use. +use serde::{Deserialize, Serialize}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::os::windows::fs::MetadataExt; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +/// Interrupted writes or a damaged index fall back to ordinary preparation. +pub(crate) fn read_receipt(path: &Path) -> Option { + let bytes = std::fs::read(path).ok()?; + let (checksum, payload) = bytes.split_at_checked(8)?; + if checksum != crate::gpu::shader::fnv64(payload).to_le_bytes() { return None; } + serde_json::from_slice(payload).ok() +} + +pub(crate) fn write_receipt(path: &Path, receipt: &T) -> bool { + let mut bytes = vec![0; 8]; + if serde_json::to_writer(&mut bytes, receipt).is_err() { return false; } + let checksum = crate::gpu::shader::fnv64(&bytes[8..]).to_le_bytes(); + bytes[..8].copy_from_slice(&checksum); + crate::hle::d3d12x::real::driver_cache::write(path, &bytes) +} + +pub(crate) type Stamp = [u64; 3]; +pub(crate) type Inventory = HashMap; + +fn stamp(m: &std::fs::Metadata) -> Option { + (m.is_file() && m.len() != 0 && m.file_attributes() & 0x400 == 0).then(|| [m.len(), m.creation_time(), m.last_write_time()]) +} + +pub(crate) fn driver_files(dir: &Path) -> Option { + let mut files = Inventory::new(); + for e in std::fs::read_dir(dir).ok()? { + let e = e.ok()?; + let m = e.metadata().ok()?; + if m.file_attributes() & 0x400 != 0 { continue; } + let Some(stamp) = stamp(&m) else { continue }; + if let Ok(name) = e.file_name().into_string() { + if name.ends_with(".pso") { files.insert(name, stamp); } + } + } + Some(files) +} +#[derive(Clone, Serialize, Deserialize)] +pub(super) struct File { name: String, stamp: Stamp } +type Recipes = HashMap>; + +thread_local! { static CAPTURE: RefCell>> = const { RefCell::new(None) }; } + +pub(super) fn capture(f: impl FnOnce() -> bool) -> (bool, Vec) { + CAPTURE.with(|slot| { *slot.borrow_mut() = Some(Vec::new()); }); + let success = f(); + let files = CAPTURE.with(|slot| slot.take().unwrap_or_default()); + (success, files) +} + +/// Record only bytes accepted by the native driver that still occupy this cache file. +pub(crate) fn accepted(path: Option<&Path>, bytes: &[u8]) { + CAPTURE.with(|slot| { + let mut slot = slot.borrow_mut(); + let Some(files) = slot.as_mut() else { return }; + let verified = || { + let path = path?; + let before = stamp(&path.metadata().ok()?)?; + if before[0] != bytes.len() as u64 || std::fs::read(path).ok()?.as_slice() != bytes { return None; } + if stamp(&path.metadata().ok()?)? != before { return None; } + Some(File { name: path.file_name()?.to_str()?.to_owned(), stamp: before }) + }; + if let Some(file) = verified() { files.push(file); } + }); +} + +pub(super) struct Index { + path: PathBuf, + entries: Recipes, + new: Mutex, +} + +impl Index { + pub(super) fn open(dir: &Path, known: &Inventory, key: u64, windows: u32) -> Option { + let path = dir.join(format!("warm-recipes-v2-{key:016x}-{windows:02x}.bin")); + let mut entries: Recipes = read_receipt(&path).unwrap_or_default(); + entries.retain(|_, files| !files.is_empty() && files.iter().all(|f| known.get(&f.name) == Some(&f.stamp))); + Some(Self { path, entries, new: Default::default() }) + } + pub(super) fn can_defer(&self, hash: u64) -> bool { self.entries.contains_key(&hash) } + pub(super) fn add(&self, hash: u64, files: Vec, mesh: bool) { + let complete = if mesh { + files.len() == 2 && files.iter().any(|f| f.name.starts_with("tp-ms-")) + && files.iter().any(|f| f.name.starts_with("tp-cs-")) + } else { + files.len() == 1 && files[0].name.starts_with("gfx-") + }; + if complete { self.new.lock().unwrap().insert(hash, files); } + } + pub(super) fn save(mut self) { + let new = self.new.into_inner().unwrap(); + if new.is_empty() { return; } + self.entries.extend(new); + if !write_receipt(&self.path, &self.entries) { + crate::xlog_warn!("PSO preparation: could not save the verified recipe index"); + } + } +} + +pub(super) fn native_key(dev: &windows::Win32::Graphics::Direct3D12::ID3D12Device) -> Option { + let gpu = crate::hle::d3d12x::real::preparation_driver_identity(dev)?; + let translation = crate::gpu::recomp::pso::translation_cache_identity(); + if translation == 0 || !crate::hle::d3d12x::real::driver_cache::enabled() { return None; } + let cache = std::path::absolute(crate::gpu::recomp::dxc::cache_dir()).ok()?; + Some(super::warm_blobs::digest(&(env!("XCL_NATIVE_PREPARATION_ID"), gpu, translation, cache, super::warm_settings_key()))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verified_mesh_needs_both_unchanged_driver_files() { + let dir = std::env::temp_dir().join(format!("xcl-warm-mesh-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let graphics = dir.join("tp-ms-test.pso"); + let compute = dir.join("tp-cs-test.pso"); + std::fs::write(&graphics, b"graphics").unwrap(); + std::fs::write(&compute, b"compute").unwrap(); + let open = || Index::open(&dir, &driver_files(&dir).unwrap(), 1, 4).unwrap(); + let capture_passes = |compute_bytes: &[u8]| capture(|| { + accepted(Some(&graphics), b"graphics"); + accepted(Some(&compute), compute_bytes); + true + }).1; + let book = open(); + book.add(1, capture_passes(b"wrong"), true); + book.add(2, capture_passes(b"compute"), true); + book.save(); + assert!(!open().can_defer(1)); + assert!(open().can_defer(2)); + std::fs::remove_file(&compute).unwrap(); + assert!(!open().can_defer(2)); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 770dbbc5f1..b0a00f5c96 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -60,9 +60,9 @@ fn incomplete_discovered_corpus_blocks_headless_title_entry() { let settings = data.join("XCL.TestTitle"); std::fs::create_dir_all(&settings).unwrap(); std::fs::write(settings.join("xcl.toml"), "graphics='null'\npresent='off'\n").unwrap(); - let launch = || Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) - .env("XCL_PREPARE", "0").env("XCL_PREPARE_GRAPHICS", "0").output().unwrap(); - let out = launch(); + let launch = |prepare| Command::new(xcl).arg("run").arg(&game).env("XCL_DATA_ROOT", &data) + .env("XCL_PREPARE", prepare).output().unwrap(); + let out = launch("0"); assert!(!out.status.success(), "An incomplete corpus released the guest"); let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); assert!(log.contains("Incomplete pipeline corpus"), "{log}"); @@ -70,7 +70,10 @@ fn incomplete_discovered_corpus_blocks_headless_title_entry() { std::fs::remove_dir(game.join(".xcl/pso-corpus")).unwrap(); std::fs::create_dir_all(settings.join("cache")).unwrap(); std::fs::write(settings.join("cache/used-graphics-pipelines.bin"), b"bad history").unwrap(); - assert!(!launch().status.success()); + let _ = launch("0"); + let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); + assert!(!log.contains("unrecognized graphics job header"), "Disabled optional preparation read local history"); + assert!(!launch("1").status.success()); let log = std::fs::read_to_string(settings.join("logs/xcl.log")).unwrap(); assert!(log.contains("unrecognized graphics job header"), "{log}"); assert!(!log.contains("game entry point returned"), "{log}"); From 0d97736044fa43becd9bcefe53f7063528e157a8 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:55:44 -0500 Subject: [PATCH 16/22] Shaders: share verification between launch and offline workers Exclude worker scheduling and observation settings from the preparation identity. Normalize Windows environment variable names, and report how many staged graphics recipes reused their existing native verification. --- crates/xcl/src/shaders.rs | 38 +++++++++++++++++++++------- crates/xcl/src/shaders/pso_corpus.rs | 4 +++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 89609ecaf9..c9cdeed753 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -18,20 +18,40 @@ mod warm_blobs; mod warm_pack; pub(crate) mod warm_replay; -pub(crate) fn warm_settings_key() -> u64 { - let mut settings: Vec<_> = std::env::vars_os().filter(|(k,_)| { - let k = k.to_string_lossy(); - k.starts_with("XCL_") && !matches!(k.as_ref(), "XCL_PRECOMPILE_PARENT" | "XCL_PREPARATION_PARENT" | "XCL_PREPARATION_MENU" | +pub(crate) fn warm_settings_key() -> u64 { warm_settings(std::env::vars_os()) } + +// Driver and cache directory are keyed separately. Worker PIDs, title paths, scheduling +// and observation settings do not affect the recipe the driver validates. +fn warm_settings(vars: impl IntoIterator) -> u64 { + let mut settings = Vec::new(); + for (name, value) in vars { + let name = name.to_string_lossy().to_ascii_uppercase(); + if !name.starts_with("XCL_") { continue; } + if matches!(name.as_str(), + "XCL_HOST" | "XCL_DATA_ROOT" | "XCL_ADAPTER" | "XCL_DXIL_CACHE" | "XCL_UMA_MB" | + "XCL_PRECOMPILE_PARENT" | "XCL_PREPARATION_PARENT" | "XCL_PREPARATION_MENU" | "XCL_PRECOMPILE_SLICE" | "XCL_PRECOMPILE_COVERAGE_MAP" | "XCL_PRECOMPILE_COVERAGE_DIR" | - "XCL_PIPELINE_THREADS" | "XCL_PREPARE_WORKERS" | "XCL_PREPARE" | "XCL_PREPARE_GRAPHICS" | "XCL_PREPARE_ALL_LIVE" | "XCL_RUN_SECONDS" | - "XCL_PRESS_AT" | "XCL_PRESS_AFTER_POLL" | "XCL_ACTIVITY" | "XCL_SKIP_BINK" | - "XCL_FRAME_DUMP" | "XCL_FRAME_DUMP_FULL" | "XCL_GPU_CULPRIT" | "XCL_DSTORAGE_LATE_PAGE_MS" | "XCL_DISPATCH_TILE_AXIS") - }).collect(); + "XCL_DXC_THREADS" | "XCL_PIPELINE_THREADS" | "XCL_PREPARE_WORKERS" | "XCL_PREPARE" | + "XCL_PREPARE_GRAPHICS" | "XCL_PREPARE_ALL_LIVE" | "XCL_RUN_SECONDS" | "XCL_PRESS_AT" | + "XCL_PRESS_AFTER_POLL" | "XCL_ACTIVITY" | "XCL_SKIP_BINK" | "XCL_FRAME_DUMP" | + "XCL_FRAME_DUMP_FULL" | "XCL_GPU_CULPRIT" | "XCL_DSTORAGE_LATE_PAGE_MS" | "XCL_DISPATCH_TILE_AXIS") { + continue; + } + settings.push((name, value)); + } settings.sort(); warm_blobs::digest(&settings) } - +#[cfg(test)] +#[test] +fn warm_settings_ignore_worker_identity_but_keep_backend_changes() { + let key = |entries: &[(&str, &str)]| warm_settings(entries.iter().map(|(k, v)| ((*k).into(), (*v).into()))); + let offline = key(&[("XCL_DIRECT_DXIL", "1")]); + let worker = key(&[("XCL_PRECOMPILE_PARENT", "812"), ("XCL_DXC_THREADS", "2"), ("xcl_direct_dxil", "1")]); + assert_eq!(offline, worker); + assert_ne!(offline, key(&[("xcl_direct_dxil", "all")])); +} /// `--iface`: how console programs connect to their DXBC signatures (hypothesis checks for /// the VS/PS interface of the recompiler). diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index bf74215fc4..2a1237cbf4 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -156,6 +156,10 @@ fn run_graphics(path: &Path, count: usize, windows: u32, parallel: usize, progre made = made.max(n); if let Err(e) = progress.complete_corpus(made) { break Err(e); } } else { + if let Some(verified) = line.strip_prefix("previously verified native graphics recipes: ") + .and_then(|n| n.parse::().ok()) { + eprintln!("Reused {verified} verified native graphics recipes"); + } if let Some(values) = graphics_summary(&line) { summary = Some(values); } if !line.trim().is_empty() { last = line; } } From b64e48627fce09d2983a1cf420400f244738aebb Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:33:59 -0500 Subject: [PATCH 17/22] Shaders: preserve inactive-stage cache identities on main --- crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index 6f9c86ad1c..187c9885fa 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -221,9 +221,15 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp } } 1..=6 | 24 | 25 => { - if matches!(ty, 1..=5) && payload.iter().all(|&byte| byte == 0) { - h.u32(ty); - h.u64(0); + let state = read_state::(payload)?; + if state.BytecodeLength == 0 { + if ty == 25 { + return None; + } + if matches!(ty, 1..=5) && payload.iter().all(|&byte| byte == 0) { + h.u32(ty); + h.u64(0); + } continue; } let code = payload_shader(payload)?; From 62c6bda8ace4b520bfba669ab4d13ec00ad1abd2 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:50:01 -0500 Subject: [PATCH 18/22] Shaders: prove native pipeline library round trips Add an internal owner for serialized D3D12 pipeline libraries and focused synthetic coverage for compute, graphics, and mesh state streams. The owner retains the input storage because CreatePipelineLibrary does not copy it. A 256-name synthetic library serialized to 47,888 bytes and reopened in 99 microseconds on the test adapter. Assisted-by: Codex (GPT-5) --- crates/xcl/src/shaders.rs | 1 + crates/xcl/src/shaders/pipeline_library.rs | 286 +++++++++++++++++++++ 2 files changed, 287 insertions(+) create mode 100644 crates/xcl/src/shaders/pipeline_library.rs diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index c9cdeed753..9de9625d7a 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -14,6 +14,7 @@ use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; use crate::hle::d3d12x::gfx_records; pub(crate) mod pso_corpus; +mod pipeline_library; mod warm_blobs; mod warm_pack; pub(crate) mod warm_replay; diff --git a/crates/xcl/src/shaders/pipeline_library.rs b/crates/xcl/src/shaders/pipeline_library.rs new file mode 100644 index 0000000000..ef151b7607 --- /dev/null +++ b/crates/xcl/src/shaders/pipeline_library.rs @@ -0,0 +1,286 @@ +//! Native D3D12 pipeline-library ownership and serialization. +//! +//! D3D12 retains the pointer passed to `CreatePipelineLibrary`, so a reopened library must own +//! its serialized bytes for at least as long as the COM object. + +use windows::core::{HSTRING, Interface, Result}; +use windows::Win32::Graphics::Direct3D12::*; + +pub(crate) struct NativeLibrary { + library: ID3D12PipelineLibrary1, + _serialized: Vec, +} + +impl NativeLibrary { + pub(crate) fn supported(device: &ID3D12Device) -> bool { + let mut feature = D3D12_FEATURE_DATA_SHADER_CACHE::default(); + unsafe { + device.CheckFeatureSupport( + D3D12_FEATURE_SHADER_CACHE, + (&mut feature as *mut D3D12_FEATURE_DATA_SHADER_CACHE).cast(), + std::mem::size_of_val(&feature) as u32, + ) + } + .is_ok() + && feature.SupportFlags.0 & D3D12_SHADER_CACHE_SUPPORT_LIBRARY.0 != 0 + } + + pub(crate) fn empty(device: &ID3D12Device) -> Result { + Self::open(device, Vec::new()) + } + + pub(crate) fn open(device: &ID3D12Device, serialized: Vec) -> Result { + let device: ID3D12Device1 = device.cast()?; + let library = unsafe { device.CreatePipelineLibrary::(&serialized)? }; + Ok(Self { library, _serialized: serialized }) + } + + pub(crate) fn store(&self, name: &str, pipeline: &ID3D12PipelineState) -> Result<()> { + unsafe { self.library.StorePipeline(&HSTRING::from(name), pipeline) } + } + + pub(crate) fn load_compute( + &self, + name: &str, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + ) -> Result { + unsafe { self.library.LoadComputePipeline(&HSTRING::from(name), desc) } + } + + pub(crate) fn load_graphics( + &self, + name: &str, + desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + ) -> Result { + unsafe { self.library.LoadGraphicsPipeline(&HSTRING::from(name), desc) } + } + + pub(crate) fn load_stream( + &self, + name: &str, + desc: &D3D12_PIPELINE_STATE_STREAM_DESC, + ) -> Result { + unsafe { self.library.LoadPipeline(&HSTRING::from(name), desc) } + } + + pub(crate) fn serialize(&self) -> Result> { + let mut bytes = vec![0; unsafe { self.library.GetSerializedSize() }]; + unsafe { self.library.Serialize(&mut bytes)? }; + Ok(bytes) + } +} + +#[cfg(test)] +mod tests { + use super::NativeLibrary; + use crate::gpu::recomp; + use crate::shaders::Pipelines; + use std::mem::ManuallyDrop; + use std::time::Instant; + use windows::core::Interface; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Direct3D12::*; + + fn fixture() -> Option<(Pipelines, Vec, ID3D12RootSignature)> { + if let Err(reason) = recomp::dxc::location() { + recomp::runner::skip_test(&format!("no DXC: {reason}")); + return None; + } + let pipelines = match Pipelines::new() { + Ok(pipelines) => pipelines, + Err(reason) => { + recomp::runner::skip_test(&format!("no D3D12 device: {reason}")); + return None; + } + }; + if !NativeLibrary::supported(&pipelines.dev) { + recomp::runner::skip_test("adapter does not support D3D12 pipeline libraries"); + return None; + } + let source = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer output : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { output.Store(0, 42); } +"#; + let dxil = recomp::dxc::compile(source, "main", "cs_6_6", &[]).expect("DXC compile"); + let root = unsafe { pipelines.dev.CreateRootSignature(0, &dxil) }.expect("root signature"); + Some((pipelines, dxil, root)) + } + + fn compute_desc(dxil: &[u8], root: &ID3D12RootSignature) -> D3D12_COMPUTE_PIPELINE_STATE_DESC { + D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root.clone())), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: dxil.as_ptr().cast(), + BytecodeLength: dxil.len(), + }, + ..Default::default() + } + } + + fn drop_desc(desc: D3D12_COMPUTE_PIPELINE_STATE_DESC) { + drop(ManuallyDrop::into_inner(desc.pRootSignature)); + } + + #[test] + fn compute_pipeline_round_trips_through_serialized_library() { + let Some((pipelines, dxil, root)) = fixture() else { return }; + let desc = compute_desc(&dxil, &root); + let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) } + .expect("compute pipeline"); + let library = NativeLibrary::empty(&pipelines.dev).expect("empty pipeline library"); + for n in 1..=256 { + library.store(&format!("compute-{n:04}"), &pso).expect("store pipeline alias"); + } + assert!(library.store("compute-0001", &pso).is_err(), "duplicate names must be rejected"); + + let serialize_at = Instant::now(); + let bytes = library.serialize().expect("serialize pipeline library"); + let serialize_time = serialize_at.elapsed(); + assert!(!bytes.is_empty()); + + let open_at = Instant::now(); + let reopened = NativeLibrary::open(&pipelines.dev, bytes.clone()).expect("reopen pipeline library"); + let open_time = open_at.elapsed(); + let loaded = reopened.load_compute("compute-0001", &desc).expect("load compute pipeline"); + assert!(unsafe { loaded.GetCachedBlob() }.is_ok()); + println!( + "pipeline library: aliases=256 serialized_bytes={} serialize_us={} open_us={}", + bytes.len(), + serialize_time.as_micros(), + open_time.as_micros() + ); + drop_desc(desc); + } + + #[test] + fn truncated_pipeline_library_is_rejected() { + let Some((pipelines, dxil, root)) = fixture() else { return }; + let desc = compute_desc(&dxil, &root); + let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) } + .expect("compute pipeline"); + let library = NativeLibrary::empty(&pipelines.dev).expect("empty pipeline library"); + library.store("compute-0001", &pso).expect("store pipeline"); + let mut bytes = library.serialize().expect("serialize pipeline library"); + bytes.truncate(bytes.len() / 2); + assert!(NativeLibrary::open(&pipelines.dev, bytes).is_err()); + drop_desc(desc); + } + + #[test] + fn graphics_pipeline_round_trips_through_serialized_library() { + let Some((pipelines, _, _)) = fixture() else { return }; + let source = r#" +#define RS "" +struct V { float4 p : SV_Position; }; +[RootSignature(RS)] V vs(uint id : SV_VertexID) { + V v; v.p = float4(id == 1 ? 1.0 : -1.0, id == 2 ? 1.0 : -1.0, 0.0, 1.0); return v; +} +[RootSignature(RS)] float4 ps() : SV_Target { return float4(1, 0, 1, 1); } +"#; + let vs = recomp::dxc::compile(source, "vs", "vs_6_6", &[]).expect("compile VS"); + let ps = recomp::dxc::compile(source, "ps", "ps_6_6", &[]).expect("compile PS"); + let root = unsafe { pipelines.dev.CreateRootSignature(0, &vs) }.expect("graphics root signature"); + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root)), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr().cast(), BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr().cast(), BytecodeLength: ps.len() }, + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso = unsafe { pipelines.dev.CreateGraphicsPipelineState::(&desc) } + .expect("graphics pipeline"); + let library = NativeLibrary::empty(&pipelines.dev).expect("empty pipeline library"); + library.store("graphics-0001", &pso).expect("store graphics pipeline"); + let bytes = library.serialize().expect("serialize graphics library"); + let reopened = NativeLibrary::open(&pipelines.dev, bytes).expect("reopen graphics library"); + reopened.load_graphics("graphics-0001", &desc).expect("load graphics pipeline"); + drop(ManuallyDrop::into_inner(desc.pRootSignature)); + } + + #[repr(C, align(8))] + struct Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + value: T, + } + + #[repr(C)] + struct MeshStream { + root: Sub<*mut std::ffi::c_void>, + mesh: Sub, + topology: Sub, + } + + #[test] + fn mesh_pipeline_round_trips_through_serialized_library() { + let Some((pipelines, _, _)) = fixture() else { return }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + if unsafe { + pipelines.dev.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&mut options as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS7).cast(), + std::mem::size_of_val(&options) as u32, + ) + } + .is_err() + || options.MeshShaderTier.0 < D3D12_MESH_SHADER_TIER_1.0 + { + recomp::runner::skip_test("adapter does not support mesh shaders"); + return; + } + let source = r#" +#define RS "" +struct V { float4 p : SV_Position; }; +[RootSignature(RS)] +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void main(out vertices V vertices[3], out indices uint3 triangles[1]) { + SetMeshOutputCounts(3, 1); + vertices[0].p = float4(-1, -1, 0, 1); + vertices[1].p = float4( 0, 1, 0, 1); + vertices[2].p = float4( 1, -1, 0, 1); + triangles[0] = uint3(0, 1, 2); +} +"#; + let mesh = recomp::dxc::compile(source, "main", "ms_6_6", &[]).expect("compile MS"); + let root: ID3D12RootSignature = unsafe { pipelines.dev.CreateRootSignature(0, &mesh) } + .expect("mesh root signature"); + let mut stream = MeshStream { + root: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, value: root.as_raw() }, + mesh: Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, + value: D3D12_SHADER_BYTECODE { pShaderBytecode: mesh.as_ptr().cast(), BytecodeLength: mesh.len() }, + }, + topology: Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + value: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + }, + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: std::mem::size_of::(), + pPipelineStateSubobjectStream: (&mut stream as *mut MeshStream).cast(), + }; + let device: ID3D12Device2 = pipelines.dev.cast().expect("ID3D12Device2"); + let pso = unsafe { device.CreatePipelineState::(&desc) }.expect("mesh pipeline"); + let library = NativeLibrary::empty(&pipelines.dev).expect("empty pipeline library"); + library.store("mesh-0001", &pso).expect("store mesh pipeline"); + let bytes = library.serialize().expect("serialize mesh library"); + let reopened = NativeLibrary::open(&pipelines.dev, bytes).expect("reopen mesh library"); + reopened.load_stream("mesh-0001", &desc).expect("load mesh pipeline"); + } +} From b83c3f0d7efed89a88b0f5c2182cc2a8cde0b233 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:43:34 -0500 Subject: [PATCH 19/22] Shaders: pass null for empty pipeline libraries Create a new D3D12 pipeline library with the API-mandated null blob pointer and zero length instead of Rust's non-null empty-slice pointer. Windows accepts both forms, while Wine correctly rejects the latter with E_INVALIDARG. Tested with the four native pipeline-library round-trip tests on an RTX 4090. Assisted-by: Codex (GPT-5) --- crates/xcl/src/shaders/pipeline_library.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders/pipeline_library.rs b/crates/xcl/src/shaders/pipeline_library.rs index ef151b7607..e7a390ba60 100644 --- a/crates/xcl/src/shaders/pipeline_library.rs +++ b/crates/xcl/src/shaders/pipeline_library.rs @@ -31,7 +31,21 @@ impl NativeLibrary { pub(crate) fn open(device: &ID3D12Device, serialized: Vec) -> Result { let device: ID3D12Device1 = device.cast()?; - let library = unsafe { device.CreatePipelineLibrary::(&serialized)? }; + let library = if serialized.is_empty() { + let mut library = std::ptr::null_mut(); + unsafe { + (Interface::vtable(&device).CreatePipelineLibrary)( + Interface::as_raw(&device), + std::ptr::null(), + 0, + &ID3D12PipelineLibrary1::IID, + &mut library, + ).ok()?; + ID3D12PipelineLibrary1::from_raw(library) + } + } else { + unsafe { device.CreatePipelineLibrary::(&serialized)? } + }; Ok(Self { library, _serialized: serialized }) } From 0d84fb5ee17489e45b61c16420955e0044fe2abc Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:53:52 -0500 Subject: [PATCH 20/22] Shaders: publish semantic corpus identities Publish a SHA-256 identity with atomically staged pipeline corpora and expose it to the runtime. Add a pipeline-layout source identity that deliberately excludes compiler, profile, optimization, and diagnostic build inputs while preserving the existing preparation key. Existing corpora without the new identity remain readable and can take the conservative preparation path. Assisted-by: Codex (GPT-5) --- README.md | 3 ++- crates/xcl/build.rs | 10 ++++++++-- crates/xcl/src/shaders/pso_corpus.rs | 29 +++++++++++++++++++++++++++- scripts/pso_corpus/stage.py | 18 +++++++++++++++++ scripts/pso_corpus/test_stage.py | 7 +++++++ 5 files changed, 63 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6324896115..9f57eef865 100644 --- a/README.md +++ b/README.md @@ -272,7 +272,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder rebuilds. Changes to translation, pipeline layout, settings or cache files trigger validation. - To prepare known graphics, two-pass mesh and compute recipes offline, use a local [archive layout profile](scripts/pso_corpus/archive-profile.md) with the following commands. - The staging command accepts several journals and deduplicates their recipes. + The staging command accepts several journals, deduplicates their recipes and atomically publishes + a content identity for later preparation receipts. ```powershell python scripts/pso_corpus/pso_archive.py profile.json archive.bin pipelines.bin diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index c2d191e8f6..4ad42df3be 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -60,7 +60,7 @@ const PREPARATION_LAYOUT_SOURCES: &[&str] = &[ "src/hle/d3d12x/gfx_records.rs", // normalized recipe fields and reconstruction ]; -fn preparation_source_id(root: &Path) -> u64 { +fn preparation_layout_id(root: &Path) -> u64 { let mut id = 0xcbf2_9ce4_8422_2325u64; add(&mut id, NATIVE_PREPARATION_ABI); for &relative in PREPARATION_LAYOUT_SOURCES { @@ -70,6 +70,10 @@ fn preparation_source_id(root: &Path) -> u64 { add_source(&mut id, &std::fs::read(root.join(relative)).expect("read pipeline layout input")); add(&mut id, &[0]); } + id +} + +fn preparation_source_id(mut id: u64) -> u64 { for name in ["TARGET", "PROFILE", "CARGO_ENCODED_RUSTFLAGS", "OPT_LEVEL", "DEBUG"] { add(&mut id, name.as_bytes()); add(&mut id, std::env::var(name).unwrap_or_default().as_bytes()); @@ -94,7 +98,9 @@ fn main() { _ => {} } let root = Path::new(env!("CARGO_MANIFEST_DIR")); - println!("cargo:rustc-env=XCL_NATIVE_PREPARATION_ID={:016x}", preparation_source_id(root)); + let layout = preparation_layout_id(root); + println!("cargo:rustc-env=XCL_PIPELINE_LAYOUT_ID={layout:016x}"); + println!("cargo:rustc-env=XCL_NATIVE_PREPARATION_ID={:016x}", preparation_source_id(layout)); let mut h = 0xcbf2_9ce4_8422_2325u64; add(&mut h, b"xcl-translator-source-v1\0"); add(&mut h, TRANSLATION_GLUE_REVISION.as_bytes()); diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index 2a1237cbf4..1b949d0095 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -10,6 +10,24 @@ pub(crate) struct Corpus { graphics: Option<(PathBuf, usize)>, compute: Vec<(u64, PathBuf)>, windows: u32, + identity: Option<[u8; 32]>, +} + +fn identity(path: &Path) -> Result, String> { + let text = match std::fs::read_to_string(path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("Could not read pipeline corpus identity: {e}")), + }; + let text = text.trim(); + if text.len() != 64 || !text.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("Invalid pipeline corpus identity".into()); + } + let mut out = [0; 32]; + for (i, byte) in out.iter_mut().enumerate() { + *byte = u8::from_str_radix(&text[2*i..2*i+2], 16).map_err(|_| "Invalid pipeline corpus identity")?; + } + Ok(Some(out)) } pub(crate) fn discover(root: &Path) -> Result, String> { @@ -55,10 +73,13 @@ pub(crate) fn discover(root: &Path) -> Result, String> { return Err("Pipeline corpus is missing records. Restage before launching.".into()); } if graphics.is_none() && compute.is_empty() { return Err("Published pipeline corpus is empty".into()); } - Ok(Some(Corpus { graphics, compute, windows })) + let identity = identity(&dir.join("identity"))?; + Ok(Some(Corpus { graphics, compute, windows, identity })) } impl Corpus { + pub(crate) fn identity(&self) -> Option<[u8; 32]> { self.identity } + pub(super) fn graphics_path(&self) -> Option<&Path> { self.graphics.as_ref().map(|(path, _)| path.as_path()) } @@ -206,6 +227,12 @@ mod tests { assert!(corpus.compute_path(17).is_none()); assert!(corpus.graphics_path().is_none()); assert_eq!(corpus.windows, 1); + assert_eq!(corpus.identity(), None); + std::fs::write(dir.join("identity"), "00".repeat(32)).unwrap(); + assert_eq!(discover(&root).unwrap().unwrap().identity(), Some([0; 32])); + std::fs::write(dir.join("identity"), "truncated").unwrap(); + assert!(discover(&root).is_err()); + std::fs::remove_file(dir.join("identity")).unwrap(); std::fs::write(dir.join("windows"), "255").unwrap(); assert!(discover(&root).is_err()); std::fs::write(dir.join("windows"), "0").unwrap(); diff --git a/scripts/pso_corpus/stage.py b/scripts/pso_corpus/stage.py index 6e2723f486..e97a15a015 100644 --- a/scripts/pso_corpus/stage.py +++ b/scripts/pso_corpus/stage.py @@ -17,6 +17,7 @@ OFFSET, PRIME, MASK = 0xcbf29ce484222325, 0x100000001b3, (1 << 64) - 1 HEADER = struct.Struct(" Date: Fri, 27 Nov 2026 12:58:01 -0500 Subject: [PATCH 21/22] Shaders: collect prepared PSOs into native libraries Collect successful standalone compute, graphics, mesh and two-pass compute PSOs into process-local D3D12 pipeline libraries. Graphics and compute publish separate pending libraries because preparation crosses a process boundary. Verified-blob shortcuts remain unchanged outside an active library build. During library construction they replay cached PSOs once so StorePipeline receives the native objects. Unsupported drivers retain the existing preparation path. Assisted-by: Codex (GPT-5) --- crates/xcl/src/hle/d3d12x/real.rs | 28 ++++++ crates/xcl/src/shaders.rs | 34 ++++++-- crates/xcl/src/shaders/pipeline_library.rs | 99 +++++++++++++++++++++- crates/xcl/src/shaders/pso_corpus.rs | 18 +++- 4 files changed, 170 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c1c0aceb99..d620a35a39 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5358,6 +5358,14 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else if build.reused && from_disk { driver_cache::note(true, None); } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(pso) = ID3D12PipelineState::from_raw_borrowed(&*ppv) { + if let Err(e) = crate::shaders::pipeline_library::store(driver_cache::graphics_name(gkey.0, gkey.1), pso) { + note_translation_error(e); + return Some(E_INVALIDARG); + } + } + } if hr < 0 { note_translation_error(format!( "the driver rejected the PSO with the translated shaders ({hr:#x}; topology type {}, {} render targets, DSV format {}, HS {}, GS {})", @@ -6480,6 +6488,26 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: note_translation_error(format!("the driver rejected the compute pass of the console {kind} ({hc:#x})")); return E_INVALIDARG; } + let library = crate::shaders::pipeline_library::store( + match gkey { + Some((hash, bytes)) => driver_cache::graphics_name(hash, bytes), + None if crate::shaders::pipeline_library::building() => { + super::pso_async::release(compute as usize); + return E_INVALIDARG; + } + None => String::new(), + }, + &mesh_pso, + ).and_then(|_| { + let compute_pso = ID3D12PipelineState::from_raw_borrowed(&compute) + .ok_or_else(|| "The two-pass compute pipeline has no native object".to_string())?; + crate::shaders::pipeline_library::store(driver_cache::name(&tp.cs, 0), compute_pso) + }); + if let Err(e) = library { + note_translation_error(e); + super::pso_async::release(compute as usize); + return E_INVALIDARG; + } let mesh_pso = mesh_pso.into_raw(); *ppv = mesh_pso; note_pso_rs(mesh_pso, mesh_rs); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9de9625d7a..8b3a111f3f 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -14,7 +14,7 @@ use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; use crate::hle::d3d12x::gfx_records; pub(crate) mod pso_corpus; -mod pipeline_library; +pub(crate) mod pipeline_library; mod warm_blobs; mod warm_pack; pub(crate) mod warm_replay; @@ -32,7 +32,7 @@ fn warm_settings(vars: impl IntoIterator pipeline_library::store(driver_cache::name_for(dxil, desc.Flags.0, chained), pso), + Err(_) => Ok(()), + }; drop(claim); *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); @@ -1800,7 +1804,8 @@ impl Pipelines { if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } - r.map(drop).map_err(|e| format!("Creating native compute pipeline ({} bytes of DXIL): {e}", dxil.len())) + r.map(drop).map_err(|e| format!("Creating native compute pipeline ({} bytes of DXIL): {e}", dxil.len()))?; + library } } @@ -2484,8 +2489,15 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { crate::gpu::uma::leave_out(); recomp::pso::set_title_windows(windows); recomp::dxc::set_memory_reserve(2); + let library_path = std::env::var_os("XCL_PIPELINE_LIBRARY_OUT").map(PathBuf::from); let (device, book) = match Pipelines::for_adapter("auto") { Ok(p) => { + if library_path.is_some() { + match pipeline_library::begin(&p.dev) { + Ok(_) => {} + Err(e) => { eprintln!("xcl shaders: {e}"); return 2; } + } + } let cache = recomp::dxc::cache_dir(); let book = warm_replay::native_key(&p.dev).and_then(|key| { let known = warm_replay::driver_files(&cache.join("driver")).unwrap_or_default(); @@ -2518,7 +2530,7 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { } })).unwrap_or(false); let ok = if let Some(book) = &book { - if book.can_defer(key) { + if !pipeline_library::building() && book.can_defer(key) { verified.fetch_add(1, Ordering::Relaxed); true } else { @@ -2540,7 +2552,17 @@ fn graphics_worker(job: &Path, windows: u32, requested: Option) -> i32 { if let Some(book) = book { book.save(); } eprintln!("previously verified native graphics recipes: {}", verified.into_inner()); let (hits, _, stored) = real::driver_cache_stats(); - let failed = failed.into_inner(); + let mut failed = failed.into_inner(); + if failed == 0 { + if let Some(path) = library_path.as_deref().filter(|_| pipeline_library::building()) { + match pipeline_library::finish(path) { + Ok(n) => eprintln!("pipeline library: {n} graphics entries"), + Err(e) => { eprintln!("xcl shaders: {e}"); failed += 1; } + } + } + } else { + pipeline_library::abort(); + } eprintln!("graphics pipelines: {} made, {failed} failed; driver blobs: {hits} from disk, {stored} kept", made.into_inner()); if failed == 0 { 0 } else { 2 } } diff --git a/crates/xcl/src/shaders/pipeline_library.rs b/crates/xcl/src/shaders/pipeline_library.rs index e7a390ba60..b1a2c2137c 100644 --- a/crates/xcl/src/shaders/pipeline_library.rs +++ b/crates/xcl/src/shaders/pipeline_library.rs @@ -6,6 +6,75 @@ use windows::core::{HSTRING, Interface, Result}; use windows::Win32::Graphics::Direct3D12::*; +struct Builder { + library: NativeLibrary, + names: std::collections::HashSet, +} + +static BUILD: std::sync::Mutex> = std::sync::Mutex::new(None); + +pub(crate) fn building() -> bool { BUILD.lock().unwrap().is_some() } + +pub(crate) fn begin(device: &ID3D12Device) -> std::result::Result { + if !NativeLibrary::supported(device) { return Ok(false) } + let library = NativeLibrary::empty(device).map_err(|e| format!("Creating pipeline library: {e}"))?; + let mut active = BUILD.lock().unwrap(); + if active.is_some() { return Err("A pipeline library build is already active".into()); } + *active = Some(Builder { library, names: Default::default() }); + Ok(true) +} + +pub(crate) fn store(name: String, pipeline: &ID3D12PipelineState) -> std::result::Result<(), String> { + let mut active = BUILD.lock().unwrap(); + let Some(builder) = active.as_mut() else { return Ok(()) }; + if !builder.names.insert(name.clone()) { return Ok(()) } + if let Err(e) = builder.library.store(&name, pipeline) { + builder.names.remove(&name); + return Err(format!("Storing pipeline {name}: {e}")); + } + Ok(()) +} + +pub(crate) fn abort() { *BUILD.lock().unwrap() = None; } + +pub(crate) fn finish(path: &std::path::Path) -> std::result::Result { + let builder = BUILD.lock().unwrap().take().ok_or("No pipeline library build is active")?; + let count = builder.names.len(); + let bytes = builder.library.serialize().map_err(|e| format!("Serializing pipeline library: {e}"))?; + write_atomic(path, &bytes).map_err(|e| format!("Publishing {}: {e}", path.display()))?; + Ok(count) +} + +fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + use std::os::windows::ffi::OsStrExt; + use std::sync::atomic::{AtomicU64, Ordering}; + use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH}; + static NEXT: AtomicU64 = AtomicU64::new(0); + if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } + let (temporary, mut file) = loop { + let candidate = path.with_extension(format!("tmp{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&candidate) { + Ok(file) => break (candidate, file), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + }; + let result = (|| { + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + let from: Vec = temporary.as_os_str().encode_wide().chain([0]).collect(); + let to: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) } == 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + })(); + if result.is_err() { let _ = std::fs::remove_file(temporary); } + result +} + pub(crate) struct NativeLibrary { library: ID3D12PipelineLibrary1, _serialized: Vec, @@ -86,7 +155,7 @@ impl NativeLibrary { #[cfg(test)] mod tests { - use super::NativeLibrary; + use super::{abort, begin, finish, store, NativeLibrary}; use crate::gpu::recomp; use crate::shaders::Pipelines; use std::mem::ManuallyDrop; @@ -183,6 +252,34 @@ void main() { output.Store(0, 42); } drop_desc(desc); } + #[test] + fn builder_deduplicates_names_and_atomically_replaces_output() { + let Some((pipelines, dxil, root)) = fixture() else { return }; + let desc = compute_desc(&dxil, &root); + let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) } + .expect("compute pipeline"); + let path = std::env::temp_dir().join(format!("xcl-pipeline-library-{}.bin", std::process::id())); + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } } + let _cleanup = Cleanup(path.clone()); + abort(); + assert!(begin(&pipelines.dev).expect("begin library")); + store("one".into(), &pso).expect("store one"); + store("one".into(), &pso).expect("deduplicate one"); + assert_eq!(finish(&path).expect("publish library"), 1); + let first = std::fs::read(&path).expect("published bytes"); + NativeLibrary::open(&pipelines.dev, first).expect("published library"); + + assert!(begin(&pipelines.dev).expect("begin replacement")); + store("two".into(), &pso).expect("store replacement"); + assert_eq!(finish(&path).expect("replace library"), 1); + let replacement = std::fs::read(&path).expect("replacement bytes"); + let library = NativeLibrary::open(&pipelines.dev, replacement).expect("replacement library"); + assert!(library.load_compute("one", &desc).is_err()); + library.load_compute("two", &desc).expect("load replacement"); + drop_desc(desc); + } + #[test] fn graphics_pipeline_round_trips_through_serialized_library() { let Some((pipelines, _, _)) = fixture() else { return }; diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index 1b949d0095..080eb91aed 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -112,6 +112,8 @@ impl Corpus { } if self.compute.is_empty() { return progress.check_corpus_complete(); } let mut pipelines = Pipelines::for_adapter(&progress.adapter)?; + let library_path = self.compute_directory().and_then(Path::parent).map(|dir| dir.join("compute.plib.pending")); + if library_path.is_some() { super::pipeline_library::begin(&pipelines.dev)?; } pipelines.warm_blobs = super::warm_blobs::Verified::for_device(&pipelines.dev); pipelines.max_dxil = 0; pipelines.most = parallel; @@ -144,8 +146,19 @@ impl Corpus { book.save(); eprintln!("previously verified native compute pipelines: {}", pipelines.verified.load(Ordering::Relaxed)); } - if let Some(e) = error.into_inner().unwrap() { return Err(e); } - progress.check_corpus_complete() + if let Some(e) = error.into_inner().unwrap() { + super::pipeline_library::abort(); + return Err(e); + } + if let Err(e) = progress.check_corpus_complete() { + super::pipeline_library::abort(); + return Err(e); + } + if let Some(path) = library_path.as_deref().filter(|_| super::pipeline_library::building()) { + let entries = super::pipeline_library::finish(path)?; + eprintln!("pipeline library: {entries} compute entries"); + } + Ok(()) } } @@ -157,6 +170,7 @@ fn run_graphics(path: &Path, count: usize, windows: u32, parallel: usize, progre } let mut child = command.arg("shaders").arg(path).arg("--graphics-records") .arg("--windows").arg(windows.to_string()).env("XCL_PIPELINE_THREADS", parallel.to_string()) + .env("XCL_PIPELINE_LIBRARY_OUT", path.with_file_name("graphics.plib.pending")) .spawn().map_err(|e| e.to_string())?; let stderr = child.stderr.take().expect("worker_command pipes stderr"); let (tx, rx) = mpsc::channel(); From e2d5cd87fe3d490b444fd9d15dcb9d2d14515d3a Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:08:26 -0500 Subject: [PATCH 22/22] Shaders: trust complete native pipeline libraries Publish validated graphics and compute pipeline-library bytes with a semantic receipt after corpus preparation completes. On an unchanged corpus, adapter, driver, translation layout, and runtime memory configuration, validate the serialized libraries and bypass title shader parsing and PSO preparation entirely. Interrupted, corrupt, incomplete, or stale artifacts fall back to the existing preparation path. Tested with focused receipt, native-library, and warm-settings tests on an RTX 4090. Assisted-by: Codex (GPT-5) --- crates/xcl/src/shaders.rs | 11 + crates/xcl/src/shaders/pipeline_library.rs | 10 +- crates/xcl/src/shaders/pso_corpus.rs | 20 +- crates/xcl/src/shaders/warm_library.rs | 259 +++++++++++++++++++++ crates/xcl/src/shaders/warm_replay.rs | 9 +- 5 files changed, 302 insertions(+), 7 deletions(-) create mode 100644 crates/xcl/src/shaders/warm_library.rs diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 8b3a111f3f..bac329ff84 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -17,6 +17,7 @@ pub(crate) mod pso_corpus; pub(crate) mod pipeline_library; mod warm_blobs; mod warm_pack; +mod warm_library; pub(crate) mod warm_replay; pub(crate) fn warm_settings_key() -> u64 { warm_settings(std::env::vars_os()) } @@ -1951,6 +1952,16 @@ fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { let corpus = pso_corpus::discover(root)?; + if let Some(corpus) = &corpus { + if warm_library::reuse(corpus, &progress.adapter) { + let (graphics, compute) = corpus.counts(); + let total = graphics.checked_add(compute).ok_or("Pipeline corpus count overflow")?; + progress.begin_corpus(total); + progress.complete_corpus(total)?; + crate::xlog_info!("Pipeline preparation: reused the complete native pipeline libraries ({total} recipes)"); + return Ok(()); + } + } prepare_title_inputs(root, progress, corpus.as_ref())?; if let Some(corpus) = corpus { corpus.prepare(progress)?; diff --git a/crates/xcl/src/shaders/pipeline_library.rs b/crates/xcl/src/shaders/pipeline_library.rs index b1a2c2137c..f255c691e2 100644 --- a/crates/xcl/src/shaders/pipeline_library.rs +++ b/crates/xcl/src/shaders/pipeline_library.rs @@ -45,7 +45,7 @@ pub(crate) fn finish(path: &std::path::Path) -> std::result::Result std::io::Result<()> { +pub(crate) fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { use std::io::Write; use std::os::windows::ffi::OsStrExt; use std::sync::atomic::{AtomicU64, Ordering}; @@ -77,7 +77,7 @@ fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { pub(crate) struct NativeLibrary { library: ID3D12PipelineLibrary1, - _serialized: Vec, + _serialized: std::sync::Arc<[u8]>, } impl NativeLibrary { @@ -95,10 +95,14 @@ impl NativeLibrary { } pub(crate) fn empty(device: &ID3D12Device) -> Result { - Self::open(device, Vec::new()) + Self::open_shared(device, std::sync::Arc::from([])) } pub(crate) fn open(device: &ID3D12Device, serialized: Vec) -> Result { + Self::open_shared(device, serialized.into()) + } + + pub(crate) fn open_shared(device: &ID3D12Device, serialized: std::sync::Arc<[u8]>) -> Result { let device: ID3D12Device1 = device.cast()?; let library = if serialized.is_empty() { let mut library = std::ptr::null_mut(); diff --git a/crates/xcl/src/shaders/pso_corpus.rs b/crates/xcl/src/shaders/pso_corpus.rs index 080eb91aed..cc3df3f599 100644 --- a/crates/xcl/src/shaders/pso_corpus.rs +++ b/crates/xcl/src/shaders/pso_corpus.rs @@ -80,6 +80,18 @@ pub(crate) fn discover(root: &Path) -> Result, String> { impl Corpus { pub(crate) fn identity(&self) -> Option<[u8; 32]> { self.identity } + pub(crate) fn directory(&self) -> &Path { + self.graphics.as_ref().map(|(path, _)| path.parent().unwrap()) + .or_else(|| self.compute.first().and_then(|(_, path)| path.parent()?.parent())) + .expect("a published corpus is not empty") + } + + pub(crate) fn windows(&self) -> u32 { self.windows } + + pub(crate) fn counts(&self) -> (usize, usize) { + (self.graphics.as_ref().map_or(0, |(_, count)| *count), self.compute.len()) + } + pub(super) fn graphics_path(&self) -> Option<&Path> { self.graphics.as_ref().map(|(path, _)| path.as_path()) } @@ -110,7 +122,11 @@ impl Corpus { if let Some((path, n)) = &self.graphics { run_graphics(path, *n, count, parallel, progress)?; } - if self.compute.is_empty() { return progress.check_corpus_complete(); } + if self.compute.is_empty() { + progress.check_corpus_complete()?; + let pipelines = Pipelines::for_adapter(&progress.adapter)?; + return super::warm_library::publish(self, &pipelines.dev); + } let mut pipelines = Pipelines::for_adapter(&progress.adapter)?; let library_path = self.compute_directory().and_then(Path::parent).map(|dir| dir.join("compute.plib.pending")); if library_path.is_some() { super::pipeline_library::begin(&pipelines.dev)?; } @@ -158,7 +174,7 @@ impl Corpus { let entries = super::pipeline_library::finish(path)?; eprintln!("pipeline library: {entries} compute entries"); } - Ok(()) + super::warm_library::publish(self, &pipelines.dev) } } diff --git a/crates/xcl/src/shaders/warm_library.rs b/crates/xcl/src/shaders/warm_library.rs new file mode 100644 index 0000000000..d1c21cdde9 --- /dev/null +++ b/crates/xcl/src/shaders/warm_library.rs @@ -0,0 +1,259 @@ +//! A completed corpus's semantic receipt and validated native pipeline-library bytes. + +use super::{pipeline_library::NativeLibrary, pso_corpus::Corpus, Pipelines}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use windows::Win32::Graphics::Direct3D12::ID3D12Device; + +const VERSION: u32 = 1; +const RECEIPT: &str = "pipeline-libraries-v1.json"; +const GRAPHICS: &str = "graphics.plib"; +const COMPUTE: &str = "compute.plib"; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Semantic { + version: u32, + corpus: [u8; 32], + layout: u64, + translation: u64, + settings: u64, + windows: u32, + driver: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Receipt { + semantic: Semantic, + graphics_bytes: Option, + compute_bytes: Option, +} + +#[allow(dead_code)] // Consumed by the stacked lazy runtime integration. +pub(crate) struct Ready { + pub(crate) graphics: Option>, + pub(crate) compute: Option>, +} + +static READY: Mutex> = Mutex::new(None); + +#[allow(dead_code)] // Consumed by the stacked lazy runtime integration. +pub(crate) fn take_ready() -> Option { READY.lock().unwrap().take() } + +fn semantic(corpus: [u8; 32], windows: u32, driver: u64) -> Semantic { + Semantic { + version: VERSION, + corpus, + layout: u64::from_str_radix(env!("XCL_PIPELINE_LAYOUT_ID"), 16).expect("pipeline layout id"), + translation: crate::gpu::recomp::pso::translation_cache_identity(), + settings: super::warm_settings_key(), + windows, + driver, + } +} + +fn expected(corpus: &Corpus, device: &ID3D12Device) -> Option { + Some(semantic( + corpus.identity()?, + corpus.windows(), + crate::hle::d3d12x::real::preparation_driver_identity(device)?, + )) +} + +fn paths(dir: &Path) -> (PathBuf, PathBuf, PathBuf) { + (dir.join(GRAPHICS), dir.join(COMPUTE), dir.join(RECEIPT)) +} + +fn pending(path: &Path) -> PathBuf { path.with_extension("plib.pending") } + +fn validate(path: &Path, expected: u64, device: &ID3D12Device) -> Option> { + let bytes = std::fs::read(path).ok()?; + if bytes.len() as u64 != expected { return None } + let bytes: Arc<[u8]> = bytes.into(); + NativeLibrary::open_shared(device, bytes.clone()).ok()?; + Some(bytes) +} + +fn validate_set(dir: &Path, receipt: &Receipt, device: &ID3D12Device) -> Option { + let (graphics, compute, _) = paths(dir); + Some(Ready { + graphics: match receipt.graphics_bytes { Some(n) => Some(validate(&graphics, n, device)?), None => None }, + compute: match receipt.compute_bytes { Some(n) => Some(validate(&compute, n, device)?), None => None }, + }) +} + +pub(crate) fn reuse(corpus: &Corpus, adapter: &str) -> bool { + match reuse_inner(corpus, adapter) { + Ok(ready) => { + *READY.lock().unwrap() = Some(ready); + true + } + Err(reason) => { + crate::xlog_info!("Pipeline preparation: native library fast path unavailable ({reason})"); + false + } + } +} + +fn reuse_inner(corpus: &Corpus, adapter: &str) -> Result { + let pipelines = Pipelines::for_adapter(adapter)?; + if !NativeLibrary::supported(&pipelines.dev) { return Err("driver does not support pipeline libraries".into()) } + let expected = expected(corpus, &pipelines.dev).ok_or("corpus or driver has no semantic identity")?; + let (_, _, path) = paths(corpus.directory()); + let receipt = super::warm_replay::read_receipt::(&path).ok_or("receipt missing or corrupt")?; + if receipt.semantic != expected { return Err("receipt semantic identity changed".into()) } + validate_set(corpus.directory(), &receipt, &pipelines.dev).ok_or("serialized library missing, corrupt or incompatible".into()) +} + +pub(crate) fn publish(corpus: &Corpus, device: &ID3D12Device) -> Result<(), String> { + let Some(semantic) = expected(corpus, device) else { return Ok(()) }; + if !NativeLibrary::supported(device) { return Ok(()) } + let (graphics, compute, receipt_path) = paths(corpus.directory()); + let counts = corpus.counts(); + let graphics_pending = pending(&graphics); + let compute_pending = pending(&compute); + let graphics_ready: Option> = (counts.0 != 0).then(|| std::fs::read(&graphics_pending)).transpose() + .map_err(|e| format!("Reading prepared graphics library: {e}"))?.map(Into::into); + let compute_ready: Option> = (counts.1 != 0).then(|| std::fs::read(&compute_pending)).transpose() + .map_err(|e| format!("Reading prepared compute library: {e}"))?.map(Into::into); + let open = |bytes: &Arc<[u8]>| NativeLibrary::open_shared(device, bytes.clone()); + graphics_ready.as_ref().map(open).transpose() + .map_err(|e| format!("Validating prepared graphics library: {e}"))?; + compute_ready.as_ref().map(open).transpose() + .map_err(|e| format!("Validating prepared compute library: {e}"))?; + if let Some(bytes) = &graphics_ready { + super::pipeline_library::write_atomic(&graphics, bytes).map_err(|e| e.to_string())?; + } + if let Some(bytes) = &compute_ready { + super::pipeline_library::write_atomic(&compute, bytes).map_err(|e| e.to_string())?; + } + let receipt = Receipt { + semantic, + graphics_bytes: graphics_ready.as_ref().map(|b| b.len() as u64), + compute_bytes: compute_ready.as_ref().map(|b| b.len() as u64), + }; + let encoded = super::warm_replay::receipt_bytes(&receipt).ok_or("Encoding pipeline library receipt")?; + super::pipeline_library::write_atomic(&receipt_path, &encoded).map_err(|e| e.to_string())?; + if graphics_ready.is_some() { let _ = std::fs::remove_file(graphics_pending); } + if compute_ready.is_some() { let _ = std::fs::remove_file(compute_pending); } + *READY.lock().unwrap() = Some(Ready { graphics: graphics_ready, compute: compute_ready }); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::recomp; + use std::mem::ManuallyDrop; + use windows::Win32::Graphics::Direct3D12::*; + + #[test] + fn semantic_inputs_each_invalidate_the_receipt() { + let base = semantic([1; 32], 4, 7); + let mut changed = base.clone(); changed.corpus[0] ^= 1; assert_ne!(base, changed); + let mut changed = base.clone(); changed.layout ^= 1; assert_ne!(base, changed); + let mut changed = base.clone(); changed.translation ^= 1; assert_ne!(base, changed); + let mut changed = base.clone(); changed.settings ^= 1; assert_ne!(base, changed); + let mut changed = base.clone(); changed.windows ^= 1; assert_ne!(base, changed); + let mut changed = base.clone(); changed.driver ^= 1; assert_ne!(base, changed); + } + + #[test] + fn corrupt_and_truncated_receipts_do_not_parse() { + let dir = std::env::temp_dir().join(format!("xcl-library-receipt-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join(RECEIPT); + std::fs::write(&path, b"{").unwrap(); + assert!(super::super::warm_replay::read_receipt::(&path).is_none()); + std::fs::write(&path, b"not json").unwrap(); + assert!(super::super::warm_replay::read_receipt::(&path).is_none()); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn incomplete_preparation_never_publishes_a_receipt() { + let pipelines = match Pipelines::new() { + Ok(pipelines) => pipelines, + Err(reason) => { recomp::runner::skip_test(&reason); return; } + }; + if !NativeLibrary::supported(&pipelines.dev) { + recomp::runner::skip_test("adapter does not support pipeline libraries"); + return; + } + let root = std::env::temp_dir().join(format!("xcl-incomplete-library-{}", std::process::id())); + struct Cleanup(PathBuf); + impl Drop for Cleanup { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } + let _cleanup = Cleanup(root.clone()); + let dir = root.join(".xcl/pso-corpus"); + std::fs::create_dir_all(dir.join("compute")).unwrap(); + std::fs::write(dir.join("complete"), "0 1\n").unwrap(); + std::fs::write(dir.join("windows"), "1\n").unwrap(); + std::fs::write(dir.join("identity"), "01".repeat(32)).unwrap(); + std::fs::write(dir.join("compute/0000000000000001.dxbc"), b"fixture").unwrap(); + let corpus = super::super::pso_corpus::discover(&root).unwrap().unwrap(); + assert!(publish(&corpus, &pipelines.dev).is_err()); + assert!(!dir.join(RECEIPT).exists()); + } + + #[test] + fn cold_publish_makes_an_unchanged_corpus_reusable() { + if let Err(reason) = recomp::dxc::location() { + recomp::runner::skip_test(&format!("no DXC: {reason}")); + return; + } + let pipelines = match Pipelines::new() { + Ok(pipelines) => pipelines, + Err(reason) => { recomp::runner::skip_test(&reason); return; } + }; + if !NativeLibrary::supported(&pipelines.dev) { + recomp::runner::skip_test("adapter does not support pipeline libraries"); + return; + } + let root = std::env::temp_dir().join(format!("xcl-warm-library-{}", std::process::id())); + struct Cleanup(PathBuf); + impl Drop for Cleanup { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } + let _cleanup = Cleanup(root.clone()); + let dir = root.join(".xcl/pso-corpus"); + std::fs::create_dir_all(dir.join("compute")).unwrap(); + std::fs::write(dir.join("complete"), "0 1\n").unwrap(); + std::fs::write(dir.join("windows"), "1\n").unwrap(); + std::fs::write(dir.join("identity"), "01".repeat(32)).unwrap(); + std::fs::write(dir.join("compute/0000000000000001.dxbc"), b"fixture").unwrap(); + let corpus = super::super::pso_corpus::discover(&root).unwrap().unwrap(); + + let source = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b:register(u0);\n[RootSignature(RS)][numthreads(1,1,1)] void main(){b.Store(0,1);}"; + let dxil = recomp::dxc::compile(source, "main", "cs_6_6", &[]).unwrap(); + let signature: ID3D12RootSignature = unsafe { pipelines.dev.CreateRootSignature(0, &dxil) }.unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(signature)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }; + let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) }.unwrap(); + super::super::pipeline_library::abort(); + assert!(super::super::pipeline_library::begin(&pipelines.dev).unwrap()); + super::super::pipeline_library::store("fixture.pso".into(), &pso).unwrap(); + super::super::pipeline_library::finish(&dir.join("compute.plib.pending")).unwrap(); + publish(&corpus, &pipelines.dev).unwrap(); + assert!(dir.join(RECEIPT).is_file() && dir.join(COMPUTE).is_file()); + assert!(!dir.join("compute.plib.pending").exists()); + assert!(take_ready().unwrap().compute.is_some()); + std::fs::write(root.join("shaders.rpf"), b"invalid pack that the fast path must not read").unwrap(); + let progress = super::super::LaunchPreparation { adapter: "auto".into(), ..Default::default() }; + super::super::prepare_for_launch(&root, &progress).unwrap(); + assert_eq!(progress.done.load(std::sync::atomic::Ordering::Relaxed), 1); + assert_eq!(progress.total.load(std::sync::atomic::Ordering::Relaxed), 1); + assert!(take_ready().unwrap().compute.is_some()); + let final_path = dir.join(COMPUTE); + let valid = std::fs::read(&final_path).unwrap(); + std::fs::write(&final_path, b"corrupt").unwrap(); + assert!(!reuse(&corpus, "auto")); + std::fs::remove_file(&final_path).unwrap(); + assert!(!reuse(&corpus, "auto")); + std::fs::write(&final_path, valid).unwrap(); + std::fs::write(dir.join("identity"), "02".repeat(32)).unwrap(); + let changed = super::super::pso_corpus::discover(&root).unwrap().unwrap(); + assert!(!reuse(&changed, "auto")); + drop(ManuallyDrop::into_inner(desc.pRootSignature)); + } +} diff --git a/crates/xcl/src/shaders/warm_replay.rs b/crates/xcl/src/shaders/warm_replay.rs index ccda319b9b..fa6d7a225f 100644 --- a/crates/xcl/src/shaders/warm_replay.rs +++ b/crates/xcl/src/shaders/warm_replay.rs @@ -16,11 +16,16 @@ pub(crate) fn read_receipt(path: &Path) -> Optio } pub(crate) fn write_receipt(path: &Path, receipt: &T) -> bool { + let Some(bytes) = receipt_bytes(receipt) else { return false }; + crate::hle::d3d12x::real::driver_cache::write(path, &bytes) +} + +pub(crate) fn receipt_bytes(receipt: &T) -> Option> { let mut bytes = vec![0; 8]; - if serde_json::to_writer(&mut bytes, receipt).is_err() { return false; } + if serde_json::to_writer(&mut bytes, receipt).is_err() { return None; } let checksum = crate::gpu::shader::fnv64(&bytes[8..]).to_le_bytes(); bytes[..8].copy_from_slice(&checksum); - crate::hle::d3d12x::real::driver_cache::write(path, &bytes) + Some(bytes) } pub(crate) type Stamp = [u64; 3];