#Requires -Version 7.0
# 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
-Data -DataTemplate -Name [options]
# pwsh -NoProfile -File scripts\game-gate.ps1 start # the same, detached: returns at once, prints the run folder
# pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir # 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: \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