upleb.uk

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

summaryrefslogtreecommitdiff
path: root/tools/first_light.py
diff options
context:
space:
mode:
authorJeremy Goldberg <goldberg.jeremy02@gmail.com>2026-11-22 17:50:46 -0500
committerJeremy Goldberg <goldberg.jeremy02@gmail.com>2026-11-22 17:50:46 -0500
commit3b598a9be4bf9f4bc5adc0dfb8729308f5a3d5d6 (patch)
treed1e588030ba2bf78b09326d06d453801c17b35d4 /tools/first_light.py
parent3302d4ec81d17c2bb4ea8f45b8f09872eff1734f (diff)
parentaa2988cc555bad7ecd508b48a702adbb32fe7c95 (diff)
docs(first-light): distinguish UV and textured draw defaults
Refs: #3350
Diffstat (limited to 'tools/first_light.py')
-rw-r--r--tools/first_light.py207
1 files changed, 182 insertions, 25 deletions
diff --git a/tools/first_light.py b/tools/first_light.py
index 70746425c..fbca808c0 100644
--- a/tools/first_light.py
+++ b/tools/first_light.py
@@ -5,7 +5,7 @@ This assembles the smallest end-to-end path from the user's package to a Vulkan
5mesh the GPU harness reads, and run it on the device. Nothing is written outside `--work`, and no game data is 5mesh the GPU harness reads, and run it on the device. Nothing is written outside `--work`, and no game data is
6committed: the tool is the recipe, the user's copy is the input. 6committed: the tool is the recipe, the user's copy is the input.
7 7
8The default pair is a vertex shader that forwards POSITION and TEXCOORD to clip space and a pixel shader that 8Without a DDS texture, the vertex shader forwards clip-space POSITION and TEXCOORD. The default pixel shader
9writes the interpolated TEXCOORD, so the first image is the model's own UV map. Both are ordinary game shaders; 9writes the interpolated TEXCOORD, so the first image is the model's own UV map. Both are ordinary game shaders;
10`--vs` and `--ps` take other names from the carve index. 10`--vs` and `--ps` take other names from the carve index.
11 11
@@ -40,9 +40,17 @@ import sys
40 40
41TOOLS = os.path.dirname(os.path.abspath(__file__)) 41TOOLS = os.path.dirname(os.path.abspath(__file__))
42ROOT = os.path.dirname(TOOLS) 42ROOT = os.path.dirname(TOOLS)
43sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders"))
44from compute_fixture import find_test_program # noqa: E402
45
43DEFAULT_VS = "VS_main_170e32e6_Wrapped" 46DEFAULT_VS = "VS_main_170e32e6_Wrapped"
44DEFAULT_PS = "$PS_Rage_Untextured_14f8529b_Wrapped" 47DEFAULT_PS = "$PS_Rage_Untextured_14f8529b_Wrapped"
48DEFAULT_TEXTURED_PS = "PS_Copy_3ea4b38a_Wrapped"
49DEFAULT_TSHARP_VA = 0x100
50DEFAULT_PTR_SGPR = 9
51DEFAULT_SSHARP = [0x92, 0xC00000, 0x14500000, 0]
45MESH_HEADER = struct.Struct("<II") 52MESH_HEADER = struct.Struct("<II")
53TEX_HEADER = struct.Struct("<II")
46 54
47 55
48def run(argv, **kwargs): 56def run(argv, **kwargs):
@@ -239,6 +247,83 @@ def write_mesh(path: str, vertices, indices) -> None:
239 f.write(struct.pack(f"<{len(indices)}I", *indices)) 247 f.write(struct.pack(f"<{len(indices)}I", *indices))
240 248
241 249
250def decode_dds_to_rgba(path: str) -> tuple[int, int, bytes, str]:
251 """Decode a DDS texture (BC1/BC3/BC7/RGBA8/etc.) via tools/dds_png.py."""
252 if TOOLS not in sys.path:
253 sys.path.insert(0, TOOLS)
254 import dds_png
255
256 with open(path, "rb") as f:
257 raw = f.read()
258 width, height, rgba = dds_png.decode_dds(raw)
259 return width, height, rgba, hashlib.sha256(raw).hexdigest()
260
261
262def write_texture_rgba(path: str, width: int, height: int, rgba: bytes) -> None:
263 if len(rgba) != width * height * 4:
264 raise ValueError(f"expected {width * height * 4} RGBA bytes, got {len(rgba)}")
265 with open(path, "wb") as f:
266 f.write(TEX_HEADER.pack(width, height))
267 f.write(rgba)
268
269
270def sample_rgba_bilinear(
271 width: int, height: int, rgba: bytes, u: float, v: float
272) -> list[float]:
273 """Bilinear sample of an R8G8B8A8_UNORM texture with clamp-to-edge addressing."""
274 u = max(0.0, min(1.0, u))
275 v = max(0.0, min(1.0, v))
276 fx = u * width - 0.5
277 fy = v * height - 0.5
278 x0 = max(0, min(width - 1, int(fx) if fx >= 0 else 0))
279 y0 = max(0, min(height - 1, int(fy) if fy >= 0 else 0))
280 x1 = min(width - 1, x0 + 1)
281 y1 = min(height - 1, y0 + 1)
282 tx = max(0.0, min(1.0, fx - x0))
283 ty = max(0.0, min(1.0, fy - y0))
284
285 def texel(x: int, y: int) -> tuple[float, float, float, float]:
286 off = (y * width + x) * 4
287 return (
288 rgba[off] / 255.0,
289 rgba[off + 1] / 255.0,
290 rgba[off + 2] / 255.0,
291 rgba[off + 3] / 255.0,
292 )
293
294 c00, c10 = texel(x0, y0), texel(x1, y0)
295 c01, c11 = texel(x0, y1), texel(x1, y1)
296 out = []
297 for c in range(4):
298 top = c00[c] * (1.0 - tx) + c10[c] * tx
299 bot = c01[c] * (1.0 - tx) + c11[c] * tx
300 out.append(round(top * (1.0 - ty) + bot * ty, 6))
301 return out
302
303
304def harness_env(manifest: dict, out_dir: str, base_env: dict | None = None) -> dict:
305 """Build the environment variables for vk_harness from a first_light manifest."""
306 env = dict(os.environ if base_env is None else base_env)
307 env["VKH_DRAW_MESH"] = os.path.join(out_dir, manifest["files"]["mesh"])
308 env["VKH_VERTEX_LAYOUT"] = "0:3f,1:2f"
309 tex = manifest.get("texture")
310 if tex:
311 tex_file = manifest["files"]["texture"]
312 ptr_sgpr = int(tex["ptr_sgpr"])
313 tsharp_va = int(tex["tsharp_va"])
314 ssharp = tex["ssharp"]
315 sgprs = ["0"] * (ptr_sgpr + 1)
316 sgprs[ptr_sgpr] = hex(tsharp_va)
317 env["VKH_TEX_RGBA"] = os.path.join(out_dir, tex_file)
318 env["VKH_TSHARP_VA"] = hex(tsharp_va)
319 env["VKH_SSHARP"] = ",".join(hex(int(w)) for w in ssharp)
320 env["VKH_SGPRS"] = ",".join(sgprs)
321 ps_sg = manifest.get("ps", {}).get("subgroup_size")
322 if ps_sg:
323 env["VKH_SUBGROUP_SIZE"] = str(int(ps_sg))
324 return env
325
326
242def pixel_ndc(px: int, py: int, width: int, height: int) -> tuple[float, float]: 327def pixel_ndc(px: int, py: int, width: int, height: int) -> tuple[float, float]:
243 """The NDC of a pixel centre under the harness's viewport (y grows down, like Vulkan).""" 328 """The NDC of a pixel centre under the harness's viewport (y grows down, like Vulkan)."""
244 return (px + 0.5) / width * 2.0 - 1.0, (py + 0.5) / height * 2.0 - 1.0 329 return (px + 0.5) / width * 2.0 - 1.0, (py + 0.5) / height * 2.0 - 1.0
@@ -301,16 +386,20 @@ def uv_probes(vertices, indices, width: int, height: int, limit: int = 4) -> lis
301 386
302 387
303def find_harness(explicit: str | None) -> str: 388def find_harness(explicit: str | None) -> str:
304 exe = ".exe" if os.name == "nt" else "" 389 executable = "vk_harness.exe" if os.name == "nt" else "vk_harness"
390 build = os.path.join(ROOT, "runtime", "build")
391 build_dirs = (os.path.join(build, "linux"), os.path.join(build, "windows"), build)
305 for candidate in ( 392 for candidate in (
306 explicit, 393 explicit,
307 os.environ.get("LEONIDA_VK_HARNESS"), 394 os.environ.get("LEONIDA_VK_HARNESS"),
308 os.path.join(ROOT, "runtime", "build", "linux", f"vk_harness{exe}"), 395 *(os.path.join(folder, executable) for folder in build_dirs),
309 os.path.join(ROOT, "runtime", "build", "windows", f"vk_harness{exe}"),
310 os.path.join(ROOT, "runtime", "build", f"vk_harness{exe}"),
311 ): 396 ):
312 if candidate and os.path.isfile(candidate): 397 if candidate and os.path.isfile(candidate):
313 return candidate 398 return candidate
399 for folder in build_dirs:
400 configured = find_test_program(folder, "vk_harness")
401 if configured:
402 return os.path.join(configured, executable)
314 raise SystemExit( 403 raise SystemExit(
315 "vk_harness not found: build runtime/build/linux or runtime/build/windows (target vk_harness), " 404 "vk_harness not found: build runtime/build/linux or runtime/build/windows (target vk_harness), "
316 "or set --harness/LEONIDA_VK_HARNESS" 405 "or set --harness/LEONIDA_VK_HARNESS"
@@ -349,31 +438,56 @@ def check_image(data: bytes, manifest: dict) -> dict:
349 raise AssertionError( 438 raise AssertionError(
350 f"clear pixel {clear} is {pixels[i : i + 4]}, expected {want}" 439 f"clear pixel {clear} is {pixels[i : i + 4]}, expected {want}"
351 ) 440 )
352 if (uv := manifest.get("centre_uv")) is not None: 441 if (rgba := manifest.get("centre_rgba")) is not None:
353 centre = manifest.get("centre_pixel") or [width // 2, height // 2] 442 centre = manifest.get("centre_pixel") or [width // 2, height // 2]
354 i = (centre[1] * width + centre[0]) * 4 443 i = (centre[1] * width + centre[0]) * 4
355 for c, want in enumerate((uv[0], uv[1], 0.0, 1.0)): 444 tol = manifest.get("rgba_tolerance", 0.02)
356 if abs(pixels[i + c] - want) > 2e-3: 445 for c, want in enumerate(rgba):
446 if abs(pixels[i + c] - want) > tol:
357 raise AssertionError( 447 raise AssertionError(
358 f"centre {centre} is {pixels[i : i + 4]}, expected {want} at {c}" 448 f"centre {centre} is {pixels[i : i + 4]}, expected {rgba} (tol {tol})"
359 ) 449 )
360 for probe in manifest.get("uv_probes", []): 450 elif (uv := manifest.get("centre_uv")) is not None:
361 px, py = probe["pixel"] 451 centre = manifest.get("centre_pixel") or [width // 2, height // 2]
362 i = (py * width + px) * 4 452 i = (centre[1] * width + centre[0]) * 4
363 u, v = probe["uv"] 453 for c, want in enumerate((uv[0], uv[1], 0.0, 1.0)):
364 for c, want in enumerate((u, v, 0.0, 1.0)):
365 if abs(pixels[i + c] - want) > 2e-3: 454 if abs(pixels[i + c] - want) > 2e-3:
366 raise AssertionError( 455 raise AssertionError(
367 f"UV probe {probe['pixel']} is {pixels[i : i + 4]}, expected {want} at {c}" 456 f"centre {centre} is {pixels[i : i + 4]}, expected {want} at {c}"
368 ) 457 )
458 if (rgba_probes := manifest.get("rgba_probes")) is not None:
459 tol = manifest.get("rgba_tolerance", 0.02)
460 for probe in rgba_probes:
461 px, py = probe["pixel"]
462 i = (py * width + px) * 4
463 want_rgba = probe["rgba"]
464 for c, want in enumerate(want_rgba):
465 if abs(pixels[i + c] - want) > tol:
466 raise AssertionError(
467 f"RGBA probe {probe['pixel']} is {pixels[i : i + 4]}, expected {want_rgba} (tol {tol})"
468 )
469 else:
470 for probe in manifest.get("uv_probes", []):
471 px, py = probe["pixel"]
472 i = (py * width + px) * 4
473 u, v = probe["uv"]
474 for c, want in enumerate((u, v, 0.0, 1.0)):
475 if abs(pixels[i + c] - want) > 2e-3:
476 raise AssertionError(
477 f"UV probe {probe['pixel']} is {pixels[i : i + 4]}, expected {want} at {c}"
478 )
369 return {"covered": covered, "ratio": ratio, "pixels": pixels} 479 return {"covered": covered, "ratio": ratio, "pixels": pixels}
370 480
371 481
372def write_ppm(path: str, pixels, width: int, height: int) -> None: 482def write_ppm(path: str, pixels, width: int, height: int) -> None:
483 """Write RGB bytes, saturating infinities and rendering NaN as zero."""
484 def channel_byte(value: float) -> int:
485 return round(min(1.0, value) * 255) if value > 0.0 else 0
486
373 with open(path, "wb") as f: 487 with open(path, "wb") as f:
374 f.write(f"P6\n{width} {height}\n255\n".encode()) 488 f.write(f"P6\n{width} {height}\n255\n".encode())
375 f.writelines( 489 f.writelines(
376 bytes(max(0, min(255, round(pixels[i + c] * 255))) for c in range(3)) 490 bytes(channel_byte(pixels[i + c]) for c in range(3))
377 for i in range(0, len(pixels), 4) 491 for i in range(0, len(pixels), 4)
378 ) 492 )
379 493
@@ -385,11 +499,7 @@ def run_draw(args, manifest: dict, out_dir: str) -> dict:
385 os.unlink( 499 os.unlink(
386 raw 500 raw
387 ) # a harness that exits 0 without writing must not pass on a stale file 501 ) # a harness that exits 0 without writing must not pass on a stale file
388 env = dict( 502 env = harness_env(manifest, out_dir)
389 os.environ,
390 VKH_DRAW_MESH=os.path.join(out_dir, "mesh.bin"),
391 VKH_VERTEX_LAYOUT="0:3f,1:2f",
392 )
393 cmd = [ 503 cmd = [
394 harness, 504 harness,
395 os.path.join(out_dir, "vs.spv"), 505 os.path.join(out_dir, "vs.spv"),
@@ -467,7 +577,7 @@ def load_json(
467 577
468def main(argv=None) -> int: 578def main(argv=None) -> int:
469 ap = argparse.ArgumentParser( 579 ap = argparse.ArgumentParser(
470 description="Draw an exported game model with translated game shaders. The default pair displays its UVs." 580 description="Draw an exported model with translated game shaders. Display its UVs or supply a texture with --dds."
471 ) 581 )
472 ap.add_argument("--game", help="the package folder") 582 ap.add_argument("--game", help="the package folder")
473 ap.add_argument("--obj", help="an OBJ exported by rpf9dump models") 583 ap.add_argument("--obj", help="an OBJ exported by rpf9dump models")
@@ -481,7 +591,11 @@ def main(argv=None) -> int:
481 "--vs", default=DEFAULT_VS, help="vertex shader name in the carve index" 591 "--vs", default=DEFAULT_VS, help="vertex shader name in the carve index"
482 ) 592 )
483 ap.add_argument( 593 ap.add_argument(
484 "--ps", default=DEFAULT_PS, help="pixel shader name in the carve index" 594 "--ps", default=None, help="pixel shader name in the carve index (default untextured, or PS_Copy with --dds)"
595 )
596 ap.add_argument(
597 "--dds",
598 help="an exported DDS texture (e.g. BCPack-decoded TTPF albedo) to bind via set-0 T# and sampler S#",
485 ) 599 )
486 ap.add_argument("--width", type=int, default=128) 600 ap.add_argument("--width", type=int, default=128)
487 ap.add_argument("--height", type=int, default=128) 601 ap.add_argument("--height", type=int, default=128)
@@ -535,9 +649,12 @@ def main(argv=None) -> int:
535 game = os.path.abspath(os.path.expanduser(a.game)) 649 game = os.path.abspath(os.path.expanduser(a.game))
536 if not a.no_fit and not a.obj: 650 if not a.no_fit and not a.obj:
537 raise SystemExit("--obj is required unless --no-fit") 651 raise SystemExit("--obj is required unless --no-fit")
652 if a.dds and not a.obj:
653 raise SystemExit("--dds requires --obj so textured probes can be checked")
538 654
539 index = ensure_carve(game, work) 655 index = ensure_carve(game, work)
540 picked = choose(index, a.vs, a.ps) 656 ps_name = a.ps if a.ps is not None else (DEFAULT_TEXTURED_PS if a.dds else DEFAULT_PS)
657 picked = choose(index, a.vs, ps_name)
541 meta = translate(work, picked) 658 meta = translate(work, picked)
542 os.makedirs(out_dir, exist_ok=True) 659 os.makedirs(out_dir, exist_ok=True)
543 for entry in picked: 660 for entry in picked:
@@ -582,6 +699,7 @@ def main(argv=None) -> int:
582 "ps": { 699 "ps": {
583 "name": picked[1]["name"], 700 "name": picked[1]["name"],
584 "fssm_sha256": meta["ps"].get("fssm_sha256"), 701 "fssm_sha256": meta["ps"].get("fssm_sha256"),
702 "subgroup_size": meta["ps"].get("subgroup_size"),
585 "verified": True, 703 "verified": True,
586 }, 704 },
587 "vertex_count": len(vertices), 705 "vertex_count": len(vertices),
@@ -606,12 +724,51 @@ def main(argv=None) -> int:
606 "index": "index.json", 724 "index": "index.json",
607 }, 725 },
608 } 726 }
727 if a.dds:
728 tw, th, rgba, dds_sha = decode_dds_to_rgba(a.dds)
729 write_texture_rgba(os.path.join(out_dir, "texture.rgba"), tw, th, rgba)
730 ps_meta = meta["ps"]
731 ptr_sgpr = next(
732 (
733 int(r["sgpr"])
734 for r in (ps_meta.get("user_sgpr_reads") or [])
735 if r.get("kind") in ("ptr32_lo", "ptr64_lo")
736 ),
737 DEFAULT_PTR_SGPR,
738 )
739 lit_samplers = ps_meta.get("literal_samplers") or []
740 ssharp = list(lit_samplers[0]) if lit_samplers else list(DEFAULT_SSHARP)
741 manifest["texture"] = {
742 "width": tw,
743 "height": th,
744 "dds_sha256": dds_sha,
745 "ptr_sgpr": ptr_sgpr,
746 "tsharp_va": DEFAULT_TSHARP_VA,
747 "ssharp": ssharp,
748 }
749 manifest["files"]["texture"] = "texture.rgba"
750 manifest["rgba_tolerance"] = 0.02
751 if centre_uv is not None:
752 manifest["centre_rgba"] = sample_rgba_bilinear(
753 tw, th, rgba, centre_uv[0], centre_uv[1]
754 )
755 if probes:
756 manifest["rgba_probes"] = [
757 {
758 "pixel": p["pixel"],
759 "uv": p["uv"],
760 "rgba": sample_rgba_bilinear(tw, th, rgba, p["uv"][0], p["uv"][1]),
761 }
762 for p in probes
763 ]
609 with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: 764 with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f:
610 json.dump(manifest, f, indent=1) 765 json.dump(manifest, f, indent=1)
611 print(f"{len(vertices)} vertices, {len(indices) // 3} triangles -> {out_dir}") 766 print(f"{len(vertices)} vertices, {len(indices) // 3} triangles -> {out_dir}")
612 if not (a.run or a.check): 767 if not (a.run or a.check):
768 env_preview = harness_env(manifest, out_dir, base_env={})
769 env_str = " ".join(f"{k}={v}" for k, v in env_preview.items())
613 print( 770 print(
614 f"run: VKH_DRAW_MESH={os.path.join(out_dir, 'mesh.bin')} VKH_VERTEX_LAYOUT=0:3f,1:2f " 771 f"run: {env_str} "
615 f"<vk_harness> {os.path.join(out_dir, 'vs.spv')} {os.path.join(out_dir, 'ps.spv')} " 772 f"<vk_harness> {os.path.join(out_dir, 'vs.spv')} {os.path.join(out_dir, 'ps.spv')} "
616 f"{os.path.join(out_dir, 'image.raw')} {a.width} {a.height}" 773 f"{os.path.join(out_dir, 'image.raw')} {a.width} {a.height}"
617 ) 774 )