vibedgames 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +3 -2
  2. package/assets/align-framing.py +242 -0
  3. package/assets/render-model.py +406 -0
  4. package/assets/tilemap-editor.html +630 -0
  5. package/dist/THIRD_PARTY_NOTICES.txt +2 -2
  6. package/dist/{chunk-56OY4TEP.js → chunk-2SBBKY5C.js} +1361 -4493
  7. package/dist/{chunk-FC233UKH.js → chunk-2ZKS7V72.js} +16 -16
  8. package/dist/chunk-37LLKM73.js +124 -0
  9. package/dist/{chunk-BMTHAVMS.js → chunk-3HGBIUM5.js} +22 -19
  10. package/dist/chunk-3UGGMFJJ.js +22 -0
  11. package/dist/{chunk-3HUWAJQH.js → chunk-42K3BJJH.js} +93 -76
  12. package/dist/{chunk-ST5FC2W3.js → chunk-43P4U7CB.js} +20 -11
  13. package/dist/chunk-4RYTTD4D.js +53 -0
  14. package/dist/{chunk-WSRIF6K4.js → chunk-4UU622RK.js} +5 -4
  15. package/dist/chunk-52E6EKZV.js +72 -0
  16. package/dist/chunk-6IUFHPMV.js +62 -0
  17. package/dist/chunk-6KXXZXSO.js +475 -0
  18. package/dist/chunk-72KHWZMN.js +87 -0
  19. package/dist/{chunk-ZCYWDKYP.js → chunk-A556KALN.js} +14 -13
  20. package/dist/{chunk-UFR6G6BL.js → chunk-ABTUEIRC.js} +554 -254
  21. package/dist/chunk-ALPTHSUT.js +132 -0
  22. package/dist/{chunk-PEUP4MZR.js → chunk-AWJNAGPE.js} +6 -3
  23. package/dist/chunk-BJAN3RMY.js +48 -0
  24. package/dist/{chunk-HNRVSBRK.js → chunk-BN3Q7UEC.js} +20 -17
  25. package/dist/chunk-BZOMEG3X.js +412 -0
  26. package/dist/{chunk-ZYCSYJWX.js → chunk-COSLGSVO.js} +14 -24
  27. package/dist/{chunk-KZBZNTM4.js → chunk-CTY2WZQK.js} +9 -13
  28. package/dist/chunk-DH6WPL3X.js +47 -0
  29. package/dist/chunk-DPLFCKXP.js +80 -0
  30. package/dist/{chunk-K2U7L4RU.js → chunk-E3FJUPLT.js} +15 -21
  31. package/dist/chunk-E7NDOZ27.js +428 -0
  32. package/dist/{chunk-TBQ5BU3Q.js → chunk-F42QKWBB.js} +18 -18
  33. package/dist/chunk-F4J6XCHT.js +73 -0
  34. package/dist/chunk-FB3UDZAV.js +168 -0
  35. package/dist/chunk-FJXPMA63.js +48 -0
  36. package/dist/chunk-FNJL6Z5C.js +71 -0
  37. package/dist/chunk-G63MXDX2.js +45 -0
  38. package/dist/{chunk-VFFOT7KD.js → chunk-G66HRVDW.js} +1 -1
  39. package/dist/{chunk-AXTLPJ2F.js → chunk-H2C4QUTG.js} +8 -7
  40. package/dist/{chunk-H3IPLBXQ.js → chunk-HRKVAXNN.js} +17 -14
  41. package/dist/chunk-HSCTPDEU.js +126 -0
  42. package/dist/{chunk-UXCWSWWX.js → chunk-HSMG6U7J.js} +8 -7
  43. package/dist/chunk-I5LELJSK.js +22 -0
  44. package/dist/{chunk-7CXMMC5S.js → chunk-JN4WZCR7.js} +5 -4
  45. package/dist/{chunk-7QZSDU52.js → chunk-K36EOII3.js} +5 -4
  46. package/dist/chunk-KLFBAFXD.js +25 -0
  47. package/dist/{chunk-355VG7EO.js → chunk-LONQWRTR.js} +107 -77
  48. package/dist/{chunk-Z5TFZQ5U.js → chunk-LORGE2NB.js} +68 -62
  49. package/dist/{chunk-LY2GQ32S.js → chunk-MEAO33XW.js} +22 -20
  50. package/dist/{chunk-OD2MNYXD.js → chunk-MR5KIFI7.js} +23 -22
  51. package/dist/{chunk-2VUUMXAQ.js → chunk-N2UHAQXC.js} +18 -11
  52. package/dist/chunk-NG2X3SMF.js +91 -0
  53. package/dist/chunk-OFJIG4K3.js +6482 -0
  54. package/dist/chunk-P74GTK23.js +91 -0
  55. package/dist/chunk-PKM3JOKQ.js +62 -0
  56. package/dist/{chunk-NDHXM4PL.js → chunk-Q3XQPNF6.js} +12 -12
  57. package/dist/{chunk-RXHTGX7C.js → chunk-Q5NZNXJE.js} +6 -10
  58. package/dist/chunk-QEKVZ7BX.js +57 -0
  59. package/dist/chunk-QNWCBPVO.js +215 -0
  60. package/dist/{chunk-US6QZICZ.js → chunk-RPJR3S5S.js} +32 -18
  61. package/dist/chunk-RPSUFZAG.js +3307 -0
  62. package/dist/chunk-RRI23NK2.js +40 -0
  63. package/dist/{chunk-6EWHKL7Z.js → chunk-SXYQL4GK.js} +7 -6
  64. package/dist/{chunk-ZI6PKVXG.js → chunk-TMPBGXT4.js} +6 -5
  65. package/dist/{chunk-UZM6OSW5.js → chunk-UPHB5HWO.js} +15 -13
  66. package/dist/chunk-UTSSDFQL.js +64 -0
  67. package/dist/chunk-V5ADM3WC.js +741 -0
  68. package/dist/{chunk-25BAMW5X.js → chunk-VIEKOGKG.js} +18 -2
  69. package/dist/chunk-VUV5U4J5.js +117 -0
  70. package/dist/{chunk-LXS3NJYD.js → chunk-VZEJ2ZHE.js} +14 -15
  71. package/dist/chunk-W2QPNAZ3.js +58 -0
  72. package/dist/chunk-YLUB6252.js +45 -0
  73. package/dist/{chunk-Z4Z24FWO.js → chunk-YNCYMWER.js} +8 -5
  74. package/dist/chunk-YXOGRERG.js +91 -0
  75. package/dist/index.js +39 -36
  76. package/package.json +31 -16
  77. package/templates/none/src/main.ts +4 -0
  78. package/templates/none/vite.config.ts +0 -2
  79. package/templates/phaser/src/main.ts +0 -1
  80. package/templates/phaser/src/scenes/game-scene.ts +10 -8
  81. package/templates/phaser/vite.config.ts +0 -2
  82. package/templates/react-r3f/src/app.tsx +3 -1
  83. package/templates/react-r3f/src/main.tsx +1 -0
  84. package/templates/react-r3f/vite.config.ts +0 -2
  85. package/templates/threejs/src/main.ts +10 -1
  86. package/templates/threejs/vite.config.ts +0 -2
  87. package/LICENSE +0 -21
  88. package/dist/chunk-J6PKNPI2.js +0 -26
