@opengamehq/cli 0.0.0-stage → 0.5.0

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 (75) hide show
  1. package/AGENTS.md +238 -0
  2. package/CHANGELOG.md +22 -0
  3. package/README.md +129 -2
  4. package/dist/cli.mjs +1432 -0
  5. package/dist/opengame-global.js +49 -0
  6. package/dist/opengame-global.js.LEGAL.txt +1 -0
  7. package/dist/preflight-worker.mjs +20 -0
  8. package/dist/runtime-builder.mjs +800 -0
  9. package/dist/runtime-catalog.json +1 -0
  10. package/dist/runtime-catalog.sha256 +1 -0
  11. package/dist/runtime-shells/runtime-shell.html +4 -0
  12. package/dist/runtime-shells/runtime-shell.js +91 -0
  13. package/dist/safe-fs.py +242 -0
  14. package/dist/skills/manifest.json +516 -0
  15. package/dist/skills/opengame-accessibility/SKILL.md +90 -0
  16. package/dist/skills/opengame-api/SKILL.md +85 -0
  17. package/dist/skills/opengame-assets/SKILL.md +124 -0
  18. package/dist/skills/opengame-assets/references/pipeline.md +97 -0
  19. package/dist/skills/opengame-audio/SKILL.md +154 -0
  20. package/dist/skills/opengame-audio/helpers/audio-chain.js +325 -0
  21. package/dist/skills/opengame-audio/references/mix-notes.md +82 -0
  22. package/dist/skills/opengame-capture/SKILL.md +108 -0
  23. package/dist/skills/opengame-capture/references/pipeline.md +82 -0
  24. package/dist/skills/opengame-capture/references/threejs.md +145 -0
  25. package/dist/skills/opengame-characters/SKILL.md +129 -0
  26. package/dist/skills/opengame-characters/references/integration.md +144 -0
  27. package/dist/skills/opengame-characters/references/player-og.md +160 -0
  28. package/dist/skills/opengame-cli/SKILL.md +118 -0
  29. package/dist/skills/opengame-deploy/SKILL.md +207 -0
  30. package/dist/skills/opengame-deploy/references/json-events.md +62 -0
  31. package/dist/skills/opengame-deploy/references/manifest.md +83 -0
  32. package/dist/skills/opengame-deploy/references/packaging.md +117 -0
  33. package/dist/skills/opengame-depth/SKILL.md +130 -0
  34. package/dist/skills/opengame-enemies/SKILL.md +103 -0
  35. package/dist/skills/opengame-enemies/references/threejs.md +134 -0
  36. package/dist/skills/opengame-front-end/SKILL.md +143 -0
  37. package/dist/skills/opengame-front-end/references/launch.md +50 -0
  38. package/dist/skills/opengame-front-end/references/menus.md +47 -0
  39. package/dist/skills/opengame-game-feel/SKILL.md +137 -0
  40. package/dist/skills/opengame-game-feel/helpers/spring.js +146 -0
  41. package/dist/skills/opengame-game-feel/references/feel-numbers.md +83 -0
  42. package/dist/skills/opengame-jam/SKILL.md +103 -0
  43. package/dist/skills/opengame-lighting/SKILL.md +94 -0
  44. package/dist/skills/opengame-lighting/helpers/light-pool.js +185 -0
  45. package/dist/skills/opengame-loading/SKILL.md +99 -0
  46. package/dist/skills/opengame-loading/references/threejs.md +116 -0
  47. package/dist/skills/opengame-look/SKILL.md +114 -0
  48. package/dist/skills/opengame-look/references/post-and-lens.md +66 -0
  49. package/dist/skills/opengame-mobile/SKILL.md +90 -0
  50. package/dist/skills/opengame-performance/SKILL.md +140 -0
  51. package/dist/skills/opengame-performance/references/measuring.md +72 -0
  52. package/dist/skills/opengame-production/SKILL.md +131 -0
  53. package/dist/skills/opengame-production/references/templates.md +63 -0
  54. package/dist/skills/opengame-quality-bar/SKILL.md +122 -0
  55. package/dist/skills/opengame-quality-bar/references/cheap-tells.md +36 -0
  56. package/dist/skills/opengame-quality-bar/references/review-prompt.md +27 -0
  57. package/dist/skills/opengame-router/SKILL.md +51 -0
  58. package/dist/skills/opengame-router/references/process.md +38 -0
  59. package/dist/skills/opengame-scene-audit/SKILL.md +123 -0
  60. package/dist/skills/opengame-scene-audit/helpers/scene-audit.js +599 -0
  61. package/dist/skills/opengame-sdk/SKILL.md +270 -0
  62. package/dist/skills/opengame-sdk/references/engines.md +93 -0
  63. package/dist/skills/opengame-sdk/references/frame.md +107 -0
  64. package/dist/skills/opengame-sdk/references/identity.md +112 -0
  65. package/dist/skills/opengame-sdk/references/leaderboards.md +105 -0
  66. package/dist/skills/opengame-sdk/references/radio.md +71 -0
  67. package/dist/skills/opengame-stability/SKILL.md +84 -0
  68. package/dist/skills/opengame-verification/SKILL.md +136 -0
  69. package/dist/skills/opengame-verification/helpers/browser-evidence.mjs +74 -0
  70. package/dist/skills/opengame-weapons/SKILL.md +109 -0
  71. package/dist/skills/opengame-weapons/references/handling-numbers.md +72 -0
  72. package/dist/skills/opengame-weapons/references/threejs.md +169 -0
  73. package/dist/skills/opengame-world-physics/SKILL.md +114 -0
  74. package/dist/skills/opengame-world-physics/references/measured-failures.md +52 -0
  75. package/package.json +38 -4
