diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976e2f80ee..ccfaa9eb8b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1119,6 +1119,46 @@ print the same results and write the same failures as one, an unexpected transla `startup_run_ps1` checks that `-Translate` starts the watcher on the cache and stops it together with a child process. +### Native graphics interface catalog in runs + +The native graphics translator uses the catalog to look up reflected stage interfaces for +matching raw shader requests. A request that needs a reflected vertex and pixel interface +must match both stages. + +To build a corpus from your own local package, pass its shader archive to the extractor. +Replace `` with the archive path and `` with the local output directory. + +```text +python -B tools/extract_shaders.py "" --format dxbc --stage vertex pixel mesh --output-dir "" +``` + +The extractor writes `.dxbc` containers under ``. Review the output and rename the +compatible guest containers from `.dxbc` to `.cdxil`, the only extension the indexer reads. +The corpus and seeded cache contain copies of your own shader data and must stay local without +ever being committed, attached, or uploaded. See [CONTRIBUTING.md](../CONTRIBUTING.md). + +With `-Render`, pass `-InterfaceCorpus 'D:\reviewed-interfaces'` to `run.ps1`. Under Wine, pass +`--render --interface-corpus /path/to/reviewed-interfaces` to `run.sh`. Both launchers index +the corpus into the selected shader cache after any fresh-cache rotation and before the +watcher or debugger starts. An install failure stops the run. The shared preset can also +install the corpus in native shader mode. + +```powershell +python -B tools/startup/run_preset.py --package 'D:\package' --console x --gpu nvidia ` + --set translate=false --set 'interface_corpus=D:\reviewed-interfaces' +``` + +Add `--print` to see the generated launcher command. The launchers use `compile_dxil.exe` +from the selected build directory. To install the same catalog manually, pass the cache +directory that the run will use: + +```powershell +.\out\build\release\compile_dxil.exe --index-graphics-interfaces 'D:\reviewed-interfaces' 'out\startup\shader_cache' +``` + +Check the install command's output for `indexed_graphics_containers=` and the +selected cache for `interfaces/library/catalog` and its `.index` and `.stage` files. + ### Translating compute programs in the stand-in With `X2W_NATIVE_SHADERS=` (`run.ps1 -Render -NativeShaders `), diff --git a/tests/native_graphics_interface_library_check.py b/tests/native_graphics_interface_library_check.py index f022934fa9..d15946f7a0 100644 --- a/tests/native_graphics_interface_library_check.py +++ b/tests/native_graphics_interface_library_check.py @@ -1,10 +1,12 @@ """Index source-built native containers and replay their raw runtime form.""" import pathlib +import shutil import subprocess import sys import tempfile from native_direct_container_check import patched_pixel, publish, vertex, words +from startup_run_ps1_check import OLDER_CACHE, RUN_PS1, run_case def main(compiler, sdk): @@ -18,7 +20,7 @@ def run(*args, expected=None): with tempfile.TemporaryDirectory() as tmp: base = pathlib.Path(tmp) - library, cache, requests = (base / s for s in ("library", "cache", "requests")) + library, cache, requests = (base / s for s in ("reviewed interfaces", "cache", "requests")) library.mkdir() # The old raw reader has no PS state for this scalar branch. Exact # native programs recover the full stage ABI from the catalog. @@ -39,6 +41,13 @@ def batch(folder, output, **kwargs): batch(requests, base / "bare", expected="verified stage interface") install = ("--index-graphics-interfaces", library, cache) run(*install) + shell = shutil.which("powershell") or shutil.which("pwsh") + if sys.platform == "win32" and shell: + launcher = RUN_PS1.read_text(encoding="utf-8") + launch_options = dict(work=base, translate=True, switches=["-FakeUser"], absolute_build=True, + cache_files=OLDER_CACHE, interface_corpus=library, interface_compiler=compiler) + problems = run_case(shell, launcher, 7, **launch_options) + assert not problems, problems for name, hit in (("cold",0), ("warm",1)): assert f"frontend_cache_hit={hit}" in batch(requests, base / name) run(sdk,cache,"gfx1013-container-pair",vertex_file,base/"vertex.cso",pixel_file,base/"pixel.cso") @@ -67,6 +76,9 @@ def tree(folder): (library/"broken.cdxil").write_bytes(b"bad") assert subprocess.run([compiler,*install],capture_output=True).returncode assert subprocess.run([compiler,*install,"--jobs","3"],capture_output=True).returncode + if sys.platform == "win32" and shell: + problems = run_case(shell, launcher, 0, expect_catalog_error=True, **launch_options) + assert not problems, problems batch(requests,base/"retained") # Two reflected parameter rows. The fixed PS uses P1/P2 for x diff --git a/tests/startup_run_preset_check.py b/tests/startup_run_preset_check.py index ed0ade21a6..9ad8d0a829 100644 --- a/tests/startup_run_preset_check.py +++ b/tests/startup_run_preset_check.py @@ -14,6 +14,7 @@ import itertools import json import re +import subprocess import sys import tempfile from pathlib import Path @@ -78,6 +79,8 @@ def arg_after(cmd, flag): check(s["env"].get("X2W_HIDE_TITLE_WINDOW") == "1", f"{where}: the title's own window is hidden") host = "linux" if os_name == "linux" else "windows" cmd = rp.build_command(host, s, pkg / "stage" / "t.exe", pkg, pkg / "log", pkg / "storage") + corpus_flag = "--interface-corpus" if host == "linux" else "-InterfaceCorpus" + check("interface_corpus" not in s["run"] and corpus_flag not in cmd, f"{where}: no shared interface corpus") if host == "linux": check(cmd[1].endswith("run.sh") and "--render" in cmd, f"{where}: run.sh command") check(s["env"].get("X2W_XMEM_SHARED_VIEWS") == "1", f"{where}: shared views on Linux") @@ -258,6 +261,19 @@ def no_link(*_a): and "X2W_PRESET_CHECK_CALLER=1 (from the caller's shell)" in printed, "--print output") check(not (Path(tmp) / "runs").exists(), "--print creates nothing") + for host, flag in (("win11", "-InterfaceCorpus"), ("linux", "--interface-corpus")): + args = ["--package", str(package), "--console", "s", "--gpu", "amd", "--os", host, "--print", + "--runs", str(Path(tmp) / "runs")] + corpus = str(Path(tmp) / "reviewed interfaces") + for value in ("", corpus): + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = rp.main([*args, "--set", f"interface_corpus={value}"]) + command = next((line for line in out.getvalue().splitlines() if line.startswith(" command: ")), "") + passed = subprocess.list2cmdline([flag, value]) in command if value else flag not in command + check(code == 0 and command and passed, f"{host}: --print interface corpus {value!r}") + check(not (Path(tmp) / "runs").exists(), f"{host}: --print with an interface corpus creates nothing") + # A run with the child start replaced: the environment it gets and what settings.json records. mini_path = Path(tmp) / "mini.json" mini_path.write_text(json.dumps(mini), encoding="utf-8") diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index e433579fd7..f6cc2400b3 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -36,6 +36,9 @@ os.environ.get("X2W_TITLE_ID"), os.environ.get("X2W_STORAGE_MB"), os.environ.get("X2W_NATIVE_SHADERS_ONLY"), os.environ.get("X2W_XAPU_TYPED_COMPLETIONS")] Path(__file__).with_name("debugger.json").write_text(json.dumps(record), encoding="utf-8") +cache = os.environ.get("X2W_SHADER_CACHE") +if cache and (Path(cache) / "interfaces" / "library" / "catalog").is_file(): + Path(__file__).with_name("catalog-at-debugger.flag").touch() # Under -Translate, wait until the watcher stub has started so run.ps1 cannot stop it before then. watch = Path(__file__).with_name("watch.json") deadline = time.monotonic() + 30 @@ -71,6 +74,8 @@ child = None if {early_exit} else subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) record = Path(__file__).with_name("watch.json") +if (Path(sys.argv[2]) / "interfaces" / "library" / "catalog").is_file(): + record.with_name("catalog-at-watch.flag").touch() temp = record.with_suffix(".tmp") temp.write_text(json.dumps([os.getpid(), child.pid if child else None] + sys.argv[1:]), encoding="utf-8") temp.replace(record) @@ -151,13 +156,15 @@ def alive(pid): def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False, early_exit=False, trace_api_env=None, absolute_build=False, missing_build=False, emit_stderr=False, - missing_python=False, real_log_error=False, native=False, manifest="absent", cache_files=None): + missing_python=False, real_log_error=False, native=False, manifest="absent", cache_files=None, + interface_corpus=None, interface_compiler=None, expect_catalog_error=False): """Run one copy of the script on a stub that exits with `code`; return what is wrong. `switches` are extra run.ps1 switches and `passed` the debugger arguments they must add. `translate` exercises -Render -Translate and requires the watcher to stop with its child. With `early_exit` the watcher has no child and exits before the debugger finishes. `native` passes -Render -NativeShaders : the stand-in gets the directory and no watcher starts. + The native interface library fixture supplies a compiler and synthetic corpus for a fresh-cache install. This checks the log head and debugger exit code. The live watcher case checks worker cleanup. """ root = Path(tempfile.mkdtemp(dir=work)).resolve() @@ -205,6 +212,7 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), env.pop("X2W_FAKE_USER", None) env.pop("X2W_NATIVE_SHADERS", None) env.pop("X2W_NATIVE_SHADERS_ONLY", None) + env.pop("X2W_SHADER_CACHE", None) env.pop("X2W_XAPU_TYPED_COMPLETIONS", None) if trace_api_env is None: env.pop("X2W_TRACE_API", None) @@ -235,6 +243,9 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), if translate: command += ["-Render", "-Translate", "-ShaderCache", "cache"] (startup / "translate.flag").write_bytes(b"") + if interface_corpus is not None: + shutil.copyfile(interface_compiler, build / "compile_dxil.exe") + command += ["-InterfaceCorpus", str(interface_corpus), "-FreshShaderCache"] # A surviving watcher can keep a capture pipe open after PowerShell exits. # Capture to files so we can check the watcher's PID as soon as the shell exits. with (tempfile.TemporaryFile(mode="w+", errors="replace", dir=root) as stdout, @@ -247,6 +258,13 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), stderr.seek(0) printed = [line.strip() for line in stdout if line.strip()] error_text = stderr.read().strip() + if expect_catalog_error: + found = [] + if out.returncode == 0 or (startup / "debugger.json").exists() or (startup / "watch.json").exists(): + found.append("an invalid interface corpus did not stop the run") + if "Native graphics interface catalog install failed" not in error_text: + found.append(f"missing catalog install failure message (stderr: {error_text!r})") + return found if missing_python: return (["missing Python returned success"] if out.returncode == 0 else []) + ( ["missing Python launched debugger"] if (startup / "debugger.json").exists() else []) @@ -264,7 +282,19 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), summary = Path(str(log) + ".out") summary_lines = [line.strip() for line in decode(summary.read_bytes()).splitlines() if line.strip()] if summary.is_file() else [] want_output = summary_lines[:HEAD_LINES] if emit_stderr else STUB_LINES[:HEAD_LINES] - if cache_files is not None: + if interface_corpus is not None: + library = root / "cache" / "interfaces" / "library" + if not ((library / "catalog").is_file() and list(library.glob("*.index")) and list(library.glob("*.stage"))): + found.append("the catalog was not installed in the selected cache") + moved = list(root.glob("cache.old-*")) + if len(moved) != 1 or not (moved[0] / "revision.txt").is_file() or (root / "cache" / "revision.txt").exists(): + found.append("the old cache was not rotated before installing the catalog") + if not all((startup / f"catalog-at-{name}.flag").exists() for name in ("watch", "debugger")): + found.append("the catalog was missing when the watcher or debugger started") + if "indexed_graphics_containers=2" not in printed: + found.append("the indexer did not report the two installed containers") + printed = [line for line in printed if line in STUB_LINES] + elif cache_files is not None: # One warning with both revisions and the fixes; PowerShell may wrap it, so compare without whitespace. flat = re.sub(r"\s", "", " ".join(printed)) missing = [phrase for phrase in REVISION_PHRASES if re.sub(r"\s", "", phrase) not in flat] @@ -389,6 +419,23 @@ def text_problems(script): found.append("missing -TraceApi environment opt-in before launch") if not re.search(r"\$env:X2W_NATIVE_SHADERS\s*=", before): found.append("missing -NativeShaders directory hand-over before launch") + install = re.search( + r'^if \(\$InterfaceCorpus\) \{\n\$indexer = Join-Path \$buildRoot "compile_dxil\.exe"\ntry \{\n' + r'& \$indexer --index-graphics-interfaces \$InterfaceCorpus \$env:X2W_SHADER_CACHE\n' + r'if \(\$LASTEXITCODE -ne 0\) \{ throw [^\n]+ \}\n\} catch \{\n' + r'throw "Native graphics interface catalog install failed:', before, re.M) + if not re.search(r'^\[string\]\s*\$InterfaceCorpus\s*=\s*""', before, re.M) or not install: + found.append("missing opt-in catalog install into the selected cache or failure handling") + else: + fresh = before.find('$cachePath --fresh |') + selected = before.find('$env:X2W_SHADER_CACHE =') + watcher = before.find('Start-Process -FilePath $python') + if not 0 <= fresh < selected < install.start() < watcher: + found.append("the catalog install must follow fresh-cache handling and precede the watcher and debugger") + if 'if ($InterfaceCorpus -and -not $Render) { throw ' not in before: + found.append("an explicit catalog install must require rendering") + if 'if ($InterfaceCorpus -and $LASTEXITCODE -ne 0) { throw ' not in before: + found.append("a failed fresh-cache rotation must stop an explicit catalog install") if not WATCH_CLEANUP.search("\n".join(after)): found.append("tree cleanup lacks taskkill /T, the live-watcher guard or the local Continue scope") return found @@ -455,6 +502,26 @@ def shell_failures(shell, script, tmp): for removed in (' -and -not $translator.HasExited', '$ErrorActionPreference = "Continue"', '/T '): if not text_problems(script.replace(removed, '')): failures.append(f"text: removing {removed.strip()} escaped the cleanup check") + install_at = script.index(" if ($InterfaceCorpus) {") + install_end = script.index(" if (-not $Translate) {", install_at) + install = script[install_at:install_end] + before_fresh = script.replace(install, "").replace(" if ($FreshShaderCache) {", install + " if ($FreshShaderCache) {") + catalog_mutants = { + "interface corpus defaults to a path": script.replace('$InterfaceCorpus = ""', '$InterfaceCorpus = "local"'), + "no catalog install": script.replace(install, ""), + "unconditional catalog install": script.replace("if ($InterfaceCorpus) {", "if ($Render) {"), + "catalog install before fresh cache": before_fresh, + "catalog cache argument changed": script.replace("$InterfaceCorpus $env:X2W_SHADER_CACHE", + "$InterfaceCorpus $ShaderCache"), + "catalog failure ignored": script.replace( + 'if ($LASTEXITCODE -ne 0) { throw "compile_dxil.exe exited with code $LASTEXITCODE." }', ""), + "catalog without render allowed": script.replace("if ($InterfaceCorpus -and -not $Render) {", "if ($false) {"), + "catalog after a failed cache rotation": script.replace("if ($InterfaceCorpus -and $LASTEXITCODE -ne 0) {", + "if ($false) {"), + } + for label, mutant in catalog_mutants.items(): + if mutant == script or not text_problems(mutant): + failures.append(f"text: mutant '{label}' was not detected") return failures diff --git a/tests/startup_run_sh_check.py b/tests/startup_run_sh_check.py index 4c119ddfbe..97ebd01e14 100644 --- a/tests/startup_run_sh_check.py +++ b/tests/startup_run_sh_check.py @@ -57,6 +57,9 @@ # Stands in for wine: "$WINE" python.exe -B script.py args... runs script.py (a Z: path) on the # host Python and passes the other arguments as they are, so the stubs see Windows spellings. WINE_STUB = r"""#!/usr/bin/env bash +if [ "${2:-}" = --index-graphics-interfaces ]; then + exec "$X2W_CHECK_PYTHON" "$@" +fi shift args=() for arg in "$@"; do @@ -67,6 +70,21 @@ done exec "$X2W_CHECK_PYTHON" "${args[@]}" """ +INDEX_STUB = r""" +import json +import os +import sys +from pathlib import Path + +here = Path(__file__).resolve().parent.parent / "tools" / "startup" +cache = Path(sys.argv[3][2:].replace("\\", "/")) +here.joinpath("index.json").write_text(json.dumps([*sys.argv, cache.is_dir()]), encoding="utf-8") +if os.environ.get("X2W_CHECK_INDEX_FAIL"): + sys.exit(9) +library = cache / "interfaces" / "library" +library.mkdir(parents=True) +(library / "catalog").touch() +""" ENV_PREFIXES = ("X2W_", "WINE", "VKD3D", "XDG_RUNTIME_DIR", "PULSE_SERVER") # A zombie counts as gone: it no longer runs, it only waits for its parent to collect it. ALIVE = """\ @@ -98,6 +116,8 @@ def alive(pid): {alive} here = Path(__file__) +if (here.parents[2] / "cache" / "interfaces" / "library" / "catalog").is_file(): + here.with_name("catalog-at-debugger.flag").touch() here.with_name("argv.json").write_text(json.dumps(sys.argv[1:]), encoding="utf-8") here.with_name("env.json").write_text(json.dumps({{k: v for k, v in os.environ.items() if k.startswith({prefixes!r})}}), encoding="utf-8") @@ -139,6 +159,8 @@ def alive(pid): signal.signal(signal.SIGTERM, signal.SIG_IGN) # inherited by the child as ignored child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) here = Path(__file__) +if (here.parents[2] / "cache" / "interfaces" / "library" / "catalog").is_file(): + here.with_name("catalog-at-watch.flag").touch() here.with_name("watch_env.json").write_text(json.dumps({{k: v for k, v in os.environ.items() if k.startswith({prefixes!r})}}), encoding="utf-8") here.with_name("watch.json").write_text(json.dumps([os.getpid(), child.pid] + sys.argv[1:]), encoding="utf-8") @@ -168,7 +190,7 @@ def read_json(path): def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_data=False, config=CONFIG, translate=False, stop=None, drive_log=False, log_slash=False, expect_env=None, expect_warnings=None, - expect_exit=None, cache_files=None, expect_moved=False): + expect_exit=None, cache_files=None, expect_moved=False, expect_catalog=False): """Run one copy of the script on a stub that exits with `code`; return what is wrong.""" root = Path(tempfile.mkdtemp(dir=work)).resolve() startup = root / "tools" / "startup" @@ -192,6 +214,8 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d wine.write_text(WINE_STUB, encoding="utf-8") wine.chmod(0o755) (root / "bld").mkdir() + indexer = root / "bld" / "compile_dxil.exe" + indexer.write_text(INDEX_STUB, encoding="utf-8") for dll in DLLS: (root / "bld" / f"{dll}.dll").write_bytes(b"") sdk = root / "native dxc" @@ -262,6 +286,8 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d if expect_exit is not None: # a refused run must not reach the debugger if (startup / "argv.json").exists(): found.append(f"{label}: the debugger ran although run.sh refused the run") + if (startup / "watch.json").exists(): + found.append(f"{label}: the watcher ran although run.sh refused the run") if not any(expect_warnings[0] in w for w in warnings): found.append(f"{label}: missing message {expect_warnings[0]!r}, got {warnings}") return found @@ -277,8 +303,19 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d found.append(f"{label}: warnings {warnings}, expected {expect_warnings}") if expect_moved: moved = [p for p in root.iterdir() if p.name.startswith("cache.old-")] - if len(moved) != 1 or not (moved[0] / REQUEST).is_file() or list((root / "cache").iterdir()): + want_files = ["interfaces"] if expect_catalog else [] + if (len(moved) != 1 or not (moved[0] / REQUEST).is_file() + or sorted(p.name for p in (root / "cache").iterdir()) != want_files): found.append(f"{label}: --fresh-shader-cache did not move the old cache aside ({moved})") + indexed = read_json(startup / "index.json") + if expect_catalog: + want_index = [str(indexer), "--index-graphics-interfaces", win(root / "reviewed interfaces"), win(root / "cache"), True] + if indexed != want_index: + found.append(f"{label}: the indexer received {indexed}, expected {want_index}") + if not all((startup / f"catalog-at-{name}.flag").is_file() for name in ("watch", "debugger")): + found.append(f"{label}: the catalog was missing when the watcher or debugger started") + elif indexed is not None: + found.append(f"{label}: the indexer ran with no --interface-corpus") if stop == "term" and not debugger_done: found.append(f"{label}: run.sh ended before the debugger finished") if drive_log: @@ -397,6 +434,17 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d # --fresh-shader-cache moves the old cache aside, so the run starts empty and does not warn. dict(code=7, translate=True, cache_files=OLDER_CACHE, switches=["--fresh-shader-cache"], expect_moved=True, expect_warnings=[FAKE_USER_WARNING, MOVED_NOTE]), + dict(code=7, translate=True, cache_files=OLDER_CACHE, expect_moved=True, expect_catalog=True, + switches=["--fresh-shader-cache", "--interface-corpus", "reviewed interfaces"], + expect_warnings=[FAKE_USER_WARNING, MOVED_NOTE]), + dict(code=0, translate=True, switches=["--interface-corpus", "reviewed interfaces"], + env_extra={"X2W_CHECK_INDEX_FAIL": "1"}, expect_exit=1, + expect_warnings=["native graphics interface catalog install failed"]), + dict(code=0, translate=True, switches=["--fresh-shader-cache", "--interface-corpus", "reviewed interfaces"], + env_extra={"X2W_HOST_PYTHON": "false"}, expect_exit=1, + expect_warnings=["could not prepare a fresh shader cache for --interface-corpus"]), + dict(code=0, switches=["--interface-corpus", "reviewed interfaces"], expect_exit=64, + expect_warnings=["--interface-corpus requires --render"]), dict(code=7, translate=True, stop="int"), dict(code=7, translate=True, stop="term"), ] @@ -426,6 +474,11 @@ def drop_line(script, text): def mutants_of(script): + install_at = script.index(' if [ -n "$interface_corpus" ]; then\n if ! "$wine"') + install_end = script.index(' if [ -z "$translate" ]; then', install_at) + install = script[install_at:install_end] + before_fresh = replace(replace(script, install, ""), ' if [ -n "$fresh_cache" ]; then', + install + ' if [ -n "$fresh_cache" ]; then') return { "exit with head's status": replace(script, "exit $debugger_exit", "exit"), "fixed exit 0": replace(script, "exit $debugger_exit", "exit 0"), @@ -443,6 +496,18 @@ def mutants_of(script): "no hide warning": replace(script, ' echo "WARNING: --hide-title-window', ' : "WARNING: --hide-title-window'), "no revision warning": replace(script, ' echo "WARNING: $note" >&2', ' : "WARNING: $note"'), "fresh cache kept": replace(script, ' if [ -n "$fresh_cache" ]; then', ' if false; then'), + "no catalog install": replace(script, install, ""), + "unconditional catalog install": replace(script, install, install.replace('if [ -n "$interface_corpus" ]; then', 'if true; then')), + "catalog install before fresh cache": before_fresh, + "catalog install after debugger": replace(replace(script, install, ""), 'debugger_exit=$?\n', + 'debugger_exit=$?\n' + install), + "catalog corpus path changed": replace(script, '"$(win_path "$interface_corpus")"', '"$interface_corpus"'), + "catalog after a failed cache rotation": replace(script, ' if [ -n "$interface_corpus" ]; then', + ' if false; then'), + "catalog failure ignored": replace(script, ' exit 1\n fi\n fi\n if [ -z "$translate" ]; then', + ' :\n fi\n fi\n if [ -z "$translate" ]; then'), + "catalog without render allowed": replace(script, 'if [ -n "$interface_corpus" ] && [ -z "$render" ]; then', + 'if false; then'), "log through the raw path": replace(script, 'log_host=$(host_path "$log")', 'log_host=$log'), "cache through the raw path": replace(script, 'mkdir -p "$(host_path "$shader_cache")"', 'mkdir -p "$shader_cache"'), "trailing separator kept": drop_line(script, "do log=${log%?}; done"), diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index e1aa9c299a..86cebd9e67 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -37,9 +37,11 @@ param( [switch]$TraceCalls, # also break on runtime and movie-player calls (--trace-calls 1; slows the process) [double]$CaptureEvery = 0, # --capture-every: save the title window as window_s.png every N seconds (0 = off) [ValidateSet(0, 1)] [int]$SuspendOthers = 1, # --suspend-others: 0 = don't hold other threads while a hook steps (faster, can miss traced calls) - [switch]$TraceApi # log runtime provider method calls (X2W_TRACE_API) + [switch]$TraceApi, # log runtime provider method calls (X2W_TRACE_API) + [string]$InterfaceCorpus = "" # with -Render: index reviewed guest shader containers into the shader cache ) $ErrorActionPreference = "Stop" +if ($InterfaceCorpus -and -not $Render) { throw "-InterfaceCorpus requires -Render." } $repo = Resolve-Path (Join-Path $PSScriptRoot "..\..") $runDir = Split-Path -Parent (Resolve-Path $Exe) $buildRoot = if ([System.IO.Path]::IsPathRooted($BuildDir)) { $BuildDir } else { Join-Path $repo $BuildDir } @@ -77,10 +79,20 @@ if ($Render) { if ($FreshShaderCache) { $cachePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ShaderCache) & $python -B $revisionTool $cachePath --fresh | ForEach-Object { Write-Host $_ } + if ($InterfaceCorpus -and $LASTEXITCODE -ne 0) { throw "Could not prepare a fresh shader cache for -InterfaceCorpus." } } New-Item -ItemType Directory -Force $ShaderCache | Out-Null $env:X2W_D3D12_RENDER = "1"; $env:X2W_DRAW_NULL_IDENTITY = "1" $env:X2W_SHADER_CACHE = (Resolve-Path $ShaderCache).Path + if ($InterfaceCorpus) { + $indexer = Join-Path $buildRoot "compile_dxil.exe" + try { + & $indexer --index-graphics-interfaces $InterfaceCorpus $env:X2W_SHADER_CACHE + if ($LASTEXITCODE -ne 0) { throw "compile_dxil.exe exited with code $LASTEXITCODE." } + } catch { + throw "Native graphics interface catalog install failed: $_" + } + } if (-not $Translate) { if (-not $NativeShaders) { $NativeShaders = $env:X2W_NATIVE_SHADERS } $dxcDirFile = Join-Path $buildRoot "x2w-dxc-dir.txt" diff --git a/tools/startup/run.sh b/tools/startup/run.sh index be7131edfd..aad48a98c6 100755 --- a/tools/startup/run.sh +++ b/tools/startup/run.sh @@ -29,7 +29,7 @@ set -uo pipefail usage() { echo "usage: run.sh --exe EXE --data DIR --log DIR [--seconds 120] [--build-dir out/build/release]" >&2 echo " [--memory-gib 14] [--continue-asserts 0] [--assert-sites 0] [--input-script S] [--storage DIR]" >&2 - echo " [--shader-cache out/startup/shader_cache] [--console 0|1] [--render] [--fake-user]" >&2 + echo " [--shader-cache out/startup/shader_cache] [--interface-corpus DIR] [--console 0|1] [--render] [--fake-user]" >&2 echo " [--gpu-mirror] [--host-cpu] [--translate] [--startup-below-40] [--trace-calls]" >&2 echo " [--hide-title-window] [--capture-every S] [--fresh-shader-cache] [--suspend-others 0|1]" >&2 exit 64 @@ -38,12 +38,12 @@ usage() { repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) here="$repo/tools/startup" exe="" data="" log="" seconds=120 build_dir=out/build/release memory_gib=14 continue_asserts=0 assert_sites=0 -input_script="" storage="" shader_cache=out/startup/shader_cache console=1 capture_every=0 suspend_others=1 +input_script="" storage="" shader_cache=out/startup/shader_cache interface_corpus="" console=1 capture_every=0 suspend_others=1 render="" fake_user="" gpu_mirror="" host_cpu="" translate="" below_40="" trace_calls="" hide_title="" fresh_cache="" while [ $# -gt 0 ]; do case $1 in --exe|--data|--log|--seconds|--build-dir|--memory-gib|--continue-asserts|--assert-sites|--input-script|--storage|\ - --shader-cache|--console|--capture-every|--suspend-others) + --shader-cache|--interface-corpus|--console|--capture-every|--suspend-others) [ $# -ge 2 ] || usage case $1 in --exe) exe=$2 ;; --data) data=$2 ;; --log) log=$2 ;; --seconds) seconds=$2 ;; @@ -53,6 +53,7 @@ while [ $# -gt 0 ]; do --input-script) input_script=$2 ;; # X2W_INPUT_SCRIPT, e.g. "4@70" = A at 70 s --storage) storage=$2 ;; # X2W_STORAGE_PATH: persistent local storage root --shader-cache) shader_cache=$2 ;; --console) console=$2 ;; + --interface-corpus) interface_corpus=$2 ;; # with --render: reviewed guest shader containers --capture-every) capture_every=$2 ;; # window_s.png every N seconds (0 = off) --suspend-others) suspend_others=$2 ;; # 0 = don't hold other threads while a hook steps esac @@ -71,6 +72,10 @@ while [ $# -gt 0 ]; do esac done [ -n "$exe" ] && [ -n "$data" ] && [ -n "$log" ] || usage +if [ -n "$interface_corpus" ] && [ -z "$render" ]; then + echo "run.sh: --interface-corpus requires --render" >&2 + exit 64 +fi case $suspend_others in 0|1) ;; *) echo "run.sh: --suspend-others takes 0 or 1" >&2; exit 64 ;; esac [ -n "${WINEPREFIX:-}" ] || { echo "run.sh: set WINEPREFIX (docs/non-windows-hosts.md)" >&2; exit 64; } [ -n "${X2W_WIN_PYTHON:-}" ] || { echo "run.sh: set X2W_WIN_PYTHON to a Windows python.exe (docs/wine.md)" >&2; exit 64; } @@ -156,12 +161,23 @@ if [ -n "$fresh_cache" ] && [ -z "$render" ]; then fi if [ -n "$render" ]; then if [ -n "$fresh_cache" ]; then - "$host_python" -B "$here/shader_cache_revision.py" "$(host_path "$shader_cache")" --fresh >&2 + if ! "$host_python" -B "$here/shader_cache_revision.py" "$(host_path "$shader_cache")" --fresh >&2; then + if [ -n "$interface_corpus" ]; then + echo "run.sh: could not prepare a fresh shader cache for --interface-corpus" >&2 + exit 1 + fi + fi fi mkdir -p "$(host_path "$shader_cache")" export X2W_D3D12_RENDER=1 X2W_DRAW_NULL_IDENTITY=1 X2W_SHADER_CACHE=$(win_path "$shader_cache") export X2W_SHADER_CACHE + if [ -n "$interface_corpus" ]; then + if ! "$wine" "$build_dir/compile_dxil.exe" --index-graphics-interfaces "$(win_path "$interface_corpus")" "$X2W_SHADER_CACHE"; then + echo "run.sh: native graphics interface catalog install failed (compile_dxil.exe)" >&2 + exit 1 + fi + fi if [ -z "$translate" ]; then native_shaders=${X2W_NATIVE_SHADERS:-} if [ -z "$native_shaders" ] && [ -f "$build_dir/x2w-dxc-dir.txt" ]; then diff --git a/tools/startup/run_preset.py b/tools/startup/run_preset.py index c939949c0f..9613d0ddf8 100644 --- a/tools/startup/run_preset.py +++ b/tools/startup/run_preset.py @@ -3,7 +3,7 @@ python -B tools/startup/run_preset.py --package --console x|s --gpu nvidia|amd [--os win11|win10|linux] -The settings come from tools/startup/run_presets.json, not from the command line: its `base` layer, then +The shared settings come from tools/startup/run_presets.json: its `base` layer, then the chosen `os`, `console` and `gpu` layers, each overriding the one before. The launcher - finds the executable named in the package's MicrosoftGame.config, - stages it with the other PE files of its folder in /stage (hard links where the volume allows, copies @@ -20,6 +20,7 @@ recorded in settings.json (`inherited_env`); an env value of null removes the variable, also when the caller set it. --print shows the merged settings and the command without staging or starting anything. +Use --set interface_corpus=DIR to supply a reviewed local shader corpus for one run. """ from __future__ import annotations @@ -50,6 +51,7 @@ "input_script": ("-InputScript", "--input-script", "value"), "capture_every": ("-CaptureEvery", "--capture-every", "value"), "shader_cache": ("-ShaderCache", "--shader-cache", "value"), + "interface_corpus": ("-InterfaceCorpus", "--interface-corpus", "value"), "build_dir": ("-BuildDir", "--build-dir", "value"), "suspend_others": ("-SuspendOthers", "--suspend-others", "value"), "render": ("-Render", "--render", "switch"), diff --git a/tools/startup/run_presets.json b/tools/startup/run_presets.json index 2fe412edbb..facaf2d77f 100644 --- a/tools/startup/run_presets.json +++ b/tools/startup/run_presets.json @@ -1,5 +1,5 @@ { - "about": "Shared settings for tools/startup/run_preset.py. Layers apply in order base, os, console, gpu; a later layer overrides an earlier one, and an env value of null unsets it, also when the caller's shell set it. 'run' keys are run.ps1/run.sh switches (see OPTIONS in run_preset.py); 'env' keys are exported before the script starts. Every entry says why it is there. Change a value here, with the measured run that supports it, rather than adding a launcher option.", + "about": "Shared settings for tools/startup/run_preset.py. Layers apply in order base, os, console, gpu; a later layer overrides an earlier one, and an env value of null unsets it, also when the caller's shell set it. 'run' keys are run.ps1/run.sh switches (see OPTIONS in run_preset.py); 'env' keys are exported before the script starts. Every entry says why it is there. Change a value here, with the measured run that supports it, rather than adding a launcher option. The optional interface_corpus setting defaults to empty; pass a reviewed local directory with --set interface_corpus=DIR for an individual run.", "base": { "why": "The settings shared by the furthest real-title runs reported in #870 (-Render -Translate -FakeUser -GpuMirror -StartupBelow40, a large assert budget, more than the default 14 GiB, the package on its console drive letter, an empty storage folder per run). package_drive is mapped with subst for the run, not run.ps1 -MapDrive: with -MapDrive a real-title run stayed on its first screens (11 pipelines translated in 420 s) where the same settings on a subst drive went on loading (76). suspend_others 0 turns off #1408's thread holding (run.ps1 -SuspendOthers, #3332): with it on, real-title runs on main stop before the first input poll (bisected to #1408 on 2026-11-28), and #3331 measured a 3-4x slower load. RING_RELEASE_AT_SUBMIT (#2949), ROOT_SRV_AT_DRAW (#3028), TABLE_ALIAS (#2977) and RUNTIME_LOCAL were measured together against the previous shared set (RELEASE_RETIRED_VIEWS and XAPU_TYPED_COMPLETIONS instead): 420 s on the same input, 163,846 vs 75,028 translated draws, 76 vs 62 pipelines, 2,079 vs 1,925 textures, NVIDIA, Windows 11, ec71c290. X2W_PROBE_PRECHECK=0 (#3313) skips the VirtualQuery pre-check that the stand-ins run before each probe and copy while a debugger is attached, which title runs always are: 420 s on the same input, 1,142,089 vs 162,303 translated draws, 80,175 vs 15,001 executes, 5,372 vs 2,134 textures, NVIDIA, Windows 11, ec71c290. X2W_HIDE_TITLE_WINDOW=1 hides the title's own window, which nothing presents to, once presents reach the output window; dialogs stay visible, and the window is shown again if a present misses the output window. The output window belongs to the same process, so the input stand-in's focus check still sees the process in front. INLINE_DESCRIPTORS (#3429), VIEW_CONTENT_TOKENS (#3377) and TABLE_LOCK (#3391) were measured together against the set without them, 360 s from a save, the same input, means over 250-360 s, RTX 3080 Ti, Windows 10 19045: with native shaders only (44a3ad5a with #3506, #3516, #3464, #3521, #3097 and the installed interface catalog) 23.73 vs 15.56 fps, 6.87 vs 7.13 translated draws and 415 vs 423 not drawn per frame, 0 vs 0 null bindings, 18.02 vs 19.15 GiB title commit; with -Translate on 44a3ad5a 8.68 vs 5.59 fps, 256 vs 234 translated draws and 94 vs 116 not drawn per frame, 17.18 vs 17.55 GiB title commit.", "run": {