File size: 17,364 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""Render kit: a physically based rendering module and CC0 PBR library for browser builds.

The ``render_kit`` builder feature installs ``web/`` into the candidate as ``lib/render-kit/``
(the kit plus the three.js postprocessing addons it uses, rewritten to import the game's own
three.js through a one-line ``three.js`` shim), copies the PBR texture library into
``assets/pbr/`` and tells the builder how to use it.

The library's images are not in the repository. ``library.json`` pins every file by URL and
SHA-256; they are fetched once into a local cache (``fetch`` below, or automatically on install).

    uv run python -m bench_builder.render_kit fetch
    uv run python -m bench_builder.render_kit install PATH/TO/candidate
"""

from __future__ import annotations

import hashlib
import json
import os
import re
import shutil
import ssl
import sys
import urllib.request
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

PACKAGE_ROOT = Path(__file__).resolve().parent
WEB_ROOT = PACKAGE_ROOT / "web"
LIBRARY_PATH = PACKAGE_ROOT / "library.json"
DEFAULT_CACHE = PACKAGE_ROOT.parents[1] / "runs" / "asset-library" / "pbr-library"
KIT_RELATIVE = Path("lib") / "render-kit"
ASSETS_RELATIVE = Path("assets")
_USER_AGENT = "gamedev-bench-render-kit"
_REVISION = re.compile(r"REVISION\s*=\s*['\"](\d+)")


class RenderKitError(RuntimeError):
    """The render kit could not be installed."""


@dataclass
class InstallReport:
    kit_dir: Path
    three: str            # where the shim points, relative to lib/render-kit
    three_revision: str   # the game's three.js REVISION, "" when unknown
    addons_revision: str  # the REVISION the vendored addons came from
    materials: list[str] = field(default_factory=list)
    environments: list[str] = field(default_factory=list)
    missing: list[str] = field(default_factory=list)  # library files neither cached nor fetched
    notes: list[str] = field(default_factory=list)


def load_library() -> dict[str, Any]:
    return json.loads(LIBRARY_PATH.read_text(encoding="utf-8"))


def cache_root() -> Path:
    override = os.environ.get("GAMEDEVBENCH_PBR_CACHE")
    return Path(override).expanduser() if override else DEFAULT_CACHE


def library_files(library: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]:
    """Every library file by its path under ``assets/`` -> {url, sha256, bytes}."""
    library = library or load_library()
    files: dict[str, dict[str, Any]] = {}
    for entry in library["materials"].values():
        files.update(entry["files"])
    for entry in library["environments"].values():
        files[entry["hdr"]] = {key: entry[key] for key in ("url", "sha256", "bytes")}
    return files


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1 << 20), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _download(url: str) -> bytes:
    try:
        import certifi

        context = ssl.create_default_context(cafile=certifi.where())
    except ImportError:  # pragma: no cover - certifi ships with the project's dependencies
        context = ssl.create_default_context()
    request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
    with urllib.request.urlopen(request, timeout=60, context=context) as response:
        return response.read()


def fetch(cache: Path | None = None, *, download: Callable[[str], bytes] = _download) -> dict[str, list[str]]:
    """Fill the cache from the pinned URLs; a file whose hash differs is refetched."""
    root = cache or cache_root()
    fetched, failed = [], []
    for relative, info in library_files().items():
        target = root / relative
        if target.is_file() and _sha256(target) == info["sha256"]:
            continue
        try:
            data = download(info["url"])
        except OSError as exc:
            failed.append(f"{relative}: {exc}")
            continue
        if hashlib.sha256(data).hexdigest() != info["sha256"]:
            failed.append(f"{relative}: checksum mismatch")
            continue
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_bytes(data)
        fetched.append(relative)
    return {"fetched": fetched, "failed": failed}


def _three_revision(path: Path) -> str:
    try:
        match = _REVISION.search(path.read_text(encoding="utf-8", errors="replace"))
    except OSError:
        return ""
    return match.group(1) if match else ""


def _install_three(candidate: Path, report_notes: list[str]) -> tuple[str, str]:
    """Point the kit at the game's three.js; vendor the toolchain's copy into lib/ if absent."""
    lib = candidate / "lib"
    if not (lib / "three.module.js").is_file():
        build = candidate / "node_modules" / "three" / "build"
        if (build / "three.module.js").is_file():
            lib.mkdir(parents=True, exist_ok=True)
            for name in ("three.module.js", "three.core.js"):
                if (build / name).is_file():
                    shutil.copy2(build / name, lib / name)
            report_notes.append("Copied three.js into lib/ (lib/three.module.js); import it from there.")
        else:
            raise RenderKitError("no three.js in lib/ or node_modules/three to point the render kit at")
    revision = _three_revision(lib / "three.core.js") or _three_revision(lib / "three.module.js")
    return "../three.module.js", revision


def _write_three_shim(kit_dir: Path, three_path: str) -> None:
    (kit_dir / "three.js").write_text(
        "// Generated by the render kit installer: the game's own three.js, so the kit and the game\n"
        "// share one module instance. Change this line only if the game moves its three.js.\n"
        f"export * from '{three_path}';\n",
        encoding="utf-8",
    )


def install_spatial(candidate: Path) -> Path:
    """Install only ``spatial.js`` (and the three.js shim it imports) into ``lib/render-kit/``.

    Video builds get the spatial helpers and scene probe even when the ``render_kit`` feature (the
    PBR library and postprocessing) is off. Other files in the folder are left alone, so this is
    idempotent and safe before or after a full ``install`` (which also ships ``spatial.js``).
    Returns the installed ``spatial.js``.
    """
    candidate = candidate.resolve()
    if not candidate.is_dir():
        raise RenderKitError(f"candidate does not exist: {candidate}")
    kit_dir = candidate / KIT_RELATIVE
    if kit_dir.is_symlink():
        raise RenderKitError("lib/render-kit must not be a link")
    three_path, _ = _install_three(candidate, [])
    kit_dir.mkdir(parents=True, exist_ok=True)
    shutil.copy2(WEB_ROOT / "spatial.js", kit_dir / "spatial.js")
    _write_three_shim(kit_dir, three_path)
    if not (kit_dir / "README.md").is_file():
        shutil.copy2(WEB_ROOT / "README.md", kit_dir / "README.md")
    return kit_dir / "spatial.js"


def install(candidate: Path, *, cache: Path | None = None, allow_fetch: bool = True,
            download: Callable[[str], bytes] = _download) -> InstallReport:
    """Install (or refresh, on Continue) the kit and the PBR library into ``candidate``."""
    candidate = candidate.resolve()
    if not candidate.is_dir():
        raise RenderKitError(f"candidate does not exist: {candidate}")
    kit_dir = candidate / KIT_RELATIVE
    if kit_dir.is_symlink():
        raise RenderKitError("lib/render-kit must not be a link")
    if kit_dir.exists():
        shutil.rmtree(kit_dir)
    shutil.copytree(WEB_ROOT, kit_dir)
    notes: list[str] = []
    three_path, revision = _install_three(candidate, notes)
    _write_three_shim(kit_dir, three_path)
    addons_revision = json.loads((WEB_ROOT / "jsm" / "VERSION.json").read_text(encoding="utf-8"))["three"]
    if revision and not addons_revision.startswith(f"0.{revision}."):
        notes.append(f"The game's three.js is r{revision} but the kit's addons come from {addons_revision}; "
                     "keep them on the same release.")

    library = load_library()
    root = cache or cache_root()
    if allow_fetch:
        fetch(root, download=download)
    assets = candidate / ASSETS_RELATIVE
    available: set[str] = set()
    missing: list[str] = []
    for relative, info in library_files(library).items():
        source, target = root / relative, assets / relative
        if target.is_file() and _sha256(target) == info["sha256"]:
            available.add(relative)
        elif source.is_file() and _sha256(source) == info["sha256"]:
            target.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(source, target)
            available.add(relative)
        else:
            missing.append(relative)
    materials = {
        name: {"use": entry["use"], "maps": entry["maps"]}
        for name, entry in library["materials"].items()
        if all(path in available for path in entry["maps"].values())
    }
    environments = {
        name: {"use": entry["use"], "hdr": entry["hdr"]}
        for name, entry in library["environments"].items()
        if entry["hdr"] in available
    }
    # Continue refreshes managed assets, but must retain a game's additional library entries.
    # Keep their individual license metadata instead of relabelling them as library CC0 assets.
    manifest = assets / "pbr" / "library.json"
    existing = json.loads(manifest.read_text(encoding="utf-8")) if manifest.is_file() else {}
    custom = False
    for category, entries in (("materials", materials), ("environments", environments)):
        for name, entry in existing.get(category, {}).items():
            if name not in library[category]:
                entries[name] = entry
                custom = True
    if custom:
        notes.append("Preserved candidate-defined library entries and their license metadata.")
        for category, entries in (("materials", materials), ("environments", environments)):
            for name in library[category]:
                if name in entries:
                    entries[name]["license"] = library["license"]
    (assets / "pbr").mkdir(parents=True, exist_ok=True)
    manifest.write_text(json.dumps({
        "schema": library["schema"], "source": library["source"],
        "license": "See per-entry licenses" if custom else library["license"],
        "materials": materials, "environments": environments,
    }, indent=1) + "\n", encoding="utf-8")
    return InstallReport(kit_dir=kit_dir, three=three_path, three_revision=revision,
                         addons_revision=addons_revision,
                         materials=sorted(set(materials) & library["materials"].keys()),
                         environments=sorted(set(environments) & library["environments"].keys()),
                         missing=missing, notes=notes)


def builder_instructions(report: InstallReport) -> str:
    library = load_library()
    materials = "\n".join(f"  - `{name}`: {library['materials'][name]['use']}" for name in report.materials)
    environments = "\n".join(f"  - `{name}`: {library['environments'][name]['use']}" for name in report.environments)
    notes = "".join(f"\n- {note}" for note in report.notes)
    missing = (f"\n- {len(report.missing)} library files could not be fetched; `assets/pbr/library.json` "
               "lists only the complete sets." if report.missing else "")
    return f"""

