Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ method, scope and caveats. No game data is included.

| Document | What it covers |
|---|---|
| [game_gate.md](game_gate.md) | The in-game gate for the D3D12 runtime: one command runs the game a set time in the world, stops it cleanly and writes `summary.json` (PASS/FAIL/ERROR, time to the world, warm cache, fps, crashes), the same on every machine. |
| [measuring_fps.md](measuring_fps.md) | How to measure frame rates of the D3D12 runtime (`d3d12/`): look in the findings first, turn a switch inside one run with `LEONIDA_AB`, separate runs, which log number means what, what to write before reporting a cause. |
| [d3d12/docs/findings.md](../d3d12/docs/findings.md) | What was measured of the D3D12 runtime's frame on several PCs: where a frame goes, switches by turns with their spread, what was not worth it, picture faults and what they were. |
| [d3d12/docs/switches.md](../d3d12/docs/switches.md) | The `LEONIDA_*` variables the D3D12 runtime names, made from its sources (`tools/d3d12_switches.py`): how each is read, whether `LEONIDA_AB` can turn it, the sentence of the code's comment. |
Expand Down
100 changes: 100 additions & 0 deletions docs/game_gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# The in-game gate

One command runs the D3D12 runtime (`leonida.exe`) in the game for a set time in the world and says PASS, FAIL or ERROR. The same way on every machine. It is what a change to the render path needs before merge ("300 s in the world, no device loss"). It also gives the numbers an A/B compares: one `summary.json` per run, in one format.

The script is `scripts/game-gate.ps1` (Windows, PowerShell 7). The parser is `tools/game_gate.py` (standard library only). The tests are in `tests/test_game_gate.py`.

## Running it

Build the runtime first (`d3d12\scripts\build-nvidia.ps1`). The gate refuses to start without `d3d12\target\diag\leonida.exe`, because the play script would build it inside the timed run.

Make a data template once:
1. Play to the place the runs should start from.
2. Let the title save, and close the game cleanly.
3. Copy `<Data>\data\<title id>` (its `saves` and `storage`) into a folder outside the checkout.

Each run gets a copy of it, so your own saves are never touched. A save is game data: never share or commit it.

