diff --git a/README.md b/README.md index e3a6f666..89bc3218 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,40 @@ log is made. The game restarts with your settings; a crash also writes results and restarts. Uploading to the [PortWatch](https://portwatch-vi.xyz/lab/#report) form is manual. +### Benchmark routes + +```sh +./run.sh play VICTORY_BENCH=nort VICTORY_BENCH_ROUTE=downtown +./run.sh play VICTORY_BENCH=rt VICTORY_BENCH_ROUTE=drive +./run.sh play VICTORY_BENCH_ROUTE=drive # just watch it, no recording +``` + +`VICTORY_BENCH_ROUTE` takes the player along a fixed route, built into +VIctory (no mods needed), so runs on different machines see the same places +the same way. Coordinates are fixed in the code, not taken from your save. +Both start 15 seconds after the player appears in the world, set the time to +12:00 with the clock paused and the weather to clear (`sunny`, held), allow no +wanted level (a police chase would make runs differ), and make +the player invincible. + +- `downtown`: a noclip flight around a 2400 m square over the city (corner + -2600, -1000), at 30 m/s, 40 m above the ground (following it, smoothed), + in a Dinka Blista with collision off, the camera sweeping 60 degrees each + way every 6 seconds. One lap is about 5 min 20 s. +- `drive`: the player is put at -2556, 6948 in a Dinka Blista, and the + game's own AI drives a loop through the hills on its roads: to -2399, 7172, + -2566, 7202, back to the start and around again (about 3.5 minutes a lap), + with traffic on (it reacts to traffic itself, so no two runs are exactly + alike). The waypoints are points the AI was seen to reach on the road. A leg + not done in 180 seconds is skipped. +With `VICTORY_BENCH`, the run's time and its figures start when the route +starts (none are left out), and `bench_stats.txt` names the route. The game log +has a `bench route:` line for the start, each lap or leg, and anything that +stops the route; a route that cannot run (another game build, a fault in a game +call) stops with a warning and the benchmark carries on where the player is. +The routes need game build 1.0.2.1 (Xbox Series) and do not mix with ViceHook, +which hooks the same game function. + ## Diagnostics and development Build the diagnostics profile with `PROFILE=diag ./build.sh`. Page sampling, RT diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 0612ab99..24affbff 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -442,6 +442,14 @@ pub fn run( // SAFETY: as above. unsafe { victory_loader::range_allocator::apply(image.base(), size) }; } + // A fixed benchmark route (VICTORY_BENCH_ROUTE=downtown|drive, off + // without it): the game's script tick hooked to take the player along. + #[cfg(windows)] + if execute { + let size = image.info().size_of_image as usize; + // SAFETY: the image stays mapped and nothing of it has run yet. + unsafe { victory_loader::bench_route::apply_asked(image.base(), size) }; + } if !execute { println!("not executing (pass --execute to start the title)"); return Ok(()); diff --git a/crates/victory-core/src/bench.rs b/crates/victory-core/src/bench.rs index 76cd3b99..7be9d13e 100644 --- a/crates/victory-core/src/bench.rs +++ b/crates/victory-core/src/bench.rs @@ -2,6 +2,10 @@ //! `VICTORY_BENCH=rt` or `nort` over the user's settings, and the game //! closes itself after `VICTORY_BENCH_MINUTES`. Here: what was asked, and //! the frame rate figures. +//! +//! `VICTORY_BENCH_ROUTE` adds a fixed route the player is taken along (see +//! [`Route`]; driven by `victory_loader::bench_route`). In a benchmark run +//! with a route, the run's clock and its figures start when the route does. /// Minutes at the start left out of the figures (loading and menus), in /// runs of at least twice this. @@ -49,6 +53,115 @@ pub fn presses_enter() -> bool { ) } +/// A fixed route for benchmark runs (`VICTORY_BENCH_ROUTE`): the same +/// places, the same way, on every machine (game build 1.0.2.1). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Route { + /// `downtown`: a noclip flight around a 2400 m square over the city, at + /// 30 m/s, 40 m above the ground, the camera sweeping side to side. + Downtown, + /// `drive`: the game's AI drives the player's car around a fixed loop of + /// waypoints, with traffic. + Drive, +} + +impl Route { + /// The route `VICTORY_BENCH_ROUTE` names (case ignored), if any. + pub fn parse(name: &str) -> Option { + match name.trim().to_ascii_lowercase().as_str() { + "downtown" => Some(Route::Downtown), + "drive" => Some(Route::Drive), + _ => None, + } + } + + /// Its name, as `VICTORY_BENCH_ROUTE` takes it. + pub fn name(self) -> &'static str { + match self { + Route::Downtown => "downtown", + Route::Drive => "drive", + } + } +} + +/// The route asked for with `VICTORY_BENCH_ROUTE`, if a known one. +pub fn route() -> Option { + static ROUTE: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ROUTE.get_or_init(|| { + std::env::var("VICTORY_BENCH_ROUTE") + .ok() + .and_then(|v| Route::parse(&v)) + }) +} + +static ROUTE_STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// The route is under way (or gave up): a benchmark run starts its clock. +pub fn set_route_started() { + ROUTE_STARTED.store(true, std::sync::atomic::Ordering::Relaxed); +} + +/// Whether the route asked for has started (or gave up). +pub fn route_started() -> bool { + ROUTE_STARTED.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The `downtown` flight: the square's corner (x, y), the ground height the +/// flight is measured from where the ground has not streamed in yet, the +/// side in metres, the speed in m/s and the height above the ground. +pub const DOWNTOWN_CORNER: (f32, f32) = (-2600.0, -1000.0); +pub const DOWNTOWN_GROUND: f32 = 5.0; +pub const DOWNTOWN_SIDE: f32 = 2400.0; +pub const DOWNTOWN_SPEED: f32 = 30.0; +pub const DOWNTOWN_UP: f32 = 40.0; + +/// The `drive` loop's waypoints (absolute map x, y), driven in order and +/// around again; the car starts at the first, facing the second. Points the +/// game's AI was seen to reach on its roads (a dirt road in the hills): off +/// the road network its route finding stalls. +pub const DRIVE_WAYPOINTS: [(f32, f32); 3] = + [(-2556.0, 6948.0), (-2399.0, 7172.0), (-2566.0, 7202.0)]; + +/// The game's heading (degrees, 0 north, counter-clockwise) of travel from +/// `from` to `to`. +pub fn heading(from: (f32, f32), to: (f32, f32)) -> f32 { + (-(to.0 - from.0)).atan2(to.1 - from.1).to_degrees() +} + +/// Where the `downtown` flight is `seconds` after it started: (x, y), the +/// heading, and the laps completed. Corner, then +x, +y, back -x, -y. +pub fn downtown_at(seconds: f32) -> ((f32, f32), f32, u32) { + let side = DOWNTOWN_SIDE; + let corners = [ + (0.0, 0.0), + (side, 0.0), + (side, side), + (0.0, side), + (0.0, 0.0), + ]; + let travelled = seconds.max(0.0) * DOWNTOWN_SPEED; + let d = travelled % (4.0 * side); + let leg = ((d / side) as usize).min(3); + let f = (d - leg as f32 * side) / side; + let (a, b) = (corners[leg], corners[leg + 1]); + let (x0, y0) = DOWNTOWN_CORNER; + let at = (x0 + a.0 + (b.0 - a.0) * f, y0 + a.1 + (b.1 - a.1) * f); + (at, heading(a, b), (travelled / (4.0 * side)) as u32) +} + +/// The camera's sweep (radians, relative to the heading) `seconds` into the +/// flight: +-60 degrees over a 6 s period. +pub fn downtown_sweep(seconds: f32) -> f32 { + (seconds * std::f32::consts::TAU / 6.0).sin() * 60f32.to_radians() +} + +/// The flight's height over smoothed ground `ground` (none yet: the +/// reference height). +pub fn downtown_height(ground: Option) -> f32 { + let floor = DOWNTOWN_GROUND + DOWNTOWN_UP; + ground.map_or(floor, |g| floor.max(g + DOWNTOWN_UP)) +} + /// The times between presented frames, in seconds. #[derive(Default)] pub struct Recorder { @@ -84,6 +197,11 @@ impl Recorder { } else { 0.0 }; + self.summary_skipping(skip) + } + + /// The figures, leaving out the first `skip` seconds of frames. + pub fn summary_skipping(&self, skip: f64) -> Option { let mut at = 0.0; let first = self.frames.iter().position(|dt| { at += dt; @@ -159,4 +277,36 @@ mod tests { assert_eq!(r.summary().unwrap().frames, 100); assert_eq!(Recorder::default().summary(), None); } + + #[test] + fn routes_are_named_as_documented() { + assert_eq!(Route::parse("downtown"), Some(Route::Downtown)); + assert_eq!(Route::parse(" Drive "), Some(Route::Drive)); + assert_eq!(Route::parse("beach"), None); + assert_eq!(Route::Drive.name(), "drive"); + } + + #[test] + fn the_flight_goes_around_the_square() { + let close = |a: f32, b: f32| (a - b).abs() < 0.01; + let ((x, y), h, laps) = downtown_at(0.0); + assert!(close(x, -2600.0) && close(y, -1000.0) && laps == 0); + // East first (heading -90: the game's headings turn left from north). + assert!(close(h, -90.0)); + let ((x, y), h, _) = downtown_at(40.0); + assert!(close(x, -2600.0 + 1200.0) && close(y, -1000.0) && close(h, -90.0)); + let ((x, y), h, _) = downtown_at(100.0); + assert!(close(x, -200.0) && close(y, -1000.0 + 600.0) && close(h, 0.0)); + let ((x, y), _, laps) = downtown_at(320.0 + 10.0); + assert!(close(x, -2300.0) && close(y, -1000.0) && laps == 1); + assert!(close(downtown_sweep(1.5), 60f32.to_radians())); + assert!(close(downtown_height(None), 45.0)); + assert!(close(downtown_height(Some(100.0)), 140.0)); + assert!(close(downtown_height(Some(-20.0)), 45.0)); + } + + #[test] + fn the_drive_starts_toward_the_first_leg() { + assert!(heading(DRIVE_WAYPOINTS[0], DRIVE_WAYPOINTS[1]) < 0.0); + } } diff --git a/crates/victory-gpu/src/bench.rs b/crates/victory-gpu/src/bench.rs index 20ac1644..db58c68f 100644 --- a/crates/victory-gpu/src/bench.rs +++ b/crates/victory-gpu/src/bench.rs @@ -2,6 +2,11 @@ //! timed from the first one, and when the time is up the frame about to be //! presented, panel included, is saved as `screenshot.png` with the figures //! (`bench_stats.txt`) in `VICTORY_BENCH_DIR`, and the game ends. +//! +//! With a route (`VICTORY_BENCH_ROUTE`) the frames are timed from the +//! route's start instead, and none are left out of the figures; a route that +//! has not started after [`ROUTE_WAIT`] of frames is given up on and the run +//! is timed from then. use std::path::PathBuf; use std::sync::Mutex; @@ -11,8 +16,13 @@ use victory_core::bench::{self, Recorder}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; +/// The longest a benchmark run waits for its route to start. +const ROUTE_WAIT: Duration = Duration::from_secs(600); + #[derive(Default)] struct Run { + /// The first frame presented, while waiting for the route. + first: Option, started: Option, last: Option, sampled: Option, @@ -45,6 +55,16 @@ pub(crate) fn presented(memory: impl FnOnce() -> (u64, u64)) { } let now = Instant::now(); with(|r| { + if r.started.is_none() && bench::route().is_some() && !bench::route_started() { + if now.duration_since(*r.first.get_or_insert(now)) < ROUTE_WAIT { + return; + } + tracing::warn!( + "benchmark: the route did not start in {} s; timing the run from now", + ROUTE_WAIT.as_secs() + ); + bench::set_route_started(); + } r.started.get_or_insert(now); if let Some(last) = r.last.replace(now) { r.frames.add(now.duration_since(last).as_secs_f64()); @@ -146,8 +166,16 @@ pub(crate) fn finish(shot: Option) -> ! { Err(e) => tracing::warn!(error = %e, "benchmark: no screenshot"), } } + let route = bench::route(); + if let Some(route) = route { + text.push_str(&format!("route={}\n", route.name())); + } with(|r| { - if let Some(s) = r.frames.summary() { + let summary = match route { + Some(_) => r.frames.summary_skipping(0.0), + None => r.frames.summary(), + }; + if let Some(s) = summary { text.push_str(&format!( "seconds={:.0}\nframes={}\naverage={:.1}\nlow_1pct={:.1}\nlowest={:.1}\nhighest={:.1}\n", s.seconds, s.frames, s.average, s.low_1pct, s.lowest, s.highest diff --git a/crates/victory-loader/src/bench_route.rs b/crates/victory-loader/src/bench_route.rs new file mode 100644 index 00000000..b0449680 --- /dev/null +++ b/crates/victory-loader/src/bench_route.rs @@ -0,0 +1,1273 @@ +//! The benchmark routes (`VICTORY_BENCH_ROUTE=downtown|drive`, see +//! [`victory_core::bench::Route`]): the player is taken along a fixed route +//! by the game's own script natives, so every run sees the same places. +//! Off, and nothing hooked, without the variable. +//! +//! The game's scripts call natives through handlers `void(NativeContext*)`, +//! arguments and results in 8-byte cells (an entity or a vector takes two). +//! The handlers used here are found by their offsets in build 1.0.2.1, and +//! each is checked to be the native expected: a handler opens with +//! `cmp dword [rcx+10h], 0` (the argument count) and a `js` to a cold block +//! that writes the native's 64-bit id with `mov r64, imm64`, which must be +//! the id asked for. As in ViceHook (MIT), whose approach this follows. +//! +//! The route runs on the game's script update path: PLAYER_PED_ID's handler +//! is hooked, as nearly every game script calls it every frame. Once per +//! game frame (GET_FRAME_COUNT changes), and always in the same game script +//! thread (GET_ID_OF_THIS_THREAD; elected as the one that calls on the most +//! frames, as many entity flags belong to the script thread that set them), +//! the route takes one step. Every native call goes through a guard with an +//! exception handler of its own: a fault in the game's code stops the route +//! with a log line instead of the game. +//! +//! Vehicles are made with the game's asynchronous create native, as +//! ViceHook's `spawn.cpp` does: the calling script program's token for the +//! vehicle create task type, the task held strongly until it is done, the +//! vehicle then taken out of it. + +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use victory_core::bench::{self, Route}; +use windows_sys::Win32::Foundation::GetLastError; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, EXCEPTION_RECORD, FlushInstructionCache, RtlUnwindEx, +}; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_GUARD, + PAGE_NOACCESS, VirtualAlloc, VirtualProtect, VirtualQuery, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// The PE timestamp of game build 1.0.2.1 (Xbox Series), the only one the +/// offsets below are for. +const BUILD: u32 = 1_794_606_036; + +/// A native: its id and its handler's offset in 1.0.2.1. +#[derive(Clone, Copy)] +struct Native { + name: &'static str, + id: u64, + rva: usize, +} + +macro_rules! natives { + ($($konst:ident = $name:literal, $id:literal, $rva:literal;)*) => { + $(const $konst: Native = Native { name: $name, id: $id, rva: $rva };)* + const ALL: &[Native] = &[$($konst),*]; + }; +} + +natives! { + PLAYER_PED_ID = "PLAYER_PED_ID", 0x6471_F11F_F69D_8A77, 0x450_4480; + GET_FRAME_COUNT = "GET_FRAME_COUNT", 0x030E_FF3E_8820_56A7, 0x3E8_5700; + GET_ID_OF_THIS_THREAD = "GET_ID_OF_THIS_THREAD", 0x9410_969F_AAAD_A3CB, 0x446_8FF0; + GET_ENTITY_COORDS = "GET_ENTITY_COORDS", 0x6C66_0BB2_5792_A0F9, 0x3C0_9D00; + SET_ENTITY_COORDS = "SET_ENTITY_COORDS", 0xF9F5_FD94_F97B_C258, 0x3C1_3760; + SET_ENTITY_COORDS_NO_OFFSET = "SET_ENTITY_COORDS_NO_OFFSET", 0x53E2_5C7A_DC65_CCAE, 0x3C1_36D0; + SET_ENTITY_HEADING = "SET_ENTITY_HEADING", 0xBA3B_9AE4_30D4_63F9, 0x3C1_3B80; + SET_ENTITY_INVINCIBLE = "SET_ENTITY_INVINCIBLE", 0x3BD9_0347_5A3C_78C9, 0x3C1_4370; + SET_ENTITY_COLLISION = "SET_ENTITY_COLLISION", 0xF6BA_C473_0990_7DF6, 0x3C1_34D0; + FREEZE_ENTITY_POSITION = "FREEZE_ENTITY_POSITION", 0x294E_68AB_8261_0485, 0x3C0_8A00; + GET_ENTITY_MODEL = "GET_ENTITY_MODEL", 0x6DEF_2C9A_2589_560C, 0x3C0_A460; + GET_ENTITY_SPEED = "GET_ENTITY_SPEED", 0x5ACC_207E_0494_5AEF, 0x3C0_A900; + DOES_ENTITY_EXIST = "DOES_ENTITY_EXIST", 0xD1F0_E988_2BD4_2914, 0x3C0_7510; + GET_GROUND_Z = "GET_GROUND_Z_AND_NORMAL_FOR_3D_COORD", 0x9CE6_1954_D5D6_3565, 0x3E8_5910; + SET_CAM_RELATIVE = "_0x19A22EB794602C16 (camera heading, pitch)", 0x19A2_2EB7_9460_2C16, 0x3CD_0020; + SET_DRIVER_ABILITY = "SET_DRIVER_ABILITY", 0xFBD0_3A3C_4E6A_0057, 0x4BD_6770; + GET_VEHICLE_PED_IS_USING = "GET_VEHICLE_PED_IS_USING", 0xE5D1_5782_9F6B_52FE, 0x4BF_5050; + SET_PED_INTO_VEHICLE = "SET_PED_INTO_VEHICLE", 0x61E3_F9C2_08A4_F29D, 0x4BF_8EA0; + TASK_VEHICLE_DRIVE_TO_COORD = "TASK_VEHICLE_DRIVE_TO_COORD", 0x9A62_8858_1D5D_55D0, 0x44C_9120; + CREATE_VEHICLE = "VI_CREATE_VEHICLE_ASYNC", 0xE964_9529_58DE_F7B3, 0x4A8_0260; + SET_CLOCK_TIME = "SET_CLOCK_TIME", 0x04D2_1127_C5AD_3A60, 0x3CD_69A0; + PAUSE_CLOCK = "PAUSE_CLOCK", 0x6D40_C881_B2E5_A6F3, 0x3CD_53C0; + SET_WEATHER_TYPE = "SET_WEATHER_TYPE", 0x01F6_A4A5_A6E8_B0E5, 0x3E9_20D0; + REQUEST_COLLISION_AT_COORD = "REQUEST_COLLISION_AT_COORD", 0x9D5F_CC36_F5C8_DF0E, 0x446_9E80; + SET_MAX_WANTED_LEVEL = "SET_MAX_WANTED_LEVEL", 0x11DC_91E6_D75B_42D3, 0x3E9_0B70; +} + +/// PLAYER_PED_ID's handler's first 14 bytes (`push rsi; push rdi; push rbx; +/// sub rsp, 30h; cmp dword [rcx+10h], 0; mov rsi, rcx`), position +/// independent, replaced by the jump to [`player_ped_id`]. +const PLAYER_PED_ID_PROLOGUE: [u8; 14] = [ + 0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x30, 0x83, 0x79, 0x10, 0x00, 0x48, 0x89, 0xce, +]; + +/// Spawning (1.0.2.1): the strong handle helpers `(holder, object)` and +/// `(holder)`, the vehicle create task type (its record hash), the model +/// key of the Dinka Blista, and how many frames a create may take. +const PIN: usize = 0x381_A110; +const UNPIN: usize = 0x205_D410; +const VEHICLE_TASK: u64 = 0xB160_382E_3F59_FF92; +const BLISTA: u64 = 0x2C2A_ED8C_DC20_8C27; +const SPAWN_FRAMES: u32 = 300; + +/// The script thread election (frames), as ViceHook's. +const ELECT_FRAMES: i64 = 60; +const LOST_FRAMES: i64 = 90; +/// How high the player is held over the drive's start while its ground +/// streams in. +const DRIVE_HOLD_Z: f32 = 300.0; +/// From the player's first appearance to the route's start. +const SETTLE: Duration = Duration::from_secs(15); +/// The drive: a waypoint is reached within this many metres; a leg not +/// done in [`LEG_LIMIT`] is skipped. +const REACHED_M: f32 = 40.0; +const LEG_LIMIT: Duration = Duration::from_secs(180); +/// The longest the drive's start waits for the ground to stream in. +const GROUND_WAIT: Duration = Duration::from_secs(60); + +static BASE: AtomicUsize = AtomicUsize::new(0); +static TRAMPOLINE: AtomicUsize = AtomicUsize::new(0); +static TICKING: AtomicBool = AtomicBool::new(false); +/// The route ended (stopped after a fault): the hook only passes calls on. +static DONE: AtomicBool = AtomicBool::new(false); +static LAST_FRAME: AtomicI64 = AtomicI64::new(-1); +static STATE: Mutex> = Mutex::new(None); +/// Where the last fault caught by the guard was. +static FAULT_AT: AtomicUsize = AtomicUsize::new(0); + +// The guard: `victory_route_guard(f, a, b, out)` calls `f(a, b)`, stores its +// rax in `*out` and returns 0; an exception in `f` that nothing below +// handles reaches `victory_route_except`, which unwinds to the landing with +// the exception code in eax (what `__try`/`__except` does in C). +std::arch::global_asm!( + ".globl victory_route_guard", + ".globl victory_route_landing", + ".def victory_route_guard", + ".scl 2", + ".type 32", + ".endef", + ".seh_proc victory_route_guard", + "victory_route_guard:", + "push rbx", + ".seh_pushreg rbx", + "sub rsp, 32", + ".seh_stackalloc 32", + ".seh_endprologue", + ".seh_handler victory_route_except, @except", + "mov rbx, r9", + "mov rax, rcx", + "mov rcx, rdx", + "mov rdx, r8", + "call rax", + "mov qword ptr [rbx], rax", + "xor eax, eax", + "victory_route_landing:", + "add rsp, 32", + "pop rbx", + "ret", + ".seh_endproc", +); + +unsafe extern "system" { + fn victory_route_guard(f: usize, a: usize, b: usize, out: *mut u64) -> u32; + fn victory_route_landing(); +} + +/// The guard's exception handler (an x64 language handler). +#[unsafe(no_mangle)] +unsafe extern "system" fn victory_route_except( + record: *mut EXCEPTION_RECORD, + frame: *mut core::ffi::c_void, + context: *mut CONTEXT, + _dispatcher: *mut core::ffi::c_void, +) -> i32 { + // EXCEPTION_UNWINDING | EXCEPTION_EXIT_UNWIND | EXCEPTION_TARGET_UNWIND + // | EXCEPTION_COLLIDED_UNWIND: an unwind passing through, not ours to take. + const UNWIND: u32 = 0x66; + // SAFETY: the system passes the exception being dispatched. + let (flags, code, at) = unsafe { + ( + (*record).ExceptionFlags, + (*record).ExceptionCode as u32, + (*record).ExceptionAddress as usize, + ) + }; + if flags & UNWIND != 0 { + return 1; // ExceptionContinueSearch + } + FAULT_AT.store(at, Ordering::Relaxed); + // SAFETY: unwinds to the guard's own frame (`frame` is its establisher + // frame) and resumes at its landing with the code as its result, as + // `__C_specific_handler` does for `__except`. Does not return. + unsafe { + RtlUnwindEx( + frame, + victory_route_landing as *const core::ffi::c_void, + record, + code as usize as *const core::ffi::c_void, + context, + std::ptr::null(), + ); + } + 1 +} + +/// A fault in a guarded call: the exception code. +#[derive(Clone, Copy, Debug)] +struct Fault(u32); + +/// Calls `f(a, b)` under the guard. +/// +/// # Safety +/// `f` is a function taking two integer arguments, callable here. +unsafe fn guarded(f: usize, a: usize, b: usize) -> Result { + let mut out = 0u64; + // SAFETY: forwarded from the caller; `out` lives across the call. + match unsafe { victory_route_guard(f, a, b, &mut out) } { + 0 => Ok(out), + code => Err(Fault(code)), + } +} + +/// What a native handler is given. +#[repr(C)] +struct NativeContext { + args: *mut u64, + ret: *mut u64, + argc: i32, + retc: i32, +} + +/// The id the handler at `at` writes in its cold block, if it has the +/// usual shape. +/// +/// # Safety +/// `at` and the 0x50 bytes after it, and its cold block, are mapped code. +unsafe fn handler_id(at: usize) -> Option { + // SAFETY: as the caller promises. + let code = unsafe { std::slice::from_raw_parts(at as *const u8, 0x50) }; + let o = code + .windows(4) + .position(|w| w == [0x83, 0x79, 0x10, 0x00])?; + let mut cold = None; + for k in o + 4..(o + 16).min(code.len() - 6) { + if code[k] == 0x78 { + cold = Some(at as isize + k as isize + 2 + code[k + 1] as i8 as isize); + break; + } + if code[k] == 0x0f && code[k + 1] == 0x88 { + let rel = i32::from_le_bytes([code[k + 2], code[k + 3], code[k + 4], code[k + 5]]); + cold = Some(at as isize + k as isize + 6 + rel as isize); + break; + } + } + let cold = cold? as usize; + // SAFETY: the cold block is code of the same function (checked by the + // caller to be in the image). + let block = unsafe { std::slice::from_raw_parts(cold as *const u8, 24) }; + (0..14) + .find(|&k| matches!(block[k], 0x48 | 0x49) && (0xb8..=0xbf).contains(&block[k + 1])) + .map(|k| { + let mut id = [0u8; 8]; + id.copy_from_slice(&block[k + 2..k + 10]); + u64::from_le_bytes(id) + }) +} + +/// Calls a native: `args` its cells; the first result cells back. +fn call(n: Native, args: &[u64]) -> Result<[u64; 4], RouteError> { + let base = BASE.load(Ordering::Relaxed); + let handler = if n.id == PLAYER_PED_ID.id { + TRAMPOLINE.load(Ordering::Relaxed) + } else { + base + n.rva + }; + let mut cells = [0u64; 32]; + cells[..args.len()].copy_from_slice(args); + let mut ret = [0u64; 16]; + let mut ctx = NativeContext { + args: cells.as_mut_ptr(), + ret: ret.as_mut_ptr(), + argc: args.len() as i32, + retc: 4, + }; + // SAFETY: a handler checked at start to be this native's; the context + // and its cells live across the call. + unsafe { guarded(handler, &mut ctx as *mut NativeContext as usize, 0) } + .map_err(|f| RouteError::Fault(n.name, f))?; + Ok([ret[0], ret[1], ret[2], ret[3]]) +} + +/// Why a route stops. +#[derive(Debug)] +enum RouteError { + Fault(&'static str, Fault), + Failed(String), +} + +impl std::fmt::Display for RouteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RouteError::Fault(name, Fault(code)) => write!( + f, + "{name} faulted (exception {code:#010x} at {:#x})", + FAULT_AT.load(Ordering::Relaxed) + ), + RouteError::Failed(why) => f.write_str(why), + } + } +} + +type Step = Result; + +/// A script entity reference (two cells); all zero is none. +#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] +struct Entity([u64; 2]); + +impl Entity { + fn valid(self) -> bool { + self.0 != [0, 0] + } +} + +fn f(v: f32) -> u64 { + u64::from(v.to_bits()) +} + +fn int(v: i32) -> u64 { + u64::from(v as u32) +} + +fn flag(v: bool) -> u64 { + u64::from(v) +} + +/// A vector: x and y in the first cell, z in the second. +fn vector(x: f32, y: f32, z: f32) -> [u64; 2] { + [f(x) | f(y) << 32, f(z)] +} + +fn cells_of(parts: &[&[u64]]) -> Vec { + parts.concat() +} + +/// The game's one-at-a-time hash of a lower-case name. +const fn joaat(name: &[u8]) -> u32 { + let mut h = 0u32; + let mut i = 0; + while i < name.len() { + h = h.wrapping_add(name[i].to_ascii_lowercase() as u32); + h = h.wrapping_add(h << 10); + h ^= h >> 6; + i += 1; + } + h = h.wrapping_add(h << 3); + h ^= h >> 11; + h.wrapping_add(h << 15) +} + +fn player() -> Step { + let r = call(PLAYER_PED_ID, &[])?; + Ok(Entity([r[0], r[1]])) +} + +fn coords(e: Entity) -> Step<(f32, f32, f32)> { + let r = call(GET_ENTITY_COORDS, &[e.0[0], e.0[1], 0])?; + Ok(( + f32::from_bits(r[0] as u32), + f32::from_bits((r[0] >> 32) as u32), + f32::from_bits(r[1] as u32), + )) +} + +/// The ground's height under (x, y), once it has streamed in. +fn ground_z(x: f32, y: f32) -> Step> { + let mut z = 0f32; + let mut normal = [0f32; 4]; + let v = vector(x, y, 1000.0); + // The native writes through plain pointers (float*, vector*). + let r = call( + GET_GROUND_Z, + &[ + v[0], + v[1], + &mut z as *mut f32 as u64, + normal.as_mut_ptr() as u64, + ], + )?; + Ok((r[0] & 0xff != 0).then_some(z)) +} + +fn set_invincible(e: Entity) -> Step<()> { + call(SET_ENTITY_INVINCIBLE, &[e.0[0], e.0[1], flag(true)]).map(drop) +} + +fn freeze(e: Entity, on: bool) -> Step<()> { + call(FREEZE_ENTITY_POSITION, &[e.0[0], e.0[1], flag(on)]).map(drop) +} + +fn teleport(e: Entity, x: f32, y: f32, z: f32) -> Step<()> { + let v = vector(x, y, z); + call( + SET_ENTITY_COORDS, + &[e.0[0], e.0[1], v[0], v[1], 0, 0, 0, 0, f(-1.0)], + ) + .map(drop) +} + +fn vehicle_of(ped: Entity) -> Step { + let r = call(GET_VEHICLE_PED_IS_USING, &[ped.0[0], ped.0[1], 0])?; + Ok(Entity([r[0], r[1]])) +} + +fn seat(ped: Entity, vehicle: Entity) -> Step<()> { + call( + SET_PED_INTO_VEHICLE, + &[ped.0[0], ped.0[1], vehicle.0[0], vehicle.0[1], int(-1)], + ) + .map(drop) +} + +/// Noon, the clock stopped, and clear (`sunny`) weather held, for the +/// same light on every run. SET_CLOCK_TIME and SET_WEATHER_TYPE are +/// behaviour-checked in the NativeDB; PAUSE_CLOCK is corroborated. +fn fix_time_and_weather() -> Step<()> { + call(SET_CLOCK_TIME, &[int(12), int(0), int(0), flag(false)])?; + call(PAUSE_CLOCK, &[flag(true), flag(false)])?; + // instant, and held until CLEAR_WEATHER_TYPE_PERSIST + call( + SET_WEATHER_TYPE, + &[ + u64::from(joaat(b"sunny")), + flag(true), + flag(true), + flag(false), + f(0.0), + flag(false), + flag(false), + ], + )?; + // No police: a chase (the flight and the spawned car can draw one) would + // make every run different. + call(SET_MAX_WANTED_LEVEL, &[int(0)])?; + tracing::info!("bench route: time 12:00 (clock paused), weather sunny (held), no wanted level"); + Ok(()) +} + +// --------------------------------------------------------------------------- +// Spawning +// --------------------------------------------------------------------------- + +/// Whether `len` bytes at `at` are committed, readable memory. +fn readable(at: u64, len: usize) -> bool { + if at < 0x10000 || at.checked_add(len as u64).is_none() { + return false; + } + let mut page = at & !0xfff; + while page < at + len as u64 { + // SAFETY: a plain struct, all zero is valid. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a query about an address; `info` is ours. + let got = unsafe { + VirtualQuery( + page as *const _, + &mut info, + size_of::(), + ) + }; + if got == 0 + || info.State != MEM_COMMIT + || info.Protect & (PAGE_GUARD | PAGE_NOACCESS) != 0 + || info.Protect & 0xee == 0 + { + return false; + } + page += 0x1000; + } + true +} + +/// A value of the game's memory, if readable. +fn read(at: u64) -> Option { + // SAFETY: committed and readable (checked just before). + readable(at, size_of::()).then(|| unsafe { (at as *const T).read_unaligned() }) +} + +fn read_bytes(at: u64, out: &mut [u8]) -> bool { + if !readable(at, out.len()) { + return false; + } + // SAFETY: committed and readable (checked just before). + unsafe { std::ptr::copy_nonoverlapping(at as *const u8, out.as_mut_ptr(), out.len()) }; + true +} + +/// The game's TLS slot holding its per-thread block (found on a script +/// thread; -1 before). +static TLS_SLOT: AtomicI64 = AtomicI64::new(-1); + +fn tls_array() -> u64 { + let array: u64; + // SAFETY: reads this thread's TLS array pointer from its TEB. + unsafe { std::arch::asm!("mov {}, gs:[0x58]", out(reg) array, options(nostack, readonly)) }; + array +} + +/// The game's TLS block of this thread: the slot whose block holds, at +/// +0x1478, a script context with its vtable in the game image (and one at +/// +0x1470), as ViceHook finds it. +fn game_block() -> Option { + let array = tls_array(); + let slot = TLS_SLOT.load(Ordering::Relaxed); + if slot >= 0 { + return read::(array + slot as u64 * 8).filter(|b| *b != 0); + } + let base = BASE.load(Ordering::Relaxed) as u64; + let size = image_size(base as usize)? as u64; + for slot in 0..64u64 { + let Some(block) = read::(array + slot * 8).filter(|b| *b != 0) else { + continue; + }; + let context = read::(block + 0x1478).filter(|c| *c != 0); + let vtable = context.and_then(read::); + let other = read::(block + 0x1470).filter(|c| *c != 0); + if vtable.is_some_and(|v| v >= base && v < base + size) && other.is_some() { + TLS_SLOT.store(slot as i64, Ordering::Relaxed); + tracing::info!(slot, "bench route: the game's TLS block found"); + return Some(block); + } + } + None +} + +/// The calling script program: `[block + 0x1478]->vtbl[4]()`. +fn current_program() -> Step { + let fail = || RouteError::Failed("no script program on this thread".into()); + let block = game_block().ok_or_else(fail)?; + let context = read::(block + 0x1478) + .filter(|c| *c != 0) + .ok_or_else(fail)?; + let get = read::(context) + .and_then(|vt| read::(vt + 4 * 8)) + .ok_or_else(fail)?; + // SAFETY: the context's own method, called with it, as the game's task + // builder does. + unsafe { guarded(get as usize, context as usize, 0) } + .map_err(|f| RouteError::Fault("the script context", f)) +} + +/// The calling program's token for a task type: its type ranges are 24-byte +/// entries {module, ?, first token, end} at program +0x148 (count at +/// +0x144); a module's 136-byte type records are at [module + 0x30], the +/// type's hash at +0x10 of each. +fn token_for(type_hash: u64) -> Step { + let program = current_program()?; + let none = || RouteError::Failed("no vehicle task type in this script program".into()); + let table = read::(program + 0x148).ok_or_else(none)?; + let count = read::(program + 0x144).ok_or_else(none)?; + let mut records = vec![0u8; 136 * 4096]; + for i in 0..count.min(64) { + let entry = table + u64::from(i) * 24; + let (Some(module), Some(first), Some(end)) = ( + read::(entry), + read::(entry + 16), + read::(entry + 20), + ) else { + continue; + }; + let Some(recs) = read::(module + 0x30) else { + continue; + }; + let mut at = first; + while at < end { + let n = (end - at).min(4096); + let buf = &mut records[..n as usize * 136]; + if !read_bytes(recs + u64::from(at - first) * 136, buf) { + break; + } + if let Some(k) = buf + .chunks_exact(136) + .position(|r| r[0x10..0x18] == type_hash.to_le_bytes()) + { + return Ok(at + k as u32); + } + at += n; + } + } + Err(none()) +} + +/// Where a strong handle points now (the GC moves objects): [block + +/// 0x1470] -> [+0x1610] + slot * [+0x161C], each slot `object | 1 << 56`. +fn resolve_strong(handle: u32) -> Option { + let context = read::(game_block()? + 0x1470)?; + let slots = read::(context + 0x1610)?; + let stride = read::(context + 0x161c)?; + let v = read::(slots + u64::from((handle >> 4) & 0xff_ffff) * u64::from(stride))?; + Some(v & 0x00ff_ffff_ffff_ffff) +} + +/// A vehicle being made: the create task, held strongly. +struct Spawning { + holder: Box<[u64; 4]>, + frames: u32, +} + +/// Starts making a Blista at (x, y, z) facing `heading`. +fn spawn_blista(x: f32, y: f32, z: f32, heading: f32) -> Step { + let token = token_for(VEHICLE_TASK)?; + // The 96-byte block as the game's own calls fill it: model at +0x00, no + // setup (-1) at +0x1C, position at +0x20, heading at +0x30, flags + // 0x10100 at +0x38, -1.0f at +0x54; then the cancel token (0) and the + // type token. + let p = vector(x, y, z); + let mut cells = [0u64; 14]; + cells[0] = BLISTA; + cells[3] = 0xffff_ffff << 32; + cells[4] = p[0]; + cells[5] = p[1]; + cells[6] = f(heading); + cells[7] = 0x10100; + cells[10] = 0xbf80_0000_0000_0000; + cells[13] = u64::from(token); + let task = call(CREATE_VEHICLE, &cells)?[0]; + let mut holder = Box::new([0u64; 4]); + let base = BASE.load(Ordering::Relaxed); + if !readable(task, 0x40) { + return Err(RouteError::Failed( + "the vehicle create native gave no task".into(), + )); + } + // SAFETY: the game's strong-handle helper, with a holder of ours and + // the task the create native returned. + unsafe { guarded(base + PIN, holder.as_mut_ptr() as usize, task as usize) } + .map_err(|f| RouteError::Fault("holding the create task", f))?; + if holder[0] as u32 == 0 { + return Err(RouteError::Failed( + "the vehicle create task could not be held".into(), + )); + } + Ok(Spawning { holder, frames: 0 }) +} + +impl Spawning { + /// The vehicle, once made. Task layout: status byte +0x12 (5 done), + /// +0x20 error (0 when none), +0x28 the entity reference. + fn poll(&mut self) -> Step> { + self.frames += 1; + let mut q = [0u64; 8]; + let done = resolve_strong(self.holder[0] as u32).is_some_and(|at| { + // SAFETY: plain bytes; the array is ours. + let bytes = unsafe { std::slice::from_raw_parts_mut(q.as_mut_ptr().cast::(), 64) }; + read_bytes(at, bytes) && (q[2] >> 16) & 0xff == 5 + }); + if !done { + if self.frames > SPAWN_FRAMES { + // A task still running stays held (a small leak): releasing + // a running task corrupts the heap. + return Err(RouteError::Failed(format!( + "the vehicle was not made in {SPAWN_FRAMES} frames" + ))); + } + return Ok(None); + } + let base = BASE.load(Ordering::Relaxed); + // SAFETY: the game's release helper, with our holder; only once the + // task is done (an early release corrupted the heap). + unsafe { guarded(base + UNPIN, self.holder.as_mut_ptr() as usize, 0) } + .map_err(|f| RouteError::Fault("releasing the create task", f))?; + if q[4] != 0 { + return Err(RouteError::Failed("the game refused the vehicle".into())); + } + let vehicle = Entity([q[5], q[6]]); + if !vehicle.valid() { + return Err(RouteError::Failed("the vehicle create gave none".into())); + } + Ok(Some(vehicle)) + } +} + +// --------------------------------------------------------------------------- +// The routes +// --------------------------------------------------------------------------- + +enum Phase { + /// Until the player is in the world. + WaitPlayer, + /// The settling time after it. + Settle(Instant), + /// The route's first steps. + Setup, + /// downtown: the Blista being made near the player. + FlySpawn(Spawning), + Fly(Flight), + /// drive: the player held high over the start until the ground loads. + DriveGround(Instant), + /// drive: the Blista being made at the start (at the ground height given). + DriveSpawn(Spawning, f32), + Drive(Drive), + Stopped, +} + +struct Flight { + mover: Entity, + start: Instant, + /// The smoothed ground height (none until first found). + ground: Option, + laps: u32, +} + +struct Drive { + car: Entity, + model: u32, + /// The ground height at the start, for the waypoints' height. + ground: f32, + /// The waypoint driven to. + goal: usize, + legs: u32, + tasked: bool, + leg_start: Instant, + logged: Instant, + reseats: u32, + last_reseat: Option, +} + +struct Driver { + route: Route, + phase: Phase, + /// The elected game script thread, and the frame it was last seen. + chosen: Option<(i64, i64)>, + election: Option<(i64, Vec<(i64, i64, i64)>)>, +} + +impl Driver { + fn new(route: Route) -> Driver { + Driver { + route, + phase: Phase::WaitPlayer, + chosen: None, + election: None, + } + } + + /// Whether `thread` is the one to step in, at `frame` (ViceHook's + /// election: the thread calling on the most of 60 frames). + fn elected(&mut self, frame: i64, thread: i64) -> bool { + if let Some((id, seen)) = self.chosen { + if thread == id { + self.chosen = Some((id, frame)); + return true; + } + if frame - seen < LOST_FRAMES { + return false; + } + tracing::info!( + thread = id, + "bench route: the game script thread stopped; electing another" + ); + self.chosen = None; + } + let (start, seen) = self.election.get_or_insert_with(|| (frame, Vec::new())); + match seen.iter_mut().find(|s| s.0 == thread) { + Some(s) if s.2 != frame => { + s.1 += 1; + s.2 = frame; + } + Some(_) => {} + None => seen.push((thread, 1, frame)), + } + if frame - *start < ELECT_FRAMES { + return false; + } + let best = seen + .iter() + .max_by(|x, y| x.1.cmp(&y.1).then(y.0.cmp(&x.0))) + .map(|s| (s.0, s.1)); + let span = frame - *start; + let threads = seen.len(); + self.election = None; + let Some((id, frames)) = best else { + return false; + }; + self.chosen = Some((id, frame)); + tracing::info!( + thread = id, + frames, + of = span, + threads, + "bench route: runs in this game script thread" + ); + id == thread + } + + fn step(&mut self) -> Step<()> { + let phase = std::mem::replace(&mut self.phase, Phase::Stopped); + self.phase = match phase { + Phase::WaitPlayer => { + if player()?.valid() { + tracing::info!( + route = self.route.name(), + "bench route: the player is in the world; the route starts in {} s", + SETTLE.as_secs() + ); + Phase::Settle(Instant::now()) + } else { + Phase::WaitPlayer + } + } + Phase::Settle(since) if since.elapsed() < SETTLE => Phase::Settle(since), + Phase::Settle(_) => Phase::Setup, + Phase::Setup => self.setup()?, + Phase::FlySpawn(mut spawning) => { + let me = player()?; + match spawning.poll() { + Ok(None) => Phase::FlySpawn(spawning), + Ok(Some(car)) => { + seat(me, car)?; + Phase::Fly(start_flight(car)?) + } + Err(e @ RouteError::Failed(_)) => { + tracing::warn!("bench route: downtown: {e}; flying the player on foot"); + Phase::Fly(start_flight(me)?) + } + Err(e) => return Err(e), + } + } + Phase::Fly(mut flight) => { + flight.step()?; + Phase::Fly(flight) + } + Phase::DriveGround(since) => { + let (x, y) = bench::DRIVE_WAYPOINTS[0]; + let v = vector(x, y, DRIVE_HOLD_Z - 200.0); + call(REQUEST_COLLISION_AT_COORD, &[v[0], v[1]])?; + match ground_z(x, y)? { + Some(z) => { + // The player beside the start, the car on it. + let me = player()?; + teleport(me, x + 3.0, y, z + 1.0)?; + freeze(me, false)?; + let (nx, ny) = bench::DRIVE_WAYPOINTS[1]; + let heading = bench::heading((x, y), (nx, ny)); + Phase::DriveSpawn(spawn_blista(x, y, z + 0.5, heading)?, z) + } + None if since.elapsed() > GROUND_WAIT => { + return Err(RouteError::Failed(format!( + "the ground at the start did not load in {} s", + GROUND_WAIT.as_secs() + ))); + } + None => Phase::DriveGround(since), + } + } + Phase::DriveSpawn(mut spawning, ground) => match spawning.poll()? { + None => Phase::DriveSpawn(spawning, ground), + Some(car) => { + let me = player()?; + seat(me, car)?; + set_invincible(car)?; + let model = call(GET_ENTITY_MODEL, &[car.0[0], car.0[1]])?[0] as u32; + let (x, y) = bench::DRIVE_WAYPOINTS[0]; + tracing::info!( + "bench route: drive: start at ({x:.0}, {y:.0}), a loop of {} waypoints, the game's AI driving with traffic", + bench::DRIVE_WAYPOINTS.len() + ); + bench::set_route_started(); + let now = Instant::now(); + Phase::Drive(Drive { + car, + model, + ground, + goal: 1, + legs: 0, + tasked: false, + leg_start: now, + logged: now, + reseats: 0, + last_reseat: Some(now), + }) + } + }, + Phase::Drive(mut drive) => { + drive.step()?; + Phase::Drive(drive) + } + Phase::Stopped => Phase::Stopped, + }; + Ok(()) + } + + fn setup(&mut self) -> Step { + fix_time_and_weather()?; + let me = player()?; + set_invincible(me)?; + Ok(match self.route { + Route::Downtown => { + let (x, y, z) = coords(me)?; + match spawn_blista(x + 5.0, y, z + 0.5, 0.0) { + Ok(spawning) => Phase::FlySpawn(spawning), + Err(e @ RouteError::Failed(_)) => { + tracing::warn!("bench route: downtown: {e}; flying the player on foot"); + Phase::Fly(start_flight(me)?) + } + Err(e) => return Err(e), + } + } + Route::Drive => { + let (x, y) = bench::DRIVE_WAYPOINTS[0]; + // Held over the start while the area streams in (from 800 m + // up its collision never loaded); the collision is asked for + // each frame until the ground is found. + freeze(me, true)?; + teleport(me, x, y, DRIVE_HOLD_Z)?; + tracing::info!( + "bench route: drive: waiting for the ground at ({x:.0}, {y:.0}) to load" + ); + Phase::DriveGround(Instant::now()) + } + }) + } +} + +/// The downtown flight's start: `mover` (the car, or the player) made +/// invincible, without collision and frozen in place; then moved each frame. +fn start_flight(mover: Entity) -> Step { + set_invincible(mover)?; + call( + SET_ENTITY_COLLISION, + &[ + mover.0[0], + mover.0[1], + flag(false), + flag(false), + flag(false), + ], + )?; + freeze(mover, true)?; + let (x, y) = bench::DOWNTOWN_CORNER; + tracing::info!( + "bench route: downtown: start (corner {x:.0} {y:.0}, {:.0} m square, {:.0} m up, {:.0} m/s)", + bench::DOWNTOWN_SIDE, + bench::DOWNTOWN_UP, + bench::DOWNTOWN_SPEED + ); + bench::set_route_started(); + Ok(Flight { + mover, + start: Instant::now(), + ground: None, + laps: 0, + }) +} + +impl Flight { + /// One frame of the flight, as ViceMenu's `flybench`. + fn step(&mut self) -> Step<()> { + let t = self.start.elapsed().as_secs_f32(); + let ((x, y), heading, laps) = bench::downtown_at(t); + // Follow the ground, smoothed; the last height where it has not + // streamed in yet. + if let Some(g) = ground_z(x, y)? { + self.ground = Some(self.ground.map_or(g, |h| h + (g - h) * 0.05)); + } + let z = bench::downtown_height(self.ground); + let p = vector(x, y, z); + let e = self.mover; + call( + SET_ENTITY_COORDS_NO_OFFSET, + &cells_of(&[&e.0, &p, &[0, 0, 0, f(0.0)]]), + )?; + call(SET_ENTITY_HEADING, &[e.0[0], e.0[1], f(heading)])?; + call(SET_CAM_RELATIVE, &[f(bench::downtown_sweep(t)), f(-0.15)])?; + if laps != self.laps { + self.laps = laps; + tracing::info!("bench route: downtown: lap {laps} at {t:.0} s"); + } + Ok(()) + } +} + +impl Drive { + /// One frame of the drive, as ViceMenu's `stresstest`. + fn step(&mut self) -> Step<()> { + let now = Instant::now(); + let me = player()?; + // The car the player is in (references to it need not compare + // equal to the one the create gave). + let car = vehicle_of(me)?; + if !car.valid() { + // (Also the first frames after being seated.) + if self + .last_reseat + .is_some_and(|t| now.duration_since(t) < Duration::from_secs(2)) + { + return Ok(()); + } + let exists = call(DOES_ENTITY_EXIST, &[self.car.0[0], self.car.0[1]])?[0] & 0xff != 0; + if !exists || self.reseats >= 10 { + return Err(RouteError::Failed( + "the player is out of the route's car and cannot be put back".into(), + )); + } + self.reseats += 1; + self.last_reseat = Some(now); + tracing::warn!( + times = self.reseats, + "bench route: drive: the player left the car; seated again" + ); + seat(me, self.car)?; + self.tasked = false; + return Ok(()); + } + let (gx, gy) = bench::DRIVE_WAYPOINTS[self.goal]; + if !self.tasked { + set_invincible(car)?; + call(SET_DRIVER_ABILITY, &[me.0[0], me.0[1], f(1.0)])?; + // The waypoints are near the start's height (as `stresstest` + // gives its own). + let goal = vector(gx, gy, self.ground); + call( + TASK_VEHICLE_DRIVE_TO_COORD, + &cells_of(&[ + &me.0, + &car.0, + &goal, + &[ + f(30.0), + int(1), + u64::from(self.model), + int(1_074_528_293), + f(25.0), + f(-1.0), + ], + ]), + )?; + self.tasked = true; + } + let (x, y, _) = coords(car)?; + let dist = ((x - gx).powi(2) + (y - gy).powi(2)).sqrt(); + let taken = now.duration_since(self.leg_start); + if dist < REACHED_M || taken > LEG_LIMIT { + tracing::info!( + "bench route: drive: leg {} to ({gx:.0}, {gy:.0}) {} in {:.0} s", + self.legs, + if dist < REACHED_M { + "reached" + } else { + "skipped" + }, + taken.as_secs_f32() + ); + self.legs += 1; + self.goal = (self.goal + 1) % bench::DRIVE_WAYPOINTS.len(); + if self + .legs + .is_multiple_of(bench::DRIVE_WAYPOINTS.len() as u32) + { + tracing::info!( + "bench route: drive: lap {} done", + self.legs / bench::DRIVE_WAYPOINTS.len() as u32 + ); + } + self.leg_start = now; + self.tasked = false; + } + if now.duration_since(self.logged) > Duration::from_secs(30) { + let speed = f32::from_bits(call(GET_ENTITY_SPEED, &[car.0[0], car.0[1]])?[0] as u32); + tracing::info!( + "bench route: drive: leg {}, {dist:.0} m to go, {:.0} km/h at ({x:.0}, {y:.0})", + self.legs, + speed * 3.6 + ); + self.logged = now; + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// The tick +// --------------------------------------------------------------------------- + +fn int_result(n: Native) -> Step { + Ok(i64::from(call(n, &[])?[0] as u32 as i32)) +} + +/// Once per game frame, in the elected script thread: one step of the route. +fn tick() { + let frame = match int_result(GET_FRAME_COUNT) { + Ok(f) => f, + Err(e) => return stop(&e), + }; + if frame == LAST_FRAME.load(Ordering::Relaxed) { + return; + } + let thread = match int_result(GET_ID_OF_THIS_THREAD) { + Ok(t) if t > 0 => t, + Ok(_) => return, + Err(e) => return stop(&e), + }; + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(driver) = state.as_mut() else { + return; + }; + if !driver.elected(frame, thread) { + return; + } + LAST_FRAME.store(frame, Ordering::Relaxed); + if let Err(e) = driver.step() { + driver.phase = Phase::Stopped; + drop(state); + stop(&e); + } +} + +/// Ends the route after `e`; a benchmark run goes on, timed from now if +/// the route had not started. +fn stop(e: &RouteError) { + if !DONE.swap(true, Ordering::Relaxed) { + tracing::warn!("bench route: stopped: {e}"); + bench::set_route_started(); + } +} + +/// In front of PLAYER_PED_ID's handler. +unsafe extern "system" fn player_ped_id(ctx: *mut NativeContext) { + // SAFETY: the game passes its native context. + let query = unsafe { (*ctx).argc } < 0; + if !query + && !DONE.load(Ordering::Relaxed) + && TICKING + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + { + if std::panic::catch_unwind(tick).is_err() { + stop(&RouteError::Failed("a step panicked".into())); + } + TICKING.store(false, Ordering::Release); + } + let original = TRAMPOLINE.load(Ordering::Relaxed); + // SAFETY: the trampoline runs the handler's displaced head, then the + // rest of it, with the game's context. + unsafe { + std::mem::transmute::(original)(ctx) + }; +} + +fn image_size(base: usize) -> Option { + static SIZE: OnceLock = OnceLock::new(); + if let Some(s) = SIZE.get() { + return Some(*s); + } + let pe = base as u64 + u64::from(read::(base as u64 + 0x3c)?); + let size = read::(pe + 24 + 56)? as usize; + Some(*SIZE.get_or_init(|| size)) +} + +/// Hooks PLAYER_PED_ID's handler when `VICTORY_BENCH_ROUTE` names a route. +/// On another game build, or with a handler not as expected, the route is +/// left off (a benchmark run then goes on without it). +/// +/// # Safety +/// The image of `size` bytes at `base` stays mapped and nothing of it runs +/// yet. +pub unsafe fn apply_asked(base: usize, size: usize) { + let Some(asked) = std::env::var("VICTORY_BENCH_ROUTE") + .ok() + .filter(|v| !v.trim().is_empty()) + else { + return; + }; + let give_up = |why: &str| { + tracing::warn!(route = %asked, "bench route: off: {why}"); + bench::set_route_started(); + }; + let Some(route) = bench::route() else { + return give_up("not a route (downtown or drive)"); + }; + // The PE header's timestamp. + let stamp = (|| { + let pe = base as u64 + u64::from(read::(base as u64 + 0x3c)?); + read::(pe + 8) + })(); + if stamp != Some(BUILD) { + return give_up("the routes know game build 1.0.2.1 only"); + } + for n in ALL { + if n.rva + 0x100 > size { + return give_up("a native handler is outside the image"); + } + // SAFETY: inside the mapped image (checked above); the cold block a + // handler jumps to is near it, also in the image's code. + let id = unsafe { handler_id(base + n.rva) }; + if id != Some(n.id) { + return give_up(&format!("{} is not where 1.0.2.1 has it", n.name)); + } + } + let at = base + PLAYER_PED_ID.rva; + // SAFETY: inside the mapped image (checked above). + let head = unsafe { std::slice::from_raw_parts(at as *const u8, PLAYER_PED_ID_PROLOGUE.len()) }; + if head != PLAYER_PED_ID_PROLOGUE { + return give_up("PLAYER_PED_ID's handler is already changed (another hook?)"); + } + let jump = |to: usize| -> [u8; 14] { + let mut j = [0xff, 0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + j[6..].copy_from_slice(&(to as u64).to_le_bytes()); + j + }; + // SAFETY: a fresh page of our own for the trampoline. + let trampoline = unsafe { + VirtualAlloc( + std::ptr::null(), + 64, + MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE, + ) + } + .cast::(); + if trampoline.is_null() { + return give_up("no memory for the hook"); + } + // SAFETY: our page: the displaced head, then a jump back after it. + unsafe { + std::ptr::copy_nonoverlapping(head.as_ptr(), trampoline, head.len()); + let back = jump(at + head.len()); + std::ptr::copy_nonoverlapping(back.as_ptr(), trampoline.add(head.len()), back.len()); + } + BASE.store(base, Ordering::Relaxed); + TRAMPOLINE.store(trampoline as usize, Ordering::Relaxed); + *STATE.lock().unwrap_or_else(|e| e.into_inner()) = Some(Driver::new(route)); + let patch = jump(player_ped_id as unsafe extern "system" fn(*mut NativeContext) as usize); + let mut old = 0; + // SAFETY: the handler's head (checked above), made writable for the + // write and put back; nothing of the image runs yet. + unsafe { + if VirtualProtect( + at as *const _, + patch.len(), + PAGE_EXECUTE_READWRITE, + &mut old, + ) == 0 + { + return give_up(&format!( + "the handler would not become writable (error {})", + GetLastError() + )); + } + std::ptr::copy_nonoverlapping(patch.as_ptr(), at as *mut u8, patch.len()); + VirtualProtect(at as *const _, patch.len(), old, &mut old); + FlushInstructionCache(GetCurrentProcess(), at as *const _, patch.len()); + } + tracing::info!( + route = route.name(), + natives = ALL.len(), + "bench route: natives checked, the route runs from the game's script tick (PLAYER_PED_ID)" + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vectors_take_two_cells() { + let v = vector(1.0, 2.0, 3.0); + assert_eq!(v[0] as u32, 1.0f32.to_bits()); + assert_eq!((v[0] >> 32) as u32, 2.0f32.to_bits()); + assert_eq!(v[1], u64::from(3.0f32.to_bits())); + assert_eq!(int(-1), 0xffff_ffff); + } +} diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 45549355..0db32d26 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -21,6 +21,8 @@ //! point on a thread with the stack size the image asks for; from then //! on, pass every thread start and end on to the attached images. +#[cfg(windows)] +pub mod bench_route; #[cfg(windows)] mod console_insn; mod crash; diff --git a/run.sh b/run.sh index d999fb60..c1b2e705 100755 --- a/run.sh +++ b/run.sh @@ -3,7 +3,7 @@ mapfile -d '' given < <(env -0) restart_env=() for kv in "${given[@]}"; do - case "$kv" in VICTORY_BENCH=*|VICTORY_BENCH_MINUTES=*) ;; *) restart_env+=("$kv");; esac + case "$kv" in VICTORY_BENCH=*|VICTORY_BENCH_MINUTES=*|VICTORY_BENCH_ROUTE=*) ;; *) restart_env+=("$kv");; esac done source "$(dirname "$(readlink -f "$0")")/env.sh" mode=$1; shift @@ -138,7 +138,7 @@ if [ "$mode" = play ] && [[ ${VICTORY_BENCH:-} =~ ^(rt|nort)$ ]]; then benchdir=$root/local/benchmark/$(date +%Y%m%d-%H%M%S)-$bench mkdir -p "$benchdir" export VICTORY_BENCH_DIR=$(win "$benchdir") - echo "Benchmark (ray tracing $([ "$bench" = rt ] && echo on || echo off)): the game closes itself after $VICTORY_BENCH_MINUTES min of frames. Results: $benchdir" + echo "Benchmark (ray tracing $([ "$bench" = rt ] && echo on || echo off)${VICTORY_BENCH_ROUTE:+, route $VICTORY_BENCH_ROUTE}): the game closes itself after $VICTORY_BENCH_MINUTES min of frames. Results: $benchdir" fi if [ "${MUTE:-0}" = 1 ]; then source "$root/tools/mute.sh"; mute; fi # lsfg-vk (Lossless Scaling frame generation, a Vulkan layer) only when asked for, by naming the profile @@ -307,7 +307,7 @@ if [ -n "$bench" ] && [ -z "$again" ]; then fi if [ -n "$again" ]; then restart_args=() - for kv in "$@"; do case "$kv" in VICTORY_BENCH=*|VICTORY_BENCH_MINUTES=*) ;; *) restart_args+=("$kv");; esac; done + for kv in "$@"; do case "$kv" in VICTORY_BENCH=*|VICTORY_BENCH_MINUTES=*|VICTORY_BENCH_ROUTE=*) ;; *) restart_args+=("$kv");; esac; done [[ $next =~ ^(rt|nort):([0-9]+)$ ]] && restart_args+=("VICTORY_BENCH=${BASH_REMATCH[1]}" "VICTORY_BENCH_MINUTES=${BASH_REMATCH[2]}") echo "Restarting the game..." # Let the old session give its memory back first: the RAM cap of the next diff --git a/tools/bench-results.sh b/tools/bench-results.sh index 52bd2ea4..bc52a3e7 100755 --- a/tools/bench-results.sh +++ b/tools/bench-results.sh @@ -45,6 +45,7 @@ Version: ${version:-you: git log -1 in the build folder} Upscaler: $fsr Render: 2560x1440 upscaled to a 3840x2160 output Ray tracing: $([ "$rt" = rt ] && echo On || echo Off) +Route: ${s[route]:-none (free roam)} Frame generation, RSR, NIS: none you: also check nothing in your driver or desktop adds them (AFMF, lsfg-vk, gamescope upscaling).