Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.
Python 3dai-agentsclaude-codecomputer-graphicsgenerativeimage-to-3dprocedural-generationthreejstypescriptwebgl
v1.2.0: humanoid character generator (flattened template, per-part materials, character passes)
hoainho6c851e78a200
diff --git a/README.md b/README.mdindex a483316..a20d7ff 100644--- a/README.md+++ b/README.md@@ -16,6 +16,12 @@ It works under Claude Code, Codex, or OpenCode. It is agent-agnostic: wherever t---+## Subjects and detail accuracy (v1.1)++- Objects and characters. Each subject is classified `object`, `character`, or `hybrid`. Objects follow the hard-surface pipeline; characters route through an anatomy-aware track (head-unit proportions, facial landmarks, pose) documented in `references/character-reconstruction.md`.+- Detail-first analysis. Before code generation the pipeline enumerates a `detailInventory` of identity-defining small details (gloss, bevel/rounding, screws/rivets, engraved or painted linework, contours, stains and wear). Every detail must map to a real component or material entry, and a strict-quality gate blocks generation until the inventory is complete. Taxonomy: `references/detail-inventory.md`.+- Maximum likeness for a specific person or character. An opt-in projection-first path fits a parametric template to image landmarks, de-lights the photo, camera-matches the render, and projects the reference onto the mesh. A single image cannot guarantee 100 percent likeness, so the pipeline reports per-region confidence and asks for more views when it matters. Details and sources: `references/likeness-maximization.md`.+## Why it is token-efficientMost 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.@@ -29,6 +35,40 @@ Most image-to-3D agent loops burn tokens by asking the model to do mechanical woThe 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.+## Token cost analysis++The numbers below are engineering estimates, not a measured benchmark. They are order-of-magnitude figures anchored to one reference build (a rounded-bevel loot chest: gradient enamel, gold corner brackets, an emissive emblem, resolved in about six render-review cycles). Actual cost varies with the model tier, image resolution, object complexity, and — above all — how many review cycles a subject needs. Treat them as a cost model, not a guarantee.++Where the tokens go per full object reconstruction (image to a verified 3D model):++| Stage | Est. model tokens | Notes |+| --- | --- | --- |+| Deterministic scripts (probe, assessment, spec, validate, generate, sync) | ~2k-5k total | Run as subprocesses. This is the work that is near-free. |+| Read the reference image | <1k | A small reference; higher-res costs more. |+| Author assessment + detail inventory + spec JSON | ~15k-25k | The spec is the largest text artifact. |+| Write and edit the Three.js factory | ~20k-45k | Scales with part count and edit iterations. |+| Render-review loop (5-8 cycles) | ~30k-70k | The dominant cost; scales linearly with cycles. |+| **Total, one object** | **~80k-180k** | Simple/few-cycles to complex/many-cycles. |++One render-review cycle in isolation:++| Step | Est. model tokens |+| --- | --- |+| Capture screenshot (browser tool) | ~0 (tool call) |+| Package comparison sheet (stdlib script) | ~0 (subprocess) |+| Inspect the comparison sheet with vision | ~2k-3k |+| Write the review and scores (script) | ~1k-2k |+| **Per cycle** | **~5k-12k** |++Characters cost more (more review cycles plus landmark and projection checks): roughly ~150k-350k for a full stylized/likeness reconstruction once the v1.2 character generator lands.++What this buys you:++- Deterministic scripts contribute close to zero model tokens, so validation, gating, detail counting, sheet packaging, and pipeline state never eat context.+- Model tokens are spent only on vision (reading one sheet per pass), authoring the spec, and writing code.+- The gates are the savings mechanism: strict-quality blocks codegen on an underspecified spec, and the detail-inventory gate blocks it on missing detail — each avoided bad render saves roughly one full cycle (~10k-20k tokens).+- The single biggest lever on cost is the review-cycle count. A well-formed spec up front is worth more tokens than any micro-optimization downstream.+---## How it works@@ -119,6 +159,11 @@ python3 scripts/generate_threejs_factory.py spec.json --out src/createObjectMode| `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. |+| `build_detail_inventory.py` | Slice the reference into zones and scaffold a detail inventory (gloss, bevel, fasteners, linework, stains). |+| `extract_reference_landmarks.py` | Overlay a landmark grid and scaffold an anatomy block for character subjects. |+| `solve_reference_camera.py` | Emit a reference-camera block so the render can be camera-matched to the photo. |+| `delight_reference.py` | Approximate a neutral albedo from the photo before texture projection (documented approximation). |+| `bake_projected_texture.py` | Emit a projection/UV-bake descriptor for photo-texture projection in the Three.js runtime. |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).diff --git a/SKILL.md b/SKILL.mdindex f9fb938..2484794 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,8 +1,8 @@---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.+description: Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.license: MIT-version: 1.0.0+version: 1.2.0---# img2threejs — Image to procedural Three.js@@ -47,10 +47,26 @@ Full flags: `references/scripts.md`. Never let a script *score* visuals — that1. 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`.+ Set `objectClass.primaryDomain` (`object` | `character` | `hybrid`) and fill the seeded+ `detailInventory` (its `targetMinDetails` scales with complexity).+2b. **Detail inventory** (do not skip for detailed subjects) — scan zones and enumerate every+ identity-defining small detail (gloss, bevel, fasteners, linework, contours, stains):+ `scripts/build_detail_inventory.py <image> --mode grid-3x3 --out-dir <dir> --out di.json`.+ Each detail MUST map to a `component.localFeatures` or `material.localOverrides` entry — never+ prose only. Taxonomy + 3D-term recipes: `references/detail-inventory.md`.+2c. **Character/hybrid subjects** — capture head-unit proportions + facial/body landmarks:+ `scripts/extract_reference_landmarks.py <image> --out anatomy.json --overlay overlay.png`, then+ fill `preSpecAssessment.anatomy`. Route: `references/character-reconstruction.md`. For maximum+ likeness use the projection-first path (`references/likeness-maximization.md`): solve the camera+ (`solve_reference_camera.py`), de-light the photo (`delight_reference.py`), and project it onto+ the fitted mesh (`bake_projected_texture.py`). A single image cannot guarantee 100% likeness —+ report per-region confidence and request more views for a real person.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".+ systems (≤5 critical, ≤3 important per pass); for characters add `anatomy-proportion`,+ `face-landmark-placement`, `pose-silhouette`, `outfit-and-palette`. 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.@@ -85,6 +101,16 @@ Full flags: `references/scripts.md`. Never let a script *score* visuals — that`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.+- **Detail inventory**: for `moderate`+ subjects strict-quality blocks code gen until the+ `detailInventory` reaches `targetMinDetails` and every detail maps to a real component/material+ entry (gloss needs low-roughness/clearcoat; fasteners need instancing/micro parts).+- **Character track**: when `primaryDomain` is `character`/`hybrid` (or `--character`), the spec+ author auto-builds a stylized humanoid template (head/neck/torso/arms + hair, glasses,+ headphones, face features), flattened to world space under a hidden root, with per-part+ character materials and character build passes (`proportion-lock`, `feature-placement`).+ strict-quality requires a filled `anatomy` block (head-units, proportions, face landmarks) and+ character feature targets. Suitability routing for humans: `references/validation-rubric.md`+ (stylized vs maximum-likeness). Stylized bust, not a face-copy; refine positions per reference.## Self-Correctiondiff --git a/docs/UPGRADE_PLAN.md b/docs/UPGRADE_PLAN.mdnew file mode 100644index 0000000..c860637--- /dev/null+++ b/docs/UPGRADE_PLAN.md@@ -0,0 +1,343 @@+# img2threejs Upgrade Plan++Status: v1.2.0 SHIPPED. v1.1.0 = Track A detail-first + Track B/likeness scaffolding. v1.2.0 = humanoid character GENERATOR: a flattened, world-space humanoid componentTree template (head/neck/torso/arms + hair, glasses, headphones, face features), per-part character materials, character build passes (proportion-lock, feature-placement) and feature targets, auto-enabled when primaryDomain is character/hybrid (or --character). Verified end-to-end (spec -> generate -> browser render) on a real portrait, producing a recognizable stylized bust. 19/19 tests pass; object pipeline unaffected.+Target versions: 1.1.0 (Track A), 1.2.0 (Track B + character generator)++v1.2.0 implementation notes:+- Generator nodes carry transform.scale that cascades to children, so the humanoid template flattens all parts to world space under a hidden, unit-scaled root to avoid non-uniform-scale distortion. (Rig/pivot hierarchy for animation is a future refinement.)+- createSculptMaterial only honours a colorVariation.palette with >= 2 entries (else it blends in beige fallback tones), so each character material provides two shades of its intended colour.+- Remaining polish (future): rectangular glasses frames, canvas-texture wordmark on the shirt decal (currently a flat orange panel), headphone placement around the neck sides, hair-shape refinement, and the projection-first likeness path (delight + camera-match + texture projection) wired into the character render.++Shipped in 1.1.0:+- Schema: preSpecAssessment.detailInventory (+ targetMinDetails by complexity), objectClass.primaryDomain, preSpecAssessment.anatomy, top-level referenceCamera.+- Gates: validate_sculpt_spec.py detail-inventory gate (count + component/material linkage + gloss/fastener checks) and character track gate (anatomy + character feature targets); both backward compatible.+- References: detail-inventory.md, character-reconstruction.md, likeness-maximization.md; procedural-patterns.md detail + character recipes; validation-rubric.md character suitability branch.+- Scripts: build_detail_inventory.py, extract_reference_landmarks.py, solve_reference_camera.py, delight_reference.py, bake_projected_texture.py.+- Tests: 16 pass (8 new covering the schema, gates, backward compat, and new scripts). SKILL.md + README updated; version bumped to 1.1.0.++Not yet implemented (follow-up, do not assume present):+- generate_threejs_factory.py humanoid rig + face-landmark placement + detail-emission hooks.+- new_sculpt_spec.py character componentTree template.+- sculpt_pass_orchestrator.py proportion-lock / feature-placement passes.+- delight/camera/projection scripts are documented approximations/descriptors, not GPU-accurate implementations.+Scope decisions locked with maintainer:+- Primary goal for human/character subjects: maximize likeness to the reference image, aiming as close to 100 percent as the input allows.+- Honest constraint: pure hand-authored primitives cannot reach photoreal likeness. The realistic path to near-100 percent, confirmed by the research in section 13, is a projection-first pipeline: fit a parametric humanoid/face template to image landmarks, then project the (de-lit) reference image itself onto the mesh as texture, and camera-match the render to the photo. Stylized/figurine remains the safe fallback when the input is weak or the user accepts it.+- Deliver both tracks. This document is the canonical spec for the work.++---++## 1. Problem statement++Two weaknesses in the current 1.0 pipeline:++1. Character / human subjects. The pipeline is built for hard-surface objects. Generated humans do not resemble the reference because there is no anatomy proportion system, no facial-landmark placement, no pose/skeleton alignment, and the suitability rubric actively rejects hair and cloth folds (the defining traits of people).+2. Fine detail is under-captured at the analysis stage. Small but identity-defining details (gloss zones, corner rounding, screws/rivets, engraved or painted linework, contour lines, stains and wear) are represented only as a single 0-3 "local detail density" score. There is no forced, evidence-linked inventory of these details before the spec is authored, so they get skipped and never reach the render.++## 2. Root-cause map (current files)++| Symptom | Root cause | Location |+| --- | --- | --- |+| Humans look nothing like the image | No anatomy/landmark/pose model; object-only geometry recipes | `references/procedural-patterns.md`, `scripts/new_pre_spec_assessment.py`, `scripts/new_sculpt_spec.py` |+| Humans get rejected early | Rubric rejects hair/cloth-fold-dominant subjects | `references/validation-rubric.md` |+| Whole-image score hides face/proportion errors | Feature gate has no anatomy features | `scripts/visual_feature_gate.py`, spec `featureReviewTargets` |+| Small details missed | Detail density is one score; no inventory artifact or gate | `references/pre-spec-assessment.md`, `scripts/new_pre_spec_assessment.py`, `scripts/validate_sculpt_spec.py` |+| No help inspecting detail zones | Probe returns metadata only | `scripts/probe_reference_image.py` |++## 3. Design principles (must hold across the upgrade)++- Scripts enforce and package; the agent's vision judges. Do not move visual scoring into scripts.+- Pure Python 3.10+ standard library only. No pip, no PIL/numpy/Playwright. PNG via `struct`/`zlib`, matching existing scripts.+- Token efficiency preserved: new gates fail fast before codegen; one packaged sheet per review; pass-gated generation unchanged.+- Backward compatible: object-only specs from 1.0 must still validate. New blocks are additive and only enforced when relevant (by complexity or by domain).+- Agent-agnostic: any new "look at the image" step works with native vision, a browser MCP, or user-supplied crops.++---++## 4. Track A - Detail-first analysis (v1.1.0)++Goal: make micro-detail capture a required, evidence-linked artifact with its own gate, so gloss, bevels, fasteners, linework, and stains reliably reach the render.++### 4.1 New artifact: `detailInventory`++Produced during assessment, carried into the spec. Shape:++```json+{+ "detailInventory": {+ "scanMethod": "component-zones | grid-3x3 | grid-4x4",+ "targetMinDetails": 6,+ "details": [+ {+ "id": "top-bevel-gloss",+ "kind": "gloss",+ "description": "sharp specular hotspot along the top chamfer under key light",+ "region": { "x": 0.2, "y": 0.15, "width": 0.6, "height": 0.12, "units": "normalized" },+ "scale": "meso",+ "affects": "material",+ "mapsTo": { "type": "material.localOverride", "ref": "enamel-gradient/top-highlight" },+ "evidenceRef": "gradient-body",+ "confidence": 0.8+ }+ ]+ }+}+```++Supported `kind` values (the detail taxonomy): `gloss`, `bevel`, `fastener` (screw/rivet/bolt), `linework` (engraving/painted line/panel-line), `contour` (edge outline/toon rim), `seam`, `stitch`, `stain` (dirt/patina/discolour/faded), `scratch`, `chip`, `decal`, `emissive`, `hole`, `groove`, `ridge`.++Rule: every `detail` must set `affects` (geometry or material or both) and `mapsTo` a real `component.localFeatures[]` entry or `material.localOverrides[]` entry. A detail described only in prose is a gate failure.++### 4.2 New reference: `references/detail-inventory.md`++Taxonomy plus how to express each detail in 3D-graphics terms:+- gloss / do bong -> roughness low zone, clearcoat, specular hotspot location, anisotropy if streaked.+- bevel / bo goc -> `edgeTreatment.type=chamfer`, bevelRadius, segments; note whether it reads as a bright rim highlight.+- fastener / oc vit -> instanced mesh, count, spacing/distribution, head shape (hemisphere/flat), recess.+- linework / net ve, duong net -> engraved groove (geometry) vs painted line (canvas-texture decal) vs panel-line (dark AO seam); legibility target.+- stain / vet o -> dirt amount, cavity bias, vertical streak, patina colour, faded/sun-bleached zone, mask location.+- seam/stitch/chip/scratch/decal/hole -> mapping to localFeatures with placement, size, orientation, material effect, geometry effect, confidence.++Each entry states: where, what changes, how strong, which evidence supports it.++### 4.3 New script: `scripts/build_detail_inventory.py`++- Input: reference image (+ optional component regions).+- Output: crops of each zone (grid or per-component) into a directory + a `detailInventory` skeleton JSON to fill.+- Purpose: force systematic zone-by-zone inspection so the agent does not eyeball the whole image once and miss small marks.+- Pure stdlib PNG slicing (struct/zlib), consistent with `make_visual_comparison_sheet.py`.++### 4.4 Schema and gate changes++- `scripts/new_pre_spec_assessment.py`: emit `detailInventory` skeleton; set `targetMinDetails` from complexity tier (simple 3, moderate 6, complex 10, ultra 16 as starting values, tunable).+- `scripts/new_sculpt_spec.py`: carry `detailInventory` into the spec; wire a helper so each detail links to a component/material.+- `scripts/validate_sculpt_spec.py` (`--strict-quality`): new checks+ - detail count >= `targetMinDetails` for the tier.+ - every detail `mapsTo` an existing component localFeature or material localOverride (no orphan prose).+ - a "detailed" object must carry material roughness variation + at least one bevel/edgeTreatment when the inventory lists gloss/bevel details.+ - gloss details require a low-roughness localOverride or clearcoat; fastener details require an instanced/repetition system or explicit small-count meso parts.+- `references/browser-screenshot-feedback.md`: add a mandatory detail close-up review - grazing-light shot that must show bevel highlights, countable fasteners, legible linework, and stains in the correct regions. Add a per-detail checklist to the review sheet.++### 4.5 Track A acceptance criteria++- Re-running the loot-chest demo: assessment enumerates at least gloss, bevel, rivets, latch, side-handle, crown-emissive, and any stains, each with an evidence region; strict-quality blocks the spec if the inventory is empty or unlinked.+- A detail close-up comparison sheet is produced and reviewed; the review records per-detail pass/fail.+- Object-only 1.0 specs still validate (backward compatible) - the new gate only fires when `detailInventory` is present or complexity >= moderate.++---++## 5. Track B - Character / figurine reconstruction (v1.2.0)++Goal: add a first-class character track that reconstructs a humanoid matching the reference as closely as the input allows - proportions, pose, facial landmarks, clothing, and palette. The default high-likeness path is projection-first (section 5.8: parametric template fit + de-lit photo projection + camera match). Stylized/figurine is the fallback when the input is weak or the user accepts it. A guaranteed 100 percent likeness from one image is not promised (section 5.10).++### 5.1 Domain detection++- `scripts/new_pre_spec_assessment.py`: add `objectClass.primaryDomain = object | character | hybrid` inferred from the agent's classification (character-like form language + skin/cloth/hair materials + humanoid silhouette).+- When `character` or `hybrid`, the assessment additionally emits an `anatomy` block and character feature targets.++### 5.2 New reference: `references/character-reconstruction.md`++- Proportion system in head-units, with a style axis: realistic ~7.5 heads, stylized ~5-6, figurine/chibi 2-3. Record measured ratios from the image (head : torso : legs, shoulder width, hip width).+- Facial landmark layout: eye line near vertical mid-head, eye spacing, nose base, mouth line, hairline, ear top/bottom. Store normalized coordinates.+- Pose / skeleton: neck, shoulders, elbows, wrists, hips, knees, ankles; match the silhouette and limb angles.+- Character materials (stylized): skin (approximate subsurface via warm base + soft roughness + rim/backlight, not true SSS), hair (hair cards or tube-along-curve per lock, layered), eyes (glossy sphere + iris decal), cloth (extrude/plane panels with fold normals), metal/leather accessories reuse Track A detail machinery.++### 5.3 Anatomy data model++```json+{+ "anatomy": {+ "styleHeads": 3.0,+ "proportions": { "headUnit": 0.18, "torso": 2.2, "legs": 3.0, "shoulderWidth": 1.6, "hipWidth": 1.3 },+ "pose": { "type": "T-pose | contrapposto | action", "jointAngles": { "leftShoulder": [0,0,-10] } },+ "faceLandmarks": {+ "eyeLine": 0.52, "eyeSpacing": 0.3, "noseBase": 0.66, "mouthLine": 0.78, "hairline": 0.34+ },+ "features": ["hair-style-id", "outfit-parts", "accessories"],+ "confidence": 0.6+ }+}+```++### 5.4 New script: `scripts/extract_reference_landmarks.py`++- Overlays a labelled grid / guide on the reference so the agent's vision can fill in landmark coordinates (eyes, shoulders, hips, joints).+- Outputs an `anatomy` skeleton with normalized coordinates + an overlay image for review.+- Stdlib only; no face-detection library - the agent supplies the judgments, the script packages the guide and records them.++### 5.5 Generator and pipeline++- `scripts/new_sculpt_spec.py`: humanoid component template - `rig` root with joint pivot nodes; head, face-feature group, hair group, torso, arms, legs as capsule/tapered primitives; outfit parts as separate components with Track A detail hooks.+- `scripts/generate_threejs_factory.py`: emit the humanoid rig (named joint pivots, action-ready sockets), capsule limbs, face-feature placement from landmarks, hair cards; expose everything via `root.userData.sculptRuntime`.+- Two new build sub-passes inserted for the character domain, before `material-pass`:+ - `proportion-lock`: block out the humanoid at the measured head-unit proportions and pose; gate on silhouette + proportion match.+ - `feature-placement`: place facial features and hair to the landmark coordinates; gate on face landmark alignment.+- `references/validation-rubric.md`: add a character suitability branch - classify humans as `character-conditional -> stylized` rather than reject; specify when to request more views (front, side, full-body) and confirm accepted stylization level.++### 5.6 Character feature gates++`scripts/visual_feature_gate.py` + spec `featureReviewTargets`: add critical character features with their own thresholds:+- anatomy-proportion (head-unit ratios, limb lengths)+- face-landmark-placement (eye line, feature spacing)+- pose-silhouette (limb angles, stance)+- outfit-and-palette (clothing shapes + colour zones)++Reviews compare against a landmark-overlay sheet, not just a whole-image score.++### 5.7 Track B acceptance criteria++- A human reference is classified `character` and produces an `anatomy` block with measured proportions + landmarks.+- A test character reconstructs at the correct head-unit count and pose, with facial features on the landmark lines and clothing colour zones matching.+- Character feature gates score face/proportion/pose independently; at least one test case passes all critical character thresholds at the stylized bar.+- Object pipeline is unaffected when `primaryDomain = object`.++### 5.8 Maximizing likeness - projection-first pipeline (research-driven)++The single largest likeness win, per section 13, is to stop hand-sculpting faces and instead fit a template and project the photo. Adopt this as the default high-likeness path for characters; keep the freehand stylized path as fallback.++1. Parametric template fit (the industry standard for likeness):+ - Ship a lightweight, code-generated parametric humanoid template (head-unit-parameterized body plus a morphable face), conceptually mirroring SMPL-X (body + face + hands, jaw and eye joints) and FLAME (face-from-scans). This is still procedural: the template is generated by code and driven by parameters, not a downloaded art pack.+ - Fit template parameters (shape, pose, expression) to the 2D landmarks and proportions extracted from the image, following the SMPLify-X idea: minimize the reprojection error between template landmarks and observed image landmarks. Landmarks come from `extract_reference_landmarks.py` (agent-vision assisted).+ - Rationale: proportions + landmark alignment are where "looks like the person" lives; freehand primitives cannot hit this reliably.++2. Photo texture projection (biggest single-image likeness gain):+ - Solve a camera for the reference (focal/FOV/orientation) so the mesh aligns with the photo, then project the reference image onto the fitted mesh via projective/camera-projection texturing (Three.js `ShaderMaterial`, or the `three-projected-material` approach) and bake it into the mesh UVs for the visible (front) side.+ - Infer unseen back/sides by mirroring the front texture across the symmetry plane, palette-continuing, or requesting a back/side view. Flag inferred regions with lower confidence.++3. De-light before projecting:+ - The raw photo contains baked shadows, highlights, and AO. Before treating it as albedo, run a de-lighting step to recover a neutral base color (high-pass / overlay neutralization, or an AI delighter equivalent), then generate independent roughness/normal/AO. An albedo map must be free of baked lighting. Without this, the projected texture will fight the scene lights and break likeness.++4. Camera match:+ - Estimate and store camera focal length, FOV, and orientation so the review render can be taken from the same viewpoint as the photo, enabling pixel-level overlay comparison and correct projection. Add a `referenceCamera` block to the spec.++5. Turnaround / reference-plane workflow:+ - Follow the artist standard: front, side, and (when available) back orthographic references at matched height, a proportion grid in head-units, silhouette-first blockout per view, and a color palette captured alongside. When only one view exists, mark it and request more via `request-input`.++6. Rig and deform in Three.js:+ - Emit a `SkinnedMesh` with a joint skeleton for the body and morph targets / blend shapes for facial expression, exportable as glTF. Keep predictable topology so blendshapes deform cleanly (retopology principle). Expose the skeleton and morph channels through `root.userData.sculptRuntime`.++7. Part-specific recipes (stylized-to-realistic dial):+ - Skin: approximate subsurface via warm base color, soft roughness, and a rim/back light; use `MeshPhysicalMaterial` sheen/transmission cautiously.+ - Hair: hair cards or tube-along-curve per lock, layered, with an alpha/anisotropic highlight; hair is the classic single-image failure, so prefer stylized clumps over strands.+ - Eyes: glossy sphere plus an iris decal/texture; correct catchlight sells realism.+ - Clothing: extrude/plane panels with fold normals; reuse Track A detail machinery for seams, stitches, buttons, prints.++### 5.9 Optional generative-assist mode (documented escape hatch)++Modern image-to-3D generators (TRELLIS, Tripo, Hunyuan3D, Rodin, TripoSR) reach roughly 80-95 percent front-face shape accuracy and the most photoreal textures via Gaussian-splat/LRM methods (section 13). Pure procedural code cannot match that for a real human.++- Offer an explicit, opt-in `generativeAssist` mode: import a base mesh produced by an external image-to-3D model, then use img2threejs to retopologize expectations, rig, apply the projection-first texture/material pipeline, and run the same review gates.+- This breaks the "code-only, no downloaded assets" promise, so it must be clearly flagged in the spec (`meshSource: procedural | generative-assist`) and in the output, and never the silent default.+- Even in this mode, the likeness gains still come mostly from de-lighting, projection, and camera match layered on top.++### 5.10 Honesty about 100 percent++State plainly in outputs: a single image cannot yield a guaranteed 100 percent likeness because back/sides, occluded geometry, and true skin/hair microstructure are not observable. The pipeline maximizes likeness through parametric fit + photo projection + de-lighting + camera match, reports per-region confidence, and requests additional views when the target is a real person and fidelity matters.++---++## 6. Cross-cutting: feedback loop upgrades++- `make_visual_comparison_sheet.py`: optional overlay mode (landmark lines for characters; region boxes for detail review).+- Reviews record per-detail and per-landmark scores, not only the five existing layer scores.+- Keep one packaged sheet per review to preserve token efficiency.++## 7. File-by-file change summary++New files:+- `references/detail-inventory.md`+- `references/character-reconstruction.md`+- `references/likeness-maximization.md` (projection-first pipeline: template fit, photo projection, de-lighting, camera match, turnaround)+- `scripts/build_detail_inventory.py`+- `scripts/extract_reference_landmarks.py`+- `scripts/solve_reference_camera.py` (estimate focal/FOV/orientation; emit `referenceCamera` block)+- `scripts/bake_projected_texture.py` (project the de-lit reference onto the fitted mesh view and bake to UV; stdlib PNG)+- `scripts/delight_reference.py` (recover neutral albedo from the photo before projection)+- a code-generated parametric humanoid/face template module (head-unit body + morphable face), inline in the generator or as `assets/humanoid_template` data+- demo assets for one detailed object close-up and one high-likeness character (projection-based)++Modified files:+- `references/pre-spec-assessment.md` (detail inventory + domain + anatomy)+- `references/procedural-patterns.md` (character recipes + detail recipes)+- `references/validation-rubric.md` (character suitability branch)+- `references/material-lighting-realism.md` (skin/hair/cloth notes)+- `references/browser-screenshot-feedback.md` (detail close-up + landmark overlay review)+- `references/self-correction-loop.md` (character sub-pass guidance)+- `scripts/new_pre_spec_assessment.py`+- `scripts/new_sculpt_spec.py`+- `scripts/validate_sculpt_spec.py`+- `scripts/generate_threejs_factory.py`+- `scripts/visual_feature_gate.py`+- `scripts/sculpt_pass_orchestrator.py` (register proportion-lock / feature-placement passes for character domain)+- `scripts/probe_reference_image.py` (hint detail-scan when complexity high)+- `scripts/tests/test_pipeline.py` (new coverage)+- `SKILL.md`, `README.md` (document both tracks, bump version)++## 8. Phased roadmap++| Phase | Version | Content | Acceptance |+| --- | --- | --- | --- |+| P1 | 1.1.0 | detail-inventory reference + build script + assessment/spec fields | loot-chest assessment enumerates linked details; strict gate blocks empty/unlinked inventory |+| P2 | 1.1.0 | detail close-up review + validation gate + tests | close-up sheet proves bevel/fastener/stain; tests green; 1.0 specs still valid |+| P3 | 1.2.0 | character reference + rubric branch + domain/anatomy in assessment | human image -> character-stylized + anatomy block |+| P4 | 1.2.0 | character spec template + landmark script + humanoid generator | test character at correct head-units + pose + landmarks |+| P5 | 1.2.0 | character feature gates + proportion-lock/feature-placement passes | face/proportion/pose scored; one case passes stylized bar |+| P6 | 1.3.0 | likeness-max: `solve_reference_camera.py` + `delight_reference.py` + `bake_projected_texture.py` + parametric template fit | render camera-matches the photo; de-lit reference projected onto the fitted mesh; front-face likeness visibly higher than stylized baseline |+| P7 | 1.3.0 | optional `generativeAssist` mode (flagged, non-default) + confidence reporting for unseen regions | import-and-refine path works end-to-end and is clearly labelled non-procedural |+| P8 | 1.3.0 | docs + demos + version bump | SKILL.md/README updated, high-likeness character demo, no emoji |++## 9. Testing strategy++- Extend `scripts/tests/test_pipeline.py`: detail-inventory validation (pass/fail cases), domain detection, anatomy validation, character feature-gate thresholds, backward-compat (a 1.0 object spec still validates).+- End-to-end smoke: rebuild the loot-chest with the detail gate on; reconstruct one stylized character end-to-end.++## 10. Backward compatibility++- All new blocks are optional at the schema level; strict-quality only enforces them when `detailInventory` exists or complexity >= moderate (Track A) or `primaryDomain != object` (Track B).+- Existing object specs and the current loot-chest demo must continue to pass.++## 11. Risks and mitigations++- Photoreal humans are infeasible procedurally: scope locked to stylized/figurine; state this in outputs and request more views when needed.+- Over-strict gates could block simple objects: gate strength scales with complexity/domain; simple objects keep the light path.+- Single image lacks hidden faces/pose ambiguity: use `request-input` to ask for front/side/full-body views before committing.+- Token cost creep from more analysis: keep one packaged sheet per review; scripts do the enumeration scaffolding, the model only judges.++## 12. Open questions++- Default `targetMinDetails` per tier - tune after the first detailed run.+- Hair strategy default: hair cards vs tube-along-curve per lock (perf vs look).+- Whether to ship a small parametric humanoid template file or generate it inline in the factory.+- How far to build camera-solve and de-lighting in pure stdlib vs documenting an optional external step; both may need a pragmatic approximation first.+- Whether `generativeAssist` should call an external API at all, or only accept a user-supplied base mesh (keeps the skill offline and asset-free by default).++## 13. Research summary: best practices for maximum human likeness++Findings from web research (July 2026), used to shape sections 5.8 to 5.10.++1. Parametric templates plus landmark fitting are the standard for likeness. SMPL-X is a unified body-plus-hands-plus-face model (10,475 vertices, 54 joints including jaw and eyes) using linear blend skinning with corrective blendshapes; it embeds MANO (hands) and FLAME (face, learned from ~3,800 head scans). SMPLify-X fits it to a single image by optimizing pose, shape, and expression to match observed 2D landmarks - the de facto initialization for single-image human recovery. Takeaway: fit a parametric template to image landmarks instead of hand-sculpting.++2. Photo texture projection is the biggest single-image likeness lever. Projective/camera-projection texturing maps the reference image onto the mesh as if projected from the solved camera; the Three.js `three-projected-material` library and custom `ShaderMaterial` approaches implement this, including "snapshotting" the projection then baking it. Texture-projection modules that encode high-frequency detail from sparse views are how recent human-texture methods (for example TexDreamer) achieve fidelity.++3. De-lighting is mandatory before using a photo as albedo. An albedo map must be free of baked shadows, highlights, and AO; tools like Substance 3D Sampler Delight, Agisoft Delighter, Unity de-lighting, and AI delighters exist precisely for this, and a manual high-pass/overlay neutralization is the common fallback. Skipping this makes projected texture fight scene lighting.++4. Orthographic turnaround workflow drives proportion accuracy. Artists model from front/side/back references at matched height, using a head-unit proportion grid and silhouette-first blockout, with a color palette captured alongside; consistent lines across views let the model match features. Adopt reference planes plus proportion grid; request missing views.++5. Morph targets / blend shapes plus SkinnedMesh are the Three.js primitives for faces and bodies; predictable (retopologized) topology is required for clean blendshape deformation, and LOD (3-4 levels) manages performance. Three.js ships a morph-targets face example.++6. Generative image-to-3D (2026) sets the realistic likeness ceiling for a real person: TRELLIS (top open-source quality, Gaussian-splat textures), Tripo (Tripo P1 reconstructs facial features accurately with sharp textures), Hunyuan3D (strong open-source), Rodin (high-fidelity geometry), TripoSR/Stable Fast 3D (sub-second, lower fidelity). Reported ~80-95 percent front-face shape accuracy. This is ML, not procedural, hence the optional flagged `generativeAssist` mode; the procedural path still layers projection + de-lighting + camera match for likeness.++Sources:+- [Expressive Body Capture: SMPL-X / SMPLify-X (arXiv 1904.05866)](https://arxiv.org/pdf/1904.05866)+- [SMPLify-X overview (EmergentMind)](https://www.emergentmind.com/topics/smplify-x)+- [Playing with Texture Projection in Three.js (Codrops)](https://tympanus.net/codrops/2020/01/07/playing-with-texture-projection-in-three-js/)+- [three-projected-material (GitHub)](https://github.com/marcofugaro/three-projected-material)+- [three.js morph targets - face example](https://threejs.org/examples/webgl_morphtargets_face.html)+- [TexDreamer: high-fidelity 3D human texture (arXiv 2403.12906)](https://arxiv.org/pdf/2403.12906)+- [Delight AI - Adobe Substance 3D Sampler](https://helpx.adobe.com/substance-3d-sampler/filters/tools/delight-ai-powered.html)+- [De-Lighting 3D Scans (Sketchfab community)](https://sketchfab.com/blogs/community/de-lighting-3d-scans-in-unity-by-pete-mcnally/)+- [Character Turnaround Guide (spines.com)](https://spines.com/character-turnaround/)+- [How to Create a 3D Character Model Reference (Coohom)](https://www.coohom.com/article/how-to-create-a-3d-character-model-reference)+- [Best AI 3D Model Generators 2026 (TRELLIS vs Meshy vs Tripo vs Hitem3D)](https://trellis2.app/blog/best-ai-3d-model-generator)+- [7 Image-to-3D AI Generators, July 2026 (Vitalify)](https://www.vitalify.asia/en/blog/generative-ai/ai-image-to-3d-generators-comparison)+- [How To Deploy Image-To-3D Models In Three.js (Threedium)](https://threedium.io/create/3d-models/platform/threejs)diff --git a/references/character-reconstruction.md b/references/character-reconstruction.mdnew file mode 100644index 0000000..c6be73a--- /dev/null+++ b/references/character-reconstruction.md@@ -0,0 +1,63 @@+# Character Reconstruction++Use this reference when `objectClass.primaryDomain` is `character` or `hybrid`. It replaces guesswork proportions with a measured system so a generated humanoid actually resembles the reference pose and build.++## Proportion System (head-units)++Measure everything in head-units (HU): total body height divided by head height. Pick the style axis from the image, do not assume realistic by default:++- realistic: ~7.5 HU (adult human)+- stylized / anime-adjacent: ~5-6 HU+- chibi / figurine: ~2-3 HU++Record measured ratios, not assumed ones:++- `headUnit`: head height as a fraction of total image height+- `torso`: crown-to-hip distance in HU+- `legs`: hip-to-floor distance in HU+- `shoulderWidth`: in HU (roughly 1.5-2 HU realistic, wider for stylized heroic builds)+- `hipWidth`: in HU++If the image crops the legs or feet, mark `legs` and `hipWidth` as inferred and lower confidence rather than guessing a stock adult ratio.++## Facial Landmark Layout++Store landmarks as normalized coordinates (0-1) relative to head bounding box, not the full image, so they survive scale changes:++- `hairline`: ~0.0-0.15 from crown depending on hairstyle bulk+- `eyeLine`: ~0.45-0.55 (near vertical mid-head; lower for chibi, higher forehead for stylized)+- `eyeSpacing`: horizontal gap between inner eye corners, ~0.2-0.35 of head width (wider spacing reads as more stylized/cute)+- `noseBase`: ~0.6-0.7+- `mouthLine`: ~0.75-0.85+- `earTop` / `earBottom`: roughly bracket `eyeLine` to `noseBase`++Pull these from the actual image via `scripts/extract_reference_landmarks.py` overlay, not from a generic face chart. A stylized face with huge eyes will violate realistic ratios on purpose — match what is observed.++## Pose / Skeleton++Define joints as a minimal skeleton, matched to the reference silhouette and limb angles, not a default T-pose:++- root -> neck -> head+- neck -> left/right shoulder -> elbow -> wrist+- root -> left/right hip -> knee -> ankle++For each joint record an approximate angle (degrees, relative to rest pose) read off the silhouette. Prioritize matching:++1. overall stance (weight distribution, contrapposto vs symmetric)+2. limb angles at shoulders/hips (these dominate perceived pose match)+3. hand/foot orientation only if clearly visible++If a joint is occluded, do not invent an angle — mark `confidence` low and default to a neutral rest angle for that joint only.++## Character Materials (stylized default)++Reuse Track A detail machinery (`references/detail-inventory.md`) for accessories and trims. Base recipes:++- **Skin**: warm base albedo sampled from the image, low-to-mid roughness, no true subsurface scattering — approximate with a soft rim/backlight term and a slightly desaturated shadow tint. Avoid `MeshPhysicalMaterial.transmission` unless the reference clearly shows translucency (ears, fingers backlit).+- **Hair**: the single most common failure point for single-image reconstruction. Do NOT attempt strand-level geometry from one photo. Prefer stylized clumps — hair cards or short tube-along-curve locks grouped into 5-15 major masses matching the silhouette's hair shape, layered front-to-back with alpha or hard edges. Match the read silhouette (fringe, part line, volume) over any attempt at individual strands.+- **Eyes**: a glossy sphere (high specular, low roughness) plus a separate iris disc/decal with darker outline and a small bright catchlight quad or emissive dot offset toward the key light direction. The catchlight is disproportionately important for "looks alive."+- **Cloth**: extrude or plane panels following the silhouette's fold lines; add normal-map or geometry creasing at obvious fold zones (elbow, waist cinch, knee) rather than a flat plane. Local material overrides handle prints, seams, buttons via the Track A detail inventory.++## Gate Notes++Proportion and landmark values feed `anatomy` block validation (section 5.3/5.6 of the upgrade plan) — every measured value needs an `evidenceRef` back to the source image region, same discipline as object detail inventory.diff --git a/references/detail-inventory.md b/references/detail-inventory.mdnew file mode 100644index 0000000..de2f800--- /dev/null+++ b/references/detail-inventory.md@@ -0,0 +1,131 @@+# Detail Inventory++Use this reference during analysis, before the spec is authored. It exists because small+identity-defining marks (a bevel highlight, a row of rivets, a stain) get skipped when the+agent only eyeballs the whole image once. Scan zone by zone and record every mark as a+structured `detail`, not as prose.++## The Rule++Every `detail` entry records: where (`region`, normalized), what changes (`kind` + `affects`),+how strong (`scale`, intensity implied by the recipe below), evidence region (`evidenceRef`),+and confidence. It MUST set `mapsTo` a real `component.localFeatures[]` entry or+`material.localOverrides[]` entry. A detail described only in prose is a gate failure - if it+does not map to a field the generator reads, it will not reach the render.++## Taxonomy - kind to graphics terms++### gloss (do bong)+Localized low-roughness zone or specular hotspot, not a global material change.+- `material.localOverrides`: `roughness` low value (0.05-0.2) over the region, or+ `clearcoat` + `clearcoatRoughness` on `MeshPhysicalMaterial` for a lacquer/wet look.+- Streaked highlights (brushed metal, hair) -> `anisotropy` + `anisotropyRotation`.+- Record hotspot position relative to the key light direction; a gloss detail with no+ matching light direction will not render visibly.++### bevel (bo goc)+Edge treatment, not a texture trick - light catches a real chamfer.+- `component.localFeatures` geometry effect: `edgeTreatment.type = chamfer`,+ `bevelRadius` (object-relative, e.g. 0.02-0.08), `segments` (2-4 for a soft rim, 1 for hard).+- Note whether it reads as a bright rim highlight under grazing light; if the reference+ shows a crisp bright line along an edge, the bevel must be real geometry, not a normal map.++### fastener (screw / rivet / bolt)+Repeated small parts - always an instanced system, never one-off meshes.+- `InstancedMesh`, `count`, spacing/distribution (linear, radial, grid), head shape+ (hemisphere, flat, hex), recess (raised vs countersunk), material (usually metal, low+ roughness at the head crown).+- Confidence should reflect whether every instance is visible or only a legible subset+ (partial rows behind occlusion still count if spacing is inferable).++### linework (engraving / painted line / panel-line)+Three distinct techniques - pick the one the evidence supports, they read differently:+- Engraved groove: geometry effect, a recessed `groove` (see below) following a path;+ catches shadow, no geometry it will look flat under any light.+- Painted line / decal: `material.localOverrides` with a canvas-texture decal region;+ color contrast only, no relief.+- Panel-line: dark AO seam - a thin `localOverride` darkening roughness/AO along a seam+ without true depth; use when the reference shows a soft dark line, not a hard groove.+- State a legibility target: line must remain readable at the review's grazing-light shot.++### contour (edge outline / toon rim)+Stylized outline, usually a rim-light or a backface-outline technique.+- `material.localOverrides` or a dedicated outline pass (inverted-hull or shader rim).+- Record which silhouette edges carry it; partial outlines (only the top edge) are common.++### seam+Construction line where two surfaces meet (molded parts, fabric panels, armor plates).+- Geometry effect: a thin recessed `groove` or a raised `ridge` (whichever the reference+ shows) plus a slightly darker AO localOverride in the crevice.++### stitch (fabric stitch)+- `component.localFeatures`: small repeated bumps or a dashed groove along a seam path;+ usually paired with a `linework: painted line` for the thread color contrast.+- Instance or repeat along a curve like a fastener row, but finer spacing.++### stain (dirt / patina / discolour / faded)+Always a `material.localOverrides` region, described with these sub-fields:+- `dirtAmount`: 0-1, how much darker/desaturated.+- `cavityBias`: whether it concentrates in crevices/cavities (usually yes for dirt/grime).+- `streak`: vertical/directional streaking flag + direction (gravity-fed dirt runs down).+- `patinaColor`: hex or named hue shift for oxidation/verdigris/rust bloom.+- `fadedMask`: a lighter, desaturated region for sun-bleaching - opposite of dirt, still a+ localOverride.+- `region`: where on the object, tied to `evidenceRef`.++### scratch+Thin localized roughness/normal perturbation, optionally exposing an underlayer color.+- `material.localOverrides`: scratch cluster with orientation (usually radial or directional+ from handling), width, and whether it exposes a different base color underneath.++### chip+Small area of missing surface material, usually at an edge or corner.+- Geometry effect if it changes silhouette (a notch); otherwise a localOverride exposing+ an underlayer color/roughness at a corner/edge component.++### decal+Printed/applied graphic or label, flat against the surface.+- `material.localOverrides` with a canvas-texture region; record placement, approximate+ size, and rotation. Decals do not add geometry unless they have physical thickness+ (a sticker edge) - if so, add a thin raised `component.localFeatures` plate.++### emissive+Self-lit region (LED, glow, screen, ember).+- `material.localOverrides`: `emissive` color + `emissiveIntensity`, and whether it should+ bloom under the renderer's tone mapping. Record whether it is constant or should read as+ a light source affecting nearby surfaces (may need a matching point/area light).++### hole+Actual opening or socket, changes silhouette/topology.+- `component.localFeatures` geometry effect: a real cut or socket, not a dark texture patch.+ Record depth and whether the interior needs its own material (visible cavity).++### groove+Recessed linear or curved channel.+- Geometry effect: negative relief along a path, width/depth object-relative, plus AO+ darkening in the channel. Shares mechanics with engraved linework and seams.++### ridge+Raised linear or curved feature, the geometric inverse of a groove.+- Geometry effect: positive relief along a path, width/height object-relative, catches+ highlight along its top edge (pair with a gloss or bevel note if the reference shows a+ highlight line on the ridge crest).++## Scan Method++Pick one and record it as `scanMethod`:+- `component-zones`: walk each planned component's bounding region; best when component+ boundaries are already known.+- `grid-3x3` / `grid-4x4`: divide the image into a uniform grid and inspect every cell;+ use when components are not yet decided or the object has no obvious part boundaries.++Set `targetMinDetails` from complexity tier: simple 3, moderate 6, complex 10, ultra 16+(starting values, tune after runs). Scanning zone by zone against a minimum count is what+prevents a single-glance miss of small marks.++## Confidence++Score 0-1 per detail. Lower confidence for: partially occluded regions, marks inferred by+symmetry rather than seen, or ambiguous kind classification (e.g. scratch vs. panel-line).+Do not inflate confidence to pad `targetMinDetails` - an unlinked or low-confidence detail+that fails the `mapsTo` check still blocks the gate.diff --git a/references/likeness-maximization.md b/references/likeness-maximization.mdnew file mode 100644index 0000000..d5e2a5f--- /dev/null+++ b/references/likeness-maximization.md@@ -0,0 +1,74 @@+# Likeness Maximization (Projection-First Pipeline)++Use this reference when the goal is maximum resemblance to a specific person or character in a single reference image, not a generic stylized character. This is the default high-likeness path for the `character` domain; `character-reconstruction.md` covers the fallback stylized/freehand path when the input is weak or the user accepts approximation.++Read section 5.8-5.10 of `docs/UPGRADE_PLAN.md` for the full spec this reference implements.++## Why Freehand Sculpting Cannot Reach High Likeness++Hand-authored primitives (capsules, spheres, blend shapes tuned by eye) can approximate proportions but cannot reproduce the exact geometry and surface information encoded in a photo. The two levers that actually move likeness are: (1) getting the mesh's shape and camera to align precisely with the photo, and (2) putting the photo's own pixels onto that mesh as texture. Everything else is secondary.++## Pipeline++### (a) Fit a parametric template to landmarks++Ship a lightweight, code-generated parametric humanoid/face template — a head-unit-parameterized body plus a morphable face, conceptually mirroring SMPL-X (body + hands + face, jaw/eye joints, linear blend skinning with corrective blendshapes) and FLAME (face-from-scans). This stays procedural: the template is code-generated and parameter-driven, never a downloaded art asset.++Fit template parameters (shape, pose, expression) by minimizing reprojection error between template landmarks and the observed 2D landmarks from `extract_reference_landmarks.py` — the SMPLify-X idea. Do not hand-place vertices; solve for parameters that make the template's projected landmarks match the image landmarks.++### (b) Camera match++Estimate and store focal length, FOV, and orientation for the reference photo (`scripts/solve_reference_camera.py`, emits a `referenceCamera` spec block). The render camera must match this so:++- the review screenshot can be pixel-overlaid against the source photo+- the texture projection in step (d) lands correctly++Without a matched camera, projected texture will misalign the moment the model is viewed from any angle other than the accidental one it was authored at.++### (c) De-light before treating the photo as albedo++A raw photo bakes in shadows, highlights, and ambient occlusion from whatever light was present when it was taken. Using it directly as albedo means the projected texture fights the new scene's lights. Run a de-lighting pass (`scripts/delight_reference.py`) — high-pass/overlay neutralization at minimum, an AI delighter equivalent if available — to recover a neutral base color, then derive roughness/normal/AO independently. Treat "album must be free of baked lighting" as a hard requirement, not a nice-to-have.++### (d) Project and bake++Solve projective/camera-projection texturing from the matched camera (Three.js `ShaderMaterial`, or the `three-projected-material` approach) to map the de-lit reference onto the fitted mesh, then bake the result into the mesh's UVs (`scripts/bake_projected_texture.py`, stdlib PNG) for the visible (front) side.++### (e) Infer unseen regions, flag confidence++Back/sides are not observed. Options, in order of preference:++1. request an additional view (`request-input`: front/side/back) — always try this first for a real person+2. mirror the front texture across the body's symmetry plane where anatomically valid (works reasonably for faces, poorly for asymmetric hair/clothing)+3. palette-continue from the nearest observed edge as a last resort++Every inferred region gets its own confidence score and a note of which strategy produced it. Never silently present an inferred back as if it were observed.++### (f) Rig for deformation++Emit a `SkinnedMesh` with a joint skeleton for the body plus morph targets/blend shapes for facial expression, exportable as glTF. Keep topology predictable (retopologized, evenly quaded around the face) so blendshapes deform cleanly. Expose skeleton and morph channels through `root.userData.sculptRuntime`.++## Part-Specific Notes (stylized-to-realistic dial)++Same recipes as `character-reconstruction.md`, dialed toward realism: skin keeps the warm-base/soft-roughness/rim-light approximation (true SSS is out of scope); hair still prefers stylized clumps over strand geometry — a single image cannot supply real hair microstructure, so do not oversell hair likeness; eyes get the glossy-sphere-plus-iris-decal treatment with a correct catchlight, which reads as more "alive" than raw geometric accuracy.++## Honesty Note++State plainly, every time this pipeline runs: a single image cannot yield a guaranteed 100 percent likeness. Back/sides, occluded geometry, and true skin/hair microstructure are not observable from one photo. This pipeline maximizes likeness through parametric fit + photo projection + de-lighting + camera match, reports per-region confidence, and requests additional views whenever the subject is a real person and fidelity matters. Never claim "100 percent match" as an output — report confidence per region instead.++An optional, explicitly-flagged `generativeAssist` mode (importing an external image-to-3D base mesh, e.g. TRELLIS/Tripo/Hunyuan3D/Rodin) sets the realistic ceiling higher (~80-95 percent front-face shape accuracy per current generators) but is non-procedural and never the silent default — see UPGRADE_PLAN.md section 5.9.++## Sources++- [Expressive Body Capture: SMPL-X / SMPLify-X (arXiv 1904.05866)](https://arxiv.org/pdf/1904.05866)+- [SMPLify-X overview (EmergentMind)](https://www.emergentmind.com/topics/smplify-x)+- [Playing with Texture Projection in Three.js (Codrops)](https://tympanus.net/codrops/2020/01/07/playing-with-texture-projection-in-three-js/)+- [three-projected-material (GitHub)](https://github.com/marcofugaro/three-projected-material)+- [three.js morph targets - face example](https://threejs.org/examples/webgl_morphtargets_face.html)+- [TexDreamer: high-fidelity 3D human texture (arXiv 2403.12906)](https://arxiv.org/pdf/2403.12906)+- [Delight AI - Adobe Substance 3D Sampler](https://helpx.adobe.com/substance-3d-sampler/filters/tools/delight-ai-powered.html)+- [De-Lighting 3D Scans (Sketchfab community)](https://sketchfab.com/blogs/community/de-lighting-3d-scans-in-unity-by-pete-mcnally/)+- [Character Turnaround Guide (spines.com)](https://spines.com/character-turnaround/)+- [How to Create a 3D Character Model Reference (Coohom)](https://www.coohom.com/article/how-to-create-a-3d-character-model-reference)+- [Best AI 3D Model Generators 2026 (TRELLIS vs Meshy vs Tripo vs Hitem3D)](https://trellis2.app/blog/best-ai-3d-model-generator)+- [7 Image-to-3D AI Generators, July 2026 (Vitalify)](https://www.vitalify.asia/en/blog/generative-ai/ai-image-to-3d-generators-comparison)+- [How To Deploy Image-To-3D Models In Three.js (Threedium)](https://threedium.io/create/3d-models/platform/threejs)diff --git a/references/procedural-patterns.md b/references/procedural-patterns.mdindex 9c72915..2a453a8 100644--- a/references/procedural-patterns.md+++ b/references/procedural-patterns.md@@ -59,6 +59,55 @@ Use `component.localFeatures` for details that matter to recognizability:Each feature should include placement, approximate size, orientation, material effect, geometry effect, and confidence.+## Detail Recipes++Concrete Three.js material/geometry approach per `detailInventory` kind. Cross-reference+`references/detail-inventory.md` for the full taxonomy and the evidence/mapping rule.++- gloss: `MeshPhysicalMaterial` with a low-`roughness` localOverride (0.05-0.2) sized to the+ hotspot region; use `clearcoat`/`clearcoatRoughness` for a lacquer layer over a rougher+ base, `anisotropy`/`anisotropyRotation` for brushed/streaked highlights.+- bevel: real geometry, not a normal map - `edgeTreatment.type = chamfer`, `bevelRadius`+ object-relative (0.02-0.08), `segments` 2-4 for a soft catch-light rim, 1 for a hard edge.+- fastener: `InstancedMesh` for the repeated part; `count` + spacing pattern (linear, radial,+ grid) + head shape (hemisphere/flat/hex) + recess (raised vs countersunk); low-roughness+ metal material on the head crown.+- linework: pick engraved groove (real recessed geometry along a path, catches shadow),+ painted line/decal (canvas-texture localOverride, color contrast only, no relief), or+ panel-line (thin dark AO/roughness localOverride along a seam, no depth) - match whichever+ the reference evidence shows; do not default to decal for something that casts a shadow.+- stain: `material.localOverrides` region with `dirtAmount`, `cavityBias` (concentrate in+ crevices), `streak` (directional, usually gravity-down), `patinaColor` for oxidation hue+ shift, or a `fadedMask` (lighter, desaturated) for sun-bleaching - the inverse of dirt.++## Character Geometry And Material Recipes++Use these when `objectClass.primaryDomain` is `character` or `hybrid`. Pair with+`references/character-reconstruction.md` for proportion/landmark data.++- head: sphere or ellipsoid scaled to the measured head-unit, then displaced/tapered toward+ the reference face shape (jaw width, chin point, cheek fullness) rather than left spherical.+- limbs: capsule or tapered cylinder per segment (upper arm, forearm, thigh, shin); taper+ ratio and length come from `anatomy.proportions`; capsules keep joints visually continuous.+- hands: simplified capsule-cluster (palm block + finger capsules) at low segment count;+ do not attempt per-knuckle detail unless the reference is close-up and complexity is ultra.+- hair: hair cards (alpha-mapped planes layered in clumps) for stylized/low-complexity, or a+ tube-along-curve per lock for wavy/flowing hair with visible strand structure; prefer cards+ by default - hair is the classic single-image failure mode, so favor legible clumps over+ many thin strands that swim or alias.+- face feature placement: position eyes, brows, nose, mouth using `anatomy.faceLandmarks`+ normalized coordinates (eyeLine, eyeSpacing, noseBase, mouthLine, hairline); never eyeball+ placement freehand once landmarks exist.+- eyes: glossy sphere (low roughness, slight clearcoat) plus an iris decal/texture; a correct+ catchlight (small bright localOverride matching the key light) sells more realism than+ extra geometry.+- clothing: extrude or plane panels per garment piece, with fold normals (a normal-map or+ displacement pattern following expected gravity/pose creases) rather than a flat shell;+ reuse Track A detail machinery (seam, stitch, decal, stain) for prints, buttons, wear.+- skin: approximate subsurface scattering, not true SSS - warm base albedo, soft/lower+ roughness variation (skin is not uniformly matte), and a rim or backlight to fake light+ passing through thin tissue (ears, nose edge). Avoid pure-Lambertian flat skin.+## Verification CuesA procedural object is usually failing when:diff --git a/references/validation-rubric.md b/references/validation-rubric.mdindex ab63f56..d8649b5 100644--- a/references/validation-rubric.md+++ b/references/validation-rubric.md@@ -25,7 +25,21 @@ Use this reference when the suitability decision is unclear.- 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+- object relies primarily on smoke, liquid, glass caustics, or lace (no reconstruction path exists for these)++## Character / Human Suitability++Do not blanket-reject a subject for being hair- or cloth-fold-dominant. If the form language is character-like (humanoid silhouette, skin/cloth/hair materials), classify it `character-conditional -> stylized` instead of `reject`. Route through `references/character-reconstruction.md` (proportions, landmarks, pose, stylized materials) by default.++- **character-conditional -> stylized**: humanoid subject, at least one clear frontal view, pose readable, hair/cloth is present but the user accepts the stylized-clump/fold-normal treatment rather than photoreal strands or drape simulation. Proceed with the standard character pipeline.+- **character-conditional -> maximum likeness**: user explicitly wants the closest possible match to a specific person/character. Confirm this intent before starting, then route through `references/likeness-maximization.md` (projection-first: template fit, camera match, de-lighting, texture projection). State up front that a single image cannot guarantee 100 percent likeness; report per-region confidence instead of claiming an exact match.+- **still reject**: no humanoid silhouette is discernible at all, the figure is fully occluded/cropped below usable proportions, or the request demands photoreal skin/hair microstructure from a single low-resolution image with no willingness to provide more views or accept stylization.++Before committing to a character spec:++- confirm which stylization level the user accepts (realistic ~7.5 heads / stylized 5-6 / chibi 2-3) — do not assume realistic by default+- request front, side, and back (or full-body) views whenever the visible view cannot support pose, proportion, or back-of-head/body inference+- if maximum likeness is requested but only one low-quality view is available, say so explicitly and offer the stylized fallback as the practical alternative## Ask For Better Inputdiff --git a/scripts/bake_projected_texture.py b/scripts/bake_projected_texture.pynew file mode 100755index 0000000..ecabcef--- /dev/null+++ b/scripts/bake_projected_texture.py@@ -0,0 +1,163 @@+#!/usr/bin/env python3+"""Emit a projection/UV-bake descriptor for photo-projected texturing.++This script does not perform GPU projective texturing and it does not+rasterize or bake any pixels. Actual camera-space projection of the+(ideally de-lit) reference image onto the fitted mesh, and the bake of that+projection into the mesh's UV space, is a Three.js runtime operation (a+projective ShaderMaterial, e.g. the `three-projected-material` technique).+What this script produces is the plan: a validated, versioned descriptor+that records which camera, which source image(s), which mesh, and which+projection settings the Three.js generator/agent should use to actually run+that bake, plus the back/side inference strategy for regions the camera+never saw.+"""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path+from typing import Any+++VALID_PROJECTION_MODES = ("perspective-camera-projection", "orthographic-front-projection", "triplanar-fallback")+VALID_UNSEEN_STRATEGIES = ("mirror-symmetry", "palette-continue", "request-additional-view", "leave-unprojected")+++def clamp01(value: float) -> float:+ return max(0.0, min(1.0, value))+++def load_camera(camera_arg: str | None) -> tuple[dict[str, Any] | None, list[str]]:+ warnings: list[str] = []+ if not camera_arg:+ warnings.append("no --camera reference supplied; projection will use an identity/front camera assumption")+ return None, warnings+ path = Path(camera_arg).expanduser()+ if not path.exists():+ warnings.append(f"--camera path {camera_arg!r} does not exist; recording it as an opaque reference id instead")+ return {"reference": camera_arg}, warnings+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except Exception as exc:+ warnings.append(f"could not parse --camera JSON at {path}: {exc}; recording it as an opaque reference id")+ return {"reference": camera_arg}, warnings+ camera = data.get("referenceCamera", data) if isinstance(data, dict) else None+ if not isinstance(camera, dict):+ warnings.append(f"--camera JSON at {path} did not contain a referenceCamera object")+ return {"reference": camera_arg}, warnings+ return camera, warnings+++def build_descriptor(args: argparse.Namespace) -> dict[str, Any]:+ camera, camera_warnings = load_camera(args.camera)+ warnings = list(camera_warnings)++ source_images: dict[str, str] = {"reference": str(Path(args.reference_image).expanduser())}+ if args.delit_image:+ source_images["delit"] = str(Path(args.delit_image).expanduser())+ else:+ warnings.append(+ "no --delit-image supplied; projecting the raw reference will bake its lighting into the mesh "+ "unless the runtime applies its own de-lighting pass first"+ )++ unseen_strategy = args.unseen_strategy+ unseen_confidence = {+ "mirror-symmetry": 0.45,+ "palette-continue": 0.3,+ "request-additional-view": 0.0,+ "leave-unprojected": 0.0,+ }[unseen_strategy]++ bake_steps = [+ "load the fitted mesh identified by targetMeshId and its UV layout",+ "load sourceImages.delit if present, otherwise sourceImages.reference, as the projection source texture",+ "construct a projection camera in the Three.js scene from the camera block (fovDegrees, aspect, orientation, position)",+ f"apply {args.projection_mode} to project the source texture onto mesh surfaces facing the projection camera within tolerance",+ f"for surfaces outside the camera's view frustum or facing away, apply the '{unseen_strategy}' strategy",+ f"rasterize the resulting camera-space projection into a {args.texture_size}x{args.texture_size} UV-space texture",+ "flag any UV texels that received no projected sample (fully unseen regions) in the bake output metadata",+ "hand the baked texture back to the material pipeline as the projected albedo input",+ ]++ return {+ "projectedTextureBake": {+ "version": "1.0",+ "generator": "bake_projected_texture.py",+ "status": "descriptor-only; no pixels are baked or rasterized by this script",+ "targetMeshId": args.mesh_id,+ "projectionMode": args.projection_mode,+ "textureSize": args.texture_size,+ "camera": camera,+ "sourceImages": source_images,+ "unseenRegionStrategy": {+ "mode": unseen_strategy,+ "confidence": unseen_confidence,+ "note": "Regions the reference camera never saw (back, occluded folds, underside) are inferred, not observed.",+ },+ "runtimeApproach": (+ "actual projective texturing and UV bake happen in the Three.js runtime via a projective "+ "ShaderMaterial (the three-projected-material approach) or an equivalent camera-space "+ "projection shader; this descriptor only records the plan for that step"+ ),+ "bakeSteps": bake_steps,+ "limitations": [+ "this script performs no image sampling, projection math, or UV rasterization",+ "camera accuracy is inherited from whatever produced the camera block; an unrefined camera will misalign the projection",+ "unseen-region inference is a heuristic guess, not observed geometry or texture",+ "the resulting bake still needs a rendered overlay review against the reference image before being trusted",+ ]+ + warnings,+ "note": (+ "Feed this descriptor to the Three.js generator/agent to run the actual projection and bake, "+ "then re-render and visually compare the baked mesh against the reference image before "+ "accepting the result as final."+ ),+ }+ }+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--reference-image", required=True, help="Path to the original reference photo")+ parser.add_argument("--delit-image", help="Path to a de-lit albedo produced by delight_reference.py, if available")+ parser.add_argument("--camera", help="Path to a referenceCamera JSON produced by solve_reference_camera.py")+ parser.add_argument("--mesh-id", required=True, help="Identifier of the target mesh/node to project onto")+ parser.add_argument(+ "--projection-mode",+ choices=VALID_PROJECTION_MODES,+ default="perspective-camera-projection",+ help="Projection technique the Three.js runtime should use (default perspective-camera-projection)",+ )+ parser.add_argument("--texture-size", type=int, default=1024, help="Target baked texture resolution (square)")+ parser.add_argument(+ "--unseen-strategy",+ choices=VALID_UNSEEN_STRATEGIES,+ default="mirror-symmetry",+ help="How to handle mesh regions outside the reference camera's view (default mirror-symmetry)",+ )+ parser.add_argument("--out", type=Path, help="Write the descriptor JSON to this path")+ args = parser.parse_args(argv)++ if args.texture_size <= 0:+ parser.error("--texture-size must be positive")++ try:+ descriptor = build_descriptor(args)+ text = json.dumps(descriptor, indent=2, ensure_ascii=False)+ if args.out:+ out_path = args.out.expanduser().resolve()+ out_path.parent.mkdir(parents=True, exist_ok=True)+ out_path.write_text(text + "\n", encoding="utf-8")+ print(text)+ return 0+ 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/build_detail_inventory.py b/scripts/build_detail_inventory.pynew file mode 100644index 0000000..02ca54b--- /dev/null+++ b/scripts/build_detail_inventory.py@@ -0,0 +1,336 @@+#!/usr/bin/env python3+"""Slice a reference image into inspection zones and scaffold a detailInventory to fill in.++Scans the reference zone by zone (a uniform grid, or named component regions) so small+identity-defining marks are not missed by a single glance at the whole image. Writes one+crop PNG per zone plus a detailInventory skeleton JSON (see docs/UPGRADE_PLAN.md 4.1 and+references/detail-inventory.md) with one detail stub per zone for the agent to classify,+describe, and link to a component/material field. This script only scaffolds zones and+crops; it does not judge what is in them.+"""++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"++TARGET_MIN_DETAILS = {+ "simple": 3,+ "moderate": 6,+ "complex": 10,+ "ultra-complex": 16,+}++DEFAULT_COMPONENT_ZONES = [+ ("upper", 0.0, 0.0, 1.0, 1.0 / 3),+ ("middle", 0.0, 1.0 / 3, 1.0, 1.0 / 3),+ ("lower", 0.0, 2.0 / 3, 1.0, 1.0 / 3),+]+++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_white(pixel: tuple[int, int, int, int]) -> tuple[int, int, int]:+ red, green, blue, alpha = pixel+ mix = alpha / 255.0+ return (+ round(red * mix + 255 * (1 - mix)),+ round(green * mix + 255 * (1 - mix)),+ round(blue * mix + 255 * (1 - mix)),+ )+++def parse_components(spec: str) -> list[tuple[str, float, float, float, float]]:+ zones: list[tuple[str, float, float, float, float]] = []+ for part in spec.split(";"):+ part = part.strip()+ if not part:+ continue+ name, sep, coords = part.partition(":")+ if not sep:+ raise ValueError(f"malformed --components entry (expected name:x,y,w,h): {part!r}")+ values = [float(v) for v in coords.split(",")]+ if len(values) != 4:+ raise ValueError(f"malformed --components entry (expected 4 normalized values): {part!r}")+ x, y, w, h = values+ zones.append((name.strip(), x, y, w, h))+ if not zones:+ raise ValueError("--components produced no zones")+ return zones+++def build_zones(mode: str, components_spec: str | None) -> list[dict]:+ if mode == "component-zones":+ zones_spec = parse_components(components_spec) if components_spec else DEFAULT_COMPONENT_ZONES+ return [+ {"id": name, "region": {"x": x, "y": y, "width": w, "height": h, "units": "normalized"}}+ for name, x, y, w, h in zones_spec+ ]+ grid = 3 if mode == "grid-3x3" else 4+ step = 1.0 / grid+ zones = []+ for row in range(grid):+ for col in range(grid):+ zones.append(+ {+ "id": f"zone-r{row}c{col}",+ "region": {+ "x": round(col * step, 4),+ "y": round(row * step, 4),+ "width": round(step, 4),+ "height": round(step, 4),+ "units": "normalized",+ },+ }+ )+ return zones+++def make_detail_stub(zone: dict, crop_path: Path) -> dict:+ return {+ "id": zone["id"],+ "kind": "",+ "description": "",+ "region": zone["region"],+ "scale": "",+ "affects": "",+ "mapsTo": {"type": "", "ref": ""},+ "evidenceRef": str(crop_path),+ "confidence": 0.0,+ }+++def build_inventory(+ image: Path,+ mode: str,+ out_dir: Path,+ target_min_details: int,+ components_spec: str | None,+) -> dict:+ width, height, pixels = load_image(image)+ zones = build_zones(mode, components_spec)+ out_dir.mkdir(parents=True, exist_ok=True)+ details = []+ for zone in zones:+ region = zone["region"]+ x0 = round(region["x"] * width)+ y0 = round(region["y"] * height)+ x1 = min(width, x0 + max(1, round(region["width"] * width)))+ y1 = min(height, y0 + max(1, round(region["height"] * height)))+ crop_w = max(1, x1 - x0)+ crop_h = max(1, y1 - y0)+ crop_pixels = []+ for y in range(y0, y0 + crop_h):+ source_y = min(height - 1, y)+ for x in range(x0, x0 + crop_w):+ source_x = min(width - 1, x)+ crop_pixels.append(composite_over_white(pixels[source_y * width + source_x]))+ crop_path = out_dir / f"{zone['id']}.png"+ write_png_rgb(crop_path, crop_w, crop_h, crop_pixels)+ details.append(make_detail_stub(zone, crop_path))+ return {+ "scanMethod": mode,+ "targetMinDetails": target_min_details,+ "details": details,+ }+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("image", type=Path)+ parser.add_argument(+ "--mode",+ choices=["grid-3x3", "grid-4x4", "component-zones"],+ default="grid-3x3",+ help="Zone layout to scan (default: grid-3x3)",+ )+ parser.add_argument(+ "--out-dir",+ type=Path,+ help="Directory to write zone crop PNGs (default: <image-stem>-zones next to the image)",+ )+ parser.add_argument(+ "--out",+ type=Path,+ help="Output detailInventory skeleton JSON path (default: <out-dir>/detail-inventory.json)",+ )+ parser.add_argument(+ "--complexity",+ choices=sorted(TARGET_MIN_DETAILS),+ default="moderate",+ help="Sets targetMinDetails from the complexity tier; overridden by --target-min-details",+ )+ parser.add_argument("--target-min-details", type=int, help="Override targetMinDetails directly")+ parser.add_argument(+ "--components",+ help="component-zones only: 'name:x,y,w,h;name2:x,y,w,h' normalized regions "+ "(default: upper/middle/lower thirds)",+ )+ parser.add_argument("--force", action="store_true", help="Overwrite existing output JSON")+ args = parser.parse_args(argv)++ image = args.image.expanduser().resolve()+ if not image.exists():+ parser.error(f"{image} does not exist")+ out_dir = (args.out_dir or image.with_name(f"{image.stem}-zones")).expanduser().resolve()+ out_path = (args.out or out_dir / "detail-inventory.json").expanduser().resolve()+ if out_path.exists() and not args.force:+ parser.error(f"{out_path} already exists; use --force to overwrite")+ target_min_details = args.target_min_details or TARGET_MIN_DETAILS[args.complexity]++ try:+ inventory = build_inventory(image, args.mode, out_dir, target_min_details, args.components)+ except Exception as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 1++ payload = {+ "sourceImage": str(image),+ "zonesDir": str(out_dir),+ "detailInventory": inventory,+ "authoringInstruction": (+ "Open each zone crop under zonesDir and replace every detail stub's kind, description, "+ "scale, affects, mapsTo, and confidence with what is actually observed. Add more detail "+ "entries per zone if a single zone contains multiple distinct marks; do not leave stubs "+ "unfilled or unlinked (mapsTo must reference a real component.localFeatures or "+ "material.localOverrides entry)."+ ),+ }+ out_path.parent.mkdir(parents=True, exist_ok=True)+ out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ print(out_path)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/scripts/delight_reference.py b/scripts/delight_reference.pynew file mode 100755index 0000000..b408d5c--- /dev/null+++ b/scripts/delight_reference.py@@ -0,0 +1,343 @@+#!/usr/bin/env python3+"""Approximate a neutral (de-lit) albedo from a single reference photo.++This is an approximation, not true inverse rendering. A single photo bakes+together albedo, direct light, ambient occlusion, and specular response+into one signal, and there is no way to fully separate those from pixels+alone. This script applies a per-pixel normalization against a low-frequency+luminance estimate (a box-blur "lighting" proxy): pixels darker than their+local neighborhood get brightened, pixels brighter than their neighborhood+get darkened, pulling the image toward flat, even lighting. Strong specular+hotspots, deep occlusion shadows, and directional cues that vary faster than+the blur radius will not be fully removed. Always review the output next to+the source image before treating it as a projection albedo.+"""++from __future__ import annotations++import argparse+import json+import shutil+import struct+import subprocess+import sys+import tempfile+import zlib+from pathlib import Path+from typing import Any+++PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+++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 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 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 = 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 write_png_rgba(path: Path, width: int, height: int, rgba: bytes) -> None:+ if len(rgba) != width * height * 4:+ raise ValueError("RGBA 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 * 4+ for y in range(height):+ scanlines.append(0)+ scanlines.extend(rgba[y * stride : (y + 1) * stride])+ ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 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 blur_scalar(values: list[float], width: int, height: int, radius: int) -> list[float]:+ if radius <= 0:+ return values[:]+ horizontal = [0.0] * (width * height)+ for y in range(height):+ row_offset = y * width+ running = 0.0+ count = 0+ for x in range(-radius, width + radius):+ if 0 <= x < width:+ running += values[row_offset + x]+ count += 1+ remove = x - radius * 2 - 1+ if 0 <= remove < width:+ running -= values[row_offset + remove]+ count -= 1+ write_x = x - radius+ if 0 <= write_x < width:+ horizontal[row_offset + write_x] = running / max(1, count)+ vertical = [0.0] * (width * height)+ for x in range(width):+ running = 0.0+ count = 0+ for y in range(-radius, height + radius):+ if 0 <= y < height:+ running += horizontal[y * width + x]+ count += 1+ remove = y - radius * 2 - 1+ if 0 <= remove < height:+ running -= horizontal[remove * width + x]+ count -= 1+ write_y = y - radius+ if 0 <= write_y < height:+ vertical[write_y * width + x] = running / max(1, count)+ return vertical+++def delight(+ width: int,+ height: int,+ pixels: list[tuple[int, int, int, int]],+ strength: float,+ blur_radius: int,+) -> tuple[bytes, dict[str, Any]]:+ lumas = [srgb_luma(pixel[:3]) for pixel in pixels]+ target = percentile(lumas, 0.5, 0.5)+ low_frequency = blur_scalar(lumas, width, height, blur_radius)+ out = bytearray()+ corrections: list[float] = []+ for (red, green, blue, alpha), low in zip(pixels, low_frequency):+ shade = clamp(low, 0.05, 1.0)+ raw_scale = target / shade+ # strength blends between no correction (1.0) and the full normalization+ scale = 1.0 + (raw_scale - 1.0) * clamp01(strength)+ scale = clamp(scale, 0.35, 2.6)+ corrections.append(scale)+ out.extend(+ (+ round(clamp(red * scale, 0, 255)),+ round(clamp(green * scale, 0, 255)),+ round(clamp(blue * scale, 0, 255)),+ alpha,+ )+ )+ luma_before_range = percentile(lumas, 0.95, 0.8) - percentile(lumas, 0.05, 0.2)+ stats = {+ "targetLuma": round(target, 4),+ "blurRadius": blur_radius,+ "lumaRangeBefore": round(luma_before_range, 4),+ "meanCorrectionScale": round(sum(corrections) / max(1, len(corrections)), 4),+ "maxCorrectionScale": round(max(corrections, default=1.0), 4),+ "minCorrectionScale": round(min(corrections, default=1.0), 4),+ }+ return bytes(out), stats+++def estimate_confidence(stats: dict[str, Any], strength: float, warnings: list[str]) -> tuple[float, list[str]]:+ notes: list[str] = []+ luma_range = float(stats.get("lumaRangeBefore", 0.4))+ # a very large baked lighting range means more got corrected but also more+ # residual error is likely, since the box blur is only a crude lighting proxy+ range_penalty = clamp01((luma_range - 0.35) * 0.6)+ strength_bonus = clamp01(strength) * 0.15+ confidence = clamp01(0.55 - range_penalty * 0.25 + strength_bonus - min(0.1, len(warnings) * 0.04))+ confidence = min(0.72, confidence) # single-image de-lighting is always capped+ notes.append("single-image de-lighting cannot separate true albedo from baked light/AO/specular; confidence is capped")+ if luma_range > 0.5:+ notes.append("wide baked lighting range detected; expect visible residual shading after correction")+ return round(confidence, 3), notes+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("image", type=Path)+ parser.add_argument("--out", type=Path, required=True, help="Output de-lit PNG path")+ parser.add_argument("--report", type=Path, help="Write the JSON report to this path (also printed to stdout)")+ parser.add_argument(+ "--strength",+ type=float,+ default=0.6,+ help="0.0 = no correction (passthrough), 1.0 = full normalization against the blurred luminance proxy (default 0.6)",+ )+ parser.add_argument(+ "--blur-radius",+ type=int,+ default=0,+ help="Box-blur radius in pixels for the low-frequency lighting estimate; 0 = auto from image size",+ )+ args = parser.parse_args(argv)++ image = args.image.expanduser().resolve()+ if not image.exists():+ parser.error(f"{image} does not exist")+ out_path = args.out.expanduser().resolve()++ try:+ width, height, pixels, load_warnings = load_image(image)+ blur_radius = args.blur_radius if args.blur_radius > 0 else max(6, min(48, min(width, height) // 20))+ strength = clamp01(args.strength)+ delit_rgba, stats = delight(width, height, pixels, strength, blur_radius)+ write_png_rgba(out_path, width, height, delit_rgba)++ confidence, confidence_notes = estimate_confidence(stats, strength, load_warnings)+ report = {+ "delightReference": {+ "version": "1.0",+ "sourceImage": str(image),+ "outputImage": str(out_path),+ "method": (+ "per-pixel normalization against a box-blurred luminance proxy; an approximation of "+ "de-lighting, not physically based inverse rendering or true light/albedo separation"+ ),+ "strength": strength,+ "confidence": confidence,+ "stats": stats,+ "limitations": [+ "this is an approximation, not true inverse rendering; it cannot recover ground-truth albedo",+ "sharp specular highlights and hard shadow edges narrower than the blur radius will remain baked in",+ "deep occlusion shadows (creases, undercuts) are only partially lifted",+ "must be reviewed visually next to the source image before use as a projection albedo",+ ]+ + confidence_notes+ + load_warnings,+ "note": (+ "If shadows or highlights are still visible in the output, try a larger --strength or a "+ "smaller --blur-radius so the correction responds to tighter lighting gradients, then "+ "re-review; this script does not know when the correction is visually sufficient."+ ),+ }+ }+ text = json.dumps(report, indent=2, ensure_ascii=False)+ if args.report:+ report_path = args.report.expanduser().resolve()+ report_path.parent.mkdir(parents=True, exist_ok=True)+ report_path.write_text(text + "\n", encoding="utf-8")+ print(text)+ return 0+ 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/extract_reference_landmarks.py b/scripts/extract_reference_landmarks.pynew file mode 100644index 0000000..50cea8e--- /dev/null+++ b/scripts/extract_reference_landmarks.py@@ -0,0 +1,447 @@+#!/usr/bin/env python3+"""Overlay a labelled proportion/landmark guide grid on a reference image and scaffold anatomy.++Draws head-unit ticks, a rule-of-thirds grid, a center symmetry axis, default face-line+guides (hairline/eye/nose/mouth), and default shoulder/hip lines onto a copy of the+reference (see docs/UPGRADE_PLAN.md 5.3-5.4 and references/character-reconstruction.md),+then emits an anatomy skeleton JSON for the agent to fill from what the overlay reveals.+The drawn lines are generic starting positions, not measurements - the agent's vision+supplies the actual proportions, pose, and landmark coordinates.+"""++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"++MARGIN = 44++COLOR_THIRDS = (150, 150, 150)+COLOR_HEAD_UNIT = (60, 120, 220)+COLOR_HAIRLINE = (210, 80, 210)+COLOR_EYELINE = (230, 60, 60)+COLOR_NOSEBASE = (240, 150, 30)+COLOR_MOUTHLINE = (40, 170, 90)+COLOR_SHOULDER = (30, 140, 200)+COLOR_HIP = (170, 110, 40)+COLOR_CENTER = (20, 20, 20)++FONT_3X5 = {+ "0": ["###", "#.#", "#.#", "#.#", "###"],+ "1": [".#.", "##.", ".#.", ".#.", "###"],+ "2": ["###", "..#", "###", "#..", "###"],+ "3": ["###", "..#", "###", "..#", "###"],+ "4": ["#.#", "#.#", "###", "..#", "..#"],+ "5": ["###", "#..", "###", "..#", "###"],+ "6": ["###", "#..", "###", "#.#", "###"],+ "7": ["###", "..#", "..#", "..#", "..#"],+ "8": ["###", "#.#", "###", "#.#", "###"],+ "9": ["###", "#.#", "###", "..#", "###"],+ "H": ["#.#", "#.#", "###", "#.#", "#.#"],+ "E": ["###", "#..", "##.", "#..", "###"],+ "N": ["#.#", "##.", "#.#", ".##", "#.#"],+ "M": ["#.#", "###", "###", "#.#", "#.#"],+ "S": [".##", "#..", ".#.", "..#", "##."],+ "P": ["##.", "#.#", "##.", "#..", "#.."],+ "C": [".##", "#..", "#..", "#..", ".##"],+}+++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_white(pixel: tuple[int, int, int, int]) -> tuple[int, int, int]:+ red, green, blue, alpha = pixel+ mix = alpha / 255.0+ return (+ round(red * mix + 255 * (1 - mix)),+ round(green * mix + 255 * (1 - mix)),+ round(blue * mix + 255 * (1 - mix)),+ )+++def set_pixel(canvas: list[tuple[int, int, int]], width: int, height: int, x: int, y: int, color: tuple[int, int, int]) -> None:+ if 0 <= x < width and 0 <= y < height:+ canvas[y * width + x] = color+++def draw_glyph(+ canvas: list[tuple[int, int, int]],+ width: int,+ height: int,+ x0: int,+ y0: int,+ glyph: list[str],+ color: tuple[int, int, int],+ scale: int,+) -> None:+ for row_index, row in enumerate(glyph):+ for col_index, mark in enumerate(row):+ if mark != "#":+ continue+ for dy in range(scale):+ for dx in range(scale):+ set_pixel(canvas, width, height, x0 + col_index * scale + dx, y0 + row_index * scale + dy, color)+++def draw_text(+ canvas: list[tuple[int, int, int]],+ width: int,+ height: int,+ x0: int,+ y0: int,+ text: str,+ color: tuple[int, int, int],+ scale: int = 2,+) -> None:+ cursor_x = x0+ for character in text:+ glyph = FONT_3X5.get(character)+ if glyph:+ draw_glyph(canvas, width, height, cursor_x, y0, glyph, color, scale)+ cursor_x += 3 * scale + scale+++def draw_hline(+ canvas: list[tuple[int, int, int]],+ width: int,+ height: int,+ y: int,+ x_start: int,+ x_end: int,+ color: tuple[int, int, int],+ dash: int = 0,+) -> None:+ if not (0 <= y < height):+ return+ row = y * width+ for x in range(max(0, x_start), min(width, x_end)):+ if dash and (x // dash) % 2 == 1:+ continue+ canvas[row + x] = color+++def draw_vline(+ canvas: list[tuple[int, int, int]],+ width: int,+ height: int,+ x: int,+ y_start: int,+ y_end: int,+ color: tuple[int, int, int],+ dash: int = 0,+) -> None:+ if not (0 <= x < width):+ return+ for y in range(max(0, y_start), min(height, y_end)):+ if dash and (y // dash) % 2 == 1:+ continue+ canvas[y * width + x] = color+++def build_overlay(image: Path, overlay_path: Path, heads: int) -> dict:+ width, height, pixels = load_image(image)+ base = [composite_over_white(pixel) for pixel in pixels]+ canvas_w = width + MARGIN+ canvas_h = height+ canvas: list[tuple[int, int, int]] = [(255, 255, 255)] * (canvas_w * canvas_h)+ for y in range(height):+ source_row = y * width+ dest_row = y * canvas_w + MARGIN+ canvas[dest_row : dest_row + width] = base[source_row : source_row + width]++ for fraction in (1.0 / 3, 2.0 / 3):+ y = round(fraction * height)+ draw_hline(canvas, canvas_w, canvas_h, y, MARGIN, canvas_w, COLOR_THIRDS, dash=6)+ for fraction in (1.0 / 3, 2.0 / 3):+ x = MARGIN + round(fraction * width)+ draw_vline(canvas, canvas_w, canvas_h, x, 0, height, COLOR_THIRDS, dash=6)++ center_x = MARGIN + width // 2+ draw_vline(canvas, canvas_w, canvas_h, center_x, 0, height, COLOR_CENTER)+ draw_text(canvas, canvas_w, canvas_h, 4, max(0, min(height - 6, height // 2 - 3)), "C", COLOR_CENTER)++ step = height / heads+ for i in range(1, heads):+ y = round(i * step)+ draw_hline(canvas, canvas_w, canvas_h, y, MARGIN, canvas_w, COLOR_HEAD_UNIT, dash=10)+ draw_text(canvas, canvas_w, canvas_h, 4, max(0, y - 3), str(i), COLOR_HEAD_UNIT)++ band = step+ face_lines = [+ ("H", COLOR_HAIRLINE, 0.05),+ ("E", COLOR_EYELINE, 0.50),+ ("N", COLOR_NOSEBASE, 0.65),+ ("M", COLOR_MOUTHLINE, 0.80),+ ]+ for label, color, fraction in face_lines:+ y = round(fraction * band)+ draw_hline(canvas, canvas_w, canvas_h, y, MARGIN, MARGIN + width, color, dash=4)+ draw_text(canvas, canvas_w, canvas_h, 4, max(0, y - 3), label, color)++ shoulder_y = round(0.28 * height)+ hip_y = round(0.55 * height)+ draw_hline(canvas, canvas_w, canvas_h, shoulder_y, MARGIN, canvas_w, COLOR_SHOULDER, dash=14)+ draw_text(canvas, canvas_w, canvas_h, 4, max(0, shoulder_y - 3), "S", COLOR_SHOULDER)+ draw_hline(canvas, canvas_w, canvas_h, hip_y, MARGIN, canvas_w, COLOR_HIP, dash=14)+ draw_text(canvas, canvas_w, canvas_h, 4, max(0, hip_y - 3), "P", COLOR_HIP)++ write_png_rgb(overlay_path, canvas_w, canvas_h, canvas)+ return {+ "overlayImage": str(overlay_path),+ "imageWidth": width,+ "imageHeight": height,+ "headUnitCount": heads,+ "legend": {+ "C": "center symmetry axis",+ "1..N": "head-unit horizontal ticks (blue, dashed)",+ "H": "hairline guide (default fraction of the first head-unit band)",+ "E": "eye line guide",+ "N": "nose base guide",+ "M": "mouth line guide",+ "S": "shoulder line guide (default fraction, adjust to observed pose)",+ "P": "hip line guide (default fraction, adjust to observed pose)",+ "grayDashed": "rule-of-thirds compositional grid",+ },+ "note": "Guide lines are generic starting positions, not measurements. Read the overlay "+ "against the actual reference and fill anatomy with observed normalized values.",+ }+++def make_anatomy_skeleton(style_heads: float) -> dict:+ joint_names = [+ "neck",+ "leftShoulder",+ "rightShoulder",+ "leftElbow",+ "rightElbow",+ "leftWrist",+ "rightWrist",+ "leftHip",+ "rightHip",+ "leftKnee",+ "rightKnee",+ "leftAnkle",+ "rightAnkle",+ ]+ return {+ "styleHeads": style_heads,+ "proportions": {+ "headUnit": None,+ "torso": None,+ "legs": None,+ "shoulderWidth": None,+ "hipWidth": None,+ },+ "pose": {+ "type": "",+ "jointAngles": {name: [0, 0, 0] for name in joint_names},+ },+ "faceLandmarks": {+ "hairline": None,+ "eyeLine": None,+ "eyeSpacing": None,+ "noseBase": None,+ "mouthLine": None,+ "earTop": None,+ "earBottom": None,+ },+ "features": [],+ "confidence": 0.0,+ }+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("image", type=Path)+ parser.add_argument(+ "--out",+ type=Path,+ help="Output anatomy skeleton JSON path (default: <image-stem>-anatomy.json next to the image)",+ )+ parser.add_argument(+ "--overlay",+ type=Path,+ help="Output overlay PNG path (default: <image-stem>-landmarks.png next to the image)",+ )+ parser.add_argument(+ "--style-heads",+ type=float,+ default=6.0,+ help="Initial head-unit estimate driving the overlay grid "+ "(realistic ~7.5, stylized ~5-6, chibi/figurine ~2-3); refine after visual inspection",+ )+ parser.add_argument(+ "--heads",+ type=int,+ help="Override number of head-unit tick lines drawn (default: round(--style-heads))",+ )+ parser.add_argument("--force", action="store_true", help="Overwrite existing outputs")+ args = parser.parse_args(argv)++ image = args.image.expanduser().resolve()+ if not image.exists():+ parser.error(f"{image} does not exist")+ overlay_path = (args.overlay or image.with_name(f"{image.stem}-landmarks.png")).expanduser().resolve()+ out_path = (args.out or image.with_name(f"{image.stem}-anatomy.json")).expanduser().resolve()+ if not args.force:+ for existing in (overlay_path, out_path):+ if existing.exists():+ parser.error(f"{existing} already exists; use --force to overwrite")+ heads = args.heads or max(1, round(args.style_heads))++ try:+ overlay_meta = build_overlay(image, overlay_path, heads)+ except Exception as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 1++ payload = {+ "sourceImage": str(image),+ "overlayImage": str(overlay_path),+ "overlayLegend": overlay_meta["legend"],+ "anatomy": make_anatomy_skeleton(args.style_heads),+ "authoringInstruction": (+ "Open overlayImage and read the reference against its head-unit ticks, thirds grid, "+ "face-line guides, shoulder/hip lines, and center axis. Replace every null/placeholder "+ "value in anatomy with normalized coordinates or joint angles actually observed; the "+ "drawn guide lines are generic starting positions, not measurements."+ ),+ }+ out_path.parent.mkdir(parents=True, exist_ok=True)+ out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ print(out_path)+ 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.pyindex 23852a2..a9f6aad 100755--- a/scripts/new_pre_spec_assessment.py+++ b/scripts/new_pre_spec_assessment.py@@ -47,12 +47,21 @@ COMPLEXITY_MINIMUMS = {}+DETAIL_MINIMUMS = {+ "simple": 3,+ "moderate": 6,+ "complex": 10,+ "ultra-complex": 16,+}++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"] = complexityassessment["specDepthDecision"]["requiredDepth"] = complexity+ assessment["detailInventory"]["targetMinDetails"] = DETAIL_MINIMUMS[complexity]if complexity in {"complex", "ultra-complex"}:assessment["specDepthDecision"]["needsRepetitionSystems"] = Trueassessment["specDepthDecision"]["needsMaterialLocalOverrides"] = Truediff --git a/scripts/new_sculpt_spec.py b/scripts/new_sculpt_spec.pyindex 9dee52c..0d5a783 100755--- a/scripts/new_sculpt_spec.py+++ b/scripts/new_sculpt_spec.py@@ -19,11 +19,12 @@ def make_pre_spec_assessment(target_name: str) -> dict:return {"objectClass": {"primaryType": "unassessed",+ "primaryDomain": "unassessed","formLanguage": [],"structureKind": [],"motionPotential": [],"materialFamilies": [],- "notes": "Fill from direct visual inspection before writing the final spec. Do not use fixed domain profiles.",+ "notes": "Fill from direct visual inspection before writing the final spec. Do not use fixed domain profiles. Set primaryDomain to object, character, or hybrid.",},"complexity": {"tier": "unassessed",@@ -58,6 +59,42 @@ def make_pre_spec_assessment(target_name: str) -> dict:"rationale": "Choose simple/moderate/complex/ultra-complex from observed structure, not from a hardcoded domain.",},"unknownsToResolveBeforeImplementation": [],+ "detailInventory": {+ "scanMethod": "component-zones",+ "targetMinDetails": 0,+ "note": (+ "Enumerate every identity-defining small detail before authoring the spec. "+ "Each detail must map to a component.localFeatures entry or material.localOverrides entry, "+ "never prose only. Use scripts/build_detail_inventory.py to scan zones."+ ),+ "details": [],+ },+ "anatomy": {+ "applies": False,+ "styleHeads": 0.0,+ "proportions": {+ "headUnit": 0.0,+ "torso": 0.0,+ "legs": 0.0,+ "shoulderWidth": 0.0,+ "hipWidth": 0.0,+ },+ "pose": {"type": "unassessed", "jointAngles": {}},+ "faceLandmarks": {+ "eyeLine": 0.0,+ "eyeSpacing": 0.0,+ "noseBase": 0.0,+ "mouthLine": 0.0,+ "hairline": 0.0,+ },+ "features": [],+ "confidence": 0.0,+ "note": (+ "Only meaningful when objectClass.primaryDomain is character or hybrid. "+ "Set applies=true and fill from scripts/extract_reference_landmarks.py. "+ "See references/character-reconstruction.md and references/likeness-maximization.md."+ ),+ },}@@ -179,6 +216,201 @@ def load_assessment(path: Path | None) -> dict | None:return payload+def _cnode(cid, name, primitive, parent, position, scale,+ material="skin", role="body", level="meso", rotation=(0, 0, 0),+ importance=0.7, sockets=None, local_features=None, anim_role="static",+ pivot_mode="center", evidence=None):+ """Build a full schema-valid componentTree node with humanoid-friendly defaults."""+ return {+ "id": cid, "name": name, "level": level, "role": role,+ "importance": importance, "confidence": 0.8, "primitive": primitive,+ "geometryDescriptor": {+ "topologyIntent": "stylized character part",+ "edgeTreatment": {"type": "none", "bevelRadius": 0.0, "segments": 1},+ "deformationStack": [], "uvStrategy": "generated procedural coordinates",+ "normalStrategy": "smooth vertex normals",+ },+ "parent": parent, "attachment": None,+ "dimensions": {"width": float(scale[0]), "height": float(scale[1]),+ "depth": float(scale[2]), "units": "relative", "confidence": 0.8},+ "transform": {"position": list(position), "rotation": list(rotation), "scale": list(scale)},+ "actionProfile": {+ "animationRole": anim_role,+ "pivot": {"mode": pivot_mode, "localPosition": [0, 0, 0], "axis": [0, 1, 0], "confidence": 0.7},+ "transformChannels": {"translate": True, "rotate": True, "scale": True,+ "bend": False, "twist": False, "detach": False,+ "visibility": True, "materialState": False},+ "sockets": sockets or [],+ "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1],+ "isTrigger": False, "notes": "box proxy"},+ "constraints": [],+ "destruction": {"breakable": False, "fractureGroup": cid, "seamRefs": [],+ "detachableFragments": [], "breakImpulse": 0.0, "debrisMaterial": material},+ },+ "material": material, "materialLayers": [material], "deformations": [], "joints": [],+ "seams": [], "localFeatures": local_features or [],+ "surfaceDetail": {"macroRoughness": 0.0, "microRoughness": 0.0, "bumpAmplitude": 0.0,+ "normalPattern": "", "displacementPattern": "", "occlusionPattern": "",+ "edgeWearPattern": "", "notes": ""},+ "evidenceRefs": evidence or ["full-object"], "details": [], "fidelityTier": "blockout",+ }+++def make_character_component_tree(anatomy: dict | None = None) -> list:+ """A stylized humanoid bust template (head/neck/torso/arms + hair, glasses, headphones,+ face features). Head-unit driven; HU ~= 0.28 world units.++ The generator nests children under a parent node whose transform (incl. scale) cascades,+ so non-uniform parent scale would distort descendants. To avoid that, every visible part is+ authored with a logical parent + local offset, then FLATTENED to world space and parented to+ a hidden, unit-scaled root. Parents used for offsets (torso, head) are unrotated, so summing+ offsets is exact. Parts use primitives the generator already supports."""+ hu = 0.28+ # (id, name, primitive, logical_parent, offset, scale, material, role, level, rotation, importance, features)+ parts = [+ ("torso", "Torso (shirt)", "capsule", "root", (0, 0.55 * hu, 0), (2.4 * hu, 2.2 * hu, 1.5 * hu), "shirt", "shell", "macro", (0, 0, 0), 1.0, []),+ ("shirt-decal", "Chest graphic (Orioles)", "plane-card", "torso", (0, 0.1 * hu, 0.78 * hu), (1.5 * hu, 0.9 * hu, 1.0), "shirt-decal", "decal", "micro", (0, 0, 0), 0.7, ["cursive orange team wordmark with white outline"]),+ ("neck", "Neck", "cylinder", "root", (0, 1.65 * hu, 0), (0.55 * hu, 0.7 * hu, 0.55 * hu), "skin", "support", "meso", (0, 0, 0), 0.6, []),+ ("head", "Head", "ellipsoid", "root", (0, 2.5 * hu, 0.02 * hu), (0.92 * hu, 1.12 * hu, 0.98 * hu), "skin", "body", "macro", (0, 0, 0), 1.0, []),+ ("hair", "Hair (side-swept)", "ellipsoid", "head", (0, 0.28 * hu, -0.04 * hu), (1.06 * hu, 0.82 * hu, 1.08 * hu), "hair", "hair", "meso", (0, 0, 0), 0.9, ["short sides, longer swept-back top"]),+ ("hair-front", "Hair front mass", "ellipsoid", "head", (0.12 * hu, 0.34 * hu, 0.34 * hu), (0.7 * hu, 0.5 * hu, 0.6 * hu), "hair", "hair", "micro", (0, 0, 0), 0.6, []),+ ("brow-l", "Eyebrow L", "box", "head", (0.2 * hu, 0.12 * hu, 0.46 * hu), (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),+ ("brow-r", "Eyebrow R", "box", "head", (-0.2 * hu, 0.12 * hu, 0.46 * hu), (0.22 * hu, 0.04 * hu, 0.06 * hu), "hair", "detail", "micro", (0, 0, 0), 0.4, []),+ ("nose", "Nose", "cone", "head", (0, -0.04 * hu, 0.5 * hu), (0.14 * hu, 0.28 * hu, 0.18 * hu), "skin", "detail", "micro", (1.4, 0, 0), 0.4, []),+ ("mouth", "Mouth", "box", "head", (0, -0.34 * hu, 0.46 * hu), (0.24 * hu, 0.04 * hu, 0.05 * hu), "lips", "detail", "micro", (0, 0, 0), 0.4, []),+ ("glasses-frame-l", "Glasses frame L", "torus", "head", (0.21 * hu, 0.02 * hu, 0.48 * hu), (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "connector", "meso", (0, 0, 0), 0.85, []),+ ("glasses-frame-r", "Glasses frame R", "torus", "head", (-0.21 * hu, 0.02 * hu, 0.48 * hu), (0.26 * hu, 0.22 * hu, 0.08 * hu), "glasses-frame", "connector", "meso", (0, 0, 0), 0.85, []),+ ("glasses-bridge", "Glasses bridge", "box", "head", (0, 0.04 * hu, 0.5 * hu), (0.12 * hu, 0.04 * hu, 0.04 * hu), "glasses-frame", "connector", "micro", (0, 0, 0), 0.5, []),+ ("lens-l", "Lens L", "plane-card", "head", (0.21 * hu, 0.02 * hu, 0.485 * hu), (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),+ ("lens-r", "Lens R", "plane-card", "head", (-0.21 * hu, 0.02 * hu, 0.485 * hu), (0.22 * hu, 0.18 * hu, 1.0), "glasses-lens", "panel", "micro", (0, 0, 0), 0.5, []),+ ("hp-band", "Headphone band", "torus", "root", (0, 1.78 * hu, 0.05 * hu), (0.95 * hu, 0.62 * hu, 0.7 * hu), "headphone", "ring", "meso", (1.2, 0, 0), 0.85, []),+ ("hp-cup-l", "Ear cup L", "cylinder", "root", (0.5 * hu, 1.52 * hu, 0.35 * hu), (0.42 * hu, 0.28 * hu, 0.42 * hu), "headphone", "detail", "meso", (0, 0, 1.57), 0.7, []),+ ("hp-cup-r", "Ear cup R", "cylinder", "root", (-0.5 * hu, 1.52 * hu, 0.35 * hu), (0.42 * hu, 0.28 * hu, 0.42 * hu), "headphone", "detail", "meso", (0, 0, 1.57), 0.7, []),+ ("arm-l", "Upper arm L", "capsule", "torso", (1.15 * hu, -0.35 * hu, 0.1 * hu), (0.55 * hu, 1.5 * hu, 0.55 * hu), "shirt", "arm", "meso", (0, 0, 0.25), 0.7, []),+ ("arm-r", "Upper arm R", "capsule", "torso", (-1.15 * hu, -0.35 * hu, 0.1 * hu), (0.55 * hu, 1.5 * hu, 0.55 * hu), "shirt", "arm", "meso", (0, 0, -0.25), 0.7, []),+ ]+ offsets = {"root": (0.0, 0.0, 0.0)}+ for pid, _n, _p, parent, off, *_rest in parts:+ offsets[pid] = off # local offset; world resolved below++ def world_pos(pid, parent, off):+ x, y, z = off+ cur = parent+ # walk up the logical parent chain (parents are unrotated), summing offsets+ while cur and cur != "root":+ po = offsets.get(cur, (0.0, 0.0, 0.0))+ x += po[0]; y += po[1]; z += po[2]+ cur = parent_of.get(cur, "root")+ return (x, y, z)++ parent_of = {p[0]: p[3] for p in parts}+ tree = [_cnode("root", "Character (root)", "box", None, (0, 0, 0), (1, 1, 1),+ material="hidden", role="body", level="macro", importance=1.0, anim_role="root")]+ for pid, name, prim, parent, off, scale, mat, role, level, rot, imp, feats in parts:+ tree.append(_cnode(pid, name, prim, "root", world_pos(pid, parent, off), scale,+ material=mat, role=role, level=level, rotation=rot, importance=imp,+ local_features=feats))+ return tree+++def _shade_hex(hex_color: str, factor: float) -> str:+ """Return a slightly darker/lighter shade of a #RRGGBB color (factor<1 darker)."""+ h = hex_color.lstrip("#")+ if len(h) != 6:+ return hex_color+ r, g, b = (int(h[i:i + 2], 16) for i in (0, 2, 4))+ r, g, b = (max(0, min(255, round(c * factor))) for c in (r, g, b))+ return f"#{r:02x}{g:02x}{b:02x}"+++CHARACTER_MATERIALS = [+ {"id": "hidden", "baseColor": "#000000", "roughness": {"base": 1.0, "variation": 0.0}, "opacity": {"base": 0.0}},+ {"id": "skin", "baseColor": "#e8b98f", "roughness": {"base": 0.55, "variation": 0.08}},+ {"id": "hair", "baseColor": "#171310", "roughness": {"base": 0.42, "variation": 0.1}},+ {"id": "shirt", "baseColor": "#20202a", "roughness": {"base": 0.85, "variation": 0.12}},+ {"id": "shirt-decal", "baseColor": "#d24a20", "roughness": {"base": 0.7, "variation": 0.05}},+ {"id": "glasses-frame", "baseColor": "#111114", "roughness": {"base": 0.35, "variation": 0.05}},+ {"id": "glasses-lens", "baseColor": "#a9c6d8", "roughness": {"base": 0.08, "variation": 0.02}},+ {"id": "headphone", "baseColor": "#0e0e10", "roughness": {"base": 0.5, "variation": 0.08}},+ {"id": "lips", "baseColor": "#c98070", "roughness": {"base": 0.5, "variation": 0.05}},+]+++def make_character_build_passes() -> list:+ base = make_pre_spec_assessment # noqa: reference to keep import graph obvious+ passes = [+ {"id": "blockout", "goal": "Match head-unit proportions and pose silhouette.",+ "componentRefs": ["root"], "acceptance": ["Bust proportions and 3/4 pose read correctly without materials."]},+ {"id": "proportion-lock", "goal": "Lock head/torso/limb head-unit ratios and pose angles.",+ "componentRefs": ["root", "head", "torso"], "acceptance": ["Head-unit ratios match anatomy; silhouette matches reference."]},+ {"id": "feature-placement", "goal": "Place facial features, hair, glasses, headphones to landmarks.",+ "componentRefs": ["head", "hair", "glasses-frame-l", "hp-band"],+ "acceptance": ["Eyeline/nose/mouth on landmark lines; glasses and headphones placed as in reference."]},+ {"id": "material-pass", "goal": "Match skin/hair/cloth/metal color and roughness.",+ "componentRefs": ["root"], "acceptance": ["Skin, hair, shirt, decal, glasses, headphone materials match reference palette."]},+ {"id": "lighting-pass", "goal": "Soft key from reference direction plus rim.",+ "componentRefs": ["root"], "acceptance": ["Readable under neutral light; reference-matched lighting added."]},+ {"id": "interaction-pass", "goal": "Rig-ready pivots and sockets.",+ "componentRefs": ["root"], "acceptance": ["Head/neck/arm pivots and face socket exposed."]},+ {"id": "optimization-pass", "goal": "Protect runtime performance.",+ "componentRefs": ["root"], "acceptance": ["Triangle/draw-call budget documented."]},+ ]+ del base+ return passes+++def make_character_feature_targets() -> list:+ return [+ {"id": "anatomy-proportion", "name": "Head-unit proportions and pose", "tier": "critical",+ "passIds": ["blockout", "proportion-lock"], "minimumScore": 0.78, "mustPass": True,+ "componentRefs": ["root", "head", "torso"], "evidenceRefs": ["full-object"]},+ {"id": "face-landmark-placement", "name": "Face landmarks + glasses placement", "tier": "critical",+ "passIds": ["feature-placement"], "minimumScore": 0.75, "mustPass": True,+ "componentRefs": ["head", "glasses-frame-l"], "evidenceRefs": ["full-object"]},+ {"id": "pose-silhouette", "name": "Pose and bust silhouette", "tier": "critical",+ "passIds": ["blockout", "proportion-lock"], "minimumScore": 0.75, "mustPass": True,+ "componentRefs": ["root", "arm-l"], "evidenceRefs": ["full-object"]},+ {"id": "outfit-and-palette", "name": "Outfit + accessories + palette", "tier": "important",+ "passIds": ["material-pass"], "minimumScore": 0.7, "mustPass": False,+ "componentRefs": ["shirt-decal", "headphone", "glasses-frame-l"], "evidenceRefs": ["full-object"]},+ ]+++def apply_character_template(spec: dict, anatomy: dict | None = None) -> dict:+ """Swap in the humanoid componentTree, character materials, build passes, and feature+ targets. Object specs are untouched; only called when primaryDomain is character/hybrid."""+ spec["componentTree"] = make_character_component_tree(anatomy)+ existing = {m.get("id"): m for m in spec.get("materials", []) if isinstance(m, dict)}+ for mat in CHARACTER_MATERIALS:+ merged = dict(existing.get("base", {}))+ merged.update(mat)+ merged.setdefault("name", mat["id"])+ merged.setdefault("type", "standard")+ # the generator colours meshes from `color`/`albedo`, so keep them in sync with baseColor+ base_color = mat.get("baseColor")+ if base_color:+ shade = _shade_hex(base_color, 0.82)+ merged["color"] = base_color+ # the generator only honours a palette with >= 2 entries (else it blends in beige+ # fallback tones), so provide two near-identical shades of the intended colour.+ merged["albedo"] = {"dominant": base_color, "secondary": [shade]}+ merged["colorVariation"] = {"palette": [base_color, shade], "pattern": "flat",+ "amplitude": 0.05, "heightCorrelation": 0.0}+ existing[mat["id"]] = merged+ spec["materials"] = list(existing.values())+ spec["buildPasses"] = make_character_build_passes()+ # A humanoid is reviewed as a whole each pass, so every pass renders all parts+ # (unlike the object pipeline where passes add parts incrementally).+ all_ids = [c["id"] for c in spec["componentTree"] if isinstance(c, dict) and c.get("id")]+ for build_pass in spec["buildPasses"]:+ build_pass["componentRefs"] = all_ids+ spec["featureReviewTargets"] = make_character_feature_targets()+ pipeline = spec.setdefault("sculptPipeline", {})+ pipeline["passOrder"] = [p["id"] for p in spec["buildPasses"]]+ pipeline["currentPass"] = "blockout"+ return spec++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)@@ -231,6 +463,17 @@ def make_spec(target_name: str, image: str | None, assessment_payload: dict | No"descriptionRule": "Use measurable 3D graphics terms. Avoid vague words unless they are paired with concrete geometry/material/shader parameters.",},"sourceImage": image or "",+ "referenceCamera": {+ "solved": False,+ "fovDegrees": 40.0,+ "aspect": 1.0,+ "orientation": {"yaw": 0.0, "pitch": 0.0, "roll": 0.0},+ "positionHint": [0.0, 0.0, 3.0],+ "note": (+ "For likeness work, solve the reference camera (scripts/solve_reference_camera.py) so the "+ "review render aligns with the photo and the reference can be projected. Confirm by overlay review."+ ),+ },"suitability": "conditional","scores": {"object_isolation": 0,@@ -852,9 +1095,22 @@ def main(argv: list[str]) -> int: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")+ parser.add_argument("--character", action="store_true",+ help="Use the humanoid character template (auto-enabled when the assessment primaryDomain is character/hybrid)")args = parser.parse_args(argv)- spec = make_spec(args.target_name, args.image, load_assessment(args.assessment))+ assessment = load_assessment(args.assessment)+ spec = make_spec(args.target_name, args.image, assessment)+ domain = None+ if isinstance(assessment, dict):+ pre = assessment.get("preSpecAssessment", {})+ oc = pre.get("objectClass", {}) if isinstance(pre, dict) else {}+ domain = oc.get("primaryDomain") if isinstance(oc, dict) else None+ if args.character or domain in {"character", "hybrid"}:+ anatomy = None+ if isinstance(assessment, dict) and isinstance(assessment.get("preSpecAssessment"), dict):+ anatomy = assessment["preSpecAssessment"].get("anatomy")+ apply_character_template(spec, anatomy)payload = json.dumps(spec, indent=2, ensure_ascii=False) + "\n"if args.out:diff --git a/scripts/solve_reference_camera.py b/scripts/solve_reference_camera.pynew file mode 100755index 0000000..6d49df8--- /dev/null+++ b/scripts/solve_reference_camera.py@@ -0,0 +1,202 @@+#!/usr/bin/env python3+"""Estimate a starting referenceCamera block for a reference image.++This is not camera calibration and it does not solve for the true focal+length, sensor, or 6-DoF pose that produced the photo. A single 2D image+under-constrains that problem. Instead this script emits a reasonable+default guess (FOV) plus image-derived facts (aspect ratio) and explicit+agent-fill placeholders (orientation, position) that the agent is expected+to refine by rendering the fitted mesh from this camera and visually+overlaying it against the reference image until silhouettes line up. The+`agentFill` flag on each field marks what still needs that visual pass.+"""++from __future__ import annotations++import argparse+import json+import struct+import sys+from pathlib import Path+from typing import Any+++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 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)+++def clamp(value: float, minimum: float, maximum: float) -> float:+ return max(minimum, min(maximum, value))+++def estimate_fov(aspect: float | None) -> tuple[float, str]:+ """Return a default vertical FOV guess plus the rationale.++ Most product/character reference photos are shot on a phone or a short+ telephoto lens at a comfortable working distance, which lands roughly in+ the 30-45 degree vertical FOV band. There is no way to recover the true+ lens from pixels alone, so this is a fixed default, not a measurement.+ """+ if aspect is not None and aspect < 0.75:+ return 38.0, "default guess for a portrait-oriented photo (typical phone/short-tele framing)"+ return 35.0, "default guess for a landscape/square photo (typical phone/short-tele framing)"+++def build_camera(image: Path, args: argparse.Namespace) -> dict[str, Any]:+ data = image.read_bytes()+ size = detect_size(data)+ warnings: list[str] = []+ if size is None:+ warnings.append("could not read image dimensions; aspect defaults to 1.0")+ width = height = None+ aspect = 1.0+ else:+ width, height = size+ aspect = round(width / height, 4) if height else 1.0++ default_fov, fov_rationale = estimate_fov(aspect)+ fov_degrees = args.fov_degrees if args.fov_degrees is not None else default_fov+ fov_source = "user-supplied" if args.fov_degrees is not None else "default-guess"++ distance = args.distance if args.distance is not None else 2.5+ distance_source = "user-supplied" if args.distance is not None else "placeholder"++ camera: dict[str, Any] = {+ "version": "1.0",+ "sourceImage": str(image),+ "solver": "solve_reference_camera.py",+ "method": (+ "heuristic default-guess camera, not solved from image content; image dimensions give an "+ "exact aspect ratio, everything else is a starting point for agent refinement"+ ),+ "imageWidth": width,+ "imageHeight": height,+ "fovDegrees": {+ "value": round(fov_degrees, 2),+ "source": fov_source,+ "agentFill": fov_source == "default-guess",+ "rationale": fov_rationale,+ },+ "aspect": {+ "value": aspect,+ "source": "image-dimensions" if size else "fallback-default",+ "agentFill": size is None,+ },+ "orientation": {+ "yawDegrees": {"value": args.yaw, "source": "placeholder", "agentFill": True},+ "pitchDegrees": {"value": args.pitch, "source": "placeholder", "agentFill": True},+ "rollDegrees": {"value": args.roll, "source": "placeholder", "agentFill": True},+ "note": "0/0/0 assumes a straight-on, level shot; adjust by eye against the reference image.",+ },+ "position": {+ "hint": [0.0, args.height_offset, distance],+ "distance": {"value": distance, "source": distance_source, "agentFill": distance_source == "placeholder"},+ "note": "Position hint assumes the subject is centered at the origin and the camera looks down -Z.",+ },+ "confidence": 0.35 if size else 0.15,+ "limitations": [+ "no true camera calibration is performed; focal length/FOV/orientation are not recovered from pixels",+ "fovDegrees is a genre default, not a measurement; wrong FOV distorts perceived proportions under overlay",+ "orientation and position are placeholders and will almost always need manual/agent adjustment",+ "this script cannot detect lens distortion, perspective foreshortening, or non-zero roll",+ ]+ + warnings,+ "note": (+ "Final camera match must be confirmed by overlay review: render the fitted mesh from this "+ "camera, place it beside or over the reference image, and adjust fovDegrees/orientation/"+ "position until silhouette and landmark alignment match before trusting projected texture bakes."+ ),+ }+ return camera+++def main(argv: list[str]) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("image", type=Path)+ parser.add_argument("--fov-degrees", type=float, default=None, help="Override the default FOV guess")+ parser.add_argument("--yaw", type=float, default=0.0, help="Orientation placeholder, degrees")+ parser.add_argument("--pitch", type=float, default=0.0, help="Orientation placeholder, degrees")+ parser.add_argument("--roll", type=float, default=0.0, help="Orientation placeholder, degrees")+ parser.add_argument("--distance", type=float, default=None, help="Camera distance hint, scene units")+ parser.add_argument("--height-offset", type=float, default=0.0, help="Camera Y offset hint, scene units")+ parser.add_argument("--out", type=Path, help="Write the referenceCamera JSON block to this path")+ args = parser.parse_args(argv)++ image = args.image.expanduser().resolve()+ if not image.exists():+ parser.error(f"{image} does not exist")++ camera = build_camera(image, args)+ payload = {"referenceCamera": camera}+ text = json.dumps(payload, indent=2, ensure_ascii=False)+ if args.out:+ out_path = args.out.expanduser().resolve()+ out_path.parent.mkdir(parents=True, exist_ok=True)+ out_path.write_text(text + "\n", encoding="utf-8")+ print(text)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/scripts/tests/test_pipeline.py b/scripts/tests/test_pipeline.pyindex 38d073f..daad3df 100644--- a/scripts/tests/test_pipeline.py+++ b/scripts/tests/test_pipeline.py@@ -165,6 +165,113 @@ class PipelineTest(unittest.TestCase):self.assertIn(r.returncode, (0, 1), r.stderr)self.assertTrue((self.dir / "pbr-report.json").exists() or r.returncode == 1)+ # ---- Track A / Track B upgrade coverage ----++ def _fresh_spec(self, complexity="moderate"):+ run("new_pre_spec_assessment.py", "Widget", "--complexity", complexity,+ "--out", self.assessment)+ run("new_sculpt_spec.py", "Widget", "--assessment", self.assessment,+ "--out", self.spec)+ return json.loads(self.spec.read_text())++ def test_new_schema_fields_present(self):+ spec = self._fresh_spec("complex")+ pre = spec["preSpecAssessment"]+ self.assertIn("detailInventory", pre)+ self.assertIn("anatomy", pre)+ self.assertIn("primaryDomain", pre["objectClass"])+ self.assertIn("referenceCamera", spec)+ # targetMinDetails scales with complexity+ self.assertEqual(pre["detailInventory"]["targetMinDetails"], 10)++ def test_detail_inventory_gate_fires_on_empty(self):+ self._fresh_spec("moderate")+ strict = run("validate_sculpt_spec.py", self.spec, "--strict-quality")+ self.assertNotEqual(strict.returncode, 0)+ self.assertIn("detailInventory has 0 details", strict.stdout + strict.stderr)++ def test_detail_inventory_backward_compatible(self):+ # A spec with NO detailInventory (pre-upgrade shape) must not trigger the detail gate.+ spec = self._fresh_spec("moderate")+ spec["preSpecAssessment"].pop("detailInventory", None)+ self.spec.write_text(json.dumps(spec))+ strict = run("validate_sculpt_spec.py", self.spec, "--strict-quality")+ self.assertNotIn("detailInventory", strict.stdout + strict.stderr)++ def test_character_gate_requires_anatomy(self):+ spec = self._fresh_spec("moderate")+ spec["preSpecAssessment"]["objectClass"]["primaryDomain"] = "character"+ self.spec.write_text(json.dumps(spec))+ strict = run("validate_sculpt_spec.py", self.spec, "--strict-quality")+ self.assertIn("anatomy.applies is not true", strict.stdout + strict.stderr)++ def test_character_track_skipped_for_objects(self):+ # primaryDomain unassessed/object must not trigger character warnings.+ self._fresh_spec("moderate")+ strict = run("validate_sculpt_spec.py", self.spec, "--strict-quality")+ self.assertNotIn("anatomy.applies", strict.stdout + strict.stderr)++ def test_new_upgrade_scripts_help(self):+ for script in ("build_detail_inventory.py", "extract_reference_landmarks.py",+ "solve_reference_camera.py", "delight_reference.py",+ "bake_projected_texture.py"):+ r = run(script, "--help")+ self.assertEqual(r.returncode, 0, f"{script}: {r.stderr}")++ def test_build_detail_inventory_slices_zones(self):+ out = self.dir / "di.json"+ zones = self.dir / "zones"+ r = run("build_detail_inventory.py", self.ref, "--mode", "grid-3x3",+ "--out-dir", zones, "--out", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertTrue(out.exists())+ crops = list(zones.glob("*.png")) if zones.exists() else []+ self.assertGreaterEqual(len(crops), 1)++ def test_delight_reference_writes_png(self):+ out = self.dir / "albedo.png"+ r = run("delight_reference.py", self.ref, "--out", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertTrue(out.exists() and out.stat().st_size > 0)++ # ---- v1.2 character generator ----++ def test_character_flag_builds_humanoid_tree(self):+ run("new_sculpt_spec.py", "Person", "--character", "--out", self.spec)+ spec = json.loads(self.spec.read_text())+ ids = {c["id"] for c in spec["componentTree"]}+ for part in ("root", "head", "torso", "neck", "hair", "glasses-frame-l", "arm-l"):+ self.assertIn(part, ids)+ # all parts flattened to root (no cascading non-uniform parent scale)+ for c in spec["componentTree"]:+ if c["id"] != "root":+ self.assertEqual(c["parent"], "root")+ # distinct per-part colors (skin vs hair vs shirt), not a single fallback+ colors = {m["id"]: m.get("color") for m in spec["materials"] if m["id"] in ("skin", "hair", "shirt")}+ self.assertEqual(len({colors["skin"], colors["hair"], colors["shirt"]}), 3)+ # palette has >= 2 entries so the generator does not fall back to beige+ for m in spec["materials"]:+ if m["id"] in ("skin", "hair", "shirt"):+ self.assertGreaterEqual(len(m.get("colorVariation", {}).get("palette", [])), 2)++ def test_character_autodetect_from_domain(self):+ run("new_pre_spec_assessment.py", "Person", "--complexity", "complex", "--out", self.assessment)+ a = json.loads(self.assessment.read_text())+ a["preSpecAssessment"]["objectClass"]["primaryDomain"] = "character"+ self.assessment.write_text(json.dumps(a))+ run("new_sculpt_spec.py", "Person", "--assessment", self.assessment, "--out", self.spec)+ spec = json.loads(self.spec.read_text())+ self.assertIn("head", {c["id"] for c in spec["componentTree"]})++ def test_character_factory_generates(self):+ run("new_sculpt_spec.py", "Person", "--character", "--out", self.spec)+ out = self.dir / "createCharacterModel.ts"+ r = run("generate_threejs_factory.py", self.spec, "--out", out)+ self.assertEqual(r.returncode, 0, r.stderr)+ ts = out.read_text()+ self.assertIn("createPersonModel", ts)+ self.assertIn('meshes["head"]', ts)+if __name__ == "__main__":unittest.main(verbosity=2)diff --git a/scripts/validate_sculpt_spec.py b/scripts/validate_sculpt_spec.pyindex 13a7aa6..bea32ff 100755--- a/scripts/validate_sculpt_spec.py+++ b/scripts/validate_sculpt_spec.py@@ -1483,6 +1483,160 @@ def validate_look_dev_targets(spec: dict[str, Any], errors: list[str], warnings:warnings.append("quality: lighting-pass needs contact shadow or ground shadow behavior")+VALID_DETAIL_KINDS = {+ "gloss", "bevel", "fastener", "linework", "contour", "seam", "stitch",+ "stain", "scratch", "chip", "decal", "emissive", "hole", "groove", "ridge",+}+++def _detail_link_keys(spec: dict[str, Any]) -> set[str]:+ """Collect keys a detailInventory item may map to: component ids, local feature ids,+ material ids, and material localOverride ids (with and without owner prefix)."""+ keys: set[str] = set()+ for comp in spec.get("componentTree", []):+ if not isinstance(comp, dict):+ continue+ cid = comp.get("id")+ if isinstance(cid, str):+ keys.add(cid)+ for feat in comp.get("localFeatures", []) or []:+ if isinstance(feat, str):+ keys.add(feat)+ if isinstance(cid, str):+ keys.add(f"{cid}/{feat}")+ elif isinstance(feat, dict) and isinstance(feat.get("id"), str):+ keys.add(feat["id"])+ if isinstance(cid, str):+ keys.add(f"{cid}/{feat['id']}")+ for mat in spec.get("materials", []):+ if not isinstance(mat, dict):+ continue+ mid = mat.get("id")+ if isinstance(mid, str):+ keys.add(mid)+ for over in mat.get("localOverrides", []) or []:+ if isinstance(over, dict) and isinstance(over.get("id"), str):+ keys.add(over["id"])+ if isinstance(mid, str):+ keys.add(f"{mid}/{over['id']}")+ return keys+++def _has_gloss_response(spec: dict[str, Any]) -> bool:+ for mat in spec.get("materials", []):+ if not isinstance(mat, dict):+ continue+ rough = mat.get("roughness")+ base = rough.get("base") if isinstance(rough, dict) else rough+ if is_number(base) and float(base) < 0.35:+ return True+ if is_number(mat.get("clearcoat")) or isinstance(mat.get("clearcoat"), dict):+ return True+ for over in mat.get("localOverrides", []) or []:+ if isinstance(over, dict) and is_number(over.get("roughness")) and float(over["roughness"]) < 0.3:+ return True+ return False+++def _has_repetition_or_small_parts(spec: dict[str, Any]) -> bool:+ if [r for r in spec.get("repetitionSystems", []) if isinstance(r, dict)]:+ return True+ return any(+ isinstance(c, dict) and c.get("level") == "micro"+ for c in spec.get("componentTree", [])+ )+++def validate_detail_inventory(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:+ """Gate the detail inventory. Backward compatible: only enforced when a detailInventory+ block with a positive targetMinDetails is present (new-pipeline specs)."""+ assessment = spec.get("preSpecAssessment")+ if not isinstance(assessment, dict):+ return+ inv = assessment.get("detailInventory")+ if not isinstance(inv, dict):+ return+ details = inv.get("details", [])+ if not isinstance(details, list):+ errors.append("preSpecAssessment.detailInventory.details must be an array")+ return+ target = inv.get("targetMinDetails", 0)+ if not (isinstance(target, int) and not isinstance(target, bool) and target > 0):+ return # not a new-pipeline spec; skip enforcement+ if len(details) < target:+ warnings.append(+ f"quality: detailInventory has {len(details)} details but targetMinDetails is {target}; "+ "enumerate identity-defining details (gloss, bevel, fasteners, linework, stains) before code generation"+ )+ link_keys = _detail_link_keys(spec)+ has_gloss = has_fastener = False+ for index, detail in enumerate(details):+ if not isinstance(detail, dict):+ errors.append(f"detailInventory.details[{index}] must be an object")+ continue+ did = detail.get("id", index)+ kind = detail.get("kind")+ if kind not in VALID_DETAIL_KINDS:+ warnings.append(f"quality: detailInventory detail {did!r} has unknown kind {kind!r}")+ maps = detail.get("mapsTo")+ ref = maps.get("ref") if isinstance(maps, dict) else None+ if not (isinstance(ref, str) and ref in link_keys):+ warnings.append(+ f"quality: detailInventory detail {did!r} does not map to a component.localFeatures "+ "or material.localOverrides entry (no prose-only details)"+ )+ if kind == "gloss":+ has_gloss = True+ elif kind == "fastener":+ has_fastener = True+ if has_gloss and not _has_gloss_response(spec):+ warnings.append(+ "quality: detailInventory lists a gloss detail but no material provides low roughness or clearcoat response"+ )+ if has_fastener and not _has_repetition_or_small_parts(spec):+ warnings.append(+ "quality: detailInventory lists fastener details but no repetitionSystem/instancing or micro parts represent them"+ )+++def validate_character_track(spec: dict[str, Any], errors: list[str], warnings: list[str]) -> None:+ """Gate the character track. Backward compatible: only enforced when primaryDomain is+ character or hybrid."""+ assessment = spec.get("preSpecAssessment")+ if not isinstance(assessment, dict):+ return+ object_class = assessment.get("objectClass")+ domain = object_class.get("primaryDomain") if isinstance(object_class, dict) else None+ if domain not in {"character", "hybrid"}:+ return+ anatomy = assessment.get("anatomy")+ if not isinstance(anatomy, dict) or anatomy.get("applies") is not True:+ warnings.append(+ "quality: primaryDomain is character/hybrid but anatomy.applies is not true; "+ "fill anatomy (styleHeads, proportions, pose, faceLandmarks) from the reference"+ )+ return+ if not (is_number(anatomy.get("styleHeads")) and float(anatomy["styleHeads"]) > 0):+ warnings.append("quality: character anatomy.styleHeads must be greater than 0 (head-unit proportion)")+ proportions = anatomy.get("proportions")+ if not (isinstance(proportions, dict) and any(+ is_number(proportions.get(k)) and float(proportions[k]) > 0 for k in ("torso", "legs")+ )):+ warnings.append("quality: character anatomy.proportions must set torso/legs head-unit ratios")+ landmarks = anatomy.get("faceLandmarks")+ if not (isinstance(landmarks, dict) and any(+ is_number(landmarks.get(k)) and float(landmarks[k]) > 0 for k in ("eyeLine", "noseBase", "mouthLine")+ )):+ warnings.append("quality: character anatomy.faceLandmarks must set eyeLine/noseBase/mouthLine from the reference")+ targets = spec.get("featureReviewTargets", [])+ character_ids = {"anatomy-proportion", "face-landmark-placement", "pose-silhouette", "outfit-and-palette"}+ if not any(isinstance(t, dict) and t.get("id") in character_ids for t in targets):+ warnings.append(+ "quality: character track needs featureReviewTargets covering anatomy/face/pose/outfit "+ "(add anatomy-proportion, face-landmark-placement, pose-silhouette, outfit-and-palette)"+ )++def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:errors: list[str] = []warnings: list[str] = []@@ -1517,6 +1671,8 @@ def validate_spec(spec: dict[str, Any]) -> tuple[list[str], list[str]]:if performance is not None and not isinstance(performance, dict):errors.append("performanceBudget must be an object")validate_quality_depth(spec, errors, warnings)+ validate_detail_inventory(spec, errors, warnings)+ validate_character_track(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