```powershell
pwsh -NoProfile -File scripts\game-gate.ps1 run -Game <game folder> -Data <data folder> -DataTemplate <template> `
-Name base [-PlayArgs '<play-d3d12.ps1 switches>'] [-More 'LEONIDA_X=1;LEONIDA_KEYS=40:Enter,60:Enter'] [-WorldSeconds 300]
pwsh -NoProfile -File scripts\game-gate.ps1 start <same options> # detached: returns at once, prints the run folder
pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder>
```

- **The play script's switches.** `-PlayArgs` passes them on as they are, for example `-SeriesS -NoFrameGen`.
- **Reaching the world.** The gate does not drive the menus. Pass key presses with `LEONIDA_KEYS`; they are timed from the start of the process, so allow for the precompile.
- **The caches.** `-Data` keeps its caches (`cache-2`); only the saves are copied. The first start after a translator change translates every shader again: run once before measuring.
- **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45).
- **How it stops.** With `WM_SYSCOMMAND`/`SC_CLOSE`, the runtime's own end: the title is suspended and the pipeline cache saved. It kills the game only if it has not ended 60 s later.
- **Exit code.** 0 PASS, 1 FAIL, 2 ERROR. `start` exits when the detached run is created.

The run folder (under `-RunRoot`, by default `<Data>\gate-runs`, refused inside a checkout) holds:

| File | What |
| --- | --- |
| `run.json` | Name, start time, commit, exe hash, build features, card, driver, options |
| `launch.ps1` | How the game was started |
| `settings.txt` | The play script's `-DryRun` |
| `leonida-settings.txt` | The F1 menu file, when there was one (it changes every run, so the summary warns) |
| `launcher.txt` | The play script's output, with the precompile lines |
| `leonida.log` | The runtime's log, with `LEONIDA_LOG=info,leonida_gpu::frame=debug` (one line per present) |
| `events.jsonl` | What the gate did and saw: the game found, the stop asked for and why, a kill, the exit code |
| `data\` | The run's copy of the template, and the runtime's `crashes.log` |
| `summary.json` | The result, below |

## summary.json (`leonida-gate-summary/1`)

Times are seconds since the run started. The summary holds numbers, switch names and verdicts only. It never holds a path, a user or machine name, or text the title printed. A fault is told by the kind of module it was in, not by its name or address.

| Field | Meaning |
| --- | --- |
| `run` | Name, start time, commit, `dirty` (a tracked file changed), `untracked` (how many files git does not track), exe hash (16 hex), build features, card, driver, play arguments, `world_seconds` |
| `settings` | The `LEONIDA_*` settings from the runtime's `settings` line, as it shows them (folders hidden). Empty, with a warning, from a runtime without that line |
| `precompile` | From the launcher: shaders in the cache and the seconds that took, pipelines known, made before, to make, made, their seconds and median ms |
| `times.world_at_s` | The world: the first of two frame lines in a row with 500 draws a frame or more. Cutscenes count: a save that opens on one is in the world. Like every time here, it counts from the gate's start, so the precompile is in it (its seconds are `precompile.shaders_s` and `precompile.made_s`) |
| `times.warm_at_s` | From then on, 60 s in the world with no pipeline being made and no wait for one that ran out. Draws dropped for a pipeline the host never has go on all run long and do not count |
| `times.world_s` | Seconds from `world_at_s` to the stop request |
| `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning |
| `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once |
| `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes |
| `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` |
| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched`), whether it was killed, whether the cache was saved, whether the suspend was in time |
| `verdict` | `result`, `reasons`, `warnings`, `min_world_s` |

## The verdict

**PASS** needs all of these:
- at least `-WorldSeconds` (300) in the world;
- no device loss and no panic;
- no fault before the stop request;
- no gap over 10 s with no frame presented once in the world, so a run frozen on a pipeline compile does not pass;
- the game alive at the stop request: a frame line less than 30 s old.

**FAIL** comes with one or more reasons:
- `device_lost`: a host GPU failure, an out-of-memory command list that did not close, or exit 0x887A0005;
- `panic`;
- `fault_before_stop`;
- `exited_before_stop`;
- `present_gap`;
- `world_time_short`: the time limit came first;
- `not_alive_at_stop`;
- `world_not_reached`, when the game ended before reaching the world.

**ERROR** means the gate could not judge the build:
- `not_started`;
- `relaunched`: the title restarted itself;
- `stopped_early`: a STOP file before the time;
- `world_not_reached`, when the game was still in the menus at the time limit.

A crash after the stop request is a warning, except a device loss or a panic, which stay FAIL. A kill, a cache not saved and a late suspend are warnings too.

## Not in this version

- A driver for the menus and a fixed route (a Lua mod).
- An ABBA runner over several runs.
- A time series beside the summary (memory, census, reaping queue).
- A "memory rising" warning.
- VRAM and RAM peaks.
- The distance walked.
- The Vulkan runtime (`gta6rt`).
215 changes: 215 additions & 0 deletions scripts/game-gate.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
# The in-game gate for the D3D12 runtime (leonida.exe): one run, measured the same way on every machine.
#
# pwsh -NoProfile -File scripts\game-gate.ps1 run -Game <dir> -Data <dir> -DataTemplate <dir> -Name <label> [options]
# pwsh -NoProfile -File scripts\game-gate.ps1 start <same options> # the same, detached: returns at once, prints the run folder
# pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder> # asks a run to stop (a STOP file)
#
# It starts the game through this checkout's scripts\play-d3d12.ps1, so a run is what players run, and writes one
# folder per run under -RunRoot (default: <Data>\gate-runs): run.json, launch.ps1, settings.txt (the play script's
# -DryRun), leonida-settings.txt (the F1 menu file, when there is one), launcher.txt (the precompile lines),
# leonida.log (the runtime's log), events.jsonl (what this script did and saw), data\ (a copy of -DataTemplate, so
# the tester's own saves are never touched) and summary.json (tools\game_gate.py, schema in docs\game_gate.md).
#
# It stops the game with WM_SYSCOMMAND/SC_CLOSE (the runtime's own end: the title suspended, the pipeline cache
# saved) when -WorldSeconds were spent in the world, when a STOP file appears in the run folder, or after
# -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR.
# Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'.
param(
[Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb,
[string]$Game = '',
[string]$Data = '',
[string]$DataTemplate = '',
[string]$Name = '',
[string]$RunRoot = '',
[string]$RunDir = '',
[int]$WorldSeconds = 300,
[int]$MaxMinutes = 45,
[string]$More = '',
[string]$PlayArgs = '',
[string]$Python = ''
)
$ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot
$tool = Join-Path $repo 'tools\game_gate.py'
$play = Join-Path $repo 'scripts\play-d3d12.ps1'
$exe = Join-Path $repo 'd3d12\target\diag\leonida.exe'
$menuFile = Join-Path $repo 'd3d12\leonida-settings.txt'
if (-not $Python) { $Python = (Get-Command python -ErrorAction Stop).Source }

if ($Verb -eq 'stop') {
if (-not $RunDir -or -not (Test-Path (Join-Path $RunDir 'run.json'))) { throw "not a run folder: '$RunDir'" }
Set-Content (Join-Path $RunDir 'STOP') 'stop' -NoNewline
"asked $RunDir to stop"
exit 0
}

foreach ($p in 'Game', 'Data', 'DataTemplate', 'Name') {
if (-not (Get-Variable $p -ValueOnly)) { throw "-$p is needed" }
}
$Game = (Resolve-Path $Game).Path
$Data = (Resolve-Path $Data).Path
$DataTemplate = (Resolve-Path $DataTemplate).Path
if (-not $RunRoot) { $RunRoot = Join-Path $Data 'gate-runs' }
New-Item -ItemType Directory -Force $RunRoot | Out-Null
$RunRoot = (Resolve-Path $RunRoot).Path
# A run writes gigabytes of logs and a copy of the saves: never into a checkout.
if (($RunRoot + '\').StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "-RunRoot is inside the checkout: $RunRoot" }
if (-not (Test-Path $exe)) { throw "no ${exe}: build it first (d3d12\scripts\build-nvidia.ps1), the play script would build it inside the run" }
if (-not $RunDir) { $RunDir = Join-Path $RunRoot ('{0}-{1}' -f (Get-Date -Format 'yyyyMMdd-HHmmss'), ($Name -replace '[^\w.-]', '_')) }

function Get-RunningGame {
Get-CimInstance Win32_Process -Filter "Name='leonida.exe' OR Name='leonida_sm.exe'" |
Where-Object { $_.CommandLine -match '\srun\s' } | Select-Object -First 1
}

if ($Verb -eq 'start') {
if (Get-RunningGame) { throw 'a leonida run is already running' }
$pwsh = (Get-Process -Id $PID).Path
$quote = { param($s) '"' + ($s -replace '"', '\"') + '"' }
$line = @(& $quote $pwsh; '-NoProfile'; '-ExecutionPolicy'; 'Bypass'; '-File'; & $quote $PSCommandPath; 'run'
'-Game'; & $quote $Game; '-Data'; & $quote $Data; '-DataTemplate'; & $quote $DataTemplate; '-Name'; & $quote $Name
'-RunRoot'; & $quote $RunRoot; '-RunDir'; & $quote $RunDir; '-WorldSeconds'; $WorldSeconds; '-MaxMinutes'; $MaxMinutes
'-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python) -join ' '
# Created by Windows, not as a child of this shell: an agent's or a console's end does not end the run.
$startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 }
$made = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{
CommandLine = $line; CurrentDirectory = $repo; ProcessStartupInformation = $startup }
if ($made.ReturnValue -ne 0) { throw "starting the run failed ($($made.ReturnValue))" }
$RunDir
exit 0
}

# ---- run: the supervisor, in the foreground.
if (Get-RunningGame) { throw 'a leonida run is already running' }
New-Item -ItemType Directory -Force $RunDir | Out-Null
# A detached run has no console: what this script says, and any error, goes to supervisor.log.
Start-Transcript -Path (Join-Path $RunDir 'supervisor.log') -Append | Out-Null
$events = Join-Path $RunDir 'events.jsonl'
function Add-Event([string]$event, [hashtable]$fields = @{}) {
$e = [ordered]@{ t = (Get-Date).ToUniversalTime().ToString('o'); event = $event }
foreach ($k in $fields.Keys) { $e[$k] = $fields[$k] }
Add-Content $events ($e | ConvertTo-Json -Compress)
}

# The tester's saves, copied: the run plays from its own data folder (-More wins over the play script's own).
Copy-Item -Path (Join-Path $DataTemplate '*') -Destination (New-Item -ItemType Directory -Force (Join-Path $RunDir 'data')).FullName -Recurse
$hadMenuFile = Test-Path $menuFile
if ($hadMenuFile) { Copy-Item $menuFile (Join-Path $RunDir 'leonida-settings.txt') }

$settings = [ordered]@{
LEONIDA_DATA_DIR = (Join-Path $RunDir 'data')
LEONIDA_LOG = 'info,leonida_gpu::frame=debug'
}
foreach ($s in ($More -split ';' | Where-Object { $_ -match '=' })) { $k, $v = $s -split '=', 2; $settings[$k.Trim()] = $v.Trim() }
$moreText = ($settings.GetEnumerator() | ForEach-Object { " {0} = '{1}'" -f $_.Key, ($_.Value -replace "'", "''") }) -join "`n"
$launch = Join-Path $RunDir 'launch.ps1'
Set-Content $launch @"
# Written by scripts\game-gate.ps1: how this run started the game.
`$env:NO_COLOR = '1'
Set-Location '$repo'
`$settings = @{
$moreText
}
& '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args
"@

$gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1
$builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt'
[ordered]@{
name = $Name
started_utc = (Get-Date).ToUniversalTime().ToString('o')
commit = (git -C $repo rev-parse --short HEAD)
dirty = [bool](git -C $repo status --porcelain --untracked-files=no)
untracked = @(git -C $repo status --porcelain --untracked-files=normal | Where-Object { $_.StartsWith('??') }).Count
exe_sha16 = (Get-FileHash $exe -Algorithm SHA256).Hash.Substring(0, 16).ToLower()
built_with = if (Test-Path $builtWith) { (Get-Content $builtWith -Raw).Trim() } else { $null }
gpu = $gpu.Name
driver = $gpu.DriverVersion
play_args = $PlayArgs
world_seconds = $WorldSeconds
max_minutes = $MaxMinutes
f1_settings_file = $hadMenuFile
} | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json')

& pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt')
$launcher = Start-Process pwsh -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launch) -WindowStyle Hidden -PassThru `
-RedirectStandardOutput (Join-Path $RunDir 'launcher.txt') -RedirectStandardError (Join-Path $RunDir 'leonida.log')
Add-Event 'started' @{ launcher = $launcher.Id }

if (-not ('GateWindow' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
public static class GateWindow {
delegate bool EnumProc(IntPtr h, IntPtr l);
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; }
[DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
[DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out RECT r);
[DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint msg, IntPtr w, IntPtr l);
// WM_SYSCOMMAND/SC_CLOSE to the process's largest visible window: the runtime's end_title path. (A plain
// WM_CLOSE goes to the title's own window procedure, which does not end the run.)
public static bool Close(int pid) {
IntPtr best = IntPtr.Zero; long area = 0;
EnumWindows((h, l) => {
uint p; GetWindowThreadProcessId(h, out p);
RECT r;
if (p == (uint)pid && IsWindowVisible(h) && GetClientRect(h, out r)) {
long a = (long)(r.R - r.L) * (r.B - r.T);
if (a > area) { area = a; best = h; }
}
return true;
}, IntPtr.Zero);
return best != IntPtr.Zero && PostMessage(best, 0x0112, new IntPtr(0xF060), IntPtr.Zero);
}
}
'@
}

$began = Get-Date
$title = $null # the game process ($Game, the same name in any case, is its folder)
$stopReason = $null
try {
while ($true) {
Start-Sleep -Seconds 5
if (-not $title) {
$found = Get-RunningGame
if ($found) {
$title = Get-Process -Id $found.ProcessId
$null = $title.Handle # held now, so that the exit code can be read after the process ends
Add-Event 'game' @{ pid = $found.ProcessId; image = $found.Name }
}
}
if ($title -and $title.HasExited) { break }
if (-not $title -and $launcher.HasExited) { break }
$state = & $Python -I $tool state $RunDir | ConvertFrom-Json
if ($state.relaunched) { $stopReason = 'relaunched' }
elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' }
elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' }
elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' }
if ($stopReason) { break }
}

if ($stopReason -and $title -and -not $title.HasExited) {
Add-Event 'stop_requested' @{ reason = $stopReason }
if ([GateWindow]::Close($title.Id)) { Add-Event 'close_sent' }
if (-not $title.WaitForExit(60000)) {
Stop-Process -Id $title.Id -Force
Add-Event 'killed'
$title.WaitForExit()
}
} elseif ($stopReason) {
Add-Event 'stop_requested' @{ reason = $stopReason }
}
if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } }
if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force }
} catch {
Add-Event 'error' @{ message = $_.Exception.Message; line = $_.InvocationInfo.ScriptLineNumber }
Write-Host "gate error: $($_.Exception.Message) (line $($_.InvocationInfo.ScriptLineNumber))"
} finally {
& $Python -I $tool summary $RunDir
$code = $LASTEXITCODE
Stop-Transcript | Out-Null
}
exit $code
Loading
Loading