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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,16 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
<details>
<summary><b>Switches, caches, logs and the files XCL writes</b></summary>

- 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.
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ features = [
version = "0.61"
features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_Diagnostics_Debug",
Expand Down
8 changes: 6 additions & 2 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) => {
Expand Down
230 changes: 230 additions & 0 deletions crates/xcl/src/hle/d3d12x/present/preparation.rs
Original file line number Diff line number Diff line change
@@ -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<Option<Screen>> = Mutex::new(None);
const READY: u32 = WM_APP + 0x40;

struct Screen {
progress: Arc<LaunchPreparation>,
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::<usize>().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<LRESULT> {
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), &times, 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<Duration>,
}

impl StallClock {
fn sample(&mut self, done: usize, now: Duration) -> (u64, Option<u64>) {
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);
}
}
5 changes: 5 additions & 0 deletions crates/xcl/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
26 changes: 23 additions & 3 deletions crates/xcl/src/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -388,7 +397,7 @@ pub fn run(target: &Path, args: &[String]) -> i32 {
cmdline.push(' ');
cmdline.push_str(&quote(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}");
Expand Down Expand Up @@ -448,12 +457,20 @@ pub fn missing_console_cpu_features() -> Vec<&'static str> {
})
}

fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result<u32, String> {
fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path, menu: bool) -> Result<u32, String> {
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);
Expand All @@ -474,9 +491,12 @@ fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result<u32, String
&si,
&mut pi,
);
let error = GetLastError();
std::env::remove_var("XCL_HOST");
std::env::remove_var("XCL_PREPARATION_PARENT");
std::env::remove_var("XCL_PREPARATION_MENU");
if ok == 0 {
return Err(format!("CreateProcessW: error {}", GetLastError()));
return Err(format!("CreateProcessW: error {error}"));
}
WaitForSingleObject(pi.hProcess, INFINITE);
let mut code = 0u32;
Expand Down
2 changes: 1 addition & 1 deletion crates/xcl/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ fn run_picked_game() -> 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());
Expand Down
Loading
Loading