#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'.
# Memory stop (from the runtime's memory lines, every 5 s, builds with diagnostics): the run is stopped the same
# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (the lower of 90 % of this
# PC's commit limit and 1.25 x its memory), when the PC has less than -StopCommitLeftMB left to commit for 20 s
# (the larger of 128 MB and 0.25 % of the limit), or when video memory stays over the system's budget for
# -StopOverBudgetSeconds (60). 0 turns one off. A run that reaches -WorldSeconds at the same poll stops with `target`.
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 = '',
[int]$StopPrivateMB = -1,
[int]$StopCommitLeftMB = -1,
[int]$StopOverBudgetSeconds = 60
)
$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" }
# The play script also makes a build noted as made without DLSS again once NVIDIA's SDK is there, whatever the start's
# switches ask for (d3d12\scripts\play-nvidia.ps1; not with -NoDlss, and not without cargo): that build too would be
# made inside the run, after the exe's hash and what it was built with were written down below.
# Whether -PlayArgs say -NoDlss is asked of PowerShell itself: the play script's own param block binds the arguments
# the launch line below gives it, and nothing of the script runs. (A pattern over the text took `-NoDlss: $true` for
# not said, and `-Adapter 'a -NoDlss b'` for said.) It gives $true, $false, or the error's text when PowerShell cannot
# bind the arguments (the start fails on those too). A variable in -PlayArgs is read here as the gate has it, not as
# launch.ps1 will: only literal arguments are sure to bind the same way in both.
function Test-NoDlssBound([string]$PlayScript, [string]$Arguments) {
try {
$params = [System.Management.Automation.Language.Parser]::ParseFile($PlayScript, [ref]$null, [ref]$null).ParamBlock.Extent.Text
$probe = [scriptblock]::Create("$params`n[bool]`$NoDlss")
# The first thing written is the probe's answer, whatever the pasted text writes behind a `;`.
[bool]@(& ([scriptblock]::Create("& `$args[0] -Game x -Data x -More @{} $Arguments")) $probe)[0]
} catch { "$_" }
}
$builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt'
$dlssSdk = Join-Path $repo 'd3d12\nvidia-sdk\DLSS\lib\Windows_x86_64\x64\nvsdk_ngx_d.lib'
if ((Test-Path $builtWith) -and (Get-Content $builtWith -Raw) -notmatch 'dlss' -and (Test-Path $dlssSdk) -and
(Get-Command cargo -ErrorAction SilentlyContinue)) {
$noDlss = Test-NoDlssBound $play $PlayArgs
if ($noDlss -ne $true) {
$why = if ($noDlss -is [string]) { " (-PlayArgs do not bind to the play script, so -NoDlss is not read from them: $noDlss)" } else { '' }
throw "$exe was built without DLSS and NVIDIA's SDK is here: build it again first (d3d12\scripts\build-nvidia.ps1), the play script would do it inside the run$why"
}
}
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
'-StopPrivateMB'; $StopPrivateMB; '-StopCommitLeftMB'; $StopCommitLeftMB; '-StopOverBudgetSeconds'; $StopOverBudgetSeconds) -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
"@
# The memory stop's limits, from this PC's commit limit unless given (0 turns one off). On a PC with no page file a
# normal run can leave a few hundred MB to commit: the floor is low and must hold for 20 s.
$commitLimitMB = [math]::Floor((Get-CimInstance Win32_OperatingSystem).TotalVirtualMemorySize / 1KB)
$physicalMB = [math]::Floor((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB)
# With a large page file the commit limit is far above what the PC survives: two Windows crashes (0x10E) came at
# about 100 GB private on a PC with 64 GB of memory and a 175 GB limit. So also no more than 1.25 x the memory.
if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int][math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25) }
if ($StopCommitLeftMB -lt 0) { $StopCommitLeftMB = [int][math]::Max(128, $commitLimitMB * 0.0025) }
$gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1
[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
memory_stop = [ordered]@{ private_max_mb = $StopPrivateMB; commit_left_min_mb = $StopCommitLeftMB; over_budget_s = $StopOverBudgetSeconds }
} | 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);
}
}
'@
}
# Why this poll stops the run, or nothing. The target comes before the memory stop: a run that reached its world time
# in the same poll as a memory limit is a measurement, and its memory peaks are in the summary all the same.
function Get-StopReason($Poll, [bool]$StopFile, [double]$Minutes, [int]$TargetSeconds, [int]$LimitMinutes) {
if ($Poll.relaunched) { 'relaunched' }
elseif ($Poll.world_s -ge $TargetSeconds) { 'target' }
elseif ($Poll.memory_stop) { 'memory' }
elseif ($StopFile) { 'stop_file' }
elseif ($Minutes -ge $LimitMinutes) { 'timeout' }
}
$began = Get-Date
$title = $null # the game process ($Game, the same name in any case, is its folder)
$stopReason = $null
$memoryWhy = $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
$stopReason = Get-StopReason -Poll $state -StopFile (Test-Path (Join-Path $RunDir 'STOP')) `
-Minutes ((Get-Date) - $began).TotalMinutes -TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes
if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }
if ($stopReason) { break }
}
if ($stopReason -and $title -and -not $title.HasExited) {
Add-Event 'stop_requested' @{ reason = $stopReason; why = $memoryWhy }
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; why = $memoryWhy }
}
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