upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com>2026-11-25 00:43:38 -0500
committerubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com>2026-11-25 00:43:38 -0500
commit79cf7e78cfa1eedcdbf69dcdf0a4f7d5ee7b7b00 (patch)
tree287572619a84ed1cc28195ae2023d29f47e48d72
parent156a056b85289eece6878fe2ba12c7c17c44ca96 (diff)
parent570db1d58f67a3b899cc60f53055eeb86fc8ac3d (diff)
Merge #1281 (shader library keeps each compute state, select by code hash)
-rw-r--r--docs/shader_library.md9
-rw-r--r--tests/test_shader_library.py123
-rw-r--r--tools/shader_library.py12
3 files changed, 138 insertions, 6 deletions
diff --git a/docs/shader_library.md b/docs/shader_library.md
index 8cf131ca4..a1b6a2301 100644
--- a/docs/shader_library.md
+++ b/docs/shader_library.md
@@ -152,8 +152,11 @@ python -I tools/rdna2spirv.py <work>/library/disasm --out <work>/library/spirv
152 152
153* It writes `fspx/<name>.code` and `fspx/<name>.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py` 153* It writes `fspx/<name>.code` and `fspx/<name>.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py`
154 reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/<name>.state`, its record's state 154 reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/<name>.state`, its record's state
155 blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; every compute program has exactly one 155 blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library,
156 (2,684 programs, 2,693 records). It also writes `index.json` with each program's stage, and 156 every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs,
157 2,693 records). A program that records use with different state blobs is written once per distinct state, the
158 first under its name and each further one as `<name>_state_<blob index>`, so each pair of keys has an entry
159 (the library measured above has no such program). It also writes `index.json` with each program's stage, and
157 `library.json` with the header and both pipeline tables, stage to program name. Programs are named 160 `library.json` with the header and both pipeline tables, stage to program name. Programs are named
158 `lib_<stage>_<index>`. 161 `lib_<stage>_<index>`.
159* `--disasm` writes `disasm/<name>.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. 162* `--disasm` writes `disasm/<name>.s` for the code after the prologue, as `fspx_unpack.py --disasm` does.
@@ -162,6 +165,8 @@ python -I tools/rdna2spirv.py <work>/library/disasm --out <work>/library/spirv
162 interface. 165 interface.
163* `--save` writes the reassembled library. A saved file is also accepted as input. 166* `--save` writes the reassembled library. A saved file is also accepted as input.
164* `--stages` limits the output to some stages. 167* `--stages` limits the output to some stages.
168* `--compute-hashes FILE` instead writes only the compute programs whose code has one of the SHA-256 digests listed
169 in `FILE` (`fspx_code_sha256`), with every state they are used with. A digest no compute program has is an error.
165 170
166The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and 171The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and
167archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest 172archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest
diff --git a/tests/test_shader_library.py b/tests/test_shader_library.py
index 8410be28a..db5fa57f7 100644
--- a/tests/test_shader_library.py
+++ b/tests/test_shader_library.py
@@ -388,6 +388,129 @@ class Main(unittest.TestCase):
388 self.assertIn("fspx_code_sha256", meta) 388 self.assertIn("fspx_code_sha256", meta)
389 self.assertNotIn("fspx_state_sha256", meta) 389 self.assertNotIn("fspx_state_sha256", meta)
390 390
391 def two_state_library(self):
392 """Program 0 with three state blobs, two of them the same bytes, and once without a state; program 1 with one
393 of those blobs; program 2 in a graphics pipeline. Returns (library, the two distinct states, program 0)."""
394 first, second = kind0(), kind0(threads=(32, 1, 1))
395 code = prog(3)
396 compute = [(0, NONE, 0, NONE), (1, NONE, 0, NONE), (2, NONE, 0, NONE), (NONE, NONE, 0, NONE),
397 (1, NONE, 1, NONE)]
398 lib = build([(NONE, NONE, {0: (2, 3)})], compute, [first, second, first, layout_blob(2, D_PS)],
399 [code, prog(4), prog(5)])
400 return lib, (first, second), code
401
402 # The entries of that library's compute programs: program 0, its second state (blob 1) and program 1.
403 TWO_STATE_NAMES = [sl.program_name(0, {"cs"}), sl.program_name(0, {"cs"}) + "_state_1", sl.program_name(1, {"cs"})]
404
405 def test_program_with_two_states_gets_an_entry_for_each(self):
406 lib, (first, second), code = self.two_state_library()
407 with tempfile.TemporaryDirectory() as tmp:
408 src = os.path.join(tmp, "lib.bin")
409 with open(src, "wb") as f:
410 f.write(lib)
411 out = os.path.join(tmp, "out")
412 # A further state is an output like any other: --save must not name it.
413 names = self.TWO_STATE_NAMES
414 self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".state"), "--stages", "cs")
415 self.assertFalse(os.path.exists(out))
416 rc, text = self.run_main(src, "--out", out, "--stages", "cs")
417 self.assertEqual(rc, 0)
418 self.assertIn("3 written", text)
419 with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
420 index = json.load(f)
421 self.assertEqual([(e["file"], e["program"], e["threads"]) for e in index],
422 [(names[0] + ".dxbc", 0, [8, 8, 1]), (names[1] + ".dxbc", 0, [32, 1, 1]),
423 (names[2] + ".dxbc", 1, [32, 1, 1])])
424 self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))),
425 sorted(n + ext for n in names for ext in (".code", ".json", ".state")))
426 for name, state in zip(names, (first, second, second)):
427 with open(os.path.join(out, "fspx", name + ".state"), "rb") as f:
428 self.assertEqual(f.read(), state)
429 for name in names[:2]:
430 with open(os.path.join(out, "fspx", name + ".code"), "rb") as f:
431 self.assertEqual(f.read(), code)
432 # Both entries of program 0 have its code key, and each its own state key.
433 metas = [shader_meta.collect(os.path.join(out, "disasm", n + ".s"), n, [[]], [[]]) for n in names[:2]]
434 self.assertEqual({m["fspx_code_sha256"] for m in metas}, {hashlib.sha256(code).hexdigest()})
435 self.assertEqual([m["fspx_state_sha256"] for m in metas],
436 [hashlib.sha256(first).hexdigest(), hashlib.sha256(second).hexdigest()])
437 # Every record names the entry with its state; the one without a state names the program.
438 with open(os.path.join(out, "library.json"), encoding="utf-8") as f:
439 self.assertEqual([c["program"] for c in json.load(f)["compute"]],
440 [names[0], names[1], names[0], names[0], names[2]])
441
442 def test_compute_hashes_select_programs_by_their_code(self):
443 lib, (first, second), code = self.two_state_library()
444 with tempfile.TemporaryDirectory() as tmp:
445 src = os.path.join(tmp, "lib.bin")
446 with open(src, "wb") as f:
447 f.write(lib)
448 hashes = os.path.join(tmp, "hashes.txt")
449 with open(hashes, "w", encoding="utf-8", newline="\n") as f:
450 f.write("\n " + hashlib.sha256(code).hexdigest().upper() + "\n\n")
451 out = os.path.join(tmp, "out")
452 names = self.TWO_STATE_NAMES[:2]
453 self.assert_save_overlap(src, out, os.path.join(out, "fspx", names[1] + ".code"),
454 "--compute-hashes", hashes)
455 self.assertFalse(os.path.exists(out))
456 rc, text = self.run_main(src, "--out", out, "--compute-hashes", hashes)
457 self.assertEqual(rc, 0)
458 self.assertIn("2 written", text)
459 with open(os.path.join(out, "index.json"), encoding="utf-8") as f:
460 self.assertEqual([e["file"] for e in json.load(f)], [n + ".dxbc" for n in names])
461 self.assertEqual(sorted(os.listdir(os.path.join(out, "fspx"))),
462 sorted(n + ext for n in names for ext in (".code", ".json", ".state")))
463 for name, state in zip(names, (first, second)):
464 with open(os.path.join(out, "fspx", name + ".state"), "rb") as f:
465 self.assertEqual(f.read(), state)
466 # The tables are the library's, whatever was selected.
467 with open(os.path.join(out, "library.json"), encoding="utf-8") as f:
468 summary = json.load(f)
469 self.assertEqual([c["program"] for c in summary["compute"]],
470 [names[0], names[1], names[0], names[0], self.TWO_STATE_NAMES[2]])
471 self.assertEqual(summary["graphics"][0]["stages"], {"ps": sl.program_name(2, {"ps"})})
472
473 def test_compute_hashes_are_checked_before_anything_is_written(self):
474 lib, _, code = self.two_state_library()
475 digest = hashlib.sha256(code).hexdigest()
476 pixel = hashlib.sha256(sl.program(lib, sl.parse(lib), 2)).hexdigest()
477 with tempfile.TemporaryDirectory() as tmp:
478 src = os.path.join(tmp, "lib.bin")
479 with open(src, "wb") as f:
480 f.write(lib)
481 out = os.path.join(tmp, "out")
482 listed = os.path.join(tmp, "hashes.txt")
483
484 def usage_error(text, *args):
485 with open(listed, "w", encoding="utf-8", newline="\n") as f:
486 f.write(text)
487 err = io.StringIO()
488 with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as caught:
489 self.run_main(src, *args)
490 self.assertEqual(caught.exception.code, 2)
491 return err.getvalue()
492
493 self.assertIn("not allowed with", usage_error(digest, "--out", out, "--stages", "cs",
494 "--compute-hashes", listed))
495 self.assertIn("--compute-hashes needs --out", usage_error(digest, "--save", os.path.join(tmp, "l.bin"),
496 "--compute-hashes", listed))
497 for text in ("", "\n", digest[:-1], digest + " not-a-digest", "0x" + digest):
498 with self.subTest(text=text):
499 self.assertIn("cannot read --compute-hashes", usage_error(text, "--out", out,
500 "--compute-hashes", listed))
501 self.assertIn("cannot read --compute-hashes",
502 usage_error(digest, "--out", out, "--compute-hashes", os.path.join(tmp, "missing.txt")))
503 # A digest no compute program has, here an unknown one and a pixel program's.
504 for text in (digest + "\n" + "0" * 64, pixel):
505 with self.subTest(text=text):
506 with open(listed, "w", encoding="utf-8", newline="\n") as f:
507 f.write(text)
508 with self.assertRaises(sl.LibraryError) as caught:
509 self.run_main(src, "--out", out, "--compute-hashes", listed)
510 self.assertIn("match no compute program", str(caught.exception))
511 self.assertFalse(os.path.exists(out))
512 self.assertFalse(os.path.exists(os.path.join(tmp, "l.bin")))
513
391 def test_same_code_with_distinct_states_gets_distinct_state_keys(self): 514 def test_same_code_with_distinct_states_gets_distinct_state_keys(self):
392 code = prog(0x44556677) 515 code = prog(0x44556677)
393 s_a, s_b = kind0(threads=(32, 1, 1)), kind0(threads=(64, 1, 1)) 516 s_a, s_b = kind0(threads=(32, 1, 1)), kind0(threads=(64, 1, 1))
diff --git a/tools/shader_library.py b/tools/shader_library.py
index a74a820bb..b1f928292 100644
--- a/tools/shader_library.py
+++ b/tools/shader_library.py
@@ -270,7 +270,10 @@ def compute_variants(b: bytes, lib: dict, names: dict):
270 i, state_id = rec["program"], rec["state"] 270 i, state_id = rec["program"], rec["state"]
271 if i is None: 271 if i is None:
272 continue 272 continue
273 state = blob(b, lib, state_id) if state_id is not None else None 273 if state_id is None:
274 by_record[i, None] = names[i]
275 continue
276 state = blob(b, lib, state_id)
274 states = variants.setdefault(i, {}) 277 states = variants.setdefault(i, {})
275 if state not in states: 278 if state not in states:
276 states[state] = names[i] if not states else f"{names[i]}_state_{state_id}" 279 states[state] = names[i] if not states else f"{names[i]}_state_{state_id}"
@@ -301,7 +304,7 @@ def main(argv=None) -> int:
301 if not a.out and not a.save: 304 if not a.out and not a.save:
302 ap.error("give --out, --save or both") 305 ap.error("give --out, --save or both")
303 hashes = None 306 hashes = None
304 if a.compute_hashes: 307 if a.compute_hashes is not None:
305 if not a.out: 308 if not a.out:
306 ap.error("--compute-hashes needs --out") 309 ap.error("--compute-hashes needs --out")
307 try: 310 try:
@@ -310,7 +313,7 @@ def main(argv=None) -> int:
310 except (OSError, UnicodeError) as error: 313 except (OSError, UnicodeError) as error:
311 ap.error(f"cannot read --compute-hashes: {error}") 314 ap.error(f"cannot read --compute-hashes: {error}")
312 if not hashes or any(not re.fullmatch(r"[0-9a-f]{64}", h) for h in hashes): 315 if not hashes or any(not re.fullmatch(r"[0-9a-f]{64}", h) for h in hashes):
313 ap.error("--compute-hashes needs at least one SHA-256 digest") 316 ap.error("cannot read --compute-hashes: expected one or more SHA-256 digests of 64 hex digits")
314 with open(a.src, "rb") as f: 317 with open(a.src, "rb") as f:
315 head = f.read(4) 318 head = f.read(4)
316 f.seek(0) 319 f.seek(0)
@@ -346,7 +349,8 @@ def main(argv=None) -> int:
346 selected = [i for i in selected if matching[i] in hashes] 349 selected = [i for i in selected if matching[i] in hashes]
347 missing = hashes - {matching[i] for i in selected} 350 missing = hashes - {matching[i] for i in selected}
348 if missing: 351 if missing:
349 raise LibraryError(f"{len(missing)} requested compute code hashes not found in the pipeline library") 352 raise LibraryError(f"{len(missing)} of the {len(hashes)} --compute-hashes digests match no compute "
353 f"program of the library, first {min(missing)}")
350 carve_errors = [] 354 carve_errors = []
351 sources = carve_digests(a.carve, errors=carve_errors) if a.carve else None 355 sources = carve_digests(a.carve, errors=carve_errors) if a.carve else None
352 356