Shader stage: resume only finished steps, Windows-safe carve names, clear error on empty unpack (fixes #126)

- make_game.py: a step counts as done only when the file it writes last
  exists (index.json, fssm_index.json, disasm.done, spirv/index.json),
  not when its folder exists or holds >=1000 files. Re-running a step
  drops the later steps' markers so they run again.
- shader_carve.py / fssm_unpack.py: write their index last, via a temp
  file and os.replace, so a stopped run never leaves one behind.
- shader_carve.py: file names are unique without case and Windows device
  names (CON, NUL, COM1...) get a "_" prefix; ~N suffixes never land on
  a real name.
- fssm_unpack.py: exit 1 with a clear message when nothing unpacks,
  before writing the index, instead of an IndexError.
- tests/test_shader_stage_resume.py: 13 tests, standard library only.

AI-assisted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NWX10
2026-11-21 23:00:32 +03:00
parent d51bddc84e
commit 7cc6068ab6
4 changed files with 213 additions and 14 deletions

View File

@ -275,11 +275,20 @@ def shaders(game: str, work: str, jobs: int) -> None:
src = os.path.join(game, "shaders.rpf")
sh = os.path.join(work, "shaders")
dxbc = os.path.join(sh, "dxbc")
if not os.path.isfile(os.path.join(dxbc, "index.json")):
spirv = os.path.join(sh, "spirv")
# Each stage counts as finished only when the file it writes last is there, never because its folder exists
# or holds many files: a run stopped part-way leaves both. Re-running a stage drops the later stages' proof.
carved = os.path.join(dxbc, "index.json") # shader_carve.py, renamed into place at the end
unpacked = os.path.join(dxbc, "fssm_index.json") # fssm_unpack.py, the same
disassembled = os.path.join(dxbc, "disasm.done") # written here once shader_disasm.py exits with 0
translated = os.path.join(spirv, "index.json") # rdna2spirv.py --merge, renamed into place
if not os.path.isfile(carved):
log("shaders: carving shaders.rpf")
drop(unpacked, disassembled, translated)
py("shader_carve.py", src, dxbc)
if not os.path.isdir(os.path.join(dxbc, "fssm")):
if not os.path.isfile(unpacked):
log("shaders: unpacking native code")
drop(disassembled, translated)
py("fssm_unpack.py", dxbc)
# rdna2spirv.py finds index.json, the .dxbc files and fssm/ in the parent of the .s files' folder, so the
# disassembly must sit inside the carve folder: next to it, every stage reads as "?" and is rejected.
@ -288,14 +297,16 @@ def shaders(game: str, work: str, jobs: int) -> None:
if os.path.isdir(old) and not os.path.isdir(disasm):
log("shaders: moving disasm into the carve folder and translating again")
os.rename(old, disasm)
shutil.rmtree(os.path.join(sh, "spirv"), ignore_errors=True)
if not os.path.isdir(disasm) or len(os.listdir(disasm)) < 1000:
shutil.rmtree(spirv, ignore_errors=True)
if not os.path.isfile(disassembled):
need(os.environ.get("LLVM_MC", "llvm-mc"),
"Install LLVM 21 or newer with the AMDGPU target, or set LLVM_MC to llvm-mc's full path.")
log("shaders: disassembling (gfx1013)")
drop(translated)
py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs)
spirv = os.path.join(sh, "spirv")
if not os.path.isdir(spirv) or len(os.listdir(spirv)) < 1000:
with open(disassembled, "w", encoding="utf-8") as f:
f.write("shader_disasm.py finished\n")
if not os.path.isfile(translated):
need("spirv-as", "Install the Vulkan SDK (it includes spirv-as and spirv-val) and reopen the terminal.")
need("spirv-val", "Install the Vulkan SDK and reopen the terminal.")
log(f"shaders: translating RDNA2 to SPIR-V on {jobs} processes (the longest step)")
@ -303,6 +314,13 @@ def shaders(game: str, work: str, jobs: int) -> None:
log("shaders: done")
def drop(*paths: str) -> None:
"""Remove the files that mark later stages finished, so they run again on this stage's new output."""
for p in paths:
if os.path.isfile(p):
os.remove(p)
def translate(disasm: str, spirv: str, jobs: int) -> None:
"""rdna2spirv.py runs on one core: start one --shard per job side by side, then merge their index parts."""
os.makedirs(spirv, exist_ok=True)

View File