package/README.md CHANGED
@@ -71,8 +71,9 @@ of failing with a bare exit code.
71
71
  installed as a platform-specific optional package on first use — the CLI itself
72
72
  carries none of it.
73
73
 
74
- `vg generate` calls the `generate.forward` proc — the server holds the
75
- provider API key, so generation works for any logged-in user with no local keys.
74
+ `vg generate` calls the `generate.*` procedures (`run`, `status`, `models`,
75
+ `schema`, `pricing`, `docs`, `upload`), the same ones the MCP `generate_*`
76
+ tools call — the server holds the provider API key, so generation works for any logged-in user with no local keys.
76
77
 
77
78
  ## Using with a coding agent
78
79
 
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env -S uv run --python 3.12 --script
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = ["pillow"]
5
+ # ///
6
+ """Framing alignment and crop-zoom for the review gates.
7
+
8
+ Tier-1 (`diagnose_render.py`) compares frame-aligned silhouette masks, but the
9
+ shared camera (`render_model.py`) leaves a fixed margin while references
10
+ usually fill their frame — so a correct model false-fails on framing alone.
11
+ This tool measures the subject bbox of BOTH images (plain-background product
12
+ shots), then crops the render so the subject fills its frame the way the
13
+ reference fills its own. The camera is untouched: this is evidence alignment,
14
+ not a re-render. Crop math is recorded in a JSON sidecar so the next agent can
15
+ audit it.
16
+
17
+ uv run align_framing.py align --reference ref/door.jpg \
18
+ --render runs/structural/front.png --out runs/structural/front-aligned.png
19
+
20
+ Also the crop-zoom tool the authoring step needs (recessed heads, part
21
+ adjacency — detail the full frame hides):
22
+
23
+ uv run align_framing.py crop --image ref/barrel.jpg \
24
+ --box 0.25,0.02,0.75,0.30 --zoom 3 --out ref-zones/top-head.png
25
+
26
+ uv run align_framing.py --selftest
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import json
33
+ import sys
34
+ from pathlib import Path
35
+
36
+ from PIL import Image
37
+
38
+
39
+ I2T_DEFAULT = Path.home() / ".local/share/img2threejs"
40
+
41
+
42
+ def upstream_mask(img: Image.Image, i2t: Path):
43
+ """Mask via upstream's own foreground masker so alignment agrees with the
44
+ tier-1 gate by construction (it excludes ground shadow; a naive border-
45
+ median threshold does not and over-measures fill on real JPEGs)."""
46
+ sys.path.insert(0, str(i2t / "forge" / "stage1_intake"))
47
+ from extract_pbr_evidence import build_foreground_mask # noqa: PLC0415
48
+
49
+ rgb = img.convert("RGB")
50
+ w, h = rgb.size
51
+ mask, _diag, _warn = build_foreground_mask(w, h, list(rgb.getdata()))
52
+ return w, h, mask
53
+
54
+
55
+ def subject_bbox(img: Image.Image, threshold: int, i2t: Path) -> tuple[int, int, int, int]:
56
+ """Bbox of the subject, preferring the gate's own masker."""
57
+ try:
58
+ w, h, mask = upstream_mask(img, i2t)
59
+ xs = [i % w for i, v in enumerate(mask) if v]
60
+ ys = [i // w for i, v in enumerate(mask) if v]
61
+ if xs:
62
+ return min(xs), min(ys), max(xs), max(ys)
63
+ except Exception as err: # noqa: BLE001 — fall back to the naive mask
64
+ print(f" (upstream masker unavailable: {err}; using border-median fallback)", file=sys.stderr)
65
+
66
+ rgb = img.convert("RGB")
67
+ w, h = rgb.size
68
+ px = rgb.load()
69
+ border = []
70
+ for x in range(0, w, max(1, w // 64)):
71
+ border.append(px[x, 0])
72
+ border.append(px[x, h - 1])
73
+ for y in range(0, h, max(1, h // 64)):
74
+ border.append(px[0, y])
75
+ border.append(px[w - 1, y])
76
+ border.sort()
77
+ bg = border[len(border) // 2]
78
+
79
+ x0, y0, x1, y1 = w, h, -1, -1
80
+ for y in range(h):
81
+ for x in range(w):
82
+ r, g, b = px[x, y]
83
+ if abs(r - bg[0]) + abs(g - bg[1]) + abs(b - bg[2]) > threshold:
84
+ if x < x0:
85
+ x0 = x
86
+ if x > x1:
87
+ x1 = x
88
+ if y < y0:
89
+ y0 = y
90
+ if y > y1:
91
+ y1 = y
92
+ if x1 < 0:
93
+ raise SystemExit("no foreground found — is the background non-uniform?")
94
+ return x0, y0, x1, y1
95
+
96
+
97
+ def parse_bbox(spec: str, size: tuple[int, int]) -> tuple[int, int, int, int]:
98
+ v = [float(x) for x in spec.split(",")]
99
+ if all(0 <= x <= 1 for x in v):
100
+ v = [v[0] * size[0], v[1] * size[1], v[2] * size[0], v[3] * size[1]]
101
+ return round(v[0]), round(v[1]), round(v[2]), round(v[3])
102
+
103
+
104
+ def sane(bbox: tuple[int, int, int, int], size: tuple[int, int]) -> bool:
105
+ # A subject bbox spanning ~the whole frame means the mask ate the
106
+ # background (soft JPEG gradients defeat both maskers).
107
+ w, h = size
108
+ return (bbox[2] - bbox[0]) < 0.98 * w or (bbox[3] - bbox[1]) < 0.98 * h
109
+
110
+
111
+ def cmd_align(args: argparse.Namespace) -> int:
112
+ ref = Image.open(args.reference)
113
+ ren = Image.open(args.render)
114
+
115
+ if args.ref_bbox:
116
+ rx0, ry0, rx1, ry1 = parse_bbox(args.ref_bbox, ref.size)
117
+ else:
118
+ rx0, ry0, rx1, ry1 = subject_bbox(ref, args.bg_threshold, args.i2t)
119
+ if not sane((rx0, ry0, rx1, ry1), ref.size):
120
+ raise SystemExit(
121
+ "reference mask spans the whole frame — the background gradient defeated "
122
+ "both maskers. Eyeball the subject bounds (crop-zoom helps) and pass "
123
+ "--ref-bbox x0,y0,x1,y1 (px or 0-1 fractions); it is recorded in the sidecar."
124
+ )
125
+ if args.render_bbox:
126
+ nx0, ny0, nx1, ny1 = parse_bbox(args.render_bbox, ren.size)
127
+ else:
128
+ nx0, ny0, nx1, ny1 = subject_bbox(ren, args.bg_threshold, args.i2t)
129
+
130
+ ref_w, ref_h = ref.size
131
+ # How the reference's subject sits in its own frame.
132
+ fill = (ry1 - ry0 + 1) / ref_h
133
+ cx_frac = ((rx0 + rx1) / 2) / ref_w
134
+ cy_frac = ((ry0 + ry1) / 2) / ref_h
135
+
136
+ # Cut a square-ish window around the render's subject reproducing that fill
137
+ # and centring, clamped to the canvas.
138
+ subj_h = ny1 - ny0 + 1
139
+ side = subj_h / fill
140
+ cx = (nx0 + nx1) / 2
141
+ cy = (ny0 + ny1) / 2
142
+ left = max(0, round(cx - cx_frac * side))
143
+ top = max(0, round(cy - cy_frac * side))
144
+ right = min(ren.size[0], round(left + side))
145
+ bottom = min(ren.size[1], round(top + side))
146
+
147
+ out = Path(args.out)
148
+ out.parent.mkdir(parents=True, exist_ok=True)
149
+ ren.crop((left, top, right, bottom)).resize(ref.size).save(out)
150
+
151
+ sidecar = {
152
+ "reference": str(args.reference),
153
+ "refBboxSource": "override" if args.ref_bbox else "measured",
154
+ "render": str(args.render),
155
+ "referenceSubjectBbox": [rx0, ry0, rx1, ry1],
156
+ "renderSubjectBbox": [nx0, ny0, nx1, ny1],
157
+ "referenceHeightFill": round(fill, 4),
158
+ "cropBox": [left, top, right, bottom],
159
+ "resizedTo": list(ref.size),
160
+ }
161
+ Path(str(out) + ".json").write_text(json.dumps(sidecar, indent=2) + "\n")
162
+ print(f"aligned -> {out} (fill {fill:.3f}, crop {left},{top}..{right},{bottom}); math in {out}.json")
163
+ return 0
164
+
165
+
166
+ def cmd_crop(args: argparse.Namespace) -> int:
167
+ img = Image.open(args.image)
168
+ w, h = img.size
169
+ fx0, fy0, fx1, fy1 = (float(v) for v in args.box.split(","))
170
+ box = (round(fx0 * w), round(fy0 * h), round(fx1 * w), round(fy1 * h))
171
+ crop = img.crop(box)
172
+ if args.zoom > 1:
173
+ crop = crop.resize((crop.width * args.zoom, crop.height * args.zoom), Image.NEAREST)
174
+ out = Path(args.out)
175
+ out.parent.mkdir(parents=True, exist_ok=True)
176
+ crop.save(out)
177
+ print(f"crop {box} zoom x{args.zoom} -> {out}")
178
+ return 0
179
+
180
+
181
+ def selftest() -> int:
182
+ from PIL import ImageDraw
183
+
184
+ ref = Image.new("RGB", (200, 200), (230, 230, 230))
185
+ ImageDraw.Draw(ref).rectangle([40, 20, 160, 180], fill=(120, 80, 40)) # fill 0.805
186
+ ren = Image.new("RGB", (200, 200), (184, 184, 184))
187
+ ImageDraw.Draw(ren).rectangle([70, 60, 130, 140], fill=(120, 80, 40)) # small, margined
188
+
189
+ import tempfile
190
+
191
+ with tempfile.TemporaryDirectory() as td:
192
+ rp, np_, op = Path(td, "ref.png"), Path(td, "ren.png"), Path(td, "out.png")
193
+ ref.save(rp)
194
+ ren.save(np_)
195
+ ns = argparse.Namespace(
196
+ reference=rp, render=np_, out=op, bg_threshold=30,
197
+ i2t=Path("/nonexistent"), ref_bbox=None, render_bbox=None,
198
+ )
199
+ cmd_align(ns)
200
+ sidecar = json.loads(Path(str(op) + ".json").read_text())
201
+ assert sidecar["referenceHeightFill"] > 0.79, sidecar
202
+ aligned = Image.open(op)
203
+ bx0, by0, bx1, by1 = subject_bbox(aligned, 30, Path("/nonexistent"))
204
+ new_fill = (by1 - by0 + 1) / aligned.size[1]
205
+ assert abs(new_fill - sidecar["referenceHeightFill"]) < 0.06, (new_fill, sidecar)
206
+ print("selftest ok")
207
+ return 0
208
+
209
+
210
+ def main() -> int:
211
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
212
+ ap.add_argument("--selftest", action="store_true")
213
+ sub = ap.add_subparsers(dest="cmd")
214
+
215
+ al = sub.add_parser("align", help="crop a render to the reference's framing")
216
+ al.add_argument("--reference", required=True, type=Path)
217
+ al.add_argument("--render", required=True, type=Path)
218
+ al.add_argument("--out", required=True, type=Path)
219
+ al.add_argument("--bg-threshold", type=int, default=30)
220
+ al.add_argument("--i2t", type=Path, default=I2T_DEFAULT, help="upstream clone (for its foreground masker)")
221
+ al.add_argument("--ref-bbox", help="override reference subject bbox: x0,y0,x1,y1 (px or 0-1 fractions)")
222
+ al.add_argument("--render-bbox", help="override render subject bbox (same format)")
223
+
224
+ cr = sub.add_parser("crop", help="crop-zoom a region (fractions of width/height)")
225
+ cr.add_argument("--image", required=True, type=Path)
226
+ cr.add_argument("--box", required=True, help="x0,y0,x1,y1 as 0-1 fractions")
227
+ cr.add_argument("--zoom", type=int, default=2)
228
+ cr.add_argument("--out", required=True, type=Path)
229
+
230
+ args = ap.parse_args()
231
+ if args.selftest:
232
+ return selftest()
233
+ if args.cmd == "align":
234
+ return cmd_align(args)
235
+ if args.cmd == "crop":
236
+ return cmd_crop(args)
237
+ ap.error("pass a subcommand or --selftest")
238
+ return 2
239
+
240
+
241
+ if __name__ == "__main__":
242
+ raise SystemExit(main())
@@ -0,0 +1,406 @@
1
+ #!/usr/bin/env -S uv run --python 3.12 --script
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = []
5
+ # ///
6
+ """Render a generated Three.js factory to PNGs at canonical angles.
7
+
8
+ The upstream pass gate needs a browser render before it will unlock the next
9
+ pass, but leaves producing one to "your agent's browser tool". This does it
10
+ deterministically: mount the factory in a throwaway Vite entry, frame the model
11
+ by its own bounding box, and shoot fixed angles on a neutral backdrop.
12
+
13
+ Deterministic by construction — fixed camera ring, fixed lights, no animation —
14
+ so two renders of the same spec differ only where the model changed.
15
+
16
+ uv run render_model.py --project sandbox/chest-quest \
17
+ --factory src/model/chest-factory.generated.ts \
18
+ --export createTreasureChestModel --out-dir runs/blockout
19
+
20
+ Writes <out-dir>/<view>.png plus contact.json (mesh/material/geometry counts,
21
+ socket + pivot names, bounds) and parts.json (the runtime part manifest
22
+ check_part_coverage.py wants).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import glob
29
+ import json
30
+ import os
31
+ import re
32
+ import shutil
33
+ import socket
34
+ import subprocess
35
+ import sys
36
+ import time
37
+ from pathlib import Path
38
+
39
+ HARNESS_DIR = ".i2t-render"
40
+
41
+ # Azimuth/elevation degrees. `three-quarter` is first because it is the view
42
+ # reference images are usually asked for and the one reviews should score.
43
+ VIEWS: dict[str, tuple[float, float]] = {
44
+ "three-quarter": (35.0, 22.0),
45
+ "front": (0.0, 12.0),
46
+ "side": (90.0, 12.0),
47
+ "back": (180.0, 12.0),
48
+ # Completes the 0/90/180/270 ring upstream's turntable_gate.py requires.
49
+ "left": (270.0, 12.0),
50
+ "top": (35.0, 65.0),
51
+ # Grazing view for flat props: surface-pass judges normal/height detail
52
+ # under raking light, and "side" is dead edge-on for anything flat.
53
+ "raking": (15.0, 3.0),
54
+ }
55
+
56
+ INDEX_HTML = """<!doctype html>
57
+ <html>
58
+ <head><meta charset="utf-8" /><title>i2t render</title>
59
+ <style>html,body{margin:0;height:100%;background:#b8b8b8}canvas{display:block}</style>
60
+ </head>
61
+ <body><script type="module" src="./main.ts"></script></body>
62
+ </html>
63
+ """
64
+
65
+ MAIN_TS = """import * as THREE from "three";
66
+ import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
67
+ import { %(export_name)s as factory } from "%(factory_import)s";
68
+
69
+ const SIZE = %(size)d;
70
+ const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true, alpha: true });
71
+ renderer.setPixelRatio(1);
72
+ renderer.setSize(SIZE, SIZE);
73
+ document.body.append(renderer.domElement);
74
+
75
+ const scene = new THREE.Scene();
76
+ // Turntable frames need an alpha channel: upstream's masker gives up on any
77
+ // opaque frame where the subject covers < 3.5%% of the image (an edge-on flat
78
+ // prop always does) but trusts alpha at any coverage.
79
+ if (%(transparent)s) renderer.setClearColor(0x000000, 0);
80
+ else scene.background = new THREE.Color(0xb8b8b8);
81
+
82
+ const model = factory({ castShadow: false, receiveShadow: false });
83
+ scene.add(model);
84
+
85
+ // The pass gate wants map-stripped evidence: procedural albedo/roughness maps
86
+ // can flatter a wrong shape, so geometry gets reviewed on its own. Neutral matte
87
+ // keeps the light rig, which is what makes form readable at all.
88
+ if (%(map_stripped)s) {
89
+ const matte = new THREE.MeshStandardMaterial({ color: 0xc9c9c9, roughness: 1, metalness: 0 });
90
+ model.traverse((o) => {
91
+ const mesh = o as THREE.Mesh;
92
+ if (mesh.isMesh) mesh.material = matte;
93
+ });
94
+ }
95
+
96
+ // Metals need something to reflect. Without an environment map a high-metalness
97
+ // PBR material renders pure BLACK, which reads as "my material is broken"
98
+ // rather than "my scene has no reflections" — so always light metal with an env.
99
+ if (!%(map_stripped)s) {
100
+ const pmrem = new THREE.PMREMGenerator(renderer);
101
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
102
+ }
103
+
104
+ // Neutral three-point rig: enough to read form without editorialising the look.
105
+ scene.add(new THREE.AmbientLight(0xffffff, 1.5));
106
+ const key = new THREE.DirectionalLight(0xffffff, 2.2);
107
+ key.position.set(3, 5, 4);
108
+ scene.add(key);
109
+ const fill = new THREE.DirectionalLight(0xffffff, 0.8);
110
+ fill.position.set(-4, 2, -3);
111
+ scene.add(fill);
112
+
113
+ const box = new THREE.Box3().setFromObject(model);
114
+ const size = box.getSize(new THREE.Vector3());
115
+ const center = box.getCenter(new THREE.Vector3());
116
+ const radius = Math.max(size.x, size.y, size.z) * 1.25 || 1;
117
+
118
+ const camera = new THREE.PerspectiveCamera(40, 1, 0.01, 1000);
119
+
120
+ function shoot(azimuthDeg: number, elevationDeg: number) {
121
+ const az = (azimuthDeg * Math.PI) / 180;
122
+ const el = (elevationDeg * Math.PI) / 180;
123
+ const dist = radius / Math.tan((camera.fov * Math.PI) / 360);
124
+ camera.position.set(
125
+ center.x + dist * Math.cos(el) * Math.sin(az),
126
+ center.y + dist * Math.sin(el),
127
+ center.z + dist * Math.cos(el) * Math.cos(az),
128
+ );
129
+ camera.lookAt(center);
130
+ camera.updateProjectionMatrix();
131
+ renderer.render(scene, camera);
132
+ return renderer.domElement.toDataURL("image/png");
133
+ }
134
+
135
+ const meshes: string[] = [];
136
+ const materials = new Set<string>();
137
+ const geometries = new Set<string>();
138
+ const parts: { name: string; kind: string; module: string; triangles: number }[] = [];
139
+ let unnamedMeshes = 0;
140
+ model.traverse((o) => {
141
+ const mesh = o as THREE.Mesh;
142
+ if (!mesh.isMesh) return;
143
+ meshes.push(mesh.name || "(unnamed)");
144
+ const index = mesh.geometry.getIndex();
145
+ const triangles = Math.floor((index ? index.count : mesh.geometry.getAttribute("position").count) / 3);
146
+ if (mesh.name) parts.push({ name: mesh.name, kind: "part", module: mesh.name, triangles });
147
+ else unnamedMeshes++;
148
+ geometries.add(mesh.geometry.uuid);
149
+ for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
150
+ materials.add(m.uuid);
151
+ }
152
+ });
153
+
154
+ const sockets: string[] = [];
155
+ const pivots: string[] = [];
156
+ model.traverse((o) => {
157
+ if (o.name.includes("socket")) sockets.push(o.name);
158
+ if (o.name.endsWith("__pivot")) pivots.push(o.name);
159
+ });
160
+
161
+ // World-space geometry dump in the shape forge's executed-geometry gates read
162
+ // (self_intersection.py, swept_arc_gate.py, geometry_integrity). World space on
163
+ // purpose: a parent transform can fold a mesh that is clean in local space.
164
+ function exportMeshes() {
165
+ model.updateMatrixWorld(true);
166
+ const out: { name: string; vertices: number[][]; indices: number[] }[] = [];
167
+ const v = new THREE.Vector3();
168
+ model.traverse((o) => {
169
+ const mesh = o as THREE.Mesh;
170
+ if (!mesh.isMesh) return;
171
+ const pos = mesh.geometry.getAttribute("position");
172
+ const vertices: number[][] = [];
173
+ for (let i = 0; i < pos.count; i++) {
174
+ v.fromBufferAttribute(pos, i).applyMatrix4(mesh.matrixWorld);
175
+ vertices.push([v.x, v.y, v.z]);
176
+ }
177
+ const index = mesh.geometry.getIndex();
178
+ const indices = index ? Array.from(index.array) : Array.from({ length: pos.count }, (_, i) => i);
179
+ out.push({ name: mesh.name || "(unnamed)", vertices, indices });
180
+ });
181
+ return out;
182
+ }
183
+
184
+ Object.assign(window, {
185
+ __render: {
186
+ shoot,
187
+ exportMeshes,
188
+ parts: { model: model.name || "model", parts, unnamedMeshes, integralMeshes: meshes.length },
189
+ contact: {
190
+ meshCount: meshes.length,
191
+ meshNames: meshes,
192
+ materialCount: materials.size,
193
+ geometryCount: geometries.size,
194
+ sockets,
195
+ pivots,
196
+ boundsSize: [size.x, size.y, size.z],
197
+ },
198
+ },
199
+ });
200
+ """
201
+
202
+ SHOOT_JS = """const pw = await import(%(playwright)s);
203
+ const chromium = pw.chromium ?? pw.default.chromium;
204
+ const views = %(views)s;
205
+ const outDir = %(out_dir)s;
206
+ const size = %(size)d;
207
+
208
+ const browser = await chromium.launch();
209
+ const page = await browser.newPage({ viewport: { width: size, height: size } });
210
+ const problems = [];
211
+ page.on('pageerror', (e) => problems.push(String(e).split('\\n')[0]));
212
+ page.on('console', (m) => m.type() === 'error' && problems.push('console: ' + m.text()));
213
+
214
+ await page.goto(%(url)s, { waitUntil: 'load' });
215
+ await page.waitForFunction(() => Boolean(window.__render), null, { timeout: 30000 });
216
+
217
+ const fs = await import('node:fs');
218
+ const suffix = %(stripped_suffix)s;
219
+ for (const [name, [az, el]] of Object.entries(views)) {
220
+ const dataUrl = await page.evaluate(([a, e]) => window.__render.shoot(a, e), [az, el]);
221
+ fs.writeFileSync(`${outDir}/${name}${suffix}.png`, Buffer.from(dataUrl.split(',')[1], 'base64'));
222
+ }
223
+ const contact = await page.evaluate(() => window.__render.contact);
224
+ // A stripped run overrides every material, so its counts describe the override,
225
+ // not the model — keep its contact separate or run order decides what's recorded.
226
+ fs.writeFileSync(`${outDir}/contact${suffix}.json`, JSON.stringify({ ...contact, problems }, null, 2));
227
+ // Runtime part manifest in the shape forge's check_part_coverage.py --manifest reads.
228
+ const parts = await page.evaluate(() => window.__render.parts);
229
+ fs.writeFileSync(`${outDir}/parts${suffix}.json`, JSON.stringify(parts, null, 2));
230
+ if (%(export_meshes)s) {
231
+ const meshes = await page.evaluate(() => window.__render.exportMeshes());
232
+ fs.writeFileSync(`${outDir}/meshes.json`, JSON.stringify({ meshes }));
233
+ }
234
+ console.log(JSON.stringify({ views: Object.keys(views), problems }));
235
+ await browser.close();
236
+ """
237
+
238
+
239
+ def find_playwright(project: Path) -> str:
240
+ """Locate an installed playwright ESM entry, walking up to the workspace root."""
241
+ for base in [project, *project.parents]:
242
+ hits = sorted(glob.glob(str(base / "node_modules/.pnpm/playwright@*/node_modules/playwright/index.mjs")))
243
+ if hits:
244
+ return hits[-1]
245
+ direct = base / "node_modules/playwright/index.mjs"
246
+ if direct.exists():
247
+ return str(direct)
248
+ raise SystemExit(
249
+ "could not find playwright. Install it in the project or run from a workspace that has it."
250
+ )
251
+
252
+
253
+ def free_port() -> int:
254
+ with socket.socket() as s:
255
+ s.bind(("127.0.0.1", 0))
256
+ return int(s.getsockname()[1])
257
+
258
+
259
+ def wait_for_http(url: str, timeout: float) -> bool:
260
+ import urllib.error
261
+ import urllib.request
262
+
263
+ deadline = time.time() + timeout
264
+ while time.time() < deadline:
265
+ try:
266
+ with urllib.request.urlopen(url, timeout=2):
267
+ return True
268
+ except urllib.error.HTTPError:
269
+ return True
270
+ except OSError:
271
+ time.sleep(0.4)
272
+ return False
273
+
274
+
275
+ def main() -> int:
276
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
277
+ ap.add_argument("--project", required=True, help="Vite project with three installed")
278
+ ap.add_argument("--factory", required=True, help="Generated factory, relative to --project")
279
+ ap.add_argument("--export", dest="export_name", required=True, help="Factory export, e.g. createFooModel")
280
+ ap.add_argument("--out-dir", required=True)
281
+ ap.add_argument(
282
+ "--views",
283
+ default="three-quarter,front,side",
284
+ help=f"any of: {','.join(VIEWS)}, or az<degrees> for an arbitrary azimuth "
285
+ "(a 45/135/225/315 ring keeps thin props off their edge-on frames)",
286
+ )
287
+ ap.add_argument("--size", type=int, default=768)
288
+ ap.add_argument("--keep-harness", action="store_true", help="leave the temp Vite entry in place for debugging")
289
+ ap.add_argument(
290
+ "--map-stripped",
291
+ action="store_true",
292
+ help="override every material with a neutral matte and write <view>-stripped.png; "
293
+ "the pass gate requires this as geometry evidence alongside the lit renders",
294
+ )
295
+ ap.add_argument(
296
+ "--transparent",
297
+ action="store_true",
298
+ help="render on a transparent backdrop (turntable_gate.py evidence; the default grey "
299
+ "backdrop is unsegmentable once a thin prop is edge-on)",
300
+ )
301
+ ap.add_argument(
302
+ "--export-meshes",
303
+ action="store_true",
304
+ help="also write meshes.json (world-space vertices+indices per mesh) — the input "
305
+ "forge's self_intersection.py / swept_arc_gate.py / turntable evidence gates read",
306
+ )
307
+ ap.add_argument(
308
+ "--elevation",
309
+ type=float,
310
+ default=None,
311
+ help="override the elevation (degrees) of every chosen view — match the reference's "
312
+ "camera pitch before comparing silhouettes or IoU gates false-negative",
313
+ )
314
+ args = ap.parse_args()
315
+
316
+ project = Path(args.project).resolve()
317
+ factory = (project / args.factory).resolve()
318
+ if not factory.exists():
319
+ raise SystemExit(f"factory not found: {factory}")
320
+
321
+ chosen = {}
322
+ for name in [v.strip() for v in args.views.split(",") if v.strip()]:
323
+ az_match = re.fullmatch(r"az(-?\d+(?:\.\d+)?)", name)
324
+ if az_match:
325
+ az, el = float(az_match.group(1)), 12.0
326
+ elif name in VIEWS:
327
+ az, el = VIEWS[name]
328
+ else:
329
+ raise SystemExit(f"unknown view '{name}'; choose from {','.join(VIEWS)} or az<degrees>")
330
+ chosen[name] = (az, args.elevation if args.elevation is not None else el)
331
+
332
+ out_dir = Path(args.out_dir).resolve()
333
+ out_dir.mkdir(parents=True, exist_ok=True)
334
+
335
+ harness = project / HARNESS_DIR
336
+ harness.mkdir(exist_ok=True)
337
+ rel = os.path.relpath(factory, harness).replace(os.sep, "/")
338
+ if not rel.startswith("."):
339
+ rel = f"./{rel}"
340
+ (harness / "index.html").write_text(INDEX_HTML)
341
+ (harness / "main.ts").write_text(
342
+ MAIN_TS
343
+ % {
344
+ "export_name": args.export_name,
345
+ "factory_import": rel,
346
+ "size": args.size,
347
+ "map_stripped": "true" if args.map_stripped else "false",
348
+ "transparent": "true" if args.transparent else "false",
349
+ }
350
+ )
351
+
352
+ port = free_port()
353
+ vite = subprocess.Popen(
354
+ ["npx", "vite", "--port", str(port), "--strictPort"],
355
+ cwd=project,
356
+ stdout=subprocess.PIPE,
357
+ stderr=subprocess.STDOUT,
358
+ text=True,
359
+ )
360
+ try:
361
+ url = f"http://localhost:{port}/{HARNESS_DIR}/"
362
+ if not wait_for_http(url, timeout=60):
363
+ out = vite.stdout.read() if vite.stdout else ""
364
+ raise SystemExit(f"vite did not come up on {port}\n{out[-1500:]}")
365
+
366
+ script = SHOOT_JS % {
367
+ "playwright": json.dumps(find_playwright(project)),
368
+ "views": json.dumps(chosen),
369
+ "out_dir": json.dumps(str(out_dir)),
370
+ "url": json.dumps(url),
371
+ "size": args.size,
372
+ "stripped_suffix": json.dumps("-stripped" if args.map_stripped else ""),
373
+ "export_meshes": "true" if args.export_meshes else "false",
374
+ }
375
+ shot = subprocess.run(
376
+ ["node", "--input-type=module", "-e", script],
377
+ capture_output=True,
378
+ text=True,
379
+ )
380
+ if shot.returncode != 0:
381
+ sys.stderr.write(shot.stderr[-2000:])
382
+ raise SystemExit("render failed")
383
+ print(shot.stdout.strip())
384
+ finally:
385
+ vite.terminate()
386
+ try:
387
+ vite.wait(timeout=10)
388
+ except subprocess.TimeoutExpired:
389
+ vite.kill()
390
+ if not args.keep_harness:
391
+ shutil.rmtree(harness, ignore_errors=True)
392
+
393
+ contact_name = "contact-stripped.json" if args.map_stripped else "contact.json"
394
+ contact = json.loads((out_dir / contact_name).read_text())
395
+ print(
396
+ f" meshes={contact['meshCount']} materials={contact['materialCount']} "
397
+ f"geometries={contact['geometryCount']} pivots={len(contact['pivots'])} sockets={len(contact['sockets'])}"
398
+ )
399
+ if contact["problems"]:
400
+ print(" PROBLEMS:", *contact["problems"][:5], sep="\n ")
401
+ return 1
402
+ return 0
403
+
404
+
405
+ if __name__ == "__main__":
406
+ raise SystemExit(main())