mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:18:37 +00:00
Merge remote-tracking branch 'old/port/kbm' into next
# Conflicts: # docs/gameinput.md
This commit is contained in:
@ -383,6 +383,48 @@ Series X profile (sharper, much slower; DLSS there with `-Dlss`); `-Quality` giv
|
||||
stretched bodies, slower; `-RayTracing` turns the title's real ray tracing on.
|
||||
The fork's own `scripts\play.ps1` is still there for AMD cards.
|
||||
|
||||
### Keyboard and mouse
|
||||
|
||||
The game itself only knows an Xbox controller, so the keyboard and mouse press that controller's buttons for you,
|
||||
laid 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
|
||||
shot); Esc pauses and frees the mouse again.
|
||||
|
||||
| | on foot | in a vehicle |
|
||||
|---|---|---|
|
||||
| W A S D | move | W accelerate, S brake and reverse, A D steer |
|
||||
| mouse | look around | look around |
|
||||
| left mouse button | shoot | shoot from the vehicle |
|
||||
| right mouse button | aim | (nothing yet) |
|
||||
| Space | jump, climb | handbrake |
|
||||
| Left Shift | run | lean forward on a bike (also Num 8) |
|
||||
| Left Ctrl | crouch | lean back on a bike (also Num 5) |
|
||||
| F | get into a vehicle | get out |
|
||||
| E | interact | horn |
|
||||
| Q | take cover | radio |
|
||||
| R | reload, melee | (the same button) |
|
||||
| X, H | | duck, headlights |
|
||||
| Tab | weapon wheel (hold) | weapon wheel |
|
||||
| C | look behind | look behind |
|
||||
| M | map | map |
|
||||
| Esc or P | pause | pause |
|
||||
| arrow keys | phone (up) and its menus; down, left and right are the HUD, the radio and the partner menu | the same |
|
||||
| Enter, Backspace | accept, back (phone and menus) | the same |
|
||||
| Z | HUD and objective | the same |
|
||||
|
||||
A key you were holding when you got in or out counts again once you have let it go and pressed it again: W held
|
||||
while climbing in does not drive off by itself, and a held mouse button does not start to fire.
|
||||
|
||||
The runtime reads from the game whether you are in a vehicle. Where it cannot (another version of the game), the
|
||||
keys stay the on-foot ones and **Caps Lock** is the switch: press it once you sit in a vehicle for the driving keys,
|
||||
and again, or F to get out, for the on-foot keys. Without it a vehicle still drives the old way: left mouse button
|
||||
accelerates, right mouse button brakes. Should the runtime get it wrong, `-More @{LEONIDA_PLAYER_VEHICLE_AT='off'}`
|
||||
stops it reading and leaves the switch to Caps Lock.
|
||||
|
||||
Not bound, because it is not known yet which controller button does it in this game: V (camera), G (grenade), the
|
||||
number keys and the mouse wheel (weapons), aiming from a vehicle. A controller keeps working beside the keyboard at
|
||||
all times. `LEONIDA_KBM=classic` (with `-More @{LEONIDA_KBM='classic'}`) brings back the keys of before; the
|
||||
details, the mouse settings and the other switches are in [docs/gameinput.md](../docs/gameinput.md).
|
||||
|
||||
### Picking a resolution
|
||||
|
||||
There is one script per console and resolution in `scripts\`. Each one runs
|
||||
|
||||
@ -495,6 +495,9 @@ impl Game {
|
||||
);
|
||||
let ped = self.ped();
|
||||
let _ = writeln!(s, " player ped {ped:x?}, position {:?}, forward {:?}", self.position(), self.forward());
|
||||
// The global `player_context` reads: the vehicle the player is in, null on foot.
|
||||
let vehicle = self.at(Site::PlayerVehicle).and_then(mem::read_u64);
|
||||
let _ = writeln!(s, " player's vehicle {vehicle:x?}");
|
||||
// SAFETY: forwarded from this function's contract.
|
||||
let wanted = ped.and_then(|ped| unsafe { self.wanted_level(ped) });
|
||||
let _ = writeln!(s, " wanted level {wanted:?}, clock {:?}", self.clock());
|
||||
@ -820,16 +823,24 @@ fn run_script(script: Vec<(f32, Command)>) {
|
||||
}
|
||||
|
||||
/// With `LEONIDA_GAME_ACTIONS=1`: finds the title's code in the image just mapped, hooks its cheat update and
|
||||
/// lends the menu the actions. Nothing is changed in the title otherwise.
|
||||
/// lends the menu the actions. Nothing is changed in the title otherwise. Gives what it found of the title (for
|
||||
/// who else reads it: `player_context`), `None` when it did not look.
|
||||
///
|
||||
/// # Safety
|
||||
/// `base` is the title's executable `info` describes, mapped, and none of its code runs yet.
|
||||
pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo) {
|
||||
pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo) -> Option<Sites> {
|
||||
if !places::wanted() {
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
// SAFETY: forwarded from this function's contract; the hook is a function of this program.
|
||||
let (sites, hooked) = unsafe { places::install(base, info, frame_hook as extern "win64" fn() as usize) };
|
||||
let found = sites.clone();
|
||||
start(base, info, sites, hooked);
|
||||
Some(found)
|
||||
}
|
||||
|
||||
/// The rest of [`install`]: the actions, when the hook is in.
|
||||
fn start(base: usize, info: &leonida_pe::ImageInfo, sites: Sites, hooked: Result<(), String>) {
|
||||
for line in &sites.missing {
|
||||
println!("game actions not found: {line}");
|
||||
}
|
||||
|
||||
@ -14,6 +14,8 @@ mod replay;
|
||||
mod game_actions;
|
||||
#[cfg(windows)]
|
||||
mod player;
|
||||
#[cfg(windows)]
|
||||
mod player_context;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod player_find;
|
||||
mod run;
|
||||
|
||||
815
d3d12/apps/leonida/src/player_context.rs
Normal file
815
d3d12/apps/leonida/src/player_context.rs
Normal file
@ -0,0 +1,815 @@
|
||||
//! What the player is in, on foot or in a vehicle, read from the title and told to the keyboard and mouse layout
|
||||
//! (`leonida_hle::modules::gameinput`, `kbm`): the right trigger shoots on foot and accelerates in a vehicle, so
|
||||
//! the layout has two tables and has to know which one counts (`docs/gameinput.md`).
|
||||
//!
|
||||
//! A thread of ours reads a few words of the title's memory every 16 ms, through `ReadProcessMemory` on the own
|
||||
//! process (a page that is gone is a failed read, not a fault). Nothing is written to the title and none of its
|
||||
//! code is called, so this needs no `LEONIDA_GAME_ACTIONS=1`: it only needs the two globals found, by the
|
||||
//! patterns of `leonida_loader::game_actions`.
|
||||
//!
|
||||
//! What says "in a vehicle", the first of these that there is:
|
||||
//!
|
||||
//! - `LEONIDA_PED_VEHICLE_AT=0x<offset>`: a field of the player's ped that points at its vehicle and is null on
|
||||
//! foot (for a measured offset; none is known).
|
||||
//! - `LEONIDA_PLAYER_VEHICLE_AT=0x<offset in the image>`: a global of the title that holds the player's vehicle
|
||||
//! and is null on foot. Without the variable this is `Site::PlayerVehicle`, found by its pattern;
|
||||
//! `LEONIDA_PLAYER_VEHICLE_AT=off` leaves it unused.
|
||||
//! - `LEONIDA_KBM_SPEED=1`: how fast the ped moves ([`SpeedRule`]). It only ever says "in a vehicle", and only
|
||||
//! once the ped has been faster than anyone runs for a second, so it is off unless asked for: the keys' meaning
|
||||
//! would change in the middle of a drive. It always runs as a check of the two above, into the log.
|
||||
//!
|
||||
//! With none of them the context stays unknown, and the layout is the on-foot one with Caps Lock as the switch.
|
||||
//!
|
||||
//! `LEONIDA_PED_DUMP=<folder>` (outside the repository) is for measuring: F8 in the game's window, or a file named
|
||||
//! `dump` in that folder (its text is the dump's label; it is removed as it is seen), writes the first 0x4000
|
||||
//! bytes of the player's ped to `ped-<time>-<label>.bin` there, the first 0x1000 of the vehicle the global names
|
||||
//! to `vehicle-<time>-<label>.bin`, and a line to `index.txt`. Those are the title's memory: never commit them.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use leonida_hle::modules::gameinput::{self, PlayerContext};
|
||||
use leonida_loader::game_actions::{self as places, Site, Sites};
|
||||
|
||||
use crate::player::mem;
|
||||
|
||||
/// The thread's step.
|
||||
const TICK: Duration = Duration::from_millis(16);
|
||||
/// A change of what is read counts once it was read so many times in a row.
|
||||
const STEADY_READS: u32 = 3;
|
||||
/// How much of the ped, and of its vehicle, a dump holds.
|
||||
const PED_DUMP: usize = 0x4000;
|
||||
const VEHICLE_DUMP: usize = 0x1000;
|
||||
const PAGE: usize = 0x1000;
|
||||
/// The key that asks for a dump: F8.
|
||||
const VK_DUMP: i32 = 0x77;
|
||||
|
||||
/// A number as the switches give it: `0x1a2b` or `6699`.
|
||||
fn parse_offset(text: &str) -> Option<usize> {
|
||||
let text = text.trim();
|
||||
match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
|
||||
Some(hex) => usize::from_str_radix(hex, 16).ok(),
|
||||
None => text.parse().ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the switches ask for.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
struct Settings {
|
||||
/// `LEONIDA_PED_VEHICLE_AT`.
|
||||
ped_field: Option<usize>,
|
||||
/// `LEONIDA_PLAYER_VEHICLE_AT`: an offset in the image, or `off` (`Some(None)`).
|
||||
global: Option<Option<usize>>,
|
||||
/// `LEONIDA_KBM_SPEED=1`.
|
||||
speed: bool,
|
||||
/// `LEONIDA_PED_DUMP`.
|
||||
dump: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
fn parse(ped_field: Option<&str>, global: Option<&str>, speed: Option<&str>, dump: Option<&str>) -> Settings {
|
||||
Settings {
|
||||
ped_field: ped_field.and_then(parse_offset).filter(|at| *at < 0x10_0000),
|
||||
global: global.and_then(|text| match text.trim() {
|
||||
"off" | "0" => Some(None),
|
||||
text => parse_offset(text).map(Some),
|
||||
}),
|
||||
speed: speed.is_some_and(|v| v.trim() == "1"),
|
||||
dump: dump.map(str::trim).filter(|d| !d.is_empty()).map(PathBuf::from),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_env() -> Settings {
|
||||
let var = |name: &str| std::env::var(name).ok();
|
||||
Settings::parse(
|
||||
var("LEONIDA_PED_VEHICLE_AT").as_deref(),
|
||||
var("LEONIDA_PLAYER_VEHICLE_AT").as_deref(),
|
||||
var("LEONIDA_KBM_SPEED").as_deref(),
|
||||
var("LEONIDA_PED_DUMP").as_deref(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// What says whether the player is in a vehicle.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Source {
|
||||
/// A field of the player's ped that points at its vehicle (offset in the ped).
|
||||
PedField(usize),
|
||||
/// A global of the title that holds the player's vehicle (offset in the image).
|
||||
Global(usize),
|
||||
/// How fast the ped moves.
|
||||
Speed,
|
||||
Nothing,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
/// The first there is: the measured field, the global (named, or found unless turned off), the speed.
|
||||
fn pick(settings: &Settings, found_global: Option<usize>) -> Source {
|
||||
let global = match settings.global {
|
||||
Some(named) => named,
|
||||
None => found_global,
|
||||
};
|
||||
match (settings.ped_field, global) {
|
||||
(Some(at), _) => Source::PedField(at),
|
||||
(None, Some(at)) => Source::Global(at),
|
||||
(None, None) if settings.speed => Source::Speed,
|
||||
(None, None) => Source::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
match self {
|
||||
Source::PedField(at) => format!("the ped's field at {at:#x} (LEONIDA_PED_VEHICLE_AT)"),
|
||||
Source::Global(at) => format!("the title's global of the player's vehicle, at {at:#x} in the image"),
|
||||
Source::Speed => "the ped's speed (LEONIDA_KBM_SPEED=1)".into(),
|
||||
Source::Nothing => "nothing".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a word that should point at the player's vehicle says: null is on foot, an address is in a vehicle, and
|
||||
/// a read that failed or anything else says nothing.
|
||||
fn pointer_says(word: Option<u64>) -> PlayerContext {
|
||||
match word {
|
||||
Some(0) => PlayerContext::OnFoot,
|
||||
Some(p) if (0x1_0000..0x8000_0000_0000).contains(&p) => PlayerContext::InVehicle,
|
||||
_ => PlayerContext::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// A read counts once it is the same [`STEADY_READS`] times in a row: we read while the title writes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Steady {
|
||||
shown: PlayerContext,
|
||||
seen: PlayerContext,
|
||||
times: u32,
|
||||
}
|
||||
|
||||
impl Default for Steady {
|
||||
fn default() -> Steady {
|
||||
Steady { shown: PlayerContext::Unknown, seen: PlayerContext::Unknown, times: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Steady {
|
||||
fn step(&mut self, read: PlayerContext) -> PlayerContext {
|
||||
if read == self.shown {
|
||||
self.times = 0;
|
||||
} else if read == self.seen && self.times > 0 {
|
||||
self.times += 1;
|
||||
if self.times >= STEADY_READS {
|
||||
self.shown = read;
|
||||
self.times = 0;
|
||||
}
|
||||
} else {
|
||||
self.seen = read;
|
||||
self.times = 1;
|
||||
}
|
||||
self.shown
|
||||
}
|
||||
}
|
||||
|
||||
/// The speed rule: a ped that moves faster than anyone runs is in a vehicle.
|
||||
///
|
||||
/// The ped's position is taken about every [`SpeedRule::WINDOW`] and gives a speed over the ground (the title
|
||||
/// moves the ped 30 times a second, so a shorter step would read 0 and double by turns). At
|
||||
/// [`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
|
||||
/// series' are) for [`SpeedRule::PROVEN`] without a break, the ped is driving, and stays so until it has not been
|
||||
/// that fast for [`SpeedRule::HOLD`].
|
||||
///
|
||||
/// Its limits: it never says "on foot" (a car at a red light and a ped standing look the same), so below that
|
||||
/// speed it says nothing; it cannot see a drive begin, so it never switches to driving from a standstill and the
|
||||
/// first metres of every drive are on the on-foot keys; a ped carried at that speed without driving (a passenger,
|
||||
/// a train's roof) counts as driving; a fall is left out (more down than along), and so is a jump of the position
|
||||
/// (a teleport, a respawn: more than [`SpeedRule::JUMP`]), which also ends a drive.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct SpeedRule {
|
||||
/// The position the next speed is measured from, and its time (seconds).
|
||||
from: Option<([f32; 3], f64)>,
|
||||
/// The speed last measured, metres a second over the ground.
|
||||
speed: f32,
|
||||
/// Since when the ped has been fast without a break, and when it last was.
|
||||
fast_since: Option<f64>,
|
||||
fast_last: Option<f64>,
|
||||
proven: bool,
|
||||
}
|
||||
|
||||
impl SpeedRule {
|
||||
const WINDOW: f64 = 0.2;
|
||||
const FAST: f32 = 12.0;
|
||||
const JUMP: f32 = 120.0;
|
||||
const PROVEN: f64 = 1.0;
|
||||
const HOLD: f64 = 3.0;
|
||||
|
||||
/// Takes the ped's position at `t` seconds.
|
||||
fn step(&mut self, position: [f32; 3], t: f64) {
|
||||
let Some((from, at)) = self.from else {
|
||||
self.from = Some((position, t));
|
||||
return;
|
||||
};
|
||||
let dt = t - at;
|
||||
if dt < Self::WINDOW {
|
||||
return;
|
||||
}
|
||||
self.from = Some((position, t));
|
||||
// A gap (the thread or the title stood still): no speed from it.
|
||||
if dt > 1.0 {
|
||||
self.lost();
|
||||
return;
|
||||
}
|
||||
let along = (position[0] - from[0]).hypot(position[1] - from[1]) / dt as f32;
|
||||
let down = (position[2] - from[2]).abs() / dt as f32;
|
||||
if along > Self::JUMP || down > Self::JUMP {
|
||||
self.lost();
|
||||
return;
|
||||
}
|
||||
self.speed = along;
|
||||
if along >= Self::FAST && down <= along {
|
||||
self.fast_since.get_or_insert(t);
|
||||
self.fast_last = Some(t);
|
||||
self.proven |= self.fast_since.is_some_and(|since| t - since >= Self::PROVEN);
|
||||
} else if !self.proven {
|
||||
self.fast_since = None;
|
||||
}
|
||||
if self.fast_last.is_some_and(|last| t - last > Self::HOLD) {
|
||||
self.lost();
|
||||
}
|
||||
}
|
||||
|
||||
/// No position (no ped), a gap or a jump: nothing is known any more.
|
||||
fn lost(&mut self) {
|
||||
*self = SpeedRule { from: self.from, ..Default::default() };
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
*self = SpeedRule::default();
|
||||
}
|
||||
|
||||
/// Whether the ped is driving by this rule, at `t`.
|
||||
fn driving(&self, t: f64) -> bool {
|
||||
self.proven && self.fast_last.is_some_and(|last| t - last <= Self::HOLD)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the title keeps what is read, as addresses in this run.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Reader {
|
||||
base: usize,
|
||||
/// The global that holds the player's ped.
|
||||
ped_at: Option<usize>,
|
||||
/// The global that holds the player's vehicle, when one is known (also when it is not the source: dumps
|
||||
/// and the log show it).
|
||||
vehicle_at: Option<usize>,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
fn ped(&self) -> Option<usize> {
|
||||
let ped = mem::read_u64(self.ped_at?)? as usize;
|
||||
(ped > 0x10000).then_some(ped)
|
||||
}
|
||||
|
||||
fn vehicle(&self) -> Option<usize> {
|
||||
let vehicle = mem::read_u64(self.vehicle_at?)? as usize;
|
||||
(vehicle > 0x10000).then_some(vehicle)
|
||||
}
|
||||
|
||||
fn position(entity: usize) -> Option<[f32; 3]> {
|
||||
let b = mem::read_vec(entity + places::ENTITY_POSITION_AT, 12)?;
|
||||
let v: [f32; 3] = std::array::from_fn(|i| f32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().unwrap()));
|
||||
v.iter().all(|c| c.is_finite() && c.abs() < 1.0e6).then_some(v)
|
||||
}
|
||||
|
||||
/// What the source says now. With no ped in the world (loading, the menus) nothing is known.
|
||||
fn context(&self, ped: Option<usize>, speed: &SpeedRule, t: f64) -> PlayerContext {
|
||||
if self.ped_at.is_some() && ped.is_none() {
|
||||
return PlayerContext::Unknown;
|
||||
}
|
||||
match self.source {
|
||||
Source::PedField(at) => ped.map_or(PlayerContext::Unknown, |ped| pointer_says(mem::read_u64(ped + at))),
|
||||
Source::Global(at) => pointer_says(mem::read_u64(self.base + at)),
|
||||
Source::Speed if speed.driving(t) => PlayerContext::InVehicle,
|
||||
Source::Speed | Source::Nothing => PlayerContext::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn say(line: &str) {
|
||||
eprintln!("Leonida: player context: {line}");
|
||||
}
|
||||
|
||||
/// The local date and time: year, month, day, hour, minute, second, millisecond.
|
||||
fn local_time() -> [u16; 7] {
|
||||
unsafe extern "system" {
|
||||
fn GetLocalTime(time: *mut [u16; 8]);
|
||||
}
|
||||
let mut t = [0u16; 8];
|
||||
// SAFETY: fills the eight words of a SYSTEMTIME.
|
||||
unsafe { GetLocalTime(&mut t) };
|
||||
// (the third word is the day of the week)
|
||||
[t[0], t[1], t[3], t[4], t[5], t[6], t[7]]
|
||||
}
|
||||
|
||||
/// A dump's label as part of a file name: letters, digits, `-` and `_`, at most 32; `dump` when nothing is left.
|
||||
fn label_of(text: &str) -> String {
|
||||
let label: String =
|
||||
text.trim().chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(32).collect();
|
||||
if label.is_empty() { "dump".into() } else { label }
|
||||
}
|
||||
|
||||
/// `len` bytes at `address`, page by page: what does not read is zero, and its offsets are listed.
|
||||
fn read_pages(address: usize, len: usize) -> (Vec<u8>, Vec<usize>) {
|
||||
let mut data = vec![0u8; len];
|
||||
let mut unread = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < len {
|
||||
// Up to the end of the page `address + at` lies in.
|
||||
let step = (PAGE - (address + at) % PAGE).min(len - at);
|
||||
if !mem::read(address + at, &mut data[at..at + step]) {
|
||||
unread.push(at);
|
||||
}
|
||||
at += step;
|
||||
}
|
||||
(data, unread)
|
||||
}
|
||||
|
||||
/// What is known when a dump is asked for.
|
||||
struct Moment {
|
||||
label: String,
|
||||
time: [u16; 7],
|
||||
seconds: f64,
|
||||
ped: usize,
|
||||
vehicle: Option<usize>,
|
||||
speed: f32,
|
||||
read: PlayerContext,
|
||||
shown: PlayerContext,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
/// Writes the dump's files into `dir` and its line into `index.txt`; gives the ped's file.
|
||||
fn write_dump(dir: &Path, m: &Moment) -> std::io::Result<PathBuf> {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let [year, month, day, hour, minute, second, ms] = m.time;
|
||||
let stamp = format!("{year:04}{month:02}{day:02}-{hour:02}{minute:02}{second:02}-{ms:03}");
|
||||
let (bytes, unread) = read_pages(m.ped, PED_DUMP);
|
||||
let ped_file = dir.join(format!("ped-{stamp}-{}.bin", m.label));
|
||||
std::fs::write(&ped_file, &bytes)?;
|
||||
let id_at = places::ENTITY_ID_AT;
|
||||
let id = bytes.get(id_at..id_at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap()));
|
||||
let position = Reader::position(m.ped);
|
||||
let mut line = format!(
|
||||
"{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}.{ms:03} {} label {} at {:.1} s \
|
||||
ped {:#x} id {:#x} position {position:?} speed {:.1} m/s read {:?} told {:?} by {}",
|
||||
ped_file.file_name().unwrap_or_default().to_string_lossy(),
|
||||
m.label,
|
||||
m.seconds,
|
||||
m.ped,
|
||||
id.unwrap_or(0),
|
||||
m.speed,
|
||||
m.read,
|
||||
m.shown,
|
||||
m.source.describe(),
|
||||
);
|
||||
match m.vehicle {
|
||||
Some(vehicle) => {
|
||||
let (bytes, _) = read_pages(vehicle, VEHICLE_DUMP);
|
||||
let file = format!("vehicle-{stamp}-{}.bin", m.label);
|
||||
std::fs::write(dir.join(&file), &bytes)?;
|
||||
let away = position.zip(Reader::position(vehicle)).map(|(a, b)| {
|
||||
((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
|
||||
});
|
||||
let away = away.map_or("?".to_owned(), |metres| format!("{metres:.1}"));
|
||||
line.push_str(&format!(" vehicle global {vehicle:#x} ({file}), {away} m from the ped"));
|
||||
}
|
||||
None => line.push_str(" vehicle global null or not known"),
|
||||
}
|
||||
if !unread.is_empty() {
|
||||
line.push_str(&format!(" not readable (zero in the file): pages at {unread:x?}"));
|
||||
}
|
||||
let mut index = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("index.txt"))?;
|
||||
writeln!(index, "{line}")?;
|
||||
Ok(ped_file)
|
||||
}
|
||||
|
||||
/// Whether a dump is asked for now: its label.
|
||||
struct Trigger {
|
||||
dir: PathBuf,
|
||||
key_was: bool,
|
||||
}
|
||||
|
||||
impl Trigger {
|
||||
fn asked(&mut self) -> Option<String> {
|
||||
#[link(name = "user32")]
|
||||
unsafe extern "system" {
|
||||
fn GetAsyncKeyState(key: i32) -> i16;
|
||||
fn GetForegroundWindow() -> isize;
|
||||
fn GetWindowThreadProcessId(window: isize, process: *mut u32) -> u32;
|
||||
}
|
||||
unsafe extern "system" {
|
||||
fn GetCurrentProcessId() -> u32;
|
||||
}
|
||||
let mut owner = 0u32;
|
||||
// SAFETY: plain queries; a null window gives process 0.
|
||||
let down = unsafe {
|
||||
GetWindowThreadProcessId(GetForegroundWindow(), &mut owner);
|
||||
owner == GetCurrentProcessId() && GetAsyncKeyState(VK_DUMP) < 0
|
||||
};
|
||||
let pressed = down && !std::mem::replace(&mut self.key_was, down);
|
||||
if !down {
|
||||
self.key_was = false;
|
||||
}
|
||||
if pressed {
|
||||
return Some("key".into());
|
||||
}
|
||||
let file = self.dir.join("dump");
|
||||
if !file.exists() {
|
||||
return None;
|
||||
}
|
||||
let label = label_of(&std::fs::read_to_string(&file).unwrap_or_default());
|
||||
// One file asks once; a file that cannot be removed would ask for ever.
|
||||
std::fs::remove_file(&file).is_ok().then_some(label)
|
||||
}
|
||||
}
|
||||
|
||||
fn run(reader: Reader, tells: bool, dump: Option<PathBuf>) {
|
||||
let start = Instant::now();
|
||||
let mut steady = Steady::default();
|
||||
let mut speed = SpeedRule::default();
|
||||
let mut trigger = dump.map(|dir| Trigger { dir, key_was: false });
|
||||
let mut told = PlayerContext::Unknown;
|
||||
// When each check last spoke (seconds): at most once in half a minute.
|
||||
let (mut fast_on_foot, mut far_vehicle) = (f64::MIN, f64::MIN);
|
||||
let mut tick = 0u64;
|
||||
loop {
|
||||
std::thread::sleep(TICK);
|
||||
tick += 1;
|
||||
let t = start.elapsed().as_secs_f64();
|
||||
let ped = reader.ped();
|
||||
if tick.is_multiple_of(4) {
|
||||
match ped.and_then(Reader::position) {
|
||||
Some(position) => speed.step(position, t),
|
||||
None => speed.reset(),
|
||||
}
|
||||
}
|
||||
let read = reader.context(ped, &speed, t);
|
||||
let shown = steady.step(read);
|
||||
if tells {
|
||||
gameinput::set_player_context(shown);
|
||||
}
|
||||
if shown != told {
|
||||
told = shown;
|
||||
say(&format!("{shown:?} at {t:.2} s (speed {:.1} m/s)", speed.speed));
|
||||
}
|
||||
// The speed as a check of what is read: a ped this fast is not on foot.
|
||||
if shown == PlayerContext::OnFoot && speed.driving(t) && t - fast_on_foot > 30.0 {
|
||||
fast_on_foot = t;
|
||||
say(&format!(
|
||||
"on foot by {}, but the ped has moved at {:.0} m/s for over a second: what is read may be wrong",
|
||||
reader.source.describe(),
|
||||
speed.speed
|
||||
));
|
||||
}
|
||||
if tick.is_multiple_of(16) {
|
||||
// And where the vehicle is: one that stays behind when the ped walks off is not the one it is in.
|
||||
if shown == PlayerContext::InVehicle
|
||||
&& t - far_vehicle > 30.0
|
||||
&& let Some(away) = ped
|
||||
.and_then(Reader::position)
|
||||
.zip(reader.vehicle().and_then(Reader::position))
|
||||
.map(|(a, b)| (a[0] - b[0]).hypot(a[1] - b[1]))
|
||||
&& away > 60.0
|
||||
{
|
||||
far_vehicle = t;
|
||||
say(&format!("in a vehicle by what is read, but that vehicle is {away:.0} m from the ped"));
|
||||
}
|
||||
if let Some(trigger) = trigger.as_mut()
|
||||
&& let Some(label) = trigger.asked()
|
||||
{
|
||||
match ped {
|
||||
Some(ped) => {
|
||||
let moment = Moment {
|
||||
label,
|
||||
time: local_time(),
|
||||
seconds: t,
|
||||
ped,
|
||||
vehicle: reader.vehicle(),
|
||||
speed: speed.speed,
|
||||
read,
|
||||
shown,
|
||||
source: reader.source,
|
||||
};
|
||||
match write_dump(&trigger.dir, &moment) {
|
||||
Ok(file) => say(&format!("the ped is dumped to {}", file.display())),
|
||||
Err(why) => say(&format!("the dump could not be written: {why}")),
|
||||
}
|
||||
}
|
||||
None => say("a dump was asked for, but there is no player ped now"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the reading thread, when the keyboard and mouse layout follows the player's context or dumps are asked
|
||||
/// for. `found` is what the game actions found already (`LEONIDA_GAME_ACTIONS=1`); without it the two globals are
|
||||
/// looked for here, which reads the image's code twice over and changes nothing.
|
||||
///
|
||||
/// # Safety
|
||||
/// `base` is the title's executable `info` describes, mapped, and none of its code runs yet.
|
||||
pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo, found: Option<&Sites>) {
|
||||
let settings = Settings::from_env();
|
||||
let tells = gameinput::player_context_wanted();
|
||||
let dump = settings.dump.clone().filter(|dir| match leonida_core::ensure_outside_repo(dir) {
|
||||
Ok(()) => true,
|
||||
Err(why) => {
|
||||
println!("player context LEONIDA_PED_DUMP not used: {why}");
|
||||
false
|
||||
}
|
||||
});
|
||||
if !tells && dump.is_none() {
|
||||
return;
|
||||
}
|
||||
let began = Instant::now();
|
||||
let sites = match found {
|
||||
Some(sites) => sites.clone(),
|
||||
// SAFETY: forwarded from this function's contract.
|
||||
None => unsafe { places::find(base, info, Some(&[Site::PlayerPed, Site::PlayerVehicle])) },
|
||||
};
|
||||
let looked = began.elapsed();
|
||||
if found.is_none() {
|
||||
for line in &sites.missing {
|
||||
println!("player context not found: {line}");
|
||||
}
|
||||
}
|
||||
let found_global = sites.get(Site::PlayerVehicle);
|
||||
let source = match Source::pick(&settings, found_global) {
|
||||
_ if !tells => Source::Nothing,
|
||||
Source::Global(at) if at + 8 > info.size_of_image as usize => {
|
||||
println!("player context LEONIDA_PLAYER_VEHICLE_AT={at:#x} is not in the image: not used");
|
||||
Source::Nothing
|
||||
}
|
||||
source => source,
|
||||
};
|
||||
let named = match settings.global {
|
||||
Some(named) => named,
|
||||
None => found_global,
|
||||
};
|
||||
let reader = Reader {
|
||||
base,
|
||||
ped_at: sites.get(Site::PlayerPed).map(|rva| base + rva),
|
||||
vehicle_at: named.filter(|rva| *rva < info.size_of_image as usize).map(|rva| base + rva),
|
||||
source,
|
||||
};
|
||||
if tells && source == Source::Nothing {
|
||||
println!("player context not read: the on-foot keys, and Caps Lock switches to the driving keys by hand");
|
||||
} else if tells {
|
||||
println!(
|
||||
"player context read from {} ({} ms to find it): W accelerates and the mouse shoots in a vehicle",
|
||||
source.describe(),
|
||||
looked.as_millis()
|
||||
);
|
||||
}
|
||||
if let Some(dir) = &dump {
|
||||
println!("player context F8, or a file named dump in {}, dumps the player's ped there", dir.display());
|
||||
}
|
||||
if source == Source::Nothing && dump.is_none() {
|
||||
return;
|
||||
}
|
||||
let thread = std::thread::Builder::new().name("leonida-player-context".into());
|
||||
if thread.spawn(move || run(reader, tells, dump)).is_err() {
|
||||
println!("player context the reading thread could not be started");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FOOT: PlayerContext = PlayerContext::OnFoot;
|
||||
const CAR: PlayerContext = PlayerContext::InVehicle;
|
||||
const UNKNOWN: PlayerContext = PlayerContext::Unknown;
|
||||
|
||||
#[test]
|
||||
fn offsets_and_switches_read() {
|
||||
assert_eq!(parse_offset("0x1a2B"), Some(0x1a2b));
|
||||
assert_eq!(parse_offset(" 0X10 "), Some(16));
|
||||
assert_eq!(parse_offset("4096"), Some(4096));
|
||||
for wrong in ["", "0x", "xyz", "-1", "0x1g"] {
|
||||
assert_eq!(parse_offset(wrong), None, "{wrong:?}");
|
||||
}
|
||||
assert_eq!(Settings::parse(None, None, None, None), Settings::default());
|
||||
let s = Settings::parse(Some("0xd10"), Some("0xab760c8"), Some("1"), Some(r" D:\dumps "));
|
||||
assert_eq!(s.ped_field, Some(0xd10));
|
||||
assert_eq!(s.global, Some(Some(0xab7_60c8)));
|
||||
assert!(s.speed);
|
||||
assert_eq!(s.dump, Some(PathBuf::from(r"D:\dumps")));
|
||||
// An offset in a ped is small; `off` turns the global off; what does not read is as unset.
|
||||
assert_eq!(Settings::parse(Some("0x7ff600001000"), None, None, None).ped_field, None);
|
||||
assert_eq!(Settings::parse(None, Some("off"), Some("0"), Some(" ")).global, Some(None));
|
||||
assert_eq!(Settings::parse(None, Some("what"), Some("yes"), None), Settings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_source_is_the_first_there_is() {
|
||||
let none = Settings::default();
|
||||
assert_eq!(Source::pick(&none, None), Source::Nothing);
|
||||
assert_eq!(Source::pick(&none, Some(0x500)), Source::Global(0x500));
|
||||
let field = Settings { ped_field: Some(0x10), ..Default::default() };
|
||||
assert_eq!(Source::pick(&field, Some(0x500)), Source::PedField(0x10));
|
||||
let named = Settings { global: Some(Some(0x700)), speed: true, ..Default::default() };
|
||||
assert_eq!(Source::pick(&named, Some(0x500)), Source::Global(0x700));
|
||||
assert_eq!(Source::pick(&named, None), Source::Global(0x700));
|
||||
let off = Settings { global: Some(None), ..Default::default() };
|
||||
assert_eq!(Source::pick(&off, Some(0x500)), Source::Nothing);
|
||||
let speed = Settings { global: Some(None), speed: true, ..Default::default() };
|
||||
assert_eq!(Source::pick(&speed, Some(0x500)), Source::Speed);
|
||||
for source in [Source::Nothing, Source::Speed, Source::Global(1), Source::PedField(2)] {
|
||||
assert!(!source.describe().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pointer_says_where_the_player_is() {
|
||||
assert_eq!(pointer_says(Some(0)), FOOT);
|
||||
assert_eq!(pointer_says(Some(0x1_4a3f_2c80)), CAR);
|
||||
// No read, or a word that is no address: nothing.
|
||||
assert_eq!(pointer_says(None), UNKNOWN);
|
||||
assert_eq!(pointer_says(Some(7)), UNKNOWN);
|
||||
assert_eq!(pointer_says(Some(u64::MAX)), UNKNOWN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_counts_after_three_in_a_row() {
|
||||
let mut s = Steady::default();
|
||||
assert_eq!(s.step(UNKNOWN), UNKNOWN);
|
||||
assert_eq!(s.step(FOOT), UNKNOWN);
|
||||
assert_eq!(s.step(FOOT), UNKNOWN);
|
||||
assert_eq!(s.step(FOOT), FOOT);
|
||||
// One odd read (the title was writing) changes nothing, nor do two.
|
||||
assert_eq!(s.step(CAR), FOOT);
|
||||
assert_eq!(s.step(FOOT), FOOT);
|
||||
assert_eq!(s.step(CAR), FOOT);
|
||||
assert_eq!(s.step(CAR), FOOT);
|
||||
assert_eq!(s.step(UNKNOWN), FOOT);
|
||||
assert_eq!(s.step(CAR), FOOT);
|
||||
assert_eq!(s.step(CAR), FOOT);
|
||||
assert_eq!(s.step(CAR), CAR);
|
||||
assert_eq!(s.step(CAR), CAR);
|
||||
}
|
||||
|
||||
/// A ped that moves `speed` metres a second along x (and `fall` down) from `t0` to `t1`, sampled every 64 ms.
|
||||
fn travel(rule: &mut SpeedRule, at: &mut [f32; 3], t0: f64, t1: f64, speed: f32, fall: f32) {
|
||||
let mut t = t0;
|
||||
while t < t1 {
|
||||
at[0] += speed * 0.064;
|
||||
at[2] -= fall * 0.064;
|
||||
t += 0.064;
|
||||
rule.step(*at, t);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_speed_rule_never_drives_from_a_standstill() {
|
||||
let mut rule = SpeedRule::default();
|
||||
let mut at = [100.0, 200.0, 30.0];
|
||||
// Standing, walking, sprinting: never driving, however long.
|
||||
for speed in [0.0, 1.5, 7.5, 11.0] {
|
||||
travel(&mut rule, &mut at, 0.0, 30.0, speed, 0.0);
|
||||
assert!(!rule.driving(30.0), "{speed} m/s");
|
||||
assert!((rule.speed - speed).abs() < 0.5, "{} for {speed}", rule.speed);
|
||||
rule.reset();
|
||||
}
|
||||
// Fast for less than a second (thrown by a car): not driving.
|
||||
travel(&mut rule, &mut at, 0.0, 0.7, 25.0, 0.0);
|
||||
travel(&mut rule, &mut at, 0.7, 5.0, 0.0, 0.0);
|
||||
assert!(!rule.driving(5.0));
|
||||
// A fall: fast, but more down than along.
|
||||
rule.reset();
|
||||
travel(&mut rule, &mut at, 0.0, 4.0, 14.0, 40.0);
|
||||
assert!(!rule.driving(4.0));
|
||||
// A teleport: one jump, then standing.
|
||||
rule.reset();
|
||||
travel(&mut rule, &mut at, 0.0, 1.0, 0.0, 0.0);
|
||||
at[0] += 2000.0;
|
||||
travel(&mut rule, &mut at, 1.0, 5.0, 0.0, 0.0);
|
||||
assert!(!rule.driving(5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_speed_rule_sees_a_drive_once_it_is_fast_and_lets_go_after_it() {
|
||||
let mut rule = SpeedRule::default();
|
||||
let mut at = [0.0, 0.0, 0.0];
|
||||
// Pulling away: not yet. At 20 m/s for over a second: driving.
|
||||
travel(&mut rule, &mut at, 0.0, 2.0, 6.0, 0.0);
|
||||
assert!(!rule.driving(2.0));
|
||||
travel(&mut rule, &mut at, 2.0, 2.8, 20.0, 0.0);
|
||||
assert!(!rule.driving(2.8), "not yet a second");
|
||||
travel(&mut rule, &mut at, 2.8, 4.0, 20.0, 0.0);
|
||||
assert!(rule.driving(4.0));
|
||||
// Slowing for a corner keeps it; three seconds below the speed end it.
|
||||
travel(&mut rule, &mut at, 4.0, 6.0, 5.0, 0.0);
|
||||
assert!(rule.driving(6.0));
|
||||
travel(&mut rule, &mut at, 6.0, 8.0, 20.0, 0.0);
|
||||
travel(&mut rule, &mut at, 8.0, 12.0, 0.0, 0.0);
|
||||
assert!(!rule.driving(12.0));
|
||||
// And a new drive has to prove itself again.
|
||||
travel(&mut rule, &mut at, 12.0, 12.6, 20.0, 0.0);
|
||||
assert!(!rule.driving(12.6));
|
||||
// A respawn in the middle of a drive ends it.
|
||||
travel(&mut rule, &mut at, 12.6, 15.0, 20.0, 0.0);
|
||||
assert!(rule.driving(15.0));
|
||||
at[1] += 900.0;
|
||||
travel(&mut rule, &mut at, 15.0, 15.5, 0.0, 0.0);
|
||||
assert!(!rule.driving(15.5));
|
||||
// No ped: nothing is known.
|
||||
travel(&mut rule, &mut at, 15.5, 18.0, 20.0, 0.0);
|
||||
assert!(rule.driving(18.0));
|
||||
rule.reset();
|
||||
assert!(!rule.driving(18.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_reads_this_process() {
|
||||
// A made-up ped and vehicle in our own memory, and the two globals that point at them.
|
||||
let mut ped = vec![0u8; PED_DUMP];
|
||||
let mut vehicle = vec![0u8; VEHICLE_DUMP];
|
||||
for (entity, x) in [(&mut ped, 10.0f32), (&mut vehicle, 13.0)] {
|
||||
for (i, v) in [x, 20.0, 5.0].iter().enumerate() {
|
||||
let at = places::ENTITY_POSITION_AT + i * 4;
|
||||
entity[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
ped[places::ENTITY_ID_AT..places::ENTITY_ID_AT + 4].copy_from_slice(&0x6_0123u32.to_le_bytes());
|
||||
let field = 0x898;
|
||||
let mut globals: Box<[u64; 2]> = Box::new([ped.as_ptr() as u64, 0]);
|
||||
let base = globals.as_mut_ptr() as usize;
|
||||
let reader = |source| Reader { base, ped_at: Some(base), vehicle_at: Some(base + 8), source };
|
||||
let speed = SpeedRule::default();
|
||||
let r = reader(Source::Global(8));
|
||||
assert_eq!(r.ped(), Some(ped.as_ptr() as usize));
|
||||
assert_eq!(Reader::position(r.ped().unwrap()), Some([10.0, 20.0, 5.0]));
|
||||
// On foot: the global is null, and so is the ped's field.
|
||||
assert_eq!(r.context(r.ped(), &speed, 0.0), FOOT);
|
||||
assert_eq!(reader(Source::PedField(field)).context(r.ped(), &speed, 0.0), FOOT);
|
||||
assert_eq!(reader(Source::Speed).context(r.ped(), &speed, 0.0), UNKNOWN);
|
||||
assert_eq!(reader(Source::Nothing).context(r.ped(), &speed, 0.0), UNKNOWN);
|
||||
// In a vehicle.
|
||||
globals[1] = vehicle.as_ptr() as u64;
|
||||
ped[field..field + 8].copy_from_slice(&(vehicle.as_ptr() as u64).to_le_bytes());
|
||||
assert_eq!(r.context(r.ped(), &speed, 0.0), CAR);
|
||||
assert_eq!(r.vehicle(), Some(vehicle.as_ptr() as usize));
|
||||
assert_eq!(reader(Source::PedField(field)).context(r.ped(), &speed, 0.0), CAR);
|
||||
// No ped in the world: unknown, whatever the global holds.
|
||||
assert_eq!(r.context(None, &speed, 0.0), UNKNOWN);
|
||||
// A global that cannot be read: unknown.
|
||||
let gone = Reader { base: 0x10, ped_at: None, vehicle_at: None, source: Source::Global(8) };
|
||||
assert_eq!(gone.context(None, &speed, 0.0), UNKNOWN);
|
||||
|
||||
// The dump: the ped's bytes, the vehicle's, and a line that says what was read.
|
||||
let dir = std::env::temp_dir().join(format!("leonida-ped-dump-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let moment = Moment {
|
||||
label: label_of(" in a car! "),
|
||||
time: [2026, 11, 27, 21, 4, 5, 6],
|
||||
seconds: 12.5,
|
||||
ped: r.ped().unwrap(),
|
||||
vehicle: r.vehicle(),
|
||||
speed: 3.0,
|
||||
read: CAR,
|
||||
shown: CAR,
|
||||
source: r.source,
|
||||
};
|
||||
let file = write_dump(&dir, &moment).unwrap();
|
||||
assert_eq!(file.file_name().unwrap(), "ped-20261127-210405-006-inacar.bin");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), ped);
|
||||
assert_eq!(std::fs::read(dir.join("vehicle-20261127-210405-006-inacar.bin")).unwrap(), vehicle);
|
||||
let index = std::fs::read_to_string(dir.join("index.txt")).unwrap();
|
||||
assert!(index.contains("2026-11-27 21:04:05.006") && index.contains("label inacar"), "{index}");
|
||||
assert!(index.contains("id 0x60123"), "{index}");
|
||||
assert!(index.contains("3.0 m from the ped") && index.contains("read InVehicle"), "{index}");
|
||||
assert!(!index.contains("not readable"), "{index}");
|
||||
// A file named `dump` asks once, and its text is the label.
|
||||
let mut trigger = Trigger { dir: dir.clone(), key_was: false };
|
||||
assert_eq!(trigger.asked(), None);
|
||||
std::fs::write(dir.join("dump"), "foot\n").unwrap();
|
||||
assert_eq!(trigger.asked().as_deref(), Some("foot"));
|
||||
assert_eq!(trigger.asked(), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_does_not_read_is_zero_in_a_dump() {
|
||||
// Two pages of ours, then whatever follows a low address nobody has.
|
||||
let ours = vec![0xA5u8; 2 * PAGE];
|
||||
let (data, unread) = read_pages(ours.as_ptr() as usize, ours.len());
|
||||
assert!(data == ours && unread.is_empty());
|
||||
let (data, unread) = read_pages(0x1800, 0x1000);
|
||||
assert!(data.iter().all(|b| *b == 0));
|
||||
assert_eq!(unread, [0, 0x800]);
|
||||
assert_eq!(label_of(""), "dump");
|
||||
assert_eq!(label_of("on_foot-2"), "on_foot-2");
|
||||
assert_eq!(label_of(r"..\..\x"), "x");
|
||||
assert_eq!(label_of(&"a".repeat(80)).len(), 32);
|
||||
}
|
||||
}
|
||||
@ -224,9 +224,13 @@ pub fn run(
|
||||
}
|
||||
// The trainer menu's game actions (`LEONIDA_GAME_ACTIONS=1`, game_actions.rs): the title's cheat update,
|
||||
// once a frame, goes through the runtime, which does there what the menu asks.
|
||||
// What the player is in, for the keyboard and mouse layout (player_context.rs): read only, with or without
|
||||
// the game actions.
|
||||
if execute {
|
||||
// SAFETY: the image stays mapped, and nothing of it has run yet.
|
||||
unsafe { crate::game_actions::install(image.base(), image.info()) };
|
||||
let found = unsafe { crate::game_actions::install(image.base(), image.info()) };
|
||||
// SAFETY: as above.
|
||||
unsafe { crate::player_context::install(image.base(), image.info(), found.as_ref()) };
|
||||
}
|
||||
// Renderer port #2 (LEONIDA_PORT_DESCRIPTORS=1): the title's stores of descriptor records tell the layer their
|
||||
// slots. Only the 1.0.2.1 executable, each store's bytes checked as well.
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
//! `gameinput.dll`: input devices from the host. Gamepads come from XInput
|
||||
//! (host slots 0-3) and, read over HID, from Sony pads (`hid`; the kind of input in use is `family`);
|
||||
//! while none is connected, the keyboard drives one
|
||||
//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own
|
||||
//! while none is connected, the keyboard and mouse drive one
|
||||
//! stand-in gamepad, in Grand Theft Auto V's PC layout (`kbm`: one table on foot, one in a vehicle; the table
|
||||
//! of before is `FALLBACK_BUTTONS`). The keyboard is a device of its own
|
||||
//! too. A focused window also has a mouse. A poll thread records changes
|
||||
//! and runs device callbacks on connect and disconnect.
|
||||
#![allow(non_snake_case)]
|
||||
@ -24,8 +25,10 @@ use crate::{HleExport, HleModule};
|
||||
|
||||
mod family;
|
||||
mod hid;
|
||||
mod kbm;
|
||||
|
||||
pub use family::Family;
|
||||
pub use kbm::{PlayerContext, driving_controls, player_context, player_context_wanted, set_player_context};
|
||||
|
||||
/// Leonida: the kind of input the player is using (Xbox pad, PlayStation pad, keyboard and mouse), for the
|
||||
/// 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;
|
||||
const HISTORY: usize = 256;
|
||||
const POLL: Duration = Duration::from_millis(8);
|
||||
|
||||
/// The keyboard's stand-in gamepad (virtual key, button), in Leonida's layout (the one its Vulkan runtime's
|
||||
/// The keyboard's stand-in gamepad as it was before `kbm` (`LEONIDA_KBM=classic` brings it back): (virtual key,
|
||||
/// button), in Leonida's layout (the one its Vulkan runtime's
|
||||
/// gameinput shim has): the pad-named keys, and PC-style ones beside them: Space confirms/jumps (A), F interacts (Y),
|
||||
/// R goes back/reloads (B), Left Shift and C click the sticks. H stays a second right-stick click.
|
||||
/// 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 {
|
||||
fn observe(&mut self, _keys: &[KeyState], _look: (f32, f32)) {}
|
||||
}
|
||||
|
||||
/// The stand-in pad of before `kbm`: one table whatever the player is in (`LEONIDA_KBM=classic`).
|
||||
fn fallback(keys: &[KeyState]) -> PadState {
|
||||
let on = |vk: u8| {
|
||||
if keys.iter().any(|k| k.virtual_key == vk) {
|
||||
@ -498,6 +503,8 @@ struct State {
|
||||
pending: Vec<Event>,
|
||||
/// Device callbacks running now: token and thread.
|
||||
running: Vec<(u64, ThreadId)>,
|
||||
/// Leonida: the keyboard and mouse half of the stand-in pad.
|
||||
kbm: kbm::Kbm,
|
||||
}
|
||||
|
||||
pub struct Hub {
|
||||
@ -531,7 +538,7 @@ fn now() -> u64 {
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
fn new(source: Box<dyn Source>, one_pad: bool) -> &'static Hub {
|
||||
fn with(source: Box<dyn Source>, one_pad: bool, keys: kbm::Config) -> &'static Hub {
|
||||
let hub = Box::into_raw(Box::new(Hub {
|
||||
object: Object {
|
||||
vtable: &INPUT,
|
||||
@ -545,6 +552,7 @@ impl Hub {
|
||||
callbacks: Vec::new(),
|
||||
pending: Vec::new(),
|
||||
running: Vec::new(),
|
||||
kbm: kbm::Kbm::new(keys),
|
||||
}),
|
||||
returned: Condvar::new(),
|
||||
}));
|
||||
@ -560,7 +568,7 @@ impl Hub {
|
||||
|
||||
/// A hub over the host's input, polled from now on.
|
||||
fn start(source: Box<dyn Source>) -> &'static Hub {
|
||||
let hub = Hub::new(source, one_pad());
|
||||
let hub = Hub::with(source, one_pad(), kbm::Config::from_env());
|
||||
hub.poll();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
@ -649,8 +657,10 @@ impl State {
|
||||
.collect();
|
||||
let mut events = std::mem::take(&mut self.pending);
|
||||
self.update(devices, MOUSE, mouse.map(Value::Mouse), now, &mut events);
|
||||
// Leonida: the keys and mouse buttons as a pad, by the table of what the player is in (`kbm`).
|
||||
let stand_in = merged(self.kbm.pad(&pad_keys, kbm::measured(now), now), look);
|
||||
if one_pad {
|
||||
let pad = pads.into_iter().flatten().fold(merged(fallback(&pad_keys), look), merged);
|
||||
let pad = pads.into_iter().flatten().fold(stand_in, merged);
|
||||
self.update(devices, FALLBACK, Some(Value::Pad(pad)), now, &mut events);
|
||||
self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events);
|
||||
return events;
|
||||
@ -662,7 +672,7 @@ impl State {
|
||||
for (slot, pad) in pads.into_iter().enumerate() {
|
||||
self.update(devices, slot, pad.map(Value::Pad), now, &mut events);
|
||||
}
|
||||
let fallback = (!any_pad).then(|| Value::Pad(merged(fallback(&pad_keys), look)));
|
||||
let fallback = (!any_pad).then_some(Value::Pad(stand_in));
|
||||
self.update(devices, FALLBACK, fallback, now, &mut events);
|
||||
self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events);
|
||||
events
|
||||
@ -1551,7 +1561,7 @@ mod host {
|
||||
// to the pad (the title's start screen) saw nothing.
|
||||
if slot == 0 {
|
||||
for vk in scripted() {
|
||||
if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) {
|
||||
if let Some(button) = kbm::scripted_button(vk) {
|
||||
pad.buttons |= button;
|
||||
}
|
||||
}
|
||||
@ -1904,8 +1914,14 @@ mod tests {
|
||||
}
|
||||
|
||||
fn fake_with(one_pad: bool) -> (&'static Hub, Arc<Mutex<FakeHost>>) {
|
||||
fake_layout(one_pad, kbm::Config::default())
|
||||
}
|
||||
|
||||
/// A hub whose stand-in pad has this layout. No test sets the player's context (it is one for the process):
|
||||
/// the hubs here see it unknown, and `kbm`'s own tests hand theirs in.
|
||||
fn fake_layout(one_pad: bool, keys: kbm::Config) -> (&'static Hub, Arc<Mutex<FakeHost>>) {
|
||||
let host = Arc::new(Mutex::new(FakeHost::default()));
|
||||
let hub = Hub::new(Box::new(Fake(Arc::clone(&host))), one_pad);
|
||||
let hub = Hub::with(Box::new(Fake(Arc::clone(&host))), one_pad, keys);
|
||||
hub.poll();
|
||||
(hub, host)
|
||||
}
|
||||
@ -2187,6 +2203,17 @@ mod tests {
|
||||
assert_eq!(got[..4], keys[..]);
|
||||
release(r);
|
||||
|
||||
// The pad: GTA V's layout on foot, where V is no trigger.
|
||||
let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap();
|
||||
assert_eq!(pad(r), PadState { buttons: A, left_y: 1.0, right_x: 1.0, ..Default::default() });
|
||||
release(r);
|
||||
// A keyboard reading is no gamepad reading.
|
||||
assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND));
|
||||
// The layout of before (`LEONIDA_KBM=classic`): V is the right trigger.
|
||||
let classic = kbm::Config { layout: kbm::Layout::Classic, ..Default::default() };
|
||||
let (hub, host) = fake_layout(false, classic);
|
||||
host.lock().unwrap().keys = keys;
|
||||
hub.poll();
|
||||
let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap();
|
||||
assert_eq!(
|
||||
pad(r),
|
||||
@ -2199,8 +2226,51 @@ mod tests {
|
||||
}
|
||||
);
|
||||
release(r);
|
||||
// A keyboard reading is no gamepad reading.
|
||||
assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stand_in_pad_is_gta_vs_layout_in_both_pad_modes() {
|
||||
let newest = |hub: &Hub| match &hub.state().slots[FALLBACK].history.back().unwrap().value {
|
||||
Value::Pad(p) => *p,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
for one_pad in [false, true] {
|
||||
// On foot (nobody says what the player is in): W walks, the mouse shoots and aims, and the mouse look
|
||||
// stick is the camera beside them.
|
||||
let (hub, host) = fake_with(one_pad);
|
||||
host.lock().unwrap().keys =
|
||||
vec![key(b'W'), key(VK_MOUSE_LEFT), key(VK_MOUSE_RIGHT), key(0x20), key(0xA0)];
|
||||
hub.poll();
|
||||
assert_eq!(
|
||||
newest(hub),
|
||||
PadState {
|
||||
buttons: A | LEFT_STICK,
|
||||
left_y: 1.0,
|
||||
left_trigger: 1.0,
|
||||
right_trigger: 1.0,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
// The driving table (forced, as `LEONIDA_KBM_DRIVE=on` does): W is the accelerator, the left mouse
|
||||
// button shoots from the vehicle, Left Shift leans.
|
||||
let driving = kbm::Config { drive: kbm::Drive::On, settle: 0, ..Default::default() };
|
||||
let (hub, host) = fake_layout(one_pad, driving);
|
||||
host.lock().unwrap().keys = vec![key(b'W'), key(b'A'), key(VK_MOUSE_LEFT), key(0x20), key(0xA0)];
|
||||
hub.poll();
|
||||
assert_eq!(
|
||||
newest(hub),
|
||||
PadState {
|
||||
buttons: A | RIGHT_SHOULDER,
|
||||
left_x: -1.0,
|
||||
left_y: 1.0,
|
||||
right_trigger: 1.0,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
// The context is unknown here, and saying so again changes nothing.
|
||||
set_player_context(PlayerContext::Unknown);
|
||||
assert_eq!(player_context(), PlayerContext::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
879
d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs
Normal file
879
d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs
Normal file
@ -0,0 +1,879 @@
|
||||
//! Leonida: the keyboard and mouse as the title's pad, in Grand Theft Auto V's PC layout.
|
||||
//!
|
||||
//! The title reads an Xbox pad only, and a pad button means different things on foot and in a vehicle: the right
|
||||
//! trigger shoots on foot and accelerates in a car, the left trigger aims and brakes. One table of keys cannot be
|
||||
//! a PC layout then (W would have to be the left stick and the right trigger at once), so there are two, one on
|
||||
//! foot and one in a vehicle (`SHARED` with `FOOT_ONLY` or with `VEHICLE_ONLY`), and which one counts follows what
|
||||
//! the player is in ([`PlayerContext`]): told from outside with [`set_player_context`] (the runtime reads it from
|
||||
//! the title), and while nobody tells, the on-foot table with Caps Lock as the switch to the driving one by hand
|
||||
//! (only then: Caps Lock is GTA V's special ability, and a press out of habit must not change the keys).
|
||||
//!
|
||||
//! The keys are Grand Theft Auto V's defaults (its Settings > Key Bindings, as listed in BisectHosting's and
|
||||
//! StrategyWiki's control guides); the pad button of each action is the title's own default pad layout as far as
|
||||
//! it is known (`docs/gameinput.md`). A GTA V key whose action has no known pad button here is left out.
|
||||
//!
|
||||
//! The hand-over rule, when the table changes: a key whose pad input differs between the tables and that is down
|
||||
//! at that moment gives nothing until it has been let go and pressed again, and no such key gives anything for
|
||||
//! a short pause (`Config::settle`) after the change. So the left mouse button, held on foot to shoot, never
|
||||
//! becomes the accelerator, and W, held to accelerate, never becomes a shot. A key that is the same pad input in
|
||||
//! both tables (A and D, Space, F) carries over, as the button of a real pad would.
|
||||
//!
|
||||
//! `LEONIDA_KBM=classic` brings back the single table of before ([`super::fallback`]);
|
||||
//! `LEONIDA_KBM_DRIVE=on|off|auto` forces the driving table on or off (a test), `auto` being the default;
|
||||
//! `LEONIDA_KBM_SETTLE_MS` (400; 0..3000) is the pause after a change.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use super::{
|
||||
A, B, DOWN, KeyState, LEFT, LEFT_SHOULDER, LEFT_STICK, MENU, PadState, RIGHT, RIGHT_SHOULDER, RIGHT_STICK, UP,
|
||||
VIEW, VK_MOUSE_LEFT, VK_MOUSE_RIGHT, X, Y,
|
||||
};
|
||||
|
||||
const VK_BACK: u8 = 0x08;
|
||||
const VK_TAB: u8 = 0x09;
|
||||
const VK_RETURN: u8 = 0x0D;
|
||||
const VK_CAPITAL: u8 = 0x14;
|
||||
const VK_ESCAPE: u8 = 0x1B;
|
||||
const VK_SPACE: u8 = 0x20;
|
||||
const VK_LEFT: u8 = 0x25;
|
||||
const VK_UP: u8 = 0x26;
|
||||
const VK_RIGHT: u8 = 0x27;
|
||||
const VK_DOWN: u8 = 0x28;
|
||||
const VK_NUMPAD4: u8 = 0x64;
|
||||
const VK_NUMPAD5: u8 = 0x65;
|
||||
const VK_NUMPAD6: u8 = 0x66;
|
||||
const VK_NUMPAD8: u8 = 0x68;
|
||||
const VK_LSHIFT: u8 = 0xA0;
|
||||
const VK_LCONTROL: u8 = 0xA2;
|
||||
const VK_LMENU: u8 = 0xA4;
|
||||
const VK_RMENU: u8 = 0xA5;
|
||||
|
||||
/// The key that enters and leaves a vehicle (Y on the pad, in both tables).
|
||||
const VK_ENTER_EXIT: u8 = b'F';
|
||||
/// Keys that give nothing while an Alt key is down: with it they are shortcuts of Windows.
|
||||
const WITH_ALT: [u8; 4] = [VK_TAB, VK_RETURN, VK_SPACE, VK_ESCAPE];
|
||||
|
||||
/// What the player is in, as far as the runtime can tell.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PlayerContext {
|
||||
/// Nobody has told, or not for [`STALE`]: the on-foot table, and Caps Lock switches by hand.
|
||||
Unknown = 0,
|
||||
OnFoot = 1,
|
||||
InVehicle = 2,
|
||||
}
|
||||
|
||||
/// A context that was not set again for this long is unknown: 500 ms, in the clock of [`super::now`].
|
||||
const STALE: u64 = 500_000;
|
||||
/// And the stand-in pad only lets go of a known context once it has seen it unknown for this long (100 ms): after
|
||||
/// a stall of the whole process the poll may run before whoever sets the context does.
|
||||
const UNKNOWN_AFTER: u64 = 100_000;
|
||||
|
||||
/// The context and when it was set, in one word: no lock between the thread that sets it and the poll.
|
||||
pub(super) struct Shared(AtomicU64);
|
||||
|
||||
impl Shared {
|
||||
pub(super) const fn new() -> Shared {
|
||||
Shared(AtomicU64::new(0))
|
||||
}
|
||||
|
||||
/// `now`: microseconds ([`super::now`]).
|
||||
pub(super) fn set(&self, context: PlayerContext, now: u64) {
|
||||
self.0.store((now << 2) | context as u64, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(super) fn get(&self, now: u64) -> PlayerContext {
|
||||
let word = self.0.load(Ordering::Relaxed);
|
||||
if now.saturating_sub(word >> 2) > STALE {
|
||||
return PlayerContext::Unknown;
|
||||
}
|
||||
match word & 3 {
|
||||
1 => PlayerContext::OnFoot,
|
||||
2 => PlayerContext::InVehicle,
|
||||
_ => PlayerContext::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static CONTEXT: Shared = Shared::new();
|
||||
/// Whether the driving table is the one in use now (what the stand-in pad last decided).
|
||||
static DRIVING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Tells the stand-in pad what the player is in. It holds for half a second, so whoever knows says it again and
|
||||
/// again (once a frame); a context nobody renews becomes [`PlayerContext::Unknown`]. Lock-free; any thread.
|
||||
pub fn set_player_context(context: PlayerContext) {
|
||||
CONTEXT.set(context, super::now());
|
||||
}
|
||||
|
||||
/// The context last set, [`PlayerContext::Unknown`] once it is stale.
|
||||
pub fn player_context() -> PlayerContext {
|
||||
CONTEXT.get(super::now())
|
||||
}
|
||||
|
||||
/// Whether the keyboard and mouse are on the driving table now (W accelerates, the left mouse button shoots from
|
||||
/// the vehicle): the measured context, or Caps Lock, or `LEONIDA_KBM_DRIVE`. For whoever shows key prompts.
|
||||
pub fn driving_controls() -> bool {
|
||||
DRIVING.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether the stand-in pad follows the player's context at all: not with `LEONIDA_KBM=classic` nor with
|
||||
/// `LEONIDA_KBM_DRIVE=on|off`. Whoever would measure the context need not when this is false.
|
||||
pub fn player_context_wanted() -> bool {
|
||||
let config = Config::from_env();
|
||||
config.layout == Layout::GtaV && config.drive == Drive::Auto
|
||||
}
|
||||
|
||||
/// What a key does to the pad.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum To {
|
||||
Button(u32),
|
||||
LeftTrigger,
|
||||
RightTrigger,
|
||||
/// A push of the left stick: -1 or 1 (x right, y up).
|
||||
LeftX(f32),
|
||||
LeftY(f32),
|
||||
RightX(f32),
|
||||
RightY(f32),
|
||||
}
|
||||
|
||||
type Bind = (u8, To);
|
||||
|
||||
/// The keys that mean the same in both tables. GTA V's key, the pad input, and what it does in the title.
|
||||
const SHARED: &[Bind] = &[
|
||||
// Move, steer (the left stick's x in a vehicle).
|
||||
(b'A', To::LeftX(-1.0)),
|
||||
(b'D', To::LeftX(1.0)),
|
||||
// Jump and climb on foot, the handbrake in a vehicle: the title's A.
|
||||
(VK_SPACE, To::Button(A)),
|
||||
// Enter a vehicle, leave it: the title's Y.
|
||||
(VK_ENTER_EXIT, To::Button(Y)),
|
||||
// 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
|
||||
// known button here, so R stays the same pad button there.
|
||||
(b'R', To::Button(X)),
|
||||
// The weapon wheel: the title's loadout wheel (hold), holster (tap).
|
||||
(VK_TAB, To::Button(LEFT_SHOULDER)),
|
||||
// Look behind; zoom while aiming.
|
||||
(b'C', To::Button(RIGHT_STICK)),
|
||||
// Pause: Esc and P.
|
||||
(VK_ESCAPE, To::Button(MENU)),
|
||||
(b'P', To::Button(MENU)),
|
||||
// The map (the title's View button).
|
||||
(b'M', To::Button(VIEW)),
|
||||
// The phone (up) and its menus; down is the title's HUD and objective, left its radio menu, right its partner
|
||||
// menu.
|
||||
(VK_UP, To::Button(UP)),
|
||||
(VK_DOWN, To::Button(DOWN)),
|
||||
(VK_LEFT, To::Button(LEFT)),
|
||||
(VK_RIGHT, To::Button(RIGHT)),
|
||||
// Phone and menus: accept, back.
|
||||
(VK_RETURN, To::Button(A)),
|
||||
(VK_BACK, To::Button(B)),
|
||||
// GTA V's radar zoom and info: the same d-pad press as on its pad.
|
||||
(b'Z', To::Button(DOWN)),
|
||||
// (GTA V's character switch, Left Alt, would be the title's partner menu, d-pad right. It is left out: every
|
||||
// Alt+Tab would press it. The right arrow is that button.)
|
||||
// Not GTA V's: the pad-named keys of the layout before, where GTA V has nothing on them.
|
||||
(b'Y', To::Button(Y)),
|
||||
(b'I', To::RightY(1.0)),
|
||||
(b'K', To::RightY(-1.0)),
|
||||
(b'J', To::RightX(-1.0)),
|
||||
(b'L', To::RightX(1.0)),
|
||||
// (The mouse itself is the right stick: `MouseLook`.)
|
||||
];
|
||||
|
||||
/// On foot.
|
||||
const FOOT_ONLY: &[Bind] = &[
|
||||
(b'W', To::LeftY(1.0)),
|
||||
(b'S', To::LeftY(-1.0)),
|
||||
// Shoot, aim.
|
||||
(VK_MOUSE_LEFT, To::RightTrigger),
|
||||
(VK_MOUSE_RIGHT, To::LeftTrigger),
|
||||
// Sprint: the title runs on a click of the left stick.
|
||||
(VK_LSHIFT, To::Button(LEFT_STICK)),
|
||||
// GTA V's stealth: the title's crouch.
|
||||
(VK_LCONTROL, To::Button(B)),
|
||||
// Cover.
|
||||
(b'Q', To::Button(RIGHT_SHOULDER)),
|
||||
// GTA V's context action: the title interacts with Y.
|
||||
(b'E', To::Button(Y)),
|
||||
];
|
||||
|
||||
/// In a vehicle.
|
||||
const VEHICLE_ONLY: &[Bind] = &[
|
||||
// Accelerate; brake and reverse.
|
||||
(b'W', To::RightTrigger),
|
||||
(b'S', To::LeftTrigger),
|
||||
// Lean forward and back on a bike, the nose of an aircraft: the left stick's y. Num 4 and 6 roll.
|
||||
(VK_LSHIFT, To::LeftY(1.0)),
|
||||
(VK_NUMPAD8, To::LeftY(1.0)),
|
||||
(VK_LCONTROL, To::LeftY(-1.0)),
|
||||
(VK_NUMPAD5, To::LeftY(-1.0)),
|
||||
(VK_NUMPAD4, To::LeftX(-1.0)),
|
||||
(VK_NUMPAD6, To::LeftX(1.0)),
|
||||
// The horn.
|
||||
(b'E', To::Button(LEFT_STICK)),
|
||||
// Shoot from the vehicle. (Aiming from it, GTA V's right mouse button, has no known button here.)
|
||||
(VK_MOUSE_LEFT, To::Button(RIGHT_SHOULDER)),
|
||||
// Duck; the headlights.
|
||||
(b'X', To::Button(B)),
|
||||
(b'H', To::Button(B)),
|
||||
// GTA V's radio wheel: the title's radio menu.
|
||||
(b'Q', To::Button(LEFT)),
|
||||
];
|
||||
|
||||
/// The two tables: what is shared, then what is the context's own.
|
||||
fn table(driving: bool) -> impl Iterator<Item = &'static Bind> {
|
||||
SHARED.iter().chain(if driving { VEHICLE_ONLY } else { FOOT_ONLY })
|
||||
}
|
||||
|
||||
/// What `key` does in a table, in the table's order.
|
||||
fn outputs(driving: bool, key: u8) -> impl Iterator<Item = To> {
|
||||
table(driving).filter(move |(k, _)| *k == key).map(|(_, to)| *to)
|
||||
}
|
||||
|
||||
/// Whether `key` is another pad input in a vehicle than on foot: the keys the hand-over rule is about.
|
||||
fn changes(key: u8) -> bool {
|
||||
!outputs(false, key).eq(outputs(true, key))
|
||||
}
|
||||
|
||||
/// The pad of a table, with the keys `on` says are down.
|
||||
fn pad_of(driving: bool, on: impl Fn(u8) -> bool) -> PadState {
|
||||
let mut pad = PadState::default();
|
||||
for &(key, to) in table(driving) {
|
||||
if !on(key) {
|
||||
continue;
|
||||
}
|
||||
match to {
|
||||
To::Button(bit) => pad.buttons |= bit,
|
||||
To::LeftTrigger => pad.left_trigger = 1.0,
|
||||
To::RightTrigger => pad.right_trigger = 1.0,
|
||||
To::LeftX(push) => pad.left_x += push,
|
||||
To::LeftY(push) => pad.left_y += push,
|
||||
To::RightX(push) => pad.right_x += push,
|
||||
To::RightY(push) => pad.right_y += push,
|
||||
}
|
||||
}
|
||||
for axis in [&mut pad.left_x, &mut pad.left_y, &mut pad.right_x, &mut pad.right_y] {
|
||||
*axis = axis.clamp(-1.0, 1.0);
|
||||
}
|
||||
pad
|
||||
}
|
||||
|
||||
/// The button a scripted key (`LEONIDA_KEYS`) presses on a real pad: the on-foot table's, or with
|
||||
/// `LEONIDA_KBM=classic` the old table's.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
pub(super) fn scripted_button(key: u8) -> Option<u32> {
|
||||
if Config::from_env().layout == Layout::Classic {
|
||||
return super::FALLBACK_BUTTONS.iter().find(|(k, _)| *k == key).map(|(_, bit)| *bit);
|
||||
}
|
||||
outputs(false, key).find_map(|to| match to {
|
||||
To::Button(bit) => Some(bit),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Layout {
|
||||
GtaV,
|
||||
Classic,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Drive {
|
||||
Auto,
|
||||
On,
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Config {
|
||||
pub(super) layout: Layout,
|
||||
pub(super) drive: Drive,
|
||||
/// Microseconds after a change of table in which no key that changes with it counts.
|
||||
pub(super) settle: u64,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Config {
|
||||
Config { layout: Layout::GtaV, drive: Drive::Auto, settle: 400_000 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// From the values of `LEONIDA_KBM`, `LEONIDA_KBM_DRIVE` and `LEONIDA_KBM_SETTLE_MS`; what does not read is
|
||||
/// the default.
|
||||
pub(super) fn parse(kbm: Option<&str>, drive: Option<&str>, settle_ms: Option<&str>) -> Config {
|
||||
let default = Config::default();
|
||||
let word = |v: Option<&str>| v.map(|v| v.trim().to_ascii_lowercase());
|
||||
Config {
|
||||
layout: match word(kbm).as_deref() {
|
||||
Some("classic") => Layout::Classic,
|
||||
_ => Layout::GtaV,
|
||||
},
|
||||
drive: match word(drive).as_deref() {
|
||||
Some("on" | "1") => Drive::On,
|
||||
Some("off" | "0") => Drive::Off,
|
||||
_ => Drive::Auto,
|
||||
},
|
||||
settle: settle_ms
|
||||
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||
.map_or(default.settle, |ms| ms.min(3000) * 1000),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn from_env() -> Config {
|
||||
static CONFIG: std::sync::LazyLock<Config> = std::sync::LazyLock::new(|| {
|
||||
let var = |name: &str| std::env::var(name).ok();
|
||||
Config::parse(
|
||||
var("LEONIDA_KBM").as_deref(),
|
||||
var("LEONIDA_KBM_DRIVE").as_deref(),
|
||||
var("LEONIDA_KBM_SETTLE_MS").as_deref(),
|
||||
)
|
||||
});
|
||||
*CONFIG
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of virtual keys.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Keys([u64; 4]);
|
||||
|
||||
impl Keys {
|
||||
fn of(keys: &[KeyState]) -> Keys {
|
||||
let mut set = Keys::default();
|
||||
for key in keys {
|
||||
set.0[usize::from(key.virtual_key >> 6)] |= 1 << (key.virtual_key & 63);
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
fn has(&self, key: u8) -> bool {
|
||||
self.0[usize::from(key >> 6)] & (1 << (key & 63)) != 0
|
||||
}
|
||||
|
||||
fn both(&self, other: &Keys) -> Keys {
|
||||
Keys(std::array::from_fn(|i| self.0[i] & other.0[i]))
|
||||
}
|
||||
|
||||
fn either(&self, other: &Keys) -> Keys {
|
||||
Keys(std::array::from_fn(|i| self.0[i] | other.0[i]))
|
||||
}
|
||||
|
||||
/// Those of the set `keep` says yes to.
|
||||
fn only(&self, keep: impl Fn(u8) -> bool) -> Keys {
|
||||
let mut set = Keys::default();
|
||||
for key in 0..=u8::MAX {
|
||||
if self.has(key) && keep(key) {
|
||||
set.0[usize::from(key >> 6)] |= 1 << (key & 63);
|
||||
}
|
||||
}
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
/// The stand-in pad's keyboard and mouse half: which table counts, and the hand-over between them.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Kbm {
|
||||
config: Config,
|
||||
/// The table in use.
|
||||
driving: bool,
|
||||
/// Caps Lock's say while no context is measured: the driving table, until Caps Lock again or F (which leaves
|
||||
/// the vehicle).
|
||||
by_hand: bool,
|
||||
/// The measured context as it counts (see [`UNKNOWN_AFTER`]).
|
||||
measured: PlayerContext,
|
||||
unknown_since: Option<u64>,
|
||||
/// The keys down at the last poll.
|
||||
down: Keys,
|
||||
/// Keys that were down when the table changed: nothing from them until they are let go.
|
||||
latched: Keys,
|
||||
/// Until then (microseconds) no key that changes with the table counts.
|
||||
settle_until: u64,
|
||||
}
|
||||
|
||||
impl Kbm {
|
||||
pub(super) fn new(config: Config) -> Kbm {
|
||||
Kbm {
|
||||
config,
|
||||
driving: false,
|
||||
by_hand: false,
|
||||
measured: PlayerContext::Unknown,
|
||||
unknown_since: None,
|
||||
down: Keys::default(),
|
||||
latched: Keys::default(),
|
||||
settle_until: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pad the keys held make, with the context measured now (`now`: microseconds).
|
||||
pub(super) fn pad(&mut self, keys: &[KeyState], measured: PlayerContext, now: u64) -> PadState {
|
||||
if self.config.layout == Layout::Classic {
|
||||
return super::fallback(keys);
|
||||
}
|
||||
let (mut down, was) = (Keys::of(keys), self.down);
|
||||
// With Alt down these are Windows' own (Alt+Tab, Alt+Enter, Alt+Space, Alt+Esc), not the game's.
|
||||
if down.has(VK_LMENU) || down.has(VK_RMENU) {
|
||||
down = down.only(|key| !WITH_ALT.contains(&key));
|
||||
}
|
||||
let pressed = |key: u8| down.has(key) && !was.has(key);
|
||||
let (wanted, why) = match self.config.drive {
|
||||
Drive::On => (true, "LEONIDA_KBM_DRIVE=on"),
|
||||
Drive::Off => (false, "LEONIDA_KBM_DRIVE=off"),
|
||||
Drive::Auto => {
|
||||
let measured = self.settled(measured, now);
|
||||
if measured != self.measured {
|
||||
// What is measured counts; driving by hand is for when nothing is, and starts anew then.
|
||||
self.measured = measured;
|
||||
self.by_hand = false;
|
||||
}
|
||||
match self.measured {
|
||||
PlayerContext::InVehicle => (true, "the player is in a vehicle"),
|
||||
PlayerContext::OnFoot => (false, "the player is on foot"),
|
||||
PlayerContext::Unknown if pressed(VK_CAPITAL) => {
|
||||
self.by_hand = !self.by_hand;
|
||||
(self.by_hand, "Caps Lock")
|
||||
}
|
||||
PlayerContext::Unknown if pressed(VK_ENTER_EXIT) && self.by_hand => {
|
||||
// Driving by hand, and the player leaves the vehicle: W must not stay the right trigger.
|
||||
self.by_hand = false;
|
||||
(false, "F leaves the vehicle; Caps Lock is the driving keys")
|
||||
}
|
||||
PlayerContext::Unknown => (self.by_hand, "what the player is in is not known"),
|
||||
}
|
||||
}
|
||||
};
|
||||
if wanted != self.driving {
|
||||
self.driving = wanted;
|
||||
DRIVING.store(wanted, Ordering::Relaxed);
|
||||
self.latched = self.latched.either(&down.only(changes));
|
||||
self.settle_until = now + self.config.settle;
|
||||
tracing::info!(
|
||||
"keyboard and mouse: {} controls ({why})",
|
||||
if wanted { "driving" } else { "on-foot" }
|
||||
);
|
||||
}
|
||||
self.latched = self.latched.both(&down);
|
||||
self.down = down;
|
||||
let settling = now < self.settle_until;
|
||||
let latched = self.latched;
|
||||
pad_of(self.driving, |key| down.has(key) && !latched.has(key) && !(settling && changes(key)))
|
||||
}
|
||||
|
||||
/// The measured context, an unknown one only once it has been unknown for [`UNKNOWN_AFTER`].
|
||||
fn settled(&mut self, measured: PlayerContext, now: u64) -> PlayerContext {
|
||||
if measured != PlayerContext::Unknown || self.measured == PlayerContext::Unknown {
|
||||
self.unknown_since = None;
|
||||
return measured;
|
||||
}
|
||||
let since = *self.unknown_since.get_or_insert(now);
|
||||
if now.saturating_sub(since) < UNKNOWN_AFTER { self.measured } else { measured }
|
||||
}
|
||||
}
|
||||
|
||||
/// The context for the poll at `now`.
|
||||
pub(super) fn measured(now: u64) -> PlayerContext {
|
||||
CONTEXT.get(now)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const MS: u64 = 1000;
|
||||
const FOOT: PlayerContext = PlayerContext::OnFoot;
|
||||
const CAR: PlayerContext = PlayerContext::InVehicle;
|
||||
const UNKNOWN: PlayerContext = PlayerContext::Unknown;
|
||||
|
||||
fn keys(held: &[u8]) -> Vec<KeyState> {
|
||||
held.iter().map(|&vk| KeyState { virtual_key: vk, ..Default::default() }).collect()
|
||||
}
|
||||
|
||||
fn foot(held: &[u8]) -> PadState {
|
||||
pad_of(false, |key| held.contains(&key))
|
||||
}
|
||||
|
||||
fn car(held: &[u8]) -> PadState {
|
||||
pad_of(true, |key| held.contains(&key))
|
||||
}
|
||||
|
||||
fn button(bit: u32) -> PadState {
|
||||
PadState { buttons: bit, ..Default::default() }
|
||||
}
|
||||
|
||||
fn kbm() -> Kbm {
|
||||
Kbm::new(Config::default())
|
||||
}
|
||||
|
||||
/// Whether the pad pulls a trigger or presses the button that shoots from a vehicle.
|
||||
fn fires_or_drives(pad: &PadState) -> bool {
|
||||
pad.left_trigger != 0.0 || pad.right_trigger != 0.0 || pad.buttons & RIGHT_SHOULDER != 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn on_foot_is_gta_vs_layout() {
|
||||
// Movement is W A S D, and nothing else of them.
|
||||
assert_eq!(foot(b"W"), PadState { left_y: 1.0, ..Default::default() });
|
||||
assert_eq!(foot(b"S"), PadState { left_y: -1.0, ..Default::default() });
|
||||
assert_eq!(foot(b"A"), PadState { left_x: -1.0, ..Default::default() });
|
||||
assert_eq!(foot(b"D"), PadState { left_x: 1.0, ..Default::default() });
|
||||
assert_eq!(foot(b"WS"), PadState::default());
|
||||
// Shooting and aiming are the mouse, and nothing else of it.
|
||||
assert_eq!(foot(&[VK_MOUSE_LEFT]), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
assert_eq!(foot(&[VK_MOUSE_RIGHT]), PadState { left_trigger: 1.0, ..Default::default() });
|
||||
for (key, bit) in [
|
||||
(VK_SPACE, A),
|
||||
(VK_LSHIFT, LEFT_STICK),
|
||||
(VK_LCONTROL, B),
|
||||
(b'Q', RIGHT_SHOULDER),
|
||||
(b'R', X),
|
||||
(b'F', Y),
|
||||
(b'E', Y),
|
||||
(VK_TAB, LEFT_SHOULDER),
|
||||
(b'C', RIGHT_STICK),
|
||||
(b'M', VIEW),
|
||||
(VK_ESCAPE, MENU),
|
||||
(b'P', MENU),
|
||||
(VK_UP, UP),
|
||||
(VK_DOWN, DOWN),
|
||||
(VK_LEFT, LEFT),
|
||||
(VK_RIGHT, RIGHT),
|
||||
(VK_RETURN, A),
|
||||
(VK_BACK, B),
|
||||
(b'Z', DOWN),
|
||||
(b'Y', Y),
|
||||
] {
|
||||
assert_eq!(foot(&[key]), button(bit), "key {key:#x}");
|
||||
}
|
||||
assert_eq!(foot(b"IL"), PadState { right_x: 1.0, right_y: 1.0, ..Default::default() });
|
||||
// GTA V keys whose action has no known pad button: nothing. So are the old layout's trigger keys.
|
||||
for key in *b"VGXHOTBN1234567890" {
|
||||
assert_eq!(foot(&[key]), PadState::default(), "key {}", key as char);
|
||||
}
|
||||
assert_eq!(foot(&[VK_CAPITAL, VK_NUMPAD8, VK_NUMPAD5, VK_LMENU, VK_RMENU]), PadState::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_tab_presses_nothing() {
|
||||
let mut k = kbm();
|
||||
// Alt, then Tab (or Enter, Space, Esc) with it: Windows' shortcuts, no button of the pad.
|
||||
assert_eq!(k.pad(&keys(&[VK_LMENU]), FOOT, 0), PadState::default());
|
||||
for key in [VK_TAB, VK_RETURN, VK_SPACE, VK_ESCAPE] {
|
||||
assert_eq!(k.pad(&keys(&[VK_LMENU, key]), FOOT, 8 * MS), PadState::default(), "key {key:#x}");
|
||||
assert_eq!(k.pad(&keys(&[VK_RMENU, key]), FOOT, 16 * MS), PadState::default(), "key {key:#x}");
|
||||
}
|
||||
// Other keys are not held back, and without Alt Tab is the weapon wheel.
|
||||
assert_eq!(k.pad(&keys(&[VK_LMENU, b'W']), FOOT, 24 * MS), PadState { left_y: 1.0, ..Default::default() });
|
||||
assert_eq!(k.pad(&keys(&[VK_TAB]), FOOT, 32 * MS), button(LEFT_SHOULDER));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_a_vehicle_w_and_s_are_the_triggers_and_the_mouse_shoots() {
|
||||
// W accelerates, S brakes: the triggers, fully, and not the stick.
|
||||
assert_eq!(car(b"W"), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
assert_eq!(car(b"S"), PadState { left_trigger: 1.0, ..Default::default() });
|
||||
assert_eq!(car(b"WS"), PadState { left_trigger: 1.0, right_trigger: 1.0, ..Default::default() });
|
||||
// A and D steer.
|
||||
assert_eq!(car(b"A"), PadState { left_x: -1.0, ..Default::default() });
|
||||
assert_eq!(car(b"D"), PadState { left_x: 1.0, ..Default::default() });
|
||||
// Bikes and aircraft: Shift and Ctrl (and the number pad) are the stick's other axis.
|
||||
assert_eq!(car(&[VK_LSHIFT]), PadState { left_y: 1.0, ..Default::default() });
|
||||
assert_eq!(car(&[VK_LCONTROL]), PadState { left_y: -1.0, ..Default::default() });
|
||||
assert_eq!(car(&[VK_LSHIFT, VK_NUMPAD8]), PadState { left_y: 1.0, ..Default::default() });
|
||||
assert_eq!(car(&[VK_NUMPAD5, VK_NUMPAD6]), PadState { left_x: 1.0, left_y: -1.0, ..Default::default() });
|
||||
assert_eq!(car(&[VK_NUMPAD4]), PadState { left_x: -1.0, ..Default::default() });
|
||||
// The left mouse button shoots from the vehicle, which is a button and no trigger. The right one has no
|
||||
// known button.
|
||||
assert_eq!(car(&[VK_MOUSE_LEFT]), button(RIGHT_SHOULDER));
|
||||
assert_eq!(car(&[VK_MOUSE_RIGHT]), PadState::default());
|
||||
for (key, bit) in [
|
||||
(VK_SPACE, A),
|
||||
(b'F', Y),
|
||||
(b'E', LEFT_STICK),
|
||||
(b'X', B),
|
||||
(b'H', B),
|
||||
(b'Q', LEFT),
|
||||
(b'R', X),
|
||||
(b'C', RIGHT_STICK),
|
||||
(VK_TAB, LEFT_SHOULDER),
|
||||
(b'M', VIEW),
|
||||
(VK_ESCAPE, MENU),
|
||||
(VK_UP, UP),
|
||||
(VK_RETURN, A),
|
||||
(VK_BACK, B),
|
||||
] {
|
||||
assert_eq!(car(&[key]), button(bit), "key {key:#x}");
|
||||
}
|
||||
for key in *b"VGOTBN1234567890" {
|
||||
assert_eq!(car(&[key]), PadState::default(), "key {}", key as char);
|
||||
}
|
||||
}
|
||||
|
||||
/// The two rules the layout stands on, read off the tables: no table makes a mouse button the accelerator or
|
||||
/// the brake, and no table makes W or S a shot.
|
||||
#[test]
|
||||
fn the_mouse_never_drives_and_w_never_shoots() {
|
||||
for mouse in [VK_MOUSE_LEFT, VK_MOUSE_RIGHT] {
|
||||
assert!(outputs(true, mouse).all(|to| !matches!(to, To::LeftTrigger | To::RightTrigger)));
|
||||
assert!(outputs(false, mouse).all(|to| matches!(to, To::LeftTrigger | To::RightTrigger)));
|
||||
}
|
||||
for key in *b"WASD" {
|
||||
assert!(outputs(false, key).all(|to| matches!(to, To::LeftX(_) | To::LeftY(_))), "{}", key as char);
|
||||
assert!(outputs(true, key).all(|to| to != To::Button(RIGHT_SHOULDER)), "{}", key as char);
|
||||
}
|
||||
// What changes with the table, and what does not.
|
||||
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'] {
|
||||
assert!(changes(key), "key {key:#x}");
|
||||
}
|
||||
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'] {
|
||||
assert!(!changes(key), "key {key:#x}");
|
||||
}
|
||||
// No key is bound twice to the same thing, and the tables are not empty.
|
||||
for driving in [false, true] {
|
||||
let all: Vec<&Bind> = table(driving).collect();
|
||||
assert!(all.len() > 25);
|
||||
for (i, a) in all.iter().enumerate() {
|
||||
assert!(all[i + 1..].iter().all(|b| a != b), "{a:?} twice");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entering_a_vehicle_with_keys_held_neither_shoots_nor_accelerates() {
|
||||
let mut k = kbm();
|
||||
// On foot: walking forward and shooting.
|
||||
let held = keys(&[b'W', VK_MOUSE_LEFT, b'A']);
|
||||
let pad = k.pad(&held, FOOT, 0);
|
||||
assert_eq!(pad, PadState { left_x: -1.0, left_y: 1.0, right_trigger: 1.0, ..Default::default() });
|
||||
// The player is in a vehicle now, the keys still down: neither W nor the mouse button gives anything,
|
||||
// however long they stay down. A (the same stick push in both) carries over.
|
||||
for ms in [8, 100, 399, 400, 1000, 60_000] {
|
||||
let pad = k.pad(&held, CAR, ms * MS);
|
||||
assert_eq!(pad, PadState { left_x: -1.0, ..Default::default() }, "{ms} ms");
|
||||
}
|
||||
// The mouse button let go and pressed again: it shoots from the vehicle, and is still no accelerator.
|
||||
k.pad(&keys(&[b'W', b'A']), CAR, 60_008 * MS);
|
||||
let pad = k.pad(&held, CAR, 60_016 * MS);
|
||||
assert_eq!(pad, PadState { buttons: RIGHT_SHOULDER, left_x: -1.0, ..Default::default() });
|
||||
// W let go and pressed again: it accelerates.
|
||||
k.pad(&keys(&[]), CAR, 60_024 * MS);
|
||||
let pad = k.pad(&keys(b"W"), CAR, 60_032 * MS);
|
||||
assert_eq!(pad, PadState { right_trigger: 1.0, ..Default::default() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_a_vehicle_with_keys_held_neither_shoots_nor_walks() {
|
||||
let mut k = kbm();
|
||||
k.pad(&keys(&[]), CAR, 0);
|
||||
// Accelerating, steering, the handbrake on.
|
||||
let held = keys(&[b'W', b'D', VK_SPACE]);
|
||||
let pad = k.pad(&held, CAR, 1000 * MS);
|
||||
assert_eq!(pad, PadState { buttons: A, left_x: 1.0, right_trigger: 1.0, ..Default::default() });
|
||||
// On foot now with W still down: no trigger (it would be a shot), and no walking until W is pressed
|
||||
// again. D and Space are the same pad input in both.
|
||||
for ms in [1008, 1200, 1400, 5000] {
|
||||
let pad = k.pad(&held, FOOT, ms * MS);
|
||||
assert_eq!(pad, PadState { buttons: A, left_x: 1.0, ..Default::default() }, "{ms} ms");
|
||||
}
|
||||
k.pad(&keys(&[]), FOOT, 5008 * MS);
|
||||
assert_eq!(k.pad(&keys(b"W"), FOOT, 5016 * MS), PadState { left_y: 1.0, ..Default::default() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_pressed_right_after_the_change_waits_for_the_pause() {
|
||||
let mut k = kbm();
|
||||
k.pad(&keys(&[]), FOOT, 0);
|
||||
k.pad(&keys(&[]), CAR, 1000 * MS);
|
||||
// Pressed 50 ms after the change: nothing until 400 ms after it, then what the new table says.
|
||||
for ms in [1050, 1200, 1399] {
|
||||
assert_eq!(k.pad(&keys(&[b'W', VK_MOUSE_LEFT]), CAR, ms * MS), PadState::default(), "{ms} ms");
|
||||
}
|
||||
let pad = k.pad(&keys(&[b'W', VK_MOUSE_LEFT]), CAR, 1400 * MS);
|
||||
assert_eq!(pad, PadState { buttons: RIGHT_SHOULDER, right_trigger: 1.0, ..Default::default() });
|
||||
// A key that is the same in both tables does not wait.
|
||||
let mut k = kbm();
|
||||
k.pad(&keys(&[]), CAR, 0);
|
||||
k.pad(&keys(&[]), FOOT, 1000 * MS);
|
||||
assert_eq!(k.pad(&keys(b"F"), FOOT, 1008 * MS), button(Y));
|
||||
assert_eq!(k.pad(&keys(&[b'F', VK_MOUSE_LEFT]), FOOT, 1100 * MS), button(Y));
|
||||
// With no pause set, a fresh press counts at once; a held key still does not.
|
||||
let mut k = Kbm::new(Config { settle: 0, ..Config::default() });
|
||||
k.pad(&keys(b"S"), FOOT, 0);
|
||||
assert_eq!(k.pad(&keys(b"S"), CAR, 8 * MS), PadState::default());
|
||||
assert_eq!(k.pad(&keys(b"SW"), CAR, 16 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
}
|
||||
|
||||
/// Whatever is held when the table changes, in either direction: until a key is pressed anew, nothing pulls
|
||||
/// a trigger and nothing shoots from the vehicle.
|
||||
#[test]
|
||||
fn no_set_of_held_keys_fires_or_drives_across_a_change() {
|
||||
let changing = [b'W', b'S', VK_MOUSE_LEFT, VK_MOUSE_RIGHT, VK_LSHIFT, VK_LCONTROL, b'Q', b'E', b'X', b'H'];
|
||||
for (from, to) in [(FOOT, CAR), (CAR, FOOT), (UNKNOWN, CAR), (CAR, UNKNOWN)] {
|
||||
for mask in 0u32..1 << changing.len() {
|
||||
let held: Vec<u8> =
|
||||
changing.iter().enumerate().filter(|(i, _)| mask & (1 << i) != 0).map(|(_, k)| *k).collect();
|
||||
let held = keys(&held);
|
||||
let mut k = kbm();
|
||||
k.pad(&keys(&[]), from, 0);
|
||||
k.pad(&held, from, 1000 * MS);
|
||||
for ms in [1008, 1100, 1399, 1400, 1500, 9000] {
|
||||
let pad = k.pad(&held, to, ms * MS);
|
||||
// (An unknown context counts 100 ms late; until then the pad is the old table's.)
|
||||
if to == UNKNOWN && ms < 1108 {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(pad, PadState::default(), "{from:?} to {to:?}, keys {mask:#b}, {ms} ms");
|
||||
assert!(!fires_or_drives(&pad));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caps_lock_switches_by_hand_while_the_context_is_unknown() {
|
||||
let mut k = kbm();
|
||||
// Unknown: on foot.
|
||||
assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 0), PadState { left_y: 1.0, ..Default::default() });
|
||||
k.pad(&keys(&[]), UNKNOWN, 8 * MS);
|
||||
// Caps Lock: driving, once per press however long it is held.
|
||||
for ms in [16, 24, 500, 2000] {
|
||||
k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, ms * MS);
|
||||
assert!(k.driving, "{ms} ms");
|
||||
}
|
||||
k.pad(&keys(&[]), UNKNOWN, 2008 * MS);
|
||||
assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 2016 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
// Caps Lock again, W still down: on foot, and W gives nothing until pressed again.
|
||||
assert_eq!(k.pad(&keys(&[b'W', VK_CAPITAL]), UNKNOWN, 3000 * MS), PadState::default());
|
||||
assert!(!k.driving);
|
||||
k.pad(&keys(&[]), UNKNOWN, 3008 * MS);
|
||||
// Driving by hand ends when F leaves the vehicle: W must not stay the trigger on foot.
|
||||
k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 4000 * MS);
|
||||
k.pad(&keys(&[]), UNKNOWN, 4008 * MS);
|
||||
assert!(k.driving);
|
||||
assert_eq!(k.pad(&keys(b"WF"), UNKNOWN, 5000 * MS), button(Y));
|
||||
assert!(!k.driving);
|
||||
// On foot F is just F.
|
||||
k.pad(&keys(&[]), UNKNOWN, 5008 * MS);
|
||||
k.pad(&keys(b"F"), UNKNOWN, 6000 * MS);
|
||||
assert!(!k.driving);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_measured_context_wins_and_caps_lock_is_no_switch_then() {
|
||||
let mut k = kbm();
|
||||
// Driving by hand, then the runtime starts to tell: its word counts.
|
||||
k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 0);
|
||||
k.pad(&keys(&[]), UNKNOWN, 8 * MS);
|
||||
assert!(k.driving);
|
||||
k.pad(&keys(&[]), FOOT, 16 * MS);
|
||||
assert!(!k.driving);
|
||||
// Caps Lock (GTA V's special ability, pressed out of habit) does nothing on foot: W stays the stick.
|
||||
k.pad(&keys(&[VK_CAPITAL]), FOOT, 500 * MS);
|
||||
assert!(!k.driving);
|
||||
assert_eq!(k.pad(&keys(&[VK_CAPITAL, b'W']), FOOT, 600 * MS), PadState { left_y: 1.0, ..Default::default() });
|
||||
k.pad(&keys(&[]), FOOT, 700 * MS);
|
||||
// Nor in a vehicle, and F is just the Y button there.
|
||||
k.pad(&keys(&[]), CAR, 1000 * MS);
|
||||
assert!(k.driving);
|
||||
k.pad(&keys(&[VK_CAPITAL]), CAR, 2000 * MS);
|
||||
k.pad(&keys(b"F"), CAR, 2100 * MS);
|
||||
assert!(k.driving);
|
||||
k.pad(&keys(&[]), CAR, 2200 * MS);
|
||||
// The context is lost (nobody tells any more): on foot, not the driving by hand of before.
|
||||
k.pad(&keys(&[]), UNKNOWN, 3000 * MS);
|
||||
k.pad(&keys(&[]), UNKNOWN, 3100 * MS);
|
||||
assert!(!k.driving);
|
||||
// And Caps Lock is the switch again.
|
||||
k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 4000 * MS);
|
||||
assert!(k.driving);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_nobody_renews_is_unknown() {
|
||||
let shared = Shared::new();
|
||||
assert_eq!(shared.get(0), UNKNOWN);
|
||||
assert_eq!(shared.get(10_000 * MS), UNKNOWN);
|
||||
shared.set(CAR, 1000 * MS);
|
||||
assert_eq!(shared.get(1000 * MS), CAR);
|
||||
assert_eq!(shared.get(1500 * MS), CAR);
|
||||
assert_eq!(shared.get(1501 * MS), UNKNOWN);
|
||||
shared.set(FOOT, 1600 * MS);
|
||||
assert_eq!(shared.get(1700 * MS), FOOT);
|
||||
shared.set(UNKNOWN, 1800 * MS);
|
||||
assert_eq!(shared.get(1800 * MS), UNKNOWN);
|
||||
// A reader whose clock is behind the writer's does not go wrong.
|
||||
shared.set(CAR, 5000 * MS);
|
||||
assert_eq!(shared.get(4000 * MS), CAR);
|
||||
// The stand-in pad lets go of a known context only after 100 ms of unknown, and then as on any change.
|
||||
let mut k = kbm();
|
||||
k.pad(&keys(&[]), CAR, 0);
|
||||
assert_eq!(k.pad(&keys(b"W"), CAR, 1000 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 1010 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 1100 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
// Known again in time: nothing happened.
|
||||
assert_eq!(k.pad(&keys(b"W"), CAR, 1105 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 2000 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
assert_eq!(k.pad(&keys(b"W"), UNKNOWN, 2100 * MS), PadState::default());
|
||||
assert!(!k.driving);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_switches_read() {
|
||||
assert_eq!(Config::parse(None, None, None), Config::default());
|
||||
assert_eq!(Config::default().layout, Layout::GtaV);
|
||||
assert_eq!(Config::default().drive, Drive::Auto);
|
||||
assert_eq!(Config::parse(Some("classic"), None, None).layout, Layout::Classic);
|
||||
assert_eq!(Config::parse(Some(" Classic "), None, None).layout, Layout::Classic);
|
||||
assert_eq!(Config::parse(Some("gta5"), None, None).layout, Layout::GtaV);
|
||||
assert_eq!(Config::parse(None, Some("on"), None).drive, Drive::On);
|
||||
assert_eq!(Config::parse(None, Some("OFF"), None).drive, Drive::Off);
|
||||
assert_eq!(Config::parse(None, Some("auto"), None).drive, Drive::Auto);
|
||||
assert_eq!(Config::parse(None, Some("what"), None).drive, Drive::Auto);
|
||||
assert_eq!(Config::parse(None, None, Some("0")).settle, 0);
|
||||
assert_eq!(Config::parse(None, None, Some("250")).settle, 250 * MS);
|
||||
assert_eq!(Config::parse(None, None, Some("99999")).settle, 3000 * MS);
|
||||
assert_eq!(Config::parse(None, None, Some("soon")).settle, 400 * MS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_forced_tables_and_the_classic_one() {
|
||||
// Forced on: driving whatever is measured, and Caps Lock is no switch.
|
||||
let mut k = Kbm::new(Config { drive: Drive::On, ..Config::default() });
|
||||
k.pad(&keys(&[]), FOOT, 0);
|
||||
assert_eq!(k.pad(&keys(b"W"), FOOT, 1000 * MS), PadState { right_trigger: 1.0, ..Default::default() });
|
||||
k.pad(&keys(&[VK_CAPITAL]), UNKNOWN, 2000 * MS);
|
||||
assert!(k.driving);
|
||||
// Forced off.
|
||||
let mut k = Kbm::new(Config { drive: Drive::Off, ..Config::default() });
|
||||
assert_eq!(k.pad(&keys(b"W"), CAR, 0), PadState { left_y: 1.0, ..Default::default() });
|
||||
k.pad(&keys(&[b'W', VK_CAPITAL]), CAR, 1000 * MS);
|
||||
assert!(!k.driving);
|
||||
// Classic: the table of before, whatever the context.
|
||||
let mut k = Kbm::new(Config { layout: Layout::Classic, ..Config::default() });
|
||||
for context in [UNKNOWN, FOOT, CAR] {
|
||||
let held = keys(&[b'W', b'V', b'Q', VK_MOUSE_RIGHT, VK_CAPITAL]);
|
||||
assert_eq!(k.pad(&held, context, 0), super::super::fallback(&held));
|
||||
assert_eq!(
|
||||
k.pad(&held, context, 0),
|
||||
PadState {
|
||||
buttons: LEFT_SHOULDER,
|
||||
left_y: 1.0,
|
||||
left_trigger: 1.0,
|
||||
right_trigger: 1.0,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripted_keys_press_the_on_foot_buttons() {
|
||||
assert_eq!(scripted_button(VK_RETURN), Some(A));
|
||||
assert_eq!(scripted_button(VK_ESCAPE), Some(MENU));
|
||||
assert_eq!(scripted_button(VK_BACK), Some(B));
|
||||
assert_eq!(scripted_button(VK_UP), Some(UP));
|
||||
assert_eq!(scripted_button(b'F'), Some(Y));
|
||||
// A stick or a trigger is no button; an unbound key is none.
|
||||
assert_eq!(scripted_button(b'W'), None);
|
||||
assert_eq!(scripted_button(VK_MOUSE_LEFT), None);
|
||||
assert_eq!(scripted_button(b'V'), None);
|
||||
}
|
||||
}
|
||||
@ -64,10 +64,15 @@ pub enum Site {
|
||||
WeatherForced,
|
||||
/// The global that points at the weather types ([`WEATHER_TYPE_STRIDE`] bytes each, the name's hash first).
|
||||
WeatherTypes,
|
||||
/// The global that holds the vehicle the player is in, null on foot. Read from the code, not yet seen in
|
||||
/// the running title: its one setter is called with a vehicle from a large function, with null where a ped
|
||||
/// that is the player is taken out of a vehicle, and with what the title's own "the vehicle this ped is in"
|
||||
/// gives when the player's ped is set (`docs/gameinput.md`).
|
||||
PlayerVehicle,
|
||||
}
|
||||
|
||||
/// How many [`Site`]s there are.
|
||||
pub const SITES: usize = Site::WeatherTypes as usize + 1;
|
||||
pub const SITES: usize = Site::PlayerVehicle as usize + 1;
|
||||
|
||||
/// The queue the title's own cheats are deferred to (`mov ecx, 4` in the pattern of [`Site::Defer`], whose
|
||||
/// stores are the closure's four words).
|
||||
@ -192,6 +197,14 @@ const PLACES: &[Place] = &[
|
||||
8B 84 87 ?? ?? 00 00 48 6B C0 38 8B 04 01",
|
||||
takes: &[(Site::WeatherTypes, Take::Rel { at: 3, next: 7 })],
|
||||
},
|
||||
Place {
|
||||
what: "the function that records the vehicle the player is in",
|
||||
// push rsi, rdi; sub rsp, 38h; mov rsi, rcx; lea rcx, [player's vehicle]; mov rdx, rsi; call (set the
|
||||
// reference); test rsi, rsi; je; mov rcx, rsi; call; test al, al; jne
|
||||
pattern: "56 57 48 83 EC 38 48 89 CE 48 8D 0D ?? ?? ?? ?? 48 89 F2 E8 ?? ?? ?? ?? 48 85 F6 0F 84 ?? ?? ?? ?? \
|
||||
48 89 F1 E8 ?? ?? ?? ?? 84 C0 0F 85",
|
||||
takes: &[(Site::PlayerVehicle, Take::Rel { at: 12, next: 16 })],
|
||||
},
|
||||
];
|
||||
|
||||
/// 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), &'
|
||||
/// `image_size`. A place that is missing, there twice, or that points outside the image leaves its sites `None`
|
||||
/// and a line in [`Sites::missing`].
|
||||
pub fn resolve(code: &[(usize, &[u8])], image_size: usize) -> Sites {
|
||||
resolve_some(code, image_size, None)
|
||||
}
|
||||
|
||||
/// [`resolve`] for the places that give one of `wanted` only (all of them with `None`): each place is a pass
|
||||
/// over the image's code, and whoever needs two sites need not pay for all.
|
||||
pub fn resolve_some(code: &[(usize, &[u8])], image_size: usize, wanted: Option<&[Site]>) -> Sites {
|
||||
let mut sites = Sites::default();
|
||||
for place in PLACES {
|
||||
if wanted.is_some_and(|wanted| !place.takes.iter().any(|(site, _)| wanted.contains(site))) {
|
||||
continue;
|
||||
}
|
||||
let Some(pattern) = Pattern::parse(place.pattern) else {
|
||||
sites.missing.push(format!("{}: its pattern does not read", place.what));
|
||||
continue;
|
||||
@ -280,6 +302,26 @@ pub fn resolve(code: &[(usize, &[u8])], image_size: usize) -> Sites {
|
||||
sites
|
||||
}
|
||||
|
||||
/// The sites (those of `wanted`, or all with `None`) of the image mapped at `base`. Reads the image's code and
|
||||
/// changes nothing.
|
||||
///
|
||||
/// # Safety
|
||||
/// `base` is the mapped image `info` describes, and nothing writes its code meanwhile (none of it runs yet).
|
||||
pub unsafe fn find(base: usize, info: &leonida_pe::ImageInfo, wanted: Option<&[Site]>) -> Sites {
|
||||
let code: Vec<(usize, &[u8])> = info
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|s| s.characteristics & crate::vipatch::SCN_MEM_EXECUTE != 0)
|
||||
.filter(|s| u64::from(s.rva) + u64::from(s.virtual_size) <= u64::from(info.size_of_image))
|
||||
.map(|s| {
|
||||
let (start, len) = (s.rva as usize, s.virtual_size as usize);
|
||||
// SAFETY: a section of the mapped image, readable, which nothing writes now.
|
||||
(start, unsafe { std::slice::from_raw_parts((base + start) as *const u8, len) })
|
||||
})
|
||||
.collect();
|
||||
resolve_some(&code, info.size_of_image as usize, wanted)
|
||||
}
|
||||
|
||||
/// `jmp [rip + 0]` and the address it jumps to: 14 bytes of code that reach anywhere.
|
||||
fn far_jump(to: usize) -> [u8; 14] {
|
||||
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]> {
|
||||
/// `base` is the mapped image `info` describes, no title code runs yet, and `hook` stays valid for the process.
|
||||
#[cfg(windows)]
|
||||
pub unsafe fn install(base: usize, info: &leonida_pe::ImageInfo, hook: usize) -> (Sites, Result<(), String>) {
|
||||
let sites = {
|
||||
// The image's code as it is mapped; the slices end with this block, before anything is written.
|
||||
let code: Vec<(usize, &[u8])> = info
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|s| s.characteristics & crate::vipatch::SCN_MEM_EXECUTE != 0)
|
||||
.filter(|s| u64::from(s.rva) + u64::from(s.virtual_size) <= u64::from(info.size_of_image))
|
||||
.map(|s| {
|
||||
let (start, len) = (s.rva as usize, s.virtual_size as usize);
|
||||
// SAFETY: a section of the mapped image, readable, which nothing writes now.
|
||||
(start, unsafe { std::slice::from_raw_parts((base + start) as *const u8, len) })
|
||||
})
|
||||
.collect();
|
||||
resolve(&code, info.size_of_image as usize)
|
||||
};
|
||||
// SAFETY: forwarded from this function's contract; the slices end with the call, before anything is written.
|
||||
let sites = unsafe { find(base, info, None) };
|
||||
let (Some(call), Some(_), Some(_)) =
|
||||
(sites.get(Site::HookCall), sites.get(Site::CheatsUpdate), sites.get(Site::Defer))
|
||||
else {
|
||||
@ -451,9 +480,34 @@ mod tests {
|
||||
assert_eq!(sites.get(Site::WantedSet).unwrap() % 16, 0);
|
||||
assert_eq!(sites.get(Site::WantedLevelAt), Some(0));
|
||||
assert!(sites.has(&[Site::ClockSet, Site::WeatherForce, Site::WeatherTypes]));
|
||||
// The player's vehicle: lea rcx, [rip + 0], whose end is 16 bytes into its place.
|
||||
assert_eq!(sites.get(Site::PlayerVehicle), Some(at(Site::PlayerVehicle) + 16));
|
||||
assert_eq!(sites.count(), SITES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn some_sites_are_found_without_looking_for_the_rest() {
|
||||
let mut code = image();
|
||||
let vehicle = place_at(place_of(Site::PlayerVehicle));
|
||||
code[vehicle + 12..vehicle + 16].copy_from_slice(&0x4321i32.to_le_bytes());
|
||||
// A place nobody asks for may be missing: it is not looked for, and not reported.
|
||||
let clock = place_at(place_of(Site::ClockSet));
|
||||
code[clock] ^= 0xFF;
|
||||
let wanted = [Site::PlayerPed, Site::PlayerVehicle];
|
||||
let sites = resolve_some(&[(0x1000, &code[..])], 0x10_0000, Some(&wanted));
|
||||
assert!(sites.missing.is_empty(), "{:?}", sites.missing);
|
||||
assert_eq!(sites.count(), 2);
|
||||
assert_eq!(sites.get(Site::PlayerPed), Some(0x1000 + place_at(place_of(Site::PlayerPed)) + 11));
|
||||
assert_eq!(sites.get(Site::PlayerVehicle), Some(0x1000 + vehicle + 16 + 0x4321));
|
||||
assert!(sites.get(Site::HookCall).is_none() && sites.get(Site::ClockSet).is_none());
|
||||
// Asked for, it is reported.
|
||||
let sites = resolve_some(&[(0x1000, &code[..])], 0x10_0000, Some(&[Site::ClockTime]));
|
||||
assert_eq!((sites.count(), sites.missing.len()), (0, 1));
|
||||
// All of them: as `resolve`.
|
||||
let all = resolve_some(&[(0x1000, &code[..])], 0x10_0000, None);
|
||||
assert_eq!(all, resolve(&[(0x1000, &code[..])], 0x10_0000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displacements_and_numbers_are_read_from_the_code() {
|
||||
let mut code = image();
|
||||
@ -635,6 +689,7 @@ mod tests {
|
||||
Site::WeatherNext,
|
||||
Site::WeatherForced,
|
||||
Site::WeatherTypes,
|
||||
Site::PlayerVehicle,
|
||||
] {
|
||||
assert!(!in_code(sites.get(site).unwrap()), "{site:?}");
|
||||
}
|
||||
|
||||
@ -184,6 +184,185 @@ afresh on return so the right stick does not jump. Scripted presses run with or
|
||||
|
||||
To try it by hand: `set LEONIDA_KEYBOARD_PAD=always`, then `gameinput_probe --seconds 20` and press keys.
|
||||
|
||||
## The keyboard-and-mouse pad of the D3D12 runtime
|
||||
|
||||
The D3D12 runtime (`d3d12/`) has its own GameInput module (`d3d12/crates/leonida-hle/src/modules/gameinput.rs`)
|
||||
with a stand-in pad made from the keyboard and mouse, present while no host pad is connected (or beside one, with
|
||||
`LEONIDA_ONE_PAD`, the default). Keys and mouse buttons count only while a window of the runtime has focus.
|
||||
|
||||
### Grand Theft Auto V's layout: one table on foot, one in a vehicle
|
||||
|
||||
The title reads a pad only, and on a pad one button is two actions: the right trigger shoots on foot and accelerates
|
||||
in a vehicle, the left trigger aims and brakes. One table of keys cannot be a PC layout then, so there are two
|
||||
(`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
|
||||
PC defaults (its key bindings as listed in BisectHosting's "GTA V controls guide" and on StrategyWiki's controls
|
||||
page). The pad button of each action is the title's default pad layout as far as it is known: the table below is the
|
||||
one that came with the PC prompt glyphs (a contributor's notes on the Xbox layout), not measured here.
|
||||
|
||||
| pad | on foot | in a vehicle |
|
||||
|---|---|---|
|
||||
| left stick, click | move, run | steer (lean on a bike), horn |
|
||||
| right stick, click | camera, look behind (zoom while aiming) | camera, look behind |
|
||||
| A / B / X / Y | jump and climb / crouch / melee and reload / interact, enter a vehicle | handbrake / duck, headlights / not known / leave the vehicle |
|
||||
| LB / RB | loadout wheel, holster / cover | loadout wheel / shoot from the vehicle |
|
||||
| LT / RT | aim / shoot | brake and reverse / accelerate |
|
||||
| d-pad up, down, left, right | phone, HUD and objective, radio menu, partner menu | the same |
|
||||
| Menu / View | pause / map | the same |
|
||||
|
||||
| key | on foot | in a vehicle |
|
||||
|---|---|---|
|
||||
| W, S | left stick up, down: move | RT, LT (fully): accelerate, brake and reverse |
|
||||
| A, D | left stick left, right: move | the same: steer |
|
||||
| mouse | right stick: camera (mouse look, below) | the same |
|
||||
| left mouse button | RT: shoot | RB: shoot from the vehicle |
|
||||
| right mouse button | LT: aim | nothing (the button that aims from a vehicle is not known) |
|
||||
| Space | A: jump, climb | A: handbrake |
|
||||
| Left Shift | left stick click: run | left stick up: lean forward on a bike, nose down in an aircraft |
|
||||
| Left Ctrl | B: crouch (GTA V's stealth) | left stick down: lean back, nose up |
|
||||
| Num 8, Num 5, Num 4, Num 6 | nothing | left stick up, down, left, right (GTA V's aircraft keys) |
|
||||
| Q | RB: cover | d-pad left: radio menu (GTA V's radio wheel) |
|
||||
| E | Y: interact (GTA V's context action) | left stick click: horn |
|
||||
| F | Y: enter a vehicle | Y: leave it |
|
||||
| R | X: reload, melee | X (the same button; GTA V's cinematic camera has none known) |
|
||||
| X, H | nothing | B: duck, headlights |
|
||||
| Tab | LB: loadout wheel (hold), holster | LB |
|
||||
| C | right stick click: look behind | the same |
|
||||
| M | View: map | the same |
|
||||
| Esc, P | Menu: pause | the same |
|
||||
| arrows | d-pad: phone (up) and its menus | the same |
|
||||
| Enter, Backspace | A, B: accept and back in the phone and menus | the same |
|
||||
| Z | d-pad down: HUD and objective (GTA V's radar zoom, the same press on its pad) | the same |
|
||||
| Y; I J K L | Y; right stick (kept from the layout before; GTA V has nothing on them on foot) | the same |
|
||||
|
||||
GTA V keys left without a binding, because the title's pad button for the action is not known: V (camera view), G
|
||||
(grenade; landing gear), O (heavy melee), the number keys (weapon slots), `[` `]` `,` `.` `=` `-` (zoom, radio), T, B,
|
||||
N, the F keys (character switch), Insert, Page Up and Page Down, the middle mouse button, and Caps Lock (GTA V's
|
||||
special ability), which is the switch described below. Left Alt (GTA V's character switch) would be the partner
|
||||
menu, d-pad right, and is left out because every Alt+Tab would press it; the right arrow is that button. For the
|
||||
same 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
|
||||
while aiming) is not bound either: the pad has no button known for the next weapon, and the host source polls key
|
||||
states (`GetAsyncKeyState`), which a wheel does not have; it would have to be counted from `WM_MOUSEWHEEL` in the
|
||||
window procedure of `lifecycle.rs`. The layout before had Z and V as the triggers, X as X, H as a second right stick
|
||||
click and Left Ctrl as a second left stick click; those went where GTA V has another meaning for the key.
|
||||
`LEONIDA_KBM=classic` brings the table of before back whole (`FALLBACK_BUTTONS`: W A S D and I J K L the sticks,
|
||||
Space 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
|
||||
clicks, Z or the right mouse button LT, V or the left mouse button RT, Esc Menu, Tab View).
|
||||
|
||||
In an aircraft A and D are the left stick (roll), not GTA V's rudder: only "in a vehicle" is known, not which kind.
|
||||
|
||||
### Which table counts
|
||||
|
||||
`gameinput::set_player_context(OnFoot | InVehicle | Unknown)` tells the stand-in pad, lock-free from any thread; a
|
||||
context that is not set again for 500 ms is unknown (and the pad only lets go of a known one after 100 ms of
|
||||
unknown). Unknown is the on-foot table, and then **Caps Lock** switches to the driving table and back by hand, with a
|
||||
line in the log at every change of table; driving by hand also ends when F (leave the vehicle) is pressed, so that W
|
||||
cannot stay the right trigger on foot. While a context is measured Caps Lock does nothing: it is GTA V's special
|
||||
ability key, and a press out of habit on foot must not make W a shot. `gameinput::driving_controls()` says which
|
||||
table is in use (for whoever draws key prompts).
|
||||
|
||||
**The hand-over** when the table changes: a key that is another pad input in the other table (W, S, the mouse buttons,
|
||||
Left Shift, Left Ctrl, Q, E, X, H) and is down at that moment gives nothing until it has been let go and pressed
|
||||
again, and no such key gives anything for 400 ms after the change (`LEONIDA_KBM_SETTLE_MS`, 0 to 3000). So the left
|
||||
mouse button held on foot never becomes the accelerator and W held in a car never becomes a shot; the price is that W
|
||||
held while getting in has to be pressed again to drive off. Keys that are the same pad input in both tables (A, D,
|
||||
Space, F, ...) carry over as a real pad's button would. Unit-tested over every set of held keys in both directions
|
||||
(`cargo test -p leonida-hle gameinput`).
|
||||
|
||||
**Who tells.** `d3d12/apps/leonida/src/player_context.rs` reads the title every 16 ms from a thread of its own
|
||||
(`ReadProcessMemory` on the own process: nothing is written and no title code is called, so it does not need
|
||||
`LEONIDA_GAME_ACTIONS=1`; without the game actions it looks the two globals up itself at start, two more passes over
|
||||
the 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
|
||||
says "in a vehicle" is, in this order:
|
||||
|
||||
1. `LEONIDA_PED_VEHICLE_AT=0x<offset>`: a field of the player's ped that points at its vehicle and is null on foot.
|
||||
None is known (see below why there may be none), so this is unset by default.
|
||||
2. The title's own global of the player's vehicle (`Site::PlayerVehicle` in `leonida-loader/src/game_actions.rs`,
|
||||
found by a pattern that is in the 1.0.2.1 executable once; `LEONIDA_PLAYER_VEHICLE_AT=0x<offset in the image>`
|
||||
names another, `=off` turns it off). **Read from the code, not yet seen in the running title:**
|
||||
- The title keeps what belongs to a ped apart from the ped's entity, in tables looked up by the entity's id
|
||||
(`+9Ch`; a ped's id has `60000h` under the mask `3E0000h`, its index is the low 17 bits, and a 16-bit slot of
|
||||
`FFFFh` means "none"). Its "the vehicle this ped is in" (the function at `4DD7510h`) takes column `47h` of
|
||||
those tables and gives the pointer at `+898h` of it when bit `20h` of the byte at `+10h` is set, else null: the
|
||||
shape of GTA V's `GetVehiclePedInside`, a "my vehicle" pointer that outlives the ride plus a flag. That is why a
|
||||
pointer in the ped that is null on foot may not exist at all.
|
||||
- The global at `AB760C8h` is written by one function (`CA4DE0h`), which has three callers: one passes a
|
||||
vehicle (in a function of 129Fh bytes, taken to be where a ped is put in a vehicle), one passes null after
|
||||
testing that the ped's id is the player's (taken to be where a ped is taken out), and the function that sets
|
||||
the player's ped passes what `4DD7510h` gives for the new ped. The first two are methods of that same column
|
||||
`47h` record: the first begins by reading its `+10h` and `+898h` and testing bit `20h`, the second tests
|
||||
other bits beside it (`+12h`). 167 places in the code read the global; the vehicle cheats read a type byte
|
||||
at `+FAh` of what it points at.
|
||||
- Not known until it has run: that it is null in every on-foot state (after a crash through the windscreen, a
|
||||
vehicle that blows up, a cutscene), and when during getting in and out it changes compared with the title's own
|
||||
switch of its controls. The reader logs every change with its time, and warns when the ped moves at 12 m/s for
|
||||
a second while it says "on foot", or the vehicle is 60 m from the ped while it says "in a vehicle".
|
||||
3. `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
|
||||
about 7) or more for a second without a break is "in a vehicle", until 3 s have passed below that speed; a fall
|
||||
(more down than along) and a jump of the position (a teleport, a respawn) do not count. Its limits are why it is
|
||||
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
|
||||
cannot see a drive begin, so it never switches from a standstill and the first metres of every drive are on the
|
||||
on-foot keys, and so the meaning of W and of the mouse buttons would change in the middle of a drive, at every
|
||||
stop. It always runs as the check named above.
|
||||
|
||||
With none of the three the context stays unknown: the on-foot table, and Caps Lock.
|
||||
|
||||
| switch | effect |
|
||||
|---|---|
|
||||
| `LEONIDA_KBM=classic` | the single table of before; nothing reads the title |
|
||||
| `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 |
|
||||
| `LEONIDA_KBM_SETTLE_MS=<ms>` | the pause after a change of table, 400 |
|
||||
| `LEONIDA_PED_VEHICLE_AT`, `LEONIDA_PLAYER_VEHICLE_AT`, `LEONIDA_KBM_SPEED` | what says "in a vehicle", above |
|
||||
| `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. |
|
||||
|
||||
The mouse buttons are not passed to the title while the F1 settings menu or the F4 trainer menu is open, and they
|
||||
never reach the title as keyboard keys.
|
||||
|
||||
**Mouse look (D3D12 runtime).** The console title turns its camera with the right stick only; it does not read the
|
||||
mouse for that. A left click in the game window makes the window hold the mouse: the cursor is hidden and kept in the
|
||||
window, and the mouse's motion becomes a right-stick push (`MouseLook` in `d3d12/crates/leonida-hle/src/modules/
|
||||
gameinput.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
|
||||
0.6 power curve, merged with the pad's own stick. That click is not a shot; the mouse buttons reach the title as
|
||||
triggers only while the window holds the mouse. Esc (which also pauses), the F1 or F4 menu, or another window in front
|
||||
gives the mouse back. Settings: `LEONIDA_MOUSE_SENSITIVITY` (1, 0.1..10), `LEONIDA_MOUSE_INVERT_Y=1`,
|
||||
`LEONIDA_MOUSE_DEADZONE` (0.24), `LEONIDA_MOUSE_CURVE` (0.6), `LEONIDA_MOUSE_LOOK=0` (off: the old behaviour, buttons
|
||||
whenever the window has focus). Unit-tested (`mouse_look_turns_speed_into_a_stick_past_the_dead_zone`); the dead zone
|
||||
and curve are first guesses at the title's own stick response, not measured.
|
||||
|
||||
## PlayStation pads and the active input of the D3D12 runtime
|
||||
|
||||
The D3D12 runtime has no SDL. Besides XInput it reads Sony pads (vendor `054C`: DualSense `0CE6`, DualSense Edge `0DF2`,
|
||||
DualShock 4 `05C4`, `09CC`, USB adapter `0BA0`) over Windows HID directly (`gameinput/hid.rs`), on USB and Bluetooth,
|
||||
written from the public report layouts (the Linux `hid-playstation` driver documents them). One thread per pad reads
|
||||
input reports; a rescan every 2 s finds pads that came or went. A Bluetooth pad is moved to its full report by reading
|
||||
calibration feature report `0x05`.
|
||||
|
||||
| | USB input | Bluetooth input | USB output | Bluetooth output |
|
||||
|---|---|---|---|---|
|
||||
| DualSense | `0x01`, 64 bytes, data from byte 1 | `0x31`, 78 bytes, data from byte 2 | `0x02`, 63 | `0x31`, 78, CRC-32 last |
|
||||
| DualShock 4 | `0x01`, 64 bytes, data from byte 1 | `0x11`, data from byte 3 | `0x05`, 32 | `0x11`, 78, CRC-32 last |
|
||||
|
||||
Buttons: Cross, Circle, Square, Triangle are A, B, X, Y; L1/R1 the shoulders; L2/R2 the triggers (analog byte, the
|
||||
digital bit is ignored); L3/R3 the stick clicks; Options is Menu; Create (Share) and the touchpad click are View;
|
||||
the PS and mute buttons are not passed. Sticks are 0..255, centre 128. Rumble: the big motor of the title's
|
||||
`SetRumbleState` goes to the pad's left motor, the small one to its right (`rumble_report`; on Bluetooth the CRC is
|
||||
seeded with `0xA2`). Trigger effects and the lightbar are not driven. A Sony pad takes the first slot XInput leaves
|
||||
empty (all pads are one pad for the title anyway, `LEONIDA_ONE_PAD`).
|
||||
|
||||
A pad that Steam Input or DS4Windows already shows through XInput is not read twice: when input comes on an XInput pad and
|
||||
on 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
|
||||
reading is left out of what the title sees. A Sony pad present but not openable (hidden by HidHide, held exclusively)
|
||||
counts the same way: input on XInput is then PlayStation input.
|
||||
|
||||
**Active input.** `gameinput::active_family()` (`leonida-hle`, readable from any thread, lock-free) says which kind of
|
||||
device was used last: `Family::Xbox`, `Family::PlayStation` or `Family::KeyboardMouse`; `family_generation()` goes up by one
|
||||
with each change. It follows the rules of [Active input](#active-input) above (an edge counts, the first reading of a
|
||||
device is its baseline, a change waits `LEONIDA_PROMPTS_SWITCH_MS` = 300 ms), with the keyboard and mouse as a third
|
||||
family (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
|
||||
present and Xbox otherwise. One line is logged on each change (`input in use: PlayStation (Sony pad input)`).
|
||||
`LEONIDA_PROMPTS=xbox|playstation|keyboard|auto` forces it. The button prompts follow it: see
|
||||
[prompt_glyphs.md](prompt_glyphs.md). Unit-tested on hand-made report bytes and the family rules; not run against a
|
||||
real pad yet.
|
||||
|
||||
## Rumble and triggers
|
||||
|
||||
`IGameInputDevice::SetRumbleState` takes four motor levels, 0..1. The two body motors go to `SDL_RumbleGamepad` on
|
||||
|
||||
@ -194,9 +194,11 @@ menu.
|
||||
way). Our hook is the one
|
||||
`call` of the cheat input function: it calls that function, then, if something was asked, gives the same queue
|
||||
a closure of its own. So our work runs exactly where a cheat of the title's would.
|
||||
- **Finding it again.** Ten places are named by patterns of 24 to 77 bytes (19 to 36 of them fixed, `??` for
|
||||
what another build changes: short signatures, no longer than they must be), which give 19 things: 8 functions,
|
||||
the hook's call, 9 globals and the place of the level in the wanted state. Each
|
||||
- **Finding it again.** Eleven places are named by patterns of 24 to 77 bytes (19 to 36 of them fixed, `??` for
|
||||
what another build changes: short signatures, no longer than they must be), which give 20 things: 8 functions,
|
||||
the hook's call, 10 globals and the place of the level in the wanted state (the eleventh place, the global of
|
||||
the player's vehicle, is for the keyboard and mouse layout and is looked up without the game actions too:
|
||||
`docs/gameinput.md`). Each
|
||||
pattern is in the 99.9 MB of code exactly once (`cargo test -p leonida-loader game_actions` with
|
||||
`LEONIDA_GAME_DIR` set checks it, and that functions lie in code and globals behind it). None contains a load
|
||||
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
|
||||
Skipped without a D3D12 device.
|
||||
- `cargo test -p leonida-hle --features diagnostics --lib -- gameinput clock`: the input shim with the kept keys in
|
||||
place, and the title's clock.
|
||||
- `cargo test -p leonida-loader --lib game_actions`: the ten places on made-up code (found wherever they lie,
|
||||
- `cargo test -p leonida-loader --lib game_actions`: the eleven places on made-up code (found wherever they lie,
|
||||
displacements and numbers read, a place missing, twice or pointing outside left out), the hook on made-up code
|
||||
that runs (the update step calls a function of ours and returns as before) and, with `LEONIDA_GAME_DIR` set to
|
||||
the package's folder, every place once in the retail executable, functions in code and globals behind it.
|
||||
|
||||
Reference in New Issue
Block a user