"""d3d12/scripts/play-nvidia.ps1: the F1 menu's saved settings and the command line, the user's last choice winning one setting at a time (D3D12-MENU-LAST-CHOICE-WINS): a typed switch wins over the menu's value of what it sets, the menu file drops that value, every other setting keeps the menu's, and the menu's SAVE AND RESTART (-MenuRestart) keeps the menu's. The launcher's block is run alone in Windows PowerShell with the settings a command line made, against a menu file in a temporary folder.""" import json import os import subprocess import tempfile import unittest from pathlib import Path SCRIPT = Path(__file__).resolve().parents[1] / "d3d12" / "scripts" / "play-nvidia.ps1" BEGIN = "# What the F1 menu saved (leonida-settings.txt" END = "# Leonida: the runs write down the pipelines" def block() -> str: text = SCRIPT.read_text(encoding="utf-8-sig") return text[text.index(BEGIN):text.index(END)] @unittest.skipUnless(os.name == "nt", "Windows PowerShell launcher") class MenuChoiceTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.root = Path(self.tmp.name) self.menu = self.root / "leonida-settings.txt" def tearDown(self): self.tmp.cleanup() def start(self, made: dict, typed=None, console="series-s", more=None, restart=False, dry=False, direct=None) -> dict: """One start: `made` is what the command line made, `typed` the switches typed (play-d3d12.ps1's -Typed), `direct` the switches given when play-nvidia.ps1 is started by hand (no -Typed).""" pairs = "; ".join(f"'{k}' = '{v}'" for k, v in made.items()) more_pairs = "; ".join(f"'{k}' = '{v}'" for k, v in (more or {}).items()) driver = self.root / "driver.ps1" driver.write_text( "param([string[]]$Typed, [switch]$MenuRestart, [string]$Resolution, [switch]$Fullscreen)\n" "$ErrorActionPreference = 'Stop'\n" f"$root = '{self.root}'\n" f"$settings = @{{ {pairs} }}\n" f"$More = @{{ {more_pairs} }}\n" f"$console = '{console}'\n" "$NoSmoothMotion = $true\n" f"$DryRun = ${'true' if dry else 'false'}\n" + block() + "\n[pscustomobject]@{ settings = $settings; console = $console; smooth = $smooth } | ConvertTo-Json -Compress\n", encoding="utf-8-sig", ) args = [] if typed is not None: args += ["-Typed", ",".join(typed) if typed else "''"] if restart: args.append("-MenuRestart") args += direct or [] command = f"& '{driver}' {' '.join(args)}" res = subprocess.run( ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", command], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60, ) self.assertEqual(res.returncode, 0, res.stderr) out = res.stdout.strip().splitlines() ran = json.loads(out[-1]) ran["said"] = "\n".join(out[:-1]) return ran def saved(self) -> dict: lines = self.menu.read_text(encoding="utf-8").splitlines() if self.menu.exists() else [] return dict(l.split("=", 1) for l in lines if l.startswith("LEONIDA_")) def test_a_typed_switch_wins_over_the_menu_and_the_menu_file_follows(self): self.menu.write_text("LEONIDA_RENDER_SCALE=0.6\r\nLEONIDA_FPS_LINE=0\r\n", encoding="utf-8") ran = self.start({"LEONIDA_RENDER_SCALE": "1", "LEONIDA_OWN_UPSCALER": "1"}, typed=["Resolution"]) self.assertEqual(ran["settings"]["LEONIDA_RENDER_SCALE"], "1") self.assertEqual(ran["settings"]["LEONIDA_FPS_LINE"], "0", "a setting no switch made keeps F1's") self.assertEqual(self.saved(), {"LEONIDA_FPS_LINE": "0"}) self.assertIn("LEONIDA_RENDER_SCALE 0.6 -> 1 (-Resolution)", ran["said"]) def test_the_same_switch_typed_again_after_a_menu_save_wins_again(self): self.start({"LEONIDA_RENDER_SCALE": "1"}, typed=["Resolution"]) self.menu.write_text("LEONIDA_RENDER_SCALE=0.6\r\n", encoding="utf-8") ran = self.start({"LEONIDA_RENDER_SCALE": "1"}, typed=["Resolution"]) self.assertEqual(ran["settings"]["LEONIDA_RENDER_SCALE"], "1") self.assertEqual(self.saved(), {}) def test_a_default_nobody_typed_keeps_the_menu_value(self): # play-d3d12.ps1's Series X default with its -Lowest 1080: nothing typed. self.menu.write_text("LEONIDA_MENU_CONSOLE=series-s\r\nLEONIDA_RENDER_SCALE_MIN=0.6667\r\n", encoding="utf-8") ran = self.start({"LEONIDA_RENDER_SCALE_MIN": "0.75"}, typed=[], console="series-x") self.assertEqual(ran["console"], "series-s") self.assertEqual(ran["settings"]["LEONIDA_RENDER_SCALE_MIN"], "0.6667") self.assertIn("F1 menu settings", ran["said"]) # -SeriesS typed (passed on as SeriesX, the console's switch) wins over a menu's Series X. self.menu.write_text("LEONIDA_MENU_CONSOLE=series-x\r\n", encoding="utf-8") self.assertEqual(self.start({}, typed=["SeriesX"], console="series-s")["console"], "series-s") self.assertEqual(self.saved(), {}) def test_a_setting_no_switch_makes_is_never_taken_from_the_menu(self): self.menu.write_text("LEONIDA_CARD_AWAKE=1\r\n", encoding="utf-8") ran = self.start({"LEONIDA_CARD_AWAKE": "0", "LEONIDA_RENDER_SCALE": "1"}, typed=["Resolution", "Log"]) self.assertEqual(ran["settings"]["LEONIDA_CARD_AWAKE"], "1") self.assertEqual(self.saved(), {"LEONIDA_CARD_AWAKE": "1"}) self.assertNotIn("Command line over", ran["said"]) def test_the_menus_restart_keeps_the_values_it_saved(self): self.menu.write_text("LEONIDA_RENDER_SCALE=0.6\r\n", encoding="utf-8") before = self.menu.read_bytes() ran = self.start({"LEONIDA_RENDER_SCALE": "1"}, restart=True, direct=["-Resolution", "1080"]) self.assertEqual(ran["settings"]["LEONIDA_RENDER_SCALE"], "0.6") self.assertEqual(self.menu.read_bytes(), before) def test_a_start_by_hand_counts_its_own_switches(self): self.menu.write_text("LEONIDA_RENDER_SCALE=0.6\r\nLEONIDA_FULLSCREEN=\r\n", encoding="utf-8") ran = self.start({"LEONIDA_RENDER_SCALE": "1", "LEONIDA_FULLSCREEN": "1"}, direct=["-Resolution", "1080", "-Fullscreen"]) self.assertEqual(ran["settings"]["LEONIDA_RENDER_SCALE"], "1") self.assertEqual(ran["settings"]["LEONIDA_FULLSCREEN"], "1") self.assertEqual(self.saved(), {}) def test_more_wins_over_the_menu_like_a_typed_switch(self): self.menu.write_text("LEONIDA_PROMPTS=playstation\r\nLEONIDA_PANEL=1\r\n", encoding="utf-8") ran = self.start({}, typed=["More"], more={"LEONIDA_PROMPTS": "xbox"}) self.assertEqual(self.saved(), {"LEONIDA_PANEL": "1"}) self.assertIn("LEONIDA_PROMPTS playstation -> xbox (-More)", ran["said"]) # The same value from -More replaces nothing worth reporting; an empty menu value set by -More is reported. self.menu.write_text("LEONIDA_PANEL=1\r\nLEONIDA_FPS_LINE=\r\n", encoding="utf-8") ran = self.start({}, typed=["More"], more={"LEONIDA_PANEL": "1", "LEONIDA_FPS_LINE": "0"}) self.assertNotIn("LEONIDA_PANEL", ran["said"]) self.assertIn("LEONIDA_FPS_LINE (unset) -> 0 (-More)", ran["said"]) self.assertEqual(self.saved(), {}) def test_a_typed_dlss_mode_replaces_the_menus_lowest_scale(self): self.menu.write_text("LEONIDA_RENDER_SCALE_MIN=0.5\r\n", encoding="utf-8") ran = self.start({"LEONIDA_UPSCALE": "dlss"}, typed=["Dlss"]) self.assertNotIn("LEONIDA_RENDER_SCALE_MIN", ran["settings"]) self.assertEqual(self.saved(), {}) def test_smooth_motion_typed_in_play_d3d12_is_named_as_typed(self): self.menu.write_text("LEONIDA_MENU_SMOOTH_MOTION=1\r\n", encoding="utf-8") ran = self.start({}, typed=["NoSmoothMotion"]) self.assertIn("(-SmoothMotion/-NoSmoothMotion)", ran["said"]) def test_an_empty_menu_value_still_unsets(self): self.menu.write_text("LEONIDA_PANEL=\r\n", encoding="utf-8") self.assertNotIn("LEONIDA_PANEL", self.start({"LEONIDA_PANEL": "1"}, typed=[])["settings"]) def test_a_dry_run_writes_nothing(self): self.menu.write_text("LEONIDA_RENDER_SCALE=0.6\r\n", encoding="utf-8") before = self.menu.read_bytes() ran = self.start({"LEONIDA_RENDER_SCALE": "1"}, typed=["Resolution"], dry=True) self.assertEqual(ran["settings"]["LEONIDA_RENDER_SCALE"], "1") self.assertEqual(self.menu.read_bytes(), before) def test_a_menu_file_that_cannot_be_written_keeps_every_saved_value(self): self.menu.write_text("LEONIDA_RENDER_SCALE_MIN=0.6667\r\nLEONIDA_PANEL=1\r\n", encoding="utf-8") before = self.menu.read_bytes() blocker = self.root / "leonida-settings.txt.tmp" blocker.mkdir() # the new file cannot be written beside it ran = self.start({"LEONIDA_RENDER_SCALE_MIN": "0.5"}, typed=["Lowest"]) self.assertEqual(ran["settings"]["LEONIDA_RENDER_SCALE_MIN"], "0.5", "the start still runs with the switch") self.assertEqual(self.menu.read_bytes(), before) self.assertIn("was not updated", ran["said"]) self.assertTrue(blocker.is_dir(), "what stood at the temporary name is not the launcher's to remove") def test_a_typed_frame_generation_replaces_the_menus_other_one(self): # DLSS's and FSR 3's are one choice: the launcher keeps FSR 3's when both are set, so a saved FSR 3 would # undo a typed -FrameGen. self.menu.write_text("LEONIDA_FSR_FRAMEGEN=1\r\nLEONIDA_PANEL=1\r\n", encoding="utf-8") ran = self.start({"LEONIDA_FRAME_GEN": "2"}, typed=["FrameGen"]) self.assertEqual(ran["settings"]["LEONIDA_FRAME_GEN"], "2") self.assertNotIn("LEONIDA_FSR_FRAMEGEN", ran["settings"]) self.assertEqual(self.saved(), {"LEONIDA_PANEL": "1"}) self.menu.write_text("LEONIDA_FRAME_GEN=3\r\n", encoding="utf-8") ran = self.start({"LEONIDA_FSR_FRAMEGEN": "1"}, typed=["FsrFrameGen"]) self.assertEqual(ran["settings"]["LEONIDA_FSR_FRAMEGEN"], "1") self.assertNotIn("LEONIDA_FRAME_GEN", ran["settings"]) self.assertEqual(self.saved(), {}) @unittest.skipUnless(os.name == "nt", "Windows PowerShell launcher") class MenuRestartArgsTests(unittest.TestCase): def test_series_s_saved_dlss_replaces_the_upscaler_implied_by_resolution(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) scripts = root / "scripts" scripts.mkdir() script = scripts / SCRIPT.name script.write_bytes(SCRIPT.read_bytes()) exe = root / "placeholder.exe" exe.touch() (root / "nvngx_dlss.dll").touch() menu = root / "leonida-settings.txt" env = {k: v for k, v in os.environ.items() if not k.startswith("LEONIDA_")} env.update(TEST_SCRIPT=str(script), TEST_EXE=str(exe), TEST_DLSS_DIR=str(root)) command = [ "powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", ] launch = "& $env:TEST_SCRIPT -Exe $env:TEST_EXE -DlssDir $env:TEST_DLSS_DIR -NoFrameGen -DryRun" cases = ( ("dlss", "-Resolution 720", "0.6667", None, "1"), ("dlss", "-Resolution 720 -MenuRestart", None, "dlss", None), ("dlss", "-Resolution 540 -MenuRestart", "0.5", "dlss", "1"), ("dlss\nLEONIDA_OWN_UPSCALER=1", "-Resolution 720 -MenuRestart", "0.6667", "dlss", "1"), ("dlss", "-Resolution 720 -MenuRestart -More @{LEONIDA_RENDER_SCALE='0.6667'}", "0.6667", "dlss", "1"), ) for saved, args, scale, upscaler, own in cases: with self.subTest(saved=saved, args=args): menu.write_text(f"LEONIDA_UPSCALE={saved}\n", encoding="utf-8") res = subprocess.run([*command, f"{launch} {args}"], env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60) self.assertEqual(res.returncode, 0, res.stderr) settings = dict(line.split("=", 1) for line in res.stdout.splitlines() if line.startswith("LEONIDA_") and "=" in line) self.assertEqual(settings.get("LEONIDA_RENDER_SCALE"), scale) self.assertEqual(settings.get("LEONIDA_UPSCALE"), upscaler) self.assertEqual(settings.get("LEONIDA_OWN_UPSCALER"), own) def test_the_dlss_build_is_asked_for_once_its_sdk_is_here_whatever_the_switches(self): """D3D12-F1-DLSS-REBUILD: the launcher asked for the build with DLSS only when the start's switches wanted DLSS, before it read the menu's settings: a build noted as made without DLSS was never made again for a DLSS choice the menu saved behind a replayed -Resolution, and that start fell back from DLSS with NVIDIA's SDK installed. The SDK asks for the build now. A dry run builds nothing: it says what a start does first and prints the settings of the start after it.""" with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) scripts = root / "scripts" scripts.mkdir() script = scripts / SCRIPT.name script.write_bytes(SCRIPT.read_bytes()) exe = root / "placeholder.exe" exe.touch() lib = root / "nvidia-sdk" / "DLSS" / "lib" / "Windows_x86_64" (lib / "rel").mkdir(parents=True) (lib / "x64").mkdir() dll, sdk = lib / "rel" / "nvngx_dlss.dll", lib / "x64" / "nvsdk_ngx_d.lib" for build in ("diag", "release"): (root / "target" / build).mkdir(parents=True) (root / "target" / build / "leonida.exe").touch() menu = root / "leonida-settings.txt" # The launcher looks for cargo: a stand-in on a PATH that holds no other, so this PC's does not decide. tools = root / "tools" tools.mkdir() (tools / "cargo.cmd").write_text("@exit /b 0\r\n", encoding="ascii") found_as = {".ps1", *(e.lower() for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep) if e)} no_cargo = os.pathsep.join( d for d in os.environ.get("PATH", "").split(os.pathsep) if d and not any((Path(d) / f"cargo{ext}").exists() for ext in found_as)) env = {k: v for k, v in os.environ.items() if not k.startswith("LEONIDA_")} env.update(TEST_SCRIPT=str(script), TEST_EXE=str(exe)) command = ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"] launch = "& $env:TEST_SCRIPT -Exe $env:TEST_EXE -NoFrameGen -DryRun" without, with_dlss = "diagnostics,mimalloc", "diagnostics,dlss,mimalloc" here = {"sdk", "dll", "cargo", "menu"} # (the build's note, what is here, switches) -> (a build is asked for, LEONIDA_UPSCALE, the own upscaler) cases = ( # The reported start: the menu's DLSS behind a replayed -Resolution. (without, here, "-Resolution 720 -MenuRestart", True, "dlss", None), # A -Resolution typed for this start wins over the menu's choice, and the build is asked for all the same. (without, here, "-Resolution 720", True, None, "1"), # Series X drops a DLSS choice that -Dlss did not make; the SDK still asks for the build. (without, here, "-SeriesX -MenuRestart", True, None, "1"), # No menu file: Series S asks for DLSS by itself, and the dry run shows it after the build too. (without, here - {"menu"}, "", True, "dlss", None), (with_dlss, here, "-Resolution 720 -MenuRestart", False, "dlss", None), (without, here - {"sdk"}, "-Resolution 720 -MenuRestart", False, "stretch", "1"), (without, here, "-Resolution 720 -NoDlss -MenuRestart", False, "stretch", "1"), # Only the diag build is made here. (without, here, "-Resolution 720 -MenuRestart -Build release", False, "stretch", "1"), # The build alone is not DLSS: without NVIDIA's own file the start still falls back. (without, here - {"dll"}, "-Resolution 720 -MenuRestart", True, "stretch", "1"), # Without cargo nothing can be built: the launcher says so and the build that is here runs. (without, here - {"cargo"}, "-Resolution 720 -MenuRestart", False, "stretch", "1"), ) for built, there, args, asked, upscaler, own in cases: with self.subTest(built=built, missing=sorted(here - there), args=args): for build in ("diag", "release"): (root / "target" / build / "built-with.txt").write_text(built, encoding="ascii") for name, file in (("sdk", sdk), ("dll", dll)): if name in there: file.touch() elif file.exists(): file.unlink() if "menu" in there: menu.write_text("LEONIDA_UPSCALE=dlss\n", encoding="utf-8") elif menu.exists(): menu.unlink() env["PATH"] = (str(tools) + os.pathsep if "cargo" in there else "") + no_cargo res = subprocess.run([*command, f"{launch} {args}"], env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60) self.assertEqual(res.returncode, 0, res.stderr) self.assertEqual("builds the layer again with DLSS" in res.stdout, asked, res.stdout) self.assertEqual("there is no cargo" in res.stdout, "cargo" not in there, res.stdout) settings = dict(line.split("=", 1) for line in res.stdout.splitlines() if line.startswith("LEONIDA_") and "=" in line) self.assertEqual(settings.get("LEONIDA_UPSCALE"), upscaler) self.assertEqual(settings.get("LEONIDA_OWN_UPSCALER"), own) # The note of a build whose exe is gone, and no cargo: nothing here "runs", so the dry run says neither. (root / "target" / "diag" / "leonida.exe").unlink() env["PATH"] = no_cargo res = subprocess.run([*command, f"{launch} -Resolution 720 -MenuRestart"], env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60) self.assertEqual(res.returncode, 0, res.stderr) self.assertNotIn("there is no cargo", res.stdout) self.assertNotIn("builds the layer again with DLSS", res.stdout) def test_the_restart_replays_every_frame_generation_switch(self): """The menu's SAVE AND RESTART starts the launcher again with LEONIDA_MENU_ARGS: a switch left out of it is lost on that start (-NoFrameGen was, and the restart turned frame generation on).""" with tempfile.TemporaryDirectory() as tmp: exe = Path(tmp) / "title.exe" exe.write_bytes(b"") res = subprocess.run( ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), "-Exe", str(exe), "-SeriesX", "-Lowest", "1080", "-NoFrameGen", "-FsrFrameGen", "-DryRun"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120, ) self.assertEqual(res.returncode, 0, res.stderr) args = next(l for l in res.stdout.splitlines() if l.startswith("LEONIDA_MENU_ARGS=")) for switch in ("-NoFrameGen", "-FsrFrameGen", "-SeriesX", "-Lowest '1080'", "-MenuRestart"): self.assertIn(switch, args) if __name__ == "__main__": unittest.main()