diff --git a/README.md b/README.md index 4ff657b..5a854de 100644 --- a/README.md +++ b/README.md @@ -161,10 +161,11 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic | `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | | `VICTORY_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready | +| `VICTORY_PIPELINE_WORKERS=16` | use this many pipeline worker threads (1-64) instead of half the logical processors, 2-8 by default | | `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | | `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | -| `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | +| `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^14 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | | `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) | | `VICTORY_XMA_DUMP=` | saves the first 32 XMA voices' context and input | diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 713c1cb..81ca373 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1226,6 +1226,15 @@ impl State { let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] let why = |_: &str| {}; + // A call whose pipeline is not made yet cannot run. That is common + // while the world builds its pipelines; drop it before refreshing and + // clamping records nothing will read. + if crate::pipeline::host_pipeline(self.pipeline as This).is_none() { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); + why("no host pipeline"); + return false; + } let len = u64::from(stride) * u64::from(max.max(1)); let Some(args) = crate::shadow::find(arguments, len) else { why("arguments outside title buffers"); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index d82338a..0a57b81 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1599,7 +1599,12 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { for_pieces(dst as usize, len, 64 << 10, |at, n| { if !write(at, n) { for_pieces(at, n, 4 << 10, |at, n| { - write(at, n); + // Wine does not write into write-watched pages not written + // since they were committed (ERROR_PARTIAL_COPY), but reads + // into them. The kernel checks this destination as well. + if !write(at, n) { + read(src.wrapping_add(at - dst as usize), at as *mut u8, n); + } }); } }); diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 4e949a6..de0b092 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -1121,9 +1121,14 @@ mod state { } with_state(this, |list, s| s.dispatch_mesh(list, x)); } - /// `DispatchMeshX(x, flags, indirect arguments, payload)`. - /// shortcut: dispatches whose group count is in GPU memory (indirect) - /// are dropped; make them ExecuteIndirect when the title uses them. + /// `DispatchMeshX(x, flags, indirect arguments, payload)`. With + /// `indirect` set, the group counts are in GPU memory at that title + /// address: one mesh dispatch record, `x, y, z` (12 bytes), run as an + /// indirect execution of one record like ExecuteIndirect's mesh signature, + /// so earlier GPU work that wrote the counts is seen. + /// shortcut: the record layout is assumed to be the mesh dispatch + /// arguments the title's ExecuteIndirect signatures use, and `x` is + /// ignored then; not yet checked against the title. pub(super) extern "system" fn dispatch_mesh_x( this: This, x: u32, @@ -1133,12 +1138,29 @@ mod state { ) { super::count_draw(); if indirect != 0 { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); + let mut ran = false; + with_state(this, |list, s| { + ran = s.execute_indirect(list, (MESH_INDIRECT, MESH_RECORD, 1), indirect, None); + }); + if !ran { + super::INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + address = format!("{indirect:#x}"), + "an indirect mesh dispatch dropped (first time)" + ) + }); + } return; } with_state(this, |list, s| s.dispatch_mesh(list, x)); } + /// The indirect argument kind of a mesh dispatch + /// (`State::execute_indirect`). + const MESH_INDIRECT: u32 = 10; + /// Bytes of one mesh dispatch record: three u32 group counts. + const MESH_RECORD: u32 = 12; pub(super) extern "system" fn draw_indexed( this: This, indices: u32, diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index 5ee0a0a..691cb9f 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -12,13 +12,15 @@ //! graphics state); the next run hands those to the workers at //! creation, during loading. //! -//! All library calls are serialised: the interface does not promise that -//! stores, loads and serialising may overlap. +//! Stores and serialising are serialised. Loads run outside that lock on a +//! reference of the library's own: vkd3d-proton keeps no compiled code in its +//! library, so there a load is a whole compile and holding the lock would make +//! the workers wait for one another. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, LazyLock, Mutex, OnceLock}; use windows::Win32::Graphics::Direct3D12::*; use windows::core::{HSTRING, Interface, PCWSTR}; @@ -47,12 +49,17 @@ struct Library { stored: HashSet, } -// SAFETY: D3D12 objects are free-threaded; every call is made under the -// mutex that holds the library. +// SAFETY: D3D12 pipeline libraries are internally synchronised except for +// same-name loads, which `LOADS` serialises; stores and serialising are under +// the mutex that holds the library. unsafe impl Send for Library {} const LIBRARY_FILE: &str = "host-pipelines.bin"; const EARLY_FILE: &str = "early-pipelines.txt"; +/// Loads of the same pipeline serialise (the host documents that one as not +/// thread-safe); loads of different pipelines may overlap. +static LOADS: LazyLock>>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); /// Title pipelines listed for an early start, at most. const EARLY_MAX: usize = 8192; @@ -154,10 +161,23 @@ pub(crate) fn pipeline( MADE.fetch_add(1, Ordering::Relaxed); return create(); }; - if let Ok(pso) = load( - &library.lock().unwrap_or_else(|e| e.into_inner()).library, - PCWSTR(wide.as_ptr()), - ) { + // A load can be a whole compile under vkd3d-proton, whose library keeps + // no compiled code; do not hold the store/serialise lock across it. The + // host requires only same-name loads to serialise, so those get a lock of + // their own and different pipelines still load in parallel. + let handle = library + .lock() + .unwrap_or_else(|e| e.into_inner()) + .library + .clone(); + let same = LOADS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry(name.to_owned()) + .or_default() + .clone(); + let _same = same.lock().unwrap_or_else(|e| e.into_inner()); + if let Ok(pso) = load(&handle, PCWSTR(wide.as_ptr())) { LOADED.fetch_add(1, Ordering::Relaxed); return Ok(pso); } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 2c8f9d5..d3ae1ea 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -248,11 +248,24 @@ fn wait(p: &Pending, frame: u64) { /// which runs on it (reserved address space; committed only as used). const PIPELINE_STACK: usize = 64 << 20; -/// Starts the pipeline workers (half the logical processors, 2 to 8) once. +/// Pipeline workers: half the logical processors, 2 to 8, unless +/// `VICTORY_PIPELINE_WORKERS` names a count (1 to 64). Driver compiles of the +/// world's largest programs bound a first run with an empty pipeline library. +fn worker_count(asked: Option<&str>, processors: usize) -> usize { + asked + .and_then(|v| v.trim().parse::().ok()) + .map_or((processors / 2).clamp(2, 8), |n| n.clamp(1, 64)) +} + +/// Starts the pipeline workers once. fn ensure_workers() -> bool { static WORKERS: OnceLock = OnceLock::new(); *WORKERS.get_or_init(|| { - let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8)); + let workers = worker_count( + std::env::var("VICTORY_PIPELINE_WORKERS").ok().as_deref(), + std::thread::available_parallelism().map_or(4, |n| n.get()), + ); + tracing::info!(workers, "host pipeline workers"); let mut started = 0; for i in 0..workers { let spawned = std::thread::Builder::new() @@ -262,12 +275,9 @@ fn ensure_workers() -> bool { // on a world compute program and refused it as out of memory. .stack_size(PIPELINE_STACK) .spawn(move || { - // Below the title's own threads (loading, recording). - // SAFETY: a plain call on our own thread. - unsafe { - use windows::Win32::System::Threading::*; - let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); - } + // At the title's own priority: below it, the world's busy + // threads starved the workers, and draws stayed dropped + // until their pipelines existed. loop { let p = { let (lock, ready) = &WORK; @@ -318,6 +328,17 @@ fn drained() { mod tests { use super::*; + #[test] + fn worker_count_takes_the_switch_within_bounds() { + assert_eq!(worker_count(None, 20), 8); + assert_eq!(worker_count(None, 2), 2); + assert_eq!(worker_count(Some("16"), 20), 16); + assert_eq!(worker_count(Some(" 3 "), 20), 3); + assert_eq!(worker_count(Some("0"), 20), 1); + assert_eq!(worker_count(Some("1000"), 20), 64); + assert_eq!(worker_count(Some("many"), 12), 6); + } + /// A first use queues the pipeline and, within the budget, gets the /// worker's answer (here: no host pipeline for no shaders). #[test] diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 3639fda..266cb22 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1,6 +1,6 @@ //! `gameinput.dll`: input devices from the host. Gamepads come from XInput -//! (host slots 0-3); while none is connected, the keyboard drives one -//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own +//! (host slots 0-3); while none is active, the keyboard drives one stand-in +//! gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own //! too. A poll thread turns host state into readings (a new one per change) //! and runs device callbacks on connect and disconnect. #![allow(non_snake_case)] @@ -93,6 +93,24 @@ struct PadState { right_y: f32, } +/// XInput rest thresholds (`XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE` and +/// `XINPUT_GAMEPAD_TRIGGER_THRESHOLD`), so virtual or untouched controllers +/// do not silence the keyboard stand-in pad. +const STICK_DEADZONE: f32 = 8689.0 / 32767.0; +const TRIGGER_DEADZONE: f32 = 30.0 / 255.0; + +impl PadState { + fn is_active(&self) -> bool { + self.buttons != 0 + || self.left_trigger > TRIGGER_DEADZONE + || self.right_trigger > TRIGGER_DEADZONE + || self.left_x.abs() > STICK_DEADZONE + || self.left_y.abs() > STICK_DEADZONE + || self.right_x.abs() > STICK_DEADZONE + || self.right_y.abs() > STICK_DEADZONE + } +} + /// One key held down: scan code (0xE0xx when extended), character, key. #[repr(C)] #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -320,6 +338,9 @@ struct Slot { struct State { slots: [Slot; DEVICES], + /// Host pad slots that have reported input outside rest thresholds since + /// connecting (cleared when all host pads are idle and fallback keys fire). + engaged: [bool; PADS], callbacks: Vec, /// Asynchronous enumerations, delivered by the next poll. pending: Vec, @@ -366,6 +387,7 @@ impl Hub { source: Mutex::new(source), state: Mutex::new(State { slots: Default::default(), + engaged: [false; PADS], callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), @@ -454,11 +476,26 @@ impl State { ) -> Vec { let now = now(); let mut events = std::mem::take(&mut self.pending); - let any_pad = pads.iter().any(Option::is_some); + let mut any_active = false; + for (slot, pad) in pads.iter().enumerate() { + match pad { + Some(p) if p.is_active() => { + self.engaged[slot] = true; + any_active = true; + } + None => self.engaged[slot] = false, + _ => {} + } + } + let stand_in = fallback(&keys); + if !any_active && stand_in != PadState::default() { + self.engaged = [false; PADS]; + } + let using_pad = self.engaged.iter().any(|&e| e); for (slot, pad) in pads.into_iter().enumerate() { self.update(devices, slot, pad.map(Value::Pad), now, &mut events); } - let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys))); + let fallback = (!using_pad).then_some(Value::Pad(stand_in)); self.update(devices, FALLBACK, fallback, now, &mut events); self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); events @@ -602,7 +639,7 @@ extern "system" fn current_reading( }; let found = if device.is_null() { (0..DEVICES) - .filter(|&i| state.slots[i].connected) + .filter(|&i| state.slots[i].connected && (i >= PADS || state.engaged[i])) .filter_map(newest) .max_by_key(|r| r.timestamp) } else { @@ -1627,4 +1664,109 @@ mod tests { rumble(device, std::ptr::null()); assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); } + + fn current_any(hub: &Hub, kind: u32) -> Result<*const Reading, HRESULT> { + type Current = extern "system" fn(This, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let hr = + slot::(&hub.object, 0x20)(&hub.object, kind, std::ptr::null(), &mut out); + result(hr, out) + } + + #[test] + fn idle_host_pads_keep_the_keyboard_stand_in_until_active() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, GAMEPAD_KIND, 2, &log); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + // 1. An all-zero virtual XInput pad (e.g. a keyboard presenting an unused + // XInput slot) connects its own slot without disconnecting `FALLBACK`. + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + assert_eq!(log.lock().unwrap()[1..], [(0, STATUS_CONNECTED, 0)]); + + host.lock().unwrap().keys = vec![key(0x0D), key(b'W')]; + hub.poll(); + let stand_in = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!( + pad(stand_in), + PadState { + buttons: A, + left_y: 1.0, + ..Default::default() + } + ); + release(stand_in); + + // Sub-deadzone stick/trigger drift on slot 0 does not steal null-device + // `GetCurrentReading(GAMEPAD_KIND, null)` away from `FALLBACK`. + std::thread::sleep(Duration::from_millis(2)); + host.lock().unwrap().pads[0] = Some(PadState { + left_x: 0.15, + right_y: -0.20, + left_trigger: 0.05, + ..Default::default() + }); + hub.poll(); + let any = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(any).buttons, A); + release(any); + + // Releasing keys keeps `FALLBACK` connected and reports the neutral edge. + host.lock().unwrap().keys.clear(); + hub.poll(); + let rest = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(rest), PadState::default()); + release(rest); + + // 2. Real input outside deadzone on slot 1 disconnects `FALLBACK` and + // takes priority even while slot 0 keeps sub-deadzone jitter. + let active_pad = PadState { + buttons: B, + left_x: 0.6, + ..Default::default() + }; + host.lock().unwrap().pads[1] = Some(active_pad); + hub.poll(); + assert_eq!( + log.lock().unwrap()[2..], + [(1, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] + ); + assert_eq!( + current(hub, GAMEPAD_KIND, FALLBACK), + Err(DEVICE_DISCONNECTED) + ); + + std::thread::sleep(Duration::from_millis(2)); + host.lock().unwrap().pads[0] = Some(PadState { + left_x: 0.12, + ..Default::default() + }); + hub.poll(); + let any = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(any), active_pad); + release(any); + + // Releasing the physical controller back to neutral keeps pad mode engaged + // without reconnecting `FALLBACK` between button presses. + host.lock().unwrap().pads[1] = Some(PadState::default()); + hub.poll(); + assert_eq!( + current(hub, GAMEPAD_KIND, FALLBACK), + Err(DEVICE_DISCONNECTED) + ); + let neutral_pad = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(neutral_pad), PadState::default()); + release(neutral_pad); + + // 3. Pressing a fallback key while all host pads are idle hands control + // back to `FALLBACK` cleanly. + host.lock().unwrap().keys = vec![key(0x0D)]; + hub.poll(); + assert_eq!(log.lock().unwrap()[4..], [(FALLBACK, STATUS_CONNECTED, 0)]); + let back = current_any(hub, GAMEPAD_KIND).unwrap(); + assert_eq!(pad(back).buttons, A); + release(back); + } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index e7454e3..6e56ebe 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -273,7 +273,9 @@ struct Lower<'a> { /// until the driver resets it. A lane that reaches the limit leaves the /// program as killed (a pixel discards). // shortcut: a genuine loop of more iterations than this is cut short too. -pub(super) const LOOP_LIMIT: u32 = 1 << 20; +// 2^20 was not low enough: a runaway data-dependent loop can outlast the +// driver's reset and freeze the desktop. 2^14 bounds it to milliseconds per wave. +pub(super) const LOOP_LIMIT: u32 = 1 << 14; /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar /// compares, bit tests) are ballots of the lanes' booleans, taken where the diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b33b892..36dc441 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -110,7 +110,7 @@ pub use shader::{ ADDRESS_MAP_SPACE, DESCRIPTOR_WORDS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, }; -/// The loop limit without an override: 2^20. +/// The loop limit without an override: 2^14. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; /// The iteration count after which a translated loop is left, per lane and @@ -118,8 +118,8 @@ pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; /// /// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or /// `0x` hex, at least 1) sets it instead. A loop that hits the limit in -/// every lane of a full-screen pass still runs for seconds (2^20 times a -/// 4K screen is about 10^13 iterations); a much lower limit shows whether +/// every lane of a full-screen pass still runs long (2^14 times a 4K +/// screen is about 10^11 iterations); a much lower limit shows whether /// such loops are what makes a frame slow. The value is part of the /// translation, so the shader cache must key on it (`victory-gpu`'s does). pub fn loop_limit() -> u32 {