gameinput.rs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. //! `gameinput.dll`: input devices from the host. Gamepads come from XInput
  2. //! (host slots 0-3); while none is connected, the keyboard drives one
  3. //! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own
  4. //! too. A poll thread turns host state into readings (a new one per change)
  5. //! and runs device callbacks on connect and disconnect.
  6. #![allow(non_snake_case)]
  7. // Title code calls these through the objects, passing pointers the real API
  8. // would trust.
  9. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  10. use std::collections::VecDeque;
  11. use std::ffi::c_void;
  12. use std::ops::Deref;
  13. use std::ptr::NonNull;
  14. use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
  15. use std::sync::{Condvar, LazyLock, Mutex, MutexGuard, PoisonError};
  16. use std::thread::ThreadId;
  17. use std::time::{Duration, Instant};
  18. use super::xasync::{E_INVALIDARG, E_NOTIMPL};
  19. use super::xgameruntime::{HRESULT, S_OK};
  20. use crate::{HleExport, HleModule};
  21. /// The documented errors.
  22. pub const DEVICE_DISCONNECTED: HRESULT = 0x838A_0001_u32 as i32;
  23. pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32;
  24. pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32;
  25. pub const REFERENCE_TOO_OLD: HRESULT = 0x838A_0004_u32 as i32;
  26. const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
  27. /// Input kinds (bits) our devices have.
  28. const KEYBOARD_KIND: u32 = 0x10;
  29. const GAMEPAD_KIND: u32 = 0x4_0000;
  30. /// Device status of a connected device: connected, input enabled.
  31. const STATUS_CONNECTED: u32 = 0x3;
  32. const ASYNC_ENUMERATION: u32 = 1;
  33. /// Gamepad buttons; the title maps each bit to one of its pad buttons.
  34. const MENU: u32 = 0x1;
  35. const VIEW: u32 = 0x2;
  36. const A: u32 = 0x4;
  37. const B: u32 = 0x8;
  38. const X: u32 = 0x10;
  39. const Y: u32 = 0x20;
  40. const UP: u32 = 0x40;
  41. const DOWN: u32 = 0x80;
  42. const LEFT: u32 = 0x100;
  43. const RIGHT: u32 = 0x200;
  44. const LEFT_SHOULDER: u32 = 0x400;
  45. const RIGHT_SHOULDER: u32 = 0x800;
  46. const LEFT_STICK: u32 = 0x1000;
  47. const RIGHT_STICK: u32 = 0x2000;
  48. /// Devices: host pad slots, the keyboard's stand-in pad, the keyboard.
  49. const PADS: usize = 4;
  50. const FALLBACK: usize = PADS;
  51. const KEYBOARD: usize = PADS + 1;
  52. const DEVICES: usize = PADS + 2;
  53. /// Readings kept per device for next/previous lookups.
  54. const HISTORY: usize = 256;
  55. const POLL: Duration = Duration::from_millis(8);
  56. /// The keyboard's stand-in gamepad (virtual key, button); README lists it.
  57. /// Sticks: W/A/S/D left, I/J/K/L right; triggers Z and C.
  58. const FALLBACK_BUTTONS: [(u8, u32); 14] = [
  59. (0x1B, MENU), // Esc
  60. (0x09, VIEW), // Tab
  61. (0x0D, A), // Enter
  62. (0x08, B), // Backspace
  63. (b'X', X),
  64. (b'Y', Y),
  65. (0x26, UP), // arrows
  66. (0x28, DOWN),
  67. (0x25, LEFT),
  68. (0x27, RIGHT),
  69. (b'Q', LEFT_SHOULDER),
  70. (b'E', RIGHT_SHOULDER),
  71. (b'F', LEFT_STICK),
  72. (b'H', RIGHT_STICK),
  73. ];
  74. /// A gamepad reading: triggers 0 to 1, sticks -1 to 1 (up positive).
  75. #[repr(C)]
  76. #[derive(Clone, Copy, Debug, Default, PartialEq)]
  77. struct PadState {
  78. buttons: u32,
  79. left_trigger: f32,
  80. right_trigger: f32,
  81. left_x: f32,
  82. left_y: f32,
  83. right_x: f32,
  84. right_y: f32,
  85. }
  86. /// One key held down: scan code (0xE0xx when extended), character, key.
  87. #[repr(C)]
  88. #[derive(Clone, Copy, Debug, Default, PartialEq)]
  89. struct KeyState {
  90. scan_code: u32,
  91. code_point: u32,
  92. virtual_key: u8,
  93. dead_key: bool,
  94. }
  95. const _: () = assert!(size_of::<KeyState>() == 12 && size_of::<PadState>() == 28);
  96. /// Host input, or a fake in tests.
  97. trait Source: Send {
  98. /// The pad in host slot `slot`, `None` when the slot is empty.
  99. fn pad(&mut self, slot: usize) -> Option<PadState>;
  100. /// Keys held down; none while the title's window lacks focus.
  101. fn keys(&mut self) -> Vec<KeyState>;
  102. /// Motor speeds: low frequency (left), high frequency (right).
  103. fn rumble(&mut self, slot: usize, low: u16, high: u16);
  104. }
  105. fn fallback(keys: &[KeyState]) -> PadState {
  106. let on = |vk: u8| {
  107. if keys.iter().any(|k| k.virtual_key == vk) {
  108. 1.0
  109. } else {
  110. 0.0
  111. }
  112. };
  113. PadState {
  114. buttons: FALLBACK_BUTTONS
  115. .iter()
  116. .filter(|(vk, _)| on(*vk) != 0.0)
  117. .fold(0, |all, (_, bit)| all | bit),
  118. left_trigger: on(b'Z'),
  119. right_trigger: on(b'C'),
  120. left_x: on(b'D') - on(b'A'),
  121. left_y: on(b'W') - on(b'S'),
  122. right_x: on(b'L') - on(b'J'),
  123. right_y: on(b'I') - on(b'K'),
  124. }
  125. }
  126. /// Two pads as one: buttons of both, and of each axis and trigger the one
  127. /// pushed further.
  128. fn merged(a: PadState, b: PadState) -> PadState {
  129. let further = |x: f32, y: f32| if y.abs() > x.abs() { y } else { x };
  130. PadState {
  131. buttons: a.buttons | b.buttons,
  132. left_trigger: further(a.left_trigger, b.left_trigger),
  133. right_trigger: further(a.right_trigger, b.right_trigger),
  134. left_x: further(a.left_x, b.left_x),
  135. left_y: further(a.left_y, b.left_y),
  136. right_x: further(a.right_x, b.right_x),
  137. right_y: further(a.right_y, b.right_y),
  138. }
  139. }
  140. /// Whether the title sees one pad that is always there, fed by the keyboard
  141. /// and by every host pad (on by default; `VICTORY_ONE_PAD=0` shows each host
  142. /// pad as a device of its own, and the stand-in only while there is none).
  143. /// The title keeps to the pad it started with: with the stand-in taken away
  144. /// when a pad was switched on, it showed its controller-disconnected screen
  145. /// until the pad was off again. It also keeps a pad the host lists twice (its
  146. /// own slot and a remapper's) from being two players.
  147. fn one_pad() -> bool {
  148. std::env::var_os("VICTORY_ONE_PAD").is_none_or(|v| v != "0")
  149. }
  150. #[repr(C)]
  151. struct Table<const N: usize>([*const (); N]);
  152. // SAFETY: function addresses only.
  153. unsafe impl<const N: usize> Sync for Table<N> {}
  154. /// The input object; one per hub.
  155. #[repr(C)]
  156. pub struct Object {
  157. vtable: &'static Table<22>,
  158. hub: *const Hub,
  159. }
  160. #[repr(C)]
  161. pub struct Device {
  162. vtable: &'static Table<21>,
  163. hub: *const Hub,
  164. index: usize,
  165. info: DeviceInfo,
  166. }
  167. /// What a device says about itself. The title reads `id` (+0x20); the rest
  168. /// follows the public layout and is zero where we have nothing to say.
  169. #[repr(C)]
  170. #[derive(Default)]
  171. #[allow(dead_code)] // read by title code
  172. struct DeviceInfo {
  173. size: u32,
  174. vendor: u16,
  175. product: u16,
  176. revision: u16,
  177. interface: u8,
  178. collection: u8,
  179. usage: [u16; 2],
  180. versions: [u16; 8],
  181. id: [u8; 32],
  182. root_id: [u8; 32],
  183. family: i32,
  184. capabilities: u32,
  185. supported_input: u32,
  186. rumble_motors: u32,
  187. /// Counts and optional detail pointers.
  188. rest: [u64; 26],
  189. }
  190. const _: () = assert!(std::mem::offset_of!(DeviceInfo, id) == 0x20);
  191. fn kind(index: usize) -> u32 {
  192. if index == KEYBOARD {
  193. KEYBOARD_KIND
  194. } else {
  195. GAMEPAD_KIND
  196. }
  197. }
  198. impl Device {
  199. fn new(index: usize) -> Device {
  200. let mut id = [0; 32];
  201. id[..7].copy_from_slice(b"victory");
  202. id[31] = index as u8 + 1;
  203. let info = DeviceInfo {
  204. size: size_of::<DeviceInfo>() as u32,
  205. id,
  206. root_id: id,
  207. supported_input: kind(index),
  208. // Low and high frequency.
  209. rumble_motors: if index <= FALLBACK { 0x3 } else { 0 },
  210. ..Default::default()
  211. };
  212. Device {
  213. vtable: &DEVICE,
  214. hub: std::ptr::null(),
  215. index,
  216. info,
  217. }
  218. }
  219. fn hub(&self) -> &'static Hub {
  220. // SAFETY: set by `Hub::new`; hubs are never freed.
  221. unsafe { &*self.hub }
  222. }
  223. }
  224. #[derive(PartialEq)]
  225. enum Value {
  226. Pad(PadState),
  227. Keys(Vec<KeyState>),
  228. }
  229. #[repr(C)]
  230. pub struct Reading {
  231. vtable: &'static Table<25>,
  232. refs: AtomicU32,
  233. device: *const Device,
  234. sequence: u64,
  235. timestamp: u64,
  236. value: Value,
  237. }
  238. impl Reading {
  239. fn kind(&self) -> u32 {
  240. match self.value {
  241. Value::Pad(_) => GAMEPAD_KIND,
  242. Value::Keys(_) => KEYBOARD_KIND,
  243. }
  244. }
  245. }
  246. /// A counted reference to a reading.
  247. struct Ref(NonNull<Reading>);
  248. impl Ref {
  249. fn new(reading: Reading) -> Ref {
  250. Ref(NonNull::from(Box::leak(Box::new(reading))))
  251. }
  252. /// Another reference, for the title.
  253. fn share(&self) -> *const Reading {
  254. reading_add_ref(self.0.as_ptr());
  255. self.0.as_ptr()
  256. }
  257. }
  258. impl Deref for Ref {
  259. type Target = Reading;
  260. fn deref(&self) -> &Reading {
  261. // SAFETY: we hold a reference, so it is alive.
  262. unsafe { self.0.as_ref() }
  263. }
  264. }
  265. impl Drop for Ref {
  266. fn drop(&mut self) {
  267. reading_release(self.0.as_ptr());
  268. }
  269. }
  270. type DeviceCallback = extern "system" fn(u64, *mut c_void, *const Device, u64, u32, u32);
  271. #[derive(Clone, Copy)]
  272. struct Registration {
  273. token: u64,
  274. /// One device's address, or 0 for any.
  275. device: usize,
  276. kind: u32,
  277. status: u32,
  278. context: usize,
  279. callback: DeviceCallback,
  280. }
  281. impl Registration {
  282. fn matches(&self, devices: &[Device; DEVICES], index: usize) -> bool {
  283. kind(index) & self.kind != 0
  284. && (self.device == 0 || self.device == &devices[index] as *const Device as usize)
  285. }
  286. fn event(&self, device: usize, timestamp: u64, current: u32, previous: u32) -> Event {
  287. Event {
  288. registration: *self,
  289. device,
  290. timestamp,
  291. current,
  292. previous,
  293. }
  294. }
  295. }
  296. struct Event {
  297. registration: Registration,
  298. device: usize,
  299. timestamp: u64,
  300. current: u32,
  301. previous: u32,
  302. }
  303. #[derive(Default)]
  304. struct Slot {
  305. connected: bool,
  306. sequence: u64,
  307. history: VecDeque<Ref>,
  308. }
  309. struct State {
  310. slots: [Slot; DEVICES],
  311. callbacks: Vec<Registration>,
  312. /// Asynchronous enumerations, delivered by the next poll.
  313. pending: Vec<Event>,
  314. /// Device callbacks running now: token and thread.
  315. running: Vec<(u64, ThreadId)>,
  316. }
  317. pub struct Hub {
  318. object: Object,
  319. devices: [Device; DEVICES],
  320. /// Apart from the state: XInput can be slow, and the title reads
  321. /// readings every frame.
  322. source: Mutex<Box<dyn Source>>,
  323. /// The title sees one pad ([`one_pad`]).
  324. one_pad: bool,
  325. state: Mutex<State>,
  326. /// A device callback returned.
  327. returned: Condvar,
  328. }
  329. fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
  330. mutex.lock().unwrap_or_else(PoisonError::into_inner)
  331. }
  332. // SAFETY: the back pointers are set before the hub is shared and never
  333. // change; what changes sits behind the mutex or is atomic.
  334. unsafe impl Send for Hub {}
  335. // SAFETY: as above.
  336. unsafe impl Sync for Hub {}
  337. static START: LazyLock<Instant> = LazyLock::new(Instant::now);
  338. /// Microseconds, the clock of every timestamp we hand out.
  339. fn now() -> u64 {
  340. START.elapsed().as_micros() as u64
  341. }
  342. impl Hub {
  343. fn new(source: Box<dyn Source>, one_pad: bool) -> &'static Hub {
  344. let hub = Box::into_raw(Box::new(Hub {
  345. object: Object {
  346. vtable: &INPUT,
  347. hub: std::ptr::null(),
  348. },
  349. devices: std::array::from_fn(Device::new),
  350. source: Mutex::new(source),
  351. one_pad,
  352. state: Mutex::new(State {
  353. slots: Default::default(),
  354. callbacks: Vec::new(),
  355. pending: Vec::new(),
  356. running: Vec::new(),
  357. }),
  358. returned: Condvar::new(),
  359. }));
  360. // SAFETY: just allocated and never freed; nothing else sees it yet.
  361. unsafe {
  362. (*hub).object.hub = hub;
  363. for device in &mut (*hub).devices {
  364. device.hub = hub;
  365. }
  366. &*hub
  367. }
  368. }
  369. /// A hub over the host's input, polled from now on.
  370. fn start(source: Box<dyn Source>) -> &'static Hub {
  371. let hub = Hub::new(source, one_pad());
  372. hub.poll();
  373. std::thread::spawn(move || {
  374. loop {
  375. std::thread::sleep(POLL);
  376. hub.poll();
  377. }
  378. });
  379. hub
  380. }
  381. fn state(&self) -> MutexGuard<'_, State> {
  382. lock(&self.state)
  383. }
  384. /// Reads the host once; device callbacks run on the calling thread.
  385. fn poll(&self) {
  386. let (pads, keys) = {
  387. let mut source = lock(&self.source);
  388. let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot));
  389. (pads, source.keys())
  390. };
  391. let events = self.state().poll(&self.devices, self.one_pad, pads, keys);
  392. self.deliver(events);
  393. }
  394. /// Runs callbacks, never under our lock: they call back into us. One
  395. /// unregistered since the event was taken does not run, and
  396. /// `UnregisterCallback` waits for one that runs.
  397. fn deliver(&self, events: Vec<Event>) {
  398. let me = std::thread::current().id();
  399. for e in events {
  400. let r = e.registration;
  401. {
  402. let mut state = self.state();
  403. if !state.callbacks.iter().any(|c| c.token == r.token) {
  404. continue;
  405. }
  406. state.running.push((r.token, me));
  407. }
  408. (r.callback)(
  409. r.token,
  410. r.context as *mut c_void,
  411. &self.devices[e.device],
  412. e.timestamp,
  413. e.current,
  414. e.previous,
  415. );
  416. let mut state = self.state();
  417. if let Some(i) = state.running.iter().position(|&x| x == (r.token, me)) {
  418. state.running.swap_remove(i);
  419. }
  420. self.returned.notify_all();
  421. }
  422. }
  423. fn index(&self, device: *const Device) -> Option<usize> {
  424. self.devices.iter().position(|d| std::ptr::eq(d, device))
  425. }
  426. }
  427. impl State {
  428. fn poll(
  429. &mut self,
  430. devices: &[Device; DEVICES],
  431. one_pad: bool,
  432. pads: [Option<PadState>; PADS],
  433. keys: Vec<KeyState>,
  434. ) -> Vec<Event> {
  435. let now = now();
  436. let mut events = std::mem::take(&mut self.pending);
  437. if one_pad {
  438. let pad = pads.into_iter().flatten().fold(fallback(&keys), merged);
  439. self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events);
  440. self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events);
  441. return events;
  442. }
  443. let any_pad = pads.iter().any(Option::is_some);
  444. for (slot, pad) in pads.into_iter().enumerate() {
  445. self.update(devices, slot, pad.map(Value::Pad), now, &mut events);
  446. }
  447. let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys)));
  448. self.update(devices, FALLBACK, fallback, now, &mut events);
  449. self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events);
  450. events
  451. }
  452. /// Records a device's state: a reading when it changed, callbacks when
  453. /// the device came or went.
  454. fn update(
  455. &mut self,
  456. devices: &[Device; DEVICES],
  457. index: usize,
  458. value: Option<Value>,
  459. now: u64,
  460. events: &mut Vec<Event>,
  461. ) {
  462. let slot = &mut self.slots[index];
  463. let was = slot.connected;
  464. slot.connected = value.is_some();
  465. if let Some(value) = value
  466. && (!was || slot.history.back().is_none_or(|r| r.value != value))
  467. {
  468. slot.sequence += 1;
  469. if slot.history.len() == HISTORY {
  470. slot.history.pop_front();
  471. }
  472. slot.history.push_back(Ref::new(Reading {
  473. vtable: &READING,
  474. refs: AtomicU32::new(1),
  475. device: &devices[index],
  476. sequence: slot.sequence,
  477. timestamp: now,
  478. value,
  479. }));
  480. }
  481. if was != slot.connected {
  482. tracing::info!(device = index, connected = !was, "input device");
  483. let (current, previous) = if was {
  484. (0, STATUS_CONNECTED)
  485. } else {
  486. (STATUS_CONNECTED, 0)
  487. };
  488. events.extend(
  489. self.callbacks
  490. .iter()
  491. .filter(|r| r.matches(devices, index) && r.status & STATUS_CONNECTED != 0)
  492. .map(|r| r.event(index, now, current, previous)),
  493. );
  494. }
  495. }
  496. }
  497. #[cfg(windows)]
  498. fn host() -> Box<dyn Source> {
  499. Box::new(host::Host::default())
  500. }
  501. #[cfg(not(windows))]
  502. fn host() -> Box<dyn Source> {
  503. struct Nothing;
  504. impl Source for Nothing {
  505. fn pad(&mut self, _: usize) -> Option<PadState> {
  506. None
  507. }
  508. fn keys(&mut self) -> Vec<KeyState> {
  509. Vec::new()
  510. }
  511. fn rumble(&mut self, _: usize, _: u16, _: u16) {}
  512. }
  513. Box::new(Nothing)
  514. }
  515. static HUB: LazyLock<&'static Hub> = LazyLock::new(|| Hub::start(host()));
  516. type This = *const Object;
  517. type Out = *mut *const c_void;
  518. /// The DLL's only export (ordinal 1): the input object, static and shared.
  519. pub extern "system" fn GameInputCreate(out: *mut This) -> HRESULT {
  520. tracing::info!("GameInputCreate");
  521. if out.is_null() {
  522. return E_INVALIDARG;
  523. }
  524. // SAFETY: checked non-null; the title passes room for a pointer.
  525. unsafe { out.write(&HUB.object) };
  526. S_OK
  527. }
  528. fn hub(this: This) -> &'static Hub {
  529. // SAFETY: `this` is a hub's object; hubs are never freed.
  530. unsafe { &*(*this).hub }
  531. }
  532. /// Clears a COM out pointer and returns `hr`.
  533. fn fail(out: Out, hr: HRESULT) -> HRESULT {
  534. if !out.is_null() {
  535. // SAFETY: checked non-null; the title passes room for a pointer.
  536. unsafe { out.write(std::ptr::null()) };
  537. }
  538. hr
  539. }
  540. /// Gives the title a reference to `reading`, or fails as with none.
  541. fn hand(out: Out, reading: Option<&Ref>) -> HRESULT {
  542. match reading {
  543. _ if out.is_null() => E_INVALIDARG,
  544. Some(reading) => {
  545. // SAFETY: checked non-null; the title passes room for a pointer.
  546. unsafe { out.write(reading.share().cast()) };
  547. S_OK
  548. }
  549. None => fail(out, READING_NOT_FOUND),
  550. }
  551. }
  552. extern "system" fn no_interface(_: *const c_void, _iid: *const c_void, out: Out) -> HRESULT {
  553. tracing::warn!("input QueryInterface not implemented");
  554. fail(out, E_NOINTERFACE)
  555. }
  556. /// The input object and devices live as long as the process.
  557. extern "system" fn add_ref(_: *const c_void) -> u32 {
  558. 1
  559. }
  560. extern "system" fn timestamp(_: This) -> u64 {
  561. now()
  562. }
  563. extern "system" fn current_reading(
  564. this: This,
  565. kind: u32,
  566. device: *const Device,
  567. out: Out,
  568. ) -> HRESULT {
  569. let hub = hub(this);
  570. let state = hub.state();
  571. let newest = |i: usize| {
  572. state.slots[i]
  573. .history
  574. .back()
  575. .filter(|r| r.kind() & kind != 0)
  576. };
  577. let found = if device.is_null() {
  578. (0..DEVICES)
  579. .filter(|&i| state.slots[i].connected)
  580. .filter_map(newest)
  581. .max_by_key(|r| r.timestamp)
  582. } else {
  583. match hub.index(device) {
  584. None => return fail(out, E_INVALIDARG),
  585. Some(i) if !state.slots[i].connected => return fail(out, DEVICE_DISCONNECTED),
  586. Some(i) => newest(i),
  587. }
  588. };
  589. tracing::trace!(
  590. kind = format_args!("{kind:#x}"),
  591. device = ?hub.index(device),
  592. sequence = found.map(|r| r.sequence),
  593. "current reading"
  594. );
  595. hand(out, found)
  596. }
  597. /// The reading after (`forward`) or before `reference` on its device.
  598. fn relative(
  599. this: This,
  600. reference: *const Reading,
  601. kind: u32,
  602. device: *const Device,
  603. out: Out,
  604. forward: bool,
  605. ) -> HRESULT {
  606. if reference.is_null() {
  607. return fail(out, E_INVALIDARG);
  608. }
  609. let hub = hub(this);
  610. // SAFETY: a reading we handed out and the title still holds.
  611. let reference = unsafe { &*reference };
  612. // shortcut: with no device given only the reference's device is walked,
  613. // not every device's readings in time order; the title walks
  614. // only keyboard readings (one device) and the current pad's previous one.
  615. let Some(index) = hub.index(reference.device) else {
  616. return fail(out, E_INVALIDARG);
  617. };
  618. if !device.is_null() && !std::ptr::eq(device, reference.device) {
  619. return fail(out, E_INVALIDARG);
  620. }
  621. let state = hub.state();
  622. let history = &state.slots[index].history;
  623. if history
  624. .front()
  625. .is_none_or(|oldest| reference.sequence < oldest.sequence)
  626. {
  627. return fail(out, REFERENCE_TOO_OLD);
  628. }
  629. let wanted = |r: &&Ref| r.kind() & kind != 0;
  630. let found = if forward {
  631. history
  632. .iter()
  633. .filter(|r| r.sequence > reference.sequence)
  634. .find(wanted)
  635. } else {
  636. history
  637. .iter()
  638. .rev()
  639. .filter(|r| r.sequence < reference.sequence)
  640. .find(wanted)
  641. };
  642. hand(out, found)
  643. }
  644. extern "system" fn next_reading(
  645. this: This,
  646. reference: *const Reading,
  647. kind: u32,
  648. device: *const Device,
  649. out: Out,
  650. ) -> HRESULT {
  651. relative(this, reference, kind, device, out, true)
  652. }
  653. extern "system" fn previous_reading(
  654. this: This,
  655. reference: *const Reading,
  656. kind: u32,
  657. device: *const Device,
  658. out: Out,
  659. ) -> HRESULT {
  660. relative(this, reference, kind, device, out, false)
  661. }
  662. /// The device's reading at `time`, among those still kept.
  663. extern "system" fn temporal_reading(
  664. this: This,
  665. time: u64,
  666. device: *const Device,
  667. out: Out,
  668. ) -> HRESULT {
  669. let hub = hub(this);
  670. let Some(index) = hub.index(device) else {
  671. return fail(out, E_INVALIDARG);
  672. };
  673. let state = hub.state();
  674. let history = &state.slots[index].history;
  675. hand(out, history.iter().rev().find(|r| r.timestamp <= time))
  676. }
  677. static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1);
  678. fn token(out: *mut u64) -> HRESULT {
  679. if !out.is_null() {
  680. // SAFETY: checked non-null.
  681. unsafe { out.write(NEXT_TOKEN.fetch_add(1, Ordering::Relaxed)) };
  682. }
  683. S_OK
  684. }
  685. // shortcut: reading callbacks never run; the title registers none
  686. // (it polls).
  687. extern "system" fn register_reading(
  688. _: This,
  689. _device: *const c_void,
  690. _kind: u32,
  691. _threshold: f32,
  692. _context: *mut c_void,
  693. _callback: *const c_void,
  694. out: *mut u64,
  695. ) -> HRESULT {
  696. tracing::warn!("input reading callbacks are never called");
  697. token(out)
  698. }
  699. /// Device callbacks run on our poll thread when a device comes or goes.
  700. /// Enumeration reports the devices already there: blocking on the caller's
  701. /// thread before we return (the title registers holding a lock its callback
  702. /// takes again), asynchronous on the next poll.
  703. extern "system" fn register_device(
  704. this: This,
  705. device: *const Device,
  706. kind: u32,
  707. status: u32,
  708. enumeration: u32,
  709. context: *mut c_void,
  710. callback: Option<DeviceCallback>,
  711. out: *mut u64,
  712. ) -> HRESULT {
  713. let Some(callback) = callback else {
  714. return E_INVALIDARG;
  715. };
  716. let hub = hub(this);
  717. let registration = Registration {
  718. token: NEXT_TOKEN.fetch_add(1, Ordering::Relaxed),
  719. device: device as usize,
  720. kind,
  721. status,
  722. context: context as usize,
  723. callback,
  724. };
  725. let mut found = Vec::new();
  726. {
  727. let mut state = hub.state();
  728. if enumeration != 0 && status & STATUS_CONNECTED != 0 {
  729. let now = now();
  730. found = (0..DEVICES)
  731. .filter(|&i| state.slots[i].connected && registration.matches(&hub.devices, i))
  732. .map(|i| registration.event(i, now, STATUS_CONNECTED, 0))
  733. .collect();
  734. }
  735. tracing::info!(
  736. kind = format_args!("{kind:#x}"),
  737. enumeration,
  738. devices = found.len(),
  739. "input device callback"
  740. );
  741. state.callbacks.push(registration);
  742. if enumeration == ASYNC_ENUMERATION {
  743. state.pending.append(&mut found);
  744. }
  745. }
  746. if !out.is_null() {
  747. // SAFETY: checked non-null.
  748. unsafe { out.write(registration.token) };
  749. }
  750. hub.deliver(found);
  751. S_OK
  752. }
  753. /// Guide button and keyboard layout callbacks: neither ever changes here.
  754. extern "system" fn register_other(
  755. _: This,
  756. _device: *const c_void,
  757. _context: *mut c_void,
  758. _callback: *const c_void,
  759. out: *mut u64,
  760. ) -> HRESULT {
  761. token(out)
  762. }
  763. fn forget(this: This, token: u64) {
  764. let mut state = hub(this).state();
  765. state.callbacks.retain(|r| r.token != token);
  766. state.pending.retain(|e| e.registration.token != token);
  767. }
  768. extern "system" fn stop_callback(this: This, token: u64) {
  769. forget(this, token);
  770. }
  771. /// Stops the callback, then waits up to `timeout` µs for a call of it that
  772. /// is running; false on time-out, or from inside that callback (it cannot
  773. /// wait for itself), as documented. Either way it is never called again.
  774. extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> bool {
  775. forget(this, token);
  776. let hub = hub(this);
  777. let me = std::thread::current().id();
  778. let deadline = Instant::now().checked_add(Duration::from_micros(timeout));
  779. let mut state = hub.state();
  780. loop {
  781. let running = state.running.iter().filter(|r| r.0 == token);
  782. if running.clone().any(|r| r.1 == me) {
  783. return false;
  784. }
  785. if running.count() == 0 {
  786. return true;
  787. }
  788. state = match deadline {
  789. None => hub.returned.wait(state).unwrap_or_else(PoisonError::into_inner),
  790. Some(deadline) => {
  791. let Some(left) = deadline.checked_duration_since(Instant::now()) else {
  792. return false;
  793. };
  794. let waited = hub.returned.wait_timeout(state, left);
  795. waited.unwrap_or_else(PoisonError::into_inner).0
  796. }
  797. };
  798. }
  799. }
  800. /// Dispatcher and aggregate device: no title of ours asks for them.
  801. extern "system" fn create_dispatcher(_: This, out: Out) -> HRESULT {
  802. tracing::warn!("input dispatcher not implemented");
  803. fail(out, E_NOTIMPL)
  804. }
  805. extern "system" fn create_aggregate(_: This, _kind: u32, out: Out) -> HRESULT {
  806. tracing::warn!("aggregate input device not implemented");
  807. fail(out, E_NOTIMPL)
  808. }
  809. extern "system" fn find_by_id(this: This, id: *const [u8; 32], out: Out) -> HRESULT {
  810. if id.is_null() || out.is_null() {
  811. return fail(out, E_INVALIDARG);
  812. }
  813. // SAFETY: checked non-null; the title passes a device id.
  814. let id = unsafe { &*id };
  815. match hub(this).devices.iter().find(|d| d.info.id == *id) {
  816. Some(device) => {
  817. // SAFETY: checked non-null.
  818. unsafe { out.write((device as *const Device).cast()) };
  819. S_OK
  820. }
  821. None => fail(out, DEVICE_NOT_FOUND),
  822. }
  823. }
  824. /// Lookup by object, platform handle or platform string: our devices have
  825. /// none of these.
  826. extern "system" fn find_device(_: This, _value: *const c_void, out: Out) -> HRESULT {
  827. fail(out, DEVICE_NOT_FOUND)
  828. }
  829. extern "system" fn enable_oem_device(
  830. _: This,
  831. _vendor: u16,
  832. _product: u16,
  833. _interface: u8,
  834. _collection: u8,
  835. ) -> HRESULT {
  836. S_OK
  837. }
  838. extern "system" fn set_focus_policy(_: This, _policy: u32) {}
  839. static INPUT: Table<22> = Table([
  840. no_interface as *const (), // 0x00
  841. add_ref as *const (), // 0x08 AddRef
  842. add_ref as *const (), // 0x10 Release
  843. timestamp as *const (), // 0x18
  844. current_reading as *const (), // 0x20
  845. next_reading as *const (), // 0x28
  846. previous_reading as *const (), // 0x30
  847. temporal_reading as *const (), // 0x38
  848. register_reading as *const (), // 0x40
  849. register_device as *const (), // 0x48
  850. register_other as *const (), // 0x50 guide button
  851. register_other as *const (), // 0x58 keyboard layout
  852. stop_callback as *const (), // 0x60
  853. unregister_callback as *const (), // 0x68
  854. create_dispatcher as *const (), // 0x70
  855. create_aggregate as *const (), // 0x78
  856. find_by_id as *const (), // 0x80
  857. find_device as *const (), // 0x88 by object
  858. find_device as *const (), // 0x90 by platform handle
  859. find_device as *const (), // 0x98 by platform string
  860. enable_oem_device as *const (), // 0xa0
  861. set_focus_policy as *const (), // 0xa8
  862. ]);
  863. extern "system" fn device_info(this: *const Device) -> *const DeviceInfo {
  864. // SAFETY: one of our devices.
  865. unsafe { &(*this).info }
  866. }
  867. extern "system" fn device_status(this: *const Device) -> u32 {
  868. // SAFETY: one of our devices.
  869. let device = unsafe { &*this };
  870. if device.hub().state().slots[device.index].connected {
  871. STATUS_CONNECTED
  872. } else {
  873. 0
  874. }
  875. }
  876. // shortcut: trigger motors are dropped (XInput has none). The host API that
  877. // drives them without a redistributable is Windows.Gaming.Input (WinRT
  878. // `Gamepad.Vibration`), which needs WinRT bindings this crate lacks outside
  879. // diagnostics builds; the title sends trigger levels in slot 0x50.
  880. extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) {
  881. // SAFETY: one of our devices.
  882. let device = unsafe { &*this };
  883. let one_pad = device.hub().one_pad;
  884. if device.index >= PADS && !(one_pad && device.index == FALLBACK) {
  885. return;
  886. }
  887. let [low, high, ..] = if params.is_null() {
  888. [0.0; 4]
  889. } else {
  890. // SAFETY: checked non-null; four motor levels.
  891. unsafe { *params }
  892. };
  893. let speed = |level: f32| (level.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16;
  894. let mut source = lock(&device.hub().source);
  895. if one_pad {
  896. // The one pad is every host pad.
  897. for slot in 0..PADS {
  898. if source.pad(slot).is_some() {
  899. source.rumble(slot, speed(low), speed(high));
  900. }
  901. }
  902. } else {
  903. source.rumble(device.index, speed(low), speed(high));
  904. }
  905. }
  906. extern "system" fn unsupported<const SLOT: usize>(_: *const c_void) -> HRESULT {
  907. tracing::warn!(
  908. slot = format_args!("{SLOT:#x}"),
  909. "input device method not implemented"
  910. );
  911. E_NOTIMPL
  912. }
  913. static DEVICE: Table<21> = Table([
  914. no_interface as *const (), // 0x00
  915. add_ref as *const (), // 0x08 AddRef
  916. add_ref as *const (), // 0x10 Release
  917. device_info as *const (), // 0x18
  918. device_status as *const (), // 0x20
  919. unsupported::<0x28> as *const (), // battery
  920. unsupported::<0x30> as *const (), // force feedback
  921. unsupported::<0x38> as *const (), //
  922. unsupported::<0x40> as *const (), //
  923. unsupported::<0x48> as *const (), // haptics
  924. set_rumble as *const (), // 0x50
  925. unsupported::<0x58> as *const (), // input synchronization
  926. unsupported::<0x60> as *const (), //
  927. unsupported::<0x68> as *const (), // power off
  928. unsupported::<0x70> as *const (), // raw device access
  929. unsupported::<0x78> as *const (), //
  930. unsupported::<0x80> as *const (), //
  931. unsupported::<0x88> as *const (), //
  932. unsupported::<0x90> as *const (), //
  933. unsupported::<0x98> as *const (), //
  934. unsupported::<0xa0> as *const (), //
  935. ]);
  936. fn reading<'a>(this: *const Reading) -> &'a Reading {
  937. // SAFETY: a reading we handed out and the title still holds.
  938. unsafe { &*this }
  939. }
  940. extern "system" fn reading_add_ref(this: *const Reading) -> u32 {
  941. reading(this).refs.fetch_add(1, Ordering::Relaxed) + 1
  942. }
  943. extern "system" fn reading_release(this: *const Reading) -> u32 {
  944. let left = reading(this).refs.fetch_sub(1, Ordering::AcqRel) - 1;
  945. if left == 0 {
  946. // SAFETY: the last reference is gone; `Ref::new` boxed it.
  947. drop(unsafe { Box::from_raw(this.cast_mut()) });
  948. }
  949. left
  950. }
  951. extern "system" fn input_kind(this: *const Reading) -> u32 {
  952. reading(this).kind()
  953. }
  954. extern "system" fn sequence_number(this: *const Reading, kind: u32) -> u64 {
  955. let reading = reading(this);
  956. if reading.kind() & kind != 0 {
  957. reading.sequence
  958. } else {
  959. 0
  960. }
  961. }
  962. extern "system" fn reading_timestamp(this: *const Reading) -> u64 {
  963. reading(this).timestamp
  964. }
  965. extern "system" fn reading_device(this: *const Reading, out: *mut *const Device) {
  966. if !out.is_null() {
  967. // SAFETY: checked non-null; devices need no reference.
  968. unsafe { out.write(reading(this).device) };
  969. }
  970. }
  971. extern "system" fn key_count(this: *const Reading) -> u32 {
  972. match &reading(this).value {
  973. Value::Keys(keys) => keys.len() as u32,
  974. Value::Pad(_) => 0,
  975. }
  976. }
  977. extern "system" fn key_state(this: *const Reading, count: u32, out: *mut KeyState) -> u32 {
  978. let Value::Keys(keys) = &reading(this).value else {
  979. return 0;
  980. };
  981. if out.is_null() {
  982. return 0;
  983. }
  984. let n = keys.len().min(count as usize);
  985. // SAFETY: the title passes room for `count` keys.
  986. unsafe { std::ptr::copy_nonoverlapping(keys.as_ptr(), out, n) };
  987. n as u32
  988. }
  989. extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bool {
  990. match &reading(this).value {
  991. Value::Pad(state) if !out.is_null() => {
  992. // SAFETY: checked non-null.
  993. unsafe { out.write(*state) };
  994. true
  995. }
  996. _ => false,
  997. }
  998. }
  999. /// Kinds our devices do not have: no count, no state.
  1000. extern "system" fn nothing(_: *const c_void) -> usize {
  1001. 0
  1002. }
  1003. static READING: Table<25> = Table([
  1004. no_interface as *const (), // 0x00
  1005. reading_add_ref as *const (), // 0x08
  1006. reading_release as *const (), // 0x10
  1007. input_kind as *const (), // 0x18
  1008. sequence_number as *const (), // 0x20
  1009. reading_timestamp as *const (), // 0x28
  1010. reading_device as *const (), // 0x30
  1011. nothing as *const (), // 0x38 raw report
  1012. nothing as *const (), // 0x40 controller axes, buttons, switches
  1013. nothing as *const (), // 0x48
  1014. nothing as *const (), // 0x50
  1015. nothing as *const (), // 0x58
  1016. nothing as *const (), // 0x60
  1017. nothing as *const (), // 0x68
  1018. key_count as *const (), // 0x70
  1019. key_state as *const (), // 0x78
  1020. nothing as *const (), // 0x80 mouse
  1021. nothing as *const (), // 0x88 touch
  1022. nothing as *const (), // 0x90
  1023. nothing as *const (), // 0x98 motion
  1024. nothing as *const (), // 0xa0 arcade stick
  1025. nothing as *const (), // 0xa8 flight stick
  1026. gamepad_state as *const (), // 0xb0
  1027. nothing as *const (), // 0xb8 racing wheel
  1028. nothing as *const (), // 0xc0 UI navigation
  1029. ]);
  1030. pub(crate) fn module() -> HleModule {
  1031. HleModule {
  1032. name: "gameinput",
  1033. dlls: &["gameinput.dll"],
  1034. // Titles import it by ordinal only.
  1035. exports: vec![HleExport {
  1036. name: "#1",
  1037. address: GameInputCreate as *const () as usize,
  1038. }],
  1039. }
  1040. }
  1041. /// Host input: XInput pads, the keyboard while our process has focus.
  1042. #[cfg(windows)]
  1043. mod host {
  1044. use std::time::{Duration, Instant};
  1045. use windows_sys::Win32::System::Threading::GetCurrentProcessId;
  1046. use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
  1047. GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW,
  1048. };
  1049. use windows_sys::Win32::UI::Input::XboxController::{
  1050. XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK,
  1051. XINPUT_GAMEPAD_DPAD_DOWN, XINPUT_GAMEPAD_DPAD_LEFT, XINPUT_GAMEPAD_DPAD_RIGHT,
  1052. XINPUT_GAMEPAD_DPAD_UP, XINPUT_GAMEPAD_LEFT_SHOULDER, XINPUT_GAMEPAD_LEFT_THUMB,
  1053. XINPUT_GAMEPAD_RIGHT_SHOULDER, XINPUT_GAMEPAD_RIGHT_THUMB, XINPUT_GAMEPAD_START,
  1054. XINPUT_GAMEPAD_X, XINPUT_GAMEPAD_Y, XINPUT_STATE, XINPUT_VIBRATION, XInputGetState,
  1055. XInputSetState,
  1056. };
  1057. use windows_sys::Win32::UI::WindowsAndMessaging::{
  1058. GetForegroundWindow, GetWindowThreadProcessId,
  1059. };
  1060. use super::*;
  1061. /// Asking XInput about an empty slot is slow; look again this often.
  1062. const EMPTY_SLOT_RECHECK: Duration = Duration::from_secs(1);
  1063. const BUTTONS: [(u16, u32); 14] = [
  1064. (XINPUT_GAMEPAD_START, MENU),
  1065. (XINPUT_GAMEPAD_BACK, VIEW),
  1066. (XINPUT_GAMEPAD_A, A),
  1067. (XINPUT_GAMEPAD_B, B),
  1068. (XINPUT_GAMEPAD_X, X),
  1069. (XINPUT_GAMEPAD_Y, Y),
  1070. (XINPUT_GAMEPAD_DPAD_UP, UP),
  1071. (XINPUT_GAMEPAD_DPAD_DOWN, DOWN),
  1072. (XINPUT_GAMEPAD_DPAD_LEFT, LEFT),
  1073. (XINPUT_GAMEPAD_DPAD_RIGHT, RIGHT),
  1074. (XINPUT_GAMEPAD_LEFT_SHOULDER, LEFT_SHOULDER),
  1075. (XINPUT_GAMEPAD_RIGHT_SHOULDER, RIGHT_SHOULDER),
  1076. (XINPUT_GAMEPAD_LEFT_THUMB, LEFT_STICK),
  1077. (XINPUT_GAMEPAD_RIGHT_THUMB, RIGHT_STICK),
  1078. ];
  1079. /// Raw values, no dead zone: titles apply their own.
  1080. pub(super) fn convert(pad: &XINPUT_GAMEPAD) -> PadState {
  1081. let stick = |v: i16| (f32::from(v) / 32767.0).max(-1.0);
  1082. PadState {
  1083. buttons: BUTTONS
  1084. .iter()
  1085. .filter(|(host, _)| pad.wButtons & host != 0)
  1086. .fold(0, |all, (_, bit)| all | bit),
  1087. left_trigger: f32::from(pad.bLeftTrigger) / 255.0,
  1088. right_trigger: f32::from(pad.bRightTrigger) / 255.0,
  1089. left_x: stick(pad.sThumbLX),
  1090. left_y: stick(pad.sThumbLY),
  1091. right_x: stick(pad.sThumbRX),
  1092. right_y: stick(pad.sThumbRY),
  1093. }
  1094. }
  1095. #[derive(Default)]
  1096. pub(super) struct Host {
  1097. empty_until: [Option<Instant>; PADS],
  1098. }
  1099. impl Source for Host {
  1100. fn pad(&mut self, slot: usize) -> Option<PadState> {
  1101. if self.empty_until[slot].is_some_and(|until| Instant::now() < until) {
  1102. return None;
  1103. }
  1104. let mut state = XINPUT_STATE::default();
  1105. // SAFETY: room for the state.
  1106. if unsafe { XInputGetState(slot as u32, &mut state) } != 0 {
  1107. self.empty_until[slot] = Some(Instant::now() + EMPTY_SLOT_RECHECK);
  1108. return None;
  1109. }
  1110. self.empty_until[slot] = None;
  1111. #[allow(unused_mut)]
  1112. let mut pad = convert(&state.Gamepad);
  1113. // The scripted keys (`VICTORY_KEYS`) also press the first
  1114. // pad's buttons, by the stand-in pad's table: with a real pad
  1115. // connected the stand-in is not there, and a title that listens
  1116. // to the pad (the title's start screen) saw nothing.
  1117. if slot == 0 {
  1118. for vk in scripted() {
  1119. if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) {
  1120. pad.buttons |= button;
  1121. }
  1122. }
  1123. }
  1124. Some(pad)
  1125. }
  1126. fn keys(&mut self) -> Vec<KeyState> {
  1127. let mut down = scripted();
  1128. if focused() {
  1129. // Left/right modifier keys only, as devices report them; no
  1130. // mouse buttons (below 0x08).
  1131. let held: Vec<u8> = (0x08..=0xFE_u8)
  1132. .filter(|vk| !(0x10..=0x12).contains(vk) && !down.contains(vk))
  1133. // SAFETY: plain queries.
  1134. .filter(|&vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0)
  1135. .collect();
  1136. down.extend(held);
  1137. }
  1138. down.into_iter()
  1139. .map(|vk| KeyState {
  1140. // SAFETY: plain query.
  1141. scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) },
  1142. virtual_key: vk,
  1143. // shortcut: no characters (code point 0);
  1144. // the title reads scan codes and virtual keys only.
  1145. ..Default::default()
  1146. })
  1147. .collect()
  1148. }
  1149. fn rumble(&mut self, slot: usize, low: u16, high: u16) {
  1150. let speeds = XINPUT_VIBRATION {
  1151. wLeftMotorSpeed: low,
  1152. wRightMotorSpeed: high,
  1153. };
  1154. // SAFETY: a valid vibration; an empty slot just fails.
  1155. unsafe { XInputSetState(slot as u32, &speeds) };
  1156. }
  1157. }
  1158. /// Debugging aid: `VICTORY_KEYS=<seconds>:<key>,...` holds each key for
  1159. /// 0.2 s that long after input starts (`<from>-<to>:<key>`: all that
  1160. /// time), with or without focus. A key is a
  1161. /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`,
  1162. /// `Left`, `Right` (the stand-in pad's table maps them to buttons).
  1163. fn scripted() -> Vec<u8> {
  1164. static SCRIPT: LazyLock<(Instant, Vec<(Duration, Duration, u8)>)> = LazyLock::new(|| {
  1165. let list = std::env::var("VICTORY_KEYS").unwrap_or_default();
  1166. let keys = list.split(',').filter_map(|entry| {
  1167. let (at, key) = entry.split_once(':')?;
  1168. let vk = match key.trim() {
  1169. "Enter" => 0x0D,
  1170. "Esc" => 0x1B,
  1171. "Tab" => 0x09,
  1172. "Back" => 0x08,
  1173. "Up" => 0x26,
  1174. "Down" => 0x28,
  1175. "Left" => 0x25,
  1176. "Right" => 0x27,
  1177. k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => {
  1178. k.as_bytes()[0].to_ascii_uppercase()
  1179. }
  1180. _ => return None,
  1181. };
  1182. let time = |t: &str| Duration::try_from_secs_f64(t.trim().parse().ok()?).ok();
  1183. let (from, to) = match at.split_once('-') {
  1184. Some((from, to)) => (time(from)?, time(to)?),
  1185. None => (time(at)?, time(at)? + Duration::from_millis(200)),
  1186. };
  1187. Some((from, to, vk))
  1188. });
  1189. (Instant::now(), keys.collect())
  1190. });
  1191. let (start, keys) = &*SCRIPT;
  1192. let now = start.elapsed();
  1193. keys.iter()
  1194. .filter(|&&(from, to, _)| (from..to).contains(&now))
  1195. .map(|&(_, _, vk)| vk)
  1196. .collect()
  1197. }
  1198. /// The foreground window is one of ours (the title's or our fallback).
  1199. fn focused() -> bool {
  1200. let mut process = 0;
  1201. // SAFETY: plain queries; a null window gives process 0.
  1202. unsafe {
  1203. GetWindowThreadProcessId(GetForegroundWindow(), &mut process);
  1204. process == GetCurrentProcessId()
  1205. }
  1206. }
  1207. #[test]
  1208. fn host_pads_convert_to_console_pads() {
  1209. let pad = XINPUT_GAMEPAD {
  1210. wButtons: XINPUT_GAMEPAD_A | XINPUT_GAMEPAD_START | XINPUT_GAMEPAD_DPAD_LEFT,
  1211. bLeftTrigger: 255,
  1212. sThumbLX: -32768,
  1213. sThumbLY: 32767,
  1214. ..Default::default()
  1215. };
  1216. let state = convert(&pad);
  1217. assert_eq!(state.buttons, A | MENU | LEFT);
  1218. assert_eq!(
  1219. (
  1220. state.left_trigger,
  1221. state.left_x,
  1222. state.left_y,
  1223. state.right_x
  1224. ),
  1225. (1.0, -1.0, 1.0, 0.0)
  1226. );
  1227. }
  1228. }
  1229. #[cfg(test)]
  1230. mod tests {
  1231. use std::sync::Arc;
  1232. use super::*;
  1233. use crate::HleResolver;
  1234. use crate::HostPolicy;
  1235. use victory_loader::Provenance;
  1236. use victory_pe::ImportSymbol;
  1237. #[derive(Default)]
  1238. struct FakeHost {
  1239. pads: [Option<PadState>; PADS],
  1240. keys: Vec<KeyState>,
  1241. rumble: Vec<(usize, u16, u16)>,
  1242. }
  1243. struct Fake(Arc<Mutex<FakeHost>>);
  1244. impl Source for Fake {
  1245. fn pad(&mut self, slot: usize) -> Option<PadState> {
  1246. self.0.lock().unwrap().pads[slot]
  1247. }
  1248. fn keys(&mut self) -> Vec<KeyState> {
  1249. self.0.lock().unwrap().keys.clone()
  1250. }
  1251. fn rumble(&mut self, slot: usize, low: u16, high: u16) {
  1252. self.0.lock().unwrap().rumble.push((slot, low, high));
  1253. }
  1254. }
  1255. fn fake() -> (&'static Hub, Arc<Mutex<FakeHost>>) {
  1256. fake_with(false)
  1257. }
  1258. fn fake_with(one_pad: bool) -> (&'static Hub, Arc<Mutex<FakeHost>>) {
  1259. let host = Arc::new(Mutex::new(FakeHost::default()));
  1260. let hub = Hub::new(Box::new(Fake(Arc::clone(&host))), one_pad);
  1261. hub.poll();
  1262. (hub, host)
  1263. }
  1264. fn key(virtual_key: u8) -> KeyState {
  1265. KeyState {
  1266. scan_code: u32::from(virtual_key) + 0x100,
  1267. virtual_key,
  1268. ..Default::default()
  1269. }
  1270. }
  1271. fn slot<F: Copy, T>(object: *const T, offset: usize) -> F {
  1272. // SAFETY: our objects start with their table, which has the slot.
  1273. let f = unsafe { *(*(object as *const *const *const ())).add(offset / 8) };
  1274. // SAFETY: the caller names the slot's signature.
  1275. unsafe { std::mem::transmute_copy(&f) }
  1276. }
  1277. /// Device callbacks seen: device index, current and previous status.
  1278. type Log = Mutex<Vec<(usize, u32, u32)>>;
  1279. extern "system" fn record(
  1280. _token: u64,
  1281. context: *mut c_void,
  1282. device: *const Device,
  1283. _timestamp: u64,
  1284. current: u32,
  1285. previous: u32,
  1286. ) {
  1287. // SAFETY: the test passes its log and one of the hub's devices.
  1288. let (log, index) = unsafe { (&*(context as *const Log), (*device).index) };
  1289. log.lock().unwrap().push((index, current, previous));
  1290. }
  1291. fn register(hub: &Hub, kind: u32, enumeration: u32, log: &Log) -> u64 {
  1292. type Register = extern "system" fn(
  1293. This,
  1294. *const Device,
  1295. u32,
  1296. u32,
  1297. u32,
  1298. *mut c_void,
  1299. Option<DeviceCallback>,
  1300. *mut u64,
  1301. ) -> HRESULT;
  1302. let mut token = 0;
  1303. let context = log as *const Log as *mut c_void;
  1304. let register = slot::<Register, _>(&hub.object, 0x48);
  1305. let hr = register(
  1306. &hub.object,
  1307. std::ptr::null(),
  1308. kind,
  1309. 1,
  1310. enumeration,
  1311. context,
  1312. Some(record),
  1313. &mut token,
  1314. );
  1315. assert_eq!(hr, S_OK);
  1316. assert_ne!(token, 0);
  1317. token
  1318. }
  1319. fn result(hr: HRESULT, out: *const c_void) -> Result<*const Reading, HRESULT> {
  1320. if hr == S_OK {
  1321. Ok(out.cast())
  1322. } else {
  1323. assert!(out.is_null());
  1324. Err(hr)
  1325. }
  1326. }
  1327. fn current(hub: &Hub, kind: u32, device: usize) -> Result<*const Reading, HRESULT> {
  1328. type Current = extern "system" fn(This, u32, *const Device, Out) -> HRESULT;
  1329. let mut out = std::ptr::null();
  1330. let hr = slot::<Current, _>(&hub.object, 0x20)(
  1331. &hub.object,
  1332. kind,
  1333. &hub.devices[device],
  1334. &mut out,
  1335. );
  1336. result(hr, out)
  1337. }
  1338. fn walk(hub: &Hub, offset: usize, from: *const Reading) -> Result<*const Reading, HRESULT> {
  1339. type Walk = extern "system" fn(This, *const Reading, u32, *const Device, Out) -> HRESULT;
  1340. let mut out = std::ptr::null();
  1341. let device = reading(from).device;
  1342. let hr =
  1343. slot::<Walk, _>(&hub.object, offset)(&hub.object, from, GAMEPAD_KIND, device, &mut out);
  1344. result(hr, out)
  1345. }
  1346. fn pad(reading: *const Reading) -> PadState {
  1347. let mut state = PadState::default();
  1348. let get =
  1349. slot::<extern "system" fn(*const Reading, *mut PadState) -> bool, _>(reading, 0xb0);
  1350. assert!(get(reading, &mut state));
  1351. state
  1352. }
  1353. fn stamp(reading: *const Reading) -> (u64, u64) {
  1354. let time = slot::<extern "system" fn(*const Reading) -> u64, _>(reading, 0x28);
  1355. let sequence = slot::<extern "system" fn(*const Reading, u32) -> u64, _>(reading, 0x20);
  1356. (time(reading), sequence(reading, GAMEPAD_KIND))
  1357. }
  1358. fn release(reading: *const Reading) {
  1359. slot::<extern "system" fn(*const Reading) -> u32, _>(reading, 0x10)(reading);
  1360. }
  1361. #[test]
  1362. fn ordinal_one_resolves_to_create() {
  1363. let r = HleResolver::new(HostPolicy::none());
  1364. assert_eq!(
  1365. r.classify("GameInput.dll", &ImportSymbol::Ordinal(1)),
  1366. Some(Provenance::Hle)
  1367. );
  1368. assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None);
  1369. }
  1370. #[test]
  1371. fn pads_connect_report_and_disconnect() {
  1372. let (hub, host) = fake();
  1373. let log = Log::default();
  1374. register(hub, GAMEPAD_KIND, 2, &log);
  1375. // Blocking enumeration ran before registration returned: with no
  1376. // host pad the keyboard's stand-in is the only one.
  1377. assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]);
  1378. host.lock().unwrap().pads[1] = Some(PadState {
  1379. buttons: A,
  1380. left_x: 0.5,
  1381. ..Default::default()
  1382. });
  1383. hub.poll();
  1384. assert_eq!(
  1385. log.lock().unwrap()[1..],
  1386. [(1, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)]
  1387. );
  1388. let first = current(hub, GAMEPAD_KIND, 1).unwrap();
  1389. assert_eq!(pad(first).buttons, A);
  1390. assert_eq!(pad(first).left_x, 0.5);
  1391. // No change, no new reading.
  1392. hub.poll();
  1393. let again = current(hub, GAMEPAD_KIND, 1).unwrap();
  1394. assert_eq!(again, first);
  1395. release(again);
  1396. std::thread::sleep(Duration::from_millis(2));
  1397. host.lock().unwrap().pads[1].as_mut().unwrap().buttons = B;
  1398. hub.poll();
  1399. let second = current(hub, GAMEPAD_KIND, 1).unwrap();
  1400. assert_eq!(pad(second).buttons, B);
  1401. let (t1, s1) = stamp(first);
  1402. let (t2, s2) = stamp(second);
  1403. assert!(t2 > t1 && s2 == s1 + 1);
  1404. assert!(t2 <= now());
  1405. // The title's edge check: previous of current, and back again.
  1406. assert_eq!(walk(hub, 0x30, second), Ok(first));
  1407. assert_eq!(walk(hub, 0x28, first), Ok(second));
  1408. assert_eq!(walk(hub, 0x28, second), Err(READING_NOT_FOUND));
  1409. assert_eq!(walk(hub, 0x30, first), Err(READING_NOT_FOUND));
  1410. for r in [first, first, second, second] {
  1411. release(r);
  1412. }
  1413. host.lock().unwrap().pads[1] = None;
  1414. hub.poll();
  1415. assert_eq!(
  1416. log.lock().unwrap()[3..],
  1417. [(1, 0, STATUS_CONNECTED), (FALLBACK, STATUS_CONNECTED, 0)]
  1418. );
  1419. assert_eq!(current(hub, GAMEPAD_KIND, 1), Err(DEVICE_DISCONNECTED));
  1420. // The stand-in is back, at rest.
  1421. let rest = current(hub, GAMEPAD_KIND, FALLBACK).unwrap();
  1422. assert_eq!(pad(rest), PadState::default());
  1423. release(rest);
  1424. }
  1425. #[test]
  1426. fn keys_feed_the_keyboard_and_the_stand_in_pad() {
  1427. let (hub, host) = fake();
  1428. let log = Log::default();
  1429. register(hub, KEYBOARD_KIND, 2, &log);
  1430. assert_eq!(*log.lock().unwrap(), [(KEYBOARD, STATUS_CONNECTED, 0)]);
  1431. let keys = vec![key(b'W'), key(0x0D), key(b'L'), key(b'C')];
  1432. host.lock().unwrap().keys = keys.clone();
  1433. hub.poll();
  1434. let r = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap();
  1435. let count = slot::<extern "system" fn(*const Reading) -> u32, _>(r, 0x70);
  1436. let state =
  1437. slot::<extern "system" fn(*const Reading, u32, *mut KeyState) -> u32, _>(r, 0x78);
  1438. assert_eq!(count(r), 4);
  1439. let mut got = [KeyState::default(); 8];
  1440. assert_eq!(state(r, 8, got.as_mut_ptr()), 4);
  1441. assert_eq!(got[..4], keys[..]);
  1442. release(r);
  1443. let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap();
  1444. assert_eq!(
  1445. pad(r),
  1446. PadState {
  1447. buttons: A,
  1448. left_y: 1.0,
  1449. right_x: 1.0,
  1450. right_trigger: 1.0,
  1451. ..Default::default()
  1452. }
  1453. );
  1454. release(r);
  1455. // A keyboard reading is no gamepad reading.
  1456. assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND));
  1457. }
  1458. #[test]
  1459. fn a_host_pad_feeds_the_one_pad_which_never_goes() {
  1460. let (hub, host) = fake_with(true);
  1461. let log = Log::default();
  1462. register(hub, GAMEPAD_KIND, 2, &log);
  1463. assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]);
  1464. let pad = |hub: &Hub| match &hub.state().slots[FALLBACK].history.back().unwrap().value {
  1465. Value::Pad(p) => *p,
  1466. Value::Keys(_) => unreachable!(),
  1467. };
  1468. host.lock().unwrap().keys = vec![key(b'D')];
  1469. hub.poll();
  1470. assert_eq!(pad(hub).left_x, 1.0);
  1471. // A pad is switched on, in any slot: its input arrives, beside the
  1472. // keyboard's, and no device comes or goes.
  1473. host.lock().unwrap().pads[2] = Some(PadState { buttons: A, left_y: -0.5, ..Default::default() });
  1474. hub.poll();
  1475. let p = pad(hub);
  1476. assert_eq!((p.buttons, p.left_x, p.left_y), (A, 1.0, -0.5));
  1477. let device: *const Device = &hub.devices[FALLBACK];
  1478. set_rumble(device, &[1.0, 0.0, 0.0, 0.0]);
  1479. assert_eq!(host.lock().unwrap().rumble, [(2, u16::MAX, 0)]);
  1480. // And off again.
  1481. host.lock().unwrap().pads[2] = None;
  1482. host.lock().unwrap().keys.clear();
  1483. hub.poll();
  1484. assert_eq!(pad(hub), PadState::default());
  1485. assert_eq!(log.lock().unwrap().len(), 1);
  1486. assert!(!hub.state().slots[2].connected);
  1487. }
  1488. #[test]
  1489. fn async_enumeration_waits_for_the_poll_and_unregistering_stops_callbacks() {
  1490. let (hub, host) = fake();
  1491. let log = Log::default();
  1492. let token = register(hub, GAMEPAD_KIND, ASYNC_ENUMERATION, &log);
  1493. assert!(log.lock().unwrap().is_empty());
  1494. hub.poll();
  1495. assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]);
  1496. let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(&hub.object, 0x68);
  1497. assert!(unregister(&hub.object, token, 5000));
  1498. host.lock().unwrap().pads[0] = Some(PadState::default());
  1499. hub.poll();
  1500. assert_eq!(log.lock().unwrap().len(), 1);
  1501. }
  1502. #[test]
  1503. fn unregistering_waits_for_a_running_callback() {
  1504. use std::sync::atomic::AtomicBool;
  1505. static INSIDE: AtomicBool = AtomicBool::new(false);
  1506. static LEAVE: AtomicBool = AtomicBool::new(false);
  1507. static FROM_INSIDE: AtomicU32 = AtomicU32::new(0);
  1508. extern "system" fn slow(
  1509. token: u64,
  1510. context: *mut c_void,
  1511. _: *const Device,
  1512. _: u64,
  1513. _: u32,
  1514. _: u32,
  1515. ) {
  1516. // From inside its own callback, unregistering fails at once.
  1517. let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(context, 0x68);
  1518. if !unregister(context.cast(), token, 0) {
  1519. FROM_INSIDE.fetch_add(1, Ordering::SeqCst);
  1520. }
  1521. INSIDE.store(true, Ordering::SeqCst);
  1522. while !LEAVE.load(Ordering::SeqCst) {
  1523. std::thread::sleep(Duration::from_millis(1));
  1524. }
  1525. }
  1526. let (hub, host) = fake();
  1527. type Register = extern "system" fn(
  1528. This,
  1529. *const Device,
  1530. u32,
  1531. u32,
  1532. u32,
  1533. *mut c_void,
  1534. Option<DeviceCallback>,
  1535. *mut u64,
  1536. ) -> HRESULT;
  1537. let register = slot::<Register, _>(&hub.object, 0x48);
  1538. let mut token = 0;
  1539. let context = (&raw const hub.object).cast_mut().cast();
  1540. assert_eq!(
  1541. register(&hub.object, std::ptr::null(), GAMEPAD_KIND, 1, 0, context, Some(slow), &mut token),
  1542. S_OK
  1543. );
  1544. host.lock().unwrap().pads[1] = Some(PadState::default());
  1545. let poller = std::thread::spawn(|| hub.poll());
  1546. while !INSIDE.load(Ordering::SeqCst) {
  1547. std::thread::sleep(Duration::from_millis(1));
  1548. }
  1549. let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(&hub.object, 0x68);
  1550. assert!(!unregister(&hub.object, token, 5000), "times out while it runs");
  1551. let leave = std::thread::spawn(|| {
  1552. std::thread::sleep(Duration::from_millis(50));
  1553. LEAVE.store(true, Ordering::SeqCst);
  1554. });
  1555. let start = Instant::now();
  1556. assert!(unregister(&hub.object, token, u64::MAX), "waits for it");
  1557. assert!(start.elapsed() >= Duration::from_millis(40));
  1558. assert_eq!(FROM_INSIDE.load(Ordering::SeqCst), 1);
  1559. poller.join().unwrap();
  1560. leave.join().unwrap();
  1561. }
  1562. #[test]
  1563. fn devices_are_found_by_id_and_rumble_reaches_the_host() {
  1564. let (hub, host) = fake();
  1565. host.lock().unwrap().pads[2] = Some(PadState::default());
  1566. hub.poll();
  1567. let device = &hub.devices[2] as *const Device;
  1568. let info = slot::<extern "system" fn(*const Device) -> *const u8, _>(device, 0x18);
  1569. // SAFETY: the info has the id at +0x20.
  1570. let id = unsafe { *(info(device).add(0x20) as *const [u8; 32]) };
  1571. assert_ne!(id, [0; 32]);
  1572. type Find = extern "system" fn(This, *const [u8; 32], Out) -> HRESULT;
  1573. let find = slot::<Find, _>(&hub.object, 0x80);
  1574. let mut out = std::ptr::null();
  1575. assert_eq!(find(&hub.object, &id, &mut out), S_OK);
  1576. assert_eq!(out, device.cast());
  1577. assert_eq!(find(&hub.object, &[1; 32], &mut out), DEVICE_NOT_FOUND);
  1578. assert!(out.is_null());
  1579. type Rumble = extern "system" fn(*const Device, *const [f32; 4]);
  1580. let rumble = slot::<Rumble, _>(device, 0x50);
  1581. rumble(device, &[0.5, 1.0, 1.0, 1.0]);
  1582. rumble(&hub.devices[FALLBACK], &[1.0; 4]);
  1583. rumble(device, std::ptr::null());
  1584. assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]);
  1585. }
  1586. }