Skip to content

Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.

img2threejs: token-efficient image-to-3D Three.js skill with demo and README

hoainhoc9b1eded74af
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0523447
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,13 @@
+# Python
+__pycache__/
+*.pyc
+
+# macOS
+.DS_Store
+
+# Editor
+.vscode/
+.idea/
+
+# Scratch / generated review artifacts (keep committed demos in assets/)
+*.tmp
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a483316
--- /dev/null
+++ b/README.md
@@ -0,0 +1,151 @@
+# img2threejs
+
+Rebuild the object in a reference image as a **code-only, procedural Three.js model** — quality-gated, animation-ready, and deliberately token-efficient. This is reconstruction-by-code, not photogrammetry, mesh extraction, or downloaded art packs.
+
+![img2threejs demo — a reference loot-chest image reconstructed as a procedural Three.js model](assets/demo.gif)
+
+*Above: a single reference image reconstructed in code — correct proportions, colours, bevels, gold trim, and an emissive emblem — running live in the browser.*
+
+---
+
+## What it does
+
+You give it one reference image of an object. It produces a `THREE.Group` factory written in TypeScript that recreates that object from primitives, procedural shaders, and generated geometry — with a runtime hierarchy (pivots, sockets, colliders) so the result is ready to animate, not an inert lump.
+
+It works under Claude Code, Codex, or OpenCode. It is agent-agnostic: wherever the docs say "agent vision" or "agent browser tool", it uses whatever the host provides (native image reading, a browser MCP, the project preview, or a user-supplied screenshot).
+
+---
+
+## Why it is token-efficient
+
+Most image-to-3D agent loops burn tokens by asking the model to do mechanical work — re-reading the whole model every pass, scoring pixels, validating JSON by hand, re-running steps it already did. img2threejs pushes all of that into deterministic scripts and spends model tokens only where judgment is actually required.
+
+- **Scripts enforce, the model judges.** Ten Python scripts handle validation, gating, spec authoring, PBR extraction, comparison-sheet packaging, and pipeline state. They never score visuals. The model's tokens go to one thing: looking at a single side-by-side sheet and deciding pass or fail.
+- **Zero dependencies, zero install churn.** Every script is pure Python 3.10+ standard library. No pip, no PIL, no numpy, no Playwright. PNG read/write is done with `struct` and `zlib`. Nothing to install means nothing to debug in-context.
+- **Pass-gated generation.** The code generator emits only the currently unlocked build pass. The model does not regenerate or re-read the entire model on every iteration — each step is small and scoped.
+- **Fail fast, before codegen.** A strict-quality gate blocks shallow specs before a single line of Three.js is generated, so you never spend tokens rendering and re-doing a model that was underspecified from the start.
+- **One image per review.** Each pass is judged from exactly one packaged comparison sheet (reference beside render), not a scattering of screenshots.
+- **Text output, not binaries.** The result is diffable TypeScript plus a JSON spec — small, reviewable, and version-controllable, instead of multi-megabyte mesh files.
+
+The net effect: you still get a faithful 3D model from an image, but the expensive model context is reserved for visual judgment and code, not bookkeeping.
+
+---
+
+## How it works
+
+The skill runs a staged sculpting pipeline. Scripts gate each stage; the agent's vision is the only thing that can approve a pass.
+
+```mermaid
+flowchart TD
+ A[Reference image] --> B[Probe and suitability gate]
+ B --> C[Pre-Spec Assessment<br/>class, complexity, quality contract]
+ C --> D[Author ObjectSculptSpec<br/>components, materials, sockets]
+ D --> E{Validate and strict-quality}
+ E -- too shallow --> D
+ E -- ok --> F[Locked build passes]
+ F --> G[Generate Three.js factory<br/>current pass only]
+ G --> 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:<br/>refine-spec or refine-code]
+ K --> F
+ J -- pass --> L{More passes?}
+ L -- yes --> F
+ L -- no --> M[Animation-ready Three.js model]
+```
+
+### The build passes
+
+The model is sculpted in a fixed order, and a pass only unlocks after the previous one is reviewed and accepted:
+
+`blockout` to `structural-pass` to `form-refinement` to `material-pass` to `surface-pass` to `lighting-pass` to `interaction-pass` to `optimization-pass`
+
+Each pass has its own acceptance criteria. A pass can be marked `continue` only with a real render, a comparison sheet, an agent-vision score at or above threshold, and every identity-defining feature at or above its own threshold.
+
+### The gates
+
+- **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.
+- **Action-ready** — the model must expose a runtime hierarchy (pivots, sockets, colliders, destruction groups) via `root.userData.sculptRuntime`.
+- **Attachment correctness** — child parts (handles, limbs, tubes) must 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.
+
+### Self-correction
+
+After every pass the agent chooses exactly one action: `continue`, `refine-spec`, `refine-code`, `request-input`, or `stop`. `refine-spec` fixes a wrong or shallow spec and re-validates; `refine-code` fixes geometry, material, or lighting that does not match a sound spec.
+
+---
+
+## Quick start
+
+1. **Install** — place this folder in your skills directory:
+
+ ```bash
+ git clone https://github.com/hoainho/img2threejs.git ~/.claude/skills/img2threejs
+ ```
+
+2. **Invoke** — in Claude Code, attach or point to an object image and run:
+
+ ```
+ /img2threejs Rebuild this object as a Three.js model, keep the proportions, angles, and colours.
+ ```
+
+3. **Follow the pipeline** — the skill validates the image, writes an assessment and spec, generates the factory pass by pass, and shows you a side-by-side comparison at each step until the render matches.
+
+The scripts run from the skill root. They need only Python 3.10+ — nothing to install.
+
+```bash
+python3 scripts/probe_reference_image.py <image>
+python3 scripts/new_pre_spec_assessment.py "Name" --image <image> --out assessment.json
+python3 scripts/new_sculpt_spec.py "Name" --image <image> --assessment assessment.json --out spec.json
+python3 scripts/validate_sculpt_spec.py spec.json --strict-quality
+python3 scripts/generate_threejs_factory.py spec.json --out src/createObjectModel.ts
+```
+
+---
+
+## Scripts
+
+| Script | Role |
+| --- | --- |
+| `probe_reference_image.py` | Image metadata and obvious technical issues (not a visual check). |
+| `new_pre_spec_assessment.py` | Classify the object, score complexity, emit a quality contract. |
+| `new_sculpt_spec.py` | Author the ObjectSculptSpec from the assessment. |
+| `validate_sculpt_spec.py` | Validate the spec; `--strict-quality` blocks shallow specs before codegen. |
+| `extract_reference_pbr.py` | Reference-derived PBR evidence per crop (inference, not inverse rendering). |
+| `sculpt_pass_orchestrator.py` | Locked pass state: status, check, sync. |
+| `generate_threejs_factory.py` | Emit the Three.js `Group` factory for the current unlocked pass. |
+| `make_visual_comparison_sheet.py` | Package one reference-vs-render sheet for review. |
+| `append_sculpt_review.py` | Record a per-pass review: scores, decision, evidence. |
+| `visual_feature_gate.py` | Internal helper enforcing per-feature score thresholds. |
+
+The `references/` 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).
+
+---
+
+## 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.
+- A render plus comparison sheets documenting the fidelity at each pass.
+
+---
+
+## Requirements
+
+- Python 3.10+ (standard library only).
+- A Three.js project or preview to render into (any modern bundler).
+- A host that can read images and capture a browser screenshot (Claude Code, Codex, or OpenCode with a browser tool or user-supplied screenshots).
+
+---
+
+## Honesty about limits
+
+A single image cannot reveal hidden sides or guarantee exact geometry. The skill states plainly when output is approximate, stylized, or low-poly, and infers unseen faces by mirroring visible ones rather than faking confidence. "This cannot reach the requested fidelity from this image" is a valid, expected result.
+
+---
+
+## License
+
+MIT.
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..f9fb938
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,110 @@
+---
+name: img2threejs
+description: Turn an object reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, sculpt specs, and staged code generation.
+license: MIT
+version: 1.0.0
+---
+
+# img2threejs — Image to procedural Three.js
+
+Rebuild the object visible in a reference image as a **code-only** procedural Three.js model,
+gated by a staged sculpting pipeline and an AI-vision self-correction loop. This is
+reconstruction-by-code, **not** photogrammetry, mesh extraction, or downloaded art packs.
+
+Agent-agnostic: works under Claude Code, Codex, or OpenCode. Wherever this doc says "agent
+vision" or "agent browser tool", use whatever the host provides — native image reading, a
+browser MCP (playwright/chrome-devtools), the project preview, or a user-supplied screenshot.
+
+## When To Use
+
+The user attaches/points to an object image and wants a procedural Three.js model, a
+reconstruction/animation/destruction plan, a sculpt spec, or code. Also for material studies,
+action-ready props, game objects, botanical/mechanical parts, and stylized reconstructions.
+
+## Core Promise
+
+Sculpt from a photo, in order — never one-shot a mesh:
+1. **Validate** the image is a suitable 3D target (`references/validation-rubric.md`).
+2. **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.
+
+State explicitly when output is approximate/stylized/low-poly. A single image cannot reveal
+hidden sides or guarantee exact geometry — say so instead of faking confidence.
+
+## Required Inputs
+
+- one image path / screenshot / URL / attached image (if missing or unreadable, ask)
+- intended use: prop, game object, hero render, playable/destructible object, animation rig
+ (default: real-time browser prop with interactive performance)
+
+## The Loop (scripts do enforcement; agent vision does judgment)
+
+Run scripts from the skill root (`scripts/...`). Pure Python 3.10+ stdlib, no pip installs.
+Full flags: `references/scripts.md`. Never let a script *score* visuals — that is the agent's job.
+
+1. Probe local images: `scripts/probe_reference_image.py <image>` (metadata only, not a visual check).
+2. **Pre-Spec Assessment Gate** — classify + score complexity + write the quality contract:
+ `scripts/new_pre_spec_assessment.py "Name" --image <img> --complexity <simple|moderate|complex|ultra-complex> --out assessment.json`. Rules: `references/pre-spec-assessment.md`.
+3. Author the spec from the assessment:
+ `scripts/new_sculpt_spec.py "Name" --image <img> --assessment assessment.json --out object-sculpt-spec.json`.
+ Replace generic starter `featureReviewTargets` with the object's real identity-defining
+ systems (≤5 critical, ≤3 important per pass). Use 3D-graphics terms only (`references/3d-graphics-terminology.md`), never "nice/smooth/shiny".
+4. When material fidelity matters and a source image exists, extract reference PBR evidence per crop:
+ `scripts/extract_reference_pbr.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.
+5. Validate, then strict-validate before generating code:
+ `scripts/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
+ local overrides, no micro groups is NOT implementation-ready even if JSON validates).
+6. **Locked build passes** — only touch the currently unlocked pass:
+ `scripts/sculpt_pass_orchestrator.py status object-sculpt-spec.json`
+ `scripts/sculpt_pass_orchestrator.py check object-sculpt-spec.json --pass-id <pass>`
+ `scripts/generate_threejs_factory.py object-sculpt-spec.json --out src/createObjectModel.ts`
+ (generator is pass-gated: a future `--pass-id` fails until prior passes are reviewed `continue`).
+7. Render the current pass in a browser/preview, capture a screenshot at a review viewpoint.
+8. Package one side-by-side sheet, then inspect it with agent vision:
+ `scripts/make_visual_comparison_sheet.py --reference <img> --render <shot> --out cmp.png --json`.
+9. Record the review (overall + per-layer + per-feature scores + decision):
+ `scripts/append_sculpt_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`.
+10. Sync pipeline state after manual review edits:
+ `scripts/sculpt_pass_orchestrator.py sync object-sculpt-spec.json --in-place`.
+
+## Gates (do not skip)
+
+- **Suitability**: pass / conditional / reject before any planning. `references/validation-rubric.md`.
+- **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: `references/browser-screenshot-feedback.md`.
+- **Action-ready**: build a runtime hierarchy (pivots, sockets, colliders, destruction groups),
+ never an inert lump; expose `root.userData.sculptRuntime`. `references/action-ready-models.md`.
+- **Attachment**: child appendages (branches/limbs/handles/tubes) need `attachment.parentSocket`,
+ `localStart`, `localEnd`, `contactType`, `embedDepth`/`overlap`, `gapTolerance` — no mid-air parts.
+ `references/attachment-joint-correctness.md`.
+- **Material/lighting**: `references/material-lighting-realism.md` — independent PBR channels
+ (never alias albedo into roughness/normal/AO), macro/meso/micro frequency bands, real lights.
+
+## Self-Correction
+
+After every pass, decide exactly one: `continue | refine-spec | refine-code | request-input | stop`.
+`refine-spec` fixes a wrong/missing/shallow spec (re-validate, don't patch code around it);
+`refine-code` fixes geometry/material/lighting that doesn't match a sound spec. Full root-cause
+guide + fidelity scale: `references/self-correction-loop.md`.
+
+## Implementation Rules (brief)
+
+TypeScript + plain Three.js unless the project uses a wrapper. `Group` factory
+`createObjectNameModel(spec, options)`, reconstruction data kept separate from renderer objects,
+deterministic seeds for all procedural noise. Prefer primitives / `Shape` extrude / curve+tube /
+instancing / displacement / generated canvas textures before any external art. Full geometry &
+material recipes + hard-won failure patterns: `references/procedural-patterns.md`.
+
+## Output
+
+- **Analysis-only**: suitability verdict + scores, object extraction, macro→micro hierarchy,
+ geometry strategy, material/lighting recipe, animation/destruction feasibility, plan + risks.
+- **Implementation**: the above briefly, then edit code; verify with typecheck/build + a screenshot.
+- **Not feasible**: name the blocker, ask for more views / cleaner image / accepted stylization /
+ a narrower target. "This cannot reach the requested fidelity from this image" is a valid result.
diff --git a/assets/ancient-autumn-tree-demo.png b/assets/ancient-autumn-tree-demo.png
new file mode 100644
index 0000000..68b9a3f
Binary files /dev/null and b/assets/ancient-autumn-tree-demo.png differ
diff --git a/assets/codex-prompt-example.png b/assets/codex-prompt-example.png
new file mode 100644
index 0000000..ac2cecb
Binary files /dev/null and b/assets/codex-prompt-example.png differ
diff --git a/assets/demo.gif b/assets/demo.gif
new file mode 100644
index 0000000..280acca
Binary files /dev/null and b/assets/demo.gif differ
diff --git a/assets/tower-ship-demo.png b/assets/tower-ship-demo.png
new file mode 100644
index 0000000..b9a3b01
Binary files /dev/null and b/assets/tower-ship-demo.png differ
diff --git a/references/3d-graphics-terminology.md b/references/3d-graphics-terminology.md
new file mode 100644
index 0000000..ed63ff3
--- /dev/null
+++ b/references/3d-graphics-terminology.md
@@ -0,0 +1,84 @@
+# 3D Graphics Terminology For Object Sculpt Specs
+
+Use this reference when writing or reviewing an `ObjectSculptSpec`. The goal is to describe what the agent should build in terms a Three.js/technical-artist workflow can act on.
+
+## Geometry And Topology
+
+- `silhouette`: the outer read of the object from a given camera angle.
+- `primitive family`: box, sphere, ellipsoid, cylinder, cone, capsule, torus, lathe, extrusion, tube, plane card, instanced cluster.
+- `topology intent`: hard-surface blockout, subdivision-ready surface, low-poly prop, organic deformed mesh, alpha-card cluster.
+- `bevel radius`: size of rounded edge transition in object-relative units.
+- `bevel segments`: number of edge-rounding subdivisions.
+- `chamfer`: flat angled edge cut, usually cheaper than a rounded bevel.
+- `taper`: gradual scale change along an axis.
+- `bend`: curvature deformation along an axis or spline.
+- `twist`: rotational deformation along an axis.
+- `boolean cut`: subtractive shape such as hole, notch, slot, recess, or carved opening.
+- `edge loop`: repeated ring/path of vertices used to support shape or deformation.
+- `local deformation`: localized dent, swelling, pinch, warp, sag, or buckle.
+- `displacement`: geometry-level height movement that can affect silhouette.
+- `normal strategy`: vertex normals, weighted normals, flat shading, generated tangent-space normal.
+- `UV strategy`: generated procedural coordinates, cylindrical projection, triplanar-like mapping, atlas-ready unwrapped regions.
+
+## Material And PBR
+
+- `albedo` / `baseColor`: diffuse color independent of lighting.
+- `roughness`: microfacet scatter; high roughness is matte, low roughness is glossy.
+- `metalness`: whether material behaves as conductive metal in PBR.
+- `normal map`: tangent-space normal detail that changes lighting without changing silhouette.
+- `bump map`: height-derived normal detail, usually procedural and cheaper than displacement.
+- `displacement map`: geometry displacement; use only when relief should affect silhouette or close-up shape.
+- `ambient occlusion`: darkening in creases, contact zones, and cavities.
+- `cavity dirt`: localized dark/dusty buildup in recessed areas.
+- `edge wear`: exposed lighter/polished/damaged material on protruding edges.
+- `clearcoat`: secondary glossy layer over base material.
+- `transmission`: light passing through transparent/translucent material.
+- `alpha`: opacity or cutout transparency.
+- `anisotropy`: directional highlight stretch, useful for brushed metal or fibers.
+- `procedural noise scale`: spatial frequency of generated variation.
+- `local mask`: region-specific control for color, roughness, dirt, wear, or bump.
+
+## Surface Local Features
+
+- `raised ridge`: geometry or normal detail protruding from surface.
+- `recessed groove`: carved or shadowed line cut into the surface.
+- `seam line`: boundary between joined pieces or material panels.
+- `scratch cluster`: group of thin directional marks affecting albedo/roughness/normal.
+- `chip`: broken missing piece, often with exposed underlayer.
+- `dent`: inward local deformation.
+- `stain`: local albedo/roughness color change without strong geometry change.
+- `contact wear`: abrasion where object touches ground, hands, joints, or other parts.
+- `decal region`: image/text/logo-like area; approximate with colored planes or generated texture unless exact fidelity is required.
+
+## Lighting And Rendering
+
+- `key light`: dominant light source.
+- `fill light`: softer light used to lift shadows.
+- `rim light`: back/side light that outlines silhouette.
+- `environment reflection`: skybox/HDRI-like reflection source.
+- `contact shadow`: near-surface shadow grounding the object.
+- `shadow softness`: blur/spread of shadow edge.
+- `color temperature`: warm/cool light tint.
+- `exposure`: scene brightness scale.
+- `tone mapping`: output transform affecting contrast and highlights.
+
+## Animation, Physics, And Destruction
+
+- `pivot`: local rotation origin.
+- `hinge`: constrained rotation joint.
+- `socket`: attachment point for a child part.
+- `collider`: simplified physics shape.
+- `rigid body`: simulated physical body.
+- `fracture seam`: planned break line.
+- `detachable fragment`: piece that can separate during destruction.
+- `impulse direction`: force vector used to trigger movement or breakage.
+
+## Writing Rule
+
+Bad: `the surface is ugly and too smooth`.
+
+Better: `increase microRoughness to 0.45, add tangent-space fine-noise normal with strength 0.2 and scale 32, add low-frequency albedo mottling at amplitude 0.12, and add cavity dirt local masks in recessed grooves`.
+
+Bad: `make the edges realistic`.
+
+Better: `add 0.025 relative bevel radius with 3 segments on exposed hard-surface edges, add edge-wear local overrides on bevel crests, and keep internal seams sharper with 1-segment chamfers`.
diff --git a/references/action-ready-models.md b/references/action-ready-models.md
new file mode 100644
index 0000000..28cb4df
--- /dev/null
+++ b/references/action-ready-models.md
@@ -0,0 +1,53 @@
+# Action-Ready Procedural Models
+
+Use this reference when a procedural Three.js model may later need animation, transformation, physics, or destruction.
+
+## Design Goal
+
+The generated model should be a runtime-ready hierarchy, not a single decorative mesh. Future actions should be added by targeting named nodes, sockets, colliders, and destruction groups instead of rewriting the reconstruction.
+
+## Hierarchy Pattern
+
+Use this structure:
+
+- `root`: whole-object motion, visibility, global scale, runtime metadata.
+- `component pivot Group`: stable transform node for each macro/meso component.
+- `visual mesh`: child of the component pivot; holds geometry and material.
+- `socket Object3D`: child of the relevant pivot; marks attachment, effect, grip, or joint positions.
+- collider metadata/proxy: simplified runtime shape, not necessarily a visible mesh.
+- destruction group metadata: semantic grouping for detach/break logic.
+
+## Pivot Rules
+
+- Use center pivots only when the object rotates around its center of mass.
+- Use base pivots for trees, signs, bottles, poles, legs, and upright props.
+- Use hinge pivots for lids, doors, handles, flaps, jaws, levers, and wings.
+- Use branch/root pivots for organic appendages that bend from one end.
+- Use custom pivots when the reference clearly implies a mechanical joint or socket.
+
+## Collider Rules
+
+- Use primitive proxies first: box, sphere, capsule, cylinder.
+- Use compound proxies for complex silhouettes.
+- Avoid visual mesh colliders unless the user explicitly asks for high-precision collision.
+- Mark triggers separately from solid colliders.
+- Store collider intent even when no physics engine is installed.
+
+## Destruction Rules
+
+- Break along existing seams, joints, material boundaries, weak points, or branch roots.
+- Use detachable component groups for large fragments.
+- Use procedural small fragments only where they improve readability.
+- Attach impact, spark, dust, liquid, or debris effect sockets when destruction is expected.
+- Preserve material continuity on exposed fracture faces where possible.
+
+## Acceptance Criteria
+
+An action-ready model passes when:
+
+- Every major part has a stable ID and pivot node.
+- Movable or breakable parts are not merged into unrelated geometry.
+- Sockets are named and placed in local coordinates.
+- Collider proxies exist for physics-relevant parts.
+- Destruction groups and fracture seams are explicit.
+- `root.userData.sculptRuntime` exposes maps that later code can target.
diff --git a/references/attachment-joint-correctness.md b/references/attachment-joint-correctness.md
new file mode 100644
index 0000000..8c386f8
--- /dev/null
+++ b/references/attachment-joint-correctness.md
@@ -0,0 +1,40 @@
+# Attachment And Joint Correctness
+
+Use this reference when an object has child parts attached to a parent: branches, limbs, handles, legs, horns, wings, cables, tubes, sockets, panels, hinged parts, or decorative appendages.
+
+## Problem
+
+Detached or floating child parts usually come from treating a child component as a free mesh with only `position`, `rotation`, and `scale`. For attached parts, that is not enough. The reconstruction must know where the child starts, where it ends, what parent socket it connects to, and how much it overlaps or embeds into the parent.
+
+## Attachment Contract
+
+Every child appendage, connector, limb, branch, tube, handle, leg, horn, wing, cable, or hinged part should define:
+
+- `parent`: parent component id.
+- `attachment.parentId`: same semantic parent id.
+- `attachment.parentSocket`: named socket or contact region on the parent.
+- `attachment.localStart`: child root point in parent-local coordinates.
+- `attachment.localEnd`: child tip/end point in parent-local coordinates.
+- `attachment.baseRadius` and `attachment.endRadius` when the child is tube/limb/branch-like.
+- `attachment.embedDepth` or `attachment.overlap`: how far the child penetrates or blends into the parent.
+- `attachment.contactType`: `embedded`, `socket`, `overlap`, `hinge`, `surface-contact`, or `glued`.
+- `attachment.gapTolerance`: maximum acceptable visible gap.
+- `attachment.evidenceRefs`: image regions that justify this attachment.
+
+If the attachment point cannot be inferred from the image, record that as `request-input` or lower the fidelity target. Do not silently place the part in mid-air.
+
+## Generator Rule
+
+For endpoint-based parts, place the pivot group at `localStart`, generate the visible mesh from `localStart` to `localEnd`, and orient the mesh along that direction. Do not center the mesh at an arbitrary transform position.
+
+## Screenshot Review
+
+During `structural-pass` and `form-refinement`, inspect:
+
+1. Are child roots visibly touching, overlapping, or embedded into the parent?
+2. Are there floating joints or air gaps at branch roots, handles, limbs, legs, tubes, or connectors?
+3. Does the child pivot sit at the semantic joint rather than at the center of the mesh?
+4. Does deformation/bending originate from the joint/root?
+5. Are parent sockets and child roots still aligned after rotation, scale, and animation?
+
+If floating joints are visible, choose `refine-spec` when attachment data is missing, or `refine-code` when the spec has correct attachment data but the generated mesh does not use it.
diff --git a/references/browser-screenshot-feedback.md b/references/browser-screenshot-feedback.md
new file mode 100644
index 0000000..a99d8b8
--- /dev/null
+++ b/references/browser-screenshot-feedback.md
@@ -0,0 +1,81 @@
+# Browser Screenshot Feedback
+
+Use this reference when a procedural Three.js reconstruction has a browser-renderable preview.
+
+## Capture Rule
+
+Each visual build pass should produce at least one rendered screenshot from a named review viewpoint. Use your agent's browser/screenshot tool (Claude Code browser MCP, your agent's in-app browser/preview, or the project's own preview) first. Do not install or download Playwright/Chromium just for this skill; use Playwright or another browser automation path only when the user explicitly allows it or the project already depends on it. If the in-app Browser is unavailable, ask for a screenshot path or use browser tooling that is already present in the target project.
+
+Create a side-by-side review image after capture:
+
+```bash
+../../scripts/make_visual_comparison_sheet.py \
+ --reference reference.png \
+ --render render.png \
+ --out comparison.png \
+ --json
+```
+
+The script only aligns and packages evidence. It must not calculate the acceptance score. your agent's vision must inspect `comparison.png`.
+
+Use the same full image pair to score at most five critical semantic features per pass. A feature is a subsystem such as a hull, cabin system, roof system, limb assembly, face, control panel, or sail-and-rigging system. It is not an individual mesh and does not need a separate crop. Score up to three uncertain important features only when adaptive escalation is useful.
+
+The starter spec contains generic review targets only as placeholders. Replace them with object-specific systems discovered during pre-spec assessment; otherwise strict quality validation should not pass a moderate or complex object.
+
+## Compare By Layer
+
+Review screenshot evidence in this order:
+
+1. Silhouette and proportions: bounding shape, width/height/depth cues, taper, symmetry, negative space.
+2. Component structure: parent/child placement, joints, contact points, repeated systems, floating or detached parts.
+3. Form detail: bevels, chamfers, curvature, bends, dents, seams, raised ridges, holes, deformation scale.
+4. Surface response: albedo zones, roughness variation, metalness, clearcoat, transmission, normal/bump/displacement, ambient occlusion.
+5. Local features: scratches, chips, dirt accumulation, moss, stains, color patches, edge wear, contact wear.
+6. Lighting/camera: exposure, shadow softness, contact shadows, color temperature, rim light, reflection readability.
+7. Performance tradeoff: whether missing detail is intentional because of triangle, draw call, texture, or FPS budgets.
+
+## Decision Matrix
+
+- If the screenshot reveals a missing or wrong component, choose `refine-spec`.
+- If the spec describes the component but the render does not match it, choose `refine-code`.
+- If the screenshot is too dark, too close, too far, or from the wrong viewpoint, choose `refine-code` for camera/lighting before judging model fidelity.
+- If the source image does not reveal enough geometry or material information, choose `request-input`.
+- If the screenshot matches the pass acceptance criteria and does not hide future risk, choose `continue`.
+
+`continue` is allowed only when the global AI vision score meets `selfCorrectLoop.visualAcceptance.threshold`, normally `0.7`, and every critical semantic feature meets its own threshold. A numeric or pixel-difference script may help diagnose alignment, but it cannot approve the pass.
+
+## AI Vision Scorecard
+
+Score each applicable layer from `0` to `1`, then assign one overall score based on the pass goal:
+
+- `silhouetteProportion`: outer contour, mass distribution, negative space, camera-normalized proportions.
+- `componentStructure`: hierarchy, placement, attachment, repeated systems, floating or disconnected parts.
+- `formDetail`: taper, bend, bevel, deformation, secondary forms, local geometry.
+- `materialSurface`: albedo, roughness, reflectance, normal/displacement, AO, local wear, tactile frequency.
+- `lightingCamera`: camera match, exposure, key/fill/rim balance, shadow/contact response, background.
+
+Do not hide a critical failed layer inside a high average. If a layer is essential to the current pass and remains visibly wrong, choose `refine-spec` or `refine-code` even when the arithmetic mean is above threshold.
+
+## Feature Tiers
+
+- `critical`: identity-defining, user-prioritized, visually salient, or high-risk subsystem. Must be visible in the full pair and pass independently.
+- `important`: useful secondary subsystem. Review only suspicious items; the reviewed average must meet the configured threshold.
+- `detail`: micro detail. Record mismatch notes and defer to refinement unless the user promotes it.
+
+Repeated parts should be one target when they form one recognizable system. For example, review three cabins as `cabin-system`, not three separate cabin targets.
+
+## Evidence Format
+
+Record screenshot evidence with:
+
+- `referenceScreenshot`: source image, crop, or marked-up reference path.
+- `renderScreenshot`: browser-rendered screenshot path.
+- `comparisonImage`: side-by-side evidence image reviewed by AI vision.
+- `cameraView`: named viewpoint such as `front`, `three-quarter`, `side`, `top`, or `close-up-material`.
+- `notes`: concise mismatch summary using 3D graphics terms.
+- `aiVisionScore`: overall score from `0` to `1`.
+- `layerScores`: per-layer scores from the scorecard.
+- `aiVisionNotes`: concrete matched features, mismatches, root causes, and next correction.
+- `featureReviews`: feature ID, score, visibility in the shared pair, and focused notes.
+
+Never use screenshots as decoration only. They are the ground truth for the self-correction loop.
diff --git a/references/material-lighting-realism.md b/references/material-lighting-realism.md
new file mode 100644
index 0000000..198e03d
--- /dev/null
+++ b/references/material-lighting-realism.md
@@ -0,0 +1,80 @@
+# Material And Lighting Realism
+
+Use this reference whenever the model silhouette is acceptable but the render still looks unlike the source image.
+
+## Common Failure Pattern
+
+A procedural object often fails after the shape pass because the render has:
+
+- one flat albedo color per material
+- no roughness variation or cavity response
+- no normal/bump/displacement response on surfaces that should be tactile
+- missing local overrides such as moss, stains, edge wear, dirt, sap, rust, dust, scorch, or faded zones
+- lighting that is only ambient or too evenly exposed
+- weak contact shadows, no rim separation, and no tone mapping/exposure target
+
+Treat this as a `LookDev Reset`, not a geometry problem.
+
+## Material-Pass Requirements
+
+Before implementing or accepting `material-pass`, the spec must contain:
+
+- `albedo` palette: dominant, secondary, accent colors, and where they appear on the object.
+- `roughness` response: base value, variation, and local response such as smoother worn edges or rougher cavities.
+- tactile response: at least one of `normal`, `bump`, or `displacement` with scale/amplitude/strength.
+- locality: `localOverrides`, dirt, wear, scratches, chips, stains, moss, patina, wetness, soot, or cavity masks tied to `viewEvidence`.
+- material-specific behavior: alpha/transmission/translucency for thin or transparent parts, metalness/clearcoat for reflective parts, cloth/fiber grain for fabric-like parts.
+- independent PBR channels: albedo, roughness, height/normal, and AO must be generated or authored separately; never reuse albedo as a roughness, height, normal, or AO map.
+- reference-derived PBR extraction: when a source image is available and fidelity matters, run `../../scripts/extract_reference_pbr.py` for each important material or crop before accepting material-pass. The default target threshold is `0.7`; below that, stop or request better references unless the user explicitly accepts a lower-fidelity approximation.
+- scale hierarchy: close-up materials must describe macro, meso, and micro surface-frequency bands with object-relative frequency and amplitude.
+- projection/UV intent: state UV, triplanar, cylindrical, planar, or another projection strategy, plus repeat/texel-density intent so detail does not stretch across scaled components.
+- quality-first resolution: use at least 1024px procedural maps for important close-up materials and prefer 2048px when reference fidelity is the priority.
+- geometric relief: if a ridge, crack, seam, chip, bark plate, fold, or dent affects the visible silhouette, represent it with geometry or displacement-capable topology instead of texture alone.
+
+Do not accept "brown bark", "gold leaves", "dark metal", or "rough stone" as sufficient. Translate it into PBR terms: albedo palette, roughness, normal/bump, AO, dirt/wear, and local masks.
+
+Do not claim exact PBR recovery from a single image. Pixels include baked lighting, exposure, shadow, view angle, and camera response. Treat extracted maps as reference-derived material evidence that still needs neutral/grazing/reference screenshot review.
+
+Do not accept a material merely because all required fields are present. The browser render must prove that:
+
+- roughness breaks highlights independently from albedo color
+- normal/height detail remains readable under grazing light
+- cavities and contacts have coherent AO rather than uniformly dark noise
+- referencePbr maps, when present, are loaded by the generated Three.js material and have confidence at or above the configured threshold
+- micro detail does not visibly tile or swim when the object is scaled
+- local overrides appear in the same regions supported by `viewEvidence`
+
+## Lighting-Pass Requirements
+
+Before accepting `lighting-pass`, the spec must contain:
+
+- key light direction, color temperature, intensity, and shadow softness
+- fill light color/intensity, or explicit reason for no fill
+- rim/back light or environment reflection cue when the silhouette needs separation
+- ambient/hemisphere/environment color
+- exposure and tone-mapping intent
+- background color or gradient
+- contact shadow / ground shadow behavior
+
+Separate object material from photo lighting: a material should still read correctly in neutral turntable lighting, then a reference-matching lighting setup can be added.
+
+## Screenshot Review
+
+For material and lighting screenshots, compare in this order:
+
+1. Albedo palette: are dominant and accent colors close to the reference?
+2. Value range: are dark cavities and bright highlights in the right places?
+3. Surface response: does roughness/normal/bump catch light?
+4. Locality: are moss, stains, dirt, wear, chips, or color patches placed where the reference shows them?
+5. Light structure: can you identify key, fill, rim/environment, contact shadow, and exposure?
+6. Material-vs-light split: if the scene is relit neutrally, does the object still have believable material detail?
+
+For quality-first work, capture three deliberate look-dev views before choosing `continue`:
+
+1. `neutral`: broad soft key/fill lighting for honest albedo and form reading.
+2. `grazing`: a low-angle hard or semi-hard key close-up that exposes smooth-plastic highlights, weak normals, uniform roughness, and texture tiling.
+3. `reference-match`: the source camera and lighting direction as closely as the available evidence allows.
+
+A material that only looks convincing in the reference-matched light has not passed. Fix its PBR response first, then tune the reference lighting.
+
+If the mismatch is mostly color/texture/lighting, choose `refine-code` only when the spec already has the above details. Otherwise choose `refine-spec` first.
diff --git a/references/pre-spec-assessment.md b/references/pre-spec-assessment.md
new file mode 100644
index 0000000..1a6378d
--- /dev/null
+++ b/references/pre-spec-assessment.md
@@ -0,0 +1,68 @@
+# Pre-Spec Assessment And Quality Contract
+
+Use this reference before authoring an `ObjectSculptSpec`. The purpose is to prevent shallow specs that are technically valid but too vague to recreate the reference object.
+
+Do not use fixed domain profiles. Assess the object from observed traits, complexity, and target fidelity.
+
+## Soft Object Classification
+
+Describe the object using multiple axes:
+
+- form language: organic, hard-surface, mechanical, architectural, botanical-like, character-like, amorphous, sculptural, fabric-like, transparent-like
+- structure kind: single body, compound object, branching hierarchy, repeated modules, layered shell, articulated assembly, deformable surface
+- motion potential: static prop, whole-object transform, articulated, bendable, detachable, destructible, effect-emitter
+- material families: wood, bark, leaf, metal, stone, ceramic, plastic, rubber, cloth, glass-like, liquid-like, skin-like, mixed
+
+These are descriptors, not domain templates. Use only what the image supports.
+
+## Complexity Scoring
+
+Score each axis from 0 to 3:
+
+- silhouette complexity: simple outline to heavily interrupted/organic silhouette
+- component count: one piece to many visible subparts
+- hierarchy depth: flat object to deep parent-child structure
+- repetition density: none to thousands of repeated marks/leaves/scales/rivets
+- material layer count: one material to many layered local material responses
+- local detail density: plain surface to dense scratches, bumps, moss, seams, chips, pores, or grain
+- occlusion risk: fully visible to many hidden/inferred parts
+- action readiness need: static to many pivots/sockets/colliders/destruction seams
+
+Map total judgment to:
+
+- `simple`: few parts, low detail, one or two materials
+- `moderate`: several parts, visible local detail, shallow hierarchy
+- `complex`: many parts, repeated systems, multiple materials, several hierarchy levels
+- `ultra-complex`: dense organic/mechanical/architectural structure where fidelity depends on deep hierarchy and repeated microstructure
+
+## Quality Contract
+
+Before generating code, define exactly what makes the model good enough:
+
+- definition of done for this object
+- minimum macro, meso, and micro feature counts
+- required repeated systems and their distribution rules
+- required material layers and local overrides
+- screenshot viewpoints required for visual comparison
+- failure modes that should block `continue`
+
+Good feature groups are specific to the image:
+
+- weak: `make leaves look good`
+- strong: `leaf clusters must form irregular overlapping canopy masses, with varied card size/orientation/color and gaps exposing secondary branches`
+
+- weak: `add bark texture`
+- strong: `trunk and primary branches need vertical ridges, cavity-darkened cracks, moss/lichen patches near roots and inner forks, roughness variation, and nonuniform displacement/bump`
+
+## Strict Quality Gate
+
+Run `../../scripts/validate_sculpt_spec.py spec.json --strict-quality` before code generation. The script path is relative to the skill folder.
+
+If strict validation fails:
+
+- refine `preSpecAssessment` if complexity was underestimated
+- refine `qualityContract` if definition of done is too generic
+- add missing components, material layers, repetition systems, evidence refs, or local features
+- only lower the quality bar if the user explicitly accepts a simpler approximation
+
+The gate should block code generation when the spec could describe many different objects instead of the provided reference.
diff --git a/references/procedural-patterns.md b/references/procedural-patterns.md
new file mode 100644
index 0000000..9c72915
--- /dev/null
+++ b/references/procedural-patterns.md
@@ -0,0 +1,71 @@
+# Procedural Three.js Object Patterns
+
+Use this reference only when implementing a model.
+
+## Geometry Choices
+
+- box: flat machinery, furniture, panels, blockout masses
+- sphere/ellipsoid: fruit, knobs, organic joints, rounded stones
+- cylinder/cone/capsule: trunks, pipes, limbs, handles, bottles, rockets
+- 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
+- instanced mesh: screws, rivets, leaves, needles, scales, pebbles, repeated ornaments
+- plane cards: thin leaves, feathers, labels, cloth strips, decals
+
+## Material Recipes
+
+- wood: brown base, vertical grain normal, roughness variation, darker creases, lighter worn edges
+- stone: mottled albedo, high roughness, bump/normal noise, lichen/dirt patches
+- metal: lower roughness, metalness, edge scratches, anisotropic-looking streaks via texture
+- plastic: controlled roughness, subtle color variation, bevels to catch highlights
+- leaf/plant: alpha cards or thin shape geometry, green hue variation, central vein, translucent-ish bright rim
+- water/glass: transparent material only if needed; add environment/reflection cues or it reads as a flat sheet
+
+## Material Layer Fields
+
+For each material, prefer a layered description:
+
+- `baseColor`: dominant sampled color.
+- `colorVariation`: palette, mottling pattern, amplitude, regional masks.
+- `roughness`: base value, variation amount, map/pattern source.
+- `metalness`: base value and local changes.
+- `normal`: procedural pattern, strength, scale.
+- `bump`: amplitude and scale for small tactile relief.
+- `displacement`: only for silhouette-visible or close-up relief.
+- `wear`: edge wear, scratches, chips, polish, exposed underlayer.
+- `dirt`: amount, cavity bias, color, vertical streaking, contact staining.
+- `localOverrides`: named regions where color/roughness/bump differs from the base.
+
+Local overrides should answer: where, what changes, how strong, and which image evidence supports it.
+
+## Local Feature Types
+
+Use `component.localFeatures` for details that matter to recognizability:
+
+- raised ridge
+- recessed groove
+- seam line
+- screw or rivet
+- chip or dent
+- scratch cluster
+- stain or dirt patch
+- decal or label area
+- hole or socket
+- bevel highlight
+- fabric stitch
+- leaf vein or serrated edge
+
+Each feature should include placement, approximate size, orientation, material effect, geometry effect, and confidence.
+
+## Verification Cues
+
+A procedural object is usually failing when:
+
+- silhouette reads wrong even before material
+- every edge is perfectly sharp or perfectly smooth
+- material has one flat color and no roughness variation
+- lighting hides the form instead of explaining it
+- repeated details are too evenly spaced
+- close-up details add triangles but not recognizability
diff --git a/references/scripts.md b/references/scripts.md
new file mode 100644
index 0000000..ba87ab6
--- /dev/null
+++ b/references/scripts.md
@@ -0,0 +1,72 @@
+# Scripts Cheatsheet
+
+All scripts are pure Python 3.10+ **standard library** — no pip install, no PIL/numpy, no
+Playwright/Chromium. PNG read/write is done via `struct`/`zlib`. Run from the skill root so
+paths resolve as `scripts/<name>.py`. Non-zero exit = a gate failed; read the printed reasons.
+
+Division of labor: **scripts enforce structure and package evidence; they never score visuals.**
+The acceptance score always comes from the agent's own vision inspecting the comparison sheet.
+
+## probe_reference_image.py
+`probe_reference_image.py <image>` — image type, dimensions, aspect ratio, obvious technical
+issues. Metadata only; not a substitute for visual inspection.
+
+## new_pre_spec_assessment.py
+`new_pre_spec_assessment.py "Name" [--image IMG] [--complexity simple|moderate|complex|ultra-complex] --out assessment.json [--force]`
+Emits a pre-spec assessment + `qualityContract` skeleton. Refine `--complexity` after looking at
+the image. See `pre-spec-assessment.md` for the scoring axes and contract checklist.
+
+## new_sculpt_spec.py
+`new_sculpt_spec.py "Name" [--image IMG] [--assessment assessment.json] --out object-sculpt-spec.json [--force]`
+Starter `ObjectSculptSpec` (schema 2.0). With `--assessment` it seeds from the completed gate.
+Always replace generic starter `featureReviewTargets` with real identity-defining systems.
+
+## validate_sculpt_spec.py
+`validate_sculpt_spec.py spec.json [--json] [--strict-quality]`
+Normal: checks required fields, score ranges, material refs, component IDs, parent links,
+transforms, primitive names (warnings allowed). `--strict-quality`: promotes quality warnings to
+errors — blocks code gen when the spec is too shallow for its contract (min macro/meso/micro
+counts, material layers, repetition systems, review viewpoints, non-generic feature targets,
+material-pass locality, lighting-pass real lights). Fix per `pre-spec-assessment.md`.
+
+## sculpt_pass_orchestrator.py
+- `status spec.json` — current unlocked pass + required evidence.
+- `check spec.json --pass-id <pass>` — non-zero unless that pass is unlocked or already done.
+- `sync spec.json --in-place` — recompute `sculptPipeline` from `reviewHistory`.
+
+Ordered passes: `blockout → structural-pass → form-refinement → material-pass → lighting-pass →
+interaction-pass → optimization-pass`. A pass unlocks only after the prior pass has a review with
+`action=continue` backed by a render screenshot, a comparison sheet, a global AI-vision score ≥
+threshold (default 0.7), and every critical feature ≥ its own threshold.
+
+## generate_threejs_factory.py
+`generate_threejs_factory.py spec.json --out src/createObjectModel.ts [--pass-id PASS] [--force]`
+Emits a TypeScript Three.js `Group` factory for the **current unlocked pass only**. Passing a
+future `--pass-id` fails until earlier passes are reviewed `continue`. Output exposes
+`root.userData.sculptRuntime` (nodes/meshes/sockets/colliders/destructionGroups) — hand-refine it.
+
+## make_visual_comparison_sheet.py
+`make_visual_comparison_sheet.py --reference IMG --render SHOT --out cmp.png [--panel-width N] [--panel-height N] [--gutter N] [--json]`
+Aligns + packages one side-by-side sheet. It does **not** compute an acceptance score — inspect
+`cmp.png` with agent vision and write the score back via `append_sculpt_review.py`.
+
+## append_sculpt_review.py
+`append_sculpt_review.py spec.json --pass-id PASS --fidelity 0-1 --action continue|refine-spec|refine-code|request-input|stop --summary "..." [evidence flags] --in-place`
+Evidence flags: `--matched --mismatches --spec-fixes --code-fixes --evidence --reference-screenshot
+--render-screenshot --comparison-image --ai-vision-score 0-1 --layer-scores-json '{...}'
+--feature-reviews-json f.json --ai-vision-notes "..." --visual-threshold 0-1 --camera-view NAME
+--require-screenshot-files`. Layer keys: `silhouetteProportion, componentStructure, formDetail,
+materialSurface, lightingCamera`. Records one self-correction entry into `reviewHistory`.
+
+## extract_reference_pbr.py
+`extract_reference_pbr.py <crop> --out-dir DIR --material-id ID [--target-threshold 0.7] [--size N]
+[--palette-size N] [--spec spec.json --in-place | --out-spec p.json] [--report r.json]
+[--allow-low-confidence] [--multi-view-reference]`
+Extracts reference-derived evidence: albedo palette, de-lit albedo, roughness estimate, height,
+normal, AO. **Inference, not inverse rendering** — pixels include baked lighting. Exits non-zero
+and refuses to patch the spec when confidence < `--target-threshold` (default 0.7) unless
+`--allow-low-confidence`. Treat sub-threshold as `request-input`/`refine-spec`, not a pass.
+
+## visual_feature_gate.py
+Internal helper imported by the orchestrator/validator (`feature_gate_failures`,
+`feature_review_policy`). Enforces the ≤5 critical / ≤3 important feature-tier policy. Not a CLI.
diff --git a/references/self-correction-loop.md b/references/self-correction-loop.md
new file mode 100644
index 0000000..412cc4a
--- /dev/null
+++ b/references/self-correction-loop.md
@@ -0,0 +1,68 @@
+# Self-Correction Loop Reference
+
+Use this reference when a model construction pass has just finished.
+
+## Review Order
+
+1. Capture or collect a rendered screenshot for the current browser view.
+2. Select at most five critical semantic systems for the current pass and only the suspicious important systems.
+3. Create one full reference/render comparison sheet with `make_visual_comparison_sheet.py`.
+4. Inspect the sheet once with your agent's vision and score the global image, relevant visual layers, and each selected semantic feature visible in that pair.
+5. Compare the rendered result to current `ObjectSculptSpec`.
+6. Decide whether the mismatch is caused by the spec, the implementation, lighting/camera, missing evidence, or performance tradeoff.
+7. Choose exactly one action:
+ - `continue`
+ - `refine-spec`
+ - `refine-code`
+ - `request-input`
+ - `stop`
+8. Record the screenshot paths, comparison image, overall score, layer scores, feature scores, and AI critique in `reviewHistory`.
+
+For visual passes, `continue` requires a rendered screenshot, a comparison image, a global AI vision score at or above threshold, and every critical feature at or above its own threshold. Without them, the review is not evidence-backed enough. Pixel comparison code is never the acceptance authority.
+
+## Root Cause Guide
+
+Use `refine-spec` when:
+
+- a component is missing or invented incorrectly
+- the primitive family is wrong
+- proportions or coordinate frame are wrong
+- material layer is under-specified
+- local features are missing from the spec
+- evidence refs are absent or contradict the image
+- user expectation cannot be represented by current build passes
+
+Use `refine-code` when:
+
+- the spec is clear but generated geometry is wrong
+- material parameters were not implemented
+- local masks/noise/wear are missing in code
+- hierarchy/pivots do not match the spec
+- browser render has obvious artifacts
+- performance can be improved without changing the spec
+
+Use `request-input` when:
+
+- the image hides essential geometry
+- material cannot be inferred from the provided view
+- exact branding/text/ornament is required
+- the requested fidelity is incompatible with a single image
+
+Use `stop` when:
+
+- target fidelity is reached
+- user accepted current approximation
+- remaining issues require new references, manual modeling, or non-procedural assets
+
+## Fidelity Estimate
+
+Use a practical 0-1 scale:
+
+- `0.2`: only rough primitive placeholder
+- `0.4`: silhouette recognizable, structure incomplete
+- `0.6`: macro and meso forms mostly correct, material/detail weak
+- `0.75`: object reads correctly, local details approximate
+- `0.85`: strong procedural match for real-time use
+- `0.95`: near-reference, usually requires multiple views or manual art
+
+Do not claim `0.9+` from a single ambiguous image unless the object is simple and symmetrical.
diff --git a/references/validation-rubric.md b/references/validation-rubric.md
new file mode 100644
index 0000000..ab63f56
--- /dev/null
+++ b/references/validation-rubric.md
@@ -0,0 +1,52 @@
+# Object Image Validation Rubric
+
+Use this reference when the suitability decision is unclear.
+
+## Pass
+
+- one obvious target object
+- object occupies enough of the frame
+- at least one strong silhouette
+- major materials are visible
+- hidden side can be reasonably inferred
+- target can be approximated with procedural primitives
+
+## Conditional
+
+- one view only but object has rotational symmetry
+- some occlusion but macro shape is clear
+- fine surface detail can be represented with procedural texture
+- target is organic but user accepts stylization
+- exact brand/logo/text fidelity is not required
+
+## Reject
+
+- target object is ambiguous
+- photo is a scene, not an object reference
+- important shape is hidden, cropped, blurred, or transparent
+- request demands exact mesh extraction or manufacturing-grade dimensions
+- object relies primarily on hair, smoke, liquid, glass caustics, lace, or complex cloth folds
+
+## Ask For Better Input
+
+Ask for:
+
+- front, side, and back views
+- a neutral background
+- higher resolution
+- close-ups of material/detail
+- desired style: realistic, stylized, low-poly, game prop, hero render
+
+## Complex Object Detail Standard
+
+For objects with many details, require:
+
+- macro components for the overall mass
+- meso components for visible sub-assemblies
+- micro components or local features for repeated/tiny details
+- material layer stack for every visually distinct surface
+- local overrides for stains, scratches, dirt, color changes, wear, bumps, and roughness shifts
+- confidence per component or feature
+- evidence refs to image regions
+
+If these cannot be inferred from the image, mark the spec `conditional` and list missing views or close-ups.
diff --git a/scripts/append_sculpt_review.py b/scripts/append_sculpt_review.py
new file mode 100755
index 0000000..0365e6f
--- /dev/null
+++ b/scripts/append_sculpt_review.py
@@ -0,0 +1,383 @@
+#!/usr/bin/env python3
+"""Append a self-correction review entry to an ObjectSculptSpec JSON file."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+from visual_feature_gate import feature_gate_failures
+
+
+VALID_ACTIONS = {"continue", "refine-spec", "refine-code", "request-input", "stop"}
+VISUAL_PASS_IDS = {
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+}
+DEFAULT_PASS_ORDER = [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ "optimization-pass",
+]
+
+
+def split_items(value: str | None) -> list[str]:
+ if not value:
+ return []
+ return [item.strip() for item in value.split(";") if item.strip()]
+
+
+def load_spec(path: Path) -> dict:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError("spec must be a JSON object")
+ return payload
+
+
+def load_json_argument(value: str | None, label: str) -> object | None:
+ if not value:
+ return None
+ candidate = Path(value).expanduser()
+ text = candidate.read_text(encoding="utf-8") if candidate.is_file() else value
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"{label} must be valid inline JSON or a JSON file path") from exc
+
+
+def clamp_score(value: float) -> float:
+ return max(0.0, min(1.0, float(value)))
+
+
+def is_remote_or_virtual_path(value: str) -> bool:
+ return "://" in value or value.startswith("data:") or value.startswith("blob:")
+
+
+def validate_optional_file(value: str | None, label: str) -> None:
+ if not value or is_remote_or_virtual_path(value):
+ return
+ if not Path(value).expanduser().exists():
+ raise FileNotFoundError(f"{label} does not exist: {value}")
+
+
+def visual_acceptance_threshold(spec: dict) -> float:
+ loop = spec.get("selfCorrectLoop")
+ if isinstance(loop, dict):
+ acceptance = loop.get("visualAcceptance")
+ if isinstance(acceptance, dict) and isinstance(acceptance.get("threshold"), (int, float)):
+ return clamp_score(float(acceptance["threshold"]))
+ targets = spec.get("qualityTargets")
+ if isinstance(targets, dict) and isinstance(targets.get("targetFidelity"), (int, float)):
+ return clamp_score(float(targets["targetFidelity"]))
+ return 0.7
+
+
+def visual_acceptance_config(spec: dict) -> dict:
+ loop = spec.get("selfCorrectLoop")
+ if not isinstance(loop, dict):
+ return {}
+ acceptance = loop.get("visualAcceptance")
+ return acceptance if isinstance(acceptance, dict) else {}
+
+
+def pass_order(spec: dict) -> list[str]:
+ ids: list[str] = []
+ for item in spec.get("buildPasses", []):
+ if isinstance(item, dict) and isinstance(item.get("id"), str) and item["id"].strip():
+ ids.append(item["id"])
+ return ids or DEFAULT_PASS_ORDER.copy()
+
+
+def pass_acceptance(spec: dict, pass_id: str) -> list[str]:
+ for item in spec.get("buildPasses", []):
+ if isinstance(item, dict) and item.get("id") == pass_id:
+ acceptance = item.get("acceptance", [])
+ if isinstance(acceptance, list):
+ return [str(value) for value in acceptance if str(value).strip()]
+ return []
+
+
+def pass_specific_evidence(pass_id: str) -> list[str]:
+ if pass_id in {"structural-pass", "form-refinement"}:
+ return [
+ "attachment contracts for child appendages/connectors",
+ "no floating child roots/joints in the browser screenshot",
+ ]
+ if pass_id == "material-pass":
+ return [
+ "reference-derived albedo palette with dominant, secondary, and accent colors",
+ "independent albedo, roughness, height/normal, and AO maps",
+ "macro, meso, and micro surface-frequency response at 1024px or higher",
+ "local material masks: AO, dirt, wear, stains, moss, chips, scratches, wetness, or equivalent",
+ "neutral, grazing-light close-up, and reference-matched browser screenshots",
+ ]
+ if pass_id == "surface-pass":
+ return [
+ "component surfaceDetail for tactile normal/bump/displacement and locality",
+ ]
+ if pass_id == "lighting-pass":
+ return [
+ "lightingFromPhoto with key/fill/rim or environment light",
+ "exposure, tone mapping, background, shadow softness, and contact shadow behavior",
+ ]
+ return []
+
+
+def review_completes_pass(spec: dict, entry: dict, pass_id: str) -> bool:
+ if entry.get("passId") != pass_id or entry.get("action") != "continue":
+ return False
+ visual = entry.get("visualEvidence")
+ if pass_id in VISUAL_PASS_IDS and not (isinstance(visual, dict) and visual.get("renderScreenshot")):
+ return False
+ if pass_id in VISUAL_PASS_IDS:
+ score = entry.get("aiVisionScore")
+ threshold = entry.get("visualAcceptanceThreshold", 0.7)
+ if not isinstance(score, (int, float)) or not isinstance(threshold, (int, float)):
+ return False
+ if float(score) < float(threshold):
+ return False
+ if not (isinstance(visual, dict) and visual.get("comparisonImage")):
+ return False
+ if feature_gate_failures(spec, entry, pass_id):
+ return False
+ return True
+
+
+def sync_pipeline(spec: dict) -> None:
+ ids = pass_order(spec)
+ history = spec.get("reviewHistory", [])
+ completed: list[str] = []
+ if isinstance(history, list):
+ for pass_id in ids:
+ if any(
+ isinstance(entry, dict) and review_completes_pass(spec, entry, pass_id)
+ for entry in history
+ ):
+ completed.append(pass_id)
+ else:
+ break
+ current = "complete" if len(completed) >= len(ids) else ids[len(completed)]
+ required = [] if current == "complete" else pass_acceptance(spec, current)
+ required.extend(pass_specific_evidence(current))
+ if current in VISUAL_PASS_IDS:
+ required.extend(
+ [
+ "browser render screenshot from your agent's browser/screenshot tool",
+ "single side-by-side full reference/render comparison sheet",
+ "all critical semantic feature scores at or above their thresholds",
+ "self-correction review appended with action=continue before the next pass",
+ ]
+ )
+ pipeline = spec.setdefault("sculptPipeline", {})
+ if not isinstance(pipeline, dict):
+ pipeline = {}
+ spec["sculptPipeline"] = pipeline
+ pipeline.update(
+ {
+ "passGateMode": "locked-sequential",
+ "passOrder": ids,
+ "currentPass": current,
+ "completedPasses": completed,
+ "lastCompletedPass": completed[-1] if completed else "",
+ "blockedReason": "" if current != "complete" else "all build passes completed",
+ "nextRequiredEvidence": required,
+ }
+ )
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("spec", type=Path)
+ parser.add_argument("--pass-id", required=True, help="Build pass being reviewed")
+ parser.add_argument("--fidelity", type=float, required=True, help="Estimated match score from 0 to 1")
+ parser.add_argument("--action", choices=sorted(VALID_ACTIONS), required=True)
+ parser.add_argument("--summary", required=True, help="Short review summary")
+ parser.add_argument("--matched", help="Semicolon-separated matched criteria")
+ parser.add_argument("--mismatches", help="Semicolon-separated mismatches")
+ parser.add_argument("--spec-fixes", help="Semicolon-separated spec refinement tasks")
+ parser.add_argument("--code-fixes", help="Semicolon-separated code refinement tasks")
+ parser.add_argument("--evidence", help="Semicolon-separated screenshot/image/render paths or notes")
+ parser.add_argument("--reference-screenshot", help="Reference image/screenshot path or URL used for visual comparison")
+ parser.add_argument("--render-screenshot", help="Rendered browser screenshot path or URL for this pass")
+ parser.add_argument("--comparison-image", help="Side-by-side reference/render contact sheet reviewed by AI vision")
+ parser.add_argument("--ai-vision-score", type=float, help="AI vision visual match score from 0 to 1")
+ parser.add_argument("--layer-scores-json", help="JSON object with AI vision layer scores, e.g. silhouette/material/lighting")
+ parser.add_argument("--feature-reviews-json", help="JSON array or file path containing per-feature scores from the same full image pair")
+ parser.add_argument("--ai-vision-notes", help="AI vision critique explaining the score and mismatch root causes")
+ parser.add_argument("--visual-threshold", type=float, help="Override visual acceptance threshold for this review")
+ parser.add_argument("--camera-view", help="Camera/viewpoint label, e.g. front, three-quarter, side, close-up")
+ parser.add_argument("--visual-notes", help="Short notes from screenshot comparison")
+ parser.add_argument(
+ "--require-screenshot-files",
+ action="store_true",
+ help="Require local screenshot paths to exist before writing the review",
+ )
+ parser.add_argument("--in-place", action="store_true", help="Write back to the input spec")
+ parser.add_argument("--out", type=Path, help="Output JSON path when not using --in-place")
+ args = parser.parse_args(argv)
+
+ if args.require_screenshot_files:
+ validate_optional_file(args.reference_screenshot, "--reference-screenshot")
+ validate_optional_file(args.render_screenshot, "--render-screenshot")
+ validate_optional_file(args.comparison_image, "--comparison-image")
+ if args.pass_id in VISUAL_PASS_IDS and args.action == "continue" and not args.render_screenshot:
+ raise ValueError(
+ "visual pass cannot use action=continue without --render-screenshot; "
+ "capture a browser screenshot or choose refine-code/request-input"
+ )
+
+ spec_path = args.spec.expanduser().resolve()
+ spec = load_spec(spec_path)
+ history = spec.setdefault("reviewHistory", [])
+ if not isinstance(history, list):
+ raise ValueError("reviewHistory must be an array")
+ threshold = clamp_score(args.visual_threshold) if args.visual_threshold is not None else visual_acceptance_threshold(spec)
+ layer_scores = None
+ if args.layer_scores_json:
+ layer_scores = load_json_argument(args.layer_scores_json, "--layer-scores-json")
+ if not isinstance(layer_scores, dict):
+ raise ValueError("--layer-scores-json must be a JSON object")
+ for key, value in layer_scores.items():
+ if not isinstance(key, str) or not isinstance(value, (int, float)):
+ raise ValueError("--layer-scores-json values must be numeric scores")
+ if not 0 <= float(value) <= 1:
+ raise ValueError("--layer-scores-json values must be from 0 to 1")
+ if args.ai_vision_score is not None and not 0 <= args.ai_vision_score <= 1:
+ raise ValueError("--ai-vision-score must be from 0 to 1")
+ if args.visual_threshold is not None and not 0 <= args.visual_threshold <= 1:
+ raise ValueError("--visual-threshold must be from 0 to 1")
+ feature_reviews = load_json_argument(args.feature_reviews_json, "--feature-reviews-json")
+ if feature_reviews is None:
+ feature_reviews = []
+ if not isinstance(feature_reviews, list):
+ raise ValueError("--feature-reviews-json must be a JSON array")
+ for index, review in enumerate(feature_reviews):
+ if not isinstance(review, dict):
+ raise ValueError(f"feature review {index} must be an object")
+ if not isinstance(review.get("id"), str) or not review["id"].strip():
+ raise ValueError(f"feature review {index}.id is required")
+ score = review.get("score")
+ if score is not None and (
+ not isinstance(score, (int, float)) or not 0 <= float(score) <= 1
+ ):
+ raise ValueError(f"feature review {index}.score must be from 0 to 1")
+ if args.pass_id in VISUAL_PASS_IDS and args.action == "continue":
+ if not args.comparison_image:
+ raise ValueError(
+ "visual pass cannot use action=continue without --comparison-image; "
+ "create one with make_visual_comparison_sheet.py"
+ )
+ if args.ai_vision_score is None:
+ raise ValueError(
+ "visual pass cannot use action=continue without --ai-vision-score; "
+ "AI vision must review the comparison sheet"
+ )
+ if clamp_score(args.ai_vision_score) < threshold:
+ raise ValueError(
+ f"AI vision score {clamp_score(args.ai_vision_score):.3f} is below threshold "
+ f"{threshold:.3f}; choose refine-spec/refine-code/request-input instead of continue"
+ )
+ acceptance = visual_acceptance_config(spec)
+ if acceptance.get("layerScoresRequired") is True and not layer_scores:
+ raise ValueError("visual pass cannot use action=continue without --layer-scores-json")
+ required_layers = acceptance.get("requiredLayerScores", [])
+ if isinstance(required_layers, list) and layer_scores:
+ missing_layers = [
+ layer
+ for layer in required_layers
+ if isinstance(layer, str) and layer not in layer_scores
+ ]
+ if missing_layers:
+ raise ValueError(
+ "--layer-scores-json is missing required layers: "
+ + ", ".join(missing_layers)
+ )
+
+ entry = {
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ "passId": args.pass_id,
+ "estimatedFidelity": clamp_score(args.fidelity),
+ "aiVisionScore": clamp_score(args.ai_vision_score) if args.ai_vision_score is not None else None,
+ "visualAcceptanceThreshold": threshold,
+ "layerScores": layer_scores or {},
+ "featureReviews": feature_reviews,
+ "action": args.action,
+ "summary": args.summary,
+ "matched": split_items(args.matched),
+ "mismatches": split_items(args.mismatches),
+ "specFixes": split_items(args.spec_fixes),
+ "codeFixes": split_items(args.code_fixes),
+ "evidence": split_items(args.evidence),
+ }
+ if args.pass_id in VISUAL_PASS_IDS and args.action == "continue":
+ feature_failures = feature_gate_failures(spec, entry, args.pass_id)
+ if feature_failures:
+ raise ValueError(
+ "feature-level AI vision gate failed: " + "; ".join(feature_failures)
+ )
+
+ has_visual_evidence = any(
+ [
+ args.reference_screenshot,
+ args.render_screenshot,
+ args.comparison_image,
+ args.camera_view,
+ args.visual_notes,
+ args.ai_vision_notes,
+ ]
+ )
+ if has_visual_evidence:
+ visual_evidence = {
+ "referenceScreenshot": args.reference_screenshot or spec.get("sourceImage", ""),
+ "renderScreenshot": args.render_screenshot or "",
+ "comparisonImage": args.comparison_image or "",
+ "cameraView": args.camera_view or "",
+ "notes": args.visual_notes or "",
+ "aiVisionNotes": args.ai_vision_notes or "",
+ }
+ entry["visualEvidence"] = visual_evidence
+
+ visual_history = spec.setdefault("visualEvidence", [])
+ if not isinstance(visual_history, list):
+ raise ValueError("visualEvidence must be an array")
+ visual_history.append(
+ {
+ "timestamp": entry["timestamp"],
+ "passId": args.pass_id,
+ "estimatedFidelity": entry["estimatedFidelity"],
+ "aiVisionScore": entry["aiVisionScore"],
+ "visualAcceptanceThreshold": entry["visualAcceptanceThreshold"],
+ "layerScores": entry["layerScores"],
+ "featureReviews": entry["featureReviews"],
+ **visual_evidence,
+ }
+ )
+ history.append(entry)
+ sync_pipeline(spec)
+
+ output = spec_path if args.in_place else (args.out.expanduser().resolve() if args.out else None)
+ payload = json.dumps(spec, indent=2, ensure_ascii=False) + "\n"
+ if output:
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(payload, encoding="utf-8")
+ print(output)
+ else:
+ print(payload, end="")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/extract_reference_pbr.py b/scripts/extract_reference_pbr.py
new file mode 100755
index 0000000..f97fbad
--- /dev/null
+++ b/scripts/extract_reference_pbr.py
@@ -0,0 +1,834 @@
+#!/usr/bin/env python3
+"""Extract reference-derived PBR map evidence from an object image.
+
+This is not photogrammetry and it does not claim exact inverse rendering from a
+single image. It extracts pixel evidence that is useful for procedural PBR:
+albedo palette, de-lit albedo, roughness estimate, height, normal, and AO maps.
+If the estimated confidence is below the requested target, the script exits
+non-zero and refuses to patch the sculpt spec unless --allow-low-confidence is
+passed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import zlib
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def slugify(value: str) -> str:
+ parts: list[str] = []
+ last_dash = False
+ for char in value.strip().lower():
+ if char.isalnum():
+ parts.append(char)
+ last_dash = False
+ elif not last_dash:
+ parts.append("-")
+ last_dash = True
+ return "".join(parts).strip("-") or "material"
+
+
+def clamp(value: float, minimum: float, maximum: float) -> float:
+ return max(minimum, min(maximum, value))
+
+
+def clamp01(value: float) -> float:
+ return clamp(value, 0.0, 1.0)
+
+
+def srgb_luma(rgb: tuple[int, int, int]) -> float:
+ red, green, blue = rgb
+ return (0.2126 * red + 0.7152 * green + 0.0722 * blue) / 255.0
+
+
+def color_distance(a: tuple[int, int, int], b: tuple[int, int, int]) -> float:
+ return math.sqrt(sum((a[index] - b[index]) ** 2 for index in range(3)))
+
+
+def saturation(rgb: tuple[int, int, int]) -> float:
+ high = max(rgb)
+ low = min(rgb)
+ return 0.0 if high <= 0 else (high - low) / high
+
+
+def percentile(values: list[float], fraction: float, fallback: float = 0.0) -> float:
+ if not values:
+ return fallback
+ ordered = sorted(values)
+ index = int(round(clamp01(fraction) * (len(ordered) - 1)))
+ return ordered[index]
+
+
+def median_color(samples: list[tuple[int, int, int]]) -> tuple[int, int, int]:
+ if not samples:
+ return (255, 255, 255)
+ return tuple(
+ int(percentile([float(sample[channel]) for sample in samples], 0.5))
+ for channel in range(3)
+ ) # type: ignore[return-value]
+
+
+def read_png(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
+ data = path.read_bytes()
+ if not data.startswith(PNG_SIGNATURE):
+ raise ValueError("not a PNG file")
+ cursor = len(PNG_SIGNATURE)
+ width = height = bit_depth = color_type = None
+ idat = bytearray()
+ interlace = 0
+ while cursor + 8 <= len(data):
+ length = struct.unpack(">I", data[cursor : cursor + 4])[0]
+ chunk_type = data[cursor + 4 : cursor + 8]
+ chunk_data = data[cursor + 8 : cursor + 8 + length]
+ cursor += 12 + length
+ if chunk_type == b"IHDR":
+ width, height, bit_depth, color_type, _, _, interlace = struct.unpack(">IIBBBBB", chunk_data)
+ elif chunk_type == b"IDAT":
+ idat.extend(chunk_data)
+ elif chunk_type == b"IEND":
+ break
+ if width is None or height is None or bit_depth != 8 or interlace != 0:
+ raise ValueError("unsupported PNG; expected 8-bit non-interlaced image")
+ channels_by_type = {0: 1, 2: 3, 4: 2, 6: 4}
+ if color_type not in channels_by_type:
+ raise ValueError("unsupported PNG color type; convert to RGB/RGBA first")
+ channels = channels_by_type[color_type]
+ row_bytes = width * channels
+ raw = zlib.decompress(bytes(idat))
+ rows: list[bytearray] = []
+ offset = 0
+ previous = bytearray(row_bytes)
+ for _ in range(height):
+ filter_type = raw[offset]
+ offset += 1
+ row = bytearray(raw[offset : offset + row_bytes])
+ offset += row_bytes
+ for index in range(row_bytes):
+ left = row[index - channels] if index >= channels else 0
+ up = previous[index]
+ up_left = previous[index - channels] if index >= channels else 0
+ if filter_type == 1:
+ row[index] = (row[index] + left) & 0xFF
+ elif filter_type == 2:
+ row[index] = (row[index] + up) & 0xFF
+ elif filter_type == 3:
+ row[index] = (row[index] + ((left + up) // 2)) & 0xFF
+ elif filter_type == 4:
+ predictor = paeth_predictor(left, up, up_left)
+ row[index] = (row[index] + predictor) & 0xFF
+ elif filter_type != 0:
+ raise ValueError(f"unsupported PNG filter {filter_type}")
+ rows.append(row)
+ previous = row
+ pixels: list[tuple[int, int, int, int]] = []
+ for row in rows:
+ for x in range(width):
+ base = x * channels
+ if color_type == 0:
+ gray = row[base]
+ pixels.append((gray, gray, gray, 255))
+ elif color_type == 2:
+ pixels.append((row[base], row[base + 1], row[base + 2], 255))
+ elif color_type == 4:
+ gray = row[base]
+ pixels.append((gray, gray, gray, row[base + 1]))
+ elif color_type == 6:
+ pixels.append((row[base], row[base + 1], row[base + 2], row[base + 3]))
+ return width, height, pixels
+
+
+def paeth_predictor(a: int, b: int, c: int) -> int:
+ p = a + b - c
+ pa = abs(p - a)
+ pb = abs(p - b)
+ pc = abs(p - c)
+ if pa <= pb and pa <= pc:
+ return a
+ if pb <= pc:
+ return b
+ return c
+
+
+def write_png_rgb(path: Path, width: int, height: int, rgb: bytes) -> None:
+ if len(rgb) != width * height * 3:
+ raise ValueError("RGB payload has the wrong size")
+ path.parent.mkdir(parents=True, exist_ok=True)
+
+ def chunk(kind: bytes, payload: bytes) -> bytes:
+ checksum = zlib.crc32(kind)
+ checksum = zlib.crc32(payload, checksum) & 0xFFFFFFFF
+ return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", checksum)
+
+ scanlines = bytearray()
+ stride = width * 3
+ for y in range(height):
+ scanlines.append(0)
+ scanlines.extend(rgb[y * stride : (y + 1) * stride])
+ ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
+ path.write_bytes(
+ PNG_SIGNATURE
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(scanlines), level=6))
+ + chunk(b"IEND", b"")
+ )
+
+
+def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]], list[str]]:
+ warnings: list[str] = []
+ try:
+ return (*read_png(path), warnings)
+ except Exception as direct_error:
+ sips = shutil.which("sips")
+ if not sips:
+ raise ValueError(
+ f"could not decode {path.name} as PNG and macOS sips is unavailable: {direct_error}"
+ ) from direct_error
+ with tempfile.TemporaryDirectory() as tmpdir:
+ converted = Path(tmpdir) / "converted.png"
+ command = [sips, "-s", "format", "png", str(path), "--out", str(converted)]
+ result = subprocess.run(command, capture_output=True, text=True, check=False)
+ if result.returncode != 0:
+ raise ValueError(result.stderr.strip() or result.stdout.strip() or "sips conversion failed")
+ warnings.append("source image was converted to PNG with macOS sips before pixel extraction")
+ width, height, pixels = read_png(converted)
+ return width, height, pixels, warnings
+
+
+def sample_corner_background(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+) -> tuple[tuple[int, int, int], float]:
+ radius = max(3, min(width, height) // 40)
+ samples: list[tuple[int, int, int]] = []
+ corner_ranges = [
+ (0, radius, 0, radius),
+ (width - radius, width, 0, radius),
+ (0, radius, height - radius, height),
+ (width - radius, width, height - radius, height),
+ ]
+ for x0, x1, y0, y1 in corner_ranges:
+ for y in range(max(0, y0), min(height, y1)):
+ for x in range(max(0, x0), min(width, x1)):
+ red, green, blue, alpha = pixels[y * width + x]
+ if alpha > 16:
+ samples.append((red, green, blue))
+ background = median_color(samples)
+ noise = percentile([color_distance(sample, background) for sample in samples], 0.75, 0.0)
+ return background, noise
+
+
+def build_foreground_mask(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+) -> tuple[list[bool], dict[str, Any], list[str]]:
+ warnings: list[str] = []
+ alpha_values = [pixel[3] for pixel in pixels]
+ transparent_fraction = sum(1 for alpha in alpha_values if alpha < 245) / max(1, len(alpha_values))
+ background, background_noise = sample_corner_background(width, height, pixels)
+ threshold = max(24.0, background_noise * 2.4)
+ mask: list[bool] = []
+ if transparent_fraction > 0.03:
+ for red, green, blue, alpha in pixels:
+ mask.append(alpha > 24)
+ else:
+ for red, green, blue, alpha in pixels:
+ rgb = (red, green, blue)
+ distance = color_distance(rgb, background)
+ sat = saturation(rgb)
+ luma = srgb_luma(rgb)
+ mask.append(alpha > 16 and (distance > threshold or (sat > 0.16 and luma < 0.94)))
+ coverage = sum(1 for value in mask if value) / max(1, len(mask))
+ if coverage < 0.035:
+ warnings.append("foreground mask is tiny; material extraction is likely unreliable")
+ mask = [pixel[3] > 16 for pixel in pixels]
+ coverage = sum(1 for value in mask if value) / max(1, len(mask))
+ if coverage > 0.9:
+ warnings.append("image is not clearly isolated from background; using most pixels as material evidence")
+ return (
+ mask,
+ {
+ "backgroundColor": rgb_to_hex(background),
+ "backgroundNoise": round(background_noise, 3),
+ "transparentPixelFraction": round(transparent_fraction, 4),
+ "foregroundCoverage": round(coverage, 4),
+ },
+ warnings,
+ )
+
+
+def mask_bbox(width: int, height: int, mask: list[bool]) -> tuple[int, int, int, int]:
+ xs: list[int] = []
+ ys: list[int] = []
+ for index, value in enumerate(mask):
+ if value:
+ ys.append(index // width)
+ xs.append(index % width)
+ if not xs or not ys:
+ return (0, 0, width, height)
+ padding = max(2, min(width, height) // 80)
+ x0 = max(0, min(xs) - padding)
+ y0 = max(0, min(ys) - padding)
+ x1 = min(width, max(xs) + padding + 1)
+ y1 = min(height, max(ys) + padding + 1)
+ return (x0, y0, max(1, x1 - x0), max(1, y1 - y0))
+
+
+def resample_crop(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+ mask: list[bool],
+ bbox: tuple[int, int, int, int],
+ size: int,
+) -> tuple[list[tuple[int, int, int]], list[bool]]:
+ x0, y0, crop_w, crop_h = bbox
+ sampled_pixels: list[tuple[int, int, int]] = []
+ sampled_mask: list[bool] = []
+ for y in range(size):
+ source_y = y0 + (y + 0.5) * crop_h / size
+ sy = min(height - 1, max(0, int(source_y)))
+ for x in range(size):
+ source_x = x0 + (x + 0.5) * crop_w / size
+ sx = min(width - 1, max(0, int(source_x)))
+ index = sy * width + sx
+ red, green, blue, alpha = pixels[index]
+ sampled_pixels.append((red, green, blue))
+ sampled_mask.append(mask[index] and alpha > 16)
+ return sampled_pixels, sampled_mask
+
+
+def representative_samples(
+ pixels: list[tuple[int, int, int]],
+ mask: list[bool],
+ limit: int = 7000,
+) -> list[tuple[int, int, int]]:
+ candidates = [pixel for pixel, keep in zip(pixels, mask) if keep]
+ if not candidates:
+ candidates = pixels
+ if len(candidates) <= limit:
+ return candidates
+ step = max(1, len(candidates) // limit)
+ return candidates[::step][:limit]
+
+
+def kmeans_palette(samples: list[tuple[int, int, int]], k: int = 5) -> list[str]:
+ if not samples:
+ return ["#8A7A5F"]
+ ordered = sorted(samples, key=lambda rgb: (srgb_luma(rgb), rgb[0], rgb[1], rgb[2]))
+ centers = [
+ ordered[int((index + 0.5) * (len(ordered) - 1) / k)]
+ for index in range(k)
+ ]
+ for _ in range(8):
+ groups: list[list[tuple[int, int, int]]] = [[] for _ in centers]
+ for sample in samples:
+ nearest = min(range(len(centers)), key=lambda idx: color_distance(sample, centers[idx]))
+ groups[nearest].append(sample)
+ new_centers: list[tuple[int, int, int]] = []
+ for group, center in zip(groups, centers):
+ if not group:
+ new_centers.append(center)
+ continue
+ new_centers.append(
+ tuple(int(round(sum(sample[channel] for sample in group) / len(group))) for channel in range(3))
+ ) # type: ignore[arg-type]
+ centers = new_centers
+ counts = Counter(
+ min(range(len(centers)), key=lambda idx: color_distance(sample, centers[idx]))
+ for sample in samples
+ )
+ palette = [rgb_to_hex(centers[index]) for index, _ in counts.most_common()]
+ return palette[:k]
+
+
+def rgb_to_hex(rgb: tuple[int, int, int]) -> str:
+ return "#{:02X}{:02X}{:02X}".format(*rgb)
+
+
+def blur_scalar(values: list[float], size: int, radius: int) -> list[float]:
+ if radius <= 0:
+ return values[:]
+ horizontal = [0.0] * (size * size)
+ for y in range(size):
+ row_offset = y * size
+ running = 0.0
+ count = 0
+ for x in range(-radius, size + radius):
+ if 0 <= x < size:
+ running += values[row_offset + x]
+ count += 1
+ remove = x - radius * 2 - 1
+ if 0 <= remove < size:
+ running -= values[row_offset + remove]
+ count -= 1
+ write_x = x - radius
+ if 0 <= write_x < size:
+ horizontal[row_offset + write_x] = running / max(1, count)
+ vertical = [0.0] * (size * size)
+ for x in range(size):
+ running = 0.0
+ count = 0
+ for y in range(-radius, size + radius):
+ if 0 <= y < size:
+ running += horizontal[y * size + x]
+ count += 1
+ remove = y - radius * 2 - 1
+ if 0 <= remove < size:
+ running -= horizontal[remove * size + x]
+ count -= 1
+ write_y = y - radius
+ if 0 <= write_y < size:
+ vertical[write_y * size + x] = running / max(1, count)
+ return vertical
+
+
+def make_maps(
+ pixels: list[tuple[int, int, int]],
+ mask: list[bool],
+ size: int,
+ palette: list[str],
+) -> tuple[dict[str, bytes], dict[str, Any]]:
+ masked_lumas = [srgb_luma(pixel) for pixel, keep in zip(pixels, mask) if keep]
+ fallback_luma = percentile(masked_lumas, 0.5, 0.55)
+ fallback_color = hex_to_rgb(palette[0] if palette else "#8A7A5F")
+ lumas = [srgb_luma(pixel) if keep else fallback_luma for pixel, keep in zip(pixels, mask)]
+ blur_radius = max(4, min(28, size // 48))
+ low_frequency = blur_scalar(lumas, size, blur_radius)
+ p05 = percentile(masked_lumas, 0.05, 0.2)
+ p95 = percentile(masked_lumas, 0.95, 0.8)
+ value_range = max(0.08, p95 - p05)
+ high_pass = [
+ clamp((luma - low + value_range * 0.5) / value_range, 0.0, 1.0)
+ for luma, low in zip(lumas, low_frequency)
+ ]
+ height = blur_scalar(high_pass, size, max(1, size // 256))
+ gradient_values: list[float] = []
+ for y in range(size):
+ for x in range(size):
+ left = height[y * size + max(0, x - 1)]
+ right = height[y * size + min(size - 1, x + 1)]
+ up = height[max(0, y - 1) * size + x]
+ down = height[min(size - 1, y + 1) * size + x]
+ gradient_values.append(math.sqrt((right - left) ** 2 + (down - up) ** 2))
+ grad_p90 = percentile(gradient_values, 0.9, 0.0)
+ normal_strength = clamp(10.0 + grad_p90 * 75.0, 10.0, 38.0)
+ albedo = bytearray()
+ roughness = bytearray()
+ height_map = bytearray()
+ normal = bytearray()
+ ao = bytearray()
+ roughness_values: list[float] = []
+ for index, ((red, green, blue), keep) in enumerate(zip(pixels, mask)):
+ luma = lumas[index]
+ shade = clamp(low_frequency[index], 0.08, 1.0)
+ scale = clamp((fallback_luma / shade) ** 0.42, 0.72, 1.35)
+ if keep:
+ out_r = clamp(red * scale, 0, 255)
+ out_g = clamp(green * scale, 0, 255)
+ out_b = clamp(blue * scale, 0, 255)
+ else:
+ out_r, out_g, out_b = fallback_color
+ albedo.extend((round(out_r), round(out_g), round(out_b)))
+ h = height[index]
+ local_gradient = gradient_values[index]
+ bright_highlight = max(0.0, luma - p95) / max(0.02, 1.0 - p95)
+ rough = clamp01(0.68 + min(0.22, local_gradient * 2.6) + (0.5 - h) * 0.12 - bright_highlight * 0.22)
+ roughness_values.append(rough)
+ rough_byte = round(rough * 255)
+ roughness.extend((rough_byte, rough_byte, rough_byte))
+ height_byte = round(h * 255)
+ height_map.extend((height_byte, height_byte, height_byte))
+ for y in range(size):
+ for x in range(size):
+ index = y * size + x
+ left = height[y * size + max(0, x - 1)]
+ right = height[y * size + min(size - 1, x + 1)]
+ up = height[max(0, y - 1) * size + x]
+ down = height[min(size - 1, y + 1) * size + x]
+ dx = (right - left) * normal_strength
+ dy = (down - up) * normal_strength
+ inv_len = 1.0 / math.sqrt(dx * dx + dy * dy + 1.0)
+ nx = -dx * inv_len
+ ny = -dy * inv_len
+ nz = inv_len
+ normal.extend(
+ (
+ round((nx * 0.5 + 0.5) * 255),
+ round((ny * 0.5 + 0.5) * 255),
+ round((nz * 0.5 + 0.5) * 255),
+ )
+ )
+ neighbors = (
+ left
+ + right
+ + up
+ + down
+ ) * 0.25
+ cavity = max(0.0, neighbors - height[index])
+ ao_value = clamp01(1.0 - cavity * 8.0 - max(0.0, 0.35 - height[index]) * 0.16)
+ ao_byte = round(ao_value * 255)
+ ao.extend((ao_byte, ao_byte, ao_byte))
+ return (
+ {
+ "albedo": bytes(albedo),
+ "roughness": bytes(roughness),
+ "height": bytes(height_map),
+ "normal": bytes(normal),
+ "ao": bytes(ao),
+ },
+ {
+ "valueRange": round(value_range, 4),
+ "heightP90Gradient": round(grad_p90, 5),
+ "roughnessBase": round(percentile(roughness_values, 0.5, 0.72), 3),
+ "roughnessVariation": round(max(0.05, percentile(roughness_values, 0.85, 0.82) - percentile(roughness_values, 0.15, 0.62)), 3),
+ "normalStrength": round(normal_strength / 64.0, 3),
+ "blurRadius": blur_radius,
+ },
+ )
+
+
+def hex_to_rgb(value: str) -> tuple[int, int, int]:
+ if len(value) == 4 and value.startswith("#"):
+ return tuple(int(char * 2, 16) for char in value[1:]) # type: ignore[return-value]
+ if len(value) == 7 and value.startswith("#"):
+ return (int(value[1:3], 16), int(value[3:5], 16), int(value[5:7], 16))
+ return (138, 122, 95)
+
+
+def surface_bands_from_stats(stats: dict[str, Any]) -> list[dict[str, Any]]:
+ value_range = float(stats.get("valueRange", 0.4))
+ detail = float(stats.get("heightP90Gradient", 0.02))
+ return [
+ {
+ "id": "macro",
+ "frequency": 2.0,
+ "amplitude": round(clamp(0.28 + value_range * 0.35, 0.22, 0.52), 3),
+ "role": "reference-derived broad albedo and height breakup",
+ },
+ {
+ "id": "meso",
+ "frequency": 14.0,
+ "amplitude": round(clamp(0.15 + detail * 4.2, 0.12, 0.35), 3),
+ "role": "reference-derived cracks, ridges, pores, grain, or leaf clusters",
+ },
+ {
+ "id": "micro",
+ "frequency": 72.0,
+ "amplitude": round(clamp(0.055 + detail * 2.4, 0.045, 0.14), 3),
+ "role": "reference-derived micro highlight breakup under grazing light",
+ },
+ ]
+
+
+def estimate_confidence(
+ width: int,
+ height: int,
+ mask_diagnostics: dict[str, Any],
+ stats: dict[str, Any],
+ warnings: list[str],
+ single_image: bool,
+) -> tuple[float, list[str]]:
+ confidence_notes: list[str] = []
+ min_dim = min(width, height)
+ resolution_score = clamp(min_dim / 1024.0, 0.35, 1.0)
+ coverage = float(mask_diagnostics.get("foregroundCoverage", 1.0))
+ if 0.08 <= coverage <= 0.82:
+ mask_score = 1.0
+ elif 0.035 <= coverage < 0.08:
+ mask_score = 0.55
+ confidence_notes.append("foreground mask is very small")
+ elif coverage > 0.9:
+ mask_score = 0.68
+ confidence_notes.append("object/background separation is weak")
+ else:
+ mask_score = 0.78
+ value_range = float(stats.get("valueRange", 0.0))
+ dynamic_score = clamp(value_range / 0.48, 0.35, 1.0)
+ detail_score = clamp(float(stats.get("heightP90Gradient", 0.0)) * 52.0, 0.35, 1.0)
+ warning_penalty = min(0.16, len(warnings) * 0.035)
+ single_image_cap = 0.86 if single_image else 0.93
+ confidence = (
+ 0.44
+ + resolution_score * 0.14
+ + mask_score * 0.14
+ + dynamic_score * 0.12
+ + detail_score * 0.16
+ - warning_penalty
+ )
+ confidence = min(single_image_cap, clamp01(confidence))
+ if single_image:
+ confidence_notes.append("single-image inverse rendering cannot prove true physical PBR; confidence is capped")
+ if dynamic_score < 0.5:
+ confidence_notes.append("low value range weakens height/roughness inference")
+ if detail_score < 0.5:
+ confidence_notes.append("low high-frequency detail weakens normal/roughness inference")
+ return round(confidence, 3), confidence_notes
+
+
+def map_url(url_prefix: str, filename: str) -> str:
+ if not url_prefix:
+ return filename
+ return url_prefix.rstrip("/") + "/" + filename
+
+
+def material_patch(
+ material_id: str,
+ image: Path,
+ out_dir: Path,
+ url_prefix: str,
+ size: int,
+ threshold: float,
+ confidence: float,
+ verdict: str,
+ palette: list[str],
+ map_stats: dict[str, Any],
+ diagnostics: dict[str, Any],
+ warnings: list[str],
+) -> dict[str, Any]:
+ prefix = slugify(material_id)
+ maps = {
+ channel: {
+ "path": str((out_dir / f"{prefix}_{channel}.png").resolve()),
+ "url": map_url(url_prefix, f"{prefix}_{channel}.png"),
+ "channel": channel,
+ "source": "reference-pixel-extraction",
+ }
+ for channel in ("albedo", "roughness", "height", "normal", "ao")
+ }
+ usable = confidence >= threshold
+ return {
+ "referencePbr": {
+ "version": "1.0",
+ "sourceImage": str(image.resolve()),
+ "extractor": "extract_reference_pbr.py",
+ "method": "single-image pixel evidence with de-lighting estimate; not photogrammetry",
+ "usable": usable,
+ "verdict": verdict,
+ "confidence": confidence,
+ "estimatedFidelity": confidence,
+ "targetThreshold": threshold,
+ "hardLimit": "A single image cannot uniquely recover true albedo/roughness/normal/AO; maps are reference-derived estimates.",
+ "maps": maps,
+ "diagnostics": diagnostics,
+ "warnings": warnings,
+ },
+ "textureResolution": size,
+ "albedo": {
+ "dominant": palette[0],
+ "secondary": palette[1:4],
+ "samplingNotes": "Reference-derived from foreground pixels; de-lit to reduce baked shadows/highlights.",
+ "map": maps["albedo"],
+ },
+ "colorVariation": {
+ "palette": palette,
+ "pattern": "reference-derived pixel palette",
+ "amplitude": round(clamp(float(map_stats.get("valueRange", 0.4)) * 0.42, 0.08, 0.35), 3),
+ "heightCorrelation": 0.42,
+ },
+ "roughness": {
+ "base": map_stats["roughnessBase"],
+ "variation": map_stats["roughnessVariation"],
+ "map": maps["roughness"],
+ "localResponse": "reference-derived roughness estimate; cavities and textured zones trend rougher, bright highlights trend smoother",
+ },
+ "normal": {
+ "pattern": "reference-derived height-gradient normal map",
+ "strength": map_stats["normalStrength"],
+ "map": maps["normal"],
+ "heightSource": maps["height"],
+ "space": "tangent",
+ },
+ "bump": {
+ "pattern": "reference-derived height field",
+ "amplitude": round(clamp(float(map_stats.get("heightP90Gradient", 0.02)) * 0.45, 0.01, 0.08), 3),
+ "map": maps["height"],
+ },
+ "ambientOcclusion": {
+ "cavityStrength": 0.38,
+ "contactShadowBias": 0.35,
+ "map": maps["ao"],
+ "notes": "Reference-derived cavity estimate from local height minima; verify against grazing-light screenshot.",
+ },
+ "surfaceFrequencyBands": surface_bands_from_stats(map_stats),
+ "localOverrides": [
+ {
+ "id": "reference-pbr-pixel-evidence",
+ "type": "material-map-evidence",
+ "evidenceRefs": ["full-object"],
+ "channels": ["albedo", "roughness", "height", "normal", "ambient-occlusion"],
+ "notes": "Use generated maps as material evidence, then refine after browser screenshot comparison.",
+ }
+ ],
+ "shaderNotes": [
+ "Reference-derived maps are estimates from image pixels; verify with neutral, grazing, and reference-matched renders.",
+ "Do not treat baked image shadows as final albedo; rerun extraction with a tighter material crop if highlights/shadows pollute the maps.",
+ ],
+ }
+
+
+def merge_material_patch(spec: dict[str, Any], material_id: str, patch: dict[str, Any]) -> None:
+ materials = spec.get("materials")
+ if not isinstance(materials, list):
+ raise ValueError("spec.materials must be an array")
+ material = next(
+ (item for item in materials if isinstance(item, dict) and item.get("id") == material_id),
+ None,
+ )
+ if material is None:
+ raise ValueError(f"could not find material {material_id!r} in spec")
+ for key, value in patch.items():
+ if key == "localOverrides" and isinstance(material.get(key), list) and isinstance(value, list):
+ material[key].extend(value)
+ elif key == "shaderNotes" and isinstance(material.get(key), list) and isinstance(value, list):
+ material[key].extend(value)
+ else:
+ material[key] = value
+ history = spec.setdefault("pbrExtractionHistory", [])
+ if isinstance(history, list):
+ history.append(
+ {
+ "materialId": material_id,
+ "confidence": patch["referencePbr"]["confidence"],
+ "verdict": patch["referencePbr"]["verdict"],
+ "usable": patch["referencePbr"]["usable"],
+ "maps": patch["referencePbr"]["maps"],
+ }
+ )
+
+
+def extract(args: argparse.Namespace) -> tuple[dict[str, Any], dict[str, Any]]:
+ image = args.image.expanduser().resolve()
+ if not image.exists():
+ raise ValueError(f"{image} does not exist")
+ size = int(2 ** round(math.log2(args.size)))
+ size = max(256, min(2048, size))
+ out_dir = args.out_dir.expanduser().resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ width, height, source_pixels, load_warnings = load_image(image)
+ mask, mask_diag, mask_warnings = build_foreground_mask(width, height, source_pixels)
+ bbox = mask_bbox(width, height, mask)
+ sampled_pixels, sampled_mask = resample_crop(width, height, source_pixels, mask, bbox, size)
+ samples = representative_samples(sampled_pixels, sampled_mask)
+ palette = kmeans_palette(samples, max(2, min(6, args.palette_size)))
+ maps, map_stats = make_maps(sampled_pixels, sampled_mask, size, palette)
+ for channel, payload in maps.items():
+ write_png_rgb(out_dir / f"{slugify(args.material_id)}_{channel}.png", size, size, payload)
+ warnings = load_warnings + mask_warnings
+ diagnostics = {
+ "sourceWidth": width,
+ "sourceHeight": height,
+ "mapSize": size,
+ "cropBBoxPixels": {
+ "x": bbox[0],
+ "y": bbox[1],
+ "width": bbox[2],
+ "height": bbox[3],
+ },
+ "mask": mask_diag,
+ "mapStats": map_stats,
+ "palette": palette,
+ }
+ confidence, confidence_notes = estimate_confidence(
+ width,
+ height,
+ mask_diag,
+ map_stats,
+ warnings,
+ single_image=not args.multi_view_reference,
+ )
+ warnings.extend(confidence_notes)
+ threshold = clamp01(args.target_threshold)
+ verdict = "pass" if confidence >= threshold else ("conditional" if confidence >= threshold - 0.12 else "reject")
+ patch = material_patch(
+ args.material_id,
+ image,
+ out_dir,
+ args.url_prefix,
+ size,
+ threshold,
+ confidence,
+ verdict,
+ palette,
+ map_stats,
+ diagnostics,
+ warnings,
+ )
+ report = {
+ "ok": confidence >= threshold,
+ "verdict": verdict,
+ "confidence": confidence,
+ "estimatedFidelity": confidence,
+ "targetThreshold": threshold,
+ "materialId": args.material_id,
+ "sourceImage": str(image),
+ "outDir": str(out_dir),
+ "palette": palette,
+ "maps": patch["referencePbr"]["maps"],
+ "diagnostics": diagnostics,
+ "warnings": warnings,
+ "limitation": "single-image PBR extraction is an estimate; 70%+ extraction confidence still needs render screenshot review",
+ }
+ return report, patch
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("image", type=Path)
+ parser.add_argument("--out-dir", type=Path, required=True)
+ parser.add_argument("--material-id", default="base")
+ parser.add_argument("--size", type=int, default=1024)
+ parser.add_argument("--palette-size", type=int, default=5)
+ parser.add_argument("--target-threshold", type=float, default=0.7)
+ parser.add_argument("--url-prefix", default="")
+ parser.add_argument("--spec", type=Path, help="Optional ObjectSculptSpec JSON to patch")
+ parser.add_argument("--in-place", action="store_true", help="Patch --spec in place when confidence passes")
+ parser.add_argument("--out-spec", type=Path, help="Write patched spec to this path")
+ parser.add_argument("--report", type=Path, help="Write extraction report JSON")
+ parser.add_argument("--allow-low-confidence", action="store_true", help="Patch/write even when confidence is below threshold")
+ parser.add_argument("--multi-view-reference", action="store_true", help="Raise confidence cap when image belongs to a multi-view reference set")
+ args = parser.parse_args(argv)
+
+ try:
+ report, patch = extract(args)
+ if args.report:
+ args.report.expanduser().resolve().parent.mkdir(parents=True, exist_ok=True)
+ args.report.expanduser().resolve().write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ if args.spec:
+ if not report["ok"] and not args.allow_low_confidence:
+ raise ValueError(
+ f"PBR extraction confidence {report['confidence']} is below target "
+ f"{report['targetThreshold']}; spec was not patched"
+ )
+ spec_path = args.spec.expanduser().resolve()
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+ if not isinstance(spec, dict):
+ raise ValueError("spec must be a JSON object")
+ merge_material_patch(spec, args.material_id, patch)
+ output = spec_path if args.in_place else (args.out_spec.expanduser().resolve() if args.out_spec else None)
+ if output:
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps(report, indent=2, ensure_ascii=False))
+ return 0 if report["ok"] or args.allow_low_confidence else 1
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/generate_threejs_factory.py b/scripts/generate_threejs_factory.py
new file mode 100755
index 0000000..2ac9298
--- /dev/null
+++ b/scripts/generate_threejs_factory.py
@@ -0,0 +1,905 @@
+#!/usr/bin/env python3
+"""Generate a TypeScript Three.js factory skeleton from an ObjectSculptSpec."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from sculpt_pass_orchestrator import pass_specific_gaps
+
+
+VALID_PRIMITIVES = {
+ "box",
+ "sphere",
+ "ellipsoid",
+ "cylinder",
+ "cone",
+ "capsule",
+ "torus",
+ "tube",
+ "lathe",
+ "extrude",
+ "curve-sweep",
+ "plane-card",
+ "instanced-cluster",
+}
+DEFAULT_PASS_ORDER = [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ "optimization-pass",
+]
+VISUAL_PASS_IDS = set(DEFAULT_PASS_ORDER) - {"optimization-pass"}
+PASS_LEVELS = {
+ "blockout": {"macro"},
+ "structural-pass": {"macro", "meso"},
+ "form-refinement": {"macro", "meso", "micro"},
+ "material-pass": {"macro", "meso", "micro"},
+ "surface-pass": {"macro", "meso", "micro"},
+ "lighting-pass": {"macro", "meso", "micro"},
+ "interaction-pass": {"macro", "meso", "micro"},
+ "optimization-pass": {"macro", "meso", "micro"},
+}
+
+
+def load_spec(path: Path) -> dict[str, Any]:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError("spec must be a JSON object")
+ return payload
+
+
+def pass_order(spec: dict[str, Any]) -> list[str]:
+ ids: list[str] = []
+ for item in spec.get("buildPasses", []):
+ if isinstance(item, dict) and isinstance(item.get("id"), str) and item["id"].strip():
+ ids.append(item["id"])
+ return ids or DEFAULT_PASS_ORDER.copy()
+
+
+def review_visual_evidence(entry: dict[str, Any]) -> dict[str, Any]:
+ visual = entry.get("visualEvidence")
+ return visual if isinstance(visual, dict) else {}
+
+
+def review_completes_pass(entry: dict[str, Any], pass_id: str) -> bool:
+ if entry.get("passId") != pass_id or entry.get("action") != "continue":
+ return False
+ if pass_id in VISUAL_PASS_IDS and not review_visual_evidence(entry).get("renderScreenshot"):
+ return False
+ return True
+
+
+def completed_passes(spec: dict[str, Any], ids: list[str]) -> list[str]:
+ history = spec.get("reviewHistory", [])
+ if not isinstance(history, list):
+ return []
+ completed: list[str] = []
+ for pass_id in ids:
+ if any(isinstance(entry, dict) and review_completes_pass(entry, pass_id) for entry in history):
+ completed.append(pass_id)
+ else:
+ break
+ return completed
+
+
+def unlocked_pass(spec: dict[str, Any]) -> str:
+ ids = pass_order(spec)
+ completed = completed_passes(spec, ids)
+ if len(completed) >= len(ids):
+ return ids[-1]
+ return ids[len(completed)]
+
+
+def assert_pass_unlocked(spec: dict[str, Any], requested_pass: str) -> None:
+ ids = pass_order(spec)
+ if requested_pass not in ids:
+ raise ValueError(f"unknown build pass {requested_pass!r}; expected one of: {', '.join(ids)}")
+ completed = completed_passes(spec, ids)
+ current = ids[-1] if len(completed) >= len(ids) else ids[len(completed)]
+ if requested_pass in completed or requested_pass == current:
+ return
+ previous_index = ids.index(requested_pass) - 1
+ previous = ids[previous_index] if previous_index >= 0 else ""
+ raise ValueError(
+ f"build pass {requested_pass!r} is locked; complete {previous!r} first with "
+ "append_sculpt_review.py action=continue and browser screenshot evidence"
+ )
+
+
+def component_refs_for_pass(spec: dict[str, Any], pass_id: str) -> set[str]:
+ ids = pass_order(spec)
+ if pass_id not in ids:
+ return set()
+ allowed_ids = set(ids[: ids.index(pass_id) + 1])
+ refs: set[str] = set()
+ for item in spec.get("buildPasses", []):
+ if not isinstance(item, dict) or item.get("id") not in allowed_ids:
+ continue
+ component_refs = item.get("componentRefs", [])
+ if isinstance(component_refs, list):
+ refs.update(str(value) for value in component_refs if str(value).strip())
+ return refs
+
+
+def filter_components_for_pass(spec: dict[str, Any], components: list[dict[str, Any]], pass_id: str) -> list[dict[str, Any]]:
+ allowed_levels = PASS_LEVELS.get(pass_id, {"macro"})
+ explicit_refs = component_refs_for_pass(spec, pass_id)
+ included: list[dict[str, Any]] = []
+ included_ids: set[str] = set()
+ component_by_id = {str(item.get("id")): item for item in components if item.get("id") is not None}
+
+ def include_component(component: dict[str, Any]) -> None:
+ component_id = str(component.get("id") or "")
+ if not component_id or component_id in included_ids:
+ return
+ parent_id = component.get("parent")
+ if parent_id is not None and str(parent_id) in component_by_id:
+ include_component(component_by_id[str(parent_id)])
+ included.append(component)
+ included_ids.add(component_id)
+
+ for component in components:
+ component_id = str(component.get("id") or "")
+ level = str(component.get("level") or "macro")
+ tier = str(component.get("fidelityTier") or "")
+ if component_id in explicit_refs or level in allowed_levels or tier == pass_id:
+ include_component(component)
+ if not included and components:
+ included.append(components[0])
+ return included
+
+
+def pascal_case(value: str) -> str:
+ parts = re.findall(r"[A-Za-z0-9]+", value)
+ return "".join(part[:1].upper() + part[1:] for part in parts) or "Object"
+
+
+def const_name(value: str) -> str:
+ name = re.sub(r"[^A-Za-z0-9_]", "_", value.strip())
+ if not name:
+ return "component"
+ if name[0].isdigit():
+ name = "_" + name
+ return name
+
+
+def local_var(prefix: str, value: str, index: int) -> str:
+ return f"{prefix}_{const_name(value)}_{index}"
+
+
+def hex_to_number(value: Any, fallback: str = "#8A7A5F") -> str:
+ color = value if isinstance(value, str) else fallback
+ if re.fullmatch(r"#[0-9A-Fa-f]{6}", color):
+ return "0x" + color[1:]
+ if re.fullmatch(r"#[0-9A-Fa-f]{3}", color):
+ return "0x" + "".join(ch * 2 for ch in color[1:])
+ return "0x" + fallback[1:]
+
+
+def material_base_value(value: Any, fallback: float) -> float:
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
+ if isinstance(value, dict) and isinstance(value.get("base"), (int, float)):
+ return float(value["base"])
+ return fallback
+
+
+def json_literal(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False)
+
+
+def vector(values: Any, fallback: list[float]) -> str:
+ if (
+ isinstance(values, list)
+ and len(values) == 3
+ and all(isinstance(item, (int, float)) for item in values)
+ ):
+ return ", ".join(str(float(item)) for item in values)
+ return ", ".join(str(item) for item in fallback)
+
+
+def scale_vector(component: dict[str, Any], transform: dict[str, Any]) -> str:
+ if "scale" in transform:
+ return vector(transform.get("scale"), [1, 1, 1])
+ dimensions = component.get("dimensions")
+ if isinstance(dimensions, dict):
+ width = dimensions.get("width", dimensions.get("radius", 0.5) * 2 if isinstance(dimensions.get("radius"), (int, float)) else 1)
+ height = dimensions.get("height", dimensions.get("length", 1))
+ depth = dimensions.get("depth", dimensions.get("radius", 0.5) * 2 if isinstance(dimensions.get("radius"), (int, float)) else 1)
+ if all(isinstance(item, (int, float)) for item in (width, height, depth)):
+ return vector([width, height, depth], [1, 1, 1])
+ return vector(None, [1, 1, 1])
+
+
+def geometry_for(primitive: str) -> str:
+ if primitive == "box":
+ return "new THREE.BoxGeometry(1, 1, 1, 12, 12, 12)"
+ if primitive in {"sphere", "ellipsoid"}:
+ return "new THREE.SphereGeometry(0.5, 64, 40)"
+ if primitive == "cylinder":
+ return "new THREE.CylinderGeometry(0.5, 0.5, 1, 48, 16)"
+ if primitive == "cone":
+ return "new THREE.ConeGeometry(0.5, 1, 48, 16)"
+ if primitive == "capsule":
+ return "new THREE.CapsuleGeometry(0.35, 0.7, 16, 32)"
+ if primitive == "torus":
+ return "new THREE.TorusGeometry(0.45, 0.08, 24, 96)"
+ if primitive == "plane-card":
+ return "new THREE.PlaneGeometry(1, 1, 24, 24)"
+ return "new THREE.BoxGeometry(1, 1, 1, 8, 8, 8)"
+
+
+def generate(spec: dict[str, Any], pass_id: str) -> str:
+ target = str(spec.get("targetName") or "Procedural Object")
+ type_name = pascal_case(target)
+ function_name = f"create{type_name}Model"
+ materials = {
+ str(material.get("id") or f"material{index}"): material
+ for index, material in enumerate(spec.get("materials", []))
+ if isinstance(material, dict)
+ }
+ all_components = [item for item in spec.get("componentTree", []) if isinstance(item, dict)]
+ components = filter_components_for_pass(spec, all_components, pass_id)
+
+ lines: list[str] = [
+ "import * as THREE from 'three';",
+ "",
+ "export type ProceduralModelOptions = {",
+ " wireframe?: boolean;",
+ " castShadow?: boolean;",
+ " receiveShadow?: boolean;",
+ " textureSize?: number;",
+ " textureAnisotropy?: number;",
+ " qualityPriority?: 'reference-fidelity' | 'balanced';",
+ "};",
+ "",
+ "export type ProceduralModelRuntime = {",
+ " nodes: Record<string, THREE.Object3D>;",
+ " meshes: Record<string, THREE.Mesh>;",
+ " sockets: Record<string, THREE.Object3D>;",
+ " colliders: Record<string, unknown>;",
+ " destructionGroups: Record<string, THREE.Object3D[]>;",
+ "};",
+ "",
+ "type SculptMaterialSpec = Record<string, any>;",
+ "",
+ "function hashString(value: string): number {",
+ " let hash = 2166136261;",
+ " for (let index = 0; index < value.length; index += 1) {",
+ " hash ^= value.charCodeAt(index);",
+ " hash = Math.imul(hash, 16777619);",
+ " }",
+ " return hash >>> 0;",
+ "}",
+ "",
+ "function readLayerNumber(value: unknown, keys: string[], fallback: number): number {",
+ " if (typeof value === 'number') return value;",
+ " if (value && typeof value === 'object') {",
+ " const record = value as Record<string, unknown>;",
+ " for (const key of keys) {",
+ " if (typeof record[key] === 'number') return record[key] as number;",
+ " }",
+ " }",
+ " return fallback;",
+ "}",
+ "",
+ "function hexToRgb(hex: string): [number, number, number] {",
+ " const normalized = /^#[0-9a-f]{3}$/i.test(hex)",
+ " ? '#' + hex.slice(1).split('').map((part) => part + part).join('')",
+ " : hex;",
+ " const value = /^#[0-9a-f]{6}$/i.test(normalized) ? Number.parseInt(normalized.slice(1), 16) : 0x8a7a5f;",
+ " return [(value >> 16) & 255, (value >> 8) & 255, value & 255];",
+ "}",
+ "",
+ "function materialPalette(spec: SculptMaterialSpec): string[] {",
+ " const palette = spec.colorVariation?.palette;",
+ " if (Array.isArray(palette) && palette.length > 0) return palette.filter((value) => typeof value === 'string');",
+ " const secondary = spec.albedo?.secondary;",
+ " const colors = [spec.baseColor ?? spec.color ?? spec.albedo?.dominant, ...(Array.isArray(secondary) ? secondary : [])];",
+ " return colors.filter((value): value is string => typeof value === 'string' && value.startsWith('#'));",
+ "}",
+ "",
+ "function clamp01(value: number): number {",
+ " return Math.max(0, Math.min(1, value));",
+ "}",
+ "",
+ "function smoothCurve(value: number): number {",
+ " return value * value * (3 - 2 * value);",
+ "}",
+ "",
+ "function periodicHash(x: number, y: number, seed: number, periodX: number, periodY: number): number {",
+ " const wrappedX = ((x % periodX) + periodX) % periodX;",
+ " const wrappedY = ((y % periodY) + periodY) % periodY;",
+ " let value = Math.imul(wrappedX + seed * 17, 374761393) ^ Math.imul(wrappedY + seed * 31, 668265263);",
+ " value = Math.imul(value ^ (value >>> 13), 1274126177);",
+ " return ((value ^ (value >>> 16)) >>> 0) / 4294967295;",
+ "}",
+ "",
+ "function periodicValueNoise(u: number, v: number, seed: number, periodX: number, periodY: number): number {",
+ " const x = u * periodX;",
+ " const y = v * periodY;",
+ " const x0 = Math.floor(x);",
+ " const y0 = Math.floor(y);",
+ " const tx = smoothCurve(x - x0);",
+ " const ty = smoothCurve(y - y0);",
+ " const a = periodicHash(x0, y0, seed, periodX, periodY);",
+ " const b = periodicHash(x0 + 1, y0, seed, periodX, periodY);",
+ " const c = periodicHash(x0, y0 + 1, seed, periodX, periodY);",
+ " const d = periodicHash(x0 + 1, y0 + 1, seed, periodX, periodY);",
+ " return THREE.MathUtils.lerp(THREE.MathUtils.lerp(a, b, tx), THREE.MathUtils.lerp(c, d, tx), ty);",
+ "}",
+ "",
+ "type SurfaceBand = {",
+ " frequency: number;",
+ " amplitude: number;",
+ " stretchX: number;",
+ " stretchY: number;",
+ " ridge: boolean;",
+ "};",
+ "",
+ "function surfaceBands(spec: SculptMaterialSpec): SurfaceBand[] {",
+ " const source = Array.isArray(spec.surfaceFrequencyBands) ? spec.surfaceFrequencyBands : [];",
+ " const parsed = source.flatMap((item: unknown) => {",
+ " if (!item || typeof item !== 'object') return [];",
+ " const band = item as Record<string, unknown>;",
+ " const frequency = typeof band.frequency === 'number' ? band.frequency : 0;",
+ " const amplitude = typeof band.amplitude === 'number' ? band.amplitude : 0;",
+ " if (frequency <= 0 || amplitude <= 0) return [];",
+ " const stretch = Array.isArray(band.stretch) ? band.stretch : [1, 1];",
+ " const description = `${String(band.pattern ?? '')} ${String(band.role ?? '')}`.toLowerCase();",
+ " return [{",
+ " frequency,",
+ " amplitude,",
+ " stretchX: typeof stretch[0] === 'number' ? Math.max(0.1, stretch[0]) : 1,",
+ " stretchY: typeof stretch[1] === 'number' ? Math.max(0.1, stretch[1]) : 1,",
+ " ridge: /(ridge|groove|grain|fiber|striated|crack)/.test(description),",
+ " }];",
+ " });",
+ " return parsed.length > 0 ? parsed : [",
+ " { frequency: 2, amplitude: 0.42, stretchX: 1, stretchY: 1, ridge: false },",
+ " { frequency: 12, amplitude: 0.22, stretchX: 1, stretchY: 1, ridge: false },",
+ " { frequency: 56, amplitude: 0.08, stretchX: 1, stretchY: 1, ridge: false },",
+ " ];",
+ "}",
+ "",
+ "function sampleSurface(u: number, v: number, bands: SurfaceBand[], seed: number): number {",
+ " let value = 0;",
+ " let weight = 0;",
+ " for (let index = 0; index < bands.length; index += 1) {",
+ " const band = bands[index];",
+ " const periodX = Math.max(1, Math.round(band.frequency * band.stretchX));",
+ " const periodY = Math.max(1, Math.round(band.frequency * band.stretchY));",
+ " let sample = periodicValueNoise(u, v, seed + index * 1013, periodX, periodY);",
+ " if (band.ridge) sample = 1 - Math.abs(sample * 2 - 1);",
+ " value += sample * band.amplitude;",
+ " weight += band.amplitude;",
+ " }",
+ " return weight > 0 ? clamp01(value / weight) : 0.5;",
+ "}",
+ "",
+ "function mixPalette(colors: [number, number, number][], value: number): [number, number, number] {",
+ " if (colors.length === 1) return colors[0];",
+ " const scaled = clamp01(value) * (colors.length - 1);",
+ " const index = Math.min(colors.length - 2, Math.floor(scaled));",
+ " const mix = scaled - index;",
+ " const a = colors[index];",
+ " const b = colors[index + 1];",
+ " return [",
+ " Math.round(THREE.MathUtils.lerp(a[0], b[0], mix)),",
+ " Math.round(THREE.MathUtils.lerp(a[1], b[1], mix)),",
+ " Math.round(THREE.MathUtils.lerp(a[2], b[2], mix)),",
+ " ];",
+ "}",
+ "",
+ "function writePixel(data: Uint8ClampedArray, offset: number, red: number, green: number, blue: number): void {",
+ " data[offset] = Math.max(0, Math.min(255, Math.round(red)));",
+ " data[offset + 1] = Math.max(0, Math.min(255, Math.round(green)));",
+ " data[offset + 2] = Math.max(0, Math.min(255, Math.round(blue)));",
+ " data[offset + 3] = 255;",
+ "}",
+ "",
+ "function makeCanvas(size: number): HTMLCanvasElement {",
+ " const canvas = document.createElement('canvas');",
+ " canvas.width = size;",
+ " canvas.height = size;",
+ " return canvas;",
+ "}",
+ "",
+ "function createMapTexture(",
+ " canvas: HTMLCanvasElement,",
+ " colorSpace: THREE.ColorSpace,",
+ " spec: SculptMaterialSpec,",
+ " options: ProceduralModelOptions,",
+ "): THREE.CanvasTexture {",
+ " const texture = new THREE.CanvasTexture(canvas);",
+ " const projection = spec.textureProjection && typeof spec.textureProjection === 'object' ? spec.textureProjection : {};",
+ " const repeat = Array.isArray(projection.repeat) ? projection.repeat : [2, 2];",
+ " texture.colorSpace = colorSpace;",
+ " texture.wrapS = THREE.RepeatWrapping;",
+ " texture.wrapT = THREE.RepeatWrapping;",
+ " texture.repeat.set(",
+ " typeof repeat[0] === 'number' ? repeat[0] : 2,",
+ " typeof repeat[1] === 'number' ? repeat[1] : 2,",
+ " );",
+ " texture.anisotropy = Math.max(1, Math.round(options.textureAnisotropy ?? projection.anisotropy ?? 8));",
+ " texture.needsUpdate = true;",
+ " return texture;",
+ "}",
+ "",
+ "type ProceduralTextureSet = {",
+ " albedo: THREE.Texture;",
+ " roughness: THREE.Texture;",
+ " height: THREE.Texture;",
+ " normal: THREE.Texture;",
+ " ao: THREE.Texture;",
+ " source: 'reference-pixel-extraction' | 'procedural';",
+ "};",
+ "",
+ "function referenceMapUrl(spec: SculptMaterialSpec, channel: string): string | null {",
+ " const reference = spec.referencePbr;",
+ " if (!reference || typeof reference !== 'object') return null;",
+ " if (reference.usable === false) return null;",
+ " const confidence = typeof reference.confidence === 'number'",
+ " ? reference.confidence",
+ " : (typeof reference.estimatedFidelity === 'number' ? reference.estimatedFidelity : 0);",
+ " const threshold = typeof reference.targetThreshold === 'number' ? reference.targetThreshold : 0.7;",
+ " if (confidence < threshold) return null;",
+ " const maps = reference.maps;",
+ " if (!maps || typeof maps !== 'object') return null;",
+ " const map = (maps as Record<string, unknown>)[channel];",
+ " if (!map || typeof map !== 'object') return null;",
+ " const record = map as Record<string, unknown>;",
+ " const url = typeof record.url === 'string' && record.url.trim() ? record.url : record.path;",
+ " return typeof url === 'string' && url.trim() ? url : null;",
+ "}",
+ "",
+ "function createLoadedMapTexture(",
+ " url: string,",
+ " colorSpace: THREE.ColorSpace,",
+ " spec: SculptMaterialSpec,",
+ " options: ProceduralModelOptions,",
+ "): THREE.Texture {",
+ " const texture = new THREE.TextureLoader().load(url);",
+ " const projection = spec.textureProjection && typeof spec.textureProjection === 'object' ? spec.textureProjection : {};",
+ " const repeat = Array.isArray(projection.repeat) ? projection.repeat : [1, 1];",
+ " texture.colorSpace = colorSpace;",
+ " texture.wrapS = THREE.RepeatWrapping;",
+ " texture.wrapT = THREE.RepeatWrapping;",
+ " texture.repeat.set(",
+ " typeof repeat[0] === 'number' ? repeat[0] : 1,",
+ " typeof repeat[1] === 'number' ? repeat[1] : 1,",
+ " );",
+ " texture.anisotropy = Math.max(1, Math.round(options.textureAnisotropy ?? projection.anisotropy ?? 8));",
+ " texture.needsUpdate = true;",
+ " return texture;",
+ "}",
+ "",
+ "function makeReferenceTextureSet(spec: SculptMaterialSpec, options: ProceduralModelOptions): ProceduralTextureSet | null {",
+ " const albedo = referenceMapUrl(spec, 'albedo');",
+ " const roughness = referenceMapUrl(spec, 'roughness');",
+ " const height = referenceMapUrl(spec, 'height');",
+ " const normal = referenceMapUrl(spec, 'normal');",
+ " const ao = referenceMapUrl(spec, 'ao');",
+ " if (!albedo || !roughness || !height || !normal || !ao) return null;",
+ " return {",
+ " albedo: createLoadedMapTexture(albedo, THREE.SRGBColorSpace, spec, options),",
+ " roughness: createLoadedMapTexture(roughness, THREE.NoColorSpace, spec, options),",
+ " height: createLoadedMapTexture(height, THREE.NoColorSpace, spec, options),",
+ " normal: createLoadedMapTexture(normal, THREE.NoColorSpace, spec, options),",
+ " ao: createLoadedMapTexture(ao, THREE.NoColorSpace, spec, options),",
+ " source: 'reference-pixel-extraction',",
+ " };",
+ "}",
+ "",
+ "function makeProceduralTextureSet(",
+ " id: string,",
+ " spec: SculptMaterialSpec,",
+ " options: ProceduralModelOptions,",
+ "): ProceduralTextureSet | null {",
+ " if (typeof document === 'undefined') return null;",
+ " const qualityFirst = (options.qualityPriority ?? 'reference-fidelity') === 'reference-fidelity';",
+ " const requested = options.textureSize ?? spec.textureResolution;",
+ " const requestedSize = typeof requested === 'number' && Number.isFinite(requested)",
+ " ? requested",
+ " : (qualityFirst ? 1024 : 512);",
+ " const size = Math.max(256, Math.min(2048, 2 ** Math.round(Math.log2(requestedSize))));",
+ " const canvases = {",
+ " albedo: makeCanvas(size),",
+ " roughness: makeCanvas(size),",
+ " height: makeCanvas(size),",
+ " normal: makeCanvas(size),",
+ " ao: makeCanvas(size),",
+ " };",
+ " const contexts = {",
+ " albedo: canvases.albedo.getContext('2d'),",
+ " roughness: canvases.roughness.getContext('2d'),",
+ " height: canvases.height.getContext('2d'),",
+ " normal: canvases.normal.getContext('2d'),",
+ " ao: canvases.ao.getContext('2d'),",
+ " };",
+ " if (!contexts.albedo || !contexts.roughness || !contexts.height || !contexts.normal || !contexts.ao) return null;",
+ " const images = {",
+ " albedo: contexts.albedo.createImageData(size, size),",
+ " roughness: contexts.roughness.createImageData(size, size),",
+ " height: contexts.height.createImageData(size, size),",
+ " normal: contexts.normal.createImageData(size, size),",
+ " ao: contexts.ao.createImageData(size, size),",
+ " };",
+ " const seed = hashString(id);",
+ " const bands = surfaceBands(spec);",
+ " const heightField = new Float32Array(size * size);",
+ " const roughnessField = new Float32Array(size * size);",
+ " const palette = materialPalette(spec);",
+ " const fallback = typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F';",
+ " const colors = (palette.length >= 2 ? palette : [fallback, '#6E614B', '#A08F70']).map(hexToRgb);",
+ " const baseRoughness = clamp01(readLayerNumber(spec.roughness, ['base'], 0.76));",
+ " const roughnessVariation = clamp01(readLayerNumber(spec.roughness, ['variation'], 0.18));",
+ " const colorAmplitude = clamp01(readLayerNumber(spec.colorVariation, ['amplitude', 'variation'], 0.18));",
+ " const heightCorrelation = clamp01(readLayerNumber(spec.colorVariation, ['heightCorrelation'], 0.3));",
+ " for (let y = 0; y < size; y += 1) {",
+ " const v = y / size;",
+ " for (let x = 0; x < size; x += 1) {",
+ " const u = x / size;",
+ " const index = y * size + x;",
+ " const height = sampleSurface(u, v, bands, seed + 101);",
+ " const roughNoise = sampleSurface(u, v, bands, seed + 7001);",
+ " const colorNoise = sampleSurface(u, v, bands, seed + 15013);",
+ " heightField[index] = height;",
+ " roughnessField[index] = clamp01(baseRoughness + (roughNoise - 0.5) * roughnessVariation * 2);",
+ " const paletteValue = clamp01(",
+ " 0.5 + (colorNoise - 0.5) * colorAmplitude * 2 + (height - 0.5) * heightCorrelation",
+ " );",
+ " const color = mixPalette(colors, paletteValue);",
+ " writePixel(images.albedo.data, index * 4, color[0], color[1], color[2]);",
+ " }",
+ " }",
+ " const normalStrength = Math.max(0.05, readLayerNumber(spec.normal, ['strength', 'amplitude'], 0.35));",
+ " const aoStrength = clamp01(readLayerNumber(spec.ambientOcclusion, ['cavityStrength', 'strength'], 0.35));",
+ " for (let y = 0; y < size; y += 1) {",
+ " const up = ((y - 1 + size) % size) * size;",
+ " const down = ((y + 1) % size) * size;",
+ " for (let x = 0; x < size; x += 1) {",
+ " const left = (x - 1 + size) % size;",
+ " const right = (x + 1) % size;",
+ " const index = y * size + x;",
+ " const center = heightField[index];",
+ " const dx = (heightField[y * size + right] - heightField[y * size + left]) * normalStrength * 6;",
+ " const dy = (heightField[down + x] - heightField[up + x]) * normalStrength * 6;",
+ " const inverseLength = 1 / Math.sqrt(dx * dx + dy * dy + 1);",
+ " const normalX = -dx * inverseLength;",
+ " const normalY = -dy * inverseLength;",
+ " const normalZ = inverseLength;",
+ " const neighborAverage = (",
+ " heightField[y * size + left] + heightField[y * size + right]",
+ " + heightField[up + x] + heightField[down + x]",
+ " ) * 0.25;",
+ " const cavity = Math.max(0, neighborAverage - center);",
+ " const ao = clamp01(1 - aoStrength * (cavity * 12 + (1 - center) * 0.16));",
+ " const offset = index * 4;",
+ " const heightByte = center * 255;",
+ " const roughnessByte = roughnessField[index] * 255;",
+ " writePixel(images.height.data, offset, heightByte, heightByte, heightByte);",
+ " writePixel(images.roughness.data, offset, roughnessByte, roughnessByte, roughnessByte);",
+ " writePixel(",
+ " images.normal.data, offset,",
+ " (normalX * 0.5 + 0.5) * 255,",
+ " (normalY * 0.5 + 0.5) * 255,",
+ " (normalZ * 0.5 + 0.5) * 255,",
+ " );",
+ " writePixel(images.ao.data, offset, ao * 255, ao * 255, ao * 255);",
+ " }",
+ " }",
+ " contexts.albedo.putImageData(images.albedo, 0, 0);",
+ " contexts.roughness.putImageData(images.roughness, 0, 0);",
+ " contexts.height.putImageData(images.height, 0, 0);",
+ " contexts.normal.putImageData(images.normal, 0, 0);",
+ " contexts.ao.putImageData(images.ao, 0, 0);",
+ " return {",
+ " albedo: createMapTexture(canvases.albedo, THREE.SRGBColorSpace, spec, options),",
+ " roughness: createMapTexture(canvases.roughness, THREE.NoColorSpace, spec, options),",
+ " height: createMapTexture(canvases.height, THREE.NoColorSpace, spec, options),",
+ " normal: createMapTexture(canvases.normal, THREE.NoColorSpace, spec, options),",
+ " ao: createMapTexture(canvases.ao, THREE.NoColorSpace, spec, options),",
+ " source: 'procedural',",
+ " };",
+ "}",
+ "",
+ "function createSculptMaterial(id: string, spec: SculptMaterialSpec, options: ProceduralModelOptions): THREE.MeshPhysicalMaterial {",
+ " const textures = makeReferenceTextureSet(spec, options) ?? makeProceduralTextureSet(id, spec, options);",
+ " const material = new THREE.MeshPhysicalMaterial({",
+ " color: textures ? 0xffffff : new THREE.Color(typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F'),",
+ " roughness: textures ? 1 : clamp01(readLayerNumber(spec.roughness, ['base'], 0.76)),",
+ " metalness: clamp01(readLayerNumber(spec.metalness, ['base'], 0.0)),",
+ " clearcoat: clamp01(readLayerNumber(spec.clearcoat, ['base', 'amount'], 0)),",
+ " clearcoatRoughness: clamp01(readLayerNumber(spec.clearcoatRoughness, ['base'], 0.25)),",
+ " transmission: clamp01(readLayerNumber(spec.transmission, ['base', 'amount'], 0)),",
+ " opacity: clamp01(readLayerNumber(spec.opacity, ['base'], 1)),",
+ " transparent: readLayerNumber(spec.transmission, ['base', 'amount'], 0) > 0 || readLayerNumber(spec.opacity, ['base'], 1) < 1,",
+ " alphaTest: Math.max(0, readLayerNumber(spec.alpha, ['cutoff', 'alphaTest'], 0)),",
+ " wireframe: options.wireframe ?? false,",
+ " side: spec.doubleSided === true ? THREE.DoubleSide : THREE.FrontSide,",
+ " });",
+ " if (textures) {",
+ " material.map = textures.albedo;",
+ " material.roughnessMap = textures.roughness;",
+ " material.normalMap = textures.normal;",
+ " material.normalScale.setScalar(Math.max(0.05, readLayerNumber(spec.normal, ['strength', 'amplitude'], 0.35)));",
+ " material.aoMap = textures.ao;",
+ " material.aoMap.channel = 0;",
+ " material.aoMapIntensity = readLayerNumber(spec.ambientOcclusion, ['cavityStrength', 'strength'], 0.35);",
+ " const bumpScale = Math.max(0, readLayerNumber(spec.bump, ['amplitude', 'strength'], 0));",
+ " if (bumpScale > 0) {",
+ " material.bumpMap = textures.height;",
+ " material.bumpScale = bumpScale;",
+ " }",
+ " const displacementScale = Math.max(0, readLayerNumber(spec.displacement, ['amplitude', 'strength'], 0));",
+ " if (displacementScale > 0) {",
+ " material.displacementMap = textures.height;",
+ " material.displacementScale = displacementScale;",
+ " material.displacementBias = -displacementScale * 0.5;",
+ " }",
+ " }",
+ " material.envMapIntensity = readLayerNumber(spec, ['envMapIntensity'], 0.8);",
+ " material.userData.sculptMaterial = spec;",
+ " material.userData.proceduralMapsIndependent = true;",
+ " material.userData.pbrTextureSource = textures?.source ?? 'flat-fallback';",
+ " material.userData.referencePbr = spec.referencePbr ?? null;",
+ " material.needsUpdate = true;",
+ " return material;",
+ "}",
+ "",
+ "type AttachmentEndpoint = {",
+ " start: THREE.Vector3;",
+ " midpoint: THREE.Vector3;",
+ " quaternion: THREE.Quaternion;",
+ " length: number;",
+ " baseRadius: number;",
+ " endRadius: number;",
+ "};",
+ "",
+ "function readVector3(value: unknown, fallback: [number, number, number]): THREE.Vector3 {",
+ " if (Array.isArray(value) && value.length === 3 && value.every((item) => typeof item === 'number')) {",
+ " return new THREE.Vector3(value[0], value[1], value[2]);",
+ " }",
+ " return new THREE.Vector3(fallback[0], fallback[1], fallback[2]);",
+ "}",
+ "",
+ "function readNumber(value: unknown, fallback: number): number {",
+ " return typeof value === 'number' && Number.isFinite(value) ? value : fallback;",
+ "}",
+ "",
+ "function makeAttachmentEndpoint(attachment: unknown): AttachmentEndpoint | null {",
+ " if (!attachment || typeof attachment !== 'object') return null;",
+ " const record = attachment as Record<string, unknown>;",
+ " const start = readVector3(record.localStart, [0, 0, 0]);",
+ " const end = readVector3(record.localEnd, [0, 1, 0]);",
+ " const delta = end.clone().sub(start);",
+ " const length = delta.length();",
+ " if (length <= 0.0001) return null;",
+ " const direction = delta.clone().normalize();",
+ " const quaternion = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);",
+ " const baseRadius = Math.max(0.005, readNumber(record.baseRadius, 0.06));",
+ " const endRadius = Math.max(0.003, readNumber(record.endRadius, baseRadius * 0.55));",
+ " return {",
+ " start,",
+ " midpoint: delta.multiplyScalar(0.5),",
+ " quaternion,",
+ " length,",
+ " baseRadius,",
+ " endRadius,",
+ " };",
+ "}",
+ "",
+ f"// Generated from ObjectSculptSpec target: {target}",
+ f"// Sculpt build pass: {pass_id}",
+ "// This factory is intentionally pass-gated. Finish browser screenshot review before unlocking deeper passes.",
+ f"export function {function_name}(options: ProceduralModelOptions = {{}}): THREE.Group {{",
+ " const root = new THREE.Group();",
+ f" root.name = {json.dumps(target)};",
+ "",
+ " const materialMap: Record<string, THREE.Material> = {};",
+ ]
+ for material_id, material in materials.items():
+ lines.extend(
+ [
+ f" materialMap[{json.dumps(material_id)}] = createSculptMaterial(",
+ f" {json.dumps(material_id)},",
+ f" {json_literal(material)},",
+ " options",
+ " );",
+ ]
+ )
+ lines.extend(
+ [
+ "",
+ " const nodes: Record<string, THREE.Object3D> = { root };",
+ " const meshes: Record<string, THREE.Mesh> = {};",
+ " const sockets: Record<string, THREE.Object3D> = {};",
+ " const colliders: Record<string, unknown> = {};",
+ " const destructionGroups: Record<string, THREE.Object3D[]> = {};",
+ ]
+ )
+
+ for index, component in enumerate(components):
+ component_id = str(component.get("id") or f"component-{index}")
+ component_var = local_var("mesh", component_id, index)
+ node_var = local_var("node", component_id, index)
+ primitive = str(component.get("primitive") or "box")
+ if primitive not in VALID_PRIMITIVES:
+ primitive = "box"
+ transform = component.get("transform", {}) if isinstance(component.get("transform"), dict) else {}
+ action_profile = component.get("actionProfile") if isinstance(component.get("actionProfile"), dict) else {}
+ sockets_spec = action_profile.get("sockets", []) if isinstance(action_profile.get("sockets"), list) else []
+ destruction = action_profile.get("destruction") if isinstance(action_profile.get("destruction"), dict) else {}
+ fracture_group = destruction.get("fractureGroup") if isinstance(destruction, dict) else None
+ attachment = component.get("attachment") if isinstance(component.get("attachment"), dict) else None
+ attachment_var = local_var("attachment", component_id, index)
+ endpoint_var = local_var("endpoint", component_id, index)
+ material_id = str(component.get("material") or next(iter(materials.keys()), "base"))
+ parent = component.get("parent") or "root"
+ name = str(component.get("name") or component_id)
+ lines.extend(
+ [
+ "",
+ f" const {attachment_var} = {json.dumps(attachment, ensure_ascii=False)};",
+ f" const {endpoint_var} = makeAttachmentEndpoint({attachment_var});",
+ f" const {node_var} = new THREE.Group();",
+ f" {node_var}.name = {json.dumps(name + '__pivot')};",
+ f" if ({endpoint_var}) {{",
+ f" {node_var}.position.copy({endpoint_var}.start);",
+ f" {node_var}.rotation.set(0, 0, 0);",
+ f" {node_var}.scale.set(1, 1, 1);",
+ " } else {",
+ f" {node_var}.position.set({vector(transform.get('position'), [0, 0, 0])});",
+ f" {node_var}.rotation.set({vector(transform.get('rotation'), [0, 0, 0])});",
+ f" {node_var}.scale.set({scale_vector(component, transform)});",
+ " }",
+ f" {node_var}.userData.sculptComponent = {json.dumps(component, ensure_ascii=False)};",
+ f" {node_var}.userData.actionProfile = {json.dumps(action_profile, ensure_ascii=False)};",
+ f" (nodes[{json.dumps(str(parent))}] ?? root).add({node_var});",
+ f" nodes[{json.dumps(component_id)}] = {node_var};",
+ f" const {component_var}Geometry = {endpoint_var}",
+ f" ? new THREE.CylinderGeometry({endpoint_var}.endRadius, {endpoint_var}.baseRadius, {endpoint_var}.length, 32, 12)",
+ f" : {geometry_for(primitive)};",
+ f" const {component_var} = new THREE.Mesh(",
+ f" {component_var}Geometry,",
+ f" materialMap[{json.dumps(material_id)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }})",
+ " );",
+ f" {component_var}.name = {json.dumps(name)};",
+ f" if ({endpoint_var}) {{",
+ f" {component_var}.position.copy({endpoint_var}.midpoint);",
+ f" {component_var}.quaternion.copy({endpoint_var}.quaternion);",
+ " }",
+ f" {component_var}.castShadow = options.castShadow ?? true;",
+ f" {component_var}.receiveShadow = options.receiveShadow ?? true;",
+ f" {component_var}.userData.sculptComponent = {json.dumps(component, ensure_ascii=False)};",
+ f" {node_var}.add({component_var});",
+ f" meshes[{json.dumps(component_id)}] = {component_var};",
+ f" colliders[{json.dumps(component_id)}] = {json.dumps(action_profile.get('collider', {}), ensure_ascii=False)};",
+ ]
+ )
+ if isinstance(fracture_group, str) and fracture_group:
+ lines.extend(
+ [
+ f" destructionGroups[{json.dumps(fracture_group)}] ??= [];",
+ f" destructionGroups[{json.dumps(fracture_group)}].push({node_var});",
+ ]
+ )
+ for socket_index, socket in enumerate(sockets_spec):
+ if not isinstance(socket, dict):
+ continue
+ socket_id = str(socket.get("id") or f"socket-{socket_index}")
+ socket_var = local_var("socket", f"{component_id}_{socket_id}", socket_index)
+ local_position = socket.get("localPosition", socket.get("position"))
+ local_rotation = socket.get("localRotation", socket.get("rotation"))
+ socket_key = f"{component_id}:{socket_id}"
+ lines.extend(
+ [
+ f" const {socket_var} = new THREE.Object3D();",
+ f" {socket_var}.name = {json.dumps(socket_id)};",
+ f" {socket_var}.position.set({vector(local_position, [0, 0, 0])});",
+ f" {socket_var}.rotation.set({vector(local_rotation, [0, 0, 0])});",
+ f" {socket_var}.userData.socket = {json.dumps(socket, ensure_ascii=False)};",
+ f" {node_var}.add({socket_var});",
+ f" sockets[{json.dumps(socket_key)}] = {socket_var};",
+ ]
+ )
+ if primitive in {"tube", "lathe", "extrude", "curve-sweep", "instanced-cluster"}:
+ lines.append(
+ f" // TODO: replace {component_id!r} box fallback with {primitive} procedural geometry."
+ )
+
+ look_dev_targets = spec.get("lookDevTargets", {})
+ lighting_from_photo = spec.get("lightingFromPhoto", [])
+ lines.extend(
+ [
+ "",
+ " root.userData.sculptRuntime = { nodes, meshes, sockets, colliders, destructionGroups } satisfies ProceduralModelRuntime;",
+ f" root.userData.lookDevTargets = {json_literal(look_dev_targets)};",
+ " root.userData.actionReadiness = {",
+ " note: 'Use root.userData.sculptRuntime.nodes for transforms, sockets for attachments, colliders for physics proxies, and destructionGroups for breakable sets.',",
+ " };",
+ " return root;",
+ "}",
+ "",
+ f"export function create{type_name}LookDevLights(",
+ " mode: 'neutral' | 'grazing' | 'reference' = 'neutral',",
+ "): THREE.Group {",
+ " const lights = new THREE.Group();",
+ f" lights.name = {json.dumps(target + ' look-dev lights')};",
+ " const hemi = new THREE.HemisphereLight(",
+ " mode === 'reference' ? 0xfff0d6 : 0xf2f4ff,",
+ " 0x363b42,",
+ " mode === 'grazing' ? 0.28 : mode === 'reference' ? 0.72 : 0.85,",
+ " );",
+ " lights.add(hemi);",
+ " const key = new THREE.DirectionalLight(",
+ " mode === 'reference' ? 0xffcf8a : 0xfff4e8,",
+ " mode === 'grazing' ? 4.2 : mode === 'reference' ? 2.6 : 2.15,",
+ " );",
+ " if (mode === 'grazing') key.position.set(7.5, 1.1, 4.0);",
+ " else if (mode === 'reference') key.position.set(-4.5, 7.5, 5.0);",
+ " else key.position.set(-4.0, 6.0, 5.5);",
+ " key.castShadow = true;",
+ " key.shadow.mapSize.set(4096, 4096);",
+ " key.shadow.bias = -0.00025;",
+ " key.shadow.normalBias = 0.018;",
+ " lights.add(key);",
+ " const fill = new THREE.DirectionalLight(0xa8c4ff, mode === 'grazing' ? 0.12 : 0.42);",
+ " fill.position.set(4.0, 3.0, 3.5);",
+ " lights.add(fill);",
+ " const rim = new THREE.DirectionalLight(0xfff1c4, mode === 'grazing' ? 0.28 : 0.85);",
+ " rim.position.set(0.5, 4.5, -6.0);",
+ " lights.add(rim);",
+ " lights.userData.reviewMode = mode;",
+ f" lights.userData.lightingFromPhoto = {json_literal(lighting_from_photo)};",
+ f" lights.userData.lookDevTargets = {json_literal(look_dev_targets)};",
+ " return lights;",
+ "}",
+ "",
+ ]
+ )
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("spec", type=Path)
+ parser.add_argument("--out", type=Path, required=True)
+ parser.add_argument(
+ "--pass-id",
+ help="Build pass to generate. Defaults to the current unlocked sculptPipeline pass.",
+ )
+ parser.add_argument("--force", action="store_true")
+ args = parser.parse_args(argv)
+
+ spec = load_spec(args.spec.expanduser().resolve())
+ pass_id = args.pass_id or unlocked_pass(spec)
+ try:
+ assert_pass_unlocked(spec, pass_id)
+ except ValueError as exc:
+ parser.error(str(exc))
+ gaps = pass_specific_gaps(spec, pass_id)
+ if gaps:
+ parser.error(f"build pass {pass_id!r} needs spec refinement: {'; '.join(gaps)}")
+ output = args.out.expanduser().resolve()
+ if output.exists() and not args.force:
+ parser.error(f"{output} already exists; use --force to overwrite")
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(generate(spec, pass_id), encoding="utf-8")
+ print(output)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/make_visual_comparison_sheet.py b/scripts/make_visual_comparison_sheet.py
new file mode 100755
index 0000000..5bee134
--- /dev/null
+++ b/scripts/make_visual_comparison_sheet.py
@@ -0,0 +1,279 @@
+#!/usr/bin/env python3
+"""Create a side-by-side visual acceptance sheet for AI vision review.
+
+The sheet is only evidence packaging. It does not score the images. the agent or
+another AI vision reviewer should inspect the generated sheet and write the
+score back with append_sculpt_review.py.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import zlib
+from pathlib import Path
+
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def paeth_predictor(a: int, b: int, c: int) -> int:
+ p = a + b - c
+ pa = abs(p - a)
+ pb = abs(p - b)
+ pc = abs(p - c)
+ if pa <= pb and pa <= pc:
+ return a
+ if pb <= pc:
+ return b
+ return c
+
+
+def read_png(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
+ data = path.read_bytes()
+ if not data.startswith(PNG_SIGNATURE):
+ raise ValueError("not a PNG file")
+ cursor = len(PNG_SIGNATURE)
+ width = height = bit_depth = color_type = interlace = None
+ idat = bytearray()
+ while cursor + 8 <= len(data):
+ length = struct.unpack(">I", data[cursor : cursor + 4])[0]
+ chunk_type = data[cursor + 4 : cursor + 8]
+ chunk_data = data[cursor + 8 : cursor + 8 + length]
+ cursor += 12 + length
+ if chunk_type == b"IHDR":
+ width, height, bit_depth, color_type, _, _, interlace = struct.unpack(">IIBBBBB", chunk_data)
+ elif chunk_type == b"IDAT":
+ idat.extend(chunk_data)
+ elif chunk_type == b"IEND":
+ break
+ if width is None or height is None or bit_depth != 8 or interlace != 0:
+ raise ValueError("unsupported PNG; expected 8-bit non-interlaced image")
+ channels_by_type = {0: 1, 2: 3, 4: 2, 6: 4}
+ if color_type not in channels_by_type:
+ raise ValueError("unsupported PNG color type; convert to RGB/RGBA first")
+ channels = channels_by_type[color_type]
+ row_bytes = width * channels
+ raw = zlib.decompress(bytes(idat))
+ rows: list[bytearray] = []
+ offset = 0
+ previous = bytearray(row_bytes)
+ for _ in range(height):
+ filter_type = raw[offset]
+ offset += 1
+ row = bytearray(raw[offset : offset + row_bytes])
+ offset += row_bytes
+ for index in range(row_bytes):
+ left = row[index - channels] if index >= channels else 0
+ up = previous[index]
+ up_left = previous[index - channels] if index >= channels else 0
+ if filter_type == 1:
+ row[index] = (row[index] + left) & 0xFF
+ elif filter_type == 2:
+ row[index] = (row[index] + up) & 0xFF
+ elif filter_type == 3:
+ row[index] = (row[index] + ((left + up) // 2)) & 0xFF
+ elif filter_type == 4:
+ row[index] = (row[index] + paeth_predictor(left, up, up_left)) & 0xFF
+ elif filter_type != 0:
+ raise ValueError(f"unsupported PNG filter {filter_type}")
+ rows.append(row)
+ previous = row
+ pixels: list[tuple[int, int, int, int]] = []
+ for row in rows:
+ for x in range(width):
+ base = x * channels
+ if color_type == 0:
+ gray = row[base]
+ pixels.append((gray, gray, gray, 255))
+ elif color_type == 2:
+ pixels.append((row[base], row[base + 1], row[base + 2], 255))
+ elif color_type == 4:
+ gray = row[base]
+ pixels.append((gray, gray, gray, row[base + 1]))
+ elif color_type == 6:
+ pixels.append((row[base], row[base + 1], row[base + 2], row[base + 3]))
+ return width, height, pixels
+
+
+def write_png_rgb(path: Path, width: int, height: int, pixels: list[tuple[int, int, int]]) -> None:
+ if len(pixels) != width * height:
+ raise ValueError("pixel payload has the wrong size")
+
+ def chunk(kind: bytes, payload: bytes) -> bytes:
+ checksum = zlib.crc32(kind)
+ checksum = zlib.crc32(payload, checksum) & 0xFFFFFFFF
+ return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", checksum)
+
+ scanlines = bytearray()
+ for y in range(height):
+ scanlines.append(0)
+ for red, green, blue in pixels[y * width : (y + 1) * width]:
+ scanlines.extend((red, green, blue))
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(
+ PNG_SIGNATURE
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(bytes(scanlines), level=6))
+ + chunk(b"IEND", b"")
+ )
+
+
+def load_image(path: Path) -> tuple[int, int, list[tuple[int, int, int, int]]]:
+ try:
+ return read_png(path)
+ except Exception as direct_error:
+ sips = shutil.which("sips")
+ if not sips:
+ raise ValueError(f"could not decode {path.name} as PNG and sips is unavailable: {direct_error}") from direct_error
+ with tempfile.TemporaryDirectory() as tmpdir:
+ converted = Path(tmpdir) / "converted.png"
+ result = subprocess.run(
+ [sips, "-s", "format", "png", str(path), "--out", str(converted)],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if result.returncode != 0:
+ raise ValueError(result.stderr.strip() or result.stdout.strip() or "sips conversion failed")
+ return read_png(converted)
+
+
+def composite_over_checker(pixel: tuple[int, int, int, int], x: int, y: int) -> tuple[int, int, int]:
+ red, green, blue, alpha = pixel
+ background = 238 if ((x // 12 + y // 12) % 2 == 0) else 210
+ mix = alpha / 255.0
+ return (
+ round(red * mix + background * (1 - mix)),
+ round(green * mix + background * (1 - mix)),
+ round(blue * mix + background * (1 - mix)),
+ )
+
+
+def resize_cover(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+ target_w: int,
+ target_h: int,
+) -> list[tuple[int, int, int]]:
+ scale = max(target_w / width, target_h / height)
+ scaled_w = max(1, round(width * scale))
+ scaled_h = max(1, round(height * scale))
+ offset_x = max(0, (scaled_w - target_w) // 2)
+ offset_y = max(0, (scaled_h - target_h) // 2)
+ output: list[tuple[int, int, int]] = []
+ for y in range(target_h):
+ source_y = min(height - 1, max(0, int((y + offset_y) / scale)))
+ for x in range(target_w):
+ source_x = min(width - 1, max(0, int((x + offset_x) / scale)))
+ output.append(composite_over_checker(pixels[source_y * width + source_x], x, y))
+ return output
+
+
+def fill_rect(
+ canvas: list[tuple[int, int, int]],
+ width: int,
+ x0: int,
+ y0: int,
+ rect_w: int,
+ rect_h: int,
+ color: tuple[int, int, int],
+) -> None:
+ height = len(canvas) // width
+ for y in range(max(0, y0), min(height, y0 + rect_h)):
+ row = y * width
+ for x in range(max(0, x0), min(width, x0 + rect_w)):
+ canvas[row + x] = color
+
+
+def blit(
+ canvas: list[tuple[int, int, int]],
+ width: int,
+ image: list[tuple[int, int, int]],
+ image_w: int,
+ x0: int,
+ y0: int,
+) -> None:
+ image_h = len(image) // image_w
+ height = len(canvas) // width
+ for y in range(image_h):
+ target_y = y0 + y
+ if target_y < 0 or target_y >= height:
+ continue
+ for x in range(image_w):
+ target_x = x0 + x
+ if 0 <= target_x < width:
+ canvas[target_y * width + target_x] = image[y * image_w + x]
+
+
+def create_sheet(
+ reference: Path,
+ render: Path,
+ out: Path,
+ width: int,
+ height: int,
+ gutter: int,
+) -> dict:
+ ref_w, ref_h, ref_pixels = load_image(reference)
+ ren_w, ren_h, ren_pixels = load_image(render)
+ panel_w = width
+ panel_h = height
+ canvas_w = panel_w * 2 + gutter * 3
+ header_h = 28
+ canvas_h = panel_h + gutter * 2 + header_h
+ canvas = [(246, 242, 236)] * (canvas_w * canvas_h)
+ fill_rect(canvas, canvas_w, gutter, gutter, panel_w, header_h, (40, 45, 48))
+ fill_rect(canvas, canvas_w, gutter * 2 + panel_w, gutter, panel_w, header_h, (40, 45, 48))
+ fill_rect(canvas, canvas_w, gutter, gutter + header_h, panel_w, panel_h, (230, 230, 230))
+ fill_rect(canvas, canvas_w, gutter * 2 + panel_w, gutter + header_h, panel_w, panel_h, (230, 230, 230))
+ ref_panel = resize_cover(ref_w, ref_h, ref_pixels, panel_w, panel_h)
+ ren_panel = resize_cover(ren_w, ren_h, ren_pixels, panel_w, panel_h)
+ blit(canvas, canvas_w, ref_panel, panel_w, gutter, gutter + header_h)
+ blit(canvas, canvas_w, ren_panel, panel_w, gutter * 2 + panel_w, gutter + header_h)
+ fill_rect(canvas, canvas_w, panel_w + gutter + gutter // 2, gutter, max(2, gutter // 5), canvas_h - gutter * 2, (170, 146, 92))
+ write_png_rgb(out, canvas_w, canvas_h, canvas)
+ return {
+ "comparisonImage": str(out.resolve()),
+ "referenceImage": str(reference.resolve()),
+ "renderScreenshot": str(render.resolve()),
+ "layout": "left=reference,right=render",
+ "panelWidth": panel_w,
+ "panelHeight": panel_h,
+ "note": "Send this image to AI vision for global, layer, and semantic feature scores; this script does not score.",
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--reference", type=Path, required=True)
+ parser.add_argument("--render", type=Path, required=True)
+ parser.add_argument("--out", type=Path, required=True)
+ parser.add_argument("--panel-width", type=int, default=720)
+ parser.add_argument("--panel-height", type=int, default=720)
+ parser.add_argument("--gutter", type=int, default=24)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ payload = create_sheet(
+ args.reference.expanduser().resolve(),
+ args.render.expanduser().resolve(),
+ args.out.expanduser().resolve(),
+ max(128, args.panel_width),
+ max(128, args.panel_height),
+ max(6, args.gutter),
+ )
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ print(json.dumps(payload, indent=2, ensure_ascii=False) if args.json else payload["comparisonImage"])
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/new_pre_spec_assessment.py b/scripts/new_pre_spec_assessment.py
new file mode 100755
index 0000000..23852a2
--- /dev/null
+++ b/scripts/new_pre_spec_assessment.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python3
+"""Create a pre-spec assessment and quality contract skeleton before ObjectSculptSpec authoring."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+from new_sculpt_spec import make_pre_spec_assessment, make_quality_contract
+
+
+COMPLEXITY_MINIMUMS = {
+ "simple": {
+ "macroComponents": 1,
+ "mesoComponents": 0,
+ "microFeatureGroups": 0,
+ "materialLayers": 1,
+ "repetitionSystems": 0,
+ "reviewViewpoints": 2,
+ },
+ "moderate": {
+ "macroComponents": 2,
+ "mesoComponents": 3,
+ "microFeatureGroups": 2,
+ "materialLayers": 2,
+ "repetitionSystems": 0,
+ "reviewViewpoints": 3,
+ },
+ "complex": {
+ "macroComponents": 3,
+ "mesoComponents": 8,
+ "microFeatureGroups": 5,
+ "materialLayers": 3,
+ "repetitionSystems": 1,
+ "reviewViewpoints": 4,
+ },
+ "ultra-complex": {
+ "macroComponents": 5,
+ "mesoComponents": 16,
+ "microFeatureGroups": 8,
+ "materialLayers": 4,
+ "repetitionSystems": 2,
+ "reviewViewpoints": 5,
+ },
+}
+
+
+def make_payload(target_name: str, image: str | None, complexity: str) -> dict:
+ assessment = make_pre_spec_assessment(target_name)
+ contract = make_quality_contract()
+ assessment["sourceImage"] = image or ""
+ assessment["complexity"]["tier"] = complexity
+ assessment["specDepthDecision"]["requiredDepth"] = complexity
+ if complexity in {"complex", "ultra-complex"}:
+ assessment["specDepthDecision"]["needsRepetitionSystems"] = True
+ assessment["specDepthDecision"]["needsMaterialLocalOverrides"] = True
+ assessment["specDepthDecision"]["minimumComponentLevels"] = ["macro", "meso", "micro"]
+ elif complexity == "moderate":
+ assessment["specDepthDecision"]["minimumComponentLevels"] = ["macro", "meso"]
+ contract["qualityBar"] = complexity
+ contract["minimumSpecDepth"] = COMPLEXITY_MINIMUMS[complexity]
+ return {
+ "targetName": target_name,
+ "sourceImage": image or "",
+ "preSpecAssessment": assessment,
+ "qualityContract": contract,
+ "authoringInstruction": (
+ "Fill observed object class, complexity reasoning, featureGroups, visualDeltaChecks, "
+ "and unknowns before generating or implementing ObjectSculptSpec."
+ ),
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("target_name", help="Human-readable object name")
+ parser.add_argument("--image", help="Reference image path or URL")
+ parser.add_argument(
+ "--complexity",
+ choices=sorted(COMPLEXITY_MINIMUMS),
+ default="moderate",
+ help="Initial complexity estimate. Refine after visual inspection.",
+ )
+ parser.add_argument("--out", type=Path, help="Output JSON path")
+ parser.add_argument("--force", action="store_true", help="Overwrite output file")
+ args = parser.parse_args(argv)
+
+ payload = json.dumps(make_payload(args.target_name, args.image, args.complexity), indent=2, ensure_ascii=False) + "\n"
+ if args.out:
+ output = args.out.expanduser().resolve()
+ if output.exists() and not args.force:
+ parser.error(f"{output} already exists; use --force to overwrite")
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(payload, encoding="utf-8")
+ print(output)
+ else:
+ print(payload, end="")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/new_sculpt_spec.py b/scripts/new_sculpt_spec.py
new file mode 100755
index 0000000..9dee52c
--- /dev/null
+++ b/scripts/new_sculpt_spec.py
@@ -0,0 +1,873 @@
+#!/usr/bin/env python3
+"""Create a starter ObjectSculptSpec JSON file."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+
+def slugify(value: str) -> str:
+ slug = re.sub(r"[^A-Za-z0-9]+", "-", value.strip().lower()).strip("-")
+ return slug or "object"
+
+
+def make_pre_spec_assessment(target_name: str) -> dict:
+ return {
+ "objectClass": {
+ "primaryType": "unassessed",
+ "formLanguage": [],
+ "structureKind": [],
+ "motionPotential": [],
+ "materialFamilies": [],
+ "notes": "Fill from direct visual inspection before writing the final spec. Do not use fixed domain profiles.",
+ },
+ "complexity": {
+ "tier": "unassessed",
+ "scores": {
+ "silhouetteComplexity": 0,
+ "componentCount": 0,
+ "hierarchyDepth": 0,
+ "repetitionDensity": 0,
+ "materialLayerCount": 0,
+ "localDetailDensity": 0,
+ "occlusionRisk": 0,
+ "actionReadinessNeed": 0,
+ },
+ "estimatedCounts": {
+ "macroComponents": 1,
+ "mesoComponents": 0,
+ "microFeatureGroups": 0,
+ "materialLayers": 1,
+ "repetitionSystems": 0,
+ },
+ "reasoning": [
+ f"Assess {target_name!r} from the image before finalizing componentTree/materials.",
+ ],
+ },
+ "specDepthDecision": {
+ "requiredDepth": "unassessed",
+ "minimumComponentLevels": ["macro"],
+ "needsRepetitionSystems": False,
+ "needsMaterialLocalOverrides": False,
+ "needsMultipleReviewViews": True,
+ "needsActionReadyHierarchy": True,
+ "rationale": "Choose simple/moderate/complex/ultra-complex from observed structure, not from a hardcoded domain.",
+ },
+ "unknownsToResolveBeforeImplementation": [],
+ }
+
+
+def make_quality_contract() -> dict:
+ return {
+ "qualityBar": "unassessed",
+ "definitionOfDone": [
+ "The rendered model matches the reference silhouette, primary proportions, visible component hierarchy, material response, and most recognizable local features for the selected fidelity tier.",
+ ],
+ "minimumSpecDepth": {
+ "macroComponents": 1,
+ "mesoComponents": 0,
+ "microFeatureGroups": 0,
+ "materialLayers": 1,
+ "repetitionSystems": 0,
+ "reviewViewpoints": 3,
+ },
+ "featureGroups": [
+ {
+ "id": "overall-silhouette",
+ "name": "Overall silhouette and proportions",
+ "required": True,
+ "qualityCriteria": [
+ "Bounding shape, dominant curves, negative spaces, and scale relationships are explicitly described.",
+ ],
+ "evidenceRefs": ["full-object"],
+ "failureModes": [
+ "model reads as a generic placeholder instead of the reference object",
+ "major proportions are guessed without evidence",
+ ],
+ },
+ {
+ "id": "primary-structure",
+ "name": "Primary structure and hierarchy",
+ "required": True,
+ "qualityCriteria": [
+ "Major parts, joints, seams, contact points, and parent-child relationships are named before code generation.",
+ ],
+ "evidenceRefs": ["full-object"],
+ "failureModes": [
+ "large visible parts are merged into one mesh",
+ "component hierarchy is too shallow for the observed complexity",
+ ],
+ },
+ {
+ "id": "attachment-joint-correctness",
+ "name": "Attachment and joint correctness",
+ "required": True,
+ "qualityCriteria": [
+ "Every visible child appendage, branch, limb, handle, connector, tube, cable, horn, wing, leg, or hinged part has an attachment contract with parent socket, localStart/localEnd, contact type, embed/overlap, and gap tolerance.",
+ ],
+ "evidenceRefs": ["full-object"],
+ "failureModes": [
+ "child part root floats away from the parent",
+ "branch/limb/tube is centered in space instead of pivoting from its root",
+ "parent-child transform mixes world and local coordinates",
+ ],
+ },
+ {
+ "id": "surface-material-response",
+ "name": "Surface material response",
+ "required": True,
+ "qualityCriteria": [
+ "Albedo zones, roughness, normal/bump/displacement intent, cavity dirt, edge wear, and local overrides are specified where visible.",
+ "Important materials define independent albedo, roughness, height/normal, and AO responses instead of reusing one texture for unrelated PBR channels.",
+ "Surface response is decomposed into macro, meso, and micro frequency bands with scale and amplitude tied to object scale.",
+ ],
+ "evidenceRefs": ["full-object"],
+ "failureModes": [
+ "surface looks like flat plastic",
+ "local material variation is missing or not tied to image evidence",
+ ],
+ },
+ {
+ "id": "reference-lookdev",
+ "name": "Reference color, material, and lighting response",
+ "required": True,
+ "qualityCriteria": [
+ "Material-pass names the reference-derived albedo palette, roughness variation, tactile normal/bump/displacement response, and local masks.",
+ "When a source image is available, run reference PBR extraction and require confidence >= 0.7 before treating maps as implementation-ready.",
+ "Lighting-pass names key/fill/rim or environment light, exposure, tone mapping, background, and contact shadow behavior.",
+ "Neutral, grazing-angle, and reference-matched renders prove that surface relief survives relighting and is not painted into albedo.",
+ ],
+ "evidenceRefs": ["full-object"],
+ "failureModes": [
+ "model has acceptable shape but reads as flat shaded or plastic",
+ "colors are a generic average instead of reference-observed local color zones",
+ "lighting is evenly ambient and cannot reproduce the source value range",
+ ],
+ },
+ ],
+ "visualDeltaChecks": [
+ "silhouette and negative-space delta",
+ "component hierarchy depth delta",
+ "repetition density and distribution delta",
+ "material albedo/roughness/normal response delta",
+ "local feature placement and scale delta",
+ ],
+ "antiShallowSpecRules": [
+ "Do not proceed to code if qualityContract.qualityBar is unassessed.",
+ "Do not proceed to code if the spec only contains a root component for a moderate or complex object.",
+ "Do not proceed to code if required featureGroups are not represented by componentTree, materials, or repetitionSystems.",
+ "Do not proceed to code if visible local features are described only in prose and not attached to components/materials/evidenceRefs.",
+ "Do not proceed past structural-pass if attached child parts lack attachment.parentSocket, localStart, localEnd, embedDepth/overlap, and gapTolerance.",
+ "Do not pass material look-dev when albedo is reused as roughness, height, normal, or AO.",
+ "Do not pass material look-dev without macro, meso, and micro surface frequency bands for close-up materials.",
+ "Do not pass reference-fidelity material look-dev from a source image without usable referencePbr maps or an explicit documented limitation.",
+ "Do not patch a spec with extracted PBR maps when extraction confidence is below the target threshold unless the user explicitly accepts lower fidelity.",
+ ],
+ }
+
+
+def load_assessment(path: Path | None) -> dict | None:
+ if path is None:
+ return None
+ payload = json.loads(path.expanduser().read_text(encoding="utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError("assessment must be a JSON object")
+ return payload
+
+
+def make_spec(target_name: str, image: str | None, assessment_payload: dict | None = None) -> dict:
+ target_id = slugify(target_name)
+ pre_spec_assessment = make_pre_spec_assessment(target_name)
+ quality_contract = make_quality_contract()
+ if assessment_payload:
+ incoming_assessment = assessment_payload.get("preSpecAssessment")
+ incoming_contract = assessment_payload.get("qualityContract")
+ if isinstance(incoming_assessment, dict):
+ pre_spec_assessment = incoming_assessment
+ if isinstance(incoming_contract, dict):
+ quality_contract = incoming_contract
+ return {
+ "targetName": target_name,
+ "targetId": target_id,
+ "schemaVersion": "2.0",
+ "terminologyProfile": {
+ "domain": "real-time procedural Three.js asset",
+ "geometryTerms": [
+ "silhouette",
+ "topology",
+ "primitive",
+ "bevel",
+ "chamfer",
+ "taper",
+ "bend",
+ "boolean cut",
+ "edge loop",
+ "surface normal",
+ "displacement",
+ ],
+ "materialTerms": [
+ "albedo",
+ "baseColor",
+ "roughness",
+ "metalness",
+ "normal map",
+ "bump map",
+ "ambient occlusion",
+ "cavity dirt",
+ "edge wear",
+ "clearcoat",
+ ],
+ "lightingTerms": [
+ "key light",
+ "fill light",
+ "rim light",
+ "HDRI/environment reflection",
+ "contact shadow",
+ ],
+ "descriptionRule": "Use measurable 3D graphics terms. Avoid vague words unless they are paired with concrete geometry/material/shader parameters.",
+ },
+ "sourceImage": image or "",
+ "suitability": "conditional",
+ "scores": {
+ "object_isolation": 0,
+ "silhouette_readability": 0,
+ "depth_inference": 0,
+ "primitive_decomposition": 0,
+ "material_procedurality": 0,
+ "occlusion_risk": 0,
+ "interaction_fit": 0,
+ },
+ "preSpecAssessment": pre_spec_assessment,
+ "qualityContract": quality_contract,
+ "qualityTargets": {
+ "targetFidelity": 0.7,
+ "mustMatch": [
+ "macro silhouette and proportions",
+ "primary material albedo/roughness response",
+ "reference-derived PBR material response at or above 0.7 confidence when source pixels are usable",
+ "most recognizable local features",
+ ],
+ "niceToHave": [
+ "micro scratches, stains, chips, and dirt masks",
+ "secondary lighting match",
+ ],
+ "fpsTarget": 60,
+ "reviewViewpoints": ["front", "three-quarter", "side"],
+ },
+ "selfCorrectLoop": {
+ "enabled": True,
+ "visualAcceptance": {
+ "reviewer": "ai-vision",
+ "threshold": 0.7,
+ "comparisonArtifactRequired": True,
+ "layerScoresRequired": True,
+ "codePixelDiffIsAcceptanceAuthority": False,
+ "scoringRule": "AI vision must inspect a side-by-side reference/render sheet and score the current pass from 0 to 1. Pixel-diff code may assist diagnostics but cannot approve a pass.",
+ "requiredLayerScores": [
+ "silhouetteProportion",
+ "componentStructure",
+ "formDetail",
+ "materialSurface",
+ "lightingCamera",
+ ],
+ "featureReviewPolicy": {
+ "enabled": True,
+ "reviewUnit": "semantic-subsystem",
+ "maxCriticalFeaturesPerPass": 5,
+ "maxImportantFeaturesPerPass": 3,
+ "criticalDefaultThreshold": 0.8,
+ "importantAverageThreshold": 0.65,
+ "adaptiveEscalation": True,
+ "singleImagePairOnly": True,
+ "selectionRule": "Choose only the most visually salient, identity-defining, user-prioritized, or high-risk semantic systems. Group repeated parts instead of reviewing every mesh. AI vision scores every selected feature from the same full reference/render pair.",
+ },
+ },
+ "reviewAfterPasses": [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ "optimization-pass",
+ ],
+ "allowedActions": [
+ "continue",
+ "refine-spec",
+ "refine-code",
+ "request-input",
+ "stop",
+ ],
+ "specRefineTriggers": [
+ "missing component",
+ "wrong primitive family",
+ "wrong proportions",
+ "material layer under-specified",
+ "local feature not traceable to viewEvidence",
+ "reference ambiguity discovered during implementation",
+ ],
+ "codeRefineTriggers": [
+ "spec is adequate but generated geometry/material does not match",
+ "browser render differs from reference",
+ "performance budget exceeded",
+ "lighting hides geometry or material response",
+ ],
+ "stopCriteria": [
+ "target fidelity reached or user accepts current approximation",
+ "remaining gaps require new reference images or manual art",
+ ],
+ "screenshotPolicy": {
+ "requiredForPasses": [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ ],
+ "preferredCapture": "in-app-browser-screenshot",
+ "fallbackCapture": "user-supplied-screenshot-path",
+ "minimumEvidence": "Each visual pass needs a reference image, rendered screenshot, side-by-side comparison sheet, AI vision score, layer scores, and critique before choosing continue.",
+ "reviewPairRule": "Compare the same camera/viewpoint whenever possible; do not judge a front reference against a random render angle.",
+ "acceptanceAuthority": "AI vision review of the comparison sheet. Code-generated pixel similarity is not sufficient evidence.",
+ },
+ },
+ "featureReviewTargets": [
+ {
+ "id": "overall-silhouette",
+ "name": "Overall silhouette and proportion system",
+ "tier": "critical",
+ "passIds": ["blockout"],
+ "minimumScore": 0.8,
+ "mustPass": True,
+ "componentRefs": ["root"],
+ "evidenceRefs": ["full-object"],
+ },
+ {
+ "id": "primary-structure",
+ "name": "Primary identity-defining structure",
+ "tier": "critical",
+ "passIds": ["structural-pass", "form-refinement"],
+ "minimumScore": 0.8,
+ "mustPass": True,
+ "componentRefs": ["root"],
+ "evidenceRefs": ["full-object"],
+ },
+ {
+ "id": "reference-material-system",
+ "name": "Primary reference material and surface response",
+ "tier": "critical",
+ "passIds": ["material-pass", "surface-pass"],
+ "minimumScore": 0.75,
+ "mustPass": True,
+ "componentRefs": ["root"],
+ "evidenceRefs": ["full-object"],
+ },
+ ],
+ "sculptPipeline": {
+ "passGateMode": "locked-sequential",
+ "passOrder": [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ "optimization-pass",
+ ],
+ "currentPass": "blockout",
+ "completedPasses": [],
+ "lastCompletedPass": "",
+ "blockedReason": "blockout requires a browser screenshot and self-correction review before structural-pass unlocks",
+ "nextRequiredEvidence": [
+ "blockout browser render screenshot from your agent's browser/screenshot tool",
+ "side-by-side reference/render comparison sheet",
+ "AI vision score >= 0.7 with layer scores and mismatch critique",
+ "critical semantic feature scores from the same image pair meeting their individual thresholds",
+ "reviewHistory entry for blockout with action=continue",
+ ],
+ },
+ "lookDevTargets": {
+ "qualityPriority": "reference-fidelity",
+ "materialPass": {
+ "albedoPaletteRequired": True,
+ "roughnessVariationRequired": True,
+ "normalOrBumpRequired": True,
+ "localOverridesRequired": True,
+ "minimumTextureResolution": 1024,
+ "preferredTextureResolution": 2048,
+ "independentMapChannels": [
+ "albedo",
+ "roughness",
+ "height",
+ "normal",
+ "ambient-occlusion",
+ ],
+ "requiredSurfaceFrequencyBands": ["macro", "meso", "micro"],
+ "geometryReliefRequiredWhenSilhouetteAffected": True,
+ "referencePbrExtraction": {
+ "requiredWhenSourceImagePresent": True,
+ "targetThreshold": 0.7,
+ "stopOnLowConfidence": True,
+ "script": "scripts/extract_reference_pbr.py",
+ "acceptedLimitation": "single-image extraction is reference-derived inference, not exact photogrammetry",
+ },
+ "mustAvoid": [
+ "single flat albedo per material",
+ "uniform roughness",
+ "albedo texture reused as roughness/height/normal/AO",
+ "single-frequency random noise",
+ "plastic-looking smooth bark, stone, cloth, foliage, or aged material",
+ "local color/detail described only in prose without material masks",
+ "claiming exact PBR recovery when confidence is below the target threshold",
+ ],
+ },
+ "lightingPass": {
+ "requiredTerms": [
+ "key light",
+ "fill light",
+ "rim or environment light",
+ "exposure",
+ "tone mapping",
+ "background",
+ "contact shadow",
+ ],
+ "mustAvoid": [
+ "ambient-only lighting",
+ "flat value range",
+ "missing contact shadow",
+ "reference lighting copied without separating material readability",
+ ],
+ },
+ "screenshotReview": [
+ "Compare albedo palette and local color zones.",
+ "Compare roughness/normal/bump response under light.",
+ "Compare cavity dirt, edge wear, stains, moss, scratches, or other local masks.",
+ "Compare key/fill/rim structure, exposure, tone mapping, background, and contact shadows.",
+ "Capture a neutral-light render to verify material readability without reference lighting.",
+ "Capture a grazing-light close-up to expose flat normals, uniform roughness, tiling, and plastic highlights.",
+ "Capture a reference-matched render from the same camera framing as the source.",
+ ],
+ },
+ "actionReadiness": {
+ "contract": "Every macro/meso component should be generated as a stable named Object3D pivot node with a mesh child, action metadata, optional sockets, collider proxy, and destruction metadata.",
+ "defaultRigType": "action-ready-static-rig",
+ "rootMotionNode": "root",
+ "requiredComponentFields": [
+ "id",
+ "parent",
+ "transform",
+ "attachment for child appendages, connectors, limbs, tubes, handles, legs, horns, wings, branches, or cables",
+ "actionProfile.animationRole",
+ "actionProfile.pivot",
+ "actionProfile.collider",
+ "actionProfile.destruction",
+ ],
+ "transformChannels": [
+ "translate",
+ "rotate",
+ "scale",
+ "bend",
+ "twist",
+ "detach",
+ "visibility",
+ "material-state",
+ ],
+ "authoringRules": [
+ "Do not collapse independently movable parts into one mesh.",
+ "Put transforms on component pivot groups, not only on raw meshes.",
+ "For attached child parts, put the pivot at the semantic root/socket and build visible geometry from localStart to localEnd.",
+ "Represent hinge, socket, detachable, and breakable intent even when no animation is implemented yet.",
+ "Use simplified collider proxies for runtime physics instead of visual mesh colliders by default.",
+ ],
+ "destructionPolicy": {
+ "defaultBreakable": False,
+ "fractureGroupNaming": "Use stable semantic names such as body-shell, left-hinge, glass-panel, branch-segment.",
+ "debrisStrategy": "Prefer detachable component groups and a small number of procedural fragments over random mesh explosion.",
+ },
+ },
+ "assumptions": [],
+ "coordinateFrame": {
+ "front": "camera-facing side in the reference image",
+ "up": "image up direction",
+ "scaleReference": "unit scale; adjust after first browser render",
+ },
+ "silhouette": {
+ "boundingShape": "",
+ "aspectRatios": [],
+ "symmetry": "",
+ "dominantCurves": [],
+ "negativeSpaces": [],
+ "landmarks": [],
+ },
+ "viewEvidence": [
+ {
+ "id": "full-object",
+ "view": "primary",
+ "imageRegion": {
+ "x": 0.0,
+ "y": 0.0,
+ "width": 1.0,
+ "height": 1.0,
+ "units": "normalized",
+ },
+ "observations": [],
+ "confidence": 0.5,
+ }
+ ],
+ "componentTree": [
+ {
+ "id": "root",
+ "name": target_name,
+ "level": "macro",
+ "role": "body",
+ "importance": 1.0,
+ "confidence": 0.5,
+ "primitive": "box",
+ "geometryDescriptor": {
+ "topologyIntent": "low-poly blockout with bevel-ready edges",
+ "edgeTreatment": {
+ "type": "none",
+ "bevelRadius": 0.0,
+ "segments": 1,
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry",
+ },
+ "parent": None,
+ "attachment": None,
+ "dimensions": {
+ "width": 1.0,
+ "height": 1.0,
+ "depth": 1.0,
+ "units": "relative",
+ "confidence": 0.5,
+ },
+ "transform": {
+ "position": [0, 0, 0],
+ "rotation": [0, 0, 0],
+ "scale": [1, 1, 1],
+ },
+ "actionProfile": {
+ "animationRole": "root",
+ "pivot": {
+ "mode": "center",
+ "localPosition": [0, 0, 0],
+ "axis": [0, 1, 0],
+ "confidence": 0.5,
+ },
+ "transformChannels": {
+ "translate": True,
+ "rotate": True,
+ "scale": True,
+ "bend": False,
+ "twist": False,
+ "detach": False,
+ "visibility": True,
+ "materialState": True,
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [0, 0, 0],
+ "scale": [1, 1, 1],
+ "isTrigger": False,
+ "notes": "Replace with sphere/capsule/compound proxy when the object shape demands it.",
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": False,
+ "fractureGroup": "root",
+ "seamRefs": [],
+ "detachableFragments": [],
+ "breakImpulse": 0.0,
+ "debrisMaterial": "base",
+ },
+ },
+ "material": "base",
+ "materialLayers": ["base"],
+ "deformations": [],
+ "joints": [],
+ "seams": [],
+ "localFeatures": [],
+ "surfaceDetail": {
+ "macroRoughness": 0.0,
+ "microRoughness": 0.0,
+ "bumpAmplitude": 0.0,
+ "normalPattern": "",
+ "displacementPattern": "",
+ "occlusionPattern": "",
+ "edgeWearPattern": "",
+ "notes": "",
+ },
+ "evidenceRefs": ["full-object"],
+ "details": [],
+ "fidelityTier": "blockout",
+ }
+ ],
+ "materials": [
+ {
+ "id": "base",
+ "name": "Base material",
+ "type": "standard",
+ "shaderModel": "MeshStandardMaterial / PBR approximation",
+ "baseColor": "#8A7A5F",
+ "color": "#8A7A5F",
+ "albedo": {
+ "dominant": "#8A7A5F",
+ "secondary": ["#6E614B", "#A08F70"],
+ "samplingNotes": "Use image-observed local color zones, not a single averaged color.",
+ },
+ "colorVariation": {
+ "palette": ["#8A7A5F", "#6E614B", "#A08F70"],
+ "pattern": "mottled",
+ "amplitude": 0.15,
+ "heightCorrelation": 0.3,
+ },
+ "textureResolution": 1024,
+ "textureProjection": {
+ "mode": "uv",
+ "repeat": [2.0, 2.0],
+ "anisotropy": 8,
+ "texelDensityIntent": "Preserve stable world/object-scale detail; do not stretch micro detail with component scale.",
+ },
+ "surfaceFrequencyBands": [
+ {
+ "id": "macro",
+ "frequency": 2.0,
+ "amplitude": 0.42,
+ "role": "broad color and height breakup",
+ },
+ {
+ "id": "meso",
+ "frequency": 12.0,
+ "amplitude": 0.22,
+ "role": "ridges, pores, grain, dents, or equivalent visible relief",
+ },
+ {
+ "id": "micro",
+ "frequency": 56.0,
+ "amplitude": 0.08,
+ "role": "highlight breakup visible under grazing light",
+ },
+ ],
+ "roughness": {
+ "base": 0.75,
+ "variation": 0.15,
+ "map": "independent-procedural-field",
+ "localResponse": "higher roughness in cavities, lower roughness on worn edges",
+ },
+ "metalness": {
+ "base": 0.0,
+ "variation": 0.0,
+ },
+ "normal": {
+ "pattern": "derived-from-independent-height-field",
+ "strength": 0.35,
+ "scale": 24.0,
+ "space": "tangent",
+ },
+ "bump": {
+ "pattern": "none",
+ "amplitude": 0.0,
+ "scale": 1.0,
+ },
+ "displacement": {
+ "pattern": "none",
+ "amplitude": 0.0,
+ "scale": 1.0,
+ "silhouetteAffects": False,
+ },
+ "ambientOcclusion": {
+ "cavityStrength": 0.25,
+ "contactShadowBias": 0.35,
+ "notes": "Darken creases, seams, intersections, and recessed local features.",
+ },
+ "wear": {
+ "edgeWear": 0.0,
+ "scratches": [],
+ "chips": [],
+ },
+ "dirt": {
+ "amount": 0.0,
+ "cavityBias": 0.0,
+ "color": "#2F2A22",
+ },
+ "localOverrides": [],
+ "shaderNotes": [
+ "Prefer MeshPhysicalMaterial when clearcoat, sheen, transmission, or thin-surface response is observed; otherwise use MeshStandardMaterial-compatible PBR channels.",
+ "Generate albedo, roughness, height/normal, and AO independently; never alias albedo into roughness.",
+ "Use normal/bump/displacement only when they map to observed surface relief.",
+ "Use displacement geometry when the observed relief changes the close-up silhouette; texture-only relief is insufficient there.",
+ ],
+ "notes": "Replace with image-derived color, roughness, noise, and edge-wear notes.",
+ }
+ ],
+ "repetitionSystems": [],
+ "buildPasses": [
+ {
+ "id": "blockout",
+ "goal": "Match macro silhouette and proportions.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "Silhouette reads correctly without materials.",
+ "Quality contract has named all required macro feature groups before code generation.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
+ ],
+ },
+ {
+ "id": "structural-pass",
+ "goal": "Build the component hierarchy implied by the pre-spec complexity assessment.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "Macro, meso, and repeated structures meet qualityContract.minimumSpecDepth.",
+ "Parent-child relations, joints, seams, sockets, and contact points are explicit.",
+ "Every attached child appendage/connector has parentSocket, localStart/localEnd, contactType, embedDepth or overlap, and gapTolerance.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
+ ],
+ },
+ {
+ "id": "form-refinement",
+ "goal": "Refine shape, deformation, bevels, tapers, curves, asymmetry, and visible local geometry.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "Important visible forms are represented in component geometryDescriptor, deformations, localFeatures, or repetitionSystems.",
+ "Endpoint-based child parts are rooted at their attachment sockets and do not visibly float away from parents.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
+ ],
+ },
+ {
+ "id": "material-pass",
+ "goal": "Match material color, roughness, bump, and local variation.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "Reference-derived albedo palette records dominant, secondary, and accent colors per visible material.",
+ "Each important material defines roughness variation and at least one normal/bump/displacement response.",
+ "Local material overrides, dirt/wear/stains/moss/chips/scratches or equivalent masks are tied to evidenceRefs.",
+ "Thin, transparent, reflective, wet, or fibrous materials document alpha/transmission/clearcoat/metalness/fiber response when relevant.",
+ "Generated preview uses procedural albedo/roughness/bump texture or vertex color variation instead of one flat color.",
+ "Generated preview uses independent PBR maps at 1024px or higher for the quality-first tier.",
+ "If source pixels are available, referencePbr extraction passed at confidence >= 0.7 or the pass is stopped/requesting better references.",
+ "Macro, meso, and micro surface frequency bands are visible at the intended review distance without obvious tiling.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
+ ],
+ },
+ {
+ "id": "surface-pass",
+ "goal": "Add procedural surface locality such as normal/bump/displacement, AO, dirt, stains, chips, grain, moss, scratches, and wear.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "Every required material feature group has local overrides or surfaceDetail tied to evidenceRefs.",
+ "A grazing-angle close-up proves that normal/height detail breaks highlights naturally and does not read as smooth plastic.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
+ ],
+ },
+ {
+ "id": "lighting-pass",
+ "goal": "Make material and form readable under neutral turntable lighting plus optional reference lighting.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "lightingFromPhoto identifies key light direction/color/intensity, fill light, rim or environment light, and ambient color.",
+ "Exposure, tone mapping, background color/gradient, shadow softness, and contact shadow behavior are specified.",
+ "Lighting does not hide geometry/material gaps and screenshots can be compared fairly to the reference.",
+ "Neutral, grazing, and reference-matched lighting checks distinguish material errors from lighting errors.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
+ ],
+ },
+ {
+ "id": "interaction-pass",
+ "goal": "Make the model ready for future animation, transformation, physics, or destruction.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "Macro and movable meso components have stable pivot nodes.",
+ "Sockets, collider proxies, and destruction metadata are present for future runtime actions.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold.",
+ ],
+ },
+ {
+ "id": "optimization-pass",
+ "goal": "Protect runtime performance after visual fidelity is accepted.",
+ "componentRefs": ["root"],
+ "acceptance": [
+ "Triangle count, draw calls, instancing, LOD strategy, and FPS target are documented or verified.",
+ "Repeated detail is instanced or simplified where possible without breaking silhouette/material believability.",
+ ],
+ },
+ ],
+ "visualEvidence": [],
+ "reviewHistory": [],
+ "lodPlan": [
+ {
+ "tier": "near",
+ "distance": 0,
+ "strategy": "full component tree and material layers",
+ },
+ {
+ "tier": "far",
+ "distance": 30,
+ "strategy": "merge static components and reduce local feature geometry",
+ },
+ ],
+ "performanceBudget": {
+ "qualityPriority": "reference-fidelity",
+ "targetTriangles": 250000,
+ "maxDrawCalls": 160,
+ "textureSize": 2048,
+ "fpsTarget": 30,
+ "optimizationPolicy": "Reach accepted visual fidelity first, then optimize without removing reference-critical geometry or surface layers.",
+ },
+ "lightingFromPhoto": [],
+ "proceduralStrategy": [
+ "Block out macro silhouette first.",
+ "Add component hierarchy and joints.",
+ "Create stable pivot groups, sockets, collider proxies, and destruction metadata before visual polish.",
+ "Refine forms with bevels, tapers, bends, and procedural noise.",
+ "Run reference PBR extraction for important source-image materials and stop when confidence is below the target threshold.",
+ "Add material variation before adding expensive micro-geometry.",
+ ],
+ "animationAnchors": [
+ "root pivot node supports whole-object translation, rotation, scale, and visibility changes",
+ "component pivot groups support later local transforms without rebuilding geometry",
+ ],
+ "destructionAnchors": [
+ "actionProfile.destruction.fractureGroup marks detachable or breakable component sets",
+ "component seams and sockets define plausible break points instead of random explosions",
+ ],
+ "risks": [],
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("target_name", help="Human-readable object name")
+ parser.add_argument("--image", help="Reference image path or URL")
+ parser.add_argument("--assessment", type=Path, help="Pre-spec assessment JSON from new_pre_spec_assessment.py")
+ parser.add_argument("--out", type=Path, help="Output JSON path")
+ parser.add_argument("--force", action="store_true", help="Overwrite output file")
+ args = parser.parse_args(argv)
+
+ spec = make_spec(args.target_name, args.image, load_assessment(args.assessment))
+ payload = json.dumps(spec, indent=2, ensure_ascii=False) + "\n"
+
+ if args.out:
+ output = args.out.expanduser().resolve()
+ if output.exists() and not args.force:
+ parser.error(f"{output} already exists; use --force to overwrite")
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(payload, encoding="utf-8")
+ print(output)
+ else:
+ print(payload, end="")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/probe_reference_image.py b/scripts/probe_reference_image.py
new file mode 100755
index 0000000..b550184
--- /dev/null
+++ b/scripts/probe_reference_image.py
@@ -0,0 +1,168 @@
+#!/usr/bin/env python3
+"""Probe basic technical properties of a reference image before visual analysis."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import struct
+import sys
+from pathlib import Path
+
+
+def png_size(data: bytes) -> tuple[int, int] | None:
+ if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:
+ return struct.unpack(">II", data[16:24])
+ return None
+
+
+def gif_size(data: bytes) -> tuple[int, int] | None:
+ if data[:6] in {b"GIF87a", b"GIF89a"} and len(data) >= 10:
+ return struct.unpack("<HH", data[6:10])
+ return None
+
+
+def jpeg_size(data: bytes) -> tuple[int, int] | None:
+ if not data.startswith(b"\xff\xd8"):
+ return None
+ index = 2
+ while index + 9 < len(data):
+ if data[index] != 0xFF:
+ index += 1
+ continue
+ marker = data[index + 1]
+ index += 2
+ if marker in {0xD8, 0xD9}:
+ continue
+ if index + 2 > len(data):
+ return None
+ length = struct.unpack(">H", data[index : index + 2])[0]
+ if length < 2 or index + length > len(data):
+ return None
+ if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}:
+ if length >= 7:
+ height, width = struct.unpack(">HH", data[index + 3 : index + 7])
+ return width, height
+ index += length
+ return None
+
+
+def webp_size(data: bytes) -> tuple[int, int] | None:
+ if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":
+ return None
+ chunk = data[12:16]
+ if chunk == b"VP8X" and len(data) >= 30:
+ width = 1 + int.from_bytes(data[24:27], "little")
+ height = 1 + int.from_bytes(data[27:30], "little")
+ return width, height
+ if chunk == b"VP8 " and len(data) >= 30:
+ start = data.find(b"\x9d\x01\x2a")
+ if start != -1 and start + 7 <= len(data):
+ width, height = struct.unpack("<HH", data[start + 3 : start + 7])
+ return width & 0x3FFF, height & 0x3FFF
+ return None
+
+
+def bmp_size(data: bytes) -> tuple[int, int] | None:
+ if len(data) >= 26 and data[:2] == b"BM":
+ width = struct.unpack("<I", data[18:22])[0]
+ height = abs(struct.unpack("<i", data[22:26])[0])
+ return width, height
+ return None
+
+
+def tiff_size(data: bytes) -> tuple[int, int] | None:
+ if len(data) < 8:
+ return None
+ if data[:4] == b"II*\x00":
+ endian = "<"
+ elif data[:4] == b"MM\x00*":
+ endian = ">"
+ else:
+ return None
+ offset = struct.unpack(f"{endian}I", data[4:8])[0]
+ if offset + 2 > len(data):
+ return None
+ entries = struct.unpack(f"{endian}H", data[offset : offset + 2])[0]
+ width = height = None
+ cursor = offset + 2
+ for _ in range(entries):
+ if cursor + 12 > len(data):
+ return None
+ tag, value_type, count, raw_value = struct.unpack(f"{endian}HHII", data[cursor : cursor + 12])
+ if value_type in {3, 4} and count == 1:
+ value = raw_value if value_type == 4 else raw_value & 0xFFFF
+ if tag == 256:
+ width = value
+ elif tag == 257:
+ height = value
+ cursor += 12
+ if width and height:
+ return width, height
+ return None
+
+
+def detect_image_type(data: bytes) -> str | None:
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "png"
+ if data.startswith(b"\xff\xd8"):
+ return "jpeg"
+ if data[:6] in {b"GIF87a", b"GIF89a"}:
+ return "gif"
+ if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "webp"
+ if data.startswith(b"BM"):
+ return "bmp"
+ if data[:4] in {b"II*\x00", b"MM\x00*"}:
+ return "tiff"
+ return None
+
+
+def detect_size(data: bytes) -> tuple[int, int] | None:
+ return png_size(data) or jpeg_size(data) or gif_size(data) or webp_size(data) or bmp_size(data) or tiff_size(data)
+
+
+def probe(path: Path) -> dict:
+ data = path.read_bytes()
+ image_type = detect_image_type(data)
+ size = detect_size(data)
+ warnings: list[str] = []
+ if not image_type:
+ warnings.append("unknown image type")
+ if not size:
+ warnings.append("could not read image dimensions")
+ width = height = None
+ aspect = None
+ else:
+ width, height = size
+ aspect = width / height if height else None
+ if width < 512 or height < 512:
+ warnings.append("low resolution; small geometry/material details may be unreliable")
+ if aspect and (aspect > 3.0 or aspect < 0.33):
+ warnings.append("extreme aspect ratio; object may be cropped or surrounded by empty space")
+ return {
+ "path": str(path),
+ "type": image_type,
+ "bytes": len(data),
+ "width": width,
+ "height": height,
+ "aspectRatio": aspect,
+ "technicalSuitability": "conditional" if warnings else "pass",
+ "warnings": warnings,
+ "note": "This is only technical image probing. Semantic object suitability still requires visual inspection.",
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("image", type=Path)
+ args = parser.parse_args(argv)
+ path = args.image.expanduser().resolve()
+ if not path.exists():
+ parser.error(f"{path} does not exist")
+ print(json.dumps(probe(path), indent=2, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/requirements.txt b/scripts/requirements.txt
new file mode 100644
index 0000000..90cf1bc
--- /dev/null
+++ b/scripts/requirements.txt
@@ -0,0 +1,6 @@
+# Three.js Object Sculptor scripts have NO third-party dependencies.
+# Everything uses the Python 3.10+ standard library only (json, argparse, struct,
+# zlib, pathlib, math, subprocess). PNG maps and comparison sheets are written with
+# struct/zlib directly — no Pillow/numpy/OpenCV/Playwright required.
+#
+# Requires: python >= 3.10
diff --git a/scripts/sculpt_pass_orchestrator.py b/scripts/sculpt_pass_orchestrator.py
new file mode 100755
index 0000000..8f5298c
--- /dev/null
+++ b/scripts/sculpt_pass_orchestrator.py
@@ -0,0 +1,542 @@
+#!/usr/bin/env python3
+"""Gate procedural sculpt generation through ordered build passes."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from visual_feature_gate import feature_gate_failures
+
+
+DEFAULT_PASS_ORDER = [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ "optimization-pass",
+]
+VISUAL_PASS_IDS = set(DEFAULT_PASS_ORDER) - {"optimization-pass"}
+ATTACHMENT_ROLES = {
+ "appendage",
+ "branch",
+ "limb",
+ "arm",
+ "leg",
+ "handle",
+ "connector",
+ "tube",
+ "cable",
+ "horn",
+ "wing",
+ "tail",
+ "root",
+ "fork",
+ "rib",
+ "support",
+ "hinge",
+ "socket",
+ "pipe",
+}
+ATTACHMENT_PRIMITIVES = {"cylinder", "cone", "capsule", "tube", "curve-sweep"}
+
+
+def load_spec(path: Path) -> dict[str, Any]:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError("spec must be a JSON object")
+ return payload
+
+
+def write_spec(path: Path, spec: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+
+def pass_order(spec: dict[str, Any]) -> list[str]:
+ ids: list[str] = []
+ for item in spec.get("buildPasses", []):
+ if isinstance(item, dict) and isinstance(item.get("id"), str) and item["id"].strip():
+ ids.append(item["id"])
+ return ids or DEFAULT_PASS_ORDER.copy()
+
+
+def pass_acceptance(spec: dict[str, Any], pass_id: str) -> list[str]:
+ for item in spec.get("buildPasses", []):
+ if isinstance(item, dict) and item.get("id") == pass_id:
+ acceptance = item.get("acceptance", [])
+ if isinstance(acceptance, list):
+ return [str(value) for value in acceptance if str(value).strip()]
+ return []
+
+
+def visual_evidence(entry: dict[str, Any]) -> dict[str, Any]:
+ visual = entry.get("visualEvidence")
+ return visual if isinstance(visual, dict) else {}
+
+
+def review_completes_pass(spec: dict[str, Any], entry: dict[str, Any], pass_id: str) -> bool:
+ if entry.get("passId") != pass_id or entry.get("action") != "continue":
+ return False
+ if pass_id in VISUAL_PASS_IDS:
+ visual = visual_evidence(entry)
+ if not visual.get("renderScreenshot") or not visual.get("comparisonImage"):
+ return False
+ score = entry.get("aiVisionScore")
+ threshold = entry.get("visualAcceptanceThreshold", 0.7)
+ if not has_number(score) or not has_number(threshold) or float(score) < float(threshold):
+ return False
+ if feature_gate_failures(spec, entry, pass_id):
+ return False
+ return True
+
+
+def completed_passes(spec: dict[str, Any], ids: list[str]) -> list[str]:
+ history = spec.get("reviewHistory", [])
+ if not isinstance(history, list):
+ return []
+ completed: list[str] = []
+ for pass_id in ids:
+ if any(
+ isinstance(entry, dict) and review_completes_pass(spec, entry, pass_id)
+ for entry in history
+ ):
+ completed.append(pass_id)
+ else:
+ break
+ return completed
+
+
+def current_pass(ids: list[str], completed: list[str]) -> str:
+ if len(completed) >= len(ids):
+ return "complete"
+ return ids[len(completed)]
+
+
+def next_required_evidence(spec: dict[str, Any], pass_id: str) -> list[str]:
+ if pass_id == "complete":
+ return []
+ evidence = pass_acceptance(spec, pass_id)
+ evidence.extend(pass_specific_evidence(pass_id))
+ 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")
+ 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")
+ return evidence
+
+
+def has_non_empty(value: Any) -> bool:
+ if isinstance(value, str):
+ return bool(value.strip()) and value.strip().lower() not in {"none", "unassessed", "n/a"}
+ if isinstance(value, list):
+ return any(has_non_empty(item) for item in value)
+ if isinstance(value, dict):
+ return any(has_non_empty(item) for item in value.values())
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return abs(float(value)) > 0
+ return False
+
+
+def number_from_layer(value: Any, keys: tuple[str, ...]) -> float:
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
+ if isinstance(value, dict):
+ for key in keys:
+ item = value.get(key)
+ if isinstance(item, (int, float)) and not isinstance(item, bool):
+ return float(item)
+ return 0.0
+
+
+def is_vector3(value: Any) -> bool:
+ return (
+ isinstance(value, list)
+ and len(value) == 3
+ and all(isinstance(item, (int, float)) and not isinstance(item, bool) for item in value)
+ )
+
+
+def has_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def component_requires_attachment(component: dict[str, Any]) -> bool:
+ if not component.get("parent"):
+ return False
+ role = str(component.get("role") or "").lower()
+ name = str(component.get("name") or component.get("id") or "").lower()
+ primitive = str(component.get("primitive") or "").lower()
+ action = component.get("actionProfile") if isinstance(component.get("actionProfile"), dict) else {}
+ animation_role = str(action.get("animationRole") or "").lower()
+ tokens = {role, animation_role} | set(re.findall(r"[a-z0-9]+", name))
+ return bool(tokens & ATTACHMENT_ROLES) or primitive in ATTACHMENT_PRIMITIVES
+
+
+def attachment_complete(component: dict[str, Any]) -> bool:
+ attachment = component.get("attachment")
+ if not isinstance(attachment, dict):
+ return False
+ has_endpoint = is_vector3(attachment.get("localStart")) and is_vector3(attachment.get("localEnd"))
+ has_socket = has_non_empty(attachment.get("parentSocket")) or has_non_empty(attachment.get("parentId"))
+ has_contact = has_non_empty(attachment.get("contactType"))
+ has_overlap = (
+ number_from_layer(attachment.get("embedDepth"), ("base", "amount", "value")) > 0
+ or number_from_layer(attachment.get("overlap"), ("base", "amount", "value")) > 0
+ )
+ has_tolerance = has_number(attachment.get("gapTolerance"))
+ return has_endpoint and has_socket and has_contact and has_overlap and has_tolerance
+
+
+def attachment_gaps(spec: dict[str, Any]) -> list[str]:
+ gaps: list[str] = []
+ for component in spec.get("componentTree", []):
+ if not isinstance(component, dict) or not component_requires_attachment(component):
+ continue
+ if attachment_complete(component):
+ continue
+ component_id = str(component.get("id") or component.get("name") or "(unnamed)")
+ gaps.append(
+ f"component {component_id!r} requires attachment.parentSocket/localStart/localEnd/"
+ "contactType/embedDepth(or overlap)/gapTolerance"
+ )
+ return gaps
+
+
+def material_has_palette(material: dict[str, Any]) -> bool:
+ color_variation = material.get("colorVariation")
+ if isinstance(color_variation, dict) and len(color_variation.get("palette", [])) >= 2:
+ return True
+ albedo = material.get("albedo")
+ if isinstance(albedo, dict) and has_non_empty(albedo.get("secondary")):
+ return True
+ return has_non_empty(material.get("baseColor") or material.get("color"))
+
+
+def material_has_response(material: dict[str, Any]) -> bool:
+ if number_from_layer(material.get("roughness"), ("variation", "base")) > 0:
+ return True
+ if number_from_layer(material.get("normal"), ("strength", "amplitude")) > 0:
+ return True
+ if number_from_layer(material.get("bump"), ("amplitude", "strength")) > 0:
+ return True
+ if number_from_layer(material.get("displacement"), ("amplitude", "strength")) > 0:
+ return True
+ return False
+
+
+def material_has_locality(material: dict[str, Any]) -> bool:
+ if has_non_empty(material.get("localOverrides")):
+ return True
+ wear = material.get("wear")
+ if isinstance(wear, dict) and (
+ number_from_layer(wear.get("edgeWear"), ("base", "amount")) > 0
+ or has_non_empty(wear.get("scratches"))
+ or has_non_empty(wear.get("chips"))
+ ):
+ return True
+ dirt = material.get("dirt")
+ if isinstance(dirt, dict) and (
+ number_from_layer(dirt.get("amount"), ("base", "amount")) > 0
+ or number_from_layer(dirt.get("cavityBias"), ("base", "amount")) > 0
+ ):
+ return True
+ for field in ("moss", "stains", "scratches", "chips", "wetness", "patina", "soot"):
+ if has_non_empty(material.get(field)):
+ return True
+ return False
+
+
+def quality_first_enabled(spec: dict[str, Any]) -> bool:
+ targets = spec.get("lookDevTargets")
+ return isinstance(targets, dict) and targets.get("qualityPriority") == "reference-fidelity"
+
+
+def reference_pbr_usable(material: dict[str, Any], threshold: float) -> tuple[bool, str]:
+ material_id = str(material.get("id") or "(unnamed)")
+ reference = material.get("referencePbr")
+ if not isinstance(reference, dict):
+ return False, f"material {material_id!r} needs usable referencePbr extracted from source pixels"
+ if reference.get("usable") is not True:
+ return False, f"material {material_id!r} referencePbr.usable must be true"
+ confidence = reference.get("confidence", reference.get("estimatedFidelity"))
+ if not has_number(confidence) or float(confidence) < threshold:
+ return False, f"material {material_id!r} referencePbr confidence must be >= {threshold}"
+ maps = reference.get("maps")
+ if not isinstance(maps, dict):
+ return False, f"material {material_id!r} referencePbr needs maps"
+ for channel in ("albedo", "roughness", "height", "normal", "ao"):
+ entry = maps.get(channel)
+ if not isinstance(entry, dict) or not has_non_empty(entry.get("url") or entry.get("path")):
+ return False, f"material {material_id!r} referencePbr missing {channel} map path/url"
+ return True, ""
+
+
+def quality_first_material_gaps(spec: dict[str, Any], material: dict[str, Any]) -> list[str]:
+ material_id = str(material.get("id") or "(unnamed)")
+ gaps: list[str] = []
+ targets = spec.get("lookDevTargets")
+ material_targets = targets.get("materialPass", {}) if isinstance(targets, dict) else {}
+ minimum_resolution = material_targets.get("minimumTextureResolution", 1024)
+ if not isinstance(minimum_resolution, int) or isinstance(minimum_resolution, bool):
+ minimum_resolution = 1024
+ extraction_targets = material_targets.get("referencePbrExtraction", {})
+ if not isinstance(extraction_targets, dict):
+ extraction_targets = {}
+ pbr_required = (
+ extraction_targets.get("requiredWhenSourceImagePresent") is True
+ and has_non_empty(spec.get("sourceImage"))
+ )
+ pbr_threshold = extraction_targets.get("targetThreshold", 0.7)
+ if not has_number(pbr_threshold):
+ pbr_threshold = 0.7
+ resolution = material.get("textureResolution")
+ if not isinstance(resolution, int) or isinstance(resolution, bool) or resolution < minimum_resolution:
+ gaps.append(f"material {material_id!r} textureResolution must be >= {minimum_resolution}")
+
+ projection = material.get("textureProjection")
+ if not isinstance(projection, dict) or not has_non_empty(projection.get("mode")):
+ gaps.append(f"material {material_id!r} needs textureProjection.mode and texel-density intent")
+
+ bands = material.get("surfaceFrequencyBands")
+ band_ids = {
+ str(item.get("id")).lower()
+ for item in bands
+ if isinstance(item, dict) and has_non_empty(item.get("id"))
+ } if isinstance(bands, list) else set()
+ missing_bands = {"macro", "meso", "micro"} - band_ids
+ if missing_bands:
+ gaps.append(
+ f"material {material_id!r} missing surface frequency bands: "
+ + ", ".join(sorted(missing_bands))
+ )
+
+ roughness = material.get("roughness")
+ roughness_map = roughness.get("map") if isinstance(roughness, dict) else None
+ if not has_non_empty(roughness_map) or "albedo" in str(roughness_map).lower():
+ gaps.append(f"material {material_id!r} needs an independent roughness map")
+ if not has_non_empty(material.get("normal")) and not has_non_empty(material.get("bump")):
+ gaps.append(f"material {material_id!r} needs an independent height/normal response")
+ if not has_non_empty(material.get("ambientOcclusion")):
+ gaps.append(f"material {material_id!r} needs an independent ambient-occlusion response")
+ if pbr_required:
+ ok, message = reference_pbr_usable(material, float(pbr_threshold))
+ if not ok:
+ gaps.append(message)
+ return gaps
+
+
+def material_pass_gaps(spec: dict[str, Any]) -> list[str]:
+ materials = [item for item in spec.get("materials", []) if isinstance(item, dict)]
+ if not materials:
+ return ["materials array is empty"]
+ if not any(material_has_palette(item) for item in materials):
+ return ["no material has a reference-derived albedo palette or secondary color zones"]
+ gaps: list[str] = []
+ if not any(material_has_response(item) for item in materials):
+ gaps.append("no material defines roughness variation or normal/bump/displacement response")
+ if not any(material_has_locality(item) for item in materials):
+ gaps.append("no material defines local overrides, AO, dirt, wear, stains, moss, chips, or scratches")
+ if quality_first_enabled(spec):
+ for material in materials:
+ if material.get("qualityTier") == "utility":
+ continue
+ gaps.extend(quality_first_material_gaps(spec, material))
+ return gaps
+
+
+def surface_pass_gaps(spec: dict[str, Any]) -> list[str]:
+ components = [item for item in spec.get("componentTree", []) if isinstance(item, dict)]
+ has_surface_detail = any(has_non_empty(item.get("surfaceDetail")) for item in components)
+ if not has_surface_detail:
+ return ["componentTree has no meaningful surfaceDetail for normal/bump/displacement/AO locality"]
+ return []
+
+
+def lighting_pass_gaps(spec: dict[str, Any]) -> list[str]:
+ lighting = spec.get("lightingFromPhoto", [])
+ if not isinstance(lighting, list) or len([item for item in lighting if has_non_empty(item)]) < 3:
+ return ["lightingFromPhoto needs at least three concrete entries for key/fill/rim or environment lighting"]
+ text = " ".join(str(item).lower() for item in lighting)
+ required_groups = {
+ "key light": ("key", "sun", "main light"),
+ "fill light": ("fill", "ambient", "hemisphere"),
+ "rim/environment light": ("rim", "back light", "environment", "hdr", "reflection"),
+ "exposure/tone mapping": ("exposure", "tone", "aces", "filmic"),
+ "contact shadow": ("contact shadow", "ground shadow", "ambient occlusion", "ao"),
+ }
+ gaps = [
+ f"lightingFromPhoto missing {label}"
+ for label, terms in required_groups.items()
+ if not any(term in text for term in terms)
+ ]
+ return gaps
+
+
+def pass_specific_evidence(pass_id: str) -> list[str]:
+ if pass_id in {"structural-pass", "form-refinement"}:
+ return [
+ "attachment contracts for child appendages/connectors",
+ "no floating child roots/joints in the browser screenshot",
+ ]
+ if pass_id == "material-pass":
+ return [
+ "reference-derived albedo palette with dominant, secondary, and accent colors",
+ "independent albedo, roughness, height/normal, and AO maps",
+ "macro, meso, and micro surface-frequency response at 1024px or higher",
+ "local material masks: AO, dirt, wear, stains, moss, chips, scratches, wetness, or equivalent",
+ "neutral, grazing-light close-up, and reference-matched browser screenshots",
+ "AI vision comparison sheet score meeting the visual acceptance threshold",
+ ]
+ if pass_id == "surface-pass":
+ return [
+ "component surfaceDetail for tactile normal/bump/displacement and locality",
+ ]
+ if pass_id == "lighting-pass":
+ return [
+ "lightingFromPhoto with key/fill/rim or environment light",
+ "exposure, tone mapping, background, shadow softness, and contact shadow behavior",
+ ]
+ return []
+
+
+def pass_specific_gaps(spec: dict[str, Any], pass_id: str) -> list[str]:
+ if pass_id in {"structural-pass", "form-refinement"}:
+ return attachment_gaps(spec)
+ if pass_id == "material-pass":
+ return material_pass_gaps(spec)
+ if pass_id == "surface-pass":
+ return surface_pass_gaps(spec)
+ if pass_id == "lighting-pass":
+ return lighting_pass_gaps(spec)
+ return []
+
+
+def sync_pipeline(spec: dict[str, Any]) -> dict[str, Any]:
+ ids = pass_order(spec)
+ completed = completed_passes(spec, ids)
+ current = current_pass(ids, completed)
+ pipeline = spec.setdefault("sculptPipeline", {})
+ if not isinstance(pipeline, dict):
+ pipeline = {}
+ spec["sculptPipeline"] = pipeline
+ pipeline.update(
+ {
+ "passGateMode": "locked-sequential",
+ "passOrder": ids,
+ "currentPass": current,
+ "completedPasses": completed,
+ "lastCompletedPass": completed[-1] if completed else "",
+ "blockedReason": "" if current != "complete" else "all build passes completed",
+ "nextRequiredEvidence": next_required_evidence(spec, current),
+ }
+ )
+ return pipeline
+
+
+def check_pass(spec: dict[str, Any], requested_pass: str) -> tuple[bool, str, dict[str, Any]]:
+ pipeline = sync_pipeline(spec)
+ ids = list(pipeline["passOrder"])
+ if requested_pass not in ids:
+ return False, f"unknown build pass {requested_pass!r}", pipeline
+ current = str(pipeline["currentPass"])
+ completed = list(pipeline.get("completedPasses", []))
+ if requested_pass in completed or current == "complete":
+ gaps = pass_specific_gaps(spec, requested_pass)
+ if gaps:
+ return False, f"pass {requested_pass!r} needs spec refinement: {'; '.join(gaps)}", pipeline
+ return True, f"pass {requested_pass!r} is already completed and can be regenerated", pipeline
+ if requested_pass == current:
+ gaps = pass_specific_gaps(spec, requested_pass)
+ if gaps:
+ return False, f"pass {requested_pass!r} needs spec refinement: {'; '.join(gaps)}", pipeline
+ return True, f"pass {requested_pass!r} is the current unlocked pass", pipeline
+ previous_index = ids.index(requested_pass) - 1
+ previous = ids[previous_index] if previous_index >= 0 else ""
+ return (
+ False,
+ f"pass {requested_pass!r} is locked; complete {previous!r} with reviewHistory.action=continue and screenshot evidence first",
+ pipeline,
+ )
+
+
+def status_payload(spec: dict[str, Any]) -> dict[str, Any]:
+ pipeline = sync_pipeline(spec)
+ return {
+ "targetName": spec.get("targetName"),
+ "passGateMode": pipeline.get("passGateMode"),
+ "currentPass": pipeline.get("currentPass"),
+ "completedPasses": pipeline.get("completedPasses", []),
+ "nextRequiredEvidence": pipeline.get("nextRequiredEvidence", []),
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ status_parser = subparsers.add_parser("status", help="Print current sculpt pipeline state")
+ status_parser.add_argument("spec", type=Path)
+ status_parser.add_argument("--json", action="store_true")
+
+ check_parser = subparsers.add_parser("check", help="Fail unless a build pass is unlocked")
+ check_parser.add_argument("spec", type=Path)
+ check_parser.add_argument("--pass-id", required=True)
+ check_parser.add_argument("--json", action="store_true")
+
+ sync_parser = subparsers.add_parser("sync", help="Refresh sculptPipeline from reviewHistory")
+ sync_parser.add_argument("spec", type=Path)
+ sync_parser.add_argument("--in-place", action="store_true")
+ sync_parser.add_argument("--out", type=Path)
+ sync_parser.add_argument("--json", action="store_true")
+
+ args = parser.parse_args(argv)
+ spec_path = args.spec.expanduser().resolve()
+ spec = load_spec(spec_path)
+
+ if args.command == "status":
+ payload = status_payload(spec)
+ if args.json:
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
+ else:
+ print(f"currentPass: {payload['currentPass']}")
+ print(f"completedPasses: {', '.join(payload['completedPasses']) or '(none)'}")
+ for item in payload["nextRequiredEvidence"]:
+ print(f"required: {item}")
+ return 0
+
+ if args.command == "check":
+ ok, message, pipeline = check_pass(spec, args.pass_id)
+ payload = {"ok": ok, "message": message, "pipeline": pipeline}
+ if args.json:
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
+ else:
+ print("PASS" if ok else "FAIL")
+ print(message)
+ return 0 if ok else 1
+
+ if args.command == "sync":
+ payload = status_payload(spec)
+ output = spec_path if args.in_place else (args.out.expanduser().resolve() if args.out else None)
+ if output:
+ write_spec(output, spec)
+ if args.json:
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
+ else:
+ print(output or json.dumps(spec, indent=2, ensure_ascii=False))
+ return 0
+
+ parser.error("unreachable command")
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/tests/test_pipeline.py b/scripts/tests/test_pipeline.py
new file mode 100644
index 0000000..38d073f
--- /dev/null
+++ b/scripts/tests/test_pipeline.py
@@ -0,0 +1,170 @@
+#!/usr/bin/env python3
+"""End-to-end integration tests for the Three.js Object Sculptor pipeline.
+
+Pure stdlib. Runs each CLI script as a subprocess and asserts the gate behavior
+described in SKILL.md / references. Also generates a tiny real PNG (struct+zlib)
+to exercise the image-consuming scripts without any third-party deps.
+
+Run: python3 scripts/tests/test_pipeline.py (from skill root)
+ or: python3 -m unittest discover -s scripts/tests
+"""
+import json
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+SKILL = Path(__file__).resolve().parents[2]
+SCRIPTS = SKILL / "scripts"
+
+
+def run(script, *args):
+ return subprocess.run(
+ [sys.executable, str(SCRIPTS / script), *map(str, args)],
+ capture_output=True, text=True,
+ )
+
+
+def write_png(path, w=64, h=64):
+ """Write a minimal valid RGB PNG with a simple gradient (no PIL)."""
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0) # filter type 0 per scanline
+ for x in range(w):
+ raw += bytes(((x * 4) % 256, (y * 4) % 256, ((x + y) * 2) % 256))
+
+ def chunk(tag, data):
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ png = (b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
+ + chunk(b"IEND", b""))
+ Path(path).write_bytes(png)
+
+
+class PipelineTest(unittest.TestCase):
+ def setUp(self):
+ self.dir = Path(tempfile.mkdtemp())
+ self.assessment = self.dir / "assessment.json"
+ self.spec = self.dir / "object-sculpt-spec.json"
+ self.ref = self.dir / "ref.png"
+ self.render = self.dir / "render.png"
+ write_png(self.ref)
+ write_png(self.render)
+
+ def test_probe_image(self):
+ r = run("probe_reference_image.py", self.ref)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn("64", r.stdout) # reports dimensions
+
+ def test_assessment_and_spec(self):
+ r = run("new_pre_spec_assessment.py", "Oak", "--complexity", "complex",
+ "--out", self.assessment)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertTrue(self.assessment.exists())
+ self.assertIn("qualityContract", json.loads(self.assessment.read_text()))
+
+ r = run("new_sculpt_spec.py", "Oak", "--assessment", self.assessment,
+ "--out", self.spec)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ spec = json.loads(self.spec.read_text())
+ self.assertEqual(spec["schemaVersion"], "2.0")
+ self.assertEqual(spec["targetName"], "Oak")
+
+ def test_normal_validate_passes_strict_fails_on_shallow(self):
+ run("new_pre_spec_assessment.py", "Oak", "--complexity", "complex",
+ "--out", self.assessment)
+ run("new_sculpt_spec.py", "Oak", "--assessment", self.assessment,
+ "--out", self.spec)
+ # normal validation of a structurally-sound starter succeeds
+ self.assertEqual(run("validate_sculpt_spec.py", self.spec).returncode, 0)
+ # strict quality gate must BLOCK a shallow starter spec
+ strict = run("validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotEqual(strict.returncode, 0)
+ self.assertIn("strict quality failure", strict.stdout + strict.stderr)
+
+ def test_orchestrator_starts_at_blockout(self):
+ run("new_sculpt_spec.py", "Oak", "--out", self.spec)
+ r = run("sculpt_pass_orchestrator.py", "status", self.spec)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn("blockout", r.stdout)
+ # a future pass must be locked
+ locked = run("sculpt_pass_orchestrator.py", "check", self.spec,
+ "--pass-id", "material-pass")
+ self.assertNotEqual(locked.returncode, 0)
+
+ def test_generate_factory_emits_typescript(self):
+ run("new_sculpt_spec.py", "Oak", "--out", self.spec)
+ out = self.dir / "createObjectModel.ts"
+ r = run("generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("import * as THREE from 'three'", ts)
+ self.assertIn("sculptRuntime", ts)
+ # generating a locked future pass must fail
+ locked = run("generate_threejs_factory.py", self.spec, "--out", out,
+ "--pass-id", "lighting-pass")
+ self.assertNotEqual(locked.returncode, 0)
+
+ def test_comparison_sheet_packages_without_scoring(self):
+ cmp = self.dir / "cmp.png"
+ r = run("make_visual_comparison_sheet.py", "--reference", self.ref,
+ "--render", self.render, "--out", cmp, "--json")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertTrue(cmp.exists() and cmp.stat().st_size > 0)
+
+ def test_append_review_gate_and_record(self):
+ run("new_sculpt_spec.py", "Oak", "--out", self.spec)
+ # GATE: continue on a visual pass WITHOUT screenshot evidence must be refused.
+ no_evidence = run("append_sculpt_review.py", self.spec, "--pass-id", "blockout",
+ "--fidelity", "0.8", "--action", "continue",
+ "--summary", "no evidence", "--ai-vision-score", "0.8",
+ "--in-place")
+ self.assertNotEqual(no_evidence.returncode, 0)
+ self.assertIn("render-screenshot", no_evidence.stdout + no_evidence.stderr)
+ # WITH evidence: the review is recorded.
+ cmp = self.dir / "cmp.png"
+ run("make_visual_comparison_sheet.py", "--reference", self.ref,
+ "--render", self.render, "--out", cmp)
+ layers = json.dumps({
+ "silhouetteProportion": 0.82, "componentStructure": 0.78,
+ "formDetail": 0.75, "materialSurface": 0.7, "lightingCamera": 0.8,
+ })
+ # every critical feature target of this pass needs an AI-vision review entry
+ spec = json.loads(self.spec.read_text())
+ targets = spec.get("selfCorrectLoop", {}).get("featureReviewTargets", [])
+ reviews = [
+ {"id": t.get("id"), "score": 0.8, "visible": True, "notes": "acceptable"}
+ for t in targets if t.get("tier") == "critical"
+ ] or [{"id": "overall-silhouette", "score": 0.8, "visible": True, "notes": "ok"}]
+ freviews = self.dir / "features.json"
+ freviews.write_text(json.dumps(reviews))
+ r = run("append_sculpt_review.py", self.spec, "--pass-id", "blockout",
+ "--fidelity", "0.8", "--action", "continue",
+ "--summary", "Blockout silhouette acceptable.",
+ "--render-screenshot", self.render, "--comparison-image", cmp,
+ "--ai-vision-score", "0.8", "--layer-scores-json", layers,
+ "--feature-reviews-json", freviews,
+ "--camera-view", "front", "--in-place")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ spec = json.loads(self.spec.read_text())
+ self.assertTrue(len(spec.get("reviewHistory", [])) >= 1)
+
+ def test_pbr_extraction_runs(self):
+ # low-detail synthetic image: either passes or refuses (non-zero) — both are valid,
+ # but it must not crash and must respect the confidence gate.
+ r = run("extract_reference_pbr.py", self.ref, "--out-dir", self.dir / "pbr",
+ "--material-id", "bark", "--target-threshold", "0.7",
+ "--report", self.dir / "pbr-report.json")
+ self.assertIn(r.returncode, (0, 1), r.stderr)
+ self.assertTrue((self.dir / "pbr-report.json").exists() or r.returncode == 1)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/scripts/validate_sculpt_spec.py b/scripts/validate_sculpt_spec.py
new file mode 100755
index 0000000..13a7aa6
--- /dev/null
+++ b/scripts/validate_sculpt_spec.py
@@ -0,0 +1,1573 @@
+#!/usr/bin/env python3
+"""Validate an ObjectSculptSpec JSON file for procedural Three.js generation."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from visual_feature_gate import feature_gate_failures, feature_review_policy
+
+
+REQUIRED_TOP_LEVEL = {
+ "targetName": str,
+ "suitability": str,
+ "coordinateFrame": dict,
+ "silhouette": dict,
+ "componentTree": list,
+ "materials": list,
+ "proceduralStrategy": list,
+}
+VALID_SUITABILITY = {"pass", "conditional", "reject"}
+VALID_PRIMITIVES = {
+ "box",
+ "sphere",
+ "ellipsoid",
+ "cylinder",
+ "cone",
+ "capsule",
+ "torus",
+ "tube",
+ "lathe",
+ "extrude",
+ "curve-sweep",
+ "plane-card",
+ "instanced-cluster",
+}
+VALID_COMPONENT_LEVELS = {"macro", "meso", "micro"}
+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"}
+VISUAL_PASS_IDS = {
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+}
+VALID_PIPELINE_PASS_IDS = VISUAL_PASS_IDS | {"optimization-pass"}
+ATTACHMENT_ROLES = {
+ "appendage",
+ "branch",
+ "limb",
+ "arm",
+ "leg",
+ "handle",
+ "connector",
+ "tube",
+ "cable",
+ "horn",
+ "wing",
+ "tail",
+ "root",
+ "fork",
+ "rib",
+ "support",
+ "hinge",
+ "socket",
+ "pipe",
+}
+ATTACHMENT_PRIMITIVES = {"cylinder", "cone", "capsule", "tube", "curve-sweep"}
+
+
+def is_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def validate_unit_interval(value: Any, label: str, errors: list[str]) -> None:
+ if not is_number(value) or value < 0 or value > 1:
+ errors.append(f"{label} must be a number from 0 to 1")
+
+
+def load_spec(path: Path) -> dict[str, Any]:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"invalid JSON: {exc}") from exc
+ if not isinstance(payload, dict):
+ raise ValueError("spec must be a JSON object")
+ return payload
+
+
+def as_number_list(value: Any, length: int) -> bool:
+ return (
+ isinstance(value, list)
+ and len(value) == length
+ and all(isinstance(item, (int, float)) for item in value)
+ )
+
+
+def validate_score_block(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ scores = spec.get("scores")
+ if scores is None:
+ warnings.append("missing scores block; image validation evidence will be weaker")
+ return
+ if not isinstance(scores, dict):
+ errors.append("scores must be an object")
+ return
+ for key, value in scores.items():
+ if not isinstance(value, int) or value < 0 or value > 3:
+ errors.append(f"score {key!r} must be an integer from 0 to 3")
+
+
+def validate_nonnegative_int(value: Any, label: str, errors: list[str]) -> None:
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
+ errors.append(f"{label} must be a non-negative integer")
+
+
+def validate_pre_spec_assessment(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ assessment = spec.get("preSpecAssessment")
+ if assessment is None:
+ warnings.append("quality: missing preSpecAssessment; spec may be shallow because complexity was not assessed first")
+ return
+ if not isinstance(assessment, dict):
+ errors.append("preSpecAssessment must be an object")
+ return
+ object_class = assessment.get("objectClass")
+ if not isinstance(object_class, dict):
+ errors.append("preSpecAssessment.objectClass must be an object")
+ else:
+ primary_type = object_class.get("primaryType")
+ if primary_type is not None and not isinstance(primary_type, str):
+ errors.append("preSpecAssessment.objectClass.primaryType must be a string")
+ if primary_type in {None, "", "unassessed"}:
+ warnings.append("quality: preSpecAssessment.objectClass.primaryType is unassessed")
+ for field in ("formLanguage", "structureKind", "motionPotential", "materialFamilies"):
+ validate_string_array(object_class.get(field), f"preSpecAssessment.objectClass.{field}", errors)
+ if isinstance(object_class.get(field), list) and not object_class[field]:
+ warnings.append(f"quality: preSpecAssessment.objectClass.{field} is empty")
+ complexity = assessment.get("complexity")
+ if not isinstance(complexity, dict):
+ errors.append("preSpecAssessment.complexity must be an object")
+ else:
+ tier = complexity.get("tier")
+ if tier not in VALID_COMPLEXITY_TIERS:
+ errors.append(f"preSpecAssessment.complexity.tier must be one of: {', '.join(sorted(VALID_COMPLEXITY_TIERS))}")
+ if tier == "unassessed":
+ warnings.append("quality: preSpecAssessment.complexity.tier is unassessed")
+ scores = complexity.get("scores")
+ if not isinstance(scores, dict):
+ errors.append("preSpecAssessment.complexity.scores must be an object")
+ else:
+ for key, value in scores.items():
+ if not isinstance(value, int) or value < 0 or value > 3:
+ errors.append(f"preSpecAssessment.complexity.scores.{key} must be an integer from 0 to 3")
+ estimated = complexity.get("estimatedCounts")
+ if not isinstance(estimated, dict):
+ errors.append("preSpecAssessment.complexity.estimatedCounts must be an object")
+ else:
+ for field in ("macroComponents", "mesoComponents", "microFeatureGroups", "materialLayers", "repetitionSystems"):
+ if field in estimated:
+ validate_nonnegative_int(estimated[field], f"preSpecAssessment.complexity.estimatedCounts.{field}", errors)
+ validate_string_array(complexity.get("reasoning"), "preSpecAssessment.complexity.reasoning", errors)
+ decision = assessment.get("specDepthDecision")
+ if not isinstance(decision, dict):
+ errors.append("preSpecAssessment.specDepthDecision must be an object")
+ else:
+ required_depth = decision.get("requiredDepth")
+ if required_depth not in VALID_COMPLEXITY_TIERS:
+ errors.append("preSpecAssessment.specDepthDecision.requiredDepth must be a valid complexity tier")
+ if required_depth == "unassessed":
+ warnings.append("quality: preSpecAssessment.specDepthDecision.requiredDepth is unassessed")
+ validate_string_array(decision.get("minimumComponentLevels"), "preSpecAssessment.specDepthDecision.minimumComponentLevels", errors)
+ for field in (
+ "needsRepetitionSystems",
+ "needsMaterialLocalOverrides",
+ "needsMultipleReviewViews",
+ "needsActionReadyHierarchy",
+ ):
+ if field in decision and not isinstance(decision[field], bool):
+ errors.append(f"preSpecAssessment.specDepthDecision.{field} must be boolean")
+ unknowns = assessment.get("unknownsToResolveBeforeImplementation")
+ validate_string_array(unknowns, "preSpecAssessment.unknownsToResolveBeforeImplementation", errors)
+ if isinstance(unknowns, list) and unknowns:
+ warnings.append("quality: preSpecAssessment has unresolved unknowns before implementation")
+
+
+def validate_terminology_profile(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ profile = spec.get("terminologyProfile")
+ if profile is None:
+ warnings.append("missing terminologyProfile; descriptions may drift into vague non-3D language")
+ return
+ if not isinstance(profile, dict):
+ errors.append("terminologyProfile must be an object")
+ return
+ for field in TERMINOLOGY_LIST_FIELDS:
+ value = profile.get(field)
+ if value is None:
+ warnings.append(f"terminologyProfile.{field} is missing")
+ continue
+ if not isinstance(value, list) or not all(isinstance(item, str) and item.strip() for item in value):
+ errors.append(f"terminologyProfile.{field} must be an array of non-empty strings")
+ rule = profile.get("descriptionRule")
+ if rule is not None and not isinstance(rule, str):
+ errors.append("terminologyProfile.descriptionRule must be a string")
+
+
+def validate_evidence(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> set[str]:
+ refs: set[str] = set()
+ evidence = spec.get("viewEvidence", [])
+ if evidence is None:
+ return refs
+ if not isinstance(evidence, list):
+ errors.append("viewEvidence must be an array when present")
+ return refs
+ for index, item in enumerate(evidence):
+ if not isinstance(item, dict):
+ errors.append(f"viewEvidence[{index}] must be an object")
+ continue
+ evidence_id = item.get("id")
+ if not isinstance(evidence_id, str) or not evidence_id.strip():
+ errors.append(f"viewEvidence[{index}].id is required")
+ continue
+ if evidence_id in refs:
+ errors.append(f"duplicate viewEvidence id {evidence_id!r}")
+ refs.add(evidence_id)
+ confidence = item.get("confidence")
+ if confidence is not None:
+ validate_unit_interval(confidence, f"viewEvidence {evidence_id!r} confidence", errors)
+ region = item.get("imageRegion")
+ if region is not None:
+ if not isinstance(region, dict):
+ errors.append(f"viewEvidence {evidence_id!r} imageRegion must be an object")
+ else:
+ for key in ("x", "y", "width", "height"):
+ if key in region and not is_number(region[key]):
+ errors.append(f"viewEvidence {evidence_id!r} imageRegion.{key} must be numeric")
+ if not refs:
+ warnings.append("missing viewEvidence; local visual claims cannot be traced back to image regions")
+ return refs
+
+
+def validate_material_scalar_or_layer(value: Any, label: str, errors: list[str]) -> None:
+ if value is None:
+ return
+ if is_number(value):
+ return
+ if not isinstance(value, dict):
+ errors.append(f"{label} must be a number or object")
+ return
+ base = value.get("base")
+ if base is not None and not is_number(base):
+ errors.append(f"{label}.base must be numeric")
+ variation = value.get("variation")
+ if variation is not None and not is_number(variation):
+ errors.append(f"{label}.variation must be numeric")
+
+
+def validate_reference_pbr_map(value: Any, label: str, errors: list[str]) -> None:
+ if not isinstance(value, dict):
+ errors.append(f"{label} must be an object")
+ return
+ has_locator = False
+ for field in ("path", "url"):
+ item = value.get(field)
+ if item is not None:
+ if not isinstance(item, str) or not item.strip():
+ errors.append(f"{label}.{field} must be a non-empty string when present")
+ else:
+ has_locator = True
+ if not has_locator:
+ errors.append(f"{label} needs a path or url")
+ channel = value.get("channel")
+ if channel is not None and not isinstance(channel, str):
+ errors.append(f"{label}.channel must be a string")
+
+
+def validate_reference_pbr(material_id: str, value: Any, errors: list[str], warnings: list[str]) -> None:
+ if value is None:
+ return
+ if not isinstance(value, dict):
+ errors.append(f"material {material_id!r} referencePbr must be an object")
+ return
+ for field in ("version", "sourceImage", "extractor", "method", "verdict", "hardLimit"):
+ item = value.get(field)
+ if item is not None and not isinstance(item, str):
+ errors.append(f"material {material_id!r} referencePbr.{field} must be a string")
+ usable = value.get("usable")
+ if usable is not None and not isinstance(usable, bool):
+ errors.append(f"material {material_id!r} referencePbr.usable must be boolean")
+ for field in ("confidence", "estimatedFidelity", "targetThreshold"):
+ item = value.get(field)
+ if item is not None:
+ validate_unit_interval(item, f"material {material_id!r} referencePbr.{field}", errors)
+ maps = value.get("maps")
+ if maps is None:
+ warnings.append(f"quality: material {material_id!r} referencePbr is missing maps")
+ return
+ if not isinstance(maps, dict):
+ errors.append(f"material {material_id!r} referencePbr.maps must be an object")
+ return
+ required = ("albedo", "roughness", "height", "normal", "ao")
+ for channel in required:
+ if channel not in maps:
+ warnings.append(f"quality: material {material_id!r} referencePbr.maps missing {channel}")
+ else:
+ validate_reference_pbr_map(maps[channel], f"material {material_id!r} referencePbr.maps.{channel}", errors)
+
+
+def validate_materials(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> set[str]:
+ material_ids: set[str] = set()
+ for index, material in enumerate(spec.get("materials", [])):
+ if not isinstance(material, dict):
+ errors.append(f"materials[{index}] must be an object")
+ continue
+ material_id = material.get("id")
+ if not isinstance(material_id, str) or not material_id.strip():
+ errors.append(f"materials[{index}].id is required")
+ continue
+ if material_id in material_ids:
+ errors.append(f"duplicate material id {material_id!r}")
+ material_ids.add(material_id)
+ 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")
+ for field in ("shaderModel", "type"):
+ value = material.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"material {material_id!r} {field} must be a string")
+ for field in ("albedo", "ambientOcclusion"):
+ value = material.get(field)
+ if value is not None and not isinstance(value, dict):
+ errors.append(f"material {material_id!r} {field} must be an object")
+ validate_material_scalar_or_layer(material.get("roughness"), f"material {material_id!r} roughness", errors)
+ validate_material_scalar_or_layer(material.get("metalness"), f"material {material_id!r} metalness", errors)
+ for field in ("normal", "bump", "displacement", "wear", "dirt"):
+ value = material.get(field)
+ if value is not None and not isinstance(value, dict):
+ errors.append(f"material {material_id!r} {field} must be an object")
+ texture_resolution = material.get("textureResolution")
+ if texture_resolution is not None and (
+ not isinstance(texture_resolution, int)
+ or isinstance(texture_resolution, bool)
+ or texture_resolution < 64
+ or texture_resolution > 4096
+ ):
+ errors.append(f"material {material_id!r} textureResolution must be an integer from 64 to 4096")
+ projection = material.get("textureProjection")
+ if projection is not None:
+ if not isinstance(projection, dict):
+ errors.append(f"material {material_id!r} textureProjection must be an object")
+ else:
+ mode = projection.get("mode")
+ if mode is not None and not isinstance(mode, str):
+ errors.append(f"material {material_id!r} textureProjection.mode must be a string")
+ repeat = projection.get("repeat")
+ if repeat is not None and not (
+ isinstance(repeat, list)
+ and len(repeat) == 2
+ and all(is_number(item) and item > 0 for item in repeat)
+ ):
+ errors.append(f"material {material_id!r} textureProjection.repeat must contain two positive numbers")
+ anisotropy = projection.get("anisotropy")
+ if anisotropy is not None and (not is_number(anisotropy) or anisotropy < 1):
+ errors.append(f"material {material_id!r} textureProjection.anisotropy must be >= 1")
+ frequency_bands = material.get("surfaceFrequencyBands")
+ if frequency_bands is not None:
+ if not isinstance(frequency_bands, list):
+ errors.append(f"material {material_id!r} surfaceFrequencyBands must be an array")
+ else:
+ seen_band_ids: set[str] = set()
+ for band_index, band in enumerate(frequency_bands):
+ if not isinstance(band, dict):
+ errors.append(
+ f"material {material_id!r} surfaceFrequencyBands[{band_index}] must be an object"
+ )
+ continue
+ band_id = band.get("id")
+ if not isinstance(band_id, str) or not band_id.strip():
+ errors.append(
+ f"material {material_id!r} surfaceFrequencyBands[{band_index}].id is required"
+ )
+ elif band_id in seen_band_ids:
+ errors.append(f"material {material_id!r} has duplicate surface band {band_id!r}")
+ else:
+ seen_band_ids.add(band_id)
+ for field in ("frequency", "amplitude"):
+ value = band.get(field)
+ if not is_number(value) or value <= 0:
+ errors.append(
+ f"material {material_id!r} surfaceFrequencyBands[{band_index}].{field} "
+ "must be a positive number"
+ )
+ local_overrides = material.get("localOverrides", [])
+ if local_overrides is not None and not isinstance(local_overrides, list):
+ errors.append(f"material {material_id!r} localOverrides must be an array")
+ shader_notes = material.get("shaderNotes")
+ if shader_notes is not None:
+ validate_string_array(shader_notes, f"material {material_id!r} shaderNotes", errors)
+ validate_reference_pbr(material_id, material.get("referencePbr"), errors, warnings)
+ if not material_ids:
+ errors.append("at least one material is required")
+ return material_ids
+
+
+def validate_dimensions(component_id: str, dimensions: Any, errors: list[str]) -> None:
+ if dimensions is None:
+ return
+ if not isinstance(dimensions, dict):
+ errors.append(f"component {component_id!r} dimensions must be an object")
+ return
+ for field in ("width", "height", "depth", "radius", "length"):
+ if field in dimensions and not is_number(dimensions[field]):
+ errors.append(f"component {component_id!r} dimensions.{field} must be numeric")
+ confidence = dimensions.get("confidence")
+ if confidence is not None:
+ validate_unit_interval(confidence, f"component {component_id!r} dimensions.confidence", errors)
+
+
+def validate_geometry_descriptor(component_id: str, descriptor: Any, errors: list[str]) -> None:
+ if descriptor is None:
+ return
+ if not isinstance(descriptor, dict):
+ errors.append(f"component {component_id!r} geometryDescriptor must be an object")
+ return
+ for field in ("topologyIntent", "uvStrategy", "normalStrategy"):
+ value = descriptor.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"component {component_id!r} geometryDescriptor.{field} must be a string")
+ edge = descriptor.get("edgeTreatment")
+ if edge is not None:
+ if not isinstance(edge, dict):
+ errors.append(f"component {component_id!r} geometryDescriptor.edgeTreatment must be an object")
+ else:
+ if "bevelRadius" in edge and not is_number(edge["bevelRadius"]):
+ errors.append(f"component {component_id!r} edgeTreatment.bevelRadius must be numeric")
+ if "segments" in edge and not isinstance(edge["segments"], int):
+ errors.append(f"component {component_id!r} edgeTreatment.segments must be an integer")
+ stack = descriptor.get("deformationStack")
+ if stack is not None and not isinstance(stack, list):
+ errors.append(f"component {component_id!r} geometryDescriptor.deformationStack must be an array")
+
+
+def validate_bool_object(value: Any, label: str, errors: list[str]) -> None:
+ if value is None:
+ return
+ if not isinstance(value, dict):
+ errors.append(f"{label} must be an object")
+ return
+ for key, item in value.items():
+ if not isinstance(key, str):
+ errors.append(f"{label} keys must be strings")
+ if not isinstance(item, bool):
+ errors.append(f"{label}.{key} must be boolean")
+
+
+def validate_action_profile(component_id: str, profile: Any, errors: list[str], warnings: list[str]) -> None:
+ if profile is None:
+ warnings.append(f"component {component_id!r} is missing actionProfile; future animation/destruction may require refactor")
+ return
+ if not isinstance(profile, dict):
+ errors.append(f"component {component_id!r} actionProfile must be an object")
+ return
+ role = profile.get("animationRole")
+ if role is not None and not isinstance(role, str):
+ errors.append(f"component {component_id!r} actionProfile.animationRole must be a string")
+ pivot = profile.get("pivot")
+ if pivot is not None:
+ if not isinstance(pivot, dict):
+ errors.append(f"component {component_id!r} actionProfile.pivot must be an object")
+ else:
+ mode = pivot.get("mode")
+ if mode is not None and not isinstance(mode, str):
+ errors.append(f"component {component_id!r} actionProfile.pivot.mode must be a string")
+ for field in ("localPosition", "axis"):
+ if field in pivot and not as_number_list(pivot[field], 3):
+ errors.append(f"component {component_id!r} actionProfile.pivot.{field} must be [number, number, number]")
+ confidence = pivot.get("confidence")
+ if confidence is not None:
+ validate_unit_interval(confidence, f"component {component_id!r} actionProfile.pivot.confidence", errors)
+ validate_bool_object(profile.get("transformChannels"), f"component {component_id!r} actionProfile.transformChannels", errors)
+ sockets = profile.get("sockets")
+ if sockets is not None:
+ if not isinstance(sockets, list):
+ errors.append(f"component {component_id!r} actionProfile.sockets must be an array")
+ else:
+ for socket_index, socket in enumerate(sockets):
+ if not isinstance(socket, dict):
+ errors.append(f"component {component_id!r} actionProfile.sockets[{socket_index}] must be an object")
+ continue
+ socket_id = socket.get("id")
+ if socket_id is not None and not isinstance(socket_id, str):
+ errors.append(f"component {component_id!r} actionProfile.sockets[{socket_index}].id must be a string")
+ for field in ("localPosition", "position", "localRotation", "rotation"):
+ if field in socket and not as_number_list(socket[field], 3):
+ errors.append(
+ f"component {component_id!r} actionProfile.sockets[{socket_index}].{field} must be [number, number, number]"
+ )
+ collider = profile.get("collider")
+ if collider is not None:
+ if not isinstance(collider, dict):
+ errors.append(f"component {component_id!r} actionProfile.collider must be an object")
+ else:
+ collider_type = collider.get("type")
+ if collider_type is not None and not isinstance(collider_type, str):
+ errors.append(f"component {component_id!r} actionProfile.collider.type must be a string")
+ for field in ("offset", "scale"):
+ if field in collider and not as_number_list(collider[field], 3):
+ errors.append(f"component {component_id!r} actionProfile.collider.{field} must be [number, number, number]")
+ if "isTrigger" in collider and not isinstance(collider["isTrigger"], bool):
+ errors.append(f"component {component_id!r} actionProfile.collider.isTrigger must be boolean")
+ constraints = profile.get("constraints")
+ if constraints is not None and not isinstance(constraints, list):
+ errors.append(f"component {component_id!r} actionProfile.constraints must be an array")
+ destruction = profile.get("destruction")
+ if destruction is not None:
+ if not isinstance(destruction, dict):
+ errors.append(f"component {component_id!r} actionProfile.destruction must be an object")
+ else:
+ if "breakable" in destruction and not isinstance(destruction["breakable"], bool):
+ errors.append(f"component {component_id!r} actionProfile.destruction.breakable must be boolean")
+ if "breakImpulse" in destruction and not is_number(destruction["breakImpulse"]):
+ errors.append(f"component {component_id!r} actionProfile.destruction.breakImpulse must be numeric")
+ for field in ("fractureGroup", "debrisMaterial"):
+ value = destruction.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"component {component_id!r} actionProfile.destruction.{field} must be a string")
+ for field in ("seamRefs", "detachableFragments"):
+ validate_string_array(destruction.get(field), f"component {component_id!r} actionProfile.destruction.{field}", errors)
+
+
+def component_requires_attachment(component: dict[str, Any]) -> bool:
+ if not component.get("parent"):
+ return False
+ role = str(component.get("role") or "").lower()
+ name = str(component.get("name") or component.get("id") or "").lower()
+ primitive = str(component.get("primitive") or "").lower()
+ profile = component.get("actionProfile") if isinstance(component.get("actionProfile"), dict) else {}
+ animation_role = str(profile.get("animationRole") or "").lower()
+ tokens = {role, animation_role} | set(re.findall(r"[a-z0-9]+", name))
+ return bool(tokens & ATTACHMENT_ROLES) or primitive in ATTACHMENT_PRIMITIVES
+
+
+def has_attachment_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def attachment_is_complete(attachment: dict[str, Any]) -> bool:
+ has_endpoint = as_number_list(attachment.get("localStart"), 3) and as_number_list(attachment.get("localEnd"), 3)
+ has_socket = isinstance(attachment.get("parentSocket"), str) and bool(attachment["parentSocket"].strip())
+ has_parent_id = isinstance(attachment.get("parentId"), str) and bool(attachment["parentId"].strip())
+ has_contact = isinstance(attachment.get("contactType"), str) and bool(attachment["contactType"].strip())
+ has_overlap = (
+ has_attachment_number(attachment.get("embedDepth"))
+ and float(attachment["embedDepth"]) > 0
+ ) or (
+ has_attachment_number(attachment.get("overlap"))
+ and float(attachment["overlap"]) > 0
+ )
+ has_tolerance = has_attachment_number(attachment.get("gapTolerance"))
+ return has_endpoint and (has_socket or has_parent_id) and has_contact and has_overlap and has_tolerance
+
+
+def validate_attachment(
+ component_id: str,
+ parent: str | None,
+ attachment: Any,
+ required: bool,
+ errors: list[str],
+ warnings: list[str],
+) -> None:
+ if attachment is None:
+ if required:
+ warnings.append(
+ f"quality: component {component_id!r} requires attachment.parentSocket, localStart/localEnd, "
+ "contactType, embedDepth or overlap, and gapTolerance"
+ )
+ return
+ if not isinstance(attachment, dict):
+ errors.append(f"component {component_id!r} attachment must be an object")
+ return
+ for field in ("parentId", "parentSocket", "contactType"):
+ value = attachment.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"component {component_id!r} attachment.{field} must be a string")
+ if parent and isinstance(attachment.get("parentId"), str) and attachment["parentId"] != parent:
+ warnings.append(
+ f"quality: component {component_id!r} attachment.parentId {attachment['parentId']!r} "
+ f"does not match parent {parent!r}"
+ )
+ for field in ("localStart", "localEnd", "contactNormal"):
+ value = attachment.get(field)
+ if value is not None and not as_number_list(value, 3):
+ errors.append(f"component {component_id!r} attachment.{field} must be [number, number, number]")
+ for field in ("embedDepth", "overlap", "gapTolerance", "baseRadius", "endRadius"):
+ value = attachment.get(field)
+ if value is not None and (not has_attachment_number(value) or float(value) < 0):
+ errors.append(f"component {component_id!r} attachment.{field} must be a non-negative number")
+ validate_string_array(attachment.get("evidenceRefs"), f"component {component_id!r} attachment.evidenceRefs", errors)
+ if required and not attachment_is_complete(attachment):
+ warnings.append(
+ f"quality: component {component_id!r} requires attachment.parentSocket, localStart/localEnd, "
+ "contactType, embedDepth or overlap, and gapTolerance"
+ )
+
+
+def validate_string_array(value: Any, label: str, errors: list[str]) -> None:
+ if value is None:
+ return
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
+ errors.append(f"{label} must be an array of strings")
+
+
+def validate_components(
+ spec: dict[str, Any],
+ material_ids: set[str],
+ evidence_ids: set[str],
+ errors: list[str],
+ warnings: list[str],
+) -> None:
+ components = spec.get("componentTree", [])
+ ids: set[str] = set()
+ parent_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")
+ continue
+ component_id = component.get("id")
+ if not isinstance(component_id, str) or not component_id.strip():
+ errors.append(f"componentTree[{index}].id is required")
+ continue
+ if component_id in ids:
+ errors.append(f"duplicate component id {component_id!r}")
+ ids.add(component_id)
+ primitive = component.get("primitive")
+ if primitive not in VALID_PRIMITIVES:
+ errors.append(
+ f"component {component_id!r} primitive must be one of: {', '.join(sorted(VALID_PRIMITIVES))}"
+ )
+ level = component.get("level")
+ if level is not None and level not in VALID_COMPONENT_LEVELS:
+ errors.append(f"component {component_id!r} level must be macro, meso, or micro")
+ for field in ("importance", "confidence"):
+ value = component.get(field)
+ if value is not None:
+ validate_unit_interval(value, f"component {component_id!r} {field}", errors)
+ parent = component.get("parent")
+ if parent:
+ if not isinstance(parent, str):
+ errors.append(f"component {component_id!r} parent must be a string or null")
+ else:
+ parent_refs.append((component_id, parent))
+ material = component.get("material")
+ 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)
+ material_layers = component.get("materialLayers")
+ if material_layers is not None:
+ validate_string_array(material_layers, f"component {component_id!r} materialLayers", errors)
+ if isinstance(material_layers, list):
+ for material_layer in material_layers:
+ if material_layer not in material_ids:
+ errors.append(
+ f"component {component_id!r} materialLayers references unknown material {material_layer!r}"
+ )
+ validate_dimensions(component_id, component.get("dimensions"), errors)
+ transform = component.get("transform", {})
+ if transform is not None and not isinstance(transform, dict):
+ errors.append(f"component {component_id!r} transform must be an object")
+ elif isinstance(transform, dict):
+ for field in ("position", "rotation", "scale"):
+ if field in transform and not as_number_list(transform[field], 3):
+ errors.append(f"component {component_id!r} transform.{field} must be [number, number, number]")
+ validate_action_profile(component_id, component.get("actionProfile"), errors, warnings)
+ validate_attachment(
+ component_id,
+ parent if isinstance(parent, str) else None,
+ component.get("attachment"),
+ component_requires_attachment(component),
+ errors,
+ warnings,
+ )
+ for field in ("deformations", "joints", "seams", "localFeatures"):
+ 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")
+ surface = component.get("surfaceDetail")
+ if surface is not None:
+ if not isinstance(surface, dict):
+ errors.append(f"component {component_id!r} surfaceDetail must be an object")
+ else:
+ for field in ("macroRoughness", "microRoughness", "bumpAmplitude"):
+ if field in surface and not is_number(surface[field]):
+ errors.append(f"component {component_id!r} surfaceDetail.{field} must be numeric")
+ evidence_refs = component.get("evidenceRefs")
+ if evidence_refs is not None:
+ validate_string_array(evidence_refs, f"component {component_id!r} evidenceRefs", errors)
+ if isinstance(evidence_refs, list):
+ for evidence_ref in evidence_refs:
+ if evidence_ids and evidence_ref not in evidence_ids:
+ errors.append(f"component {component_id!r} references missing evidence {evidence_ref!r}")
+ for component_id, parent in parent_refs:
+ if parent not in ids:
+ errors.append(f"component {component_id!r} references missing parent {parent!r}")
+ if not ids:
+ errors.append("at least one component is required")
+ if len(ids) == 1:
+ warnings.append("only one component found; this is likely still blockout quality")
+
+
+def validate_quality_targets(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ targets = spec.get("qualityTargets")
+ if targets is None:
+ warnings.append("missing qualityTargets; self-correction loop has no explicit fidelity bar")
+ return
+ if not isinstance(targets, dict):
+ errors.append("qualityTargets must be an object")
+ return
+ target_fidelity = targets.get("targetFidelity")
+ if target_fidelity is not None:
+ validate_unit_interval(target_fidelity, "qualityTargets.targetFidelity", errors)
+ for field in ("mustMatch", "niceToHave", "reviewViewpoints"):
+ validate_string_array(targets.get(field), f"qualityTargets.{field}", errors)
+
+
+def validate_quality_contract(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ contract = spec.get("qualityContract")
+ if contract is None:
+ warnings.append("quality: missing qualityContract; no explicit definition of done prevents shallow specs")
+ return
+ if not isinstance(contract, dict):
+ errors.append("qualityContract must be an object")
+ return
+ quality_bar = contract.get("qualityBar")
+ if quality_bar is not None and not isinstance(quality_bar, str):
+ errors.append("qualityContract.qualityBar must be a string")
+ if quality_bar in {None, "", "unassessed"}:
+ warnings.append("quality: qualityContract.qualityBar is unassessed")
+ validate_string_array(contract.get("definitionOfDone"), "qualityContract.definitionOfDone", errors)
+ if isinstance(contract.get("definitionOfDone"), list) and not contract["definitionOfDone"]:
+ warnings.append("quality: qualityContract.definitionOfDone is empty")
+ minimums = contract.get("minimumSpecDepth")
+ if not isinstance(minimums, dict):
+ errors.append("qualityContract.minimumSpecDepth must be an object")
+ else:
+ for field in (
+ "macroComponents",
+ "mesoComponents",
+ "microFeatureGroups",
+ "materialLayers",
+ "repetitionSystems",
+ "reviewViewpoints",
+ ):
+ if field in minimums:
+ validate_nonnegative_int(minimums[field], f"qualityContract.minimumSpecDepth.{field}", errors)
+ feature_groups = contract.get("featureGroups")
+ if not isinstance(feature_groups, list):
+ errors.append("qualityContract.featureGroups must be an array")
+ else:
+ if len(feature_groups) < 3:
+ warnings.append("quality: qualityContract.featureGroups has fewer than 3 groups; spec may miss important visual layers")
+ for index, group in enumerate(feature_groups):
+ if not isinstance(group, dict):
+ errors.append(f"qualityContract.featureGroups[{index}] must be an object")
+ continue
+ for field in ("id", "name"):
+ value = group.get(field)
+ if not isinstance(value, str) or not value.strip():
+ errors.append(f"qualityContract.featureGroups[{index}].{field} is required")
+ if "required" in group and not isinstance(group["required"], bool):
+ errors.append(f"qualityContract.featureGroups[{index}].required must be boolean")
+ validate_string_array(group.get("qualityCriteria"), f"qualityContract.featureGroups[{index}].qualityCriteria", errors)
+ validate_string_array(group.get("evidenceRefs"), f"qualityContract.featureGroups[{index}].evidenceRefs", errors)
+ validate_string_array(group.get("failureModes"), f"qualityContract.featureGroups[{index}].failureModes", errors)
+ if group.get("required") is True and not group.get("qualityCriteria"):
+ warnings.append(f"quality: required feature group {group.get('id', index)!r} has no qualityCriteria")
+ for field in ("visualDeltaChecks", "antiShallowSpecRules"):
+ validate_string_array(contract.get(field), f"qualityContract.{field}", errors)
+ if isinstance(contract.get(field), list) and not contract[field]:
+ warnings.append(f"quality: qualityContract.{field} is empty")
+
+
+def validate_quality_depth(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ contract = spec.get("qualityContract")
+ if not isinstance(contract, dict) or not isinstance(contract.get("minimumSpecDepth"), dict):
+ return
+ minimums = contract["minimumSpecDepth"]
+ components = [item for item in spec.get("componentTree", []) if isinstance(item, dict)]
+ level_counts = {
+ "macroComponents": sum(1 for item in components if item.get("level") == "macro"),
+ "mesoComponents": sum(1 for item in components if item.get("level") == "meso"),
+ "microFeatureGroups": sum(
+ len(item.get("localFeatures", []))
+ for item in components
+ if isinstance(item.get("localFeatures", []), list)
+ ),
+ "materialLayers": len([item for item in spec.get("materials", []) if isinstance(item, dict)]),
+ "repetitionSystems": len([item for item in spec.get("repetitionSystems", []) if isinstance(item, dict)]),
+ "reviewViewpoints": len(spec.get("qualityTargets", {}).get("reviewViewpoints", []))
+ if isinstance(spec.get("qualityTargets"), dict)
+ and isinstance(spec.get("qualityTargets", {}).get("reviewViewpoints"), list)
+ else 0,
+ }
+ for field, actual in level_counts.items():
+ required = minimums.get(field)
+ if isinstance(required, int) and actual < required:
+ warnings.append(f"quality: {field} below qualityContract minimum ({actual} < {required})")
+
+
+def validate_action_readiness(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ readiness = spec.get("actionReadiness")
+ if readiness is None:
+ warnings.append("missing actionReadiness; generated model may not be ready for animation/transformation/destruction")
+ return
+ if not isinstance(readiness, dict):
+ errors.append("actionReadiness must be an object")
+ return
+ for field in ("contract", "defaultRigType", "rootMotionNode"):
+ value = readiness.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"actionReadiness.{field} must be a string")
+ for field in ("requiredComponentFields", "transformChannels", "authoringRules"):
+ validate_string_array(readiness.get(field), f"actionReadiness.{field}", errors)
+ policy = readiness.get("destructionPolicy")
+ if policy is not None and not isinstance(policy, dict):
+ errors.append("actionReadiness.destructionPolicy must be an object")
+
+
+def validate_self_correct_loop(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ loop = spec.get("selfCorrectLoop")
+ if loop is None:
+ warnings.append("missing selfCorrectLoop; construction may not review/refine after each pass")
+ return
+ if not isinstance(loop, dict):
+ errors.append("selfCorrectLoop must be an object")
+ return
+ enabled = loop.get("enabled")
+ if enabled is not None and not isinstance(enabled, bool):
+ errors.append("selfCorrectLoop.enabled must be boolean")
+ for field in ("reviewAfterPasses", "allowedActions", "specRefineTriggers", "codeRefineTriggers", "stopCriteria"):
+ validate_string_array(loop.get(field), f"selfCorrectLoop.{field}", errors)
+ actions = loop.get("allowedActions", [])
+ if isinstance(actions, list):
+ for action in actions:
+ if action not in VALID_REVIEW_ACTIONS:
+ errors.append(f"selfCorrectLoop.allowedActions contains invalid action {action!r}")
+ visual_acceptance = loop.get("visualAcceptance")
+ if visual_acceptance is None:
+ warnings.append("quality: selfCorrectLoop.visualAcceptance is missing; AI vision cannot enforce visual fidelity")
+ elif not isinstance(visual_acceptance, dict):
+ errors.append("selfCorrectLoop.visualAcceptance must be an object")
+ else:
+ reviewer = visual_acceptance.get("reviewer")
+ if reviewer is not None and not isinstance(reviewer, str):
+ errors.append("selfCorrectLoop.visualAcceptance.reviewer must be a string")
+ threshold = visual_acceptance.get("threshold")
+ if threshold is None:
+ warnings.append("quality: selfCorrectLoop.visualAcceptance.threshold is missing")
+ else:
+ validate_unit_interval(threshold, "selfCorrectLoop.visualAcceptance.threshold", errors)
+ for field in (
+ "comparisonArtifactRequired",
+ "layerScoresRequired",
+ "codePixelDiffIsAcceptanceAuthority",
+ ):
+ value = visual_acceptance.get(field)
+ if value is not None and not isinstance(value, bool):
+ errors.append(f"selfCorrectLoop.visualAcceptance.{field} must be boolean")
+ scoring_rule = visual_acceptance.get("scoringRule")
+ if scoring_rule is not None and not isinstance(scoring_rule, str):
+ errors.append("selfCorrectLoop.visualAcceptance.scoringRule must be a string")
+ validate_string_array(
+ visual_acceptance.get("requiredLayerScores"),
+ "selfCorrectLoop.visualAcceptance.requiredLayerScores",
+ errors,
+ )
+ feature_policy = visual_acceptance.get("featureReviewPolicy")
+ if feature_policy is None:
+ warnings.append("quality: visualAcceptance.featureReviewPolicy is missing")
+ elif not isinstance(feature_policy, dict):
+ errors.append("selfCorrectLoop.visualAcceptance.featureReviewPolicy must be an object")
+ else:
+ for field in (
+ "enabled",
+ "adaptiveEscalation",
+ "singleImagePairOnly",
+ ):
+ value = feature_policy.get(field)
+ if value is not None and not isinstance(value, bool):
+ errors.append(
+ f"selfCorrectLoop.visualAcceptance.featureReviewPolicy.{field} must be boolean"
+ )
+ for field in ("maxCriticalFeaturesPerPass", "maxImportantFeaturesPerPass"):
+ value = feature_policy.get(field)
+ if value is not None:
+ validate_nonnegative_int(
+ value,
+ f"selfCorrectLoop.visualAcceptance.featureReviewPolicy.{field}",
+ errors,
+ )
+ for field in ("criticalDefaultThreshold", "importantAverageThreshold"):
+ value = feature_policy.get(field)
+ if value is not None:
+ validate_unit_interval(
+ value,
+ f"selfCorrectLoop.visualAcceptance.featureReviewPolicy.{field}",
+ errors,
+ )
+ for field in ("reviewUnit", "selectionRule"):
+ value = feature_policy.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(
+ f"selfCorrectLoop.visualAcceptance.featureReviewPolicy.{field} must be a string"
+ )
+ policy = loop.get("screenshotPolicy")
+ if policy is None:
+ warnings.append("selfCorrectLoop.screenshotPolicy is missing; visual review may drift without screenshots")
+ elif not isinstance(policy, dict):
+ errors.append("selfCorrectLoop.screenshotPolicy must be an object")
+ else:
+ validate_string_array(policy.get("requiredForPasses"), "selfCorrectLoop.screenshotPolicy.requiredForPasses", errors)
+ for field in (
+ "preferredCapture",
+ "fallbackCapture",
+ "minimumEvidence",
+ "reviewPairRule",
+ "acceptanceAuthority",
+ ):
+ value = policy.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"selfCorrectLoop.screenshotPolicy.{field} must be a string")
+
+
+def validate_visual_evidence_item(item: Any, label: str, errors: list[str]) -> None:
+ if not isinstance(item, dict):
+ errors.append(f"{label} must be an object")
+ return
+ for field in (
+ "passId",
+ "referenceScreenshot",
+ "renderScreenshot",
+ "comparisonImage",
+ "cameraView",
+ "notes",
+ "aiVisionNotes",
+ ):
+ value = item.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"{label}.{field} must be a string")
+ fidelity = item.get("estimatedFidelity")
+ if fidelity is not None:
+ validate_unit_interval(fidelity, f"{label}.estimatedFidelity", errors)
+ score = item.get("aiVisionScore")
+ if score is not None:
+ validate_unit_interval(score, f"{label}.aiVisionScore", errors)
+ threshold = item.get("visualAcceptanceThreshold")
+ if threshold is not None:
+ validate_unit_interval(threshold, f"{label}.visualAcceptanceThreshold", errors)
+ layer_scores = item.get("layerScores")
+ if layer_scores is not None:
+ if not isinstance(layer_scores, dict):
+ errors.append(f"{label}.layerScores must be an object")
+ else:
+ for key, value in layer_scores.items():
+ if not isinstance(key, str):
+ errors.append(f"{label}.layerScores keys must be strings")
+ if not is_number(value) or value < 0 or value > 1:
+ errors.append(f"{label}.layerScores.{key} must be a number from 0 to 1")
+
+
+def validate_feature_review_targets(
+ spec: dict[str, Any],
+ errors: list[str],
+ warnings: list[str],
+) -> None:
+ targets = spec.get("featureReviewTargets")
+ policy = feature_review_policy(spec)
+ if targets is None:
+ if policy.get("enabled") is True:
+ errors.append("featureReviewTargets must be an array when feature review is enabled")
+ else:
+ warnings.append("quality: featureReviewTargets is missing; feature-level visual gating is disabled")
+ return
+ if not isinstance(targets, list):
+ errors.append("featureReviewTargets must be an array")
+ return
+ if not targets:
+ warnings.append("quality: featureReviewTargets is empty; component-level visual gaps can hide in the overall score")
+ return
+ ids: set[str] = set()
+ critical_by_pass: dict[str, int] = {}
+ important_by_pass: dict[str, int] = {}
+ for index, target in enumerate(targets):
+ label = f"featureReviewTargets[{index}]"
+ if not isinstance(target, dict):
+ errors.append(f"{label} must be an object")
+ continue
+ target_id = target.get("id")
+ if not isinstance(target_id, str) or not target_id.strip():
+ errors.append(f"{label}.id is required")
+ elif target_id in ids:
+ errors.append(f"duplicate feature review target id {target_id!r}")
+ else:
+ ids.add(target_id)
+ if not isinstance(target.get("name"), str) or not target["name"].strip():
+ errors.append(f"{label}.name is required")
+ tier = target.get("tier")
+ if tier not in {"critical", "important", "detail"}:
+ errors.append(f"{label}.tier must be critical, important, or detail")
+ validate_string_array(target.get("passIds"), f"{label}.passIds", errors)
+ validate_string_array(target.get("componentRefs"), f"{label}.componentRefs", errors)
+ validate_string_array(target.get("evidenceRefs"), f"{label}.evidenceRefs", errors)
+ minimum = target.get("minimumScore")
+ if minimum is not None:
+ validate_unit_interval(minimum, f"{label}.minimumScore", errors)
+ for field in ("mustPass",):
+ value = target.get(field)
+ if value is not None and not isinstance(value, bool):
+ errors.append(f"{label}.{field} must be boolean")
+ if tier == "critical" or target.get("mustPass") is True:
+ pass_ids = target.get("passIds", [])
+ if isinstance(pass_ids, list):
+ for pass_id in pass_ids:
+ if isinstance(pass_id, str):
+ critical_by_pass[pass_id] = critical_by_pass.get(pass_id, 0) + 1
+ elif tier == "important":
+ pass_ids = target.get("passIds", [])
+ if isinstance(pass_ids, list):
+ for pass_id in pass_ids:
+ if isinstance(pass_id, str):
+ important_by_pass[pass_id] = important_by_pass.get(pass_id, 0) + 1
+ maximum = policy.get("maxCriticalFeaturesPerPass", 5)
+ if is_number(maximum):
+ for pass_id, count in critical_by_pass.items():
+ if count > int(maximum):
+ errors.append(
+ f"pass {pass_id!r} has {count} critical feature targets; "
+ f"maximum is {int(maximum)}"
+ )
+ important_maximum = policy.get("maxImportantFeaturesPerPass", 3)
+ if is_number(important_maximum):
+ for pass_id, count in important_by_pass.items():
+ if count > int(important_maximum):
+ errors.append(
+ f"pass {pass_id!r} has {count} important feature targets; "
+ f"maximum is {int(important_maximum)}"
+ )
+ assessment = spec.get("preSpecAssessment")
+ complexity = (
+ assessment.get("complexity", {}).get("tier")
+ if isinstance(assessment, dict) and isinstance(assessment.get("complexity"), dict)
+ else None
+ )
+ starter_ids = {
+ "overall-silhouette",
+ "primary-structure",
+ "reference-material-system",
+ }
+ if complexity in {"moderate", "complex", "ultra-complex"} and ids.issubset(starter_ids):
+ warnings.append(
+ "quality: replace generic starter featureReviewTargets with object-specific "
+ "identity-defining semantic systems before strict validation"
+ )
+
+
+def validate_feature_reviews(
+ entry: dict[str, Any],
+ label: str,
+ errors: list[str],
+) -> None:
+ reviews = entry.get("featureReviews")
+ if reviews is None:
+ return
+ if not isinstance(reviews, list):
+ errors.append(f"{label}.featureReviews must be an array")
+ return
+ ids: set[str] = set()
+ for index, review in enumerate(reviews):
+ item_label = f"{label}.featureReviews[{index}]"
+ if not isinstance(review, dict):
+ errors.append(f"{item_label} must be an object")
+ continue
+ feature_id = review.get("id")
+ if not isinstance(feature_id, str) or not feature_id.strip():
+ errors.append(f"{item_label}.id is required")
+ elif feature_id in ids:
+ errors.append(f"{label}.featureReviews has duplicate id {feature_id!r}")
+ else:
+ ids.add(feature_id)
+ score = review.get("score")
+ if score is not None:
+ validate_unit_interval(score, f"{item_label}.score", errors)
+ for field in ("notes",):
+ value = review.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"{item_label}.{field} must be a string")
+ visible = review.get("visible")
+ if visible is not None and not isinstance(visible, bool):
+ errors.append(f"{item_label}.visible must be boolean")
+
+
+def validate_review_history(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ history = spec.get("reviewHistory", [])
+ if history is None:
+ return
+ if not isinstance(history, list):
+ errors.append("reviewHistory must be an array")
+ return
+ for index, entry in enumerate(history):
+ if not isinstance(entry, dict):
+ errors.append(f"reviewHistory[{index}] must be an object")
+ continue
+ action = entry.get("action")
+ if action is not None and action not in VALID_REVIEW_ACTIONS:
+ errors.append(f"reviewHistory[{index}].action is invalid")
+ fidelity = entry.get("estimatedFidelity")
+ if fidelity is not None:
+ validate_unit_interval(fidelity, f"reviewHistory[{index}].estimatedFidelity", errors)
+ for field in ("matched", "mismatches", "specFixes", "codeFixes", "evidence"):
+ validate_string_array(entry.get(field), f"reviewHistory[{index}].{field}", errors)
+ visual = entry.get("visualEvidence")
+ if visual is not None:
+ validate_visual_evidence_item(visual, f"reviewHistory[{index}].visualEvidence", errors)
+ validate_feature_reviews(entry, f"reviewHistory[{index}]", errors)
+ pass_id = entry.get("passId")
+ if (
+ pass_id in VISUAL_PASS_IDS
+ and action == "continue"
+ and not (isinstance(visual, dict) and visual.get("renderScreenshot"))
+ ):
+ warnings.append(
+ f"reviewHistory[{index}] continues visual pass {pass_id!r} without a render screenshot"
+ )
+ if pass_id in VISUAL_PASS_IDS and action == "continue":
+ if not isinstance(visual, dict) or not visual.get("comparisonImage"):
+ warnings.append(
+ f"quality: reviewHistory[{index}] continues visual pass {pass_id!r} without an AI vision comparison image"
+ )
+ score = entry.get("aiVisionScore")
+ threshold = entry.get("visualAcceptanceThreshold", 0.7)
+ if not is_number(score):
+ warnings.append(
+ f"quality: reviewHistory[{index}] continues visual pass {pass_id!r} without aiVisionScore"
+ )
+ elif is_number(threshold) and float(score) < float(threshold):
+ warnings.append(
+ f"quality: reviewHistory[{index}] aiVisionScore {score} is below threshold {threshold}"
+ )
+ loop = spec.get("selfCorrectLoop")
+ acceptance = loop.get("visualAcceptance", {}) if isinstance(loop, dict) else {}
+ if isinstance(acceptance, dict) and acceptance.get("layerScoresRequired") is True:
+ layer_scores = entry.get("layerScores")
+ if not isinstance(layer_scores, dict) or not layer_scores:
+ warnings.append(
+ f"quality: reviewHistory[{index}] continues visual pass {pass_id!r} without layerScores"
+ )
+ else:
+ required_layers = acceptance.get("requiredLayerScores", [])
+ if isinstance(required_layers, list):
+ missing_layers = [
+ layer
+ for layer in required_layers
+ if isinstance(layer, str) and layer not in layer_scores
+ ]
+ if missing_layers:
+ warnings.append(
+ f"quality: reviewHistory[{index}] layerScores missing: "
+ + ", ".join(missing_layers)
+ )
+ failures = feature_gate_failures(spec, entry, str(pass_id))
+ for failure in failures:
+ warnings.append(
+ f"quality: reviewHistory[{index}] feature gate failed: {failure}"
+ )
+
+
+def validate_visual_evidence_history(spec: dict[str, Any], errors: list[str]) -> None:
+ visual_history = spec.get("visualEvidence", [])
+ if visual_history is None:
+ return
+ if not isinstance(visual_history, list):
+ errors.append("visualEvidence must be an array")
+ return
+ for index, item in enumerate(visual_history):
+ validate_visual_evidence_item(item, f"visualEvidence[{index}]", errors)
+
+
+def validate_build_passes(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> list[str]:
+ build_passes = spec.get("buildPasses")
+ if build_passes is None:
+ warnings.append("quality: missing buildPasses; model construction can skip blockout/structural/material gates")
+ return []
+ if not isinstance(build_passes, list):
+ errors.append("buildPasses must be an array")
+ return []
+ ids: list[str] = []
+ for index, item in enumerate(build_passes):
+ if not isinstance(item, dict):
+ errors.append(f"buildPasses[{index}] must be an object")
+ continue
+ pass_id = item.get("id")
+ if not isinstance(pass_id, str) or not pass_id.strip():
+ errors.append(f"buildPasses[{index}].id is required")
+ continue
+ if pass_id in ids:
+ errors.append(f"duplicate buildPasses id {pass_id!r}")
+ ids.append(pass_id)
+ for field in ("goal",):
+ value = item.get(field)
+ if value is not None and not isinstance(value, str):
+ errors.append(f"buildPasses[{index}].{field} must be a string")
+ validate_string_array(item.get("componentRefs"), f"buildPasses[{index}].componentRefs", errors)
+ validate_string_array(item.get("acceptance"), f"buildPasses[{index}].acceptance", errors)
+ if ids:
+ if ids[0] != "blockout":
+ warnings.append("quality: first build pass should be blockout")
+ if "structural-pass" not in ids:
+ warnings.append("quality: missing structural-pass; component hierarchy may be skipped")
+ if not ({"material-pass", "surface-pass"} & set(ids)):
+ warnings.append("quality: missing material/surface pass; model may stay as flat geometry")
+ return ids
+
+
+def review_completes_pass(
+ spec: dict[str, Any],
+ entry: dict[str, Any],
+ pass_id: str,
+) -> bool:
+ if entry.get("passId") != pass_id or entry.get("action") != "continue":
+ return False
+ visual = entry.get("visualEvidence")
+ if pass_id in VISUAL_PASS_IDS:
+ if not (
+ isinstance(visual, dict)
+ and visual.get("renderScreenshot")
+ and visual.get("comparisonImage")
+ ):
+ return False
+ score = entry.get("aiVisionScore")
+ threshold = entry.get("visualAcceptanceThreshold", 0.7)
+ if not is_number(score) or not is_number(threshold) or float(score) < float(threshold):
+ return False
+ if feature_gate_failures(spec, entry, pass_id):
+ return False
+ return True
+
+
+def completed_passes_from_history(spec: dict[str, Any], pass_ids: list[str]) -> list[str]:
+ history = spec.get("reviewHistory", [])
+ if not isinstance(history, list):
+ return []
+ completed: list[str] = []
+ for pass_id in pass_ids:
+ if any(
+ isinstance(entry, dict) and review_completes_pass(spec, entry, pass_id)
+ for entry in history
+ ):
+ completed.append(pass_id)
+ else:
+ break
+ return completed
+
+
+def validate_sculpt_pipeline(
+ spec: dict[str, Any],
+ build_pass_ids: list[str],
+ errors: list[str],
+ warnings: list[str],
+) -> None:
+ pipeline = spec.get("sculptPipeline")
+ if pipeline is None:
+ warnings.append("quality: missing sculptPipeline; pass order is not locked and generation can skip build passes")
+ return
+ if not isinstance(pipeline, dict):
+ errors.append("sculptPipeline must be an object")
+ return
+ pass_order = pipeline.get("passOrder")
+ if pass_order is None:
+ warnings.append("quality: sculptPipeline.passOrder is missing")
+ pass_order_ids = build_pass_ids
+ else:
+ validate_string_array(pass_order, "sculptPipeline.passOrder", errors)
+ pass_order_ids = [str(value) for value in pass_order] if isinstance(pass_order, list) else build_pass_ids
+ if build_pass_ids and pass_order_ids and pass_order_ids != build_pass_ids:
+ warnings.append("sculptPipeline.passOrder differs from buildPasses order; sync the pipeline before generation")
+ current = pipeline.get("currentPass")
+ if current is not None and current != "complete" and current not in (pass_order_ids or build_pass_ids):
+ errors.append("sculptPipeline.currentPass must be a known build pass or complete")
+ completed = pipeline.get("completedPasses", [])
+ validate_string_array(completed, "sculptPipeline.completedPasses", errors)
+ if isinstance(completed, list):
+ expected = completed_passes_from_history(spec, pass_order_ids or build_pass_ids)
+ if list(completed) != expected:
+ warnings.append("sculptPipeline.completedPasses is out of sync with reviewHistory; run sculpt_pass_orchestrator.py sync")
+ for pass_id in completed:
+ if pass_id not in (pass_order_ids or build_pass_ids):
+ errors.append(f"sculptPipeline.completedPasses contains unknown pass {pass_id!r}")
+ gate_mode = pipeline.get("passGateMode")
+ if gate_mode != "locked-sequential":
+ warnings.append("quality: sculptPipeline.passGateMode should be locked-sequential")
+ validate_string_array(pipeline.get("nextRequiredEvidence"), "sculptPipeline.nextRequiredEvidence", errors)
+
+
+def has_non_empty_detail(value: Any) -> bool:
+ if isinstance(value, str):
+ return bool(value.strip()) and value.strip().lower() not in {"none", "unassessed", "n/a"}
+ if isinstance(value, list):
+ return any(has_non_empty_detail(item) for item in value)
+ if isinstance(value, dict):
+ return any(has_non_empty_detail(item) for item in value.values())
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return abs(float(value)) > 0
+ return False
+
+
+def layer_number(value: Any, keys: tuple[str, ...]) -> float:
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
+ if isinstance(value, dict):
+ for key in keys:
+ item = value.get(key)
+ if isinstance(item, (int, float)) and not isinstance(item, bool):
+ return float(item)
+ return 0.0
+
+
+def reference_pbr_usable(material: dict[str, Any], threshold: float) -> tuple[bool, str]:
+ reference = material.get("referencePbr")
+ material_id = str(material.get("id") or "(unnamed)")
+ if not isinstance(reference, dict):
+ return False, f"material {material_id!r} needs usable referencePbr extracted from source pixels"
+ if reference.get("usable") is not True:
+ return False, f"material {material_id!r} referencePbr.usable must be true"
+ confidence = reference.get("confidence", reference.get("estimatedFidelity"))
+ if not is_number(confidence) or float(confidence) < threshold:
+ return False, f"material {material_id!r} referencePbr confidence must be >= {threshold}"
+ maps = reference.get("maps")
+ if not isinstance(maps, dict):
+ return False, f"material {material_id!r} referencePbr needs maps"
+ for channel in ("albedo", "roughness", "height", "normal", "ao"):
+ entry = maps.get(channel)
+ if not isinstance(entry, dict) or not has_non_empty_detail(entry.get("url") or entry.get("path")):
+ return False, f"material {material_id!r} referencePbr missing {channel} map path/url"
+ return True, ""
+
+
+def validate_look_dev_targets(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:
+ targets = spec.get("lookDevTargets")
+ if targets is None:
+ warnings.append("quality: missing lookDevTargets; material/color/lighting passes may stay flat")
+ elif not isinstance(targets, dict):
+ errors.append("lookDevTargets must be an object")
+ materials = [item for item in spec.get("materials", []) if isinstance(item, dict)]
+ if materials:
+ has_palette = any(
+ has_non_empty_detail(item.get("colorVariation"))
+ or has_non_empty_detail(item.get("albedo", {}).get("secondary") if isinstance(item.get("albedo"), dict) else None)
+ for item in materials
+ )
+ has_response = any(
+ layer_number(item.get("roughness"), ("variation", "base")) > 0
+ or layer_number(item.get("normal"), ("strength", "amplitude")) > 0
+ or layer_number(item.get("bump"), ("amplitude", "strength")) > 0
+ or layer_number(item.get("displacement"), ("amplitude", "strength")) > 0
+ for item in materials
+ )
+ has_locality = any(
+ has_non_empty_detail(item.get("localOverrides"))
+ or (
+ isinstance(item.get("wear"), dict)
+ and (
+ layer_number(item["wear"].get("edgeWear"), ("base", "amount")) > 0
+ or has_non_empty_detail(item["wear"].get("scratches"))
+ or has_non_empty_detail(item["wear"].get("chips"))
+ )
+ )
+ or (
+ isinstance(item.get("dirt"), dict)
+ and (
+ layer_number(item["dirt"].get("amount"), ("base", "amount")) > 0
+ or layer_number(item["dirt"].get("cavityBias"), ("base", "amount")) > 0
+ )
+ )
+ or has_non_empty_detail(item.get("moss"))
+ or has_non_empty_detail(item.get("stains"))
+ or has_non_empty_detail(item.get("scratches"))
+ or has_non_empty_detail(item.get("chips"))
+ or has_non_empty_detail(item.get("wetness"))
+ or has_non_empty_detail(item.get("patina"))
+ for item in materials
+ )
+ if not has_palette:
+ warnings.append("quality: material-pass needs reference-derived albedo palette or secondary/accent color zones")
+ if not has_response:
+ warnings.append("quality: material-pass needs roughness variation or normal/bump/displacement response")
+ if not has_locality:
+ warnings.append("quality: material-pass needs local overrides, AO, dirt, wear, stains, moss, chips, scratches, or equivalent masks")
+ quality_first = isinstance(targets, dict) and targets.get("qualityPriority") == "reference-fidelity"
+ if quality_first:
+ material_targets = targets.get("materialPass", {})
+ if not isinstance(material_targets, dict):
+ warnings.append("quality: quality-first lookDevTargets.materialPass must be an object")
+ material_targets = {}
+ minimum_resolution = material_targets.get("minimumTextureResolution", 1024)
+ if not isinstance(minimum_resolution, int) or isinstance(minimum_resolution, bool):
+ warnings.append("quality: minimumTextureResolution must be an integer")
+ minimum_resolution = 1024
+ required_channels = {
+ str(item).lower()
+ for item in material_targets.get("independentMapChannels", [])
+ if isinstance(item, str)
+ }
+ extraction_targets = material_targets.get("referencePbrExtraction", {})
+ if not isinstance(extraction_targets, dict):
+ extraction_targets = {}
+ pbr_required = (
+ extraction_targets.get("requiredWhenSourceImagePresent") is True
+ and has_non_empty_detail(spec.get("sourceImage"))
+ )
+ pbr_threshold = extraction_targets.get("targetThreshold", 0.7)
+ if not is_number(pbr_threshold):
+ pbr_threshold = 0.7
+ expected_channels = {"albedo", "roughness", "height", "normal", "ambient-occlusion"}
+ if not expected_channels.issubset(required_channels):
+ warnings.append(
+ "quality: quality-first materialPass must require independent albedo, roughness, "
+ "height, normal, and ambient-occlusion channels"
+ )
+ for material in materials:
+ if material.get("qualityTier") == "utility":
+ continue
+ material_id = str(material.get("id") or "(unnamed)")
+ resolution = material.get("textureResolution")
+ if not isinstance(resolution, int) or isinstance(resolution, bool) or resolution < minimum_resolution:
+ warnings.append(
+ f"quality: material {material_id!r} textureResolution must be >= {minimum_resolution}"
+ )
+ projection = material.get("textureProjection")
+ if not isinstance(projection, dict) or not has_non_empty_detail(projection.get("mode")):
+ warnings.append(
+ f"quality: material {material_id!r} needs textureProjection.mode and texel-density intent"
+ )
+ bands = material.get("surfaceFrequencyBands")
+ band_ids = {
+ str(item.get("id")).lower()
+ for item in bands
+ if isinstance(item, dict) and has_non_empty_detail(item.get("id"))
+ } if isinstance(bands, list) else set()
+ missing_bands = {"macro", "meso", "micro"} - band_ids
+ if missing_bands:
+ warnings.append(
+ f"quality: material {material_id!r} missing surface frequency bands: "
+ + ", ".join(sorted(missing_bands))
+ )
+ roughness = material.get("roughness")
+ roughness_map = roughness.get("map") if isinstance(roughness, dict) else None
+ if not has_non_empty_detail(roughness_map) or "albedo" in str(roughness_map).lower():
+ warnings.append(f"quality: material {material_id!r} needs an independent roughness map")
+ if not has_non_empty_detail(material.get("ambientOcclusion")):
+ warnings.append(
+ f"quality: material {material_id!r} needs an independent ambient-occlusion response"
+ )
+ if pbr_required:
+ ok, message = reference_pbr_usable(material, float(pbr_threshold))
+ if not ok:
+ warnings.append(f"quality: {message}")
+ lighting = spec.get("lightingFromPhoto", [])
+ if not isinstance(lighting, list):
+ errors.append("lightingFromPhoto must be an array")
+ else:
+ meaningful = [item for item in lighting if has_non_empty_detail(item)]
+ if len(meaningful) < 3:
+ warnings.append("quality: lighting-pass needs concrete key/fill/rim or environment light entries")
+ lighting_text = " ".join(str(item).lower() for item in meaningful)
+ if meaningful and not any(term in lighting_text for term in ("exposure", "tone", "aces", "filmic")):
+ warnings.append("quality: lighting-pass needs exposure and tone mapping intent")
+ if meaningful and not any(term in lighting_text for term in ("contact shadow", "ground shadow", "ambient occlusion", "ao")):
+ warnings.append("quality: lighting-pass needs contact shadow or ground shadow behavior")
+
+
+def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:
+ errors: list[str] = []
+ warnings: list[str] = []
+ for key, expected_type in REQUIRED_TOP_LEVEL.items():
+ if key not in spec:
+ errors.append(f"missing top-level field {key!r}")
+ elif not isinstance(spec[key], expected_type):
+ errors.append(f"field {key!r} must be {expected_type.__name__}")
+ suitability = spec.get("suitability")
+ if suitability not in VALID_SUITABILITY:
+ errors.append("suitability must be pass, conditional, or reject")
+ validate_pre_spec_assessment(spec, errors, warnings)
+ validate_terminology_profile(spec, errors, warnings)
+ validate_score_block(spec, errors, warnings)
+ validate_quality_targets(spec, errors, warnings)
+ validate_quality_contract(spec, errors, warnings)
+ validate_action_readiness(spec, errors, warnings)
+ validate_self_correct_loop(spec, errors, warnings)
+ validate_feature_review_targets(spec, errors, warnings)
+ validate_review_history(spec, errors, warnings)
+ validate_visual_evidence_history(spec, errors)
+ build_pass_ids = validate_build_passes(spec, errors, warnings)
+ validate_sculpt_pipeline(spec, build_pass_ids, errors, warnings)
+ validate_look_dev_targets(spec, errors, warnings)
+ evidence_ids = validate_evidence(spec, errors, warnings)
+ material_ids = validate_materials(spec, errors, warnings)
+ validate_components(spec, material_ids, evidence_ids, errors, warnings)
+ lod_plan = spec.get("lodPlan")
+ if lod_plan is not None and not isinstance(lod_plan, list):
+ errors.append("lodPlan must be an array")
+ performance = spec.get("performanceBudget")
+ if performance is not None and not isinstance(performance, dict):
+ errors.append("performanceBudget must be an object")
+ validate_quality_depth(spec, errors, warnings)
+ if suitability == "pass" and spec.get("risks"):
+ warnings.append("suitability is pass but risks are present; confirm they are acceptable")
+ return errors, warnings
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("spec", type=Path)
+ parser.add_argument("--json", action="store_true", help="Print machine-readable result")
+ parser.add_argument(
+ "--strict-quality",
+ action="store_true",
+ help="Treat quality warnings as validation errors before implementation/generation",
+ )
+ args = parser.parse_args(argv)
+
+ try:
+ spec = load_spec(args.spec)
+ errors, warnings = validate_spec(spec)
+ except ValueError as exc:
+ errors, warnings = [str(exc)], []
+
+ if args.strict_quality:
+ errors.extend(
+ f"strict quality failure: {warning.removeprefix('quality: ').strip()}"
+ for warning in warnings
+ if warning.startswith("quality:")
+ )
+
+ ok = not errors
+ result = {
+ "ok": ok,
+ "errors": errors,
+ "warnings": warnings,
+ "summary": {
+ "targetName": spec.get("targetName") if "spec" in locals() else None,
+ "suitability": spec.get("suitability") if "spec" in locals() else None,
+ "components": len(spec.get("componentTree", [])) if "spec" in locals() else 0,
+ "materials": len(spec.get("materials", [])) if "spec" in locals() else 0,
+ },
+ }
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print("PASS" if ok else "FAIL")
+ for warning in warnings:
+ print(f"warning: {warning}")
+ for error in errors:
+ print(f"error: {error}")
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/visual_feature_gate.py b/scripts/visual_feature_gate.py
new file mode 100755
index 0000000..f79cd91
--- /dev/null
+++ b/scripts/visual_feature_gate.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python3
+"""Shared feature-level acceptance logic for visual sculpt passes."""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def is_number(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
+
+
+def feature_review_policy(spec: dict[str, Any]) -> dict[str, Any]:
+ loop = spec.get("selfCorrectLoop")
+ if not isinstance(loop, dict):
+ return {}
+ acceptance = loop.get("visualAcceptance")
+ if not isinstance(acceptance, dict):
+ return {}
+ policy = acceptance.get("featureReviewPolicy")
+ return policy if isinstance(policy, dict) else {}
+
+
+def feature_targets_for_pass(spec: dict[str, Any], pass_id: str) -> list[dict[str, Any]]:
+ targets = spec.get("featureReviewTargets", [])
+ if not isinstance(targets, list):
+ return []
+ applicable: list[dict[str, Any]] = []
+ for target in targets:
+ if not isinstance(target, dict):
+ continue
+ pass_ids = target.get("passIds", [])
+ if isinstance(pass_ids, list) and pass_id in pass_ids:
+ applicable.append(target)
+ return applicable
+
+
+def feature_gate_failures(
+ spec: dict[str, Any],
+ entry: dict[str, Any],
+ pass_id: str,
+) -> list[str]:
+ policy = feature_review_policy(spec)
+ if policy.get("enabled") is not True:
+ return []
+
+ targets = feature_targets_for_pass(spec, pass_id)
+ critical = [
+ target
+ for target in targets
+ if target.get("tier") == "critical" or target.get("mustPass") is True
+ ]
+ max_critical = policy.get("maxCriticalFeaturesPerPass", 5)
+ failures: list[str] = []
+ if is_number(max_critical) and len(critical) > int(max_critical):
+ failures.append(
+ f"pass {pass_id!r} defines {len(critical)} critical features; "
+ f"group them into at most {int(max_critical)} semantic systems"
+ )
+ important = [target for target in targets if target.get("tier") == "important"]
+ max_important = policy.get("maxImportantFeaturesPerPass", 3)
+ if is_number(max_important) and len(important) > int(max_important):
+ failures.append(
+ f"pass {pass_id!r} defines {len(important)} important features; "
+ f"keep only the {int(max_important)} most uncertain or high-value systems"
+ )
+
+ reviews = entry.get("featureReviews", [])
+ review_by_id = {
+ review.get("id"): review
+ for review in reviews
+ if isinstance(review, dict) and isinstance(review.get("id"), str)
+ } if isinstance(reviews, list) else {}
+
+ default_threshold = policy.get("criticalDefaultThreshold", 0.8)
+ for target in critical:
+ target_id = target.get("id")
+ if not isinstance(target_id, str) or not target_id:
+ continue
+ review = review_by_id.get(target_id)
+ if not isinstance(review, dict):
+ failures.append(f"critical feature {target_id!r} has no AI vision review")
+ continue
+ if review.get("visible") is False:
+ failures.append(f"critical feature {target_id!r} is not visible in the review view")
+ continue
+ score = review.get("score")
+ minimum = target.get("minimumScore", default_threshold)
+ if not is_number(score):
+ failures.append(f"critical feature {target_id!r} has no numeric score")
+ elif not is_number(minimum) or float(score) < float(minimum):
+ failures.append(
+ f"critical feature {target_id!r} score {score} is below {minimum}"
+ )
+ important_ids = {
+ target.get("id")
+ for target in targets
+ if target.get("tier") == "important" and isinstance(target.get("id"), str)
+ }
+ important_scores = [
+ float(review["score"])
+ for feature_id, review in review_by_id.items()
+ if feature_id in important_ids and is_number(review.get("score"))
+ ]
+ important_threshold = policy.get("importantAverageThreshold", 0.65)
+ if important_scores and is_number(important_threshold):
+ average = sum(important_scores) / len(important_scores)
+ if average < float(important_threshold):
+ failures.append(
+ f"reviewed important features average {average:.3f} is below "
+ f"{float(important_threshold):.3f}"
+ )
+ return failures