Skip to content

You can now generate creatures directly within your project. Drop the open-source into your Agent, and start prompting what you want.

JavaScript

anyCreature 1.3.2

Ariescar88041c1efb31
diff --git a/.gitignore b/.gitignore
index 1e3c9e2..7b13ce5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,10 +23,6 @@ gate.json
# the operator's saved signature (personal data — never commit)
.anyCreature.json
-# synccheck's site-specific leak words: the names of whatever else lives on
-# this disk. They belong in the scanner, never in the tree it scans.
-harness/leakwords.local.txt
-
# scratch / editor / OS
*.log
*.bak
@@ -41,3 +37,7 @@ Thumbs.db
# large archives: ship these as GitHub Release attachments, not repo objects.
# Once a big blob is pushed it stays in history even after deletion.
*.zip
+
+# synccheck's site-specific leak words: the names of whatever else lives on
+# this disk. They belong in the scanner, never in the tree it scans.
+harness/leakwords.local.txt
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ae5e5ed..2e4dbdc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,214 @@
# CHANGELOG
+## 1.3.2 — the creature declares what its parts are for, and the engine makes it pay
+
+**The declaration**
+
+- `function` on each chain: `axis` / `locomotion` / `effector` / `ornament`. Manufacturing
+ vocabulary only — nothing about damage, hardness or worth. A part bolted to a chain
+ inherits that chain's function, so the blade on the neck is covered without naming it.
+- Six checks make the declaration cost something. A label nobody verifies rots, and each
+ of the six blocks a defect class the engine could not see before.
+
+**Joint limits are declared, and the body is asked whether it agrees**
+
+- `joint_range` on each joint: degrees per axis, in the joint's own frame, the same axis
+ names the tracks use. An axis left out is LOCKED at 0; `"free"` opts one out. The L side
+ is authored and the R side is generated — `ry`/`rz` negate, which swaps the interval's
+ ends — because a hand-written mirror is the bug this release just finished fixing.
+- The numbers are authored because a spec writer already knows a knee is a hinge and an
+ elbow does not twist, and that is not computable from vertices. They are then CHECKED
+ because the author does not know how thick THIS body is: every declared bound is swept
+ against the geometry, and a limit the body cannot reach blocks with the angle that can.
+ A gorilla's shoulder swings 60° back; a gorilla with a wrecking ball hanging off a crane
+ on its back stops at 50°, and only the sweep knows that.
+- Three failures with three different fixes: `undeclared` (a clip turns a joint with no
+ entry), `overrun` (a track leaves its own interval), `unreachable` (the body collides
+ first).
+
+**Every part has a name, and the name reaches the file**
+
+- `name` is required on every part and must be unique. A material is a CLASS — primitives
+ merge one per material so a forty-plate body does not ship forty draw calls — so a
+ material name can never say WHICH part something is. The same `paw` material sits on a
+ foot pad and on a nose-leaf, and anything aggregating by material adds them together.
+- `asset.extras.part_spans` records, per part, the primitive and the `[first, count]`
+ vertex range it owns. Same materials, same primitives, same bytes of geometry: the
+ identity simply stops being thrown away at merge time. Mirrored twins carry `.R`, an
+ eye pair carries `.L`/`.R`.
+- This was not cosmetic. `self_clip` keyed its meshes by material and host, so thirteen
+ `steel_bolt` parts on one creature collapsed to one entry and twelve of them were never
+ narrow-phase tested. With names, the check found a real interpenetration on the first
+ rebuild.
+
+**Mirroring was truncating every mirrored limb**
+
+- `mirrorTrack` resamples instead of shifting keys. The old code mapped a key at `t=1` onto
+ `t=phase`, where it collided with the key already there and the sort dropped the rest of
+ the track — the mirrored limb froze partway through the cycle. **Every mirrored track was
+ affected.** Fixing it also cleared `root_drive` failures that were downstream of it.
+
+**Checks**
+
+- `gait_footfall` — a step must land in FRONT of where it lifts, measured against the foot's
+ own liftoff point, not the hip: a bird's hip sits inside the body and a hip-relative test
+ calls a correct walk wrong. The contact window now expands contiguously from the foot's
+ lowest frame; thresholding the whole cycle split the window the moment the pelvis bobbed.
+- `effector_leads` — at the frame the attack reaches furthest forward, the declared effector
+ must be the frontmost mesh. The frame that matters is peak reach, not the last frame.
+- `attack_windup` — 5% back, or 15% out to the side. Either route passes; a weapon that
+ cannot pull straight back without sweeping through the body goes around.
+- `self_clip` — swept self-collision. Sphere proxies bound to the dominant bone for the broad
+ phase, real mesh distance only for the pairs it names: 0.3–0.7 s for all three clips.
+ Pairs that already touch at rest are excluded — that is `part_overlap`'s question.
+- `clip_closes` — a clip that does not loop still snaps back when it ends.
+- `ground_clip` — nothing below the plane the creature stands on. The receiving physics
+ builds its collision proxy from the mesh; a hand under the floor lifts the whole body.
+
+**`harness/autofix.mjs`**
+
+- The arithmetic corrections, run before a round is spent: the ground offset onto the root's
+ `ty` (chasing it with joint angles does not converge), loop closure, and compensation for
+ joints that must hold their own aim while the body turns for some other purpose.
+- Compensation is written as the parent's inverse rotation, not solved by iterating on
+ angles — past vertical the `atan2` jumps and the correction diverges.
+- **Compensation is subordinate to the purpose.** A head aimed forward pushes its muzzle out
+ in front; if that overtakes the effector the strike reads as a head-butt. The share is
+ solved for, not assumed.
+- It never touches decisions: which way a leg swings, what the creature attacks with, how far
+ it lunges. Those stay with the designer.
+
+**The browser is gone**
+
+- Nothing in this package launches a renderer any more. `setup.sh` installs no Chromium,
+ so the class of install failures where a blocked CDN stalls setup is gone with it, and
+ the harness is `three` plus numpy/pillow/scipy.
+- Every number the renderer used to produce is arithmetic on the vertices, and now lives
+ in ONE file: `harness/outline.py` already owned the silhouettes and the z-buffer that
+ attributes part shares, so it took the rest. Part shares, the colour numbers, the clip
+ and skin list, per-part bounding boxes — all of it read from the file it was already
+ reading. `judge.mjs` stopped taking its own photograph of the same model and now checks
+ its claims against outline's numbers.
+- The colour ruler is verified, not asserted: run both ways over a reference shelf, the
+ saturated-area measure agrees with the browser's at **r=0.999** and the same thresholds
+ carry over untouched. `style_dark` / `style_light` deliberately changed meaning — they
+ now read the creature's OWN colour instead of a studio render of it, which is what the
+ designer controls; the two correlate at r≈0.96 but are not the same scale, so a
+ pre-1.3.2 threshold needs re-picking once.
+- `hero.png` is projected, not rendered. The entire L1–L8 shading stack is baked into the
+ vertex colours at build time, so lighting it again in three.js was lighting a
+ photograph. Same z-buffer, transparent background, framed to its own content.
+- Two view conventions moved to the tool that survived: `side` is the LONG profile rather
+ than a fixed +X camera (the old one showed a spread-winged creature edge-on and called
+ it a side view), and the three-quarter view is `hero` — `tq` still resolves to it.
+- Retired: `silmetrics.mjs`, `maskmetrics.py`, `hero.mjs`, `pwlaunch.mjs`, `pwprobe.mjs`,
+ `calibrate.py`. The SHARED-TOOL QUEUE that named their duplicate measures now prints
+ nothing. `synccheck.py` refuses any file that imports playwright or launches chromium.
+
+**The trap list became code where it could**
+
+- Four engine traps that were previously only written down are now the engine's own words, at the moment they happen, instead of a document
+ someone has to have read:
+ - a `fin` whose outline has two nearly-coincident points is refused BY NAME, with the
+ two indices and the distance. It used to extrude into flipped triangles and surface
+ later as a `mesh_integrity` count with no address, costing a round of bisection.
+ - a `joints_R` entry written relative to itself says so, instead of "dependency cycle",
+ which sends the author hunting for a loop between joints that does not exist.
+ - `eye_pupil` names a lone eye sphere for what it is: a flat coloured disc, which at
+ reading size is a sticker. An eye reads by the value step between iris and pupil.
+ - `part_overlap` above.
+- The rest of that list is process advice already covered by the cards, or notes that
+ belong to the operator. It does not ship as a document.
+
+**part_overlap was comparing boxes**
+
+- The check that reports one part sitting inside another tested A's vertices against B's
+ axis-aligned BOUNDING BOX. A box is not a shape: a 2.8 m spear's box contains any hand
+ gripping it, so the check reported the hand as buried in the spear. The signal was not
+ noisy, it was wrong, and acting on it removes parts that are correctly placed. Same error
+ class as the sphere below.
+- Measured against the real surfaces now. On a reference creature the count halved
+ (32 → 16) and what disappeared was box artefact.
+- Two severities, because they are different problems: COMPLETELY buried is invisible
+ geometry that still costs triangles, and partial is a seam, which is usually the point.
+
+**The signature has to say whether it is visible in black**
+
+- Gate 1 reads a 48px silhouette, which has exactly one dimension. A feature made of
+ colour, of COUNT (nine faces, one leg), of something soft, or of a face has no boundary
+ in one — so betting a creature's identity on it asks Gate 1 to measure what it cannot
+ see.
+- `brief.py` now blocks a signature slot that does not end `silhouette: yes` or
+ `silhouette: no`. It does not forbid the bet; it forbids it being an accident. "No" is
+ allowed and often right — it declares that MID or HIGH carries the feature and the body
+ has to carry the identity on its own, decided before the rounds are paid for.
+
+**The trap list ships**
+
+- `cards/PITMAP.md` — facts about this engine that are expensive to discover by trial: the
+ shapes it refuses, the fields that must be declared a particular way, the corrections
+ that never converge. Card 00 sends you there before you author anything.
+
+**A volume is not a string of spheres**
+
+- `root_containment`, `limb_clearance` and `part_attachment` all asked the same question —
+ "is this point inside that volume, and if not, how far out?" — and all three answered it
+ by finding the nearest ring CENTRE and comparing against a SPHERE of that ring's widest
+ radius. A volume is a lofted tube, and that sphere bulges past the END CAP by a whole
+ half-width. The error is therefore worst exactly where it matters most: at the end of a
+ chain, which is where the next chain attaches. A torso 0.80 m wide handed out 0.4 m of
+ phantom "inside" straight off the chest, so a head sitting 0.33 m in front of the last
+ ring centre was declared buried while its real distance to the surface was 0.24 m — a
+ floating head, attached only by two stray vertices of a foreleg.
+- `engine/core/inside.js` measures against the triangles the file will actually ship, and
+ all three checks now call it. The sign comes from the closest triangle's own normal, not
+ from a ray cast, because an attached chain leaves its root ring open on purpose and ray
+ casting needs a closed surface.
+- `root_containment` now judges by the ring's MEDIAN rather than a count of points. A ring
+ meets a CURVED host, so a few of its points always poke out; across a reference set of
+ 102 joints the median sits inside on 95 of them, and the 7 it does not are the ones you
+ can see.
+- The corrected distance is stricter than the sphere was hiding: the same 1.5%-of-height
+ tolerance that `part_attachment` always had now sits on the 99th percentile of that set
+ instead of nowhere, and it catches parts standing 4–6 cm clear of their host.
+
+**One creature is one connected body**
+
+- `body_islands` walks every piece, unions the ones that share material, and refuses
+ anything that comes back as more than one object. The weld is 3% of model height at
+ three points — two stray vertices poking in is a coincidence, not an attachment.
+- It exists because the three checks above all ask a LOCAL question (is this piece seated
+ in ITS host) and the failure was global, and because a silhouette cannot see it either:
+ a head floating inside the outline is not a hole in the mask.
+- 3% is a floor, not a target. Well-built parts sit anywhere from fully embedded to ~3% of
+ height off their host and there is no gap in that distribution to put a threshold in, so
+ this takes the loosest value that is still correct. The failure it exists for is 9.3% —
+ three times the bar.
+
+**Gate 1 stopped grading itself**
+
+- `identity.py` used to ask you which rank the brief's noun reached, and one judgment
+ sat under that number: *does "hound" count as "wolf"?* The only party available to make
+ it was the party being graded. A brief can already carry an accepted list, and nothing
+ compared the reader's words against it.
+- Now you hand over the reader's words, verbatim and in order (`--guesses side="…"`), and
+ the machine matches them against the brief's accepted list. Widening the family is still
+ the designer's call — it just has to happen in the brief, before the geometry exists,
+ instead of at r3 with a shape to defend.
+- `brief.py` blocks an identity slot with no accepted list. It is one line, it costs
+ nothing to write generously, and it has to be on the record.
+
+**Housekeeping**
+
+- `synccheck.py` refuses any file named `DEVLOG*`: a lab notebook never ships, and the
+ filename is the only rule that works in every language.
+- `example/wolf.json` builds green under the 1.3.2 checks: named parts, declared joint
+ limits, and a stride that no longer walks the hind paw through the front one. The
+ shipped example is the reference the cards point at; it has to pass its own gates.
+- `outline.py` says so out loud when scipy is missing. It used to return four keys short
+ — protrusions, thinnest feature, convexity, mirror symmetry — so the legibility and
+ boldness gates had nothing to read and every build passed them by default.
+
## 1.3.1 — reads are scored, the brief is checked, and everything computable is computed
**Publishing hands back two links, and the second one is checked (2026-09-03)**
diff --git a/MANUAL.md b/MANUAL.md
index 070fdfd..eb05541 100644
--- a/MANUAL.md
+++ b/MANUAL.md
@@ -1,4 +1,4 @@
-# anyCreature 1.3.1 — text → game-ready 3D creature, one shot
+# anyCreature 1.3.2 — text → game-ready 3D creature, one shot
> **STOP — read this before you write a single line of code.**
> You do not need to build a GLB writer, a renderer, a screenshot tool, a
@@ -49,17 +49,18 @@ README.md repository front page (humans)
LICENSE MIT
THIRD-PARTY-NOTICES.md bundled + installed dependency licences
SECURITY.md local servers, the public key, untrusted input
-VERSION 1.3.1
+VERSION 1.3.2
setup.sh deps + calibration self-check
cards/ 00_START · 01_LOW · 02_MID · 03_HIGH · 04_SHIP · SYNTAX.md
engine/ cli.js + core/ — the ACS engine v2
core/normals.js angle-weighted normals + `smooth_angle` creases (bodies stay smooth)
harness/
- silmetrics.mjs 4-view silhouettes (front/side/top/hero45) + numbers + 24/48px thumbs
- maskmetrics.py per-view measures + dullness flags (sq_fill / mirror_sym / straight_max)
- judge.mjs claims judge (part shares, focal contrast, styles, saturated area, rig/anim/tri)
- deliver.py stamped GLB + showroom viewer + hero shots + backup upload pack
- hero.mjs hero.png (1024² transparent 45°) + hero.jpg (studio grey)
+ outline.py THE measuring tool: 4-view silhouettes + thumbs, layout and boldness
+ measures, per-part shares off a z-buffer, colour off the baked albedo,
+ and the hero shot. All from the vertices — no browser anywhere
+ judge.mjs claims judge over outline.py's numbers (part shares, focal contrast,
+ styles, saturated area, rig/anim/tri)
+ deliver.py stamped GLB + showroom viewer + hero.png + backup upload pack
publish.mjs Gobkit publisher — ONLY after the user's explicit yes (card 04).
ALWAYS attempt the upload; the drag-and-drop page is the
fallback for a `blocked` result, never the opening move
@@ -111,7 +112,7 @@ features (four wings) still stagger. Model-level looks are the final judge.
Card 04 is the whole flow, now ONE command (`harness/ship.py`): gate stamp → name + signature questions (once;
`~/.anyCreature.json` remembers the signature) → `deliver.py` (stamped GLB,
-offline showroom viewer, hero shots, backup upload pack) → the share ask LAST →
+offline showroom viewer, hero.png, backup upload pack) → the share ask LAST →
`publish.mjs` only on an explicit yes — and then RUN it, never assume the
environment is offline. hero.png must be attached or the listing waits for a
human reviewer. CC0 is stamped at consent time, not before.
diff --git a/README.md b/README.md
index 20f0b7b..8875145 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@ two questions, and delivers a skinned, animated, vertex-coloured, AO-baked GLB p
offline showroom viewer.
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
-[![Version](https://img.shields.io/badge/version-1.3.1-green.svg)](CHANGELOG.md)
+[![Version](https://img.shields.io/badge/version-1.3.2-green.svg)](CHANGELOG.md)
[![Engine](https://img.shields.io/badge/engine-zero%20dependencies-brightgreen.svg)](engine)
[![Output](https://img.shields.io/badge/output-glTF%202.0-000000.svg)](https://www.khronos.org/gltf/)
[![Tooling](https://img.shields.io/badge/tooling-Node%2018%2B%20%C2%B7%20Python%203.9%2B-3776ab.svg)](setup.sh)
@@ -143,14 +143,17 @@ Form beats obedience, everywhere.
- **Isolated-part blind reads misfire on dome-plus-hanging-tube heads.** Elephants and
birds get read as something else when the head is shown alone; put the same head back
on the body and it reads fine. Trust the whole-body read when the two disagree.
-- **Cost scales with the creature.** Treat the triangle budget in
- `harness/claims.json` as an estimate rather than data.
-- **Splitting the modelling across subagents costs more, not less.** One agent
- start-to-finish beats a chain of short-lived agents (skeleton → parts → anims →
- verify) on tokens, wall clock and turns alike. Onboarding is not the cause —
- every fresh agent reads the same ground truth. The cause is re-derivation: work
- the previous agent had already done and could not hand over. Iron law 9 in card
- 00 states the rule.
+- **The budgets are calibrated on the heaviest class of creature only.** A simpler one
+ should cost less, but nothing lighter has been calibrated — treat the triangle budget
+ in `harness/claims.json` as an estimate rather than data.
+- **Splitting the modelling across subagents costs more, not less.** Same creature,
+ same green build, measured both ways: one agent start-to-finish against four
+ short-lived agents in a chain (skeleton → parts → anims → verify). The chain was
+ worse on every axis. Onboarding was not the cause — every fresh agent read the
+ same ground truth, a small fraction of either bill — the cause was re-derivation:
+ work the previous agent had already done and could not hand over. Iron law 9 in
+ card 00 states the rule; this is the measurement behind it. Two repetitions per arm, all four builds passed, so
+ this fixes the direction and not the distribution.
- **`part_attachment` and `mirror_distortion` are new in 1.2.0.** Specs authored against
an older version may now be blocked. That is usually the checker being right, but it
is a breaking change, not a silent improvement.
@@ -160,29 +163,28 @@ Form beats obedience, everywhere.
(`example_copy`), because a thin order is not permission to ship a recoloured
wolf. Read it for syntax, not for
animation coverage.
-- **The engine has zero dependencies; the tooling does not.** Every render and measure
- tool drives headless Chromium through playwright. If playwright will not install, you
- can still compile creatures — you just cannot measure them, and the gates are the
- point.
+- **The engine has zero dependencies; the tooling needs numpy, pillow and scipy.**
+ Nothing here launches a browser: as of 1.3.2 every silhouette, share, colour number
+ and even the hero shot is computed from the vertices. scipy is the one that matters —
+ without it the legibility and boldness measures do not compute, and a gate with
+ nothing to read passes everything.
## Scripts
| Script | Role |
|---|---|
| `engine/cli.js` | Spec → GLB. The whole engine interface. |
-| `harness/silmetrics.mjs` | Renders the four silhouettes and the 24px thumbnail; emits the layout metrics. |
-| `harness/maskmetrics.py` | Per-view mask measures and dullness flags (`sq_fill`, `mirror_sym`, `straight_max`). |
-| `harness/judge.mjs` | Claims judge — part shares, focal contrast, saturated area, rig/anim/triangle budgets. |
-| `harness/hero.mjs` | `hero.png` (1024² transparent, 45°) and `hero.jpg` over studio grey. |
-| `harness/deliver.py` | Stamps identity into the GLB, writes the offline showroom viewer, builds the upload pack. |
+| `harness/outline.py` | THE measuring tool. Silhouettes, thumbnails, layout and boldness measures, per-part shares, colour, and `hero.png` — all projected from the vertices. |
+| `harness/judge.mjs` | Claims judge over those numbers — part shares, focal contrast, saturated area, rig/anim/triangle budgets. |
+| `harness/deliver.py` | Stamps identity into the GLB, writes the offline showroom viewer and `hero.png`, builds the upload pack. |
| `harness/publish.mjs` | Gobkit publisher. Only runs after an explicit yes, and always tries the upload before offering the manual page. |
-| `harness/calibrate.py` | The red/green self-check `setup.sh` runs. |
## Requirements
-Node 18+ and Python 3.9+. Windows: run `setup.ps1` in PowerShell (or `setup.sh` in Git Bash/WSL). `setup.sh` installs `three`, `playwright`, `numpy`, `pillow`
-and `scipy`, then runs the calibration self-check. The engine alone needs nothing but
-Node; the dependencies are for the measuring and render tools.
+Node 18+ and Python 3.9+. Windows: run `setup.ps1` in PowerShell (or `setup.sh` in Git Bash/WSL). `setup.sh` installs `three`, `numpy`, `pillow` and `scipy`,
+then builds the shipped example end to end as a self-check. No browser is installed
+or launched. The engine alone needs nothing but Node; the dependencies are for the
+measuring tools and the offline viewer.
## Output contract
diff --git a/SECURITY.md b/SECURITY.md
index ef8d940..e3d41bd 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -2,23 +2,20 @@
## What this package runs on your machine
-`silmetrics.mjs`, `hero.mjs` and `judge.mjs` each start a short-lived local HTTP
-server so a headless Chromium can load the model, then shut it down. All three
-**bind to `127.0.0.1` on an OS-assigned port** — they are not reachable from the
-network, and two runs cannot collide on a port.
-
-`judge.mjs` also serves the JavaScript its measuring page imports. Paths are
-resolved and then checked for containment inside the allowed roots, and only
-`.js .mjs .map .json .wasm` are served. Before 1.2.0 this used `path.join` with
-no containment check and listened on `0.0.0.0`, which allowed any host on the
-same network to read arbitrary files — `/etc/passwd` and `/proc/self/environ`
-among them — for as long as a judge run lasted. If you are on an older copy,
-update or do not run it on an untrusted network.
-
-Chromium is launched **with the OS sandbox enabled**. Set `PW_NO_SANDBOX=1` only
-where the sandbox genuinely cannot work (a container without the required
-privileges). `PW_CHROMIUM_PATH` pins a browser binary if you need to; otherwise
-Playwright picks its own.
+**Nothing here opens a socket or launches a browser.** As of 1.3.2 every
+measurement is arithmetic on the vertices (`harness/outline.py`), so the tools
+read files and write files and that is all.
+
+Before 1.3.2 three tools each started a local HTTP server so a headless Chromium
+could load the model. If you are on an older copy: those servers bound to
+`127.0.0.1` from 1.2.0 onward, but **before 1.2.0 `judge.mjs` resolved served
+paths with `path.join` and no containment check while listening on `0.0.0.0`** —
+any host on the same network could read arbitrary files, `/etc/passwd` and
+`/proc/self/environ` among them, for as long as a judge run lasted. Update, or
+do not run that copy on an untrusted network.
+
+The only network call this package can make is the explicit `publish.mjs`
+upload, which runs only after the user says yes.
## The Gobkit key in `harness/gobkit.json`
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index cc33baa..6a06a6a 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -10,8 +10,8 @@ itself is MIT — see `LICENSE`.
### three.js — `harness/assets/three-bundle.js`
A prebuilt bundle of three.js (core + `GLTFLoader` + `OrbitControls`), used by
-`silmetrics.mjs`, `hero.mjs` and by the offline showroom that `deliver.py`
-writes. The upstream licence banner is preserved at the end of the bundle.
+the offline showroom viewer that `deliver.py` writes — the customer's own
+browser opens it; nothing in this package launches one. The upstream licence banner is preserved at the end of the bundle.
```
Copyright © 2010-2025 Three.js Authors
@@ -43,13 +43,12 @@ SOFTWARE.
| Package | Licence |
|---|---|
| three (npm, pinned 0.180.0) | MIT |
-| playwright | Apache-2.0 |
| numpy | BSD-3-Clause |
| pillow | MIT-CMU |
| scipy | BSD-3-Clause |
-Playwright downloads a Chromium build on install; Chromium carries its own
-licences (BSD-3-Clause and others), shown at `chrome://credits` in that build.
+Playwright and its Chromium download were dependencies until 1.3.2. Every
+measurement they served now comes from the geometry, so neither is installed.
## Output files
diff --git a/VERSION b/VERSION
index 3a3cd8c..1892b92 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.3.1
+1.3.2
diff --git a/calibration/wolf_green.json b/calibration/wolf_green.json
index a872a50..a2c5a0c 100644
--- a/calibration/wolf_green.json
+++ b/calibration/wolf_green.json
@@ -289,8 +289,7 @@
"color": "#f2ead7"
}
]
- },
- "smooth_angle": 17
+ }
},
{
"chain": "head",
@@ -357,8 +356,7 @@
"color": "#f2ead7"
}
]
- },
- "smooth_angle": 20
+ }
},
{
"chain": "tail",
@@ -398,8 +396,7 @@
"color": "#57513f"
}
]
- },
- "smooth_angle": 31
+ }
},
{
"chain": "LFront",
@@ -431,8 +428,7 @@
"none",
"dome"
],
- "ring_step": 0.055,
- "smooth_angle": 35
+ "ring_step": 0.055
},
{
"chain": "LBack",
@@ -475,8 +471,7 @@
"none",
"dome"
],
- "ring_step": 0.055,
- "smooth_angle": 35
+ "ring_step": 0.055
}
],
"parts": [
diff --git a/cards/00_START.md b/cards/00_START.md
index 3255ebe..0636cef 100644
--- a/cards/00_START.md
+++ b/cards/00_START.md
@@ -10,8 +10,8 @@ order → ONE required question → silhouette brief → LOW: design FREE + two
1. **Form beats obedience.** Every rule below exists to protect form quality; if following a rule would make the creature tamer, the rule loses. Edits whose only purpose is to make a number match a declaration are forbidden.
2. **You never grade your own thumbnails — and you never trust a reader either.** Every gate is read by a context-free agent who knows nothing about the order, and every read carries the verification traps of card 01 §4 (binding questions, a canary, shuffled labels): assume every reader is lazy until its answers prove otherwise. Its verified verbatim answer is the verdict.
- **A reader is the most expensive thing in the run** — a subagent's price is almost entirely the cost of it EXISTING, with no images and a one-line prompt, so ~80% of a read's price is fixed overhead. Three rules follow, and all three are in the cards: batch the images (a five-image read costs barely more than a one-image read), never spend a read the machine could answer (`roundcheck --preflight` refuses those), and never let one round test one idea.
-3. **Same symptom failed twice = no third tweak.** Restart that view/element from a DIFFERENT concept. If the restart also fails, ship your best version and write one honest DEVLOG line about what didn't land. **This one is counted, not trusted** — `harness/roundcheck.py` records each gate verdict and reads `iou_vs_prev` to tell a real restart from a nudge, and refuses the third tweak. Law 2 exists because you cannot grade your own thumbnails; this law had the same problem and now has the same answer. A measured run spent rounds 6–15 moving the same head and ears before restarting at r16: eight rounds, and by then every round cost three times what round 6 did, because the context they ride on keeps growing.
+ **A reader is the most expensive thing in the run** — a subagent bills for EXISTING: with no images and a one-line prompt it still costs the great majority of what a full read costs, so almost all of a read's price is fixed overhead. Three rules follow, and all three are in the cards: batch the images (a five-image read costs barely more than a one-image read), never spend a read the machine could answer (`roundcheck --preflight` refuses those), and never let one round test one idea.
+3. **Same symptom failed twice = no third tweak.** Restart that view/element from a DIFFERENT concept. If the restart also fails, ship your best version and write one honest DEVLOG line about what didn't land. **This one is counted, not trusted** — `harness/roundcheck.py` records each gate verdict and reads `iou_vs_prev` to tell a real restart from a nudge, and refuses the third tweak. Law 2 exists because you cannot grade your own thumbnails; this law had the same problem and now has the same answer. A run can spend rounds 6–15 moving the same head and ears before restarting at r16 — eight rounds, and by then every round costs three times what round 6 did, because the context they ride on keeps growing.
**A round tests THREE ideas, not one** (card 01 §4b). A repair builds three versions that differ in KIND and shows all three to one reader — three builds cost four seconds more than one, while three separate reads cost three times a read. Three sizes of the same head is not three ideas; it is one idea with a wobble, and this law counts it as one.
4. **The signature part gets real geometry at LOW.** A giant whose identity is its fists gets fingers, knuckles and a planted pose in the silhouette round — not a placeholder sphere. Budget follows 6:3:1: the 6-level element gets 6-level geometry.
5. **Materials are named per PART** (`skin_torso`, `fur_leg`, `eye`, `tusk`…) — the area rulers identify parts by material name.
@@ -20,7 +20,7 @@ order → ONE required question → silhouette brief → LOW: design FREE + two
**ONE means one message, and it is the FIRST thing you send.** Not one question bundled with two others, not "a few quick things before I start". Between the order and that message you run `setup.sh` and nothing else; the very next words the person reads are card 01's question, alone. A second question in that message is a violation even if the question is a good one.
**Never ask about:** the delivery format, file type, triangle count, folder layout, whether to run a check, whether your expansion of the order is acceptable — **nor what it will cost, how many tokens or rounds it will take, how long you should spend, nor anything about publishing, sharing, uploading, or where the file should end up.** Those are decided by this harness, not by the customer. Cost and scope are your job: a non-designer has no way to price a round and asking makes them do yours. Publishing is decided in card 04, after the creature exists — nobody can consent to sharing a thing they have not seen, so asking early buys a worthless answer at the price of the one question that mattered. If you truly cannot proceed, choose the option you can defend, state the choice in one line at delivery, and keep moving.
8. **Nothing is ever uploaded without the user's explicit yes, this session — and that yes is collected in card 04, never before.** No background uploads, no test uploads, ask for every creature. This law says you may not upload unasked; it does not license an early ask, and reading it as one breaks law 7. The share question comes after the creature exists, after they have seen it, in card 04's closing dialogue. Asking it at the start is a violation of both laws at once — it spends the single question they had on a decision they cannot make yet.
-9. **One creature, one agent. The reader is the ONLY subagent.** You build the whole thing yourself — brief, skeleton, parts, anims, repairs — in one session, and you spawn subagents for exactly one purpose: the context-free reads of law 2. Handing the modelling itself to a chain of subagents feels tidy and costs more on every axis — tokens, wall clock and turns alike. Onboarding is not the cause; every fresh agent reads the same ground truth. The cause is RE-DERIVATION: work the previous agent had already done and could not hand over. The reader splits cheaply for the opposite reason — it is one turn, and it MUST NOT inherit anything. The rule that falls out: the cost of a split is how much understanding the next agent has to rebuild.
+9. **One creature, one agent. The reader is the ONLY subagent.** You build the whole thing yourself — brief, skeleton, parts, anims, repairs — in one session, and you spawn subagents for exactly one purpose: the context-free reads of law 2. Handing the modelling itself to a chain of subagents feels tidy and is measurably worse on every axis: on the same creature to the same green build, splitting it four ways (skeleton → parts → anims → verify) cost more tokens, more wall clock and more turns, because each fresh agent re-derived what the previous one already knew — one of them rebuilt a simulator of the compiler's own ring maths from scratch. The reader splits cheaply for the opposite reason: it is one turn, and it *must not* inherit anything. Cost of a split = how much understanding the next agent has to rebuild. For the reader that is zero, which is the point of it; for the modelling that is everything, which is the price of it.
10. **Write state down every round; never rely on your own memory of it.** A boss session outlives its own context — the transcript gets compacted and the early rounds are gone. That is a record problem, not a cost problem, and splitting the work does not fix it (see law 9). What fixes it: after every round, the archived `spec.json`, the metrics, and the reader's verbatim verdict are on disk under `out/rN/` and in `log.md` before you move on. Anything not written there did not happen, and after a compaction you resume by reading those files, not by trusting what you think you remember.
## Every check is tagged twice — read the map before arguing with one
@@ -53,9 +53,8 @@ Not tokens, not tools, not compute — **round-trips.** Every command you issue
re-reads the entire conversation up to that point, and the conversation only
grows, so an identical command costs several times more at round 20 than at
early in a run. Split into separate commands, compiles, silhouette renders and
-mask measures are most of a run's round trips. None of those tools is slow: a
-compile is 1.4 seconds, a silhouette view half a second, the whole measure phase
-under ten. The tools are never the bill.
+measures are most of a run's round trips. None of those tools is slow: a compile is 1.4 seconds, a silhouette view half a second,
+the whole measure phase under ten. The tools were never the bill.
So the harness gives you ONE command per phase, and you use it:
@@ -72,8 +71,11 @@ are one command. Loop in the shell, not in the conversation.
used and fills them, so the outline is computed rather than photographed and
then measured. Verified against the rendered masks on all four views at IoU
0.980–0.989 — the remainder is the renderer's antialiased edge. A round went
-from 9.0s to 1.4s, a three-variant round from 11.0s to 4.4s, and Chromium is now
-only needed for colour (`judge.mjs`), hero shots and the viewer.
+from 9.0s to 1.4s and a three-variant round from 11.0s to 4.4s. **1.3.2 finished
+the job: nothing in this harness launches a browser at all.** Part shares are the
+same z-buffer, the colour numbers are the baked albedo the engine already wrote,
+and even `hero.png` is projected rather than rendered. The offline viewer is HTML
+the customer opens themselves.
## Environment self-check (run verbatim)
diff --git a/cards/01_LOW.md b/cards/01_LOW.md
index a5be98f..958e063 100644
--- a/cards/01_LOW.md
+++ b/cards/01_LOW.md
@@ -285,14 +285,23 @@ Spawn a context-free reader agent (a fresh subagent given NOTHING but the images
> this is, most likely first.** Then: what parts can you make out, and does this
> view read as a build or as an abstract shape/nothing?
-**The verdict is SCORED, not argued.** Note where the brief's noun landed in each
-view's ranked guesses, then run:
+**The verdict is SCORED, not argued — and you do not do the scoring.** Hand over
+the reader's words, verbatim and in order. The tool matches them against the
+accepted list your brief wrote down before any geometry existed:
```bash
-python3 harness/identity.py --round N --noun scorpion \
- --ranks front=none side=2 top=2 hero=1
+python3 harness/identity.py --brief brief.md --round N \
+ --guesses side="t-rex,dinosaur,velociraptor,dragon,lizard" \
+ hero="four-legged animal,dog,goat,boar,bear"
```
+**You may not decide that "hound" counts as "wolf" here.** That judgment is real
+and it is yours — but it belongs in the brief, in writing, before the rounds are
+paid for. If a reader keeps saying a word you think IS the creature, go and add
+it to the identity slot and say why in the closing DEVLOG. Adding it at r3, with
+a shape you have already built and want to keep, is grading your own thumbnails,
+which iron law 2 forbids and which this tool no longer lets you do.
+
The rule it applies — **rank R passes if the noun reached R in at least R
views**:
@@ -313,12 +322,12 @@ is yours; it is the only one the tool leaves you.
Why scored rather than exact. A 48px silhouette is a genuinely ambiguous object,
and a one-word bar measures the reader's confidence as much as the creature's
-clarity. Two shipped logs make the case. One boss's first read came back *"a
-generic bat/moth/gargoyle silhouette"* — the ordered noun is IN that sentence.
-And a creature failed on one view while three readers named it first on the
-others will run round after round and revert to a shape whose read is identical
-to the one that was refused — because a one-word bar cannot express "three
-readers said it first".
+clarity. Two shapes of read make the case. A first read can come back as *"a
+generic bat/moth/gargoyle silhouette"* — the ordered noun IS in that sentence.
+And a read of `front=Rabbit, side/top/hero=Scorpion` under an exact-match rule
+fails on the front view alone, sending the creature back for round after round
+that cannot improve the verdict, because the rule cannot express "three of four
+views named it first".
Every view answering "abstract / nothing / a stick" scores nothing and fails.
"A fox" plus four other canines when the order said dragon is still a failed
diff --git a/cards/02_MID.md b/cards/02_MID.md
index 13e9b36..fbd4244 100644
--- a/cards/02_MID.md
+++ b/cards/02_MID.md
@@ -12,9 +12,17 @@ part, run one build, read the whole BLOCK list — the engine reports **all**
failures at once, it does not stop at the first — fix them all in one edit, and
build again.
-The arithmetic: writing the spec is not the cost. Touching the same forty
-elements three times each is, because a turn re-reads the whole conversation and
-the conversation only grows. Two passes is the target: **author everything, then
+The arithmetic on a 28-part body:
+
+- the entire spec is a **few percent** of one build's output. The spec would have
+ to be written **dozens of times over** to account for the run. Writing the spec
+ is not the cost.
+- MID takes ~130 turns for 40 elements — **every part and volume touched 3.2
+ times on average.** That is the cost.
+
+A turn re-reads the whole conversation, which only grows. Touching 40 elements
+three times each is 120 round-trips over material that could have been written
+once and corrected once. Two passes is the target: **author everything, then
repair everything.**
Mirrored structure is not authored twice, either. `"mirror": ["LArm"]` generates
@@ -27,11 +35,11 @@ chance of the two drifting apart. Use `mirror` for anything symmetric, and
Both reads that used to live here are gone, and neither was replaced by a
cheaper read — they were replaced by arithmetic that runs at build time.
-**The isolated part read is deleted.** It failed every time it was tried: a
-crown reads as "a blob", a face as "a stone", an armoured basket as "a fist" —
-while the whole-body read names all three without being asked twice. A part cut
-away from the body has lost the only context that told the reader what it was,
-so reading it there measures the crop, not the part.
+**The isolated part read is deleted.** It failed every time it was tried — a part
+cut out of the body comes back as "a blob", "a stone", "a fist" — while the
+whole-body read of the same body had already named the parts. A part cut away
+from the body has lost the only context that told the reader what it was, so
+reading it there measures the crop, not the part.
**The colour read is deleted too.** It asked three things, and a machine answers
all three off the palette in microseconds:
@@ -40,12 +48,12 @@ all three off the palette in microseconds:
|---|---|
| what colour is this creature | the palette. You wrote it. |
| which part draws the eye | `value_order` — every material sorted by OKLab lightness, brightest first, printed on every build. Whatever is at the top owns the eye. |
-| which parts can you make out | `contrast_adjacent` — every part compared against the material of the thing it SITS ON. Under 0.10 OKLab they read as one mass. |
+| which parts can you make out | `contrast_adjacent` — every part measured against the material of the thing it SITS ON. Under 0.10 OKLab they read as one mass. |
-Both answers sit in the palette the whole time. Two masses at the same
-lightness compete and neither owns the eye; a part wearing its host's colour is
-not a part. Rendering a hero and squinting at it is guessing at numbers you
-already have.
+Eyeballing "value readability" costs hero renders and then a MID reader, to be
+told that a shin blade is the same colour as the leg under it. Both answers sit
+in the palette the whole time — a declared focal at L 0.975 tied for brightest
+with a claw at L 0.973 is exactly what those renders are being used to guess.
Both checks are ADVICE with numbers, not blocks: camouflage and deliberately
subtle detail are real choices. What is not acceptable is paying a subagent to
diff --git a/cards/03_HIGH.md b/cards/03_HIGH.md
index 49fdffd..154c86d 100644
--- a/cards/03_HIGH.md
+++ b/cards/03_HIGH.md
@@ -49,7 +49,7 @@ lighting reacts to.
**The only field you normally write is `shading.pattern.color`, and you decided
it at MID.** Everything else is settled — see `cards/SYNTAX.md` for the full
-block for the settled values.
+block; the settled values themselves are `DEFAULTS` in `engine/core/shade.js`.
Two things worth knowing: brighter-and-more-saturated is impossible with any
blend mode (every mode that brightens moves toward white, and white has chroma
zero), which is why that layer works in OKLab; and pushing chroma walks back to
@@ -100,9 +100,9 @@ engine checks every clip in one pass (`anim_integrity`, `attack_reach`,
`limb_clearance`) and reports all of their failures at once, so a build per clip
buys nothing but round-trips at the most expensive point in the run.
-Tracks are cheap to write and expensive to iterate: three whole clips are a
-few thousand characters. The characters were never the
-problem. Three builds instead of one were.
+Tracks are cheap to write and expensive to iterate: three clips of a big
+creature come to a few dozen tracks and a couple of thousand characters. The
+characters were never the problem. Three builds instead of one were.
- The bar for idle/move: skinned, actually moving, no clipping, no explosions.
- **`attack` must COMMIT FORWARD — but it does not have to lunge.** The engine
diff --git a/cards/04_SHIP.md b/cards/04_SHIP.md
index b511a7e..fcbb841 100644
--- a/cards/04_SHIP.md
+++ b/cards/04_SHIP.md
@@ -71,7 +71,7 @@ python3 harness/ship.py out/<name>.glb --name "<their name>" --author "<signatur
```
`ship.py` stamps the name and signature INTO the GLB (they travel with the file
-forever), packs the viewer, hero shots and the backup upload pack, and — only
+forever), packs the viewer, `hero.png` and the backup upload pack, and — only
with `--publish` — uploads and prints the result. Never pass `--publish` without
an explicit yes in this session.
@@ -144,7 +144,7 @@ it. It says how the gates landed and what did not get solved, and stops.
This is the most expensive moment in the entire run to write prose: the
conversation is at its longest, so every token here costs several times what the
-same cost early in the run. A boss build writes a few thousand characters of session
-narrative here — tables, verbatim reader quotes, per-round analysis — all of it
-duplicating `log.md`, all of it at maximum context price. One line was the rule
-the whole time.
+same token cost at round 3. It is easy to write **thousands of characters** of
+session narrative here — tables, verbatim reader quotes, per-round analysis —
+all of it duplicating `log.md`, all of it at maximum context price. One line is
+the rule.
diff --git a/cards/SYNTAX.md b/cards/SYNTAX.md
index 5f7bae7..7831fac 100644
--- a/cards/SYNTAX.md
+++ b/cards/SYNTAX.md
@@ -150,3 +150,108 @@
`info:` = the compiler telling you what actually happened — always read them.
Shipped GLBs auto-merge primitives per material and export public bone names
(`LArm1Sh` convention) — internal spec names never leak.
+
+---
+
+## `function` — what each chain is FOR (1.3.2)
+
+```jsonc
+"function": {
+ "body": "axis", // the load-bearing spine of the creature
+ "LArm": "locomotion", // what moves it: legs, wings, fins, wheels
+ "RArm": "locomotion",
+ "LLeg": "effector", // the end that reaches out and contacts the world
+ "case": "ornament" // carried, not load-bearing, does no work
+}
+```
+
+Keys are chain names. A chain listed in `mirror` covers its twin automatically.
+A part bolted onto a chain inherits that chain's function, so `"neck": "effector"`
+covers the blade mounted on the neck; naming the part directly also works.
+
+Five words, all manufacturing vocabulary. Nothing here says how hard a thing hits or
+what it is worth in a fight — that is the receiving system's business.
+
+**A declaration is not a label; it is a claim the engine checks:**
+
+| check | what the declaration has to pay for |
+|---|---|
+| `effector_leads` | at the frame the attack reaches furthest, the effector is the frontmost mesh |
+| `attack_windup` | the effector winds back 5% of its travel, or swings 15% out to the side |
+| `gait_footfall` | a locomotion chain that touches ground lands in FRONT of where it lifts |
+| `self_clip` | nothing that starts far apart ends up inside something else |
+| `clip_closes` | a non-looping clip returns to its first frame |
+| `ground_clip` | nothing goes below the plane the creature stands on |
+
+`harness/autofix.mjs` fixes the arithmetic ones before a round is spent — the ground
+offset, the loop closure, and the compensation of joints that must hold their own aim
+while the body turns for some other purpose. It never touches the decisions: which way
+a leg swings, what the creature attacks with, how far it lunges.
+
+## `joint_range` — how far each joint turns (1.3.2)
+
+```jsonc
+"joint_range": {
+ "LKnee": { "rx": [-130, 10] }, // a knee is a hinge, one way
+ "LSh": { "rx": [-50, 90], "ry": [-60, 60], "rz": [-70, 70] },
+ "Beak": { "rx": [-10, 40] }, // opens, does not close past shut
+ "BallTop":{ "rx": [-35, 35], "ry": "free" } // hangs on a chain, spins freely
+}
+```
+
+Degrees, per axis, in the joint's **own frame** — the same frame and the same axis
+names (`rx`/`ry`/`rz`) the animation tracks use, so a limit and a track compare
+directly.
+
+- **An axis you leave out is LOCKED at 0**, not free. A table with holes in it is a
+ table that checks nothing, and one axis per joint is the common case anyway.
+ `"free"` opts an axis out on purpose — a rotor, a wheel, a weight on a chain.
+- **Declare the L side only.** The R twin is generated: `ry` and `rz` negate, which
+ swaps the ends of the interval, so `[-10, 90]` becomes `[-90, 10]`. Writing both
+ sides by hand is how mirrored limbs get broken. Writing `R…` explicitly overrides,
+ for a body that really is asymmetric.
+- **Write what the ANIMAL can do**, not what your clip happens to use. A limit is a
+ fact about the body; a track is one use of it. If they are the same numbers, the
+ declaration is not saying anything.
+
+**What the declaration has to pay for:**
+
+| failure | what it means | the fix |
+|---|---|---|
+| undeclared | a clip turns a joint with no entry | write the entry |
+| overrun | a track leaves its own declared interval | fix the track, or the number — one of them, not both |
+| unreachable | the body collides before the declared limit | tighten the number to the angle the engine reports |
+
+`unreachable` is the one worth understanding. You know a gorilla's shoulder swings 60°
+back; you do not know that THIS gorilla has a wrecking ball hanging off a crane on its
+back, so its arm stops at 53°. The engine sweeps every declared bound against the actual
+geometry and reports the last angle that clears. Authored knowledge, checked arithmetic —
+neither one alone is enough.
+
+## `name` on every part — the identity channel (1.3.2)
+
+```jsonc
+"parts": [
+ { "name": "nose_leaf", "type": "fin", "host": "Muzzle", "material": "paw" },
+ { "name": "foot_claws", "type": "paw", "host": "LToe", "material": "paw", "mirrored": true },
+ { "name": "left_tusk", "type": "curve", "host": "Muzzle", "material": "tusk" }
+]
+```
+
+Required, and unique within the creature. It may not reuse a chain name, because
+volumes are identified by their chain.
+
+**Why it is not optional, and why the material cannot do the job.** A material is a
+CLASS — "this is horn", "this is brass pipe". Many parts share one on purpose, and the
+GLB merges primitives one per material so a body with forty plates does not ship forty
+draw calls. That makes a material name structurally unable to answer *which part is
+this*: above, `paw` names both a foot pad and a nose-leaf, and anything that groups by
+material adds the two together. Naming is the fix, and it costs nothing — you already
+know what you are building at the moment you write the part.
+
+Name the THING, not its type and host. `spike@Skull` is a description of where you put
+something, and two spikes on one skull share it; `left_horn` and `right_horn` are names.
+
+The engine writes each name into the file as `asset.extras.part_spans`, with the exact
+vertex range that part owns — so a checker, the Arena importer or `graft.py` can point
+at one piece of geometry without a single extra material.
diff --git a/docs/HANDOVER_sanitize.md b/docs/HANDOVER_sanitize.md
index 4f28d85..03bda47 100644
--- a/docs/HANDOVER_sanitize.md
+++ b/docs/HANDOVER_sanitize.md
@@ -146,9 +146,9 @@ Anisotropy stretches the specular highlight ALONG THE TANGENT. A primitive with
neither `TANGENT` nor `TEXCOORD_0` gives the renderer no direction, so each one
invents its own and the model is a flat white smear in some viewers and correct
in none — and lowering `anisotropyStrength` does not help, because the missing
-information is *which way*, not *how much* (expressed in the field: 0.9 → 0.15,
-no change). On a submission whose primitives lack both, DROP the extension and
-keep the model — the base colour is unaffected and the creature renders
+information is *which way*, not *how much* — dropping `anisotropyStrength` from
+0.9 to 0.15 changes nothing. On a submission whose primitives lack both, DROP
+the extension and keep the model — the base colour is unaffected and the creature renders
correctly without it. anyCreature 1.3.0 refuses to emit this case at all
(`anisotropy_without_direction`), so any file carrying it was hand-edited or
came from another tool.
diff --git a/docs/OUTPUT_CONTRACT.md b/docs/OUTPUT_CONTRACT.md
index 1f14ae1..4ad3e1b 100644
--- a/docs/OUTPUT_CONTRACT.md
+++ b/docs/OUTPUT_CONTRACT.md
@@ -58,7 +58,9 @@ A receiving system can treat a file that satisfies this contract as
"license": "CC0-1.0", // written ONLY at publish, after consent
"source_spec": { /* the pristine authored spec — see below */ },
"parts": [ { "kind": "volume|part", "type": "...", "name": "...",
- "material": "...", "host": "...", "join": "..." } ]
+ "material": "...", "host": "...", "join": "..." } ],
+ "part_spans": [ { "id": "nose_leaf", "material": "paw",
+ "primitive": 7, "first": 1204, "count": 376 } ]
}
}
```
@@ -73,6 +75,20 @@ creature (`harness/graft.py`). `embed_spec: false` in the spec opts out.
`parts` is a flat manifest of what the creature is made of, so a receiver can
list its pieces without parsing the whole spec.
+`part_spans` (1.3.2) says WHERE each of those pieces is in the geometry: one row
+per part, giving the primitive it landed in and the `[first, count]` range of
+vertices it owns inside that primitive's `POSITION` accessor.
+
+It exists because a **material name cannot identify a part**. A material is a
+class — "this is horn" — and primitives are merged one per material precisely so
+a body with forty plates does not ship forty draw calls. The same `paw` material
+can therefore sit on a foot pad and on a nose-leaf, and anything that aggregates
+by material silently adds the two together. `part_spans` is the identity channel:
+every `id` is unique within the creature, mirrored twins carry `.R`, an eye pair
+carries `.L`/`.R`, and nothing about the rendering changes — no extra material,
+no extra primitive, no extra byte of geometry. A receiver that wants "the claw"
+reads the span and slices the buffer.
+
## Error vocabulary
`glbcheck` reports machine-readable codes. A server rejecting a submission
diff --git a/engine/cli.js b/engine/cli.js
index 9b78125..01a5d82 100644
--- a/engine/cli.js
+++ b/engine/cli.js
@@ -151,7 +151,7 @@ const L8 = STACK
? (((spec.shading || {}).normals || {}).flesh ?? 0.90)
: 0;
const bytes = writeGLB({ meshes, skeleton: sk, ibm: inverseBindMatrices(sk), anims }, outPath,
- { asset, names, boneNormals: L8 });
+ { asset, names, boneNormals: L8, spans: spec.embed_spec !== false });
if (L8) {
const moved = require('./core/glb.js').L8_MOVED;
const tot = moved.reduce((a, r) => a + r[1], 0), all = moved.reduce((a, r) => a + r[2], 0);
diff --git a/engine/core/anim.js b/engine/core/anim.js
index 74f8a5f..c7c80d1 100644
--- a/engine/core/anim.js
+++ b/engine/core/anim.js
@@ -35,6 +35,25 @@ function sampleKeys(keys, t) { // keys [[frac, val]...] sorted; linear interp, t
// Expand one animation into per-joint uniform samplers (N samples across duration).
// Returns { name, duration, channels: [{joint, path:'rotation'|'translation', times:[], values:[]}] }
+
+// Mirroring a track is a RESAMPLE, not a key shift.
+//
+// The old code did `keys.map(([t,v]) => [(t+phase)%1, v*flip]).sort(...)`. A key at
+// t=1 lands on t=phase, collides with whatever is already there, and after the sort
+// the track simply ends early — the R-side limb freezes partway through the cycle.
+// Every mirrored track whose last key sits at t=1 — which is every looping track —
+// is truncated this way, so the mirrored limb freezes partway through the cycle.
+//
+// Resampling keeps every original key's shifted position (so the shape is exact),
+// adds the endpoints, and cannot collide because the times go through a Set.
+function mirrorTrack(keys, phase, flip, loop) {
+ const ts = new Set([0, 1]);
+ const wrap = u => loop ? ((u % 1) + 1) % 1 : Math.max(0, Math.min(1, u));
+ for (const [t] of keys) ts.add(+wrap(t + phase).toFixed(6));
+ return [...ts].sort((a, b) => a - b)
+ .map(t => [t, flip * sampleKeys(keys, wrap(t - phase))]);
+}
+
function compileAnim(name, a, spec, sk, samples = 24) {
const tracks = { ...a.tracks };
// auto-mirror: for each track on a joint belonging to a mirrored chain,
@@ -48,11 +67,7 @@ function compileAnim(name, a, spec, sk, samples = 24) {
const src = tracks[jn]; const dst = {};
for (const [axis, keys] of Object.entries(src)) {
const flip = (axis === 'ry' || axis === 'rz' || axis === 'tx') ? -1 : 1;
- dst[axis] = keys.map(([t, v]) => [(t + phase) % 1, v * flip])
- .sort((p, q) => p[0] - q[0]);
- // re-close the loop
- if (dst[axis][0][0] !== 0) dst[axis].unshift([0, sampleKeys(src[axis].map(([t,v])=>[(t+phase)%1, v*flip]).sort((p,q)=>p[0]-q[0]), 0)]);
- if (dst[axis][dst[axis].length-1][0] !== 1) dst[axis].push([1, dst[axis][0][1]]);
+ dst[axis] = mirrorTrack(keys, phase, flip, a.loop !== false);
}
tracks[rj] = dst;
}
@@ -94,4 +109,4 @@ function compileAnims(spec, sk) {
return Object.entries(spec.animations || {}).map(([n, a]) => compileAnim(n, a, spec, sk));
}
-module.exports = { compileAnims, eulerToQuat, sampleKeys };
+module.exports = { compileAnims, eulerToQuat, sampleKeys, mirrorTrack };
diff --git a/engine/core/checks.js b/engine/core/checks.js
index de30f3d..c3ddee0 100644
--- a/engine/core/checks.js
+++ b/engine/core/checks.js
@@ -7,7 +7,8 @@
// 3. balance — mass centroid must project inside the support polygon.
'use strict';
const G = require('./geometry.js');
-const { sampleKeys, eulerToQuat } = require('./anim.js');
+const { sampleKeys, eulerToQuat, mirrorTrack } = require('./anim.js');
+const { signedDistance } = require('./inside.js');
// ── mat helpers (column-major mat4) ──
function quatMat(q) {
@@ -147,8 +148,7 @@ function runChecks(spec, sk, meshes, animsCompiled) {
// `faceted: true` on a VOLUME shatters the mass into one independent facet per
// triangle — an 800-triangle torso becomes 800 shards — and because AO bakes
// from those normals the mess ships inside COLOR_0, where no relighting can
- // reach it — a faceted body comes back ~90% hard-edged. Bodies are
- // smooth-shaded. Parts — plates, spikes, claws, crystal,
+ // reach it — a faceted body comes back ~90% hard-edged. Bodies are smooth-shaded. Parts — plates, spikes, claws, crystal,
// armour — may still face freely; only volumes are covered.
if (spec.build !== 'rigid') {
const bad = (spec.volumes || []).filter(v => v.faceted).map(v => `"${v.chain}"`);
@@ -221,7 +221,7 @@ function runChecks(spec, sk, meshes, animsCompiled) {
const dst = {};
for (const [axis, keys] of Object.entries(tracks[jn])) {
const flip = (axis === 'ry' || axis === 'rz' || axis === 'tx') ? -1 : 1;
- dst[axis] = keys.map(([t, v]) => [(t + phase) % 1, v * flip]).sort((p, q) => p[0] - q[0]);
+ dst[axis] = mirrorTrack(keys, phase, flip, a.loop !== false); // 同一支:重新取樣,不是搬鍵
}
tracks[mirrorName(jn)] = dst;
}
@@ -355,19 +355,29 @@ function runChecks(spec, sk, meshes, animsCompiled) {
// just did — the same work, done twice, once in code and once by hand.
const over = []; let nearC = null, nearD = Infinity;
for (const p of rootRing) {
- let best = Infinity, bs = 0;
- host._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });
- const ring = host._rings[bs]; const c2 = host._pts[bs];
- const rad = Math.max(...ring.map(q => G.len(G.sub(q, c2))));
- over.push(best - rad * 0.98);
- if (best < nearD) { nearD = best; nearC = c2; }
- if (best < rad * 0.98) inside++;
+ // Distance to the host's actual SURFACE, signed: negative is inside. This
+ // used to compare against a sphere of the nearest ring's widest radius,
+ // which hands out a whole half-width of phantom "inside" straight off the
+ // end cap — exactly where the next chain attaches. See engine/core/inside.js.
+ const sd = signedDistance(p, host);
+ over.push(sd);
+ if (sd < nearD) { nearD = sd; nearC = p; }
+ if (sd < 0) inside++;
}
- if (inside < rootRing.length * 0.8) {
+ // THE STATISTIC IS THE MEDIAN, not a count of points. A root ring meets a
+ // CURVED host, so a few of its points always poke out; counting them punishes
+ // every honest quadruped. What separates a seated ring from a floating one is
+ // whether its MIDDLE is buried. Across a reference set of 102 joints the median
+ // point sits inside on 95 of them, and the 7 it does not are the ones you can
+ // see. That is a style number, not a law, and it is a tag away from being a
+ // profile.
+ const sortedSD = over.slice().sort((a, b) => a - b);
+ const medianSD = sortedSD[Math.floor(sortedSD.length / 2)];
+ if (medianSD >= 0) {
// 80% of the ring has to end up inside, so the move that fixes it is the
// 80th-percentile overshoot — not the worst point, which would bury it
// further than the rule asks for.
- const sorted = over.slice().sort((a, b) => a - b);
+ const sorted = sortedSD;
const need = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.8))];
// Name the CHAIN'S OWN first joint, not the host joint it hangs from.
// Moving the host drags this chain along with it, so that correction can
@@ -398,13 +408,11 @@ function runChecks(spec, sk, meshes, animsCompiled) {
};
const containedInHost = (p, host) => {
if (!host) return false;
- let best = Infinity, bs = 0;
- host._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });
- const rad = Math.max(...host._rings[bs].map(q => G.len(G.sub(q, host._pts[bs]))));
- // 1.05: verts within 5% of the host surface are thigh-belly SEAM geometry,
- // covered by the host silhouette — not a visible limb at the centreline.
- // (a zero-margin binary test flags every quadruped groin seam as "exposed")
- return best < rad * 1.05;
+ // Surface distance, not a sphere (engine/core/inside.js). The band is the
+ // same idea it always was: a vert sitting just OUTSIDE the host is seam
+ // geometry, covered by the host's own silhouette, not a limb showing at the
+ // centreline — a zero-margin test flags every quadruped groin seam.
+ return signedDistance(p, host) < 0.02 * modelH;
};
for (const cn of spec.mirror || []) {
const v = volsByChain[cn]; if (!v) continue;
@@ -448,10 +456,9 @@ function runChecks(spec, sk, meshes, animsCompiled) {
if (!host || !host._rings) continue;
let nearest = Infinity;
for (const p of m.V) {
- let best = Infinity, bs = 0;
- host._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });
- const rad = Math.max(...host._rings[bs].map(q => G.len(G.sub(q, host._pts[bs]))));
- const outside = best - rad; // <0 inside the host, >0 clear of it
+ // <0 inside the host, >0 clear of it — measured against the surface, not
+ // a sphere through the widest ring (engine/core/inside.js).
+ const outside = signedDistance(p, host);
if (outside < nearest) nearest = outside;
}
if (nearest > gap)
@@ -605,7 +612,36 @@ function runChecks(spec, sk, meshes, animsCompiled) {
// Sum the per-step forward travel over contact frames, rather than
// (last - first): a contact phase that straddles the loop point would
// otherwise subtract two frames that are the same frame and read 0.
- const low = path.map(p => p[1] < ymin + (ymax - ymin) * 0.30);
+ // Contact window: expand CONTIGUOUSLY from the foot's lowest frame.
+ // Thresholding the whole cycle breaks as soon as the pelvis bobs: the bob puts
+ // a second harmonic on the foot's Y, the window splits in two, and touchdown /
+ // liftoff land on the wrong frames. (Measured: a correct 24%-reach walk read as
+ // -17% after adding pelvis translation.) Contiguous expansion is immune to that.
+ const L = path.length, lim = ymin + (ymax - ymin) * 0.30;
+ let c0 = ys.indexOf(ymin), aI = c0, bI = c0;
+ while (ys[(aI - 1 + L) % L] < lim && (bI - aI) < L - 1) aI--;
+ while (ys[(bI + 1) % L] < lim && (bI - aI) < L - 1) bI++;
+ const ix = i => ((i % L) + L) % L;
+ const low = path.map(() => false);
+ for (let i = aI; i <= bI; i++) low[ix(i)] = true;
+ // 7c. gait_footfall — THE FOOT MUST LAND IN FRONT OF WHERE IT LEAVES.
+ // gait_direction only asks that the planted foot sweeps backward. A leg that
+ // lifts and puts itself down in the same place passes that and still is not
+ // walking; so does a leg that reaches backward and plants behind the body.
+ // The reference is the foot's own liftoff point, NOT the hip: a bird's hip sits
+ // far forward inside the body, so its foot is always ahead of the hip and a
+ // hip-relative test calls a good walk bad.
+ {
+ const reach = path[ix(aI)][2] - path[ix(bI)][2];
+ if (reach < 0.15 * stride)
+ fails.push(`gait_footfall: "${jn}" touches down ${reach >= 0 ? '' : '-'}`
+ + `${Math.abs(reach).toFixed(3)} m ${reach >= 0 ? 'in front of' : 'BEHIND'} where it lifts off `
+ + `(${(100 * reach / stride).toFixed(0)}% of its ${stride.toFixed(2)} m stride; needs >= 15% in FRONT). `
+ + `A step reaches FORWARD and DOWN, then sweeps back under the body. Lifting the foot and `
+ + `setting it down level or behind is walking backwards, or marching on the spot. `
+ + `THE FIX: shift the hip track so the leg is FORWARD when the foot comes down and BACK when it lifts `
+ + `— the phase, not the amplitude.`);
+ }
let net = 0, contact = 0;
for (let s = 0; s < path.length - 1; s++) {
if (!(low[s] && low[s + 1])) continue;
@@ -766,29 +802,53 @@ function runChecks(spec, sk, meshes, animsCompiled) {
}
}
- // 9. part_overlap — a MEASURE, not a law: gross part-into-part interpenetration
- // (the self-intersecting fist class). Reported as warn; you judge.
+ // 9. part_overlap — how much of one part is actually inside another.
+ //
+ // THIS USED TO COMPARE BOUNDING BOXES, and that is not a shape. A 2.8 m spear's
+ // box contains any hand gripping it, so the check reported "the hand is 100%
+ // inside the spear" — and acting on that number removes parts that are placed
+ // correctly. The signal was not noisy, it was wrong: a box says nothing about
+ // whether two surfaces share space. Same error class as the sphere that let a
+ // head float.
+ //
+ // Measured against the real surfaces now (engine/core/inside.js), which makes
+ // most of the old false positives disappear on their own — a hand around a
+ // haft is not inside the haft. Two severities, because they are different
+ // problems: a part BURIED whole is geometry nobody will ever see that still
+ // costs triangles, and a part partly in is a seam, which is usually the point.
{
- const parts = meshes.filter(m => m.part);
- for (let i = 0; i < parts.length; i++) for (let k = 0; k < parts.length; k++) {
- if (i === k) continue;
- const A = parts[i], B = parts[k];
- if (A.part.replace(/\.R$/, '') === B.part.replace(/\.R$/, '')) continue; // own mirror twin
- if (B.doubleSided) continue; // a zero-thickness membrane has a huge hollow box — it contains nothing
+ const { signedDistance } = require('./inside.js');
+ const parts = meshes.filter(m => m.part && m.V && m.V.length && m.F && m.F.length);
+ const box = m => {
const lo = [1e9, 1e9, 1e9], hi = [-1e9, -1e9, -1e9];
- for (const v of B.V) for (let a = 0; a < 3; a++) {
+ for (const v of m.V) for (let a = 0; a < 3; a++) {
if (v[a] < lo[a]) lo[a] = v[a];
if (v[a] > hi[a]) hi[a] = v[a];
}
- const c = [0, 1, 2].map(a => (lo[a] + hi[a]) / 2);
- const h = [0, 1, 2].map(a => (hi[a] - lo[a]) / 2);
- if (Math.min(...h) <= 0) continue;
- let inside = 0;
- for (const v of A.V)
- if (Math.abs(v[0] - c[0]) < h[0] && Math.abs(v[1] - c[1]) < h[1] && Math.abs(v[2] - c[2]) < h[2]) inside++;
- const frac = inside / A.V.length;
- if (frac > 0.45)
- warns.push(`part_overlap: '${A.part}' sits ${Math.round(frac * 100)}% inside '${B.part}' — check for interpenetration`);
+ return { lo, hi };
+ };
+ const boxes = parts.map(box);
+ const stem = s => s.replace(/\.R$/, '').replace(/[_-]?\d+$/, '');
+ for (let i = 0; i < parts.length; i++) for (let k = 0; k < parts.length; k++) {
+ if (i === k) continue;
+ const A = parts[i], B = parts[k];
+ if (stem(A.part) === stem(B.part)) continue; // own mirror twin, or the same ring repeat
+ if (B.doubleSided) continue; // a membrane encloses nothing
+ let sep = false;
+ for (let a = 0; a < 3; a++) if (boxes[i].lo[a] > boxes[k].hi[a] || boxes[k].lo[a] > boxes[i].hi[a]) sep = true;
+ if (sep) continue; // boxes do not even touch — cheap reject only
+ const step = Math.max(1, Math.ceil(A.V.length / 160));
+ let inside = 0, tested = 0;
+ for (let v = 0; v < A.V.length; v += step) { tested++; if (signedDistance(A.V[v], B) < 0) inside++; }
+ if (!tested) continue;
+ const frac = inside / tested;
+ if (frac >= 0.995)
+ warns.push(`part_overlap: '${A.part}' is COMPLETELY buried inside '${B.part}' — invisible geometry `
+ + `that still costs triangles. Either it is meant to nest (an eye in a socket) and is fine, or it `
+ + `should be pushed out until it shows, or deleted.`);
+ else if (frac > 0.45)
+ warns.push(`part_overlap: '${A.part}' sits ${Math.round(frac * 100)}% inside '${B.part}' `
+ + `— measured surface to surface, so this is real interpenetration, not a bounding box.`);
}
}
@@ -841,6 +901,385 @@ function runChecks(spec, sk, meshes, animsCompiled) {
}
}
+
+ // ── 7i. eye_pupil — an eye is a VALUE STEP, not a coloured dot.
+ //
+ // The engine's `eye` part is one monochrome sphere. On its own it ships a flat
+ // disc of colour, and at reading size a flat disc is a sticker, not an eye. What
+ // makes an eye read is the step between a bright iris and a near-black pupil —
+ // not the saturation of either. Faces built from a lone sphere measure as "no
+ // eyes" for exactly this, and the fix is always the same: a second, smaller,
+ // much darker sphere on the same host. `harness/pupils.py` places it by measuring where the eyeball actually
+ // landed, because guessed numbers bury it inside the iris or float it in front.
+ {
+ const eyes = (spec.parts || []).filter(p => p.type === 'eye');
+ const byHost = {};
+ for (const p of eyes) (byHost[p.host] = byHost[p.host] || []).push(p);
+ const bare = [];
+ for (const [host, ps] of Object.entries(byHost)) {
+ if (ps.length > 1) continue; // a pair on one host IS iris + pupil
+ const L = m => {
+ const pal = (spec.palette || {})[m];
+ if (!pal || !pal.color) return null;
+ const h = pal.color.replace('#', '');
+ const [r, g, b] = [0, 2, 4].map(i => parseInt(h.substr(i, 2), 16) / 255);
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ };
+ const l = L(ps[0].material || 'eye');
+ if (l !== null && l < 0.18) continue; // a single very dark sphere is a pupil-only eye
+ bare.push(`${ps[0].name || 'eye'}@${host}`);
+ }
+ if (bare.length)
+ warns.push(`eye_pupil: ${bare.join(', ')} — one sphere on its own is a flat coloured disc, `
+ + `and at reading size a disc is a sticker. An eye reads because of the VALUE STEP `
+ + `between a bright iris and a near-black pupil. Add the pupil with `
+ + `\`python3 harness/pupils.py <spec.json>\` — it measures where the eyeball actually `
+ + `landed before placing it, which hand-picked numbers cannot do.`);
+ }
+
+ // ── 7g. part_names — every part carries its own name, and no two share one.
+ //
+ // A material is a CLASS: "this is horn". Many parts share one on purpose, and the
+ // GLB merges by material precisely so a body with forty plates does not ship forty
+ // draw calls. That makes a material name structurally incapable of answering "which
+ // part is this" — the same `paw` material sits on a foot pad AND on a nose-leaf, and
+ // anything that aggregates by material silently adds the two together.
+ //
+ // So identity gets its own channel and the author fills it, because the generator
+ // already knows what it is emitting at the moment it emits it. `nose_leaf` is a name;
+ // `spike@Skull` is a description of where a thing was put, and two spikes on one skull
+ // share it. glb.js then records [first, count] per name, so a name reaches all the way
+ // into the file without costing a single extra material.
+ {
+ const chainNames = new Set(Object.keys(spec.chains || {}));
+ const seen = new Map();
+ const unnamed = [], dupes = [], clashes = [];
+ (spec.parts || []).forEach((p, i) => {
+ const n = (p.name || '').trim();
+ if (!n) { unnamed.push(`parts[${i}] (${p.type} on ${p.host || 'ribs'})`); return; }
+ if (seen.has(n)) dupes.push(n); else seen.set(n, i);
+ if (chainNames.has(n)) clashes.push(n);
+ });
+ if (unnamed.length)
+ fails.push(`part_names: ${unnamed.length} part(s) have no "name" — ${unnamed.slice(0, 6).join(', ')}`
+ + (unnamed.length > 6 ? `, +${unnamed.length - 6} more` : '')
+ + `. THE FIX: give every part the name of the THING it is ("nose_leaf", "left_tusk"), not its type `
+ + `and host. The material is a class shared by many parts and cannot identify one; this name is what `
+ + `checks, the Arena importer and graft.py use to point at a single piece of geometry.`);
+ if (dupes.length)
+ fails.push(`part_names: duplicated — ${[...new Set(dupes)].join(', ')}. Two parts with one name is two `
+ + `things nothing downstream can tell apart. THE FIX: name them for what they are (left_tusk / `
+ + `right_tusk), not what they are made of.`);
+ if (clashes.length)
+ fails.push(`part_names: ${[...new Set(clashes)].join(', ')} is already a chain name, and volumes are `
+ + `identified by their chain. THE FIX: pick a different name for the part.`);
+ }
+
+ // ── 7h. body_islands — a creature is ONE thing, and one thing is connected.
+ //
+ // This exists because a head shipped as a free-floating object: 0.24 m clear of
+ // the torso surface, every one of its 311 vertices outside the body mesh, held
+ // to the creature only by two stray vertices of a foreleg that happened to poke
+ // into it. Nothing caught it. root_containment, limb_clearance and
+ // part_attachment were all reading a SPHERE through the widest ring instead of
+ // the surface (fixed — see engine/core/inside.js), and even corrected, all three
+ // ask a LOCAL question: is this piece seated in ITS host. The failure was global.
+ // A silhouette cannot see it either: a head floating inside the outline is not a
+ // hole in the mask. So the global question gets asked directly.
+ //
+ // THE WELD TOLERANCE IS 3% OF MODEL HEIGHT, and it is a floor rather than a
+ // target. Well-built parts sit anywhere from fully embedded to ~3% of height
+ // off their host, because part_attachment's own bar allows a part to
+ // TOUCH rather than sink in. There is no gap in that distribution to put a
+ // threshold in, so this takes the loosest value that is still correct and calls
+ // anything looser detached. The failure it exists for is 9.3% — three times the
+ // bar — so a loose floor still catches it by a wide margin. Tightening attachment
+ // is a separate decision, and it belongs to part_attachment, not here.
+ if (!spec.qa_isolate) {
+ const groups = require('./inside.js').islands(meshes, 0.03 * modelH, 3);
+ if (groups.length > 1) {
+ const loose = groups.slice(1);
+ const shown = loose.slice(0, 6).map(g => `[${g.join(', ')}]`).join(' ');
+ fails.push(`body_islands: this is ${groups.length} separate objects, not one creature. `
+ + `Floating free of the main body: ${shown}${loose.length > 6 ? ` +${loose.length - 6} more` : ''}. `
+ + `A piece counts as attached when it shares material with something else — `
+ + `${(0.03 * modelH).toFixed(3)} m of weld, at three points. Two stray vertices `
+ + `poking in is not an attachment, it is a coincidence. THE FIX: move the floating `
+ + `piece INTO whatever it is supposed to grow out of, along its own axis; a root is `
+ + `meant to be buried, and burying it is what hides the seam as well.`);
+ }
+ }
+
+ // ── 7f. joint_range — a joint that turns declares how far it turns, the
+ // declaration is honest about THIS body, and the clips stay inside it.
+ //
+ // The numbers are authored, because whoever writes the spec already knows a knee
+ // bends one way and an elbow does not twist, and that knowledge is impossible to
+ // compute from vertices. The numbers are then CHECKED, because the author does not
+ // know how thick this creature's thigh is — a declared limit is a claim about the
+ // body, and an unverified claim is the thing this release exists to stop.
+ //
+ // Three failures, three different fixes, so three different messages:
+ // undeclared a clip turns a joint that has no entry -> write the entry
+ // overrun a track leaves its own declared interval -> fix the track or the number
+ // unreachable the body collides before the limit -> tighten the number
+ //
+ // The sweep costs one pass at the declared extreme per axis, which is the same
+ // order as self_clip's own broad phase. The 8-step ladder that finds the angle it
+ // ACTUALLY reaches only runs on bounds that already failed, so a clean body pays
+ // nothing for it.
+ if (!spec.qa_isolate) {
+ const SK = require('./skeleton.js');
+ const mirrorName2L = n => (n.startsWith('R') ? 'L' + n.slice(1) : n);
+ let ranges = null;
+ try { ranges = SK.jointRanges(spec, sk); }
+ catch (e) { fails.push(`joint_range: ${e.message}`); }
+ if (ranges) {
+ const AX = SK.RANGE_AXES;
+
+ // a limit on a joint that does not exist is a typo doing nothing quietly
+ const ghosts = Object.keys(spec.joint_range || {}).filter(jn => sk.index[jn] === undefined);
+ if (ghosts.length)
+ fails.push(`joint_range: no such joint — ${ghosts.join(', ')}. THE FIX: use the joint names from `
+ + `"chains"; a limit on a name nothing owns is silently doing nothing.`);
+
+ const turned = new Map(); // joint -> Set(axis) actually animated
+ for (const a of animsResolved)
+ for (const [jn, tr] of Object.entries(a.tracksResolved))
+ for (const ax of AX) if (tr[ax]) {
+ if (!turned.has(jn)) turned.set(jn, new Set());
+ turned.get(jn).add(ax);
+ }
+
+ // (a) undeclared
+ const allUndec = [...turned.keys()].filter(jn => !ranges[jn]);
+ // a generated R joint disappears the moment its L twin is declared, so asking for it
+ // by name would send the author to a file that must not contain it
+ const undec = allUndec.filter(jn => !(jn.startsWith('R') && sk.index[mirrorName2L(jn)] !== undefined
+ && allUndec.includes(mirrorName2L(jn)))).sort();
+ if (undec.length) {
+ const ex = undec[0], exAx = [...turned.get(ex)][0];
+ fails.push(`joint_range: ${undec.length} joint(s) are turned by an animation with no declared limit — `
+ + undec.slice(0, 8).join(', ') + (undec.length > 8 ? `, +${undec.length - 8} more` : '')
+ + `. THE FIX: add a "joint_range" block — { "${ex}": { "${exAx}": [min, max] } } — in DEGREES, in the `
+ + `joint's own frame, using the same axis names the tracks use. Write what the ANIMAL can do; an axis `
+ + `you leave out is LOCKED at 0, and "free" opts one out. Declare the L side only: R is generated.`);
+ }
+
+ // (b) overrun — keys interpolate linearly, so the key values ARE the extremes
+ for (const a of animsResolved) {
+ for (const [jn, tr] of Object.entries(a.tracksResolved)) {
+ const lim = ranges[jn]; if (!lim) continue;
+ for (const ax of AX) {
+ if (!tr[ax] || !lim[ax]) continue;
+ const [lo, hi] = lim[ax];
+ const bad = tr[ax].find(([, v]) => v < lo - 1e-6 || v > hi + 1e-6);
+ if (!bad) continue;
+ fails.push(`joint_range: "${a.name}" turns ${jn}.${ax} to ${bad[1].toFixed(1)}° at t=${(+bad[0]).toFixed(2)}, `
+ + `outside its declared limit [${lo}, ${hi}]. THE FIX: one of the two is wrong, not both — either the `
+ + `clip overreaches and the key comes back inside, or the joint really does turn that far and the limit `
+ + `was written too tight.`
+ + (mirrorName(jn) !== jn && jn.startsWith('R')
+ ? ` (${jn} and its limit are BOTH generated from the L side; edit the L side.)` : ''));
+ }
+ }
+ }
+
+ // (c) unreachable — sweep to the declared extreme and see whether the body arrives first
+ const bodyHJ = Math.max(...allV0.map(v => v[1])) - Math.min(...allV0.map(v => v[1])) || 1;
+ const hit = g => g != null && g < 0.006 * bodyHJ;
+ const poseAnim = (jn, ax, deg, tag) =>
+ ({ name: tag, tracksResolved: { [jn]: { [ax]: [[0, 0], [1, deg]] } } });
+ const bounds = [];
+ for (const [jn, lim] of Object.entries(ranges)) {
+ if (!turned.has(jn)) continue; // only limits the clips actually lean on
+ for (const ax of AX) {
+ const r = lim[ax]; if (!r) continue;
+ for (const deg of r) {
+ if (Math.abs(deg) < 1e-6) continue;
+ bounds.push({ jn, ax, deg, tag: `${jn}.${ax}@${deg}` });
+ }
+ }
+ }
+ const sweepAt = list => {
+ try {
+ return require('./selfclip.js').selfClip(
+ spec, sk, locals, meshes, list.map(b => poseAnim(b.jn, b.ax, b.deg, b.tag)),
+ 1, 4, 0.15 * bodyHJ);
+ } catch (e) { return []; }
+ };
+ if (bounds.length) {
+ const first = new Map();
+ for (const r of sweepAt(bounds)) if (hit(r.gap)) first.set(r.clip, r);
+ for (const b of bounds) {
+ const r = first.get(b.tag); if (!r) continue;
+ // ladder, only for the bounds that already failed: the largest fraction of the
+ // declared angle this body can actually hold.
+ let safe = 0;
+ for (let k = 7; k >= 1; k--) {
+ const frac = k / 8;
+ const res = sweepAt([{ jn: b.jn, ax: b.ax, deg: b.deg * frac, tag: 'L' }]);
+ if (!hit((res[0] || {}).gap)) { safe = b.deg * frac; break; }
+ }
+ fails.push(`joint_range: ${b.jn}.${b.ax} is declared to ${b.deg}°, but this body stops first — `
+ + `"${r.a}" reaches "${r.b}" (${r.gap.toFixed(3)} m apart, from ${r.rest.toFixed(2)} m at rest). `
+ + `A limit is a claim about THIS creature, not about the species. THE FIX: set the limit to `
+ + `${safe.toFixed(0)}°, which is the last angle that clears, or move the geometry that is in the way. `
+ + `Leaving the number means every clip authored against it interpenetrates.`);
+ }
+ }
+ }
+ }
+
+ // ── 7e. self_clip — the swept volume must not go through the creature itself.
+ // Joint limits say what one joint MAY do; they say nothing about where the chain ends up.
+ // A windup can stay inside legal angles the whole time and still swing a carried part
+ // through the creature's own leg — which is easy to miss by eye.
+ if (!spec.qa_isolate) {
+ let res = null;
+ const bodyH0 = Math.max(...allV0.map(v => v[1])) - Math.min(...allV0.map(v => v[1])) || 1;
+ try { res = require('./selfclip.js').selfClip(spec, sk, locals, meshes, animsResolved, 32, 4, 0.15 * bodyH0); }
+ catch (e) { res = null; }
+ for (const r of (res || [])) {
+ if (r.gap == null) continue;
+ const bodyH2 = Math.max(...allV0.map(v => v[1])) - Math.min(...allV0.map(v => v[1])) || 1;
+ if (r.gap < 0.006 * bodyH2)
+ fails.push(`self_clip: in "${r.clip}" at t=${r.t.toFixed(2)}, "${r.a}" comes within `
+ + `${r.gap.toFixed(3)} m of "${r.b}" — they are ${r.rest.toFixed(2)} m apart at rest, and they are `
+ + `not neighbours on the skeleton, so this is the animation driving one through the other. `
+ + `THE FIX: change the PLANE the part travels in, not the amount. A weapon that cannot wind `
+ + `straight back goes out to the side; a limb that sweeps through the body gets lifted over it `
+ + `(hoist the load above the shoulder before slewing, the way a crane actually works).`);
+ }
+ }
+
+ // ── 7d. clip_closes / ground_clip / attack_windup / effector_leads ──────────
+ //
+ // Four checks that all need the same thing: the mesh, skinned, at sampled times.
+ // They are grouped so the skinning is paid for once.
+ {
+ const groundY = Math.min(...allV0.map(v => v[1]));
+ const bodyH = Math.max(...allV0.map(v => v[1])) - groundY || 1;
+ const N = 32;
+ const declared = spec.function || {};
+ const effChains = new Set(Object.entries(declared).filter(([, v]) => v === 'effector').map(([k]) => k));
+ const labOf = m => `${m.material}@${m.chain || m.part || '?'}`;
+ // A part (a claw, a blade, a spike) carries no chain of its own — it hangs off a joint.
+ // Find that joint from the skin weights and ask which chain the joint belongs to, so
+ // "function": {"neck": "effector"} covers the blade bolted to the neck without the
+ // designer having to name every part. Declaring the part's own name works too.
+ const jointChain = {};
+ for (const [cn, js] of Object.entries(spec.chains || {})) for (const j of js) jointChain[j] = cn;
+ const chainOfMesh = m => {
+ if (m.chain) return m.chain;
+ const tally = {};
+ for (const w of (m.skin || [])) if (w && w[0]) tally[w[0][0]] = (tally[w[0][0]] || 0) + 1;
+ const bone = Object.keys(tally).sort((a, b) => tally[b] - tally[a])[0];
+ return bone ? jointChain[bone] : null;
+ };
+ const isEff = m => effChains.has(chainOfMesh(m))
+ || (m.part && effChains.has(String(m.part).split('@').pop()))
+ || effChains.has(m.material);
+
+ for (const a of animsResolved) {
+ const frames = [];
+ for (let f = 0; f <= N; f++) frames.push(jointWorlds(sk, locals, a, f / N));
+
+ // clip_closes — a clip that does not loop still SNAPS back when it ends.
+ // If the last frame is not the first frame, that snap is a visible pop.
+ {
+ let worst = 0, who = '';
+ for (const j of sk.joints) {
+ const i = sk.index[j.name]; if (i == null) continue;
+ const p0 = matVec(frames[0][i], [0, 0, 0]), p1 = matVec(frames[N][i], [0, 0, 0]);
+ const d = Math.hypot(p0[0] - p1[0], p0[1] - p1[1], p0[2] - p1[2]);
+ if (d > worst) { worst = d; who = j.name; }
+ }
+ if (worst > 0.05 * bodyH)
+ fails.push(`clip_closes: "${a.name}" ends ${worst.toFixed(2)} m away from where it starts `
+ + `(joint "${who}"; the ceiling is ${(0.05 * bodyH).toFixed(2)} m = 5% of the body). The clip does not `
+ + `loop, so when it finishes the creature TELEPORTS back to the rest pose. `
+ + `THE FIX: give every track a final key equal to its first key — the action must recover, `
+ + `not freeze mid-lunge.`);
+ }
+
+ // ground_clip — nothing may go below the plane the creature stands on.
+ // The collision proxy is built from the mesh, so a hand or a claw that spends the
+ // clip under the floor is a hand the physics engine will push the whole body up off.
+ {
+ let deep = 0, who = '';
+ for (const m of meshes) for (let f = 0; f <= N; f += 2) {
+ const V = skinVerts(m, sk, frames[f]);
+ for (const v of V) if (v[1] - groundY < deep) { deep = v[1] - groundY; who = labOf(m); }
+ }
+ if (deep < -0.02 * bodyH)
+ fails.push(`ground_clip: "${a.name}" drives "${who}" ${(-deep).toFixed(3)} m BELOW the ground plane `
+ + `(the ceiling is ${(0.02 * bodyH).toFixed(3)} m). The ground is the lowest point of the bind pose; `
+ + `anything under it is inside the floor. THE FIX: this is arithmetic, not posing — measure the `
+ + `penetration per frame and add it to the ROOT's "ty" track. Chasing it with joint angles does not `
+ + `converge, because a contact point rotating about a joint above it always dips below the tangent plane.`);
+ }
+
+ if (a.name !== 'attack') continue;
+
+ // The frame the attack reaches furthest forward. That is the frame that lands the
+ // hit, and the only frame whose silhouette anyone judges.
+ let peakF = 0, peakZ = -Infinity;
+ const frontOf = f => {
+ let z = -Infinity, who = '';
+ for (const m of meshes) { const V = skinVerts(m, sk, frames[f]); for (const v of V) if (v[2] > z) { z = v[2]; who = labOf(m); } }
+ return [z, who];
+ };
+ for (let f = 0; f <= N; f++) { const [z] = frontOf(f); if (z > peakZ) { peakZ = z; peakF = f; } }
+
+ // attack_windup — a strike winds BACK (or out to the side) before it commits.
+ // Straight-line push reads as a shove, and gives the physics nothing to load against.
+ {
+ let bestM = null, bestI = 0, best = -Infinity;
+ for (const m of meshes) {
+ if (effChains.size && !isEff(m)) continue;
+ for (let f = 0; f <= N; f++) { const V = skinVerts(m, sk, frames[f]);
+ for (let i = 0; i < V.length; i++) { const d = V[i][2] - m.V[i][2]; if (d > best) { best = d; bestM = m; bestI = i; } } }
+ }
+ if (bestM) {
+ const zs = [], xs = [];
+ for (let f = 0; f <= N; f++) { const V = skinVerts(bestM, sk, frames[f]); zs.push(V[bestI][2]); xs.push(V[bestI][0]); }
+ const zi = zs.indexOf(Math.max(...zs));
+ const back = zs[0] - Math.min(...zs.slice(0, zi + 1));
+ const lat = Math.max(...xs.slice(0, zi + 1)) - Math.min(...xs.slice(0, zi + 1));
+ const tot = Math.max(...zs) - Math.min(...zs) || 1e-6;
+ if (back < 0.05 * tot && lat < 0.15 * tot)
+ fails.push(`attack_windup: "${labOf(bestM)}" travels ${tot.toFixed(2)} m but never winds up — `
+ + `it pulls back ${(100 * back / tot).toFixed(0)}% (needs 5%) and swings sideways `
+ + `${(100 * lat / tot).toFixed(0)}% (needs 15%). A strike loads before it commits. `
+ + `If the structure cannot pull straight back — the weapon would sweep through the body — `
+ + `take it out to the SIDE and bring it round instead. Either route satisfies this.`);
+ }
+ }
+
+ // effector_leads — at the moment of furthest reach, the declared effector must be
+ // the frontmost thing on the creature. Otherwise the strike reads as whatever IS in
+ // front: a head-butt when it was meant to be a kick.
+ if (effChains.size) {
+ let effZ = -Infinity, othZ = -Infinity, othWho = '';
+ for (const m of meshes) { const V = skinVerts(m, sk, frames[peakF]);
+ let z = -Infinity; for (const v of V) if (v[2] > z) z = v[2];
+ if (isEff(m)) { if (z > effZ) effZ = z; } else if (z > othZ) { othZ = z; othWho = labOf(m); } }
+ if (effZ === -Infinity)
+ warns.push(`effector_leads: "function" declares effector chain(s) `
+ + `${[...effChains].map(c => `"${c}"`).join(', ')} but no mesh belongs to them.`);
+ else if (effZ <= othZ)
+ fails.push(`effector_leads: at the frame the attack reaches furthest (t=${(peakF / N).toFixed(2)}), `
+ + `the frontmost part is "${othWho}" at z=${othZ.toFixed(2)}, ahead of the declared effector at `
+ + `z=${effZ.toFixed(2)}. Whatever is in front is what the strike reads as. `
+ + `THE FIX: either the effector has to reach further — rotate the BASE the effector hangs off `
+ + `(pitching the whole torso back sends the legs forward far better than extending the legs does) `
+ + `— or "${othWho}" has to get out of the way. A part that keeps its own world aim while the body `
+ + `turns will stick out; aim it only as far as leaves the effector in front.`);
+ }
+ }
+ }
+
return { fails, warns };
}
diff --git a/engine/core/compile.js b/engine/core/compile.js
index bb6b613..09bb636 100644
--- a/engine/core/compile.js
+++ b/engine/core/compile.js
@@ -309,7 +309,7 @@ function buildEye(spec, p, builtVols) {
}
for (const v of V) allV.push(v);
const Vw = allV.map(v => G.add(c, G.mul(G.nrm(v), r)));
- out.push({ material: p.material || 'eye', V: Vw, F: tris,
+ out.push({ material: p.material || 'eye', V: Vw, F: tris, side: sx > 0 ? 'L' : 'R',
skin: Vw.map(() => [[p.host, 1]]) });
}
return out;
@@ -601,6 +601,25 @@ function buildFin(spec, p, builtVols) {
// plane axes given by udir/vdir (world), extruded ±thickness/2 along normal.
const host = spec.joints[p.host];
if (!host) throw new Error(`fin host joint "${p.host}" missing`);
+ // TWO NEARLY-COINCIDENT OUTLINE POINTS make a degenerate sliver, which extrudes
+ // into flipped triangles. The build then fails on mesh_integrity, which counts
+ // flipped tris across the WHOLE model and cannot say which part made them — so
+ // the author bisects by hand for a round. It is visible right here, before a
+ // single triangle exists, so it is said right here.
+ if (Array.isArray(p.points) && p.points.length > 2) {
+ const span = Math.max(...p.points.map(a =>
+ Math.max(...p.points.map(b => Math.hypot(a[0] - b[0], a[1] - b[1])))));
+ for (let i = 0; i < p.points.length; i++) {
+ const j = (i + 1) % p.points.length;
+ const d = Math.hypot(p.points[i][0] - p.points[j][0], p.points[i][1] - p.points[j][1]);
+ if (span > 0 && d < span * 0.02)
+ throw new Error(`fin "${p.name || p.host}": outline points ${i} and ${j} are `
+ + `${d.toFixed(4)} apart, under 2% of the shape's own size (${span.toFixed(3)}). Two points `
+ + `that close make a sliver, and extruding a sliver makes flipped triangles that show up `
+ + `later as a mesh_integrity count with no address. Merge them, or move one; 5-6 `
+ + `well-separated points is the shape this builder wants.`);
+ }
+ }
let U = G.nrm(p.udir || [0, 0, 1]), Vv = G.nrm(p.vdir || [0, 1, 0]);
let Nn = G.nrm(G.cross(U, Vv));
let o = G.add(host, p.offset || [0, 0, 0]);
@@ -719,8 +738,10 @@ function compile(spec) {
|| (p.host && Object.keys(spec.chains || {}).find(c => (spec.chains[c] || []).includes(p.host)))
|| null;
if (p.type === 'eye') {
+ // an eye part is a PAIR of meshes; they are two objects and get two names
for (const m of buildEye(spec, p, builtVols)) {
- m.part = label; m.smoothAngle = sa; m.partType = p.type; m.hostChain = hostChain; meshes.push(m); }
+ m.part = label + '.' + m.side; m.smoothAngle = sa; m.partType = p.type;
+ m.hostChain = hostChain; meshes.push(m); }
} else if (BUILDERS[p.type]) {
const m = BUILDERS[p.type](spec, p);
m.part = label; m.smoothAngle = sa; m.partType = p.type; m.hostChain = hostChain; meshes.push(m);
diff --git a/engine/core/glb.js b/engine/core/glb.js
index 2b82951..9894a90 100644
--- a/engine/core/glb.js
+++ b/engine/core/glb.js
@@ -121,6 +121,13 @@ function writeGLB(build, outPath, opts = {}) {
// every mesh ships its own primitive+material copy (the 67-material class).
// Semantic part names are the palette keys, so merging by material signature
// loses nothing the judge needs.
+ // Where each PART ended up in the merged buffers. A material is a class and is
+ // shared on purpose, so the material name cannot answer "which part is this" —
+ // the same `paw` material can sit on a foot pad and on a nose-leaf. The merge
+ // knows exactly which vertices came from which part, so it writes that down
+ // instead of throwing it away: one row per part, [first, count] into its own
+ // primitive. Nothing renders differently; the identity simply survives.
+ const spans = [];
const groups = new Map();
for (const m of meshes) {
let tris = triangulate(m.F);
@@ -158,13 +165,20 @@ function writeGLB(build, outPath, opts = {}) {
if (!g) groups.set(key, g = { m, V: [], N: [], C: m.C ? [] : null, UV: m.UV ? [] : null,
skin: m.skin ? [] : null, tris: [] });
const off = g.V.length;
+ // a mirrored twin is a different piece of geometry and gets a different id;
+ // parts already carry ".R", volumes deliberately keep their source chain name
+ // (checks compare the twin against the original by it), so it is added here
+ spans.push({ id: (m.part || (m.chain && m._mirrorSrc ? m.chain + '.R' : m.chain) || null),
+ material: m.material, _key: key, first: off, count: m.V.length });
g.V.push(...m.V); g.N.push(...N);
if (g.C && m.C) g.C.push(...m.C);
if (g.UV && m.UV) g.UV.push(...m.UV);
if (g.skin && m.skin) g.skin.push(...m.skin);
for (const t of tris) g.tris.push([t[0] + off, t[1] + off, t[2] + off]);
}
- for (const g of groups.values()) {
+ const primOf = new Map();
+ for (const [gkey, g] of groups) {
+ primOf.set(gkey, gltf.meshes[0].primitives.length);
const { m } = g;
// Portability: the hue lives in baseColorFactor, COLOR_0 carries only the
// shading multiplier. With baseColorFactor white (the old way) EVERY colour
@@ -233,6 +247,11 @@ function writeGLB(build, outPath, opts = {}) {
gltf.buffers.push({ byteLength: byteLen });
const bin = Buffer.concat(bufs);
+ if (opts.spans !== false) {
+ for (const s of spans) { s.primitive = primOf.get(s._key); delete s._key; }
+ gltf.asset.extras = Object.assign({}, gltf.asset.extras, { part_spans: spans });
+ }
+
let js = Buffer.from(JSON.stringify(gltf)); const jpad = (4 - (js.length % 4)) % 4;
if (jpad) js = Buffer.concat([js, Buffer.alloc(jpad, 0x20)]);
const total = 12 + 8 + js.length + 8 + bin.length;
diff --git a/engine/core/inside.js b/engine/core/inside.js
new file mode 100644
index 0000000..aa070b7
--- /dev/null
+++ b/engine/core/inside.js
@@ -0,0 +1,169 @@
+// ACS engine — where is this point, relative to that volume's surface?
+//
+// ONE answer, one definition. There used to be three copies of a wrong one.
+//
+// THE BUG. root_containment, limb_clearance and part_attachment each asked the
+// same question — "is this point inside that volume, and if not, how far out?" —
+// and each answered it the same way: find the nearest ring CENTRE, then compare
+// against a SPHERE whose radius is that ring's widest point.
+//
+// const rad = Math.max(...ring.map(q => G.len(G.sub(q, c2))));
+// if (best < rad * 0.98) inside++;
+//
+// A volume is not a string of spheres. It is a lofted tube, and the sphere
+// bulges past the tube's END CAP by the ring's own half-width. The error is
+// therefore WORST EXACTLY WHERE IT MATTERS MOST: at the end of a chain, which is
+// where the next chain attaches. A torso 0.80 m wide hands out 0.4 m of free
+// "inside" straight off the front of the chest — so a head sitting 0.33 m in
+// front of the last ring centre was declared buried, while its real distance to
+// the surface was 0.24 m. It floated. Nothing caught it, because all three
+// checks that could have were reading the same wrong shape.
+//
+// THE FIX is not a better radius. Any radius is still a sphere. This measures
+// against the actual triangles the file will ship.
+//
+// SIGN WITHOUT A CLOSED MESH. Ray casting needs a closed surface and these are
+// not closed: an attached chain leaves its root ring open on purpose, because it
+// is meant to be buried. So the sign comes from the surface itself — take the
+// closest point, and ask which side of ITS triangle the query point is on. Local,
+// exact for a smooth tube, and indifferent to holes elsewhere in the mesh.
+'use strict';
+
+function tris(mesh) {
+ // faces may be quads (the loft emits rings of quads); fan them once and keep it
+ if (mesh._sdT) return mesh._sdT;
+ const out = [];
+ for (const f of mesh.F) {
+ if (f.length === 3) out.push(f);
+ else for (let i = 1; i + 1 < f.length; i++) out.push([f[0], f[i], f[i + 1]]);
+ }
+ const V = mesh.V;
+ const T = out.map(t => {
+ const a = V[t[0]], b = V[t[1]], c = V[t[2]];
+ const ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ const ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
+ const n = [ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]];
+ const L = Math.hypot(n[0], n[1], n[2]) || 1;
+ const cen = [(a[0] + b[0] + c[0]) / 3, (a[1] + b[1] + c[1]) / 3, (a[2] + b[2] + c[2]) / 3];
+ const rad = Math.max(Math.hypot(a[0] - cen[0], a[1] - cen[1], a[2] - cen[2]),
+ Math.hypot(b[0] - cen[0], b[1] - cen[1], b[2] - cen[2]),
+ Math.hypot(c[0] - cen[0], c[1] - cen[1], c[2] - cen[2]));
+ return { a, b, c, n: [n[0] / L, n[1] / L, n[2] / L], cen, rad };
+ });
+ Object.defineProperty(mesh, '_sdT', { value: T, enumerable: false });
+ return T;
+}
+
+// closest point on a triangle to p — the standard region test, no iteration
+function closestOnTri(p, T) {
+ const { a, b, c } = T;
+ const ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
+ const ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
+ const ap = [p[0] - a[0], p[1] - a[1], p[2] - a[2]];
+ const d1 = ab[0] * ap[0] + ab[1] * ap[1] + ab[2] * ap[2];
+ const d2 = ac[0] * ap[0] + ac[1] * ap[1] + ac[2] * ap[2];
+ if (d1 <= 0 && d2 <= 0) return a;
+ const bp = [p[0] - b[0], p[1] - b[1], p[2] - b[2]];
+ const d3 = ab[0] * bp[0] + ab[1] * bp[1] + ab[2] * bp[2];
+ const d4 = ac[0] * bp[0] + ac[1] * bp[1] + ac[2] * bp[2];
+ if (d3 >= 0 && d4 <= d3) return b;
+ const vc = d1 * d4 - d3 * d2;
+ if (vc <= 0 && d1 >= 0 && d3 <= 0) {
+ const v = d1 / (d1 - d3);
+ return [a[0] + ab[0] * v, a[1] + ab[1] * v, a[2] + ab[2] * v];
+ }
+ const cp = [p[0] - c[0], p[1] - c[1], p[2] - c[2]];
+ const d5 = ab[0] * cp[0] + ab[1] * cp[1] + ab[2] * cp[2];
+ const d6 = ac[0] * cp[0] + ac[1] * cp[1] + ac[2] * cp[2];
+ if (d6 >= 0 && d5 <= d6) return c;
+ const vb = d5 * d2 - d1 * d6;
+ if (vb <= 0 && d2 >= 0 && d6 <= 0) {
+ const w = d2 / (d2 - d6);
+ return [a[0] + ac[0] * w, a[1] + ac[1] * w, a[2] + ac[2] * w];
+ }
+ const va = d3 * d6 - d5 * d4;
+ if (va <= 0 && (d4 - d3) >= 0 && (d5 - d6) >= 0) {
+ const w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
+ return [b[0] + (c[0] - b[0]) * w, b[1] + (c[1] - b[1]) * w, b[2] + (c[2] - b[2]) * w];
+ }
+ const den = 1 / (va + vb + vc), v = vb * den, w = vc * den;
+ return [a[0] + ab[0] * v + ac[0] * w, a[1] + ab[1] * v + ac[1] * w, a[2] + ab[2] * v + ac[2] * w];
+}
+
+// Signed distance from p to the mesh surface. NEGATIVE means inside.
+function signedDistance(p, mesh) {
+ const T = tris(mesh);
+ if (!T.length) return Infinity;
+ // Cheap bound first: a triangle whose centroid is farther than (best + its own
+ // radius) cannot beat the incumbent, so most of them never get the full test.
+ let best = Infinity, hit = null;
+ let bound = Infinity;
+ for (const t of T) {
+ const dc = Math.hypot(p[0] - t.cen[0], p[1] - t.cen[1], p[2] - t.cen[2]);
+ if (dc - t.rad >= bound) continue;
+ const q = closestOnTri(p, t);
+ const d = Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
+ if (d < best) { best = d; hit = t; bound = d; }
+ }
+ if (!hit) return Infinity;
+ const q = closestOnTri(p, hit);
+ const side = (p[0] - q[0]) * hit.n[0] + (p[1] - q[1]) * hit.n[1] + (p[2] - q[2]) * hit.n[2];
+ return side < 0 ? -best : best;
+}
+
+const isInside = (p, mesh) => signedDistance(p, mesh) < 0;
+
+const bbox = (m) => {
+ if (m._sdBox) return m._sdBox;
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
+ for (const v of m.V) for (let k = 0; k < 3; k++) {
+ if (v[k] < lo[k]) lo[k] = v[k];
+ if (v[k] > hi[k]) hi[k] = v[k];
+ }
+ const b = { lo, hi };
+ Object.defineProperty(m, '_sdBox', { value: b, enumerable: false });
+ return b;
+};
+
+// Do these two pieces of geometry actually share space? Not "are they close" —
+// close is a seam, and a seam is fine. Joined means one has material inside the
+// other, by enough that it is a weld and not a graze.
+function joined(a, b, tol, weld) {
+ const A = bbox(a), B = bbox(b);
+ for (let k = 0; k < 3; k++) if (A.lo[k] - tol > B.hi[k] || B.lo[k] - tol > A.hi[k]) return false;
+ const step = x => Math.max(1, Math.ceil(x.V.length / 240));
+ let n = 0;
+ for (const [x, y] of [[a, b], [b, a]]) {
+ const s = step(x);
+ for (let i = 0; i < x.V.length; i += s) if (signedDistance(x.V[i], y) < tol && ++n >= weld) return true;
+ }
+ return false;
+}
+
+// One body, or several? A creature is a THING, and a thing is connected. This
+// exists because a head once shipped as a free-floating object 0.24 m clear of
+// the neck, held to the creature only by two stray vertices of a foreleg that
+// happened to poke into it. Every check that could have caught that was reading
+// a sphere instead of a surface — but even with the surface, "is this seated in
+// its host" is a local question, and the failure was global. So ask the global
+// question too: walk the pieces, union the ones that share material, and refuse
+// anything that comes back as more than one island. `weld` is why two stray
+// vertices do not count as an attachment.
+function islands(meshes, tol, weld = 3) {
+ const ms = meshes.filter(m => m.V && m.V.length && m.F && m.F.length);
+ const parent = ms.map((_, i) => i);
+ const find = i => { while (parent[i] !== i) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; };
+ const union = (i, j) => { const a = find(i), b = find(j); if (a !== b) parent[a] = b; };
+ for (let i = 0; i < ms.length; i++)
+ for (let j = i + 1; j < ms.length; j++)
+ if (find(i) !== find(j) && joined(ms[i], ms[j], tol, weld)) union(i, j);
+ const groups = new Map();
+ ms.forEach((m, i) => {
+ const r = find(i);
+ if (!groups.has(r)) groups.set(r, []);
+ groups.get(r).push(m.part || m.chain || '?');
+ });
+ return [...groups.values()].sort((a, b) => b.length - a.length);
+}
+
+module.exports = { signedDistance, isInside, islands };
diff --git a/engine/core/relative.js b/engine/core/relative.js
index d4a294a..2484f64 100644
--- a/engine/core/relative.js
+++ b/engine/core/relative.js
@@ -56,7 +56,22 @@ function resolveJoints(spec) {
if (d.ground !== undefined) p[1] = d.ground;
R[name] = p;
}
- if (next.length === pend.length) throw new Error(`joints_R dependency cycle: ${next.join(', ')}`);
+ if (next.length === pend.length) {
+ // Almost always ONE mistake with one shape: an R joint written relative to
+ // ITSELF. `joints_R: { RHip: { from: "RHip", ... } }` cannot resolve and the
+ // old message said only "dependency cycle", which sends the author looking
+ // for a loop between joints that does not exist. Name it.
+ const selfRef = next.filter(n => {
+ const d = (spec.joints_R || {})[n];
+ return d && !Array.isArray(d) && d.from === n;
+ });
+ if (selfRef.length)
+ throw new Error(`joints_R: ${selfRef.join(', ')} is written relative to ITSELF `
+ + `("from": "${selfRef[0]}"). An R joint is generated from its L twin — usually the `
+ + `whole joints_R entry should just be deleted, and only kept when the right side `
+ + `genuinely sits somewhere the mirror would not put it.`);
+ throw new Error(`joints_R dependency cycle: ${next.join(', ')}`);
+ }
pend = next;
}
if (pend.length) throw new Error(`unresolvable joints_R: ${pend.join(', ')}`);
diff --git a/engine/core/selfclip.js b/engine/core/selfclip.js
new file mode 100644
index 0000000..d67081d
--- /dev/null
+++ b/engine/core/selfclip.js
@@ -0,0 +1,245 @@
+// ACS engine — self-collision over the animation (broad phase spheres, narrow phase mesh).
+//
+// Cost was the objection to doing this at all; it is not real. Sphere proxies bound to
+// the dominant bone move with a matrix multiply and never touch the skinning path, so the
+// broad phase is O(spheres^2 x frames) and independent of vertex count. Only the pairs the
+// broad phase names get skinned. A whole body comes to a few hundred spheres and tens
+// of thousands of candidate pairs, of which a few dozen reach the narrow phase; all
+// three clips together stay well under a second.
+//
+// Two filters keep it honest:
+// - joints within 3 hops on the skeleton are skipped; neighbouring parts touch by design
+// - pairs that already overlap in the BIND pose are skipped; a brace bolted to the back
+// is a static question and belongs to part_overlap, not to the animation
+'use strict';
+const { skinVerts, jointWorlds } = require('./checks.js');
+
+const mul=(a,b)=>{const o=new Array(16).fill(0);
+ for(let c=0;c<4;c++)for(let r=0;r<4;r++)for(let k=0;k<4;k++)o[c*4+r]+=a[k*4+r]*b[c*4+k];return o;};
+const apply=(m,v)=>[m[0]*v[0]+m[4]*v[1]+m[8]*v[2]+m[12],
+ m[1]*v[0]+m[5]*v[1]+m[9]*v[2]+m[13],
+ m[2]*v[0]+m[6]*v[1]+m[10]*v[2]+m[14]];
+function inv(m){ // 剛性矩陣的反矩陣:R^T 與 -R^T·t
+ const r=[m[0],m[1],m[2],m[4],m[5],m[6],m[8],m[9],m[10]];
+ const t=[m[12],m[13],m[14]];
+ const o=[r[0],r[3],r[6],0, r[1],r[4],r[7],0, r[2],r[5],r[8],0, 0,0,0,1];
+ o[12]=-(r[0]*t[0]+r[1]*t[1]+r[2]*t[2]);
+ o[13]=-(r[3]*t[0]+r[4]*t[1]+r[5]*t[2]);
+ o[14]=-(r[6]*t[0]+r[7]*t[1]+r[8]*t[2]);
+ return o; }
+
+function build(spec){
+ const s=JSON.parse(JSON.stringify(spec));
+ require(E+'relative.js').resolveJoints(s);
+ const sk=buildSkeleton(s), meshes=compile(s);
+ try{ require(E+'compile.js').drainInfo(); }catch(e){}
+ const locals=localTranslations(sk);
+ // 骨架跳數
+ const N=sk.joints.length, par=sk.joints.map(j=>j.parent);
+ const depth=i=>{let d=0,c=i; while(par[c]>=0&&d<64){c=par[c];d++;} return d;};
+ const hop=(a,b)=>{ let x=a,y=b,d=0; let dx=depth(x),dy=depth(y);
+ while(dx>dy){x=par[x];dx--;d++;} while(dy>dx){y=par[y];dy--;d++;}
+ while(x!==y&&d<64){x=par[x];y=par[y];d+=2;} return d; };
+ // 球體代理
+ const rest=jointWorlds(sk,locals,{name:'_',tracksResolved:{}},0);
+ const restInv=rest.map(inv);
+ const balls=[];
+ for(const m of meshes){
+ const grp=new Map();
+ for(let i=0;i<m.V.length;i++){
+ const w=m.skin[i]; if(!w||!w.length) continue;
+ let bn=w[0][0],bw=w[0][1];
+ for(const [n,q] of w) if(q>bw){bn=n;bw=q;}
+ const bi=sk.index[bn]; if(bi==null) continue;
+ if(!grp.has(bi)) grp.set(bi,[]); grp.get(bi).push(m.V[i]);
+ }
+ for(const [bi,P] of grp){
+ if(P.length<3) continue;
+ // 沿「兩個最長軸」切格子,不是只切一軸。
+ // 只切一軸的話,翼膜那種又寬又薄的面會變成一顆超大球(半徑=對角線一半),
+ // 兩片翅膀根本沒碰到也會被判成穿透。切成近似立方的格子才不會灌水。
+ let lo=[1e9,1e9,1e9],hi=[-1e9,-1e9,-1e9];
+ for(const p of P) for(let k=0;k<3;k++){ if(p[k]<lo[k])lo[k]=p[k]; if(p[k]>hi[k])hi[k]=p[k]; }
+ const ext=[hi[0]-lo[0],hi[1]-lo[1],hi[2]-lo[2]];
+ const ord=[0,1,2].sort((a,b)=>ext[b]-ext[a]);
+ const cell=Math.max(ext[ord[2]], Math.max(...ext)/6, 1e-3); // 目標格子邊長 ≈ 最短邊
+ const nb=[1,1,1];
+ for(const k of [ord[0],ord[1]]) nb[k]=Math.max(1,Math.min(6,Math.round(ext[k]/cell)));
+ const bins=new Map();
+ for(const p of P){
+ const key=[0,1,2].map(k=>Math.min(nb[k]-1,Math.floor(((p[k]-lo[k])/(ext[k]||1))*nb[k]))).join(',');
+ if(!bins.has(key)) bins.set(key,[]); bins.get(key).push(p);
+ }
+ for(const B of bins.values()){ if(B.length<2) continue;
+ const c=[0,0,0]; for(const p of B) for(let k=0;k<3;k++) c[k]+=p[k]/B.length;
+ let r=0; for(const p of B){ const d=Math.hypot(p[0]-c[0],p[1]-c[1],p[2]-c[2]); if(d>r)r=d; }
+ balls.push({ bone:bi, mesh:`${m.material}@${m.chain||m.part||'?'}`,
+ c:apply(restInv[bi],c), r });
+ }
+ }
+ }
+ return {s,sk,locals,meshes,balls,hop,anims:resolveAnims(s),rest};
+}
+
+function sweep(ctxo, frames=32, hopMin=4){
+ const {sk,locals,balls,hop,anims,rest}=ctxo;
+ // 先量 bind 姿勢的間距當基準線。本來就貼在一起的(背上的托架、殼縫的甲片)
+ // 不是動畫的錯 —— 那是 part_overlap / touch 管的靜態問題。
+ // 這裡只問一件事:動畫有沒有把它們壓得比休息姿勢更深。
+ const n=balls.length, pairs=[];
+ const R=balls.map(b=>apply(rest[b.bone],b.c));
+ for(let i=0;i<n;i++) for(let j=i+1;j<n;j++){
+ if(balls[i].mesh===balls[j].mesh) continue;
+ if(hop(balls[i].bone,balls[j].bone)<hopMin) continue;
+ const d0=Math.hypot(R[i][0]-R[j][0],R[i][1]-R[j][1],R[i][2]-R[j][2])-balls[i].r-balls[j].r;
+ pairs.push([i,j,d0]);
+ }
+ const meshByName=new Map();
+ for(const m of ctxo.meshes) meshByName.set(`${m.material}@${m.chain||m.part||'?'}`, m);
+ const out=[];
+ for(const a of anims){
+ // ── 粗相:球體。只負責點名「這一幀這兩塊可能撞」,不下結論。
+ const cand=new Map(); // "meshA|meshB" -> Set(frame)
+ for(let f=0;f<=frames;f++){
+ const W=jointWorlds(sk,locals,a,f/frames);
+ const P=balls.map(b=>apply(W[b.bone],b.c));
+ for(const [i,j,d0] of pairs){
+ const d=Math.hypot(P[i][0]-P[j][0],P[i][1]-P[j][1],P[i][2]-P[j][2])-balls[i].r-balls[j].r;
+ if(d-Math.min(d0,0) >= 0) continue;
+ const k=[balls[i].mesh,balls[j].mesh].sort().join('|');
+ if(!cand.has(k)) cand.set(k,new Set()); cand.get(k).add(f);
+ }
+ }
+ // ── 窄相:只對被點名的配對+幀,算真正的網格最近距離。
+ let worst=1e9, info=null, narrow=0;
+ const cacheV=new Map();
+ const vertsAt=(m,f)=>{ const k=m.material+'|'+(m.chain||m.part)+'|'+f;
+ if(!cacheV.has(k)) cacheV.set(k, skinVerts(m,sk,jointWorlds(sk,locals,a,f/frames)));
+ return cacheV.get(k); };
+ for(const [k,fs2] of cand){
+ const [na,nb2]=k.split('|'); const ma=meshByName.get(na), mb=meshByName.get(nb2);
+ if(!ma||!mb) continue;
+ const step=Math.max(1,Math.ceil(Math.max(ma.V.length,mb.V.length)/60));
+ // 先量休息姿勢的真實間距當基準
+ let rest0=1e9;
+ { const A=vertsAt(ma,0), B=vertsAt(mb,0); } // 觸發 cache(用第 0 幀近似不準,改用 restV)
+ const RA=skinVerts(ma,sk,rest), RB=skinVerts(mb,sk,rest);
+ for(let i=0;i<RA.length;i+=step) for(let j=0;j<RB.length;j+=step){
+ const d=Math.hypot(RA[i][0]-RB[j][0],RA[i][1]-RB[j][1],RA[i][2]-RB[j][2]); if(d<rest0)rest0=d; }
+ for(const f of fs2){
+ const A=vertsAt(ma,f), B=vertsAt(mb,f);
+ let mn=1e9;
+ for(let i=0;i<A.length;i+=step) for(let j=0;j<B.length;j+=step){
+ const d=Math.hypot(A[i][0]-B[j][0],A[i][1]-B[j][1],A[i][2]-B[j][2]); if(d<mn)mn=d; }
+ narrow++;
+ const rel=mn-Math.min(rest0,1e9);
+ if(rel<worst){ worst=rel; info={t:+(f/frames).toFixed(2),a:na,b:nb2,rest:+rest0.toFixed(3),abs:+mn.toFixed(3)}; }
+ }
+ }
+ out.push({clip:a.name, gap:+worst.toFixed(3), pairs:pairs.length, cand:cand.size, narrow, ...info});
+ }
+ return out;
+}
+
+function buildProxies(sk, meshes, restWorld) {
+ const restInv = restWorld.map(inv);
+ const balls = [];
+ for (const m of meshes) {
+ const grp = new Map();
+ for (let i = 0; i < m.V.length; i++) {
+ const w = m.skin[i]; if (!w || !w.length) continue;
+ let bn = w[0][0], bw = w[0][1];
+ for (const [n, q] of w) if (q > bw) { bn = n; bw = q; }
+ const bi = sk.index[bn]; if (bi == null) continue;
+ if (!grp.has(bi)) grp.set(bi, []); grp.get(bi).push(m.V[i]);
+ }
+ for (const [bi, P] of grp) {
+ if (P.length < 3) continue;
+ // Bin along the TWO longest axes so each cell is roughly cubic. Binning one axis
+ // turns a wing membrane into one sphere of radius half its diagonal, and two wings
+ // that never touch report a collision.
+ let lo = [1e9, 1e9, 1e9], hi = [-1e9, -1e9, -1e9];
+ for (const p of P) for (let k = 0; k < 3; k++) { if (p[k] < lo[k]) lo[k] = p[k]; if (p[k] > hi[k]) hi[k] = p[k]; }
+ const ext = [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]];
+ const ord = [0, 1, 2].sort((a, b) => ext[b] - ext[a]);
+ const cell = Math.max(ext[ord[2]], Math.max(...ext) / 6, 1e-3);
+ const nb = [1, 1, 1];
+ for (const k of [ord[0], ord[1]]) nb[k] = Math.max(1, Math.min(6, Math.round(ext[k] / cell)));
+ const bins = new Map();
+ for (const p of P) {
+ const key = [0, 1, 2].map(k => Math.min(nb[k] - 1, Math.floor(((p[k] - lo[k]) / (ext[k] || 1)) * nb[k]))).join(',');
+ if (!bins.has(key)) bins.set(key, []); bins.get(key).push(p);
+ }
+ for (const B of bins.values()) {
+ if (B.length < 2) continue;
+ const c = [0, 0, 0]; for (const p of B) for (let k = 0; k < 3; k++) c[k] += p[k] / B.length;
+ let r = 0; for (const p of B) { const d = Math.hypot(p[0] - c[0], p[1] - c[1], p[2] - c[2]); if (d > r) r = d; }
+ balls.push({ bone: bi, mesh: `${m.material}@${m.chain || m.part || '?'}`, c: apply(restInv[bi], c), r });
+ }
+ }
+ }
+ return balls;
+}
+
+function selfClip(spec, sk, locals, meshes, anims, frames = 32, hopMin = 4, restMin = 0) {
+ const rest = jointWorlds(sk, locals, { name: '_', tracksResolved: {} }, 0);
+ const balls = buildProxies(sk, meshes, rest);
+ const par = sk.joints.map(j => j.parent);
+ const depth = i => { let d = 0, c = i; while (par[c] >= 0 && d < 64) { c = par[c]; d++; } return d; };
+ const hop = (a, b) => { let x = a, y = b, d = 0, dx = depth(x), dy = depth(y);
+ while (dx > dy) { x = par[x]; dx--; d++; } while (dy > dx) { y = par[y]; dy--; d++; }
+ while (x !== y && d < 64) { x = par[x]; y = par[y]; d += 2; } return d; };
+ const R = balls.map(b => apply(rest[b.bone], b.c));
+ const pairs = [];
+ for (let i = 0; i < balls.length; i++) for (let j = i + 1; j < balls.length; j++) {
+ if (balls[i].mesh === balls[j].mesh) continue;
+ if (hop(balls[i].bone, balls[j].bone) < hopMin) continue;
+ const d0 = Math.hypot(R[i][0] - R[j][0], R[i][1] - R[j][1], R[i][2] - R[j][2]) - balls[i].r - balls[j].r;
+ // Only pairs that start FAR APART. Fingers on the same wing, a membrane and the arm
+ // that carries it, a neck and the chest it grows out of — all sit at ~0 m at rest and
+ // will "close" the moment anything moves. The defect this check exists for looks
+ // different: something that was a metre away arrives at a millimetre.
+ if (d0 < restMin) continue;
+ pairs.push([i, j, d0]);
+ }
+ const byName = new Map(); for (const m of meshes) byName.set(`${m.material}@${m.chain || m.part || '?'}`, m);
+ const out = [];
+ for (const a of anims) {
+ const cand = new Map();
+ for (let f = 0; f <= frames; f++) {
+ const W = jointWorlds(sk, locals, a, f / frames);
+ const P = balls.map(b => apply(W[b.bone], b.c));
+ for (const [i, j, d0] of pairs) {
+ const d = Math.hypot(P[i][0] - P[j][0], P[i][1] - P[j][1], P[i][2] - P[j][2]) - balls[i].r - balls[j].r;
+ if (d >= 0) continue;
+ const k = [balls[i].mesh, balls[j].mesh].sort().join('|');
+ if (!cand.has(k)) cand.set(k, new Set()); cand.get(k).add(f);
+ }
+ }
+ let worst = Infinity, info = null;
+ for (const [k, fs] of cand) {
+ const [na, nb] = k.split('|'); const ma = byName.get(na), mb = byName.get(nb);
+ if (!ma || !mb) continue;
+ const step = Math.max(1, Math.ceil(Math.max(ma.V.length, mb.V.length) / 60));
+ const RA = skinVerts(ma, sk, rest), RB = skinVerts(mb, sk, rest);
+ let rest0 = Infinity;
+ for (let i = 0; i < RA.length; i += step) for (let j = 0; j < RB.length; j += step) {
+ const d = Math.hypot(RA[i][0] - RB[j][0], RA[i][1] - RB[j][1], RA[i][2] - RB[j][2]); if (d < rest0) rest0 = d; }
+ // Re-apply the "far apart at rest" filter on the TRUE mesh distance. Spheres
+ // over-approximate, so a pair can clear the broad-phase filter and still be two
+ // things that touch in the bind pose.
+ if (rest0 < restMin) continue;
+ for (const f of fs) {
+ const W = jointWorlds(sk, locals, a, f / frames);
+ const A = skinVerts(ma, sk, W), B = skinVerts(mb, sk, W);
+ let mn = Infinity;
+ for (let i = 0; i < A.length; i += step) for (let j = 0; j < B.length; j += step) {
+ const d = Math.hypot(A[i][0] - B[j][0], A[i][1] - B[j][1], A[i][2] - B[j][2]); if (d < mn) mn = d; }
+ if (mn < worst) { worst = mn; info = { t: f / frames, a: na, b: nb, rest: rest0 }; }
+ }
+ }
+ out.push({ clip: a.name, gap: worst === Infinity ? null : worst, ...(info || {}) });
+ }
+ return out;
+}
+module.exports = { selfClip };
diff --git a/engine/core/skeleton.js b/engine/core/skeleton.js
index 574307b..96c5d80 100644
--- a/engine/core/skeleton.js
+++ b/engine/core/skeleton.js
@@ -157,4 +157,59 @@ function exportNames(spec, sk) {
return map;
}
-module.exports = { buildSkeleton, localTranslations, inverseBindMatrices, mirrorName, exportNames };
+// ── joint_range — how far each joint is allowed to turn ──────────────────────
+//
+// Degrees, per axis, in the joint's OWN frame: the same frame and the same axis
+// names (rx/ry/rz) the animation tracks already use, so a limit and a track are
+// directly comparable and no second coordinate convention exists to get wrong.
+//
+// The numbers are AUTHORED, not discovered. Whoever writes the spec already
+// knows a knee bends one way, an elbow does not twist and a jaw opens further
+// than a wrist bends — that knowledge is free to write down and impossible to
+// compute from geometry. What the author does NOT know is how thick THIS
+// creature's thigh is, so the declared limit is treated as a claim about the
+// body and checks.js sweeps it against the body.
+//
+// An axis a joint declares nothing for is LOCKED at 0, not free. A limit table
+// with holes in it is a table that checks nothing, and the common case is one
+// axis per joint anyway. "free" opts an axis out explicitly (a wheel, a rotor).
+//
+// The R side is GENERATED and must never be authored. Mirroring negates ry and
+// rz — the same rule compileAnim applies to tracks — and negating an interval
+// swaps its ends, so [-10, 90] becomes [-90, 10]. An author writing both sides
+// by hand is the exact shape of the mirror bug this release fixed.
+const RANGE_AXES = ['rx', 'ry', 'rz'];
+
+function jointRanges(spec, sk) {
+ const out = {};
+ const norm = (jn, r) => {
+ const o = {};
+ for (const ax of RANGE_AXES) {
+ const v = r[ax];
+ if (v === undefined) { o[ax] = [0, 0]; continue; } // unwritten = locked
+ if (v === 'free') { o[ax] = null; continue; } // explicitly unbounded
+ if (!Array.isArray(v) || v.length !== 2 || !v.every(x => Number.isFinite(x)))
+ throw new Error(`joint_range "${jn}".${ax}: expected [min, max] in degrees, or "free"`);
+ o[ax] = [Math.min(v[0], v[1]), Math.max(v[0], v[1])];
+ }
+ return o;
+ };
+ for (const [jn, r] of Object.entries(spec.joint_range || {})) {
+ if (!r || typeof r !== 'object') throw new Error(`joint_range "${jn}": expected an object of axes`);
+ out[jn] = norm(jn, r);
+ }
+ // generate the R side for every declared L joint whose twin exists
+ for (const jn of Object.keys(spec.joint_range || {})) {
+ const rj = mirrorName(jn);
+ if (rj === jn || out[rj]) continue; // not mirrored, or overridden
+ if (sk && sk.index && sk.index[rj] === undefined) continue; // no such twin on this body
+ const s = out[jn];
+ out[rj] = { rx: s.rx && s.rx.slice(),
+ ry: s.ry && [-s.ry[1], -s.ry[0]],
+ rz: s.rz && [-s.rz[1], -s.rz[0]] };
+ }
+ return out;
+}
+
+module.exports = { buildSkeleton, localTranslations, inverseBindMatrices, mirrorName, exportNames,
+ jointRanges, RANGE_AXES };
diff --git a/example/README.md b/example/README.md
index a28718d..760e43b 100644
--- a/example/README.md
+++ b/example/README.md
@@ -17,11 +17,10 @@ Measured: high-saturation area **26.0%** of the tq view, mid-band for the
```bash
# rebuild
node engine/cli.js example/wolf.json example/wolf.glb
-# silhouettes (front/side/top/hero45) + numbers + 24/48px thumbs
-node harness/silmetrics.mjs example/wolf.glb out/r1
-# per-view measures + dullness flags
-python3 harness/maskmetrics.py out/r1 out/r1/sil_front.png out/r1/sil_side.png \
- out/r1/sil_top.png out/r1/sil_hero.png
-# metrics incl. hi_sat_share per view (add --spec <claims.json> to check claims)
+# silhouettes + thumbs + every measure (layout, boldness, part shares, colour)
+python3 harness/outline.py example/wolf.glb out/r1
+# the hero shot, projected not rendered
+python3 harness/outline.py example/wolf.glb out/r1 --hero out/r1/hero.png
+# claims judged over those numbers (add --spec <claims.json> to check claims)
node harness/judge.mjs example/wolf.glb out/j wolf
```
diff --git a/example/wolf.checks.json b/example/wolf.checks.json
new file mode 100644
index 0000000..86a97f9
--- /dev/null
+++ b/example/wolf.checks.json
@@ -0,0 +1,68 @@
+{
+ "spec": "wolf.json",
+ "passed": true,
+ "checks": [
+ {
+ "name": "mesh_integrity",
+ "passed": true
+ },
+ {
+ "name": "root_containment",
+ "passed": true
+ },
+ {
+ "name": "part_attachment",
+ "passed": true
+ },
+ {
+ "name": "touch",
+ "passed": true
+ },
+ {
+ "name": "balance",
+ "passed": true
+ },
+ {
+ "name": "size",
+ "passed": true,
+ "warned": true
+ },
+ {
+ "name": "proportion",
+ "passed": true
+ },
+ {
+ "name": "limb_clearance",
+ "passed": true
+ },
+ {
+ "name": "anim_integrity",
+ "passed": true
+ },
+ {
+ "name": "attack_reach",
+ "passed": true
+ },
+ {
+ "name": "faceted_body",
+ "passed": true
+ },
+ {
+ "name": "mirror_distortion",
+ "passed": true
+ },
+ {
+ "name": "part_overlap",
+ "passed": true
+ },
+ {
+ "name": "part_seat",
+ "passed": true
+ }
+ ],
+ "blocking": [],
+ "measures": [
+ "value_order: materials by lightness, brightest first — eye 0.78 · fur_head 0.56 · fur_tail 0.56 · fur_body 0.55 · fur_paw 0.51 · fur_leg 0.46 · ear 0.46 · nose 0.19",
+ "contrast_adjacent: part \"front_paw\" (fur_paw, L 0.51) against its host \"LFront\" (fur_leg, L 0.46) — OKLab distance 0.042, under 0.10. They will read as one mass at thumbnail size. Move one of them in LIGHTNESS, which is what survives shrinking; hue alone does not."
+ ]
+}
\ No newline at end of file
diff --git a/example/wolf.glb b/example/wolf.glb
index 2268ef7..697e472 100644
Binary files a/example/wolf.glb and b/example/wolf.glb differ
diff --git a/example/wolf.json b/example/wolf.json
index 18f16ca..ce83f58 100644
--- a/example/wolf.json
+++ b/example/wolf.json
@@ -236,7 +236,7 @@
"sides": 16,
"profile": [
[
- 0.0,
+ 0,
0.14,
0.16
],
@@ -279,7 +279,7 @@
0.19
],
[
- 1.0,
+ 1,
0.175,
0.2
]
@@ -311,7 +311,7 @@
"sides": 14,
"profile": [
[
- 0.0,
+ 0,
0.155,
0.17
],
@@ -347,7 +347,7 @@
0.072
],
[
- 1.0,
+ 1,
0.06,
0.052
]
@@ -531,7 +531,8 @@
0.055
]
],
- "mirrored": true
+ "mirrored": true,
+ "name": "ear"
},
{
"type": "eye",
@@ -542,7 +543,8 @@
"chain": "head",
"t": 0.4,
"around": 62
- }
+ },
+ "name": "eye"
},
{
"type": "spike",
@@ -550,7 +552,7 @@
"offset": [
0,
0.005,
- 0.0
+ 0
],
"dir": [
0,
@@ -564,7 +566,8 @@
}
],
"sides": 8,
- "material": "nose"
+ "material": "nose",
+ "name": "nose_pad"
},
{
"type": "paw",
@@ -575,7 +578,8 @@
0.151,
0.076
],
- "mirrored": true
+ "mirrored": true,
+ "name": "front_paw"
},
{
"type": "paw",
@@ -586,7 +590,8 @@
0.158,
0.076
],
- "mirrored": true
+ "mirrored": true,
+ "name": "back_paw"
}
],
"animations": {
@@ -689,15 +694,15 @@
"rx": [
[
0,
- -26
+ -20.8
],
[
0.5,
- 28
+ 22.4
],
[
1,
- -26
+ -20.8
]
]
},
@@ -745,15 +750,15 @@
"rx": [
[
0,
- 24
+ 19.2
],
[
0.5,
- -22
+ -17.6
],
[
1,
- 24
+ 19.2
]
]
},
@@ -852,8 +857,335 @@
9
]
]
+ },
+ "Rump": {
+ "ty": [
+ [
+ 0,
+ 0.083
+ ],
+ [
+ 0.042,
+ 0.03
+ ],
+ [
+ 0.083,
+ 0.037
+ ],
+ [
+ 0.125,
+ 0.037
+ ],
+ [
+ 0.167,
+ 0.037
+ ],
+ [
+ 0.208,
+ 0.0362
+ ],
+ [
+ 0.25,
+ 0.0273
+ ],
+ [
+ 0.292,
+ 0.0103
+ ],
+ [
+ 0.333,
+ 0.004
+ ],
+ [
+ 0.375,
+ 0.004
+ ],
+ [
+ 0.417,
+ 0.0152
+ ],
+ [
+ 0.458,
+ 0.0249
+ ],
+ [
+ 0.5,
+ 0.0289
+ ],
+ [
+ 0.542,
+ 0.0321
+ ],
+ [
+ 0.583,
+ 0.0344
+ ],
+ [
+ 0.625,
+ 0.0358
+ ],
+ [
+ 0.667,
+ 0.0364
+ ],
+ [
+ 0.708,
+ 0.0364
+ ],
+ [
+ 0.75,
+ 0.0427
+ ],
+ [
+ 0.792,
+ 0.0539
+ ],
+ [
+ 0.833,
+ 0.0662
+ ],
+ [
+ 0.875,
+ 0.075
+ ],
+ [
+ 0.917,
+ 0.079
+ ],
+ [
+ 0.958,
+ 0.083
+ ],
+ [
+ 1,
+ 0.083
+ ]
+ ]
}
}
}
+ },
+ "function": {
+ "body": "axis",
+ "head": "ornament",
+ "tail": "ornament",
+ "LFront": "locomotion",
+ "LBack": "locomotion"
+ },
+ "joint_range": {
+ "Rump": {
+ "rx": [
+ -20,
+ 20
+ ],
+ "rz": [
+ -15,
+ 15
+ ]
+ },
+ "Hips": {
+ "rx": [
+ -20,
+ 20
+ ],
+ "rz": [
+ -18,
+ 18
+ ]
+ },
+ "Spine": {
+ "rx": [
+ -25,
+ 25
+ ],
+ "rz": [
+ -15,
+ 15
+ ]
+ },
+ "Chest": {
+ "rx": [
+ -25,
+ 25
+ ],
+ "rz": [
+ -15,
+ 15
+ ]
+ },
+ "NeckB": {
+ "rx": [
+ -35,
+ 45
+ ],
+ "ry": [
+ -45,
+ 45
+ ],
+ "rz": [
+ -20,
+ 20
+ ]
+ },
+ "Neck2": {
+ "rx": [
+ -30,
+ 40
+ ],
+ "ry": [
+ -40,
+ 40
+ ],
+ "rz": [
+ -20,
+ 20
+ ]
+ },
+ "HeadRoot": {
+ "rx": [
+ -40,
+ 40
+ ],
+ "ry": [
+ -60,
+ 60
+ ],
+ "rz": [
+ -30,
+ 30
+ ]
+ },
+ "Skull": {
+ "rx": [
+ -25,
+ 25
+ ],
+ "ry": [
+ -30,
+ 30
+ ],
+ "rz": [
+ -20,
+ 20
+ ]
+ },
+ "Brow": {
+ "rx": [
+ -10,
+ 10
+ ]
+ },
+ "Muzzle": {
+ "rx": [
+ -8,
+ 35
+ ]
+ },
+ "Nose": {
+ "rx": [
+ -5,
+ 5
+ ]
+ },
+ "TailRoot": {
+ "rx": [
+ -45,
+ 55
+ ],
+ "ry": [
+ -40,
+ 40
+ ],
+ "rz": [
+ -25,
+ 25
+ ]
+ },
+ "Tail1": {
+ "rx": [
+ -40,
+ 50
+ ],
+ "ry": [
+ -40,
+ 40
+ ]
+ },
+ "Tail2": {
+ "rx": [
+ -40,
+ 50
+ ],
+ "ry": [
+ -40,
+ 40
+ ]
+ },
+ "TailTip": {
+ "rx": [
+ -35,
+ 45
+ ],
+ "ry": [
+ -35,
+ 35
+ ]
+ },
+ "LFrontRoot": {
+ "rx": [
+ -50,
+ 60
+ ],
+ "ry": [
+ -25,
+ 25
+ ]
+ },
+ "LFrontElbow": {
+ "rx": [
+ -80,
+ 40
+ ]
+ },
+ "LFrontWrist": {
+ "rx": [
+ -35,
+ 35
+ ]
+ },
+ "LFrontToe": {
+ "rx": [
+ -30,
+ 30
+ ]
+ },
+ "LBackRoot": {
+ "rx": [
+ -55,
+ 65
+ ],
+ "ry": [
+ -25,
+ 25
+ ]
+ },
+ "LBackKnee": {
+ "rx": [
+ -40,
+ 80
+ ]
+ },
+ "LBackHock": {
+ "rx": [
+ -70,
+ 35
+ ]
+ },
+ "LBackToe": {
+ "rx": [
+ -35,
+ 35
+ ]
+ }
}
}
\ No newline at end of file
diff --git a/harness/autofix.mjs b/harness/autofix.mjs
new file mode 100644
index 0000000..f34a1b9
--- /dev/null
+++ b/harness/autofix.mjs
@@ -0,0 +1,204 @@
+#!/usr/bin/env node
+// ACS harness — automatic animation corrections.
+//
+// Three things the engine BLOCKS on are pure arithmetic: the animator should not be
+// hand-solving them, and every creature's animation is different so they cannot be
+// hardcoded. fit.py runs this before a round is spent.
+//
+// ground_clip -> measure the penetration per frame, add it to the ROOT's ty.
+// Chasing it with joint angles does not converge: a contact point
+// rotating about a joint above it always dips below the tangent plane.
+// clip_closes -> give every track a final key equal to its first key.
+// carrier compensation -> a joint that must keep its own world aim while the body
+// turns for some OTHER purpose gets the parent's inverse rotation
+// written into it. Do NOT iterate on angles: once the parent passes
+// vertical the atan2 jumps and the correction diverges (measured: the
+// head ended up facing backwards and the neck tore).
+// The compensation is SUBORDINATE to the action's purpose — a head
+// aimed forward pushes its muzzle out front, and if that overtakes the
+// declared effector the strike reads as a head-butt. So the share is
+// solved for, not assumed.
+//
+// usage: node harness/autofix.mjs <spec.json> [out.json]
+// .mjs in this harness means ESM; the engine is CommonJS, so pull it in with createRequire.
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+const require = createRequire(import.meta.url);
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const EP = path.join(__dirname, '..', 'engine', 'core') + path.sep;
+
+function closeLoop(tracks){
+ for(const tr of Object.values(tracks))
+ for(const [ax,k] of Object.entries(tr)){
+ if(!k.length) continue;
+ const v0=k[0][1];
+ if(k[k.length-1][0]>=0.999) k[k.length-1][1]=v0; else k.push([1,v0]);
+ }
+ return tracks;
+}
+
+
+function groundFix(spec, rootBone){
+ const { compile }=require(EP+'compile.js');
+ const { buildSkeleton, localTranslations }=require(EP+'skeleton.js');
+ const { skinVerts, jointWorlds }=require(EP+'checks.js');
+ const mirrorName=n=>n.startsWith('L')?'R'+n.slice(1):n;
+ const work=JSON.parse(JSON.stringify(spec));
+ require(EP+'relative.js').resolveJoints(work);
+ const sk=buildSkeleton(work), meshes=compile(work);
+ try{ require(EP+'compile.js').drainInfo(); }catch(e){}
+ const locals=localTranslations(sk);
+ const GROUND=Math.min(...meshes.flatMap(m=>m.V).map(v=>v[1]));
+ const N=24;
+ for(const [name,a0] of Object.entries(work.animations)){
+ const tracks={...a0.tracks}, ph=a0.mirror_phase??0;
+ for(const cn of work.mirror||[]) for(const jn of (work.chains[cn]||[])){
+ if(!tracks[jn]||tracks[mirrorName(jn)]) continue; const d={};
+ for(const [ax,k] of Object.entries(tracks[jn])){ const f=(ax==='ry'||ax==='rz'||ax==='tx')?-1:1;
+ d[ax]=k.map(([t,v])=>[(t+ph)%1,v*f]).sort((p,q)=>p[0]-q[0]); }
+ tracks[mirrorName(jn)]=d; }
+ const a={name,tracksResolved:tracks};
+ const lift=[];
+ for(let s=0;s<=N;s++){ const w=jointWorlds(sk,locals,a,s/N);
+ let mn=1e9;
+ for(const m of meshes){ const V2=skinVerts(m,sk,w); for(const v of V2) if(v[1]<mn) mn=v[1]; }
+ lift.push(Math.max(0, GROUND-mn)); }
+ // 平滑一點,免得補償本身變成抖動
+ const sm=lift.map((v,i)=>Math.max(v,lift[(i+N)%(N+1)],lift[(i+1)%(N+1)],lift[(i-1+N+1)%(N+1)]));
+ if(Math.max(...sm)<0.005) continue;
+ const T=spec.animations[name].tracks;
+ T[rootBone]=T[rootBone]||{};
+ const base=T[rootBone].ty||[];
+ const at2=(k,t)=>{ if(!k.length) return 0; t=((t%1)+1)%1;
+ for(let i=0;i<k.length-1;i++){const [t0,v0]=k[i],[t1,v1]=k[i+1];
+ if(t>=t0&&t<=t1) return v0+(v1-v0)*(t1===t0?0:(t-t0)/(t1-t0));}
+ return k[k.length-1][1]; };
+ T[rootBone].ty = sm.map((v,i)=>[+(i/N).toFixed(3), +(at2(base,i/N)+v+0.004).toFixed(4)]);
+ }
+ return spec;
+}
+
+
+function aimCompensate(spec, clipName, bone, share){
+ // 補償 = 直接寫入「父關節世界旋轉的反轉」。
+ // 骨頭的世界旋轉 = R_parent(t) · R_anim(t);令 R_anim = R_parent(t)⁻¹,
+ // 世界旋轉就回到單位(=休息時的朝向),頭就一直盯著前方。
+ // 不要用角度迭代:父關節越過垂直時 atan2 會跳,補償跟著發散(實測頭會翻到背面、脖子被扯破)。
+ const { compile }=require(EP+'compile.js');
+ const { buildSkeleton, localTranslations }=require(EP+'skeleton.js');
+ const { jointWorlds }=require(EP+'checks.js');
+ const k=share??1, N=16;
+ const work=JSON.parse(JSON.stringify(spec));
+ require(EP+'relative.js').resolveJoints(work);
+ const sk=buildSkeleton(work); compile(work);
+ try{ require(EP+'compile.js').drainInfo(); }catch(e){}
+ const locals=localTranslations(sk);
+ const anim={name:clipName, tracksResolved:work.animations[clipName].tracks};
+ const bi=sk.index[bone]; if(bi==null) return;
+ const pi=sk.joints[bi].parent; if(pi<0) return;
+ // 欄位優先的 4x4:m[col*4+row]。轉置=旋轉的反轉。
+ const eulXYZ=(m)=>{ // 對照 three.js Euler 'XYZ'
+ const m11=m[0],m12=m[4],m13=m[8],m22=m[5],m23=m[9],m32=m[6],m33=m[10];
+ const c=v=>Math.max(-1,Math.min(1,v));
+ let x,y,z;
+ y=Math.asin(c(m13));
+ if(Math.abs(m13)<0.9999999){ x=Math.atan2(-m23,m33); z=Math.atan2(-m12,m11); }
+ else { x=Math.atan2(m32,m22); z=0; }
+ return [x*57.29578,y*57.29578,z*57.29578];
+ };
+ const rx=[],ry=[],rz=[];
+ for(let i=0;i<=N;i++){
+ const t=i/N, w=jointWorlds(sk,locals,anim,t), P=w[pi];
+ // 取出旋轉並轉置(列變欄)
+ const T=[P[0],P[4],P[8],0, P[1],P[5],P[9],0, P[2],P[6],P[10],0, 0,0,0,1];
+ const [ex,ey,ez]=eulXYZ(T);
+ rx.push([+t.toFixed(3), +(ex*k).toFixed(2)]);
+ ry.push([+t.toFixed(3), +(ey*k).toFixed(2)]);
+ rz.push([+t.toFixed(3), +(ez*k).toFixed(2)]);
+ }
+ spec.animations[clipName].tracks[bone]={rx,ry,rz};
+}
+
+// 補償要「服從動作的目的」。頭轉正 → 吻端往前吐;吻端一旦超過作用端,
+// 這個動作就從踢變成頭撞。所以補償的幅度不是常數,是解出來的:
+// 從 1.0 往下找,找到最大的 share,使得峰值幀時作用端仍在最前面。
+function aimSubordinate(spec, clipName, bone, effRe, marginFrac){
+ const { compile }=require(EP+'compile.js');
+ const { buildSkeleton, localTranslations }=require(EP+'skeleton.js');
+ const { skinVerts, jointWorlds }=require(EP+'checks.js');
+ const lab=m=>`${m.material}@${m.chain||m.part||'?'}`;
+ const test=(share)=>{
+ const t=JSON.parse(JSON.stringify(spec));
+ aimCompensate(t, clipName, bone, share);
+ const work=JSON.parse(JSON.stringify(t));
+ require(EP+'relative.js').resolveJoints(work);
+ const sk=buildSkeleton(work), meshes=compile(work);
+ try{ require(EP+'compile.js').drainInfo(); }catch(e){}
+ const locals=localTranslations(sk);
+ const a={name:clipName, tracksResolved:work.animations[clipName].tracks};
+ // 取樣密度要跟驗證端一致(48)。之前解算器用 32、驗證用 48,
+ // 峰值幀不同、結論就相反 —— 解出來的東西過不了自己的驗收。
+ const N=48; const glob=[];
+ for(let f=0;f<=N;f++){ const w=jointWorlds(sk,locals,a,f/N);
+ let z=-1e9; for(const m of meshes){ const V=skinVerts(m,sk,w); for(const v of V) if(v[2]>z)z=v[2]; }
+ glob.push(z); }
+ const bz=Math.max(...glob);
+ // 不只看峰值那一幀:峰值附近 5% 帶內的每一幀都要成立,才不會因為取樣位置不同而翻盤
+ let worst=1e9, effAt=0, othAt=0, top='';
+ for(let f=0;f<=N;f++){
+ if(glob[f] < bz-0.05*Math.abs(bz)) continue;
+ const w=jointWorlds(sk,locals,a,f/N);
+ let effZ=-1e9, othZ=-1e9, who='';
+ for(const m of meshes){ const V=skinVerts(m,sk,w); let z=-1e9; for(const v of V) if(v[2]>z)z=v[2];
+ if(effRe.test(lab(m))){ if(z>effZ) effZ=z; } else if(z>othZ){ othZ=z; who=lab(m); } }
+ const d=effZ-othZ;
+ if(d<worst){ worst=d; effAt=effZ; othAt=othZ; top=who; }
+ }
+ return {ok: worst > (marginFrac??0.02), effZ:effAt, othZ:othAt, top};
+ };
+ let best=0, r=null;
+ for(const sh of [1.0,0.85,0.7,0.55,0.4,0.25,0.1,0]){
+ const q=test(sh);
+ if(q.ok){ best=sh; r=q; break; }
+ }
+ aimCompensate(spec, clipName, bone, best);
+ console.error(` ${bone} 補償 share=${best}${r?`(作用端 ${r.effZ.toFixed(2)} > 其餘最前 ${r.top} ${r.othZ.toFixed(2)})`:'(找不到可行值)'}`);
+}
+
+function autofix(spec) {
+ const axis = Object.keys(spec.chains || {})[0];
+ const root = (spec.chains[axis] || [])[0];
+ const eff = new Set(Object.entries(spec.function || {}).filter(([, v]) => v === 'effector').map(([k]) => k));
+ for (const [name, clip] of Object.entries(spec.animations || {})) {
+ if (clip.loop === false) closeLoop(clip.tracks);
+ }
+ // Compensate any chain that is NOT on the path to the effector but carries an eye:
+ // the thing that has to keep watching where the action is going. Derived, not configured.
+ if (eff.size) {
+ const eyed = new Set();
+ for (const p of spec.parts || []) if (p.type === 'eye' && p.host) {
+ for (const [cn, js] of Object.entries(spec.chains || {})) if (js.includes(p.host)) eyed.add(cn);
+ }
+ for (const cn of eyed) {
+ if (eff.has(cn)) continue;
+ const bone = (spec.chains[cn] || [])[0];
+ if (!bone) continue;
+ for (const name of Object.keys(spec.animations || {})) {
+ if (name !== 'attack') continue;
+ aimSubordinate(spec, name, bone, new RegExp([...eff].join('|')), 0.03);
+ }
+ }
+ }
+ if (root) groundFix(spec, root);
+ return spec;
+}
+export { autofix, closeLoop, groundFix, aimCompensate, aimSubordinate };
+if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
+ const inp = process.argv[2], outp = process.argv[3] || inp;
+ if (!inp) { console.error('usage: node harness/autofix.mjs <spec.json> [out.json]'); process.exit(2); }
+ const spec = JSON.parse(fs.readFileSync(inp, 'utf8'));
+ fs.writeFileSync(outp, JSON.stringify(autofix(spec), null, 1));
+ console.error(`[autofix] ${path.basename(inp)} -> ${path.basename(outp)}`);
+}
diff --git a/harness/brief.py b/harness/brief.py
index 4345b8e..94030fc 100644
--- a/harness/brief.py
+++ b/harness/brief.py
@@ -44,11 +44,10 @@ THE NAMED-CHAIN CONTRACT. Slots that name PARTS may end with
and those names must exist in the spec. This is still presence, not content —
you invent the names, the check only asks that what you promised got built. It
-exists because of a measured failure: one boss brief named "the boulder in the
-iron net at the beam's tip" as its second focal in minute four, part_exists sits
-at stage MID, and nothing required that part until MID — so rounds 1 to 3 built
-an incomplete brief and the shape the customer eventually singled out did not
-appear until round 4.
+exists because of a failure mode with teeth: a brief names a part in one of its
+focal slots, part_exists sits at stage MID, and nothing requires that part until
+MID — so the early rounds build an incomplete brief, and the shape that turns
+out to carry the whole design does not appear until the round that builds it.
TWO POLES, NOT THREE NEAR-COPIES (--poles). Card 01 §4b builds TWO variants that
are opposite extremes of one declared axis, and this measures whether they
@@ -79,19 +78,19 @@ SLOTS = [
# Slots that name parts and must therefore declare the chains they mean.
NEEDS_CHAINS = ('signature', 'two focals')
-# How far apart two poles must sit on the mass-layout ruler. Measured, not
+# How far apart two poles must sit on the mass-layout ruler. Calibrated, not
# guessed, and deliberately set as a FLOOR rather than a target:
#
-# 0.08 0.14 0.20 the three "variants" of a build's r1-r3 — one
-# design adjusted three times, which is the waste this stops
-# 0.15 r3 -> r4 of the same build
-# 0.38 two poses of ONE locked spec, authored here as opposites
+# 0.08 0.14 0.20 three "variants" that are one design adjusted three times,
+# which is the waste this stops
+# 0.15 one more nudge along that same design
+# 0.38 two poses of ONE locked spec, authored as opposites
# (tail hauled back vs tail whipped forward) and built green
-# 0.42 0.56 0.61 the same build's rounds either side of a concept restart
+# 0.42 0.56 0.61 rounds either side of a concept restart
#
# 0.25 clears every same-idea pair by a wide margin and passes every deliberate
-# restaging. It is a first cut off one creature's history plus one authored
-# pair; re-cut it when more runs exist, the way RESTART_IOU was.
+# restaging. It is a first cut off one history plus one authored pair; re-cut it
+# when more exists, the way RESTART_IOU was.
POLE_MIN = 0.25
# A pole can be far away on the layout ruler and still be junk — the authored
@@ -179,7 +178,43 @@ def check(brief_path, spec_path=None):
if name == 'identity':
m = re.search(r'reads as\s*[::]?\s*\**([^*|(]+)', val, re.I)
facts['noun'] = (m.group(1) if m else val).strip().strip('*` ')
+ # THE ACCEPTED LIST IS PART OF THE ORDER, and it is decided here or it
+ # is decided by whoever is being graded. A 48px silhouette is genuinely
+ # ambiguous, so a noun almost never comes back verbatim; something has
+ # to say how wide the family is. When that was left to Gate 1 it went
+ # the only way it could: the graded party decided its own substitution.
+ # One line, written before any geometry exists, and identity.py does
+ # the comparing instead of the arguing.
+ if not re.search(r'\(([^)]*)\)', val):
+ blocks.append('identity: no accepted list. Write the words a reader '
+ 'may say that still count as this creature, in brackets '
+ 'after the noun — e.g. "reads as: bison (accepted: '
+ 'buffalo, ox, bull, yak, wisent)". Gate 1 matches against '
+ 'exactly this list and nothing else, so decide the width '
+ 'now, while it is one line, and not at r3 with a shape to '
+ 'defend. Nothing stops you being generous; it has to be on '
+ 'the record.')
if name == 'signature':
+ # DOES THE SIGNATURE HAVE AN OUTLINE? Gate 1 reads a 48px SILHOUETTE, and a
+ # silhouette has exactly one dimension: shape. A feature made of colour, of
+ # COUNT (nine faces, one leg), of something soft (fur, a hanging snake), or
+ # of a FACE has no boundary in it at all — so betting the creature's identity
+ # on one means asking Gate 1 to measure a thing it cannot see, and paying
+ # reader rounds to be told so. A signature can be real, well built, and
+ # invisible in black.
+ #
+ # This does not forbid it. It forbids it being an ACCIDENT. Say "silhouette:
+ # yes" and Gate 1 is fair game; say "silhouette: no" and you have declared,
+ # before any geometry exists, that MID or HIGH carries this and Gate 1 will be
+ # judged on the body instead.
+ if not re.search(r'silhouette\s*[::]\s*(yes|no)', val, re.I):
+ blocks.append('signature: does not say whether it has an outline. End the '
+ 'cell with "silhouette: yes" or "silhouette: no". Gate 1 reads '
+ 'a 48px black shape — colour, counts, fur, hanging things and '
+ 'faces have no boundary in one. If the answer is no, that is '
+ 'allowed and often right, but it has to be a decision made '
+ 'here, before the rounds are paid for, and the body then has '
+ 'to carry the identity on its own.')
v = [w for w in VIEWS if w in val.lower()]
if not v:
blocks.append('signature: no view named. Gate 1 requires the '
diff --git a/harness/calibrate.py b/harness/calibrate.py
deleted file mode 100644
index 89ec3c7..0000000
--- a/harness/calibrate.py
+++ /dev/null
@@ -1,167 +0,0 @@
-#!/usr/bin/env python3
-"""Calibration: prove the rulers tell good from bad, per ruler.
-
-L1 — the ENGINE rulers (no browser needed)
-green = the bred example wolf (must build clean)
-red = legacy multi-fault wolf (must be blocked)
-red_5050 = violates ONLY the 50:50 proportion rule — must be blocked AND the
- block reason must actually be 'proportion' (a red sample that fails
- for other reasons proves nothing about this ruler).
-
-L2 — the COLOUR ruler (judge.mjs; skipped when no browser is installed)
-Same shape, both directions: the shipped example wolf must read as COLOURED
-(saturated area above the 10% floor), and a DESATURATED copy of that same file
-must be blocked BY saturation_area. A ruler is calibrated by proving it
-separates, not by pinning one sample inside a band — the band's ceiling is gone
-(saturation_area is advisory now, and the L1-L8 stack raises chroma by design).
-Added after a real miss: the 1.3.0 colour split moved the hue
-from COLOR_0 into baseColorFactor, the judge's albedo pass still forced the
-base to white, and saturation_area silently measured 0.0% on every creature —
-which would have failed every HIGH gate with "reads as a grey mass". Nothing
-caught it because calibration had never run the judge at all.
-"""
-import subprocess, os, sys, tempfile, json, struct
-H = os.path.dirname(os.path.abspath(__file__))
-R = os.path.join(H, '..')
-tmp = tempfile.mkdtemp(prefix='calib_')
-
-def build(spec, folder='calibration'):
- out = os.path.join(tmp, os.path.basename(spec) + '.glb')
- p = subprocess.run(['node', os.path.join(R, 'engine', 'cli.js'),
- os.path.join(R, folder, spec), out],
- capture_output=True, text=True)
- return p.returncode, p.stderr, out
-
-rc_g, _, green_glb = build('wolf_green.json')
-rc_r, _, _ = build('wolf_red.json')
-rc_5, err5, _ = build('red_5050.json')
-ok_g = rc_g == 0
-ok_r = rc_r != 0
-ok_5 = rc_5 != 0 and 'proportion' in err5
-
-print(f"green (known-good) -> {'PASS ✓' if ok_g else 'blocked ✗ (ruler too strict)'}")
-print(f"red (multi-fault) -> {'blocked ✓' if ok_r else 'PASSED ✗ (ruler too loose)'}")
-print(f"red_5050 (only 50:50) -> {'blocked by proportion ✓' if ok_5 else 'NOT blocked by proportion ✗'}")
-
-# ── L2: the colour ruler ─────────────────────────────────────────────────────
-# The upper bound is gone, and it had to go twice over. The gate restructure
-# made saturation_area advisory — there is no ceiling left to calibrate against
-# — and the L1-L8 shading stack then measured the shipped wolf at ~52%, because
-# L4 raises chroma on purpose in the upper region. Calibrating against a ceiling
-# that neither the gate nor the shading believes in would fail every fresh
-# install for a creature nothing is wrong with.
-#
-# What a ruler has to prove is that it SEPARATES, and that is what this tests:
-# the shipped wolf must read as coloured, and a desaturated copy of the same
-# file must read as grey. Both directions, one sample, no magic ceiling.
-SAT_CLAIM = {'name': 'colour-ruler', 'claims': [
- {'type': 'saturation_area', 'view': 'tq', 'min': 0.10,
- 'stage': 'HIGH', 'label': 'must not read as a grey mass (floor 10%)'}]}
-
-
-def desaturate(src, dst):
- """A grey twin of a built GLB: every colour replaced by its own luminance.
-
- Both halves of the albedo, and it has to be both. This used to grey only
- `baseColorFactor` on the theory that COLOR_0 carries a neutral shading
- ratio — which was true while one material meant one hue. The L1-L8 stack
- makes hue vary per VERTEX, so the ratio carries real chroma, and greying the
- factor alone left a creature that still measured 51% saturated. The test
- then reported the ruler was broken when what was broken was the twin.
-
- Geometry and animation are untouched, so the only thing that changed is
- still the exact quantity this ruler claims to measure."""
- d = open(src, 'rb').read()
- jl, = struct.unpack('<I', d[12:16])
- g = json.loads(d[20:20 + jl])
- rest = bytearray(d[20 + jl:])
- for m in g.get('materials', []):
- p = m.setdefault('pbrMetallicRoughness', {})
- b = p.get('baseColorFactor', [1, 1, 1, 1])
- lum = 0.2126 * b[0] + 0.7152 * b[1] + 0.0722 * b[2]
- p['baseColorFactor'] = [lum, lum, lum, b[3] if len(b) > 3 else 1]
-
- # COLOR_0, in the binary chunk. rest = 8-byte BIN chunk header + payload.
- acc_ids = {prim['attributes']['COLOR_0']
- for mesh in g.get('meshes', []) for prim in mesh.get('primitives', [])
- if 'COLOR_0' in prim.get('attributes', {})}
- views, base = g.get('bufferViews', []), 8
- for ai in acc_ids:
- a = g['accessors'][ai]
- if a.get('componentType') != 5126 or a.get('type') not in ('VEC3', 'VEC4'):
- continue # only float colours are rewritten
- n = 3 if a['type'] == 'VEC3' else 4
- bv = views[a['bufferView']]
- off = base + bv.get('byteOffset', 0) + a.get('byteOffset', 0)
- stride = bv.get('byteStride') or 4 * n
- for i in range(a['count']):
- o = off + i * stride
- r, gg, bb = struct.unpack_from('<fff', rest, o)
- L = 0.2126 * r + 0.7152 * gg + 0.0722 * bb
- struct.pack_into('<fff', rest, o, L, L, L)
- js = json.dumps(g).encode()
- js += b' ' * ((4 - len(js) % 4) % 4)
- out = (b"glTF" + struct.pack("<II", 2, 0) + struct.pack("<II", len(js), 0x4E4F534A) + js + bytes(rest))
- out = out[:8] + struct.pack('<I', len(out)) + out[12:]
- open(dst, 'wb').write(out)
-
-
-def judge(glb, spec_path):
- # --json because this is a machine reading the output: the judge prints a
- # short human summary by default now (a 2KB blob on stdout every run is paid
- # for again on every later turn), and calibration needs the numbers.
- p = subprocess.run(['node', os.path.join(H, 'judge.mjs'), glb,
- os.path.join(tmp, 'j'), 'calib', '--spec', spec_path,
- '--json'],
- capture_output=True, text=True)
- return p.returncode, (p.stdout or '') + (p.stderr or '')
-
-
-# The colour sample is example/wolf.json, NOT calibration/wolf_green.json:
-# wolf_green carries the pre-1.2.0 beige palette (it measures 0.2% saturated
-# and exists to exercise the ENGINE blocks, where palette is irrelevant),
-# while example/wolf.json is the reshipped creature the colour norms were
-# written against. Using the wrong one here would calibrate the ruler against
-# a sample that the shipped norms themselves reject.
-rc_cbuild, _, colour_glb = build('wolf.json', 'example')
-ok_c = True
-if rc_cbuild != 0:
- print('colour ruler -> skipped (example/wolf.json did not build)')
- ok_c = False
-else:
- spec_path = os.path.join(tmp, 'sat.json')
- json.dump(SAT_CLAIM, open(spec_path, 'w'))
- rc_cg, out_cg = judge(colour_glb, spec_path)
- # A judge that never MEASURED anything (no metrics line) did not fail this
- # ruler — it failed to run: no browser, no `npm install` yet, a sandbox with
- # no /dev/shm. Saying "the colour ruler is blind" there would send someone
- # hunting a bug in the ruler on a machine that simply has no browser.
- measured = any(l.startswith('{') and 'hi_sat_share' in l for l in out_cg.splitlines())
- if not measured:
- why = ('no browser installed' if 'cannot start a browser' in out_cg
- else "playwright is not installed (run setup.sh, or npm i)"
- if 'ERR_MODULE_NOT_FOUND' in out_cg or "Cannot find package" in out_cg
- else 'the judge could not run: ' + (out_cg.strip().splitlines() or [''])[-1][:120])
- print(f'colour ruler -> SKIPPED ({why})')
- else:
- grey = os.path.join(tmp, 'grey.glb')
- desaturate(colour_glb, grey)
- rc_cr, out_cr = judge(grey, spec_path)
- pass_green = rc_cg == 0
- block_grey = rc_cr != 0 and 'saturation' in out_cr.lower()
- share = ''
- for line in out_cg.splitlines():
- if line.startswith('{'):
- try:
- share = f" (measured {json.loads(line)['hi_sat_share']['tq'] * 100:.1f}%)"
- except Exception:
- pass
- print(f"colour green (saturated) -> {'PASS ✓' + share if pass_green else 'BLOCKED ✗ (the wolf read as a grey mass — the colour ruler is not seeing baseColorFactor x COLOR_0)' + share}")
- print(f"colour grey (desaturated) -> {'blocked by saturation ✓' if block_grey else 'NOT blocked ✗ (the colour ruler passes anything)'}")
- ok_c = pass_green and block_grey
-
-if ok_g and ok_r and ok_5 and ok_c:
- print('[calibrate] OK: the rulers separate good from bad.')
-else:
- print('[calibrate] FAILED — do not start work; report this.')
- sys.exit(1)
diff --git a/harness/deliver.py b/harness/deliver.py
index 770d800..99c4cf3 100644
--- a/harness/deliver.py
+++ b/harness/deliver.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Delivery packer (L1, zero handwork): stamped GLB + showroom viewer + hero shots + upload pack.
+"""Delivery packer (L1, zero handwork): stamped GLB + showroom viewer + hero + upload pack.
usage: python3 deliver.py <model.glb> <delivery_dir> <name>
[--title "Monster Name"] [--author "Signature"] [--gate gate.json]
@@ -7,7 +7,6 @@ usage: python3 deliver.py <model.glb> <delivery_dir> <name>
outputs in <delivery_dir>:
<name>.glb final stamped model (identity written INTO the file)
<name>_viewer.html offline showroom (open by double-click, no server)
- hero.png / hero.jpg 1024² hero shots (transparent / studio grey)
upload/ ready-to-drag backup pack for gobkit.com/community/upload
stamping (asset block):
@@ -18,7 +17,7 @@ stamping (asset block):
extras.gate --gate JSON, ONLY if it holds really-run check results
CC0 licence is NOT stamped here — publish.mjs adds it at upload, after consent.
"""
-import sys, os, json, base64, struct, shutil, subprocess, html, re
+import sys, os, json, base64, struct, shutil, subprocess, html, re, tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -172,13 +171,15 @@ def main():
.replace('__B64__', base64.b64encode(glb).decode()))
open(os.path.join(outdir, f'{name}_viewer.html'), 'w', encoding='utf-8').write(page)
- # hero shots (transparent + studio) — the hero NEVER shows the label card.
- # A hero failure (usually: no browser installed) must NOT kill the delivery:
- # the GLB and the viewer are the deliverable; heroes degrade to a warning.
- hero_ok = subprocess.run(['node', os.path.join(HERE, 'hero.mjs'), glb_path, outdir]).returncode == 0
- if not hero_ok:
- print('[deliver] WARN: hero shots failed — delivery continues without hero.png/jpg.')
- print('[deliver] fix: npx playwright install chromium (then rerun deliver.py)')
+ # hero.png — rasterised, not rendered. This was the last thing in the harness
+ # that launched a browser, and it did not need one: the whole shading stack is
+ # baked into the vertex colours at build time, so lighting it again in three.js
+ # was lighting a photograph. outline.py projects it with the same z-buffer every
+ # other measure uses, over a transparent background.
+ with tempfile.TemporaryDirectory() as scratch:
+ subprocess.run(['python3', os.path.join(HERE, 'outline.py'), glb_path, scratch,
+ '--hero', os.path.join(outdir, 'hero.png'),
+ '--views', 'hero'], check=False)
# backup upload pack (web drag path)
up = os.path.join(outdir, 'upload'); os.makedirs(up, exist_ok=True)
@@ -187,10 +188,9 @@ def main():
shutil.copy(os.path.join(outdir, 'hero.png'), os.path.join(up, 'hero.png'))
open(os.path.join(up, 'README.txt'), 'w').write(UPLOAD_README)
- heroes = 'hero.png/jpg' if hero_ok else 'NO heroes (see warning)'
- print(f'[deliver] done: {name}.glb · {name}_viewer.html · {heroes} · upload/'
+ print(f'[deliver] done: {name}.glb · {name}_viewer.html · hero.png · upload/'
f'\n[deliver] stamped: {disp}{" " + byline if byline else ""} · gate={"yes" if gate else "no"}'
- f'\n[deliver] checklist: glb, viewer, heroes, spec JSON, DEVLOG one-liner')
+ f'\n[deliver] checklist: glb, viewer, hero, spec JSON, DEVLOG one-liner')
if __name__ == '__main__':
main()
diff --git a/harness/gates.json b/harness/gates.json
index d2a7b42..2cca801 100644
--- a/harness/gates.json
+++ b/harness/gates.json
@@ -1,415 +1,514 @@
{
- "_": [
- "THE MAP. Every check in the system, in one place, tagged on five axes.",
- "",
- "enforce — block | advise",
- "when — allocate (decidable before the build) | verify (only after it exists)",
- "by — A | B | C (which judgment source runs it)",
- "kind — legality (a defect; only ever gets stricter) | style (a tunable threshold)",
- "dept — design | model | surface | rig | animation | process",
- "",
- "stage is a FIELD, not a hard-coded branch: LOW/MID/HIGH are levels of",
- "refinement, not a fixed department order. Any stage may run any department at",
- "its own resolution, and moving a check between stages is a data edit.",
- "",
- "The 18 checks tagged `allocate` are decidable before the build. `harness/fit.py`",
- "applies the arithmetic subset of them (root_containment, proportion, size) from",
- "the numbers the engine already prints, so a build round is spent on the",
- "creature rather than on legality.",
- "",
- "Rule of placement: put a check as early as the thing it measures can exist,",
- "at the coarsest resolution that can still show it."
- ],
- "stages": {
- "LOW": "coarse resolution — the whole creature, big masses",
- "MID": "part resolution — named parts and colour",
- "HIGH": "finishing resolution — rig, clips, shading"
- },
- "checks": [
- {
- "id": "mesh_integrity",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "verify",
- "plain": "geometry that is not geometry — degenerate or broken faces",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "root_containment",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "the root bone must sit inside the body",
- "by": "A",
- "kind": "legality",
- "dept": "rig"
- },
- {
- "id": "part_attachment",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "a part must actually be seated on what it claims to attach to",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "touch",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "parts that should touch must touch",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "balance",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "the creature must not fall over",
- "by": "A",
- "kind": "legality",
- "dept": "rig"
- },
- {
- "id": "size",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "built height must land within ±15% of the declared height",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "proportion",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "limb and body proportions inside sane bounds",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "limb_clearance",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "verify",
- "plain": "limbs must not pass through each other while animating",
- "by": "A",
- "kind": "legality",
- "dept": "animation"
- },
- {
- "id": "anim_integrity",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "verify",
- "plain": "the animation clips must be valid and must not tear the mesh",
- "by": "A",
- "kind": "legality",
- "dept": "animation"
- },
- {
- "id": "attack_reach",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "verify",
- "plain": "the attack must actually reach out, not mime",
- "by": "A",
- "kind": "style",
- "dept": "animation"
- },
- {
- "id": "gait_direction",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "verify",
- "plain": "a planted foot must sweep BACKWARD — a forward sweep is a walk cycle playing in reverse",
- "by": "A",
- "kind": "legality",
- "dept": "animation"
- },
- {
- "id": "root_drive",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "verify",
- "plain": "a lunge must be driven on the skeleton ROOT, not on one of its children",
- "by": "A",
- "kind": "legality",
- "dept": "animation"
- },
- {
- "id": "faceted",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "a body that is all flat facets when it should read as flesh",
- "by": "A",
- "kind": "style",
- "dept": "surface"
- },
- {
- "id": "soft_mass",
- "where": "engine",
- "stage": "any",
- "enforce": "block",
- "when": "allocate",
- "plain": "a volume that cannot break anywhere — the rounded sausage",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "mirror_distortion",
- "where": "engine",
- "stage": "any",
- "enforce": "advise",
- "when": "verify",
- "plain": "mirrored twins deformed differently",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "part_overlap",
- "where": "engine",
- "stage": "any",
- "enforce": "advise",
- "when": "verify",
- "plain": "how deeply parts interpenetrate",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "part_seat",
- "where": "engine",
- "stage": "any",
- "enforce": "advise",
- "when": "verify",
- "plain": "how well a part sits on its host surface",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "brief_slots",
- "where": "harness/brief.py",
- "stage": "LOW",
- "enforce": "block",
- "when": "allocate",
- "plain": "every brief slot a later stage READS must be filled in — presence only, never content",
- "by": "A",
- "kind": "legality",
- "dept": "process"
- },
- {
- "id": "brief_coverage",
- "where": "harness/brief.py",
- "stage": "LOW",
- "enforce": "block",
- "when": "allocate",
- "plain": "the chains the brief NAMED must exist in the r1 spec",
- "by": "A",
- "kind": "legality",
- "dept": "process"
- },
- {
- "id": "poles_apart",
- "where": "harness/brief.py + round.py",
- "stage": "LOW",
- "enforce": "block",
- "when": "verify",
- "plain": "the two versions in a round must be opposite ends of one axis, not one design built twice",
- "by": "A",
- "kind": "style",
- "dept": "process"
- },
- {
- "id": "pole_fill",
- "where": "harness/brief.py + round.py",
- "stage": "LOW",
- "enforce": "advise",
- "when": "verify",
- "plain": "a pole that fills too much of its own bounding box is a blob, not a pose",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "gate1_recognised",
- "where": "card 01",
- "stage": "LOW",
- "enforce": "block",
- "when": "verify",
- "plain": "a reader who knows nothing must rank the brief's creature high enough, in enough views (harness/identity.py)",
- "by": "B",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "gate2_punchier",
- "where": "card 01",
- "stage": "LOW",
- "enforce": "block",
- "when": "verify",
- "plain": "the exaggerated silhouette must beat the previous round's",
- "by": "B",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "thinnest_px48",
- "where": "harness/maskmetrics.py + roundcheck.py",
- "stage": "LOW",
- "enforce": "advise",
- "when": "allocate",
- "plain": "the width of the thinnest feature on the 48px thumbnail the reader sees",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "tri_budget",
- "where": "harness/claims.json",
- "stage": "LOW",
- "enforce": "advise",
- "when": "allocate",
- "plain": "triangle budget band",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "value_order",
- "where": "engine",
- "stage": "MID",
- "enforce": "advise",
- "when": "allocate",
- "plain": "every material sorted by OKLab lightness — the value plan, computed instead of eyeballed",
- "by": "A",
- "kind": "style",
- "dept": "surface"
- },
- {
- "id": "contrast_adjacent",
- "where": "engine",
- "stage": "MID",
- "enforce": "advise",
- "when": "allocate",
- "plain": "a part must separate in colour from the thing it SITS ON",
- "by": "A",
- "kind": "style",
- "dept": "surface"
- },
- {
- "id": "part_exists",
- "where": "harness/claims.json",
- "stage": "MID",
- "enforce": "block",
- "when": "verify",
- "plain": "the signature part the brief named must exist",
- "by": "A",
- "kind": "legality",
- "dept": "model"
- },
- {
- "id": "part_signature",
- "where": "harness/claims.json",
- "stage": "MID",
- "enforce": "advise",
- "when": "allocate",
- "plain": "how much of the side view the signature part holds",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "focal_contrast",
- "where": "harness/claims.json",
- "stage": "MID",
- "enforce": "advise",
- "when": "allocate",
- "plain": "the signature part should read clearly bigger than the head",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "share_hierarchy",
- "where": "harness/claims.json",
- "stage": "MID",
- "enforce": "advise",
- "when": "allocate",
- "plain": "main mass : signature : detail ≈ 6:3:1",
- "by": "A",
- "kind": "style",
- "dept": "model"
- },
- {
- "id": "rig_skinned",
- "where": "harness/claims.json",
- "stage": "HIGH",
- "enforce": "block",
- "when": "verify",
- "plain": "RIG — the mesh must actually be skinned to the skeleton",
- "by": "A",
- "kind": "legality",
- "dept": "rig"
- },
- {
- "id": "anim_named",
- "where": "harness/claims.json",
- "stage": "HIGH",
- "enforce": "block",
- "when": "verify",
- "plain": "CLIP — idle, move and attack must all be present",
- "by": "A",
- "kind": "legality",
- "dept": "animation"
- },
- {
- "id": "saturation_area",
- "where": "harness/claims.json",
- "stage": "HIGH",
- "enforce": "advise",
- "when": "allocate",
- "plain": "how much of the creature carries a strongly saturated colour",
- "by": "A",
- "kind": "style",
- "dept": "surface"
- },
- {
- "id": "output_contract",
- "where": "harness/glbcheck.mjs",
- "stage": "SHIP",
- "enforce": "block",
- "when": "verify",
- "plain": "the delivered file must satisfy the output contract",
- "by": "A",
- "kind": "legality",
- "dept": "process"
- }
- ]
+ "_": [
+ "THE MAP. Every check in the system, in one place, tagged on five axes.",
+ "",
+ "enforce — block | advise",
+ "when — allocate (decidable before the build) | verify (only after it exists)",
+ "by — A | B | C (which judgment source runs it)",
+ "kind — legality (a defect; only ever gets stricter) | style (a tunable threshold)",
+ "dept — design | model | surface | rig | animation | process",
+ "",
+ "stage is a FIELD, not a hard-coded branch: LOW/MID/HIGH are levels of",
+ "refinement, not a fixed department order. Any stage may run any department at",
+ "its own resolution, and moving a check between stages is a data edit.",
+ "",
+ "The 18 checks tagged `allocate` are decidable before the build. `harness/fit.py`",
+ "applies the arithmetic subset of them (root_containment, proportion, size) from",
+ "the numbers the engine already prints, so a build round is spent on the",
+ "creature rather than on legality.",
+ "",
+ "Rule of placement: put a check as early as the thing it measures can exist,",
+ "at the coarsest resolution that can still show it."
+ ],
+ "stages": {
+ "LOW": "coarse resolution — the whole creature, big masses",
+ "MID": "part resolution — named parts and colour",
+ "HIGH": "finishing resolution — rig, clips, shading"
+ },
+ "checks": [
+ {
+ "id": "mesh_integrity",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "geometry that is not geometry — degenerate or broken faces",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "root_containment",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "the root bone must sit inside the body",
+ "by": "A",
+ "kind": "legality",
+ "dept": "rig"
+ },
+ {
+ "id": "part_attachment",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "a part must actually be seated on what it claims to attach to",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "touch",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "parts that should touch must touch",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "balance",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "the creature must not fall over",
+ "by": "A",
+ "kind": "legality",
+ "dept": "rig"
+ },
+ {
+ "id": "size",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "built height must land within ±15% of the declared height",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "proportion",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "limb and body proportions inside sane bounds",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "limb_clearance",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "limbs must not pass through each other while animating",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "anim_integrity",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the animation clips must be valid and must not tear the mesh",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "attack_reach",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the attack must actually reach out, not mime",
+ "by": "A",
+ "kind": "style",
+ "dept": "animation"
+ },
+ {
+ "id": "gait_direction",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a planted foot must sweep BACKWARD — a forward sweep is a walk cycle playing in reverse",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "root_drive",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a lunge must be driven on the skeleton ROOT, not on one of its children",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "faceted",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "a body that is all flat facets when it should read as flesh",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "soft_mass",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "a volume that cannot break anywhere — the rounded sausage",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "mirror_distortion",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "mirrored twins deformed differently",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "part_overlap",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "how deeply parts interpenetrate",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "part_seat",
+ "where": "engine",
+ "stage": "any",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "how well a part sits on its host surface",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "brief_slots",
+ "where": "harness/brief.py",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "every brief slot a later stage READS must be filled in — presence only, never content",
+ "by": "A",
+ "kind": "legality",
+ "dept": "process"
+ },
+ {
+ "id": "brief_coverage",
+ "where": "harness/brief.py",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "allocate",
+ "plain": "the chains the brief NAMED must exist in the r1 spec",
+ "by": "A",
+ "kind": "legality",
+ "dept": "process"
+ },
+ {
+ "id": "poles_apart",
+ "where": "harness/brief.py + round.py",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the two versions in a round must be opposite ends of one axis, not one design built twice",
+ "by": "A",
+ "kind": "style",
+ "dept": "process"
+ },
+ {
+ "id": "pole_fill",
+ "where": "harness/brief.py + round.py",
+ "stage": "LOW",
+ "enforce": "advise",
+ "when": "verify",
+ "plain": "a pole that fills too much of its own bounding box is a blob, not a pose",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "gate1_recognised",
+ "where": "card 01",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a reader who knows nothing must rank the brief's creature high enough, in enough views (harness/identity.py)",
+ "by": "B",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "gate2_punchier",
+ "where": "card 01",
+ "stage": "LOW",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the exaggerated silhouette must beat the previous round's",
+ "by": "B",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "thinnest_px48",
+ "where": "harness/outline.py + roundcheck.py",
+ "stage": "LOW",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "the width of the thinnest feature on the 48px thumbnail the reader sees",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "tri_budget",
+ "where": "harness/claims.json",
+ "stage": "LOW",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "triangle budget band",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "value_order",
+ "where": "engine",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "every material sorted by OKLab lightness — the value plan, computed instead of eyeballed",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "contrast_adjacent",
+ "where": "engine",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "a part must separate in colour from the thing it SITS ON",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "part_exists",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the signature part the brief named must exist",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "part_signature",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "how much of the side view the signature part holds",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "focal_contrast",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "the signature part should read clearly bigger than the head",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "share_hierarchy",
+ "where": "harness/claims.json",
+ "stage": "MID",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "main mass : signature : detail ≈ 6:3:1",
+ "by": "A",
+ "kind": "style",
+ "dept": "model"
+ },
+ {
+ "id": "rig_skinned",
+ "where": "harness/claims.json",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "RIG — the mesh must actually be skinned to the skeleton",
+ "by": "A",
+ "kind": "legality",
+ "dept": "rig"
+ },
+ {
+ "id": "anim_named",
+ "where": "harness/claims.json",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "CLIP — idle, move and attack must all be present",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "saturation_area",
+ "where": "harness/claims.json",
+ "stage": "HIGH",
+ "enforce": "advise",
+ "when": "allocate",
+ "plain": "how much of the creature carries a strongly saturated colour",
+ "by": "A",
+ "kind": "style",
+ "dept": "surface"
+ },
+ {
+ "id": "output_contract",
+ "where": "harness/glbcheck.mjs",
+ "stage": "SHIP",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the delivered file must satisfy the output contract",
+ "by": "A",
+ "kind": "legality",
+ "dept": "process"
+ },
+ {
+ "id": "joint_range",
+ "where": "engine",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a joint turns further than it declared it could, or the body collides before the declared limit",
+ "by": "A",
+ "kind": "legality",
+ "dept": "skeleton"
+ },
+ {
+ "id": "part_names",
+ "where": "engine",
+ "stage": "MID",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "every part carries its own unique name; a material is a class and cannot identify one",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "body_islands",
+ "where": "engine",
+ "stage": "MID",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the creature is ONE connected object, not a body with pieces floating near it",
+ "by": "A",
+ "kind": "legality",
+ "dept": "model"
+ },
+ {
+ "id": "gait_footfall",
+ "where": "engine",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a step lands in FRONT of where it lifted, measured against the foot’s own liftoff",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "effector_leads",
+ "where": "engine",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "at the frame the attack reaches furthest, the declared effector is the frontmost mesh",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "attack_windup",
+ "where": "engine",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a strike winds back before it commits, or swings out to the side",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "clip_closes",
+ "where": "engine",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "a non-looping clip returns to its first frame instead of snapping back",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "ground_clip",
+ "where": "engine",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "nothing is driven below the plane the creature stands on",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ },
+ {
+ "id": "self_clip",
+ "where": "engine",
+ "stage": "HIGH",
+ "enforce": "block",
+ "when": "verify",
+ "plain": "the swept volume does not drive one part through another",
+ "by": "A",
+ "kind": "legality",
+ "dept": "animation"
+ }
+ ]
}
\ No newline at end of file
diff --git a/harness/hero.mjs b/harness/hero.mjs
deleted file mode 100644
index 36671cb..0000000
--- a/harness/hero.mjs
+++ /dev/null
@@ -1,97 +0,0 @@
-// anyCreature — hero shot renderer. Author: Ariescar.
-// Renders the delivery hero images from the final GLB:
-// hero.png 1024×1024, TRANSPARENT background, 45° three-quarter view,
-// idle mid-frame, ≥8% margin on every side (nothing cropped)
-// hero.jpg same shot over the studio grey backdrop
-// usage: node harness/hero.mjs <model.glb> <outdir>
-import { launchBrowser } from './pwlaunch.mjs';
-import fs from 'fs'; import path from 'path'; import http from 'http';
-import { fileURLToPath } from 'url';
-
-const here = path.dirname(fileURLToPath(import.meta.url));
-const [modelPath, outDir] = process.argv.slice(2);
-if (!modelPath || !outDir) { console.error('usage: node hero.mjs <model.glb> <outdir>'); process.exit(2); }
-fs.mkdirSync(outDir, { recursive: true });
-
-const html = `<!doctype html><body style="margin:0;background:transparent"><script src="/bundle.js"></script><script>
-const S=1024;
-const scene=new THREE.Scene(); scene.background=null;
-const cam=new THREE.PerspectiveCamera(32,1,0.01,500);
-const r=new THREE.WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true});
-r.setSize(S,S); r.outputColorSpace=THREE.SRGBColorSpace; document.body.appendChild(r.domElement);
-scene.add(new THREE.HemisphereLight(0xffffff,0x8a8578,1.5));
-const key=new THREE.DirectionalLight(0xffffff,2.4); key.position.set(3,4,2.5); scene.add(key);
-const fill=new THREE.DirectionalLight(0xcfd8ff,1.0); fill.position.set(-4,1.5,2); scene.add(fill);
-const rim=new THREE.DirectionalLight(0xaac4ff,1.6); rim.position.set(-2.5,2.5,-4); scene.add(rim);
-let cur=null,mixer=null,anims=[];
-window.load=(url)=>new Promise((res,rej)=>{ fetch(url).then(x=>x.arrayBuffer()).then(buf=>{
- new GLTFLoader().parse(buf,'',g=>{ cur=g.scene; scene.add(cur);
- cur.traverse(o=>{o.frustumCulled=false});
- anims=g.animations||[];
- const idle=anims.find(a=>a.name==='idle');
- if(idle){ mixer=new THREE.AnimationMixer(cur);
- mixer.clipAction(idle).play(); mixer.update(idle.duration*0.3); }
- res(1);},e=>rej(String(e))); }); });
-window.shoot=(dist,panX,panY)=>{ const box=new THREE.Box3().setFromObject(cur),
- c=box.getCenter(new THREE.Vector3()), sz=box.getSize(new THREE.Vector3());
- const rad=Math.max(sz.x,sz.y,sz.z);
- cam.position.copy(c).add(new THREE.Vector3(1,0.5,1).normalize().multiplyScalar(rad*dist));
- cam.lookAt(c);
- if(panX||panY){ // recentre: shift camera AND target along camera right/up
- const right=new THREE.Vector3().setFromMatrixColumn(cam.matrix,0);
- const up=new THREE.Vector3().setFromMatrixColumn(cam.matrix,1);
- const off=right.multiplyScalar(panX).add(up.multiplyScalar(panY));
- cam.position.add(off); c.add(off); cam.lookAt(c);
- }
- r.render(scene,cam);
- const g2=r.domElement.getContext('webgl2')||r.domElement.getContext('webgl');
- const px=new Uint8Array(S*S*4); g2.readPixels(0,0,S,S,g2.RGBA,g2.UNSIGNED_BYTE,px);
- let x0=S,x1=-1,y0=S,y1=-1;
- for(let y=0;y<S;y++)for(let x=0;x<S;x++) if(px[(y*S+x)*4+3]>8){
- if(x<x0)x0=x; if(x>x1)x1=x; if(y<y0)y0=y; if(y>y1)y1=y; }
- const camDist=rad*dist, half=camDist*Math.tan(cam.fov/2*Math.PI/180);
- return { png:r.domElement.toDataURL('image/png'),
- frac: x1<0?0:Math.max(x1-x0+1,y1-y0+1)/S,
- // gl reads y-up, matching NDC — world offset of the alpha centre
- ndcX:((x0+x1)/2-S/2)/(S/2)*half, ndcY:((y0+y1)/2-S/2)/(S/2)*half };
-};
-window.jpg=()=>{ const cv=document.createElement('canvas'); cv.width=cv.height=S;
- const ctx=cv.getContext('2d'); ctx.fillStyle='#4c4c51'; ctx.fillRect(0,0,S,S);
- ctx.drawImage(r.domElement,0,0); return cv.toDataURL('image/jpeg',0.92); };
-</script></body>`;
-
-const srv = http.createServer((q, res) => {
- if (q.url === '/') { res.writeHead(200, { 'content-type': 'text/html' }); return res.end(html); }
- if (q.url === '/bundle.js') { res.writeHead(200, { 'content-type': 'text/javascript' }); return res.end(fs.readFileSync(path.join(here, 'assets/three-bundle.js'))); }
- if (q.url === '/model.glb') { res.writeHead(200); return res.end(fs.readFileSync(modelPath)); }
- res.writeHead(404); res.end();
-});
-// loopback only, and let the OS pick the port — a fixed port on 0.0.0.0
-// exposed the page and the model to the whole network, and collided
-// whenever two runs overlapped.
-await new Promise(r => srv.listen(0, '127.0.0.1', r));
-const port = srv.address().port;
-// Shared launcher: PW_CHROMIUM_PATH pins a binary; a missing browser dies with
-// ONE actionable line ("run npx playwright install chromium"), never a stack.
-const br = await launchBrowser();
-const pg = await br.newPage({ viewport: { width: 1044, height: 1044 } });
-await pg.goto(`http://127.0.0.1:${port}/`);
-await pg.evaluate(() => window.load('/model.glb'));
-await pg.waitForTimeout(500);
-
-// iterative fit: rescale so the long side is 84%, then pan the camera so the
-// alpha bbox centres — both re-measured, so margins land ≥8% on every side
-let dist = 2.6, panX = 0, panY = 0;
-let shot = await pg.evaluate(a => window.shoot(a.d, a.x, a.y), { d: dist, x: 0, y: 0 });
-for (let i = 0; i < 3 && shot.frac > 0.01; i++) {
- dist = dist * shot.frac / 0.83;
- panX += shot.ndcX; panY += shot.ndcY;
- shot = await pg.evaluate(a => window.shoot(a.d, a.x, a.y), { d: dist, x: panX, y: panY });
- if (Math.abs(shot.frac - 0.83) < 0.02 && Math.hypot(shot.ndcX, shot.ndcY) < 0.01) break;
-}
-const jpg = await pg.evaluate(() => window.jpg());
-await br.close(); srv.close();
-
-fs.writeFileSync(path.join(outDir, 'hero.png'), Buffer.from(shot.png.split(',')[1], 'base64'));
-fs.writeFileSync(path.join(outDir, 'hero.jpg'), Buffer.from(jpg.split(',')[1], 'base64'));
-console.log(JSON.stringify({ ok: true, margin: +((1 - shot.frac) / 2 * 100).toFixed(1) + 0 }));
diff --git a/harness/identity.py b/harness/identity.py
index 9b6db7d..2d3273a 100644
--- a/harness/identity.py
+++ b/harness/identity.py
@@ -1,13 +1,23 @@
#!/usr/bin/env python3
"""The identity verdict, weighted and counted — not argued.
- python3 harness/identity.py --round 1 --noun scorpion \\
- --ranks front=none side=2 top=2 hero=1
+ python3 harness/identity.py --brief brief.md --round 1 \\
+ --guesses side="t-rex,dinosaur,velociraptor,dragon,lizard" \\
+ hero="four-legged animal,dog,goat,boar,bear"
-Each view's rank is WHERE the brief's noun appeared in that reader's ranked
-guesses (1 = its first guess), or `none` if it was not in the list at all.
-Synonyms count as the noun; that judgment is yours, and it is the only one this
-tool leaves you.
+You hand over THE WORDS THE READER SAID, in order. This tool decides whether any
+of them is the creature, by matching against the accepted list the brief wrote
+down before any money was spent.
+
+IT USED TO ASK YOU FOR THE RANK, and that was a hole straight through iron law 2.
+The rank depends on one judgment — "does "hound" count as "wolf"?" — and the only
+party available to make it was the party being graded. The accepted list was
+already in the brief and nothing compared against
+it. Now the machine compares.
+
+Widening the list is still allowed and still the designer's call. It just has to
+happen in the BRIEF, in writing, before the geometry exists — not here, after
+four rounds have been paid for and there is a shape to defend.
THE RULE. A rank of R passes if the noun reached R in at least R views:
@@ -29,16 +39,66 @@ information it buys does not:
WHY WEIGHTED AT ALL. The bar used to be one word, exactly right. A 48px
silhouette is a genuinely ambiguous object, and that bar measured the reader's
-confidence as much as the creature's clarity. A reader will answer "a generic
-bat/moth/gargoyle silhouette" with the ordered noun sitting INSIDE that
-sentence, and a one-word bar throws the whole read away. Recognition is not
-binary and this scores it as what it is.
+confidence as much as the creature's clarity — a read can name the target inside
+a hedged list ("a generic bat/moth/gargoyle silhouette": the ordered noun IS in
+that sentence), and a creature can take several rounds to move from "in the list"
+to "first". Recognition is not binary and this scores it as what it is.
"""
-import sys
+import sys, os, re
MAX_RANK = 4
+def norm(s):
+ return re.sub(r'[^a-z0-9 ]+', ' ', s.lower()).strip()
+
+
+def accepted_from_brief(path):
+ """The identity slot's noun plus every synonym it declared, normalised."""
+ txt = open(path, encoding='utf-8').read()
+ for line in txt.splitlines():
+ s = line.strip()
+ if not s.startswith('|'):
+ continue
+ cells = [c.strip() for c in s.strip('|').split('|')]
+ if len(cells) < 2 or norm(cells[0]) != 'identity':
+ continue
+ val = cells[1]
+ m = re.search(r'reads as\s*[::]?\s*\**([^*|(]+)', val, re.I)
+ noun = (m.group(1) if m else val).strip().strip('*` ')
+ syn = []
+ ms = re.search(r'\(([^)]*)\)', val)
+ if ms:
+ # longest alternative first, or "synonyms accepted:" leaves "accepted"
+ # behind as a word and the list quietly gains a member nobody wrote
+ body = re.sub(r'^\s*(?:synonyms?\s+accepted|accepted\s+synonyms?|synonyms?|accept(?:ed)?|also)\s*[::]?',
+ '', ms.group(1), flags=re.I)
+ syn = [x.strip() for x in re.split(r'[,、/]', body) if x.strip()]
+ out, seen = [], set()
+ for w in [noun] + syn:
+ n = norm(w)
+ if n and n not in seen:
+ seen.add(n)
+ out.append(n)
+ return noun.strip(), out
+ return None, []
+
+
+def rank_of(guess_list, accepted):
+ """1-based position of the first guess that IS one of the accepted words.
+
+ A guess is often a phrase — "crouching four-legged animal (dog/boar)" — so an
+ accepted word counts when it appears in the phrase as a whole word. Nothing
+ looser than that: "boarhound" is not "boar", and "bison" is not "buffalo"
+ unless the brief said so."""
+ for i, g in enumerate(guess_list, 1):
+ gn = ' ' + norm(g) + ' '
+ for a in accepted:
+ if ' ' + a + ' ' in gn:
+ return i, a
+ return None, None
+
+
def needed(rank, rnd):
"""Views required at this rank, for this round."""
return max(1, rank - (rnd - 1))
@@ -58,12 +118,98 @@ def verdict(ranks, rnd):
return best is not None, best, lines
+def collect(a, flag):
+ out = {}
+ if flag not in a:
+ return out
+ for x in a[a.index(flag) + 1:]:
+ if x.startswith('--'):
+ break
+ if '=' not in x:
+ print(f'BLOCK: "{x}" should look like side=... ')
+ sys.exit(2)
+ k, v = x.split('=', 1)
+ out[k] = v
+ return out
+
+
def main():
a = sys.argv[1:]
- if '--ranks' not in a:
+ if '--ranks' not in a and '--guesses' not in a:
print(__doc__)
return 2
rnd = int(a[a.index('--round') + 1]) if '--round' in a else 1
+ brief = a[a.index('--brief') + 1] if '--brief' in a else None
+ noun, accepted = (None, [])
+ if brief:
+ if not os.path.exists(brief):
+ print(f'BLOCK: no brief at {brief}')
+ return 2
+ noun, accepted = accepted_from_brief(brief)
+ if not accepted:
+ print('BLOCK: the brief has no identity slot, so there is nothing to match '
+ 'against. Fix the brief (harness/brief.py will tell you how).')
+ return 2
+
+ # ── the judgment is not yours ────────────────────────────────────────────
+ if '--guesses' in a:
+ if not brief:
+ print('BLOCK: --guesses needs --brief. The accepted words live in the brief, '
+ 'written down before the geometry existed; that is the whole point.')
+ return 2
+ said = collect(a, '--guesses')
+ if not said:
+ print('BLOCK: --guesses needs at least one view, e.g. side="a,b,c,d,e"')
+ return 2
+ ranks, matched, verbatim = {}, {}, {}
+ for v, blob in said.items():
+ gs = [g.strip() for g in blob.split(',') if g.strip()][:MAX_RANK + 1]
+ verbatim[v] = gs
+ k, hit = rank_of(gs, accepted)
+ ranks[v] = k
+ matched[v] = hit
+ passed, carried, lines = verdict(ranks, rnd)
+ print(f'identity r{rnd} — accepted: {", ".join(accepted)}')
+ for v, gs in verbatim.items():
+ k = ranks[v]
+ tail = (f'guess {k} = "{matched[v]}"' if k else 'nothing accepted')
+ print(f' {v:<7} {tail}')
+ print(f' reader said: {", ".join(gs)}')
+ print()
+ for r, got, need, ok, hit in lines:
+ print(f' {"✓" if ok else " "} rank {r}: {got} view(s) at {r} or better, needs {need}'
+ + (f' [{", ".join(hit)}]' if hit else ''))
+ print()
+ if passed:
+ print(f'PASS — carried at rank {carried}.')
+ print(f' record it: roundcheck.py <out> --record r{rnd} ID pass '
+ f'"{noun} (rank {carried})"')
+ return 0
+ near = sorted({g for gs in verbatim.values() for g in gs})[:8]
+ print(f'FAIL — none of the accepted words reached a rank in enough views.')
+ print()
+ print(' WHAT THE READERS ACTUALLY SAID: ' + ', '.join(near))
+ print(f' WHAT THE BRIEF WILL ACCEPT: {", ".join(accepted)}')
+ print()
+ print(' If one of those words genuinely IS the creature you ordered, that is a')
+ print(' decision about the ORDER, and it is made in the brief — add the word to')
+ print(' the identity slot and say why in the closing DEVLOG. You may not add it')
+ print(' here. This tool exists because the party being graded kept making that')
+ print(' call for itself, and the brief already had the answer written down.')
+ print()
+ print(' Otherwise the verdict IS the work order: repair the BIG masses, and')
+ print(' remember a repair must clear roundcheck\'s minimum change.')
+ print(f' record it: roundcheck.py <out> --record r{rnd} ID fail "<what they saw>"')
+ return 1
+
+ if brief:
+ print('BLOCK: --ranks says WHERE you decided the noun landed. With a brief on')
+ print(' disk there is no reason to decide it — pass the reader\'s words instead:')
+ print(' --guesses side="first,second,third,fourth,fifth"')
+ return 2
+ print('WARN: no --brief, so the synonym judgment is yours and nothing checked it.')
+ print(' This is the hole iron law 2 exists to close. Pass --brief.')
+ print()
noun = a[a.index('--noun') + 1] if '--noun' in a else 'the brief\'s noun'
ranks = {}
for x in a[a.index('--ranks') + 1:]:
diff --git a/harness/judge.mjs b/harness/judge.mjs
index 8a3c61c..97b18b8 100644
--- a/harness/judge.mjs
+++ b/harness/judge.mjs
@@ -1,16 +1,32 @@
-// Generic creature mechanical judge (engine layer, L1) — renders (silhouette / ID / beauty) + pure numeric measurement, zero LLM.
+// Generic creature mechanical judge (engine layer, L1) — pure numeric measurement, zero LLM, zero browser.
// The engine contains no creature-specific vocabulary; all identity claims live in the spec JSON.
//
-// usage: node judge.mjs <model.gltf|glb> <outDir> <name> [--spec creature.json] [--stage LOW|MID|HIGH]
+// usage: node judge.mjs <model.glb> <outDir> <name> [--spec creature.json] [--stage LOW|MID|HIGH]
// no --spec = measure only, emit metrics JSON (for humans or for scoring)
// with --spec = check every claim in the spec; any failure exits 1 (symptom-first messages)
//
+// WHERE THE NUMBERS COME FROM. This used to launch a headless Chromium, load the
+// model into three.js, render five views, and read the pixels back. Every number
+// it wanted was already in the file: part shares are a z-buffer, the baked colour
+// IS the albedo, and the clip list and skin count are in the glTF header. So the
+// measuring moved to harness/outline.py — the tool that already owns every other
+// geometry measure in this harness — and this file does what is left: check the
+// claims. One measure, one definition, in one place.
+//
+// Two conventions changed with the move, both toward the tool that survived:
+// · `side` is the LONG profile (outline.py picks the axis), not a fixed +X.
+// Judge's old fixed camera showed a spread-winged creature edge-on and
+// called it a side view.
+// · `tq` and `reartq` are gone; the three-quarter view is `hero`. The two
+// cameras sit within a few degrees of each other and the shares agree to
+// ~1 percentage point, so a band calibrated on `tq` still means what it meant.
+//
// spec JSON = { "name": "...", "claims": [ {type, ...params, "label": "plain-language description"} ] }
// Supported claim types (add a new one in CHECKS; keep the engine creature-agnostic):
// part_exists {part} — a material/part with this name must exist
// part_visible {part, view?, min_share} — minimum share of body pixels the part holds in a given view
// part_signature {part, view?, min_share, or_min_span} — signature part: share OR span ratio must clear its bar
-// style_dark {view?, max_median_lum} — dark styling: body median luminance must not exceed the cap
+// style_dark {view?, max_median_lum} — dark styling: the creature's OWN colour must not be brighter
// style_light {view?, min_median_lum} — light styling: must not fall below the floor
// rig_skinned {} — must be skinned (bones move nothing without skin weights)
// anim_named {names:[...]} — these named animations must be present
@@ -18,10 +34,9 @@
// share_hierarchy {primary:[..],secondary:[..],tertiary:[..],view?,tolerance?} — primary/secondary/tertiary shares ≈6:3:1
// focal_contrast {a, b, view?, min_ratio?} — the two focal parts' shares must differ by ≥N× (default 2)
// saturation_area {view?, min?, max?} — share of the view carrying a highly saturated colour
-// (HSV S ≥ 0.50 on the UNLIT baked colour). Default band
-// 0.10–0.34. Says how much, never where.
-import { launchBrowser } from './pwlaunch.mjs';
-import path from 'path'; import fs from 'fs'; import http from 'http';
+// (HSV S ≥ 0.50 on the UNLIT baked colour). Default floor 0.10.
+import path from 'path'; import fs from 'fs';
+import { spawnSync } from 'child_process';
import { fileURLToPath } from 'url';
const args = process.argv.slice(2);
@@ -35,267 +50,106 @@ const root = path.dirname(fileURLToPath(import.meta.url));
const abs = path.resolve(src);
fs.mkdirSync(outDir, { recursive: true });
-const PAGE = `<!doctype html><html><head><meta charset="utf-8">
-<script type="importmap">{"imports":{"three":"/node_modules/three/build/three.module.js",
-"three/addons/":"/node_modules/three/examples/jsm/"}}</script></head><body style="margin:0">
-<script type="module">
-import * as THREE from 'three';
-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-const W=512,H=512;
-const r=new THREE.WebGLRenderer({antialias:false,preserveDrawingBuffer:true});
-r.setSize(W,H); r.setPixelRatio(1); document.body.appendChild(r.domElement);
-const scene=new THREE.Scene(); scene.background=new THREE.Color(0xffffff);
-const gltf=await new GLTFLoader().loadAsync('/__model');
-const model=gltf.scene; scene.add(model);
-const anims=(gltf.animations||[]).map(a=>a.name);
-let skins=0; model.traverse(o=>{ if(o.isSkinnedMesh) skins++; });
-
-const groups=new Map();
-model.traverse(o=>{ if(!o.isMesh) return;
- const mats=Array.isArray(o.material)?o.material:[o.material];
- const n=(mats[0]?.name||'unnamed').toLowerCase();
- if(!groups.has(n)) groups.set(n,[]);
- groups.get(n).push(o); });
-const names=[...groups.keys()];
-const idMat=new Map();
-names.forEach((n,i)=>{ const id=i+1;
- idMat.set(n,new THREE.MeshBasicMaterial({color:new THREE.Color((id&3)/3,((id>>2)&3)/3,((id>>4)&3)/3),side:THREE.DoubleSide})); });
-const idRGB=names.map((n,i)=>{const id=i+1;return [Math.round((id&3)/3*255),Math.round(((id>>2)&3)/3*255),Math.round(((id>>4)&3)/3*255)];});
-
-// per-group world bbox (skinned parts use undeformed vertices ≈ rest pose)
-const gb={};
-for(const [n,ms] of groups){ const b=new THREE.Box3();
- for(const m of ms){ m.updateWorldMatrix(true,false);
- const pos=m.geometry.attributes.position; const idx=m.geometry.index; const v=new THREE.Vector3();
- // ★ Measure only the vertices the index actually references — glTF primitives often share one POSITION accessor;
- // scanning attributes directly measures every group's bbox as the whole body.
- if(idx){ const seen=new Set();
- for(let i=0;i<idx.count;i++){ const k=idx.getX(i); if(seen.has(k))continue; seen.add(k);
- v.fromBufferAttribute(pos,k).applyMatrix4(m.matrixWorld); b.expandByPoint(v); } }
- else for(let i=0;i<pos.count;i++){ v.fromBufferAttribute(pos,i).applyMatrix4(m.matrixWorld); b.expandByPoint(v); } }
- gb[n]={min:b.min.toArray(),max:b.max.toArray()}; }
-const box=new THREE.Box3().setFromObject(model);
-const size=box.getSize(new THREE.Vector3()), c=box.getCenter(new THREE.Vector3());
-const rad=Math.max(size.x,size.y,size.z);
-const cam=new THREE.PerspectiveCamera(35,1,rad*0.01,rad*100);
-const VIEWS={front:[0,0.12,1],side:[1,0.12,0],tq:[0.8,0.3,0.8],reartq:[-0.8,0.3,-0.8],top:[0.02,1,0.02]};
-
-const cv=document.createElement('canvas'); cv.width=W; cv.height=H;
-const cx=cv.getContext('2d',{willReadFrequently:true});
-function grab(){ cx.drawImage(r.domElement,0,0); return cx.getImageData(0,0,W,H).data; }
-function shoot(analyze){ const out={},px={};
- for(const [vn,v] of Object.entries(VIEWS)){
- const d=new THREE.Vector3(...v).normalize().multiplyScalar(rad*2.5);
- cam.position.copy(c).add(d); cam.lookAt(c); cam.updateProjectionMatrix();
- r.render(scene,cam); out[vn]=r.domElement.toDataURL('image/png');
- if(analyze) px[vn]=analyze(grab()); }
- return {out,px}; }
-
-// 1) beauty (original materials + lights, sRGB = what the display actually shows) → measure luminance
-r.outputColorSpace=THREE.SRGBColorSpace;
-const hemi=new THREE.HemisphereLight(0xffffff,0x888877,0.9);
-const key=new THREE.DirectionalLight(0xffffff,1.6); key.position.set(2,3,2);
-const fill=new THREE.DirectionalLight(0xffffff,0.5); fill.position.set(-2,1,-1);
-scene.add(hemi,key,fill);
-const beauty=shoot(d=>{ const lums=[];
- for(let i=0;i<d.length;i+=4){ const R=d[i],G=d[i+1],B=d[i+2];
- if(R>248&&G>248&&B>248) continue; // white background
- lums.push(0.2126*R+0.7152*G+0.0722*B); }
- lums.sort((a,b)=>a-b);
- return {bodyPx:lums.length, medianLum:lums.length?lums[Math.floor(lums.length/2)]:255}; });
-scene.remove(hemi,key,fill);
-r.outputColorSpace=THREE.LinearSRGBColorSpace;
-
-// 1b) albedo — the baked vertex colours with NO lighting, so saturation can be
-// Verified:dependently of brightness. gradient, grain and AO are all uniform
-// multiplies, so they move a pixel's value but never its HSV saturation; lights
-// do move it (a white key washes colour out, a blue rim invents it). Measuring
-// here is the only way "how much of this creature is highly saturated" comes out
-// as an honest area rather than a lighting artefact.
-// ALBEDO = baseColorFactor × COLOR_0, ALWAYS BOTH. This line used to force the
-// base colour to white whenever COLOR_0 existed, which was correct only while
-// the entire palette lived in the vertices. Since 1.3.0 the engine splits the
-// baked colour — the HUE into baseColorFactor, the shading RATIO (≤1) into
-// COLOR_0 — so measuring COLOR_0 alone measures a deliberately near-grey
-// multiplier: the wolf's saturated area read 26.0% before the split and 0.0%
-// after it, and every creature would have been told it "reads as a grey mass".
-// A ruler that does not follow the format it measures is worse than no ruler.
-r.outputColorSpace=THREE.SRGBColorSpace;
-const albedoMat=new Map();
-model.traverse(o=>{ if(o.isMesh){ albedoMat.set(o,o.material);
- o.material=new THREE.MeshBasicMaterial({vertexColors:!!o.geometry.attributes.color,
- color:o.material.color?o.material.color.clone():0xffffff,
- map:o.material.map||null,
- side:THREE.DoubleSide}); }});
-const albedo=shoot(d=>{ let body=0,hi=0;
- for(let i=0;i<d.length;i+=4){ const R=d[i],G=d[i+1],B=d[i+2];
- if(R>248&&G>248&&B>248) continue; // white background
- body++;
- const mx=Math.max(R,G,B), mn=Math.min(R,G,B);
- if(mx>0 && (mx-mn)/mx>=0.50) hi++; } // HSV saturation ≥ 0.50
- return {bodyPx:body, hiSatPx:hi, hiSatShare: body? hi/body : 0}; });
-model.traverse(o=>{ if(o.isMesh) o.material=albedoMat.get(o); });
-r.outputColorSpace=THREE.LinearSRGBColorSpace;
-
-// 2) silhouette
-const orig=new Map();
-model.traverse(o=>{ if(o.isMesh){ orig.set(o,o.material);
- o.material=new THREE.MeshBasicMaterial({color:0x000000,side:THREE.DoubleSide}); }});
-const sil=shoot(null);
-// 3) ID buffer → per-material pixel counts per view
-for(const [n,ms] of groups) for(const m of ms) m.material=idMat.get(n);
-const ids=shoot(d=>{ const cnt={}; let body=0;
- for(let i=0;i<d.length;i+=4){ const R=d[i],G=d[i+1],B=d[i+2];
- if(R>248&&G>248&&B>248) continue; body++;
- for(let k=0;k<idRGB.length;k++){ const t=idRGB[k];
- if(Math.abs(R-t[0])<28&&Math.abs(G-t[1])<28&&Math.abs(B-t[2])<28){ cnt[names[k]]=(cnt[names[k]]||0)+1; break; } } }
- return {bodyPx:body,counts:cnt}; });
-model.traverse(o=>{ if(o.isMesh) o.material=orig.get(o); });
+// ── measure: one call to the one measuring tool ──
+const outline = path.join(root, 'outline.py');
+const run = spawnSync('python3', [outline, abs, outDir], { encoding: 'utf8' });
+if (run.status !== 0) {
+ console.error('[judge] outline.py failed — it owns every measurement here, so nothing can be judged:\n'
+ + (run.stderr || run.stdout || '').trim());
+ process.exit(2);
+}
+const M = JSON.parse(fs.readFileSync(path.join(outDir, 'metrics.json'), 'utf8'));
-let tris=0; model.traverse(o=>{ if(o.isMesh){ const g=o.geometry.index;
- tris += g? g.count/3 : o.geometry.attributes.position.count/3; }});
-window.__r={ beauty:beauty.out, sil:sil.out, ids:ids.out, albedo:albedo.out,
- lum:beauty.px, idpx:ids.px, sat:albedo.px,
- names, gbox:gb, wbox:{min:box.min.toArray(),max:box.max.toArray()},
- stats:{triangles:Math.round(tris), skinnedMeshes:skins, animations:anims} };
-window.__done=true;
-</script></body></html>`;
+// `tq`/`reartq` were judge's own camera names; the surviving three-quarter view is `hero`.
+const VIEW = v => (v === 'tq' || v === 'reartq') ? 'hero' : v;
+const view = v => M.views[VIEW(v)] || {};
+const names = M.materials || [];
+const parts = M.parts || {};
+const share = (v, mat) => (view(v).share || {})[mat] ?? 0;
+const stats = M.stats || { triangles: M.triangles, skinnedMeshes: 0, animations: [] };
-// Static file serving is CONFINED. `path.join(base, urlPath)` is not safe:
-// a raw request line carrying "/../../../../etc/passwd" (fetch normalises it,
-// a socket does not) escaped every base and served the file, and the listener
-// was bound to 0.0.0.0 — arbitrary file read from anywhere on the network,
-// /proc/self/environ included. Resolve, then require containment, then allow
-// only the extensions the page actually imports.
-const OK_EXT = new Set(['.js', '.mjs', '.map', '.json', '.wasm']);
-const BASES = [path.dirname(abs), root, path.join(root, '..')].map(b => path.resolve(b));
-function safeResolve(urlPath) {
- for (const base of BASES) {
- const f = path.resolve(base, '.' + urlPath);
- if (f !== base && !f.startsWith(base + path.sep)) continue; // escaped the base
- if (!OK_EXT.has(path.extname(f))) continue;
- try { if (fs.statSync(f).isFile()) return f; } catch {}
- }
- return null;
-}
-const server = http.createServer((req,res)=>{
- let p; try { p = decodeURIComponent(req.url.split('?')[0]); } catch { res.writeHead(400); return res.end(); }
- if(p==='/'){res.writeHead(200,{'Content-Type':'text/html'});return res.end(PAGE);}
- if(p==='/__model'){res.writeHead(200,{'Content-Type':'model/gltf+json'});return res.end(fs.readFileSync(abs));}
- const f = safeResolve(p);
- if(f){res.writeHead(200,{'Content-Type':'text/javascript'});return res.end(fs.readFileSync(f));}
- res.writeHead(404);res.end();
-});
-// loopback only — nothing here is meant to be reachable from the network
-await new Promise(r=>server.listen(0,'127.0.0.1',r));
-const port=server.address().port;
-// Let Playwright find its own browser. A hardcoded container path breaks every
-// clone on macOS/Windows; PW_CHROMIUM_PATH stays available for pinned setups.
-// Shared launcher (harness/pwlaunch.mjs): PW_CHROMIUM_PATH pins a binary,
-// PW_NO_SANDBOX=1 opts out of the OS sandbox only where it cannot run, and a
-// missing browser dies with ONE actionable line instead of a stack.
-const browser=await launchBrowser();
-const page=await browser.newPage({viewport:{width:560,height:560}});
-const errs=[]; page.on('pageerror',e=>errs.push(String(e)));
-await page.goto(`http://127.0.0.1:${port}/`);
-try{ await page.waitForFunction('window.__done===true',{timeout:120000}); }
-catch(e){ console.error('FAILED\n'+errs.join('\n')); await browser.close(); server.close(); process.exit(2); }
-const R=await page.evaluate('window.__r');
-for(const [vn,d] of Object.entries(R.sil)) fs.writeFileSync(path.join(outDir,`${name}_sil_${vn}.png`),Buffer.from(d.split(',')[1],'base64'));
-for(const [vn,d] of Object.entries(R.ids)) fs.writeFileSync(path.join(outDir,`${name}_id_${vn}.png`),Buffer.from(d.split(',')[1],'base64'));
-for(const [vn,d] of Object.entries(R.beauty)) fs.writeFileSync(path.join(outDir,`${name}_beauty_${vn}.png`),Buffer.from(d.split(',')[1],'base64'));
+const m = { name, stats, names,
+ lum: Object.fromEntries(Object.entries(M.views).map(([vn, d]) => [vn, d.median_lum])),
+ hi_sat_share: Object.fromEntries(Object.entries(M.views).map(([vn, d]) => [vn, d.saturated_area])),
+ parts, whole: M.whole };
+const metricsPath = path.join(outDir, `${name}_metrics.json`);
+fs.writeFileSync(metricsPath, JSON.stringify(m, null, 1));
-// ── Export measurements (every part measured; no name filtering) ──
-const sz=b=>[b.max[0]-b.min[0],b.max[1]-b.min[1],b.max[2]-b.min[2]];
-const diagXZ=s=>Math.hypot(s[0],s[2]);
-const whole=sz(R.wbox);
-const share=(vn,mat)=>{ const p=R.idpx[vn]; return p.bodyPx? (p.counts[mat]||0)/p.bodyPx : 0; };
-const parts={};
-for(const n of R.names){ const b=R.gbox[n]; if(!b) continue; const s=sz(b);
- parts[n]={ size:s,
- share:Object.fromEntries(Object.keys(R.idpx).map(vn=>[vn,+share(vn,n).toFixed(5)])),
- span_ratio:+(diagXZ(s)/(diagXZ(whole)||1)).toFixed(4),
- height_ratio:+(s[1]/(whole[1]||1)).toFixed(4) }; }
-const m={ name, stats:R.stats, names:R.names,
- lum:Object.fromEntries(Object.entries(R.lum).map(([vn,x])=>[vn,+x.medianLum.toFixed(1)])),
- hi_sat_share:Object.fromEntries(Object.entries(R.sat).map(([vn,x])=>[vn,+x.hiSatShare.toFixed(4)])),
- parts, whole:{size:whole} };
-const metricsPath=path.join(outDir,`${name}_metrics.json`);
-fs.writeFileSync(metricsPath,JSON.stringify(m,null,1));
-// A SUMMARY, not the blob. This used to print the entire metrics object — every
-// part, every view, every share, about 2KB — straight to stdout, on every run.
-// Tool output lands in the conversation permanently and the conversation is
-// re-read on every turn afterwards, so a 2KB dump at round 3 is still being
-// paid for at round 30. The file has always held the full record; print where it
-// is and the handful of numbers a decision actually turns on. `--json` restores
-// the old behaviour for anything parsing this.
-if(process.argv.includes('--json')) console.log(JSON.stringify(m));
+// A SUMMARY, not the blob. Tool output lands in the conversation permanently and
+// the conversation is re-read on every turn afterwards, so a 2KB dump at round 3
+// is still being paid for at round 30. `--json` restores the full object.
+if (process.argv.includes('--json')) console.log(JSON.stringify(m));
else {
- const v='tq';
- console.log(`[judge] ${name}: ${m.stats.triangles} tris · ${m.names.length} materials · `
- +`clips ${m.stats.animations.join('/')||'none'} · skinned ${m.stats.skinnedMeshes}`);
+ const v = 'hero';
+ console.log(`[judge] ${name}: ${stats.triangles} tris · ${names.length} materials · `
+ + `clips ${stats.animations.join('/') || 'none'} · skinned ${stats.skinnedMeshes}`);
console.log(` ${v} view: luminance ${m.lum[v]} · saturated area `
- +`${(m.hi_sat_share[v]*100).toFixed(1)}%`);
- const top=Object.entries(m.parts).sort((a,b)=>(b[1].share[v]||0)-(a[1].share[v]||0)).slice(0,3);
- console.log(' biggest in view: '+top.map(([n,p])=>`${n} ${(p.share[v]*100).toFixed(0)}%`).join(' · '));
+ + `${((m.hi_sat_share[v] || 0) * 100).toFixed(1)}%`);
+ const top = Object.entries(parts).sort((a, b) => (share(v, b[0])) - (share(v, a[0]))).slice(0, 3);
+ console.log(' biggest in view: ' + top.map(([n]) => `${n} ${(share(v, n) * 100).toFixed(0)}%`).join(' · '));
console.log(` full numbers: ${metricsPath}`);
}
// ── Spec mode: check every claim, symptom first ──
-if(specFile){
- const S=JSON.parse(fs.readFileSync(specFile,'utf8'));
- const bad=[];
- const pct=x=>(x*100).toFixed(2)+'%';
- const CHECKS={
- part_exists(c){ if(!R.names.includes(c.part))
+if (specFile) {
+ const S = JSON.parse(fs.readFileSync(specFile, 'utf8'));
+ const bad = [];
+ const pct = x => (x * 100).toFixed(2) + '%';
+ const CHECKS = {
+ part_exists(c){ if(!names.includes(c.part))
bad.push(`Part "${c.part}" not measurable: no material by that name in the model (part missing, or naming convention not followed)`); },
- part_visible(c){ if(!R.names.includes(c.part)) return CHECKS.part_exists(c);
+ part_visible(c){ if(!names.includes(c.part)) return CHECKS.part_exists(c);
const v=c.view||'side'; const s=share(v,c.part);
if(s<c.min_share) bad.push(`Part "${c.part}" is nearly invisible in the ${v} view (share ${pct(s)} < ${pct(c.min_share)}) — occluded, too small, or in the wrong place`); },
- part_signature(c){ if(!R.names.includes(c.part)) return CHECKS.part_exists(c);
- const v=c.view||'side'; const s=share(v,c.part); const sp=parts[c.part].span_ratio;
+ part_signature(c){ if(!names.includes(c.part)) return CHECKS.part_exists(c);
+ const v=c.view||'side'; const s=share(v,c.part); const sp=(parts[c.part]||{}).span_ratio ?? 0;
if(!(s>=c.min_share||sp>=c.or_min_span))
- bad.push(`Signature part \"${c.part}\" is not exaggerated enough: ${v}-view share ${pct(s)} (need ≥${pct(c.min_share)}) and span ratio ${sp} (need ≥${c.or_min_span}) — right now it is just another part; it cannot carry this creature's identity`); },
- style_dark(c){ const v=c.view||'side'; const L=R.lum[v].medianLum;
- if(L>c.max_median_lum) bad.push(`Declared dark but does not read dark on screen: ${v}-view body median luminance ${L.toFixed(0)}/255 (need ≤${c.max_median_lum}) — push the material colour values darker`); },
- style_light(c){ const v=c.view||'side'; const L=R.lum[v].medianLum;
- if(L<c.min_median_lum) bad.push(`Declared light but reads too dark on screen: ${v}-view body median luminance ${L.toFixed(0)}/255 (need ≥${c.min_median_lum})`); },
- // High-saturation AREA, Verified: the unlit baked colour (HSV S ≥ 0.50).
+ bad.push(`Signature part "${c.part}" is not exaggerated enough: ${v}-view share ${pct(s)} (need ≥${pct(c.min_share)}) and span ratio ${sp} (need ≥${c.or_min_span}) — right now it is just another part; it cannot carry this creature's identity`); },
+ // Dark/light now read the creature's OWN colour, not a studio render of it.
+ // The old number was the median luminance of a lit beauty pass, which made
+ // the verdict a property of a lighting rig nobody ships. This is the unlit
+ // baked albedo: what the designer actually chose. The two correlate at
+ // r≈0.96 but are not the same scale — the albedo runs darker — so a
+ // threshold carried over from a pre-1.3.2 spec needs re-picking once.
+ style_dark(c){ const v=c.view||'side'; const L=view(v).median_lum;
+ if(L>c.max_median_lum) bad.push(`Declared dark but its own colour is not dark: ${v}-view median albedo luminance ${L.toFixed(0)}/255 (need ≤${c.max_median_lum}) — push the material colour values darker`); },
+ style_light(c){ const v=c.view||'side'; const L=view(v).median_lum;
+ if(L<c.min_median_lum) bad.push(`Declared light but its own colour is too dark: ${v}-view median albedo luminance ${L.toFixed(0)}/255 (need ≥${c.min_median_lum})`); },
+ // High-saturation AREA, computed from the unlit baked colour (HSV S ≥ 0.50).
// Too little and the creature is a grey lump; too much and saturation stops
// being a spotlight and the whole thing screams. Do NOT name which surfaces
// carry it — where the colour goes is the designer's call, only how much.
saturation_area(c){ const v=c.view||'tq';
- const s=R.sat[v]; if(!s) return;
+ const s=view(v).saturated_area; if(s==null) return;
// There is NO default ceiling. Dropping `max` from claims.json did not
// remove the old 0.34 one, because it lived here as a fallback — so the
// ceiling went on refusing creatures after it had supposedly been
- // retired, and it took the shading stack (which raises chroma on purpose)
- // to expose that. A ceiling only applies now if a spec asks for one by
- // name. The floor keeps its default: "reads as a grey lump" is a real
- // failure and nobody has to opt into catching it.
- const pct=s.hiSatShare*100, lo=(c.min??0.10)*100;
- if(pct<lo) bad.push(`Too little colour: only ${pct.toFixed(1)}% of the ${v} view is highly saturated (need ≥${lo.toFixed(0)}%) — the creature reads as a grey mass. Raise the saturation of a mass that deserves the attention, do not tint everything.`);
- if(c.max!=null && pct>c.max*100) bad.push(`Too much colour: ${pct.toFixed(1)}% of the ${v} view is highly saturated (need ≤${(c.max*100).toFixed(0)}%) — saturation stops reading as a spotlight when it covers this much. Desaturate the supporting masses and keep the loud colour on the signature.`); },
- rig_skinned(){ if(R.stats.skinnedMeshes<1)
+ // retired. A ceiling only applies now if a spec asks for one by name. The
+ // floor keeps its default: "reads as a grey lump" is a real failure and
+ // nobody has to opt into catching it.
+ const p=s*100, lo=(c.min??0.10)*100;
+ if(p<lo) bad.push(`Too little colour: only ${p.toFixed(1)}% of the ${VIEW(v)} view is highly saturated (need ≥${lo.toFixed(0)}%) — the creature reads as a grey mass. Raise the saturation of a mass that deserves the attention, do not tint everything.`);
+ if(c.max!=null && p>c.max*100) bad.push(`Too much colour: ${p.toFixed(1)}% of the ${VIEW(v)} view is highly saturated (need ≤${(c.max*100).toFixed(0)}%) — saturation stops reading as a spotlight when it covers this much. Desaturate the supporting masses and keep the loud colour on the signature.`); },
+ rig_skinned(){ if(stats.skinnedMeshes<1)
bad.push('Model is not skinned: the rig is not bound to the mesh, so animating the bones moves nothing'); },
- anim_named(c){ for(const a of c.names) if(!R.stats.animations.includes(a))
- bad.push(`Missing named animation ${a} (present: ${R.stats.animations.join(',')||'none'})`); },
- tri_budget(c){ const t=R.stats.triangles;
+ anim_named(c){ for(const a of c.names) if(!stats.animations.includes(a))
+ bad.push(`Missing named animation ${a} (present: ${stats.animations.join(',')||'none'})`); },
+ tri_budget(c){ const t=stats.triangles;
if(t<c.min||t>c.max) bad.push(`Triangle count ${t} is outside the budget band ${c.min}–${c.max}`); },
// 6:3:1 hierarchy: the primary / secondary / tertiary part groups must hold roughly
// 6:3:1 of the frame. An even spread reads as no hierarchy at all — a silhouette needs
// one mass that clearly leads, one that supports, and detail that stays detail.
share_hierarchy(c){ const v=c.view||'side';
- const grp=g=>g.reduce((a,p)=>a+(R.names.includes(p)?share(v,p):0),0);
- const [P,S,T]=[grp(c.primary||[]),grp(c.secondary||[]),grp(c.tertiary||[])];
- const tot=P+S+T; if(!tot){ bad.push(`631 hierarchy not measurable: primary/secondary/tertiary parts are all 0 in the ${v} view`); return; }
- const tol=c.tolerance??0.15, want=[0.6,0.3,0.1], got=[P/tot,S/tot,T/tot];
+ const grp=g=>g.reduce((a,p)=>a+(names.includes(p)?share(v,p):0),0);
+ const [P,Sc,T]=[grp(c.primary||[]),grp(c.secondary||[]),grp(c.tertiary||[])];
+ const tot=P+Sc+T; if(!tot){ bad.push(`631 hierarchy not measurable: primary/secondary/tertiary parts are all 0 in the ${v} view`); return; }
+ const tol=c.tolerance??0.15, want=[0.6,0.3,0.1], got=[P/tot,Sc/tot,T/tot];
const off=got.map((g,i)=>Math.abs(g-want[i]));
if(Math.max(...off)>tol) bad.push(`Hierarchy ratio off: primary/secondary/tertiary = ${got.map(x=>(x*100).toFixed(0)).join(':')} (target 60:30:10, tolerance ±${tol*100}%) — no dominance; the frame is split evenly`); },
// No equal-weight focal points: two focal parts of the same size make the eye ping-pong
// between them and neither one wins. The declared pair's shares must differ by ≥ratio×.
focal_contrast(c){ const v=c.view||'side';
- for(const p of [c.a,c.b]) if(!R.names.includes(p)) return CHECKS.part_exists({part:p});
+ for(const p of [c.a,c.b]) if(!names.includes(p)) return CHECKS.part_exists({part:p});
const A=share(v,c.a), B=share(v,c.b); const hi=Math.max(A,B), lo=Math.min(A,B);
const ratio=c.min_ratio??2;
if(lo>0 && hi/lo<ratio) bad.push(`Two focal points of equal weight compete: "${c.a}" ${(A*100).toFixed(1)}% vs "${c.b}" ${(B*100).toFixed(1)}% (need ≥${ratio}× apart) — the eye ping-pongs between them; open up the dominance gap`); },
@@ -313,7 +167,6 @@ if(specFile){
if(!fn){ bad.push(`Spec contains a claim type the engine does not recognise: "${c.type}"`); continue; }
const before=bad.length; fn(c);
if(bad.length===before) continue;
- // a check may push more than one line; the tag applies to all of them
const mine=bad.splice(before);
if(c.label) mine[mine.length-1] += ` [${c.label}]`;
if((c.enforce||'block')==='advise') advice.push(...mine); else bad.push(...mine);
@@ -326,9 +179,8 @@ if(specFile){
console.log(`BLOCKING — against spec "${S.name||path.basename(specFile)}", the following fail and must be fixed:`);
for(const b of bad) console.log(' ✗ '+b);
console.log('='.repeat(68)+`\n${bad.length} blocking item(s). exit 1 — cannot ship.`);
- await browser.close(); server.close(); process.exit(1); }
+ process.exit(1); }
console.log(advice.length
- ? `[judge] Spec \"${S.name||''}\" — nothing blocking. ${advice.length} advisory item(s) above; read them, then decide.`
- : `[judge] Spec \"${S.name||''}\" — all claims pass.`);
+ ? `[judge] Spec "${S.name||''}" — nothing blocking. ${advice.length} advisory item(s) above; read them, then decide.`
+ : `[judge] Spec "${S.name||''}" — all claims pass.`);
}
-await browser.close(); server.close();
diff --git a/harness/maskmetrics.py b/harness/maskmetrics.py
deleted file mode 100644
index fb744d7..0000000
--- a/harness/maskmetrics.py
+++ /dev/null
@@ -1,155 +0,0 @@
-#!/usr/bin/env python3
-"""Silhouette measurement report (MEASURES ONLY — judgment belongs to the LLM).
-usage: python3 maskmetrics.py <outdir> <img1.png> [img2.png ...]
-Per image: crops to content, writes <stem>_thumb24.png / _thumb48.png and
-metrics to <outdir>/metrics.json. Also writes sheet.png (all views side by side).
-Descriptors: W_over_H, fill, thirds_cols, thirds_rows, compactness
-(perimeter^2/4πA: 1=disc, higher=spikier/branchier), neg_pockets (enclosed
-whitespace count+sizes), protrusions (direction & sharpness of major limbs/spikes),
-com (centre of mass position in bbox, 0..1)."""
-import sys, os, json
-import numpy as np
-from PIL import Image
-
-outdir = sys.argv[1]; os.makedirs(outdir, exist_ok=True)
-report = {}
-sheets = []
-for p in sys.argv[2:]:
- name = os.path.splitext(os.path.basename(p))[0]
- im = np.array(Image.open(p).convert('L'))
- m = im < 128
- if not m.any():
- report[name] = None; continue
- ys, xs = np.where(m)
- m = m[ys.min():ys.max()+1, xs.min():xs.max()+1]
- H, W = m.shape; area = int(m.sum())
- # perimeter: count edge transitions
- per = int((m[:, 1:] != m[:, :-1]).sum() + (m[1:] != m[:-1]).sum()
- + m[0].sum() + m[-1].sum() + m[:, 0].sum() + m[:, -1].sum())
- from scipy import ndimage
- inv = ~m
- lab, n = ndimage.label(inv)
- border = set(lab[0]) | set(lab[-1]) | set(lab[:, 0]) | set(lab[:, -1])
- pockets = sorted([int((lab == i).sum()) for i in range(1, n+1)
- if i not in border and (lab == i).sum() > area*0.002], reverse=True)
- # protrusions: erode heavily -> core; subtract -> appendages; report each blob's
- # direction from core centroid and aspect (long/thin = sharp)
- core = ndimage.binary_erosion(m, iterations=max(2, int(min(H, W)*0.06)))
- app = m & ~ndimage.binary_dilation(core, iterations=max(2, int(min(H, W)*0.06)))
- la, na = ndimage.label(app)
- cy, cx = ndimage.center_of_mass(m)
- protr = []
- for i in range(1, na+1):
- blob = la == i
- s = int(blob.sum())
- if s < area*0.01: continue
- by, bx = ndimage.center_of_mass(blob)
- import math
- ang = math.degrees(math.atan2(-(by-cy), bx-cx)) # 0=right, 90=up
- ys2, xs2 = np.where(blob)
- ext = max(ys2.max()-ys2.min(), xs2.max()-xs2.min()) + 1
- thin = ext*ext / max(s, 1) # higher = longer/thinner = sharper read
- # WIDTH AT READING SIZE. The blind read happens on a 48px thumbnail, so
- # an arm two pixels across is not a thin arm, it is an invisible one —
- # and no amount of repositioning will make the reader see it. This is
- # arithmetic available on the FIRST build; a run that discovers it at
- # round 22 has spent sixteen rounds moving something nobody could see.
- # Twice the max inscribed radius = the blob's own thickness, scaled to 48.
- dt = ndimage.distance_transform_edt(blob)
- px48 = round(2 * float(dt.max()) * 48.0 / max(H, W), 1)
- protr.append({'dir_deg': round(ang), 'size': round(s/area, 3),
- 'thinness': round(thin, 1), 'px48': px48})
- protr.sort(key=lambda x: -x['size'])
- # the thinnest thing that is still trying to be a feature
- thinnest = min([p['px48'] for p in protr], default=None)
- # ── dullness flags (MEASURES ONLY, the reader/LLM judges) ──
- # 1:1-frame fill: the silhouette in a square frame must carry real volume
- Ssq = max(H, W)
- sq_fill = area / (Ssq * Ssq)
- # mirror symmetry: IoU with own horizontal flip (front views of bilateral
- # creatures are EXEMPT from judgment on this — measure everywhere, judge per view)
- mf = np.fliplr(m)
- mirror_sym = float((m & mf).sum() / max((m | mf).sum(), 1))
- # straight-line runs: longest constant-slope run on any boundary, as a
- # fraction of that boundary's length (stiff legs / plank wings light this up)
- def longest_const_slope(arr):
- best, cur, slope = 0, 1, None
- for i in range(1, len(arr)):
- if arr[i] < 0 or arr[i-1] < 0:
- cur, slope = 1, None; continue
- s = arr[i] - arr[i-1]
- if slope is not None and s == slope: cur += 1
- else: slope, cur = s, 2
- best = max(best, cur)
- return best
- topB = [-1]*W; botB = [-1]*W; lefB = [-1]*H; rigB = [-1]*H
- for x in range(W):
- col = np.where(m[:, x])[0]
- if len(col): topB[x] = int(col.min()); botB[x] = int(col.max())
- for y in range(H):
- row = np.where(m[y])[0]
- if len(row): lefB[y] = int(row.min()); rigB[y] = int(row.max())
- straight = max(longest_const_slope(topB)/max(W,1), longest_const_slope(botB)/max(W,1),
- longest_const_slope(lefB)/max(H,1), longest_const_slope(rigB)/max(H,1))
- report[name] = {
- 'W_over_H': round(W/H, 2), 'fill': round(area/(H*W), 3),
- 'thirds_cols': [round(float(m[:, i*W//3:(i+1)*W//3].sum()/area), 2) for i in range(3)],
- 'thirds_rows': [round(float(m[i*H//3:(i+1)*H//3].sum()/area), 2) for i in range(3)],
- 'compactness': round(per*per/(4*np.pi*area), 1),
- 'neg_pockets': pockets[:6],
- 'com': [round(float(cx)/W, 2), round(float(cy)/H, 2)],
- 'protrusions': protr[:8],
- 'thinnest_px48': thinnest,
- 'sq_fill': round(sq_fill, 3),
- 'mirror_sym': round(mirror_sym, 2),
- 'straight_max': round(float(straight), 2),
- }
- sil = Image.fromarray((~m*255).astype(np.uint8))
- # ASPECT IS THE BINDING QUESTION. Card 01 §4 asks every reader "wider or
- # taller?" and voids the whole read when the answer disagrees with
- # W_over_H in metrics.json. A hard resize((px,px)) makes every thumbnail
- # square, so the honest answer is always "square-ish" and no read can ever
- # bind — measured cost: 21 of 52 reads in the 1.3.0 three-creature batch
- # were re-runs, ~40% of the blind-read budget, for a trap that was
- # mechanically unanswerable. Fit inside the box instead and pad with the
- # background, so the shape keeps the proportion the reader is asked about.
- for px in (24, 48):
- w = max(1, round(px * W / H)) if W < H else px
- h = px if W < H else max(1, round(px * H / W))
- small = sil.resize((w, h), Image.LANCZOS)
- box = Image.new('L', (px, px), 255)
- box.paste(small, ((px - w) // 2, (px - h) // 2))
- box.resize((240, 240), Image.NEAREST)\
- .save(os.path.join(outdir, f'{name}_thumb{px}.png'))
- sheets.append((name, sil))
-if sheets:
- hmax = 300
- tiles = [(n, s.resize((int(s.width*hmax/s.height), hmax))) for n, s in sheets]
- Wt = sum(t.width for _, t in tiles) + 10*(len(tiles)+1)
- sheet = Image.new('L', (Wt, hmax+40), 255)
- x = 10
- from PIL import ImageDraw
- d = ImageDraw.Draw(sheet)
- for n, t in tiles:
- sheet.paste(t, (x, 30)); d.text((x, 8), n, fill=0); x += t.width + 10
- sheet.save(os.path.join(outdir, 'sheet.png'))
-# MERGE, never overwrite. silmetrics writes its own report to this same file in
-# this same round directory — including iou_vs_prev, the regression guard — and
-# card 01 runs silmetrics first, then this. A plain write therefore deleted the
-# guard a second after it was computed, in every round of every run since it was
-# added. Our keys are image names, silmetrics' are flat scalars, so they merge
-# without collision; a stale key from a re-run is harmless and worth keeping.
-mpath = os.path.join(outdir, 'metrics.json')
-merged = {}
-if os.path.exists(mpath):
- try:
- with open(mpath, encoding='utf-8') as f:
- prev = json.load(f)
- if isinstance(prev, dict):
- merged = prev
- except Exception:
- pass
-merged.update(report)
-with open(mpath, 'w') as f:
- json.dump(merged, f, indent=1)
-print(json.dumps(report))
diff --git a/harness/outline.py b/harness/outline.py
index f72af35..20b0039 100644
--- a/harness/outline.py
+++ b/harness/outline.py
@@ -10,7 +10,7 @@ back. That is a lot of machinery to answer a question the vertices already
contain: this is low-poly, a few thousand triangles, and the outline of a solid
under a known camera is arithmetic.
-So this projects the triangles and fills them. Same camera as silmetrics.mjs
+So this projects the triangles and fills them. Same camera the renderer used
(perspective, 30 degrees, distance = longest dimension x 2.4, 640x640, same view
directions and up vectors), same mask convention, same metrics. The point is not
only speed — it is that the numbers stop being *estimates read off a picture*
@@ -61,11 +61,19 @@ def accessor(g, b, base, idx):
return out
-def triangles_by_material(path):
- """Triangles grouped by material name, so a share can be attributed."""
+def triangles_by_material(path, want_colour=False):
+ """Triangles grouped by material name, so a share can be attributed.
+
+ With want_colour, also returns the baked albedo: per-vertex COLOR_0 and the
+ per-material baseColorFactor. ALBEDO = baseColorFactor x COLOR_0, ALWAYS
+ BOTH — the engine splits the baked colour, the hue into baseColorFactor and
+ the shading ratio (<=1) into COLOR_0, so reading either alone measures half
+ a colour. Both are linear; the sRGB encode happens at measurement time."""
g, b, base = read_glb(path)
mats = [m.get('name', f'mat{i}') for i, m in enumerate(g.get('materials', []))]
- V, F, MID = [], [], []
+ basecol = np.array([(m.get('pbrMetallicRoughness', {}) or {}).get('baseColorFactor', [1, 1, 1, 1])[:3]
+ for m in g.get('materials', [])], dtype=np.float64) if g.get('materials') else np.zeros((0, 3))
+ V, F, MID, C, N = [], [], [], [], []
for mesh in g.get('meshes', []):
for pr in mesh.get('primitives', []):
at = pr.get('attributes', {})
@@ -74,6 +82,19 @@ def triangles_by_material(path):
off = sum(len(x) for x in V)
pos = accessor(g, b, base, at['POSITION'])
V.append(pos)
+ if want_colour:
+ N.append(accessor(g, b, base, at['NORMAL']).astype(np.float64)
+ if 'NORMAL' in at else np.zeros((len(pos), 3)))
+ if 'COLOR_0' in at:
+ c = accessor(g, b, base, at['COLOR_0'])[:, :3].astype(np.float64)
+ a0 = g['accessors'][at['COLOR_0']]
+ if a0['componentType'] == 5123: # normalised ushort
+ c = c / 65535.0
+ elif a0['componentType'] == 5121: # normalised ubyte
+ c = c / 255.0
+ else:
+ c = np.ones((len(pos), 3))
+ C.append(c)
if 'indices' in pr:
f = accessor(g, b, base, pr['indices']).reshape(-1, 3) + off
else:
@@ -84,9 +105,55 @@ def triangles_by_material(path):
MID.append(np.full(len(f), mi, dtype=np.int64))
if not V:
raise ValueError('no geometry in the file')
+ if want_colour:
+ return np.vstack(V), np.vstack(F), np.concatenate(MID), mats, np.vstack(C), basecol, np.vstack(N)
return np.vstack(V), np.vstack(F), np.concatenate(MID), mats
+def structure(path):
+ """What the file IS, from the JSON chunk: clips, skins, triangle count.
+
+ This used to come from loading the model into three.js inside a headless
+ browser and traversing the scene graph. It is written in the glTF header."""
+ g, b, base = read_glb(path)
+ tris = 0
+ skinned = 0
+ for mesh in g.get('meshes', []):
+ for pr in mesh.get('primitives', []):
+ at = pr.get('attributes', {})
+ if 'indices' in pr:
+ tris += g['accessors'][pr['indices']]['count'] // 3
+ elif 'POSITION' in at:
+ tris += g['accessors'][at['POSITION']]['count'] // 3
+ for nd in g.get('nodes', []):
+ if 'skin' in nd and 'mesh' in nd:
+ skinned += 1
+ return {'triangles': int(tris), 'skinnedMeshes': int(skinned),
+ 'animations': [a.get('name', f'anim{i}') for i, a in enumerate(g.get('animations', []))]}
+
+
+def part_boxes(V, F, MID, mats):
+ """Per-material bounding box, from the vertices its own triangles reference.
+
+ Measure only the referenced vertices: glTF primitives routinely share one
+ POSITION accessor, so scanning the attribute gives every material the bbox
+ of the whole body."""
+ whole = [float(V[:, k].max() - V[:, k].min()) for k in range(3)]
+ dxz = lambda s: math.hypot(s[0], s[2])
+ out = {}
+ for mi in np.unique(MID):
+ if mi < 0:
+ continue
+ idx = np.unique(F[MID == mi].reshape(-1))
+ sub_v = V[idx]
+ s = [float(sub_v[:, k].max() - sub_v[:, k].min()) for k in range(3)]
+ name = mats[mi] if 0 <= mi < len(mats) else f'mat{mi}'
+ out[name] = {'size': [round(x, 4) for x in s],
+ 'span_ratio': round(dxz(s) / (dxz(whole) or 1), 4),
+ 'height_ratio': round(s[1] / (whole[1] or 1), 4)}
+ return out, [round(x, 4) for x in whole]
+
+
def triangles(path):
"""Every triangle in the file, as world-space vertex positions.
@@ -114,7 +181,7 @@ def triangles(path):
return np.vstack(V), np.vstack(F)
-# ── camera, matching silmetrics.mjs exactly ────────────────────────────────
+# ── camera, matching the renderer this replaced, exactly ───────────────────
def view_dir(view, size):
long_axis = 'x' if size[0] > size[2] else 'z'
if view == 'top':
@@ -179,7 +246,7 @@ def measures(mask):
'px': [w, h],
}
# WHERE THE MASS SITS, in thirds of its own bounding box. Same definition as
- # maskmetrics.py, on the cropped mask, so the two agree to the decimal.
+ # the measure pass it replaced, on the cropped mask, to the decimal.
#
# This is the number that tells two DESIGNS apart, which iou_vs_prev does
# not: iou counts overlapping pixels, so a proportion change moves it a lot
@@ -194,8 +261,14 @@ def measures(mask):
try:
from scipy import ndimage
except ImportError:
+ # Silence here is dangerous: thinnest_px48 gates legibility and protrusions
+ # gates boldness, so a missing dependency would drop two BLOCKING measures and
+ # every build would pass them by not having them. Say so, once, loudly.
+ print('WARN: scipy missing — protrusions, thinnest_px48, convexity and mirror_sym '
+ 'are NOT computed, so the legibility and boldness gates have nothing to read. '
+ 'Run setup.sh.', file=sys.stderr)
return m
- # Protrusions and thinnest_px48 use maskmetrics.py's definitions EXACTLY —
+ # Protrusions and thinnest_px48 keep the original definitions EXACTLY —
# erode hard to get a core, subtract to get appendages, and measure each
# appendage's own thickness as twice its maximum inscribed radius, scaled to
# the 48px thumbnail the reader actually sees. Two implementations of the
@@ -243,7 +316,7 @@ def project(V, view):
return px, py, z
-def material_shares(V, F, MID, mats, view):
+def material_shares(V, F, MID, mats, view, C=None, basecol=None, N=None):
"""Which material OWNS each silhouette pixel, with a depth test.
The share of the frame a part holds is a geometry question, and it was being
@@ -255,6 +328,11 @@ def material_shares(V, F, MID, mats, view):
px, py, z = project(V, view)
depth = np.full((RES, RES), np.inf)
owner = np.full((RES, RES), -1, dtype=np.int64)
+ # The colour buffer rides along in the SAME rasteriser. A second pass would be
+ # a second definition of "which pixel does this triangle win", and two of those
+ # have to be kept in agreement by hand.
+ colour = np.zeros((RES, RES, 3)) if C is not None else None
+ normal = np.zeros((RES, RES, 3)) if N is not None else None
for tri, mi in zip(F, MID):
a, b, c = tri
xs = np.array([px[a], px[b], px[c]])
@@ -274,12 +352,35 @@ def material_shares(V, F, MID, mats, view):
inside = (l0 >= 0) & (l1 >= 0) & (l2 >= 0)
if not inside.any():
continue
- zz = l0 * z[a] + l1 * z[b] + l2 * z[c]
+ # PERSPECTIVE-CORRECT interpolation, not affine. l0/l1/l2 are barycentric
+ # in SCREEN space, and screen space is already divided by depth — so
+ # blending a per-vertex quantity with them directly is only right for an
+ # orthographic camera. This one is a pinhole at 30 degrees. The textbook
+ # correction: blend 1/z, take the reciprocal for depth, and divide any
+ # other attribute back out by it.
+ #
+ # It matters most exactly where it is hardest to see: a long triangle
+ # running away from the camera, where the affine version puts the middle
+ # of the surface at the wrong depth and can lose a depth test against
+ # something genuinely behind it.
+ iz = l0 / z[a] + l1 / z[b] + l2 / z[c]
+ iz = np.where(np.abs(iz) < 1e-12, 1e-12, iz)
+ zz = 1.0 / iz
sub = depth[y0:y1 + 1, x0:x1 + 1]
win = inside & (zz < sub)
if win.any():
sub[win] = zz[win]
owner[y0:y1 + 1, x0:x1 + 1][win] = mi
+ if colour is not None:
+ cc = ((l0 / z[a])[..., None] * C[a] + (l1 / z[b])[..., None] * C[b]
+ + (l2 / z[c])[..., None] * C[c]) * zz[..., None]
+ if basecol is not None and 0 <= mi < len(basecol):
+ cc = cc * basecol[mi]
+ colour[y0:y1 + 1, x0:x1 + 1][win] = cc[win]
+ if normal is not None:
+ nn = ((l0 / z[a])[..., None] * N[a] + (l1 / z[b])[..., None] * N[b]
+ + (l2 / z[c])[..., None] * N[c]) * zz[..., None]
+ normal[y0:y1 + 1, x0:x1 + 1][win] = nn[win]
total = int((owner >= 0).sum())
out = {}
if total:
@@ -288,9 +389,102 @@ def material_shares(V, F, MID, mats, view):
continue
name = mats[mi] if 0 <= mi < len(mats) else f'mat{mi}'
out[name] = round(float((owner == mi).sum()) / total, 5)
+ if colour is not None and normal is not None:
+ return out, owner >= 0, colour, normal
+ if colour is not None:
+ return out, owner >= 0, colour
return out, owner >= 0
+def hero_png(model, out_png, view='hero', res=1024):
+ """The delivery's hero shot, rasterised — no browser, no renderer, no lights.
+
+ This is the last thing Chromium was kept alive for, and it did not need to be
+ alive for it: the whole L1-L8 shading stack is BAKED into COLOR_0 at build
+ time, so the flat albedo already carries the gradient, the seams, the ambient
+ occlusion and the rim. Rendering it again with three-point studio lighting was
+ lighting a photograph. The z-buffer here decides occlusion exactly as it does
+ for every other measure, and the background is alpha rather than a grey card.
+
+ Resolution is raised for this one pass because a thumbnail is looked at by a
+ person, not measured; every gate keeps reading the 640 grid."""
+ global RES
+ keep = RES
+ try:
+ RES = res
+ V, F, MID, mats, C, basecol, Nv = triangles_by_material(model, want_colour=True)
+ _, mask, colour, nrm = material_shares(V, F, MID, mats, view, C, basecol, Nv)
+ # The same rig the retired renderer used: a warm-over-cool hemisphere, a
+ # key, a cool fill and a cool rim. Lambert only — these are matte low-poly
+ # surfaces with the specular story already painted into the vertex colour,
+ # so a full PBR evaluation would be re-deriving what is baked.
+ ln = np.linalg.norm(nrm, axis=2, keepdims=True)
+ n = np.divide(nrm, np.where(ln > 1e-9, ln, 1.0))
+ up = n[:, :, 1:2]
+ sky, ground = np.array([1.0, 1.0, 1.0]), np.array([0.541, 0.522, 0.471])
+ irr = 1.5 * (sky * (0.5 + 0.5 * up) + ground * (0.5 - 0.5 * up))
+ for pos, col, amp in ((( 3.0, 4.0, 2.5), (1.0, 1.0, 1.0), 2.4),
+ ((-4.0, 1.5, 2.0), (0.812, 0.847, 1.0), 1.0),
+ ((-2.5, 2.5, -4.0), (0.667, 0.769, 1.0), 1.6)):
+ d = np.array(pos, dtype=np.float64); d /= np.linalg.norm(d)
+ lam = np.clip((n * d).sum(axis=2, keepdims=True), 0.0, 1.0)
+ irr = irr + np.array(col) * amp * lam
+ # Exposure. The Lambert sum above is not the renderer's shader, so it lands
+ # near but not on the old brightness: checked against the renderer this
+ # replaces, across the reference shelf, the ratio ran 0.91 median. 1.1 puts
+ # it back. This constant touches the PICTURE only — no gate reads the hero.
+ lin = np.clip(colour * irr * (1.1 / np.pi), 0.0, 1.0)
+ srgb = np.where(lin <= 0.0031308, lin * 12.92, 1.055 * np.power(lin, 1 / 2.4) - 0.055)
+ rgb = np.clip(srgb * 255.0, 0, 255).astype(np.uint8)
+ rgba = np.dstack([rgb, np.where(mask, 255, 0).astype(np.uint8)])
+ # Frame it. The measuring camera fits the whole bounding sphere so that a
+ # silhouette is comparable between rounds; a thumbnail has no such duty and
+ # a creature sitting in a third of the frame reads as a small creature.
+ # Crop to what is actually drawn, keep it square, leave a margin.
+ ys, xs = np.nonzero(mask)
+ if len(xs):
+ cx, cy = (xs.min() + xs.max()) / 2, (ys.min() + ys.max()) / 2
+ half = max(xs.max() - xs.min(), ys.max() - ys.min()) / 2 * 1.12
+ x0, y0 = int(round(cx - half)), int(round(cy - half))
+ side = int(round(half * 2))
+ pad = np.zeros((side, side, 4), dtype=np.uint8)
+ sx0, sy0 = max(0, x0), max(0, y0)
+ sx1, sy1 = min(res, x0 + side), min(res, y0 + side)
+ pad[sy0 - y0:sy1 - y0, sx0 - x0:sx1 - x0] = rgba[sy0:sy1, sx0:sx1]
+ rgba = pad
+ Image.fromarray(rgba, 'RGBA').resize((res, res), Image.LANCZOS).save(out_png)
+ finally:
+ RES = keep
+ return out_png
+
+
+def colour_measures(body, colour):
+ """The two colour numbers, off the UNLIT baked albedo.
+
+ They used to come from a headless browser: render the model, read the pixels,
+ count. Rendering was never what made them true — the baked colour IS the
+ answer, and the z-buffer above already decides which surface each pixel sees.
+
+ median_lum how bright the creature's own colour is, 0-255 sRGB
+ saturated_area the share of it carrying a strong colour (HSV S >= 0.50)
+
+ Unlit on purpose. Gradient, grain and AO are uniform multiplies, so they move
+ a pixel's value but never its saturation; LIGHTS do move it — a white key
+ washes colour out, a blue rim invents it. Measuring the lit render made the
+ answer a property of the lighting rig, which nobody ships."""
+ if not body.any():
+ return {}
+ lin = np.clip(colour[body], 0.0, 1.0)
+ srgb = np.where(lin <= 0.0031308, lin * 12.92, 1.055 * np.power(lin, 1 / 2.4) - 0.055)
+ d = np.clip(srgb * 255.0, 0, 255)
+ lum = 0.2126 * d[:, 0] + 0.7152 * d[:, 1] + 0.0722 * d[:, 2]
+ mx = d.max(axis=1)
+ mn = d.min(axis=1)
+ sat = np.where(mx > 0, (mx - mn) / np.maximum(mx, 1e-9), 0.0)
+ return {'median_lum': round(float(np.median(lum)), 1),
+ 'saturated_area': round(float((sat >= 0.50).mean()), 4)}
+
+
def exaggeration(mask):
"""The numbers that answer 'is this bold enough' — no reader required.
@@ -336,7 +530,7 @@ def iou(a, b):
def thumb(mask, px, path):
- """Letterboxed, exactly like maskmetrics: the proportion the reader sees is
+ """Letterboxed, as the measure pass always was: the proportion the reader sees is
the proportion the file records."""
ys, xs = np.nonzero(mask)
if len(xs) == 0:
@@ -359,16 +553,22 @@ def main():
return 2
model, outdir = a[0], a[1]
prev = a[a.index('--prev') + 1] if '--prev' in a else None
+ hero_out = a[a.index('--hero') + 1] if '--hero' in a else None
views = (a[a.index('--views') + 1].split(',') if '--views' in a
else ['front', 'side', 'top', 'hero'])
os.makedirs(outdir, exist_ok=True)
- V, F, MID, mats = triangles_by_material(model)
+ if hero_out:
+ hero_png(model, hero_out)
+ print(f'hero: {hero_out}')
+ V, F, MID, mats, C, basecol, _N = triangles_by_material(model, want_colour=True)
+ boxes, whole = part_boxes(V, F, MID, mats)
report = {'vertices': int(len(V)), 'triangles': int(len(F)),
- 'materials': mats, 'views': {}}
+ 'materials': mats, 'stats': structure(model),
+ 'parts': boxes, 'whole': {'size': whole}, 'views': {}}
thin_all = []
for v in views:
- shares, mask = material_shares(V, F, MID, mats, v)
+ shares, mask, colour = material_shares(V, F, MID, mats, v, C, basecol)
np.save(os.path.join(outdir, f'mask_{v}.npy'), mask)
Image.fromarray(np.where(mask, 0, 255).astype(np.uint8), 'L').save(
os.path.join(outdir, f'sil_{v}.png'))
@@ -376,6 +576,7 @@ def main():
thumb(mask, px, os.path.join(outdir, f'sil_{v}_thumb{px}.png'))
mm = measures(mask)
mm.update(exaggeration(mask))
+ mm.update(colour_measures(mask, colour))
mm['share'] = shares
if mm.get('thinnest_px48') is not None:
thin_all.append(mm['thinnest_px48'])
@@ -383,6 +584,9 @@ def main():
p = os.path.join(prev, f'mask_{v}.npy')
if os.path.exists(p):
mm['iou_vs_prev'] = iou(mask, np.load(p))
+ for name, sh in shares.items():
+ if name in report['parts']:
+ report['parts'][name].setdefault('share', {})[v] = sh
report['views'][v] = mm
if thin_all:
diff --git a/harness/partreads.py b/harness/partreads.py
index df5901e..f4eca31 100644
--- a/harness/partreads.py
+++ b/harness/partreads.py
@@ -2,7 +2,7 @@
"""Every MID part read, ONE command — build, render, and hand back one batch.
python3 harness/partreads.py <outdir> --spec face.json claw.json tail.json
- [--colour hero.png]
+ [--colour]
The MID whitelist reads used to be two commands PER PART — a compile and a
silhouette render — issued one at a time, and then one reader per part. Card 02
@@ -10,8 +10,8 @@ already merged the reads into a single batch; this merges the building too, so
four parts cost one turn instead of eight.
The turn is the unit that costs. A compile is 1.4 seconds and a view is half a
-second; a round-trip re-reads the entire conversation so far. A measured a run
-build spent 150-odd turns on tool calls that could have been a handful.
+second; a round-trip re-reads the entire conversation so far. A build can
+spend 150-odd turns on tool calls that could have been a handful.
Prints the shuffled batch the reader should see, and the answer key you keep to
yourself. Python and stdlib only — the harness ships to other people.
@@ -60,15 +60,13 @@ def main():
print(' ' + b[:140])
continue
# ONE tool reads geometry and produces measures, and it is outline.py.
- # This used to be silmetrics.mjs (launch a browser, render, read pixels)
- # followed by maskmetrics.py (letterbox and measure) — two commands, a
- # browser dependency, and a SECOND definition of every number outline.py
- # already computes. Two implementations of one measure have to be kept
- # in agreement by hand, and they were not: outline.py's first
- # thinnest_px48 took the global minimum of the distance transform and
- # read ~0.25px on every creature, because it was re-derived instead of
- # shared. Departments share their tools; synccheck.py lists any measure
- # that still has more than one definition.
+ # This used to be two commands — a browser render, then a letterbox and
+ # measure pass — with a browser dependency and a SECOND definition of every
+ # number outline.py already computes. Two implementations of one measure have
+ # to be kept in agreement by hand, and they were not: one of them took the
+ # global minimum of the distance transform for thinnest_px48 and read ~0.25px
+ # on every creature, because it was re-derived instead of shared. Departments
+ # share their tools; synccheck.py lists any measure that still has more than one definition.
rc2, out2 = run(['python3', os.path.join('harness', 'outline.py'), glb, dest])
if rc2 != 0:
print(f' {name:<22} silhouette failed: '
@@ -78,7 +76,7 @@ def main():
thumbs = [f'sil_{v}_thumb48.png' for v in ('hero', 'side', 'front', 'top')]
pick = next((t for t in thumbs if os.path.exists(os.path.join(dest, t))), None)
if not pick:
- print(f' {name:<22} no thumb48 produced (maskmetrics did not run?)')
+ print(f' {name:<22} no thumb48 produced (outline.py did not run?)')
continue
p = os.path.join(dest, pick)
images.append(p)
diff --git a/harness/publish.mjs b/harness/publish.mjs
index 1d6a9f0..9d82d5a 100644
--- a/harness/publish.mjs
+++ b/harness/publish.mjs
@@ -149,6 +149,10 @@ try {
}
// ── 3. one JSON line for the closing dialogue ──
+// The server hands back ONE handle that lets the person manage or take down
+// their own model. It is shown once and losing it is not recoverable, so it is
+// written next to the delivery AND printed — never swallowed.
+//
// AND ITS NAME IS NOT OURS TO ASSUME. The comment forty lines below this one says
// "the server's vocabulary is ITS to change ... never match a fixed word again",
// because a status word changed once and this client called a successful upload
@@ -306,7 +310,7 @@ if (ACK && located && !REVIEW) {
...M,
title: body.title ?? title, creator: body.creator ?? creator, thumb: hasThumb }));
} else if (ACK && REVIEW) {
- // held for a human: still a successful upload, and it can still carry a token
+ // held for a human: still a successful upload, and it can still carry a handle
console.log(JSON.stringify({ status: 'pending_review', server_status: body.status ?? null,
...M, thumb: hasThumb }));
} else if (ACK) {
@@ -314,7 +318,7 @@ if (ACK && located && !REVIEW) {
console.log(JSON.stringify({ status: 'pending_review', server_status: body.status ?? null,
...M, thumb: hasThumb }));
} else {
- // even a refusal can carry a token for an earlier upload — never swallow it
+ // even a refusal can carry a handle for an earlier upload — never swallow it
console.log(JSON.stringify({ status: 'error', http: res.status,
server_status: body.status ?? null,
error: body.error || `unexpected response: ${JSON.stringify(body).slice(0, 200)}`,
diff --git a/harness/pwlaunch.mjs b/harness/pwlaunch.mjs
deleted file mode 100644
index 82e55cc..0000000
--- a/harness/pwlaunch.mjs
+++ /dev/null
@@ -1,62 +0,0 @@
-// One browser launcher for every render tool. Author: Ariescar.
-// PW_CHROMIUM_PATH pins a binary; PW_NO_SANDBOX=1 only where the OS sandbox
-// genuinely cannot run. On failure, dies with ONE actionable line — the fix is
-// always the same and a stack trace never says it.
-//
-// AND IT LOOKS IN THE BROWSER CACHE BEFORE IT GIVES UP. Playwright asks for the
-// exact build number its own package was pinned to, so a machine holding
-// chromium-1194 while the installed playwright wants 1234 reports "Executable
-// doesn't exist" and the setup script goes off to download one. On a host whose
-// egress is filtered that download can never succeed: measured, one run spent
-// a run on four retries of a fetch that was never going to complete, on a
-// container that already had a working Chromium in /opt/pw-browsers. A build
-// number mismatch is not a missing browser. Look first, download second.
-import { chromium } from 'playwright';
-import fs from 'fs';
-import path from 'path';
-
-const BIN = ['chrome', 'chrome-headless-shell', 'headless_shell', 'chrome.exe'];
-
-export function findCachedChromium() {
- const roots = [process.env.PLAYWRIGHT_BROWSERS_PATH,
- path.join(process.env.HOME || '', '.cache', 'ms-playwright'),
- path.join(process.env.LOCALAPPDATA || '', 'ms-playwright')].filter(Boolean);
- const hits = [];
- const walk = (dir, depth) => {
- if (depth > 4) return;
- let ents;
- try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
- for (const e of ents) {
- const p = path.join(dir, e.name);
- if (e.isDirectory()) walk(p, depth + 1);
- else if (BIN.includes(e.name)) hits.push(p);
- }
- };
- for (const r of roots) walk(r, 0);
- // a full chromium beats a headless shell: the render tools take screenshots
- hits.sort((a, b) => (a.includes('headless') ? 1 : 0) - (b.includes('headless') ? 1 : 0));
- return hits[0] || null;
-}
-
-export async function launchBrowser() {
- const args = ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']
- .concat(process.env.PW_NO_SANDBOX === '1' ? ['--no-sandbox'] : []);
- const tries = [process.env.PW_CHROMIUM_PATH || undefined];
- let first = null;
- for (const executablePath of tries) {
- try { return await chromium.launch({ executablePath, args }); }
- catch (e) { first = e; }
- }
- // playwright could not find its own pinned build — look for ANY cached one
- const found = findCachedChromium();
- if (found) {
- try {
- const br = await chromium.launch({ executablePath: found, args });
- console.error(`note: playwright's pinned build is absent; using the cached browser at ${found}`);
- return br;
- } catch (e) { first = e; }
- }
- console.error('render tool cannot start a browser: ' + String(first && first.message || first).split('\n')[0]);
- console.error('Fix: run npx playwright install chromium (or set PW_CHROMIUM_PATH to a Chromium/Chrome binary)');
- process.exit(3);
-}
diff --git a/harness/pwprobe.mjs b/harness/pwprobe.mjs
deleted file mode 100644
index 6448129..0000000
--- a/harness/pwprobe.mjs
+++ /dev/null
@@ -1,13 +0,0 @@
-// Launch-and-quit probe: proves the render tools can start a browser.
-// Prints ONE actionable line on failure instead of a stack trace.
-import { launchBrowser } from './pwlaunch.mjs';
-try {
- const br = await launchBrowser();
- await br.close();
- console.log('render tools OK (browser launches)');
-} catch (e) {
- console.error(String(e && e.message || e).split('\n')[0]);
- console.error('render tools need a browser. Fix: run npx playwright install chromium');
- console.error('(or point PW_CHROMIUM_PATH at an existing Chromium/Chrome binary)');
- process.exit(3);
-}
diff --git a/harness/round.py b/harness/round.py
index f1de1aa..9db6e1d 100644
--- a/harness/round.py
+++ b/harness/round.py
@@ -5,7 +5,7 @@
[--prev rM] [--gate ID|PUNCH] [--brief brief.md]
WHY THIS EXISTS. A round used to be five or six separate commands: build, then
-silmetrics, then maskmetrics, then roundcheck --preflight, then (after the
+a silhouette pass, then a measure pass, then roundcheck --preflight, then (after the
read) --record and --check. Each of those is a TURN, and a turn is the unit
that actually costs money here — every one re-reads the whole conversation so
far, which keeps growing, so the same command issued at round 20 costs several
@@ -23,9 +23,11 @@ them. Give it one spec and it is an ordinary repair round.
AT r1 IT ALSO CHECKS THE BRIEF, because r1 is the last moment anything there is
cheap to change. Two things, both from harness/brief.py: every slot a later
stage actually reads is filled in, and the two poles are really two designs
-rather than one design built twice. Three separate rounds that are all the same
-design cost three builds, three renders and three turns and produce zero
-comparisons.
+rather than one design built twice. The second one exists because of a failure
+mode with teeth — r1, r2 and r3 come out as three separate rounds of one design,
+0.08 to 0.20 apart on the mass-layout ruler when two different creatures are
+typically 0.63 apart, and nobody compares any of them until r4. Three builds,
+three renders, three turns, zero comparisons.
Python and stdlib only, so it behaves the same on Windows, macOS and Linux —
the harness ships to other people and cannot assume a shell.
diff --git a/harness/roundcheck.py b/harness/roundcheck.py
index f1899ee..2d50a31 100644
--- a/harness/roundcheck.py
+++ b/harness/roundcheck.py
@@ -20,7 +20,7 @@ session says it did:
the round did not happen and the next check refuses to pass it)
· whether the round was a TWEAK or a real restart, from iou_vs_prev in
out/rN/metrics.json — a nudged silhouette stays >0.85 similar to the last
- one no matter what the session calls it. Run silmetrics with
+ one no matter what the session calls it. Run outline.py with
`--prev out/r<N-1>` or this number is null and the guard is blind.
· whether the feature being argued about is even visible at reading size,
from thinnest_px48 — the blind read happens on a 48px thumbnail.
@@ -44,7 +44,8 @@ MAX_FAILS_TOTAL = 5 # hard ceiling per gate, counted regardless of iou
# differ: "a fox, not a dragon" is not a fine-tuning verdict. Nothing between
# 0.70 and 0.85 — a moved ear, a longer tail — changes what a stranger calls the
# animal, so a repair in that band is a round spent to be told the same noun
-# again.
+# again. Field evidence: one creature was read 13 times with barely a change
+# between rounds, some rounds changing nothing at all.
#
# The number is enforceable now because `outline.py` computes iou from the
# geometry rather than from a rasterised picture, so it is exact and free.
@@ -84,8 +85,8 @@ def rounds(outdir):
def iou_of(m):
- """metrics.json is either the silmetrics shape (flat) or the maskmetrics
- shape (keyed by image name). Only silmetrics computes iou_vs_prev."""
+ """metrics.json is either the flat shape or one keyed by image name.
+ Only a run given --prev computes iou_vs_prev."""
if not isinstance(m, dict):
return None
if 'iou_vs_prev' in m:
@@ -226,7 +227,7 @@ def preflight(outdir, rn, gate):
f'this number; do NOT thicken a feature whose thinness is the design.')
if iou is None and cur['n'] > 1:
- print('[roundcheck] iou_vs_prev is null — run silmetrics with `--prev out/r<N-1>` '
+ print('[roundcheck] iou_vs_prev is null — run outline.py with `--prev out/r<N-1>` '
'or this pre-check is blind and every round pays for its reader.')
for n in notes_thin:
@@ -325,7 +326,7 @@ def check(outdir, gate):
notes.append(f'{gate} has failed {fails} time(s) in a row: {shown}')
if blind:
- problems.append('iou_vs_prev is null — silmetrics was run without `--prev out/r<N-1>`, '
+ problems.append('iou_vs_prev is null — outline.py was run without `--prev out/r<N-1>`, '
'so the tweak detector is switched off and law 3 cannot be enforced. '
'Re-run the measure step with --prev.')
diff --git a/harness/silmetrics.mjs b/harness/silmetrics.mjs
deleted file mode 100644
index fd9ab32..0000000
--- a/harness/silmetrics.mjs
+++ /dev/null
@@ -1,267 +0,0 @@
-// anyCreature — silhouette metrics tool. Author: Ariescar.
-// The measuring half of the LOWRES loop. Renders the model as a pure-black
-// silhouette (side + front), then computes the FLOOR numbers and the
-// CHARACTER-AXIS numbers, plus the 24px thumbnail used by the blind-read gate.
-//
-// node harness/silmetrics.mjs <model.glb> <outdir> [--prev <outdir_of_previous_round>]
-//
-// outputs in <outdir>:
-// sil_side.png / sil_front.png 640px silhouettes (human review)
-// thumb24.png 24px silhouette, nearest-upscaled to 240px
-// → show ONLY this image to a context-free
-// blind reader; ask (1) "what is this?"
-// (2) "which part grabs the eye most?"
-// (3) "list the parts/features you can read"
-// sil_side.mask.json packed mask (input for next round's --prev)
-// metrics.json all numbers, see below
-//
-// metrics.json:
-// W_over_H, fill, mass_thirds — global mass layout
-// torso_depth_{min,max}, mass_contrast (max/min torso depth over mid-band)
-// leg_fraction — ground→belly gap at mid-body / H
-// turn_count — hard silhouette corners (>35°); LOW
-// turn_count = the "too round" disease
-// zigzag_alignment — fraction of top-contour bumps sitting
-// directly above a bottom-contour bump
-// (0 = staggered/good, 1 = stacked/stiff)
-// iou_vs_prev — regression guard (needs --prev)
-//
-// These are not pass/fail thresholds. The design card DECLARES a position per
-// axis (tension targets); this tool verifies the declared position was reached.
-import { launchBrowser } from './pwlaunch.mjs';
-import fs from 'fs'; import path from 'path'; import http from 'http';
-import { fileURLToPath } from 'url';
-
-const here = path.dirname(fileURLToPath(import.meta.url));
-const [modelPath, outDir] = process.argv.slice(2);
-const prevIx = process.argv.indexOf('--prev');
-const prevDir = prevIx > 0 ? process.argv[prevIx + 1] : null;
-if (!modelPath || !outDir) { console.error('usage: node silmetrics.mjs <model.glb> <outdir> [--prev <prev outdir>]'); process.exit(2); }
-fs.mkdirSync(outDir, { recursive: true });
-
-const html = `<!doctype html><body style="margin:0"><script src="/bundle.js"></script><script>
-const scene=new THREE.Scene(); scene.background=new THREE.Color(0xffffff);
-const cam=new THREE.PerspectiveCamera(30,1,0.01,100);
-const r=new THREE.WebGLRenderer({antialias:false,preserveDrawingBuffer:true}); r.setSize(640,640);
-document.body.appendChild(r.domElement);
-let cur=null;
-window.load=(url)=>new Promise((res,rej)=>{ fetch(url).then(x=>x.arrayBuffer()).then(buf=>{
- new GLTFLoader().parse(buf,'',g=>{ cur=g.scene; scene.add(cur);
- cur.traverse(o=>{o.frustumCulled=false; if(o.isMesh)o.material=new THREE.MeshBasicMaterial({color:0,side:THREE.DoubleSide});});
- res(1);},e=>rej(String(e))); }); });
-window.shoot=(view)=>{ const box=new THREE.Box3().setFromObject(cur),c=box.getCenter(new THREE.Vector3()),s=box.getSize(new THREE.Vector3());
- const long = s.x>s.z ? 'x':'z';
- let dir;
- if(view==='top'){ dir=[0,1,0]; cam.up.set(long==='x'?1:0, 0, long==='x'?0:1); }
- else if(view==='hero'){ cam.up.set(0,1,0); dir=[1,0.5,1]; }
- else { cam.up.set(0,1,0); dir = view==='side' ? (long==='x'?[0,0,1]:[1,0,0]) : (long==='x'?[1,0,0]:[0,0,1]); }
- const rad=Math.max(s.x,s.y,s.z);
- cam.position.copy(c).add(new THREE.Vector3(...dir).multiplyScalar(rad*2.4)); cam.lookAt(c);
- r.render(scene,cam);
- const g2=r.domElement.getContext('webgl2')||r.domElement.getContext('webgl');
- const px=new Uint8Array(640*640*4); g2.readPixels(0,0,640,640,g2.RGBA,g2.UNSIGNED_BYTE,px);
- let bits='';
- for(let y=639;y>=0;y--){ let acc=0,n=0;
- for(let x=0;x<640;x++){ acc=(acc<<1)|(px[(y*640+x)*4]<128?1:0); if(++n===6){bits+=String.fromCharCode(48+acc);acc=0;n=0;} }
- if(n)bits+=String.fromCharCode(48+(acc<<(6-n))); // row-aligned: flush per row
- }
- return { bits, png: r.domElement.toDataURL('image/png') }; };
-</script></body>`;
-
-const srv = http.createServer((q, res) => {
- if (q.url === '/') { res.writeHead(200, { 'content-type': 'text/html' }); return res.end(html); }
- if (q.url === '/bundle.js') { res.writeHead(200, { 'content-type': 'text/javascript' }); return res.end(fs.readFileSync(path.join(here, 'assets/three-bundle.js'))); }
- if (q.url === '/model.glb') { res.writeHead(200); return res.end(fs.readFileSync(modelPath)); }
- res.writeHead(404); res.end();
-});
-// loopback only, and let the OS pick the port — a fixed port on 0.0.0.0
-// exposed the page and the model to the whole network, and collided
-// whenever two runs overlapped.
-await new Promise(r => srv.listen(0, '127.0.0.1', r));
-const port = srv.address().port;
-// Shared launcher: PW_CHROMIUM_PATH pins a binary; a missing browser dies with
-// ONE actionable line ("run npx playwright install chromium"), never a stack.
-const br = await launchBrowser();
-const pg = await br.newPage({ viewport: { width: 660, height: 660 } });
-await pg.goto(`http://127.0.0.1:${port}/`);
-await pg.evaluate(() => window.load('/model.glb'));
-await pg.waitForTimeout(600);
-
-function unpack(bits) {
- const m = Array.from({ length: 640 }, () => new Uint8Array(640));
- let i = 0;
- for (let y = 0; y < 640; y++) for (let x = 0; x < 640; x += 6) {
- const c = bits.charCodeAt(i++) - 48;
- for (let b = 0; b < 6 && x + b < 640; b++) m[y][x + b] = (c >> (5 - b)) & 1;
- }
- return m;
-}
-function bbox(m) {
- let y0 = 640, y1 = -1, x0 = 640, x1 = -1;
- for (let y = 0; y < 640; y++) for (let x = 0; x < 640; x++) if (m[y][x]) {
- if (y < y0) y0 = y; if (y > y1) y1 = y; if (x < x0) x0 = x; if (x > x1) x1 = x;
- }
- return { y0, y1, x0, x1 };
-}
-const shots = {};
-for (const view of ['side', 'front', 'top', 'hero']) {
- const { bits, png } = await pg.evaluate(v => window.shoot(v), view);
- fs.writeFileSync(path.join(outDir, `sil_${view}.png`), Buffer.from(png.split(',')[1], 'base64'));
- shots[view] = unpack(bits);
-}
-await br.close(); srv.close();
-
-// ── 24px thumbnail (nearest ×10) from the side mask ──
-{
- const m = shots.side, b = bbox(m);
- const W = b.x1 - b.x0 + 1, H = b.y1 - b.y0 + 1, S = Math.max(W, H);
- const canvasPng = await (async () => {
- // tiny hand-rolled PNG: 240x240 grayscale via zlib store — use playwright page instead? keep simple: write PGM then let humans open PNGs; blind reader gets a PNG rendered from mask
- const px = 240; const img = Buffer.alloc(px * px, 255);
- for (let y = 0; y < px; y++) for (let x = 0; x < px; x++) {
- const sx = b.x0 + Math.floor((Math.floor(x / 10) + 0.5) / 24 * S) - Math.floor((S - W) / 2);
- const sy = b.y0 + Math.floor((Math.floor(y / 10) + 0.5) / 24 * S) - Math.floor((S - H) / 2);
- let on = 0;
- if (sx >= 0 && sy >= 0 && sx < 640 && sy < 640) {
- // 24px cell = majority vote over the source block
- const cell = S / 24; let cnt = 0, tot = 0;
- for (let dy = 0; dy < cell; dy += 2) for (let dx = 0; dx < cell; dx += 2) {
- const yy = sy + Math.floor(dy - cell / 2), xx = sx + Math.floor(dx - cell / 2);
- if (yy >= 0 && xx >= 0 && yy < 640 && xx < 640) { tot++; cnt += m[yy][xx]; }
- }
- on = tot && cnt / tot > 0.35 ? 1 : 0;
- }
- if (on) img[y * px + x] = 0;
- }
- const zlib = await import('zlib');
- const raw = Buffer.alloc(px * (px + 1));
- for (let y = 0; y < px; y++) { raw[y * (px + 1)] = 0; img.copy(raw, y * (px + 1) + 1, y * px, (y + 1) * px); }
- const idat = zlib.deflateSync(raw);
- const crc = (buf) => { let c = ~0; for (const b2 of buf) { c ^= b2; for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xEDB88320 & -(c & 1)); } return ~c >>> 0; };
- const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const cc = Buffer.alloc(4); cc.writeUInt32BE(crc(td)); return Buffer.concat([len, td, cc]); };
- const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(px, 0); ihdr.writeUInt32BE(px, 4); ihdr[8] = 8; ihdr[9] = 0;
- return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', idat), chunk('IEND', Buffer.alloc(0))]);
- })();
- fs.writeFileSync(path.join(outDir, 'thumb24.png'), canvasPng);
-}
-
-// ── metrics on the side mask ──
-const m = shots.side, b = bbox(m);
-const H = b.y1 - b.y0 + 1, W = b.x1 - b.x0 + 1;
-const at = (y, x) => m[b.y0 + y] ? (m[b.y0 + y][b.x0 + x] || 0) : 0;
-let area = 0; for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) area += at(y, x);
-const thirds = [0, 1, 2].map(i => {
- let s = 0;
- for (let y = 0; y < H; y++) for (let x = Math.floor(i * W / 3); x < Math.floor((i + 1) * W / 3); x++) s += at(y, x);
- return +(s / area).toFixed(3);
-});
-// largest contiguous run per column = torso(+merged limb) depth
-const runTop = new Array(W).fill(-1), runBot = new Array(W).fill(-1), runLen = new Array(W).fill(0);
-for (let x = 0; x < W; x++) {
- let best = 0, bt = -1, bb = -1, s = -1;
- for (let y = 0; y <= H; y++) {
- const v = y < H ? at(y, x) : 0;
- if (v && s < 0) s = y;
- if (!v && s >= 0) { if (y - s > best) { best = y - s; bt = s; bb = y - 1; } s = -1; }
- }
- runTop[x] = bt; runBot[x] = bb; runLen[x] = best;
-}
-const band = runLen.slice(Math.floor(0.18 * W), Math.floor(0.82 * W)).filter(v => v > 0);
-const dMax = Math.max(...band) / H, dMin = Math.min(...band) / H;
-// leg fraction: columns whose run touches the bottom 3% are feet; take the gap
-// between front and back foot groups, measure belly→ground there
-const footCols = [];
-for (let x = 0; x < W; x++) if (runBot[x] >= 0 && runBot[x] > H * 0.94 - 1) footCols.push(x);
-let legFrac = null;
-if (footCols.length) {
- // largest gap between consecutive foot columns = under-belly span
- let g0 = -1, g1 = -1, best = 0;
- for (let i = 1; i < footCols.length; i++) {
- const gap = footCols[i] - footCols[i - 1];
- if (gap > best) { best = gap; g0 = footCols[i - 1]; g1 = footCols[i]; }
- }
- if (best > 3) {
- const mid = Math.floor((g0 + g1) / 2);
- legFrac = +((H - 1 - runBot[mid]) / H).toFixed(3);
- }
-}
-// contour turn count (top + bottom boundary polylines)
-function turnCount(boundary) {
- const ys = boundary.filter(v => v >= 0);
- if (ys.length < 20) return 0;
- const sm = ys.map((_, i) => {
- let s = 0, n = 0;
- for (let k = -2; k <= 2; k++) if (ys[i + k] !== undefined) { s += ys[i + k]; n++; }
- return s / n;
- });
- let count = 0, last = -10;
- const step = 4;
- for (let i = step; i < sm.length - step; i++) {
- const a = Math.atan2(sm[i] - sm[i - step], step), c = Math.atan2(sm[i + step] - sm[i], step);
- const d = Math.abs(c - a) * 180 / Math.PI;
- if (d > 35 && i - last > 8) { count++; last = i; }
- }
- return count;
-}
-const topB = new Array(W).fill(-1), botB = new Array(W).fill(-1);
-for (let x = 0; x < W; x++) for (let y = 0; y < H; y++) if (at(y, x)) { topB[x] = y; break; }
-for (let x = 0; x < W; x++) for (let y = H - 1; y >= 0; y--) if (at(y, x)) { botB[x] = y; break; }
-const turns = turnCount(topB) + turnCount(botB);
-// zigzag alignment: top-contour extrema stacked over bottom-contour extrema?
-function extrema(bd) {
- const out = [];
- for (let x = 6; x < W - 6; x++) {
- if (bd[x] < 0) continue;
- let isMin = true, isMax = true;
- for (let k = -6; k <= 6; k++) { if (bd[x + k] < 0) { isMin = isMax = false; break; }
- if (bd[x + k] < bd[x]) isMin = false; if (bd[x + k] > bd[x]) isMax = false; }
- if ((isMin || isMax) && (!out.length || x - out[out.length - 1] > 10)) out.push(x);
- }
- return out;
-}
-const te = extrema(topB), be = extrema(botB);
-let stacked = 0;
-for (const x of te) if (be.some(x2 => Math.abs(x2 - x) < 0.04 * W)) stacked++;
-const zigzag = te.length ? +(stacked / te.length).toFixed(2) : 0;
-
-// iou vs previous round
-let iou = null;
-if (prevDir) {
- const prev = unpack(JSON.parse(fs.readFileSync(path.join(prevDir, 'sil_side.mask.json'))).bits);
- const pb = bbox(prev);
- let inter = 0, uni = 0;
- for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
- const a = at(y, x);
- const py = pb.y0 + Math.floor(y * (pb.y1 - pb.y0 + 1) / H);
- const px2 = pb.x0 + Math.floor(x * (pb.x1 - pb.x0 + 1) / W);
- const p = prev[py] ? (prev[py][px2] || 0) : 0;
- if (a & p) inter++; if (a | p) uni++;
- }
- iou = +(inter / (uni || 1)).toFixed(3);
-}
-
-let repack = '';
-for (let y = 0; y < 640; y++) for (let x = 0; x < 640; x += 6) {
- let c = 0; for (let bq = 0; bq < 6; bq++) c = (c << 1) | (x + bq < 640 ? m[y][x + bq] : 0);
- repack += String.fromCharCode(48 + c);
-}
-fs.writeFileSync(path.join(outDir, 'sil_side.mask.json'), JSON.stringify({ bits: repack }));
-// per-view basics: identity must hold from every orthographic view, not one
-const viewStats = {};
-for (const view of ['front', 'top', 'hero']) {
- const mv = shots[view], bv = bbox(mv);
- if (bv.y1 < 0) { viewStats[view] = null; continue; }
- const Hv = bv.y1 - bv.y0 + 1, Wv = bv.x1 - bv.x0 + 1;
- let av = 0;
- for (let y = bv.y0; y <= bv.y1; y++) for (let x = bv.x0; x <= bv.x1; x++) av += mv[y][x];
- viewStats[view] = { W_over_H: +(Wv / Hv).toFixed(2), fill: +(av / (Wv * Hv)).toFixed(3) };
-}
-const metrics = {
- W_over_H: +(W / H).toFixed(2), fill: +(area / (W * H)).toFixed(3),
- mass_thirds: thirds, torso_depth_max: +dMax.toFixed(2), torso_depth_min: +dMin.toFixed(2),
- mass_contrast: +(dMax / (dMin || 1)).toFixed(2), leg_fraction: legFrac,
- turn_count: turns, zigzag_alignment: zigzag, iou_vs_prev: iou,
- front: viewStats.front, top: viewStats.top, hero: viewStats.hero,
-};
-fs.writeFileSync(path.join(outDir, 'metrics.json'), JSON.stringify(metrics, null, 1));
-console.log(JSON.stringify(metrics));
diff --git a/harness/synccheck.py b/harness/synccheck.py
index 3db8f81..7ce1c82 100644
--- a/harness/synccheck.py
+++ b/harness/synccheck.py
@@ -14,11 +14,10 @@ What it verifies:
2. promised features every feature the CHANGELOG promises is present in
the code that ships (the 1.2.0 leak class)
3. required files everything the cards and scripts point at exists
- 4. leak scan strings that must never appear in a public tree
- 5. no dangling docs a shipped file may not point at a doc that stayed home
- 6. no forward refs nothing ships describing a version that is not out yet
+ 4. leak scan strings — and whole files — that must never appear
+ in a public tree
"""
-import os, re, sys
+import os, re, sys, subprocess, shutil
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
bad = []
@@ -54,13 +53,31 @@ if version:
# One line per promise. ADD A LINE WHEN YOU ADD A FEATURE — this list is the
# contract between the release notes and the code.
FEATURES = [
+ ('engine/core/checks.js', 'gait_footfall', 'a step lands in front of where it lifts'),
+ ('engine/core/checks.js', 'effector_leads', 'the declared effector is frontmost at the strike'),
+ ('engine/core/checks.js', 'attack_windup', 'a strike winds up before it commits'),
+ ('engine/core/checks.js', 'clip_closes', 'a non-looping clip returns to its first frame'),
+ ('engine/core/checks.js', 'ground_clip', 'nothing goes below the ground plane'),
+ ('engine/core/selfclip.js', 'selfClip', 'swept self-collision, broad + narrow phase'),
+ ('engine/core/inside.js', 'signedDistance', 'surface distance, not a sphere through the widest ring'),
+ ('engine/core/inside.js', 'function islands', 'one creature is one connected body'),
+ ('engine/core/checks.js', 'body_islands:', 'a floating piece is refused'),
+ ('engine/core/anim.js', 'mirrorTrack', 'mirroring resamples instead of shifting keys'),
+ ('harness/autofix.mjs', 'aimSubordinate', 'compensation is subordinate to the purpose'),
+ ('cards/SYNTAX.md', '"function"', 'the function block is documented'),
+ ('engine/core/skeleton.js', 'jointRanges', 'declared joint limits, R side generated'),
+ ('engine/core/checks.js', 'joint_range:', 'joint limits: undeclared / overrun / unreachable'),
+ ('cards/SYNTAX.md', '"joint_range"', 'the joint_range block is documented'),
+ ('engine/core/checks.js', 'part_names:', 'every part is named, uniquely'),
+ ('engine/core/glb.js', 'part_spans', 'per-part vertex ranges in the manifest'),
+ ('docs/OUTPUT_CONTRACT.md', 'part_spans', 'part_spans documented in the contract'),
+ ('cards/SYNTAX.md', 'the identity channel', 'part naming is documented'),
('engine/core/checks.js', 'part_seat', 'declared joins / exposed-root check'),
('engine/core/checks.js', 'attack_reach', 'attack must lunge'),
('engine/core/checks.js', 'gait_direction', 'a planted foot must sweep backward'),
('harness/fit.py', 'FIXABLE', 'the arithmetic blocks are applied, not hand-fixed'),
('cards/01_LOW.md', 'harness/fit.py', 'the card runs the fitter before the first round'),
('engine/core/checks.js', 'root_drive', 'a lunge is driven on the skeleton root'),
- ('harness/pwlaunch.mjs', 'findCachedChromium', 'the cached browser is found before any download'),
('engine/core/checks.js', 'touch:', 'declared adjacency'),
('engine/core/checks.js', 'part_overlap', 'part interpenetration measure'),
('engine/core/checks.js', 'faceted_body', 'faceted volumes blocked'),
@@ -76,9 +93,11 @@ FEATURES = [
('engine/core/relative.js', 'joints_R', 'right-side pose overrides'),
('engine/core/ao.js', 'bakeAO', 'vertex AO bake'),
('engine/core/normals.js', 'smoothSplit', 'smoothing-angle normals'),
- ('harness/pwlaunch.mjs', 'launchBrowser', 'shared browser launcher'),
- ('setup.sh', 'playwright install', 'browser installed at setup'),
- ('setup.sh', 'pwprobe', 'browser probed at setup'),
+ ('setup.sh', 'NO BROWSER', 'setup installs no browser'),
+ ('harness/outline.py', 'def hero_png', 'the hero shot is projected, not rendered'),
+ ('harness/outline.py', 'def structure', 'clips/skins/tris read from the glTF header'),
+ ('harness/outline.py', 'def part_boxes', 'per-part bboxes without a scene graph'),
+ ('harness/judge.mjs', 'zero browser', 'the judge measures nothing itself'),
('cards/02_MID.md', 'join', 'join doctrine in the MID card'),
('cards/SYNTAX.md', '"join"', 'join in the syntax page'),
('engine/core/compile.js', 'buildHand', 'hand part type (palm/fingers/thumb)'),
@@ -103,6 +122,17 @@ FEATURES = [
('engine/cli.js', 'example_copy', 'recoloured-example builds are refused'),
('cards/01_LOW.md', 'The verdict is SCORED', 'identity is scored by rank and view count'),
('harness/identity.py', 'def verdict', 'the identity score is counted, not argued'),
+ ('harness/identity.py', 'def rank_of', 'the synonym judgment is matched, not asserted'),
+ ('harness/identity.py', 'accepted_from_brief', 'the accepted list comes from the brief'),
+ ('harness/brief.py', 'identity: no accepted list', 'the brief must declare its accepted words'),
+ ('harness/brief.py', 'does not say whether it has an outline', 'the signature must declare whether it is visible in black'),
+ ('engine/core/checks.js', 'COMPLETELY buried', 'buried geometry is named separately from a seam'),
+ ('engine/core/checks.js', 'eye_pupil:', 'a lone eye sphere is named as a flat disc'),
+ ('engine/core/compile.js', 'outline points', 'a fin sliver is caught before it makes flipped tris'),
+ ('engine/core/relative.js', 'written relative to ITSELF', 'a self-referencing joints_R entry names itself'),
+ ('harness/publish.mjs', 'MANAGE_KEYS', 'the manage handle is read by family, not by one field name'),
+ ('cards/04_SHIP.md', 'manage_kind', 'the card tells the person a link or a code, per the server'),
+ ('cards/01_LOW.md', '--guesses', 'the card hands over the words, not a rank'),
('harness/publish.mjs', 'manage_token', 'one-time takedown token surfaced'),
('harness/ship.py', '--publish', 'one-command closing (package [+ publish])'),
('cards/04_SHIP.md', 'ship.py', 'card uses the one-command closing'),
@@ -119,8 +149,7 @@ FEATURES = [
('harness/glbcheck.mjs', 'anisotropy_without_direction', 'anisotropy without UV/TANGENT is blocked'),
('cards/03_HIGH.md', 'No anisotropy', 'anisotropy limit stated in the card'),
('harness/publish.mjs', 'SUCCESS IS NOT A MAGIC WORD', 'upload success is not matched by a literal word'),
- ('harness/judge.mjs', 'ALBEDO = baseColorFactor', 'the colour ruler reads the material, not COLOR_0 alone'),
- ('harness/calibrate.py', 'saturation_area', 'the colour ruler is calibrated both ways'),
+ ('harness/outline.py', 'ALBEDO = baseColorFactor', 'the colour ruler reads the material, not COLOR_0 alone'),
('harness/roundcheck.py', 'def preflight', 'the reader is gated BEFORE it is spent'),
('cards/01_LOW.md', '--preflight', 'card runs the pre-check before the read'),
('cards/01_LOW.md', 'TWO OPPOSITE POLES', 'a round builds two opposite poles, not three near-copies'),
@@ -147,6 +176,7 @@ FEATURES = [
('cards/04_SHIP.md', 'checks.json', 'card 04 copies the stamp instead of retyping it'),
('cards/03_HIGH.md', 'Write all three, then build ONCE', 'all three clips authored in one pass'),
('harness/outline.py', 'def render_mask', 'silhouettes computed from geometry, no browser'),
+ ('harness/outline.py', 'def colour_measures', 'colour measured off the baked albedo, no browser'),
('harness/round.py', 'outline.py', 'the round loop uses the geometry silhouette'),
('cards/00_START.md', 'LOW no longer needs a browser', 'the LOW loop is browser-free'),
('harness/roundcheck.py', 'RESTART_IOU', 'an identity repair has a minimum change'),
@@ -171,9 +201,8 @@ REQUIRED = [
'cards/00_START.md', 'cards/01_LOW.md', 'cards/02_MID.md',
'cards/03_HIGH.md', 'cards/04_SHIP.md', 'cards/SYNTAX.md',
'engine/cli.js',
- 'harness/silmetrics.mjs', 'harness/maskmetrics.py', 'harness/judge.mjs',
- 'harness/deliver.py', 'harness/hero.mjs', 'harness/publish.mjs',
- 'harness/pwlaunch.mjs', 'harness/pwprobe.mjs', 'harness/calibrate.py',
+ 'harness/judge.mjs',
+ 'harness/deliver.py', 'harness/publish.mjs',
'harness/gobkit.json', 'harness/assets/showroom.html',
'harness/assets/three-bundle.js',
'harness/claims.json', 'harness/roundcheck.py',
@@ -226,8 +255,10 @@ if esm and cjs:
# This does not fail the build; it prints the standing work queue, the way
# gates.py prints the blocking-but-allocatable list.
MEASURES = ['thirds_cols', 'thirds_rows', 'protrusions', 'thinnest_px48',
- 'sq_fill', 'mirror_sym', 'compactness', 'W_over_H']
-DEFINES = ['harness/outline.py', 'harness/maskmetrics.py', 'harness/silmetrics.mjs']
+ 'sq_fill', 'mirror_sym', 'compactness', 'W_over_H',
+ 'median_lum', 'saturated_area', 'span_ratio']
+DEFINES = ['harness/outline.py', 'harness/judge.mjs', 'harness/roundcheck.py',
+ 'harness/partreads.py', 'harness/brief.py']
dupes = []
for m in MEASURES:
where = [f for f in DEFINES if re.search(r"['\"]?" + m + r"['\"]?\s*[:=]", read(f) or '')]
@@ -237,9 +268,25 @@ if dupes:
print('[synccheck] SHARED-TOOL QUEUE — one measure should have one definition:')
for m, where in dupes:
print(f' {m:16} defined in {len(where)}: ' + ', '.join(where))
- print(' No card invokes maskmetrics.py or silmetrics.mjs any more (partreads.py')
- print(' moved to outline.py). They are superseded, kept one release for anyone')
- print(' calling them by hand, and the definitions above are the reason to finish.')
+ print(' A measure belongs to exactly one file. outline.py owns them all; anything')
+ print(' else listed above has re-derived one instead of reading it.')
+
+# ── 3bb. a generated manifest, where one exists, matches its sources ─────────
+# Only checked when the generator is present; it is not part of every tree.
+MANIFEST_GEN = 'tools/server-manifest.mjs'
+manifest_checked = os.path.isfile(os.path.join(ROOT, MANIFEST_GEN))
+if manifest_checked:
+ node = shutil.which('node')
+ if not node:
+ bad.append('manifest check: no `node` on PATH')
+ else:
+ proc = subprocess.run([node, MANIFEST_GEN, '--check'], cwd=ROOT, capture_output=True,
+ text=True, encoding='utf-8', errors='replace')
+ if proc.returncode != 0:
+ bad.append(f'manifest drift: regenerate with `node {MANIFEST_GEN}`')
+ for line in (proc.stdout + proc.stderr).splitlines():
+ enc = sys.stdout.encoding or 'utf-8'
+ print(' ' + line.encode(enc, errors='replace').decode(enc, errors='replace'))
# ── 3c. STRATEGY LEAK — the harness ships the architecture, not the reasoning ──
# What the pipeline DOES is the product. Why it was tuned that way, what each
@@ -251,12 +298,10 @@ STRATEGY = [
(r'~?\d+(?:\.\d+)?\s*[kKmM]?\s*tokens', 'a token cost'),
(r'\b\d+h\d+m\b|\b\d+m\d+s\b', 'a wall-clock timing'),
(r'\b\d+\s*minutes?\b', 'a wall-clock timing'),
- (r'[Mm]easured (?:on|across|in|,)', 'a field-report citation'),
+ (r'[Mm]easured (?:on|across|in)\b', 'a field-report citation'),
(r'a (?:shipped|delivered|measured|real) (?:build|creature|boss|run)', 'a field-report citation'),
(r'field report|its customer|a customer (?:said|singled|rejected)', 'a customer reference'),
(r'\b(?:322|327|315) turns\b', 'a run-length citation'),
- (r'\b\d+(?:\.\d+)?[x×] the (?:tokens|wall clock|model turns|cost)', 'a cost ratio'),
- (r'(?i)\b(scorpion|salamander|cassowary|bison|hippo|pagoda|millipede|elephant|boar|snail|gryphon|mammoth|naga|avian)\b[^.\n]{0,60}\b(?:read|round|run|build|shipped|failed|took)\b', 'a named creature tied to a run'),
]
SKIP = ('node_modules', '.git', 'example/', 'calibration/', 'assets/',
'harness/synccheck.py') # this file IS the pattern list
@@ -280,6 +325,41 @@ if leaks:
for rel, line, what, frag in leaks[:40]:
print(f' {rel}:{line} {what}: "{frag}"')
+# ── 3d. NO LAB NOTEBOOKS ─────────────────────────────────────────────────────
+# A lab notebook never ships, in any language, so no phrase list can be trusted
+# to catch one. The rule is the filename itself: what a notebook taught the
+# pipeline belongs in the cards and the code.
+for root, dirs, files in os.walk(ROOT):
+ dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', 'out',
+ 'delivery', 'creatures')]
+ for fn in files:
+ if fn.upper().startswith('DEVLOG'):
+ rel = os.path.relpath(os.path.join(root, fn), ROOT).replace(os.sep, '/')
+ bad.append(f'lab notebook in the public tree: {rel} — move it out; '
+ 'ship what it taught, not the notebook')
+
+# ── 3e. NO BROWSER ───────────────────────────────────────────────────────────
+# 1.3.2 removed the renderer from every measuring path: a silhouette is a
+# projection, occlusion is a z-buffer, the baked colour IS the albedo, and the
+# clip list is in the glTF header. Nothing that ships may launch one again — it
+# is a 100MB download that fails behind a filtered CDN and buys numbers the
+# vertices already hold. The offline viewer is exempt: it is HTML the CUSTOMER
+# opens, and it never runs here.
+for root, dirs, files in os.walk(ROOT):
+ dirs[:] = [d for d in dirs if d not in ('node_modules', '.git', 'out', 'delivery')]
+ for fn in files:
+ if not fn.endswith(('.py', '.js', '.mjs', '.sh', '.ps1')):
+ continue
+ rel = os.path.relpath(os.path.join(root, fn), ROOT).replace(os.sep, '/')
+ if rel == 'harness/synccheck.py' or '/assets/' in rel:
+ continue
+ s = read(rel) or ''
+ for pat in (r"from 'playwright'", r'require\(.playwright', r'playwright install',
+ r'chromium\.launch', r'puppeteer'):
+ if re.search(pat, s):
+ bad.append(f'a browser came back: {rel} matches /{pat}/ — every measurement '
+ 'is arithmetic on the vertices; see harness/outline.py')
+
# ── 4. leak scan ─────────────────────────────────────────────────────────────
# Only GENERIC patterns ship. Site-specific words — the names of whatever else
# lives on the author's disk — must never be written here: a list of names you
@@ -368,4 +448,6 @@ if bad:
print(' - ' + b)
sys.exit(1)
print(f'[synccheck] OK — version {version}, {len(FEATURES)} promised features present, '
- f'{len(REQUIRED)} required files present, no leaked strings. Safe to ship.')
+ f'{len(REQUIRED)} required files present, '
+ + ('manifest in sync, ' if manifest_checked else '')
+ + 'no leaked strings. Safe to ship.')
diff --git a/setup.ps1 b/setup.ps1
index 2c73677..c36fc59 100644
--- a/setup.ps1
+++ b/setup.ps1
@@ -1,43 +1,18 @@
-# anyCreature one-command start (Windows PowerShell).
-# Same steps as setup.sh: deps -> browser -> calibration -> browser probe.
-$ErrorActionPreference = "Stop"
+# anyCreature one-command start (Windows).
+$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot
-npm install [email protected] [email protected] --no-fund --no-audit
-# Same rule as setup.sh: a download is the normal path, skipped only when
-# Playwright can already launch a browser (prebuilt images, warm CI caches).
-# No hunting for chrome.exe, no remembered path — PW_CHROMIUM_PATH is the only
-# pin, and whoever sets it owns it.
-if ($env:PW_CHROMIUM_PATH) {
- Write-Output "browser: pinned by PW_CHROMIUM_PATH"
-} else {
- node harness/pwprobe.mjs *> $null
- if ($LASTEXITCODE -eq 0) {
- Write-Output "browser: Playwright can already launch one, skipping the download"
- } else {
- # Same bound as setup.sh: a blocked CDN must fail in minutes, not tens of
- # them. A measured run lost ~minutes to an install that could never
- # finish, because nothing capped it.
- $limit = if ($env:PW_INSTALL_TIMEOUT) { [int]$env:PW_INSTALL_TIMEOUT } else { 420 }
- Write-Output "browser: downloading chromium (up to ${limit}s)…"
- $p = Start-Process -FilePath "npx" -ArgumentList "playwright","install","chromium" `
- -NoNewWindow -PassThru
- if (-not $p.WaitForExit($limit * 1000)) {
- try { $p.Kill($true) } catch {}
- $code = 124
- } else { $code = $p.ExitCode }
- if ($code -ne 0) {
- Write-Output ""
- Write-Output "browser download did not finish (exit $code)."
- Write-Output "If this machine cannot reach the Playwright CDN, point PW_CHROMIUM_PATH at a"
- Write-Output "Chromium or Chrome you already have and run setup.ps1 again:"
- Write-Output ' $env:PW_CHROMIUM_PATH="C:\path\to\chrome.exe"; .\setup.ps1'
- Write-Output 'A slow-but-working line just needs longer: $env:PW_INSTALL_TIMEOUT=1200'
- exit 1
- }
- }
-}
+
+# NO BROWSER. Until 1.3.2 this installed Playwright and downloaded a Chromium,
+# because the silhouettes, part shares and colour numbers were read back off a
+# rendered frame. None of them needed to be — see setup.sh for the long version.
+npm install [email protected] --no-fund --no-audit
+
pip install numpy pillow scipy -q
-python -c "import numpy, PIL, scipy.ndimage"
-python harness/calibrate.py
-node harness/pwprobe.mjs
-Write-Output "calibrate OK"
+python3 -c "import numpy, PIL, scipy.ndimage"
+if ($LASTEXITCODE -ne 0) { Write-Error "python deps missing"; exit 1 }
+
+New-Item -ItemType Directory -Force -Path out | Out-Null
+node engine/cli.js example/wolf.json out/_setup.glb | Out-Null
+python3 harness/outline.py out/_setup.glb out/_setup | Out-Null
+node harness/judge.mjs out/_setup.glb out/_setup _setup | Out-Null
+Write-Output "setup OK - engine builds, checks pass, measures compute. No browser required."
diff --git a/setup.sh b/setup.sh
index 5f5078b..e530840 100644
--- a/setup.sh
+++ b/setup.sh
@@ -1,57 +1,27 @@
#!/bin/bash
-# anyCreature one-command start: install deps → red/green ruler calibration
+# anyCreature one-command start.
set -e
cd "$(dirname "$0")"
-npm install [email protected] [email protected] --no-fund --no-audit
-# The npm package alone ships NO browser. Without a browser, setup prints
-# "calibrate OK" and then every render tool (silmetrics/hero/judge) dies at its
-# first launch on a fresh machine — so a download here is the normal path and
-# must stay the normal path.
-#
-# The one case worth skipping: Playwright can ALREADY launch. Some CI images and
-# prebuilt containers ship a browser cache, and there the installer runs, fails,
-# retries six times and gives up ~minutes later for nothing. Ask Playwright
-# itself — one probe, its own resolution, no guessing where a browser might be.
-# We do NOT go hunting for chrome on PATH and we do NOT remember a path in a
-# file: a pinned absolute path is how 1.2.0 broke every clone on macOS and
-# Windows, and re-deriving it automatically is the same bug wearing a hat. An
-# environment that needs a specific binary sets PW_CHROMIUM_PATH and owns it.
-if [ -n "$PW_CHROMIUM_PATH" ]; then
- echo "browser: pinned by PW_CHROMIUM_PATH"
-elif node harness/pwprobe.mjs >/dev/null 2>&1; then
- echo "browser: Playwright can already launch one, skipping the download"
-else
- # Nothing used to bound this. On a machine whose network blocks the Playwright
- # CDN the installer retries and retries: a build lost ~minutes here,
- # 21% of the whole build, to a download that was never going to complete. The
- # 1.3.1 fix above only covers "a browser already works, don't download" — it
- # said nothing about how long failing is allowed to take.
- #
- # A watchdog rather than `timeout`: timeout(1) is GNU coreutils and is NOT on
- # a stock macOS (there it is `gtimeout`, if it is there at all). Reaching for
- # it would be the same mistake as pinning a browser path — works here, breaks
- # on someone else's machine.
- echo "browser: downloading chromium (up to ${PW_INSTALL_TIMEOUT:-420}s)…"
- npx playwright install chromium & PW_PID=$!
- ( sleep "${PW_INSTALL_TIMEOUT:-420}"; kill -TERM "$PW_PID" 2>/dev/null ) & PW_WD=$!
- wait "$PW_PID"; PW_RC=$?
- kill -TERM "$PW_WD" 2>/dev/null
- if [ "$PW_RC" -ne 0 ]; then
- echo ""
- echo "browser download did not finish (exit $PW_RC)."
- echo "If this machine cannot reach the Playwright CDN, point PW_CHROMIUM_PATH at a"
- echo "Chromium or Chrome you already have and run setup.sh again:"
- echo " PW_CHROMIUM_PATH=/path/to/chromium bash setup.sh"
- echo "A slow-but-working line just needs longer: PW_INSTALL_TIMEOUT=1200 bash setup.sh"
- exit 1
- fi
-fi
-# scipy is NOT optional: harness/maskmetrics.py imports scipy.ndimage. Leaving it
-# out let setup print "calibrate OK" and then blow up mid-LOW on the first measure.
+
+# NO BROWSER. Until 1.3.2 this script installed Playwright and downloaded a
+# Chromium, because the silhouettes, the part shares and the colour numbers were
+# all read back off a rendered frame. None of them needed to be: a silhouette is
+# a projection, occlusion is a z-buffer, and the baked colour IS the albedo. All
+# of it moved into harness/outline.py, so the browser — and the install failures
+# a blocked CDN used to cause — is gone. The offline viewer that ships with a
+# delivery is HTML the customer opens themselves; nothing here launches one.
+npm install [email protected] --no-fund --no-audit
+
+# Python does every measurement. scipy is NOT optional: protrusions, thinnest
+# feature, convexity and mirror symmetry come from it, and without it those
+# gates have nothing to read — so every build would pass them by default.
pip install numpy pillow scipy --break-system-packages -q 2>/dev/null || pip install numpy pillow scipy -q
python3 -c "import numpy, PIL, scipy.ndimage" || { echo "python deps missing"; exit 1; }
-python3 harness/calibrate.py
-# probe an actual browser launch NOW — a missing/broken browser must fail setup
-# loudly here, not mid-LOW on the first silhouette
-node harness/pwprobe.mjs
-echo "calibrate OK"
+
+# Prove the whole chain on the shipped example before a line is authored: the
+# engine builds it, the checks pass it, and the measures compute on the result.
+mkdir -p out
+node engine/cli.js example/wolf.json out/_setup.glb >/dev/null
+python3 harness/outline.py out/_setup.glb out/_setup >/dev/null
+node harness/judge.mjs out/_setup.glb out/_setup _setup >/dev/null
+echo "setup OK — engine builds, checks pass, measures compute. No browser required."