## Render kit (physically based look)

The host installed `lib/render-kit/render-kit.js` (read `lib/render-kit/README.md`) and a CC0 texture
library in `assets/pbr/`. Select components that address a demonstrated visual gap: image-based
lighting, tone mapping, ambient occlusion, restrained bloom, anti-aliasing or PBR texture sets
with world-scale UVs. Full composer adoption is not an acceptance requirement. Existing rendering
may be retained when matched evidence is stronger; individual library textures can also be used
with the existing renderer. The kit works on the main thread and in a worker (no DOM use).

```js
import {{ createRenderKit, qualityFromQuery }} from '../lib/render-kit/render-kit.js';
const kit = await createRenderKit({{
  renderer, scene, camera, width, height, maxPixelRatio: devicePixelRatio,
  assetBase: new URL('../assets/', import.meta.url).href,
  quality: qualityFromQuery(location.search),   // ?render=auto|off|low|medium|high|ultra, default auto
  environment: '<environment id>',               // lighting only; the game's sky stays the background
}});
kit.standardize(scene);                          // Lambert/Phong -> MeshStandardMaterial
wall.material = kit.pbr('<material id>', {{ tileMeters: 3, tint: 0xd8cdb8 }});
kit.worldUV(wall);                               // constant texel size on boxes of any scale
kit.configureSun(sun, {{ extent: 60 }});          // then kit.followSun(sun, player.position) per frame
kit.addOverlay(viewmodelScene, viewmodelCamera); // first-person weapon or markers drawn after AO
// frame: kit.render(dt)   resize: kit.setSize(w, h, devicePixelRatio)   camera swap: kit.setCamera(c)
```