@ -0,0 +1,150 @@
"""Shader stage of make_game.py: resuming a stopped build, Windows-safe carve names, an empty unpack (#126).
Standard library only; no game data: the tools are mocked or fed hand-made inputs.
"""
import os
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
sys.path.insert(0, os.path.join(ROOT, "tools"))
import make_game # noqa: E402
import shader_carve # noqa: E402
UNPACK = os.path.join(ROOT, "tools", "fssm_unpack.py")
class CarveFileNameTest(unittest.TestCase):
def names(self, *shader_names):
seen, used = {}, set()
return [shader_carve.file_name(n, seen, used) for n in shader_names]
def test_repeated_name_gets_a_suffix(self):
self.assertEqual(self.names("ps_a", "ps_a", "ps_a"), ["ps_a.dxbc", "ps_a~1.dxbc", "ps_a~2.dxbc"])
def test_names_differing_only_in_case_do_not_share_a_file(self):
out = self.names("PS_Water", "ps_water")
self.assertEqual(len({n.lower() for n in out}), 2, out)
def test_names_that_sanitize_to_the_same_file_do_not_share_it(self):
out = self.names("a:b", "a_b", "a?b")
self.assertEqual(len({n.lower() for n in out}), 3, out)
def test_suffix_never_lands_on_a_real_name(self):
out = self.names("x~1", "x", "x")
self.assertEqual(len({n.lower() for n in out}), 3, out)
def test_windows_device_names_are_prefixed(self):
for dev in ("CON", "nul", "Aux", "PRN", "COM1", "lpt9", "con.vs"):
name = self.names(dev)[0]
self.assertNotIn(name.split(".")[0].upper(), shader_carve.RESERVED, name)
self.assertEqual(self.names("CONSOLE")[0], "CONSOLE.dxbc")
class EmptyUnpackTest(unittest.TestCase):
def test_nothing_unpacked_fails_clearly_and_writes_no_index(self):
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, "junk.dxbc"), "wb") as f:
f.write(b"DXBC" + bytes(60)) # no parts: nothing to unpack
r = subprocess.run([sys.executable, "-I", UNPACK, d], capture_output=True, text=True)
self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
self.assertIn("ERROR", r.stderr)
self.assertNotIn("Traceback", r.stderr)
self.assertFalse(os.path.exists(os.path.join(d, "fssm_index.json")))
def test_empty_folder_fails_clearly(self):
with tempfile.TemporaryDirectory() as d:
r = subprocess.run([sys.executable, "-I", UNPACK, d], capture_output=True, text=True)
self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
self.assertNotIn("Traceback", r.stderr)
class ShaderStageResumeTest(unittest.TestCase):
"""Which steps shaders() runs for a given work folder. The tools are mocked; each mock writes what the real
tool writes last, so the next run sees the same files a real one would."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.work = self.tmp.name
self.dxbc = os.path.join(self.work, "shaders", "dxbc")
self.spirv = os.path.join(self.work, "shaders", "spirv")
self.ran = []
def tearDown(self):
self.tmp.cleanup()
def touch(self, *parts):
p = os.path.join(*parts)
os.makedirs(os.path.dirname(p), exist_ok=True)
open(p, "w").close()
def fake_py(self, tool, *args):
self.ran.append(tool)
if tool == "shader_carve.py":
self.touch(self.dxbc, "index.json")
elif tool == "fssm_unpack.py":
self.touch(self.dxbc, "fssm_index.json")
elif tool == "shader_disasm.py":
os.makedirs(os.path.join(self.dxbc, "disasm"), exist_ok=True)
def fake_translate(self, disasm, spirv, jobs):
self.ran.append("translate")
self.touch(spirv, "index.json")
def run_stage(self):
self.ran = []
with mock.patch.object(make_game, "py", self.fake_py), \
mock.patch.object(make_game, "need", lambda *a: None), \
mock.patch.object(make_game, "translate", self.fake_translate), \
mock.patch.object(make_game, "log", lambda *a: None):
make_game.shaders(os.path.join(self.work, "game"), self.work, 2)
return self.ran
def test_fresh_folder_runs_every_step_then_nothing(self):
self.assertEqual(self.run_stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate"])
self.assertEqual(self.run_stage(), [])
def test_unpack_stopped_after_creating_fssm_folder_runs_again(self):
self.touch(self.dxbc, "index.json")
os.makedirs(os.path.join(self.dxbc, "fssm")) # what a stopped fssm_unpack.py leaves
self.assertEqual(self.run_stage(), ["fssm_unpack.py", "shader_disasm.py", "translate"])
def test_disasm_stopped_after_many_files_runs_again(self):
self.touch(self.dxbc, "index.json")
self.touch(self.dxbc, "fssm_index.json")
for i in range(1200): # past the old 1000-file threshold
self.touch(self.dxbc, "disasm", f"s{i}.s")
self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"])
def test_translation_stopped_after_many_files_runs_again(self):
self.run_stage()
os.remove(os.path.join(self.spirv, "index.json")) # stopped before --merge
for i in range(1200):
self.touch(self.spirv, f"s{i}.spv")
self.assertEqual(self.run_stage(), ["translate"])
def test_failed_disasm_leaves_no_marker(self):
self.touch(self.dxbc, "index.json")
self.touch(self.dxbc, "fssm_index.json")
def failing_py(tool, *args):
raise SystemExit(1)
with mock.patch.object(make_game, "py", failing_py), \
mock.patch.object(make_game, "need", lambda *a: None), \
mock.patch.object(make_game, "log", lambda *a: None):
with self.assertRaises(SystemExit):
make_game.shaders(os.path.join(self.work, "game"), self.work, 2)
self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm.done")))
def test_rerunning_a_step_reruns_the_steps_after_it(self):
self.run_stage()
os.remove(os.path.join(self.dxbc, "fssm_index.json"))
self.assertEqual(self.run_stage(), ["fssm_unpack.py", "shader_disasm.py", "translate"])
if __name__ == "__main__":
unittest.main()

View File

@ -83,9 +83,18 @@ def main() -> int:
rows.append({"name": stem, "size": len(fssm), "magic": fssm[:4].decode("latin-1"),
"version": struct.unpack_from("<H", fssm, 4)[0], "endpgm": ends,
"tags": sorted(hex(t) for t in ents)})
with open(os.path.join(src, "fssm_index.json"), "w", encoding="utf-8") as f:
json.dump(rows, f)
print(f"{len(rows)} FSSM blobs, problems: {dict(problems)}")
if not rows:
# No index: make_game.py takes fssm_index.json as proof this step finished, and an empty one is not.
print(f"ERROR: no shader in {src} unpacked. Check that it holds the carved .dxbc files of a supported "
"game version.", file=sys.stderr)
return 1
tmp = os.path.join(src, "fssm_index.json.tmp") # written last and renamed in, so a stopped run leaves none
with open(tmp, "w", encoding="utf-8") as f:
json.dump(rows, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, os.path.join(src, "fssm_index.json"))
print("magic:", dict(Counter(r["magic"] for r in rows)))
print("s_endpgm per blob:", dict(Counter(len(r["endpgm"]) for r in rows)))
sizes = sorted(r["size"] for r in rows)

View File

@ -21,6 +21,7 @@ import zlib
ENTRY = re.compile(rb"([\x21-\x7e]{3,200})\x00(.)(....)(....)\3(....)", re.DOTALL)
STAGES = {0: "ps", 1: "vs", 2: "gs", 3: "hs", 4: "ds", 5: "cs", 6: "lib", 13: "ms", 14: "as"}
RESERVED = {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f"LPT{i}" for i in range(1, 10))}
def parts(dxbc: bytes) -> dict:
@ -40,10 +41,29 @@ def shader_model(dxbc: bytes, p: dict):
return STAGES.get(kind, str(kind)), f"{ver >> 4}.{ver & 0xF}"
def file_name(name: str, seen: dict, used: set) -> str:
"""A file name for `name` that no earlier shader has, as Windows compares them: without case, and with the
device names (CON, NUL, COM1...) that open a device instead of a file. Same name twice means distinct
variants; the second gets ~1, the third ~2."""
base = re.sub(r'[<>:"/\\|?*]', "_", name)
if base.split(".")[0].upper() in RESERVED:
base = "_" + base
key = base.lower()
n = seen.get(key, 0)
while True:
fname = base + (f"~{n}" if n else "") + ".dxbc"
if fname.lower() not in used:
break
n += 1
seen[key] = n + 1
used.add(fname.lower())
return fname
def main() -> int:
src, out = sys.argv[1], sys.argv[2]
os.makedirs(out, exist_ok=True)
index, seen, bad = [], {}, 0
index, seen, used, bad = [], {}, set(), 0
with open(src, "rb") as fh:
m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
for mt in ENTRY.finditer(m):
@ -63,16 +83,18 @@ def main() -> int:
continue
p = parts(data)
stage, sm = shader_model(data, p)
# Same name twice means distinct variants; keep both.
n = seen.get(name, 0)
seen[name] = n + 1
fname = re.sub(r'[<>:"/\\|?*]', "_", name) + (f"~{n}" if n else "") + ".dxbc"
fname = file_name(name, seen, used)
with open(os.path.join(out, fname), "wb") as f:
f.write(data)
index.append({"name": name, "file": fname, "offset": mt.start(), "kind": mt.group(2)[0],
"stage": stage, "sm": sm, "size": size, "parts": {k: v[1] for k, v in p.items()}})
with open(os.path.join(out, "index.json"), "w", encoding="utf-8") as f:
# make_game.py takes index.json as proof the carve finished: write it last, under another name, then rename.
tmp = os.path.join(out, "index.json.tmp")
with open(tmp, "w", encoding="utf-8") as f:
json.dump(index, f, indent=1)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, os.path.join(out, "index.json"))
from collections import Counter
print(f"{len(index)} shaders carved, {bad} candidates rejected")
print("stages:", dict(Counter(e["stage"] for e in index)))