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
5 changes: 5 additions & 0 deletions crates/xcl/src/gpu/agility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ use windows::core::{Interface, IUnknown, Param, GUID, PCSTR};
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL;
use windows::Win32::Graphics::Direct3D12::*;

/// Exported for `gpu::recomp::runner` to enable the D3D12 debug layer before device creation.
pub use windows::Win32::Graphics::Direct3D12::CLSID_D3D12Debug;
/// Exported for `gpu::recomp::runner` to enable the D3D12 debug layer before device creation.
pub use windows::Win32::Graphics::Direct3D12::ID3D12Debug;

use crate::pe::{Layout, Pe};

/// Environment variable overriding the Agility SDK folder.
Expand Down
7 changes: 7 additions & 0 deletions crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use windows::Win32::Graphics::Dxgi::*;

use super::{KERNEL_LANES, KERNEL_RES_DWORDS, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_VGPRS};
use crate::gpu::fence;
use crate::gpu::agility::{configuration_interface, CLSID_D3D12Debug, ID3D12Debug};

/// Initial state of a kernel run.
#[derive(Clone)]
Expand Down Expand Up @@ -85,6 +86,12 @@ unsafe fn wait_for_submission(

fn init() -> Result<Gpu, String> {
unsafe {
// Enable debug layer BEFORE creating the device if XCL_D3D12_DEBUG is set
if std::env::var_os("XCL_D3D12_DEBUG").is_some() {
if let Ok(debug) = configuration_interface::<ID3D12Debug>(&CLSID_D3D12Debug) {
debug.EnableDebugLayer();
}
}
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(e)?;
// `XCL_ADAPTER` picks the adapter (default: the first in high-performance order)
let sel = crate::gpu::adapter::Selector::from_env_or("auto");
Expand Down
18 changes: 18 additions & 0 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4133,6 +4133,11 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea
pc::<W>(this, PC_WRITE_BUFFER_IMMEDIATE)(this, params.len() as u32, params.as_ptr(), modes.as_ptr());
}

/// Serializes tests that create D3D12 devices / access shared GPU state (LISTS, LIVE_QUEUES,
/// SYNC_GRAPH, COPY_SCRATCH, QUEUE_IDS, WRITE_TRACE, MIRRORS, VISIBLE, etc.). Tests that
/// don't touch these can run in parallel.
pub static TEST_LOCK: Mutex<()> = Mutex::new(());

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -4142,6 +4147,7 @@ mod tests {
/// and is gone from it once the fence gets there.
#[test]
fn an_internal_wait_is_listed_until_its_fence_reaches_the_value() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;

unsafe {
Expand All @@ -4164,6 +4170,7 @@ mod tests {

#[test]
fn copy_scratch_budget_counts_resources_until_gpu_completion() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;

unsafe {
Expand Down Expand Up @@ -4212,6 +4219,7 @@ mod tests {
/// scratch buffer, which the GPU may still use.
#[test]
fn a_new_list_takes_no_copy_scratch_of_an_earlier_one() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;

unsafe {
Expand Down Expand Up @@ -4548,6 +4556,7 @@ mod tests {

#[test]
fn depth_bias_native_list9_and_bundle_fallback() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -5367,6 +5376,7 @@ mod tests {
/// land once the queue completes. Unaligned and unwritable addresses are ignored.
#[test]
fn timestamps_outside_unified_memory_land_after_the_queue() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -5442,6 +5452,7 @@ mod tests {

#[test]
fn write_buffer_immediate_on_open_existing_heap_visible_to_cpu() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
Expand Down Expand Up @@ -5631,6 +5642,7 @@ mod tests {
/// GPU `queue.Wait`/`queue.Signal` without blocking the submitter thread for `WAIT_TIMEOUT`.
#[test]
fn cross_queue_wait64_before_signal_does_not_deadlock_submit_thread() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -5710,6 +5722,7 @@ mod tests {
/// complete immediately without stalling CPU or hanging GPU.
#[test]
fn cross_queue_cycle_and_same_queue_fifo_do_not_deadlock() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -5804,6 +5817,7 @@ mod tests {
/// pipelined frame N/N+1 or back-to-back cross-queue handshakes (`wait_seq > prod_sig_seq`).
#[test]
fn pipelined_next_frame_write_is_not_false_cycle() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -5971,6 +5985,7 @@ mod tests {
/// already has an armed `queue.Wait` on it — must rescue the waiter instead of orphaning it.
#[test]
fn rotating_queue_self_deadlock_and_non_monotonic_rescue_do_not_hang() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -6093,6 +6108,7 @@ mod tests {
/// already in flight (watchdog release path) does not hang subsequent queue completions.
#[test]
fn cpu_watchdog_signal_with_inflight_gpu_signal_completes_cleanly() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -6145,6 +6161,7 @@ mod tests {
/// completes on GPU with ZERO CPU cycle breaks, and reuses `pc_c1` from the spare pool on Reset.
#[test]
fn mid_list_write64_wait64_split_avoids_cycle_and_reuses_spares() {
let _guard = TEST_LOCK.lock().unwrap();
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

Expand Down Expand Up @@ -6297,6 +6314,7 @@ mod tests {
/// title's address back, which the PC's GPU has no address for).
#[test]
fn a_mirrored_buffer_binds_its_mirror_without_asking_readable() {
let _guard = TEST_LOCK.lock().unwrap();
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE};
if crate::gpu::uma::get().is_none() {
crate::gpu::recomp::runner::skip_test("no unified memory");
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/hle/d3d12x/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub mod guard;
mod late_release;
pub mod layout;
pub mod list_x;
/// Re-export TEST_LOCK from list_x so tests in sibling modules can use it.
pub use list_x::TEST_LOCK;
pub mod null;
pub mod present;
pub mod pso_async;
Expand Down
6 changes: 6 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6593,6 +6593,7 @@ mod readback_routing_tests {
/// and state bits before creating the cross-adapter placed resource.
#[test]
fn coherent_buffer_sanitizes_console_flags_and_state() {
let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap();
let raw_desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Alignment: 0x10_0000,
Expand Down Expand Up @@ -6735,6 +6736,7 @@ mod readback_routing_tests {
/// its entry from `list_x::LISTS`.
#[test]
fn dma_list_release_cleans_up_list_state() {
let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap();
assert!(
overrides(Kind::DmaList).iter().any(|&(name, f)| name == "Release" && f == cl_release as usize),
"Kind::DmaList must override Release with cl_release"
Expand Down Expand Up @@ -6922,6 +6924,7 @@ mod console_format_query_tests {
/// PC has no such format.
#[test]
fn gpu_console_depth_formats_are_supported() {
let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap();
let Some(dev) = device() else { return };
let (this, f) = (dev.as_raw(), pc_check(&dev));
// the gap: the PC's own answer (unless another test adopted a device, and the vtable it
Expand Down Expand Up @@ -6966,6 +6969,7 @@ mod console_format_query_tests {
/// (XG), and the PC's for the resource made of the desc (`pc_resource_desc`), both sane.
#[test]
fn gpu_console_format_allocation_info_is_sane() {
let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap();
let Some(dev) = device() else { return };
// (bytes a pixel at least, as XG lays them out: 119 alone is a plain 2-byte format, 120 alone
// the stencil plane)
Expand Down Expand Up @@ -6993,6 +6997,7 @@ mod console_format_query_tests {
/// the clear value with it (`pc_clear`) – one still in 118 the PC refuses.
#[test]
fn gpu_placed_console_depth_target_with_clear_value() {
let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap();
let Some(dev) = device() else {
crate::gpu::recomp::runner::skip_test("no GPU");
return;
Expand Down Expand Up @@ -7039,6 +7044,7 @@ mod map_tests {
/// or a reserved one gets its title address instead (the PC's Map on it is an invalid call).
#[test]
fn only_resources_with_cpu_pages_go_to_the_pc_map() {
let _guard = crate::hle::d3d12x::TEST_LOCK.lock().unwrap();
unsafe {
let mut dev: Option<ID3D12Device> = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() {
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/title_textures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1211,6 +1211,7 @@ mod tests {
/// texture that was forgotten (released, or its address registered again) is uploaded again.
#[test]
fn a_texture_with_unchanged_memory_is_left_out_until_it_is_forgotten() {
let _guard = TEST_LOCK.lock().unwrap();
let (a, b) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize);
let mut mem = vec![0u8; 3 << 20];
mem[5] = 1;
Expand Down
81 changes: 76 additions & 5 deletions crates/xcl/src/hle/kbm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,14 @@ pub struct Velocity {

impl Velocity {
pub fn update(&mut self, dx: i32, dy: i32, dt: f32) {
let dt = dt.clamp(0.001, 0.1);
let a = 1.0 - (-dt / SMOOTHING).exp();
self.x += a * (dx as f32 / dt - self.x);
self.y += a * (dy as f32 / dt - self.y);
// Use the real dt for rate calculation; only clamp the smoothing factor
// to avoid spikes when the title pauses input for a long time (issue #963).
let dt_clamped = dt.clamp(0.001, 0.1);
let a = 1.0 - (-dt_clamped / SMOOTHING).exp();
if dt > 0.0 {
self.x += a * (dx as f32 / dt - self.x);
self.y += a * (dy as f32 / dt - self.y);
}
}
}

Expand Down Expand Up @@ -223,6 +227,8 @@ struct Mouse {
velocity: Velocity,
wheel: Wheel,
wheel_rest: i32,
/// Last absolute mouse position (for MOUSE_MOVE_ABSOLUTE), None if not yet set or after reset
last_abs: Option<(i32, i32)>,
}

impl Mouse {
Expand All @@ -231,6 +237,7 @@ impl Mouse {
self.velocity = Velocity::default();
self.wheel = Wheel::default();
self.wheel_rest = 0;
self.last_abs = None;
}
}

Expand Down Expand Up @@ -307,8 +314,20 @@ pub unsafe fn on_message(hwnd: *mut c_void, msg: u32, wp: usize, lp: isize) -> b
let n = GetRawInputData(lp, RID_INPUT, &mut raw as *mut _ as *mut c_void, &mut size, 24);
if n != u32::MAX && n as usize >= std::mem::size_of::<RawMouseInput>() && raw.kind == RIM_TYPEMOUSE && CAPTURED.load(Ordering::Acquire) {
if raw.flags & MOUSE_MOVE_ABSOLUTE == 0 {
// Relative movement
DX.fetch_add(raw.last_x, Ordering::Relaxed);
DY.fetch_add(raw.last_y, Ordering::Relaxed);
} else {
// Absolute movement: compute delta from last absolute position
let mut g = MOUSE.lock().unwrap_or_else(|e| e.into_inner());
let m = g.get_or_insert_with(|| Mouse { last: Instant::now(), velocity: Velocity::default(), wheel: Wheel::default(), wheel_rest: 0, last_abs: None });
if let Some((last_x, last_y)) = m.last_abs {
let dx = raw.last_x - last_x;
let dy = raw.last_y - last_y;
DX.fetch_add(dx, Ordering::Relaxed);
DY.fetch_add(dy, Ordering::Relaxed);
}
m.last_abs = Some((raw.last_x, raw.last_y));
}
if raw.button_flags & RI_MOUSE_WHEEL != 0 {
WHEEL.fetch_add(raw.button_data as i16 as i32, Ordering::Relaxed);
Expand Down Expand Up @@ -429,7 +448,7 @@ pub fn apply(s: &mut GamepadState) {
s.left_trigger = 1.0;
}
let mut g = MOUSE.lock().unwrap_or_else(|e| e.into_inner());
let m = g.get_or_insert_with(|| Mouse { last: Instant::now(), velocity: Velocity::default(), wheel: Wheel::default(), wheel_rest: 0 });
let m = g.get_or_insert_with(|| Mouse { last: Instant::now(), velocity: Velocity::default(), wheel: Wheel::default(), wheel_rest: 0, last_abs: None });
let now = Instant::now();
let dt = now.duration_since(m.last).as_secs_f32();
m.last = now;
Expand Down Expand Up @@ -549,6 +568,57 @@ mod tests {
assert_eq!(scancode_to_vk(0xFFFF, SC_Q.1, layout), SC_Q.1);
}

#[test]
fn velocity_update_uses_real_dt_for_rate_clamped_for_smoothing() {
// Issue #963: camera whip on focus regain – the fix uses real dt for rate
// calculation (dx/dt) but clamps dt only for the smoothing factor.
let mut v = Velocity::default();

// A long pause (dt = 1.0) followed by a small movement should not spike velocity.
// With the bug: a = 1 - exp(-0.1/0.03) ≈ 0.96, rate = 10/0.1 = 100 → velocity jumps to ~100.
// With the fix: a = 1 - exp(-0.1/0.03) ≈ 0.96, rate = 10/1.0 = 10 → velocity gently moves toward 10.
v.update(10, 0, 1.0);
assert!(v.x < 20.0, "velocity should not spike after a long pause, got {}", v.x);

// Normal short dt still works: 10 counts in 0.004s = 2500 counts/s.
// Velocity approaches the target rate exponentially; run enough updates to converge.
for _ in 0..50 {
v.update(10, 0, 0.004);
}
assert!((v.x - 2500.0).abs() < 100.0, "velocity should track normal movement, got {}", v.x);
}

#[test]
fn mouse_struct_has_last_abs_field_for_absolute_coordinates() {
// Issue #962: some Raw Input devices report absolute coordinates (MOUSE_MOVE_ABSOLUTE).
// The Mouse struct needs a last_abs field to track the previous position for delta calculation.
let m = Mouse {
last: Instant::now(),
velocity: Velocity::default(),
wheel: Wheel::default(),
wheel_rest: 0,
last_abs: Some((1000, 500)),
};
// The field should store the last absolute position
assert_eq!(m.last_abs, Some((1000, 500)));
}

#[test]
fn mouse_reset_clears_last_abs() {
// Reset must clear last_abs to None, so the first absolute move is handled correctly
// (first move has no previous position to compute delta from)
let mut m = Mouse {
last: Instant::now(),
velocity: Velocity::default(),
wheel: Wheel::default(),
wheel_rest: 0,
last_abs: Some((1000, 500)),
};
m.reset(Instant::now());
// After reset, last_abs should be None
assert!(m.last_abs.is_none());
}

#[test]
fn focus_loss_resets_mouse_velocity_and_wheel_state() {
// Seed raw deltas and active MOUSE state (velocity, in-flight & pending wheel notches, remainder).
Expand All @@ -569,6 +639,7 @@ mod tests {
velocity: v,
wheel: w,
wheel_rest: 90,
last_abs: None,
});
let m = g.as_ref().unwrap();
assert!(m.velocity.x.abs() > REST_SPEED && m.velocity.y.abs() > REST_SPEED);
Expand Down
Loading
Loading