From 1e2ceda9d3958330b158f96c0b60c165786e3d58 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 05:19:47 +0100 Subject: [PATCH 01/24] test: fssm_pack.py, synthetic FSSM programs from hand-written RDNA2 assembly runtime/test/lanterns/fssm_pack.py assembles .asm with llvm-mc and packs the code into an FSSM program in the layout docs/design.md and tools/fssm_header.py describe (code section at 0xC0/0xC8 with the code 0x28 in, the wave flag at 0xD4, the code end at 0xE8, the 0x120/0x12C/0x130 directory, the PS input table or the CS thread-group header at 0x138, the binding-table tail). It wraps the program in the container the title ships (DXBC { DXIL { XDAT { 0x0D: XBCH + zlib(FSSM) } } }, plus an ISG1 part when a pixel shader reads SV_Position). With --translate it runs fssm_unpack.py, shader_disasm.py and rdna2spirv.py on the folder, as make_game.py's shaders stage does, and fails unless every shader comes back: same blob, decoded from the header with no invalid word, and a row in spirv/index.json keyed by the packed program's SHA-256. It is a test helper, so it does not live in tools/: make_game.py's translator_digest() hashes every file there, and a new one would make a resumed shaders stage throw away its finished shards. tests/test_fssm_pack.py (standard library, the check job) reads the packed fields back with fssm_header.py, the code range with shader_disasm.py and the container with fssm_unpack.py, and checks the refusals. tests/test_fssm_pack_chain.py (pytest, the translator-tests job, which has llvm-mc 21 and spirv-tools) runs the whole offline chain on three small programs. The runtime workflow's path filter gains tools/rdna2_decode.py and tools/rdna2_isa_tables.py: shader_disasm.py imports them, and tests/test_runtime_paths.py requires every tool a runtime/ script runs to be listed there. --- runtime/test/lanterns/fssm_pack.py | 360 +++++++++++++++++++++++++++++ tests/test_fssm_pack.py | 65 ++++++ tests/test_fssm_pack_chain.py | 88 +++++++ 3 files changed, 513 insertions(+) create mode 100644 runtime/test/lanterns/fssm_pack.py create mode 100644 tests/test_fssm_pack.py create mode 100644 tests/test_fssm_pack_chain.py diff --git a/runtime/test/lanterns/fssm_pack.py b/runtime/test/lanterns/fssm_pack.py new file mode 100644 index 0000000000..2700aa85f7 --- /dev/null +++ b/runtime/test/lanterns/fssm_pack.py @@ -0,0 +1,360 @@ +"""Pack hand-written RDNA2 assembly into a synthetic FSSM program inside the title's shader container. + + python -I runtime/test/lanterns/fssm_pack.py [...] [--translate] [--mcpu gfx1013] + +It is a test helper: the Lanterns guest (runtime/test/lanterns) builds its pipelines from what it writes. It lives here, +not in tools/: make_game.py's translator_digest() hashes every file in tools/, so a new file there would make a resumed +shaders stage throw away the shards it had already translated, for a script the game build never runs. + +Each .asm is assembled with llvm-mc (-triple=amdgcn--amdpal -mcpu=gfx1013 -filetype=obj; LLVM_MC names it, see +mc_command.py), and its code is the object's .text section, so branches to labels are resolved by the assembler. The +code goes into an FSSM blob laid out the way docs/design.md and tools/fssm_header.py describe the game's, and the blob +into the container the game ships (DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(FSSM) } } }, tools/fssm_unpack.py), with an +ISG1 input signature part when the pixel shader reads SV_Position. +The tool writes /.dxbc and a carve index /index.json (name, file, stage), the folder shape +make_game.py gets from shader_carve.py. With --translate it then runs the project's own offline chain on that folder, +as make_game.py does for the game: fssm_unpack.py , shader_disasm.py /fssm --out /disasm --mcpu gfx1013, +rdna2spirv.py /disasm --out /spirv. It checks that every shader came back: the unpacked blob is the packed +one, its listing decoded with no invalid word, and spirv/index.json has it with the stage and fssm_sha256 of the +packed blob, which is the key the runtime looks a PSO's shader up by (docs/d3d12_vulkan.md 3.6). Nothing here comes +from the game: the code is ours, the layout is the measured one. + +FSSM fields written (offsets in the blob; every other header byte is zero): + 0x00 'FSSM', u16 version 0x0101 + 0x08 u32 blob size + 0xC0 u64 code-section offset (HEADER_SIZE); the instructions start CODE_SKIP (0x28) bytes into the section + 0xC8 u64 code-section size: CODE_SKIP + code + padding + data + 0xD4 u32 flags: bit 5 (0x20) set for wave32, clear for wave64 (fssm_header.wave_size) + 0xE8 u64 code end: section offset + size (fssm_header.binding_table) + 0x120 / 0x12C / 0x130 u32 section offset, size, and offset + size (fssm_header.directory_ok) + 0x138 PS: one 8-byte input record per "; input:" line (kind 6, semantic, mask 0xF, index, slot, read method); + CS: COMPUTE_PGM_RSRC2 and the thread-group size x, y, z (docs/design.md, "Compute shaders") + code end: 4 x 0xBF9F0000 (s_code_end), u32 0, u32 0, no binding records, 0xFFFFFFFF, u32 0, u16 0, u16 name + length, the name (fssm_header.binding_table) + +Header comments an .asm may carry (before its first instruction): + ; stage: vs | ps | cs default: the name's prefix (vs_, ps_, cs_) + ; wave: 32 | 64 default 32 + ; input: flat | interp [fp16] PS only, one per table position, in v_interp attr order + ; data-at: 0xOFFSET bytes from the first instruction to the data words (what s_getpc_b64 + K reaches) + ; data: 0xWORD ... u32 words placed there, after the code's s_endpgm; s_code_end fills the gap + ; group: X,Y,Z ; rsrc2: 0x... CS only (thread-group size and COMPUTE_PGM_RSRC2) + ; position: xy PS only: the shader reads SV_Position's x and y (any of xyzw). The container gets an + ISG1 part declaring it with that read mask, which rdna2spirv.py turns into the + system VGPRs v2.. (one per component read, in order), as for the title's shaders + ; native-variant: NAME also pack the same code as NAME (its tail name differs, so its FSSM hash does) and + translate NAME without --wave64-emulate even when the others get it: a wave64 + compute shader's native translation beside its exact one, to measure the difference + +With --wave64-emulate (or LEONIDA_W64_EMULATE=1, as for runtime/test/shaders/build.py) the shaders are translated with +rdna2spirv.py --wave64-emulate, which makes wave64 compute shaders exact on 32-wide subgroups; native variants are +translated in a second rdna2spirv.py run into the same spirv/ folder, whose index.json it merges into. +""" +import argparse +import hashlib +import json +import os +import re +import struct +import subprocess +import sys +import zlib + +TOOLS = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "tools")) +sys.path.insert(0, TOOLS) +import mc_command # noqa: E402 + +VERSION = 0x0101 +HEADER_SIZE = 0x200 # where the code section starts; leaves room for 25 PS input records from 0x138 +CODE_SKIP = 0x28 # docs/design.md: code starts at u32[0xC0] + 0x28 +WAVE32 = 0x20 +INPUT_TABLE = 0x138 +INPUT_KIND = 6 +READ_METHODS = {"flat": 0x01, "interp": 0x02} +FP16 = 0x10 +ENDPGM = 0xBF810000 +CODE_END_FILLER = 0xBF9F0000 +SENTINEL = 0xFFFFFFFF +STAGES = ("vs", "ps", "cs") +MAX_INPUTS = (HEADER_SIZE - INPUT_TABLE) // 8 - 1 # leaves a non-6 byte after the last record + + +class PackError(ValueError): + """An .asm header or code that cannot make a well-formed FSSM blob.""" + + +def header_fields(text, name): + """The packing options from an .asm's leading comment lines (see the module docstring).""" + fields = {"stage": name[:2].lower() if name[2:3] == "_" else None, "wave": 32, "inputs": [], + "data_at": None, "data": [], "group": (64, 1, 1), "rsrc2": 0x8088, "native_variant": None, + "position": 0} + for ln in text.splitlines(): + s = ln.strip() + if not s: + continue + if not s.startswith(";"): + break + m = re.match(r";\s*(stage|wave|input|data-at|data|group|rsrc2|native-variant|position):\s*(.*?)\s*$", s) + if not m: + continue + key, value = m.groups() + try: + if key == "stage": + fields["stage"] = value.lower() + elif key == "wave": + fields["wave"] = int(value) + elif key == "input": + words = value.lower().split() + if not words or words[0] not in READ_METHODS or set(words[1:]) - {"fp16"}: + raise PackError(f"{name}: input must be 'flat' or 'interp' [fp16], not {value!r}") + fields["inputs"].append((READ_METHODS[words[0]], "fp16" in words[1:])) + elif key == "data-at": + fields["data_at"] = int(value, 0) + elif key == "data": + fields["data"] += [int(w, 0) for w in value.split()] + elif key == "group": + fields["group"] = tuple(int(v) for v in value.split(",")) + elif key == "rsrc2": + fields["rsrc2"] = int(value, 0) + elif key == "position": + letters = value.lower() + if not letters or set(letters) - set("xyzw"): + raise PackError(f"{name}: position must name components of xyzw, not {value!r}") + fields["position"] = sum(1 << "xyzw".index(c) for c in set(letters)) + elif key == "native-variant": + if not re.fullmatch(r"[A-Za-z0-9_]+", value) or value == name: + raise PackError(f"{name}: native-variant needs another plain name, not {value!r}") + fields["native_variant"] = value + except ValueError as e: + if isinstance(e, PackError): + raise + raise PackError(f"{name}: bad '{key}' value {value!r}") from None + if fields["stage"] not in STAGES: + raise PackError(f"{name}: stage must be one of {STAGES} (a '; stage:' line or a vs_/ps_/cs_ name)") + if fields["wave"] not in (32, 64): + raise PackError(f"{name}: wave must be 32 or 64") + if fields["position"] and fields["stage"] != "ps": + raise PackError(f"{name}: position is for pixel shaders") + if fields["inputs"] and fields["stage"] != "ps": + raise PackError(f"{name}: input records are for pixel shaders") + if len(fields["group"]) != 3: + raise PackError(f"{name}: group needs X,Y,Z") + return fields + + +def pack(code, *, stage, name, wave=32, inputs=(), data_at=None, data=(), group=(64, 1, 1), rsrc2=0x8088): + """One FSSM blob: the header fields above, the code section and the binding-table tail.""" + if len(code) < 4 or len(code) % 4 or struct.unpack_from(" MAX_INPUTS: + raise PackError(f"{name}: at most {MAX_INPUTS} input records fit before the code section") + body = bytearray(code) + if data: + if data_at is None or data_at % 4 or data_at < len(code): + raise PackError(f"{name}: data-at must be a dword offset at or after the code's end (0x{len(code):x})") + if ENDPGM in data: + raise PackError(f"{name}: a data word equal to s_endpgm would end the code for shader_disasm.py") + body += struct.pack(" len(obj) or shstrndx >= shnum: + raise PackError(f"{name}.asm: llvm-mc's object has a section table this tool cannot read") + sections = [ELF_SECTION.unpack_from(obj, shoff + i * shentsize) for i in range(shnum)] + names_at = sections[shstrndx][4] + text = None + for section in sections: + start = names_at + section[0] + label = obj[start:obj.index(b"\0", start)].decode("ascii", "replace") + if label in (".rel.text", ".rela.text"): + raise PackError(f"{name}.asm: llvm-mc left relocations in .text (a branch to a label it does not define?)") + if label == ".text": + text = obj[section[4]:section[4] + section[5]] + if text is None: + raise PackError(f"{name}.asm: llvm-mc's object has no .text section") + return text + + +def assemble(text, name, mcpu="gfx1013", wave=32): + """The code bytes of the .asm text: llvm-mc assembles it into an ELF object (on stdout) and the code is its .text + section, so branches to labels come out resolved, as the assembler lays them out. Wave64 code is assembled with + +wavefrontsize64, so it can name VCC and 64-bit masks as such; the encodings are the same.""" + cmd = mc_command.mc_command() + ["-triple=amdgcn--amdpal", f"-mcpu={mcpu}", "-filetype=obj", "-o", "-"] + if wave == 64: + cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") + r = mc_command.run(cmd, input=text.encode("utf-8"), capture_output=True) + errors = r.stderr.decode("utf-8", "replace") + if r.returncode or "error:" in errors: + raise PackError(f"{name}.asm did not assemble:\n{errors}") + return text_section(r.stdout, name) + + +def pack_file(path, out, mcpu="gfx1013"): + """Assemble and pack one .asm (and its native variant, if it names one); writes /.dxbc for each. + Returns [(name, stage, fssm blob, native)].""" + name = os.path.splitext(os.path.basename(path))[0] + with open(path, encoding="utf-8") as f: + text = f.read() + fields = header_fields(text, name) + variant = fields.pop("native_variant") + position = fields.pop("position") + code = assemble(text, name, mcpu, fields["wave"]) + packed = [] + for packed_name, native in ((name, False),) + (((variant, True),) if variant else ()): + blob = pack(code, name=packed_name, **fields) + with open(os.path.join(out, packed_name + ".dxbc"), "wb") as f: + f.write(container(blob, position)) + packed.append((packed_name, fields["stage"], blob, native)) + return packed + + +def run_tool(tool, *args): + r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool), *map(str, args)], + capture_output=True, text=True) + if r.returncode: + raise PackError(f"{tool} exited with {r.returncode}:\n{r.stdout[-2000:]}{r.stderr[-2000:]}") + return r.stdout + + +def translate(out, packed, mcpu="gfx1013", emulate=False): + """Run fssm_unpack.py, shader_disasm.py and rdna2spirv.py on and check that every packed shader made it + through. Returns the rows of spirv/index.json for the packed shaders.""" + run_tool("fssm_unpack.py", out) + disasm = os.path.join(out, "disasm") + os.makedirs(disasm, exist_ok=True) + run_tool("shader_disasm.py", os.path.join(out, "fssm"), "--out", disasm, "--mcpu", mcpu) + for name, _, blob, _ in packed: + with open(os.path.join(out, "fssm", name + ".fssm"), "rb") as f: + if f.read() != blob: + raise PackError(f"{name}: fssm_unpack.py did not give back the packed blob") + with open(os.path.join(disasm, name + ".s"), encoding="utf-8") as f: + first = f.readline() + if "(header)" not in first or not first.rstrip().endswith(" 0 invalid words"): + raise PackError(f"{name}: shader_disasm.py did not decode the code from the header: {first.strip()}") + spirv = os.path.join(out, "spirv") + natives = [name for name, _, _, native in packed if native] if emulate else [] + if natives: + # A second listing folder beside disasm/ (rdna2spirv.py reads fssm/, the .dxbc and index.json from the parent). + native_dir = os.path.join(out, "disasm_native") + os.makedirs(native_dir, exist_ok=True) + for name in natives: + os.replace(os.path.join(disasm, name + ".s"), os.path.join(native_dir, name + ".s")) + translated = run_tool("rdna2spirv.py", disasm, "--out", spirv, *(["--wave64-emulate"] if emulate else [])) + if natives: + translated += run_tool("rdna2spirv.py", native_dir, "--out", spirv) + with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: + index = json.load(f) + rows = {} + for name, stage, blob, _ in packed: + row = index.get(name) + want = hashlib.sha256(blob).hexdigest() + if not row or row.get("stage") != stage or row.get("fssm_sha256") != want: + raise PackError(f"{name}: spirv/index.json has no {stage} entry with fssm_sha256 {want}; " + f"rdna2spirv.py said:\n{translated[-2000:]}") + rows[name] = row + return rows + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Pack RDNA2 assembly into synthetic FSSM programs in shader containers.") + ap.add_argument("out", help="folder for .dxbc and index.json (and fssm/, disasm/, spirv/ with --translate)") + ap.add_argument("asm", nargs="+", help="hand-written .asm files") + ap.add_argument("--translate", action="store_true", help="run fssm_unpack, shader_disasm and rdna2spirv after") + ap.add_argument("--mcpu", default="gfx1013") + ap.add_argument("--wave64-emulate", action="store_true", + help="translate with rdna2spirv.py --wave64-emulate (also LEONIDA_W64_EMULATE=1)") + a = ap.parse_args(argv) + emulate = a.wave64_emulate or os.environ.get("LEONIDA_W64_EMULATE") == "1" + # As build.py: CMake names the spirv-as/spirv-val folder instead of passing a whole PATH. + if os.environ.get("LEONIDA_SPIRV_TOOLS"): + os.environ["PATH"] = os.environ["LEONIDA_SPIRV_TOOLS"] + os.pathsep + os.environ.get("PATH", "") + os.makedirs(a.out, exist_ok=True) + try: + packed = [entry for p in a.asm for entry in pack_file(p, a.out, a.mcpu)] + names = [entry[0] for entry in packed] + if len(set(names)) != len(names): + raise PackError("two shaders have the same name: " + ", ".join(sorted({n for n in names if names.count(n) > 1}))) + carve = [{"name": n, "file": n + ".dxbc", "stage": s, "size": os.path.getsize(os.path.join(a.out, n + ".dxbc"))} + for n, s, _, _ in packed] + with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(carve, f, indent=1) + f.write("\n") + rows = translate(a.out, packed, a.mcpu, emulate) if a.translate else {} + except PackError as e: + print(f"ERROR: {e}", file=sys.stderr) + return 1 + for name, stage, blob, _ in packed: + row = rows.get(name, {}) + wave = 32 if struct.unpack_from(".asm with --translate; returns the out folder and its spirv/index.json.""" + src = tmp_path / f"{name}.asm" + src.write_text(asm, encoding="utf-8") + out = tmp_path / "out" + env = dict(os.environ) + env.setdefault("LLVM_MC", subprocess.list2cmdline(LLVM_MC) if LLVM_MC else "llvm-mc") + r = subprocess.run([sys.executable, "-I", PACK, str(out), str(src), "--translate", *flags], + capture_output=True, text=True, env=env, timeout=300) + assert r.returncode == 0, r.stdout + r.stderr + return out, json.loads((out / "spirv" / "index.json").read_text(encoding="utf-8")) + + +def test_translated_index_is_keyed_by_the_packed_blob(tmp_path): + asm = ("; stage: ps\n; wave: 32\n; input: flat\n; data-at: 0x40\n; data: 0x3f000000\n" + "v_interp_mov_f32 v2, p0, attr0.x\nv_mov_b32_e32 v3, 1.0\n" + "exp mrt0 v2, v3, v3, v3 done vm\ns_endpgm\n") + out, index = pack_and_translate(tmp_path, "ps_chain", asm) + blob = (out / "fssm" / "ps_chain.fssm").read_bytes() + row = index["ps_chain"] + assert row["fssm_sha256"] == hashlib.sha256(blob).hexdigest() + assert (row["stage"], row["ps_flat_interpolants"]) == ("ps", [0]) + + +@pytest.mark.parametrize("header, system_inputs", [("; stage: ps\n; position: xy\n", ["0", "1"]), + ("; stage: ps\n", None)]) +def test_position_header_lets_a_pixel_shader_read_sv_position(tmp_path, header, system_inputs): + # With the ISG1 part v2 and v3 are FragCoord.x and .y; without it the translator takes them for registers + # nothing wrote (zeros), and the shader would read 0 for every pixel. + body = "v_cvt_u32_f32_e32 v4, v2\nv_cvt_u32_f32_e32 v5, v3\nexp mrt0 v4, v5, v4, v5 done vm\ns_endpgm\n" + _, index = pack_and_translate(tmp_path, "ps_pos", header + body) + assert index["ps_pos"].get("ps_system_inputs") == system_inputs + + +def test_branches_to_labels_are_resolved(tmp_path): + # A loop (backward s_cbranch_scc0) and a jump over one instruction (forward s_branch), both to labels. The packed + # code must carry the offsets llvm-mc resolves, and --translate decodes it from the header with 0 invalid words. + asm = ("; stage: ps\n" + "s_mov_b32 s0, 2\n" # 0x00 + "loop:\n" + "s_sub_u32 s0, s0, 1\n" # 0x04 + "s_cmp_eq_u32 s0, 0\n" # 0x08 + "s_cbranch_scc0 loop\n" # 0x0c: back to 0x04, (0x04 - 0x10) / 4 = -3 + "s_branch done\n" # 0x10: on to 0x18, (0x18 - 0x14) / 4 = 1 + "v_mov_b32_e32 v0, 0\n" # 0x14, jumped over + "done:\n" + "v_mov_b32_e32 v1, 1.0\n" # 0x18 + "exp mrt0 v1, v1, v1, v1 done vm\n" + "s_endpgm\n") + out, index = pack_and_translate(tmp_path, "ps_branch", asm) + blob = (out / "fssm" / "ps_branch.fssm").read_bytes() + code_at = struct.unpack_from(" Date: Mon, 23 Nov 2026 05:19:47 +0100 Subject: [PATCH 02/24] ci: the runtime workflow also runs for tools/rdna2_decode.py and rdna2_isa_tables.py runtime/test/lanterns/fssm_pack.py runs shader_disasm.py, which imports them, and tests/test_runtime_paths.py requires every tool a runtime/ script reaches to be in the runtime workflow's path filter. --- .github/workflows/runtime.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 45478151f3..f30431a8db 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -34,6 +34,8 @@ on: - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" + - "tools/rdna2_decode.py" + - "tools/rdna2_isa_tables.py" - "tools/rdna2spirv.py" - "tools/report_paths.py" - "tools/shader_carve.py" @@ -72,6 +74,8 @@ on: - "tools/lane_masks.py" - "tools/mc_command.py" - "tools/mesh_compute_vs.py" + - "tools/rdna2_decode.py" + - "tools/rdna2_isa_tables.py" - "tools/rdna2spirv.py" - "tools/report_paths.py" - "tools/shader_carve.py" From 369e071669d7750e2e5b7ea891c31f20d18333b1 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 05:55:34 +0100 Subject: [PATCH 03/24] test: fssm_pack.py writes slot bytes, binding records and two 0x0D payloads The packer wrote one narrow container layout: every PS input's slot byte was position + 1, the tail had no binding records, and XDAT had one 0x0D entry. A reader that took the slot byte for the attr number, or the first of two payloads, would still pass on what it packed. - "; input: ... slot=N" sets byte 6 of the record; the attr number stays the table position. - "; binding: W0 W1 W2 W3 W4" adds a 20-byte record to the tail (fssm_header.binding_table reads them back in order). - "; first-payload: NAME" puts a second program (the same code under NAME, so another hash) in a first 0x0D entry, as 195 of the title's containers have two. fssm_unpack.py and the runtime take the last. Tests: the slot bytes, records and both payloads read back (test_fssm_pack.py), and through the offline chain a PS with slot 9, a binding record and a first payload is keyed by its own blob with its flat input at position 0 (test_fssm_pack_chain.py; the old packer fails it). --- runtime/test/lanterns/fssm_pack.py | 76 ++++++++++++++++++++++-------- tests/test_fssm_pack.py | 34 +++++++++++++ tests/test_fssm_pack_chain.py | 14 ++++++ 3 files changed, 105 insertions(+), 19 deletions(-) diff --git a/runtime/test/lanterns/fssm_pack.py b/runtime/test/lanterns/fssm_pack.py index 2700aa85f7..fc0eb2fd54 100644 --- a/runtime/test/lanterns/fssm_pack.py +++ b/runtime/test/lanterns/fssm_pack.py @@ -29,13 +29,21 @@ 0x120 / 0x12C / 0x130 u32 section offset, size, and offset + size (fssm_header.directory_ok) 0x138 PS: one 8-byte input record per "; input:" line (kind 6, semantic, mask 0xF, index, slot, read method); CS: COMPUTE_PGM_RSRC2 and the thread-group size x, y, z (docs/design.md, "Compute shaders") - code end: 4 x 0xBF9F0000 (s_code_end), u32 0, u32 0, no binding records, 0xFFFFFFFF, u32 0, u16 0, u16 name - length, the name (fssm_header.binding_table) + code end: 4 x 0xBF9F0000 (s_code_end), u32 0, u32 0, the "; binding:" records (20 bytes each, none by default), + 0xFFFFFFFF, u32 0, u16 0, u16 name length, the name (fssm_header.binding_table) Header comments an .asm may carry (before its first instruction): ; stage: vs | ps | cs default: the name's prefix (vs_, ps_, cs_) ; wave: 32 | 64 default 32 - ; input: flat | interp [fp16] PS only, one per table position, in v_interp attr order + ; input: flat | interp [fp16] [slot=N] + PS only, one per table position, in v_interp attr order. The record's parameter + slot (byte 6) is position + 1 unless slot= gives another: the table position, not + the slot, is the attr number the code reads (fssm_header.py) + ; binding: W0 W1 W2 W3 W4 one 20-byte binding record (five u32) in the tail, in order; the title's tails carry + 5,640,704 of them (fssm_header.py), nothing in the chain reads their fields yet + ; first-payload: NAME the container gets two XDAT 0x0D entries, as 195 of the title's do: first the same + code packed under NAME (another hash), then this shader's. fssm_unpack.py and the + runtime take the last one, so a reader that took the first would miss the shader ; data-at: 0xOFFSET bytes from the first instruction to the data words (what s_getpc_b64 + K reaches) ; data: 0xWORD ... u32 words placed there, after the code's s_endpgm; s_code_end fills the gap ; group: X,Y,Z ; rsrc2: 0x... CS only (thread-group size and COMPUTE_PGM_RSRC2) @@ -87,14 +95,14 @@ def header_fields(text, name): """The packing options from an .asm's leading comment lines (see the module docstring).""" fields = {"stage": name[:2].lower() if name[2:3] == "_" else None, "wave": 32, "inputs": [], "data_at": None, "data": [], "group": (64, 1, 1), "rsrc2": 0x8088, "native_variant": None, - "position": 0} + "position": 0, "bindings": [], "first_payload": None} for ln in text.splitlines(): s = ln.strip() if not s: continue if not s.startswith(";"): break - m = re.match(r";\s*(stage|wave|input|data-at|data|group|rsrc2|native-variant|position):\s*(.*?)\s*$", s) + m = re.match(r";\s*(stage|wave|input|data-at|data|group|rsrc2|native-variant|position|binding|first-payload):\s*(.*?)\s*$", s) if not m: continue key, value = m.groups() @@ -105,9 +113,23 @@ def header_fields(text, name): fields["wave"] = int(value) elif key == "input": words = value.lower().split() - if not words or words[0] not in READ_METHODS or set(words[1:]) - {"fp16"}: - raise PackError(f"{name}: input must be 'flat' or 'interp' [fp16], not {value!r}") - fields["inputs"].append((READ_METHODS[words[0]], "fp16" in words[1:])) + slots = [w for w in words[1:] if w.startswith("slot=")] + if (not words or words[0] not in READ_METHODS or set(words[1:]) - {"fp16"} - set(slots) + or len(slots) > 1): + raise PackError(f"{name}: input must be 'flat' or 'interp' [fp16] [slot=N], not {value!r}") + slot = int(slots[0][5:], 0) if slots else len(fields["inputs"]) + 1 + if not 0 <= slot <= 0xFF: + raise PackError(f"{name}: an input's slot is one byte, not {slot}") + fields["inputs"].append((READ_METHODS[words[0]], "fp16" in words[1:], slot)) + elif key == "binding": + words = [int(w, 0) for w in value.split()] + if len(words) != 5 or not all(0 <= w <= 0xFFFFFFFF for w in words) or words[0] == SENTINEL: + raise PackError(f"{name}: a binding is five u32 words, the first not 0xFFFFFFFF, not {value!r}") + fields["bindings"].append(tuple(words)) + elif key == "first-payload": + if not re.fullmatch(r"[A-Za-z0-9_]+", value) or value == name: + raise PackError(f"{name}: first-payload needs another plain name, not {value!r}") + fields["first_payload"] = value elif key == "data-at": fields["data_at"] = int(value, 0) elif key == "data": @@ -142,8 +164,10 @@ def header_fields(text, name): return fields -def pack(code, *, stage, name, wave=32, inputs=(), data_at=None, data=(), group=(64, 1, 1), rsrc2=0x8088): - """One FSSM blob: the header fields above, the code section and the binding-table tail.""" +def pack(code, *, stage, name, wave=32, inputs=(), data_at=None, data=(), group=(64, 1, 1), rsrc2=0x8088, + bindings=()): + """One FSSM blob: the header fields above, the code section and the binding-table tail. inputs: (read method, + fp16) or (read method, fp16, slot) per table position; bindings: five-word records for the tail.""" if len(code) < 4 or len(code) % 4 or struct.unpack_from(" MAX_INPUTS: @@ -159,7 +183,10 @@ def pack(code, *, stage, name, wave=32, inputs=(), data_at=None, data=(), group= section_size = CODE_SKIP + len(body) code_end = HEADER_SIZE + section_size label = name.encode("ascii") + if any(len(b) != 5 or b[0] == SENTINEL for b in bindings): + raise PackError(f"{name}: a binding record is five u32 words, the first not the sentinel") tail = (struct.pack(" Date: Mon, 23 Nov 2026 06:34:21 +0100 Subject: [PATCH 04/24] fix: fssm_pack.py refuses shader names that differ only in case Every output is named after its shader (.dxbc, fssm/.fssm, disasm/.s, the SPIR-V). Two inputs such as a/ps_tile.asm and b/ps_Tile.asm, or a native variant named like its shader in another case, wrote one file on a case-insensitive volume (Windows, macOS) while index.json listed two rows, and the packer exited 0. The first row then read the second shader's container. pack_file() now only packs; main() compares all names after casefold() and refuses a clash, naming both inputs, before it creates the output folder or writes any file. --- runtime/test/lanterns/fssm_pack.py | 35 ++++++++++++++++-------- tests/test_fssm_pack.py | 44 ++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 11 deletions(-) diff --git a/runtime/test/lanterns/fssm_pack.py b/runtime/test/lanterns/fssm_pack.py index fc0eb2fd54..c5cc09de42 100644 --- a/runtime/test/lanterns/fssm_pack.py +++ b/runtime/test/lanterns/fssm_pack.py @@ -286,9 +286,9 @@ def assemble(text, name, mcpu="gfx1013", wave=32): return text_section(r.stdout, name) -def pack_file(path, out, mcpu="gfx1013"): - """Assemble and pack one .asm (and its native variant, if it names one); writes /.dxbc for each. - Returns [(name, stage, fssm blob, native)].""" +def pack_file(path, mcpu="gfx1013"): + """Assemble and pack one .asm (and its native variant, if it names one). Writes nothing: main() checks every name + first. Returns [(name, stage, fssm blob, native, container, path)].""" name = os.path.splitext(os.path.basename(path))[0] with open(path, encoding="utf-8") as f: text = f.read() @@ -301,12 +301,20 @@ def pack_file(path, out, mcpu="gfx1013"): packed = [] for packed_name, native in ((name, False),) + (((variant, True),) if variant else ()): blob = pack(code, name=packed_name, **fields) - with open(os.path.join(out, packed_name + ".dxbc"), "wb") as f: - f.write(container(blob, position, first)) - packed.append((packed_name, fields["stage"], blob, native)) + packed.append((packed_name, fields["stage"], blob, native, container(blob, position, first), path)) return packed +def name_clashes(entries): + """Names that would share an output file on a case-insensitive volume (Windows, macOS): every output is named + after the shader (.dxbc, fssm/.fssm, disasm/.s, the SPIR-V), so two names equal after casefold() + would overwrite each other's files. Returns one message per clash, naming the inputs.""" + seen = {} + for name, _, _, native, _, path in entries: + seen.setdefault(name.casefold(), []).append(f"{name} ({path}{', native variant' if native else ''})") + return [" and ".join(names) for names in seen.values() if len(names) > 1] + + def run_tool(tool, *args): r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool), *map(str, args)], capture_output=True, text=True) @@ -367,12 +375,17 @@ def main(argv=None): # As build.py: CMake names the spirv-as/spirv-val folder instead of passing a whole PATH. if os.environ.get("LEONIDA_SPIRV_TOOLS"): os.environ["PATH"] = os.environ["LEONIDA_SPIRV_TOOLS"] + os.pathsep + os.environ.get("PATH", "") - os.makedirs(a.out, exist_ok=True) try: - packed = [entry for p in a.asm for entry in pack_file(p, a.out, a.mcpu)] - names = [entry[0] for entry in packed] - if len(set(names)) != len(names): - raise PackError("two shaders have the same name: " + ", ".join(sorted({n for n in names if names.count(n) > 1}))) + entries = [entry for p in a.asm for entry in pack_file(p, a.mcpu)] + clashes = name_clashes(entries) + if clashes: + raise PackError("shader names must differ in more than case, since each names its output files; nothing " + "was written: " + "; ".join(clashes)) + os.makedirs(a.out, exist_ok=True) + for name, _, _, _, data, _ in entries: + with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: + f.write(data) + packed = [entry[:4] for entry in entries] carve = [{"name": n, "file": n + ".dxbc", "stage": s, "size": os.path.getsize(os.path.join(a.out, n + ".dxbc"))} for n, s, _, _ in packed] with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: diff --git a/tests/test_fssm_pack.py b/tests/test_fssm_pack.py index f59316cb0f..3a31942060 100644 --- a/tests/test_fssm_pack.py +++ b/tests/test_fssm_pack.py @@ -6,10 +6,14 @@ python -I tests/test_fssm_pack.py """ +import contextlib +import io import os import struct 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, os.path.join(ROOT, "tools")) @@ -95,5 +99,45 @@ def test_refuses_what_would_not_read_back(self): fssm_pack.pack(stage="ps", name="ps_t", **kwargs) +class Names(unittest.TestCase): + """Every output file is named after its shader, so two names equal but for case would share files on a + case-insensitive volume. The packer must refuse them before it writes anything.""" + + def run_main(self, files): + with tempfile.TemporaryDirectory() as tmp: + paths = [] + for rel, text in files: + path = os.path.join(tmp, rel) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + paths.append(path) + out = os.path.join(tmp, "out") + err = io.StringIO() + with mock.patch.object(fssm_pack, "assemble", return_value=struct.pack(" Date: Mon, 23 Nov 2026 05:52:46 +0100 Subject: [PATCH 05/24] test: Lanterns stage 1, a synthetic title-shaped guest drawn through gta6rt --run Lanterns is an x64 guest that goes through the chain a title would: its hand-written RDNA2 shaders are packed into FSSM programs inside DXBC/XDAT/XBCH containers (runtime/test/lanterns/fssm_pack.py) and translated by fssm_unpack.py, shader_disasm.py and rdna2spirv.py; gta6rt --run maps it and answers d3d12_xs.dll!D3D12XboxCreateDevice with the Vulkan device; the guest builds its pipelines from the containers through the D3D12 API. lanterns.cpp is the guest's checks, lanterns_gpu.cpp/.h its D3D12 side and lanterns_d3d12.h the shared helpers, the layout later stages extend. Stage 1: five DrawIndexedInstanced calls (prisms, cubes, octahedra, pyramids, a checker floor) into a 384x256 RGBA32F target with D32 depth. Vertex, index and instance buffers sit in DEFAULT heaps, filled by upload copies; the VS fetches through two V#s in two descriptor tables, the model matrix and tint come from root constants, the camera from a root CBV, and the floor PS reads its colours through the code base. Interior pixels must match the CPU reference bit for bit; edge, depth-tie and checker-border pixels must be one of their candidate colours. A container whose FSSM program the index does not know must be refused, and with the depth test off exactly the pixels the reference predicts must change. run_lanterns.py passes a run only on exit 0, the PASS line once and the shim's complete factory line, and kills the whole process group when its timeout expires (tests/test_run_lanterns.py, with a launcher that never ends). Opt-in with -DLEONIDA_TEST_LANTERNS=ON; nothing is built or run by default. The guest links tiny_frame's failing d3d12_xs stub (test/fixtures, #3488) instead of a copy. docs/lanterns.md says what it covers, how to run it and its limits. --- docs/README.md | 1 + docs/d3d12_vulkan.md | 7 + docs/lanterns.md | 131 +++++++ runtime/CMakeLists.txt | 2 + runtime/test/lanterns/lanterns.cmake | 67 ++++ runtime/test/lanterns/lanterns.cpp | 138 ++++++++ runtime/test/lanterns/lanterns_d3d12.h | 50 +++ runtime/test/lanterns/lanterns_gpu.cpp | 321 ++++++++++++++++++ runtime/test/lanterns/lanterns_gpu.h | 72 ++++ runtime/test/lanterns/lanterns_reference.h | 239 +++++++++++++ runtime/test/lanterns/lanterns_scene.h | 226 ++++++++++++ runtime/test/lanterns/run_lanterns.py | 223 ++++++++++++ .../lanterns/shaders/ps_lanterns_floor.asm | 48 +++ .../test/lanterns/shaders/ps_lanterns_lit.asm | 13 + runtime/test/lanterns/shaders/vs_lanterns.asm | 60 ++++ tests/test_run_lanterns.py | 80 +++++ 16 files changed, 1678 insertions(+) create mode 100644 docs/lanterns.md create mode 100644 runtime/test/lanterns/lanterns.cmake create mode 100644 runtime/test/lanterns/lanterns.cpp create mode 100644 runtime/test/lanterns/lanterns_d3d12.h create mode 100644 runtime/test/lanterns/lanterns_gpu.cpp create mode 100644 runtime/test/lanterns/lanterns_gpu.h create mode 100644 runtime/test/lanterns/lanterns_reference.h create mode 100644 runtime/test/lanterns/lanterns_scene.h create mode 100644 runtime/test/lanterns/run_lanterns.py create mode 100644 runtime/test/lanterns/shaders/ps_lanterns_floor.asm create mode 100644 runtime/test/lanterns/shaders/ps_lanterns_lit.asm create mode 100644 runtime/test/lanterns/shaders/vs_lanterns.asm create mode 100644 tests/test_run_lanterns.py diff --git a/docs/README.md b/docs/README.md index a5bd39f357..2738a990a9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -74,6 +74,7 @@ method, scope and caveats. No game data is included. | [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. | | [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | | [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 13 of 29 translate with `tools/fspx_unpack.py`. | +| [lanterns.md](lanterns.md) | Lanterns, a synthetic title-shaped guest through `gta6rt --run`: hand-written RDNA2 shaders packed into FSSM containers, translated offline, drawn on the Vulkan device and checked pixel by pixel against a CPU reference, with a negative control; stage 1 (five instanced draws with depth) passes on an RTX 5080 under Wine. | | [first_light.md](first_light.md) | The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). | | [material_pass_replay.md](material_pass_replay.md) | How one authored mesh writes packed draw indices, how six compute programs read the layout, and which sibling passes read the surface material. | | [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool and the one rule still missing. | diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 9de1527b94..acdc55ad98 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3137,6 +3137,13 @@ M0–M2 do not need the executable. | **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | | **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). **Plane compose** (section 4.5): 1-2 planes scaled from a source rectangle to a destination placement, point or bilinear, plane 1 alpha-blended (premultiplied or straight), filtered and blended in linear light, SDR (sRGB or gamma 2.2) and HDR10 (PQ) planes converted to the swapchain, SDR white from Windows' setting when HDR10 is active (else 203 nits), checked against a CPU model on two GPUs with 0 VUIDs (exact for point filtering, within 1-2 levels for bilinear, alpha, tone map and PQ conversions); the layouts, flag values and alpha convention are ours, the console's plane semantics are unmeasured, and the public HDR sample's second plane is the GameDVR copy, not an overlay. HDR10 swapchain (ST.2084 surface): verified on an RTX 5080 with an HDR10 display by @JavierBlanco23 in #2069, not on AMD (our test displays list no ST.2084 surface); HDR10 on an SDR swapchain is tone mapped (identity below 0.8 of SDR white, Reinhard shoulder above, then clipped per channel). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; VRS, alt-tab, an AMD HDR10 display run are open | +**Milestones together in one guest.** [lanterns.md](lanterns.md) runs a synthetic title-shaped guest under +`gta6rt --run`, with hand-written shaders that take the title's FSSM container path (`fssm_unpack.py`, +`shader_disasm.py`, `rdna2spirv.py`). Its stage 1 covers the M1/M1.5 contracts in one frame: translated VS and PS +found by FSSM hash, V# vertex and instance fetch, root constants, a root CBV, the code base, and a depth buffer. Every +pixel is checked against a CPU reference, with a depth-off negative control. It is opt-in +(`-DLEONIDA_TEST_LANTERNS=ON`). + **M3 occlusion portability (D3D-209).** Vulkan's [occlusion query specification](https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#queries-occlusion) permits a count multiplied by the number of written color outputs, even with `VK_QUERY_CONTROL_PRECISE_BIT`. The original two-output query returned twice the CPU area on Intel UHD (Windows driver 31.0.101.4146), diff --git a/docs/lanterns.md b/docs/lanterns.md new file mode 100644 index 0000000000..9eb30abb8c --- /dev/null +++ b/docs/lanterns.md @@ -0,0 +1,131 @@ +# Lanterns: a synthetic title through `gta6rt --run` + +Lanterns is a test guest, an x64 Windows program shaped like a title. It goes through the same chain a title would: + +1. Its RDNA2 shaders are hand-written. They are packed into synthetic FSSM programs inside the container the title + ships: `DXBC { DXIL { XDAT { 0x0D: XBCH + zlib(FSSM) } } }`. +2. The project's offline tools translate them, the way `make_game.py`'s shaders stage does: `fssm_unpack.py`, + `shader_disasm.py` (code range from the FSSM header) and `rdna2spirv.py`. +3. `gta6rt --run` maps the guest and answers its imports. The guest gets its device only from + `d3d12_xs.dll!D3D12XboxCreateDevice`, which the shim registry answers with the Vulkan device + (`LEONIDA_D3D12=vulkan`). +4. The guest creates its pipelines from those containers through the D3D12 API. The layer finds each translated shader + by the SHA-256 of its FSSM program. +5. The guest draws, reads the frame back and compares every pixel with a CPU reference. A negative control then shows + that the check would have caught a wrong frame. + +Nothing comes from the game. The scene is abstract solids on a checkered floor, and the shaders, scene and reference +are ours. + +Code: `runtime/test/lanterns/`. `lanterns.cpp` is the guest and `lanterns_gpu.cpp` its D3D12 side. +`lanterns_scene.h` is the scene and `lanterns_reference.h` the CPU reference. `shaders/*.asm` are the shaders, +`fssm_pack.py` the packer, `run_lanterns.py` the runner and `lanterns.cmake` the build. + +## How it relates to the other synthetic tests + +Each boot milestone in [d3d12_vulkan.md](d3d12_vulkan.md) section 6 has its own gate: `d3d12_draw_test` (M1), +`d3d12_translated_draw_test` (M1.5), `d3d12_m2_textured_test`, `d3d12_m3_frame_test` and `d3d12_m4_compute_test`. These +are host programs. They link the layer and create the device directly, and most build their shaders with +`runtime/test/shaders/build.py`, which hands llvm-mc's listing straight to the translator. +`run_tiny_frame` (#3488) runs a mapped guest through `gta6rt --run` for a clear and a readback. + +Lanterns puts the pieces together in one guest. Its shaders take the title's path through the FSSM container, +`fssm_unpack.py` and `shader_disasm.py`, and the guest runs under `gta6rt --run`. Each stage then adds what the +milestone tests check one at a time. + +## Stages + +Each stage is its own run (`--stage N`) and prints its own PASS line. Every stage has a control the reference +predicts, so a check that could not tell a right frame from a wrong one fails. + +| Stage | What it adds | Control | +|---|---|---| +| [1](#stage-1) | Five indexed, instanced draws with a depth buffer | Depth test off changes the predicted pixels | + +## Stage 1 + +Five `DrawIndexedInstanced` calls draw hexagonal prisms, cubes, octahedra, pyramids and a checker floor into a 384x256 +`R32G32B32A32_FLOAT` target with a `D32_FLOAT` depth buffer (depth test LESS). The frame is drawn twice: once with the +depth test (the image) and once without it (the negative control). + +What it covers: + +- The PE loader, the shims and `D3D12XboxCreateDevice` on Vulkan, called from a mapped guest. +- Pipelines from DXBC/XDAT/XBCH containers, with each shader found by its FSSM hash. +- Vertex, index and instance buffers in DEFAULT heaps, filled from an upload buffer by `CopyBufferRegion`. +- The vertex shader fetches the vertex and the instance through two V#s in two descriptor tables. It reads the descriptor + heap start handles through heap slots 9 and 10. +- The model matrix and tint come from 16 root constants, and the camera from a root CBV. +- The floor's pixel shader reads its two checker colours from its own FSSM program, through the code base + (`s_getpc_b64`). +- The PS input table declares one flat input and one interpolated input. +- Clear, depth, readback through `CopyTextureRegion`, and a fence wait. + +How the check works: + +- **Exact pixels.** Colours are short binary fractions, so every product the shaders form is exact in float. Pixels + that are clearly inside one face, or clearly background, must match the CPU reference bit for bit. +- **Uncertain pixels.** A few pixels depend on how the GPU rounds: triangle edges, depth near-ties and checker borders. + Each of these must be one of the colours the reference lists for it. +- **Lookup control.** Before drawing, the guest builds a container from the vertex shader's FSSM program with one byte + of its name changed. The layer must refuse that pipeline with `E_INVALIDARG`, because no translated shader has + that hash. So a pass cannot come from a lookup that matches anything. +- **Negative control.** With the depth test off, submission order decides what is visible. The reference predicts + which certain pixels change. The GPU frame must change exactly those pixels, and there must be at least 1,000 of + them. A layer that ignored the depth state, or a reference that could not tell the two frames apart, fails here. + +On success the guest prints one line and exits 0: + +``` +Lanterns stage 1: PASS, 97916 of 98304 pixels exact, 388 edge pixels plausible, depth-off control changed 11601 pixels +``` + +`run_lanterns.py` passes the run only when all of these hold: exit code 0, this line exactly once, and the shim's +complete factory line, `[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy 0x... (Vulkan device 0x...)`. That last line +means the device is the Vulkan one, not the host's. The runner's timeout kills the whole process group or tree, so a +stalled guest, Wine or GPU fails the run with exit code 3 instead of hanging it. It writes +`lanterns-stage1.png` and `lanterns-stage1-sheet.png`. The sheet shows the GPU frame, the reference, the control +frame, and a mask (grey: exact, red: wrong, yellow: uncertain). + +A wrong shader fails. We repacked the floor shader with one checker colour changed (red 0.4375 to 0.5). The guest then +reported 20,430 certain pixels wrong and exited 1, and the runner failed the run. + +## Build and run + +The guest is opt-in: `-DLEONIDA_TEST_LANTERNS=ON` (off by default). It needs llvm-mc 21 with the AMDGPU target +(`LLVM_MC`, as for `runtime/test/shaders`), spirv-tools, Python 3, and a Vulkan GPU at run time. Default CI builds and +runs none of it. + +Windows (native): + +```sh +cmake -S runtime -B runtime/build -DLEONIDA_TEST_LANTERNS=ON +cmake --build runtime/build --config RelWithDebInfo --target gta6rt lanterns +ctest --test-dir runtime/build -C RelWithDebInfo -R lanterns_stage1 --output-on-failure +``` + +Linux with Wine: cross-build with `runtime/cmake/clang-cl-xwin.cmake` as in +[testing.md](testing.md#the-windows-runtime-on-linux-under-wine-or-proton), adding `-DLEONIDA_TEST_LANTERNS=ON`, and +build the targets `gta6rt` and `lanterns`. Then run, in a virtual X server if there is no display: + +```sh +B=runtime/build/windows +WINEPREFIX="$HOME/.local/share/leonida-wine" xvfb-run -a python3 -I runtime/test/lanterns/run_lanterns.py --wine \ + --gta6rt $B/gta6rt.exe --guest $B/fixtures/lanterns/RelWithDebInfo/lanterns.exe \ + --shaders $B/generated/lanterns --out lanterns_out --stage 1 +``` + +The packed containers are in `/generated/lanterns/*.dxbc`. The translated shaders and their index +(`spirv/index.json`, keyed by FSSM SHA-256) are in the same folder. The runner points `LEONIDA_SHADERS` at that +`spirv/` folder. + +## Limits + +- Tested on one machine so far: an RTX 5080 on Linux, under Wine 11, with the clang-cl/xwin cross-build. No native + Windows run and no AMD or Intel GPU yet. +- No validation claim. Vulkan validation layers under Wine on that machine are still being looked into, so this page + does not say the run is validation clean. +- A few frames per stage, offscreen. No present, no frame loop, no swapchain. +- The FSSM programs are synthetic. They use the measured layout (`docs/design.md`, `tools/fssm_header.py`), but only + the fields the tools read, and the code is ours. A title's programs carry more than this. +- The reference is computed on the CPU, not by another D3D12 implementation. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 851330b998..28a149f2e0 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2121,6 +2121,8 @@ if(TARGET Vulkan::Headers) set_tests_properties(run_tiny_frame PROPERTIES SKIP_RETURN_CODE 77) endif() endif() + # Lanterns, a synthetic title-shaped guest for gta6rt --run (opt-in: -DLEONIDA_TEST_LANTERNS=ON, docs/lanterns.md). + include(test/lanterns/lanterns.cmake) # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan). if(TARGET bvh_builder_test) target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_com) diff --git a/runtime/test/lanterns/lanterns.cmake b/runtime/test/lanterns/lanterns.cmake new file mode 100644 index 0000000000..863cda2e01 --- /dev/null +++ b/runtime/test/lanterns/lanterns.cmake @@ -0,0 +1,67 @@ +# Lanterns, a synthetic title-shaped guest run by `gta6rt --run` (runtime/test/lanterns/lanterns.cpp, docs/lanterns.md). +# Included from runtime/CMakeLists.txt inside the Vulkan device block, after tiny_frame; opt-in, because it needs a +# Vulkan GPU at run time: +# +# -DLEONIDA_TEST_LANTERNS=ON, then build the `lanterns` and `gta6rt` targets. +# +# The shaders: fssm_pack.py (this folder) assembles shaders/*.asm with llvm-mc, packs each into a synthetic FSSM program +# inside a DXBC/XDAT/XBCH container (/generated/lanterns/.dxbc, what the guest hands to +# CreateGraphicsPipelineState) and runs tools/fssm_unpack.py, shader_disasm.py and rdna2spirv.py on that folder, which +# write spirv/index.json keyed by each program's FSSM SHA-256 (what LEONIDA_SHADERS points the runtime at). +# The guest links nothing from src/ or shims/: its device comes from the D3D12XboxCreateDevice it imports from +# d3d12_xs.dll, which only gta6rt's shim registry can answer. The import library is tiny_frame's failing stub +# (d3d12_xs_stub, test/fixtures/d3d12_xs_stub.cpp), built into a folder the loader does not search. +# +# Running it: run_lanterns.py (native Windows, or Wine with --wine) checks the exit code, the guest's PASS line and the +# device line, and writes PNGs of the frames. On a native Windows build it is also the ctest `lanterns_stage1`. +option(LEONIDA_TEST_LANTERNS + "Build lanterns.exe, a synthetic title-shaped guest for gta6rt --run (needs a Vulkan GPU to run)" OFF) +if(LEONIDA_TEST_LANTERNS AND NOT TARGET d3d12_xs_stub) + message(STATUS "LEONIDA_TEST_LANTERNS: lanterns.exe needs gta6rt and the d3d12_xs_stub target; not built") +elseif(LEONIDA_TEST_LANTERNS) + set(_lanterns_src ${CMAKE_CURRENT_SOURCE_DIR}/test/lanterns) + add_executable(lanterns ${_lanterns_src}/lanterns.cpp ${_lanterns_src}/lanterns_gpu.cpp) + target_link_libraries(lanterns PRIVATE d3d12_xs_stub Vulkan::Headers) + target_compile_definitions(lanterns PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) + target_compile_options(lanterns PRIVATE /W4 /permissive- /utf-8) + set_target_properties(lanterns PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/lanterns/$") + + if(NOT LEONIDA_LLVM_MC) + if(DEFINED ENV{LLVM_MC}) + set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") + else() + find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") + endif() + endif() + find_program(LEONIDA_SPIRV_AS spirv-as HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") + if(LEONIDA_LLVM_MC AND LEONIDA_SPIRV_AS AND TARGET Python3::Interpreter) + set(LEONIDA_LANTERNS_SHADERS ${CMAKE_CURRENT_BINARY_DIR}/generated/lanterns) + set(_lanterns_tools ${CMAKE_CURRENT_SOURCE_DIR}/../tools) + set(_lanterns_asm ${_lanterns_src}/shaders/vs_lanterns.asm ${_lanterns_src}/shaders/ps_lanterns_lit.asm + ${_lanterns_src}/shaders/ps_lanterns_floor.asm) + get_filename_component(_lanterns_spirv_tools ${LEONIDA_SPIRV_AS} DIRECTORY) + file(TO_NATIVE_PATH "${_lanterns_spirv_tools}" _lanterns_spirv_tools) + add_custom_command( + OUTPUT ${LEONIDA_LANTERNS_SHADERS}/spirv/index.json + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_LANTERNS_SHADERS} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${_lanterns_spirv_tools}" + $ -I ${_lanterns_src}/fssm_pack.py + ${LEONIDA_LANTERNS_SHADERS} ${_lanterns_asm} --translate + DEPENDS ${_lanterns_asm} ${_lanterns_src}/fssm_pack.py ${_lanterns_tools}/fssm_unpack.py + ${_lanterns_tools}/shader_disasm.py ${_lanterns_tools}/rdna2spirv.py + COMMENT "Packing and translating the Lanterns shaders" + VERBATIM) + add_custom_target(lanterns_shaders DEPENDS ${LEONIDA_LANTERNS_SHADERS}/spirv/index.json) + add_dependencies(lanterns lanterns_shaders) + if(CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING) + add_test(NAME lanterns_stage1 + COMMAND $ -I ${_lanterns_src}/run_lanterns.py + --gta6rt $ --guest $ + --shaders ${LEONIDA_LANTERNS_SHADERS} --out ${CMAKE_CURRENT_BINARY_DIR}/lanterns_out --stage 1) + set_tests_properties(lanterns_stage1 PROPERTIES TIMEOUT 300) + endif() + else() + message(STATUS "llvm-mc (set LLVM_MC), spirv-as or Python 3 not found: lanterns.exe builds without its shaders") + endif() +endif() diff --git a/runtime/test/lanterns/lanterns.cpp b/runtime/test/lanterns/lanterns.cpp new file mode 100644 index 0000000000..49bc16caec --- /dev/null +++ b/runtime/test/lanterns/lanterns.cpp @@ -0,0 +1,138 @@ +// Lanterns: an original stand-in title that runs under gta6rt --run and drives the whole chain a real title would: +// an x64 PE the loader maps, imports the loader's shims answer, the Xbox D3D12 device on Vulkan +// (D3D12XboxCreateDevice from d3d12_xs.dll, LEONIDA_D3D12=vulkan), pipelines from shader containers holding RDNA2 +// programs (DXBC { DXIL { XDAT { XBCH + zlib(FSSM) } } }, packed by fssm_pack.py beside this file, translated offline by +// fssm_unpack.py, shader_disasm.py and rdna2spirv.py; the layer finds each by the SHA-256 of its FSSM program), draws, +// and a readback checked against a CPU reference. Content: abstract solids on a checkered floor, colours from short +// binary fractions; no game data. How to build and run it: lanterns.cmake. +// +// lanterns.exe --stage 1 --shaders --out +// +// Stage 1: five DrawIndexedInstanced (hexagonal prisms, cubes, octahedra, pyramids, the floor) into a 384x256 +// R32G32B32A32_FLOAT target with a D32_FLOAT depth buffer. Vertex, index and instance buffers live in DEFAULT heaps, +// filled from an upload buffer by copies; the vertex shader reads vertices and instances through V#s in two descriptor +// tables, the model matrix and tint from root constants, the camera from a root CBV. The frame is drawn twice: with +// the depth test (the image) and without it (the negative control, which must change exactly the pixels the reference +// says it changes). +// +// On success the guest prints one line starting "Lanterns stage N: PASS" and exits 0; run_lanterns.py checks that +// line, the exit code and the device line. +#include "lanterns_gpu.h" +#include "lanterns_reference.h" +#include "lanterns_scene.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using lanterns::Color; +using lanterns::kHeight; +using lanterns::kWidth; + +bool write_file(const std::filesystem::path& path, const void* data, std::size_t size) { + std::ofstream out(path, std::ios::binary); + out.write(static_cast(data), std::streamsize(size)); + return bool(out); +} + +// Writes /.gpu.rgba32f, .ref.rgba32f and .uncertain.u8 (one byte per pixel, 1 = uncertain), which +// run_lanterns.py turns into PNGs. +bool dump(const std::filesystem::path& out, const char* name, const std::vector& gpu, + const lanterns::Reference& ref) { + std::vector uncertain(gpu.size()); + for (std::size_t i = 0; i < gpu.size(); ++i) uncertain[i] = ref.candidates[i].empty() ? 0 : 1; + const std::string base = (out / name).string(); + const bool ok = write_file(base + ".gpu.rgba32f", gpu.data(), gpu.size() * sizeof(Color)) && + write_file(base + ".ref.rgba32f", ref.color.data(), ref.color.size() * sizeof(Color)) && + write_file(base + ".uncertain.u8", uncertain.data(), uncertain.size()); + if (!ok) std::fprintf(stderr, "lanterns: cannot write %s.* +", base.c_str()); + return ok; +} + +void report(const char* what, const lanterns::Comparison& c) { + std::printf("lanterns: %s: %u of %u certain pixels exact, %u of %u uncertain pixels one of their candidates\n", + what, c.certain_exact, c.certain, c.uncertain_plausible, c.uncertain); + if (!c.pass()) + std::printf("lanterns: %s: first bad pixel (%u, %u): gpu (%g, %g, %g, %g), reference (%g, %g, %g, %g)\n", what, + c.first_bad_x, c.first_bad_y, c.first_bad_gpu[0], c.first_bad_gpu[1], c.first_bad_gpu[2], + c.first_bad_gpu[3], c.first_bad_ref[0], c.first_bad_ref[1], c.first_bad_ref[2], c.first_bad_ref[3]); +} + +// Pixels certain in both references whose expected colours differ, and how many of those differ on the GPU too. +struct Change { + unsigned expected = 0, changed = 0; +}; +Change changes(const std::vector& a, const lanterns::Reference& ra, const std::vector& b, + const lanterns::Reference& rb) { + Change c; + for (std::size_t i = 0; i < a.size(); ++i) { + if (!ra.candidates[i].empty() || !rb.candidates[i].empty()) continue; + if (lanterns::detail::same(ra.color[i], rb.color[i])) continue; + ++c.expected; + c.changed += !lanterns::detail::same(a[i], b[i]); + } + return c; +} + +int stage1(const std::filesystem::path& shader_dir, const std::filesystem::path& out_dir) { + const lanterns::Scene scene = lanterns::stage1(); + lanterns::Shaders shaders; + if (!lanterns::load_shaders(shader_dir, shaders)) return 1; + std::vector with_depth, without_depth; + { + lanterns::Gpu gpu; + if (!gpu.create(scene, shaders)) return 1; + if (!gpu.submit_frame(scene, true) || !gpu.finish_frame(with_depth)) return 1; + if (!gpu.submit_frame(scene, false) || !gpu.finish_frame(without_depth)) return 1; + if (!gpu.idle()) return 1; + } + const lanterns::Reference ref_on = lanterns::reference_frame(scene, true); + const lanterns::Reference ref_off = lanterns::reference_frame(scene, false); + const auto on = lanterns::compare(with_depth, ref_on), off = lanterns::compare(without_depth, ref_off); + report("depth test on", on); + report("depth test off (negative control)", off); + const Change control = changes(with_depth, ref_on, without_depth, ref_off); + std::printf("lanterns: the depth test changes %u certain pixels (the reference expects %u); %u faces edge-on\n", + control.changed, control.expected, ref_on.degenerate_faces); + if (!dump(out_dir, "stage1-depth", with_depth, ref_on) || !dump(out_dir, "stage1-nodepth", without_depth, ref_off)) + return 1; + if (!on.pass() || !off.pass() || control.expected < 1000 || control.changed != control.expected) { + std::fprintf(stderr, "lanterns: stage 1 FAILED\n"); + return 1; + } + // Printed only here, after every check: run_lanterns.py wants this line once and exit code 0. + std::printf("Lanterns stage 1: PASS, %u of %u pixels exact, %u edge pixels plausible, depth-off control changed " + "%u pixels\n", on.certain_exact, kWidth * kHeight, on.uncertain_plausible, control.changed); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); // the marker reaches the launcher even if the process dies after it + int stage = 0; + std::filesystem::path shader_dir, out_dir; + for (int i = 1; i + 1 < argc; i += 2) { + const std::string key = argv[i]; + if (key == "--stage") stage = std::atoi(argv[i + 1]); + else if (key == "--shaders") shader_dir = argv[i + 1]; + else if (key == "--out") out_dir = argv[i + 1]; + } + if (shader_dir.empty() || out_dir.empty()) stage = 0; + std::error_code ec; + if (stage) std::filesystem::create_directories(out_dir, ec); + switch (stage) { + case 1: return stage1(shader_dir, out_dir); + default: + std::fprintf(stderr, "usage: lanterns --stage 1 --shaders --out \n"); + return 2; + } +} diff --git a/runtime/test/lanterns/lanterns_d3d12.h b/runtime/test/lanterns/lanterns_d3d12.h new file mode 100644 index 0000000000..2748a542a9 --- /dev/null +++ b/runtime/test/lanterns/lanterns_d3d12.h @@ -0,0 +1,50 @@ +// Lanterns: small D3D12 helpers the GPU files share. The heap-handle calls through slots 9/10 and the V# encoding are +// ported from test/d3d12_translated_draw_test.cpp (M1.5), as lanterns_gpu.cpp first had them. +#pragma once + +#include "../d3d12_test_shaders.h" +#include "../../src/gfx10_descriptors.h" + +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "lanterns: %s:%d: %s\n", __FILE__, __LINE__, #condition); return false; } \ +} while (0) + +namespace lanterns { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +// The heap's first CPU handle (slot 9) and, for a shader-visible heap, its first GPU handle (slot 10). +inline std::uint64_t heap_cpu(ID3D12DescriptorHeap* heap) { + return reinterpret_cast(d3d12test::slot(heap, 9))(heap); +} +inline std::uint64_t heap_gpu(ID3D12DescriptorHeap* heap) { + return reinterpret_cast(d3d12test::slot(heap, 10))(heap); +} + +inline std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +inline std::uint64_t align(std::uint64_t v, std::uint64_t a) { return (v + a - 1) / a * a; } + +// A V# over records of 'stride' bytes, format 32_32_32_32_FLOAT, structured out-of-range checks (an idxen access). +inline std::array make_vsharp(std::uint64_t base, std::uint32_t stride, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = stride; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_gpu.cpp b/runtime/test/lanterns/lanterns_gpu.cpp new file mode 100644 index 0000000000..095a4a2274 --- /dev/null +++ b/runtime/test/lanterns/lanterns_gpu.cpp @@ -0,0 +1,321 @@ +// Lanterns: the GPU side (lanterns_gpu.h). Borrowed pieces, all from this repository under its licence: the +// D3D12XboxCreateDevice import (tiny_frame's, #3488), and from test/d3d12_translated_draw_test.cpp (M1.5) the heap-handle calls +// through slots 9/10, the V# encoding and the upload-to-DEFAULT copies. +#include "lanterns_gpu.h" + +#include "lanterns_d3d12.h" + +#include +#include +#include + +// Resolved at link time against test/fixtures/d3d12_xs_stub.cpp (which fails), at run time by gta6rt's shim registry. +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, + const IID* riid, void** out); + +using namespace d3d12test; + +namespace lanterns { +namespace { + +Geometry flatten(const Scene& scene) { + Geometry g; + for (const Mesh& mesh : scene.meshes) { + g.first_vertex.push_back(std::uint32_t(g.vertices.size())); + g.vertex_count.push_back(std::uint32_t(mesh.vertices.size())); + g.first_index.push_back(std::uint32_t(g.indices.size())); + g.vertices.insert(g.vertices.end(), mesh.vertices.begin(), mesh.vertices.end()); + for (const Face& face : mesh.faces) + for (unsigned k = 1; k + 1 < face.count; ++k) // indices are relative to the mesh: its V# starts there + g.indices.insert(g.indices.end(), {face.v[0], face.v[k], face.v[k + 1]}); + g.index_count.push_back(std::uint32_t(g.indices.size()) - g.first_index.back()); + } + for (const Draw& draw : scene.draws) { + g.first_instance.push_back(std::uint32_t(g.instances.size())); + g.instances.insert(g.instances.end(), draw.instances.begin(), draw.instances.end()); + } + return g; +} + +constexpr std::uint64_t kReadbackBytes = std::uint64_t(kPitch) * kHeight; // the image + +} // namespace + +bool load_shaders(const std::filesystem::path& dir, Shaders& out) { + out.vs = read_file(dir / "vs_lanterns.dxbc"); + out.ps_lit = read_file(dir / "ps_lanterns_lit.dxbc"); + out.ps_floor = read_file(dir / "ps_lanterns_floor.dxbc"); + CHECK(out.vs.size() > 64 && out.ps_lit.size() > 64 && out.ps_floor.size() > 64); + // The negative control of the lookup: the VS's FSSM program (fssm_unpack.py's copy) with its last byte, in the + // tail's name, changed. The layer must refuse a container whose program the index does not know. + auto program = read_file(dir / "fssm" / "vs_lanterns.fssm"); + CHECK(program.size() > 0x200 && std::memcmp(program.data(), "FSSM", 4) == 0); + program.back() ^= 0x20; + out.unknown_vs = shader_container(program); + return true; +} + +bool Gpu::create(const Scene& scene, const Shaders& shaders) { + const std::uint32_t device_params[24] = {}; + const IID device_iid = __uuidof(ID3D12Device); + const HRESULT created = D3D12XboxCreateDevice(nullptr, device_params, &device_iid, reinterpret_cast(&device_.p)); + if (FAILED(created) || !device_.p) { + std::fprintf(stderr, "lanterns: D3D12XboxCreateDevice failed (hr=0x%08lx)\n", static_cast(created)); + return false; + } + geometry_ = flatten(scene); + CHECK(create_pipelines(shaders)); + CHECK(create_resources(scene)); + CHECK(fill_descriptors(scene)); + return initialize(scene); +} + +// The root tables and constants of draw d (the mesh V#, the draw's instance V#, its model matrix and tint). +void Gpu::bind_draw(const Scene& scene, std::size_t d) { + const Draw& draw = scene.draws[d]; + list_->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu_ + draw.mesh * srv_step_}); + list_->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{srv_gpu_ + (scene.meshes.size() + d) * srv_step_}); + float constants[16]; + std::memcpy(constants, draw.model.data(), sizeof(draw.model)); + std::memcpy(constants + 12, draw.tint.data(), sizeof(draw.tint)); + list_->SetGraphicsRoot32BitConstants(2, 16, constants, 0); +} + +bool Gpu::create_pipelines(const Shaders& shaders) { + // [0] table: the mesh V# (t0) [1] table: the instance V# (t1) [2] 16 constants (b0) [3] root CBV (b1) + // -> s[0:1], s[2:3], s4..s19, s[20:21]: what vs_lanterns.asm reads. + D3D12_DESCRIPTOR_RANGE ranges[2] = {{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}, + {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 1, 0, 0}}; + D3D12_ROOT_PARAMETER params[4] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &ranges[0]}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &ranges[1]}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants = {0, 0, 16}; + params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + params[3].Descriptor = {1, 0}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {4, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + CHECK(!root_blob.empty()); + CHECK(SUCCEEDED(device_->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root_.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root_.p; + desc.VS = {shaders.vs.data(), shaders.vs.size()}; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.SampleMask = 0xffffffff; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.SampleDesc.Count = 1; + for (int floor = 0; floor < 2; ++floor) + for (int depth = 0; depth < 2; ++depth) { + const auto& ps = floor ? shaders.ps_floor : shaders.ps_lit; + desc.PS = {ps.data(), ps.size()}; + desc.DepthStencilState.DepthEnable = depth ? TRUE : FALSE; + CHECK(SUCCEEDED(device_->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso_[floor][depth].p)))); + } + std::printf("lanterns: 4 graphics pipelines from 3 FSSM containers; next, a VS the index does not know, which the " + "layer must refuse (its 'no translated vs' line is expected)\n"); + Ref unknown; + desc.VS = {shaders.unknown_vs.data(), shaders.unknown_vs.size()}; + CHECK(device_->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); + return true; +} + +bool Gpu::create_resources(const Scene& scene) { + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD, {}, {}, 0, 0}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK, {}, {}, 0, 0}; + const std::uint64_t vb_bytes = geometry_.vertices.size() * sizeof(Vertex); + const std::uint64_t ib_bytes = align(geometry_.indices.size() * sizeof(std::uint16_t), 4); + const std::uint64_t inst_bytes = std::max(geometry_.instances.size() * sizeof(Instance), 256); + // Upload layout: vertices, indices, instances, the camera's 64 bytes (the root CBV reads them in place: root views + // are 64-bit console VAs, docs/d3d12_vulkan.md 3.3). + upload_vb_ = 0; + upload_ib_ = align(upload_vb_ + vb_bytes, 256); + upload_inst_ = align(upload_ib_ + ib_bytes, 256); + upload_cbv_ = align(upload_inst_ + inst_bytes, 256); + const std::uint64_t upload_bytes = upload_cbv_ + 256; + const auto make_buffer = [&](const D3D12_HEAP_PROPERTIES& heap, std::uint64_t bytes, D3D12_RESOURCE_STATES state, + Ref& out, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + const auto desc = buffer_desc(bytes, flags); + return SUCCEEDED(device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(&out.p))); + }; + CHECK(make_buffer(default_heap, vb_bytes, D3D12_RESOURCE_STATE_COPY_DEST, vertex_buffer_)); + CHECK(make_buffer(default_heap, ib_bytes, D3D12_RESOURCE_STATE_COPY_DEST, index_buffer_)); + CHECK(make_buffer(default_heap, inst_bytes, D3D12_RESOURCE_STATE_COPY_DEST, instance_buffer_)); + CHECK(make_buffer(upload_heap, upload_bytes, D3D12_RESOURCE_STATE_GENERIC_READ, upload_)); + CHECK(make_buffer(readback_heap, kReadbackBytes, D3D12_RESOURCE_STATE_COPY_DEST, readback_)); + + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = kWidth; + tex.Height = kHeight; + tex.DepthOrArraySize = 1; + tex.MipLevels = 1; + tex.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + tex.SampleDesc.Count = 1; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + CHECK(SUCCEEDED(device_->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target_.p)))); + tex.Format = DXGI_FORMAT_D32_FLOAT; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_CLEAR_VALUE depth_clear{}; + depth_clear.Format = DXGI_FORMAT_D32_FLOAT; + depth_clear.DepthStencil = {1.0f, 0}; + CHECK(SUCCEEDED(device_->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &tex, + D3D12_RESOURCE_STATE_DEPTH_WRITE, &depth_clear, + IID_PPV_ARGS(&depth_.p)))); + + const D3D12_DESCRIPTOR_HEAP_DESC srv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 32, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&srv_desc, IID_PPV_ARGS(&srv_heap_.p)))); + CHECK(scene.meshes.size() + scene.draws.size() <= 32); + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap_.p)))); + const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + CHECK(SUCCEEDED(device_->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv_heap_.p)))); + rtv_ = {SIZE_T(heap_cpu(rtv_heap_.p))}; + dsv_ = {SIZE_T(heap_cpu(dsv_heap_.p))}; + device_->CreateRenderTargetView(target_.p, nullptr, rtv_); + device_->CreateDepthStencilView(depth_.p, nullptr, dsv_); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(device_->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator_.p)))); + CHECK(SUCCEEDED(device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator_.p, nullptr, + IID_PPV_ARGS(&list_.p)))); + CHECK(list_->Close() == S_OK); + CHECK(SUCCEEDED(device_->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence_.p)))); + return true; +} + +// The descriptor tables: slot m holds mesh m's V#, slot (meshes + d) draw d's instance V#. Raw V# bytes, written through the CPU handle as the title writes them. +bool Gpu::fill_descriptors(const Scene& scene) { + srv_cpu_ = heap_cpu(srv_heap_.p); + srv_gpu_ = heap_gpu(srv_heap_.p); + srv_step_ = device_->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + CHECK(srv_cpu_ && srv_gpu_ >= 0x10000 && srv_step_ >= 16); + const auto put = [&](std::size_t index, const std::array& v) { + std::memcpy(reinterpret_cast(srv_cpu_ + index * srv_step_), v.data(), 16); + }; + const std::uint64_t vb = vertex_buffer_->GetGPUVirtualAddress(), inst = instance_buffer_->GetGPUVirtualAddress(); + const std::size_t meshes = scene.meshes.size(), draws = scene.draws.size(); + for (std::size_t m = 0; m < meshes; ++m) + put(m, make_vsharp(vb + geometry_.first_vertex[m] * sizeof(Vertex), sizeof(Vertex), geometry_.vertex_count[m])); + for (std::size_t d = 0; d < draws; ++d) { + const Draw& draw = scene.draws[d]; + const auto count = std::uint32_t(draw.instances.size()); + put(meshes + d, make_vsharp(inst + geometry_.first_instance[d] * sizeof(Instance), sizeof(Instance), count)); + } + return true; +} + +// One direct-queue submission, waited for: the uploads into the DEFAULT buffers, and the target into COPY_SOURCE. +bool Gpu::initialize(const Scene& scene) { + std::uint8_t* up = nullptr; + CHECK(SUCCEEDED(upload_->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up + upload_vb_, geometry_.vertices.data(), geometry_.vertices.size() * sizeof(Vertex)); + std::memcpy(up + upload_ib_, geometry_.indices.data(), geometry_.indices.size() * sizeof(std::uint16_t)); + if (!geometry_.instances.empty()) + std::memcpy(up + upload_inst_, geometry_.instances.data(), geometry_.instances.size() * sizeof(Instance)); + std::memcpy(up + upload_cbv_, scene.view_projection.data(), sizeof(scene.view_projection)); + + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + list_->CopyBufferRegion(vertex_buffer_.p, 0, upload_.p, upload_vb_, geometry_.vertices.size() * sizeof(Vertex)); + list_->CopyBufferRegion(index_buffer_.p, 0, upload_.p, upload_ib_, + align(geometry_.indices.size() * sizeof(std::uint16_t), 4)); + if (!geometry_.instances.empty()) + list_->CopyBufferRegion(instance_buffer_.p, 0, upload_.p, upload_inst_, + geometry_.instances.size() * sizeof(Instance)); + const std::vector barriers = { + transition(vertex_buffer_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(index_buffer_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER), + transition(instance_buffer_.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target_.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + list_->ResourceBarrier(UINT(barriers.size()), barriers.data()); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + CHECK(SUCCEEDED(fence_->SetEventOnCompletion(fence_value_, nullptr))); + return true; +} + +bool Gpu::submit_frame(const Scene& scene, bool depth_test) { + CHECK(SUCCEEDED(allocator_->Reset())); + CHECK(SUCCEEDED(list_->Reset(allocator_.p, nullptr))); + const std::vector before = { + transition(target_.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list_->ResourceBarrier(UINT(before.size()), before.data()); + list_->ClearRenderTargetView(rtv_, kClear.data(), 0, nullptr); + list_->ClearDepthStencilView(dsv_, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + list_->SetGraphicsRootSignature(root_.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap_.p}; + list_->SetDescriptorHeaps(1, heaps); + list_->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_INDEX_BUFFER_VIEW ibv{index_buffer_->GetGPUVirtualAddress(), + UINT(align(geometry_.indices.size() * sizeof(std::uint16_t), 4)), + DXGI_FORMAT_R16_UINT}; + list_->IASetIndexBuffer(&ibv); + const D3D12_VIEWPORT viewport{0, 0, float(kWidth), float(kHeight), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(kWidth), LONG(kHeight)}; + list_->RSSetViewports(1, &viewport); + list_->RSSetScissorRects(1, &scissor); + list_->OMSetRenderTargets(1, &rtv_, FALSE, &dsv_); + list_->SetGraphicsRootConstantBufferView(3, upload_->GetGPUVirtualAddress() + upload_cbv_); + for (std::size_t d = 0; d < scene.draws.size(); ++d) { + const Draw& draw = scene.draws[d]; + list_->SetPipelineState(pso_[draw.floor ? 1 : 0][depth_test ? 1 : 0].p); + bind_draw(scene, d); + list_->DrawIndexedInstanced(geometry_.index_count[draw.mesh], UINT(draw.instances.size()), + geometry_.first_index[draw.mesh], 0, 0); + } + const std::vector to_copy = { + transition(target_.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)}; + list_->ResourceBarrier(UINT(to_copy.size()), to_copy.data()); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback_.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, kWidth, kHeight, 1, kPitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target_.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list_->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + CHECK(list_->Close() == S_OK); + ID3D12CommandList* lists[] = {list_.p}; + queue_->ExecuteCommandLists(1, lists); + CHECK(SUCCEEDED(queue_->Signal(fence_.p, ++fence_value_))); + return true; +} + +bool Gpu::finish_frame(std::vector& pixels) { + CHECK(SUCCEEDED(fence_->SetEventOnCompletion(fence_value_, nullptr))); + void* mapped = nullptr; + CHECK(SUCCEEDED(readback_->Map(0, nullptr, &mapped))); + const auto* bytes = static_cast(mapped); + pixels.resize(std::size_t(kWidth) * kHeight); + for (unsigned y = 0; y < kHeight; ++y) + std::memcpy(pixels.data() + std::size_t(y) * kWidth, bytes + y * kPitch, kWidth * sizeof(Color)); + readback_->Unmap(0, nullptr); + return true; +} + +bool Gpu::idle() { + CHECK(SUCCEEDED(fence_->SetEventOnCompletion(fence_value_, nullptr))); + return true; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_gpu.h b/runtime/test/lanterns/lanterns_gpu.h new file mode 100644 index 0000000000..7a7bc69ce3 --- /dev/null +++ b/runtime/test/lanterns/lanterns_gpu.h @@ -0,0 +1,72 @@ +// Lanterns: the GPU side, through the D3D12 API only. The device comes from the D3D12XboxCreateDevice the guest +// imports from d3d12_xs.dll (test/fixtures/tiny_frame.cpp does the same); pipelines come from the shader +// containers fssm_pack.py wrote. See lanterns.cpp for what each stage draws and checks. +#pragma once + +#include "../d3d12_test_shaders.h" +#include "lanterns_scene.h" + +#include +#include +#include +#include + +namespace lanterns { + +using Color = std::array; +using d3d12test::Ref; + +// The containers the guest hands to the pipelines, read from the folder fssm_pack.py wrote. +struct Shaders { + std::vector vs, ps_lit, ps_floor, unknown_vs; +}; +bool load_shaders(const std::filesystem::path& dir, Shaders& out); + +// The scene's meshes as one vertex array and one 16-bit index array (each face fanned), with where each mesh starts, +// and every draw's instances. +struct Geometry { + std::vector vertices; + std::vector indices; + std::vector first_vertex, vertex_count, first_index, index_count; + std::vector instances; + std::vector first_instance; +}; + +class Gpu { +public: + // Device, pipelines, buffers, and an initial direct-queue submission that copies the uploads into the DEFAULT + // buffers. + bool create(const Scene& scene, const Shaders& shaders); + // Records and submits one frame on the direct queue. + bool submit_frame(const Scene& scene, bool depth_test); + // Waits for the last frame and reads back its pixels. + bool finish_frame(std::vector& pixels); + // Waits until the queue is idle (before the objects are released). + bool idle(); + +private: + bool create_pipelines(const Shaders& shaders); + void bind_draw(const Scene& scene, std::size_t d); + bool create_resources(const Scene& scene); + bool initialize(const Scene& scene); + bool fill_descriptors(const Scene& scene); + + // Declared first, released last: everything below is a child of the device. + Ref device_; + Ref root_; + Ref pso_[2][2]; // [floor][depth test] + Ref vertex_buffer_, index_buffer_, instance_buffer_, upload_, readback_, target_, depth_; + Ref srv_heap_, rtv_heap_, dsv_heap_; + Ref queue_; + Ref allocator_; + Ref list_; + Ref fence_; + Geometry geometry_; + std::uint64_t upload_vb_ = 0, upload_ib_ = 0, upload_inst_ = 0, upload_cbv_ = 0; + std::uint64_t srv_cpu_ = 0, srv_gpu_ = 0; + UINT srv_step_ = 0; + D3D12_CPU_DESCRIPTOR_HANDLE rtv_{}, dsv_{}; + UINT64 fence_value_ = 0; +}; + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_reference.h b/runtime/test/lanterns/lanterns_reference.h new file mode 100644 index 0000000000..a72f69a0ff --- /dev/null +++ b/runtime/test/lanterns/lanterns_reference.h @@ -0,0 +1,239 @@ +// Lanterns: the CPU reference for a stage-1 frame. It rasterizes the scene of lanterns_scene.h in double precision, +// face by face (each face is a convex polygon; the GPU draws it as a triangle fan, which covers the same pixels), and +// says for every pixel either "this exact colour" or "uncertain, one of these colours". A pixel is uncertain when a +// tiny change in where the GPU puts a vertex could change it: its centre lies within kMargin pixels of a face edge, +// two faces with different colours are within their depth tolerance of each other, or (on the floor) the centre is +// within kMargin pixels of a checker border. kMargin is 1/32 pixel, eight times the vertex snapping of an 8-bit +// sub-pixel rasterizer. Every other pixel must match bit for bit: its colour is a product of short binary fractions +// (lanterns_scene.h), which float arithmetic computes exactly, and nothing near it is in doubt. The uncertain pixels +// are counted apart, as d3d12_translated_draw_test counts its diagonal, and each must still be one of its candidates. +#pragma once + +#include "lanterns_scene.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace lanterns { + +using Color = std::array; +constexpr double kMargin = 1.0 / 32.0; + +struct Reference { + std::vector color; // the expected colour (the most likely one where uncertain) + std::vector> candidates; // empty: certain; else every colour the pixel may have + unsigned degenerate_faces = 0; // faces seen edge-on, which cover nothing for certain +}; + +namespace detail { + +struct ScreenVertex { + double x, y, z, q; // screen position (pixels, y down), depth z/w, q = 1/w + double wx, wz; // world x and z (the floor's checker reads them) +}; + +struct Fragment { + unsigned seq; // submission order of the face + double depth, tol; + bool certain_cover; // the centre is more than kMargin inside every edge + unsigned count; // 1 or 2 colours (2: a floor pixel on a checker border) + Color colors[2]; +}; + +inline bool same(const Color& a, const Color& b) { return std::memcmp(a.data(), b.data(), sizeof(Color)) == 0; } + +inline void add_unique(std::vector& out, const Color& c) { + for (const Color& o : out) + if (same(o, c)) return; + out.push_back(c); +} + +// The vertex shader's arithmetic, in double: local = M * (p, 1), world = local * scale + offset, clip = VP * world. +inline ScreenVertex transform(const Scene& scene, const Draw& draw, const Instance& inst, const Vertex& v) { + const auto& m = draw.model; + double local[3], world[3], clip[4]; + for (int r = 0; r < 3; ++r) + local[r] = double(m[r * 4]) * v.x + double(m[r * 4 + 1]) * v.y + double(m[r * 4 + 2]) * v.z + m[r * 4 + 3]; + for (int r = 0; r < 3; ++r) world[r] = local[r] * inst.scale + inst.offset[r]; + const auto& vp = scene.view_projection; + for (int r = 0; r < 4; ++r) + clip[r] = double(vp[r * 4]) * world[0] + double(vp[r * 4 + 1]) * world[1] + double(vp[r * 4 + 2]) * world[2] + + vp[r * 4 + 3]; + const double q = 1.0 / clip[3]; + return {(clip[0] * q + 1.0) * 0.5 * kWidth, (1.0 - clip[1] * q) * 0.5 * kHeight, clip[2] * q, q, world[0], + world[2]}; +} + +// The colour vs_lanterns.asm exports for a face, as the float products it forms: (tint * colour) * shade. +inline Color face_color(const Draw& draw, const Instance& inst, float shade) { + Color c; + for (int k = 0; k < 3; ++k) c[k] = (draw.tint[k] * inst.color[k]) * shade; + c[3] = draw.tint[3] * inst.color[3]; + return c; +} + +inline Color times(const std::array& a, const Color& b) { + return {a[0] * b[0], a[1] * b[1], a[2] * b[2], a[3] * b[3]}; +} + +inline double cross(double ax, double ay, double bx, double by) { return ax * by - ay * bx; } + +} // namespace detail + +// The frame the stage-1 draws make, with the depth test on (LESS, cleared to 1) or off (submission order wins). +inline Reference reference_frame(const Scene& scene, bool depth_test) { + using namespace detail; + std::vector> frags(std::size_t(kWidth) * kHeight); + Reference ref; + unsigned seq = 0; + for (const Draw& draw : scene.draws) { + const Mesh& mesh = scene.meshes[draw.mesh]; + for (const Instance& inst : draw.instances) { + for (const Face& face : mesh.faces) { + const unsigned self = seq++; + ScreenVertex s[6]; + for (unsigned k = 0; k < face.count; ++k) s[k] = transform(scene, draw, inst, mesh.vertices[face.v[k]]); + double area = 0; + for (unsigned k = 0; k < face.count; ++k) { + const auto& a = s[k]; + const auto& b = s[(k + 1) % face.count]; + area += cross(a.x, a.y, b.x, b.y); + } + const double a012 = cross(s[1].x - s[0].x, s[1].y - s[0].y, s[2].x - s[0].x, s[2].y - s[0].y); + if (std::fabs(area) < 1e-6 || std::fabs(a012) < 1e-9) { + ++ref.degenerate_faces; + continue; + } + const double orient = area > 0 ? 1.0 : -1.0; + // Barycentrics of the plane through s0, s1, s2 (the whole face lies in it). + const auto bary = [&](double px, double py, double l[3]) { + l[1] = cross(px - s[0].x, py - s[0].y, s[2].x - s[0].x, s[2].y - s[0].y) / a012; + l[2] = cross(s[1].x - s[0].x, s[1].y - s[0].y, px - s[0].x, py - s[0].y) / a012; + l[0] = 1.0 - l[1] - l[2]; + }; + const auto depth_at = [&](double px, double py) { + double l[3]; + bary(px, py, l); + return l[0] * s[0].z + l[1] * s[1].z + l[2] * s[2].z; + }; + // Perspective-correct world x and z, as the PS's v_interp_p1/p2 reads them. + const auto world_at = [&](double px, double py, double& wx, double& wz) { + double l[3]; + bary(px, py, l); + const double qs = l[0] * s[0].q + l[1] * s[1].q + l[2] * s[2].q; + wx = (l[0] * s[0].wx * s[0].q + l[1] * s[1].wx * s[1].q + l[2] * s[2].wx * s[2].q) / qs; + wz = (l[0] * s[0].wz * s[0].q + l[1] * s[1].wz * s[1].q + l[2] * s[2].wz * s[2].q) / qs; + }; + const double dzdx = depth_at(1, 0) - depth_at(0, 0), dzdy = depth_at(0, 1) - depth_at(0, 0); + const double tol = (std::fabs(dzdx) + std::fabs(dzdy)) * kMargin + 1e-6; + const Color lit = face_color(draw, inst, mesh.vertices[face.v[0]].shade); + double minx = 1e30, maxx = -1e30, miny = 1e30, maxy = -1e30; + for (unsigned k = 0; k < face.count; ++k) { + minx = std::min(minx, s[k].x), maxx = std::max(maxx, s[k].x); + miny = std::min(miny, s[k].y), maxy = std::max(maxy, s[k].y); + } + const int x0 = std::max(0, int(std::floor(minx)) - 1), x1 = std::min(int(kWidth) - 1, int(maxx) + 1); + const int y0 = std::max(0, int(std::floor(miny)) - 1), y1 = std::min(int(kHeight) - 1, int(maxy) + 1); + for (int y = y0; y <= y1; ++y) + for (int x = x0; x <= x1; ++x) { + const double px = x + 0.5, py = y + 0.5; + double inside = 1e30; + for (unsigned k = 0; k < face.count; ++k) { + const auto& a = s[k]; + const auto& b = s[(k + 1) % face.count]; + const double ex = b.x - a.x, ey = b.y - a.y; + const double d = orient * cross(ex, ey, px - a.x, py - a.y) / std::sqrt(ex * ex + ey * ey); + inside = std::min(inside, d); + } + if (inside < -kMargin) continue; + Fragment f{self, depth_at(px, py), tol, inside > kMargin, 1, {lit, lit}}; + if (draw.floor) { + double wx, wz, wx1, wz1, wx2, wz2; + world_at(px, py, wx, wz); + world_at(px + 1, py, wx1, wz1); + world_at(px, py + 1, wx2, wz2); + const double gx = std::fabs(wx1 - wx) + std::fabs(wx2 - wx); + const double gz = std::fabs(wz1 - wz) + std::fabs(wz2 - wz); + const auto near_border = [](double v, double g) { + return std::fabs(v - std::round(v)) <= g * kMargin + 1e-5; + }; + const long parity = (long(std::floor(wx)) + long(std::floor(wz))) & 1; + f.colors[0] = times(parity ? kFloorB : kFloorA, lit); + f.colors[1] = times(parity ? kFloorA : kFloorB, lit); + f.count = near_border(wx, gx) || near_border(wz, gz) ? 2 : 1; + } + frags[std::size_t(y) * kWidth + x].push_back(f); + } + } + } + } + + ref.color.assign(frags.size(), Color{kClear[0], kClear[1], kClear[2], kClear[3]}); + ref.candidates.resize(frags.size()); + for (std::size_t i = 0; i < frags.size(); ++i) { + const auto& list = frags[i]; + const Fragment* winner = nullptr; // among the certain fragments + for (const Fragment& f : list) { + if (!f.certain_cover) continue; + if (!winner || (depth_test ? f.depth < winner->depth : f.seq > winner->seq)) winner = &f; + } + std::vector cand; + if (winner) { + ref.color[i] = winner->colors[0]; + for (unsigned k = 0; k < winner->count; ++k) add_unique(cand, winner->colors[k]); + } else { + add_unique(cand, ref.color[i]); + } + for (const Fragment& f : list) { + if (&f == winner) continue; + // Could f be what the GPU shows instead? With the depth test, if it may be nearer; without, if it comes + // later. An uncertain fragment counts wherever it might be covered. + const bool may_win = !winner ? true + : depth_test ? f.depth - f.tol <= winner->depth + winner->tol + : f.seq > winner->seq; + if (!may_win) continue; + for (unsigned k = 0; k < f.count; ++k) add_unique(cand, f.colors[k]); + } + if (cand.size() > 1) ref.candidates[i] = std::move(cand); + } + return ref; +} + +struct Comparison { + unsigned certain = 0, certain_exact = 0, uncertain = 0, uncertain_plausible = 0; + unsigned first_bad_x = 0, first_bad_y = 0; + Color first_bad_gpu{}, first_bad_ref{}; + bool pass() const { return certain_exact == certain && uncertain_plausible == uncertain; } +}; + +inline Comparison compare(const std::vector& gpu, const Reference& ref) { + using detail::same; + Comparison c; + bool reported = false; + for (std::size_t i = 0; i < gpu.size(); ++i) { + bool ok; + if (ref.candidates[i].empty()) { + ++c.certain; + ok = same(gpu[i], ref.color[i]); + c.certain_exact += ok; + } else { + ++c.uncertain; + ok = std::any_of(ref.candidates[i].begin(), ref.candidates[i].end(), + [&](const Color& k) { return same(gpu[i], k); }); + c.uncertain_plausible += ok; + } + if (!ok && !reported) { + reported = true; + c.first_bad_x = unsigned(i % kWidth), c.first_bad_y = unsigned(i / kWidth); + c.first_bad_gpu = gpu[i], c.first_bad_ref = ref.color[i]; + } + } + return c; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/lanterns_scene.h b/runtime/test/lanterns/lanterns_scene.h new file mode 100644 index 0000000000..112c5f316b --- /dev/null +++ b/runtime/test/lanterns/lanterns_scene.h @@ -0,0 +1,226 @@ +// Lanterns, stage 1: the scene, as data both the guest's draws and its CPU reference read (lanterns_reference.h). +// Everything here is ours and abstract: a few convex solids (hexagonal prisms, cubes, octahedra, square pyramids) +// standing on a floor plane, seen by a perspective camera. Colours come from short binary fractions (multiples of +// 1/8 for the instance colours, the per-draw tint and the per-face shade; 1/16 for the floor's two checker colours), +// so every product the shaders form is exact in float and the CPU reference can compare interior pixels bit for bit. +// Positions and matrices are ordinary floats: the reference treats the pixels they make uncertain (edges, depth +// near-ties, checker borders) apart. No Windows or D3D12 types: lanterns.cpp turns this into buffers and draws. +#pragma once + +#include +#include +#include +#include +#include + +namespace lanterns { + +constexpr unsigned kWidth = 384, kHeight = 256; // render target, R32G32B32A32_FLOAT +constexpr unsigned kPitch = kWidth * 16; // 6144 bytes, a multiple of D3D12's 256 +constexpr std::array kClear = {0.0625f, 0.0625f, 0.125f, 1.0f}; + +// One vertex as vs_lanterns.asm fetches it through the mesh V# (stride 16): position xyz, then the face's shade. +struct Vertex { + float x, y, z, shade; +}; +// One instance as vs_lanterns.asm fetches it through the instance V# (stride 32): offset xyz, uniform scale, colour. +struct Instance { + float offset[3]; + float scale; + float color[4]; +}; +static_assert(sizeof(Vertex) == 16 && sizeof(Instance) == 32); + +// A convex planar face: 3 to 6 vertex indices into its mesh, wound consistently; the index buffer fans it. +struct Face { + unsigned count; + std::array v; +}; + +struct Mesh { + const char* name; + std::vector vertices; // each face has its own vertices, so a face's shade is constant across it + std::vector faces; +}; + +// The shade of a face from its local normal and a fixed light: 0.5 + 0.5 * max(0, n.l), rounded to 1/8, clamped to +// [0.25, 1]. Integer eighths keep the colour products exact. +inline float face_shade(double nx, double ny, double nz) { + const double lx = -0.4, ly = 0.8, lz = -0.45; // towards the light, roughly from above and in front + const double len = std::sqrt(nx * nx + ny * ny + nz * nz) * std::sqrt(lx * lx + ly * ly + lz * lz); + const double d = (nx * lx + ny * ly + nz * lz) / len; + long eighths = std::lround((0.5 + 0.5 * (d > 0 ? d : 0.0)) * 8.0); + eighths = eighths < 2 ? 2 : eighths > 8 ? 8 : eighths; + return float(eighths) / 8.0f; +} + +// Adds one face from positions; the shade comes from the face's own normal (Newell's method), turned to point away +// from `inside` (a point inside the convex solid), and the face is wound the same way for every face. +inline void add_face(Mesh& mesh, std::vector> p, const std::array& inside) { + double nx = 0, ny = 0, nz = 0, cx = 0, cy = 0, cz = 0; + for (std::size_t i = 0; i < p.size(); ++i) { + const auto& a = p[i]; + const auto& b = p[(i + 1) % p.size()]; + nx += (a[1] - b[1]) * (a[2] + b[2]); + ny += (a[2] - b[2]) * (a[0] + b[0]); + nz += (a[0] - b[0]) * (a[1] + b[1]); + cx += a[0], cy += a[1], cz += a[2]; + } + const double n = double(p.size()); + if (nx * (cx / n - inside[0]) + ny * (cy / n - inside[1]) + nz * (cz / n - inside[2]) < 0) { + nx = -nx, ny = -ny, nz = -nz; + std::reverse(p.begin(), p.end()); + } + const float shade = face_shade(nx, ny, nz); + Face face{unsigned(p.size()), {}}; + for (std::size_t i = 0; i < p.size(); ++i) { + face.v[i] = std::uint16_t(mesh.vertices.size()); + mesh.vertices.push_back({float(p[i][0]), float(p[i][1]), float(p[i][2]), shade}); + } + mesh.faces.push_back(face); +} + +// A prism with an n-gon cross-section, axis along y from y0 to y1, circumradius r. +inline Mesh prism(const char* name, unsigned n, double r, double y0, double y1) { + Mesh m{name, {}, {}}; + const double pi = 3.14159265358979323846; + const std::array centre{0.0, (y0 + y1) / 2, 0.0}; + std::vector> ring(n); + for (unsigned i = 0; i < n; ++i) + ring[i] = {r * std::cos(2 * pi * i / n), 0.0, r * std::sin(2 * pi * i / n)}; + for (unsigned i = 0; i < n; ++i) { + const auto& a = ring[i]; + const auto& b = ring[(i + 1) % n]; + add_face(m, {{a[0], y0, a[2]}, {a[0], y1, a[2]}, {b[0], y1, b[2]}, {b[0], y0, b[2]}}, centre); + } + std::vector> top, bottom; + for (unsigned i = 0; i < n; ++i) { + top.push_back({ring[i][0], y1, ring[i][2]}); + bottom.push_back({ring[i][0], y0, ring[i][2]}); + } + add_face(m, top, centre); + add_face(m, bottom, centre); + return m; +} + +inline Mesh octahedron(double r) { + Mesh m{"octahedron", {}, {}}; + for (double sy : {1.0, -1.0}) + for (double sx : {1.0, -1.0}) + for (double sz : {1.0, -1.0}) + add_face(m, {{sx * r, 0, 0}, {0, sy * r, 0}, {0, 0, sz * r}}, {0, 0, 0}); + // Lift it so its lowest vertex rests at y = 0 when the instance offset is on the floor. + for (Vertex& v : m.vertices) v.y += float(r); + return m; +} + +inline Mesh pyramid(double half, double height) { + Mesh m{"pyramid", {}, {}}; + const std::array c[4] = {{-half, 0, -half}, {half, 0, -half}, {half, 0, half}, {-half, 0, half}}; + const std::array apex{0, height, 0}; + const std::array centre{0, height / 4, 0}; + for (int i = 0; i < 4; ++i) add_face(m, {c[i], apex, c[(i + 1) % 4]}, centre); + add_face(m, {c[0], c[1], c[2], c[3]}, centre); + return m; +} + +inline Mesh floor_quad(double x0, double x1, double z0, double z1) { + Mesh m{"floor", {}, {}}; + Face face{4, {0, 1, 2, 3}}; + m.vertices = {{float(x0), 0, float(z0), 1}, {float(x0), 0, float(z1), 1}, {float(x1), 0, float(z1), 1}, + {float(x1), 0, float(z0), 1}}; + m.faces.push_back(face); + return m; +} + +// The floor pixel shader's two checker colours, the data words ps_lanterns_floor.asm carries in its own FSSM program +// (read through s_getpc_b64, the code base): colour A where floor(x) + floor(z) is even, B where it is odd. +constexpr std::array kFloorA = {0.4375f, 0.4375f, 0.5f, 1.0f}; +constexpr std::array kFloorB = {0.125f, 0.1875f, 0.25f, 1.0f}; + +// One DrawIndexedInstanced: a mesh, its instances, the root constants (a 3x4 model matrix, row-major, then a tint). +struct Draw { + unsigned mesh; + bool floor; // drawn with ps_lanterns_floor (the checker) instead of ps_lanterns_lit + std::vector instances; + std::array model; // rows: local = M * (x, y, z, 1) + std::array tint; +}; + +inline std::array rotation_y(double degrees) { + const double a = degrees * 3.14159265358979323846 / 180.0; + const float c = float(std::cos(a)), s = float(std::sin(a)); + return {c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0}; +} + +// Instance colour i of a family: the base colour in eighths, red raised by i mod 2 and blue by i / 2 (capped at 8/8). +inline Instance instance(float x, float y, float z, float scale, std::array base_eighths, unsigned i) { + const int r = std::min(8, base_eighths[0] + int(i % 2)), b = std::min(8, base_eighths[2] + int(i / 2)); + return {{x, y, z}, scale, {float(r) / 8.0f, float(base_eighths[1]) / 8.0f, float(b) / 8.0f, 1.0f}}; +} + +struct Scene { + std::vector meshes; + std::vector draws; + std::array view_projection; // rows: clip = VP * (world, 1); the root CBV's 64 bytes +}; + +// Camera: left-handed, y up, looking from the eye at the target; D3D-style depth (0 at near, 1 at far). +inline std::array camera(const double eye[3], const double target[3], double fov_y_deg, double aspect, + double znear, double zfar) { + double f[3] = {target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]}; + const double fl = std::sqrt(f[0] * f[0] + f[1] * f[1] + f[2] * f[2]); + for (double& v : f) v /= fl; + double r[3] = {f[2], 0, -f[0]}; // up (0,1,0) x forward + const double rl = std::sqrt(r[0] * r[0] + r[2] * r[2]); + for (double& v : r) v /= rl; + const double u[3] = {f[1] * r[2] - f[2] * r[1], f[2] * r[0] - f[0] * r[2], f[0] * r[1] - f[1] * r[0]}; + const double ys = 1.0 / std::tan(fov_y_deg * 3.14159265358979323846 / 360.0), xs = ys / aspect; + const double zf = zfar / (zfar - znear), zn = -znear * zfar / (zfar - znear); + const auto dot_eye = [&](const double* a) { return -(a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]); }; + const double view[3][4] = {{r[0], r[1], r[2], dot_eye(r)}, {u[0], u[1], u[2], dot_eye(u)}, + {f[0], f[1], f[2], dot_eye(f)}}; + std::array m{}; + for (int c = 0; c < 4; ++c) { + m[0 + c] = float(xs * view[0][c]); + m[4 + c] = float(ys * view[1][c]); + m[8 + c] = float(zf * view[2][c] + (c == 3 ? zn : 0.0)); + m[12 + c] = float(view[2][c]); + } + return m; +} + +// Stage 1. Draws are submitted nearest family first and the floor last, so with the depth test off the floor paints +// over everything and the far solids over the near ones: the negative control has plenty to change. +inline Scene stage1() { + Scene s; + s.meshes.push_back(prism("lantern", 6, 0.45, 0.0, 1.5)); // 0: hexagonal prisms, the "lanterns" + s.meshes.push_back(prism("cube", 4, 0.70710678, 0.0, 1.0)); // 1: square prism = a unit cube (turned 45 degrees) + s.meshes.push_back(octahedron(0.6)); // 2 + s.meshes.push_back(pyramid(0.6, 1.1)); // 3 + s.meshes.push_back(floor_quad(-6.0, 6.0, -3.0, 9.0)); // 4 + + Draw lanterns{0, false, {}, rotation_y(10), {1.0f, 1.0f, 1.0f, 1.0f}}; + for (unsigned i = 0; i < 3; ++i) + lanterns.instances.push_back(instance(-2.25f + 2.25f * float(i), 0.0f, -0.5f + 0.75f * float(i % 2), 1.0f, + {7, 5, 1}, i)); + Draw cubes{1, false, {}, rotation_y(20), {1.0f, 0.875f, 1.0f, 1.0f}}; + const float cube_x[3] = {-1.25f, 1.125f, 3.375f}; + for (unsigned i = 0; i < 3; ++i) + cubes.instances.push_back(instance(cube_x[i], 0.0f, 2.0f, 0.875f + 0.125f * float(i % 2), {2, 6, 6}, i)); + Draw octahedra{2, false, {}, rotation_y(30), {1.0f, 1.0f, 1.0f, 1.0f}}; + for (unsigned i = 0; i < 2; ++i) + octahedra.instances.push_back(instance(-1.5f + 3.0f * float(i), 0.0f, 4.0f, 1.25f, {5, 3, 7}, i)); + Draw pyramids{3, false, {}, rotation_y(-15), {1.0f, 1.0f, 0.875f, 1.0f}}; + for (unsigned i = 0; i < 2; ++i) + pyramids.instances.push_back(instance(-4.0f + 8.0f * float(i), 0.0f, 5.5f, 1.5f, {7, 3, 2}, i)); + Draw floor{4, true, {}, rotation_y(0), {1.0f, 0.875f, 0.75f, 1.0f}}; + floor.instances.push_back({{0.0f, 0.0f, 0.0f}, 1.0f, {1.0f, 1.0f, 1.0f, 1.0f}}); + s.draws = {lanterns, cubes, octahedra, pyramids, floor}; + + const double eye[3] = {0.5, 3.25, -6.5}, target[3] = {0.0, 0.6, 2.5}; + s.view_projection = camera(eye, target, 52.0, double(kWidth) / double(kHeight), 0.5, 40.0); + return s; +} + +} // namespace lanterns diff --git a/runtime/test/lanterns/run_lanterns.py b/runtime/test/lanterns/run_lanterns.py new file mode 100644 index 0000000000..e916044bc5 --- /dev/null +++ b/runtime/test/lanterns/run_lanterns.py @@ -0,0 +1,223 @@ +"""Run Lanterns under gta6rt --run, check what it printed, and turn its frame dumps into PNGs. + + python -I runtime/test/lanterns/run_lanterns.py --gta6rt --guest + --shaders --out [--stage 1] [--wine] [--timeout 240] [--png FILE] + +It sets LEONIDA_D3D12=vulkan and LEONIDA_SHADERS=/spirv and runs +"gta6rt --run lanterns.exe -- --stage N --shaders --out " (under Wine with --wine, paths turned into +Z:\ paths). The run passes only if all of these hold, which a loader that exits 0 early, a guest that prints and then +fails, or the host's PC device instead of the shim's Vulkan device would each break: + - the exit code is 0; + - stdout has the line "Lanterns stage N: PASS, ..." exactly once (the guest prints it after every check); + - the output has the shim's complete factory line "[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy 0x... (Vulkan + device 0x...)" (the guard PR #3913's run_guest_draw.cmake uses). +The timeout is a promise: when it expires the whole process group (Windows: the process tree) is killed and the run +fails with exit code 3, whatever the guest, Wine or the GPU are doing. tests/test_run_lanterns.py checks it with a +launcher that never ends. + +PNGs (sRGB-encoded from the linear float target), /lanterns-stage.png and lanterns-stage-sheet.png: + stage 1: the GPU frame with the depth test; sheet: GPU | CPU reference / GPU without depth (the negative control) | + mask of the depth frame: certain and exact (grey), certain and wrong (red), uncertain (yellow) +""" +import argparse +import array +import os +import re +import signal +import struct +import subprocess +import sys +import time +import zlib + +WIDTH, HEIGHT = 384, 256 +TIMEOUT_EXIT = 3 +FACTORY = re.compile(r"^\[rt\] d3d12_xs: D3D12XboxCreateDevice -> proxy (0[xX])?0*[1-9A-Fa-f][0-9A-Fa-f]* " + r"\(Vulkan device (0[xX])?0*[1-9A-Fa-f][0-9A-Fa-f]*\)$", re.M) + + +def marker(stage): + return re.compile(rf"^Lanterns stage {stage}: PASS, .*$", re.M) + + +def check_transcript(stage, exit_code, stdout, stderr): + """The reasons a finished run does not count as a pass (empty: it passes).""" + stdout, stderr = stdout.replace("\r\n", "\n"), stderr.replace("\r\n", "\n") + failures = [] + if exit_code != 0: + failures.append(f"exit code {exit_code}, not 0") + found = marker(stage).findall(stdout) + if len(found) != 1: + failures.append(f"stdout has the 'Lanterns stage {stage}: PASS' line {len(found)} times, not once") + if not FACTORY.search(stderr) and not FACTORY.search(stdout): + failures.append("no line shows D3D12XboxCreateDevice returning the shim's Vulkan device") + return failures + + +def kill_tree(proc): + """Kill the launcher and everything it started, then reap it; never waits unboundedly.""" + try: + if os.name == "nt": + subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True, timeout=30) + else: + os.killpg(proc.pid, signal.SIGKILL) + except (OSError, subprocess.TimeoutExpired): + proc.kill() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + pass + + +def run(cmd, env, timeout, log_base): + """(exit code, stdout, stderr, timed out). Output goes to .stdout/.stderr files, not pipes: a process + the launcher leaves behind (wineserver) may hold a pipe open long after gta6rt exits, so the wait is on the + process. The child gets its own process group, so a timeout kills all of it.""" + kwargs = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True} + with open(log_base + ".stdout", "wb") as out_file, open(log_base + ".stderr", "wb") as err_file: + proc = subprocess.Popen(cmd, env=env, stdin=subprocess.DEVNULL, stdout=out_file, stderr=err_file, **kwargs) + try: + code, timed_out = proc.wait(timeout=timeout), False + except subprocess.TimeoutExpired: + kill_tree(proc) + code, timed_out = None, True + texts = [] + for suffix in (".stdout", ".stderr"): + with open(log_base + suffix, "rb") as f: + texts.append(f.read().decode("utf-8", "replace")) + return code, texts[0], texts[1], timed_out + + +def wine_path(path): + return "Z:" + os.path.abspath(path).replace("/", "\\") + + +# ---------------------------------------------------------------------------------------------------------- PNG + +def png(path, width, height, rows): + """rows: one bytes object of width * 3 RGB bytes per row.""" + raw = b"".join(b"\x00" + row for row in rows) + + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) + + with open(path, "wb") as f: + f.write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")) + + +def srgb8(v): + v = 0.0 if v != v or v < 0 else 1.0 if v > 1 else v + v = 12.92 * v if v <= 0.0031308 else 1.055 * v ** (1 / 2.4) - 0.055 + return int(v * 255 + 0.5) + + +def read_floats(path): + data = array.array("f") + with open(path, "rb") as f: + data.frombytes(f.read()) + if sys.byteorder != "little": + data.byteswap() + if len(data) != WIDTH * HEIGHT * 4: + raise ValueError(f"{path}: {len(data)} floats, not {WIDTH * HEIGHT * 4}") + return data + + +def rgb_rows(floats): + return [bytes(srgb8(floats[(y * WIDTH + x) * 4 + c]) for x in range(WIDTH) for c in range(3)) for y in range(HEIGHT)] + + +def mask_rows(gpu, ref, uncertain): + rows = [] + for y in range(HEIGHT): + row = bytearray() + for x in range(WIDTH): + i = y * WIDTH + x + if uncertain[i]: + row += b"\xe0\xc0\x20" + elif gpu[i * 4:i * 4 + 4] == ref[i * 4:i * 4 + 4]: + row += b"\x50\x50\x50" + else: + row += b"\xff\x00\x00" + rows.append(bytes(row)) + return rows + + +# The panels of each stage's PNGs: ".gpu" or ".ref" is a frame, ":mask" the uncertainty map of a dump. +PANELS = { + 1: {"main": [["stage1-depth.gpu"]], + "sheet": [["stage1-depth.gpu", "stage1-depth.ref"], ["stage1-nodepth.gpu", "stage1-depth:mask"]]}, +} + + +def panel_rows(out, name, cache): + if name not in cache: + if name.endswith(":mask"): + dump = os.path.join(out, name[:-5]) + with open(dump + ".uncertain.u8", "rb") as f: + uncertain = f.read() + cache[name] = mask_rows(read_floats(dump + ".gpu.rgba32f"), read_floats(dump + ".ref.rgba32f"), uncertain) + else: + cache[name] = rgb_rows(read_floats(os.path.join(out, name + ".rgba32f"))) + return cache[name] + + +def grid(out, layout, cache): + rows = [] + for panel_row in layout: + panels = [panel_rows(out, name, cache) for name in panel_row] + rows += [b"".join(parts) for parts in zip(*panels)] + return WIDTH * len(layout[0]), HEIGHT * len(layout), rows + + +def write_pngs(out, stage, main_png): + cache = {} + png(main_png, *grid(out, PANELS[stage]["main"], cache)) + sheet = os.path.join(out, f"lanterns-stage{stage}-sheet.png") + png(sheet, *grid(out, PANELS[stage]["sheet"], cache)) + return sheet + + +def main(argv=None): + ap = argparse.ArgumentParser(description="Run Lanterns under gta6rt --run and check it.") + ap.add_argument("--gta6rt", required=True) + ap.add_argument("--guest", required=True) + ap.add_argument("--shaders", required=True, help="the folder fssm_pack.py wrote (with spirv/index.json)") + ap.add_argument("--out", required=True) + ap.add_argument("--stage", type=int, default=1, choices=sorted(PANELS)) + ap.add_argument("--wine", action="store_true", help="run gta6rt.exe under wine (paths become Z:\\...)") + ap.add_argument("--timeout", type=float, default=240.0, help="seconds before the run is killed and fails") + ap.add_argument("--png", help="where to write the main PNG (default /lanterns-stage.png)") + a = ap.parse_args(argv) + for path in (a.gta6rt, a.guest, os.path.join(a.shaders, "spirv", "index.json")): + if not os.path.exists(path): + print(f"ERROR: {path} does not exist", file=sys.stderr) + return 2 + os.makedirs(a.out, exist_ok=True) + conv = wine_path if a.wine else os.path.abspath + env = dict(os.environ, LEONIDA_D3D12="vulkan", LEONIDA_SHADERS=conv(os.path.join(a.shaders, "spirv"))) + cmd = (["wine"] if a.wine else []) + [a.gta6rt, "--run", conv(a.guest), "--", "--stage", str(a.stage), + "--shaders", conv(a.shaders), "--out", conv(a.out)] + started = time.monotonic() + code, out, err, timed_out = run(cmd, env, a.timeout, os.path.join(a.out, f"gta6rt-stage{a.stage}")) + took = time.monotonic() - started + print(f"--- gta6rt stdout ---\n{out}\n--- gta6rt stderr ---\n{err}\n--- exit: {code} ({took:.1f} s)") + if timed_out: + print(f"lanterns: FAILED: no exit after {a.timeout:g} s; the process group was killed", file=sys.stderr) + return TIMEOUT_EXIT + failures = check_transcript(a.stage, code, out, err) + try: + main_png = a.png or os.path.join(a.out, f"lanterns-stage{a.stage}.png") + sheet = write_pngs(a.out, a.stage, main_png) + print(f"lanterns: wrote {main_png} and {sheet}") + except (OSError, ValueError) as e: + failures.append(f"no frame dumps to draw: {e}") + if failures: + print("lanterns: FAILED: " + "; ".join(failures), file=sys.stderr) + return 1 + print("lanterns: " + marker(a.stage).search(out.replace("\r\n", "\n")).group(0)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runtime/test/lanterns/shaders/ps_lanterns_floor.asm b/runtime/test/lanterns/shaders/ps_lanterns_floor.asm new file mode 100644 index 0000000000..2d9bc72719 --- /dev/null +++ b/runtime/test/lanterns/shaders/ps_lanterns_floor.asm @@ -0,0 +1,48 @@ +; Lanterns pixel shader for the floor (stage 1): a checker from the interpolated world position, in two colours that +; sit in the shader's own FSSM program and are read through the code base, times the draw's tint (read flat). +; The first instruction is s_getpc_b64, which returns the address of the next one: the first instruction + 4. The +; colours are "data-at" 0x100 bytes after the first instruction, so the offset added is 0x100 - 4 = 0xfc. +; parity = (floor(world.x) + floor(world.z)) & 1 +; mrt0 = (parity == 0 ? A : B) * tint A = (0.4375, 0.4375, 0.5, 1), B = (0.125, 0.1875, 0.25, 1) +; The same values are kFloorA and kFloorB in lanterns_scene.h. +; stage: ps +; wave: 32 +; input: flat +; input: interp +; data-at: 0x100 +; data: 0x3ee00000 0x3ee00000 0x3f000000 0x3f800000 +; data: 0x3e000000 0x3e400000 0x3e800000 0x3f800000 +s_getpc_b64 s[6:7] +s_add_u32 s6, s6, 0xfc +s_addc_u32 s7, s7, 0 +s_load_dwordx8 s[8:15], s[6:7], 0x0 +v_interp_p1_f32_e32 v2, v0, attr1.x +v_interp_p2_f32_e32 v2, v1, attr1.x +v_interp_p1_f32_e32 v3, v0, attr1.z +v_interp_p2_f32_e32 v3, v1, attr1.z +v_interp_mov_f32 v10, p0, attr0.x +v_interp_mov_f32 v11, p0, attr0.y +v_interp_mov_f32 v12, p0, attr0.z +v_interp_mov_f32 v13, p0, attr0.w +v_floor_f32_e32 v2, v2 +v_floor_f32_e32 v3, v3 +v_cvt_i32_f32_e32 v2, v2 +v_cvt_i32_f32_e32 v3, v3 +v_add_nc_u32_e32 v2, v2, v3 +v_and_b32_e32 v2, 1, v2 +v_cmp_eq_u32_e32 vcc_lo, 0, v2 +s_waitcnt lgkmcnt(0) +v_mov_b32_e32 v4, s8 +v_mov_b32_e32 v5, s9 +v_mov_b32_e32 v6, s10 +v_mov_b32_e32 v7, s11 +v_cndmask_b32_e32 v4, s12, v4, vcc_lo +v_cndmask_b32_e32 v5, s13, v5, vcc_lo +v_cndmask_b32_e32 v6, s14, v6, vcc_lo +v_cndmask_b32_e32 v7, s15, v7, vcc_lo +v_mul_f32_e32 v4, v4, v10 +v_mul_f32_e32 v5, v5, v11 +v_mul_f32_e32 v6, v6, v12 +v_mul_f32_e32 v7, v7, v13 +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm diff --git a/runtime/test/lanterns/shaders/ps_lanterns_lit.asm b/runtime/test/lanterns/shaders/ps_lanterns_lit.asm new file mode 100644 index 0000000000..cd32ebfa49 --- /dev/null +++ b/runtime/test/lanterns/shaders/ps_lanterns_lit.asm @@ -0,0 +1,13 @@ +; Lanterns pixel shader for the solids (stage 1): the face colour, read flat (v_interp_mov_f32), straight to mrt0. +; Packed by ../fssm_pack.py; the FSSM input table declares both of vs_lanterns.asm's parameters, as the title's +; tables do: position 0 read flat (read method 1), position 1 interpolated (read method 2) but unread here. +; stage: ps +; wave: 32 +; input: flat +; input: interp +v_interp_mov_f32 v2, p0, attr0.x +v_interp_mov_f32 v3, p0, attr0.y +v_interp_mov_f32 v4, p0, attr0.z +v_interp_mov_f32 v5, p0, attr0.w +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/lanterns/shaders/vs_lanterns.asm b/runtime/test/lanterns/shaders/vs_lanterns.asm new file mode 100644 index 0000000000..0e014b1000 --- /dev/null +++ b/runtime/test/lanterns/shaders/vs_lanterns.asm @@ -0,0 +1,60 @@ +; Lanterns vertex shader (stage 1). Hand-written RDNA2 (gfx1013), packed by ../fssm_pack.py into a synthetic +; FSSM program in a DXBC/XDAT/XBCH container, then unpacked, disassembled and translated by the project's own tools. +; It fetches its vertex and its instance through two V#s, as the title's vertex shaders that have no fetch program do. +; stage: vs +; wave: 32 +; +; User SGPRs (root signature order, docs/d3d12_vulkan.md 3.5): +; s[0:1] table 0: console VA of the mesh's V# (stride 16: position xyz, face shade) +; s[2:3] table 1: console VA of the draw's instance V# (stride 32: offset xyz, scale, colour rgba) +; s4..s15 root constants: the draw's 3x4 model matrix, row-major +; s16..s19 root constants: the draw's tint (rgba) +; s[20:21] root CBV: console VA of the camera's view-projection matrix (16 floats, row-major) +; v0 = vertex index (from the index buffer), v3 = instance index; the draws use BaseVertex 0 and StartInstance 0. +; local = M * (pos, 1) world = local * scale + offset pos0 = VP * (world, 1) +; param0 = (tint * colour) * shade, alpha tint.a * colour.a: constant over a face, read flat by the pixel shaders +; param1 = (world, 1): the floor's pixel shader interpolates x and z for its checker +s_load_dwordx4 s[24:27], s[0:1], 0x0 +s_load_dwordx4 s[28:31], s[2:3], 0x0 +s_load_dwordx16 s[32:47], s[20:21], 0x0 +s_waitcnt lgkmcnt(0) +buffer_load_dwordx4 v[4:7], v0, s[24:27], 0 idxen +buffer_load_dwordx4 v[8:11], v3, s[28:31], 0 idxen +buffer_load_dwordx4 v[12:15], v3, s[28:31], 0 idxen offset:16 +s_waitcnt vmcnt(0) +v_fma_f32 v16, s4, v4, s7 +v_fmac_f32_e32 v16, s5, v5 +v_fmac_f32_e32 v16, s6, v6 +v_fma_f32 v17, s8, v4, s11 +v_fmac_f32_e32 v17, s9, v5 +v_fmac_f32_e32 v17, s10, v6 +v_fma_f32 v18, s12, v4, s15 +v_fmac_f32_e32 v18, s13, v5 +v_fmac_f32_e32 v18, s14, v6 +v_fma_f32 v19, v16, v11, v8 +v_fma_f32 v20, v17, v11, v9 +v_fma_f32 v21, v18, v11, v10 +v_fma_f32 v22, s32, v19, s35 +v_fmac_f32_e32 v22, s33, v20 +v_fmac_f32_e32 v22, s34, v21 +v_fma_f32 v23, s36, v19, s39 +v_fmac_f32_e32 v23, s37, v20 +v_fmac_f32_e32 v23, s38, v21 +v_fma_f32 v24, s40, v19, s43 +v_fmac_f32_e32 v24, s41, v20 +v_fmac_f32_e32 v24, s42, v21 +v_fma_f32 v25, s44, v19, s47 +v_fmac_f32_e32 v25, s45, v20 +v_fmac_f32_e32 v25, s46, v21 +v_mul_f32_e32 v26, s16, v12 +v_mul_f32_e32 v26, v26, v7 +v_mul_f32_e32 v27, s17, v13 +v_mul_f32_e32 v27, v27, v7 +v_mul_f32_e32 v28, s18, v14 +v_mul_f32_e32 v28, v28, v7 +v_mul_f32_e32 v29, s19, v15 +v_mov_b32_e32 v30, 1.0 +exp pos0 v22, v23, v24, v25 done +exp param0 v26, v27, v28, v29 +exp param1 v19, v20, v21, v30 +s_endpgm diff --git a/tests/test_run_lanterns.py b/tests/test_run_lanterns.py new file mode 100644 index 0000000000..66dd765a6e --- /dev/null +++ b/tests/test_run_lanterns.py @@ -0,0 +1,80 @@ +"""run_lanterns.py: its timeout keeps its promise against a launcher that never ends, and only a complete transcript +(exit 0, the PASS line once, the shim's Vulkan device line) counts as a pass. + + python -I tests/test_run_lanterns.py +""" +import os +import subprocess +import sys +import tempfile +import time +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RUNNER = os.path.join(ROOT, "runtime", "test", "lanterns", "run_lanterns.py") +sys.path.insert(0, os.path.dirname(RUNNER)) + +import run_lanterns # noqa: E402 + +FACTORY = "[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy 0x1f2e3d4c (Vulkan device 0x5a6b7c8d)" +PASS = "Lanterns stage 1: PASS, 90000 of 98304 pixels exact, 8304 edge pixels plausible, depth-off control changed 20000 pixels" + + +def alive(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +@unittest.skipIf(os.name == "nt", "the stalled launcher is a POSIX shell script") +class StalledLauncher(unittest.TestCase): + def test_timeout_kills_the_launcher_and_its_children(self): + with tempfile.TemporaryDirectory() as tmp: + pids = os.path.join(tmp, "pids") + # A "gta6rt" that starts a child and then hangs, as a guest stuck on a fence or a hung GPU would. + fake = os.path.join(tmp, "gta6rt") + with open(fake, "w", encoding="utf-8") as f: + f.write(f"#!/bin/sh\necho $$ > {pids}\nsleep 300 &\necho $! >> {pids}\nwait\n") + os.chmod(fake, 0o755) + shaders = os.path.join(tmp, "shaders") + os.makedirs(os.path.join(shaders, "spirv")) + open(os.path.join(shaders, "spirv", "index.json"), "w").close() + started = time.monotonic() + r = subprocess.run([sys.executable, "-I", RUNNER, "--gta6rt", fake, "--guest", fake, "--shaders", shaders, + "--out", os.path.join(tmp, "out"), "--timeout", "2"], + capture_output=True, text=True, timeout=60) + took = time.monotonic() - started + self.assertEqual(r.returncode, run_lanterns.TIMEOUT_EXIT, r.stderr) + self.assertLess(took, 20) + with open(pids, encoding="utf-8") as f: + launched = [int(line) for line in f.read().split()] + self.assertEqual(len(launched), 2) + deadline = time.monotonic() + 5 + while any(alive(p) for p in launched) and time.monotonic() < deadline: + time.sleep(0.1) + self.assertFalse([p for p in launched if alive(p)]) + + +class Transcript(unittest.TestCase): + def test_only_a_complete_transcript_passes(self): + check = run_lanterns.check_transcript + self.assertEqual(check(1, 0, PASS + "\n", FACTORY + "\n"), []) + self.assertEqual(check(1, 0, PASS + "\r\n", FACTORY + "\r\n"), []) + cases = { + "nonzero exit": (1, PASS + "\n", FACTORY + "\n"), + "no PASS line": (0, "lanterns: stage 1 FAILED\n", FACTORY + "\n"), + "PASS twice": (0, PASS + "\n" + PASS + "\n", FACTORY + "\n"), + "PASS inside another line": (0, "echo " + PASS + "\n", FACTORY + "\n"), + "no device line": (0, PASS + "\n", ""), + "host device, not the shim's": (0, PASS + "\n", "[rt] d3d12_xs: D3D12XboxCreateDevice -> host device\n"), + "null device pointer": (0, PASS + "\n", FACTORY.replace("0x5a6b7c8d", "0x0") + "\n"), + } + for name, (code, out, err) in cases.items(): + with self.subTest(name): + self.assertTrue(check(1, code, out, err)) + + +if __name__ == "__main__": + unittest.main() From 3049375d2c574860fa147ca4ad1597b7eef734f9 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 06:25:43 +0100 Subject: [PATCH 06/24] fix: run_lanterns.py accepts only the whole PASS line and fails when cleanup fails - The PASS line must match its stage's full pattern, with numbers that fit together; "PASS" followed by anything else no longer passes. - Each run writes into a new folder under --out, so an old run's dumps or pictures cannot stand in for a missing one. - On Linux the runner becomes a child subreaper and also kills descendants that left the launcher's session. taskkill and killpg results are checked; anything left alive fails the run with exit code 4. - With --wine it stops the prefix's wineserver (-k, then -w, 10 s each) before the launch: a launch under a new virtual X server while the last run's explorer.exe is alive can hang in winevulkan's device creation. - The docstring's Windows path no longer has an invalid escape (SyntaxWarning, fatal under -W error). tests/test_run_lanterns.py: a grandchild that calls setsid() must die too, each run gets its own folder, three malformed PASS lines are refused, and the wineserver stop runs before the launch (fake wineserver and wine on PATH; a hanging wineserver fails the run within its timeout). --- runtime/test/lanterns/run_lanterns.py | 177 ++++++++++++++++++++++---- tests/test_run_lanterns.py | 85 ++++++++++--- 2 files changed, 219 insertions(+), 43 deletions(-) diff --git a/runtime/test/lanterns/run_lanterns.py b/runtime/test/lanterns/run_lanterns.py index e916044bc5..39d56a856a 100644 --- a/runtime/test/lanterns/run_lanterns.py +++ b/runtime/test/lanterns/run_lanterns.py @@ -5,17 +5,27 @@ It sets LEONIDA_D3D12=vulkan and LEONIDA_SHADERS=/spirv and runs "gta6rt --run lanterns.exe -- --stage N --shaders --out " (under Wine with --wine, paths turned into -Z:\ paths). The run passes only if all of these hold, which a loader that exits 0 early, a guest that prints and then +Z:\\ paths). The run passes only if all of these hold, which a loader that exits 0 early, a guest that prints and then fails, or the host's PC device instead of the shim's Vulkan device would each break: - the exit code is 0; - - stdout has the line "Lanterns stage N: PASS, ..." exactly once (the guest prints it after every check); + - stdout has the stage's PASS line exactly once, whole, with numbers that fit together (PASS_LINES; the guest + prints it after every check); - the output has the shim's complete factory line "[rt] d3d12_xs: D3D12XboxCreateDevice -> proxy 0x... (Vulkan device 0x...)" (the guard PR #3913's run_guest_draw.cmake uses). -The timeout is a promise: when it expires the whole process group (Windows: the process tree) is killed and the run -fails with exit code 3, whatever the guest, Wine or the GPU are doing. tests/test_run_lanterns.py checks it with a -launcher that never ends. +The timeout is a promise: when it expires everything the run started is killed and the run fails with exit code 3, +whatever the guest, Wine or the GPU are doing. On Linux the runner is a child subreaper, so a process that left the +launcher's session and lost its parent still comes back to it and is killed too; on Windows the process tree is +killed with taskkill /T. If anything survives (or taskkill fails), the run fails with exit code 4 and says what is +left. tests/test_run_lanterns.py checks it with a launcher that never ends and a child that escapes its session. -PNGs (sRGB-encoded from the linear float target), /lanterns-stage.png and lanterns-stage-sheet.png: +With --wine the prefix's wineserver is stopped (wineserver -k, then -w, each under a 10 s timeout) before the +launch: a launch under a new virtual X server while the previous run's explorer.exe is alive hangs in winevulkan. + +Each run writes into a new folder, /stage--