Benchmark routes: accepted gate revision

This commit is contained in:
goldfishdev
2026-12-05 11:00:50 -06:00
parent 2d1a3ec6b7
commit 24abbb25cc
8 changed files with 777 additions and 146 deletions

View File

@ -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).

38
THIRD-PARTY.md Normal file
View File

@ -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
(<https://github.com/0x000NULL/vicehook>, 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
(<https://github.com/modpapi/scripthook-vi>), licensed under CC BY 4.0
(<https://creativecommons.org/licenses/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.

View File

@ -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<Route> {
})
}
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<Summary> {
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<f64>) -> Option<Summary> {
let mut at = 0.0;
let first = self.frames.iter().position(|dt| {
at += dt;
at > skip
})?;
let frames = &self.frames[first..];
let frames: Vec<f64> = 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<Summary> {
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);
}
}

View File

@ -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<f64>,
}
/// 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<f64>,
}
/// The accounting for a requested route and its final state.
fn route_accounting(
route: Option<Route>,
state: RouteState,
stopped_at: Option<f64>,
) -> 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<Option<Run>> = 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<ReadBack>) -> ! {
}
}
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<u8> {
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),
}
);
}
}

View File

@ -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<Option<Driver>> = 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<u64> {
// 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<u64> {
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<u64> {
}
}
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<u64> {
/// 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<Box<[u64; 4]>>,
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<Spawning> {
}
// 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<Option<Entity>> {
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::<u8>(), 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::<u8>(), 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<f32>,
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<Phase> {
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<Flight> {
set_invincible(mover)?;
call(
@ -937,6 +1046,11 @@ fn start_flight(mover: Entity) -> Step<Flight> {
],
)?;
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<Flight> {
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<Flight> {
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<i64> {
}
/// 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));
}
}

View File

@ -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=<profile>` | [lsfg-vk](https://lsfg-vk.dev) 2.x frame generation with that profile from its `conf.toml`. Off by default |
| `LSFG_PROCESS=<entry>` | The equivalent for lsfg-vk 1.0 |
| `VERBOSE=1` | Turns Wine, vkd3d-proton and DXVK log lines back on |

12
run.sh
View File

@ -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

View File

@ -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" <<TXT
PortWatch Lab report: https://portwatch-vi.xyz/lab/#report
Copy each answer into the form. Lines marked "you:" are for you to answer.
$banner
== What you tested ==
Build: VIctory-xmem (lobomfz/VIctory-xmem in the list)
@ -45,7 +81,9 @@ 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)}
Route: $route_display
Route status: ${s[route_status]:-not applicable}
Route stop: ${s[route_stopped_at]:-not stopped}${s[route_stopped_at]:+ s after start}
Frame generation, RSR, NIS: none
you: also check nothing in your driver or desktop adds them
(AFMF, lsfg-vk, gamescope upscaling).
@ -60,7 +98,7 @@ Average: $(get average)
Lowest: $(get lowest) (slowest whole second)
Highest: $(get highest) (quickest whole second)
1% low: $(get low_1pct) (for your notes)
Measured: $(get seconds) s, $(get frames) frames (the first minute is left out of runs of 2 min or more;
Measured: $(get seconds) s, $(get frames) frames ($measured_note;
loading screens or menus after it are counted: say so, or run again)
Frame-time log: not made by this benchmark. The form takes PresentMon, CapFrameX or OCAT recordings.