Merge PR #189: gameinput: the keyboard's keys from its raw input, not 240 askings every 8 ms

This commit is contained in:
DoubleGhosty
2026-12-01 10:55:34 +01:00

View File

@ -1134,7 +1134,7 @@ mod host {
use windows_sys::Win32::System::Threading::GetCurrentProcessId;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW,
MAPVK_VK_TO_VSC_EX, MapVirtualKeyW,
};
use windows_sys::Win32::UI::Input::XboxController::{
XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK,
@ -1191,6 +1191,7 @@ mod host {
pub(super) struct Host {
empty_until: [Option<Instant>; XINPUT_PADS],
dualsense: dualsense::Controllers,
keyboard: keyboard::Keyboard,
}
impl Source for Host {
@ -1230,16 +1231,8 @@ mod host {
fn keys(&mut self) -> Vec<KeyState> {
let mut down = scripted();
if focused() {
// Left/right modifier keys only, as devices report them; no
// mouse buttons (below 0x08).
let held: Vec<u8> = (0x08..=0xFE_u8)
.filter(|vk| !(0x10..=0x12).contains(vk) && !down.contains(vk))
// SAFETY: plain queries.
.filter(|&vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0)
.collect();
down.extend(held);
}
let held: Vec<u8> = self.keyboard.held(focused()).into_iter().filter(|vk| !down.contains(vk)).collect();
down.extend(held);
down.into_iter()
.map(|vk| KeyState {
// SAFETY: plain query.
@ -1307,6 +1300,250 @@ mod host {
.collect()
}
/// The keyboard's keys held, from the keyboard's raw input
/// (`VICTORY_RAW_KEYS=0`: every key asked at every poll, as before).
///
/// Asking Windows about each of 240 keys every 8 ms was 30,000 calls a
/// second, 0.4 of a core in a drive (wpr profile), on a CPU whose
/// cores the title's threads, the pipelines and the streaming fill.
/// Raw input tells of each press and release; at each poll only the
/// keys held are asked about (a release raw input missed does not
/// stick), and every [`FULL_EVERY`](keyboard) polls, and when focus
/// comes back, all of them. A key held that raw input never told of,
/// three such times in a row: raw input is off for the rest of the run.
mod keyboard {
use windows_sys::Win32::Foundation::HWND;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
use windows_sys::Win32::UI::Input::{
GetRawInputData, HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTHEADER, RID_INPUT, RIDEV_INPUTSINK,
RIM_TYPEKEYBOARD, RegisterRawInputDevices,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DispatchMessageW, HWND_MESSAGE, MSG, PM_REMOVE, PeekMessageW, RI_KEY_BREAK, RI_KEY_E0,
WM_INPUT,
};
/// Polls between askings about every key.
const FULL_EVERY: u32 = 32;
/// A key the title is told of: left/right modifier keys only, as
/// devices report them; no mouse buttons (below 0x08).
pub(super) fn counted(vk: u8) -> bool {
(0x08..=0xFE).contains(&vk) && !(0x10..=0x12).contains(&vk)
}
fn down(vk: u8) -> bool {
// SAFETY: a plain query.
unsafe { GetAsyncKeyState(i32::from(vk)) < 0 }
}
/// Every key the title is told of that is down, asked one by one.
fn all_down() -> Vec<u8> {
(0..=0xFF_u8).filter(|&vk| counted(vk) && down(vk)).collect()
}
/// The key of a raw keyboard report: shift, control and alt by side.
pub(super) fn sided(vkey: u16, make: u16, flags: u32) -> Option<u8> {
let e0 = flags & RI_KEY_E0 != 0;
let vk = match vkey {
0x10 if make == 0x36 => 0xA1,
0x10 => 0xA0,
0x11 if e0 => 0xA3,
0x11 => 0xA2,
0x12 if e0 => 0xA5,
0x12 => 0xA4,
other => u8::try_from(other).ok()?,
};
counted(vk).then_some(vk)
}
/// A message-only window of the polling thread's, given the
/// keyboard's raw input even while another window has focus.
struct Raw {
window: usize,
thread: std::thread::ThreadId,
}
impl Raw {
fn new() -> Option<Raw> {
let class: Vec<u16> = "STATIC\0".encode_utf16().collect();
// SAFETY: a system class; a message-only window with no
// procedure of ours.
let window: HWND = unsafe {
CreateWindowExW(
0,
class.as_ptr(),
std::ptr::null(),
0,
0,
0,
0,
0,
HWND_MESSAGE,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null(),
)
};
if window.is_null() {
return None;
}
let device = RAWINPUTDEVICE { usUsagePage: 1, usUsage: 6, dwFlags: RIDEV_INPUTSINK, hwndTarget: window };
// SAFETY: one device description.
if unsafe { RegisterRawInputDevices(&device, 1, size_of::<RAWINPUTDEVICE>() as u32) } == 0 {
return None;
}
Some(Raw { window: window as usize, thread: std::thread::current().id() })
}
/// Takes the reports that came, into `held`.
fn drain(&self, held: &mut [bool; 256]) {
// SAFETY: zeroed is a valid MSG.
let mut msg: MSG = unsafe { std::mem::zeroed() };
// SAFETY: our window, on its thread.
while unsafe { PeekMessageW(&mut msg, self.window as HWND, WM_INPUT, WM_INPUT, PM_REMOVE) } != 0 {
let mut input = RAWINPUT::default();
let mut size = size_of::<RAWINPUT>() as u32;
// SAFETY: the report the message names, into room for one.
let got = unsafe {
GetRawInputData(
msg.lParam as HRAWINPUT,
RID_INPUT,
(&raw mut input).cast(),
&mut size,
size_of::<RAWINPUTHEADER>() as u32,
)
};
if got != u32::MAX && input.header.dwType == RIM_TYPEKEYBOARD {
// SAFETY: a keyboard report.
let k = unsafe { input.data.keyboard };
let flags = u32::from(k.Flags);
if let Some(vk) = sided(k.VKey, k.MakeCode, flags) {
held[usize::from(vk)] = flags & RI_KEY_BREAK == 0;
}
}
// The system's cleanup of the report.
// SAFETY: the message just taken.
unsafe { DispatchMessageW(&msg) };
}
}
}
pub(in super::super) struct Keyboard {
raw: Option<Raw>,
tried: bool,
held: [bool; 256],
was_focused: bool,
polls: u32,
/// Full askings in a row that found a key raw input missed.
missed: u32,
}
impl Default for Keyboard {
fn default() -> Keyboard {
Keyboard { raw: None, tried: false, held: [false; 256], was_focused: false, polls: 0, missed: 0 }
}
}
fn raw_on() -> bool {
std::env::var_os("VICTORY_RAW_KEYS").is_none_or(|v| v != "0")
}
/// Raw input reaches the window: a press and release of F24 sent.
#[test]
#[ignore = "sends a key press (F24) to the desktop"]
fn raw_input_tells_of_a_key_sent() {
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP, SendInput,
};
let raw = Raw::new().expect("a raw input window");
let key = |flags| INPUT {
r#type: INPUT_KEYBOARD,
Anonymous: INPUT_0 { ki: KEYBDINPUT { wVk: 0x87, wScan: 0, dwFlags: flags, time: 0, dwExtraInfo: 0 } },
};
let mut held = [false; 256];
// SAFETY: one input description.
unsafe { SendInput(1, &key(0), size_of::<INPUT>() as i32) };
std::thread::sleep(std::time::Duration::from_millis(50));
raw.drain(&mut held);
assert!(held[0x87], "the press was told");
// SAFETY: as above.
unsafe { SendInput(1, &key(KEYEVENTF_KEYUP), size_of::<INPUT>() as i32) };
std::thread::sleep(std::time::Duration::from_millis(50));
raw.drain(&mut held);
assert!(!held[0x87], "the release was told");
}
impl Keyboard {
/// The keys held; none without focus.
pub(in super::super) fn held(&mut self, focused: bool) -> Vec<u8> {
// Made on the thread that polls: the first poll is the
// starter's, the rest the polling thread's.
let here = std::thread::current().id();
if raw_on() && (!self.tried || self.raw.as_ref().is_some_and(|r| r.thread != here)) {
self.tried = true;
self.raw = Raw::new();
self.was_focused = false;
if self.raw.is_none() {
tracing::info!("keyboard: no raw input, every key asked at every poll");
}
}
let Some(raw) = &self.raw else {
return if focused { all_down() } else { Vec::new() };
};
raw.drain(&mut self.held);
if !focused {
self.was_focused = false;
return Vec::new();
}
self.polls = self.polls.wrapping_add(1);
if !self.was_focused || self.polls.is_multiple_of(FULL_EVERY) {
let all = all_down();
if self.was_focused && all.iter().any(|&vk| !self.held[usize::from(vk)]) {
self.missed += 1;
if self.missed >= 3 {
tracing::warn!("keyboard: raw input missed keys; every key asked at every poll from now on");
self.raw = None;
}
} else {
self.missed = 0;
}
self.held = [false; 256];
for &vk in &all {
self.held[usize::from(vk)] = true;
}
self.was_focused = true;
return all;
}
// Asked about: a release raw input missed does not stick.
(0..=0xFF_u8)
.filter(|&vk| {
let i = usize::from(vk);
if self.held[i] && !down(vk) {
self.held[i] = false;
}
self.held[i] && counted(vk)
})
.collect()
}
}
}
#[test]
fn raw_keys_name_shift_control_and_alt_by_side() {
use windows_sys::Win32::UI::WindowsAndMessaging::RI_KEY_E0;
assert_eq!(keyboard::sided(0x10, 0x2A, 0), Some(0xA0));
assert_eq!(keyboard::sided(0x10, 0x36, 0), Some(0xA1));
assert_eq!(keyboard::sided(0x11, 0x1D, 0), Some(0xA2));
assert_eq!(keyboard::sided(0x11, 0x1D, RI_KEY_E0), Some(0xA3));
assert_eq!(keyboard::sided(0x12, 0x38, 0), Some(0xA4));
assert_eq!(keyboard::sided(0x12, 0x38, RI_KEY_E0), Some(0xA5));
assert_eq!(keyboard::sided(0x41, 0x1E, 0), Some(0x41));
// A report's fake key, and mouse buttons: not keys.
assert_eq!(keyboard::sided(0xFF, 0, 0), None);
assert_eq!(keyboard::sided(0x01, 0, 0), None);
}
/// The foreground window is one of ours (the title's or our fallback).
fn focused() -> bool {
let mut process = 0;