diff --git a/README.md b/README.md index 6c97b6ad33..1bd0c54868 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,16 @@ 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 that need state supplied by the + title are created during play. 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. - 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/Cargo.toml b/crates/xcl/Cargo.toml index c3b23a1b8b..08bd049d19 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -44,6 +44,7 @@ features = [ version = "0.61" features = [ "Win32_Foundation", + "Win32_Graphics_Gdi", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..482f2d1ec2 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -357,7 +357,10 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { // window // --------------------------------------------------------------------------------------- +pub(crate) mod preparation; + unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + if let Some(result) = preparation::on_message(hwnd, msg, wp) { return result; } // keyboard and mouse as the gamepad: raw mouse input, the cursor held in the window if crate::hle::kbm::on_message(hwnd.0, msg, wp.0, lp.0) { return LRESULT(0); @@ -499,10 +502,10 @@ fn window_thread() { crate::xlog_error!("could not create the XCL window"); return; }; - HWND_RAW.store(hwnd.0 as isize, Ordering::Release); crate::xlog_info!("XCL window created ({}x{})", cfg.window_width, cfg.window_height); - crate::hle::kbm::attach(hwnd.0); + if !preparation::active() { crate::hle::kbm::attach(hwnd.0); } SetTimer(Some(hwnd), COMPILE_TIMER, 500, None); + HWND_RAW.store(hwnd.0 as isize, Ordering::Release); let mut msg = MSG::default(); while GetMessageW(&mut msg, None, 0, 0).as_bool() { let _ = TranslateMessage(&msg); @@ -1005,6 +1008,7 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D p.h = h; p.fmt = fmt; crate::xlog_info!("present: swap chain {w}x{h} {:?} – the game image will appear in the XCL window", fmt); + crate::xlog_info!("present: swap chain window {:#x}", hwnd.0 as usize); p.sc.is_some() } Err(e) => { diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs new file mode 100644 index 0000000000..1d4e614b8f --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -0,0 +1,230 @@ +//! Pre-entry shader preparation in the same HWND that later owns the DXGI swap chain. +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; +use windows::Win32::Foundation::{HWND, LRESULT, WPARAM}; +use windows_sys::Win32::Foundation::{RECT, WAIT_OBJECT_0}; +use windows_sys::Win32::Graphics::Gdi::*; +use windows_sys::Win32::System::Threading::WaitForSingleObject; +use windows_sys::Win32::UI::WindowsAndMessaging::*; +use crate::config::Boot; +use crate::shaders::{LaunchPreparation, prepare_for_launch}; +use crate::util::wide; + +static ACTIVE: AtomicBool = AtomicBool::new(false); +static SCREEN: Mutex> = Mutex::new(None); +const READY: u32 = WM_APP + 0x40; + +struct Screen { + progress: Arc, + start: Instant, + clock: StallClock, + ready: bool, +} + +impl Screen { + fn release(&mut self) -> bool { + self.ready = !self.progress.cancel.load(Ordering::Relaxed); + self.ready + } +} + +pub(super) fn active() -> bool { ACTIVE.load(Ordering::Acquire) } + +pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { + // This handle was opened by the launcher on itself, then inherited by this host. + let parent = std::env::var("XCL_PREPARATION_PARENT").ok() + .and_then(|s| s.parse::().ok()).filter(|&h| h != 0) + .map(|h| unsafe { OwnedHandle::from_raw_handle(h as _) }); + let menu = std::env::var_os("XCL_PREPARATION_MENU").is_some(); + 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()) { + return Ok(()); + } + 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")?; + crate::xlog_info!("Shader preparation window {:#x}", hwnd.0 as usize); + Some(hwnd) + } else { None }; + let result = std::thread::scope(|scope| { + let worker = scope.spawn(|| prepare_for_launch(root, &progress)); + while !worker.is_finished() { + 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. + std::process::exit(2); + } + } else { std::thread::sleep(Duration::from_millis(80)); } + } + worker.join().map_err(|_| "Shader preparation worker stopped unexpectedly")? + }); + let mut result = if progress.cancel.load(Ordering::Relaxed) { Err("Shader preparation cancelled".into()) } else { result }; + if let Some(hwnd) = hwnd { + if result.is_ok() { + // Complete painting on the window's owner thread before the guest can draw. + if unsafe { SendMessageW(hwnd.0, READY, 0, 0) } == 0 { + result = Err("Shader preparation cancelled".into()); + } + } else if let Err(e) = &result { + if menu && !progress.cancel.load(Ordering::Relaxed) { + unsafe { MessageBoxW(hwnd.0, wide(e).as_ptr(), wide("XCL – Shader preparation failed").as_ptr(), MB_OK | MB_ICONERROR); } + } + } + ACTIVE.store(false, Ordering::Release); + *SCREEN.lock().unwrap() = None; + } + result +} + +pub(super) unsafe fn on_message(hwnd: HWND, msg: u32, wp: WPARAM) -> Option { + if !active() { return None; } + match msg { + WM_PAINT => { + let mut guard = SCREEN.lock().unwrap(); + if let Some(s) = guard.as_mut() { paint(hwnd, s); } + } + WM_ERASEBKGND => return Some(LRESULT(1)), + WM_TIMER if wp.0 == super::COMPILE_TIMER => { InvalidateRect(hwnd.0, std::ptr::null(), 0); } + WM_CLOSE => { + if let Some(s) = SCREEN.lock().unwrap().as_ref() { s.progress.cancel.store(true, Ordering::Relaxed); } + InvalidateRect(hwnd.0, std::ptr::null(), 0); + } + READY => { + { + let mut view = SCREEN.lock().unwrap(); + let s = view.as_mut()?; + if !s.release() { return Some(LRESULT(0)); } + } + RedrawWindow(hwnd.0, std::ptr::null(), std::ptr::null_mut(), RDW_INVALIDATE | RDW_UPDATENOW); + crate::hle::kbm::attach(hwnd.0); + ACTIVE.store(false, Ordering::Release); + return Some(LRESULT(1)); + } + _ => return None, + } + Some(LRESULT(0)) +} + +unsafe fn fill(dc: HDC, rect: RECT, color: u32) { + let brush = CreateSolidBrush(color); + FillRect(dc, &rect, brush); + DeleteObject(brush); +} + +unsafe fn text(dc: HDC, rect: RECT, value: &str, size: i32, weight: i32, color: u32, align: u32) { + let font = CreateFontW(-size, 0, 0, 0, weight, 0, 0, 0, DEFAULT_CHARSET as _, 0, 0, CLEARTYPE_QUALITY as _, 0, wide("Segoe UI").as_ptr()); + let old = SelectObject(dc, font); + SetTextColor(dc, color); + let utf = wide(value); + let mut rect = rect; + DrawTextW(dc, utf.as_ptr(), (utf.len()-1) as i32, &mut rect, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS | align); + SelectObject(dc, old); + DeleteObject(font); +} + +unsafe fn paint(hwnd: HWND, s: &mut Screen) { + let mut ps: PAINTSTRUCT = std::mem::zeroed(); + let dest = BeginPaint(hwnd.0, &mut ps); + let mut rc = RECT::default(); + GetClientRect(hwnd.0, &mut rc); + if rc.right > 0 && rc.bottom > 0 { + let dc = CreateCompatibleDC(dest); + let bitmap = CreateCompatibleBitmap(dest, rc.right, rc.bottom); + let old = SelectObject(dc, bitmap); + SetBkMode(dc, TRANSPARENT as i32); + fill(dc, rc, 0x201815); + 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 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); + 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 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); + 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") }; + text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); + let mut times = 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); + SelectObject(dc, old); + DeleteObject(bitmap); + DeleteDC(dc); + } + EndPaint(hwnd.0, &ps); +} + +#[derive(Default)] +struct StallClock { + done: usize, + advanced_at: Duration, + last_stall_ended: Option, +} + +impl StallClock { + fn sample(&mut self, done: usize, now: Duration) -> (u64, Option) { + if done != self.done { + if now - self.advanced_at >= Duration::from_secs(5) { + self.last_stall_ended = Some(now); + } + self.done = done; + self.advanced_at = now; + } + ((now - self.advanced_at).as_secs(), self.last_stall_ended.map(|end| (now - end).as_secs())) + } +} + +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) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clock_advances_during_a_stall_and_remembers_recovery() { + let mut clock = StallClock::default(); + let s = Duration::from_secs; + assert_eq!(clock.sample(0, s(1)), (1, None)); + assert_eq!(clock.sample(0, s(5)), (5, None)); + assert_eq!(clock.sample(2, s(6)), (0, Some(0))); + assert_eq!(clock.sample(2, s(8)), (2, Some(2))); + assert_eq!(clock.sample(3, s(9)), (0, Some(3))); + assert_eq!(clock.sample(3, s(15)), (6, Some(9))); + assert_eq!(clock.sample(4, s(16)), (0, Some(0))); + } + + #[test] + fn close_before_the_ready_message_cancels_the_handoff() { + let progress = Arc::new(LaunchPreparation::default()); + let mut screen = Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }; + progress.cancel.store(true, Ordering::Relaxed); + assert!(!screen.release()); + assert!(!screen.ready); + } + + #[test] + fn only_a_successful_join_releases_the_last_percent() { + assert_eq!(percent(0, 0, false), 0); + assert_eq!(percent(1, 4, false), 25); + assert_eq!(percent(4, 4, false), 99); + assert_eq!(percent(4, 4, true), 100); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 444333d891..a9412c658c 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -36,6 +36,11 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + if let Err(e) = crate::hle::d3d12x::present::preparation::before_guest(&boot) { + crate::xlog_error!("Shader preparation: {e}"); + eprintln!("xcl: {e}"); + return 2; + } let _ = std::thread::Builder::new().name("xcl-split-counts".into()).spawn(|| loop { std::thread::sleep(std::time::Duration::from_secs(10)); crate::hle::d3d12x::real::log_dispatch_chain_counts(); diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index 00a9cb1f87..c328c22750 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf}; use crate::config::{Boot, Config}; use crate::util::wide; + /// Data root: `%XCL_DATA_ROOT%` or `%LOCALAPPDATA%\XCL`. pub fn data_root() -> PathBuf { if let Ok(p) = std::env::var("XCL_DATA_ROOT") { @@ -286,6 +287,14 @@ fn quote(a: &str) -> String { } pub fn run(target: &Path, args: &[String]) -> i32 { + run_with_ui(target, args, false) +} + +pub fn run_from_menu(target: &Path) -> i32 { + run_with_ui(target, &[], true) +} + +fn run_with_ui(target: &Path, args: &[String], menu: bool) -> i32 { let (root, explicit_exe, title) = match resolve_location(target) { Ok(x) => x, Err(e) => { @@ -388,7 +397,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 { cmdline.push(' '); cmdline.push_str("e(a)); } - let code = match spawn_host(&cmdline, &root, &boot_path) { + let code = match spawn_host(&cmdline, &root, &boot_path, menu) { Ok(c) => c, Err(e) => { eprintln!("xcl: failed to start the game process: {e}"); @@ -448,12 +457,20 @@ pub fn missing_console_cpu_features() -> Vec<&'static str> { }) } -fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result { +fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path, menu: bool) -> Result { use windows_sys::Win32::Foundation::{CloseHandle, GetLastError}; use windows_sys::Win32::System::Threading::{ CreateProcessW, GetExitCodeProcess, WaitForSingleObject, INFINITE, PROCESS_INFORMATION, STARTUPINFOW, }; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, OpenProcess, PROCESS_SYNCHRONIZE}; let me = std::env::current_exe().map_err(|e| e.to_string())?; + // An inheritable, synchronize-only handle identifies this exact launcher even after PID reuse. + let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 1, GetCurrentProcessId()) }; + if handle.is_null() { return Err(std::io::Error::last_os_error().to_string()); } + let parent = unsafe { OwnedHandle::from_raw_handle(handle) }; + std::env::set_var("XCL_PREPARATION_PARENT", (parent.as_raw_handle() as usize).to_string()); + if menu { std::env::set_var("XCL_PREPARATION_MENU", "1"); } std::env::set_var("XCL_HOST", boot_path); let app = wide(&me.to_string_lossy()); let mut cmd = wide(cmdline); @@ -474,9 +491,12 @@ fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result i32 { let _ = std::fs::create_dir_all(xcl::launcher::data_root()); let _ = std::fs::write(&last_file, target.to_string_lossy().as_bytes()); println!("xcl run \"{}\"", target.display()); - let code = xcl::launcher::run(&target, &[]); + let code = xcl::launcher::run_from_menu(&target); if code != 0 { println!("\nXCL ended with code {code}. Press Enter to close."); let _ = std::io::stdin().read_line(&mut String::new()); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..4c5a014974 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -981,7 +981,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0); + return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) { + Ok(()) => 0, + Err(e) => { eprintln!("xcl shaders: {e}"); 2 } + }; } if opts.direct { return direct_sweep(&input, &opts, t0); @@ -1411,14 +1414,21 @@ mod pipeline_cap_tests { unsafe impl Sync for Pipelines {} impl Pipelines { - fn new() -> Result { + fn new() -> Result { Self::for_adapter("auto") } + + fn for_adapter(adapter: &str) -> Result { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Dxgi::*; unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; - let sel = crate::gpu::adapter::Selector::from_env_or("auto"); - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; - let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; + let sel = crate::gpu::adapter::Selector::from_env_or(adapter); + let dev = if sel == crate::gpu::adapter::Selector::Warp { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().map_err(|e| e.to_string())?; + crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? + } else { + let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? + }; let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { @@ -1590,15 +1600,66 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant) -> i32 { +#[derive(Default)] +pub(crate) struct LaunchPreparation { + pub adapter: String, + pub done: AtomicUsize, + pub total: AtomicUsize, + pub cancel: std::sync::atomic::AtomicBool, +} + +/// Unpacked shader containers in the title's shaders directory. Do not follow directory +/// junctions into another tree or back into the shader directory. +fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { + use std::os::windows::fs::MetadataExt; + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let metadata = entry.metadata()?; + if metadata.file_attributes() & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 { continue; } + let path = entry.path(); + if metadata.is_dir() { + loose_inputs(&path, files)?; + } else if path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("dxbc")) { + files.push(path); + } + } + Ok(()) +} + +pub(crate) fn prepare_for_launch(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())? { + let data = std::fs::read(&pack).map_err(|e| format!("Reading {}: {e}", pack.display()))?; + if !data.starts_with(pack::RPF9_MAGIC) { return Err(format!("Unrecognized shader pack: {}", pack.display())); } + let records = pack::scan(&data, 0x40); + if records.is_empty() { return Err(format!("No readable shader records in {}", pack.display())); } + inputs.push(Input::Pack { data, records }); + } + let loose = root.join("shaders"); + if loose.is_dir() { + let mut files = Vec::new(); + loose_inputs(&loose, &mut files).map_err(|e| format!("Reading {}: {e}", loose.display()))?; + if !files.is_empty() { inputs.push(Input::Files(files)); } + } + 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; } + for input in inputs { + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + precompile(&input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?; + } + Ok(()) +} + +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { let pipelines = if pipelines { - match Pipelines::new() { - Ok(p) => Some(p), - Err(e) => { - eprintln!("xcl shaders --pipelines: no GPU device: {e}"); - return 2; - } + let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) + .map_err(|e| format!("No pipeline device: {e}"))?; + if startup.is_some() && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { + p.max_dxil = 0; } + Some(p) } else { None }; @@ -1614,11 +1675,12 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; // no title runs: only a little commit is kept free besides the compiles - recomp::dxc::set_memory_reserve(2); + if startup.is_none() { recomp::dxc::set_memory_reserve(2); } // VS / PS: the 32-lane form wherever the GPU can run 32-lane waves (`pso::graphics_wave32`); // `--split` sets both - let graphics_split = split.unwrap_or_else(recomp::runner::graphics_wave32); - let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); + 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))); println!( "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), @@ -1630,15 +1692,31 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on std::thread::scope(|s| { for _ in 0..threads { s.spawn(|| loop { + if startup.is_some_and(|p| p.cancel.load(Ordering::Relaxed)) { break; } let i = next.fetch_add(1, Ordering::Relaxed); if i >= n { break; } + 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()); } + }; let (name, blob) = input.get(i); - let Some(blob) = blob else { continue }; - let Some(sh) = xbox::parse(&blob) else { continue }; + let Some(blob) = blob else { + if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); } + record_done(); + continue; + }; + let Some(sh) = xbox::parse(&blob) else { + if startup.is_some() && !matches!(shader::classify(&blob).0, shader::Kind::Dxil | shader::Kind::Dxbc) { + failed.fetch_add(1, Ordering::Relaxed); + } + record_done(); + continue; + }; if only.is_some_and(|o| !sh.stage.eq_ignore_ascii_case(o)) { - done.fetch_add(1, Ordering::Relaxed); + record_done(); continue; } // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): @@ -1646,13 +1724,16 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { if used.is_some_and(|u| !used_compute(&blob, u)) { unused.fetch_add(1, Ordering::Relaxed); - done.fetch_add(1, Ordering::Relaxed); + record_done(); continue; } match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { p.make(&c); + if startup.is_some() && c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { + p.make_one(&c.dxil, &c.samplers, true, None); + } } compiled.fetch_add(1, Ordering::Relaxed) } @@ -1664,10 +1745,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on failed.fetch_add(1, Ordering::Relaxed) } }; - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - if d % 200 == 0 { - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); - } + record_done(); continue; } for f in &sh.fssm { @@ -1688,10 +1766,21 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; - let Ok(t) = recomp::translate(code, &opt) else { continue }; - if !t.complete() { - continue; - } + let t = match recomp::translate(code, &opt) { + Ok(t) if t.complete() => t, + Ok(_) => { + if startup.is_some() { skipped.fetch_add(1, Ordering::Relaxed); } + continue; + } + Err(e) => { + if startup.is_some() { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + } + continue; + } + }; 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), @@ -1707,18 +1796,17 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } } } - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - if d % 200 == 0 { - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); - } + record_done(); }); } }); + let failed = failed.into_inner(); + let skipped_reason = if startup.is_some() { "runtime pairing or unsupported translation" } else { "GS – paired at pipeline creation" }; println!( - "compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}, time {:.1} s", + "compiled {}, already cached {}, errors {}, skipped ({skipped_reason}) {}, time {:.1} s", compiled.into_inner(), cached.into_inner(), - failed.into_inner(), + failed, skipped.into_inner(), t0.elapsed().as_secs_f64() ); @@ -1737,10 +1825,21 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on println!("pipelines over the {} MiB DXIL cap, left to the runtime: {} ({} MiB of DXIL; XCL_PIPELINE_MAX_KB)", p.max_dxil >> 20, capped, p.capped_bytes.load(Ordering::Relaxed) >> 20); } } - for e in errors.into_inner().unwrap() { - println!(" {e}"); + 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()); } + let p = pipelines.expect("startup requested pipelines"); + let refused = p.refused.load(Ordering::Relaxed); + let capped = 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." } + else { "Check the shader pack and driver diagnostics." }); + return Err(format!("Shader preparation stopped: {failed} record failures, {refused} refused pipelines, {capped} over the size cap. {cause}")); + } } - 0 + Ok(()) } /// Compile the kept HLSL samples with DXC on all cores: (ok, failures with the first error line). diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 027638eee7..4f238248a9 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -128,6 +128,9 @@ fn test_title_runs_and_game_folder_is_untouched() { copy_dir(&manifest.join("..").join("..").join("tests").join("data").join("testgame"), &game); std::fs::copy(&title, game.join("xcl_testtitle.exe")).unwrap(); std::fs::copy(&dll, game.join("testgame_mw.dll")).unwrap(); + // Already-compiled graphics bytecode still goes through startup discovery. + std::fs::create_dir(game.join("shaders")).unwrap(); + std::fs::copy(manifest.join("../../tests/data/dxil/dxc_vs_uav.dxil"), game.join("shaders/vertex.dxbc")).unwrap(); let before = snapshot(&game); let out = Command::new(&xcl) @@ -157,6 +160,10 @@ fn test_title_runs_and_game_folder_is_untouched() { assert!(stdout.contains("xcl_testtitle: done, failures: 0"), "the test title did not run to the end"); assert!(out.status.success(), "exit code {:?}", out.status.code()); + let log = std::fs::read_to_string(data.join("XCL.TestTitle/logs/xcl.log")).unwrap(); + let window = |tag| log.lines().find_map(|line| line.split_once(tag).map(|(_, hwnd)| hwnd)).unwrap(); + assert_eq!(window("Shader preparation window "), window("present: swap chain window ")); + // (2) the game folder is untouched assert_eq!(snapshot(&game), before, "GAME FOLDER WAS MODIFIED"); diff --git a/crates/xcl/tests/launcher_e2e.rs b/crates/xcl/tests/launcher_e2e.rs index 4100fad051..733d14a866 100644 --- a/crates/xcl/tests/launcher_e2e.rs +++ b/crates/xcl/tests/launcher_e2e.rs @@ -22,6 +22,21 @@ impl Drop for TempDir { } } +#[test] +fn unreadable_shader_pack_stops_launch_before_host_start() { + let game = TempDir::new("xcl-preparation-failed"); + std::fs::write(game.0.join("title.exe"), b"must never be loaded").unwrap(); + std::fs::write(game.0.join("shaders.rpf"), b"9FPR").unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["run"]).arg(&game.0) + .env("XCL_DATA_ROOT", game.0.join("user")) + .env("XCL_SKIP_CPU_CHECK", "1") + .output().unwrap(); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("No readable shader records")); + assert!(!String::from_utf8_lossy(&output.stdout).contains("Log:")); +} + #[test] fn launcher_missing_target_argument_exits_code_two() { let output = Command::new(env!("CARGO_BIN_EXE_xcl")) diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 index db296218b2..ad15cbc0c0 100644 --- a/scripts/smoke.ps1 +++ b/scripts/smoke.ps1 @@ -2,7 +2,7 @@ # prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built # from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). # -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] [-Title