Skip to content
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ next steps:
| **Shader recompiler** | ✅ | RDNA2 → HLSL → DXIL: VS, PS, CS, mesh (NGG), GS; atomics, LDS, scratch, images, samplers incl. static ones, wave ops, ray-tracing instructions; structured control flow; parallel DXC, disk cache | 26 698 / 26 698 programs of the retail pack; 0 DXC errors on random samples; per-instruction GPU tests |
| **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background |
| **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL |
| **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens |
| **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; fence mirrors follow completed values even when a queue rewinds them; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens |
| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact |
| **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU |
| **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output |
Expand Down
116 changes: 97 additions & 19 deletions crates/xcl/src/hle/d3d12x/fence_x.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Fence #12 of the newer console layout (a retail game): the address of the fence's completed value,
//! which the title reads and sleeps on (`monitorx` / `mwaitx`). On the console the GPU writes
//! that memory; a PC fence's value is only behind GetCompletedValue, so each fence asked gets a
//! cell of its own that a thread keeps equal to it: every Signal the title queues arms an event.
//! cell of its own that a thread refreshes on queue-signal events and on a timer for rewinds.

use std::collections::HashMap;
use std::ffi::c_void;
Expand All @@ -10,8 +10,11 @@ use std::sync::{Mutex, OnceLock};
use windows::core::Interface;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Graphics::Direct3D12::ID3D12Fence;
use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows_sys::Win32::System::Threading as th;

const REWIND_POLL_MS: u32 = 10;

/// a cache line of its own: the title's monitors wake on writes to the line
#[repr(C, align(64))]
struct Cell(AtomicU64);
Expand All @@ -27,18 +30,32 @@ struct Fence {
static FENCES: Mutex<Option<HashMap<usize, Fence>>> = Mutex::new(None);

/// the event a completion sets (auto-reset); the first use starts the thread that follows it
fn event() -> usize {
static E: OnceLock<usize> = OnceLock::new();
fn event() -> Option<usize> {
static E: OnceLock<Option<usize>> = OnceLock::new();
*E.get_or_init(|| unsafe {
let e = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize;
if e == 0 {
crate::xlog_error!("D3D12.X: could not create the fence completion event");
return None;
}
let spawned = std::thread::Builder::new().name("xcl-fences".into()).spawn(move || loop {
th::WaitForSingleObject(e as _, th::INFINITE);
refresh();
// SetEventOnCompletion is a threshold notification. A lower queued value
// may already satisfy it before the GPU has reached that signal.
match th::WaitForSingleObject(e as _, REWIND_POLL_MS) {
WAIT_OBJECT_0 => refresh(true),
WAIT_TIMEOUT => refresh(false),
status => {
crate::xlog_error!("D3D12.X: fence completion wait failed ({status:#x})");
break;
}
}
});
if let Err(err) = spawned {
crate::xlog_error!("D3D12.X: no thread for the fences' completed values: {err}");
CloseHandle(e as _);
return None;
}
e
Some(e)
})
}

Expand All @@ -47,19 +64,26 @@ unsafe fn borrowed<R>(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option
ID3D12Fence::from_raw_borrowed(&p).map(f)
}

fn refresh() {
fn refresh(write_unchanged: bool) {
let g = FENCES.lock().unwrap_or_else(|e| e.into_inner());
for (&p, f) in g.iter().flatten() {
if let Some(c) = f.cell {
if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } {
c.0.store(v, Ordering::Release);
// Preserve wakes on a signal. An idle timer tick must only wake the
// title's cache-line monitor if the fence has actually changed.
if write_unchanged || c.0.load(Ordering::Relaxed) != v {
c.0.store(v, Ordering::Release);
}
}
}
}
}

unsafe fn arm(fence: usize, value: u64) {
if let Some(Err(e)) = borrowed(fence, |f| f.SetEventOnCompletion(value, HANDLE(event() as *mut c_void))) {
let Some(event) = event() else {
return;
};
if let Some(Err(e)) = borrowed(fence, |f| f.SetEventOnCompletion(value, HANDLE(event as *mut c_void))) {
crate::xlog_warn!("D3D12.X: fence {fence:#x}: SetEventOnCompletion({value:#x}): {e}");
}
}
Expand All @@ -81,7 +105,7 @@ pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) {
pub(super) fn note_cpu_signal(fence: usize) {
let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some()));
if known {
refresh();
refresh(true);
}
}

Expand All @@ -101,8 +125,11 @@ pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void)
};
if pending > 0 {
arm(this as usize, pending);
} else {
// A signal to zero before the title asked for the address still needs polling.
event();
}
refresh();
refresh(true);
cell.0.as_ptr()
}

Expand All @@ -113,18 +140,26 @@ mod tests {
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::*;

unsafe fn device() -> Option<ID3D12Device> {
let mut dev = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() {
return dev;
}
let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?;
let warp: IDXGIAdapter = factory.EnumWarpAdapter().ok()?;
D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?;
dev
}

/// The cell follows the fence: CPU signals at once, queue signals when the GPU is there –
/// also one queued before the address was asked for.
#[test]
fn the_cell_follows_the_fence() {
unsafe {
let mut dev: Option<ID3D12Device> = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap();
let warp: IDXGIAdapter = factory.EnumWarpAdapter().unwrap();
D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device");
}
let dev = dev.unwrap();
let Some(dev) = device() else {
crate::gpu::recomp::runner::skip_test("no D3D12 device");
return;
};
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap();
let fence: ID3D12Fence = dev.CreateFence(5, D3D12_FENCE_FLAG_NONE).unwrap();
let p = fence.as_raw();
Expand All @@ -145,8 +180,51 @@ mod tests {
wait(cell, 7);
fence.Signal(9).unwrap();
note_cpu_signal(p as usize);
assert_eq!(*cell, 9);
assert_eq!((*cell.cast::<AtomicU64>()).load(Ordering::Acquire), 9);
std::mem::forget(fence); // the map keeps its address
}
}

#[test]
fn the_cell_follows_a_delayed_queue_rewind() {
unsafe {
let Some(dev) = device() else {
crate::gpu::recomp::runner::skip_test("no D3D12 device");
return;
};
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
..Default::default()
}).unwrap();
let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
let fence: &ID3D12Fence = Box::leak(Box::new(
dev.CreateFence(9, D3D12_FENCE_FLAG_NONE).unwrap(),
));
let cell = &*completed_value_address(fence.as_raw()).cast::<AtomicU64>();

// Change the native fence without refreshing the cell here. The cell reaching
// 40 tells us the worker refreshed while the queue was still held at the gate.
fence.Signal(40).unwrap();
queue.Wait(&gate, 1).unwrap();
let signal = queue.Signal(fence, 3);
if signal.is_ok() {
note_queue_signal(fence.as_raw() as usize, 3);
}
let wait = |expected| {
let start = std::time::Instant::now();
loop {
let value = cell.load(Ordering::Acquire);
if value == expected || start.elapsed().as_secs() >= 5 {
return value;
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
};
let before_rewind = wait(40);
gate.Signal(1).unwrap();
signal.unwrap();
assert_eq!(before_rewind, 40, "the worker did not refresh before the queue rewind");
assert_eq!(wait(3), 3, "stale cell after queue rewind, native fence {}", fence.GetCompletedValue());
}
}
}
Loading