diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index 5dfb218..331cf8c 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -248,9 +248,29 @@ fn display_size() -> (u32, u32) { }) } -/// The console's mode list: one 4K mode at 60 Hz (the title looks -/// for a 120 Hz one to allow 120 Hz frame intervals). -/// shortcut: fixed mode, not the host display's; report the host's rates if +/// The refresh rates the mode list offers: 60 Hz, and with +/// `VICTORY_DISPLAY_REFRESH=` (61..=240, e.g. 120) that rate too, as a +/// console on a television with a faster mode lists it. The title looks for +/// a 120 Hz mode to allow 120 Hz frame intervals. +fn refresh_rates() -> &'static [u32] { + static RATES: std::sync::OnceLock> = std::sync::OnceLock::new(); + RATES.get_or_init(|| { + let mut rates = vec![60]; + if let Some(hz) = std::env::var("VICTORY_DISPLAY_REFRESH").ok().and_then(|v| v.trim().parse::().ok()) { + if (61..=240).contains(&hz) { + rates.push(hz); + } else { + tracing::warn!(hz, "VICTORY_DISPLAY_REFRESH outside 61..=240: ignored"); + } + } + tracing::info!(?rates, "display refresh rates reported to the title"); + rates + }) +} + +/// The console's mode list: the display size at each rate of +/// [`refresh_rates`] (by default one mode at 60 Hz). +/// shortcut: fixed modes, not the host display's; report the host's rates if /// a title paces by them. extern "system" fn modes( _: This, @@ -263,26 +283,32 @@ extern "system" fn modes( let Some(count) = (unsafe { count.as_mut() }) else { return E_INVALIDARG; }; + let rates = refresh_rates(); + let n = rates.len() as u32; if out.is_null() { - *count = 1; + *count = n; return S_OK; } - if *count < 1 { + // As DXGI: what fits is written; a short buffer says so and keeps its count. + let fits = (*count).min(n) as usize; + let (width, height) = display_size(); + for (i, &hz) in rates.iter().take(fits).enumerate() { + let mode = Mode { + width, + height, + refresh: [hz, 1], + format: 0, + scanlines: 1, // progressive + scaling: 0, + flags: 0, + }; + // SAFETY: checked non-null; `i` < the title's `count`. + unsafe { out.add(i).write(mode) }; + } + if *count < n { return MORE_DATA; } - *count = 1; - let (width, height) = display_size(); - let mode = Mode { - width, - height, - refresh: [60, 1], - format: 0, - scanlines: 1, // progressive - scaling: 0, - flags: 0, - }; - // SAFETY: checked non-null; room for `count` >= 1 modes. - unsafe { out.write(mode) }; + *count = n; S_OK } diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 8bf432f..c745e81 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -39,6 +39,25 @@ fn clock() -> std::sync::MutexGuard<'static, Option> { CLOCK.lock().unwrap_or_else(|e| e.into_inner()) } +/// `VICTORY_FRAME_INTERVAL_US=`: frames begin every `n` microseconds +/// whatever interval the title sets (16667: 60 a second, 8333: 120, 1000: +/// as fast as frames are made). The title sets 33,333 us (30 a second) +/// against the 60 Hz mode it is offered; it times its own frames with the +/// performance counter, so a shorter interval is a higher frame rate, not a +/// faster game. Values outside 1,000..=1,000,000 are ignored. +fn interval_override() -> Option { + static OVERRIDE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *OVERRIDE.get_or_init(|| { + let us = std::env::var("VICTORY_FRAME_INTERVAL_US").ok()?.trim().parse::().ok()?; + let interval = (1_000..=1_000_000).contains(&us).then(|| Duration::from_micros(us)); + match interval { + Some(interval) => tracing::info!(?interval, "VICTORY_FRAME_INTERVAL_US: frame interval overridden"), + None => tracing::warn!(us, "VICTORY_FRAME_INTERVAL_US outside 1000..=1000000: ignored"), + } + interval + }) +} + /// Device method: a frame every `length` microseconds. The period is how /// many intervals a frame may take to reach the display (pipeline depth), /// not part of the rate. @@ -46,14 +65,15 @@ pub(crate) extern "system" fn set_interval( _: This, _output: This, length: u32, - _period: u32, - _flags: u32, + period: u32, + flags: u32, ) -> HRESULT { - let interval = match length { + let asked = match length { 0 => SIXTIETH, us => Duration::from_micros(u64::from(us)), }; - tracing::info!(?interval, "frame interval"); + let interval = interval_override().unwrap_or(asked); + tracing::info!(?asked, ?interval, period, flags, "frame interval"); // A new interval starts from now, after the last tick handed out. let first = LAST .iter() @@ -105,7 +125,7 @@ fn next_tick(kind: u32) -> (u64, Duration) { let mut clock = clock(); let c = clock.get_or_insert_with(|| Clock { start: Instant::now(), - interval: SIXTIETH, + interval: interval_override().unwrap_or(SIXTIETH), first: 0, }); let elapsed = c.start.elapsed().as_nanos(); diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index d8e7056..9cf1666 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1241,30 +1241,34 @@ mod host { } } + /// A scripted key's virtual key: a letter, a digit, or `Enter`, `Esc`, + /// `Tab`, `Back`, `Up`, `Down`, `Left`, `Right`. + fn key_code(name: &str) -> Option { + Some(match name.trim() { + "Enter" => 0x0D, + "Esc" => 0x1B, + "Tab" => 0x09, + "Back" => 0x08, + "Up" => 0x26, + "Down" => 0x28, + "Left" => 0x25, + "Right" => 0x27, + k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => k.as_bytes()[0].to_ascii_uppercase(), + _ => return None, + }) + } + /// Debugging aid: `VICTORY_KEYS=:,...` holds each key for /// 0.2 s that long after input starts (`-:`: all that - /// time), with or without focus. A key is a - /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, - /// `Left`, `Right` (the stand-in pad's table maps them to buttons). + /// time), with or without focus. Keys as [`key_code`] names them (the + /// stand-in pad's table maps them to buttons). Also the keys of + /// [`live`] (`VICTORY_KEYS_FILE`). fn scripted() -> Vec { static SCRIPT: LazyLock<(Instant, Vec<(Duration, Duration, u8)>)> = LazyLock::new(|| { let list = std::env::var("VICTORY_KEYS").unwrap_or_default(); let keys = list.split(',').filter_map(|entry| { let (at, key) = entry.split_once(':')?; - let vk = match key.trim() { - "Enter" => 0x0D, - "Esc" => 0x1B, - "Tab" => 0x09, - "Back" => 0x08, - "Up" => 0x26, - "Down" => 0x28, - "Left" => 0x25, - "Right" => 0x27, - k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => { - k.as_bytes()[0].to_ascii_uppercase() - } - _ => return None, - }; + let vk = key_code(key)?; let time = |t: &str| Duration::try_from_secs_f64(t.trim().parse().ok()?).ok(); let (from, to) = match at.split_once('-') { Some((from, to)) => (time(from)?, time(to)?), @@ -1276,10 +1280,107 @@ mod host { }); let (start, keys) = &*SCRIPT; let now = start.elapsed(); - keys.iter() + let mut down: Vec = keys + .iter() .filter(|&&(from, to, _)| (from..to).contains(&now)) .map(|&(_, _, vk)| vk) - .collect() + .collect(); + for vk in live() { + if !down.contains(&vk) { + down.push(vk); + } + } + down + } + + /// A key [`live`] holds: from `from` for `hold`. + struct LiveKey { + from: Instant, + hold: Duration, + vk: u8, + } + + /// One line of `VICTORY_KEYS_FILE`: ` [ []]`, held + /// 0.2 s by default, starting `after` seconds after it is read (0 by + /// default). `None` for a line that says nothing of the kind. + fn live_line(line: &str, read: Instant) -> Option { + let mut words = line.split_whitespace(); + let vk = key_code(words.next()?)?; + let mut seconds = || words.next().and_then(|w| w.parse::().ok()).and_then(|s| Duration::try_from_secs_f64(s).ok()); + let hold = seconds().unwrap_or(Duration::from_millis(200)).min(Duration::from_secs(60)); + let after = seconds().unwrap_or_default().min(Duration::from_secs(600)); + Some(LiveKey { from: read + after, hold, vk }) + } + + /// Debugging aid for a driver outside the process: + /// `VICTORY_KEYS_FILE=`, a text file the driver appends lines to + /// while the title runs, each ` [ []]` + /// (keys as [`key_code`] names them), e.g. `Enter`, `W 3` (walk ahead for + /// three seconds) or `Enter 0.2 5`. A thread of ours reads what was + /// appended every 50 ms; lines in the file before the run are skipped. + /// With or without focus, as [`scripted`]. The keys held now. + fn live() -> Vec { + use std::io::{Read, Seek, SeekFrom}; + use std::sync::Mutex; + static KEYS: Mutex> = Mutex::new(Vec::new()); + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let Some(path) = std::env::var_os("VICTORY_KEYS_FILE") else { return }; + tracing::info!(file = %std::path::Path::new(&path).display(), "keys are read from a file as it grows (VICTORY_KEYS_FILE)"); + let _ = std::thread::Builder::new().name("victory-keys-file".into()).spawn(move || { + // Skip what is there already. + let mut at = std::fs::metadata(&path).map_or(0, |m| m.len()); + let mut rest = String::new(); + loop { + std::thread::sleep(Duration::from_millis(50)); + let Ok(mut file) = std::fs::File::open(&path) else { continue }; + let len = file.metadata().map_or(0, |m| m.len()); + if len < at { + // Emptied or replaced: read it from the start. + at = 0; + rest.clear(); + } + if len == at || file.seek(SeekFrom::Start(at)).is_err() { + continue; + } + let mut bytes = Vec::new(); + let Ok(n) = file.read_to_end(&mut bytes) else { continue }; + at += n as u64; + rest.push_str(&String::from_utf8_lossy(&bytes)); + let read = Instant::now(); + // Whole lines only; a line still being written waits. + let Some(end) = rest.rfind('\n') else { continue }; + let lines: String = rest.drain(..=end).collect(); + let mut keys = KEYS.lock().unwrap_or_else(|e| e.into_inner()); + for line in lines.lines().filter(|l| !l.trim().is_empty()) { + match live_line(line, read) { + Some(key) => keys.push(key), + None => tracing::warn!(line, "VICTORY_KEYS_FILE: not a key line"), + } + } + } + }); + }); + let now = Instant::now(); + let mut keys = KEYS.lock().unwrap_or_else(|e| e.into_inner()); + keys.retain(|k| now < k.from + k.hold); + keys.iter().filter(|k| k.from <= now).map(|k| k.vk).collect() + } + + #[test] + fn live_key_lines() { + let t = Instant::now(); + let k = live_line("Enter", t).unwrap(); + assert_eq!((k.vk, k.from, k.hold), (0x0D, t, Duration::from_millis(200))); + let k = live_line(" w 3 ", t).unwrap(); + assert_eq!((k.vk, k.hold), (b'W', Duration::from_secs(3))); + let k = live_line("Up 0.5 2", t).unwrap(); + assert_eq!((k.vk, k.from, k.hold), (0x26, t + Duration::from_secs(2), Duration::from_millis(500))); + // Holds are kept to a minute; unknown keys and bad numbers say nothing or fall back. + assert_eq!(live_line("S 999", t).unwrap().hold, Duration::from_secs(60)); + assert_eq!(live_line("D x", t).unwrap().hold, Duration::from_millis(200)); + assert!(live_line("Shift", t).is_none()); + assert!(live_line("", t).is_none()); } /// The foreground window is one of ours (the title's or our fallback).