@@ -0,0 +1,599 @@
1
+ /**
2
+ * A geometry audit for a 3D game scene: floating props, buried props, solids driven
3
+ * through each other, coplanar faces that z-fight, visible solids with no collider, and
4
+ * a walk bot that climbs every staircase holding forward only. No GPU, no browser.
5
+ *
6
+ * Copy this file into the game and feed it the scene the game actually builds:
7
+ *
8
+ * import { runSceneAudit, fromThreeScene } from "./scene-audit.js";
9
+ * const scene = fromThreeScene(THREE, world, { colliders: collisionBoxes });
10
+ * scene.routes = [{ name: "west stairs", from: [2, 0, 8], to: [2, 3, -4] }];
11
+ * const report = runSceneAudit(scene);
12
+ * console.log(formatReport(report));
13
+ * if (!report.ok) process.exitCode = 1;
14
+ *
15
+ * Or describe the scene directly. A part is an axis-aligned box in world metres:
16
+ * { id, min: [x, y, z], max: [x, y, z], solid, collider, nocollide, hangs, group, prop }
17
+ * solid opaque volume a body should not pass through (default true)
18
+ * collider true when the game's collision layer blocks it
19
+ * nocollide a reason it is deliberately walk-through ("foliage", "decal")
20
+ * hangs a reason it is held up by design ("lamp on a wire")
21
+ * group parts emitted together as one object; they may touch and overlap
22
+ * triangles optional [[ax,ay,az, bx,by,bz, cx,cy,cz], ...] for the coplanar check;
23
+ * boxes without triangles contribute their six faces
24
+ * plus `colliders` (boxes the controller collides with), `ramps` (invisible stair
25
+ * ramps), `groundY` (a number or a function of x and z), `floors` (walkable heights)
26
+ * and `routes` for the walk bot.
27
+ *
28
+ * EVERY CHECK PLANTS A DEFECT FIRST. Before measuring the real scene, each check runs on
29
+ * a copy with a known defect placed at a site it chooses from the real scene, and the
30
+ * audit fails if the defect is not found. A check that examined nothing also fails.
31
+ * Both rules exist because an audit that cannot fail reports the same clean zero as a
32
+ * clean scene: one coplanar audit in our own games clipped triangles with inverted
33
+ * winding and measured 0 m² on every prop, including one with 0.4 m² of z-fighting.
34
+ *
35
+ * Default tolerances are World at War's map-coherence reference configuration, measured
36
+ * for a human-scale shooter in metres. Pass `tolerances` to change them for your scale.
37
+ */
38
+
39
+ export const TOLERANCES = Object.freeze({
40
+ floatTol: 0.12, // a base this far above its support is floating
41
+ contactTol: 0.08, // parts this close are touching
42
+ sinkTol: 0.25, // a prop's base this far below the ground is buried
43
+ propScale: 2.5, // larger than this in plan or height is structure, not a prop
44
+ penVolume: 0.02, // overlaps smaller than this many cubic metres are rounding
45
+ penFraction: 0.2, // a fifth of the smaller part inside the other
46
+ penSlack: 0.05, // slack on "deeper than the thinner part"
47
+ zEps: 0.002, // faces closer than this to one plane have no depth winner
48
+ zArea: 0.02, // overlap smaller than this many square metres is not visible
49
+ bodyRadius: 0.35, bodyHeight: 1.8, stepHeight: 0.42, walkSpeed: 4.9,
50
+ stuckSeconds: 1.0, routeSeconds: 30,
51
+ });
52
+
53
+ /* ----------------------------------------------------------------- geometry basics */
54
+
55
+ const sizeOf = (p, axis) => p.max[axis] - p.min[axis];
56
+ const volumeOf = (p) => sizeOf(p, 0) * sizeOf(p, 1) * sizeOf(p, 2);
57
+ const centre = (p) => [0, 1, 2].map((a) => (p.min[a] + p.max[a]) / 2);
58
+ function overlap1(a, b, axis) { return Math.min(a.max[axis], b.max[axis]) - Math.max(a.min[axis], b.min[axis]); }
59
+ function boxGap(a, b) {
60
+ let d2 = 0;
61
+ for (let axis = 0; axis < 3; axis++) { const gap = -overlap1(a, b, axis); if (gap > 0) d2 += gap * gap; }
62
+ return Math.sqrt(d2);
63
+ }
64
+ const footprintsOverlap = (a, b) => overlap1(a, b, 0) > 0 && overlap1(a, b, 2) > 0;
65
+ const isSolid = (p) => p.solid !== false;
66
+ const lowestBase = new WeakMap();
67
+ /**
68
+ * The ground under a point: `scene.groundY` as a number or a function of x and z. A
69
+ * scene that gives neither is grounded at its lowest solid base, which is the world's
70
+ * own floor in any scene built on one.
71
+ */
72
+ function groundAt(scene, x, z) {
73
+ if (typeof scene.groundY === "function") return scene.groundY(x, z);
74
+ if (typeof scene.groundY === "number") return scene.groundY;
75
+ if (!lowestBase.has(scene)) {
76
+ const bases = scene.parts.filter((p) => p.visible !== false && p.solid !== false).map((p) => p.min[1]);
77
+ lowestBase.set(scene, bases.length ? Math.min(...bases) : null);
78
+ }
79
+ return lowestBase.get(scene);
80
+ }
81
+ const site = (p) => centre(p).map((v) => Math.round(v * 100) / 100);
82
+
83
+ /** The six faces of a box as twelve triangles, outward facing. */
84
+ export function boxTriangles(p) {
85
+ const [x0, y0, z0] = p.min, [x1, y1, z1] = p.max;
86
+ const quads = [
87
+ [[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]], [[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]],
88
+ [[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], [[x0, y0, z1], [x0, y0, z0], [x1, y0, z0], [x1, y0, z1]],
89
+ [[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]], [[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]],
90
+ ];
91
+ return quads.flatMap(([a, b, c, d]) => [[...a, ...b, ...c], [...a, ...c, ...d]]);
92
+ }
93
+
94
+ /* ------------------------------------------------------------------ the checks */
95
+
96
+ /**
97
+ * float: a part whose base hangs above whatever is under it and which is not, through
98
+ * any chain of contact, standing on the ground. "Attached" is derived from contact, not
99
+ * named, and contact only counts when it leads to the ground: two crates touching each
100
+ * other in mid-air do not hold each other up.
101
+ */
102
+ export function checkFloat(scene, tol = TOLERANCES) {
103
+ const parts = scene.parts.filter((p) => p.visible !== false);
104
+ const judged = parts.filter((p) => !p.hangs);
105
+ const surfaceUnder = (p) => {
106
+ const [cx, , cz] = centre(p);
107
+ let best = groundAt(scene, cx, cz);
108
+ for (const floor of scene.floors ?? []) if (floor <= p.min[1] + tol.floatTol && (best === null || floor > best)) best = floor;
109
+ for (const q of parts) {
110
+ if (q === p || !footprintsOverlap(p, q) || q.max[1] > p.min[1] + tol.contactTol) continue;
111
+ if (best === null || q.max[1] > best) best = q.max[1];
112
+ }
113
+ return best;
114
+ };
115
+ // Seed only from the ground and published floors. Seeding from "the top of whatever
116
+ // is under me" lets two crates in mid-air hold each other up for ever.
117
+ const grounded = new Set(parts.filter((p) => p.hangs));
118
+ for (const p of judged) {
119
+ const [cx, , cz] = centre(p);
120
+ const levels = [groundAt(scene, cx, cz), ...(scene.floors ?? [])].filter((y) => y !== null);
121
+ if (levels.some((y) => Math.abs(p.min[1] - y) <= tol.floatTol || (p.min[1] < y && p.max[1] > y))) grounded.add(p);
122
+ }
123
+ // Spread support through contact until nothing changes.
124
+ let changed = true;
125
+ while (changed) {
126
+ changed = false;
127
+ for (const p of judged) {
128
+ if (grounded.has(p)) continue;
129
+ for (const q of grounded) if (boxGap(p, q) <= tol.contactTol) { grounded.add(p); changed = true; break; }
130
+ }
131
+ }
132
+ const findings = judged.filter((p) => !grounded.has(p)).map((p) => {
133
+ const under = surfaceUnder(p);
134
+ const gap = under === null ? null : p.min[1] - under;
135
+ return { id: p.id, at: site(p), why: gap === null ? "nothing under it and touching nothing that reaches the ground" : `base is ${gap.toFixed(3)} m above the surface under it and nothing holds it up` };
136
+ });
137
+ return { name: "float", examined: judged.length, findings };
138
+ }
139
+
140
+ const isProp = (p, tol) => p.prop ?? (Math.max(sizeOf(p, 0), sizeOf(p, 1), sizeOf(p, 2)) <= tol.propScale);
141
+
142
+ /**
143
+ * buried: a prop whose base sits well under the floor it stands on while its top still
144
+ * stands proud. The floor is the ground, or the highest structure (anything larger than
145
+ * a prop) under the prop's centre whose top is below the prop's top. A part sunk deeper
146
+ * than it is tall, or a large one, is a footing or a foundation, which is what those
147
+ * are for, and is not judged.
148
+ */
149
+ export function checkBuried(scene, tol = TOLERANCES) {
150
+ const solids = scene.parts.filter((p) => p.visible !== false && isSolid(p));
151
+ const structure = solids.filter((p) => !isProp(p, tol));
152
+ const findings = [];
153
+ let examined = 0;
154
+ for (const p of solids) {
155
+ if (!isProp(p, tol)) continue;
156
+ const [cx, , cz] = centre(p);
157
+ let floor = groundAt(scene, cx, cz);
158
+ if (floor !== null && floor > p.max[1]) floor = null;
159
+ for (const q of structure) {
160
+ if (q === p || cx < q.min[0] || cx > q.max[0] || cz < q.min[2] || cz > q.max[2] || q.max[1] > p.max[1]) continue;
161
+ if (floor === null || q.max[1] > floor) floor = q.max[1];
162
+ }
163
+ if (floor === null) continue;
164
+ examined++;
165
+ const depth = floor - p.min[1];
166
+ if (depth > tol.sinkTol && depth < sizeOf(p, 1)) findings.push({ id: p.id, at: site(p), why: `base is ${depth.toFixed(3)} m under the floor it stands on` });
167
+ }
168
+ return { name: "buried", examined, findings };
169
+ }
170
+
171
+ /**
172
+ * interpenetration: two solids sharing volume, judged two ways because each misses
173
+ * what the other sees. Depth past the thinner part's own thickness catches a wall
174
+ * through a wall; a fraction of the smaller part catches two equal crates inside each
175
+ * other, which depth alone never can.
176
+ */
177
+ export function checkInterpenetration(scene, tol = TOLERANCES) {
178
+ const solids = scene.parts.filter((p) => p.visible !== false && isSolid(p) && volumeOf(p) > 0).sort((a, b) => a.min[0] - b.min[0]);
179
+ const findings = [];
180
+ let examined = 0;
181
+ for (let i = 0; i < solids.length; i++) {
182
+ const a = solids[i];
183
+ for (let j = i + 1; j < solids.length && solids[j].min[0] < a.max[0]; j++) {
184
+ const b = solids[j];
185
+ if (a.group !== undefined && a.group === b.group) continue;
186
+ examined++;
187
+ // A prop entering a structure through its top surface is standing in it, which is
188
+ // the buried check's question, not this one's.
189
+ const [big, small] = volumeOf(a) >= volumeOf(b) ? [a, b] : [b, a];
190
+ if (!isProp(big, tol) && small.max[1] > big.max[1] && small.min[1] >= big.min[1]) continue;
191
+ const ox = overlap1(a, b, 0), oy = overlap1(a, b, 1), oz = overlap1(a, b, 2);
192
+ if (ox <= 0 || oy <= 0 || oz <= 0) continue;
193
+ const shared = ox * oy * oz;
194
+ if (shared < tol.penVolume) continue;
195
+ const smaller = Math.min(volumeOf(a), volumeOf(b));
196
+ const thinner = Math.min(...[0, 1, 2].map((axis) => Math.min(sizeOf(a, axis), sizeOf(b, axis))));
197
+ const depth = Math.min(ox, oy, oz);
198
+ const fraction = shared / smaller;
199
+ if (fraction > tol.penFraction || depth > thinner + tol.penSlack) {
200
+ findings.push({ id: `${a.id} + ${b.id}`, at: site({ min: [0, 1, 2].map((k) => Math.max(a.min[k], b.min[k])), max: [0, 1, 2].map((k) => Math.min(a.max[k], b.max[k])) }),
201
+ why: `${shared.toFixed(3)} m³ shared, ${(fraction * 100).toFixed(0)}% of the smaller part` });
202
+ }
203
+ }
204
+ }
205
+ return { name: "interpenetration", examined, findings };
206
+ }
207
+
208
+ /* coplanar faces --------------------------------------------------------------- */
209
+
210
+ function triNormal(t) {
211
+ const ux = t[3] - t[0], uy = t[4] - t[1], uz = t[5] - t[2], vx = t[6] - t[0], vy = t[7] - t[1], vz = t[8] - t[2];
212
+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
213
+ const len = Math.hypot(nx, ny, nz);
214
+ return len < 1e-12 ? null : [nx / len, ny / len, nz / len, len / 2];
215
+ }
216
+ /** Projects a triangle onto the plane's two largest axes, wound counter-clockwise. */
217
+ function project(t, n) {
218
+ const drop = Math.abs(n[0]) > Math.abs(n[1]) ? (Math.abs(n[0]) > Math.abs(n[2]) ? 0 : 2) : (Math.abs(n[1]) > Math.abs(n[2]) ? 1 : 2);
219
+ const [u, v] = [0, 1, 2].filter((a) => a !== drop);
220
+ const pts = [[t[u], t[v]], [t[3 + u], t[3 + v]], [t[6 + u], t[6 + v]]];
221
+ return area2(pts) < 0 ? pts.reverse() : pts;
222
+ }
223
+ function area2(poly) { let s = 0; for (let i = 0; i < poly.length; i++) { const [x0, y0] = poly[i], [x1, y1] = poly[(i + 1) % poly.length]; s += x0 * y1 - x1 * y0; } return s / 2; }
224
+ /** Sutherland-Hodgman: the part of `subject` inside the convex counter-clockwise `clip`. */
225
+ function clipPolygon(subject, clip) {
226
+ let output = subject;
227
+ for (let i = 0; i < clip.length && output.length; i++) {
228
+ const [ax, ay] = clip[i], [bx, by] = clip[(i + 1) % clip.length];
229
+ const inside = ([x, y]) => (bx - ax) * (y - ay) - (by - ay) * (x - ax) >= 0;
230
+ const input = output; output = [];
231
+ for (let j = 0; j < input.length; j++) {
232
+ const p = input[j], q = input[(j + 1) % input.length];
233
+ const pin = inside(p), qin = inside(q);
234
+ if (pin) output.push(p);
235
+ if (pin !== qin) {
236
+ const [px, py] = p, [qx, qy] = q;
237
+ const den = (bx - ax) * (qy - py) - (by - ay) * (qx - px);
238
+ if (Math.abs(den) > 1e-15) {
239
+ const s = ((bx - ax) * (ay - py) - (by - ay) * (ax - px)) / den;
240
+ output.push([px + s * (qx - px), py + s * (qy - py)]);
241
+ }
242
+ }
243
+ }
244
+ }
245
+ return output;
246
+ }
247
+ export function overlapArea(t1, t2, n) {
248
+ const poly = clipPolygon(project(t1, n), project(t2, n));
249
+ if (poly.length < 3) return 0;
250
+ // Projection onto an axis plane shrinks area by |n . axis|; undo it.
251
+ const scale = Math.max(Math.abs(n[0]), Math.abs(n[1]), Math.abs(n[2]));
252
+ return Math.abs(area2(poly)) / scale;
253
+ }
254
+
255
+ /**
256
+ * coplanar: two opaque faces in one plane, facing the same way, overlapping. Neither
257
+ * wins the depth test, so the seam crawls as the camera moves. Opposite-facing pairs
258
+ * are ignored (only one can face the camera) and so is a down-facing face lying on a
259
+ * floor (an underside nobody sees). Faces of one part are compared with faces of other
260
+ * parts only: inside one mesh, a quad's two triangles share an edge and overlap by zero.
261
+ */
262
+ export function checkCoplanar(scene, tol = TOLERANCES) {
263
+ const faces = [];
264
+ for (const p of scene.parts) {
265
+ if (p.visible === false || !isSolid(p) || p.decal) continue;
266
+ for (const t of p.triangles ?? boxTriangles(p)) {
267
+ const n = triNormal(t);
268
+ if (!n) continue;
269
+ const d = n[0] * t[0] + n[1] * t[1] + n[2] * t[2];
270
+ if (n[1] < -0.999 && (scene.floors ?? [groundAt(scene, t[0], t[2])]).some((f) => f !== null && Math.abs(-d - f) < tol.zEps)) continue;
271
+ faces.push({ part: p.id, group: p.group, t, n, d, min: [0, 1, 2].map((a) => Math.min(t[a], t[3 + a], t[6 + a])), max: [0, 1, 2].map((a) => Math.max(t[a], t[3 + a], t[6 + a])) });
272
+ }
273
+ }
274
+ const bins = new Map();
275
+ const keyOf = (f, slot) => `${Math.round(f.n[0] * 1000)},${Math.round(f.n[1] * 1000)},${Math.round(f.n[2] * 1000)},${slot}`;
276
+ for (const f of faces) {
277
+ const slot = Math.floor(f.d / tol.zEps);
278
+ const key = keyOf(f, slot);
279
+ if (!bins.has(key)) bins.set(key, []);
280
+ bins.get(key).push(f);
281
+ }
282
+ const pairs = new Map();
283
+ let examined = 0;
284
+ for (const f of faces) {
285
+ const slot = Math.floor(f.d / tol.zEps);
286
+ for (const s of [slot, slot + 1]) {
287
+ for (const g of bins.get(keyOf(f, s)) ?? []) {
288
+ if (g === f || g.part === f.part || (f.group !== undefined && f.group === g.group)) continue;
289
+ if (s === slot && g.part < f.part) continue; // count each cross-part pair once
290
+ if (f.n[0] * g.n[0] + f.n[1] * g.n[1] + f.n[2] * g.n[2] < 0.9999 || Math.abs(f.d - g.d) > tol.zEps) continue;
291
+ let apart = false;
292
+ for (let a = 0; a < 3; a++) if (f.min[a] > g.max[a] + tol.zEps || g.min[a] > f.max[a] + tol.zEps) { apart = true; break; }
293
+ if (apart) continue;
294
+ examined++;
295
+ const area = overlapArea(f.t, g.t, f.n);
296
+ if (area <= 0) continue;
297
+ const key = [f.part, g.part].sort().join(" + ");
298
+ const entry = pairs.get(key) ?? { area: 0, at: f.t.slice(0, 3) };
299
+ entry.area += area;
300
+ pairs.set(key, entry);
301
+ }
302
+ }
303
+ }
304
+ const findings = [...pairs].filter(([, e]) => e.area > tol.zArea).map(([id, e]) => ({ id, at: e.at.map((v) => Math.round(v * 100) / 100), area: e.area, why: `${e.area.toFixed(3)} m² of same-facing faces in one plane` }));
305
+ return { name: "coplanar", examined: faces.length, pairsCompared: examined, findings, area: findings.reduce((sum, f) => sum + f.area, 0) };
306
+ }
307
+
308
+ /** Visible solids that no collider covers and that give no reason for it. */
309
+ export function uncollided(scene) {
310
+ const colliders = scene.colliders ?? scene.parts.filter((p) => p.collider);
311
+ const ramps = scene.ramps ?? [];
312
+ const covered = (p) => p.collider === true
313
+ || colliders.some((c) => [0, 1, 2].every((a) => c.min[a] <= p.min[a] + 0.05 && c.max[a] >= p.max[a] - 0.05))
314
+ || ramps.some((r) => r.min[0] <= p.min[0] + 0.05 && r.max[0] >= p.max[0] - 0.05 && r.min[2] <= p.min[2] + 0.05 && r.max[2] >= p.max[2] - 0.05);
315
+ return scene.parts.filter((p) => p.visible !== false && isSolid(p) && !p.nocollide && !covered(p));
316
+ }
317
+
318
+ /** colliders: every visible solid either blocks a body or says why it does not. */
319
+ export function checkColliders(scene) {
320
+ const examined = scene.parts.filter((p) => p.visible !== false && isSolid(p)).length;
321
+ const findings = uncollided(scene).map((p) => ({ id: p.id, at: site(p), why: "drawn solid with no collider and no nocollide reason: a body walks through it" }));
322
+ return { name: "colliders", examined, findings };
323
+ }
324
+
325
+ /* the walk bot ---------------------------------------------------------------- */
326
+
327
+ function rampHeight(ramp, x, z) {
328
+ if (x < ramp.min[0] || x > ramp.max[0] || z < ramp.min[2] || z > ramp.max[2]) return null;
329
+ const axis = ramp.axis === "x" ? 0 : 2, at = axis === 0 ? x : z;
330
+ let t = (at - ramp.min[axis]) / (ramp.max[axis] - ramp.min[axis]);
331
+ if (ramp.rises === "negative") t = 1 - t;
332
+ return ramp.min[1] + t * (ramp.max[1] - ramp.min[1]);
333
+ }
334
+
335
+ /**
336
+ * A kinematic capsule driven with forward input only: no jump, ever. Support is the
337
+ * highest collider top or ramp surface under the body that is within one step of the
338
+ * feet; anything taller that overlaps the body blocks it, and the body slides along it.
339
+ */
340
+ export function createWalker(scene, tol = TOLERANCES) {
341
+ const boxes = (scene.colliders ?? scene.parts.filter((p) => p.collider)).filter((c) => sizeOf(c, 1) > 0);
342
+ const ramps = scene.ramps ?? [];
343
+ const r = tol.bodyRadius;
344
+ const circleHitsBox = (x, z, c) => {
345
+ const nx = Math.max(c.min[0], Math.min(x, c.max[0])), nz = Math.max(c.min[2], Math.min(z, c.max[2]));
346
+ return (x - nx) ** 2 + (z - nz) ** 2 < r * r - 1e-9;
347
+ };
348
+ function support(x, z, feet) {
349
+ let best = null;
350
+ const ground = groundAt(scene, x, z);
351
+ if (ground !== null && ground <= feet + tol.stepHeight) best = ground;
352
+ for (const c of boxes) if (c.max[1] <= feet + tol.stepHeight + 1e-9 && circleHitsBox(x, z, c) && (best === null || c.max[1] > best)) best = c.max[1];
353
+ for (const ramp of ramps) {
354
+ const h = rampHeight(ramp, x, z);
355
+ if (h !== null && h <= feet + tol.stepHeight && (best === null || h > best)) best = h;
356
+ }
357
+ return best;
358
+ }
359
+ function blocked(x, z, feet) {
360
+ for (const c of boxes) {
361
+ if (c.max[1] <= feet + tol.stepHeight + 1e-9 || c.min[1] >= feet + tol.bodyHeight) continue;
362
+ if (circleHitsBox(x, z, c)) return true;
363
+ }
364
+ return false;
365
+ }
366
+ return {
367
+ support, blocked,
368
+ /** One fixed step toward `goal`. Returns the new position. */
369
+ step(pos, goal, dt) {
370
+ const dx = goal[0] - pos[0], dz = goal[2] - pos[2], dist = Math.hypot(dx, dz);
371
+ let [x, y, z] = pos;
372
+ if (dist > 1e-6) {
373
+ const travel = Math.min(dist, tol.walkSpeed * dt);
374
+ const substeps = Math.max(1, Math.ceil(travel / Math.max(0.05, r * 0.45)));
375
+ const sx = (dx / dist) * travel / substeps, sz = (dz / dist) * travel / substeps;
376
+ for (let i = 0; i < substeps; i++) {
377
+ for (const [mx, mz] of [[sx, sz], [sx, 0], [0, sz]]) {
378
+ const nx = x + mx, nz = z + mz;
379
+ const under = support(nx, nz, y);
380
+ if (blocked(nx, nz, y) || under === null) continue;
381
+ x = nx; z = nz;
382
+ // Step up onto the landing; fall at most one step per substep downhill.
383
+ y = under > y ? under : Math.max(under, y - tol.stepHeight);
384
+ break;
385
+ }
386
+ }
387
+ }
388
+ const under = support(x, z, y);
389
+ if (under !== null && under < y) y = Math.max(under, y - 9.8 * dt);
390
+ return [x, y, z];
391
+ },
392
+ };
393
+ }
394
+
395
+ /** Walks each route forward-only. A route passes when the body arrives without stalling. */
396
+ export function checkStairs(scene, tol = TOLERANCES) {
397
+ const routes = scene.routes ?? [];
398
+ const walker = createWalker(scene, tol);
399
+ const visibleUncollided = uncollided(scene);
400
+ const findings = [];
401
+ const dt = 1 / 60;
402
+ for (const route of routes) {
403
+ let pos = [...route.from];
404
+ let lastProgress = 0, best = Infinity, climbed = 0;
405
+ const goal = route.to;
406
+ let arrived = false;
407
+ // One finding per route and cause. The loop runs every frame, so half a second
408
+ // inside one uncollided wall was thirty identical findings, and formatReport's cap
409
+ // hid the different ones behind them.
410
+ const said = new Set();
411
+ const once = (why) => { if (!said.has(why)) { said.add(why); findings.push({ id: route.name, at: pos.map((v) => Math.round(v * 100) / 100), why }); } };
412
+ for (let time = 0; time < tol.routeSeconds; time += dt) {
413
+ const before = pos[1];
414
+ pos = walker.step(pos, goal, dt);
415
+ climbed = Math.max(climbed, pos[1] - route.from[1]);
416
+ if (pos[1] - before > tol.stepHeight + 1e-6) once("rose more than one step in a frame");
417
+ const remaining = Math.hypot(goal[0] - pos[0], goal[2] - pos[2]);
418
+ if (remaining < best - 0.05) { best = remaining; lastProgress = time; }
419
+ if (remaining < 0.25 && Math.abs(pos[1] - goal[1]) <= tol.stepHeight) { arrived = true; break; }
420
+ if (time - lastProgress > tol.stuckSeconds) break;
421
+ for (const p of visibleUncollided) {
422
+ if (pos[0] > p.min[0] && pos[0] < p.max[0] && pos[2] > p.min[2] && pos[2] < p.max[2] && pos[1] + 1 > p.min[1] && pos[1] < p.max[1]) {
423
+ once(`walked through ${p.id}, which is drawn solid and has no collider`);
424
+ }
425
+ }
426
+ }
427
+ if (!arrived) findings.push({ id: route.name, at: pos.map((v) => Math.round(v * 100) / 100), why: `stuck holding forward with no jump, ${best.toFixed(2)} m short, after climbing ${climbed.toFixed(2)} m` });
428
+ }
429
+ return { name: "stairs", examined: routes.length, findings };
430
+ }
431
+
432
+ /* ------------------------------------------------------------------- the plants */
433
+
434
+ const clone = (scene) => ({ ...scene, parts: scene.parts.map((p) => ({ ...p })), colliders: scene.colliders?.map((c) => ({ ...c })), ramps: scene.ramps?.map((r) => ({ ...r })), routes: scene.routes?.map((r) => ({ ...r })) });
435
+
436
+ /**
437
+ * Where a plant goes: open ground on the real scene, so a plant proves the check on
438
+ * this scene's own geometry. The site is the top of a grounded structure larger than a
439
+ * prop, with a clear column above it wide enough for every plant, searched on a grid.
440
+ * A plant that lands inside an existing prop proves nothing about the rule, so a site
441
+ * with anything in the column is skipped.
442
+ */
443
+ function plantSite(scene, tol) {
444
+ const visible = scene.parts.filter((p) => p.visible !== false);
445
+ const floating = new Set(checkFloat(scene, tol).findings.map((f) => f.id));
446
+ const floors = visible.filter((p) => isSolid(p) && !p.hangs && !floating.has(p.id) && sizeOf(p, 0) > tol.propScale + 0.5 && sizeOf(p, 2) > tol.propScale + 0.5)
447
+ .sort((a, b) => sizeOf(b, 0) * sizeOf(b, 2) - sizeOf(a, 0) * sizeOf(a, 2));
448
+ const half = 1.0, height = 3;
449
+ for (const floor of floors) {
450
+ const top = floor.max[1];
451
+ for (let x = floor.min[0] + half; x <= floor.max[0] - half; x += 0.5) {
452
+ for (let z = floor.min[2] + half; z <= floor.max[2] - half; z += 0.5) {
453
+ const column = { min: [x - half, top + 0.001, z - half], max: [x + half, top + height, z + half] };
454
+ if (visible.some((p) => p !== floor && overlap1(p, column, 0) > 0 && overlap1(p, column, 1) > 0 && overlap1(p, column, 2) > 0)) continue;
455
+ return { x, y: top, z, floor };
456
+ }
457
+ }
458
+ }
459
+ return null;
460
+ }
461
+
462
+ const box = (id, x, y, z, w, h, d, extra = {}) => ({ id, min: [x - w / 2, y, z - d / 2], max: [x + w / 2, y + h, z + d / 2], collider: true, ...extra });
463
+
464
+ /** A synthetic flight of stairs with one riser too tall, and an honest flight beside it. */
465
+ export function stairScene(riser = 0.17, badRiser = null) {
466
+ const parts = [box("ground", 0, -1, 0, 40, 1, 40)];
467
+ let y = 0;
468
+ for (let i = 0; i < 12; i++) {
469
+ const rise = badRiser !== null && i === 6 ? badRiser : riser;
470
+ y += rise;
471
+ parts.push(box(`tread${i}`, 0, 0, -i * 0.3 - 0.15, 1.6, y, 0.3));
472
+ }
473
+ parts.push(box("landing", 0, 0, -3.6 - 1.5, 3, y, 3));
474
+ return { parts, groundY: 0, routes: [{ name: badRiser ? "planted stairs" : "honest stairs", from: [0, 0, 3], to: [0, y, -5.5] }] };
475
+ }
476
+
477
+ /**
478
+ * Each plant returns the scene with a defect added and the id the check must report.
479
+ * Plants that need a site take it from the real scene; if the scene offers none, the
480
+ * plant reports that rather than passing.
481
+ */
482
+ const PLANTS = {
483
+ float(scene, tol) {
484
+ const s = plantSite(scene, tol); if (!s) return null;
485
+ const copy = clone(scene);
486
+ copy.parts.push(box("planted-float", s.x, s.y + tol.floatTol * 2.5, s.z, 0.5, 0.5, 0.5));
487
+ return { scene: copy, id: "planted-float" };
488
+ },
489
+ buried(scene, tol) {
490
+ const s = plantSite(scene, tol); if (!s) return null;
491
+ const copy = clone(scene);
492
+ copy.parts.push(box("planted-buried", s.x, s.y - tol.sinkTol * 2, s.z, 0.6, 1.2, 0.6, { prop: true }));
493
+ return { scene: copy, id: "planted-buried" };
494
+ },
495
+ interpenetration(scene, tol) {
496
+ const s = plantSite(scene, tol); if (!s) return null;
497
+ const copy = clone(scene);
498
+ copy.parts.push(box("planted-crate-a", s.x - 0.2, s.y, s.z, 0.8, 0.8, 0.8), box("planted-crate-b", s.x + 0.2, s.y, s.z, 0.8, 0.8, 0.8));
499
+ return { scene: copy, id: "planted-crate-a + planted-crate-b" };
500
+ },
501
+ coplanar(scene, tol) {
502
+ const s = plantSite(scene, tol); if (!s) return null;
503
+ const copy = clone(scene);
504
+ copy.parts.push(box("planted-panel-a", s.x - 0.25, s.y, s.z, 1, 1, 0.2), box("planted-panel-b", s.x + 0.25, s.y + 0.3, s.z, 1, 1, 0.2));
505
+ return { scene: copy, id: "planted-panel-a + planted-panel-b" };
506
+ },
507
+ colliders(scene, tol) {
508
+ const s = plantSite(scene, tol); if (!s) return null;
509
+ const copy = clone(scene);
510
+ copy.parts.push(box("planted-ghost-wall", s.x, s.y, s.z, 1.6, 2, 0.2, { collider: false }));
511
+ return { scene: copy, id: "planted-ghost-wall" };
512
+ },
513
+ stairs(_scene, tol) {
514
+ return { scene: stairScene(0.17, tol.stepHeight + 0.08), id: "planted stairs" };
515
+ },
516
+ };
517
+
518
+ const CHECKS = { float: checkFloat, buried: checkBuried, interpenetration: checkInterpenetration, coplanar: checkCoplanar, colliders: checkColliders, stairs: checkStairs };
519
+
520
+ /**
521
+ * Runs every check (or `only`), each after its plant. Returns
522
+ * `{ ok, failures, checks: [{ name, examined, findings, plant }] }`. A finding is a
523
+ * defect in the scene; a failure is a defect in the instrument or an unexamined check.
524
+ */
525
+ export function runSceneAudit(scene, { tolerances = {}, only, notApplicable = {} } = {}) {
526
+ const tol = { ...TOLERANCES, ...tolerances };
527
+ const failures = [], checks = [];
528
+ for (const [name, check] of Object.entries(CHECKS)) {
529
+ if (only && !only.includes(name)) continue;
530
+ const reason = notApplicable[name];
531
+ if (typeof reason === "string" && reason.trim()) {
532
+ checks.push({ name, examined: 0, findings: [], plant: "not applicable", reason: reason.trim() });
533
+ continue;
534
+ }
535
+ const plant = PLANTS[name](scene, tol);
536
+ let plantState = "caught";
537
+ if (!plant) { plantState = "no site"; failures.push(`${name}: found no open grounded floor larger than a prop with a clear 2 m column to plant a defect on`); }
538
+ else if (!check(plant.scene, tol).findings.some((f) => f.id === plant.id)) { plantState = "missed"; failures.push(`${name}: the planted defect ${plant.id} was not found, so this check cannot be trusted`); }
539
+ const result = check(scene, tol);
540
+ if (result.examined === 0) failures.push(`${name}: examined nothing${name === "stairs" ? "; add scene.routes for every staircase" : ""}`);
541
+ checks.push({ ...result, plant: plantState });
542
+ }
543
+ const findings = checks.reduce((n, c) => n + c.findings.length, 0);
544
+ return { ok: failures.length === 0 && findings === 0, failures, checks };
545
+ }
546
+
547
+ export function formatReport(report) {
548
+ const lines = [];
549
+ for (const c of report.checks) {
550
+ if (c.reason) { lines.push(`${c.name.padEnd(17)} not applicable: ${c.reason}`); continue; }
551
+ lines.push(`${c.name.padEnd(17)} examined ${String(c.examined).padStart(6)} findings ${String(c.findings.length).padStart(4)} plant ${c.plant}`);
552
+ for (const f of c.findings.slice(0, 20)) lines.push(` ${f.id} at (${f.at.join(", ")}): ${f.why}`);
553
+ if (c.findings.length > 20) lines.push(` and ${c.findings.length - 20} more`);
554
+ }
555
+ for (const failure of report.failures) lines.push(`FAILED ${failure}`);
556
+ lines.push(report.ok ? "Scene audit passed." : "Scene audit did not pass.");
557
+ return lines.join("\n");
558
+ }
559
+
560
+ /* --------------------------------------------------------------- three.js adapter */
561
+
562
+ /**
563
+ * Reads a three.js scene into the audit's shape. Pass the THREE namespace the game
564
+ * already imports. Mesh flags come from `userData`: `collider`, `nocollide` (a reason),
565
+ * `hangs` (a reason), `group`, `prop`, `decal`. Transparent and alpha-tested materials
566
+ * are not opaque volume. `colliders` may be Box3s or meshes from the collision layer.
567
+ */
568
+ export function fromThreeScene(THREE, root, { colliders = [], groundY = null, floors, triangles = true } = {}) {
569
+ root.updateMatrixWorld(true);
570
+ const parts = [];
571
+ const v = new THREE.Vector3();
572
+ root.traverse((object) => {
573
+ if (!object.isMesh || !object.visible || object.isSkinnedMesh) return;
574
+ const material = Array.isArray(object.material) ? object.material[0] : object.material;
575
+ const opaque = !material || (!material.transparent && (material.alphaTest ?? 0) === 0 && (material.opacity ?? 1) >= 1);
576
+ const bounds = new THREE.Box3().setFromObject(object);
577
+ if (bounds.isEmpty()) return;
578
+ const data = object.userData ?? {};
579
+ const part = { id: object.name || object.uuid, min: bounds.min.toArray(), max: bounds.max.toArray(), solid: opaque && !data.decal,
580
+ collider: data.collider === true, nocollide: data.nocollide, hangs: data.hangs, group: data.group, prop: data.prop, decal: data.decal || material?.polygonOffset };
581
+ if (triangles && object.geometry?.attributes?.position) {
582
+ const position = object.geometry.attributes.position, index = object.geometry.index;
583
+ const count = index ? index.count : position.count;
584
+ const tris = [];
585
+ for (let i = 0; i + 2 < count; i += 3) {
586
+ const t = [];
587
+ for (let k = 0; k < 3; k++) { v.fromBufferAttribute(position, index ? index.getX(i + k) : i + k).applyMatrix4(object.matrixWorld); t.push(v.x, v.y, v.z); }
588
+ tris.push(t);
589
+ }
590
+ part.triangles = tris;
591
+ }
592
+ parts.push(part);
593
+ });
594
+ const boxes = colliders.map((c, i) => {
595
+ const b = c.isBox3 ? c : new THREE.Box3().setFromObject(c);
596
+ return { id: c.name || `collider${i}`, min: b.min.toArray(), max: b.max.toArray() };
597
+ });
598
+ return { parts, colliders: boxes.length ? boxes : undefined, groundY, floors };
599
+ }