- Materials (`assets/pbr/textures`, 1k, colour/normal/roughness/AO):
{materials}
- Environments (`assets/pbr/hdri`):
{environments}
- In a worker, send the page's `location.search` and `devicePixelRatio` with the canvas and pass them
  to `qualityFromQuery` and `maxPixelRatio`.
- Match the reference, not a generic look: tint albedo to each surface's colour, set `exposure` and
  `environmentIntensity` so matched frames read with the same brightness, keep AO and bloom subtle.
  Keep an existing colour grade with `lut: '<url>.cube'` (applied after tone mapping).
- `auto` preserves the same high profile on desktop and software rendering. First measure a short
  isolated trial at the existing viewport and drawing-buffer resolution. If software rendering
  cannot sustain it, retain the verified playable and investigate performance or the replay backend;
  do not lower quality to pass. An explicitly selected low profile is a separate diagnostic result,
  never evidence that the high profile passed. Record backend, resolved profile and resolution.
- The environment is the ambient light: lower or remove existing hemisphere/ambient lights.
- Before retrying a rejected integration, read its checkpoint and identify a changed cause
  (for example a measured bottleneck fix or a separately labelled backend experiment). Do not
  repeat the same chain after session rollover. Correct route, camera and major scene geometry
  before treating postprocessing as the solution to composition errors.
