upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNotRexed <therealnothingfn@gmail.com>2026-11-27 18:06:59 -0500
committerNotRexed <therealnothingfn@gmail.com>2026-11-27 18:06:59 -0500
commit0d8fcf4a030d945f119fb9cf08c38d38f70d46ef (patch)
tree66973a5a2b9090fa64a78e5f766278ac89c5712b
parent34025b5be60d74a8529212cabf223b1b5c1ff252 (diff)
parentf33c963a5c2e905cd1d474c07418f5593619b1f4 (diff)
Merge remote-tracking branch 'old/port/kbm' into next
# Conflicts: # docs/gameinput.md
-rw-r--r--d3d12/README.md42
-rw-r--r--d3d12/apps/leonida/src/game_actions.rs17
-rw-r--r--d3d12/apps/leonida/src/main.rs2
-rw-r--r--d3d12/apps/leonida/src/player_context.rs815
-rw-r--r--d3d12/apps/leonida/src/run.rs6
-rw-r--r--d3d12/crates/leonida-hle/src/modules/gameinput.rs92
-rw-r--r--d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs879
-rw-r--r--d3d12/crates/leonida-loader/src/game_actions.rs87
-rw-r--r--docs/gameinput.md179
-rw-r--r--docs/mod-menu.md10
10 files changed, 2094 insertions, 35 deletions
diff --git a/d3d12/README.md b/d3d12/README.md
index b406ac074..e4886a5be 100644
--- a/d3d12/README.md
+++ b/d3d12/README.md
@@ -383,6 +383,48 @@ Series X profile (sharper, much slower; DLSS there with `-Dlss`); `-Quality` giv
383stretched bodies, slower; `-RayTracing` turns the title's real ray tracing on. 383stretched bodies, slower; `-RayTracing` turns the title's real ray tracing on.
384The fork's own `scripts\play.ps1` is still there for AMD cards. 384The fork's own `scripts\play.ps1` is still there for AMD cards.
385 385
386### Keyboard and mouse
387
388The game itself only knows an Xbox controller, so the keyboard and mouse press that controller's buttons for you,
389laid out as in Grand Theft Auto V on PC. Click in the game's window once to give it the mouse (that click is not a
390shot); Esc pauses and frees the mouse again.
391
392| | on foot | in a vehicle |
393|---|---|---|
394| W A S D | move | W accelerate, S brake and reverse, A D steer |
395| mouse | look around | look around |
396| left mouse button | shoot | shoot from the vehicle |
397| right mouse button | aim | (nothing yet) |
398| Space | jump, climb | handbrake |
399| Left Shift | run | lean forward on a bike (also Num 8) |
400| Left Ctrl | crouch | lean back on a bike (also Num 5) |
401| F | get into a vehicle | get out |
402| E | interact | horn |
403| Q | take cover | radio |
404| R | reload, melee | (the same button) |
405| X, H | | duck, headlights |
406| Tab | weapon wheel (hold) | weapon wheel |
407| C | look behind | look behind |
408| M | map | map |
409| Esc or P | pause | pause |
410| arrow keys | phone (up) and its menus; down, left and right are the HUD, the radio and the partner menu | the same |
411| Enter, Backspace | accept, back (phone and menus) | the same |
412| Z | HUD and objective | the same |
413
414A key you were holding when you got in or out counts again once you have let it go and pressed it again: W held
415while climbing in does not drive off by itself, and a held mouse button does not start to fire.
416
417The runtime reads from the game whether you are in a vehicle. Where it cannot (another version of the game), the
418keys stay the on-foot ones and **Caps Lock** is the switch: press it once you sit in a vehicle for the driving keys,
419and again, or F to get out, for the on-foot keys. Without it a vehicle still drives the old way: left mouse button
420accelerates, right mouse button brakes. Should the runtime get it wrong, `-More @{LEONIDA_PLAYER_VEHICLE_AT='off'}`
421stops it reading and leaves the switch to Caps Lock.
422
423Not bound, because it is not known yet which controller button does it in this game: V (camera), G (grenade), the
424number keys and the mouse wheel (weapons), aiming from a vehicle. A controller keeps working beside the keyboard at
425all times. `LEONIDA_KBM=classic` (with `-More @{LEONIDA_KBM='classic'}`) brings back the keys of before; the
426details, the mouse settings and the other switches are in [docs/gameinput.md](../docs/gameinput.md).
427
386### Picking a resolution 428### Picking a resolution
387 429
388There is one script per console and resolution in `scripts\`. Each one runs 430There is one script per console and resolution in `scripts\`. Each one runs
diff --git a/d3d12/apps/leonida/src/game_actions.rs b/d3d12/apps/leonida/src/game_actions.rs
index d65fdda30..a35f5eadb 100644
--- a/d3d12/apps/leonida/src/game_actions.rs
+++ b/d3d12/apps/leonida/src/game_actions.rs
@@ -495,6 +495,9 @@ impl Game {
495 ); 495 );
496 let ped = self.ped(); 496 let ped = self.ped();
497 let _ = writeln!(s, " player ped {ped:x?}, position {:?}, forward {:?}", self.position(), self.forward()); 497 let _ = writeln!(s, " player ped {ped:x?}, position {:?}, forward {:?}", self.position(), self.forward());
498 // The global `player_context` reads: the vehicle the player is in, null on foot.
499 let vehicle = self.at(Site::PlayerVehicle).and_then(mem::read_u64);
500 let _ = writeln!(s, " player's vehicle {vehicle:x?}");
498 // SAFETY: forwarded from this function's contract. 501 // SAFETY: forwarded from this function's contract.
499 let wanted = ped.and_then(|ped| unsafe { self.wanted_level(ped) }); 502 let wanted = ped.and_then(|ped| unsafe { self.wanted_level(ped) });
500 let _ = writeln!(s, " wanted level {wanted:?}, clock {:?}", self.clock()); 503 let _ = writeln!(s, " wanted level {wanted:?}, clock {:?}", self.clock());
@@ -820,16 +823,24 @@ fn run_script(script: Vec<(f32, Command)>) {
820} 823}
821 824
822/// With `LEONIDA_GAME_ACTIONS=1`: finds the title's code in the image just mapped, hooks its cheat update and 825/// With `LEONIDA_GAME_ACTIONS=1`: finds the title's code in the image just mapped, hooks its cheat update and
823/// lends the menu the actions. Nothing is changed in the title otherwise. 826/// lends the menu the actions. Nothing is changed in the title otherwise. Gives what it found of the title (for
827/// who else reads it: `player_context`), `None` when it did not look.
824/// 828///
825/// # Safety 829/// # Safety
826/// `base` is the title's executable `info` describes, mapped, and none of its code runs yet. 830/// `base` is the title's executable `info` describes, mapped, and none of its code runs yet.
827pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo) { 831pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo) -> Option<Sites> {
828 if !places::wanted() { 832 if !places::wanted() {
829 return; 833 return None;
830 } 834 }
831 // SAFETY: forwarded from this function's contract; the hook is a function of this program. 835 // SAFETY: forwarded from this function's contract; the hook is a function of this program.
832 let (sites, hooked) = unsafe { places::install(base, info, frame_hook as extern "win64" fn() as usize) }; 836 let (sites, hooked) = unsafe { places::install(base, info, frame_hook as extern "win64" fn() as usize) };
837 let found = sites.clone();
838 start(base, info, sites, hooked);
839 Some(found)
840}
841
842/// The rest of [`install`]: the actions, when the hook is in.
843fn start(base: usize, info: &leonida_pe::ImageInfo, sites: Sites, hooked: Result<(), String>) {
833 for line in &sites.missing { 844 for line in &sites.missing {
834 println!("game actions not found: {line}"); 845 println!("game actions not found: {line}");
835 } 846 }
diff --git a/d3d12/apps/leonida/src/main.rs b/d3d12/apps/leonida/src/main.rs
index 08df7abe8..6ad3b6719 100644
--- a/d3d12/apps/leonida/src/main.rs
+++ b/d3d12/apps/leonida/src/main.rs
@@ -14,6 +14,8 @@ mod replay;
14mod game_actions; 14mod game_actions;
15#[cfg(windows)] 15#[cfg(windows)]
16mod player; 16mod player;
17#[cfg(windows)]
18mod player_context;
17#[cfg(all(windows, feature = "diagnostics"))] 19#[cfg(all(windows, feature = "diagnostics"))]
18mod player_find; 20mod player_find;
19mod run; 21mod run;
diff --git a/d3d12/apps/leonida/src/player_context.rs b/d3d12/apps/leonida/src/player_context.rs
new file mode 100644
index 000000000..9cd0c03f4
--- /dev/null
+++ b/d3d12/apps/leonida/src/player_context.rs
@@ -0,0 +1,815 @@
1//! What the player is in, on foot or in a vehicle, read from the title and told to the keyboard and mouse layout
2//! (`leonida_hle::modules::gameinput`, `kbm`): the right trigger shoots on foot and accelerates in a vehicle, so
3//! the layout has two tables and has to know which one counts (`docs/gameinput.md`).
4//!
5//! A thread of ours reads a few words of the title's memory every 16 ms, through `ReadProcessMemory` on the own
6//! process (a page that is gone is a failed read, not a fault). Nothing is written to the title and none of its
7//! code is called, so this needs no `LEONIDA_GAME_ACTIONS=1`: it only needs the two globals found, by the
8//! patterns of `leonida_loader::game_actions`.
9//!
10//! What says "in a vehicle", the first of these that there is:
11//!
12//! - `LEONIDA_PED_VEHICLE_AT=0x<offset>`: a field of the player's ped that points at its vehicle and is null on
13//! foot (for a measured offset; none is known).
14//! - `LEONIDA_PLAYER_VEHICLE_AT=0x<offset in the image>`: a global of the title that holds the player's vehicle
15//! and is null on foot. Without the variable this is `Site::PlayerVehicle`, found by its pattern;
16//! `LEONIDA_PLAYER_VEHICLE_AT=off` leaves it unused.
17//! - `LEONIDA_KBM_SPEED=1`: how fast the ped moves ([`SpeedRule`]). It only ever says "in a vehicle", and only
18//! once the ped has been faster than anyone runs for a second, so it is off unless asked for: the keys' meaning
19//! would change in the middle of a drive. It always runs as a check of the two above, into the log.
20//!
21//! With none of them the context stays unknown, and the layout is the on-foot one with Caps Lock as the switch.
22//!
23//! `LEONIDA_PED_DUMP=<folder>` (outside the repository) is for measuring: F8 in the game's window, or a file named
24//! `dump` in that folder (its text is the dump's label; it is removed as it is seen), writes the first 0x4000
25//! bytes of the player's ped to `ped-<time>-<label>.bin` there, the first 0x1000 of the vehicle the global names
26//! to `vehicle-<time>-<label>.bin`, and a line to `index.txt`. Those are the title's memory: never commit them.
27
28use std::io::Write as _;
29use std::path::{Path, PathBuf};
30use std::time::{Duration, Instant};
31
32use leonida_hle::modules::gameinput::{self, PlayerContext};
33use leonida_loader::game_actions::{self as places, Site, Sites};
34
35use crate::player::mem;
36
37/// The thread's step.
38const TICK: Duration = Duration::from_millis(16);
39/// A change of what is read counts once it was read so many times in a row.
40const STEADY_READS: u32 = 3;
41/// How much of the ped, and of its vehicle, a dump holds.
42const PED_DUMP: usize = 0x4000;
43const VEHICLE_DUMP: usize = 0x1000;
44const PAGE: usize = 0x1000;
45/// The key that asks for a dump: F8.
46const VK_DUMP: i32 = 0x77;
47
48/// A number as the switches give it: `0x1a2b` or `6699`.
49fn parse_offset(text: &str) -> Option<usize> {
50 let text = text.trim();
51 match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
52 Some(hex) => usize::from_str_radix(hex, 16).ok(),
53 None => text.parse().ok(),
54 }
55}
56
57/// What the switches ask for.
58#[derive(Clone, Debug, Default, PartialEq, Eq)]
59struct Settings {
60 /// `LEONIDA_PED_VEHICLE_AT`.
61 ped_field: Option<usize>,
62 /// `LEONIDA_PLAYER_VEHICLE_AT`: an offset in the image, or `off` (`Some(None)`).
63 global: Option<Option<usize>>,
64 /// `LEONIDA_KBM_SPEED=1`.
65 speed: bool,
66 /// `LEONIDA_PED_DUMP`.
67 dump: Option<PathBuf>,
68}
69
70impl Settings {
71 fn parse(ped_field: Option<&str>, global: Option<&str>, speed: Option<&str>, dump: Option<&str>) -> Settings {
72 Settings {
73 ped_field: ped_field.and_then(parse_offset).filter(|at| *at < 0x10_0000),
74 global: global.and_then(|text| match text.trim() {
75 "off" | "0" => Some(None),
76 text => parse_offset(text).map(Some),
77 }),
78 speed: speed.is_some_and(|v| v.trim() == "1"),
79 dump: dump.map(str::trim).filter(|d| !d.is_empty()).map(PathBuf::from),
80 }
81 }
82
83 fn from_env() -> Settings {
84 let var = |name: &str| std::env::var(name).ok();
85 Settings::parse(
86 var("LEONIDA_PED_VEHICLE_AT").as_deref(),
87 var("LEONIDA_PLAYER_VEHICLE_AT").as_deref(),
88 var("LEONIDA_KBM_SPEED").as_deref(),
89 var("LEONIDA_PED_DUMP").as_deref(),
90 )
91 }
92}
93
94/// What says whether the player is in a vehicle.
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96enum Source {
97 /// A field of the player's ped that points at its vehicle (offset in the ped).
98 PedField(usize),
99 /// A global of the title that holds the player's vehicle (offset in the image).
100 Global(usize),
101 /// How fast the ped moves.
102 Speed,
103 Nothing,
104}
105
106impl Source {
107 /// The first there is: the measured field, the global (named, or found unless turned off), the speed.
108 fn pick(settings: &Settings, found_global: Option<usize>) -> Source {
109 let global = match settings.global {
110 Some(named) => named,
111 None => found_global,
112 };
113 match (settings.ped_field, global) {
114 (Some(at), _) => Source::PedField(at),
115 (None, Some(at)) => Source::Global(at),
116 (None, None) if settings.speed => Source::Speed,
117 (None, None) => Source::Nothing,
118 }
119 }
120
121 fn describe(&self) -> String {
122 match self {
123 Source::PedField(at) => format!("the ped's field at {at:#x} (LEONIDA_PED_VEHICLE_AT)"),
124 Source::Global(at) => format!("the title's global of the player's vehicle, at {at:#x} in the image"),
125 Source::Speed => "the ped's speed (LEONIDA_KBM_SPEED=1)".into(),
126 Source::Nothing => "nothing".into(),
127 }
128 }
129}
130
131/// What a word that should point at the player's vehicle says: null is on foot, an address is in a vehicle, and
132/// a read that failed or anything else says nothing.
133fn pointer_says(word: Option<u64>) -> PlayerContext {
134 match word {
135 Some(0) => PlayerContext::OnFoot,
136 Some(p) if (0x1_0000..0x8000_0000_0000).contains(&p) => PlayerContext::InVehicle,
137 _ => PlayerContext::Unknown,
138 }
139}
140
141/// A read counts once it is the same [`STEADY_READS`] times in a row: we read while the title writes.
142#[derive(Clone, Copy, Debug)]
143struct Steady {
144 shown: PlayerContext,
145 seen: PlayerContext,
146 times: u32,
147}
148
149impl Default for Steady {
150 fn default() -> Steady {
151 Steady { shown: PlayerContext::Unknown, seen: PlayerContext::Unknown, times: 0 }
152 }
153}
154
155impl Steady {
156 fn step(&mut self, read: PlayerContext) -> PlayerContext {
157 if read == self.shown {
158 self.times = 0;
159 } else if read == self.seen && self.times > 0 {
160 self.times += 1;
161 if self.times >= STEADY_READS {
162 self.shown = read;
163 self.times = 0;
164 }
165 } else {
166 self.seen = read;
167 self.times = 1;
168 }
169 self.shown
170 }
171}
172
173/// The speed rule: a ped that moves faster than anyone runs is in a vehicle.
174///
175/// The ped's position is taken about every [`SpeedRule::WINDOW`] and gives a speed over the ground (the title
176/// moves the ped 30 times a second, so a shorter step would read 0 and double by turns). At
177/// [`SpeedRule::FAST`] or more (12 m/s, 43 km/h; a sprint is about 7 m/s, assuming the world is in metres as the
178/// series' are) for [`SpeedRule::PROVEN`] without a break, the ped is driving, and stays so until it has not been
179/// that fast for [`SpeedRule::HOLD`].
180///
181/// Its limits: it never says "on foot" (a car at a red light and a ped standing look the same), so below that
182/// speed it says nothing; it cannot see a drive begin, so it never switches to driving from a standstill and the
183/// first metres of every drive are on the on-foot keys; a ped carried at that speed without driving (a passenger,
184/// a train's roof) counts as driving; a fall is left out (more down than along), and so is a jump of the position
185/// (a teleport, a respawn: more than [`SpeedRule::JUMP`]), which also ends a drive.
186#[derive(Clone, Copy, Debug, Default)]
187struct SpeedRule {
188 /// The position the next speed is measured from, and its time (seconds).
189 from: Option<([f32; 3], f64)>,
190 /// The speed last measured, metres a second over the ground.
191 speed: f32,
192 /// Since when the ped has been fast without a break, and when it last was.
193 fast_since: Option<f64>,
194 fast_last: Option<f64>,
195 proven: bool,
196}
197
198impl SpeedRule {
199 const WINDOW: f64 = 0.2;
200 const FAST: f32 = 12.0;
201 const JUMP: f32 = 120.0;
202 const PROVEN: f64 = 1.0;
203 const HOLD: f64 = 3.0;
204
205 /// Takes the ped's position at `t` seconds.
206 fn step(&mut self, position: [f32; 3], t: f64) {
207 let Some((from, at)) = self.from else {
208 self.from = Some((position, t));
209 return;
210 };
211 let dt = t - at;
212 if dt < Self::WINDOW {
213 return;
214 }
215 self.from = Some((position, t));
216 // A gap (the thread or the title stood still): no speed from it.
217 if dt > 1.0 {
218 self.lost();
219 return;
220 }
221 let along = (position[0] - from[0]).hypot(position[1] - from[1]) / dt as f32;
222 let down = (position[2] - from[2]).abs() / dt as f32;
223 if along > Self::JUMP || down > Self::JUMP {
224 self.lost();
225 return;
226 }
227 self.speed = along;
228 if along >= Self::FAST && down <= along {
229 self.fast_since.get_or_insert(t);
230 self.fast_last = Some(t);
231 self.proven |= self.fast_since.is_some_and(|since| t - since >= Self::PROVEN);
232 } else if !self.proven {
233 self.fast_since = None;
234 }
235 if self.fast_last.is_some_and(|last| t - last > Self::HOLD) {
236 self.lost();
237 }
238 }
239
240 /// No position (no ped), a gap or a jump: nothing is known any more.
241 fn lost(&mut self) {
242 *self = SpeedRule { from: self.from, ..Default::default() };
243 }
244
245 fn reset(&mut self) {
246 *self = SpeedRule::default();
247 }
248
249 /// Whether the ped is driving by this rule, at `t`.
250 fn driving(&self, t: f64) -> bool {
251 self.proven && self.fast_last.is_some_and(|last| t - last <= Self::HOLD)
252 }
253}
254
255/// Where the title keeps what is read, as addresses in this run.
256#[derive(Clone, Copy, Debug)]
257struct Reader {
258 base: usize,
259 /// The global that holds the player's ped.
260 ped_at: Option<usize>,
261 /// The global that holds the player's vehicle, when one is known (also when it is not the source: dumps
262 /// and the log show it).
263 vehicle_at: Option<usize>,
264 source: Source,
265}
266
267impl Reader {
268 fn ped(&self) -> Option<usize> {
269 let ped = mem::read_u64(self.ped_at?)? as usize;
270 (ped > 0x10000).then_some(ped)
271 }
272
273 fn vehicle(&self) -> Option<usize> {
274 let vehicle = mem::read_u64(self.vehicle_at?)? as usize;
275 (vehicle > 0x10000).then_some(vehicle)
276 }
277
278 fn position(entity: usize) -> Option<[f32; 3]> {
279 let b = mem::read_vec(entity + places::ENTITY_POSITION_AT, 12)?;
280 let v: [f32; 3] = std::array::from_fn(|i| f32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().unwrap()));
281 v.iter().all(|c| c.is_finite() && c.abs() < 1.0e6).then_some(v)
282 }
283
284 /// What the source says now. With no ped in the world (loading, the menus) nothing is known.
285 fn context(&self, ped: Option<usize>, speed: &SpeedRule, t: f64) -> PlayerContext {
286 if self.ped_at.is_some() && ped.is_none() {
287 return PlayerContext::Unknown;
288 }
289 match self.source {
290 Source::PedField(at) => ped.map_or(PlayerContext::Unknown, |ped| pointer_says(mem::read_u64(ped + at))),
291 Source::Global(at) => pointer_says(mem::read_u64(self.base + at)),
292 Source::Speed if speed.driving(t) => PlayerContext::InVehicle,
293 Source::Speed | Source::Nothing => PlayerContext::Unknown,
294 }
295 }
296}
297
298fn say(line: &str) {
299 eprintln!("Leonida: player context: {line}");
300}
301
302/// The local date and time: year, month, day, hour, minute, second, millisecond.
303fn local_time() -> [u16; 7] {
304 unsafe extern "system" {
305 fn GetLocalTime(time: *mut [u16; 8]);
306 }
307 let mut t = [0u16; 8];
308 // SAFETY: fills the eight words of a SYSTEMTIME.
309 unsafe { GetLocalTime(&mut t) };
310 // (the third word is the day of the week)
311 [t[0], t[1], t[3], t[4], t[5], t[6], t[7]]
312}
313
314/// A dump's label as part of a file name: letters, digits, `-` and `_`, at most 32; `dump` when nothing is left.
315fn label_of(text: &str) -> String {
316 let label: String =
317 text.trim().chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(32).collect();
318 if label.is_empty() { "dump".into() } else { label }
319}
320
321/// `len` bytes at `address`, page by page: what does not read is zero, and its offsets are listed.
322fn read_pages(address: usize, len: usize) -> (Vec<u8>, Vec<usize>) {
323 let mut data = vec![0u8; len];
324 let mut unread = Vec::new();
325 let mut at = 0;
326 while at < len {
327 // Up to the end of the page `address + at` lies in.
328 let step = (PAGE - (address + at) % PAGE).min(len - at);
329 if !mem::read(address + at, &mut data[at..at + step]) {
330 unread.push(at);
331 }
332 at += step;
333 }
334 (data, unread)
335}
336
337/// What is known when a dump is asked for.
338struct Moment {
339 label: String,
340 time: [u16; 7],
341 seconds: f64,
342 ped: usize,
343 vehicle: Option<usize>,
344 speed: f32,
345 read: PlayerContext,
346 shown: PlayerContext,
347 source: Source,
348}
349
350/// Writes the dump's files into `dir` and its line into `index.txt`; gives the ped's file.
351fn write_dump(dir: &Path, m: &Moment) -> std::io::Result<PathBuf> {
352 std::fs::create_dir_all(dir)?;
353 let [year, month, day, hour, minute, second, ms] = m.time;
354 let stamp = format!("{year:04}{month:02}{day:02}-{hour:02}{minute:02}{second:02}-{ms:03}");
355 let (bytes, unread) = read_pages(m.ped, PED_DUMP);
356 let ped_file = dir.join(format!("ped-{stamp}-{}.bin", m.label));
357 std::fs::write(&ped_file, &bytes)?;
358 let id_at = places::ENTITY_ID_AT;
359 let id = bytes.get(id_at..id_at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap()));
360 let position = Reader::position(m.ped);
361 let mut line = format!(
362 "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}.{ms:03} {} label {} at {:.1} s \
363 ped {:#x} id {:#x} position {position:?} speed {:.1} m/s read {:?} told {:?} by {}",
364 ped_file.file_name().unwrap_or_default().to_string_lossy(),
365 m.label,
366 m.seconds,
367 m.ped,
368 id.unwrap_or(0),
369 m.speed,
370 m.read,
371 m.shown,
372 m.source.describe(),
373 );
374 match m.vehicle {
375 Some(vehicle) => {
376 let (bytes, _) = read_pages(vehicle, VEHICLE_DUMP);
377 let file = format!("vehicle-{stamp}-{}.bin", m.label);
378 std::fs::write(dir.join(&file), &bytes)?;
379 let away = position.zip(Reader::position(vehicle)).map(|(a, b)| {
380 ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
381 });
382 let away = away.map_or("?".to_owned(), |metres| format!("{metres:.1}"));
383 line.push_str(&format!(" vehicle global {vehicle:#x} ({file}), {away} m from the ped"));
384 }
385 None => line.push_str(" vehicle global null or not known"),
386 }
387 if !unread.is_empty() {
388 line.push_str(&format!(" not readable (zero in the file): pages at {unread:x?}"));
389 }
390 let mut index = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("index.txt"))?;
391 writeln!(index, "{line}")?;
392 Ok(ped_file)
393}
394
395/// Whether a dump is asked for now: its label.
396struct Trigger {
397 dir: PathBuf,
398 key_was: bool,
399}
400
401impl Trigger {
402 fn asked(&mut self) -> Option<String> {
403 #[link(name = "user32")]
404 unsafe extern "system" {
405 fn GetAsyncKeyState(key: i32) -> i16;
406 fn GetForegroundWindow() -> isize;
407 fn GetWindowThreadProcessId(window: isize, process: *mut u32) -> u32;
408 }
409 unsafe extern "system" {
410 fn GetCurrentProcessId() -> u32;
411 }
412 let mut owner = 0u32;
413 // SAFETY: plain queries; a null window gives process 0.
414 let down = unsafe {
415 GetWindowThreadProcessId(GetForegroundWindow(), &mut owner);
416 owner == GetCurrentProcessId() && GetAsyncKeyState(VK_DUMP) < 0
417 };
418 let pressed = down && !std::mem::replace(&mut self.key_was, down);
419 if !down {
420 self.key_was = false;
421 }
422 if pressed {
423 return Some("key".into());
424 }
425 let file = self.dir.join("dump");
426 if !file.exists() {
427 return None;
428 }
429 let label = label_of(&std::fs::read_to_string(&file).unwrap_or_default());
430 // One file asks once; a file that cannot be removed would ask for ever.
431 std::fs::remove_file(&file).is_ok().then_some(label)
432 }
433}
434
435fn run(reader: Reader, tells: bool, dump: Option<PathBuf>) {
436 let start = Instant::now();
437 let mut steady = Steady::default();
438 let mut speed = SpeedRule::default();
439 let mut trigger = dump.map(|dir| Trigger { dir, key_was: false });
440 let mut told = PlayerContext::Unknown;
441 // When each check last spoke (seconds): at most once in half a minute.
442 let (mut fast_on_foot, mut far_vehicle) = (f64::MIN, f64::MIN);
443 let mut tick = 0u64;
444 loop {
445 std::thread::sleep(TICK);
446 tick += 1;
447 let t = start.elapsed().as_secs_f64();
448 let ped = reader.ped();
449 if tick.is_multiple_of(4) {
450 match ped.and_then(Reader::position) {
451 Some(position) => speed.step(position, t),
452 None => speed.reset(),
453 }
454 }
455 let read = reader.context(ped, &speed, t);
456 let shown = steady.step(read);
457 if tells {
458 gameinput::set_player_context(shown);
459 }
460 if shown != told {
461 told = shown;
462 say(&format!("{shown:?} at {t:.2} s (speed {:.1} m/s)", speed.speed));
463 }
464 // The speed as a check of what is read: a ped this fast is not on foot.
465 if shown == PlayerContext::OnFoot && speed.driving(t) && t - fast_on_foot > 30.0 {
466 fast_on_foot = t;
467 say(&format!(
468 "on foot by {}, but the ped has moved at {:.0} m/s for over a second: what is read may be wrong",
469 reader.source.describe(),
470 speed.speed
471 ));
472 }
473 if tick.is_multiple_of(16) {
474 // And where the vehicle is: one that stays behind when the ped walks off is not the one it is in.
475 if shown == PlayerContext::InVehicle
476 && t - far_vehicle > 30.0
477 && let Some(away) = ped
478 .and_then(Reader::position)
479 .zip(reader.vehicle().and_then(Reader::position))
480 .map(|(a, b)| (a[0] - b[0]).hypot(a[1] - b[1]))
481 && away > 60.0
482 {
483 far_vehicle = t;
484 say(&format!("in a vehicle by what is read, but that vehicle is {away:.0} m from the ped"));
485 }
486 if let Some(trigger) = trigger.as_mut()
487 && let Some(label) = trigger.asked()
488 {
489 match ped {
490 Some(ped) => {
491 let moment = Moment {
492 label,
493 time: local_time(),
494 seconds: t,
495 ped,
496 vehicle: reader.vehicle(),
497 speed: speed.speed,
498 read,
499 shown,
500 source: reader.source,
501 };
502 match write_dump(&trigger.dir, &moment) {
503 Ok(file) => say(&format!("the ped is dumped to {}", file.display())),
504 Err(why) => say(&format!("the dump could not be written: {why}")),
505 }
506 }
507 None => say("a dump was asked for, but there is no player ped now"),
508 }
509 }
510 }
511 }
512}
513
514/// Starts the reading thread, when the keyboard and mouse layout follows the player's context or dumps are asked
515/// for. `found` is what the game actions found already (`LEONIDA_GAME_ACTIONS=1`); without it the two globals are
516/// looked for here, which reads the image's code twice over and changes nothing.
517///
518/// # Safety
519/// `base` is the title's executable `info` describes, mapped, and none of its code runs yet.
520pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo, found: Option<&Sites>) {
521 let settings = Settings::from_env();
522 let tells = gameinput::player_context_wanted();
523 let dump = settings.dump.clone().filter(|dir| match leonida_core::ensure_outside_repo(dir) {
524 Ok(()) => true,
525 Err(why) => {
526 println!("player context LEONIDA_PED_DUMP not used: {why}");
527 false
528 }
529 });
530 if !tells && dump.is_none() {
531 return;
532 }
533 let began = Instant::now();
534 let sites = match found {
535 Some(sites) => sites.clone(),
536 // SAFETY: forwarded from this function's contract.
537 None => unsafe { places::find(base, info, Some(&[Site::PlayerPed, Site::PlayerVehicle])) },
538 };
539 let looked = began.elapsed();
540 if found.is_none() {
541 for line in &sites.missing {
542 println!("player context not found: {line}");
543 }
544 }
545 let found_global = sites.get(Site::PlayerVehicle);
546 let source = match Source::pick(&settings, found_global) {
547 _ if !tells => Source::Nothing,
548 Source::Global(at) if at + 8 > info.size_of_image as usize => {
549 println!("player context LEONIDA_PLAYER_VEHICLE_AT={at:#x} is not in the image: not used");
550 Source::Nothing
551 }
552 source => source,
553 };
554 let named = match settings.global {
555 Some(named) => named,
556 None => found_global,
557 };
558 let reader = Reader {
559 base,
560 ped_at: sites.get(Site::PlayerPed).map(|rva| base + rva),
561 vehicle_at: named.filter(|rva| *rva < info.size_of_image as usize).map(|rva| base + rva),
562 source,
563 };
564 if tells && source == Source::Nothing {
565 println!("player context not read: the on-foot keys, and Caps Lock switches to the driving keys by hand");
566 } else if tells {
567 println!(
568 "player context read from {} ({} ms to find it): W accelerates and the mouse shoots in a vehicle",
569 source.describe(),
570 looked.as_millis()
571 );
572 }
573 if let Some(dir) = &dump {
574 println!("player context F8, or a file named dump in {}, dumps the player's ped there", dir.display());
575 }
576 if source == Source::Nothing && dump.is_none() {
577 return;
578 }
579 let thread = std::thread::Builder::new().name("leonida-player-context".into());
580 if thread.spawn(move || run(reader, tells, dump)).is_err() {
581 println!("player context the reading thread could not be started");
582 }
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588
589 const FOOT: PlayerContext = PlayerContext::OnFoot;
590 const CAR: PlayerContext = PlayerContext::InVehicle;
591 const UNKNOWN: PlayerContext = PlayerContext::Unknown;
592
593 #[test]
594 fn offsets_and_switches_read() {
595 assert_eq!(parse_offset("0x1a2B"), Some(0x1a2b));
596 assert_eq!(parse_offset(" 0X10 "), Some(16));
597 assert_eq!(parse_offset("4096"), Some(4096));
598 for wrong in ["", "0x", "xyz", "-1", "0x1g"] {
599 assert_eq!(parse_offset(wrong), None, "{wrong:?}");
600 }
601 assert_eq!(Settings::parse(None, None, None, None), Settings::default());
602 let s = Settings::parse(Some("0xd10"), Some("0xab760c8"), Some("1"), Some(r" D:\dumps "));
603 assert_eq!(s.ped_field, Some(0xd10));
604 assert_eq!(s.global, Some(Some(0xab7_60c8)));
605 assert!(s.speed);
606 assert_eq!(s.dump, Some(PathBuf::from(r"D:\dumps")));
607 // An offset in a ped is small; `off` turns the global off; what does not read is as unset.
608 assert_eq!(Settings::parse(Some("0x7ff600001000"), None, None, None).ped_field, None);
609 assert_eq!(Settings::parse(None, Some("off"), Some("0"), Some(" ")).global, Some(None));
610 assert_eq!(Settings::parse(None, Some("what"), Some("yes"), None), Settings::default());
611 }
612
613 #[test]
614 fn the_source_is_the_first_there_is() {
615 let none = Settings::default();
616 assert_eq!(Source::pick(&none, None), Source::Nothing);
617 assert_eq!(Source::pick(&none, Some(0x500)), Source::Global(0x500));
618 let field = Settings { ped_field: Some(0x10), ..Default::default() };
619 assert_eq!(Source::pick(&field, Some(0x500)), Source::PedField(0x10));
620 let named = Settings { global: Some(Some(0x700)), speed: true, ..Default::default() };
621 assert_eq!(Source::pick(&named, Some(0x500)), Source::Global(0x700));
622 assert_eq!(Source::pick(&named, None), Source::Global(0x700));
623 let off = Settings { global: Some(None), ..Default::default() };
624 assert_eq!(Source::pick(&off, Some(0x500)), Source::Nothing);
625 let speed = Settings { global: Some(None), speed: true, ..Default::default() };
626 assert_eq!(Source::pick(&speed, Some(0x500)), Source::Speed);
627 for source in [Source::Nothing, Source::Speed, Source::Global(1), Source::PedField(2)] {
628 assert!(!source.describe().is_empty());
629 }
630 }
631
632 #[test]
633 fn a_pointer_says_where_the_player_is() {
634 assert_eq!(pointer_says(Some(0)), FOOT);
635 assert_eq!(pointer_says(Some(0x1_4a3f_2c80)), CAR);
636 // No read, or a word that is no address: nothing.
637 assert_eq!(pointer_says(None), UNKNOWN);
638 assert_eq!(pointer_says(Some(7)), UNKNOWN);
639 assert_eq!(pointer_says(Some(u64::MAX)), UNKNOWN);
640 }
641
642 #[test]
643 fn a_read_counts_after_three_in_a_row() {
644 let mut s = Steady::default();
645 assert_eq!(s.step(UNKNOWN), UNKNOWN);
646 assert_eq!(s.step(FOOT), UNKNOWN);
647 assert_eq!(s.step(FOOT), UNKNOWN);
648 assert_eq!(s.step(FOOT), FOOT);
649 // One odd read (the title was writing) changes nothing, nor do two.
650 assert_eq!(s.step(CAR), FOOT);
651 assert_eq!(s.step(FOOT), FOOT);
652 assert_eq!(s.step(CAR), FOOT);
653 assert_eq!(s.step(CAR), FOOT);
654 assert_eq!(s.step(UNKNOWN), FOOT);
655 assert_eq!(s.step(CAR), FOOT);
656 assert_eq!(s.step(CAR), FOOT);
657 assert_eq!(s.step(CAR), CAR);
658 assert_eq!(s.step(CAR), CAR);
659 }
660
661 /// A ped that moves `speed` metres a second along x (and `fall` down) from `t0` to `t1`, sampled every 64 ms.
662 fn travel(rule: &mut SpeedRule, at: &mut [f32; 3], t0: f64, t1: f64, speed: f32, fall: f32) {
663 let mut t = t0;
664 while t < t1 {
665 at[0] += speed * 0.064;
666 at[2] -= fall * 0.064;
667 t += 0.064;
668 rule.step(*at, t);
669 }
670 }
671
672 #[test]
673 fn the_speed_rule_never_drives_from_a_standstill() {
674 let mut rule = SpeedRule::default();
675 let mut at = [100.0, 200.0, 30.0];
676 // Standing, walking, sprinting: never driving, however long.
677 for speed in [0.0, 1.5, 7.5, 11.0] {
678 travel(&mut rule, &mut at, 0.0, 30.0, speed, 0.0);
679 assert!(!rule.driving(30.0), "{speed} m/s");
680 assert!((rule.speed - speed).abs() < 0.5, "{} for {speed}", rule.speed);
681 rule.reset();
682 }
683 // Fast for less than a second (thrown by a car): not driving.
684 travel(&mut rule, &mut at, 0.0, 0.7, 25.0, 0.0);
685 travel(&mut rule, &mut at, 0.7, 5.0, 0.0, 0.0);
686 assert!(!rule.driving(5.0));
687 // A fall: fast, but more down than along.
688 rule.reset();
689 travel(&mut rule, &mut at, 0.0, 4.0, 14.0, 40.0);
690 assert!(!rule.driving(4.0));
691 // A teleport: one jump, then standing.
692 rule.reset();
693 travel(&mut rule, &mut at, 0.0, 1.0, 0.0, 0.0);
694 at[0] += 2000.0;
695 travel(&mut rule, &mut at, 1.0, 5.0, 0.0, 0.0);
696 assert!(!rule.driving(5.0));
697 }
698
699 #[test]
700 fn the_speed_rule_sees_a_drive_once_it_is_fast_and_lets_go_after_it() {
701 let mut rule = SpeedRule::default();
702 let mut at = [0.0, 0.0, 0.0];
703 // Pulling away: not yet. At 20 m/s for over a second: driving.
704 travel(&mut rule, &mut at, 0.0, 2.0, 6.0, 0.0);
705 assert!(!rule.driving(2.0));
706 travel(&mut rule, &mut at, 2.0, 2.8, 20.0, 0.0);
707 assert!(!rule.driving(2.8), "not yet a second");
708 travel(&mut rule, &mut at, 2.8, 4.0, 20.0, 0.0);
709 assert!(rule.driving(4.0));
710 // Slowing for a corner keeps it; three seconds below the speed end it.
711 travel(&mut rule, &mut at, 4.0, 6.0, 5.0, 0.0);
712 assert!(rule.driving(6.0));
713 travel(&mut rule, &mut at, 6.0, 8.0, 20.0, 0.0);
714 travel(&mut rule, &mut at, 8.0, 12.0, 0.0, 0.0);
715 assert!(!rule.driving(12.0));
716 // And a new drive has to prove itself again.
717 travel(&mut rule, &mut at, 12.0, 12.6, 20.0, 0.0);
718 assert!(!rule.driving(12.6));
719 // A respawn in the middle of a drive ends it.
720 travel(&mut rule, &mut at, 12.6, 15.0, 20.0, 0.0);
721 assert!(rule.driving(15.0));
722 at[1] += 900.0;
723 travel(&mut rule, &mut at, 15.0, 15.5, 0.0, 0.0);
724 assert!(!rule.driving(15.5));
725 // No ped: nothing is known.
726 travel(&mut rule, &mut at, 15.5, 18.0, 20.0, 0.0);
727 assert!(rule.driving(18.0));
728 rule.reset();
729 assert!(!rule.driving(18.0));
730 }
731
732 #[test]
733 fn a_reader_reads_this_process() {
734 // A made-up ped and vehicle in our own memory, and the two globals that point at them.
735 let mut ped = vec![0u8; PED_DUMP];
736 let mut vehicle = vec![0u8; VEHICLE_DUMP];
737 for (entity, x) in [(&mut ped, 10.0f32), (&mut vehicle, 13.0)] {
738 for (i, v) in [x, 20.0, 5.0].iter().enumerate() {
739 let at = places::ENTITY_POSITION_AT + i * 4;
740 entity[at..at + 4].copy_from_slice(&v.to_le_bytes());
741 }
742 }
743 ped[places::ENTITY_ID_AT..places::ENTITY_ID_AT + 4].copy_from_slice(&0x6_0123u32.to_le_bytes());
744 let field = 0x898;
745 let mut globals: Box<[u64; 2]> = Box::new([ped.as_ptr() as u64, 0]);
746 let base = globals.as_mut_ptr() as usize;
747 let reader = |source| Reader { base, ped_at: Some(base), vehicle_at: Some(base + 8), source };
748 let speed = SpeedRule::default();
749 let r = reader(Source::Global(8));
750 assert_eq!(r.ped(), Some(ped.as_ptr() as usize));
751 assert_eq!(Reader::position(r.ped().unwrap()), Some([10.0, 20.0, 5.0]));
752 // On foot: the global is null, and so is the ped's field.
753 assert_eq!(r.context(r.ped(), &speed, 0.0), FOOT);
754 assert_eq!(reader(Source::PedField(field)).context(r.ped(), &speed, 0.0), FOOT);
755 assert_eq!(reader(Source::Speed).context(r.ped(), &speed, 0.0), UNKNOWN);
756 assert_eq!(reader(Source::Nothing).context(r.ped(), &speed, 0.0), UNKNOWN);
757 // In a vehicle.
758 globals[1] = vehicle.as_ptr() as u64;
759 ped[field..field + 8].copy_from_slice(&(vehicle.as_ptr() as u64).to_le_bytes());
760 assert_eq!(r.context(r.ped(), &speed, 0.0), CAR);
761 assert_eq!(r.vehicle(), Some(vehicle.as_ptr() as usize));
762 assert_eq!(reader(Source::PedField(field)).context(r.ped(), &speed, 0.0), CAR);
763 // No ped in the world: unknown, whatever the global holds.
764 assert_eq!(r.context(None, &speed, 0.0), UNKNOWN);
765 // A global that cannot be read: unknown.
766 let gone = Reader { base: 0x10, ped_at: None, vehicle_at: None, source: Source::Global(8) };
767 assert_eq!(gone.context(None, &speed, 0.0), UNKNOWN);
768
769 // The dump: the ped's bytes, the vehicle's, and a line that says what was read.
770 let dir = std::env::temp_dir().join(format!("leonida-ped-dump-test-{}", std::process::id()));
771 let _ = std::fs::remove_dir_all(&dir);
772 let moment = Moment {
773 label: label_of(" in a car! "),
774 time: [2026, 11, 27, 21, 4, 5, 6],
775 seconds: 12.5,
776 ped: r.ped().unwrap(),
777 vehicle: r.vehicle(),
778 speed: 3.0,
779 read: CAR,
780 shown: CAR,
781 source: r.source,
782 };
783 let file = write_dump(&dir, &moment).unwrap();
784 assert_eq!(file.file_name().unwrap(), "ped-20261127-210405-006-inacar.bin");
785 assert_eq!(std::fs::read(&file).unwrap(), ped);
786 assert_eq!(std::fs::read(dir.join("vehicle-20261127-210405-006-inacar.bin")).unwrap(), vehicle);
787 let index = std::fs::read_to_string(dir.join("index.txt")).unwrap();
788 assert!(index.contains("2026-11-27 21:04:05.006") && index.contains("label inacar"), "{index}");
789 assert!(index.contains("id 0x60123"), "{index}");
790 assert!(index.contains("3.0 m from the ped") && index.contains("read InVehicle"), "{index}");
791 assert!(!index.contains("not readable"), "{index}");
792 // A file named `dump` asks once, and its text is the label.
793 let mut trigger = Trigger { dir: dir.clone(), key_was: false };
794 assert_eq!(trigger.asked(), None);
795 std::fs::write(dir.join("dump"), "foot\n").unwrap();
796 assert_eq!(trigger.asked().as_deref(), Some("foot"));
797 assert_eq!(trigger.asked(), None);
798 std::fs::remove_dir_all(&dir).unwrap();
799 }
800
801 #[test]
802 fn what_does_not_read_is_zero_in_a_dump() {
803 // Two pages of ours, then whatever follows a low address nobody has.
804 let ours = vec![0xA5u8; 2 * PAGE];
805 let (data, unread) = read_pages(ours.as_ptr() as usize, ours.len());
806 assert!(data == ours && unread.is_empty());
807 let (data, unread) = read_pages(0x1800, 0x1000);
808 assert!(data.iter().all(|b| *b == 0));
809 assert_eq!(unread, [0, 0x800]);
810 assert_eq!(label_of(""), "dump");
811 assert_eq!(label_of("on_foot-2"), "on_foot-2");
812 assert_eq!(label_of(r"..\..\x"), "x");
813 assert_eq!(label_of(&"a".repeat(80)).len(), 32);
814 }
815}
diff --git a/d3d12/apps/leonida/src/run.rs b/d3d12/apps/leonida/src/run.rs
index ed330654c..2d2e383d6 100644
--- a/d3d12/apps/leonida/src/run.rs
+++ b/d3d12/apps/leonida/src/run.rs
@@ -224,9 +224,13 @@ pub fn run(
224 } 224 }
225 // The trainer menu's game actions (`LEONIDA_GAME_ACTIONS=1`, game_actions.rs): the title's cheat update, 225 // The trainer menu's game actions (`LEONIDA_GAME_ACTIONS=1`, game_actions.rs): the title's cheat update,
226 // once a frame, goes through the runtime, which does there what the menu asks. 226 // once a frame, goes through the runtime, which does there what the menu asks.
227 // What the player is in, for the keyboard and mouse layout (player_context.rs): read only, with or without
228 // the game actions.
227 if execute { 229 if execute {
228 // SAFETY: the image stays mapped, and nothing of it has run yet. 230 // SAFETY: the image stays mapped, and nothing of it has run yet.
229 unsafe { crate::game_actions::install(image.base(), image.info()) }; 231 let found = unsafe { crate::game_actions::install(image.base(), image.info()) };
232 // SAFETY: as above.
233 unsafe { crate::player_context::install(image.base(), image.info(), found.as_ref()) };
230 } 234 }
231 // Renderer port #2 (LEONIDA_PORT_DESCRIPTORS=1): the title's stores of descriptor records tell the layer their 235 // Renderer port #2 (LEONIDA_PORT_DESCRIPTORS=1): the title's stores of descriptor records tell the layer their
232 // slots. Only the 1.0.2.1 executable, each store's bytes checked as well. 236 // slots. Only the 1.0.2.1 executable, each store's bytes checked as well.
diff --git a/d3d12/crates/leonida-hle/src/modules/gameinput.rs b/d3d12/crates/leonida-hle/src/modules/gameinput.rs
index 2ab43a838..51f40bf5e 100644
--- a/d3d12/crates/leonida-hle/src/modules/gameinput.rs
+++ b/d3d12/crates/leonida-hle/src/modules/gameinput.rs
@@ -1,7 +1,8 @@
1//! `gameinput.dll`: input devices from the host. Gamepads come from XInput 1//! `gameinput.dll`: input devices from the host. Gamepads come from XInput
2//! (host slots 0-3) and, read over HID, from Sony pads (`hid`; the kind of input in use is `family`); 2//! (host slots 0-3) and, read over HID, from Sony pads (`hid`; the kind of input in use is `family`);
3//! while none is connected, the keyboard drives one 3//! while none is connected, the keyboard and mouse drive one
4//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own 4//! stand-in gamepad, in Grand Theft Auto V's PC layout (`kbm`: one table on foot, one in a vehicle; the table
5//! of before is `FALLBACK_BUTTONS`). The keyboard is a device of its own
5//! too. A focused window also has a mouse. A poll thread records changes 6//! too. A focused window also has a mouse. A poll thread records changes
6//! and runs device callbacks on connect and disconnect. 7//! and runs device callbacks on connect and disconnect.
7#![allow(non_snake_case)] 8#![allow(non_snake_case)]
@@ -24,8 +25,10 @@ use crate::{HleExport, HleModule};
24 25
25mod family; 26mod family;
26mod hid; 27mod hid;
28mod kbm;
27 29
28pub use family::Family; 30pub use family::Family;
31pub use kbm::{PlayerContext, driving_controls, player_context, player_context_wanted, set_player_context};
29 32
30/// Leonida: the kind of input the player is using (Xbox pad, PlayStation pad, keyboard and mouse), for the 33/// Leonida: the kind of input the player is using (Xbox pad, PlayStation pad, keyboard and mouse), for the
31/// runtime's own use: the button prompts follow it. `LEONIDA_PROMPTS` forces it. Reading it starts the input hub. 34/// runtime's own use: the button prompts follow it. `LEONIDA_PROMPTS` forces it. Reading it starts the input hub.
@@ -93,7 +96,8 @@ const DEVICES: usize = MOUSE + 1;
93const HISTORY: usize = 256; 96const HISTORY: usize = 256;
94const POLL: Duration = Duration::from_millis(8); 97const POLL: Duration = Duration::from_millis(8);
95 98
96/// The keyboard's stand-in gamepad (virtual key, button), in Leonida's layout (the one its Vulkan runtime's 99/// The keyboard's stand-in gamepad as it was before `kbm` (`LEONIDA_KBM=classic` brings it back): (virtual key,
100/// button), in Leonida's layout (the one its Vulkan runtime's
97/// gameinput shim has): the pad-named keys, and PC-style ones beside them: Space confirms/jumps (A), F interacts (Y), 101/// gameinput shim has): the pad-named keys, and PC-style ones beside them: Space confirms/jumps (A), F interacts (Y),
98/// R goes back/reloads (B), Left Shift and C click the sticks. H stays a second right-stick click. 102/// R goes back/reloads (B), Left Shift and C click the sticks. H stays a second right-stick click.
99/// Sticks: W/A/S/D left, I/J/K/L right (and the mouse, once a click in the window has it: `MouseLook`); 103/// Sticks: W/A/S/D left, I/J/K/L right (and the mouse, once a click in the window has it: `MouseLook`);
@@ -260,6 +264,7 @@ trait Source: Send {
260 fn observe(&mut self, _keys: &[KeyState], _look: (f32, f32)) {} 264 fn observe(&mut self, _keys: &[KeyState], _look: (f32, f32)) {}
261} 265}
262 266
267/// The stand-in pad of before `kbm`: one table whatever the player is in (`LEONIDA_KBM=classic`).
263fn fallback(keys: &[KeyState]) -> PadState { 268fn fallback(keys: &[KeyState]) -> PadState {
264 let on = |vk: u8| { 269 let on = |vk: u8| {
265 if keys.iter().any(|k| k.virtual_key == vk) { 270 if keys.iter().any(|k| k.virtual_key == vk) {
@@ -498,6 +503,8 @@ struct State {
498 pending: Vec<Event>, 503 pending: Vec<Event>,
499 /// Device callbacks running now: token and thread. 504 /// Device callbacks running now: token and thread.
500 running: Vec<(u64, ThreadId)>, 505 running: Vec<(u64, ThreadId)>,
506 /// Leonida: the keyboard and mouse half of the stand-in pad.
507 kbm: kbm::Kbm,
501} 508}
502 509
503pub struct Hub { 510pub struct Hub {
@@ -531,7 +538,7 @@ fn now() -> u64 {
531} 538}
532 539
533impl Hub { 540impl Hub {
534 fn new(source: Box<dyn Source>, one_pad: bool) -> &'static Hub { 541 fn with(source: Box<dyn Source>, one_pad: bool, keys: kbm::Config) -> &'static Hub {
535 let hub = Box::into_raw(Box::new(Hub { 542 let hub = Box::into_raw(Box::new(Hub {
536 object: Object { 543 object: Object {
537 vtable: &INPUT, 544 vtable: &INPUT,
@@ -545,6 +552,7 @@ impl Hub {
545 callbacks: Vec::new(), 552 callbacks: Vec::new(),
546 pending: Vec::new(), 553 pending: Vec::new(),
547 running: Vec::new(), 554 running: Vec::new(),
555 kbm: kbm::Kbm::new(keys),
548 }), 556 }),
549 returned: Condvar::new(), 557 returned: Condvar::new(),
550 })); 558 }));
@@ -560,7 +568,7 @@ impl Hub {
560 568
561 /// A hub over the host's input, polled from now on. 569 /// A hub over the host's input, polled from now on.
562 fn start(source: Box<dyn Source>) -> &'static Hub { 570 fn start(source: Box<dyn Source>) -> &'static Hub {
563 let hub = Hub::new(source, one_pad()); 571 let hub = Hub::with(source, one_pad(), kbm::Config::from_env());
564 hub.poll(); 572 hub.poll();
565 std::thread::spawn(move || { 573 std::thread::spawn(move || {
566 loop { 574 loop {
@@ -649,8 +657,10 @@ impl State {
649 .collect(); 657 .collect();
650 let mut events = std::mem::take(&mut self.pending); 658 let mut events = std::mem::take(&mut self.pending);
651 self.update(devices, MOUSE, mouse.map(Value::Mouse), now, &mut events); 659 self.update(devices, MOUSE, mouse.map(Value::Mouse), now, &mut events);
660 // Leonida: the keys and mouse buttons as a pad, by the table of what the player is in (`kbm`).
661 let stand_in = merged(self.kbm.pad(&pad_keys, kbm::measured(now), now), look);
652 if one_pad { 662 if one_pad {
653 let pad = pads.into_iter().flatten().fold(merged(fallback(&pad_keys), look), merged); 663 let pad = pads.into_iter().flatten().fold(stand_in, merged);
654 self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events); 664 self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events);
655 self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); 665 self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events);
656 return events; 666 return events;
@@ -662,7 +672,7 @@ impl State {
662 for (slot, pad) in pads.into_iter().enumerate() { 672 for (slot, pad) in pads.into_iter().enumerate() {
663 self.update(devices, slot, pad.map(Value::Pad), now, &mut events); 673 self.update(devices, slot, pad.map(Value::Pad), now, &mut events);
664 } 674 }
665 let fallback = (!any_pad).then(|| Value::Pad(merged(fallback(&pad_keys), look))); 675 let fallback = (!any_pad).then_some(Value::Pad(stand_in));
666 self.update(devices, FALLBACK, fallback, now, &mut events); 676 self.update(devices, FALLBACK, fallback, now, &mut events);
667 self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); 677 self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events);
668 events 678 events
@@ -1551,7 +1561,7 @@ mod host {
1551 // to the pad (the title's start screen) saw nothing. 1561 // to the pad (the title's start screen) saw nothing.
1552 if slot == 0 { 1562 if slot == 0 {
1553 for vk in scripted() { 1563 for vk in scripted() {
1554 if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { 1564 if let Some(button) = kbm::scripted_button(vk) {
1555 pad.buttons |= button; 1565 pad.buttons |= button;
1556 } 1566 }
1557 } 1567 }
@@ -1904,8 +1914,14 @@ mod tests {
1904 } 1914 }
1905 1915
1906 fn fake_with(one_pad: bool) -> (&'static Hub, Arc<Mutex<FakeHost>>) { 1916 fn fake_with(one_pad: bool) -> (&'static Hub, Arc<Mutex<FakeHost>>) {
1917 fake_layout(one_pad, kbm::Config::default())
1918 }
1919
1920 /// A hub whose stand-in pad has this layout. No test sets the player's context (it is one for the process):
1921 /// the hubs here see it unknown, and `kbm`'s own tests hand theirs in.
1922 fn fake_layout(one_pad: bool, keys: kbm::Config) -> (&'static Hub, Arc<Mutex<FakeHost>>) {
1907 let host = Arc::new(Mutex::new(FakeHost::default())); 1923 let host = Arc::new(Mutex::new(FakeHost::default()));
1908 let hub = Hub::new(Box::new(Fake(Arc::clone(&host))), one_pad); 1924 let hub = Hub::with(Box::new(Fake(Arc::clone(&host))), one_pad, keys);
1909 hub.poll(); 1925 hub.poll();
1910 (hub, host) 1926 (hub, host)
1911 } 1927 }
@@ -2187,6 +2203,17 @@ mod tests {
2187 assert_eq!(got[..4], keys[..]); 2203 assert_eq!(got[..4], keys[..]);
2188 release(r); 2204 release(r);
2189 2205
2206 // The pad: GTA V's layout on foot, where V is no trigger.
2207 let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap();
2208 assert_eq!(pad(r), PadState { buttons: A, left_y: 1.0, right_x: 1.0, ..Default::default() });
2209 release(r);
2210 // A keyboard reading is no gamepad reading.
2211 assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND));
2212 // The layout of before (`LEONIDA_KBM=classic`): V is the right trigger.
2213 let classic = kbm::Config { layout: kbm::Layout::Classic, ..Default::default() };
2214 let (hub, host) = fake_layout(false, classic);
2215 host.lock().unwrap().keys = keys;
2216 hub.poll();
2190 let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); 2217 let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap();
2191 assert_eq!( 2218 assert_eq!(
2192 pad(r), 2219 pad(r),
@@ -2199,8 +2226,51 @@ mod tests {
2199 } 2226 }
2200 ); 2227 );
2201 release(r); 2228 release(r);
2202 // A keyboard reading is no gamepad reading. 2229 }
2203 assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND)); 2230
2231 #[test]
2232 fn the_stand_in_pad_is_gta_vs_layout_in_both_pad_modes() {
2233 let newest = |hub: &Hub| match &hub.state().slots[FALLBACK].history.back().unwrap().value {
2234 Value::Pad(p) => *p,
2235 _ => unreachable!(),
2236 };
2237 for one_pad in [false, true] {
2238 // On foot (nobody says what the player is in): W walks, the mouse shoots and aims, and the mouse look
2239 // stick is the camera beside them.
2240 let (hub, host) = fake_with(one_pad);
2241 host.lock().unwrap().keys =
2242 vec![key(b'W'), key(VK_MOUSE_LEFT), key(VK_MOUSE_RIGHT), key(0x20), key(0xA0)];
2243 hub.poll();
2244 assert_eq!(
2245 newest(hub),
2246 PadState {
2247 buttons: A | LEFT_STICK,
2248 left_y: 1.0,
2249 left_trigger: 1.0,
2250 right_trigger: 1.0,
2251 ..Default::default()
2252 }
2253 );
2254 // The driving table (forced, as `LEONIDA_KBM_DRIVE=on` does): W is the accelerator, the left mouse
2255 // button shoots from the vehicle, Left Shift leans.
2256 let driving = kbm::Config { drive: kbm::Drive::On, settle: 0, ..Default::default() };
2257 let (hub, host) = fake_layout(one_pad, driving);
2258 host.lock().unwrap().keys = vec![key(b'W'), key(b'A'), key(VK_MOUSE_LEFT), key(0x20), key(0xA0)];
2259 hub.poll();
2260 assert_eq!(
2261 newest(hub),
2262 PadState {
2263 buttons: A | RIGHT_SHOULDER,
2264 left_x: -1.0,
2265 left_y: 1.0,
2266 right_trigger: 1.0,
2267 ..Default::default()
2268 }
2269 );
2270 }
2271 // The context is unknown here, and saying so again changes nothing.
2272 set_player_context(PlayerContext::Unknown);
2273 assert_eq!(player_context(), PlayerContext::Unknown);
2204 } 2274 }
2205 2275
2206 #[test] 2276 #[test]
diff --git a/d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs b/d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs
new file mode 100644
index 000000000..00a2978c4
--- /dev/null
+++ b/d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs
@@ -0,0 +1,879 @@
1//! Leonida: the keyboard and mouse as the title's pad, in Grand Theft Auto V's PC layout.
2//!
3//! The title reads an Xbox pad only, and a pad button means different things on foot and in a vehicle: the right
4//! trigger shoots on foot and accelerates in a car, the left trigger aims and brakes. One table of keys cannot be
5//! a PC layout then (W would have to be the left stick and the right trigger at once), so there are two, one on
6//! foot and one in a vehicle (`SHARED` with `FOOT_ONLY` or with `VEHICLE_ONLY`), and which one counts follows what
7//! the player is in ([`PlayerContext`]): told from outside with [`set_player_context`] (the runtime reads it from
8//! the title), and while nobody tells, the on-foot table with Caps Lock as the switch to the driving one by hand
9//! (only then: Caps Lock is GTA V's special ability, and a press out of habit must not change the keys).
10//!
11//! The keys are Grand Theft Auto V's defaults (its Settings > Key Bindings, as listed in BisectHosting's and
12//! StrategyWiki's control guides); the pad button of each action is the title's own default pad layout as far as
13//! it is known (`docs/gameinput.md`). A GTA V key whose action has no known pad button here is left out.
14//!
15//! The hand-over rule, when the table changes: a key whose pad input differs between the tables and that is down
16//! at that moment gives nothing until it has been let go and pressed again, and no such key gives anything for
17//! a short pause (`Config::settle`) after the change. So the left mouse button, held on foot to shoot, never
18//! becomes the accelerator, and W, held to accelerate, never becomes a shot. A key that is the same pad input in
19//! both tables (A and D, Space, F) carries over, as the button of a real pad would.
20//!
21//! `LEONIDA_KBM=classic` brings back the single table of before ([`super::fallback`]);
22//! `LEONIDA_KBM_DRIVE=on|off|auto` forces the driving table on or off (a test), `auto` being the default;
23//! `LEONIDA_KBM_SETTLE_MS` (400; 0..3000) is the pause after a change.
24
25use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
26
27use super::{
28 A, B, DOWN, KeyState, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER, RIGHT_STICK, UP,
29 VIEW, VK_MOUSE_LEFT, VK_MOUSE_RIGHT, X, Y,
30};
31
32const VK_BACK: u8 = 0x08;
33const VK_TAB: u8 = 0x09;
34const VK_RETURN: u8 = 0x0D;
35const VK_CAPITAL: u8 = 0x14;
36const VK_ESCAPE: u8 = 0x1B;
37const VK_SPACE: u8 = 0x20;
38const VK_LEFT: u8 = 0x25;
39const VK_UP: u8 = 0x26;
40const VK_RIGHT: u8 = 0x27;
41const VK_DOWN: u8 = 0x28;
42const VK_NUMPAD4: u8 = 0x64;
43const VK_NUMPAD5: u8 = 0x65;
44const VK_NUMPAD6: u8 = 0x66;
45const VK_NUMPAD8: u8 = 0x68;
46const VK_LSHIFT: u8 = 0xA0;
47const VK_LCONTROL: u8 = 0xA2;
48const VK_LMENU: u8 = 0xA4;
49const VK_RMENU: u8 = 0xA5;
50
51/// The key that enters and leaves a vehicle (Y on the pad, in both tables).
52const VK_ENTER_EXIT: u8 = b'F';
53/// Keys that give nothing while an Alt key is down: with it they are shortcuts of Windows.
54const WITH_ALT: [u8; 4] = [VK_TAB, VK_RETURN, VK_SPACE, VK_ESCAPE];
55
56/// What the player is in, as far as the runtime can tell.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum PlayerContext {
59 /// Nobody has told, or not for [`STALE`]: the on-foot table, and Caps Lock switches by hand.
60 Unknown = 0,
61 OnFoot = 1,
62 InVehicle = 2,
63}
64
65/// A context that was not set again for this long is unknown: 500 ms, in the clock of [`super::now`].
66const STALE: u64 = 500_000;
67/// And the stand-in pad only lets go of a known context once it has seen it unknown for this long (100 ms): after
68/// a stall of the whole process the poll may run before whoever sets the context does.
69const UNKNOWN_AFTER: u64 = 100_000;
70
71/// The context and when it was set, in one word: no lock between the thread that sets it and the poll.
72pub(super) struct Shared(AtomicU64);
73
74impl Shared {
75 pub(super) const fn new() -> Shared {
76 Shared(AtomicU64::new(0))
77 }
78
79 /// `now`: microseconds ([`super::now`]).
80 pub(super) fn set(&self, context: PlayerContext, now: u64) {
81 self.0.store((now << 2) | context as u64, Ordering::Relaxed);
82 }
83
84 pub(super) fn get(&self, now: u64) -> PlayerContext {
85 let word = self.0.load(Ordering::Relaxed);
86 if now.saturating_sub(word >> 2) > STALE {
87 return PlayerContext::Unknown;
88 }
89 match word & 3 {
90 1 => PlayerContext::OnFoot,
91 2 => PlayerContext::InVehicle,
92 _ => PlayerContext::Unknown,
93 }
94 }
95}
96
97static CONTEXT: Shared = Shared::new();
98/// Whether the driving table is the one in use now (what the stand-in pad last decided).
99static DRIVING: AtomicBool = AtomicBool::new(false);
100
101/// Tells the stand-in pad what the player is in. It holds for half a second, so whoever knows says it again and
102/// again (once a frame); a context nobody renews becomes [`PlayerContext::Unknown`]. Lock-free; any thread.
103pub fn set_player_context(context: PlayerContext) {
104 CONTEXT.set(context, super::now());
105}
106
107/// The context last set, [`PlayerContext::Unknown`] once it is stale.
108pub fn player_context() -> PlayerContext {
109 CONTEXT.get(super::now())
110}
111
112/// Whether the keyboard and mouse are on the driving table now (W accelerates, the left mouse button shoots from
113/// the vehicle): the measured context, or Caps Lock, or `LEONIDA_KBM_DRIVE`. For whoever shows key prompts.
114pub fn driving_controls() -> bool {
115 DRIVING.load(Ordering::Relaxed)
116}
117
118/// Whether the stand-in pad follows the player's context at all: not with `LEONIDA_KBM=classic` nor with
119/// `LEONIDA_KBM_DRIVE=on|off`. Whoever would measure the context need not when this is false.
120pub fn player_context_wanted() -> bool {
121 let config = Config::from_env();
122 config.layout == Layout::GtaV && config.drive == Drive::Auto
123}
124
125/// What a key does to the pad.
126#[derive(Clone, Copy, Debug, PartialEq)]
127enum To {
128 Button(u32),
129 LeftTrigger,
130 RightTrigger,
131 /// A push of the left stick: -1 or 1 (x right, y up).
132 LeftX(f32),
133 LeftY(f32),
134 RightX(f32),
135 RightY(f32),
136}
137
138type Bind = (u8, To);
139
140/// The keys that mean the same in both tables. GTA V's key, the pad input, and what it does in the title.
141const SHARED: &[Bind] = &[
142 // Move, steer (the left stick's x in a vehicle).
143 (b'A', To::LeftX(-1.0)),
144 (b'D', To::LeftX(1.0)),
145 // Jump and climb on foot, the handbrake in a vehicle: the title's A.
146 (VK_SPACE, To::Button(A)),
147 // Enter a vehicle, leave it: the title's Y.
148 (VK_ENTER_EXIT, To::Button(Y)),
149 // Reload (GTA V's R; melee too): the title's X. In a vehicle GTA V has the cinematic camera on R, which has no
150 // known button here, so R stays the same pad button there.
151 (b'R', To::Button(X)),
152 // The weapon wheel: the title's loadout wheel (hold), holster (tap).
153 (VK_TAB, To::Button(LEFT_SHOULDER)),
154 // Look behind; zoom while aiming.
155 (b'C', To::Button(RIGHT_STICK)),
156 // Pause: Esc and P.
157 (VK_ESCAPE, To::Button(MENU)),
158 (b'P', To::Button(MENU)),
159 // The map (the title's View button).
160 (b'M', To::Button(VIEW)),
161 // The phone (up) and its menus; down is the title's HUD and objective, left its radio menu, right its partner
162 // menu.
163 (VK_UP, To::Button(UP)),
164 (VK_DOWN, To::Button(DOWN)),
165 (VK_LEFT, To::Button(LEFT)),
166 (VK_RIGHT, To::Button(RIGHT)),
167 // Phone and menus: accept, back.
168 (VK_RETURN, To::Button(A)),
169 (VK_BACK, To::Button(B)),
170 // GTA V's radar zoom and info: the same d-pad press as on its pad.
171 (b'Z', To::Button(DOWN)),
172 // (GTA V's character switch, Left Alt, would be the title's partner menu, d-pad right. It is left out: every
173 // Alt+Tab would press it. The right arrow is that button.)
174 // Not GTA V's: the pad-named keys of the layout before, where GTA V has nothing on them.
175 (b'Y', To::Button(Y)),
176 (b'I', To::RightY(1.0)),
177 (b'K', To::RightY(-1.0)),
178 (b'J', To::RightX(-1.0)),
179 (b'L', To::RightX(1.0)),
180 // (The mouse itself is the right stick: `MouseLook`.)
181];
182
183/// On foot.
184const FOOT_ONLY: &[Bind] = &[
185 (b'W', To::LeftY(1.0)),
186 (b'S', To::LeftY(-1.0)),
187 // Shoot, aim.
188 (VK_MOUSE_LEFT, To::RightTrigger),
189 (VK_MOUSE_RIGHT, To::LeftTrigger),
190 // Sprint: the title runs on a click of the left stick.
191 (VK_LSHIFT, To::Button(LEFT_STICK)),
192 // GTA V's stealth: the title's crouch.
193 (VK_LCONTROL, To::Button(B)),
194 // Cover.
195 (b'Q', To::Button(RIGHT_SHOULDER)),
196 // GTA V's context action: the title interacts with Y.
197 (b'E', To::Button(Y)),
198];
199
200/// In a vehicle.
201const VEHICLE_ONLY: &[Bind] = &[
202 // Accelerate; brake and reverse.
203 (b'W', To::RightTrigger),
204 (b'S', To::LeftTrigger),
205 // Lean forward and back on a bike, the nose of an aircraft: the left stick's y. Num 4 and 6 roll.
206 (VK_LSHIFT, To::LeftY(1.0)),
207 (VK_NUMPAD8, To::LeftY(1.0)),
208 (VK_LCONTROL, To::LeftY(-1.0)),
209 (VK_NUMPAD5, To::LeftY(-1.0)),
210 (VK_NUMPAD4, To::LeftX(-1.0)),
211 (VK_NUMPAD6, To::LeftX(1.0)),
212 // The horn.
213 (b'E', To::Button(LEFT_STICK)),
214 // Shoot from the vehicle. (Aiming from it, GTA V's right mouse button, has no known button here.)
215 (VK_MOUSE_LEFT, To::Button(RIGHT_SHOULDER)),
216 // Duck; the headlights.
217 (b'X', To::Button(B)),
218 (b'H', To::Button(B)),
219 // GTA V's radio wheel: the title's radio menu.
220 (b'Q', To::Button(LEFT)),
221];
222
223/// The two tables: what is shared, then what is the context's own.
224fn table(driving: bool) -> impl Iterator<Item = &'static Bind> {
225 SHARED.iter().chain(if driving { VEHICLE_ONLY } else { FOOT_ONLY })
226}
227
228/// What `key` does in a table, in the table's order.
229fn outputs(driving: bool, key: u8) -> impl Iterator<Item = To> {
230 table(driving).filter(move |(k, _)| *k == key).map(|(_, to)| *to)
231}
232
233/// Whether `key` is another pad input in a vehicle than on foot: the keys the hand-over rule is about.
234fn changes(key: u8) -> bool {
235 !outputs(false, key).eq(outputs(true, key))
236}
237
238/// The pad of a table, with the keys `on` says are down.
239fn pad_of(driving: bool, on: impl Fn(u8) -> bool) -> PadState {
240 let mut pad = PadState::default();
241 for &(key, to) in table(driving) {
242 if !on(key) {
243 continue;
244 }
245 match to {
246 To::Button(bit) => pad.buttons |= bit,
247 To::LeftTrigger => pad.left_trigger = 1.0,
248 To::RightTrigger => pad.right_trigger = 1.0,
249 To::LeftX(push) => pad.left_x += push,
250 To::LeftY(push) => pad.left_y += push,
251 To::RightX(push) => pad.right_x += push,
252 To::RightY(push) => pad.right_y += push,
253 }
254 }
255 for axis in [&mut pad.left_x, &mut pad.left_y, &mut pad.right_x, &mut pad.right_y] {
256 *axis = axis.clamp(-1.0, 1.0);
257 }
258 pad
259}
260
261/// The button a scripted key (`LEONIDA_KEYS`) presses on a real pad: the on-foot table's, or with
262/// `LEONIDA_KBM=classic` the old table's.
263#[cfg_attr(not(windows), allow(dead_code))]
264pub(super) fn scripted_button(key: u8) -> Option<u32> {
265 if Config::from_env().layout == Layout::Classic {
266 return super::FALLBACK_BUTTONS.iter().find(|(k, _)| *k == key).map(|(_, bit)| *bit);
267 }
268 outputs(false, key).find_map(|to| match to {
269 To::Button(bit) => Some(bit),
270 _ => None,
271 })
272}
273
274#[derive(Clone, Copy, Debug, PartialEq, Eq)]
275pub(super) enum Layout {
276 GtaV,
277 Classic,
278}
279
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
281pub(super) enum Drive {
282 Auto,
283 On,
284 Off,
285}
286
287#[derive(Clone, Copy, Debug, PartialEq, Eq)]
288pub(super) struct Config {
289 pub(super) layout: Layout,
290 pub(super) drive: Drive,
291 /// Microseconds after a change of table in which no key that changes with it counts.
292 pub(super) settle: u64,
293}
294
295impl Default for Config {
296 fn default() -> Config {
297 Config { layout: Layout::GtaV, drive: Drive::Auto, settle: 400_000 }
298 }
299}
300
301impl Config {
302 /// From the values of `LEONIDA_KBM`, `LEONIDA_KBM_DRIVE` and `LEONIDA_KBM_SETTLE_MS`; what does not read is
303 /// the default.
304 pub(super) fn parse(kbm: Option<&str>, drive: Option<&str>, settle_ms: Option<&str>) -> Config {
305 let default = Config::default();
306 let word = |v: Option<&str>| v.map(|v| v.trim().to_ascii_lowercase());
307 Config {
308 layout: match word(kbm).as_deref() {
309 Some("classic") => Layout::Classic,
310 _ => Layout::GtaV,
311 },
312 drive: match word(drive).as_deref() {
313 Some("on" | "1") => Drive::On,
314 Some("off" | "0") => Drive::Off,
315 _ => Drive::Auto,
316 },
317 settle: settle_ms
318 .and_then(|v| v.trim().parse::<u64>().ok())
319 .map_or(default.settle, |ms| ms.min(3000) * 1000),
320 }
321 }
322
323 pub(super) fn from_env() -> Config {
324 static CONFIG: std::sync::LazyLock<Config> = std::sync::LazyLock::new(|| {
325 let var = |name: &str| std::env::var(name).ok();
326 Config::parse(
327 var("LEONIDA_KBM").as_deref(),
328 var("LEONIDA_KBM_DRIVE").as_deref(),
329 var("LEONIDA_KBM_SETTLE_MS").as_deref(),
330 )
331 });
332 *CONFIG
333 }
334}
335
336/// A set of virtual keys.
337#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
338struct Keys([u64; 4]);
339
340impl Keys {
341 fn of(keys: &[KeyState]) -> Keys {
342 let mut set = Keys::default();
343 for key in keys {
344 set.0[usize::from(key.virtual_key >> 6)] |= 1 << (key.virtual_key & 63);
345 }
346 set
347 }
348
349 fn has(&self, key: u8) -> bool {
350 self.0[usize::from(key >> 6)] & (1 << (key & 63)) != 0
351 }
352
353 fn both(&self, other: &Keys) -> Keys {
354 Keys(std::array::from_fn(|i| self.0[i] & other.0[i]))
355 }
356
357 fn either(&self, other: &Keys) -> Keys {
358 Keys(std::array::from_fn(|i| self.0[i] | other.0[i]))
359 }
360
361 /// Those of the set `keep` says yes to.
362 fn only(&self, keep: impl Fn(u8) -> bool) -> Keys {
363 let mut set = Keys::default();
364 for key in 0..=u8::MAX {
365 if self.has(key) && keep(key) {
366 set.0[usize::from(key >> 6)] |= 1 << (key & 63);
367 }
368 }
369 set
370 }
371}
372
373/// The stand-in pad's keyboard and mouse half: which table counts, and the hand-over between them.
374#[derive(Debug)]
375pub(super) struct Kbm {
376 config: Config,
377 /// The table in use.
378 driving: bool,
379 /// Caps Lock's say while no context is measured: the driving table, until Caps Lock again or F (which leaves
380 /// the vehicle).
381 by_hand: bool,
382 /// The measured context as it counts (see [`UNKNOWN_AFTER`]).
383 measured: PlayerContext,
384 unknown_since: Option<u64>,
385 /// The keys down at the last poll.
386 down: Keys,
387 /// Keys that were down when the table changed: nothing from them until they are let go.
388 latched: Keys,
389 /// Until then (microseconds) no key that changes with the table counts.
390 settle_until: u64,
391}
392
393impl Kbm {
394 pub(super) fn new(config: Config) -> Kbm {
395 Kbm {
396 config,
397 driving: false,
398 by_hand: false,
399 measured: PlayerContext::Unknown,
400 unknown_since: None,
401 down: Keys::default(),
402 latched: Keys::default(),
403 settle_until: 0,
404 }
405 }
406
407 /// The pad the keys held make, with the context measured now (`now`: microseconds).
408 pub(super) fn pad(&mut self, keys: &[KeyState], measured: PlayerContext, now: u64) -> PadState {
409 if self.config.layout == Layout::Classic {
410 return super::fallback(keys);
411 }
412 let (mut down, was) = (Keys::of(keys), self.down);
413 // With Alt down these are Windows' own (Alt+Tab, Alt+Enter, Alt+Space, Alt+Esc), not the game's.
414 if down.has(VK_LMENU) || down.has(VK_RMENU) {
415 down = down.only(|key| !WITH_ALT.contains(&key));
416 }
417 let pressed = |key: u8| down.has(key) && !was.has(key);
418 let (wanted, why) = match self.config.drive {
419 Drive::On => (true, "LEONIDA_KBM_DRIVE=on"),
420 Drive::Off => (false, "LEONIDA_KBM_DRIVE=off"),
421 Drive::Auto => {
422 let measured = self.settled(measured, now);
423 if measured != self.measured {
424 // What is measured counts; driving by hand is for when nothing is, and starts anew then.
425 self.measured = measured;
426 self.by_hand = false;
427 }
428 match self.measured {
429 PlayerContext::InVehicle => (true, "the player is in a vehicle"),
430 PlayerContext::OnFoot => (false, "the player is on foot"),
431 PlayerContext::Unknown if pressed(VK_CAPITAL) => {
432 self.by_hand = !self.by_hand;
433 (self.by_hand, "Caps Lock")
434 }
435 PlayerContext::Unknown if pressed(VK_ENTER_EXIT) && self.by_hand => {
436 // Driving by hand, and the player leaves the vehicle: W must not stay the right trigger.
437 self.by_hand = false;
438 (false, "F leaves the vehicle; Caps Lock is the driving keys")
439 }
440 PlayerContext::Unknown => (self.by_hand, "what the player is in is not known"),
441 }
442 }
443 };
444 if wanted != self.driving {
445 self.driving = wanted;
446 DRIVING.store(wanted, Ordering::Relaxed);
447 self.latched = self.latched.either(&down.only(changes));
448 self.settle_until = now + self.config.settle;
449 tracing::info!(
450 "keyboard and mouse: {} controls ({why})",
451 if wanted { "driving" } else { "on-foot" }
452 );
453 }
454 self.latched = self.latched.both(&down);
455 self.down = down;
456 let settling = now < self.settle_until;
457 let latched = self.latched;
458 pad_of(self.driving, |key| down.has(key) && !latched.has(key) && !(settling && changes(key)))
459 }
460
461 /// The measured context, an unknown one only once it has been unknown for [`UNKNOWN_AFTER`].
462 fn settled(&mut self, measured: PlayerContext, now: u64) -> PlayerContext {
463 if measured != PlayerContext::Unknown || self.measured == PlayerContext::Unknown {
464 self.unknown_since = None;
465 return measured;
466 }
467 let since = *self.unknown_since.get_or_insert(now);
468 if now.saturating_sub(since) < UNKNOWN_AFTER { self.measured } else { measured }
469 }
470}
471
472/// The context for the poll at `now`.
473pub(super) fn measured(now: u64) -> PlayerContext {
474 CONTEXT.get(now)
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 const MS: u64 = 1000;
482 const FOOT: PlayerContext = PlayerContext::OnFoot;
483 const CAR: PlayerContext = PlayerContext::InVehicle;
484 const UNKNOWN: PlayerContext = PlayerContext::Unknown;
485
486 fn keys(held: &[u8]) -> Vec<KeyState> {
487 held.iter().map(|&vk| KeyState { virtual_key: vk, ..Default::default() }).collect()
488 }
489
490 fn foot(held: &[u8]) -> PadState {
491 pad_of(false, |key| held.contains(&key))
492 }
493
494 fn car(held: &[u8]) -> PadState {
495 pad_of(true, |key| held.contains(&key))
496 }
497
498 fn button(bit: u32) -> PadState {
499 PadState { buttons: bit, ..Default::default() }
500 }
501
502 fn kbm() -> Kbm {
503 Kbm::new(Config::default())
504 }
505
506 /// Whether the pad pulls a trigger or presses the button that shoots from a vehicle.
507 fn fires_or_drives(pad: &PadState) -> bool {
508 pad.left_trigger != 0.0 || pad.right_trigger != 0.0 || pad.buttons & RIGHT_SHOULDER != 0
509 }
510
511 #[test]
512 fn on_foot_is_gta_vs_layout() {
513 // Movement is W A S D, and nothing else of them.
514 assert_eq!(foot(b"W"), PadState { left_y: 1.0, ..Default::default() });
515 assert_eq!(foot(b"S"), PadState { left_y: -1.0, ..Default::default() });
516 assert_eq!(foot(b"A"), PadState { left_x: -1.0, ..Default::default() });
517 assert_eq!(foot(b"D"), PadState { left_x: 1.0, ..Default::default() });
518 assert_eq!(foot(b"WS"), PadState::default());
519 // Shooting and aiming are the mouse, and nothing else of it.
520 assert_eq!(foot(&[VK_MOUSE_LEFT]), PadState { right_trigger: 1.0, ..Default::default() });
521 assert_eq!(foot(&[VK_MOUSE_RIGHT]), PadState { left_trigger: 1.0, ..Default::default() });
522 for (key, bit) in [
523 (VK_SPACE, A),
524 (VK_LSHIFT, LEFT_STICK),
525 (VK_LCONTROL, B),
526 (b'Q', RIGHT_SHOULDER),
527 (b'R', X),
528 (b'F', Y),
529 (b'E', Y),
530 (VK_TAB, LEFT_SHOULDER),
531 (b'C', RIGHT_STICK),
532 (b'M', VIEW),
533 (VK_ESCAPE, MENU),
534 (b'P', MENU),
535 (VK_UP, UP),
536 (VK_DOWN, DOWN),
537 (VK_LEFT, LEFT),
538 (VK_RIGHT, RIGHT),
539 (VK_RETURN, A),
540 (VK_BACK, B),
541 (b'Z', DOWN),
542 (b'Y', Y),
543 ] {
544 assert_eq!(foot(&[key]), button(bit), "key {key:#x}");
545 }
546 assert_eq!(foot(b"IL"), PadState { right_x: 1.0, right_y: 1.0, ..Default::default() });
547 // GTA V keys whose action has no known pad button: nothing. So are the old layout's trigger keys.
548 for key in *b"VGXHOTBN1234567890" {
549 assert_eq!(foot(&[key]), PadState::default(), "key {}", key as char);
550 }
551 assert_eq!(foot(&[VK_CAPITAL, VK_NUMPAD8, VK_NUMPAD5, VK_LMENU, VK_RMENU]), PadState::default());
552 }
553
554 #[test]
555 fn alt_tab_presses_nothing() {
556 let mut k = kbm();
557 // Alt, then Tab (or Enter, Space, Esc) with it: Windows' shortcuts, no button of the pad.
558 assert_eq!(k.pad(&keys(&[VK_LMENU]), FOOT, 0), PadState::default());
559 for key in [VK_TAB, VK_RETURN, VK_SPACE, VK_ESCAPE] {
560 assert_eq!(k.pad(&keys(&[VK_LMENU, key]), FOOT, 8 * MS), PadState::default(), "key {key:#x}");
561 assert_eq!(k.pad(&keys(&[VK_RMENU, key]), FOOT, 16 * MS), PadState::default(), "key {key:#x}");
562 }
563 // Other keys are not held back, and without Alt Tab is the weapon wheel.
564 assert_eq!(k.pad(&keys(&[VK_LMENU, b'W']), FOOT, 24 * MS), PadState { left_y: 1.0, ..Default::default() });
565 assert_eq!(k.pad(&keys(&[VK_TAB]), FOOT, 32 * MS), button(LEFT_SHOULDER));
566 }
567
568 #[test]
569 fn in_a_vehicle_w_and_s_are_the_triggers_and_the_mouse_shoots() {
570 // W accelerates, S brakes: the triggers, fully, and not the stick.
571 assert_eq!(car(b"W"), PadState { right_trigger: 1.0, ..Default::default() });
572 assert_eq!(car(b"S"), PadState { left_trigger: 1.0, ..Default::default() });
573 assert_eq!(car(b"WS"), PadState { left_trigger: 1.0, right_trigger: 1.0, ..Default::default() });
574 // A and D steer.
575 assert_eq!(car(b"A"), PadState { left_x: -1.0, ..Default::default() });
576 assert_eq!(car(b"D"), PadState { left_x: 1.0, ..Default::default() });
577 // Bikes and aircraft: Shift and Ctrl (and the number pad) are the stick's other axis.
578 assert_eq!(car(&[VK_LSHIFT]), PadState { left_y: 1.0, ..Default::default() });
579 assert_eq!(car(&[VK_LCONTROL]), PadState { left_y: -1.0, ..Default::default() });
580 assert_eq!(car(&[VK_LSHIFT, VK_NUMPAD8]), PadState { left_y: 1.0, ..Default::default() });
581 assert_eq!(car(&[VK_NUMPAD5, VK_NUMPAD6]), PadState { left_x: 1.0, left_y: -1.0, ..Default::default() });
582 assert_eq!(car(&[VK_NUMPAD4]), PadState { left_x: -1.0, ..Default::default() });
583 // The left mouse button shoots from the vehicle, which is a button and no trigger. The right one has no
584 // known button.
585 assert_eq!(car(&[VK_MOUSE_LEFT]), button(RIGHT_SHOULDER));
586 assert_eq!(car(&[VK_MOUSE_RIGHT]), PadState::default());
587 for (key, bit) in [
588 (VK_SPACE, A),
589 (b'F', Y),
590 (b'E', LEFT_STICK),
591 (b'X', B),
592 (b'H', B),
593 (b'Q', LEFT),
594 (b'R', X),
595 (b'C', RIGHT_STICK),
596 (VK_TAB, LEFT_SHOULDER),
597 (b'M', VIEW),
598 (VK_ESCAPE, MENU),
599 (VK_UP, UP),
600 (VK_RETURN, A),
601 (VK_BACK, B),
602 ] {
603 assert_eq!(car(&[key]), button(bit), "key {key:#x}");
604 }
605 for key in *b"VGOTBN1234567890" {
606 assert_eq!(car(&[key]), PadState::default(), "key {}", key as char);
607 }
608 }
609
610 /// The two rules the layout stands on, read off the tables: no table makes a mouse button the accelerator or
611 /// the brake, and no table makes W or S a shot.
612 #[test]
613 fn the_mouse_never_drives_and_w_never_shoots() {
614 for mouse in [VK_MOUSE_LEFT, VK_MOUSE_RIGHT] {
615 assert!(outputs(true, mouse).all(|to| !matches!(to, To::LeftTrigger | To::RightTrigger)));
616 assert!(outputs(false, mouse).all(|to| matches!(to, To::LeftTrigger | To::RightTrigger)));
617 }
618 for key in *b"WASD" {
619 assert!(outputs(false, key).all(|to| matches!(to, To::LeftX(_) | To::LeftY(_))), "{}", key as char);
620 assert!(outputs(true, key).all(|to| to != To::Button(RIGHT_SHOULDER)), "{}", key as char);
621 }
622 // What changes with the table, and what does not.
623 for key in [b'W', b'S', VK_MOUSE_LEFT, VK_MOUSE_RIGHT, VK_LSHIFT, VK_LCONTROL, b'Q', b'E', b'X', b'H'] {
624 assert!(changes(key), "key {key:#x}");
625 }
626 for key in [b'A', b'D', VK_SPACE, b'F', b'R', b'C', VK_TAB, VK_ESCAPE, VK_UP, b'M', b'V'] {
627 assert!(!changes(key), "key {key:#x}");
628 }
629 // No key is bound twice to the same thing, and the tables are not empty.
630 for driving in [false, true] {
631 let all: Vec<&Bind> = table(driving).collect();
632 assert!(all.len() > 25);
633 for (i, a) in all.iter().enumerate() {
634 assert!(all[i + 1..].iter().all(|b| a != b), "{a:?} twice");
635 }
636 }
637 }
638
639 #[test]
640 fn entering_a_vehicle_with_keys_held_neither_shoots_nor_accelerates() {
641 let mut k = kbm();
642 // On foot: walking forward and shooting.
643 let held = keys(&[b'W', VK_MOUSE_LEFT, b'A']);
644 let pad = k.pad(&held, FOOT, 0);
645 assert_eq!(pad, PadState { left_x: -1.0, left_y: 1.0, right_trigger: 1.0, ..Default::default() });
646 // The player is in a vehicle now, the keys still down: neither W nor the mouse button gives anything,
647 // however long they stay down. A (the same stick push in both) carries over.
648 for ms in [8, 100, 399, 400, 1000, 60_000] {
649 let pad = k.pad(&held, CAR, ms * MS);
650 assert_eq!(pad, PadState { left_x: -1.0, ..Default::default() }, "{ms} ms");
651 }
652 // The mouse button let go and pressed again: it shoots from the vehicle, and is still no accelerator.
653 k.pad(&keys(&[b'W', b'A']), CAR, 60_008 * MS);
654 let pad = k.pad(&held, CAR, 60_016 * MS);
655 assert_eq!(pad, PadState { buttons: RIGHT_SHOULDER, left_x: -1.0, ..Default::default() });
656 // W let go and pressed again: it accelerates.
657 k.pad(&keys(&[]), CAR, 60_024 * MS);
658 let pad = k.pad(&keys(b"W"), CAR, 60_032 * MS);
659 assert_eq!(pad, PadState { right_trigger: 1.0, ..Default::default() });
660 }
661
662 #[test]
663 fn leaving_a_vehicle_with_keys_held_neither_shoots_nor_walks() {
664 let mut k = kbm();
665 k.pad(&keys(&[]), CAR, 0);
666 // Accelerating, steering, the handbrake on.
667 let held = keys(&[b'W', b'D', VK_SPACE]);
668 let pad = k.pad(&held, CAR, 1000 * MS);
669 assert_eq!(pad, PadState { buttons: A, left_x: 1.0, right_trigger: 1.0, ..Default::default() });
670 // On foot now with W still down: no trigger (it would be a shot), and no walking until W is pressed
671 // again. D and Space are the same pad input in both.
672 for ms in [1008, 1200, 1400, 5000] {
673 let pad = k.pad(&held, FOOT, ms * MS);
674 assert_eq!(pad, PadState { buttons: A, left_x: 1.0, ..Default::default() }, "{ms} ms");
675 }
676 k.pad(&keys(&[]), FOOT, 5008 * MS);
677 assert_eq!(k.pad(&keys(b"W"), FOOT, 5016 * MS), PadState { left_y: 1.0, ..Default::default() });
678 }
679
680 #[test]
681 fn a_key_pressed_right_after_the_change_waits_for_the_pause() {
682 let mut k = kbm();
683 k.pad(&keys(&[]), FOOT, 0);
684 k.pad(&keys(&[]), CAR, 1000 * MS);
685 // Pressed 50 ms after the change: nothing until 400 ms after it, then what the new table says.
686 for ms in [1050, 1200, 1399] {
687 assert_eq!(k.pad(&keys(&[b'W', VK_MOUSE_LEFT]), CAR, ms * MS), PadState::default(), "{ms} ms");
688 }
689 let pad = k.pad(&keys(&[b'W', VK_MOUSE_LEFT]), CAR, 1400 * MS);
690 assert_eq!(pad, PadState { buttons: RIGHT_SHOULDER, right_trigger: 1.0, ..Default::default() });
691 // A key that is the same in both tables does not wait.
692 let mut k = kbm();
693 k.pad(&keys(&[]), CAR, 0);
694 k.pad(&keys(&[]), FOOT, 1000 * MS);
695 assert_eq!(k.pad(&keys(b"F"), FOOT, 1008 * MS), button(Y));
696 assert_eq!(k.pad(&keys(&[b'F', VK_MOUSE_LEFT]), FOOT, 1100 * MS), button(Y));
697 // With no pause set, a fresh press counts at once; a held key still does not.
698 let mut k = Kbm::new(Config { settle: 0, ..Config::default() });
699 k.pad(&keys(b"S"), FOOT, 0);
700 assert_eq!(k.pad(&keys(b"S"), CAR, 8 * MS), PadState::default());
701 assert_eq!(k.pad(&keys(b"SW"), CAR, 16 * MS), PadState { right_trigger: 1.0, ..Default::default() });
702 }
703
704 /// Whatever is held when the table changes, in either direction: until a key is pressed anew, nothing pulls
705 /// a trigger and nothing shoots from the vehicle.
706 #[test]
707 fn no_set_of_held_keys_fires_or_drives_across_a_change() {
708 let changing = [b'W', b'S', VK_MOUSE_LEFT, VK_MOUSE_RIGHT, VK_LSHIFT, VK_LCONTROL, b'Q', b'E', b'X', b'H'];
709 for (from, to) in [(FOOT, CAR), (CAR, FOOT), (UNKNOWN, CAR), (CAR, UNKNOWN)] {
710 for mask in 0u32..1 << changing.len() {
711 let held: Vec<u8> =
712 changing.iter().enumerate().filter(|(i, _)| mask & (1 << i) != 0).map(|(_, k)| *k).collect();
713 let held = keys(&held);
714 let mut k = kbm();
715 k.pad(&keys(&[]), from, 0);
716 k.pad(&held, from, 1000 * MS);
717 for ms in [1008, 1100, 1399, 1400, 1500, 9000] {
718 let pad = k.pad(&held, to, ms * MS);
719 // (An unknown context counts 100 ms late; until then the pad is the old table's.)
720 if to == UNKNOWN && ms < 1108 {
721 continue;
722 }
723 assert_eq!(pad, PadState::default(), "{from:?} to {to:?}, keys {mask:#b}, {ms} ms");
724 assert!(!fires_or_drives(&pad));
725 }
726 }
727 }
728 }
729
730 #[test]
731 fn caps_lock_switches_by_hand_while_the_context_is_unknown() {
732 let mut k = kbm();
733 // Unknown: on foot.
734 assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 0), PadState { left_y: 1.0, ..Default::default() });
735 k.pad(&keys(&[]), UNKNOWN, 8 * MS);
736 // Caps Lock: driving, once per press however long it is held.
737 for ms in [16, 24, 500, 2000] {
738 k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, ms * MS);
739 assert!(k.driving, "{ms} ms");
740 }
741 k.pad(&keys(&[]), UNKNOWN, 2008 * MS);
742 assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 2016 * MS), PadState { right_trigger: 1.0, ..Default::default() });
743 // Caps Lock again, W still down: on foot, and W gives nothing until pressed again.
744 assert_eq!(k.pad(&keys(&[b'W', VK_CAPITAL]), UNKNOWN, 3000 * MS), PadState::default());
745 assert!(!k.driving);
746 k.pad(&keys(&[]), UNKNOWN, 3008 * MS);
747 // Driving by hand ends when F leaves the vehicle: W must not stay the trigger on foot.
748 k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 4000 * MS);
749 k.pad(&keys(&[]), UNKNOWN, 4008 * MS);
750 assert!(k.driving);
751 assert_eq!(k.pad(&keys(b"WF"), UNKNOWN, 5000 * MS), button(Y));
752 assert!(!k.driving);
753 // On foot F is just F.
754 k.pad(&keys(&[]), UNKNOWN, 5008 * MS);
755 k.pad(&keys(b"F"), UNKNOWN, 6000 * MS);
756 assert!(!k.driving);
757 }
758
759 #[test]
760 fn a_measured_context_wins_and_caps_lock_is_no_switch_then() {
761 let mut k = kbm();
762 // Driving by hand, then the runtime starts to tell: its word counts.
763 k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 0);
764 k.pad(&keys(&[]), UNKNOWN, 8 * MS);
765 assert!(k.driving);
766 k.pad(&keys(&[]), FOOT, 16 * MS);
767 assert!(!k.driving);
768 // Caps Lock (GTA V's special ability, pressed out of habit) does nothing on foot: W stays the stick.
769 k.pad(&keys(&[VK_CAPITAL]), FOOT, 500 * MS);
770 assert!(!k.driving);
771 assert_eq!(k.pad(&keys(&[VK_CAPITAL, b'W']), FOOT, 600 * MS), PadState { left_y: 1.0, ..Default::default() });
772 k.pad(&keys(&[]), FOOT, 700 * MS);
773 // Nor in a vehicle, and F is just the Y button there.
774 k.pad(&keys(&[]), CAR, 1000 * MS);
775 assert!(k.driving);
776 k.pad(&keys(&[VK_CAPITAL]), CAR, 2000 * MS);
777 k.pad(&keys(b"F"), CAR, 2100 * MS);
778 assert!(k.driving);
779 k.pad(&keys(&[]), CAR, 2200 * MS);
780 // The context is lost (nobody tells any more): on foot, not the driving by hand of before.
781 k.pad(&keys(&[]), UNKNOWN, 3000 * MS);
782 k.pad(&keys(&[]), UNKNOWN, 3100 * MS);
783 assert!(!k.driving);
784 // And Caps Lock is the switch again.
785 k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 4000 * MS);
786 assert!(k.driving);
787 }
788
789 #[test]
790 fn a_context_nobody_renews_is_unknown() {
791 let shared = Shared::new();
792 assert_eq!(shared.get(0), UNKNOWN);
793 assert_eq!(shared.get(10_000 * MS), UNKNOWN);
794 shared.set(CAR, 1000 * MS);
795 assert_eq!(shared.get(1000 * MS), CAR);
796 assert_eq!(shared.get(1500 * MS), CAR);
797 assert_eq!(shared.get(1501 * MS), UNKNOWN);
798 shared.set(FOOT, 1600 * MS);
799 assert_eq!(shared.get(1700 * MS), FOOT);
800 shared.set(UNKNOWN, 1800 * MS);
801 assert_eq!(shared.get(1800 * MS), UNKNOWN);
802 // A reader whose clock is behind the writer's does not go wrong.
803 shared.set(CAR, 5000 * MS);
804 assert_eq!(shared.get(4000 * MS), CAR);
805 // The stand-in pad lets go of a known context only after 100 ms of unknown, and then as on any change.
806 let mut k = kbm();
807 k.pad(&keys(&[]), CAR, 0);
808 assert_eq!(k.pad(&keys(b"W"), CAR, 1000 * MS), PadState { right_trigger: 1.0, ..Default::default() });
809 assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 1010 * MS), PadState { right_trigger: 1.0, ..Default::default() });
810 assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 1100 * MS), PadState { right_trigger: 1.0, ..Default::default() });
811 // Known again in time: nothing happened.
812 assert_eq!(k.pad(&keys(b"W"), CAR, 1105 * MS), PadState { right_trigger: 1.0, ..Default::default() });
813 assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 2000 * MS), PadState { right_trigger: 1.0, ..Default::default() });
814 assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 2100 * MS), PadState::default());
815 assert!(!k.driving);
816 }
817
818 #[test]
819 fn the_switches_read() {
820 assert_eq!(Config::parse(None, None, None), Config::default());
821 assert_eq!(Config::default().layout, Layout::GtaV);
822 assert_eq!(Config::default().drive, Drive::Auto);
823 assert_eq!(Config::parse(Some("classic"), None, None).layout, Layout::Classic);
824 assert_eq!(Config::parse(Some(" Classic "), None, None).layout, Layout::Classic);
825 assert_eq!(Config::parse(Some("gta5"), None, None).layout, Layout::GtaV);
826 assert_eq!(Config::parse(None, Some("on"), None).drive, Drive::On);
827 assert_eq!(Config::parse(None, Some("OFF"), None).drive, Drive::Off);
828 assert_eq!(Config::parse(None, Some("auto"), None).drive, Drive::Auto);
829 assert_eq!(Config::parse(None, Some("what"), None).drive, Drive::Auto);
830 assert_eq!(Config::parse(None, None, Some("0")).settle, 0);
831 assert_eq!(Config::parse(None, None, Some("250")).settle, 250 * MS);
832 assert_eq!(Config::parse(None, None, Some("99999")).settle, 3000 * MS);
833 assert_eq!(Config::parse(None, None, Some("soon")).settle, 400 * MS);
834 }
835
836 #[test]
837 fn the_forced_tables_and_the_classic_one() {
838 // Forced on: driving whatever is measured, and Caps Lock is no switch.
839 let mut k = Kbm::new(Config { drive: Drive::On, ..Config::default() });
840 k.pad(&keys(&[]), FOOT, 0);
841 assert_eq!(k.pad(&keys(b"W"), FOOT, 1000 * MS), PadState { right_trigger: 1.0, ..Default::default() });
842 k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 2000 * MS);
843 assert!(k.driving);
844 // Forced off.
845 let mut k = Kbm::new(Config { drive: Drive::Off, ..Config::default() });
846 assert_eq!(k.pad(&keys(b"W"), CAR, 0), PadState { left_y: 1.0, ..Default::default() });
847 k.pad(&keys(&[b'W', VK_CAPITAL]), CAR, 1000 * MS);
848 assert!(!k.driving);
849 // Classic: the table of before, whatever the context.
850 let mut k = Kbm::new(Config { layout: Layout::Classic, ..Config::default() });
851 for context in [UNKNOWN, FOOT, CAR] {
852 let held = keys(&[b'W', b'V', b'Q', VK_MOUSE_RIGHT, VK_CAPITAL]);
853 assert_eq!(k.pad(&held, context, 0), super::super::fallback(&held));
854 assert_eq!(
855 k.pad(&held, context, 0),
856 PadState {
857 buttons: LEFT_SHOULDER,
858 left_y: 1.0,
859 left_trigger: 1.0,
860 right_trigger: 1.0,
861 ..Default::default()
862 }
863 );
864 }
865 }
866
867 #[test]
868 fn scripted_keys_press_the_on_foot_buttons() {
869 assert_eq!(scripted_button(VK_RETURN), Some(A));
870 assert_eq!(scripted_button(VK_ESCAPE), Some(MENU));
871 assert_eq!(scripted_button(VK_BACK), Some(B));
872 assert_eq!(scripted_button(VK_UP), Some(UP));
873 assert_eq!(scripted_button(b'F'), Some(Y));
874 // A stick or a trigger is no button; an unbound key is none.
875 assert_eq!(scripted_button(b'W'), None);
876 assert_eq!(scripted_button(VK_MOUSE_LEFT), None);
877 assert_eq!(scripted_button(b'V'), None);
878 }
879}
diff --git a/d3d12/crates/leonida-loader/src/game_actions.rs b/d3d12/crates/leonida-loader/src/game_actions.rs
index 001fff65b..aff440cb7 100644
--- a/d3d12/crates/leonida-loader/src/game_actions.rs
+++ b/d3d12/crates/leonida-loader/src/game_actions.rs
@@ -64,10 +64,15 @@ pub enum Site {
64 WeatherForced, 64 WeatherForced,
65 /// The global that points at the weather types ([`WEATHER_TYPE_STRIDE`] bytes each, the name's hash first). 65 /// The global that points at the weather types ([`WEATHER_TYPE_STRIDE`] bytes each, the name's hash first).
66 WeatherTypes, 66 WeatherTypes,
67 /// The global that holds the vehicle the player is in, null on foot. Read from the code, not yet seen in
68 /// the running title: its one setter is called with a vehicle from a large function, with null where a ped
69 /// that is the player is taken out of a vehicle, and with what the title's own "the vehicle this ped is in"
70 /// gives when the player's ped is set (`docs/gameinput.md`).
71 PlayerVehicle,
67} 72}
68 73
69/// How many [`Site`]s there are. 74/// How many [`Site`]s there are.
70pub const SITES: usize = Site::WeatherTypes as usize + 1; 75pub const SITES: usize = Site::PlayerVehicle as usize + 1;
71 76
72/// The queue the title's own cheats are deferred to (`mov ecx, 4` in the pattern of [`Site::Defer`], whose 77/// The queue the title's own cheats are deferred to (`mov ecx, 4` in the pattern of [`Site::Defer`], whose
73/// stores are the closure's four words). 78/// stores are the closure's four words).
@@ -192,6 +197,14 @@ const PLACES: &[Place] = &[
192 8B 84 87 ?? ?? 00 00 48 6B C0 38 8B 04 01", 197 8B 84 87 ?? ?? 00 00 48 6B C0 38 8B 04 01",
193 takes: &[(Site::WeatherTypes, Take::Rel { at: 3, next: 7 })], 198 takes: &[(Site::WeatherTypes, Take::Rel { at: 3, next: 7 })],
194 }, 199 },
200 Place {
201 what: "the function that records the vehicle the player is in",
202 // push rsi, rdi; sub rsp, 38h; mov rsi, rcx; lea rcx, [player's vehicle]; mov rdx, rsi; call (set the
203 // reference); test rsi, rsi; je; mov rcx, rsi; call; test al, al; jne
204 pattern: "56 57 48 83 EC 38 48 89 CE 48 8D 0D ?? ?? ?? ?? 48 89 F2 E8 ?? ?? ?? ?? 48 85 F6 0F 84 ?? ?? ?? ?? \
205 48 89 F1 E8 ?? ?? ?? ?? 84 C0 0F 85",
206 takes: &[(Site::PlayerVehicle, Take::Rel { at: 12, next: 16 })],
207 },
195]; 208];
196 209
197/// What was found: each [`Site`]'s offset in the image (or its number), `None` for what this executable does 210/// What was found: each [`Site`]'s offset in the image (or its number), `None` for what this executable does
@@ -238,8 +251,17 @@ fn once(pattern: &Pattern, code: &[(usize, &[u8])]) -> Result<(usize, usize), &'
238/// `image_size`. A place that is missing, there twice, or that points outside the image leaves its sites `None` 251/// `image_size`. A place that is missing, there twice, or that points outside the image leaves its sites `None`
239/// and a line in [`Sites::missing`]. 252/// and a line in [`Sites::missing`].
240pub fn resolve(code: &[(usize, &[u8])], image_size: usize) -> Sites { 253pub fn resolve(code: &[(usize, &[u8])], image_size: usize) -> Sites {
254 resolve_some(code, image_size, None)
255}
256
257/// [`resolve`] for the places that give one of `wanted` only (all of them with `None`): each place is a pass
258/// over the image's code, and whoever needs two sites need not pay for all.
259pub fn resolve_some(code: &[(usize, &[u8])], image_size: usize, wanted: Option<&[Site]>) -> Sites {
241 let mut sites = Sites::default(); 260 let mut sites = Sites::default();
242 for place in PLACES { 261 for place in PLACES {
262 if wanted.is_some_and(|wanted| !place.takes.iter().any(|(site, _)| wanted.contains(site))) {
263 continue;
264 }
243 let Some(pattern) = Pattern::parse(place.pattern) else { 265 let Some(pattern) = Pattern::parse(place.pattern) else {
244 sites.missing.push(format!("{}: its pattern does not read", place.what)); 266 sites.missing.push(format!("{}: its pattern does not read", place.what));
245 continue; 267 continue;
@@ -280,6 +302,26 @@ pub fn resolve(code: &[(usize, &[u8])], image_size: usize) -> Sites {
280 sites 302 sites
281} 303}
282 304
305/// The sites (those of `wanted`, or all with `None`) of the image mapped at `base`. Reads the image's code and
306/// changes nothing.
307///
308/// # Safety
309/// `base` is the mapped image `info` describes, and nothing writes its code meanwhile (none of it runs yet).
310pub unsafe fn find(base: usize, info: &leonida_pe::ImageInfo, wanted: Option<&[Site]>) -> Sites {
311 let code: Vec<(usize, &[u8])> = info
312 .sections
313 .iter()
314 .filter(|s| s.characteristics & crate::vipatch::SCN_MEM_EXECUTE != 0)
315 .filter(|s| u64::from(s.rva) + u64::from(s.virtual_size) <= u64::from(info.size_of_image))
316 .map(|s| {
317 let (start, len) = (s.rva as usize, s.virtual_size as usize);
318 // SAFETY: a section of the mapped image, readable, which nothing writes now.
319 (start, unsafe { std::slice::from_raw_parts((base + start) as *const u8, len) })
320 })
321 .collect();
322 resolve_some(&code, info.size_of_image as usize, wanted)
323}
324
283/// `jmp [rip + 0]` and the address it jumps to: 14 bytes of code that reach anywhere. 325/// `jmp [rip + 0]` and the address it jumps to: 14 bytes of code that reach anywhere.
284fn far_jump(to: usize) -> [u8; 14] { 326fn far_jump(to: usize) -> [u8; 14] {
285 let mut code = [0xFF, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 327 let mut code = [0xFF, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
@@ -301,21 +343,8 @@ fn call_distance(call: usize, to: usize) -> Option<[u8; 4]> {
301/// `base` is the mapped image `info` describes, no title code runs yet, and `hook` stays valid for the process. 343/// `base` is the mapped image `info` describes, no title code runs yet, and `hook` stays valid for the process.
302#[cfg(windows)] 344#[cfg(windows)]
303pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo, hook: usize) -> (Sites, Result<(), String>) { 345pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo, hook: usize) -> (Sites, Result<(), String>) {
304 let sites = { 346 // SAFETY: forwarded from this function's contract; the slices end with the call, before anything is written.
305 // The image's code as it is mapped; the slices end with this block, before anything is written. 347 let sites = unsafe { find(base, info, None) };
306 let code: Vec<(usize, &[u8])> = info
307 .sections
308 .iter()
309 .filter(|s| s.characteristics & crate::vipatch::SCN_MEM_EXECUTE != 0)
310 .filter(|s| u64::from(s.rva) + u64::from(s.virtual_size) <= u64::from(info.size_of_image))
311 .map(|s| {
312 let (start, len) = (s.rva as usize, s.virtual_size as usize);
313 // SAFETY: a section of the mapped image, readable, which nothing writes now.
314 (start, unsafe { std::slice::from_raw_parts((base + start) as *const u8, len) })
315 })
316 .collect();
317 resolve(&code, info.size_of_image as usize)
318 };
319 let (Some(call), Some(_), Some(_)) = 348 let (Some(call), Some(_), Some(_)) =
320 (sites.get(Site::HookCall), sites.get(Site::CheatsUpdate), sites.get(Site::Defer)) 349 (sites.get(Site::HookCall), sites.get(Site::CheatsUpdate), sites.get(Site::Defer))
321 else { 350 else {
@@ -451,10 +480,35 @@ mod tests {
451 assert_eq!(sites.get(Site::WantedSet).unwrap() % 16, 0); 480 assert_eq!(sites.get(Site::WantedSet).unwrap() % 16, 0);
452 assert_eq!(sites.get(Site::WantedLevelAt), Some(0)); 481 assert_eq!(sites.get(Site::WantedLevelAt), Some(0));
453 assert!(sites.has(&[Site::ClockSet, Site::WeatherForce, Site::WeatherTypes])); 482 assert!(sites.has(&[Site::ClockSet, Site::WeatherForce, Site::WeatherTypes]));
483 // The player's vehicle: lea rcx, [rip + 0], whose end is 16 bytes into its place.
484 assert_eq!(sites.get(Site::PlayerVehicle), Some(at(Site::PlayerVehicle) + 16));
454 assert_eq!(sites.count(), SITES); 485 assert_eq!(sites.count(), SITES);
455 } 486 }
456 487
457 #[test] 488 #[test]
489 fn some_sites_are_found_without_looking_for_the_rest() {
490 let mut code = image();
491 let vehicle = place_at(place_of(Site::PlayerVehicle));
492 code[vehicle + 12..vehicle + 16].copy_from_slice(&0x4321i32.to_le_bytes());
493 // A place nobody asks for may be missing: it is not looked for, and not reported.
494 let clock = place_at(place_of(Site::ClockSet));
495 code[clock] ^= 0xFF;
496 let wanted = [Site::PlayerPed, Site::PlayerVehicle];
497 let sites = resolve_some(&[(0x1000, &code[..])], 0x10_0000, Some(&wanted));
498 assert!(sites.missing.is_empty(), "{:?}", sites.missing);
499 assert_eq!(sites.count(), 2);
500 assert_eq!(sites.get(Site::PlayerPed), Some(0x1000 + place_at(place_of(Site::PlayerPed)) + 11));
501 assert_eq!(sites.get(Site::PlayerVehicle), Some(0x1000 + vehicle + 16 + 0x4321));
502 assert!(sites.get(Site::HookCall).is_none() && sites.get(Site::ClockSet).is_none());
503 // Asked for, it is reported.
504 let sites = resolve_some(&[(0x1000, &code[..])], 0x10_0000, Some(&[Site::ClockTime]));
505 assert_eq!((sites.count(), sites.missing.len()), (0, 1));
506 // All of them: as `resolve`.
507 let all = resolve_some(&[(0x1000, &code[..])], 0x10_0000, None);
508 assert_eq!(all, resolve(&[(0x1000, &code[..])], 0x10_0000));
509 }
510
511 #[test]
458 fn displacements_and_numbers_are_read_from_the_code() { 512 fn displacements_and_numbers_are_read_from_the_code() {
459 let mut code = image(); 513 let mut code = image();
460 // The player's global: mov rax, [rip + 0x1234], 4 bytes into its place. 514 // The player's global: mov rax, [rip + 0x1234], 4 bytes into its place.
@@ -635,6 +689,7 @@ mod tests {
635 Site::WeatherNext, 689 Site::WeatherNext,
636 Site::WeatherForced, 690 Site::WeatherForced,
637 Site::WeatherTypes, 691 Site::WeatherTypes,
692 Site::PlayerVehicle,
638 ] { 693 ] {
639 assert!(!in_code(sites.get(site).unwrap()), "{site:?}"); 694 assert!(!in_code(sites.get(site).unwrap()), "{site:?}");
640 } 695 }
diff --git a/docs/gameinput.md b/docs/gameinput.md
index e0df71085..b5d6cc6f7 100644
--- a/docs/gameinput.md
+++ b/docs/gameinput.md
@@ -184,6 +184,185 @@ afresh on return so the right stick does not jump. Scripted presses run with or
184 184
185To try it by hand: `set LEONIDA_KEYBOARD_PAD=always`, then `gameinput_probe --seconds 20` and press keys. 185To try it by hand: `set LEONIDA_KEYBOARD_PAD=always`, then `gameinput_probe --seconds 20` and press keys.
186 186
187## The keyboard-and-mouse pad of the D3D12 runtime
188
189The D3D12 runtime (`d3d12/`) has its own GameInput module (`d3d12/crates/leonida-hle/src/modules/gameinput.rs`)
190with a stand-in pad made from the keyboard and mouse, present while no host pad is connected (or beside one, with
191`LEONIDA_ONE_PAD`, the default). Keys and mouse buttons count only while a window of the runtime has focus.
192
193### Grand Theft Auto V's layout: one table on foot, one in a vehicle
194
195The title reads a pad only, and on a pad one button is two actions: the right trigger shoots on foot and accelerates
196in a vehicle, the left trigger aims and brakes. One table of keys cannot be a PC layout then, so there are two
197(`gameinput/kbm.rs`), and the stand-in pad uses the one of what the player is in. The keys are Grand Theft Auto V's
198PC defaults (its key bindings as listed in BisectHosting's "GTA V controls guide" and on StrategyWiki's controls
199page). The pad button of each action is the title's default pad layout as far as it is known: the table below is the
200one that came with the PC prompt glyphs (a contributor's notes on the Xbox layout), not measured here.
201
202| pad | on foot | in a vehicle |
203|---|---|---|
204| left stick, click | move, run | steer (lean on a bike), horn |
205| right stick, click | camera, look behind (zoom while aiming) | camera, look behind |
206| A / B / X / Y | jump and climb / crouch / melee and reload / interact, enter a vehicle | handbrake / duck, headlights / not known / leave the vehicle |
207| LB / RB | loadout wheel, holster / cover | loadout wheel / shoot from the vehicle |
208| LT / RT | aim / shoot | brake and reverse / accelerate |
209| d-pad up, down, left, right | phone, HUD and objective, radio menu, partner menu | the same |
210| Menu / View | pause / map | the same |
211
212| key | on foot | in a vehicle |
213|---|---|---|
214| W, S | left stick up, down: move | RT, LT (fully): accelerate, brake and reverse |
215| A, D | left stick left, right: move | the same: steer |
216| mouse | right stick: camera (mouse look, below) | the same |
217| left mouse button | RT: shoot | RB: shoot from the vehicle |
218| right mouse button | LT: aim | nothing (the button that aims from a vehicle is not known) |
219| Space | A: jump, climb | A: handbrake |
220| Left Shift | left stick click: run | left stick up: lean forward on a bike, nose down in an aircraft |
221| Left Ctrl | B: crouch (GTA V's stealth) | left stick down: lean back, nose up |
222| Num 8, Num 5, Num 4, Num 6 | nothing | left stick up, down, left, right (GTA V's aircraft keys) |
223| Q | RB: cover | d-pad left: radio menu (GTA V's radio wheel) |
224| E | Y: interact (GTA V's context action) | left stick click: horn |
225| F | Y: enter a vehicle | Y: leave it |
226| R | X: reload, melee | X (the same button; GTA V's cinematic camera has none known) |
227| X, H | nothing | B: duck, headlights |
228| Tab | LB: loadout wheel (hold), holster | LB |
229| C | right stick click: look behind | the same |
230| M | View: map | the same |
231| Esc, P | Menu: pause | the same |
232| arrows | d-pad: phone (up) and its menus | the same |
233| Enter, Backspace | A, B: accept and back in the phone and menus | the same |
234| Z | d-pad down: HUD and objective (GTA V's radar zoom, the same press on its pad) | the same |
235| Y; I J K L | Y; right stick (kept from the layout before; GTA V has nothing on them on foot) | the same |
236
237GTA V keys left without a binding, because the title's pad button for the action is not known: V (camera view), G
238(grenade; landing gear), O (heavy melee), the number keys (weapon slots), `[` `]` `,` `.` `=` `-` (zoom, radio), T, B,
239N, the F keys (character switch), Insert, Page Up and Page Down, the middle mouse button, and Caps Lock (GTA V's
240special ability), which is the switch described below. Left Alt (GTA V's character switch) would be the partner
241menu, d-pad right, and is left out because every Alt+Tab would press it; the right arrow is that button. For the
242same reason Tab, Enter, Space and Esc give nothing while an Alt key is down. The mouse wheel (GTA V's next and previous weapon, and zoom
243while aiming) is not bound either: the pad has no button known for the next weapon, and the host source polls key
244states (`GetAsyncKeyState`), which a wheel does not have; it would have to be counted from `WM_MOUSEWHEEL` in the
245window procedure of `lifecycle.rs`. The layout before had Z and V as the triggers, X as X, H as a second right stick
246click and Left Ctrl as a second left stick click; those went where GTA V has another meaning for the key.
247`LEONIDA_KBM=classic` brings the table of before back whole (`FALLBACK_BUTTONS`: W A S D and I J K L the sticks,
248Space or Enter A, R or Backspace B, X, F or Y, Q and E the shoulders, Left Shift or Left Ctrl and C or H the stick
249clicks, Z or the right mouse button LT, V or the left mouse button RT, Esc Menu, Tab View).
250
251In an aircraft A and D are the left stick (roll), not GTA V's rudder: only "in a vehicle" is known, not which kind.
252
253### Which table counts
254
255`gameinput::set_player_context(OnFoot | InVehicle | Unknown)` tells the stand-in pad, lock-free from any thread; a
256context that is not set again for 500 ms is unknown (and the pad only lets go of a known one after 100 ms of
257unknown). Unknown is the on-foot table, and then **Caps Lock** switches to the driving table and back by hand, with a
258line in the log at every change of table; driving by hand also ends when F (leave the vehicle) is pressed, so that W
259cannot stay the right trigger on foot. While a context is measured Caps Lock does nothing: it is GTA V's special
260ability key, and a press out of habit on foot must not make W a shot. `gameinput::driving_controls()` says which
261table is in use (for whoever draws key prompts).
262
263**The hand-over** when the table changes: a key that is another pad input in the other table (W, S, the mouse buttons,
264Left Shift, Left Ctrl, Q, E, X, H) and is down at that moment gives nothing until it has been let go and pressed
265again, and no such key gives anything for 400 ms after the change (`LEONIDA_KBM_SETTLE_MS`, 0 to 3000). So the left
266mouse button held on foot never becomes the accelerator and W held in a car never becomes a shot; the price is that W
267held while getting in has to be pressed again to drive off. Keys that are the same pad input in both tables (A, D,
268Space, F, ...) carry over as a real pad's button would. Unit-tested over every set of held keys in both directions
269(`cargo test -p leonida-hle gameinput`).
270
271**Who tells.** `d3d12/apps/leonida/src/player_context.rs` reads the title every 16 ms from a thread of its own
272(`ReadProcessMemory` on the own process: nothing is written and no title code is called, so it does not need
273`LEONIDA_GAME_ACTIONS=1`; without the game actions it looks the two globals up itself at start, two more passes over
274the image's code, about 0.15 s together on the retail executable's 99.9 MB of code). It tells `Unknown` while there is no player ped, and a change counts after three equal reads. What
275says "in a vehicle" is, in this order:
276
2771. `LEONIDA_PED_VEHICLE_AT=0x<offset>`: a field of the player's ped that points at its vehicle and is null on foot.
278 None is known (see below why there may be none), so this is unset by default.
2792. The title's own global of the player's vehicle (`Site::PlayerVehicle` in `leonida-loader/src/game_actions.rs`,
280 found by a pattern that is in the 1.0.2.1 executable once; `LEONIDA_PLAYER_VEHICLE_AT=0x<offset in the image>`
281 names another, `=off` turns it off). **Read from the code, not yet seen in the running title:**
282 - The title keeps what belongs to a ped apart from the ped's entity, in tables looked up by the entity's id
283 (`+9Ch`; a ped's id has `60000h` under the mask `3E0000h`, its index is the low 17 bits, and a 16-bit slot of
284 `FFFFh` means "none"). Its "the vehicle this ped is in" (the function at `4DD7510h`) takes column `47h` of
285 those tables and gives the pointer at `+898h` of it when bit `20h` of the byte at `+10h` is set, else null: the
286 shape of GTA V's `GetVehiclePedInside`, a "my vehicle" pointer that outlives the ride plus a flag. That is why a
287 pointer in the ped that is null on foot may not exist at all.
288 - The global at `AB760C8h` is written by one function (`CA4DE0h`), which has three callers: one passes a
289 vehicle (in a function of 129Fh bytes, taken to be where a ped is put in a vehicle), one passes null after
290 testing that the ped's id is the player's (taken to be where a ped is taken out), and the function that sets
291 the player's ped passes what `4DD7510h` gives for the new ped. The first two are methods of that same column
292 `47h` record: the first begins by reading its `+10h` and `+898h` and testing bit `20h`, the second tests
293 other bits beside it (`+12h`). 167 places in the code read the global; the vehicle cheats read a type byte
294 at `+FAh` of what it points at.
295 - Not known until it has run: that it is null in every on-foot state (after a crash through the windscreen, a
296 vehicle that blows up, a cutscene), and when during getting in and out it changes compared with the title's own
297 switch of its controls. The reader logs every change with its time, and warns when the ped moves at 12 m/s for
298 a second while it says "on foot", or the vehicle is 60 m from the ped while it says "in a vehicle".
2993. `LEONIDA_KBM_SPEED=1`: the speed rule. From the ped's position (taken every 0.2 s): 12 m/s (43 km/h; a sprint is
300 about 7) or more for a second without a break is "in a vehicle", until 3 s have passed below that speed; a fall
301 (more down than along) and a jump of the position (a teleport, a respawn) do not count. Its limits are why it is
302 off unless asked for: it never says "on foot" (a car at a red light and a ped standing are the same to it), it
303 cannot see a drive begin, so it never switches from a standstill and the first metres of every drive are on the
304 on-foot keys, and so the meaning of W and of the mouse buttons would change in the middle of a drive, at every
305 stop. It always runs as the check named above.
306
307With none of the three the context stays unknown: the on-foot table, and Caps Lock.
308
309| switch | effect |
310|---|---|
311| `LEONIDA_KBM=classic` | the single table of before; nothing reads the title |
312| `LEONIDA_KBM_DRIVE=on` / `off` / `auto` | forces the driving table on or off (a test; nothing reads the title and Caps Lock does nothing then); `auto` is the default |
313| `LEONIDA_KBM_SETTLE_MS=<ms>` | the pause after a change of table, 400 |
314| `LEONIDA_PED_VEHICLE_AT`, `LEONIDA_PLAYER_VEHICLE_AT`, `LEONIDA_KBM_SPEED` | what says "in a vehicle", above |
315| `LEONIDA_PED_DUMP=<folder>` | for measuring: F8 in the game's window, or a file named `dump` in that folder (its text is the label), writes the first 4000h bytes of the player's ped to `ped-<date>-<time>-<label>.bin`, the first 1000h of the vehicle the global names to `vehicle-...bin`, and a line to `index.txt` (time, addresses, the ped's id, position, speed, what was read). The folder must be outside the repository; the files are the title's memory and are never committed. |
316
317The mouse buttons are not passed to the title while the F1 settings menu or the F4 trainer menu is open, and they
318never reach the title as keyboard keys.
319
320**Mouse look (D3D12 runtime).** The console title turns its camera with the right stick only; it does not read the
321mouse for that. A left click in the game window makes the window hold the mouse: the cursor is hidden and kept in the
322window, and the mouse's motion becomes a right-stick push (`MouseLook` in `d3d12/crates/leonida-hle/src/modules/
323gameinput.rs`): its speed over the last 40 ms, a full push at 1600 pixels a second, lifted past a 0.24 dead zone with a
3240.6 power curve, merged with the pad's own stick. That click is not a shot; the mouse buttons reach the title as
325triggers only while the window holds the mouse. Esc (which also pauses), the F1 or F4 menu, or another window in front
326gives the mouse back. Settings: `LEONIDA_MOUSE_SENSITIVITY` (1, 0.1..10), `LEONIDA_MOUSE_INVERT_Y=1`,
327`LEONIDA_MOUSE_DEADZONE` (0.24), `LEONIDA_MOUSE_CURVE` (0.6), `LEONIDA_MOUSE_LOOK=0` (off: the old behaviour, buttons
328whenever the window has focus). Unit-tested (`mouse_look_turns_speed_into_a_stick_past_the_dead_zone`); the dead zone
329and curve are first guesses at the title's own stick response, not measured.
330
331## PlayStation pads and the active input of the D3D12 runtime
332
333The D3D12 runtime has no SDL. Besides XInput it reads Sony pads (vendor `054C`: DualSense `0CE6`, DualSense Edge `0DF2`,
334DualShock 4 `05C4`, `09CC`, USB adapter `0BA0`) over Windows HID directly (`gameinput/hid.rs`), on USB and Bluetooth,
335written from the public report layouts (the Linux `hid-playstation` driver documents them). One thread per pad reads
336input reports; a rescan every 2 s finds pads that came or went. A Bluetooth pad is moved to its full report by reading
337calibration feature report `0x05`.
338
339| | USB input | Bluetooth input | USB output | Bluetooth output |
340|---|---|---|---|---|
341| DualSense | `0x01`, 64 bytes, data from byte 1 | `0x31`, 78 bytes, data from byte 2 | `0x02`, 63 | `0x31`, 78, CRC-32 last |
342| DualShock 4 | `0x01`, 64 bytes, data from byte 1 | `0x11`, data from byte 3 | `0x05`, 32 | `0x11`, 78, CRC-32 last |
343
344Buttons: Cross, Circle, Square, Triangle are A, B, X, Y; L1/R1 the shoulders; L2/R2 the triggers (analog byte, the
345digital bit is ignored); L3/R3 the stick clicks; Options is Menu; Create (Share) and the touchpad click are View;
346the PS and mute buttons are not passed. Sticks are 0..255, centre 128. Rumble: the big motor of the title's
347`SetRumbleState` goes to the pad's left motor, the small one to its right (`rumble_report`; on Bluetooth the CRC is
348seeded with `0xA2`). Trigger effects and the lightbar are not driven. A Sony pad takes the first slot XInput leaves
349empty (all pads are one pad for the title anyway, `LEONIDA_ONE_PAD`).
350
351A pad that Steam Input or DS4Windows already shows through XInput is not read twice: when input comes on an XInput pad and
352on a readable Sony pad within 150 ms of each other, they are one controller for the next 10 s, and the Sony pad's own
353reading is left out of what the title sees. A Sony pad present but not openable (hidden by HidHide, held exclusively)
354counts the same way: input on XInput is then PlayStation input.
355
356**Active input.** `gameinput::active_family()` (`leonida-hle`, readable from any thread, lock-free) says which kind of
357device was used last: `Family::Xbox`, `Family::PlayStation` or `Family::KeyboardMouse`; `family_generation()` goes up by one
358with each change. It follows the rules of [Active input](#active-input) above (an edge counts, the first reading of a
359device is its baseline, a change waits `LEONIDA_PROMPTS_SWITCH_MS` = 300 ms), with the keyboard and mouse as a third
360family (a key going down, or mouse look pushing the stick past 0.35). Before the first input it is PlayStation if a Sony pad is
361present and Xbox otherwise. One line is logged on each change (`input in use: PlayStation (Sony pad input)`).
362`LEONIDA_PROMPTS=xbox|playstation|keyboard|auto` forces it. The button prompts follow it: see
363[prompt_glyphs.md](prompt_glyphs.md). Unit-tested on hand-made report bytes and the family rules; not run against a
364real pad yet.
365
187## Rumble and triggers 366## Rumble and triggers
188 367
189`IGameInputDevice::SetRumbleState` takes four motor levels, 0..1. The two body motors go to `SDL_RumbleGamepad` on 368`IGameInputDevice::SetRumbleState` takes four motor levels, 0..1. The two body motors go to `SDL_RumbleGamepad` on
diff --git a/docs/mod-menu.md b/docs/mod-menu.md
index 064fa1390..18023dd0f 100644
--- a/docs/mod-menu.md
+++ b/docs/mod-menu.md
@@ -194,9 +194,11 @@ menu.
194 way). Our hook is the one 194 way). Our hook is the one
195 `call` of the cheat input function: it calls that function, then, if something was asked, gives the same queue 195 `call` of the cheat input function: it calls that function, then, if something was asked, gives the same queue
196 a closure of its own. So our work runs exactly where a cheat of the title's would. 196 a closure of its own. So our work runs exactly where a cheat of the title's would.
197- **Finding it again.** Ten places are named by patterns of 24 to 77 bytes (19 to 36 of them fixed, `??` for 197- **Finding it again.** Eleven places are named by patterns of 24 to 77 bytes (19 to 36 of them fixed, `??` for
198 what another build changes: short signatures, no longer than they must be), which give 19 things: 8 functions, 198 what another build changes: short signatures, no longer than they must be), which give 20 things: 8 functions,
199 the hook's call, 9 globals and the place of the level in the wanted state. Each 199 the hook's call, 10 globals and the place of the level in the wanted state (the eleventh place, the global of
200 the player's vehicle, is for the keyboard and mouse layout and is looked up without the game actions too:
201 `docs/gameinput.md`). Each
200 pattern is in the 99.9 MB of code exactly once (`cargo test -p leonida-loader game_actions` with 202 pattern is in the 99.9 MB of code exactly once (`cargo test -p leonida-loader game_actions` with
201 `LEONIDA_GAME_DIR` set checks it, and that functions lie in code and globals behind it). None contains a load 203 `LEONIDA_GAME_DIR` set checks it, and that functions lie in code and globals behind it). None contains a load
202 of the thread's TLS array, which the loader rewrites. A place that is not found leaves its items saying so; the 204 of the thread's TLS array, which the loader rewrites. A place that is not found leaves its items saying so; the
@@ -396,7 +398,7 @@ interpreter is simply not found by these signatures, which is why the run-time s
396 Skipped without a D3D12 device. 398 Skipped without a D3D12 device.
397- `cargo test -p leonida-hle --features diagnostics --lib -- gameinput clock`: the input shim with the kept keys in 399- `cargo test -p leonida-hle --features diagnostics --lib -- gameinput clock`: the input shim with the kept keys in
398 place, and the title's clock. 400 place, and the title's clock.
399- `cargo test -p leonida-loader --lib game_actions`: the ten places on made-up code (found wherever they lie, 401- `cargo test -p leonida-loader --lib game_actions`: the eleven places on made-up code (found wherever they lie,
400 displacements and numbers read, a place missing, twice or pointing outside left out), the hook on made-up code 402 displacements and numbers read, a place missing, twice or pointing outside left out), the hook on made-up code
401 that runs (the update step calls a function of ours and returns as before) and, with `LEONIDA_GAME_DIR` set to 403 that runs (the update step calls a function of ours and returns as before) and, with `LEONIDA_GAME_DIR` set to
402 the package's folder, every place once in the retail executable, functions in code and globals behind it. 404 the package's folder, every place once in the retail executable, functions in code and globals behind it.