"""The render kit installs a self-contained module and a pinned PBR library into a candidate.""" import hashlib import json import re import shutil import subprocess from pathlib import Path import pytest from bench_builder import render_kit as rk from bench_builder import workflow_features as wf from bench_builder.harness_plugins import get_harness_plugin _IMPORT = re.compile(r"""^\s*(?:import|export)\s[^'"]*?from\s+['"]([^'"]+)['"]""", re.M) TOOLCHAIN_THREE = sorted(Path(__file__).resolve().parents[1].glob("runs/agent-toolchain/*/node_modules/three")) def _library(tmp_path: Path) -> tuple[dict, Path]: """A two-material, one-environment library whose files live in a cache under tmp_path.""" cache = tmp_path / "cache" files = {} def add(relative: str, data: bytes) -> dict: (cache / relative).parent.mkdir(parents=True, exist_ok=True) (cache / relative).write_bytes(data) info = {"url": f"https://example.invalid/{relative}", "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)} files[relative] = info return info stone = {kind: f"pbr/textures/stone/stone_{kind}_1k.jpg" for kind in ("diff", "nor_gl", "rough")} for path in stone.values(): add(path, path.encode()) # The second set's normal map is not in the cache, so the set is incomplete. wood = {"diff": "pbr/textures/wood/wood_diff_1k.jpg", "nor_gl": "pbr/textures/wood/wood_nor_gl_1k.jpg"} add(wood["diff"], b"wood") files[wood["nor_gl"]] = {"url": "https://example.invalid/missing", "sha256": "0" * 64, "bytes": 1} sky = add("pbr/hdri/sky_2k.hdr", b"#?RADIANCE") library = { "schema": "gamedevbench.pbr-library.v1", "source": "test", "license": "CC0-1.0", "materials": { "stone": {"use": "stone floor", "maps": stone, "files": {p: files[p] for p in stone.values()}}, "wood": {"use": "wood", "maps": wood, "files": {p: files[p] for p in wood.values()}}, }, "environments": {"sky": {"use": "daylight", "hdr": "pbr/hdri/sky_2k.hdr", **sky}}, } return library, cache def _candidate(tmp_path: Path, *, revision: str | None = "185", node_modules: bool = False) -> Path: candidate = tmp_path / "candidate" candidate.mkdir() if revision: (candidate / "lib").mkdir() (candidate / "lib" / "three.core.js").write_text(f"const REVISION = '{revision}';\n") (candidate / "lib" / "three.module.js").write_text("export * from './three.core.js';\n") if node_modules: build = candidate / "node_modules" / "three" / "build" build.mkdir(parents=True) (build / "three.module.js").write_text("export const REVISION = '185';\n") (build / "three.core.js").write_text("const REVISION = '185';\n") return candidate @pytest.fixture def library(tmp_path, monkeypatch): data, cache = _library(tmp_path) monkeypatch.setattr(rk, "load_library", lambda: data) return data, cache def _offline(url): raise OSError("offline") def test_install_copies_the_kit_points_its_shim_at_the_game_and_lists_complete_sets(tmp_path, library): _, cache = library candidate = _candidate(tmp_path) report = rk.install(candidate, cache=cache, download=_offline) kit = candidate / "lib" / "render-kit" assert (kit / "render-kit.js").is_file() and (kit / "README.md").is_file() assert "export * from '../three.module.js';" in (kit / "three.js").read_text() assert report.three_revision == "185" and not report.notes assert report.materials == ["stone"] and report.environments == ["sky"] assert report.missing == ["pbr/textures/wood/wood_nor_gl_1k.jpg"] listed = json.loads((candidate / "assets" / "pbr" / "library.json").read_text()) assert set(listed["materials"]) == {"stone"} and listed["license"] == "CC0-1.0" assert "url" not in json.dumps(listed) # the game gets paths only assert (candidate / "assets" / "pbr" / "textures" / "stone" / "stone_diff_1k.jpg").is_file() def test_every_kit_import_resolves_after_install(tmp_path, library): _, cache = library candidate = _candidate(tmp_path) rk.install(candidate, cache=cache, download=_offline) kit = candidate / "lib" / "render-kit" for module in kit.rglob("*.js"): for specifier in _IMPORT.findall(module.read_text()): assert specifier.startswith("."), f"{module.name} imports bare {specifier}" assert (module.parent / specifier).resolve().is_file(), f"{module.name} -> {specifier}" def test_continue_preserves_candidate_materials_and_their_licenses(tmp_path, library): _, cache = library candidate = _candidate(tmp_path) rk.install(candidate, cache=cache, download=_offline) manifest = candidate / "assets/pbr/library.json" data = json.loads(manifest.read_text()) custom = {"use": "hero wall", "maps": {"diff": "custom/hero.jpg"}, "license": "CC-BY-4.0"} data["materials"]["hero_wall"] = custom manifest.write_text(json.dumps(data)) report = rk.install(candidate, cache=cache, download=_offline) assert "stone" in rk.builder_instructions(report) data = json.loads(manifest.read_text()) assert data["materials"]["hero_wall"] == custom assert data["materials"]["stone"]["license"] == "CC0-1.0" assert data["license"] != "CC0-1.0" def test_reinstall_is_idempotent_and_replaces_edits_to_the_kit(tmp_path, library): _, cache = library candidate = _candidate(tmp_path) rk.install(candidate, cache=cache, download=_offline) (candidate / "lib" / "render-kit" / "render-kit.js").write_text("edited") shutil.rmtree(cache) # assets already in the candidate are kept and verified report = rk.install(candidate, cache=cache, download=_offline) assert (candidate / "lib" / "render-kit" / "render-kit.js").read_text() != "edited" assert report.materials == ["stone"] and report.environments == ["sky"] def test_three_is_vendored_from_node_modules_when_the_game_has_none(tmp_path, library): _, cache = library candidate = _candidate(tmp_path, revision=None, node_modules=True) report = rk.install(candidate, cache=cache, download=_offline) assert (candidate / "lib" / "three.module.js").is_file() assert any("lib/three.module.js" in note for note in report.notes) bare = tmp_path / "bare" bare.mkdir() (bare / "candidate").mkdir() with pytest.raises(rk.RenderKitError, match="no three.js"): rk.install(bare / "candidate", cache=cache, download=_offline) def test_a_different_three_release_is_reported(tmp_path, library): _, cache = library report = rk.install(_candidate(tmp_path, revision="170"), cache=cache, download=_offline) assert any("r170" in note for note in report.notes) def test_fetch_keeps_only_files_whose_checksum_matches(tmp_path, library): data, _ = library cache = tmp_path / "fresh" payload = {info["url"]: relative.encode() for relative, info in rk.library_files(data).items()} payload["https://example.invalid/pbr/textures/wood/wood_diff_1k.jpg"] = b"wood" result = rk.fetch(cache, download=lambda url: payload.get(url, b"wrong")) assert (cache / "pbr/textures/stone/stone_diff_1k.jpg").is_file() assert any("checksum mismatch" in failure for failure in result["failed"]) assert not (cache / "pbr/textures/wood/wood_nor_gl_1k.jpg").exists() def test_prepare_appends_instructions_naming_the_installed_sets(tmp_path, library): _, cache = library prompt = rk.prepare_render_kit("Build it.", candidate=_candidate(tmp_path), cache=cache) assert prompt.startswith("Build it.") assert "## Render kit" in prompt and "`stone`: stone floor" in prompt and "`sky`: daylight" in prompt assert "`wood`" not in prompt and "could not be fetched" in prompt def test_the_feature_is_a_builder_switch(): assert wf.normalize_features(["render_kit"], stage="builder") == ("render_kit",) assert wf.builder_options({"agent": "claude"}, ["render_kit"]) == {"agent": "claude", "render_kit": "on"} plugin = get_harness_plugin("acpx") assert plugin.validate_options({"agent": "claude", "render_kit": "on"})["render_kit"] == "on" with pytest.raises(Exception, match="on or off"): plugin.validate_options({"agent": "claude", "render_kit": "maybe"}) def test_the_shipped_library_pins_every_file(): library = json.loads(rk.LIBRARY_PATH.read_text()) files = rk.library_files(library) assert library["license"] == "CC0-1.0" and len(library["materials"]) >= 10 and library["environments"] for relative, info in files.items(): assert relative.startswith("pbr/") and re.fullmatch(r"[0-9a-f]{64}", info["sha256"]) assert info["url"].startswith("https://dl.polyhaven.org/") for entry in library["materials"].values(): assert {"diff", "nor_gl", "rough"} <= set(entry["maps"]) @pytest.mark.skipif(not TOOLCHAIN_THREE or shutil.which("node") is None, reason="needs node and the agent toolchain") def test_the_kit_module_graph_loads_with_real_three(tmp_path, library): _, cache = library candidate = _candidate(tmp_path, revision=None, node_modules=False) shutil.copytree(TOOLCHAIN_THREE[-1], candidate / "node_modules" / "three") rk.install(candidate, cache=cache, download=_offline) script = ("const kit = await import('./lib/render-kit/render-kit.js');" "if (typeof kit.createRenderKit !== 'function' || !kit.QUALITY.high) throw new Error('exports');" "if (kit.qualityFromQuery('?render=low') !== 'low') throw new Error('query');" "kit.RenderKit.prototype._loadLibrary = async function() {};" "const renderer = {capabilities:{getMaxAnisotropy:()=>1}," "getContext:()=>({getExtension:()=>null, getParameter:()=> 'SwiftShader'})};" "const auto = new kit.RenderKit({renderer,scene:{},camera:{},width:1280,height:720," "quality:'auto',tune:{enabled:false}});" "await auto.ready;" "if(auto.quality !== 'high') throw new Error('software silently reduced quality');" "let decoded=0,closed=0; globalThis.createImageBitmap=async()=>{decoded++;return{width:1,height:1,close(){closed++;}}};" "Object.assign(renderer,{shadowMap:{},getPixelRatio:()=>1,getSize:v=>v.set(1280,720),setPixelRatio(){},setSize(){}});" "const ultra = new kit.RenderKit({renderer,scene:new kit.THREE.Scene(),camera:new kit.THREE.PerspectiveCamera()," "width:1280,height:720,quality:'ultra',ao:false,bloom:false,environment:null});" "await ultra.ready;" "if(decoded!==2 || !ultra.smaaPass._areaTexture.image) throw new Error('SMAA lookup readiness');" "if(ultra.composer.passes.indexOf(ultra.smaaPass)>ultra.composer.passes.indexOf(ultra.outputPass)) throw new Error('SMAA color space order');" "ultra.dispose(); if(closed!==2) throw new Error('SMAA bitmap leak');" "console.log('ok');") result = subprocess.run(["node", "--input-type=module", "-e", script], cwd=candidate, capture_output=True, text=True, timeout=60) assert result.returncode == 0, result.stderr assert result.stdout.strip() == "ok" def test_install_spatial_ships_the_helpers_without_the_pbr_library_and_keeps_a_full_kit(tmp_path, library): _, cache = library candidate = _candidate(tmp_path) spatial = rk.install_spatial(candidate) kit = candidate / "lib" / "render-kit" assert spatial == kit / "spatial.js" and spatial.is_file() assert "export * from '../three.module.js';" in (kit / "three.js").read_text() assert not (kit / "render-kit.js").exists() and not (candidate / "assets").exists() for specifier in _IMPORT.findall(spatial.read_text()): assert (kit / specifier).resolve().is_file(), specifier spatial.write_text("edited") rk.install_spatial(candidate) # idempotent, refreshes edits assert spatial.read_text() == (rk.WEB_ROOT / "spatial.js").read_text() rk.install(candidate, cache=cache, download=_offline) # the full kit ships spatial.js too assert (kit / "spatial.js").is_file() rk.install_spatial(candidate) # and a later spatial install leaves the full kit in place assert (kit / "render-kit.js").is_file() and (kit / "jsm").is_dir() with pytest.raises(rk.RenderKitError, match="no three.js"): (tmp_path / "bare").mkdir() rk.install_spatial(tmp_path / "bare") _SPATIAL_SCRIPT = r""" const S = await import('./lib/render-kit/spatial.js'); const THREE = await import('./lib/three.module.js'); const out = {}; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(50, 16 / 9, 0.1, 2000); scene.add(camera); const car = new THREE.Mesh(new THREE.BoxGeometry(1.8, 1.4, 4.5)); car.position.set(0, 0.7, 0); scene.add(car); S.tagObject(car, 'sedan', 'sedan-00'); const ndc = (p) => p.clone().project(camera); S.placeShotCamera(camera, car, { hfov_deg: 60, height_m: 1.6, distance_m: 7.5, azimuth_deg: 0 }); out.behind = { position: camera.position.toArray(), distance: camera.position.distanceTo(car.position), centre: ndc(car.position).toArray() }; S.placeShotCamera(camera, car, { hfov_deg: 60, height_m: 1.6, distance_m: 7.5, azimuth_deg: 90 }); out.right = camera.position.toArray(); // A model authored facing +Z, turned to face +X: "behind" is then -X. const truck = new THREE.Object3D(); truck.position.set(20, 0, -10); truck.rotation.y = Math.PI / 2; S.placeShotCamera(camera, truck, { height_m: 2, distance_m: 5, azimuth_deg: 0 }, { subjectForward: new THREE.Vector3(0, 0, 1) }); out.truck = camera.position.toArray(); const probe = S.installSceneProbe({ camera, scene, getShot: () => 'shot-01' }); S.placeShotCamera(camera, car, { hfov_deg: 60, height_m: 1.6, distance_m: 7.5, azimuth_deg: 0, pitch_deg: 0 }); const cone = new THREE.Mesh(new THREE.BoxGeometry(0.5, 0.5, 0.5)); cone.position.set(0, 1, camera.position.z + 6); // behind the camera S.tagObject(cone, 'cone', 'cone-00'); scene.add(cone); out.level = globalThis.__gbbSceneProbe(); out.missing = S.installSceneProbe({ scene, target: null })(); for (let i = 0; i < 200; i += 1) { const extra = new THREE.Mesh(car.geometry); extra.position.set((i % 20) * 3 - 30, 0.7, -10 - Math.floor(i / 20) * 8); S.tagObject(extra, 'parked', `parked-${i}`); scene.add(extra); } probe(); const t0 = performance.now(); for (let i = 0; i < 50; i += 1) probe(); out.probe_ms = (performance.now() - t0) / 50; const road = S.buildRoad({ lanes: 4, lane_width_m: 3.5, shoulder_m: 1, sidewalk_m: 2, median: { kind: 'concrete_barrier', width_m: 0.8 }, elevated: true, length_m: 300 }); const box = new THREE.Box3().setFromObject(road); out.road = { width: box.max.x - box.min.x, zmin: box.min.z, zmax: box.max.z, ymin: box.min.y, userData: road.userData, names: road.children.map((c) => c.name) }; const curve = S.roadFrameAt({ curvature: 'gentle_right' }, 100); out.curve = { x: curve.position.x, heading: curve.heading_deg }; const frontage = S.buildFrontage([{ side: 'left', kind: 'towers', setback_m: 12, height_m: 60, spacing_m: 25 }], { road: { lanes: 4, lane_width_m: 3.5 }, length_m: 200 }); const fbox = new THREE.Box3().setFromObject(frontage); out.frontage = { xmax: fbox.max.x, ymax: fbox.max.y }; const cabin = S.buildCabin({ width_m: 1.45, length_m: 2.6, height_m: 1.15, seat_rows: 2, camera_mounts: [{ id: 'dash-left', x: -0.4, y: 1.1, z: -0.9, look_at: [0.3, 1.0, 0.4] }] }); const cbox = new THREE.Box3().setFromObject(cabin); const mount = cabin.getObjectByName('mount.dash-left'); const look = new THREE.Vector3(0, 0, -1).applyQuaternion(mount.quaternion); const want = new THREE.Vector3(0.7, -0.1, 1.3).normalize(); out.cabin = { size: cbox.getSize(new THREE.Vector3()).toArray(), aim: look.dot(want), mount: cabin.userData.mounts['dash-left'].position.toArray() }; // Rooms: a 4 x 10 m corridor joined to a 6 x 6 m room by a 1.2 m door in the corridor's north wall. const plan = { id: 'floor', rooms: [ { id: 'hall', x_m: 0, z_m: -5, width_m: 4, length_m: 10, height_m: 3 }, { id: 'flat', x_m: 0, z_m: -13, width_m: 6, length_m: 6, height_m: 2.8 }], openings: [{ id: 'door', kind: 'door', rooms: ['hall', 'flat'], x_m: 0, z_m: -10, width_m: 1.2, height_m: 2.1 }] }; const rooms = S.buildRooms(plan); const hall = new THREE.Box3().setFromObject(rooms.getObjectByName('room.hall.floor')); const walker = { x: 1.95, z: -5 }; const pushed = S.resolveWalls(rooms, walker, 0.35); const through = { x: 0, z: -10 }; out.rooms = { floor: hall.getSize(new THREE.Vector3()).toArray(), segments: rooms.userData.segments.length, north: rooms.userData.segments.filter((s) => s.room === 'hall' && Math.abs(s.z0 + 10) < 1e-6 && Math.abs(s.z1 + 10) < 1e-6) .map((s) => [s.x0, s.x1]), lintel: !!rooms.getObjectByName('room.hall').children.find((c) => c.name.startsWith('room.hall.wall.north') && Math.abs(c.position.y - 2.55) < 1e-6), pushed, walker: [walker.x, walker.z], door: S.resolveWalls(rooms, through, 0.35), at: [S.roomAt(plan, 0, -3), S.roomAt(plan, 2.5, -14), S.roomAt(plan, 9, 9)] }; const walkCam = new THREE.PerspectiveCamera(60, 16 / 9, 0.1, 100); walkCam.position.set(103, 1.7, 40); walkCam.rotation.set(0, -Math.PI / 2, 0, 'YXZ'); walkCam.updateMatrixWorld(true); const walkProbe = S.installSceneProbe({ camera: walkCam, scene: new THREE.Scene(), target: null, getPlace: () => ({ id: 'floor', origin: [100, 0, 40], yaw_deg: 90 }) }); out.place = walkProbe(); const rig = { subject: 'sedan', distance_m: 8, azimuth_deg: 350, keyframes: [{ t: 12, azimuth_deg: 10 }, { t: 14, distance_m: 4 }] }; out.rig = [S.rigAt(rig, 11, { start: 10 }), S.rigAt(rig, 13), S.rigAt(rig, 20), S.rigAt(rig, 5)]; out.topdown = S.captureTopDown({ domElement: {} }, scene, {}); console.log(JSON.stringify(out)); """ @pytest.mark.skipif(not TOOLCHAIN_THREE or shutil.which("node") is None, reason="needs node and the agent toolchain") def test_spatial_helpers_place_cameras_probe_the_scene_and_build_places_to_size(tmp_path): candidate = _candidate(tmp_path, revision=None) build = candidate / "node_modules" / "three" / "build" build.mkdir(parents=True) for name in ("three.module.js", "three.core.js"): shutil.copy2(TOOLCHAIN_THREE[-1] / "build" / name, build / name) rk.install_spatial(candidate) result = subprocess.run(["node", "--input-type=module", "-e", _SPATIAL_SCRIPT], cwd=candidate, capture_output=True, text=True, timeout=60) assert result.returncode == 0, result.stderr out = json.loads(result.stdout) approx = lambda value, tol=1e-3: pytest.approx(value, abs=tol) # noqa: E731 # Behind a -Z-facing subject is +Z; height is absolute, the 3D distance is the rig's. x, y, z = out["behind"]["position"] assert x == approx(0) and y == approx(1.6) and z > 7 and out["behind"]["distance"] == approx(7.5) cx, cy, _ = out["behind"]["centre"] assert abs(cx) < 0.01 and abs(cy) < 0.01 # the subject projects at the screen centre assert out["right"][0] == approx(7.5 * (1 - (0.9 / 7.5) ** 2) ** 0.5) and out["right"][2] == approx(0) assert out["truck"][0] < 20 and out["truck"][2] == approx(-10) and out["truck"][1] == approx(2) level = out["level"] assert level["shot"] == "shot-01" assert level["camera"]["hfov_deg"] == approx(60, 0.01) and level["camera"]["height_m"] == approx(1.6) assert level["camera"]["pitch_deg"] == approx(0) and level["camera"]["yaw_deg"] == approx(0) assert level["camera"]["horizon_y"] == approx(0.5) assert [o["instance_id"] for o in level["objects"]] == ["sedan-00"] # the cone behind is omitted x0, y0, x1, y1 = level["objects"][0]["box"] assert x0 < 0.5 < x1 and 0.5 < y1 <= 1 and level["objects"][0]["distance_m"] == approx(7.45, 0.1) assert "error" in out["missing"] assert out["probe_ms"] < 2 road = out["road"] assert road["width"] == approx(4 * 3.5 + 2 * 1 + 0.8 + 2 * 2) and road["userData"]["width_m"] == approx(20.8) assert road["userData"]["lanes"] == [approx(v) for v in (-5.65, -2.15, 2.15, 5.65)] assert road["zmax"] == approx(0) and road["zmin"] == approx(-300, 0.01) and road["ymin"] == approx(-8) assert {"road.asphalt", "road.markings.dashed", "road.median.barrier", "road.deck", "road.piers", "road.railing.left", "road.sidewalk.right"} <= set(road["names"]) assert out["curve"]["x"] > 5 and out["curve"]["heading"] == approx(100 / 500 * 57.29578, 0.01) assert out["frontage"]["xmax"] == approx(-(7 + 12)) # road edge 7 m + 12 m setback to the front face assert out["frontage"]["ymax"] <= 60 * 1.2 + 1e-3 # Rooms are built to the contract's size; the door is a gap in the wall with a lintel above it. rooms = out["rooms"] assert rooms["floor"] == [approx(4), approx(0.1), approx(10)] and rooms["lintel"] assert sorted(map(sorted, rooms["north"])) == [[approx(-2), approx(-0.6)], [approx(0.6), approx(2)]] assert rooms["pushed"] and rooms["walker"][0] == approx(1.65) and not rooms["door"] assert rooms["at"] == ["hall", "flat", None] # A place whose -Z axis points along world +X: 3 m along world +X is 3 m forward (z -3), facing ahead. place = out["place"]["camera"]["place"] assert out["place"]["shot"] == "floor" and place["id"] == "floor" assert place["x_m"] == approx(0) and place["z_m"] == approx(-3) and place["yaw_deg"] == approx(0) w, h, l = out["cabin"]["size"] assert w == approx(1.45 + 0.08, 0.01) and h == approx(1.15 + 0.08, 0.01) and l == approx(2.6 + 0.08, 0.01) assert out["cabin"]["aim"] == approx(1) and out["cabin"]["mount"] == [-0.4, 1.1, -0.9] before, between, after, early = out["rig"] assert before["azimuth_deg"] == approx(0) and before["subject"] == "sedan" and "keyframes" not in before assert between["distance_m"] == approx(6) and between["azimuth_deg"] == approx(10) assert after["distance_m"] == 4 and early["azimuth_deg"] == 350 assert out["topdown"] is None