Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.
Python 3dai-agentsclaude-codecomputer-graphicsgenerativeimage-to-3dprocedural-generationthreejstypescriptwebgl
Release v1.5.1 — The Character Update, plus the region and swept-arc gates (#98)
Hoài Nhớdede5909be4e
diff --git a/.gitignore b/.gitignoreindex 9d72418..729a22a 100644--- a/.gitignore+++ b/.gitignore@@ -55,3 +55,17 @@ docs/research/# session, never inputs to a build, and they carry multi-megabyte PNGs. Tuning ships with the# stable release, not with a beta of the scripts.work/++# Per-subject authoring prompts. Same class as work/ -- one subject's brief, never an input to a+# build, and no script reads them.+docs/prompts/++# Session postmortems. Provenance for a decision, kept locally like docs/research/; the operational+# rule each one produced already lives in grimoire/ or docs/.+.sisyphus/++# Handover and distillation notes. Same rule as docs/PLAN_*.md above: feature work is committed,+# planning and review-of-other-branches notes are not. These also carry absolute local paths and+# session ids, which must never reach the public skill.+docs/WS_*_HANDOVER_*.md+docs/PR_DISTILLED.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex eade046..fc43033 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,17 +5,160 @@ All notable changes to **img2threejs** are documented here.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).-## [1.4.4-beta.2]+## [1.5.1] — 2026-08-22### Added++- Add code-only skin and cloth material profiles with validation for engine clamps, folded+ uniforms, and sheen configuration.+- Label multipart GLB nodes from measured bounds while keeping semantic assignments explicitly+ provisional until render confirmation.+- Add executed-geometry gates for flat-colour vertex regions and swept-arc bend, span, and taper,+ plus required semantic-region declarations in render-profile v2.++### Fixed++- Deduplicate `SKILL.md` into one continuous reconstruction loop so every host loads one canonical+ sequence of gates.+- Bound all three axes in the SDF quad pass, preventing out-of-range and aliased cell reads at the+ sampling-grid boundary.++## [1.5.0] — 2026-08-12++**Theme: The Character Update.** A character stops being a stylized approximation. A skeleton is+derived from the component tree and bound to real `SkinnedMesh` geometry, hair gets its own+subsystem spanning all five stages, and left/right becomes an importable constant instead of a+comment. Every gate added here traces to a regression that was measured, not imagined.++This release supersedes the unreleased `1.4.4-beta.1`/`1.4.4-beta.2` line and the `v1.5-beta` tags.+`1.4.4` was never published as a stable version.++### Added++**Animation-ready rigs — new `forge/stage5_rig/`**+- Derive a validated `RigSpec` from the component tree rather than authoring a skeleton beside it,+ so the bones cannot drift from the geometry they drive. A generated humanoid is 61 components and+ 49 bones (pelvis, 3 spine, 2 clavicle, 8 arm, 6 leg, head, neck, 30 digit phalanges).+- Emit the bone hierarchy parents-first, one shared `THREE.Skeleton`, exactly one vertex-weight+ helper, and bind every skinned component as a `THREE.SkinnedMesh`. `root.userData.rig` reports+ `bound` honestly rather than asserting it. Enforced: `|Σw − 1| < 1e-5`, every `skinIndex` in+ range, no zero-weight-sum vertex, bone lookup through a `Map`.+- `root.updateMatrixWorld(true)` before constructing the `Skeleton`, because `calculateInverses()`+ reads each bone's current world matrix and those inverses are what cancel the rest pose. Built in+ the wrong order it captures identity matrices and every vertex is displaced by its bone's offset+ at rest — measured, not assumed.+- Add `forge/stage5_rig/geodesic_skinning.py`: weights from distance measured *through the solid*+ on a voxel grid with 26-connectivity and true step lengths, so falloff does not bias along grid+ axes. A vertex no bone can reach is reported, never quietly pinned to the nearest bone in space.+- Add `forge/stage5_rig/validate_rig_payload.py`, which proves structural payload integrity only.+ Pose stress, dynamic bounds and visual likeness remain separate gates, and this is stated rather+ than implied.+- Add canonical humanoid proportions (`forge/stage2_spec/humanoid_proportions.py`) and reachable+ character sub-routes.++**Hair — a subsystem spanning all five stages**+- Replace the single `ellipsoid` that was the entirety of hair generation. Full contract, every+ measurement behind it, and every stated non-goal: `docs/HAIR_PIPELINE.md`.+- Add `forge/_shared/scalp_field.py`: signed distance to a skull built as a stack of ellipse rings,+ derived from the head component rather than authored twice. The sign is exact; the magnitude is a+ first-order estimate that errs toward pushing further, which is the safe direction.+- Add `forge/stage1_intake/extract_hair_evidence.py`, which finally writes the+ `faceLandmarks.hairline` slot that has existed unfilled since v1.2, and measures banded coverage,+ highlight-band position and root-to-tip luminance delta. Views never seen are reported as+ `notObserved` instead of authored as if measured.+- Add `forge/stage2_spec/hair_profile.py`: the hairstyle schema and its validation. Roots bind to+ the scalp as `(u, v)`; an absolute root position is a hard error, which makes the recorded+ "mass slides off the skull" failure structurally impossible rather than a matter of care.+- Add `standProud` as a component property, enforced by an emitted per-vertex clearance march+ (`applyStandProud`). This generalises `hug` out of the hand-written showcase demo and into the+ skill. `maxPush` is required, not optional: an uncapped march walks inner vertices through the+ target and out the far side.+- Add `forge/stage4_review/scalp_exposure.py`, a HARD gate that finds bald patches geometrically+ before anything is rendered. Silhouette IoU is blind to them (only ~11% of figure cells lie on the+ outline) and interior difference cannot separate them from a colour shift. It counts only hair+ *outside* the skull — a nearest-neighbour test passes the failing build, because those vertices+ were still nearby, merely sunk below the surface.+- Add `forge/stage4_review/hair_gate.py`, separating hard failures (a bald patch, always wrong) from+ soft signals (a coverage shortfall, often the right compromise) so the two stop being answered the+ same way. A shortfall never authorises widening the masses on its own.+- Add a `hair.human.code-only` material profile requiring no maps, and a `rootTipGradient` vertex+ colour ramp that runs along the mass's own axis rather than world Y.++**Left and right**+- Add `forge/_shared/chirality.py`. `CHARACTER_LEFT_SIGN` is derived, not chosen: with `forward: +Z`,+ Y up and a right-handed frame, the character's own left is `+X`. It is a constant because a comment+ cannot be imported and two checkouts had already diverged on it.+- `validate_chirality` is a hard spec-time gate naming the actual relation between a pair+ (`rotation` / `translation` / `unrelated`) instead of reporting "mismatch". A pair built by negating+ x *and* z is a 180° rotation, and rotation preserves handedness, so both limbs come out the same+ hand. Fixing that moved the humanoid's hand region 46% closer to the reference in front.+- `chirality.medial_lateral_bias` catches what a pair test structurally cannot: a pair that is wrong+ the *same* way on both sides is still a perfect mirror of itself. Threshold `0.025` is calibrated+ against measured reference feet (`+0.0403`, `+0.0579`) — the first guess of `0.05` would have made+ the gate blind to the defect it was written for.++**Review gates**+- Add `forge/stage4_review/interior_difference.py`: appearance difference *inside* the silhouette,+ banded by height, and required per visual pass. Silhouette IoU reads ~11% of figure cells, so a+ finished face and the same model with its face deleted both scored `0.8803`, and adding an entire+ mouth moved it `-0.0002` — in the wrong direction. An outline metric must not be the signal a+ correction loop optimises for interior work.+- Add the Divine Eye fitting loop (`forge/stage4_review/fit_params.py`), connecting deterministic+ parameter-to-render callbacks to bounded, gate-aware optimisation with explicit provenance.+- Add per-feature correction, self-intersection, turntable, attachment-anchor, joint-loop,+ pairwise-penetration and geometry-integrity gates.+- Add the Python ↔ Three.js render bridge and render profile v2, with capture-readback validation.+- Add `forge/stage4_review/compare_region_passes.py`, which blocks per-region claims that paired+ browser diagnostic passes do not support.++**Material pipeline**+- Add region crop admission, PBR extraction and registry resolution+ (`material_region_analysis.py`, `forge/materials/reference.py`), the spec hand-off+ (`apply_material_analysis.py`), the deterministic camera/crop/microscope plan (`material_views.py`),+ the per-region comparator, bounded material feedback, cross-pass compatibility, and a blocking+ `material_gate.py`. The registry never decides from colour alone; an ambiguous or low-confidence+ region stays `probe`/`request-input`.++**Build**+- Add the `tapered-sweep` primitive: `rx`/`rz` vary per station and framing uses parallel transport,+ because `extrudePath`'s Frenet frames flip 180° at an inflection. Nothing that came to a point+ could be built before, so hair locks, horns and tails were assembled from constant-radius pieces+ that read as noodles. The validator warns when stations do not actually taper.+- Add SDF primitives and subdivision surfaces capped to tessellation tiers, UV unwrap, visual-hull+ carving, morph targets and quadric decimation.++**Intake**+- Add the camera-fitting solver, `probe_glb.py` (provenance, bounds, scene inventory and a+ conservative semantic-readiness assessment), and semantic decomposition.+- Add optional isolated SAM2 / MediaPipe / Depth Anything V2 evidence adapters+ (`run_vision_adapter.py`). They never approve a pass and never supply geometry.+- Add a pure-stdlib baseline JPEG decoder with an explicit fallback for unsupported+ progressive/12-bit/CMYK modes, removing the macOS-only `sips` dependency for common inputs.++**Workflow**- Add a repository-local mandatory workflow checklist, resume gate, and evidence-backed step- tracking under `.img2threejs/state.json`.-- Add per-pass and total correction ceilings derived from `reviewHistory`; `forge/next.py` now- hard-stops when either limit is reached.+ tracking under `.img2threejs/state.json`, with `generic`, `character` and `cs2` profiles inserting+ their required intake gates in order.+- Add per-pass and total correction ceilings derived from `reviewHistory`; `forge/next.py` hard-stops+ when either limit is reached.+- Add fail-closed pipeline routing (`forge/_shared/pipeline_routing.py`): below a confidence of+ `0.82` the track resolves to `request-input` rather than guessing between weapon and character.- Add an executable CS2 review CLI and profile-specific CS2/character checklist gates.- Add explicit suitability, projection-route, and material-evidence decisions to every profile.### Changed+- Resolve the hair strategy question open since v1.2. `plane-card` is rejected for hair: it needs an+ alpha texture this skill cannot emit. The default representation tier is `shell`, not locks —+ measured on the reference GLB, hair surface roughness is 0.00338 against a torso control of+ 0.00312, so its hair is a smooth shell with all strand detail in textures. `tube` and `box` are+ rejected for hair as well.+- Exclude `hair`, `detail`, `decal` and `panel` roles from geodesic skinning. The field measures+ distance through the solid, so on the test fixture a crown vertex takes 8.1% neck weight through+ the skull and shears against it under rotation. Rigid components are excluded from the returned+ weights, not merely noted beside them.+- Give the primitive list one owner. `generate_threejs_factory.py` kept its own copy of+ `VALID_PRIMITIVES`; a primitive present in one list and absent from the other did not error, it+ was silently rewritten to `box`.- Keep progressive-disclosure references while making CS2 intake, deterministic review gates,self-correction, multi-angle review, part coverage, and action-ready validation explicit routerrequirements.@@ -23,6 +166,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0AI review, and sync.- Make regeneration action-aware so `refine-code` cannot overwrite the artifact it must repair,and reject spec paths that disagree with local state.+- Make the material aliases, CS2 vocabularies and spec-search examples English-only; the dataset+ vocabulary stays bilingual by design.+- Resolve the companion showcase through `IMG2THREEJS_SHOWCASE_ROOT` instead of an absolute path, and+ remove machine-specific paths from the shipped skill. Research distillations stay local.++### Fixed+- Let a `tapered-sweep` station collapse to a real point. A ring of radius zero still carried+ coincident vertices and zero-area triangles, so a sweep ended in a blunt cap the width of+ floating-point noise — and the taper warning would have passed it.+- Resolve the instanced-cluster base primitive through the shared subdivision helper, so emitted+ helpers and geometry calls cannot drift at that seam.+- Read the version front-matter key the release tooling actually writes.+- Score an empty IoU/edge union as `0`, not `1`, and treat inverted or tiny foreground masks as+ unusable evidence rather than a perfect match.++### Known limits at this release+Stated because a schema reads exactly like a working feature:+- There is no `hairProfile` → `componentTree` compiler. The schema is validated; a spec still authors+ its hair components directly.+- `scalp_exposure` measures spec-derived points while the clearance march displaces vertices at+ runtime, so the gate does not measure the geometry that ships. Moving the march into Python at+ build time is the largest improvement still available in that subsystem.+- Lock-tier hair parameters and every hair gate threshold are derived, not measured, and report+ themselves as such. No multipart GLB with separated hair geometry exists to calibrate against.+- `BoneSpec.ik` exists in the schema and nothing populates it. Pose-sweep gating is not implemented.+- Hair dynamics and strand-level hair are permanently out of scope: a single image carries no motion,+ and this pipeline emits no textures or alpha.## [1.4.3] — 2026-07-30@@ -224,6 +394,8 @@ and harness improvements to the underlying code generator.- Action-ready runtime hierarchy exposing pivots, sockets, and colliders.- Token-efficient, code-only output (diffable TypeScript + JSON spec, no binaries).+[1.5.1]: https://github.com/img2threejs/img2threejs/compare/v1.5.0...v1.5.1+[1.5.0]: https://github.com/img2threejs/img2threejs/compare/v1.4.3...v1.5.0[1.4.1]: https://github.com/hoainho/img2threejs/compare/v1.4.0...4e9fbecae0e63b370581737c89991d4dca84c287[1.4.0]: https://github.com/hoainho/img2threejs/releases/tag/v1.4.0[1.3.0]: https://github.com/hoainho/img2threejs/releases/tag/v1.3diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 658c355..1118373 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -21,11 +21,17 @@ quality-gated Three.js model. Contributions that keep that identity sharp are vePlease do not add code that silently downloads meshes or art packs — the core promise isreconstruction by code. If you want a projection or generative-assist path, propose it as an-explicit, flagged, opt-in mode.+explicit, flagged, opt-in mode. `integrations/glb_character_pipeline/` is one such mode: a GLB-baseline+character reconstruction pipeline (SDF point-cloud splat + Surface Nets) that runs against a companion+showcase checkout via `IMG2THREEJS_SHOWCASE_ROOT`, isolated behind its own `pyproject.toml`/`uv.lock`+and `node/package.json` so the `forge` core stays dependency-free. It only applies when a character+build actually has a GLB reference to measure — skip it entirely otherwise. See its `README.md`.## Development-- Scripts are pure Python 3.10+ standard library. No pip dependencies.+- Scripts under `forge/` are pure Python 3.10+ standard library. No pip dependencies there. Optional+ integrations under `integrations/<name>/` may declare their own pip/npm dependencies in their own+ `pyproject.toml`/`package.json`, isolated from the core.- Run the test suite from the skill root: `python3 -m unittest discover -s forge/tests -p 'test_*.py'`.Set `IMG2THREEJS_SHOWCASE_ROOT` to a showcase checkout to include the TypeScript typecheck gates;without it they skip, so a green run has not proven the emitted Three.js compiles.diff --git a/README.md b/README.mdindex 7e1c823..4150471 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@Quality-gated, animation-ready, and deliberately token-efficient — reconstruction-by-code, not photogrammetry, mesh extraction, or downloaded art packs.[](LICENSE)-[](CHANGELOG.md)+[](CHANGELOG.md)[](CONTRIBUTING.md)[](https://threejs.org)[](forge)@@ -49,18 +49,28 @@ Every model in the gallery is generated code, running in your browser. No mesh fReconstructions built entirely from primitives, procedural shaders, and generated geometry. Open any model to orbit it, inspect its reference, and read the generated source.-| Demo | Subject | View | Source |-| --- | --- | --- | --- |-| Glock-18 · Ghost Protocol (Well-Worn) | CS2 weapon | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/glock-ghost-protocol) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/glock-ghost-protocol/createGlockGhostProtocolModel.ts) |-| Classic Knife · Fade (Minimal Wear) | CS2 weapon | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/classic-fade) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/classic-fade/createClassicFadeModel.ts) |-| BMX Endurance Bike | hard-surface object | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/bmx-endurance) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/bmx-endurance/createBmxEnduranceBikeModel.ts) |-| M9 Bayonet · Doppler Phase 2 | CS2 weapon | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/m9-doppler) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/m9-doppler/createM9DopplerModel.ts) |-| Sony WF-1000XM3 Earbuds + Case | hard-surface object | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/sony-wf1000xm3) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/sony-wf1000xm3/createSonyWf1000xm3Model.ts) |-| ISSACA 12 Gauge Shotgun | hard-surface object | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/issaca-shotgun) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/issaca-shotgun/createIssacaShotgunModel.ts) |-| Gerber Paracord Knife | hard-surface object | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/gerber-knife) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/gerber-knife/createGerberKnifeModel.ts) |-| Doraemon House (isometric diorama) | diorama | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/doraemon-house) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/doraemon-house/createDoraemonHouseModel.ts) |-| War-Hauler "SECTOR 07" | hard-surface object | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/warhauler) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/warhauler/createWarHaulerModel.ts) |-| Crowned Loot Chest | hard-surface object | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/crown-chest) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/crown-chest/createCrownChestModel.ts) |+| Demo | Subject | Built with | View | Source |+| --- | --- | --- | --- | --- |+| Dual-Sword Warrior — TypeScript procedural surfaces ⚠︎ | character | `v1.5.1` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/girl-character) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/girl-character/createGirlCharacterModel.ts) |+| Low-Poly Humanoid — Rigged Character ⚠︎ | character | `v1.5.0` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/low-poly-humanoid) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/low-poly-humanoid/createLowPolyHumanoidModel.ts) |+| ★ Talon Knife \| Doppler Ruby (Factory New) | object | `v1.4.4` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/talon-doppler-ruby) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/talon-doppler-ruby/createTalonDopplerRubyModel.ts) |+| AWP \| Medusa (Minimal Wear) · V2 rebuild | object | `V2` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/awp-medusa-v2) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/awp-medusa-v2/createAwpMedusaModelV2.ts) |+| Pikachu 10K Star Celebration ⚠︎ | character | `v1.5-beta` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/electric-mouse-mascot) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/electric-mouse-mascot/createElectricMouseMascotModel.ts) |+| Glock-18 \| Ghost Protocol (Well-Worn) | object | `v1.4.1` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/glock-ghost-protocol) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/glock-ghost-protocol/createGlockGhostProtocolModel.ts) |+| Classic Knife \| Fade (Minimal Wear) | object | `v1.3` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/classic-fade) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/classic-fade/createClassicFadeModel.ts) |+| BMX Endurance Bike | object | `v1.3` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/bmx-endurance) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/bmx-endurance/createBmxEnduranceBikeModel.ts) |+| M9 Bayonet \| Doppler Phase 2 | object | `v1.3` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/m9-doppler) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/m9-doppler/createM9DopplerModel.ts) |+| Sony WF-1000XM3 Earbuds + Case | object | `v1.2` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/sony-wf1000xm3) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/sony-wf1000xm3/createSonyWf1000xm3Model.ts) |+| ISSACA 12 Gauge Shotgun | object | `v1.2` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/issaca-shotgun) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/issaca-shotgun/createIssacaShotgunModel.ts) |+| Gerber Paracord Knife | object | `v1.2` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/gerber-knife) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/gerber-knife/createGerberKnifeModel.ts) |+| Doraemon House (isometric diorama) | object | `v1.2` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/doraemon-house) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/doraemon-house/createDoraemonHouseModel.ts) |+| War-Hauler "SECTOR 07" | object | `v1.2` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/warhauler) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/warhauler/createWarHaulerModel.ts) |+| Crowned Loot Chest ⚠︎ | object | `v1.2` | [Live](https://img2threejs.github.io/img2threejs-showcase/#/demo/crown-chest) | [code](https://github.com/img2threejs/img2threejs-showcase/blob/main/src/demos/crown-chest/createCrownChestModel.ts) |++⚠︎ marks a demo whose registry `status` is still `placeholder` rather than `final` — it renders, but it+is not finished work. The **Built with** column is the version each demo's own registry entry records in+`generatedWith`, not an inference from dates; `awp-medusa-v2` records `V2`, which is that demo's rebuild+pass rather than a release number. Rows are ordered newest first by the commit that added the demo.The gallery source lives in [img2threejs/img2threejs-showcase](https://github.com/img2threejs/img2threejs-showcase). If this project is useful, a star on this repo helps others find it.@@ -169,6 +179,30 @@ The factory generator repeats the strict-quality gate and is fail-closed: on fai`BLOCKED` with the spec artifact, failure metrics, causes, and next action, and does not write afactory. `--allow-nonstrict` is only for explicit legacy test fixtures, never production output.+### Copy-paste prompts for the GLB-reference route++Rebuilding a character from a **GLB reference** rather than a photo is a different route with its own+gates — the GLB is a measurement instrument and never ships. Three prompts cover it, each in its own+copy block:++| Prompt | Use it when | Do not use it when |+|---|---|---|+| [Build](docs/GLB_CHARACTER_PROMPT.md) | you have a GLB and no built surfaces yet | there is no GLB, or the build already completed and merely looks wrong |+| [Polish](docs/GLB_CHARACTER_POLISH_PROMPT.md) | the build completed and the result does not look like the GLB | the surfaces were never built — that is a build re-run, not a polish |+| [Animation](docs/GLB_CHARACTER_ANIMATION_PROMPT.md) | the figure looks right standing still and has passed the build gates | the surface is ungated, or `joint_loops.py` fails — that is a surface finding no weight tuning reaches |++They force every parameter the GLB genuinely carries — size, proportions, per-band widths and+centroids, base colour, roughness and metalness — to the measured value, with the check that proves+it landed. Three things are **not** 1:1 and each prompt says so: rigging and animation are usually+absent from the asset (`skinCount: 0`, `animationCount: 0`), texture images and normal maps are+deliberately not copied per this skill's code-only contract, and nothing finer than the node's cell+size can be carried at all.++**These are reference material, not a guarantee.** They are written to be general, so the measured+figures in them came from one character and are there to show what to measure — not values to copy.+Run the one that matches your situation rather than all three in sequence; each notes the cost of+being used out of turn.+For the script-by-script reference, the full scripts table, and expected artifacts, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).---@@ -215,7 +249,17 @@ The net effect: you still get a faithful 3D model from an image, but the expensi| `stage1_intake/delight_albedo.py` | Approximate a neutral albedo from the photo before texture projection. || `stage3_build/bake_projected_texture.py` | Emit a projection/UV-bake descriptor for photo-texture projection. |-The `grimoire/` folder holds the detailed rubrics each gate applies (validation, pre-spec assessment, procedural patterns, material and lighting realism, attachment correctness, action-ready models, self-correction).+| `stage5_rig/rig_spec.py` | Derive and validate a skeleton from the component tree, so bones cannot drift from the geometry. |+| `stage5_rig/geodesic_skinning.py` | Vertex weights from distance measured through the solid; keeps rigid roles out of smooth skinning. |+| `stage5_rig/validate_rig_payload.py` | Blocking payload-integrity gate before a `THREE.Skeleton` is bound. |+| `stage1_intake/extract_hair_evidence.py` | Hair/skin split, banded coverage, hairline, highlight band, root-to-tip delta. |+| `stage4_review/scalp_exposure.py` | HARD gate: finds bald patches on geometry, before any render. |+| `stage4_review/hair_gate.py` | Soft gate: hair coverage, hairline and highlight offsets against the reference. |+| `stage4_review/interior_difference.py` | Appearance difference inside the silhouette, banded by height. Required per visual pass. |+| `_shared/chirality.py` | Left/right as an importable convention, with the two gates the two chirality defects need. |+| `_shared/pipeline_routing.py` | Fail-closed weapon/character routing; low confidence resolves to `request-input`. |++This is a curated selection — `forge/` holds around ninety modules. The executable reference with every flag is [`grimoire/scripts.md`](grimoire/scripts.md), and the gate-by-gate contract is [`grimoire/review/gates_reference.md`](grimoire/review/gates_reference.md). The rest of `grimoire/` holds the rubrics each gate applies (validation, pre-spec assessment, procedural patterns, material and lighting realism, attachment correctness, action-ready models, self-correction).### Optional reference-fidelity tooling@@ -226,12 +270,26 @@ version-aware Context7 retrieval. These tools never approve a pass or silently pInstall, routing, provenance rules and exact commands:[`docs/integrations/reference_fidelity_tooling.md`](docs/integrations/reference_fidelity_tooling.md).+### Optional GLB-baseline character pipeline++[`integrations/glb_character_pipeline`](integrations/glb_character_pipeline) reconstructs a character+from a **multipart GLB used as a measurement instrument plus its diffuse image**, and emits the+procedural TypeScript the demo actually ships — no `.glb` or `.bin` is fetched at runtime. It carries+its own `pyproject.toml`/`uv.lock` so the stdlib-only `forge` core stays dependency-free, and operates+on a companion showcase checkout via `IMG2THREEJS_SHOWCASE_ROOT`.++It applies **only** when a build has a GLB to measure — skip it entirely otherwise, and use the core+image-driven pipeline instead. Reproduces `girl-character`'s shipped `crossSections.ts` exactly (748+rings, 86,240 ring points). Method and per-stage rationale:+[`PIPELINE.md`](integrations/glb_character_pipeline/PIPELINE.md).+---## What you get- An `ObjectSculptSpec` JSON: the full component tree, materials, repetition systems, sockets, and a recorded review history for every pass.- A TypeScript `createObjectNameModel(spec, options)` factory returning a `THREE.Group`, with `root.userData.sculptRuntime` exposing nodes, sockets, colliders, and destruction groups.+- For character builds, `root.userData.rig`: bones, one shared `Skeleton`, bone order and index map, and a `bound` flag computed from whether every skinned mesh actually bound.- A render plus comparison sheets documenting the fidelity at each pass.For the script-by-script reference and the full list of output artifacts, see [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).@@ -248,10 +306,9 @@ For the script-by-script reference and the full list of output artifacts, see [d- **v1.4 — The Weapon Update** — CS2 image-matched reconstruction: provenance-aware intake, projection-first finishes, family-specific weapon adapters, and structural review gates.- **v1.4.1** — CS2 hardening: explicit component coverage, a dedicated Glock-18 assembly contract, map-stripped blockout evidence, and stricter geometry-integrity checks.- **creature generator** — 4 body plans (quadruped / avian / winged-dragon / serpentine), `animalAnatomy` spec, spine-loft geometry, ΔE00 colour gates.+- **v1.5 — The Character Update** — a skeleton derived from the component tree and bound to `SkinnedMesh` geometry, geodesic skinning, hair as a five-stage subsystem with a hard scalp-exposure gate, chirality gates, interior-difference review, the `tapered-sweep` primitive, the material pipeline with a blocking acceptance gate, and resumable workflow state. Not included: the `hairProfile` compiler, IK, pose-sweep gating, clothing.**Next — one theme per release:**--- **v1.5 — The Character Update** *(in progress)*: character reconstruction, facial features, rigging-ready topology, blendshape preparation, hair and clothing.- **v1.6 — The Environment Update**: buildings, rooms, streets, vegetation, terrain-aware and multi-object reconstruction.- **v1.7 — The Game Pipeline Update**: Unity and Unreal exporters, a Blender bridge, LOD and collision-mesh generation.- **v1.8 — The Animation Update**: auto rigging, auto skin weights, Mixamo compatibility, facial rig.diff --git a/ROADMAP.md b/ROADMAP.mdindex 0de488e..226e93d 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -16,6 +16,7 @@ can plan around.| v1.2 | Humanoid character generator | 2026-07-21 | Character/hybrid domain detection, anatomy-aware track, proportion-lock and feature-placement gated passes, per-part character materials || v1.3 | Quality & efficiency (Divine Eye) | 2026-07-22 | Deterministic multi-signal review harness, input-integrity and geometry-truth gates, reference-grounded texture/material analysis, CIEDE2000 colour math || v1.4 | Weapon Pipeline | 2026-07-25–26 | CS2 image-matched reconstruction, provenance-aware intake and local search, projection-first finishes, family-specific adapters, structural review and component-coverage gates |+| v1.5 | The Character Update | 2026-08-12 | Skeleton derived from the component tree and bound to `SkinnedMesh` geometry, geodesic skinning, hair as a five-stage subsystem with a hard scalp-exposure gate, chirality gates, interior-difference review, `tapered-sweep`, material pipeline with a blocking acceptance gate, resumable workflow state |### v1.2 — Humanoid character generator@@ -78,7 +79,7 @@ judgment is spent only where a script cannot decide.| v1.2 | Humanoid character generator | Shipped | Character/hybrid domain detection, anatomy and facial landmarks, proportion-lock and feature-placement build passes, per-part character materials || v1.3 | Quality & efficiency (Divine Eye) | Shipped | Deterministic review harness, input-integrity and geometry-truth gates, projection-first texture/material analysis, CIEDE2000 colour math || v1.4 | Weapon Pipeline | Shipped | CS2 image-matched reconstruction, provenance-aware intake, projection-first finishes, family-specific adapters, structural and component-coverage gates |-| **v1.5** | Character Pipeline | Start supporting characters properly | Character reconstruction · facial features · rigging-ready topology · blendshape preparation · hair & clothing improvements |+| v1.5 | Character Pipeline | Shipped | Component-derived skeleton bound to `SkinnedMesh` geometry · geodesic skinning · hair subsystem across all five stages · chirality gates · interior-difference review · `tapered-sweep` · material pipeline · resumable workflow state. Not shipped: `hairProfile` compiler, IK, pose-sweep gating, clothing || **v1.6** | Environment Pipeline | Build scenes, not just objects | Buildings · rooms · streets · trees & vegetation · terrain-aware generation · multi-object reconstruction || **v1.7** | Game Pipeline | Game-ready assets | Unity exporter · Unreal exporter · Blender bridge · FBX / OBJ / glTF improvements · LOD generation · collision mesh generation || **v1.8** | Animation Pipeline | Move assets into production | Auto rigging · auto skin weights · Mixamo compatibility · facial rig · lip-sync preparation · animation-ready exports |@@ -112,15 +113,26 @@ on the strength of a projected texture alone.### v1.5 — The Character Update-Characters become a first-class subject rather than a stylized approximation. Facial features get-dedicated treatment, and the output topology is built to be rigged: clean, predictable loops that-deform without artifacts, plus blendshape preparation so expression work has somewhere to attach.-Hair and clothing — the two things that most often break a code-built character — get their own-material and geometry improvements. Optional local SAM2 masks, MediaPipe face/pose landmarks and-Depth Anything V2 relative-depth priors feed provenance-backed evidence into intake without changing-the zero-dependency core or gaining authority over geometry and review gates. The local v1.5 line-also records resumable, evidence-backed workflow state so character intake and correction loops can-continue across agents without turning state into a pass bypass.+*Shipped 2026-08-12.*++Characters became a first-class subject rather than a stylized approximation. A skeleton is derived+from the component tree — never authored beside it — and bound to real `SkinnedMesh` geometry through+one shared `Skeleton` and exactly one weight helper, with weights from geodesic distance measured+through the solid. Hair got its own subsystem across all five stages, gated before its generators+were written, because the failure it exists to prevent had already shipped four wrong fixes. Left and+right became an importable constant with two different gates, because a rotated limb pair and a pair+wrong the same way on both sides are different defects. Review learned to measure inside the+silhouette, after an outline metric scored a deleted face identically to a finished one. Optional+local SAM2 masks, MediaPipe face/pose landmarks and Depth Anything V2 relative-depth priors feed+provenance-backed evidence into intake without changing the zero-dependency core or gaining authority+over geometry and review gates. Resumable, evidence-backed workflow state lets character intake and+correction loops continue across agents without turning state into a pass bypass.++**Not shipped in v1.5**, and tracked rather than implied: the `hairProfile` → `componentTree`+compiler, IK (`BoneSpec.ik` exists and nothing populates it), pose-sweep gating, blendshape-driven+expression work beyond the morph-target emitter, and clothing. Hair dynamics and strand-level hair+are out of scope permanently — a single image carries no motion, and this pipeline emits no textures+or alpha.### v1.6 — The Environment Update@@ -184,7 +196,7 @@ latent bug.|---|---|---|---|| G1 | SkinnedMesh + Bones + Morph targets (organic deform, facial expression) | Roadmap **v1.8 — Animation** (rig-ready topology prepared in v1.5) | deferred || G2 | glTF / GLB export + AnimationMixer (engine portability) | Roadmap **v1.7 — Game Pipeline** | deferred |-| G3 | **InstancedMesh — real latent bug**: `instanced-cluster` in `VALID_PRIMITIVES` has no `geometry_for()` branch; repetition systems emit a hand-rolled `Mesh` clone loop, not `InstancedMesh` (`generate_threejs_factory.py:1091-1146`) | **Hotfix in progress** | high |+| G3 | ~~**InstancedMesh — real latent bug**: `instanced-cluster` has no `geometry_for()` branch; repetition systems emit a hand-rolled `Mesh` clone loop~~ | **Closed.** `geometry_for()` resolves the cluster's base primitive and the repetition emitter builds `new THREE.InstancedMesh(geo, mat, count)`; `test_repetition_system_scale.py` verifies placement by reading matrices back through `InstancedMesh.getMatrixAt` composed with `cluster.matrixWorld`, not by matching source strings | — || G4 | UV unwrapping / atlas, normal+AO baking (high→low), LOD, BVH; procedural-UV seams stretch at primitive joins | Partial today (procedural cyl/triplanar UV + height→normal). Baking and LOD land in **v1.7** | med || G5 | WebGPURenderer + TSL node materials | Deferred — architecture, not render quality | low || G6 | Topology / retopology / CSG boolean-merge (clean welded mesh for skinning) | Feeds **v1.5** rigging-ready topology; `three-bvh-csg` is for export/skinning, not static-prop quality | low |diff --git a/SKILL.md b/SKILL.mdindex 3075c34..55aa909 100644--- a/SKILL.md+++ b/SKILL.md@@ -2,7 +2,7 @@name: img2threejsdescription: Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.license: Apache-2.0-version: 1.4.4+version: 1.5.1---# img2threejs — Image to procedural Three.js@@ -15,6 +15,10 @@ Agent-agnostic: works under Claude Code, Codex, or OpenCode. Wherever this doc svision" or "agent browser tool", use whatever the host provides — native image reading, abrowser MCP (playwright/chrome-devtools), the project preview, or a user-supplied screenshot.+This file is the always-loaded router: it holds the order of operations and every hard rule as one+line. The full contract behind each rule lives in the `grimoire/` or `docs/` file that rule names —+read the named file at the moment you reach that stage, not before.+## Canonical shared checkoutKeep one checkout of this repository and let every host enter it through a symlink, so Claude and@@ -34,84 +38,42 @@ action-ready props, game objects, botanical/mechanical parts, and stylized recon## Core PromiseSculpt from a photo, in order — never one-shot a mesh:-1. **Run `python3 forge/next.py <spec>` first, or `python3 forge/next.py --state .img2threejs/state.json`.** The state form reports the ordered local checklist, exact next command, evidence status, and bounded correction-loop status; it never replaces the spec/pass gates.-1. **Use local state first.** Initialize it once, then run- `python3 forge/next.py --state .img2threejs/state.json [<spec>]` at every start/resume and before- every correction iteration. Obey a hard stop; never continue from memory.+1. **Run `python3 forge/next.py --state .img2threejs/state.json [<spec>]` first**, at every start,+ resume, and before every correction iteration. It reports the ordered checklist, exact next+ command, evidence status, and bounded correction-loop status; it never replaces the spec/pass+ gates. Obey a hard stop; never continue from memory.2. **Validate** the image is a suitable 3D target (`grimoire/intake/validation_rubric.md`).3. **Assess** object class + complexity, then write a `qualityContract` before any code.-3. **Spec** it: component hierarchy, materials, lighting, pivots, sockets, action anchors.-4. **Build pass-by-pass** from blockout → structure → form → material → lighting → interaction → optimization.-5. **Verify** each pass with a screenshot compared against the reference; fail a pass if an identity-defining feature is wrong even when the global score looks fine.+4. **Spec** it: component hierarchy, materials, lighting, pivots, sockets, action anchors.+5. **Build pass-by-pass** from blockout → structure → form → material → lighting → interaction → optimization.+6. **Verify** each pass with a screenshot compared against the reference; fail a pass if an+ identity-defining feature is wrong even when the global score looks fine.State explicitly when output is approximate/stylized/low-poly. A single image cannot revealhidden sides or guarantee exact geometry — say so instead of faking confidence.-## Resumable local workflow+## Mandatory Local State Gate-For a cross-agent or multi-session reconstruction, initialize the local state before intake:+Conversation context is disposable; `.img2threejs/state.json` is the local checklist authority.+Initialize once per reconstruction, then gate every step through it:```bash-python3 forge/state.py init --reference <image> --profile character --spec object-sculpt-spec.json-python3 forge/next.py --state .img2threejs/state.json-python3 forge/state.py mark image-analysis --evidence analysis.md+python3 forge/state.py init --state .img2threejs/state.json --reference <img> --profile <generic|cs2|character> --spec object-sculpt-spec.json+python3 forge/next.py --state .img2threejs/state.json [object-sculpt-spec.json]+python3 forge/state.py mark <step-id> --state .img2threejs/state.json --evidence <path>```-`generic`, `character`, and `cs2` profiles insert their required intake gates in order. Every-completed step needs evidence; every skipped step needs a reason. The state file is a resumability-index, not visual evidence: renders, specs, review history, and deterministic gates remain the-authoritative artifacts.--## Transparency and Process Debugging (Critical — from Bowie Knife reconstruction)--**The problem:** When the user cannot tell what was done or where something went wrong, they cannot debug the process. Over-claiming (reporting success when features still don't match) destroys trust and makes iterative improvement impossible.--**Rule:** Be transparent + don't over-claim. State exactly what changed each pass, with evidence, and name what still doesn't match:-- After each pass, explicitly list what changed: "Updated guard shape to extend left edge from -0.56 to -0.48 for handle overlap"-- Provide evidence: reference the specific values, coordinates, or parameters that changed-- Name what still doesn't match: "Handle silhouette traced but still flat plane (no Z palm-swell), procedural crosshatch not reference's exact dot-grid knurl"-- Explain why a change was made: "Extended guard left edge because handle ends at X=-0.42 and guard ended at X=-0.20, causing visual gap"-- Never claim a feature is "done" when it's only "improved" — use precise language-- When a gate passes but visual inspection shows issues, explain the limitation: "2D gate passed (fidelity 0.83) but three-quarter render shows blade reads as toy (no grind wedge) — 2D gates are blind to 3D realism"--**The user needs to be able to debug the process, not just the output.** If something is wrong, they should be able to trace which decision led to the error and correct it. Opaque processes force restarts; transparent processes enable refinement.-## Transparency and Process Debugging--Report what changed each pass with evidence (exact values/coordinates), name what still doesn't-match, and never claim "done" when only "improved". A passing gate is not proof of 3D realism.-Full rule + examples: `grimoire/review/self_correction.md`.--## GLB-mediated v2 render-fidelity track (1.5 alpha)--When the user supplies a GLB as an intermediate reference, use the browser-rendered GLB-as the structural and visual baseline, then author an independent procedural factory. The-raw GLB is never pixel evidence and its topology/materials are never copied into the factory.--Before any factory edit:--1. Run `forge/stage1_intake/probe_glb.py` and inspect `semanticDecomposition`. A merged- one-node/one-mesh/one-primitive/one-material asset is `insufficient` for reliable semantic- labels; connected-component/curvature/normal/UV segmentation is hypothesis evidence only.- Request a multipart GLB or capture a browser semantic-ID pass before claiming exact regions.-2. Author and validate one shared `render-profile.v2` with- `forge/stage4_review/validate_render_profile.py`. Both GLB and procedural routes must use- the same output color space, linear working space, tone mapping/exposure, PMREM environment,- viewport/DPR, camera, background and lighting settings.-3. Capture six passes for every admitted view: `beauty`, `alpha-silhouette`, `semantic-id`,- `depth`, `normal`, and `roughness-material-id`. Use- `forge/stage4_review/compare_region_passes.py` for deterministic global/per-region evidence;- missing semantic-ID data blocks per-region confidence instead of falling back to whole-image- color or silhouette scores.-4. Use region-specific continuous geometry/material strategies. Do not replace a face/head volume,- cloth shell, kasa, staff, or tail with a generic collection of floating primitives when the- region's silhouette or attachment requires a continuous surface.-5. Run one correction group per loop in this order: `camera → silhouette → face → clothing →- accessory → materials → lighting`. Recapture the full pass set after each group and record- the changed group, hashes and score. Never combine groups when diagnosing improvement.--The machine-readable contract lives in `docs/specs/render-profile.v2.schema.json` and-`docs/specs/render-profile.v2.example.json`. The executable manifest bridge accepts-`--render-profile` and exposes `record-pass`; its `glb-mediated-v2` validation is fail-closed.+- `next.py` prints the current step, pass, incomplete mandatory steps, exact next command, and+ `loop/max`. Exit code 3 or `status=stopped` is a hard stop: report the reason and request input.+ Never bypass it by reconstructing progress from chat history.+- Every completed step needs evidence; mark a non-applicable step `skipped` only with `--reason` —+ silent omission is forbidden. Loop counts derive from `reviewHistory` actions+ (`refine-spec`/`refine-code`), not agent memory. Defaults: 3 corrections per pass, 6 total.+- Profiles add mandatory gates without changing the core order: `cs2` requires classification,+ manifest, and a machine-readable CS2 review before AI review; `character` requires the character+ contracts and landmark evidence. Every profile records suitability, projection applicability, and+ material-evidence applicability. The state file is a resumability index, not visual evidence:+ renders, specs, review history, and deterministic gates remain the authoritative artifacts.## Required Inputs@@ -122,30 +84,6 @@ The machine-readable contract lives in `docs/specs/render-profile.v2.schema.jsonan explicit request for the user/vision provider to supply one; heuristic detection alone is notenough to select a geometry adapter-## Mandatory Local State Gate--Conversation context is disposable; `.img2threejs/state.json` is the local checklist authority.-Initialize it once per reconstruction:--`python3 forge/state.py init --state .img2threejs/state.json --reference <img> --profile <generic|cs2|character>`--At every fresh start, resume, or correction loop, run-`python3 forge/next.py --state .img2threejs/state.json [object-sculpt-spec.json]` before touching-code. It prints the current step, pass, incomplete mandatory steps, exact next command, and-`loop/max`. Exit code 3 or `status=stopped` is a hard stop: report the reason and request input.-Never bypass it by reconstructing progress from chat history.--After evidence exists, record it with-`python3 forge/state.py mark <step-id> --state .img2threejs/state.json --evidence <path>`.-Mark a non-applicable step `skipped` only with `--reason`; silent omission is forbidden. Loop counts-are derived from `reviewHistory` actions `refine-spec`/`refine-code`, not agent memory. Defaults are-3 corrections per pass and 6 total.--Profiles add mandatory gates rather than changing the core order: `cs2` requires classification,-manifest, and a machine-readable CS2 review before AI review; `character` requires the character-contracts and landmark evidence. Every profile records suitability, projection applicability, and-material-evidence applicability; conditional steps require evidence or an explicit skip reason.-## The Loop (scripts do enforcement; agent vision does judgment)Run scripts from the skill root (`forge/...`). Pure Python 3.10+ stdlib, no pip installs.@@ -155,61 +93,8 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that iprotocol in `grimoire/intake/image_analysis.md` — identify/classify, decompose macro→meso→micro,map part relationships, name materials in PBR terms, list identity-defining features, and flagwhat the single view hides. Observation before inference; controlled 3D vocabulary; 3D- object-space not 2D image-space. This is generic for any subject and feeds every field below.- Then probe local images: `forge/stage1_intake/probe_image.py <image>` (metadata only, not a visual check).-1a. **Local Spec Search** — after image analysis and before writing or refining a spec, local- evidence is a pipeline stage, not an optional memory lookup, whenever the request needs- domain-specific anatomy, PBR, wear, geometry, runtime, or physics specifications. The pre-spec- command automatically runs BM25, chooses `cs2` for CS2 targets and `core_3d` otherwise, and- writes a `localSpecSearch` evidence bundle into the assessment:- `python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json`.- Add observed terms with repeatable `--spec-query "<term>"`; use `--collection <collection>` only- when the automatic collection choice is insufficient. `new_sculpt_spec.py --assessment` carries- that bundle into the final spec, including snippets, `source_refs`, and `evidence_refs`.- For extra focused retrieval, the direct CLI remains available:- `python3 forge/stage1_intake/search_specs.py "<query>" --collection <collection> --limit 3 --snippet-chars 250 --json`.- For CS2, include the anatomical and the colloquial name, for example- `--spec-query "safety ring finger ring"` or `search_specs.py "roughness matte" --collection cs2`.- Expand queries with object names,- component names, material/finish terms, behavior terms, and known aliases; retry focused- alternatives when the first result is incomplete. Build the spec from returned evidence and do- not invent domain specs when local evidence exists. Search caches are local/generated only;- preserve JSONL records and source provenance rather than replacing them with cache output.-1aa. **Optional fidelity evidence adapters** — use them only when they improve an observed weak- point; the stdlib core remains authoritative. Route thin/complex masks to local SAM2, character- face/pose evidence to MediaPipe, and weak front/back cues to Depth Anything V2:- `python3 forge/stage1_intake/run_vision_adapter.py <segment|landmarks|depth> ...`.- Every adapter emits provenance. Confirm SAM2 selected the intended component; treat monocular- depth as relative only; review landmarks before copying them into anatomy. For browser work,- prefer Chrome DevTools MCP for live console/network/performance diagnosis, use- threejs-devtools MCP read-only to inspect scene/material/renderer state, and reserve Playwright- MCP for cross-browser or host fallback. MCP-only scene mutations never count as implementation:- write the proven change back to the spec or TypeScript, rebuild, and recapture. Use Context7- only with the target project's installed Three.js version; local types, typecheck and runtime- smoke tests override live docs. Full routing and commands:- `docs/integrations/reference_fidelity_tooling.md`.-1b. **CS2 intake manifest** — for a CS2 request, create and validate `cs2-intake.json` before- pre-spec authoring. Run admission and probing for every source view, record the heuristic signal- as non-authoritative evidence, attach the classification record, resolve the supported family,- and choose `route` independently from `exactnessTier`. Missing classification, insufficient- coverage, or a contradictory high-confidence class is `request-input`; unsupported families do- not continue into spec generation.-2. **Pre-Spec Assessment Gate** — classify + score complexity + write the quality contract:- `forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --complexity <simple|moderate|complex|ultra-complex> --out assessment.json`. Rules: `grimoire/intake/quality_contract.md`.- Set `objectClass.primaryDomain` (`object` | `character` | `hybrid`) and fill the seeded- `detailInventory` (its `targetMinDetails` scales with complexity). **Supported CS2 knife skins- and Glock-18 assets**: always pass `--cs2`, which defaults the complexity tier to `ultra-complex`- (`targetMinDetails` 16) — the finish/wear/hardware is the item, so CS2 is held to the top- fidelity bar; `targetMinDetails` never drops below the 9 floor even if downgraded by hand.- **Author procedural GEOMETRY (blade/guard/grip profiles) but make the FINISH a de-lit- reference-crop PROJECTION, not a procedural finish material** — projecting the photo's own- pixels is what reaches reference fidelity for patterned skins (Doppler/Gamma/Marble/Fade), and- is what the v1.3 baseline demos do; a procedural finish for a patterned skin reads visibly wrong- against the reference. Take the projection path in step 2c (it generalizes from characters to- any reference-matched surface). Procedural finish is the fallback ONLY when live view-dependent- response matters more than matching this one reference. Finish routes + rulebook:- `grimoire/build/cs2_finishes.md`; optional exact-texture acquisition:- `grimoire/intake/cs2_texture_acquisition.md`.+ object-space not 2D image-space. Then probe local images:+ `forge/stage1_intake/probe_image.py <image>` (metadata only, not a visual check).1a. **Local Spec Search** — after image analysis, before writing or refining a spec, pull localdomain evidence (anatomy/PBR/wear/geometry/runtime/physics) rather than inventing it:`python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json`@@ -222,11 +107,19 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that ipre-spec authoring (admission, heuristic signal, classification, family/route resolution).MUST read `grimoire/intake/cs2_intake_contract.md` completely before creating the manifest orrunning pre-spec assessment.+1c. **Optional fidelity evidence adapters** — only when they improve an observed weak point; the+ stdlib core remains authoritative. Thin/complex masks → local SAM2; character face/pose →+ MediaPipe; weak front/back cues → Depth Anything V2+ (`forge/stage1_intake/run_vision_adapter.py <segment|landmarks|depth> ...`; every adapter emits+ provenance; monocular depth is relative only). **MCP-only scene mutations never count as+ implementation** — write the proven change back to the spec or TypeScript, rebuild, recapture.+ Full adapter + MCP routing and authority boundaries:+ `docs/integrations/reference_fidelity_tooling.md`.2. **Pre-Spec Assessment Gate** — classify + score complexity + write the quality contract:`forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --complexity <simple|moderate|complex|ultra-complex> --out assessment.json`. Rules: `grimoire/intake/quality_contract.md`.Set `objectClass.primaryDomain` (`object` | `character` | `hybrid`) and fill the seeded- `detailInventory` (its `targetMinDetails` scales with complexity). **Supported CS2 knife- skins**: always pass `--cs2`, which defaults the complexity tier to `ultra-complex`+ `detailInventory` (its `targetMinDetails` scales with complexity). **Supported CS2 knife skins+ and Glock-18 assets**: always pass `--cs2`, which defaults the complexity tier to `ultra-complex`(`targetMinDetails` 16, floor 9) — the finish/wear/hardware is the item, so CS2 is held to thetop fidelity bar. Author procedural GEOMETRY but route the FINISH through the projection path instep 2c — a procedural finish for a patterned skin (Doppler/Gamma/Marble/Fade) reads visibly@@ -237,37 +130,32 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i`forge/stage1_intake/build_detail_inventory.py <image> --mode grid-3x3 --out-dir <dir> --out di.json`.Each detail MUST map to a `component.localFeatures` or `material.localOverrides` entry — neverprose only. Taxonomy + 3D-term recipes: `grimoire/intake/detail_inventory.md`.-2c. **Projection-first fidelity (characters AND reference-matched surfaces — supported CS2 skins, decals,- painted patterns)** — when the goal is matching a specific reference's surface, put the photo's- own pixels on the mesh instead of approximating them procedurally. This is the single biggest- fidelity lever; a procedural material for a patterned surface is the #1 reconstruction failure.- Recipe (`grimoire/character/likeness_maximization.md` — its two levers, align-mesh+camera and- project-the-photo, generalize past characters): solve the camera- (`stage1_intake/solve_camera_pose.py` → `referenceCamera`), **de-light** the reference so it is- free of baked lighting (`stage1_intake/delight_albedo.py`, hard requirement — this is what makes- projection safe, not the flat-lit icon), then project the de-lit crop onto the mesh and bake it- into UVs (`stage3_build/bake_projected_texture.py --mesh-id <id>`). For a CS2 skin the mesh is the- procedural family-specific component tree you author in the spec, and the projected de-lit crop IS the finish- (front + back from the two views) — no procedural Doppler material. For characters, first capture- landmarks (`stage1_intake/extract_landmarks.py --out anatomy.json`), fill `preSpecAssessment.anatomy`,+2c. **Projection-first fidelity** (characters AND reference-matched surfaces — supported CS2 skins,+ decals, painted patterns) — when the goal is matching a specific reference's surface, put the+ photo's own pixels on the mesh instead of approximating them procedurally. This is the single+ biggest fidelity lever; a procedural material for a patterned surface is the #1 reconstruction+ failure. Recipe (`grimoire/character/likeness_maximization.md` — its two levers generalize past+ characters): solve the camera (`stage1_intake/solve_camera_pose.py` → `referenceCamera`),+ **de-light** the reference (`stage1_intake/delight_albedo.py`, hard requirement — de-lighting is+ what makes projection safe), then project the de-lit crop and bake it into UVs+ (`stage3_build/bake_projected_texture.py --mesh-id <id>`). For a CS2 skin the projected de-lit+ crop IS the finish — no procedural Doppler material. For characters, first capture landmarks+ (`stage1_intake/extract_landmarks.py --out anatomy.json`), fill `preSpecAssessment.anatomy`,route `grimoire/character/reconstruction.md`. A single view cannot show hidden sides — reportper-region confidence and request more views when it matters.- Character sub-routes, in the order they are needed — decide what parts exist before shaping any- of them, and shape the head before the hair that sits on it:- - **Parts** — `grimoire/character/structure_decomposition.md`: which parts the figure is made of,- and where each one's boundary falls.- - **Head** — `grimoire/character/head_construction.md`: skull, face plane and feature placement,- the sub-route the likeness gate reads against.- - **Hair** — `grimoire/character/stylized_hair_threejs.md`, with the parameter contract in- `grimoire/character/threejs_hair_parameter_contract.json`. Lock topology first: material- tuning cannot repair wrong lock topology, so run it only after the silhouette review passes.-2d. **Reference-free humanoid** — when the request is a generic figure with no reference image- ("a low-poly humanoid"), there is nothing to measure, so fill anatomy from public canon with+ Character sub-routes, in order — decide what parts exist before shaping any, and shape the head+ before the hair that sits on it:+ - **Parts** — `grimoire/character/structure_decomposition.md`+ - **Head** — `grimoire/character/head_construction.md` (what the likeness gate reads against)+ - **Hair** — `grimoire/character/stylized_hair_threejs.md` + parameter contract in+ `grimoire/character/threejs_hair_parameter_contract.json`. Lock topology only after the+ silhouette review passes: material tuning cannot repair wrong lock topology.+2d. **Reference-free humanoid** — a generic figure with no reference image has nothing to measure,+ so fill anatomy from public canon:`forge/stage2_spec/humanoid_proportions.py <spec> --style-heads 8 --in-place`. It writes- `anatomy.source: "canon-table"` so canon is never mistaken for measured evidence, refuses to- run at all when the spec names a reference image, and lists what the corpus does NOT supply- under `anatomy.unsourced`. Only complete head counts are derivable (currently 8); anything- else fails with the missing landmark named rather than being interpolated.+ `anatomy.source: "canon-table"` so canon is never mistaken for measurement, refuses to run when+ the spec names a reference image, and names anything the corpus does not supply rather than+ interpolating it.3. Author the spec from the assessment:`forge/stage2_spec/new_sculpt_spec.py "Name" --image <img> --assessment assessment.json --manifest cs2-intake.json --out object-sculpt-spec.json`.Replace generic starter `featureReviewTargets` with the object's real identity-defining@@ -277,19 +165,20 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i`topologyClass`/`topologyRationale` per `grimoire/intake/surface_topology.md` before picking a`primitive` — this is what prevents a continuous organic form from being picked as a box.4. When material fidelity matters and a source image exists, analyze each material's **finish** then- extract reference PBR evidence, both per crop (crop the correct region — verify the crop is on the- part you think it is):+ extract reference PBR evidence, both per crop (verify the crop is on the part you think it is):- `forge/stage1_intake/analyze_texture.py <crop> --spec spec.json --material-id <id> --in-place`- classifies the finish (`gem-metal | gemstone | painted-metal | worn-composite | brushed-steel |- plastic`), extracts the gradient palette, and writes doc-grounded MeshPhysicalMaterial scalars- (metalness/roughness/clearcoat/transmission/ior/anisotropy/envMapIntensity) onto the material.- Recipes + Three.js texture/PBR rules (colorSpace, CanvasTexture/DataTexture, height→normal) live- in `grimoire/build/threejs_texture_reference.md`. Rule of thumb: **solid albedo for flat paint,- real reference crop for patterned finishes** (doppler/quartz/hydro-dip/camo).+ classifies the finish, extracts the gradient palette, and writes doc-grounded+ MeshPhysicalMaterial scalars onto the material. Recipes + Three.js texture/PBR rules:+ `grimoire/build/threejs_texture_reference.md`. Rule of thumb: **solid albedo for flat paint,+ real reference crop for patterned finishes**.- `forge/stage1_intake/extract_pbr_evidence.py <crop> --out-dir <dir> --material-id <id> --target-threshold 0.7`.- Confidence < 0.7 is a stop/refine-input signal, not a pass. It is inference, not inverse rendering.- - For multiple named regions, use `forge/stage1_intake/material_region_analysis.py --manifest regions.json --out-dir material-evidence --out material-analysis.json`. Resolve each accepted assignment from `docs/materials/material-reference.json`, then wire it into the spec with `forge/stage2_spec/apply_material_analysis.py`.- - Emit the controlled material camera/crop contract with `forge/stage4_review/material_views.py`, compare saved visible-footprint crops with `forge/stage4_review/material_comparator.py`, apply only bounded material-scoped corrections with `forge/stage4_review/material_feedback.py`, and record the blocking result with `forge/stage4_review/material_gate.py`.+ Confidence < 0.7 is a stop/refine-input signal, not a pass. It is inference, not inverse rendering.+ - For multiple named regions: `forge/stage1_intake/material_region_analysis.py --manifest regions.json --out-dir material-evidence --out material-analysis.json`,+ resolve each assignment from `docs/materials/material-reference.json`, wire it in with+ `forge/stage2_spec/apply_material_analysis.py`.+ - Emit the controlled material camera/crop contract (`forge/stage4_review/material_views.py`),+ compare visible-footprint crops (`material_comparator.py`), apply only bounded material-scoped+ corrections (`material_feedback.py`), and record the blocking result (`material_gate.py`).5. Validate, then strict-validate before generating code:`forge/stage2_spec/validate_sculpt_spec.py object-sculpt-spec.json` then `--strict-quality`.Strict blocks shallow specs (a complex object with one root, no repetition systems, no@@ -297,61 +186,32 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i6. **Locked build passes** — only touch the currently unlocked pass:`forge/stage3_build/orchestrate_passes.py status object-sculpt-spec.json``forge/stage3_build/generate_threejs_factory.py object-sculpt-spec.json --out src/createObjectModel.ts`- (generator is fail-closed: `strict-quality` must pass before it can write any factory; a future- `--pass-id` also fails until prior passes are reviewed `continue`). If blocked, preserve the+ The generator is fail-closed: `strict-quality` must pass before it writes any factory, and a+ future `--pass-id` fails until prior passes are reviewed `continue`. If blocked, preserve the`BLOCKED` artifact and refine the subject-specific spec; do not substitute a generic template.-6a. **Hitting a triangle budget.** `performanceBudget.targetTriangles` selects a tessellation- tier for every primitive that has segment counts (low ≤6k, standard ≤60k, else hero), and- caps implicit-surface sampling grids. Where that is not precise enough — an SDF's grid is- quantised, so a tier can only get near a number — add- `geometryDescriptor.decimate: {"targetRatio": 0.4}` to that component. It emits a- Garland-Heckbert quadric collapse into the generated factory and runs **before** skin- binding, so weights are computed on the surviving vertices and no skinning data is- interpolated across a vertex merge. It keeps `position` only, recomputing normals, so it is- refused on an authored/unwrapped `uvStrategy`. For offline LOD tiers from an exported mesh,- `forge/stage3_build/decimate.py <mesh.json> --ratio <r> --json` is the same algorithm.+ The local state adds `--force` only for a new pass or `refine-spec`; `refine-code` edits the+ current artifact without regenerating it. Before overwriting, carry valid hand refinement back+ into the spec; generated code must not be the only copy of reconstruction decisions.+6a. **Hitting a triangle budget.** `performanceBudget.targetTriangles` selects a tessellation tier+ for every primitive with segment counts (low ≤6k, standard ≤60k, else hero) and caps+ implicit-surface sampling grids. Where a tier is not precise enough, add+ `geometryDescriptor.decimate: {"targetRatio": 0.4}` to that component — a quadric collapse in+ the generated factory, run **before** skin binding so weights are computed on surviving+ vertices. It keeps `position` only (normals recomputed), so it is refused on an+ authored/unwrapped `uvStrategy`. Offline LOD tiers:+ `forge/stage3_build/decimate.py <mesh.json> --ratio <r> --json`.7. Render the current pass in a browser/preview, capture a screenshot at a review viewpoint.7a. **Off-axis and placement gates — a single review viewpoint is not evidence about the model.**- Capture a turntable, not one frame, and run all three. Each catches a defect class the older gates- pass by construction; skipping them is how a hole through a skull, a hat at hip height and a charm- floating below the ground plane survived eight front-only review rounds.+ Capture a turntable, not one frame, and run all three; each catches a defect class the older+ gates pass by construction (a hole through a skull, a hat at hip height and a floating charm all+ survived eight front-only review rounds):`forge/stage4_review/turntable_gate.py --capture 0=front.png --capture 90=right.png --capture 180=rear.png --capture 270=left.png --json``node runtime/scripts/export_mesh_geometry.mjs --url <preview> --out meshes.json` then`forge/stage4_review/self_intersection.py meshes.json --json``forge/stage4_review/attachment_anchor.py object-sculpt-spec.json --measured measured.json --json`- All three exit `0` clean / `1` gate failure / `2` error. A failure blocks `continue` for the pass- even when the global fidelity score passes — the score is computed from one camera and a 64×64 luma- grid, and neither can represent any of these defects. Read `sampledVertexCount` /- `unmeasuredAttachments` / `missingAzimuths` before believing a clean verdict: each names the part of- the model the gate did not actually look at.-8. Package one side-by-side sheet, then inspect it with agent vision:- `forge/stage4_review/make_comparison_sheet.py --reference <img> --render <shot> --out cmp.png --json`.-9. Record the review (overall + per-layer + per-feature scores + decision):- `forge/stage4_review/append_review.py object-sculpt-spec.json --pass-id <pass> --fidelity <0-1> --action <continue|refine-spec|refine-code|request-input|stop> --summary "..." --render-screenshot <shot> --comparison-image cmp.png --ai-vision-score <0-1> --layer-scores-json '{...}' --feature-reviews-json <f.json> --in-place`.- For the CS2 family path, also attach the versioned report with- `--cs2-review-json cs2-review.json --review-scene-json forge/tests/fixtures/knife_review_scene.json`.- A failed family, painted-region, projection-coverage, critical-detail, or orbit gate blocks- `continue` even when the global score passes. See `docs/cs2/review-gates.md`.-10. Sync pipeline state after manual review edits:- `forge/stage3_build/orchestrate_passes.py sync object-sculpt-spec.json --in-place`.--## Forge Runtime Contracts--Subdivision runtime tests compile generated TypeScript against the showcase checkout. Set-`IMG2THREEJS_SHOWCASE_ROOT` to that checkout; without it, local runtime-only tests skip with an-actionable message while static contracts still run. CI should set `IMG2THREEJS_REQUIRE_SHOWCASE=1`-to turn a missing showcase checkout into a test failure.--```bash-IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_subdivision.py-IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 -m unittest discover -s forge/tests-IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_showcase_tsc_smoke.py-```- (generator is pass-gated: a future `--pass-id` fails until prior passes are reviewed `continue`).- The local state adds `--force` only for a new pass or `refine-spec`; `refine-code` edits the- current artifact without regenerating it. Before overwriting, carry valid hand refinement back- into the spec; generated code must not be the only copy of reconstruction decisions.-7. Render the current pass in a browser/preview, capture a screenshot at a review viewpoint.+ All three exit `0` clean / `1` gate failure / `2` error. A failure blocks `continue` even when+ the global fidelity score passes. Read `sampledVertexCount` / `unmeasuredAttachments` /+ `missingAzimuths` before believing a clean verdict: each names what the gate did not look at.8. **Run deterministic gates before AI vision.** MUST read`grimoire/review/gates_reference.md` and `grimoire/review/self_correction.md` completely. Run`forge/stage4_review/diagnose_render.py` and record the passing Tier 1 result with@@ -363,12 +223,11 @@ IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test`forge/stage4_review/make_comparison_sheet.py --reference <img> --render <shot> --out cmp.png --json`.10. Record the review (overall + per-layer + per-feature scores + decision):`forge/stage4_review/append_review.py object-sculpt-spec.json --pass-id <pass> --fidelity <0-1> --action <continue|refine-spec|refine-code|request-input|stop> --summary "..." --render-screenshot <shot> --comparison-image cmp.png --ai-vision-score <0-1> --layer-scores-json '{...}' --feature-reviews-json <f.json> --in-place`.- For the CS2 knife path, also attach the versioned report with- `--cs2-review-json cs2-review.json --review-scene-json forge/tests/fixtures/knife_review_scene.json`.- Produce that report first with- `forge/stage4_review/cs2_review.py --manifest cs2-intake.json --metrics cs2-review-inputs.json --scene forge/tests/fixtures/knife_review_scene.json --out cs2-review.json`.- A failed family, painted-region, projection-coverage, critical-detail, or orbit gate blocks- `continue` even when the global score passes. See `docs/cs2/review-gates.md`.+ For the CS2 family path, produce the versioned report first with+ `forge/stage4_review/cs2_review.py --manifest cs2-intake.json --metrics cs2-review-inputs.json --scene forge/tests/fixtures/knife_review_scene.json --out cs2-review.json`+ and attach it with `--cs2-review-json cs2-review.json --review-scene-json forge/tests/fixtures/knife_review_scene.json`.+ A failed family, painted-region, projection-coverage, critical-detail, or orbit gate blocks+ `continue` even when the global score passes. See `docs/cs2/review-gates.md`.11. Sync pipeline state after manual review edits, record checklist evidence, then re-run the localstate gate before another correction or pass:`forge/stage3_build/orchestrate_passes.py sync object-sculpt-spec.json --in-place`@@ -377,172 +236,56 @@ IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test`forge/stage4_review/check_part_coverage.py --spec object-sculpt-spec.json --manifest parts.json`and verify the action-ready hierarchy. Mark `part-coverage` and `action-ready` only with evidence.-## CS2 image-matched rule--For a CS2 item, the target is observable agreement between the supplied image and the rendered-item: silhouette, proportions, edge profile, hardware layout, coating colour, pattern placement,-wear, roughness response, and camera framing. Every decision must be traceable to evidence or be-labelled as an approximation.--The initial CS2 family boundary covers supported **knife** subtypes and the **Glock-18** pistol-adapter. Rifle, SMG, sniper, heavy, glove, unsupported pistol, and unknown knife subtypes must stop-with `unsupported-family` or `unsupported-subtype`; they must not receive another family's component-tree as a generic fallback.--### Layer contract--Pass these records between layers. Do not copy an informal vision description into the next stage:--| Layer | Owns | Must emit | Must not decide alone |-| --- | --- | --- | --- |-| Intake | view validity and technical evidence | role, path/hash, resolution, coverage, duplicate status, admission verdict | item identity from aspect ratio or filename |-| Classification | semantic identity | family, subtype, confidence, evidence refs, provider/version, timeout state | geometry or finish parameters |-| Identity | skin/name/paint metadata | precedence, resolved values, ambiguity candidates, provenance | guessed paint index, float, or seed |-| Surface evidence | pixels and texture sources | de-lit reference, PBR channels, map provenance, colour space, UV orientation, confidence | albedo reused as roughness/normal/AO |-| Geometry adapter | family-specific form | component tree, topology, dimensions, edge/spine, hardware relationships, painted regions | hidden geometry without confidence notes |-| Spec/route | evidence-backed implementation choice | route, exactness tier, assumptions, feature targets, camera contract | exact-texture claim without exact evidence |-| Build/review | rendered observables | fixed view, two non-degenerate orbit views, per-region results, failed gates, next action | overriding a failed critical feature with a global score |--The canonical hand-off is `cs2-intake.json` (`schemaVersion: 1`). Its state is one of-`proceed`, `request-input`, `fallback`, `rejected`, `unsupported-family`, or-`unsupported-subtype`. Write it atomically and preserve unknown provider fields under-`extensions`; a fallback must never erase prior evidence.--### CS2 intake order--1. Admit and technically probe every view. Reject undecodable, empty, tiny, fragmented, or- duplicate references before classification.-2. Record the heuristic CS2 signal only as a routing hint. `detect_cs2.py` is never authoritative- identity evidence.-3. Require a classification record before selecting a family adapter. If classification is absent,- timed out, or contradicts a high-confidence objectness result, return `request-input`.-4. Resolve identity in this order: explicit user metadata, uniquely resolved metadata, then the- authoritative classification record. Preserve ambiguity rather than guessing.-5. Select route and exactness independently:- - `reference-projection`: default for matching a specific patterned image;- - `authored-texture`: only when independent texture maps are supplied or legally acquired;- - `procedural-finish`: fallback when projection evidence is unavailable or live response is the- stated priority.- Exactness is `image-only`, `metadata-assisted`, or `exact-texture`; changing route must not- silently upgrade or downgrade the evidence tier.-6. Select the family adapter only after family/subtype validation. Record painted regions, unpainted- substrate, visible hardware, hidden-region confidence, and every approximation in the spec.-7. For projection, solve the camera and de-light the source first. Projected pixels provide colour- evidence, not automatic geometry truth; geometry still comes from the adapter and silhouette- review.--### Surface and review rule--For a specific CS2 reference, preserve the reference's own colour/pattern pixels whenever legal and-technically possible. Procedural Doppler/Fade/Gamma/Marble patterns are not equivalent to the input-image and may only be used with an explicit `procedural-finish` route and approximation warning.-Keep albedo, roughness, metalness, normal/height, AO, mask, and wear as independent channels. Record-channel source, colour space, UV orientation, dimensions, packed-channel decoding, and missing-channel-derivation. A low-confidence PBR inference is a refine-input signal, not proof of exact material.--Single-view reconstruction may proceed only when visible identity features are sufficiently covered;-hidden blade sides, underside, and back hardware must carry inference confidence and may trigger-`request-input`. Review the fixed camera plus two meaningful orbit views. Report what changed, which-evidence caused it, what still differs, and choose exactly one next action:-`continue`, `refine-spec`, `refine-code`, `request-input`, or `stop`.--## Gates (do not skip)+## GLB-mediated v2 render-fidelity track (1.5 alpha)-- **Suitability + reference integrity**: pass / conditional / reject before any planning- (`grimoire/intake/validation_rubric.md`), AND every reference admitted via- `forge/stage1_intake/check_reference_admission.py` (rejects empty/fragmented/tiny/duplicate/- undecodable refs with a reason). Intake understanding cross-checked by- `forge/stage1_intake/check_intake_correctness.py` (halts on a confident class contradiction).-- **Divine Eye (the harness heart) — deterministic-first, model-last**: the render evaluator is- `forge/stage4_review/divine_eye.py` — a zero-token multi-signal ensemble (IoU/scale HARD gates;- proportion/symmetry-parity/pHash/SSIM/edge/blowout/flat/tonal-parity soft) with self-uncertainty- (`probe` on signal disagreement) and deterministic routing (`continue`/`refine-spec`/`refine-code`/- `probe`). The VLM (`forge/stage4_review/vlm_gate.py`) is a gated, calibrated, cross-checked- last layer: **never consulted on a hard-gate failure**, multi-sample-voted, and can rescue a- soft near-threshold reject but never grant past a hard geometric failure.-- **Multi-angle or it didn't happen**: a non-planar form must hold from ≥2 camera angles.- `forge/stage4_review/diagnose_render_multi_angle.py` flags `degenerate-view` when an orbited- silhouette collapses (a flat plane faking a volume). Orbit angles use reference-free- self-consistency — never scored against a reference angle the photo doesn't cover.-- **CS2 review contract**: `forge/stage4_review/cs2_review.py` consumes the manifest and- versioned scene fixture, then blocks wrong family identity, missing projection coverage,- painted-region mismatch, critical identity-detail failure, finish/material response failure,- and degenerate orbit form. It records exactness tier, hidden-region confidence, per-region- confidence, approximation notes, camera, environment hash, exposure, tone mapping, resolution,- background, and renderer version.-- **Bounded correction loop (token-burn safety)**: `forge/stage4_review/correction_loop.py`- guarantees termination: hard gates route to `refine-code`; repeated defects and oscillation route- to `refine-spec`; plateau and the hard ceiling route to `request-input` — never a silent infinite- burn. Deterministic analysis-by-synthesis parameter fitting and Divine Eye provenance are- documented in `grimoire/build/analysis_by_synthesis_fitting.md`.-- **Executable Divine Eye fitting**: `fit_against_divine_eye()` in- `forge/stage4_review/fit_params.py` connects deterministic parameter-to-render callbacks to- bounded gate-aware Divine Eye optimization. Clean candidates use raw fidelity; hard-gated- candidates score below all clean results while retaining original fidelity and provenance. The- returned objective and optional selected raw fidelity are explicit, and each copied record has- candidate/reference/render provenance. It lazily loads the default evaluator and returns- normalized raw-fidelity correction-loop provenance without mutating sources.-- **Tier 1 (legacy, still valid)**: "Tier 2 (AI-vision) never runs against a render that has not passed Tier 1." Run `forge/stage4_review/diagnose_render.py` (silhouette IoU/proportion/symmetry/per-part color) and record it (`--spec ... --in-place`) before requesting a comparison sheet; `orchestrate_passes.py check` refuses otherwise.-- **Pre-spec / strict-quality**: blocks code gen until the spec is deep enough for its contract.-- **Screenshot feedback**: `continue` is allowed only with a render + comparison sheet + global- AI-vision score ≥ threshold (default 0.7) AND every critical feature ≥ its own threshold.- Details + per-layer scorecard: `grimoire/feedback/render_capture.md`.-- **Action-ready**: build a runtime hierarchy (pivots, sockets, colliders, destruction groups),- never an inert lump; expose `root.userData.sculptRuntime`. `grimoire/readiness/action_rigging.md`.-- **Procedural rig contract (1.5-alpha)**: for humanoid/character builds, validate the authored- `joints`/`parents`/`names`/`matrix_local`/packed skin payload with- `forge/stage5_rig/validate_rig_payload.py` before binding `THREE.Skeleton`. The gate proves- structural payload integrity only; pose stress, dynamic bounds, readable screenshots, and- visual likeness remain separate gates. Payload ownership and non-goals:- `grimoire/readiness/procedural_rigging_contract.md`.-- **Assembly gate (structure, not pixels) — every model ships explodable AND clickable**: this is- a build requirement, not a per-project extra. Name every mesh; flag surface relief- `userData.explodeWithParent` so it rides its shell; let a named group of *anonymous* meshes be one- part while a named group of *named* parts stays a container. Explode and part-picking must share- one definition of "a part" — if they disagree, both are wrong. Separate parts by SCALING the- layout about the model centre, never by pushing every part the same distance (that translates the- arrangement without opening any gap). Then run- `forge/stage4_review/check_part_coverage.py --spec <spec> --manifest <parts.json>`: it FAILS on a- specified component that was never built and on two components fused onto one mesh; it warns on- inventoried details that never reached the spec and on meshes belonging to no named part. This is- the only gate that scores STRUCTURE — every other one scores pixels, and a single fused mesh- wearing a projected photo passes all of those. Its limit is honest and must be stated when- reporting: it proves you built what you specified, never that you specified enough.- Full contract + the two rules it took a wrong pass to learn: `grimoire/build/geometry_patterns.md`.-- **Attachment**: child appendages (branches/limbs/handles/tubes) need `attachment.parentSocket`,- `localStart`, `localEnd`, `contactType`, `embedDepth`/`overlap`, `gapTolerance` — no mid-air parts.- `grimoire/readiness/joint_attachment.md`.-- **Material/lighting**: `grimoire/feedback/shading_realism.md` — independent PBR channels- (never alias albedo into roughness/normal/AO), macro/meso/micro frequency bands, real lights.-- **Detail inventory**: for `moderate`+ subjects strict-quality blocks code gen until the- `detailInventory` reaches `targetMinDetails` and every detail maps to a real component/material- entry (gloss needs low-roughness/clearcoat; fasteners need instancing/micro parts).-- **Character track**: when `primaryDomain` is `character`/`hybrid` (or `--character`), the spec- author auto-builds a stylized humanoid template (head/neck/torso/arms + hair, glasses,- headphones, face features), flattened to world space under a hidden root, with per-part- character materials and character build passes (`proportion-lock`, `feature-placement`).- strict-quality requires a filled `anatomy` block (head-units, proportions, face landmarks) and- character feature targets. Suitability routing for humans: `grimoire/intake/validation_rubric.md`- (stylized vs maximum-likeness). Stylized bust, not a face-copy; refine positions per reference.-The initial CS2 family boundary is **knife only**. Pistol, rifle, SMG, sniper, heavy, glove, and-unknown knife subtypes must stop with `unsupported-family` or `unsupported-subtype`; they must not-receive the knife component tree as a generic fallback.--For every CS2 reconstruction, MUST read the full layer contract, intake order, and surface/review-rule in `grimoire/intake/cs2_intake_contract.md` before intake state can advance.+When the user supplies a GLB as an intermediate reference, the browser-rendered GLB is the+structural and visual baseline for an independently authored procedural factory. The raw GLB is+never pixel evidence and its topology/materials are never copied into the factory. Before any+factory edit — full contract in `grimoire/build/python_threejs_render_bridge.md`, machine-readable+schema in `docs/specs/render-profile.v2.schema.json` (+ example; fail-closed validation):++1. `forge/stage1_intake/probe_glb.py` first. A merged one-node/one-mesh asset is `insufficient`+ for semantic labels; request a multipart GLB or a browser semantic-ID pass before claiming+ exact regions.+2. Author ONE shared `render-profile.v2` (`forge/stage4_review/validate_render_profile.py`) used by+ both the GLB and procedural routes. Region IDs are subject-specific, never inherited from the+ example profile; declare the required set in `extensions.requiredSemanticRegions` so omission is+ a hard validation error.+3. Capture six passes per admitted view (`beauty`, `alpha-silhouette`, `semantic-id`, `depth`,+ `normal`, `roughness-material-id`); score with `forge/stage4_review/compare_region_passes.py`.+ Missing semantic-ID data blocks per-region confidence rather than falling back to whole-image+ scores.+4. Use region-specific continuous geometry — never replace a face/head volume, cloth shell, or tail+ with floating primitives when the region's silhouette requires a continuous surface.+5. Run ONE correction group per loop, in order: `camera → silhouette → face → clothing → accessory+ → materials → lighting`; recapture the full pass set after each group and record the changed+ group, hashes and score. Never combine groups when diagnosing improvement.## Gates (do not skip)Before any visual review or `continue` decision, MUST read the full gate-by-gate contract in-`grimoire/review/gates_reference.md` (Divine Eye, VLM rescue, multi-angle, CS2 review, bounded-correction, screenshot feedback, assembly, attachment, material, detail inventory, character-track). In short:+`grimoire/review/gates_reference.md` (Divine Eye, VLM rescue, multi-angle, interior difference,+chirality, hair, CS2 review, bounded correction, Divine Eye fitting, screenshot feedback, assembly,+attachment, material, detail inventory, rig payload, character track). In short:- Validate references first (`grimoire/intake/validation_rubric.md`, `check_reference_admission.py`).- `divine_eye.py` is deterministic-first; the VLM (`vlm_gate.py`) is a gated last layer, neverconsulted on a hard-gate failure.- A non-planar form must hold from ≥2 angles (`diagnose_render_multi_angle.py`).-- CS2 knife builds also run `cs2_review.py` against the versioned scene fixture.+- Measure INSIDE the silhouette every visual pass (`interior_difference.py`). Silhouette IoU reads+ ~11% of figure cells: a model with its face deleted scored the same 0.8803 as the finished face.+- Every `-l`/`-r` pair is a MIRROR, not a rotation — hard at spec time (`validate_chirality`). A pair+ wrong the same way on both sides still passes, and needs `medial_lateral_bias` vs a reference.+- Hair subjects: `scalp_exposure.py` is HARD and runs on geometry before any render; `hair_gate.py`+ is soft and subordinate to it. A coverage shortfall never authorises widening the masses.+- Flat colour regions with hard boundaries (blaze/bib/socks, livery stripe, painted marking) are an+ identity feature, so their boundaries are gated on geometry: `vertex_region_gate.py`. Never a+ texture — this pipeline emits code; the shape predicates live in `_shared/vertex_paint.py`.+- A curve claim ("curled into a hook, not a straight cone") needs `swept_arc_gate.py`: silhouette IoU+ passes a straight cone occupying roughly the right cells.+- Character builds validate the rig payload (`stage5_rig/validate_rig_payload.py`) before binding a+ `THREE.Skeleton`; it proves payload integrity only, never pose stress or likeness.+- CS2 builds also run `cs2_review.py` against the versioned scene fixture.- Local state enforces 3 corrections per pass and 6 total by default; reaching either limit is ahard stop. `correction_loop.py` may stop earlier on repeated defects, oscillation, or plateau.- `continue` requires a render + comparison sheet + AI-vision score ≥ threshold, every critical@@ -563,15 +306,76 @@ decision, MUST read the root-cause guide + fidelity scale in `grimoire/review/serecord the decision, and re-run the local state gate.**Small features need a different instrument.** Divine Eye's SSIM/tonal/edge signals run on a 64×64-luma grid and a 96×96 edge grid, so a detail a few pixels wide in the reference is not scored badly —-it is absent before any comparison happens, and `per_feature.py` cannot compensate because it consumes-a scores dict and never opens an image. When fidelity depends on individual tears, spars, fangs or-eyes, use the four-tier microscope: `grimoire/review/divine_eye_microscope.md`. Two rules there are-empirically established rather than proposed, and both produced confident false findings before being-understood: measure fidelity on a component's **visible footprint** (the full frame minus a-component-hidden frame), never on an isolation render, which reveals geometry the reference cannot-see; and never colour-gate a **concave** feature, where a dark ratio captures cavity shading rather-than material.+luma grid, so a detail a few pixels wide is absent before any comparison happens. When fidelity+depends on individual tears, spars, fangs or eyes, use the four-tier microscope:+`grimoire/review/divine_eye_microscope.md`. Two empirically established rules from it: measure+fidelity on a component's **visible footprint** (full frame minus a component-hidden frame), never+on an isolation render; and never colour-gate a **concave** feature, where a dark ratio captures+cavity shading rather than material.++## Transparency and Process Debugging++Report what changed each pass with evidence (exact values/coordinates), name what still doesn't+match, and never claim "done" when only "improved". A passing gate is not proof of 3D realism.+Full rule + examples: `grimoire/review/self_correction.md`.++## Left and right++A left/right pair is a **reflection**, never a rotation: negate the lateral axis and nothing else,+`(x, y, z) → (-x, y, z)`. With `forward: +Z`, Y up and a right-handed frame, the character's own+left is **+X**. The convention lives as code in `forge/_shared/chirality.py`+(`CHARACTER_LEFT_SIGN`), with two different gates for the two defects that shipped from getting it+wrong: `validate_chirality` catches a rotation-mistaken-for-reflection at spec time, and+`medial_lateral_bias` vs a reference catches a pair that is wrong the same way on both sides.+Reflecting also inverts triangle winding — flip it back on the mirrored side or `flatShading`+lights the limb as though lit from behind. Full write-up with the measured defects:+`grimoire/scripts.md` ("Left and right").++## Hair++Hair has its own subsystem because it has failure modes no other gate can see. Full contract,+measurements and non-goals: `docs/HAIR_PIPELINE.md`. The hard rules:++- Roots bind to the scalp as `(u, v)`, never absolute positions (hard validation error).+- `standProud` is enforced by the generator, not advisory.+- `scalp_exposure.py` is a HARD gate on geometry before any render; a coverage shortfall never on+ its own authorises widening the masses.+- Default representation tier is `shell`, not locks; strand impression comes from faceting and+ material (`hair.human.code-only`), since this skill emits no textures.+- `plane-card` is rejected for hair (needs an alpha texture this skill cannot emit).+- Hair is rigidly parented, never smooth-skinned (the geodesic field runs through the skull).++## CS2 image-matched rule++For a CS2 item, the target is observable agreement between the supplied image and the rendered+item: silhouette, proportions, edge profile, hardware layout, coating colour, pattern placement,+wear, roughness response, and camera framing. Every decision must be traceable to evidence or be+labelled as an approximation.++The initial CS2 family boundary covers supported **knife** subtypes and the **Glock-18** pistol+adapter. Rifle, SMG, sniper, heavy, glove, unsupported pistol, and unknown knife subtypes must stop+with `unsupported-family` or `unsupported-subtype`; they must not receive another family's component+tree as a generic fallback.++The full layer contract (what each layer owns, must emit, and must never decide alone), the CS2+intake order, and the surface/review rule live in `grimoire/intake/cs2_intake_contract.md` — step+1b already requires reading it completely before intake state can advance. The canonical hand-off+is `cs2-intake.json` (`schemaVersion: 1`, states `proceed | request-input | fallback | rejected |+unsupported-family | unsupported-subtype`); write it atomically, preserve unknown provider fields+under `extensions`, and never let a fallback erase prior evidence.++## Forge Runtime Contracts++Subdivision runtime tests compile generated TypeScript against the showcase checkout. Set+`IMG2THREEJS_SHOWCASE_ROOT` to that checkout; without it, local runtime-only tests skip with an+actionable message while static contracts still run. CI should set `IMG2THREEJS_REQUIRE_SHOWCASE=1`+to turn a missing showcase checkout into a test failure.++```bash+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_subdivision.py+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 -m unittest discover -s forge/tests+IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase python3 forge/tests/test_showcase_tsc_smoke.py+```## Implementation Rules (brief)@@ -597,12 +401,10 @@ strict sculpt/build/review gates; alpha owns deterministic camera manifests, broevidence and UniRig-shaped rig validation. CharacterGen, Tripo, VRM and other neural/assetsystems are opt-in adapters with source, checkpoint, license, coordinate conversion and outputhashes. They never silently replace the procedural TypeScript factory. Image-to-mesh systems emit a-static mesh with no skeleton, so their output is never animation-ready however good it looks; neural-riggers are offline inference whose value here is the serialized payload, not a browser dependency.--Executable entry points are `forge/stage4_review/render_bridge.py` and-`scripts/capture_threejs_playwright.py`. Run `init → browser capture → validate → diagnose`;-capture must operate on the real showcase/browser route and leave readable PNGs in the workspace.+static mesh with no skeleton, so their output is never animation-ready however good it looks.+Executable entry points: `forge/stage4_review/render_bridge.py` and+`scripts/capture_threejs_playwright.py` (`init → browser capture → validate → diagnose`; capture+must operate on the real showcase/browser route and leave readable PNGs in the workspace).## Outputdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex bdfddcf..98f673c 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -14,21 +14,33 @@ flowchart TDB --> C[Pre-Spec Assessment: class, complexity, quality contract]B -. when useful .-> A1[Optional mask, landmark and relative-depth evidence]A1 --> C- C --> D[Author ObjectSculptSpec: components, materials, sockets]- D --> E{Validate and strict-quality}- E -- too shallow --> D+ C --> R{Pipeline routing: weapon or character}+ R -- confidence below threshold --> RQ[request-input]+ R -- resolved --> D[Author ObjectSculptSpec: components, materials, sockets]+ D --> E{Validate, chirality, strict-quality}+ E -- too shallow or wrong handedness --> DE -- ok --> F[Locked build passes]F --> G[Generate Three.js factory: current pass only]- G --> H[Render in browser and screenshot]+ G --> G2{Geometric gates before any render}+ G2 -- "bald patch, self-intersection" --> K[Self-correct]+ G2 -- ok --> H[Render in browser and screenshot]H --> I[Package one side-by-side sheet]- I --> J{Agent vision review}- J -- score below threshold --> K[Self-correct: refine-spec or refine-code]+ I --> J{Deterministic review, then agent vision}+ J -- score below threshold --> KK --> FJ -- pass --> L{More passes?}L -- yes --> F- L -- no --> M[Animation-ready Three.js model]+ L -- no --> N[Derive rig from component tree]+ N --> O[Bind SkinnedMesh to one shared Skeleton]+ O --> M[Animation-ready Three.js model]```+Two things in that diagram are easy to miss and both were added because a render-only loop missed+them. **Geometric gates run before the browser does** — a bald patch or a self-intersection is found+on points, so a pass is never spent rendering geometry that was already wrong. And **routing can+refuse**: below a confidence of `0.82` the track resolves to `request-input` rather than guessing+whether the subject is a weapon or a character.+### Material reference hand-offMaterial identity is an executable sub-pipeline rather than prose in the spec:@@ -68,10 +80,16 @@ the ObjectSculptSpec, render evidence, review history, and deterministic gates s- **Suitability** — is the image a viable 3D target at all.- **Pre-spec and strict-quality** — blocks code generation until the spec is deep enough for the object's complexity (no single-root spec for a compound object).-- **Screenshot feedback** — `continue` requires a render plus a comparison sheet plus a passing vision score.+- **Chirality** — every `-l`/`-r` pair must be a sagittal mirror, not a rotated copy. Rotation preserves handedness, so a pair built by negating two axes comes out as the same hand twice. Hard, at spec time.+- **Scalp exposure (hair subjects)** — hard, and it runs on geometry before anything is drawn, because a bald patch is interior and an outline metric cannot see it.+- **Screenshot feedback** — `continue` requires a render plus a comparison sheet plus a passing vision score, plus banded interior difference: silhouette IoU reads roughly 11% of figure cells and scored a deleted face identically to a finished one.- **Action-ready** — the model exposes a runtime hierarchy (pivots, sockets, colliders, destruction groups) via `root.userData.sculptRuntime`.- **Attachment correctness** — child parts (handles, limbs, tubes) declare how they join their parent, so nothing floats in mid-air.- **Material and lighting realism** — independent PBR channels and real lights, never albedo aliased into roughness.+- **Rig payload** — for character builds, the joint/parent/matrix payload is validated before a `THREE.Skeleton` is bound. It proves structural integrity only; pose stress and likeness stay separate gates.++The ordering matters more than the list. Everything measurable on geometry runs *before* the browser,+so a pass is never spent rendering something already known to be wrong.### Self-correction@@ -124,7 +142,44 @@ The net effect: you still get a faithful 3D model from an image, but the expensi| `stage1_intake/run_vision_adapter.py` | Invoke optional isolated SAM2, MediaPipe, and Depth Anything evidence adapters. || `stage3_build/bake_projected_texture.py` | Emit a projection/UV-bake descriptor for photo-texture projection. |-The `grimoire/` folder holds the detailed rubrics each gate applies (validation, pre-spec assessment, procedural patterns, material and lighting realism, attachment correctness, action-ready models, self-correction).+### Character rig — `stage5_rig/`++| Script | Role |+| --- | --- |+| `stage5_rig/rig_spec.py` | Derive and validate a `RigSpec` from the component tree, so bones cannot drift from the geometry they drive. |+| `stage5_rig/geodesic_skinning.py` | Vertex weights from distance measured *through the solid*; partitions rigid roles out of smooth skinning. |+| `stage5_rig/emit_rig.py` | The one vertex-weight implementation, ported into the generator rather than duplicated. |+| `stage5_rig/validate_rig_payload.py` | Blocking payload-integrity gate before binding a `THREE.Skeleton`. Proves structure only, never pose or likeness. |++### Hair++| Script | Role |+| --- | --- |+| `stage1_intake/extract_hair_evidence.py` | Otsu hair/skin split, banded coverage, the hairline, highlight band, root-to-tip delta. Unseen views report `notObserved`. |+| `stage2_spec/hair_profile.py` | The hairstyle schema and its validation. Roots are scalp `(u, v)`; an absolute root is a hard error. |+| `_shared/scalp_field.py` | Signed distance to a skull built from the head component's own ring stack. |+| `stage4_review/scalp_exposure.py` | **HARD** gate: finds bald patches on geometry, before any render. |+| `stage4_review/hair_gate.py` | Soft gate: banded coverage, hairline and highlight offsets. Subordinate to scalp exposure. |++### Chirality, review and structure++| Script | Role |+| --- | --- |+| `_shared/chirality.py` | Left/right as code. `check_pair` catches a rotated pair; `medial_lateral_bias` catches a pair wrong the same way on both sides. |+| `stage4_review/interior_difference.py` | Appearance difference *inside* the silhouette, banded by height. Required on every visual pass. |+| `stage4_review/divine_eye.py` | The deterministic multi-signal render evaluator; hard gates plus soft signals with self-uncertainty. |+| `stage4_review/vlm_gate.py` | Gated, calibrated last layer. Never consulted on a hard-gate failure. |+| `stage4_review/fit_params.py` | Bounded, gate-aware analysis-by-synthesis parameter fitting. |+| `stage4_review/self_intersection.py`, `turntable_gate.py`, `attachment_anchor.py`, `joint_loops.py`, `pairwise_penetration.py`, `geometry_integrity.py` | Off-axis, placement and topology gates that run on geometry rather than pixels. |+| `stage3_build/visual_hull.py`, `uv_unwrap.py`, `morph_targets.py`, `decimate.py` | Hull carving, UV unwrap, blendshape targets and quadric decimation. |+| `_shared/pipeline_routing.py` | Fail-closed weapon/character routing; below `0.82` confidence it resolves to `request-input`. |+| `_shared/workflow_state.py`, `state.py`, `next.py` | The resumable ordered checklist and the next-action reporter. |++This table is a curated selection, not an inventory — `forge/` holds around ninety modules. The+executable reference, with every flag and the measurement behind each threshold, is+`grimoire/scripts.md`; the gate-by-gate contract is `grimoire/review/gates_reference.md`. The rest of+`grimoire/` holds the rubrics each gate applies (validation, pre-spec assessment, procedural patterns,+material and lighting realism, attachment correctness, action-ready models, self-correction).---@@ -132,4 +187,5 @@ The `grimoire/` folder holds the detailed rubrics each gate applies (validation,- An `ObjectSculptSpec` JSON: the full component tree, materials, repetition systems, sockets, and a recorded review history for every pass.- A TypeScript `createObjectNameModel(spec, options)` factory returning a `THREE.Group`, with `root.userData.sculptRuntime` exposing nodes, sockets, colliders, and destruction groups.+- For character builds, `root.userData.rig`: the bones, one shared `Skeleton`, bone order and index map, and a `bound` flag that is computed rather than asserted — it is true only when every skinned mesh actually bound.- A render plus comparison sheets documenting the fidelity at each pass.diff --git a/docs/GLB_CHARACTER_ANIMATION_PROMPT.md b/docs/GLB_CHARACTER_ANIMATION_PROMPT.mdnew file mode 100644index 0000000..ade1716--- /dev/null+++ b/docs/GLB_CHARACTER_ANIMATION_PROMPT.md@@ -0,0 +1,273 @@+# GLB-reference character prompt — animation++The third of three prompts for the GLB-mediated character route. It rigs and animates a character+whose surfaces are already built and gated.++| | |+|---|---|+| **Use it when** | the figure looks right standing still, and has passed the build pass's gates including `joint_loops.py` |+| **Do not use it when** | the surface has not been gated — a skeleton bound to an ungated surface makes surface defects read as art problems; or `joint_loops.py` fails, which is a surface-build finding and no amount of weight tuning reaches it |+| **Before this** | [build](GLB_CHARACTER_PROMPT.md), then [polish](GLB_CHARACTER_POLISH_PROMPT.md) |++## Read this before using it++**This is reference material, not a guarantee.** The measured figures throughout — dominant-bone+percentages, capsule radii, gait harmonics — came from one character with one axis convention. They+are there to show *what to measure and what a wrong answer looks like*, not to be copied. The sign+table in Step 5 in particular must be re-derived for your own axes; copying it is how a gait ends up+playing backwards.++**Do not run this before the shape is settled.** Rigging is the most expensive pass to redo, because+a surface change invalidates the weights. Finish the build and polish passes first.++## The prompt++Copy everything inside this block, fill the placeholders, and paste it as a single message.++````markdown++Rig and animate a GLB-referenced img2threejs character whose surfaces are already built.++## Inputs++```+GLB reference: <ABSOLUTE_PATH_TO_GLB>+Demo id: <subject-id>+Showcase root: <PATH_TO_img2threejs-showcase>+Motion wanted: <e.g. "walk cycle", "idle breathing", "draw the sword">+Props: <rigid items held or worn — sword, bag, tool — or NONE>+```++## What can and cannot be 1:1 here++This is the stage where "match the GLB exactly" most often means matching something the file does+not contain. Establish which case you are in at Step 0 and put it in the report:++| | |+|---|---|+| **Rig, when the GLB carries none** | `skinCount: 0`, `animationCount: 0`, no `JOINTS_0`/`WEIGHTS_0` — there is nothing to match. Every joint, radius, weight and pose is **computed**, and each must trace to a measurement of this model or a cited gait dataset. Report them as computed, never as matched. |+| **Rig, when the GLB carries one** | matching it is a different deliverable from this pipeline's contract, and a licence question. Stop and ask. |+| **Bind-pose proportions** | these *are* 1:1 and must stay so. Joint positions come from the built model's own measured bounds, so a knee sits where the shin mesh ends. Re-measure after rigging: binding must not move a vertex at rest. |+| **Anything below the cell size** | a resolution statement, not a rig problem. |++The one 1:1 check this stage owes the reference: **the rest pose must still match.** Re-run the band+comparison after binding. A skeleton that shifts the figure at phase 0 has broken the shape the+previous two passes measured, and no motion quality makes that acceptable.++## Step 0 — Confirm there is no rig to copy++```bash+python3 forge/stage1_intake/probe_glb.py <glb> --out glb-probe.json+python3 -c "import json;d=json.load(open('glb-probe.json'));print({k:d.get(k) for k in ('skinCount','animationCount')})"+```++A baseline asset typically reports `skinCount: 0`, `animationCount: 0` and carries no `JOINTS_0` or+`WEIGHTS_0` on any primitive. If so, **state it in the report**: there is no rig in the asset, so+every joint position, every skin weight and every pose is computed here. That is also the honest+answer to "which part of this is actually procedural" — this part is, with no alternative.++If the GLB *does* carry skins or animations, stop and ask. Copying them is a different deliverable+with a different licence question, and this pipeline's contract is that reference topology and+materials are never copied into the factory.++## Step 1 — Joints from the model's own bounds, never from fractions of figure height++The factory's parts are named anatomically, so a knee goes where the shin mesh actually **ends**.+Measure the built model and write the table into the rig module. From a real subject:++```+boots y -0.001 .. 0.167 ankle at the boot top+shins y 0.158 .. 0.433 knee at the shin top+trousers y 0.522 .. 1.154 hip below the belt+torso+arms y 0.974 .. 1.602 shoulder below the neck+head y 1.525 .. 1.749+```++`left` and `right` are the **character's**, so left is at positive x when the figure faces +z. Write+which way your figure faces and derive from it; do not carry this sentence over unchecked.++## Step 2 — Skin, unless the part is a rigid prop++Decide per part, and record the reason:++- **Skinned**, when one mesh spans a joint. A single node holding the torso *and both arms* cannot+ swing an arm by rigid rotation, and linear blend skinning is also what keeps the surface+ continuous at hip and shoulder where rigid parts open a visible gap.+- **One bone, rigid**, for a prop. A sword allowed both the arm chain and the pelvis measured+ **44.7% arm-bound and 55% hip-bound** — one solid object split between the hand holding it and the+ body it hangs beside, so every arm movement stretched it and the scabbard tore away from the hilt.+ A rigid prop wants a rigid attachment.++## Step 3 — Weights fail in three independent ways. All three need fixing.++This is the core of the stage. Each defect below has a different cause and **none of the three fixes+addresses another**. Skipping any one produces motion that looks wrong in a way weight tuning cannot+reach.++### 3a. Influence radius, not point distance — or the torso follows the arms++Weighting by raw distance to a bone *segment* reads the body inside out: a torso surface sits+~0.15 m from the spine axis while the arms hang against the ribs, so an arm segment passes **closer+to a chest vertex than the spine does**. Measured on a first build, the torso mesh's dominant bone+was `shoulder.L` at **25.2%**, ahead of `spine` at **21.8%** — and the torso duly swung with the arm.++Give each bone a capsule radius taken from measured part widths (that subject: torso x-extent+~0.26 m without the arms, shins ~0.11, boots ~0.14). A vertex inside the capsule is distance zero,+so a thick bone owns its own volume and a thin one cannot reach across the body.++### 3b. Geodesic distance, not euclidean — or raising an arm drags the chest++Straight-line distance does not care whether the path stays **inside** the model. An arm resting+against the ribs is millimetres from the chest *through the air*. Every character whose limbs touch+the body has this defect; it is not an edge case, it is the default pose.++```bash+python3 forge/stage5_rig/geodesic_skinning.py <mesh.json> --bones <bones.json> \+ --resolution <N> --out weights.json --json+```++Geodesic voxel binding (Dionne & de Lasa, SCA 2013) voxelizes the mesh, seeds each bone's voxels and+propagates without crossing empty space, so the arm-to-chest path is forced around through the+shoulder and is correctly long. Purely geometric — no training data, no time constants, nothing to+tune at bind or pose time.++### 3c. A region → bone allow-list — because geometry cannot know how clothing is worn++A capsule radius fixes "the torso follows the arm". It cannot fix "the belt pouch follows the left+leg", because a pouch at hip height genuinely **is** closest to the thigh bone and no radius makes+that false. What makes it wrong is knowledge the geometry does not carry and the part list does: a+pouch is worn on the **belt**, so it rides the pelvis however the leg swings.++Measured before the allow-list existed:++| Part | Dominant bones | Consequence |+|---|---|---|+| cage canister | `hip.L` 66%, `hips` 34% | would swing with the left leg |+| belt pouch, left | `hip.L` 100% | same |+| head and hair | `chest` 58%, `head` 39% | skull owned by the chest capsule — the head would not turn |+| trousers | 13.8% arm-**dominated** | the arm swings and the trousers go with it |++So write an explicit `{region: [allowed bones]}` map. Constrain a rigid prop to one bone. Leave+regions that genuinely span the figure (bare skin, a full-body garment) unconstrained, and say which+ones you left open.++## Step 4 — Topology has to survive being bent++```bash+python3 forge/stage4_review/joint_loops.py <meshes.json> --min-loops <N> --json+```++A joint with too few rings of geometry across it collapses when it flexes: the elbow pinches into a+crease, the knee loses its volume, the shoulder folds. **No amount of weight tuning fixes it**,+because the vertices needed to describe a bent surface do not exist.++Automatic remeshing does not reliably produce deformation-grade topology — but that constraint+belongs to pipelines that *receive* a finished mesh. A procedural generator writes its own topology+and can place loops at joints by construction. If this gate fails, the fix is upstream in the+surface build, not in the rig.++## Step 5 — The gait, as a Fourier series++A walk is not a sine wave and a clamp is not a joint.++The knee flexes **twice** per stride, and that is the whole difference between a walk and a limp: a+small stance flexion of ~18° just after heel strike absorbing the load, and a large swing flexion of+~60° while the foot clears the ground. A single-peak curve reads as disjointed **no matter how the+amplitudes are tuned** — that is the symptom to recognise.++Fit coefficients to standard sagittal joint angles for adult level walking, sampled every 5% of the+cycle from heel strike. Four harmonics were enough to reproduce them to:++```+hip 0.27° knee 0.89° ankle 1.44°+```++A truncated Fourier series is smooth by construction — infinitely differentiable and periodic — so+unlike a clamped sine it cannot introduce a kink at any amplitude, and the cycle joins itself+seamlessly at the wrap. The opposite leg is exactly half a cycle behind.++**Verify the signs by forward kinematics, never by eye.** Reversed signs play the gait backwards, and+because the pose stays symmetric it is not obvious — it just reads as moonwalking. Measure where the+ankle actually goes:++| Sign choice | Result |+|---|---|+| hip +, knee − | 66% of the cycle moving forward, peak +2.49 / −4.02 — fast **backward** |+| hip −, knee + | 34%, peak +4.02 / −2.49 — fast forward, **40% swing** |++The second matches the human 40% swing / 60% stance split. Bone local axes are world-aligned in this+rig, so a positive x rotation swings a downward limb to −Z, i.e. backward: hip flexion is −x, knee+flexion +x, ankle dorsiflexion −x. **Re-derive this for your own axis convention rather than copying+the signs.**++Expose one `scale` that trims every joint together, so the walk can be made gentler without changing+its shape. Tuning individual amplitudes is what breaks the coordination between them.++If the figure carries something in one hand, damp that arm's counter-swing — a full swing on an armed+hand reads as flailing rather than walking.++## Step 6 — Chirality: a reflection, never a rotation++Negate the lateral axis only. Reflecting inverts triangle winding, so flip it back or `flatShading`+lights the limb as though lit from behind.++```bash+python3 forge/stage2_spec/validate_sculpt_spec.py <spec> --json+```++That runs two checks that catch two different defects, and you need both: `validate_chirality`+catches a rotation mistaken for a reflection, and `medial_lateral_bias` against a reference catches a+pair wrong the **same** way on both sides — which any mirror test passes by construction.++## Step 7 — Gate through the cycle. A rest pose proves nothing about motion.++Every static gate is necessary and none is sufficient: the defects this stage introduces only exist+while the figure moves. Sample the cycle — at minimum phase 0, 0.25, 0.5, 0.75 — and run the+penetration and coverage gates **at each phase**.++```bash+python3 forge/stage5_rig/validate_rig_payload.py --payload <payload.json> # BEFORE binding any Skeleton+node $IMG2THREEJS_SHOWCASE_ROOT/pipelines/warrior/export_mesh_geometry.mjs --url <preview?phase=0.25> --out meshes-p25.json+python3 forge/stage4_review/self_intersection.py meshes-p25.json --json+python3 forge/stage4_review/pairwise_penetration.py meshes-p25.json --allow <nameA,nameB> --json+python3 forge/stage4_review/vertex_region_gate.py --geometry meshes-p25.json --palette palette.json --expect expect.json --json+python3 forge/stage4_review/swept_arc_gate.py --geometry meshes-p25.json --component <name> --expect <spec> --json+python3 forge/stage4_review/turntable_gate.py --capture 0=p25-front.png --capture 90=p25-right.png --json+```++- `validate_rig_payload.py` runs **before** any `THREE.Skeleton` is constructed. A bad payload+ becomes a bound skeleton, and a bound skeleton's defects read as art problems.+- `pairwise_penetration.py --allow` is for pairs genuinely permitted to touch. Every pair you allow+ is a pair the gate stops checking — list them in the report.+- `swept_arc_gate.py` fits a curved component's actual bend radius, angular span and taper. A+ silhouette IoU passes a straight cone that occupies roughly the right cells; this does not.+- Read `sampledVertexCount`, `unmeasuredAttachments` and `missingAzimuths` before believing a clean+ verdict — each names what the gate did not look at.++Then **watch the animation**, not a strip of stills: a foot that slides, a limb that pops at the+wrap, and a prop that lags one frame are all invisible in single frames and obvious in motion.++## Standing rules++1. **No typed-in anatomical constant.** Every joint position, radius and amplitude traces to a+ measurement of this model or to a cited gait dataset. Anything else is labelled an assumption.+2. **One change, then re-measure.** Weight defects mask each other; two changes at once means the+ next agent inherits a fact that is not true.+3. **A rest pose is not evidence of motion**, and a strip of stills is not evidence of a cycle.+4. **Never claim "done" when it is "improved."** Name what still reads wrong and at which phase.++## Report format++Per step: what was **measured** (the number and the command that printed it), what was **decided**,+what is still **unverified**. Close with:++- the dominant-bone percentage per region, before and after the allow-list;+- every pair passed to `--allow`, and why;+- which phases were gated and which were not;+- every constant you could not measure, named as an assumption;+- what still reads wrong in motion.++"This motion cannot be reached from this rig without changing the surface topology" is a valid+result — `joint_loops.py` failing is exactly that finding. Say it rather than tuning weights against+a joint with no geometry in it.+````diff --git a/docs/GLB_CHARACTER_POLISH_PROMPT.md b/docs/GLB_CHARACTER_POLISH_PROMPT.mdnew file mode 100644index 0000000..4f99c63--- /dev/null+++ b/docs/GLB_CHARACTER_POLISH_PROMPT.md@@ -0,0 +1,194 @@+# GLB-reference character prompt — polish++The second of three prompts for the GLB-mediated character route. Its whole job is to **localise** a+mismatch to one band and one named cause before anything is changed.++| | |+|---|---|+| **Use it when** | the build **completed** and the result does not look like the GLB |+| **Do not use it when** | the surfaces were never built — if the emitted header's `nodes` count is below `CHARACTER_NODES`, you are looking at the cross-section loft and nothing here will fix it; re-run [build](GLB_CHARACTER_PROMPT.md). Also not for motion, which is [animation](GLB_CHARACTER_ANIMATION_PROMPT.md) |+| **Next** | [animation](GLB_CHARACTER_ANIMATION_PROMPT.md), once the shape holds still |++## Read this before using it++**This is reference material, not a guarantee.** The failure-mode table below covers the modes this+pipeline is known to produce. Your subject can present one that is not in it — the prompt tells the+agent to say so and stop rather than force a match to the nearest row, and that is the correct+outcome, not a failure of the prompt.++**Respect the stop rule; this is the prompt most easily abused.** It is a+one-change-then-re-measure loop with a deliberate termination condition. Running it repeatedly in+the hope of convergence produces changes nobody can attribute and burns a full re-splat each round.+Two consecutive changes that fail to improve the targeted measurement means the remaining gap is not+reachable by config — that is information, and the honest output is which regions still differ and+by how much.++## The prompt++Copy everything inside this block, fill the placeholders, and paste it as a single message.++````markdown++Polish a GLB-referenced img2threejs character that built successfully but does not match the+reference.++## Inputs++```+GLB reference: <ABSOLUTE_PATH_TO_GLB>+Demo id: <subject-id>+Showcase root: <PATH_TO_img2threejs-showcase>+Config used: <path to the .env from the init run>+Complaint: <in your own words — "the face is a lumpy shell", "the arm is on the wrong side">+```++## What "1:1" means in a polish pass++Every gap you close must close **towards a measured figure**, never towards taste. Before changing+anything, write down the reference value and the current value:++| Parameter | Reference source | Current value read from |+|---|---|---|+| Per-band width and depth | `mesh_reference_compare.py` on the GLB | the same run's candidate columns |+| Band centroid, lateral and depth | same | same — a limb the right size on the wrong side |+| Figure height and node extents | `probe_glb.py` bounds | the built model's bounds |+| Base colour per region | `baseColorTexture` x `baseColorFactor`, sRGB decoded to linear | the emitted vertex colours |+| Roughness, metalness per region | `metallicRoughnessTexture` x its factors | the emitted material record |+| Vertex and triangle count per node | the round-trip check against the binary | the emitted header |++A change that improves the render but moves a value **away** from the reference is not a fix; it is+taste overriding measurement, and it will fail the next comparison. Revert it and say why.++Two limits are not defects and must not be chased: anything finer than the node's cell size is a+resolution statement, and texture images, the UV atlas and normal maps are deliberately not copied+per SKILL.md's contract, so surface detail below the cell is authored and must be labelled authored.++## Rule for this whole pass++**One change, then re-measure.** Never two. If two things change and the number improves, you do+not know which one did it, and the next agent inherits a fact that is not true.++**Do not chase zero.** Where a residual is unavoidable, make it *one-sided* and say so. Chasing+zero error on a socket rim cost three rebuilds; two constants that made the error always-proud+fixed the actual complaint.++## Step 1 — Confirm the build is the one you are looking at++Before diagnosing geometry, rule out the boring causes. The init pipeline has two stages that+skip with a message and still exit 0.++```bash+python3 forge/next.py --state .img2threejs/state.json+ls -l public/head-<subject-id>/sdf-surfaces*.bin+git diff --stat -- src/demos/<subject-id>/+grep -A12 "Measured, on the level shipped here" src/demos/<subject-id>/surfaceData.ts+```++Read the emitted header's `nodes`, `vertices` and `bytes per vertex`. If `nodes` is smaller than+`CHARACTER_NODES`, the surface for the region you are complaining about **was never built** — the+figure you are looking at is the cross-section loft, which is convex per horizontal slice and+cannot hold a finger gap, a cupped palm or the inside of a sleeve. Stop here and re-run the init+pipeline with that node included; nothing in this document will fix it.++Also check which tier the page loaded. `x3` uses a bigger cell than `x2`, so `x3` is the *coarser*+tier and belongs in `surfaceDataLow.ts`. A swapped mapping shows up as a model that looks *worse*+at a higher quality setting, and `git diff` is the only thing that catches it.++## Step 2 — Measure where it is wrong, band by band++This is the tool that answers "where", and it takes two GLBs:++```bash+python3 forge/stage4_review/mesh_reference_compare.py <glb> <candidate.glb> \+ --bands 24 --align landmarks --json+```++**The candidate GLB has to be exported, and no script in this repo does it.** Write it once, ~20+lines, using the pattern in `$IMG2THREEJS_SHOWCASE_ROOT/pipelines/warrior/export_mesh_geometry.mjs`:+Playwright to the preview URL, `window.__IMG2THREEJS_VIEWER__.scene.getObjectByName('<root-name>')`,+`updateMatrixWorld(true)`, then three.js's `GLTFExporter`. `mesh_reference_compare.py` composes real+node matrices specifically so the `matrix` nodes that `GLTFExporter` writes can be read.++Both meshes are normalised **feet-to-height**, not bounding-box top — the top of a bbox is whatever+pokes up highest, which is exactly what differs between two subjects. Read per band:++| Field | What a non-zero value means |+|---|---|+| `widthDelta`, `depthDelta` | wrong size at that height |+| `centroidXDelta`, `centroidZDelta` | right size, wrong **place** — a limb on the wrong side passes any width-only check |+| `lowPct` / `highPct` vs `widthFull` | body vs prop: percentiles report the body, raw extent keeps a genuine prop difference visible |+| `meanBandError` | rank the bands; fix the worst one only |+| `note` | read it before trusting the alignment |++## Step 3 — Name the failure mode before touching a config++Match the measured signal to one cause. These are the modes this pipeline actually produces:++| Signal | Cause | The one change |+|---|---|---|+| Region reads lumpy/blobby, features below ~1 mm absent | cell too coarse for that node | lower **only that node's** cell in `CHARACTER_CELL_SIZES_JSON` |+| A fold that doubles back is filled in (eyelid, nostril, sleeve interior) | node still on the 2.5D loft | add that node to `CHARACTER_NODES` — no spoke count fixes this |+| Node inside-out, or exploded | `NORMAL` missing or flipped on that primitive | the SDF field's sign comes entirely from the normal, so a wrong normal *inverts* the surface rather than roughening it |+| `widthDelta` positive while silhouette IoU **falls** | spoke count above the node's density ceiling | re-run `measure_density_convergence.py`, take `min(convergence, density ceiling)` |+| Too dark or over-saturated, correct shape | colour space | vertex colours are baked sRGB-decoded to linear; `material.color` must stay white or it tints the bake |+| `centroid*Delta` non-zero, `widthDelta` ~0 | placement, not shape | fix the transform; do not touch cells or spokes |+| Right shape, wrong handedness | rotation used where a reflection was needed | negate the lateral axis only, then flip triangle winding back — `validate_chirality` catches this, `medial_lateral_bias` catches a pair wrong the *same* way on both sides |+| Looks worse at higher quality | swapped tier mapping | `git diff` the three `surfaceData*.ts` |+| A joint creases or loses volume the moment it bends | not a weight problem — too few edge loops across the joint | `joint_loops.py <meshes.json> --min-loops N`; the fix is upstream in the surface build, no weight tuning reaches it |++If the signal matches none of these, say so and stop. A change with no named mechanism is a guess+even when it improves the number.++## Step 4 — Change one thing, rebuild that node only++```bash+IMG2THREEJS_SHOWCASE_ROOT=<showcase> \+ integrations/glb_character_pipeline/build-character.sh --config <subject-id>.env --skip-build+```++`--skip-build` stops before the tsc/vite pass while you iterate on geometry. Narrow+`CHARACTER_NODES` to the node under investigation so a pass costs minutes, not an hour — then+restore the full list before the final run.++## Step 5 — Prove it improved, against the previous capture++An absolute score cannot tell improvement from regression. Keep the previous capture directory:++```bash+node integrations/glb_character_pipeline/node/capture-character.mjs \+ --demo <subject-id> --out work/cmp/<tag-new> --root-name <root>+node integrations/glb_character_pipeline/node/compare_views.mjs \+ work/cmp/<tag-new> work/cmp/<tag-previous>+python3 forge/stage4_review/interior_difference.py <baseline.png> <render.png> --json+python3 forge/stage4_review/diagnose_render_multi_angle.py --reference <ref> \+ --orbit 0.png --orbit 40.png --orbit 90.png --json+```++Measure **inside** the silhouette. Silhouette IoU reads ~11% of figure cells: a model with its face+deleted scored 0.8803 — identical to four decimals to the finished face. Re-run Step 2's band+comparison and confirm the band you targeted improved **and no other band got worse**.++Then look at the render at 0°, 40° and a grazing angle. A surface can score 2.49 mm median accuracy+and still read as a lumpy, hole-riddled shell. If the render and the metric disagree, the render is+right.++## Stop rule++Stop and report when either holds:++- the worst band's `meanBandError` is within the reference's own per-band spread, or+- **two consecutive single changes** failed to improve the targeted measurement.++The second is not failure, it is information: it means the remaining gap is not reachable by+config, and the honest output is which regions still differ and by how much. Report per band: what+was measured, which mode you named, what you changed, and what the re-measurement said — including+the changes you reverted.++"This cannot reach the requested fidelity from this reference" is a valid result.+````++---++Once the shape holds still, motion is a separate pass with its own failure modes — a rig bound to+an ungated surface hides surface defects as art problems. Use+[`GLB_CHARACTER_ANIMATION_PROMPT.md`](GLB_CHARACTER_ANIMATION_PROMPT.md).diff --git a/docs/GLB_CHARACTER_PROMPT.md b/docs/GLB_CHARACTER_PROMPT.mdnew file mode 100644index 0000000..28502a4--- /dev/null+++ b/docs/GLB_CHARACTER_PROMPT.md@@ -0,0 +1,354 @@+# GLB-reference character prompt — build++The first of three prompts for the GLB-mediated character route. It takes a GLB reference and+produces the procedural TypeScript that reproduces its measured surface, with no `.glb` or `.bin`+fetched at runtime.++| | |+|---|---|+| **Use it when** | you have a GLB reference and no built surfaces yet |+| **Do not use it when** | there is no GLB — use the single-image route in the README's "Driving it harder" section instead; or the build already completed and the result merely looks wrong, which is [`GLB_CHARACTER_POLISH_PROMPT.md`](GLB_CHARACTER_POLISH_PROMPT.md) |+| **Next** | [polish](GLB_CHARACTER_POLISH_PROMPT.md) if the shape is off, then [animation](GLB_CHARACTER_ANIMATION_PROMPT.md) |++## Read this before using it++**This is reference material, not a guarantee.** It is written to be general, so it cannot know your+subject: a different GLB has different node counts, different feature sizes and a different density+ceiling, and the measured figures quoted throughout came from one character. Expect to adapt it, and+expect the first run not to be the last. Treat every number in it as an example of *what to measure*,+not as a value to copy.++**Do not re-run it hoping for a better result.** A full pass re-splats every node and is expensive.+If it completed and the shape is wrong, the polish prompt localises the cause in one node instead of+rebuilding all of them. Re-run this prompt only when the surfaces were never built — the emitted+header's `nodes` count tells you which case you are in.++## Requirements++- an img2threejs checkout, and a companion `img2threejs-showcase` checkout for the emitted demo+- `uv sync --project integrations/glb_character_pipeline` — the integration needs numpy and Pillow,+ which the stdlib-only core deliberately does not+- a multipart GLB is preferred; a merged single-node asset still runs, but cannot support per-region+ claims++## The prompt++Copy everything inside this block, fill the placeholders, and paste it as a single message.++````markdown++Build a procedural Three.js character from a GLB reference using img2threejs 1.5.1.++## Inputs++```+GLB reference: <ABSOLUTE_PATH_TO_GLB>+Diffuse texture: <ABSOLUTE_PATH_TO_PNG_OR_NONE>+Reference photo: <PATH_OR_NONE>+Demo id: <subject-id> # lowercase, hyphenated; becomes src/demos/<id>/+Showcase root: <PATH_TO_img2threejs-showcase>+Real longest dimension: <e.g. 1.70 m> # sanity-checks scale; never used to scale+```++## Force these to the GLB, 1:1++The reference is a **measurement instrument**, and every parameter it genuinely carries is measured+rather than approximated. Do not eyeball, round or "improve" any of these — each one has a source in+the file and a check that proves it landed:++| Parameter | Where it comes from in the GLB | How it is verified |+|---|---|---|+| Size and bounds | node world-space bounds from `probe_glb.py` / `label_glb_nodes.py` | figure height and per-node extents match the reference; state the residual in metres |+| Proportions | per-band widths and centroids | `mesh_reference_compare.py --align landmarks` — `widthDelta`, `depthDelta`, `centroidXDelta`, `centroidZDelta` per band |+| Geometry | the node's own vertex cloud, contoured by Surface Nets at the measured cell | `verify_cells.mjs` reports 0 collisions and every quad rebuilt; `verify_roundtrip.mjs` reports identical vertex and triangle counts, identical colours, and positions inside the quantisation step |+| Base colour | `baseColorTexture` x `baseColorFactor`, sampled per vertex, sRGB decoded to linear | median per-region colour delta against the reference render |+| Roughness, metalness | `metallicRoughnessTexture` green/blue x `roughnessFactor` / `metallicFactor`, per vertex | the emitted material record per region, read back and compared to the GLB's declared figures |+| Region count and extents | `semanticDecomposition` plus measured bounds | every node in `CHARACTER_NODES` appears in the emitted header's `nodes` |++Scale is measured, never fitted: the cell size that recovers the grid must be the measured value+carried at full precision. Rounding a measured 1.504 mm to 1.50 mm shifted the recovered grid and+produced 110,695 apparent cell collisions on one node.++### Three things cannot be 1:1, and saying so is part of the job++Read this before promising a match, because two of the three are commonly assumed to be available+and are not:++1. **Rigging and animation are usually absent from the asset.** A baseline GLB typically reports+ `skinCount: 0`, `animationCount: 0` and carries no `JOINTS_0` or `WEIGHTS_0`. There is nothing to+ match 1:1 — every joint, weight and pose is computed, and that must be reported as computed. If+ your GLB *does* carry skins or animations, say so and ask before proceeding: matching them is a+ different deliverable from this pipeline's contract.+2. **Texture images, the UV atlas and normal maps are deliberately not copied.** SKILL.md's contract+ is that the reference's "topology/materials are never copied into the factory", and the skill+ emits no textures. The *values* above are measured and baked into code; the image files are not+ shipped. A surface detail below the cell size — leather grain, fabric weave — is therefore+ authored procedurally, and must be labelled authored, not measured.+3. **Anything finer than the cell.** A 1.5 mm cell cannot carry a 0.2 mm feature. That is a+ resolution statement, not a tuning failure; lower the cell for that node or state the limit.++If a build genuinely needs the baseline's UV atlas, the pipeline has one gated escape hatch —+`CHARACTER_ALLOW_BASELINE_UV=1`, which `bake_atlas_uvs.py` refuses to run without. It is documented+as an authorised deviation from the no-baseline-assets rule. Using it means the result is no longer+purely code-only, so say that in the report rather than leaving the claim standing.++## Step 0 — Preflight. Do this before anything else and stop if any line fails.++Stage 2 is what makes the result resemble the GLB, and it **skips silently** when numpy is+missing — the run then exits 0 having produced nothing, and Stage 3 re-encodes an empty+directory. That is the single most common way this pipeline "succeeds" and returns a figure+that looks nothing like the reference. So prove the environment first:++```bash+cd <img2threejs checkout>+uv sync --project integrations/glb_character_pipeline+export IMG2THREEJS_GLB_PIPELINE_PYTHON="uv run --project integrations/glb_character_pipeline python3"+$IMG2THREEJS_GLB_PIPELINE_PYTHON -c "import numpy, PIL; print('numpy', numpy.__version__)"+export IMG2THREEJS_SHOWCASE_ROOT=<PATH_TO_img2threejs-showcase>+head -c 4 "<ABSOLUTE_PATH_TO_GLB>" | xxd # must read glTF+```++Report the printed numpy version. If the import fails, **stop** — do not continue with a+plan to "encode whatever is on disk".++## Step 1 — Write the decoder, because nothing ships one++The integration emits `surfaceData.ts` containing `import type { EncodedNode } from './surfaceCodec'`.+**That file does not exist for a new demo and no script creates it.** Write+`src/demos/<subject-id>/surfaceCodec.ts` now, before any encoding, or Step 5's round-trip+check has nothing to verify against. Do not point `CHARACTER_CODEC` at another demo's copy —+it round-trips against the wrong contract and the mistake surfaces as geometry, not an error.++The decode contract, per node, in stream order:++| Field | Encoding |+|---|---|+| `cells` | zigzag varint deltas of the linear cell index, ascending |+| `offsets` | position inside the cell, 8 bits per axis |+| `colours` | 8 bits per channel, already in the linear working space |+| `edges` | one byte per cell: bit `2*axis` = grid edge changes sign, bit `2*axis+1` = quad winds the other way |+| `exceptions` | varint count, then four vertex indices per quad the edge byte cannot express |++Recover the grid origin from the builder's own rule, `lo = cloud_min - 5*cell`. Never sweep+for a sub-cell phase: a search-based origin put 29% of vertices in an already-occupied cell.+Normals are not carried — recompute them from the rebuilt triangles.++## Step 2 — Intake, and label nodes by measurement++```bash+python3 forge/state.py init --state .img2threejs/state.json --reference <glb> \+ --profile character --spec object-sculpt-spec.json+python3 forge/stage1_intake/probe_glb.py <glb> --out glb-probe.json+python3 forge/stage1_intake/label_glb_nodes.py <glb> --out nodes.json --min-confidence 0.6+```++Baseline assets name nodes `root.0..root.N`, so any name-reading labeller produces confident+nonsense. Labels come from measured world-space bounds and stay+`hypothesis-requires-render-confirmation` until a render confirms them.++Record per node: vertex and triangle count, whether `NORMAL` exists (**required** — the SDF+splat takes its sign from the normal, so a missing or flipped normal inverts the surface+rather than roughening it), and whether the primitive is single-material.++If `semanticDecomposition` reports a merged single-node asset, per-region claims are not+available from this reference. Say so, then **continue** with the whole figure as one region+and label it `single-region-merged-asset` — do not stop, and do not invent regions.++## Step 3 — Measure the spoke budget, per node++```bash+$IMG2THREEJS_GLB_PIPELINE_PYTHON \+ integrations/glb_character_pipeline/python/measure_density_convergence.py <glb> <node>+```++Take **`min(convergence, density ceiling)`** from the printed tables. The tool prints+`density ceiling (largest median <= 5%)` as its last line; if it says `none`, no spoke count+is supported for that node — say so rather than picking the floor.++Convergence alone is wrong and fails silently: `radial_outline` interpolates an empty+angular bin from its neighbours, so past a node's density the outline bridges arcs holding+no vertices and bulges outward.++| Measured on a real subject | |+|---|---|+| 192 spokes on a glove | area grew to 1.12x baseline while IoU *fell* 0.896 → 0.867 |+| same run, a pouch | pushed 7.96 mm past its own point cloud |+| slice count | error vs a 320-slice reference is U-shaped: 13.81% at 20, **8.59% at 40**, 13.83% at 160 |++Slice count stays at 40. A thinner band holds fewer points and its percentile turns to+sampling noise.++## Step 4 — Write one config file, then run one command++Every sub-script defaults to `girl-character` paths (`public/mesh/girl-character-baseline.glb`,+`src/demos/girl-character/surfaceData.ts`, `public/head`). Calling them by hand without the+orchestrator's exports reads the wrong GLB and writes into another demo. **Use the+orchestrator.**++Copy `integrations/glb_character_pipeline/configs/example.env`, fill it, and keep the level+mapping exactly as below — `x3` uses a bigger cell, so `x3` is the *coarser* tier:++```bash+CHARACTER_GLB="public/mesh/<subject-id>-baseline.glb" # symlink, gitignored+CHARACTER_DIFFUSE="work/<subject-id>-textures/diffuse.png"+CHARACTER_DEMO_ID="<subject-id>"+CHARACTER_NODES="<every node, coarsest-first>"+CHARACTER_LEVELS="x2 x3 default"+CHARACTER_BIN_DIR="public/head-<subject-id>"+CHARACTER_OUT_PREFIX="public/head-<subject-id>/sdf-surfaces"+CHARACTER_WORKDIR="work/head-<subject-id>"+CHARACTER_WORK_TAG="-<subject-id>"+CHARACTER_CODEC="src/demos/<subject-id>/surfaceCodec.ts"+CHARACTER_CELL_SIZES_JSON="<abs path to cells.json>"+CHARACTER_SECTION_REGIONS_JSON="<abs path>" # all three or Stage 1 silently skips+CHARACTER_SPOKES_JSON="<abs path>"+CHARACTER_CROSS_SECTIONS="src/demos/<subject-id>/crossSections.ts"+CHARACTER_DEST_X2="src/demos/<subject-id>/surfaceDataMedium.ts"+CHARACTER_DEST_X3="src/demos/<subject-id>/surfaceDataLow.ts"+CHARACTER_DEST_DEFAULT="src/demos/<subject-id>/surfaceData.ts"+```++**Start with every node in `CHARACTER_NODES`.** Fidelity to the reference comes almost+entirely from the implicit surface; a cross-section is 2.5D — one radius per angular bin — so+no spoke count recovers a fold that doubles back, such as an eyelid or a nostril. Demote a+node to the loft only after measuring that its noise already matches the baseline.++Cell size is **per node**, from the finest real feature: a lid margin is ~1 mm, so a head+needs ~1.5 mm; a large smooth surface carries nothing that fine and doubles the file for no+measured gain below ~2.5 mm. **Do not round a measured cell.** Stage 3 recovers the grid+origin from it, so rounding a measured 1.504 mm to 1.50 mm shifted the grid and produced+110,695 apparent cell collisions on one node.++Then:++```bash+IMG2THREEJS_SHOWCASE_ROOT=<showcase> \+ integrations/glb_character_pipeline/build-character.sh --config <subject-id>.env+```++## Step 5 — Verify the run did what it printed++Exit 0 does not mean the stages ran. Both Stage 1 and Stage 2 skip with a message and+succeed. After the run, assert all four:++```bash+ls -l public/head-<subject-id>/sdf-surfaces*.bin # non-empty, mtime from this run+grep -c "^" src/demos/<subject-id>/crossSections.ts # regenerated, not left alone+git diff --stat -- src/demos/<subject-id>/ # the tiers that changed+grep -A12 "Measured, on the level shipped here" src/demos/<subject-id>/surfaceData.ts+```++The orchestrator runs `verify_cells.mjs` before every encode and `verify_roundtrip.mjs` after;+both must report **0 collisions, every quad rebuilt**. Read the emitted header's `nodes`,+`vertices` and `bytes per vertex` and confirm they match what Step 3 and Step 4 decided —+that header is machine-printed and is the one number in this pipeline nobody can fudge.++`git diff` each written file. A swapped level→destination mapping writes valid, wrong data+with no error anywhere: tsc, the round-trip check and the build all pass, because the module+is still valid TypeScript carrying a valid but mislabelled level.++## Step 6 — Surface features++Hair is a hard gate on geometry **before** any render:++```bash+python3 forge/stage4_review/scalp_exposure.py --rings <rings.json> --hair-points <points.json>+```++A bald patch is always a failure; a coverage shortfall is a soft signal and never on its own+authorises widening the masses.++A facial feature placed as a thin card (eye, lash) is fitted as a clean analytic form seated+into its socket. Do not chase zero error on the socket rim — make the residual **one-sided**+(always proud, never sunk). Chasing zero cost three rebuilds; two constants fixed it.++Left/right is a **reflection**, never a rotation: negate the lateral axis only, then flip the+triangle winding back or `flatShading` lights the limb as though lit from behind. Two defects+need two checks and `validate_sculpt_spec.py <spec> --json` runs both: `validate_chirality`+catches a rotation mistaken for a reflection, and `medial_lateral_bias` catches a pair wrong+the *same* way on both sides, which any mirror test passes by construction.++**Rigging and motion are not part of this pass.** A skeleton bound to a surface that has not+been gated yet hides surface defects as art problems. Finish Step 8, then use+[`GLB_CHARACTER_ANIMATION_PROMPT.md`](GLB_CHARACTER_ANIMATION_PROMPT.md).++## Step 7 — Gates. One viewpoint is not evidence.++```bash+python3 forge/stage4_review/turntable_gate.py \+ --capture 0=front.png --capture 90=right.png --capture 180=rear.png --capture 270=left.png --json+node $IMG2THREEJS_SHOWCASE_ROOT/pipelines/warrior/export_mesh_geometry.mjs --url <preview> --out meshes.json+python3 forge/stage4_review/self_intersection.py meshes.json --json+python3 forge/stage4_review/attachment_anchor.py <spec> --measured measured.json --json+python3 forge/stage4_review/interior_difference.py <baseline.png> <render.png> --json+python3 forge/stage4_review/diagnose_render_multi_angle.py ...+```++Measure **inside** the silhouette. Silhouette IoU reads ~11% of figure cells: a model with+its face deleted scored 0.8803, identical to four decimals to the finished face.++Read `sampledVertexCount`, `unmeasuredAttachments` and `missingAzimuths` before believing a+clean verdict — each names the part of the model the gate did not look at. A hole through a+skull, a hat at hip height and a floating charm all survived eight front-only review rounds+before these gates existed.++Each gate answers one question and no gate covers another's:++| Gate | The question it answers |+|---|---|+| `self_intersection.py` | does a mesh cross itself |+| `pairwise_penetration.py <meshes> --allow A,B` | do two parts interpenetrate — every allowed pair is one it stops checking |+| `objectness.py --reference R --render X` | does the render read as the object at all |+| `check_part_coverage.py --spec S --manifest M` | is every part the spec promised actually present |+| `vertex_region_gate.py --geometry G --palette P` | did each region land where it was claimed |+| `swept_arc_gate.py --geometry G --component C` | is a curved component actually that curve — a silhouette IoU passes a straight cone |+| `joint_loops.py <meshes>` | is there enough geometry at each joint to survive bending later |++Run `joint_loops.py` in *this* pass even though nothing moves yet. It fails on the surface+build, not on the rig, and finding that out after a skeleton is bound wastes the rig work.++## Step 8 — Prove nothing is fetched, then look at it++Move the binary directory out of the way, rebuild, re-render. Renders that still appear with+that directory absent **are** the proof.++```bash+npx tsc --noEmit && npx vite build+```++**Then actually look at the render, at 0°, 40° and a grazing angle.** Metrics hide structural+failure: a surface can score 2.49 mm median accuracy and still read as a lumpy, hole-riddled+shell rather than a face. If the render and the metric disagree, the render is right.++## Standing rules++1. **The GLB is a measurement instrument, never an asset.** Symlink it into `public/mesh/`+ (gitignored). No topology, material or texture is copied into the factory, and no+ `.glb`/`.bin` is fetched by the running demo.+2. **Verify magic bytes, never HTTP status.** A dev server returns `index.html` with HTTP 200+ for a missing file. Check for `glTF`.+3. **Measure before every numeric decision.** Any spoke count, cell size, threshold or tier+ you cannot point at a printed measurement for is a guess — label it one.+4. **Colour is baked sRGB-decoded to linear**; Three.js treats a vertex-colour attribute as+ already in the working space. Keep `material.color` white or it tints the bake.+5. **State gate at start, at resume, and before every correction:**+ `python3 forge/next.py --state .img2threejs/state.json`. Exit 3 / `status=stopped` is a+ hard stop — report and ask.+6. **Never claim "done" when it is "improved."** Name what still does not match.++## Report format++Per step: what was **measured** (the number and the command that printed it), what was+**decided** from it, what remains **unverified**. Close with per-region confidence and the+regions no view covered; every number you could not measure, named as an assumption; and what+still does not match the reference.++"This cannot reach the requested fidelity from this reference" is a valid result. Say it+rather than producing a confident wrong surface.+````++---++If this run completes and the result still does not match the reference, do **not** re-run this+prompt — it rebuilds everything and localises nothing. Use+[`GLB_CHARACTER_POLISH_PROMPT.md`](GLB_CHARACTER_POLISH_PROMPT.md) instead.diff --git a/docs/HAIR_PIPELINE.md b/docs/HAIR_PIPELINE.mdnew file mode 100644index 0000000..604d8fe--- /dev/null+++ b/docs/HAIR_PIPELINE.md@@ -0,0 +1,209 @@+# Hair++How img2threejs reconstructs hair, what it measures, and — as precisely as possible — what it does+not know.++## Why hair needed its own subsystem++Before this, hair was one ellipsoid (`forge/stage2_spec/new_sculpt_spec.py`, the `("hair", "Hair",+"ellipsoid", ...)` entry). A grep for `hair` across `forge/` returned 44 lines, all of them tests,+comments or material ids, and none of them logic. Three pieces existed and were unused: a+`faceLandmarks.hairline` slot no generator read, a `fiber-strand` topology class with nothing behind+it, and the `tapered-sweep` primitive with zero specs using it.++The gap that mattered was not geometric. In one session, four separate diagnoses of a single+hairstyle were wrong, and every one was caught only by measurement after the fact. So the gates were+built before the generators.++## The measurement that set the architecture++The reference this pipeline calibrates against is+`public/references/low-poly-humanoid-glb/human_pbr.glb`. Probing it:++| property | value |+| --- | --- |+| vertices | 570,400 |+| triangles | 1,000,000 |+| meshes / materials | 1 / 1, merged |+| textures | diffuse, normal, metallic-roughness (PNG) |+| skins / animations | 0 / 0 |++`forge/stage1_intake/probe_glb.py` reports `"reliableSemanticBoundary": "multipart-glb-required"` —+the hair cannot be separated from the body by metadata.++Surface roughness, measured as the radial step between adjacent azimuth bins at each height:++| height band | radial step | vs control |+| --- | --- | --- |+| crown / hair | 0.00338 | **+8%** |+| upper hair | 0.00405 | +30% |+| hair / brow | 0.00429 | +38% |+| face / cheek | 0.00385 | +23% |+| **torso (no hair, control)** | **0.00312** | — |++The hair surface is as smooth as a torso. At a head radius of ~0.10 that is roughly 3.4 mm of+undulation, where a real lock is 10–30 mm. **The reference contains no lock geometry.** Its entire+strand appearance is in the diffuse and normal textures.++Two consequences follow, and they run in opposite directions to the obvious plan:++1. Since img2threejs emits code and no textures, the strand impression must come from **faceting and+ material response**, not from adding lock geometry.+2. The reference **cannot calibrate lock parameters**, because it has none to measure.++## Representation tiers++| tier | what it is | calibration |+| --- | --- | --- |+| `shell` (default) | a faceted mass hugging the scalp | measurable against the reference |+| `masses` | a shell plus a few named regional masses | envelope measurable |+| `locks` | individual tapered locks | **no ground truth available** |++`locks` is not forbidden. It emits a warning naming exactly why its numbers are derived rather than+observed. Unblocking it needs a multipart GLB with a separated, named hair mesh.++## Primitives++| primitive | verdict |+| --- | --- |+| `tapered-sweep` | preferred — curved spine, parallel transport, reaches a true point |+| `curve-sweep`, `lathe`, `ellipsoid` | allowed |+| `instanced-cluster` | allowed, for distant strand impressions only |+| `plane-card` | **rejected** — needs an alpha texture, which this pipeline cannot emit |+| `tube` | **rejected** — constant radius, reads as a noodle |+| `box` | **rejected** |++Enforced in `forge/stage2_spec/hair_profile.py` and again per-component in+`validate_sculpt_spec.py`.++## The stages++### Stage 1 — `extract_hair_evidence.py`++Measures from reference images: hair/skin split (Otsu, not a percentile — see below), banded dark+coverage across crown/mid/jaw, the hairline (writing the `faceLandmarks.hairline` slot that has+existed unfilled since v1.2), the specular band position, and the root-to-tip luminance delta.++It reports `notObserved` explicitly. A frontal-only set states that the rear of the head was never+seen, so nothing downstream authors a nape as if it were measured.++> **A trap worth recording.** The first implementation thresholded at a fixed percentile. That makes+> the reported hair fraction true by construction: it read 0.380, 0.384 and 0.382 across three+> different views of the same subject, which looks like agreement and is arithmetic. Otsu's+> between-class variance split fixed it, and the same three views now read 0.387 / 0.592 / 0.747 —+> front lowest because the face occupies it, rear highest.++### Stage 2 — `hair_profile.py`++**This stage defines and validates a schema. It does not compile one.** There is no+profile-to-`componentTree` compiler yet; a spec still authors its hair components directly, and the+profile's rules are enforced by the validator plus the `standProud` march the generator emits.+Writing that compiler is the next piece of work, and it is called out here because a schema reads+exactly like a working feature and this one is not one yet.++The schema has four blocks: `scalpComponentId` (the head component whose ring stack the scalp is+derived from, never authored twice), `hairline` (control points in scalp `(u, v)`), `flowField`+(part line, whorls, gravity, sweep — about six numbers, which is what makes a wide range of styles+reachable without authoring a direction per mass), and `masses[]`.++**Roots are `(u, v)` on the scalp, never absolute positions.** An absolute root is a hard validation+error. This is the same binding Blender uses for hair, where a curve root is a+`surface_uv_coordinate` on the emitter mesh, and it makes the recorded failure structurally+impossible rather than a matter of authoring care.++### Stage 3 — `standProud` and the clearance march++A component declares `standProud: {againstComponentId, clearance, maxPush}`. The generator emits+`applyStandProud`, which pushes every vertex outward along its **own radial spoke** until a signed+distance field reads at least `clearance`, capped at `maxPush`.++This is `hug` from the hand-written showcase demo, generalised into the skill. In that demo the+garment held its clearance as a measurement and worked; the hair held the same requirement as a+comment and broke. `maxPush` is required, not optional: an uncapped march walks inner vertices+through the target and out the far side.++Hair material comes from `hair.human.code-only` in the material reference — no maps, higher sheen+and anisotropy than the textured profile, because with no `anisotropyMap` and no `normalMap` those+are the only carriers left. A `rootTipGradient` emits vertex colours along the mass's own axis.++### Stage 4 — the gates++| gate | kind | catches |+| --- | --- | --- |+| `scalp_exposure.py` | **hard** | skull showing through, geometrically, before any render |+| `hair_gate.py` | soft | banded coverage delta, hairline offset, highlight-band offset |++The hard/soft split is the point. A bald patch is always wrong; a coverage shortfall is often the+right compromise. Conflating them is what produced the recorded regression: a shortfall was answered+by widening the masses, which pushed them off the skull.++`scalp_exposure` only counts hair that is **outside** the skull. A nearest-neighbour test would have+passed the failing build, because the vertices were still nearby — they had sunk below the surface.++### Stage 5 — rigging++Hair is **rigidly parented**, never smooth-skinned. `geodesic_skinning.RIGID_ROLES` excludes+`hair`, `detail`, `decal` and `panel`.++Measured on the test fixture: the geodesic distance from the neck joint to a crown vertex is 33.6+voxels against the head bone's 15.0, which at falloff power 3 leaves the **neck holding 8.1% of the+crown**. Turning the neck would shear the hair against the skull it sits on — and because+`standProud` and `scalpExposure` are bind-pose checks, no gate would ever see it.++Long hair that crosses a joint uses a short chain of bones with one mesh segment rigidly parented+per bone. Still no blended vertex weights.++## What this does not know++- **Lock parameters are derived, not measured.** Taper ratios, cross-section aspect, lock counts,+ whorl strengths. Listed in `hair_profile.UNCALIBRATED_FIELDS`, and any mass setting one without+ `uncalibrated: true` gets a warning. Precedent for why: a recovered build had eleven hair locks+ sharing a tip radius of 0.0327 to four decimal places, and nothing objected.+- **Every gate threshold in this subsystem is uncalibrated** and reports itself as such.+- **Dynamics is out of scope.** A single image contains no motion, so any hair simulation would be+ invention rather than reconstruction.+- **Strand-level hair is out of scope permanently**, by architecture. No textures, no alpha.+- **There is no `hairProfile` compiler.** The schema is validated; nothing turns it into components.+- **The `standProud` march can fail silently-ish.** A vertex that exhausts `maxPush` while still+ inside the target is counted and warned about at runtime (`geometry.userData.standProud`), but+ nothing fails the build over it. Measured on the shipped fixture: 2 of 8 sampled hair vertices sat+ 0.059 inside the skull against a 0.04 cap and could never have reached clear.+- **`scalp_exposure` measures spec-derived points, while the march displaces vertices at runtime.**+ So the gate does not measure the geometry that ships. Closing that means moving the march into+ Python at build time — the single largest improvement still available here.++## The recorded failure, in full++It is referenced throughout the code, so here it is once, completely.++The hair side masses of the low-poly humanoid demo were widened by hand to close a measured coverage+deficit (profile mid band: reference 41.5%, ours 7.8%).++| view | before | after | delta |+| --- | --- | --- | --- |+| profile | 46.8% | 43.2% | **−3.6** |+| left-profile | 61.4% | 59.0% | −2.5 |+| orbit−35 | 30.7% | 29.6% | −1.2 |+| front | 38.7% | 38.3% | −0.5 |+| orbit+35 | 25.7% | 25.3% | −0.4 |+| rear | 49.9% | 49.8% | −0.0 |+| **mean** | **42.2%** | **40.9%** | **−1.3** |++Worse on all six. Dark coverage went *down*. Crown scalp exposure, measured on the archived captures:++| view | before | after | delta |+| --- | --- | --- | --- |+| orbit+35 | 54.0% | 68.9% | **+14.9** |+| profile | 48.8% | 55.1% | +6.3 |+| front | 53.3% | 57.6% | +4.3 |+| orbit−35 | 43.3% | 44.3% | +1.0 |++The cause: `sectionedLoft` has a straight root-to-tip spine while the skull is convex, so thickening+a section moved the surface sideways rather than outward. The mass slid off the skull, the skull+became proud of the hair, and the render grew a bare strip. The invariant it broke was already+written in the file it broke in:++> EVERY piece must stand proud of the skull at its own height. Where the skull is proud of the hair,+> the head renders bald there.++Every gate in this subsystem exists to make that sentence arithmetic.diff --git a/docs/UPGRADE_PLAN.md b/docs/UPGRADE_PLAN.mdindex 506d12b..1cef9be 100644--- a/docs/UPGRADE_PLAN.md+++ b/docs/UPGRADE_PLAN.md@@ -306,7 +306,15 @@ Modified files:## 12. Open questions- Default `targetMinDetails` per tier - tune after the first detailed run.-- Hair strategy default: hair cards vs tube-along-curve per lock (perf vs look).+- ~~Hair strategy default: hair cards vs tube-along-curve per lock (perf vs look).~~ **RESOLVED.**+ Neither, as originally framed. See `docs/HAIR_PIPELINE.md`. Cards are rejected outright — a card+ needs an alpha texture to read as hair and this skill emits code with no textures, so it renders+ as an opaque rectangle. Swept volume (`tapered-sweep`) carries silhouette. But the measurement+ that decided it also reframed the question: on the reference GLB the hair surface roughness is+ 0.00338 against a torso control of 0.00312, meaning its hair is a **smooth shell** whose entire+ strand appearance lives in the diffuse and normal textures. Since those are unavailable, the+ strand impression has to come from faceting and material response, and the default representation+ tier is `shell`, not locks. Enforced in `forge/stage2_spec/hair_profile.py`.- Whether to ship a small parametric humanoid template file or generate it inline in the factory.- How far to build camera-solve and de-lighting in pure stdlib vs documenting an optional external step; both may need a pragmatic approximation first.- Whether `generativeAssist` should call an external API at all, or only accept a user-supplied base mesh (keeps the skill offline and asset-free by default).diff --git a/docs/materials/material-reference.json b/docs/materials/material-reference.jsonindex f4cd787..78f3deb 100644--- a/docs/materials/material-reference.json+++ b/docs/materials/material-reference.json@@ -39,7 +39,12 @@"policy": "Direct Three.js and glTF facts define property contracts. Per-material numbers are bounded starting priors and must be fitted against admitted image evidence and controlled renders."},"textureContract": {- "colorMaps": ["map", "emissiveMap", "sheenColorMap", "specularColorMap"],+ "colorMaps": [+ "map",+ "emissiveMap",+ "sheenColorMap",+ "specularColorMap"+ ],"colorMapColorSpace": "SRGBColorSpace","dataMaps": ["roughnessMap",@@ -77,17 +82,50 @@}},"legalRanges": {- "metalness": [0.0, 1.0],- "roughness": [0.0, 1.0],- "clearcoat": [0.0, 1.0],- "clearcoatRoughness": [0.0, 1.0],- "sheen": [0.0, 1.0],- "sheenRoughness": [0.0, 1.0],- "transmission": [0.0, 1.0],- "ior": [1.0, 2.333],- "anisotropy": [0.0, 1.0],- "iridescence": [0.0, 1.0],- "dispersion": [0.0, 1.0]+ "metalness": [+ 0.0,+ 1.0+ ],+ "roughness": [+ 0.0,+ 1.0+ ],+ "clearcoat": [+ 0.0,+ 1.0+ ],+ "clearcoatRoughness": [+ 0.0,+ 1.0+ ],+ "sheen": [+ 0.0,+ 1.0+ ],+ "sheenRoughness": [+ 0.0,+ 1.0+ ],+ "transmission": [+ 0.0,+ 1.0+ ],+ "ior": [+ 1.0,+ 2.333+ ],+ "anisotropy": [+ 0.0,+ 1.0+ ],+ "iridescence": [+ 0.0,+ 1.0+ ],+ "dispersion": [+ 0.0,+ 1.0+ ]},"sources": [{@@ -227,525 +265,2060 @@"materials": [{"id": "skin.human",- "aliases": ["skin", "human skin"],+ "aliases": [+ "skin",+ "human skin"+ ],"family": "skin","subtype": "human","finish": "natural","model": "dielectric-approximation","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.52, "range": [0.35, 0.7]},- "clearcoat": {"default": 0.12, "range": [0.0, 0.25]},- "clearcoatRoughness": {"default": 0.35, "range": [0.2, 0.6]},- "ior": {"default": 1.4, "range": [1.33, 1.5]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.52,+ "range": [+ 0.35,+ 0.7+ ]+ },+ "clearcoat": {+ "default": 0.12,+ "range": [+ 0.0,+ 0.25+ ]+ },+ "clearcoatRoughness": {+ "default": 0.35,+ "range": [+ 0.2,+ 0.6+ ]+ },+ "ior": {+ "default": 1.4,+ "range": [+ 1.33,+ 1.5+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["aoMap"],- "visualCues": ["warm dielectric diffuse response", "broad soft highlights", "pores and wrinkles at micro scale"],- "confusableWith": ["plastic.matte", "rubber.matte", "coating.paint-matte"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],- "limitations": ["MeshPhysicalMaterial has no true multilayer skin subsurface scattering"],- "sourceRefs": ["three.mesh-physical", "three.mesh-standard", "nvidia.faceworks", "activision.separable-sss", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "aoMap"+ ],+ "visualCues": [+ "warm dielectric diffuse response",+ "broad soft highlights",+ "pores and wrinkles at micro scale"+ ],+ "confusableWith": [+ "plastic.matte",+ "rubber.matte",+ "coating.paint-matte"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "MeshPhysicalMaterial has no true multilayer skin subsurface scattering"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.mesh-standard",+ "nvidia.faceworks",+ "activision.separable-sss",+ "mit.material-recognition"+ ]},{"id": "hair.human",- "aliases": ["hair", "human hair"],+ "aliases": [+ "hair",+ "human hair"+ ],"family": "hair","subtype": "human","finish": "strand-directional","model": "anisotropic-dielectric-approximation","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.45, "range": [0.3, 0.7]},- "anisotropy": {"default": 0.65, "range": [0.4, 1.0]},- "ior": {"default": 1.5, "range": [1.4, 1.6]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.45,+ "range": [+ 0.3,+ 0.7+ ]+ },+ "anisotropy": {+ "default": 0.65,+ "range": [+ 0.4,+ 1.0+ ]+ },+ "sheen": {+ "default": 0.45,+ "range": [+ 0.2,+ 0.8+ ]+ },+ "sheenRoughness": {+ "default": 0.35,+ "range": [+ 0.2,+ 0.6+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.4,+ 1.6+ ]+ }+ },+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap",+ "anisotropyMap"+ ],+ "optionalMaps": [+ "aoMap"+ ],+ "visualCues": [+ "elongated highlights follow strand or clump direction",+ "silhouette breakup",+ "dark masses retain directional specular"+ ],+ "confusableWith": [+ "fabric.velvet",+ "plastic.glossy",+ "rubber.matte"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "environment-reflection",+ "reference-beauty"+ ],+ "limitations": [+ "Use geometry clumps or cards for silhouette; a normal map cannot replace hair volume"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "pbrt.hair",+ "mit.material-recognition"+ ]+ },+ {+ "id": "hair.human.code-only",+ "aliases": [+ "hair code only",+ "procedural hair",+ "untextured hair"+ ],+ "family": "hair",+ "subtype": "human-code-only",+ "finish": "strand-directional",+ "model": "anisotropic-dielectric-approximation",+ "recipeBasis": "inferred-starting-prior",+ "renderPrior": {+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.38,+ "range": [+ 0.25,+ 0.6+ ]+ },+ "anisotropy": {+ "default": 0.8,+ "range": [+ 0.5,+ 1.0+ ]+ },+ "sheen": {+ "default": 0.6,+ "range": [+ 0.35,+ 0.9+ ]+ },+ "sheenRoughness": {+ "default": 0.3,+ "range": [+ 0.15,+ 0.5+ ]+ },+ "ior": {+ "default": 1.55,+ "range": [+ 1.45,+ 1.6+ ]+ }+ },+ "requiredMaps": [],+ "optionalMaps": [],+ "visualCues": [+ "one broad highlight band running across the mass, not per-strand speculars",+ "root darker than tip",+ "facet edges read as clump boundaries"+ ],+ "confusableWith": [+ "hair.human",+ "fabric.velvet",+ "plastic.glossy"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "No maps by construction: this pipeline emits code, so anisotropyMap and normalMap are unavailable and every value here has to carry the whole strand impression on its own.",+ "Priors are pushed above hair.human deliberately: on the reference scan the hair surface is smooth (radial roughness 0.00338 against a torso control of 0.00312) and its entire strand appearance lives in the diffuse and normal textures. Without those textures, sheen and anisotropy are the only remaining carriers.",+ "Not calibrated against a reference render. No multipart GLB with separated hair geometry exists to fit these against, so they are a documented starting point and not a measurement."+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "pbrt.hair"+ ],+ "colorPrior": {+ "sheenColor": {+ "default": "#fff6e8",+ "note": "REQUIRED whenever sheen > 0: three's default sheenColor is 0x000000 and the sheen term is a multiply by that colour, so sheen alone contributes exactly zero (WebGLMaterials.js:408). Warm off-white because a hair highlight carries the light's tint, not the hair's."+ }+ }+ },+ {+ "id": "skin.human.code-only",+ "aliases": [+ "skin code only",+ "procedural skin",+ "untextured skin"+ ],+ "family": "skin",+ "subtype": "human-code-only",+ "finish": "natural",+ "model": "clearcoat-over-warm-dielectric",+ "recipeBasis": "inferred-starting-prior",+ "renderPrior": {+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.55,+ "range": [+ 0.4,+ 0.75+ ]+ },+ "clearcoat": {+ "default": 0.18,+ "range": [+ 0.08,+ 0.32+ ]+ },+ "clearcoatRoughness": {+ "default": 0.38,+ "range": [+ 0.0525,+ 0.6+ ],+ "note": "The low bound is three's own floor: max(clearcoatRoughness, 0.0525) at lights_physical_fragment.glsl.js:72. A smaller number renders as exactly 0.0525."+ },+ "ior": {+ "default": 1.4,+ "range": [+ 1.33,+ 1.5+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap", "anisotropyMap"],- "optionalMaps": ["aoMap"],- "visualCues": ["elongated highlights follow strand or clump direction", "silhouette breakup", "dark masses retain directional specular"],- "confusableWith": ["fabric.velvet", "plastic.glossy", "rubber.matte"],- "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],- "limitations": ["Use geometry clumps or cards for silhouette; a normal map cannot replace hair volume"],- "sourceRefs": ["three.mesh-physical", "pbrt.hair", "mit.material-recognition"]+ "requiredMaps": [],+ "optionalMaps": [],+ "forbiddenProperties": [+ "transmission",+ "thickness",+ "attenuationDistance"+ ],+ "visualCues": [+ "broad soft highlight that moves with the light, not a tight specular dot",+ "warm diffuse base",+ "tone varies by region: forehead lighter, cheek warmer, jaw cooler"+ ],+ "confusableWith": [+ "plastic.matte",+ "rubber.matte",+ "skin.human"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "No maps by construction: this pipeline emits code, so map/roughnessMap/normalMap are unavailable and the whole skin impression rests on base colour, clearcoat and per-region tone.",+ "MeshPhysicalMaterial has no true multilayer subsurface scattering, and transmission is NOT a substitute -- it is a screen-space refraction (glass) model that on a closed body mesh renders a glassy figure and costs an extra render target. transmission/thickness are therefore forbidden on this family.",+ "clearcoatRoughness has geometryRoughness ADDED at shade time (lights_physical_fragment.glsl.js:73), so a value tuned on smooth geometry reads blurrier flat-shaded. Author it on the final tessellation.",+ "Not calibrated against a reference render. These are a documented starting point, not a measurement."+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "nvidia.faceworks"+ ]+ },+ {+ "id": "fabric.woven-matte.code-only",+ "aliases": [+ "fabric code only",+ "procedural cloth",+ "untextured cloth"+ ],+ "family": "fabric",+ "subtype": "woven-code-only",+ "finish": "matte",+ "model": "sheen-dielectric",+ "recipeBasis": "inferred-starting-prior",+ "renderPrior": {+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.9,+ "range": [+ 0.75,+ 1.0+ ]+ },+ "sheen": {+ "default": 0.7,+ "range": [+ 0.4,+ 1.0+ ]+ },+ "sheenRoughness": {+ "default": 0.85,+ "range": [+ 0.6,+ 1.0+ ],+ "note": "High for cotton/linen/wool: a broad soft rim. Drop toward 0.2 only for a visible satin rim, and never on sparse geometry where a tight rim lands on a few facets and reads as plastic."+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.45,+ 1.55+ ]+ }+ },+ "requiredMaps": [],+ "optionalMaps": [],+ "visualCues": [+ "diffuse body with a grazing-angle rim",+ "soft broad highlights",+ "folds and hems read as geometry, never as texture"+ ],+ "confusableWith": [+ "leather.matte",+ "rubber.matte",+ "plastic.matte",+ "fabric.woven-matte"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "No maps by construction, so sheen is the entire woven cue available.",+ "Enabling sheen DARKENS this material's own diffuse base by 0.157 x effective sheen strength (sheenEnergyComp, meshphysical.glsl.js:205). Author the base colour brighter by 1/(1-darkening) or the render lands darker than the reference at every non-grazing angle.",+ "Large folds and hems belong in geometry, per fabric.woven-matte. A code-only profile cannot fake them with a normal map.",+ "A garment shell with an open hem, cuff or collar must set side to DoubleSide; three defaults to FrontSide and culls the backfaces, so the opening renders as a hole.",+ "Not calibrated against a reference render."+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "khronos.sheen"+ ],+ "colorPrior": {+ "sheenColor": {+ "default": "#f2ece2",+ "note": "REQUIRED whenever sheen > 0. sheen and sheenColor are multiplied into ONE uniform before upload (WebGLMaterials.js:408), so they are a single degree of freedom -- extract the tint, keep sheen as an authored strength."+ }+ }},{"id": "fur.stylized",- "aliases": ["fur", "animal fur"],+ "aliases": [+ "fur",+ "animal fur"+ ],"family": "fur","subtype": "stylized","finish": "fibre-matte","model": "sheen-dielectric-approximation","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.78, "range": [0.55, 1.0]},- "sheen": {"default": 0.45, "range": [0.2, 0.8]},- "sheenRoughness": {"default": 0.75, "range": [0.5, 1.0]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.78,+ "range": [+ 0.55,+ 1.0+ ]+ },+ "sheen": {+ "default": 0.45,+ "range": [+ 0.2,+ 0.8+ ]+ },+ "sheenRoughness": {+ "default": 0.75,+ "range": [+ 0.5,+ 1.0+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["sheenColorMap", "sheenRoughnessMap", "aoMap"],- "visualCues": ["soft grazing response", "directional fibres", "broken outer silhouette"],- "confusableWith": ["fabric.velvet", "hair.human"],- "validationViews": ["neutral-studio", "grazing", "reference-beauty"],- "limitations": ["Geometry shells, tufts or cards are required for identity-scale fur"],- "sourceRefs": ["three.mesh-physical", "pbrt.hair", "khronos.sheen"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "sheenColorMap",+ "sheenRoughnessMap",+ "aoMap"+ ],+ "visualCues": [+ "soft grazing response",+ "directional fibres",+ "broken outer silhouette"+ ],+ "confusableWith": [+ "fabric.velvet",+ "hair.human"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Geometry shells, tufts or cards are required for identity-scale fur"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "pbrt.hair",+ "khronos.sheen"+ ]},{"id": "fabric.woven-matte",- "aliases": ["fabric", "cloth", "cotton", "linen"],+ "aliases": [+ "fabric",+ "cloth",+ "cotton",+ "linen"+ ],"family": "fabric","subtype": "woven","finish": "matte","model": "sheen-dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.85, "range": [0.7, 1.0]},- "sheen": {"default": 0.65, "range": [0.3, 1.0]},- "sheenRoughness": {"default": 0.75, "range": [0.5, 1.0]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.85,+ "range": [+ 0.7,+ 1.0+ ]+ },+ "sheen": {+ "default": 0.65,+ "range": [+ 0.3,+ 1.0+ ]+ },+ "sheenRoughness": {+ "default": 0.75,+ "range": [+ 0.5,+ 1.0+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["sheenColorMap", "sheenRoughnessMap", "aoMap"],- "visualCues": ["diffuse body with grazing-angle sheen", "woven directional microstructure", "soft broad highlights"],- "confusableWith": ["leather.matte", "rubber.matte", "plastic.matte"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],- "limitations": ["Large folds and hems belong in geometry"],- "sourceRefs": ["three.mesh-physical", "three.texture", "khronos.sheen", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "sheenColorMap",+ "sheenRoughnessMap",+ "aoMap"+ ],+ "visualCues": [+ "diffuse body with grazing-angle sheen",+ "woven directional microstructure",+ "soft broad highlights"+ ],+ "confusableWith": [+ "leather.matte",+ "rubber.matte",+ "plastic.matte"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Large folds and hems belong in geometry"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.texture",+ "khronos.sheen",+ "mit.material-recognition"+ ]},{"id": "fabric.silk-satin",- "aliases": ["silk", "satin"],+ "aliases": [+ "silk",+ "satin"+ ],"family": "fabric","subtype": "silk-satin","finish": "smooth-directional","model": "sheen-anisotropic-dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.32, "range": [0.18, 0.55]},- "sheen": {"default": 0.85, "range": [0.5, 1.0]},- "sheenRoughness": {"default": 0.4, "range": [0.2, 0.65]},- "anisotropy": {"default": 0.45, "range": [0.2, 0.8]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.32,+ "range": [+ 0.18,+ 0.55+ ]+ },+ "sheen": {+ "default": 0.85,+ "range": [+ 0.5,+ 1.0+ ]+ },+ "sheenRoughness": {+ "default": 0.4,+ "range": [+ 0.2,+ 0.65+ ]+ },+ "anisotropy": {+ "default": 0.45,+ "range": [+ 0.2,+ 0.8+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap", "anisotropyMap"],- "optionalMaps": ["sheenColorMap", "sheenRoughnessMap"],- "visualCues": ["bright moving grazing highlight", "directional weave response", "smooth drape"],- "confusableWith": ["plastic.glossy", "coating.paint-gloss", "fabric.woven-matte"],- "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],- "limitations": ["Highlight direction must follow the authored fibre tangent"],- "sourceRefs": ["three.mesh-physical", "khronos.sheen", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap",+ "anisotropyMap"+ ],+ "optionalMaps": [+ "sheenColorMap",+ "sheenRoughnessMap"+ ],+ "visualCues": [+ "bright moving grazing highlight",+ "directional weave response",+ "smooth drape"+ ],+ "confusableWith": [+ "plastic.glossy",+ "coating.paint-gloss",+ "fabric.woven-matte"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "environment-reflection",+ "reference-beauty"+ ],+ "limitations": [+ "Highlight direction must follow the authored fibre tangent"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "khronos.sheen",+ "google.filament-pbr"+ ]},{"id": "fabric.velvet",- "aliases": ["velvet", "nhung"],+ "aliases": [+ "velvet",+ "nhung"+ ],"family": "fabric","subtype": "velvet","finish": "pile-sheen","model": "sheen-dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.72, "range": [0.55, 0.95]},- "sheen": {"default": 1.0, "range": [0.75, 1.0]},- "sheenRoughness": {"default": 0.65, "range": [0.4, 0.9]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.72,+ "range": [+ 0.55,+ 0.95+ ]+ },+ "sheen": {+ "default": 1.0,+ "range": [+ 0.75,+ 1.0+ ]+ },+ "sheenRoughness": {+ "default": 0.65,+ "range": [+ 0.4,+ 0.9+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap", "sheenColorMap"],- "optionalMaps": ["sheenRoughnessMap", "aoMap"],- "visualCues": ["dark frontal body", "strong soft rim or grazing sheen", "pile direction changes tone"],- "confusableWith": ["fur.stylized", "hair.human", "fabric.woven-matte"],- "validationViews": ["neutral-studio", "grazing", "reference-beauty"],- "limitations": ["Short pile is an approximation without a fibre shader"],- "sourceRefs": ["three.mesh-physical", "khronos.sheen", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap",+ "sheenColorMap"+ ],+ "optionalMaps": [+ "sheenRoughnessMap",+ "aoMap"+ ],+ "visualCues": [+ "dark frontal body",+ "strong soft rim or grazing sheen",+ "pile direction changes tone"+ ],+ "confusableWith": [+ "fur.stylized",+ "hair.human",+ "fabric.woven-matte"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Short pile is an approximation without a fibre shader"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "khronos.sheen",+ "google.filament-pbr"+ ]},{"id": "leather.matte",- "aliases": ["leather", "matte leather"],+ "aliases": [+ "leather",+ "matte leather"+ ],"family": "leather","subtype": "natural-or-synthetic","finish": "matte-worn","model": "dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.62, "range": [0.35, 0.85]},- "clearcoat": {"default": 0.08, "range": [0.0, 0.3]},- "clearcoatRoughness": {"default": 0.45, "range": [0.2, 0.8]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.62,+ "range": [+ 0.35,+ 0.85+ ]+ },+ "clearcoat": {+ "default": 0.08,+ "range": [+ 0.0,+ 0.3+ ]+ },+ "clearcoatRoughness": {+ "default": 0.45,+ "range": [+ 0.2,+ 0.8+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["aoMap", "clearcoatMap"],- "visualCues": ["irregular grain", "worn edges become smoother", "creases darken without becoming metallic"],- "confusableWith": ["fabric.woven-matte", "rubber.matte", "plastic.matte"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],- "limitations": ["Single images rarely prove natural versus synthetic leather"],- "sourceRefs": ["three.mesh-physical", "three.mesh-standard", "adobe.pbr-guide-2", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "aoMap",+ "clearcoatMap"+ ],+ "visualCues": [+ "irregular grain",+ "worn edges become smoother",+ "creases darken without becoming metallic"+ ],+ "confusableWith": [+ "fabric.woven-matte",+ "rubber.matte",+ "plastic.matte"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Single images rarely prove natural versus synthetic leather"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.mesh-standard",+ "adobe.pbr-guide-2",+ "mit.material-recognition"+ ]},{"id": "metal.steel-polished",- "aliases": ["polished steel", "chrome", "stainless steel"],+ "aliases": [+ "polished steel",+ "chrome",+ "stainless steel"+ ],"family": "metal","subtype": "steel","finish": "polished","model": "conductor","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 1.0, "range": [1.0, 1.0]},- "roughness": {"default": 0.12, "range": [0.03, 0.25]},- "anisotropy": {"default": 0.0, "range": [0.0, 0.15]}+ "metalness": {+ "default": 1.0,+ "range": [+ 1.0,+ 1.0+ ]+ },+ "roughness": {+ "default": 0.12,+ "range": [+ 0.03,+ 0.25+ ]+ },+ "anisotropy": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.15+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "metalnessMap"],- "visualCues": ["neutral tinted environment reflection", "sharp high-contrast highlights", "little diffuse body colour"],- "confusableWith": ["metal.aluminum", "coating.metallic-paint", "plastic.glossy"],- "validationViews": ["neutral-studio", "environment-reflection", "grazing", "reference-beauty"],- "limitations": ["A meaningful environment map is mandatory; flat lighting cannot validate polished metal"],- "sourceRefs": ["three.mesh-standard", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "metalnessMap"+ ],+ "visualCues": [+ "neutral tinted environment reflection",+ "sharp high-contrast highlights",+ "little diffuse body colour"+ ],+ "confusableWith": [+ "metal.aluminum",+ "coating.metallic-paint",+ "plastic.glossy"+ ],+ "validationViews": [+ "neutral-studio",+ "environment-reflection",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "A meaningful environment map is mandatory; flat lighting cannot validate polished metal"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "three.pmrem",+ "gltf.2",+ "khronos.gltf-pbr",+ "adobe.pbr-guide-2",+ "google.filament-pbr"+ ]},{"id": "metal.steel-brushed",- "aliases": ["brushed steel", "machined steel"],+ "aliases": [+ "brushed steel",+ "machined steel"+ ],"family": "metal","subtype": "steel","finish": "brushed","model": "anisotropic-conductor","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 1.0, "range": [1.0, 1.0]},- "roughness": {"default": 0.35, "range": [0.2, 0.55]},- "anisotropy": {"default": 0.85, "range": [0.5, 1.0]}+ "metalness": {+ "default": 1.0,+ "range": [+ 1.0,+ 1.0+ ]+ },+ "roughness": {+ "default": 0.35,+ "range": [+ 0.2,+ 0.55+ ]+ },+ "anisotropy": {+ "default": 0.85,+ "range": [+ 0.5,+ 1.0+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap", "anisotropyMap"],- "optionalMaps": ["metalnessMap"],- "visualCues": ["elongated highlight aligned to brushing", "neutral conductor reflection", "parallel micro-scratches"],- "confusableWith": ["metal.aluminum", "plastic.glossy"],- "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],- "limitations": ["Anisotropy direction must agree with geometry tangent and visible brushing"],- "sourceRefs": ["three.mesh-physical", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap",+ "anisotropyMap"+ ],+ "optionalMaps": [+ "metalnessMap"+ ],+ "visualCues": [+ "elongated highlight aligned to brushing",+ "neutral conductor reflection",+ "parallel micro-scratches"+ ],+ "confusableWith": [+ "metal.aluminum",+ "plastic.glossy"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "environment-reflection",+ "reference-beauty"+ ],+ "limitations": [+ "Anisotropy direction must agree with geometry tangent and visible brushing"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.pmrem",+ "gltf.2",+ "khronos.gltf-pbr",+ "adobe.pbr-guide-2",+ "google.filament-pbr"+ ]},{"id": "metal.aluminum",- "aliases": ["aluminum", "aluminium"],+ "aliases": [+ "aluminum",+ "aluminium"+ ],"family": "metal","subtype": "aluminum","finish": "satin","model": "conductor","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 1.0, "range": [1.0, 1.0]},- "roughness": {"default": 0.3, "range": [0.15, 0.55]},- "anisotropy": {"default": 0.2, "range": [0.0, 0.8]}+ "metalness": {+ "default": 1.0,+ "range": [+ 1.0,+ 1.0+ ]+ },+ "roughness": {+ "default": 0.3,+ "range": [+ 0.15,+ 0.55+ ]+ },+ "anisotropy": {+ "default": 0.2,+ "range": [+ 0.0,+ 0.8+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "anisotropyMap"],- "visualCues": ["bright neutral conductor", "soft satin highlight unless polished", "often fine machining direction"],- "confusableWith": ["metal.steel-polished", "coating.metallic-paint"],- "validationViews": ["neutral-studio", "environment-reflection", "grazing"],- "limitations": ["Steel versus aluminium may require context or metadata"],- "sourceRefs": ["three.mesh-standard", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "anisotropyMap"+ ],+ "visualCues": [+ "bright neutral conductor",+ "soft satin highlight unless polished",+ "often fine machining direction"+ ],+ "confusableWith": [+ "metal.steel-polished",+ "coating.metallic-paint"+ ],+ "validationViews": [+ "neutral-studio",+ "environment-reflection",+ "grazing"+ ],+ "limitations": [+ "Steel versus aluminium may require context or metadata"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "three.pmrem",+ "gltf.2",+ "khronos.gltf-pbr",+ "adobe.pbr-guide-2",+ "google.filament-pbr"+ ]},{"id": "metal.copper",- "aliases": ["copper"],+ "aliases": [+ "copper"+ ],"family": "metal","subtype": "copper","finish": "polished-or-aged","model": "coloured-conductor","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 1.0, "range": [1.0, 1.0]},- "roughness": {"default": 0.28, "range": [0.08, 0.65]}+ "metalness": {+ "default": 1.0,+ "range": [+ 1.0,+ 1.0+ ]+ },+ "roughness": {+ "default": 0.28,+ "range": [+ 0.08,+ 0.65+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "metalnessMap", "aoMap"],- "visualCues": ["warm red-orange conductor reflection", "patina may create rough dielectric corrosion regions"],- "confusableWith": ["metal.brass", "coating.metallic-paint"],- "validationViews": ["albedo-unlit", "environment-reflection", "grazing", "reference-beauty"],- "limitations": ["Patina and oxidation require region masks rather than one uniform metal recipe"],- "sourceRefs": ["three.mesh-standard", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "metalnessMap",+ "aoMap"+ ],+ "visualCues": [+ "warm red-orange conductor reflection",+ "patina may create rough dielectric corrosion regions"+ ],+ "confusableWith": [+ "metal.brass",+ "coating.metallic-paint"+ ],+ "validationViews": [+ "albedo-unlit",+ "environment-reflection",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Patina and oxidation require region masks rather than one uniform metal recipe"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "gltf.2",+ "khronos.gltf-pbr",+ "adobe.pbr-guide-2",+ "google.filament-pbr"+ ]},{"id": "metal.brass",- "aliases": ["brass", "bronze"],+ "aliases": [+ "brass",+ "bronze"+ ],"family": "metal","subtype": "brass-bronze","finish": "polished-or-aged","model": "coloured-conductor","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 1.0, "range": [1.0, 1.0]},- "roughness": {"default": 0.3, "range": [0.1, 0.65]}+ "metalness": {+ "default": 1.0,+ "range": [+ 1.0,+ 1.0+ ]+ },+ "roughness": {+ "default": 0.3,+ "range": [+ 0.1,+ 0.65+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "aoMap", "metalnessMap"],- "visualCues": ["warm yellow-to-brown conductor reflection", "aged recesses darken and roughen"],- "confusableWith": ["metal.gold", "metal.copper", "coating.metallic-paint"],- "validationViews": ["albedo-unlit", "environment-reflection", "grazing", "reference-beauty"],- "limitations": ["Brass versus bronze versus gold may require context or metadata"],- "sourceRefs": ["three.mesh-standard", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "aoMap",+ "metalnessMap"+ ],+ "visualCues": [+ "warm yellow-to-brown conductor reflection",+ "aged recesses darken and roughen"+ ],+ "confusableWith": [+ "metal.gold",+ "metal.copper",+ "coating.metallic-paint"+ ],+ "validationViews": [+ "albedo-unlit",+ "environment-reflection",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Brass versus bronze versus gold may require context or metadata"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "gltf.2",+ "khronos.gltf-pbr",+ "adobe.pbr-guide-2",+ "google.filament-pbr"+ ]},{"id": "metal.gold",- "aliases": ["gold"],+ "aliases": [+ "gold"+ ],"family": "metal","subtype": "gold","finish": "polished","model": "coloured-conductor","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 1.0, "range": [1.0, 1.0]},- "roughness": {"default": 0.22, "range": [0.08, 0.45]}+ "metalness": {+ "default": 1.0,+ "range": [+ 1.0,+ 1.0+ ]+ },+ "roughness": {+ "default": 0.22,+ "range": [+ 0.08,+ 0.45+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "metalnessMap"],- "visualCues": ["yellow conductor reflection rather than yellow diffuse paint", "strong environment-dependent highlight"],- "confusableWith": ["metal.brass", "coating.metallic-paint"],- "validationViews": ["albedo-unlit", "environment-reflection", "grazing", "reference-beauty"],- "limitations": ["Gold identity should not be inferred from yellow albedo alone"],- "sourceRefs": ["three.mesh-standard", "three.pmrem", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-2", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "metalnessMap"+ ],+ "visualCues": [+ "yellow conductor reflection rather than yellow diffuse paint",+ "strong environment-dependent highlight"+ ],+ "confusableWith": [+ "metal.brass",+ "coating.metallic-paint"+ ],+ "validationViews": [+ "albedo-unlit",+ "environment-reflection",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Gold identity should not be inferred from yellow albedo alone"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "three.pmrem",+ "gltf.2",+ "khronos.gltf-pbr",+ "adobe.pbr-guide-2",+ "google.filament-pbr"+ ]},{"id": "coating.painted-metal",- "aliases": ["painted metal", "coated metal"],+ "aliases": [+ "painted metal",+ "coated metal"+ ],"family": "coating","subtype": "paint-over-metal","finish": "gloss-or-satin","model": "coated-dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.1]},- "roughness": {"default": 0.45, "range": [0.2, 0.7]},- "clearcoat": {"default": 0.75, "range": [0.0, 1.0]},- "clearcoatRoughness": {"default": 0.12, "range": [0.02, 0.35]},- "ior": {"default": 1.5, "range": [1.35, 1.65]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.1+ ]+ },+ "roughness": {+ "default": 0.45,+ "range": [+ 0.2,+ 0.7+ ]+ },+ "clearcoat": {+ "default": 0.75,+ "range": [+ 0.0,+ 1.0+ ]+ },+ "clearcoatRoughness": {+ "default": 0.12,+ "range": [+ 0.02,+ 0.35+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.35,+ 1.65+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "clearcoatMap", "clearcoatRoughnessMap", "metalnessMap"],- "visualCues": ["diffuse paint colour under a separate glossy coat", "chips may expose metallic substrate"],- "confusableWith": ["plastic.glossy", "metal.gold", "metal.steel-polished"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "environment-reflection", "reference-beauty"],- "limitations": ["Intact paint is dielectric; exposed substrate needs a separate region or mask"],- "sourceRefs": ["three.mesh-physical", "gltf.2", "khronos.gltf-pbr", "adobe.pbr-guide-1", "adobe.pbr-guide-2"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "clearcoatMap",+ "clearcoatRoughnessMap",+ "metalnessMap"+ ],+ "visualCues": [+ "diffuse paint colour under a separate glossy coat",+ "chips may expose metallic substrate"+ ],+ "confusableWith": [+ "plastic.glossy",+ "metal.gold",+ "metal.steel-polished"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "environment-reflection",+ "reference-beauty"+ ],+ "limitations": [+ "Intact paint is dielectric; exposed substrate needs a separate region or mask"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "gltf.2",+ "khronos.gltf-pbr",+ "adobe.pbr-guide-1",+ "adobe.pbr-guide-2"+ ]},{"id": "plastic.glossy",- "aliases": ["glossy plastic", "acrylic"],+ "aliases": [+ "glossy plastic",+ "acrylic"+ ],"family": "plastic","subtype": "generic-polymer","finish": "glossy","model": "dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.28, "range": [0.12, 0.5]},- "clearcoat": {"default": 0.2, "range": [0.0, 0.6]},- "clearcoatRoughness": {"default": 0.18, "range": [0.05, 0.4]},- "ior": {"default": 1.5, "range": [1.4, 1.65]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.28,+ "range": [+ 0.12,+ 0.5+ ]+ },+ "clearcoat": {+ "default": 0.2,+ "range": [+ 0.0,+ 0.6+ ]+ },+ "clearcoatRoughness": {+ "default": 0.18,+ "range": [+ 0.05,+ 0.4+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.4,+ 1.65+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "clearcoatMap"],- "visualCues": ["untinted or light-coloured specular over coloured diffuse body", "smooth molded surface"],- "confusableWith": ["coating.painted-metal", "ceramic.glazed", "metal.steel-polished"],- "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],- "limitations": ["Do not set metalness from highlight sharpness alone"],- "sourceRefs": ["three.mesh-physical", "three.mesh-standard", "adobe.pbr-guide-1", "google.filament-pbr", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "clearcoatMap"+ ],+ "visualCues": [+ "untinted or light-coloured specular over coloured diffuse body",+ "smooth molded surface"+ ],+ "confusableWith": [+ "coating.painted-metal",+ "ceramic.glazed",+ "metal.steel-polished"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "environment-reflection",+ "reference-beauty"+ ],+ "limitations": [+ "Do not set metalness from highlight sharpness alone"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.mesh-standard",+ "adobe.pbr-guide-1",+ "google.filament-pbr",+ "mit.material-recognition"+ ]},{"id": "plastic.matte",- "aliases": ["matte plastic", "polymer"],+ "aliases": [+ "matte plastic",+ "polymer"+ ],"family": "plastic","subtype": "generic-polymer","finish": "matte","model": "dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.68, "range": [0.48, 0.88]},- "ior": {"default": 1.5, "range": [1.4, 1.65]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.68,+ "range": [+ 0.48,+ 0.88+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.4,+ 1.65+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "aoMap"],- "visualCues": ["coloured diffuse body", "broad neutral highlight", "mold seams or fine stipple"],- "confusableWith": ["rubber.matte", "leather.matte", "skin.human"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing"],- "limitations": ["Context and texture frequency often distinguish matte plastics from rubber"],- "sourceRefs": ["three.mesh-standard", "adobe.pbr-guide-1", "google.filament-pbr", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "aoMap"+ ],+ "visualCues": [+ "coloured diffuse body",+ "broad neutral highlight",+ "mold seams or fine stipple"+ ],+ "confusableWith": [+ "rubber.matte",+ "leather.matte",+ "skin.human"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing"+ ],+ "limitations": [+ "Context and texture frequency often distinguish matte plastics from rubber"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "adobe.pbr-guide-1",+ "google.filament-pbr",+ "mit.material-recognition"+ ]},{"id": "rubber.matte",- "aliases": ["rubber", "matte rubber", "cao su"],+ "aliases": [+ "rubber",+ "matte rubber",+ "cao su"+ ],"family": "rubber","subtype": "generic-elastomer","finish": "matte","model": "dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.88, "range": [0.68, 1.0]},- "ior": {"default": 1.48, "range": [1.4, 1.55]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.88,+ "range": [+ 0.68,+ 1.0+ ]+ },+ "ior": {+ "default": 1.48,+ "range": [+ 1.4,+ 1.55+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["aoMap"],- "visualCues": ["dark diffuse body", "weak broad highlight", "molded or grippy microtexture"],- "confusableWith": ["plastic.matte", "leather.matte", "fabric.woven-matte"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],- "limitations": ["Wet or polished rubber needs a separate finish record"],- "sourceRefs": ["three.mesh-standard", "adobe.pbr-guide-1", "google.filament-pbr", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "aoMap"+ ],+ "visualCues": [+ "dark diffuse body",+ "weak broad highlight",+ "molded or grippy microtexture"+ ],+ "confusableWith": [+ "plastic.matte",+ "leather.matte",+ "fabric.woven-matte"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Wet or polished rubber needs a separate finish record"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "adobe.pbr-guide-1",+ "google.filament-pbr",+ "mit.material-recognition"+ ]},{"id": "wood.unfinished",- "aliases": ["wood", "raw wood"],+ "aliases": [+ "wood",+ "raw wood"+ ],"family": "wood","subtype": "generic","finish": "unfinished","model": "directional-dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.72, "range": [0.5, 0.95]},- "anisotropy": {"default": 0.12, "range": [0.0, 0.4]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.72,+ "range": [+ 0.5,+ 0.95+ ]+ },+ "anisotropy": {+ "default": 0.12,+ "range": [+ 0.0,+ 0.4+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["aoMap", "anisotropyMap"],- "visualCues": ["directional grain", "pores and growth rings", "roughness follows grain and wear"],- "confusableWith": ["plastic.matte", "leather.matte"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing"],- "limitations": ["Species identity cannot usually be established from a small crop"],- "sourceRefs": ["three.mesh-standard", "three.texture", "adobe.pbr-guide-1", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "aoMap",+ "anisotropyMap"+ ],+ "visualCues": [+ "directional grain",+ "pores and growth rings",+ "roughness follows grain and wear"+ ],+ "confusableWith": [+ "plastic.matte",+ "leather.matte"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing"+ ],+ "limitations": [+ "Species identity cannot usually be established from a small crop"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "three.texture",+ "adobe.pbr-guide-1",+ "mit.material-recognition"+ ]},{"id": "wood.varnished",- "aliases": ["varnished wood", "lacquered wood"],+ "aliases": [+ "varnished wood",+ "lacquered wood"+ ],"family": "wood","subtype": "generic","finish": "varnished","model": "coated-dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.42, "range": [0.25, 0.65]},- "clearcoat": {"default": 0.75, "range": [0.35, 1.0]},- "clearcoatRoughness": {"default": 0.16, "range": [0.04, 0.35]},- "ior": {"default": 1.5, "range": [1.4, 1.6]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.42,+ "range": [+ 0.25,+ 0.65+ ]+ },+ "clearcoat": {+ "default": 0.75,+ "range": [+ 0.35,+ 1.0+ ]+ },+ "clearcoatRoughness": {+ "default": 0.16,+ "range": [+ 0.04,+ 0.35+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.4,+ 1.6+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["clearcoatMap", "clearcoatRoughnessMap", "aoMap"],- "visualCues": ["wood grain under a separate glossy layer", "coating scratches differ from grain"],- "confusableWith": ["plastic.glossy", "coating.painted-metal"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "environment-reflection"],- "limitations": ["Do not bake the coating highlight into the grain albedo"],- "sourceRefs": ["three.mesh-physical", "three.texture", "adobe.pbr-guide-1", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "clearcoatMap",+ "clearcoatRoughnessMap",+ "aoMap"+ ],+ "visualCues": [+ "wood grain under a separate glossy layer",+ "coating scratches differ from grain"+ ],+ "confusableWith": [+ "plastic.glossy",+ "coating.painted-metal"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "environment-reflection"+ ],+ "limitations": [+ "Do not bake the coating highlight into the grain albedo"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.texture",+ "adobe.pbr-guide-1",+ "google.filament-pbr"+ ]},{"id": "stone.natural",- "aliases": ["stone", "rock", "granite", "marble"],+ "aliases": [+ "stone",+ "rock",+ "granite",+ "marble"+ ],"family": "stone","subtype": "natural","finish": "rough-or-polished","model": "dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.78, "range": [0.25, 1.0]},- "clearcoat": {"default": 0.0, "range": [0.0, 0.35]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.78,+ "range": [+ 0.25,+ 1.0+ ]+ },+ "clearcoat": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.35+ ]+ }},- "requiredMaps": ["map", "roughnessMap", "normalMap"],- "optionalMaps": ["aoMap", "displacementMap", "clearcoatMap"],- "visualCues": ["multi-scale mineral pattern", "fracture or pore relief", "polished stone retains dielectric reflection"],- "confusableWith": ["ceramic.glazed", "plastic.matte", "coating.paint-matte"],- "validationViews": ["albedo-unlit", "neutral-studio", "grazing", "reference-beauty"],- "limitations": ["Marble and polished stone may need transmission or subsurface approximation beyond this base record"],- "sourceRefs": ["three.mesh-standard", "three.mesh-physical", "adobe.pbr-guide-1", "mit.material-recognition"]+ "requiredMaps": [+ "map",+ "roughnessMap",+ "normalMap"+ ],+ "optionalMaps": [+ "aoMap",+ "displacementMap",+ "clearcoatMap"+ ],+ "visualCues": [+ "multi-scale mineral pattern",+ "fracture or pore relief",+ "polished stone retains dielectric reflection"+ ],+ "confusableWith": [+ "ceramic.glazed",+ "plastic.matte",+ "coating.paint-matte"+ ],+ "validationViews": [+ "albedo-unlit",+ "neutral-studio",+ "grazing",+ "reference-beauty"+ ],+ "limitations": [+ "Marble and polished stone may need transmission or subsurface approximation beyond this base record"+ ],+ "sourceRefs": [+ "three.mesh-standard",+ "three.mesh-physical",+ "adobe.pbr-guide-1",+ "mit.material-recognition"+ ]},{"id": "ceramic.glazed",- "aliases": ["ceramic", "porcelain", "glazed ceramic"],+ "aliases": [+ "ceramic",+ "porcelain",+ "glazed ceramic"+ ],"family": "ceramic","subtype": "glazed","finish": "glossy","model": "coated-dielectric","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.26, "range": [0.1, 0.5]},- "clearcoat": {"default": 0.7, "range": [0.4, 1.0]},- "clearcoatRoughness": {"default": 0.12, "range": [0.02, 0.3]},- "ior": {"default": 1.5, "range": [1.4, 1.65]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.26,+ "range": [+ 0.1,+ 0.5+ ]+ },+ "clearcoat": {+ "default": 0.7,+ "range": [+ 0.4,+ 1.0+ ]+ },+ "clearcoatRoughness": {+ "default": 0.12,+ "range": [+ 0.02,+ 0.3+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.4,+ 1.65+ ]+ }},- "requiredMaps": ["map", "roughnessMap"],- "optionalMaps": ["normalMap", "clearcoatMap", "clearcoatRoughnessMap"],- "visualCues": ["hard dielectric body", "smooth glaze reflection", "small chips reveal matte body"],- "confusableWith": ["plastic.glossy", "stone.natural", "coating.painted-metal"],- "validationViews": ["neutral-studio", "grazing", "environment-reflection", "reference-beauty"],- "limitations": ["Unglazed ceramic needs a separate matte finish"],- "sourceRefs": ["three.mesh-physical", "adobe.pbr-guide-1", "google.filament-pbr"]+ "requiredMaps": [+ "map",+ "roughnessMap"+ ],+ "optionalMaps": [+ "normalMap",+ "clearcoatMap",+ "clearcoatRoughnessMap"+ ],+ "visualCues": [+ "hard dielectric body",+ "smooth glaze reflection",+ "small chips reveal matte body"+ ],+ "confusableWith": [+ "plastic.glossy",+ "stone.natural",+ "coating.painted-metal"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "environment-reflection",+ "reference-beauty"+ ],+ "limitations": [+ "Unglazed ceramic needs a separate matte finish"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "adobe.pbr-guide-1",+ "google.filament-pbr"+ ]},{"id": "glass.clear",- "aliases": ["glass", "clear glass"],+ "aliases": [+ "glass",+ "clear glass"+ ],"family": "glass","subtype": "clear","finish": "polished","model": "transmissive-dielectric-volume","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.05, "range": [0.0, 0.18]},- "transmission": {"default": 1.0, "range": [0.85, 1.0]},- "ior": {"default": 1.5, "range": [1.45, 1.55]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.05,+ "range": [+ 0.0,+ 0.18+ ]+ },+ "transmission": {+ "default": 1.0,+ "range": [+ 0.85,+ 1.0+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.45,+ 1.55+ ]+ }},- "requiredMaps": ["roughnessMap", "thicknessMap"],- "optionalMaps": ["map", "normalMap", "transmissionMap"],- "visualCues": ["background distortion", "bright interface reflection", "visible thickness or absorption"],- "confusableWith": ["plastic.glossy", "gemstone.quartz", "alpha-transparent material"],- "validationViews": ["neutral-studio", "environment-reflection", "backlight-transmission", "reference-beauty"],- "limitations": ["Use opacity 1 with transmission; thickness must be derived from geometry scale"],- "sourceRefs": ["three.mesh-physical", "three.pmrem", "gltf.2", "khronos.transmission", "khronos.volume", "google.filament-pbr"]+ "requiredMaps": [+ "roughnessMap",+ "thicknessMap"+ ],+ "optionalMaps": [+ "map",+ "normalMap",+ "transmissionMap"+ ],+ "visualCues": [+ "background distortion",+ "bright interface reflection",+ "visible thickness or absorption"+ ],+ "confusableWith": [+ "plastic.glossy",+ "gemstone.quartz",+ "alpha-transparent material"+ ],+ "validationViews": [+ "neutral-studio",+ "environment-reflection",+ "backlight-transmission",+ "reference-beauty"+ ],+ "limitations": [+ "Use opacity 1 with transmission; thickness must be derived from geometry scale"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.pmrem",+ "gltf.2",+ "khronos.transmission",+ "khronos.volume",+ "google.filament-pbr"+ ]},{"id": "glass.frosted",- "aliases": ["frosted glass", "etched glass"],+ "aliases": [+ "frosted glass",+ "etched glass"+ ],"family": "glass","subtype": "frosted","finish": "rough-transmissive","model": "transmissive-dielectric-volume","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.52, "range": [0.3, 0.8]},- "transmission": {"default": 0.85, "range": [0.6, 1.0]},- "ior": {"default": 1.5, "range": [1.45, 1.55]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.52,+ "range": [+ 0.3,+ 0.8+ ]+ },+ "transmission": {+ "default": 0.85,+ "range": [+ 0.6,+ 1.0+ ]+ },+ "ior": {+ "default": 1.5,+ "range": [+ 1.45,+ 1.55+ ]+ }},- "requiredMaps": ["roughnessMap", "normalMap", "thicknessMap"],- "optionalMaps": ["transmissionMap", "map"],- "visualCues": ["blurred transmitted background", "broad interface highlight", "fine etched normal structure"],- "confusableWith": ["plastic.matte", "glass.clear"],- "validationViews": ["neutral-studio", "grazing", "backlight-transmission", "reference-beauty"],- "limitations": ["Transmission quality and cost depend on renderer and scene configuration"],- "sourceRefs": ["three.mesh-physical", "three.pmrem", "khronos.transmission", "khronos.volume", "google.filament-pbr"]+ "requiredMaps": [+ "roughnessMap",+ "normalMap",+ "thicknessMap"+ ],+ "optionalMaps": [+ "transmissionMap",+ "map"+ ],+ "visualCues": [+ "blurred transmitted background",+ "broad interface highlight",+ "fine etched normal structure"+ ],+ "confusableWith": [+ "plastic.matte",+ "glass.clear"+ ],+ "validationViews": [+ "neutral-studio",+ "grazing",+ "backlight-transmission",+ "reference-beauty"+ ],+ "limitations": [+ "Transmission quality and cost depend on renderer and scene configuration"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.pmrem",+ "khronos.transmission",+ "khronos.volume",+ "google.filament-pbr"+ ]},{"id": "gemstone.quartz",- "aliases": ["quartz", "crystal", "gemstone"],+ "aliases": [+ "quartz",+ "crystal",+ "gemstone"+ ],"family": "gemstone","subtype": "quartz-like","finish": "polished","model": "transmissive-dielectric-volume","recipeBasis": "inferred-starting-prior","renderPrior": {- "metalness": {"default": 0.0, "range": [0.0, 0.0]},- "roughness": {"default": 0.06, "range": [0.01, 0.2]},- "transmission": {"default": 0.9, "range": [0.5, 1.0]},- "ior": {"default": 1.54, "range": [1.45, 1.7]},- "dispersion": {"default": 0.0, "range": [0.0, 0.3]}+ "metalness": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.0+ ]+ },+ "roughness": {+ "default": 0.06,+ "range": [+ 0.01,+ 0.2+ ]+ },+ "transmission": {+ "default": 0.9,+ "range": [+ 0.5,+ 1.0+ ]+ },+ "ior": {+ "default": 1.54,+ "range": [+ 1.45,+ 1.7+ ]+ },+ "dispersion": {+ "default": 0.0,+ "range": [+ 0.0,+ 0.3+ ]+ }},- "requiredMaps": ["roughnessMap", "thicknessMap"],- "optionalMaps": ["map", "normalMap", "transmissionMap"],- "visualCues": ["faceted interface reflections", "transmitted or internally varied colour", "thickness-dependent appearance"],- "confusableWith": ["glass.clear", "plastic.glossy", "coating.candy"],- "validationViews": ["neutral-studio", "environment-reflection", "backlight-transmission", "reference-beauty"],- "limitations": ["A painted opaque gem-like surface is not a transmissive gemstone and needs a coating record"],- "sourceRefs": ["three.mesh-physical", "three.pmrem", "gltf.2", "khronos.transmission", "khronos.volume", "google.filament-pbr"]+ "requiredMaps": [+ "roughnessMap",+ "thicknessMap"+ ],+ "optionalMaps": [+ "map",+ "normalMap",+ "transmissionMap"+ ],+ "visualCues": [+ "faceted interface reflections",+ "transmitted or internally varied colour",+ "thickness-dependent appearance"+ ],+ "confusableWith": [+ "glass.clear",+ "plastic.glossy",+ "coating.candy"+ ],+ "validationViews": [+ "neutral-studio",+ "environment-reflection",+ "backlight-transmission",+ "reference-beauty"+ ],+ "limitations": [+ "A painted opaque gem-like surface is not a transmissive gemstone and needs a coating record"+ ],+ "sourceRefs": [+ "three.mesh-physical",+ "three.pmrem",+ "gltf.2",+ "khronos.transmission",+ "khronos.volume",+ "google.filament-pbr"+ ]}]}diff --git a/docs/specs/render-profile.v2.example.json b/docs/specs/render-profile.v2.example.jsonindex ab26e37..352ab3a 100644--- a/docs/specs/render-profile.v2.example.json+++ b/docs/specs/render-profile.v2.example.json@@ -56,5 +56,8 @@{ "id": "accessory", "order": 5 },{ "id": "materials", "order": 6 },{ "id": "lighting", "order": 7 }- ]+ ],+ "extensions": {+ "requiredSemanticRegions": ["face", "kasa", "scarf", "tunic", "staff", "tail", "feet", "materials"]+ }}diff --git a/docs/specs/render-profile.v2.schema.json b/docs/specs/render-profile.v2.schema.jsonindex 3a5e9fc..29ec9a9 100644--- a/docs/specs/render-profile.v2.schema.json+++ b/docs/specs/render-profile.v2.schema.json@@ -3,7 +3,7 @@"$id": "https://img2threejs.local/specs/render-profile.v2.schema.json","title": "img2threejs shared Three.js render profile v2","type": "object",- "required": ["schemaVersion", "kind", "authority", "renderer", "environment", "camera", "background", "passes", "regions", "feedbackGroups"],+ "required": ["schemaVersion", "kind", "authority", "renderer", "environment", "camera", "background", "passes", "regions", "feedbackGroups", "extensions"],"properties": {"schemaVersion": { "const": "render-profile.v2" },"kind": { "const": "threejs-render-profile" },@@ -48,7 +48,8 @@},"background": { "type": "object", "required": ["kind"], "properties": { "kind": { "enum": ["solid", "transparent", "scene"] } }, "additionalProperties": true },"passes": { "type": "array", "minItems": 6, "items": { "type": "object", "required": ["id", "required"], "properties": { "id": { "type": "string" }, "required": { "type": "boolean" } }, "additionalProperties": true } },- "regions": { "type": "array", "items": { "type": "object", "required": ["id", "criticality"], "properties": { "id": { "type": "string" }, "criticality": { "enum": ["critical", "high", "important", "detail"] }, "idColor": { "type": "array", "prefixItems": [{ "type": "integer", "minimum": 0, "maximum": 255 }, { "type": "integer", "minimum": 0, "maximum": 255 }, { "type": "integer", "minimum": 0, "maximum": 255 }], "minItems": 3, "maxItems": 3 } }, "additionalProperties": true } },+ "regions": { "type": "array", "minItems": 1, "items": { "type": "object", "required": ["id", "criticality"], "properties": { "id": { "type": "string", "minLength": 1 }, "criticality": { "enum": ["critical", "high", "important", "detail"] }, "idColor": { "type": "array", "prefixItems": [{ "type": "integer", "minimum": 0, "maximum": 255 }, { "type": "integer", "minimum": 0, "maximum": 255 }, { "type": "integer", "minimum": 0, "maximum": 255 }], "minItems": 3, "maxItems": 3 } }, "additionalProperties": true } },+ "extensions": { "type": "object", "properties": { "requiredSemanticRegions": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "type": "string", "minLength": 1 } } }, "additionalProperties": true },"feedbackGroups": { "type": "array", "minItems": 7, "items": { "type": "object", "required": ["id", "order"], "properties": { "id": { "type": "string" }, "order": { "type": "integer", "minimum": 1 } }, "additionalProperties": true } }},"additionalProperties": truediff --git a/forge/_shared/chirality.py b/forge/_shared/chirality.pynew file mode 100644index 0000000..c146750--- /dev/null+++ b/forge/_shared/chirality.py@@ -0,0 +1,272 @@+#!/usr/bin/env python3+"""Left and right, in one place, with the two ways of getting it wrong.++WHY THIS MODULE EXISTS. Two chirality defects shipped in the same figure and neither was caught by+any gate, because both produce geometry that is internally tidy and only wrong with respect to a+convention nothing had written down as code.++ THE HAND `place()` built the mirrored limb as `[side*along, height, side*across]`, negating+ x AND z. Two negations is not a reflection -- it is a 180-degree ROTATION about Y,+ and a rotation PRESERVES handedness. The left hand was the right hand turned+ around. Measured on the thumb tip: z +0.288 on one side and -0.288 on the other,+ where a mirror leaves z alone.++ THE FOOT The pair WAS a correct reflection, so any pair test passes. But the toes were+ ordered little-to-big across a knuckle strip whose index 0 lands on the medial+ edge, so the big toe went lateral -- on both feet. Measured in the render's toe+ band: mass 350 medial / 443 lateral, against a reference of 529 / 488. A foot with+ its big toe outside IS the other foot, so the pair read as swapped.++They need DIFFERENT tests, and that is the point of this module:++ check_pair() catches the hand. Compares a left component against its right partner.+ medial_lateral_bias() catches the foot. Compares one limb's own asymmetry against a reference,+ because a pair that is wrong the SAME way on both sides is still a+ perfectly good mirror of itself.++THE CONVENTION, stated once so nothing can quietly diverge from it. `new_sculpt_spec.py` carries it+as a comment -- "'left' is the CHARACTER's left, which the component tree spells `-l`. On a+front-facing reference that is the viewer's right." -- and a comment cannot be imported. With+`forward: +Z`, Y up and a right-handed frame, the camera in front looks along -Z and its right is++X, so the character's own left is +X.++Pure Python 3.10+ standard library.+"""+from __future__ import annotations++import math+import re+from typing import Any, Iterable, Sequence++Point = Sequence[float]++# Index of the left-right axis in an (x, y, z) triple. The ONLY axis a sagittal mirror negates.+LATERAL_AXIS = 0+# Sign of the character's own left, given coordinateFrame up=+Y forward=+Z and a right-handed+# system. Derived, not chosen: the camera that sees the front looks along -Z, its right is +X, and+# a figure facing the camera has its own left on the viewer's right.+CHARACTER_LEFT_SIGN = 1++# Suffixes that mark a component as one half of a lateral pair.+LEFT_SUFFIX = "-l"+RIGHT_SUFFIX = "-r"+_PAIR_RE = re.compile(r"^(?P<stem>.+)-(?P<side>[lr])$")++# How far apart two mirrored coordinates may sit before the pair is called broken, in world units.+# Not a tuning knob: mirrored values are produced by negating the same authored number, so they+# agree to floating-point noise or they disagree structurally. Anything between those is itself a+# defect worth seeing.+MIRROR_TOLERANCE = 1e-6+++def mirror_point(point: Point) -> tuple[float, float, float]:+ """The sagittal mirror of a position: negate the lateral axis, leave the rest alone."""+ values = [float(v) for v in point]+ if len(values) != 3:+ raise ValueError(f"a point needs three components, got {len(values)}")+ values[LATERAL_AXIS] = -values[LATERAL_AXIS]+ return (values[0], values[1], values[2])+++def mirror_vector(vector: Point) -> tuple[float, float, float]:+ """The sagittal mirror of a DIRECTION. Same rule as a point.++ Kept as its own name because the reflex is to think a direction transforms differently, and+ reaching for a rotation here is exactly the recorded bug.+ """+ return mirror_point(vector)+++def side_of(component_id: str) -> str | None:+ """'l', 'r', or None for a component that is not one half of a pair."""+ match = _PAIR_RE.match(str(component_id))+ return match.group("side") if match else None+++def pair_stem(component_id: str) -> str | None:+ match = _PAIR_RE.match(str(component_id))+ return match.group("stem") if match else None+++def find_pairs(component_ids: Iterable[str]) -> list[tuple[str, str]]:+ """Every `(right_id, left_id)` both halves of which are present. Right first, because the+ convention is stated as 'the left is the mirror of the right'."""+ by_stem: dict[str, dict[str, str]] = {}+ for component_id in component_ids:+ stem = pair_stem(component_id)+ side = side_of(component_id)+ if stem and side:+ by_stem.setdefault(stem, {})[side] = str(component_id)+ return [+ (sides["r"], sides["l"])+ for _stem, sides in sorted(by_stem.items())+ if "l" in sides and "r" in sides+ ]+++def classify_relation(right: Point, left: Point) -> str:+ """How the two halves of a pair are actually related. One of:++ 'reflection' the left is the sagittal mirror of the right. Correct.+ 'rotation' the left is the right ROTATED about the vertical axis, not mirrored. This is+ the recorded hand defect and the reason this function names it rather than+ just saying 'mismatch': the two are trivially confused, they agree exactly on+ a symmetric part, and they differ only in handedness.+ 'translation' the left is the right moved, not transformed at all.+ 'unrelated' none of the above.+ """+ r = [float(v) for v in right]+ l = [float(v) for v in left]+ if len(r) != 3 or len(l) != 3:+ raise ValueError("both points need three components")++ def close(a: Sequence[float], b: Sequence[float]) -> bool:+ return all(abs(x - y) <= MIRROR_TOLERANCE for x, y in zip(a, b))++ if close(mirror_point(r), l):+ return "reflection"+ # 180 degrees about Y negates x and z, leaves y. Indistinguishable from a reflection whenever+ # the part sits on the midline in z, which is why a symmetric torso never exposed this.+ if close((-r[0], r[1], -r[2]), l):+ return "rotation"+ if close((r[0], r[1], r[2]), l):+ return "translation"+ return "unrelated"+++def check_pair(+ stem: str,+ right: Point,+ left: Point,+) -> tuple[bool, str]:+ """`(ok, message)` for one lateral pair. `ok` is True only for a true reflection."""+ relation = classify_relation(right, left)+ if relation == "reflection":+ return (True, "")+ expected = mirror_point(right)+ if relation == "rotation":+ return (False, (+ f"{stem}: the left half is the right half ROTATED about the vertical axis, not "+ f"mirrored. A rotation preserves handedness, so both halves are the same hand. "+ f"right {tuple(round(float(v), 6) for v in right)} should mirror to "+ f"{tuple(round(v, 6) for v in expected)}, but the left is "+ f"{tuple(round(float(v), 6) for v in left)}. Negate the lateral axis only."+ ))+ if relation == "translation":+ return (False, (+ f"{stem}: both halves sit on the same side -- the left is the right translated, not "+ f"mirrored at all. Expected {tuple(round(v, 6) for v in expected)}."+ ))+ return (False, (+ f"{stem}: the halves are not a sagittal mirror. right "+ f"{tuple(round(float(v), 6) for v in right)} mirrors to "+ f"{tuple(round(v, 6) for v in expected)}, but the left is "+ f"{tuple(round(float(v), 6) for v in left)}."+ ))+++def medial_lateral_bias(+ samples: Sequence[tuple[float, float]],+ midline: float = 0.0,+) -> dict[str, Any]:+ """Which half of a limb carries more of it: the half toward the body, or the half away.++ `samples` is `(lateral_coordinate, weight)`. The limb's own midline is taken from its extent,+ and `midline` is the BODY's centreline, which decides which of its halves is medial.++ THIS IS THE TEST A PAIR CHECK CANNOT REPLACE. Two limbs can be perfect mirrors of each other and+ both be the wrong hand. The foot defect was exactly that: `check_pair` passes, and only+ comparing one foot's own internal asymmetry against a reference shows the big toe on the wrong+ edge.+ """+ if not samples:+ return {"medial": 0.0, "lateral": 0.0, "bias": 0.0, "heavier": "none", "sampleCount": 0}+ coords = [float(c) for c, _ in samples]+ low, high = min(coords), max(coords)+ limb_centre = (low + high) / 2.0+ # Medial means nearer the body centreline. Which direction that is depends on which side of the+ # body this limb is on, so it is derived from the limb's own position rather than assumed.+ toward_body = -1.0 if limb_centre > midline else 1.0++ medial = lateral = 0.0+ for coordinate, weight in samples:+ offset = (float(coordinate) - limb_centre) * toward_body+ if offset > 0:+ medial += float(weight)+ elif offset < 0:+ lateral += float(weight)+ total = medial + lateral+ bias = (medial - lateral) / total if total else 0.0+ return {+ "medial": round(medial, 6),+ "lateral": round(lateral, 6),+ "bias": round(bias, 6),+ "heavier": "medial" if bias > 0 else ("lateral" if bias < 0 else "even"),+ "sampleCount": len(samples),+ "limbCentre": round(limb_centre, 6),+ }+++# Below this the reference is treated as too symmetric to judge handedness from.+#+# CALIBRATED, and the first guess was not. 0.05 was picked by eye and it would have made the gate+# blind to the exact defect it was written for: the reference feet measure +0.0403 and +0.0579, so a+# 0.05 floor calls one of them unjudgeable. Measured endpoints, toe band, front view:+#+# reference, left foot +0.0403 medial-heavy, as a real foot is+# reference, right foot +0.0579 same sign, which is what makes the weak signal trustworthy+# the defect -0.1173 opposite sign, and three times the magnitude+# after the fix +0.0867+#+# 0.025 sits below the weaker reference reading with 38% margin and nowhere near the defect.+MIN_REFERENCE_BIAS = 0.025+++def compare_bias(+ reference: dict[str, Any],+ candidate: dict[str, Any],+ label: str,+ tolerance: float = MIN_REFERENCE_BIAS,+) -> tuple[bool, str]:+ """`(ok, message)`. Fails when the candidate's asymmetry points the OPPOSITE way to the+ reference's, which is the signature of a limb built with the wrong handedness.++ A difference in MAGNITUDE is not a chirality defect -- it is a proportion difference, and other+ gates own that. Only the sign is judged here, and only when the reference's own bias is large+ enough to mean something.+ """+ reference_bias = float(reference.get("bias", 0.0))+ candidate_bias = float(candidate.get("bias", 0.0))+ if abs(reference_bias) < tolerance:+ return (True, (+ f"{label}: the reference is close to symmetric here (bias {reference_bias:+.3f}), so "+ f"handedness cannot be judged from it"+ ))+ if reference_bias * candidate_bias > 0:+ return (True, "")+ return (False, (+ f"{label}: mass sits on the {candidate.get('heavier')} side while the reference has it "+ f"{reference.get('heavier')} (bias {candidate_bias:+.3f} against {reference_bias:+.3f}). "+ f"A limb whose internal asymmetry points the wrong way is the OTHER limb -- check the order "+ f"of anything laid out across it, not its position."+ ))+++def sagittal_symmetry_error(points: Sequence[Point]) -> float:+ """RMS distance from each point to the nearest mirror of another point.++ A whole-figure sanity number: near zero for a symmetric figure, and large for one where a+ lateral pair has drifted. Reported rather than gated, because deliberate asymmetry -- a+ side-swept fringe, a hand on a hip -- is legitimate and common.+ """+ if not points:+ return 0.0+ mirrored = [mirror_point(p) for p in points]+ total = 0.0+ for point in points:+ best = min(+ (p[0] - point[0]) ** 2 + (p[1] - point[1]) ** 2 + (p[2] - point[2]) ** 2+ for p in mirrored+ )+ total += best+ return math.sqrt(total / len(points))diff --git a/forge/_shared/material_physics.py b/forge/_shared/material_physics.pynew file mode 100644index 0000000..ddd414e--- /dev/null+++ b/forge/_shared/material_physics.py@@ -0,0 +1,253 @@+#!/usr/bin/env python3+"""What three.js actually does with a material value, as code rather than as a comment.++WHY THIS MODULE EXISTS. A material number can be authored, validated, emitted, rendered -- and still+never reach a pixel, because the engine gates it behind another value, clamps it, adds to it, or folds+it into a different uniform. None of that is on the docs page. All of it is in the source, and every+constant below cites the file:line in `[email protected]` it came from.++The two failure modes this prevents:++ AUTHORING A VALUE THE ENGINE IGNORES. `sheen: 0.65` with three's default `sheenColor` of+ 0x000000 contributes exactly zero, because the sheen term+ is `sheenColor * (D * V)` -- a multiply by black.++ EXPOSING ONE DEGREE OF FREEDOM TWICE. `sheen` and `sheenColor` are multiplied together before+ upload, so `sheen 1.0 / #808080` is bit-identical to+ `sheen 0.5 / #ffffff`. Extracting both from a reference as+ independent evidence extracts the same number twice and+ produces priors that contradict each other on paper while+ rendering identically.++Full derivation, with every citation: `grimoire/build/threejs_skin_and_cloth_materials.md`.++Pure Python 3.10+ standard library.+"""+from __future__ import annotations++from typing import Any, Final++# ---------------------------------------------------------------------------------------------+# Engine constants. Each is a measured property of [email protected], not a policy choice.+# ---------------------------------------------------------------------------------------------++THREE_VERSION: Final = "0.169.0"++# `material.clearcoatRoughness = max( clearcoatRoughness, 0.0525 )`+# ShaderChunk/lights_physical_fragment.glsl.js:72+# Anything below this renders identically to it, so accepting a smaller number as meaningful is+# accepting a value the engine will not honour.+CLEARCOAT_ROUGHNESS_FLOOR: Final = 0.0525++# `float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );`+# `outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;`+# ShaderLib/meshphysical.glsl.js:205,207+# Turning sheen on DARKENS the diffuse base by this coefficient times the effective sheen strength.+SHEEN_ENERGY_COMPENSATION_COEFFICIENT: Final = 0.157++# `clearcoatF0 = vec3( 0.04 )` -- fixed, not authorable.+# ShaderChunk/lights_physical_fragment.glsl.js:56+CLEARCOAT_F0: Final = 0.04++# three's own defaults, needed to know when an omitted value is a silent no-op rather than a+# reasonable fallback. MeshPhysicalMaterial.js:52,54 / Material.js:24,25+THREE_DEFAULT_SHEEN_COLOR: Final = "#000000"+THREE_DEFAULT_SHEEN_ROUGHNESS: Final = 1.0+THREE_DEFAULT_SIDE: Final = "FrontSide"++# Properties whose entire uniform block is gated behind the scalar being > 0, and whose crossing of+# zero bumps `material.version` and forces a shader recompile.+# WebGLMaterials.js:406 (sheen); MeshPhysicalMaterial.js getters for the rest.+ZERO_GATED_FEATURES: Final = frozenset({+ "sheen", "clearcoat", "transmission", "iridescence", "anisotropy", "dispersion",+})++# Pairs the engine collapses into a single degree of freedom. Authoring both as independent+# reference-derived evidence is authoring one number twice.+# sheen x sheenColor: WebGLMaterials.js:408+# ior <-> reflectivity: MeshPhysicalMaterial.js:34-44+COLLAPSED_DEGREES_OF_FREEDOM: Final = (+ ("sheen", "sheenColor", "multiplied into one uniform before upload"),+ ("ior", "reflectivity", "reflectivity is a derived accessor over ior"),+)++# Skin's real signature at this fidelity is a broad soft dielectric highlight over a warm diffuse+# base, which is a low-strength mid-roughness clearcoat. `transmission` is a SCREEN-SPACE REFRACTION+# model -- glass, not subsurface -- and on a closed opaque body mesh it produces a glassy figure at+# the cost of an extra render target. The registry states the same limit for skin.human.+SKIN_FORBIDDEN_PROPERTIES: Final = frozenset({"transmission", "thickness", "attenuationDistance"})+++def effective_sheen_strength(sheen: float, sheen_color: str | None) -> float:+ """What the engine actually applies, after folding the scalar into the colour.++ `uniforms.sheenColor = sheenColor x sheen` (WebGLMaterials.js:408), and the BRDF multiplies by+ that colour, so the strength that matters is the scalar times the colour's largest channel --+ `max3` is exactly what the energy term reads.+ """+ if sheen <= 0.0:+ return 0.0+ channel = _max_channel(sheen_color if sheen_color is not None else THREE_DEFAULT_SHEEN_COLOR)+ return sheen * channel+++def sheen_base_darkening(sheen: float, sheen_color: str | None) -> float:+ """How much the diffuse base is scaled DOWN by enabling sheen, in [0, 0.157].++ This is the number that makes "the garment came out too dark" diagnosable rather than a matter of+ opinion: given the authored sheen, the darkening is known before the render exists.+ """+ return SHEEN_ENERGY_COMPENSATION_COEFFICIENT * effective_sheen_strength(sheen, sheen_color)+++def compensated_base_luminance(target: float, sheen: float, sheen_color: str | None) -> float:+ """The base luminance to author so the RENDER matches `target` once sheen has darkened it.++ Returns `target` unchanged when sheen is off, so it is safe to apply unconditionally.+ """+ darkening = sheen_base_darkening(sheen, sheen_color)+ if darkening <= 0.0:+ return target+ return min(1.0, target / (1.0 - darkening))+++def _max_channel(color: str) -> float:+ """Largest of r, g, b in [0, 1] for a `#rgb` or `#rrggbb` string. Unparseable -> 0.0.++ Returning 0 rather than raising is deliberate: an unparseable colour cannot be shown to carry+ sheen, and the caller's job here is to detect a no-op, not to validate colour syntax.+ """+ text = str(color).strip().lstrip("#")+ if len(text) == 3:+ text = "".join(ch * 2 for ch in text)+ if len(text) != 6:+ return 0.0+ try:+ channels = [int(text[i:i + 2], 16) / 255.0 for i in (0, 2, 4)]+ except ValueError:+ return 0.0+ return max(channels)+++def check_material_physics(+ material_id: str,+ material: dict[str, Any],+ *,+ family: str | None = None,+) -> tuple[list[str], list[str]]:+ """`(errors, warnings)` for one material, judged against what the engine will do with it.++ `family` routes the family-specific rules -- `skin` forbids transmission, and a `fabric` or+ `hair` family that ships no sheen tint has no woven cue at all.+ """+ errors: list[str] = []+ warnings: list[str] = []++ sheen = _number(material.get("sheen"))+ sheen_color = material.get("sheenColor")++ # A no-op, not a subtle mis-tune: the term is a multiply by colour and the default colour is black.+ if sheen is not None and sheen > 0.0:+ if sheen_color is None:+ errors.append(+ f"material {material_id!r} sets sheen {sheen} but no sheenColor. three's default "+ f"sheenColor is {THREE_DEFAULT_SHEEN_COLOR} and the sheen term is a multiply by that "+ f"colour, so this contributes exactly zero. Declare sheenColor."+ )+ elif _max_channel(str(sheen_color)) == 0.0:+ errors.append(+ f"material {material_id!r} sets sheen {sheen} with sheenColor {sheen_color!r}, whose "+ f"channels are all zero, so the sheen term evaluates to zero."+ )+ else:+ darkening = sheen_base_darkening(sheen, str(sheen_color))+ if darkening > 0.0:+ warnings.append(+ f"quality: material {material_id!r} sheen darkens its own diffuse base by "+ f"{darkening * 100:.1f}% (sheenEnergyComp). Author the base colour "+ f"{1.0 / (1.0 - darkening):.3f}x brighter than the reference sample, or the "+ f"render lands darker than the reference at every non-grazing angle."+ )++ # A value below the clamp is indistinguishable from the clamp, so reporting it as authored is+ # reporting a precision the engine does not have.+ clearcoat_roughness = _number(material.get("clearcoatRoughness"))+ if clearcoat_roughness is not None and 0.0 < clearcoat_roughness < CLEARCOAT_ROUGHNESS_FLOOR:+ warnings.append(+ f"quality: material {material_id!r} clearcoatRoughness {clearcoat_roughness} is below "+ f"three's floor of {CLEARCOAT_ROUGHNESS_FLOOR} and will render as exactly that. Author "+ f"{CLEARCOAT_ROUGHNESS_FLOOR} so the spec says what ships."+ )++ # Both halves of a collapsed pair authored at once: the spec looks richer than it is, and the two+ # numbers can disagree while rendering identically.+ for first, second, why in COLLAPSED_DEGREES_OF_FREEDOM:+ if material.get(first) is not None and material.get(second) is not None:+ if (first, second) == ("ior", "reflectivity"):+ errors.append(+ f"material {material_id!r} sets both {first} and {second}: {why}. Author {first} "+ f"only -- it is the physical quantity."+ )+ else:+ warnings.append(+ f"quality: material {material_id!r} sets both {first} and {second}: {why}. They "+ f"are one control, so these are not independent evidence."+ )++ normalized_family = (family or material.get("family") or "").lower()++ if normalized_family == "skin":+ for forbidden in sorted(SKIN_FORBIDDEN_PROPERTIES):+ if material.get(forbidden) is not None:+ errors.append(+ f"material {material_id!r} is family 'skin' and sets {forbidden!r}. transmission "+ f"is a screen-space refraction (glass) model, not subsurface scattering; on a "+ f"closed body mesh it renders a glassy figure and costs an extra render target. "+ f"Use clearcoat over a warm base instead. A thin translucent membrane is a "+ f"separate component with a separate material, declared as an approximation."+ )++ if normalized_family in {"fabric", "hair"} and (sheen is None or sheen <= 0.0):+ warnings.append(+ f"quality: material {material_id!r} is family {normalized_family!r} but carries no sheen. "+ f"With no textures available, sheen is the whole of the woven or fibre cue this pipeline "+ f"can emit."+ )++ return errors, warnings+++def check_open_boundary_sides(component_id: str, component: dict[str, Any]) -> list[str]:+ """A garment shell with an open boundary must render both sides.++ `Material.side` defaults to `FrontSide` (Material.js:24), which culls backfaces. A sleeve, hem or+ collar opening therefore shows a HOLE rather than the inside of the garment: the geometry is+ there, the engine simply does not draw the faces pointing away. Reported as an error because a+ hole at a hem is indistinguishable at a glance from a garment that is too short, and the two want+ completely different fixes.+ """+ garment = component.get("garment")+ if not isinstance(garment, dict):+ return []+ boundaries = garment.get("boundaries")+ if not isinstance(boundaries, list) or not boundaries:+ return []+ has_open = any(+ isinstance(entry, dict) and entry.get("closed") is not True for entry in boundaries+ )+ if not has_open:+ return []+ if str(component.get("side") or THREE_DEFAULT_SIDE) == "FrontSide":+ return [+ f"component {component_id!r} is a garment with an open boundary but leaves side at "+ f"'FrontSide', so backfaces are culled and the opening renders as a hole rather than as "+ f"the inside of the garment. Set side to 'DoubleSide', or author the garment as a closed "+ f"offset volume and mark its boundaries closed."+ ]+ return []+++def _number(value: Any) -> float | None:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ return None+ return float(value)diff --git a/forge/_shared/scalp_field.py b/forge/_shared/scalp_field.pynew file mode 100644index 0000000..64991c7--- /dev/null+++ b/forge/_shared/scalp_field.py@@ -0,0 +1,302 @@+#!/usr/bin/env python3+"""Signed distance to a skull built as a stack of ellipse rings.++WHY THIS EXISTS. Hair was being held off the skull by a comment. The low-poly humanoid demo carries+this invariant in prose:++ EVERY piece must stand proud of the skull at its own height. Where the skull is proud of the+ hair, the head renders bald there.++The garment in the same file is held off the body by a MEASUREMENT instead -- `sectionedLoft`'s `hug`+marches every vertex outward along its own spoke until a signed distance field reads at least+`clearance`. Its docstring records why authoring the numbers by hand does not work:++ Five rounds of widening these sections by hand still left the body poking through 0.09 H of the+ front ... Any single ellipse that clears the widest point is loose at the narrowest and vice+ versa, so the error moves rather than shrinks.++That is exactly what happened when the hair side-masses were widened by hand: closure went 42.2% to+40.9%, worse on all six views, and dark coverage went DOWN because the widened mass slid off the+skull instead of growing on it. The error moved rather than shrank. This module is the field the+hair never had.++The skull is already a ring stack in every character spec -- the humanoid's head is eight rows of+`[y, radiusX, radiusZ]` plus a per-row z offset -- so the field is derived, never authored twice.++SIGN IS EXACT, MAGNITUDE IS AN ESTIMATE. Inside/outside comes from the sign of the ellipse function,+which is exact. The distance magnitude uses the first-order estimate `f / |grad f|`, which is the+standard Newton step for an ellipse and is not the true Euclidean distance. Every gate built on this+must therefore treat the sign as authoritative and the magnitude as approximate.++Pure Python 3.10+ standard library. No numpy, no PIL.+"""+from __future__ import annotations++import math+from typing import Any, Iterable, Sequence++Ring = tuple[float, float, float, float]+"""One ring: (y, radiusX, radiusZ, zCentre)."""+++def _finite(value: object, label: str) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise ValueError(f"{label} must be a number, got {value!r}")+ number = float(value)+ if not math.isfinite(number):+ raise ValueError(f"{label} must be finite, got {number!r}")+ return number+++def normalise_rings(rings: Iterable[Sequence[float] | dict[str, float]]) -> list[Ring]:+ """Accept the shapes a spec actually carries and return sorted, validated rings.++ A ring may arrive as `(y, rx, rz)`, `(y, rx, rz, zc)`, or a mapping with those keys. The demo's+ head table is the three-tuple form with the z offsets held in a parallel array, so both are real.+ """+ out: list[Ring] = []+ for index, ring in enumerate(rings):+ label = f"ring[{index}]"+ if isinstance(ring, dict):+ y = _finite(ring.get("y"), f"{label}.y")+ rx = _finite(ring.get("rx", ring.get("radiusX")), f"{label}.rx")+ rz = _finite(ring.get("rz", ring.get("radiusZ")), f"{label}.rz")+ zc = _finite(ring.get("zc", ring.get("zCentre", 0.0)), f"{label}.zc")+ else:+ values = list(ring)+ if len(values) not in (3, 4):+ raise ValueError(f"{label} must have 3 or 4 values, got {len(values)}")+ y = _finite(values[0], f"{label}.y")+ rx = _finite(values[1], f"{label}.rx")+ rz = _finite(values[2], f"{label}.rz")+ zc = _finite(values[3], f"{label}.zc") if len(values) == 4 else 0.0+ if rx <= 0.0 or rz <= 0.0:+ raise ValueError(f"{label} radii must be positive, got rx={rx} rz={rz}")+ out.append((y, rx, rz, zc))++ if len(out) < 2:+ raise ValueError("a scalp field needs at least 2 rings")+ out.sort(key=lambda r: r[0])+ for lower, upper in zip(out, out[1:]):+ if upper[0] - lower[0] <= 1e-9:+ raise ValueError(f"rings must have distinct y values, found two at y={lower[0]}")+ return out+++class ScalpField:+ """The skull as a lofted ellipse stack, queryable as a signed distance field.++ Negative inside, positive outside, zero on the surface.+ """++ def __init__(self, rings: Iterable[Sequence[float] | dict[str, float]]) -> None:+ self.rings: list[Ring] = normalise_rings(rings)+ self.y_min: float = self.rings[0][0]+ self.y_max: float = self.rings[-1][0]++ # ---- interpolation -------------------------------------------------------------------++ def section(self, y: float) -> tuple[float, float, float]:+ """Interpolated (rx, rz, zCentre) at height `y`, clamped to the stack's own extent."""+ if y <= self.y_min:+ _, rx, rz, zc = self.rings[0]+ return rx, rz, zc+ if y >= self.y_max:+ _, rx, rz, zc = self.rings[-1]+ return rx, rz, zc+ for lower, upper in zip(self.rings, self.rings[1:]):+ if lower[0] <= y <= upper[0]:+ span = upper[0] - lower[0]+ t = (y - lower[0]) / span+ return (+ lower[1] + (upper[1] - lower[1]) * t,+ lower[2] + (upper[2] - lower[2]) * t,+ lower[3] + (upper[3] - lower[3]) * t,+ )+ # Unreachable given the clamps above, but a silent wrong answer here would be a bald patch.+ raise AssertionError(f"no ring interval contains y={y}")++ # ---- the field -----------------------------------------------------------------------++ def radial_distance(self, x: float, y: float, z: float) -> float:+ """Signed distance to the ellipse at this height, ignoring the caps.++ The sign is exact. The magnitude is the first-order estimate `f / |grad f|`.+ """+ rx, rz, zc = self.section(y)+ dx = x / rx+ dz = (z - zc) / rz+ f = dx * dx + dz * dz - 1.0+ # grad f = (2x/rx^2, 2z'/rz^2). At the axis the gradient vanishes and the estimate blows up;+ # the point is then as deep inside as the section is wide, which is the honest answer.+ gx = 2.0 * x / (rx * rx)+ gz = 2.0 * (z - zc) / (rz * rz)+ grad = math.hypot(gx, gz)+ if grad < 1e-12:+ return -min(rx, rz)+ return f / grad++ def distance(self, x: float, y: float, z: float) -> float:+ """Signed distance to the capped ring stack. Negative inside.++ This is the canonical capped-extrusion composition: outside contributions combine by+ Pythagoras, inside contributions take the least-negative (nearest) surface.+ """+ radial = self.radial_distance(x, y, z)+ axial = max(self.y_min - y, y - self.y_max)+ outside = math.hypot(max(radial, 0.0), max(axial, 0.0))+ inside = min(max(radial, axial), 0.0)+ return outside + inside++ # ---- the surface ---------------------------------------------------------------------++ def sample(self, u: float, v: float) -> tuple[float, float, float]:+ """A point on the skull. `u` is azimuth in [0,1), `v` is height in [0,1] bottom to top.++ This is the parametrisation hair roots bind to. A root held as (u,v) cannot slide off the+ skull when its mass is widened, which is the whole reason the binding exists -- the failure+ it prevents is a measured one, not a hypothetical.+ """+ theta = 2.0 * math.pi * u+ y = self.y_min + (self.y_max - self.y_min) * v+ rx, rz, zc = self.section(y)+ return (rx * math.cos(theta), y, zc + rz * math.sin(theta))++ def normal(self, u: float, v: float) -> tuple[float, float, float]:+ """Outward unit normal at `sample(u, v)`.++ Taken as the cross product of the surface's own partial derivatives rather than as the+ horizontal radial direction: the skull's radius changes with height, so near the crown the+ true normal tilts upward substantially and a radial approximation would push hair sideways+ off the top of the head.+ """+ theta = 2.0 * math.pi * u+ cos_t = math.cos(theta)+ sin_t = math.sin(theta)+ height = self.y_max - self.y_min+ y = self.y_min + height * v+ rx, rz, _ = self.section(y)++ # d/dv of the section, by central difference -- the stack is piecewise linear, so the+ # derivative is undefined exactly at a ring and a central difference is the sane reading.+ step = max(height * 1e-4, 1e-9)+ rx_hi, rz_hi, zc_hi = self.section(min(y + step, self.y_max))+ rx_lo, rz_lo, zc_lo = self.section(max(y - step, self.y_min))+ actual = min(y + step, self.y_max) - max(y - step, self.y_min)+ if actual <= 0.0:+ d_rx = d_rz = d_zc = 0.0+ else:+ d_rx = (rx_hi - rx_lo) / actual+ d_rz = (rz_hi - rz_lo) / actual+ d_zc = (zc_hi - zc_lo) / actual++ # dS/du and dS/dv, with y parametrised by v so dy/dv = height.+ du = (-rx * sin_t, 0.0, rz * cos_t)+ dv = (d_rx * cos_t * height, height, (d_zc + d_rz * sin_t) * height)++ # dv x du points outward; verified against a cylinder, where it reduces to (cos, 0, sin).+ nx = dv[1] * du[2] - dv[2] * du[1]+ ny = dv[2] * du[0] - dv[0] * du[2]+ nz = dv[0] * du[1] - dv[1] * du[0]+ length = math.sqrt(nx * nx + ny * ny + nz * nz)+ if length < 1e-12:+ return (cos_t, 0.0, sin_t)+ return (nx / length, ny / length, nz / length)++ # ---- convenience ---------------------------------------------------------------------++ def surface_samples(+ self,+ u_count: int,+ v_count: int,+ v_range: tuple[float, float] = (0.0, 1.0),+ ) -> list[dict[str, Any]]:+ """Area-weighted samples over the surface, for gates that integrate over the scalp.++ Each entry is `{weight, point, normal, u, v, cap}`. The weight is the local patch area, so a+ gate reporting an exposed FRACTION reports area and not sample count -- rings near the crown+ are far shorter in circumference than rings at the temples, and counting samples would let a+ small bare crown hide behind a large well-covered band.++ THE CAP IS INCLUDED, and that is the part worth stating. The (u, v) parametrisation walks v+ from the bottom ring to the top and samples the ELLIPSE at each height, so the flat disc+ closing the stack at `y_max` belongs to no (u, v) and was invisible to a caller that only+ iterated the band. On a skull whose top ring still has real radius that disc IS the crown,+ and a completely bare crown measured as fully covered.+ """+ if u_count < 3 or v_count < 2:+ raise ValueError("need at least 3 azimuth and 2 height samples")+ low, high = v_range+ if not 0.0 <= low < high <= 1.0:+ raise ValueError(f"v_range must be an ascending band inside [0,1], got {v_range}")++ out: list[dict[str, Any]] = []+ height = self.y_max - self.y_min+ band = high - low+ for j in range(v_count):+ v = low + band * (j + 0.5) / v_count+ y = self.y_min + height * v+ rx, rz, _ = self.section(y)+ # Ramanujan's first approximation to the ellipse perimeter; the exact value needs an+ # elliptic integral and the weights only need to be right relative to each other.+ circumference = math.pi * (3.0 * (rx + rz) - math.sqrt((3.0 * rx + rz) * (rx + 3.0 * rz)))+ weight = (circumference / u_count) * (height * band / v_count)+ for i in range(u_count):+ u = i / u_count+ out.append({"weight": weight, "point": self.sample(u, v),+ "normal": self.normal(u, v), "u": u, "v": v, "cap": False})++ if high >= 1.0 - 1e-9:+ top_rx, top_rz, top_zc = self.section(self.y_max)+ cap_rings = max(1, v_count // 4)+ for ring_index in range(cap_rings):+ # Mid-radius of an annulus, so a sample stands for the area around it, not a line.+ middle = (ring_index + 0.5) / cap_rings+ outer = (ring_index + 1) / cap_rings+ inner = ring_index / cap_rings+ annulus = math.pi * top_rx * top_rz * (outer * outer - inner * inner)+ weight = annulus / u_count+ for i in range(u_count):+ u = i / u_count+ angle = 2.0 * math.pi * u+ point = (top_rx * middle * math.cos(angle), self.y_max,+ top_zc + top_rz * middle * math.sin(angle))+ # `capRing` distinguishes the annuli. They all share v = 1.0 by construction,+ # and a consumer that buckets rows by v alone collapses the whole disc into one+ # row -- `largest_exposed_run` then reports a full-circle run the moment any+ # single annulus is bare.+ out.append({"weight": weight, "point": point, "normal": (0.0, 1.0, 0.0),+ "u": u, "v": 1.0, "cap": True, "capRing": ring_index})+ return out+++def field_from_component(component: dict) -> ScalpField:+ """Build the field from a spec component that carries a ring stack.++ Accepts the two shapes the pipeline produces: `geometryDescriptor.ringStack.rings`, and the+ parallel-array form `{rings: [[y, rx, rz], ...], zOffsets: [...]}` that the humanoid head uses.+ """+ descriptor = component.get("geometryDescriptor") if isinstance(component, dict) else None+ if not isinstance(descriptor, dict):+ raise ValueError("component has no geometryDescriptor")+ stack = descriptor.get("ringStack")+ if not isinstance(stack, dict):+ raise ValueError("component.geometryDescriptor has no ringStack")+ rings = stack.get("rings")+ if not isinstance(rings, list) or not rings:+ raise ValueError("ringStack.rings must be a non-empty array")++ offsets = stack.get("zOffsets")+ if isinstance(offsets, list) and offsets:+ if len(offsets) != len(rings):+ raise ValueError(+ f"ringStack.zOffsets has {len(offsets)} entries for {len(rings)} rings"+ )+ merged: list[Sequence[float]] = []+ for ring, offset in zip(rings, offsets):+ values = list(ring)+ if len(values) < 3:+ raise ValueError("each ring needs at least [y, rx, rz]")+ merged.append([values[0], values[1], values[2], offset])+ return ScalpField(merged)+ return ScalpField(rings)diff --git a/forge/_shared/vertex_paint.py b/forge/_shared/vertex_paint.pynew file mode 100644index 0000000..095741f--- /dev/null+++ b/forge/_shared/vertex_paint.py@@ -0,0 +1,236 @@+"""Region-painted vertex colour: the shape predicates, shared by the validator, the gate and TS.++WHY THIS EXISTS. A subject whose identity is a set of flat colour regions with hard boundaries --+a tuxedo cat's blaze, bib and socks; a livery stripe; a painted marking -- cannot be reproduced by+`rootTipGradient`, which is a single linear ramp along one axis, and must not be reproduced by a+texture, because this pipeline emits code and no image assets. The remaining honest representation+is per-vertex colour driven by a declared region shape.++The predicates live here, in Python, rather than only inside the emitted TypeScript, because the+region boundary is an identity feature and therefore has to be GATED -- and a gate that can only run+after a browser render is a gate that runs too late. `forge/stage4_review/vertex_region_gate.py`+evaluates these same functions on exported geometry. `_VERTEX_PAINT_HELPER_SOURCE` in+generate_threejs_factory.py implements the identical maths in TS, and+`forge/tests/test_vertex_paint.py` holds the two to the same numbers on a fixture so they cannot+drift apart silently.++Three shapes, deliberately not more. Each earns its place on a real boundary class:++- `axis-band` a slab between two planes on one local axis -- a sock ending at an ankle height.+- `ellipsoid` a closed blob -- a nose pad, a moustache patch, an inner ear.+- `tapered-capsule` a segment whose radius varies from end to end -- a blaze running down a nose+ bridge, a bib widening under the chin and tapering down the chest. This is the shape a constant+ radius capsule cannot express, and it is the one the bib actually needs.++Every shape takes a `softness` in the component's own local units. `softness: 0` is a hard+boundary. A non-zero softness is a smooth ramp and is the ONLY approximation offered here -- it is+not fur, and anything using it to stand in for a fur fringe must say so.+"""++from __future__ import annotations++import math+from typing import Any, Iterable, Sequence++VALID_REGION_KINDS = {"axis-band", "ellipsoid", "tapered-capsule"}+VALID_AXES = {"x", "y", "z"}+++class VertexPaintError(ValueError):+ """Raised when a paint declaration cannot be evaluated as written."""+++def _as_vec3(value: Any, label: str) -> tuple[float, float, float]:+ if not isinstance(value, (list, tuple)) or len(value) != 3:+ raise VertexPaintError(f"{label} must be a 3-number array")+ out = []+ for item in value:+ if isinstance(item, bool) or not isinstance(item, (int, float)):+ raise VertexPaintError(f"{label} must be a 3-number array")+ out.append(float(item))+ return (out[0], out[1], out[2])+++def _as_number(value: Any, label: str, *, minimum: float | None = None) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise VertexPaintError(f"{label} must be a number")+ number = float(value)+ if minimum is not None and number < minimum:+ raise VertexPaintError(f"{label} must be >= {minimum}")+ return number+++def parse_hex_color(value: Any, label: str) -> tuple[float, float, float]:+ """`#rrggbb` to linear-ish 0..1 floats.++ No colour-space conversion is applied: Three.js decides how to interpret a colour set from a+ hex string, and doing a second conversion here would put the gate and the renderer on two+ different values for the same authored colour.+ """+ if not isinstance(value, str) or not value.startswith("#") or len(value) != 7:+ raise VertexPaintError(f"{label} must be a '#rrggbb' string")+ try:+ red = int(value[1:3], 16)+ green = int(value[3:5], 16)+ blue = int(value[5:7], 16)+ except ValueError as error:+ raise VertexPaintError(f"{label} must be a '#rrggbb' string") from error+ return (red / 255.0, green / 255.0, blue / 255.0)+++def normalize_region(region: Any, label: str) -> dict[str, Any]:+ """Validate one region and return it in canonical form."""+ if not isinstance(region, dict):+ raise VertexPaintError(f"{label} must be an object")+ kind = region.get("kind")+ if kind not in VALID_REGION_KINDS:+ raise VertexPaintError(+ f"{label}.kind must be one of: {', '.join(sorted(VALID_REGION_KINDS))}"+ )+ region_id = region.get("id")+ if not isinstance(region_id, str) or not region_id:+ raise VertexPaintError(f"{label}.id must be a non-empty string")+ color = region.get("color")+ parse_hex_color(color, f"{label}.color")+ softness = _as_number(region.get("softness", 0.0), f"{label}.softness", minimum=0.0)++ canonical: dict[str, Any] = {+ "id": region_id,+ "kind": kind,+ "color": color,+ "softness": softness,+ }+ if kind == "axis-band":+ axis = region.get("axis")+ if axis not in VALID_AXES:+ raise VertexPaintError(f"{label}.axis must be one of: x, y, z")+ low = _as_number(region.get("min"), f"{label}.min")+ high = _as_number(region.get("max"), f"{label}.max")+ if high <= low:+ raise VertexPaintError(f"{label}.max must be greater than {label}.min")+ canonical.update({"axis": axis, "min": low, "max": high})+ elif kind == "ellipsoid":+ canonical["center"] = list(_as_vec3(region.get("center"), f"{label}.center"))+ radii = _as_vec3(region.get("radii"), f"{label}.radii")+ if min(radii) <= 0.0:+ raise VertexPaintError(f"{label}.radii must all be positive")+ canonical["radii"] = list(radii)+ else:+ canonical["start"] = list(_as_vec3(region.get("start"), f"{label}.start"))+ canonical["end"] = list(_as_vec3(region.get("end"), f"{label}.end"))+ start_radius = _as_number(region.get("startRadius"), f"{label}.startRadius", minimum=0.0)+ end_radius = _as_number(region.get("endRadius"), f"{label}.endRadius", minimum=0.0)+ if start_radius <= 0.0 and end_radius <= 0.0:+ raise VertexPaintError(f"{label} needs at least one positive radius")+ if canonical["start"] == canonical["end"]:+ raise VertexPaintError(f"{label}.start and {label}.end must differ")+ canonical.update({"startRadius": start_radius, "endRadius": end_radius})+ return canonical+++def normalize_vertex_paint(paint: Any, label: str = "vertexPaint") -> dict[str, Any]:+ """Validate a whole `vertexPaint` block and return it in canonical form."""+ if not isinstance(paint, dict):+ raise VertexPaintError(f"{label} must be an object")+ base_color = paint.get("baseColor")+ parse_hex_color(base_color, f"{label}.baseColor")+ regions = paint.get("regions")+ if not isinstance(regions, list) or not regions:+ raise VertexPaintError(f"{label}.regions must be a non-empty array")+ seen: set[str] = set()+ canonical_regions = []+ for index, region in enumerate(regions):+ canonical = normalize_region(region, f"{label}.regions[{index}]")+ if canonical["id"] in seen:+ raise VertexPaintError(f"{label}.regions has a duplicate id {canonical['id']!r}")+ seen.add(canonical["id"])+ canonical_regions.append(canonical)+ return {"baseColor": base_color, "regions": canonical_regions}+++def _smoothstep(edge0: float, edge1: float, value: float) -> float:+ if edge1 <= edge0:+ return 0.0 if value < edge1 else 1.0+ t = (value - edge0) / (edge1 - edge0)+ t = 0.0 if t < 0.0 else 1.0 if t > 1.0 else t+ return t * t * (3.0 - 2.0 * t)+++def signed_distance(region: dict[str, Any], point: Sequence[float]) -> float:+ """Distance from `point` to the region boundary: negative inside, positive outside.++ Reported in the component's own local units so `softness` is expressed in the same units as+ the geometry, not in a normalised parameter nobody can measure against the reference.+ """+ x, y, z = float(point[0]), float(point[1]), float(point[2])+ kind = region["kind"]+ if kind == "axis-band":+ value = {"x": x, "y": y, "z": z}[region["axis"]]+ low, high = region["min"], region["max"]+ if value < low:+ return low - value+ if value > high:+ return value - high+ return -min(value - low, high - value)+ if kind == "ellipsoid":+ cx, cy, cz = region["center"]+ rx, ry, rz = region["radii"]+ # Scaled-space distance times the smallest radius: an exact SDF for a sphere and a+ # conservative, continuous approximation for a general ellipsoid. It is monotonic in the+ # true distance, which is all the boundary test and the softness ramp need.+ q = math.sqrt(((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 + ((z - cz) / rz) ** 2)+ return (q - 1.0) * min(rx, ry, rz)+ ax, ay, az = region["start"]+ bx, by, bz = region["end"]+ abx, aby, abz = bx - ax, by - ay, bz - az+ apx, apy, apz = x - ax, y - ay, z - az+ denominator = abx * abx + aby * aby + abz * abz+ t = (apx * abx + apy * aby + apz * abz) / denominator if denominator > 0.0 else 0.0+ t = 0.0 if t < 0.0 else 1.0 if t > 1.0 else t+ closest = (ax + abx * t, ay + aby * t, az + abz * t)+ distance = math.sqrt(+ (x - closest[0]) ** 2 + (y - closest[1]) ** 2 + (z - closest[2]) ** 2+ )+ radius = region["startRadius"] + (region["endRadius"] - region["startRadius"]) * t+ return distance - radius+++def region_weight(region: dict[str, Any], point: Sequence[float]) -> float:+ """How strongly a region claims a point: 1 well inside, 0 well outside."""+ distance = signed_distance(region, point)+ softness = region["softness"]+ if softness <= 0.0:+ return 1.0 if distance <= 0.0 else 0.0+ return 1.0 - _smoothstep(-softness * 0.5, softness * 0.5, distance)+++def paint_point(paint: dict[str, Any], point: Sequence[float]) -> tuple[float, float, float]:+ """The final colour at one local-space point, regions applied in declaration order."""+ color = list(parse_hex_color(paint["baseColor"], "vertexPaint.baseColor"))+ for region in paint["regions"]:+ weight = region_weight(region, point)+ if weight <= 0.0:+ continue+ target = parse_hex_color(region["color"], "region.color")+ for channel in range(3):+ color[channel] += (target[channel] - color[channel]) * weight+ return (color[0], color[1], color[2])+++def dominant_region(paint: dict[str, Any], point: Sequence[float], threshold: float = 0.5) -> str:+ """Which region owns a point, or `'base'`.++ Later regions win ties, matching `paint_point`'s ordered application: the last region to claim+ a point is the one whose colour ends up dominating it.+ """+ owner = "base"+ for region in paint["regions"]:+ if region_weight(region, point) >= threshold:+ owner = region["id"]+ return owner+++def classify_points(+ paint: dict[str, Any], points: Iterable[Sequence[float]], threshold: float = 0.5+) -> list[str]:+ return [dominant_region(paint, point, threshold) for point in points]diff --git a/forge/next.py b/forge/next.pyindex 32e4e20..46a0b37 100644--- a/forge/next.py+++ b/forge/next.py@@ -64,6 +64,13 @@ def main(argv: list[str]) -> int:else:local_state["artifacts"]["spec"] = str(spec_path)+ if spec_path is not None and local_state is not None and not spec_path.expanduser().is_file():+ # `state.py init --spec <path>` records where the spec WILL be written, so between init+ # and spec-authoring that path does not exist yet. That is the normal pre-spec state, not+ # an error: fall back to the local checklist report so the mandatory gate stays runnable+ # for the whole pre-spec phase instead of hard-failing on its own documented first step.+ spec_path = None+if spec_path is None:if local_state is None:parser.error("spec is required unless --state points to an initialized pre-spec workflow")diff --git a/forge/stage1_intake/extract_hair_evidence.py b/forge/stage1_intake/extract_hair_evidence.pynew file mode 100644index 0000000..9ec1e11--- /dev/null+++ b/forge/stage1_intake/extract_hair_evidence.py@@ -0,0 +1,385 @@+#!/usr/bin/env python3+"""Measure what a reference image actually says about its hair.++WHAT WAS MISSING. `faceLandmarks.hairline` has existed as a slot since v1.2 and no generator has+ever read it, because nothing ever filled it. Banded dark coverage -- the measurement that finally+localised a hair deficit to the mid band -- was run by hand, four times, and never became a script.+And nothing at all measured the SHADING, which is where the deficit turned out mostly to live.++WHY SHADING IS IN HERE AT ALL. The reference this pipeline calibrates against is a 570,400-vertex+merged scan whose hair surface roughness is 0.00338 against a torso control of 0.00312. Its hair is+a smooth shell; every strand it appears to have is in the diffuse and normal textures. A pipeline+that emits code and no textures cannot copy that with geometry, so the numbers worth extracting are+the ones a material can act on: where the highlight band sits, and how much darker the roots are+than the tips.++WHAT THIS DELIBERATELY DOES NOT DO. It does not guess lock geometry. A single image does not carry+it, the reference does not contain it, and inventing it is how eleven hair locks ended up sharing a+tip radius of 0.0327.++Pure Python 3.10+ standard library.+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path+from typing import Any, Sequence++sys.path.insert(0, str(Path(__file__).resolve().parent))++from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402++# Hair is dark against skin at every skin tone the reference set contains, but "dark" has to be+# relative or a blonde subject reports no hair at all.+#+# The threshold is the between-class variance maximum (Otsu) over the head's own luminance+# histogram. A fixed PERCENTILE was tried first and is a trap: taking the 38th percentile as the+# cut makes "38% of head pixels are hair" true by construction. It measured 0.380, 0.384 and 0.382+# on three different views of the same subject, which looks like agreement and is arithmetic.+# Otsu finds where the distribution actually splits, so a bald head reports little hair and a+# hooded one reports a lot.+OTSU_BINS = 64+# If the two classes Otsu finds are barely separated there is no hair/skin split to speak of -- a+# bald head, or a subject cropped so tightly that only hair is in frame. Reported rather than+# silently returning a threshold through the middle of one population.+MIN_CLASS_SEPARATION = 12.0+# ... and the two classes must be far apart RELATIVE TO THEIR OWN SPREAD. Separation alone does not+# catch a single broad population: an ordinarily lit BALD head has a wide luminance spread from+# shading and measures a separation of 38.6, three times the floor above, while reporting a quarter+# of its scalp as hair.+#+# This bound is one of the few in the hair subsystem with real endpoints under it, because the+# archived BALD calibration capture is genuine ground truth for "no hair":+#+# unimodal, theoretical 1.732 any uniform spread cut at its own middle, sqrt(3)+# bald, synthetic key light 1.735 and identical at every gradient width, as predicted+# BALD capture, real render 1.119 <-- the measured floor+# reference front view 2.450 <-- the measured ceiling, and the tightest real case+# reference profile 3.603+# reference rear 4.177+#+# 2.0 sits between the two measured neighbours, 15% above the theoretical unimodal value and 22%+# below the tightest genuine hair view. A first attempt at 3.0 was invented rather than measured and+# rejected the reference's own front view.+MIN_SEPARABILITY = 2.0+# Reported in place of infinity when both classes are exactly constant. Finite because this value is+# serialised, and `json.dumps(float("inf"))` writes a bare `Infinity` that RFC 8259 forbids.+SEPARABILITY_MAX = 1.0e6+# Bands across the head, top to bottom. Three is what the by-hand measurement used, and it was+# enough to localise the deficit to the middle one.+BAND_NAMES = ("crown", "mid", "jaw")+# Fraction of the figure's height taken to be head. Anchored on the reference's own proportion --+# a 1.75m figure whose head spans y 1.52 to 1.75 -- which is 0.13, rounded up for framing slack.+HEAD_FRACTION = 0.15+# Views that see the back of the head. Anything not in here leaves the rear unobserved, and the+# report has to say so rather than let a generator invent a nape.+#+# A profile sees the nape and the rear mass in outline, which is weaker evidence than a true rear+# view but is evidence. `right-profile` was missing purely because the capture set this was written+# against names its two side views `profile` and `left-profile`; a set that spells both sides out+# would have had one of them silently ignored.+REAR_VIEWS = {+ "rear", "back", "orbit-plus-145", "orbit-minus-145",+ "profile", "left-profile", "right-profile",+}+++def _luma(pixel: tuple[int, int, int, int]) -> float:+ return 0.2126 * pixel[0] + 0.7152 * pixel[1] + 0.0722 * pixel[2]+++def otsu_threshold(values: Sequence[float], bins: int = OTSU_BINS) -> tuple[float, float, float]:+ """Split a luminance population in two where the between-class variance is greatest.++ Returns `(threshold, separation, separability)`.++ `separation` is the gap between the two class means. `separability` is that gap divided by the+ two classes' combined standard deviation -- large when the classes are genuinely distinct, and+ around 1.7 for ANY single broad population cut down the middle.++ SEPARABILITY IS NOT OPTIONAL. Otsu always returns a split, even from one population, and+ separation alone does not catch that: an ordinarily lit BALD head has a wide luminance spread+ from shading and measures a separation of 38.6, three times over any sane floor, while+ reporting a quarter of its scalp as hair.+ """+ if not values:+ return (0.0, 0.0, 0.0)+ low = min(values)+ high = max(values)+ if high - low < 1e-9:+ return (low, 0.0, 0.0)++ histogram = [0] * bins+ width = (high - low) / bins+ for value in values:+ index = min(bins - 1, int((value - low) / width))+ histogram[index] += 1++ total = len(values)+ sum_all = sum((low + (i + 0.5) * width) * count for i, count in enumerate(histogram))+ best_variance = -1.0+ best_index = 0+ weight_below = 0+ sum_below = 0.0+ for index, count in enumerate(histogram[:-1]):+ weight_below += count+ if weight_below == 0:+ continue+ weight_above = total - weight_below+ if weight_above == 0:+ break+ sum_below += (low + (index + 0.5) * width) * count+ mean_below = sum_below / weight_below+ mean_above = (sum_all - sum_below) / weight_above+ variance = weight_below * weight_above * (mean_below - mean_above) ** 2+ if variance > best_variance:+ best_variance = variance+ best_index = index++ threshold = low + (best_index + 1) * width+ below = [v for v in values if v <= threshold]+ above = [v for v in values if v > threshold]+ if not below or not above:+ return (threshold, 0.0, 0.0)+ mean_below = sum(below) / len(below)+ mean_above = sum(above) / len(above)+ separation = abs(mean_above - mean_below)++ # SEPARABILITY, not histogram shape. Two shape-based attempts failed here, each on a different+ # edge case, and both are recorded because the failures are instructive:+ #+ # valley = min bin between the peaks Broke on QUANTISATION. An 8-bit gradient lands on far+ # fewer distinct values than there are bins, so empty+ # bins scatter through a perfectly unimodal spread and+ # read as a bottomless valley. A key-lit bald head+ # scored 0.000 -- maximally bimodal -- and passed as 50%+ # hair.+ # valley = the bin at the cut Broke when the cut lands beside a spike, which is what+ # a two-tone synthetic image always does. Every haired+ # fixture scored 1.0 and was thrown out.+ #+ # This measure asks the question directly: are the two classes far apart RELATIVE TO THEIR OWN+ # spread? Two tight clusters give a large ratio. One broad population cut down the middle gives+ # about 1.7 whatever its width, because widening it grows the gap and the spreads together.+ # No bins, no smoothing, no peak finding, nothing to tune.+ spread_below = (sum((v - mean_below) ** 2 for v in below) / len(below)) ** 0.5+ spread_above = (sum((v - mean_above) ** 2 for v in above) / len(above)) ** 0.5+ total_spread = spread_below + spread_above+ if total_spread < 1e-9:+ # Two exactly-constant classes -- as separated as it is possible to be, and the arithmetic+ # answer is infinity. A FINITE sentinel goes out instead, because this value is serialised:+ # `json.dumps(float("inf"))` emits a bare `Infinity`, which RFC 8259 does not allow. Python's+ # own loader accepts it, so every test here parsed it happily while `jq`, `JSON.parse` and+ # any strict validator would reject the file the CLI had just written. And this is not a+ # rare branch: a two-tone synthetic image hits it every time.+ return (threshold, separation, SEPARABILITY_MAX)+ return (threshold, separation, min(separation / total_spread, SEPARABILITY_MAX))+++def _bbox(mask: Sequence[bool], width: int) -> tuple[int, int, int, int] | None:+ rows = [i // width for i, on in enumerate(mask) if on]+ if not rows:+ return None+ columns = [i % width for i, on in enumerate(mask) if on]+ return (min(columns), min(rows), max(columns), max(rows))+++def analyse_view(path: Path, view: str) -> dict[str, Any]:+ """Everything one image can honestly say about the hair in it."""+ width, height, pixels, warnings = load_image(path)+ mask, _mask_info, mask_warnings = build_foreground_mask(width, height, pixels)+ warnings = list(warnings) + list(mask_warnings)++ box = _bbox(mask, width)+ if box is None:+ return {"view": view, "status": "no-foreground", "warnings": warnings + ["empty mask"]}+ x0, y0, x1, y1 = box+ figure_height = y1 - y0 + 1+ head_bottom = y0 + max(1, int(figure_height * HEAD_FRACTION))++ head_pixels: list[tuple[int, int, float]] = []+ for y in range(y0, head_bottom + 1):+ for x in range(x0, x1 + 1):+ index = y * width + x+ if mask[index]:+ head_pixels.append((x, y, _luma(pixels[index])))+ if not head_pixels:+ return {"view": view, "status": "no-head-region", "warnings": warnings}++ threshold, separation, separability = otsu_threshold([luma for _, _, luma in head_pixels])+ if separation < MIN_CLASS_SEPARATION or separability < MIN_SEPARABILITY:+ reason = (+ f"class separation {separation:.1f} < {MIN_CLASS_SEPARATION}"+ if separation < MIN_CLASS_SEPARATION+ else f"separability {separability:.2f} < {MIN_SEPARABILITY}, so the spread is one broad "+ f"population cut down the middle -- shading on bare skin looks exactly like this"+ )+ return {+ "view": view,+ "status": "no-hair-skin-split",+ "darkThreshold": round(threshold, 2),+ "classSeparation": round(separation, 2),+ "separability": round(separability, 3),+ "warnings": warnings + [+ f"the head region has one luminance population, not two ({reason}); this view "+ f"cannot tell hair from skin"+ ],+ }+ hair = [(x, y, luma) for x, y, luma in head_pixels if luma <= threshold]++ # ---- banded coverage: the by-hand measurement, made repeatable ----+ head_height = head_bottom - y0 + 1+ bands: dict[str, dict[str, float]] = {}+ for band_index, band_name in enumerate(BAND_NAMES):+ top = y0 + int(head_height * band_index / len(BAND_NAMES))+ bottom = y0 + int(head_height * (band_index + 1) / len(BAND_NAMES))+ in_band = [(x, y, luma) for x, y, luma in head_pixels if top <= y < max(bottom, top + 1)]+ dark = [p for p in in_band if p[2] <= threshold]+ bands[band_name] = {+ "coverage": round(len(dark) / len(in_band), 4) if in_band else 0.0,+ "meanLuma": round(sum(p[2] for p in dark) / len(dark), 2) if dark else 0.0,+ "pixelCount": len(in_band),+ }++ # ---- hairline: where the hair stops and the face starts ----+ # Per column, walk down from the top of the head and record the first non-hair row. Reported as+ # a fraction of figure height, which is the unit `faceLandmarks` already uses.+ hair_rows_by_column: dict[int, list[int]] = {}+ for x, y, _ in hair:+ hair_rows_by_column.setdefault(x, []).append(y)+ crossings: list[float] = []+ for x, rows in hair_rows_by_column.items():+ rows.sort()+ run_end = rows[0]+ for row in rows[1:]:+ if row - run_end > 2:+ break+ run_end = row+ crossings.append((run_end - y0) / figure_height)+ crossings.sort()+ hairline = round(crossings[len(crossings) // 2], 4) if crossings else None++ # ---- shading: where the highlight band sits, and how much darker the roots are ----+ #+ # Measured over rows the hair OWNS, not over the sub-threshold pixels alone. A specular band on+ # dark hair is bright by definition, so it lands above the hair/skin threshold and a naive pass+ # discards exactly the thing it is looking for -- measured on a fixture whose planted highlight+ # had luminance 132.8: the reported band luminance came back as 31.8, the base hair colour, and+ # the highlight was invisible to it. A row that is majority hair is a hair row, and every head+ # pixel in it counts.+ hair_by_row: dict[int, int] = {}+ total_by_row: dict[int, list[float]] = {}+ for _, y, _ in hair:+ hair_by_row[y] = hair_by_row.get(y, 0) + 1+ for _, y, luma in head_pixels:+ total_by_row.setdefault(y, []).append(luma)+ owned = {+ y for y, values in total_by_row.items()+ if len(values) >= 3 and hair_by_row.get(y, 0) >= len(values) * 0.5+ }+ # A row can be blown out end to end -- glossy hair under a key light does exactly this -- and+ # then it holds no sub-threshold pixels at all and the majority test drops it. Since it is the+ # brightest row, dropping it removes the highlight the moment the highlight is strong enough to+ # matter. Any row ENCLOSED by owned rows is owned: hair does not stop for one row and resume.+ if owned:+ for y in range(min(owned), max(owned) + 1):+ if y in total_by_row and len(total_by_row[y]) >= 3:+ owned.add(y)+ row_means = {y: sum(total_by_row[y]) / len(total_by_row[y]) for y in owned}+ specular_row = max(row_means, key=lambda y: row_means[y]) if row_means else None+ ordered_rows = sorted(row_means)+ if len(ordered_rows) >= 6:+ third = max(1, len(ordered_rows) // 3)+ top_mean = sum(row_means[y] for y in ordered_rows[:third]) / third+ bottom_mean = sum(row_means[y] for y in ordered_rows[-third:]) / third+ root_tip_delta = round(bottom_mean - top_mean, 2)+ else:+ root_tip_delta = None++ return {+ "view": view,+ "status": "measured",+ "figureBox": {"x0": x0, "y0": y0, "x1": x1, "y1": y1},+ "darkThreshold": round(threshold, 2),+ "classSeparation": round(separation, 2),+ "separability": round(separability, 3),+ "hairFraction": round(len(hair) / len(head_pixels), 4),+ "bands": bands,+ "hairline": hairline,+ "shading": {+ "specularBandV": (+ round((specular_row - y0) / max(1, head_height), 4) if specular_row is not None else None+ ),+ "specularBandLuma": round(row_means[specular_row], 2) if specular_row is not None else None,+ "rootToTipLumaDelta": root_tip_delta,+ "note": (+ "rootToTipLumaDelta is lower-row mean minus upper-row mean, so a positive value "+ "means the hair gets LIGHTER downward. Which end is the root depends on the "+ "hairstyle and is not inferred here."+ ),+ },+ "warnings": warnings,+ }+++def extract_hair_evidence(views: dict[str, Path]) -> dict[str, Any]:+ """Combine per-view measurements and state plainly what was never seen."""+ per_view = {name: analyse_view(path, name) for name, path in sorted(views.items())}+ measured = {name: data for name, data in per_view.items() if data.get("status") == "measured"}++ hairlines = [d["hairline"] for d in measured.values() if d.get("hairline") is not None]+ consensus = round(sorted(hairlines)[len(hairlines) // 2], 4) if hairlines else None++ not_observed: list[str] = []+ if not any(name in REAR_VIEWS for name in measured):+ not_observed.append(+ "rear: no view in this set sees the back of the head, so the nape and rear mass are "+ "unobserved. Do not author them as if measured."+ )+ if len(measured) < 2:+ not_observed.append(+ "depth: a single view cannot separate hair thickness from hair silhouette."+ )+ if not hairlines:+ not_observed.append("hairline: no view produced a usable hair/skin boundary.")++ return {+ "schemaVersion": 1,+ "kind": "hair-evidence",+ "views": per_view,+ "faceLandmarks": {"hairline": consensus} if consensus is not None else {},+ "notObserved": not_observed,+ "confidence": round(min(1.0, len(measured) / 4.0), 3),+ "calibrationNote": (+ "Envelope and shading numbers are measurable from an image. Lock geometry is not, and "+ "is not reported: the reference this pipeline calibrates against is a merged scan whose "+ "hair is a smooth shell with all strand detail in textures."+ ),+ }+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("images", nargs="+", help="view=path pairs, e.g. front=ref.front.png")+ parser.add_argument("--out")+ args = parser.parse_args(argv)++ views: dict[str, Path] = {}+ for entry in args.images:+ if "=" not in entry:+ parser.error(f"expected view=path, got {entry!r}")+ name, _, raw = entry.partition("=")+ views[name] = Path(raw)++ report = extract_hair_evidence(views)+ text = json.dumps(report, indent=2)+ if args.out:+ Path(args.out).write_text(text + "\n")+ print(text)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/forge/stage1_intake/label_glb_nodes.py b/forge/stage1_intake/label_glb_nodes.pynew file mode 100644index 0000000..31bfe4a--- /dev/null+++ b/forge/stage1_intake/label_glb_nodes.py@@ -0,0 +1,318 @@+#!/usr/bin/env python3+"""Label a multipart GLB's mesh nodes from MEASURED world-space bounds, never from their names.++WHY THIS REFUSES TO READ NAMES. `probe_glb.py` can report `reliableSemanticBoundary:+named-node-or-mesh` while every name is meaningless -- the reference this was written against has 16+nodes called `root.0`..`root.15` and 16 materials with the same strings. A pipeline that trusts those+names will confidently call a boot a knee pad, and every per-region comparison built on top inherits+the error silently. So the only inputs here are geometry: each node's world-space axis-aligned bounds,+normalised against the figure's own height.++WHAT THIS IS, EXACTLY. Hypothesis evidence, at the level `SKILL.md`'s GLB track allows for+connected-component/curvature segmentation -- NOT a confirmed semantic label. Every entry carries a+`confidence` and the measurement that produced it, and the report's `status` stays+`hypothesis-requires-render-confirmation` until a browser semantic-ID pass confirms it. Treating this+output as confirmed is the failure it is designed to make visible rather than prevent.++Only the glTF JSON chunk is read. Accessors carry POSITION `min`/`max`, so per-mesh bounds are exact+without decoding a single vertex -- which matters when the asset is 104 MB.++Pure Python 3.10+ standard library.+"""+from __future__ import annotations++import argparse+import json+import struct+import sys+from pathlib import Path+from typing import Any, Sequence++GLB_MAGIC = 0x46546C67+CHUNK_JSON = 0x4E4F534A++# Height fractions of the figure's own bounding box. Derived from human proportion, not tuned against+# this asset: a boot sole is at 0, a head crown at 1. Bands overlap on purpose -- an overlap produces+# a lower confidence and a named ambiguity, which is the honest answer for a node that spans two.+BANDS: tuple[tuple[str, float, float], ...] = (+ ("footwear", 0.00, 0.12),+ ("lower-leg", 0.10, 0.30),+ ("knee", 0.28, 0.42),+ ("thigh", 0.38, 0.55),+ ("hip-waist", 0.50, 0.62),+ ("torso", 0.60, 0.80),+ ("shoulder-neck", 0.78, 0.88),+ ("head", 0.86, 1.00),+)++# Below this fraction of the figure's half-width, a node sits on the midline and has no side.+MIDLINE_FRACTION = 0.08+++def _read_gltf_json(path: Path) -> dict[str, Any]:+ with path.open("rb") as handle:+ header = handle.read(12)+ if len(header) < 12:+ raise ValueError("file is too short to be a GLB")+ magic, _version, _length = struct.unpack("<III", header)+ if magic != GLB_MAGIC:+ raise ValueError("not a GLB container (bad magic)")+ chunk_header = handle.read(8)+ if len(chunk_header) < 8:+ raise ValueError("GLB has no chunk header")+ chunk_length, chunk_type = struct.unpack("<II", chunk_header)+ if chunk_type != CHUNK_JSON:+ raise ValueError("first GLB chunk is not JSON")+ payload = handle.read(chunk_length)+ return json.loads(payload.decode("utf-8"))+++def _identity() -> list[float]:+ return [1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0]+++def _compose(node: dict[str, Any]) -> list[float]:+ """Column-major 4x4 for a glTF node, from `matrix` or from TRS."""+ if isinstance(node.get("matrix"), list) and len(node["matrix"]) == 16:+ return [float(v) for v in node["matrix"]]+ tx, ty, tz = (node.get("translation") or [0.0, 0.0, 0.0])[:3]+ qx, qy, qz, qw = (node.get("rotation") or [0.0, 0.0, 0.0, 1.0])[:4]+ sx, sy, sz = (node.get("scale") or [1.0, 1.0, 1.0])[:3]+ # Rotation matrix from quaternion, then scale each basis column.+ xx, yy, zz = qx * qx, qy * qy, qz * qz+ xy, xz, yz = qx * qy, qx * qz, qy * qz+ wx, wy, wz = qw * qx, qw * qy, qw * qz+ r = [+ 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy),+ 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx),+ 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy),+ ]+ return [+ r[0] * sx, r[1] * sx, r[2] * sx, 0.0,+ r[3] * sy, r[4] * sy, r[5] * sy, 0.0,+ r[6] * sz, r[7] * sz, r[8] * sz, 0.0,+ float(tx), float(ty), float(tz), 1.0,+ ]+++def _multiply(a: Sequence[float], b: Sequence[float]) -> list[float]:+ """Column-major `a * b`, applying b first."""+ out = [0.0] * 16+ for col in range(4):+ for row in range(4):+ out[col * 4 + row] = sum(a[k * 4 + row] * b[col * 4 + k] for k in range(4))+ return out+++def _apply(matrix: Sequence[float], point: Sequence[float]) -> tuple[float, float, float]:+ x, y, z = point+ return (+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14],+ )+++def _mesh_local_bounds(gltf: dict[str, Any], mesh_index: int) -> tuple[list[float], list[float]] | None:+ """Union of every primitive's POSITION accessor min/max. Exact, and reads no vertex data."""+ meshes = gltf.get("meshes") or []+ accessors = gltf.get("accessors") or []+ if mesh_index >= len(meshes):+ return None+ lo = [float("inf")] * 3+ hi = [float("-inf")] * 3+ found = False+ for primitive in meshes[mesh_index].get("primitives") or []:+ position = (primitive.get("attributes") or {}).get("POSITION")+ if position is None or position >= len(accessors):+ continue+ accessor = accessors[position]+ amin, amax = accessor.get("min"), accessor.get("max")+ if not (isinstance(amin, list) and isinstance(amax, list) and len(amin) >= 3):+ continue+ found = True+ for axis in range(3):+ lo[axis] = min(lo[axis], float(amin[axis]))+ hi[axis] = max(hi[axis], float(amax[axis]))+ return (lo, hi) if found else None+++def _world_bounds(matrix: Sequence[float], lo: Sequence[float], hi: Sequence[float]) -> dict[str, list[float]]:+ """AABB of the transformed local AABB. All 8 corners, because a rotation makes the naive+ min/max-of-endpoints answer wrong."""+ wlo = [float("inf")] * 3+ whi = [float("-inf")] * 3+ for ix in (lo[0], hi[0]):+ for iy in (lo[1], hi[1]):+ for iz in (lo[2], hi[2]):+ for axis, value in enumerate(_apply(matrix, (ix, iy, iz))):+ wlo[axis] = min(wlo[axis], value)+ whi[axis] = max(whi[axis], value)+ return {+ "min": [round(v, 6) for v in wlo],+ "max": [round(v, 6) for v in whi],+ "center": [round((wlo[i] + whi[i]) / 2, 6) for i in range(3)],+ "size": [round(whi[i] - wlo[i], 6) for i in range(3)],+ }+++def _collect(gltf: dict[str, Any]) -> list[dict[str, Any]]:+ """Every mesh-bearing node with its world matrix, walking the scene tree parents-first."""+ nodes = gltf.get("nodes") or []+ scenes = gltf.get("scenes") or []+ scene_index = gltf.get("scene", 0)+ roots = scenes[scene_index].get("nodes", []) if scene_index < len(scenes) else list(range(len(nodes)))+ collected: list[dict[str, Any]] = []+ stack: list[tuple[int, list[float]]] = [(int(r), _identity()) for r in roots]+ seen: set[int] = set()+ while stack:+ index, parent = stack.pop()+ if index in seen or index >= len(nodes):+ continue+ seen.add(index)+ node = nodes[index]+ world = _multiply(parent, _compose(node))+ if isinstance(node.get("mesh"), int):+ local = _mesh_local_bounds(gltf, node["mesh"])+ if local is not None:+ collected.append({+ "nodeIndex": index,+ "nodeName": node.get("name"),+ "meshIndex": node["mesh"],+ "bounds": _world_bounds(world, local[0], local[1]),+ })+ for child in node.get("children") or []:+ stack.append((int(child), world))+ return sorted(collected, key=lambda e: e["nodeIndex"])+++def _classify(entry: dict[str, Any], figure: dict[str, list[float]]) -> dict[str, Any]:+ """Height band + lateral side, from measurement only. Overlap lowers confidence and is named."""+ base_y, top_y = figure["min"][1], figure["max"][1]+ height = max(top_y - base_y, 1e-9)+ centre = entry["bounds"]["center"]+ lo_f = (entry["bounds"]["min"][1] - base_y) / height+ hi_f = (entry["bounds"]["max"][1] - base_y) / height+ mid_f = (centre[1] - base_y) / height++ matches = [name for name, low, high in BANDS if not (hi_f < low or lo_f > high)]+ containing = [name for name, low, high in BANDS if low <= mid_f <= high]+ band = containing[0] if containing else (matches[0] if matches else "unbanded")++ half_width = max(abs(figure["min"][0]), abs(figure["max"][0]), 1e-9)+ lateral = centre[0] / half_width+ if abs(lateral) < MIDLINE_FRACTION:+ side = "midline"+ else:+ # With forward +Z and a right-handed frame the character's own left is +X. Same convention as+ # forge/_shared/chirality.py CHARACTER_LEFT_SIGN, which exists so this cannot silently diverge.+ side = "left" if lateral > 0 else "right"++ span_fraction = hi_f - lo_f+ # A node spanning most of the figure is a merged multi-part shell, not one body part. Saying so is+ # more useful than picking whichever band its centroid happens to land in.+ if span_fraction > 0.45:+ band, confidence, reason = "multi-region-shell", 0.20, "spans >45% of figure height"+ elif len(matches) > 2:+ confidence, reason = 0.35, f"overlaps {len(matches)} height bands: {', '.join(matches)}"+ elif len(matches) == 2:+ confidence, reason = 0.55, f"straddles {matches[0]} and {matches[1]}"+ else:+ confidence, reason = 0.70, "centroid falls inside exactly one height band"++ return {+ "partHypothesis": f"{band}-{side}" if side != "midline" else band,+ "band": band,+ "side": side,+ "confidence": confidence,+ "evidence": {+ "method": "measured-world-bounds",+ "heightFractionRange": [round(lo_f, 4), round(hi_f, 4)],+ "centroidHeightFraction": round(mid_f, 4),+ "lateralFractionOfHalfWidth": round(lateral, 4),+ "reason": reason,+ },+ }+++def label(path: Path) -> dict[str, Any]:+ gltf = _read_gltf_json(path)+ entries = _collect(gltf)+ if not entries:+ raise ValueError("no mesh-bearing nodes found; this is not usable as a multipart baseline")++ lo = [min(e["bounds"]["min"][i] for e in entries) for i in range(3)]+ hi = [max(e["bounds"]["max"][i] for e in entries) for i in range(3)]+ figure = {+ "min": [round(v, 6) for v in lo],+ "max": [round(v, 6) for v in hi],+ "size": [round(hi[i] - lo[i], 6) for i in range(3)],+ }++ labelled = []+ for entry in entries:+ labelled.append({**entry, **_classify(entry, figure)})++ # A name is recorded as an observation and never used as evidence. If a caller ever wants to trust+ # it, this flag is what they have to argue past.+ names = [e.get("nodeName") for e in entries]+ return {+ "schemaVersion": 1,+ "kind": "glb-semantic-map",+ "status": "hypothesis-requires-render-confirmation",+ "source": {"path": str(path), "nodeCount": len(entries)},+ "figureBounds": figure,+ "namesUsedAsEvidence": False,+ "observedNodeNames": names,+ "nodes": labelled,+ "note": (+ "Labels are hypotheses from measured world bounds, at the confidence level SKILL.md allows "+ "for geometric segmentation. Confirm each with a browser semantic-ID pass before asserting "+ "any per-region result against this baseline."+ ),+ }+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("glb", type=Path)+ parser.add_argument("--out", type=Path)+ parser.add_argument(+ "--min-confidence",+ type=float,+ default=0.0,+ help="exit 1 if any node lands below this; use it to gate a downstream per-region claim",+ )+ args = parser.parse_args(argv)++ try:+ report = label(args.glb)+ except ValueError as error:+ print(f"FAILED: {error}", file=sys.stderr)+ return 2++ if args.out:+ args.out.parent.mkdir(parents=True, exist_ok=True)+ args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")++ weak = [n for n in report["nodes"] if n["confidence"] < args.min_confidence]+ for node in report["nodes"]:+ print(+ f" node {node['nodeIndex']:>3} {str(node['nodeName'])[:18]:20s} "+ f"{node['partHypothesis']:24s} conf={node['confidence']:.2f} "+ f"y={node['evidence']['heightFractionRange']} {node['evidence']['reason']}"+ )+ print(f"\n{len(report['nodes'])} nodes, figure size {report['figureBounds']['size']}")+ print(f"status: {report['status']}")+ if weak:+ print(+ f"\nFAILED: {len(weak)} node(s) below --min-confidence {args.min_confidence}: "+ f"{', '.join(str(n['nodeIndex']) for n in weak)}",+ file=sys.stderr,+ )+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/forge/stage2_spec/hair_profile.py b/forge/stage2_spec/hair_profile.pynew file mode 100644index 0000000..cd9374c--- /dev/null+++ b/forge/stage2_spec/hair_profile.py@@ -0,0 +1,306 @@+#!/usr/bin/env python3+"""The semantic description of a hairstyle: its schema and its validation rules.++WHAT THIS IS AND IS NOT, PRECISELY. This module defines and VALIDATES a `hairProfile`. It does not+compile one into geometry -- there is no profile-to-componentTree compiler yet, and a spec still+authors its hair components directly. Enforcement of the profile's rules today comes from the+validator here plus the `standProud` march the generator emits.++That distinction is stated first because getting it wrong is the specific way this subsystem is+likely to mislead someone: a schema is cheap to write and reads exactly like a working feature.++WHY A PROFILE AND NOT GEOMETRY. Everywhere else in this pipeline the model writes a spec and a+generator writes the geometry. Hair was the one subsystem where the model still placed vertices by+hand, and it showed: four separate attempts to fix one hairstyle by adjusting numbers, four wrong+diagnoses, and the only thing that ever caught them was measurement after the fact. A profile moves+hair onto the same footing as everything else -- the model reverse-engineers PARAMETERS from the+reference and a compiler owns topology. That compiler is not written yet -- see the header.++WHY THE COMPILER RUNS IN PYTHON. The obvious design puts a hair engine in the emitted TypeScript+and lets it generate guide curves at runtime. That would break the one property this project sells:+output a person can read. A hundred procedurally generated curves is not readable. So the profile is+intended to be compiled at spec time into a finite, named, readable set of masses. That step does+not exist yet; today the schema is validated and hair components are still authored directly.++WHY TIER 0 IS A SHELL. Measured on the reference this pipeline is calibrated against -- a 570,400+vertex merged scan -- the surface roughness over the hair is 0.00338 against a torso control of+0.00312, a difference of 8%. Hair on a real reference at this fidelity is a SMOOTH SHELL whose+strand detail lives entirely in the diffuse and normal textures. There are no locks in it to copy.+Since this pipeline emits code and no textures, the strand impression has to come from faceting and+material response, not from lock geometry, and the default representation is therefore a shell with+masses layered on it.++WHAT IS NOT CALIBRATED. Every numeric bound below that could not be traced to a measurement is+listed in UNCALIBRATED_FIELDS and reported as such. No multipart GLB with separated hair geometry is+available, so lock-tier parameters -- taper ratios, cross-section aspect, lock counts -- have no+ground truth. They are derived from anatomy and declared derived. The alternative, quietly inventing+plausible numbers, is precisely how eleven hair locks all ended up with a tip radius of 0.0327.++Pure Python 3.10+ standard library.+"""+from __future__ import annotations++from typing import Any++VALID_REPRESENTATION_TIERS = ("shell", "masses", "locks")+DEFAULT_REPRESENTATION_TIER = "shell"++VALID_HAIR_REGIONS = {+ "crown", "fringe", "temple-left", "temple-right", "side-left", "side-right",+ "rear", "nape", "sideburn-left", "sideburn-right", "tail", "stray",+}++# Primitives a hair mass may be built from, and why the obvious alternatives are not here.+#+# plane-card needs an alpha texture to read as hair. This pipeline emits code and no+# textures, so a card is a visible opaque rectangle. This is the decision left+# open in docs/UPGRADE_PLAN.md since v1.2 ("hair cards vs tube-along-curve per+# lock"), now closed by measurement: the review metrics respond to silhouette and+# banded interior luminance, both of which come from mass, not from card count.+# tube constant radius. A lock that does not taper reads as a noodle; that failure is+# already recorded in taper_risk().+VALID_HAIR_PRIMITIVES = {"tapered-sweep", "curve-sweep", "lathe", "ellipsoid", "instanced-cluster"}+REJECTED_HAIR_PRIMITIVES = {+ "plane-card": (+ "a card needs an alpha texture to read as hair, and this pipeline emits code with no "+ "textures, so it renders as an opaque rectangle"+ ),+ "tube": (+ "a tube has a constant radius, so a lock built from one reads as a noodle; use "+ "'tapered-sweep', which can reach a real point"+ ),+ "box": "a box cannot describe a hair mass; use 'tapered-sweep' or 'lathe'",+}++# Fields whose numeric bounds are DERIVED, not measured, because no reference with separated hair+# geometry exists to calibrate them against. Anything listed here must carry uncalibrated: true.+UNCALIBRATED_FIELDS = (+ "masses[].taper",+ "masses[].crossSection.aspect",+ "flowField.gravity",+ "flowField.whorls[].strength",+)+++def _is_number(value: Any) -> bool:+ return isinstance(value, (int, float)) and not isinstance(value, bool)+++def _unit(value: Any) -> bool:+ return _is_number(value) and 0.0 <= float(value) <= 1.0+++def _validate_hairline(hairline: Any, errors: list[str], warnings: list[str]) -> None:+ """The hairline is five control points across the brow, held in scalp (u, v) coordinates.++ It gets its own object because it drives the silhouette out of proportion to its size and+ because the pipeline already has an unfilled `faceLandmarks.hairline` slot that nothing reads.+ """+ if hairline is None:+ warnings.append(+ "hairProfile.hairline is missing; the hairline sets where the face ends and the hair "+ "begins, and without it the fringe has no anchor"+ )+ return+ if not isinstance(hairline, dict):+ errors.append("hairProfile.hairline must be an object")+ return+ points = hairline.get("controlPoints")+ if not isinstance(points, list) or len(points) < 3:+ errors.append(+ "hairProfile.hairline.controlPoints needs at least 3 points "+ "(temple-left, peak, temple-right at minimum)"+ )+ return+ for index, point in enumerate(points):+ label = f"hairProfile.hairline.controlPoints[{index}]"+ if not isinstance(point, dict):+ errors.append(f"{label} must be an object with u and v")+ continue+ if not _unit(point.get("u")) or not _unit(point.get("v")):+ errors.append(f"{label} must carry u and v in [0,1] on the scalp surface")+++def _validate_flow_field(flow: Any, errors: list[str], warnings: list[str]) -> None:+ """Direction as a FIELD over the scalp rather than a direction per mass.++ This is what makes a wide range of hairstyles reachable without authoring a direction for every+ piece: a style is largely a part line, one or two whorls, how much gravity wins, and a sweep+ direction. Roughly six numbers instead of thirty.+ """+ if flow is None:+ warnings.append(+ "hairProfile.flowField is missing; every mass will then need its own authored "+ "direction, which is what produced fourteen competing directions in a recorded build"+ )+ return+ if not isinstance(flow, dict):+ errors.append("hairProfile.flowField must be an object")+ return++ gravity = flow.get("gravity")+ if gravity is not None and not _unit(gravity):+ errors.append("hairProfile.flowField.gravity must be a number in [0,1]")++ part = flow.get("partLine")+ if part is not None:+ if not isinstance(part, dict):+ errors.append("hairProfile.flowField.partLine must be an object")+ elif not _unit(part.get("u")):+ errors.append("hairProfile.flowField.partLine.u must be in [0,1]")++ whorls = flow.get("whorls")+ if whorls is not None:+ if not isinstance(whorls, list):+ errors.append("hairProfile.flowField.whorls must be an array")+ else:+ for index, whorl in enumerate(whorls):+ label = f"hairProfile.flowField.whorls[{index}]"+ if not isinstance(whorl, dict):+ errors.append(f"{label} must be an object")+ continue+ if not _unit(whorl.get("u")) or not _unit(whorl.get("v")):+ errors.append(f"{label} needs u and v in [0,1]")+ strength = whorl.get("strength")+ if strength is not None and not _unit(strength):+ errors.append(f"{label}.strength must be in [0,1]")+++def _validate_mass(index: int, mass: Any, tier: str, errors: list[str], warnings: list[str]) -> None:+ label = f"hairProfile.masses[{index}]"+ if not isinstance(mass, dict):+ errors.append(f"{label} must be an object")+ return++ if not isinstance(mass.get("id"), str) or not str(mass.get("id")).strip():+ errors.append(f"{label}.id is required")++ region = mass.get("region")+ if region is not None and region not in VALID_HAIR_REGIONS:+ errors.append(+ f"{label}.region {region!r} is not one of: {', '.join(sorted(VALID_HAIR_REGIONS))}"+ )++ primitive = mass.get("primitive")+ if primitive in REJECTED_HAIR_PRIMITIVES:+ errors.append(f"{label} may not use primitive {primitive!r}: {REJECTED_HAIR_PRIMITIVES[primitive]}")+ elif primitive is not None and primitive not in VALID_HAIR_PRIMITIVES:+ errors.append(+ f"{label}.primitive {primitive!r} is not usable for hair; "+ f"choose from: {', '.join(sorted(VALID_HAIR_PRIMITIVES))}"+ )++ # THE ROOT RULE. A root held as an absolute position can drift off the skull the moment the mass+ # is resized -- which is the measured failure this whole subsystem exists to prevent. Held as+ # (u, v) on the scalp it cannot: the surface carries it. This is the same binding Blender uses+ # for hair, where a curve's root is a `surface_uv_coordinate` on the emitter mesh.+ root = mass.get("root")+ if not isinstance(root, dict):+ errors.append(+ f"{label}.root is required and must be {{u, v}} on the scalp surface"+ )+ elif "position" in root or "xyz" in root:+ errors.append(+ f"{label}.root must be scalp (u, v), not an absolute position: an absolute root slides "+ f"off the skull when the mass is resized, which renders as a bald patch"+ )+ elif not _unit(root.get("u")) or not _unit(root.get("v")):+ errors.append(f"{label}.root needs u and v in [0,1] on the scalp surface")++ for field in ("length", "width", "thickness"):+ value = mass.get(field)+ if value is not None and (not _is_number(value) or float(value) <= 0.0):+ errors.append(f"{label}.{field} must be a positive number")++ taper = mass.get("taper")+ if taper is not None:+ if not _unit(taper):+ errors.append(f"{label}.taper must be a tip/root ratio in [0,1]")+ elif not mass.get("uncalibrated"):+ warnings.append(+ f"quality: {label}.taper is set but the mass is not marked uncalibrated; no "+ f"reference with separated hair geometry exists to calibrate a taper ratio against"+ )++ if tier == "locks" and mass.get("primitive") not in (None, "tapered-sweep", "curve-sweep"):+ warnings.append(+ f"quality: {label} is in a 'locks' tier profile but is not a swept primitive; a lock "+ f"has to reach a point and only the sweeps can"+ )+++def validate_hair_profile(profile: Any, errors: list[str], warnings: list[str]) -> None:+ """Validate a `hairProfile` block. Appends to `errors` and `warnings` in place."""+ if profile is None:+ return+ if not isinstance(profile, dict):+ errors.append("hairProfile must be an object")+ return++ tier = profile.get("representationTier", DEFAULT_REPRESENTATION_TIER)+ if tier not in VALID_REPRESENTATION_TIERS:+ errors.append(+ f"hairProfile.representationTier must be one of: {', '.join(VALID_REPRESENTATION_TIERS)}"+ )+ tier = DEFAULT_REPRESENTATION_TIER++ scalp = profile.get("scalpComponentId")+ if not isinstance(scalp, str) or not scalp.strip():+ errors.append(+ "hairProfile.scalpComponentId is required; it names the component whose surface hair "+ "roots bind to and stand proud of"+ )++ _validate_hairline(profile.get("hairline"), errors, warnings)+ _validate_flow_field(profile.get("flowField"), errors, warnings)++ masses = profile.get("masses")+ if masses is None:+ if tier != "shell":+ errors.append(f"hairProfile.masses is required for representationTier {tier!r}")+ elif not isinstance(masses, list):+ errors.append("hairProfile.masses must be an array")+ else:+ seen: set[str] = set()+ for index, mass in enumerate(masses):+ _validate_mass(index, mass, tier, errors, warnings)+ if isinstance(mass, dict) and isinstance(mass.get("id"), str):+ if mass["id"] in seen:+ errors.append(f"hairProfile.masses has a duplicate id {mass['id']!r}")+ seen.add(mass["id"])++ if tier == "locks":+ warnings.append(+ "quality: representationTier 'locks' has no calibration reference. The available "+ "reference GLB is one merged 570,400-vertex scan whose hair is a smooth shell "+ "(surface roughness 0.00338 against a torso control of 0.00312), so it contains no "+ "lock geometry to measure. Lock parameters here are derived, not observed."+ )+++def hair_profile_report(profile: Any) -> dict[str, Any]:+ """A machine-readable summary, including what in it is uncalibrated."""+ errors: list[str] = []+ warnings: list[str] = []+ validate_hair_profile(profile, errors, warnings)+ tier = DEFAULT_REPRESENTATION_TIER+ mass_count = 0+ if isinstance(profile, dict):+ tier = profile.get("representationTier", DEFAULT_REPRESENTATION_TIER)+ masses = profile.get("masses")+ mass_count = len(masses) if isinstance(masses, list) else 0+ return {+ "schemaVersion": 1,+ "kind": "hair-profile-report",+ "representationTier": tier,+ "massCount": mass_count,+ "errors": errors,+ "warnings": warnings,+ "uncalibratedFields": list(UNCALIBRATED_FIELDS),+ "calibrationNote": (+ "Shell-tier envelope values can be measured against the reference scan. Lock-tier "+ "parameters cannot: that reference is one merged mesh whose hair is a smooth textured "+ "shell, so it holds no lock geometry. A multipart GLB with a separated hair mesh is "+ "required before those bounds mean anything."+ ),+ }diff --git a/forge/stage2_spec/validate_sculpt_spec.py b/forge/stage2_spec/validate_sculpt_spec.pyindex 3734814..61376aa 100644--- a/forge/stage2_spec/validate_sculpt_spec.py+++ b/forge/stage2_spec/validate_sculpt_spec.py@@ -12,8 +12,13 @@ from typing import Anysys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage3_build"))+sys.path.insert(0, str(Path(__file__).resolve().parent))+from chirality import CHARACTER_LEFT_SIGN, check_pair, find_pairs # noqa: E402from feature_acceptance_policy import feature_gate_failures, feature_review_policy+from hair_profile import REJECTED_HAIR_PRIMITIVES, validate_hair_profile+from material_physics import check_material_physics, check_open_boundary_sidesfrom sdf_primitives import validate_sdf_descriptor+from vertex_paint import VertexPaintError, normalize_vertex_paintfrom subdivision import (ATTACHMENT_CYLINDER_SUBDIVISION_SOURCE_FACES,MAX_SUBDIVISION_ITERATIONS,@@ -48,10 +53,15 @@ VALID_PRIMITIVES = {"extrude","ground-blade","curve-sweep",+ "tapered-sweep","plane-card","instanced-cluster",}VALID_COMPONENT_LEVELS = {"macro", "meso", "micro"}+# Roles that are expected to declare `standProud`. Hair is the only one so far, and it earned the+# place: it is the one subsystem that carried the requirement as prose while the garment beside it+# carried the same requirement as a measurement.+STAND_PROUD_EXPECTED_ROLES = {"hair"}VALID_COMPLEXITY_TIERS = {"unassessed", "simple", "moderate", "complex", "ultra-complex"}TERMINOLOGY_LIST_FIELDS = {"geometryTerms", "materialTerms", "lightingTerms"}VALID_REVIEW_ACTIONS = {"continue", "refine-spec", "refine-code", "request-input", "stop"}@@ -289,6 +299,213 @@ def _bbox_diagonal(points: list) -> float:return ((max(xs) - min(xs)) ** 2 + (max(ys) - min(ys)) ** 2) ** 0.5+TAPER_RATIO_MAX = 0.55 # tip/root radius above this ⇒ it is not tapering, it is a tube+++def taper_risk(component_id: str, component: dict[str, Any]) -> tuple[str, str]:+ """Warn when a `tapered-sweep`'s stations do not actually taper.++ Measured from a recovered build: eleven hair locks each ended at radius 0.0327 -- identical to+ four decimals across every lock -- for tip/root ratios of 0.58 to 0.79. The machinery was+ correct and the authored stations were not, so the locks came out blunt and read as noodles.+ Nothing caught it, because a sweep that refuses to taper is still a valid sweep. The reference+ those locks were built against measures 0.087.+ """+ descriptor = component.get("geometryDescriptor")+ if not isinstance(descriptor, dict):+ return ("OK", "")+ sweep = descriptor.get("taperedSweep")+ if not isinstance(sweep, dict):+ return ("OK", "")+ stations = sweep.get("stations")+ if not isinstance(stations, list) or len(stations) < 2:+ return ("OK", "")+ radii = [+ max(+ float(station.get("rx", 0.0)) if is_number(station.get("rx")) else 0.0,+ float(station.get("rz", 0.0)) if is_number(station.get("rz")) else 0.0,+ )+ for station in stations+ if isinstance(station, dict)+ ]+ if len(radii) < 2:+ return ("OK", "")+ root, tip = max(radii), min(radii)+ if root <= 0:+ return ("OK", "")+ # Narrowest station over widest, across ALL stations -- not first over last.+ #+ # Two things break an end-to-end reading. First, station order is not free: a sweep's stations+ # run along its path, and reversing them reverses the triangle winding with them, so a limb+ # authored tip-first renders as an open shell seen from the inside. A part may therefore+ # legitimately be authored root-last, and reading station[0] as "the root" reported a real+ # 0.53 taper as 1.89. Second, plenty of real forms are widest in the MIDDLE -- a barrel torso,+ # a spindle, a lemon -- and their two ends are near-identical however hard they taper; the+ # end-to-end reading called a torso that runs 0.055 to 0.213 and back a constant-radius noodle.+ #+ # The question this check is actually asking is whether the radii vary at all, and that has+ # neither a direction nor a preferred pair of stations.+ ratio = tip / root+ if ratio > TAPER_RATIO_MAX:+ return (+ "HIGH",+ f"quality: component {component_id!r} declares primitive 'tapered-sweep' but its "+ f"stations barely taper (narrow/wide={ratio:.2f} > {TAPER_RATIO_MAX}); it will read as "+ f"a constant-radius noodle. Either taper one end toward the fraction the reference "+ f"measures, or use 'tube' and say so.",+ )+ return ("OK", "")+++def validate_chirality(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:+ """Every `-l`/`-r` pair must be a sagittal MIRROR of each other, not a rotated copy.++ WHY THIS IS A HARD GATE. Two chirality defects shipped in one figure and no gate saw either,+ because both produce geometry that is internally tidy and only wrong against a convention that+ lived in a comment.++ The one this catches: a limb pair built by negating x AND z. That is a 180-degree rotation about+ the vertical axis, and a rotation PRESERVES handedness, so both limbs come out the same hand.+ Measured on the humanoid's thumb, whose tip sat at z +0.288 on one side and -0.288 on the other+ where a mirror leaves z alone. Fixing it moved the hand region 46% closer to the reference in+ the front view.++ The one it CANNOT catch, stated here so nobody trusts a green result too far: a pair that is+ wrong the SAME way on both sides is still a perfect mirror of itself. The humanoid's feet were+ exactly that -- both had the big toe on the outer edge -- and this test passes them. That needs+ `chirality.medial_lateral_bias` against a reference, which lives in the stage 4 gate.+ """+ components = spec.get("componentTree")+ if not isinstance(components, list):+ return++ positions: dict[str, list[float]] = {}+ for component in components:+ if not isinstance(component, dict) or not component.get("id"):+ continue+ transform = component.get("transform")+ offset = transform.get("position") if isinstance(transform, dict) else None+ if isinstance(offset, list) and len(offset) == 3 and all(+ isinstance(v, (int, float)) and not isinstance(v, bool) for v in offset+ ):+ positions[str(component["id"])] = [float(v) for v in offset]++ for right_id, left_id in find_pairs(positions):+ ok, message = check_pair(right_id.rsplit("-", 1)[0], positions[right_id], positions[left_id])+ if not ok:+ errors.append(f"chirality: {message}")++ # A component whose id says left but whose position says right. Separate from the pair test+ # because it fires even when only one half of the pair exists.+ #+ # Measured on WORLD x, not on the component's own transform. `transform.position` is relative+ # to the parent, so a nested pair member -- a toe inside a left paw, a claw inside that toe --+ # legitimately carries a negative local x while sitting on the character's left. Reading the+ # local value flagged every inboard toe of a correctly mirrored pair, and the only way to+ # silence it would have been to stop mirroring them, which is the defect this whole function+ # exists to catch. The pair test above deliberately stays on LOCAL coordinates, where a+ # mirrored pair under mirrored parents is exactly a sign flip.+ parents = {+ str(component["id"]): component.get("parent")+ for component in components+ if isinstance(component, dict) and component.get("id")+ }++ def world_x(component_id: str) -> float:+ total = 0.0+ seen: set[str] = set()+ current = component_id+ while isinstance(current, str) and current in positions and current not in seen:+ seen.add(current)+ total += positions[current][0]+ current = parents.get(current)+ return total++ for component_id, _offset in sorted(positions.items()):+ side = component_id.rsplit("-", 1)[-1] if "-" in component_id else ""+ accumulated = world_x(component_id)+ if side not in ("l", "r") or abs(accumulated) < 1e-9:+ continue+ expected = CHARACTER_LEFT_SIGN if side == "l" else -CHARACTER_LEFT_SIGN+ if (accumulated > 0) != (expected > 0):+ warnings.append(+ f"quality: component {component_id!r} is named for the character's "+ f"{'left' if side == 'l' else 'right'} but sits at world x {accumulated:+.4f}. With "+ f"forward +Z and a right-handed frame the character's left is +X, so a pose or "+ f"animation addressed by anatomical joint name would drive the wrong side."+ )+++def validate_stand_proud(+ component_id: str,+ component: dict[str, Any],+ errors: list[str],+ warnings: list[str],+ proud_refs: list[tuple[str, str]],+) -> None:+ """A component may declare that it must stay OUTSIDE another component's surface.++ WHY THIS IS A SCHEMA PROPERTY AND NOT AUTHORING DISCIPLINE. The humanoid demo holds the same+ requirement twice, in two different ways, with two different outcomes. The garment holds it as a+ measurement -- `sectionedLoft`'s `hug` marches every vertex outward along its own spoke until a+ signed distance field reads at least `clearance` -- and it works. The hair holds it as a comment:++ EVERY piece must stand proud of the skull at its own height. Where the skull is proud of the+ hair, the head renders bald there.++ Widening the hair side masses by hand broke that comment and nothing objected. Closure went+ 42.2% to 40.9%, worse on all six views, and dark coverage went DOWN because the widened mass had+ slid off the skull. Measured on the archived captures, crown scalp exposure rose on every view,+ by 14.9 points on the worst one.++ `clearance` is how far outside the target surface the component must sit. `maxPush` caps how far+ a vertex may travel to get there, and is required rather than optional: an uncapped march walks+ inner vertices straight through the target and out the far side, closing the very gap the+ component exists to leave.+ """+ proud = component.get("standProud")+ if proud is None:+ if str(component.get("role") or "").lower() in STAND_PROUD_EXPECTED_ROLES:+ warnings.append(+ f"quality: component {component_id!r} has role 'hair' but declares no standProud; "+ f"nothing will stop it sinking into the head, which renders as a bald patch. "+ f"Declare standProud against the head component, or say why it cannot sink."+ )+ return++ if not isinstance(proud, dict):+ errors.append(f"component {component_id!r} standProud must be an object")+ return++ against = proud.get("againstComponentId")+ if not isinstance(against, str) or not against.strip():+ errors.append(f"component {component_id!r} standProud.againstComponentId is required")+ elif against == component_id:+ errors.append(f"component {component_id!r} standProud references itself")+ else:+ proud_refs.append((component_id, against))++ clearance = proud.get("clearance")+ max_push = proud.get("maxPush")+ if not is_number(clearance) or float(clearance) <= 0.0:+ errors.append(+ f"component {component_id!r} standProud.clearance must be a positive number "+ f"(got {clearance!r}); a clearance of zero permits the surfaces to touch and z-fight"+ )+ return+ if not is_number(max_push) or float(max_push) <= 0.0:+ errors.append(+ f"component {component_id!r} standProud.maxPush must be a positive number "+ f"(got {max_push!r}); an uncapped march walks vertices through the target"+ )+ return+ if float(max_push) < float(clearance):+ errors.append(+ f"component {component_id!r} standProud.maxPush ({max_push}) is below its clearance "+ f"({clearance}); the march would stop before reaching the clearance it asks for"+ )++def flatness_risk(component_id: str, component: dict[str, Any]) -> tuple[str, str]:"""Return ('HIGH'|'OK', message). HIGH when a component the spec declares to be acontinuous 3D form (`continuous-sculpt`, gated at the call site) is built as a THIN@@ -695,6 +912,13 @@ def validate_materials(spec: dict[str, Any], errors: list[str], warnings: list[sif material_id in material_ids:errors.append(f"duplicate material id {material_id!r}")material_ids.add(material_id)+ # What three.js will ACTUALLY do with these numbers -- gated features, clamps, values folded+ # into one uniform, and the base-darkening sheen applies to itself. A value the engine ignores+ # is worse than a missing one: it reads as authored evidence and renders as nothing.+ # Derivation with every file:line: grimoire/build/threejs_skin_and_cloth_materials.md+ physics_errors, physics_warnings = check_material_physics(material_id, material)+ errors.extend(physics_errors)+ warnings.extend(physics_warnings)color = material.get("baseColor", material.get("color"))if color is not None and not (isinstance(color, str) and color.startswith("#") and len(color) in {4, 7}):errors.append(f"material {material_id!r} baseColor/color should be #RGB or #RRGGBB")@@ -775,6 +999,7 @@ def validate_materials(spec: dict[str, Any], errors: list[str], warnings: list[sshader_notes = material.get("shaderNotes")if shader_notes is not None:validate_string_array(shader_notes, f"material {material_id!r} shaderNotes", errors)+ validate_textureless(material_id, material, errors)validate_reference_pbr(material_id, material.get("referencePbr"), errors, warnings)if not material_ids:errors.append("at least one material is required")@@ -1214,6 +1439,7 @@ def validate_components(}ids: set[str] = set()parent_refs: list[tuple[str, str]] = []+ proud_refs: list[tuple[str, str]] = []for index, component in enumerate(components):if not isinstance(component, dict):errors.append(f"componentTree[{index}] must be an object")@@ -1273,6 +1499,9 @@ def validate_components(severity, message = flatness_risk(component_id, component)if severity == "HIGH":warnings.append(message)+ taper_severity, taper_message = taper_risk(component_id, component)+ if taper_severity == "HIGH":+ warnings.append(taper_message)if topology_class == "implicit":descriptor = component.get("geometryDescriptor")if not isinstance(descriptor, dict) or "sdf" not in descriptor:@@ -1296,6 +1525,20 @@ def validate_components(if material and material not in material_ids:errors.append(f"component {component_id!r} references unknown material {material!r}")validate_geometry_descriptor(component_id, component.get("geometryDescriptor"), errors)+ validate_stand_proud(component_id, component, errors, warnings, proud_refs)+ # three's Material.side defaults to FrontSide, which culls backfaces, so a garment opening+ # renders as a HOLE rather than as the inside of the sleeve -- indistinguishable at a glance+ # from a garment that is simply too short, and the two want opposite fixes.+ errors.extend(check_open_boundary_sides(component_id, component))+ # The decision left open in docs/UPGRADE_PLAN.md since v1.2 -- "hair cards vs+ # tube-along-curve per lock" -- closed here by what this pipeline can actually emit.+ if str(component.get("role") or "").lower() == "hair":+ reason = REJECTED_HAIR_PRIMITIVES.get(str(primitive))+ if reason:+ errors.append(+ f"component {component_id!r} has role 'hair' and may not use primitive "+ f"{primitive!r}: {reason}"+ )validate_subdivision_budget(component_id,primitive,@@ -1334,6 +1577,21 @@ def validate_components(value = component.get(field)if value is not None and not isinstance(value, list):errors.append(f"component {component_id!r} {field} must be an array")+ paint = component.get("vertexPaint")+ if paint is not None:+ try:+ normalize_vertex_paint(paint, f"component {component_id!r} vertexPaint")+ except VertexPaintError as error:+ errors.append(str(error))+ # Both write the geometry's `color` attribute, and the second one to run wins. A spec+ # declaring both is asking for two different colours on the same vertex and would get+ # whichever the emission order happens to apply last -- an ordering dependency no gate+ # can see, so it is refused at spec time instead.+ if component.get("rootTipGradient") is not None:+ errors.append(+ f"component {component_id!r} declares both vertexPaint and rootTipGradient; "+ "both write the vertex colour attribute, so only one may be used"+ )surface = component.get("surfaceDetail")if surface is not None:if not isinstance(surface, dict):@@ -1352,6 +1610,13 @@ def validate_components(for component_id, parent in parent_refs:if parent not in ids:errors.append(f"component {component_id!r} references missing parent {parent!r}")+ # Resolved after the loop, like parents: a component may legitimately stand proud of one that+ # appears later in the tree, and a forward reference is not a defect.+ for component_id, against in proud_refs:+ if against not in ids:+ errors.append(+ f"component {component_id!r} standProud references missing component {against!r}"+ )if not ids:errors.append("at least one component is required")if len(ids) == 1:@@ -1994,6 +2259,68 @@ def reference_pbr_usable(material: dict[str, Any], threshold: float) -> tuple[boreturn True, ""+TEXTURE_AUTHORING_FIELDS = (+ "normal",+ "bump",+ "displacement",+ "surfaceFrequencyBands",+ "textureProjection",+ "textureResolution",+ "referencePbr",+)+++def is_textureless(material: dict[str, Any]) -> bool:+ declaration = material.get("textureless")+ return isinstance(declaration, dict) and declaration.get("declared") is True+++def validate_textureless(material_id: str, material: dict[str, Any], errors: list[str]) -> None:+ """A material may declare that its subject carries NO texture detail — with evidence.++ WHY THIS EXISTS. The quality-first material bar below requires independent albedo, roughness,+ height, normal and AO channels at >= 1024, because the subjects it was written for are+ photographic and their identity lives in surface detail. Some subjects genuinely have none:+ a flat-shaded designer-toy render carries no grain, no print and no pores, and its identity is+ entirely silhouette, proportion and the boundaries between flat colour regions.++ Without this declaration the only ways past that bar are to fabricate a texture resolution and+ frequency bands the renderer will never read, or to mislabel a hero material `qualityTier:+ "utility"`. Both put numbers in the spec that describe nothing — which is worse than a missing+ value, because they read as authored evidence.++ So the escape is explicit, evidence-bearing, and closed on both sides: a textureless material+ must say what measurement supports the claim, and must NOT then carry any texture-authoring+ field, since a material cannot both have no texture and specify one.+ """+ declaration = material.get("textureless")+ if declaration is None:+ return+ if not isinstance(declaration, dict):+ errors.append(f"material {material_id!r} textureless must be an object")+ return+ if declaration.get("declared") is not True:+ errors.append(+ f"material {material_id!r} textureless.declared must be true; remove the block instead "+ "of declaring it false"+ )+ return+ evidence = declaration.get("evidence")+ if not isinstance(evidence, list) or not [+ item for item in evidence if isinstance(item, str) and item.strip()+ ]:+ errors.append(+ f"material {material_id!r} textureless.evidence must name at least one measurement or "+ "reference view supporting the claim that the subject carries no texture detail"+ )+ for field in TEXTURE_AUTHORING_FIELDS:+ if material.get(field) is not None:+ errors.append(+ f"material {material_id!r} declares textureless but also carries {field!r}; a "+ "material cannot both have no texture and specify one"+ )++def validate_look_dev_targets(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:targets = spec.get("lookDevTargets")if targets is None:@@ -2079,6 +2406,12 @@ def validate_look_dev_targets(spec: dict[str, Any], errors: list[str], warnings:for material in materials:if material.get("qualityTier") == "utility":continue+ # A material that declares -- with evidence -- that its subject carries no texture+ # detail is not held to the texture-channel bar. See validate_textureless: the+ # declaration is hard-validated, so this skip cannot be taken without the evidence+ # and cannot coexist with any texture-authoring field.+ if is_textureless(material):+ continuematerial_id = str(material.get("id") or "(unnamed)")resolution = material.get("textureResolution")if not isinstance(resolution, int) or isinstance(resolution, bool) or resolution < minimum_resolution:@@ -2458,6 +2791,8 @@ def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:validate_action_readiness(spec, errors, warnings)validate_self_correct_loop(spec, errors, warnings)validate_feature_review_targets(spec, errors, warnings)+ validate_chirality(spec, errors, warnings)+ validate_hair_profile(spec.get("hairProfile"), errors, warnings)validate_review_history(spec, errors, warnings)validate_visual_evidence_history(spec, errors)build_pass_ids = validate_build_passes(spec, errors, warnings)diff --git a/forge/stage3_build/generate_threejs_factory.py b/forge/stage3_build/generate_threejs_factory.pyindex 2bbd6fb..40431dd 100644--- a/forge/stage3_build/generate_threejs_factory.py+++ b/forge/stage3_build/generate_threejs_factory.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport argparseimport json+import mathimport reimport sysfrom pathlib import Path@@ -35,26 +36,15 @@ from subdivision import (TORUS_RADIAL_SEGMENTS,TORUS_TUBULAR_SEGMENTS,)-from validate_sculpt_spec import validate_spec+from validate_sculpt_spec import ATTACHMENT_PRIMITIVES, VALID_PRIMITIVES, validate_spec+from vertex_paint import VertexPaintError, normalize_vertex_paintfrom visual_hull import MAX_VISUAL_HULL_TRIANGLES--VALID_PRIMITIVES = {- "box",- "sphere",- "ellipsoid",- "cylinder",- "cone",- "capsule",- "torus",- "tube",- "lathe",- "extrude",- "ground-blade",- "curve-sweep",- "plane-card",- "instanced-cluster",-}+# VALID_PRIMITIVES is re-exported rather than redefined. This module used to keep its own copy,+# and the two stayed identical only because someone edited both every time. A primitive present+# in one list and absent from the other does not error: line ~2873 silently rewrites it to "box",+# so the spec validates, the factory builds, and the wrong shape ships. Importing the validator's+# set makes that class of drift impossible instead of merely unlikely.DEFAULT_PASS_ORDER = ["blockout","structural-pass",@@ -279,6 +269,34 @@ def vector(values: Any, fallback: list[float]) -> str:return ", ".join(str(item) for item in fallback)+def scale_triple(component: dict[str, Any], transform: dict[str, Any]) -> tuple[float, float, float]:+ """The numeric factors `scale_vector` renders, for callers that must do arithmetic with them.++ This exists because `geometry.scale(...)` bakes the factors into the VERTEX DATA and leaves the+ pivot at scale 1. Anything that describes a component's surface analytically -- a ring stack to+ stand proud of, say -- therefore has to apply the same factors itself, because no matrix in the+ scene graph carries them. Reading the surface from the unit form instead put the skull's radius+ at 0.5 where the geometry actually sits at 0.2.+ """+ if "scale" in transform:+ values = transform.get("scale")+ if isinstance(values, list) and len(values) == 3 and all(+ isinstance(item, (int, float)) for item in values+ ):+ return (float(values[0]), float(values[1]), float(values[2]))+ return (1.0, 1.0, 1.0)+ dimensions = component.get("dimensions")+ if isinstance(dimensions, dict):+ radius = dimensions.get("radius")+ fallback = radius * 2 if isinstance(radius, (int, float)) else 1+ width = dimensions.get("width", fallback)+ height = dimensions.get("height", dimensions.get("length", 1))+ depth = dimensions.get("depth", fallback)+ if all(isinstance(item, (int, float)) for item in (width, height, depth)):+ return (float(width), float(height), float(depth))+ return (1.0, 1.0, 1.0)++def scale_vector(component: dict[str, Any], transform: dict[str, Any]) -> str:if "scale" in transform:return vector(transform.get("scale"), [1, 1, 1])@@ -323,6 +341,24 @@ _DEFAULT_CURVE_SWEEP = {"closed": False,}+# A sweep whose cross-section CHANGES along the spine. Every other sweep this factory emits --+# tube, curve-sweep, extrude -- carries one constant section from root to tip, so nothing that+# comes to a point (a hair lock, a horn, a tail, a blade tip, a finger) can be expressed by them.+# The default tapers to 8% of its root, which is the profile the grimoire prescribes; the+# validator warns when a spec's stations do not actually taper, because a barely-tapering sweep+# is a `tube` written the long way and reads as a noodle.+_DEFAULT_TAPERED_SWEEP = {+ "stations": [+ {"position": [0.0, -0.5, 0.0], "rx": 0.060, "rz": 0.040, "twist": 0.0},+ {"position": [0.0, -0.1, 0.0], "rx": 0.048, "rz": 0.030, "twist": 0.0},+ {"position": [0.0, 0.25, 0.0], "rx": 0.024, "rz": 0.014, "twist": 0.0},+ # A true point, not a small ring: the tip is where a lock, a horn or a blade has to close.+ {"position": [0.0, 0.5, 0.0], "rx": 0.0, "rz": 0.0, "twist": 0.0},+ ],+ "radialSegments": 10,+ "capEnds": True,+}+_VISUAL_HULL_HELPER_SOURCE = """type VisualHullVector = readonly [number, number, number];type VisualHullAxis = 'front' | 'side' | 'top';@@ -818,6 +854,21 @@ function sdfSample(descriptor: SdfDescriptor): SdfFunction {}function polygonizeSdf(descriptor: SdfDescriptor): THREE.BufferGeometry {+ // SURFACE NETS, not a voxel shell.+ //+ // This used to emit one axis-aligned quad per exposed voxel face, which is a Minecraft surface:+ // every face is axis-aligned, every edge is a 90-degree step, and the result is stair-stepped at+ // exactly the scale of the sampling grid. For a subject whose whole identity is smooth blended+ // organic form -- which is the only kind of subject anyone reaches for an implicit surface to+ // build -- that is worse than the assembled primitives it was meant to replace.+ //+ // Naive surface nets places ONE vertex per sign-changing cell, at the average of the linearly+ // interpolated crossings on that cell's edges, and joins the four cells around each crossing+ // edge into a quad. It is compact, manifold, and smooth, and it is a natural fit for a field+ // that can be sampled anywhere rather than only at corners.+ //+ // Normals come from the field GRADIENT, not from face averaging: the gradient is the exact+ // surface normal of the implicit surface, so shading no longer carries the grid's imprint.const resolution = Math.max(4, Math.min(64, Math.floor(descriptor.resolution)));const defaultBounds: { readonly min: SdfVector; readonly max: SdfVector } = { min: [-2, -2, -2], max: [2, 2, 2] };const bounds = descriptor.bounds ?? defaultBounds;@@ -827,55 +878,137 @@ function polygonizeSdf(descriptor: SdfDescriptor): THREE.BufferGeometry {(bounds.max[1] - bounds.min[1]) / resolution,(bounds.max[2] - bounds.min[2]) / resolution,);- const field = new Float32Array(resolution * resolution * resolution);const sample = sdfSample(descriptor);- const indexAt = (x: number, y: number, z: number): number => (z * resolution + y) * resolution + x;- for (let z = 0; z < resolution; z += 1) {- for (let y = 0; y < resolution; y += 1) {- for (let x = 0; x < resolution; x += 1) {- field[indexAt(x, y, z)] = sample(new THREE.Vector3(- min.x + (x + 0.5) * step.x,- min.y + (y + 0.5) * step.y,- min.z + (z + 0.5) * step.z,- ));+ const scratch = new THREE.Vector3();++ // Corner grid: one more corner than cells on each axis.+ const side = resolution + 1;+ const field = new Float32Array(side * side * side);+ const cornerAt = (x: number, y: number, z: number): number => (z * side + y) * side + x;+ for (let z = 0; z < side; z += 1) {+ for (let y = 0; y < side; y += 1) {+ for (let x = 0; x < side; x += 1) {+ scratch.set(min.x + x * step.x, min.y + y * step.y, min.z + z * step.z);+ field[cornerAt(x, y, z)] = sample(scratch);}}}++ // The 12 cell edges as corner-offset pairs.+ const CUBE_EDGES: readonly (readonly [number, number, number, number, number, number])[] = [+ [0, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0],+ [0, 0, 1, 1, 0, 1], [1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 0, 1, 1],+ [0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 0, 1], [1, 1, 0, 1, 1, 1], [0, 1, 0, 0, 1, 1],+ ];+const positions: number[] = [];+ const normals: number[] = [];const indices: number[] = [];- const vertices = new Map<string, number>();- const vertexAt = (x: number, y: number, z: number): number => {- const key = `${x},${y},${z}`;- const existing = vertices.get(key);- if (existing !== undefined) return existing;- const vertex = positions.length / 3;- positions.push(min.x + x * step.x, min.y + y * step.y, min.z + z * step.z);- vertices.set(key, vertex);- return vertex;- };- const addFace = (a: number, b: number, c: number, d: number): void => {- indices.push(a, b, c, a, c, d);+ const cellVertex = new Int32Array(resolution * resolution * resolution).fill(-1);+ const cellAt = (x: number, y: number, z: number): number => (z * resolution + y) * resolution + x;++ // Central-difference gradient, stepped at a fraction of a cell so it follows the field rather+ // than the grid.+ const epsilon = Math.min(step.x, step.y, step.z) * 0.25;+ const gradient = (point: THREE.Vector3): THREE.Vector3 => {+ const gx = sample(scratch.set(point.x + epsilon, point.y, point.z))+ - sample(scratch.set(point.x - epsilon, point.y, point.z));+ const gy = sample(scratch.set(point.x, point.y + epsilon, point.z))+ - sample(scratch.set(point.x, point.y - epsilon, point.z));+ const gz = sample(scratch.set(point.x, point.y, point.z + epsilon))+ - sample(scratch.set(point.x, point.y, point.z - epsilon));+ const normal = new THREE.Vector3(gx, gy, gz);+ // A point where the field is flat has no defined normal; +Y is arbitrary but finite, and+ // leaving a zero vector would poison every lighting calculation downstream.+ return normal.lengthSq() < 1e-20 ? new THREE.Vector3(0, 1, 0) : normal.normalize();};- const inside = (x: number, y: number, z: number): boolean => (- x >= 0 && y >= 0 && z >= 0 && x < resolution && y < resolution && z < resolution && field[indexAt(x, y, z)] <= 0- );+for (let z = 0; z < resolution; z += 1) {for (let y = 0; y < resolution; y += 1) {for (let x = 0; x < resolution; x += 1) {- if (!inside(x, y, z)) continue;- if (!inside(x - 1, y, z)) addFace(vertexAt(x, y, z), vertexAt(x, y, z + 1), vertexAt(x, y + 1, z + 1), vertexAt(x, y + 1, z));- if (!inside(x + 1, y, z)) addFace(vertexAt(x + 1, y, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y, z + 1));- if (!inside(x, y - 1, z)) addFace(vertexAt(x, y, z), vertexAt(x + 1, y, z), vertexAt(x + 1, y, z + 1), vertexAt(x, y, z + 1));- if (!inside(x, y + 1, z)) addFace(vertexAt(x, y + 1, z), vertexAt(x, y + 1, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x + 1, y + 1, z));- if (!inside(x, y, z - 1)) addFace(vertexAt(x, y, z), vertexAt(x, y + 1, z), vertexAt(x + 1, y + 1, z), vertexAt(x + 1, y, z));- if (!inside(x, y, z + 1)) addFace(vertexAt(x, y, z + 1), vertexAt(x + 1, y, z + 1), vertexAt(x + 1, y + 1, z + 1), vertexAt(x, y + 1, z + 1));+ let crossings = 0;+ let sumX = 0;+ let sumY = 0;+ let sumZ = 0;+ for (const [ax, ay, az, bx, by, bz] of CUBE_EDGES) {+ const a = field[cornerAt(x + ax, y + ay, z + az)];+ const b = field[cornerAt(x + bx, y + by, z + bz)];+ if ((a <= 0) === (b <= 0)) continue;+ const t = a / (a - b);+ sumX += (ax + (bx - ax) * t);+ sumY += (ay + (by - ay) * t);+ sumZ += (az + (bz - az) * t);+ crossings += 1;+ }+ if (crossings === 0) continue;+ const px = min.x + (x + sumX / crossings) * step.x;+ const py = min.y + (y + sumY / crossings) * step.y;+ const pz = min.z + (z + sumZ / crossings) * step.z;+ cellVertex[cellAt(x, y, z)] = positions.length / 3;+ positions.push(px, py, pz);+ const normal = gradient(new THREE.Vector3(px, py, pz));+ normals.push(normal.x, normal.y, normal.z);+ }+ }+ }++ // One quad per sign-changing grid edge, joining the four cells that share it.+ //+ // Winding, worked out rather than guessed. For the +x edge from corner (x,y,z), the four cells+ // around it are (x, y-1, z-1), (x, y, z-1), (x, y, z), (x, y-1, z); in the (y,z) plane that+ // traversal is +y, +z, -y, whose cross product is +x. So when the corner is INSIDE and its+ // neighbour is outside, the unflipped order already faces out, and the flip belongs on the+ // opposite case. Getting this backwards is invisible in the normals -- those come from the+ // gradient and stay correct -- and shows only as back-face culling removing the front surface,+ // i.e. the model rendering as a hollow shell with its interior visible.+ const quad = (a: number, b: number, c: number, d: number, flip: boolean): void => {+ if (a < 0 || b < 0 || c < 0 || d < 0) return;+ if (flip) indices.push(a, c, b, a, d, c);+ else indices.push(a, b, c, a, c, d);+ };+ // Each quad joins the FOUR cells sharing one grid edge, so every one of those cells must exist.+ // Bounding only the edge axis and the lower end of the other two let y/z reach `resolution`, which+ // is a corner index, not a cell index: `cellAt` then strides into an unrelated slot (with+ // resolution 8, `cellAt(3, 8, 1)` is 131 -- the slot for cell (3, 0, 2)) or past the end of the+ // array, where a typed-array read yields `undefined`. `undefined < 0` is false, so the guard in+ // `quad` passed it through to `setIndex`, which coerces it to 0. Measured on a sphere reaching its+ // own bounds at resolution 8: 60 out-of-range reads and 108 aliased reads. A surface that touches+ // the sampling box is therefore left OPEN at that face rather than closed with wrong triangles --+ // pad `bounds` past the surface to get a closed mesh.+ for (let z = 0; z < side; z += 1) {+ for (let y = 0; y < side; y += 1) {+ for (let x = 0; x < side; x += 1) {+ const here = field[cornerAt(x, y, z)] <= 0;+ if (x + 1 < side && y > 0 && z > 0 && y < side - 1 && z < side - 1+ && here !== (field[cornerAt(x + 1, y, z)] <= 0)) {+ quad(+ cellVertex[cellAt(x, y - 1, z - 1)], cellVertex[cellAt(x, y, z - 1)],+ cellVertex[cellAt(x, y, z)], cellVertex[cellAt(x, y - 1, z)], !here,+ );+ }+ if (y + 1 < side && x > 0 && z > 0 && x < side - 1 && z < side - 1+ && here !== (field[cornerAt(x, y + 1, z)] <= 0)) {+ quad(+ cellVertex[cellAt(x - 1, y, z - 1)], cellVertex[cellAt(x - 1, y, z)],+ cellVertex[cellAt(x, y, z)], cellVertex[cellAt(x, y, z - 1)], !here,+ );+ }+ if (z + 1 < side && x > 0 && y > 0 && x < side - 1 && y < side - 1+ && here !== (field[cornerAt(x, y, z + 1)] <= 0)) {+ quad(+ cellVertex[cellAt(x - 1, y - 1, z)], cellVertex[cellAt(x, y - 1, z)],+ cellVertex[cellAt(x, y, z)], cellVertex[cellAt(x - 1, y, z)], !here,+ );+ }}}}+const geometry = new THREE.BufferGeometry();geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));+ geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));geometry.setIndex(indices);- geometry.computeVertexNormals();+ geometry.computeBoundingSphere();return geometry;}"""@@ -1284,6 +1417,381 @@ def capped_sdf(sdf: dict[str, Any], segments: dict[str, int]) -> dict[str, Any]:return {**sdf, "resolution": ceiling}+_STAND_PROUD_HELPER_SOURCE = '''\+type ProudRingStack = { rings: [number, number, number, number][] };++// Signed distance to a stack of ellipse rings. Negative inside, positive outside.+//+// The sign is exact; the magnitude is the first-order estimate f / |grad f|, which UNDERSTATES how+// clear an outside point is and OVERSTATES how deep an inside point is. Both errors make the march+// below push slightly further than strictly necessary, which is the safe direction: the failure+// being prevented is a component sinking into the one beneath it and rendering as a bare patch.+function ringStackDistance(stack: ProudRingStack, x: number, y: number, z: number): number {+ const rings = stack.rings;+ const yMin = rings[0][0];+ const yMax = rings[rings.length - 1][0];+ let rx = rings[0][1];+ let rz = rings[0][2];+ let zc = rings[0][3];+ if (y >= yMax) {+ const last = rings[rings.length - 1];+ rx = last[1]; rz = last[2]; zc = last[3];+ } else if (y > yMin) {+ for (let i = 0; i + 1 < rings.length; i += 1) {+ const lo = rings[i];+ const hi = rings[i + 1];+ if (y >= lo[0] && y <= hi[0]) {+ const span = hi[0] - lo[0];+ const t = span > 1e-9 ? (y - lo[0]) / span : 0;+ rx = lo[1] + (hi[1] - lo[1]) * t;+ rz = lo[2] + (hi[2] - lo[2]) * t;+ zc = lo[3] + (hi[3] - lo[3]) * t;+ break;+ }+ }+ }+ const dx = x / rx;+ const dz = (z - zc) / rz;+ const f = dx * dx + dz * dz - 1;+ const gx = (2 * x) / (rx * rx);+ const gz = (2 * (z - zc)) / (rz * rz);+ const grad = Math.hypot(gx, gz);+ const radial = grad < 1e-12 ? -Math.min(rx, rz) : f / grad;+ const axial = Math.max(yMin - y, y - yMax);+ return Math.hypot(Math.max(radial, 0), Math.max(axial, 0)) + Math.min(Math.max(radial, axial), 0);+}++// Push every vertex outward until it stands `clearance` clear of the target's surface.+//+// WHY THE AUTHORED NUMBERS ARE ONLY A LOWER BOUND. A ring is an ELLIPSE, and the surface it has to+// clear generally is not. Any single ellipse that clears the widest point is loose at the narrowest+// and vice versa, so hand-widening moves the error rather than shrinking it -- measured on hair,+// where widening the side masses took closure from 42.2% to 40.9%, worse on all six views, with+// dark coverage DOWN because the widened mass had slid off the skull. Here the authored width is a+// floor and the real radius is MEASURED per vertex.+//+// Each vertex travels along its OWN radial spoke rather than along the field's gradient, so the+// ring keeps its vertex order and its seam positions and only its radius changes. `maxPush` is+// required, not a safeguard: an uncapped march walks inner vertices straight through the target and+// out the far side, closing the very gap the component exists to leave.+function applyStandProud(+ geometry: THREE.BufferGeometry,+ marcher: THREE.Object3D,+ target: THREE.Object3D,+ stack: ProudRingStack,+ clearance: number,+ maxPush: number,+): void {+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;+ marcher.updateWorldMatrix(true, false);+ target.updateWorldMatrix(true, false);+ const toTarget = new THREE.Matrix4().copy(target.matrixWorld).invert().multiply(marcher.matrixWorld);+ const fromTarget = new THREE.Matrix4().copy(toTarget).invert();+ const p = new THREE.Vector3();+ // A vertex can exhaust `maxPush` and still be inside the target. That is the cap doing its job --+ // an uncapped march walks vertices out the far side -- but it means the clearance this function+ // promises was NOT achieved, and saying nothing there hides exactly the defect the caller asked+ // to be protected from. Measured on the shipped fixture: 2 of 8 sampled hair vertices sat 0.059+ // inside a skull against a 0.04 cap and could never have reached clear.+ let unresolved = 0;++ for (let i = 0; i < position.count; i += 1) {+ p.fromBufferAttribute(position, i).applyMatrix4(toTarget);+ // The spoke is the vertex's own radial direction in the target's frame; marching along it keeps+ // each ring a ring, since every vertex holds its own angle and only its radius changes.+ //+ // A vertex on the axis has no radial direction at all -- and that is precisely the crown, the+ // one place a bald patch is most visible. Skipping it leaves the exact failure this function+ // exists to prevent. So a degenerate spoke marches axially instead, out through whichever cap+ // it is nearer, which is the direction the field itself measures there.+ const spokeLength = Math.hypot(p.x, p.z);+ const onAxis = spokeLength < 1e-9;+ const midHeight = (stack.rings[0][0] + stack.rings[stack.rings.length - 1][0]) / 2;+ const sx = onAxis ? 0 : p.x / spokeLength;+ const sz = onAxis ? 0 : p.z / spokeLength;+ const sy = onAxis ? (p.y >= midHeight ? 1 : -1) : 0;++ let travelled = 0;+ for (let step = 0; step < 24; step += 1) {+ const gap = ringStackDistance(stack, p.x, p.y, p.z);+ if (gap >= clearance) break;+ const move = Math.min(Math.max(0.002, clearance - gap), maxPush - travelled);+ if (move <= 0) break;+ p.x += sx * move;+ p.y += sy * move;+ p.z += sz * move;+ travelled += move;+ }++ if (ringStackDistance(stack, p.x, p.y, p.z) < clearance) unresolved += 1;++ p.applyMatrix4(fromTarget);+ position.setXYZ(i, p.x, p.y, p.z);+ }++ position.needsUpdate = true;+ geometry.computeVertexNormals();++ geometry.userData.standProud = { clearance, maxPush, unresolved, total: position.count };+ if (unresolved > 0) {+ console.warn(+ `standProud: ${unresolved}/${position.count} vertices could not reach ${clearance} within ` ++ `maxPush ${maxPush}. They are still inside the target and will render as bare patches. ` ++ `Raise maxPush, or move the component out so it does not start that deep.`,+ );+ }+}+'''+++_ROOT_TIP_GRADIENT_HELPER_SOURCE = '''\+// Darken a mass toward its root.+//+// WHY THIS IS SHADING AND NOT GEOMETRY. Measured on the reference this pipeline is calibrated+// against -- a 570,400 vertex merged scan -- the surface roughness over the hair is 0.00338 against+// a torso control of 0.00312. Its hair is a SMOOTH SHELL and every strand it appears to have lives+// in the diffuse and normal textures. This pipeline emits code and no textures, so the same+// impression has to be carried by vertex colour, faceting and sheen. Adding lock geometry does not+// substitute for it: four attempts to close the gap geometrically all failed, and the last one made+// every view worse.+//+// The gradient runs along the mass's own local axis rather than world Y, so a fringe sweeping+// sideways darkens at its root and not at whatever happens to be lowest.+function applyRootTipGradient(+ geometry: THREE.BufferGeometry,+ rootColor: THREE.ColorRepresentation,+ tipColor: THREE.ColorRepresentation,+ axis: 'x' | 'y' | 'z',+): void {+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;+ const root = new THREE.Color(rootColor);+ const tip = new THREE.Color(tipColor);+ const values = new Float32Array(position.count * 3);++ let low = Infinity;+ let high = -Infinity;+ for (let i = 0; i < position.count; i += 1) {+ const v = axis === 'x' ? position.getX(i) : axis === 'z' ? position.getZ(i) : position.getY(i);+ if (v < low) low = v;+ if (v > high) high = v;+ }+ // A mass with no extent along its own axis has no root and no tip; a flat colour is the honest+ // answer, and dividing by the span would produce NaN on every vertex.+ const span = high - low;++ const mixed = new THREE.Color();+ for (let i = 0; i < position.count; i += 1) {+ const v = axis === 'x' ? position.getX(i) : axis === 'z' ? position.getZ(i) : position.getY(i);+ const t = span > 1e-9 ? (v - low) / span : 1;+ mixed.copy(root).lerp(tip, t);+ values[i * 3] = mixed.r;+ values[i * 3 + 1] = mixed.g;+ values[i * 3 + 2] = mixed.b;+ }+ geometry.setAttribute('color', new THREE.BufferAttribute(values, 3));+}+'''+++_VERTEX_PAINT_HELPER_SOURCE = '''\+// Paint declared colour regions into the vertex-colour attribute.+//+// WHY VERTEX COLOUR AND NOT A TEXTURE. A subject whose identity is a set of flat colour regions+// with hard boundaries -- a blaze, a bib, a sock, a livery stripe -- needs those boundaries placed+// to a measured position. This pipeline emits code and no image assets, so a texture is not+// available to place them with; a single root-to-tip ramp cannot express a shaped region. Per-+// vertex colour driven by a declared shape is the remaining honest representation, and it is the+// one the boundary gate can measure BEFORE a browser is involved.+//+// The maths here is a transcription of forge/_shared/vertex_paint.py, and+// forge/tests/test_vertex_paint.py holds the two to the same numbers on a fixture. Editing one+// side without the other turns a gated boundary into an ungated one, which is exactly the failure+// the shared implementation exists to prevent.+//+// Regions are evaluated in the component's own local space AFTER its real dimensions have been+// applied to the vertex data, so every coordinate below is in the same units as the component's+// measured dimensions rather than in a unit cube.+type VertexPaintRegion = {+ id: string;+ kind: 'axis-band' | 'ellipsoid' | 'tapered-capsule';+ color: string;+ softness: number;+ axis?: 'x' | 'y' | 'z';+ min?: number;+ max?: number;+ center?: [number, number, number];+ radii?: [number, number, number];+ start?: [number, number, number];+ end?: [number, number, number];+ startRadius?: number;+ endRadius?: number;+};++function vertexPaintSmoothstep(edge0: number, edge1: number, value: number): number {+ if (edge1 <= edge0) return value < edge1 ? 0 : 1;+ let t = (value - edge0) / (edge1 - edge0);+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ return t * t * (3 - 2 * t);+}++function vertexPaintSignedDistance(+ region: VertexPaintRegion,+ x: number,+ y: number,+ z: number,+): number {+ if (region.kind === 'axis-band') {+ const value = region.axis === 'x' ? x : region.axis === 'z' ? z : y;+ const low = region.min as number;+ const high = region.max as number;+ if (value < low) return low - value;+ if (value > high) return value - high;+ return -Math.min(value - low, high - value);+ }+ if (region.kind === 'ellipsoid') {+ const [cx, cy, cz] = region.center as [number, number, number];+ const [rx, ry, rz] = region.radii as [number, number, number];+ const q = Math.sqrt(+ ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 + ((z - cz) / rz) ** 2,+ );+ return (q - 1) * Math.min(rx, ry, rz);+ }+ const [ax, ay, az] = region.start as [number, number, number];+ const [bx, by, bz] = region.end as [number, number, number];+ const abx = bx - ax;+ const aby = by - ay;+ const abz = bz - az;+ const denominator = abx * abx + aby * aby + abz * abz;+ let t = denominator > 0+ ? ((x - ax) * abx + (y - ay) * aby + (z - az) * abz) / denominator+ : 0;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ const distance = Math.sqrt(+ (x - (ax + abx * t)) ** 2 + (y - (ay + aby * t)) ** 2 + (z - (az + abz * t)) ** 2,+ );+ const startRadius = region.startRadius as number;+ const endRadius = region.endRadius as number;+ return distance - (startRadius + (endRadius - startRadius) * t);+}++function vertexPaintWeight(region: VertexPaintRegion, x: number, y: number, z: number): number {+ const distance = vertexPaintSignedDistance(region, x, y, z);+ if (region.softness <= 0) return distance <= 0 ? 1 : 0;+ return 1 - vertexPaintSmoothstep(-region.softness * 0.5, region.softness * 0.5, distance);+}++function applyVertexPaint(+ geometry: THREE.BufferGeometry,+ baseColor: string,+ regions: VertexPaintRegion[],+): void {+ const position = geometry.getAttribute('position') as THREE.BufferAttribute;+ const values = new Float32Array(position.count * 3);+ const base = new THREE.Color(baseColor);+ const target = new THREE.Color();+ const mixed = new THREE.Color();+ const regionColors = regions.map((region) => new THREE.Color(region.color));++ for (let i = 0; i < position.count; i += 1) {+ const x = position.getX(i);+ const y = position.getY(i);+ const z = position.getZ(i);+ mixed.copy(base);+ for (let r = 0; r < regions.length; r += 1) {+ const weight = vertexPaintWeight(regions[r], x, y, z);+ if (weight <= 0) continue;+ target.copy(regionColors[r]);+ mixed.lerp(target, weight);+ }+ values[i * 3] = mixed.r;+ values[i * 3 + 1] = mixed.g;+ values[i * 3 + 2] = mixed.b;+ }+ geometry.setAttribute('color', new THREE.BufferAttribute(values, 3));+}+'''+++def vertex_paint(component: dict[str, Any]) -> dict[str, Any] | None:+ """A component's declared colour-region paint, or None.++ Raises rather than degrading to flat colour when the declaration is malformed. A boundary that+ silently vanishes is the failure mode this whole subsystem exists to remove: the render still+ looks like a cat, the gate still finds a mesh, and the identity feature is simply not there.+ """+ paint = component.get("vertexPaint")+ if paint is None:+ return None+ try:+ return normalize_vertex_paint(paint, f"component {component.get('id')!r} vertexPaint")+ except VertexPaintError as error:+ raise ValueError(str(error)) from error+++def root_tip_gradient(component: dict[str, Any]) -> dict[str, Any] | None:+ """A component's root-to-tip colour ramp, or None.++ Rejected rather than defaulted when malformed: a gradient silently falling back to flat colour+ is the kind of quiet no-op that made hair hard to diagnose in the first place.+ """+ gradient = component.get("rootTipGradient")+ if not isinstance(gradient, dict):+ return None+ root = gradient.get("rootColor")+ tip = gradient.get("tipColor")+ if not isinstance(root, str) or not isinstance(tip, str):+ return None+ axis = gradient.get("axis", "y")+ if axis not in ("x", "y", "z"):+ axis = "y"+ return {"rootColor": root, "tipColor": tip, "axis": axis}+++def stand_proud_ring_stack(component: dict[str, Any]) -> list[list[float]] | None:+ """The ring stack a component presents as a surface to stand proud of, in its own local space.++ Two sources, because two shapes actually occur. A component authored as a ring stack carries one+ directly. Everything else that is a closed convex blob -- an ellipsoid or a sphere, which is what+ a generated head is -- gets one synthesised from its unit geometry, since `geometry_for` authors+ those at radius 0.5 and the real dimensions arrive later via `geometry.scale`. Returning None+ means the target has no surface this march can describe, and the caller must say so rather than+ silently skip the clearance.+ """+ descriptor = component.get("geometryDescriptor")+ if isinstance(descriptor, dict):+ stack = descriptor.get("ringStack")+ if isinstance(stack, dict) and isinstance(stack.get("rings"), list) and stack["rings"]:+ offsets = stack.get("zOffsets")+ rings: list[list[float]] = []+ for index, ring in enumerate(stack["rings"]):+ values = [float(v) for v in list(ring)[:4]]+ if len(values) < 3:+ return None+ if len(values) == 3:+ offset = 0.0+ if isinstance(offsets, list) and index < len(offsets):+ offset = float(offsets[index])+ values.append(offset)+ rings.append(values)+ rings.sort(key=lambda r: r[0])+ return rings++ if component.get("primitive") in {"ellipsoid", "sphere", "capsule"}:+ # A unit sphere of radius 0.5, sliced into rings. The march runs in the TARGET's local+ # space, and `geometry.scale` has already been applied to the target's own vertices, so the+ # stack has to describe the unit form and let the caller's matrix carry the scale.+ slices = 12+ rings = []+ for index in range(slices + 1):+ t = index / slices+ y = -0.5 + t+ radius = math.sqrt(max(0.0, 0.25 - y * y))+ rings.append([round(y, 6), round(max(radius, 1e-4), 6), round(max(radius, 1e-4), 6), 0.0])+ return rings++ return None++def geometry_for(primitive: str,component: dict[str, Any] | None = None,@@ -1336,6 +1844,13 @@ def geometry_for(if primitive == "curve-sweep":sweep = descriptor.get("curveSweep") if isinstance(descriptor.get("curveSweep"), dict) else _DEFAULT_CURVE_SWEEPreturn f"buildCurveSweepGeometry({json_literal(sweep)})"+ if primitive == "tapered-sweep":+ tapered = (+ descriptor.get("taperedSweep")+ if isinstance(descriptor.get("taperedSweep"), dict)+ else _DEFAULT_TAPERED_SWEEP+ )+ return f"buildTaperedSweepGeometry({json_literal(tapered)})"if primitive == "instanced-cluster":# An instanced cluster's *geometry* is its base shape; the instancing itself is applied# by the repetition-system emitter (THREE.InstancedMesh). Resolve the base primitive from@@ -1415,12 +1930,15 @@ def rig_is_bone_track(spec: dict[str, Any]) -> bool:def emit_rig_hierarchy(spec: dict[str, Any]) -> list[str]:- """Emit the bone hierarchy from `spec["rig"]` — PLAN_1.5 WS-C, first slice.+ """Emit the bone hierarchy from `spec["rig"]` — PLAN_1.5 WS-C.- Bones ONLY: no `SkinnedMesh`, no `bind()`. Keeping those in a later slice is deliberate,- because it means this change cannot alter any existing demo's rendered output — on the- pivot track it emits nothing, and on the bone track it only ADDS a hierarchy that nothing- is yet bound to. `root.userData.rig.bound` is `false` to say so out loud.+ Emits the bones, one shared `THREE.Skeleton`, exactly one vertex-weight helper, and binds every+ skinned component as a `THREE.SkinnedMesh`. `root.userData.rig.bound` is COMPUTED — it is true+ only when every skinned mesh actually bound — rather than asserted, so a partial bind reports+ itself instead of reading as success.++ On the pivot track this emits nothing at all, so an object spec's output is byte-identical to+ what it was before the rig track existed.Two things that are easy to get wrong here:@@ -1577,12 +2095,10 @@ def _rig_weight_function_lines(spec: dict[str, Any], ordered: list[dict[str, Any- **The envelope radius is computed in Python**, by `derive_envelope_radius` (PLAN_1.5 §4.3),and emitted as a literal. Doing it here reuses the one implementation instead oftranscribing the formula into TypeScript, where it could drift.- - **The attributes are written but nothing is bound yet.** `skinIndex`/`skinWeight` on a- plain `THREE.Mesh` are inert — nothing renders differently — so this slice cannot change- any existing output. It also means the emitted function IS called, which matters because- both the showcase tsconfig and the test harness compile with `--noUnusedLocals`: an- emitted-but-uncalled helper is a hard tsc error, so WS-C.2 genuinely cannot land on its- own without this half.+ - **The helper is emitted once and IS called.** Both the showcase tsconfig and the test+ harness compile with `--noUnusedLocals`, so an emitted-but-uncalled helper is a hard tsc+ error. WS-C.3 consumes these attributes: each skinned component becomes a+ `THREE.SkinnedMesh` and binds against the one shared `Skeleton`."""# stage5_rig was deliberately standalone "until WS-C integration" per its own docstring.# This is that integration, so importing its derivation is the intended coupling rather than@@ -1857,6 +2373,86 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:if isinstance(component.get("geometryDescriptor"), dict)and isinstance(component["geometryDescriptor"].get("visualHull"), dict)]+ # A component may require that it stay outside another's surface. Resolved here rather than at+ # each emission site so an unresolvable declaration becomes one visible comment in the output+ # instead of a clearance that silently never ran.+ components_by_id = {+ str(component.get("id")): component+ for component in components+ if isinstance(component, dict) and component.get("id")+ }+ stand_proud_jobs: list[dict[str, Any]] = []+ stand_proud_skipped: list[str] = []+ for component in components:+ proud = component.get("standProud") if isinstance(component, dict) else None+ if not isinstance(proud, dict):+ continue+ component_id = str(component.get("id"))+ target_id = str(proud.get("againstComponentId") or "")+ proud_target = components_by_id.get(target_id)+ if proud_target is None:+ stand_proud_skipped.append(+ f"{component_id}: standProud target {target_id!r} is not in this component tree"+ )+ continue+ # In the target's LOCAL frame -- which is what `toTarget` maps into -- the surface sits+ # where `geometry.scale` put it, and that scale is baked into the vertices rather than into+ # any matrix. So the analytic stack has to be scaled by hand to match. Measured on the+ # fixture: the authored rings span rx 0.12..0.20 while the scaled geometry spans+ # 0.048..0.080, and an ellipsoid target's unit stack claims 0.5 against an actual 0.2. Left+ # unscaled, the march pushed hair to two and a half times the skull's real radius.+ target_transform = proud_target.get("transform")+ sx, sy, sz = scale_triple(+ proud_target, target_transform if isinstance(target_transform, dict) else {}+ )+ rings = stand_proud_ring_stack(proud_target)+ # A ring stack is a SEPARATE description of a shape the generator also builds another way,+ # so the two can disagree and nothing else would notice. The case that occurs: a `lathe` is+ # a revolve and is therefore circular before `geometry.scale`, so its rings must have+ # rx == rz and let the dimensions supply the ellipticity. A fixture here authored rx != rz+ # on a lathe and described a surface 10-33% wider in z than the geometry it stood for.+ if rings and proud_target.get("primitive") == "lathe":+ for ring in rings:+ if abs(ring[1] - ring[2]) > 1e-9:+ stand_proud_skipped.append(+ f"{component_id}: standProud target {target_id!r} is a lathe, which is "+ f"circular before scaling, but its ringStack authors rx {ring[1]} != rz "+ f"{ring[2]}. The stack does not describe the target's geometry."+ )+ rings = None+ break+ if rings:+ rings = [+ [ring[0] * sy, ring[1] * sx, ring[2] * sz, ring[3] * sz] for ring in rings+ ]+ if not rings:+ stand_proud_skipped.append(+ f"{component_id}: standProud target {target_id!r} "+ f"(primitive {proud_target.get('primitive')!r}) exposes no ring stack to stand proud of"+ )+ continue+ clearance = proud.get("clearance")+ max_push = proud.get("maxPush")+ if not isinstance(clearance, (int, float)) or not isinstance(max_push, (int, float)):+ stand_proud_skipped.append(f"{component_id}: standProud needs numeric clearance and maxPush")+ continue+ stand_proud_jobs.append({+ "componentId": component_id,+ "targetId": target_id,+ "rings": rings,+ "clearance": float(clearance),+ "maxPush": float(max_push),+ })+ if stand_proud_jobs:+ lines.extend(_STAND_PROUD_HELPER_SOURCE.splitlines())+ lines.append("")+ if any(root_tip_gradient(component) for component in components):+ lines.extend(_ROOT_TIP_GRADIENT_HELPER_SOURCE.splitlines())+ lines.append("")+ if any(vertex_paint(component) for component in components):+ lines.extend(_VERTEX_PAINT_HELPER_SOURCE.splitlines())+ lines.append("")+has_subdivision = any(subdivision_iterations(component) > 0 for component in components)has_decimation = any(decimate_ratio(component) is not None for component in components)if visual_hull_components:@@ -2140,6 +2736,131 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:"",])+ if "tapered-sweep" in used_primitives:+ lines.extend(+ [+ "type TaperedStation = { position: [number, number, number]; rx: number; rz: number; twist?: number };",+ "",+ "// Frames come from PARALLEL TRANSPORT, not from a Frenet frame. A Frenet frame is defined by",+ "// the curve's normal, which flips sign wherever the path has an inflection or straightens out,",+ "// and every flip twists the surface 180 degrees within one segment. Carrying the previous frame",+ "// forward and removing only its along-path component keeps the twist continuous. THREE's own",+ "// extrudePath and TubeGeometry do not expose this, which is why this is hand-built.",+ "function buildTaperedSweepGeometry(",+ " sweep: { stations: TaperedStation[]; radialSegments?: number; capEnds?: boolean },",+ "): THREE.BufferGeometry {",+ " const stations = sweep.stations;",+ " if (stations.length < 2) throw new Error('tapered-sweep needs at least two stations');",+ " const radial = Math.max(3, sweep.radialSegments ?? 10);",+ " const centres = stations.map((s) => new THREE.Vector3(...s.position));",+ "",+ " const tangents = centres.map((_, i) => {",+ " const prev = centres[Math.max(0, i - 1)];",+ " const next = centres[Math.min(centres.length - 1, i + 1)];",+ " const t = next.clone().sub(prev);",+ " // Coincident neighbours would normalise to NaN and poison every downstream vertex.",+ " return t.lengthSq() < 1e-12 ? new THREE.Vector3(0, 1, 0) : t.normalize();",+ " });",+ "",+ " // Seed a reference axis that is not parallel to the first tangent, or the first cross",+ " // product is degenerate and the whole sweep collapses to a line.",+ " let ref = new THREE.Vector3(0, 0, 1);",+ " if (Math.abs(tangents[0].dot(ref)) > 0.9) ref = new THREE.Vector3(1, 0, 0);",+ "",+ " const normals: THREE.Vector3[] = [];",+ " const binormals: THREE.Vector3[] = [];",+ " let carried = ref.clone().sub(tangents[0].clone().multiplyScalar(ref.dot(tangents[0]))).normalize();",+ " for (let i = 0; i < tangents.length; i += 1) {",+ " const t = tangents[i];",+ " // Project the carried frame back onto the plane perpendicular to this tangent.",+ " const n = carried.clone().sub(t.clone().multiplyScalar(carried.dot(t)));",+ " if (n.lengthSq() < 1e-12) {",+ " const fallback = Math.abs(t.y) > 0.9 ? new THREE.Vector3(1, 0, 0) : new THREE.Vector3(0, 1, 0);",+ " n.copy(fallback.sub(t.clone().multiplyScalar(fallback.dot(t))));",+ " }",+ " n.normalize();",+ " normals.push(n);",+ " binormals.push(new THREE.Vector3().crossVectors(t, n).normalize());",+ " carried = n;",+ " }",+ "",+ " const positions: number[] = [];",+ " const uvs: number[] = [];",+ " const indices: number[] = [];",+ " const ringStart: number[] = [];",+ " const isPoint: boolean[] = [];",+ "",+ " for (let i = 0; i < stations.length; i += 1) {",+ " const st = stations[i];",+ " const v = i / (stations.length - 1);",+ " ringStart.push(positions.length / 3);",+ " // A station whose section has collapsed emits ONE vertex, not a ring of radius zero.",+ " // A degenerate ring still carries `radial` coincident vertices and `radial` zero-area",+ " // triangles, so the lock ends in a blunt cap the width of the floating-point noise",+ " // rather than at a point -- and a hair lock, a horn or a blade tip has to reach a point.",+ " if (st.rx <= 1e-6 && st.rz <= 1e-6) {",+ " isPoint.push(true);",+ " positions.push(centres[i].x, centres[i].y, centres[i].z);",+ " uvs.push(0.5, v);",+ " continue;",+ " }",+ " isPoint.push(false);",+ " const twist = ((st.twist ?? 0) * Math.PI) / 180;",+ " for (let j = 0; j <= radial; j += 1) {",+ " const theta = (j / radial) * Math.PI * 2 + twist;",+ " const offset = normals[i].clone().multiplyScalar(Math.cos(theta) * st.rx)",+ " .add(binormals[i].clone().multiplyScalar(Math.sin(theta) * st.rz));",+ " const p = centres[i].clone().add(offset);",+ " positions.push(p.x, p.y, p.z);",+ " uvs.push(j / radial, v);",+ " }",+ " }",+ "",+ " for (let i = 0; i < stations.length - 1; i += 1) {",+ " const a0 = ringStart[i];",+ " const b0 = ringStart[i + 1];",+ " if (isPoint[i] && isPoint[i + 1]) continue; // two collapsed stations bound nothing",+ " for (let j = 0; j < radial; j += 1) {",+ " // Wound so the face normal points radially OUTWARD.",+ " //",+ " // Ring vertices advance from `normal` toward `binormal`, and binormal is",+ " // tangent x normal, so increasing theta runs counter-clockwise seen from the",+ " // far end of the segment. Taking the ring-to-ring edge first therefore puts",+ " // the cross product on the inside. Measured as signed volume on the built",+ " // mesh: every tapered-sweep came out negative -- a torso at -0.0674 and a",+ " // tail at -0.0044 against a positive ellipsoid head -- so every sweep this",+ " // generator has ever emitted rendered its back faces, with normals pointing",+ " // into the solid and every lighting judgement made on the wrong surface.",+ " if (isPoint[i]) indices.push(a0, b0 + j + 1, b0 + j);",+ " else if (isPoint[i + 1]) indices.push(a0 + j, a0 + j + 1, b0);",+ " else indices.push(a0 + j, a0 + j + 1, b0 + j, a0 + j + 1, b0 + j + 1, b0 + j);",+ " }",+ " }",+ "",+ " if (sweep.capEnds ?? true) {",+ " for (const end of [0, stations.length - 1]) {",+ " if (isPoint[end]) continue; // a point end is already closed",+ " const centreIndex = positions.length / 3;",+ " positions.push(centres[end].x, centres[end].y, centres[end].z);",+ " uvs.push(0.5, end === 0 ? 0 : 1);",+ " const base = ringStart[end];",+ " for (let j = 0; j < radial; j += 1) {",+ " if (end === 0) indices.push(centreIndex, base + j + 1, base + j);",+ " else indices.push(centreIndex, base + j, base + j + 1);",+ " }",+ " }",+ " }",+ "",+ " const geometry = new THREE.BufferGeometry();",+ " geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));",+ " geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));",+ " geometry.setIndex(indices);",+ " geometry.computeVertexNormals();",+ " return geometry;",+ "}",+ "",+ ]+ )if "curve-sweep" in used_primitives:lines.extend([@@ -2229,8 +2950,14 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:"","function clampedAlbedoColor(spec: SculptMaterialSpec): THREE.Color {"," const source = typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F';",- " const [red, green, blue] = hexToRgb(source);",- " return new THREE.Color(red / 255, green / 255, blue / 255);",+ " // setStyle with an explicit SRGBColorSpace, NOT the numeric constructor.",+ " //",+ " // `new THREE.Color(r, g, b)` treats its arguments as LINEAR working-space components,",+ " // while an authored `baseColor` hex is sRGB. Feeding one to the other skipped the",+ " // transfer function and lifted every dark albedo: #2e2a28, authored as a near-black",+ " // vinyl, rendered at roughly sRGB 0.46 — a mid grey. The error is largest exactly where",+ " // it matters most, because the transfer curve is steepest near black.",+ " return new THREE.Color().setStyle(source, THREE.SRGBColorSpace);","}","","function smoothCurve(value: number): number {",@@ -2588,7 +3315,17 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:"}","","function createSculptMaterial(id: string, spec: SculptMaterialSpec, options: ProceduralModelOptions, denseComponent = false): THREE.MeshPhysicalMaterial {",- " const textures = makeReferenceTextureSet(spec, options) ?? makeProceduralTextureSet(id, spec, options);",+ " // A material that declares -- with evidence -- that its subject carries no texture",+ " // detail gets NO texture set. Synthesising one anyway is not a harmless default: the",+ " // branch below then forces color to white and roughness to 1 and reads both from the",+ " // generated maps, so the authored albedo and the reference-derived roughness are both",+ " // discarded, and the model gains mottling the reference does not have. Measured on the",+ " // tuxedo cat, whose black fur rendered as speckled grey-and-white from a palette that",+ " // only ever described two flat regions.",+ " const textureless = (spec.textureless as { declared?: boolean } | undefined)?.declared === true;",+ " const textures = textureless",+ " ? null",+ " : makeReferenceTextureSet(spec, options) ?? makeProceduralTextureSet(id, spec, options);"," const material = new THREE.MeshPhysicalMaterial({"," color: textures ? 0xffffff : clampedAlbedoColor(spec),"," roughness: textures ? 1 : clamp01(readLayerNumber(spec.roughness, ['base'], 0.76)),",@@ -2837,8 +3574,40 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:lines.extend(["",- f" const {attachment_var} = {json.dumps(attachment, ensure_ascii=False)};",- f" const {endpoint_var} = makeAttachmentEndpoint({attachment_var});",+ *(+ [f" const {attachment_var} = {json.dumps(attachment, ensure_ascii=False)};"]+ if primitive in ATTACHMENT_PRIMITIVES and not is_implicit+ else []+ ),+ # Endpoint-DERIVED GEOMETRY only for primitives that are attachment shapes.+ #+ # An `attachment` block is a contract -- parent socket, contact type, embed depth,+ # local start and end -- and the structural pass requires one on every child+ # appendage. It is NOT a statement that the part is a tapered cylinder. Deriving+ # geometry from it unconditionally silently overrode the authored primitive: an+ # ellipsoid head, a tapered-sweep ear and a swept tail all came out as cylinders+ # between their two endpoints, the spec validated, the factory built, and the+ # wrong shape shipped. That is the same failure mode `GeometryNotImplementedError`+ # exists to prevent one step earlier.+ #+ # So the branch is gated on ATTACHMENT_PRIMITIVES. Every other primitive keeps the+ # geometry it declared and uses the attachment as what it is: a contract the+ # anchor gate reads.+ (+ f" const {endpoint_var} = makeAttachmentEndpoint({attachment_var});"+ # `not is_implicit` as well as the primitive test. An implicit component's+ # geometry comes from the SDF and its placement from its own transform, but it+ # still has to declare SOME `primitive` -- the shipped fixture uses "capsule" --+ # and that lands it in ATTACHMENT_PRIMITIVES. Taking the endpoint branch then+ # moved the node to `attachment.localStart`: a head authored at y 0.705 was+ # emitted at y -0.195, inside the body, and the model rendered with no head at+ # all.+ if primitive in ATTACHMENT_PRIMITIVES and not is_implicit+ # `makeAttachmentEndpoint(null)` rather than a bare `null`, so the+ # binding keeps its `AttachmentEndpoint | null` type. A literal null narrows to+ # `never` and every later `endpoint.start` stops compiling.+ else f" const {endpoint_var} = makeAttachmentEndpoint(null);"+ ),f" const {node_var} = new THREE.Group();",f" {node_var}.name = {json.dumps(name + '__pivot')};",# PLAN_1.5 WS-E: the hierarchy transform (this pivot Group) never carries@@ -2873,12 +3642,64 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:f" if (!{endpoint_var}) {{",f" {component_var}Geometry.scale({scale_vector(component, transform)});"," }",+ # After the scale, so the ramp spans the mass's real extent rather than its unit+ # extent, and before the mesh, so the colour attribute exists when the material+ # reads it.+ *(+ [+ f" applyRootTipGradient({component_var}Geometry, "+ f"{json.dumps(gradient['rootColor'])}, {json.dumps(gradient['tipColor'])}, "+ f"{json.dumps(gradient['axis'])});"+ ]+ if (gradient := root_tip_gradient(component))+ else []+ ),+ *(+ [+ f" applyVertexPaint({component_var}Geometry, "+ f"{json.dumps(paint['baseColor'])}, "+ f"{json.dumps(paint['regions'], ensure_ascii=False)});"+ ]+ if (paint := vertex_paint(component))+ else []+ ),f" const {component_var} = new THREE."f"{'SkinnedMesh' if component_id in skinned_ids else 'Mesh'}(",f" {component_var}Geometry,",f" {material_expression}"," );",f" {component_var}.name = {json.dumps(name)};",+ # Cloned before enabling vertex colours: materials are shared by id, and flipping+ # the flag in place would tint every other component using the same material.+ *(+ [+ f" {component_var}.material = {component_var}.material.clone();",+ f" {component_var}.material.vertexColors = true;",+ ]+ if root_tip_gradient(component) or vertex_paint(component)+ else []+ ),+ # With vertexColors on, three MULTIPLIES material.color by the vertex colour. A+ # paint block already carries the component's full albedo -- its own baseColor for+ # the unpainted surface and a region colour where a region claims it -- so leaving+ # the material's albedo in place squares it. Measured: a 0.027 linear black fur+ # against a 0.027 black material renders at 0.0007, and the white sock authored at+ # 0.937 comes out at 0.025, i.e. darker than the fur is supposed to be. The region+ # boundary is still exactly where the gate measures it, and is invisible.+ #+ # Only for `vertexPaint`. `rootTipGradient` is a SHADING ramp that is meant to+ # modulate the material's own colour, so it keeps the multiply.+ *(+ # Cast: `Mesh.material` is typed `Material | Material[]`, and `color`+ # lives on the concrete material rather than on the base class. `vertexColors`+ # above needs no cast because it IS on `Material`.+ [+ f" ({component_var}.material as THREE.MeshPhysicalMaterial)"+ ".color.setRGB(1, 1, 1);"+ ]+ if vertex_paint(component)+ else []+ ),f" if ({endpoint_var}) {{",f" {component_var}.position.copy({endpoint_var}.midpoint);",f" {component_var}.quaternion.copy({endpoint_var}.quaternion);",@@ -2924,9 +3745,48 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:# same macro/meso/micro levels as componentTree so blockout stays clay-macro.allowed_levels = PASS_LEVELS.get(pass_id, {"macro"})known_ids = {str(c.get("id")) for c in all_components if isinstance(c, dict)}+ # Ids that already exist as built geometry: components in their own right, plus the SDF+ # primitives that make up an implicit component. A repetition system naming these is describing+ # parts that have already been authored, not asking for new ones.+ realised_ids = set(known_ids)+ for component in all_components:+ if not isinstance(component, dict):+ continue+ descriptor = component.get("geometryDescriptor")+ sdf = descriptor.get("sdf") if isinstance(descriptor, dict) else None+ for primitive in (sdf or {}).get("primitives", []) or []:+ if isinstance(primitive, dict) and primitive.get("id"):+ realised_ids.add(str(primitive["id"]))+for rep_index, system in enumerate(spec.get("repetitionSystems", [])):if not isinstance(system, dict):continue+ # A repetition system whose members are ALL already built is documentation, not an+ # instruction, and instancing it emits a second copy of parts that exist.+ #+ # The tuxedo cat declares limb-set, whisker-set and toe-set with elementComponentIds naming+ # the four legs (SDF primitives inside the fused body), the eight whiskers and the six toes+ # (each an authored component that already emits its own mesh), and a PROSE placement —+ # "three per front paw at x offsets -0.040, 0.0, +0.040" — rather than a {mode, axis,+ # radius} object. The emitter below reads that string as an empty dict and falls through to+ # its defaults, so each system came out as an InstancedMesh of unit BOXES centred on the+ # origin, spanning -0.5..0.5 on every axis.+ #+ # That is not merely ugly. geometry.json is measured by run_geometry_gates.py, and the+ # boxes dragged the model's minimum Y from 0.0012 to -0.5 — half a unit underground — so+ # belly-clearance-over-torso-depth was computed against a ground line that does not exist+ # and "failed" for a reason that had nothing to do with the belly.+ #+ # Skipping requires ALL members to be realised, so a genuine instancing system — whose+ # members are deliberately not authored one by one — still emits.+ element_ids = [str(e) for e in (system.get("elementComponentIds") or []) if e]+ if element_ids and all(e in realised_ids for e in element_ids):+ lines.append(+ f" // repetition system {json.dumps(str(system.get('id') or f'rep_{rep_index}'))} "+ f"describes {len(element_ids)} parts that are already built individually; "+ "not instanced."+ )+ continuelevel = str(system.get("level") or "meso")if level not in allowed_levels:continue@@ -2993,6 +3853,30 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:])+ # Deferred to here, after every node is parented, because the march runs in the TARGET's frame+ # and needs both world matrices. Running it at each component's own emission site would depend+ # on the target already existing, which makes a legal forward reference silently do nothing.+ if stand_proud_jobs or stand_proud_skipped:+ lines.append("")+ lines.append(" // standProud: hold these components outside the surfaces they cover.")+ for note in stand_proud_skipped:+ lines.append(f" // SKIPPED {note}")+ for job in stand_proud_jobs:+ marcher = json.dumps(job["componentId"])+ proud_target_key = json.dumps(job["targetId"])+ lines.extend([+ f" if (meshes[{marcher}] && nodes[{proud_target_key}]) {{",+ " applyStandProud(",+ f" meshes[{marcher}].geometry,",+ f" meshes[{marcher}],",+ f" nodes[{proud_target_key}],",+ f" {json_literal({'rings': job['rings']})},",+ f" {job['clearance']},",+ f" {job['maxPush']},",+ " );",+ " }",+ ])+lines.extend(emit_rig_hierarchy(spec))look_dev_targets = spec.get("lookDevTargets", {})diff --git a/forge/stage3_build/orchestrate_passes.py b/forge/stage3_build/orchestrate_passes.pyindex cd1d555..e02b971 100755--- a/forge/stage3_build/orchestrate_passes.py+++ b/forge/stage3_build/orchestrate_passes.py@@ -122,6 +122,24 @@ def current_pass(ids: list[str], completed: list[str]) -> str:return ids[len(completed)]+def spec_has_hair(spec: dict[str, Any]) -> bool:+ """Does this subject have hair the review path has to reason about?++ Two signals, because either can occur alone: a `hairProfile` block, and any component whose role+ is hair. A subject with neither gets no hair evidence demanded of it, which keeps the requirement+ off every chair and knife the pipeline builds.+ """+ if isinstance(spec.get("hairProfile"), dict):+ return True+ components = spec.get("componentTree")+ if not isinstance(components, list):+ return False+ return any(+ isinstance(component, dict) and str(component.get("role") or "").lower() == "hair"+ for component in components+ )++def next_required_evidence(spec: dict[str, Any], pass_id: str) -> list[str]:if pass_id == "complete":return []@@ -130,6 +148,30 @@ def next_required_evidence(spec: dict[str, Any], pass_id: str) -> list[str]:if pass_id in VISUAL_PASS_IDS:evidence.append("browser render screenshot from your agent's browser/screenshot tool")evidence.append("side-by-side reference/render comparison sheet for AI vision review")+ # Silhouette IoU is computed from the ~11% of figure cells on the outline. A model with its+ # face deleted scored 0.8803 against the finished face's 0.8803 -- so an outline score is+ # not evidence about anything inside the outline, and a loop optimising it will spend its+ # whole budget without moving the interior. Read this per region, not as one number.+ evidence.append(+ "banded interior difference vs the reference baseline "+ "(forge/stage4_review/interior_difference.py --from/--to per region)"+ )+ # Hair has its own failure mode that none of the signals above can see. A bald patch is+ # interior, so silhouette IoU is blind to it; it is a luminance change, so interior+ # difference cannot separate it from a colour shift; and it only appears in the render,+ # which is after the loop has already spent a pass. `scalp_exposure.py` finds it+ # geometrically, before anything is drawn. The failure is recorded: widening the hair masses+ # took closure from 42.2% to 40.9%, worse on all six views, and the cause -- masses sliding+ # off the skull -- was invisible to every gate that existed at the time.+ if spec_has_hair(spec):+ evidence.append(+ "scalp exposure below the hard maximum, measured on geometry before rendering "+ "(forge/stage4_review/scalp_exposure.py)"+ )+ evidence.append(+ "hair gate comparing banded coverage, hairline offset and highlight-band position "+ "against the reference (forge/stage4_review/hair_gate.py)"+ )evidence.append("AI vision score at or above the visual acceptance threshold")evidence.append("all critical semantic feature scores from the shared image pair at or above their thresholds")evidence.append("self-correction review appended with action=continue before the next pass")diff --git a/forge/stage4_review/diagnose_render.py b/forge/stage4_review/diagnose_render.pyindex 9e7e5c9..b210499 100644--- a/forge/stage4_review/diagnose_render.py+++ b/forge/stage4_review/diagnose_render.py@@ -68,6 +68,47 @@ def mask_is_inverted(warnings: list[str]) -> bool:return any("tiny" in str(warning).lower() for warning in warnings)+def largest_component(mask: list[bool], size: int) -> tuple[list[bool], float]:+ """Keep the largest 4-connected blob; return it and the fraction of cells discarded.++ WHY. `bbox_of` is an EXTREMAL statistic: one stray foreground cell in a corner moves the+ bounding box to the frame edge, and every proportion derived from it with it. Measured on a+ real review plate, a subject filling 24% of the grid reported a bbox of the entire 224x224+ grid, so `aspectRatioDelta` and `scaleDelta` were describing the render's background gradient+ and did not move at all when the camera did.++ The discarded fraction is returned rather than swallowed: a subject with genuinely separated+ parts in projection -- a floating accessory, a detached prop -- would lose them here, and that+ has to be visible instead of quietly improving the numbers.+ """+ seen = [False] * len(mask)+ best: list[int] = []+ total = sum(1 for value in mask if value)+ for start in range(len(mask)):+ if not mask[start] or seen[start]:+ continue+ stack = [start]+ seen[start] = True+ blob = []+ while stack:+ index = stack.pop()+ blob.append(index)+ y, x = divmod(index, size)+ for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):+ if 0 <= nx < size and 0 <= ny < size:+ neighbour = ny * size + nx+ if mask[neighbour] and not seen[neighbour]:+ seen[neighbour] = True+ stack.append(neighbour)+ if len(blob) > len(best):+ best = blob+ filtered = [False] * len(mask)+ for index in best:+ filtered[index] = True+ discarded = (total - len(best)) / total if total else 0.0+ return filtered, discarded++def load_mask(png_path: Path, size: int = MASK_GRID_SIZE) -> tuple[list[bool], list[str]]:"""Return the resized foreground mask and extraction warnings."""width, height, pixels, _warnings = load_image(png_path)@@ -78,7 +119,14 @@ def load_mask(png_path: Path, size: int = MASK_GRID_SIZE) -> tuple[list[bool], lfor x in range(size):sx = min(width - 1, int(x * width / size))resized.append(mask[sy * width + sx])- return resized, mask_warnings+ filtered, discarded = largest_component(resized, size)+ if discarded > 0.02:+ mask_warnings = list(mask_warnings) + [+ f"{discarded:.1%} of foreground cells lie outside the largest connected blob and were "+ "excluded from the bounding box; if the subject really has separated parts in this "+ "projection, they are not being measured"+ ]+ return filtered, mask_warningsdef silhouette_iou(reference_mask: list[bool], render_mask: list[bool]) -> float:diff --git a/forge/stage4_review/hair_gate.py b/forge/stage4_review/hair_gate.pynew file mode 100644index 0000000..7dc5ba7--- /dev/null+++ b/forge/stage4_review/hair_gate.py@@ -0,0 +1,216 @@+#!/usr/bin/env python3+"""Compare a render's hair against the reference's, and say which differences are which kind.++WHY THE HARD/SOFT SPLIT IS THE POINT. Every hair failure recorded in this pipeline falls into one of+two classes that want opposite responses:++ a bald patch the skull is showing through. Always wrong, at any coverage number, and no+ amount of matching elsewhere compensates. HARD.+ a coverage shortfall there is less hair than the reference has. Often true and often the best+ available compromise at a given triangle budget. SOFT.++Conflating them is what produced four wrong fixes in one session. A coverage shortfall was read as+"add more hair", the masses were widened, and the widening pushed them off the skull -- turning a+soft signal into a hard failure while the coverage number barely moved. The measured result: closure+42.2% to 40.9%, worse on all six views, with crown scalp exposure UP 14.9 points on the worst view.++So a shortfall never authorises widening on its own. `scalpExposure` runs first, geometrically, and+its verdict dominates.++Pure Python 3.10+ standard library.+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path+from typing import Any, Sequence++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))++from extract_hair_evidence import extract_hair_evidence # noqa: E402++# A band whose coverage is this far below the reference is worth reporting. Not calibrated: chosen+# to sit just under the smallest shortfall that proved visible by eye (the profile mid band, which+# read 41.5% against 7.8%).+BAND_SHORTFALL_SOFT = 0.08+# Hairline offset, as a fraction of figure height, beyond which the face has visibly the wrong+# amount of forehead. Derived from the head being roughly 0.13 of figure height: a tenth of a head.+HAIRLINE_OFFSET_MAX = 0.013+# Specular band position difference, in scalp v units, beyond which the highlight reads as sitting+# on the wrong part of the head. Uncalibrated.+SPECULAR_OFFSET_MAX = 0.15+++def compare_views(reference: dict[str, Any], render: dict[str, Any]) -> dict[str, Any]:+ """Per-view band, hairline and shading deltas between two hair-evidence reports."""+ views: dict[str, Any] = {}+ for name, reference_view in reference.get("views", {}).items():+ render_view = render.get("views", {}).get(name)+ if not isinstance(render_view, dict):+ views[name] = {"status": "missing-from-render"}+ continue+ if reference_view.get("status") != "measured" or render_view.get("status") != "measured":+ views[name] = {+ "status": "not-measurable",+ "referenceStatus": reference_view.get("status"),+ "renderStatus": render_view.get("status"),+ }+ continue++ bands = {}+ for band, reference_band in reference_view.get("bands", {}).items():+ render_band = render_view.get("bands", {}).get(band, {})+ delta = round(render_band.get("coverage", 0.0) - reference_band.get("coverage", 0.0), 4)+ bands[band] = {+ "reference": reference_band.get("coverage"),+ "render": render_band.get("coverage"),+ "delta": delta,+ "shortfall": delta <= -BAND_SHORTFALL_SOFT,+ }++ reference_hairline = reference_view.get("hairline")+ render_hairline = render_view.get("hairline")+ hairline_offset = (+ round(render_hairline - reference_hairline, 4)+ if reference_hairline is not None and render_hairline is not None+ else None+ )++ reference_specular = reference_view.get("shading", {}).get("specularBandV")+ render_specular = render_view.get("shading", {}).get("specularBandV")+ specular_offset = (+ round(render_specular - reference_specular, 4)+ if reference_specular is not None and render_specular is not None+ else None+ )++ views[name] = {+ "status": "compared",+ "bands": bands,+ "hairlineOffset": hairline_offset,+ "specularOffset": specular_offset,+ "hairFractionDelta": round(+ render_view.get("hairFraction", 0.0) - reference_view.get("hairFraction", 0.0), 4+ ),+ }+ return views+++def hair_gate(+ reference_views: dict[str, Path],+ render_views: dict[str, Path],+ scalp_exposure_report: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """The whole hair verdict: one hard channel, several soft ones.++ `scalp_exposure_report` is the output of `scalp_exposure.py`. It is optional only so this module+ can be used on captures alone, and its absence is reported as a gap rather than treated as a+ pass -- an image-only comparison cannot see a bald patch reliably, which is the entire reason+ the geometric gate exists.+ """+ reference = extract_hair_evidence(reference_views)+ render = extract_hair_evidence(render_views)+ views = compare_views(reference, render)++ hard: list[str] = []+ soft: list[str] = []++ if scalp_exposure_report is None:+ soft.append(+ "scalpExposure was not supplied; a pixel comparison cannot reliably see a bald patch, "+ "so this verdict is incomplete. Run forge/stage4_review/scalp_exposure.py."+ )+ elif scalp_exposure_report.get("verdict") == "fail":+ hard.append(+ f"scalpExposure {scalp_exposure_report.get('exposedFraction')} exceeds "+ f"{scalp_exposure_report.get('hardMax')}: the skull is uncovered and will render bald. "+ f"No coverage improvement elsewhere compensates for this."+ )++ for name, view in views.items():+ if view.get("status") != "compared":+ soft.append(f"{name}: {view.get('status')}")+ continue+ for band, data in view.get("bands", {}).items():+ if data.get("shortfall"):+ soft.append(+ f"{name}/{band}: coverage {data['render']} against reference {data['reference']} "+ f"(delta {data['delta']})"+ )+ offset = view.get("hairlineOffset")+ if offset is not None and abs(offset) > HAIRLINE_OFFSET_MAX:+ soft.append(f"{name}: hairline off by {offset} of figure height")+ specular = view.get("specularOffset")+ if specular is not None and abs(specular) > SPECULAR_OFFSET_MAX:+ soft.append(+ f"{name}: highlight band off by {specular} in scalp v; this is a MATERIAL "+ f"difference, not a geometry one, and adding hair will not move it"+ )++ return {+ "schemaVersion": 1,+ "kind": "hair-gate",+ "verdict": "fail" if hard else ("review" if soft else "pass"),+ # Whether the HARD channel actually ran, kept separate from the verdict. "review" with the+ # geometric gate present means "checked, here are notes"; "review" with it absent means "I+ # could not check the one thing that is always a failure". Collapsing those two into one+ # word let a run with no bald-patch check at all exit 0.+ "hardChannelPresent": scalp_exposure_report is not None,+ "hardFailures": hard,+ "softSignals": soft,+ "views": views,+ "referenceNotObserved": reference.get("notObserved", []),+ "renderNotObserved": render.get("notObserved", []),+ "thresholds": {+ "bandShortfallSoft": BAND_SHORTFALL_SOFT,+ "hairlineOffsetMax": HAIRLINE_OFFSET_MAX,+ "specularOffsetMax": SPECULAR_OFFSET_MAX,+ "uncalibrated": True,+ },+ "note": (+ "A band shortfall is a soft signal and never on its own authorises widening the masses. "+ "That exact response was measured: widening took closure from 42.2% to 40.9%, worse on "+ "all six views, because the widened mass slid off the skull rather than growing on it."+ ),+ }+++def _pairs(entries: Sequence[str], parser: argparse.ArgumentParser) -> dict[str, Path]:+ views: dict[str, Path] = {}+ for entry in entries:+ if "=" not in entry:+ parser.error(f"expected view=path, got {entry!r}")+ name, _, raw = entry.partition("=")+ views[name] = Path(raw)+ return views+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("--reference", nargs="+", required=True, help="view=path pairs")+ parser.add_argument("--render", nargs="+", required=True, help="view=path pairs")+ parser.add_argument("--scalp-exposure", help="JSON report from scalp_exposure.py")+ parser.add_argument("--out")+ args = parser.parse_args(argv)++ exposure = json.loads(Path(args.scalp_exposure).read_text()) if args.scalp_exposure else None+ report = hair_gate(_pairs(args.reference, parser), _pairs(args.render, parser), exposure)+ text = json.dumps(report, indent=2)+ if args.out:+ Path(args.out).write_text(text + "\n")+ print(text)++ # 1 = a hard failure. 2 = the hard channel never ran, so this verdict is incomplete and must not+ # read as approval to a caller that only checks for zero. 0 = the hard gate ran and passed;+ # soft signals alone do not fail a build, by design.+ if report["verdict"] == "fail":+ return 1+ if not report["hardChannelPresent"]:+ return 2+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/forge/stage4_review/interior_difference.py b/forge/stage4_review/interior_difference.pynew file mode 100644index 0000000..a3aafda--- /dev/null+++ b/forge/stage4_review/interior_difference.py@@ -0,0 +1,188 @@+#!/usr/bin/env python3+"""Appearance difference INSIDE the silhouette, banded by height, against a baseline render.++Silhouette IoU is computed from the figure cells that lie on the outline -- about 11% of them at+grid 192. This reads the other 89%.++It exists because of a measured result, not a theory. A finished face and the same model with its+face deleted -- nose, mouth, eyes and both brows set invisible, hair material swapped for skin --+scored 0.8803 and 0.8803 on the outline metric, identical to four decimals. Adding an entire mouth+moved that metric by -0.0002, in the wrong direction. An outline metric cannot answer whether a face+is right, or even whether it is present, so it must not be the signal a correction loop optimises+for interior work.++Both renders are aligned by their foreground bounding box -- the same normalisation the IoU scorer+performs -- then resampled to a common lattice. Only cells that are figure in BOTH are compared, so+outline agreement cannot leak back in and inflate the result. The number is mean absolute luminance+difference as a fraction of full range: 0.000 is identical inside the mask, larger is further from+the baseline.++Restrict with --from/--to to read one region. On a standing figure the head is roughly the top 19%+of figure height, i.e. `--from 0 --to 0.19`.++BBOX CONVENTION. This module uses half-open corners `(x0, y0, x1, y1)`, matching+`objectness._bbox`. It deliberately does NOT use `diagnose_render.bbox_of`, which returns+`(x0, y0, width, height)` -- passing one where the other is expected produces confident garbage+rather than an error, and that exact substitution has already cost this project a debugging session.+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path+from typing import Any++sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402++from diagnose_render import mask_is_inverted # noqa: E402++GRID = 192 # the lattice the audit's published numbers were computed on; changing it changes them+++def _bbox_corners(mask: list[bool], width: int, height: int) -> tuple[int, int, int, int]:+ """Half-open `(x0, y0, x1, y1)`. An empty mask returns the whole frame."""+ min_x = min_y = 1 << 30+ max_x = max_y = -1+ for y in range(height):+ row = y * width+ for x in range(width):+ if mask[row + x]:+ if x < min_x:+ min_x = x+ if x > max_x:+ max_x = x+ if y < min_y:+ min_y = y+ if y > max_y:+ max_y = y+ if max_x < 0:+ return (0, 0, width, height)+ return (min_x, min_y, max_x + 1, max_y + 1)+++def sample(png_path: Path, grid: int = GRID) -> tuple[list[float], list[bool], list[str]]:+ """Per-cell mean channel value and figure-majority flag, over the foreground bounding box.++ The cell value is an AREA MEAN, not a point sample. At grid 192 over a 1024px render each cell+ covers roughly 5x5 source pixels; point sampling would alias hard edges and make the result+ depend on where the lattice happened to land.+ """+ width, height, pixels, load_warnings = load_image(png_path)+ mask, _diagnostics, mask_warnings = build_foreground_mask(width, height, pixels)+ x0, y0, x1, y1 = _bbox_corners(mask, width, height)+ box_w = max(1, x1 - x0)+ box_h = max(1, y1 - y0)++ values = [0.0] * (grid * grid)+ solid = [False] * (grid * grid)+ for gy in range(grid):+ ys = y0 + gy * box_h // grid+ ye = max(y0 + (gy + 1) * box_h // grid, ys + 1)+ for gx in range(grid):+ xs = x0 + gx * box_w // grid+ xe = max(x0 + (gx + 1) * box_w // grid, xs + 1)+ total = 0+ counted = 0+ foreground = 0+ for y in range(ys, min(ye, height)):+ row = y * width+ for x in range(xs, min(xe, width)):+ red, green, blue, _alpha = pixels[row + x]+ total += red + green + blue+ counted += 1+ if mask[row + x]:+ foreground += 1+ index = gy * grid + gx+ values[index] = (total / (3 * counted)) if counted else 0.0+ solid[index] = bool(counted) and foreground > counted / 2+ return values, solid, list(load_warnings) + list(mask_warnings)+++def compare(+ baseline_png: Path,+ render_png: Path,+ band_from: float = 0.0,+ band_to: float = 1.0,+ grid: int = GRID,+) -> dict[str, Any]:+ """Mean absolute luminance difference over cells that are figure in both, within a height band.++ `cellsCompared` is reported alongside the score for the same reason every other gate here+ reports its sample count: a small difference over four cells is not evidence.+ """+ baseline_values, baseline_solid, baseline_warnings = sample(baseline_png, grid)+ render_values, render_solid, render_warnings = sample(render_png, grid)++ first_row = int(band_from * grid)+ last_row = max(int(band_to * grid), first_row + 1)+ shared = [+ gy * grid + gx+ for gy in range(first_row, min(last_row, grid))+ for gx in range(grid)+ if baseline_solid[gy * grid + gx] and render_solid[gy * grid + gx]+ ]++ result: dict[str, Any] = {+ "schemaVersion": 1,+ "kind": "interior-difference",+ "baseline": str(baseline_png),+ "render": str(render_png),+ "band": {"from": band_from, "to": band_to},+ "grid": grid,+ "cellsCompared": len(shared),+ "warnings": baseline_warnings + render_warnings,+ }+ # Same hard refusal divine_eye makes. A mask that fell back to whole-frame coverage marks every+ # cell solid, so this metric would compare background against background and return a confident+ # number about nothing -- worse than the outline metric it replaces, because the number looks+ # like interior evidence.+ if mask_is_inverted(baseline_warnings) or mask_is_inverted(render_warnings):+ result["interiorDifference"] = None+ result["status"] = "foreground-mask-fell-back-to-whole-frame"+ return result+ if not shared:+ result["interiorDifference"] = None+ result["status"] = "no-overlapping-figure-cells"+ return result++ total = sum(abs(baseline_values[i] - render_values[i]) for i in shared)+ result["interiorDifference"] = total / len(shared) / 255.0+ result["status"] = "measured"+ return result+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("baseline", type=Path)+ parser.add_argument("renders", nargs="+", type=Path)+ parser.add_argument("--from", dest="band_from", type=float, default=0.0)+ parser.add_argument("--to", dest="band_to", type=float, default=1.0)+ parser.add_argument("--grid", type=int, default=GRID)+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args(argv)++ results = [+ compare(args.baseline, render, args.band_from, args.band_to, args.grid)+ for render in args.renders+ ]+ if args.json:+ print(json.dumps(results if len(results) > 1 else results[0], indent=2))+ return 0++ print(f"band y/H {args.band_from:.2f}..{args.band_to:.2f} vs {args.baseline.name}")+ for result in results:+ name = Path(result["render"]).name+ if result["interiorDifference"] is None:+ print(f" {name:<34} {result['status']}")+ else:+ print(+ f" {name:<34} interior difference {result['interiorDifference']:.4f}"+ f" ({result['cellsCompared']} cells)"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/forge/stage4_review/scalp_exposure.py b/forge/stage4_review/scalp_exposure.pynew file mode 100644index 0000000..d3f3917--- /dev/null+++ b/forge/stage4_review/scalp_exposure.py@@ -0,0 +1,257 @@+#!/usr/bin/env python3+"""Find bald patches before anything is rendered.++WHY THIS GATE EXISTS. Three review signals already look at hair and none of them can see this+failure:++ silhouette_iou blind by construction -- only about 11% of a figure's cells lie on the+ outline, and a bald crown is interior+ interior_difference sees it, but only AFTER a browser capture, and only as a number that could+ equally mean a colour shift+ the human eye sees it instantly, and was the only thing that caught it the last three times++The failure is specific and repeatable. Widening the hair side masses by hand took closure from+42.2% to 40.9%, worse on all six views, and dark coverage went DOWN. The widened mass had slid off+the skull: the loft's spine is straight while the skull is convex, so thickening the section moved+the surface sideways rather than outward, the skull ended up proud of the hair, and the render grew+a bare strip. The invariant it broke was already written down in the demo:++ EVERY piece must stand proud of the skull at its own height. Where the skull is proud of the+ hair, the head renders bald there.++This gate is that sentence as arithmetic. It runs on points, so it works on any hair+representation -- shell, masses or locks -- and it needs no browser, no GPU and no capture.++HAIR INSIDE THE SKULL IS NOT COVERAGE. That is the whole point. A naive "is there a hair vertex near+this patch of scalp" test would have passed the widened build, because the vertices were still+nearby -- they had merely sunk below the surface. Only points on the outside of the skull count.++Pure Python 3.10+ standard library.+"""+from __future__ import annotations++import argparse+import json+import math+import sys+from pathlib import Path+from typing import Any, Iterable, Sequence++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))++from scalp_field import ScalpField # noqa: E402++Point = tuple[float, float, float]++# A patch of scalp counts as covered when hair sits within this far along its outward normal,+# measured as a fraction of the skull's own height. Hair further out than this is a separate mass+# floating clear of the head rather than the layer that covers it.+DEFAULT_REACH_FRACTION = 0.22+# ... and within this far off that normal, laterally, again as a fraction of skull height. This is+# the sampling radius, not a physical property: it must be a little wider than the gap between+# adjacent scalp samples or the test reports stripes of exposure between the samples themselves.+DEFAULT_LATERAL_FRACTION = 0.075+# Azimuth and height sampling of the scalp. 32x16 is 512 patches over a head, which resolves a strip+# roughly a finger wide -- finer than the failure being caught and coarse enough to stay instant.+DEFAULT_U_SAMPLES = 32+DEFAULT_V_SAMPLES = 16+# Anything above this fraction of scalp area uncovered is a hard failure rather than a soft signal.+# Not calibrated against a reference: no multipart hair reference exists yet, so this is a+# deliberately loose bound chosen to catch the recorded failure and flagged as uncalibrated in the+# report rather than presented as a measurement.+DEFAULT_HARD_MAX = 0.05+++class _PointGrid:+ """Uniform bucket grid, so the gate stays linear in hair points rather than quadratic."""++ def __init__(self, points: Sequence[Point], cell: float) -> None:+ self.cell = max(cell, 1e-6)+ self.buckets: dict[tuple[int, int, int], list[Point]] = {}+ for point in points:+ self.buckets.setdefault(self._key(point), []).append(point)++ def _key(self, point: Point) -> tuple[int, int, int]:+ return (+ int(math.floor(point[0] / self.cell)),+ int(math.floor(point[1] / self.cell)),+ int(math.floor(point[2] / self.cell)),+ )++ def near(self, point: Point) -> Iterable[Point]:+ cx, cy, cz = self._key(point)+ for dx in (-1, 0, 1):+ for dy in (-1, 0, 1):+ for dz in (-1, 0, 1):+ bucket = self.buckets.get((cx + dx, cy + dy, cz + dz))+ if bucket:+ yield from bucket+++def scalp_exposure(+ field: ScalpField,+ hair_points: Sequence[Point],+ *,+ reach: float | None = None,+ lateral: float | None = None,+ u_samples: int = DEFAULT_U_SAMPLES,+ v_samples: int = DEFAULT_V_SAMPLES,+ hard_max: float = DEFAULT_HARD_MAX,+ v_range: tuple[float, float] = (0.0, 1.0),+) -> dict[str, Any]:+ """What fraction of the scalp has no hair standing over it.++ `v_range` restricts the test to a band of the skull. The face is scalp by geometry and not by+ anatomy, so a full-head sweep would report the forehead, nose and chin as bald and drown the+ signal; callers pass the band above the hairline.++ The returned fraction is AREA-weighted, not sample-weighted: rings near the crown are far+ shorter in circumference than rings at the temples, and counting samples would let a small bare+ crown hide behind a large well-covered band.+ """+ height = field.y_max - field.y_min+ if height <= 0.0:+ raise ValueError("the scalp field has no height")+ reach_distance = reach if reach is not None else DEFAULT_REACH_FRACTION * height+ lateral_distance = lateral if lateral is not None else DEFAULT_LATERAL_FRACTION * height+ if reach_distance <= 0.0 or lateral_distance <= 0.0:+ raise ValueError("reach and lateral must both be positive")+ low, high = v_range+ if not 0.0 <= low < high <= 1.0:+ raise ValueError(f"v_range must be an ascending band inside [0,1], got {v_range}")++ # Only hair OUTSIDE the skull can cover it. This single filter is the difference between a gate+ # that catches the recorded failure and one that waves it through.+ outside = [p for p in hair_points if field.distance(*p) > 0.0]+ sunk = len(hair_points) - len(outside)+ grid = _PointGrid(outside, lateral_distance)++ march_steps = max(2, int(math.ceil(reach_distance / lateral_distance)) + 1)++ total_area = 0.0+ exposed_area = 0.0+ exposed: list[dict[str, float]] = []+ walked = 0++ # The band and the cap disc used to be two near-identical loops here. They are one now, because+ # `ScalpField.surface_samples` already knows how to walk both -- and the duplicate was worse+ # than untidy: the cap loop was added later to close a defect, and having a second copy of the+ # march is precisely how the two would drift apart the next time one of them is fixed.+ for sample in field.surface_samples(u_samples, v_samples, v_range=(low, high)):+ px, py, pz = sample["point"]+ nx, ny, nz = sample["normal"]+ weight = sample["weight"]+ total_area += weight+ walked += 1++ covered = False+ for step in range(march_steps + 1):+ t = reach_distance * step / march_steps+ qx, qy, qz = px + nx * t, py + ny * t, pz + nz * t+ for hx, hy, hz in grid.near((qx, qy, qz)):+ if (hx - qx) ** 2 + (hy - qy) ** 2 + (hz - qz) ** 2 <= lateral_distance ** 2:+ covered = True+ break+ if covered:+ break++ if not covered:+ exposed_area += weight+ entry = {"u": round(sample["u"], 4), "v": round(sample["v"], 4),+ "x": round(px, 5), "y": round(py, 5), "z": round(pz, 5)}+ if sample["cap"]:+ entry["cap"] = True+ entry["capRing"] = sample["capRing"]+ exposed.append(entry)++ fraction = exposed_area / total_area if total_area > 0.0 else 0.0+ return {+ "schemaVersion": 1,+ "kind": "scalp-exposure",+ "exposedFraction": round(fraction, 6),+ "exposedSamples": exposed,+ # What was actually walked, not u*v: the cap disc adds its own annuli, so the product+ # under-reported by 128 of 640 and a caller sizing anything off it would be wrong.+ "sampleCount": walked,+ "hairPointCount": len(hair_points),+ "hairPointsInsideSkull": sunk,+ "reach": round(reach_distance, 6),+ "lateral": round(lateral_distance, 6),+ "vRange": [low, high],+ "hardMax": hard_max,+ "hardMaxUncalibrated": True,+ "verdict": "fail" if fraction > hard_max else "pass",+ "note": (+ "Area-weighted fraction of scalp with no hair standing outside the skull above it. "+ "Hair points inside the skull are excluded from coverage by design: the recorded "+ "failure was a mass that slid off the skull while staying nearby."+ ),+ }+++def largest_exposed_run(result: dict[str, Any], u_samples: int = DEFAULT_U_SAMPLES) -> int:+ """Longest unbroken azimuth run of exposed samples at any one height.++ A scatter of isolated exposed samples is sampling noise. A RUN is a strip, and a strip is what+ a viewer reads as a parting or a bald line -- the recorded failure showed exactly that, a bare+ band down the centre of the crown.+ """+ # Keyed by (v, capRing), not by v. Every cap annulus reports v = 1.0, so keying on v alone+ # merged the whole disc into a single row and let one bare annulus read as a full-circle run.+ by_row: dict[tuple[float, int], set[int]] = {}+ for sample in result.get("exposedSamples", []):+ column = int(round(sample["u"] * u_samples)) % u_samples+ by_row.setdefault((sample["v"], sample.get("capRing", -1)), set()).add(column)++ longest = 0+ for columns in by_row.values():+ # A fully exposed ring has NO first column -- every column's predecessor is also exposed --+ # so the run-start scan below finds no start and falls through reporting zero. That is the+ # worst case reporting as the best, on a head with no hair on it at all.+ if len(columns) >= u_samples:+ return u_samples+ for start in columns:+ if (start - 1) % u_samples in columns:+ continue # not the beginning of a run+ run = 1+ while (start + run) % u_samples in columns and run < u_samples:+ run += 1+ longest = max(longest, run)+ return longest+++def _load_points(path: Path) -> list[Point]:+ payload = json.loads(path.read_text())+ raw = payload.get("points", payload) if isinstance(payload, dict) else payload+ if not isinstance(raw, list):+ raise ValueError("expected a JSON array of [x,y,z] points, or {\"points\": [...]}")+ return [(float(p[0]), float(p[1]), float(p[2])) for p in raw]+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ parser.add_argument("--rings", required=True, help="JSON file: [[y,rx,rz,(zc)], ...]")+ parser.add_argument("--hair-points", required=True, help="JSON file: [[x,y,z], ...]")+ parser.add_argument("--v-low", type=float, default=0.0)+ parser.add_argument("--v-high", type=float, default=1.0)+ parser.add_argument("--hard-max", type=float, default=DEFAULT_HARD_MAX)+ parser.add_argument("--out", help="also write the report here")+ args = parser.parse_args(argv)++ field = ScalpField(json.loads(Path(args.rings).read_text()))+ report = scalp_exposure(+ field,+ _load_points(Path(args.hair_points)),+ hard_max=args.hard_max,+ v_range=(args.v_low, args.v_high),+ )+ report["largestExposedRun"] = largest_exposed_run(report)+ text = json.dumps(report, indent=2)+ if args.out:+ Path(args.out).write_text(text + "\n")+ print(text)+ return 0 if report["verdict"] == "pass" else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/forge/stage4_review/swept_arc_gate.py b/forge/stage4_review/swept_arc_gate.pynew file mode 100644index 0000000..168f7d7--- /dev/null+++ b/forge/stage4_review/swept_arc_gate.py@@ -0,0 +1,336 @@+#!/usr/bin/env python3+"""Gate a swept component's SHAPE — bend radius, angular span and taper — on executed geometry.++WHAT THIS IS FOR. "Curled upward into a hook; a curved spine, not a straight cone" is a claim about+a curve, and no existing gate can hold it. A silhouette IoU passes a straight cone that happens to+occupy roughly the right cells. `self_intersection.py` asks whether a mesh crosses itself, not what+shape it is. A visual review can see the difference but only after a render, and only as an+impression rather than a number.++So the shape claim is fitted directly. The component's vertices are projected onto their own+best-fit plane, an arc centre is fitted by minimising the spread of radii, and the gate reports the+bend radius, the angular span actually covered, the tube radius along the arc, and the residual of+the fit.++THE NEGATIVE CONTROL IS THE POINT. A straight tapered cone has no stable arc centre: pushing the+centre far enough away makes any bounded set look like a thin annulus, so `radiusSpread` alone can+be driven arbitrarily low and is not evidence of curvature on its own. What separates a hook from a+cone is the ANGULAR SPAN subtended at the fitted centre — a straight segment subtends a span that+shrinks as the fitted centre recedes, while a real hook holds a large span at a centre close to it.+The gate therefore requires span AND a bounded centre distance, and `forge/tests/test_swept_arc.py`+runs a straight cone through it to prove it fails.++Exit codes: 0 clean, 1 gate failure, 2 error.+"""++from __future__ import annotations++import argparse+import json+import math+import sys+from pathlib import Path+from typing import Any, Sequence+++def _load_json(path: Path, label: str) -> Any:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as error:+ raise SystemExit(f"{label} error: {error}")+++def _mean(values: Sequence[float]) -> float:+ return sum(values) / len(values)+++def symmetric_eigenvalues(matrix: list[list[float]]) -> tuple[float, float, float]:+ """Eigenvalues of a symmetric 3x3, largest first, by the closed-form trigonometric solution."""+ p1 = matrix[0][1] ** 2 + matrix[0][2] ** 2 + matrix[1][2] ** 2+ trace = matrix[0][0] + matrix[1][1] + matrix[2][2]+ if p1 == 0.0:+ return tuple(sorted((matrix[0][0], matrix[1][1], matrix[2][2]), reverse=True))+ q = trace / 3.0+ p2 = sum((matrix[i][i] - q) ** 2 for i in range(3)) + 2.0 * p1+ p = math.sqrt(p2 / 6.0)+ b = [[(matrix[i][j] - (q if i == j else 0.0)) / p for j in range(3)] for i in range(3)]+ determinant = (+ b[0][0] * (b[1][1] * b[2][2] - b[1][2] * b[2][1])+ - b[0][1] * (b[1][0] * b[2][2] - b[1][2] * b[2][0])+ + b[0][2] * (b[1][0] * b[2][1] - b[1][1] * b[2][0])+ )+ r = determinant / 2.0+ r = -1.0 if r <= -1.0 else 1.0 if r >= 1.0 else r+ phi = math.acos(r) / 3.0+ eig1 = q + 2.0 * p * math.cos(phi)+ eig3 = q + 2.0 * p * math.cos(phi + 2.0 * math.pi / 3.0)+ eig2 = trace - eig1 - eig3+ return (eig1, eig2, eig3)+++def best_fit_plane(points: list[tuple[float, float, float]]):+ """Return (origin, u, v, normal, planarity) for the plane the points lie closest to.++ `planarity` is `(lambda2 - lambda3) / lambda2` on the covariance eigenvalues. It matters+ because a SHORT sweep of a THICK tube is a rod, and a rod does not determine a plane: its two+ smaller eigenvalues are both the tube's cross-section and are nearly equal, so the smallest+ eigenvector is an arbitrary direction in that cross-section. Fitting an arc in that arbitrary+ plane produces a confident, meaningless bend radius — this measurement found exactly that on a+ 40-degree fixture before the degeneracy was detected instead of ignored.+ """+ cx, cy, cz = (_mean([p[0] for p in points]), _mean([p[1] for p in points]), _mean([p[2] for p in points]))+ xx = xy = xz = yy = yz = zz = 0.0+ for x, y, z in points:+ dx, dy, dz = x - cx, y - cy, z - cz+ xx += dx * dx+ xy += dx * dy+ xz += dx * dz+ yy += dy * dy+ yz += dy * dz+ zz += dz * dz+ matrix = [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]+ eig1, eig2, eig3 = symmetric_eigenvalues(matrix)+ planarity = (eig2 - eig3) / eig2 if eig2 > 1e-15 else 0.0++ # Power-iterate on (trace*I - M) to land on the SMALLEST eigenvector of M.+ trace = xx + yy + zz+ shifted = [[(trace if i == j else 0.0) - matrix[i][j] for j in range(3)] for i in range(3)]+ vector = [1.0, 0.37, 0.11]+ for _ in range(200):+ nxt = [sum(shifted[i][j] * vector[j] for j in range(3)) for i in range(3)]+ norm = math.sqrt(sum(v * v for v in nxt))+ if norm < 1e-15:+ break+ vector = [v / norm for v in nxt]+ normal = tuple(vector)++ seed = (1.0, 0.0, 0.0) if abs(normal[0]) < 0.9 else (0.0, 1.0, 0.0)+ ux = seed[1] * normal[2] - seed[2] * normal[1]+ uy = seed[2] * normal[0] - seed[0] * normal[2]+ uz = seed[0] * normal[1] - seed[1] * normal[0]+ ulen = math.sqrt(ux * ux + uy * uy + uz * uz)+ u = (ux / ulen, uy / ulen, uz / ulen)+ v = (+ normal[1] * u[2] - normal[2] * u[1],+ normal[2] * u[0] - normal[0] * u[2],+ normal[0] * u[1] - normal[1] * u[0],+ )+ return (cx, cy, cz), u, v, normal, planarity+++def fit_arc_centre(points2d: list[tuple[float, float]]):+ """Coarse-to-fine search for the centre minimising the standard deviation of radii."""+ xs = [p[0] for p in points2d]+ ys = [p[1] for p in points2d]+ span = max(max(xs) - min(xs), max(ys) - min(ys)) or 1.0+ lo_x, hi_x = min(xs) - span, max(xs) + span+ lo_y, hi_y = min(ys) - span, max(ys) + span+ best_centre = (_mean(xs), _mean(ys))+ best_spread = float("inf")+ for _ in range(6):+ step_x = (hi_x - lo_x) / 12+ step_y = (hi_y - lo_y) / 12+ for i in range(13):+ for j in range(13):+ cx = lo_x + i * step_x+ cy = lo_y + j * step_y+ radii = [math.hypot(x - cx, y - cy) for x, y in points2d]+ mean = _mean(radii)+ spread = math.sqrt(_mean([(r - mean) ** 2 for r in radii]))+ if spread < best_spread:+ best_spread = spread+ best_centre = (cx, cy)+ lo_x, hi_x = best_centre[0] - step_x, best_centre[0] + step_x+ lo_y, hi_y = best_centre[1] - step_y, best_centre[1] + step_y+ return best_centre, best_spread+++def angular_span(points2d: list[tuple[float, float]], centre: tuple[float, float]) -> float:+ """Degrees of arc actually occupied, found as the complement of the largest empty gap."""+ angles = sorted(math.degrees(math.atan2(y - centre[1], x - centre[0])) for x, y in points2d)+ if len(angles) < 2:+ return 0.0+ gaps = [angles[i + 1] - angles[i] for i in range(len(angles) - 1)]+ gaps.append(angles[0] + 360.0 - angles[-1])+ return round(360.0 - max(gaps), 2)+++def analyse(points: list[tuple[float, float, float]], bins: int = 24) -> dict[str, Any]:+ origin, u, v, normal, planarity = best_fit_plane(points)+ planar = []+ off_plane = []+ for x, y, z in points:+ dx, dy, dz = x - origin[0], y - origin[1], z - origin[2]+ planar.append((dx * u[0] + dy * u[1] + dz * u[2], dx * v[0] + dy * v[1] + dz * v[2]))+ off_plane.append(abs(dx * normal[0] + dy * normal[1] + dz * normal[2]))++ centre, spread = fit_arc_centre(planar)+ radii = [math.hypot(x - centre[0], y - centre[1]) for x, y in planar]+ bend_radius = _mean(radii)+ span = angular_span(planar, centre)++ extent = max(+ max(p[0] for p in planar) - min(p[0] for p in planar),+ max(p[1] for p in planar) - min(p[1] for p in planar),+ )+ centre_distance = math.hypot(centre[0] - _mean([p[0] for p in planar]),+ centre[1] - _mean([p[1] for p in planar]))++ buckets: dict[int, list[float]] = {}+ for (x, y), radius in zip(planar, radii):+ key = int(math.degrees(math.atan2(y - centre[1], x - centre[0])) // (360 / bins))+ buckets.setdefault(key, []).append(radius)+ tube = [+ {"bin": key, "tubeRadius": round((max(values) - min(values)) / 2, 6), "samples": len(values)}+ for key, values in sorted(buckets.items())+ if len(values) >= 8+ ]+ tube_radii = [entry["tubeRadius"] for entry in tube]++ return {+ "sampledVertexCount": len(points),+ "planeNormal": [round(component, 5) for component in normal],+ "planarity": round(planarity, 5),+ "maxOffPlaneDistance": round(max(off_plane), 6),+ "bendRadius": round(bend_radius, 6),+ "radiusSpread": round(spread, 6),+ "radiusSpreadOverBendRadius": round(spread / bend_radius, 5) if bend_radius else None,+ "angularSpanDeg": span,+ "centreDistanceOverExtent": round(centre_distance / extent, 5) if extent else None,+ "planarExtent": round(extent, 6),+ "tubeRadius": {+ "min": round(min(tube_radii), 6) if tube_radii else None,+ "max": round(max(tube_radii), 6) if tube_radii else None,+ "mean": round(_mean(tube_radii), 6) if tube_radii else None,+ "bins": tube,+ },+ }+++def evaluate(measured: dict[str, Any], expectations: dict[str, Any]) -> dict[str, Any]:+ checks = []++ def record(name: str, value: Any, ok: bool, detail: str) -> None:+ checks.append({"check": name, "value": value, "status": "pass" if ok else "fail", "detail": detail})++ # Checked first, and reported first, because every number after it is computed IN the fitted+ # plane. When the plane is not determined the rest of the report is arithmetic on an arbitrary+ # projection, so a "bend radius" there is uncalibrated rather than merely wrong.+ planarity_min = expectations.get("minPlanarity", 0.35)+ record(+ "planeDetermined",+ measured["planarity"],+ measured["planarity"] >= planarity_min,+ "the sweep must actually determine a plane; a short sweep of a thick tube is a rod, whose "+ "two smaller covariance eigenvalues are both its cross-section, so any plane fitted "+ "through it is arbitrary",+ )++ span_min = expectations.get("minAngularSpanDeg")+ if span_min is not None:+ record(+ "angularSpan",+ measured["angularSpanDeg"],+ measured["angularSpanDeg"] >= span_min,+ f"a hook must subtend at least {span_min} degrees at its fitted centre; a straight "+ "cone cannot",+ )++ centre_max = expectations.get("maxCentreDistanceOverExtent")+ if centre_max is not None:+ value = measured["centreDistanceOverExtent"]+ record(+ "centreDistance",+ value,+ value is not None and value <= centre_max,+ "the fitted centre must sit near the component, not be pushed far away to make a "+ "straight run look like a shallow arc",+ )++ bend = expectations.get("bendRadius")+ if bend is not None:+ tolerance = float(expectations.get("bendRadiusTolerance", 0.1 * bend))+ record(+ "bendRadius",+ measured["bendRadius"],+ abs(measured["bendRadius"] - bend) <= tolerance,+ f"measured bend radius must be within {tolerance} of the reference-derived {bend}",+ )++ tube = expectations.get("tubeRadius")+ if tube is not None and measured["tubeRadius"]["mean"] is not None:+ tolerance = float(expectations.get("tubeRadiusTolerance", 0.2 * tube))+ record(+ "tubeRadius",+ measured["tubeRadius"]["mean"],+ abs(measured["tubeRadius"]["mean"] - tube) <= tolerance,+ f"measured mean tube radius must be within {tolerance} of the reference-derived {tube}",+ )++ residual_max = expectations.get("maxRadiusSpreadOverBendRadius")+ if residual_max is not None:+ value = measured["radiusSpreadOverBendRadius"]+ record(+ "arcResidual",+ value,+ value is not None and value <= residual_max,+ "radial spread relative to the bend radius; a sweep that is not close to a circular "+ "arc will exceed this",+ )++ return {"failures": sum(1 for check in checks if check["status"] == "fail"), "checks": checks}+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])+ parser.add_argument("--geometry", type=Path, required=True)+ parser.add_argument("--component", required=True, help="mesh id or name to analyse")+ parser.add_argument("--expect", type=Path)+ parser.add_argument("--out", type=Path)+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args(argv)++ geometry = _load_json(args.geometry, "geometry")+ meshes = geometry.get("meshes") if isinstance(geometry, dict) else geometry+ if not isinstance(meshes, list):+ raise SystemExit("geometry error: expected a list of meshes or {\"meshes\": [...]}")+ match = None+ for mesh in meshes:+ if isinstance(mesh, dict) and args.component in {mesh.get("id"), mesh.get("name")}:+ match = mesh+ break+ if match is None:+ raise SystemExit(f"geometry error: no mesh named {args.component!r}")+ positions = match.get("positions") or match.get("worldPositions")+ if not isinstance(positions, list) or len(positions) < 30 or len(positions) % 3:+ raise SystemExit(f"geometry error: mesh {args.component!r} has no usable position array")++ points = [+ (positions[index], positions[index + 1], positions[index + 2])+ for index in range(0, len(positions), 3)+ ]+ measured = analyse(points)+ report: dict[str, Any] = {"component": args.component, "measured": measured}+ exit_code = 0+ if args.expect is not None:+ expectations = _load_json(args.expect, "expectations")+ evaluation = evaluate(measured, expectations)+ report["evaluation"] = evaluation+ if evaluation["failures"]:+ exit_code = 1+ report["exitCode"] = exit_code+ if args.out:+ args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")+ if args.json or not args.out:+ print(json.dumps(report, indent=2))+ return exit_code+++if __name__ == "__main__":+ try:+ raise SystemExit(main(sys.argv[1:]))+ except SystemExit as exit_error:+ if isinstance(exit_error.code, str):+ print(exit_error.code, file=sys.stderr)+ raise SystemExit(2)+ raisediff --git a/forge/stage4_review/validate_render_profile.py b/forge/stage4_review/validate_render_profile.pyindex 1a02043..24071e3 100644--- a/forge/stage4_review/validate_render_profile.py+++ b/forge/stage4_review/validate_render_profile.py@@ -22,7 +22,6 @@ PASS_IDS = ("normal","roughness-material-id",)-REGION_IDS = ("face", "kasa", "scarf", "tunic", "staff", "tail", "feet", "materials")FEEDBACK_GROUPS = ("camera", "silhouette", "face", "clothing", "accessory", "materials", "lighting")TONE_MAPPINGS = {"NoToneMapping", "ACESFilmicToneMapping", "AgXToneMapping", "NeutralToneMapping"}@@ -124,9 +123,27 @@ def validate_profile(profile: dict[str, Any]) -> dict[str, Any]:regions = profile.get("regions")region_ids = [item.get("id") for item in regions] if isinstance(regions, list) and all(isinstance(item, dict) for item in regions) else []- missing_regions = [region for region in REGION_IDS if region not in region_ids]+ if not region_ids:+ errors.append("regions must contain at least one subject-specific semantic region")+ if any(not isinstance(region_id, str) or not region_id.strip() for region_id in region_ids):+ errors.append("every region.id must be a non-empty string")+ if len(set(region_ids)) != len(region_ids):+ errors.append("region IDs must be unique")++ extensions = profile.get("extensions")+ required_regions = extensions.get("requiredSemanticRegions") if isinstance(extensions, dict) else None+ if (+ not isinstance(required_regions, list)+ or not required_regions+ or any(not isinstance(region_id, str) or not region_id.strip() for region_id in required_regions)+ ):+ errors.append("extensions.requiredSemanticRegions must be a non-empty array of non-empty strings")+ required_regions = []+ elif len(set(required_regions)) != len(required_regions):+ errors.append("extensions.requiredSemanticRegions must contain unique IDs")+ missing_regions = [region for region in required_regions if region not in region_ids]if missing_regions:- errors.append(f"regions missing required IDs: {', '.join(missing_regions)}")+ errors.append(f"regions missing declared required IDs: {', '.join(missing_regions)}")feedback = profile.get("feedbackGroups")feedback_ids = [item.get("id") for item in feedback] if isinstance(feedback, list) and all(isinstance(item, dict) for item in feedback) else []diff --git a/forge/stage4_review/vertex_region_gate.py b/forge/stage4_review/vertex_region_gate.pynew file mode 100644index 0000000..518d01b--- /dev/null+++ b/forge/stage4_review/vertex_region_gate.py@@ -0,0 +1,456 @@+#!/usr/bin/env python3+"""Gate colour-region boundaries on executed geometry, before any browser render.++WHAT THIS IS FOR. When a subject's identity is carried by flat colour regions with hard boundaries+-- a tuxedo cat's blaze, bib and socks; a livery stripe; a painted marking -- the position of those+boundaries is an identity feature, and identity features are gated, not eyeballed. Neither existing+instrument can do it:++- `divine_eye.py` scores a 64x64 luma grid over the whole frame. A bib boundary a few pixels out+ moves a handful of cells and is lost in the global score.+- `interior_difference.py` measures inside the silhouette, but against a rendered image, so it+ cannot run until a browser has produced pixels -- and by then the spec is already built.++This gate runs on exported geometry: world positions plus the vertex colours the model will+actually be shaded with. It projects those vertices to a review azimuth, computes each colour+region's 2D bounding box normalised to the model's own projected bounding box, and compares that+against the box measured on the reference at the same azimuth. Same units on both sides, and no+renderer involved.++WHAT IT DOES NOT SEE, stated because a clean verdict here is not a clean model:++- It measures a bounding box, not a shape. A region of the right extent and the wrong outline+ passes. Shape is the visual review's job.+- It classifies a vertex by matching its colour to the declared palette. Vertices inside a soft+ boundary fringe match nothing and are reported as `unclassifiedFraction` rather than being+ silently assigned. Read that number before believing the verdict.+- Vertex density is not uniform over a mesh, so `areaFraction` here is a vertex-count fraction and+ is a weaker signal than the box. It is reported, never gated on.+- A region hidden behind another surface at this azimuth is still measured: these are vertices, not+ pixels, and there is no occlusion test.++Exit codes: 0 clean, 1 gate failure, 2 error.+"""++from __future__ import annotations++import argparse+import json+import math+import sys+from pathlib import Path+from typing import Any++DEFAULT_COLOR_TOLERANCE = 0.06+++def _load_json(path: Path, label: str) -> Any:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as error:+ raise SystemExit(f"{label} error: {error}")+++def _hex_to_rgb(value: str) -> tuple[float, float, float]:+ number = int(value.lstrip("#"), 16)+ return (((number >> 16) & 255) / 255.0, ((number >> 8) & 255) / 255.0, (number & 255) / 255.0)+++def collect_vertices(geometry: Any) -> list[dict[str, Any]]:+ """Flatten an exported geometry payload into per-mesh position/colour arrays.++ Accepts the shape `runtime/scripts/export_mesh_geometry.mjs` emits (a list of meshes, each with+ a flat `positions` array) extended with a matching flat `colors` array.+ """+ meshes = geometry.get("meshes") if isinstance(geometry, dict) else geometry+ if not isinstance(meshes, list):+ raise SystemExit("geometry error: expected a list of meshes or {\"meshes\": [...]}")+ out = []+ for index, mesh in enumerate(meshes):+ if not isinstance(mesh, dict):+ continue+ positions = mesh.get("positions") or mesh.get("worldPositions")+ colors = mesh.get("colors")+ if not isinstance(positions, list) or not positions:+ continue+ if len(positions) % 3:+ raise SystemExit(f"geometry error: mesh {index} positions length is not a multiple of 3")+ if colors is not None:+ if not isinstance(colors, list) or len(colors) != len(positions):+ raise SystemExit(+ f"geometry error: mesh {index} colors must be the same length as positions"+ )+ out.append(+ {+ "id": mesh.get("id") or mesh.get("name") or f"mesh-{index}",+ "positions": positions,+ "colors": colors,+ }+ )+ if not out:+ raise SystemExit("geometry error: no mesh carried positions")+ return out+++def project(positions: list[float], azimuth_degrees: float) -> list[tuple[float, float]]:+ """Rotate about world Y by -azimuth, then drop Z. Azimuth 0 looks along -Z at the model's front."""+ angle = math.radians(-azimuth_degrees)+ cos_a, sin_a = math.cos(angle), math.sin(angle)+ points = []+ for index in range(0, len(positions), 3):+ x, y, z = positions[index], positions[index + 1], positions[index + 2]+ points.append((x * cos_a + z * sin_a, y))+ return points+++def classify(color: tuple[float, float, float], palette: dict[str, tuple[float, float, float]],+ tolerance: float) -> str | None:+ best_id = None+ best_distance = tolerance+ for region_id, target in palette.items():+ distance = math.sqrt(+ (color[0] - target[0]) ** 2 + (color[1] - target[1]) ** 2 + (color[2] - target[2]) ** 2+ )+ if distance <= best_distance:+ best_distance = distance+ best_id = region_id+ return best_id+++def measure(+ meshes: list[dict[str, Any]],+ palette: dict[str, tuple[float, float, float]],+ azimuth: float,+ tolerance: float,+ scope: set[str] | None = None,+) -> dict[str, Any]:+ """Measure colour regions at one azimuth.++ `scope` restricts which MESHES contribute region buckets, while the model's projected bounding+ box is always computed from every mesh. Both halves of that matter: a subject can carry the+ same colour in several unrelated places — a tuxedo cat's white is its bib, its four socks and+ its muzzle at once — so colour alone cannot separate them, and the part they sit on can. And+ normalising to the whole model keeps a scoped measurement in the same coordinates as the+ reference box it is compared against, instead of in the scoped part's own frame.+ """+ all_points: list[tuple[float, float]] = []+ labelled: list[tuple[str | None, tuple[float, float]]] = []+ for mesh in meshes:+ points = project(mesh["positions"], azimuth)+ all_points.extend(points)+ if scope is not None and mesh["id"] not in scope and mesh.get("name") not in scope:+ continue+ colors = mesh["colors"]+ for index, point in enumerate(points):+ if colors is None:+ labelled.append((None, point))+ continue+ color = (colors[index * 3], colors[index * 3 + 1], colors[index * 3 + 2])+ labelled.append((classify(color, palette, tolerance), point))+ if not labelled:+ raise SystemExit(+ "geometry error: the requested mesh scope selected no vertices; check the mesh ids"+ )++ xs = [p[0] for p in all_points]+ ys = [p[1] for p in all_points]+ span_x = max(xs) - min(xs)+ span_y = max(ys) - min(ys)+ if span_x <= 0 or span_y <= 0:+ raise SystemExit("geometry error: projected model has zero extent at this azimuth")+ origin = (min(xs), min(ys))++ buckets: dict[str, list[tuple[float, float]]] = {}+ unclassified = 0+ for label, point in labelled:+ if label is None:+ unclassified += 1+ continue+ buckets.setdefault(label, []).append(point)++ regions = {}+ for region_id, points in buckets.items():+ blobs = projected_blobs(points, origin, span_x, span_y)+ rxs = [(p[0] - origin[0]) / span_x for p in points]+ # Image space runs downward while world Y runs up, so the reference's y0 is the model's+ # TOP. Flipping here keeps both sides of every comparison in reference coordinates.+ rys = [1.0 - (p[1] - origin[1]) / span_y for p in points]+ regions[region_id] = {+ "x0": round(min(rxs), 4),+ "x1": round(max(rxs), 4),+ "y0": round(min(rys), 4),+ "y1": round(max(rys), 4),+ "vertexCount": len(points),+ "areaFraction": round(len(points) / len(labelled), 5),+ "blobs": [+ {+ "vertexCount": len(members),+ "centroidX": round(+ sum((points[i][0] - origin[0]) / span_x for i in members) / len(members), 4+ ),+ "centroidY": round(+ sum(1.0 - (points[i][1] - origin[1]) / span_y for i in members)+ / len(members), 4+ ),+ "x0": round(min((points[i][0] - origin[0]) / span_x for i in members), 4),+ "x1": round(max((points[i][0] - origin[0]) / span_x for i in members), 4),+ "y0": round(min(1.0 - (points[i][1] - origin[1]) / span_y for i in members), 4),+ "y1": round(max(1.0 - (points[i][1] - origin[1]) / span_y for i in members), 4),+ }+ for members in blobs+ ],+ }+ return {+ "azimuth": azimuth,+ "projectedExtent": {"width": span_x, "height": span_y},+ "sampledVertexCount": len(labelled),+ "unclassifiedFraction": round(unclassified / len(labelled), 5) if labelled else 1.0,+ "regions": regions,+ }+++# The clustering grid is derived from the point count, not fixed.+#+# A fixed fine grid does not cluster: neighbouring vertices land in non-adjacent cells and every+# vertex becomes its own blob — a 288-point fixture split into 24. A fixed coarse grid merges+# regions that are genuinely apart. Sizing it as sqrt(count)/2 keeps roughly a handful of vertices+# per occupied cell at any mesh density, which is what connectivity needs.+MIN_BLOB_GRID = 6+MAX_BLOB_GRID = 96+++def projected_blobs(points: list[tuple[float, float]], origin, span_x, span_y):+ """Split a region's projected points into connected blobs, largest first.++ WHY. The reference side of every comparison is a connected blob found in the image; once the+ model's parts are FUSED into one mesh, colour alone cannot tell the model's equivalent blobs+ apart. A tuxedo cat's white is its bib, its four socks and its muzzle at once, all one colour+ on one mesh, so the measured "sock" box ran from the muzzle to the ground and the comparison+ was meaningless. Clustering the projection puts both sides on the same instrument.++ The grid is coarse on purpose: it is a connectivity test, not a shape measurement, and the box+ is still computed from the real point coordinates rather than from grid cells.+ """+ if not points:+ return []+ grid = max(MIN_BLOB_GRID, min(MAX_BLOB_GRID, int(len(points) ** 0.5 / 2)))+ cells: dict[tuple[int, int], list[int]] = {}+ for index, (x, y) in enumerate(points):+ column = min(grid - 1, max(0, int((x - origin[0]) / span_x * grid)))+ row = min(grid - 1, max(0, int((y - origin[1]) / span_y * grid)))+ cells.setdefault((column, row), []).append(index)++ seen: set[tuple[int, int]] = set()+ blobs = []+ for start in cells:+ if start in seen:+ continue+ stack = [start]+ seen.add(start)+ members: list[int] = []+ while stack:+ cell = stack.pop()+ members.extend(cells[cell])+ for step in ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)):+ neighbour = (cell[0] + step[0], cell[1] + step[1])+ if neighbour in cells and neighbour not in seen:+ seen.add(neighbour)+ stack.append(neighbour)+ blobs.append(members)+ blobs.sort(key=len, reverse=True)+ return blobs+++def union_box(regions: dict[str, Any], ids: list[str]) -> dict[str, float] | None:+ present = [regions[region_id] for region_id in ids if region_id in regions]+ if not present:+ return None+ return {+ "x0": min(box["x0"] for box in present),+ "x1": max(box["x1"] for box in present),+ "y0": min(box["y0"] for box in present),+ "y1": max(box["y1"] for box in present),+ }+++def evaluate(measured: dict[str, Any], expectations: list[dict[str, Any]]) -> dict[str, Any]:+ """Evaluate expectations against a per-expectation measurement.++ `measured` may be a single measurement (every expectation reads the same regions) or a mapping+ of expectation id to measurement, which is what a scoped run produces.+ """+ results = []+ failures = 0+ for expectation in expectations:+ ids = expectation.get("regions") or [expectation["id"]]+ tolerance = float(expectation.get("tolerance", 0.04))+ expected = expectation["expected"]+ source = measured.get("byExpectation", {}).get(expectation["id"], measured)+ wanted = expectation.get("blobs")+ spatial = expectation.get("blobFilter")+ if spatial is not None:+ # Selection by a DECLARED spatial fact, not by area rank.+ #+ # Rank is not stable between the two sides: on the reference the bib is the largest+ # white blob, but once the model's legs and paws are fused the four socks merge into+ # one band that is larger still, so rank 0 means the bib on one side and the socks on+ # the other. Measured: every sock comparison was off by -0.45 in y0 and every bib+ # comparison by +0.56 or more, all in the same direction — the signature of a swapped+ # correspondence rather than a misplaced boundary.+ #+ # "the socks are the white below the belly line" is a fact about the subject, stated+ # once, and it is independent of the box being tested — so using it to pick the blob+ # does not make the comparison circular.+ kept = []+ for region_id in ids:+ for blob in source["regions"].get(region_id, {}).get("blobs", []):+ low = spatial.get("centroidYMin", 0.0)+ high = spatial.get("centroidYMax", 1.0)+ if low <= blob["centroidY"] <= high:+ kept.append(blob)+ if not kept:+ results.append({+ "id": expectation["id"], "status": "missing",+ "detail": f"no blob of {ids} has its centroid in {spatial}",+ "availableCentroids": [+ blob["centroidY"]+ for region_id in ids+ for blob in source["regions"].get(region_id, {}).get("blobs", [])+ ],+ })+ failures += 1+ continue+ actual = {+ "x0": min(box["x0"] for box in kept), "x1": max(box["x1"] for box in kept),+ "y0": min(box["y0"] for box in kept), "y1": max(box["y1"] for box in kept),+ }+ elif wanted is None:+ actual = union_box(source["regions"], ids)+ else:+ # Blob selection mirrors how the reference blob was isolated: by connectivity, then by+ # size rank. Naming a blob that does not exist is a failure, not a silent fallback to+ # the whole region.+ boxes = []+ missing = []+ for region_id in ids:+ blobs = source["regions"].get(region_id, {}).get("blobs", [])+ for rank in wanted:+ if rank < len(blobs):+ boxes.append(blobs[rank])+ else:+ missing.append(f"{region_id}[{rank}]")+ if missing or not boxes:+ results.append({+ "id": expectation["id"], "status": "missing",+ "detail": f"requested blobs not present: {missing or ids}",+ "availableBlobCounts": {+ region_id: len(source["regions"].get(region_id, {}).get("blobs", []))+ for region_id in ids+ },+ })+ failures += 1+ continue+ actual = {+ "x0": min(box["x0"] for box in boxes), "x1": max(box["x1"] for box in boxes),+ "y0": min(box["y0"] for box in boxes), "y1": max(box["y1"] for box in boxes),+ }+ if actual is None:+ results.append(+ {+ "id": expectation["id"],+ "status": "missing",+ "detail": f"no vertex carried any of the colours for {ids}",+ }+ )+ failures += 1+ continue+ deltas = {edge: round(actual[edge] - expected[edge], 4) for edge in ("x0", "x1", "y0", "y1")}+ worst = max(abs(value) for value in deltas.values())+ status = "pass" if worst <= tolerance else "fail"+ if status == "fail":+ failures += 1+ results.append(+ {+ "id": expectation["id"],+ "status": status,+ "regions": ids,+ "expected": expected,+ "actual": {edge: round(actual[edge], 4) for edge in ("x0", "x1", "y0", "y1")},+ "deltas": deltas,+ "worstDelta": round(worst, 4),+ "tolerance": tolerance,+ }+ )+ return {"failures": failures, "results": results}+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])+ parser.add_argument("--geometry", type=Path, required=True, help="exported mesh geometry JSON")+ parser.add_argument("--palette", type=Path, required=True,+ help="{regionId: '#rrggbb'} for every region to measure")+ parser.add_argument("--expect", type=Path,+ help="expectation list; without it the gate only reports measurements")+ parser.add_argument("--azimuth", type=float, default=0.0,+ help="review azimuth in degrees; 0 looks at the model's front")+ parser.add_argument("--color-tolerance", type=float, default=DEFAULT_COLOR_TOLERANCE)+ parser.add_argument("--max-unclassified", type=float, default=0.25,+ help="fail if more than this fraction of vertices match no palette colour")+ parser.add_argument("--out", type=Path)+ parser.add_argument("--json", action="store_true")+ args = parser.parse_args(argv)++ geometry = _load_json(args.geometry, "geometry")+ palette_raw = _load_json(args.palette, "palette")+ if not isinstance(palette_raw, dict) or not palette_raw:+ raise SystemExit("palette error: expected a non-empty {regionId: '#rrggbb'} object")+ palette = {key: _hex_to_rgb(value) for key, value in palette_raw.items()}++ meshes = collect_vertices(geometry)+ measured = measure(meshes, palette, args.azimuth, args.color_tolerance)++ report: dict[str, Any] = {"measured": measured, "palette": palette_raw}+ exit_code = 0+ if measured["unclassifiedFraction"] > args.max_unclassified:+ report["unclassifiedVerdict"] = (+ f"{measured['unclassifiedFraction']:.3f} of vertices matched no palette colour, above "+ f"the {args.max_unclassified} limit — the measurement below covers less of the model "+ "than it appears to"+ )+ exit_code = 1++ if args.expect is not None:+ expectations = _load_json(args.expect, "expectations")+ if not isinstance(expectations, list):+ raise SystemExit("expectations error: expected a list")+ # An expectation may name the meshes it applies to. Each such expectation gets its own+ # scoped measurement, so a white bib is never accidentally satisfied by a white sock.+ by_expectation: dict[str, Any] = {}+ for expectation in expectations:+ scope = expectation.get("meshes")+ if isinstance(scope, list) and scope:+ by_expectation[expectation["id"]] = measure(+ meshes, palette, args.azimuth, args.color_tolerance, scope=set(scope)+ )+ measured["byExpectation"] = by_expectation+ evaluation = evaluate(measured, expectations)+ report["evaluation"] = evaluation+ if evaluation["failures"]:+ exit_code = 1++ report["exitCode"] = exit_code+ if args.out:+ args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")+ if args.json or not args.out:+ print(json.dumps(report, indent=2))+ return exit_code+++if __name__ == "__main__":+ try:+ raise SystemExit(main(sys.argv[1:]))+ except SystemExit as exit_error:+ if isinstance(exit_error.code, str):+ print(exit_error.code, file=sys.stderr)+ raise SystemExit(2)+ raisediff --git a/forge/stage5_rig/geodesic_skinning.py b/forge/stage5_rig/geodesic_skinning.pyindex 70876a6..29ee90e 100644--- a/forge/stage5_rig/geodesic_skinning.py+++ b/forge/stage5_rig/geodesic_skinning.py@@ -44,6 +44,27 @@ MAX_INFLUENCES = 4DEFAULT_FALLOFF_POWER = 3.0UNREACHABLE = float("inf")+# Roles that must be rigidly parented to a joint rather than smooth-skinned to the skeleton.+#+# WHY HAIR IS FIRST ON THIS LIST. The geodesic field measures distance THROUGH THE SOLID, which is+# exactly right for a limb and exactly wrong for hair. Hair sits ON the skull, so the path from the+# neck joint to a crown vertex runs up through the head and arrives short -- the crown then takes a+# real share of neck weight, and turning the neck DEFORMS the hair, shearing it against the very+# skull it is supposed to sit on.+#+# The deformation also voids the one guarantee the hair pipeline has. `standProud` and the+# `scalpExposure` gate are build-time geometric checks against the bind pose; smooth-skin the hair+# and every other pose is unverified, so the model can go bald when the head turns with no gate able+# to see it. Rigid parenting keeps hair and skull on a single shared transform, which makes the+# relation between them invariant under every pose.+#+# It is also simply more correct. Short hair on a skull genuinely does move rigidly with it; smooth+# skinning would introduce a deformation that does not exist in the subject.+#+# Long hair that crosses a joint is the real exception, and it is served by a short chain of bones+# with one mesh segment rigidly parented per bone -- still no blended vertex weights.+RIGID_ROLES = frozenset({"hair", "detail", "decal", "panel"})+# 26-connectivity with true step lengths: a face step is 1 voxel, an edge step sqrt(2), a corner# sqrt(3). Using 6-connectivity instead makes every distance a Manhattan distance, which biases# weights along the grid axes and shows up as boxy falloff on a diagonal limb.@@ -193,12 +214,84 @@ def geodesic_field(grid: VoxelGrid, sources: set[tuple[int, int, int]]) -> dict[return distance+def partition_for_binding(+ components: list[dict[str, Any]],+ rigid_roles: frozenset[str] = RIGID_ROLES,+) -> dict[str, Any]:+ """Split a component tree into what may be smooth-skinned and what must be rigidly parented.++ `bind()` weights every vertex of whatever mesh it is handed, with no notion of role. That is the+ correct contract for a distance solver and the wrong default for a character: hand it a merged+ mesh containing hair and it will skin the hair, because nothing told it not to. This is the+ thing that tells it not to.++ Rigid components are REPORTED, never silently dropped. Each carries the joint it rides, resolved+ by walking up the parent chain to the first ancestor that is itself skinned -- a lock parented to+ a hair mass parented to the head rides the head, not the mass.+ """+ by_id = {+ str(component.get("id")): component+ for component in components+ if isinstance(component, dict) and component.get("id")+ }++ def is_rigid(component: dict[str, Any]) -> bool:+ return str(component.get("role") or "").lower() in rigid_roles++ def ride(component: dict[str, Any]) -> str | None:+ """First ancestor that is skinned, so the rigid piece has a joint to hang from."""+ seen: set[str] = set()+ parent_id = component.get("parent")+ while isinstance(parent_id, str) and parent_id in by_id and parent_id not in seen:+ seen.add(parent_id)+ parent = by_id[parent_id]+ if not is_rigid(parent):+ return parent_id+ parent_id = parent.get("parent")+ return None++ skinned: list[str] = []+ rigid: list[dict[str, Any]] = []+ warnings: list[str] = []+ for component in components:+ if not isinstance(component, dict) or not component.get("id"):+ continue+ component_id = str(component["id"])+ if not is_rigid(component):+ skinned.append(component_id)+ continue+ joint = ride(component)+ if joint is None:+ warnings.append(+ f"component {component_id!r} has rigid role "+ f"{str(component.get('role') or '')!r} but no skinned ancestor to parent to; "+ f"it would be left unattached to the skeleton"+ )+ rigid.append({"id": component_id, "role": component.get("role"), "parentJoint": joint})++ return {+ "schemaVersion": 1,+ "kind": "binding-partition",+ "skinned": skinned,+ "rigidlyParented": rigid,+ "rigidRoles": sorted(rigid_roles),+ "warnings": warnings,+ "note": (+ "Rigid components are parented to a joint and inherit its transform exactly. They are "+ "excluded from geodesic binding because the field measures distance through the solid, "+ "so a crown vertex would take neck weight through the skull and shear against it."+ ),+ }++def bind(mesh: dict[str, Any],bones: list[dict[str, Any]],resolution: int = DEFAULT_RESOLUTION,falloff_power: float = DEFAULT_FALLOFF_POWER,max_influences: int = MAX_INFLUENCES,+ components: list[dict[str, Any]] | None = None,+ rigid_roles: frozenset[str] = RIGID_ROLES,) -> dict[str, Any]:"""Compute skin indices and weights for every vertex.@@ -206,6 +299,14 @@ def bind(distance, the top `max_influences` are kept and normalised, and a vertex no bone can reach throughthe solid is reported rather than quietly pinned to the nearest bone in space -- being unreachableusually means the mesh has a hole or a detached island, and that is worth knowing.++ Pass `components` -- the component tree the mesh was built from -- and the result carries a+ `bindingPartition` naming everything that must be rigidly parented instead of skinned, plus a+ warning if any of it looks like it reached the mesh anyway. Without it the caller gets weights+ for every vertex handed in and no signal at all that some of them should not have been, which is+ the failure mode this whole rule exists to prevent: the geodesic path from the neck to a crown+ vertex runs UP THROUGH THE SKULL, so hair takes real neck weight (8.1% on the test fixture) and+ shears against the skull it sits on."""vertices = mesh.get("vertices")indices = mesh.get("indices")@@ -261,9 +362,55 @@ def bind(skin_indices.append(row_indices)skin_weights.append(row_weights)+ partition = partition_for_binding(components, rigid_roles) if components is not None else None+ partition_warnings: list[str] = []+ rigid_pinned = 0+ if partition and partition["rigidlyParented"]:+ partition_warnings.append(+ f"{len(partition['rigidlyParented'])} component(s) carry a rigid role "+ f"({', '.join(sorted(rigid_roles))}) and are parented to a joint rather than skinned."+ )++ # EXCLUSION, not just a note. Reporting the partition and then handing back geodesic weights+ # for those vertices anyway leaves the caller holding exactly the wrong numbers -- and the+ # obvious thing to do with a returned weight array is to use it. A rigidly parented vertex+ # gets weight 1.0 on the single joint it rides and nothing else, which IS rigid parenting+ # written in the only language a skinned mesh speaks.+ #+ # This needs to know which vertex belongs to which component, so the mesh must carry+ # `vertexComponents`, a component id per vertex. Without it the exclusion cannot be applied+ # and that is said out loud rather than silently skipped.+ rides = {entry["id"]: entry["parentJoint"] for entry in partition["rigidlyParented"]}+ owners = mesh.get("vertexComponents")+ if not isinstance(owners, list) or len(owners) != len(vertices):+ partition_warnings.append(+ "mesh has no `vertexComponents` (one component id per vertex), so the rigid "+ "components above could NOT be excluded from these weights. Supply it, or bind "+ "only the skinned components' geometry."+ )+ else:+ bone_slot = {str(bone.get("id")): index for index, bone in enumerate(bones)}+ for index, owner in enumerate(owners):+ joint = rides.get(str(owner))+ if joint is None:+ continue+ slot = bone_slot.get(str(joint))+ if slot is None:+ partition_warnings.append(+ f"component {owner!r} rides joint {joint!r}, which is not among the bones "+ f"supplied; its vertices keep their geodesic weights"+ )+ continue+ skin_indices[index] = [slot] + [0] * (max_influences - 1)+ skin_weights[index] = [1.0] + [0.0] * (max_influences - 1)+ rigid_pinned += 1+return {"skinIndices": skin_indices,"skinWeights": skin_weights,+ "bindingPartition": partition,+ "partitionWarnings": partition_warnings + (partition["warnings"] if partition else []),+ "rigidPinnedVertexCount": rigid_pinned,"boneOrder": [str(bone.get("id")) for bone in bones],"resolution": resolution,"voxelStep": grid.step,diff --git a/forge/tests/fixtures/stand_proud_hair_on_head.json b/forge/tests/fixtures/stand_proud_hair_on_head.jsonnew file mode 100644index 0000000..d02bda6--- /dev/null+++ b/forge/tests/fixtures/stand_proud_hair_on_head.json@@ -0,0 +1,81 @@+{+ "targetName": "StandProudHead",+ "schemaVersion": "2.1",+ "suitability": "pass",+ "coordinateFrame": {"up": "y", "forward": "z", "handedness": "right"},+ "silhouette": {"summary": "A head with hair masses held clear of the skull."},+ "proceduralStrategy": ["skull as a ring stack", "hair as masses that must stand proud of it"],+ "materials": [+ {"id": "skin", "color": "#c9a08a"},+ {"id": "hair", "color": "#2b2118"}+ ],+ "componentTree": [+ {+ "id": "head",+ "name": "Head",+ "primitive": "lathe",+ "material": "skin",+ "role": "head",+ "level": "macro",+ "topologyClass": "assembled-solid",+ "topologyRationale": "a closed skull volume the hair sits on",+ "dimensions": {"width": 0.4, "height": 0.5, "depth": 0.42},+ "geometryDescriptor": {+ "ringStack": {+ "_note": "A lathe is a REVOLVE, so it is circular before geometry.scale: rx must equal rz here, and the ellipticity comes from dimensions (width 0.4, depth 0.42). Authoring rx != rz double-counts it -- the first version of this fixture had rz 10-33% wider than the geometry it claimed to describe.",+ "rings": [+ [-0.25, 0.12, 0.12],+ [-0.10, 0.19, 0.19],+ [0.00, 0.20, 0.20],+ [0.12, 0.19, 0.19],+ [0.25, 0.15, 0.15]+ ],+ "zOffsets": [0.01, 0.03, 0.02, 0.00, -0.02]+ },+ "latheProfile": {+ "points": [[0.12, -0.25], [0.19, -0.10], [0.20, 0.0], [0.19, 0.12], [0.15, 0.25]],+ "segments": 16+ }+ }+ },+ {+ "id": "hair-crown",+ "name": "Hair crown",+ "primitive": "tapered-sweep",+ "material": "hair",+ "role": "hair",+ "parent": "head",+ "level": "meso",+ "topologyClass": "assembled-solid",+ "topologyRationale": "a solid mass of hair over the top of the skull",+ "dimensions": {"width": 0.42, "height": 0.22, "depth": 0.44},+ "standProud": {"againstComponentId": "head", "clearance": 0.012, "maxPush": 0.04},+ "rootTipGradient": {"rootColor": "#1a1310", "tipColor": "#4a3a2c", "axis": "y"},+ "geometryDescriptor": {+ "taperedSweep": {+ "stations": [+ {"position": [0.0, -0.18, -0.16], "rx": 0.16, "rz": 0.12},+ {"position": [0.0, 0.02, -0.02], "rx": 0.19, "rz": 0.15},+ {"position": [0.0, 0.16, 0.14], "rx": 0.10, "rz": 0.08},+ {"position": [0.0, 0.22, 0.24], "rx": 0.0, "rz": 0.0}+ ],+ "radialSegments": 10+ }+ }+ },+ {+ "id": "hair-temple-l",+ "name": "Hair temple L",+ "primitive": "ellipsoid",+ "material": "hair",+ "role": "hair",+ "parent": "head",+ "level": "meso",+ "topologyClass": "assembled-solid",+ "topologyRationale": "a side mass that must not sink into the skull",+ "dimensions": {"width": 0.10, "height": 0.20, "depth": 0.22},+ "transform": {"position": [0.17, 0.0, 0.0]},+ "standProud": {"againstComponentId": "head", "clearance": 0.010, "maxPush": 0.035}+ }+ ]+}diff --git a/forge/tests/test_albedo_color_space.py b/forge/tests/test_albedo_color_space.pynew file mode 100644index 0000000..6727189--- /dev/null+++ b/forge/tests/test_albedo_color_space.py@@ -0,0 +1,111 @@+from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "forge" / "_shared"))+sys.path.insert(0, str(ROOT / "forge" / "stage2_spec"))+sys.path.insert(0, str(ROOT / "forge" / "stage3_build"))++import generate_threejs_factory as generator # noqa: E402+++def spec(base_color: str) -> dict:+ return {+ "targetName": "Albedo",+ "targetId": "albedo",+ "schemaVersion": "2.1",+ "suitability": "pass",+ "coordinateFrame": {"front": "+Z", "up": "+Y", "scaleReference": "unit"},+ "silhouette": {"boundingShape": "test", "symmetry": "bilateral"},+ "proceduralStrategy": ["blockout"],+ "materials": [{+ "id": "vinyl",+ "name": "Vinyl",+ "baseColor": base_color,+ "roughness": {"base": 0.52},+ "metalness": {"base": 0.0},+ "textureless": {"declared": True, "evidence": ["no texture in the reference"]},+ }],+ "buildPasses": [{"id": "blockout", "acceptance": []}],+ "componentTree": [{+ "id": "body",+ "name": "Body",+ "level": "macro",+ "role": "body",+ "primitive": "ellipsoid",+ "topologyClass": "continuous-sculpt",+ "topologyRationale": "test",+ "parent": None,+ "material": "vinyl",+ "dimensions": {"width": 1.0, "height": 1.0, "depth": 1.0, "units": "relative"},+ "transform": {"position": [0, 0.5, 0], "rotation": [0, 0, 0]},+ }],+ }+++class AlbedoColorSpace(unittest.TestCase):+ """An authored `baseColor` hex is sRGB and must be read as sRGB.++ `new THREE.Color(r, g, b)` treats its arguments as LINEAR components. Feeding sRGB channel+ values to it skips the transfer function, and the error is largest near black because that is+ where the curve is steepest — which is exactly where a dark subject lives.+ """++ def test_the_emitted_helper_names_the_colour_space(self):+ source = generator.generate(spec("#2e2a28"), "blockout")+ self.assertIn("setStyle(source, THREE.SRGBColorSpace)", source)+ self.assertNotIn("new THREE.Color(red / 255, green / 255, blue / 255)", source)++ def test_a_dark_albedo_survives_the_round_trip_at_the_right_value(self):+ """Executed, not grepped: the emitted expression is evaluated and compared to sRGB→linear.++ A near-black vinyl authored at #2e2a28 is sRGB 0.180; its linear value is about 0.0273.+ Reading it as linear instead would leave 0.180 in the working space and render it at+ roughly sRGB 0.46 — a mid grey where the reference has near-black.+ """+ node = shutil.which("node")+ if node is None:+ self.fail("node is required to evaluate the emitted colour conversion")+ harness = """+ import * as THREE from 'three';+ const wrong = new THREE.Color(0x2e / 255, 0x2a / 255, 0x28 / 255);+ const right = new THREE.Color().setStyle('#2e2a28', THREE.SRGBColorSpace);+ console.log(JSON.stringify({+ wrong: [wrong.r, wrong.g, wrong.b],+ right: [right.r, right.g, right.b],+ }));+ """+ showcase = ROOT.parent / "img2threejs-showcase"+ if not (showcase / "node_modules" / "three").is_dir():+ self.skipTest(+ "three is not installed at "+ f"{showcase / 'node_modules' / 'three'}; the numeric half of this check needs it. "+ "The emitted-source assertion above still runs."+ )+ work = showcase / "node_modules" / ".cache" / "albedo-color-space"+ work.mkdir(parents=True, exist_ok=True)+ script = work / "check.mjs"+ script.write_text(harness, encoding="utf-8")+ result = subprocess.run([node, str(script)], capture_output=True, text=True)+ script.unlink(missing_ok=True)+ self.assertEqual(result.returncode, 0, result.stderr)+ values = json.loads(result.stdout)+ # sRGB 0.1804 -> linear 0.0273. The two readings differ by more than 6x.+ self.assertAlmostEqual(values["right"][0], 0.0273, places=3)+ self.assertAlmostEqual(values["wrong"][0], 0.1804, places=3)+ self.assertGreater(values["wrong"][0] / values["right"][0], 6.0)++ def test_a_mid_grey_is_also_affected_so_this_is_not_a_black_only_quirk(self):+ source = generator.generate(spec("#808080"), "blockout")+ self.assertIn("setStyle(source, THREE.SRGBColorSpace)", source)+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_attachment_does_not_override_primitive.py b/forge/tests/test_attachment_does_not_override_primitive.pynew file mode 100644index 0000000..38eb808--- /dev/null+++ b/forge/tests/test_attachment_does_not_override_primitive.py@@ -0,0 +1,156 @@+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "forge" / "_shared"))+sys.path.insert(0, str(ROOT / "forge" / "stage2_spec"))+sys.path.insert(0, str(ROOT / "forge" / "stage3_build"))++import generate_threejs_factory as generator # noqa: E402+++def spec_with(primitive: str, topology: str) -> dict:+ """One child part that declares BOTH a primitive and an attachment contract.++ This is the ordinary case, not an exotic one: the structural pass requires an attachment on+ every child appendage, so any head, ear, limb or tail that is not itself a cylinder arrives+ here.+ """+ return {+ "targetName": "Attachment Primitive",+ "targetId": "attachment-primitive",+ "schemaVersion": "2.1",+ "materials": [{"id": "base", "name": "Base", "baseColor": "#808080"}],+ "buildPasses": [{"id": "blockout", "acceptance": []}],+ "suitability": "pass",+ "coordinateFrame": {"front": "+Z", "up": "+Y", "scaleReference": "unit"},+ "silhouette": {"boundingShape": "test", "symmetry": "bilateral"},+ "proceduralStrategy": ["blockout"],+ "componentTree": [+ {+ "id": "body",+ "name": "Body",+ "level": "macro",+ "role": "body",+ "primitive": "ellipsoid",+ "topologyClass": "continuous-sculpt",+ "topologyRationale": "test",+ "parent": None,+ "material": "base",+ "dimensions": {"width": 1.0, "height": 0.6, "depth": 1.4, "units": "relative"},+ "transform": {"position": [0, 0.5, 0], "rotation": [0, 0, 0]},+ },+ {+ "id": "part",+ "name": "Part",+ "level": "macro",+ "role": "head",+ "primitive": primitive,+ "topologyClass": topology,+ "topologyRationale": "test",+ "parent": "body",+ "material": "base",+ "dimensions": {"width": 0.9, "height": 0.7, "depth": 0.8, "units": "relative"},+ "transform": {"position": [0, 0.4, 0.6], "rotation": [0, 0, 0]},+ "attachment": {+ "parentSocket": "neck",+ "localStart": [0.0, -0.35, -0.4],+ "localEnd": [0.0, 0.35, 0.4],+ "contactType": "embed",+ "embedDepth": 0.2,+ "gapTolerance": 0.004,+ "confidence": 0.9,+ },+ },+ ],+ }+++class AttachmentDoesNotOverridePrimitive(unittest.TestCase):+ def _emit(self, primitive: str, topology: str) -> str:+ return generator.generate(spec_with(primitive, topology), "blockout")++ def test_an_ellipsoid_with_an_attachment_does_not_take_the_endpoint_geometry_path(self):+ """The endpoint binding is what selects the geometry, so that is what is asserted.++ The emitted geometry line is a ternary carrying both branches, so grepping for+ `CylinderGeometry` proves nothing either way — what decides which branch runs is whether+ the endpoint is null. For a non-attachment primitive it is statically null.+ """+ source = self._emit("ellipsoid", "continuous-sculpt")+ self.assertIn("const endpoint_part_1 = makeAttachmentEndpoint(null);", source)+ self.assertNotIn("const endpoint_part_1 = makeAttachmentEndpoint(attachment_part_1);",+ source)+ self.assertIn("SphereGeometry", source)++ def test_a_tapered_sweep_with_an_attachment_keeps_its_swept_geometry(self):+ source = self._emit("tapered-sweep", "continuous-sculpt")+ self.assertIn("const endpoint_part_1 = makeAttachmentEndpoint(null);", source)+ self.assertIn("buildTaperedSweepGeometry", source)++ def test_a_cylinder_with_an_attachment_still_derives_geometry_from_its_endpoints(self):+ """Negative control: the endpoint path is not removed, only scoped.++ A cylinder, cone, capsule, tube or curve-sweep IS an attachment shape, and deriving its+ radius and length from the measured endpoints is the whole point of the contract.+ """+ source = self._emit("cylinder", "assembled-solid")+ self.assertIn("const endpoint_part_1 = makeAttachmentEndpoint(attachment_part_1);", source)++ def test_every_attachment_primitive_still_takes_the_endpoint_path(self):+ for primitive, topology in (("cylinder", "assembled-solid"), ("cone", "assembled-solid"),+ ("capsule", "assembled-solid"), ("tube", "continuous-sculpt"),+ ("curve-sweep", "continuous-sculpt")):+ with self.subTest(primitive=primitive):+ source = self._emit(primitive, topology)+ self.assertIn(+ "const endpoint_part_1 = makeAttachmentEndpoint(attachment_part_1);", source+ )++ def test_an_implicit_component_is_placed_by_its_transform_not_its_attachment(self):+ """An implicit part must still declare a `primitive`, and the fixture's is `capsule`.++ That put it in ATTACHMENT_PRIMITIVES, so a head authored at y 0.705 was emitted at its+ attachment's localStart — y -0.195, inside the body — and the model rendered with no head.+ """+ spec = spec_with("capsule", "implicit")+ part = spec["componentTree"][1]+ part["geometryDescriptor"] = {"sdf": {+ "primitives": [{"id": "ball", "type": "sphere", "radius": 0.3,+ "transform": {"position": [0, 0, 0]}}],+ "operations": [],+ "resolution": 16,+ "bounds": {"min": [-0.5, -0.5, -0.5], "max": [0.5, 0.5, 0.5]},+ }}+ source = generator.generate(spec, "blockout")+ self.assertIn("polygonizeSdf", source)+ self.assertIn("const endpoint_part_1 = makeAttachmentEndpoint(null);", source)+ self.assertIn("node_part_1.position.set(0.0, 0.4, 0.6);", source)++ def test_a_non_attachment_primitive_still_carries_its_attachment_contract(self):+ """The contract survives; only the geometry override goes.++ It ships on `userData.sculptComponent`, which is what `attachment_anchor.py` reads. The+ local `const attachment_*` binding is emitted only where the endpoint path consumes it,+ because an unused local would not survive the project's typecheck.+ """+ source = self._emit("ellipsoid", "continuous-sculpt")+ self.assertIn('"parentSocket": "neck"', source)+ self.assertIn('"contactType": "embed"', source)+ self.assertIn('"gapTolerance": 0.004', source)++ def test_the_part_keeps_its_authored_dimensions(self):+ """An endpoint-derived part is not re-scaled; an authored one must be.++ The scale call is guarded by `if (!endpoint)`, so this is the other half of the same fact:+ with the endpoint statically null the authored dimensions reach the vertex data.+ """+ source = self._emit("ellipsoid", "continuous-sculpt")+ self.assertIn("mesh_part_1Geometry.scale(0.9, 0.7, 0.8);", source)+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_chirality.py b/forge/tests/test_chirality.pynew file mode 100644index 0000000..3a85af2--- /dev/null+++ b/forge/tests/test_chirality.py@@ -0,0 +1,304 @@+#!/usr/bin/env python3+"""Left and right: the two ways it went wrong, and the two different tests that catch them.++Both defects below shipped in the same figure and no gate saw either, because both produce geometry+that is internally tidy and only wrong against a convention that lived in a comment. They are+reproduced here from their measured values, so the gates are validated against real failures rather+than against invented ones.++ THE HAND Built as `[side*along, height, side*across]` -- x AND z negated. Two negations is a+ 180-degree ROTATION about Y, not a reflection, and a rotation preserves handedness,+ so the left hand was the right hand turned around. Caught by `check_pair`.+ After the fix the hand region moved 46.0% closer to the reference in the front view.++ THE FOOT A correct reflection, so `check_pair` PASSES it -- and it was still wrong. The toes+ were ordered little-to-big across a strip whose index 0 is medial, so the big toe+ went lateral on BOTH feet. Caught only by `medial_lateral_bias` against a reference.+ Measured toe-band mass: reference 529 medial / 488 lateral, ours 350 / 443.++Run: python3 forge/tests/test_chirality.py+"""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage2_spec"))++from chirality import ( # noqa: E402+ CHARACTER_LEFT_SIGN,+ check_pair,+ classify_relation,+ compare_bias,+ find_pairs,+ medial_lateral_bias,+ mirror_point,+ mirror_vector,+ pair_stem,+ sagittal_symmetry_error,+ side_of,+)+import validate_sculpt_spec # noqa: E402+++class TheConvention(unittest.TestCase):+ def test_the_characters_left_is_plus_x(self) -> None:+ """Derived, not chosen: with forward +Z and a right-handed frame, the camera that sees the+ front looks along -Z and its right is +X, so a figure facing it has its own left there."""+ self.assertEqual(CHARACTER_LEFT_SIGN, 1)++ def test_a_mirror_negates_the_lateral_axis_and_nothing_else(self) -> None:+ self.assertEqual(mirror_point((2.8, 4.643, 0.288)), (-2.8, 4.643, 0.288))++ def test_a_direction_mirrors_by_the_same_rule(self) -> None:+ """The reflex is to think a direction transforms differently. Reaching for a rotation here+ is exactly the recorded bug."""+ self.assertEqual(mirror_vector((0.72, 0.0, -0.69)), (-0.72, 0.0, -0.69))++ def test_a_malformed_point_is_rejected(self) -> None:+ for bad in ((1.0, 2.0), (1.0, 2.0, 3.0, 4.0), ()):+ with self.subTest(bad=bad):+ with self.assertRaises(ValueError):+ mirror_point(bad)+++class NamingPairs(unittest.TestCase):+ def test_sides_are_read_off_the_suffix(self) -> None:+ self.assertEqual(side_of("hand-l"), "l")+ self.assertEqual(side_of("foot-r"), "r")+ self.assertIsNone(side_of("torso"))++ def test_a_stem_survives_internal_hyphens(self) -> None:+ self.assertEqual(pair_stem("hair-temple-l"), "hair-temple")++ def test_only_complete_pairs_are_returned(self) -> None:+ pairs = find_pairs(["hand-l", "hand-r", "foot-l", "torso", "tail-r"])+ self.assertEqual(pairs, [("hand-r", "hand-l")])++ def test_the_right_half_comes_first(self) -> None:+ """The convention is stated as 'the left is the mirror of the right'."""+ self.assertEqual(find_pairs(["eye-l", "eye-r"]), [("eye-r", "eye-l")])+++class TheHandDefect(unittest.TestCase):+ """Reproduced from the measured thumb positions."""++ RIGHT_THUMB_TIP = (2.800, 4.643, 0.288)+ LEFT_AS_BUILT = (-2.800, 4.643, -0.288) # side applied to x AND z+ LEFT_CORRECT = (-2.800, 4.643, 0.288) # sagittal mirror++ def test_the_defect_is_named_a_rotation_not_just_a_mismatch(self) -> None:+ """The two are trivially confused, agree exactly on any symmetric part, and differ only in+ handedness. Saying 'mismatch' would leave the reader to rediscover that."""+ self.assertEqual(classify_relation(self.RIGHT_THUMB_TIP, self.LEFT_AS_BUILT), "rotation")++ def test_the_defect_fails_the_pair_check(self) -> None:+ ok, message = check_pair("thumb", self.RIGHT_THUMB_TIP, self.LEFT_AS_BUILT)+ self.assertFalse(ok)+ self.assertIn("ROTATED", message)+ self.assertIn("preserves handedness", message)+ self.assertIn("same hand", message)++ def test_the_fixed_pair_passes(self) -> None:+ ok, message = check_pair("thumb", self.RIGHT_THUMB_TIP, self.LEFT_CORRECT)+ self.assertTrue(ok, message)++ def test_a_part_on_the_midline_hides_the_defect(self) -> None:+ """Why nothing caught it for so long: at z = 0 a rotation and a reflection are identical,+ so every symmetric component agrees under both and only a chiral one disagrees."""+ on_midline = (2.8, 4.6, 0.0)+ self.assertEqual(classify_relation(on_midline, (-2.8, 4.6, 0.0)), "reflection")++ def test_both_halves_on_the_same_side_is_reported_as_such(self) -> None:+ ok, message = check_pair("hand", (2.8, 4.6, 0.1), (2.8, 4.6, 0.1))+ self.assertFalse(ok)+ self.assertIn("same side", message)+++class TheFootDefect(unittest.TestCase):+ """The one a pair check cannot catch, with the numbers measured off the renders."""++ REFERENCE = [(0.0, 529.0), (1.0, 488.0)] # medial-heavy, as a real foot is+ BEFORE = [(0.0, 350.0), (1.0, 443.0)] # lateral-heavy: big toe on the wrong edge+ AFTER = [(0.0, 426.0), (1.0, 358.0)]++ def build(self, samples, midline=-1.0):+ """A left foot: its own centre sits left of the body midline, so 'medial' is +lateral."""+ return medial_lateral_bias([(c, w) for c, w in samples], midline=midline)++ def test_a_perfect_mirror_pair_can_still_both_be_wrong(self) -> None:+ """The whole reason this test exists beside `check_pair`. Both feet were built from one+ authored shape and mirrored correctly, so the pair check is happy."""+ ok, _ = check_pair("foot", (0.37, 0.0, 0.0), (-0.37, 0.0, 0.0))+ self.assertTrue(ok)++ def test_the_reference_is_medial_heavy(self) -> None:+ self.assertEqual(self.build(self.REFERENCE)["heavier"], "medial")++ def test_the_defect_is_lateral_heavy_and_is_caught(self) -> None:+ reference = self.build(self.REFERENCE)+ before = self.build(self.BEFORE)+ self.assertEqual(before["heavier"], "lateral")+ ok, message = compare_bias(reference, before, "foot-l toe band")+ self.assertFalse(ok)+ self.assertIn("the OTHER limb", message)+ self.assertIn("order of anything laid out across it", message)++ def test_the_fix_passes(self) -> None:+ ok, message = compare_bias(self.build(self.REFERENCE), self.build(self.AFTER), "foot-l")+ self.assertTrue(ok, message)++ def test_a_magnitude_difference_alone_is_not_a_chirality_failure(self) -> None:+ """Proportion is another gate's job. Only the SIGN is judged here."""+ reference = self.build([(0.0, 700.0), (1.0, 300.0)])+ candidate = self.build([(0.0, 520.0), (1.0, 480.0)])+ ok, _ = compare_bias(reference, candidate, "foot-l")+ self.assertTrue(ok)++ def test_the_floor_is_low_enough_to_see_the_real_reference(self) -> None:+ """The first floor was 0.05, picked by eye, and it made the gate blind to the very defect+ it exists for: the reference feet measure +0.0403 and +0.0579."""+ from chirality import MIN_REFERENCE_BIAS # noqa: PLC0415+ self.assertLess(MIN_REFERENCE_BIAS, 0.0403)+ self.assertGreater(MIN_REFERENCE_BIAS, 0.0)++ def test_a_symmetric_reference_cannot_judge_handedness_and_says_so(self) -> None:+ reference = self.build([(0.0, 505.0), (1.0, 500.0)])+ candidate = self.build([(0.0, 300.0), (1.0, 700.0)])+ ok, message = compare_bias(reference, candidate, "foot-l")+ self.assertTrue(ok)+ self.assertIn("cannot be judged", message)++ def test_medial_is_derived_from_which_side_the_limb_is_on(self) -> None:+ """Not assumed: the same samples on the right foot must report the opposite side."""+ left = medial_lateral_bias([(-0.50, 100.0), (-0.25, 400.0)], midline=0.0)+ right = medial_lateral_bias([(0.25, 400.0), (0.50, 100.0)], midline=0.0)+ self.assertEqual(left["heavier"], right["heavier"])++ def test_no_samples_does_not_raise(self) -> None:+ self.assertEqual(medial_lateral_bias([])["sampleCount"], 0)+++class SpecLevelGate(unittest.TestCase):+ def run_spec(self, tree):+ from validate_sculpt_spec import validate_chirality # noqa: PLC0415++ errors: list[str] = []+ warnings: list[str] = []+ validate_chirality({"componentTree": tree}, errors, warnings)+ return errors, warnings++ def test_a_rotated_pair_is_a_hard_error(self) -> None:+ errors, _ = self.run_spec([+ {"id": "hand-r", "transform": {"position": [2.8, 4.6, 0.288]}},+ {"id": "hand-l", "transform": {"position": [-2.8, 4.6, -0.288]}},+ ])+ self.assertEqual(len(errors), 1)+ self.assertIn("ROTATED", errors[0])++ def test_a_mirrored_pair_on_the_right_convention_is_clean(self) -> None:+ """`-l` at +X, which is the character's own left. Writing this test the other way round+ first was instructive: the warning fired, correctly, and I had reached for the demo's+ inverted convention without noticing."""+ errors, warnings = self.run_spec([+ {"id": "hand-l", "transform": {"position": [2.8, 4.6, 0.288]}},+ {"id": "hand-r", "transform": {"position": [-2.8, 4.6, 0.288]}},+ ])+ self.assertEqual(errors, [])+ self.assertEqual(warnings, [])++ def test_a_left_named_component_sitting_on_the_right_warns(self) -> None:+ """Fires even with no partner present, and this is the divergence the showcase demo has:+ it spells the character's left `-l` and places it at -X, which is the opposite of the+ generator's own documented convention."""+ _, warnings = self.run_spec([+ {"id": "foot-l", "transform": {"position": [-0.37, 0.0, 0.0]}},+ {"id": "foot-r", "transform": {"position": [0.37, 0.0, 0.0]}},+ ])+ self.assertEqual(len(warnings), 2)+ self.assertIn("would drive the wrong side", warnings[0])++ def test_the_generators_own_convention_passes_clean(self) -> None:+ _, warnings = self.run_spec([+ {"id": "ear-l", "transform": {"position": [0.43, 0.02, -0.02]}},+ {"id": "ear-r", "transform": {"position": [-0.43, 0.02, -0.02]}},+ ])+ self.assertEqual(warnings, [])++ def test_components_on_the_midline_are_not_judged(self) -> None:+ _, warnings = self.run_spec([{"id": "thing-l", "transform": {"position": [0.0, 1.0, 0.0]}}])+ self.assertEqual(warnings, [])++ def test_unpaired_and_untransformed_components_are_ignored(self) -> None:+ errors, warnings = self.run_spec([+ {"id": "torso"}, {"id": "head", "transform": {}},+ {"id": "arm-l", "transform": {"position": ["x", 1, 2]}},+ ])+ self.assertEqual(errors, [])+ self.assertEqual(warnings, [])+++class WholeFigureSanity(unittest.TestCase):+ def test_a_symmetric_figure_reports_near_zero(self) -> None:+ points = [(0.3, 1.0, 0.0), (-0.3, 1.0, 0.0), (0.0, 2.0, 0.0)]+ self.assertLess(sagittal_symmetry_error(points), 1e-9)++ def test_a_drifted_pair_raises_the_number(self) -> None:+ points = [(0.3, 1.0, 0.0), (-0.3, 1.0, 0.4), (0.0, 2.0, 0.0)]+ self.assertGreater(sagittal_symmetry_error(points), 0.1)++ def test_no_points_does_not_raise(self) -> None:+ self.assertEqual(sagittal_symmetry_error([]), 0.0)++++class NestedPairSideNaming(unittest.TestCase):+ """The side-naming warning reads WORLD x, so a nested pair member is judged by where it is.++ A toe inside a left paw legitimately carries a negative LOCAL x while sitting on the+ character's left. Reading the local value flagged every inboard toe of a correctly mirrored+ pair, and the only way to silence it would have been to stop mirroring them.+ """++ @staticmethod+ def _spec(toe_offset_left: float, toe_offset_right: float):+ def part(component_id, parent, x):+ return {+ "id": component_id,+ "name": component_id,+ "level": "meso",+ "role": "paw",+ "primitive": "ellipsoid",+ "topologyClass": "continuous-sculpt",+ "topologyRationale": "test",+ "parent": parent,+ "dimensions": {"width": 0.1, "height": 0.1, "depth": 0.1, "units": "relative"},+ "transform": {"position": [x, 0.0, 0.0], "rotation": [0, 0, 0]},+ }++ return {+ "componentTree": [+ part("paw-l", None, 0.12),+ part("paw-r", None, -0.12),+ part("toe-0-l", "paw-l", toe_offset_left),+ part("toe-0-r", "paw-r", toe_offset_right),+ ]+ }++ def test_a_correctly_mirrored_inboard_toe_is_not_flagged(self):+ errors, warnings = [], []+ validate_sculpt_spec.validate_chirality(self._spec(-0.04, 0.04), errors, warnings)+ self.assertEqual(errors, [])+ self.assertEqual([w for w in warnings if "named for the character" in w], [])++ def test_a_toe_that_really_crosses_the_midline_is_still_flagged(self):+ """Negative control: the world-space read must not simply stop catching the defect."""+ errors, warnings = [], []+ validate_sculpt_spec.validate_chirality(self._spec(-0.30, 0.30), errors, warnings)+ flagged = [w for w in warnings if "named for the character" in w]+ self.assertEqual(len(flagged), 2, warnings)+ self.assertIn("world x", flagged[0])+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_hair_evidence.py b/forge/tests/test_hair_evidence.pynew file mode 100644index 0000000..c1c1c85--- /dev/null+++ b/forge/tests/test_hair_evidence.py@@ -0,0 +1,323 @@+#!/usr/bin/env python3+"""Tests for stage 1 hair evidence extraction.++Three things this fills that were previously absent: `faceLandmarks.hairline`, a slot that has+existed since v1.2 with nothing ever writing to it; banded dark coverage, which was run by hand four+times in one session and never became a script; and shading evidence, which nothing measured at all+and which turned out to be where the deficit mostly lived.++`ThresholdIsNotATautology` is the load-bearing class. The first implementation cut at a fixed+percentile, which makes the reported hair fraction true by construction -- it read 0.380, 0.384 and+0.382 across three different views of the same subject, which looks like agreement and is+arithmetic.++Run: python3 forge/tests/test_hair_evidence.py+"""+import struct+import sys+import tempfile+import unittest+import zlib+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))++from extract_hair_evidence import ( # noqa: E402+ MIN_CLASS_SEPARATION,+ MIN_SEPARABILITY,+ analyse_view,+ extract_hair_evidence,+ otsu_threshold,+)+++def write_png(path: Path, width: int, height: int, pixel) -> None:+ """Minimal RGBA PNG writer. `pixel(x, y)` returns (r, g, b, a)."""+ raw = bytearray()+ for y in range(height):+ raw.append(0) # filter type: none+ for x in range(width):+ raw.extend(bytes(pixel(x, y)))++ def chunk(tag: bytes, payload: bytes) -> bytes:+ return (struct.pack(">I", len(payload)) + tag + payload+ + struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF))++ path.write_bytes(+ b"\x89PNG\r\n\x1a\n"+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0))+ + chunk(b"IDAT", zlib.compress(bytes(raw)))+ + chunk(b"IEND", b"")+ )+++BACKGROUND = (255, 255, 255, 0)+SKIN = (200, 160, 140, 255)+HAIR = (40, 30, 25, 255)+HIGHLIGHT = (150, 130, 110, 255)+++FIGURE_TOP = 5+FIGURE_BOTTOM = 395+# The module takes the head to be the top HEAD_FRACTION (0.15) of the figure, anchored on the+# reference's own proportion. A fixture must therefore be a whole FIGURE, not a head: a 90-row+# head-only image makes the analysed band 13 rows of pure hair, one luminance population, and the+# module correctly refuses to split it. Getting that wrong was the first attempt here.+HEAD_ROWS = int((FIGURE_BOTTOM - FIGURE_TOP) * 0.15)+++def head_image(path: Path, hair_rows: int = 6, highlight_row: int | None = None,+ width: int = 120, height: int = 400) -> None:+ """A full figure whose head band is `hair_rows` of hair over skin.++ `hair_rows` counts rows inside the head band, which is what the module actually analyses.+ """+ def pixel(x: int, y: int):+ if not (20 <= x < 100 and FIGURE_TOP <= y < FIGURE_BOTTOM):+ return BACKGROUND+ if y < FIGURE_TOP + hair_rows:+ if highlight_row is not None and y == highlight_row:+ return HIGHLIGHT+ return HAIR+ return SKIN++ write_png(path, width, height, pixel)+++class OtsuBehaviour(unittest.TestCase):+ def test_two_clear_populations_split_between_them(self) -> None:+ threshold, separation, _ = otsu_threshold([10.0] * 50 + [200.0] * 50)+ self.assertGreater(threshold, 10.0)+ self.assertLess(threshold, 200.0)+ self.assertGreater(separation, 150.0)++ def test_one_population_reports_no_separation(self) -> None:+ _, separation, _ = otsu_threshold([120.0] * 100)+ self.assertEqual(separation, 0.0)++ def test_an_empty_population_does_not_raise(self) -> None:+ self.assertEqual(otsu_threshold([]), (0.0, 0.0, 0.0))++ def test_the_split_moves_with_the_data_not_with_the_count(self) -> None:+ """The property a percentile cut does not have."""+ mostly_dark, _, _ = otsu_threshold([10.0] * 90 + [200.0] * 10)+ mostly_light, _, _ = otsu_threshold([10.0] * 10 + [200.0] * 90)+ self.assertAlmostEqual(mostly_dark, mostly_light, delta=25.0)++ def test_a_uniform_spread_scores_the_theoretical_unimodal_value(self) -> None:+ """sqrt(3) for any uniform population cut at its own middle -- and INDEPENDENT of width,+ which is the whole reason separability catches what raw separation cannot."""+ for width in (20.0, 80.0, 200.0):+ with self.subTest(width=width):+ spread = [i * width / 400 for i in range(400)]+ _, separation, separability = otsu_threshold(spread)+ self.assertAlmostEqual(separability, 1.732, delta=0.05)+ self.assertGreater(separation, width * 0.4)++ def test_two_tight_clusters_score_far_above_the_floor(self) -> None:+ _, _, separability = otsu_threshold([30.0] * 100 + [200.0] * 100)+ self.assertGreater(separability, MIN_SEPARABILITY * 2)+++class ThresholdIsNotATautology(unittest.TestCase):+ def test_more_hair_in_the_image_reports_more_hair(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ fractions = []+ for hair_rows in (8, 24, 48):+ path = Path(directory) / f"h{hair_rows}.png"+ head_image(path, hair_rows=hair_rows)+ fractions.append(analyse_view(path, "front")["hairFraction"])+ self.assertLess(fractions[0], fractions[1])+ self.assertLess(fractions[1], fractions[2])++ def test_a_head_with_no_hair_is_reported_as_having_no_split(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "bald.png"+ head_image(path, hair_rows=0)+ result = analyse_view(path, "front")+ self.assertEqual(result["status"], "no-hair-skin-split")++ def test_a_bald_head_under_a_key_light_is_still_rejected(self) -> None:+ """The case raw separation cannot see. Shading alone gives a bald scalp a wide luminance+ spread -- measured separation 38.6, three times any sane floor -- and it reported a quarter+ of itself as hair. Separability stays at the unimodal value however hard the light is.+ """+ def shaded(path: Path, spread: int) -> None:+ def pixel(x: int, y: int):+ if not (20 <= x < 100 and FIGURE_TOP <= y < FIGURE_BOTTOM):+ return BACKGROUND+ value = max(0, min(255, int(160 + spread * ((x - 20) / 80.0 - 0.5))))+ return (value, int(value * 0.8), int(value * 0.7), 255)+ write_png(path, 120, 400, pixel)++ with tempfile.TemporaryDirectory() as directory:+ for spread in (20, 80, 200):+ path = Path(directory) / f"bald{spread}.png"+ shaded(path, spread)+ result = analyse_view(path, "front")+ with self.subTest(spread=spread):+ self.assertEqual(result["status"], "no-hair-skin-split")+ self.assertLess(result["separability"], MIN_SEPARABILITY)+ # A faint gradient is caught by the raw separation floor and never reaches the+ # separability test; a strong one passes that floor easily and is caught only+ # here. Both are correct rejections, and asserting one message for both would+ # be asserting a detail of which rule fired first.+ if result["classSeparation"] >= MIN_CLASS_SEPARATION:+ self.assertIn("one broad", " ".join(result["warnings"]))++ def test_the_no_split_case_says_why(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "bald.png"+ head_image(path, hair_rows=0)+ result = analyse_view(path, "front")+ self.assertTrue(any("cannot tell hair from skin" in w for w in result["warnings"]))+++class BandedCoverage(unittest.TestCase):+ def test_hair_confined_to_the_top_shows_in_the_crown_band_only(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "top.png"+ head_image(path, hair_rows=HEAD_ROWS // 3)+ bands = analyse_view(path, "front")["bands"]+ self.assertGreater(bands["crown"]["coverage"], 0.85)+ self.assertLess(bands["jaw"]["coverage"], 0.15)++ def test_every_band_is_reported_even_when_empty(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "top.png"+ head_image(path, hair_rows=12)+ bands = analyse_view(path, "front")["bands"]+ self.assertEqual(set(bands), {"crown", "mid", "jaw"})+ for band in bands.values():+ self.assertIn("coverage", band)+ self.assertIn("pixelCount", band)+++class Shading(unittest.TestCase):+ def test_the_highlight_row_is_found(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "spec.png"+ head_image(path, hair_rows=30, highlight_row=FIGURE_TOP + 10)+ shading = analyse_view(path, "front")["shading"]+ self.assertIsNotNone(shading["specularBandV"])+ # The highlight sits 10 rows into a 58-row head band, so in its upper quarter.+ self.assertLess(shading["specularBandV"], 0.5)+ self.assertGreater(shading["specularBandLuma"], 100.0)++ def test_a_flat_mass_reports_no_root_to_tip_delta_worth_having(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "flat.png"+ head_image(path, hair_rows=30)+ shading = analyse_view(path, "front")["shading"]+ self.assertIsNotNone(shading["rootToTipLumaDelta"])+ self.assertAlmostEqual(shading["rootToTipLumaDelta"], 0.0, delta=1.0)++ def test_the_delta_sign_convention_is_documented_not_assumed(self) -> None:+ """Which end is the root depends on the hairstyle, and this module does not guess."""+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "flat.png"+ head_image(path, hair_rows=30)+ note = analyse_view(path, "front")["shading"]["note"]+ self.assertIn("not inferred here", note)+++class Hairline(unittest.TestCase):+ def test_the_hairline_tracks_where_the_hair_actually_stops(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ shallow = Path(directory) / "a.png"+ deep = Path(directory) / "b.png"+ head_image(shallow, hair_rows=12)+ head_image(deep, hair_rows=45)+ a = analyse_view(shallow, "front")["hairline"]+ b = analyse_view(deep, "front")["hairline"]+ self.assertLess(a, b)++ def test_the_consensus_hairline_reaches_faceLandmarks(self) -> None:+ """The slot that has existed since v1.2 with nothing writing to it."""+ with tempfile.TemporaryDirectory() as directory:+ front = Path(directory) / "front.png"+ profile = Path(directory) / "profile.png"+ head_image(front, hair_rows=20)+ head_image(profile, hair_rows=20)+ report = extract_hair_evidence({"front": front, "profile": profile})+ self.assertIn("hairline", report["faceLandmarks"])+ self.assertGreater(report["faceLandmarks"]["hairline"], 0.0)+++class HonestyAboutWhatWasNotSeen(unittest.TestCase):+ def test_a_frontal_only_set_reports_the_rear_as_unobserved(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ front = Path(directory) / "front.png"+ head_image(front, hair_rows=20)+ report = extract_hair_evidence({"front": front})+ joined = " ".join(report["notObserved"])+ self.assertIn("rear", joined)+ self.assertIn("Do not author them as if measured", joined)++ def test_a_set_that_includes_a_rear_view_does_not_claim_it_is_missing(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ paths = {}+ for name in ("front", "rear"):+ path = Path(directory) / f"{name}.png"+ head_image(path, hair_rows=20)+ paths[name] = path+ report = extract_hair_evidence(paths)+ self.assertFalse([n for n in report["notObserved"] if n.startswith("rear")])++ def test_a_single_view_reports_that_depth_is_unobservable(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ front = Path(directory) / "front.png"+ head_image(front, hair_rows=20)+ report = extract_hair_evidence({"front": front})+ self.assertTrue(any(n.startswith("depth") for n in report["notObserved"]))++ def test_confidence_rises_with_the_number_of_usable_views(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ paths = {}+ confidences = []+ for name in ("front", "rear", "profile", "left-profile"):+ path = Path(directory) / f"{name}.png"+ head_image(path, hair_rows=20)+ paths[name] = path+ confidences.append(extract_hair_evidence(dict(paths))["confidence"])+ self.assertEqual(confidences, sorted(confidences))+ self.assertEqual(confidences[-1], 1.0)++ def test_lock_geometry_is_explicitly_not_reported(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ front = Path(directory) / "front.png"+ head_image(front, hair_rows=20)+ report = extract_hair_evidence({"front": front})+ self.assertIn("Lock geometry is not", report["calibrationNote"])+ self.assertNotIn("locks", report["views"]["front"])+++class RealReferenceViews(unittest.TestCase):+ """The synthetic cases above prove the arithmetic; this proves it survives a real render."""++ def test_the_reference_views_disagree_with_each_other_in_the_right_direction(self) -> None:+ from showcase_test_support import showcase_root # noqa: PLC0415++ captures = showcase_root() / "artifacts" / "low-poly-humanoid-glb" / "TRY1"+ if not captures.is_dir():+ raise unittest.SkipTest("archived reference captures are not in this checkout")++ views = {}+ for name in ("front", "rear"):+ path = captures / f"glb-baseline.{name}.png"+ if path.is_file():+ views[name] = path+ if len(views) < 2:+ raise unittest.SkipTest("need both a front and a rear baseline capture")++ report = extract_hair_evidence(views)+ front = report["views"]["front"]["hairFraction"]+ rear = report["views"]["rear"]["hairFraction"]+ # The back of a head is nearly all hair; the front is mostly face. A tautological threshold+ # reported these as equal to three decimal places.+ self.assertGreater(rear, front + 0.15, f"front={front} rear={rear}")+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_hair_gate.py b/forge/tests/test_hair_gate.pynew file mode 100644index 0000000..5a48775--- /dev/null+++ b/forge/tests/test_hair_gate.py@@ -0,0 +1,244 @@+#!/usr/bin/env python3+"""Tests for the stage 4 hair gate and its wiring into the pass orchestrator.++The gate's whole reason for existing is the HARD/SOFT split. Two failures look similar in a coverage+number and want opposite responses:++ bald patch the skull shows through. Always wrong. HARD.+ coverage shortfall less hair than the reference. Often the right compromise. SOFT.++Reading the second as the first is what produced the recorded regression: a shortfall was answered+by widening the masses, the widening pushed them off the skull, and closure went 42.2% to 40.9% --+worse on all six views -- while crown scalp exposure rose 14.9 points on the worst one.++Run: python3 forge/tests/test_hair_gate.py+"""+import json+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage3_build"))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage4_review"))++from hair_gate import BAND_SHORTFALL_SOFT, compare_views, hair_gate # noqa: E402+from orchestrate_passes import next_required_evidence, spec_has_hair # noqa: E402+from test_hair_evidence import HEAD_ROWS, head_image # noqa: E402++PASSING_EXPOSURE = {"verdict": "pass", "exposedFraction": 0.0, "hardMax": 0.05}+FAILING_EXPOSURE = {"verdict": "fail", "exposedFraction": 0.31, "hardMax": 0.05}+++class HardBeatsSoft(unittest.TestCase):+ def test_a_bald_patch_fails_even_when_every_view_matches(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ report = hair_gate({"front": path}, {"front": path}, FAILING_EXPOSURE)+ self.assertEqual(report["verdict"], "fail")+ self.assertEqual(report["softSignals"], [])+ self.assertTrue(any("skull is uncovered" in h for h in report["hardFailures"]))++ def test_a_coverage_shortfall_alone_is_review_not_fail(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ reference = Path(directory) / "ref.png"+ render = Path(directory) / "out.png"+ head_image(reference, hair_rows=HEAD_ROWS - 4)+ head_image(render, hair_rows=HEAD_ROWS // 3)+ report = hair_gate({"front": reference}, {"front": render}, PASSING_EXPOSURE)+ self.assertEqual(report["verdict"], "review")+ self.assertEqual(report["hardFailures"], [])+ self.assertTrue(report["softSignals"])++ def test_an_identical_pair_passes(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ report = hair_gate({"front": path}, {"front": path}, PASSING_EXPOSURE)+ self.assertEqual(report["verdict"], "pass")+ self.assertEqual(report["hardFailures"], [])+ self.assertEqual(report["softSignals"], [])++ def test_the_report_says_a_shortfall_does_not_authorise_widening(self) -> None:+ """The instruction that would have prevented the recorded regression."""+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ report = hair_gate({"front": path}, {"front": path}, PASSING_EXPOSURE)+ self.assertIn("never on its own authorises widening", report["note"])+ self.assertIn("42.2%", report["note"])+++class MissingExposureIsAGapNotAPass(unittest.TestCase):+ def test_omitting_the_geometric_gate_is_reported(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ report = hair_gate({"front": path}, {"front": path})+ self.assertEqual(report["verdict"], "review")+ self.assertTrue(any("scalpExposure was not supplied" in s for s in report["softSignals"]))++ def test_the_missing_channel_is_a_flag_not_just_prose(self) -> None:+ """So a caller can branch on it. Collapsed into the verdict word, "review because I could+ not check" was indistinguishable from "review, here are some notes"."""+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ self.assertFalse(hair_gate({"front": path}, {"front": path})["hardChannelPresent"])+ self.assertTrue(+ hair_gate({"front": path}, {"front": path}, PASSING_EXPOSURE)["hardChannelPresent"]+ )++ def test_the_cli_does_not_exit_zero_when_the_hard_channel_never_ran(self) -> None:+ """A caller that only checks for zero would have read a missing bald-patch check as a pass."""+ import hair_gate as module # noqa: PLC0415++ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ exposure = Path(directory) / "exposure.json"+ exposure.write_text(json.dumps(PASSING_EXPOSURE))++ import contextlib, io # noqa: PLC0415+ def run(argv):+ with contextlib.redirect_stdout(io.StringIO()):+ return module.main(argv)++ base = ["--reference", f"front={path}", "--render", f"front={path}"]+ self.assertEqual(run(base), 2, "no exposure report supplied")+ self.assertEqual(run(base + ["--scalp-exposure", str(exposure)]), 0)++ failing = Path(directory) / "failing.json"+ failing.write_text(json.dumps(FAILING_EXPOSURE))+ self.assertEqual(run(base + ["--scalp-exposure", str(failing)]), 1)++ def test_the_reason_is_stated_not_just_the_absence(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ report = hair_gate({"front": path}, {"front": path})+ joined = " ".join(report["softSignals"])+ self.assertIn("cannot reliably see a bald patch", joined)+++class Deltas(unittest.TestCase):+ def build(self, reference_bands, render_bands, **overrides):+ def view(bands, **extra):+ payload = {+ "status": "measured",+ "bands": {k: {"coverage": v} for k, v in bands.items()},+ "hairline": 0.05,+ "hairFraction": 0.4,+ "shading": {"specularBandV": 0.5},+ }+ payload.update(extra)+ return payload++ return compare_views(+ {"views": {"front": view(reference_bands)}},+ {"views": {"front": view(render_bands, **overrides)}},+ )++ def test_a_shortfall_past_the_threshold_is_flagged(self) -> None:+ views = self.build({"crown": 0.9}, {"crown": 0.9 - BAND_SHORTFALL_SOFT - 0.01})+ self.assertTrue(views["front"]["bands"]["crown"]["shortfall"])++ def test_a_shortfall_under_the_threshold_is_not(self) -> None:+ views = self.build({"crown": 0.9}, {"crown": 0.9 - BAND_SHORTFALL_SOFT + 0.01})+ self.assertFalse(views["front"]["bands"]["crown"]["shortfall"])++ def test_having_MORE_hair_than_the_reference_is_not_a_shortfall(self) -> None:+ views = self.build({"crown": 0.5}, {"crown": 0.9})+ self.assertFalse(views["front"]["bands"]["crown"]["shortfall"])+ self.assertGreater(views["front"]["bands"]["crown"]["delta"], 0)++ def test_a_view_absent_from_the_render_is_reported(self) -> None:+ views = compare_views(+ {"views": {"rear": {"status": "measured", "bands": {}}}}, {"views": {}}+ )+ self.assertEqual(views["rear"]["status"], "missing-from-render")++ def test_an_unmeasurable_view_carries_both_statuses(self) -> None:+ views = compare_views(+ {"views": {"front": {"status": "no-hair-skin-split"}}},+ {"views": {"front": {"status": "measured", "bands": {}}}},+ )+ self.assertEqual(views["front"]["status"], "not-measurable")+ self.assertEqual(views["front"]["referenceStatus"], "no-hair-skin-split")+++class ShadingIsNamedAsMaterial(unittest.TestCase):+ def test_a_displaced_highlight_says_adding_hair_will_not_fix_it(self) -> None:+ """The correction that four geometric attempts never found."""+ with tempfile.TemporaryDirectory() as directory:+ reference = Path(directory) / "ref.png"+ render = Path(directory) / "out.png"+ head_image(reference, hair_rows=HEAD_ROWS - 4, highlight_row=8)+ head_image(render, hair_rows=HEAD_ROWS - 4, highlight_row=HEAD_ROWS - 2)+ report = hair_gate({"front": reference}, {"front": render}, PASSING_EXPOSURE)+ joined = " ".join(report["softSignals"])+ self.assertIn("MATERIAL difference", joined)+ self.assertIn("adding hair will not move it", joined)+++class Thresholds(unittest.TestCase):+ def test_the_thresholds_declare_themselves_uncalibrated(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ report = hair_gate({"front": path}, {"front": path}, PASSING_EXPOSURE)+ self.assertTrue(report["thresholds"]["uncalibrated"])++ def test_what_neither_side_observed_is_carried_through(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "same.png"+ head_image(path, hair_rows=HEAD_ROWS // 2)+ report = hair_gate({"front": path}, {"front": path}, PASSING_EXPOSURE)+ self.assertTrue(any("rear" in n for n in report["referenceNotObserved"]))+ self.assertTrue(any("rear" in n for n in report["renderNotObserved"]))+++class OrchestratorWiring(unittest.TestCase):+ def hair_spec(self) -> dict:+ return {+ "componentTree": [+ {"id": "head", "primitive": "ellipsoid", "role": "head"},+ {"id": "hair", "primitive": "tapered-sweep", "role": "hair", "parent": "head"},+ ]+ }++ def test_a_hair_subject_is_detected_by_component_role(self) -> None:+ self.assertTrue(spec_has_hair(self.hair_spec()))++ def test_a_hair_subject_is_detected_by_profile_alone(self) -> None:+ self.assertTrue(spec_has_hair({"hairProfile": {"scalpComponentId": "head"}}))++ def test_a_chair_is_not_a_hair_subject(self) -> None:+ self.assertFalse(spec_has_hair({"componentTree": [{"id": "seat", "role": "panel"}]}))+ self.assertFalse(spec_has_hair({}))++ def test_scalp_exposure_is_demanded_for_a_visual_pass_on_a_hair_subject(self) -> None:+ evidence = " ".join(next_required_evidence(self.hair_spec(), "structural-pass"))+ self.assertIn("scalp_exposure.py", evidence)+ self.assertIn("before rendering", evidence)++ def test_the_hair_gate_is_demanded_too(self) -> None:+ evidence = " ".join(next_required_evidence(self.hair_spec(), "structural-pass"))+ self.assertIn("hair_gate.py", evidence)++ def test_a_non_hair_subject_is_not_asked_for_hair_evidence(self) -> None:+ evidence = " ".join(+ next_required_evidence({"componentTree": [{"id": "seat", "role": "panel"}]},+ "structural-pass")+ )+ self.assertNotIn("scalp_exposure.py", evidence)+ self.assertNotIn("hair_gate.py", evidence)++ def test_the_completed_pass_demands_nothing(self) -> None:+ self.assertEqual(next_required_evidence(self.hair_spec(), "complete"), [])+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_hair_material.py b/forge/tests/test_hair_material.pynew file mode 100644index 0000000..39e24b4--- /dev/null+++ b/forge/tests/test_hair_material.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""Hair reads as hair through shading, because in this pipeline it cannot read as hair through+geometry.++THE MEASUREMENT THAT REORDERED THIS. The reference these gates are calibrated against is a merged+570,400-vertex scan. Its hair surface roughness, measured as the radial step between adjacent+azimuth bins, is 0.00338 -- against 0.00312 for a torso with no hair on it at all. The hair is a+smooth shell and its entire strand appearance lives in the diffuse and normal textures.++img2threejs emits code and no textures. So the strand impression has to come from sheen, anisotropy+and a root-to-tip ramp. That is the opposite of the earlier judgement in this session, which was+that shading should be deferred because "a shader cannot move a geometry score" -- four attempts to+close the gap with geometry all failed, and the last one made every view worse.++Run: python3 forge/tests/test_hair_material.py+"""+import json+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage3_build"))++from generate_threejs_factory import generate, root_tip_gradient # noqa: E402+from materials.reference import load_reference, validate_reference # noqa: E402++FIXTURE = Path(__file__).resolve().parent / "fixtures" / "stand_proud_hair_on_head.json"+++def fixture_spec() -> dict:+ return json.loads(FIXTURE.read_text())+++class TheMaterialReference(unittest.TestCase):+ def setUp(self) -> None:+ self.reference = load_reference()+ self.by_id = {m["id"]: m for m in self.reference["materials"]}++ def test_the_registry_still_validates(self) -> None:+ self.assertEqual(validate_reference(self.reference), [])++ def test_hair_human_now_carries_sheen(self) -> None:+ """It described anisotropy and no sheen, which leaves the broad highlight band with nothing+ to come from once there are no maps."""+ prior = self.by_id["hair.human"]["renderPrior"]+ self.assertIn("sheen", prior)+ self.assertIn("sheenRoughness", prior)++ def test_a_code_only_hair_profile_exists_and_needs_no_maps(self) -> None:+ profile = self.by_id["hair.human.code-only"]+ self.assertEqual(profile["requiredMaps"], [])+ self.assertEqual(profile["optionalMaps"], [])++ def test_the_code_only_profile_leans_harder_on_shading_than_the_textured_one(self) -> None:+ """With no anisotropyMap and no normalMap, what is left has to work harder."""+ textured = self.by_id["hair.human"]["renderPrior"]+ code_only = self.by_id["hair.human.code-only"]["renderPrior"]+ self.assertGreater(code_only["anisotropy"]["default"], textured["anisotropy"]["default"])+ self.assertGreater(code_only["sheen"]["default"], textured["sheen"]["default"])++ def test_the_code_only_profile_admits_it_is_not_calibrated(self) -> None:+ limitations = " ".join(self.by_id["hair.human.code-only"]["limitations"])+ self.assertIn("Not calibrated", limitations)+ self.assertIn("0.00338", limitations)++ def test_both_hair_profiles_label_their_basis_as_a_prior(self) -> None:+ for material_id in ("hair.human", "hair.human.code-only"):+ with self.subTest(material_id=material_id):+ self.assertEqual(self.by_id[material_id]["recipeBasis"], "inferred-starting-prior")+++class GradientDescriptor(unittest.TestCase):+ def test_a_well_formed_gradient_is_read(self) -> None:+ parsed = root_tip_gradient(+ {"rootTipGradient": {"rootColor": "#111", "tipColor": "#eee", "axis": "z"}}+ )+ self.assertEqual(parsed, {"rootColor": "#111", "tipColor": "#eee", "axis": "z"})++ def test_the_axis_defaults_to_y(self) -> None:+ parsed = root_tip_gradient({"rootTipGradient": {"rootColor": "#111", "tipColor": "#eee"}})+ self.assertEqual(parsed["axis"], "y")++ def test_an_unknown_axis_falls_back_to_y_rather_than_emitting_nonsense(self) -> None:+ parsed = root_tip_gradient(+ {"rootTipGradient": {"rootColor": "#111", "tipColor": "#eee", "axis": "w"}}+ )+ self.assertEqual(parsed["axis"], "y")++ def test_a_malformed_gradient_is_none_not_a_default(self) -> None:+ for bad in ({}, {"rootTipGradient": "dark"}, {"rootTipGradient": {"rootColor": "#111"}},+ {"rootTipGradient": {"rootColor": 1, "tipColor": 2}}):+ with self.subTest(bad=bad):+ self.assertIsNone(root_tip_gradient(bad))+++class GradientEmission(unittest.TestCase):+ def test_nothing_is_emitted_when_no_component_asks_for_one(self) -> None:+ spec = fixture_spec()+ for component in spec["componentTree"]:+ component.pop("rootTipGradient", None)+ source = generate(spec, "structural-pass")+ self.assertNotIn("applyRootTipGradient", source)++ def test_the_helper_and_the_call_are_emitted(self) -> None:+ source = generate(fixture_spec(), "structural-pass")+ self.assertIn("function applyRootTipGradient(", source)+ self.assertIn('applyRootTipGradient(', source)+ self.assertIn('"#1a1310"', source)+ self.assertIn('"#4a3a2c"', source)++ def test_the_ramp_runs_along_the_mass_own_axis(self) -> None:+ """World Y would darken a sideways-sweeping fringe at whatever end happens to be lowest."""+ source = generate(fixture_spec(), "structural-pass")+ self.assertIn("axis === 'x' ? position.getX(i) : axis === 'z' ? position.getZ(i)", source)++ def test_a_mass_with_no_extent_does_not_divide_by_zero(self) -> None:+ source = generate(fixture_spec(), "structural-pass")+ self.assertIn("span > 1e-9", source)++ def test_the_material_is_cloned_before_vertex_colours_are_enabled(self) -> None:+ """Materials are shared by id; flipping the flag in place would tint unrelated components."""+ source = generate(fixture_spec(), "structural-pass")+ self.assertIn(".material.clone();", source)+ self.assertIn(".material.vertexColors = true;", source)+ self.assertLess(+ source.index(".material.clone();"),+ source.index(".material.vertexColors = true;"),+ )++ def test_the_gradient_runs_after_the_scale(self) -> None:+ """Before it, the ramp would span the unit form rather than the mass's real extent.++ Anchored on the LAST call site rather than the first match: the first match is the helper's+ own signature, which sits near the top of the file and would make this assertion pass or+ fail for reasons unrelated to the ordering it is checking.+ """+ source = generate(fixture_spec(), "structural-pass")+ call_at = source.rindex(" applyRootTipGradient(")+ scale_before = source.rindex("Geometry.scale(", 0, call_at)+ self.assertLess(scale_before, call_at)+ # ... and the two belong to the same component block, not to different ones.+ self.assertNotIn("new THREE.Mesh(", source[scale_before:call_at])+++class EmittedSourceTypechecks(unittest.TestCase):+ def test_a_factory_with_hair_shading_typechecks(self) -> None:+ import subprocess # noqa: PLC0415++ sys.path.insert(0, str(Path(__file__).resolve().parent))+ from showcase_test_support import showcase_root # noqa: PLC0415++ root = showcase_root()+ destination = root / "src" / "__hair_material_smoke__.ts"+ self.assertFalse(destination.exists(), "a previous run left its smoke source behind")++ source = generate(fixture_spec(), "structural-pass")+ self.assertIn("function applyRootTipGradient(", source)+ try:+ destination.write_text(source, encoding="utf-8")+ result = subprocess.run(+ ["npx", "tsc", "--noEmit"], cwd=root, capture_output=True, text=True, check=False+ )+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ finally:+ if destination.exists():+ destination.unlink()+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_hair_profile.py b/forge/tests/test_hair_profile.pynew file mode 100644index 0000000..a9cb721--- /dev/null+++ b/forge/tests/test_hair_profile.py@@ -0,0 +1,277 @@+#!/usr/bin/env python3+"""Tests for the hairProfile schema.++The profile exists so the model reverse-engineers PARAMETERS and a compiler owns topology, which is+how every other subsystem in this pipeline already works. Hair was the exception, and it produced+four wrong diagnoses of one hairstyle in a single session, each caught only by measurement after the+fact.++Two rules here carry measurements rather than opinions:++ the root rule a root held as an absolute position slides off the skull when the mass is+ resized. Measured: widening the hair side masses took closure from 42.2% to+ 40.9%, worse on all six views, with crown scalp exposure UP 14.9 points on the+ worst view.+ the tier default the calibration reference is a 570,400-vertex merged scan whose hair surface+ roughness is 0.00338 against a torso control of 0.00312. Its hair is a smooth+ shell with the strand detail in textures, so shell is the default and lock+ parameters have no ground truth at all.++Run: python3 forge/tests/test_hair_profile.py+"""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage2_spec"))++from hair_profile import ( # noqa: E402+ DEFAULT_REPRESENTATION_TIER,+ REJECTED_HAIR_PRIMITIVES,+ UNCALIBRATED_FIELDS,+ VALID_REPRESENTATION_TIERS,+ hair_profile_report,+ validate_hair_profile,+)+++def check(profile):+ errors: list[str] = []+ warnings: list[str] = []+ validate_hair_profile(profile, errors, warnings)+ return errors, warnings+++def mass(**overrides) -> dict:+ base = {+ "id": "crown", "region": "crown", "primitive": "tapered-sweep",+ "root": {"u": 0.5, "v": 0.8}, "length": 0.12, "width": 0.09, "thickness": 0.05,+ }+ base.update(overrides)+ return base+++def profile(**overrides) -> dict:+ base = {+ "scalpComponentId": "head",+ "representationTier": "masses",+ "hairline": {"controlPoints": [+ {"u": 0.15, "v": 0.55}, {"u": 0.50, "v": 0.62}, {"u": 0.85, "v": 0.55},+ ]},+ "flowField": {"gravity": 0.6, "partLine": {"u": 0.62}, "whorls": [{"u": 0.5, "v": 0.95}]},+ "masses": [mass()],+ }+ base.update(overrides)+ return base+++class Baseline(unittest.TestCase):+ def test_a_well_formed_profile_is_clean(self) -> None:+ errors, warnings = check(profile())+ self.assertEqual(errors, [])+ self.assertEqual(warnings, [])++ def test_an_absent_profile_is_not_an_error(self) -> None:+ """Most subjects are not characters, and none of them should be asked about hair."""+ self.assertEqual(check(None), ([], []))++ def test_a_non_object_profile_is_an_error(self) -> None:+ for bad in ("hair", 7, []):+ with self.subTest(bad=bad):+ errors, _ = check(bad)+ self.assertEqual(errors, ["hairProfile must be an object"])+++class TheRootRule(unittest.TestCase):+ def test_an_absolute_root_is_rejected_with_the_reason(self) -> None:+ errors, _ = check(profile(masses=[mass(root={"position": [0.1, 5.9, 0.0]})]))+ self.assertTrue(any("must be scalp (u, v)" in e for e in errors), errors)+ self.assertTrue(any("bald patch" in e for e in errors), errors)++ def test_an_xyz_root_is_rejected_too(self) -> None:+ errors, _ = check(profile(masses=[mass(root={"xyz": [0, 0, 0]})]))+ self.assertTrue(any("must be scalp (u, v)" in e for e in errors), errors)++ def test_a_missing_root_is_rejected(self) -> None:+ bare = mass()+ del bare["root"]+ errors, _ = check(profile(masses=[bare]))+ self.assertTrue(any(".root is required" in e for e in errors), errors)++ def test_uv_outside_the_unit_square_is_rejected(self) -> None:+ for bad in ({"u": 1.4, "v": 0.5}, {"u": 0.5, "v": -0.1}, {"u": "left", "v": 0.5}):+ with self.subTest(bad=bad):+ errors, _ = check(profile(masses=[mass(root=bad)]))+ self.assertTrue(any("u and v in [0,1]" in e for e in errors), errors)+++class RepresentationTier(unittest.TestCase):+ def test_the_default_is_shell(self) -> None:+ self.assertEqual(DEFAULT_REPRESENTATION_TIER, "shell")+ report = hair_profile_report({"scalpComponentId": "head"})+ self.assertEqual(report["representationTier"], "shell")++ def test_shell_needs_no_masses(self) -> None:+ errors, _ = check({"scalpComponentId": "head", "representationTier": "shell",+ "hairline": profile()["hairline"], "flowField": profile()["flowField"]})+ self.assertEqual(errors, [])++ def test_a_mass_tier_without_masses_is_an_error(self) -> None:+ payload = profile()+ del payload["masses"]+ errors, _ = check(payload)+ self.assertTrue(any("masses is required" in e for e in errors), errors)++ def test_an_unknown_tier_is_rejected(self) -> None:+ errors, _ = check(profile(representationTier="strands"))+ self.assertTrue(any("representationTier must be one of" in e for e in errors), errors)++ def test_the_lock_tier_declares_that_it_has_no_calibration(self) -> None:+ """The reference scan holds no lock geometry to measure, and the profile must say so."""+ _, warnings = check(profile(representationTier="locks"))+ joined = " ".join(warnings)+ self.assertIn("no calibration reference", joined)+ self.assertIn("0.00338", joined)++ def test_all_three_tiers_are_reachable(self) -> None:+ for tier in VALID_REPRESENTATION_TIERS:+ with self.subTest(tier=tier):+ errors, _ = check(profile(representationTier=tier))+ self.assertFalse([e for e in errors if "representationTier" in e], errors)+++class PrimitiveChoice(unittest.TestCase):+ def test_a_plane_card_is_rejected_because_there_is_no_texture(self) -> None:+ errors, _ = check(profile(masses=[mass(primitive="plane-card")]))+ self.assertTrue(any("alpha texture" in e for e in errors), errors)++ def test_a_tube_is_rejected_because_it_cannot_taper(self) -> None:+ errors, _ = check(profile(masses=[mass(primitive="tube")]))+ self.assertTrue(any("noodle" in e for e in errors), errors)++ def test_an_unusable_primitive_names_the_alternatives(self) -> None:+ errors, _ = check(profile(masses=[mass(primitive="torus")]))+ self.assertTrue(any("choose from" in e for e in errors), errors)++ def test_the_rejection_table_carries_a_reason_for_every_entry(self) -> None:+ for primitive, reason in REJECTED_HAIR_PRIMITIVES.items():+ with self.subTest(primitive=primitive):+ self.assertTrue(reason and len(reason) > 20, f"{primitive} has no usable reason")+++class Calibration(unittest.TestCase):+ def test_a_taper_without_an_uncalibrated_flag_warns(self) -> None:+ _, warnings = check(profile(masses=[mass(taper=0.12)]))+ self.assertTrue(any("not marked uncalibrated" in w for w in warnings), warnings)++ def test_a_flagged_taper_is_silent(self) -> None:+ _, warnings = check(profile(masses=[mass(taper=0.12, uncalibrated=True)]))+ self.assertEqual(warnings, [])++ def test_the_report_lists_what_is_uncalibrated(self) -> None:+ report = hair_profile_report(profile())+ self.assertEqual(report["uncalibratedFields"], list(UNCALIBRATED_FIELDS))+ self.assertIn("multipart GLB", report["calibrationNote"])++ def test_no_uncalibrated_field_is_silently_absent_from_the_list(self) -> None:+ """Guards the honesty rule: taper is derived, so it must appear."""+ self.assertIn("masses[].taper", UNCALIBRATED_FIELDS)+++class HairlineAndFlow(unittest.TestCase):+ def test_a_missing_hairline_warns(self) -> None:+ payload = profile()+ del payload["hairline"]+ _, warnings = check(payload)+ self.assertTrue(any("hairline is missing" in w for w in warnings), warnings)++ def test_too_few_control_points_is_an_error(self) -> None:+ errors, _ = check(profile(hairline={"controlPoints": [{"u": 0.5, "v": 0.6}]}))+ self.assertTrue(any("at least 3 points" in e for e in errors), errors)++ def test_a_missing_flow_field_warns_with_the_recorded_reason(self) -> None:+ payload = profile()+ del payload["flowField"]+ _, warnings = check(payload)+ self.assertTrue(any("fourteen competing directions" in w for w in warnings), warnings)++ def test_gravity_outside_the_unit_interval_is_an_error(self) -> None:+ errors, _ = check(profile(flowField={"gravity": 1.5}))+ self.assertTrue(any("gravity must be a number in [0,1]" in e for e in errors), errors)++ def test_a_whorl_needs_a_position_on_the_scalp(self) -> None:+ errors, _ = check(profile(flowField={"whorls": [{"strength": 0.5}]}))+ self.assertTrue(any("needs u and v" in e for e in errors), errors)+++class Structure(unittest.TestCase):+ def test_the_scalp_component_is_required(self) -> None:+ payload = profile()+ del payload["scalpComponentId"]+ errors, _ = check(payload)+ self.assertTrue(any("scalpComponentId is required" in e for e in errors), errors)++ def test_duplicate_mass_ids_are_rejected(self) -> None:+ errors, _ = check(profile(masses=[mass(), mass()]))+ self.assertTrue(any("duplicate id" in e for e in errors), errors)++ def test_an_unknown_region_is_rejected(self) -> None:+ errors, _ = check(profile(masses=[mass(region="moustache")]))+ self.assertTrue(any("is not one of" in e for e in errors), errors)++ def test_non_positive_dimensions_are_rejected(self) -> None:+ for field in ("length", "width", "thickness"):+ with self.subTest(field=field):+ errors, _ = check(profile(masses=[mass(**{field: 0.0})]))+ self.assertTrue(any(f".{field} must be a positive number" in e for e in errors))+++class ComponentLevelRejection(unittest.TestCase):+ """The same rule applied where components are declared, not only inside the profile."""++ def test_a_hair_role_component_may_not_be_a_plane_card(self) -> None:+ from validate_sculpt_spec import validate_components # noqa: PLC0415++ errors: list[str] = []+ warnings: list[str] = []+ validate_components(+ {+ "schemaVersion": "2.0",+ "materials": [{"id": "hair"}],+ "componentTree": [+ {"id": "head", "primitive": "ellipsoid", "material": "hair"},+ {"id": "hair-card", "primitive": "plane-card", "material": "hair",+ "role": "hair", "parent": "head",+ "standProud": {"againstComponentId": "head", "clearance": 0.01, "maxPush": 0.02}},+ ],+ },+ {"hair"},+ set(),+ errors,+ warnings,+ )+ self.assertTrue(any("may not use primitive 'plane-card'" in e for e in errors), errors)++ def test_a_non_hair_component_may_still_be_a_plane_card(self) -> None:+ from validate_sculpt_spec import validate_components # noqa: PLC0415++ errors: list[str] = []+ warnings: list[str] = []+ validate_components(+ {+ "schemaVersion": "2.0",+ "materials": [{"id": "glass"}],+ "componentTree": [+ {"id": "lens", "primitive": "plane-card", "material": "glass", "role": "panel"},+ ],+ },+ {"glass"},+ set(),+ errors,+ warnings,+ )+ self.assertFalse([e for e in errors if "plane-card" in e], errors)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_hierarchy_scale.py b/forge/tests/test_hierarchy_scale.pyindex 3bf62e1..d3307c9 100644--- a/forge/tests/test_hierarchy_scale.py+++ b/forge/tests/test_hierarchy_scale.py@@ -191,6 +191,19 @@ class HierarchyScaleTest(unittest.TestCase):except json.JSONDecodeError as exc:raise RuntimeError(f"FAIL CLOSED: result was not parseable JSON: {exc}\nstdout: {runtime.stdout!r}") from exc+ def test_non_attachment_primitives_keep_strict_endpoint_types(self) -> None:+ """Ordinary primitives must compile without invented attachment variables.++ A literal-null endpoint narrows the shared guarded branches to `never` under strict+ TypeScript. The pure helper keeps the same runtime null while preserving its declared+ `AttachmentEndpoint | null` return type.+ """+ generated = generate(NESTED_SCALE_SPEC, "blockout")+ self.assertIn("const endpoint_torso_0 = makeAttachmentEndpoint(null);", generated)+ self.assertIn("const endpoint_head_1 = makeAttachmentEndpoint(null);", generated)+ self.assertNotIn("const attachment_torso_0", generated)+ self.assertNotIn("const attachment_head_1", generated)+@classmethoddef tearDownClass(cls) -> None:cls._tempdir_ctx.cleanup()diff --git a/forge/tests/test_interior_difference.py b/forge/tests/test_interior_difference.pynew file mode 100644index 0000000..35e47ee--- /dev/null+++ b/forge/tests/test_interior_difference.py@@ -0,0 +1,180 @@+#!/usr/bin/env python3+"""Tests for the interior appearance metric.++The property under test is the one that cost this project 35 correction loops: a model whose face+was deleted entirely scored 0.8803 on silhouette IoU against the finished face's 0.8803 -- identical+to four decimals -- because the outline never changed. Each test below asserts that the OLD metric+is blind to the same input the new one resolves, so the pair cannot silently regress into agreement.++Run: python3 forge/tests/test_interior_difference.py+"""+import struct+import sys+import tempfile+import unittest+import zlib+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage4_review"))++from diagnose_render import load_mask, silhouette_iou # noqa: E402+from interior_difference import _bbox_corners, compare # noqa: E402++PNG_SIG = b"\x89PNG\r\n\x1a\n"+SIZE = 256+GRID = 64++BACKGROUND = (18, 18, 20)+SKIN = (214, 190, 168)+FEATURE = (40, 30, 28)+++def write_png(path: Path, pixel_fn) -> None:+ def chunk(tag: bytes, data: bytes) -> bytes:+ return (+ struct.pack(">I", len(data))+ + tag+ + data+ + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)+ )++ raw = bytearray()+ for y in range(SIZE):+ raw.append(0)+ for x in range(SIZE):+ raw += bytes(pixel_fn(x, y))+ ihdr = struct.pack(">IIBBBBB", SIZE, SIZE, 8, 2, 0, 0, 0)+ path.write_bytes(+ PNG_SIG + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b"")+ )+++def _inside_figure(x: int, y: int) -> bool:+ """A standing blob: head disc on top, body slab below. Identical in every variant."""+ if 40 <= y < 100:+ return (x - 128) ** 2 + (y - 70) ** 2 < 30 * 30+ return 100 <= y < 220 and 100 <= x < 156+++def blank_figure(x: int, y: int) -> tuple[int, int, int]:+ return SKIN if _inside_figure(x, y) else BACKGROUND+++def featured_figure(x: int, y: int) -> tuple[int, int, int]:+ """Same silhouette, but with eyes and a mouth painted INSIDE the head."""+ if _inside_figure(x, y):+ if (x - 118) ** 2 + (y - 62) ** 2 < 5 * 5:+ return FEATURE+ if (x - 138) ** 2 + (y - 62) ** 2 < 5 * 5:+ return FEATURE+ if 78 <= y < 82 and 118 <= x < 138:+ return FEATURE+ return SKIN+ return BACKGROUND+++class BboxConvention(unittest.TestCase):+ def test_returns_half_open_corners_not_origin_and_size(self) -> None:+ """Pins the convention. `diagnose_render.bbox_of` returns (x0, y0, w, h); this returns+ corners. Substituting one for the other produces confident garbage rather than an error."""+ width = height = 10+ mask = [False] * (width * height)+ for y in range(2, 6):+ for x in range(3, 8):+ mask[y * width + x] = True++ self.assertEqual(_bbox_corners(mask, width, height), (3, 2, 8, 6))++ def test_empty_mask_falls_back_to_whole_frame(self) -> None:+ self.assertEqual(_bbox_corners([False] * 16, 4, 4), (0, 0, 4, 4))+++class InteriorDifference(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls._dir = tempfile.mkdtemp(prefix="interior-difference-")+ cls.blank = Path(cls._dir) / "blank.png"+ cls.featured = Path(cls._dir) / "featured.png"+ write_png(cls.blank, blank_figure)+ write_png(cls.featured, featured_figure)++ def test_identical_images_score_zero(self) -> None:+ result = compare(self.featured, self.featured, grid=GRID)+ self.assertEqual(result["status"], "measured")+ self.assertEqual(result["interiorDifference"], 0.0)+ self.assertGreater(result["cellsCompared"], 0)++ def test_silhouette_iou_is_blind_to_the_face_this_metric_resolves(self) -> None:+ """The regression this whole module exists for.++ Adding eyes and a mouth changes no outline pixel, so IoU cannot move. If a future change+ makes IoU sensitive here the assertion below fails loudly rather than quietly making the+ interior metric redundant.+ """+ blank_mask, _ = load_mask(self.blank)+ featured_mask, _ = load_mask(self.featured)+ iou = silhouette_iou(blank_mask, featured_mask)++ result = compare(self.blank, self.featured, grid=GRID)++ self.assertEqual(iou, 1.0, "the two figures must share an identical silhouette")+ self.assertGreater(+ result["interiorDifference"],+ 0.01,+ "an added face must register as interior difference even though IoU is 1.0",+ )++ def test_band_restriction_localises_the_change_to_the_head(self) -> None:+ head = compare(self.blank, self.featured, band_from=0.0, band_to=0.30, grid=GRID)+ body = compare(self.blank, self.featured, band_from=0.45, band_to=1.0, grid=GRID)++ self.assertGreater(head["interiorDifference"], body["interiorDifference"])+ self.assertAlmostEqual(body["interiorDifference"], 0.0, places=6)++ def test_reports_sample_count_so_a_thin_band_cannot_pass_as_evidence(self) -> None:+ result = compare(self.blank, self.featured, band_from=0.0, band_to=0.30, grid=GRID)+ self.assertIn("cellsCompared", result)+ self.assertGreater(result["cellsCompared"], 0)++ def test_a_figureless_render_reports_status_instead_of_a_number(self) -> None:+ """A capture that came out empty must not be scored.++ Note that two non-empty figures practically always overlap here: both are normalised to+ their own bounding box, so even a small corner blob is stretched across the same lattice.+ The reachable no-overlap case is a render with no foreground at all -- a failed capture,+ which the loop must refuse to score rather than rank.+ """+ empty = Path(self._dir) / "empty.png"+ write_png(empty, lambda x, y: BACKGROUND)++ result = compare(self.blank, empty, grid=GRID)++ self.assertIsNone(result["interiorDifference"])+ self.assertEqual(result["status"], "foreground-mask-fell-back-to-whole-frame")+++class EvidenceWiring(unittest.TestCase):+ """The instrument existed for 35 loops and was never required, so it was never run.++ Building it again without wiring it into the gate would repeat exactly that.+ """++ def test_every_visual_pass_requires_banded_interior_difference(self) -> None:+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage3_build"))+ from orchestrate_passes import VISUAL_PASS_IDS, next_required_evidence # noqa: PLC0415++ for pass_id in sorted(VISUAL_PASS_IDS):+ with self.subTest(pass_id=pass_id):+ evidence = " ".join(next_required_evidence({}, pass_id))+ self.assertIn("interior_difference.py", evidence)++ def test_optimization_pass_is_not_asked_for_visual_evidence(self) -> None:+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage3_build"))+ from orchestrate_passes import next_required_evidence # noqa: PLC0415++ evidence = " ".join(next_required_evidence({}, "optimization-pass"))+ self.assertNotIn("interior_difference.py", evidence)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_label_glb_nodes.py b/forge/tests/test_label_glb_nodes.pynew file mode 100644index 0000000..4b3d0bb--- /dev/null+++ b/forge/tests/test_label_glb_nodes.py@@ -0,0 +1,212 @@+"""The point of these tests is that a NAME can never become evidence.++The asset this was written against has 16 nodes called `root.0`..`root.15`, so any labeller that reads+names produces confident nonsense. Every assertion below is about measurement surviving and names not.+"""+from __future__ import annotations++import json+import math+import struct+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))++from label_glb_nodes import BANDS, label, main # noqa: E402+++def _glb(gltf: dict) -> bytes:+ payload = json.dumps(gltf).encode("utf-8")+ payload += b" " * ((4 - len(payload) % 4) % 4)+ return (+ struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(payload))+ + struct.pack("<II", len(payload), 0x4E4F534A)+ + payload+ )+++def _asset(nodes: list[dict], meshes: list[dict], accessors: list[dict]) -> dict:+ return {+ "asset": {"version": "2.0"},+ "scene": 0,+ "scenes": [{"nodes": list(range(len(nodes)))}],+ "nodes": nodes,+ "meshes": meshes,+ "accessors": accessors,+ }+++def _box(lo, hi):+ return {"type": "VEC3", "componentType": 5126, "count": 8, "min": list(lo), "max": list(hi)}+++class TwoNodeFigure(unittest.TestCase):+ """A 2-unit figure: a boot at the bottom, a head at the top, both named meaninglessly."""++ def setUp(self):+ gltf = _asset(+ nodes=[+ {"name": "root.0", "mesh": 0, "translation": [0.0, 0.0, 0.0]},+ {"name": "root.1", "mesh": 1, "translation": [0.0, 0.0, 0.0]},+ ],+ meshes=[+ {"primitives": [{"attributes": {"POSITION": 0}}]},+ {"primitives": [{"attributes": {"POSITION": 1}}]},+ ],+ accessors=[_box((-0.2, 0.0, -0.1), (0.2, 0.2, 0.1)), _box((-0.15, 1.8, -0.1), (0.15, 2.0, 0.1))],+ )+ self.path = Path(tempfile.mkdtemp()) / "a.glb"+ self.path.write_bytes(_glb(gltf))+ self.report = label(self.path)++ def test_every_node_is_labelled(self):+ self.assertEqual(len(self.report["nodes"]), 2)+ self.assertEqual({n["nodeIndex"] for n in self.report["nodes"]}, {0, 1})++ def test_names_are_recorded_but_never_used_as_evidence(self):+ self.assertFalse(self.report["namesUsedAsEvidence"])+ self.assertEqual(self.report["observedNodeNames"], ["root.0", "root.1"])+ for node in self.report["nodes"]:+ self.assertEqual(node["evidence"]["method"], "measured-world-bounds")++ def test_the_bottom_node_bands_as_footwear_and_the_top_as_head(self):+ by_index = {n["nodeIndex"]: n for n in self.report["nodes"]}+ self.assertEqual(by_index[0]["band"], "footwear")+ self.assertEqual(by_index[1]["band"], "head")++ def test_status_refuses_to_claim_confirmation(self):+ self.assertEqual(self.report["status"], "hypothesis-requires-render-confirmation")++ def test_figure_height_is_measured_not_assumed(self):+ self.assertAlmostEqual(self.report["figureBounds"]["size"][1], 2.0, places=6)++ def test_every_node_carries_a_confidence_and_a_reason(self):+ for node in self.report["nodes"]:+ self.assertIsInstance(node["confidence"], float)+ self.assertTrue(node["evidence"]["reason"])+++class SideDetection(unittest.TestCase):+ def _side_for(self, x_centre: float) -> str:+ gltf = _asset(+ nodes=[+ {"name": "n", "mesh": 0},+ {"name": "wide", "mesh": 1},+ ],+ meshes=[+ {"primitives": [{"attributes": {"POSITION": 0}}]},+ {"primitives": [{"attributes": {"POSITION": 1}}]},+ ],+ accessors=[+ _box((x_centre - 0.05, 0.0, -0.05), (x_centre + 0.05, 0.2, 0.05)),+ _box((-0.5, 0.0, -0.1), (0.5, 2.0, 0.1)),+ ],+ )+ path = Path(tempfile.mkdtemp()) / "b.glb"+ path.write_bytes(_glb(gltf))+ return next(n for n in label(path)["nodes"] if n["nodeIndex"] == 0)["side"]++ def test_positive_x_is_the_characters_own_left(self):+ """Matches CHARACTER_LEFT_SIGN in forge/_shared/chirality.py, which exists so the two+ cannot silently diverge."""+ self.assertEqual(self._side_for(0.4), "left")++ def test_negative_x_is_the_characters_own_right(self):+ self.assertEqual(self._side_for(-0.4), "right")++ def test_a_node_on_the_axis_has_no_side(self):+ self.assertEqual(self._side_for(0.0), "midline")+++class HonestyAboutMergedShells(unittest.TestCase):+ def test_a_node_spanning_most_of_the_figure_is_called_a_merged_shell(self):+ """Naming the band its centroid lands in would be a confident wrong answer for a shell that+ covers hip through head."""+ gltf = _asset(+ nodes=[{"name": "root.0", "mesh": 0}],+ meshes=[{"primitives": [{"attributes": {"POSITION": 0}}]}],+ accessors=[_box((-0.3, 0.0, -0.1), (0.3, 2.0, 0.1))],+ )+ path = Path(tempfile.mkdtemp()) / "c.glb"+ path.write_bytes(_glb(gltf))+ node = label(path)["nodes"][0]+ self.assertEqual(node["band"], "multi-region-shell")+ self.assertLess(node["confidence"], 0.30)+ self.assertIn("45%", node["evidence"]["reason"])+++class RotationIsHandled(unittest.TestCase):+ def test_a_rotated_node_uses_all_eight_corners(self):+ """Transforming only min and max is the classic wrong way to rotate an AABB.++ The rotation here is 45 deg, NOT 90, and that choice is the whole test. A 90 deg rotation maps+ an axis-aligned box onto another axis-aligned box, so the two-corner shortcut happens to return+ the correct answer and the test passes while the code is wrong -- verified by mutation, which is+ how an earlier version of this test was caught being worthless.++ At 45 deg the unit square's true x-extent is the diagonal, sqrt(2). The shortcut transforms only+ (0,0,0) and (1,1,0), which both land on x = 0, so it reports an x-extent of ZERO.+ """+ # Quaternion for a rotation of THETA about Z is (0, 0, sin(THETA/2), cos(THETA/2)).+ theta = math.radians(45.0)+ s, c = math.sin(theta / 2), math.cos(theta / 2)+ gltf = _asset(+ nodes=[{"name": "r", "mesh": 0, "rotation": [0.0, 0.0, s, c]}],+ meshes=[{"primitives": [{"attributes": {"POSITION": 0}}]}],+ accessors=[_box((0.0, 0.0, 0.0), (1.0, 1.0, 0.1))],+ )+ path = Path(tempfile.mkdtemp()) / "d.glb"+ path.write_bytes(_glb(gltf))+ size = label(path)["nodes"][0]["bounds"]["size"]+ self.assertAlmostEqual(size[0], 2 ** 0.5, places=5)+ self.assertAlmostEqual(size[1], 2 ** 0.5, places=5)+++class ParentTransformsCompose(unittest.TestCase):+ def test_a_child_inherits_its_parent_translation(self):+ gltf = {+ "asset": {"version": "2.0"},+ "scene": 0,+ "scenes": [{"nodes": [0]}],+ "nodes": [+ {"name": "parent", "translation": [0.0, 1.0, 0.0], "children": [1]},+ {"name": "child", "mesh": 0},+ ],+ "meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}],+ "accessors": [_box((-0.1, 0.0, -0.1), (0.1, 0.2, 0.1))],+ }+ path = Path(tempfile.mkdtemp()) / "e.glb"+ path.write_bytes(_glb(gltf))+ bounds = label(path)["nodes"][0]["bounds"]+ self.assertAlmostEqual(bounds["min"][1], 1.0, places=6)+ self.assertAlmostEqual(bounds["max"][1], 1.2, places=6)+++class CliGate(unittest.TestCase):+ def test_min_confidence_gates_a_weak_map(self):+ """The whole reason the flag exists: a downstream per-region claim must be blockable."""+ gltf = _asset(+ nodes=[{"name": "root.0", "mesh": 0}],+ meshes=[{"primitives": [{"attributes": {"POSITION": 0}}]}],+ accessors=[_box((-0.3, 0.0, -0.1), (0.3, 2.0, 0.1))],+ )+ path = Path(tempfile.mkdtemp()) / "f.glb"+ path.write_bytes(_glb(gltf))+ self.assertEqual(main([str(path), "--min-confidence", "0.6"]), 1)+ self.assertEqual(main([str(path), "--min-confidence", "0.0"]), 0)++ def test_a_non_glb_fails_with_exit_two(self):+ path = Path(tempfile.mkdtemp()) / "g.glb"+ path.write_bytes(b"not a glb at all")+ self.assertEqual(main([str(path)]), 2)++ def test_bands_are_ordered_bottom_to_top(self):+ lows = [low for _name, low, _high in BANDS]+ self.assertEqual(lows, sorted(lows))+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_material_physics.py b/forge/tests/test_material_physics.pynew file mode 100644index 0000000..366d30d--- /dev/null+++ b/forge/tests/test_material_physics.py@@ -0,0 +1,162 @@+"""Every assertion here pins a measured property of [email protected], not a policy preference.++If three changes one of these, the test should fail loudly rather than the pipeline quietly emitting+values the engine no longer honours.+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))++from material_physics import ( # noqa: E402+ CLEARCOAT_ROUGHNESS_FLOOR,+ SHEEN_ENERGY_COMPENSATION_COEFFICIENT,+ check_material_physics,+ check_open_boundary_sides,+ compensated_base_luminance,+ effective_sheen_strength,+ sheen_base_darkening,+)+++class SheenFoldingTests(unittest.TestCase):+ def test_sheen_and_sheen_color_are_one_degree_of_freedom(self):+ """WebGLMaterials.js:408 multiplies them, so these two must be indistinguishable."""+ self.assertAlmostEqual(+ effective_sheen_strength(1.0, "#808080"),+ effective_sheen_strength(0.50196, "#ffffff"),+ places=4,+ )++ def test_default_sheen_color_makes_sheen_a_no_op(self):+ """three's default sheenColor is black and the term is a multiply, so strength is zero."""+ self.assertEqual(effective_sheen_strength(0.65, None), 0.0)+ self.assertEqual(effective_sheen_strength(0.65, "#000000"), 0.0)++ def test_sheen_off_is_zero_strength_whatever_the_colour(self):+ self.assertEqual(effective_sheen_strength(0.0, "#ffffff"), 0.0)++ def test_short_hex_is_expanded(self):+ self.assertAlmostEqual(effective_sheen_strength(1.0, "#fff"), 1.0, places=6)++ def test_unparseable_colour_carries_no_sheen(self):+ self.assertEqual(effective_sheen_strength(1.0, "not-a-colour"), 0.0)+++class SheenEnergyTests(unittest.TestCase):+ def test_full_white_sheen_darkens_base_by_the_engine_coefficient(self):+ """ShaderLib/meshphysical.glsl.js:205 -- 15.7% at full strength, exactly."""+ self.assertAlmostEqual(+ sheen_base_darkening(1.0, "#ffffff"),+ SHEEN_ENERGY_COMPENSATION_COEFFICIENT,+ places=6,+ )++ def test_darkening_scales_with_effective_strength(self):+ self.assertAlmostEqual(sheen_base_darkening(0.5, "#ffffff"), 0.0785, places=4)++ def test_compensation_inverts_the_darkening(self):+ """Authoring the compensated base must land back on the target after the engine darkens it."""+ target = 0.5+ compensated = compensated_base_luminance(target, 1.0, "#ffffff")+ self.assertAlmostEqual(compensated * (1.0 - sheen_base_darkening(1.0, "#ffffff")), target, places=6)++ def test_compensation_is_a_no_op_when_sheen_is_off(self):+ self.assertEqual(compensated_base_luminance(0.42, 0.0, "#ffffff"), 0.42)++ def test_compensation_never_exceeds_one(self):+ self.assertLessEqual(compensated_base_luminance(0.99, 1.0, "#ffffff"), 1.0)+++class MaterialPhysicsGateTests(unittest.TestCase):+ def test_sheen_without_sheen_color_is_an_error_not_a_warning(self):+ errors, _ = check_material_physics("shirt", {"sheen": 0.65})+ self.assertTrue(any("no sheenColor" in e for e in errors), errors)++ def test_sheen_with_black_sheen_color_is_an_error(self):+ errors, _ = check_material_physics("shirt", {"sheen": 0.65, "sheenColor": "#000000"})+ self.assertTrue(any("evaluates to zero" in e for e in errors), errors)++ def test_valid_sheen_warns_about_its_own_base_darkening(self):+ errors, warnings = check_material_physics("shirt", {"sheen": 1.0, "sheenColor": "#ffffff"})+ self.assertEqual(errors, [])+ self.assertTrue(any("15.7%" in w for w in warnings), warnings)++ def test_clearcoat_roughness_below_the_floor_is_flagged(self):+ _, warnings = check_material_physics("skin", {"clearcoatRoughness": 0.01})+ self.assertTrue(any(str(CLEARCOAT_ROUGHNESS_FLOOR) in w for w in warnings), warnings)++ def test_clearcoat_roughness_at_or_above_the_floor_is_silent(self):+ _, warnings = check_material_physics("skin", {"clearcoatRoughness": CLEARCOAT_ROUGHNESS_FLOOR})+ self.assertEqual([w for w in warnings if "clearcoatRoughness" in w], [])++ def test_zero_clearcoat_roughness_is_not_flagged(self):+ """0.0 is the three default and means 'unset', not 'authored below the floor'."""+ _, warnings = check_material_physics("skin", {"clearcoatRoughness": 0.0})+ self.assertEqual([w for w in warnings if "clearcoatRoughness" in w], [])++ def test_ior_and_reflectivity_together_is_an_error(self):+ errors, _ = check_material_physics("skin", {"ior": 1.4, "reflectivity": 0.5})+ self.assertTrue(any("reflectivity" in e for e in errors), errors)++ def test_skin_may_not_set_transmission(self):+ errors, _ = check_material_physics("skin", {"transmission": 0.3}, family="skin")+ self.assertTrue(any("transmission" in e and "subsurface" in e for e in errors), errors)++ def test_skin_may_not_set_thickness_either(self):+ errors, _ = check_material_physics("skin", {"thickness": 0.5}, family="skin")+ self.assertTrue(any("thickness" in e for e in errors), errors)++ def test_non_skin_may_set_transmission(self):+ errors, _ = check_material_physics("glass", {"transmission": 0.9}, family="glass")+ self.assertEqual(errors, [])++ def test_family_is_read_from_the_material_when_not_passed(self):+ errors, _ = check_material_physics("skin", {"family": "skin", "transmission": 0.3})+ self.assertTrue(errors)++ def test_fabric_without_sheen_warns_it_has_no_woven_cue(self):+ _, warnings = check_material_physics("shirt", {"roughness": 0.85}, family="fabric")+ self.assertTrue(any("woven or fibre cue" in w for w in warnings), warnings)++ def test_a_clean_fabric_material_passes(self):+ errors, _ = check_material_physics(+ "shirt", {"roughness": 0.85, "sheen": 0.6, "sheenColor": "#e8e2d8"}, family="fabric"+ )+ self.assertEqual(errors, [])+++class OpenBoundarySideTests(unittest.TestCase):+ def test_open_garment_boundary_with_front_side_is_an_error(self):+ failures = check_open_boundary_sides(+ "shirt-shell",+ {"garment": {"boundaries": [{"kind": "hem", "at": 0.8}]}},+ )+ self.assertTrue(any("FrontSide" in f for f in failures), failures)++ def test_double_side_clears_it(self):+ failures = check_open_boundary_sides(+ "shirt-shell",+ {"side": "DoubleSide", "garment": {"boundaries": [{"kind": "hem", "at": 0.8}]}},+ )+ self.assertEqual(failures, [])++ def test_closed_boundaries_do_not_require_double_side(self):+ failures = check_open_boundary_sides(+ "shirt-shell",+ {"garment": {"boundaries": [{"kind": "hem", "at": 0.8, "closed": True}]}},+ )+ self.assertEqual(failures, [])++ def test_a_non_garment_component_is_not_checked(self):+ self.assertEqual(check_open_boundary_sides("chest", {"primitive": "ellipsoid"}), [])++ def test_a_garment_with_no_boundaries_is_not_checked(self):+ self.assertEqual(check_open_boundary_sides("shirt", {"garment": {}}), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_primitive_watertightness.py b/forge/tests/test_primitive_watertightness.pyindex 4651300..8c121ff 100644--- a/forge/tests/test_primitive_watertightness.py+++ b/forge/tests/test_primitive_watertightness.py@@ -103,7 +103,9 @@ PRIMITIVES = sorted(VALID_PRIMITIVES)# after a position-only weld -- box/cylinder/sphere/ellipsoid/torus/instanced-cluster# via their normal, benign UV-seam duplication, capsule via true construction (RAW,# no weld needed).-EXPECTED_WELDED_WATERTIGHT = {"box", "cylinder", "sphere", "ellipsoid", "torus", "instanced-cluster", "extrude", "curve-sweep", "capsule", "cone"}+# tapered-sweep caps both ends by default (capEnds), so it is a closed solid; its ring seam+# duplicates one column of vertices exactly like the UV seam on a cylinder, and welds away.+EXPECTED_WELDED_WATERTIGHT = {"box", "cylinder", "sphere", "ellipsoid", "torus", "instanced-cluster", "extrude", "curve-sweep", "capsule", "cone", "tapered-sweep"}# capsule needs no weld at all: built closed by construction.EXPECTED_WATERTIGHT_EVEN_RAW = {"capsule"}# Inherently open shapes by design (a real edge is CORRECT, not a defect): a flatdiff --git a/forge/tests/test_region_and_arc_gates.py b/forge/tests/test_region_and_arc_gates.pynew file mode 100644index 0000000..f603ee1--- /dev/null+++ b/forge/tests/test_region_and_arc_gates.py@@ -0,0 +1,424 @@+from __future__ import annotations++import json+import math+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+REVIEW = ROOT / "forge" / "stage4_review"+sys.path.insert(0, str(REVIEW))++import swept_arc_gate # noqa: E402+import vertex_region_gate # noqa: E402++BLACK = "#1d1b1a"+WHITE = "#f2efe9"+++def _rgb(value: str) -> tuple[float, float, float]:+ number = int(value.lstrip("#"), 16)+ return (((number >> 16) & 255) / 255, ((number >> 8) & 255) / 255, (number & 255) / 255)+++def two_tone_box(white_below_y: float) -> dict:+ """A 1x1x1 grid of vertices, white below a height and black above it.++ A synthetic body whose one colour boundary sits at a known height, so the gate's reported box+ can be checked against a number derived by hand rather than against another run of itself.+ """+ positions: list[float] = []+ colors: list[float] = []+ steps = 11+ for i in range(steps):+ for j in range(steps):+ for k in range(steps):+ x = -0.5 + i / (steps - 1)+ y = -0.5 + j / (steps - 1)+ z = -0.5 + k / (steps - 1)+ positions.extend([x, y, z])+ colors.extend(_rgb(WHITE if y <= white_below_y else BLACK))+ return {"meshes": [{"id": "body", "positions": positions, "colors": colors}]}+++def arc_tube(bend_radius: float, tube_radius: float, span_degrees: float, rings: int = 40,+ around: int = 16) -> dict:+ positions: list[float] = []+ for ring in range(rings):+ theta = math.radians(span_degrees) * ring / (rings - 1)+ for step in range(around):+ phi = 2 * math.pi * step / around+ radius = bend_radius + tube_radius * math.cos(phi)+ positions.extend([radius * math.cos(theta), radius * math.sin(theta),+ tube_radius * math.sin(phi)])+ return {"meshes": [{"id": "tail", "positions": positions}]}+++def two_patches():+ """Two dense, well-separated white patches on one mesh — a bib and a sock, in miniature."""+ positions, colors = [], []+ for cy in (0.31, -0.41):+ for i in range(12):+ for j in range(12):+ positions.extend([-0.05 + 0.1 * i / 11, cy + 0.04 * j / 11, 0.0])+ colors.extend(_rgb(WHITE))+ return positions, colors+++def straight_cone(length: float, base_radius: float, rings: int = 40, around: int = 16) -> dict:+ positions: list[float] = []+ for ring in range(rings):+ t = ring / (rings - 1)+ radius = base_radius * (1 - t)+ for step in range(around):+ phi = 2 * math.pi * step / around+ positions.extend([radius * math.cos(phi), t * length, radius * math.sin(phi)])+ return {"meshes": [{"id": "tail", "positions": positions}]}+++class VertexRegionGate(unittest.TestCase):+ def test_the_measured_boundary_matches_the_height_it_was_built_at(self):+ geometry = two_tone_box(white_below_y=-0.2)+ meshes = vertex_region_gate.collect_vertices(geometry)+ measured = vertex_region_gate.measure(+ meshes, {"white": _rgb(WHITE), "black": _rgb(BLACK)}, azimuth=0.0, tolerance=0.06+ )+ white = measured["regions"]["white"]+ # The box spans y -0.5..0.5, so a boundary at y=-0.2 sits 0.3 up a unit height: in+ # reference coordinates (y measured downward from the top) the white region runs from+ # y0 = 0.7 to y1 = 1.0.+ self.assertAlmostEqual(white["y1"], 1.0, places=4)+ self.assertAlmostEqual(white["y0"], 0.7, places=4)+ self.assertEqual(measured["unclassifiedFraction"], 0.0)++ def test_moving_the_boundary_moves_the_measurement(self):+ """Negative control: the gate must not report the same box for a different model."""+ low = vertex_region_gate.measure(+ vertex_region_gate.collect_vertices(two_tone_box(-0.2)),+ {"white": _rgb(WHITE), "black": _rgb(BLACK)}, 0.0, 0.06,+ )["regions"]["white"]+ high = vertex_region_gate.measure(+ vertex_region_gate.collect_vertices(two_tone_box(0.1)),+ {"white": _rgb(WHITE), "black": _rgb(BLACK)}, 0.0, 0.06,+ )["regions"]["white"]+ self.assertNotAlmostEqual(low["y0"], high["y0"], places=3)++ def test_an_expectation_outside_tolerance_fails_and_names_the_delta(self):+ measured = vertex_region_gate.measure(+ vertex_region_gate.collect_vertices(two_tone_box(-0.2)),+ {"white": _rgb(WHITE), "black": _rgb(BLACK)}, 0.0, 0.06,+ )+ evaluation = vertex_region_gate.evaluate(+ measured,+ [{"id": "sock", "regions": ["white"],+ "expected": {"x0": 0.0, "x1": 1.0, "y0": 0.55, "y1": 1.0}, "tolerance": 0.04}],+ )+ self.assertEqual(evaluation["failures"], 1)+ self.assertEqual(evaluation["results"][0]["status"], "fail")+ self.assertAlmostEqual(evaluation["results"][0]["deltas"]["y0"], 0.15, places=3)++ def test_a_matching_expectation_passes(self):+ measured = vertex_region_gate.measure(+ vertex_region_gate.collect_vertices(two_tone_box(-0.2)),+ {"white": _rgb(WHITE), "black": _rgb(BLACK)}, 0.0, 0.06,+ )+ evaluation = vertex_region_gate.evaluate(+ measured,+ [{"id": "sock", "regions": ["white"],+ "expected": {"x0": 0.0, "x1": 1.0, "y0": 0.70, "y1": 1.0}, "tolerance": 0.04}],+ )+ self.assertEqual(evaluation["failures"], 0)++ def test_a_region_with_no_vertices_is_reported_missing_rather_than_passing(self):+ measured = vertex_region_gate.measure(+ vertex_region_gate.collect_vertices(two_tone_box(-0.2)),+ {"white": _rgb(WHITE), "black": _rgb(BLACK), "pink": _rgb("#c07060")}, 0.0, 0.06,+ )+ evaluation = vertex_region_gate.evaluate(+ measured,+ [{"id": "ear-inner", "regions": ["pink"],+ "expected": {"x0": 0.1, "x1": 0.2, "y0": 0.1, "y1": 0.2}}],+ )+ self.assertEqual(evaluation["results"][0]["status"], "missing")+ self.assertEqual(evaluation["failures"], 1)++ def test_unpaintable_vertices_are_counted_not_absorbed(self):+ geometry = two_tone_box(-0.2)+ # Repaint a slab mid-grey: it matches neither palette entry and must be declared.+ colors = geometry["meshes"][0]["colors"]+ for index in range(0, len(colors), 3):+ if colors[index] > 0.5 and index % 9 == 0:+ colors[index] = colors[index + 1] = colors[index + 2] = 0.5+ measured = vertex_region_gate.measure(+ vertex_region_gate.collect_vertices(geometry),+ {"white": _rgb(WHITE), "black": _rgb(BLACK)}, 0.0, 0.06,+ )+ self.assertGreater(measured["unclassifiedFraction"], 0.0)++ def test_azimuth_rotates_what_is_measured(self):+ positions = [-0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 0.4, 0.0, -0.5, -0.4]+ colors = list(_rgb(WHITE)) * 2 + list(_rgb(BLACK)) * 2+ geometry = {"meshes": [{"id": "m", "positions": positions, "colors": colors}]}+ meshes = vertex_region_gate.collect_vertices(geometry)+ front = vertex_region_gate.measure(meshes, {"white": _rgb(WHITE)}, 0.0, 0.06)+ side = vertex_region_gate.measure(meshes, {"white": _rgb(WHITE)}, 90.0, 0.06)+ self.assertNotAlmostEqual(front["regions"]["white"]["x1"],+ side["regions"]["white"]["x1"], places=3)++ def test_a_scoped_measurement_ignores_the_same_colour_on_another_mesh(self):+ """Colour alone cannot separate a bib from a sock; the part they sit on can."""+ body = two_tone_box(-0.2)["meshes"][0]+ body["id"] = "torso"+ sock = {+ "id": "paw",+ "positions": [0.0, -1.4, 0.0, 0.1, -1.3, 0.0, -0.1, -1.3, 0.0],+ "colors": list(_rgb(WHITE)) * 3,+ }+ meshes = vertex_region_gate.collect_vertices({"meshes": [body, sock]})+ palette = {"white": _rgb(WHITE), "black": _rgb(BLACK)}+ unscoped = vertex_region_gate.measure(meshes, palette, 0.0, 0.06)+ scoped = vertex_region_gate.measure(meshes, palette, 0.0, 0.06, scope={"torso"})+ # Unscoped, the white region runs all the way to the sock at the bottom of the model.+ self.assertAlmostEqual(unscoped["regions"]["white"]["y1"], 1.0, places=3)+ # Scoped to the torso it stops at the torso's own white band, well above it.+ self.assertLess(scoped["regions"]["white"]["y1"], 0.85)+ # Both are normalised to the WHOLE model, so the two numbers are comparable.+ self.assertEqual(unscoped["projectedExtent"], scoped["projectedExtent"])++ def test_an_empty_scope_is_an_error_rather_than_an_empty_pass(self):+ meshes = vertex_region_gate.collect_vertices(two_tone_box(-0.2))+ with self.assertRaises(SystemExit):+ vertex_region_gate.measure(meshes, {"white": _rgb(WHITE)}, 0.0, 0.06,+ scope={"no-such-mesh"})++ def test_one_colour_in_two_places_splits_into_two_blobs(self):+ """The fused-mesh case: a bib and a sock are the same colour on the same mesh.++ Without clustering, the measured "sock" box ran from the muzzle to the ground, because a+ colour bucket on one mesh is one region however many separate places it appears in.+ """+ # Dense patches, because the clustering grid is a connectivity test on a real mesh: three+ # scattered points land in three separate cells and are three blobs, correctly.+ positions, colors = two_patches()+ positions.extend([0.0, 0.0, 0.0])+ colors.extend(_rgb(BLACK))+ meshes = vertex_region_gate.collect_vertices(+ {"meshes": [{"id": "body", "positions": positions, "colors": colors}]}+ )+ measured = vertex_region_gate.measure(+ meshes, {"white": _rgb(WHITE), "black": _rgb(BLACK)}, 0.0, 0.06+ )+ blobs = measured["regions"]["white"]["blobs"]+ self.assertEqual(len(blobs), 2)+ # The whole-region box spans both patches; each blob covers only its own.+ self.assertGreater(measured["regions"]["white"]["y1"]+ - measured["regions"]["white"]["y0"], 0.8)+ for blob in blobs:+ self.assertLess(blob["y1"] - blob["y0"], 0.2)++ def test_selecting_a_blob_measures_that_blob_and_not_the_other(self):+ positions, colors = two_patches()+ meshes = vertex_region_gate.collect_vertices(+ {"meshes": [{"id": "body", "positions": positions, "colors": colors}]}+ )+ measured = vertex_region_gate.measure(meshes, {"white": _rgb(WHITE)}, 0.0, 0.06)+ blobs = measured["regions"]["white"]["blobs"]+ self.assertEqual(len(blobs), 2)+ # Expectations are built from each blob's own measured box, so this tests the SELECTION+ # rather than re-deriving the geometry by hand.+ for rank, blob in enumerate(blobs):+ with self.subTest(rank=rank):+ evaluation = vertex_region_gate.evaluate(+ measured,+ [{"id": "patch", "regions": ["white"], "blobs": [rank],+ "expected": {k: blob[k] for k in ("x0", "x1", "y0", "y1")},+ "tolerance": 0.001}],+ )+ self.assertEqual(evaluation["failures"], 0, evaluation)+ # And the two selections are genuinely different boxes.+ self.assertGreater(abs(blobs[0]["y0"] - blobs[1]["y0"]), 0.5)++ def test_a_spatial_filter_picks_the_blob_by_where_it_is_not_by_its_rank(self):+ """Rank is not stable between the reference and the model.++ On the reference the bib is the largest white blob; once the model's legs and paws are+ fused the four socks merge into a larger band, so rank 0 means different features on the+ two sides. Every sock comparison was then off by -0.45 in y0 and every bib comparison by+ +0.56, all in the same direction — a swapped correspondence, not a misplaced boundary.+ """+ positions, colors = two_patches()+ meshes = vertex_region_gate.collect_vertices(+ {"meshes": [{"id": "body", "positions": positions, "colors": colors}]}+ )+ measured = vertex_region_gate.measure(meshes, {"white": _rgb(WHITE)}, 0.0, 0.06)+ blobs = measured["regions"]["white"]["blobs"]+ upper = min(blobs, key=lambda blob: blob["centroidY"])+ lower = max(blobs, key=lambda blob: blob["centroidY"])+ self.assertGreater(lower["centroidY"] - upper["centroidY"], 0.5)++ evaluation = vertex_region_gate.evaluate(+ measured,+ [{"id": "sock", "regions": ["white"], "blobFilter": {"centroidYMin": 0.5},+ "expected": {k: lower[k] for k in ("x0", "x1", "y0", "y1")}, "tolerance": 0.001},+ {"id": "bib", "regions": ["white"], "blobFilter": {"centroidYMax": 0.5},+ "expected": {k: upper[k] for k in ("x0", "x1", "y0", "y1")}, "tolerance": 0.001}],+ )+ self.assertEqual(evaluation["failures"], 0, evaluation)++ def test_a_spatial_filter_matching_nothing_is_missing_not_a_pass(self):+ """Negative control: an empty selection must not quietly measure the whole region."""+ positions, colors = two_patches()+ meshes = vertex_region_gate.collect_vertices(+ {"meshes": [{"id": "body", "positions": positions, "colors": colors}]}+ )+ measured = vertex_region_gate.measure(meshes, {"white": _rgb(WHITE)}, 0.0, 0.06)+ evaluation = vertex_region_gate.evaluate(+ measured,+ [{"id": "sock", "regions": ["white"],+ "blobFilter": {"centroidYMin": 0.99, "centroidYMax": 1.0},+ "expected": {"x0": 0.0, "x1": 1.0, "y0": 0.0, "y1": 1.0}, "tolerance": 0.05}],+ )+ self.assertEqual(evaluation["results"][0]["status"], "missing")+ self.assertEqual(evaluation["failures"], 1)++ def test_naming_a_blob_that_does_not_exist_is_missing_not_a_silent_whole_region(self):+ """Negative control: an out-of-range rank must not quietly fall back to everything."""+ positions, colors = two_patches()+ meshes = vertex_region_gate.collect_vertices(+ {"meshes": [{"id": "body", "positions": positions, "colors": colors}]}+ )+ measured = vertex_region_gate.measure(meshes, {"white": _rgb(WHITE)}, 0.0, 0.06)+ evaluation = vertex_region_gate.evaluate(+ measured,+ [{"id": "sock", "regions": ["white"], "blobs": [3],+ "expected": {"x0": 0.0, "x1": 1.0, "y0": 0.0, "y1": 1.0}, "tolerance": 0.05}],+ )+ self.assertEqual(evaluation["results"][0]["status"], "missing")+ self.assertEqual(evaluation["failures"], 1)++ def test_cli_exits_one_on_a_failed_expectation_and_zero_on_a_met_one(self):+ with tempfile.TemporaryDirectory() as directory:+ base = Path(directory)+ (base / "geometry.json").write_text(json.dumps(two_tone_box(-0.2)), encoding="utf-8")+ (base / "palette.json").write_text(json.dumps({"white": WHITE, "black": BLACK}),+ encoding="utf-8")+ (base / "bad.json").write_text(json.dumps(+ [{"id": "sock", "regions": ["white"],+ "expected": {"x0": 0.0, "x1": 1.0, "y0": 0.4, "y1": 1.0}, "tolerance": 0.04}]),+ encoding="utf-8")+ (base / "good.json").write_text(json.dumps(+ [{"id": "sock", "regions": ["white"],+ "expected": {"x0": 0.0, "x1": 1.0, "y0": 0.7, "y1": 1.0}, "tolerance": 0.04}]),+ encoding="utf-8")+ for expectation, expected_code in (("bad.json", 1), ("good.json", 0)):+ result = subprocess.run(+ [sys.executable, str(REVIEW / "vertex_region_gate.py"),+ "--geometry", str(base / "geometry.json"),+ "--palette", str(base / "palette.json"),+ "--expect", str(base / expectation), "--json"],+ capture_output=True, text=True,+ )+ self.assertEqual(result.returncode, expected_code, result.stdout + result.stderr)+++class SweptArcGate(unittest.TestCase):+ EXPECTATIONS = {+ "minAngularSpanDeg": 150.0,+ "maxCentreDistanceOverExtent": 0.75,+ "bendRadius": 1.0,+ "bendRadiusTolerance": 0.08,+ "tubeRadius": 0.25,+ "tubeRadiusTolerance": 0.06,+ "maxRadiusSpreadOverBendRadius": 0.25,+ }++ def _points(self, geometry):+ positions = geometry["meshes"][0]["positions"]+ return [+ (positions[i], positions[i + 1], positions[i + 2])+ for i in range(0, len(positions), 3)+ ]++ def test_a_hook_recovers_the_radius_span_and_tube_it_was_built_with(self):+ measured = swept_arc_gate.analyse(self._points(arc_tube(1.0, 0.25, 190.0)))+ self.assertAlmostEqual(measured["bendRadius"], 1.0, delta=0.06)+ self.assertGreater(measured["angularSpanDeg"], 150.0)+ self.assertAlmostEqual(measured["tubeRadius"]["mean"], 0.25, delta=0.05)+ self.assertEqual(swept_arc_gate.evaluate(measured, self.EXPECTATIONS)["failures"], 0)++ def test_a_straight_tapered_cone_fails_the_same_gate(self):+ """The negative control the tail claim rests on.++ A cone is the shape the reference is explicitly not. If it passed, a passing verdict on the+ real tail would mean nothing.+ """+ measured = swept_arc_gate.analyse(self._points(straight_cone(2.0, 0.3)))+ evaluation = swept_arc_gate.evaluate(measured, self.EXPECTATIONS)+ self.assertGreater(evaluation["failures"], 0)+ failed = {check["check"] for check in evaluation["checks"] if check["status"] == "fail"}+ self.assertIn("angularSpan", failed)++ def test_a_thin_shallow_arc_fails_the_span_requirement(self):+ """A shallow but genuinely planar sweep must fail on span, not on the plane fit."""+ measured = swept_arc_gate.analyse(self._points(arc_tube(1.0, 0.02, 40.0)))+ evaluation = swept_arc_gate.evaluate(measured, self.EXPECTATIONS)+ failed = {check["check"] for check in evaluation["checks"] if check["status"] == "fail"}+ self.assertNotIn("planeDetermined", failed)+ self.assertIn("angularSpan", failed)++ def test_a_short_sweep_of_a_thick_tube_reports_an_undetermined_plane(self):+ """A rod does not determine a plane, and the gate must say so rather than fit one anyway.++ This is a real defect the gate had before the check existed: a 40-degree sweep of a+ 0.25-radius tube fitted its own circular CROSS-SECTION and reported bend radius 0.256 with+ a 352-degree span — a confident number describing the wrong circle entirely.+ """+ measured = swept_arc_gate.analyse(self._points(arc_tube(1.0, 0.25, 40.0)))+ evaluation = swept_arc_gate.evaluate(measured, self.EXPECTATIONS)+ failed = {check["check"] for check in evaluation["checks"] if check["status"] == "fail"}+ self.assertIn("planeDetermined", failed)+ self.assertLess(measured["planarity"], 0.35)++ def test_a_real_hook_reports_a_determined_plane(self):+ """Negative control for the planarity check: it must not fire on the shape that is fine."""+ measured = swept_arc_gate.analyse(self._points(arc_tube(1.0, 0.25, 190.0)))+ self.assertGreater(measured["planarity"], 0.35)++ def test_a_hook_of_the_wrong_radius_fails_the_radius_check_and_not_the_span(self):+ measured = swept_arc_gate.analyse(self._points(arc_tube(1.6, 0.25, 190.0)))+ evaluation = swept_arc_gate.evaluate(measured, self.EXPECTATIONS)+ failed = {check["check"] for check in evaluation["checks"] if check["status"] == "fail"}+ self.assertIn("bendRadius", failed)+ self.assertNotIn("angularSpan", failed)++ def test_a_hook_of_the_wrong_thickness_fails_the_tube_check(self):+ measured = swept_arc_gate.analyse(self._points(arc_tube(1.0, 0.45, 190.0)))+ evaluation = swept_arc_gate.evaluate(measured, self.EXPECTATIONS)+ failed = {check["check"] for check in evaluation["checks"] if check["status"] == "fail"}+ self.assertIn("tubeRadius", failed)++ def test_the_fit_reports_which_plane_it_used_and_how_far_off_it_the_points_are(self):+ measured = swept_arc_gate.analyse(self._points(arc_tube(1.0, 0.25, 190.0)))+ self.assertEqual(len(measured["planeNormal"]), 3)+ self.assertAlmostEqual(measured["maxOffPlaneDistance"], 0.25, delta=0.05)++ def test_cli_reports_a_cone_failure_with_a_nonzero_exit(self):+ with tempfile.TemporaryDirectory() as directory:+ base = Path(directory)+ (base / "cone.json").write_text(json.dumps(straight_cone(2.0, 0.3)), encoding="utf-8")+ (base / "expect.json").write_text(json.dumps(self.EXPECTATIONS), encoding="utf-8")+ result = subprocess.run(+ [sys.executable, str(REVIEW / "swept_arc_gate.py"),+ "--geometry", str(base / "cone.json"), "--component", "tail",+ "--expect", str(base / "expect.json"), "--json"],+ capture_output=True, text=True,+ )+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)+ self.assertIn("angularSpan", result.stdout)+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_release_metadata.py b/forge/tests/test_release_metadata.pyindex 0b85f09..9beef15 100644--- a/forge/tests/test_release_metadata.py+++ b/forge/tests/test_release_metadata.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonimport subprocess+import sysimport tempfileimport unittestfrom pathlib import Path@@ -28,7 +29,10 @@ class ReleaseMetadataTests(unittest.TestCase):def run_release(self, directory: Path, commits: Path, dry_run: bool = False) -> subprocess.CompletedProcess[str]:command = [- "python3",+ # `sys.executable`, not "python3": the release script uses `match`, so it needs+ # 3.10+, and on macOS the system `python3` is still 3.9. Hardcoding the name tested+ # whichever interpreter happened to be on PATH instead of the one running the suite.+ sys.executable,str(SCRIPT),"--root",str(directory),diff --git a/forge/tests/test_render_profile.py b/forge/tests/test_render_profile.pyindex bebe08d..1961c5a 100644--- a/forge/tests/test_render_profile.py+++ b/forge/tests/test_render_profile.py@@ -38,6 +38,43 @@ class RenderProfileTest(unittest.TestCase):self.assertFalse(result["passed"])self.assertTrue(any("passes must contain exactly" in error for error in result["errors"]))+ def test_profile_accepts_subject_specific_regions(self) -> None:+ profile = json.loads(PROFILE.read_text(encoding="utf-8"))+ profile["regions"] = [+ {"id": "skin", "criticality": "critical", "idColor": [255, 128, 0]},+ {"id": "clothing", "criticality": "critical", "idColor": [0, 255, 0]},+ {"id": "hair", "criticality": "critical", "idColor": [0, 0, 255]},+ {"id": "face", "criticality": "critical", "idColor": [255, 0, 0]},+ ]+ profile["extensions"] = {+ "requiredSemanticRegions": ["skin", "clothing", "hair", "face"],+ }+ result = validate_profile(profile)+ self.assertTrue(result["passed"], result)++ def test_profile_rejects_missing_declared_subject_region(self) -> None:+ profile = json.loads(PROFILE.read_text(encoding="utf-8"))+ profile["extensions"] = {+ "requiredSemanticRegions": ["face", "missing-garment"],+ }+ result = validate_profile(profile)+ self.assertFalse(result["passed"])+ self.assertTrue(any("missing declared required IDs" in error for error in result["errors"]))++ def test_profile_rejects_duplicate_region_id(self) -> None:+ profile = json.loads(PROFILE.read_text(encoding="utf-8"))+ profile["regions"].append(dict(profile["regions"][0]))+ result = validate_profile(profile)+ self.assertFalse(result["passed"])+ self.assertTrue(any("region IDs must be unique" in error for error in result["errors"]))++ def test_profile_rejects_empty_required_region_contract(self) -> None:+ profile = json.loads(PROFILE.read_text(encoding="utf-8"))+ profile["extensions"]["requiredSemanticRegions"] = []+ result = validate_profile(profile)+ self.assertFalse(result["passed"])+ self.assertTrue(any("must be a non-empty array" in error for error in result["errors"]))+if __name__ == "__main__":unittest.main()diff --git a/forge/tests/test_rigid_hair_binding.py b/forge/tests/test_rigid_hair_binding.pynew file mode 100644index 0000000..d430586--- /dev/null+++ b/forge/tests/test_rigid_hair_binding.py@@ -0,0 +1,294 @@+#!/usr/bin/env python3+"""Hair is rigidly parented, never geodesically skinned.++`bind()` weights every vertex of whatever mesh it is handed and has no notion of role, which is the+right contract for a distance solver and the wrong default for a character. Today nothing calls it+with a component tree -- `emit_rig.py` is still a milestone-0 proof that builds a single SkinnedMesh+-- so the defect has not shipped. The rule is being written before that wiring lands, not after.++`test_the_hazard_is_real` is the load-bearing one: it does the wrong thing on purpose and measures+the result, so the exclusion rests on a demonstrated number rather than on an argument.++Run: python3 forge/tests/test_rigid_hair_binding.py+"""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage5_rig"))++from geodesic_skinning import RIGID_ROLES, bind, partition_for_binding # noqa: E402+++def column(x0: float, x1: float, y0: float, y1: float, z0: float, z1: float,+ base: int = 0) -> tuple[list[list[float]], list[int]]:+ """A closed axis-aligned box: eight vertices, twelve triangles."""+ vertices = [[x, y, z] for x in (x0, x1) for y in (y0, y1) for z in (z0, z1)]+ faces = [+ (0, 1, 3), (0, 3, 2), (4, 7, 5), (4, 6, 7),+ (0, 4, 5), (0, 5, 1), (2, 3, 7), (2, 7, 6),+ (0, 2, 6), (0, 6, 4), (1, 5, 7), (1, 7, 3),+ ]+ indices = [base + i for face in faces for i in face]+ return vertices, indices+++def head_on_neck_with_hair() -> dict:+ """Neck below, head above, hair capping the head -- one merged mesh, as a rig would receive it.++ Deliberately built as ONE solid so the geodesic field can actually propagate from the neck up+ through the head into the hair. That connectivity is the hazard being measured.+ """+ vertices: list[list[float]] = []+ indices: list[int] = []+ for box in (+ (-0.15, 0.15, 0.00, 1.00, -0.15, 0.15), # neck+ (-0.40, 0.40, 1.00, 2.00, -0.40, 0.40), # head+ (-0.42, 0.42, 2.00, 2.20, -0.42, 0.42), # hair cap, sitting on the crown+ ):+ box_vertices, box_indices = column(*box, base=len(vertices))+ vertices.extend(box_vertices)+ indices.extend(box_indices)+ return {"vertices": vertices, "indices": indices}+++NECK_BONE = {"id": "neck", "jointPos": [0.0, 0.0, 0.0], "tipPos": [0.0, 1.0, 0.0]}+HEAD_BONE = {"id": "head", "jointPos": [0.0, 1.0, 0.0], "tipPos": [0.0, 1.9, 0.0]}+++def weight_of(result: dict, vertex: int, bone: str) -> float:+ """Total weight a named bone holds on one vertex.++ Summed rather than looked up: unused influence slots are padded with bone index 0 and weight+ 0.0, so building a dict from `zip(indices, weights)` lets a pad silently overwrite the real+ entry for bone 0. That mistake reported the neck's share of the crown as 0.000 when it is 0.081.+ """+ slot = result["boneOrder"].index(bone)+ return sum(+ weight+ for index, weight in zip(result["skinIndices"][vertex], result["skinWeights"][vertex])+ if index == slot+ )+++class TheHazardIsReal(unittest.TestCase):+ def test_the_neck_bone_reaches_the_crown_through_the_skull(self) -> None:+ """Skin the hair and the neck claims a real share of it, because the path runs through+ the head rather than around it.++ This is the measurement the exclusion rests on. Measured on this fixture at resolution 48:+ the geodesic distance from the neck to a crown vertex is 33.6 voxels against the head+ bone's 15.0, and with the falloff power of 3 that leaves the neck holding 8.1% of the+ crown. Turning the neck would drag the hair off the skull by that fraction -- and the+ `standProud` and `scalpExposure` guarantees are bind-pose checks that would never see it.+ """+ mesh = head_on_neck_with_hair()+ result = bind(mesh, [NECK_BONE, HEAD_BONE], resolution=48)++ crown = [i for i, v in enumerate(mesh["vertices"]) if v[1] >= 2.19]+ self.assertTrue(crown, "fixture has no crown vertices")++ worst = max(weight_of(result, index, "neck") for index in crown)+ self.assertGreater(+ worst, 0.05,+ "the neck bone was expected to hold a visible share of the crown; if it no longer "+ "does, re-derive whether hair still needs excluding rather than deleting the rule",+ )++ def test_every_influence_slot_is_accounted_for(self) -> None:+ """Guards the weight_of helper above -- the bug it documents cost a wrong conclusion."""+ mesh = head_on_neck_with_hair()+ result = bind(mesh, [NECK_BONE, HEAD_BONE], resolution=32)+ for index in range(len(mesh["vertices"])):+ total = weight_of(result, index, "neck") + weight_of(result, index, "head")+ self.assertAlmostEqual(total, 1.0, places=6)+++class ThePartition(unittest.TestCase):+ def test_hair_is_excluded_and_reported_not_dropped(self) -> None:+ partition = partition_for_binding([+ {"id": "neck", "role": "body"},+ {"id": "head", "role": "head", "parent": "neck"},+ {"id": "hair-crown", "role": "hair", "parent": "head"},+ ])+ self.assertEqual(partition["skinned"], ["neck", "head"])+ self.assertEqual(len(partition["rigidlyParented"]), 1)+ self.assertEqual(partition["rigidlyParented"][0]["id"], "hair-crown")+ self.assertEqual(partition["rigidlyParented"][0]["parentJoint"], "head")++ def test_all_four_rigid_roles_are_excluded(self) -> None:+ partition = partition_for_binding(+ [{"id": "head", "role": "head"}]+ + [{"id": role, "role": role, "parent": "head"} for role in sorted(RIGID_ROLES)]+ )+ self.assertEqual(partition["skinned"], ["head"])+ self.assertEqual(+ {entry["id"] for entry in partition["rigidlyParented"]}, set(RIGID_ROLES)+ )++ def test_a_lock_rides_the_first_SKINNED_ancestor_not_its_immediate_parent(self) -> None:+ """A lock parented to a hair mass rides the head; the mass is not a joint."""+ partition = partition_for_binding([+ {"id": "head", "role": "head"},+ {"id": "hair-mass", "role": "hair", "parent": "head"},+ {"id": "hair-lock", "role": "hair", "parent": "hair-mass"},+ ])+ joints = {entry["id"]: entry["parentJoint"] for entry in partition["rigidlyParented"]}+ self.assertEqual(joints["hair-lock"], "head")+ self.assertEqual(joints["hair-mass"], "head")++ def test_an_orphan_rigid_component_warns(self) -> None:+ partition = partition_for_binding([{"id": "hair-crown", "role": "hair"}])+ self.assertEqual(len(partition["warnings"]), 1)+ self.assertIn("no skinned ancestor", partition["warnings"][0])+ self.assertIsNone(partition["rigidlyParented"][0]["parentJoint"])++ def test_a_parent_cycle_terminates(self) -> None:+ partition = partition_for_binding([+ {"id": "a", "role": "hair", "parent": "b"},+ {"id": "b", "role": "hair", "parent": "a"},+ ])+ self.assertEqual(len(partition["warnings"]), 2)++ def test_the_role_set_is_overridable(self) -> None:+ """A caller that genuinely wants skinned hair must say so explicitly."""+ partition = partition_for_binding(+ [{"id": "head", "role": "head"}, {"id": "hair", "role": "hair", "parent": "head"}],+ rigid_roles=frozenset(),+ )+ self.assertEqual(partition["skinned"], ["head", "hair"])+ self.assertEqual(partition["rigidlyParented"], [])++ def test_components_without_ids_are_skipped_not_crashed_on(self) -> None:+ partition = partition_for_binding([{"role": "hair"}, None, {"id": "head", "role": "head"}])+ self.assertEqual(partition["skinned"], ["head"])++ def test_role_matching_is_case_insensitive(self) -> None:+ partition = partition_for_binding([+ {"id": "head", "role": "head"},+ {"id": "hair", "role": "Hair", "parent": "head"},+ ])+ self.assertEqual(partition["skinned"], ["head"])+++class BindReportsThePartition(unittest.TestCase):+ """The rule has to be reachable from `bind`, or it is a policy nobody is holding.++ An earlier version put `partition_for_binding` beside `bind` and left the two unconnected, so a+ caller doing the obvious thing -- hand `bind` a merged mesh -- got weights for the hair and no+ signal whatsoever that some of those weights should not exist.+ """++ COMPONENTS = [+ {"id": "neck", "role": "body"},+ {"id": "head", "role": "head", "parent": "neck"},+ {"id": "hair-crown", "role": "hair", "parent": "head"},+ ]++ def test_bind_carries_the_partition_when_given_components(self) -> None:+ result = bind(head_on_neck_with_hair(), [NECK_BONE, HEAD_BONE], resolution=24,+ components=self.COMPONENTS)+ partition = result["bindingPartition"]+ self.assertIsNotNone(partition)+ self.assertEqual([e["id"] for e in partition["rigidlyParented"]], ["hair-crown"])++ def test_bind_names_the_rigid_components_it_found(self) -> None:+ result = bind(head_on_neck_with_hair(), [NECK_BONE, HEAD_BONE], resolution=24,+ components=self.COMPONENTS)+ joined = " ".join(result["partitionWarnings"])+ self.assertIn("parented to a joint rather than skinned", joined)+ self.assertIn("hair", joined)++ def test_bind_without_components_behaves_exactly_as_before(self) -> None:+ """The parameter is additive; existing callers must not change behaviour."""+ plain = bind(head_on_neck_with_hair(), [NECK_BONE, HEAD_BONE], resolution=24)+ self.assertIsNone(plain["bindingPartition"])+ self.assertEqual(plain["partitionWarnings"], [])+ self.assertEqual(len(plain["skinWeights"]), len(head_on_neck_with_hair()["vertices"]))++ def test_a_tree_with_no_rigid_roles_produces_no_warning(self) -> None:+ result = bind(head_on_neck_with_hair(), [NECK_BONE, HEAD_BONE], resolution=24,+ components=[{"id": "neck", "role": "body"}, {"id": "head", "role": "head"}])+ self.assertEqual(result["partitionWarnings"], [])+ self.assertEqual(result["bindingPartition"]["rigidlyParented"], [])+++class BindActuallyExcludes(unittest.TestCase):+ """Reporting the partition is not enough. The obvious thing to do with a returned weight array+ is to use it, so weights that should not exist have to not exist.++ Rigid parenting expressed in the only language a skinned mesh speaks: weight 1.0 on the single+ joint the component rides, and nothing else.+ """++ COMPONENTS = [+ {"id": "neck", "role": "body"},+ {"id": "head", "role": "head", "parent": "neck"},+ {"id": "hair-crown", "role": "hair", "parent": "head"},+ ]+ OWNERS = ["neck"] * 8 + ["head"] * 8 + ["hair-crown"] * 8++ def mesh_with_owners(self) -> dict:+ mesh = head_on_neck_with_hair()+ mesh["vertexComponents"] = list(self.OWNERS)+ return mesh++ def hair_vertices(self) -> list[int]:+ return [i for i, owner in enumerate(self.OWNERS) if owner == "hair-crown"]++ def test_the_neck_loses_its_grip_on_the_crown_entirely(self) -> None:+ mesh = self.mesh_with_owners()+ without = bind(mesh, [NECK_BONE, HEAD_BONE], resolution=48)+ with_exclusion = bind(mesh, [NECK_BONE, HEAD_BONE], resolution=48,+ components=self.COMPONENTS)+ hair = self.hair_vertices()++ self.assertGreater(max(weight_of(without, i, "neck") for i in hair), 0.05)+ self.assertEqual(max(weight_of(with_exclusion, i, "neck") for i in hair), 0.0)++ def test_rigid_vertices_ride_their_joint_at_full_weight(self) -> None:+ result = bind(self.mesh_with_owners(), [NECK_BONE, HEAD_BONE], resolution=48,+ components=self.COMPONENTS)+ for index in self.hair_vertices():+ with self.subTest(vertex=index):+ self.assertEqual(weight_of(result, index, "head"), 1.0)++ def test_skinned_vertices_are_untouched(self) -> None:+ mesh = self.mesh_with_owners()+ plain = bind(mesh, [NECK_BONE, HEAD_BONE], resolution=48)+ excluded = bind(mesh, [NECK_BONE, HEAD_BONE], resolution=48, components=self.COMPONENTS)+ for index, owner in enumerate(self.OWNERS):+ if owner == "hair-crown":+ continue+ with self.subTest(vertex=index):+ self.assertEqual(plain["skinWeights"][index], excluded["skinWeights"][index])++ def test_the_count_of_pinned_vertices_is_reported(self) -> None:+ result = bind(self.mesh_with_owners(), [NECK_BONE, HEAD_BONE], resolution=48,+ components=self.COMPONENTS)+ self.assertEqual(result["rigidPinnedVertexCount"], 8)++ def test_without_vertexComponents_the_exclusion_says_it_could_not_run(self) -> None:+ """The one thing worse than not excluding is claiming to have excluded."""+ result = bind(head_on_neck_with_hair(), [NECK_BONE, HEAD_BONE], resolution=24,+ components=self.COMPONENTS)+ self.assertEqual(result["rigidPinnedVertexCount"], 0)+ self.assertTrue(any("could NOT be excluded" in w for w in result["partitionWarnings"]))++ def test_a_joint_that_is_not_among_the_bones_is_reported(self) -> None:+ result = bind(self.mesh_with_owners(), [NECK_BONE], resolution=24,+ components=self.COMPONENTS)+ self.assertTrue(any("not among the bones" in w for w in result["partitionWarnings"]))+ self.assertEqual(result["rigidPinnedVertexCount"], 0)++ def test_weights_still_sum_to_one_after_pinning(self) -> None:+ result = bind(self.mesh_with_owners(), [NECK_BONE, HEAD_BONE], resolution=48,+ components=self.COMPONENTS)+ for index in range(len(self.OWNERS)):+ with self.subTest(vertex=index):+ total = weight_of(result, index, "neck") + weight_of(result, index, "head")+ self.assertAlmostEqual(total, 1.0, places=6)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_scalp_exposure.py b/forge/tests/test_scalp_exposure.pynew file mode 100644index 0000000..30b6bdf--- /dev/null+++ b/forge/tests/test_scalp_exposure.py@@ -0,0 +1,339 @@+#!/usr/bin/env python3+"""Tests for the scalp exposure gate.++The gate exists to catch one recorded failure at build time. Widening the hair side masses by hand+took closure from 42.2% to 40.9%, worse on all six views, with dark coverage DOWN -- the widened+mass had slid off the skull and the render grew a bare strip. Nothing in the review path saw it;+only the eye did, three times running.++The decisive test here is `test_hair_that_sank_into_the_skull_is_not_coverage`: a gate that merely+asked "is there a hair vertex near this patch" would have passed that build, because the vertices+were still nearby -- they had sunk below the surface.++Run: python3 forge/tests/test_scalp_exposure.py+"""+import math+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage4_review"))++from scalp_field import ScalpField # noqa: E402+from scalp_exposure import largest_exposed_run, scalp_exposure # noqa: E402++HUMANOID_HEAD_RINGS = [+ [5.10, 0.145, 0.249], [5.28, 0.190, 0.311], [5.36, 0.356, 0.375], [5.44, 0.416, 0.400],+ [5.60, 0.398, 0.480], [5.76, 0.398, 0.515], [5.90, 0.356, 0.498], [6.04, 0.327, 0.440],+]++# The band above the hairline. The face is scalp by geometry and not by anatomy, so a full sweep+# would report the forehead and chin as bald.+CROWN_BAND = (0.55, 1.0)+++def shell(field: ScalpField, offset: float, u_count: int = 96, v_count: int = 48,+ v_range: tuple[float, float] = (0.0, 1.0),+ skip: object = None) -> list[tuple[float, float, float]]:+ """A dense layer of points sitting `offset` outside the skull.++ `skip` takes (u, v) and returns True where the layer should have a hole, which is how the bald+ strip cases below are built.+ """+ low, high = v_range+ points = []+ for j in range(v_count):+ v = low + (high - low) * (j + 0.5) / v_count+ for i in range(u_count):+ u = i / u_count+ if skip is not None and skip(u, v):+ continue+ px, py, pz = field.sample(u, v)+ nx, ny, nz = field.normal(u, v)+ points.append((px + nx * offset, py + ny * offset, pz + nz * offset))++ # The cap disc closing the top of the ring stack has no (u, v) and so is never produced by the+ # loop above. Real hair over a crown does cover it, and leaving it out of this helper is what+ # let a version of the gate that ignored the cap entirely look correct in these tests.+ if high >= 1.0 - 1e-9:+ top_rx, top_rz, top_zc = field.section(field.y_max)+ for ring_index in range(max(1, v_count // 4)):+ radius_fraction = (ring_index + 0.5) / max(1, v_count // 4)+ for i in range(u_count):+ u = i / u_count+ if skip is not None and skip(u, 1.0):+ continue+ angle = 2.0 * math.pi * u+ points.append((+ top_rx * radius_fraction * math.cos(angle),+ field.y_max + offset,+ top_zc + top_rz * radius_fraction * math.sin(angle),+ ))+ return points+++class FullCoverage(unittest.TestCase):+ def test_a_skull_fully_wrapped_reports_nothing_exposed(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, shell(field, 0.02), v_range=CROWN_BAND)+ self.assertEqual(result["exposedFraction"], 0.0)+ self.assertEqual(result["verdict"], "pass")+ self.assertEqual(result["exposedSamples"], [])++ def test_no_hair_at_all_reports_everything_exposed(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, [], v_range=CROWN_BAND)+ self.assertEqual(result["exposedFraction"], 1.0)+ self.assertEqual(result["verdict"], "fail")++ def test_hair_beyond_reach_does_not_count_as_coverage(self) -> None:+ """A mass floating clear of the head is a separate object, not the layer that covers it."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ height = field.y_max - field.y_min+ result = scalp_exposure(field, shell(field, height * 0.9), v_range=CROWN_BAND)+ self.assertGreater(result["exposedFraction"], 0.9)+++class TheRecordedFailure(unittest.TestCase):+ def test_hair_that_sank_into_the_skull_is_not_coverage(self) -> None:+ """The TRY2 failure, encoded.++ Every point is close to the scalp -- a nearest-neighbour test would call this covered. Every+ point is also INSIDE the skull, which is exactly what a widened straight-spine loft does+ against a convex skull, and what renders as bald.+ """+ field = ScalpField(HUMANOID_HEAD_RINGS)+ sunk = shell(field, -0.012)+ result = scalp_exposure(field, sunk, v_range=CROWN_BAND)+ self.assertEqual(result["exposedFraction"], 1.0)+ self.assertEqual(result["verdict"], "fail")+ self.assertEqual(result["hairPointsInsideSkull"], len(sunk))++ def test_a_partial_sink_exposes_only_the_sunk_region(self) -> None:+ """Half the hair proud, half sunk: the gate must localise, not just alarm."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ points = (+ shell(field, 0.02, skip=lambda u, v: u < 0.5)+ + shell(field, -0.012, skip=lambda u, v: u >= 0.5)+ )+ result = scalp_exposure(field, points, v_range=CROWN_BAND)+ self.assertGreater(result["exposedFraction"], 0.35)+ self.assertLess(result["exposedFraction"], 0.65)+ for sample in result["exposedSamples"]:+ self.assertLess(sample["u"], 0.55)+++class BaldStrips(unittest.TestCase):+ def test_a_strip_is_found_and_its_area_is_about_right(self) -> None:+ """A quarter of the azimuth left bare must read as about a quarter of the area."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ points = shell(field, 0.02, skip=lambda u, v: 0.25 <= u < 0.5)+ result = scalp_exposure(field, points, v_range=CROWN_BAND)+ self.assertAlmostEqual(result["exposedFraction"], 0.25, delta=0.05)+ self.assertEqual(result["verdict"], "fail")++ def test_the_strip_is_reported_where_it_actually_is(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ points = shell(field, 0.02, skip=lambda u, v: 0.25 <= u < 0.5)+ result = scalp_exposure(field, points, v_range=CROWN_BAND)+ self.assertTrue(result["exposedSamples"])+ for sample in result["exposedSamples"]:+ self.assertTrue(0.20 <= sample["u"] <= 0.55, f"unexpected exposure at u={sample['u']}")++ def test_a_strip_reads_as_a_run_and_scattered_holes_do_not(self) -> None:+ """A run is a parting a viewer sees; a scatter is sampling noise."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ strip = scalp_exposure(field, shell(field, 0.02, skip=lambda u, v: 0.25 <= u < 0.5),+ v_range=CROWN_BAND)+ self.assertGreaterEqual(largest_exposed_run(strip), 6)++ scatter = scalp_exposure(+ field,+ shell(field, 0.02, skip=lambda u, v: int(u * 96) % 24 == 0),+ v_range=CROWN_BAND,+ )+ self.assertLessEqual(largest_exposed_run(scatter), 2)++ def test_a_bare_crown_cap_is_found(self) -> None:+ """The exact shape of the recorded failure: hair present at the sides, gone off the top."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ points = shell(field, 0.02, skip=lambda u, v: v > 0.88)+ result = scalp_exposure(field, points, v_range=CROWN_BAND)+ self.assertGreater(result["exposedFraction"], 0.10)+ for sample in result["exposedSamples"]:+ self.assertGreater(sample["v"], 0.80)+++class TheCapDisc(unittest.TestCase):+ """The flat disc closing the top of the ring stack, which has no (u, v) of its own.++ The parametrisation walks v from the bottom ring to the top and samples the ELLIPSE at each+ height, so nothing ever visits the disc that closes the stack. On a skull whose top ring still+ has real radius that disc IS the crown -- and a completely bare crown scored exposedFraction 0.0+ and passed. The one place a bald patch shows most was the one place the gate could not look.+ """++ def test_a_bare_cap_is_now_found(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, shell(field, 0.02, skip=lambda u, v: v > 0.97),+ v_range=CROWN_BAND)+ self.assertGreater(result["exposedFraction"], 0.15)+ self.assertEqual(result["verdict"], "fail")++ def test_the_cap_samples_are_labelled_so_a_caller_can_tell_where(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, shell(field, 0.02, skip=lambda u, v: v > 0.97),+ v_range=CROWN_BAND)+ cap = [s for s in result["exposedSamples"] if s.get("cap")]+ self.assertTrue(cap)+ for sample in cap:+ self.assertAlmostEqual(sample["y"], field.y_max, places=6)++ def test_a_covered_cap_reports_nothing(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, shell(field, 0.02), v_range=CROWN_BAND)+ self.assertEqual(result["exposedFraction"], 0.0)++ def test_a_band_that_stops_below_the_crown_does_not_sample_the_cap(self) -> None:+ """Asking about the temples should not report the crown."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, [], v_range=(0.4, 0.7))+ self.assertFalse([s for s in result["exposedSamples"] if s.get("cap")])+++class ExposedRuns(unittest.TestCase):+ def test_a_fully_exposed_ring_reports_the_whole_ring(self) -> None:+ """Every column's predecessor is also exposed, so the run-start scan finds no start and+ fell through reporting zero -- the worst case reporting as the best."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, [], v_range=CROWN_BAND)+ self.assertEqual(largest_exposed_run(result), 32)++ def test_a_partial_run_is_still_measured_as_a_run(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, shell(field, 0.02, skip=lambda u, v: 0.25 <= u < 0.5),+ v_range=CROWN_BAND)+ run = largest_exposed_run(result)+ self.assertGreaterEqual(run, 6)+ self.assertLess(run, 32)+++class AreaWeighting(unittest.TestCase):+ def test_the_fraction_is_area_weighted_not_sample_counted(self) -> None:+ """A small bare crown must not hide behind a large well-covered band.++ On a strongly tapered skull the top ring holds the same NUMBER of samples as the bottom but+ a small fraction of the area, so the two weightings give visibly different answers.+ """+ field = ScalpField([[0.0, 1.0, 1.0], [1.0, 0.1, 0.1]])+ points = shell(field, 0.02, skip=lambda u, v: v > 0.5)+ result = scalp_exposure(field, points)+ by_count = len(result["exposedSamples"]) / result["sampleCount"]++ # Roughly the upper half of the samples are bare either way -- the exact row count depends+ # on how far the reach march lets the topmost covered row extend upward, which is a sampling+ # detail and not the property under test.+ self.assertGreater(by_count, 0.3)+ # The property under test: on a skull that tapers 10:1, that same bare region is a far+ # smaller share of the AREA, and the gate must report the smaller, truer number.+ self.assertLess(result["exposedFraction"], by_count * 0.6)+++class TheFailureIsRealInPixels(unittest.TestCase):+ """The geometric gate above is only worth having if the failure it models actually happened.++ This measures scalp showing through the crown band of the saved renders: light pixels inside the+ top 9% of the figure, where the hair mass should be. It is a PROXY, not a bald-fraction -- lit+ hair also reads light, which is why the absolute numbers sit near 50% rather than near zero. The+ signal is the CHANGE, and it is unambiguous. Measured 2026-08-07 on the archived captures:++ view TRY1 TRY2 delta+ orbit-plus-35 54.0% 68.9% +14.9+ profile 48.8% 55.1% +6.3+ front 53.3% 57.6% +4.3+ orbit-minus-35 43.3% 44.3% +1.0++ Widening the side masses raised scalp exposure on every view, worst on the exact view where the+ bare crown was visible by eye. That is the mechanism this module encodes: the mass slid off the+ skull instead of growing on it.+ """++ BAND = 0.09+ LIGHT = 110.0++ def crown_light_fraction(self, png: Path) -> float:+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))+ from extract_pbr_evidence import build_foreground_mask, load_image # noqa: PLC0415++ width, height, pixels, _ = load_image(png)+ mask, _, _ = build_foreground_mask(width, height, pixels)+ rows = [i // width for i, on in enumerate(mask) if on]+ columns = [i % width for i, on in enumerate(mask) if on]+ if not rows:+ self.fail(f"{png.name} has an empty foreground mask")+ top, bottom = min(rows), max(rows)+ band_bottom = top + int((bottom - top + 1) * self.BAND)++ light = total = 0+ for y in range(top, band_bottom + 1):+ for x in range(min(columns), max(columns) + 1):+ index = y * width + x+ if not mask[index]:+ continue+ r, g, b, _ = pixels[index]+ total += 1+ if 0.2126 * r + 0.7152 * g + 0.0722 * b > self.LIGHT:+ light += 1+ return light / total if total else 0.0++ def test_widening_the_side_masses_raised_scalp_exposure_on_every_view(self) -> None:+ from showcase_test_support import showcase_root # noqa: PLC0415++ captures = showcase_root() / "artifacts" / "low-poly-humanoid-glb"+ if not (captures / "TRY1").is_dir() or not (captures / "TRY2").is_dir():+ raise unittest.SkipTest("archived TRY1/TRY2 captures are not in this checkout")++ for view in ("orbit-plus-35", "orbit-minus-35", "front", "profile"):+ before = captures / "TRY1" / f"procedural-factory.{view}.png"+ after = captures / "TRY2" / f"procedural-factory.{view}.png"+ if not before.is_file() or not after.is_file():+ continue+ with self.subTest(view=view):+ self.assertGreater(+ self.crown_light_fraction(after),+ self.crown_light_fraction(before),+ f"{view}: widening the masses should have raised scalp exposure",+ )+++class Contract(unittest.TestCase):+ def test_the_uncalibrated_threshold_is_declared_as_such(self) -> None:+ """No multipart hair reference exists yet, so this bound is chosen, not measured."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ result = scalp_exposure(field, shell(field, 0.02), v_range=CROWN_BAND)+ self.assertTrue(result["hardMaxUncalibrated"])++ def test_a_degenerate_band_is_rejected(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for bad in ((0.5, 0.5), (0.8, 0.2), (-0.1, 0.5), (0.5, 1.4)):+ with self.subTest(bad=bad):+ with self.assertRaises(ValueError):+ scalp_exposure(field, [], v_range=bad)++ def test_non_positive_reach_is_rejected(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ with self.assertRaises(ValueError):+ scalp_exposure(field, [], reach=0.0)++ def test_the_report_counts_what_it_discarded(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ proud = shell(field, 0.02, u_count=24, v_count=12)+ sunk = shell(field, -0.02, u_count=24, v_count=12)+ result = scalp_exposure(field, proud + sunk, v_range=CROWN_BAND)+ self.assertEqual(result["hairPointCount"], len(proud) + len(sunk))+ self.assertEqual(result["hairPointsInsideSkull"], len(sunk))+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_scalp_field.py b/forge/tests/test_scalp_field.pynew file mode 100644index 0000000..1b3f3ac--- /dev/null+++ b/forge/tests/test_scalp_field.py@@ -0,0 +1,284 @@+#!/usr/bin/env python3+"""Tests for the scalp signed distance field.++The field exists because hair was held off the skull by a comment while the garment in the same file+was held off the body by a measurement. The measured failure it prevents: widening the hair side+masses by hand took closure from 42.2% to 40.9%, worse on all six views, with dark coverage going+DOWN because the widened mass slid off the skull rather than growing on it.++Run: python3 forge/tests/test_scalp_field.py+"""+import math+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))++from scalp_field import ScalpField, field_from_component, normalise_rings # noqa: E402++# The humanoid demo's actual head: eight rows of [y, radiusX, radiusZ] with a parallel z-offset+# array. Carried verbatim so the tests exercise a real skull rather than a tidy synthetic one.+HUMANOID_HEAD_RINGS = [+ [5.10, 0.145, 0.249], [5.28, 0.190, 0.311], [5.36, 0.356, 0.375], [5.44, 0.416, 0.400],+ [5.60, 0.398, 0.480], [5.76, 0.398, 0.515], [5.90, 0.356, 0.498], [6.04, 0.327, 0.440],+]+HUMANOID_HEAD_OFFSETS = [0.010, 0.010, 0.02, 0.06, 0.05, 0.03, -0.01, -0.03]++CYLINDER = [[0.0, 1.0, 1.0], [2.0, 1.0, 1.0]]+++class Validation(unittest.TestCase):+ def test_one_ring_is_rejected(self) -> None:+ with self.assertRaises(ValueError):+ ScalpField([[0.0, 1.0, 1.0]])++ def test_zero_or_negative_radius_is_rejected(self) -> None:+ for bad in ([[0.0, 0.0, 1.0], [1.0, 1.0, 1.0]], [[0.0, 1.0, -0.5], [1.0, 1.0, 1.0]]):+ with self.subTest(bad=bad):+ with self.assertRaises(ValueError):+ ScalpField(bad)++ def test_duplicate_heights_are_rejected(self) -> None:+ with self.assertRaises(ValueError):+ ScalpField([[1.0, 0.5, 0.5], [1.0, 0.6, 0.6]])++ def test_non_finite_values_are_rejected(self) -> None:+ for bad in (float("nan"), float("inf")):+ with self.subTest(bad=bad):+ with self.assertRaises(ValueError):+ ScalpField([[0.0, 1.0, 1.0], [bad, 1.0, 1.0]])++ def test_rings_are_sorted_not_assumed_sorted(self) -> None:+ field = ScalpField([[2.0, 1.0, 1.0], [0.0, 0.5, 0.5]])+ self.assertEqual(field.y_min, 0.0)+ self.assertEqual(field.y_max, 2.0)++ def test_mapping_and_tuple_forms_agree(self) -> None:+ tuples = ScalpField([[0.0, 1.0, 2.0, 0.1], [1.0, 1.5, 2.5, 0.2]])+ mappings = ScalpField([+ {"y": 0.0, "rx": 1.0, "rz": 2.0, "zc": 0.1},+ {"y": 1.0, "radiusX": 1.5, "radiusZ": 2.5, "zCentre": 0.2},+ ])+ self.assertAlmostEqual(tuples.distance(1.2, 0.5, 0.0), mappings.distance(1.2, 0.5, 0.0))++ def test_wrong_arity_is_rejected(self) -> None:+ with self.assertRaises(ValueError):+ normalise_rings([[0.0, 1.0], [1.0, 1.0]])+++class SignIsExact(unittest.TestCase):+ """The magnitude is a first-order estimate; the sign is the part gates may rely on."""++ def test_axis_is_inside(self) -> None:+ field = ScalpField(CYLINDER)+ self.assertLess(field.distance(0.0, 1.0, 0.0), 0.0)++ def test_far_outside_is_positive(self) -> None:+ field = ScalpField(CYLINDER)+ self.assertGreater(field.distance(10.0, 1.0, 0.0), 0.0)++ def test_sign_flips_exactly_at_the_surface(self) -> None:+ field = ScalpField(CYLINDER)+ self.assertLess(field.distance(0.999, 1.0, 0.0), 0.0)+ self.assertGreater(field.distance(1.001, 1.0, 0.0), 0.0)+ self.assertAlmostEqual(field.distance(1.0, 1.0, 0.0), 0.0, places=9)++ def test_an_elliptical_section_is_not_treated_as_a_circle(self) -> None:+ field = ScalpField([[0.0, 1.0, 0.25], [1.0, 1.0, 0.25]])+ # Inside on the wide axis, outside on the narrow one, at the same radius.+ self.assertLess(field.distance(0.5, 0.5, 0.0), 0.0)+ self.assertGreater(field.distance(0.0, 0.5, 0.5), 0.0)++ def test_the_z_offset_moves_the_section(self) -> None:+ field = ScalpField([[0.0, 1.0, 1.0, 5.0], [1.0, 1.0, 1.0, 5.0]])+ self.assertLess(field.distance(0.0, 0.5, 5.0), 0.0)+ self.assertGreater(field.distance(0.0, 0.5, 0.0), 0.0)++ def test_a_surface_sample_reads_zero(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for u in (0.0, 0.2, 0.5, 0.77):+ for v in (0.25, 0.5, 0.75):+ x, y, z = field.sample(u, v)+ with self.subTest(u=u, v=v):+ self.assertAlmostEqual(field.distance(x, y, z), 0.0, places=6)+++class Caps(unittest.TestCase):+ def test_above_the_stack_is_outside(self) -> None:+ field = ScalpField(CYLINDER)+ self.assertGreater(field.distance(0.0, 3.0, 0.0), 0.0)++ def test_below_the_stack_is_outside(self) -> None:+ field = ScalpField(CYLINDER)+ self.assertGreater(field.distance(0.0, -1.0, 0.0), 0.0)++ def test_the_axial_gap_is_the_distance_above_the_cap(self) -> None:+ field = ScalpField(CYLINDER)+ self.assertAlmostEqual(field.distance(0.0, 2.5, 0.0), 0.5, places=6)++ def test_a_corner_combines_both_gaps(self) -> None:+ field = ScalpField(CYLINDER)+ # Both gaps contribute, so the corner reads further out than either alone.+ radial_only = field.distance(2.0, 1.0, 0.0)+ axial_only = field.distance(0.0, 2.5, 0.0)+ corner = field.distance(2.0, 2.5, 0.0)+ self.assertGreater(corner, radial_only)+ self.assertGreater(corner, axial_only)+ self.assertAlmostEqual(corner, math.hypot(radial_only, axial_only), places=9)+++class EstimateErrsSafely(unittest.TestCase):+ """The magnitude is `f / |grad f|`, not the true distance. Which WAY it errs decides whether a+ clearance gate built on it is safe, so the direction is pinned here rather than left to luck.++ For a circle of radius R at distance d from the axis the estimate is (d-R)(d+R)/2d against a+ true distance of |d-R|, so the ratio is (d+R)/2d: below 1 outside, above 1 inside. Outside it+ UNDERSTATES how clear a point is and inside it OVERSTATES how deep it is. Both readings make a+ `standProud` march push further than strictly necessary, which is the safe direction -- the+ failure being prevented is hair sitting inside the skull and rendering as a bald patch.+ """++ def test_outside_the_estimate_never_overstates_clearance(self) -> None:+ field = ScalpField(CYLINDER)+ for d in (1.05, 1.5, 2.0, 5.0):+ with self.subTest(d=d):+ self.assertLess(field.distance(d, 1.0, 0.0), d - 1.0)+ self.assertGreater(field.distance(d, 1.0, 0.0), 0.0)++ def test_inside_the_estimate_never_understates_depth(self) -> None:+ field = ScalpField(CYLINDER)+ for d in (0.2, 0.5, 0.95):+ with self.subTest(d=d):+ self.assertLess(field.distance(d, 1.0, 0.0), -(1.0 - d) + 1e-12)++ def test_the_estimate_converges_at_the_surface(self) -> None:+ """Where it matters most -- a vertex being marched to clearance -- the error vanishes."""+ field = ScalpField(CYLINDER)+ for d in (0.999, 1.001):+ with self.subTest(d=d):+ self.assertAlmostEqual(field.distance(d, 1.0, 0.0), d - 1.0, places=5)++ def test_nothing_returns_nan(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for point in ((0, 0, 0), (0, 100, 0), (0, -100, 0), (1e6, 5.5, 1e6), (0.0, 5.10, 0.0)):+ with self.subTest(point=point):+ self.assertTrue(math.isfinite(field.distance(*point)))+++class Normals(unittest.TestCase):+ def test_a_cylinder_normal_is_radial(self) -> None:+ field = ScalpField(CYLINDER)+ nx, ny, nz = field.normal(0.0, 0.5)+ self.assertAlmostEqual(nx, 1.0, places=5)+ self.assertAlmostEqual(ny, 0.0, places=5)+ self.assertAlmostEqual(nz, 0.0, places=5)++ def test_normals_are_unit_length(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for u in (0.0, 0.13, 0.5, 0.9):+ for v in (0.1, 0.5, 0.95):+ with self.subTest(u=u, v=v):+ self.assertAlmostEqual(math.dist((0, 0, 0), field.normal(u, v)), 1.0, places=6)++ def test_normals_point_outward(self) -> None:+ """Stepping along the normal must leave the skull; stepping against it must enter."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for u in (0.0, 0.25, 0.5, 0.75):+ for v in (0.2, 0.5, 0.8):+ x, y, z = field.sample(u, v)+ nx, ny, nz = field.normal(u, v)+ with self.subTest(u=u, v=v):+ self.assertGreater(field.distance(x + nx * 0.01, y + ny * 0.01, z + nz * 0.01), 0.0)+ self.assertLess(field.distance(x - nx * 0.01, y - ny * 0.01, z - nz * 0.01), 0.0)++ def test_a_tapering_stack_tilts_its_normal_upward(self) -> None:+ """A radial approximation would push crown hair sideways off the top of the head."""+ field = ScalpField([[0.0, 1.0, 1.0], [1.0, 0.2, 0.2]])+ _, ny, _ = field.normal(0.0, 0.5)+ self.assertGreater(ny, 0.3)+++class SurfaceSamples(unittest.TestCase):+ def test_samples_carry_area_weight_not_count(self) -> None:+ """A narrow crown ring must not weigh the same as a wide temple ring."""+ field = ScalpField([[0.0, 1.0, 1.0], [1.0, 0.1, 0.1]])+ band = [s for s in field.surface_samples(16, 8) if not s["cap"]]+ self.assertGreater(band[0]["weight"], band[-1]["weight"] * 3.0)++ def test_every_band_sample_lies_on_the_surface(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for sample in field.surface_samples(12, 6):+ if sample["cap"]:+ continue+ self.assertAlmostEqual(field.distance(*sample["point"]), 0.0, places=6)++ def test_the_cap_disc_is_sampled(self) -> None:+ """The disc closing the stack belongs to no (u, v), so a caller iterating the band alone+ never sees it. On a skull whose top ring has real radius that disc IS the crown, and a+ completely bare crown measured as fully covered."""+ field = ScalpField(HUMANOID_HEAD_RINGS)+ cap = [s for s in field.surface_samples(16, 8) if s["cap"]]+ self.assertTrue(cap)+ for sample in cap:+ self.assertAlmostEqual(sample["point"][1], field.y_max, places=9)+ self.assertEqual(sample["normal"], (0.0, 1.0, 0.0))++ def test_the_cap_carries_the_disc_area(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ rx, rz, _ = field.section(field.y_max)+ cap_area = sum(s["weight"] for s in field.surface_samples(24, 12) if s["cap"])+ self.assertAlmostEqual(cap_area, math.pi * rx * rz, places=6)++ def test_a_band_that_stops_short_has_no_cap(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ self.assertFalse([s for s in field.surface_samples(12, 6, v_range=(0.2, 0.8)) if s["cap"]])++ def test_the_band_range_is_honoured(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for sample in field.surface_samples(12, 6, v_range=(0.4, 0.7)):+ self.assertGreaterEqual(sample["v"], 0.4)+ self.assertLessEqual(sample["v"], 0.7)++ def test_a_degenerate_band_is_rejected(self) -> None:+ field = ScalpField(HUMANOID_HEAD_RINGS)+ for bad in ((0.5, 0.5), (0.8, 0.2), (-0.1, 0.5), (0.5, 1.4)):+ with self.subTest(bad=bad):+ with self.assertRaises(ValueError):+ field.surface_samples(12, 6, v_range=bad)++ def test_degenerate_sample_counts_are_rejected(self) -> None:+ field = ScalpField(CYLINDER)+ for u_count, v_count in ((2, 4), (8, 1)):+ with self.subTest(u_count=u_count, v_count=v_count):+ with self.assertRaises(ValueError):+ field.surface_samples(u_count, v_count)+++class FromComponent(unittest.TestCase):+ def test_the_parallel_offset_array_form_is_accepted(self) -> None:+ field = field_from_component({+ "geometryDescriptor": {+ "ringStack": {"rings": HUMANOID_HEAD_RINGS, "zOffsets": HUMANOID_HEAD_OFFSETS}+ }+ })+ self.assertEqual(len(field.rings), 8)+ # The offset must actually be applied: ring 3 sits 0.06 forward.+ _, _, zc = field.section(5.44)+ self.assertAlmostEqual(zc, 0.06, places=9)++ def test_a_mismatched_offset_array_is_an_error_not_a_silent_truncation(self) -> None:+ with self.assertRaises(ValueError):+ field_from_component({+ "geometryDescriptor": {"ringStack": {"rings": HUMANOID_HEAD_RINGS, "zOffsets": [0.0]}}+ })++ def test_missing_descriptor_shapes_raise(self) -> None:+ for component in ({}, {"geometryDescriptor": {}}, {"geometryDescriptor": {"ringStack": {}}}):+ with self.subTest(component=component):+ with self.assertRaises(ValueError):+ field_from_component(component)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_sdf_primitives.py b/forge/tests/test_sdf_primitives.pyindex 5b10eca..21bcb93 100644--- a/forge/tests/test_sdf_primitives.py+++ b/forge/tests/test_sdf_primitives.py@@ -6,6 +6,8 @@ from __future__ import annotationsimport jsonimport mathimport sys+import shutil+import subprocessimport unittestfrom pathlib import Path@@ -234,7 +236,13 @@ class SdfPrimitiveContractTest(unittest.TestCase):self.assertIn("function polygonizeSdf", generated)polygonizer_start = generated.index("function polygonizeSdf")polygonizer_end = generated.index("return geometry;", polygonizer_start)- self.assertIn("computeVertexNormals()", generated[polygonizer_start:polygonizer_end])+ body = generated[polygonizer_start:polygonizer_end]+ # Normals come from the field gradient, which is the implicit surface's exact normal.+ # `computeVertexNormals` averaged face normals and carried the sampling grid's imprint into+ # the shading; this assertion used to require it and so encoded the old voxel extractor.+ self.assertIn("setAttribute('normal'", body)+ self.assertIn("const gradient = ", body)+ self.assertNotIn("computeVertexNormals()", body)for marker in ('"type": "capsule"','"type": "smooth-union"',@@ -256,5 +264,165 @@ class SdfPrimitiveContractTest(unittest.TestCase):self.assertIn(".invert()", generated)++class ImplicitSurfaceIsSmooth(unittest.TestCase):+ """An implicit surface must not be a voxel shell.++ The polygonizer used to emit one axis-aligned quad per exposed voxel face, so every vertex sat+ exactly on a grid plane and every edge was a 90-degree step. That is the wrong output for the+ only kind of subject anyone reaches for an implicit surface to build — a smooth blended organic+ form — and it is worse than the assembled primitives it replaces.+ """++ SPHERE = {+ "primitives": [{"id": "ball", "type": "sphere", "radius": 0.6,+ "transform": {"position": [0, 0, 0]}}],+ "operations": [],+ "resolution": 24,+ "bounds": {"min": [-1, -1, -1], "max": [1, 1, 1]},+ }++ def _mesh(self, sdf):+ node = shutil.which("node")+ if node is None:+ self.fail("node is required to execute the emitted polygonizer")+ showcase = Path(__file__).resolve().parents[2].parent / "img2threejs-showcase"+ if not (showcase / "node_modules" / "three").is_dir():+ self.skipTest(f"three is not installed at {showcase / 'node_modules' / 'three'}")+ spec = load_fixture()+ component = spec["componentTree"][0]+ component["geometryDescriptor"]["sdf"] = sdf+ source = generate(spec, "blockout")+ work = showcase / "node_modules" / ".cache" / "sdf-smoothness"+ work.mkdir(parents=True, exist_ok=True)+ entry = work / "factory.ts"+ entry.write_text(source, encoding="utf-8")+ subprocess.run(+ [str(showcase / "node_modules" / ".bin" / "esbuild"), str(entry), "--bundle",+ "--format=esm", "--platform=node", "--external:three",+ f"--outfile={work / 'factory.mjs'}", "--log-level=error"],+ check=True, capture_output=True, text=True, cwd=showcase,+ )+ export = next(name for name in ("createImplicitCharacterTorsoLimbModel",)+ if name in source) if False else None+ harness = work / "run.mjs"+ harness.write_text(+ "import * as factory from './factory.mjs';\n"+ "const create = Object.entries(factory).find(([k, v]) =>\n"+ " k.startsWith('create') && k.endsWith('Model') && typeof v === 'function')[1];\n"+ "const model = create({});\n"+ "let out = null;\n"+ "model.traverse((o) => { if (o.isMesh && !out) { const g = o.geometry;\n"+ " out = { positions: Array.from(g.getAttribute('position').array),\n"+ " normals: Array.from(g.getAttribute('normal').array),\n"+ " indices: Array.from(g.getIndex().array) }; } });\n"+ "console.log(JSON.stringify(out));\n",+ encoding="utf-8",+ )+ result = subprocess.run([node, str(harness)], capture_output=True, text=True, cwd=work)+ self.assertEqual(result.returncode, 0, result.stderr)+ return json.loads(result.stdout)++ def test_vertices_do_not_sit_on_the_sampling_grid_planes(self):+ """The voxel shell's signature: every coordinate is an exact multiple of the cell size."""+ mesh = self._mesh(self.SPHERE)+ step = 2.0 / self.SPHERE["resolution"]+ offsets = []+ for value in mesh["positions"]:+ local = ((value + 1.0) / step) % 1.0+ offsets.append(min(local, 1.0 - local))+ on_grid = sum(1 for offset in offsets if offset < 1e-6) / len(offsets)+ self.assertLess(on_grid, 0.5, "most vertices lie exactly on grid planes — voxel shell")++ def test_the_recovered_surface_is_close_to_the_sphere_it_was_sampled_from(self):+ mesh = self._mesh(self.SPHERE)+ radii = [+ math.dist((0.0, 0.0, 0.0), mesh["positions"][i:i + 3])+ for i in range(0, len(mesh["positions"]), 3)+ ]+ mean = sum(radii) / len(radii)+ self.assertAlmostEqual(mean, 0.6, delta=0.03)+ spread = max(abs(r - 0.6) for r in radii)+ self.assertLess(spread, 0.06, "surface deviates from the sampled sphere by more than a cell")++ def test_the_surface_encloses_a_positive_volume(self):+ """Winding, which the normals cannot reveal.++ Gradient normals are outward whatever the triangle order is, so an inverted winding shows+ only as back-face culling removing the front surface — the model renders as a hollow shell+ with its interior visible, which reads as a modelling fault rather than a winding one.+ """+ mesh = self._mesh(self.SPHERE)+ total = 0.0+ indices = mesh["indices"]+ positions = mesh["positions"]+ for i in range(0, len(indices), 3):+ a = positions[indices[i] * 3:indices[i] * 3 + 3]+ b = positions[indices[i + 1] * 3:indices[i + 1] * 3 + 3]+ c = positions[indices[i + 2] * 3:indices[i + 2] * 3 + 3]+ cross = (b[1] * c[2] - b[2] * c[1], b[2] * c[0] - b[0] * c[2], b[0] * c[1] - b[1] * c[0])+ total += (a[0] * cross[0] + a[1] * cross[1] + a[2] * cross[2]) / 6.0+ self.assertGreater(total, 0.0, "implicit surface is inside-out")+ # 4/3 pi r^3 for r = 0.6 is 0.905; surface nets on a 24-cell grid lands a little under.+ self.assertAlmostEqual(total, 0.905, delta=0.06)++ # A sphere whose surface pushes out through the six face centres of its own sampling box:+ # face centres sit at 1.0, the radius is 1.25, and the corners at sqrt(3) stay outside. The+ # in-bounds SPHERE above never exercises the boundary planes, which is why the quad pass could+ # read a cell index of `resolution` for years without a test noticing.+ SPHERE_THROUGH_BOUNDS = {+ "primitives": [{"id": "ball", "type": "sphere", "radius": 1.25,+ "transform": {"position": [0, 0, 0]}}],+ "operations": [],+ "resolution": 24,+ "bounds": {"min": [-1, -1, -1], "max": [1, 1, 1]},+ }++ def test_a_surface_reaching_its_sampling_bounds_emits_no_stray_index(self):+ """The quad pass must not index a cell that does not exist.++ Each quad joins the four cells sharing one grid edge. Bounding only the edge axis and the+ lower end of the other two let an index reach `resolution` -- a corner coordinate, not a cell+ coordinate -- so `cellAt` either aliased into an unrelated slot or read past the array, where+ a typed-array read gives `undefined`. `undefined < 0` is false, so it survived the guard in+ `quad` and reached `setIndex`, which coerces it to 0: triangles wired to whichever vertex+ happens to be first. A range check cannot catch that (0 is a valid index), so this measures+ edge length instead -- adjacent cells are at most a few cells apart, and a stray index+ produces an edge spanning the model.+ """+ mesh = self._mesh(self.SPHERE_THROUGH_BOUNDS)+ indices, positions = mesh["indices"], mesh["positions"]+ self.assertGreater(len(indices), 0, "no surface was emitted at all")++ step = 2.0 / self.SPHERE_THROUGH_BOUNDS["resolution"]+ longest = 0.0+ for i in range(0, len(indices), 3):+ triangle = [positions[indices[i + k] * 3:indices[i + k] * 3 + 3] for k in range(3)]+ for a, b in ((0, 1), (1, 2), (2, 0)):+ longest = max(longest, math.dist(triangle[a], triangle[b]))++ # Two cells sharing a grid edge are at most one cell apart per axis, so a legitimate edge+ # cannot exceed a couple of cell diagonals. Six cells is loose and still far below the+ # model-spanning edges a stray index produces.+ self.assertLess(+ longest, 6 * step,+ f"longest triangle edge {longest:.4f} exceeds {6 * step:.4f}; an index points at a cell "+ f"that is not adjacent, which is the signature of an out-of-range or aliased cell read",+ )++ def test_normals_point_outward_and_are_unit_length(self):+ mesh = self._mesh(self.SPHERE)+ checked = 0+ for i in range(0, len(mesh["positions"]), 3):+ position = mesh["positions"][i:i + 3]+ normal = mesh["normals"][i:i + 3]+ length = math.sqrt(sum(component * component for component in normal))+ self.assertAlmostEqual(length, 1.0, places=4)+ dot = sum(p * n for p, n in zip(position, normal))+ self.assertGreater(dot, 0.0, "normal points into the solid")+ checked += 1+ self.assertGreater(checked, 100)++if __name__ == "__main__":unittest.main(verbosity=2)diff --git a/forge/tests/test_stand_proud.py b/forge/tests/test_stand_proud.pynew file mode 100644index 0000000..73944f4--- /dev/null+++ b/forge/tests/test_stand_proud.py@@ -0,0 +1,177 @@+#!/usr/bin/env python3+"""Tests for the `standProud` component property.++The property exists because the humanoid demo holds the same requirement twice and gets two+different outcomes: the garment holds it as a measurement (`sectionedLoft`'s `hug`) and it works,+the hair holds it as a comment and it broke. Widening the hair side masses took closure from 42.2%+to 40.9% with dark coverage DOWN, and crown scalp exposure measured on the archived captures rose on+all four views, worst by 14.9 points. Nothing in the schema objected.++Run: python3 forge/tests/test_stand_proud.py+"""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage2_spec"))++from validate_sculpt_spec import ( # noqa: E402+ STAND_PROUD_EXPECTED_ROLES,+ validate_stand_proud,+)+++def run(component: dict, component_id: str = "hair-crown"):+ errors: list[str] = []+ warnings: list[str] = []+ refs: list[tuple[str, str]] = []+ validate_stand_proud(component_id, component, errors, warnings, refs)+ return errors, warnings, refs+++def proud(**overrides) -> dict:+ base = {"againstComponentId": "head", "clearance": 0.012, "maxPush": 0.04}+ base.update(overrides)+ return {"role": "hair", "standProud": base}+++class Accepted(unittest.TestCase):+ def test_a_well_formed_declaration_passes_and_records_its_reference(self) -> None:+ errors, warnings, refs = run(proud())+ self.assertEqual(errors, [])+ self.assertEqual(warnings, [])+ self.assertEqual(refs, [("hair-crown", "head")])++ def test_a_non_hair_component_may_also_declare_it(self) -> None:+ """Garments need it too; the hair role only decides where the MISSING warning fires."""+ errors, _, refs = run({"role": "garment", "standProud":+ {"againstComponentId": "torso", "clearance": 0.04, "maxPush": 0.06}},+ component_id="skirt")+ self.assertEqual(errors, [])+ self.assertEqual(refs, [("skirt", "torso")])++ def test_maxPush_equal_to_clearance_is_allowed(self) -> None:+ errors, _, _ = run(proud(clearance=0.03, maxPush=0.03))+ self.assertEqual(errors, [])+++class MissingIsWarnedNotIgnored(unittest.TestCase):+ def test_a_hair_component_without_it_warns(self) -> None:+ errors, warnings, _ = run({"role": "hair"})+ self.assertEqual(errors, [])+ self.assertEqual(len(warnings), 1)+ self.assertIn("standProud", warnings[0])+ self.assertIn("bald", warnings[0])++ def test_a_non_hair_component_without_it_is_silent(self) -> None:+ errors, warnings, _ = run({"role": "detail"}, component_id="nose")+ self.assertEqual(errors, [])+ self.assertEqual(warnings, [])++ def test_the_expected_role_set_is_exported_so_the_rule_is_inspectable(self) -> None:+ self.assertIn("hair", STAND_PROUD_EXPECTED_ROLES)+++class HardErrors(unittest.TestCase):+ def test_a_non_object_declaration_is_an_error(self) -> None:+ for bad in ("yes", 1, [], True):+ with self.subTest(bad=bad):+ errors, _, _ = run({"role": "hair", "standProud": bad})+ self.assertEqual(len(errors), 1)+ self.assertIn("must be an object", errors[0])++ def test_a_missing_target_is_an_error(self) -> None:+ for bad in ({}, {"againstComponentId": ""}, {"againstComponentId": 7}):+ with self.subTest(bad=bad):+ declaration = dict(bad)+ declaration.setdefault("clearance", 0.01)+ declaration.setdefault("maxPush", 0.02)+ errors, _, _ = run({"role": "hair", "standProud": declaration})+ self.assertTrue(any("againstComponentId is required" in e for e in errors))++ def test_standing_proud_of_itself_is_an_error(self) -> None:+ errors, _, refs = run(proud(againstComponentId="hair-crown"))+ self.assertTrue(any("references itself" in e for e in errors))+ self.assertEqual(refs, [])++ def test_a_non_positive_clearance_is_an_error(self) -> None:+ """Zero clearance permits the surfaces to touch, which z-fights rather than covers."""+ for bad in (0.0, -0.01, None, "thin"):+ with self.subTest(bad=bad):+ errors, _, _ = run(proud(clearance=bad))+ self.assertTrue(any("clearance must be a positive number" in e for e in errors))++ def test_a_non_positive_maxPush_is_an_error(self) -> None:+ """An uncapped march walks inner vertices through the target and out the far side."""+ for bad in (0.0, -1.0, None):+ with self.subTest(bad=bad):+ errors, _, _ = run(proud(maxPush=bad))+ self.assertTrue(any("maxPush must be a positive number" in e for e in errors))++ def test_maxPush_below_clearance_is_an_error(self) -> None:+ errors, _, _ = run(proud(clearance=0.05, maxPush=0.01))+ self.assertTrue(any("below its clearance" in e for e in errors))++ def test_a_bad_clearance_short_circuits_before_the_maxPush_comparison(self) -> None:+ """One clear error beats two derived ones."""+ errors, _, _ = run(proud(clearance=-1.0, maxPush=-2.0))+ self.assertEqual(len(errors), 1)+++class ReferenceResolution(unittest.TestCase):+ def test_an_unknown_target_is_caught_by_the_spec_level_pass(self) -> None:+ """Resolution is deferred so a forward reference is legal, exactly like `parent`."""+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage2_spec"))+ from validate_sculpt_spec import validate_components # noqa: PLC0415++ errors: list[str] = []+ warnings: list[str] = []+ validate_components(+ {+ "schemaVersion": "2.0",+ "materials": [{"id": "hair"}],+ "componentTree": [+ {"id": "head", "primitive": "ellipsoid", "material": "hair"},+ {"id": "hair-crown", "primitive": "ellipsoid", "material": "hair",+ "role": "hair", "parent": "head",+ "standProud": {"againstComponentId": "skull-that-does-not-exist",+ "clearance": 0.01, "maxPush": 0.02}},+ ],+ },+ {"hair"},+ set(),+ errors,+ warnings,+ )+ self.assertTrue(+ any("standProud references missing component" in e for e in errors),+ f"expected a missing-target error, got {errors}",+ )++ def test_a_forward_reference_is_legal(self) -> None:+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage2_spec"))+ from validate_sculpt_spec import validate_components # noqa: PLC0415++ errors: list[str] = []+ warnings: list[str] = []+ validate_components(+ {+ "schemaVersion": "2.0",+ "materials": [{"id": "hair"}],+ "componentTree": [+ {"id": "hair-crown", "primitive": "ellipsoid", "material": "hair",+ "role": "hair",+ "standProud": {"againstComponentId": "head", "clearance": 0.01, "maxPush": 0.02}},+ {"id": "head", "primitive": "ellipsoid", "material": "hair"},+ ],+ },+ {"hair"},+ set(),+ errors,+ warnings,+ )+ self.assertFalse([e for e in errors if "standProud" in e], errors)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_stand_proud_emission.py b/forge/tests/test_stand_proud_emission.pynew file mode 100644index 0000000..d689925--- /dev/null+++ b/forge/tests/test_stand_proud_emission.py@@ -0,0 +1,480 @@+#!/usr/bin/env python3+"""The generator emits the clearance march, so `standProud` is enforced and not merely declared.++This is `hug` from the hand-written humanoid demo, generalised out of that one file and into the+skill. In the demo the garment gets a measured per-vertex clearance and works; the hair got a prose+invariant and broke. Widening the hair masses by hand took closure from 42.2% to 40.9%, worse on all+six views, with dark coverage DOWN.++Run: python3 forge/tests/test_stand_proud_emission.py+"""+import json+import math+import subprocess+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage2_spec"))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage3_build"))++from generate_threejs_factory import generate, stand_proud_ring_stack # noqa: E402+from showcase_test_support import showcase_root # noqa: E402++FIXTURE = Path(__file__).resolve().parent / "fixtures" / "stand_proud_hair_on_head.json"+++def spec(hair_extra: dict | None = None, head_extra: dict | None = None) -> dict:+ head = {"id": "head", "name": "Head", "primitive": "ellipsoid", "material": "skin",+ "dimensions": {"width": 0.4, "height": 0.5, "depth": 0.42}}+ head.update(head_extra or {})+ hair = {"id": "hair-crown", "name": "Hair crown", "primitive": "ellipsoid", "material": "hair",+ "parent": "head", "role": "hair",+ "dimensions": {"width": 0.41, "height": 0.3, "depth": 0.43}}+ hair.update(hair_extra or {})+ return {+ "targetName": "ProudTest",+ "schemaVersion": "2.1",+ "suitability": "pass",+ "coordinateFrame": {},+ "silhouette": {},+ "proceduralStrategy": [],+ "materials": [{"id": "skin"}, {"id": "hair"}],+ "componentTree": [head, hair],+ }+++PROUD = {"againstComponentId": "head", "clearance": 0.012, "maxPush": 0.04}+++class RingStackDerivation(unittest.TestCase):+ def test_an_authored_ring_stack_is_used_directly(self) -> None:+ rings = stand_proud_ring_stack({+ "primitive": "lathe",+ "geometryDescriptor": {"ringStack": {"rings": [[1.0, 0.4, 0.5], [0.0, 0.3, 0.35]]}},+ })+ self.assertEqual(rings[0][0], 0.0, "rings must come back sorted bottom to top")+ self.assertEqual(rings[-1][0], 1.0)+ self.assertEqual(len(rings[0]), 4, "a missing z offset must be filled, not dropped")++ def test_parallel_z_offsets_are_merged(self) -> None:+ rings = stand_proud_ring_stack({+ "primitive": "lathe",+ "geometryDescriptor": {+ "ringStack": {"rings": [[0.0, 0.4, 0.5], [1.0, 0.3, 0.35]], "zOffsets": [0.06, -0.03]}+ },+ })+ self.assertEqual(rings[0][3], 0.06)+ self.assertEqual(rings[1][3], -0.03)++ def test_an_ellipsoid_is_synthesised_at_unit_scale(self) -> None:+ """This function returns the UNIT form, because `geometry_for` authors an ellipsoid at+ radius 0.5 and knows nothing about the component's dimensions.++ Applying the dimensions is the EMISSION layer's job, and getting that split wrong was a real+ defect: the unit stack went out unscaled, claiming a skull radius of 0.5 where the geometry+ sat at 0.2. `TheStackDescribesTheRealSurface` below covers the scaled result; this covers+ only the unit form this function is responsible for.+ """+ rings = stand_proud_ring_stack({"primitive": "ellipsoid"})+ self.assertAlmostEqual(rings[0][0], -0.5, places=6)+ self.assertAlmostEqual(rings[-1][0], 0.5, places=6)+ widest = max(rings, key=lambda r: r[1])+ self.assertAlmostEqual(widest[1], 0.5, places=3)++ def test_a_shape_with_no_describable_surface_returns_none(self) -> None:+ """Better a visible skip than a clearance that silently never ran."""+ self.assertIsNone(stand_proud_ring_stack({"primitive": "plane-card"}))+ self.assertIsNone(stand_proud_ring_stack({"primitive": "extrude"}))+++class HelperEmission(unittest.TestCase):+ def test_nothing_is_emitted_when_no_component_declares_it(self) -> None:+ source = generate(spec(), "blockout")+ self.assertNotIn("applyStandProud", source)+ self.assertNotIn("ringStackDistance", source)++ def test_the_helper_and_the_call_are_both_emitted(self) -> None:+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("function applyStandProud(", source)+ self.assertIn("function ringStackDistance(", source)+ self.assertIn("applyStandProud(", source.split("function applyStandProud(")[-1])++ def test_the_march_travels_along_the_vertex_spoke(self) -> None:+ """Along its OWN radial direction, not the field gradient: that is what keeps a ring a ring+ rather than letting neighbouring vertices settle at different radii."""+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("const spokeLength = Math.hypot(p.x, p.z);", source)+ self.assertIn("p.x += sx * move;", source)+ self.assertIn("p.z += sz * move;", source)++ def test_travel_is_capped_at_maxPush(self) -> None:+ """Required, not a safeguard: an uncapped march walks inner vertices out the far side."""+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("maxPush - travelled", source)+ self.assertIn("if (move <= 0) break;", source)++ def test_normals_are_recomputed_after_moving_vertices(self) -> None:+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ tail = source.split("function applyStandProud(")[-1]+ self.assertIn("position.needsUpdate = true;", tail)+ self.assertIn("geometry.computeVertexNormals();", tail)++ def test_the_march_runs_in_the_target_frame(self) -> None:+ """Clearance is measured against the target's surface, so both world matrices are needed."""+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("target.matrixWorld", source)+ self.assertIn("marcher.matrixWorld", source)+ self.assertIn(".invert()", source)++ def test_the_declared_numbers_reach_the_call(self) -> None:+ source = generate(spec(hair_extra={"standProud": {+ "againstComponentId": "head", "clearance": 0.0175, "maxPush": 0.0625}}), "blockout")+ self.assertIn("0.0175", source)+ self.assertIn("0.0625", source)++ def test_a_vertex_on_the_axis_marches_axially_instead_of_being_skipped(self) -> None:+ """The axis IS the crown, which is where a bald patch shows most. An earlier version+ skipped these vertices, leaving the exact failure the march exists to prevent."""+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("const onAxis = spokeLength < 1e-9;", source)+ self.assertIn("const sy = onAxis ? (p.y >= midHeight ? 1 : -1) : 0;", source)+ self.assertIn("p.y += sy * move;", source)+ self.assertNotIn("if (spokeLength < 1e-9) continue;", source)+++class ThePortsAgree(unittest.TestCase):+ """`ringStackDistance` in the emitted TypeScript reimplements `ScalpField.distance` in Python.++ Two implementations of one formula in two languages, and until this class existed nothing held+ them together -- every other test here is a substring check, so a fix applied to one side would+ have left the other silently wrong. That is not hypothetical: the scale defect this file's+ `TheStackDescribesTheRealSurface` covers was exactly a divergence between what Python computed+ and what the browser then measured against.++ The TS body is transliterated here rather than executed. That is a weaker lock than running it,+ but it is a real one: it fails the moment the two formulas stop matching numerically, which is+ the drift being guarded against.+ """++ @staticmethod+ def ts_ring_stack_distance(rings, x, y, z):+ """Line-for-line transliteration of the emitted `ringStackDistance`."""+ y_min, y_max = rings[0][0], rings[-1][0]+ rx, rz, zc = rings[0][1], rings[0][2], rings[0][3]+ if y >= y_max:+ rx, rz, zc = rings[-1][1], rings[-1][2], rings[-1][3]+ elif y > y_min:+ for lo, hi in zip(rings, rings[1:]):+ if lo[0] <= y <= hi[0]:+ span = hi[0] - lo[0]+ t = (y - lo[0]) / span if span > 1e-9 else 0+ rx = lo[1] + (hi[1] - lo[1]) * t+ rz = lo[2] + (hi[2] - lo[2]) * t+ zc = lo[3] + (hi[3] - lo[3]) * t+ break+ dx = x / rx+ dz = (z - zc) / rz+ f = dx * dx + dz * dz - 1+ gx = (2 * x) / (rx * rx)+ gz = (2 * (z - zc)) / (rz * rz)+ grad = math.hypot(gx, gz)+ radial = -min(rx, rz) if grad < 1e-12 else f / grad+ axial = max(y_min - y, y - y_max)+ return math.hypot(max(radial, 0), max(axial, 0)) + min(max(radial, axial), 0)++ def test_the_transliteration_matches_the_emitted_source(self) -> None:+ """Guards the transliteration itself: if the emitted body changes shape, this must be+ revisited rather than quietly continuing to test a stale copy."""+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ body = source.split("function ringStackDistance(")[1].split("\n}")[0]+ for fragment in (+ "const f = dx * dx + dz * dz - 1;",+ "const gx = (2 * x) / (rx * rx);",+ "const radial = grad < 1e-12 ? -Math.min(rx, rz) : f / grad;",+ "const axial = Math.max(yMin - y, y - yMax);",+ "return Math.hypot(Math.max(radial, 0), Math.max(axial, 0)) "+ "+ Math.min(Math.max(radial, axial), 0);",+ ):+ self.assertIn(fragment, body)++ def test_the_two_implementations_agree_across_the_domain(self) -> None:+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))+ from scalp_field import ScalpField # noqa: PLC0415++ rings = [[-0.25, 0.12, 0.16, 0.01], [-0.10, 0.19, 0.21, 0.03],+ [0.00, 0.20, 0.22, 0.02], [0.12, 0.19, 0.21, 0.0],+ [0.25, 0.15, 0.17, -0.02]]+ field = ScalpField(rings)++ checked = 0+ for xi in range(-6, 7):+ for yi in range(-8, 9):+ for zi in range(-6, 7):+ x, y, z = xi * 0.05, yi * 0.05, zi * 0.05+ with self.subTest(point=(x, y, z)):+ self.assertAlmostEqual(+ self.ts_ring_stack_distance(rings, x, y, z),+ field.distance(x, y, z),+ places=12,+ )+ checked += 1+ self.assertGreater(checked, 2000, "the sweep must actually cover the domain")++ def test_they_agree_on_the_signs_too(self) -> None:+ """The magnitude is a first-order estimate; the SIGN is what gates rely on."""+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))+ from scalp_field import ScalpField # noqa: PLC0415++ rings = [[0.0, 0.2, 0.3, 0.0], [1.0, 0.1, 0.15, 0.05]]+ field = ScalpField(rings)+ for x, y, z in ((0, 0.5, 0), (0.5, 0.5, 0), (0, 2.0, 0), (0, -1.0, 0), (0.05, 0.9, 0.05)):+ with self.subTest(point=(x, y, z)):+ self.assertEqual(+ self.ts_ring_stack_distance(rings, x, y, z) < 0,+ field.distance(x, y, z) < 0,+ )+++class SaturationIsReported(unittest.TestCase):+ """A vertex can exhaust `maxPush` and still be inside the target.++ That is the cap doing its job, but the clearance the function promised was NOT achieved, and+ saying nothing there hides the very defect the caller asked to be protected from. Measured by+ executing the emitted logic against the shipped fixture: 2 of 8 sampled hair vertices sat 0.059+ inside the skull against a 0.04 cap and could never have reached clear.+ """++ def test_unresolved_vertices_are_counted(self) -> None:+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("let unresolved = 0;", source)+ self.assertIn("unresolved += 1;", source)++ def test_the_count_is_left_on_the_geometry_for_a_gate_to_read(self) -> None:+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("geometry.userData.standProud = {", source)+ self.assertIn("unresolved,", source)++ def test_a_warning_names_the_consequence_and_the_fix(self) -> None:+ source = generate(spec(hair_extra={"standProud": PROUD}), "blockout")+ self.assertIn("console.warn(", source)+ self.assertIn("render as bare patches", source)+ self.assertIn("Raise maxPush", source)+++class UnresolvableDeclarations(unittest.TestCase):+ """Two layers, and they catch different things.++ A malformed declaration -- unknown target, non-numeric bounds -- never reaches the generator,+ because stage 2 validation rejects the spec first. Those cases are covered in+ test_stand_proud.py, at the layer that owns them. What survives validation and still cannot be+ marched is a target whose SHAPE exposes no surface to measure against, and only the generator+ knows that, because only the generator knows which primitives it can describe as a ring stack.+ """++ def test_a_malformed_declaration_never_reaches_the_generator(self) -> None:+ for hair_extra, expected in (+ ({"standProud": dict(PROUD, againstComponentId="ghost")}, "references missing component"),+ ({"standProud": {"againstComponentId": "head", "clearance": "thin", "maxPush": 0.04}},+ "clearance must be a positive number"),+ ({"standProud": {"againstComponentId": "head", "clearance": 0.05, "maxPush": 0.01}},+ "below its clearance"),+ ):+ with self.subTest(expected=expected):+ with self.assertRaises(ValueError) as caught:+ generate(spec(hair_extra=hair_extra), "blockout")+ self.assertIn(expected, str(caught.exception))++ def test_a_target_whose_shape_has_no_ring_stack_is_reported_in_the_output(self) -> None:+ """Valid to the schema, unmarchable in practice. A visible skip beats a silent no-op."""+ source = generate(+ spec(hair_extra={"standProud": PROUD}, head_extra={"primitive": "plane-card"}),+ "blockout",+ )+ self.assertIn("// SKIPPED", source)+ self.assertIn("exposes no ring stack", source)+ self.assertNotIn("function applyStandProud(", source)+++class ForwardReference(unittest.TestCase):+ def test_a_component_may_stand_proud_of_one_declared_after_it(self) -> None:+ """The pass is deferred to after the whole tree is parented, so ordering cannot break it."""+ payload = spec(hair_extra={"standProud": PROUD})+ payload["componentTree"].reverse()+ source = generate(payload, "blockout")+ self.assertIn("function applyStandProud(", source)+ self.assertNotIn("// SKIPPED", source)+ # The call must come after both nodes exist, which is what the meshes/nodes lookup asserts.+ self.assertIn('if (meshes["hair-crown"] && nodes["head"])', source)+++class TheStackDescribesTheRealSurface(unittest.TestCase):+ """Where the emitted stack SAYS the surface is, against where the geometry actually puts it.++ Every other test in this file checks emitted strings or that the file typechecks. None of them+ could see this, and it was wrong: `geometry.scale(width, height, depth)` bakes the factors into+ the vertex data and leaves the pivot at scale 1, so nothing in the scene graph carries them. The+ stack was being emitted from the UNIT form, claiming a skull radius of 0.5 where the geometry+ sat at 0.2, and claiming rings at 0.12..0.20 where the scaled lathe sat at 0.048..0.080. The+ march would have pushed hair to roughly two and a half times the skull's real radius.+ """++ def emitted_rings(self, spec_payload: dict, marcher_id: str) -> list[list[float]]:+ """Pull the ring stack literal back out of the generated source."""+ source = generate(spec_payload, "structural-pass")+ marker = f'if (meshes["{marcher_id}"]'+ start = source.index(marker)+ rings_at = source.index('"rings"', start)+ open_bracket = source.index("[", rings_at)+ depth = 0+ for index in range(open_bracket, len(source)):+ if source[index] == "[":+ depth += 1+ elif source[index] == "]":+ depth -= 1+ if depth == 0:+ return json.loads(source[open_bracket:index + 1])+ raise AssertionError("could not recover the emitted ring stack")++ def test_an_authored_stack_is_scaled_to_the_geometry_it_describes(self) -> None:+ payload = json.loads(FIXTURE.read_text())+ head = next(c for c in payload["componentTree"] if c["id"] == "head")+ width = head["dimensions"]["width"]+ authored = head["geometryDescriptor"]["ringStack"]["rings"]++ rings = self.emitted_rings(payload, "hair-crown")+ widest_authored = max(r[1] for r in authored)+ widest_emitted = max(r[1] for r in rings)+ self.assertAlmostEqual(widest_emitted, widest_authored * width, places=6)++ def test_an_ellipsoid_target_reports_its_real_half_extent_not_0_5(self) -> None:+ payload = json.loads(FIXTURE.read_text())+ head = next(c for c in payload["componentTree"] if c["id"] == "head")+ head["primitive"] = "ellipsoid"+ del head["geometryDescriptor"]["ringStack"]++ rings = self.emitted_rings(payload, "hair-crown")+ widest = max(r[1] for r in rings)+ self.assertAlmostEqual(widest, 0.5 * head["dimensions"]["width"], places=3)+ self.assertNotAlmostEqual(widest, 0.5, places=3)++ def test_the_stack_height_is_scaled_too(self) -> None:+ payload = json.loads(FIXTURE.read_text())+ head = next(c for c in payload["componentTree"] if c["id"] == "head")+ height = head["dimensions"]["height"]+ authored = head["geometryDescriptor"]["ringStack"]["rings"]++ rings = self.emitted_rings(payload, "hair-crown")+ self.assertAlmostEqual(max(r[0] for r in rings), max(r[0] for r in authored) * height, places=6)+ self.assertAlmostEqual(min(r[0] for r in rings), min(r[0] for r in authored) * height, places=6)++ def test_the_z_offset_is_scaled_by_depth_not_by_width(self) -> None:+ payload = json.loads(FIXTURE.read_text())+ head = next(c for c in payload["componentTree"] if c["id"] == "head")+ depth = head["dimensions"]["depth"]+ authored_offsets = head["geometryDescriptor"]["ringStack"]["zOffsets"]++ rings = self.emitted_rings(payload, "hair-crown")+ self.assertAlmostEqual(rings[0][3], authored_offsets[0] * depth, places=6)++ def test_an_explicit_transform_scale_wins_over_dimensions(self) -> None:+ """`scale_vector` prefers transform.scale, so the stack has to prefer it identically or the+ two descriptions of the same geometry disagree."""+ payload = json.loads(FIXTURE.read_text())+ head = next(c for c in payload["componentTree"] if c["id"] == "head")+ head["transform"] = {"scale": [2.0, 3.0, 4.0]}+ authored = head["geometryDescriptor"]["ringStack"]["rings"]++ rings = self.emitted_rings(payload, "hair-crown")+ self.assertAlmostEqual(max(r[1] for r in rings), max(r[1] for r in authored) * 2.0, places=6)+ self.assertAlmostEqual(max(r[0] for r in rings), max(r[0] for r in authored) * 3.0, places=6)++ def test_a_target_with_no_dimensions_is_left_at_unit_scale(self) -> None:+ payload = json.loads(FIXTURE.read_text())+ head = next(c for c in payload["componentTree"] if c["id"] == "head")+ authored = list(head["geometryDescriptor"]["ringStack"]["rings"])+ del head["dimensions"]++ rings = self.emitted_rings(payload, "hair-crown")+ self.assertAlmostEqual(max(r[1] for r in rings), max(r[1] for r in authored), places=6)+++class EmittedSourceTypechecks(unittest.TestCase):+ """The emitted TypeScript is the deliverable, so it has to actually compile.++ Generated through the Python API rather than the CLI: the CLI's strict-quality gate is about+ whether a SPEC is complete enough to build from, which is a different question from whether the+ code path under test emits valid TypeScript, and `--allow-nonstrict` cannot be combined with+ `--pass-id`. The fixture's hair is `meso`, so it needs a pass that admits meso -- under+ `blockout` the hair is correctly filtered out and there would be nothing to typecheck.+ """++ def test_a_factory_using_standProud_typechecks(self) -> None:+ root = showcase_root()+ destination = root / "src" / "__stand_proud_smoke__.ts"+ self.assertFalse(destination.exists(), "a previous run left its smoke source behind")++ source = generate(json.loads(FIXTURE.read_text()), "structural-pass")+ self.assertIn("function applyStandProud(", source)+ self.assertNotIn("// SKIPPED", source)++ try:+ destination.write_text(source, encoding="utf-8")+ result = subprocess.run(+ ["npx", "tsc", "--noEmit"], cwd=root, capture_output=True, text=True, check=False+ )+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ finally:+ if destination.exists():+ destination.unlink()++ def test_the_fixture_carries_both_a_ring_stack_target_and_two_marchers(self) -> None:+ """Guards the fixture itself: a fixture that quietly stopped exercising the path would let+ the typecheck above pass while proving nothing."""+ spec_payload = json.loads(FIXTURE.read_text())+ marchers = [c for c in spec_payload["componentTree"] if "standProud" in c]+ self.assertEqual(len(marchers), 2)+ head = next(c for c in spec_payload["componentTree"] if c["id"] == "head")+ self.assertIn("ringStack", head["geometryDescriptor"])++ def test_the_fixture_ring_stack_matches_the_geometry_it_claims_to_describe(self) -> None:+ """A ring stack is a SECOND description of a shape the generator builds another way, so the+ two can disagree with nothing to notice.++ This fixture disagreed. Its lathe profile and its ring stack were authored independently and+ the stack was 10-33% wider in z than the revolve it stood for, because a lathe is circular+ before `geometry.scale` and the stack had already baked ellipticity in. Checking only rx --+ the axis that had just been fixed -- did not see it.+ """+ spec_payload = json.loads(FIXTURE.read_text())+ head = next(c for c in spec_payload["componentTree"] if c["id"] == "head")+ width = head["dimensions"]["width"]+ depth = head["dimensions"]["depth"]+ height = head["dimensions"]["height"]+ profile = head["geometryDescriptor"]["latheProfile"]["points"]+ rings = sorted(head["geometryDescriptor"]["ringStack"]["rings"])++ self.assertEqual(len(rings), len(profile), "one ring per profile point, or they cannot align")+ for (radius, y), ring in zip(profile, rings):+ with self.subTest(y=y):+ self.assertAlmostEqual(ring[0] * height, y * height, places=9)+ # A revolve is circular; the ellipse comes from the dimensions, not the stack.+ self.assertAlmostEqual(ring[1], ring[2], places=9)+ self.assertAlmostEqual(ring[1] * width, radius * width, places=9)+ self.assertAlmostEqual(ring[2] * depth, radius * depth, places=9)++ def test_a_lathe_target_with_an_elliptical_stack_is_refused(self) -> None:+ """The rule, not just the fixture: a stack that cannot describe a revolve is reported."""+ payload = json.loads(FIXTURE.read_text())+ head = next(c for c in payload["componentTree"] if c["id"] == "head")+ head["geometryDescriptor"]["ringStack"]["rings"][2][2] += 0.02++ source = generate(payload, "structural-pass")+ self.assertIn("// SKIPPED", source)+ self.assertIn("circular before scaling", source)+ self.assertNotIn("function applyStandProud(", source)+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_tapered_sweep.py b/forge/tests/test_tapered_sweep.pynew file mode 100644index 0000000..e5eed89--- /dev/null+++ b/forge/tests/test_tapered_sweep.py@@ -0,0 +1,366 @@+#!/usr/bin/env python3+"""Tests for the `tapered-sweep` primitive.++Every other sweep this factory emits carries a CONSTANT cross-section: `buildTubeGeometry` takes one+radius, `buildCurveSweepGeometry` extrudes one Shape along a path. Nothing that comes to a point --+a hair lock, a horn, a tail, a finger, a blade tip -- could be expressed, so those subjects were+built from stacked constant-radius pieces and read as noodles.++The taper warning exists because of a measured failure, not a theory. A recovered build contained+eleven hair locks whose tip radius was 0.0327 on every single one, identical to four decimals, for+tip/root ratios of 0.58-0.79 against a reference that measures 0.087. The frame maths was correct;+the authored stations were not, and nothing objected.++Run: python3 forge/tests/test_tapered_sweep.py+"""+import sys+import json+import math+import shutil+import subprocess+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage2_spec"))+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage3_build"))++import generate_threejs_factory # noqa: E402+from generate_threejs_factory import _DEFAULT_TAPERED_SWEEP, geometry_for # noqa: E402+from validate_sculpt_spec import TAPER_RATIO_MAX, VALID_PRIMITIVES, taper_risk # noqa: E402+++def component(stations: list[dict[str, object]]) -> dict[str, object]:+ return {"geometryDescriptor": {"taperedSweep": {"stations": stations}}}+++def station(y: float, rx: float, rz: float, twist: float = 0.0) -> dict[str, object]:+ return {"position": [0.0, y, 0.0], "rx": rx, "rz": rz, "twist": twist}+++class PrimitiveRegistration(unittest.TestCase):+ def test_primitive_is_accepted_by_the_schema(self) -> None:+ self.assertIn("tapered-sweep", VALID_PRIMITIVES)++ def test_geometry_for_emits_the_builder(self) -> None:+ call = geometry_for("tapered-sweep", {"taperedSweep": _DEFAULT_TAPERED_SWEEP}, {})+ self.assertTrue(call.startswith("buildTaperedSweepGeometry("))+ self.assertIn("stations", call)++ def test_a_missing_descriptor_falls_back_to_a_tapering_default(self) -> None:+ """The default must not itself trip the taper warning -- otherwise every spec that omits+ the descriptor inherits a warning it cannot act on."""+ stations = _DEFAULT_TAPERED_SWEEP["stations"]+ ratio = max(stations[-1]["rx"], stations[-1]["rz"]) / max(stations[0]["rx"], stations[0]["rz"])+ self.assertLess(ratio, TAPER_RATIO_MAX)++ call = geometry_for("tapered-sweep", {}, {})+ self.assertIn("buildTaperedSweepGeometry(", call)+++class TaperWarning(unittest.TestCase):+ def test_a_lock_that_reaches_a_point_passes(self) -> None:+ severity, _ = taper_risk(+ "hair-lock",+ component([station(-0.5, 0.060, 0.040), station(0.0, 0.030, 0.020), station(0.5, 0.005, 0.003)]),+ )+ self.assertEqual(severity, "OK")++ def test_the_recovered_blunt_lock_is_caught(self) -> None:+ """The exact numbers from the recovered build: root 0.0538, tip 0.0323, ratio 0.60."""+ severity, message = taper_risk(+ "Hair_Fringe_L",+ component([station(-0.5, 0.0538, 0.0538), station(0.5, 0.0323, 0.0323)]),+ )+ self.assertEqual(severity, "HIGH")+ self.assertIn("0.60", message)+ self.assertIn("noodle", message)++ def test_a_constant_radius_sweep_is_caught(self) -> None:+ severity, _ = taper_risk(+ "cable", component([station(-0.5, 0.02, 0.02), station(0.5, 0.02, 0.02)])+ )+ self.assertEqual(severity, "HIGH")++ def test_components_without_the_descriptor_are_untouched(self) -> None:+ for candidate in ({}, {"geometryDescriptor": {}}, {"geometryDescriptor": {"tubePath": {}}}):+ with self.subTest(candidate=candidate):+ self.assertEqual(taper_risk("x", candidate)[0], "OK")++ def test_malformed_stations_do_not_raise(self) -> None:+ for stations in ([], [station(0, 0.1, 0.1)], ["not-a-dict", 7], [station(0, 0.0, 0.0), station(1, 0.0, 0.0)]):+ with self.subTest(stations=stations):+ self.assertEqual(taper_risk("x", component(stations))[0], "OK")+++class EmittedSource(unittest.TestCase):+ """The emitted TypeScript is the deliverable; these assert the properties that make it correct.++ A full typecheck of the generated factory runs in test_showcase_tsc_smoke when a showcase+ checkout is configured; these checks hold with no browser and no Node.+ """++ _cached: str | None = None++ def source(self) -> str:+ """Generate a real factory from a spec that uses the primitive, and read what came out."""+ if EmittedSource._cached is None:+ from generate_threejs_factory import generate # noqa: PLC0415++ spec = {+ "targetName": "TaperTest",+ "schemaVersion": "2.1",+ "suitability": "pass",+ "coordinateFrame": {},+ "silhouette": {},+ "proceduralStrategy": [],+ "materials": [{"id": "hair"}],+ "componentTree": [+ {+ "id": "lock",+ "name": "Lock",+ "primitive": "tapered-sweep",+ "materialId": "hair",+ "geometryDescriptor": {"taperedSweep": _DEFAULT_TAPERED_SWEEP},+ }+ ],+ }+ EmittedSource._cached = generate(spec, "blockout")+ return EmittedSource._cached++ def test_the_builder_is_emitted_and_called(self) -> None:+ source = self.source()+ self.assertIn("function buildTaperedSweepGeometry(", source)+ self.assertIn("buildTaperedSweepGeometry({", source)++ def test_uses_parallel_transport_not_frenet(self) -> None:+ source = self.source()+ self.assertIn("buildTaperedSweepGeometry", source)+ self.assertNotIn("computeFrenetFrames", source)++ def test_guards_the_degenerate_seed_axis(self) -> None:+ """A reference axis parallel to the first tangent makes the first cross product zero and+ collapses the sweep to a line."""+ self.assertIn("> 0.9", self.source())++ def test_guards_coincident_stations(self) -> None:+ """Two stations at the same position normalise to NaN and poison every later vertex."""+ self.assertIn("1e-12", self.source())++ def test_recomputes_normals_after_building(self) -> None:+ self.assertIn("computeVertexNormals", self.source())++ def test_a_collapsed_station_emits_one_vertex_not_a_zero_radius_ring(self) -> None:+ """The reason the taper warning was not enough on its own.++ A ring of radius 0 still carries `radial` coincident vertices and `radial` zero-area+ triangles, so the sweep ends in a blunt cap the width of floating-point noise. The existing+ `sectionedLoft` in the humanoid demo collapses such a section to a single vertex, and a hair+ lock, a horn or a blade tip has to actually reach a point.+ """+ source = self.source()+ self.assertIn("st.rx <= 1e-6 && st.rz <= 1e-6", source)+ self.assertIn("isPoint", source)++ def test_a_point_end_is_not_capped_again(self) -> None:+ self.assertIn("if (isPoint[end]) continue;", self.source())+++class DefaultDescriptor(unittest.TestCase):+ def test_the_default_tip_is_a_true_point(self) -> None:+ tip = _DEFAULT_TAPERED_SWEEP["stations"][-1]+ self.assertEqual(tip["rx"], 0.0)+ self.assertEqual(tip["rz"], 0.0)++ def test_the_default_passes_its_own_taper_gate(self) -> None:+ severity, _ = taper_risk(+ "default", {"geometryDescriptor": {"taperedSweep": _DEFAULT_TAPERED_SWEEP}}+ )+ self.assertEqual(severity, "OK")++++class TaperRiskIsDirectionAgnostic(unittest.TestCase):+ """A sweep authored ankle-to-haunch tapers exactly as much as one authored haunch-to-ankle.++ Station order is not free: reversing it reverses the triangle winding, so a limb authored+ tip-first renders as an open shell seen from the inside. Reading station[0] as "the root"+ therefore reported a real 0.53 taper as 1.89 and pushed the author toward breaking the winding+ to satisfy the check.+ """++ @staticmethod+ def _component(radii):+ return {+ "geometryDescriptor": {+ "taperedSweep": {+ "stations": [+ {"position": [0.0, index * 0.1, 0.0], "rx": radius, "rz": radius}+ for index, radius in enumerate(radii)+ ]+ }+ }+ }++ def test_the_same_limb_scores_the_same_either_way_round(self):+ from validate_sculpt_spec import taper_risk++ narrow_first = taper_risk("leg", self._component([0.061, 0.09, 0.113]))+ wide_first = taper_risk("leg", self._component([0.113, 0.09, 0.061]))+ self.assertEqual(narrow_first[0], wide_first[0])+ self.assertEqual(narrow_first[0], "OK")++ def test_a_barrel_widest_in_the_middle_is_not_called_a_noodle(self):+ """A torso, a spindle and a lemon all taper hard and have near-identical ends."""+ from validate_sculpt_spec import taper_risk++ level, _ = taper_risk("torso", self._component([0.055, 0.18, 0.213, 0.18, 0.092]))+ self.assertEqual(level, "OK")++ def test_a_genuinely_untapered_sweep_still_warns_in_both_orders(self):+ """Negative control: the check is not simply weakened."""+ from validate_sculpt_spec import taper_risk++ for radii in ([0.10, 0.10, 0.098], [0.098, 0.10, 0.10]):+ with self.subTest(radii=radii):+ level, message = taper_risk("noodle", self._component(radii))+ self.assertEqual(level, "HIGH")+ self.assertIn("narrow/wide", message)++++class SweepWindingFacesOutward(unittest.TestCase):+ """A closed sweep must have POSITIVE signed volume, i.e. outward-facing triangles.++ Measured on a built model before the fix: torso -0.0674, tail -0.0044, and each leg -0.000155+ against a true volume of +0.0032 — the legs' two triangles per quad were wound OPPOSITE to each+ other, so the solid nearly cancelled itself out and rendered as an open shell. Nothing caught+ it: the mesh was watertight by vertex count, the silhouette was right, and the defect showed+ only as a pale, see-through part that reads as a material fault.+ """++ @staticmethod+ def _signed_volume(positions, indices):+ total = 0.0+ for i in range(0, len(indices), 3):+ a = positions[indices[i] * 3:indices[i] * 3 + 3]+ b = positions[indices[i + 1] * 3:indices[i + 1] * 3 + 3]+ c = positions[indices[i + 2] * 3:indices[i + 2] * 3 + 3]+ cross = (+ b[1] * c[2] - b[2] * c[1],+ b[2] * c[0] - b[0] * c[2],+ b[0] * c[1] - b[1] * c[0],+ )+ total += (a[0] * cross[0] + a[1] * cross[1] + a[2] * cross[2]) / 6.0+ return total++ def _build(self, sweep):+ node = shutil.which("node")+ if node is None:+ self.fail("node is required to execute the emitted sweep builder")+ showcase = ROOT.parent / "img2threejs-showcase"+ if not (showcase / "node_modules" / "three").is_dir():+ self.skipTest(f"three is not installed at {showcase / 'node_modules' / 'three'}")+ source = generate_threejs_factory.generate(_sweep_spec(sweep), "blockout")+ # Built inside the showcase's node_modules so `three` resolves; a module outside the+ # project tree cannot see the project's dependencies.+ work = showcase / "node_modules" / ".cache" / "sweep-winding"+ work.mkdir(parents=True, exist_ok=True)+ entry = work / "factory.ts"+ entry.write_text(source, encoding="utf-8")+ module = work / "factory.mjs"+ subprocess.run(+ [+ str(showcase / "node_modules" / ".bin" / "esbuild"),+ str(entry),+ "--bundle", "--format=esm", "--platform=node", "--external:three",+ f"--outfile={module}", "--log-level=error",+ ],+ text=True, check=True, capture_output=True, cwd=showcase,+ )+ harness = work / "run.mjs"+ harness.write_text(+ "import { createSweepModel } from './factory.mjs';\n"+ "const model = createSweepModel({});\n"+ "let out = null;\n"+ "model.traverse((o) => { if (o.isMesh) { const g = o.geometry;\n"+ " out = { positions: Array.from(g.getAttribute('position').array),\n"+ " indices: Array.from(g.getIndex().array) }; } });\n"+ "console.log(JSON.stringify(out));\n",+ encoding="utf-8",+ )+ result = subprocess.run([node, str(harness)], capture_output=True, text=True, cwd=work)+ self.assertEqual(result.returncode, 0, result.stderr)+ return json.loads(result.stdout)++ def test_a_straight_sweep_encloses_a_positive_volume(self):+ mesh = self._build({+ "stations": [+ {"position": [0.0, 0.0, 0.0], "rx": 0.06, "rz": 0.06, "twist": 0.0},+ {"position": [0.0, 0.5, 0.0], "rx": 0.10, "rz": 0.10, "twist": 0.0},+ {"position": [0.0, 1.0, 0.0], "rx": 0.04, "rz": 0.04, "twist": 0.0},+ ],+ "radialSegments": 16,+ "capEnds": True,+ })+ volume = self._signed_volume(mesh["positions"], mesh["indices"])+ self.assertGreater(volume, 0.0, "sweep is inside-out")+ # A rough solid-of-revolution estimate, to catch a sign that is right and a magnitude that+ # is not — which is what a self-cancelling quad split produces.+ self.assertGreater(volume, 0.01)++ def test_a_sweep_ending_in_a_point_also_encloses_a_positive_volume(self):+ mesh = self._build({+ "stations": [+ {"position": [0.0, 0.0, 0.0], "rx": 0.08, "rz": 0.08, "twist": 0.0},+ {"position": [0.0, 0.6, 0.0], "rx": 0.05, "rz": 0.05, "twist": 0.0},+ {"position": [0.0, 1.0, 0.0], "rx": 0.0, "rz": 0.0, "twist": 0.0},+ ],+ "radialSegments": 14,+ "capEnds": True,+ })+ self.assertGreater(self._signed_volume(mesh["positions"], mesh["indices"]), 0.005)++ def test_a_curved_sweep_encloses_a_positive_volume(self):+ stations = []+ for index in range(20):+ angle = math.radians(-85 - 190 * index / 19)+ stations.append({+ "position": [0.0, 0.19 * math.sin(angle), 0.19 * math.cos(angle)],+ "rx": 0.05, "rz": 0.05, "twist": 0.0,+ })+ mesh = self._build({"stations": stations, "radialSegments": 16, "capEnds": True})+ self.assertGreater(self._signed_volume(mesh["positions"], mesh["indices"]), 0.002)+++def _sweep_spec(sweep):+ return {+ "targetName": "Sweep",+ "targetId": "sweep",+ "schemaVersion": "2.1",+ "suitability": "pass",+ "coordinateFrame": {"front": "+Z", "up": "+Y", "scaleReference": "unit"},+ "silhouette": {"boundingShape": "test", "symmetry": "bilateral"},+ "proceduralStrategy": ["blockout"],+ "materials": [{"id": "base", "name": "Base", "baseColor": "#808080"}],+ "buildPasses": [{"id": "blockout", "acceptance": []}],+ "componentTree": [{+ "id": "sweep",+ "name": "Sweep",+ "level": "macro",+ "role": "body",+ "primitive": "tapered-sweep",+ "topologyClass": "continuous-sculpt",+ "topologyRationale": "test",+ "parent": None,+ "material": "base",+ "dimensions": {"width": 1.0, "height": 1.0, "depth": 1.0, "units": "relative"},+ "transform": {"position": [0, 0, 0], "rotation": [0, 0, 0], "scale": [1, 1, 1]},+ "geometryDescriptor": {"taperedSweep": sweep},+ }],+ }+++if __name__ == "__main__":+ unittest.main(verbosity=2)diff --git a/forge/tests/test_textureless_material.py b/forge/tests/test_textureless_material.pynew file mode 100644index 0000000..a4a9793--- /dev/null+++ b/forge/tests/test_textureless_material.py@@ -0,0 +1,210 @@+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "forge" / "_shared"))+sys.path.insert(0, str(ROOT / "forge" / "stage2_spec"))++sys.path.insert(0, str(ROOT / "forge" / "stage3_build"))++from validate_sculpt_spec import ( # noqa: E402+ is_textureless,+ validate_look_dev_targets,+ validate_materials,+ validate_textureless,+)++DECLARED = {+ "declared": True,+ "evidence": [+ "view-front: no grain, print or pore is resolvable anywhere on the subject",+ "reference-measurements.json: colour regions are flat, with hard boundaries",+ ],+}+++def base_material(**overrides):+ material = {+ "id": "vinyl-fur",+ "name": "Matte-to-satin vinyl",+ "type": "physical",+ "shaderModel": "MeshPhysicalMaterial",+ "baseColor": "#2e2a28",+ "roughness": {"base": 0.52, "variation": 0.04},+ "metalness": {"base": 0.0, "variation": 0.0},+ }+ material.update(overrides)+ return material+++def quality_first_spec(materials):+ return {+ "sourceImage": "reference/cat.jpeg",+ "materials": materials,+ "lookDevTargets": {+ "qualityPriority": "reference-fidelity",+ "materialPass": {+ "minimumTextureResolution": 1024,+ "independentMapChannels": ["albedo", "roughness", "height", "normal",+ "ambient-occlusion"],+ "referencePbrExtraction": {"requiredWhenSourceImagePresent": True,+ "targetThreshold": 0.7},+ },+ "lightingPass": {"requiredTerms": ["key light"]},+ },+ }+++class Declaration(unittest.TestCase):+ def test_a_declaration_with_evidence_is_accepted(self):+ errors: list[str] = []+ validate_textureless("m", base_material(textureless=DECLARED), errors)+ self.assertEqual(errors, [])+ self.assertTrue(is_textureless(base_material(textureless=DECLARED)))++ def test_a_declaration_without_evidence_is_rejected(self):+ errors: list[str] = []+ validate_textureless("m", base_material(textureless={"declared": True}), errors)+ self.assertTrue(any("evidence" in error for error in errors), errors)++ def test_an_empty_evidence_list_is_rejected(self):+ errors: list[str] = []+ validate_textureless("m", base_material(textureless={"declared": True, "evidence": [" "]}),+ errors)+ self.assertTrue(any("evidence" in error for error in errors), errors)++ def test_declared_false_is_rejected_rather_than_treated_as_absent(self):+ errors: list[str] = []+ validate_textureless("m", base_material(textureless={"declared": False}), errors)+ self.assertTrue(any("must be true" in error for error in errors), errors)++ def test_a_material_cannot_be_textureless_and_carry_a_texture_field(self):+ for field, value in (+ ("normal", {"strength": 0.4}),+ ("bump", {"amplitude": 0.2}),+ ("displacement", {"amplitude": 0.1}),+ ("surfaceFrequencyBands", [{"id": "macro", "frequency": 2.0, "amplitude": 0.4}]),+ ("textureProjection", {"mode": "uv"}),+ ("textureResolution", 2048),+ ("referencePbr", {"usable": True}),+ ):+ with self.subTest(field=field):+ errors: list[str] = []+ validate_textureless("m", base_material(textureless=DECLARED, **{field: value}),+ errors)+ self.assertTrue(+ any("cannot both have no texture" in error for error in errors), errors+ )++ def test_absent_declaration_changes_nothing(self):+ errors: list[str] = []+ validate_textureless("m", base_material(), errors)+ self.assertEqual(errors, [])+ self.assertFalse(is_textureless(base_material()))+++class QualityBar(unittest.TestCase):+ def test_an_undeclared_material_still_fails_the_texture_channel_bar(self):+ """Negative control: the exemption must not leak to materials that did not declare it."""+ errors: list[str] = []+ warnings: list[str] = []+ spec = quality_first_spec([base_material()])+ validate_look_dev_targets(spec, errors, warnings)+ self.assertTrue(+ any("textureResolution must be >=" in warning for warning in warnings), warnings+ )++ def test_a_declared_material_is_exempt_from_the_texture_channel_bar(self):+ errors: list[str] = []+ warnings: list[str] = []+ spec = quality_first_spec([base_material(textureless=DECLARED)])+ validate_look_dev_targets(spec, errors, warnings)+ for phrase in ("textureResolution must be >=", "surface frequency bands",+ "independent roughness map", "referencePbr extracted"):+ self.assertFalse(+ any(phrase in warning for warning in warnings),+ f"{phrase!r} should not fire on a declared-textureless material: {warnings}",+ )++ def test_the_exemption_is_per_material_not_global(self):+ errors: list[str] = []+ warnings: list[str] = []+ spec = quality_first_spec([+ base_material(textureless=DECLARED),+ base_material(id="painted-metal"),+ ])+ validate_look_dev_targets(spec, errors, warnings)+ offenders = [w for w in warnings if "textureResolution must be >=" in w]+ self.assertEqual(len(offenders), 1, warnings)+ self.assertIn("painted-metal", offenders[0])++ def test_the_declaration_is_hard_validated_through_validate_materials(self):+ errors: list[str] = []+ warnings: list[str] = []+ validate_materials(+ {"materials": [base_material(textureless={"declared": True})]}, errors, warnings+ )+ self.assertTrue(any("textureless.evidence" in error for error in errors), errors)+++class EmittedFactory(unittest.TestCase):+ """A declared-textureless material must not be given a synthesised texture set.++ The emitted `createSculptMaterial` forces `color` to white and `roughness` to 1 whenever a+ texture set exists, and reads both from the generated maps instead. A subject measured to have+ no texture would therefore lose its authored albedo AND its reference-derived roughness, and+ gain mottling that is not in the reference.+ """++ def test_the_emitted_material_skips_texture_synthesis_when_declared(self):+ import generate_threejs_factory as generator++ source = generator._SCULPT_MATERIAL_HELPER_SOURCE if hasattr(+ generator, "_SCULPT_MATERIAL_HELPER_SOURCE"+ ) else generator.generate(_minimal_spec(), "blockout")+ self.assertIn("const textureless =", source)+ self.assertIn("? null", source)+ self.assertIn("makeProceduralTextureSet(id, spec, options)", source)++ def test_a_material_without_the_declaration_still_gets_its_texture_set(self):+ """Negative control: the synthesis path is scoped, not deleted."""+ import generate_threejs_factory as generator++ source = generator.generate(_minimal_spec(), "blockout")+ self.assertIn("makeReferenceTextureSet(spec, options) ?? makeProceduralTextureSet", source)+++def _minimal_spec():+ return {+ "targetName": "Textureless",+ "targetId": "textureless",+ "schemaVersion": "2.1",+ "suitability": "pass",+ "coordinateFrame": {"front": "+Z", "up": "+Y", "scaleReference": "unit"},+ "silhouette": {"boundingShape": "test", "symmetry": "bilateral"},+ "proceduralStrategy": ["blockout"],+ "materials": [base_material(textureless=DECLARED)],+ "buildPasses": [{"id": "blockout", "acceptance": []}],+ "componentTree": [+ {+ "id": "body",+ "name": "Body",+ "level": "macro",+ "role": "body",+ "primitive": "ellipsoid",+ "topologyClass": "continuous-sculpt",+ "topologyRationale": "test",+ "parent": None,+ "material": "vinyl-fur",+ "dimensions": {"width": 1.0, "height": 1.0, "depth": 1.0, "units": "relative"},+ "transform": {"position": [0, 0.5, 0], "rotation": [0, 0, 0]},+ }+ ],+ }+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_tier1_diagnostics.py b/forge/tests/test_tier1_diagnostics.pyindex d5e5fe3..7d3a0f4 100644--- a/forge/tests/test_tier1_diagnostics.py+++ b/forge/tests/test_tier1_diagnostics.py@@ -105,5 +105,58 @@ class BboxOfTest(unittest.TestCase):self.assertEqual((x0, y0, w, h), (4, 2, 6, 6))++class MaskIsRobustToStrayForeground(unittest.TestCase):+ """A bounding box is an extremal statistic, so one stray cell ruins it.++ Measured on a real review plate: a subject filling 24% of the grid reported a bbox of the whole+ 224x224 grid, because the viewer's background gradient registered as foreground. Every+ proportion derived from that bbox was describing the background, and none of them moved when+ the camera did.+ """++ SIZE = 8++ def _mask(self, cells):+ mask = [False] * (self.SIZE * self.SIZE)+ for x, y in cells:+ mask[y * self.SIZE + x] = True+ return mask++ def test_a_stray_cell_is_dropped_from_the_bounding_box(self):+ from diagnose_render import bbox_of, largest_component++ blob = [(x, y) for x in range(2, 5) for y in range(2, 5)]+ with_stray = self._mask(blob + [(7, 7)])+ self.assertEqual(bbox_of(with_stray, self.SIZE), (2, 2, 6, 6))+ filtered, discarded = largest_component(with_stray, self.SIZE)+ self.assertEqual(bbox_of(filtered, self.SIZE), (2, 2, 3, 3))+ self.assertAlmostEqual(discarded, 1 / 10, places=6)++ def test_a_clean_mask_is_returned_unchanged(self):+ """Negative control: the filter must not alter a subject that is already one blob."""+ from diagnose_render import largest_component++ blob = self._mask([(x, y) for x in range(2, 5) for y in range(2, 5)])+ filtered, discarded = largest_component(blob, self.SIZE)+ self.assertEqual(filtered, blob)+ self.assertEqual(discarded, 0.0)++ def test_discarded_geometry_is_reported_rather_than_swallowed(self):+ from diagnose_render import largest_component++ big = [(x, y) for x in range(0, 4) for y in range(0, 4)]+ small = [(x, y) for x in range(6, 8) for y in range(6, 8)]+ _filtered, discarded = largest_component(self._mask(big + small), self.SIZE)+ self.assertAlmostEqual(discarded, 4 / 20, places=6)++ def test_an_empty_mask_does_not_divide_by_zero(self):+ from diagnose_render import largest_component++ filtered, discarded = largest_component([False] * (self.SIZE * self.SIZE), self.SIZE)+ self.assertEqual(sum(filtered), 0)+ self.assertEqual(discarded, 0.0)++if __name__ == "__main__":unittest.main()diff --git a/forge/tests/test_vertex_paint.py b/forge/tests/test_vertex_paint.pynew file mode 100644index 0000000..4b96988--- /dev/null+++ b/forge/tests/test_vertex_paint.py@@ -0,0 +1,384 @@+from __future__ import annotations++import json+import shutil+import struct+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "forge" / "_shared"))+sys.path.insert(0, str(ROOT / "forge" / "stage2_spec"))+sys.path.insert(0, str(ROOT / "forge" / "stage3_build"))++from vertex_paint import ( # noqa: E402+ VertexPaintError,+ dominant_region,+ normalize_vertex_paint,+ paint_point,+ region_weight,+ signed_distance,+)++PAINT = {+ "baseColor": "#1d1b1a",+ "regions": [+ {+ "id": "sock",+ "kind": "axis-band",+ "axis": "y",+ "min": -0.50,+ "max": -0.32,+ "color": "#f2efe9",+ "softness": 0.0,+ },+ {+ "id": "nose",+ "kind": "ellipsoid",+ "center": [0.0, 0.1, 0.4],+ "radii": [0.06, 0.04, 0.05],+ "color": "#141212",+ "softness": 0.01,+ },+ {+ "id": "blaze",+ "kind": "tapered-capsule",+ "start": [0.0, 0.30, 0.20],+ "end": [0.0, -0.05, 0.36],+ "startRadius": 0.03,+ "endRadius": 0.12,+ "color": "#f2efe9",+ "softness": 0.02,+ },+ ],+}++SAMPLE_POINTS = [+ [0.0, -0.40, 0.0],+ [0.0, -0.20, 0.0],+ [0.0, 0.10, 0.40],+ [0.0, 0.00, 0.34],+ [0.0, 0.30, 0.20],+ [0.25, 0.00, 0.34],+ [0.0, -0.325, 0.0],+ [0.02, 0.12, 0.42],+]+++class ShapePredicates(unittest.TestCase):+ def test_axis_band_is_inside_between_its_planes_and_outside_beyond_them(self):+ region = normalize_vertex_paint(PAINT)["regions"][0]+ self.assertLess(signed_distance(region, [0, -0.40, 0]), 0)+ self.assertGreater(signed_distance(region, [0, -0.20, 0]), 0)+ self.assertGreater(signed_distance(region, [0, -0.60, 0]), 0)++ def test_a_hard_boundary_gives_only_zero_or_one_weight(self):+ region = normalize_vertex_paint(PAINT)["regions"][0]+ for point in ([0, -0.40, 0], [0, -0.20, 0], [0, -0.32, 0], [0, -0.3199, 0]):+ self.assertIn(region_weight(region, point), (0.0, 1.0))++ def test_softness_produces_intermediate_weights_only_inside_its_band(self):+ region = normalize_vertex_paint(PAINT)["regions"][1]+ self.assertEqual(region_weight(region, [0.0, 0.1, 0.4]), 1.0)+ self.assertEqual(region_weight(region, [0.0, 0.1, 0.9]), 0.0)+ edge = region_weight(region, [0.0, 0.1, 0.45])+ self.assertGreater(edge, 0.0)+ self.assertLess(edge, 1.0)++ def test_tapered_capsule_radius_grows_from_start_to_end(self):+ region = normalize_vertex_paint(PAINT)["regions"][2]+ near_start = signed_distance(region, [0.05, 0.30, 0.20])+ near_end = signed_distance(region, [0.05, -0.05, 0.36])+ self.assertGreater(near_start, 0.0, "0.05 out is beyond the 0.03 start radius")+ self.assertLess(near_end, 0.0, "0.05 out is inside the 0.12 end radius")++ def test_later_regions_win_where_they_overlap(self):+ paint = normalize_vertex_paint(PAINT)+ # The blaze's wide end covers the nose pad's centre; the blaze is declared later.+ overlap = [0.0, -0.02, 0.35]+ self.assertEqual(dominant_region(paint, overlap), "blaze")++ def test_a_point_claimed_by_nothing_keeps_the_base_colour(self):+ paint = normalize_vertex_paint(PAINT)+ self.assertEqual(dominant_region(paint, [0.9, 0.9, 0.9]), "base")+ self.assertEqual(+ [round(c, 6) for c in paint_point(paint, [0.9, 0.9, 0.9])],+ [round(int("1d", 16) / 255, 6), round(int("1b", 16) / 255, 6), round(int("1a", 16) / 255, 6)],+ )+++class Rejection(unittest.TestCase):+ def test_an_unknown_kind_is_rejected_rather_than_ignored(self):+ with self.assertRaises(VertexPaintError):+ normalize_vertex_paint({"baseColor": "#000000", "regions": [{"id": "x", "kind": "blob", "color": "#ffffff"}]})++ def test_a_zero_radius_ellipsoid_is_rejected(self):+ with self.assertRaises(VertexPaintError):+ normalize_vertex_paint(+ {+ "baseColor": "#000000",+ "regions": [+ {"id": "x", "kind": "ellipsoid", "center": [0, 0, 0], "radii": [0.1, 0, 0.1], "color": "#fff000"}+ ],+ }+ )++ def test_a_capsule_with_identical_endpoints_is_rejected(self):+ with self.assertRaises(VertexPaintError):+ normalize_vertex_paint(+ {+ "baseColor": "#000000",+ "regions": [+ {+ "id": "x",+ "kind": "tapered-capsule",+ "start": [0, 0, 0],+ "end": [0, 0, 0],+ "startRadius": 0.1,+ "endRadius": 0.2,+ "color": "#ffffff",+ }+ ],+ }+ )++ def test_duplicate_region_ids_are_rejected(self):+ with self.assertRaises(VertexPaintError):+ normalize_vertex_paint(+ {+ "baseColor": "#000000",+ "regions": [+ {"id": "a", "kind": "axis-band", "axis": "y", "min": 0, "max": 1, "color": "#ffffff"},+ {"id": "a", "kind": "axis-band", "axis": "y", "min": 2, "max": 3, "color": "#ffffff"},+ ],+ }+ )++ def test_a_bad_colour_string_is_rejected(self):+ with self.assertRaises(VertexPaintError):+ normalize_vertex_paint({"baseColor": "black", "regions": PAINT["regions"]})+++class SpecValidation(unittest.TestCase):+ def _spec_with(self, component_extra: dict) -> dict:+ return {+ "targetName": "T",+ "schemaVersion": "2.1",+ "componentTree": [+ {+ "id": "root",+ "name": "root",+ "level": "macro",+ "role": "body",+ "primitive": "ellipsoid",+ "topologyClass": "continuous-sculpt",+ "topologyRationale": "test",+ "parent": None,+ "dimensions": {"width": 1, "height": 1, "depth": 1, "units": "relative"},+ **component_extra,+ }+ ],+ }++ def test_validator_rejects_a_malformed_paint_block(self):+ from validate_sculpt_spec import validate_components++ errors: list[str] = []+ warnings: list[str] = []+ spec = self._spec_with({"vertexPaint": {"baseColor": "#000000", "regions": []}})+ validate_components(spec, set(), set(), errors, warnings)+ self.assertTrue(any("vertexPaint.regions" in error for error in errors), errors)++ def test_validator_rejects_paint_and_gradient_on_the_same_component(self):+ from validate_sculpt_spec import validate_components++ errors: list[str] = []+ warnings: list[str] = []+ spec = self._spec_with(+ {+ "vertexPaint": PAINT,+ "rootTipGradient": {"rootColor": "#000000", "tipColor": "#ffffff", "axis": "y"},+ }+ )+ validate_components(spec, set(), set(), errors, warnings)+ self.assertTrue(+ any("both write the vertex colour attribute" in error for error in errors), errors+ )++ def test_validator_accepts_a_well_formed_paint_block(self):+ from validate_sculpt_spec import validate_components++ errors: list[str] = []+ warnings: list[str] = []+ validate_components(self._spec_with({"vertexPaint": PAINT}), set(), set(), errors, warnings)+ self.assertFalse([error for error in errors if "vertexPaint" in error], errors)+++class TypeScriptParity(unittest.TestCase):+ """The emitted TS and the Python predicates must agree to floating-point noise.++ They are two transcriptions of the same maths, and the gate reads the Python one while the+ render reads the TS one. If they drift, the gate passes a boundary the viewer never sees.+ """++ def test_python_and_typescript_agree_on_every_sample_point(self):+ node = shutil.which("node")+ if node is None:+ self.fail(+ "node is required for the vertex-paint parity check; without it the Python gate "+ "and the emitted TypeScript are never compared and may silently diverge"+ )+ from generate_threejs_factory import _VERTEX_PAINT_HELPER_SOURCE++ paint = normalize_vertex_paint(PAINT)+ # The helper's only THREE dependency is Color/BufferAttribute; a tiny stub keeps this a+ # pure maths comparison and avoids needing three installed to check the arithmetic.+ harness = (+ "const THREE = {\n"+ " Color: class { r = 0; g = 0; b = 0; constructor(hex?: string){ if (hex) this.set(hex); }\n"+ " set(hex: string){ const n = parseInt(hex.slice(1), 16);\n"+ " this.r = ((n >> 16) & 255) / 255; this.g = ((n >> 8) & 255) / 255;"+ " this.b = (n & 255) / 255; return this; }\n"+ " copy(o: any){ this.r = o.r; this.g = o.g; this.b = o.b; return this; }\n"+ " lerp(o: any, t: number){ this.r += (o.r - this.r) * t;"+ " this.g += (o.g - this.g) * t; this.b += (o.b - this.b) * t; return this; }\n"+ " },\n"+ " BufferAttribute: class { array: any; itemSize: number; count: number;\n"+ " constructor(array: any, size: number){ this.array = array; this.itemSize = size;"+ " this.count = array.length / size; }\n"+ " getX(i: number){ return this.array[i * this.itemSize]; }\n"+ " getY(i: number){ return this.array[i * this.itemSize + 1]; }\n"+ " getZ(i: number){ return this.array[i * this.itemSize + 2]; } },\n"+ "} as any;\n"+ + _VERTEX_PAINT_HELPER_SOURCE+ + "\n"+ "const points = " + json.dumps(SAMPLE_POINTS) + ";\n"+ "const flat = new Float64Array(points.length * 3);\n"+ "points.forEach((p, i) => { flat[i*3] = p[0]; flat[i*3+1] = p[1]; flat[i*3+2] = p[2]; });\n"+ "const geometry: any = { attributes: {} as any,\n"+ " getAttribute(){ return new THREE.BufferAttribute(flat, 3); },\n"+ " setAttribute(name: string, attribute: any){ this.attributes[name] = attribute; } };\n"+ "applyVertexPaint(geometry, " + json.dumps(paint["baseColor"]) + ", "+ + json.dumps(paint["regions"]) + " as any);\n"+ "console.log(JSON.stringify(Array.from(geometry.attributes.color.array)));\n"+ )+ with tempfile.TemporaryDirectory() as directory:+ script = Path(directory) / "parity.ts"+ script.write_text(harness, encoding="utf-8")+ result = subprocess.run(+ [node, "--experimental-strip-types", "--no-warnings", str(script)],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ ts_colors = json.loads(result.stdout)++ py_colors: list[float] = []+ for point in SAMPLE_POINTS:+ py_colors.extend(paint_point(paint, point))++ self.assertEqual(len(ts_colors), len(py_colors))+ for index, (ts_value, py_value) in enumerate(zip(ts_colors, py_colors)):+ # The TS side stores into a Float32Array, so the only admissible difference is that+ # single rounding. Comparing against the float32 image of the Python value makes the+ # assertion exact rather than tolerance-based, which is what keeps it able to catch a+ # small genuine divergence.+ expected = struct.unpack("f", struct.pack("f", py_value))[0]+ self.assertEqual(ts_value, expected, msg=f"channel {index}")++ def test_the_parity_harness_would_catch_a_divergence(self):+ """Negative control: perturbing the Python side must break the comparison.++ Without this, a parity test that silently compared nothing would still pass.+ """+ paint = normalize_vertex_paint(PAINT)+ baseline = paint_point(paint, SAMPLE_POINTS[0])+ mutated = dict(paint)+ mutated["regions"] = [dict(region) for region in paint["regions"]]+ mutated["regions"][0]["min"] = -0.10+ self.assertNotEqual(baseline, paint_point(mutated, SAMPLE_POINTS[0]))+++class GeneratorEmission(unittest.TestCase):+ def test_the_helper_is_emitted_only_when_a_component_declares_paint(self):+ from generate_threejs_factory import vertex_paint++ self.assertIsNone(vertex_paint({"id": "a"}))+ self.assertIsNotNone(vertex_paint({"id": "a", "vertexPaint": PAINT}))++ def test_a_painted_component_gets_a_white_material_albedo(self):+ """Otherwise the authored albedo is applied twice.++ `vertexColors` MULTIPLIES material.color by the vertex colour, and a paint block already+ carries the component's full albedo. Leaving the material's own colour in place squares it:+ a 0.027 linear black against a 0.027 black material renders at 0.0007, and a 0.937 white+ sock comes out at 0.025 — darker than the fur it is supposed to stand out from.+ """+ from generate_threejs_factory import generate++ source = generate(_painted_spec(), "blockout")+ self.assertIn("material.vertexColors = true;", source)+ self.assertIn("as THREE.MeshPhysicalMaterial).color.setRGB(1, 1, 1);", source)++ def test_a_gradient_component_keeps_its_material_albedo(self):+ """Negative control. A root-to-tip gradient is SHADING and is meant to multiply."""+ from generate_threejs_factory import generate++ spec = _painted_spec()+ component = spec["componentTree"][0]+ del component["vertexPaint"]+ component["rootTipGradient"] = {"rootColor": "#000000", "tipColor": "#ffffff", "axis": "y"}+ source = generate(spec, "blockout")+ self.assertIn("material.vertexColors = true;", source)+ self.assertNotIn("color.setRGB(1, 1, 1);", source)++ def test_an_unpainted_component_does_not_enable_vertex_colours_at_all(self):+ from generate_threejs_factory import generate++ spec = _painted_spec()+ del spec["componentTree"][0]["vertexPaint"]+ source = generate(spec, "blockout")+ self.assertNotIn("material.vertexColors = true;", source)+++def _painted_spec():+ return {+ "targetName": "Painted",+ "targetId": "painted",+ "schemaVersion": "2.1",+ "suitability": "pass",+ "coordinateFrame": {"front": "+Z", "up": "+Y", "scaleReference": "unit"},+ "silhouette": {"boundingShape": "test", "symmetry": "bilateral"},+ "proceduralStrategy": ["blockout"],+ "materials": [{"id": "fur", "name": "Fur", "baseColor": "#2e2a28"}],+ "buildPasses": [{"id": "blockout", "acceptance": []}],+ "componentTree": [{+ "id": "body",+ "name": "Body",+ "level": "macro",+ "role": "body",+ "primitive": "ellipsoid",+ "topologyClass": "continuous-sculpt",+ "topologyRationale": "test",+ "parent": None,+ "material": "fur",+ "dimensions": {"width": 1.0, "height": 1.0, "depth": 1.0, "units": "relative"},+ "transform": {"position": [0, 0.5, 0], "rotation": [0, 0, 0]},+ "vertexPaint": PAINT,+ }],+ }+++class MalformedDeclaration(unittest.TestCase):+ def test_a_malformed_declaration_raises_instead_of_degrading_to_flat_colour(self):+ from generate_threejs_factory import vertex_paint++ with self.assertRaises(ValueError):+ vertex_paint({"id": "a", "vertexPaint": {"baseColor": "#000000", "regions": []}})+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_workflow_state.py b/forge/tests/test_workflow_state.pyindex 61fb3ec..37a7ed8 100644--- a/forge/tests/test_workflow_state.py+++ b/forge/tests/test_workflow_state.py@@ -212,6 +212,76 @@ class WorkflowStateTest(unittest.TestCase):self.assertIn("LOCAL_STATE status=active step=image-analysis", result.stdout)self.assertIn("pending mandatory steps", result.stdout)+ def test_next_cli_reads_state_when_init_recorded_a_spec_path_that_is_not_written_yet(self):+ """`state.py init --spec` records where the spec WILL land.++ SKILL.md's documented opening pair is `state.py init ... --spec object-sculpt-spec.json`+ followed immediately by `next.py --state ...`, so the recorded path is absent for the+ whole pre-spec phase. The mandatory gate must still report the checklist there instead of+ failing, otherwise the pipeline cannot be entered by its own instructions.+ """+ with tempfile.TemporaryDirectory() as directory:+ state_path = Path(directory) / "state.json"+ spec_path = Path(directory) / "object-sculpt-spec.json"+ init = subprocess.run(+ [+ sys.executable,+ str(ROOT / "forge" / "state.py"),+ "init",+ "--state",+ str(state_path),+ "--reference",+ "reference.png",+ "--spec",+ str(spec_path),+ ],+ capture_output=True,+ text=True,+ )+ self.assertEqual(init.returncode, 0, init.stderr)+ self.assertFalse(spec_path.exists())+ result = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "next.py"), "--state", str(state_path)],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("LOCAL_STATE status=active step=image-analysis", result.stdout)+ self.assertNotIn("spec error", result.stderr)++ def test_next_cli_still_fails_on_an_unreadable_spec_without_state(self):+ """The pre-spec fallback is scoped to --state; a bare missing spec is still an error."""+ with tempfile.TemporaryDirectory() as directory:+ missing = Path(directory) / "object-sculpt-spec.json"+ result = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "next.py"), str(missing)],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 2)+ self.assertIn("spec error", result.stderr)++ def test_next_cli_reads_a_spec_that_exists_rather_than_the_pre_spec_checklist(self):+ """Negative control for the fallback: once the spec is on disk it must be parsed."""+ with tempfile.TemporaryDirectory() as directory:+ state_path = Path(directory) / "state.json"+ spec_path = Path(directory) / "object-sculpt-spec.json"+ state = new_state("reference.png", spec=str(spec_path))+ setup_ids = [entry["id"] for entry in state["checklist"] if entry["scope"] == "setup"]+ mark_steps(state, setup_ids, status="done", evidence=["setup.json"])+ state_path.write_text(json.dumps(state), encoding="utf-8")+ spec_path.write_text(+ json.dumps({"buildPasses": [{"id": "blockout", "acceptance": []}], "reviewHistory": []}),+ encoding="utf-8",+ )+ result = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "next.py"), "--state", str(state_path)],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("pass=blockout", result.stdout)+def test_next_cli_emits_only_state_ordered_build_command(self):with tempfile.TemporaryDirectory() as directory:state_path = Path(directory) / "state.json"diff --git a/grimoire/build/geometry_patterns.md b/grimoire/build/geometry_patterns.mdindex eeeaf2b..90e268f 100644--- a/grimoire/build/geometry_patterns.md+++ b/grimoire/build/geometry_patterns.md@@ -10,9 +10,17 @@ Use this reference only when implementing a model.- torus: rings, tires, loops, trim, cable coils- shape extrude: logos, flat ornamental plates, blades, keys, leaves- lathe: vases, bottles, bowls, lamps, wheels-- tube along curve: cables, roots, branches, straps, hoses+- tube along curve: cables, roots, branches, straps, hoses — constant radius, so never for anything+ that must come to a point+- tapered-sweep: hair locks, horns, tails, claws, blade tips — anything with a curved spine that+ narrows to a real point. `rx`/`rz` vary per station and framing uses parallel transport, because+ `extrudePath`'s Frenet frames flip 180° at an inflection. Prefer this over `tube` whenever the+ cross-section changes: a lock that does not taper reads as a noodle, and the validator warns when+ authored stations do not actually taper.- instanced mesh: screws, rivets, leaves, needles, scales, pebbles, repeated ornaments-- plane cards: thin leaves, feathers, labels, cloth strips, decals+- plane cards: thin leaves, feathers, labels, cloth strips, decals — needs an alpha texture to read+ as anything but an opaque rectangle, and this pipeline emits no textures. Rejected outright for+ hair.## Material Recipesdiff --git a/grimoire/build/python_threejs_render_bridge.md b/grimoire/build/python_threejs_render_bridge.mdindex f722726..33edef6 100644--- a/grimoire/build/python_threejs_render_bridge.md+++ b/grimoire/build/python_threejs_render_bridge.md@@ -71,8 +71,15 @@ reference hash + reference kind + runtime URL + viewport/DPR + camera transform```Before accepting a render, reopen the saved screenshot with an image-capable tool. Reject-background-only, clipped, stale, unreadable, or incorrectly sized files. Capture fixed,-`±35°`, profile, rear, and head close-up views for a character.+background-only, clipped, stale, unreadable, or incorrectly sized files. When a subject contract+requires six full-body angles, head close-ups do not count toward the six: capture fixed, `±35°`,+profile, rear three-quarter and rear full-body views, then capture head views separately.++The default manifest stores orbit cameras as `azimuthDegrees`, `elevationDegrees` and `target`.+For paired GLB/model evidence, also author an explicit shared `distance` and `fovDegrees`; deriving+distance independently from each subject's auto-frame produces different cameras even when the+azimuths match. Treat `near` and `far` as shared camera fields too. A reference-only camera override+is forbidden: the one capture record is the authority for both routes.## GLB-mediated v2 passes@@ -100,6 +107,10 @@ python3 forge/stage4_review/compare_region_passes.py \The comparison blocks per-region claims when the semantic-ID pass or region colors are absent.It is a deterministic diagnostic, not an AI likeness score.+See also: `integrations/glb_character_pipeline/` for an opt-in, GLB-baseline reconstruction pipeline+(SDF point-cloud splat + Surface Nets) that produces the procedural TypeScript/three.js character this+bridge captures passes from — distinct from this doc's own manifest/pass-recording contract.+## Failure routing- no browser/MCP: `request-input` and ask for installation/authentication;@@ -146,7 +157,7 @@ route must expose this small browser-side contract:```jswindow.__IMG2THREEJS_READY__ = true;window.__IMG2THREEJS_CAPTURE__ = {- async setCamera({ azimuthDegrees, elevationDegrees, target, near, far }) {+ async setCamera({ azimuthDegrees, elevationDegrees, target, distance, fovDegrees, near, far }) {// Apply the camera and controls to the real Three.js scene, then resolve.},async capturePass({ passId, mode }) {@@ -158,6 +169,13 @@ window.__IMG2THREEJS_CAPTURE__ = {If the ready signal, capture contract, canvas, screenshot, or hash check fails, the adapter stops.It does not fall back to a Python/Blender image and does not claim that a render happened.+For an asynchronously loaded multipart GLB, install the capture API immediately but enumerate its+meshes and allocate anonymous ID materials only after the route's `ready` promise resolves. Capture+must fail if the post-ready mesh count differs from the probed contract. Enumerating an empty group+at bridge installation time can otherwise yield a plausible beauty image and empty semantic-ID+passes. Anonymous object IDs prove physical boundaries only; generic `model.*` names never become+garment or anatomy labels.+## Prohibited shortcuts- Do not use Python to claim it rendered Three.js when it rendered Blender instead.diff --git a/grimoire/build/threejs_skin_and_cloth_materials.md b/grimoire/build/threejs_skin_and_cloth_materials.mdnew file mode 100644index 0000000..b60a6ce--- /dev/null+++ b/grimoire/build/threejs_skin_and_cloth_materials.md@@ -0,0 +1,222 @@+# Three.js for skin and cloth — what the engine actually does++Distilled from the **source of the exact version the showcase pins, `[email protected]`**, not from the+docs site. Every number below is a `file:line` citation into `node_modules/three/src`, because the+docs page omits the clamps, the foldings and the energy terms — and those are precisely what decides+whether an authored number reaches the pixel.++Read this before choosing a material for skin or cloth. Its purpose is to stop the two failure modes+that cost the most: **authoring a value the engine ignores**, and **exposing one degree of freedom+twice as if it were two**.++---++## 1. Sheen — the cloth carrier++### The mechanism++| Fact | Source |+|---|---|+| BRDF is Estevez & Kulla 2017 "Production Friendly Microfacet Sheen", `D_Charlie` distribution | `shaders/ShaderChunk/lights_physical_pars_fragment.glsl.js:320,337,345` |+| The sheen term is `sheenColor * (D * V)` — a **multiply** by colour | `…lights_physical_pars_fragment.glsl.js:348` |+| `sheenColor` default is **`0x000000`** | `materials/MeshPhysicalMaterial.js:52` |+| `sheenRoughness` default is **`1.0`** | `materials/MeshPhysicalMaterial.js:54` |+| The uniform is uploaded **only when `sheen > 0`** | `renderers/webgl/WebGLMaterials.js:406` |+| `sheen` is folded into the colour: `uniforms.sheenColor = sheenColor × sheen` | `renderers/webgl/WebGLMaterials.js:408` |+| `sheen` crossing zero bumps `material.version` → shader recompile | `materials/MeshPhysicalMaterial.js` getter/setter on `_sheen` |++### Three consequences that must be encoded, not remembered++**S-1. `sheen` alone does nothing.** Default `sheenColor` is black and the term is a multiply, so+`sheen: 0.65` with an untouched `sheenColor` contributes exactly `0`. A fabric profile that specifies+`sheen` and omits `sheenColor` is specifying nothing.++> Status in this repo: `generate_threejs_factory.py` already defaults `sheenColor` to `#ffffff`+> (grep `sheenColor:` — it is the file's only occurrence, in the emitted+> `MeshPhysicalMaterial` constructor)+> rather than three's black, so emitted code escapes the trap. But **no registry profile declares+> `sheenColor`** — `fabric.woven-matte` and `hair.human.code-only` both give `sheen` without it. The+> tint therefore comes from a generator fallback and is never reference-derived. Fix by adding+> `sheenColor` to the profile, not by changing the fallback.++**S-2. `sheen` and `sheenColor` are ONE degree of freedom, not two.** They are multiplied before+upload, so `sheen: 1.0, sheenColor: #808080` is bit-identical to `sheen: 0.5, sheenColor: #ffffff`.+A spec that extracts both from the reference as independent evidence is extracting the same number+twice and will produce contradictory-looking priors that render identically. **Extract one: the+sheen tint. Keep `sheen` as a scalar strength with a fixed authored default.**++**S-3. Turning sheen on makes the cloth DARKER, by a computable amount.**++```glsl+float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );+outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;+```+`ShaderLib/meshphysical.glsl.js:205,207`++With full white sheen the diffuse base is scaled by `0.843` — **a 15.7% darkening** — before the+sheen lobe is added back. So a garment whose base colour is matched to the reference *and then* given+sheen renders darker than the reference at every non-grazing angle. The correction is predictable:++```+effective_sheen_strength = sheen × max(sheenColor.r, .g, .b)+base_darkening = 0.157 × effective_sheen_strength+compensated_base_colour = target_colour / (1 - base_darkening)+```++This is a **gate-able number**, not a matter of taste: given the authored sheen, the expected+darkening is known in advance, so a cloth region that is darker than the reference by roughly+`0.157 × strength` is diagnosable as "sheen applied without base compensation" rather than as a+generic colour miss.++### Choosing sheenRoughness++`sheenRoughness` is the Charlie distribution width, so it maps to how tight the grazing rim is:++| Fabric | `sheenRoughness` | reads as |+|---|---|---|+| cotton, linen, wool, felt | `0.7 – 1.0` | broad, soft, almost no visible rim |+| brushed / matte synthetic | `0.5 – 0.7` | a wide band |+| satin, silk | `0.15 – 0.35` | a narrow bright rim — the satin signature |++Low `sheenRoughness` on a low-poly garment concentrates the rim onto a few facets and reads as+plastic. Prefer the high end unless the reference clearly shows a satin rim.++---++## 2. Clearcoat — the skin carrier++### The mechanism++| Fact | Source |+|---|---|+| `clearcoatF0` is **fixed at `0.04`** and is not authorable | `ShaderChunk/lights_physical_fragment.glsl.js:56` |+| `clearcoatRoughness` is **clamped up**: `max(clearcoatRoughness, 0.0525)` | `…lights_physical_fragment.glsl.js:72` |+| Geometric roughness is **added**: `clearcoatRoughness += geometryRoughness` | `…lights_physical_fragment.glsl.js:73` |+| The same addition applies to base roughness: `material.roughness += geometryRoughness` | `…lights_physical_fragment.glsl.js:9` |+| `geometryRoughness = max(max(dxy.x, dxy.y), dxy.z)` from normal derivatives | `…lights_physical_fragment.glsl.js:6` |+| `clearcoat` crossing zero bumps `material.version` | `MeshPhysicalMaterial.js` `_clearcoat` setter |+| `clearcoatRoughness` default `0.0`, `clearcoatNormalScale` default `(1,1)` | `MeshPhysicalMaterial.js:27,29` |++### Two consequences++**C-1. `clearcoatRoughness` below `0.0525` is a lie.** Authoring `0.0` and authoring `0.05` produce+the identical render. A validator must not accept a value below the clamp as if it were meaningful,+and evidence extraction must not report one.++**C-2. Faceting roughens skin automatically, and this is the low-poly coupling.** `geometryRoughness`+comes from screen-space normal derivatives, so **flat shading raises it at every facet edge**. A+clearcoat tuned on smooth geometry will read blurrier on the same figure flat-shaded, at no change to+the material. Consequences for this pipeline, which deliberately uses a low-poly faceted language:++- Skin clearcoat should be authored on the **final tessellation**, never on a smooth proxy.+- Two components with the same skin material but different facet density will not match. That is an+ engine property, not a bug, and it is why skin cannot be gated on absolute specular response.+- It is another reason the standing rule holds: **never gate roughness from a reference with unknown+ lighting — report only.** Here even the *geometry* moves the number.++### Why clearcoat and not transmission for skin++Skin's real signature at this fidelity is a **broad soft dielectric highlight sitting over a warm+diffuse base** — which is exactly a low-strength, mid-roughness clearcoat over a warm base colour.+`clearcoat 0.1–0.3` with `clearcoatRoughness 0.3–0.5` produces it with two numbers and no maps.++---++## 3. Transmission and thickness — rejected for skin, with the reason++`transmission` is a **screen-space refraction** approximation: it needs `transparent: true`, a+transmission render target, and it samples the backbuffer. It is a glass model, not a subsurface+model.++| Fact | Source |+|---|---|+| `thickness` default `0`, `attenuationDistance` default `Infinity` | `MeshPhysicalMaterial.js:59,61` |+| `attenuationColor` default white | `MeshPhysicalMaterial.js:62` |+| The generator already forces `transparent` when `transmission > 0` | `generate_threejs_factory.py`, emitted `transparent:` in the `MeshPhysicalMaterial` constructor |++On a closed opaque body mesh, transmission produces a glassy figure, not fleshy skin — and it costs a+full extra render target. The registry already states the honest limit: *"MeshPhysicalMaterial has no+true multilayer skin subsurface scattering"* (`docs/materials/material-reference.json`, `skin.human`).++**Rule: skin never sets `transmission`.** Approximating SSS with a glass model and presenting the+result as reconstruction is invention. Thin-membrane translucency — an earlobe, a nostril rim, a+webbed finger — is the only legitimate use, is a *separate* material on a *separate* thin component,+and must be declared as an approximation.++---++## 4. Degrees of freedom that are secretly the same++Exposing either pair twice creates specs that look richer than they are and priors that contradict+each other while rendering identically.++| Pair | Relation | Source |+|---|---|---|+| `sheen` × `sheenColor` | multiplied into one uniform before upload | `WebGLMaterials.js:408` |+| `ior` ↔ `reflectivity` | `reflectivity = clamp(2.5(ior−1)/(ior+1), 0, 1)`; writing `reflectivity` writes `ior = (1+0.4r)/(1−0.4r)` | `MeshPhysicalMaterial.js:34–44` |++**Author `ior`, never `reflectivity`.** `ior` is the physical quantity, has a meaningful range+(skin ≈ 1.33–1.5, most fabric ≈ 1.45–1.55), and `reflectivity` is a derived view of it.++---++## 5. Base-material facts that bite cloth specifically++| Fact | Default | Why it matters for a garment | Source |+|---|---|---|---|+| `side` | `FrontSide` | A garment shell open at hem, cuff or collar shows **nothing** through the opening — backfaces are culled, so the inside of the sleeve is a hole. Any garment with an open boundary needs `DoubleSide`, and `shadowSide` set so it still casts. | `Material.js:24` |+| `vertexColors` | `false` | Must be enabled explicitly. Materials are shared by id, so **clone before enabling** or every component sharing the material gets tinted — the generator already does this for `rootTipGradient`. | `Material.js:25` |+| `flatShading` | `false` | The low-poly language depends on it, and it raises `geometryRoughness` (§2 C-2). | `Material.js:382` (toJSON) |+| `roughness` / `metalness` | `1.0` / `0.0` | A fabric left at default roughness `1.0` is already correct-ish; skin is not. | `MeshStandardMaterial.js:20,21` |+| `polygonOffset` | `false` | Cloth offset from skin by a small clearance can still z-fight where the offset approaches zero. Prefer real geometric clearance (`standProud`) over depth tricks. | `Material.js` |++---++## 6. Geometry: which component for which garment part++The trap this section exists to prevent is reaching for a named convenience geometry because its name+matches the noun.++| Need | Use | Do **not** use, and why |+|---|---|---|+| Sleeve, trouser leg, anything tapering along a curved spine | **`tapered-sweep`** (this repo's primitive; parallel transport framing) | `TubeGeometry` — constant radius, reads as a noodle. `ExtrudeGeometry` with a path — Frenet frames flip 180° at an inflection. |+| A garment body that must follow the torso's own section | **offset surface derived from the covered components' ring stack**, then `standProud` | `LatheGeometry` — a revolve is circular before scaling, so it cannot express a torso's front/back asymmetry. Authoring `rx ≠ rz` on a lathe describes a surface the geometry does not have (this repo already gates that case). |+| Hem, waistband, collar edge — a crisp boundary | **plain intersection against a slab** (`max`, not `smin`) | A smooth union / `smin` — it rolls the edge, and a rolled hem is visibly not a hem. |+| Flat trim, a patch, a badge | `ShapeGeometry` / `ExtrudeGeometry` from a `Shape` | `PlaneGeometry` + alpha — needs a texture this pipeline cannot emit. |+| Repeated fasteners: buttons, studs, eyelets | `InstancedMesh` (this repo's `instanced-cluster`) | Individual meshes — cost with no fidelity gain. |+| Cloth folds and wrinkles | **geometry**, at meso scale, or nothing | `normalMap` — no textures. `displacementMap` — same. The registry's own `fabric.woven-matte` note already says *"Large folds and hems belong in geometry"*. |++**`side: DoubleSide` is a geometry decision as much as a material one:** if a garment is authored as a+closed offset volume rather than an open shell, `FrontSide` is correct and cheaper. Choose closed+volumes where possible and reserve `DoubleSide` for genuinely open boundaries.++---++## 7. What no Three.js feature can give this pipeline++Stated so it is never planned around:++- **No true skin subsurface scattering.** `MeshPhysicalMaterial` has no multilayer SSS. `transmission`+ is a glass model (§3).+- **No cloth simulation.** Three.js has no cloth solver, and a single reference image contains no+ motion and no material parameters to fit one against.+- **No per-fibre or per-thread detail without textures.** Sheen is the whole of the woven cue+ available to a code-only pipeline.+- **No alpha-cut silhouette detail.** Which is why `plane-card` is rejected for hair and for cloth+ trim alike.++---++## 8. The authored-value checklist++Before a skin or cloth number reaches a spec:++- [ ] Does the engine read it at all, or is it gated behind another value being `> 0`? (`sheen`,+ `clearcoat`, `transmission`, `iridescence`, `anisotropy` all gate their own uniform block.)+- [ ] Is it clamped? (`clearcoatRoughness` ≥ `0.0525`.)+- [ ] Is something added to it at shade time? (`geometryRoughness` → `roughness`, `clearcoatRoughness`.)+- [ ] Is it multiplied into another value before upload, making the pair one degree of freedom?+ (`sheen` × `sheenColor`.)+- [ ] Is it a derived view of a different property? (`reflectivity` of `ior`.)+- [ ] Does it require a map this pipeline cannot emit? If yes, the value is decoration.+- [ ] Does turning it on change the base layer? (`sheenEnergyComp` darkens by `0.157 × strength`.)diff --git a/grimoire/readiness/standard_character_pipeline.md b/grimoire/readiness/standard_character_pipeline.mdindex 922c4c8..d48fd60 100644--- a/grimoire/readiness/standard_character_pipeline.md+++ b/grimoire/readiness/standard_character_pipeline.md@@ -95,18 +95,27 @@ The capture adapter waits for readiness, rejects fatal console errors and zero-ssets the camera, waits for settled frames, saves PNGs inside the workspace, reopens them with animage-capable reader, and records hashes in the manifest. Python never renders a replacement scene.+For paired GLB/model batches, each capture record owns one complete camera specification shared by+both routes: azimuth, elevation, target, distance, FOV, near and far. Do not auto-frame the GLB and+procedural model separately. If the GLB loads asynchronously, enumerate its multipart meshes and+build diagnostic ID materials after readiness, then compare the executed count to the intake probe.+## Required character capture batch```texthero/reference-matchorbit +35°orbit -35°-profile ~78°+profile 90°+rear three-quarter 135°rear 180°head herohead three-quarter```+This is six full-body angles plus two head controls. A head crop cannot substitute for a missing+full-body azimuth when the reconstruction contract requires six whole-character views.+Only the fixed view is pixel/feature aligned to the supplied reference. Orbit views are judgedfor volume, attachment, rear coverage, hair continuity, deformation and non-degenerate form.diff --git a/grimoire/review/gates_reference.md b/grimoire/review/gates_reference.mdindex e2bb541..cea0182 100644--- a/grimoire/review/gates_reference.md+++ b/grimoire/review/gates_reference.md@@ -24,10 +24,54 @@ only the executable order and one-line summary; this file defines the mandatorypainted-region mismatch, critical identity-detail failure, finish/material response failure,and degenerate orbit form. It records exactness tier, hidden-region confidence, per-regionconfidence, approximation notes, camera, environment hash, exposure, tone mapping, resolution,- background, and renderer version.+ background, and renderer version. The CS2 family boundary covers supported **knife** subtypes and+ the **Glock-18** pistol; every other family and unknown subtype must stop with+ `unsupported-family` or `unsupported-subtype`, and must never receive another family's component+ tree as a generic fallback. Registering a family is not implementing its geometry. Authoritative+ boundary and intake order: `grimoire/intake/cs2_intake_contract.md` and `SKILL.md`'s CS2 section.- **Bounded correction loop (token-burn safety)**: `forge/stage4_review/correction_loop.py`guarantees termination (success/repeated-defect/oscillation/plateau/hard-ceiling), escalating to- `request-input` — never a silent infinite burn.+ `request-input` — never a silent infinite burn. Hard gates route to `refine-code`; repeated defects+ and oscillation route to `refine-spec`. Deterministic analysis-by-synthesis parameter fitting and+ Divine Eye provenance: `grimoire/build/analysis_by_synthesis_fitting.md`.+- **Executable Divine Eye fitting**: `fit_against_divine_eye()` in+ `forge/stage4_review/fit_params.py` connects deterministic parameter-to-render callbacks to+ bounded gate-aware Divine Eye optimization. Clean candidates use raw fidelity; hard-gated+ candidates score below all clean results while retaining original fidelity and provenance. The+ returned objective and optional selected raw fidelity are explicit, and each copied record has+ candidate/reference/render provenance. It lazily loads the default evaluator and returns+ normalized raw-fidelity correction-loop provenance without mutating sources.+- **Interior difference (required per visual pass)**: `forge/stage4_review/interior_difference.py`+ measures appearance INSIDE the silhouette, banded by height. Silhouette IoU is computed from+ roughly 11% of figure cells — the ones on the outline — so it is blind to the other 89%. Measured:+ a finished face and the same model with its face DELETED both scored 0.8803, identical to four+ decimals, and adding an entire mouth moved the outline metric −0.0002, in the wrong direction. An+ outline metric must never be the signal a correction loop optimises for interior work. It refuses+ to score when either foreground mask fell back to whole-frame coverage, and reports `cellsCompared`+ so a difference measured over a handful of cells cannot pass as evidence.+- **Chirality (spec time, HARD)**: `validate_chirality` in `forge/stage2_spec/validate_sculpt_spec.py`+ requires every `-l`/`-r` pair to be a sagittal MIRROR, not a rotated copy. Negating x *and* z is a+ 180° rotation about Y, and rotation preserves handedness, so both limbs come out the same hand.+ What this CANNOT catch, so nobody trusts a green result too far: a pair wrong the SAME way on both+ sides is still a perfect mirror of itself, and needs `chirality.medial_lateral_bias` against a+ reference. Convention as code: `forge/_shared/chirality.py`.+- **Scalp exposure (HARD, hair subjects, before any render)**:+ `forge/stage4_review/scalp_exposure.py` finds bald patches geometrically, on points, so it needs no+ browser and no capture. Exposure above `--hard-max` is always a failure. It counts only hair+ OUTSIDE the skull — a nearest-neighbour test passes the failing build, because those vertices were+ still nearby, merely sunk below the surface. Silhouette IoU cannot see a bald crown (it is+ interior) and interior difference cannot separate it from a colour shift.+- **Hair gate (soft, hair subjects)**: `forge/stage4_review/hair_gate.py` compares banded coverage,+ hairline offset and highlight-band position. Its verdict is subordinate to `scalp_exposure`. **A+ coverage shortfall never authorises widening the masses on its own** — doing so took closure from+ 42.2% to 40.9%, worse on all six views, with crown exposure up 14.9 points on the worst view,+ because the widened masses slid off the skull. Full record: `docs/HAIR_PIPELINE.md`.+- **Procedural rig contract**: for humanoid/character builds, validate the authored+ `joints`/`parents`/`names`/`matrix_local`/packed skin payload with+ `forge/stage5_rig/validate_rig_payload.py` before binding `THREE.Skeleton`. The gate proves+ structural payload integrity only; pose stress, dynamic bounds, readable screenshots, and+ visual likeness remain separate gates. Payload ownership and non-goals:+ `grimoire/readiness/procedural_rigging_contract.md`.- **Tier 1 (legacy, still valid)**: "Tier 2 (AI-vision) never runs against a render that has not passed Tier 1." Run `forge/stage4_review/diagnose_render.py` (silhouette IoU/proportion/symmetry/per-part color) and record it (`--spec ... --in-place`) before requesting a comparison sheet; `orchestrate_passes.py check` refuses otherwise.- **Pre-spec / strict-quality**: blocks code gen until the spec is deep enough for its contract.- **Screenshot feedback**: `continue` is allowed only with a render + comparison sheet + globaldiff --git a/grimoire/scripts.md b/grimoire/scripts.mdindex 2113481..fcfbd3e 100644--- a/grimoire/scripts.md+++ b/grimoire/scripts.md@@ -80,6 +80,31 @@ future `--pass-id` fails until earlier passes are reviewed `continue`. Output ex`root.userData.sculptRuntime` (nodes/meshes/sockets/colliders/destructionGroups) — hand-refine it.`--allow-nonstrict` is reserved for legacy test fixtures and must not be used for production output.+### Executed geometry gates before browser capture++After generation, execute the factory without a renderer and inspect+`root.userData.sculptRuntime`; do this before opening the browser. For multipart characters, the+pre-browser report must cover every named spec component and measure, where applicable:++- left/right reflection from world-space bounds, plus thumb/index chirality for hands;+- ordered garment-shell intervals so a waist layer cannot sink into the layer beneath it;+- every `geometry.userData.standProud.unresolved` count (zero is the exact pass condition);+- engine-visible `material.userData.referenceMaterialId`, not an ignored authoring field;+- garment boundary positions against the relevant articulation joints, not all unrelated bones.++Global width/height/depth ratios may be recorded against a GLB baseline, but remain diagnostic and+must declare themselves uncalibrated until paired multi-angle silhouette controls establish an+acceptance threshold. Do not turn an arbitrary ratio tolerance into a gate. Every exact gate added+for a showcase needs a passing fixture and a mutation that makes it fail (missing mesh, same-side+reflection, sunk layer, swapped thumb, unresolved proud vertex, missing material ID, or boundary+moved onto its joint). A clean TypeScript build is not executed-geometry evidence.++Ordinary primitives stay on their authored geometry path: generated factories do not invent an+attachment variable for them, and the shared endpoint branches retain the declared+`AttachmentEndpoint | null` helper return type rather than a literal null that strict TypeScript+narrows to `never`. Verify that negative-control path with a spec containing no attachment-derived+primitives before accepting the showcase build.+## Forge subdivision runtime validationRuntime subdivision tests compile generated TypeScript against `img2threejs-showcase`. Set`IMG2THREEJS_SHOWCASE_ROOT` to that checkout. Without it, runtime-only cases skip locally with an@@ -183,7 +208,9 @@ materialSurface, lightingCamera`. Records one self-correction entry into `review`stage4_review/validate_render_profile.py docs/specs/render-profile.v2.example.json`validates the shared browser renderer/camera/environment contract. Use it when initializing-the GLB-mediated route:+the GLB-mediated route. `regions` must name the actual subject regions; list the mandatory subset+under `extensions.requiredSemanticRegions`. The validator rejects missing declared regions and does+not impose the example subject's names on another reconstruction:`stage4_review/render_bridge.py init --reference-glb GLB --render-profile PROFILE --runtime-url URL --out render-manifest.json`@@ -311,8 +338,107 @@ local geometry is fine, and local space would hide exactly that. Normals go throinverse-transpose. Every mesh it declines to emit — instanced, over the triangle cap, filtered out —is listed with its reason, so a short mesh list cannot be mistaken for a clean one.+### stage4_review/vertex_region_gate.py+`stage4_review/vertex_region_gate.py --geometry meshes.json --palette palette.json [--expect expect.json] [--azimuth 0] [--color-tolerance T] [--max-unclassified N] [--out report.json] [--json]`+Gates colour-region BOUNDARIES on executed geometry, before any browser render. When a subject's+identity is carried by flat colour regions with hard edges — a tuxedo cat's blaze, bib and socks; a+livery stripe; a painted marking — the position of those boundaries is an identity feature, so it is+measured rather than eyeballed. `--palette` is `{regionId: '#rrggbb'}` for every region to measure;+without `--expect` the gate only reports measurements instead of passing or failing. Read+`--max-unclassified`: vertices matching no palette entry are named, so a clean verdict over a mostly+unclassified mesh cannot be mistaken for agreement. The shape predicates it shares with the+validator and the emitted TypeScript live in `_shared/vertex_paint.py` (no CLI).++### stage4_review/swept_arc_gate.py+`stage4_review/swept_arc_gate.py --geometry meshes.json --component ID [--expect expect.json] [--out report.json] [--json]`+Gates a swept component's SHAPE — bend radius, angular span and taper — on executed geometry.+"Curled upward into a hook; a curved spine, not a straight cone" is a claim about a curve, and no+other gate can hold it: a silhouette IoU passes a straight cone that happens to occupy roughly the+right cells, and `self_intersection.py` asks whether a mesh crosses itself rather than what shape it+is. `--component` takes a mesh id or name.+## Reference comparison and baselines+### stage4_review/interior_difference.py+`stage4_review/interior_difference.py BASELINE.png RENDER.png [--from 0] [--to 0.19] [--json]`+Appearance difference **inside** the silhouette, banded by height. Required evidence on every visual+pass, because silhouette IoU is computed from roughly 11% of figure cells — the ones on the outline —+and is blind to the other 89%. The measured proof: a model with its face deleted scored 0.8803+against the finished face's 0.8803, identical to four decimals, and adding an entire mouth moved+that metric −0.0002. Both renders are aligned by foreground bounding box, the same normalisation the+IoU scorer uses, and only cells that are figure in **both** are compared so outline agreement cannot+leak back in. Refuses to score when either foreground mask fell back to whole-frame coverage — the+same hard gate `divine_eye` makes, for the same reason. Reports `cellsCompared`, so a difference+measured over a handful of cells cannot pass as evidence. On a standing figure the head is roughly+`--from 0 --to 0.19`.++## Hair++Full contract, every measurement behind it, and every stated non-goal: `docs/HAIR_PIPELINE.md`.+Run these only when the subject has hair — `orchestrate_passes.py` demands them via+`spec_has_hair()`, which reads a `hairProfile` block or any component whose role is `hair`, so a+chair and a knife are never asked for hair evidence.++### stage1_intake/extract_hair_evidence.py+`stage1_intake/extract_hair_evidence.py front=ref.front.png rear=ref.rear.png [--out evidence.json]`+Measures what the reference actually says about its hair: the hair/skin split, banded dark coverage+across crown/mid/jaw, the hairline (writing the `faceLandmarks.hairline` slot that existed unfilled+since v1.2), the specular band position, and the root-to-tip luminance delta. Views not supplied are+reported as `notObserved`, so nothing downstream authors a nape as if it had been seen. The split is+Otsu's between-class variance, not a percentile: a fixed percentile makes the reported hair fraction+true by construction and read 0.380 / 0.384 / 0.382 across three different views of one subject,+which looks like agreement and is arithmetic. The same three views now read 0.387 / 0.592 / 0.747.++### stage4_review/scalp_exposure.py — HARD+`stage4_review/scalp_exposure.py --rings skull.json --hair-points hair.json [--v-low 0] [--v-high 1] [--hard-max 0.05] [--out report.json]`+Finds bald patches geometrically, on points, before anything is rendered — so it needs no browser, no+GPU and no capture, and works on any hair representation. It counts only hair **outside** the skull:+a nearest-neighbour test passes the failing build, because those vertices were still nearby, merely+sunk below the surface. Exposure above `--hard-max` is a hard failure, never a soft signal.+`--hard-max` is deliberately loose and uncalibrated, and the report says so.++### stage4_review/hair_gate.py — soft+`stage4_review/hair_gate.py --reference front=ref.png --render front=out.png [--scalp-exposure report.json] [--out gate.json]`+Compares banded coverage, hairline offset and highlight-band position against the reference, and+classifies each difference by kind. Pass `--scalp-exposure` and its verdict dominates: a bald patch+is always wrong, while a coverage shortfall is often the best available compromise at a given+triangle budget. Conflating the two produced four wrong fixes in one session — a shortfall was read+as "add more hair", the masses were widened, and the widening pushed them off the skull, taking+closure from 42.2% to 40.9%, worse on all six views, with crown exposure up 14.9 points on the worst.+**A coverage shortfall never authorises widening the masses on its own.**++### Hair libraries (no CLI)+- `_shared/scalp_field.py` — signed distance to a skull built as a stack of ellipse rings, derived+ from the head component so it is never authored twice. Sign is exact; magnitude is the first-order+ estimate `f / |grad f|`, so treat the sign as authoritative and the magnitude as approximate.+- `stage2_spec/hair_profile.py` — the hairstyle schema and its validation rules. Roots are `(u, v)`+ on the scalp; an absolute root is a hard error. `plane-card`, `tube` and `box` are rejected for+ hair. Default representation tier is `shell`. **This module validates a profile; it does not+ compile one into components** — no profile-to-`componentTree` compiler exists yet.++## Left and right++### _shared/chirality.py (no CLI)+Two chirality defects can ship in one figure and need **different** tests, which is why both exist:+- `check_pair()` — enforced at spec time by `validate_sculpt_spec.py`. A pair built by negating x+ *and* z is a 180° rotation, and rotation preserves handedness, so both limbs come out the same+ hand. It names the relation (`rotation` / `translation` / `unrelated`) rather than saying+ "mismatch", because the two are trivially confused and agree exactly on a symmetric part.+ Measured on the humanoid: the thumb tip sat at z ±0.288 across the pair where a mirror leaves z+ alone; fixing it moved the hand region **46% closer** to the reference in front view.+- `medial_lateral_bias()` + `compare_bias()` — needs a reference. Catches what a pair test+ structurally cannot: a pair wrong the *same* way on both sides is still a perfect mirror of+ itself. Only the **sign** of the bias is judged; a magnitude difference is a proportion issue that+ other gates own. Measured on the humanoid: toes ordered little-to-big across a strip whose index 0+ is medial put the big toe outboard on *both* feet — toe-band mass reference 529 medial / 488+ lateral, ours 350 / 443 — and a foot with its big toe outside is the other foot. Below `MIN_REFERENCE_BIAS` (0.025) the reference is treated as too symmetric to+ judge handedness from.++`CHARACTER_LEFT_SIGN` is the convention as code: with `forward: +Z`, Y up and a right-handed frame,+the character's own left is `+X`. Reflecting also inverts triangle winding — flip it back on the+mirrored side, or `flatShading` derives every normal from the reversed winding and the limb lights as+though lit from behind.+### stage4_review/mesh_reference_compare.py`stage4_review/mesh_reference_compare.py REFERENCE.glb CANDIDATE.glb [--bands N] [--json]`Says **where** a candidate is wrong, band by band, instead of returning one aggregate score. Bothdiff --git a/integrations/glb_character_pipeline/.python-version b/integrations/glb_character_pipeline/.python-versionnew file mode 100644index 0000000..2c07333--- /dev/null+++ b/integrations/glb_character_pipeline/.python-version@@ -0,0 +1 @@+3.11diff --git a/integrations/glb_character_pipeline/PIPELINE.md b/integrations/glb_character_pipeline/PIPELINE.mdnew file mode 100644index 0000000..f252f5d--- /dev/null+++ b/integrations/glb_character_pipeline/PIPELINE.md@@ -0,0 +1,385 @@+# Character Pipeline++**Packaged here** as an opt-in img2threejs integration (see `README.md`): parameterised, runnable copies+of the character-agnostic scripts under `python/` and `node/`, a generic orchestrator+(`build-character.sh`), and two `.env` configs (`configs/girl-character.env`, reproducing girl-character's+own build; `configs/example.env`, a template for a new reference). This integration runs entirely against+a companion `img2threejs-showcase` checkout, pointed to via `IMG2THREEJS_SHOWCASE_ROOT` — every showcase-+relative path below (`public/mesh/`, `work/progress.txt`, `src/demos/...`) means "inside that checkout,"+never inside this repo.++Distilled from building `girl-character` in that showcase: a GLB baseline reconstructed as code-only+TypeScript/three.js, with a fully procedural walk rig and no external asset fetched at runtime. This+document is the reusable process, kept separate from the demo's own source so it can be applied to the+next character. Where a stage references a script by a bare `scripts/...` path, that script lives only in+the showcase repo's own top-level `scripts/` (character-specific, not packaged here); where it references+`python/...` or `node/...`, that is a script packaged in this integration.++Everything here is grounded in the showcase's own `work/progress.txt` (48 recorded runs as of packaging)+and the actual scripts. Where a step says "measure," it means a script produced a number before the next+decision was made — not that the number was assumed.++## When to use this++You have a multipart GLB (or several — a PBR and a shaded variant, ideally) as a **measurement target**,+not an asset to ship, and you want a character that:+- renders from TypeScript/three.js code alone, with no `.glb`/`.bin` fetched by the running demo+- matches the baseline's silhouette and surface character closely enough that the two are hard to tell+ apart in a side-by-side, while remaining honest that it is a reconstruction, not a copy+- animates (at minimum a walk cycle) without a rig baked into the source file++## Applicability gate — GLB is optional, check for it before anything else++**A GLB reference is optional for a character build, and this whole integration only applies when one+exists.** Before running anything below, check the current build request for a GLB reference (a+`CHARACTER_GLB` path, an attached/linked `.glb`, or an explicit mention of one):++- **A GLB reference exists** → proceed through Stage 0 onward, as described below.+- **No GLB reference** → **skip every stage in this document (Stage 0 through Stage 9) entirely.** Do+ not treat the absence as an error, a blocker, or something to substitute a placeholder for. Build the+ character through the core img2threejs image-driven procedural pipeline instead (`forge/`) — that path+ never depends on a GLB. This integration has no code path that runs without one; every stage below+ (the cross-section loft included) measures a real GLB point cloud, so there is nothing here to+ partially apply to an image-only build.++## Stage 0 — Intake++1. Symlink the baseline GLB(s) into `public/mesh/` and `public/baseline/` (both gitignored — they are+ measurement instruments, never shipped). A missing symlink resolves to `index.html` under Vite and+ masquerades as a 200 response with the wrong content; check the magic bytes of anything you load, not+ just the HTTP status.+2. Parse the GLB in JavaScript (see `node/encode_surfaces.mjs`'s `cloudMinima`) or Python+ (`python/build_head_surface.py`'s accessor walk) — whichever the rest of that stage's tooling uses.+ Do **not** assume `numpy` is installed; check first (`python3 -c "import numpy"`), and if it is not,+ write the JS equivalent rather than blocking the whole pipeline on one dependency.+3. Record per-node: vertex/triangle count, whether `NORMAL` is present (needed for oriented SDF splatting),+ whether the primitive is single-material/single-connected-component (needed later if you ever want to+ separate sub-features like eye/lash cards — see Stage 6's negative result).+4. Capture a reference photo if one exists and register it as `referenceImage` in the demo entry — it is+ what a human compares the result against, and it is not part of the reconstruction pipeline itself.++## Stage 1 — Cross-section loft (the code-only floor)++Build the coarse body from **measured cross-sections** of each node's own point cloud: cluster the cloud,+slice by height, take the radial concave outline per band, resample onto fixed spokes, loft between bands.+This is real code, fully parametric, and must always work with **zero external data** — it is the fallback+path (`?sdf=0` in this demo) and the thing that proves the pipeline is not secretly shipping the source+mesh.++Key parameters, tuned by measurement, not assumption:+- **spokes per node** = `min(convergence, density)`, where convergence is where the radial outline stops+ changing and density is the most spokes that keep a monotone outline — both measured per node, not+ shared globally.+- **centripetal (α=0.5) Catmull-Rom**, not uniform: uniform overshoot was measured at 31 mm on this model;+ centripetal cut it to 6 mm. Do not clamp the curve to the control polygon — that removes the exact+ bowing that turns a polygon into a circle.+- **adaptive subdivision** to a target edge length matched to the baseline's own measured median edge, not+ a fixed triangle budget.++This stage alone will not match the baseline closely on organic detail (a face, a navel) — a cross-section+is fundamentally 2.5D (one radius per angular bin), and no amount of spoke density recovers a fold that+doubles back on itself (an eyelid, a nostril). That is what Stage 2 is for.++**Read this before treating Stage 2/3 as "more of the same" measurement-to-parameter process this stage+is.** Stage 1 measures the GLB down to a SPARSE set of ring samples per node (girl-character: 748 rings,+86,240 points total, from a 2.1-million-vertex source) plus a handful of tuning numbers (spoke counts,+control-curve behaviour, a target edge length). At runtime a loft function SYNTHESISES the walls between+consecutive rings by interpolation -- that geometry does not exist in the measurement at all. Stage 2/3+does the opposite: it measures DENSELY (every sign-changing voxel cell, millions of vertices) and+re-encodes that whole capture (compressed, but still the whole thing) as embedded code, with no+interpolation at decode time -- what comes back out is the measured surface itself, not a synthesis+between sparse samples of it. Both are "code-only, no runtime fetch," and both embed genuinely measured+data as committed TypeScript; they differ in how much of the surface that data is and whether runtime+code synthesises between it or merely decodes it. Stage 2/3 is reached for only where Stage 1's 2.5D+loft-and-interpolate cannot express the geometry at all (a fold that doubles back on itself).++## Stage 2 — Implicit surface reconstruction (Surface Nets)++For nodes where the loft is not enough, splat a signed distance field from that node's own point cloud+using its own `NORMAL` attribute (oriented reconstruction — unoriented has to guess inside from outside)+and contour it with **Surface Nets**, not marching cubes: Surface Nets is a few dozen lines and one vertex+per sign-changing cell, marching cubes is a 256-case table that is easy to get subtly wrong with only+stdlib available.++- `python/build_head_surface.py <node> <cell>` — the field + Surface Nets for one node.+- `python/export_sdf_surfaces.py <node...> [xN]` — batches the above across every node that needs it,+ bakes per-vertex colour from the diffuse texture (mean of 4 nearest source vertices, **sRGB decoded to+ linear** — three.js treats a vertex colour attribute as already being in the working space), and writes+ a versioned binary (`HEDS`, magic-checked, not just HTTP-status-checked) as the intermediate artifact.+- Cell size per node, not a global constant: a lid margin is ~1 mm, so the head needs ~1.5 mm; the+ trousers carry nothing that fine and cost twice the file for no measured gain at anything below 2.5 mm.+ Measure the noise-vs-cell curve before picking one.++**This intermediate binary is not the deliverable.** It is 107.6 MB for this model, larger than the GLB it+is measured against — the point of Stage 2 is fidelity, and Stage 3 is what makes that fidelity shippable+as code.++## Stage 3 — Compact TypeScript encoding (no binary asset ships)++The insight that makes this stage possible: **Surface Nets places exactly one vertex per sign-changing+voxel cell.** A vertex's cell coordinate identifies it, so the index buffer is derivable from cell+adjacency and does not need to be stored — that was 50.6 MB of 107.6 on this model. Normals are similarly+derivable by recomputing them from the rebuilt triangles (another 25 MB). **Verify this claim on the real+data before encoding anything**, on every node, not just the ones that look regular:+- recover the grid origin from the builder's own rule (`lo = point-cloud min − 5×cell`, read from the GLB+ accessor minima) — it is not safely *searchable* by sweeping a sub-cell phase; that put 29% of vertices+ in an already-occupied cell in this project.+- require vertex → cell to be a bijection (watch for exact-boundary float ties; resolve by searching the+ 27-cell neighbourhood for one that still contains the point, with a tolerance scaled to the actual+ float32 precision at that coordinate magnitude — not an arbitrary epsilon).+- rebuild every triangle from cell adjacency alone and diff the triangle **sets** (not just counts) against+ the source. `node/verify_cells.mjs <bin> [glb]` does this and must show 0 collisions and every quad+ rebuilt before you write a single byte of encoder.++What actually gets written, per node (`node/encode_surfaces.mjs <level...>`):+- the active cell list as **varint deltas of the linear index** (zigzag, signed — the source order must be+ *preserved*, not re-sorted, or every later index-based comparison becomes meaningless; sorting to fix an+ apparent non-monotonicity is what silently reordered 1,193 vertices on one run of this project)+- the in-cell offset, 8 bits/axis+- colour, 8 bits/channel+- **4 bits per axis of connectivity** — exists / reversed / which corner the quad's diagonal split starts+ from. Two bits (exists + reversed) is *not enough*: a quad is split into two triangles from its first+ corner, and a rotation of the same four corners cuts the *other* diagonal. On non-planar Surface Nets+ quads (most of them) that is a real, different surface — it rendered as rows of diamond-shaped facets+ across a third of one region before the extra 2 bits were added.+- an explicit exception list for the handful of quads (~0.001% on this model) the reduction cannot+ express, so the rebuild is bit-exact rather than approximately right.++Result on this model: **9.0–9.1 bytes/vertex**, ~20–24% of the binary's size, base64-embedded in a+generated `.ts` module (`node/emit_surface_module.mjs <level> [dest.ts]`) — base64 because the same+data as a plain number array is roughly 10× larger as source text, and every browser has `atob` built in.++**Verify the round trip against the real decoder, not a second implementation of it** — transpile the+actual shipping `surfaceCodec.ts` with esbuild and run it inside the check script+(`node/verify_roundtrip.mjs <level>`), so what is tested is what ships. Compare, per node: vertex count,+worst-case position error against the *quantisation step* the encoding is actually allowed (not an+arbitrary round number — a tolerance the same size as the error it is meant to tolerate measures nothing),+colour delta, and the triangle set by **index**, only after confirming vertex order is preserved (measure+that too — don't assume it).++Ship **multiple detail levels as separate committed modules** (this project ships three:+`surfaceData[.ts|Low.ts|Medium.ts]`), selected in code, not fetched — a detail selector is a UI choice+between modules that are all already in the bundle, never a network request.++## Stage 4 — Runtime decoder++A single decode function (`surfaceCodec.ts`) that:+- walks one shared byte cursor across every node in the stream and **asserts it lands exactly on the+ declared length of each section**, not just the total stream length at the end — a per-node assertion+ catches drift at the node where it happened; a total-length check only tells you *something* drifted,+ after every later node already decoded from the wrong offset.+- range-checks a neighbour cell coordinate *before* packing it into a linear index — a negative offset+ does not go out of range, it silently wraps into a different valid cell.+- recomputes normals from the rebuilt index buffer (never stored).++## Stage 5 — Procedural rig++Build a skeleton and skin weights from the model's own measured proportions, not from a rig baked into the+GLB (there usually isn't one).+- **Capsule-radius weighting** per bone, with a **region → bone whitelist** (a glove only takes arm-chain+ bones, a boot only takes leg-chain bones) and a **trunk-exclusion shield** with smooth attenuation —+ plain distance-to-bone-segment weighting reads the body inside out (a shoulder joint dominating the+ torso's own weights) and drags the wrong body part when an adjacent limb moves.+- Derive the skeleton's spine axis from the **legs**, not the whole model's bounding box — the bbox average+ includes both arms and can put the spine several centimetres off-centre, silently, with no error to+ catch it except a measured band-by-band lateral-influence check.+- 4 bone influences, inverse-linear falloff, **no hard 0→100% steps** at a region boundary — that is what+ tears an arm off at the shoulder during animation.+- Gait curves as a **Fourier series**, not `Math.max(0, sin(...))` — the latter is C¹-discontinuous and+ produces a visible kink at the joint; square the clamped sine, or use a proper series, if you need a+ one-sided pulse.+- **Verify direction with forward kinematics before trusting how it looks**: proportion of the cycle spent+ moving forward vs. backward is a number, and "looks about right" is not.+- Rigid attachments (buckles, studs, fasteners) bind to the **nearest host *surface vertex's* bone**, not+ the nearest bone by raw distance — nearest-bone tore studs off a knee pad whose skin was 97% weighted to+ the hip.++## Stage 6 — Facial features (the hardest, least-resolved stage)++Everything below is real experience from ~20 iterations on eyes specifically. Read it as a decision tree,+not a recipe, because the terrain depends entirely on what the source GLB actually put at that node.++**First, measure what the source socket actually is**, by ray-casting along the face-normal axis from+outside in: is it a shallow bowl, a deep cavity, closed, torn? On this model it was a 20–36 mm deep bowl+with the eye *painted* into the diffuse (flat grey discs) and the lash/eye geometry drawn as thin cards+inside the head mesh. **A distance field splatted from a thin card has no interior, so it always contours+into a torn shell — that is not a bug in Stage 2, it is what an SDF does to a sheet, and it cannot be fixed+downstream.** Confirm before spending time on it: check whether the eye/lash geometry is its own+primitive/material/connected-component (it will not be, on most consumer GLBs) and whether its triangles+are statistically distinguishable from skin by shape (on this model they were not — p50 triangle quality+0.815 at the socket vs. 0.805 on a cheek control patch; a distance field makes uniform triangles everywhere+it runs, including on a torn shell). If both come back negative, **the socket cannot be repaired from+outside the SDF build** — the fix is rebuilding that node's field at a finer cell or with the lash+primitives excluded before splatting, nothing else works, and every attempt below that skips this check+will eventually be reverted.++Approaches tried, cheapest lesson first:+1. **A ball in the socket.** Fails structurally: an eye socket on this kind of asset is a broad shallow+ bowl, not a lid-shaped cavity, so any ball radius either stands proud of the face or shrinks the iris+ below a legible size. Don't start here.+2. **Sculpting a lid by pulling socket vertices onto a shell concentric with the ball.** Tore the face into+ flaps — "near the eye" is most of the eye region on a bowl this size, and a plain proximity sculpt moves+ far more geometry than a lid actually is.+3. **A dome that caps the whole bowl, sized to cover the tearing, with the opening painted into its+ texture.** This is the most promising shape and the one that surfaces every remaining subtlety:+ - the dome's rim depth has to be a **robust fit** (harmonics through a ring of casts, clamped against+ a high-percentile anchor) — the raw casts hit torn cards as often as skin, and a plain average sinks+ the whole dome below the face.+ - the join between dome and socket has a **sign problem, not a precision problem**: fit error puts the+ rim behind the real skin about half the time, and *that* half shows as a dark line all the way round+ the eye. Three rebuilds were spent trying to make the error *zero* (welding to the exact boundary+ loop, ordering it by angle, reading depth per sector) and each traded the gap for a different visible+ defect (a starburst, a ring of saw-teeth, stippled cheeks). What actually worked was making the error+ **one-sided**: lift the rim slightly proud of the fitted depth, so the dome always laps *over* real+ skin and never sinks under it. Two constants, not a fourth geometry rebuild.+ - covering the socket by literally cutting a hole in the head and capping it **always leaves a line of+ sight** between the cap's edge and the hole's edge at a grazing angle, however tight the fit — a cap+ over a hole in a closed surface is unavoidably a hole. Leaving the head's own geometry intact and+ only removing triangles that would visibly *poke through* the dome (compared against the dome's own+ rendered surface, not a second, independently-fitted approximation of it — the latter has a blind+ spot exactly where a shard is dense enough to define its own "surface") removes this failure mode by+ construction.+ - the dome's edge needs to disappear into the face in **three separate channels**, and each is a+ distinct bug class: **colour** (read the real vertex colour at each rim point directly rather than+ approximating it as one face-wide average — an averaged patch is right at one point on the face and+ visibly wrong everywhere else on it); **shading** (blend the rim's normals toward the face's own+ normals at the same point, or the seam is a lighting discontinuity no matter how well the colour+ matches); **material** (a cornea's wet clearcoat has to stay off the skin band via a roughness/+ clearcoat mask, or the blended surround reads as wet plastic).+ - **describing the same boundary shape twice, in two different parametrisations, is the single most+ repeated bug in this whole stage.** Painting the iris opening as a hand-fitted ellipse while the lid+ shape is drawn as cubic Bézier curves guarantees the two disagree somewhere — a bright sliver where+ the ellipse runs wider, a dark band cutting the iris where it runs narrower. Read the boundary back+ out of the canvas the shape was actually drawn on (rasterise, sample the alpha) rather than writing a+ second geometric description of it.+ - texture UV and the dome's own footprint radius are coupled by default (`u,v` as a function of the+ same `(radius, angle)` the geometry uses) — **decoupling one without the other stretches or distorts+ the painted iris.** If you change how far the dome reaches in a given direction, either the texture+ frame has to reach exactly as far, or the mapping needs its own fixed reference span independent of+ the geometry's.+4. **An ellipse that is only the eye, with no surrounding face geometry at all** — the approach actually+ shipped in this project, on the client's explicit direction after (3) kept needing another blend fix.+ This sidesteps every edge-blending problem in (3) because **there is no edge to blend** — the face+ around the eye is simply the face, untouched. The tradeoff is explicit and cannot be avoided by more+ engineering: with no cover, the source's torn socket geometry is visible around the small eye lens; with+ a cover big enough to hide it, you are back in (3) and its edge problems. **State this tradeoff to+ whoever is directing the work rather than re-solving it silently** — it is a real choice, not a bug.+ - Even the "just an ellipse" version is not immune to earlier lessons: it must be a clean **analytic**+ cap (e.g. `depth = -set + cap × (1 − t²)`), not one that still samples the measured, torn socket+ surface — sampling copies the tearing straight into the lens and produces an off-centre iris in an+ irregular blob.+ - Iris/pupil size is specified in millimetres and converted through the mesh's own half-spans; when the+ mesh shrinks, **re-derive the iris size from that conversion**, don't assume it still fits.++## Stage 7 — Detail-level strategy++Don't ship a triangle budget you haven't measured the cost of. For each candidate level, capture the same+six camera views and score (see Stage 8) against the *full* level, not just against the baseline — that+tells you what coarsening actually costs, separately from what reconstruction already costs. On this+project the jump from full to a 4×-coarser level cost 0.02 IoU and was worth shipping at a quarter of the+file size and build time; going further started visibly softening the face specifically, so the head node+was exempted from the global coarsening factor while the body kept it.++## Stage 8 — Verification harness++The single highest-leverage habit in this whole project: **when a fix looks done, hide the thing you just+added and re-render the same shot.** More defects were correctly diagnosed by "render with the new mesh+hidden and see if the problem is still there" than by any other technique — it is what separated "this is+geometry I introduced" from "this is damage already in the source," and got the fix effort pointed at the+right layer more than once after it had been pointed at the wrong one.++Metrics that mattered, computed the same way on both sides being compared:+- **IoU** of the two silhouettes (everything not the declared background colour, with a tolerance wide+ enough to keep the figure's own near-black rim without picking up compression noise).+- **colour error**: mean absolute RGB difference inside the *intersection* of the two silhouettes.+- **surface noise**: mean |Laplacian| of luma inside the silhouette — a roughness reading, not an error;+ the baseline has its own non-zero value, and the question is whether the reconstruction sits near it,+ not whether it is small. A noise value *below* the baseline's is evidence of smoothing, not fidelity.+- Comparing two builds directly (encoded-in-code vs. the intermediate binary it replaced) isolates the+ *encoding's* error from the *reconstruction's* error — do this before also comparing either one against+ the original baseline, or a real distortion becomes impossible to attribute to the right stage.+- If the numpy-based comparator isn't available in the working environment, **write the arithmetic to run+ inside a headless browser** (`node/compare_views.mjs`) rather than skipping the measurement — a PNG+ decodes to pixels there with no dependency at all.+- **A tolerance the same size as the error it's meant to tolerate measures nothing.** A position check+ that quantised to 10 µm against an encoding allowed 9.8 µm of error reported 99.94% of triangles wrong+ when the actual defect rate was near zero, in the opposite direction from a separate bug that really was+ present. Derive the tolerance from the encoding's own stated precision, not a round number.+- **Counting is not comparing.** A check that only compares triangle *counts* will pass a mesh where every+ triangle joins the wrong three vertices. Compare the actual index/position sets.++## Stage 9 — Build & regression checklist++Before calling a pass done:+- [ ] `npx tsc --noEmit` exits 0+- [ ] `npm run build` (`tsc --noEmit && vite build`) succeeds; note bundle size and gzip size if the change+ touched an embedded data module — that number is the actual cost users pay+- [ ] the demo renders with every asset directory it *shouldn't* need moved out of the way+ (`public/head`, `public/mesh`, `public/baseline`) — this is the literal proof nothing is fetched+- [ ] mesh/triangle/region counts read off the live scene match what the encoder reported, within ~1%+- [ ] `node/compare_views.mjs <newBuild> <previousBuild>` shows the change you intended and nothing else+- [ ] `work/progress.txt` gets an entry: what changed, what was measured, what negative results were found+ (a reverted attempt is only worth what it teaches the next person — write it down even when it fails)++---++## Appendix A — Anti-pattern catalog (grep-able, one line each)++- **A relative import breaks the moment the importing file moves.** Packaging+ `verify_roundtrip.mjs` one directory deeper broke its `../work/codec/...` dynamic import --+ `outfile` and the dynamic `import()` must agree on an ABSOLUTE path (resolved against+ `process.cwd()`, since the orchestrator always `cd`s to the repo root first), not a path relative to+ the script's own location. Caught by actually running the packaged copy, not by reading it.+- **A swapped filename mapping writes valid, wrong data with no error at all.** Packaging this pipeline's+ own orchestrator, `x2` and `x3` got assigned to the wrong destination file ("Low" vs. "Medium") --+ every check (tsc, the round-trip verifier, `npm run build`) passed, because the file was still+ perfectly valid TypeScript carrying a perfectly valid, just mislabelled, level. Only `git diff` on the+ file the script had just written caught it. The orchestrator now runs that same `git diff` check on+ every file it writes and prints a warning if a tracked file changed -- add the equivalent check to any+ script that overwrites a file that might already be finished and committed.+- **Trusting an HTTP status without checking content.** A dev server serves `index.html` for a missing+ file with a 200; check the magic bytes / parse result, not just `res.ok`.+- **Sweeping for a grid phase instead of deriving it from the builder's own rule.** A search-based origin+ put 29% of vertices in the wrong cell; the builder's formula got 100% right.+- **A tolerance sized around convenience, not around the error it's meant to catch.** Quantify the actual+ precision the upstream step promises, then set the check a notch tighter than that — not looser.+- **Comparing counts instead of contents.** Same triangle count, same vertex count, wrong mesh.+- **Describing one boundary shape twice in two coordinate systems.** They will disagree somewhere; sample+ the one that was actually drawn instead of re-deriving the other.+- **Coupling a UV parametrisation to a geometry parameter you're about to change.** Decide which one is+ allowed to move before touching either.+- **Trying to make a fitted error exactly zero.** Three rebuilds chasing zero error on a socket rim; two+ constants making the error one-sided (always proud, never sunk) fixed the actual complaint.+- **Cutting a hole and capping it.** Always leaves a sightline at the cap's own edge at some angle; prefer+ "remove only what pokes through," leaving the surface intact everywhere else.+- **A single global average standing in for a gradient.** Skin colour, socket depth, subdivision density —+ whichever one is being averaged, measure it locally instead once the average visibly fails at any point.+- **Assuming a moved/resized mesh keeps its old proportions.** Anything specified in absolute units+ (millimetres) through a converted local frame has to be re-checked against the frame every time the+ frame's size changes.+- **Declaring victory from the intended camera angle only.** The grazing angle, the angle from below, and+ the angle the actual reporter used are where a construction seam shows up; render all of them.+- **Not re-rendering with the new geometry hidden.** The fastest way to learn whether a defect is "mine" or+ "already in the source" and to stop fixing the wrong layer.++## Appendix B — File map (this project's instance)++| Stage | Script/module | Produces |+|---|---|---|+| 1 | `python/slice_node.py`, `python/measure_density_convergence.py`, `python/build_cross_sections.py`, `src/demos/girl-character/crossSections.ts` | measured ring data, loft geometry |+| 1 (gated) | `python/bake_atlas_uvs.py` (`CHARACTER_ALLOW_BASELINE_UV=1` only) | baseline-transferred UVs -- authorised one-off deviation, not the default path |+| 2 | `python/build_head_surface.py`, `python/export_sdf_surfaces.py` | per-node SDF + Surface Nets → `HEDS` binary (dev-only intermediate) |+| 3 | `node/encode_surfaces.mjs`, `node/emit_surface_module.mjs` | `src/demos/girl-character/surfaceData[.ts\|Low.ts\|Medium.ts]` |+| 4 | `src/demos/girl-character/surfaceCodec.ts` | runtime decode → `THREE.BufferGeometry` |+| 5 | `src/demos/girl-character/walkRig.ts`, `hardware.ts`, `measuredAnchors.ts` | skeleton, skin weights, gait, attachments |+| 6 | `createGirlCharacterModel.ts` (eye functions) | eye lens mesh + texture |+| 8 | `node/verify_cells.mjs`, `node/verify_roundtrip.mjs`, `node/compare_views.mjs`, `node/capture-character.mjs` | correctness + fidelity evidence |++## Appendix C — Open item on this character++The eye sockets still show the source's own torn card geometry around the lens (Stage 6, approach 4's+stated tradeoff). It is not fixable from any of the downstream stages — confirmed by measurement, not+assumption (single primitive, single material, single connected component; triangle shape statistically+identical to skin). Closing it requires going back to Stage 2 and either rebuilding node 9 at a finer cell+or excluding the GLB's lash/eye card primitives before splatting. Budget that as its own pass, not a+touch-up on top of Stage 6.diff --git a/integrations/glb_character_pipeline/README.md b/integrations/glb_character_pipeline/README.mdnew file mode 100644index 0000000..2952098--- /dev/null+++ b/integrations/glb_character_pipeline/README.md@@ -0,0 +1,105 @@+# GLB character pipeline (opt-in)++**GLB reference is optional. If the character build has none, skip this integration entirely** — do+not error, do not partially apply it, do not substitute anything. Build through the core img2threejs+image-driven pipeline (`forge/`) instead; nothing here has a code path that runs without a real GLB+point cloud to measure. Only reach for anything below once you've confirmed a GLB reference actually+exists for this character (see `PIPELINE.md`'s "Applicability gate").++This integration reconstructs a **multipart GLB baseline** as code-only TypeScript/three.js — a fully+procedural character with no `.glb`/`.bin` fetched at runtime — using an SDF point-cloud splat and+Surface Nets contouring for organic detail a cross-section loft alone can't reach (eyelids, folds,+navels). It exists as an opt-in integration, not core `forge/`, because it needs `numpy` and `Pillow`+for the splat/bake step and `playwright`/`esbuild` for the Node-side capture and round-trip verification+— dependencies the stdlib-only `forge` core deliberately does not carry. `CONTRIBUTING.md` allows this+explicitly: "If you want a projection or generative-assist path, propose it as an explicit, flagged,+opt-in mode."++This is a **companion-showcase** tool: every script here operates against a separate+`img2threejs-showcase` checkout (where the demo's own `src/demos/<character>/`, `public/mesh/`, and+`work/` directories live), never against this repo's own tree. Point `IMG2THREEJS_SHOWCASE_ROOT` at+that checkout before running anything below — the same env var `forge/tests` already uses to reach a+companion showcase for its TypeScript typecheck gates.++**The GLB is a measurement instrument, never a shipped asset — but "code-only" covers two genuinely+different things here, and they should not be read as the same claim.** Both stages embed measured+data as committed `.ts` code (no runtime fetch either way); they differ in HOW MUCH of the measured+surface that data actually is, and what runtime code does with it:+- **Stage 1 (cross-section loft)** measures a SPARSE set of ring samples per node (girl-character: 748+ rings, 86,240 points total, from a 2.1-million-vertex source) and a small set of tuning numbers+ (per-node spoke count, Catmull-Rom control behaviour, target edge length). At runtime, a loft+ function SYNTHESISES new geometry by interpolating *between* those measured rings — the walls+ between ring i and ring i+1 do not exist in the measurement at all; they are generated.+- **Stage 2/3 (SDF splat + Surface Nets + compact encoding)** measures DENSELY — every sign-changing+ voxel cell, millions of vertices — and re-encodes that (varint deltas + connectivity bits,+ ~8 bytes/vertex) as base64 inside a committed `.ts` module. At runtime there is no interpolation or+ synthesis: decoding reproduces the measured surface itself, essentially unchanged. It exists only+ because a cross-section loft is fundamentally 2.5D and cannot express detail that folds back on+ itself (an eyelid, a nostril, a navel) — see `PIPELINE.md` Stage 1's closing note and Stage 2's+ opening.++Read `PIPELINE.md` end to end before running this on a new character — it is the full, stage-by-stage+methodology (intake, cross-section loft, Surface Nets, compact encoding, verification, the eye-socket+lesson in Stage 6), distilled from actually building `girl-character`. This README only covers install+and the day-to-day commands.++## Install++```bash+uv sync --project integrations/glb_character_pipeline --python 3.11+cd integrations/glb_character_pipeline/node && npm install && npx playwright install chromium+```++## Use++```bash+export IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase+export IMG2THREEJS_GLB_PIPELINE_PYTHON="uv run --project integrations/glb_character_pipeline python3"++# reproduce girl-character's own shipped build, byte-for-byte+integrations/glb_character_pipeline/build-character.sh \+ --config integrations/glb_character_pipeline/configs/girl-character.env++# bring up a new character: copy configs/example.env, fill in every value, then run the same way+integrations/glb_character_pipeline/build-character.sh --config path/to/your-character.env+```++`--skip-splat` reuses whatever `.bin` intermediate already exists on disk (skip Stage 2); `--skip-build`+stops before Stage 9's `tsc`/`vite build` and screenshot capture, useful while iterating on Stage 3+alone. See `PIPELINE.md`'s Appendix A for anti-patterns worth avoiding on a first read, and Appendix B+for the full stage → script → output file map.++## What's here++- `python/slice_node.py`, `python/measure_density_convergence.py`, `python/build_cross_sections.py` —+ Stage 1: cross-section loft, the code-only floor. `measure_density_convergence.py` only prints+ tables — deciding the final per-node spoke count is a human/agent judgment call, not something it+ resolves for you (see `PIPELINE.md` Stage 1). Optional per build: leave `CHARACTER_SECTION_REGIONS_JSON`+ / `CHARACTER_SPOKES_JSON` / `CHARACTER_CROSS_SECTIONS` unset to skip and keep an existing file as-is.+- `python/bake_atlas_uvs.py` — an explicitly-gated (`CHARACTER_ALLOW_BASELINE_UV=1`) escape hatch that+ transfers a baseline GLB's own texture UVs onto the cross-sections. This departs from img2threejs's+ normal no-baseline-assets rule (it was a one-off, authorised exception for girl-character) — read its+ own docstring in full before ever setting that env var for a new character.+- `python/build_head_surface.py`, `python/export_sdf_surfaces.py` — Stage 2: SDF splat + Surface Nets,+ per node, batched across a character's node list.+- `node/verify_cells.mjs` — Stage 3 pre-check: rebuild every triangle from cell adjacency alone and diff+ against the source; must show 0 collisions before any encoder byte is written.+- `node/encode_surfaces.mjs`, `node/emit_surface_module.mjs` — Stage 3: compact varint + connectivity+ encoding, base64-embedded into a committed `.ts` module (no runtime fetch).+- `node/verify_roundtrip.mjs` — Stage 3 verify: round-trip every emitted level against the binary it+ replaces.+- `node/capture-character.mjs`, `node/compare_views.mjs` — Stage 9: headless-browser renders with the+ binary intermediate moved out of the way (proof nothing was fetched), and pixel-diff against a prior+ capture.+- `build-character.sh` — the generic orchestrator chaining all of the above; every path and node list+ comes from a `--config` `.env` file (`configs/example.env`, `configs/girl-character.env`), never+ hardcoded in the script.++## Environment++- Python: `integrations/glb_character_pipeline/.venv/` (via `uv sync`).+- Node: `integrations/glb_character_pipeline/node/node_modules/` (via `npm install`).++See `docs/integrations/reference_fidelity_tooling.md` for how this fits alongside the other+diagnostic/reference tooling, and `grimoire/build/python_threejs_render_bridge.md` for the GLB-mediated+capture bridge contract this integration's capture step relies on.diff --git a/integrations/glb_character_pipeline/build-character.sh b/integrations/glb_character_pipeline/build-character.shnew file mode 100755index 0000000..fc4a8df--- /dev/null+++ b/integrations/glb_character_pipeline/build-character.sh@@ -0,0 +1,193 @@+#!/usr/bin/env bash+# GLB Character Pipeline (img2threejs integration) — generic orchestrator.+#+# Ported from the img2threejs-showcase repo's character-pipeline v1.5.1: chains Stage 0 (intake+# check) -> Stage 2 (re-splat, Python/numpy) -> Stage 3 (encode + emit TypeScript, per level, with+# round-trip verification) -> Stage 9 (build + no-fetch regression), as described in PIPELINE.md.+# Every path and node list comes from a --config .env file, not from anything hardcoded here.+#+# This is an OPT-IN integration (see README.md): it depends on numpy, Pillow and Playwright, which+# the img2threejs stdlib-only core deliberately does not. It operates entirely inside a companion+# showcase checkout, never inside this repo's own tree -- point IMG2THREEJS_SHOWCASE_ROOT at that+# checkout before running this script.+#+# Written for macOS's stock /bin/bash (3.2): no associative arrays, no readarray.+#+# Usage:+# IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase \+# build-character.sh --config path/to/character.env [--skip-splat] [--skip-build]+#+# --skip-splat skip Stage 2 even if numpy is available (reuse whatever .bin already exists on disk)+# --skip-build skip Stage 9's tsc/vite build + capture (useful while iterating on Stage 3 alone)+set -euo pipefail++: "${IMG2THREEJS_SHOWCASE_ROOT:?set IMG2THREEJS_SHOWCASE_ROOT to a companion img2threejs-showcase checkout (see integrations/glb_character_pipeline/README.md)}"+PKG_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_ROOT="$(cd "$IMG2THREEJS_SHOWCASE_ROOT" && pwd)"+export IMG2THREEJS_SHOWCASE_ROOT="$REPO_ROOT"+cd "$REPO_ROOT"++CONFIG=""+SKIP_SPLAT=0+SKIP_BUILD=0+while [ $# -gt 0 ]; do+ case "$1" in+ --config) CONFIG="$2"; shift 2 ;;+ --skip-splat) SKIP_SPLAT=1; shift ;;+ --skip-build) SKIP_BUILD=1; shift ;;+ *) echo "unrecognised argument: $1" >&2; exit 1 ;;+ esac+done+if [ -z "$CONFIG" ]; then+ echo "usage: IMG2THREEJS_SHOWCASE_ROOT=... build-character.sh --config path/to/character.env [--skip-splat] [--skip-build]" >&2+ echo " see configs/example.env for a template, configs/girl-character.env for a filled-in one" >&2+ exit 1+fi+if [ ! -f "$CONFIG" ]; then+ echo "config not found: $CONFIG" >&2+ exit 1+fi+# shellcheck disable=SC1090+source "$CONFIG"++PY_SCRIPTS="$PKG_DIR/python"+NODE_SCRIPTS="$PKG_DIR/node"++# Override to e.g. `uv run --project integrations/glb_character_pipeline python3` (run from the+# img2threejs checkout) to use this integration's own isolated numpy/Pillow environment; falls back+# to plain python3, which works fine if numpy is already available in the ambient environment.+PY="${IMG2THREEJS_GLB_PIPELINE_PYTHON:-python3}"++: "${CHARACTER_GLB:?config must set CHARACTER_GLB}"+: "${CHARACTER_DEMO_ID:?config must set CHARACTER_DEMO_ID}"+: "${CHARACTER_NODES:?config must set CHARACTER_NODES}"+: "${CHARACTER_LEVELS:?config must set CHARACTER_LEVELS}"+export CHARACTER_GLB+export CHARACTER_DIFFUSE="${CHARACTER_DIFFUSE:-work/baseline-textures/01-texture_diffuse.png}"+export CHARACTER_OUT_PREFIX="${CHARACTER_OUT_PREFIX:-public/head/sdf-surfaces}"+export CHARACTER_WORKDIR="${CHARACTER_WORKDIR:-work/head}"+export CHARACTER_BIN_DIR="${CHARACTER_BIN_DIR:-public/head}"+export CHARACTER_WORK_TAG="${CHARACTER_WORK_TAG:-}"+export CHARACTER_CODEC="${CHARACTER_CODEC:-src/demos/girl-character/surfaceCodec.ts}"+export CHARACTER_CODEC_IMPORT="${CHARACTER_CODEC_IMPORT:-./surfaceCodec}"+export CHARACTER_REGIONS_JSON="${CHARACTER_REGIONS_JSON:-}"+export CHARACTER_CELL_SIZES_JSON="${CHARACTER_CELL_SIZES_JSON:-}"+export CHARACTER_SECTION_REGIONS_JSON="${CHARACTER_SECTION_REGIONS_JSON:-}"+export CHARACTER_SPOKES_JSON="${CHARACTER_SPOKES_JSON:-}"+export CHARACTER_CROSS_SECTIONS="${CHARACTER_CROSS_SECTIONS:-}"++echo "== Stage 0: baseline present and is actually a GLB? =="+if [ ! -e "$CHARACTER_GLB" ]; then+ echo " MISSING $CHARACTER_GLB (relative to $REPO_ROOT) -- symlink the baseline GLB there before continuing (PIPELINE.md Stage 0)." >&2+ exit 1+fi+magic="$(head -c 4 "$CHARACTER_GLB" 2>/dev/null || true)"+if [ "$magic" != "glTF" ]; then+ echo " $CHARACTER_GLB does not start with the glTF magic (got: '$magic')." >&2+ echo " A dev server serves index.html for a missing file with HTTP 200 -- if this path came from a" >&2+ echo " URL fetch rather than a local symlink, that is almost certainly what happened." >&2+ exit 1+fi+echo " ok: $CHARACTER_GLB"++echo+echo "== Stage 1: cross-section loft (Python, the code-only floor) =="+if [ -z "$CHARACTER_SPOKES_JSON" ] || [ -z "$CHARACTER_SECTION_REGIONS_JSON" ] || [ -z "$CHARACTER_CROSS_SECTIONS" ]; then+ echo " CHARACTER_SPOKES_JSON / CHARACTER_SECTION_REGIONS_JSON / CHARACTER_CROSS_SECTIONS not all set --"+ echo " skipping regeneration and leaving any existing crossSections.ts alone. See PIPELINE.md Stage 1"+ echo " and configs/example.env before setting these for a new character: the per-node spoke budget is"+ echo " a MEASURED, per-character decision (measure_density_convergence.py), not something to guess."+else+ "$PY" "$PY_SCRIPTS/build_cross_sections.py"+ if [ "${CHARACTER_ALLOW_BASELINE_UV:-}" = "1" ]; then+ if "$PY" -c "import numpy" 2>/dev/null; then+ echo " CHARACTER_ALLOW_BASELINE_UV=1 -- baking baseline UVs onto the cross-sections (authorised"+ echo " deviation from the no-baseline-assets rule; see bake_atlas_uvs.py's own docstring)."+ "$PY" "$PY_SCRIPTS/bake_atlas_uvs.py"+ else+ echo " CHARACTER_ALLOW_BASELINE_UV=1 but numpy is not installed for \$PY ($PY) -- skipping." >&2+ fi+ fi+fi++echo+echo "== Stage 2: re-splat implicit surfaces (Python + numpy) =="+if [ "$SKIP_SPLAT" -eq 1 ]; then+ echo " --skip-splat: reusing whatever ${CHARACTER_BIN_DIR}/sdf-surfaces*.bin already exists on disk."+elif "$PY" -c "import numpy" 2>/dev/null; then+ # shellcheck disable=SC2086+ "$PY" "$PY_SCRIPTS/export_sdf_surfaces.py" $CHARACTER_NODES+else+ echo " numpy not installed for \$PY ($PY) -- skipping Stage 2." >&2+ echo " Run 'uv sync --project integrations/glb_character_pipeline' from the img2threejs checkout" >&2+ echo " and set IMG2THREEJS_GLB_PIPELINE_PYTHON to that venv's python3 to re-splat node geometry;" >&2+ echo " Stage 3 below re-encodes whatever ${CHARACTER_BIN_DIR}/sdf-surfaces*.bin already exists on" >&2+ echo " disk, which is a no-op the first time a new character runs this without numpy available." >&2+fi++echo+echo "== Stage 3: encode + emit TypeScript modules, one per level =="+for level in $CHARACTER_LEVELS; do+ case "$level" in+ # x3 coarsens MORE than x2 (a bigger cell, so fewer vertices), so x3 defaults to "Low" and x2+ # to "Medium" -- checked against girl-character's own shipped files, not assumed.+ x2) dest="${CHARACTER_DEST_X2:-src/demos/$CHARACTER_DEMO_ID/surfaceDataMedium.ts}" ;;+ x3) dest="${CHARACTER_DEST_X3:-src/demos/$CHARACTER_DEMO_ID/surfaceDataLow.ts}" ;;+ *) dest="${CHARACTER_DEST_DEFAULT:-src/demos/$CHARACTER_DEMO_ID/surfaceData.ts}" ;;+ esac+ echo " -- level $level -> $dest"+ case "$level" in+ default|"") surface_bin="${CHARACTER_BIN_DIR}/sdf-surfaces.bin" ;;+ *) surface_bin="${CHARACTER_BIN_DIR}/sdf-surfaces-${level}.bin" ;;+ esac+ node "$NODE_SCRIPTS/verify_cells.mjs" "$surface_bin" "$CHARACTER_GLB"+ node --max-old-space-size=8192 "$NODE_SCRIPTS/encode_surfaces.mjs" "$level"+ node "$NODE_SCRIPTS/emit_surface_module.mjs" "$level" "$dest"+ # SAFETY NET, carried over from the showcase pipeline after this exact mistake happened once: a+ # swapped x2/x3 destination mapping wrote the wrong level's data into an already-shipped, committed+ # file with no error -- npm run build, tsc and the round-trip check all still passed, because the+ # file was still perfectly valid TypeScript carrying a perfectly valid (just wrong) level. Only+ # `git diff` caught it. Never rely on catching this by eye again.+ if git -C "$REPO_ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1 \+ && git -C "$REPO_ROOT" ls-files --error-unmatch "$dest" >/dev/null 2>&1 \+ && ! git -C "$REPO_ROOT" diff --quiet -- "$dest"; then+ echo " !! $dest CHANGED relative to the last commit. If this was already shipped, that is worth a"+ echo " second look before it gets committed -- run: git diff -- $dest"+ fi+done++echo+echo "== Stage 3 verify: round-trip every level against the binary it replaces =="+for level in $CHARACTER_LEVELS; do+ echo " -- level $level"+ node --max-old-space-size=8192 "$NODE_SCRIPTS/verify_roundtrip.mjs" "$level"+done++if [ "$SKIP_BUILD" -eq 1 ]; then+ echo+ echo "--skip-build: stopping before Stage 9."+ exit 0+fi++echo+echo "== Stage 9: build & regression =="+npx tsc --noEmit+npx vite build++echo+echo "== Stage 9: renders with $CHARACTER_BIN_DIR moved out of the way =="+tmp="$(mktemp -d)"+if [ -e "$CHARACTER_BIN_DIR" ]; then mv "$CHARACTER_BIN_DIR" "$tmp/bin_dir"; fi+node "$NODE_SCRIPTS/capture-character.mjs" \+ --base http://127.0.0.1:5200/img2threejs-showcase/ \+ --demo "$CHARACTER_DEMO_ID" \+ --out "work/cmp/pipeline-check${CHARACTER_WORK_TAG}"+if [ -e "$tmp/bin_dir" ]; then mv "$tmp/bin_dir" "$CHARACTER_BIN_DIR"; fi+rmdir "$tmp" 2>/dev/null || true+echo " wrote work/cmp/pipeline-check${CHARACTER_WORK_TAG}/*.png with $CHARACTER_BIN_DIR absent -- inspect"+echo " these by hand; their existence with that directory absent is the proof nothing was fetched."++echo+echo "Done. Compare against a prior capture with:"+echo " node $NODE_SCRIPTS/compare_views.mjs work/cmp/pipeline-check${CHARACTER_WORK_TAG} work/cmp/<previous>"+echo "Then record the run in \$IMG2THREEJS_SHOWCASE_ROOT/work/progress.txt, per PIPELINE.md Stage 9."diff --git a/integrations/glb_character_pipeline/configs/example.env b/integrations/glb_character_pipeline/configs/example.envnew file mode 100644index 0000000..4c11417--- /dev/null+++ b/integrations/glb_character_pipeline/configs/example.env@@ -0,0 +1,103 @@+# GLB Character Pipeline (img2threejs integration) — template for a NEW reference. Copy this file,+# fill in every value below, and run:+# IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase \+# integrations/glb_character_pipeline/build-character.sh --config path/to/your.env+#+# Read integrations/glb_character_pipeline/PIPELINE.md end to end BEFORE running this on a new+# character, especially Stage 6 (facial features) if the new reference has a face -- the eye-socket+# lesson there was expensive to learn once and applies to every future character that draws eyes as+# thin cards.++# --- Stage 0/2 inputs -------------------------------------------------------------------------------+# Path to the baseline GLB, relative to IMG2THREEJS_SHOWCASE_ROOT (never to this repo). Symlink it+# into public/mesh/ first (gitignored in the showcase repo -- it is a measurement instrument, never+# shipped) rather than pointing straight at wherever it lives on disk, so the pipeline's own+# path-existence checks and any future `git status` inside the showcase checkout stay meaningful.+CHARACTER_GLB="public/mesh/<your-character>-baseline.glb"++# --- Stage 1 inputs (cross-section loft -- optional; leave all three unset to skip regenerating it) --+# Leaving CHARACTER_SECTION_REGIONS_JSON / CHARACTER_SPOKES_JSON / CHARACTER_CROSS_SECTIONS unset skips+# Stage 1 entirely and leaves any existing crossSections.ts alone -- fine once it's already built and+# frozen. Set all three to (re)generate it for a new character.+#+# A JSON file mapping node index (as a string) -> a region label of your choosing, e.g.+# {"0": "TORSO", "9": "HEAD"}. Each distinct region becomes one `export const <REGION>_SECTIONS` block+# in the emitted file, so the label must be a valid TS identifier component. Not the same file as+# CHARACTER_REGIONS_JSON below -- that one feeds Stage 2's per-vertex material lookup and historically+# uses different casing/labels; keep them separate rather than reconciling two unrelated conventions.+CHARACTER_SECTION_REGIONS_JSON="${IMG2THREEJS_SHOWCASE_ROOT}/pipelines/character-pipeline/v1.5.1/configs/<your-character>-section-regions.json"++# A JSON file mapping node index (as a string) -> the FINAL spoke count for that node, e.g. {"0": 128}.+# This is a MEASURED, per-character decision, not a formula: run measure_density_convergence.py against+# each node first, read its printed convergence/density tables, and pick min(convergence, density),+# raised only where a material-patch boundary needs finer cutting. See PIPELINE.md Stage 1 for the two+# ways guessing this goes wrong (under-sampled outlines; over-sampled outlines bulging past the point+# cloud on nodes with sparse density).+CHARACTER_SPOKES_JSON="${IMG2THREEJS_SHOWCASE_ROOT}/pipelines/character-pipeline/v1.5.1/configs/<your-character>-spokes.json"++# Where Stage 1 writes the generated cross-sections module.+CHARACTER_CROSS_SECTIONS="src/demos/<your-character>/crossSections.ts"++# Override only if you re-measured slice convergence for this character and it genuinely differs from+# the 40 that was optimal for girl-character's proportions (see build_cross_sections.py's docstring).+# CHARACTER_SLICES="40"++# Leave unset. Setting this to "1" runs bake_atlas_uvs.py, which copies a baseline GLB's own texture UVs+# onto the generated cross-sections -- an authorised, one-off deviation from img2threejs's normal+# no-baseline-assets rule that girl-character's build used. Read bake_atlas_uvs.py's own docstring in+# full before ever setting this for a new character; the default (unset) path uses per-region procedural+# material colour instead, which needs no UV at all.+# CHARACTER_ALLOW_BASELINE_UV="1"++# Path to the extracted diffuse/albedo texture that Stage 2 samples for per-vertex colour. If you don't+# already have this as a standalone PNG, run scripts/extract_glb_images.py against CHARACTER_GLB first+# (that script is in the top-level scripts/ directory, not packaged here, since image extraction has+# nothing character-specific about it).+CHARACTER_DIFFUSE="work/<your-character>-textures/diffuse.png"++# Where Stage 2's binary lands, and where Stage 3 reads it back from. Keep these matched, and give a new+# character its own prefix/dir so a second character's build never overwrites the first's while both are+# checked out at once.+CHARACTER_OUT_PREFIX="public/head-<your-character>/sdf-surfaces"+CHARACTER_BIN_DIR="public/head-<your-character>"+CHARACTER_WORKDIR="work/head-<your-character>"++# A short, unique tag so Stage 3's intermediate work/surfaces* files don't collide with another+# character's. Leave it descriptive -- it becomes part of a filename, so keep it filesystem-safe.+CHARACTER_WORK_TAG="-<your-character>"++# The runtime decoder is CHARACTER-AGNOSTIC (it decodes whatever EncodedNode metadata it is handed), so+# almost every new character can point straight at the SAME file girl-character uses instead of writing+# a new one. Only change this if the new character needs a decoder feature that doesn't exist yet --+# and if so, consider adding that feature to the shared file rather than forking it.+# Write this file for your own demo first -- the integration does not ship a decoder,+# and pointing at another demo's copy round-trips against the wrong contract.+CHARACTER_CODEC="src/demos/<your-character>/surfaceCodec.ts"++# A JSON file mapping node index (as a string) -> region label, e.g. {"0": "torso", "9": "head"}. This+# drives per-region material lookups and detail-level exemptions (see PIPELINE.md Stage 2's note on why+# the head is exempt from body-wide coarsening) in your OWN demo code -- it does not need to match+# girl-character's region names, only your own createXCharacterModel.ts's expectations.+CHARACTER_REGIONS_JSON="${IMG2THREEJS_SHOWCASE_ROOT}/pipelines/character-pipeline/v1.5.1/configs/<your-character>-regions.json"++# --- Orchestration -----------------------------------------------------------------------------------+# The demo id this character is registered under in src/demos/registry.ts, and the scene root name+# createXCharacterModel.ts assigns via `root.name = ...` (capture-character.mjs's --root-name defaults+# to "<demo>-procedural" and only affects one optional diagnostic, so getting this wrong is not fatal).+CHARACTER_DEMO_ID="<your-character>"++# Space-separated GLB node indices that need Stage 2 (implicit-surface) reconstruction, in the order+# export_sdf_surfaces.py should process them. Nodes NOT listed here stay on the Stage 1 loft. Measure+# per-node noise before deciding a node needs this stage at all -- Stage 2 is expensive, and half this+# project's regions never needed it.+CHARACTER_NODES="0 1 2 3"++# Which detail levels to build. "default" is the full-fidelity level; "x2"/"x3" are coarser (see+# export_sdf_surfaces.py's scale argument). Measure the IoU cost of each coarser level against the full+# one (PIPELINE.md Stage 7) before deciding which to actually ship.+CHARACTER_LEVELS="x2 x3 default"+# x3 uses a BIGGER cell than x2, so x3 is the coarser tier. Getting these two the wrong way+# round writes valid, mislabelled data that tsc, the round-trip check and the build all pass.+CHARACTER_DEST_X2="src/demos/<your-character>/surfaceDataMedium.ts"+CHARACTER_DEST_X3="src/demos/<your-character>/surfaceDataLow.ts"+CHARACTER_DEST_DEFAULT="src/demos/<your-character>/surfaceData.ts"diff --git a/integrations/glb_character_pipeline/configs/girl-character-section-regions.json b/integrations/glb_character_pipeline/configs/girl-character-section-regions.jsonnew file mode 100644index 0000000..d2d4df2--- /dev/null+++ b/integrations/glb_character_pipeline/configs/girl-character-section-regions.json@@ -0,0 +1,18 @@+{+ "0": "OVERALLS",+ "1": "SKIN",+ "2": "BOOTS",+ "3": "SKIN",+ "4": "BOOTS",+ "5": "POUCHES",+ "6": "CANISTER",+ "7": "POUCHES",+ "8": "KATANA",+ "9": "HAIR",+ "10": "KNEE_PADS",+ "11": "BOOTS",+ "12": "KNEE_PADS",+ "13": "BOOTS",+ "14": "GLOVES",+ "15": "SKIN"+}diff --git a/integrations/glb_character_pipeline/configs/girl-character-spokes.json b/integrations/glb_character_pipeline/configs/girl-character-spokes.jsonnew file mode 100644index 0000000..0693162--- /dev/null+++ b/integrations/glb_character_pipeline/configs/girl-character-spokes.json@@ -0,0 +1,18 @@+{+ "0": 192,+ "1": 128,+ "2": 96,+ "3": 64,+ "4": 32,+ "5": 64,+ "6": 128,+ "7": 64,+ "8": 192,+ "9": 192,+ "10": 128,+ "11": 128,+ "12": 96,+ "13": 128,+ "14": 128,+ "15": 32+}diff --git a/integrations/glb_character_pipeline/configs/girl-character.env b/integrations/glb_character_pipeline/configs/girl-character.envnew file mode 100644index 0000000..132dca7--- /dev/null+++ b/integrations/glb_character_pipeline/configs/girl-character.env@@ -0,0 +1,45 @@+# GLB Character Pipeline (img2threejs integration) — config reproducing girl-character's own shipped+# build in the companion img2threejs-showcase repo.+#+# Every CHARACTER_* value here matches the DEFAULT already baked into the packaged scripts (that is not+# a coincidence: the defaults were taken FROM this character). All paths below are relative to+# IMG2THREEJS_SHOWCASE_ROOT, never to this repo. Running+# IMG2THREEJS_SHOWCASE_ROOT=/path/to/img2threejs-showcase \+# integrations/glb_character_pipeline/build-character.sh \+# --config integrations/glb_character_pipeline/configs/girl-character.env+# regenerates surfaceData.ts / surfaceDataLow.ts / surfaceDataMedium.ts inside that showcase checkout+# and should reproduce them byte-for-byte, since nothing about the reconstruction (Stage 2's cell+# sizes, the region map) changed -- only where the scripts read their configuration from did.++# Stage 1 (cross-section loft) is deliberately left unset here: girl-character's own crossSections.ts+# is already built and frozen ("DIMENSIONS ARE FROZEN" -- see build_cross_sections.py's docstring), so+# a routine build should not regenerate it. To reproduce it (proof-by-use, same idea as this file),+# run build-character.sh with these three added on top of this config:+# CHARACTER_SECTION_REGIONS_JSON=integrations/glb_character_pipeline/configs/girl-character-section-regions.json+# CHARACTER_SPOKES_JSON=integrations/glb_character_pipeline/configs/girl-character-spokes.json+# CHARACTER_CROSS_SECTIONS=work/verify-crossSections.ts # NOT src/demos/... -- don't overwrite the frozen file+# then diff the result against src/demos/girl-character/crossSections.ts by ring/region counts (the+# emitted file now always carries `uv: []`, which the original hand-shipped file predates, so an exact+# byte diff is expected to differ only in that one field per ring).++CHARACTER_GLB="public/mesh/girl-character-baseline.glb"+CHARACTER_DIFFUSE="work/baseline-textures/01-texture_diffuse.png"+CHARACTER_OUT_PREFIX="public/head/sdf-surfaces"+CHARACTER_WORKDIR="work/head"+CHARACTER_BIN_DIR="public/head"+CHARACTER_WORK_TAG=""+CHARACTER_CODEC="src/demos/girl-character/surfaceCodec.ts"+# Empty = use the script's built-in girl-character region map (Stage 2's NODE_REGION dict). A new+# character supplies its own via CHARACTER_REGIONS_JSON pointing at a {"node": "region"} JSON file.+CHARACTER_REGIONS_JSON=""++CHARACTER_DEMO_ID="girl-character"+CHARACTER_NODES="9 6 8 2 4 11 13 10 12 5 7 1 3 15 14 0"+CHARACTER_LEVELS="x2 x3 default"+# x3 coarsens MORE than x2 (bigger cell, fewer vertices), so x3 is "Low" and x2 is "Medium" --+# verified against the real, shipped files, not assumed. Swapping these two writes the wrong+# level's data under the other's filename with no error, since the .ts module's own shape doesn't+# encode which numeric level it is; only the header comment and vertex count reveal a mismatch.+CHARACTER_DEST_X2="src/demos/girl-character/surfaceDataMedium.ts"+CHARACTER_DEST_X3="src/demos/girl-character/surfaceDataLow.ts"+CHARACTER_DEST_DEFAULT="src/demos/girl-character/surfaceData.ts"diff --git a/integrations/glb_character_pipeline/node/.gitignore b/integrations/glb_character_pipeline/node/.gitignorenew file mode 100644index 0000000..c2658d7--- /dev/null+++ b/integrations/glb_character_pipeline/node/.gitignore@@ -0,0 +1 @@+node_modules/diff --git a/integrations/glb_character_pipeline/node/capture-character.mjs b/integrations/glb_character_pipeline/node/capture-character.mjsnew file mode 100644index 0000000..e391d56--- /dev/null+++ b/integrations/glb_character_pipeline/node/capture-character.mjs@@ -0,0 +1,281 @@+/**+ * Capture review views for a demo. PACKAGED (v1.5.1): generalised from capture-girl-character.mjs so a+ * new character's demo id, render profile and scene-root name are all flags rather than hardcoded.+ *+ * PORTABLE ON PURPOSE. The existing capture-awp-v2-review.cjs hardcodes another machine's+ * /Users/tamlh/... playwright and Chromium paths, so it cannot run anywhere but that laptop. This+ * resolves the browser from the environment instead: CloakBrowser first (the configured default for+ * browser automation here), then a locally installed playwright. If neither is present it says so and+ * exits non-zero rather than producing zero screenshots and a green log.+ *+ * Usage: node capture-character.mjs --demo <id> [--base URL] [--out DIR] [--profile FILE] [--root-name NAME]+ *+ * --profile defaults to work/render-profile.<demo>.json (the convention this project's own demos use).+ * --root-name defaults to <demo>-procedural (the convention createGirlCharacterModel.ts's root.name+ * follows) and is only used for an optional on-screen-bbox diagnostic -- getting it wrong skips that+ * diagnostic rather than failing the capture.+ */+import fs from 'node:fs';+import path from 'node:path';+import process from 'node:process';++const argv = process.argv.slice(2);+const arg = (name, fallback) => {+ const i = argv.indexOf(`--${name}`);+ return i >= 0 && argv[i + 1] ? argv[i + 1] : fallback;+};++const BASE = arg('base', 'http://127.0.0.1:5173/img2threejs-showcase/');+const DEMO = arg('demo', 'girl-character');+const ROOT_NAME = arg('root-name', `${DEMO}-procedural`);+/**+ * The background the render profile declares, measured off the reference (#0f0f0f). Capture mode+ * defaults to white because most demos' references are shot on white; this subject's is not, and a+ * render captured on the wrong background makes every foreground number a measurement of the+ * mismatch. Passed through to the viewer as ?bg=.+ */+const BG = arg('bg', '0f0f0f');+/** Read straight from the render profile so the capture cannot drift from the declared contract. */+const PROFILE = JSON.parse(fs.readFileSync(arg('profile', `work/render-profile.${DEMO}.json`), 'utf8'));+const PROFILE_CAMERA = {+ target: PROFILE.camera.target,+ radius: Math.hypot(+ PROFILE.camera.position[0] - PROFILE.camera.target[0],+ PROFILE.camera.position[2] - PROFILE.camera.target[2],+ ),+ fov: PROFILE.camera.fovDegrees,+};+const OUT = path.resolve(arg('out', path.join('.img2threejs', 'renders', 'pass-blockout')));++/** The six review angles. A single front view is not evidence about a 3D model. */+const VIEWS = [+ { id: 'front', azimuth: 0 },+ { id: 'orbit-plus-35', azimuth: 35 },+ { id: 'profile-left', azimuth: 90 },+ { id: 'rear', azimuth: 180 },+ { id: 'profile-right', azimuth: 270 },+ { id: 'orbit-minus-35', azimuth: -35 },+];++async function resolveBrowser() {+ try {+ const { launch } = await import('cloakbrowser');+ return { kind: 'cloakbrowser', launch: () => launch({ headless: true }) };+ } catch { /* fall through to playwright */ }+ try {+ const { chromium } = await import('playwright');+ return { kind: 'playwright', launch: () => chromium.launch({ headless: true }) };+ } catch { /* neither available */ }+ return null;+}++async function main() {+ const resolved = await resolveBrowser();+ if (!resolved) {+ console.error(+ 'FAILED: no browser driver found. Install one of:\n'+ + ' npm i -D playwright && npx playwright install chromium\n'+ + ' (or make cloakbrowser importable from this project)\n'+ + 'Refusing to report success with zero screenshots.',+ );+ process.exit(2);+ }+ console.log(`browser driver: ${resolved.kind}`);+ fs.mkdirSync(OUT, { recursive: true });++ const browser = await resolved.launch();+ const context = await browser.newContext({+ viewport: { width: 931, height: 2000 },+ deviceScaleFactor: 1,+ });+ const page = await context.newPage();+ const errors = [];+ page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });+ page.on('pageerror', (e) => errors.push(String(e)));++ const mask = argv.includes('--mask');+ // NO `capture=1`. Capture mode runs frameForCapture, which re-derives the camera from the scene+ // bounding box and KEEPS re-applying it: a profile-pinned camera set here was reverted within 250 ms+ // and produced a completely empty frame (0 non-background pixels vs 25,551 auto-framed). Worse, the+ // camera it chooses sits at y 0.875 — below the waist-rig mass at y 0.973 — so only that mass's+ // underside ever rendered, which is the "missing mass" chased across four iterations. The profile+ // camera has to win, or no per-pass number is comparable between passes.+ // MERGE with any query already on BASE instead of appending a second `?`. Passing+ // `--base '...?glb=shaded'` used to produce `...?glb=shaded?bg=000000`, where the whole tail is the+ // VALUE of `glb`, so the page silently loaded the default asset. Two captures then compared the+ // same file with itself and reported a 0.0/255 difference, which reads as "the two baselines are+ // identical" -- a conclusion about the assets drawn from a bug in the URL.+ const url = new URL(BASE, 'http://127.0.0.1');+ url.searchParams.set('bg', BG);+ if (mask) url.searchParams.set('mask', '1');+ url.hash = `#/demo/${DEMO}`;+ await page.goto(url.toString(), { waitUntil: 'networkidle' });+ await page.waitForSelector('canvas', { timeout: 120_000 });+ // The viewer sets this only after the first real frame; waiting on it rather than a fixed sleep is+ // what stops a blank canvas being captured and scored.+ // 120 s, not 30. Subdividing to 1.98 M triangles takes about 30 s of main-thread work, and a+ // capture that times out silently reuses the previous plate -- which is a stale image scored as if+ // it were the new one.+ await page.waitForFunction(() => window.__IMG2THREEJS_READY__ === true, { timeout: 120_000 });+ // The head arrives through `prewarm`, AFTER __IMG2THREEJS_READY__ fires. Capturing before it+ // attaches produced a plate with no head at all, and scored hair IoU as 0.000 rather than as a bug.+ await page.waitForFunction(() => {+ // Either path counts as ready: the implicit-surface build arrives through `prewarm` AFTER+ // __IMG2THREEJS_READY__ fires, while `?sdf=0` lofts everything synchronously and never sets+ // sdfSurface at all. Waiting only for sdfSurface hung the loft capture until it timed out.+ let sdf = false;+ let regions = 0;+ let meshes = 0;+ window.__IMG2THREEJS_VIEWER__?.scene?.traverse((o) => {+ if (o.userData?.sdfSurface) sdf = true;+ if (o.isMesh) meshes += 1;+ if (o.isMesh && o.userData?.region) regions += 1;+ });+ // THREE paths, not two. The GLB baseline demo carries no `region` tags and no sdfSurface at all --+ // it is the loaded asset -- so waiting on either of those hung it until the capture timed out and+ // it scored as if the comparison had been run.+ return sdf || regions >= 30 || meshes >= 8;+ }, { timeout: 120_000 });+ await page.evaluate(() => {+ document.querySelector('.demo-panel')?.setAttribute('style', 'display:none');+ document.querySelector('.hint')?.setAttribute('style', 'display:none');+ });++ const written = [];+ for (const view of VIEWS) {+ const placed = await page.evaluate(({ azimuthDeg, PROFILE_CAMERA, rootName }) => {+ const viewer = window.__IMG2THREEJS_VIEWER__;+ const camera = viewer?.camera;+ const controls = viewer?.controls;+ if (!camera) return { ok: false, reason: 'no camera on __IMG2THREEJS_VIEWER__' };+ // Pinned from the render profile, never inherited from the viewer's current framing. The AWP demo+ // recorded what inheriting costs: every geometry change reframed the shot and moved IoU ~0.039,+ // an order of magnitude above the per-pass signal being measured.+ const target = { x: PROFILE_CAMERA.target[0], y: PROFILE_CAMERA.target[1], z: PROFILE_CAMERA.target[2] };+ const radius = PROFILE_CAMERA.radius;+ camera.fov = PROFILE_CAMERA.fov;+ camera.updateProjectionMatrix();+ if (controls) controls.enabled = false;+ const theta = (azimuthDeg * Math.PI) / 180;+ camera.position.set(+ target.x + Math.sin(theta) * radius,+ target.y,+ target.z + Math.cos(theta) * radius,+ );+ camera.lookAt(target.x, target.y, target.z);+ camera.updateMatrixWorld(true);+ // SET THE CONTROLS' OWN TARGET BEFORE UPDATING THEM. `update()` re-derives the camera from+ // `controls.target`, which nothing here had ever synchronised with the profile, so the line+ // below used to throw away the camera placed just above and pull it back to the viewer's+ // default framing -- 43 px of vertical offset, measured.+ //+ // Disabling the controls does not prevent it, and the offset is invisible in the beauty plate+ // on its own. It only shows up against the semantic-ID pass, which sets this target and was+ // therefore 43 px away from the very pixels its masks were being used to measure: a pure+ // vertical shift of 43 px lifts the two passes' figure agreement from 0.8205 to 0.9941.+ //+ // Every per-region COLOUR number taken through those masks was reading the wrong pixels --+ // including the "lower body is 2-4x too bright" gap. Per-region IoU is unaffected, because it+ // compares two semantic-ID passes and both carried this same target.+ if (controls) {+ controls.target.set(target.x, target.y, target.z);+ controls.update();+ camera.updateMatrixWorld(true);+ }+ // `viewer.render` DOES NOT EXIST — optional chaining on it silently did nothing, so every frame+ // captured before this fix was whatever the render loop happened to draw, not the frame for the+ // camera just placed. Drive the real renderer directly and assert it is there, because a probe+ // that quietly no-ops is worse than one that fails.+ if (typeof viewer?.renderer?.render !== 'function') {+ return { ok: false, reason: 'viewer.renderer.render is not a function; cannot force a frame' };+ }+ viewer.renderer.render(viewer.scene, camera);++ // Record what the camera ACTUALLY is, plus where the model lands on screen. Six views are only+ // comparable if they share one orbit: same radius, same target, same fov. Capture mode re-frames+ // the camera for its own side-on plate, so assuming the orbit held is exactly the way a framing+ // difference gets mistaken for a geometry difference.+ const THREE = viewer?.THREE ?? window.THREE;+ let screen = null;+ const model = viewer?.scene?.getObjectByName?.(rootName);+ if (model && THREE?.Box3) {+ const box = new THREE.Box3().setFromObject(model);+ const pts = [];+ for (const x of [box.min.x, box.max.x]) {+ for (const y of [box.min.y, box.max.y]) {+ for (const z of [box.min.z, box.max.z]) {+ const v = new THREE.Vector3(x, y, z).project(camera);+ pts.push(v);+ }+ }+ }+ const xs = pts.map((v) => v.x); const ys = pts.map((v) => v.y);+ screen = {+ ndcMinX: Math.min(...xs), ndcMaxX: Math.max(...xs),+ ndcMinY: Math.min(...ys), ndcMaxY: Math.max(...ys),+ widthFraction: (Math.max(...xs) - Math.min(...xs)) / 2,+ heightFraction: (Math.max(...ys) - Math.min(...ys)) / 2,+ };+ }+ return {+ ok: true,+ radius,+ camera: {+ position: [camera.position.x, camera.position.y, camera.position.z],+ target: [target.x, target.y, target.z],+ fov: camera.fov,+ },+ screen,+ };+ }, { azimuthDeg: view.azimuth, PROFILE_CAMERA, rootName: ROOT_NAME });++ if (!placed.ok) {+ console.error(`FAILED placing camera for ${view.id}: ${placed.reason}`);+ await browser.close();+ process.exit(1);+ }+ await page.waitForTimeout(350);+ const file = path.join(OUT, `${view.id}.png`);+ await page.screenshot({ path: file, timeout: 120_000 });+ const bytes = fs.statSync(file).size;+ // A screenshot that exists but is a few hundred bytes is a blank frame, which would otherwise be+ // scored as if it were the model.+ if (bytes < 5_000) {+ console.error(`FAILED: ${view.id}.png is only ${bytes} bytes — that is a blank frame, not a render`);+ await browser.close();+ process.exit(1);+ }+ written.push({ view: view.id, azimuth: view.azimuth, file, bytes, camera: placed.camera, screen: placed.screen });+ const h = placed.screen ? placed.screen.heightFraction.toFixed(3) : 'n/a';+ const w = placed.screen ? placed.screen.widthFraction.toFixed(3) : 'n/a';+ console.log(+ ` ${view.id.padEnd(16)} az=${String(view.azimuth).padStart(4)} ${(bytes / 1024).toFixed(0).padStart(3)} KB`+ + ` r=${placed.radius.toFixed(3)} fov=${placed.camera.fov} screenH=${h} screenW=${w}`,+ );+ }++ await browser.close();++ const manifest = {+ schemaVersion: 1,+ demo: DEMO,+ pass: 'blockout',+ passId: mask ? 'alpha-silhouette' : 'beauty',+ viewport: [931, 2000],+ captureFrozen: true,+ background: mask ? 'transparent (alpha)' : `#${BG}`,+ backgroundMatchesProfile: mask ? 'n/a — alpha capture is background-independent' : `#${BG}`,+ views: written,+ browserConsoleErrors: errors,+ };+ fs.writeFileSync(path.join(OUT, 'capture-manifest.json'), JSON.stringify(manifest, null, 2) + '\n');+ console.log(`\n${written.length}/${VIEWS.length} views written to ${OUT}`);+ if (errors.length) {+ console.error(`\n${errors.length} browser console error(s):`);+ errors.slice(0, 5).forEach((e) => console.error(' ', e));+ process.exit(1);+ }+ console.log('no browser console errors');+}++main().catch((error) => { console.error('FAILED:', error); process.exit(1); });diff --git a/integrations/glb_character_pipeline/node/compare_views.mjs b/integrations/glb_character_pipeline/node/compare_views.mjsnew file mode 100644index 0000000..f3aeab5--- /dev/null+++ b/integrations/glb_character_pipeline/node/compare_views.mjs@@ -0,0 +1,111 @@+/**+ * US-004: score the code-only build against the GLB baseline, on identical framing.+ *+ * The existing comparator is Python and needs numpy, which is not installed here. Rather than skip the+ * measurement -- the whole acceptance criterion is "the picture did not change" -- the arithmetic runs+ * in a browser, which can decode a PNG and hand back pixels without any dependency at all.+ *+ * Three figures per view, the same three the earlier runs recorded:+ *+ * IoU intersection over union of the two silhouettes, where a silhouette is every pixel+ * that is not the declared background+ * noise mean |Laplacian| of luma inside the silhouette, one figure per side. This is a+ * SURFACE-ROUGHNESS reading, not an error: the baseline has its own value and the+ * question is whether ours sits near it, not whether it is small.+ * colour error mean absolute RGB difference inside the intersection, 0-1+ */+import { chromium } from 'playwright';+import { readFileSync, writeFileSync } from 'node:fs';+import path from 'node:path';++const A = process.argv[2] ?? 'work/cmp/code';+const B = process.argv[3] ?? 'work/cmp/glb';+const VIEWS = ['front', 'profile-left', 'profile-right', 'rear', 'orbit-plus-35', 'orbit-minus-35'];++const browser = await chromium.launch({ headless: true });+const page = await browser.newPage();+await page.setContent('<canvas id="a"></canvas><canvas id="b"></canvas>');++const dataUrl = (file) => `data:image/png;base64,${readFileSync(file).toString('base64')}`;++const rows = [];+for (const view of VIEWS) {+ const result = await page.evaluate(async ([srcA, srcB]) => {+ const load = (src) => new Promise((resolve, reject) => {+ const image = new Image();+ image.onload = () => resolve(image);+ image.onerror = reject;+ image.src = src;+ });+ const [imageA, imageB] = await Promise.all([load(srcA), load(srcB)]);+ if (imageA.width !== imageB.width || imageA.height !== imageB.height) {+ return { error: `size ${imageA.width}x${imageA.height} vs ${imageB.width}x${imageB.height}` };+ }+ const width = imageA.width; const height = imageA.height;+ const pixels = (image) => {+ const canvas = document.createElement('canvas');+ canvas.width = width; canvas.height = height;+ const ctx = canvas.getContext('2d', { willReadFrequently: true });+ ctx.drawImage(image, 0, 0);+ return ctx.getImageData(0, 0, width, height).data;+ };+ const pa = pixels(imageA); const pb = pixels(imageB);++ // The declared background is #0f0f0f. A tolerance of 12 keeps the near-black rim of the figure in+ // the silhouette while keeping compression noise out of it.+ const isFigure = (p, i) => Math.abs(p[i] - 15) > 12 || Math.abs(p[i + 1] - 15) > 12 || Math.abs(p[i + 2] - 15) > 12;+ const luma = (p, i) => 0.2126 * p[i] + 0.7152 * p[i + 1] + 0.0722 * p[i + 2];++ let both = 0; let either = 0; let colourSum = 0;+ const maskA = new Uint8Array(width * height);+ const maskB = new Uint8Array(width * height);+ for (let y = 0; y < height; y += 1) {+ for (let x = 0; x < width; x += 1) {+ const n = y * width + x; const i = n * 4;+ const fa = isFigure(pa, i); const fb = isFigure(pb, i);+ maskA[n] = fa ? 1 : 0; maskB[n] = fb ? 1 : 0;+ if (fa || fb) either += 1;+ if (fa && fb) {+ both += 1;+ colourSum += (Math.abs(pa[i] - pb[i]) + Math.abs(pa[i + 1] - pb[i + 1]) + Math.abs(pa[i + 2] - pb[i + 2])) / 3;+ }+ }+ }++ const laplacian = (p, mask) => {+ let sum = 0; let count = 0;+ for (let y = 1; y < height - 1; y += 1) {+ for (let x = 1; x < width - 1; x += 1) {+ const n = y * width + x;+ if (!mask[n]) continue;+ const i = n * 4;+ const value = 4 * luma(p, i)+ - luma(p, i - 4) - luma(p, i + 4)+ - luma(p, i - width * 4) - luma(p, i + width * 4);+ sum += Math.abs(value); count += 1;+ }+ }+ return count ? sum / count : 0;+ };++ return {+ iou: both / Math.max(either, 1),+ colourError: colourSum / Math.max(both, 1) / 255,+ noiseA: laplacian(pa, maskA),+ noiseB: laplacian(pb, maskB),+ pixelsA: maskA.reduce((s, v) => s + v, 0),+ pixelsB: maskB.reduce((s, v) => s + v, 0),+ };+ }, [dataUrl(path.join(A, `${view}.png`)), dataUrl(path.join(B, `${view}.png`))]);++ if (result.error) { console.log(`${view.padEnd(16)} ${result.error}`); continue; }+ rows.push({ view, ...result });+ console.log(`${view.padEnd(16)} IoU ${result.iou.toFixed(4)} colour ${result.colourError.toFixed(4)} `+ + `noise ours ${result.noiseA.toFixed(2)} / baseline ${result.noiseB.toFixed(2)} `+ + `px ${result.pixelsA.toLocaleString()} vs ${result.pixelsB.toLocaleString()}`);+}+const mean = (key) => rows.reduce((s, r) => s + r[key], 0) / Math.max(rows.length, 1);+console.log(`\nmean over ${rows.length} views: IoU ${mean('iou').toFixed(4)} colour ${mean('colourError').toFixed(4)}`+ + ` noise ours ${mean('noiseA').toFixed(2)} / baseline ${mean('noiseB').toFixed(2)}`);+writeFileSync('work/compare-views.json', JSON.stringify({ a: A, b: B, rows }, null, 1));+await browser.close();diff --git a/integrations/glb_character_pipeline/node/emit_surface_module.mjs b/integrations/glb_character_pipeline/node/emit_surface_module.mjsnew file mode 100644index 0000000..54178d5--- /dev/null+++ b/integrations/glb_character_pipeline/node/emit_surface_module.mjs@@ -0,0 +1,66 @@+/**+ * Write the encoded surfaces out as a TypeScript module, so the demo imports them instead of fetching.+ *+ * The stream goes in as base64 rather than as a number array for a measured reason: the same data as a+ * plain literal is about ten times the source size, and the browser has `atob` built in.+ */+import { readFileSync, writeFileSync, statSync } from 'node:fs';++const LEVEL = process.argv[2] ?? 'x2';+const tag = LEVEL === 'default' ? '-default' : `-${LEVEL}`;+const DEST = process.argv[3] ?? 'src/demos/girl-character/surfaceData.ts';+const CODEC_IMPORT = process.env.CHARACTER_CODEC_IMPORT ?? './surfaceCodec';++// PACKAGED (v1.5.1): must match CHARACTER_WORK_TAG used when encode_surfaces.mjs wrote these files.+const workTag = process.env.CHARACTER_WORK_TAG ?? '';+const meta = JSON.parse(readFileSync(`work/surfaces${workTag}${tag}.json`, 'utf8'));+const base64 = readFileSync(`work/surfaces${workTag}${tag}.b64`, 'utf8').trim();++const nodes = meta.nodes.map((n) => ({+ node: n.node,+ region: n.region,+ material: n.material ?? null,+ cellMillimetres: n.cellMillimetres,+ vertexCount: n.vertexCount,+ origin: n.origin,+ dims: n.dims,+ bytes: n.bytes,+ exceptionQuads: n.exceptionQuads,+}));+const vertices = nodes.reduce((sum, n) => sum + n.vertexCount, 0);+const exceptions = nodes.reduce((sum, n) => sum + n.exceptionQuads, 0);++const header = `import type { EncodedNode } from '${CODEC_IMPORT}';++/**+ * GENERATED by scripts/emit_surface_module.mjs -- do not edit by hand.+ *+ * The figure's implicit surfaces, encoded as described in surfaceCodec.ts and carried IN THE BUNDLE so+ * that nothing is fetched at runtime. Regenerate with:+ *+ * node scripts/encode_surfaces.mjs ${LEVEL}+ * node scripts/emit_surface_module.mjs ${LEVEL}+ *+ * Measured, on the level shipped here:+ *+ * detail level ${LEVEL}+ * nodes ${nodes.length}+ * vertices ${vertices.toLocaleString()}+ * bytes per vertex ${(Buffer.from(base64, 'base64').length / vertices).toFixed(2)}+ * stream ${(Buffer.from(base64, 'base64').length / 1e6).toFixed(2)} MB+ * base64 in this file ${(base64.length / 1e6).toFixed(2)} MB+ * exception quads ${exceptions}+ *+ * Round-tripped against the source before being written: identical vertex and triangle counts,+ * identical colours, positions inside the quantisation step. See scripts/verify_roundtrip.mjs.+ */+export const SURFACE_LEVEL = ${JSON.stringify(LEVEL)};++export const SURFACE_NODES: readonly EncodedNode[] = ${JSON.stringify(nodes, null, 2)};++export const SURFACE_STREAM =+ '${base64}';+`;+writeFileSync(DEST, header);+console.log(`wrote ${DEST} ${(statSync(DEST).size / 1e6).toFixed(2)} MB`+ + ` (${nodes.length} nodes, ${vertices.toLocaleString()} vertices, ${exceptions} exception quads)`);diff --git a/integrations/glb_character_pipeline/node/encode_surfaces.mjs b/integrations/glb_character_pipeline/node/encode_surfaces.mjsnew file mode 100644index 0000000..fb10b75--- /dev/null+++ b/integrations/glb_character_pipeline/node/encode_surfaces.mjs@@ -0,0 +1,264 @@+/**+ * US-002: encode the Surface Nets output compactly enough to live inside a TypeScript module.+ *+ * US-001 established what is actually information in the .bin and what is not. Every vertex sits in its+ * own voxel cell, so the cell coordinate identifies it and the connectivity follows from cell adjacency:+ * the stored index buffer (50.6 MB of the default level's 107.6) and the stored normals (another 25 MB)+ * are both derivable and are not written here at all.+ *+ * WHAT IS WRITTEN, per node:+ *+ * grid origin, cell size, dimensions -- 7 numbers, from the GLB's accessor minima+ * cells the active cell list, sorted by linear index and DELTA-encoded as varints. Sorted+ * deltas are mostly small, which is the whole reason this fits: a raw (i,j,k) is 5 bytes+ * and a delta is usually 1.+ * offsets the in-cell position, 8 bits per axis. One cell is 1.5-2.5 mm, so a step is 6-10 microns+ * -- three orders below the cell, and the cell is already the resolution limit.+ * colours 8 bits per channel, unchanged from the source bake.+ * edges 6 bits per cell: for each of the three axes, whether the grid edge leaving this cell+ * changes sign, and which way the resulting quad winds. This is what replaces the indices.+ * exceptions the 0.001% of quads US-001 could not reduce, written out explicitly, so the rebuild is+ * bit-exact instead of approximately right.+ *+ * Emitted as base64 inside a .ts module, so the demo imports it and fetches nothing.+ */+import { readFileSync, writeFileSync, statSync } from 'node:fs';++const LEVELS = process.argv.slice(2).length ? process.argv.slice(2) : ['x3'];+/**+ * PACKAGED (v1.5.1). GLB path, .bin source directory and the intermediate work/surfaces* filename+ * prefix are overridable, so a second character can be encoded in the same checkout without colliding+ * with girl-character's own artifacts. build-character.sh sets these from a per-character .env config.+ */+const GLB = process.env.CHARACTER_GLB ?? 'public/mesh/girl-character-baseline.glb';+const BIN_DIR = process.env.CHARACTER_BIN_DIR ?? 'public/head';+const WORK_TAG = process.env.CHARACTER_WORK_TAG ?? '';++function loadNodes(path) {+ const buf = readFileSync(path);+ if (buf.toString('latin1', 0, 4) !== 'HEDS') throw new Error(`${path}: bad magic`);+ const jsonLength = buf.readUInt32LE(8);+ const header = JSON.parse(buf.toString('utf8', 12, 12 + jsonLength));+ let offset = 12 + jsonLength;+ offset += (4 - (offset % 4)) % 4;+ return header.map((entry) => {+ const n = entry.vertexCount;+ const posAt = offset;+ const colAt = posAt + n * 12 + n * 12;+ let idxAt = colAt + n * 3;+ idxAt += (4 - (idxAt % 4)) % 4;+ const end = idxAt + entry.indexCount * 4;+ const out = {+ ...entry,+ V: new Float32Array(buf.buffer.slice(buf.byteOffset + posAt, buf.byteOffset + posAt + n * 12)),+ C: new Uint8Array(buf.buffer.slice(buf.byteOffset + colAt, buf.byteOffset + colAt + n * 3)),+ T: new Uint32Array(buf.buffer.slice(buf.byteOffset + idxAt, buf.byteOffset + end)),+ };+ offset = end;+ return out;+ });+}++function cloudMinima(glbPath) {+ const raw = readFileSync(glbPath);+ let off = 12; const chunks = {};+ while (off < raw.length) {+ const ln = raw.readUInt32LE(off); const ty = raw.readUInt32LE(off + 4);+ chunks[ty] = raw.subarray(off + 8, off + 8 + ln);+ off += 8 + ln; off += (4 - (off % 4)) % 4;+ }+ const g = JSON.parse(chunks[0x4E4F534A].toString('utf8'));+ const minima = new Map();+ g.nodes.forEach((node, index) => {+ if (node.mesh === undefined) return;+ const min = [Infinity, Infinity, Infinity];+ const max = [-Infinity, -Infinity, -Infinity];+ for (const primitive of g.meshes[node.mesh].primitives) {+ const accessor = g.accessors[primitive.attributes.POSITION];+ for (let c = 0; c < 3; c += 1) {+ min[c] = Math.min(min[c], accessor.min[c]);+ max[c] = Math.max(max[c], accessor.max[c]);+ }+ }+ minima.set(index, { min, max });+ });+ return minima;+}++/** Varint, low seven bits first, high bit as the continuation flag. */+function pushVarint(bytes, value) {+ let v = value;+ while (v >= 0x80) { bytes.push((v & 0x7f) | 0x80); v = Math.floor(v / 128); }+ bytes.push(v);+}++const MINIMA = cloudMinima(GLB);++for (const level of LEVELS) {+ const suffix = level === '' || level === 'default' ? '' : `-${level}`;+ const src = `${BIN_DIR}/sdf-surfaces${suffix}.bin`;+ const nodes = loadNodes(src);+ const out = { level: suffix, nodes: [] };+ const blocks = [];+ let totalVertices = 0; let totalQuads = 0; let totalExceptions = 0;++ for (const node of nodes) {+ const cell = node.cellMillimetres / 1000;+ const n = node.vertexCount;+ const bounds = MINIMA.get(node.node);+ const lo = bounds.min.map((m) => m - cell * 5);+ // THE BUILDER'S OWN GRID, reproduced rather than invented. build_head_surface.py sets+ // hi = P.max + PAD and dims = ceil((hi - lo) / cell) + 1, and emits vertices in C-order over the+ // CELL grid, which is dims - 1. Using a tighter grid of my own changed the linear index, so the+ // sort reordered the vertices relative to the source -- 1,193 of them on the trousers -- and every+ // index-based comparison downstream became meaningless. Matching the builder means the source is+ // already in order and nothing is reordered at all.+ const hi = bounds.max.map((m) => m + cell * 5);+ const grid = [0, 1, 2].map((c) => Math.ceil((hi[c] - lo[c]) / cell) + 1);+ const cellDims = grid.map((v) => v - 1);++ // Cell assignment, with the same boundary handling US-001 needed.+ const taken = new Map();+ const ijkOf = new Array(n);+ const fracOf = new Array(n);+ for (let i = 0; i < n; i += 1) {+ const raw = [0, 1, 2].map((c) => (node.V[3 * i + c] - lo[c]) / cell);+ const ijk = raw.map(Math.floor);+ let key = `${ijk[0]},${ijk[1]},${ijk[2]}`;+ if (taken.has(key)) {+ const EPS = 1e-3;+ for (let d = 0; d < 27; d += 1) {+ const t = [ijk[0] + (d % 3) - 1, ijk[1] + (Math.floor(d / 3) % 3) - 1, ijk[2] + Math.floor(d / 9) - 1];+ if (![0, 1, 2].every((c) => raw[c] >= t[c] - EPS && raw[c] <= t[c] + 1 + EPS)) continue;+ const tk = `${t[0]},${t[1]},${t[2]}`;+ if (taken.has(tk)) continue;+ ijk[0] = t[0]; ijk[1] = t[1]; ijk[2] = t[2]; key = tk; break;+ }+ }+ taken.set(key, i);+ ijkOf[i] = ijk;+ fracOf[i] = [0, 1, 2].map((c) => Math.min(1, Math.max(0, raw[c] - ijk[c])));+ }++ // Grid dimensions from the cells present, so the linear index is compact.+ const dims = cellDims;+ // A coordinate outside the grid must be rejected, not packed: negative j or k wraps into another+ // valid cell rather than out of range, which silently connects the wrong vertices.+ const inGrid = (ijk) => ijk.every((v, c) => v >= 0 && v < dims[c]);+ const linear = (ijk) => (ijk[0] * dims[1] + ijk[1]) * dims[2] + ijk[2];+ const cellIndex = (ijk) => (inGrid(ijk) ? linear(ijk) : -1);++ // Sort by linear index: this is what makes the deltas small.+ // NOT SORTED, so vertex i means the same point on both sides. With the builder's grid the source is+ // very nearly ascending already, but not perfectly: the collision search moves a handful of+ // vertices into a neighbouring cell, which can step backwards. Sorting to fix that is what+ // reordered 1,193 vertices on the trousers and made every index-based check meaningless, so the+ // order is kept and the delta is allowed to be negative instead.+ const order = Array.from({ length: n }, (_, i) => i);+ let backwards = 0;+ for (let i = 1; i < n; i += 1) {+ if (linear(ijkOf[order[i]]) < linear(ijkOf[order[i - 1]])) backwards += 1;+ }+ const rank = new Array(n);+ order.forEach((original, position) => { rank[original] = position; });+ const cellAt = new Map();+ order.forEach((original, position) => { cellAt.set(linear(ijkOf[original]), position); });++ // Quads, recovered as US-001 did, then reduced to per-cell edge bits.+ const tris = node.T.length / 3;+ const half = tris / 2;+ const edgeBits = new Uint16Array(n);+ const exceptions = [];+ const OFFSETS = [+ [[0, -1, -1], [0, 0, -1], [0, 0, 0], [0, -1, 0]],+ [[-1, 0, -1], [-1, 0, 0], [0, 0, 0], [0, 0, -1]],+ [[-1, -1, 0], [0, -1, 0], [0, 0, 0], [-1, 0, 0]],+ ];+ for (let q = 0; q < half; q += 1) {+ const a = node.T.subarray(3 * q, 3 * q + 3);+ const b = node.T.subarray(3 * (q + half), 3 * (q + half) + 3);+ const quad = [a[0], a[1], a[2], b[2]];+ const cs = quad.map((v) => ijkOf[v]);+ let axis = -1;+ for (let c = 0; c < 3; c += 1) if (cs.every((x) => x[c] === cs[0][c])) { axis = c; break; }+ if (axis === -1) { exceptions.push(quad.map((v) => rank[v])); continue; }+ const base = [0, 1, 2].map((c) => Math.max(...cs.map((x) => x[c])));+ const owner = cellAt.get(cellIndex(base));+ if (owner === undefined) { exceptions.push(quad.map((v) => rank[v])); continue; }+ // Does the rebuild from this cell reproduce the quad? If not, keep the quad verbatim.+ const corner = OFFSETS[axis].map(([di, dj, dk]) => cellAt.get(cellIndex([base[0] + di, base[1] + dj, base[2] + dk])));+ if (corner.some((c) => c === undefined)) { exceptions.push(quad.map((v) => rank[v])); continue; }+ const wanted = quad.map((v) => rank[v]).join(',');+ // WHICH CORNER THE SPLIT STARTS FROM MATTERS. The quad is cut into two triangles from its first+ // vertex, so a rotation of the same four corners cuts the OTHER diagonal -- a different surface+ // wherever the quad is not planar, which for Surface Nets output is most of them. Storing only+ // "these four corners, maybe reversed" left exactly one triangle per quad wrong and rendered as+ // rows of diamond-shaped facets. So the rotation is stored too: four bits per axis, not two.+ let rotation = -1; let reversed = false;+ for (let rev = 0; rev < 2 && rotation < 0; rev += 1) {+ const seq = rev ? [...corner].reverse() : corner;+ for (let r = 0; r < 4; r += 1) {+ if ([...seq.slice(r), ...seq.slice(0, r)].join(',') === wanted) { rotation = r; reversed = rev === 1; break; }+ }+ }+ if (rotation < 0) { exceptions.push(quad.map((v) => rank[v])); continue; }+ // bit 0 of the nibble: the edge exists. bit 1: reversed. bits 2-3: the rotation.+ edgeBits[owner] |= (1 | (reversed ? 2 : 0) | (rotation << 2)) << (4 * axis);+ }++ // Stream it.+ const cells = [];+ let previous = 0;+ for (const original of order) {+ const value = linear(ijkOf[original]);+ // DELTA, NOT DELTA MINUS ONE. Two vertices can land in the same cell when the collision search+ // cannot free one -- five times in 2.1 million on the full level -- and `delta - 1` is then -1,+ // which Uint8Array stores as 255: a continuation byte that makes the decoder read past the end of+ // the section. It drifted node 10 by six bytes and every node after it decoded from the wrong+ // offset. Encoding the delta itself costs nothing (a run of consecutive cells is still one byte)+ // and makes a duplicate representable; the quads around it become explicit exceptions.+ // Zigzag, so a backwards step costs one bit rather than being unrepresentable.+ const delta = value - previous;+ pushVarint(cells, delta >= 0 ? delta * 2 : -delta * 2 - 1);+ previous = value;+ }+ const offsets = new Uint8Array(n * 3);+ const colours = new Uint8Array(n * 3);+ order.forEach((original, position) => {+ for (let c = 0; c < 3; c += 1) {+ offsets[position * 3 + c] = Math.round(fracOf[original][c] * 255);+ colours[position * 3 + c] = node.C[original * 3 + c];+ }+ });+ const exceptionBytes = [];+ pushVarint(exceptionBytes, exceptions.length);+ for (const quad of exceptions) for (const v of quad) pushVarint(exceptionBytes, v);++ const edgeBytes = new Uint8Array(edgeBits.buffer, edgeBits.byteOffset, edgeBits.byteLength);+ const parts = [Uint8Array.from(cells), offsets, colours, edgeBytes, Uint8Array.from(exceptionBytes)];+ const block = Buffer.concat(parts.map((p) => Buffer.from(p.buffer, p.byteOffset, p.byteLength)));+ blocks.push(block);+ out.nodes.push({+ node: node.node, region: node.region, material: node.material ?? null,+ cellMillimetres: node.cellMillimetres,+ vertexCount: n, origin: lo, dims,+ bytes: { cells: cells.length, offsets: offsets.length, colours: colours.length, edges: n * 2, exceptions: exceptionBytes.length },+ exceptionQuads: exceptions.length,+ backwardsSteps: backwards,+ });+ totalVertices += n; totalQuads += half; totalExceptions += exceptions.length;+ }++ const body = Buffer.concat(blocks);+ const base64 = body.toString('base64');+ const dest = `work/surfaces${WORK_TAG}${suffix || '-default'}.json`;+ writeFileSync(dest, JSON.stringify(out, null, 1));+ writeFileSync(`work/surfaces${WORK_TAG}${suffix || '-default'}.b64`, base64);+ const binMb = statSync(src).size / 1e6;+ console.log(`${src}`);+ console.log(` ${totalVertices.toLocaleString()} verts ${totalQuads.toLocaleString()} quads `+ + `${totalExceptions} exception quads (${(100 * totalExceptions / totalQuads).toFixed(4)}%)`);+ console.log(` stream ${(body.length / 1e6).toFixed(2)} MB = ${(body.length / totalVertices).toFixed(2)} bytes/vertex`+ + ` base64 ${(base64.length / 1e6).toFixed(2)} MB was ${binMb.toFixed(1)} MB `+ + `(${(100 * base64.length / (binMb * 1e6)).toFixed(1)}% of the .bin)`);+}diff --git a/integrations/glb_character_pipeline/node/package-lock.json b/integrations/glb_character_pipeline/node/package-lock.jsonnew file mode 100644index 0000000..5498767--- /dev/null+++ b/integrations/glb_character_pipeline/node/package-lock.json@@ -0,0 +1,529 @@+{+ "name": "img2threejs-glb-character-pipeline-node",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "img2threejs-glb-character-pipeline-node",+ "version": "0.1.0",+ "devDependencies": {+ "esbuild": "0.24.2",+ "playwright": "1.57.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz",+ "integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz",+ "integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz",+ "integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz",+ "integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz",+ "integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz",+ "integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz",+ "integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz",+ "integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz",+ "integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz",+ "integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz",+ "integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz",+ "integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz",+ "integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz",+ "integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz",+ "integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz",+ "integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz",+ "integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz",+ "integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz",+ "integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz",+ "integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz",+ "integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz",+ "integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz",+ "integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz",+ "integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz",+ "integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/esbuild": {+ "version": "0.24.2",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz",+ "integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.24.2",+ "@esbuild/android-arm": "0.24.2",+ "@esbuild/android-arm64": "0.24.2",+ "@esbuild/android-x64": "0.24.2",+ "@esbuild/darwin-arm64": "0.24.2",+ "@esbuild/darwin-x64": "0.24.2",+ "@esbuild/freebsd-arm64": "0.24.2",+ "@esbuild/freebsd-x64": "0.24.2",+ "@esbuild/linux-arm": "0.24.2",+ "@esbuild/linux-arm64": "0.24.2",+ "@esbuild/linux-ia32": "0.24.2",+ "@esbuild/linux-loong64": "0.24.2",+ "@esbuild/linux-mips64el": "0.24.2",+ "@esbuild/linux-ppc64": "0.24.2",+ "@esbuild/linux-riscv64": "0.24.2",+ "@esbuild/linux-s390x": "0.24.2",+ "@esbuild/linux-x64": "0.24.2",+ "@esbuild/netbsd-arm64": "0.24.2",+ "@esbuild/netbsd-x64": "0.24.2",+ "@esbuild/openbsd-arm64": "0.24.2",+ "@esbuild/openbsd-x64": "0.24.2",+ "@esbuild/sunos-x64": "0.24.2",+ "@esbuild/win32-arm64": "0.24.2",+ "@esbuild/win32-ia32": "0.24.2",+ "@esbuild/win32-x64": "0.24.2"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/playwright": {+ "version": "1.57.0",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.57.0.tgz",+ "integrity": "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.57.0"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.57.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.57.0.tgz",+ "integrity": "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ }+ }+}diff --git a/integrations/glb_character_pipeline/node/package.json b/integrations/glb_character_pipeline/node/package.jsonnew file mode 100644index 0000000..4a65d3b--- /dev/null+++ b/integrations/glb_character_pipeline/node/package.json@@ -0,0 +1,11 @@+{+ "name": "img2threejs-glb-character-pipeline-node",+ "private": true,+ "version": "0.1.0",+ "type": "module",+ "description": "Node-side Surface Nets encode/verify/capture scripts for the GLB character pipeline integration",+ "devDependencies": {+ "esbuild": "0.24.2",+ "playwright": "1.57.0"+ }+}diff --git a/integrations/glb_character_pipeline/node/verify_cells.mjs b/integrations/glb_character_pipeline/node/verify_cells.mjsnew file mode 100644index 0000000..47d7a09--- /dev/null+++ b/integrations/glb_character_pipeline/node/verify_cells.mjs@@ -0,0 +1,191 @@+/**+ * US-001: prove the .bin's index buffer is redundant, or find out that it is not.+ *+ * The surfaces were contoured with Surface Nets, which places exactly ONE vertex per sign-changing+ * cell at `lo + (ijk + offset) * cell`, and emits one quad per sign-changing grid edge. If that holds+ * for the shipped data then a vertex's cell coordinate identifies it, and the connectivity follows from+ * a handful of bits per cell instead of a stored index buffer -- 50.6 MB of the default level's 107.6.+ *+ * This checks the claim rather than assuming it, on all 16 nodes:+ *+ * 1. recover the grid origin, and require vertex -> cell to be a BIJECTION+ * 2. recover the quads (they were written as two triangle halves, so quad q is T[q] and T[q + n/2])+ * 3. reduce each quad to (cell, axis, winding) -- six bits per cell+ * 4. rebuild the quads from those bits alone and compare the triangle SETS+ *+ * A mismatch on any node is reported as a mismatch. Shipping a silent one would trade a visible 107 MB+ * download for an invisible hole in the mesh.+ */+import { readFileSync } from 'node:fs';++const SRC = process.argv[2] ?? 'public/head/sdf-surfaces-x3.bin';+const GLB = process.argv[3] ?? 'public/mesh/girl-character-baseline.glb';++function loadNodes(path) {+ const buf = readFileSync(path);+ if (buf.toString('latin1', 0, 4) !== 'HEDS') throw new Error(`${path}: bad magic`);+ const jsonLength = buf.readUInt32LE(8);+ const header = JSON.parse(buf.toString('utf8', 12, 12 + jsonLength));+ let offset = 12 + jsonLength;+ offset += (4 - (offset % 4)) % 4;+ const out = [];+ for (const entry of header) {+ const n = entry.vertexCount;+ const posAt = offset;+ let idxAt = posAt + n * 12 + n * 12 + n * 3;+ idxAt += (4 - (idxAt % 4)) % 4;+ const end = idxAt + entry.indexCount * 4;+ out.push({+ ...entry,+ V: new Float32Array(buf.buffer.slice(buf.byteOffset + posAt, buf.byteOffset + posAt + n * 12)),+ T: new Uint32Array(buf.buffer.slice(buf.byteOffset + idxAt, buf.byteOffset + end)),+ });+ offset = end;+ }+ return out;+}++/**+ * The grid origin, taken from the builder's own rule rather than searched for.+ *+ * scripts/build_head_surface.py sets `lo = P.min(axis=0) - PAD` with PAD = RADIUS * 2 and+ * RADIUS = CELL * 2.5, so the origin is the node's point-cloud minimum less five cells. A first+ * version of this script swept the sub-cell phase instead and put 29% of vertices in a cell already+ * taken -- the phase is set by the CLOUD's minimum, and the surface's minimum is a different number.+ */+function cloudMinima(glbPath) {+ const raw = readFileSync(glbPath);+ let off = 12; const chunks = {};+ while (off < raw.length) {+ const ln = raw.readUInt32LE(off); const ty = raw.readUInt32LE(off + 4);+ chunks[ty] = raw.subarray(off + 8, off + 8 + ln);+ off += 8 + ln; off += (4 - (off % 4)) % 4;+ }+ const g = JSON.parse(chunks[0x4E4F534A].toString('utf8'));+ const minima = new Map();+ g.nodes.forEach((node, index) => {+ if (node.mesh === undefined) return;+ const min = [Infinity, Infinity, Infinity];+ for (const primitive of g.meshes[node.mesh].primitives) {+ const accessor = g.accessors[primitive.attributes.POSITION];+ if (!accessor.min) throw new Error(`accessor for node ${index} has no min`);+ for (let c = 0; c < 3; c += 1) min[c] = Math.min(min[c], accessor.min[c]);+ }+ minima.set(index, min);+ });+ return minima;+}++function findOrigin(cloudMin, cell) {+ return [0, 1, 2].map((c) => cloudMin[c] - cell * 5);+}++const MINIMA = cloudMinima(GLB);+let ok = 0; let bad = 0;+for (const node of loadNodes(SRC)) {+ const cell = node.cellMillimetres / 1000;+ const n = node.vertexCount;+ const lo = findOrigin(MINIMA.get(node.node), cell);++ // 1. bijection vertex -> cell+ const cellOf = new Array(n);+ const seen = new Map();+ let collisions = 0;+ for (let i = 0; i < n; i += 1) {+ const raw = [0, 1, 2].map((c) => (node.V[3 * i + c] - lo[c]) / cell);+ const ijk = raw.map(Math.floor);+ let key = `${ijk[0]},${ijk[1]},${ijk[2]}`;+ // BOUNDARY CASE, and it is not floating-point noise. The builder's in-cell offset is an average of+ // edge crossings and can come out exactly 1.0 when every crossing clips to the far corner, which+ // floors into the NEXT cell and collides with whatever lives there. Stepping back along an axis+ // whose offset landed on the boundary puts the vertex back in its own cell.+ if (seen.has(key)) {+ // Search the 27 neighbours for a free cell that still CONTAINS this vertex to within float32's+ // reach. The tolerance has to be scaled: (V - lo) / cell runs to about 500, so a float32 mantissa+ // is worth roughly 3e-5 there, not the 1e-5 a first pass assumed -- which is why five nodes still+ // collided after it.+ const EPS = 1e-3;+ let placed = false;+ for (let d = 0; d < 27 && !placed; d += 1) {+ const trial = [ijk[0] + (d % 3) - 1, ijk[1] + (Math.floor(d / 3) % 3) - 1, ijk[2] + Math.floor(d / 9) - 1];+ const contains = [0, 1, 2].every((c) => raw[c] >= trial[c] - EPS && raw[c] <= trial[c] + 1 + EPS);+ if (!contains) continue;+ const trialKey = `${trial[0]},${trial[1]},${trial[2]}`;+ if (seen.has(trialKey)) continue;+ ijk[0] = trial[0]; ijk[1] = trial[1]; ijk[2] = trial[2];+ key = trialKey; placed = true;+ }+ }+ if (seen.has(key)) collisions += 1;+ seen.set(key, i);+ cellOf[i] = ijk;+ }++ // 2. quads: written as T[q] = quad[0,1,2] and T[q + half] = quad[0,2,3]+ const tris = node.T.length / 3;+ const half = tris / 2;+ const quads = [];+ let pairingOk = Number.isInteger(half);+ if (pairingOk) {+ for (let q = 0; q < half; q += 1) {+ const a = node.T.subarray(3 * q, 3 * q + 3);+ const b = node.T.subarray(3 * (q + half), 3 * (q + half) + 3);+ if (a[0] !== b[0] || a[2] !== b[1]) { pairingOk = false; break; }+ quads.push([a[0], a[1], a[2], b[2]]);+ }+ }++ // 3. reduce each quad to (cell, axis, winding). The four cells around a grid edge differ by -1/0 on+ // the two axes that are not the edge's own, so the axis falls out of which coordinate is constant.+ const bits = new Map();+ const reducible = pairingOk;+ // COUNT, do not bail. An earlier version broke out of this loop on the first quad it could not+ // reduce, which reported "rebuilt 0" and hid whether the problem was one quad or all of them.+ let unreduced = 0;+ for (const quad of quads) {+ const cs = quad.map((v) => cellOf[v]);+ let axis = -1;+ for (let c = 0; c < 3; c += 1) {+ if (cs.every((x) => x[c] === cs[0][c])) { axis = c; break; }+ }+ if (axis === -1) { unreduced += 1; continue; }+ // the edge is identified by the maximum corner of the four cells+ const base = [0, 1, 2].map((c) => Math.max(...cs.map((x) => x[c])));+ const key = `${base[0]},${base[1]},${base[2]},${axis}`;+ // winding: which of the two orderings the builder emitted+ bits.set(key, quad);+ }++ // 4. rebuild from the bits alone: for each recorded edge, gather its four cells and re-emit+ let rebuilt = 0; let mismatched = 0;+ if (reducible) {+ const OFFSETS = [+ [[0, -1, -1], [0, 0, -1], [0, 0, 0], [0, -1, 0]],+ [[-1, 0, -1], [-1, 0, 0], [0, 0, 0], [0, 0, -1]],+ [[-1, -1, 0], [0, -1, 0], [0, 0, 0], [-1, 0, 0]],+ ];+ for (const [key, original] of bits) {+ const [i, j, k, axis] = key.split(',').map(Number);+ const corner = OFFSETS[axis].map(([di, dj, dk]) => seen.get(`${i + di},${j + dj},${k + dk}`));+ if (corner.some((c) => c === undefined)) { mismatched += 1; continue; }+ const forward = corner.join(',');+ const reversed = [...corner].reverse().join(',');+ const want = original.join(',');+ const wantRotations = [0, 1, 2, 3].flatMap((r) => {+ const rot = [...original.slice(r), ...original.slice(0, r)].join(',');+ const rev = [...original].reverse();+ return [rot, [...rev.slice(r), ...rev.slice(0, r)].join(',')];+ });+ if (wantRotations.includes(forward) || wantRotations.includes(reversed)) rebuilt += 1;+ else { mismatched += 1; if (mismatched < 3) console.log(` want ${want} got ${forward}`); }+ }+ }++ const verdict = collisions === 0 && pairingOk && reducible && mismatched === 0 && unreduced === 0;+ if (verdict) ok += 1; else bad += 1;+ console.log(`node ${String(node.node).padStart(2)} ${node.region.padEnd(11)} ${String(n).padStart(8)} verts `+ + `cell ${String(node.cellMillimetres).padStart(4)}mm collisions ${String(collisions).padStart(6)} `+ + `quads ${String(quads.length).padStart(8)} rebuilt ${String(rebuilt).padStart(8)} `+ + `unreduced ${String(unreduced).padStart(5)} mismatched ${String(mismatched).padStart(6)} ${verdict ? 'OK' : 'FAIL'}`);+}+console.log(`\n${ok} of ${ok + bad} nodes reproduce their index buffer from cell adjacency alone`);diff --git a/integrations/glb_character_pipeline/node/verify_roundtrip.mjs b/integrations/glb_character_pipeline/node/verify_roundtrip.mjsnew file mode 100644index 0000000..a4c1a2b--- /dev/null+++ b/integrations/glb_character_pipeline/node/verify_roundtrip.mjs@@ -0,0 +1,148 @@+/**+ * US-002/US-003: decode the encoded stream with the SHIPPING codec and compare it to the .bin.+ *+ * The point of using the real `surfaceCodec.ts` rather than a second implementation in this script is+ * that a reimplementation can agree with itself and still disagree with the browser. esbuild is already+ * a vite dependency, so the TypeScript is transpiled and imported here exactly as the bundle will get+ * it.+ *+ * What is compared, per node:+ *+ * vertex count must match exactly+ * position worst-case error, against the cell/255 quantisation step it is allowed+ * colour must match exactly; the encoder copies these bytes untouched+ * triangle count must match exactly+ * triangle set the same triangles, up to rotation and winding, as a set+ *+ * A difference in the triangle SET is the one that matters: positions can be a micron out without+ * anyone seeing it, but a missing triangle is a hole.+ */+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { build } from 'esbuild';++const LEVEL = process.argv[2] ?? 'x2';+const suffix = LEVEL === 'default' ? '' : `-${LEVEL}`;+const tag = LEVEL === 'default' ? '-default' : suffix;+/**+ * PACKAGED (v1.5.1). The codec entrypoint, the .bin source directory and the work/surfaces* tag are+ * overridable. The codec itself (surfaceCodec.ts) is character-agnostic -- it decodes whatever+ * EncodedNode metadata it is given -- so a new character normally reuses the SAME codec file and only+ * needs its own CHARACTER_BIN_DIR / CHARACTER_WORK_TAG.+ */+const CODEC_ENTRY = process.env.CHARACTER_CODEC ?? 'src/demos/girl-character/surfaceCodec.ts';+const BIN_DIR = process.env.CHARACTER_BIN_DIR ?? 'public/head';+const WORK_TAG = process.env.CHARACTER_WORK_TAG ?? '';++mkdirSync('work/codec', { recursive: true });+await build({+ entryPoints: [CODEC_ENTRY],+ // PACKAGED (v1.5.1) FIX: an absolute path, resolved against process.cwd() (build-character.sh always+ // cds to the repo root first). A path relative to THIS SCRIPT's own location broke the moment the+ // script moved one directory deeper during packaging -- '../work/codec/...' resolved to+ // v1.5.1/work/codec/... instead of <repo root>/work/codec/..., and the dynamic import below threw+ // ERR_MODULE_NOT_FOUND. Caught by actually running this against real data, not by inspection.+ outfile: path.resolve(process.cwd(), 'work/codec/surfaceCodec.mjs'),+ format: 'esm', platform: 'node', bundle: true, external: ['three'], logLevel: 'error',+});+const codecOut = path.resolve(process.cwd(), 'work/codec/surfaceCodec.mjs');+const { decodeSurfaces } = await import(pathToFileURL(codecOut).href);++function loadNodes(path) {+ const buf = readFileSync(path);+ const jsonLength = buf.readUInt32LE(8);+ const header = JSON.parse(buf.toString('utf8', 12, 12 + jsonLength));+ let offset = 12 + jsonLength;+ offset += (4 - (offset % 4)) % 4;+ return header.map((entry) => {+ const n = entry.vertexCount;+ const posAt = offset;+ const colAt = posAt + n * 12 + n * 12;+ let idxAt = colAt + n * 3;+ idxAt += (4 - (idxAt % 4)) % 4;+ const end = idxAt + entry.indexCount * 4;+ const out = {+ ...entry,+ V: new Float32Array(buf.buffer.slice(buf.byteOffset + posAt, buf.byteOffset + posAt + n * 12)),+ C: new Uint8Array(buf.buffer.slice(buf.byteOffset + colAt, buf.byteOffset + colAt + n * 3)),+ T: new Uint32Array(buf.buffer.slice(buf.byteOffset + idxAt, buf.byteOffset + end)),+ };+ offset = end;+ return out;+ });+}++const meta = JSON.parse(readFileSync(`work/surfaces${WORK_TAG}${tag}.json`, 'utf8'));+const base64 = readFileSync(`work/surfaces${WORK_TAG}${tag}.b64`, 'utf8');+const decoded = decodeSurfaces(base64, meta.nodes);+const original = loadNodes(`${BIN_DIR}/sdf-surfaces${suffix}.bin`);+const byNode = new Map(original.map((o) => [o.node, o]));++/**+ * Triangles compared as unordered index triples, which is valid because the vertex ORDER is preserved.+ *+ * Two earlier versions of this comparison were both wrong, in opposite directions. The first compared+ * only triangle COUNTS and passed a mesh that rendered with flakes all over it -- counting is not+ * comparing. The second keyed on positions quantised to 1e-5, which is 10 microns, against a+ * quantisation error the encoder is allowed up to 9.8 microns: keys fell on either side of a bucket+ * edge and it reported 99.94% of triangles wrong when the codec was right. A comparison whose tolerance+ * is the same size as the thing it tolerates measures nothing.+ *+ * The position check above already establishes that vertex i means the same point in both, so indices+ * are directly comparable and exact.+ */+const triangleKey = (a, b, c) => [a, b, c].sort((x, y) => x - y).join(',');++let failures = 0;+console.log(`level ${LEVEL}\n`);+for (const surface of decoded) {+ const source = byNode.get(surface.node);+ const n = surface.position.length / 3;+ const cell = surface.cellMillimetres / 1000;++ // ORDER FIRST, because the triangle comparison below depends on it. Comparing index triples is only+ // valid if vertex i means the same point on both sides; this measures that rather than assuming it. A+ // permutation would show up here as centimetres, not microns.+ let worst = 0;+ for (let i = 0; i < n * 3; i += 1) worst = Math.max(worst, Math.abs(surface.position[i] - source.V[i]));+ let displaced = 0;+ for (let i = 0; i < n; i += 1) {+ const d = Math.hypot(surface.position[3 * i] - source.V[3 * i],+ surface.position[3 * i + 1] - source.V[3 * i + 1],+ surface.position[3 * i + 2] - source.V[3 * i + 2]);+ if (d > cell) displaced += 1;+ }+ let colourDiff = 0;+ for (let i = 0; i < n * 3; i += 1) colourDiff = Math.max(colourDiff, Math.abs(surface.colour[i] - source.C[i]));++ const mine = new Set();+ for (let t = 0; t < surface.index.length; t += 3) {+ mine.add(triangleKey(surface.index[t], surface.index[t + 1], surface.index[t + 2]));+ }+ const theirs = new Set();+ for (let t = 0; t < source.T.length; t += 3) {+ theirs.add(triangleKey(source.T[t], source.T[t + 1], source.T[t + 2]));+ }+ let missing = 0;+ for (const key of theirs) if (!mine.has(key)) missing += 1;+ let extra = 0;+ for (const key of mine) if (!theirs.has(key)) extra += 1;++ const step = cell / 255;+ const pass = n === source.vertexCount+ && worst <= step * 1.01+ && colourDiff === 0+ && surface.index.length === source.T.length+ && missing === 0 && extra === 0 && displaced === 0;+ if (!pass) failures += 1;+ console.log(`node ${String(surface.node).padStart(2)} ${surface.region.padEnd(11)} `+ + `verts ${String(n).padStart(7)}/${String(source.vertexCount).padStart(7)} `+ + `pos worst ${(worst * 1e6).toFixed(1).padStart(7)} um (step ${(step * 1e6).toFixed(1)} um) `+ + `order-broken ${String(displaced).padStart(5)} tris ${String(surface.index.length / 3).padStart(8)}/`+ + `${String(source.T.length / 3).padStart(8)} missing ${String(missing).padStart(7)} `+ + `extra ${String(extra).padStart(7)} ${pass ? 'OK' : 'FAIL'}`);+}+console.log(`\n${decoded.length - failures} of ${decoded.length} nodes decode to the source within the quantisation step`);+writeFileSync(`work/roundtrip${WORK_TAG}${tag}.txt`, `failures ${failures}\n`);+if (failures) process.exitCode = 1;diff --git a/integrations/glb_character_pipeline/pyproject.toml b/integrations/glb_character_pipeline/pyproject.tomlnew file mode 100644index 0000000..7ababb1--- /dev/null+++ b/integrations/glb_character_pipeline/pyproject.toml@@ -0,0 +1,12 @@+[project]+name = "img2threejs-glb-character-pipeline"+version = "0.1.0"+description = "Optional GLB-baseline character reconstruction pipeline (Surface Nets + SDF splat) for the img2threejs procedural pipeline"+requires-python = ">=3.11,<3.13"+dependencies = [+ "numpy>=1.26,<3",+ "pillow>=11,<13",+]++[tool.uv]+package = falsediff --git a/integrations/glb_character_pipeline/python/bake_atlas_uvs.py b/integrations/glb_character_pipeline/python/bake_atlas_uvs.pynew file mode 100644index 0000000..2dd7e07--- /dev/null+++ b/integrations/glb_character_pipeline/python/bake_atlas_uvs.py@@ -0,0 +1,238 @@+"""Transfer a baseline GLB's TEXCOORD_0 onto a crossSections.ts's ring points, with CONTINUITY as a+constraint.++AUTHORISED DEVIATION -- READ BEFORE RUNNING. img2threejs's normal rule is no baseline textures/maps+copied into the procedural factory; this script exists only because that rule was explicitly lifted,+once, for girl-character's own build, as a deliberate experiment. It is packaged here as an opt-in+escape hatch, gated behind CHARACTER_ALLOW_BASELINE_UV=1, precisely so it is never the default path a+new character falls into by just following the pipeline: it refuses to run without that env var+explicitly set, on purpose, every time. The default path for a new character is per-region procedural+material colour, which needs no UV at all -- reach for this only with the same kind of explicit,+one-off authorisation girl-character's build had.++WHY PURE NEAREST-NEIGHBOUR FAILS. A UV is transferred per POINT, from whichever baseline vertex happens+to be closest. A baseline atlas packs many small islands, and within a couple of mm of any ring point+there are usually SEVERAL vertices belonging to DIFFERENT islands. Nearest-neighbour picks among them+by distance alone, so neighbouring ring points can land on unrelated parts of the map. Measured on+girl-character's first attempt: 3.15% of spoke-wise edges and 40.59% of ring-wise edges jumped more+than 0.02 in UV, and 21.16% of triangles needed repair (36370 of 171904) -- one in five collapsed to a+flat colour, producing visible dark slabs and streaking.++THE FIX. Among the candidates that are geometrically acceptable, choose the one whose UV best CONTINUES+its neighbours, rather than the one a hair closer. Acceptability is deliberately tight -- a candidate+may be at most `SLACK` further than the true nearest -- so continuity never buys itself geometric+error. Rings are walked bottom to top and spokes in order, so each point has a settled neighbour below+it and beside it to continue from.++MEASURED, THEN LEFT OFF: on girl-character, scoring candidates by continuity changed the pick for 94.6%+of points, made the ring-wise seam rate barely move (40.59% -> 40.01%), and made median transfer+distance 50% WORSE. The seams are where the surface crosses a genuine cut in the baseline's own UV+layout, not an ambiguity in picking a vertex, so no selection rule removes them -- nearest wins on+accuracy and loses nothing. This script keeps that negative result rather than re-deriving it.++Usage: CHARACTER_ALLOW_BASELINE_UV=1 python3 bake_atlas_uvs.py [glb]+(CHARACTER_GLB, CHARACTER_SECTION_REGIONS_JSON, CHARACTER_CROSS_SECTIONS same as build_cross_sections.py.)+"""+from __future__ import annotations++import array+import json+import os+import re+import struct+import sys+from pathlib import Path++import numpy as np++ROOT = Path(os.environ.get('IMG2THREEJS_SHOWCASE_ROOT', '.')).resolve()+# A candidate may sit this much further from the query than the nearest vertex does. 2 mm on a+# roughly life-size figure, chosen so the transfer stays inside the tolerance the first pass already+# achieved -- re-measure for a character at a very different scale.+SLACK = float(os.environ.get('CHARACTER_UV_SLACK', '0.002'))+++def read_node(handle, gltf, base, node):+ prim = gltf["meshes"][gltf["nodes"][node]["mesh"]]["primitives"][0]++ def acc(index):+ a = gltf["accessors"][index]+ v = gltf["bufferViews"][a["bufferView"]]+ handle.seek(base + v.get("byteOffset", 0) + a.get("byteOffset", 0))+ kinds = {5126: ("f", 4), 5125: ("I", 4), 5123: ("H", 2), 5121: ("B", 1)}+ code, size = kinds[a["componentType"]]+ per = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4}[a["type"]]+ out = array.array(code)+ out.frombytes(handle.read(a["count"] * per * size))+ return np.array(out, dtype=np.float64).reshape(a["count"], per)++ return acc(prim["attributes"]["POSITION"]), acc(prim["attributes"]["TEXCOORD_0"])+++class Grid:+ """Uniform-grid neighbourhood query. Returns every candidate, not just the closest."""++ def __init__(self, points: np.ndarray, cell: float):+ self.points = points+ self.cell = cell+ self.buckets: dict[tuple[int, int, int], list[int]] = {}+ for i, key in enumerate(map(tuple, np.floor(points / cell).astype(np.int64))):+ self.buckets.setdefault(key, []).append(i)++ def candidates(self, q: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ home = np.floor(q / self.cell).astype(np.int64)+ for radius in range(0, 24):+ found: list[int] = []+ for dx in range(-radius, radius + 1):+ for dy in range(-radius, radius + 1):+ for dz in range(-radius, radius + 1):+ if radius and max(abs(dx), abs(dy), abs(dz)) != radius:+ continue+ found += self.buckets.get(+ (home[0] + dx, home[1] + dy, home[2] + dz), ())+ if found:+ # One more shell, so a candidate just outside the first hit is still considered.+ extra: list[int] = []+ r2 = radius + 1+ for dx in range(-r2, r2 + 1):+ for dy in range(-r2, r2 + 1):+ for dz in range(-r2, r2 + 1):+ if max(abs(dx), abs(dy), abs(dz)) != r2:+ continue+ extra += self.buckets.get(+ (home[0] + dx, home[1] + dy, home[2] + dz), ())+ idx = np.array(found + extra, dtype=np.int64)+ return idx, np.linalg.norm(self.points[idx] - q, axis=1)+ d = np.linalg.norm(self.points - q, axis=1) # exhaustive; never a miss+ return np.arange(len(self.points)), d+++def main() -> int:+ if os.environ.get('CHARACTER_ALLOW_BASELINE_UV') != '1':+ print("Refusing to run: CHARACTER_ALLOW_BASELINE_UV=1 is not set.\n"+ "This transfers a baseline GLB's own texture UVs onto the procedural mesh, which departs "+ "from img2threejs's normal no-baseline-assets rule. Set the env var explicitly if you "+ "have the same kind of one-off authorisation girl-character's build had -- see this "+ "script's own module docstring first.", file=sys.stderr)+ return 1++ glb = Path(sys.argv[1] if len(sys.argv) > 1+ else os.environ.get('CHARACTER_GLB', str(ROOT / 'public/mesh/girl-character-baseline.glb')))+ sections = Path(os.environ.get('CHARACTER_CROSS_SECTIONS', str(ROOT / 'work/crossSections.ts')))+ regions_path = os.environ.get('CHARACTER_SECTION_REGIONS_JSON')+ if not regions_path:+ print("CHARACTER_SECTION_REGIONS_JSON must be set (same file build_cross_sections.py used).",+ file=sys.stderr)+ return 1+ node_region: dict[int, str] = {int(k): v for k, v in+ json.loads(Path(regions_path).read_text()).items()}+ region_nodes: dict[str, list[int]] = {}+ for node, region in sorted(node_region.items()):+ region_nodes.setdefault(region, []).append(node)++ text = sections.read_text()++ with glb.open("rb") as handle:+ struct.unpack("<III", handle.read(12))+ json_length, _ = struct.unpack("<II", handle.read(8))+ gltf = json.loads(handle.read(json_length))+ struct.unpack("<II", handle.read(8))+ base = handle.tell()+ clouds = {node: read_node(handle, gltf, base, node)+ for nodes in region_nodes.values() for node in nodes}++ grids = {}+ for node, (pos, _) in clouds.items():+ span = float(np.linalg.norm(pos.max(axis=0) - pos.min(axis=0)))+ grids[node] = Grid(pos, max(span / 120, 1e-4))++ # Parse every ring first: continuity needs the ring BELOW, so nothing can be done line by line.+ parsed = []+ for number, line in enumerate(text.splitlines()):+ if not line.lstrip().startswith("{ node:"):+ parsed.append((number, line, None))+ continue+ node = int(re.search(r"node: (\d+)", line).group(1))+ y = float(re.search(r"y: (-?[\d.]+)", line).group(1))+ pts = [(float(a), float(b)) for a, b in+ re.findall(r"\[(-?[\d.]+),(-?[\d.]+)\]", line.split("points: [")[1])]+ parsed.append((number, line, {"node": node, "y": y, "points": pts}))++ rings = [p[2] for p in parsed if p[2]]+ order = sorted(range(len(rings)), key=lambda i: (rings[i]["node"], rings[i]["y"]))+ previous: dict[tuple[int, int], np.ndarray] = {} # (node, spoke) -> settled UV+ distances: dict[int, list[float]] = {}+ switched = 0+ total = 0++ for i in order:+ ring = rings[i]+ node = ring["node"]+ pos, uv = clouds[node]+ grid = grids[node]+ assigned: list[np.ndarray] = []+ for k, (x, z) in enumerate(ring["points"]):+ q = np.array([x, ring["y"], z], dtype=np.float64)+ idx, dist = grid.candidates(q)+ nearest = float(dist.min())+ ok = idx[dist <= nearest + SLACK]+ total += 1+ # Reference UVs: the same spoke on the ring below, and the previous spoke on this ring.+ refs = [r for r in (previous.get((node, k)),+ assigned[k - 1] if k else None) if r is not None]+ # CONTINUITY IS NOT APPLIED, and the reason is measured rather than assumed -- see the+ # module docstring's "MEASURED, THEN LEFT OFF" note. Kept as a no-op branch rather than+ # deleted, so the negative result stays visible at the point it was tested.+ choice = int(idx[int(np.argmin(dist))])+ if refs and len(ok) > 1:+ pass+ assigned.append(uv[choice])+ distances.setdefault(node, []).append(+ float(np.linalg.norm(pos[choice] - q)))+ for k, value in enumerate(assigned):+ previous[(node, k)] = value+ ring["uv"] = assigned++ out_lines = []+ for _, line, ring in parsed:+ if ring is None:+ out_lines.append(line)+ continue+ packed = ",".join(f"[{u:.5f},{v:.5f}]" for u, v in ring["uv"])+ # Replaces this script's own earlier `uv: []` (written by build_cross_sections.py) rather than+ # appending a second `uv:` key.+ out_lines.append(re.sub(r"uv: \[[^\]]*\] \},$", f"uv: [{packed}] }},", line.rstrip()))+ sections.write_text("\n".join(out_lines) + "\n")++ print(f"continuity chose a different vertex for {switched} of {total} points "+ f"({switched/total:.1%})\n")+ print(f"{'node':>5}{'points':>9}{'median dist':>14}{'p95':>10}{'max':>10} (world units)")+ for node, ds in sorted(distances.items()):+ a = np.array(ds)+ print(f"{node:>5}{len(a):9d}{np.median(a):14.5f}{np.percentile(a,95):10.5f}{a.max():10.5f}")++ # Seam rates, both directions, so the claim is not made on one axis again.+ by_node: dict[int, list[tuple[float, np.ndarray]]] = {}+ spoke_bad = spoke_all = ring_bad = ring_all = 0+ for ring in rings:+ u = np.array(ring["uv"])+ d = np.linalg.norm(np.diff(np.vstack([u, u[:1]]), axis=0), axis=1)+ spoke_bad += int((d > 0.02).sum())+ spoke_all += len(d)+ by_node.setdefault(ring["node"], []).append((ring["y"], u))+ for node, rs in by_node.items():+ rs.sort(key=lambda t: t[0])+ for a, b in zip(rs, rs[1:]):+ if a[1].shape != b[1].shape:+ continue+ d = np.linalg.norm(a[1] - b[1], axis=1)+ ring_bad += int((d > 0.02).sum())+ ring_all += len(d)+ print(f"\nseam edges after continuity:")+ print(f" spoke-wise {spoke_bad:6d} of {spoke_all:6d} = {spoke_bad/spoke_all:6.2%}")+ print(f" ring-wise {ring_bad:6d} of {ring_all:6d} = {ring_bad/ring_all:6.2%}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/integrations/glb_character_pipeline/python/build_cross_sections.py b/integrations/glb_character_pipeline/python/build_cross_sections.pynew file mode 100644index 0000000..e3f0f40--- /dev/null+++ b/integrations/glb_character_pipeline/python/build_cross_sections.py@@ -0,0 +1,208 @@+"""Regenerate a character's crossSections.ts at a MEASURED per-node spoke budget (PIPELINE.md Stage 1).++WHY THIS SCRIPT EXISTS AT ALL. A hand-authored cross-sections file has no recorded density, so a+question like "is the triangle count too low" is unanswerable -- nothing can be re-run at a different+density to see whether the gap matters. It is a generator, not an artifact, on purpose.++ADAPTED FOR img2threejs (opt-in integration): this script's own location is no longer the showcase repo+root -- it lives in integrations/glb_character_pipeline/python/ inside the img2threejs tool repo. Every+showcase-side path resolves against IMG2THREEJS_SHOWCASE_ROOT, and every character-specific input --+which GLB, which node belongs to which region, and the final spoke count per node -- comes from+CHARACTER_* env vars / JSON config files, never hardcoded here, so the same script serves every+character.++THE BUDGET IS MEASURED, NOT CHOSEN, AND THIS SCRIPT DOES NOT MEASURE IT FOR YOU. Run+measure_density_convergence.py against each node first, read its printed convergence/density tables,+and decide the final per-node spoke count by hand: min(convergence, density), raised only where a+material-patch boundary genuinely needs finer cutting (a patch can only be cut along the (ring, spoke)+lattice). Put the RESULT of that judgment in CHARACTER_SPOKES_JSON as a plain {"<node>": <spokes>} map.+"Measured, not assumed" means a human/agent reads the actual error numbers for THIS character's own+GLB -- reusing another character's numbers, or a formula that skips reading them, is exactly the+mistake this script exists to prevent. See PIPELINE.md Stage 1 for the two failure modes measured on+girl-character (spokes under-sampled at low counts; naively maximising spokes bulges nodes whose point+density can't support them).++SLICES = 40 is carried over as a starting default from girl-character's own measurement (error against+a 320-slice-thin reference is U-shaped: worse at both 20 and 160 slices, best near 40, because a+thinner band holds fewer points and its per-bin percentile turns to sampling noise). Re-measure it with+measure_density_convergence.py for a new character if its proportions differ enough that this might not+hold; override via CHARACTER_SLICES.++UV IS LEFT EMPTY HERE ON PURPOSE. Populating real UVs from a baseline GLB's own texture atlas is a+separate, explicitly-gated step (bake_atlas_uvs.py) that departs from img2threejs's normal no-baseline-+assets rule -- see that script's own docstring before reaching for it. The default path for a new+character is per-region procedural material colour, which needs no UV at all.+"""+from __future__ import annotations++import json+import os+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from slice_node import read_node_positions, slice_node # noqa: E402++ROOT = Path(os.environ.get('IMG2THREEJS_SHOWCASE_ROOT', '.')).resolve()+SLICES = int(os.environ.get('CHARACTER_SLICES', '40'))++HEADER_TEMPLATE = '''/**+ * Horizontal cross-sections of every measured GLB node, as stacked rings in world space.+ *+ * Rings are radial outlines of the node's actual point cloud, one per cluster per height band,+ * resampled onto a fixed set of rays from each slice's centroid so ring i point k always joins ring+ * i+1 point k and the lofted walls come out untwisted. Per-node spoke count is MEASURED, not shared+ * globally -- see measure_density_convergence.py and PIPELINE.md Stage 1.+ *+ * `uv` is intentionally empty ([]) unless a separate, explicitly-gated bake_atlas_uvs.py pass filled+ * it in from a baseline GLB's own texture atlas -- see that script's own docstring before reaching for+ * it; the default path needs no UV at all.+ *+ * Generated by build_cross_sections.py (integrations/glb_character_pipeline/python/); regenerate+ * rather than edit by hand.+ */++/**+ * `node` is load-bearing, not provenance. A region can span several GLB nodes, and rings from+ * different nodes must never be lofted into one another.+ */+export type Ring = {+ readonly node: number;+ readonly y: number;+ readonly centroid: readonly [number, number];+ readonly points: readonly (readonly [number, number])[];+ readonly uv: readonly (readonly [number, number])[];+};+export type CrossSections = readonly Ring[];+'''+++def region_rings(nodes: list[int], glb: Path, spokes: dict[int, int]) -> list[dict]:+ rings = []+ for node in nodes:+ data = slice_node(glb, node, SLICES, spokes[node])+ for ring in data["rings"]:+ rings.append({"node": node, **ring})+ # Canonical order is load-bearing, not tidiness: the loft chains each ring onto the nearest strand+ # tip below it in ARRIVAL order, so an unspecified emission order can change the mesh with no+ # geometry changing. Sorting by height, then centroid, makes the input deterministic.+ rings.sort(key=lambda r: (r["y"], r["node"], r["centroid"][0], r["centroid"][1]))+ return rings+++def emit(rings: list[dict]) -> str:+ lines = []+ for r in rings:+ pts = ",".join(f"[{x},{z}]" for x, z in r["points"])+ lines.append(f' {{ node: {r["node"]}, y: {r["y"]}, '+ f'centroid: [{r["centroid"][0]}, {r["centroid"][1]}], points: [{pts}], uv: [] }},')+ return "\n".join(lines)+++def bboxes(path: Path) -> dict[str, tuple]:+ """Region bounding boxes in x/z, parsed back out of the emitted numbers."""+ import re+ out, region = {}, None+ for line in path.read_text().splitlines():+ if line.startswith("export const "):+ region = line.split()[2].rstrip(":")+ out[region] = [1e9, -1e9, 1e9, -1e9]+ elif region and line.lstrip().startswith("{ node:"):+ for x, z in re.findall(r"\[(-?[\d.]+),\s*(-?[\d.]+)\]", line.split("points: [")[1]):+ x, z, b = float(x), float(z), out[region]+ b[0], b[1] = min(b[0], x), max(b[1], x)+ b[2], b[3] = min(b[2], z), max(b[3], z)+ return {k: tuple(v) for k, v in out.items()}+++def cloud_bboxes(region_nodes: dict[str, list[int]], glb: Path) -> dict[str, tuple]:+ """The same boxes taken from the GLB's own vertices -- the only ground truth available."""+ out = {}+ for region, nodes in region_nodes.items():+ x0 = z0 = 1e9+ x1 = z1 = -1e9+ for node in nodes:+ positions, _ = read_node_positions(glb, node)+ xs, zs = positions[0::3], positions[2::3]+ x0, x1 = min(x0, min(xs)), max(x1, max(xs))+ z0, z1 = min(z0, min(zs)), max(z1, max(zs))+ out[f"{region}_SECTIONS"] = (x0, x1, z0, z1)+ return out+++def verify_frozen(target: Path, glb: Path, previous: Path, region_nodes: dict[str, list[int]]) -> int:+ """Did raising the spoke count CHANGE the dimensions, or shrink the sampling error?++ Comparing the new file against the old one cannot answer that: the old file is the coarser+ measurement, not ground truth, and wide angular bins are SUPPOSED to cut the corners off an+ extremity. The vertices are the authority. A freeze holds when every region's box sits closer to+ the point cloud than it did before, and overshoot past the cloud stays small.+ """+ truth, before, after = cloud_bboxes(region_nodes, glb), bboxes(previous), bboxes(target)+ failed = []+ print(f"{'region':20s}{'was':>10}{'now':>10}{'overshoot':>12}")+ for region, t in truth.items():+ b, a = before[region], after[region]+ eb = sum(abs(p - q) for p, q in zip(b, t)) / 4 * 1000+ ea = sum(abs(p - q) for p, q in zip(a, t)) / 4 * 1000+ over = max(a[1] - t[1], t[0] - a[0], a[3] - t[3], t[2] - a[2]) * 1000+ note = ""+ if ea > eb:+ note, _ = " FAIL: further from the cloud", failed.append(+ f"{region}: bbox error rose {eb:.2f} -> {ea:.2f} mm")+ elif over > 5.0:+ note = " overshoots the cloud"+ print(f"{region:20s}{eb:7.2f} mm{ea:7.2f} mm{over:+9.2f} mm{note}")+ if failed:+ print("\nFROZEN-DIMENSION CHECK FAILED:\n " + "\n ".join(failed))+ return 1+ print("\nFrozen dimensions hold: every region sits closer to its own point cloud than before, so "+ "the boxes grew toward the surface rather than being resized.")+ return 0+++def main() -> int:+ glb = Path(os.environ.get('CHARACTER_GLB', str(ROOT / 'public/mesh/girl-character-baseline.glb')))+ target = Path(os.environ.get('CHARACTER_CROSS_SECTIONS', str(ROOT / 'work/crossSections.ts')))++ regions_path = os.environ.get('CHARACTER_SECTION_REGIONS_JSON')+ spokes_path = os.environ.get('CHARACTER_SPOKES_JSON')+ if not regions_path or not spokes_path:+ print("CHARACTER_SECTION_REGIONS_JSON and CHARACTER_SPOKES_JSON must both be set -- see PIPELINE.md "+ "Stage 1 and configs/example.env. Neither is auto-derived; both are a measured, "+ "per-character decision.", file=sys.stderr)+ return 1++ node_region: dict[int, str] = {int(k): v for k, v in+ json.loads(Path(regions_path).read_text()).items()}+ spokes: dict[int, int] = {int(k): v for k, v in json.loads(Path(spokes_path).read_text()).items()}+ region_nodes: dict[str, list[int]] = {}+ for node, region in sorted(node_region.items()):+ region_nodes.setdefault(region, []).append(node)++ if "--verify-frozen" in sys.argv:+ return verify_frozen(target, glb, Path(sys.argv[sys.argv.index("--verify-frozen") + 1]),+ region_nodes)++ body = [HEADER_TEMPLATE]+ total_rings = total_points = 0+ for region, nodes in region_nodes.items():+ rings = region_rings(nodes, glb, spokes)+ points = sum(len(r["points"]) for r in rings)+ total_rings += len(rings)+ total_points += points+ spoke_note = ", ".join(f"node {n} at {spokes[n]}" for n in nodes)+ body.append(f"\n/**\n * {len(rings)} rings, {points} ring points, from node(s) "+ f"{nodes}.\n * Spokes: {spoke_note}.\n */\n"+ f"export const {region}_SECTIONS: CrossSections = [\n{emit(rings)}\n];")+ print(f" {region:12s} {len(rings):4d} rings {points:7d} points ({spoke_note})")++ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text("\n".join(body) + "\n")+ size = target.stat().st_size+ print(f"\n{total_rings} rings, {total_points} ring points, {size / 1e6:.2f} MB -> {target}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/integrations/glb_character_pipeline/python/build_head_surface.py b/integrations/glb_character_pipeline/python/build_head_surface.pynew file mode 100644index 0000000..7897c42--- /dev/null+++ b/integrations/glb_character_pipeline/python/build_head_surface.py@@ -0,0 +1,166 @@+"""Rebuild the head as an implicit surface, then contour it with Surface Nets.++WHY NOT CROSS-SECTIONS. A radial outline stores ONE radius per angular bin, and an eyelid is several+surfaces at one azimuth, so the face is unrecoverable at any triangle count -- 2.97 M left the head an+egg. That the face IS geometry was proven by rendering baseline node 9 with map, normalMap and+roughnessMap all null: eyelids, brow ridges, nostrils, a philtrum.++WHY SURFACE NETS AND NOT MARCHING CUBES. Only numpy and PIL are available here. Marching cubes needs a+256-case table that is easy to get subtly wrong; Surface Nets emits one vertex per sign-changing cell+and one quad per sign-changing grid edge, which is a few dozen lines and cannot be half-right.++The field is the signed distance to the point cloud's local tangent planes, splatted: every vertex+contributes dot(cell - p, n_p) to the cells within RADIUS, weighted by a smooth falloff. Using the GLB's+own NORMAL attribute is what makes this reliable -- unoriented reconstruction has to guess inside from+outside, and oriented does not.+"""+from __future__ import annotations+import json, os, struct, sys+from pathlib import Path+import numpy as np++# ADAPTED FOR img2threejs (opt-in integration): this script's own location is no longer the+# showcase repo root -- it lives in integrations/glb_character_pipeline/python/ inside the+# img2threejs tool repo. Every showcase-side default path is resolved against+# IMG2THREEJS_SHOWCASE_ROOT instead (the same env var forge/tests already uses to reach a+# companion showcase checkout), falling back to the current directory only if unset.+ROOT = Path(os.environ.get('IMG2THREEJS_SHOWCASE_ROOT', '.')).resolve()+NODE = int(sys.argv[1]) if len(sys.argv) > 1 else 9+CELL = float(sys.argv[2]) if len(sys.argv) > 2 else 0.0012+RADIUS = CELL * 2.5+PAD = RADIUS * 2++# PACKAGED (v1.5.1). GLB path and output directory are overridable so a second character can be built in+# the same checkout without colliding with girl-character's own artifacts. export_sdf_surfaces.py passes+# these through as env vars when it calls this script as a subprocess.+GLB_PATH = Path(os.environ.get('CHARACTER_GLB', str(ROOT / 'public/mesh/girl-character-baseline.glb')))+OUT_DIR = Path(os.environ.get('CHARACTER_WORKDIR', str(ROOT / 'work/head')))+OUT_DIR.mkdir(parents=True, exist_ok=True)++raw = GLB_PATH.read_bytes()+off, chunks = 12, {}+while off < len(raw):+ ln, ty = struct.unpack_from('<II', raw, off); chunks[ty] = raw[off+8:off+8+ln]; off += 8+ln+ off = off if off % 4 == 0 else off + (4 - off % 4)+g = json.loads(chunks[0x4E4F534A].decode()); BIN = chunks[0x004E4942]+def acc(i):+ a=g['accessors'][i]; bv=g['bufferViews'][a['bufferView']]+ dt={5120:'i1',5121:'u1',5122:'i2',5123:'u2',5125:'u4',5126:'f4'}[a['componentType']]+ nc={'SCALAR':1,'VEC2':2,'VEC3':3,'VEC4':4}[a['type']]+ o=bv.get('byteOffset',0)+a.get('byteOffset',0)+ return np.frombuffer(BIN,dtype=np.dtype('<'+dt),count=a['count']*nc,offset=o).reshape(a['count'],nc)+prims = g['meshes'][g['nodes'][NODE]['mesh']]['primitives']+P = np.concatenate([acc(p['attributes']['POSITION']) for p in prims]).astype(np.float64)+N = np.concatenate([acc(p['attributes']['NORMAL']) for p in prims]).astype(np.float64)+N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-12)+print(f"node {NODE}: {len(P):,} vertices, cell {CELL*1000:.2f} mm")++lo = P.min(axis=0) - PAD+hi = P.max(axis=0) + PAD+dims = np.ceil((hi - lo) / CELL).astype(int) + 1+print(f" grid {dims[0]}x{dims[1]}x{dims[2]} = {np.prod(dims)/1e6:.1f} M cells")++sum_w = np.zeros(dims, dtype=np.float32)+sum_f = np.zeros(dims, dtype=np.float32)+K = int(np.ceil(RADIUS / CELL))+oc = np.arange(-K, K+1)+ox, oy, oz = np.meshgrid(oc, oc, oc, indexing='ij')+ox, oy, oz = ox.ravel(), oy.ravel(), oz.ravel()+base = np.floor((P - lo) / CELL).astype(np.int32)+CH = 4000+for s in range(0, len(P), CH):+ b = base[s:s+CH]; p = P[s:s+CH]; n = N[s:s+CH]+ ix = (b[:, None, 0] + ox[None, :]).ravel()+ iy = (b[:, None, 1] + oy[None, :]).ravel()+ iz = (b[:, None, 2] + oz[None, :]).ravel()+ ok = (ix >= 0) & (ix < dims[0]) & (iy >= 0) & (iy < dims[1]) & (iz >= 0) & (iz < dims[2])+ pid = np.repeat(np.arange(len(b)), len(ox))+ ix, iy, iz, pid = ix[ok], iy[ok], iz[ok], pid[ok]+ cx = lo[0] + ix*CELL; cy = lo[1] + iy*CELL; cz = lo[2] + iz*CELL+ dx = cx - p[pid, 0]; dy = cy - p[pid, 1]; dz = cz - p[pid, 2]+ d2 = dx*dx + dy*dy + dz*dz+ keep = d2 <= RADIUS*RADIUS+ ix, iy, iz, pid = ix[keep], iy[keep], iz[keep], pid[keep]+ dx, dy, dz, d2 = dx[keep], dy[keep], dz[keep], d2[keep]+ w = (1.0 - d2/(RADIUS*RADIUS))**2+ f = dx*n[pid,0] + dy*n[pid,1] + dz*n[pid,2]+ np.add.at(sum_w, (ix, iy, iz), w.astype(np.float32))+ np.add.at(sum_f, (ix, iy, iz), (w*f).astype(np.float32))+covered = sum_w > 1e-6+print(f" cells with support: {covered.sum()/1e6:.2f} M ({covered.mean():.1%})")+# Outside the support the field must be POSITIVE, or the contour closes around empty space.+F = np.full(dims, RADIUS, dtype=np.float32)+F[covered] = sum_f[covered] / sum_w[covered]+del sum_w, sum_f++# ---- Surface Nets -------------------------------------------------------------------------------+sgn = F > 0+# a cell (i,j,k) owns the cube spanning i..i+1 in each axis+c000 = sgn[:-1,:-1,:-1]; c100 = sgn[1:,:-1,:-1]; c010 = sgn[:-1,1:,:-1]; c001 = sgn[:-1,:-1,1:]+c110 = sgn[1:,1:,:-1]; c101 = sgn[1:,:-1,1:]; c011 = sgn[:-1,1:,1:]; c111 = sgn[1:,1:,1:]+allsame = (c000==c100)&(c000==c010)&(c000==c001)&(c000==c110)&(c000==c101)&(c000==c011)&(c000==c111)+active = ~allsame+print(f" active cells: {active.sum():,}")+ai, aj, ak = np.nonzero(active)+vid = -np.ones(np.array(dims)-1, dtype=np.int64)+vid[ai, aj, ak] = np.arange(len(ai))+# vertex position: average of zero crossings on the cube's 12 edges+acc_p = np.zeros((len(ai), 3)); acc_n = np.zeros(len(ai))+EDGES = [((0,0,0),(1,0,0)),((0,1,0),(1,1,0)),((0,0,1),(1,0,1)),((0,1,1),(1,1,1)),+ ((0,0,0),(0,1,0)),((1,0,0),(1,1,0)),((0,0,1),(0,1,1)),((1,0,1),(1,1,1)),+ ((0,0,0),(0,0,1)),((1,0,0),(1,0,1)),((0,1,0),(0,1,1)),((1,1,0),(1,1,1))]+for (a0,b0,c0),(a1,b1,c1) in EDGES:+ f0 = F[ai+a0, aj+b0, ak+c0]; f1 = F[ai+a1, aj+b1, ak+c1]+ cross = (f0 > 0) != (f1 > 0)+ if not cross.any(): continue+ t = np.zeros(len(ai)); den = (f0 - f1)+ with np.errstate(divide='ignore', invalid='ignore'):+ t = np.where(np.abs(den) > 1e-12, f0/den, 0.5)+ t = np.clip(t, 0.0, 1.0)+ px = (a0 + t*(a1-a0)); py = (b0 + t*(b1-b0)); pz = (c0 + t*(c1-c0))+ acc_p[cross] += np.stack([px[cross], py[cross], pz[cross]], axis=1)+ acc_n[cross] += 1+acc_n = np.maximum(acc_n, 1)+# Keep every vertex strictly inside the active cell that owns it. A zero crossing can average to an+# exact face/corner; float32 then floors it into the neighbouring cell and breaks the one-cell/one-+# vertex invariant the compact encoder verifies. The guard is one quarter of the encoder's own 8-bit+# in-cell quantisation step, so the largest correction is < cell/1020 (1.47 um at a 1.5 mm cell) and+# remains below the already-declared encoding precision.+fraction = acc_p / acc_n[:, None]+cell_guard = 1.0 / (255.0 * 4.0)+fraction = np.clip(fraction, cell_guard, 1.0 - cell_guard)+V = lo + (np.stack([ai, aj, ak], axis=1) + fraction) * CELL+# quads: one per sign-changing grid edge whose 4 surrounding cells are all active+# one quad per sign-changing grid edge, per axis+out = []+for axis in range(3):+ sl0 = [slice(1, dims[d]-1) if d == axis else slice(1, dims[d]) for d in range(3)]+ sl1 = list(sl0); sl1[axis] = slice(2, dims[axis])+ a = sgn[tuple(sl0)]; b = sgn[tuple(sl1)]+ ch = a != b+ if not ch.any(): continue+ idx = np.nonzero(ch)+ i = idx[0] + 1; j = idx[1] + 1; k = idx[2] + 1+ o = [(0,0,0)]*4+ if axis == 0: o = [(0,-1,-1),(0,0,-1),(0,0,0),(0,-1,0)]+ if axis == 1: o = [(-1,0,-1),(-1,0,0),(0,0,0),(0,0,-1)]+ if axis == 2: o = [(-1,-1,0),(0,-1,0),(0,0,0),(-1,0,0)]+ corner = []+ good = np.ones(len(i), dtype=bool)+ for (di,dj,dk) in o:+ ii, jj, kk = i+di, j+dj, k+dk+ inb = (ii>=0)&(ii<vid.shape[0])&(jj>=0)&(jj<vid.shape[1])&(kk>=0)&(kk<vid.shape[2])+ c = np.where(inb, vid[np.clip(ii,0,vid.shape[0]-1), np.clip(jj,0,vid.shape[1]-1), np.clip(kk,0,vid.shape[2]-1)], -1)+ good &= inb & (c >= 0)+ corner.append(c)+ q = np.stack([c[good] for c in corner], axis=1)+ flip = a[idx][good]+ q = np.where(flip[:,None], q[:, ::-1], q)+ out.append(q)+Q = np.concatenate(out) if out else np.zeros((0,4), dtype=np.int64)+T = np.concatenate([Q[:, [0,1,2]], Q[:, [0,2,3]]])+print(f" surface: {len(V):,} vertices, {len(T):,} triangles")+np.save(OUT_DIR / 'V.npy', V.astype(np.float32))+np.save(OUT_DIR / 'T.npy', T.astype(np.int32))+np.save(OUT_DIR / 'cloud.npy', P.astype(np.float32))+print(f' wrote {OUT_DIR}/{{V,T,cloud}}.npy')diff --git a/integrations/glb_character_pipeline/python/export_sdf_surfaces.py b/integrations/glb_character_pipeline/python/export_sdf_surfaces.pynew file mode 100644index 0000000..6dc97df--- /dev/null+++ b/integrations/glb_character_pipeline/python/export_sdf_surfaces.py@@ -0,0 +1,260 @@+"""Pack one or more Surface Nets node surfaces into a single binary the demo fetches.++Supersedes export_head_surface.py, which handled node 9 alone. Same construction throughout: a signed+distance field splatted from the node's own point cloud using the GLB's NORMAL attribute, contoured by+Surface Nets, coloured per vertex from the GLB diffuse (mean of the four nearest source vertices,+decoded sRGB -> linear because three.js treats a colour attribute as already being in the working+space). No UVs, so no UV seams.++WHY THIS EXISTS FOR MORE THAN THE HEAD. Five regions never moved across an entire pass of filtering and+material work -- pouches, boots, knee-pads, katana, canister -- and all five sit 1.3-1.8x the baseline's+surface noise. US-001 established that the residual is a SMOOTH error in the radial estimator, not+noise: a notch filter with zero gain at the ring frequency removed 100% of that component and moved the+figure by 6.8%. The head then showed what replacing the estimator is worth -- 17.40 -> 9.65, below the+baseline's own 11.76, with IoU 0.995.++Layout, little-endian:+ magic 'HEDS' u32 version(3) u32 jsonLength+ json bytes, padded to a 4-byte boundary+ then, per entry in json order: f32 position[3n], f32 normal[3n], u8 colour[3n] padded, u32 index[m]+"""+from __future__ import annotations+import json, os, struct, subprocess, sys+from collections import defaultdict+from io import BytesIO+from pathlib import Path+import numpy as np+from PIL import Image+Image.MAX_IMAGE_PIXELS = None++# ADAPTED FOR img2threejs (opt-in integration): this script's own location is no longer the+# showcase repo root -- it lives in integrations/glb_character_pipeline/python/ inside the+# img2threejs tool repo. Every showcase-side default path is resolved against+# IMG2THREEJS_SHOWCASE_ROOT instead (the same env var forge/tests already uses to reach a+# companion showcase checkout), falling back to the current directory only if unset.+ROOT = Path(os.environ.get('IMG2THREEJS_SHOWCASE_ROOT', '.')).resolve()++# PACKAGED (v1.5.1). Everything a new character has to supply is read from environment variables, with+# girl-character's own values as the default so this script reproduces the existing build unchanged when+# none are set. build-character.sh sets all of these from a per-character .env config file; see+# configs/example.env for what a new reference needs.+#+# CHARACTER_GLB path to the baseline GLB+# CHARACTER_DIFFUSE path to the extracted diffuse texture (run extract_glb_images.py first, or+# point this at whatever PNG holds the node's colour bake)+# CHARACTER_REGIONS_JSON path to a JSON object mapping node index (string) -> region label, e.g.+# {"0": "torso", "9": "head"}. A node missing from this map falls back to+# "region<N>" rather than crashing, so an incomplete map degrades gracefully.+# CHARACTER_OUT_PREFIX output .bin path prefix (default public/head/sdf-surfaces)+# CHARACTER_WORKDIR passed through to build_head_surface.py (default work/head)+GLB_PATH = Path(os.environ.get('CHARACTER_GLB', str(ROOT / 'public/mesh/girl-character-baseline.glb')))+_diffuse_value = os.environ.get('CHARACTER_DIFFUSE', str(ROOT / 'work/baseline-textures/01-texture_diffuse.png'))+EMBEDDED_MATERIALS = _diffuse_value.lower() in {'embedded', 'glb'}+DIFFUSE_PATH = None if _diffuse_value.lower() in {'none', 'neutral', '', 'embedded', 'glb'} else Path(_diffuse_value)+OUT_PREFIX = os.environ.get('CHARACTER_OUT_PREFIX', str(ROOT / 'public/head/sdf-surfaces'))+_regions_file = os.environ.get('CHARACTER_REGIONS_JSON')+if _regions_file:+ NODE_REGION = {int(k): v for k, v in json.loads(Path(_regions_file).read_text()).items()}+else:+ NODE_REGION = {0:'overalls',1:'skin',2:'boots',3:'skin',4:'boots',5:'pouches',6:'canister',7:'pouches',+ 8:'katana',9:'hair',10:'knee-pads',11:'boots',12:'knee-pads',13:'boots',14:'gloves',+ 15:'skin'}+# node -> cell size in metres. The head needs 1.5 mm because an eyelid's relief is 1.6 mm at an 8 mm+# scale; nothing else on the figure carries a feature that fine, and 2.0 mm keeps p95 near 1.17 mm.+# The head needs 1.5 mm because an eyelid's relief is 1.6 mm at an 8 mm scale. The trousers are the+# largest surface on the figure and carry nothing near that fine, so they take 2.5 mm to keep the file+# from doubling for no measured gain.+CELL = {9: 0.0015, 0: 0.0025}+DEFAULT_CELL = 0.0020+_cell_sizes_file = os.environ.get('CHARACTER_CELL_SIZES_JSON')+if _cell_sizes_file:+ CELL.update({int(k): float(v) for k, v in json.loads(Path(_cell_sizes_file).read_text()).items()})++raw = GLB_PATH.read_bytes()+off, chunks = 12, {}+while off < len(raw):+ ln, ty = struct.unpack_from('<II', raw, off); chunks[ty] = raw[off+8:off+8+ln]; off += 8+ln+ off = off if off % 4 == 0 else off + (4 - off % 4)+g = json.loads(chunks[0x4E4F534A].decode()); BIN = chunks[0x004E4942]+def acc(i):+ a=g['accessors'][i]; bv=g['bufferViews'][a['bufferView']]+ dt={5120:'i1',5121:'u1',5122:'i2',5123:'u2',5125:'u4',5126:'f4'}[a['componentType']]+ nc={'SCALAR':1,'VEC2':2,'VEC3':3,'VEC4':4}[a['type']]+ o=bv.get('byteOffset',0)+a.get('byteOffset',0)+ return np.frombuffer(BIN,dtype=np.dtype('<'+dt),count=a['count']*nc,offset=o).reshape(a['count'],nc)++_image_cache = {}+def embedded_image(image_index):+ cached = _image_cache.get(image_index)+ if cached is not None:+ return cached+ image = g['images'][image_index]+ view = g['bufferViews'][image['bufferView']]+ start = view.get('byteOffset', 0)+ data = BIN[start:start + view['byteLength']]+ decoded = np.asarray(Image.open(BytesIO(data)).convert('RGB'))+ _image_cache[image_index] = decoded+ return decoded++TEXTURE_SOURCE = [texture.get('source') for texture in g.get('textures', [])]++def sample_texture(texture_info, uv, fallback):+ if texture_info is None:+ return np.broadcast_to(np.asarray(fallback, dtype=np.float64), (len(uv), len(fallback))).copy()+ source = TEXTURE_SOURCE[texture_info['index']]+ image = embedded_image(source)+ height, width = image.shape[:2]+ x = np.clip((uv[:, 0] % 1.0 * width).astype(int), 0, width - 1)+ y = np.clip((uv[:, 1] % 1.0 * height).astype(int), 0, height - 1)+ return image[y, x].astype(np.float64)++if DIFFUSE_PATH is not None:+ diffuse = np.asarray(Image.open(DIFFUSE_PATH).convert('RGB'))+ TH, TW = diffuse.shape[:2]+else:+ diffuse = None+ TH = TW = 0++# Optional trailing "xN" argument scales every cell size, for measuring what triangle budget actually+# costs in fidelity rather than assuming it.+scale = 1.0+keep_head = False+argv = list(sys.argv[1:])+if argv and argv[-1] == 'keephead':+ keep_head = True+ argv.pop()+if argv and argv[-1].startswith('x'):+ scale = float(argv.pop()[1:])+nodes = [int(a) for a in argv] or [9]+entries, blocks = [], []+for node in nodes:+ # The head is exempt from coarsening. It is the only part whose detail the eye tracks -- the+ # measured comparison across detail levels shows the nose and eyes softening first, while boots,+ # trousers and armour hold up -- so scaling it with everything else spends the budget in the one+ # place it is worst spent.+ cell = CELL.get(node, DEFAULT_CELL) * (1.0 if node == 9 and keep_head else scale)+ workdir = Path(os.environ.get('CHARACTER_WORKDIR', str(ROOT / 'work/head')))+ subprocess.run([sys.executable, str(Path(__file__).resolve().parent / 'build_head_surface.py'),+ str(node), str(cell)],+ check=True, cwd=ROOT, stdout=subprocess.DEVNULL, env={**os.environ, 'CHARACTER_GLB': str(GLB_PATH)})+ V = np.load(workdir/'V.npy').astype(np.float64)+ T = np.load(workdir/'T.npy').astype(np.int64)+ prims = g['meshes'][g['nodes'][node]['mesh']]['primitives']+ P = np.concatenate([acc(p['attributes']['POSITION']) for p in prims]).astype(np.float64)+ material_info = None+ if EMBEDDED_MATERIALS:+ colours = []+ roughness = []+ metalness = []+ material_records = []+ for primitive in prims:+ uv = acc(primitive['attributes']['TEXCOORD_0']).astype(np.float64)+ material = g['materials'][primitive.get('material', 0)]+ pbr = material.get('pbrMetallicRoughness', {})+ base_factor = np.asarray(pbr.get('baseColorFactor', [1, 1, 1, 1])[:3], dtype=np.float64)+ base_srgb = sample_texture(pbr.get('baseColorTexture'), uv, [255, 255, 255]) / 255.0+ base_linear = np.where(base_srgb <= 0.04045, base_srgb / 12.92,+ ((base_srgb + 0.055) / 1.055) ** 2.4)+ colours.append(np.clip(base_linear * base_factor, 0, 1))++ mr = sample_texture(pbr.get('metallicRoughnessTexture'), uv, [255, 255, 255]) / 255.0+ roughness.append(np.clip(mr[:, 1] * float(pbr.get('roughnessFactor', 1)), 0, 1))+ metalness.append(np.clip(mr[:, 2] * float(pbr.get('metallicFactor', 1)), 0, 1))+ material_records.append({+ 'materialIndex': int(primitive.get('material', 0)),+ 'baseColorFactor': [float(value) for value in pbr.get('baseColorFactor', [1, 1, 1, 1])],+ 'metallicFactor': float(pbr.get('metallicFactor', 1)),+ 'roughnessFactor': float(pbr.get('roughnessFactor', 1)),+ 'doubleSided': bool(material.get('doubleSided', False)),+ 'alphaMode': material.get('alphaMode', 'OPAQUE'),+ 'alphaCutoff': float(material.get('alphaCutoff', 0.5)),+ 'emissiveFactor': [float(value) for value in material.get('emissiveFactor', [0, 0, 0])],+ 'normalScale': float(material.get('normalTexture', {}).get('scale', 1)),+ 'occlusionStrength': float(material.get('occlusionTexture', {}).get('strength', 1)),+ 'hasBaseColorTexture': 'baseColorTexture' in pbr,+ 'hasMetallicRoughnessTexture': 'metallicRoughnessTexture' in pbr,+ 'hasNormalTexture': 'normalTexture' in material,+ 'hasOcclusionTexture': 'occlusionTexture' in material,+ 'hasEmissiveTexture': 'emissiveTexture' in material,+ })+ source_colour = np.concatenate(colours)+ source_roughness = np.concatenate(roughness)+ source_metalness = np.concatenate(metalness)+ material_info = {+ **material_records[0],+ 'roughnessMedian': float(np.median(source_roughness)),+ 'roughnessP25': float(np.percentile(source_roughness, 25)),+ 'roughnessP75': float(np.percentile(source_roughness, 75)),+ 'metalnessMedian': float(np.median(source_metalness)),+ 'metalnessP25': float(np.percentile(source_metalness, 25)),+ 'metalnessP75': float(np.percentile(source_metalness, 75)),+ 'surfaceColourEncoding': 'linear RGB sampled from embedded baseColor texture',+ }+ elif diffuse is None:+ # Geometry-only mode for references whose materials/textures may be measured but not copied.+ # White vertex colour leaves the independently-authored Three.js material un-tinted.+ COL = np.full((len(V), 3), 255, dtype=np.uint8)+ else:+ UV = np.concatenate([acc(p['attributes']['TEXCOORD_0']) for p in prims]).astype(np.float64)+ source_srgb = diffuse[np.clip((UV[:,1] % 1.0 * TH).astype(int), 0, TH-1),+ np.clip((UV[:,0] % 1.0 * TW).astype(int), 0, TW-1)].astype(np.float64) / 255.0+ source_colour = np.where(source_srgb <= 0.04045, source_srgb / 12.92,+ ((source_srgb + 0.055) / 1.055) ** 2.4)+ if EMBEDDED_MATERIALS or diffuse is not None:+ hash_cell = 0.005+ lo = np.minimum(V.min(0), P.min(0)) - hash_cell+ buck = defaultdict(list)+ for i, key in enumerate(map(tuple, np.floor((P - lo)/hash_cell).astype(np.int64))):+ buck[key].append(i)+ vk = np.floor((V - lo)/hash_cell).astype(np.int64)+ linear = np.zeros((len(V), 3))+ for index in range(len(V)):+ key = tuple(vk[index]); candidates = []+ for dx in (-1,0,1):+ for dy in (-1,0,1):+ for dz in (-1,0,1):+ candidates += buck.get((key[0]+dx,key[1]+dy,key[2]+dz), [])+ if not candidates:+ continue+ candidates = np.asarray(candidates)+ nearest = candidates[np.argsort(np.linalg.norm(P[candidates]-V[index], axis=1))[:4]]+ linear[index] = source_colour[nearest].mean(axis=0)+ COL = np.clip(np.round(linear*255), 0, 255).astype(np.uint8)+ fn = np.cross(V[T[:,1]]-V[T[:,0]], V[T[:,2]]-V[T[:,0]])+ N = np.zeros_like(V)+ for c in range(3): np.add.at(N, T[:,c], fn)+ N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-12)+ # Keep the configured cell exactly enough to reproduce the builder's grid origin. Rounding a+ # measured 1.504 mm cell to 1.50 mm shifted the recovered grid and created 110,695 apparent cell+ # collisions on one node even though Surface Nets emits one vertex per active cell by construction.+ entry = {'node': node, 'region': NODE_REGION.get(node, f'region{node}'), 'cellMillimetres': round(cell*1000, 6),+ 'vertexCount': int(len(V)), 'indexCount': int(T.size)}+ if material_info is not None:+ entry['material'] = material_info+ entries.append(entry)+ body = bytearray()+ body += V.astype('<f4').tobytes()+ body += N.astype('<f4').tobytes()+ body += COL.tobytes()+ while len(body) % 4: body += b'\x00'+ body += T.ravel().astype('<u4').tobytes()+ blocks.append(bytes(body))+ print(f"node {node:2d} {NODE_REGION.get(node, f'region{node}'):10s} cell {cell*1000:.1f} mm "+ f"{len(V):,} verts {T.shape[0]:,} tris {len(body)/1e6:.2f} MB")++hdr = json.dumps(entries, separators=(',', ':')).encode()+out = bytearray(b'HEDS') + struct.pack('<II', 3, len(hdr)) + hdr+while len(out) % 4: out += b'\x00'+for b in blocks: out += b+suffix = '' if scale == 1.0 else f'-x{scale:g}'+if keep_head:+ suffix += '-sharpface'+dest = Path(f'{OUT_PREFIX}{suffix}.bin')+dest.parent.mkdir(parents=True, exist_ok=True)+dest.write_bytes(out)+resolved_dest = dest.resolve()+try:+ _shown = resolved_dest.relative_to(ROOT)+except ValueError:+ _shown = resolved_dest+print(f"\nwrote {_shown} {len(out)/1e6:.2f} MB ({len(entries)} node(s))")diff --git a/integrations/glb_character_pipeline/python/measure_density_convergence.py b/integrations/glb_character_pipeline/python/measure_density_convergence.pynew file mode 100644index 0000000..7a418de--- /dev/null+++ b/integrations/glb_character_pipeline/python/measure_density_convergence.py@@ -0,0 +1,217 @@+"""Does raising slice/spoke density recover REAL form, or only smooth through the same samples?++This is the question that decides whether matching the baseline's triangle count buys anything.+Triangle count is a COST metric; it becomes a FIDELITY metric only if the extra triangles carry+outline that the coarser sampling missed. There is no way to tell by inspection which it is -- hence+this measurement rather than an assumption.++METHOD. Build the radial outline of one band at rising spoke counts and compare each against the+finest, resampled onto a common dense set of rays so the comparison is like-for-like. Sampling that+has CONVERGED shows error collapsing toward zero: the extra spokes are re-describing a curve already+captured. Sampling still SHORT of the form shows error that keeps falling as density rises. The same+test along the height axis answers it for slice count.++Interpretation is the whole point: a converged axis means triangles spent there are cosmetic.++The second table measures whether the point cloud is dense enough to support each spoke count. An+empty angular bin is later interpolated by ``radial_outline``; once many bins are empty that+interpolation bridges arcs with no measured vertices and the loft bulges. The density ceiling is the+largest spoke count whose median empty-bin fraction across measured bands is at most 5%.++THIS SCRIPT ONLY PRINTS TABLES. Reading them and deciding the final per-node spoke count for+CHARACTER_SPOKES_JSON (min(convergence, density), raised only where a material-patch boundary needs+finer cutting) is a human/agent judgment call -- see PIPELINE.md Stage 1 -- not something this script+resolves for you.++Usage: python3 measure_density_convergence.py <glb> [nodeIndex]+"""+from __future__ import annotations++import math+import json+import statistics+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from slice_node import cluster_slice, radial_outline, read_node_positions # noqa: E402++RAYS = 360+++def outline_on_rays(points, spokes):+ """Outline at `spokes` resolution, re-read on a fixed dense ray set so densities are comparable."""+ ring = radial_outline(points, spokes)+ if len(ring) < 3:+ return None+ cx = sum(p[0] for p in ring) / len(ring)+ cy = sum(p[1] for p in ring) / len(ring)+ polar = sorted((math.atan2(p[1] - cy, p[0] - cx) % (2 * math.pi),+ math.hypot(p[0] - cx, p[1] - cy)) for p in ring)+ angles = [t[0] for t in polar]+ out = []+ for i in range(RAYS):+ a = 2 * math.pi * i / RAYS+ j = 0+ while j < len(angles) and angles[j] <= a:+ j += 1+ lo = polar[j - 1] if j else (polar[-1][0] - 2 * math.pi, polar[-1][1])+ hi = polar[j] if j < len(polar) else (polar[0][0] + 2 * math.pi, polar[0][1])+ gap = hi[0] - lo[0]+ out.append(lo[1] if gap <= 0 else lo[1] + (hi[1] - lo[1]) * (a - lo[0]) / gap)+ return out+++def biggest_cluster(band):+ groups = cluster_slice(band)+ return max(groups, key=len) if groups else []+++def empty_bin_fraction(points, spokes):+ """Return the fraction of angular bins containing no measured point."""+ cx = sum(p[0] for p in points) / len(points)+ cy = sum(p[1] for p in points) / len(points)+ occupied = [False] * spokes+ for x, y in points:+ angle = math.atan2(y - cy, x - cx) % (2 * math.pi)+ occupied[min(spokes - 1, int(angle / (2 * math.pi) * spokes))] = True+ return (spokes - sum(occupied)) / spokes+++def main() -> int:+ glb, node = Path(sys.argv[1]), int(sys.argv[2]) if len(sys.argv) > 2 and not sys.argv[2].startswith("--") else 0+ out_path = None+ if "--out" in sys.argv:+ out_path = Path(sys.argv[sys.argv.index("--out") + 1])+ positions, count = read_node_positions(glb, node)+ xs, ys, zs = positions[0::3], positions[1::3], positions[2::3]+ low, high = min(ys), max(ys)+ span = high - low+ print(f"node {node}: {count} vertices, height span {span:.4f}")++ def band_at(y, half):+ return [(round(xs[i], 4), round(zs[i], 4))+ for i in range(count) if abs(ys[i] - y) <= half]++ # Include a deliberately coarse floor for non-star-shaped/accessory nodes. A new subject can+ # have no density-supported value at the 16-spoke floor used by the original character; measuring+ # 4/8/12 is preferable to silently treating 16 as supported.+ SPOKES = (4, 8, 12, 16, 32, 64, 96, 128, 192)+ density_bands = []+ for frac in (0.12, 0.32, 0.52, 0.72, 0.92):+ y = low + span * frac+ group = biggest_cluster(band_at(y, span / 80))+ # Four points per bin at the 4-spoke floor is the minimum useful occupancy sample.+ if len(group) >= 16:+ density_bands.append((y, group))++ density_rows = [[empty_bin_fraction(group, spokes) * 100 for spokes in SPOKES]+ for _, group in density_bands]+ density_medians = ([statistics.median(row[i] for row in density_rows)+ for i in range(len(SPOKES))] if density_rows else [])+ density_supported = [spokes for spokes, value in zip(SPOKES, density_medians) if value <= 5.0]+ density_ceiling = max(density_supported) if density_supported else None++ # Convergence is meaningful only up to the density ceiling. Using an unsupported 320-spoke+ # reference asks interpolated, vertex-free arcs to define truth and is exactly the silent bulge+ # this tool is meant to prevent.+ convergence_spokes = tuple(spokes for spokes in SPOKES+ if density_ceiling is not None and spokes <= density_ceiling)+ convergence_bands = density_bands if convergence_spokes else []+ print("\nSPOKE CONVERGENCE mean |radius error| vs the density-ceiling outline")+ print(f"{'band y':>9}{'pts':>8} " + "".join(f"{s:>8}" for s in convergence_spokes))+ convergence_rows = []+ for y, group in convergence_bands:+ ref = outline_on_rays(group, density_ceiling)+ if ref is None:+ continue+ mean_r = statistics.fmean(ref)+ errors = []+ for spokes in convergence_spokes:+ test = outline_on_rays(group, spokes)+ err = statistics.fmean(abs(a - b) for a, b in zip(test, ref)) / mean_r * 100+ errors.append(err)+ convergence_rows.append(errors)+ print(f"{y:9.3f}{len(group):8d} " + "".join(f"{err:7.2f}%" for err in errors))+ if convergence_rows:+ convergence_medians = [statistics.median(row[i] for row in convergence_rows)+ for i in range(len(convergence_spokes))]+ print(f"{'median':>17} " + "".join(f"{err:7.2f}%" for err in convergence_medians))+ else:+ convergence_medians = []++ print("\nSPOKE DENSITY empty angular bins as % of bins; median must stay <= 5%")+ print(f"{'band y':>9}{'pts':>8} " + "".join(f"{s:>8}" for s in SPOKES))+ for (y, group), fractions in zip(density_bands, density_rows):+ print(f"{y:9.3f}{len(group):8d} " + "".join(f"{value:7.2f}%" for value in fractions))+ if density_rows:+ print(f"{'median':>17} " + "".join(f"{value:7.2f}%" for value in density_medians))+ print("density ceiling (largest median <= 5%): "+ + (str(density_ceiling) if density_ceiling is not None else "none"))+ else:+ density_medians = []+ print("density ceiling (largest median <= 5%): none (no band had >= 16 points)")++ print("\nSLICE CONVERGENCE coarse band vs a 320-slice-thin band at the same height, 96 spokes")+ print(f"{'slices':>8}{'bands':>8}{'error':>9}")+ fine_half = span / 640+ slice_results = []+ for slices in (20, 40, 80, 160):+ half = span / (2 * slices)+ errs = []+ for i in range(2, slices - 2, max(1, slices // 12)):+ yc = low + span * (i + 0.5) / slices+ coarse = biggest_cluster(band_at(yc, half))+ fine = biggest_cluster(band_at(yc, fine_half))+ if len(coarse) < 400 or len(fine) < 400:+ continue+ a, b = outline_on_rays(coarse, 96), outline_on_rays(fine, 96)+ if a is None or b is None:+ continue+ errs.append(statistics.fmean(abs(x - y) for x, y in zip(a, b))+ / statistics.fmean(b) * 100)+ if errs:+ mean_error = statistics.fmean(errs)+ slice_results.append({"slices": slices, "bands": len(errs), "meanErrorPercent": mean_error})+ print(f"{slices:8d}{len(errs):8d}{mean_error:8.2f}%")++ convergence_supported = [spokes for spokes, value in zip(convergence_spokes, convergence_medians)+ if value <= 1.0]+ if convergence_supported:+ convergence_candidate = min(convergence_supported)+ convergence_basis = "first median at or below 1%"+ elif convergence_medians:+ convergence_candidate = max(convergence_spokes)+ convergence_basis = "density ceiling; no lower count reached 1%"+ else:+ convergence_candidate = None+ convergence_basis = "no density-supported reference outline"+ result = {+ "schemaVersion": 1,+ "glb": str(glb.resolve()),+ "node": node,+ "vertexCount": count,+ "heightSpan": span,+ "measuredBandCount": len(density_bands),+ "convergenceBandCount": len(convergence_bands),+ "spokes": list(SPOKES),+ "convergenceSpokes": list(convergence_spokes),+ "convergenceMedianErrorPercent": convergence_medians,+ "convergenceCandidateFirstMedianAtOrBelow1Percent": convergence_candidate,+ "convergenceCandidateBasis": convergence_basis,+ "densityMedianEmptyBinPercent": density_medians,+ "densityCeilingLargestMedianAtOrBelow5Percent": (+ density_ceiling+ ),+ "sliceConvergence": slice_results,+ "decisionRule": "min(convergence candidate, density ceiling); null means insufficient measured bands",+ }+ if out_path is not None:+ out_path.parent.mkdir(parents=True, exist_ok=True)+ out_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")+ print(f"\nwrote {out_path}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/integrations/glb_character_pipeline/python/slice_node.py b/integrations/glb_character_pipeline/python/slice_node.pynew file mode 100644index 0000000..0e93677--- /dev/null+++ b/integrations/glb_character_pipeline/python/slice_node.py@@ -0,0 +1,279 @@+"""Slice a GLB node's point cloud into horizontal cross-sections.++WHY THIS REPLACES THE SILHOUETTE EXTRUSIONS. Those matched the reference's front outline almost+exactly -- 11 of 11 regions above 9/10 -- by extruding a traced 2D outline. From any other angle the+model was a stack of flat, mutually detached slabs, because an extrusion has no cross-section to speak+of. That is a one-view fit, not a model.++The GLB is a real 3D asset and was never used as one here: only its per-node bounding boxes, then its+per-height widths. Node 0 alone carries 371083 vertices. Reading the actual point cloud and taking a+convex hull per height band gives a solid that is correct from every direction, which is what the+front-outline approach could never be.++WHAT A PER-SLICE CONVEX HULL CAN AND CANNOT DO. It captures how a part's footprint changes with+height -- a boot's toe, a head narrowing to a face, trousers tapering at the waist -- so silhouettes+from any azimuth are plausible. It CANNOT represent a concavity in the horizontal plane: a cupped+palm, the gap between two fingers, the hollow inside a sleeve. Those get filled. The alternative,+tracing each slice's true outline, needs a sensible 2D boundary from a sparse and noisy point set;+hulls are robust where that is not, so this starts with hulls and says so.++Character-agnostic: takes a GLB path and node index as arguments, no character-specific data baked in.++Usage: python3 slice_node.py <glb> <nodeIndex> [slices]+"""+from __future__ import annotations++import array+import json+import struct+import sys+from pathlib import Path+++def read_node_positions(glb: Path, node_index: int) -> tuple[array.array, int]:+ """POSITION accessor of the node's first primitive, straight from the binary chunk."""+ with glb.open("rb") as handle:+ struct.unpack("<III", handle.read(12))+ json_length, _ = struct.unpack("<II", handle.read(8))+ gltf = json.loads(handle.read(json_length))+ struct.unpack("<II", handle.read(8))+ binary_start = handle.tell()++ node = gltf["nodes"][node_index]+ primitive = gltf["meshes"][node["mesh"]]["primitives"][0]+ accessor = gltf["accessors"][primitive["attributes"]["POSITION"]]+ view = gltf["bufferViews"][accessor["bufferView"]]+ handle.seek(binary_start + view.get("byteOffset", 0) + accessor.get("byteOffset", 0))+ raw = handle.read(accessor["count"] * 12)++ positions = array.array("f")+ positions.frombytes(raw)+ return positions, accessor["count"]+++def convex_hull(points: list[tuple[float, float]]) -> list[tuple[float, float]]:+ """Andrew's monotone chain, counter-clockwise, no collinear points retained.++ Deduplicated first: these clouds hold tens of thousands of points per slice and many coincide+ once projected to the horizontal plane, which makes the cross-product test degenerate.+ """+ unique = sorted(set(points))+ if len(unique) < 3:+ return unique++ def cross(o, a, b) -> float:+ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])++ lower: list[tuple[float, float]] = []+ for point in unique:+ while len(lower) >= 2 and cross(lower[-2], lower[-1], point) <= 0:+ lower.pop()+ lower.append(point)+ upper: list[tuple[float, float]] = []+ for point in reversed(unique):+ while len(upper) >= 2 and cross(upper[-2], upper[-1], point) <= 0:+ upper.pop()+ upper.append(point)+ return lower[:-1] + upper[:-1]+++def resample_ring(ring: list[tuple[float, float]], spokes: int) -> list[tuple[float, float]]:+ """Resample a hull to exactly `spokes` points, evenly spaced in angle about its centroid.++ Lofting needs every ring to have the same point count in the same angular order; hulls of+ different slices do not. Casting a fixed set of rays and taking where each crosses the hull gives+ that correspondence, so ring i point k always connects to ring i+1 point k and the side walls come+ out untwisted.+ """+ import math++ cx = sum(x for x, _ in ring) / len(ring)+ cy = sum(y for _, y in ring) / len(ring)+ out: list[tuple[float, float]] = []+ for index in range(spokes):+ angle = 2 * math.pi * index / spokes+ dx, dy = math.cos(angle), math.sin(angle)+ best = 0.0+ # Intersect the ray with every hull edge; the hull is convex so at most one crossing counts.+ for i in range(len(ring)):+ (x0, y0), (x1, y1) = ring[i], ring[(i + 1) % len(ring)]+ ex, ey = x1 - x0, y1 - y0+ denominator = dx * ey - dy * ex+ if abs(denominator) < 1e-12:+ continue+ t = ((x0 - cx) * ey - (y0 - cy) * ex) / denominator+ u = ((x0 - cx) * dy - (y0 - cy) * dx) / denominator+ if t > 0 and -1e-9 <= u <= 1 + 1e-9:+ best = max(best, t)+ out.append((round(cx + dx * best, 4), round(cy + dy * best, 4)))+ return out+++def radial_outline(points: list[tuple[float, float]], spokes: int,+ percentile: float = 0.92) -> list[tuple[float, float]]:+ """Concave outline of a cluster: the real radius in each angular bin, not a hull around it.++ WHY THIS REPLACES convex_hull + resample_ring. A hull is the tightest CONVEX shape containing the+ cluster, so it erases every inward curve -- the waist above the hips, the arch of a boot, the dip+ between a knee pad and the shin. That is exactly the detail the silhouette needs, and no amount of+ extra slices recovers it, because the loss is within each slice rather than between them.++ Taking a high percentile of the radii per bin rather than the maximum keeps a single stray vertex+ from throwing a spike; `percentile` is the one tuning knob. Empty bins are filled by interpolating+ their nearest occupied neighbours, so a sparse cluster degrades to a smooth ring instead of a+ collapsed one.+ """+ import math++ cx = sum(x for x, _ in points) / len(points)+ cy = sum(y for _, y in points) / len(points)+ bins: list[list[float]] = [[] for _ in range(spokes)]+ for x, y in points:+ dx, dy = x - cx, y - cy+ radius = math.hypot(dx, dy)+ if radius <= 0:+ continue+ index = int((math.atan2(dy, dx) % (2 * math.pi)) / (2 * math.pi) * spokes) % spokes+ bins[index].append(radius)++ radii: list[float | None] = []+ for values in bins:+ if not values:+ radii.append(None)+ continue+ values.sort()+ radii.append(values[min(len(values) - 1, int(len(values) * percentile))])++ if all(value is None for value in radii):+ return []+ for index in range(spokes):+ if radii[index] is not None:+ continue+ before = next(radii[(index - step) % spokes] for step in range(1, spokes + 1)+ if radii[(index - step) % spokes] is not None)+ after = next(radii[(index + step) % spokes] for step in range(1, spokes + 1)+ if radii[(index + step) % spokes] is not None)+ radii[index] = (before + after) / 2++ out = []+ for index in range(spokes):+ angle = 2 * math.pi * (index + 0.5) / spokes+ out.append((round(cx + math.cos(angle) * radii[index], 4),+ round(cy + math.sin(angle) * radii[index], 4)))+ return out+++def decimate_ring(ring: list[tuple[float, float]], limit: int) -> list[tuple[float, float]]:+ """Keep at most `limit` points, dropping the ones that change direction least.++ A hull of a dense cloud can run to hundreds of points that are visually identical; every one+ becomes vertices in the lofted mesh. Dropping by turn angle keeps corners and sheds the rest.+ """+ if len(ring) <= limit:+ return ring+ while len(ring) > limit:+ worst_index, worst_turn = 1, float("inf")+ for i in range(len(ring)):+ previous, current, following = ring[i - 1], ring[i], ring[(i + 1) % len(ring)]+ turn = abs((current[0] - previous[0]) * (following[1] - current[1])+ - (current[1] - previous[1]) * (following[0] - current[0]))+ if turn < worst_turn:+ worst_index, worst_turn = i, turn+ ring.pop(worst_index)+ return ring+++def cluster_slice(points: list[tuple[float, float]],+ cell: float = 0.012) -> list[list[tuple[float, float]]]:+ """Split one slice's points into spatially separate groups, largest first.++ A single hull per slice is wrong whenever a slice cuts through two disconnected pieces of the same+ node. Grid-based union of occupied cells: cheap, and `cell` is the only tuning knob -- it is the+ widest gap that still counts as connected.+ """+ buckets: dict[tuple[int, int], list[tuple[float, float]]] = {}+ for x, z in points:+ buckets.setdefault((int(x // cell), int(z // cell)), []).append((x, z))++ seen: set[tuple[int, int]] = set()+ groups: list[list[tuple[float, float]]] = []+ for key in buckets:+ if key in seen:+ continue+ stack, group = [key], []+ seen.add(key)+ while stack:+ cx, cz = stack.pop()+ group.extend(buckets[(cx, cz)])+ for dx in (-1, 0, 1):+ for dz in (-1, 0, 1):+ neighbour = (cx + dx, cz + dz)+ if neighbour in buckets and neighbour not in seen:+ seen.add(neighbour)+ stack.append(neighbour)+ groups.append(group)+ return sorted(groups, key=len, reverse=True)+++def slice_node(glb: Path, node_index: int, slices: int = 12,+ max_points: int = 24) -> dict[str, object]:+ positions, count = read_node_positions(glb, node_index)+ xs, ys, zs = positions[0::3], positions[1::3], positions[2::3]+ low, high = min(ys), max(ys)+ span = high - low++ buckets: list[list[tuple[float, float]]] = [[] for _ in range(slices)]+ for i in range(count):+ index = min(slices - 1, int((ys[i] - low) / span * slices)) if span else 0+ # Quantise to 0.1 mm before hulling: raw floats make thousands of near-duplicate points that+ # the hull has to sort through for no gain in shape.+ buckets[index].append((round(xs[i], 4), round(zs[i], 4)))++ rings = []+ for index, bucket in enumerate(buckets):+ if len(bucket) < 3:+ continue+ y = round(low + span * (index + 0.5) / slices, 4)+ for group in cluster_slice(bucket):+ # Drop specks: a handful of stray points make a degenerate ring that adds a spike to the+ # loft without describing anything.+ if len(group) < max(12, len(bucket) // 100):+ continue+ ring = radial_outline(group, max_points)+ if len(ring) < 3:+ continue+ cx = sum(x for x, _ in group) / len(group)+ cz = sum(z for _, z in group) / len(group)+ rings.append({+ "y": y,+ "centroid": [round(cx, 4), round(cz, 4)],+ "points": [[round(x, 4), round(z, 4)] for x, z in ring],+ })++ return {+ "nodeIndex": node_index,+ "vertexCount": count,+ "yRange": [round(low, 4), round(high, 4)],+ "sliceCount": len(rings),+ "rings": rings,+ "limitations": [+ "Each ring is a radial outline of one CLUSTER within its slice, so inward curves survive. "+ "What it still cannot represent is a shape that is not star-convex about its own centroid: "+ "a spiral, a deep hook, or a C-section whose opening faces away from the centre.",+ "Rings are sampled at slice centres, so a feature thinner than one slice is averaged away.",+ "Rings are resampled on rays from each slice's own centroid, so a part whose slices are "+ "offset from one another has its correspondence set by centroid, not by world position.",+ ],+ }+++def main(argv: list[str]) -> int:+ glb = Path(argv[0])+ node_index = int(argv[1])+ slices = int(argv[2]) if len(argv) > 2 else 12+ print(json.dumps(slice_node(glb, node_index, slices), indent=2))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/integrations/glb_character_pipeline/uv.lock b/integrations/glb_character_pipeline/uv.locknew file mode 100644index 0000000..ffeaa7c--- /dev/null+++ b/integrations/glb_character_pipeline/uv.lock@@ -0,0 +1,116 @@+version = 1+revision = 3+requires-python = ">=3.11, <3.13"+resolution-markers = [+ "python_full_version >= '3.12'",+ "python_full_version < '3.12'",+]++[[package]]+name = "img2threejs-glb-character-pipeline"+version = "0.1.0"+source = { virtual = "." }+dependencies = [+ { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },+ { name = "numpy", version = "2.5.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },+ { name = "pillow" },+]++[package.metadata]+requires-dist = [+ { name = "numpy", specifier = ">=1.26,<3" },+ { name = "pillow", specifier = ">=11,<13" },+]++[[package]]+name = "numpy"+version = "2.4.6"+source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version < '3.12'",+]+sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/b3/49/ec46835a70be8fa6446c495126ac84fdb28cb2558e1620ffb87a10c8b64c/numpy-2.4.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0280e0356c0829a18d9de1cb7eee50ec22ca639878d7240307ca0943d73cd2c4", size = 16969194, upload-time = "2026-05-18T23:33:13.503Z" },+ { url = "https://files.pythonhosted.org/packages/0e/0d/f5957185c0ee2f3e12f78715aa9e3b353fd83633316c8532b38faa37e3f6/numpy-2.4.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:110f8b71aacb688ec69062bb7f6938a0f8acb01b7c1c4beb453c65b6d234584d", size = 14964111, upload-time = "2026-05-18T23:33:17.795Z" },+ { url = "https://files.pythonhosted.org/packages/ad/40/40a40ee0ddf7ceb782c49af278894b686e586d65d8c1889c8b5da01a3d7d/numpy-2.4.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:4cfe66903cc32a9921a6733d96b19bb6abf310397581bbad89c228f5abaf0ee8", size = 5469159, upload-time = "2026-05-18T23:33:20.654Z" },+ { url = "https://files.pythonhosted.org/packages/63/13/f9a8046535cb21deae82f8d03de9617e08882d274fad2539630761888228/numpy-2.4.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:8155154c7c691289fe18f510b5d4657c68c67989f293f0535a91360392ff6538", size = 6798936, upload-time = "2026-05-18T23:33:22.987Z" },+ { url = "https://files.pythonhosted.org/packages/33/a8/6fa8c1a345a8c85dbb21932c447bee07c30a2c2a3f31e369c0a84b300147/numpy-2.4.6-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0ab0a9c4ffb1a6d95ef519fe4247dba8eb6b18ad93999f76b7f657039acabd47", size = 15966692, upload-time = "2026-05-18T23:33:26.62Z" },+ { url = "https://files.pythonhosted.org/packages/02/03/74fe2a4cb3817d94d86402f2506554130a2f01414e299b5a843e5a8a957f/numpy-2.4.6-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:89cd468399cfd2504718f0ba50e410dca55a170b61a02ad92bb18c8a65186e93", size = 16918164, upload-time = "2026-05-18T23:33:29.955Z" },+ { url = "https://files.pythonhosted.org/packages/c5/80/3615be3313f7e7696609bc194b9f0101da809df79e859bdb84e0cd043f46/numpy-2.4.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c2d37ab77531417474168eb79d6d80b14f821a966818505d03013d0833edb7a8", size = 17322877, upload-time = "2026-05-18T23:33:34.724Z" },+ { url = "https://files.pythonhosted.org/packages/ca/ac/a691e0fe2675e370d0e08ff905adc49a1c8830e8cae03efe4477e92cd55d/numpy-2.4.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f407cb6b8e9d6d8c626bc73c945db1706035af8fd632295547bf1c9e46d092d6", size = 18651487, upload-time = "2026-05-18T23:33:38.217Z" },+ { url = "https://files.pythonhosted.org/packages/15/a7/9bc1cd626d7bf6869bfedf27b91b6ab5dd607758bf8e959d6fa80c6a59cb/numpy-2.4.6-cp311-cp311-win32.whl", hash = "sha256:ddea102b48f9e339f3948bf22040944184627a30fdf7f858667673b9c5f033c8", size = 6233945, upload-time = "2026-05-18T23:33:41.331Z" },+ { url = "https://files.pythonhosted.org/packages/c5/31/7fc6239c12bce7e931463251cca4426c465e1876ba3cc785402ef4dd8f4e/numpy-2.4.6-cp311-cp311-win_amd64.whl", hash = "sha256:1e254a00cdf42b1e4d5b3d68d33af63268d41340d8885df2ab6470f2e1500147", size = 12608406, upload-time = "2026-05-18T23:33:44.131Z" },+ { url = "https://files.pythonhosted.org/packages/27/83/140f85a466595a16382996a1bf06b2b54bcd597488921b0c9daaeeda72af/numpy-2.4.6-cp311-cp311-win_arm64.whl", hash = "sha256:ed9749eef4cbd126da3dc1d6bcb3a57f5eb7ac6a6484146bdbf743f552dfc577", size = 10479528, upload-time = "2026-05-18T23:33:50.725Z" },+ { url = "https://files.pythonhosted.org/packages/95/2a/3d7b5ac8aac24feaf9ad7ed58f45b0bbc06d37e4338ae84c9f2298b570f9/numpy-2.4.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:001fbb8e08d942dd57599e781f2472269ee7f2755fae407b4f67b2f0b17da3f1", size = 16689119, upload-time = "2026-05-18T23:33:54.065Z" },+ { url = "https://files.pythonhosted.org/packages/ea/12/92c4c131527599e8288d6918e888d88726f84d805d784b771f32408aeaef/numpy-2.4.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ebfb099f8dcf083deef3ac1ca4c1503f387cf76296fcb3816b66f5ecb5f54fdb", size = 14699246, upload-time = "2026-05-18T23:33:57.621Z" },+ { url = "https://files.pythonhosted.org/packages/ad/fe/c0a6b7b2ca128a8fb228575147073b660656734b8ebe4d76c8fd748dcc79/numpy-2.4.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:3213d622a0283a39a93d188f3cf72b26862df52fbb4ca3697f51705016523d41", size = 5204410, upload-time = "2026-05-18T23:34:00.302Z" },+ { url = "https://files.pythonhosted.org/packages/f3/d4/9770d14ba719432bb90a421bfd443872ed0f70f7264b64bec12ea363d5fd/numpy-2.4.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:357cc07a6d7b0b182ff02249616a03742827ebb1277546b5c7cd7f7620a45698", size = 6551240, upload-time = "2026-05-18T23:34:02.852Z" },+ { url = "https://files.pythonhosted.org/packages/c9/c6/50a46a6205feba2343f1d6d17438107c5dc491ed1c736e6ea68689fd906b/numpy-2.4.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f9fb9157b4ce2971008323afe46053787b526ef624fea915b261468a8421a0f", size = 15671012, upload-time = "2026-05-18T23:34:05.485Z" },+ { url = "https://files.pythonhosted.org/packages/99/60/14115e6364fa676c5397c2ad3004e527e9aa487abf5d0706ec81bbd08529/numpy-2.4.6-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:90f9849678c75fe7afa2d348ac842c168b0a4d3d61919687216dfc547976d853", size = 16645538, upload-time = "2026-05-18T23:34:09.265Z" },+ { url = "https://files.pythonhosted.org/packages/ae/c5/693cbe59e57db94d2231fa519ca3978dc9e19da5a8f088588f5c6e947ff2/numpy-2.4.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c1a2af6c6ef86344a6b0db6b97834208bf598db514f2b155042439b62605601a", size = 17020706, upload-time = "2026-05-18T23:34:13.053Z" },+ { url = "https://files.pythonhosted.org/packages/ef/fc/85b7c4eff9b4966ade25c2273cf7e7012e92366c032058653934b37de044/numpy-2.4.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e5805d5a22fd19c8ccff10a9561f9df94436b0545619ea579db2d3c35294bce2", size = 18368541, upload-time = "2026-05-18T23:34:17.024Z" },+ { url = "https://files.pythonhosted.org/packages/f6/81/e1b27545deedce7f4a0b348618c6b62d74e36a4dc9ccd42f3eb2f85eee32/numpy-2.4.6-cp312-cp312-win32.whl", hash = "sha256:e3eeb0aabd6bd5ce64faae67e9935203a6991b4bc2a485a767fbafb2c5125f45", size = 5962825, upload-time = "2026-05-18T23:34:20.3Z" },+ { url = "https://files.pythonhosted.org/packages/ab/ca/feab00bd44aa5fe1ad2c18f08b4d3bb92e26484b0b1d1443897809ed528c/numpy-2.4.6-cp312-cp312-win_amd64.whl", hash = "sha256:d8e8286dd7cea7895157318d1b91cdacac64c479f3cbc8dce548331728484751", size = 12321687, upload-time = "2026-05-18T23:34:23.095Z" },+ { url = "https://files.pythonhosted.org/packages/63/cf/5a6d34850a39d1093558564f77ee8e8e0bee5061151b8f05a55711001ec7/numpy-2.4.6-cp312-cp312-win_arm64.whl", hash = "sha256:4081eb135ac24158bd51cdfbef16f1c64df7063b1143f24731387137c092bec8", size = 10221482, upload-time = "2026-05-18T23:34:25.876Z" },+ { url = "https://files.pythonhosted.org/packages/de/12/b422cc84439adc0d00de605bf4a308890ae5c26f2c71fbd73e5d08fbb0dd/numpy-2.4.6-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:55cced7c52e981362f708ad635198e97a752dfba412cc03c23bbf3bd8d5cd662", size = 16847511, upload-time = "2026-05-18T23:36:50.673Z" },+ { url = "https://files.pythonhosted.org/packages/44/53/f481bef68011740f8849418d82db07230e825013f31f4eef5ba5b805316a/numpy-2.4.6-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d6da64deb6b8ed903e7560180a92f2d804ee1ba5eeb849ac2748b8c1aba1f6d7", size = 14889064, upload-time = "2026-05-18T23:36:53.879Z" },+ { url = "https://files.pythonhosted.org/packages/7f/57/42ed575c10ced8af951d426bc4e1f8aff16fd851db33f067036215a7f860/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:68a5124b13fa6cc2086764a20005d30bc0548146f7f5322f02fce212ca14317f", size = 5394157, upload-time = "2026-05-18T23:36:57.194Z" },+ { url = "https://files.pythonhosted.org/packages/6a/ef/f66cc724fcc36c1e364c67f51ae9146090b8b584f27d58b97fdae3edd737/numpy-2.4.6-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:948424b06129ce883307e8cff868c31396d8dc7630a59c61d70d98dbe70f222c", size = 6708728, upload-time = "2026-05-18T23:36:59.575Z" },+ { url = "https://files.pythonhosted.org/packages/1a/9c/c531f2293b91265d8b48e9b329f54fdd7ffae73cb4134ea10cca4237e9cc/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5dbbdb29840ca3d91ee0fece42fc29278886d908280bfec0a5846c6f901a3eb0", size = 15798374, upload-time = "2026-05-18T23:37:02.674Z" },+ { url = "https://files.pythonhosted.org/packages/1a/b0/413077f6b1153ed3cba361401c6783bbad6114804a000cc22eb71c13e190/numpy-2.4.6-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ad03c0965fb3c692200e74d458ca28c1dbb4ce96f9a479a8aa041ad5fabca02", size = 16747286, upload-time = "2026-05-18T23:37:06.327Z" },+ { url = "https://files.pythonhosted.org/packages/15/ce/e5ec180bc41812edcd8daeb8639d205622c0e8c02259d8ab25a0201b3c2a/numpy-2.4.6-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:2803abfebfc990042cd494d8ce2d5f82e9d847af6d35ec486923aa19dbad5e73", size = 12504263, upload-time = "2026-05-18T23:37:09.715Z" },+]++[[package]]+name = "numpy"+version = "2.5.2"+source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version >= '3.12'",+]+sdist = { url = "https://files.pythonhosted.org/packages/9a/80/db0b4559e57ec36362bedbb05530a87fafbcb6067708c946967a41d449e7/numpy-2.5.2.tar.gz", hash = "sha256:d482d171c406ae88c5b19cad3b6a1c4c5209f886ab74bc44c2c865c23f52d860", size = 20773161, upload-time = "2026-08-09T13:48:27.962Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/69/72/dccb0aaf40972777283303919f613964227266d0c13adebb79ac124f1c3e/numpy-2.5.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:14e373cfc6387177e8409dac3c7159be8eb05cd77096cd7c950268b86f62831c", size = 16891693, upload-time = "2026-08-09T13:44:51.702Z" },+ { url = "https://files.pythonhosted.org/packages/60/2e/b5aee50a1f74ac815cf8331812cb8251e29024025de462e0c047641c614c/numpy-2.5.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4bbd96c833ecc8cc069ce518078fc8c60cb9cbfb0fea5b7a803ad65035596d03", size = 11903109, upload-time = "2026-08-09T13:44:55.501Z" },+ { url = "https://files.pythonhosted.org/packages/f3/f4/29e78102a80601cf034d4e9767022cffeca2c3b4c926e1754572ca95593d/numpy-2.5.2-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:6e8172ddfcf5cf74b811d372b570b83c60bd2de87a6fbfbebdadb4a9bd9c6cbb", size = 5350202, upload-time = "2026-08-09T13:44:58.401Z" },+ { url = "https://files.pythonhosted.org/packages/11/4b/dcd3b7eadaf4035d2c7a4289d232523a6964f602598ef7674e4bd7291f93/numpy-2.5.2-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:65f188481f1669e26f62b701e8205d19e460fa4a9b52a1414ba382330e4a3414", size = 6687736, upload-time = "2026-08-09T13:45:00.813Z" },+ { url = "https://files.pythonhosted.org/packages/e5/21/4947e0e9d6c9fc2e2ff15b8949049ee44f63adb9cacc729ab8793f97e712/numpy-2.5.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8ee9c4eeb8454b3660a8b53493563c3e121c2fc94fbd72b848ef814ed7b676a9", size = 15612696, upload-time = "2026-08-09T13:45:04.151Z" },+ { url = "https://files.pythonhosted.org/packages/3a/5f/62d28cf019460c7f1394105b4d49d9911a9c444cb77ab0bd95a204c5a6de/numpy-2.5.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cdec01fa790a186d430433fdd4d4ffb70eed6f0eeb4bf05c8dbe2dce0a9bcb8", size = 16722264, upload-time = "2026-08-09T13:45:07.714Z" },+ { url = "https://files.pythonhosted.org/packages/14/25/3f0be4c1b9fdf5dd5e708a6806978564d7c46a055c000496309ff2a2f8af/numpy-2.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:7999d4ddb0c4025018373fd787510d46e04c769467af22869707b3c1cfd459ab", size = 16974396, upload-time = "2026-08-09T13:45:11.316Z" },+ { url = "https://files.pythonhosted.org/packages/22/72/6262cbdeeb45da9d971e40715f579d791603ba8ec0b5e2db1ac55454421d/numpy-2.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c1f017dc0875c9209d219f97feceb7d54c2661bb243deb4114478e1295808af7", size = 18476044, upload-time = "2026-08-09T13:45:14.869Z" },+ { url = "https://files.pythonhosted.org/packages/36/33/29208b8b075bde62d26a81d14b358c42b0f69b6cabd98d4ff97f37f22b05/numpy-2.5.2-cp312-cp312-win32.whl", hash = "sha256:d6a48072864e3324e194a8fbb3c657bcc5b5c869dbc64c9537b1d5c862572c0a", size = 6072817, upload-time = "2026-08-09T13:45:17.867Z" },+ { url = "https://files.pythonhosted.org/packages/7f/b9/87fea2769fe1c47c1b5b01d8310772c9d1a85d485de7cf386ef7a3332b02/numpy-2.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:28ac63476ec7651484215ee7fa15a1f78b57c14621f01e392afe17b9a1390ce4", size = 12464674, upload-time = "2026-08-09T13:45:20.734Z" },+ { url = "https://files.pythonhosted.org/packages/14/52/032b97e00461ab0809bbe4c588b035620e5a14b8cdee47ecddefc7b17d33/numpy-2.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:27650bb0e7140fa3d37b9923b4803645e0b125d190f326eecfd3f4dad8e8ade1", size = 10397131, upload-time = "2026-08-09T13:45:23.73Z" },+]++[[package]]+name = "pillow"+version = "12.3.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" },+ { url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" },+ { url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" },+ { url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" },+ { url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" },+ { url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" },+ { url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" },+ { url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" },+ { url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" },+ { url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" },+ { url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" },+ { url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" },+ { url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" },+ { url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" },+ { url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" },+ { url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" },+ { url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" },+ { url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" },+ { url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" },+ { url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" },+ { url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" },+ { url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" },+ { url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },+]