From 2d1a3ec6b7c0681ecb4a08c36fdd69e23850ce82 Mon Sep 17 00:00:00 2001 From: port-um local Date: Fri, 4 Dec 2026 20:17:59 -0600 Subject: [PATCH 1/2] Benchmark routes: VICTORY_BENCH_ROUTE=downtown|drive Two fixed, reproducible routes built into the layer, so every machine benchmarks the same places the same way without mods (game 1.0.2.1). - victory-loader bench_route: a minimal script-native caller. Handlers are found by their 1.0.2.1 offsets and each checked by the id its cold block writes; PLAYER_PED_ID's handler is hooked for a per-frame tick in one elected game script thread (the approach of ViceHook, MIT). Every call goes through an SEH-guarded stub: a fault stops the route, not the game. Nothing is hooked without the variable. - downtown: a noclip flight over a 2400 m square at (-2600, -1000), 30 m/s, 40 m over the smoothed ground, camera sweeping, in a Blista: the city's densest blocks (found by a frame-rate scout over the map). - drive: the game's AI drives a Blista around a loop on the roads in the hills from (-2556, 6948), with traffic (about 3.5 min a lap). - Both set 12:00 (clock paused), held sunny weather and no wanted level. - With VICTORY_BENCH, the run is timed from the route's start (nothing skipped) and bench_stats.txt names the route; run.sh does not carry the route over into the restart after a benchmark. Co-Authored-By: Claude Opus 5.5 --- README.md | 34 + apps/victory/src/run.rs | 8 + crates/victory-core/src/bench.rs | 150 +++ crates/victory-gpu/src/bench.rs | 30 +- crates/victory-loader/src/bench_route.rs | 1273 ++++++++++++++++++++++ crates/victory-loader/src/lib.rs | 2 + run.sh | 6 +- tools/bench-results.sh | 1 + 8 files changed, 1500 insertions(+), 4 deletions(-) create mode 100644 crates/victory-loader/src/bench_route.rs 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). From 24abbb25cc3807e613025d6255e7daa702638e67 Mon Sep 17 00:00:00 2001 From: goldfishdev Date: Sat, 5 Dec 2026 11:00:50 -0600 Subject: [PATCH 2/2] Benchmark routes: accepted gate revision --- README.md | 66 ++-- THIRD-PARTY.md | 38 ++ crates/victory-core/src/bench.rs | 116 ++++-- crates/victory-gpu/src/bench.rs | 217 +++++++++++- crates/victory-loader/src/bench_route.rs | 431 ++++++++++++++++++----- docs/SETTINGS.md | 1 + run.sh | 12 + tools/bench-results.sh | 42 ++- 8 files changed, 777 insertions(+), 146 deletions(-) create mode 100644 THIRD-PARTY.md diff --git a/README.md b/README.md index 89bc3218..12a19000 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,7 @@ existing `local/menu.conf` is migrated once, with a backup at | `VICTORY_FSR_4K` | unset | FSR 4 (or FSR 3.1 fallback on RDNA 2/3) to the output size; requires `CONSOLE=series-x` and `./setup.sh fsr4` | | `VICTORY_FIDELITYFX_FRAMEGEN` | unset | AMD frame generation over FSR 4 (or FSR 3.1 fallback on RDNA 2/3); `4`: experimental ML frame generation (FSR FG 4.x from the driver, direct path only; RDNA 4, run `./setup.sh win11` once for a Windows 11 prefix, and an amdxc64.dll shim with MLFG support from GE-Proton 11, Proton-EM 10.0-33+ or proton-cachyos (`./setup.sh fsr4` picks it); without it, falls back to the built-in 3.x generator on the direct path, never the proxy) | | `VICTORY_BVH_BUILDER` | `1` | `0`: no ray tracing | +| `VICTORY_BENCH_ROUTE` | unset | `downtown`, or the experimental `drive`; see [Benchmark routes](#benchmark-routes) | | `VICTORY_CARD_PULL` | unset | `0`: CPU reads GPU memory; `1`: GPU copies; unset auto | | `VICTORY_PANEL` | `full` | `full`, `compact`, `fps`, `off`; `F3` hides, `Shift+F3` steps | | `VICTORY_LOG` | `info` | `info`, `warn`, `error`, `off` | @@ -200,7 +201,9 @@ mouse-lock keys, DualSense/DualShock details and controller settings are in `rt` runs with ray tracing on, `nort` with it off. `VICTORY_BENCH_MINUTES` sets the length: 1 to 240, default 5. The run uses Series X, FSR 4 Quality to 3840x2160, no frame generation, intro skipped and the full panel. -The `F1` menu's benchmark rows start the same run. +The `F1` menu's benchmark rows start the same run. Benchmark runs force +`VICTORY_FRAME_INTERVAL_MS=0`, so a play cap in `run.conf` or the title's +settings does not limit the measured frame rate. Enter (and the first controller's A) is pressed once a second from 5 to 65 seconds. The game closes after the requested time. For runs of 2 minutes or @@ -216,34 +219,54 @@ 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=nort VICTORY_BENCH_MINUTES=6 VICTORY_BENCH_ROUTE=downtown +./run.sh play VICTORY_BENCH=rt VICTORY_BENCH_MINUTES=6 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. +VIctory (no mods needed). Downtown aims to show runs on different machines the +same places; drive is an experimental demo. Coordinates are fixed in the code, +not taken from your save. +After a 15 second settle, each route waits for the ground at its start to +stream in (downtown at the corner, drive over the start) and for the car to be +made; the route clock starts after that setup, so its start is about 15 +seconds plus load time after the player appears. It sets the time to 12:00 with +the clock paused and the weather to clear (`sunny`, held), allows no wanted +level (a police chase would make runs differ), and makes the player invincible. +Use downtown against downtown for comparable figures; the drive route is an +experimental demo whose path and scenes vary from run to run. - `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. + way every 6 seconds. One lap is about 5 min 20 s; the default 5 minute run + stops before the lap ends, so set `VICTORY_BENCH_MINUTES=6` for a full lap. +- `drive`: **experimental, not comparable.** The player is put at -2556, + 6948 in a Dinka Blista, and the game's own AI drives to -2405, 6862.5, a + vehicle-node point, turns around and comes back, with traffic on. The AI + may take a different road each time: in the six-minute gate run, legs took + 111, 31 and 63 seconds, and another leg had passed 155 seconds when the run + ended; the first lap took 142 seconds, and the next was not finished after + more than 218 seconds. The earlier -2399, 7172 to -2566, 7202 leg left the + road network and drove into trees; the vehicle-node query found no road at + either point. A leg not done in 600 seconds stops the route instead of + skipping it, but a normal 6-minute run ends well before that, so a stuck + experimental-drive run can still report `ran`; use downtown for gate + comparisons. Each leg's log line has its time and distance; keep those lines + with the result, and do not compare drive figures across machines. 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. +starts; the first 30 seconds of the route are left out, and +`bench_stats.txt` names the route and says whether it ran or stopped. 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 start (another game build, a fault in a +game call, a failed spawn) is not recorded as a route: the benchmark is timed +and skipped as a normal run. A failure after setup has begun to change the +world (a ground or spawn timeout, a refused car) is marked +`route_status=failed_after_setup`; that run is not comparable and should not +be submitted. A route that stops after starting is recorded as +`route_status=stopped`; the game may then be in an inconsistent state, so +restart it. The routes need game build 1.0.2.1 (Xbox Series) and do not mix with ViceHook, which hooks the same game function. @@ -296,4 +319,5 @@ cxy0072019-sketch and [gassy](https://codeberg.org/erry/coasting/src/branch/sex) ## License -GPL-3.0-or-later. See [LICENSE](LICENSE). +GPL-3.0-or-later. See [LICENSE](LICENSE). Third-party notices are in +[THIRD-PARTY.md](THIRD-PARTY.md). diff --git a/THIRD-PARTY.md b/THIRD-PARTY.md new file mode 100644 index 00000000..5a021ec2 --- /dev/null +++ b/THIRD-PARTY.md @@ -0,0 +1,38 @@ +# Third-party notices + +## ViceHook + +Parts of `crates/victory-loader/src/bench_route.rs` follow ViceHook's script +hook, native-call guard, thread election and spawn implementation +(, MIT). + +MIT License + +Copyright (c) 2026 Ethan Aldrich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## Native database + +The native ids, names and argument layouts in `bench_route.rs` follow the +GTA VI NativeDB from ScriptHook VI +(), licensed under CC BY 4.0 +(), as carried by ViceHook's +`sdk/inc/natives.h`. The MIT text above covers ViceHook's own code; the +database is attributed here separately. diff --git a/crates/victory-core/src/bench.rs b/crates/victory-core/src/bench.rs index 7be9d13e..fbdf00cc 100644 --- a/crates/victory-core/src/bench.rs +++ b/crates/victory-core/src/bench.rs @@ -5,12 +5,17 @@ //! //! `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. +//! with a route, the run's clock starts when the route does; the first +//! [`ROUTE_SKIPPED_SECONDS`] of route frames are left out of its figures. /// Minutes at the start left out of the figures (loading and menus), in /// runs of at least twice this. pub const SKIPPED_SECONDS: f64 = 60.0; +/// Seconds at the start of a route left out of its figures: streaming and +/// first-use work, kept out of cross-machine comparisons. +pub const ROUTE_SKIPPED_SECONDS: f64 = 30.0; + /// Whether this process is a benchmark run. pub fn running() -> bool { std::env::var("VICTORY_BENCH").is_ok_and(|v| v == "rt" || v == "nort") @@ -60,8 +65,9 @@ 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`: experimental. The game's AI drives the player's car to a fixed + /// road point and back, with traffic, but may choose different roads; its + /// measured scenes and lap times are not comparable between runs. Drive, } @@ -94,16 +100,55 @@ pub fn route() -> Option { }) } -static ROUTE_STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static ROUTE_STATE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(RouteState::Pending as u8); -/// 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); +/// How the route asked for stands in a benchmark run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum RouteState { + /// Asked for, not started yet. + Pending, + /// Under way at the end of the run. + Running, + /// Could not start: another build, a handler mismatch, or a fault before + /// the route began. A benchmark run then goes on as a normal one. + Failed, + /// Failed after setup had begun to change the world (time, weather, + /// invincibility, player position). The run is not a normal free-roam + /// benchmark and its figures are not comparable. + FailedAfterSetup, + /// Ran, then stopped early. + Stopped, } -/// Whether the route asked for has started (or gave up). -pub fn route_started() -> bool { - ROUTE_STARTED.load(std::sync::atomic::Ordering::Relaxed) +/// Sets how the route stands. +pub fn set_route_state(state: RouteState) { + ROUTE_STATE.store(state as u8, std::sync::atomic::Ordering::Relaxed); +} + +/// How the route asked for stands. +pub fn route_state() -> RouteState { + match ROUTE_STATE.load(std::sync::atomic::Ordering::Relaxed) { + x if x == RouteState::Running as u8 => RouteState::Running, + x if x == RouteState::Failed as u8 => RouteState::Failed, + x if x == RouteState::FailedAfterSetup as u8 => RouteState::FailedAfterSetup, + x if x == RouteState::Stopped as u8 => RouteState::Stopped, + _ => RouteState::Pending, + } +} + +/// Starts the route only if it is still pending. A concurrent failure (for +/// example the benchmark's wait timeout) wins; the caller must stop. +pub fn try_start_route() -> bool { + ROUTE_STATE + .compare_exchange( + RouteState::Pending as u8, + RouteState::Running as u8, + std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, + ) + .is_ok() } /// The `downtown` flight: the square's corner (x, y), the ground height the @@ -115,12 +160,11 @@ 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 `drive` route's two points (absolute map x, y), driven in order and +/// around again; the car starts at the first, facing the second. The second +/// is a vehicle-node point, but the AI may take different roads to it; the +/// route is experimental and its scenes are not comparable between runs. +pub const DRIVE_WAYPOINTS: [(f32, f32); 2] = [(-2556.0, 6948.0), (-2405.0, 6862.5)]; /// The game's heading (degrees, 0 north, counter-clockwise) of travel from /// `from` to `to`. @@ -202,12 +246,30 @@ impl Recorder { /// The figures, leaving out the first `skip` seconds of frames. pub fn summary_skipping(&self, skip: f64) -> Option { + self.summary_between(skip, None) + } + + /// The figures, leaving out the first `skip` seconds and any frame that + /// starts at or after `end` seconds. + pub fn summary_between(&self, skip: f64, end: Option) -> Option { let mut at = 0.0; - let first = self.frames.iter().position(|dt| { - at += dt; - at > skip - })?; - let frames = &self.frames[first..]; + let frames: Vec = self + .frames + .iter() + .copied() + .filter(|dt| { + let start = at; + at += dt; + at > skip && end.is_none_or(|end| start < end) + }) + .collect(); + Self::summarize(&frames) + } + + fn summarize(frames: &[f64]) -> Option { + if frames.is_empty() { + return None; + } let seconds: f64 = frames.iter().sum(); let average = frames.len() as f64 / seconds; let mut sorted = frames.to_vec(); @@ -278,6 +340,17 @@ mod tests { assert_eq!(Recorder::default().summary(), None); } + #[test] + fn a_stopped_run_ends_at_the_stop_time() { + let mut r = Recorder::default(); + (0..100).for_each(|_| r.add(0.1)); + let s = r.summary_between(1.0, Some(5.0)).unwrap(); + assert!((40..=41).contains(&s.frames)); + assert!((s.seconds - 4.0).abs() < 0.11); + let s = r.summary_between(0.0, Some(5.0)).unwrap(); + assert!((50..=51).contains(&s.frames)); + } + #[test] fn routes_are_named_as_documented() { assert_eq!(Route::parse("downtown"), Some(Route::Downtown)); @@ -308,5 +381,6 @@ mod tests { #[test] fn the_drive_starts_toward_the_first_leg() { assert!(heading(DRIVE_WAYPOINTS[0], DRIVE_WAYPOINTS[1]) < 0.0); + assert_eq!(DRIVE_WAYPOINTS.len(), 2); } } diff --git a/crates/victory-gpu/src/bench.rs b/crates/victory-gpu/src/bench.rs index db58c68f..4cab7064 100644 --- a/crates/victory-gpu/src/bench.rs +++ b/crates/victory-gpu/src/bench.rs @@ -4,15 +4,15 @@ //! (`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. +//! route's start, after [`bench::ROUTE_SKIPPED_SECONDS`] of route warm-up; a +//! route that cannot start is not recorded as one and the run is timed and +//! skipped as a normal benchmark. use std::path::PathBuf; use std::sync::Mutex; use std::time::{Duration, Instant}; -use victory_core::bench::{self, Recorder}; +use victory_core::bench::{self, Recorder, Route, RouteState}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -29,6 +29,75 @@ struct Run { frames: Recorder, vram_peak: u64, ram_peak: u64, + /// Seconds from the route's start to the frame the route stopped on. + route_stopped_at: Option, +} + +/// How a run's route frames are summarized and labelled. +#[derive(Debug, PartialEq)] +struct RouteAccounting { + ran: bool, + failed: bool, + invalid: bool, + status: &'static str, + skip: f64, + end: Option, +} + +/// The accounting for a requested route and its final state. +fn route_accounting( + route: Option, + state: RouteState, + stopped_at: Option, +) -> RouteAccounting { + if route.is_none() { + return RouteAccounting { + ran: false, + failed: false, + invalid: false, + status: "none", + skip: 0.0, + end: None, + }; + } + match state { + RouteState::Pending | RouteState::Failed => RouteAccounting { + ran: false, + failed: true, + invalid: false, + status: "failed", + skip: 0.0, + end: None, + }, + RouteState::FailedAfterSetup => RouteAccounting { + ran: false, + failed: true, + invalid: true, + status: "failed_after_setup", + skip: 0.0, + end: None, + }, + RouteState::Running => RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "ran", + skip: bench::ROUTE_SKIPPED_SECONDS, + end: None, + }, + RouteState::Stopped => RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "stopped", + skip: if stopped_at.is_some_and(|stopped| stopped < bench::ROUTE_SKIPPED_SECONDS) { + 0.0 + } else { + bench::ROUTE_SKIPPED_SECONDS + }, + end: stopped_at, + }, + } } static RUN: Mutex> = Mutex::new(None); @@ -54,18 +123,34 @@ pub(crate) fn presented(memory: impl FnOnce() -> (u64, u64)) { return; } let now = Instant::now(); + let route = bench::route(); 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; + if r.started.is_none() { + if route.is_some() { + match bench::route_state() { + RouteState::Pending => { + if now.duration_since(*r.first.get_or_insert(now)) < ROUTE_WAIT { + return; + } + tracing::warn!( + "benchmark: the route did not start in {} s; timing a normal run from now", + ROUTE_WAIT.as_secs() + ); + bench::set_route_state(RouteState::Failed); + } + RouteState::Failed | RouteState::FailedAfterSetup => {} + RouteState::Running | RouteState::Stopped => {} + } } - 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 = Some(now); + } + if route.is_some() + && r.route_stopped_at.is_none() + && bench::route_state() == RouteState::Stopped + && let Some(started) = r.started + { + r.route_stopped_at = Some(now.duration_since(started).as_secs_f64()); } - r.started.get_or_insert(now); if let Some(last) = r.last.replace(now) { r.frames.add(now.duration_since(last).as_secs_f64()); } @@ -167,13 +252,34 @@ pub(crate) fn finish(shot: Option) -> ! { } } let route = bench::route(); - if let Some(route) = route { - text.push_str(&format!("route={}\n", route.name())); - } + let state = bench::route_state(); with(|r| { - let summary = match route { - Some(_) => r.frames.summary_skipping(0.0), - None => r.frames.summary(), + if state == RouteState::Stopped + && r.route_stopped_at.is_none() + && let Some(started) = r.started + { + r.route_stopped_at = Some(started.elapsed().as_secs_f64()); + } + let accounting = route_accounting(route, state, r.route_stopped_at); + if accounting.ran { + let route = route.expect("checked above"); + text.push_str(&format!("route={}\n", route.name())); + text.push_str(&format!("route_status={}\n", accounting.status)); + if let Some(stopped) = r.route_stopped_at { + text.push_str(&format!("route_stopped_at={stopped:.1}\n")); + } + text.push_str(&format!("route_skip={:.0}\n", accounting.skip)); + } else if accounting.failed { + text.push_str("route_failed=1\n"); + text.push_str(&format!("route_status={}\n", accounting.status)); + if accounting.invalid { + text.push_str("route_invalid=1\n"); + } + } + let summary = if accounting.ran { + r.frames.summary_between(accounting.skip, accounting.end) + } else { + r.frames.summary() }; if let Some(s) = summary { text.push_str(&format!( @@ -262,3 +368,76 @@ fn png(width: u32, height: u32, raw: &[u8]) -> Vec { chunk(&mut png, b"IEND", &[]); png } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn route_accounting_covers_every_state_and_stop_time() { + let none = RouteAccounting { + ran: false, + failed: false, + invalid: false, + status: "none", + skip: 0.0, + end: None, + }; + assert_eq!(route_accounting(None, RouteState::Pending, None), none); + assert_eq!( + route_accounting(Some(Route::Downtown), RouteState::Failed, None), + RouteAccounting { + ran: false, + failed: true, + invalid: false, + status: "failed", + skip: 0.0, + end: None, + } + ); + assert_eq!( + route_accounting(Some(Route::Downtown), RouteState::FailedAfterSetup, None), + RouteAccounting { + ran: false, + failed: true, + invalid: true, + status: "failed_after_setup", + skip: 0.0, + end: None, + } + ); + assert_eq!( + route_accounting(Some(Route::Downtown), RouteState::Running, None), + RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "ran", + skip: 30.0, + end: None, + } + ); + assert_eq!( + route_accounting(Some(Route::Drive), RouteState::Stopped, Some(42.5)), + RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "stopped", + skip: 30.0, + end: Some(42.5), + } + ); + assert_eq!( + route_accounting(Some(Route::Drive), RouteState::Stopped, Some(10.0)), + RouteAccounting { + ran: true, + failed: false, + invalid: false, + status: "stopped", + skip: 0.0, + end: Some(10.0), + } + ); + } +} diff --git a/crates/victory-loader/src/bench_route.rs b/crates/victory-loader/src/bench_route.rs index b0449680..8ca0da1f 100644 --- a/crates/victory-loader/src/bench_route.rs +++ b/crates/victory-loader/src/bench_route.rs @@ -1,7 +1,8 @@ //! 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. +//! by the game's own script natives. Downtown aims to show every run the same +//! places; drive is experimental and its AI may choose different roads. 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). @@ -9,7 +10,8 @@ //! 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 id asked for. As in ViceHook (MIT), whose approach this follows; see +//! `THIRD-PARTY.md`. //! //! 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 @@ -18,7 +20,7 @@ //! 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. +//! with a log line; the game may already be left in an inconsistent state. //! //! Vehicles are made with the game's asynchronous create native, as //! ViceHook's `spawn.cpp` does: the calling script program's token for the @@ -29,7 +31,7 @@ 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 victory_core::bench::{self, Route, RouteState}; use windows_sys::Win32::Foundation::GetLastError; use windows_sys::Win32::System::Diagnostics::Debug::{ CONTEXT, EXCEPTION_RECORD, FlushInstructionCache, RtlUnwindEx, @@ -64,7 +66,6 @@ natives! { 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; @@ -96,31 +97,43 @@ const PLAYER_PED_ID_PROLOGUE: [u8; 14] = [ /// 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. +/// key of the Dinka Blista, and how long 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; +const SPAWN_WAIT: Duration = Duration::from_secs(30); /// 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; +/// How high the player is held over a route's start while its ground streams +/// in. +const HOLD_Z: f32 = 300.0; +/// The time constant of the flight's ground-follow smoothing, in seconds. +const GROUND_SMOOTH: f32 = 0.33; /// 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. +/// done in [`LEG_LIMIT`] stops the route, so its figures are not reported +/// as a completed route. The limit is well above the 31-155 s legs seen in +/// the experimental route, so normal traffic does not stop a run. const REACHED_M: f32 = 40.0; -const LEG_LIMIT: Duration = Duration::from_secs(180); +const LEG_LIMIT: Duration = Duration::from_secs(600); /// The longest the drive's start waits for the ground to stream in. const GROUND_WAIT: Duration = Duration::from_secs(60); +/// Whether a drive leg has run past its limit without reaching its goal. +fn leg_stalled(taken: Duration, dist: f32) -> bool { + dist >= REACHED_M && taken > LEG_LIMIT +} + static BASE: AtomicUsize = AtomicUsize::new(0); static TRAMPOLINE: AtomicUsize = AtomicUsize::new(0); static TICKING: AtomicBool = AtomicBool::new(false); +/// Setup has begun to change the world (time, weather, invincibility, +/// position); a failure from here on is not a clean free-roam run. +static SETUP_BEGAN: 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); @@ -128,6 +141,15 @@ static STATE: Mutex> = Mutex::new(None); /// Where the last fault caught by the guard was. static FAULT_AT: AtomicUsize = AtomicUsize::new(0); +/// Clears [`TICKING`] on every exit, including a Rust unwind out of the hook. +struct Ticking; + +impl Drop for Ticking { + fn drop(&mut self) { + TICKING.store(false, Ordering::Release); + } +} + // 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 @@ -235,9 +257,14 @@ struct NativeContext { /// 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. +/// `at` and the 0x50 bytes after it are mapped code in the image of `size` +/// bytes at `base`; its cold block is checked separately before it is read. +unsafe fn handler_id(base: usize, size: usize, at: usize) -> Option { + let image_end = base.checked_add(size)?; + if at < base || at.checked_add(0x50)? > image_end { + return None; + } + // SAFETY: as the caller promises, and checked above. let code = unsafe { std::slice::from_raw_parts(at as *const u8, 0x50) }; let o = code .windows(4) @@ -255,9 +282,13 @@ unsafe fn handler_id(at: usize) -> Option { } } 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) }; + if cold < base || cold.checked_add(24)? > image_end { + return None; + } + let mut block = [0u8; 24]; + if !read_bytes(cold as u64, &mut block) { + return None; + } (0..14) .find(|&k| matches!(block[k], 0x48 | 0x49) && (0xb8..=0xbf).contains(&block[k + 1])) .map(|k| { @@ -401,9 +432,11 @@ fn freeze(e: Entity, on: bool) -> Step<()> { fn teleport(e: Entity, x: f32, y: f32, z: f32) -> Step<()> { let v = vector(x, y, z); + // The no-offset form is the one the flight moves with; `SET_ENTITY_COORDS` + // left the player at its spawn point in the drive's start. call( - SET_ENTITY_COORDS, - &[e.0[0], e.0[1], v[0], v[1], 0, 0, 0, 0, f(-1.0)], + SET_ENTITY_COORDS_NO_OFFSET, + &cells_of(&[&e.0, &v, &[0, 0, 0, f(0.0)]]), ) .map(drop) } @@ -602,8 +635,24 @@ fn resolve_strong(handle: u32) -> Option { /// A vehicle being made: the create task, held strongly. struct Spawning { - holder: Box<[u64; 4]>, - frames: u32, + /// The strong handle, if it is still ours to release. + holder: Option>, + since: Instant, + /// The strong handle was released (or the task never got one). + released: bool, +} + +impl Drop for Spawning { + fn drop(&mut self) { + if !self.released { + // A task still running stays held: releasing it corrupts the + // heap, and the helper may still refer to the holder, so keep + // both alive (a small leak) rather than free the box. + if let Some(holder) = self.holder.take() { + std::mem::forget(holder); + } + } + } } /// Starts making a Blista at (x, y, z) facing `heading`. @@ -633,42 +682,59 @@ fn spawn_blista(x: f32, y: f32, z: f32, heading: f32) -> Step { } // 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 let Err(f) = unsafe { guarded(base + PIN, holder.as_mut_ptr() as usize, task as usize) } { + // The helper may have written a handle before it faulted; keep the + // holder alive rather than free memory the game might still mean. + std::mem::forget(holder); + return Err(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 }) + Ok(Spawning { + holder: Some(holder), + since: Instant::now(), + released: false, + }) } 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 - }); + let done = self + .holder + .as_ref() + .and_then(|holder| resolve_strong(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. + if self.since.elapsed() > SPAWN_WAIT { return Err(RouteError::Failed(format!( - "the vehicle was not made in {SPAWN_FRAMES} frames" + "the vehicle was not made in {} s", + SPAWN_WAIT.as_secs() ))); } return Ok(None); } let base = BASE.load(Ordering::Relaxed); + let Some(holder) = self.holder.as_mut() else { + return Err(RouteError::Failed( + "the vehicle create task lost its holder".into(), + )); + }; // 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) } + unsafe { guarded(base + UNPIN, holder.as_mut_ptr() as usize, 0) } .map_err(|f| RouteError::Fault("releasing the create task", f))?; + self.released = true; if q[4] != 0 { return Err(RouteError::Failed("the game refused the vehicle".into())); } @@ -691,7 +757,9 @@ enum Phase { Settle(Instant), /// The route's first steps. Setup, - /// downtown: the Blista being made near the player. + /// downtown: the player held at the corner until the ground loads. + FlyGround(Instant), + /// downtown: the Blista being made at the corner. FlySpawn(Spawning), Fly(Flight), /// drive: the player held high over the start until the ground loads. @@ -705,6 +773,8 @@ enum Phase { struct Flight { mover: Entity, start: Instant, + /// The last frame's time, for time-based ground smoothing. + last: Instant, /// The smoothed ground height (none until first found). ground: Option, laps: u32, @@ -731,6 +801,10 @@ struct Driver { /// The elected game script thread, and the frame it was last seen. chosen: Option<(i64, i64)>, election: Option<(i64, Vec<(i64, i64, i64)>)>, + /// The route has started (the vehicle is ready and the route clock is on). + started: bool, + /// The elected thread ended after the route started. + thread_lost: bool, } impl Driver { @@ -740,6 +814,8 @@ impl Driver { phase: Phase::WaitPlayer, chosen: None, election: None, + started: false, + thread_lost: false, } } @@ -754,6 +830,10 @@ impl Driver { if frame - seen < LOST_FRAMES { return false; } + if self.started || SETUP_BEGAN.load(Ordering::Relaxed) { + self.thread_lost = true; + return false; + } tracing::info!( thread = id, "bench route: the game script thread stopped; electing another" @@ -800,7 +880,7 @@ impl Driver { if player()?.valid() { tracing::info!( route = self.route.name(), - "bench route: the player is in the world; the route starts in {} s", + "bench route: the player is in the world; setup starts in {} s", SETTLE.as_secs() ); Phase::Settle(Instant::now()) @@ -811,19 +891,37 @@ impl Driver { Phase::Settle(since) if since.elapsed() < SETTLE => Phase::Settle(since), Phase::Settle(_) => Phase::Setup, Phase::Setup => self.setup()?, + Phase::FlyGround(since) => { + let (x, y) = bench::DOWNTOWN_CORNER; + let v = vector(x, y, HOLD_Z - 200.0); + call(REQUEST_COLLISION_AT_COORD, &[v[0], v[1]])?; + match ground_z(x, y)? { + Some(z) => { + // The player beside the corner, the car on it. + let me = player()?; + teleport(me, x + 3.0, y, z + 1.0)?; + freeze(me, false)?; + Phase::FlySpawn(spawn_blista(x, y, z + 0.5, 0.0)?) + } + None if since.elapsed() > GROUND_WAIT => { + return Err(RouteError::Failed(format!( + "the ground at the corner did not load in {} s", + GROUND_WAIT.as_secs() + ))); + } + None => Phase::FlyGround(since), + } + } Phase::FlySpawn(mut spawning) => { let me = player()?; - match spawning.poll() { - Ok(None) => Phase::FlySpawn(spawning), - Ok(Some(car)) => { + match spawning.poll()? { + None => Phase::FlySpawn(spawning), + Some(car) => { seat(me, car)?; - Phase::Fly(start_flight(car)?) + let flight = start_flight(car)?; + self.started = true; + Phase::Fly(flight) } - 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) => { @@ -832,7 +930,7 @@ impl Driver { } Phase::DriveGround(since) => { let (x, y) = bench::DRIVE_WAYPOINTS[0]; - let v = vector(x, y, DRIVE_HOLD_Z - 200.0); + let v = vector(x, y, HOLD_Z - 200.0); call(REQUEST_COLLISION_AT_COORD, &[v[0], v[1]])?; match ground_z(x, y)? { Some(z) => { @@ -865,7 +963,12 @@ impl Driver { "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(); + if !bench::try_start_route() { + return Err(RouteError::Failed( + "the benchmark route state changed before start".into(), + )); + } + self.started = true; let now = Instant::now(); Phase::Drive(Drive { car, @@ -891,20 +994,26 @@ impl Driver { } fn setup(&mut self) -> Step { + if bench::route_state() != RouteState::Pending { + return Err(RouteError::Failed( + "the benchmark route state changed before setup".into(), + )); + } + SETUP_BEGAN.store(true, Ordering::Relaxed); 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), - } + let (x, y) = bench::DOWNTOWN_CORNER; + // Held at the corner while the area streams in; the collision + // is asked for each frame until the ground is found. + freeze(me, true)?; + teleport(me, x, y, HOLD_Z)?; + tracing::info!( + "bench route: downtown: waiting for the ground at ({x:.0}, {y:.0}) to load" + ); + Phase::FlyGround(Instant::now()) } Route::Drive => { let (x, y) = bench::DRIVE_WAYPOINTS[0]; @@ -912,7 +1021,7 @@ impl Driver { // 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)?; + teleport(me, x, y, HOLD_Z)?; tracing::info!( "bench route: drive: waiting for the ground at ({x:.0}, {y:.0}) to load" ); @@ -922,8 +1031,8 @@ impl Driver { } } -/// The downtown flight's start: `mover` (the car, or the player) made -/// invincible, without collision and frozen in place; then moved each frame. +/// The downtown flight's start: `mover` made invincible, without collision +/// and frozen in place; then moved each frame. fn start_flight(mover: Entity) -> Step { set_invincible(mover)?; call( @@ -937,6 +1046,11 @@ fn start_flight(mover: Entity) -> Step { ], )?; freeze(mover, true)?; + if !bench::try_start_route() { + return Err(RouteError::Failed( + "the benchmark route state changed before start".into(), + )); + } 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)", @@ -944,10 +1058,11 @@ fn start_flight(mover: Entity) -> Step { bench::DOWNTOWN_UP, bench::DOWNTOWN_SPEED ); - bench::set_route_started(); + let now = Instant::now(); Ok(Flight { mover, - start: Instant::now(), + start: now, + last: now, ground: None, laps: 0, }) @@ -956,12 +1071,16 @@ fn start_flight(mover: Entity) -> Step { impl Flight { /// One frame of the flight, as ViceMenu's `flybench`. fn step(&mut self) -> Step<()> { + let now = Instant::now(); let t = self.start.elapsed().as_secs_f32(); + let dt = now.duration_since(self.last).as_secs_f32(); + self.last = now; let ((x, y), heading, laps) = bench::downtown_at(t); - // Follow the ground, smoothed; the last height where it has not - // streamed in yet. + // Follow the ground, smoothed over time; 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 alpha = 1.0 - (-dt / GROUND_SMOOTH).exp(); + self.ground = Some(self.ground.map_or(g, |h| h + (g - h) * alpha)); } let z = bench::downtown_height(self.ground); let p = vector(x, y, z); @@ -1040,15 +1159,10 @@ impl Drive { 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 { + if dist < REACHED_M { tracing::info!( - "bench route: drive: leg {} to ({gx:.0}, {gy:.0}) {} in {:.0} s", + "bench route: drive: leg {} to ({gx:.0}, {gy:.0}) reached in {:.0} s", self.legs, - if dist < REACHED_M { - "reached" - } else { - "skipped" - }, taken.as_secs_f32() ); self.legs += 1; @@ -1064,6 +1178,12 @@ impl Drive { } self.leg_start = now; self.tasked = false; + } else if leg_stalled(taken, dist) { + return Err(RouteError::Failed(format!( + "the drive's leg {} to ({gx:.0}, {gy:.0}) was not reached in {} s", + self.legs, + LEG_LIMIT.as_secs() + ))); } 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); @@ -1087,6 +1207,10 @@ fn int_result(n: Native) -> Step { } /// Once per game frame, in the elected script thread: one step of the route. +/// +/// This runs on every PLAYER_ENTITY call, before the same-frame early-out, so +/// route runs include the two guarded frame/thread queries per call. Compare +/// route runs with route runs, not with free roam. fn tick() { let frame = match int_result(GET_FRAME_COUNT) { Ok(f) => f, @@ -1104,7 +1228,16 @@ fn tick() { let Some(driver) = state.as_mut() else { return; }; - if !driver.elected(frame, thread) { + let elected = driver.elected(frame, thread); + if driver.thread_lost { + driver.phase = Phase::Stopped; + drop(state); + stop(&RouteError::Failed( + "the game script thread ended after the route started".into(), + )); + return; + } + if !elected { return; } LAST_FRAME.store(frame, Ordering::Relaxed); @@ -1115,15 +1248,47 @@ fn tick() { } } -/// Ends the route after `e`; a benchmark run goes on, timed from now if -/// the route had not started. +/// Ends the route after `e`: a run that had started keeps its route label +/// and records a stop; a run that had not started is a failed route and the +/// benchmark continues as a normal one. fn stop(e: &RouteError) { if !DONE.swap(true, Ordering::Relaxed) { tracing::warn!("bench route: stopped: {e}"); - bench::set_route_started(); + let setup = SETUP_BEGAN.load(Ordering::Relaxed); + match bench::route_state() { + RouteState::Running => bench::set_route_state(RouteState::Stopped), + RouteState::Pending | RouteState::Failed if setup => { + bench::set_route_state(RouteState::FailedAfterSetup) + } + RouteState::Pending | RouteState::Failed => bench::set_route_state(RouteState::Failed), + RouteState::FailedAfterSetup | RouteState::Stopped => {} + } + // Best effort: put the player back under the game's control after any + // stop once setup began. It may still be in the route's car, or have + // been left in the air; the route may also have stopped on a fault. + if setup { + release_player(); + } } } +/// Undoes the player's freeze and collision changes, ignoring errors: the +/// route may already be in a bad state. The route's mover or car is not +/// restored here. +fn release_player() { + let Ok(me) = player() else { + return; + }; + if !me.valid() { + return; + } + let _ = call( + SET_ENTITY_COLLISION, + &[me.0[0], me.0[1], flag(true), flag(true), flag(true)], + ); + let _ = freeze(me, false); +} + /// 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. @@ -1134,10 +1299,10 @@ unsafe extern "system" fn player_ped_id(ctx: *mut NativeContext) { .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) .is_ok() { + let _ticking = Ticking; 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 @@ -1173,7 +1338,7 @@ pub unsafe fn apply_asked(base: usize, size: usize) { }; let give_up = |why: &str| { tracing::warn!(route = %asked, "bench route: off: {why}"); - bench::set_route_started(); + bench::set_route_state(RouteState::Failed); }; let Some(route) = bench::route() else { return give_up("not a route (downtown or drive)"); @@ -1190,9 +1355,9 @@ pub unsafe fn apply_asked(base: usize, size: usize) { 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) }; + // SAFETY: inside the mapped image (checked above); handler_id checks + // the cold block it follows is inside the image too. + let id = unsafe { handler_id(base, size, base + n.rva) }; if id != Some(n.id) { return give_up(&format!("{} is not where 1.0.2.1 has it", n.name)); } @@ -1270,4 +1435,104 @@ mod tests { assert_eq!(v[1], u64::from(3.0f32.to_bits())); assert_eq!(int(-1), 0xffff_ffff); } + + #[test] + fn a_handler_reads_the_id_in_its_cold_block() { + let mut code = vec![0u8; 0x60]; + code[..4].copy_from_slice(&[0x83, 0x79, 0x10, 0x00]); + code[4..6].copy_from_slice(&[0x0f, 0x88]); + // js rel32 from after the six-byte instruction to 0x40. + code[6..10].copy_from_slice(&(0x40i32 - 10).to_le_bytes()); + code[0x40..0x42].copy_from_slice(&[0x48, 0xb8]); + let id = 0x1122_3344_5566_7788u64; + code[0x42..0x4a].copy_from_slice(&id.to_le_bytes()); + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, Some(id)); + } + + #[test] + fn a_short_jump_and_a_second_register_encode_the_same_id() { + for (jump, opcode) in [ + (vec![0x78, (0x40i8 - 6) as u8], [0x48u8, 0xb8]), + (vec![0x0f, 0x88, 0x36, 0x00, 0x00, 0x00], [0x49, 0xba]), + ] { + let mut code = vec![0u8; 0x60]; + code[..4].copy_from_slice(&[0x83, 0x79, 0x10, 0x00]); + code[4..4 + jump.len()].copy_from_slice(&jump); + code[0x40..0x42].copy_from_slice(&opcode); + let id = 0x8877_6655_4433_2211u64; + code[0x42..0x4a].copy_from_slice(&id.to_le_bytes()); + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, Some(id)); + } + } + + #[test] + fn a_cold_block_outside_the_image_is_refused() { + let mut code = vec![0u8; 0x60]; + code[..4].copy_from_slice(&[0x83, 0x79, 0x10, 0x00]); + code[4..6].copy_from_slice(&[0x0f, 0x88]); + // js rel32 to 0x1000, well outside this 0x60-byte image. + code[6..10].copy_from_slice(&(0x1000i32 - 10).to_le_bytes()); + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, None); + } + + #[test] + fn a_handler_without_the_usual_head_is_refused() { + let code = vec![0u8; 0x60]; + let base = code.as_ptr() as usize; + // SAFETY: the test's own buffer is mapped and long enough. + assert_eq!(unsafe { handler_id(base, code.len(), base) }, None); + } + + #[test] + fn election_needs_sixty_frames_and_replaces_a_lost_thread() { + let mut driver = Driver::new(Route::Downtown); + for frame in 0..60 { + assert!(!driver.elected(frame, 7)); + } + assert!(driver.elected(60, 7)); + assert!(driver.elected(61, 7)); + assert!(!driver.elected(62, 8)); + assert!(!driver.elected(151, 8)); + for frame in 152..=210 { + assert!(!driver.elected(frame, 8)); + } + assert!(driver.elected(211, 8)); + } + + #[test] + fn losing_the_thread_after_start_is_reported() { + let mut driver = Driver::new(Route::Downtown); + for frame in 0..60 { + assert!(!driver.elected(frame, 7)); + } + assert!(driver.elected(60, 7)); + assert!(driver.elected(61, 7)); + driver.started = true; + assert!(!driver.elected(151, 8)); + assert!(driver.thread_lost); + } + + #[test] + fn a_fault_in_a_guarded_call_is_caught() { + unsafe extern "system" fn fault(_: usize, _: usize) -> u64 { + // SAFETY: deliberately unmapped; the guard is what is tested. + unsafe { std::ptr::read_volatile(1 as *const u64) } + } + // SAFETY: deliberately faults; the guard catches it. + let caught = unsafe { guarded(fault as *const () as usize, 0, 0) }; + assert!(matches!(caught, Err(Fault(_)))); + } + + #[test] + fn a_leg_is_stalled_only_after_the_limit_and_out_of_reach() { + assert!(!leg_stalled(Duration::from_secs(599), 100.0)); + assert!(leg_stalled(Duration::from_secs(601), 100.0)); + assert!(!leg_stalled(Duration::from_secs(601), REACHED_M - 1.0)); + } } diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index f9014047..c14de5e6 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -163,6 +163,7 @@ mentioned in its header. Diagnostics settings are listed under | `VICTORY_HAPTICS_LOG=1` | Logs haptic levels | | `VICTORY_BENCH_MINUTES` | Benchmark length: 1 to 240, default 5 | | `VICTORY_METER_OCCLUDED=1` | The frame meter also counts frames the swap chain did not show because the window is covered, for timing runs behind other windows. Off by default | +| `VICTORY_BENCH_ROUTE` | `downtown`, or the experimental `drive`: a route for benchmark runs; see [Benchmark routes](../README.md#benchmark-routes). Off without it | | `LSFGVK_PROFILE=` | [lsfg-vk](https://lsfg-vk.dev) 2.x frame generation with that profile from its `conf.toml`. Off by default | | `LSFG_PROCESS=` | The equivalent for lsfg-vk 1.0 | | `VERBOSE=1` | Turns Wine, vkd3d-proton and DXVK log lines back on | diff --git a/run.sh b/run.sh index c1b2e705..6d15a228 100755 --- a/run.sh +++ b/run.sh @@ -124,6 +124,16 @@ if [ -f "$root/run.conf" ]; then fi export VICTORY_MENU_FILE=$(win "$root/run.conf") VICTORY_MENU_STATE=$(win "$root/local") VICTORY_MENU_DEFS=$(win "$root/run.conf.default") for kv in "$@"; do case "$kv" in *=*) export "$kv";; esac; done +if [ "$mode" = play ] && [ -n "${VICTORY_BENCH_ROUTE:-}" ]; then + route=${VICTORY_BENCH_ROUTE} + route=${route#"${route%%[![:space:]]*}"} + route=${route%"${route##*[![:space:]]}"} + route=${route,,} + case "$route" in + downtown|drive) ;; + *) echo "VICTORY_BENCH_ROUTE must be downtown or drive (got '$VICTORY_BENCH_ROUTE')"; exit 1;; + esac +fi # A benchmark run (VICTORY_BENCH=rt|nort): PortWatch's settings over the # user's for this run only. bench= @@ -133,6 +143,8 @@ if [ "$mode" = play ] && [[ ${VICTORY_BENCH:-} =~ ^(rt|nort)$ ]]; then VICTORY_LOD_SCALE VICTORY_SMALL_CULL VICTORY_VEHICLE_LOD_BIAS VICTORY_QUAD_GUARD VICTORY_BVH_HARDWARE \ VICTORY_PLACED_COPIED VICTORY_KEEP_GPU_WRITTEN VICTORY_WARM LSFGVK_PROFILE LSFG_PROCESS export CONSOLE=series-x VICTORY_FSR_4K=quality VICTORY_OUTPUT=3840x2160 VICTORY_SKIP_BINK=1 VICTORY_PANEL=full + # A play cap (run.conf or the title's settings) must not limit a benchmark. + export VICTORY_FRAME_INTERVAL_MS=0 export VICTORY_BVH_BUILDER=$([ "$bench" = rt ] && echo 1 || echo 0) export VICTORY_BENCH_MINUTES=${VICTORY_BENCH_MINUTES:-5} benchdir=$root/local/benchmark/$(date +%Y%m%d-%H%M%S)-$bench diff --git a/tools/bench-results.sh b/tools/bench-results.sh index bc52a3e7..7ed8bf9d 100755 --- a/tools/bench-results.sh +++ b/tools/bench-results.sh @@ -28,9 +28,45 @@ ram=$(awk '/MemTotal/{printf "%.0f GB", $2/1048576}' /proc/meminfo) os=$(. /etc/os-release 2>/dev/null; echo "${PRETTY_NAME:-Linux}") version=$(git -C "$root" log -1 --format='%h (%cs)' 2>/dev/null) git -C "$root" diff --quiet HEAD 2>/dev/null || version="$version, with local changes" +if [ -n "${s[route]:-}" ]; then + route_skip=${s[route_skip]:-30} + if [ "$route_skip" = 0 ]; then + measured_note="no route warm-up is left out" + else + measured_note="the first ${route_skip} s of the route are left out" + fi + route_display=${s[route]} + if [ "${s[route_status]:-}" = stopped ]; then + banner="INCOMPLETE: route stopped at ${s[route_stopped_at]:-?} s after start; figures are cut at the stop." + else + banner="" + fi + # The drive route is experimental: its path and scenes vary between runs. + if [ "${s[route]}" = drive ]; then + if [ -n "$banner" ]; then + banner="$banner +EXPERIMENTAL: drive figures are not comparable; do not submit them." + else + banner="EXPERIMENTAL: drive figures are not comparable; do not submit them." + fi + fi +elif [ "${s[route_invalid]:-0}" = 1 ] || [ "${s[route_status]:-}" = failed_after_setup ]; then + measured_note="INVALID RUN: the route failed after setup; the run is not comparable and should not be submitted" + route_display="none (route failed after setup)" + banner="INVALID RUN: route failed after setup; do not submit these figures." +elif [ "${s[route_failed]:-0}" = 1 ]; then + measured_note="the route failed to start; the run is timed as a normal benchmark" + route_display="none (route failed to start)" + banner="" +else + measured_note="the first minute is left out of runs of 2 min or more" + route_display="none (free roam)" + banner="" +fi cat > "$dir/bench_results.txt" <