- Compare a frozen pre-integration build with the trial at matched timestamps before keeping a change.
  `?render=off` alone is not the original look if integration also changes materials, UVs or lights.
  Preserve authored GLB materials and UVs; apply library materials to selected procedural surfaces.
  After integrating, run one full replay and check that max input lateness and
  dark-frame counts are no worse than before.
- `lib/render-kit/` is reinstalled on every build round: configure it through options, do not edit
  its files. Record any texture you add yourself in `assets/pbr/library.json` with its licence.{notes}{missing}

### Matching the reference's look: fitted, not hand-tuned

`lib/render-kit/look.js` (`createLook`, same options as `createRenderKit` plus `look: 'look.json'`) keeps
sun direction, sky, haze, exposure, grade and every surface's colour, roughness, dirt and wetness in one
parameter object. You make the discrete choices: indoors or outdoors (`sky.mode`), and what each surface
is (`look.surface('road', {{ type: 'asphalt', color }})`, or `look.adopt(scene)` for the rest). Then
`mcp__reference_replay__look_fit` finds the numbers: it renders your build from a replay's camera poses,
compares with the reference at the same moments and searches the parameters until the frames agree,
writing `look.json` and a reference/before/after sheet. Do not spend turns nudging light colours,
exposure or material tints by eye: get geometry and surface types right, run `look_fit`, replay, read the
scorecard's `look`. The defaults add no haze, grain or dirt, so nothing appears that the reference does
not show. Details and the parameter list: the look section of `lib/render-kit/README.md`.
"""


def prepare_render_kit(prompt: str, *, candidate: Path, cache: Path | None = None) -> str:
    """Install the kit for a build round and append its instructions to the builder prompt."""
    return prompt + builder_instructions(install(candidate, cache=cache))


def _main(argv: list[str]) -> int:
    if argv[:1] == ["fetch"]:
        result = fetch()
        print(json.dumps({"fetched": len(result["fetched"]), "failed": result["failed"]}, indent=1))
        return 1 if result["failed"] else 0
    if len(argv) == 2 and argv[0] == "install":
        report = install(Path(argv[1]))
        print(json.dumps({"kit": str(report.kit_dir), "three": report.three, "revision": report.three_revision,
                          "materials": len(report.materials), "environments": len(report.environments),
                          "missing": report.missing, "notes": report.notes}, indent=1))
        return 0
    print(__doc__)
    return 2


if __name__ == "__main__":
    raise SystemExit(_main(sys.argv[1:]))