From 031bab29f8905a5c6eba0c306f5e328e23b54e54 Mon Sep 17 00:00:00 2001 From: EdenBendheim Date: Mon, 23 Nov 2026 11:07:17 -0500 Subject: [PATCH 01/42] Repair zero-byte DDS files on TTPF resume Require a non-empty file before the manifest or exporter considers a DDS complete. Rebuild empty outputs through the atomic writer and cover skipped rows and surviving siblings with synthetic tests. --- make_game.py | 37 +++++++++++--- tests/test_make_game_dry_run.py | 86 ++++++++++++++++++++++---------- tests/test_ttpf_export_resume.py | 61 ++++++++++++++++++++++ tools/rpf9dump/Program.cs | 16 +++++- 4 files changed, 164 insertions(+), 36 deletions(-) diff --git a/make_game.py b/make_game.py index 83cc5fd367..54752a1600 100644 --- a/make_game.py +++ b/make_game.py @@ -2064,12 +2064,10 @@ def rpf9dump(work: str) -> str: def ttpf_manifest(pool_dir: str) -> dict | None: - """An older exporter could publish the manifest after a failed DDS write. Check its promised files on resume.""" + """Accept the resume manifest only when every listed DDS is a non-empty regular file.""" try: with open(os.path.join(pool_dir, "manifest.json"), encoding="utf-8") as f: doc = json.load(f) - with os.scandir(pool_dir) as it: - have = {e.name for e in it if e.is_file()} except (OSError, ValueError, RecursionError): return None if not isinstance(doc, dict): @@ -2077,18 +2075,41 @@ def ttpf_manifest(pool_dir: str) -> dict | None: rows, count = doc.get("Textures"), doc.get("Count") if not isinstance(rows, list) or type(count) is not int or count != len(rows): return None + wanted: set[str] = set() for row in rows: if not isinstance(row, dict) or "File" not in row: return None name = row["File"] if name is None: # The catalog marked this texture unsupported. continue - if not isinstance(name, str): + if not isinstance(name, str) or name != os.path.basename(name): + return None + wanted.add(name) + if not wanted: + return doc + try: + with os.scandir(pool_dir) as it: + for entry in it: + if entry.name not in wanted: + continue + try: + # On Windows, DirEntry.stat() reuses FindFirstFile data for ordinary files and follows symlinks. + output = entry.stat() + except OSError: + return None + if not stat.S_ISREG(output.st_mode) or output.st_size == 0: + return None + wanted.remove(entry.name) + except OSError: + return None + for name in wanted: + # An existing file may use another spelling on a case-insensitive volume. + try: + output = os.stat(os.path.join(pool_dir, name)) + except (OSError, ValueError): + return None + if not stat.S_ISREG(output.st_mode) or output.st_size == 0: return None - if name not in have: - # An existing file may use another spelling on a case-insensitive volume. - if name != os.path.basename(name) or not os.path.isfile(os.path.join(pool_dir, name)): - return None return doc diff --git a/tests/test_make_game_dry_run.py b/tests/test_make_game_dry_run.py index 6a7d1ebd66..5d7d830b3c 100644 --- a/tests/test_make_game_dry_run.py +++ b/tests/test_make_game_dry_run.py @@ -273,7 +273,7 @@ def setUp(self) -> None: def test_pipelines_fails_when_spirv_index_is_missing(self) -> None: dummy_exe = os.path.join(self.tmp.name, "vk_pipeline_check.exe") - with open(dummy_exe, "w", encoding="utf-8") as f: + with open(dummy_exe, "w", encoding="utf-8", newline="\n") as f: f.write("dummy") with mock.patch("make_game.pipeline_check_exe", return_value=dummy_exe): stderr_buf = io.StringIO() @@ -286,7 +286,7 @@ def test_pipelines_fails_when_spirv_index_is_missing(self) -> None: def test_pipelines_fails_when_pipeline_check_exe_not_built_on_windows(self) -> None: spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") os.makedirs(spirv_dir, exist_ok=True) - with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: f.write("{}") with mock.patch("make_game.pipeline_check_exe", return_value=None), \ @@ -301,7 +301,7 @@ def test_pipelines_fails_when_pipeline_check_exe_not_built_on_windows(self) -> N def test_pipelines_fails_when_pipeline_check_exe_not_built_on_posix(self) -> None: spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") os.makedirs(spirv_dir, exist_ok=True) - with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: f.write("{}") with mock.patch("make_game.pipeline_check_exe", return_value=None), \ @@ -317,11 +317,11 @@ def test_pipelines_executes_compiler_isolated_with_expected_command_line(self) - spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") os.makedirs(spirv_dir, exist_ok=True) index_path = os.path.join(spirv_dir, "index.json") - with open(index_path, "w", encoding="utf-8") as f: + with open(index_path, "w", encoding="utf-8", newline="\n") as f: f.write('{"shader_0": {}}') # a finished translation is never empty dummy_exe = os.path.join(self.tmp.name, "vk_pipeline_check.exe") - with open(dummy_exe, "w", encoding="utf-8") as f: + with open(dummy_exe, "w", encoding="utf-8", newline="\n") as f: f.write("binary") expected_cache = os.path.join(self.out_dir, "pipeline_cache.bin") @@ -392,19 +392,19 @@ def test_shaders_stage_skips_finished_steps_based_on_markers(self) -> None: os.makedirs(os.path.join(dxbc_dir, "disasm")) os.makedirs(spirv_dir, exist_ok=True) - with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: f.write('[{"file": "shader.dxbc"}]') - with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8", newline="\n") as f: f.write('[{"name": "shader"}]') with open(os.path.join(dxbc_dir, "disasm", "shader.s"), "w", encoding="utf-8", newline="\n") as f: f.write("synthetic listing\n") - with open(os.path.join(dxbc_dir, "disasm.done"), "w", encoding="utf-8") as f: + with open(os.path.join(dxbc_dir, "disasm.done"), "w", encoding="utf-8", newline="\n") as f: f.write("test llvm-mc 21\n") - with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: f.write('{"shader": {}}') # a bare {} is an empty merge and is translated again (translated_index_is_empty) - with open(os.path.join(spirv_dir, "wave64_emulate.txt"), "w", encoding="utf-8") as f: + with open(os.path.join(spirv_dir, "wave64_emulate.txt"), "w", encoding="utf-8", newline="\n") as f: f.write("off\n") - with open(os.path.join(spirv_dir, "translation_sources.sha256"), "w", encoding="utf-8") as f: + with open(os.path.join(spirv_dir, "translation_sources.sha256"), "w", encoding="utf-8", newline="\n") as f: f.write(make_game.translation_sources_digest() + "\n") with mock.patch("make_game.py") as mock_py, \ @@ -423,9 +423,9 @@ def test_shaders_step_invalidation_when_early_marker_missing(self) -> None: disasm_done = os.path.join(dxbc_dir, "disasm.done") spirv_index = os.path.join(spirv_dir, "index.json") - with open(disasm_done, "w", encoding="utf-8") as f: + with open(disasm_done, "w", encoding="utf-8", newline="\n") as f: f.write("done\n") - with open(spirv_index, "w", encoding="utf-8") as f: + with open(spirv_index, "w", encoding="utf-8", newline="\n") as f: f.write("{}\n") fake_py_calls = [] @@ -433,10 +433,10 @@ def test_shaders_step_invalidation_when_early_marker_missing(self) -> None: def fake_py(tool: str, *args: str) -> None: fake_py_calls.append(tool) if tool == "shader_carve.py": - with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: f.write('[{"file": "shader.dxbc"}]') elif tool == "fssm_unpack.py": - with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8") as f: + with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8", newline="\n") as f: f.write('[{"name": "shader"}]') elif tool == "shader_disasm.py": disasm = os.path.join(dxbc_dir, "disasm") @@ -464,16 +464,16 @@ def test_assets_stage_skips_existing_markers(self) -> None: for mode in ("models", "textures"): dest = os.path.join(assets_dir, name, mode) os.makedirs(dest, exist_ok=True) - with open(os.path.join(dest, "manifest.json"), "w", encoding="utf-8") as f: + with open(os.path.join(dest, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: f.write("{}") - with open(os.path.join(dest, make_game.DECODER_RECORD), "w", encoding="utf-8") as f: + with open(os.path.join(dest, make_game.DECODER_RECORD), "w", encoding="utf-8", newline="\n") as f: f.write(make_game.decoder_digest()) - with open(os.path.join(audio_dir, "audio_manifest.json"), "w", encoding="utf-8") as f: + with open(os.path.join(audio_dir, "audio_manifest.json"), "w", encoding="utf-8", newline="\n") as f: f.write("{}") - with open(os.path.join(audio_dir, "ogg.done"), "w", encoding="utf-8") as f: + with open(os.path.join(audio_dir, "ogg.done"), "w", encoding="utf-8", newline="\n") as f: f.write("done\n") - with open(os.path.join(audio_dir, "xma.done"), "w", encoding="utf-8") as f: + with open(os.path.join(audio_dir, "xma.done"), "w", encoding="utf-8", newline="\n") as f: f.write("done\n") with mock.patch("make_game.rpf9dump") as exporter, \ @@ -486,7 +486,7 @@ def test_assets_stage_skips_existing_markers(self) -> None: mock_run.assert_not_called() mock_py.assert_not_called() - def test_texture_pools_resume_only_when_their_listed_dds_files_exist(self) -> None: + def test_texture_pools_resume_only_when_their_listed_dds_files_are_nonempty(self) -> None: assets = Path(self.work_dir, "assets") audio = assets / "audio" audio.mkdir(parents=True) @@ -504,28 +504,31 @@ def test_texture_pools_resume_only_when_their_listed_dds_files_exist(self) -> No src.touch() (dest / "sample").mkdir(parents=True) (dest / "sample" / "first.dds").write_bytes(b"completed sibling") - (dest / "sample" / make_game.DECODER_RECORD).write_text(make_game.decoder_digest(), encoding="utf-8") + (dest / "sample" / make_game.DECODER_RECORD).write_text(make_game.decoder_digest(), encoding="utf-8", newline="\n") (pack_dest / "sample" / "second.dds").mkdir() + (base_dest / "sample" / "empty.dds").touch() valid = json.dumps({"Count": 2, "Textures": [{"File": "first.dds"}, {"File": None}]}) legacy = json.dumps({"Count": 2, "Textures": [{"File": "first.dds"}, {"File": "second.dds"}]}) + empty = json.dumps({"Count": 2, "Textures": [{"File": "first.dds"}, {"File": "empty.dds"}]}) base_call = mock.call(["rpf9dump", "ttpf", str(base_source), str(base_dest)]) pack_call = mock.call(["rpf9dump", "ttpf", str(pack_source), str(pack_dest)]) def publish_catalog(cmd): - (Path(cmd[3]) / "sample" / "manifest.json").write_text(valid, encoding="utf-8") + (Path(cmd[3]) / "sample" / "manifest.json").write_text(valid, encoding="utf-8", newline="\n") for case, base_manifest, pack_manifest, expected in ( ("complete including skipped rows", valid, valid, []), ("listed DDS is missing", legacy, valid, [base_call]), ("listed DDS is a directory", valid, legacy, [pack_call]), + ("listed DDS is empty", empty, valid, [base_call]), ("missing texture list", "{}", valid, [base_call]), ("incomplete row list", '{"Count": 2, "Textures": [{"File": "first.dds"}]}', valid, [base_call]), ("missing File field", valid, '{"Count": 1, "Textures": [{}]}', [pack_call]), ("incomplete JSON", valid, "{", [pack_call]), ): with self.subTest(case=case): - (base_dest / "sample" / "manifest.json").write_text(base_manifest, encoding="utf-8") - (pack_dest / "sample" / "manifest.json").write_text(pack_manifest, encoding="utf-8") + (base_dest / "sample" / "manifest.json").write_text(base_manifest, encoding="utf-8", newline="\n") + (pack_dest / "sample" / "manifest.json").write_text(pack_manifest, encoding="utf-8", newline="\n") with mock.patch.object(make_game, "MODEL_ARCHIVES", ()), \ mock.patch.object(make_game, "rpf9dump", return_value="rpf9dump"), \ mock.patch.object(make_game, "run", side_effect=publish_catalog) as run, \ @@ -533,6 +536,35 @@ def publish_catalog(cmd): make_game.assets(self.game_dir, self.work_dir, wav=False, jobs=1) self.assertEqual(run.call_args_list, expected) + def test_ttpf_manifest_requires_nonempty_listed_dds_files(self) -> None: + pool_dir = os.path.join(self.tmp.name, "pool") + os.makedirs(pool_dir) + manifest = {"Count": 3, "Textures": [ + {"File": "first.dds"}, {"File": "second.dds"}, + {"File": None, "BCPackLimitation": "unsupported codec"}, + ]} + with open(os.path.join(pool_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(manifest, f) + first = os.path.join(pool_dir, "first.dds") + second = os.path.join(pool_dir, "second.dds") + for path in (first, second): + with open(path, "wb") as f: + f.write(b"dds") + with mock.patch.object(make_game.os, "stat", side_effect=AssertionError("unexpected path stat")): + self.assertEqual(make_game.ttpf_manifest(pool_dir), manifest) + + alt_case = {"Count": 2, "Textures": [{"File": "FIRST.DDS"}, {"File": "second.dds"}]} + with open(os.path.join(pool_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(alt_case, f) + with mock.patch.object(make_game.os, "stat", side_effect=PermissionError): + self.assertIsNone(make_game.ttpf_manifest(pool_dir)) + + with open(os.path.join(pool_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(manifest, f) + with open(second, "wb"): + pass + self.assertIsNone(make_game.ttpf_manifest(pool_dir)) + def test_pending_exports_refresh_the_existing_helper_once(self) -> None: # Built under the repo (not --work) so `dotnet -o` is not pointed at a locked remote path. output = os.path.join(self.tmp.name, "tools", "rpf9dump", "bin", "Release", "net8.0") @@ -560,9 +592,9 @@ def test_drop_removes_existing_marker_files(self) -> None: p1 = os.path.join(self.work_dir, "m1.txt") p2 = os.path.join(self.work_dir, "m2.txt") p3 = os.path.join(self.work_dir, "nonexistent.txt") - with open(p1, "w", encoding="utf-8") as f: + with open(p1, "w", encoding="utf-8", newline="\n") as f: f.write("1") - with open(p2, "w", encoding="utf-8") as f: + with open(p2, "w", encoding="utf-8", newline="\n") as f: f.write("2") self.assertTrue(os.path.isfile(p1)) self.assertTrue(os.path.isfile(p2)) diff --git a/tests/test_ttpf_export_resume.py b/tests/test_ttpf_export_resume.py index e63d7e3cb9..46a69241d2 100644 --- a/tests/test_ttpf_export_resume.py +++ b/tests/test_ttpf_export_resume.py @@ -83,6 +83,67 @@ def test_manifest_is_published_only_after_all_extractable_outputs_exist(self): self.assertEqual([sibling.read_bytes(), blocked.read_bytes()], expected) self.assertEqual(sibling.stat().st_mtime_ns, saved_mtime) + def test_resume_repairs_empty_dds_and_keeps_siblings(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + write_pool(pool) + out = root / "out" + clean = export(pool, out) + self.assertEqual(clean.returncode, 0, clean.stdout + clean.stderr) + + folder = out / pool.stem + rows = textures(folder) + skipped, first, second = rows + self.assertIsNone(skipped["File"]) + self.assertTrue(skipped["Limitation"]) + damaged = folder / first["File"] + sibling = folder / second["File"] + original = damaged.read_bytes() + self.assertTrue(original) + sibling_bytes = sibling.read_bytes() + damaged.write_bytes(b"") + os.utime(sibling, (1_000_000_000, 1_000_000_000)) + sibling_mtime = sibling.stat().st_mtime_ns + + resumed = export(pool, out) + self.assertEqual(resumed.returncode, 0, resumed.stdout + resumed.stderr) + self.assertEqual(damaged.read_bytes(), original) + self.assertEqual(sibling.read_bytes(), sibling_bytes) + self.assertEqual(sibling.stat().st_mtime_ns, sibling_mtime) + self.assertEqual(textures(folder), rows) + self.assertEqual({p.name for p in folder.glob("*.dds")}, {damaged.name, sibling.name}) + + def test_resume_checks_dds_symlink_targets(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + write_pool(pool) + out = root / "out" + clean = export(pool, out) + self.assertEqual(clean.returncode, 0, clean.stdout + clean.stderr) + + folder = out / pool.stem + _, first, second = textures(folder) + damaged, sibling = (folder / row["File"] for row in (first, second)) + original = damaged.read_bytes() + empty_target = root / "empty" + empty_target.touch() + sibling_target = root / "sibling" + sibling.rename(sibling_target) + damaged.unlink() + try: + damaged.symlink_to(empty_target) + sibling.symlink_to(sibling_target) + except (NotImplementedError, OSError) as exc: + self.skipTest(f"symlinks unavailable: {exc}") + + resumed = export(pool, out) + self.assertEqual(resumed.returncode, 0, resumed.stdout + resumed.stderr) + self.assertEqual(damaged.read_bytes(), original) + self.assertEqual(empty_target.read_bytes(), b"") + self.assertTrue(sibling.is_symlink()) + def test_undecodable_texture_is_a_limitation_and_siblings_still_publish(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) diff --git a/tools/rpf9dump/Program.cs b/tools/rpf9dump/Program.cs index efb4c9989b..911ab8183e 100644 --- a/tools/rpf9dump/Program.cs +++ b/tools/rpf9dump/Program.cs @@ -83,7 +83,7 @@ string path = Path.Combine(outDir, name); string? file = t.CanExtract ? name : null, limitation = t.Limitation; if (!t.CanExtract) Interlocked.Increment(ref skip); - else if (File.Exists(path)) Interlocked.Increment(ref ok); + else if (HasNonemptyDds(path)) Interlocked.Increment(ref ok); else { try @@ -399,6 +399,20 @@ Result Export(ArchiveEntry e) Console.WriteLine($"{mode} {baseName}: ok={ok} fail={fail} skip={skip} in {sw.Elapsed.TotalSeconds:0}s"); return (mode == "ttpf" && fail != 0) || writeFail != 0 ? 1 : 0; +static bool HasNonemptyDds(string path) +{ + try + { + FileSystemInfo output = new FileInfo(path); + if (!output.Exists) return false; + // FileInfo.Length can report the link's length instead of its target's length. + if ((output.Attributes & FileAttributes.ReparsePoint) != 0) + output = output.ResolveLinkTarget(returnFinalTarget: true) ?? output; + return output is FileInfo file && file.Exists && file.Length > 0; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return false; } +} + // A stale marker may be read-only from an earlier interrupted run; clear the attribute so the withdraw works. static void WithdrawMarker(string path) { From d90e4b213f82d12ab45250ddc0b3c6a110d35e7a Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 17:09:40 +0300 Subject: [PATCH 02/42] world_build: restore write mode before unlink on replace failure in _write_json_atomic (WORLD-BUILD-STAGE-CLEANUP) When writing world JSON atomically, if os.replace fails (for instance due to permission errors), resetting os.chmod to 0o600 ensures unlinking the temporary file does not fail on Windows with PermissionError. agent: yes AI-assisted: yes --- tests/test_world_build.py | 18 ++++++++++++++++++ tools/world_build.py | 1 + 2 files changed, 19 insertions(+) diff --git a/tests/test_world_build.py b/tests/test_world_build.py index 6524d92106..65d800eb9f 100644 --- a/tests/test_world_build.py +++ b/tests/test_world_build.py @@ -2068,6 +2068,24 @@ def test_stale_cleanup_preserves_staging_with_unrestored_previous_chunks(self): with open(os.path.join(recovery, "previous", "c_0_0.glb"), "rb") as f: self.assertEqual(f.read(), b"previous chunk") + def test_write_json_atomic_cleanup_restores_write_mode_on_replace_failure(self): + with tempfile.TemporaryDirectory() as tmp: + dest = os.path.join(tmp, "world.json") + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(p, mode, **kwargs): + chmod_calls.append((p, mode)) + return real_chmod(p, mode, **kwargs) + + def failing_replace(src, dst): + raise OSError("replace failed") + + with unittest.mock.patch("world_build.os.chmod", side_effect=track_chmod): + with self.assertRaises(OSError): + world_build._write_json_atomic(dest, {"test": 1}, replace=failing_replace) + self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) + # --------------------------------------------------------------------------- # 4. viewer/serve.py tests diff --git a/tools/world_build.py b/tools/world_build.py index d2a71762fd..857ffbb9ca 100644 --- a/tools/world_build.py +++ b/tools/world_build.py @@ -1218,6 +1218,7 @@ def _write_json_atomic(path: str, data: dict, replace=None) -> None: except BaseException: try: if tmp_path is not None: + os.chmod(tmp_path, 0o600) os.remove(tmp_path) except OSError: pass From b5dd9acbb6de86b17d19be3c3ae5e34601191341 Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 17:21:01 +0300 Subject: [PATCH 03/42] dds_png: restore write mode before unlink on replace failure in main (DDS-PNG-STAGE-CLEANUP) When previewing/saving PNG in CLI main(), if os.replace fails after shutil.copymode set the destination's permissions, resetting os.chmod to 0o600 ensures TemporaryDirectory cleanup does not fail with PermissionError on Windows if the output was read-only. agent: yes AI-assisted: yes --- tests/test_dds_png.py | 20 ++++++++++++++++++++ tools/dds_png.py | 6 +++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/test_dds_png.py b/tests/test_dds_png.py index 4d800b25b4..1e80aa8c91 100644 --- a/tests/test_dds_png.py +++ b/tests/test_dds_png.py @@ -1268,6 +1268,26 @@ def test_cli_writes_the_png(self): raw = zlib.decompress(b"".join(p for t, p, _ in chunks if t == b"IDAT")) self.assertEqual(raw[1:], bytes((255, 0, 128, 255, 0, 255, 64, 128))) + def test_cli_cleanup_restores_write_mode_on_replace_failure(self): + payload = halves(0x3C00, 0x0000, 0x3800, 0x3C00, 0x7E00, 0x7C00, 0x3400, 0x3800) + with tempfile.TemporaryDirectory() as tmp: + src = os.path.join(tmp, "in.dds") + dst = os.path.join(tmp, "out.png") + with open(src, "wb") as f: + f.write(dds_buffer(2, 1, payload, pitch=16, dxgi=10, **HALF_FLOAT)) + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(p, mode, **kwargs): + chmod_calls.append((p, mode)) + return real_chmod(p, mode, **kwargs) + + with mock.patch.object(dds.os, "replace", side_effect=OSError("replace failed")), \ + mock.patch.object(dds.os, "chmod", side_effect=track_chmod): + ret = dds.main([src, dst]) + self.assertEqual(ret, 1) + self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) + if __name__ == "__main__": unittest.main() diff --git a/tools/dds_png.py b/tools/dds_png.py index dd59d75455..eb5ce48e95 100644 --- a/tools/dds_png.py +++ b/tools/dds_png.py @@ -1538,7 +1538,11 @@ def main(argv: list[str] | None = None) -> int: f.write(png) if os.path.isfile(output): shutil.copymode(output, pending) - os.replace(pending, output) + try: + os.replace(pending, output) + except BaseException: + os.chmod(pending, 0o600) + raise except (DdsError, OSError) as exc: print(f"ERROR: {exc}", file=sys.stderr) return 1 From 2cb6ed88211623460ceab5b3d9cf819d1816fb26 Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 17:22:00 +0300 Subject: [PATCH 04/42] world_names: restore write mode before unlink on replace failure and publish mode (WORLD-NAMES-STAGE-CLEANUP) When writing dictionary JSON atomically in _write_json, apply published_mode to the staged file and reset os.chmod to 0o600 before exiting TemporaryDirectory if os.replace fails, ensuring cleanup does not fail with PermissionError on Windows when replacing a read-only file. agent: yes AI-assisted: yes --- tests/test_world_names.py | 16 ++++++++++++++++ tools/world_names.py | 8 +++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/tests/test_world_names.py b/tests/test_world_names.py index ceb2dc92b3..c62916274b 100644 --- a/tests/test_world_names.py +++ b/tests/test_world_names.py @@ -588,6 +588,22 @@ def test_build_out_refuses_to_overwrite_an_input(self): with open(source, "rb") as handle: self.assertEqual(handle.read(), original) + def test_stage_cleanup_restores_write_mode_on_replace_failure(self): + with tempfile.TemporaryDirectory() as tmp: + dest = os.path.join(tmp, "out.json") + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(p, mode, **kwargs): + chmod_calls.append((p, mode)) + return real_chmod(p, mode, **kwargs) + + with mock.patch.object(WN.os, "replace", side_effect=OSError("replace failed")), \ + mock.patch.object(WN.os, "chmod", side_effect=track_chmod): + with self.assertRaises(OSError): + WN._write_json(dest, {}) + self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) + if __name__ == "__main__": unittest.main() diff --git a/tools/world_names.py b/tools/world_names.py index a7b4ca84d1..ae600c3072 100644 --- a/tools/world_names.py +++ b/tools/world_names.py @@ -38,6 +38,7 @@ # -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from file_mode import published_mode # noqa: E402 from report_paths import same_report_path # noqa: E402 MASK32 = 0xFFFFFFFF @@ -630,7 +631,12 @@ def _write_json(path: str, data: dict) -> None: with open(tmp, "w", encoding="utf-8", newline="\n") as handle: json.dump(data, handle, indent=1, sort_keys=True) handle.write("\n") - os.replace(tmp, path) + os.chmod(tmp, published_mode(path)) + try: + os.replace(tmp, path) + except BaseException: + os.chmod(tmp, 0o600) + raise def main(argv=None) -> int: From ac42150c720f1ac867013b5e5fc9b06317f67d4b Mon Sep 17 00:00:00 2001 From: robot00f Date: Tue, 24 Nov 2026 15:00:48 -0300 Subject: [PATCH 05/42] gpu-test-results: 4 GB Pascal card on Windows (GPU-PASCAL4GB-WIN) --- gpu-test-results/NvidiaPascal4GB.txt | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 gpu-test-results/NvidiaPascal4GB.txt diff --git a/gpu-test-results/NvidiaPascal4GB.txt b/gpu-test-results/NvidiaPascal4GB.txt new file mode 100644 index 0000000000..6c624b42cb --- /dev/null +++ b/gpu-test-results/NvidiaPascal4GB.txt @@ -0,0 +1,34 @@ +GPU: NVIDIA GPU (Pascal class, 4 GB of VRAM), subgroup 32..32 (model and PCI id withheld) +Driver: NVIDIA 582.28 (proprietary), Vulkan device API 1.4.312 +OS: Windows 10 Pro, 10.0.19045 +Commit: 82a2aabcc33bf296b5c2e3e4e7021fa506f8570e (main, 2026-11-24) +Tools: llvm-mc 23.1.6 (conda-forge llvm-tools, AMDGPU target), SPIRV-Tools v2026.4, + CMake 4.4.5, Ninja 1.13.2, g++ 13.2.0 (Strawberry MinGW-w64 UCRT), Python 3.13, Release +build.py: 284 shaders: 284 translated, 284 pass spirv-val + not built (need a DXBC container with signatures): ms_clip, ms_f16_pack, ms_tri, + ms_v5_workgroup, ms_w64x_ballot, ms_wave_info_s3 +check.py: 178 of 222 pass, 42 skipped, 2 failed +run_gpu_tests.py: 284 shaders: 284 translated, 284 pass spirv-val + native: 191/252 passed, 59 skipped, 2 failed + LEONIDA_W64_EMULATE=1: 222/252 passed, 28 skipped, 2 failed +Failed: cs_imgload_tfe and cs_imgload_d16_tfe, both "exit 1: r32 sint (sint view): 64 bad, + texel(5,3) = 2071". Deterministic here: 3 of 3 isolated --filter reruns per case failed + with the same texel and count, in the native and the emulated path alike. Known rows, + not new: #31 on Intel Meteor Lake (passing there with #98) and the Apple M5 run (passing + with #291). +Skipped: Both runs: the six mesh cases (no VK_EXT_mesh_shader), five pixel cases reading + BaryCoordKHR (no VK_KHR_fragment_shader_barycentric: ps_bary, ps_persp_bary, + ps_scc_mask32, ps_uniform_branch, and ps_ij_computed, which was not translated), + one 64-wide fragment subgroup case, and 16 cases run by the d3d12_*_test and + w64_graphics.py programs. Native additionally skipped 31 cases needing a 64-wide + compute subgroup; the emulated run carried those. +Notes: +- The Vulkan test tools were built from the same commit with LEONIDA_BUILD_WINDOWS_RUNTIME=OFF + and LEONIDA_VULKAN_HEADERS_FETCH=ON. The separate D3D12 and w64_graphics test programs were + not run (the d3d12_* CMake targets need the Windows SDK d3d12.h, which this machine lacks; + the GPU suite below does not link them). +- Implicit Vulkan layers disabled (VK_LOADER_LAYERS_DISABLE=~implicit~): the machine has the OBS + and RenderDoc implicit layers installed. +- Wave64 VS/PS/GS on 32-wide subgroups: tier A: 11, tier B: 8, tier C: 13. Tier C is not exact there. +- No game files were used; the suite runs its handwritten fixtures. +- AI-assisted: OpenCode (DeepSeek V4.1 Flash) built the tools, ran the tests and prepared this report. From ef46cae4ccf7262a4aac830332fa43dd8db4770a Mon Sep 17 00:00:00 2001 From: robot00f Date: Tue, 24 Nov 2026 16:34:39 -0300 Subject: [PATCH 06/42] gpu-test-results: spot reruns for the known-failure and wave64 rows (GPU-PASCAL4GB-WIN) --- gpu-test-results/NvidiaPascal4GB.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/gpu-test-results/NvidiaPascal4GB.txt b/gpu-test-results/NvidiaPascal4GB.txt index 6c624b42cb..65ca5d189a 100644 --- a/gpu-test-results/NvidiaPascal4GB.txt +++ b/gpu-test-results/NvidiaPascal4GB.txt @@ -16,6 +16,11 @@ Failed: cs_imgload_tfe and cs_imgload_d16_tfe, both "exit 1: r32 sint (sint with the same texel and count, in the native and the emulated path alike. Known rows, not new: #31 on Intel Meteor Lake (passing there with #98) and the Apple M5 run (passing with #291). +Spot reruns (same commit and binaries, --filter, each case 3 times native and 3 emulated): + cs_fma_fused 3/3 pass native, 3/3 pass emulated ("8/8 fused exact") + ps_imgatomic 3/3 pass native, 3/3 pass emulated (0 of 256 texels, 0 of 4096 pixels wrong) + The two rows that fail or flake on MoltenVK are stable passes here. Three wave64 cases that only + run emulated also pass 2/2 each: cs_w64_exec_computed, cs_wave64_ballot, cs_w64_mask_detect. Skipped: Both runs: the six mesh cases (no VK_EXT_mesh_shader), five pixel cases reading BaryCoordKHR (no VK_KHR_fragment_shader_barycentric: ps_bary, ps_persp_bary, ps_scc_mask32, ps_uniform_branch, and ps_ij_computed, which was not translated), From 4210685ecea3b90f381efae12022409df0af54a4 Mon Sep 17 00:00:00 2001 From: robot00f Date: Tue, 24 Nov 2026 16:36:38 -0300 Subject: [PATCH 07/42] gpu-test-results: fallback runs for the barycentric and f16 rows (GPU-PASCAL4GB-WIN) --- gpu-test-results/NvidiaPascal4GB.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/gpu-test-results/NvidiaPascal4GB.txt b/gpu-test-results/NvidiaPascal4GB.txt index 65ca5d189a..4d3f14dce5 100644 --- a/gpu-test-results/NvidiaPascal4GB.txt +++ b/gpu-test-results/NvidiaPascal4GB.txt @@ -21,6 +21,13 @@ Spot reruns (same commit and binaries, --filter, each case 3 times native and 3 ps_imgatomic 3/3 pass native, 3/3 pass emulated (0 of 256 texels, 0 of 4096 pixels wrong) The two rows that fail or flake on MoltenVK are stable passes here. Three wave64 cases that only run emulated also pass 2/2 each: cs_w64_exec_computed, cs_wave64_ballot, cs_w64_mask_detect. +Fallback runs (the device has no VK_KHR_fragment_shader_barycentric, so the default run skips these): + with LEONIDA_BARY_FALLBACK=1, 2/2 pass each and exact: ps_bary (4096/4096 pixels), + ps_persp_bary (perspective-correct on every covered pixel), ps_scc_mask32 and ps_uniform_branch. + With LEONIDA_F16_INTERP_FALLBACK=1, ps_interp_f16_high passes 2/2 (halves and control within 2e-3). + ps_ij_computed still skips with both variables set: it wants PerVertexKHR inputs and the fallbacks + do not provide them. These passes are conditional on the variable, so compare them with the + default-run numbers above, not instead of them. Skipped: Both runs: the six mesh cases (no VK_EXT_mesh_shader), five pixel cases reading BaryCoordKHR (no VK_KHR_fragment_shader_barycentric: ps_bary, ps_persp_bary, ps_scc_mask32, ps_uniform_branch, and ps_ij_computed, which was not translated), From cffe269d80967821db9f8c928aee33f3d4f4e771 Mon Sep 17 00:00:00 2001 From: robot00f Date: Tue, 24 Nov 2026 16:42:08 -0300 Subject: [PATCH 08/42] gpu-test-results: run the 29 wave64 VS/PS/GS fixtures the suite leaves out (GPU-PASCAL4GB-WIN) --- gpu-test-results/NvidiaPascal4GB.txt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/gpu-test-results/NvidiaPascal4GB.txt b/gpu-test-results/NvidiaPascal4GB.txt index 4d3f14dce5..216e30a918 100644 --- a/gpu-test-results/NvidiaPascal4GB.txt +++ b/gpu-test-results/NvidiaPascal4GB.txt @@ -28,11 +28,18 @@ Fallback runs (the device has no VK_KHR_fragment_shader_barycentric, so the defa ps_ij_computed still skips with both variables set: it wants PerVertexKHR inputs and the fallbacks do not provide them. These passes are conditional on the variable, so compare them with the default-run numbers above, not instead of them. +w64_graphics.py runs (the 29 wave64 VS/PS/GS fixtures this program owns, which the suite above does not run): + built into a work folder by hand (the translator for the ps_, gs_ fixtures, the same assembler), + 2 full passes: 17 of 29 "ok" in both, the same 17 both times, 12 tier C skipped both times. + Tiers A and B pass exactly: 12 pixel, 4 vertex and 1 geometry fixtures, all against the words their + headers derive. Tier C needs one device that can require both 64 and 32 lanes before it can compare the + two images, so it skips here (or needs W64G_REF from a 64-lane GPU); this card has no 64-wide fragment + subgroup. So the A/B result is the single-size check, not the two-size comparison. Skipped: Both runs: the six mesh cases (no VK_EXT_mesh_shader), five pixel cases reading BaryCoordKHR (no VK_KHR_fragment_shader_barycentric: ps_bary, ps_persp_bary, ps_scc_mask32, ps_uniform_branch, and ps_ij_computed, which was not translated), - one 64-wide fragment subgroup case, and 16 cases run by the d3d12_*_test and - w64_graphics.py programs. Native additionally skipped 31 cases needing a 64-wide + one 64-wide fragment subgroup case, and 16 cases run by the d3d12_*_test program + (the w64_graphics.py cases were run separately, see above). Native additionally skipped 31 cases needing a 64-wide compute subgroup; the emulated run carried those. Notes: - The Vulkan test tools were built from the same commit with LEONIDA_BUILD_WINDOWS_RUNTIME=OFF From 881cf301eff6fe4e1f885bc72cba29008ebf17a3 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Wed, 25 Nov 2026 01:19:48 +0200 Subject: [PATCH 09/42] docs/d3d12_vulkan.md: the GTX 1050 Ti host-transfer measurement names driver 582.66 too Follow-up to #1364 from its review: the row named only 582.78, while that PR's run was on 582.66. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6a6d03274e..32cc80822b 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2516,7 +2516,8 @@ The trace will enumerate them. the host refuses and the layer copies on purpose. - A driver can report `VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT_EXT` for a format, create the image with host-transfer usage, and then give it no memory type (`memoryTypeBits = 0`). This was measured on a GTX 1050 Ti - with NVIDIA 582.78, and the validation layer of Vulkan SDK 1.4.363 reports nothing. Such a texture is made again + with NVIDIA 582.78 and again with 582.66 on Windows 10 (#1364), where the same image without host-transfer usage + takes device-local memory; the validation layer of Vulkan SDK 1.4.363 reports nothing. Such a texture is made again without host-transfer usage before it is bound, and takes the staging path. `d3d12_vulkan_device_test` and `d3d12_subresource_copy_test` force this branch on any GPU with `VulkanDeviceInfo::force_host_transfer_retry` (their third CPU-copy path; the second compares it with the host runtime). From 8dd9eb777c4b1c22d20e66c74ba94c7113da9fda Mon Sep 17 00:00:00 2001 From: dash Date: Tue, 24 Nov 2026 19:30:25 -0500 Subject: [PATCH 10/42] world_drawable_verify: treat another case of one archive as the same source. normcase(abspath()) kept Game/missing.rpf and game/missing.rpf apart on macOS when neither file existed, so two reports of one archive were rejected. The archive key now uses the shared path key. Co-authored-by: Cursor --- tests/test_world_drawable_verify.py | 13 ++++++++++++- tests/test_world_drawable_verify_archive_aliases.py | 11 +++++++++++ tools/world_drawable_verify.py | 5 ++++- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/tests/test_world_drawable_verify.py b/tests/test_world_drawable_verify.py index 98e1fc5de1..1ea4ce121c 100644 --- a/tests/test_world_drawable_verify.py +++ b/tests/test_world_drawable_verify.py @@ -120,8 +120,19 @@ def test_fallback_respects_normcase_for_case_aliases(self): first = self.write("First.json", export) real_first = os.path.realpath(first) upper_first = real_first.replace("First.json", "FIRST.JSON") + original_realpath = os.path.realpath + seen = {"manifest": 0} + + def realpath(path): + resolved = original_realpath(path) + if os.path.basename(resolved) == "First.json": + seen["manifest"] += 1 + if seen["manifest"] > 1: + return upper_first + return resolved + with mock.patch.object(verifier.os, "fstat", return_value=SimpleNamespace(st_dev=0, st_ino=0)), \ - mock.patch.object(verifier.os.path, "realpath", side_effect=[real_first, upper_first]), \ + mock.patch.object(verifier.os.path, "realpath", side_effect=realpath), \ mock.patch.object(verifier.os.path, "normcase", side_effect=str.lower): if os.path.exists(upper_first): self.assert_observations(predictions, [first, upper_first], 1) diff --git a/tests/test_world_drawable_verify_archive_aliases.py b/tests/test_world_drawable_verify_archive_aliases.py index 448732a410..325831372e 100644 --- a/tests/test_world_drawable_verify_archive_aliases.py +++ b/tests/test_world_drawable_verify_archive_aliases.py @@ -71,6 +71,17 @@ def test_cli_accepts_source_archive_alias(self): self.assertEqual(result.stderr, "") self.assert_confirmed(json.loads(result.stdout)) + def test_another_case_of_one_missing_archive_is_the_same_source(self): + folder = self.root / "Game" + folder.mkdir() + probe = folder / "Probe.tmp" + probe.write_bytes(b"") + if not (folder / "probe.tmp").exists(): + self.skipTest("volume keeps case") + probe.unlink() + predictions, manifest = self.reports(folder / "missing.rpf", self.root / "game" / "missing.rpf") + self.assert_confirmed(verifier.verify(predictions, [manifest])) + def test_distinct_archive_with_identical_bytes_is_rejected(self): other = self.root / "different.bin" other.write_bytes(self.archive.read_bytes()) diff --git a/tools/world_drawable_verify.py b/tools/world_drawable_verify.py index 34a122c071..a524566094 100644 --- a/tools/world_drawable_verify.py +++ b/tools/world_drawable_verify.py @@ -10,6 +10,7 @@ import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from report_paths import path_key # noqa: E402 from world_drawable_lookup import report_rows import world_build import world_names @@ -27,7 +28,9 @@ def _same_archive(first, second): def archive_path(value): if not isinstance(value, str) or not value.strip(): raise ValueError("expected a source archive path") - return os.path.normcase(os.path.abspath(value)) + # path_key folds case on a volume that ignores it. normcase(abspath()) keeps the typed case on macOS, + # so Game/missing.rpf and game/missing.rpf looked like two archives when neither file existed yet. + return path_key(value) def _manifest_identity(handle, path): From a9413ce4d64cbf438cb92e60ca45323141aa0f8e Mon Sep 17 00:00:00 2001 From: IlyassRS Date: Wed, 25 Nov 2026 04:37:10 +0100 Subject: [PATCH 11/42] sampler_source_census: fix V#/pointer/SMEM/v_mov dataflow and harden JSON I/O --- tests/test_sampler_source_census.py | 184 ++++++++++++++++++++++++++++ tools/sampler_source_census.py | 172 +++++++++++++++++++++++--- 2 files changed, 340 insertions(+), 16 deletions(-) diff --git a/tests/test_sampler_source_census.py b/tests/test_sampler_source_census.py index 7e744ec2e6..7b6a300fbf 100644 --- a/tests/test_sampler_source_census.py +++ b/tests/test_sampler_source_census.py @@ -590,6 +590,190 @@ def test_cli_report_json_and_errors(self): self.assertEqual(p.returncode, 2) self.assertTrue(p.stderr.startswith("ERROR: cannot read the carve index"), p.stderr) + def test_vsharp_with_per_dword_offset_keeps_user_class(self): + static_v = [ + ("s_add_u32 s4, s4, 0x100", 8), + ("s_addc_u32 s5, s5, 0", 4), + ("s_buffer_load_dwordx4 s[28:31], s[4:7], 0x10", 8), + SAMPLE, END, + ] + self.work.add("vs_static", "ps", static_v) + insns = ssc.shader_ir.parse_file(os.path.join(self.work.disasm, "vs_static.s"))["insns"] + uses, stats = ssc.analyse(insns, "ps", 32) + self.assertEqual(list(uses.values()), [("user_pointer", "static")]) + self.assertEqual(stats["max_pointer_constant"], 0x100) + + dyn_v = [ + ("s_lshl_b32 s1, s1, 4", 4), + ("s_add_u32 s4, s4, s1", 4), + ("s_addc_u32 s5, s5, 0", 4), + ("s_buffer_load_dwordx4 s[28:31], s[4:7], 0x10", 8), + SAMPLE, END, + ] + self.assertEqual(self.classes(dyn_v), [("user_pointer", "dynamic")]) + + def test_pointer_high_word_unary_zero_and_offset_propagation(self): + unary_zero = [ + ("s_not_b32 s9, -1", 4), + ("s_load_dwordx4 s[28:31], s[8:9], 0x40", 8), + SAMPLE, END, + ] + self.assertEqual(self.classes(unary_zero), [("user_pointer", "static")]) + + hi_const = [ + ("s_add_u32 s9, s9, 0x200", 8), + ("s_load_dwordx4 s[28:31], s[8:9], 0x40", 8), + SAMPLE, END, + ] + self.work.add("hi_c", "ps", hi_const) + insns = ssc.shader_ir.parse_file(os.path.join(self.work.disasm, "hi_c.s"))["insns"] + uses, stats = ssc.analyse(insns, "ps", 32) + self.assertEqual(list(uses.values()), [("user_pointer", "static")]) + self.assertEqual(stats["max_pointer_constant"], 0x200) + + hi_dyn = [ + ("s_lshl_b32 s5, s5, 4", 4), + ("s_add_u32 s9, s9, s5", 4), + ("s_load_dwordx4 s[28:31], s[8:9], 0x40", 8), + SAMPLE, END, + ] + self.assertEqual(self.classes(hi_dyn), [("user_pointer", "dynamic")]) + + def test_smem_inst_offset_modifier_counted_in_bounds(self): + self.work.add("dyn_mod", "ps", [ + ("s_mov_b32 s9, 0", 4), + ("s_load_dwordx4 s[28:31], s[8:9], s5 offset:0x7f004000", 8), + SAMPLE, END, + ]) + self.work.add("const_mod", "ps", [ + ("s_mov_b32 s9, 0", 4), + ("s_mov_b32 s6, 0x100", 8), + ("s_load_dwordx4 s[28:31], s[8:9], s6 offset:0x40", 8), + SAMPLE, END, + ]) + out = ssc.census(self.work.disasm) + self.assertEqual(out["total"]["classes"]["user_pointer"], 2) + self.assertEqual(out["total"]["max_pointer_constant"], 0x7f004000) + self.assertEqual(out["total"]["max_static_offset"], 0x140) + + def test_v_mov_modifiers_sdwa_and_dpp_are_not_lossless_spills(self): + lost = [("undetermined", "a dword the dataflow does not follow")] + restore = "v_readfirstlane_b32 s{s}, v{v}" + self.assertEqual(self.classes(spilled("v_mov_b32_e32 v{v}, s{s}", restore)), [("user_pointer", "static")]) + self.assertEqual(self.classes(spilled("v_mov_b32_e64 v{v}, -s{s}", restore)), lost) + self.assertEqual(self.classes(spilled("v_mov_b32_e64 v{v}, |s{s}|", restore)), lost) + self.assertEqual(self.classes(spilled("v_mov_b32_e64 v{v}, s{s} clamp", restore)), lost) + self.assertEqual( + self.classes(spilled("v_mov_b32_sdwa v{v}, s{s} dst_sel:DWORD src0_sel:BYTE_0", restore)), + lost, + ) + dpp = spilled("v_mov_b32 v{v}, s{s}", restore) + dpp.insert(7, ("v_mov_b32_dpp v9, v9 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", 8)) + self.assertEqual(self.classes(dpp), lost) + + def test_anchored_invalid_hex_skips_and_empty_blocks_do_not_crash(self): + self.assertEqual(ssc.blocks_of([]), ([], [])) + self.assertEqual( + ssc.analyse([], "ps", 32), + ({}, {"max_pointer_constant": 0, "max_static_offset": 0, "unreachable": 0}), + ) + self.work.add("badhex", "ps", USER_TABLE, blob=bytes(0x140)) + info = { + "name": "badhex", + "code_start": 0x100, + "insns": [{"op": "s_endpgm", "args": [], "mods": [], "enc": "zz", "pc": 0x100}], + } + with self.assertRaises(ssc.hic.Skip): + ssc.anchored(os.path.join(self.work.disasm, "badhex.s"), info) + + def test_census_validates_limit_and_jobs(self): + self.work.add("a", "ps", USER_TABLE) + for bad in (0, -1, True, False): + with self.assertRaises(ValueError): + ssc.census(self.work.disasm, limit=bad) + with self.assertRaises(ValueError): + ssc.census(self.work.disasm, jobs=bad) + + def test_cli_json_guards_atomic_write_and_oserror(self): + self.work.add("a", "ps", USER_TABLE, rsrc2=16 << 1) + idx_path = os.path.join(self.work.root, "index.json") + dxbc_path = os.path.join(self.work.root, "a.dxbc") + fssm_path = os.path.join(self.work.root, "fssm", "a.fssm") + listing_path = os.path.join(self.work.disasm, "a.s") + with open(idx_path, "rb") as f: + idx_before = f.read() + with open(dxbc_path, "rb") as f: + dxbc_before = f.read() + with open(fssm_path, "rb") as f: + fssm_before = f.read() + with open(listing_path, "rb") as f: + listing_before = f.read() + + hardlink = os.path.join(self.work.root, "linked_listing.json") + os.link(listing_path, hardlink) + existing_dir = os.path.join(self.work.root, "out_dir") + os.makedirs(existing_dir) + + for bad_target in ( + idx_path, + os.path.join(self.work.disasm, "census.json"), + os.path.join(self.work.disasm, "nested", "census.json"), + dxbc_path, + fssm_path, + hardlink, + existing_dir, + ): + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + rc = ssc.main([self.work.disasm, "--json", bad_target]) + self.assertEqual(rc, 2, bad_target) + self.assertTrue(err.getvalue().startswith("ERROR:"), (bad_target, err.getvalue())) + + for path, before in ((idx_path, idx_before), (dxbc_path, dxbc_before), + (fssm_path, fssm_before), (listing_path, listing_before)): + with open(path, "rb") as f: + self.assertEqual(f.read(), before, path) + + # Atomic write failure must preserve any pre-existing report and leave no temp file behind. + out_dir = os.path.join(self.work.root, "atomic") + os.makedirs(out_dir) + out_path = os.path.join(out_dir, "census.json") + with open(out_path, "w", encoding="utf-8", newline="\n") as f: + f.write('{"keep": true}\n') + orig_replace = ssc.replace_retry.replace + + def boom(src, dst, **kw): + raise OSError("disk full") + + ssc.replace_retry.replace = boom + try: + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + rc = ssc.main([self.work.disasm, "--json", out_path]) + self.assertEqual(rc, 2) + self.assertIn("ERROR: cannot write", err.getvalue()) + finally: + ssc.replace_retry.replace = orig_replace + with open(out_path, "r", encoding="utf-8") as f: + self.assertEqual(f.read(), '{"keep": true}\n') + self.assertEqual(os.listdir(out_dir), ["census.json"]) + + # OSError during census() must report ERROR and exit 2 instead of crashing. + orig_census = ssc.census + + def bad_census(*args, **kwargs): + raise OSError("read failed") + + ssc.census = bad_census + try: + err = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): + rc = ssc.main([self.work.disasm]) + self.assertEqual(rc, 2) + self.assertIn("ERROR: cannot read", err.getvalue()) + finally: + ssc.census = orig_census + if __name__ == "__main__": unittest.main() diff --git a/tools/sampler_source_census.py b/tools/sampler_source_census.py index b7277c07d8..6e06fbe142 100644 --- a/tools/sampler_source_census.py +++ b/tools/sampler_source_census.py @@ -64,14 +64,18 @@ import json import os import sys +import tempfile from collections import Counter, defaultdict from concurrent.futures import ProcessPoolExecutor sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import file_mode # noqa: E402 import heap_index_census as hic # noqa: E402 import pool_workers # noqa: E402 +import replace_retry # noqa: E402 import shader_ir # noqa: E402 import shader_meta # noqa: E402 +from report_paths import same_report_path # noqa: E402 CLASSES = ("user_sgprs", "user_pointer", "literal", "other_base", "undetermined") ENDS = ("s_endpgm", "s_setpc_b64") # no fall-through and no successor the listing names @@ -100,7 +104,10 @@ def anchored(path, info): for ins in info["insns"]: if not ins["enc"]: raise hic.Skip("embedded data words, instruction without encoding") - enc = bytes.fromhex(ins["enc"]) + try: + enc = bytes.fromhex(ins["enc"]) + except ValueError: + raise hic.Skip("embedded data words, invalid instruction encoding") from None at, skipped = pos, 0 while not rdna2spirv.same_encoding(blob[at:at + len(enc)], enc, ins["op"], len(ins["args"])): at += 4 @@ -138,6 +145,8 @@ def target(ins): def is_branch(ins): return shader_meta.base_op(ins["op"]) in hic.BRANCHES + if not insns: + return [], [] if any(is_branch(i) and not i.get("enc") for i in insns): raise hic.Skip("branch without encoding") pcs = {i["pc"] for i in insns} @@ -226,8 +235,14 @@ def step(sym, ins, lanes=None): written = [x for x in (a if op == "v_swap_b32" else a[:1]) if x["k"] == "vgpr"] lane = a[2]["v"] if op == "v_writelane_b32" and len(a) >= 3 and a[2]["k"] == "imm" else None moved = None - if op in ("v_mov_b32", "v_writelane_b32") and len(a) >= 2 and a[0].get("n", 1) == 1: - moved = sym.get(("v", a[1]["r"])) if a[1]["k"] == "vgpr" else hic._src(sym, a[1]) + if op in ("v_mov_b32", "v_writelane_b32") and len(a) >= 2 and a[0].get("n", 1) == 1 \ + and not ins["op"].endswith(("_sdwa", "_dpp")) and not ins.get("mods"): + src = a[1] + if src["k"] == "vgpr": + if src.get("n", 1) == 1 and not (src.get("neg") or src.get("abs") or src.get("sext")): + moved = sym.get(("v", src["r"])) + elif src["k"] != "sgpr" or not (src.get("neg") or src.get("abs") or src.get("sext")): + moved = hic._src(sym, src) for x in written: for r in range(x["r"], x["r"] + x.get("n", 1)): sym.pop(("v", r), None) @@ -282,6 +297,17 @@ def merge(old, new): return out +def _smem_inst_offset(mods): + """Immediate byte offset from an SMEM `offset:N` modifier, or 0.""" + for mod in mods or (): + if mod.startswith("offset:"): + try: + return int(mod.split(":", 1)[1], 0) + except ValueError: + return 0 + return 0 + + def analyse(insns, stage, user_count, follow_skips=True): """{code offset: (class, detail)} of the reachable sampling instructions, in code order, and the shader's statistics. detail: the offset kind for user_pointer ("static" / "dynamic"), the form for other_base, the @@ -289,6 +315,8 @@ def analyse(insns, stage, user_count, follow_skips=True): follow_skips=False leaves out the taken edge of every s_cbranch_execz that also falls through: the branch skips a region when no lane is active, so without it the region always runs (see the module docstring).""" blocks, succ = blocks_of(insns) + if not blocks: + return {}, {"max_pointer_constant": 0, "max_static_offset": 0, "unreachable": 0} if not follow_skips: succ = [s[1:] if len(s) == 2 and shader_meta.base_op(blk[-1]["op"]) == "s_cbranch_execz" else s for blk, s in zip(blocks, succ)] @@ -328,6 +356,7 @@ def analyse(insns, stage, user_count, follow_skips=True): loads[ins["pc"]] = { "base": None if slots is None else [shader_meta._slot_tag(sym, s) for s in slots], "offset": hic._src(sym, a[2]) if len(a) >= 3 else ("const", 0), + "inst_offset": _smem_inst_offset(ins.get("mods")), } elif op.startswith(shader_meta.SAMPLER_IMAGE_OPS) and len(a) >= 4: slots = shader_meta._sgpr_slots(a[3], 4, exact=False) @@ -385,17 +414,29 @@ def one_load_source(ld, seen): if base is None: return None, False, 0, "load base not an SGPR range" if len(base) == 4: # s_buffer_load: the V# decides - got = {source(t, seen) for t in base} - where, dyn, k = next(iter(got)) if len(got) == 1 else (None, False, 0) + got = [source(t, seen) for t in base] + wheres = {g[0] for g in got} + where = wheres.pop() if len(wheres) == 1 else None + dyn, k = any(g[1] for g in got), max(g[2] for g in got) reason = "V# from different sources" else: where, dyn, k = source(base[0], seen) reason = "load base not followed" - if where == "user" and base[1] != ("const", 0) and source(base[1], seen)[0] != "user": - where, reason = None, "pointer high word not followed" + hi_zero = base[1] is not None and base[1][0] == "const" and base[1][1] == 0 + if where == "user" and not hi_zero: + hi_where, hi_dyn, hi_k = source(base[1], seen) + if hi_where != "user": + where, reason = None, "pointer high word not followed" + else: + dyn = dyn or hi_dyn + k = max(k, hi_k) off = ld["offset"] + inst_off = ld.get("inst_offset", 0) static = off is not None and off[0] == "const" and not dyn - return where, not static, k if static or off is None else max(k, source(off, seen)[2]), reason + if static: + return where, False, k, reason + off_k = source(off, seen)[2] if off is not None else 0 + return where, True, max(k, off_k, abs(inst_off)), reason by_load = {} @@ -411,7 +452,8 @@ def one_load(pc): else: stats["max_pointer_constant"] = max(stats["max_pointer_constant"], k) if not dyn: - stats["max_static_offset"] = max(stats["max_static_offset"], ld["offset"][1]) + static_off = ld["offset"][1] + ld.get("inst_offset", 0) + stats["max_static_offset"] = max(stats["max_static_offset"], abs(static_off)) by_load[pc] = "user_pointer", "dynamic" if dyn else "static" return by_load[pc] @@ -539,11 +581,87 @@ def counts(): } +def _check_positive_int(name, value): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer, got {value!r}") + + +def _path_inside(path, folder): + cur = os.path.realpath(os.path.abspath(path)) + while True: + if same_report_path(cur, folder): + return True + parent = os.path.dirname(cur) + if parent == cur: + return False + cur = parent + + +def _same_stat(st, path): + try: + return os.path.samestat(st, os.stat(path)) + except OSError: + return False + + +def _json_input_collision(json_path, disasm_dir, stages, listing_names): + parent = os.path.dirname(os.path.abspath(disasm_dir)) + fssm_dir = os.path.join(parent, "fssm") + target_real = os.path.realpath(os.path.abspath(json_path)) + target_dir = os.path.dirname(target_real) + try: + target_stat = os.stat(target_real) + except OSError: + target_stat = None + in_parent = same_report_path(target_dir, parent) + in_fssm = same_report_path(target_dir, fssm_dir) + for name in sorted(set(stages) | set(listing_names)): + for path, in_dir in ( + (os.path.join(parent, name + ".dxbc"), in_parent), + (os.path.join(fssm_dir, name + ".fssm"), in_fssm), + (os.path.join(disasm_dir, name + ".s"), False), + ): + if (target_stat is not None and _same_stat(target_stat, path)) or ( + (in_dir or os.path.islink(path)) and same_report_path(json_path, path) + ): + return path + return None + + +def _write_json_atomic(path, data): + payload = json.dumps(data, indent=1, sort_keys=True, allow_nan=False) + "\n" + abs_path = os.path.abspath(path) + parent = os.path.dirname(abs_path) + os.makedirs(parent, exist_ok=True) + mode = file_mode.published_mode(abs_path) + tmp_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", newline="\n", + prefix=".sampler_source_census.", suffix=".tmp", + dir=parent, delete=False, + ) as f: + tmp_path = f.name + f.write(payload) + os.chmod(tmp_path, mode) + replace_retry.replace(tmp_path, abs_path) + tmp_path = None + finally: + if tmp_path is not None: + try: + os.unlink(tmp_path) + except OSError: + pass + + def census(disasm_dir, limit=None, jobs=1, stages=None): + if limit is not None: + _check_positive_int("limit", limit) + _check_positive_int("jobs", jobs) if stages is None: stages = hic.stage_index(disasm_dir) names = sorted(n[:-2] for n in os.listdir(disasm_dir) if n.endswith(".s")) - if limit: + if limit is not None: names = names[:limit] work = [(disasm_dir, name, stages.get(name)) for name in names] if jobs > 1: @@ -594,20 +712,42 @@ def main(argv=None): if not os.path.isdir(args.disasm): print(f"ERROR: {args.disasm} is not a folder", file=sys.stderr) return 2 + if args.json: + if os.path.isdir(args.json): + print(f"ERROR: --json is a folder: {args.json}", file=sys.stderr) + return 2 + index_path = os.path.join(os.path.dirname(os.path.abspath(args.disasm)), "index.json") + if same_report_path(args.json, index_path): + print(f"ERROR: --json would overwrite the carve index: {args.json}", file=sys.stderr) + return 2 + if _path_inside(args.json, args.disasm): + print(f"ERROR: --json must not write inside the disasm folder it reads: {args.json}", file=sys.stderr) + return 2 try: stages = hic.stage_index(args.disasm) except (OSError, ValueError, KeyError, TypeError) as e: print(f"ERROR: cannot read the carve index next to {args.disasm}: {e}", file=sys.stderr) return 2 - out = census(args.disasm, args.limit, args.jobs, stages) - print_report(out) if args.json: try: - os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1, sort_keys=True) - f.write("\n") + listing_names = [n[:-2] for n in os.listdir(args.disasm) if n.endswith(".s")] except OSError as e: + print(f"ERROR: cannot read {args.disasm}: {e}", file=sys.stderr) + return 2 + hit = _json_input_collision(args.json, args.disasm, stages, listing_names) + if hit is not None: + print(f"ERROR: --json would overwrite an input the census reads: {hit}", file=sys.stderr) + return 2 + try: + out = census(args.disasm, args.limit, args.jobs, stages) + except OSError as e: + print(f"ERROR: cannot read {args.disasm}: {e}", file=sys.stderr) + return 2 + print_report(out) + if args.json: + try: + _write_json_atomic(args.json, out) + except (OSError, ValueError) as e: print(f"ERROR: cannot write {args.json}: {e}", file=sys.stderr) return 2 bad = [f"{c}: {out['total']['classes'][c]} instructions" for c in args.expect_none if out["total"]["classes"][c]] From 0294aed3ddc263d8698f46c9c9c2c225d5ab07a6 Mon Sep 17 00:00:00 2001 From: xel1uz <16402913+xel1uz@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:06:02 +0100 Subject: [PATCH 12/42] buffer_format_fuzz: validate --budget --budget is a count of random elements per format, and a negative one was accepted with exit 0 and no message. `for _ in range(budget)` simply does not run, so -1, -100 and -1000000 produced exactly the run of 0 -- 1026 instead of 1106 elements for 8_8_8_8_UNORM -- and every format still reported "ok". --self-test was worse: it builds its own patterns with a hardcoded budget of 2 and never reads the option, so `--self-test --budget -100` and `--budget 1000000` both printed the same "self-test: ok" in the same 1.4 s. Before: $ python -I tools/buffer_format_fuzz.py --self-test --budget -1 self-test: ok # exit 0 $ python -I tools/buffer_format_fuzz.py --oracle hw --budget -3 hardware oracle unavailable: ... # exit 77, no GPU needed to know After, one check next to the other argument guards and before both the self-test and the oracle, so the value is validated even where it is not used: $ python -I tools/buffer_format_fuzz.py --self-test --budget -1 buffer_format_fuzz.py: error: --budget cannot be negative # exit 2 $ python -I tools/buffer_format_fuzz.py --self-test --budget 0 self-test: ok # 0 stays legal: sweeps only tests/test_buffer_format_fuzz.py (CPU only, hw_oracle stubbed) covers the negative value on both paths, that it is refused before the oracle is opened, that 0 stays legal and that -1 is otherwise indistinguishable from 0. 3 of its 7 tests fail without this change, 7 pass with it. --- tests/test_buffer_format_fuzz.py | 115 +++++++++++++++++++++++++++++++ tools/buffer_format_fuzz.py | 7 +- 2 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 tests/test_buffer_format_fuzz.py diff --git a/tests/test_buffer_format_fuzz.py b/tests/test_buffer_format_fuzz.py new file mode 100644 index 0000000000..37d8515cde --- /dev/null +++ b/tests/test_buffer_format_fuzz.py @@ -0,0 +1,115 @@ +"""CPU-only tests for tools/buffer_format_fuzz.py's --budget. + + python -I tests/test_buffer_format_fuzz.py + +A negative --budget used to be accepted (exit 0) and then silently skipped every random element: `for _ in +range(budget)` just does not run, so -1 and -1000000 produce exactly the run of 0 and the tool still reports "ok". +--self-test was worse: it builds its own patterns and never reads --budget at all, so 0, -100 and 1000000 all +printed the same "self-test: ok" with exit 0. A negative value is a usage error (2), raised before the self-test +runs and before the oracle is opened; 0 stays legal (the sweeps remain, no random extras are added). + +No GPU and no game file is used: the hardware path stubs hw_oracle. +""" +import contextlib +import io +import os +import random +import subprocess +import sys +import types +import unittest +from unittest.mock import patch + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = os.path.join(REPO, "tools") +TOOL = os.path.join(TOOLS, "buffer_format_fuzz.py") +sys.path.insert(0, TOOLS) + +import buffer_format_fuzz as bff # noqa: E402 + +MESSAGE = "--budget cannot be negative" + + +def run(*args): + return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, check=False) + + +def make_hw_oracle_pkg(opened): + """A hw_oracle that answers like a missing GPU, remembering whether it was asked at all.""" + pkg = types.ModuleType("hw_oracle") + runner_mod = types.ModuleType("hw_oracle.runner") + asm_mod = types.ModuleType("hw_oracle.asm") + + class Unavailable(Exception): + pass + + def open_oracle(arch=None): + opened.append(arch) + raise Unavailable("no GPU here") + + runner_mod.Unavailable = Unavailable + runner_mod.open_oracle = open_oracle + asm_mod.family = lambda arch: "gfx11" + pkg.runner = runner_mod + pkg.asm = asm_mod + return {"hw_oracle": pkg, "hw_oracle.runner": runner_mod, "hw_oracle.asm": asm_mod} + + +def call_main(argv): + """main() with argv, hw_oracle stubbed: -> (SystemExit code, stderr, stdout).""" + mods = make_hw_oracle_pkg([]) + out, err = io.StringIO(), io.StringIO() + with patch.dict(sys.modules, mods): + with patch.object(sys, "argv", ["buffer_format_fuzz.py", *argv]): + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + with unittest.TestCase().assertRaises(SystemExit) as caught: + bff.main() + return caught.exception.code, err.getvalue(), out.getvalue() + + +class BudgetUsageErrorTests(unittest.TestCase): + def test_negative_budget_fails_the_self_test_with_2(self): + proc = run("--self-test", "--budget", "-1") + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn(MESSAGE, proc.stderr) + self.assertNotIn("traceback", proc.stderr.lower()) + self.assertNotIn("self-test: ok", proc.stdout) + + def test_absurdly_negative_budget_fails_too(self): + proc = run("--self-test", "--budget", "-1000000") + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn(MESSAGE, proc.stderr) + + def test_negative_budget_is_refused_before_the_oracle_is_opened(self): + code, err, out = call_main(["--oracle", "hw", "--budget", "-3"]) + self.assertEqual(code, 2, out + err) + self.assertIn(MESSAGE, err) + self.assertNotIn("hardware oracle unavailable", out) # a usage error, not "no GPU" + + def test_zero_budget_stays_legal(self): + proc = run("--self-test", "--budget", "0") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertIn("self-test: ok", proc.stdout) + + +class BudgetValueTests(unittest.TestCase): + def test_zero_keeps_the_sweeps_and_adds_no_random_elements(self): + rng = random.Random(1) + sweeps = len(bff.load_patterns("8_8_8_8_UNORM", rng, 0)) + self.assertGreater(sweeps, 0) + self.assertEqual(len(bff.load_patterns("8_8_8_8_UNORM", random.Random(1), 0)), sweeps) + + def test_a_negative_budget_is_indistinguishable_from_zero(self): + """Why -1 must be a usage error rather than "just no random elements".""" + rng = random.Random(1) + zero = len(bff.load_patterns("8_8_8_8_UNORM", rng, 0)) + self.assertEqual(len(bff.load_patterns("8_8_8_8_UNORM", random.Random(1), -1)), zero) + + def test_a_budget_adds_two_elements_per_unit(self): + rng = random.Random(1) + zero = len(bff.load_patterns("8_8_8_8_UNORM", rng, 0)) + self.assertEqual(len(bff.load_patterns("8_8_8_8_UNORM", random.Random(1), 3)) - zero, 6) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/buffer_format_fuzz.py b/tools/buffer_format_fuzz.py index 2bee995d24..12af7ffafb 100644 --- a/tools/buffer_format_fuzz.py +++ b/tools/buffer_format_fuzz.py @@ -597,11 +597,16 @@ def main(): ap.add_argument("--formats", default="", help="GFX10 codes or names, comma separated (default: every GFX10 code " "the GPU family has)") ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--budget", type=int, default=40, help="random elements per format on top of the sweeps") + ap.add_argument("--budget", type=int, default=40, + help="random elements per format on top of the sweeps (0: none; --self-test uses its own patterns)") ap.add_argument("--hw-arch", default=None) ap.add_argument("--negative-control", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args() + # A negative --budget is a usage error, not "no random elements": `range(-1)` runs zero times, so -1 used to be + # silently the run of 0, and --self-test never reads the value at all, so 0 and -1000000 both printed "ok". + if a.budget < 0: + ap.error("--budget cannot be negative") if a.self_test: return self_test() if a.oracle != "hw": From 1ded3b4d8e2939d7cf2ca7ce535917afb440ff69 Mon Sep 17 00:00:00 2001 From: xel1uz <16402913+xel1uz@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:06:06 +0100 Subject: [PATCH 13/42] f16misc_diff: reject a zero or negative --max-ops and --programs A zero --programs ran the sweep and nothing else with exit 0, and a zero --max-ops reached random.randint(1, 0)'s ValueError traceback. Both are now usage errors: --max-ops and --programs must be at least 1, checked right after parsing and before any work, and argparse exits 2 with the message. main() takes argv so the tests can drive it. --- tests/test_f16misc_diff.py | 50 +++++++++++++++++++++++++++++++++++++- tools/f16misc_diff.py | 19 ++++++++++----- 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/tests/test_f16misc_diff.py b/tests/test_f16misc_diff.py index c3c9d5c864..91d3631ba8 100644 --- a/tests/test_f16misc_diff.py +++ b/tests/test_f16misc_diff.py @@ -22,7 +22,7 @@ import sys import unittest from collections import Counter -from contextlib import redirect_stdout +from contextlib import redirect_stderr, redirect_stdout ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tools")) @@ -42,6 +42,22 @@ def base_op(line): return re.sub(r"_e(32|64)$", "", line.split()[0]) +def run_main(*argv): + """(return code, stdout, stderr) of main() with these arguments.""" + out, err = io.StringIO(), io.StringIO() + real = sys.argv + try: + sys.argv = ["f16misc_diff.py"] + [str(a) for a in argv] + with redirect_stdout(out), redirect_stderr(err): + try: + rc = f.main() + except SystemExit as e: + rc = e.code + finally: + sys.argv = real + return rc, out.getvalue(), err.getvalue() + + def measured(rows): """Run the hardware-oracle rows (text, v1, v2, v3, word in v4) of the family through the reference. Returns (Counter of ok / unjudged reasons, the mismatching rows).""" @@ -350,5 +366,37 @@ def test_a_wrong_translation_is_caught(self): f.translate_listing = real +class CommandLine(unittest.TestCase): + """A zero or negative --programs / --max-ops is a usage error (exit 2), checked before any work.""" + + def assert_rejected(self, argv, message): + rc, out, err = run_main(*argv) + self.assertEqual(rc, 2, (argv, out, err)) + self.assertIn(message, err) + self.assertEqual(out, "") # nothing ran: a zero --programs used to print sweep stats only + self.assertTrue(err.startswith("usage: "), err) + + def test_max_ops_zero_is_rejected(self): + self.assert_rejected(["--programs", 1, "--no-sweep", "--max-ops", 0], "--max-ops must be at least 1") + + def test_max_ops_negative_is_rejected(self): + self.assert_rejected(["--programs", 1, "--no-sweep", "--max-ops", -3], "--max-ops must be at least 1") + + def test_programs_zero_is_rejected(self): + self.assert_rejected(["--programs", 0, "--no-sweep"], "--programs must be at least 1") + + def test_programs_negative_is_rejected(self): + self.assert_rejected(["--programs", -1, "--no-sweep"], "--programs must be at least 1") + + def test_validation_comes_before_list_ops(self): + self.assert_rejected(["--list-ops", "--programs", 0], "--programs must be at least 1") + + def test_the_smallest_valid_run_passes(self): + rc, out, err = run_main("--programs", 1, "--no-sweep", "--max-ops", 1, "--ops", "v_ldexp_f16") + self.assertEqual(rc, 0, (out, err)) + self.assertIn("f16 misc family: 1/1 judged programs match", out) + self.assertEqual(err, "") + + if __name__ == "__main__": unittest.main() diff --git a/tools/f16misc_diff.py b/tools/f16misc_diff.py index 942b9587f1..723be00c47 100644 --- a/tools/f16misc_diff.py +++ b/tools/f16misc_diff.py @@ -67,11 +67,12 @@ exponents in turn). Exit code 0 when every judged program matches, 1 on a mismatch (the first one is printed with its listing) or a -translator skip (every generated form is one the translator takes), 2 on a harness error. +translator skip (every generated form is one the translator takes), 2 on a usage error or a harness error. +--programs and --max-ops must be at least 1 (checked before any work). Usage: python -I tools/f16misc_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_ldexp_f16,v_fma_mix_f32] - python -I tools/f16misc_diff.py --exhaustive-f16 --programs 0 --no-sweep + python -I tools/f16misc_diff.py --exhaustive-f16 --programs 1 --no-sweep python -I tools/f16misc_diff.py --list-ops python -I tools/f16misc_diff.py --self-test """ @@ -1189,7 +1190,7 @@ def report(good, what): return ok -def main(): +def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep") ap.add_argument("--seed", type=int, default=1) @@ -1199,7 +1200,14 @@ def main(): ap.add_argument("--exhaustive-f16", action="store_true", help="also run every f16 input through frexp/ldexp") ap.add_argument("--list-ops", action="store_true") ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() + if argv is None: + argv = sys.argv[1:] + args = ap.parse_args(argv) + # Before any work: a zero --programs silently did nothing and a zero --max-ops reached randint(1, 0)'s traceback. + if args.max_ops < 1: + ap.error("--max-ops must be at least 1") + if args.programs < 1: + ap.error("--programs must be at least 1") if args.list_ops: for op in FAMILY: print(f"{op:22s} {OP_FORMS[op]}") @@ -1218,8 +1226,7 @@ def main(): stages += [("sweep", lambda: run_sweep(args.seed, ops)), ("edge grid", lambda: run_grid(ops))] if args.exhaustive_f16: stages.append(("exhaustive f16", lambda: run_exhaustive(ops))) - if args.programs > 0: - stages.append(("random", lambda: run_suite(args.programs, args.seed, args.max_ops, ops))) + stages.append(("random", lambda: run_suite(args.programs, args.seed, args.max_ops, ops))) total = {"pass": 0, "mismatch": 0, "skip": 0, "unjudged": Counter(), "ops": Counter(), "events": {}} first = None try: From 362b854007f09b5f0c61ea9c4829cd9f7d3b26ce Mon Sep 17 00:00:00 2001 From: xel1uz <16402913+xel1uz@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:56:53 +0100 Subject: [PATCH 14/42] feature_scan: write --out atomically and keep the old report on failure Write JSON to a same-directory temporary file and replace the report only after serialization succeeds. On write failure, keep the existing report and remove the temporary file; preserve the current error message and exit code. Evidence (run from /home/hampa/work/leonida-feature-scan): Tests: - Original: git checkout upstream/main -- tools/feature_scan.py && /home/hampa/work/.venv/bin/python -m pytest tests/test_feature_scan.py -q -> rc 1; 1 failed, 15 passed. The existing report was empty instead of the 23-byte sentinel. - Fixed: git checkout HEAD -- tools/feature_scan.py && /home/hampa/work/.venv/bin/python -m pytest tests/test_feature_scan.py -q -> rc 0; 16 passed. File-size-limit reproduction (synthetic shaders only): - Setup: mkdir -p /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/shaders/dxbc /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/out; python3 -c 'import json,sys; json.dump([{"stage":"synthetic_stage_"+str(i)+"_"+("x"*80)} for i in range(40)], open(sys.argv[1],"w"))' /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/shaders/dxbc/index.json; printf '{"previous": "sentinel report"}\\n' > /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/out/report.json - Before: bash -c 'ulimit -f 1; python3 -I -B tools/feature_scan.py "$1" --out "$2" >/dev/null' _ /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/shaders /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/out/report.json -> rc 2; report 32 bytes before, 1024 bytes after (old contents replaced by partial JSON). - After: bash -c 'trap "" XFSZ; ulimit -f 1; python3 -I -B tools/feature_scan.py "$1" --out "$2" >/dev/null' _ /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/shaders /home/hampa/.hermes/profiles/mikuling/cache/scratch/feature-scan-ulimit1.hlUt9B/out/report.json -> rc 2; report 32 bytes before and after, with no temp file remaining. --- tests/test_feature_scan.py | 68 ++++++++++++++++++++++++++++++++++++++ tools/feature_scan.py | 18 ++++++++-- 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py index 06514341fb..133099bd9a 100644 --- a/tests/test_feature_scan.py +++ b/tests/test_feature_scan.py @@ -13,6 +13,7 @@ import subprocess import sys import tempfile +import unittest from unittest import mock TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools") @@ -562,6 +563,73 @@ def run_tests(tests, report=print): return raised +class FeatureScanAtomicOutputTests(unittest.TestCase): + """Subprocess tests for --out failure handling and successful JSON output.""" + + @staticmethod + def make_shaders(root): + shaders = os.path.join(root, "shaders") + dxbc = os.path.join(shaders, "dxbc") + os.makedirs(dxbc) + with open(os.path.join(dxbc, "index.json"), "w", encoding="utf-8") as stream: + json.dump([], stream) + return shaders + + @staticmethod + def fail_file_writes(): + import resource + import signal + + signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0)) + + def run_scan(self, shaders, report, *, fail_writes=False): + return subprocess.run( + [sys.executable, "-I", "-B", os.path.join(TOOLS, "feature_scan.py"), shaders, "--out", report], + cwd=os.path.dirname(TOOLS), capture_output=True, text=True, + preexec_fn=self.fail_file_writes if fail_writes else None, + ) + + def test_failed_write_keeps_existing_report(self): + with tempfile.TemporaryDirectory() as root: + shaders = self.make_shaders(root) + report = os.path.join(root, "report.json") + original = b'{"previous": "report"}\n' + with open(report, "wb") as stream: + stream.write(original) + + result = self.run_scan(shaders, report, fail_writes=True) + + self.assertEqual(result.returncode, 2, result.stderr) + with open(report, "rb") as stream: + self.assertEqual(stream.read(), original) + + def test_failed_write_leaves_no_temporary_file(self): + with tempfile.TemporaryDirectory() as root: + shaders = self.make_shaders(root) + report = os.path.join(root, "report.json") + with open(report, "w", encoding="utf-8") as stream: + stream.write('{"previous": true}\n') + + result = self.run_scan(shaders, report, fail_writes=True) + + self.assertEqual(result.returncode, 2, result.stderr) + self.assertEqual(set(os.listdir(root)), {"shaders", "report.json"}) + + def test_success_writes_valid_json(self): + with tempfile.TemporaryDirectory() as root: + shaders = self.make_shaders(root) + report = os.path.join(root, "report.json") + + result = self.run_scan(shaders, report) + + self.assertEqual(result.returncode, 0, result.stderr) + with open(report, encoding="utf-8") as stream: + parsed = json.load(stream) + self.assertEqual(parsed["shaders"], 0) + self.assertEqual(set(os.listdir(root)), {"shaders", "report.json"}) + + if __name__ == "__main__": # Every test_* function in the file, in file order, so a new test can't be left out of the script run. raised = run_tests([fn for name, fn in list(globals().items()) if name.startswith("test_") and callable(fn)]) diff --git a/tools/feature_scan.py b/tools/feature_scan.py index 8045c9a9e6..5bdb81ed30 100644 --- a/tools/feature_scan.py +++ b/tools/feature_scan.py @@ -31,6 +31,7 @@ import re import struct import sys +import tempfile from collections import Counter, defaultdict sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -639,8 +640,21 @@ def main() -> int: try: if folder: os.makedirs(folder, exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump(result, f, indent=1) + fd, temporary = tempfile.mkstemp(dir=folder or ".") + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f: + json.dump(result, f, indent=1) + os.replace(temporary, a.out) + except BaseException: + try: + os.close(fd) + except OSError: + pass + try: + os.unlink(temporary) + except OSError: + pass + raise except OSError as e: print(f"ERROR: cannot write {a.out}: {e.strerror or e}", file=sys.stderr) return 2 From f85de7d9535ef41a6b071d8f9c7f11cbf9180517 Mon Sep 17 00:00:00 2001 From: xel1uz <16402913+xel1uz@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:10:38 +0100 Subject: [PATCH 15/42] gen_gdk_runtime_classes: write --out atomically Write the generated JSON to a temporary file in the destination directory, then atomically replace the output. Remove the temporary file on write errors and preserve output permissions. Before: with 128 synthetic classes and an existing 14-byte output, `bash -c 'trap "" XFSZ; ulimit -f 1; python3 -I tools/gen_gdk_runtime_classes.py /home/hampa/.hermes/profiles/mikuling/cache/scratch/gdk-atomic-repro/docs --out /home/hampa/.hermes/profiles/mikuling/cache/scratch/gdk-atomic-repro/out.json'` returned 1 (Errno 27, File too large); output grew to 1024 bytes (partial JSON). After: the same command returned 1, left the 14-byte sentinel unchanged, and left no temporary file. Tests against upstream/main: 1 failed, 2 passed; against the fix: 3 passed. --- tests/test_gen_gdk_runtime_classes.py | 85 +++++++++++++++++++++++++++ tools/gen_gdk_runtime_classes.py | 28 ++++++++- 2 files changed, 110 insertions(+), 3 deletions(-) create mode 100644 tests/test_gen_gdk_runtime_classes.py diff --git a/tests/test_gen_gdk_runtime_classes.py b/tests/test_gen_gdk_runtime_classes.py new file mode 100644 index 0000000000..a54d30df7b --- /dev/null +++ b/tests/test_gen_gdk_runtime_classes.py @@ -0,0 +1,85 @@ +"""Tests for atomic output from gen_gdk_runtime_classes.""" +import json +import os +from pathlib import Path +import resource +import signal +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "tools" / "gen_gdk_runtime_classes.py" + + +def make_docs(root: Path) -> Path: + """Create the smallest synthetic docs tree accepted by the generator.""" + docs = root / "docs" + (docs / "COM").mkdir(parents=True) + return docs + + +def command(docs: Path, output: Path) -> list[str]: + return [sys.executable, "-I", str(SCRIPT), str(docs), "--out", str(output)] + + +def fail_after_bytes(limit: int): + def set_file_limit() -> None: + resource.setrlimit(resource.RLIMIT_FSIZE, (limit, limit)) + signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + + return set_file_limit + + +class GenGdkRuntimeClassesTests(unittest.TestCase): + def test_failed_write_preserves_existing_file(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + docs = make_docs(root) + output = root / "table.json" + original = b"previous table must survive\n" + output.write_bytes(original) + + # Validate that this input reaches the output path and exceeds the limit. + successful = subprocess.run(command(docs, output), capture_output=True, check=False) + self.assertEqual(successful.returncode, 0, successful.stderr.decode(errors="replace")) + self.assertGreater(output.stat().st_size, 64) + output.write_bytes(original) + + failed = subprocess.run(command(docs, output), capture_output=True, check=False, + preexec_fn=fail_after_bytes(64)) + self.assertNotEqual(failed.returncode, 0, failed.stdout.decode(errors="replace")) + self.assertEqual(output.read_bytes(), original) + + def test_failed_write_leaves_no_temporary_file(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + docs = make_docs(root) + output = root / "table.json" + output.write_bytes(b"existing table") + before = set(os.listdir(root)) + + failed = subprocess.run(command(docs, output), capture_output=True, check=False, + preexec_fn=fail_after_bytes(64)) + + self.assertNotEqual(failed.returncode, 0, failed.stdout.decode(errors="replace")) + self.assertEqual(set(os.listdir(root)), before) + + def test_successful_write_produces_valid_json(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + docs = make_docs(root) + output = root / "table.json" + + result = subprocess.run(command(docs, output), capture_output=True, check=False) + + self.assertEqual(result.returncode, 0, result.stderr.decode(errors="replace")) + with output.open(encoding="utf-8") as stream: + table = json.load(stream) + self.assertEqual(table["classes"], {}) + self.assertEqual(table["interfaces"], {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/gen_gdk_runtime_classes.py b/tools/gen_gdk_runtime_classes.py index 714f5a167f..11107bd095 100644 --- a/tools/gen_gdk_runtime_classes.py +++ b/tools/gen_gdk_runtime_classes.py @@ -22,8 +22,10 @@ import json import os import re +import stat import subprocess import sys +import tempfile ID = re.compile(r"(?:Interface|Class) Id: `([0-9a-fA-F-]{36})`") INHERITS = re.compile(r"Inherits: (?:\[(I\w+)\]|IUnknown\b)") @@ -136,9 +138,29 @@ def main(argv: list[str] | None = None) -> int: parent = os.path.dirname(os.path.abspath(a.out)) if parent: os.makedirs(parent, exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump(table, f, indent=1, sort_keys=True) - f.write("\n") + try: + mode = stat.S_IMODE(os.stat(a.out).st_mode) + except FileNotFoundError: + current_umask = os.umask(0) + os.umask(current_umask) + mode = 0o666 & ~current_umask + fd, tmp = tempfile.mkstemp(dir=parent) + try: + os.chmod(tmp, mode) + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f: + json.dump(table, f, indent=1, sort_keys=True) + f.write("\n") + os.replace(tmp, a.out) + except BaseException: + try: + os.close(fd) + except OSError: + pass + try: + os.unlink(tmp) + except OSError: + pass + raise print(f"{len(table['classes'])} classes, {len(table['interfaces'])} interfaces -> {a.out}") return 0 From 4c2666a7ceb5b81c112a9e2e2686a38cd6aec7eb Mon Sep 17 00:00:00 2001 From: Ramon Victor Cardoso Date: Mon, 23 Nov 2026 19:48:40 -0300 Subject: [PATCH 16/42] docs: D3D-56 descriptor lookup numbers on RTX 3070 (Ampere, ReBAR off) --- docs/README.md | 1 + docs/descriptor_lookup_ampere.md | 68 ++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 docs/descriptor_lookup_ampere.md diff --git a/docs/README.md b/docs/README.md index 6856349124..289afa5b9e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -74,6 +74,7 @@ method, scope and caveats. No game data is included. | [modding.md](modding.md) | The mod format: a `mods//mod.json` next to `gta6rt.exe` or under `--mods DIR`, swapping a named (or `joaat`) archetype for another; the `tools/leonida_mods.py` manager (`Mods.bat` on Windows, `Mods.sh` on Linux and macOS); load order, the start-up log, and the fact that a swap waits for the executable's archetype lookup address (RT-5). | | [descriptor_lookup_apple.md](descriptor_lookup_apple.md) | M3 Max GPU timings for texture and sampler descriptor lookups at 1k, 10k and 100k live entries. | | [descriptor_lookup_ada.md](descriptor_lookup_ada.md) | RTX 4070 SUPER (Ada, Windows) timings for the same lookups in VRAM, host-visible and ReBAR memory. | +| [descriptor_lookup_ampere.md](descriptor_lookup_ampere.md) | RTX 3070 (Ampere, Windows, PCIe 3.0 x16, ReBAR off) timings for the same lookups in VRAM, host-visible and 214 MiB BAR1 memory. | | [descriptor_lookup_intel.md](descriptor_lookup_intel.md) | Intel UHD Graphics 770 (Xe-LP, Windows, driver 101.6129) timings for the same lookups at 1k–100k live entries; both memory placements within 0.6% of each other. | | [d3d12_xs_surface.md](d3d12_xs_surface.md) | The 116-slot `d3d12_xs.dll` export surface; 83/83 standard GUIDs match the PC SDK. | | [xdxr.md](xdxr.md) | `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) from `XboxBvhBuilder.dll`'s reads; stream records' offsets and defaults; offline statistics not in the package. | diff --git a/docs/descriptor_lookup_ampere.md b/docs/descriptor_lookup_ampere.md new file mode 100644 index 0000000000..440d7ec068 --- /dev/null +++ b/docs/descriptor_lookup_ampere.md @@ -0,0 +1,68 @@ +# Descriptor lookup cost on NVIDIA RTX 3070 (Ampere) + +Divergent lookups in host-visible system RAM showed a steep cliff once the table reached 100,000 entries on this PCIe 3.0 x16 Ampere card with Resizable BAR off. On the GPU-only memory type, one million logical lane lookups took 270.3 µs at 1,000 live descriptors, 773.3 µs at 10,000 and 2,502.6 µs at 100,000 for divergent misses, and 73.0, 94.3 and 231.9 µs for divergent texture hits. The 214 MiB BAR1 memory type (`DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT`, exposed even with Resizable BAR disabled) stayed within 0.5% of GPU-only in every cell across all three sizes. By contrast, host-visible memory outside VRAM stayed within 10% of GPU-only at 1,000 entries and within 16% at 10,000, but at 100,000 entries it was 5.0× slower for uniform texture hits, 14.2× slower for divergent texture hits, 21.9× slower for divergent T#+S# pairs and 22.6× slower for divergent misses. These are synthetic compute results from one GeForce RTX 3070 on an idle Windows 11 desktop with NVIDIA driver 621.24. The benchmark ran unchanged at `5d74c27` (with the current default `--warmup-ms 300`). + +## Measurements + +Each cell is gross GPU time in **µs per million logical lane lookups**, including key reads and result accumulation. The benchmark also prints a figure with a key-read baseline subtracted (summarised below). The table uses its gross column so it compares directly with the [RTX 4070 SUPER (Ada) run](descriptor_lookup_ada.md). + +| Live descriptors | Memory type | Uniform T# hit | Uniform S# hit | Divergent T# hit | Divergent T#+S# pair | Divergent miss | +|---:|:---|---:|---:|---:|---:|---:| +| 1,000 | GPU-only | 15.0 | 15.1 | 73.0 | 68.2 | 270.3 | +| 1,000 | Host-visible | 16.5 | 16.4 | 71.3 | 69.9 | 267.6 | +| 1,000 | BAR1 (`host_device_local`) | 15.0 | 15.1 | 73.0 | 68.2 | 270.3 | +| 10,000 | GPU-only | 15.5 | 15.0 | 94.3 | 115.9 | 773.3 | +| 10,000 | Host-visible | 16.8 | 17.0 | 104.4 | 134.4 | 880.7* | +| 10,000 | BAR1 (`host_device_local`) | 15.5 | 15.0 | 94.4 | 115.4 | 771.7 | +| 100,000 | GPU-only | 21.7 | 15.7 | 231.9 | 216.6 | 2,502.6 | +| 100,000 | Host-visible | 108.0 | 18.4 | 3,290.5 | 4,734.5 | 56,519.6* | +| 100,000 | BAR1 (`host_device_local`) | 21.7 | 15.8 | 231.8 | 216.7 | 2,499.3 | + +\* Shortened by the benchmark's Windows timeout guard in all 12 rounds (see Method). + +Net timings (after subtracting the matching key-read baseline) at 100,000 entries were: GPU-only `14.6`, `8.6`, `207.6`, `204.5`, `2,478.3`; BAR1 `14.6`, `8.6`, `207.5`, `204.6`, `2,475.1`; Host-visible `101.0`, `11.5`, `3,265.5`, `4,722.4`, `56,495.1*` µs per million. + +At 100,000 entries on type 1 (GPU-only), a divergent T# dispatch took 3.89 ms, a T#+S# dispatch took 7.27 ms and a divergent miss dispatch took 41.99 ms. Each paired iteration resolves two descriptors. + +GPU-only is type 1, `DEVICE_LOCAL`, on heap 0 (8,018 MiB). Host-visible is type 3, `HOST_VISIBLE | HOST_COHERENT` without `HOST_CACHED`, on heap 1 (16,345 MiB, not device-local). BAR1 (`host_device_local`, selected by `--memory rebar`) is type 5, `DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT`, on heap 2 (214 MiB). Resizable BAR was **off**: `nvidia-smi` reported a 256 MiB BAR1 aperture (227 MiB used, 29 MiB free at idle), and every allocation on type 5 still succeeded up to the 20.0 MiB table. On this card, keeping the descriptor table out of non-device-local host-visible RAM matters far more at 100,000 entries than on the [Ada PCIe 4.0 + ReBAR card](descriptor_lookup_ada.md) (14.2×–22.6× penalty on divergent traffic here vs 1.45×–2.5× there), while the 214 MiB BAR1 heap remained within 0.5% of GPU-only VRAM in every cell whenever the table fit inside it. + +At 100,000 entries on GPU-only and BAR1, the 12 round medians split deterministically by which table size ran first in the process: the four rounds that started with 1,000 entries (rounds 1, 5, 8 and 12) measured 167.4–167.9 µs per million for divergent T# hits and 1,791.5–1,791.9 for divergent misses; the four that started with 10,000 entries (rounds 3, 6, 7 and 10) measured 231.8–232.1 and 2,498.4–2,505.4; and the four that started with 100,000 entries (rounds 2, 4, 9 and 11) measured 232.2–232.9 and 2,581.9–2,591.8. The table medians follow the eight rounds that did not start at 1,000 entries. The cause was not measured. + +The tables contain 90% T# texture keys and 10% S# sampler keys. Their allocations were 163,844, 2,621,444 and 20,971,524 bytes (0.156, 2.50 and 20.0 MiB). The capacities were 4,096, 65,536 and 524,288 slots, at 24.4%, 15.3% and 19.1% load. At 100,000 entries the ordinary uniform hit runs covered all 90,000 textures or all 10,000 samplers. Each workgroup shared a key for each iteration. The separate hot-key control (`uniform_hot_tsharp`) reused one texture and measured 12.8–13.1 µs per million gross (5.7–6.8 µs net) across all three memory types and sizes. Divergent misses visited 1,024, 16,384 and 131,072 distinct absent keys across the three sizes. Cache residency and memory traffic were unmeasured. + +## Method and replay + +Each dispatch used 4,096 groups of 64 lanes and 64 iterations. The RTX 3070 reported 32-lane subgroups (`minSubgroupSize = maxSubgroupSize = 32`). The denominator was 16,777,216 logical lookups per single-key dispatch and 33,554,432 per paired dispatch, counting the texture and sampler separately. Vulkan timestamps bracketed one dispatch. The compute queue advertised 64 valid bits and a 1 ns tick period. + +Each cell is the median of 12 process medians, each from 25 timed dispatches after five warmups plus the default `--warmup-ms 300` clock-warmup window (TEST-277). The 11 scenarios ran in the benchmark's fixed order. There were 36 processes: three memory types in each of 12 rounds. Across them there were 29,124 timed dispatches. Every process exited 0, wrote nothing to stderr and reported `timing_status` `ok` on all 1,188 rows. The run used the default Windows Vulkan loader with validation layers off and `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` set to keep overlay layers out of the run; desktop GPU utilization at idle was 2% (993 MiB VRAM used, P5). + +As in the [Ada run](descriptor_lookup_ada.md), this run kept the default `--max-dispatch-ms 120` guard to stay clear of the Windows 2 s GPU timeout (TDR). Only host-visible cells were shortened, all 12 of 12 rounds: at 10,000 entries, `divergent_miss` ran with 13–26 iterations (median dispatch 4.38 ms, range 1.60–6.37 ms); at 100,000 entries, `divergent_miss` ran with 19 iterations in all 12 rounds (median dispatch 281.51 ms, range 276.11–285.21 ms) and `latency_divergent` (outside the summary table; gross median 8,135.0 µs per million) ran with 26 iterations in all 12 rounds (median dispatch 55.45 ms, range 47.57–56.15 ms). + +From a Leonida checkout on Windows, with Visual Studio C++ tools, CMake + Ninja, Windows SDK 10.0.26100+ and Vulkan headers (`VULKAN_SDK` or `-DLEONIDA_VULKAN_HEADERS_FETCH=ON`): + +```powershell +runtime\build\vk_descriptor_bench.exe --list-devices +runtime\build\vk_descriptor_bench.exe --self-test +$env:DISABLE_RTSS_LAYER = "1" +$env:DISABLE_VULKAN_OBS_CAPTURE = "1" +foreach ($memory in 'device', 'host', 'rebar') { + runtime\build\vk_descriptor_bench.exe --device 0 --memory $memory --sizes 1000,10000,100000 ` + --groups 4096 --iters 64 --warmup 5 --reps 25 --warmup-ms 300 --csv +} +``` + +Device 0 was the RTX 3070, the only Vulkan device. For the full 12-round series, let A, B and C denote 1k, 10k and 100k. The rounds used the same size orders and starting memory types as the [M3 Max](descriptor_lookup_apple.md) and [Ada](descriptor_lookup_ada.md) runs: the first six size orders were ABC, CBA, BAC, CAB, ACB and BCA, starting with `device`, `host`, `device`, `device`, `host` and `host` respectively; the next six reversed the sequence of rounds and swapped the starting memory type in each, with `rebar` third in every round. + +## System + +| | | +|:---|:---| +| GPU | NVIDIA GeForce RTX 3070 (Ampere), 8,192 MiB (discrete) | +| PCI id | `0x10de:0x2488`, subsystem `0x404e1458` | +| Link | PCIe 3.0 x16 (current and maximum reported by `nvidia-smi`; B450 AORUS M) | +| Resizable BAR | Off (BAR1 aperture 256 MiB, `nvidia-smi -q -d MEMORY`; Vulkan heap 2 reports 214 MiB `DEVICE_LOCAL \| HOST_VISIBLE \| HOST_COHERENT`) | +| Subgroup size | 32 | +| Driver | NVIDIA 621.24 (`nvidia-smi`), Vulkan API 1.4.357 | +| OS | Windows 11 Pro 26H2, build 26300.9974 | +| Vulkan headers | 1.4.363.0 (`-DLEONIDA_VULKAN_HEADERS_FETCH=ON`) | +| Compiler | Visual Studio 18 Professional (MSVC 19.51.36260.0), `RelWithDebInfo` via CMake + Ninja | From b3bca1991b7e4500b0e13e6f0aad1698a18120f0 Mon Sep 17 00:00:00 2001 From: Joseph Weiner Date: Wed, 25 Nov 2026 11:58:13 -0500 Subject: [PATCH 17/42] docs(testing): note V100 cube-store failure --- docs/testing.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/testing.md b/docs/testing.md index ffe729d24f..450b1c3263 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -773,6 +773,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | `vk_sync_validation` fails with `LEONIDA_VK_VALIDATION=1` ("the write-after-write hazard was not reported") | Synchronization validation is off although the tests ask for it: an older layer, or a layer setting such as `VK_KHRONOS_VALIDATION_VALIDATE_SYNC=false` or a `vk_layer_settings.txt` that overrides it. Every other GPU test then reports "0 validation errors" without having been checked | Remove the override or update the Vulkan SDK, then rerun `ctest -R vk_sync_validation` until it passes | | On RADV with Mesa 25.2 (Ubuntu 24.04's default; 25.2.8 measured) or 25.3 (from the source, not run), `cs_w32_salu64` fails with word 2 = `0` (want `0xFFFFFFFF`) and `cs_signed_zero_nan` fails with word 5 = `0` (want `1`). The `cs_signed_zero_nan` failure alone is also measured on RADV 25.0.7 (RX 7800 XT, Debian 13; @mrbean56, #4421) and on ANV 25.2.8 (Intel UHD 630; @theswiss24, #4571); llvmpipe on Mesa 26.0.8 (Ubuntu 26.04) still gives word 5 = `0`, which `check.py` does not judge there (`UNJUDGED_WORDS`) | Two Mesa bugs, not translator bugs (#166). `cs_w32_salu64`: ACO's `combine_add_sub_b2i` reads a temporary without counting the use, so dead-code elimination removes it (`ACO ERROR: ... never defined` with `MESA_SHADER_CACHE_DISABLE=true`); `RADV_DEBUG=llvm` passes. `cs_signed_zero_nan`: NIR's range analysis (`fmul_is_a_number`) calls `0 * x` a number when `x` may be infinite, so the `x != x` check folds to false despite `SignedZeroInfNanPreserve`. The same NIR code is behind llvmpipe's word 5 (#664) and ANV's, since both drivers run NIR; `cs_w32_salu64` is ACO's, so only RADV has it | Expected with these Mesa versions. From the source, the ACO function is gone from Mesa 26.0 and the NIR code was replaced in 26.1 (neither run); RADV from Mesa 26.3.1 passes both on an 8060S (gfx1151) | | Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer | +| The synthetic `cs_imgstore_cube` test reports 63 bad `r32 sint` texels on a Tesla V100-SXM2-16GB (Volta, NVIDIA 580.178.04, Linux; Vulkan 1.4.312; [#1492](https://github.com/ubiquitarianism/leonida/issues/1492)) | The signed 32-bit cube-storage-write failure is known on that reported host, but its cause has not been isolated. It passes on an RTX 5090 with NVIDIA 621.14 on Windows 11 | No workaround is confirmed. Keep the test's expected values; report the GPU, driver and output if you reproduce it on another setup | | `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | | `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old | | `ps_bary` and `ps_uniform_branch` fail by about 0.9 | The GPU runs pixel shaders wave64 without fragment barycentrics (GCN3 and RDNA1 on RADV), or an old AMD Windows driver (22.40) | Current `main` skips them on such devices; on Windows, update the driver | From 2bdc69c3019a508234abf73131db283331de75b4 Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 17:39:37 +0300 Subject: [PATCH 18/42] bvh_slot_check: restore write mode before unlink on replace failure and publish mode (BVH-SLOT-CHECK-STAGE-CLEANUP) Apply published_mode(path) to temporary file before atomic replacement, and restore write permission (0o600) before unlinking in finally block when replace fails, preventing Windows PermissionError [WinError 5] and stranded temporary files. agent: yes AI-assisted: yes --- tests/test_bvh_slot_check.py | 18 ++++++++++++++++++ tools/bvh_slot_check.py | 9 ++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/tests/test_bvh_slot_check.py b/tests/test_bvh_slot_check.py index d712a16393..28f713f1a5 100644 --- a/tests/test_bvh_slot_check.py +++ b/tests/test_bvh_slot_check.py @@ -7,6 +7,7 @@ import sys import tempfile import unittest +from unittest import mock import zlib from collections import Counter from pathlib import Path @@ -204,6 +205,23 @@ def test_empty_entry_keeps_matrix_index(self): with self.assertRaises(ValueError): S.slots(desc, block) + def test_save_evidence_cleanup_restores_write_mode_on_replace_failure(self): + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(path, mode, *args, **kwargs): + chmod_calls.append((str(path), mode)) + return real_chmod(path, mode, *args, **kwargs) + + with tempfile.TemporaryDirectory() as directory: + out_path = Path(directory) / "evidence.json" + with mock.patch("os.replace", side_effect=OSError("replace failed")), \ + mock.patch("os.chmod", side_effect=track_chmod): + with self.assertRaisesRegex(OSError, "replace failed"): + S.save_evidence(out_path, {"test": 123}) + + self.assertTrue(any(mode == 0o600 for _, mode in chmod_calls), chmod_calls) + if __name__ == "__main__": unittest.main() diff --git a/tools/bvh_slot_check.py b/tools/bvh_slot_check.py index 610ddf4be1..0531db2d46 100644 --- a/tools/bvh_slot_check.py +++ b/tools/bvh_slot_check.py @@ -21,6 +21,7 @@ from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from file_mode import published_mode import bvh_geometry_check as C import bvh_index as I import bvh_match as M @@ -229,9 +230,15 @@ def save_evidence(path, record): try: with f: json.dump(record, f) + os.chmod(temporary, published_mode(path)) os.replace(temporary, path) finally: - temporary.unlink(missing_ok=True) + if temporary.exists(): + try: + os.chmod(temporary, 0o600) + except OSError: + pass + temporary.unlink(missing_ok=True) def census(archive, index, manifests, prior=(), save=None): From 065df3d8b2468fb27cd4f388232bff19d8803b7d Mon Sep 17 00:00:00 2001 From: d7ommy Date: Wed, 25 Nov 2026 21:29:28 +0300 Subject: [PATCH 19/42] runtime: guard align_up_saturating against zero alignment and add unit tests (RT-XS-ALLOC-SIZE-GUARDS-AND-TESTS) Guard align_up_saturating against zero alignment (to == 0) in runtime/shims/d3d12_xs_alloc_size.h, avoiding division by zero and underflow. Add standalone CPU-only unit test runtime/test/d3d12_xs_alloc_size_test.cpp covering align_up_saturating, render_target_element_bytes, console_depth_planes, console_render_target_size, console_depth_stencil_size, and console_placement. Register test executable and CTest in runtime/CMakeLists.txt. AI-assisted (Claude Code) --- runtime/CMakeLists.txt | 12 + runtime/shims/d3d12_xs_alloc_size.h | 1 + runtime/test/d3d12_xs_alloc_size_test.cpp | 265 ++++++++++++++++++++++ 3 files changed, 278 insertions(+) create mode 100644 runtime/test/d3d12_xs_alloc_size_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 66af48c7da..e7782960d0 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -323,6 +323,15 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(xg_xs_test PRIVATE /W4 /permissive- /utf-8) target_link_options(xg_xs_test PRIVATE /OPT:NOREF) + # Console allocation sizes for render targets and depth-stencil targets. + add_executable(d3d12_xs_alloc_size_test + test/d3d12_xs_alloc_size_test.cpp + ) + target_include_directories(d3d12_xs_alloc_size_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(d3d12_xs_alloc_size_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_xs_alloc_size_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(d3d12_xs_alloc_size_test PRIVATE /OPT:NOREF) + # acphal shim ABI test: resolves the registered acphal.dll exports through the registry. add_executable(acphal_test test/acphal_test.cpp @@ -1535,6 +1544,9 @@ if(BUILD_TESTING) if(WIN32 AND TARGET xg_xs_test) add_test(NAME xg_xs COMMAND xg_xs_test) endif() + if(WIN32 AND TARGET d3d12_xs_alloc_size_test) + add_test(NAME d3d12_xs_alloc_size COMMAND d3d12_xs_alloc_size_test) + endif() if(WIN32 AND TARGET acphal_test) add_test(NAME acphal COMMAND acphal_test) add_test(NAME acphal_noncached_only COMMAND acphal_test --noncached-only) diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h index 7f1948eccd..ad8677dd58 100644 --- a/runtime/shims/d3d12_xs_alloc_size.h +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -202,6 +202,7 @@ inline bool console_texture_layout(const D3D12_RESOURCE_DESC& desc, UINT64& size // Rounds up to a multiple of `to`, stopping at the last multiple below 2^64 instead of wrapping (as the PC device's // totals do). inline UINT64 align_up_saturating(UINT64 value, UINT64 to) { + if (to == 0) return value; return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; } diff --git a/runtime/test/d3d12_xs_alloc_size_test.cpp b/runtime/test/d3d12_xs_alloc_size_test.cpp new file mode 100644 index 0000000000..31255fbc32 --- /dev/null +++ b/runtime/test/d3d12_xs_alloc_size_test.cpp @@ -0,0 +1,265 @@ +// Tests console allocation sizes and placement for render targets and depth-stencil targets +// (runtime/shims/d3d12_xs_alloc_size.h). +// Synthetic descriptions only; no game data or GPU required. +#include +#include + +#include +#include +#include + +#include "d3d12_xs_alloc_size.h" + +namespace { + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + if (!condition) { + ++g_failures; + std::printf("FAIL %s\n", what); + } +} + +void test_align_up_saturating() { + using rt::d3d12_xs::align_up_saturating; + + check(align_up_saturating(0, 0) == 0, "align_up_saturating(0, 0) == 0"); + check(align_up_saturating(1234, 0) == 1234, "align_up_saturating with to=0 returns value"); + check(align_up_saturating(0, 64) == 0, "align_up_saturating(0, 64) == 0"); + check(align_up_saturating(1, 64) == 64, "align_up_saturating(1, 64) == 64"); + check(align_up_saturating(64, 64) == 64, "align_up_saturating(64, 64) == 64"); + check(align_up_saturating(65, 64) == 128, "align_up_saturating(65, 64) == 128"); + check(align_up_saturating(100, 65536) == 65536, "align_up_saturating(100, 64K) == 64K"); + check(align_up_saturating(65536, 65536) == 65536, "align_up_saturating(64K, 64K) == 64K"); + check(align_up_saturating(65537, 65536) == 131072, "align_up_saturating(64K+1, 64K) == 128K"); + + // Saturation behavior near UINT64_MAX + const UINT64 saturated = align_up_saturating(UINT64_MAX - 10, 64); + check(saturated == (UINT64_MAX / 64 * 64), "align_up_saturating saturates without wrapping"); + check(align_up_saturating(UINT64_MAX, 65536) == (UINT64_MAX / 65536 * 65536), "align_up_saturating UINT64_MAX saturates"); +} + +void test_render_target_element_bytes() { + using rt::d3d12_xs::render_target_element_bytes; + + // 1-byte formats + check(render_target_element_bytes(DXGI_FORMAT_R8_UNORM) == 1, "R8_UNORM is 1 byte"); + check(render_target_element_bytes(DXGI_FORMAT_R8_UINT) == 1, "R8_UINT is 1 byte"); + check(render_target_element_bytes(DXGI_FORMAT_R8_SNORM) == 1, "R8_SNORM is 1 byte"); + check(render_target_element_bytes(DXGI_FORMAT_R8_SINT) == 1, "R8_SINT is 1 byte"); + check(render_target_element_bytes(DXGI_FORMAT_A8_UNORM) == 1, "A8_UNORM is 1 byte"); + + // 2-byte formats + check(render_target_element_bytes(DXGI_FORMAT_R8G8_UNORM) == 2, "R8G8_UNORM is 2 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R16_FLOAT) == 2, "R16_FLOAT is 2 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R16_UNORM) == 2, "R16_UNORM is 2 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_B5G6R5_UNORM) == 2, "B5G6R5_UNORM is 2 bytes"); + + // 4-byte formats + check(render_target_element_bytes(DXGI_FORMAT_R8G8B8A8_UNORM) == 4, "R8G8B8A8_UNORM is 4 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) == 4, "R8G8B8A8_UNORM_SRGB is 4 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_B8G8R8A8_UNORM) == 4, "B8G8R8A8_UNORM is 4 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R10G10B10A2_UNORM) == 4, "R10G10B10A2_UNORM is 4 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R11G11B10_FLOAT) == 4, "R11G11B10_FLOAT is 4 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R16G16_FLOAT) == 4, "R16G16_FLOAT is 4 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R32_FLOAT) == 4, "R32_FLOAT is 4 bytes"); + + // 8-byte formats + check(render_target_element_bytes(DXGI_FORMAT_R16G16B16A16_FLOAT) == 8, "R16G16B16A16_FLOAT is 8 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_R32G32_FLOAT) == 8, "R32G32_FLOAT is 8 bytes"); + + // 16-byte formats + check(render_target_element_bytes(DXGI_FORMAT_R32G32B32A32_FLOAT) == 16, "R32G32B32A32_FLOAT is 16 bytes"); + + // Unsupported / non-render target formats + check(render_target_element_bytes(DXGI_FORMAT_UNKNOWN) == 0, "UNKNOWN format is 0 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_BC1_UNORM) == 0, "BC1_UNORM is 0 bytes"); + check(render_target_element_bytes(DXGI_FORMAT_D32_FLOAT) == 0, "D32_FLOAT is 0 bytes for RT"); +} + +void test_console_depth_planes() { + using rt::d3d12_xs::console_depth_planes; + + auto p = console_depth_planes(DXGI_FORMAT_D32_FLOAT_S8X24_UINT); + check(p.depth == 4 && p.stencil == 1, "D32_FLOAT_S8X24_UINT is 4+1 planes"); + + p = console_depth_planes(DXGI_FORMAT_D24_UNORM_S8_UINT); + check(p.depth == 4 && p.stencil == 1, "D24_UNORM_S8_UINT is 4+1 planes"); + + p = console_depth_planes(static_cast(118)); + check(p.depth == 2 && p.stencil == 1, "DXGI 118 (console D16S8) is 2+1 planes"); + + p = console_depth_planes(DXGI_FORMAT_D32_FLOAT); + check(p.depth == 4 && p.stencil == 0, "D32_FLOAT is 4+0 planes"); + + p = console_depth_planes(DXGI_FORMAT_D16_UNORM); + check(p.depth == 2 && p.stencil == 0, "D16_UNORM is 2+0 planes"); + + p = console_depth_planes(DXGI_FORMAT_R8G8B8A8_UNORM); + check(p.depth == 0 && p.stencil == 0, "R8G8B8A8_UNORM has no depth planes"); +} + +void test_console_render_target_size() { + using rt::d3d12_xs::console_render_target_size; + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Alignment = 0; + desc.Width = 1920; + desc.Height = 1080; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + + // 1920x1080 R8G8B8A8 (4 bytes/texel): + // Tile size is 64 KiB. For 4 bytes/texel, tile is 128x128. + // 1920 / 128 = 15 tiles wide. + // ceil(1080 / 128) = 9 tiles high. + // 15 * 9 = 135 tiles = 135 * 65536 = 8,847,360 bytes. + const UINT64 rt_size = console_render_target_size(desc); + check(rt_size == 135 * 65536, "1920x1080 R8G8B8A8 render target is 135 64K tiles"); + + // Two slices + desc.DepthOrArraySize = 2; + check(console_render_target_size(desc) == 2 * 135 * 65536, "2 slices double the allocation"); + desc.DepthOrArraySize = 1; + + // Multisampling (Count > 1) returns 0 + desc.SampleDesc.Count = 4; + check(console_render_target_size(desc) == 0, "Multisampled target returns 0"); + desc.SampleDesc.Count = 1; + + // Missing ALLOW_RENDER_TARGET flag returns 0 + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + check(console_render_target_size(desc) == 0, "Missing ALLOW_RENDER_TARGET returns 0"); + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + + // Non-2D dimension returns 0 + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + check(console_render_target_size(desc) == 0, "3D texture returns 0"); + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + check(console_render_target_size(desc) == 0, "Buffer returns 0"); + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + + // Unsupported format returns 0 + desc.Format = DXGI_FORMAT_BC1_UNORM; + check(console_render_target_size(desc) == 0, "BC1 format returns 0"); + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + + // Zero dimensions return 0 + desc.Width = 0; + check(console_render_target_size(desc) == 0, "Zero width returns 0"); + desc.Width = 1920; + desc.Height = 0; + check(console_render_target_size(desc) == 0, "Zero height returns 0"); + desc.Height = 1080; + desc.DepthOrArraySize = 0; + check(console_render_target_size(desc) == 0, "Zero depth returns 0"); + desc.DepthOrArraySize = 1; + + // Full mip chain: non-zero and >= single mip size + desc.MipLevels = 0; // full chain + const UINT64 full_chain_size = console_render_target_size(desc); + check(full_chain_size > rt_size, "Full mip chain is larger than single mip"); +} + +void test_console_depth_stencil_size() { + using rt::d3d12_xs::console_depth_stencil_size; + + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Alignment = 0; + desc.Width = 1920; + desc.Height = 1080; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + + const UINT64 ds_size = console_depth_stencil_size(desc); + check(ds_size > 0, "1920x1080 D32S8 depth-stencil target has non-zero size"); + + // Missing ALLOW_DEPTH_STENCIL returns 0 + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + check(console_depth_stencil_size(desc) == 0, "Missing ALLOW_DEPTH_STENCIL returns 0"); + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + + // Count > 1 returns 0 + desc.SampleDesc.Count = 2; + check(console_depth_stencil_size(desc) == 0, "Multisampled depth returns 0"); + desc.SampleDesc.Count = 1; + + // Non-depth format returns 0 + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + check(console_depth_stencil_size(desc) == 0, "Colour format returns 0 for depth size"); +} + +void test_console_placement() { + using rt::d3d12_xs::console_placement; + + // Null descs returns false + D3D12_RESOURCE_ALLOCATION_INFO total{}; + check(!console_placement(nullptr, 1, [](UINT) -> D3D12_RESOURCE_ALLOCATION_INFO { return {0, 0}; }, total, nullptr), + "console_placement rejects null descs"); + + // Non-target list returns false (PC answer stands) + D3D12_RESOURCE_DESC buffer_desc{}; + buffer_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer_desc.Width = 1024; + buffer_desc.Height = 1; + buffer_desc.DepthOrArraySize = 1; + buffer_desc.MipLevels = 1; + buffer_desc.SampleDesc.Count = 1; + check(!console_placement(&buffer_desc, 1, [](UINT) -> D3D12_RESOURCE_ALLOCATION_INFO { return {1024, 65536}; }, total, nullptr), + "console_placement returns false for buffers (no target)"); + + // Growing render target + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = 1920; + rt_desc.Height = 1080; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + + // Suppose PC device reported 1920*1080*4 = 8,294,400 bytes, aligned to 64 KiB + // Console size is 135 * 65536 = 8,847,360 bytes (which grows). + D3D12_RESOURCE_ALLOCATION_INFO1 each[1]{}; + bool placed = console_placement(&rt_desc, 1, + [](UINT) -> D3D12_RESOURCE_ALLOCATION_INFO { + return {8294400, 65536}; + }, + total, each); + check(placed, "console_placement accepts growing render target"); + check(total.SizeInBytes == 8847360, "total size matches console tile-padded size"); + check(total.Alignment == 65536, "total alignment matches 64 KiB"); + check(each[0].Offset == 0, "each[0] offset is 0"); + check(each[0].SizeInBytes == 8847360, "each[0] size matches console tile-padded size"); + check(each[0].Alignment == 65536, "each[0] alignment matches 64 KiB"); +} + +} // namespace + +int main() { + test_align_up_saturating(); + test_render_target_element_bytes(); + test_console_depth_planes(); + test_console_render_target_size(); + test_console_depth_stencil_size(); + test_console_placement(); + + std::printf("%d/%d checks passed\n", g_checks - g_failures, g_checks); + return g_failures ? 1 : 0; +} From 401d04bde8040a6fd111513b05f6ad3484e5affd Mon Sep 17 00:00:00 2001 From: robot00f Date: Tue, 24 Nov 2026 13:46:41 -0300 Subject: [PATCH 20/42] docs: device slot 62 takes five parameters and slot 76 has no call site in the executable (D3D12-DEVICE-SLOT-ARITY) --- docs/d3d12_vulkan.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index c2e36319e2..c6ca1117a2 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2530,7 +2530,7 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv | D3D12 / Xbox object | Vulkan / layer object | Notes | |---|---|---| -| `ID3D12Device` … `ID3D12Device11` | one `Device` object with the public chain plus measured Xbox overrides | The shipped BVH builder names Device11; slots 1/15/18/19/27/38 matched desktop in prior art, slot 48 is called as `(desc, riid, out)` with `IID_ID3D12CommandQueue` (PC slot 48 is `OpenExistingHeapFromAddress`; the 32-byte desc is a PC `D3D12_COMMAND_QUEUE_DESC` plus four Xbox words, logged once, and the proxy takes the slot 8 path with the PC prefix and only `DISABLE_GPU_TIMEOUT` kept), slot 62 is called as `CreateComputePipelineState`, slot 76 is Xbox texture creation, and heap slots 9/10 return in RAX. Unknown Xbox IIDs/slots are logged and refused. | +| `ID3D12Device` … `ID3D12Device11` | one `Device` object with the public chain plus measured Xbox overrides | The shipped BVH builder names Device11; slots 1/15/18/19/27/38 matched desktop in prior art, slot 48 is called as `(desc, riid, out)` with `IID_ID3D12CommandQueue` (PC slot 48 is `OpenExistingHeapFromAddress`; the 32-byte desc is a PC `D3D12_COMMAND_QUEUE_DESC` plus four Xbox words, logged once, and the proxy takes the slot 8 path with the PC prefix and only `DISABLE_GPU_TIMEOUT` kept), slot 62 is called at `0x14247FE66` as a create with `(desc, 0, 0, &riid, &out)` — five parameters with an explicit IID/out pair, where the PC method it forwards to, `CreateComputePipelineState`, takes three — and static Capstone disassembly over the executable's `.text` (following the device globals `0x148759D00` and `0x1475DF000`–`0x1475DF048` from renderer init `0x142478440`) finds no device call site for slot 76 (`+0x260`; none of the 57 indirect `call [reg+0x260]` sites in `.text` loads a device global); its only measured caller is the shipped FidelityFX upscaler, with the seven `CreateCommittedResource` arguments ([d3d12_command_objects.md](d3d12_command_objects.md) §3.5a), and heap slots 9/10 return in RAX. Unknown Xbox IIDs/slots are logged and refused. | | `ID3D12CommandQueue` | one leased `VkQueue` per live queue: direct queues on the graphics family, compute queues on an async-compute family and copy queues on a transfer-only (DMA) family when the GPU has them (`src/queue_families.h`), else graphics-family leases | Distinct Vulkan queues allow cross-queue waits and signals to make progress. With more than one family in use, buffers, images, the arena and staging are created `VK_SHARING_MODE_CONCURRENT` over those families, so no ownership transfers are needed. Barriers on copy and compute queues are narrowed to the stages their family has; render-target and depth clears are refused there (as in D3D12), and the D24/RGB96 copy conversions and bindless flushes stay off a transfer-only queue. Tested by `vk_queue_test`. `PresentX`, `SuspendX`, `ResumeX` are Xbox queue methods, not in the public vtable; public GDKX samples present only through them (§4.5). Call shapes known, slots **Open**. | | `ID3D12CommandAllocator` | IR arena + `VkCommandPool` | Reset only when the previous submission's fence is complete. | | `ID3D12GraphicsCommandList` … `8` | `CommandList` with IR | Replay at `ExecuteCommandLists`; bundles inlined. Supports render passes, mesh dispatch, enhanced barriers; records the GCL8 front/back stencil references (applied only once a pipeline path consumes them). `Draw` views are inlined and moved into the command stream (D3D-289), eliminating per-draw heap allocations. | From 16a95502a2ff4eae321718d3aebf4f0c40452cbb Mon Sep 17 00:00:00 2001 From: Zack Date: Thu, 26 Nov 2026 01:49:30 -0800 Subject: [PATCH 21/42] tools/dstorage: fit missing BPTC history slots across multi-level sibling mips When a BC6H or BC7 stream still references an unfitted built-in predictor slot after adjacent-mip fitting, pair its mips with the closest raw or zlib mip on the same layer across multi-level mip distances before running the full-stream constraint pass. Existing adjacent-mip, array, and cubemap fits keep precedence. --- docs/directstorage.md | 10 +- tests/test_dstorage_multilevel_fit.py | 154 +++++++++++++++++++++ tools/build_dstorage_history.py | 191 ++++++++++++++++++++++++++ 3 files changed, 351 insertions(+), 4 deletions(-) create mode 100644 tests/test_dstorage_multilevel_fit.py diff --git a/docs/directstorage.md b/docs/directstorage.md index 919d52282a..d7ea641931 100644 --- a/docs/directstorage.md +++ b/docs/directstorage.md @@ -187,10 +187,12 @@ The first boot with the executable settles most of this: the dry-run report show ``` The fitter follows the physical block offset of packed 2D mips, including those that start past the first - 256 blocks of a stream. It combines adjacent mips from the same layer with full-stream index anchor - and shared-p-bit constraints. A shared p-bit can relate low red endpoint bits even when its sibling - mip supplies only the leading bits. These local fits preserve the recorded precision and exact reference - bits. A profile can still lack endpoint values or exceed the reference consistency tolerance. Such a request reports a decompression error before publication. + 256 blocks of a stream. It fits adjacent mips from the same layer first, then pairs any stream that still + references an unfitted slot with the closest raw or zlib mip on the same layer across multi-level mip + distances, before applying full-stream index anchor and shared-p-bit constraints. A shared p-bit can relate + low red endpoint bits even when its sibling mip supplies only the leading bits. These local fits preserve + the recorded precision and exact reference bits. A profile can still lack endpoint values or exceed the + reference consistency tolerance. Such a request reports a decompression error before publication. - The four swizzle modes interleave stripes from request-wide component planes into 16 KiB (mode 1) or 32 KiB (modes 2–4) groups. The enum names give the successive stripe widths. The shipped BC4 sample separates its endpoint planes from indices across the inflated source. The title's compute shader does diff --git a/tests/test_dstorage_multilevel_fit.py b/tests/test_dstorage_multilevel_fit.py new file mode 100644 index 0000000000..b7a374696c --- /dev/null +++ b/tests/test_dstorage_multilevel_fit.py @@ -0,0 +1,154 @@ +"""Synthetic multi-level raw/zlib sibling mip fitting tests for DirectStorage sidecar generation.""" +from pathlib import Path +import sys +import tempfile +import unittest +import zlib + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT / "tools"), str(ROOT / "tests")] +from test_bcpack_history_calib import ( # noqa: E402 + _encode_bc6h_mode14_tiled, + _encode_bc7_mode6_tiled, + _pack_etpf, + _write_custom_rds5_pool, +) +import bcpack # noqa: E402 +import build_dstorage_history as history # noqa: E402 + + +def _solid_bc7_mode6_block(rgba): + r, g, b, a = rgba + acc = 1 << 6 + pos = 7 + for ch in (r, g, b, a): + for _ in range(2): + acc |= ((ch >> 1) & 0x7F) << pos + pos += 7 + acc |= (r & 1) << pos + acc |= (r & 1) << (pos + 1) + return acc.to_bytes(16, "little") + + +def _solid_bc6h_mode14_block(w_rgb): + plan, _ = bcpack._bc6h_plan(0x0F) + fields = [[bcpack._bc6h_stream_w(14, w_rgb[c]), 0, 0, 0] for c in range(3)] + acc = 0x0F + for c, q, bit_idx, pos in plan: + if c >= 0 and ((fields[c][q] >> bit_idx) & 1): + acc |= 1 << pos + return acc.to_bytes(16, "little") + + +def _initial_fit(pools): + fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()} + history.calib.calibrate_from_pools(pools, fits) + docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} + history.extend_missing(docs, history.fit_slices(pools)) + return docs + + +class MultilevelMipFitTest(unittest.TestCase): + def test_bc7_multilevel_parent_downsample_unlocks_provisional_decode(self): + # 128x128 3-mip 2D BC7 chain: mip[0] zlib, mip[1] self-contained BC7, mip[2] BC7 needing entry 176. + # Because mip[2] is 2 levels away from mip[0] and adjacent mip[1] is BC7, adjacent fitting misses 176. + color = (72, 136, 184, 220) + solid = _solid_bc7_mode6_block(color) + secret = color * 6 + raw_mip2 = _encode_bc7_mode6_tiled(solid * 256, secret_entry=176, secret_ep=secret, ref_count=160) + raw_mip1 = _encode_bc7_mode6_tiled(solid * 256) + zlib_mip0 = zlib.compress(solid * 1024, 9) + + with tempfile.TemporaryDirectory() as tmp: + pool = Path(tmp) / "parent-multilevel.ttpf" + record = _pack_etpf(128, 128, 3, 2, 98, 4096, mode=4) + _write_custom_rds5_pool( + pool, + [record], + [(7, 4096, raw_mip2), (7, 4096, raw_mip1), (8, 16384, zlib_mip0)], + ) + docs = _initial_fit([pool]) + self.assertEqual(docs["bc7"]["historyEndpointBits"][176], [0] * 24) + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(raw_mip2, 7, 4096, allow_provisional=True, history=docs) + + history.extend_missing(docs, history.fit_distant_mips([pool], docs)) + + for c, target in enumerate(color): + for field in (c, 4 + c): + self.assertGreaterEqual(docs["bc7"]["historyEndpointBits"][176][field], 4) + self.assertEqual(docs["bc7"]["historyEndpointConfirmedBits"][176][field], 0) + self.assertLessEqual(abs(docs["bc7"]["historyEndpoints"][176][field] - target), 4) + decoded = bcpack.decode(raw_mip2, 7, 4096, allow_provisional=True, history=docs) + self.assertEqual(len(decoded), 4096) + + def test_bc7_multilevel_child_upsample_unlocks_provisional_decode(self): + # 128x128 3-mip 2D BC7 chain: mip[0] BC7 needing entry 209, mip[1] self-contained BC7, mip[2] zlib. + color = (160, 88, 44, 248) + solid = _solid_bc7_mode6_block(color) + secret = color * 6 + zlib_mip2 = zlib.compress(solid * 256, 9) + raw_mip1 = _encode_bc7_mode6_tiled(solid * 256) + raw_mip0 = _encode_bc7_mode6_tiled(solid * 1024, secret_entry=209, secret_ep=secret, ref_count=48) + + with tempfile.TemporaryDirectory() as tmp: + pool = Path(tmp) / "child-multilevel.ttpf" + record = _pack_etpf(128, 128, 3, 2, 98, 4096, mode=4) + _write_custom_rds5_pool( + pool, + [record], + [(8, 4096, zlib_mip2), (7, 4096, raw_mip1), (7, 16384, raw_mip0)], + ) + docs = _initial_fit([pool]) + self.assertEqual(docs["bc7"]["historyEndpointBits"][209], [0] * 24) + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(raw_mip0, 7, 16384, allow_provisional=True, history=docs) + + history.extend_missing(docs, history.fit_distant_mips([pool], docs)) + + for c, target in enumerate(color): + for field in (c, 4 + c): + self.assertGreaterEqual(docs["bc7"]["historyEndpointBits"][209][field], 4) + self.assertLessEqual(abs(docs["bc7"]["historyEndpoints"][209][field] - target), 4) + decoded = bcpack.decode(raw_mip0, 7, 16384, allow_provisional=True, history=docs) + self.assertEqual(len(decoded), 16384) + + def test_bc6h_multilevel_fit_and_existing_slot_precedence(self): + # 128x128 3-mip 2D BC6H UF16 chain: mip[0] zlib, mip[1] self-contained BC6H, mip[2] BC6H needing entry 91. + w_rgb = (0x3400, 0x2800, 0x1C00) + solid = _solid_bc6h_mode14_block(w_rgb) + secret_eh = tuple((w_rgb[c], 0x200, 0x20, 0x20) for c in range(3)) + raw_mip2 = _encode_bc6h_mode14_tiled(solid * 256, secret_entry=91, secret_eh=secret_eh, ref_count=160) + raw_mip1 = _encode_bc6h_mode14_tiled(solid * 256) + zlib_mip0 = zlib.compress(solid * 1024, 9) + + with tempfile.TemporaryDirectory() as tmp: + pool = Path(tmp) / "bc6h-multilevel.ttpf" + record = _pack_etpf(128, 128, 3, 2, 95, 4096, mode=4) + _write_custom_rds5_pool( + pool, + [record], + [(6, 4096, raw_mip2), (6, 4096, raw_mip1), (8, 16384, zlib_mip0)], + ) + docs = _initial_fit([pool]) + self.assertEqual(docs["bc6h"]["endpointClass"][91], 0) + with self.assertRaises(bcpack.BcpackProvisionalError): + bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) + + # A pre-populated slot in `docs` must keep precedence over distant-mip estimates. + docs["bc7"]["historyEndpointBits"][5][0] = 6 + docs["bc7"]["historyEndpoints"][5][0] = 192 + extra = history.fit_distant_mips([pool], docs) + extra["bc7"]["historyEndpointBits"][5][0] = 5 + extra["bc7"]["historyEndpoints"][5][0] = 32 + history.extend_missing(docs, extra) + + self.assertEqual(docs["bc6h"]["endpointClass"][91], 1) + self.assertEqual(docs["bc7"]["historyEndpointBits"][5][0], 6) + self.assertEqual(docs["bc7"]["historyEndpoints"][5][0], 192) + decoded = bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) + self.assertEqual(len(decoded), 4096) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/build_dstorage_history.py b/tools/build_dstorage_history.py index ee9c224bd5..cf15ded1a1 100644 --- a/tools/build_dstorage_history.py +++ b/tools/build_dstorage_history.py @@ -13,6 +13,7 @@ TOOLS = Path(__file__).resolve().parent sys.path.insert(0, str(TOOLS)) +import bcpack import bcpack_history_calib as calib import bcpack_tables_bptc as bptc import gen_bcpack_runtime_tables as pack @@ -79,6 +80,195 @@ def address(m): return docs +def _chunk_needs_missing_slot(codec, prefix, blocks, docs, static_bc7): + l0, l1, l15 = prefix[0], prefix[1], prefix[15] + if codec == 6: + eclass = docs["bc6h"]["endpointClass"] + iclass = docs["bc6h"]["indexClass"] + for i in range(blocks): + di = bcpack._inter8(l1[2 * i], l1[2 * i + 1]) + de = (di + bcpack._unzig(bcpack._inter8(l0[2 * i], l0[2 * i + 1]))) & 255 + if (de > i and not eclass[256 + i - de]) or (di > i and not iclass[256 + i - di]): + return True + return False + ep_bits = docs["bc7"]["historyEndpointBits"] + ix_bits = docs["bc7"]["historyIndexBits"] + cfg = static_bc7["config"] + rank_of = static_bc7["rank_of"] + for i in range(blocks): + di = bcpack._inter8(l1[2 * i], l1[2 * i + 1]) + de = (di + bcpack._unzig(bcpack._inter8(l0[2 * i], l0[2 * i + 1]))) & 255 + if de <= i and di <= i: + continue + s15a, s15b = l15[2 * i], l15[2 * i + 1] + rank = rank_of[s15a * 16 + s15b] if s15a < 32 and s15b < 16 else -1 + if rank < 0 or cfg[rank][0] > 7: + continue + mode, _, rot, _ = cfg[rank] + if de > i: + row = ep_bits[256 + i - de] + bits = bcpack._bc7_field_bits(mode, rot) + for sub in range(bcpack._B7_NS[mode]): + base = sub * 8 + for c, b in enumerate(bits): + if b and (not row[base + c] or not row[base + 4 + c]): + return True + if di > i: + ix_row = ix_bits[256 + i - di] + if any(not ix_row[p] for p in range(16)): + return True + if mode in (4, 5) and any(not ix_row[16 + p] for p in range(16)): + return True + return False + + +def _make_multilevel_quads_getter(codec, layout, ref, tiled, delta_level, signed=False, block_cache=None): + if block_cache is None: + block_cache = {} + pw, ph = ref["pixels_w"], ref["pixels_h"] + nch = 3 if codec == 6 else 4 + + def _get_pixel(px, py): + px = min(pw - 1, max(0, px)) + py = min(ph - 1, max(0, py)) + key = (px >> 2, py >> 2) + blk = block_cache.get(key) + if blk is None: + off = calib.tiled_offset(layout, ref, key[0], key[1]) + blk = (calib.decode_bc6h_block_unq(tiled, off, signed=signed) if codec == 6 else + calib.decode_bc7_block_rgba(tiled, off)) + block_cache[key] = blk + return blk[((py & 3) << 2) | (px & 3)] + + if delta_level < 0: + shift = -delta_level + return lambda bx, by: tuple( + _get_pixel((4 * bx + 2 * qx) >> shift, (4 * by + 2 * qy) >> shift) + for qy in (0, 1) for qx in (0, 1) + ) + + step = 2 << delta_level + stride = max(1, step >> 3) + half = stride >> 1 + + def get_quads(bx, by): + out = [] + for qy in (0, 1): + for qx in (0, 1): + x0 = (4 * bx + 2 * qx) << delta_level + y0 = (4 * by + 2 * qy) << delta_level + x1, y1 = min(pw, x0 + step), min(ph, y0 + step) + if x0 >= x1 or y0 >= y1: + out.append(_get_pixel(x0, y0)) + continue + sx = x0 + half if x0 + half < x1 else x0 + sy = y0 + half if y0 + half < y1 else y0 + acc = [0.0] * nch + cnt = 0 + for py in range(sy, y1, stride): + for px in range(sx, x1, stride): + pv = _get_pixel(px, py) + for c in range(nch): + acc[c] += pv[c] + cnt += 1 + out.append(tuple(v / cnt for v in acc)) + return tuple(out) + + return get_quads + + +def fit_distant_mips(pools, docs): + """Fit remaining missing BPTC history slots from multi-level raw/zlib mips on the same layer.""" + arrays = {6: calib.Bc6hCalibrator(), 7: calib.Bc7Calibrator()} + tails = {6: calib.Bc6hCalibrator(), 7: calib.Bc7Calibrator()} + static_bc7 = bptc._bc7_static() + for path in pools: + with closing(ttpf.Pool(path)) as pool: + if not any(chunk[4] in arrays for chunk in pool.chunks): + continue + raw_cache = {} + need_cache = {} + lanes_cache = {} + for index in range(pool.textures): + d = pool.descriptor(index) + fit = tails if d["depth"] == 1 else arrays + codec = next((c for c in fit if d["format"] in calib.CODEC_DXGI[c]), None) + if not codec or d["dimension"] not in (1, 2): + continue + span = pool.span(index, d["base"]) + if not span: + continue + try: + cs = pool.codecs(d["base"], span) + except ValueError: + continue + if codec not in cs or not (cs & {0, 8}): + continue + a = ttpf.analyze(pool, index) + if not a.get("available") or a.get("blocked"): + continue + mc = a["mip_codecs"] + if not any(codec in s for s in mc) or not any(0 in s or 8 in s for s in mc): + continue + if d["depth"] == 1 and not any(s and set(s) <= {0, 8} for s in mc): + continue + layout = a["layout"] + mips = layout["mips"] + for layer in range(d["depth"]): + def address(m): + return (d["base"] + layout.get("data_offset", 0) + m["offset"] + + layer * m.get("slice_stride", layout.get("face_size", 0))) + ref_levels = [ + lv for lv, m in enumerate(mips) + if m["region"] <= 1048576 and not (pool.codecs(address(m), m["region"]) - {0, 8}) + ] + if not ref_levels: + continue + ref_blocks = {} + for level, mip in enumerate(mips): + if level in ref_levels: + continue + start = address(mip) + needy_chunks = [] + for virt, size, offset, packed, mode, _ in pool.chunks_for(start, mip["region"]): + if mode != codec or size < 16 or start - virt >= 4096 * 16: + continue + key = (offset, packed) + needs = need_cache.get(key) + if needs is None: + pblocks = min(256, size // 16) + prefix = calib.decode_lanes_prefix( + pool.data[offset:offset + packed], codec, size, pblocks * 2) + needs = _chunk_needs_missing_slot(codec, prefix, pblocks, docs, static_bc7) + need_cache[key] = needs + if needs: + lanes_cache[(offset, packed, pblocks)] = prefix + if needs: + needy_chunks.append((size, offset, packed, virt - start, min(4096, size // 16))) + if not needy_chunks: + continue + ref_lv = min(ref_levels, key=lambda rl: (abs(rl - level), rl)) + ref = mips[ref_lv] + ref_addr = address(ref) + tiled = pool.read_range(ref_addr, ref["region"], raw_cache, bcpack_mode="off") + bcache = ref_blocks.setdefault((ref_addr, ref["region"]), {}) + getter = _make_multilevel_quads_getter( + codec, layout, ref, tiled, level - ref_lv, + signed=d["format"] == 96, block_cache=bcache) + inverse = calib.make_inverse_tile_lookup(layout, mip) + for size, offset, packed, relative, blocks in needy_chunks: + lkey = (offset, packed, blocks) + lanes = lanes_cache.get(lkey) + if lanes is None: + lanes = calib.decode_lanes_prefix( + pool.data[offset:offset + packed], codec, size, blocks * 2) + lanes_cache[lkey] = lanes + fit[codec].add_pool_chunk(lanes, blocks, inverse, relative, getter) + out = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in arrays.items()} + extend_missing(out, {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in tails.items()}) + return out + + def extend_missing(base, extra): for value, flag in (("endpointHistory", "endpointClass"), ("indexHistory", "indexClass")): for k, cls in enumerate(extra["bc6h"][flag]): @@ -214,6 +404,7 @@ def build(game, output, trainer, base_history=None, json_out=None, if_needed=Fal calib.calibrate_from_pools(pools, fits) docs = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} extend_missing(docs, fit_slices(pools)) + extend_missing(docs, fit_distant_mips(pools, docs)) history = temp/"history.json" history.write_text(json.dumps(docs), encoding="utf-8", newline="\n") if not trainer: From 4bc50fbd6d9e03587ad33eb521d10e049db50ce3 Mon Sep 17 00:00:00 2001 From: Zack Date: Sat, 28 Nov 2026 01:44:28 -0800 Subject: [PATCH 22/42] tests: drive build_dstorage_history.build in multilevel mip fit tests Exercise the public history.build(...) pipeline end-to-end across all four synthetic multi-level BPTC mip fitting tests so running the test file against main reaches value assertions (4 AssertionErrors, 0 AttributeErrors) instead of stopping on the missing fit_distant_mips helper. --- tests/test_dstorage_multilevel_fit.py | 146 ++++++++++++++++---------- 1 file changed, 92 insertions(+), 54 deletions(-) diff --git a/tests/test_dstorage_multilevel_fit.py b/tests/test_dstorage_multilevel_fit.py index 9991025ab4..e1d5de30a1 100644 --- a/tests/test_dstorage_multilevel_fit.py +++ b/tests/test_dstorage_multilevel_fit.py @@ -1,8 +1,11 @@ """Synthetic multi-level raw/zlib sibling mip fitting tests for DirectStorage sidecar generation.""" +from array import array +import json from pathlib import Path import sys import tempfile import unittest +from unittest import mock import zlib ROOT = Path(__file__).resolve().parents[1] @@ -41,39 +44,55 @@ def _solid_bc6h_mode14_block(w_rgb): return acc.to_bytes(16, "little") -def _initial_fit(pools): - fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()} - history.calib.calibrate_from_pools(pools, fits) - docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()} - history.extend_missing(docs, history.fit_slices(pools)) - return docs +def _refused_bc7_mode6_stream(nblocks): + solid = bytes([0x40]) + bytes(15) + lanes, _ = bcpack.decode_lanes(_encode_bc7_mode6_tiled(solid * nblocks), 7, nblocks * 16) + lanes[11] = [2, 0] * nblocks + return encode_lanes(lanes, 7) + + +def _zero_votes(_pools, _trainer, _temp): + return array("Q", [0]) * (2 * 256 * 35 * 16) + + +def _build_history(game_input, work, base_history=None): + sidecar = work / "out" / "history.bcph" + json_out = work / "out" / "fitted.json" + with mock.patch.object(history, "collect", side_effect=_zero_votes): + history.build( + Path(game_input), + sidecar, + Path("stub-trainer"), + base_history=base_history, + json_out=json_out, + ) + raw = sidecar.read_bytes() + assert raw[:8] == b"BCPHIST1" and len(raw) == 60936 + return json.loads(json_out.read_text(encoding="utf-8")) class MultilevelMipFitTest(unittest.TestCase): def test_bc7_multilevel_parent_downsample_unlocks_provisional_decode(self): - # 128x128 3-mip 2D BC7 chain: mip[0] zlib, mip[1] self-contained BC7, mip[2] BC7 needing entry 176. - # Because mip[2] is 2 levels away from mip[0] and adjacent mip[1] is BC7, adjacent fitting misses 176. + # 128x128 3-mip 2D array BC7 chain: mip[0] lossless zlib, mip[1] BC7 with an undecodable + # anchor bit (so neighbor decode masks out mip[1]), and mip[2] BC7 needing entry 176. color = (72, 136, 184, 220) solid = _solid_bc7_mode6_block(color) secret = color * 6 - raw_mip2 = _encode_bc7_mode6_tiled(solid * 256, secret_entry=176, secret_ep=secret, ref_count=160) - raw_mip1 = _encode_bc7_mode6_tiled(solid * 256) + raw_mip2 = _encode_bc7_mode6_tiled(solid * 256, secret_entry=176, secret_ep=secret, ref_count=255) + raw_mip1 = _refused_bc7_mode6_stream(256) zlib_mip0 = zlib.compress(solid * 1024, 9) with tempfile.TemporaryDirectory() as tmp: - pool = Path(tmp) / "parent-multilevel.ttpf" + work = Path(tmp) + pool = work / "pools" / "parent-multilevel.ttpf" + pool.parent.mkdir(parents=True, exist_ok=True) record = _pack_etpf(128, 128, 3, 2, 98, 4096, mode=4) _write_custom_rds5_pool( pool, [record], [(7, 4096, raw_mip2), (7, 4096, raw_mip1), (8, 16384, zlib_mip0)], ) - docs = _initial_fit([pool]) - self.assertEqual(docs["bc7"]["historyEndpointBits"][176], [0] * 24) - with self.assertRaises(bcpack.BcpackProvisionalError): - bcpack.decode(raw_mip2, 7, 4096, allow_provisional=True, history=docs) - - history.extend_missing(docs, history.fit_distant_mips([pool], docs)) + docs = _build_history(pool, work) for c, target in enumerate(color): for field in (c, 4 + c): @@ -84,28 +103,26 @@ def test_bc7_multilevel_parent_downsample_unlocks_provisional_decode(self): self.assertEqual(len(decoded), 4096) def test_bc7_multilevel_child_upsample_unlocks_provisional_decode(self): - # 128x128 3-mip 2D BC7 chain: mip[0] BC7 needing entry 209, mip[1] self-contained BC7, mip[2] zlib. + # 128x128 3-mip 2D array BC7 chain: mip[0] BC7 needing entry 209, mip[1] undecodable BC7, + # and mip[2] lossless zlib two levels smaller. color = (160, 88, 44, 248) solid = _solid_bc7_mode6_block(color) secret = color * 6 zlib_mip2 = zlib.compress(solid * 256, 9) - raw_mip1 = _encode_bc7_mode6_tiled(solid * 256) + raw_mip1 = _refused_bc7_mode6_stream(256) raw_mip0 = _encode_bc7_mode6_tiled(solid * 1024, secret_entry=209, secret_ep=secret, ref_count=48) with tempfile.TemporaryDirectory() as tmp: - pool = Path(tmp) / "child-multilevel.ttpf" + work = Path(tmp) + pool = work / "pools" / "child-multilevel.ttpf" + pool.parent.mkdir(parents=True, exist_ok=True) record = _pack_etpf(128, 128, 3, 2, 98, 4096, mode=4) _write_custom_rds5_pool( pool, [record], [(8, 4096, zlib_mip2), (7, 4096, raw_mip1), (7, 16384, raw_mip0)], ) - docs = _initial_fit([pool]) - self.assertEqual(docs["bc7"]["historyEndpointBits"][209], [0] * 24) - with self.assertRaises(bcpack.BcpackProvisionalError): - bcpack.decode(raw_mip0, 7, 16384, allow_provisional=True, history=docs) - - history.extend_missing(docs, history.fit_distant_mips([pool], docs)) + docs = _build_history(pool, work) for c, target in enumerate(color): for field in (c, 4 + c): @@ -115,36 +132,61 @@ def test_bc7_multilevel_child_upsample_unlocks_provisional_decode(self): self.assertEqual(len(decoded), 16384) def test_bc6h_multilevel_fit_and_existing_slot_precedence(self): - # 128x128 3-mip 2D BC6H UF16 chain: mip[0] zlib, mip[1] self-contained BC6H, mip[2] BC6H needing entry 91. + # 128x128 BC6H UF16 pools where mip[0] is lossless zlib, mip[1] is refused BC6H, and mip[2] + # needs unknown entry 91 (plus a second pool referencing pre-populated entry 12 to verify + # base_history slots keep precedence over distant-mip estimates). w_rgb = (0x3400, 0x2800, 0x1C00) solid = _solid_bc6h_mode14_block(w_rgb) - secret_eh = tuple((w_rgb[c], 0x200, 0x20, 0x20) for c in range(3)) - raw_mip2 = _encode_bc6h_mode14_tiled(solid * 256, secret_entry=91, secret_eh=secret_eh, ref_count=160) - raw_mip1 = _encode_bc6h_mode14_tiled(solid * 256) + lanes_mip1 = [[0] * 512 for _ in range(16)] + lanes_mip1[15] = [13, 0] * 256 + raw_mip1 = encode_lanes(lanes_mip1, 6) + secret_91 = tuple((w_rgb[c], 0x200, 0x20, 0x20) for c in range(3)) + raw_mip2 = _encode_bc6h_mode14_tiled( + solid * 256, secret_entry=91, secret_eh=secret_91, ref_count=160 + ) zlib_mip0 = zlib.compress(solid * 1024, 9) + other_w = (0x1000, 0x1400, 0x1800) + other_solid = _solid_bc6h_mode14_block(other_w) + secret_12 = tuple((other_w[c], 0x200, 0x20, 0x20) for c in range(3)) + other_mip2 = _encode_bc6h_mode14_tiled( + other_solid * 256, secret_entry=12, secret_eh=secret_12, ref_count=160 + ) + other_zlib = zlib.compress(other_solid * 1024, 9) + with tempfile.TemporaryDirectory() as tmp: - pool = Path(tmp) / "bc6h-multilevel.ttpf" + work = Path(tmp) + pools_dir = work / "pools" + pools_dir.mkdir(parents=True, exist_ok=True) record = _pack_etpf(128, 128, 3, 2, 95, 4096, mode=4) _write_custom_rds5_pool( - pool, + pools_dir / "bc6h-multilevel.ttpf", [record], [(6, 4096, raw_mip2), (6, 4096, raw_mip1), (8, 16384, zlib_mip0)], ) - docs = _initial_fit([pool]) - self.assertEqual(docs["bc6h"]["endpointClass"][91], 0) - with self.assertRaises(bcpack.BcpackProvisionalError): - bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) - - # A pre-populated slot in `docs` must keep precedence over distant-mip estimates. - docs["bc7"]["historyEndpointBits"][5][0] = 6 - docs["bc7"]["historyEndpoints"][5][0] = 192 - extra = history.fit_distant_mips([pool], docs) - extra["bc7"]["historyEndpointBits"][5][0] = 5 - extra["bc7"]["historyEndpoints"][5][0] = 32 - history.extend_missing(docs, extra) + _write_custom_rds5_pool( + pools_dir / "bc6h-precedence.ttpf", + [record], + [(6, 4096, other_mip2), (6, 4096, raw_mip1), (8, 16384, other_zlib)], + ) + + base_dir = work / "base" + base_dir.mkdir(parents=True, exist_ok=True) + base_bc6h = history.calib.Bc6hCalibrator().build_document()[0] + kept_entry = [[0x2AAA, 11, 2, 3], [0x2BBB, 12, 3, 4], [0x2CCC, 13, 4, 5]] + base_bc6h["endpointClass"][12] = 1 + base_bc6h["endpointHistory"][12] = kept_entry + base_bc7 = history.calib.Bc7Calibrator().build_document()[0] + base_bc7["historyEndpointBits"][5][0] = 6 + base_bc7["historyEndpoints"][5][0] = 192 + (base_dir / "bc6h.json").write_text(json.dumps(base_bc6h), encoding="utf-8", newline="\n") + (base_dir / "bc7.json").write_text(json.dumps(base_bc7), encoding="utf-8", newline="\n") + + docs = _build_history(pools_dir, work, base_history=base_dir) self.assertEqual(docs["bc6h"]["endpointClass"][91], 1) + self.assertEqual(docs["bc6h"]["endpointClass"][12], 1) + self.assertEqual(docs["bc6h"]["endpointHistory"][12], kept_entry) self.assertEqual(docs["bc7"]["historyEndpointBits"][5][0], 6) self.assertEqual(docs["bc7"]["historyEndpoints"][5][0], 192) decoded = bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) @@ -152,8 +194,8 @@ def test_bc6h_multilevel_fit_and_existing_slot_precedence(self): def test_refused_bc6h_intermediate_sibling_falls_back_to_multilevel_zlib_mip(self): # mip[0] is zlib, mip[1] is a BC6H stream refused by decode (inconsistent anchor index 8), and mip[2] needs - # unknown endpoint entry 91. fit_decoded_neighbors cannot decode mip[1] as a reference, whereas fit_distant_mips - # pairs mip[2] directly with lossless zlib mip[0] two levels up. + # unknown endpoint entry 91. Neighbor decoding cannot decode mip[1] as a reference, whereas multi-level + # fitting pairs mip[2] directly with lossless zlib mip[0] two levels up. w_rgb = (0x3400, 0x2800, 0x1C00) solid = _solid_bc6h_mode14_block(w_rgb) lanes_mip1 = [[0] * 512 for _ in range(16)] @@ -164,20 +206,16 @@ def test_refused_bc6h_intermediate_sibling_falls_back_to_multilevel_zlib_mip(sel zlib_mip0 = zlib.compress(solid * 1024, 9) with tempfile.TemporaryDirectory() as tmp: - pool = Path(tmp) / "bc6h-refused-mid.ttpf" + work = Path(tmp) + pool = work / "pools" / "bc6h-refused-mid.ttpf" + pool.parent.mkdir(parents=True, exist_ok=True) record = _pack_etpf(128, 128, 3, 2, 95, 4096, mode=4) _write_custom_rds5_pool( pool, [record], [(6, 4096, raw_mip2), (6, 4096, raw_mip1), (8, 16384, zlib_mip0)], ) - docs = _initial_fit([pool]) - history.fit_decoded_neighbors([pool], docs) - self.assertEqual(docs["bc6h"]["endpointClass"][91], 0) - with self.assertRaises(bcpack.BcpackProvisionalError): - bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) - - history.extend_missing(docs, history.fit_distant_mips([pool], docs)) + docs = _build_history(pool, work) self.assertEqual(docs["bc6h"]["endpointClass"][91], 1) decoded = bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) From b55056766ee6dda71f8a86565d8eeeee3a159846 Mon Sep 17 00:00:00 2001 From: Zack Date: Sat, 28 Nov 2026 02:11:41 -0800 Subject: [PATCH 23/42] tests: eliminate wrap-around and strengthen precedence/decode checks in multilevel mip fit - Keep secret_entry >= 192 with ref_count <= secret_entry across all synthetic BPTC streams so predictor distances never wrap mod 256 and main leaves unknown slots at zero rather than self-fitting wrapped blocks. - Drive dual-slot BC6H and BC7 chunks (missing slot 240 + pre-populated slot 241 with conflicting pool colors) so extend_missing precedence is genuinely exercised for both codecs. - Assert fitted BC6H endpoint values, zero confirmed-bit masks, and per-block decoded RGBA / unquantized HDR pixels across both parent-downsample and child-upsample streams, and include codec mode in fit_distant_mips wanted keys. --- tests/test_dstorage_multilevel_fit.py | 315 +++++++++++++++++++------- tools/build_dstorage_history.py | 4 +- 2 files changed, 233 insertions(+), 86 deletions(-) diff --git a/tests/test_dstorage_multilevel_fit.py b/tests/test_dstorage_multilevel_fit.py index e1d5de30a1..e18f38c0aa 100644 --- a/tests/test_dstorage_multilevel_fit.py +++ b/tests/test_dstorage_multilevel_fit.py @@ -11,13 +11,20 @@ ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT / "tools"), str(ROOT / "tests")] from test_bcpack_history_calib import ( # noqa: E402 + _deint4, + _deint_n, _encode_bc6h_mode14_tiled, _encode_bc7_mode6_tiled, _pack_etpf, + _pack_ix_pair, + _signed_mod_delta, + _signed_mod_delta_m, _write_custom_rds5_pool, + _zig, encode_lanes, ) import bcpack # noqa: E402 +import bcpack_tables_bptc as bptc # noqa: E402 import build_dstorage_history as history # noqa: E402 @@ -51,34 +58,117 @@ def _refused_bc7_mode6_stream(nblocks): return encode_lanes(lanes, 7) -def _zero_votes(_pools, _trainer, _temp): - return array("Q", [0]) * (2 * 256 * 35 * 16) +def _encode_dual_bc6h_mode14_tiled(tiled_bytes, even_slot, even_eh, odd_slot, odd_eh): + """Encode Mode-14 BC6H blocks referencing `even_slot` on even blocks and `odd_slot` on odd blocks.""" + assert 192 <= even_slot <= 255 and 192 <= odd_slot <= 255 + nblocks = len(tiled_bytes) // 16 + lanes = [[] for _ in range(16)] + for i in range(nblocks): + parsed = history.calib.unpack_bc6h_block(tiled_bytes, i * 16) + assert parsed is not None and parsed[0] == 14 + _mode, part, f, ixs = parsed + slot, eref = (even_slot, even_eh) if (i % 2 == 0) else (odd_slot, odd_eh) + if i < slot: + de = 256 + i - slot + assert i < de <= 255 + else: + de = 0 + eref = bcpack._BC6H_NONE_E + lanes[0].extend(_deint4(_zig(_signed_mod_delta_m(de, 0, 256)))) + lanes[1].extend(_deint4(0)) + lanes[15].extend([13, part]) + for c in range(3): + dz0 = _signed_mod_delta(f[c][0], eref[c][0], 16) + dz1 = _signed_mod_delta(f[c][1], eref[c][1] >> 6, 4) + lanes[2 + c].extend(_deint_n(_zig(dz0), 8)) + lanes[5 + c].extend(_deint_n(_zig(dz1), 5)) + lanes[8 + c].extend([0, 0]) + for yy in range(4): + ds = [_zig(_signed_mod_delta(ixs[yy * 4 + xx], 0, 4)) for xx in range(4)] + lanes[11 + yy].extend([_pack_ix_pair(ds[0], ds[1], yy), _pack_ix_pair(ds[2], ds[3], yy)]) + return encode_lanes(lanes, 6) -def _build_history(game_input, work, base_history=None): - sidecar = work / "out" / "history.bcph" - json_out = work / "out" / "fitted.json" - with mock.patch.object(history, "collect", side_effect=_zero_votes): - history.build( - Path(game_input), - sidecar, - Path("stub-trainer"), - base_history=base_history, - json_out=json_out, - ) - raw = sidecar.read_bytes() - assert raw[:8] == b"BCPHIST1" and len(raw) == 60936 - return json.loads(json_out.read_text(encoding="utf-8")) +def _encode_dual_bc7_mode6_tiled(tiled_bytes, even_slot, even_ep, odd_slot, odd_ep): + """Encode Mode-6 BC7 blocks referencing `even_slot` on even blocks and `odd_slot` on odd blocks.""" + assert 192 <= even_slot <= 255 and 192 <= odd_slot <= 255 + tab = bptc.load_bc7() + rank = tab["config"].index((6, 0, 0, 0)) + s15a, s15b = divmod(tab["rank_of"].index(rank), 16) + nblocks = len(tiled_bytes) // 16 + lanes = [[] for _ in range(16)] + for i in range(nblocks): + acc = int.from_bytes(tiled_bytes[i * 16:(i + 1) * 16], "little") + pos = 7 + ch = [[0, 0] for _ in range(4)] + for c in range(4): + for e in range(2): + ch[c][e] = (acc >> pos) & 0x7F + pos += 7 + p0 = (acc >> pos) & 1 + p1 = (acc >> (pos + 1)) & 1 + pos += 2 + ch[0][0] = (ch[0][0] << 1) | p0 + ch[0][1] = (ch[0][1] << 1) | p1 + ixs = [] + for p in range(16): + nb = 3 if p == 0 else 4 + ixs.append((acc >> pos) & ((1 << nb) - 1)) + pos += nb + + slot, rep = (even_slot, even_ep) if (i % 2 == 0) else (odd_slot, odd_ep) + if i < slot: + de = 256 + i - slot + assert i < de <= 255 + else: + de = 0 + rep = (0,) * 24 + lanes[0].extend(_deint4(_zig(_signed_mod_delta_m(de, 0, 256)))) + lanes[1].extend(_deint4(0)) + lanes[15].extend([s15a, s15b]) + for c, ln in enumerate((2, 3, 4, 5)): + bits = 8 if c == 0 else 7 + sh = 8 - bits + lanes[ln].extend([ + _zig(_signed_mod_delta(ch[c][0], rep[c] >> sh, bits)), + _zig(_signed_mod_delta(ch[c][1], rep[4 + c] >> sh, bits)), + ]) + for ln in (6, 7, 8, 9, 10): + lanes[ln].extend([0, 0]) + for y in range(4): + ds = [_zig(_signed_mod_delta(ixs[y * 4 + x], 0, 4)) for x in range(4)] + lanes[11 + y].extend([_pack_ix_pair(ds[0], ds[1], y), _pack_ix_pair(ds[2], ds[3], y)]) + return encode_lanes(lanes, 7) + + +def _zero_votes(_pools, _trainer, _temp): + return array("Q", [0]) * (2 * 256 * 35 * 16) class MultilevelMipFitTest(unittest.TestCase): + def _build_history(self, game_input, work, base_history=None): + sidecar = work / "out" / "history.bcph" + json_out = work / "out" / "fitted.json" + with mock.patch.object(history, "collect", side_effect=_zero_votes): + history.build( + Path(game_input), + sidecar, + Path("stub-trainer"), + base_history=base_history, + json_out=json_out, + ) + raw = sidecar.read_bytes() + self.assertEqual((raw[:8], len(raw)), (b"BCPHIST1", 60936)) + return json.loads(json_out.read_text(encoding="utf-8")) + def test_bc7_multilevel_parent_downsample_unlocks_provisional_decode(self): - # 128x128 3-mip 2D array BC7 chain: mip[0] lossless zlib, mip[1] BC7 with an undecodable - # anchor bit (so neighbor decode masks out mip[1]), and mip[2] BC7 needing entry 176. + # 128x128 5-mip (2 non-tail + 3 packed-tail) 2D BC7 chain: mip[0] lossless zlib, + # mip[1] BC7 with an undecodable anchor bit (so neighbor decode masks out mip[1]), + # and packed tail mips[2..4] rooting all 256 blocks at entry 255 without wrap-around. color = (72, 136, 184, 220) solid = _solid_bc7_mode6_block(color) secret = color * 6 - raw_mip2 = _encode_bc7_mode6_tiled(solid * 256, secret_entry=176, secret_ep=secret, ref_count=255) + raw_tail = _encode_bc7_mode6_tiled(solid * 256, secret_entry=255, secret_ep=secret, ref_count=255) raw_mip1 = _refused_bc7_mode6_stream(256) zlib_mip0 = zlib.compress(solid * 1024, 9) @@ -90,25 +180,31 @@ def test_bc7_multilevel_parent_downsample_unlocks_provisional_decode(self): _write_custom_rds5_pool( pool, [record], - [(7, 4096, raw_mip2), (7, 4096, raw_mip1), (8, 16384, zlib_mip0)], + [(7, 4096, raw_tail), (7, 4096, raw_mip1), (8, 16384, zlib_mip0)], ) - docs = _build_history(pool, work) + docs = self._build_history(pool, work) for c, target in enumerate(color): for field in (c, 4 + c): - self.assertGreaterEqual(docs["bc7"]["historyEndpointBits"][176][field], 4) - self.assertEqual(docs["bc7"]["historyEndpointConfirmedBits"][176][field], 0) - self.assertLessEqual(abs(docs["bc7"]["historyEndpoints"][176][field] - target), 4) - decoded = bcpack.decode(raw_mip2, 7, 4096, allow_provisional=True, history=docs) + self.assertGreaterEqual(docs["bc7"]["historyEndpointBits"][255][field], 4) + self.assertEqual(docs["bc7"]["historyEndpointConfirmedBits"][255][field], 0) + self.assertLessEqual(abs(docs["bc7"]["historyEndpoints"][255][field] - target), 4) + decoded = bcpack.decode(raw_tail, 7, 4096, allow_provisional=True, history=docs) self.assertEqual(len(decoded), 4096) + expected_px = history.calib.decode_bc7_block_rgba(solid, 0)[0] + for blk in range(256): + px = history.calib.decode_bc7_block_rgba(decoded, blk * 16)[0] + for c in range(4): + self.assertLessEqual(abs(px[c] - expected_px[c]), 4, f"block {blk} ch {c}") def test_bc7_multilevel_child_upsample_unlocks_provisional_decode(self): - # 128x128 3-mip 2D array BC7 chain: mip[0] BC7 needing entry 209, mip[1] undecodable BC7, - # and mip[2] lossless zlib two levels smaller. + # 128x128 5-mip (2 non-tail + 3 packed-tail) 2D BC7 chain: mip[0] BC7 needing entry 209 + # (ref_count=48 <= 209, zero wrap-around), mip[1] undecodable BC7, and packed tail + # mips[2..4] lossless zlib two levels smaller. color = (160, 88, 44, 248) solid = _solid_bc7_mode6_block(color) secret = color * 6 - zlib_mip2 = zlib.compress(solid * 256, 9) + zlib_tail = zlib.compress(solid * 256, 9) raw_mip1 = _refused_bc7_mode6_stream(256) raw_mip0 = _encode_bc7_mode6_tiled(solid * 1024, secret_entry=209, secret_ep=secret, ref_count=48) @@ -120,106 +216,157 @@ def test_bc7_multilevel_child_upsample_unlocks_provisional_decode(self): _write_custom_rds5_pool( pool, [record], - [(8, 4096, zlib_mip2), (7, 4096, raw_mip1), (7, 16384, raw_mip0)], + [(8, 4096, zlib_tail), (7, 4096, raw_mip1), (7, 16384, raw_mip0)], ) - docs = _build_history(pool, work) + docs = self._build_history(pool, work) for c, target in enumerate(color): for field in (c, 4 + c): self.assertGreaterEqual(docs["bc7"]["historyEndpointBits"][209][field], 4) + self.assertEqual(docs["bc7"]["historyEndpointConfirmedBits"][209][field], 0) self.assertLessEqual(abs(docs["bc7"]["historyEndpoints"][209][field] - target), 4) decoded = bcpack.decode(raw_mip0, 7, 16384, allow_provisional=True, history=docs) self.assertEqual(len(decoded), 16384) + expected_px = history.calib.decode_bc7_block_rgba(solid, 0)[0] + for blk in range(1024): + px = history.calib.decode_bc7_block_rgba(decoded, blk * 16)[0] + for c in range(4): + self.assertLessEqual(abs(px[c] - expected_px[c]), 4, f"block {blk} ch {c}") - def test_bc6h_multilevel_fit_and_existing_slot_precedence(self): - # 128x128 BC6H UF16 pools where mip[0] is lossless zlib, mip[1] is refused BC6H, and mip[2] - # needs unknown entry 91 (plus a second pool referencing pre-populated entry 12 to verify - # base_history slots keep precedence over distant-mip estimates). + def test_bc6h_and_bc7_multilevel_fit_preserve_existing_base_history_slots(self): + # Single dual-slot BC6H chunk and single dual-slot BC7 chunk: each chunk references BOTH + # a missing slot (240, forcing _chunk_needs_missing_slot == True so fit_distant_mips scans + # the chunk) AND a pre-populated base_history slot (241) whose distant-mip observation + # conflicts with base_history, proving extend_missing fills 240 without overwriting 241. w_rgb = (0x3400, 0x2800, 0x1C00) - solid = _solid_bc6h_mode14_block(w_rgb) + solid_bc6h = _solid_bc6h_mode14_block(w_rgb) + stream_w = [bcpack._bc6h_stream_w(14, w_rgb[c]) for c in range(3)] + pool_eh = tuple((stream_w[c], 0, 0, 0) for c in range(3)) lanes_mip1 = [[0] * 512 for _ in range(16)] lanes_mip1[15] = [13, 0] * 256 - raw_mip1 = encode_lanes(lanes_mip1, 6) - secret_91 = tuple((w_rgb[c], 0x200, 0x20, 0x20) for c in range(3)) - raw_mip2 = _encode_bc6h_mode14_tiled( - solid * 256, secret_entry=91, secret_eh=secret_91, ref_count=160 - ) - zlib_mip0 = zlib.compress(solid * 1024, 9) + refused_bc6h_mip1 = encode_lanes(lanes_mip1, 6) + dual_bc6h_tail = _encode_dual_bc6h_mode14_tiled(solid_bc6h * 256, 240, pool_eh, 241, pool_eh) + zlib_bc6h_mip0 = zlib.compress(solid_bc6h * 1024, 9) - other_w = (0x1000, 0x1400, 0x1800) - other_solid = _solid_bc6h_mode14_block(other_w) - secret_12 = tuple((other_w[c], 0x200, 0x20, 0x20) for c in range(3)) - other_mip2 = _encode_bc6h_mode14_tiled( - other_solid * 256, secret_entry=12, secret_eh=secret_12, ref_count=160 - ) - other_zlib = zlib.compress(other_solid * 1024, 9) + color_bc7 = (72, 136, 184, 220) + solid_bc7 = _solid_bc7_mode6_block(color_bc7) + pool_ep_bc7 = color_bc7 * 6 + dual_bc7_tail = _encode_dual_bc7_mode6_tiled(solid_bc7 * 256, 240, pool_ep_bc7, 241, pool_ep_bc7) + refused_bc7_mip1 = _refused_bc7_mode6_stream(256) + zlib_bc7_mip0 = zlib.compress(solid_bc7 * 1024, 9) with tempfile.TemporaryDirectory() as tmp: work = Path(tmp) pools_dir = work / "pools" pools_dir.mkdir(parents=True, exist_ok=True) - record = _pack_etpf(128, 128, 3, 2, 95, 4096, mode=4) + rec_bc6h = _pack_etpf(128, 128, 3, 2, 95, 4096, mode=4) _write_custom_rds5_pool( - pools_dir / "bc6h-multilevel.ttpf", - [record], - [(6, 4096, raw_mip2), (6, 4096, raw_mip1), (8, 16384, zlib_mip0)], + pools_dir / "bc6h-dual.ttpf", + [rec_bc6h], + [(6, 4096, dual_bc6h_tail), (6, 4096, refused_bc6h_mip1), (8, 16384, zlib_bc6h_mip0)], ) + rec_bc7 = _pack_etpf(128, 128, 3, 2, 98, 4096, mode=4) _write_custom_rds5_pool( - pools_dir / "bc6h-precedence.ttpf", - [record], - [(6, 4096, other_mip2), (6, 4096, raw_mip1), (8, 16384, other_zlib)], + pools_dir / "bc7-dual.ttpf", + [rec_bc7], + [(7, 4096, dual_bc7_tail), (7, 4096, refused_bc7_mip1), (8, 16384, zlib_bc7_mip0)], ) base_dir = work / "base" base_dir.mkdir(parents=True, exist_ok=True) base_bc6h = history.calib.Bc6hCalibrator().build_document()[0] - kept_entry = [[0x2AAA, 11, 2, 3], [0x2BBB, 12, 3, 4], [0x2CCC, 13, 4, 5]] - base_bc6h["endpointClass"][12] = 1 - base_bc6h["endpointHistory"][12] = kept_entry + kept_bc6h = [[0x2AAA, 11, 2, 3], [0x2BBB, 12, 3, 4], [0x2CCC, 13, 4, 5]] + base_bc6h["endpointClass"][241] = 1 + base_bc6h["endpointHistory"][241] = kept_bc6h base_bc7 = history.calib.Bc7Calibrator().build_document()[0] - base_bc7["historyEndpointBits"][5][0] = 6 - base_bc7["historyEndpoints"][5][0] = 192 + for f in range(8): + base_bc7["historyEndpointBits"][241][f] = 6 + base_bc7["historyEndpoints"][241][f] = 192 (base_dir / "bc6h.json").write_text(json.dumps(base_bc6h), encoding="utf-8", newline="\n") (base_dir / "bc7.json").write_text(json.dumps(base_bc7), encoding="utf-8", newline="\n") - docs = _build_history(pools_dir, work, base_history=base_dir) + docs = self._build_history(pools_dir, work, base_history=base_dir) - self.assertEqual(docs["bc6h"]["endpointClass"][91], 1) - self.assertEqual(docs["bc6h"]["endpointClass"][12], 1) - self.assertEqual(docs["bc6h"]["endpointHistory"][12], kept_entry) - self.assertEqual(docs["bc7"]["historyEndpointBits"][5][0], 6) - self.assertEqual(docs["bc7"]["historyEndpoints"][5][0], 192) - decoded = bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) - self.assertEqual(len(decoded), 4096) + self.assertEqual(docs["bc6h"]["endpointClass"][240], 1) + self.assertEqual(docs["bc6h"]["endpointConfirmedBits"][240], [[0, 0, 0, 0]] * 3) + for c in range(3): + self.assertLessEqual(abs(docs["bc6h"]["endpointHistory"][240][c][0] - stream_w[c]), 8) + self.assertEqual(docs["bc6h"]["endpointClass"][241], 1) + self.assertEqual(docs["bc6h"]["endpointHistory"][241], kept_bc6h) + + for c, target in enumerate(color_bc7): + for field in (c, 4 + c): + self.assertGreaterEqual(docs["bc7"]["historyEndpointBits"][240][field], 4) + self.assertLessEqual(abs(docs["bc7"]["historyEndpoints"][240][field] - target), 4) + for f in range(8): + self.assertEqual(docs["bc7"]["historyEndpointBits"][241][f], 6) + self.assertEqual(docs["bc7"]["historyEndpoints"][241][f], 192) def test_refused_bc6h_intermediate_sibling_falls_back_to_multilevel_zlib_mip(self): - # mip[0] is zlib, mip[1] is a BC6H stream refused by decode (inconsistent anchor index 8), and mip[2] needs - # unknown endpoint entry 91. Neighbor decoding cannot decode mip[1] as a reference, whereas multi-level - # fitting pairs mip[2] directly with lossless zlib mip[0] two levels up. - w_rgb = (0x3400, 0x2800, 0x1C00) - solid = _solid_bc6h_mode14_block(w_rgb) + # Full build without base_history across both parent-downsample (slot 200, ref_count=200) + # and child-upsample (slot 212, ref_count=64) BC6H textures whose intermediate mip[1] is + # refused by decode (inconsistent anchor index 8), verifying fitted HDR endpoint values + # and exact decoded block bytes. + w_parent = (0x3400, 0x2800, 0x1C00) + solid_parent = _solid_bc6h_mode14_block(w_parent) + sw_parent = [bcpack._bc6h_stream_w(14, w_parent[c]) for c in range(3)] + eh_parent = tuple((sw_parent[c], 0, 0, 0) for c in range(3)) + raw_tail_parent = _encode_bc6h_mode14_tiled( + solid_parent * 256, secret_entry=200, secret_eh=eh_parent, ref_count=200 + ) + zlib_mip0_parent = zlib.compress(solid_parent * 1024, 9) + + w_child = (0x2200, 0x3100, 0x1500) + solid_child = _solid_bc6h_mode14_block(w_child) + sw_child = [bcpack._bc6h_stream_w(14, w_child[c]) for c in range(3)] + eh_child = tuple((sw_child[c], 0, 0, 0) for c in range(3)) + raw_mip0_child = _encode_bc6h_mode14_tiled( + solid_child * 1024, secret_entry=212, secret_eh=eh_child, ref_count=64 + ) + zlib_tail_child = zlib.compress(solid_child * 256, 9) + lanes_mip1 = [[0] * 512 for _ in range(16)] lanes_mip1[15] = [13, 0] * 256 raw_mip1 = encode_lanes(lanes_mip1, 6) - secret_eh = tuple((w_rgb[c], 0x200, 0x20, 0x20) for c in range(3)) - raw_mip2 = _encode_bc6h_mode14_tiled(solid * 256, secret_entry=91, secret_eh=secret_eh, ref_count=160) - zlib_mip0 = zlib.compress(solid * 1024, 9) with tempfile.TemporaryDirectory() as tmp: work = Path(tmp) - pool = work / "pools" / "bc6h-refused-mid.ttpf" - pool.parent.mkdir(parents=True, exist_ok=True) + pools_dir = work / "pools" + pools_dir.mkdir(parents=True, exist_ok=True) record = _pack_etpf(128, 128, 3, 2, 95, 4096, mode=4) _write_custom_rds5_pool( - pool, + pools_dir / "bc6h-parent-refused-mid.ttpf", [record], - [(6, 4096, raw_mip2), (6, 4096, raw_mip1), (8, 16384, zlib_mip0)], + [(6, 4096, raw_tail_parent), (6, 4096, raw_mip1), (8, 16384, zlib_mip0_parent)], ) - docs = _build_history(pool, work) + _write_custom_rds5_pool( + pools_dir / "bc6h-child-refused-mid.ttpf", + [record], + [(8, 4096, zlib_tail_child), (6, 4096, raw_mip1), (6, 16384, raw_mip0_child)], + ) + docs = self._build_history(pools_dir, work) - self.assertEqual(docs["bc6h"]["endpointClass"][91], 1) - decoded = bcpack.decode(raw_mip2, 6, 4096, allow_provisional=True, history=docs) - self.assertEqual(len(decoded), 4096) + for slot, expected_sw in ((200, sw_parent), (212, sw_child)): + self.assertEqual(docs["bc6h"]["endpointClass"][slot], 1) + self.assertEqual(docs["bc6h"]["endpointConfirmedBits"][slot], [[0, 0, 0, 0]] * 3) + for c in range(3): + self.assertLessEqual(abs(docs["bc6h"]["endpointHistory"][slot][c][0] - expected_sw[c]), 8) + + decoded_parent = bcpack.decode(raw_tail_parent, 6, 4096, allow_provisional=True, history=docs) + self.assertEqual(len(decoded_parent), 4096) + exp_parent = history.calib.decode_bc6h_block_unq(solid_parent, 0)[0] + for blk in range(256): + px = history.calib.decode_bc6h_block_unq(decoded_parent, blk * 16)[0] + for c in range(3): + self.assertLessEqual(abs(px[c] - exp_parent[c]), 64.0, f"parent blk {blk} ch {c}") + + decoded_child = bcpack.decode(raw_mip0_child, 6, 16384, allow_provisional=True, history=docs) + self.assertEqual(len(decoded_child), 16384) + exp_child = history.calib.decode_bc6h_block_unq(solid_child, 0)[0] + for blk in range(1024): + px = history.calib.decode_bc6h_block_unq(decoded_child, blk * 16)[0] + for c in range(3): + self.assertLessEqual(abs(px[c] - exp_child[c]), 64.0, f"child blk {blk} ch {c}") if __name__ == "__main__": diff --git a/tools/build_dstorage_history.py b/tools/build_dstorage_history.py index b01df687c0..1d221c6149 100644 --- a/tools/build_dstorage_history.py +++ b/tools/build_dstorage_history.py @@ -195,7 +195,7 @@ def fit_distant_mips(pools, docs): prefix = calib.decode_lanes_prefix( pool.data[offset:offset + packed], mode, size, pblocks * 2) if _chunk_needs_missing_slot(mode, prefix, pblocks, docs, static_bc7): - wanted.add((offset, packed)) + wanted.add((offset, packed, mode)) lanes_cache[(offset, packed, pblocks)] = prefix if not wanted: continue @@ -243,7 +243,7 @@ def address(m): needy_chunks = [ (size, offset, packed, virt - start, min(4096, size // 16)) for virt, size, offset, packed, mode, _ in pool.chunks_for(start, mip["region"]) - if mode == codec and (offset, packed) in wanted and start - virt < 4096 * 16 + if mode == codec and (offset, packed, mode) in wanted and start - virt < 4096 * 16 ] if not needy_chunks: continue From 656cfa15e3de63590a4e5a303c792cd122ccb54a Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sat, 28 Nov 2026 19:35:42 +0200 Subject: [PATCH 24/42] d3d12: mesh programs translate as compute on a host without mesh shaders (D3D12-MESH-COMPUTE-FALLBACK) set_host_mesh_shaders(false) lowers a mesh program as cs_6_6. setMeshOutputCounts goes. emitIndices, storeVertexOutput and storePrimitiveOutput become raw stores into the root UAV SLOT_MESH_OUT (251), in the group's MeshOut slot: max_vertices vertices, then max_primitives primitives (three indices, then the per-primitive outputs). - The buffer is MESH_OUT_BYTES (64 MiB). A 256-byte header holds a draw's arguments: lane 0 of each group raises its instance count to the group id + 1, so an indirect dispatch's draw needs no CPU read. - Groups past MeshOut::groups_cap write to one sink slot after the last. - mesh_vs() builds the pass-through vertex shader that draws it. SV_VertexID gives primitive and corner, SV_InstanceID the group. It reads the root SRV SLOT_MESH_IN (250) and outputs the program's vertex outputs register for register, plus the per-primitive outputs where the pixel shader reads them, constant. A group past the cap draws a triangle of no area. - HostShader carries the layout and the signatures, and the shader cache encodes them. host_settings() has a word for it, so a translation for one kind of host never serves the other. Tests: the triangle mesh fixture translates as compute (layout, root UAV, empty output signature; dxil.dll takes it for plain, edge-flagged and culled primitives) and stays a mesh shader with mesh shaders. Its vertex shader validates. On a device, the program run as compute and drawn lights the texels the mesh pipeline lights, compared texel for texel where the device has mesh shaders. The test harness gets a root UAV for dispatches, root SRVs in draws and a vertex count. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/shader_cache.rs | 58 ++++- .../leonida-shader/src/emit/diff_tests.rs | 2 + d3d12/crates/leonida-shader/src/emit/host.rs | 52 +++- .../src/emit/intersect_tests.rs | 3 + d3d12/crates/leonida-shader/src/emit/lower.rs | 225 +++++++++++++++-- .../crates/leonida-shader/src/emit/mesh_vs.rs | 206 +++++++++++++++ d3d12/crates/leonida-shader/src/emit/mod.rs | 234 +++++++++++++++++- .../leonida-shader/src/emit/pack_tests.rs | 2 + .../leonida-shader/src/emit/permlane_tests.rs | 2 + .../leonida-shader/src/emit/probe_tests.rs | 1 + d3d12/crates/leonida-shader/src/emit/rect.rs | 2 + .../crates/leonida-shader/src/emit/shader.rs | 89 +++++++ .../leonida-shader/src/emit/size_tests.rs | 2 + .../leonida-shader/src/emit/valu_tests.rs | 6 + .../src/emit/waterfall_tests.rs | 4 + .../leonida-shader/src/emit/wave64_tests.rs | 7 + 16 files changed, 871 insertions(+), 24 deletions(-) create mode 100644 d3d12/crates/leonida-shader/src/emit/mesh_vs.rs diff --git a/d3d12/crates/leonida-gpu/src/shader_cache.rs b/d3d12/crates/leonida-gpu/src/shader_cache.rs index 82481d0034..bf136a117c 100644 --- a/d3d12/crates/leonida-gpu/src/shader_cache.rs +++ b/d3d12/crates/leonida-gpu/src/shader_cache.rs @@ -218,7 +218,7 @@ fn paired_override(container: &[u8], mut shader: HostShader) -> HostShader { let Some(dir) = DIR.get_or_init(|| std::env::var_os("LEONIDA_PAIRED_SHADER_DIR").map(PathBuf::from)) else { return shader; }; - if shader.stage != HwStage::Cs || leonida_shader::emit::host_settings() != [32, 999_999, 0, 0] { + if shader.stage != HwStage::Cs || leonida_shader::emit::host_settings() != [32, 999_999, 0, 0, 0] { return shader; } let digest = blake3::hash(container).to_hex(); @@ -397,6 +397,26 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, u32::from(slot)); word(&mut out, dword); } + // A mesh program lowered as compute: its output layout (0: none). + match &s.mesh_out { + None => word(&mut out, 0), + Some(m) => { + word(&mut out, 1); + for value in [m.max_vertices, m.max_primitives, m.vertex_stride, m.primitive_stride] { + word(&mut out, value); + } + for at in [&m.vertex_at, &m.primitive_at] { + word(&mut out, at.len() as u32); + for &offset in at { + word(&mut out, offset); + } + } + for part in [&m.osg1, &m.psg1] { + word(&mut out, part.len() as u32); + out.extend_from_slice(part); + } + } + } out } @@ -470,6 +490,30 @@ fn decode(bytes: &[u8]) -> Option { for _ in 0..n { half_views.push((u8::try_from(r.word()?).ok()?, r.word()?)); } + let mesh_out = match r.word()? { + 0 => None, + 1 => { + let [max_vertices, max_primitives, vertex_stride, primitive_stride] = + [r.word()?, r.word()?, r.word()?, r.word()?]; + let mut offsets = || -> Option> { + let n = r.word()? as usize; + (0..n.min(1024)).map(|_| r.word()).collect() + }; + let (vertex_at, primitive_at) = (offsets()?, offsets()?); + let (osg1, psg1) = (r.list()?, r.list()?); + Some(leonida_shader::emit::MeshOut { + max_vertices, + max_primitives, + vertex_stride, + primitive_stride, + vertex_at, + primitive_at, + osg1, + psg1, + }) + } + _ => return None, + }; r.0.is_empty().then_some(HostShader { stage, dxil, @@ -481,6 +525,7 @@ fn decode(bytes: &[u8]) -> Option { root_uavs, root_indexed_views, half_views, + mesh_out, }) } @@ -543,6 +588,17 @@ mod tests { shift: 5, }], half_views: vec![(0, 8), (4, 0)], + // A mesh program's output layout survives the round trip. + mesh_out: Some(leonida_shader::emit::MeshOut { + max_vertices: 64, + max_primitives: 126, + vertex_stride: 32, + primitive_stride: 16, + vertex_at: vec![0, 16], + primitive_at: vec![12], + osg1: b"OSG1 part".to_vec(), + psg1: Vec::new(), + }), } } diff --git a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs index b870750dc7..f0094ad7b2 100644 --- a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs @@ -773,6 +773,7 @@ fn translated_shaders_draw_as_pc_ones() { stride: 24, size: (16, 16), mesh_groups: 0, + vertex_count: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); @@ -895,6 +896,7 @@ fn translated_mesh_shaders_draw_as_pc_ones() { stride: 0, size: (16, 16), mesh_groups, + vertex_count: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 1ee50a3aeb..103d46cc9c 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -613,6 +613,7 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, } } @@ -631,6 +632,9 @@ pub enum Root { srv: bool, data: Vec, }, + /// A root UAV over a raw buffer of this many dwords, zeroed + /// ([`Host::dispatch`] only; its contents come after the heap's UAVs). + Uav(u32), } /// Bindings for [`Host::draw`]: root arguments and the heap contents. @@ -647,6 +651,8 @@ pub struct Draw<'a> { pub size: (u32, u32), /// Mesh thread groups to dispatch instead of drawing (0: draw). pub mesh_groups: u32, + /// Vertices drawn (0: three, one triangle). + pub vertex_count: u32, } #[cfg(test)] @@ -868,7 +874,33 @@ impl Host { at.ptr += (index * size) as u64; list.SetGraphicsRootDescriptorTable(*param, at); } - Root::View { .. } => return Err("root views in a draw".into()), + Root::View { srv: true, data } => { + let bytes = (data.len() * 4).next_multiple_of(256) as u64; + let b = make( + D3D12_HEAP_TYPE_UPLOAD, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping(data.as_ptr(), p.cast::(), data.len()); + b.Unmap(0, None); + list.SetGraphicsRootShaderResourceView(*param, b.GetGPUVirtualAddress()); + keep.push(b); + } + Root::View { .. } | Root::Uav(_) => { + return Err("a root CBV or UAV in a draw".into()); + } } } list.OMSetRenderTargets(1, Some(&rtv), false, None); @@ -898,7 +930,8 @@ impl Host { let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(err)?; list6.DispatchMesh(d.mesh_groups, 1, 1); } else { - list.DrawInstanced(3, 1, 0, 0); + let count = if d.vertex_count == 0 { 3 } else { d.vertex_count }; + list.DrawInstanced(count, 1, 0, 0); } list.ResourceBarrier(&[transition( &target, @@ -1476,6 +1509,21 @@ impl Host { } keep.push(b); } + Root::Uav(n) => { + let bytes = u64::from(*n) * 4; + let b = make( + D3D12_HEAP_TYPE_DEFAULT, + &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + )?; + list.SetComputeRootUnorderedAccessView(*param, b.GetGPUVirtualAddress()); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((b, None, *n, rb)); + } } } let [x, y, z] = d.groups; diff --git a/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs b/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs index 91143f6457..c296573b4a 100644 --- a/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/intersect_tests.rs @@ -183,6 +183,7 @@ pub(super) fn build_compute_shader( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, })?; let shader = HostShader { stage: HwStage::Cs, @@ -195,6 +196,7 @@ pub(super) fn build_compute_shader( root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -693,6 +695,7 @@ fn a_structure_that_returns_triangle_ids_is_refused_by_name() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); match r { Err(ShaderError::Unsupported { what, .. }) => { diff --git a/d3d12/crates/leonida-shader/src/emit/lower.rs b/d3d12/crates/leonida-shader/src/emit/lower.rs index 895edceca4..a897d21c34 100644 --- a/d3d12/crates/leonida-shader/src/emit/lower.rs +++ b/d3d12/crates/leonida-shader/src/emit/lower.rs @@ -61,6 +61,8 @@ enum Val { pub(crate) struct Lowered { pub dxil: Vec, + /// A mesh program lowered as compute: where its outputs went. + pub mesh_out: Option, /// Bit n: immediate sampler n is a comparison sampler. pub cmp_samplers: u64, pub root_cbvs: Vec, @@ -94,6 +96,10 @@ pub(crate) struct Parts<'a> { pub prims: Vec, /// Mesh: what the group id arrives multiplied by. pub mesh_stride: u32, + /// Mesh: lower the program as compute, its outputs going to + /// [`super::SLOT_MESH_OUT`] ([`super::shader::MeshOut`]): for a host + /// without mesh shaders. + pub mesh_compute: bool, } enum Stop { @@ -427,6 +433,9 @@ struct Lower<'a> { console_lanes: bool, /// Mesh: the thread index in the group (made in the entry block). flat: Option, + /// Mesh as compute: the byte offset of this group's + /// [`super::SLOT_MESH_OUT`] slot (made in the entry block). + mesh_base: Option, /// Mesh: IR blocks whose `s_barrier` is left out. no_barrier: HashSet, /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane @@ -1586,8 +1595,46 @@ fn own_bits_on() -> bool { /// What the translator was told of the host, for a cache's key: the widest /// wave, the view heap's limit, where the raw twins of its views start, and /// what it writes for the console's own hardware. -pub fn host_settings() -> [u32; 4] { - [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views(), host_rdna()] +pub fn host_settings() -> [u32; 5] { + [ + host_max_wave(), + super::shader::view_heap_limit(), + super::shader::raw_views(), + host_rdna(), + u32::from(host_mesh_compute()), + ] +} + +static HOST_MESH_COMPUTE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tells the translator whether the host runs mesh shaders. Without them a +/// mesh program is lowered as compute, its outputs going to +/// [`super::SLOT_MESH_OUT`] for the pass-through vertex shader +/// ([`super::mesh_vs`]) to draw. +pub fn set_host_mesh_shaders(on: bool) { + HOST_MESH_COMPUTE.store(!on, std::sync::atomic::Ordering::Relaxed); +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`host_mesh_compute`], for its thread only. + pub(super) static TEST_MESH_COMPUTE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Whether mesh programs are translated as compute (the host has no mesh +/// shaders, or `LEONIDA_MESH_COMPUTE=1` asked for it): the pipeline side +/// draws them through `mesh_vs`. +pub fn mesh_as_compute() -> bool { + host_mesh_compute() +} + +/// Whether mesh programs are lowered as compute ([`set_host_mesh_shaders`]). +pub(super) fn host_mesh_compute() -> bool { + #[cfg(test)] + if let Some(on) = TEST_MESH_COMPUTE.get() { + return on; + } + HOST_MESH_COMPUTE.load(std::sync::atomic::Ordering::Relaxed) } static HOST_RDNA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -2372,6 +2419,14 @@ impl<'a> Lower<'a> { max_primitives: ms.max_primitives, topology: ms.topology, }); + if x.mesh_compute { + s.mesh_compute = Some(super::shader::MeshOut::new( + ms.max_vertices, + ms.max_primitives, + &s.outputs, + &s.prims, + )); + } // Barriers order the lanes' LDS accesses; the console's // allocation request needs them too, but the host does not. One // lane sends that request, and what it dominates (the path for @@ -2497,6 +2552,7 @@ impl<'a> Lower<'a> { wave_base: None, wave_rank: None, flat: None, + mesh_base: None, no_barrier, fence_only, half_outputs: half_outputs(&x.native.io, &x.outputs), @@ -3295,7 +3351,16 @@ impl<'a> Lower<'a> { let half_views = std::mem::take(&mut self.half_views).into_iter().collect(); let cmp_samplers = self.s.cmp_samplers; let wave_size = self.s.wave_size; + // Mesh as compute: the container is a compute shader's, with no + // output signatures (what they held is in the layout). + let mesh_out = self.s.mesh_compute.take(); + if mesh_out.is_some() { + self.s.mesh = None; + self.s.outputs.clear(); + self.s.prims.clear(); + } Ok(Lowered { + mesh_out, wave_size, cmp_samplers, root_cbvs, @@ -5878,7 +5943,10 @@ impl<'a> Lower<'a> { let fits = |m: super::shader::Mesh| { mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT }; - if !fits(mesh) { + let compute = self.s.mesh_compute.is_some(); + // As compute there is no output limit: the maxima stay the + // program's, as the layout has them. + if !compute && !fits(mesh) { mesh.max_vertices = mesh.max_vertices.min(threads); mesh.max_primitives = mesh.max_primitives.min(threads); // shortcut: outputs past the cap even at the lane count are @@ -5896,9 +5964,29 @@ impl<'a> Lower<'a> { self.s.m.i32(mesh.max_vertices), self.s.m.i32(mesh.max_primitives), ); - self.s - .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + if !compute { + self.s + .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + } let flat = self.mesh_thread(); + if compute { + // Made here, in the entry block, before any guarded block ends + // it: every store below uses them. + self.mesh_base(); + let out = self.s.root_uav_handle(super::SLOT_MESH_OUT); + // Lane 0 raises the header's instance count to the group's id + 1: + // after the dispatch it holds the groups to draw. + let i32t = self.s.t.i32; + let zero = self.s.m.i32(0); + let group = self.s.op(e, "groupId.i32", Attr::ReadNone, i32t, 94, &[zero]); + let one = self.s.m.i32(1); + let count = self.s.m.bin(e, Bin::Add, group, one); + let first = self.s.m.cmp(e, pred::EQ, flat, zero); + let at = self.begin_guarded(Some(first)); + let (code, byte, iu) = (self.s.m.i32(7), self.s.m.i32(4), self.s.m.undef(i32t)); + self.s.op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &[out, code, byte, iu, iu, count]); + self.end_guarded(at, &[]); + } let z = self.s.m.i32(0); // Every primitive of the declared count starts culled, also those // past the lanes (a count of 256 with 128 lanes): lane n culls @@ -5916,14 +6004,18 @@ impl<'a> Lower<'a> { let guard = ((pass + 1) * threads > mesh.max_primitives) .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p)); let at = self.begin_guarded(guard); - self.s.op( - self.cur, - "emitIndices", - Attr::NoUnwind, - void, - 169, - &[index, z, z, z], - ); + if compute { + self.mesh_out_indices(index, [z, z, z]); + } else { + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[index, z, z, z], + ); + } self.end_guarded(at, &[]); } Ok(()) @@ -5948,6 +6040,71 @@ impl<'a> Lower<'a> { f } + /// Mesh as compute: the byte offset of this group's slot in + /// [`super::SLOT_MESH_OUT`] (the host group's x id times the slot size). + fn mesh_base(&mut self) -> V { + if let Some(b) = self.mesh_base { + return b; + } + let m = self.s.mesh_compute.as_ref().expect("mesh as compute"); + let (bytes, cap) = (m.group_bytes(), m.groups_cap()); + let e = self.s.entry; + let zero = self.s.m.i32(0); + let i32t = self.s.t.i32; + let group = self.s.op(e, "groupId.i32", Attr::ReadNone, i32t, 94, &[zero]); + // A group past the cap writes to the slot after the last one. + let cap = self.s.m.i32(cap); + let slot = self.s.op(e, "binary.i32", Attr::ReadNone, i32t, 40, &[group, cap]); + self.s.m.tag(slot, super::bitcode::Tag::Clamp); + let k = self.s.m.i32(bytes); + let b = self.s.m.bin(e, Bin::Mul, slot, k); + let header = self.s.m.i32(super::shader::MESH_OUT_HEADER); + let b = self.s.m.bin(e, Bin::Add, b, header); + self.mesh_base = Some(b); + b + } + + /// Mesh as compute: one dword, `value`, at byte `at` of this group's + /// slot in the current block. + fn mesh_out_store(&mut self, at: V, value: V) { + let base = self.mesh_base(); + let out = self.s.root_uav_handle(super::SLOT_MESH_OUT); + let c = self.cur; + let place = self.s.m.bin(c, Bin::Add, base, at); + let iu = self.s.m.undef(self.s.t.i32); + let (mask, align) = (self.s.m.i8(1), self.s.m.i32(4)); + let void = self.s.t.void; + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[out, place, iu, value, iu, iu, iu, mask, align], + ); + } + + /// Mesh as compute: the byte offset of primitive `index` in the slot. + fn mesh_primitive_at(&mut self, index: V) -> V { + let m = self.s.mesh_compute.as_ref().expect("mesh as compute"); + let (first, stride) = (m.primitives_at(), m.primitive_stride); + let c = self.cur; + let (first, stride) = (self.s.m.i32(first), self.s.m.i32(stride)); + let at = self.s.m.bin(c, Bin::Mul, index, stride); + self.s.m.bin(c, Bin::Add, at, first) + } + + /// Mesh as compute: the three indices of primitive `index`. + fn mesh_out_indices(&mut self, index: V, corners: [V; 3]) { + let at = self.mesh_primitive_at(index); + for (k, v) in corners.into_iter().enumerate() { + let c = self.cur; + let off = self.s.m.i32(4 * k as u32); + let place = self.s.m.bin(c, Bin::Add, at, off); + self.mesh_out_store(place, v); + } + } + /// The console wave size. fn wave(&self) -> u32 { if self.x.native.wave64 { 64 } else { 32 } @@ -13965,6 +14122,30 @@ impl<'a> Lower<'a> { } _ => (".i32", x), }; + let placed = self.s.mesh_compute.as_ref().filter(|_| mesh).map(|layout| { + let element = if primitive { layout.primitive_at[id] } else { layout.vertex_at[id] }; + (element + 4 * u32::from(col), layout.vertex_stride) + }); + if let Some((column, vertex_stride)) = placed { + // As compute: the value's bits at the element's column of + // this lane's vertex or primitive (`x` is the float the + // output takes for `.f32`). + let bits = if suffix == ".f32" { self.as_int(x) } else { x }; + let flat = self.mesh_thread(); + let c = self.cur; + let at = if primitive { + let at = self.mesh_primitive_at(flat); + let off = self.s.m.i32(column); + self.s.m.bin(c, Bin::Add, at, off) + } else { + let stride = self.s.m.i32(vertex_stride); + let at = self.s.m.bin(c, Bin::Mul, flat, stride); + let off = self.s.m.i32(column); + self.s.m.bin(c, Bin::Add, at, off) + }; + self.mesh_out_store(at, bits); + continue; + } let mut args = vec![ self.s.m.i32(id as u32), self.s.m.i32(0), @@ -14035,13 +14216,16 @@ impl<'a> Lower<'a> { } *slot = i; } - let mut args = vec![flat]; - for i in indices { - args.push(self.s.m.select(c, culled, z, i)); + let corners = indices.map(|i| self.s.m.select(c, culled, z, i)); + if self.s.mesh_compute.is_some() { + self.mesh_out_indices(flat, corners); + } else { + let mut args = vec![flat]; + args.extend(corners); + let void = self.s.t.void; + self.s + .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args); } - let void = self.s.t.void; - self.s - .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args); self.end_guarded(at, &[]); Ok(()) } @@ -14606,6 +14790,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + mesh_compute: false, }) .map(|_| ()) } @@ -14656,6 +14841,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + mesh_compute: false, }) } @@ -14826,6 +15012,7 @@ mod tests { outputs: vec![], prims: vec![], mesh_stride: 0, + mesh_compute: false, }).unwrap(); let container = diff --git a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs new file mode 100644 index 0000000000..f570562a30 --- /dev/null +++ b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs @@ -0,0 +1,206 @@ +//! The vertex shader that draws a mesh program run as compute on a host +//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute +//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices, +//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`] +//! in its [`MeshOut`] layout; the draw that follows is a triangle list of +//! `3 * max_primitives` vertices and one instance a group, with this shader +//! in front of the title's pixel shader, reading the same buffer as the root +//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the +//! header's arguments, which the groups wrote.) +//! +//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of +//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own: +//! it draws nothing. A primitive the program culled, or +//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh +//! path. Every corner is its own vertex here, so a per-primitive output is +//! a vertex output with constant interpolation, the same at all three. +//! +//! The outputs are the mesh program's vertex outputs, register for +//! register, and its per-primitive outputs in the registers the pixel +//! shader reads them from (by semantic and index): a mesh pipeline's +//! per-primitive outputs have their own signature, which a vertex shader +//! has not. + +use super::bitcode::{Attr, Bin, Term, V}; +use super::container::SigElement; +use super::shader::{MeshOut, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// The pass-through vertex shader (a DXIL container) for a mesh program +/// translated as compute with `layout`, drawn with the translated pixel +/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one. +pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result, ShaderError> { + let vertex = super::signature(&layout.osg1)?; + let primitive = super::signature(&layout.psg1)?; + let wanted = match ps { + Some(ps) => { + let c = Container::parse(ps)?; + match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + } + } + None => Vec::new(), + }; + build(layout, vertex, &primitive, &wanted) +} + +/// Where an output's value comes from: byte `at` of its vertex (`false`) +/// or of its primitive past the indices (`true`). +struct Source { + primitive: bool, + at: u32, +} + +fn build( + layout: &MeshOut, + vertex: Vec, + primitive: &[SigElement], + ps_inputs: &[SigElement], +) -> Result, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() { + return Err(unsupported("a mesh layout that does not match its signatures")); + } + if vertex.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a mesh vertex output without a register")); + } + if layout.max_primitives == 0 { + return Err(unsupported("a mesh program without primitives")); + } + let mut outputs = Vec::new(); + let mut sources = Vec::new(); + for (e, &at) in vertex.iter().zip(&layout.vertex_at) { + outputs.push(SigElement { + usage: (1 << e.cols) - 1, + ..e.clone() + }); + sources.push(Source { primitive: false, at }); + } + // A per-primitive output goes where the pixel shader reads it; one the + // pixel shader does not read is not drawn with. + for (p, &at) in primitive.iter().zip(&layout.primitive_at) { + let Some(e) = ps_inputs + .iter() + .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some()) + else { + continue; + }; + let clash = outputs.iter().any(|o| { + o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols + }); + if clash || e.cols < p.cols { + return Err(unsupported( + "a per-primitive output whose pixel shader register a vertex output takes", + )); + } + outputs.push(SigElement { + row: e.row, + col: e.col, + interp: 1, + usage: (1 << p.cols) - 1, + ..p.clone() + }); + sources.push(Source { primitive: true, at }); + } + + let mut s = Shader::new(false); + let system = |name: &str, kind, row| SigElement { + name: name.into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)]; + s.outputs = outputs; + let b = s.entry; + let i32t = s.t.i32; + let k = |s: &mut Shader, v: u32| s.m.i32(v); + + // (vertex id, instance id) -> primitive, corner, group. + let input = |s: &mut Shader, n: u32| { + let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)]; + s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args) + }; + let (id, group) = (input(&mut s, 0), input(&mut s, 1)); + let three = k(&mut s, 3); + let prim = s.m.bin(b, Bin::UDiv, id, three); + let corner = s.m.bin(b, Bin::URem, id, three); + // A group past the cap wrote to the sink slot: it draws nothing. + let cap = k(&mut s, layout.groups_cap()); + let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap); + let group = s.op(b, "binary.i32", Attr::ReadNone, i32t, 40, &[group, cap]); + s.m.tag(group, super::bitcode::Tag::Clamp); + + // Byte offsets in the buffer. + let slot = k(&mut s, layout.group_bytes()); + let base = s.m.bin(b, Bin::Mul, group, slot); + let header = k(&mut s, super::shader::MESH_OUT_HEADER); + let base = s.m.bin(b, Bin::Add, base, header); + let (first, pstride) = (k(&mut s, layout.primitives_at()), k(&mut s, layout.primitive_stride)); + let prim_at = s.m.bin(b, Bin::Mul, prim, pstride); + let prim_at = s.m.bin(b, Bin::Add, prim_at, first); + let prim_at = s.m.bin(b, Bin::Add, prim_at, base); + let four = k(&mut s, 4); + let corner_at = s.m.bin(b, Bin::Mul, corner, four); + let index_at = s.m.bin(b, Bin::Add, prim_at, corner_at); + let index = load(&mut s, index_at); + let zero = k(&mut s, 0); + let index = s.m.select(b, past, zero, index); + // An index past the vertices (none is written so) reads vertex 0. + let index = { + let last = k(&mut s, layout.max_vertices.saturating_sub(1)); + let v = s.op(b, "binary.i32", Attr::ReadNone, i32t, 40, &[index, last]); + s.m.tag(v, super::bitcode::Tag::Clamp); + v + }; + let vstride = k(&mut s, layout.vertex_stride); + let vertex_at = s.m.bin(b, Bin::Mul, index, vstride); + let vertex_at = s.m.bin(b, Bin::Add, vertex_at, base); + + for (id, source) in sources.iter().enumerate() { + let (from, cols, float) = { + let e = &s.outputs[id]; + (if source.primitive { prim_at } else { vertex_at }, e.cols, e.comp == 9) + }; + for col in 0..cols { + let off = k(&mut s, source.at + 4 * u32::from(col)); + let at = s.m.bin(b, Bin::Add, from, off); + let bits = load(&mut s, at); + let (name, value) = if float { + let f32t = s.t.f32; + ("storeOutput.f32", s.m.cast(b, super::bitcode::Cast::Bitcast, bits, f32t)) + } else { + ("storeOutput.i32", bits) + }; + let args = [k(&mut s, id as u32), k(&mut s, 0), s.m.i8(col), value]; + s.op(b, name, Attr::NoUnwind, s.t.void, 5, &args); + } + } + s.m.terminate(b, Term::Ret); + Ok(s.finish()) +} + +/// The dword at byte `at` of [`super::SLOT_MESH_IN`], as an i32. +fn load(s: &mut Shader, at: V) -> V { + let b = s.entry; + let handle = s.root_srv_handle(super::SLOT_MESH_IN); + let (undef, mask, align) = (s.m.undef(s.t.i32), s.m.i8(1), s.m.i32(4)); + let r = s.op( + b, + "rawBufferLoad.f32", + Attr::ReadOnly, + s.t.res_ret, + 139, + &[handle, at, undef, mask, align], + ); + let f = s.m.extract(b, r, 0); + s.m.cast(b, super::bitcode::Cast::Bitcast, f, s.t.i32) +} diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 707095287c..28586eff66 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -94,6 +94,7 @@ mod lds_exact; mod lds_flags; mod lds_init; mod lower; +pub mod mesh_vs; mod own_bits; #[cfg(all(test, windows))] mod permlane_tests; @@ -127,10 +128,12 @@ use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; pub use sampler::StaticSampler; -pub use lower::{host_settings, set_host_max_wave, set_host_rdna, take_pack_why}; +pub use lower::{host_settings, mesh_as_compute, set_host_max_wave, set_host_mesh_shaders, set_host_rdna, take_pack_why}; +pub use mesh_vs::mesh_vs; pub use rect::rect_list_gs; pub use shader::{ - MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, MeshOut, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, + MESH_OUT_BYTES, MESH_OUT_HEADER, SLOT_MESH_IN, SLOT_MESH_OUT, SLOT_STRIDES, SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_PACK_GROUPS, USER_PACK_X, USER_PACK_Y, PACK_FOLD, pack_grid, pack_group, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, constant_marks, constants_raw, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; @@ -595,6 +598,10 @@ pub struct HostShader { /// descriptor picked at run time keeps the float path (its slot, and so /// its format, is known only then). pub half_views: Vec<(u8, u32)>, + /// A mesh program lowered as compute ([`set_host_mesh_shaders`]): the + /// shader is `cs_6_6` and writes what its outputs would to the root UAV + /// [`SLOT_MESH_OUT`] in this layout; [`mesh_vs::mesh_vs`] reads it back. + pub mesh_out: Option, } impl HostShader { @@ -1464,6 +1471,7 @@ fn emit_program_plain( outputs, prims, mesh_stride, + mesh_compute: matches!(native.io, crate::native::StageIo::Ms(_)) && lower::host_mesh_compute(), })?; let counted = match early { EarlyDepth::NotAsked => None, @@ -1497,6 +1505,7 @@ fn emit_program_plain( root_uavs: l.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: l.half_views, + mesh_out: l.mesh_out, }; Ok((shader, wave_size)) } @@ -1971,6 +1980,7 @@ mod tests { outputs, prims: vec![], mesh_stride: 0, + mesh_compute: false, }) .unwrap(); let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); @@ -2406,6 +2416,7 @@ mod tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -2419,6 +2430,7 @@ mod tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }) }; let ps = file("LEONIDA_REF_PS", crate::HwStage::Ps).unwrap_or(ps); @@ -2578,6 +2590,7 @@ mod tests { stride: 0, size: (16, 16), mesh_groups: 1, + vertex_count: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2703,6 +2716,75 @@ mod tests { } } + /// On a host without mesh shaders a mesh program translates as compute + /// (`D3D12-MESH-COMPUTE-FALLBACK`): no output signatures, the root UAV + /// [`SLOT_MESH_OUT`], and the layout of its outputs: one position (16 + /// bytes a vertex) and three indices (12 bytes a primitive) for each of + /// its 32 vertices and primitives. dxil.dll, where there is one, takes + /// the module for every primitive export the native path takes. + #[test] + fn a_mesh_program_translates_as_compute_without_mesh_shaders() { + #[cfg(windows)] + let mut validator = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) + .ok(); + super::lower::TEST_MESH_COMPUTE.set(Some(true)); + for prim in [ + TRIANGLE, + TRIANGLE | EDGE_FLAGS, + TRIANGLE | EDGE_FLAGS | CULL, + ] { + let cs = triangle_mesh(prim).unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + let layout = cs.mesh_out.as_ref().unwrap_or_else(|| panic!("{prim:#x}: no layout")); + assert_eq!( + ( + layout.max_vertices, + layout.max_primitives, + layout.vertex_stride, + layout.primitive_stride + ), + (32, 32, 16, 12), + "{prim:#x}" + ); + assert_eq!((&layout.vertex_at[..], &layout.primitive_at[..]), (&[0][..], &[][..]), "{prim:#x}"); + // The mesh program's position, for the pass-through vertex shader. + let position = signature(&layout.osg1).unwrap(); + assert_eq!(position.len(), 1, "{prim:#x}"); + assert_eq!((position[0].kind, position[0].cols), (3, 4), "{prim:#x}"); + assert!(cs.root_uavs.contains(&SLOT_MESH_OUT), "{prim:#x}: {:?}", cs.root_uavs); + let c = Container::parse(&cs.dxil).unwrap(); + // A compute shader's output signature is there and empty. + let outputs = c.part(FourCC::OSG1).map(|p| signature(p.data).unwrap()); + assert_eq!(outputs, Some(vec![]), "{prim:#x}"); + assert!(c.part(FourCC::PSG1).is_none(), "{prim:#x}"); + #[cfg(windows)] + if let Some(v) = validator.as_mut() { + v.validate(&mut cs.dxil.clone()) + .unwrap_or_else(|e| panic!("{prim:#x}: {e}")); + } + } + // Its pass-through vertex shader: SV_VertexID in, the program's + // position out (register for register), and dxil.dll takes it. + let cs = triangle_mesh(TRIANGLE).unwrap(); + let vs = mesh_vs(cs.mesh_out.as_ref().unwrap(), None).unwrap(); + let c = Container::parse(&vs).unwrap(); + let inputs = signature(c.part(FourCC::ISG1).unwrap().data).unwrap(); + assert_eq!(inputs.iter().map(|e| (e.kind, e.comp)).collect::>(), [(1, 5), (2, 5)]); + let outputs = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + assert_eq!(outputs.iter().map(|e| (e.kind, e.row, e.cols)).collect::>(), [(3, Some(0), 4)]); + #[cfg(windows)] + if let Some(v) = validator.as_mut() { + v.validate(&mut vs.clone()).unwrap_or_else(|e| panic!("mesh_vs: {e}")); + } + // The same program on a host with mesh shaders stays one. + super::lower::TEST_MESH_COMPUTE.set(Some(false)); + let ms = triangle_mesh(TRIANGLE).unwrap(); + assert_eq!(ms.mesh_out, None); + assert!(!ms.root_uavs.contains(&SLOT_MESH_OUT)); + super::lower::TEST_MESH_COMPUTE.set(None); + } + /// A triangle mesh program on the host GPU and on WARP (where they have /// mesh shaders): triangle (0, 1, 2) covers the target with its corners' /// edge flags set as without them; with the culling bit, nothing is lit. @@ -2761,6 +2843,7 @@ mod tests { stride: 0, size: (16, 16), mesh_groups: 1, + vertex_count: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2782,6 +2865,145 @@ mod tests { } } + /// `D3D12-MESH-COMPUTE-FALLBACK` on a device: the triangle mesh program + /// run as compute, then drawn as a triangle list with its pass-through + /// vertex shader, lights the texels the mesh pipeline lights (all of + /// them in the pixel shader's colour, none when the program culls its + /// triangle), with or without edge flags. Where the device has mesh + /// shaders the two draws are compared texel for texel; the fallback + /// itself needs none (WARP, or a shader model 6.6 card). + #[test] + #[cfg(windows)] + fn a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws() { + use super::host::{Dispatch, Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FEATURE_D3D12_OPTIONS7, D3D12_FEATURE_DATA_D3D12_OPTIONS7, + D3D12_MESH_SHADER_TIER_NOT_SUPPORTED, D3D12_SHADER_VISIBILITY_ALL, + D3D12_SHADER_VISIBILITY_MESH, D3D12_SHADER_VISIBILITY_VERTEX, + }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let ps = constant_color(); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + // SAFETY: the query writes the structure of the given size. + let queried = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + let mesh_shaders = + queried.is_ok() && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; + let draw = |roots, mesh_groups, vertex_count| Draw { + roots, + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups, + vertex_count, + }; + for (prim, culled) in [ + (TRIANGLE, false), + (TRIANGLE | EDGE_FLAGS, false), + (TRIANGLE | EDGE_FLAGS | CULL, true), + ] { + // The program as compute: its outputs into the root UAV. + super::lower::TEST_MESH_COMPUTE.set(Some(true)); + let cs = triangle_mesh(prim); + super::lower::TEST_MESH_COMPUTE.set(None); + let cs = cs.unwrap(); + let layout = cs.mesh_out.clone().unwrap(); + let root = host + .root_signature_for(&[(&cs, D3D12_SHADER_VISIBILITY_ALL)]) + .unwrap(); + let pso = host + .compute_pipeline_with(&root, &cs.dxil) + .unwrap_or_else(|e| panic!("{label}: compute pipeline: {e}")); + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(vec![0])), + (1, Root::Uav((MESH_OUT_HEADER + layout.group_bytes()) / 4)), + ], + views: &[], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch: {e}")); + let written = out.last().unwrap().clone(); + // Drawn with the pass-through vertex shader. + let vs = mesh_vs(&layout, Some(&ps)).unwrap(); + let vs_shader = HostShader { + stage: HwStage::Vs, + dxil: vs.clone(), + user_data: vec![], + samplers: vec![], + static_samplers: vec![], + root_cbvs: vec![], + root_srvs: vec![SLOT_MESH_IN], + root_uavs: vec![], + root_indexed_views: vec![], + half_views: vec![], + mesh_out: None, + }; + let root = host + .root_signature_for(&[(&vs_shader, D3D12_SHADER_VISIBILITY_VERTEX)]) + .unwrap(); + let pso = host + .pipeline_with(&root, &vs, &ps) + .unwrap_or_else(|e| panic!("{label}: pass-through pipeline: {e}")); + let roots = vec![ + (0, Root::Constants(vec![0])), + (1, Root::View { srv: true, data: written }), + ]; + let texels = host + .draw(&root, &pso, &draw(roots, 0, 3 * layout.max_primitives)) + .unwrap_or_else(|e| panic!("{label}: draw: {e}")); + let lit = texels.iter().filter(|t| t[3] != 0.0).count(); + if culled { + assert_eq!(lit, 0, "{label}, {prim:#x}: a culled triangle lit texels"); + } else { + assert!( + texels.iter().all(|t| *t == [1.0, 0.5, 0.25, 1.0]), + "{label}, {prim:#x}: {lit} of 256 texels lit" + ); + } + if mesh_shaders { + let ms = triangle_mesh(prim).unwrap(); + let root = host + .root_signature_for(&[(&ms, D3D12_SHADER_VISIBILITY_MESH)]) + .unwrap(); + let pso = host + .mesh_pipeline_with(&root, &ms.dxil, &ps) + .unwrap_or_else(|e| panic!("{label}: mesh pipeline: {e}")); + let native = host + .draw(&root, &pso, &draw(vec![(0, Root::Constants(vec![0]))], 1, 0)) + .unwrap_or_else(|e| panic!("{label}: mesh draw: {e}")); + assert_eq!(texels, native, "{label}, {prim:#x}: the fallback and the mesh pipeline differ"); + } + } + eprintln!("{label}: the mesh program drew as compute (mesh shaders there: {mesh_shaders})"); + ran += 1; + } + if ran == 0 { + eprintln!("no SM 6.6 device; skipped"); + } + } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) @@ -3003,6 +3225,7 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap(); // The calls that read the SRV: 28 a dword, 7 with four a call. @@ -3029,6 +3252,7 @@ mod tests { root_uavs: l.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); // Twelve dwords: the loads below run across the view's end. @@ -3132,6 +3356,7 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap(); super::shader::CONSTANTS_RAW_HERE.set(None); @@ -3165,6 +3390,7 @@ mod tests { root_uavs: l.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let views: Vec = if raw { @@ -3291,6 +3517,7 @@ mod tests { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap(); let mut dxil = l.dxil; @@ -3313,6 +3540,7 @@ mod tests { root_uavs: l.root_uavs, root_indexed_views: Vec::new(), half_views: l.half_views, + mesh_out: None, }; let (root, pso) = host.compute_pipeline(&cs).unwrap(); let inputs: Vec = [ @@ -3751,6 +3979,7 @@ mod barycentric_tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; validate(&vs); // One triangle covers an 8x8 target, with attribute values 2, 6, 10. @@ -3793,6 +4022,7 @@ mod barycentric_tests { stride: 32, size: (8, 8), mesh_groups: 0, + vertex_count: 0, }, ) .expect("draw partial interpolation"); diff --git a/d3d12/crates/leonida-shader/src/emit/pack_tests.rs b/d3d12/crates/leonida-shader/src/emit/pack_tests.rs index 2fa7f2275d..7ae9836689 100644 --- a/d3d12/crates/leonida-shader/src/emit/pack_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/pack_tests.rs @@ -152,6 +152,7 @@ fn translate(native: &NativeProgram, k: u32) -> Result outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_GROUP_PACK.set(packing); lower::TEST_HOST_WAVE.set(was); @@ -167,6 +168,7 @@ fn translate(native: &NativeProgram, k: u32) -> Result root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs b/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs index a72b559d9f..86edb1d087 100644 --- a/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/permlane_tests.rs @@ -93,6 +93,7 @@ fn lowered(native: &NativeProgram, host_wave: u32) -> Result Result { diff --git a/d3d12/crates/leonida-shader/src/emit/probe_tests.rs b/d3d12/crates/leonida-shader/src/emit/probe_tests.rs index b8fc775334..28413aa1d3 100644 --- a/d3d12/crates/leonida-shader/src/emit/probe_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/probe_tests.rs @@ -35,6 +35,7 @@ fn probe() { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; let (root, pso) = match host.compute_pipeline(&shader) { Ok(made) => made, diff --git a/d3d12/crates/leonida-shader/src/emit/rect.rs b/d3d12/crates/leonida-shader/src/emit/rect.rs index ba2f4b9a05..983bc4c07b 100644 --- a/d3d12/crates/leonida-shader/src/emit/rect.rs +++ b/d3d12/crates/leonida-shader/src/emit/rect.rs @@ -416,6 +416,7 @@ mod tests { root_uavs: Vec::new(), root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; ( host(crate::native::HwStage::Vs, vs), @@ -465,6 +466,7 @@ mod tests { stride: 32, size: (8, 8), mesh_groups: 0, + vertex_count: 0, }; host.draw(&root, &pso, &d).unwrap() }; diff --git a/d3d12/crates/leonida-shader/src/emit/shader.rs b/d3d12/crates/leonida-shader/src/emit/shader.rs index 2255f9ecdc..4ca71e678b 100644 --- a/d3d12/crates/leonida-shader/src/emit/shader.rs +++ b/d3d12/crates/leonida-shader/src/emit/shader.rs @@ -80,6 +80,22 @@ pub fn constant_marks() -> bool { pub const SLOT_MEMORY: u8 = 254; /// See [`SLOT_MEMORY`]. pub const SLOT_FAULTS: u8 = 253; +/// A mesh program translated as compute (the host has no mesh shaders): the +/// root UAV `u` takes what the mesh outputs would, one +/// [`MeshOut`] slot per group, for the pass-through vertex shader +/// (`mesh_vs.rs`) to read back as the root SRV `t`. +pub const SLOT_MESH_OUT: u8 = 251; +/// See [`SLOT_MESH_OUT`]. +pub const SLOT_MESH_IN: u8 = 250; +/// Bytes of the [`SLOT_MESH_OUT`] buffer: the header, then the groups' +/// slots ([`MeshOut::groups_cap`] of them and one more, where groups past +/// the cap write). +pub const MESH_OUT_BYTES: u32 = 64 << 20; +/// Bytes before the first group's slot: the draw arguments of the groups +/// written (`D3D12_DRAW_ARGUMENTS`: the host writes `3 * max_primitives` +/// to dword 0 and zero to dword 1 before a dispatch; each group raises +/// dword 1 to its id + 1, so it holds the group count for an indirect draw). +pub const MESH_OUT_HEADER: u32 = 256; /// Entries of the [`SLOT_MEMORY`] directory: title addresses below 128 GiB. pub const MEMORY_PAGES: u32 = 1 << 21; /// In a directory entry's first dword: shaders do not store there by address @@ -214,6 +230,74 @@ pub(crate) struct Mesh { pub topology: u8, } +/// Where a mesh program lowered as compute ([`SLOT_MESH_OUT`]) puts what +/// its outputs would hold, in bytes from the start of its group's slot: +/// `max_vertices` vertices of `vertex_stride` bytes, then `max_primitives` +/// primitives of `primitive_stride` bytes (three indices, then the +/// per-primitive outputs). Each output element takes one dword per +/// column, in signature order (`vertex_at`, `primitive_at`). The +/// pass-through vertex shader (`mesh_vs.rs`) reads the same layout. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshOut { + pub max_vertices: u32, + pub max_primitives: u32, + pub vertex_stride: u32, + pub primitive_stride: u32, + /// Byte offset of each vertex output element (OSG1 order). + pub vertex_at: Vec, + /// Byte offset of each per-primitive output element (PSG1 order), + /// past the three indices. + pub primitive_at: Vec, + /// The mesh program's vertex outputs as an `OSG1` part, and its + /// per-primitive outputs as a `PSG1` part: what the pass-through vertex + /// shader outputs. + pub osg1: Vec, + pub psg1: Vec, +} + +impl MeshOut { + /// The layout for these maxima and signatures. + pub fn new(max_vertices: u32, max_primitives: u32, outputs: &[SigElement], prims: &[SigElement]) -> Self { + let place = |first: u32, elements: &[SigElement]| { + let mut at = Vec::with_capacity(elements.len()); + let mut next = first; + for e in elements { + at.push(next); + next += 4 * u32::from(e.cols); + } + (at, next) + }; + let (vertex_at, vertex_stride) = place(0, outputs); + let (primitive_at, primitive_stride) = place(12, prims); + MeshOut { + max_vertices, + max_primitives, + vertex_stride, + primitive_stride, + vertex_at, + primitive_at, + osg1: super::container::signature(outputs, false), + psg1: super::container::signature(prims, false), + } + } + + /// Bytes of one group's slot. + pub fn group_bytes(&self) -> u32 { + self.max_vertices * self.vertex_stride + self.max_primitives * self.primitive_stride + } + + /// Groups with a slot of their own in [`MESH_OUT_BYTES`]; one more slot + /// takes the writes of every group past them (which draw nothing). + pub fn groups_cap(&self) -> u32 { + ((MESH_OUT_BYTES - MESH_OUT_HEADER) / self.group_bytes().max(4)).saturating_sub(1).max(1) + } + + /// Byte offset of primitive 0 in a group's slot. + pub fn primitives_at(&self) -> u32 { + self.max_vertices * self.vertex_stride + } +} + /// What a geometry shader declares: triangles in, triangle strips out on /// stream 0, one instance. #[derive(Debug, Clone, Copy)] @@ -304,6 +388,10 @@ pub(crate) struct Shader { pub prims: Vec, /// A mesh shader (`threads` is its thread-group size). pub mesh: Option, + /// The mesh program is lowered as compute: the outputs go to + /// [`SLOT_MESH_OUT`] in this layout (`mesh` stays set while lowering and + /// is cleared before [`Shader::finish`]). + pub mesh_compute: Option, /// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false. pub geometry: Option, /// Dwords of user data the shader reads (0: no user-data buffer). @@ -368,6 +456,7 @@ impl Shader { outputs: Vec::new(), prims: Vec::new(), mesh: None, + mesh_compute: None, geometry: None, user_data: 0, samplers: 0, diff --git a/d3d12/crates/leonida-shader/src/emit/size_tests.rs b/d3d12/crates/leonida-shader/src/emit/size_tests.rs index 9cba89a92f..300fffe28c 100644 --- a/d3d12/crates/leonida-shader/src/emit/size_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/size_tests.rs @@ -62,6 +62,7 @@ fn build(words: &[u32], srv: (u8, u32)) -> Result { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, })?; let shader = HostShader { stage: HwStage::Cs, @@ -74,6 +75,7 @@ fn build(words: &[u32], srv: (u8, u32)) -> Result { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) diff --git a/d3d12/crates/leonida-shader/src/emit/valu_tests.rs b/d3d12/crates/leonida-shader/src/emit/valu_tests.rs index 4f10e95e9b..3a21bdec14 100644 --- a/d3d12/crates/leonida-shader/src/emit/valu_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/valu_tests.rs @@ -168,6 +168,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); @@ -182,6 +183,7 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -1954,6 +1956,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); @@ -1968,6 +1971,7 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -2166,6 +2170,7 @@ fn build_table_typed_cs(body: &[u32], used: Vec) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); let shader = HostShader { @@ -2179,6 +2184,7 @@ fn build_table_typed_cs(body: &[u32], used: Vec) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); diff --git a/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs b/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs index b25f684e94..a0d76ba95a 100644 --- a/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/waterfall_tests.rs @@ -69,6 +69,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .expect("lower"); // One access with each lane's own heap index, no wave operation. @@ -85,6 +86,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()) @@ -369,6 +371,7 @@ fn immediate_sampler_chosen_by_control_flow() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }) .unwrap_or_else(|e| panic!("{case_name}: lower failed: {e}")); @@ -388,6 +391,7 @@ fn immediate_sampler_chosen_by_control_flow() { root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), half_views: Vec::new(), + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) diff --git a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs index 309dc48eb2..5f5247409e 100644 --- a/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/wave64_tests.rs @@ -129,6 +129,7 @@ fn lowered_counted( outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }, counted); lower::TEST_HOST_WAVE.set(was); let lowered = lowered?; @@ -143,6 +144,7 @@ fn lowered_counted( root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: lowered.half_views, + mesh_out: None, }) } @@ -268,6 +270,7 @@ fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_HOST_WAVE.set(was); let lowered = lowered.expect("lower"); @@ -283,6 +286,7 @@ fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, half_views: Vec::new(), + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -1010,6 +1014,7 @@ fn flag_wave(native: &NativeProgram) -> Option { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_HOST_WAVE.set(was); lowered.expect("lower").wave_size @@ -1353,6 +1358,7 @@ fn partial_dispatch_with_a_cross_half_wave_op_runs_in_32_lane_waves() { outputs: Vec::new(), prims: Vec::new(), mesh_stride: 0, + mesh_compute: false, }); lower::TEST_HOST_WAVE.set(was); let lowered = lowered.unwrap_or_else(|e| panic!("lower: {e}")); @@ -1374,6 +1380,7 @@ fn partial_dispatch_with_a_cross_half_wave_op_runs_in_32_lane_waves() { root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views.clone(), half_views: lowered.half_views, + mesh_out: None, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { v.validate(&mut shader.dxil.clone()).unwrap_or_else(|e| panic!("DXIL validation: {e}")); From dc5818bb8424d96b642ba07cd03a3251d529a147 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sat, 28 Nov 2026 19:35:42 +0200 Subject: [PATCH 25/42] d3d12: mesh pipelines draw through compute and a triangle list without mesh shaders At device creation the translator is told whether the host has mesh shaders at shader model 6.6 (LEONIDA_MESH_COMPUTE=1 takes the fallback on any card). Without them, a mesh pipeline is made as two: - the mesh program as a compute pipeline; - the pass-through vertex shader with the title's pixel shader and state, drawing triangle lists with no vertex input. The draw path: - A mesh dispatch binds the compute pipeline with the title's graphics root arguments (roots_ref reads them while title_side_graphics is set). - It dispatches and draws 3 * max_primitives vertices, one instance a group. - An indirect one writes the header's draw arguments (WriteBufferImmediate), runs the title's record with a dispatch signature, and draws from the header with ExecuteIndirect. - The buffer goes common -> UAV -> shader resource and indirect argument -> common. shortcut: an indirect call of several records is left out (each would fill the same slots). MEASURED on a GTX 1050 Ti (Pascal: mesh shader tier 0), Windows 10 with #2557: the title gets past its start screen through the opening cutscenes into the first playable scene. Without this, every mesh pipeline was refused and the world drew nothing. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 211 +++++++++++++++++- d3d12/crates/leonida-gpu/src/host.rs | 18 ++ d3d12/crates/leonida-gpu/src/pipeline.rs | 63 ++++++ d3d12/crates/leonida-gpu/src/pipeline/host.rs | 76 ++++++- 4 files changed, 366 insertions(+), 2 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index d729e65cad..8381f99392 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -67,6 +67,22 @@ fn is_depth_companion(stencil: &View, depth: &View) -> bool { && s[7] == d[7] } +/// The device-local buffer mesh programs run as compute write to +/// ([`leonida_shader::emit::MESH_OUT_BYTES`], made once; it starts and ends +/// each use in the common state). +fn mesh_buffer() -> Option { + static BUFFER: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut held = BUFFER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(b) = held.as_ref() { + return Some(b.clone()); + } + let size = u64::from(leonida_shader::emit::MESH_OUT_BYTES); + let b = crate::host::host()?.uav_buffer(size)?; + tracing::info!(mib = size >> 20, "mesh buffer (mesh programs run as compute)"); + *held = Some(b.clone()); + Some(b) +} + /// Shader interface metadata shared by every pipeline variant and draw. pub(crate) struct TablePlan { groups: Vec, @@ -980,6 +996,10 @@ pub(crate) struct State { heaps: [usize; 2], graphics: Vec, compute: Vec, + /// While a mesh program runs as compute (`D3D12-MESH-COMPUTE-FALLBACK`): + /// its root arguments are the title's graphics ones, bound on the + /// compute side. + title_side_graphics: bool, vertex: [VertexView; 32], index: IndexView, /// Bound render target and depth resources, for their host states. @@ -2694,6 +2714,10 @@ impl State { } for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { for (at, &(slot, param)) in views.iter().enumerate() { + if srv && slot == leonida_shader::emit::SLOT_MESH_IN { + // Ours: the mesh buffer, bound by `mesh_as_compute`. + continue; + } if srv && slot == leonida_shader::emit::SLOT_MEMORY { // Ours: the directory of title memory by address. if let Some(m) = &memory { @@ -2763,6 +2787,10 @@ impl State { } } for &(slot, param) in &stage.root_uavs { + if slot == leonida_shader::emit::SLOT_MESH_OUT { + // Ours: the mesh buffer, bound by `mesh_as_compute`. + continue; + } if slot == leonida_shader::emit::SLOT_FAULTS { // Ours: where shaders note the pages they found empty. if let Some(m) = &memory { @@ -4619,6 +4647,148 @@ impl State { ) } + /// `D3D12-MESH-COMPUTE-FALLBACK`: `x` groups of a mesh pipeline on a host + /// without mesh shaders. The mesh program runs as compute with the + /// title's graphics root arguments, writing each group's outputs to the + /// mesh buffer; the pipeline then draws them as a triangle list of + /// `x * max_primitives * 3` vertices through its pass-through vertex + /// shader. The buffer starts and ends each use in the common state, so + /// every list finds it there. + fn mesh_as_compute(&mut self, list: &HostList, x: u32, p: &crate::pipeline::host::HostPipeline) -> bool { + let Some(mc) = p.mesh_compute.as_deref() else { + return false; + }; + // Groups past the buffer's slots (`MeshOut::groups_cap`) draw nothing. + if x > mc.layout.groups_cap() { + once!(x, cap = mc.layout.groups_cap(), "a mesh dispatch of more groups than the mesh buffer holds: the rest draw nothing"); + } + let n = x.min(65_535); + if n == 0 { + return true; + } + let Some(buffer) = mesh_buffer() else { + once!("no mesh buffer: the mesh draw is dropped"); + return false; + }; + let l = &list.list; + self.title_side_graphics = true; + let bound = self.bind(list, &mc.cs, true); + self.title_side_graphics = false; + if !bound { + return false; + } + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }; + // SAFETY: an open list, a live buffer and the compute pipeline bound. + unsafe { + l.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + l.SetComputeRootUnorderedAccessView(mc.out_param, buffer.GetGPUVirtualAddress()); + l.Dispatch(n, 1, 1); + l.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + // The compute pipeline took the list's pipeline slot. + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.mesh_scissor(list, true); + l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); + l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.DrawInstanced(mc.layout.max_primitives * 3, n, 0, 0); + self.mesh_scissor(list, false); + } + l.ResourceBarrier(&[crate::host::transition( + &buffer, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + list.keep(&buffer); + drawn + } + + /// [`Self::mesh_as_compute`] for one indirect record: the record's + /// `(x, y, z)` is a dispatch's arguments as it stands (`stride` apart), + /// so the compute pipeline runs it as recorded; its groups raise the + /// buffer header's instance count, and the draw reads the header's + /// arguments (`3 * max_primitives` vertices, one instance a group). + fn mesh_indirect_as_compute( + &mut self, + list: &HostList, + p: &crate::pipeline::host::HostPipeline, + (arguments, at, stride): (&ID3D12Resource, u64, u32), + count: Option<(&ID3D12Resource, u64)>, + ) -> bool { + let Some(mc) = p.mesh_compute.as_deref() else { + return false; + }; + let (Some(dispatch), Some(draw)) = (host_signature(2, stride), host_signature(0, 16)) else { + return false; + }; + let Some(buffer) = mesh_buffer() else { + once!("no mesh buffer: the mesh draw is dropped"); + return false; + }; + let Ok(l2) = list.list.cast::() else { + return false; + }; + self.title_side_graphics = true; + let bound = self.bind(list, &mc.cs, true); + self.title_side_graphics = false; + if !bound { + return false; + } + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, + }; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + let l = &list.list; + // SAFETY: an open list, live buffers and the compute pipeline bound. + unsafe { + let va = buffer.GetGPUVirtualAddress(); + l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let header = [mc.layout.max_primitives * 3, 0, 0, 0].map(|v| v); + let params: Vec = header + .iter() + .enumerate() + .map(|(k, &value)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: va + 4 * k as u64, Value: value }) + .collect(); + l2.WriteBufferImmediate(params.len() as u32, params.as_ptr(), None); + l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.SetComputeRootUnorderedAccessView(mc.out_param, va); + l.ExecuteIndirect(&dispatch, 1, arguments, at, count.map(|c| c.0), count.map_or(0, |c| c.1)); + l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, read)]); + } + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.mesh_scissor(list, true); + l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); + l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + l.ExecuteIndirect(&draw, 1, &buffer, 0, None, 0); + self.mesh_scissor(list, false); + } + l.ResourceBarrier(&[crate::host::transition(&buffer, read, D3D12_RESOURCE_STATE_COMMON)]); + } + list.keep(&buffer); + drawn + } + /// A mesh draw under `LEONIDA_MESH_TEST=scissor` rasterises one pixel: /// the scissors before it (`on`), the title's after it. fn mesh_scissor(&self, list: &HostList, on: bool) { @@ -4645,6 +4815,20 @@ impl State { crate::drops::begin(); crate::drops::note(Why::SkipList); } + // Without mesh shaders: the program as compute, its output drawn. + let fallback = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + .filter(|p| p.mesh_compute.is_some()); + if let Some(p) = fallback { + let ran = !held && self.mesh_as_compute(list, x, p); + if ran { + self.drew(Some(p)); + DRAWN.fetch_add(1, Ordering::Relaxed); + } else { + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::drops::count_noted(Kind::Draw, Why::Other); + } + return; + } let ran = !held && self.prepare_for(list, false, true) && match list.list.cast::() { @@ -4747,7 +4931,7 @@ impl State { } fn roots_ref(&self, compute: bool) -> &Vec { - if compute { + if compute && !self.title_side_graphics { &self.compute } else { &self.graphics @@ -5681,6 +5865,19 @@ impl State { )); return false; } + // `D3D12-MESH-COMPUTE-FALLBACK`: the pipeline is a compute and a + // graphics one, not a mesh pipeline, so the title's indirect mesh + // dispatch cannot run as recorded (the host loses the device when it + // is: 2026-11-28, GTX 1050 Ti). + // So it runs as compute and a draw (`mesh_indirect_as_compute`), one + // record at a time. + // shortcut: several records a call (each would fill the same slots) + // are left out. + if kind == MESH && p.mesh_compute.is_some() && max != 1 { + once!(max, "an indirect mesh dispatch of several records without mesh shaders is left out"); + why("an indirect mesh dispatch of several records without mesh shaders"); + return false; + } // A program run several console groups to a host group takes the console's grid from // root constants the records carry (`crate::indirect::bound_packed`). if kind == DISPATCH && pack_broken(p) { @@ -5820,6 +6017,18 @@ impl State { (bounded, 0) } }; + if kind == MESH && p.mesh_compute.is_some() { + let counted = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + let ran = self.mesh_indirect_as_compute(list, p, (&bounded, at, stride), counted); + if ran { + self.drew(Some(p)); + DRAWN.fetch_add(1, Ordering::Relaxed); + } else { + crate::drops::note(Why::BindFailed); + why("the mesh program as compute did not run"); + } + return ran; + } let ran = match kind { DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 41a90d743f..c5d47593d6 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1191,6 +1191,24 @@ fn create() -> windows::core::Result { let amd = crate::indirect::amd(&device); leonida_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64); } + // `D3D12-MESH-COMPUTE-FALLBACK`: without mesh shaders at shader model 6.6 (Pascal and older) the + // translator writes mesh programs as compute, drawn through a vertex shader of ours + // (`pipeline::host::MeshCompute`). `LEONIDA_MESH_COMPUTE=1` takes that path on any card. + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + let mesh = device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, (&raw mut o7).cast(), size_of_val(&o7) as u32) + .is_ok() + && device + .CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, (&raw mut model).cast(), size_of_val(&model) as u32) + .is_ok() + && o7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + let forced = std::env::var_os("LEONIDA_MESH_COMPUTE").is_some_and(|v| v == "1"); + leonida_shader::emit::set_host_mesh_shaders(mesh && !forced); + tracing::info!(mesh, forced, "mesh programs run as compute: {}", !mesh || forced); let messages = debug .then(|| device.cast::().ok()) .flatten(); diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index b6122e33d4..fbf2a5c58d 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -176,6 +176,69 @@ pub(crate) struct Translated { #[cfg(windows)] impl Shader { + /// `D3D12-MESH-COMPUTE-FALLBACK`, on a host without mesh shaders: this + /// mesh program seen as a compute stage (its translation there is the + /// compute variant, which writes its outputs to + /// [`leonida_shader::emit::SLOT_MESH_OUT`]), and the pass-through vertex + /// shader that draws what it wrote in front of the pixel shader `ps`, + /// with the layout both use. None when the program did not translate + /// as compute or the vertex shader cannot be made (logged). + pub(crate) fn mesh_fallback( + &self, + ps: Option<&Shader>, + ) -> Option<(Arc, Arc, leonida_shader::emit::MeshOut)> { + let layout = self.translated()?.host.mesh_out.clone()?; + let cs = Arc::new(Shader { + stage: "compute", + hash: self.hash.clone(), + container: self.container.clone(), + ambient: None, + translated: OnceLock::new(), + }); + let ps_dxil = ps.and_then(Shader::translated).map(|t| t.host.dxil.as_slice()); + let dxil = match leonida_shader::emit::mesh_vs(&layout, ps_dxil) { + Ok(dxil) => dxil, + Err(e) => { + tracing::warn!(error = %e, shader = %self.hash, "no pass-through vertex shader for a mesh program"); + return None; + } + }; + let host = leonida_shader::emit::HostShader { + stage: leonida_shader::HwStage::Vs, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: vec![leonida_shader::emit::SLOT_MESH_IN], + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + mesh_out: None, + }; + let vs = Arc::new(Shader { + stage: "vertex", + hash: format!("{}.vs", self.hash), + container: Vec::new(), + ambient: None, + translated: OnceLock::from(Some(Translated { + host, + threads: None, + used: Vec::new(), + tables: crate::draw::TablePlan::new(&[], &[]), + stores: false, + stores_by_address: false, + stores_past_views: false, + writes: false, + pack: None, + pack_logged: Default::default(), + picks: Default::default(), + bound: Default::default(), + })), + }); + Some((cs, vs, layout)) + } + /// The translation, made on first use; a shader that does not /// translate is logged once. pub(crate) fn translated(&self) -> Option<&Translated> { diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index 6776eab8e1..e07f3ebca7 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -582,6 +582,19 @@ fn biased_root_srvs(root_srvs: &[(u8, u32)], user_data: &[leonida_shader::emit:: .fold(0, |mask, (at, _)| mask | 1 << at) } +/// `D3D12-MESH-COMPUTE-FALLBACK`: how a mesh pipeline runs on a host +/// without mesh shaders. The mesh program runs as compute (`cs`), writing +/// its groups' outputs to a buffer bound as its root UAV `out_param`; the +/// pipeline it belongs to then draws them as a triangle list with the +/// pass-through vertex shader, reading the buffer as its root SRV +/// `in_param`. `layout` is where each group's outputs lie. +pub(crate) struct MeshCompute { + pub(crate) cs: HostPipeline, + pub(crate) out_param: u32, + pub(crate) in_param: u32, + pub(crate) layout: leonida_shader::emit::MeshOut, +} + pub(crate) struct HostPipeline { /// A compute pipeline (else graphics). pub(crate) compute: bool, @@ -604,6 +617,8 @@ pub(crate) struct HostPipeline { /// listing (empty for compute). #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] pub(crate) state: String, + /// A mesh pipeline drawn without mesh shaders ([`MeshCompute`]). + pub(crate) mesh_compute: Option>, } /// Logs a pipeline that gets no host pipeline, once per reason. @@ -640,6 +655,9 @@ impl HostPipeline { ); } let mesh = find("mesh"); + if mesh.is_some() && leonida_shader::emit::mesh_as_compute() { + return Self::mesh_compute(shaders, g); + } let stages = if let Some(cs) = compute { vec![(cs, D3D12_SHADER_VISIBILITY_ALL)] } else { @@ -717,11 +735,12 @@ impl HostPipeline { // table of strides, the directory of title memory by // address and its fault notes. let ours = if uav { - slot == leonida_shader::emit::SLOT_FAULTS + slot == leonida_shader::emit::SLOT_FAULTS || slot == leonida_shader::emit::SLOT_MESH_OUT } else { slot == leonida_shader::emit::SLOT_STRIDES || slot == leonida_shader::emit::SLOT_TABLE_STRIDES || slot == leonida_shader::emit::SLOT_MEMORY + || slot == leonida_shader::emit::SLOT_MESH_IN }; if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { // A one-view table: the view's size bounds the @@ -849,6 +868,7 @@ impl HostPipeline { inputs: Vec::new(), rects: false, state: String::new(), + mesh_compute: None, }); } let Some(g) = g else { @@ -905,6 +925,7 @@ impl HostPipeline { inputs: Vec::new(), rects: false, state: String::new(), + mesh_compute: None, }); } @@ -1026,6 +1047,7 @@ impl HostPipeline { slots: g.slots(), inputs: g.elements(), rects: rect_gs.is_some(), + mesh_compute: None, state: { let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { @@ -1082,6 +1104,58 @@ pub(super) fn stream_pipeline( ) } +impl HostPipeline { + /// A mesh pipeline on a host without mesh shaders + /// (`D3D12-MESH-COMPUTE-FALLBACK`): the mesh program as a compute + /// pipeline, and a graphics pipeline of the pass-through vertex shader + /// and the title's pixel shader with the title's state, drawing + /// triangle lists with no vertex input. The graphics one is returned, + /// as a mesh pipeline (the draw path takes it for mesh dispatches), + /// carrying the compute one. + fn mesh_compute(shaders: &[Arc], g: Option<&GraphicsState>) -> Option { + let ms = shaders.iter().find(|s| s.stage == "mesh")?; + let ps = shaders.iter().find(|s| s.stage == "pixel"); + let Some(g) = g else { + return refuse("graphics state not kept (plain description)", shaders); + }; + let Some((cs, vs, layout)) = ms.mesh_fallback(ps.map(|p| &**p)) else { + return refuse("a mesh program that does not run as compute", shaders); + }; + let compute = HostPipeline::new(&[cs], None)?; + let out_param = compute + .stages + .first()? + .root_uavs + .iter() + .find(|r| r.0 == leonida_shader::emit::SLOT_MESH_OUT)? + .1; + // The title's state, drawing triangles from no vertex input. + let mut state = g.with_formats(&g.formats()); + state.topology = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + state.inputs.clear(); + state.names.clear(); + let mut stages = vec![vs]; + stages.extend(ps.cloned()); + let mut graphics = HostPipeline::new(&stages, Some(&state))?; + let in_param = graphics + .stages + .first()? + .root_srvs + .iter() + .find(|r| r.0 == leonida_shader::emit::SLOT_MESH_IN)? + .1; + tracing::info!(?shaders, "host mesh pipeline as compute and a triangle list (no mesh shaders)"); + graphics.mesh = true; + graphics.mesh_compute = Some(Box::new(MeshCompute { + cs: compute, + out_param, + in_param, + layout, + })); + Some(graphics) + } +} + /// A graphics pipeline enabling the depth bounds test: `D3D12_GRAPHICS_PIPELINE_STATE_DESC` /// has no field for `DepthBoundsTestEnable`, so it is created and loaded as a /// pipeline-state stream with `DEPTH_STENCIL1`. From 9f189d6254527d1e90c8ab545b083ae5516d1d1a Mon Sep 17 00:00:00 2001 From: DanielMarcos1 <99456595+DanielMarcos1@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:00:01 -0300 Subject: [PATCH 26/42] docs: refresh GPU testing and Vulkan links --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3100522a2d..72601bfa4f 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,7 @@ translator's contract, [docs/linux.md](docs/linux.md) the Linux steps. | Piece | Where it stands | |---|---| | Shaders: carve, unpack the native RDNA2 code, disassemble | all 26,503 | -| Shaders: RDNA2 → SPIR-V | **26,503 / 26,503 translated** (2,236 vertex, 12,101 pixel, 2,689 compute, 9,282 mesh, 195 geometry) and 26,503 / 26,503 passing `spirv-val`. 23,841 are wave64: exact on 64-wide subgroups (AMD); on 32-wide subgroups (NVIDIA, Intel) compute and mesh shaders are exact with wave64 emulation, cross-half wave operations in vertex, pixel and geometry shaders still approximate. The hand-written GPU tests ran on more than 30 GPU and driver combinations ([#166](https://github.com/ItsNotRexed/Leonida/issues/166)) | +| Shaders: RDNA2 → SPIR-V | **26,503 / 26,503 translated** (2,236 vertex, 12,101 pixel, 2,689 compute, 9,282 mesh, 195 geometry) and 26,503 / 26,503 passing `spirv-val`. 23,841 are wave64: exact on 64-wide subgroups (AMD); on 32-wide subgroups (NVIDIA, Intel) compute and mesh shaders are exact with wave64 emulation, cross-half wave operations in vertex, pixel and geometry shaders still approximate. The hand-written GPU tests ran on more than 30 GPU and driver combinations ([GPU test reports](gpu-test-results/)) | | Models | exported as OBJ with names, UVs and material references: 382,781 recovered in a ten-archive scan, 343,327 of them from `levels.rpf` ([notes](docs/models.md)) | | Textures | texture dictionaries and world texture pools exported as DDS; BCPack decoded for BC1-BC7 where the history it needs is known ([notes](docs/textures.md)) | | Audio | AWC banks exported whole: Opus losslessly as Ogg Opus, PCM as WAV, XMA2 through ffmpeg; 1,589 music and radio records measured ([notes](docs/audio.md), [config](docs/audio_config.md)) | From 3c1f549fd860bb77f74039eb585422bdc7af471a Mon Sep 17 00:00:00 2001 From: EvgHaze Date: Sun, 29 Nov 2026 14:01:09 +1000 Subject: [PATCH 27/42] docs/testing: record the two ps_* KosmicKrisp NaN cases ps_cndmask_sign_mods and ps_valu16_mad_sel fail 4096/4096 on KosmicKrisp (Mesa 26.3.1) and pass on llvmpipe with the same Mesa and on MoltenVK 1.4.2; both read back 0x7fc00000 where the shader wrote a non-canonical NaN or 0xffffffff, the same nir_to_msl constant path already recorded for cs_bvh. Measured on an Apple M3, macOS 27.0. --- docs/testing.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/testing.md b/docs/testing.md index d62a0cf995..ac7afdd7f4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -918,6 +918,8 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | On a Mac, `valu_fuzz.py --family f16` reads `+0` where the model wants `-0`, from a multiply whose exact product is -0 (`v_mul_f16`, `v_pk_mul_f16`) or from an FMA whose product and addend are both -0 (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) | MoltenVK computes a `NoContraction` multiply as `fma(l, r, +0)`, which drops the sign. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-182, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions. To run the rest of the fuzzer clean, add `--skip-op` for each of the five ops. To see them match, install Homebrew's `mesa` and use its KosmicKrisp driver: `LEONIDA_VULKAN_LOADER=/opt/homebrew/opt/vulkan-loader/lib/libvulkan.1.dylib VK_DRIVER_FILES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json python3 -I tools/valu_fuzz.py --family f16 --build runtime/build/linux`. Or build MoltenVK with SPIRV-Cross `300681bb` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision`, and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | A pixel shader exporting non-canonical f32 NaNs reads back `0x7fc00000` from an RGBA32F color attachment | KosmicKrisp (Mesa 26.3.1), reproduced on Apple M3 Max, M2 Ultra and M1 Pro ([#3125](https://github.com/ItsNotRexed/Leonida/issues/3125)): `nir_to_msl` emits `(NAN)` for `float`-typed NaN constants (`MESA_KK_DEBUG=msl`); MoltenVK 1.4.2 preserved both tested payloads on the same hardware | `ps_nan_payload` allows the measured canonical word only for the NaN channels and only when `vk_harness` reports `driver: KosmicKrisp`. Finite channels and other drivers still require exact words. Integer or storage-buffer readback still canonicalizes constants that NIR infers as `float` (see the `cs_bvh` row below). | | `cs_bvh` and `cs_bvh32` fail on a Mac with KosmicKrisp: `out[3]` reads `0x7fc00000`, want `0xffffffff` | KosmicKrisp's `nir_to_msl` compiler (Mesa 26.3.1, measured on Apple M2 Ultra, macOS 27.3), not the translator or the buffer format. The triangle branch writes bitcast `float` words and the box branch writes `OpSelect %uint` with `0xffffffff` (`-1`) into the same VGPRs; NIR erases `OpBitcast`, type inference marks the shared register and `bcsel` as `float`, and `nir_to_msl` prints any `float`-typed 32-bit constant in the IEEE-754 NaN range (`0x7f800001..0x7fffffff`, `0xff800001..0xffffffff`) as `(NAN)` (`0x7fc00000`) | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) return `0xffffffff` on the same machine. Do not weaken `vk_compute_test`'s expected BVH words | +| `ps_cndmask_sign_mods` fails on a Mac with KosmicKrisp: all 4096 pixels differ, `(0,0)` reads `0x7fc00000, 0x7fc00000, 0x80000001, 0x7fc00000`, want `0xff800001, 0x7f800001, 0x80000001, 0x7f800001` | The same `nir_to_msl` NaN-constant path as `cs_bvh` above: the shader selects between `float` NaNs with sign and payload (`-NaN`, `+NaN`), and KosmicKrisp prints each such constant as `(NAN)` (`0x7fc00000`). Measured on an Apple M3, macOS 27.0, Mesa 26.3.1 | Expected with KosmicKrisp; the same test passes 4096/4096 on llvmpipe (Mesa 26.3.1) and on MoltenVK 1.4.2 on the same machine | +| `ps_valu16_mad_sel` fails on a Mac with KosmicKrisp: all 4096 pixels differ, `(0,0)` reads `0x8003, 0xdb880000, 0x7fc00000, 0x80000000`, want `0x8003, 0xdb880000, 0xffffffff, 0x80000000` | Same cause: a value the shader writes as `0xffffffff` (`-1`) reaches the render target as `0x7fc00000` because `nir_to_msl` types the shared register as `float` and prints the NaN-range constant as `(NAN)`. Measured on an Apple M3, macOS 27.0, Mesa 26.3.1 | Expected with KosmicKrisp; passes 4096/4096 on llvmpipe (Mesa 26.3.1) and on MoltenVK 1.4.2 on the same machine | | `cs_fma_fused` fails on a Mac with KosmicKrisp: word 7 reads `0x7352`, want `0x7351` | The f16 multiply-add (round to odd), computed at run time, comes out as if the product were rounded first: the exact product, 14988, is halfway between the f16 values 14984 (`0x7351`) and 14992 (`0x7352`), the addend is -2^-22, and one rounding gives `0x7351`. Measured on an Apple M3 with Mesa 26.3.1, 20 of 20 runs (the review of #1724). While the fixture's f16 operands were literals the constant was folded exactly, so the test passed there | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) give `0x7351` on the same machine. The f32 words KosmicKrisp splits are accepted under `--fma glsl`; the f16 word is not, since it does not use `Fma` | | CMake stops with "needs the Windows SDK 10.0.26100 or newer", or MSVC reports `'Desc_1_2': is not a member of 'D3D12_VERSIONED_ROOT_SIGNATURE_DESC'` | A Windows SDK older than 10.0.26100 (10.0.22621 is the common one), which has no version 1.2 root signatures | `winget install Microsoft.WindowsSDK.10.0.26100`, or add it in the Visual Studio Installer, then delete `runtime/build` and configure again | | `scripts/build_runtime.ps1` stops at once: "The checkout path ... contains '%'" (`build_llvm_mc.ps1`: "-Temp ... contains '%'") | A `%` in the checkout's path (or in `-Temp`). cmd.exe expands `%...%` in the generated `_build.cmd` (twice on a `CALL` line), and even with that escaped, `cl` rejects a `%` in the path-valued `/D` definitions of the test targets (`D8038: invalid argument`) however it is quoted. Older scripts failed in configure or a few hundred steps into Ninja instead | Move or clone the checkout (or choose a `-Temp`) in a folder without `%` in its path | From ab4102efee76939e8604a782403df3b3a45c7ef6 Mon Sep 17 00:00:00 2001 From: Zack Date: Sat, 28 Nov 2026 20:56:33 -0800 Subject: [PATCH 28/42] fix(dstorage): preserve signed BC6H SF16 targets and average full multi-level footprint - Thread signed=(format == 96) into Bc6hCalibrator.add_pool_chunk so signed BC6H_SF16 reference targets clamp to [-32768, 32767] instead of [0, 65535] and _eval_w_ops sign-extends and unquantizes candidates in signed space. - Average the full [x0, x1) x [y0, y1) quadrant footprint across multi-level downsamples in _make_multilevel_quads_getter (caching per-4x4-block sums), eliminating single-phase column/row aliasing at 4+ mip levels. - Add DXGI 96 negative-endpoint and 4-level alternating-column BC7 regression tests in tests/test_dstorage_multilevel_fit.py. --- tests/test_dstorage_multilevel_fit.py | 106 ++++++++++++++++++++++++++ tools/bcpack_history_calib.py | 29 ++++--- tools/build_dstorage_history.py | 71 +++++++++++------ 3 files changed, 172 insertions(+), 34 deletions(-) diff --git a/tests/test_dstorage_multilevel_fit.py b/tests/test_dstorage_multilevel_fit.py index e18f38c0aa..5e6a8d31e2 100644 --- a/tests/test_dstorage_multilevel_fit.py +++ b/tests/test_dstorage_multilevel_fit.py @@ -41,6 +41,25 @@ def _solid_bc7_mode6_block(rgba): return acc.to_bytes(16, "little") +def _striped_bc7_mode6_block(even_rgba, odd_rgba): + acc = 1 << 6 + pos = 7 + for ch in range(4): + acc |= ((even_rgba[ch] >> 1) & 0x7F) << pos + pos += 7 + acc |= ((odd_rgba[ch] >> 1) & 0x7F) << pos + pos += 7 + acc |= (even_rgba[0] & 1) << pos + acc |= (odd_rgba[0] & 1) << (pos + 1) + pos += 2 + for p in range(16): + nb = 3 if p == 0 else 4 + ix = 0 if (p % 4) in (0, 2) else 15 + acc |= (ix & ((1 << nb) - 1)) << pos + pos += nb + return acc.to_bytes(16, "little") + + def _solid_bc6h_mode14_block(w_rgb): plan, _ = bcpack._bc6h_plan(0x0F) fields = [[bcpack._bc6h_stream_w(14, w_rgb[c]), 0, 0, 0] for c in range(3)] @@ -368,6 +387,93 @@ def test_refused_bc6h_intermediate_sibling_falls_back_to_multilevel_zlib_mip(sel for c in range(3): self.assertLessEqual(abs(px[c] - exp_child[c]), 64.0, f"child blk {blk} ch {c}") + def test_signed_bc6h_sf16_multilevel_fit_preserves_negative_endpoints(self): + # DXGI 96 (BC6H_SF16) Mode-14 stream with missing history row 205, zero base-endpoint + # deltas (dz0 == 0), and signed negative reference endpoints (-16384, -12288, -6144). + signed_targets = (-16384, -12288, -6144) + sw_sf16 = tuple(bcpack._bc6h_stream_w(14, v & 0xFFFF) for v in signed_targets) + solid_sf16 = _solid_bc6h_mode14_block(sw_sf16) + self.assertEqual( + history.calib.decode_bc6h_block_unq(solid_sf16, 0, signed=True)[0], + tuple(float(v) for v in signed_targets), + ) + eh_sf16 = tuple((sw_sf16[c], 0, 0, 0) for c in range(3)) + raw_tail = _encode_bc6h_mode14_tiled( + solid_sf16 * 256, secret_entry=205, secret_eh=eh_sf16, ref_count=205 + ) + lanes_mip1 = [[0] * 512 for _ in range(16)] + lanes_mip1[15] = [13, 0] * 256 + raw_mip1 = encode_lanes(lanes_mip1, 6) + zlib_mip0 = zlib.compress(solid_sf16 * 1024, 9) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + pool = work / "pools" / "bc6h-sf16-negative.ttpf" + pool.parent.mkdir(parents=True, exist_ok=True) + record = _pack_etpf(128, 128, 3, 2, 96, 4096, mode=4) + _write_custom_rds5_pool( + pool, + [record], + [(6, 4096, raw_tail), (6, 4096, raw_mip1), (8, 16384, zlib_mip0)], + ) + docs = self._build_history(pool, work) + + self.assertEqual(docs["bc6h"]["endpointClass"][205], 1) + decoded = bcpack.decode(raw_tail, 6, 4096, allow_provisional=True, history=docs) + self.assertEqual(len(decoded), 4096) + for blk in range(256): + px = history.calib.decode_bc6h_block_unq(decoded, blk * 16, signed=True)[0] + for c, want in enumerate(signed_targets): + self.assertLess(px[c], 0.0, f"blk {blk} ch {c} lost negative sign: {px[c]}") + self.assertLessEqual(abs(px[c] - want), 64.0, f"blk {blk} ch {c}: {px[c]} vs {want}") + + def test_bc7_four_level_downsample_averages_full_footprint_across_alternating_columns(self): + # 512x512 7-mip (4 non-tail + 3 packed-tail) BC7 chain: mip[0] (512x512, 256 KiB) is + # lossless zlib with alternating 0 and 254 columns (box mean = 127), mips[1..3] are + # undecodable BC7, and packed tail mip[4] (32x32, delta_level = 4) roots at entry 254. + striped_ref = _striped_bc7_mode6_block((0, 0, 0, 254), (254, 254, 254, 254)) + tail_color = (126, 126, 126, 254) + solid_tail = _solid_bc7_mode6_block(tail_color) + secret = tail_color * 6 + raw_tail = _encode_bc7_mode6_tiled(solid_tail * 256, secret_entry=254, secret_ep=secret, ref_count=254) + raw_mip3 = _refused_bc7_mode6_stream(256) + raw_mip2 = _refused_bc7_mode6_stream(1024) + raw_mip1 = _refused_bc7_mode6_stream(4096) + zlib_mip0 = zlib.compress(striped_ref * 16384, 9) + + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + pool = work / "pools" / "bc7-4level-striped.ttpf" + pool.parent.mkdir(parents=True, exist_ok=True) + record = _pack_etpf(512, 512, 3, 4, 98, 4096, mode=4) + _write_custom_rds5_pool( + pool, + [record], + [ + (7, 4096, raw_tail), + (7, 4096, raw_mip3), + (7, 16384, raw_mip2), + (7, 65536, raw_mip1), + (8, 262144, zlib_mip0), + ], + ) + docs = self._build_history(pool, work) + + for c, target in enumerate((127, 127, 127, 254)): + for field in (c, 4 + c): + self.assertGreaterEqual(docs["bc7"]["historyEndpointBits"][254][field], 4) + self.assertLessEqual( + abs(docs["bc7"]["historyEndpoints"][254][field] - target), + 4, + f"field {field}: {docs['bc7']['historyEndpoints'][254][field]} vs {target}", + ) + decoded = bcpack.decode(raw_tail, 7, 4096, allow_provisional=True, history=docs) + self.assertEqual(len(decoded), 4096) + for blk in range(256): + px = history.calib.decode_bc7_block_rgba(decoded, blk * 16)[0] + for c, target in enumerate((127, 127, 127, 254)): + self.assertLessEqual(abs(px[c] - target), 4, f"blk {blk} ch {c}: {px[c]} vs {target}") + if __name__ == "__main__": unittest.main() diff --git a/tools/bcpack_history_calib.py b/tools/bcpack_history_calib.py index f22dec30be..3cae5fd086 100644 --- a/tools/bcpack_history_calib.py +++ b/tools/bcpack_history_calib.py @@ -1002,7 +1002,7 @@ def _quadrant_weights(self, lanes, i): out.append(tuple(v / 4.0 for v in aq)) return tuple(out) - def add_pool_chunk(self, lanes, nblocks, inv_lookup, chunk_rel_start, get_quads): + def add_pool_chunk(self, lanes, nblocks, inv_lookup, chunk_rel_start, get_quads, signed=False): """Accumulate sibling-mip observations for built-in history chains.""" self.pool_chunks += 1 eb = bcpack.BLOCK_BYTES[self.codec] @@ -1275,7 +1275,7 @@ def add_reference_chunk(self, lanes, ref_blocks, nblocks, *, valid_blocks=None): self.ref_ix[ki][p][0] = nb2 self.ref_ix[ki][p][1] = nv2 - def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get_quads=None): + def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get_quads=None, signed=False): """Accumulate algebraic constraints and optional sibling-mip HDR endpoint targets.""" self.pool_chunks += 1 l0, l1, l15 = lanes[0], lanes[1], lanes[15] @@ -1398,14 +1398,15 @@ def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(3)) wt = 4.0 if spread <= 512.0 else (2.0 if spread <= 2048.0 else 0.75) mean_rgb = tuple(sum(p[c] for p in qpts) / 4.0 for c in range(3)) + lo_bound, hi_bound = (-32768.0, 32767.0) if signed else (0.0, 65535.0) for c in range(3): if cur_w[c] is not None: lst = self.w_obs.setdefault((ke, c), []) if len(lst) < 64: - lst.append((cur_w[c], mode, max(0.0, min(65535.0, mean_rgb[c])), wt)) + lst.append((cur_w[c], mode, max(lo_bound, min(hi_bound, mean_rgb[c])), wt, signed)) @staticmethod - def _eval_w_ops(ops, mode, r0): + def _eval_w_ops(ops, mode, r0, signed=False): v = r0 last_base = 16 for base, dz in ops: @@ -1414,7 +1415,9 @@ def _eval_w_ops(ops, mode, r0): v = (((v >> sh) + dz) & m) << sh last_base = base d3d_w = bcpack._bc6h_stream_w(mode, v >> (16 - last_base)) - return _bc6h_unquantize(d3d_w, last_base, signed=False) + if signed: + d3d_w = _sign_extend(d3d_w, last_base) + return _bc6h_unquantize(d3d_w, last_base, signed=signed) @classmethod def _fit_w(cls, obs_list): @@ -1422,8 +1425,10 @@ def _fit_w(cls, obs_list): cands = [] for h in range(0, 65536, 1024): err = 0.0 - for ops, mode, tgt, wt in obs_list: - d = abs(cls._eval_w_ops(ops, mode, h | 512) - tgt) + for obs in obs_list: + ops, mode, tgt, wt = obs[:4] + obs_signed = obs[4] if len(obs) > 4 else False + d = abs(cls._eval_w_ops(ops, mode, h | 512, signed=obs_signed) - tgt) err += wt * (d if d < cap else cap) cands.append((err, h)) cands.sort() @@ -1437,8 +1442,10 @@ def _fit_w(cls, obs_list): if h in nxt: continue err = 0.0 - for ops, mode, tgt, wt in obs_list: - d = abs(cls._eval_w_ops(ops, mode, h | mid) - tgt) + for obs in obs_list: + ops, mode, tgt, wt = obs[:4] + obs_signed = obs[4] if len(obs) > 4 else False + d = abs(cls._eval_w_ops(ops, mode, h | mid, signed=obs_signed) - tgt) err += wt * (d if d < cap else cap) nxt[h] = err top = sorted((e, h) for h, e in nxt.items())[:4] @@ -1691,7 +1698,7 @@ def add_reference_chunk(self, lanes, ref_blocks, nblocks, *, valid_blocks=None): self.ref_ix[ki][16 + p][0] = nb2 self.ref_ix[ki][16 + p][1] = nv2 - def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get_quads=None): + def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get_quads=None, signed=False): """Accumulate BC7 anchor/p-bit constraints and optional sibling-mip RGBA endpoint fits.""" self.pool_chunks += 1 cfg = self.tab["config"] @@ -2400,7 +2407,7 @@ def calibrate_from_pools(pools, calibrators, *, limit=0, max_blocks=256): continue raw = pool.data[src:src + packed] lanes = decode_lanes_prefix(raw, cid, csize, nb * sym_per_blk) - cal.add_pool_chunk(lanes, nb, inv_lookup, virt - mip_virt, get_quads) + cal.add_pool_chunk(lanes, nb, inv_lookup, virt - mip_virt, get_quads, signed=signed) seen_alg.add((src, packed, cid)) used_mixed = True diff --git a/tools/build_dstorage_history.py b/tools/build_dstorage_history.py index 606a59b93d..dd84a301ec 100644 --- a/tools/build_dstorage_history.py +++ b/tools/build_dstorage_history.py @@ -76,7 +76,8 @@ def address(m): for size, offset, packed, relative, blocks in chunks: lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2) - fit[codec].add_pool_chunk(lanes, blocks, inverse, relative, getter) + fit[codec].add_pool_chunk( + lanes, blocks, inverse, relative, getter, signed=d["format"] == 96) break docs = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in arrays.items()} # Existing array and cube fits keep precedence over supplemental 2D observations. @@ -132,16 +133,34 @@ def _make_multilevel_quads_getter(codec, layout, ref, tiled, delta_level, signed pw, ph = ref["pixels_w"], ref["pixels_h"] nch = 3 if codec == 6 else 4 + def _get_block(bkx, bky): + key = (bkx, bky) + entry = block_cache.get(key) + if entry is None: + off = calib.tiled_offset(layout, ref, bkx, bky) + blk = (calib.decode_bc6h_block_unq(tiled, off, signed=signed) if codec == 6 else + calib.decode_bc7_block_rgba(tiled, off)) + if nch == 3: + bsum = ( + sum(p[0] for p in blk), + sum(p[1] for p in blk), + sum(p[2] for p in blk), + ) + else: + bsum = ( + sum(p[0] for p in blk), + sum(p[1] for p in blk), + sum(p[2] for p in blk), + sum(p[3] for p in blk), + ) + entry = (blk, bsum) + block_cache[key] = entry + return entry + def _get_pixel(px, py): px = min(pw - 1, max(0, px)) py = min(ph - 1, max(0, py)) - key = (px >> 2, py >> 2) - blk = block_cache.get(key) - if blk is None: - off = calib.tiled_offset(layout, ref, key[0], key[1]) - blk = (calib.decode_bc6h_block_unq(tiled, off, signed=signed) if codec == 6 else - calib.decode_bc7_block_rgba(tiled, off)) - block_cache[key] = blk + blk, _ = _get_block(px >> 2, py >> 2) return blk[((py & 3) << 2) | (px & 3)] if delta_level < 0: @@ -152,8 +171,6 @@ def _get_pixel(px, py): ) step = 2 << delta_level - stride = max(1, step >> 3) - half = stride >> 1 def get_quads(bx, by): out = [] @@ -165,17 +182,23 @@ def get_quads(bx, by): if x0 >= x1 or y0 >= y1: out.append(_get_pixel(x0, y0)) continue - sx = x0 + half if x0 + half < x1 else x0 - sy = y0 + half if y0 + half < y1 else y0 - acc = [0.0] * nch - cnt = 0 - for py in range(sy, y1, stride): - for px in range(sx, x1, stride): - pv = _get_pixel(px, py) - for c in range(nch): - acc[c] += pv[c] - cnt += 1 - out.append(tuple(v / cnt for v in acc)) + cnt = (x1 - x0) * (y1 - y0) + if (x0 | y0 | x1 | y1) & 3 == 0: + acc = [0.0] * nch + for bky in range(y0 >> 2, y1 >> 2): + for bkx in range(x0 >> 2, x1 >> 2): + _, bsum = _get_block(bkx, bky) + for c in range(nch): + acc[c] += bsum[c] + out.append(tuple(v / cnt for v in acc)) + else: + acc = [0.0] * nch + for py in range(y0, y1): + for px in range(x0, x1): + pv = _get_pixel(px, py) + for c in range(nch): + acc[c] += pv[c] + out.append(tuple(v / cnt for v in acc)) return tuple(out) return get_quads @@ -267,7 +290,8 @@ def address(m): lanes = calib.decode_lanes_prefix( pool.data[offset:offset + packed], codec, size, blocks * 2) lanes_cache[lkey] = lanes - fit[codec].add_pool_chunk(lanes, blocks, inverse, relative, getter) + fit[codec].add_pool_chunk( + lanes, blocks, inverse, relative, getter, signed=d["format"] == 96) out = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in arrays.items()} extend_missing(out, {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in tails.items()}) return out @@ -438,7 +462,8 @@ def address(m): inverse = calib.make_inverse_tile_lookup(layout, mip) for size, offset, packed, relative, blocks in chunks: lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2) - fits[codec].add_pool_chunk(lanes, blocks, inverse, relative, getter) + fits[codec].add_pool_chunk( + lanes, blocks, inverse, relative, getter, signed=d["format"] == 96) extend_missing(docs, {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}) if _field_count(docs) == before: break From a79340fae81fe6821cf0eb68c29de847396a13b3 Mon Sep 17 00:00:00 2001 From: sodove Date: Wed, 25 Nov 2026 16:41:28 +0500 Subject: [PATCH 29/42] windows-boot: summarize device loss API and queue checkpoints --- scripts/windows-boot/README.md | 6 ++ scripts/windows-boot/boot.ps1 | 65 ++++++++++++++++ tests/test_windows_boot_fault_context.py | 97 ++++++++++++++++++++++++ 3 files changed, 168 insertions(+) create mode 100644 tests/test_windows_boot_fault_context.py diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index 3f22846738..b2bb0188a2 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md @@ -87,6 +87,12 @@ Several records can describe one loss. A driver can also report loss without any Share counts and states on the board. Keep paths, logs, traces, captures and dumps on your machine ([AGENTS.md](../../AGENTS.md), "No game data"). +When the log contains a device loss, a fault query outcome or checkpoint records, `fault context` shows the first +recognized Vulkan API that reported loss and the first observed fault query outcome. An unrecognized operation is +shown as `other`. A missing outcome is `not observed`. The queue count includes queries that returned zero +checkpoints. `reported` sums the driver counts from the queue headers. `decoded` and `unrecognized` count the +two kinds of printed stage records, so a truncated log can have fewer printed records than reported checkpoints. + How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing screen waiting for A), `d` after A. diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 index a0e713c177..5e93bf7acb 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 @@ -473,6 +473,67 @@ if (-not $DigestOnly) { # -------------------------------------------------------------------------------------------- the digest +function Get-FaultContext { + param([string]$Path) + $apis = @("vkAcquireNextImageKHR", "vkBeginCommandBuffer", "vkCreateSwapchainKHR", "vkDeviceWaitIdle", + "vkEndCommandBuffer", "vkGetFenceStatus", "vkGetQueryPoolResults", "vkGetSemaphoreCounterValue", + "vkQueueBindSparse", "vkQueuePresentKHR", "vkQueueSubmit", "vkQueueWaitIdle", "vkResetFences", + "vkSignalSemaphore", "vkWaitForFences", "vkWaitSemaphores") + $api = "not observed" + $query = "not observed" + $lost = $false + [long]$queues = 0 + [long]$reported = 0 + [long]$decoded = 0 + [long]$unrecognized = 0 + + # Select-String streams matches, including a report that arrives after a long trace. + $prefix = '^\s*\[rt\] (device-fault: |vulkan: the device was lost \()' + Select-String -LiteralPath $Path -CaseSensitive -Pattern $prefix | ForEach-Object { + $tag = $_.Matches[0] + $record = $_.Line.Substring($tag.Length).TrimEnd() + if ($tag.Groups[1].Value -eq "vulkan: the device was lost (") { + $lost = $true + if ($api -in @("not observed", "other")) { + if ($record -cmatch '^(vkWaitSemaphores|vkGetSemaphoreCounterValue) in the fence dispatcher returned VK_ERROR_DEVICE_LOST\)') { + $api = $Matches[1] + } elseif ($record.StartsWith("a fence's counter read UINT64_MAX and vkDeviceWaitIdle then returned VK_ERROR_DEVICE_LOST)")) { + $api = "vkDeviceWaitIdle" + } + } + } elseif ($record.StartsWith("VK_ERROR_DEVICE_LOST from ")) { + $lost = $true + if ($api -in @("not observed", "other")) { + $api = "other" + if ($record -cmatch '^VK_ERROR_DEVICE_LOST from ([^\s(]+)' -and $apis -ccontains $Matches[1]) { + $api = $Matches[1] + } + } + } elseif ($record -cmatch '^queue \S+ checkpoints=([0-9]+)$') { + [uint32]$count = 0 + if ([uint32]::TryParse($Matches[1], [ref]$count)) { + $queues++ + $reported += $count + } + } elseif ($record -cmatch '^stage=0x[0-9a-fA-F]+ submission=[0-9]+ list=[0-9]+ command=[0-9]+ kind=\S+$') { + $decoded++ + } elseif ($record -cmatch '^stage=0x[0-9a-fA-F]+ marker=\S+ \(unrecognized\)$') { + $unrecognized++ + } elseif ($query -eq "not observed") { + if ($record.StartsWith("description:")) { + $query = if ($record.EndsWith(" (partial report)")) { "partial" } else { "complete" } + } elseif ($record -cmatch '^vkGetDeviceFaultInfoEXT (counts|data) failed \(-?[0-9]+\)$') { + $query = "$($Matches[1]) failed" + } elseif ($record -ceq "fault info collection failed") { + $query = "collection failed" + } + } + } + if ($lost -or $query -ne "not observed" -or $queues -or $decoded -or $unrecognized) { + "fault context: api=$api, query=$query, queues=$queues, reported=$reported, decoded=$decoded, unrecognized=$unrecognized" + } +} + $py = @(Resolve-Python $Python) if ($py.Count) { $pyArgs = @() @@ -585,6 +646,10 @@ if ($deviceLost -or $faultClasses.Count) { } $digest.Add("faults: $faultText") if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } +if (Test-Path -LiteralPath $LogFile) { + $faultContext = Get-FaultContext $LogFile + if ($faultContext) { $digest.Add($faultContext) } +} $digest.Add("frames: $capText") $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") $digest | Out-File -FilePath $DigestFile -Encoding utf8 diff --git a/tests/test_windows_boot_fault_context.py b/tests/test_windows_boot_fault_context.py new file mode 100644 index 0000000000..e2be2c027e --- /dev/null +++ b/tests/test_windows_boot_fault_context.py @@ -0,0 +1,97 @@ +"""Run the native Windows digest against synthetic device-fault reports.""" + +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + + +BOOT = Path(__file__).resolve().parents[1] / "scripts" / "windows-boot" / "boot.ps1" +POWERSHELL = shutil.which("powershell") or shutil.which("pwsh") +FAULT = "[rt] device-fault: " + + +@unittest.skipUnless(os.name == "nt" and POWERSHELL, "requires PowerShell on Windows") +class FaultContextTest(unittest.TestCase): + def context(self, lines, newline="\n"): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / "boot.log").write_text("\n".join(lines), encoding="utf-8", newline=newline) + (root / "boot.jsonl").write_text('{"kind":"trace_open"}\n', encoding="utf-8", newline="\n") + subprocess.run( + [POWERSHELL, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(BOOT), + "-DigestOnly", "-Name", "boot", "-OutDir", folder, "-SummaryLines", "0", + "-Python", sys.executable], + check=True, capture_output=True, timeout=60, + ) + digest = (root / "boot.digest.txt").read_text(encoding="utf-8-sig") + return [line for line in digest.splitlines() if line.startswith("fault context:")] + + def test_counts_reported_and_printed_checkpoints_separately(self): + lines = [FAULT + "submitted dispatch seq=7 queue=0xfe (copy) shader=private"] * 10 + lines += [FAULT + "VK_ERROR_DEVICE_LOST from vkQueueSubmit (private)", + FAULT + "VK_ERROR_DEVICE_LOST from vkQueueWaitIdle", + FAULT + "description: private (partial report)", + FAULT + "description: second report", + FAULT + "queue 00AAAAAA checkpoints=2", + FAULT + "stage=0x80 submission=1 list=0 command=2 kind=dispatch", + FAULT + "ExecuteCommandLists #1 queue=00AAAAAA (compute) lists=1", + FAULT + "last shader pipeline=0x12 shaders=private - -", + FAULT + "stage=0x40 marker=00000011 (unrecognized)", + FAULT + "queue 00BBBBBB checkpoints=0", + FAULT + "ExecuteCommandLists #9 queue=00BBBBBB (copy) lists=1", + FAULT + "queue 00CCCCCC checkpoints=3", + FAULT + "stage=0x20 submission=2 list=0 command=1 kind=draw", + FAULT + "submission metadata unavailable"] # log ends before two stages are printed + self.assertEqual(self.context(lines, newline="\r\n"), [ + "fault context: api=vkQueueSubmit, query=partial, queues=3, reported=5, decoded=2, unrecognized=1" + ]) + + def test_unknown_operation_and_driver_text_do_not_become_labels(self): + self.assertEqual(self.context([ + FAULT + "VK_ERROR_DEVICE_LOST from vkQueueSubmitPrivate (vkWaitForFences)", + FAULT + "description: private (partial report) and more", + FAULT + "vendor[0] private stage=0x40 marker=12 (unrecognized)", + ]), ["fault context: api=other, query=complete, queues=0, reported=0, decoded=0, unrecognized=0"]) + + def test_first_recognized_api_after_an_unknown_operation(self): + rows = self.context([FAULT + "VK_ERROR_DEVICE_LOST from private", + " " + FAULT + "VK_ERROR_DEVICE_LOST from vkCreateSwapchainKHR (DXGI)"]) + self.assertEqual(rows, [ + "fault context: api=vkCreateSwapchainKHR, query=not observed, queues=0, reported=0, decoded=0, unrecognized=0" + ]) + + def test_query_failures_in_truncated_reports(self): + for detail, outcome in [("vkGetDeviceFaultInfoEXT counts failed (-4)", "counts failed"), + ("vkGetDeviceFaultInfoEXT data failed (-4)", "data failed"), + ("fault info collection failed", "collection failed")]: + with self.subTest(detail=detail): + self.assertEqual(self.context([FAULT + detail]), [ + f"fault context: api=not observed, query={outcome}, queues=0, reported=0, decoded=0, unrecognized=0" + ]) + + def test_runtime_loss_without_diagnostics(self): + reasons = [ + ("vkWaitSemaphores in the fence dispatcher returned VK_ERROR_DEVICE_LOST", "vkWaitSemaphores"), + ("a fence's counter read UINT64_MAX and vkDeviceWaitIdle then returned VK_ERROR_DEVICE_LOST", "vkDeviceWaitIdle"), + ("a Vulkan call returned VK_ERROR_DEVICE_LOST", "not observed"), + ] + for reason, api in reasons: + with self.subTest(reason=reason): + rows = self.context([f"[rt] vulkan: the device was lost ({reason}); its fences now read UINT64_MAX"]) + self.assertEqual(rows, [ + f"fault context: api={api}, query=not observed, queues=0, reported=0, decoded=0, unrecognized=0" + ]) + + def test_normal_dispatches_and_quoted_diagnostics_do_not_create_context(self): + self.assertEqual(self.context([FAULT + "enabled (fault info on, checkpoints on, NVIDIA diagnostics config on)", + FAULT + "submitted dispatch seq=7 queue=0xfe (copy) shader=private", + FAULT + "queue 00AAAAAA checkpoints=999999999999999999999", + "[rt] title: " + FAULT + "description: private"]), []) + + +if __name__ == "__main__": + unittest.main() From bc0c72f500a486fd88a761b5b65221a73fa14740 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 12:20:05 +0200 Subject: [PATCH 30/42] d3d12: mesh fallback review fixes: no mesh signature for it, the sink slot drawn by no instance, the title's topology back, offsets beside their elements From timbot103's audit of dc5818bb8 (#2580): - An indirect mesh dispatch run as compute makes no host mesh command signature first: a host without mesh shaders may refuse one, and the fallback needs none (draw.rs). - Slot `groups_cap` is the sink every group from the cap on writes to at once: mesh_vs draws nothing for an instance from the cap on (it took only those past it), and the direct path draws at most `cap` instances. - The fallback's triangle list no longer stays the list's topology: the title's comes back after it (`restore_topology`). - MeshOut's OSG1/PSG1 parts keep their elements in the order of the byte offsets made for them: sorted by register, an element stood beside another's offset where the outputs were not in register order. - A per-primitive render-target or viewport index is refused by mesh_vs rather than left out (the translator does not export them yet). - The host device is made before a pipeline chooses between the mesh path and the fallback, so a pipeline made first cannot keep the mesh path. - The mesh program's own stores (to title buffers) count after a fallback draw, as the draw's do (`drew_mesh_as_compute`). Tests: mesh_out_parts_keep_their_elements_beside_their_offsets (fails without the fix), the_mesh_sink_slot_draws_nothing (GPU; the test harness's Draw takes an instance count). Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 53 ++++++-- d3d12/crates/leonida-gpu/src/pipeline/host.rs | 7 + .../leonida-shader/src/emit/container.rs | 16 ++- .../leonida-shader/src/emit/diff_tests.rs | 2 + d3d12/crates/leonida-shader/src/emit/host.rs | 4 +- .../crates/leonida-shader/src/emit/mesh_vs.rs | 12 +- d3d12/crates/leonida-shader/src/emit/mod.rs | 121 ++++++++++++++++++ d3d12/crates/leonida-shader/src/emit/rect.rs | 1 + .../crates/leonida-shader/src/emit/shader.rs | 6 +- 9 files changed, 208 insertions(+), 14 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 8381f99392..7b1cbc432d 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -1995,6 +1995,14 @@ impl State { }; } + /// The title's topology on the list again, after a pass of ours set + /// another (the mesh fallback's triangle list). + fn restore_topology(&mut self, list: &HostList) { + if self.topology_set { + self.set_topology(list, self.topology); + } + } + pub(crate) fn set_pipeline(&mut self, pipeline: This) { self.pipeline = pipeline as usize; } @@ -4705,7 +4713,8 @@ impl State { self.mesh_scissor(list, true); l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - l.DrawInstanced(mc.layout.max_primitives * 3, n, 0, 0); + // Instances from the cap on would read the sink slot. + l.DrawInstanced(mc.layout.max_primitives * 3, n.min(mc.layout.groups_cap()), 0, 0); self.mesh_scissor(list, false); } l.ResourceBarrier(&[crate::host::transition( @@ -4714,6 +4723,11 @@ impl State { D3D12_RESOURCE_STATE_COMMON, )]); } + // The fallback drew a triangle list: the title's next draw has its + // own topology again. + if drawn { + self.restore_topology(list); + } list.keep(&buffer); drawn } @@ -4785,6 +4799,11 @@ impl State { } l.ResourceBarrier(&[crate::host::transition(&buffer, read, D3D12_RESOURCE_STATE_COMMON)]); } + // The fallback drew a triangle list: the title's next draw has its + // own topology again. + if drawn { + self.restore_topology(list); + } list.keep(&buffer); drawn } @@ -4821,7 +4840,7 @@ impl State { if let Some(p) = fallback { let ran = !held && self.mesh_as_compute(list, x, p); if ran { - self.drew(Some(p)); + self.drew_mesh_as_compute(p); DRAWN.fetch_add(1, Ordering::Relaxed); } else { DROPPED.fetch_add(1, Ordering::Relaxed); @@ -5651,6 +5670,16 @@ impl State { /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] /// if its shaders can store to buffers). + /// [`Self::drew`] for a mesh pipeline run as compute and a draw: the + /// mesh program's own stores (to title buffers; its outputs to the mesh + /// buffer are not counted) as well as the draw's. + fn drew_mesh_as_compute(&mut self, p: &HostPipeline) { + self.drew(Some(p)); + if let Some(mc) = p.mesh_compute.as_deref() { + self.drew(Some(&mc.cs)); + } + } + fn drew(&mut self, p: Option<&HostPipeline>) { if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) { // (With 4 a known pipeline's stores are told apart by address, if they are all @@ -5901,16 +5930,20 @@ impl State { }, None => None, }; - let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) + // A mesh program run as compute needs no host signature of its own + // (`mesh_indirect_as_compute` makes its own of a dispatch and a + // draw), and a host without mesh shaders may refuse a mesh one. + let as_compute = kind == MESH && p.mesh_compute.is_some(); + let signature = (matches!(kind, DRAW | INDEXED | DISPATCH | MESH) && !as_compute) .then(|| match pack { Some(pack) => pack_signature(&p.root, pack), None => host_signature(kind, stride), }) - .flatten() - else { + .flatten(); + if signature.is_none() && !as_compute { why("no host signature"); return false; - }; + } if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { crate::drops::note(Why::SkipList); why("mesh draws are switched off (LEONIDA_MESH_TEST=skip)"); @@ -6017,11 +6050,11 @@ impl State { (bounded, 0) } }; - if kind == MESH && p.mesh_compute.is_some() { + if as_compute { let counted = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); let ran = self.mesh_indirect_as_compute(list, p, (&bounded, at, stride), counted); if ran { - self.drew(Some(p)); + self.drew_mesh_as_compute(p); DRAWN.fetch_add(1, Ordering::Relaxed); } else { crate::drops::note(Why::BindFailed); @@ -6029,6 +6062,10 @@ impl State { } return ran; } + // (Made above for every kind but a mesh program run as compute.) + let Some(signature) = signature else { + return false; + }; let ran = match kind { DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), diff --git a/d3d12/crates/leonida-gpu/src/pipeline/host.rs b/d3d12/crates/leonida-gpu/src/pipeline/host.rs index e07f3ebca7..5e141f0c1a 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline/host.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline/host.rs @@ -655,6 +655,13 @@ impl HostPipeline { ); } let mesh = find("mesh"); + // Whether mesh programs run as compute is known once the host device + // is made (`crate::host::create`): made first, so a pipeline made + // before it does not take (and keep) the mesh path on a host + // without mesh shaders. + if mesh.is_some() { + host()?; + } if mesh.is_some() && leonida_shader::emit::mesh_as_compute() { return Self::mesh_compute(shaders, g); } diff --git a/d3d12/crates/leonida-shader/src/emit/container.rs b/d3d12/crates/leonida-shader/src/emit/container.rs index 9ed2b78bd0..c41618ec92 100644 --- a/d3d12/crates/leonida-shader/src/emit/container.rs +++ b/d3d12/crates/leonida-shader/src/emit/container.rs @@ -66,6 +66,18 @@ impl SigElement { /// `ISG1`/`OSG1`: 32-byte rows, then the names. pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { + signature_sorted(elements, input, true) +} + +/// [`signature`] with the elements in the order given, not sorted by +/// register: for a part only we read back (a mesh program's outputs, +/// `super::shader::MeshOut`), whose elements must stay beside the byte +/// offsets made in that order. +pub(crate) fn signature_in_order(elements: &[SigElement], input: bool) -> Vec { + signature_sorted(elements, input, false) +} + +fn signature_sorted(elements: &[SigElement], input: bool, sorted: bool) -> Vec { let mut out = Vec::new(); out.extend((elements.len() as u32).to_le_bytes()); out.extend(8u32.to_le_bytes()); @@ -90,7 +102,9 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { } } let mut order: Vec = (0..elements.len()).collect(); - order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), offsets[i])); + if sorted { + order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), offsets[i])); + } for i in order { let (e, offset) = (&elements[i], offsets[i]); let used = e.usage << e.col; diff --git a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs index f0094ad7b2..91879879e9 100644 --- a/d3d12/crates/leonida-shader/src/emit/diff_tests.rs +++ b/d3d12/crates/leonida-shader/src/emit/diff_tests.rs @@ -774,6 +774,7 @@ fn translated_shaders_draw_as_pc_ones() { size: (16, 16), mesh_groups: 0, vertex_count: 0, + instances: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); @@ -897,6 +898,7 @@ fn translated_mesh_shaders_draw_as_pc_ones() { size: (16, 16), mesh_groups, vertex_count: 0, + instances: 0, }; let mut failures = Vec::new(); let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 103d46cc9c..26c3316676 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -653,6 +653,8 @@ pub struct Draw<'a> { pub mesh_groups: u32, /// Vertices drawn (0: three, one triangle). pub vertex_count: u32, + /// Instances drawn (0: one). + pub instances: u32, } #[cfg(test)] @@ -931,7 +933,7 @@ impl Host { list6.DispatchMesh(d.mesh_groups, 1, 1); } else { let count = if d.vertex_count == 0 { 3 } else { d.vertex_count }; - list.DrawInstanced(count, 1, 0, 0); + list.DrawInstanced(count, d.instances.max(1), 0, 0); } list.ResourceBarrier(&[transition( &target, diff --git a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs index f570562a30..a12e8b8b63 100644 --- a/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs +++ b/d3d12/crates/leonida-shader/src/emit/mesh_vs.rs @@ -81,6 +81,12 @@ fn build( // A per-primitive output goes where the pixel shader reads it; one the // pixel shader does not read is not drawn with. for (p, &at) in primitive.iter().zip(&layout.primitive_at) { + // A render-target or viewport index is the rasteriser's, read or not + // (the translator refuses to export them as yet: `lower.rs`, "render- + // target or viewport index exports"). + if matches!(p.kind, 4 | 5) { + return Err(unsupported("a per-primitive render-target or viewport index")); + } let Some(e) = ps_inputs .iter() .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some()) @@ -133,9 +139,11 @@ fn build( let three = k(&mut s, 3); let prim = s.m.bin(b, Bin::UDiv, id, three); let corner = s.m.bin(b, Bin::URem, id, three); - // A group past the cap wrote to the sink slot: it draws nothing. + // Slots 0 to cap - 1 are groups' own; slot cap is the sink every group + // from cap on wrote to at once: an instance from cap on draws nothing + // (and nothing reads the sink). let cap = k(&mut s, layout.groups_cap()); - let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap); + let past = s.m.cmp(b, super::bitcode::pred::IUGE, group, cap); let group = s.op(b, "binary.i32", Attr::ReadNone, i32t, 40, &[group, cap]); s.m.tag(group, super::bitcode::Tag::Clamp); diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 28586eff66..d46884dffd 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -2591,6 +2591,7 @@ mod tests { size: (16, 16), mesh_groups: 1, vertex_count: 0, + instances: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2844,6 +2845,7 @@ mod tests { size: (16, 16), mesh_groups: 1, vertex_count: 0, + instances: 0, }, ) .unwrap_or_else(|e| panic!("{label}: draw: {e}")); @@ -2911,6 +2913,7 @@ mod tests { size: (16, 16), mesh_groups, vertex_count, + instances: 0, }; for (prim, culled) in [ (TRIANGLE, false), @@ -3004,6 +3007,123 @@ mod tests { } } + /// The sink slot (`MeshOut::groups_cap`) takes the writes of every + /// group past the cap at once, so the pass-through vertex shader draws + /// nothing of it: a triangle there, in a buffer drawn with one instance + /// more than the cap, lights no texel, where the same triangle in slot 0 + /// lights them all. + #[test] + #[cfg(windows)] + fn the_mesh_sink_slot_draws_nothing() { + use super::host::{Dispatch, Draw, Host, Root}; + use windows::Win32::Graphics::Direct3D12::{D3D12_SHADER_VISIBILITY_ALL, D3D12_SHADER_VISIBILITY_VERTEX}; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; skipped"); + return; + }; + let ps = constant_color(); + super::lower::TEST_MESH_COMPUTE.set(Some(true)); + let cs = triangle_mesh(TRIANGLE); + super::lower::TEST_MESH_COMPUTE.set(None); + let cs = cs.unwrap(); + let layout = cs.mesh_out.clone().unwrap(); + let root = host.root_signature_for(&[(&cs, D3D12_SHADER_VISIBILITY_ALL)]).unwrap(); + let pso = host.compute_pipeline_with(&root, &cs.dxil).unwrap(); + let slot_words = (layout.group_bytes() / 4) as usize; + let header_words = (MESH_OUT_HEADER / 4) as usize; + let one = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(vec![0])), + (1, Root::Uav((MESH_OUT_HEADER + layout.group_bytes()) / 4)), + ], + views: &[], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let group0 = one.last().unwrap()[header_words..header_words + slot_words].to_vec(); + let vs = mesh_vs(&layout, Some(&ps)).unwrap(); + let vs_shader = HostShader { + stage: HwStage::Vs, + dxil: vs.clone(), + user_data: vec![], + samplers: vec![], + static_samplers: vec![], + root_cbvs: vec![], + root_srvs: vec![SLOT_MESH_IN], + root_uavs: vec![], + root_indexed_views: vec![], + half_views: vec![], + mesh_out: None, + }; + let root = host.root_signature_for(&[(&vs_shader, D3D12_SHADER_VISIBILITY_VERTEX)]).unwrap(); + let pso = host.pipeline_with(&root, &vs, &ps).unwrap(); + let cap = layout.groups_cap(); + // The triangle in slot `at` of a whole buffer, drawn with `instances`. + let lit = |at: u32, instances: u32| { + let mut data = vec![0u32; (MESH_OUT_BYTES / 4) as usize]; + let first = header_words + at as usize * slot_words; + data[first..first + slot_words].copy_from_slice(&group0); + let texels = host + .draw( + &root, + &pso, + &Draw { + roots: vec![(0, Root::Constants(vec![0])), (1, Root::View { srv: true, data })], + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups: 0, + vertex_count: 3 * layout.max_primitives, + instances, + }, + ) + .unwrap(); + texels.iter().filter(|t| t[3] != 0.0).count() + }; + assert_eq!(lit(0, 1), 256, "the triangle in slot 0"); + assert_eq!(lit(cap, cap + 1), 0, "the sink slot (cap {cap}) drew"); + } + + /// A mesh program's outputs out of register order (the position in a + /// row of its own after a parameter, as the 2020 compiler's first entry + /// can be) keep each element beside its byte offset: the layout's parts + /// list them in the order the offsets were made, which is the order the + /// pass-through vertex shader pairs them in. + #[test] + fn mesh_out_parts_keep_their_elements_beside_their_offsets() { + let el = |name: &str, kind: u8, row: u32, cols: u8| container::SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: if kind == 0 { 2 } else { 0 }, + row: Some(row), + col: 0, + cols, + usage: (1 << cols) - 1, + half: false, + }; + let outputs = [el("TEXCOORD", 0, 2, 2), el("SV_Position", 3, 0, 4), el("COLOR", 0, 1, 3)]; + let prims = [el("PRIMDATA", 0, 4, 1), el("PRIMFLAGS", 0, 3, 2)]; + let layout = MeshOut::new(3, 1, &outputs, &prims); + assert_eq!(layout.vertex_at, [0, 8, 24]); + assert_eq!(layout.primitive_at, [12, 16]); + let names = |part: &[u8]| signature(part).unwrap().into_iter().map(|e| e.name).collect::>(); + assert_eq!(names(&layout.osg1), ["TEXCOORD", "SV_Position", "COLOR"]); + assert_eq!(names(&layout.psg1), ["PRIMDATA", "PRIMFLAGS"]); + } + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) @@ -4023,6 +4143,7 @@ mod barycentric_tests { size: (8, 8), mesh_groups: 0, vertex_count: 0, + instances: 0, }, ) .expect("draw partial interpolation"); diff --git a/d3d12/crates/leonida-shader/src/emit/rect.rs b/d3d12/crates/leonida-shader/src/emit/rect.rs index 983bc4c07b..4fab257544 100644 --- a/d3d12/crates/leonida-shader/src/emit/rect.rs +++ b/d3d12/crates/leonida-shader/src/emit/rect.rs @@ -467,6 +467,7 @@ mod tests { size: (8, 8), mesh_groups: 0, vertex_count: 0, + instances: 0, }; host.draw(&root, &pso, &d).unwrap() }; diff --git a/d3d12/crates/leonida-shader/src/emit/shader.rs b/d3d12/crates/leonida-shader/src/emit/shader.rs index 4ca71e678b..9e36a38de5 100644 --- a/d3d12/crates/leonida-shader/src/emit/shader.rs +++ b/d3d12/crates/leonida-shader/src/emit/shader.rs @@ -276,8 +276,10 @@ impl MeshOut { primitive_stride, vertex_at, primitive_at, - osg1: super::container::signature(outputs, false), - psg1: super::container::signature(prims, false), + // In element order, as the offsets above: sorted by register the + // elements would no longer stand beside their offsets. + osg1: super::container::signature_in_order(outputs, false), + psg1: super::container::signature_in_order(prims, false), } } From 528e0862f2dc3411a66d30501b8f8670ddd0d88c Mon Sep 17 00:00:00 2001 From: slipperysquid Date: Tue, 24 Nov 2026 20:11:17 -0300 Subject: [PATCH 31/42] runtime: LEONIDA_SKIP_ASSERTS steps over guest asserts without a trace (RT-526) A diagnostic for the retail boot (RT-5 follow-ups), off the hot path and with no behaviour change unless asked for: LEONIDA_SKIP_ASSERTS=N (src/assert_skip.h, installed by main.cpp before any image code runs under --init/--run): a vectored handler, added last, steps over up to N int3 (0xCC) at addresses in no host module and logs each one as module+RVA (and as an int3_skipped trace event when --trace is open). After N it says so once and the next int3 ends the run as before. An int3 in a host module, a breakpoint with no 0xCC at its address, or a RIP that is neither at nor one past the 0xCC is passed on. Needs no --trace and no debugger. Tests (synthetic, no game files): assert_skip_test (int3 in a VirtualAlloc'd page, the limit, a host-module int3, a two-byte int 3, value parsing) and run_tiny_game_skip_asserts (two int3 in the mapped stand-in game, stepped over end to end). Carried over from old upstream PR 9961 (#228) without its caller logging for forwarded device slots, which the carry-over of old PR 9990 (#1390) brings instead. Co-Authored-By: Claude Opus 5.5 --- docs/boot.md | 4 + runtime/CMakeLists.txt | 19 ++++ runtime/README.md | 23 ++++- runtime/src/assert_skip.h | 151 ++++++++++++++++++++++++++++ runtime/src/main.cpp | 12 +++ runtime/test/assert_skip_test.cpp | 135 +++++++++++++++++++++++++ runtime/test/fixtures/tiny_game.cpp | 23 ++++- tools/boot_trace.py | 3 +- 8 files changed, 366 insertions(+), 4 deletions(-) create mode 100644 runtime/src/assert_skip.h create mode 100644 runtime/test/assert_skip_test.cpp diff --git a/docs/boot.md b/docs/boot.md index 06b34a11df..8949050ba0 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -109,6 +109,10 @@ Useful switches: read when the trace opens. Diagnostic only: a correct run reaches none, so each skipped address is a finding, not a fix. A failed guest file open is always traced as `file_open_failed` (path, error, caller) when `--trace` is on. +* `LEONIDA_SKIP_ASSERTS=N` steps over up to N int3 in guest code, with or without `--trace`, and prints each one + as `[rt] LEONIDA_SKIP_ASSERTS: int3 at +0x... stepped over (k of N)`; the next one after N ends the run as + before. An int3 in a host module is never stepped over. The same caveat: each skipped address is a finding + ([runtime/README.md](../runtime/README.md), "Guest asserts"). * `LEONIDA_STUB_PIPELINES=1` creates a pipeline whose translated shader is missing (no shader library, or no entry for its program) as a stub instead of failing `CreateGraphicsPipelineState` / `CreateComputePipelineState`. A graphics pipeline with a vertex stage (MVP-GPU-04) is a real Vulkan pipeline built from the built-in stages in diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index f6cb8f6fbd..14e4d94f44 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -556,6 +556,16 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(int3_skip_test PRIVATE /W4 /permissive- /utf-8) target_link_options(int3_skip_test PRIVATE /OPT:NOREF) + # LEONIDA_SKIP_ASSERTS (src/assert_skip.h): int3 in a page no host module owns, stepped over up to a limit. + add_executable(assert_skip_test + test/assert_skip_test.cpp + shims/registry.cpp + ) + target_include_directories(assert_skip_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_compile_definitions(assert_skip_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(assert_skip_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(assert_skip_test PRIVATE /OPT:NOREF) + # Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched. add_executable(winhttp_offline_test test/winhttp_offline_test.cpp @@ -1837,6 +1847,9 @@ if(BUILD_TESTING) if(WIN32 AND TARGET int3_skip_test) add_test(NAME int3_skip COMMAND int3_skip_test) endif() + if(WIN32 AND TARGET assert_skip_test) + add_test(NAME assert_skip COMMAND assert_skip_test) + endif() if(WIN32 AND TARGET winhttp_offline_test) add_test(NAME winhttp_offline COMMAND winhttp_offline_test) endif() @@ -2035,6 +2048,12 @@ if(BUILD_TESTING) "-DTOOL=$" "-DWANT=${GTA6RT_STACK}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $ -- hello 42 stack) + # LEONIDA_SKIP_ASSERTS (src/assert_skip.h): two int3 in the mapped image, in no host module, are stepped over and + # the game carries on to its normal exit. Without the variable the first one would end the run. + add_test(NAME run_tiny_game_skip_asserts COMMAND gta6rt --run $ -- hello 42 int3) + set_tests_properties(run_tiny_game_skip_asserts PROPERTIES + ENVIRONMENT "LEONIDA_SKIP_ASSERTS=2" + FAIL_REGULAR_EXPRESSION "tiny_game: FAIL|LEONIDA_SKIP_ASSERTS: [^\n]* is not") # A /GA executable under --run and --init reads its TLS from slot 0, and the trace names gta6rt.exe as the image # whose index 0 moved. add_test(NAME run_tiny_tls_ga COMMAND ${CMAKE_COMMAND} diff --git a/runtime/README.md b/runtime/README.md index 5153640f6f..f24ae61e0d 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -101,6 +101,25 @@ The thunk keeps the Win64 argument registers and the return address intact (it i reaches a shared stub that saves them, so a floating-point caller still reads 0.0 from xmm0 and a debugger can unwind through it. +### Guest asserts: `LEONIDA_SKIP_ASSERTS` + +A title's assert ends in an `int3`. Without a debugger that breakpoint is unhandled and the run ends there. +`LEONIDA_SKIP_ASSERTS=N` (a decimal number, 1 to 1000000; diagnostic, off by default) makes `--init` and `--run` +install a vectored exception handler ([src/assert_skip.h](src/assert_skip.h)) before any image code runs. It steps +over up to N `int3` (the byte 0xCC) at addresses in no host module, the mapped images and code a title wrote +itself, and prints one line for each: + +``` +[rt] LEONIDA_SKIP_ASSERTS: int3 at game.exe+0x1234 stepped over (1 of 3) +``` + +After N it says so once (`3 int3 stepped over; the one at ... is not`) and the next `int3` ends the run as before. An +`int3` in a host module (gta6rt, its shims, a system DLL) is never stepped over. Unset, empty or `0` installs +nothing; any other value is reported and treated as `0`. No `--trace` is needed; with one, each skip is also an +`int3_skipped` event and the trace's own handler records the breakpoint and its stack first. `LEONIDA_SKIP_INT3` +(with `--trace`) is the older switch: it steps over every guest `int3` without a limit and logs each address once; +while a trace is open it runs first. Each skipped address is a finding, not a fix: a correct run reaches none. + ### Compat modules: `LEONIDA_COMPAT_DIR` Opt-in. When `LEONIDA_COMPAT_DIR` names a folder, an import whose DLL is a file in that folder (matched by file name, @@ -700,7 +719,7 @@ from the ANSI code page. | `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) | | `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` | | `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) | -| `int3_skipped` | with `LEONIDA_SKIP_INT3` set when the trace opens: first int3 at each address, which is then stepped over (after 4096 distinct addresses, a new one is logged each time it is hit) | `at` (module+RVA) | +| `int3_skipped` | with `LEONIDA_SKIP_INT3` set when the trace opens: first int3 at each address, which is then stepped over (after 4096 distinct addresses, a new one is logged each time it is hit); with `LEONIDA_SKIP_ASSERTS` (below): every int3 it steps over | `at` (module+RVA); `skip` (the count, `LEONIDA_SKIP_ASSERTS` only) | | `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | | `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) | | `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` | @@ -708,7 +727,7 @@ from the ANSI code page. Every line also has `seq` and `t` (seconds since the trace opened). Addresses are `module+0xRVA` for mapped images, `host:name.dll+0xRVA` for host modules. The exception handler only records: it returns `EXCEPTION_CONTINUE_SEARCH`, so the process behaves the same with or without the trace (except under the diagnostic `LEONIDA_SKIP_INT3`, which -steps over int3). It works with any `LEONIDA_UNIMPLEMENTED` policy. +steps over int3; `LEONIDA_SKIP_ASSERTS` steps over int3 with or without the trace). It works with any `LEONIDA_UNIMPLEMENTED` policy. The file can quote what the game prints, so it stays on your machine. In issues and pull requests, share counts or lines from synthetic fixtures only. diff --git a/runtime/src/assert_skip.h b/runtime/src/assert_skip.h new file mode 100644 index 0000000000..9565d8dbdf --- /dev/null +++ b/runtime/src/assert_skip.h @@ -0,0 +1,151 @@ +#pragma once + +// LEONIDA_SKIP_ASSERTS=N (diagnostic, off by default): step over up to N int3 breakpoints in guest code. +// +// A title's assert ends in an int3 (0xCC). With a debugger attached that is a stop to look at; without one it is an +// unhandled EXCEPTION_BREAKPOINT and the run ends there. gta6rt installs this vectored handler when the variable is a +// number above 0 (main.cpp, before any image code runs). For an EXCEPTION_BREAKPOINT whose address is in no host +// module (the Windows loader knows none at that address: the mapped game images, or code a title wrote itself) and +// whose byte there is 0xCC, it logs one line, moves RIP past the int3 and continues; after N of them it stops doing so, +// says so once, and the next int3 ends the run as before. An int3 in a host module (gta6rt, its shims, a system DLL, +// DbgBreakPoint) is never stepped over. +// +// RIP: on Windows x64 an int3's ExceptionAddress and the context's RIP both name the 0xCC (the kernel backs RIP up +// over it), and Wine reports the same; the handler also takes a RIP one past the 0xCC, which it leaves as it is. +// Any other RIP is not this int3's, and the exception is passed on. +// +// Unlike LEONIDA_SKIP_INT3 (startup_trace.h), it needs no --trace, counts every int3 rather than each address once, +// and stops after N, so a loop of asserts can't spin forever. With --trace each skip is also an `int3_skipped` event, +// and the trace's own handler, which runs first, records the exception and its stack. The handler is added last, so +// every other vectored handler sees the breakpoint first. Each skipped address is a finding, not a fix: a correct run +// reaches none. +// +// The log lines quote addresses as module+RVA only; they stay on the player's machine like the startup trace does. + +#include + +#include +#include +#include +#include +#include +#include + +#include "../shims/shims.h" +#include "../shims/startup_trace.h" + +namespace rt::assert_skip { + +inline constexpr wchar_t kVariable[] = L"LEONIDA_SKIP_ASSERTS"; +// Far above any useful count; it only keeps the number in an unsigned. +inline constexpr unsigned long kMaxLimit = 1000000; + +// The limit LEONIDA_SKIP_ASSERTS asks for: 0 when the text is null or empty, "0", or not a decimal number in +// 0..kMaxLimit (then `*valid`, when given, is false). +inline unsigned parse_limit(const wchar_t* text, bool* valid = nullptr) { + if (valid) *valid = true; + if (!text || !*text) return 0; + if (*text < L'0' || *text > L'9') { // no sign, no leading space: wcstoul would take "-1" as ULONG_MAX + if (valid) *valid = false; + return 0; + } + errno = 0; + wchar_t* end = nullptr; + const unsigned long n = std::wcstoul(text, &end, 10); + if (errno != 0 || !end || *end != L'\0' || n > kMaxLimit) { + if (valid) *valid = false; + return 0; + } + return static_cast(n); +} + +// LEONIDA_SKIP_ASSERTS as a limit; a value that is not one is reported on stderr and counts as 0 (off). +inline unsigned limit_from_environment() { + wchar_t value[32] = {}; + const DWORD length = GetEnvironmentVariableW(kVariable, value, 32); + if (length == 0) return 0; + bool valid = false; + const unsigned limit = length < 32 ? parse_limit(value, &valid) : 0; + if (length >= 32 || !valid) + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: expected a number of int3 to step over (0..%lu); off\n", + kMaxLimit); + return limit; +} + +namespace detail { +inline std::atomic limit{0}; +inline std::atomic claimed{0}; // skips handed out, may pass `limit` by the declined ones +inline std::atomic exhausted_logged{false}; +inline void* veh = nullptr; + +// True when the Windows loader knows a module at `address`: gta6rt, its DLLs, system DLLs. The Loader's mapped +// images are not among them. +inline bool in_host_module(const void* address) { + HMODULE module = nullptr; + return GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &module) && module; +} + +// The byte at `address`, read only when the page is committed and readable. +inline bool read_byte(const void* address, unsigned char& byte) { + MEMORY_BASIC_INFORMATION mbi{}; + if (!address || !VirtualQuery(address, &mbi, sizeof mbi) || mbi.State != MEM_COMMIT) return false; + if (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; + const DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + if (!(mbi.Protect & readable)) return false; + byte = *static_cast(address); + return true; +} + +inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { + if (!info || !info->ExceptionRecord || !info->ContextRecord) return EXCEPTION_CONTINUE_SEARCH; + const EXCEPTION_RECORD& r = *info->ExceptionRecord; + if (r.ExceptionCode != EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_SEARCH; + const unsigned max = limit.load(std::memory_order_relaxed); + if (max == 0) return EXCEPTION_CONTINUE_SEARCH; + const void* at = r.ExceptionAddress; + const auto at_word = reinterpret_cast(at); + CONTEXT& c = *info->ContextRecord; + if (c.Rip != at_word && c.Rip != at_word + 1) return EXCEPTION_CONTINUE_SEARCH; // not this int3's RIP + unsigned char byte = 0; + if (in_host_module(at) || !read_byte(at, byte) || byte != 0xCC) return EXCEPTION_CONTINUE_SEARCH; + const unsigned n = claimed.fetch_add(1, std::memory_order_relaxed) + 1; + if (n > max) { + if (!exhausted_logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: %u int3 stepped over; the one at %s is not\n", max, + shims::module_offset(at_word).c_str()); + return EXCEPTION_CONTINUE_SEARCH; + } + const std::string where = shims::module_offset(at_word); + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: int3 at %s stepped over (%u of %u)\n", where.c_str(), n, max); + std::fflush(stderr); + startup_trace::event("int3_skipped", "\"at\":" + startup_trace::quote(where) + ",\"skip\":" + std::to_string(n)); + if (c.Rip == at_word) c.Rip = at_word + 1; + return EXCEPTION_CONTINUE_EXECUTION; +} +} // namespace detail + +// Steps over up to `limit` guest int3 from now on (0 removes the handler). Returns false only when the handler could +// not be added. Called once, from main.cpp; tests call it again to start over. +inline bool install(unsigned limit) { + detail::limit.store(0, std::memory_order_relaxed); + if (detail::veh) RemoveVectoredExceptionHandler(detail::veh); + detail::veh = nullptr; + detail::claimed.store(0, std::memory_order_relaxed); + detail::exhausted_logged.store(false, std::memory_order_relaxed); + if (limit == 0) return true; + detail::limit.store(limit, std::memory_order_relaxed); + detail::veh = AddVectoredExceptionHandler(0, &detail::handler); // last: the other handlers see it first + if (!detail::veh) detail::limit.store(0, std::memory_order_relaxed); + return detail::veh != nullptr; +} + +// int3 stepped over since install. +inline unsigned skipped() { + const unsigned claimed = detail::claimed.load(std::memory_order_relaxed); + const unsigned max = detail::limit.load(std::memory_order_relaxed); + return claimed < max ? claimed : max; +} + +} // namespace rt::assert_skip diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index f44eb2535a..ad17dd3b0d 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -176,6 +176,7 @@ void start_title_peek(std::uint8_t* base) { } // namespace +#include "assert_skip.h" #include "avx2_emulation.h" #include "base_reservation.h" #include "compile_gate_policy.h" @@ -576,6 +577,17 @@ int wmain(int argc, wchar_t** argv) { if (!rt::avx2_emulation::install()) std::fprintf(stderr, "[rt] cpu: AddVectoredExceptionHandler (AVX2) failed (error %lu); instructions this CPU " "lacks will stop the game\n", GetLastError()); + // LEONIDA_SKIP_ASSERTS=N (src/assert_skip.h): up to N int3 in guest code are logged and stepped over. Off unless + // set; installed before the first TLS callback, the first image code that runs. + if (init || run) + if (const unsigned skip_asserts = rt::assert_skip::limit_from_environment()) { + if (rt::assert_skip::install(skip_asserts)) + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS=%u: up to %u int3 in guest code are stepped over " + "(diagnostic)\n", skip_asserts, skip_asserts); + else + std::fprintf(stderr, "[rt] LEONIDA_SKIP_ASSERTS: AddVectoredExceptionHandler failed (error %lu); off\n", + GetLastError()); + } try { rt::Loader loader(game_dir); diff --git a/runtime/test/assert_skip_test.cpp b/runtime/test/assert_skip_test.cpp new file mode 100644 index 0000000000..6715fa2d79 --- /dev/null +++ b/runtime/test/assert_skip_test.cpp @@ -0,0 +1,135 @@ +// LEONIDA_SKIP_ASSERTS=N (src/assert_skip.h), with synthetic code only: +// - the value: unset, empty and 0 are off; a decimal number up to 1000000 is the limit; anything else is off; +// - off, nothing is installed and an int3 reaches the next handler as before; +// - on, an int3 in memory no host module owns (a page this test writes, as the loader maps a game image) is +// stepped over, logged with its address, and the code after it runs; +// - only N of them: the next one is passed on, as are an int3 in a host module (this executable's own +// __debugbreak) and a breakpoint whose address holds no 0xCC (the two-byte `int 3`). +// A fallback vectored handler added after the one under test stands in for "the run ends": it counts what reaches it +// and steps over it, so the test keeps going. No game data, no mapped images. +#include + +#include +#include +#include + +#include "assert_skip.h" + +namespace { + +int g_failed = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "ok " : "FAIL ", what); + if (!ok) ++g_failed; +} + +// What the handler under test passed on. +volatile LONG g_passed_on = 0; +// What it saw for RIP in the first breakpoint (Windows and Wine report the 0xCC's own address). +volatile LONG g_rip_at_int3 = -1; + +LONG CALLBACK fallback(EXCEPTION_POINTERS* info) { + if (info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT) return EXCEPTION_CONTINUE_SEARCH; + const auto at = reinterpret_cast(info->ExceptionRecord->ExceptionAddress); + InterlockedIncrement(&g_passed_on); + if (g_rip_at_int3 < 0) InterlockedExchange(&g_rip_at_int3, info->ContextRecord->Rip == at ? 1 : 0); + if (info->ContextRecord->Rip == at) info->ContextRecord->Rip += 1; // over the one-byte int3 + return EXCEPTION_CONTINUE_EXECUTION; +} + +// int3; mov eax, imm32; ret. The value shows that the code after the int3 ran. +using Site = int (*)(); +Site write_site(unsigned char* at, std::uint32_t value) { + const unsigned char code[] = {0xCC, 0xB8, 0, 0, 0, 0, 0xC3}; + std::memcpy(at, code, sizeof code); + std::memcpy(at + 2, &value, sizeof value); + return reinterpret_cast(at); +} + +__declspec(noinline) int host_int3() { + __debugbreak(); + return 7; +} + +} // namespace + +int main() { + SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + std::setvbuf(stdout, nullptr, _IONBF, 0); + namespace as = rt::assert_skip; + + bool valid = false; + check(as::parse_limit(nullptr, &valid) == 0 && valid, "a null value is off"); + check(as::parse_limit(L"", &valid) == 0 && valid, "an empty value is off"); + check(as::parse_limit(L"0", &valid) == 0 && valid, "0 is off"); + check(as::parse_limit(L"3", &valid) == 3 && valid, "3 is a limit of 3"); + check(as::parse_limit(L"1000000", &valid) == 1000000 && valid, "1000000 is the largest limit"); + check(as::parse_limit(L"1000001", &valid) == 0 && !valid, "1000001 is refused"); + check(as::parse_limit(L"-1", &valid) == 0 && !valid, "a negative number is refused"); + check(as::parse_limit(L" 2", &valid) == 0 && !valid, "a leading space is refused"); + check(as::parse_limit(L"2x", &valid) == 0 && !valid, "trailing text is refused"); + check(as::parse_limit(L"yes", &valid) == 0 && !valid, "text is refused"); + SetEnvironmentVariableW(L"LEONIDA_SKIP_ASSERTS", nullptr); + check(as::limit_from_environment() == 0, "unset in the environment: off"); + SetEnvironmentVariableW(L"LEONIDA_SKIP_ASSERTS", L"2"); + check(as::limit_from_environment() == 2, "LEONIDA_SKIP_ASSERTS=2 in the environment: 2"); + SetEnvironmentVariableW(L"LEONIDA_SKIP_ASSERTS", L"many"); + check(as::limit_from_environment() == 0, "LEONIDA_SKIP_ASSERTS=many in the environment: off"); + + // Executable memory no host module owns, the way the loader maps a title's image. + auto* page = static_cast( + VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); + check(page != nullptr, "allocate an executable page"); + if (!page) return 1; + HMODULE owner = nullptr; + check(!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(page), &owner), + "the page is in no host module"); + const Site a = write_site(page, 0x41); + const Site b = write_site(page + 16, 0x42); + const Site c = write_site(page + 32, 0x43); + FlushInstructionCache(GetCurrentProcess(), page, 4096); + + void* const fallback_handler = AddVectoredExceptionHandler(0, &fallback); + check(fallback_handler != nullptr, "add the fallback handler"); + + // Off: the int3 reaches the fallback, which stands in for the end of the run. + check(as::install(0) && as::skipped() == 0, "install(0) adds nothing"); + check(a() == 0x41 && g_passed_on == 1, "off: a guest int3 is passed on"); + check(g_rip_at_int3 == 1, "the breakpoint's RIP is the 0xCC's own address"); + + // On, limit 2. The handler is added last, so it must come before the fallback to see anything: remove the + // fallback and add it again behind it. + RemoveVectoredExceptionHandler(fallback_handler); + check(as::install(2), "install(2) adds the handler"); + void* const fallback_again = AddVectoredExceptionHandler(0, &fallback); + check(fallback_again != nullptr, "add the fallback handler behind it"); + check(a() == 0x41 && as::skipped() == 1 && g_passed_on == 1, "the first guest int3 is stepped over"); + check(b() == 0x42 && as::skipped() == 2 && g_passed_on == 1, "the second, at another address, too"); + check(host_int3() == 7 && as::skipped() == 2 && g_passed_on == 2, "an int3 in a host module is passed on"); + check(c() == 0x43 && as::skipped() == 2 && g_passed_on == 3, "past the limit, a guest int3 is passed on"); + check(a() == 0x41 && as::skipped() == 2 && g_passed_on == 4, "and so is every later one"); + + // A breakpoint whose reported address holds no 0xCC: the two-byte `int 3` (CD 03), for which Windows and Wine + // report the byte after the CD. It is passed on, whatever the budget. + check(as::install(5), "install(5) starts over"); + RemoveVectoredExceptionHandler(fallback_again); + void* const fallback_last = AddVectoredExceptionHandler(0, &fallback); + page[48] = 0xCD; // int 3, two bytes; then the site's mov eax, 0x44; ret + page[49] = 0x03; + const Site d = reinterpret_cast(page + 48); + write_site(page + 49, 0x44); + page[49] = 0x03; // write_site's 0xCC is the second byte of the int 3 + FlushInstructionCache(GetCurrentProcess(), page, 4096); + const LONG before = g_passed_on; + check(d() == 0x44 && as::skipped() == 0 && g_passed_on == before + 1, + "a breakpoint with no 0xCC at its address is passed on"); + check(b() == 0x42 && as::skipped() == 1 && g_passed_on == before + 1, "a guest int3 after a restart is stepped over"); + + as::install(0); + RemoveVectoredExceptionHandler(fallback_last); + VirtualFree(page, 0, MEM_RELEASE); + std::printf("%s\n", g_failed ? "FAILED" : "all checks passed"); + return g_failed ? 1 : 0; +} diff --git a/runtime/test/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp index 5e36d53dba..20093612fc 100644 --- a/runtime/test/fixtures/tiny_game.cpp +++ b/runtime/test/fixtures/tiny_game.cpp @@ -1,6 +1,6 @@ // A stand-in game executable for `gta6rt --run`: what a real title does in its first second, run through the // loader instead of the Windows one. Test code, not game content. Run as -// gta6rt --run tiny_game.exe -- hello 42 [tls] [eh] [stack] [game-file] [exit-code] [abort-mode] +// gta6rt --run tiny_game.exe -- hello 42 [tls] [eh] [stack] [game-file] [int3] [exit-code] [abort-mode] // It checks its arguments, a static initializer, the heap, a file round trip, a second thread, and the // xgameruntime.dll imports (answered by the shim registry: the stub DLL it links against would fail them), then // calls exit() with 0 (42 with `exit-code`) when everything held. Two checks are opt-in, by argument (CTest's @@ -12,6 +12,8 @@ // A fourth, `stack` (run_tiny_game_stack), checks that the entry thread and a thread created with dwStackSize 0 // both have 8 MB of stack: a driver compiles shaders on the game's threads (BUILD-1457). Only under gta6rt: run // natively, the second thread gets this program's own 1 MB. +// `int3` (run_tiny_game_skip_asserts) runs two soft asserts, an int3 at each of two sites followed by code that +// carries on, as a title's assert does; it passes only under LEONIDA_SKIP_ASSERTS=2 or more, which steps over them. // An `abort-*` mode installs a SIGABRT disposition and calls abort(); tiny_game_abort_test compares the exact exit // codes with a native run of the same image. No game files. // On MSVC, `eh` needs more than the unwind tables #176 registers: _CxxThrowException finds the throwing image @@ -65,6 +67,16 @@ void abort_crt_exit_handler(int) { } void abort_return_handler(int) {} +// Two int3 sites: noinline, so the optimizer cannot fold them into one. +__declspec(noinline) void soft_assert_a(volatile int& reached) { + __debugbreak(); + reached = reached + 1; +} +__declspec(noinline) void soft_assert_b(volatile int& reached) { + __debugbreak(); + reached = reached + 1; +} + // The reserved stack of the calling thread, in bytes, written to *out (a size_t). DWORD WINAPI stack_reserve(void* out) { ULONG_PTR low = 0, high = 0; @@ -180,6 +192,15 @@ int main(int argc, char** argv) { std::printf("tiny_game: SKIP GAME: file (argument game-file)\n"); } + if (has_arg(argc, argv, "int3")) { + volatile int reached = 0; + soft_assert_a(reached); + soft_assert_b(reached); + check(reached == 2, "the code after each of two int3 ran (LEONIDA_SKIP_ASSERTS stepped over them)"); + } else { + std::printf("tiny_game: SKIP int3 (argument int3)\n"); + } + if (has_arg(argc, argv, "abort-handler")) { std::signal(SIGABRT, abort_exit_handler); std::abort(); diff --git a/tools/boot_trace.py b/tools/boot_trace.py index 7a69b0ede3..3c26559ed9 100644 --- a/tools/boot_trace.py +++ b/tools/boot_trace.py @@ -502,7 +502,8 @@ def format_text(summary: dict, limit: int) -> str: if startup["file_open_failed_count"] > limit: out.append(f" ... {startup['file_open_failed_count'] - limit} more") if startup["int3_skipped"]: - out.append(f" int3 skipped (LEONIDA_SKIP_INT3, one per address): {_tail(startup['int3_skipped'], limit)}") + out.append(" int3 skipped (LEONIDA_SKIP_INT3: one per address; LEONIDA_SKIP_ASSERTS: each one): " + f"{_tail(startup['int3_skipped'], limit)}") if startup["exception_count"]: out.append(f" exceptions: {startup['exception_count']}") for exc in startup["exceptions"][:limit]: From 24d89be1739c18cfa655530c874ebe386b98ae97 Mon Sep 17 00:00:00 2001 From: Diego Luiz Becker Date: Tue, 24 Nov 2026 19:55:42 -0300 Subject: [PATCH 32/42] make_game: a run without the LEONIDA board still writes /logs/.log (MAKE-GAME-PLAIN-LOG) Only the board wrote the stage logs, so a build with --no-tui (or with stdout redirected) left nothing in /logs to read afterwards. PlainStageLogs now covers that case while the build stages run: - log() and fail() lines go to the console as before and to the running stage's log; - a command run() starts for a build stage has its stdout and stderr through one pipe: every byte goes on to the console as it arrives (a \r progress line still redraws) and every \r- or \n-ended piece to the stage's log, the same split the board uses. The child keeps the console, so Ctrl+C reaches it as before; on Ctrl+C it gets 0.25 s to stop and is then killed, as subprocess.run does; - a caller that sets its own pipes, and commands outside a build stage, keep subprocess.run; - a stage's file is opened with its first line; an unwritable folder gives one note on stderr and the build goes on without the logs. The module docstring and the --no-tui help say where the logs are in both modes. tests/test_make_game_plain_logs.py covers the cases above with real child processes. --- make_game.py | 126 ++++++++++++++++++++-- tests/test_make_game_plain_logs.py | 165 +++++++++++++++++++++++++++++ 2 files changed, 285 insertions(+), 6 deletions(-) create mode 100644 tests/test_make_game_plain_logs.py diff --git a/make_game.py b/make_game.py index 3ea912976f..769b20ab3d 100644 --- a/make_game.py +++ b/make_game.py @@ -43,14 +43,15 @@ weighted by module size, and overall weighted stage completion while they overlap). On an interactive terminal, a LEONIDA setup screen asks for --jobs and whether to overlap stages, then a -key-switchable per-stage log view (1-4 / Tab) keeps parallel output demuxed; full logs land in /logs/. -Pass --no-tui (or redirect stdout) for the plain interleaved console. +key-switchable per-stage log view (1-4 / Tab) keeps parallel output demuxed. Pass --no-tui (or redirect stdout) +for the plain interleaved console. Either way each build stage's full log lands in /logs/.log. """ import argparse import functools import glob import hashlib import json +import locale import ntpath import os import re @@ -95,6 +96,103 @@ ] +class PlainStageLogs: + """The stage logs of a build without the LEONIDA board (--no-tui, or stdout redirected). The console keeps the + plain interleaved output, and each stage's lines also go to /logs/.log, the files the board writes: + log() and fail() lines, and the output of the commands run() starts, one line per \\r- or \\n-ended piece as the + board splits it. Active (module-level _plain_logs) while run_build_stages runs. A stage's file is opened with its + first line; when the folder can't be written, one note goes to stderr and the build goes on without the logs.""" + + def __init__(self, stages: list, log_dir: str): + self.log_dir = log_dir + self.stages = tuple(stages) + self.consoles: dict = {} + self._lock = threading.Lock() + self._unwritable = False + # What a text-mode pipe decodes with, so a line reads the same as in the board's log. + self.encoding = locale.getpreferredencoding(False) + + def _console(self, stage: "str | None"): + if stage not in self.stages: + return None + with self._lock: + console = self.consoles.get(stage) + if console is None and not self._unwritable: + try: + console = self.consoles[stage] = leonida_tui.StageConsole( + stage, os.path.join(self.log_dir, f"{stage}.log")) + except OSError as e: + self._unwritable = True + print(f"cannot write the stage logs in {self.log_dir} ({e.strerror or e}); the build goes on " + "without them", file=sys.stderr, flush=True) + return console + + def __enter__(self) -> "PlainStageLogs": + global _plain_logs + _plain_logs = self + return self + + def __exit__(self, exc_type, exc, tb) -> bool: + global _plain_logs + if _plain_logs is self: + _plain_logs = None + for console in self.consoles.values(): + console.close() + if self.consoles: + print(f"stage logs in {self.log_dir}", flush=True) + return False + + def write(self, stage: "str | None", line: str) -> None: + console = self._console(stage) + if console is not None: + console.write_line(line) + + def _write_pieces(self, stage: str, data: bytes) -> bytes: + """Log each \\r- or \\n-ended piece of data (stripped, empty ones dropped); return the unended rest.""" + *ended, rest = re.split(rb"[\r\n]", data) + for piece in ended: + text = piece.decode(self.encoding, errors="replace").strip() + if text: + self.write(stage, text) + return rest + + def run(self, cmd: list, stage: str, **kw) -> int: + """Run cmd with its stdout and stderr through one pipe: every byte goes on to the console as it comes (so a + \\r progress line still redraws in place) and every piece to the stage's log. The child keeps the console, + so Ctrl+C reaches it as before. Returns the exit code.""" + console = getattr(sys.stdout, "buffer", None) + with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw) as proc: + try: + rest = b"" + while True: + chunk = proc.stdout.read1(65536) # what has arrived, not a full buffer: progress shows at once + if not chunk: + break + sys.stdout.flush() # a log() line printed by another stage's thread goes out first + if console is not None: + console.write(chunk) + console.flush() + else: + sys.stdout.write(chunk.decode(self.encoding, errors="replace")) + sys.stdout.flush() + rest = self._write_pieces(stage, rest + chunk) + self._write_pieces(stage, rest + b"\n") + except KeyboardInterrupt: # the child got the Ctrl+C too: a moment to stop on its own, as subprocess.run + try: + proc.wait(timeout=0.25) + except subprocess.TimeoutExpired: + pass + proc.kill() + raise + except BaseException: # a failed write: do not leave the child running + proc.kill() + raise + return proc.wait() + + +_plain_logs: "PlainStageLogs | None" = None + + def log(msg: str) -> None: line = f"{time.strftime('%H:%M:%S')} {msg}" board = leonida_tui.current_board() @@ -102,6 +200,8 @@ def log(msg: str) -> None: board.write(leonida_tui.current_stage(), line) return print(line, flush=True) + if _plain_logs is not None: + _plain_logs.write(leonida_tui.current_stage(), line) def fail(msg: str) -> "None": @@ -113,6 +213,8 @@ def fail(msg: str) -> "None": board.set_status(stage, "failed") # Do not print through the board's stderr proxy (would duplicate into the pane). sys.exit(1) + if _plain_logs is not None: + _plain_logs.write(leonida_tui.current_stage(), f"ERROR: {msg}") print(f"\nERROR: {msg}", file=sys.stderr) sys.exit(1) @@ -264,6 +366,17 @@ def run(args: list, hint: str = "", check: bool = True, **kw) -> int: if check and code != 0: fail(f"{os.path.basename(str(args[0]))} exited with {code}" + (f". {hint}" if hint else "")) return code + # Without the board, a build stage's commands also go to its log (PlainStageLogs), with the same rule for pipes. + stage = leonida_tui.current_stage() + if (_plain_logs is not None and stage in _plain_logs.stages and kw.get("stdout") is None + and kw.get("stderr") is None and not kw.get("capture_output")): + extra = {k: v for k, v in kw.items() + if k not in ("stdout", "stderr", "capture_output", "text", "universal_newlines", "encoding", + "errors")} + code = _plain_logs.run([str(a) for a in args], stage, **extra) + if check and code != 0: + fail(f"{os.path.basename(str(args[0]))} exited with {code}" + (f". {hint}" if hint else "")) + return code r = subprocess.run([str(a) for a in args], **kw) if check and r.returncode != 0: fail(f"{os.path.basename(str(args[0]))} exited with {r.returncode}" + (f". {hint}" if hint else "")) @@ -3466,7 +3579,7 @@ def main() -> int: "the shaders need (144, or 152 with --mesh-compute)") ap.add_argument("--no-tui", action="store_true", help="plain console logs (default when stdout is not a TTY); skip the LEONIDA setup screen " - "and per-stage log view") + "and per-stage log view (the stage logs still go to /logs)") a = ap.parse_args() if a.loop_limit is not None and not 0 <= a.loop_limit <= 0xffffffff: ap.error("--loop-limit must be in 0..4294967295") @@ -3601,9 +3714,10 @@ def main() -> int: fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3) tui_board.set_summary(f"finished in {(time.time() - t0) / 60:.0f} min") else: - run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs, - runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated, - fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3) + with PlainStageLogs(build_stages, os.path.join(work, "logs")): + run_build_stages(stages, game=game, work=work, out=out, v=v, wav=a.wav, jobs=a.jobs, + runtime_build=runtime_build, emulate=emulate, keep_emulated=keep_emulated, + fallbacks=fallbacks, overlap=overlap, sdl3=not a.no_sdl3) log(f"finished in {(time.time() - t0) / 60:.0f} min") return 0 diff --git a/tests/test_make_game_plain_logs.py b/tests/test_make_game_plain_logs.py new file mode 100644 index 0000000000..f0e25567d3 --- /dev/null +++ b/tests/test_make_game_plain_logs.py @@ -0,0 +1,165 @@ +"""make_game.py without the LEONIDA board (--no-tui, or stdout redirected) still writes /logs/.log: +log() and fail() lines and the output of the commands run() starts, which also reach the console byte for byte. +No game files needed. + + python -I tests/test_make_game_plain_logs.py +""" +import contextlib +import io +import os +import subprocess +import sys +import tempfile +import time +import unittest +from unittest.mock import patch + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) +import make_game # noqa: E402 + +leonida_tui = make_game.leonida_tui + + +def console(): + """A stdout with a byte buffer, like the real one, so the mirrored bytes can be read back.""" + return io.TextIOWrapper(io.BytesIO(), encoding="utf-8", newline="") + + +def console_bytes(stream) -> bytes: + stream.flush() + return stream.buffer.getvalue() + + +def child(code: str) -> list: + return [sys.executable, "-I", "-c", code] + + +class PlainStageLogsTest(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + self.logs_dir = os.path.join(self.dir.name, "logs") + self.assertIsNone(leonida_tui.current_board()) + + def read(self, stage: str) -> list: + with open(os.path.join(self.logs_dir, f"{stage}.log"), encoding="utf-8") as f: + return f.read().splitlines() + + def test_log_and_fail_lines_go_to_the_running_stage(self): + out = console() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): + with make_game.PlainStageLogs(["shaders", "assets"], self.logs_dir): + with leonida_tui.stage_scope("shaders"): + make_game.log("translating") + with self.assertRaises(SystemExit): + make_game.fail("llvm-mc is missing") + with leonida_tui.stage_scope("assets"): + make_game.log("exporting") + make_game.log("outside every stage") + shaders, assets = self.read("shaders"), self.read("assets") + self.assertEqual(len(shaders), 2) + self.assertTrue(shaders[0].endswith(" translating")) + self.assertEqual(shaders[1], "ERROR: llvm-mc is missing") + self.assertEqual(len(assets), 1) + self.assertTrue(assets[0].endswith(" exporting")) + text = console_bytes(out).decode() + for line in ("translating", "exporting", "outside every stage", f"stage logs in {self.logs_dir}"): + self.assertIn(line, text) + + def test_run_mirrors_the_bytes_and_logs_each_piece(self): + # A \r progress line, a \r\n ending, stderr after stdout and a last piece with no ending. The child writes + # bytes, so its own text mode (\n -> \r\n on Windows) does not change what it sends. + code = ("import sys; o, e = sys.stdout.buffer, sys.stderr.buffer; " + "o.write(b'shard 1/2\\rshard 2/2\\r\\ndone\\n'); o.flush(); e.write(b'a warning\\n'); e.flush(); " + "o.write(b'tail'); o.flush()") + out = console() + with contextlib.redirect_stdout(out): + with make_game.PlainStageLogs(["shaders"], self.logs_dir): + with leonida_tui.stage_scope("shaders"): + self.assertEqual(make_game.run(child(code)), 0) + self.assertIn(b"shard 1/2\rshard 2/2\r\ndone\na warning\ntail", console_bytes(out)) + lines = self.read("shaders") + self.assertIn(os.path.basename(sys.executable), lines[0]) # run() logs the command first + self.assertEqual(lines[1:], ["shard 1/2", "shard 2/2", "done", "a warning", "tail"]) + + def test_a_failed_command_stops_the_build_with_its_code_in_the_log(self): + with contextlib.redirect_stdout(console()), contextlib.redirect_stderr(io.StringIO()): + with make_game.PlainStageLogs(["runtime"], self.logs_dir): + with leonida_tui.stage_scope("runtime"): + self.assertEqual(make_game.run(child("import sys; sys.exit(3)"), check=False), 3) + with self.assertRaises(SystemExit): + make_game.run(child("import sys; sys.exit(4)"), hint="see the log") + self.assertEqual(self.read("runtime")[-1], f"ERROR: {os.path.basename(sys.executable)} exited with 4. " + "see the log") + + def test_caller_pipes_and_unlogged_stages_keep_subprocess_run(self): + done = subprocess.CompletedProcess([], 0) + with contextlib.redirect_stdout(console()), patch("make_game.subprocess.run", return_value=done) as plain: + with make_game.PlainStageLogs(["shaders"], self.logs_dir): + with leonida_tui.stage_scope("shaders"): + make_game.run(["tool", "a"], stdout=subprocess.PIPE) # the caller reads the output + with leonida_tui.stage_scope("check"): + make_game.run(["tool", "b"]) # not a build stage with a log + make_game.run(["tool", "c"]) # no stage at all + self.assertEqual([c.args[0] for c in plain.call_args_list], [["tool", "a"], ["tool", "b"], ["tool", "c"]]) + + def test_extra_arguments_reach_the_child(self): + with contextlib.redirect_stdout(console()): + with make_game.PlainStageLogs(["pipelines"], self.logs_dir): + with leonida_tui.stage_scope("pipelines"): + env = dict(os.environ, LEONIDA_PLAIN_LOG_TEST="from the caller") + make_game.run(child("import os; print(os.getcwd()); print(os.environ['LEONIDA_PLAIN_LOG_TEST'])"), + cwd=self.dir.name, env=env, text=True) + lines = self.read("pipelines") + self.assertEqual(os.path.normcase(lines[1]), os.path.normcase(os.path.realpath(self.dir.name))) + self.assertEqual(lines[2], "from the caller") + + def test_inactive_after_the_build_and_appends_like_the_board(self): + for word in ("first", "second"): + with contextlib.redirect_stdout(console()): + with make_game.PlainStageLogs(["assets"], self.logs_dir): + with leonida_tui.stage_scope("assets"): + make_game.log(word) + self.assertIsNone(make_game._plain_logs) + self.assertEqual([line.split(" ", 1)[1] for line in self.read("assets")], ["first", "second"]) + + def test_ctrl_c_stops_the_child(self): + # Ctrl+C while the output is pumped: the interrupt goes on, and the child does not keep running. + slow = child("import sys, time; print('started', flush=True); time.sleep(60)") + started = time.monotonic() + with contextlib.redirect_stdout(console()), \ + patch.object(make_game.PlainStageLogs, "_write_pieces", side_effect=KeyboardInterrupt): + with make_game.PlainStageLogs(["assets"], self.logs_dir): + with leonida_tui.stage_scope("assets"), self.assertRaises(KeyboardInterrupt): + make_game.run(slow) + self.assertLess(time.monotonic() - started, 20) + + def test_an_unwritable_log_folder_does_not_stop_the_build(self): + blocker = os.path.join(self.dir.name, "a file") + with open(blocker, "w", encoding="utf-8", newline="\n") as f: + f.write("not a folder\n") + out, err = console(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + with make_game.PlainStageLogs(["shaders"], os.path.join(blocker, "logs")): + with leonida_tui.stage_scope("shaders"): + make_game.log("still logged to the console") + self.assertEqual(make_game.run(child("print('child output')")), 0) + text = console_bytes(out).decode() + self.assertIn("still logged to the console", text) + self.assertIn("child output", text) + self.assertNotIn("stage logs in", text) + self.assertEqual(err.getvalue().count("cannot write the stage logs"), 1) + + def test_no_build_stage_writes_nothing(self): + out = console() + with contextlib.redirect_stdout(out): + with make_game.PlainStageLogs([], self.logs_dir): + make_game.log("check only") + self.assertFalse(os.path.exists(self.logs_dir)) + self.assertNotIn(b"stage logs in", console_bytes(out)) + + +if __name__ == "__main__": + unittest.main() From 1b33fa2bb1b9e6377aa39db1641000278c8f928d Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 16:19:56 +0200 Subject: [PATCH 33/42] d3d12: drew()'s doc comment back on drew(), not on drew_mesh_as_compute Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/draw.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 7b1cbc432d..c899535bc8 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -5668,8 +5668,6 @@ impl State { } } - /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] - /// if its shaders can store to buffers). /// [`Self::drew`] for a mesh pipeline run as compute and a draw: the /// mesh program's own stores (to title buffers; its outputs to the mesh /// buffer are not counted) as well as the draw's. @@ -5680,6 +5678,8 @@ impl State { } } + /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] + /// if its shaders can store to buffers). fn drew(&mut self, p: Option<&HostPipeline>) { if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) { // (With 4 a known pipeline's stores are told apart by address, if they are all From 48ca87fa24e4e04ea736b0e800f9d71cce631016 Mon Sep 17 00:00:00 2001 From: Diego Luiz Becker Date: Sun, 29 Nov 2026 11:23:16 -0300 Subject: [PATCH 34/42] make_game: the plain stage logs show a command's output as decoded text, in the caller's encoding (MAKE-GAME-PLAIN-LOG) PlainStageLogs passed a command's raw bytes to sys.stdout.buffer. A Windows console's buffer takes UTF-8, so non-ASCII text a command wrote in its own code page showed U+FFFD on screen, where main's --no-tui (the command inheriting the console) shows it right. Measured in a console with OEM 850 / ANSI 1252: a child writing cp850 "n\xc6o par\x83metro" showed "n\ufffdo par\ufffdmetro". - run() decodes the output once as it arrives (an incremental decoder, so a character split between two reads stays whole) and sends that text to the console, encoded for sys.stdout with errors="replace", and to the log; - the encoding is the one the caller names with run(..., encoding=), else what a text-mode pipe decodes with, as on the board. Three new tests: the caller's encoding on the console and in the log, a UTF-8 character split between reads, and a character the console's code page lacks. --- make_game.py | 53 +++++++++++++++++++----------- tests/test_make_game_plain_logs.py | 48 ++++++++++++++++++++++++--- 2 files changed, 76 insertions(+), 25 deletions(-) diff --git a/make_game.py b/make_game.py index 769b20ab3d..cbfddac330 100644 --- a/make_game.py +++ b/make_game.py @@ -47,6 +47,7 @@ for the plain interleaved console. Either way each build stage's full log lands in /logs/.log. """ import argparse +import codecs import functools import glob import hashlib @@ -101,7 +102,8 @@ class PlainStageLogs: plain interleaved output, and each stage's lines also go to /logs/.log, the files the board writes: log() and fail() lines, and the output of the commands run() starts, one line per \\r- or \\n-ended piece as the board splits it. Active (module-level _plain_logs) while run_build_stages runs. A stage's file is opened with its - first line; when the folder can't be written, one note goes to stderr and the build goes on without the logs.""" + first line; when the folder can't be written, one note goes to stderr and the build goes on without the logs. + A command's output is decoded once, and the console and the log both get that text.""" def __init__(self, stages: list, log_dir: str): self.log_dir = log_dir @@ -147,36 +149,46 @@ def write(self, stage: "str | None", line: str) -> None: if console is not None: console.write_line(line) - def _write_pieces(self, stage: str, data: bytes) -> bytes: + def _write_pieces(self, stage: str, data: str) -> str: """Log each \\r- or \\n-ended piece of data (stripped, empty ones dropped); return the unended rest.""" - *ended, rest = re.split(rb"[\r\n]", data) + *ended, rest = re.split(r"[\r\n]", data) for piece in ended: - text = piece.decode(self.encoding, errors="replace").strip() + text = piece.strip() if text: self.write(stage, text) return rest - def run(self, cmd: list, stage: str, **kw) -> int: - """Run cmd with its stdout and stderr through one pipe: every byte goes on to the console as it comes (so a - \\r progress line still redraws in place) and every piece to the stage's log. The child keeps the console, - so Ctrl+C reaches it as before. Returns the exit code.""" - console = getattr(sys.stdout, "buffer", None) + @staticmethod + def _echo(text: str) -> None: + """Show a command's text on the console as it wrote it (\\r and \\r\\n kept), in the console's encoding: a + Windows console's sys.stdout.buffer takes UTF-8, so the command's own OEM or ANSI bytes would show wrong.""" + sys.stdout.flush() # a log() line printed by another stage's thread goes out first + buffer = getattr(sys.stdout, "buffer", None) + if buffer is None: + sys.stdout.write(text) + sys.stdout.flush() + return + buffer.write(text.encode(sys.stdout.encoding or "utf-8", errors="replace")) + buffer.flush() + + def run(self, cmd: list, stage: str, encoding: "str | None" = None, **kw) -> int: + """Run cmd with its stdout and stderr through one pipe. Its output is decoded as it comes, with encoding (the + one the command writes in; by default what a text-mode pipe decodes with, as on the board), then goes on to + the console (so a \\r progress line still redraws in place) and piece by piece to the stage's log. The child + keeps the console, so Ctrl+C reaches it as before. Returns the exit code.""" + decoder = codecs.getincrementaldecoder(encoding or self.encoding)(errors="replace") with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw) as proc: try: - rest = b"" + rest = "" while True: chunk = proc.stdout.read1(65536) # what has arrived, not a full buffer: progress shows at once + text = decoder.decode(chunk, final=not chunk) # a character split between reads waits for the rest + if text: + self._echo(text) + rest = self._write_pieces(stage, rest + text) if not chunk: break - sys.stdout.flush() # a log() line printed by another stage's thread goes out first - if console is not None: - console.write(chunk) - console.flush() - else: - sys.stdout.write(chunk.decode(self.encoding, errors="replace")) - sys.stdout.flush() - rest = self._write_pieces(stage, rest + chunk) - self._write_pieces(stage, rest + b"\n") + self._write_pieces(stage, rest + "\n") except KeyboardInterrupt: # the child got the Ctrl+C too: a moment to stop on its own, as subprocess.run try: proc.wait(timeout=0.25) @@ -373,7 +385,8 @@ def run(args: list, hint: str = "", check: bool = True, **kw) -> int: extra = {k: v for k, v in kw.items() if k not in ("stdout", "stderr", "capture_output", "text", "universal_newlines", "encoding", "errors")} - code = _plain_logs.run([str(a) for a in args], stage, **extra) + # A caller's encoding= names what the command writes in; the log and the console get the decoded text. + code = _plain_logs.run([str(a) for a in args], stage, encoding=kw.get("encoding"), **extra) if check and code != 0: fail(f"{os.path.basename(str(args[0]))} exited with {code}" + (f". {hint}" if hint else "")) return code diff --git a/tests/test_make_game_plain_logs.py b/tests/test_make_game_plain_logs.py index f0e25567d3..e3dca8d205 100644 --- a/tests/test_make_game_plain_logs.py +++ b/tests/test_make_game_plain_logs.py @@ -1,6 +1,6 @@ """make_game.py without the LEONIDA board (--no-tui, or stdout redirected) still writes /logs/.log: -log() and fail() lines and the output of the commands run() starts, which also reach the console byte for byte. -No game files needed. +log() and fail() lines and the output of the commands run() starts, which also reach the console as the same text, +in the console's own encoding. No game files needed. python -I tests/test_make_game_plain_logs.py """ @@ -22,9 +22,10 @@ leonida_tui = make_game.leonida_tui -def console(): - """A stdout with a byte buffer, like the real one, so the mirrored bytes can be read back.""" - return io.TextIOWrapper(io.BytesIO(), encoding="utf-8", newline="") +def console(encoding: str = "utf-8"): + """A stdout with a byte buffer, like the real one (a Windows console's takes UTF-8), so what reached it can be + read back.""" + return io.TextIOWrapper(io.BytesIO(), encoding=encoding, newline="") def console_bytes(stream) -> bytes: @@ -84,6 +85,43 @@ def test_run_mirrors_the_bytes_and_logs_each_piece(self): self.assertIn(os.path.basename(sys.executable), lines[0]) # run() logs the command first self.assertEqual(lines[1:], ["shard 1/2", "shard 2/2", "done", "a warning", "tail"]) + def test_the_console_and_the_log_get_the_text_in_the_callers_encoding(self): + # A command that writes in an 8-bit code page (cp1252 here: "não parâmetro"). Its raw bytes on a console + # that takes UTF-8 would show U+FFFD; decoded with the encoding the caller names, both get the same text. + code = "import sys; sys.stdout.buffer.write(b'n\\xe3o par\\xe2metro\\r\\n'); sys.stdout.flush()" + out = console() + with contextlib.redirect_stdout(out): + with make_game.PlainStageLogs(["runtime"], self.logs_dir): + with leonida_tui.stage_scope("runtime"): + self.assertEqual(make_game.run(child(code), encoding="cp1252"), 0) + self.assertIn("não parâmetro\r\n".encode("utf-8"), console_bytes(out)) + self.assertEqual(self.read("runtime")[1:], ["não parâmetro"]) + + def test_a_character_split_between_reads_is_decoded_whole(self): + # The two bytes of a UTF-8 "ã" arrive in two reads: neither the console nor the log gets a broken half. + code = ("import sys, time; o = sys.stdout.buffer; o.write(b'n\\xc3'); o.flush(); time.sleep(0.3); " + "o.write(b'\\xa3o\\n'); o.flush()") + out = console() + with contextlib.redirect_stdout(out): + with make_game.PlainStageLogs(["runtime"], self.logs_dir): + with leonida_tui.stage_scope("runtime"): + make_game.run(child(code), encoding="utf-8") + self.assertIn("não\n".encode("utf-8"), console_bytes(out)) + self.assertEqual(self.read("runtime")[1:], ["não"]) + + def test_a_character_the_console_cannot_show_is_replaced(self): + # A redirected stdout in an 8-bit code page has no Cyrillic: the console gets "?", the log the text, and the + # build goes on. (The child's code spells the word with escapes, so the logged command line stays ASCII.) + code = ("import sys; sys.stdout.buffer.write('\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442\\n'.encode('utf-8')); " + "sys.stdout.flush()") + out = console("cp1252") + with contextlib.redirect_stdout(out): + with make_game.PlainStageLogs(["runtime"], self.logs_dir): + with leonida_tui.stage_scope("runtime"): + self.assertEqual(make_game.run(child(code), encoding="utf-8"), 0) + self.assertIn(b"??????\n", console_bytes(out)) + self.assertEqual(self.read("runtime")[1:], ["Привет"]) + def test_a_failed_command_stops_the_build_with_its_code_in_the_log(self): with contextlib.redirect_stdout(console()), contextlib.redirect_stderr(io.StringIO()): with make_game.PlainStageLogs(["runtime"], self.logs_dir): From e1e78f34c00f6dc3c4bfc0f20cdd1aa9059efdd7 Mon Sep 17 00:00:00 2001 From: fiestorra Date: Wed, 25 Nov 2026 14:48:29 +0100 Subject: [PATCH 35/42] SHADER-VCC-BASE-GPU-VERIFIED: the vcc base row is GPU-checked on RDNA2 and under wave64 emulation --- docs/design.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design.md b/docs/design.md index fa7e34a4eb..d11c332069 100644 --- a/docs/design.md +++ b/docs/design.md @@ -300,7 +300,7 @@ How the generated SPIR-V expects the runtime to work: |---|---| | Heap-relative buffer device addresses | `Gen.host_addr` sign-extends the low 48 bits of the effective VA after adding any byte offset, then adds `%heap_base`. The runtime stores `device_address - heap_base` in a V#'s 48-bit base field. NVIDIA's Windows driver can place an imported buffer below the heap, so that offset is negative. Zero extension made the resulting device address too high by `2^48`. Console user-mode VAs below `2^47` and full-width root descriptor addresses already within the signed 48-bit range retain their values. A 64-bit base-plus-offset sum gives the correct address for effective VAs in that range, including when the sum crosses zero. Each new shader's `index.json` entry carries `"vsharp_base_sign_extended": true`. Check the field on all loaded entries before enabling below-arena imports for a library, because older modules can share an index with newly translated ones. `tests/semantic/test_vsharp_sext48.py` checks the emitted shifts, both reads against synthetic memory, and the metadata field. | | Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | -| `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`) and `tests/semantic/test_scalar_mem_smem.py` (both halves and the resulting addresses); **not GPU-verified**: the synthetic `runtime/test/shaders/cs_smem_vcc_base.asm` reads back eight seeded words through the pair in the standard GPU runner. | +| `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`) and `tests/semantic/test_scalar_mem_smem.py` (both halves and the resulting addresses); **GPU-checked** with the synthetic `runtime/test/shaders/cs_smem_vcc_base.asm`, which reads back the eight seeded words through the pair in the standard GPU runner (`0x7210..0x7217`): on an AMD Radeon gfx1036 iGPU (Ryzen 7 7800X3D, Windows 11, driver 32.0.21045.29003) and, under `LEONIDA_W64_EMULATE=1`, on an NVIDIA GeForce RTX 4090 (Windows 11, driver 32.0.16.2124); without the emulation the fixture skips on the 4090 (no 64-wide compute subgroup). Still not measured: those eight words of one fixture are the whole hardware check, the 79-program corpus count stays a translation count, and there is no native 32-wide-subgroup run of this form. | | Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. | | DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. Hardware applies src0 float modifiers (`neg`/`abs`) after the invalid-lane zero selection, so `-src0` on an invalid lane yields `-0.0f` (`0x80000000`) and `\|src0\|` yields `+0.0f` (HW-DPP-NEG-INVALID-LANE, measured on RDNA3 (gfx1101) RX 7800 XT, RDNA2 not measured; tested by `tests/semantic/test_dpp_bound_ctrl_modifiers.py`). A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. For native FI=0, the source-lane ballot bit also selects the shuffle index: an absent or EXEC-off source is redirected to the current subgroup lane before `OpGroupNonUniformShuffle`, because masking an undefined shuffle result afterwards is not sufficient; FI=1 is unchanged. CPU-checked by `tests/semantic/test_dpp_eager_subgroup.py::test_fi0_shuffle_index_is_ballot_safe` with a hand-written `quad_perm` case whose active lane 6 reads absent lane 7 in a seven-invocation wave; **not GPU-verified**. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | | DPP on a VOPC compare | A VOPC compare whose src0 field is a DPP marker (250 for DPP16, 233/234 for DPP8) takes src0 through the DPP lane selection of the row above and writes VCC: a lane's bit is `compare(src0 of the selected lane, its own src1)`, with 0 for src0 when the selected lane is out of its row or inactive (`bound_ctrl` 1, or DPP8 with `fi` 0). The second word has the layout of a VOP2's DPP word. `llvm-mc` has no decoding for it on gfx10 (LLVM 21.1.8 rejects the first word for `gfx1013`; LLVM defines the form from GFX11 on), so `tools/shader_disasm.py` prints it: it decodes the pair with the first word turned into `v_max_f32` into `v0`, which takes the same second word, and gives the line the compare's name, a `vcc_lo` destination and the real encoding back (`with_vopc_dpp`); `tools/rdna2_decode.py` decodes it directly. **Only the forms where every lane writes its bit are translated**: `row_mask` and `bank_mask` 0xF and either `bound_ctrl` 1 or DPP8. Any other form is refused (`DPP compare with lanes DPP leaves unwritten`), because what such a lane writes is measured only on RDNA3, not on RDNA2. On RDNA3 (gfx1101, RX 7800 XT, `tools/hw_oracle`, wave32 and wave64; [measurement](https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7161289307)) a lane DPP leaves unwritten does not keep its bit: `v_cmp` writes 0 to its VCC bit and `v_cmpx` turns it off in EXEC. That holds for an invalid source with `bound_ctrl` 0, and for a lane `row_mask` or `bank_mask` turns off, even with `bound_ctrl` 1. Translating these forms on RDNA2 (gfx1013) would need the same measurement there. `v_cmpx` in DPP form takes the same lane selection and the same forms, and writes EXEC as the plain `v_cmpx` does (a lane that was off stays off); it prints no destination, so its src0 is the first operand (SHADER-VOPCX-DPP). Found in 3 of the 2,684 pipeline-library compute programs of 1.0.2.1: 4 `v_cmp_gt_f32` each, with `quad_perm:[1,0,3,2]`, `quad_perm:[2,3,0,1]`, `row_ror:8` (all `bound_ctrl:1`, masks 0xF) and `dpp8:[4,5,6,7,0,1,2,3]`, beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` on the same lanes. `v_cmpx` in DPP form is in 78 of the 18,837 graphics programs of the pipeline library (all pixel shaders, 113 instructions), all `v_cmpx_gt_f32_dpp vN, -vM quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf bound_ctrl:1 fi:1`, a compare against the lane two above or below in its quad. **Not measured on RDNA2 hardware**: the rule follows from the encoding, from LLVM's GFX11 definition of the same form and from the VOP2 DPP rules measured in the row above; the sweep that measured those (`tools/crosslane_fuzz.py --dpp-sweep --oracle hw`) does not cover compares. The RDNA3 measurement above also ran the translated forms (`bound_ctrl` 1, masks 0xF): an invalid source lane gets the compare of a 0 source, as the rule says. Lane values are checked in `tests/semantic/test_dpp_compare.py` (the SPIR-V interpreter) and on a GPU with `runtime/test/shaders/cs_dpp_cmp.asm` and, for `v_cmpx`, `cs_dpp_cmpx.asm` (RTX 4070 Laptop, native wave32 and `--wave64-emulate`). | From 3e0f3074c4081a543beab9bae8bfd31d477dd0b4 Mon Sep 17 00:00:00 2001 From: Andrey Date: Tue, 24 Nov 2026 18:03:04 +0300 Subject: [PATCH 36/42] manifest_verifier: restore write mode before unlink on replace failure and publish mode (MANIFEST-VERIFIER-STAGE-CLEANUP) Apply published_mode(path) to temporary cache file before atomic replacement, and restore write permission (0o600) before unlink in exception block when replace fails, preventing Windows PermissionError [WinError 5] and stranded temporary cache files. agent: yes AI-assisted: yes --- tests/test_manifest_verifier.py | 18 ++++++++++++++++++ tools/manifest_verifier.py | 8 ++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/tests/test_manifest_verifier.py b/tests/test_manifest_verifier.py index 1a93a12bce..456e8d2004 100644 --- a/tests/test_manifest_verifier.py +++ b/tests/test_manifest_verifier.py @@ -1132,6 +1132,24 @@ def test_cli_cache_flag(self) -> None: with open(self.cache, "rb") as f: self.assertNotIn(b"\r\n", f.read()) + def test_save_cache_stage_cleanup_restores_write_mode_on_replace_failure(self) -> None: + chmod_calls = [] + real_chmod = os.chmod + + def track_chmod(path, mode, *args, **kwargs): + chmod_calls.append((str(path), mode)) + return real_chmod(path, mode, *args, **kwargs) + + with patch("os.replace", side_effect=OSError("replace failed")), \ + patch("os.chmod", side_effect=track_chmod): + with self.assertRaisesRegex(OSError, "replace failed"): + mv.save_cache(self.cache, {"foo": {"stamp": [1, 2, 3, 4, 5], "sha256": "abc"}}) + + self.assertTrue(any(mode == 0o600 for _, mode in chmod_calls), chmod_calls) + cache_dir = os.path.dirname(self.cache) + leftover = [f for f in os.listdir(cache_dir) if f.startswith(".verify-cache-")] + self.assertEqual(leftover, []) + class TestSaveVerifyCache(unittest.TestCase): def setUp(self) -> None: diff --git a/tools/manifest_verifier.py b/tools/manifest_verifier.py index eff896a0b0..d5d7fe78cc 100644 --- a/tools/manifest_verifier.py +++ b/tools/manifest_verifier.py @@ -30,6 +30,7 @@ import unicodedata from typing import Callable, Optional, TextIO +# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from file_mode import published_mode # noqa: E402 from report_paths import case_insensitive_volume, path_key, same_report_path # noqa: E402 @@ -161,11 +162,14 @@ def save_cache(path: str, entries: dict[str, dict]) -> None: ) as f: tmp = f.name json.dump({"version": CACHE_VERSION, "files": dict(sorted(entries.items()))}, f, indent=1) - if os.name != "nt": - os.chmod(tmp, published_mode(path)) # do not publish NamedTemporaryFile's private 0600 mode + os.chmod(tmp, published_mode(path)) os.replace(tmp, path) except BaseException: if tmp is not None: + try: + os.chmod(tmp, 0o600) + except OSError: + pass try: os.unlink(tmp) except OSError: From 6d5a3ba26039ee6c4771f5c2b0efeba70454c6a6 Mon Sep 17 00:00:00 2001 From: Bloh09 <104168236+Bloh09@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:02:08 -0800 Subject: [PATCH 37/42] windows-boot: test_crash_monitor reads its text files as UTF-8 (text-encoding lint red on main since 1b9e4969) --- scripts/windows-boot/test_crash_monitor.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/windows-boot/test_crash_monitor.py b/scripts/windows-boot/test_crash_monitor.py index 140a870abe..fffda8e30b 100644 --- a/scripts/windows-boot/test_crash_monitor.py +++ b/scripts/windows-boot/test_crash_monitor.py @@ -34,7 +34,7 @@ def check_artifacts(self, code, exception): streams = dict((kind, pos) for kind, size, pos in (struct.unpack_from(" Date: Sun, 29 Nov 2026 09:05:17 -0800 Subject: [PATCH 38/42] windows-boot: test_crash_monitor tolerates code-page module names in stack.txt --- scripts/windows-boot/test_crash_monitor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/windows-boot/test_crash_monitor.py b/scripts/windows-boot/test_crash_monitor.py index fffda8e30b..a28af6380e 100644 --- a/scripts/windows-boot/test_crash_monitor.py +++ b/scripts/windows-boot/test_crash_monitor.py @@ -34,7 +34,7 @@ def check_artifacts(self, code, exception): streams = dict((kind, pos) for kind, size, pos in (struct.unpack_from(" Date: Sun, 29 Nov 2026 19:20:44 +0200 Subject: [PATCH 39/42] d3d12: MeshOut::new is crate-private, as SigElement it takes Both callers are in leonida-shader; a public constructor taking a crate-private type set off private_interfaces. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-shader/src/emit/shader.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-shader/src/emit/shader.rs b/d3d12/crates/leonida-shader/src/emit/shader.rs index 9e36a38de5..9c0d1a30ee 100644 --- a/d3d12/crates/leonida-shader/src/emit/shader.rs +++ b/d3d12/crates/leonida-shader/src/emit/shader.rs @@ -257,7 +257,7 @@ pub struct MeshOut { impl MeshOut { /// The layout for these maxima and signatures. - pub fn new(max_vertices: u32, max_primitives: u32, outputs: &[SigElement], prims: &[SigElement]) -> Self { + pub(crate) fn new(max_vertices: u32, max_primitives: u32, outputs: &[SigElement], prims: &[SigElement]) -> Self { let place = |first: u32, elements: &[SigElement]| { let mut at = Vec::with_capacity(elements.len()); let mut next = first; From 924b29417548d7798febe17bca99bf91790238c3 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 20:28:04 +0200 Subject: [PATCH 40/42] d3d12: the mesh fallback's recording in one place, tested in one list on a device The commands the mesh fallback records between and after the pipelines the draw path binds (barriers, the dispatch or counted indirect dispatch, the header of the indirect draw, the triangle list drawn from the buffer, the title's topology again) move from draw.rs into mesh_fallback::MeshRun, which draw.rs calls. A test records the same commands on a device of its own, as a title does in one list: a counted indirect run (count 1), a direct run of three groups, a run whose triangle is culled, a counted indirect run with a count of 0, then the title's triangle strip; every texel comes out as the runs and the strip draw it. Without the topology restored the strip draws one triangle (64 texels differ); without the header's instance count reset the count-0 run draws the first run's groups again (100 differ). leonida-shader's host checks (emit::host) take the test programs this needs: triangle_mesh_program (the triangle mesh program its own tests used), color_ps and position_vs; dxbc::build is there for them too. draw.rs names its topology mapping (host_topology). Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/Cargo.toml | 2 + d3d12/crates/leonida-gpu/src/draw.rs | 162 ++++----- d3d12/crates/leonida-gpu/src/lib.rs | 2 + d3d12/crates/leonida-gpu/src/mesh_fallback.rs | 149 ++++++++ .../leonida-gpu/src/mesh_fallback/tests.rs | 335 ++++++++++++++++++ d3d12/crates/leonida-shader/src/dxbc.rs | 4 +- d3d12/crates/leonida-shader/src/emit/host.rs | 149 ++++++++ d3d12/crates/leonida-shader/src/emit/mod.rs | 102 +----- 8 files changed, 708 insertions(+), 197 deletions(-) create mode 100644 d3d12/crates/leonida-gpu/src/mesh_fallback.rs create mode 100644 d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs diff --git a/d3d12/crates/leonida-gpu/Cargo.toml b/d3d12/crates/leonida-gpu/Cargo.toml index b7806fe009..03e00b25cd 100644 --- a/d3d12/crates/leonida-gpu/Cargo.toml +++ b/d3d12/crates/leonida-gpu/Cargo.toml @@ -24,6 +24,8 @@ blake3.workspace = true [dev-dependencies] tempfile.workspace = true +# The host checks' device and shaders (`emit::host`) for the mesh fallback's test. +leonida-shader = { workspace = true, features = ["host"] } [features] # Debugging switches (frame capture, the host debug layer, per-draw data). diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index c899535bc8..e28559a155 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -67,6 +67,15 @@ fn is_depth_companion(stencil: &View, depth: &View) -> bool { && s[7] == d[7] } +/// The host topology a title's draws with `topology` go out with: the +/// console's rectangles, fans, loops and quads as triangle lists. +fn host_topology(topology: u32) -> u32 { + match topology { + RECTANGLES | TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => 4, + t => t, + } +} + /// The device-local buffer mesh programs run as compute write to /// ([`leonida_shader::emit::MESH_OUT_BYTES`], made once; it starts and ends /// each use in the common state). @@ -1980,14 +1989,10 @@ impl State { pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { self.topology = topology; self.topology_set = true; - let host = match topology { - RECTANGLES => 4, - TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { - once!(topology, "console topology drawn as a triangle list"); - 4 - } - t => t, - }; + if matches!(topology, TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP) { + once!(topology, "console topology drawn as a triangle list"); + } + let host = host_topology(topology); // SAFETY: an open list. unsafe { list.list @@ -1995,14 +2000,6 @@ impl State { }; } - /// The title's topology on the list again, after a pass of ours set - /// another (the mesh fallback's triangle list). - fn restore_topology(&mut self, list: &HostList) { - if self.topology_set { - self.set_topology(list, self.topology); - } - } - pub(crate) fn set_pipeline(&mut self, pipeline: This) { self.pipeline = pipeline as usize; } @@ -4678,60 +4675,54 @@ impl State { once!("no mesh buffer: the mesh draw is dropped"); return false; }; - let l = &list.list; self.title_side_graphics = true; let bound = self.bind(list, &mc.cs, true); self.title_side_graphics = false; if !bound { return false; } - use windows::Win32::Graphics::Direct3D12::{ - D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - }; + let run = self.mesh_run(list, &buffer, mc); // SAFETY: an open list, a live buffer and the compute pipeline bound. - unsafe { - l.ResourceBarrier(&[crate::host::transition( - &buffer, - D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - )]); - l.SetComputeRootUnorderedAccessView(mc.out_param, buffer.GetGPUVirtualAddress()); - l.Dispatch(n, 1, 1); - l.ResourceBarrier(&[crate::host::transition( - &buffer, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )]); - } - // The compute pipeline took the list's pipeline slot. - self.host_pipeline = 0; - let drawn = self.prepare_for(list, false, true); - // SAFETY: as above, the graphics pipeline bound when `drawn`. - unsafe { - if drawn { - self.mesh_scissor(list, true); - l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); - l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - // Instances from the cap on would read the sink slot. - l.DrawInstanced(mc.layout.max_primitives * 3, n.min(mc.layout.groups_cap()), 0, 0); - self.mesh_scissor(list, false); - } - l.ResourceBarrier(&[crate::host::transition( - &buffer, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - D3D12_RESOURCE_STATE_COMMON, - )]); - } - // The fallback drew a triangle list: the title's next draw has its - // own topology again. + let drawn = unsafe { + run.direct(n, || { + // The compute pipeline took the list's pipeline slot. + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + if drawn { + self.mesh_scissor(list, true); + } + drawn + }) + }; if drawn { - self.restore_topology(list); + self.mesh_scissor(list, false); } list.keep(&buffer); drawn } + /// The recorder of a mesh run on `list` ([`crate::mesh_fallback`]): it + /// sets the title's topology again after its triangle list, for the + /// title's next draw. + fn mesh_run<'a>( + &self, + list: &'a HostList, + buffer: &'a ID3D12Resource, + mc: &crate::pipeline::host::MeshCompute, + ) -> crate::mesh_fallback::MeshRun<'a> { + crate::mesh_fallback::MeshRun { + list: &list.list, + buffer, + out_param: mc.out_param, + in_param: mc.in_param, + max_primitives: mc.layout.max_primitives, + groups_cap: mc.layout.groups_cap(), + restore: self + .topology_set + .then(|| windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(host_topology(self.topology) as i32)), + } + } + /// [`Self::mesh_as_compute`] for one indirect record: the record's /// `(x, y, z)` is a dispatch's arguments as it stands (`stride` apart), /// so the compute pipeline runs it as recorded; its groups raise the @@ -4754,55 +4745,30 @@ impl State { once!("no mesh buffer: the mesh draw is dropped"); return false; }; - let Ok(l2) = list.list.cast::() else { - return false; - }; self.title_side_graphics = true; let bound = self.bind(list, &mc.cs, true); self.title_side_graphics = false; if !bound { return false; } - use windows::Win32::Graphics::Direct3D12::{ - D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, - }; - let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; - let l = &list.list; + let run = self.mesh_run(list, &buffer, mc); // SAFETY: an open list, live buffers and the compute pipeline bound. - unsafe { - let va = buffer.GetGPUVirtualAddress(); - l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); - let header = [mc.layout.max_primitives * 3, 0, 0, 0].map(|v| v); - let params: Vec = header - .iter() - .enumerate() - .map(|(k, &value)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: va + 4 * k as u64, Value: value }) - .collect(); - l2.WriteBufferImmediate(params.len() as u32, params.as_ptr(), None); - l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); - l.SetComputeRootUnorderedAccessView(mc.out_param, va); - l.ExecuteIndirect(&dispatch, 1, arguments, at, count.map(|c| c.0), count.map_or(0, |c| c.1)); - l.ResourceBarrier(&[crate::host::transition(&buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, read)]); - } - self.host_pipeline = 0; - let drawn = self.prepare_for(list, false, true); - // SAFETY: as above, the graphics pipeline bound when `drawn`. - unsafe { - if drawn { - self.mesh_scissor(list, true); - l.SetGraphicsRootShaderResourceView(mc.in_param, buffer.GetGPUVirtualAddress()); - l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - l.ExecuteIndirect(&draw, 1, &buffer, 0, None, 0); - self.mesh_scissor(list, false); - } - l.ResourceBarrier(&[crate::host::transition(&buffer, read, D3D12_RESOURCE_STATE_COMMON)]); - } - // The fallback drew a triangle list: the title's next draw has its - // own topology again. + let drawn = unsafe { + run.indirect(&dispatch, &draw, (arguments, at), count, || { + self.host_pipeline = 0; + let drawn = self.prepare_for(list, false, true); + if drawn { + self.mesh_scissor(list, true); + } + drawn + }) + }; + let Some(drawn) = drawn else { + once!("a list without WriteBufferImmediate: the mesh draw is dropped"); + return false; + }; if drawn { - self.restore_topology(list); + self.mesh_scissor(list, false); } list.keep(&buffer); drawn diff --git a/d3d12/crates/leonida-gpu/src/lib.rs b/d3d12/crates/leonida-gpu/src/lib.rs index 3aa021b01d..8c070a046d 100644 --- a/d3d12/crates/leonida-gpu/src/lib.rs +++ b/d3d12/crates/leonida-gpu/src/lib.rs @@ -40,6 +40,8 @@ pub mod descriptor; pub mod device; #[cfg(windows)] mod draw; +#[cfg(windows)] +mod mesh_fallback; #[cfg(any(windows, test))] mod drops; #[cfg(windows)] diff --git a/d3d12/crates/leonida-gpu/src/mesh_fallback.rs b/d3d12/crates/leonida-gpu/src/mesh_fallback.rs new file mode 100644 index 0000000000..ed19cc651d --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/mesh_fallback.rs @@ -0,0 +1,149 @@ +//! `D3D12-MESH-COMPUTE-FALLBACK` as it is recorded on a command list: the +//! mesh program as compute writing each group's outputs to the mesh buffer +//! (`leonida_shader::emit::MESH_OUT_BYTES`), then a triangle list drawn +//! from them through the pass-through vertex shader +//! (`leonida_shader::emit::mesh_vs`). The draw path binds the pipelines and +//! the title's root arguments (`crate::draw`); what is recorded between and +//! after them is here, so a test records the same commands on a device of +//! its own. +//! +//! The buffer starts and ends each run in the common state, so every list, +//! and every run in one list, finds it there. + +use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST}; +use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, ID3D12CommandSignature, ID3D12GraphicsCommandList, + ID3D12GraphicsCommandList2, ID3D12Resource, +}; +use windows::core::Interface; + +use crate::host::transition; + +/// One run of a mesh pipeline as compute and a triangle list. +pub(crate) struct MeshRun<'a> { + pub(crate) list: &'a ID3D12GraphicsCommandList, + /// The mesh buffer, in the common state. + pub(crate) buffer: &'a ID3D12Resource, + /// The compute pipeline's root UAV the groups write to. + pub(crate) out_param: u32, + /// The graphics pipeline's root SRV the vertex shader reads. + pub(crate) in_param: u32, + pub(crate) max_primitives: u32, + /// Instances from this one on would read the sink slot + /// (`MeshOut::groups_cap`). + pub(crate) groups_cap: u32, + /// The topology the list has again after the draw (the title's, for its + /// next draw); `None` leaves the triangle list. + pub(crate) restore: Option, +} + +impl MeshRun<'_> { + /// `x` groups, the compute pipeline and its root arguments bound: + /// dispatches them, then `graphics` binds the graphics pipeline and its + /// root arguments (false: nothing is drawn) and the groups are drawn, + /// one instance a group up to the cap. Whether it drew. + /// + /// # Safety + /// An open list with the compute pipeline bound; live resources. + pub(crate) unsafe fn direct(&self, x: u32, graphics: impl FnOnce() -> bool) -> bool { + let n = x.min(65_535); + if n == 0 { + return true; + } + let (l, buffer) = (self.list, self.buffer); + // SAFETY: as the caller promises. + unsafe { + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.SetComputeRootUnorderedAccessView(self.out_param, buffer.GetGPUVirtualAddress()); + l.Dispatch(n, 1, 1); + l.ResourceBarrier(&[transition( + buffer, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + let drawn = graphics(); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.draw_from_buffer(|l| l.DrawInstanced(self.max_primitives * 3, n.min(self.groups_cap), 0, 0)); + } + l.ResourceBarrier(&[transition( + buffer, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + drawn + } + + /// One indirect record, the compute pipeline and its root arguments + /// bound: the record at `arguments` (a dispatch's `(x, y, z)` with the + /// title's stride, in `dispatch`) runs as recorded, or not at all when + /// the count at `count` is 0. Each group raises the instance count in + /// the buffer's header, which is written first ([3 * max_primitives, 0, + /// 0, 0]), and the draw (`draw`, of 16-byte records) reads the header. + /// `graphics` as for [`Self::direct`]. Whether it drew; `None` on a + /// list without `WriteBufferImmediate`. + /// + /// # Safety + /// As [`Self::direct`]; the argument and count buffers in the indirect + /// argument state. + pub(crate) unsafe fn indirect( + &self, + dispatch: &ID3D12CommandSignature, + draw: &ID3D12CommandSignature, + (arguments, at): (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + graphics: impl FnOnce() -> bool, + ) -> Option { + let (l, buffer) = (self.list, self.buffer); + let l2 = l.cast::().ok()?; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // SAFETY: as the caller promises. + unsafe { + let va = buffer.GetGPUVirtualAddress(); + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + let header = [self.max_primitives * 3, 0, 0, 0]; + let params: Vec = header + .iter() + .enumerate() + .map(|(k, &value)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: va + 4 * k as u64, Value: value }) + .collect(); + l2.WriteBufferImmediate(params.len() as u32, params.as_ptr(), None); + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.SetComputeRootUnorderedAccessView(self.out_param, va); + l.ExecuteIndirect(dispatch, 1, arguments, at, count.map(|c| c.0), count.map_or(0, |c| c.1)); + l.ResourceBarrier(&[transition(buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, read)]); + } + let drawn = graphics(); + // SAFETY: as above, the graphics pipeline bound when `drawn`. + unsafe { + if drawn { + self.draw_from_buffer(|l| l.ExecuteIndirect(draw, 1, buffer, 0, None, 0)); + } + l.ResourceBarrier(&[transition(buffer, read, D3D12_RESOURCE_STATE_COMMON)]); + } + Some(drawn) + } + + /// The draw itself: the buffer as the vertex shader's root SRV, a + /// triangle list, then the topology to restore. + unsafe fn draw_from_buffer(&self, draw: impl FnOnce(&ID3D12GraphicsCommandList)) { + let l = self.list; + // SAFETY: an open list with the graphics pipeline bound. + unsafe { + l.SetGraphicsRootShaderResourceView(self.in_param, self.buffer.GetGPUVirtualAddress()); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + draw(l); + if let Some(t) = self.restore { + l.IASetPrimitiveTopology(t); + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs new file mode 100644 index 0000000000..3750657cf6 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs @@ -0,0 +1,335 @@ +//! The mesh fallback's recording ([`MeshRun`]) on a device, several runs in +//! one command list as a title records them, then a draw of the title's +//! own: each run draws what its own dispatch wrote, a counted indirect run +//! with a count of 0 draws nothing (the header's instance count starts at 0 +//! each run), and the strip after them draws as a strip. + +use leonida_shader::HwStage; +use leonida_shader::emit::host::{Host, MESH_CULL, MESH_TRIANGLE, color_ps, position_vs, triangle_mesh_program}; +use leonida_shader::emit::{HostShader, MESH_OUT_BYTES, SLOT_MESH_IN, mesh_vs, set_host_mesh_shaders}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::MeshRun; + +const SIZE: u32 = 16; +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; +const MAGENTA: [f32; 4] = [1.0, 0.0, 1.0, 1.0]; + +fn buffer(device: &ID3D12Device, heap: D3D12_HEAP_TYPE, bytes: u64, uav: bool, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let mut made: Option = None; + // SAFETY: plain descriptions that outlive the call. + unsafe { + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }, + state, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() +} + +/// An upload buffer holding `data`. +fn upload(device: &ID3D12Device, data: &[T]) -> ID3D12Resource { + let bytes = size_of_val(data); + let b = buffer(device, D3D12_HEAP_TYPE_UPLOAD, bytes.max(256) as u64, false, D3D12_RESOURCE_STATE_GENERIC_READ); + // SAFETY: a mapped upload buffer of at least `bytes`. + unsafe { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(data.as_ptr().cast::(), p.cast::(), bytes); + b.Unmap(0, None); + } + b +} + +fn signature(device: &ID3D12Device, kind: D3D12_INDIRECT_ARGUMENT_TYPE, stride: u32) -> ID3D12CommandSignature { + let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: kind, ..Default::default() }; + let mut made: Option = None; + // SAFETY: a description of one argument; no root arguments. + unsafe { + device + .CreateCommandSignature( + &D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() +} + +/// The colour a texel ends with: the strip's right half over the second +/// run's lower-left triangle over the first run's whole target. +fn expected(column: u32, row: u32) -> [f32; 4] { + let x = -1.0 + (2 * column + 1) as f32 / SIZE as f32; + let y = 1.0 - (2 * row + 1) as f32 / SIZE as f32; + if x > 0.0 { + MAGENTA + } else if x + y < 0.0625 { + GREEN + } else { + RED + } +} + +#[test] +fn mesh_runs_in_one_list_draw_their_own_groups_and_the_strip_after_them_its_strip() { + // The programs as compute, as on a host without mesh shaders. + set_host_mesh_shaders(false); + let programs = [ + triangle_mesh_program(MESH_TRIANGLE, 4.0), + // Far corners at 1.0625: the target's lower-left triangle, its edge + // past every texel centre (x + y < 0.0625). + triangle_mesh_program(MESH_TRIANGLE, 2.0625), + triangle_mesh_program(MESH_TRIANGLE | MESH_CULL, 4.0), + ]; + set_host_mesh_shaders(true); + let [full, half, culled] = programs.map(|p| p.unwrap()); + let layout = full.mesh_out.clone().expect("translated as compute"); + let vs = HostShader { + stage: HwStage::Vs, + dxil: mesh_vs(&layout, None).unwrap(), + user_data: vec![], + samplers: vec![], + static_samplers: vec![], + root_cbvs: vec![], + root_srvs: vec![SLOT_MESH_IN], + root_uavs: vec![], + root_indexed_views: vec![], + half_views: vec![], + mesh_out: None, + }; + let strip_vs = position_vs(); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let device = &host.device; + let compute = |cs: &HostShader| { + let root = host.root_signature_for(&[(cs, D3D12_SHADER_VISIBILITY_ALL)]).unwrap(); + let pso = host.compute_pipeline_with(&root, &cs.dxil).unwrap(); + (root, pso) + }; + let [full_cs, half_cs, culled_cs] = [&full, &half, &culled].map(compute); + let mesh_root = host.root_signature_for(&[(&vs, D3D12_SHADER_VISIBILITY_VERTEX)]).unwrap(); + let mesh_pso = |rgba| host.pipeline_with(&mesh_root, &vs.dxil, &color_ps(rgba).dxil).unwrap(); + let [red, green, blue, yellow] = [RED, GREEN, BLUE, YELLOW].map(mesh_pso); + let strip_root = host.root_signature_for(&[(&strip_vs, D3D12_SHADER_VISIBILITY_VERTEX)]).unwrap(); + let strip_pso = host.pipeline_with(&strip_root, &strip_vs.dxil, &color_ps(MAGENTA).dxil).unwrap(); + + // SAFETY: D3D12 calls with descriptions that outlive them; every + // resource is alive until the fence below says the GPU is done. + unsafe { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .unwrap(); + let alloc: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + // The target. + let mut target: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(SIZE), + Height: SIZE, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut target, + ) + .unwrap(); + let target = target.unwrap(); + let rtv_heap: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + list.ClearRenderTargetView(rtv, &[0.0; 4], None); + + let mesh_buffer = + buffer(device, D3D12_HEAP_TYPE_DEFAULT, u64::from(MESH_OUT_BYTES), true, D3D12_RESOURCE_STATE_COMMON); + // Two dispatch records (12 bytes apart) and the counts 1 and 0. + let arguments = upload(device, &[1u32, 1, 1, 1, 1, 1]); + let counts = upload(device, &[1u32, 0]); + let dispatch = signature(device, D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, 12); + let draw = signature(device, D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, 16); + // The strip: the target's right half, x from 0 to 1. + let corners: [[f32; 4]; 4] = [[0.0, -1.0, 0.5, 1.0], [1.0, -1.0, 0.5, 1.0], [0.0, 1.0, 0.5, 1.0], [1.0, 1.0, 0.5, 1.0]]; + let vertices = upload(device, &corners); + + // The title draws strips: its topology, set before the runs. + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); + let run = MeshRun { + list: &list, + buffer: &mesh_buffer, + out_param: 1, + in_param: 1, + max_primitives: layout.max_primitives, + groups_cap: layout.groups_cap(), + restore: Some(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP), + }; + let bind_compute = |(root, pso): &(ID3D12RootSignature, ID3D12PipelineState)| { + list.SetComputeRootSignature(root); + list.SetPipelineState(pso); + list.SetComputeRoot32BitConstant(0, 0, 0); + }; + let graphics = |pso: &ID3D12PipelineState| { + list.SetGraphicsRootSignature(&mesh_root); + list.SetPipelineState(pso); + list.SetGraphicsRoot32BitConstant(0, 0, 0); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: SIZE as f32, + Height: SIZE as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[RECT { right: SIZE as i32, bottom: SIZE as i32, ..Default::default() }]); + true + }; + + // 1. Counted indirect, count 1: the whole target red. + bind_compute(&full_cs); + assert_eq!(run.indirect(&dispatch, &draw, (&arguments, 0), Some((&counts, 0)), || graphics(&red)), Some(true)); + // 2. Direct, three groups: the lower-left triangle green. + bind_compute(&half_cs); + assert!(run.direct(3, || graphics(&green))); + // 3. Direct, the triangle culled: nothing blue, where the + // buffer still holds the green run's triangles. + bind_compute(&culled_cs); + assert!(run.direct(2, || graphics(&blue))); + // 4. Counted indirect, count 0: no group runs, and the instance + // count the first indirect run left in the header is not + // drawn again: nothing yellow. + bind_compute(&full_cs); + assert_eq!( + run.indirect(&dispatch, &draw, (&arguments, 12), Some((&counts, 4)), || graphics(&yellow)), + Some(true) + ); + // 5. The title's strip, its topology left as the runs restored it. + list.SetGraphicsRootSignature(&strip_root); + list.SetPipelineState(&strip_pso); + list.SetGraphicsRoot32BitConstant(0, 0, 0); + list.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: vertices.GetGPUVirtualAddress(), + SizeInBytes: size_of_val(&corners) as u32, + StrideInBytes: 16, + }]), + ); + list.DrawInstanced(4, 1, 0, 0); + + // Read the target back. + list.ResourceBarrier(&[crate::host::transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let pitch = SIZE * 16; + let readback = buffer( + device, + D3D12_HEAP_TYPE_READBACK, + u64::from(pitch * SIZE), + false, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Width: SIZE, + Height: SIZE, + Depth: 1, + RowPitch: pitch, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).unwrap())]); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + while fence.GetCompletedValue() < 1 { + if let Err(e) = device.GetDeviceRemovedReason() { + panic!("{label}: device removed: {e}"); + } + std::thread::yield_now(); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let texels = std::slice::from_raw_parts(p.cast::<[f32; 4]>(), (SIZE * SIZE) as usize).to_vec(); + readback.Unmap(0, None); + + let wrong: Vec<(u32, u32, [f32; 4], [f32; 4])> = (0..SIZE * SIZE) + .map(|i| (i % SIZE, i / SIZE)) + .map(|(c, r)| (c, r, texels[(r * SIZE + c) as usize], expected(c, r))) + .filter(|&(_, _, got, want)| got != want) + .collect(); + assert!( + wrong.is_empty(), + "{label}: {} of {} texels differ, first (column, row, got, wanted): {:?}", + wrong.len(), + SIZE * SIZE, + wrong[0] + ); + } + eprintln!("{label}: four mesh runs and a strip in one list drew as recorded"); + ran += 1; + } + if ran == 0 { + eprintln!("no SM 6.6 device; skipped"); + } +} diff --git a/d3d12/crates/leonida-shader/src/dxbc.rs b/d3d12/crates/leonida-shader/src/dxbc.rs index 8d5bd73ee2..adc075c226 100644 --- a/d3d12/crates/leonida-shader/src/dxbc.rs +++ b/d3d12/crates/leonida-shader/src/dxbc.rs @@ -131,8 +131,8 @@ pub(crate) fn u64_at(data: &[u8], at: usize) -> Result { .ok_or(ShaderError::Malformed("truncated")) } -/// Builds a container from parts (test helper). -#[cfg(test)] +/// Builds a container from parts (tests and the host checks, `emit::host`). +#[cfg(any(test, feature = "host"))] pub fn build(parts: &[(FourCC, &[u8])]) -> Vec { let table = HEADER_SIZE + 4 * parts.len(); let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 26c3316676..47517e71d5 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -617,6 +617,155 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { } } +/// A pixel shader writing the constant colour `rgba` to target 0. +pub fn color_ps(rgba: [f32; 4]) -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(true); + s.outputs.push(SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }); + let b = s.entry; + for (c, v) in rgba.into_iter().enumerate() { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(c as u8), s.m.f32(v.to_bits())]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, Term::Ret); + plain(crate::native::HwStage::Ps, s.finish()) +} + +/// A vertex shader passing its float4 `POSITION` through as `SV_Position`. +pub fn position_vs() -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(false); + let element = |name: &str, kind: u8, interp: u8| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + s.inputs = vec![element("POSITION", 0, 0)]; + s.outputs = vec![element("SV_Position", 3, 4)]; + for col in 0..4 { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), v]; + s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(s.entry, Term::Ret); + plain(crate::native::HwStage::Vs, s.finish()) +} + +fn plain(stage: crate::native::HwStage, dxil: Vec) -> HostShader { + HostShader { + stage, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + mesh_out: None, + } +} + +/// Triangle (0, 1, 2) as a primitive export: each corner's 9-bit index in +/// its 10-bit field ([`triangle_mesh_program`]). +pub const MESH_TRIANGLE: u32 = 1 << 10 | 2 << 20; +/// The edge flags of the three corners (bits 9, 19 and 29). +pub const MESH_EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; +/// The culling bit of a primitive export. +pub const MESH_CULL: u32 = 1 << 31; + +/// A one-wave (32-lane) console mesh program, translated: its lanes all +/// export primitive `prim` and, as vertex `lane`, the position +/// (lane & 1 ? reach - 1 : -1, lane & 2 ? reach - 1 : -1, 0.5, 1), so +/// triangle (0, 1, 2) has its far corners at `reach` - 1 (with `reach` 4 +/// it covers the whole target). Translated as a mesh program or as compute +/// as the translator is set ([`super::set_host_mesh_shaders`]). +pub fn triangle_mesh_program(prim: u32, reach: f32) -> Result { + use crate::native::{HwStage, MeshIo, NativeProgram, StageIo}; + // (the second corner's y comes out as 2 x its lane bit: half of it) + let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; + let words = [ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04FF, // v_mul_f32 v4, reach, v2 + x, + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 + y, + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E12_02FF, // v_mov_b32 v9, prim + prim, + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 10, + layout: vec![], + used: vec![], + io: StageIo::Ms(MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 32, + max_vertices: 32, + max_primitives: 32, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let osg1 = super::container::signature(&[position], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes)?; + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = crate::structure::structure(&p)?; + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = crate::io::raise(&p, &native)?; + super::emit(&c, &native, &p, &st, &io, &res) +} + /// A root argument for [`Host::draw`]. #[cfg(test)] pub enum Root { diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index d46884dffd..01fe25fe85 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -2368,31 +2368,7 @@ mod tests { /// A pixel shader writing a constant colour. #[cfg(windows)] fn constant_color() -> Vec { - let mut s = Shader::new(true); - s.outputs.push(SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }); - let b = s.entry; - for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() { - let args = [ - s.m.i32(0), - s.m.i32(0), - s.m.i8(c as u8), - s.m.f32(v.to_bits()), - ]; - s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); - } - s.m.terminate(b, super::bitcode::Term::Ret); - s.finish() + super::host::color_ps([1.0, 0.5, 0.25, 1.0]).dxil } #[test] @@ -2609,85 +2585,17 @@ mod tests { } } - /// Triangle (0, 1, 2), each corner's 9-bit index in its 10-bit field. - const TRIANGLE: u32 = 1 << 10 | 2 << 20; - /// The edge flags of the three corners (bits 9, 19 and 29). - const EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; - /// The culling bit. - const CULL: u32 = 1 << 31; + use super::host::{MESH_CULL as CULL, MESH_EDGE_FLAGS as EDGE_FLAGS, MESH_TRIANGLE as TRIANGLE}; - /// A one-wave (32-lane) triangle mesh program whose lanes all export - /// primitive `prim` and, as vertex `lane`, the position - /// (lane & 1 ? 3 : -1, lane & 2 ? 3 : -1, 0.5, 1): triangle (0, 1, 2) - /// covers the whole target. + /// The triangle mesh program covering the whole target + /// ([`super::host::triangle_mesh_program`]). fn triangle_mesh(prim: u32) -> Result { triangle_mesh_to(prim, 4.0) } /// The triangle with its far corners at `reach` - 1. fn triangle_mesh_to(prim: u32, reach: f32) -> Result { - // (the second corner's y comes out as 2 x its lane bit: half of it) - let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; - let words = [ - 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 - 0x0001_00C1, - 0x3604_0281, // v_and_b32 v2, 1, v1 - 0x3606_0282, // v_and_b32 v3, 2, v1 - 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 - 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 - 0x1008_04FF, // v_mul_f32 v4, reach, v2 - x, - 0x0608_08F3, // v_add_f32 v4, -1.0, v4 - 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 - y, - 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 - 0x7E0C_02F0, // v_mov_b32 v6, 0.5 - 0x7E0E_02F2, // v_mov_b32 v7, 1.0 - 0x7E12_02FF, // v_mov_b32 v9, prim - prim, - 0xF800_0941, // exp prim v9, off, off, off done - 0x0000_0009, - 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done - 0x0706_0504, - 0xBF81_0000, // s_endpgm - ]; - let native = NativeProgram { - stage: HwStage::Ms, - wave64: false, - vgprs: 10, - layout: vec![], - used: vec![], - io: StageIo::Ms(crate::native::MeshIo { - outputs: vec![], - clip_cntl: 0, - threads: 32, - max_vertices: 32, - max_primitives: 32, - topology: 2, - lds_bytes: 0, - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let position = SigElement { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }; - let osg1 = container::signature(&[position], false); - let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); - let c = Container::parse(&bytes)?; - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; - let st = structure::structure(&p)?; - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native)?; - emit(&c, &native, &p, &st, &io, &res) + super::host::triangle_mesh_program(prim, reach) } /// A primitive export's corners are 9-bit indices: the edge flag above From eab9c1e0f4b60c1c0fabe3d42d6787a3001bed8b Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 21:10:02 +0200 Subject: [PATCH 41/42] d3d12: the test programs in emit::test_programs, built on every platform The mesh, colour and position programs 924b29417 put in emit::host are needed by portable tests too (primitive_export_indices_drop_the_edge_flags), and emit::host is Windows-only: the Linux test build did not resolve them. They need no device, so they live in emit::test_programs, built for tests and the host feature on every platform. Co-Authored-By: Claude Opus 5.5 --- .../leonida-gpu/src/mesh_fallback/tests.rs | 3 +- d3d12/crates/leonida-shader/src/emit/host.rs | 149 ----------------- d3d12/crates/leonida-shader/src/emit/mod.rs | 10 +- .../leonida-shader/src/emit/test_programs.rs | 157 ++++++++++++++++++ 4 files changed, 165 insertions(+), 154 deletions(-) create mode 100644 d3d12/crates/leonida-shader/src/emit/test_programs.rs diff --git a/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs index 3750657cf6..59f40e1c0c 100644 --- a/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs +++ b/d3d12/crates/leonida-gpu/src/mesh_fallback/tests.rs @@ -5,7 +5,8 @@ //! each run), and the strip after them draws as a strip. use leonida_shader::HwStage; -use leonida_shader::emit::host::{Host, MESH_CULL, MESH_TRIANGLE, color_ps, position_vs, triangle_mesh_program}; +use leonida_shader::emit::host::Host; +use leonida_shader::emit::test_programs::{MESH_CULL, MESH_TRIANGLE, color_ps, position_vs, triangle_mesh_program}; use leonida_shader::emit::{HostShader, MESH_OUT_BYTES, SLOT_MESH_IN, mesh_vs, set_host_mesh_shaders}; use windows::Win32::Foundation::RECT; use windows::Win32::Graphics::Direct3D::*; diff --git a/d3d12/crates/leonida-shader/src/emit/host.rs b/d3d12/crates/leonida-shader/src/emit/host.rs index 47517e71d5..26c3316676 100644 --- a/d3d12/crates/leonida-shader/src/emit/host.rs +++ b/d3d12/crates/leonida-shader/src/emit/host.rs @@ -617,155 +617,6 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { } } -/// A pixel shader writing the constant colour `rgba` to target 0. -pub fn color_ps(rgba: [f32; 4]) -> HostShader { - use super::bitcode::{Attr, Term}; - let mut s = super::shader::Shader::new(true); - s.outputs.push(SigElement { - name: "SV_Target".into(), - index: 0, - kind: 16, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }); - let b = s.entry; - for (c, v) in rgba.into_iter().enumerate() { - let args = [s.m.i32(0), s.m.i32(0), s.m.i8(c as u8), s.m.f32(v.to_bits())]; - s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); - } - s.m.terminate(b, Term::Ret); - plain(crate::native::HwStage::Ps, s.finish()) -} - -/// A vertex shader passing its float4 `POSITION` through as `SV_Position`. -pub fn position_vs() -> HostShader { - use super::bitcode::{Attr, Term}; - let mut s = super::shader::Shader::new(false); - let element = |name: &str, kind: u8, interp: u8| SigElement { - name: name.into(), - index: 0, - kind, - comp: 9, - interp, - row: Some(0), - col: 0, - cols: 4, - usage: 15, - half: false, - }; - s.inputs = vec![element("POSITION", 0, 0)]; - s.outputs = vec![element("SV_Position", 3, 4)]; - for col in 0..4 { - let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; - let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); - let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), v]; - s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); - } - s.m.terminate(s.entry, Term::Ret); - plain(crate::native::HwStage::Vs, s.finish()) -} - -fn plain(stage: crate::native::HwStage, dxil: Vec) -> HostShader { - HostShader { - stage, - dxil, - user_data: Vec::new(), - samplers: Vec::new(), - static_samplers: Vec::new(), - root_cbvs: Vec::new(), - root_srvs: Vec::new(), - root_uavs: Vec::new(), - root_indexed_views: Vec::new(), - half_views: Vec::new(), - mesh_out: None, - } -} - -/// Triangle (0, 1, 2) as a primitive export: each corner's 9-bit index in -/// its 10-bit field ([`triangle_mesh_program`]). -pub const MESH_TRIANGLE: u32 = 1 << 10 | 2 << 20; -/// The edge flags of the three corners (bits 9, 19 and 29). -pub const MESH_EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; -/// The culling bit of a primitive export. -pub const MESH_CULL: u32 = 1 << 31; - -/// A one-wave (32-lane) console mesh program, translated: its lanes all -/// export primitive `prim` and, as vertex `lane`, the position -/// (lane & 1 ? reach - 1 : -1, lane & 2 ? reach - 1 : -1, 0.5, 1), so -/// triangle (0, 1, 2) has its far corners at `reach` - 1 (with `reach` 4 -/// it covers the whole target). Translated as a mesh program or as compute -/// as the translator is set ([`super::set_host_mesh_shaders`]). -pub fn triangle_mesh_program(prim: u32, reach: f32) -> Result { - use crate::native::{HwStage, MeshIo, NativeProgram, StageIo}; - // (the second corner's y comes out as 2 x its lane bit: half of it) - let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; - let words = [ - 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 - 0x0001_00C1, - 0x3604_0281, // v_and_b32 v2, 1, v1 - 0x3606_0282, // v_and_b32 v3, 2, v1 - 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 - 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 - 0x1008_04FF, // v_mul_f32 v4, reach, v2 - x, - 0x0608_08F3, // v_add_f32 v4, -1.0, v4 - 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 - y, - 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 - 0x7E0C_02F0, // v_mov_b32 v6, 0.5 - 0x7E0E_02F2, // v_mov_b32 v7, 1.0 - 0x7E12_02FF, // v_mov_b32 v9, prim - prim, - 0xF800_0941, // exp prim v9, off, off, off done - 0x0000_0009, - 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done - 0x0706_0504, - 0xBF81_0000, // s_endpgm - ]; - let native = NativeProgram { - stage: HwStage::Ms, - wave64: false, - vgprs: 10, - layout: vec![], - used: vec![], - io: StageIo::Ms(MeshIo { - outputs: vec![], - clip_cntl: 0, - threads: 32, - max_vertices: 32, - max_primitives: 32, - topology: 2, - lds_bytes: 0, - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let position = SigElement { - name: "SV_Position".into(), - index: 0, - kind: 3, - comp: 9, - interp: 0, - row: Some(0), - col: 0, - cols: 4, - usage: 0xF, - half: false, - }; - let osg1 = super::container::signature(&[position], false); - let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); - let c = Container::parse(&bytes)?; - let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs)?; - let st = crate::structure::structure(&p)?; - let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = crate::io::raise(&p, &native)?; - super::emit(&c, &native, &p, &st, &io, &res) -} - /// A root argument for [`Host::draw`]. #[cfg(test)] pub enum Root { diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 9a0f23a84b..1387a43912 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -90,6 +90,8 @@ mod diff_tests; mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; +#[cfg(any(test, feature = "host"))] +pub mod test_programs; mod lds_exact; mod lds_flags; mod lds_init; @@ -2466,7 +2468,7 @@ mod tests { /// A pixel shader writing a constant colour. #[cfg(windows)] fn constant_color() -> Vec { - super::host::color_ps([1.0, 0.5, 0.25, 1.0]).dxil + super::test_programs::color_ps([1.0, 0.5, 0.25, 1.0]).dxil } #[test] @@ -2807,17 +2809,17 @@ mod tests { } } - use super::host::{MESH_CULL as CULL, MESH_EDGE_FLAGS as EDGE_FLAGS, MESH_TRIANGLE as TRIANGLE}; + use super::test_programs::{MESH_CULL as CULL, MESH_EDGE_FLAGS as EDGE_FLAGS, MESH_TRIANGLE as TRIANGLE}; /// The triangle mesh program covering the whole target - /// ([`super::host::triangle_mesh_program`]). + /// ([`super::test_programs::triangle_mesh_program`]). fn triangle_mesh(prim: u32) -> Result { triangle_mesh_to(prim, 4.0) } /// The triangle with its far corners at `reach` - 1. fn triangle_mesh_to(prim: u32, reach: f32) -> Result { - super::host::triangle_mesh_program(prim, reach) + super::test_programs::triangle_mesh_program(prim, reach) } /// A primitive export's corners are 9-bit indices: the edge flag above diff --git a/d3d12/crates/leonida-shader/src/emit/test_programs.rs b/d3d12/crates/leonida-shader/src/emit/test_programs.rs new file mode 100644 index 0000000000..8b8e88445b --- /dev/null +++ b/d3d12/crates/leonida-shader/src/emit/test_programs.rs @@ -0,0 +1,157 @@ +//! Programs for checks of the host side without the title (tests here and +//! the `host` feature's users, the runtime's tests): a mesh program whose +//! triangle covers a part of the target as asked, a constant-colour pixel +//! shader and a position pass-through vertex shader. None needs a device. + +use super::HostShader; +use super::container::SigElement; +use crate::dxbc::{Container, FourCC}; + +/// A pixel shader writing the constant colour `rgba` to target 0. +pub fn color_ps(rgba: [f32; 4]) -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(true); + s.outputs.push(SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }); + let b = s.entry; + for (c, v) in rgba.into_iter().enumerate() { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(c as u8), s.m.f32(v.to_bits())]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, Term::Ret); + plain(crate::native::HwStage::Ps, s.finish()) +} + +/// A vertex shader passing its float4 `POSITION` through as `SV_Position`. +pub fn position_vs() -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(false); + let element = |name: &str, kind: u8, interp: u8| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + s.inputs = vec![element("POSITION", 0, 0)]; + s.outputs = vec![element("SV_Position", 3, 4)]; + for col in 0..4 { + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), s.m.undef(s.t.i32)]; + let v = s.op(s.entry, "loadInput.f32", Attr::ReadNone, s.t.f32, 4, &args); + let args = [s.m.i32(0), s.m.i32(0), s.m.i8(col), v]; + s.op(s.entry, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(s.entry, Term::Ret); + plain(crate::native::HwStage::Vs, s.finish()) +} + +fn plain(stage: crate::native::HwStage, dxil: Vec) -> HostShader { + HostShader { + stage, + dxil, + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + root_indexed_views: Vec::new(), + half_views: Vec::new(), + mesh_out: None, + } +} + +/// Triangle (0, 1, 2) as a primitive export: each corner's 9-bit index in +/// its 10-bit field ([`triangle_mesh_program`]). +pub const MESH_TRIANGLE: u32 = 1 << 10 | 2 << 20; +/// The edge flags of the three corners (bits 9, 19 and 29). +pub const MESH_EDGE_FLAGS: u32 = 1 << 9 | 1 << 19 | 1 << 29; +/// The culling bit of a primitive export. +pub const MESH_CULL: u32 = 1 << 31; + +/// A one-wave (32-lane) console mesh program, translated: its lanes all +/// export primitive `prim` and, as vertex `lane`, the position +/// (lane & 1 ? reach - 1 : -1, lane & 2 ? reach - 1 : -1, 0.5, 1), so +/// triangle (0, 1, 2) has its far corners at `reach` - 1 (with `reach` 4 +/// it covers the whole target). Translated as a mesh program or as compute +/// as the translator is set ([`super::set_host_mesh_shaders`]). +pub fn triangle_mesh_program(prim: u32, reach: f32) -> Result { + use crate::native::{HwStage, MeshIo, NativeProgram, StageIo}; + // (the second corner's y comes out as 2 x its lane bit: half of it) + let [x, y] = [reach.to_bits(), (reach / 2.0).to_bits()]; + let words = [ + 0xD765_0001u32, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0x0001_00C1, + 0x3604_0281, // v_and_b32 v2, 1, v1 + 0x3606_0282, // v_and_b32 v3, 2, v1 + 0x7E04_0D02, // v_cvt_f32_u32 v2, v2 + 0x7E06_0D03, // v_cvt_f32_u32 v3, v3 + 0x1008_04FF, // v_mul_f32 v4, reach, v2 + x, + 0x0608_08F3, // v_add_f32 v4, -1.0, v4 + 0x100A_06FF, // v_mul_f32 v5, reach / 2, v3 + y, + 0x060A_0AF3, // v_add_f32 v5, -1.0, v5 + 0x7E0C_02F0, // v_mov_b32 v6, 0.5 + 0x7E0E_02F2, // v_mov_b32 v7, 1.0 + 0x7E12_02FF, // v_mov_b32 v9, prim + prim, + 0xF800_0941, // exp prim v9, off, off, off done + 0x0000_0009, + 0xF800_08CF, // exp pos0 v4, v5, v6, v7 done + 0x0706_0504, + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Ms, + wave64: false, + vgprs: 10, + layout: vec![], + used: vec![], + io: StageIo::Ms(MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 32, + max_vertices: 32, + max_primitives: 32, + topology: 2, + lds_bytes: 0, + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let position = SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0xF, + half: false, + }; + let osg1 = super::container::signature(&[position], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes)?; + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = crate::structure::structure(&p)?; + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = crate::io::raise(&p, &native)?; + super::emit(&c, &native, &p, &st, &io, &res) +} From 74ac98c64b6b65ba94e8161738fe8fb76cec7c74 Mon Sep 17 00:00:00 2001 From: qhukz13 Date: Sun, 29 Nov 2026 21:42:30 +0200 Subject: [PATCH 42/42] d3d12: the mesh fallback's shaders take main's sample-mask fields Main's Shader gained mask and masked_twins (the sample mask's pixel shader twins); the mesh program seen as compute and its pass-through vertex shader are the title's own forms: no mask, no twins yet. Co-Authored-By: Claude Opus 5.5 --- d3d12/crates/leonida-gpu/src/pipeline.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs index f26fb9986a..5601bc4a83 100644 --- a/d3d12/crates/leonida-gpu/src/pipeline.rs +++ b/d3d12/crates/leonida-gpu/src/pipeline.rs @@ -211,6 +211,8 @@ impl Shader { container: self.container.clone(), ambient: None, translated: OnceLock::new(), + mask: None, + masked_twins: Mutex::new(Vec::new()), }); let ps_dxil = ps.and_then(Shader::translated).map(|t| t.host.dxil.as_slice()); let dxil = match leonida_shader::emit::mesh_vs(&layout, ps_dxil) { @@ -252,6 +254,8 @@ impl Shader { picks: Default::default(), bound: Default::default(), })), + mask: None, + masked_twins: Mutex::new(Vec::new()), }); Some((cs, vs, layout)) }