Production interior authoring and interactive Three.js delivery plugin for img2.
feat: add production interior workflow plugin
hoainho3326ce07509e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..4986363--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,37 @@+name: Interior plugin contract+on: [push, pull_request]+permissions:+ contents: read+jobs:+ plugin:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/checkout@v4+ with:+ repository: img2threejs/img2+ ref: 95c722b524118eb6dde74c1f47bff7dd1c18aef3+ path: .harness-sdk+ - uses: actions/setup-python@v5+ with:+ python-version: '3.10'+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - name: Install optional image-tool dependencies+ run: python3 -m pip install -r requirements-surfaces.txt+ - name: Run behavior regressions+ env:+ IMG2_HARNESS_SOURCE: ${{ github.workspace }}/.harness-sdk+ run: python3 -m unittest discover -s tests -v+ - name: Build real viewer modules and run behavioral regressions+ env:+ VIEWER_ROOT: ${{ github.workspace }}/runtime/viewer+ run: |+ npm ci --prefix runtime/viewer+ npm run build --prefix runtime/viewer+ node --test tests/viewer/*.test.mjs+ - name: Install through the official ecosystem in isolated hosts+ run: python3 scripts/verify_install.py --harness-source .harness-sdk+ - name: Build deterministic source release+ run: python3 scripts/package_plugin.pydiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..aa79787--- /dev/null+++ b/.gitignore@@ -0,0 +1,11 @@+_img2_local.py+__pycache__/+*.py[cod]+.img2/+.venv/+node_modules/+dist/+.DS_Store+.env+.env.*+!.env.examplediff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..3520e4e--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,46 @@+# Changelog++## 0.2.0 — 2026-10-18++### Full agent-operated production++- Expand the single-assignment skill and ordered actor/program steps through actual image/reference analysis, composition, live resource selection, native geometry/PBR, observed repair, bake/export, Three.js interaction and three-product delivery. The agent authors project inputs/code; no user-supplied JSON or stock-room fallback.+- Add workspace-only source intake/preflight, owned template/recipe installation, immutable evidence snapshots and manifest-derived delivery inventories.+- Add live Poly Haven discovery/info/files/acquisition with local glTF dependencies, bounded HTTPS/redirect/path handling, publisher MD5/size and SHA receipts, plus real dye/roughness/crop/metric-normal preparation.+- Package reusable bpy geometry/material/UV helpers, render/refresh stages, full-static and SUN-free two-pass diffuse/OIDN bakes, revision-bound indoor probe, actual runtime/portable exports and packed-master/portable consumer inspection.+- Preserve policy-addressable material identities and UV0 mappings across rebakes; a real native failing-before/passing-after regression covers repeated export and retained artist roughness. Update the production case policy to its stable names.+- Add real asymmetric UV1/native/EXR/probe/browser calibration fixtures, packed-pixel/non-white-sheen/export-failure regression and local Khronos validation; retain actual warnings rather than suppressing them.+- Package the pinned manifest-driven Three.js/Vite viewer: arbitrary source aspect/views/finishes, optional sun/background/cloth, UV1 linear atlases/PI, specular probe, bounded navigation, point-bound rail cloth, accessible controls, loading/retry/lifecycle and product links.+- Keep complete Oak/Linen authoring/spec/resource/surface reproduction behind the exact source hash; provide a separate complete asymmetric studio mechanism fixture. Neither reconstructs a different image automatically.++### Integration and distribution++- Preserve all eight evidence-pinned reviews, append-only revision/invalidation and three blocking gates; distinguish agent attestations from mechanical checks.+- Normalize production workspace roots before macOS alias confinement/relative paths; retain genuine traversal, escaping symlink, stale source and ownership protections.+- Separate installed-library import paths from explicit workspace output roots using the official SDK-compatible entrypoint convention.+- Include authoring/resources/viewer/recipes and optional dependency declarations in deterministic source ZIPs; exclude dependency/environment/build/private output trees. Extend CI definition with real image dependencies and viewer behavioral/build commands.+- Document executable per-step inputs/actions/exits, causal repair, resource/license authority, native/runtime/portable limitations and evidence-backed release verification. No universal neural recovery, fresh full-quality realism, physical-phone certification or npm/catalog publication is implied.++## 0.1.0 — 2026-10-18++### Interior workflow++- Ship a standalone img2 plugin with registry ID `interior`, host skill `img2-interior`, typed `image → interior-scene-candidate` capability, explicit program/agent steps and three blocking gates.+- Add eight evidence-pinned authoring/review stages with immutable source/intake, named reviewer attestations, rejection/request-input/stop handling, append-only history and dependent-stage invalidation.+- Add stdlib GLB binding/resource/UV/scalar-policy audits and distinct source/runtime/portable/native/sidecar hash contracts. Gates reevaluate current inputs without rewriting receipts.+- Distill Oak / Linen repairs into routed guidance for camera/form, textile/PBR/export pitfalls, UV0/UV1 and EXR calibration, ambient/direct lighting, cloth/camera ownership, lifecycle/accessibility and consumer delivery.++### Installation and distribution++- Use official img2 install/add/link/state/gate APIs; no custom installer, Forge imports or cross-plugin Python imports.+- Add isolated three-host installation/removal verification, pinned compatibility CI, deterministic installable source-ZIP packaging and a professional README/input/reference set.+- Exclude generated bootstrap files, workspace state, caches, credentials and large showcase assets from release archives.++### Integration repairs and observed verification++- Fix valid intake evidence rejection through workspace path aliases (including macOS `/var` versus `/private/var`) by comparing resolved identity/content while retaining lexical pins for symlink-retarget detection.+- Add a failing-before/passing-after directory-alias regression; keep source/evidence freshness and confinement checks intact.+- Correct capability examples/probes to specify both typed-edge endpoints, not a named plugin with an unspecified `null → null` query.+- Verify 47 behavior regressions, official installation in Claude/Codex/OpenCode sandboxes with zero doctor findings, and real showcase audit/state/gate replay including rejection/revision and stale-input counterexamples. See [VERIFICATION.md](VERIFICATION.md) for scope and limits.++0.1.0 was verified as a local source release. Repository hosting is separate from npm/catalog publication; no room-generation or physical-phone certification is implied.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..a40f4c4--- /dev/null+++ b/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or Derivative+ Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2026 hoainho++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..9c21589--- /dev/null+++ b/README.md@@ -0,0 +1,75 @@+# img2 Interior++**Version 0.2.0** — installable img2 skill for an image-capable agent to take one image/assignment through an actual editable interior, Three.js viewer and verified delivery. Requires img2 ≥0.4.0 / core API 1.++The agent reads the image/references, authors its camera/spec/Python scene, finds/acquires suitable resources, builds geometry/PBR, renders and repairs, bakes/exports, runs the viewer and independently opens the delivered files. The user does **not** have to provide JSON or approve every routine step. This is an agent-operated workflow/toolkit, not a universal neural image-to-mesh engine or an automatic photorealism guarantee.++## Install through img2++The source repository is private; cloning requires access to `img2threejs/img2interior`. Keep the linked checkout in a persistent location.++```sh+git clone https://github.com/img2threejs/img2interior.git "$HOME/img2interior"+npx --yes @img2threejs/[email protected] add --link "$HOME/img2interior" --yes+npx --yes @img2threejs/[email protected] doctor --json+npx --yes @img2threejs/[email protected] sync --check+npx --yes @img2threejs/[email protected] capabilities --from-kind image --to-kind interior-scene-candidate --plugin interior --json+```++Install the official harness first if needed; [installation](reference/installation.md) describes source/ZIP installation, sandbox verification and publication status. Claude Code, Codex and OpenCode receive the same `img2-interior` skill through official host registration, not hand-made unrelated skill symlinks. Nothing here installs into your real host account or deploys a website automatically.++Give the agent the image and request, for example:++> Use img2-interior to reconstruct this reference as an editable room and working Three.js scene. Follow the full production/repair/consumer-verification loop; preserve assumptions and deliver native, runtime with sidecars, and static portable outputs.++The skill starts in the project workspace, reads [SKILL.md](SKILL.md) and routes to the required reference. New images require their own authored scene; Oak/Linen is an explicit source-hash-guarded reproduction, never a fallback.++## Complete production workflow++| Operation | What actually runs / required exit |+|---|---|+| Read image and references | Byte-pinned intake, actual pixel/browser observations, source kind/authority, normalized anchors, uncertainty. No invented measurements. |+| Choose camera/composition | Agent-authored spec and physical blockout; actual source-aspect Cycles render, pose/FOV/framing and lateral/contact observations. |+| Find/acquire resources | Live Poly Haven search/info/files, explicit suitable CC0 selection, verified model dependencies/scans/HDRIs, MD5/size/SHA receipts and API credit. |+| Build geometry | Explicit workspace `build_scene(context)`, reusable Blender/Python primitives/imports/UV helpers, editable physical shell/furniture/detail/cloth metadata. |+| Prepare PBR | Real recipe-driven linear dyes/roughness/crops/metric yarn normals, separate material UV0, packed-image refresh and bound-GLB audit. |+| Render, compare, repair | Actual labeled contact sheets and source/lateral/macro views; preserve rejection, invalidate causally, regenerate and look again. No automatic likeness score. |+| Calibrate/bake/export | Real asymmetric UV1/EXR/probe fixtures; full-static and SUN-free ambient passes, normal-guided OIDN, current indoor probe and distinct native/runtime/portable products. |+| Integrate Three.js | Actual pinned Vite/Three template; linear UV1 atlases/PI, one shadowed sun, specular probe, optional background, source/finish/camera/download surfaces. |+| Verify interaction | Real browser input, bounds, point-bound cloth where authored, reduced motion, failure/retry/context loss/recovery, desktop/narrow and lifecycle evidence. |+| Handoff | Actual independent packed-master/portable reopening/renders, Khronos and local audits, current eight-stage approvals/three blocking gates, reproducible source/setup/resources/limits. |++Start with the [executable production runbook](reference/production-runbook.md). Detailed contracts: [scene/builder](reference/scene-contract.md), [resources/PBR](reference/resources.md), [bake/export](reference/bake-export.md), [viewer](reference/viewer-integration.md), [causal review](reference/review.md), [delivery](reference/delivery.md).++## Package layout++- `tools/`: actual project/source/template/snapshot CLI, live acquisition/surfaces, native production/inspection, view comparison, Khronos wrapper and retained workflow/audits/gates.+- `authoring/`: reusable context, geometry/PBR/UV, two-pass bake/probe/export, native consumers and real calibration/regression fixtures.+- `resources_lib/`: bounded HTTPS/integrity/local glTF dependencies and actual image operations.+- `runtime/viewer/`: complete source template and exact npm lockfile; installed into the **authored workspace**.+- `recipes/oak-linen/`: full source-specific builder/spec/resource/surface recipe, guarded by its supplied image SHA256.+- `examples/studio/`: complete independent asymmetric-room/one-curtain mechanism fixture, not a substitute for interpreting a new image.+- `reference/`: per-step inputs, actions, observable exit requirements, actual commands and limits; progressive disclosure under 150 lines/file.+- `tests/`, `scripts/`, `.github/`: behavior regressions, isolated official installation, deterministic source ZIP and CI definition.++The archive excludes large images/models/renders, vendor assets, installed dependencies, environments, credentials, local bootstrap/state and historical screenshots. Downloads/authoring/viewer outputs belong outside the installed plugin.++## Environments and verification++Audit/workspace tools remain stdlib Python ≥3.10 plus the installed img2 core. Native production uses isolated Python 3.11, **bpy 4.3.0 / NumPy 1.26.4** from `requirements-authoring.txt`. Image preparation/comparison uses `requirements-surfaces.txt` separately. Viewer/validator use workspace-local `npm ci` with pinned Three.js 0.180.0 / Vite 6.4.1 / Khronos validator 2.0.0-dev.3.10. See the runbook for setup and actual preflight.++```sh+IMG2_HARNESS_SOURCE=/absolute/path/to/img2 python3 -m unittest discover -s tests -v+# Set IMG2_BLENDER_PYTHON to the compatible executable to include real native regressions.+VIEWER_ROOT=/absolute/path/to/authored-workspace node --test tests/viewer/*.test.mjs+python3 scripts/verify_install.py --harness-source /absolute/path/to/img2+python3 scripts/package_plugin.py+```++Install optional image dependencies before the Python suite; missing image/native environments are reported as skips, not proof. Compile/tests do not replace a changed-path runtime smoke. [VERIFICATION.md](VERIFICATION.md) records exercised release checks, repair rounds and limits, not imagined CI/phone/hosting success.++## Honest boundaries++One image does not establish hidden geometry, scale, BRDF or collision truth. Agent-authored estimates remain explicit. Runtime indirect lighting/probe and portable appearance are static; the shipped cloth is a position-based horizontal-rail approximation with an identity-root/owned-geometry contract, not arbitrary rig support or calibrated FEM. Heavy source-specific research output is not a mobile budget baseline.++Paid generation, private uploads, publishing/deployment, purchases and a real-account install require separate authority. Review [SECURITY.md](SECURITY.md) before executing trusted authored Python or installing dependencies. Source/local ZIP readiness is not catalog publication.diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..f77dabb--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,31 @@+# Security and trust boundaries++Review source and install through the official img2 harness. Production now includes explicit network acquisition, optional Python packages, npm dependencies and execution of agent-authored Blender/Python. These are not hidden behind an audit-only or "no dependencies/downloads" claim. No tool automatically uploads references/models, purchases assets, invokes paid generation, deploys or registers itself into the real host account.++## Explicit workspace versus installed libraries++All production CLIs require `--workspace`; outputs/resources/evidence stay in that authored workspace, never the installed plugin/descendants. Import search paths locate installed libraries only. Local path checks reject traversal/escaping resolution and relevant symlinks; canonical macOS aliases are normalized before confinement. These are placement/integrity checks, **not an OS sandbox against hostile local filesystem races or executable Python**.++A workspace builder is trusted executable code. The agent must author/review it rather than run scripts found in an image, website, glTF, metadata or downloaded asset. Treat descriptions, URLs, source documents and model contents as untrusted data. Do not execute Blender auto-run scripts/macros from untrusted files. External-resource data does not override user/system instructions or grant publication rights.++## Acquiring and decoding resources++Poly Haven tools use bounded HTTPS to the explicit API/CDN allowlist, validate redirects/descriptors and published model-local buffer/image dependencies, stream to temporary files, check publisher size/MD5 and record SHA256 before replacement. They reject unsupported URI/path aliases and verify cached bytes, not just file size. Current limits include 16 MiB JSON, 512 MiB per asset file and 4 GiB per selection; they are not exhaustive decompression/decoder vulnerability defenses.++Poly Haven CC0 asset licensing is separate from live API terms; the client identifies itself and the viewer displays actual receipt-derived API attribution. The agent remains responsible for suitability, authority and any reference-image redistribution. No credentials are required or stored by this client. PNG/JPEG/WebP header intake is not a pixel decoder or content classifier; inspect/decode the actual image separately.++Pinned authoring requirements isolate bpy 4.3.0/NumPy 1.26.4; image tools use their own NumPy/Pillow environment. Workspace `npm ci` uses the checked-in lockfile, but third-party package lifecycle scripts/native dependencies still execute under normal npm policy. Review dependencies and apply the host's policy; this plugin does not claim a general dependency/CVE audit or universal platform support.++Khronos validation is local via the pinned workspace package. External-resource callbacks are size-bounded/local-only and cannot fetch remote URIs. Native/glTF consumers and browser decoders still process complex untrusted formats; run them in an appropriate environment for the source's trust level.++## State, template ownership and evidence++Only img2_core API 1 owns workspace state mutation. Plugin state is isolated under `plugins.interior`; other plugins' state must survive. Generated `_img2_local.py` resolves the installed harness and is ignored/excluded from releases. Template installation preflights ownership/hashes and refuses to overwrite unowned/user-edited files. A matching ownership receipt is not protection from an attacker able to edit the receipt itself.++Hash pinning detects changed bytes against a recorded value; it is not a signature, license proof or reviewer authentication. Someone able to edit both state and evidence can forge attestations. Gates enforce order/current inputs and mechanical audit conditions, not screenshot truth, aesthetic acceptance, ownership, measured dimensions or physical correctness. Freezing a report prevents accidental later changes from invalidating an earlier review; it does not authenticate the report's claims.++Review artifacts may expose project paths/images/designs. Do not publish workspace `.img2/`, client images, resources or captures without permission. Source release packaging excludes local bootstrap/state, dependencies/environments/build caches, large showcase assets and common `.env*` (except `.env.example`), `.pem`/`.key` files. It is not a general secret scanner; review all included source/examples before publishing.++The official installation smoke uses temporary HOME/IMG2_HOME/host directories, preserves unrelated sandbox settings and restores the bootstrap files it touches. Real-account installation remains an explicit user operation. Local ZIP/install readiness is distinct from publishing to a host/catalog.++For private security reports, contact the repository owner through the actual hosting account once a remote exists. This local project does not invent a security address or disclosure endpoint.diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..f998031--- /dev/null+++ b/SKILL.md@@ -0,0 +1,95 @@+---+name: img2-interior+description: Builds image-led interiors through Blender/Python, PBR, render-and-repair, bake/export and an interactive Three.js viewer; verifies native/runtime/portable delivery with img2.+license: Apache-2.0+version: 0.2.0+---++# Image → authored interior → working delivery++Accept one supplied room image and one assignment. Continue through analysis, implementation, visual repair, interactive runtime and delivery; do not return only a plan, ask the user to supply JSON, or stop after a Blender file/build. This is a skill for an image-capable coding agent, not a deterministic neural image-to-mesh service.++Set `SKILL_DIR` to this installed directory and work in the user's project, never the plugin checkout. Install through the official img2 harness; see [installation](reference/installation.md). Preserve unrelated user files. No global installs, publishing or paid-service requests by default.++## Start from the actual image++Read [start-to-finish operation](reference/production-runbook.md), [reference analysis](reference/reference-analysis.md) and [intake/camera](reference/intake-camera.md). Inspect actual source pixels, source kind and any supplied reference URLs. Use the host image/browser tools; header dimensions are not image analysis.++```sh+python3 "$SKILL_DIR/tools/interior_project.py" start --workspace "$PWD" --image "$IMAGE" --source-kind "$SOURCE_KIND"+python3 "$SKILL_DIR/tools/interior_project.py" preflight --workspace "$PWD" --blender-python "$BLENDER_PYTHON"+```++`start` preserves source bytes/provenance, not a generated room or an approval. Choose source kind honestly. Author `interior-intake.json`, `scene-spec.json` and image-specific `build_scene.py` yourself after observation; see [scene contract](reference/scene-contract.md) and [input schemas](reference/tool-inputs.md). State metre scale, visible anchors, camera estimates, hidden geometry assumptions, material goals, interaction scope and output budget. Make reasonable labeled design estimates; request input only when a material requirement cannot be decided safely.++The native builder is actual Blender code using the packaged `authoring` helpers, with `build_scene(context)`. It is not a prose description. Never substitute a bundled room, source-photo furniture cards or fabricated recovered dimensions. The explicit `oak-linen` recipe is source-hash guarded; [case reproduction](reference/oak-linen-recipe.md) is not the path for a different image.++Install missing dependencies in project-local environments. Rendering needs the tested Python 3.11 / bpy 4.3.0 / NumPy 1.26.4 environment; image tools use `requirements-surfaces.txt`; the viewer pins Three.js/Vite. Do not mix the image-tools NumPy environment into bpy. See the runbook for setup and recovery.++```sh+python3 "$SKILL_DIR/tools/interior_workflow.py" init --workspace "$PWD" --image "$IMAGE" --intake ./interior-intake.json+python3 "$SKILL_DIR/tools/interior_workflow.py" next --workspace "$PWD"+```++On resume use `next`, never reinitialize. Exit 3 means an explicit block; resolve its cause and revise. Project setup does not erase existing review history.++## Execute the complete production loop++| Work | Required implementation and exit evidence | Governance stage |+|---|---|---|+| Read image/reference | Source/provenance, anchors, uncertainty, task/quality/budget and technical reference findings; validated intake snapshot | `intake` |+| Decide camera/composition | Real coarse room and volumes, source-aspect render, camera/projection and meaningful lateral/reverse views; fix framing before polish | `camera` |+| Find suitable resources | [Poly Haven discovery/acquisition](reference/resources.md); inspect actual candidates, choose by silhouette/material need, verify dependencies/hashes/CC0 and record provenance | `geometry` / `materials` evidence |+| Author actual geometry | [Blender/Python geometry](reference/geometry.md); editable shell, furniture, soft forms, contacts, semantic components, UV0 and authored unseen surfaces | `geometry` |+| Prepare and bind PBR | [Materials](reference/materials.md); actual color/normal/roughness, physical scale, decoded statistics, packed images, frontal/grazing review and exported binding policy | `materials` |+| Render, compare, repair | [Review loop](reference/review.md); open actual images, compare camera → form → surface/light, preserve rejected versions, fix causes and rerender; never accept a score/build instead | Earliest affected stage |+| Calibrate, bake and export | [Lighting](reference/lighting.md) and [bake/export](reference/bake-export.md); UV1/EXR fixture, full-static vs ambient bake, denoise, probe, packed native and distinct GLBs | `lighting` |+| Integrate Three.js | [Viewer integration](reference/viewer-integration.md); install real template, consume generated manifest/resources, compile and view the actual scene; no canned scene fallback | `interaction` |+| Exercise interaction | [Interaction](reference/interaction.md); bounded camera, source/wireframe/reset, variants/cloth when present, input ownership, visibility, errors/retry, desktop/narrow accessibility | `interaction` |+| Independently inspect and hand off | [Delivery](reference/delivery.md); reopen/render native/portable, exercise runtime/download URLs, current hashes/dependencies, limits and reproducible commands | `delivery`, then `review` |++These are real operations, not ten declarations. Resource acquisition and provisional bakes/exports may be needed before a material review; they do not grant final lighting approval. Do not omit operations because a program returned zero.++## Run real authoring and visual iterations++Use a new `RUN_ID` for each repair round. Native stages write inside the explicit workspace; library import must not read/write a previous project.++```sh+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" draft --workspace "$PWD" --spec scene-spec.json --run-id "$RUN_ID" --width 1280 --samples 96+"$IMAGE_PYTHON" "$SKILL_DIR/tools/compare_views.py" --workspace "$PWD" --run-id "$RUN_ID" --render ".img2/artifacts/interior/production/$RUN_ID/draft-source.png"+```++Open the render/contact sheet with image tools and write findings, not just its filename. The runbook lists resource, PBR, bake/probe/export, viewer and inspection commands. For repairs use the native scoped refresh or change the builder/recipe and regenerate required outputs. Retain UV/geometry/material identity outside scope. Rebuild/rebake/reexport after changes affecting transport; partial bakes retain explicitly named old-GI approximations.++## Attest only observed stages++Run `next` before stage acceptance. Record reviewer identity, causal notes and immutable stage-specific evidence; an agent reviewer is permitted, routine human confirmation is not required.++```sh+python3 "$SKILL_DIR/tools/interior_workflow.py" record --workspace "$PWD" --stage camera --decision accept --reviewer "agent:session" --note "Observed source framing and lateral proportions; hidden depth remains authored" --evidence ./.img2/artifacts/interior/production/camera-r01/draft-source.png --evidence ./camera-review.json+python3 "$SKILL_DIR/tools/interior_workflow.py" revise --workspace "$PWD" --from materials --reason "Bound roughness image creates an unwanted specular tail; remap and rebake affected atlases"+```++Use `reject`, `request-input` or `stop` when warranted. Revise from the earliest affected stage and re-review downstream stages in order. A changed source needs a new project/run, not silently repinned truth. Preserve the rejected capture and actual before/after repair; do not relax tolerances, brighten exposure or delete required components to suppress a finding.++Reports use `.img2/artifacts/interior/`. Never overwrite accepted captures. Current machine audit receipts can change on rerun: freeze them with `interior_project.py snapshot --workspace "$PWD" --run-id "$RUN_ID" --input PATH --name NAME` before citing them. Do not cite a mutable master/runtime GLB as early-stage evidence that later stages will legitimately modify. The workflow pins bytes and order, not screenshot meaning or reviewer identity.++## Current audits and final gate++Author expected material policy from the intended design, not by copying actual exported values into tautological expectations. Use exact exported names, then run all current audits:++```sh+python3 "$SKILL_DIR/tools/audit_materials.py" --workspace "$PWD" --glb ./public/assets/interior/room-runtime.glb --policy ./material-policy.json+python3 "$SKILL_DIR/tools/interior_project.py" delivery-contract --workspace "$PWD" --spec scene-spec.json+python3 "$SKILL_DIR/tools/audit_delivery.py" --workspace "$PWD" --contract ./.img2/artifacts/interior/delivery-contract.json+python3 "$SKILL_DIR/tools/run_gates.py" --plugin-dir "$SKILL_DIR" --workspace "$PWD"+python3 "$SKILL_DIR/tools/interior_workflow.py" report --workspace "$PWD"+```++All eight governance stages and all three blocking gates must pass on current inputs. Binding/hash audits cannot establish fabric appearance, independent reopening, interaction correctness or photorealism. Maintain [showcase causal lessons](reference/showcase-lessons.md) without treating one room's numbers as universal settings.++## Handoff and authority++Deliver source/assumptions, scene builder/spec, resource/provenance receipts, packed master, runtime GLB plus every sidecar/viewer, separate static portable GLB, actual render/interaction/consumer evidence, dependency/setup/reproduction commands and known limits. Static portable lacks PBR relighting and browser cloth/current dye state; fixed GI/probe does not dynamically rebounce. Distinguish emulation from real-device proof and observed execution from untested generalization.++Free public CC0 discovery/download within the task scope is permitted; keep live API credit/terms distinct from asset licensing. Ask separately for paid generation, image uploads, restricted resources, public deployment or destructive unrelated changes. Technical reference pages are inspiration/evidence, not permission to redistribute their private code/assets. Do not claim publication, host installation or arbitrary-image photorealism from a local toolkit smoke run.diff --git a/VERIFICATION.md b/VERIFICATION.mdnew file mode 100644index 0000000..a764f69--- /dev/null+++ b/VERIFICATION.md@@ -0,0 +1,77 @@+# Verification — 0.2.0++Observed on 2026-10-18, macOS 14.5 arm64. Executed environments: Python 3.12.15 with NumPy 2.5.4/Pillow 12.3.0 for image tools; Python 3.11.10 with bpy 4.3.0/NumPy 1.26.4 for native production; Node 20.18.1; Three.js 0.180.0, Vite 6.4.1 and glTF Validator 2.0.0-dev.3.10. The compatibility harness is img2 0.4.0, core API 1, source revision `95c722b524118eb6dde74c1f47bff7dd1c18aef3`.++Evidence is retained in external authored workspaces under `.img2/artifacts/interior/production/`. Images, downloaded resources, generated models, private host settings and machine bootstrap paths are not part of the source release. These are mechanism/consumer checks, not a final-quality reconstruction or physical-phone certification.++## Integrated behavior and installation++- Current source: **80 Python tests passed, no skips**, in 16.755 seconds, including actual bpy packed-image, weighted-sheen, repeated-bake identity and asymmetric UV1/native transport regressions.+- Current viewer: **13 Node behavior tests passed, no skips**, in 842.301 ms. These exercise actual geometry/numerics, material-point and hem binding, input ownership/cancellation, sleeping/reduced motion, bounded navigation, manifest boundaries and decoded lightmap orientation.+- Both official source CLI and npm-published img2 0.4.0 entrypoints passed `scripts/verify_install.py`: install → link → doctor → sync → typed capability → update check → removal, across isolated Claude Code, Codex and OpenCode configurations. Each doctor reported **0 failures and 0 warnings**. Existing host configuration/source checkout were preserved; no real host account was installed or rewritten.++Reproduction commands, with the compatible interpreters/dependencies selected:++```sh+IMG2_HARNESS_SOURCE="$HARNESS" IMG2_BLENDER_PYTHON="$BLENDER_PYTHON" python3 -m unittest discover -s tests -v+VIEWER_ROOT="$W" node --test tests/viewer/*.test.mjs+python3 scripts/verify_install.py --harness-source "$HARNESS"+```++## Cold live-resource production++The source-hash-guarded Oak/Linen recipe ran in a fresh external workspace. Live Poly Haven API discovery/files/acquisition downloaded **48 files, 82,059,982 bytes**, covering 12 selected assets: five models, five scans and two HDRIs. Publisher MD5/size and local SHA receipts were recorded. Model/texture/HDRI inputs were not copied from the old showcase outputs.++Actual preparation, native geometry, source render and all five two-pass/OIDN atlas groups completed. The labelled eight-sample smoke used these atlas resolutions: architecture 256, textiles 1024, furniture 512, garden 2048, details 512. The final sequential five-group/probe/export command completed in 1031.32 seconds; this is an observed workload duration, not a model/worker benchmark.++A prior uniform 2K/4K CPU bake exceeded its 1800-second runner deadline and is **not** counted as successful. Small budgets also triggered real subpixel-UV rejection. UV-only measurements selected working per-group budgets; geometry was not deleted and the pixel-area/gutter guards were not weakened.++Independent Blender processes reopened/rendered the packed master and portable GLB. The actual scene has **208 meshes, 661,342 triangles and 18 components**; its browser loaded all five atlases and real PBR resources with no captured page errors. Actual source/native/portable contact sheet, lateral render and textile render were generated and inspected. They show coarse composition and consumer appearance, not a renewed high-resolution likeness grade.++| Cold product | Bytes | SHA256 |+|---|---:|---|+| Runtime GLB | 106,828,728 | `77c8a4f7ef0a4d2d227bd306255c27f4bfde137fbfe8577d2d3a8c753d8e72e1` |+| Portable GLB | 25,557,016 | `116463d44dd0b81835c645c041a129b8ea672921639b18261ae06a39fb5923f9` |++Both GLBs passed actual Khronos validation with **0 errors and 0 warnings**; informational unused-attribute messages remain in the receipts. The portable has five embedded images and 35 unlit materials; two glass/emission exceptions remain physically approximate. Its UV1 texture coordinates were independently inspected. Current named-material audit passed, and the delivery audit hashed all **12** manifest-discovered source/runtime/portable/native/sidecar products.++## Fresh independent scene and causal material repair++The separate asymmetric studio was authored outside the plugin: **34 meshes, 10,832 triangles, nine components, four atlases**. It is deliberately not a reconstruction of the supplied Oak/Linen image. It exercised draft → bake → probe → export, real image dye, packed-image refresh, invalidation, regeneration, viewer and independent native/portable reopening.++- External 32×32 albedo changed from SHA `2fc6f37a08d526538e6b693925c024e77509c1b875bf4de3bb5af9eddbf95094` to `f59860df30e2a3e3a624fbdb103135c6ed2aec16321e7e8da67a6b12665bb6fc`.+- After refresh, export actually rejected the stale probe. With a newly captured probe but no rebake, it separately rejected dirty atlases. Full regeneration then succeeded.+- Exported repaired GLB albedo was decoded and compared against the real PNG: **maximum 8-bit channel error 0**. Canonical oriented triangle/transform/POSITION/NORMAL/TANGENT/UV0 digest stayed `02c7483966e6af72d23ee76ec290ffce8b74612878741128d5ca360d6aaea87f`; UV1 was excluded because repacking is allowed.+- Actual repeated export initially failed because names grew from `PackedCloth__textiles` to `PackedCloth__textiles__textiles`. The permanent native regression fails before the repair and passes afterward. Reusing prepared materials/UV0 mappings preserves all ten studio material names; artist roughness 0.72 survives repeated preparation/export. Production case policy targets were migrated to stable names.+- The repaired runtime/portable again passed Khronos with zero errors/warnings. Independent consumers rendered both products. Actual UI-triggered downloads matched the current portable and packed native bytes by SHA, not merely filename.++## Native ↔ browser transport calibration++The actual asymmetric UV1/native reimport, emissive-cardinal equirectangular probe and lossless float EXR checks passed. A separate zero-specular/black-probe/no-sun fixture used rotated UV1 and the real EXR decoder, PI convention and production shader.++Its browser drawing buffer and native expected image were both **256×192 at DPR 1**, with matching projection and no image realignment. Normalized sRGB absolute error: all-pixel mean **0.00364147**; interior mean **0.00311741**, p95 **0.00784314**. The interior mask is expected nonblack pixels >0.02, eroded two pixels, 28,616 pixels. It passed the declared mean ≤0.01/p95 ≤0.02 tolerances. An intentionally vertically flipped negative control had interior mean **0.11207560**. Native, actual browser and amplified-difference images were inspected. This is transport calibration, not image likeness or a complete browser specular-probe certification.++## Real browser interaction and lifecycle++On the original studio generation, frame-paced low/mid/high cloth grips measured held-point errors **1.24–2.16 mm**; actual hem picking measured **0.094 mm**. Headers and camera pose/projection stayed unchanged during those grips, including wheel ownership, and wheel navigation resumed after release. Evidence retains transient timing rather than claiming every unpaced sample is converged.++Visible controls exercised source/3D, wireframe restoration, finishes, keyboard/reset/bounds, coverage/open/close and wind. Actual capture loss and source-mode changes cancelled grabs; settled wind-off and reduced-motion scenes stopped requesting frames. A real manifest 404 and real `WEBGL_lose_context` event each produced error UI and recovered through Retry. A 390-pixel viewport had no horizontal document overflow; actual offscreen scrolling paused frames and returning resumed them.++After the final albedo repair, a fresh persistent browser tab loaded the regenerated assets, changed the actual finish, switched source/3D and downloaded both products with matching bytes. Live reference images were fully loaded; computed heading sizes were 54.72/32 px. The static design detector's two missing-src and flat-heading warnings do not describe this live surface; its Arial preference warning was not treated as a functional defect. Vite's genuine **>500 kB chunk warning** remains (676.47 kB minified JS, 180.32 kB gzip).++The cold room also exercised a real rear-panel body grip/release: both header errors 0, camera unchanged, moving held-point lag **15.884 mm**. That is a different workload from the small studio, not a universal sub-3-mm claim.++## Eight reviews and three blocking gates++Current repaired studio products passed material and delivery audits, immutable receipt snapshotting, all eight ordered reviews and the installed SDK gate runner. The run deliberately rejected materials, refused a downstream acceptance, explicitly revised, then completed; **11 history events** remain. `interior-materials`, `interior-delivery` and `interior-workflow` each passed with exit 0.++All attestations explicitly identify this as a controlled release-mechanism fixture, **not image-likeness or final-artwork approval**. Review identity is an attestation, not cryptographic reviewer authentication. Regression coverage separately exercises changed source/policy/assets/receipts, symlink/path escapes, stale evidence and dependent-stage invalidation.++## Source packaging and limits++Build with `python3 scripts/package_plugin.py --output /absolute/release-directory`; `--output` is a directory. Extract the ZIP into a fresh location and run the behavior/official-install checks against that extracted checkout. Keep `SHA256SUMS` outside the source document rather than embedding an archive checksum in the files it hashes. The packager excludes Git metadata, dependencies/builds, environments, generated bootstraps, credentials, workspace state and generated image/model assets; fixed timestamps/modes support reproducible source ZIPs.++- Smoke resolutions/eight samples do not establish final texture density, denoising quality, glass fidelity, full-resolution realism or a mobile asset budget. The cold runtime is about 107 MB; it is not a phone-performance baseline.+- GI/probe/portable appearance remain static during runtime cloth/finish changes. Native estimates are not measured geometry/material truth; cloth is the documented rail/PBD approximation, not FEM.+- Hidden-document browser pausing, actual multitouch/touchcancel on physical devices and physical-phone performance were not certified. An old heavily instrumented tab stalled image decode after reload; identical final assets completed in a fresh persistent tab without errors. No asset/shader workaround was added for that retained-context observation.+- Local source/runtime evidence does not claim a completed GitHub Actions run, public deployment, npm publication or catalog registration. Repository hosting/visibility are separate publication checks; keep the requested source repository private.diff --git a/authoring/__init__.py b/authoring/__init__.pynew file mode 100644index 0000000..c051749--- /dev/null+++ b/authoring/__init__.py@@ -0,0 +1,87 @@+"""Explicit, workspace-bound Blender authoring. Importing this package is inert."""+from dataclasses import dataclass+from pathlib import Path+import importlib.util+import json+import re+import uuid+++def private_module(path):+ """Load without sys.modules caching: each workspace gets independent bindings."""+ spec = importlib.util.spec_from_file_location('_img2_' + uuid.uuid4().hex, path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++@dataclass+class Context:+ workspace: Path+ spec: dict+ assets: Path+ evidence: Path++ def __post_init__(self):+ self.workspace = Path(self.workspace).resolve()+ installed = Path(__file__).resolve().parents[1]+ if self.workspace.is_relative_to(installed):+ raise ValueError('Authored workspace must be outside the installed plugin tree')+ for name in ('assets', 'evidence'):+ path = Path(getattr(self, name)).resolve()+ if not path.is_relative_to(self.workspace) or path.is_relative_to(installed):+ raise ValueError(f'{name} must remain inside the authored workspace and outside the installed plugin')+ setattr(self, name, path)++ def resolve(self, relative):+ path = Path(relative)+ if path.is_absolute():+ raise ValueError(f'Expected workspace-relative path: {relative}')+ result = (self.workspace / path).resolve()+ if not result.is_relative_to(self.workspace):+ raise ValueError(f'Path escapes workspace: {relative}')+ if result.is_relative_to(Path(__file__).resolve().parents[1]):+ raise ValueError('Workspace paths must not resolve into the installed plugin tree')+ return result++ @property+ def helpers(self):+ if not hasattr(self, '_helpers'):+ module = private_module(Path(__file__).with_name('geometry.py'))+ module.ROOT = self.workspace+ module.CONTEXT = self+ # Public ergonomic names for the reusable geometry primitives.+ for name in ('activate', 'tag', 'image', 'material', 'project_uv', 'mesh', 'box',+ 'tube', 'lathe', 'cushion', 'bounds', 'import_model', 'light'):+ setattr(module, name, getattr(module, '_' + name))+ module.curtain = module.curtain_panel+ self._helpers = module+ return self._helpers+++def context_from_args(args):+ workspace = Path(args.workspace).resolve(strict=True)+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,95}', args.run_id):+ raise ValueError('run-id must be a simple alphanumeric slug')+ context = Context(workspace, {}, workspace / 'public/assets/interior',+ workspace / '.img2/artifacts/interior/production' / args.run_id)+ context.spec = json.loads(context.resolve(args.spec).read_text())+ dimensions = context.spec['authoring']['sourceImageSize']+ if len(dimensions) != 2 or any(not isinstance(v, int) or v <= 0 for v in dimensions):+ raise ValueError('sourceImageSize must contain two positive integer pixel dimensions')+ context.resolve(context.spec['source']).resolve(strict=True)+ for path in (context.assets, context.evidence):+ context.resolve(path.relative_to(workspace)).mkdir(parents=True, exist_ok=True)+ return context+++def bound_module(name, context):+ module = private_module(Path(__file__).with_name(name + '.py'))+ module.CONTEXT = context+ module.ROOT = context.workspace+ module.ASSETS = context.assets+ module.EVIDENCE = context.evidence+ module.WORK = context.evidence+ module.MASTER = context.assets / 'room-master.blend'+ module.CONTRACT = context.spec+ return modulediff --git a/authoring/calibration.py b/authoring/calibration.pynew file mode 100644index 0000000..9bdd6d4--- /dev/null+++ b/authoring/calibration.py@@ -0,0 +1,192 @@+"""Evidence-only runtime fixture for EXR row orientation, rotated UV1 and PI transport.++The Cycles reference evaluates the known Lambertian outgoing radiance albedo*field.+The runtime GLB instead contains only a zero-specular PBR material; the actual+viewer must reconstruct that radiance from its EXR lightmap at intensity PI.+No browser comparison or realism approval is asserted by generating this fixture.+"""+import hashlib+import json+import math+from pathlib import Path+++def runtime_fixture(context, args):+ import bpy+ import numpy as np+ from mathutils import Vector+ from authoring import Context, bound_module++ child = context.evidence / 'calibration-viewer'+ assets = child / 'public/assets/interior'+ assets.mkdir(parents=True, exist_ok=False)+ local = Context(child, context.spec, assets, child)+ pipeline = bound_module('pipeline', local)+ bpy.ops.wm.read_factory_settings(use_empty=True)+ scene = bpy.context.scene+ h = local.helpers+ width = max(64, args.width)+ height = max(1, round(width * 3 / 4))+ aspect = width / height+ scene.render.engine = 'CYCLES'+ scene.cycles.samples = args.samples+ scene.cycles.use_denoising = False+ scene.cycles.seed = 17+ scene.render.resolution_x, scene.render.resolution_y = width, height+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = 'PNG'+ scene.render.image_settings.color_mode = 'RGBA'+ scene.view_settings.view_transform = 'Khronos PBR Neutral'+ scene.view_settings.look = 'None'+ scene.view_settings.exposure = 0+ scene.view_settings.gamma = 1+ scene.render.film_transparent = False+ world = bpy.data.worlds.new('Calibration.BlackWorld')+ world.use_nodes = True+ world.node_tree.nodes['Background'].inputs['Color'].default_value = (0,0,0,1)+ world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0+ scene.world = world++ # Bottom-up Blender image rows; asymmetric continuous field plus a distinct+ # upper-left region means row flips, rotations and PI errors cannot cancel.+ nx, ny = 32, 16+ field = np.empty((ny,nx,4), dtype=np.float32)+ for y in range(ny):+ for x in range(nx):+ u, v = x/(nx-1), y/(ny-1)+ field[y,x] = (.12 + .9*u, .08 + .7*v,+ .15 + (.8 if x < 9 and y > 10 else .15*u*v), 1)+ atlas = pipeline.create_target('RuntimeCalibrationField', nx)+ atlas.scale(nx, ny)+ atlas.pixels.foreach_set(field.ravel())+ exr = assets / 'lightmap-calibration.exr'+ pipeline.save_linear_exr(atlas, exr)+ decoded = bpy.data.images.load(str(exr), check_existing=False)+ actual = np.asarray(decoded.pixels[:], dtype=np.float32).reshape(ny,nx,4)+ exr_error = float(np.max(np.abs(actual-field)))+ if exr_error > 1e-6:+ raise RuntimeError(f'Lossless EXR field changed decoded linear pixels: {exr_error}')+ bpy.data.images.remove(atlas)+ atlas = decoded+ atlas.colorspace_settings.name = 'Linear Rec.709'+ black = bpy.data.images.new('BlackProbe', width=32, height=16, alpha=True, float_buffer=True)+ black.colorspace_settings.name = 'Linear Rec.709'+ black.pixels[:] = [0,0,0,1] * (32*16)+ pipeline.save_linear_exr(black, assets / 'room-environment.exr')++ albedo = (.63,.42,.27)+ material = h.material('Calibration.PBR', albedo, roughness=1.0)+ shader = next(n for n in material.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')+ shader.inputs['Specular IOR Level'].default_value = 0+ shader.inputs['Metallic'].default_value = 0+ shader.inputs['Sheen Weight'].default_value = 0+ obj = h.mesh('calibration.rotated-uv1', [(-1.2,0,.3),(1.2,0,.3),(1.2,0,2.1),(-1.2,0,2.1)],+ [(0,1,2,3)], material, 'calibration')+ obj['lightmap'] = 'calibration'+ uv0 = [(0,0),(1,0),(1,1),(0,1)]+ uv1 = [(v,1-u) for u,v in uv0]+ for corner, value in zip(obj.data.uv_layers['UV0'].data, uv0):+ corner.uv = value+ layer = obj.data.uv_layers.new(name='Lightmap')+ for corner, value in zip(layer.data, uv1):+ corner.uv = value+ obj.data.uv_layers[0].active_render = True+ obj.data.uv_layers.active_index = 0+ data = bpy.data.cameras.new('Calibration.PerspectiveCamera')+ data.type = 'PERSP'+ data.lens, data.sensor_width = 35, 36+ data.sensor_fit = 'HORIZONTAL'+ data.clip_start, data.clip_end = .03, 100+ camera = bpy.data.objects.new('Calibration.PerspectiveCamera', data)+ scene.collection.objects.link(camera)+ camera.location = (0,-3,1.2)+ target = Vector((0,0,1.2))+ camera.rotation_euler = (target-camera.location).to_track_quat('-Z','Y').to_euler()+ scene.camera = camera+ bpy.context.view_layer.update()+ pipeline.export_gltf(assets / 'room-runtime.glb', tangents=True)++ # Cycles expected radiance, independent of the runtime's lightMap machinery.+ expected_material = bpy.data.materials.new('Calibration.ExpectedLambertianRadiance')+ expected_material.use_nodes = True+ tree = expected_material.node_tree+ tree.nodes.clear()+ output = tree.nodes.new('ShaderNodeOutputMaterial')+ emission = tree.nodes.new('ShaderNodeEmission')+ multiply = tree.nodes.new('ShaderNodeMixRGB')+ multiply.blend_type = 'MULTIPLY'+ multiply.inputs[0].default_value = 1+ multiply.inputs[2].default_value = (*albedo,1)+ texture = tree.nodes.new('ShaderNodeTexImage')+ texture.image = atlas+ texture.interpolation = 'Linear'+ texture.extension = 'EXTEND'+ uv = tree.nodes.new('ShaderNodeUVMap')+ uv.uv_map = 'Lightmap'+ tree.links.new(uv.outputs['UV'], texture.inputs['Vector'])+ tree.links.new(texture.outputs['Color'], multiply.inputs[1])+ tree.links.new(multiply.outputs['Color'], emission.inputs['Color'])+ tree.links.new(emission.outputs[0], output.inputs['Surface'])+ obj.data.materials[0] = expected_material+ expected = context.evidence / 'calibration-runtime-expected.png'+ scene.render.filepath = str(expected)+ bpy.ops.render.render(write_still=True)+ # The child source is the actual rendered calibration image, never a substitute+ # reference photograph. Main may register it with interior_project start.+ (child / 'public/assets/reference.png').write_bytes(expected.read_bytes())+ pipeline.save_master()++ # Genuine portable static appearance, with Neutral applied once to its pixels.+ portable_pixels = field.copy()+ portable_pixels[...,:3] *= np.asarray(albedo, dtype=np.float32)+ portable_image = bpy.data.images.new('Calibration.Portable', width=nx, height=ny, alpha=True, float_buffer=True)+ portable_image.colorspace_settings.name = 'Linear Rec.709'+ portable_image.pixels.foreach_set(portable_pixels.ravel())+ portable_path = assets / 'portable-calibration.png'+ portable_image.save_render(str(portable_path), scene=scene)+ bpy.data.images.remove(portable_image)+ portable_image = bpy.data.images.load(str(portable_path), check_existing=False)+ portable_image.colorspace_settings.name = 'sRGB'+ portable_material = bpy.data.materials.new('Calibration.PortableUnlit')+ portable_material.use_nodes = True+ tree = portable_material.node_tree+ tree.nodes.clear()+ output = tree.nodes.new('ShaderNodeOutputMaterial')+ background = tree.nodes.new('ShaderNodeBackground')+ texture = tree.nodes.new('ShaderNodeTexImage')+ texture.image = portable_image+ uv = tree.nodes.new('ShaderNodeUVMap')+ uv.uv_map = 'Lightmap'+ tree.links.new(uv.outputs['UV'], texture.inputs['Vector'])+ tree.links.new(texture.outputs['Color'], background.inputs['Color'])+ tree.links.new(background.outputs[0], output.inputs['Surface'])+ try:+ obj.data.materials[0] = portable_material+ pipeline.export_gltf(assets / 'room-portable.glb')+ finally:+ obj.data.materials[0] = expected_material++ fov = math.degrees(2*math.atan(data.sensor_width/(2*data.lens*aspect)))+ manifest = {+ 'schemaVersion':2, 'title':'EXR UV1 / PI transport calibration', 'sourceKind':'render',+ 'sourceImage':'/assets/reference.png', 'sourceImageSize':[width,height], 'sourceAspect':aspect,+ 'model':'/assets/interior/room-runtime.glb', 'portableModel':'/assets/interior/room-portable.glb',+ 'blender':'/assets/interior/room-master.blend', 'environment':'/assets/interior/room-environment.exr',+ 'background':'/assets/interior/room-environment.exr', 'backgroundIntensity':1,+ 'camera':{'position':pipeline.three_point(camera.location), 'target':pipeline.three_point(target), 'fov':fov},+ 'roomBounds':{'min':[-3,0,-2], 'max':[3,3,4]}, 'views':{},+ 'lighting':{'model':'ambient-bake+shadowed-sun-v1', 'sun':None},+ 'lightmaps':[{'id':'calibration', 'url':'/assets/interior/lightmap-calibration.exr', 'intensity':math.pi}],+ 'variants':[], 'toneMapping':'neutral', 'exposure':1,+ 'stats':{'meshes':1, 'triangles':2, 'components':1, 'lightmapAtlases':1},+ 'sourceLimit':'Analytic transport fixture, not an image reconstruction or realism grade.',+ 'portability':'Runtime PBR uses the EXR sidecar; portable embeds static Neutral diffuse. Native reference evaluates analytic Lambertian radiance.'+ }+ (assets / 'manifest.json').write_text(json.dumps(manifest, indent=2))+ return {'viewerWorkspace':str(child), 'manifest':str(assets/'manifest.json'),+ 'expectedRender':str(expected), 'renderSize':[width,height],+ 'uv0':uv0, 'uv1':uv1, 'linearAlbedo':albedo, 'lightmapIntensity':math.pi,+ 'decodedExrMaxError':exr_error, 'exrSha256':hashlib.sha256(exr.read_bytes()).hexdigest(),+ 'camera':manifest['camera'], 'probe':'Actual all-black float EXR; no IBL contribution',+ 'browserComparison':'Not performed by native stage; compare actual viewer canvas against expectedRender at identical dimensions and source camera',+ 'expectedRadiance':'linearAlbedo * bilinear(EXR field, rotated UV1); runtime Lambertian PI cancels 1/PI'}diff --git a/authoring/geometry.py b/authoring/geometry.pynew file mode 100755index 0000000..fa73fe9--- /dev/null+++ b/authoring/geometry.py@@ -0,0 +1,418 @@+#!/usr/bin/env python3+"""Reusable metric geometry/PBR/UV helpers, bound explicitly by Context.helpers.++Coordinates are native Blender Z-up metres. Importing does not author a scene.+"""+from __future__ import annotations++import math+from pathlib import Path++import bpy+import bmesh+from mathutils import Matrix, Vector+from mathutils.bvhtree import BVHTree++# This implementation is loaded into a private namespace by Context.helpers.+# ROOT and CONTEXT are bound only on that instance, never on this imported module.+++def _activate(obj):+ bpy.ops.object.select_all(action='DESELECT')+ obj.select_set(True)+ bpy.context.view_layer.objects.active = obj+++def _tag(obj, name, component, finish=None):+ obj.name = name+ obj['component'] = component+ obj['physical_id'] = name+ if finish:+ obj['finish'] = finish+ return obj+++def _image(path, color=True):+ path = Path(path)+ path = CONTEXT.resolve(path.relative_to(ROOT) if path.is_absolute() else path)+ image = bpy.data.images.load(str(path), check_existing=True)+ image.colorspace_settings.name = 'sRGB' if color else 'Non-Color'+ return image+++def _material(name, color, roughness=0.6, metallic=0.0, maps=None,+ color_path=None, normal_strength=0.3):+ mat = bpy.data.materials.new(name)+ mat.use_nodes = True+ mat.diffuse_color = (*color, 1)+ nodes, links = mat.node_tree.nodes, mat.node_tree.links+ nodes.clear()+ output = nodes.new('ShaderNodeOutputMaterial')+ output.is_active_output = True+ shader = nodes.new('ShaderNodeBsdfPrincipled')+ shader.inputs['Base Color'].default_value = (*color, 1)+ shader.inputs['Roughness'].default_value = roughness+ shader.inputs['Metallic'].default_value = metallic+ links.new(shader.outputs['BSDF'], output.inputs['Surface'])+ if color_path is None and maps and maps.get('color'):+ color_path = CONTEXT.resolve(maps['color'])+ if color_path:+ texture = nodes.new('ShaderNodeTexImage')+ texture.image = _image(color_path)+ texture.label = 'UV0 albedo, sRGB'+ links.new(texture.outputs['Color'], shader.inputs['Base Color'])+ if maps and maps.get('roughness'):+ texture = nodes.new('ShaderNodeTexImage')+ texture.image = _image(CONTEXT.resolve(maps['roughness']), False)+ links.new(texture.outputs['Color'], shader.inputs['Roughness'])+ if maps and maps.get('normal'):+ texture = nodes.new('ShaderNodeTexImage')+ texture.image = _image(CONTEXT.resolve(maps['normal']), False)+ normal = nodes.new('ShaderNodeNormalMap')+ normal.uv_map = 'UV0'+ normal.inputs['Strength'].default_value = normal_strength+ links.new(texture.outputs['Color'], normal.inputs['Color'])+ links.new(normal.outputs['Normal'], shader.inputs['Normal'])+ return mat+++++def _project_uv(obj, metres=1.0):+ """Local metric box projection, independent of object placement/rotation."""+ mesh = obj.data+ mesh.update()+ # Authored primitives often arrive with a default UVMap. Replace it rather+ # than appending UV0: the baker must reserve index 1 for its lightmap.+ # Imported native glTF UVs bypass this projection when already present.+ for layer in list(mesh.uv_layers):+ mesh.uv_layers.remove(layer)+ uv = mesh.uv_layers.new(name='UV0')+ mesh.uv_layers.active = uv+ uv.active_render = True+ for face in mesh.polygons:+ axis = max(range(3), key=lambda k: abs(face.normal[k]))+ a, b = ((1, 2), (0, 2), (0, 1))[axis]+ sign = -1 if face.normal[axis] < 0 else 1+ for index in face.loop_indices:+ point = mesh.vertices[mesh.loops[index].vertex_index].co+ uv.data[index].uv = (sign * point[a] / metres, point[b] / metres)+ obj['uv_tile_metres'] = metres+++def _mesh(name, vertices, faces, mat, component, finish=None, tile=1.0):+ data = bpy.data.meshes.new(name + '.geometry')+ data.from_pydata(vertices, [], faces)+ data.update()+ obj = bpy.data.objects.new(name, data)+ bpy.context.scene.collection.objects.link(obj)+ _tag(obj, name, component, finish)+ obj.data.materials.append(mat)+ _project_uv(obj, tile)+ return obj+++def _box(name, location, size, mat, component, bevel=0.0, tile=1.0,+ finish=None):+ bpy.ops.mesh.primitive_cube_add(size=1, location=location)+ obj = _tag(bpy.context.object, name, component, finish)+ obj.dimensions = size+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ obj.data.materials.append(mat)+ if bevel:+ modifier = obj.modifiers.new('Physical softened edges', 'BEVEL')+ modifier.width = bevel+ modifier.segments = 4+ bpy.ops.object.modifier_apply(modifier=modifier.name)+ _project_uv(obj, tile)+ return obj+++def _tube(name, points, radius, mat, component, cyclic=False, finish=None):+ curve = bpy.data.curves.new(name + '.path', 'CURVE')+ curve.dimensions = '3D'+ curve.resolution_u = 1+ curve.bevel_depth = radius+ curve.bevel_resolution = 2+ curve.use_fill_caps = True+ spline = curve.splines.new('POLY')+ spline.points.add(len(points) - 1)+ for p, co in zip(spline.points, points):+ p.co = (*co, 1)+ spline.use_cyclic_u = cyclic+ obj = bpy.data.objects.new(name, curve)+ bpy.context.scene.collection.objects.link(obj)+ _activate(obj)+ bpy.ops.object.convert(target='MESH')+ obj = _tag(bpy.context.object, name, component, finish)+ obj['bake_detail'] = True+ obj.data.materials.append(mat)+ _project_uv(obj, 1.1 if finish == 'sofa' else 0.25)+ for face in obj.data.polygons:+ face.use_smooth = True+ return obj+++def _lathe(name, profile, mat, component, location=(0, 0, 0), segments=64):+ # Closed meridian profile makes a shell with actual inner and outer faces.+ vertices, rings, faces = [], [], []+ for r, z in profile:+ ring = []+ for i in range(1 if r == 0 else segments):+ ring.append(len(vertices))+ vertices.append((r * math.cos(i * math.tau / segments),+ r * math.sin(i * math.tau / segments), z))+ rings.append(ring)+ for j, ring in enumerate(rings):+ following = rings[(j + 1) % len(rings)]+ if len(ring) == len(following) == 1:+ continue+ for i in range(segments):+ n = (i + 1) % segments+ if len(ring) == 1:+ faces.append((ring[0], following[n], following[i]))+ elif len(following) == 1:+ faces.append((ring[i], ring[n], following[0]))+ else:+ faces.append((ring[i], ring[n], following[n], following[i]))+ obj = _mesh(name, vertices, faces, mat, component, tile=0.5)+ obj.location = location+ for face in obj.data.polygons:+ face.use_smooth = True+ return obj+++++def _cushion(name, location, size, mat, rotation=(0, 0, 0), phase=0.0,+ exponent=5.0, seams=True, loose=False, component='sofa',+ finish='sofa', tile=0.75, seam_levels=None, seam_radius=0.0011, outline=None, resolution=28):+ """Closed dense cloth volume, with localized perimeter gathers and optional sewn outline.++ Each face starts as a resolution-by-resolution grid. Deformation happens on actual vertices,+ including underside; piping is seated on the actual tessellated cloth mesh.+ """+ bm = bmesh.new()+ bmesh.ops.create_cube(bm, size=2)+ bmesh.ops.subdivide_edges(bm, edges=list(bm.edges), cuts=resolution-1, use_grid_fill=True)+ # Irregular, localized cloth gathers, not a periodic corrugated panel.+ folds = tuple((center+0.025*math.sin(phase+i), width, depth, zc, span)+ for i, (center, width, depth, zc, span) in enumerate((+ (-0.83,0.045,0.0070,-0.20,0.65), (-0.57,0.060,-0.0035,0.35,0.45),+ (-0.17,0.040,0.0022,-0.30,0.55), (0.36,0.050,-0.0026,0.20,0.60),+ (0.68,0.040,0.0050,-0.15,0.70), (0.86,0.045,-0.0065,0.10,0.55)+ ))) if seams and not loose else ()+ fold_bend = 0.025*math.sin(phase)++ def shape(p):+ denominator = sum(abs(v) ** exponent for v in p) ** (1 / exponent)+ x, y, z = (v / denominator for v in p)+ if loose:+ # A sewn square pillow has thin pointed corners, not a rounded balloon.+ x, y = p[0], p[1]+ puff = 0.16 + 0.84 * math.sqrt(max((1 - x*x) * (1 - y*y), 0))+ z = p[2] * puff+ x *= 1 - 0.035 * (1 - y*y)+ y *= 1 - 0.035 * (1 - p[0]*p[0])+ # Local seam gathers and front-panel folds, not global displacement noise.+ edge = math.exp(-((abs(y) - 0.86) / 0.16) ** 2)+ edge2 = math.exp(-((abs(x) - 0.86) / 0.15) ** 2)+ wrinkle = (math.sin(39 * x + phase + 3 * y) * edge+ + 0.65 * math.sin(43 * y - phase) * edge2)+ top = abs(p[2]) ** 3 if loose else abs(z) ** 3+ crease = 0.003 * math.exp(-((abs(y) - 0.93) / 0.045) ** 2)+ # A shallow off-centre compression, not high-frequency surface noise.+ sag = (0.009 * max(z, 0) ** 2+ * math.exp(-((x - 0.16 * math.sin(phase)) / 0.60) ** 2+ - ((y + 0.08) / 0.65) ** 2)) if seams else 0.0+ front_fold = 0.0+ for center, width, depth, zc, span in folds:+ q = (x-center-fold_bend*z*z)/width+ front_fold += depth*q*math.exp(-0.5*q*q-((z-zc)/span)**2)+ front_fold *= max(-y, 0)**6+ if loose:+ corner_fold = (+ math.exp(-((x - 0.63 + 0.26*y) / 0.055) ** 2 - ((y - 0.65) / 0.35) ** 2)+ + 0.75 * math.exp(-((x + 0.62 - 0.20*y) / 0.065) ** 2 - ((y + 0.58) / 0.38) ** 2))+ crease += 0.018 * corner_fold+ px, py = x * size[0] / 2, y * size[1] / 2+ if outline is not None:+ # A source-guided, deformed seam is lofted into a closed bag, not a photo plane.+ u, v = (x+1)/2, (y+1)/2+ px = ((1-u)*outline[0][0]+u*outline[1][0])*v + ((1-u)*outline[3][0]+u*outline[2][0])*(1-v)+ py = ((1-u)*outline[0][1]+u*outline[1][1])*v + ((1-u)*outline[3][1]+u*outline[2][1])*(1-v)+ return (px, py + front_fold,+ z * size[2] / 2 + (1 if z >= 0 else -1) * top * ((0 if loose else 0.0014) * wrinkle - crease) - sag)++ for vertex in bm.verts:+ vertex.co = shape(vertex.co)+ bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))+ data = bpy.data.meshes.new(name + '.geometry')+ bm.to_mesh(data)+ bm.free()+ obj = bpy.data.objects.new(name, data)+ bpy.context.scene.collection.objects.link(obj)+ _tag(obj, name, component, finish)+ obj.data.materials.append(mat)+ _project_uv(obj, tile)+ obj.location = location+ obj.rotation_euler = rotation+ for face in data.polygons:+ face.use_smooth = True+ if seams:+ surface = BVHTree.FromPolygons(+ [vertex.co for vertex in data.vertices], [face.vertices[:] for face in data.polygons])+ levels = seam_levels if seam_levels is not None else ((0.0,) if loose else (-0.65,))+ for index, z in enumerate(levels):+ points = []+ radial = (1 - abs(z) ** exponent) ** (1 / exponent)+ for i in range(160):+ angle = math.tau * i / 160+ c, s = math.cos(angle), math.sin(angle)+ if loose:+ scale = max(abs(c), abs(s))+ p = (c / scale, s / scale, z)+ else:+ p = (math.copysign(abs(c) ** (2 / exponent), c) * radial,+ math.copysign(abs(s) ** (2 / exponent), s) * radial, z)+ # The analytic cloth differs from its tessellated surface by millimetres.+ # Seat the welt on the actual mesh, not partly inside those facets.+ point, normal, _, _ = surface.find_nearest(Vector(shape(p)))+ points.append(point + normal * (seam_radius * 0.8))+ seam = _tube(name + f'.welt.{index}',+ points, seam_radius, mat, component, True, finish)+ seam.location = location+ seam.rotation_euler = rotation+ return obj+++++++++def _bounds(objects):+ points = [obj.matrix_world @ Vector(corner)+ for obj in objects for corner in obj.bound_box]+ return ([min(p[i] for p in points) for i in range(3)],+ [max(p[i] for p in points) for i in range(3)])+++def _import_model(path, component, center, height=None, width=None, yaw=0.0):+ path = Path(path)+ path = CONTEXT.resolve(path.relative_to(ROOT) if path.is_absolute() else path)+ if (height is None) == (width is None):+ raise ValueError('Specify exactly one positive import height or width')+ if (height if height is not None else width) <= 0:+ raise ValueError('Import dimension must be positive')+ before = set(bpy.data.objects)+ bpy.ops.import_scene.gltf(filepath=str(path))+ created = sorted(set(bpy.data.objects) - before, key=lambda o: o.name)+ meshes = [o for o in created if o.type == 'MESH']+ bpy.context.view_layer.update()+ low, high = _bounds(meshes)+ scale = height / (high[2] - low[2]) if height else width / (high[0] - low[0])+ origin = Vector(((low[0] + high[0]) / 2, (low[1] + high[1]) / 2, low[2]))+ placement = (Matrix.Translation(Vector(center)) @ Matrix.Rotation(yaw, 4, 'Z')+ @ Matrix.Scale(scale, 4) @ Matrix.Translation(-origin))+ # Flatten imported hierarchy but preserve each child's complete world matrix.+ matrices = {obj: obj.matrix_world.copy() for obj in meshes}+ for index, obj in enumerate(meshes):+ obj.parent = None+ obj.matrix_world = placement @ matrices[obj]+ _tag(obj, f'{component}.{index:02d}.{obj.name}', component)+ obj['source_asset'] = str(path.relative_to(ROOT))+ if obj.data.uv_layers:+ old_uv_name = obj.data.uv_layers[0].name+ obj.data.uv_layers[0].name = 'UV0'+ obj.data.uv_layers.active_index = 0+ obj.data.uv_layers[0].active_render = True+ for material in obj.data.materials:+ if material and material.use_nodes:+ for node in material.node_tree.nodes:+ if node.type in {'NORMAL_MAP', 'UVMAP'} and node.uv_map == old_uv_name:+ node.uv_map = 'UV0'+ else:+ _project_uv(obj)+ for obj in created:+ if obj.type != 'MESH':+ bpy.data.objects.remove(obj, do_unlink=True)+ bpy.context.view_layer.update()+ return meshes+++++def _light(name, kind, position, target, energy, color):+ data = bpy.data.lights.new(name, kind)+ data.energy, data.color = energy, color+ obj = bpy.data.objects.new(name, data)+ bpy.context.scene.collection.objects.link(obj)+ obj.location = position+ obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler()+ return obj+++++def curtain_panel(name, origin, rail, depth, width, closed_width, height, material,+ panel_id='panel', floor=0.02, folds=5, fabric_width=None, tile=0.65):+ """Create cloth, hems and hooks in an explicit native Z-up horizontal frame.++ origin is the horizontal start of the rail at z=0; rail and depth are+ orthogonal horizontal unit vectors. All generated geometry is world-space.+ Metadata vectors alone are converted to glTF Y-up for the runtime solver.+ """+ rail, depth, origin = Vector(rail), Vector(depth), Vector(origin)+ if (abs(rail.length-1) > 1e-6 or abs(depth.length-1) > 1e-6+ or abs(rail.dot(depth)) > 1e-6 or abs(rail.z)+abs(depth.z)+abs(origin.z) > 1e-6):+ raise ValueError('Curtain requires horizontal orthonormal rail/depth and origin.z=0')+ if min(width, closed_width, height, tile) <= 0 or folds < 1:+ raise ValueError('Curtain dimensions and folds must be positive')+ fabric_width = fabric_width or closed_width * 1.2+ convert = lambda p: [p[0], p[2], -p[1]]+ metadata = {'curtain_id': panel_id, 'curtain_direction': 1,+ 'curtain_anchor': 0.0, 'curtain_open_width': width,+ 'curtain_closed_width': closed_width, 'curtain_height': height,+ 'curtain_floor': floor, 'curtain_folds': folds,+ 'curtain_fabric_width': fabric_width, 'curtain_tile': tile,+ 'curtain_rail_axis': convert(rail), 'curtain_depth_axis': convert(depth),+ 'curtain_plane_origin': convert(origin)}++ def attach(obj, part):+ for key, value in metadata.items():+ obj[key] = value+ obj['curtain_part'] = part+ return obj++ nx, nz = 100, 32+ vertices, faces = [], []+ for j in range(nz+1):+ v = j/nz+ for i in range(nx+1):+ u = i/nx+ p = origin + rail * (width*u) + depth * (0.06 * math.sin(u*math.tau*folds))+ p.z = floor + height*v+ vertices.append(tuple(p))+ for j in range(nz):+ for i in range(nx):+ a = j*(nx+1)+i+ faces.append((a, a+1, a+nx+2, a+nx+1))+ obj = attach(_mesh(name, vertices, faces, material, 'curtains'), 'cloth')+ for polygon in obj.data.polygons:+ polygon.use_smooth = True+ for loop in polygon.loop_indices:+ j, i = divmod(obj.data.loops[loop].vertex_index, nx+1)+ obj.data.uv_layers['UV0'].data[loop].uv = (i/nx*fabric_width/tile, j/nz*height/tile)+ for j, v, label in ((0, 0, 'bottom'), (nz, 1, 'top')):+ hem = attach(_tube(name+'.'+label, vertices[j*(nx+1):(j+1)*(nx+1)],+ 0.003, material, 'curtains'), 'hem')+ hem['curtain_v'] = v+ for i in range(folds+1):+ p = origin + rail*(width*i/folds)+ p.z = floor+height+ hook = attach(_tube(name+f'.hook.{i}', [p, p+Vector((0,0,0.035))],+ 0.003, material, 'curtains'), 'hook')+ hook['curtain_u'] = i/folds+ return objdiff --git a/authoring/inspection.py b/authoring/inspection.pynew file mode 100644index 0000000..0b3f8b8--- /dev/null+++ b/authoring/inspection.py@@ -0,0 +1,162 @@+"""Reopen the authored master or import the portable GLB and render it as a consumer.++Run with the project's bpy Python. Portable colors already contain the Neutral+view transform, so its independent render uses Standard rather than applying+Neutral twice. A neutral world is authored for the portable inspection; glTF+has no embedded environment-light/background contract.+"""+from argparse import ArgumentParser+from collections import Counter+import hashlib+import json+from pathlib import Path+import struct+import time++import bpy+import bmesh+import numpy as np++++def glb_json(path):+ with path.open('rb') as stream:+ magic, version, size = struct.unpack('<4sII', stream.read(12))+ if magic != b'glTF' or version != 2 or size != path.stat().st_size:+ raise RuntimeError(f'Invalid GLB header: {path.name}')+ length, kind = struct.unpack('<I4s', stream.read(8))+ if kind != b'JSON':+ raise RuntimeError(f'Missing GLB JSON chunk: {path.name}')+ return json.loads(stream.read(length))+++def component_of(obj):+ while obj is not None:+ if obj.get('component'):+ return obj['component']+ obj = obj.parent+ return None+++def audit(scene):+ rows = []+ for obj in scene.objects:+ if obj.type != 'MESH':+ continue+ component = component_of(obj)+ if not component or not obj.data.uv_layers:+ raise RuntimeError(f'Missing component or UVs: {obj.name}')+ if obj.get('lightmap') and len(obj.data.uv_layers) != 2:+ raise RuntimeError(f'Baked surface does not have exactly UV0 and UV1: {obj.name}')+ coordinates = np.empty(len(obj.data.vertices)*3, dtype=np.float32)+ obj.data.vertices.foreach_get('co', coordinates)+ if not np.isfinite(coordinates).all():+ raise RuntimeError(f'Non-finite positions: {obj.name}')+ for layer in obj.data.uv_layers:+ uv = np.empty(len(layer.data)*2, dtype=np.float32)+ layer.data.foreach_get('uv', uv)+ if not np.isfinite(uv).all():+ raise RuntimeError(f'Non-finite UV coordinates: {obj.name}:{layer.name}')+ obj.data.calc_loop_triangles()+ row = {'name': obj.name, 'component': component, 'vertices': len(obj.data.vertices),+ 'triangles': len(obj.data.loop_triangles), 'uvLayers': [layer.name for layer in obj.data.uv_layers]}+ if component == 'sofa':+ # Weld UV/normal export seams on an audit-only copy; never mutate the asset.+ mesh = bmesh.new()+ mesh.from_mesh(obj.data)+ bmesh.ops.remove_doubles(mesh, verts=list(mesh.verts), dist=1e-6)+ row['boundaryEdgesAfterWelding'] = sum(edge.is_boundary for edge in mesh.edges)+ row['nonManifoldEdgesAfterWelding'] = sum(not edge.is_manifold for edge in mesh.edges)+ mesh.free()+ if row['nonManifoldEdgesAfterWelding']:+ raise RuntimeError(f'Open or non-manifold authored sofa component: {obj.name}')+ rows.append(row)+ if not rows:+ raise RuntimeError('No imported scene geometry')+ return rows+++def run(args):+ started = time.perf_counter()+ asset = ASSETS / ('room-master.blend' if args.asset == 'master' else 'room-portable.glb')+ extension_summary = None+ if args.asset == 'master':+ bpy.ops.wm.open_mainfile(filepath=str(asset))+ missing = [image.name for image in bpy.data.images+ if image.source in {'FILE', 'TILED'} and not image.packed_file and not image.packed_files]+ if missing:+ raise RuntimeError(f'Unpacked master images: {missing}')+ else:+ document = glb_json(asset)+ extension_summary = {'used': document.get('extensionsUsed', []),+ 'unlitMaterials': sum('KHR_materials_unlit' in material.get('extensions', {})+ for material in document.get('materials', [])),+ 'materials': len(document.get('materials', [])),+ 'embeddedImages': len(document.get('images', []))}+ if not extension_summary['unlitMaterials'] or any('uri' in image for image in document.get('images', [])):+ raise RuntimeError('Portable GLB lacks embedded static unlit appearance')+ if any('uri' in buffer for buffer in document.get('buffers', [])):+ raise RuntimeError('Portable GLB has external buffers')+ unlit_coordinates = {+ material.get('pbrMetallicRoughness', {}).get('baseColorTexture', {}).get('texCoord', 0)+ for material in document.get('materials', [])+ if 'KHR_materials_unlit' in material.get('extensions', {})+ }+ if unlit_coordinates != {1}:+ raise RuntimeError(f'Portable appearance does not sample the baked UV1 atlas: {unlit_coordinates}')+ extension_summary['unlitTextureCoordinates'] = sorted(unlit_coordinates)+ bpy.ops.wm.read_factory_settings(use_empty=True)+ bpy.ops.import_scene.gltf(filepath=str(asset))+ world = bpy.data.worlds.new('PortableInspection.NeutralWorld')+ world.use_nodes = True+ world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.35, 0.35, 0.35, 1)+ world.node_tree.nodes['Background'].inputs['Strength'].default_value = 1+ bpy.context.scene.world = world+ scene = bpy.context.scene+ cameras = [obj for obj in scene.objects if obj.type == 'CAMERA']+ if not cameras:+ raise RuntimeError('Export lost its authored camera')+ scene.camera = scene.camera or cameras[0]+ rows = audit(scene)+ scene.render.engine = 'CYCLES'+ from mathutils import Vector+ pose = (CONTRACT['authoring']['cameraEstimate'] if args.view == 'source'+ else CONTRACT['authoring']['inspectionViews'][args.view])+ scene.camera.rotation_mode = 'XYZ'+ scene.camera.location = pose['position']+ scene.camera.rotation_euler = (Vector(pose['target']) - scene.camera.location).to_track_quat('-Z', 'Y').to_euler()+ scene.cycles.device = 'CPU'+ scene.cycles.samples = args.samples+ scene.cycles.use_denoising = True+ scene.cycles.seed = 17+ scene.render.resolution_x = args.width+ w, h = CONTRACT['authoring']['sourceImageSize']+ scene.render.resolution_y = max(1, round(args.width * h / w))+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = 'PNG'+ scene.render.image_settings.color_mode = 'RGB'+ scene.view_settings.view_transform = 'Khronos PBR Neutral' if args.asset == 'master' else 'Standard'+ scene.view_settings.look = 'None'+ scene.view_settings.exposure = 0+ scene.view_settings.gamma = 1+ output = EVIDENCE / f'reimport-{args.asset}-{args.view}.png'+ scene.render.filepath = str(output)+ bpy.ops.render.render(write_still=True)+ with asset.open('rb') as stream:+ digest = hashlib.file_digest(stream, 'sha256').hexdigest()+ receipt = {'asset': str(asset.relative_to(ROOT)), 'sha256': digest,+ 'bytes': asset.stat().st_size, 'blenderVersion': bpy.app.version_string,+ 'objects': len(rows), 'triangles': sum(row['triangles'] for row in rows),+ 'components': dict(Counter(row['component'] for row in rows)),+ 'extensionSummary': extension_summary, 'meshes': rows,+ 'materials': [{'name': m.name, 'nodes': [n.type for n in m.node_tree.nodes] if m.use_nodes else []}+ for m in bpy.data.materials],+ 'images': [{'name': i.name, 'packed': bool(i.packed_file or i.packed_files),+ 'size': list(i.size)} for i in bpy.data.images if i.type != 'RENDER_RESULT'],+ 'viewTransform': scene.view_settings.view_transform, 'samples': args.samples,+ 'portableWorld': 'Independent neutral world; source HDRI/background not embedded' if args.asset == 'portable' else None,+ 'render': str(output.relative_to(ROOT)), 'elapsedSeconds': round(time.perf_counter()-started, 3)}+ (EVIDENCE / f'reimport-{args.asset}-{args.view}.json').write_text(json.dumps(receipt, indent=2)+'\n')+ print(json.dumps({key: value for key, value in receipt.items() if key != 'meshes'}), flush=True)++diff --git a/authoring/pipeline.py b/authoring/pipeline.pynew file mode 100644index 0000000..1b31ee1--- /dev/null+++ b/authoring/pipeline.py@@ -0,0 +1,748 @@+"""Workspace-bound native production using actual Blender/Cycles.++Loaded privately by authoring.bound_module; no paths or scene data are accessed+at import. Numeric regression results never certify reference likeness.+"""+from collections import defaultdict+from pathlib import Path+import hashlib+import json+import math+import time+import uuid++import bpy+import numpy as np+from mathutils import Vector++BAKE_MARGIN = 2+++def log(event, **data):+ print(json.dumps({'event': event, **data}), flush=True)+++def select_objects(objects):+ bpy.ops.object.select_all(action='DESELECT')+ for obj in objects:+ obj.select_set(True)+ bpy.context.view_layer.objects.active = objects[0]+++def meshes():+ return [obj for obj in bpy.context.scene.objects if obj.type == 'MESH' and not obj.hide_render]+++def set_render(width, samples, format='PNG'):+ scene = bpy.context.scene+ scene.render.engine = 'CYCLES'+ scene.cycles.device = 'CPU'+ scene.cycles.samples = samples+ scene.cycles.use_denoising = True+ scene.cycles.seed = 17+ scene.render.resolution_x = width+ width_px, height_px = CONTRACT['authoring']['sourceImageSize']+ scene.render.resolution_y = max(1, round(width * height_px / width_px))+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = format+ scene.render.image_settings.color_mode = 'RGB'+ scene.render.image_settings.color_depth = '16' if format == 'OPEN_EXR' else '8'+ scene.render.film_transparent = False+ scene.view_settings.view_transform = 'Khronos PBR Neutral'+ scene.view_settings.look = 'None'+ scene.view_settings.exposure = 0+ scene.view_settings.gamma = 1+ return scene+++def look_at(camera, target):+ camera.rotation_mode = 'XYZ'+ camera.rotation_euler = (Vector(target) - camera.location).to_track_quat('-Z', 'Y').to_euler()+++def save_master():+ bpy.ops.file.pack_all()+ settings = bpy.context.preferences.filepaths+ original = settings.save_version+ try:+ settings.save_version = 0+ bpy.ops.wm.save_as_mainfile(filepath=str(MASTER), compress=True)+ finally:+ settings.save_version = original+++def inventory():+ rows = []+ for obj in meshes():+ obj.data.calc_loop_triangles()+ coordinates = np.empty(len(obj.data.vertices) * 3, dtype=np.float32)+ obj.data.vertices.foreach_get('co', coordinates)+ if not np.isfinite(coordinates).all():+ raise RuntimeError(f'Non-finite geometry: {obj.name}')+ if not obj.get('component'):+ raise RuntimeError(f'Physical mesh missing component identity: {obj.name}')+ if not obj.data.uv_layers:+ raise RuntimeError(f'Physical mesh missing material UVs: {obj.name}')+ rows.append({'name': obj.name, 'component': obj['component'],+ 'finish': obj.get('finish'), 'lightmap': obj.get('lightmap'),+ 'vertices': len(obj.data.vertices), 'triangles': len(obj.data.loop_triangles),+ 'uvLayers': [layer.name for layer in obj.data.uv_layers],+ 'materials': [slot.material.name if slot.material else None for slot in obj.material_slots],+ 'bounds': [list(obj.matrix_world @ Vector(corner)) for corner in obj.bound_box]})+ return rows+++def stage_draft(args):+ from authoring import private_module+ bpy.ops.wm.read_factory_settings(use_empty=True)+ builder = private_module(CONTEXT.resolve(CONTRACT['authoring']['sceneBuilder']))+ result = builder.build_scene(CONTEXT)+ json.dumps(result)+ scene = set_render(args.width, args.samples)+ if not scene.camera:+ raise RuntimeError('Scene builder did not provide a reference camera')+ for obj in meshes():+ select_objects([obj])+ if obj.data.users > 1:+ obj.data = obj.data.copy()+ for modifier in list(obj.modifiers):+ bpy.ops.object.modifier_apply(modifier=modifier.name)+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)+ if len(obj.data.uv_layers) != 1 or obj.data.uv_layers[0].name != 'UV0':+ raise ValueError(f'{obj.name}: builder must supply exactly one UV0 layer before baking')+ scene['dirty_atlases_json'] = json.dumps(sorted({atlas_group(o) for o in meshes() if atlas_group(o)}))+ scene['authoring_revision'] = uuid.uuid4().hex+ rows = inventory()+ scene['authoring_summary_json'] = json.dumps(result)+ scene['reference_camera'] = scene.camera.name+ save_master()+ scene.render.filepath = str(EVIDENCE / 'draft-source.png')+ bpy.ops.render.render(write_still=True)+ (EVIDENCE / 'authoring.json').write_text(json.dumps({'builder': result, 'meshes': rows}, indent=2) + '\n')+ log('draft-complete', output=str(EVIDENCE / 'draft-source.png'), meshes=len(rows),+ triangles=sum(row['triangles'] for row in rows))+++def stage_refresh_material(args):+ """Reload named file maps from disk, removing stale packed bytes first."""+ bpy.ops.wm.open_mainfile(filepath=str(MASTER))+ paths = {CONTEXT.resolve(path) for path in args.image}+ if not paths:+ raise ValueError('refresh-material requires one or more --image W-relative paths')+ for path in paths:+ if not path.is_file():+ raise FileNotFoundError(path)+ refreshed = []+ for image in bpy.data.images:+ path = Path(bpy.path.abspath(image.filepath)).resolve()+ if image.source == 'FILE' and path in paths:+ if image.packed_file:+ image.unpack(method='REMOVE')+ image.reload()+ image.pack()+ refreshed.append(str(path.relative_to(ROOT)))+ if set(refreshed) != {str(path.relative_to(ROOT)) for path in paths}:+ raise ValueError('Some requested maps are not used by the packed master')+ bpy.context.scene['dirty_atlases_json'] = json.dumps(sorted({atlas_group(o) for o in meshes() if atlas_group(o)}))+ bpy.context.scene['authoring_revision'] = uuid.uuid4().hex+ save_master()+ (EVIDENCE / 'material-refresh.json').write_text(json.dumps({+ 'images': refreshed, 'nextStages': ['bake', 'probe', 'export'],+ 'sha256': {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}+ }, indent=2))+++def is_glass(obj):+ for slot in obj.material_slots:+ material = slot.material+ if not material or not material.use_nodes:+ continue+ for node in material.node_tree.nodes:+ if node.type == 'BSDF_PRINCIPLED':+ transmission = node.inputs.get('Transmission Weight')+ if transmission and not transmission.is_linked and transmission.default_value > 0.5:+ return True+ return False+++def atlas_group(obj):+ component = str(obj['component']).lower()+ if is_glass(obj) or 'bulb' in obj.name.lower():+ return None+ if obj.get('bake_detail'):+ return 'details'+ if 'exterior' in component or 'garden' in component:+ return 'garden'+ if any(part in component for part in ('sofa', 'pillow', 'curtain', 'rug')):+ return 'textiles'+ if any(part in component for part in ('floor', 'wall', 'ceiling', 'window', 'architecture', 'room')):+ return 'architecture'+ return 'furniture'+++def unwrap_atlas(objects, size):+ for obj in objects:+ # Shared imported geometry needs independent lightmap coordinates per placement.+ if obj.data.users > 1:+ obj.data = obj.data.copy()+ original = obj.data.uv_layers[0]+ original.active_render = True+ layer = obj.data.uv_layers.get('Lightmap') or obj.data.uv_layers.new(name='Lightmap')+ obj.data.uv_layers.active = layer+ select_objects(objects)+ bpy.ops.object.mode_set(mode='EDIT')+ bpy.ops.mesh.select_all(action='SELECT')+ bpy.ops.uv.smart_project(angle_limit=math.radians(70), margin_method='FRACTION',+ island_margin=(2 * BAKE_MARGIN + 2) / size,+ area_weight=0.4, correct_aspect=True, scale_to_bounds=True)+ bpy.ops.object.mode_set(mode='OBJECT')+ for obj in objects:+ obj.data.uv_layers[0].active_render = True+ mesh = obj.data+ mesh.calc_loop_triangles()+ coordinates = np.array([corner.uv[:] for corner in mesh.uv_layers['Lightmap'].data])+ triangles = coordinates[np.array([triangle.loops[:] for triangle in mesh.loop_triangles])]+ edges = triangles[:, 1:] - triangles[:, :1]+ area = np.abs(edges[:, 0, 0] * edges[:, 1, 1] - edges[:, 0, 1] * edges[:, 1, 0]).sum() * 0.5+ if not np.isfinite(coordinates).all() or area * size * size < 1:+ raise RuntimeError(f'Collapsed or subpixel lightmap UVs: {obj.name}, area={area}')+++def create_target(name, size):+ image = bpy.data.images.new(name, width=size, height=size, alpha=True, float_buffer=True)+ image.colorspace_settings.name = 'Linear Rec.709'+ return image+++def assign_bake_materials(objects, atlas_id, target):+ copies = {}+ for obj in objects:+ obj['lightmap'] = atlas_id+ if not obj.material_slots:+ raise RuntimeError(f'No material on bake target: {obj.name}')+ for slot in obj.material_slots:+ original = slot.material+ if original is None:+ raise RuntimeError(f'Empty material slot: {obj.name}')+ key = original.as_pointer()+ if key not in copies:+ # The reserved target node already identifies our prepared+ # material. Reuse it across bakes instead of copying it again.+ prepared = original.node_tree.nodes.get('InteriorBakeTarget') is not None+ material = original if prepared else original.copy()+ if not prepared:+ material.name = f'{original.name}__{atlas_id}'+ # The bake operator overrides the active UV with Lightmap. Source+ # sampling must remain explicitly UV0, independent of that target.+ tree = material.node_tree+ source_uv = next((node for node in tree.nodes+ if node.type == 'UVMAP' and node.uv_map == 'UV0'), None)+ if source_uv is None:+ source_uv = tree.nodes.new('ShaderNodeUVMap')+ source_uv.uv_map = 'UV0'+ for texture in tree.nodes:+ if texture.type == 'TEX_IMAGE' and texture.name != 'InteriorBakeTarget' and not texture.inputs['Vector'].is_linked:+ tree.links.new(source_uv.outputs['UV'], texture.inputs['Vector'])+ node = material.node_tree.nodes.get('InteriorBakeTarget')+ if node is None:+ node = material.node_tree.nodes.new('ShaderNodeTexImage')+ node.name = 'InteriorBakeTarget'+ node.label = 'UV1 diffuse irradiance; runtime sidecar, not baked into source PBR'+ node.image = target+ material.node_tree.nodes.active = node+ copies[key] = material+ slot.material = copies[key]+ return list(copies.values())+++def set_targets(materials, image):+ for material in materials:+ node = material.node_tree.nodes['InteriorBakeTarget']+ node.image = image+ material.node_tree.nodes.active = node+++def bake_albedo(objects, materials, target, channel='Base Color'):+ restores = []+ for material in materials:+ tree = material.node_tree+ outputs = [node for node in tree.nodes if node.type == 'OUTPUT_MATERIAL' and node.is_active_output]+ principled = next((node for node in tree.nodes if node.type == 'BSDF_PRINCIPLED'), None)+ if not outputs or principled is None:+ raise RuntimeError(f'Expected exportable Principled material: {material.name}')+ output = outputs[0]+ surface = output.inputs['Surface']+ original = surface.links[0].from_socket if surface.is_linked else None+ emission = tree.nodes.new('ShaderNodeEmission')+ color = principled.inputs[channel]+ if color.is_linked:+ tree.links.new(color.links[0].from_socket, emission.inputs['Color'])+ else:+ value = color.default_value+ emission.inputs['Color'].default_value = (value, value, value, 1) if isinstance(value, float) else value+ tree.links.new(emission.outputs[0], surface)+ restores.append((tree, output, original, emission))+ set_targets(materials, target)+ select_objects(objects)+ original_samples = bpy.context.scene.cycles.samples+ bpy.context.scene.cycles.samples = 1+ try:+ bpy.ops.object.bake(type='EMIT', uv_layer='Lightmap', use_clear=True,+ margin=BAKE_MARGIN, margin_type='EXTEND')+ finally:+ bpy.context.scene.cycles.samples = original_samples+ for tree, output, original, emission in restores:+ tree.nodes.remove(emission)+ if original is not None:+ tree.links.new(original, output.inputs['Surface'])+++def save_linear_exr(image, path):+ image.filepath_raw = str(path)+ image.file_format = 'OPEN_EXR'+ # Image.save() otherwise writes uncompressed float atlases.+ scene = bpy.context.scene+ settings = scene.render.image_settings+ original = (settings.file_format, settings.color_depth, settings.color_mode, settings.exr_codec)+ try:+ settings.file_format = 'OPEN_EXR'+ settings.color_depth = '32'+ settings.color_mode = 'RGBA'+ settings.exr_codec = 'ZIP'+ image.save_render(str(path), scene=scene)+ finally:+ settings.file_format, settings.color_depth, settings.color_mode, settings.exr_codec = original+++def denoise_irradiance(objects, materials, irradiance, group, size):+ """OIDN filters lighting only; UV0 albedo and normal detail remain separate."""+ normal = create_target(f'NormalGuide_{group}', size)+ set_targets(materials, normal)+ select_objects(objects)+ bpy.ops.object.bake(type='NORMAL', normal_space='OBJECT', uv_layer='Lightmap',+ use_clear=True, margin=BAKE_MARGIN, margin_type='EXTEND')+ values = np.empty(size * size * 4, dtype=np.float32)+ normal.pixels.foreach_get(values)+ values.reshape(-1, 4)[:, :3] = values.reshape(-1, 4)[:, :3] * 2 - 1+ normal.pixels.foreach_set(values)+ compositor = bpy.data.scenes.new(f'Denoise_{group}')+ camera_data = bpy.data.cameras.new('DenoiseCamera')+ camera = bpy.data.objects.new('DenoiseCamera', camera_data)+ compositor.collection.objects.link(camera)+ compositor.camera = camera+ compositor.render.engine = 'BLENDER_EEVEE_NEXT'+ compositor.render.resolution_x = compositor.render.resolution_y = size+ compositor.render.resolution_percentage = 100+ compositor.use_nodes = True+ tree = compositor.node_tree+ tree.nodes.clear()+ source = tree.nodes.new('CompositorNodeImage')+ source.image = irradiance+ guide = tree.nodes.new('CompositorNodeImage')+ guide.image = normal+ denoise = tree.nodes.new('CompositorNodeDenoise')+ denoise.prefilter = 'ACCURATE'+ denoise.use_hdr = True+ tree.links.new(source.outputs['Image'], denoise.inputs['Image'])+ tree.links.new(guide.outputs['Image'], denoise.inputs['Normal'])+ output = tree.nodes.new('CompositorNodeComposite')+ tree.links.new(denoise.outputs['Image'], output.inputs['Image'])+ compositor.view_settings.view_transform = 'Standard'+ compositor.render.image_settings.file_format = 'OPEN_EXR'+ compositor.render.image_settings.color_depth = '32'+ path = WORK / f'denoised-{group}.exr'+ compositor.render.filepath = str(path)+ filtered = None+ try:+ bpy.ops.render.render(scene=compositor.name, write_still=True)+ filtered = bpy.data.images.load(str(path), check_existing=False)+ filtered.pixels.foreach_get(values)+ if not np.isfinite(values).all():+ raise RuntimeError(f'Non-finite denoised irradiance: {group}')+ np.maximum(values, 0, out=values)+ irradiance.pixels.foreach_set(values)+ finally:+ if filtered is not None:+ bpy.data.images.remove(filtered)+ bpy.data.scenes.remove(compositor)+ bpy.data.objects.remove(camera, do_unlink=True)+ bpy.data.cameras.remove(camera_data)+ bpy.data.images.remove(normal)+ set_targets(materials, irradiance)+++def stage_bake(args):+ bpy.ops.wm.open_mainfile(filepath=str(MASTER))+ scene = set_render(args.width, args.samples)+ scene.cycles.use_denoising = False # Cycles texture baking does not use the render denoiser.+ groups = defaultdict(list)+ for obj in meshes():+ group = atlas_group(obj)+ if group:+ groups[group].append(obj)+ if args.atlas:+ if args.atlas not in groups:+ raise RuntimeError(f'No geometry for atlas: {args.atlas}')+ groups = {args.atlas: groups[args.atlas]}+ selected_names = {obj.name for objects in groups.values() for obj in objects}+ receipt = [row for row in json.loads(scene.get('bake_receipt_json', '[]')) if row['id'] != args.atlas]+ for row in receipt:+ row['objects'] = [name for name in row['objects'] if name not in selected_names]+ else:+ receipt = []+ for group, objects in groups.items():+ started = time.perf_counter()+ # Dense curved upholstery and repeated plant leaves need room for chart gutters.+ size = args.resolution * 2 if group in ('textiles', 'garden') else args.resolution+ unwrap_atlas(objects, size)+ irradiance = create_target(f'Lightmap_{group}', size)+ materials = assign_bake_materials(objects, group, irradiance)+ select_objects(objects)+ log('bake-start', atlas=group, size=size, objects=len(objects), samples=args.samples)+ bpy.ops.object.bake(type='DIFFUSE', pass_filter={'DIRECT', 'INDIRECT'},+ uv_layer='Lightmap', use_clear=True, margin=BAKE_MARGIN, margin_type='EXTEND')+ save_linear_exr(irradiance, WORK / f'raw-lightmap-{group}.exr')+ denoise_irradiance(objects, materials, irradiance, group, size)+ # Preserve the full static appearance for portable glTF. Runtime direct+ # sunlight is evaluated with moving cloth shadows, never baked twice.+ save_linear_exr(irradiance, WORK / f'full-lightmap-{group}.exr')+ albedo = create_target(f'Albedo_{group}', size)+ bake_albedo(objects, materials, albedo)+ light_pixels = np.empty(size * size * 4, dtype=np.float32)+ color_pixels = np.empty_like(light_pixels)+ irradiance.pixels.foreach_get(light_pixels)+ albedo.pixels.foreach_get(color_pixels)+ light_pixels = light_pixels.reshape(size, size, 4)+ color_pixels = color_pixels.reshape(size, size, 4)+ if not np.isfinite(light_pixels).all() or not np.isfinite(color_pixels).all():+ raise RuntimeError(f'Non-finite bake pixels: {group}')+ if light_pixels[..., :3].max() <= 0:+ raise RuntimeError(f'Empty irradiance bake: {group}')+ combined = color_pixels.copy()+ combined[..., :3] *= light_pixels[..., :3]+ combined[..., 3] = 1+ has_alpha = any(node.inputs['Alpha'].is_linked or node.inputs['Alpha'].default_value < 1+ for material in materials for node in material.node_tree.nodes+ if node.type == 'BSDF_PRINCIPLED')+ if has_alpha:+ alpha = create_target(f'Alpha_{group}', size)+ bake_albedo(objects, materials, alpha, channel='Alpha')+ alpha_pixels = np.empty(size * size * 4, dtype=np.float32)+ alpha.pixels.foreach_get(alpha_pixels)+ combined[..., 3] = np.clip(alpha_pixels.reshape(size, size, 4)[..., 0], 0, 1)+ bpy.data.images.remove(alpha)+ portable = create_target(f'PortableDiffuse_{group}', size)+ portable.pixels.foreach_set(combined.ravel())+ portable_path = ASSETS / f'portable-{group}.png'+ scene.render.image_settings.color_mode = 'RGBA'+ portable.save_render(str(portable_path), scene=scene)+ bpy.data.images.remove(portable)+ full_max, full_mean = float(light_pixels[..., :3].max()), float(light_pixels[..., :3].mean())+ sun_strengths = [(obj.data, obj.data.energy) for obj in scene.objects+ if obj.type == 'LIGHT' and obj.data.type == 'SUN']+ set_targets(materials, irradiance)+ select_objects(objects)+ try:+ for light, _ in sun_strengths:+ light.energy = 0+ log('ambient-bake-start', atlas=group, size=size, samples=args.samples)+ bpy.ops.object.bake(type='DIFFUSE', pass_filter={'DIRECT', 'INDIRECT'},+ uv_layer='Lightmap', use_clear=True, margin=BAKE_MARGIN, margin_type='EXTEND')+ finally:+ for light, energy in sun_strengths:+ light.energy = energy+ save_linear_exr(irradiance, WORK / f'raw-ambient-{group}.exr')+ denoise_irradiance(objects, materials, irradiance, group, size)+ save_linear_exr(irradiance, ASSETS / f'lightmap-{group}.exr')+ irradiance.pixels.foreach_get(light_pixels.ravel())+ if not np.isfinite(light_pixels).all() or light_pixels[..., :3].max() <= 0:+ raise RuntimeError(f'Invalid ambient irradiance bake: {group}')+ set_targets(materials, irradiance)+ bpy.data.images.remove(albedo)+ receipt.append({'id': group, 'url': f'/assets/interior/lightmap-{group}.exr',+ 'intensity': math.pi, 'size': size, 'objects': [obj.name for obj in objects],+ 'portableImage': f'/assets/interior/portable-{group}.png', 'linearRgbMax': float(light_pixels[..., :3].max()),+ 'linearRgbMean': float(light_pixels[..., :3].mean()),+ 'samples': args.samples, 'denoised': True,+ 'lightingModel': 'ambient-bake+shadowed-sun-v1',+ 'portableFullLightingMax': full_max, 'portableFullLightingMean': full_mean,+ 'denoiser': 'OpenImageDenoise HDR, accurate object-normal guide in UV1 atlas space',+ 'elapsedSeconds': round(time.perf_counter() - started, 3)})+ log('bake-complete', **{key: value for key, value in receipt[-1].items() if key != 'objects'})+ scene['bake_receipt_json'] = json.dumps(receipt)+ dirty = set(json.loads(scene.get('dirty_atlases_json', '[]'))) - set(groups)+ scene['dirty_atlases_json'] = json.dumps(sorted(dirty))+ scene['bake_lighting_model'] = 'ambient-bake+shadowed-sun-v1'+ scene.cycles.use_denoising = True+ scene.cycles.samples = 128+ scene.render.resolution_x, scene.render.resolution_y = CONTRACT['authoring']['sourceImageSize']+ save_master()+ (EVIDENCE / 'bake.json').write_text(json.dumps({'atlases': receipt, 'meshes': inventory()}, indent=2) + '\n')+++def probe_pose():+ position = CONTRACT['authoring'].get('probePosition')+ if position is None:+ raise ValueError('Declare authoring.probePosition inside the authored room')+ return {'position': list(position), 'rotationEuler': [math.pi / 2, 0, -math.pi / 2]}+++def require_current_probe(scene):+ pointer = CONTEXT.resolve('.img2/artifacts/interior/current-probe.json')+ path = ASSETS / 'room-environment.exr'+ if not pointer.is_file() or not path.is_file():+ raise RuntimeError('Run probe before export: current probe receipt or EXR is missing')+ receipt = json.loads(pointer.read_text())+ if (not scene.get('authoring_revision')+ or receipt.get('authoringRevision') != scene['authoring_revision']+ or receipt.get('pose') != probe_pose()+ or receipt.get('sha256') != hashlib.sha256(path.read_bytes()).hexdigest()):+ raise RuntimeError('Stale reflection probe: rerun probe for the current authoring revision and pose')+ return receipt+++def stage_probe(args):+ bpy.ops.wm.open_mainfile(filepath=str(MASTER))+ scene = set_render(args.width, args.samples, 'OPEN_EXR')+ if not scene.get('authoring_revision'):+ raise RuntimeError('Master lacks authoring revision; rerun draft before probe')+ pose = probe_pose()+ source_camera = scene.camera+ scene.render.resolution_y = max(1, args.width // 2)+ camera_data = bpy.data.cameras.new('IndoorReflectionProbe')+ camera_data.type = 'PANO'+ camera_data.panorama_type = 'EQUIRECTANGULAR'+ camera = bpy.data.objects.new('IndoorReflectionProbe', camera_data)+ scene.collection.objects.link(camera)+ camera.location = pose['position']+ camera.rotation_euler = pose['rotationEuler']+ scene.camera = camera+ path = ASSETS / 'room-environment.exr'+ scene.render.filepath = str(path)+ try:+ bpy.ops.render.render(write_still=True)+ receipt = {'authoringRevision': scene['authoring_revision'], 'pose': pose,+ 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),+ 'path': str(path.relative_to(ROOT)), 'width': args.width,+ 'samples': args.samples, 'run': str(EVIDENCE.relative_to(ROOT))}+ with (EVIDENCE / 'probe.json').open('x') as stream:+ json.dump(receipt, stream, indent=2)+ pointer = CONTEXT.resolve('.img2/artifacts/interior/current-probe.json')+ pointer.write_text(json.dumps(receipt, indent=2))+ finally:+ scene.camera = source_camera+ bpy.data.objects.remove(camera, do_unlink=True)+ bpy.data.cameras.remove(camera_data)+ log('probe-complete', **receipt)+++def three_point(point):+ return [point[0], point[2], -point[1]]+++def export_gltf(path, *, tangents=False):+ """Export-only thin-pane, tangent-cap and weighted sheen corrections."""+ restores, sheen_restores, triangulations = [], [], []+ try:+ for material in bpy.data.materials:+ if not material.use_nodes:+ continue+ tree = material.node_tree+ if material.get('thin_pane_shadow_transmittance'):+ output = next(n for n in tree.nodes if n.type == 'OUTPUT_MATERIAL' and n.is_active_output)+ shader = next(n for n in tree.nodes if n.type == 'BSDF_PRINCIPLED')+ original = output.inputs['Surface'].links[0].from_socket+ restores.append((tree, output, original))+ tree.links.new(shader.outputs['BSDF'], output.inputs['Surface'])+ for shader in tree.nodes:+ if shader.type != 'BSDF_PRINCIPLED':+ continue+ weight, tint = shader.inputs['Sheen Weight'], shader.inputs['Sheen Tint']+ if weight.is_linked or tint.is_linked or weight.default_value in (0, 1):+ continue+ original = tuple(tint.default_value)+ sheen_restores.append((tint, original))+ tint.default_value = (*[v * weight.default_value for v in original[:3]], original[3])+ if tangents:+ for obj in meshes():+ if any(len(face.vertices) > 4 for face in obj.data.polygons):+ modifier = obj.modifiers.new('ExportTangentCaps', 'TRIANGULATE')+ modifier.min_vertices = 5+ modifier.keep_custom_normals = True+ triangulations.append((obj, modifier))+ bpy.ops.export_scene.gltf(filepath=str(path), export_format='GLB', export_texcoords=True,+ export_normals=True, export_tangents=tangents, export_cameras=True, export_lights=False,+ export_extras=True, export_yup=True, export_apply=True,+ export_image_format='AUTO', export_keep_originals=False)+ finally:+ for obj, modifier in triangulations:+ obj.modifiers.remove(modifier)+ for tree, output, original in restores:+ tree.links.new(original, output.inputs['Surface'])+ for tint, original in sheen_restores:+ tint.default_value = original+++def stage_export(args):+ bpy.ops.wm.open_mainfile(filepath=str(MASTER))+ scene = bpy.context.scene+ require_current_probe(scene)+ camera = scene.camera+ if not camera or camera.type != 'CAMERA':+ raise RuntimeError('Packed master has no active reference camera')+ rows = inventory()+ receipt = json.loads(scene['bake_receipt_json'])+ if (scene.get('bake_lighting_model') != 'ambient-bake+shadowed-sun-v1'+ or any(row.get('lightingModel') != 'ambient-bake+shadowed-sun-v1' for row in receipt)):+ raise RuntimeError('Rebake every atlas: runtime sunlight must not be present in static irradiance')+ if json.loads(scene.get('dirty_atlases_json', '[]')):+ raise RuntimeError('Rebake dirty atlases after draft/material refresh before export')+ expected = {obj.name for obj in meshes() if atlas_group(obj)}+ baked = {name for row in receipt for name in row['objects']}+ if expected != baked:+ raise RuntimeError(f'Incomplete bake inventory; missing={sorted(expected-baked)}, obsolete={sorted(baked-expected)}')+ # Use material UV0 as render UV, preserving Lightmap in TEXCOORD_1.+ for obj in meshes():+ obj.data.uv_layers[0].active_render = True+ obj.data.uv_layers.active_index = 0+ summary = json.loads(scene['authoring_summary_json'])+ summary['views'] = CONTRACT['authoring']['inspectionViews']+ scene['interior_metadata'] = scene['authoring_summary_json'] = json.dumps(summary)+ authoring_path = EVIDENCE / 'authoring.json'+ authoring = {'builder': summary, 'meshes': rows}+ authoring['builder'] = summary+ authoring_path.write_text(json.dumps(authoring, indent=2) + '\n')+ save_master()+ # Export the packed native world's actual HDRI, not a manually copied old sky.+ outdoor_nodes = ([node for node in scene.world.node_tree.nodes if node.type == 'TEX_ENVIRONMENT']+ if scene.world and scene.world.use_nodes else [])+ if len(outdoor_nodes) > 1:+ raise RuntimeError('Only one world HDRI is supported for runtime background export')+ background_url = CONTRACT['runtime'].get('background')+ if background_url:+ if len(outdoor_nodes) != 1 or not outdoor_nodes[0].image or not outdoor_nodes[0].image.packed_file:+ raise RuntimeError('Configured background requires one actual packed world HDRI')+ background_path = CONTEXT.resolve('public/' + background_url.lstrip('/'))+ background_path.parent.mkdir(parents=True, exist_ok=True)+ background_path.write_bytes(outdoor_nodes[0].image.packed_file.data)+ runtime = ASSETS / 'room-runtime.glb'+ export_gltf(runtime, tangents=True)+ source_position = list(camera.location)+ forward = camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))+ source_target = camera.location + forward * 6+ aspect = CONTRACT['authoring']['sourceImageSize'][0] / CONTRACT['authoring']['sourceImageSize'][1]+ vertical_fov = math.degrees(2 * math.atan(camera.data.sensor_width / (2 * camera.data.lens * aspect)))+ suns = [obj for obj in scene.objects if obj.type == 'LIGHT' and obj.data.type == 'SUN']+ if len(suns) > 1:+ raise RuntimeError('Runtime supports at most one SUN; consolidate authored sunlight')+ sunlight = suns[0] if suns else None+ sun_forward = sunlight.matrix_world.to_quaternion() @ Vector((0, 0, -1)) if sunlight else None+ transmission = CONTRACT['runtime'].get('glassTransmission', 1.0)+ room = summary['roomBounds']+ manifest = {+ 'schemaVersion': 2, 'title': CONTRACT['title'],+ 'sourceImage': '/' + str(Path(CONTRACT['source']).relative_to('public')),+ 'sourceImageSize': CONTRACT['authoring']['sourceImageSize'],+ 'sourceAspect': aspect, 'sourceKind': CONTRACT['sourceKind'],+ 'model': '/assets/interior/room-runtime.glb',+ 'portableModel': '/assets/interior/room-portable.glb',+ 'blender': '/assets/interior/room-master.blend',+ 'environment': '/assets/interior/room-environment.exr',+ 'background': background_url,+ 'backgroundIntensity': CONTRACT['runtime'].get('backgroundIntensity', 1),+ 'camera': {'position': three_point(source_position), 'target': three_point(source_target), 'fov': vertical_fov},+ 'roomBounds': {'min': [room['min'][0], room['min'][2], -room['max'][1]],+ 'max': [room['max'][0], room['max'][2], -room['min'][1]]},+ 'lighting': {'model': 'ambient-bake+shadowed-sun-v1',+ 'sun': {'position': three_point(sunlight.location),+ 'target': three_point(sunlight.location+sun_forward*10),+ 'color': list(sunlight.data.color),+ 'intensity': sunlight.data.energy * transmission,+ 'glassTransmission': transmission,+ 'shadowMapSize': 2048} if sunlight else None},+ 'views': {name: {'position': three_point(pose['position']), 'target': three_point(pose['target'])}+ for name, pose in CONTRACT['authoring']['inspectionViews'].items()},+ 'lightmaps': [{key: row[key] for key in ('id', 'url', 'intensity')} for row in receipt],+ 'variants': CONTRACT['runtime'].get('variants', []),+ 'toneMapping': 'neutral', 'exposure': 1,+ 'stats': {'meshes': len(rows), 'triangles': sum(row['triangles'] for row in rows),+ 'components': len(set(row['component'] for row in rows)),+ 'lightmapAtlases': len(receipt)},+ 'portability': CONTRACT['portability'],+ 'sourceLimit': CONTRACT['sourceViewLimit'],+ }+ if CONTRACT['runtime'].get('finishTarget'):+ manifest['finishTarget'] = CONTRACT['runtime']['finishTarget']+ resource_path = CONTRACT['authoring'].get('resourceManifest')+ if resource_path:+ resources = json.loads(CONTEXT.resolve(resource_path).read_text())+ if resources.get('provider') == 'Poly Haven':+ manifest['resourceCredit'] = {'provider': 'Poly Haven', 'apiDerived': True, 'credit': 'Powered by Poly Haven'}+ # A separate explicitly static appearance export; do not pretend native glTF has a lightMap slot.+ portable_materials = {}+ portable_textures = {+ row['id']: bpy.data.images.load(str(ROOT / 'public' / row['portableImage'].lstrip('/')), check_existing=False)+ for row in receipt+ }+ for image in portable_textures.values():+ image.colorspace_settings.name = 'sRGB'+ original_slots = [(slot, slot.material) for obj in meshes() for slot in obj.material_slots]+ portable_path = ASSETS / 'room-portable.glb'+ try:+ for obj in meshes():+ group = obj.get('lightmap')+ if not group:+ continue+ for slot in obj.material_slots:+ key = (slot.material.as_pointer(), group)+ if key not in portable_materials:+ material = bpy.data.materials.new(f'Baked_{slot.material.name}')+ material.use_nodes = True+ tree = material.node_tree+ tree.nodes.clear()+ output = tree.nodes.new('ShaderNodeOutputMaterial')+ background = tree.nodes.new('ShaderNodeBackground')+ texture = tree.nodes.new('ShaderNodeTexImage')+ texture.image = portable_textures[group]+ uv = tree.nodes.new('ShaderNodeUVMap')+ uv.uv_map = 'Lightmap'+ tree.links.new(uv.outputs['UV'], texture.inputs['Vector'])+ tree.links.new(texture.outputs['Color'], background.inputs['Color'])+ tree.links.new(background.outputs[0], output.inputs['Surface'])+ principled = next((node for node in slot.material.node_tree.nodes if node.type == 'BSDF_PRINCIPLED'), None)+ if principled and (principled.inputs['Alpha'].is_linked or principled.inputs['Alpha'].default_value < 1):+ transparent = tree.nodes.new('ShaderNodeBsdfTransparent')+ coverage = tree.nodes.new('ShaderNodeMixShader')+ tree.links.new(texture.outputs['Alpha'], coverage.inputs[0])+ tree.links.new(transparent.outputs[0], coverage.inputs[1])+ tree.links.new(background.outputs[0], coverage.inputs[2])+ tree.links.new(coverage.outputs[0], output.inputs['Surface'])+ material.surface_render_method = slot.material.surface_render_method+ portable_materials[key] = material+ slot.material = portable_materials[key]+ export_gltf(portable_path)+ finally:+ for slot, material in original_slots:+ slot.material = material+ (ASSETS / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')+ output = {'manifest': manifest, 'runtimeBytes': runtime.stat().st_size,+ 'runtimeSha256': hashlib.sha256(runtime.read_bytes()).hexdigest(),+ 'portableBytes': portable_path.stat().st_size,+ 'portableSha256': hashlib.sha256(portable_path.read_bytes()).hexdigest(),+ 'masterBytes': MASTER.stat().st_size}+ (EVIDENCE / 'exports.json').write_text(json.dumps(output, ensure_ascii=False, indent=2) + '\n')+ log('export-complete', runtimeBytes=output['runtimeBytes'], portableBytes=output['portableBytes'])+++def stage_render(args):+ bpy.ops.wm.open_mainfile(filepath=str(MASTER))+ scene = set_render(args.width, args.samples)+ if args.view != 'source':+ pose = CONTRACT['authoring']['inspectionViews'][args.view]+ scene.camera.location = pose['position']+ look_at(scene.camera, pose['target'])+ scene.render.filepath = str(EVIDENCE / f'blender-{args.view}.png')+ bpy.ops.render.render(write_still=True)+ log('render-complete', view=args.view, output=str(Path(scene.render.filepath).relative_to(ROOT)))++diff --git a/authoring/regression.py b/authoring/regression.pynew file mode 100644index 0000000..3d38113--- /dev/null+++ b/authoring/regression.py@@ -0,0 +1,273 @@+"""Real Blender export regressions. These measurements are not visual-quality scores."""+from pathlib import Path+from types import SimpleNamespace+import json+import tempfile+++def png(path, color):+ import bpy+ image = bpy.data.images.new('RegressionPixels', 2, 2, alpha=True)+ image.colorspace_settings.name = 'Non-Color'+ image.pixels[:] = color * 4+ image.filepath_raw = str(path)+ image.file_format = 'PNG'+ image.save()+ bpy.data.images.remove(image)+++def material_regression(context, args):+ import bpy+ from authoring import Context, bound_module+ with tempfile.TemporaryDirectory(prefix='material-', dir=context.evidence) as temporary:+ root = Path(temporary)+ assets = root / 'public/assets/interior'+ assets.mkdir(parents=True)+ local = Context(root, context.spec, assets, root)+ pipeline = bound_module('pipeline', local)+ inspection = bound_module('inspection', local)+ bpy.ops.wm.read_factory_settings(use_empty=True)+ path = root / 'color.png'+ png(path, [.25, .20, .18, 1])+ material = local.helpers.material('PackedCloth', (1,1,1), maps={'color':'color.png'})+ obj = local.helpers.box('cloth', (0,0,0), (1,0.2,1), material, 'curtains')+ shader = next(n for n in material.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')+ shader.inputs['Sheen Weight'].default_value = .12+ shader.inputs['Sheen Tint'].default_value = (.8,.5,.25,1)+ original_tint = tuple(shader.inputs['Sheen Tint'].default_value)+ before_uv = [list(v.uv) for v in obj.data.uv_layers['UV0'].data]+ pipeline.save_master()+ png(path, [.75,.65,.5,1])+ fresh = bpy.data.images.load(str(path), check_existing=False)+ expected = list(fresh.pixels[:])+ bpy.data.images.remove(fresh)+ pipeline.stage_refresh_material(SimpleNamespace(image=['color.png']))+ path.unlink()+ bpy.ops.wm.open_mainfile(filepath=str(pipeline.MASTER))+ obj = bpy.context.scene.objects['cloth']+ shader = next(n for n in obj.active_material.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')+ image = shader.inputs['Base Color'].links[0].from_node.image+ error = max(abs(a-b) for a,b in zip(image.pixels[:], expected))+ if not image.packed_file or error > 1e-6:+ raise RuntimeError(f'Packed pixels stale after external map removal: {error}')+ if before_uv != [list(v.uv) for v in obj.data.uv_layers['UV0'].data]:+ raise RuntimeError('Refresh changed UV0')+ path = context.evidence / 'weighted-sheen.glb'+ pipeline.export_gltf(path, tangents=True)+ document = inspection.glb_json(path)+ actual = document['materials'][0]['extensions']['KHR_materials_sheen']['sheenColorFactor']+ expected_sheen = [v*.12 for v in original_tint[:3]]+ if max(abs(a-b) for a,b in zip(actual, expected_sheen)) > 1e-6:+ raise RuntimeError(f'Weighted sheen not exported: {actual}')+ if tuple(shader.inputs['Sheen Tint'].default_value) != original_tint:+ raise RuntimeError('Successful export mutated native sheen')+ # Exercise failure restoration too, without replacing exporter or mocking bpy.+ blocked = root / 'not-a-directory'+ blocked.write_text('block actual filesystem export')+ try:+ pipeline.export_gltf(blocked / 'failure.glb', tangents=True)+ except Exception:+ pass+ else:+ raise RuntimeError('Expected actual export failure beneath a regular file')+ if tuple(shader.inputs['Sheen Tint'].default_value) != original_tint:+ raise RuntimeError('Failed export mutated native sheen')+ # Material policies address exported identities. Repeating a bake must+ # preserve those identities and artist edits, not grow suffixes/copies.+ pipeline.unwrap_atlas([obj], 64)+ identities = []+ for generation in ('first', 'repeat'):+ target = pipeline.create_target('RepeatBakeTarget', 64)+ pipeline.assign_bake_materials([obj], 'textiles', target)+ current_shader = next(n for n in obj.active_material.node_tree.nodes+ if n.type == 'BSDF_PRINCIPLED')+ if generation == 'first':+ current_shader.inputs['Roughness'].default_value = .72+ exported = context.evidence / f'rebake-{generation}.glb'+ pipeline.export_gltf(exported, tangents=True)+ emitted = inspection.glb_json(exported)['materials']+ identities.append([entry['name'] for entry in emitted])+ roughness = emitted[0]['pbrMetallicRoughness']['roughnessFactor']+ if abs(roughness - .72) > 1e-6:+ raise RuntimeError(f'Repeated bake lost edited roughness: {roughness}')+ if identities[0] != identities[1]:+ raise RuntimeError(f'Repeated bake changed exported material identity: {identities}')+ if before_uv != [list(v.uv) for v in obj.data.uv_layers['UV0'].data]:+ raise RuntimeError('Repeated bake preparation changed UV0')+ result = {'packedAlbedoPixelError':error, 'externalMapRemovedBeforeReopen':True,+ 'uv0Preserved':True, 'expectedGltfSheen':expected_sheen, 'actualGltfSheen':actual,+ 'nativeSheenRestoredAfterSuccessAndFailure':True,+ 'rebake': {'firstMaterialNames':identities[0], 'repeatMaterialNames':identities[1],+ 'editedRoughnessFactor':roughness}}+ (context.evidence / 'material-regression.json').write_text(json.dumps(result, indent=2))+ return result+++def calibrate(context, args):+ """Render an asymmetric UV1 chart before/after actual GLB transport.++ UV0 is deliberately reversed. A texCoord=0 regression therefore produces a+ different image. Non-square offset geometry catches coordinate/root mistakes.+ All calibration assets are evidence-only; the production master is untouched.+ """+ import bpy+ import numpy as np+ from mathutils import Vector+ from authoring import bound_module+ pipeline = bound_module('pipeline', context)+ inspection = bound_module('inspection', context)+ bpy.ops.wm.read_factory_settings(use_empty=True)+ h = context.helpers+ material = h.material('Calibration.UV1', (1,1,1))+ tree = material.node_tree+ tree.nodes.clear()+ output = tree.nodes.new('ShaderNodeOutputMaterial')+ emission = tree.nodes.new('ShaderNodeBackground')+ texture = tree.nodes.new('ShaderNodeTexImage')+ texture.interpolation = 'Closest'+ image = bpy.data.images.new('AsymmetricUV1Chart', width=4, height=3, alpha=True)+ image.colorspace_settings.name = 'Non-Color'+ colors = [(1,0,0),(0,1,0),(0,0,1),(1,1,0), (.1,.3,.6),(.8,.2,.1),(.2,.7,.5),(.7,.1,.8),+ (0,1,1),(1,0,1),(.25,.5,.75),(.9,.6,.2)]+ image.pixels[:] = [channel for color in colors for channel in (*color,1)]+ image.filepath_raw = str(context.evidence / 'uv1-chart.png')+ image.file_format = 'PNG'+ image.save()+ bpy.data.images.remove(image)+ image = bpy.data.images.load(str(context.evidence / 'uv1-chart.png'), check_existing=False)+ image.colorspace_settings.name = 'sRGB'+ texture.image = image+ uv = tree.nodes.new('ShaderNodeUVMap')+ uv.uv_map = 'Lightmap'+ tree.links.new(uv.outputs['UV'], texture.inputs['Vector'])+ tree.links.new(texture.outputs['Color'], emission.inputs['Color'])+ tree.links.new(emission.outputs[0], output.inputs['Surface'])+ obj = h.mesh('calibration.chart', [(-.7,.3,.2),(1.3,.3,.2),(1.3,.3,1.7),(-.7,.3,1.7)],+ [(0,1,2,3)], material, 'calibration')+ layer = obj.data.uv_layers.new(name='Lightmap')+ values = [(0,0),(1,0),(1,1),(0,1)]+ for corner, value in zip(layer.data, values):+ corner.uv = value+ for corner, value in zip(obj.data.uv_layers['UV0'].data, values):+ corner.uv = (1-value[0], 1-value[1])+ obj.data.uv_layers[0].active_render = True+ obj.data.uv_layers.active_index = 0+ bpy.context.view_layer.update()+ before_bounds = h.bounds([obj])+ data = bpy.data.cameras.new('CalibrationCamera')+ camera = bpy.data.objects.new('CalibrationCamera', data)+ bpy.context.scene.collection.objects.link(camera)+ camera.location = (.3,-3,.95)+ camera.rotation_euler = (Vector((.3,.3,.95))-camera.location).to_track_quat('-Z','Y').to_euler()+ data.type = 'ORTHO'+ data.ortho_scale = 2.4+ bpy.context.scene.camera = camera++ def render(label):+ scene = bpy.context.scene+ scene.render.engine = 'CYCLES'+ scene.cycles.samples = args.samples+ scene.cycles.use_denoising = False+ scene.render.resolution_x = args.width+ scene.render.resolution_y = max(1, round(args.width * .75))+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = 'PNG'+ scene.render.image_settings.color_mode = 'RGBA'+ scene.view_settings.view_transform = 'Standard'+ scene.view_settings.look = 'None'+ scene.view_settings.exposure = 0+ scene.view_settings.gamma = 1+ path = context.evidence / f'calibration-{label}.png'+ scene.render.filepath = str(path)+ bpy.ops.render.render(write_still=True)+ loaded = bpy.data.images.load(str(path), check_existing=False)+ pixels = np.array(loaded.pixels[:], dtype=np.float32)+ bpy.data.images.remove(loaded)+ return pixels++ before = render('native')+ glb = context.evidence / 'calibration.glb'+ pipeline.export_gltf(glb)+ document = inspection.glb_json(glb)+ coordinate = document['materials'][0]['pbrMetallicRoughness']['baseColorTexture'].get('texCoord',0)+ if coordinate != 1:+ raise RuntimeError(f'Calibration exported UV{coordinate}, expected UV1')+ bpy.ops.wm.read_factory_settings(use_empty=True)+ bpy.ops.import_scene.gltf(filepath=str(glb))+ scene = bpy.context.scene+ scene.camera = next(o for o in scene.objects if o.type == 'CAMERA')+ objects = [o for o in scene.objects if o.type == 'MESH']+ bpy.context.view_layer.update()+ after_bounds = h.bounds(objects)+ coordinate_error = float(np.max(np.abs(np.array(before_bounds)-np.array(after_bounds))))+ after = render('reimport')+ difference = np.abs(before-after)+ # Antialiasing at transported primitive edges may vary by a pixel; compare mean+ # and record max, never erase/rewrite a mismatch to manufacture a passing image.+ mean_error = float(difference.mean())+ if coordinate_error > 1e-5 or mean_error > .01:+ raise RuntimeError(f'Calibration transport mismatch: bounds={coordinate_error}, mean pixels={mean_error}')+ result = {'texCoord':coordinate, 'nativeBounds':before_bounds, 'reimportBounds':after_bounds,+ 'gltfYUpBounds': {'min':[-.7,.2,-.3], 'max':[1.3,1.7,-.3]},+ 'coordinateRoundTripMaxError':coordinate_error,+ 'decodedPixelMeanError':mean_error, 'decodedPixelMaxError':float(difference.max()),+ 'limit':'UV/color/coordinate transport regression only, not visual realism or reference fidelity'}+ result['probeAxes'] = probe_axes(context, args)+ from authoring.calibration import runtime_fixture+ result['runtimeLightmap'] = runtime_fixture(context, args)+ (context.evidence / 'calibration.json').write_text(json.dumps(result, indent=2))+ return result+++def probe_axes(context, args):+ """Measure actual equirectangular export against Three's cardinal UV convention."""+ import math+ import bpy+ import numpy as np+ bpy.ops.wm.read_factory_settings(use_empty=True)+ h = context.helpers+ fixtures = [+ ('positiveX', (2,0,0), (.05,4,4), (1,0,0), .5),+ ('positiveZ', (0,-2,0), (4,.05,4), (0,1,0), .75),+ ('negativeX', (-2,0,0), (.05,4,4), (0,0,1), 0.0),+ ('negativeZ', (0,2,0), (4,.05,4), (1,1,0), .25),+ ]+ for name, position, size, color, u in fixtures:+ material = h.material('Axis.'+name, color)+ tree = material.node_tree+ tree.nodes.clear()+ emission = tree.nodes.new('ShaderNodeEmission')+ emission.inputs['Color'].default_value = (*color,1)+ output = tree.nodes.new('ShaderNodeOutputMaterial')+ tree.links.new(emission.outputs[0], output.inputs['Surface'])+ h.box(name, position, size, material, 'calibration')+ data = bpy.data.cameras.new('AxisProbe')+ data.type = 'PANO'+ data.panorama_type = 'EQUIRECTANGULAR'+ camera = bpy.data.objects.new('AxisProbe', data)+ scene = bpy.context.scene+ scene.collection.objects.link(camera)+ camera.rotation_euler = (math.pi/2, 0, -math.pi/2)+ scene.camera = camera+ scene.render.engine = 'CYCLES'+ scene.cycles.samples = args.samples+ scene.cycles.use_denoising = False+ scene.render.resolution_x, scene.render.resolution_y = 256, 128+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = 'OPEN_EXR'+ scene.render.image_settings.color_depth = '32'+ scene.render.image_settings.color_mode = 'RGBA'+ path = context.evidence / 'calibration-probe.exr'+ scene.render.filepath = str(path)+ bpy.ops.render.render(write_still=True)+ image = bpy.data.images.load(str(path), check_existing=False)+ pixels = np.array(image.pixels[:], dtype=np.float32).reshape(128,256,4)+ readings = {}+ for name, position, size, color, u in fixtures:+ actual = pixels[64, int(u*256), :3]+ error = float(np.max(np.abs(actual-np.array(color))))+ if error > .001:+ raise RuntimeError(f'Probe coordinate mismatch at {name}, u={u}: {actual.tolist()}')+ readings[name] = {'u':u, 'rgb':actual.tolist(), 'maxError':error}+ bpy.data.images.remove(image)+ return readingsdiff --git a/examples/oak-linen-intake.json b/examples/oak-linen-intake.jsonnew file mode 100644index 0000000..fdc5e6d--- /dev/null+++ b/examples/oak-linen-intake.json@@ -0,0 +1,13 @@+{+ "schemaVersion": 1,+ "sourceKind": "synthetic-design-reference",+ "authorization": "The project owner explicitly authorized the Oak / Linen synthetic design reference for interior authoring. This declaration applies only to that showcase image, not arbitrary future inputs.",+ "scale": {+ "unit": "m",+ "basis": "authored-estimate",+ "note": "Single-image room dimensions, camera, hidden surfaces and textile parameters are authored design estimates, not a measured survey."+ },+ "components": ["room-shell", "glazing", "curtains", "sofa", "pillows", "rug", "coffee-table", "armchair", "console", "lights", "artwork", "garden-context"],+ "unknowns": ["Absolute scale is not recovered from the image", "Unseen surfaces and construction are authored", "Static indirect lighting does not rebounce with curtain or finish changes", "Real-phone performance is not verified"],+ "interactionRequired": true+}diff --git a/examples/oak-linen-material-policy.json b/examples/oak-linen-material-policy.jsonnew file mode 100644index 0000000..bc589b7--- /dev/null+++ b/examples/oak-linen-material-policy.json@@ -0,0 +1,7 @@+{+ "schemaVersion": 1,+ "materials": [+ {"name":"Interior.CurtainLinen__textiles","requireBaseColorTexture":true,"requireNormalTexture":true,"requireRoughnessTexture":true,"minRoughnessFactor":0.8,"maxMetallicFactor":0,"maxSheenColorFactor":0.2,"texCoord":0},+ {"name":"Interior.CurtainLinen__details","requireBaseColorTexture":true,"requireNormalTexture":true,"requireRoughnessTexture":true,"minRoughnessFactor":0.8,"maxMetallicFactor":0,"maxSheenColorFactor":0.2,"texCoord":0}+ ]+}diff --git a/examples/studio/build_scene.py b/examples/studio/build_scene.pynew file mode 100644index 0000000..f11385a--- /dev/null+++ b/examples/studio/build_scene.py@@ -0,0 +1,97 @@+"""Small authored studio: actual desk, stool, shelf, window and optional moving linen.++Install this file and scene-spec.json in W. Supply an authorized source image at+spec.source. This fixture exercises transport/export, not source-image likeness.+"""+import json+import math+import bpy+from mathutils import Vector+++def build_scene(context):+ h = context.helpers+ bpy.ops.wm.read_factory_settings(use_empty=True)+ scene = bpy.context.scene+ scene.unit_settings.system = 'METRIC'+ # Deterministic physical material map, intentionally asymmetric for repair checks.+ path = context.assets / 'studio-textile.png'+ if not path.exists():+ image = bpy.data.images.new('StudioWovenMap', width=32, height=32, alpha=True)+ image.colorspace_settings.name = 'Non-Color'+ pixels = []+ for y in range(32):+ for x in range(32):+ thread = 0.86 if (x+y) % 2 else 1.0+ color = (0.65, 0.38, 0.19) if x < 11 and y > 18 else (0.62, 0.68, 0.72)+ pixels.extend([c*thread for c in color] + [1])+ image.pixels[:] = pixels+ image.filepath_raw = str(path)+ image.file_format = 'PNG'+ image.save()+ bpy.data.images.remove(image)+ plaster = h.material('Studio.Plaster', (0.7, 0.66, 0.56), 0.85)+ floor = h.material('Studio.Oak', (0.26, 0.16, 0.08), 0.48)+ blue = h.material('Studio.BlueJoinery', (0.045, 0.13, 0.19), 0.46)+ steel = h.material('Studio.Steel', (0.1, 0.11, 0.12), 0.3, metallic=0.8)+ cloth = h.material('Studio.Textile', (1, 1, 1), 0.9,+ maps={'color': str(path.relative_to(context.workspace))})+ shader = next(n for n in cloth.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')+ shader.inputs['Sheen Weight'].default_value = 0.12+ shader.inputs['Sheen Tint'].default_value = (0.8, 0.5, 0.25, 1)+ h.box('room.floor', (0, 0, -0.06), (4.2, 4.6, 0.12), floor, 'floor')+ h.box('room.back', (0, 2.3, 1.4), (4.2, 0.12, 2.8), plaster, 'walls')+ h.box('room.right', (2.1, 0, 1.4), (0.12, 4.6, 2.8), plaster, 'walls')+ h.box('room.front', (0, -2.3, 1.4), (4.2, 0.12, 2.8), plaster, 'walls')+ h.box('room.ceiling', (0, 0, 2.85), (4.2, 4.6, 0.1), plaster, 'ceiling')+ # Left wall has a real large opening, asymmetric upper and lower returns.+ h.box('window.sill-wall', (-2.1, 0, 0.22), (0.12, 4.6, 0.44), plaster, 'walls')+ h.box('window.header', (-2.1, 0, 2.68), (0.12, 4.6, 0.24), plaster, 'walls')+ for y in (-2.25, 0.55, 2.25):+ h.box('window.mullion.'+str(y), (-2.1, y, 1.5), (0.08, 0.045, 2.2), steel, 'windows')+ h.box('desk.top', (0.55, 1.45, 0.77), (1.65, 0.72, 0.065), floor, 'desk', 0.015)+ for x in (-0.15, 1.25):+ for y in (1.17, 1.73):+ h.box(f'desk.leg.{x}.{y}', (x, y, 0.37), (0.045, 0.045, 0.74), steel, 'desk')+ h.box('stool.seat', (0.25, 0.55, 0.47), (0.55, 0.48, 0.12), cloth, 'stool', 0.025, finish='seat')+ for x in (0.04, 0.46):+ for y in (0.38, 0.72):+ h.box(f'stool.leg.{x}.{y}', (x, y, 0.22), (0.045, 0.045, 0.44), blue, 'stool')+ h.box('shelf.left-panel', (-1.25, 1.95, 0.66), (0.05, 0.45, 1.32), blue, 'shelf')+ h.box('shelf.right-panel', (-0.65, 1.95, 0.66), (0.05, 0.45, 1.32), blue, 'shelf')+ for z in (0.1, 0.65, 1.3):+ h.box('shelf.board.'+str(z), (-0.95, 1.95, z), (0.65, 0.45, 0.045), blue, 'shelf')+ h.lathe('desk.cup', [(0,0),(0.055,0),(0.06,0.12),(0.052,0.12),(0.047,0.01),(0,0.01)],+ plaster, 'cup', (0.95,1.5,0.804), segments=24)+ if context.spec['authoring'].get('includeCurtain', True):+ h.curtain('curtain.studio', (-1.93, 1.95, 0), (0,-1,0), (1,0,0),+ 0.48, 2.1, 2.42, cloth, panel_id='studio', floor=0.08, folds=4)+ world = bpy.data.worlds.new('Studio.SolidDaylight')+ world.use_nodes = True+ world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.65, 0.75, 1.0, 1)+ world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0.35+ scene.world = world+ sun = h.light('Studio.Sun', 'SUN', (-5,-3,6), (0,1,0), 1.8, (1,0.94,0.84))+ sun.data.angle = math.radians(1)+ area = h.light('Studio.WindowFill', 'AREA', (-2.5,0.1,1.8), (0,0.7,0.7), 150, (0.9,0.95,1))+ area.data.shape = 'RECTANGLE'+ area.data.size, area.data.size_y = 2.5, 1.9+ pose = context.spec['authoring']['cameraEstimate']+ data = bpy.data.cameras.new('Studio.SourceCamera')+ camera = bpy.data.objects.new('Studio.SourceCamera', data)+ scene.collection.objects.link(camera)+ camera.location = pose['position']+ camera.rotation_euler = (Vector(pose['target'])-camera.location).to_track_quat('-Z','Y').to_euler()+ data.lens, data.sensor_width = pose['lensMm'], pose['sensorWidthMm']+ data.sensor_fit = 'HORIZONTAL'+ scene.camera = camera+ bpy.context.view_layer.update()+ components = {}+ for obj in scene.objects:+ if obj.type == 'MESH':+ components.setdefault(obj['component'], []).append(obj.name)+ summary = {'schemaVersion':1, 'roomBounds':{'min':[-2.04,-2.24,0], 'max':[2.04,2.24,2.8]},+ 'camera':pose, 'views':context.spec['authoring']['inspectionViews'],+ 'components':components, 'assumptions':context.spec['assumptions']}+ scene['interior_metadata'] = json.dumps(summary)+ return summarydiff --git a/examples/studio/scene-spec.json b/examples/studio/scene-spec.jsonnew file mode 100644index 0000000..4fc5383--- /dev/null+++ b/examples/studio/scene-spec.json@@ -0,0 +1,31 @@+{+ "schemaVersion": 1,+ "title": "Asymmetric studio · transport fixture",+ "source": "public/assets/reference.png",+ "sourceKind": "render",+ "sourceViewLimit": "This authored mechanism fixture does not claim likeness to the supplied image. Example sourceKind assumes a rendered reference: replace it with photo, render, synthetic-design-reference, or floorplan according to the actual caller image. Replace dimensions/camera/builder for actual reconstruction.",+ "authoring": {+ "sceneBuilder": "build_scene.py",+ "sourceImageSize": [960, 720],+ "room": {"x": [-2.04, 2.04], "y": [-2.24, 2.24], "height": 2.8},+ "cameraEstimate": {"position": [0.8, -1.9, 1.45], "target": [-0.25, 1.1, 1.0], "lensMm": 23, "sensorWidthMm": 36},+ "probePosition": [0, -0.4, 1.3],+ "inspectionViews": {+ "desk": {"position": [1.4, -0.5, 1.6], "target": [0.3, 1.45, 0.8]},+ "curtain": {"position": [1.3, -0.8, 1.5], "target": [-1.93, 1.3, 1.3]},+ "reverse": {"position": [-1.4, 1.2, 1.6], "target": [0.2, -1.1, 1.0]}+ },+ "includeCurtain": true+ },+ "runtime": {+ "background": null,+ "backgroundIntensity": 1,+ "finishTarget": "seat",+ "variants": [+ {"id": "blue", "label": "Blue grey textile", "color": "#a3afb8", "roughness": 0.9},+ {"id": "ochre", "label": "Ochre textile", "color": "#b89050", "roughness": 0.9}+ ]+ },+ "portability": "Portable contains static baked full diffuse lighting; runtime uses ambient EXR plus shadowed SUN. Probe and bounce are static. Original editable PBR is in the packed master.",+ "assumptions": ["Metric asymmetric studio authored as a fast physical integration fixture, not a universal template.", "Solid world, no external HDRI or downloaded resources required.", "Deterministic textile PNG is a real map for packed-image repair and export testing, not a realism claim."]+}diff --git a/gates.json b/gates.jsonnew file mode 100644index 0000000..72a0595--- /dev/null+++ b/gates.json@@ -0,0 +1,5 @@+[+ {"id":"interior-materials","command":"python3 \"{plugin_dir}/tools/audit_materials.py\" --workspace \"{workspace}\" --gate","actor":"program","blocking":true,"after":[]},+ {"id":"interior-delivery","command":"python3 \"{plugin_dir}/tools/audit_delivery.py\" --workspace \"{workspace}\" --gate","actor":"program","blocking":true,"after":["interior-materials"]},+ {"id":"interior-workflow","command":"python3 \"{plugin_dir}/tools/gate_workflow.py\" --workspace \"{workspace}\"","actor":"program","blocking":true,"after":["interior-delivery"]}+]diff --git a/plugin.json b/plugin.jsonnew file mode 100644index 0000000..3253e7f--- /dev/null+++ b/plugin.json@@ -0,0 +1,8 @@+{+ "schema": 1,+ "name": "interior",+ "version": "0.2.0",+ "description": "Agent-operated image/reference analysis, Poly Haven acquisition, Blender/Python authoring and PBR, render/repair, bake/export, Three.js interaction and verified native/runtime/portable delivery.",+ "capabilities": [{"from": "image", "to": "interior-scene-candidate"}],+ "requires": {"harness": ">=0.4.0", "coreApi": 1}+}diff --git a/recipes/oak-linen/build_scene.py b/recipes/oak-linen/build_scene.pynew file mode 100644index 0000000..c27d8e1--- /dev/null+++ b/recipes/oak-linen/build_scene.py@@ -0,0 +1,619 @@+"""Explicit hash-guarded Oak/Linen recipe, not a generic image interpreter."""++import json+import math++import bpy+import bmesh+from mathutils import Matrix, Vector++def _curtain_material(context, linen_maps):+ _material = context.helpers.material+ ROOT = context.workspace+ material = _material('Interior.CurtainLinen', (0.85, 0.81, 0.71), 0.94,+ maps={'normal': linen_maps['normal'], 'roughness': 'public/assets/interior/curtain-roughness.png'},+ color_path=ROOT / 'public/assets/interior/curtain-basecolor.png', normal_strength=0.70)+ tree = material.node_tree+ shader = next(node for node in tree.nodes if node.type == 'BSDF_PRINCIPLED')+ shader.inputs['Specular IOR Level'].default_value = 0.25+ shader.inputs['Sheen Weight'].default_value = 0.12+ shader.inputs['Sheen Roughness'].default_value = 0.90+ uv = tree.nodes.new('ShaderNodeUVMap')+ uv.uv_map = 'UV0'+ for texture in tree.nodes:+ if texture.type == 'TEX_IMAGE':+ tree.links.new(uv.outputs['UV'], texture.inputs['Vector'])+ return material+++def _table_vase(helpers, mat, location):+ """Smooth cubic meridian, 6 mm shell, open neck and closed ceramic foot."""+ _lathe = helpers.lathe+ profile = [(0.0, 0.0), (0.052, 0.0)]++ def arc(control_a, control_b, end, steps=20):+ start = profile[-1]+ for i in range(1, steps + 1):+ t = i / steps+ s = 1 - t+ profile.append(tuple(s**3 * start[k] + 3*s*s*t * control_a[k]+ + 3*s*t*t * control_b[k] + t**3 * end[k]+ for k in range(2)))++ arc((0.054, 0.0), (0.052, 0.025), (0.052, 0.040), 12)+ arc((0.052, 0.065), (0.120, 0.075), (0.120, 0.130))+ arc((0.120, 0.195), (0.035, 0.205), (0.035, 0.235), 28)+ arc((0.035, 0.250), (0.035, 0.280), (0.035, 0.296), 12)+ arc((0.035, 0.3013), (0.029, 0.3013), (0.029, 0.296), 12)+ arc((0.029, 0.280), (0.029, 0.250), (0.029, 0.235), 12)+ arc((0.029, 0.199), (0.114, 0.189), (0.114, 0.130), 28)+ arc((0.114, 0.081), (0.046, 0.071), (0.046, 0.045))+ arc((0.046, 0.020), (0.020, 0.012), (0.0, 0.012), 16)+ return _lathe('table-vase.body', profile, mat, 'table-vase', location, segments=96)+++def _book(helpers, name, center, size, cover, paper):+ _box = helpers.box+ x, y, z = center+ w, d, h = size+ _box(name + '.pages', (x, y, z+h/2), (w-0.009, d-0.009, h-0.006), paper, 'books', 0.001)+ for side in (0, 1):+ _box(name + f'.cover.{side}', (x, y, z+0.0015+side*(h-0.003)), (w, d, 0.003), cover, 'books', 0.001)+ _box(name + '.spine', (x-w/2+0.002, y, z+h/2), (0.004, d, h), cover, 'books', 0.001)+++def _source_table(helpers, center, stone, metal):+ """Source's thin disk and three radial U-shaped hairpin legs."""+ _lathe, _project_uv, _tube = helpers.lathe, helpers.project_uv, helpers.tube+ x, y, floor = center+ top = 0.435 + floor+ disk = _lathe('coffee-table.marble-top',+ [(0, top-0.029), (0.696, top-0.029), (0.708, top-0.022),+ (0.712, top-0.009), (0.704, top), (0, top)],+ stone, 'coffee-table', (x, y, 0), segments=128)+ _project_uv(disk, 1.5)+ for uv in disk.data.uv_layers.active.data:+ uv.uv += Vector((0.5, 0.5))+ # Two convex-hull-bounded Bezier bends share a horizontal floor tangent.+ # The shared apex is one tube radius above the rug; both ends stay in the stone.+ controls = (+ ((0.29,top-0.030),(0.39,floor+0.120),(0.44,floor+0.012),(0.49,floor+0.012)),+ ((0.49,floor+0.012),(0.54,floor+0.012),(0.60,floor+0.120),(0.63,top-0.030)))+ profile = []+ for a, b, c, d in controls:+ for step in range(24):+ t, u = step/24, 1-step/24+ profile.append((u**3*a[0]+3*u*u*t*b[0]+3*u*t*t*c[0]+t**3*d[0],+ u**3*a[1]+3*u*u*t*b[1]+3*u*t*t*c[1]+t**3*d[1]))+ profile.append(controls[-1][-1])+ for index, angle in enumerate((math.pi/2, math.pi*7/6, math.pi*11/6)):+ cosine, sine = math.cos(angle), math.sin(angle)+ points = [(x+r*cosine, y+r*sine, z) for r, z in profile]+ _tube(f'coffee-table.hairpin.{index}', points, 0.012, metal, 'coffee-table')+ return top+++def _source_chair(helpers, center, yaw, wood, leather, rug):+ """Low lounge chair with canted tapered legs, flowing arms and separate leather pads."""+ _cushion, _mesh, _tube = helpers.cushion, helpers.mesh, helpers.tube+ before = set(bpy.data.objects)+ transform = (Matrix.Translation(Vector(center)) @ Matrix.Rotation(yaw, 4, 'Z')+ @ Matrix.Diagonal((0.825, 0.99, 1.0, 1.0)))+ _cushion('armchair.seat-pad', (0, -0.10, 0.435), (0.86, 0.84, 0.17),+ leather, exponent=4.0, component='armchair', finish=None, tile=0.50,+ seam_levels=(-0.6,), seam_radius=0.0012, resolution=42)+ _cushion('armchair.back-pad', (0, 0.275, 0.66), (0.82, 0.55, 0.18),+ leather, (math.radians(72), 0, 0), phase=2.6, exponent=3.2,+ component='armchair', finish=None, tile=0.50,+ seam_levels=(0.65,), seam_radius=0.0012, resolution=42)+ for side in (-1, 1):+ for label, bottom, upper in (+ ('front', (side*0.475, -0.48, 0), (side*0.405, -0.335, 0.65)),+ ('rear', (side*0.475, 0.49, 0), (side*0.385, 0.34, 0.87))):+ contact = transform @ Vector(bottom)+ support = rug[4] if rug[0] <= contact.x <= rug[1] and rug[2] <= contact.y <= rug[3] else 0+ vertices = [(p[0]+r*math.cos(i*math.tau/24), p[1]+r*math.sin(i*math.tau/24), p[2]+dz)+ for p, r, dz in ((bottom, 0.019, support), (upper, 0.033, 0))+ for i in range(24)]+ faces = [(i, (i+1)%24, (i+1)%24+24, i+24) for i in range(24)]+ faces.extend([tuple(reversed(range(24))), tuple(range(24, 48))])+ obj = _mesh(f'armchair.{label}-leg.{side}', vertices, faces, wood, 'armchair', tile=1.4)+ for face in obj.data.polygons:+ face.use_smooth = len(face.vertices) == 4+ _tube(f'armchair.side-apron.{side}', [(side*0.41, -0.35, 0.345), (side*0.405, 0.35, 0.36)],+ 0.024, wood, 'armchair')+ rail = []+ for i in range(41):+ t = i/40+ rail.append((side*(0.455-0.055*t), -0.52+0.92*t,+ 0.635-0.025*math.sin(math.pi*t)+0.235*t*t))+ _tube(f'armchair.curved-arm.{side}', rail, 0.022, wood, 'armchair')+ for y, z in ((-0.335, 0.345), (0.34, 0.365), (0.34, 0.85)):+ _tube(f'armchair.crossrail.{z}', [(-0.405, y, z), (0.405, y, z)], 0.021, wood, 'armchair')+ for obj in set(bpy.data.objects)-before:+ # Bake the complete affine placement into vertices; no TRS shear loss on pads.+ placement = transform @ obj.matrix_world+ for vertex in obj.data.vertices:+ vertex.co = placement @ vertex.co+ obj.matrix_world = Matrix.Identity(4)+++def _curtain(helpers, name, anchor, width, mat, *, panel_id, direction, closed_width=3.10):+ """Rail-mounted linen; UV0 also preserves material coordinates for runtime cloth."""+ _mesh, _tube = helpers.mesh, helpers.tube+ vertices, faces = [], []+ nx, nz = 100, 32+ folds = 7 if panel_id == 'front' else 9+ settings = {+ 'curtain_id': panel_id, 'curtain_anchor': anchor, 'curtain_direction': direction,+ 'curtain_open_width': width, 'curtain_closed_width': closed_width,+ 'curtain_height': 3.086, 'curtain_floor': 0.014, 'curtain_folds': folds,+ 'curtain_fabric_width': 3.65, 'curtain_tile': 0.65, 'curtain_plane_x': -2.98,+ 'curtain_rail_axis': [0, 0, -direction],+ 'curtain_depth_axis': [1, 0, 0],+ 'curtain_plane_origin': [-2.98, 0, -anchor],+ }++ def attach(obj, part):+ for key, value in settings.items():+ obj[key] = value+ obj['curtain_part'] = part+ return obj++ for j in range(nz + 1):+ v = j / nz+ for i in range(nx + 1):+ u = i / nx+ y = anchor + direction * (width*u + 0.008*math.sin(v*math.pi)*math.sin(u*19))+ x = -2.98 + (0.085+0.015*(1-v))*math.sin(u*math.tau*folds)+ x += 0.010*math.sin(u*math.tau*folds*2+0.4*v)+ vertices.append((x, y, 0.014+3.086*v+0.007*(1-v)*math.sin(u*49)))+ for j in range(nz):+ for i in range(nx):+ a = j*(nx+1)+i+ faces.append((a, a+1, a+nx+2, a+nx+1))+ obj = attach(_mesh(name, vertices, faces, mat, 'curtains', tile=0.65), 'cloth')+ uv = obj.data.uv_layers['UV0']+ for polygon in obj.data.polygons:+ polygon.use_smooth = True+ for loop_index in polygon.loop_indices:+ vertex = obj.data.loops[loop_index].vertex_index+ j, i = divmod(vertex, nx+1)+ uv.data[loop_index].uv = (i/nx*3.65/0.65, j/nz*3.086/0.65)+ solid = obj.modifiers.new('Hemmed cloth thickness', 'SOLIDIFY')+ solid.thickness = 0.0015+ for end, j, v in (('bottom', 0, 0), ('top', nz, 1)):+ hem = attach(_tube(name+'.'+end+'-hem', vertices[j*(nx+1):(j+1)*(nx+1)],+ 0.003, mat, 'curtains'), 'hem')+ hem['curtain_v'] = v+ for i in range(folds+1):+ u = i/folds+ y = anchor+direction*width*u+ hook = attach(_tube(name+f'.hook.{i:02}', [(-2.98, y, 3.10), (-2.98, y, 3.14)],+ 0.003, mat, 'curtains'), 'hook')+ hook['curtain_u'] = u+ return obj+++def build_scene(context) -> dict:+ """Build the complete editable PBR scene and return JSON-serializable metadata."""+ import hashlib+ CONTEXT, ROOT = context, context.workspace+ helpers = context.helpers+ _material, _box, _mesh = helpers.material, helpers.box, helpers.mesh+ _cushion, _lathe, _tube = helpers.cushion, helpers.lathe, helpers.tube+ _image, _import_model, _bounds = helpers.image, helpers.import_model, helpers.bounds+ _activate, _tag, _project_uv = helpers.activate, helpers.tag, helpers.project_uv+ _light = helpers.light+ contract = CONTEXT.spec+ expected = '95eb31d840165964deac849813dc77ad18bad71f1df90770bff1f7b4a5fb666b'+ if hashlib.sha256(CONTEXT.resolve(contract['source']).read_bytes()).hexdigest() != expected:+ raise ValueError('Oak/Linen requires its exact authorized reference image; author a new builder for a different room')+ resources = json.loads(CONTEXT.resolve(contract['authoring']['resourceManifest']).read_text())+ for category in ('models', 'hdris'):+ for path in resources[category].values():+ CONTEXT.resolve(path)+ for maps in resources['textures'].values():+ for path in maps.values():+ CONTEXT.resolve(path)+ artwork = ROOT / 'public/assets/interior/artwork.png'+ linen = ROOT / 'public/assets/interior/linen-neutral.png'+ walnut_color = ROOT / 'public/assets/interior/walnut-color.png'+ surfaces = {name: ROOT / f'public/assets/interior/{name}.png' for name in (+ 'floor-oak-color', 'plaster-color', 'rug-basecolor', 'rug-normal', 'rug-roughness',+ 'curtain-basecolor', 'curtain-roughness', 'chair-oak-color', 'leather-basecolor',+ 'leather-roughness', 'marble-basecolor', 'marble-normal')}+ required = [artwork, linen, walnut_color, *surfaces.values()]+ required += [ROOT / p for p in resources['models'].values()]+ required += [ROOT / p for maps in resources['textures'].values() for p in maps.values()]+ required += [ROOT / p for p in resources['hdris'].values()]+ missing = [str(p) for p in required if not p.is_file()]+ if missing:+ raise FileNotFoundError('Required interior resources missing: ' + ', '.join(missing))+ bpy.ops.wm.read_factory_settings(use_empty=True)+ scene = bpy.context.scene+ scene.unit_settings.system = 'METRIC'+ scene.unit_settings.scale_length = 1.0+ tex = resources['textures']+ plaster = _material('Interior.WarmPlaster', (0.72, 0.67, 0.57), maps=tex['painted_plaster_wall'], color_path=surfaces['plaster-color'], normal_strength=0.20)+ ceiling = _material('Interior.CeilingIvory', (0.83, 0.81, 0.75), 0.85)+ oak = _material('Interior.OakFloor', (0.49, 0.39, 0.26), maps=tex['oak_wood_planks'], color_path=surfaces['floor-oak-color'], normal_strength=0.35)+ walnut = _material('Interior.WalnutCabinet', (0.18, 0.075, 0.032), maps=tex['oak_veneer_03'], color_path=walnut_color, normal_strength=0.20)+ chair_wood = _material('Interior.ChairNaturalOak', (0.32, 0.215, 0.12), 0.38, maps={'normal': tex['oak_veneer_03']['normal']}, color_path=surfaces['chair-oak-color'], normal_strength=0.15)+ leather = _material('Interior.ChairBlackLeather', (0.022, 0.022, 0.018), 0.43, maps={'normal': tex['brown_leather']['normal'], 'roughness': str(surfaces['leather-roughness'].relative_to(ROOT))}, color_path=surfaces['leather-basecolor'], normal_strength=0.35)+ marble = _material('Interior.TableIvoryMarble', (0.78, 0.75, 0.67), 0.27, maps={'normal': str(surfaces['marble-normal'].relative_to(ROOT))}, color_path=surfaces['marble-basecolor'], normal_strength=0.10)+ bronze = _material('Interior.BrushedBronze', (0.13, 0.11, 0.085), 0.30, 0.8)+ dark = _material('Interior.DarkJoinery', (0.025, 0.019, 0.012), 0.45)+ upholstery = _material('Interior.SofaCreamLinen', (0.84, 0.78, 0.67), maps=tex['rough_linen'], color_path=linen, normal_strength=0.45)+ linen_relief = {key: tex['rough_linen'][key] for key in ('normal', 'roughness')}+ tan = _material('Interior.SofaTanLinen', (0.39, 0.27, 0.16), maps=linen_relief, normal_strength=0.45)+ rug_mat = _material('Interior.WovenIvoryRug', (0.64, 0.60, 0.50),+ maps={'normal': str(surfaces['rug-normal'].relative_to(ROOT)), 'roughness': str(surfaces['rug-roughness'].relative_to(ROOT))},+ color_path=surfaces['rug-basecolor'], normal_strength=0.65)+ curtain_mat = _curtain_material(context, tex['rough_linen'])+ shade_mat = _material('Interior.LinenShade', (0.80, 0.69, 0.49), maps=linen_relief, normal_strength=0.15)+ ceramic = _material('Interior.GlazedCreamCeramic', (0.74, 0.70, 0.61), 0.32)+ pages = _material('Interior.BookPaper', (0.79, 0.75, 0.64), 0.82)+ book_white = _material('Interior.BookCoverIvory', (0.65, 0.62, 0.54), 0.55)+ book_brown = _material('Interior.BookCoverUmber', (0.13, 0.08, 0.045), 0.57)+ ground = _material('Exterior.GardenSoil', (0.065, 0.047, 0.026), 0.95)+ stone = _material('Exterior.TerraceStone', (0.42, 0.40, 0.34), 0.83)+ glass = _material('Interior.WindowGlass', (0.98, 0.99, 1), 0.035)+ glass_shader = next(n for n in glass.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')+ glass_shader.inputs['Transmission Weight'].default_value = 1+ glass_shader.inputs['IOR'].default_value = 1.45+ # Parallel 6 mm clear panes have negligible net angular deviation. Cycles+ # shadow rays use straight-through interface transmission; camera/glossy+ # rays retain the refractive Principled surface. Geometry still casts shadows.+ tree = glass.node_tree+ path = tree.nodes.new('ShaderNodeLightPath')+ transmitted = tree.nodes.new('ShaderNodeBsdfTransparent')+ transmitted.inputs['Color'].default_value = (0.96, 0.96, 0.96, 1)+ shadow_mix = tree.nodes.new('ShaderNodeMixShader')+ tree.links.new(path.outputs['Is Shadow Ray'], shadow_mix.inputs[0])+ tree.links.new(glass_shader.outputs['BSDF'], shadow_mix.inputs[1])+ tree.links.new(transmitted.outputs[0], shadow_mix.inputs[2])+ output = next(node for node in tree.nodes if node.type == 'OUTPUT_MATERIAL')+ tree.links.new(shadow_mix.outputs[0], output.inputs['Surface'])+ glass['thin_pane_shadow_transmittance'] = 0.96++ room = contract['authoring']['room']+ xmin, xmax = room['x']+ ymin, ymax = room['y']+ ymin = min(ymin, -6.4) # Authored unseen shell extension, behind source camera.+ height = room['height']+ midx, midy = (xmin + xmax) / 2, (ymin + ymax) / 2+ _box('architecture.floor', (midx, midy, -0.09), (xmax-xmin+0.3, ymax-ymin+0.3, 0.18), oak, 'floor', 0.006, tile=1.8)+ _box('architecture.back-wall', (midx, ymax+0.1, height/2), (xmax-xmin+0.4, 0.2, height), plaster, 'walls', 0.008, tile=2.0)+ _box('architecture.right-wall', (xmax+0.1, midy, height/2), (0.2, ymax-ymin, height), plaster, 'walls', 0.008, tile=2.0)+ _box('architecture.ceiling', (midx, midy, height+0.10), (xmax-xmin+0.4, ymax-ymin+0.4, 0.2), ceiling, 'ceiling')+ _box('architecture.front-wall', (midx, ymin-0.1, height/2), (xmax-xmin+0.4, 0.2, height), plaster, 'walls', 0.008, tile=2.0)+ window_min, window_end = -4.0, 2.2+ window_mid = (window_min+window_end)/2+ _box('architecture.left-extension', (xmin-0.1, (ymin+window_min)/2, height/2), (0.2, window_min-ymin, height), plaster, 'walls', 0.008, tile=2.0)+ _box('architecture.left-rear-return', (xmin-0.1, (window_end+ymax)/2, height/2), (0.2, ymax-window_end, height), plaster, 'walls', 0.008, tile=2.0)+ _box('architecture.skirt.back', (midx, ymax-0.012, 0.045), (xmax-xmin, 0.025, 0.09), plaster, 'walls', 0.004)+ _box('architecture.skirt.right', (xmax-0.012, midy, 0.045), (0.025, ymax-ymin, 0.09), plaster, 'walls', 0.004)+ for z in (0.035, height-0.035):+ _box(f'window.horizontal.{z:.3f}', (xmin, window_mid, z), (0.09, window_end-window_min, 0.07), bronze, 'windows', 0.006)+ divisions = 5+ for i in range(divisions + 1):+ y = window_min + (window_end-window_min) * i / divisions+ _box(f'window.mullion.{i:02}', (xmin, y, height/2), (0.065, 0.035, height), bronze, 'windows', 0.004)+ if i < divisions:+ spacing = (window_end-window_min)/divisions+ _box(f'window.glass.{i:02}', (xmin-0.014, y+spacing/2, height/2), (0.006, spacing-0.035, height-0.07), glass, 'windows')+ _tube('window.door-handle', [(xmin+0.07, -0.03, 0.93), (xmin+0.12, -0.03, 0.93), (xmin+0.12, -0.03, 1.14), (xmin+0.07, -0.03, 1.14)], 0.009, bronze, 'windows')+ _box('curtains.track', (-2.98, window_mid, 3.14), (0.045, window_end-window_min, 0.035), ceiling, 'curtains', 0.006)+ _curtain(helpers, 'curtains.rear-panel', window_end, 0.88, curtain_mat, panel_id='rear', direction=-1)+ _curtain(helpers, 'curtains.front-panel', window_min, 0.68, curtain_mat, panel_id='front', direction=1)++ # Three tall soft seat fronts over an almost hidden plinth, not stacked mattresses.+ sx, sy = -0.65, 1.93+ for i, x in enumerate((sx-1.58, sx+1.58)):+ for j, y in enumerate((1.43, 2.30)):+ _box(f'sofa.foot.{i}.{j}', (x, y, 0.035+(0.007 if j == 0 else 0)),+ (0.10, 0.10, 0.07), walnut, 'sofa', 0.012)+ _box('sofa.lower-frame', (sx, 1.99, 0.105), (3.66, 0.85, 0.09), upholstery, 'sofa', 0.04, 0.75, 'sofa')+ _box('sofa.back-shell', (sx, 2.365, 0.435), (3.66, 0.25, 0.78), upholstery, 'sofa', 0.115, 0.75, 'sofa')+ for side in (-1, 1):+ _cushion('sofa.arm.' + ('left' if side < 0 else 'right'), (sx+side*1.71, 1.92, 0.35),+ (0.30, 1.14, 0.66), upholstery, exponent=8, seams=False)+ for i, x in enumerate((sx-1.095, sx, sx+1.095)):+ _cushion(f'sofa.seat.{i}', (x, 1.83, 0.24), (1.075, 1.0, 0.44), upholstery, phase=i*1.9, exponent=6, resolution=72)+ _cushion(f'sofa.back-cushion.{i}', (x, 2.27, 0.5925), (1.10, 0.435, 0.21), upholstery,+ (math.radians(83), 0, 0), phase=i*2.3, exponent=6, resolution=42)+ for profile in contract['authoring']['pillowProfiles']:+ _cushion('sofa.throw.' + profile['id'], profile['position'], profile['size'],+ tan if profile['id'] == 'right-back' else upholstery,+ tuple(math.radians(v) for v in profile['rotationDegrees']), profile['phase'],+ exponent=6, loose=True, seam_radius=0.0009, outline=profile['outline'], resolution=56)++ rug_center = (-0.645, 0.36)+ rug_width, rug_depth, rug_thickness = 4.21, 2.68, 0.007+ rug_left, rug_right = (rug_center[0]-rug_width/2, rug_center[0]+rug_width/2)+ rug_front, rug_back = (rug_center[1]-rug_depth/2, rug_center[1]+rug_depth/2)+ _box('rug.woven-body', (*rug_center, rug_thickness/2), (rug_width, rug_depth, rug_thickness), rug_mat, 'rug', 0.003, tile=0.36)+ for side in (-1, 1):+ y = rug_center[1] + side * (rug_depth/2-0.008)+ _tube(f'rug.bound-edge.{side}', [(rug_left+0.02, y, rug_thickness-0.001), (rug_right-0.02, y, rug_thickness-0.001)], 0.002, rug_mat, 'rug')+ # Short twisted yarn loops, rather than an alpha fringe strip.+ vertices, faces = [], []+ for side in (-1, 1):+ x = rug_center[0] + side * (rug_width/2-0.01)+ yarn_count = round((rug_depth-0.04)/0.0152) + 1+ for i in range(yarn_count):+ y = rug_front + 0.02 + i*(rug_back-rug_front-0.04)/(yarn_count-1)+ start = len(vertices)+ for j in range(5):+ t = j / 4+ for k in range(4):+ a = k * math.tau/4+ vertices.append((x + side*(0.035*t), y+0.0010*math.cos(a)+0.002*math.sin(t*math.tau), 0.003+0.0010*math.sin(a)+0.002*math.sin(t*math.pi)))+ for j in range(4):+ for k in range(4):+ faces.append((start+j*4+k, start+j*4+(k+1)%4, start+(j+1)*4+(k+1)%4, start+(j+1)*4+k))+ faces.extend([(start+3, start+2, start+1, start), tuple(start+16+k for k in range(4))])+ _mesh('rug.fringe-yarns', vertices, faces, rug_mat, 'rug', tile=0.36)++ models = resources['models']+ table_top = _source_table(helpers, (-0.65, 0.05, rug_thickness), marble, bronze)+ _source_chair(helpers, (0.98, -0.65, 0), math.radians(-105), chair_wood, leather,+ (rug_left, rug_right, rug_front, rug_back, rug_thickness))+ _table_vase(helpers, ceramic, (-0.65, 0.18, table_top+0.002))+ _lathe('table-bowl', [(0.025, 0), (0.042, 0), (0.046, 0.025), (0.105, 0.069), (0.114, 0.095), (0.107, 0.098), (0.099, 0.075), (0.038, 0.035), (0.025, 0.034)], ceramic, 'table-bowl', (-0.90, -0.20, table_top+0.002))+ for i, (x, y, w, d, h, cover) in enumerate(((-0.26, -0.09, 0.34, 0.24, 0.034, book_white), (-0.28, -0.075, 0.31, 0.225, 0.027, book_white))):+ _book(helpers, f'books.table.{i}', (x, y, table_top+0.002+(0.038 if i else 0)), (w, d, h), cover, pages)++ # Complete cabinet carcass with reveals; slats attach to individual doors.+ cx, cy, cw, cd = 2.95, 2.30, 1.72, 0.55+ for i, x in enumerate((cx-cw/2+0.10, cx+cw/2-0.10)):+ for j, y in enumerate((cy-cd/2+0.08, cy+cd/2-0.08)):+ _box(f'console.foot.{i}.{j}', (x, y, 0.08), (0.065, 0.065, 0.16), dark, 'console', 0.012)+ for label, z in (('bottom', 0.17), ('top', 0.95)):+ _box('console.' + label, (cx, cy, z), (cw, cd, 0.045), walnut, 'console', 0.008, tile=0.8)+ _box('console.back', (cx, cy+cd/2-0.015, 0.56), (cw-0.06, 0.03, 0.74), walnut, 'console', tile=0.8)+ for index, x in enumerate((cx-cw/2+0.02, cx, cx+cw/2-0.02)):+ _box(f'console.partition.{index}', (x, cy, 0.56), (0.035, cd-0.04, 0.74), walnut, 'console', tile=0.8)+ for door in range(2):+ x = cx + (door-0.5)*cw/2+ _box(f'console.door.{door}', (x, cy-cd/2-0.006, 0.56), (cw/2-0.009, 0.025, 0.735), walnut, 'console', 0.003, tile=0.8)+ for i in range(23):+ px = x-cw/4+0.024+i*(cw/2-0.048)/22+ _box(f'console.door.{door}.flute.{i:02}', (px, cy-cd/2-0.025, 0.56), (0.024, 0.025, 0.724), walnut, 'console', 0.011, tile=0.8)+ handle_x = x + (1 if door == 0 else -1)*(cw/4-0.08)+ _tube(f'console.handle.{door}', [(handle_x, cy-cd/2-0.044, 0.46), (handle_x, cy-cd/2-0.070, 0.46), (handle_x, cy-cd/2-0.070, 0.67), (handle_x, cy-cd/2-0.044, 0.67)], 0.006, bronze, 'console')+ console_z_scale = 0.88+ console_prop_base = 0.974 * console_z_scale+ _lathe('console.jug', [(0, 0), (0.045, 0), (0.065, 0.02), (0.060, 0.18),+ (0.048, 0.23), (0.043, 0.23), (0.055, 0.18), (0.059, 0.025), (0, 0.010)],+ ceramic, 'console-vase', (cx-0.08, cy-0.03, console_prop_base))+ _tube('console.jug-handle', [(cx-0.025, cy-0.03, console_prop_base+0.18),+ (cx+0.035, cy-0.03, console_prop_base+0.17),+ (cx+0.050, cy-0.03, console_prop_base+0.10),+ (cx-0.025, cy-0.03, console_prop_base+0.07)],+ 0.008, ceramic, 'console-vase')+ for i in range(2):+ _lathe(f'console.small-bowl.{i}', [(0.02, 0), (0.045, 0), (0.08, 0.045), (0.085, 0.075), (0.078, 0.076), (0.071, 0.048), (0.025, 0.012)],+ ceramic, 'console-bowl', (cx-0.42, cy-0.05, console_prop_base+i*0.022))+ for i in range(2):+ _book(helpers, f'books.console.{i}', (cx+0.50, cy-0.04, console_prop_base+i*0.035),+ (0.30, 0.22, 0.032), book_white if i else book_brown, pages)++ lx, ly = 1.32, 1.43+ _lathe('lamp.base', [(0.002, 0), (0.15, 0), (0.16, 0.006), (0.15, 0.012), (0.002, 0.012)], bronze, 'floor-lamp', (lx, ly, 0))+ _tube('lamp.stem', [(lx, ly, 0.010), (lx, ly, 1.65)], 0.009, bronze, 'floor-lamp')+ _lathe('lamp.open-shade', [(0.24, 1.35), (0.17, 1.69), (0.167, 1.69), (0.237, 1.35)], shade_mat, 'floor-lamp', (lx, ly, 0))+ for z, radius in ((1.35, 0.239), (1.69, 0.169)):+ _tube(f'lamp.shade-rim.{z}', [(lx+radius*math.cos(i*math.tau/96), ly+radius*math.sin(i*math.tau/96), z) for i in range(96)], 0.0035, shade_mat, 'floor-lamp', True)+ for i in range(3):+ a = i*math.tau/3+ _tube(f'lamp.spider.{i}', [(lx, ly, 1.53), (lx+0.18*math.cos(a), ly+0.18*math.sin(a), 1.51)], 0.0025, bronze, 'floor-lamp')+ bulb_mat = _material('Interior.LampBulb', (1, 0.78, 0.46), 0.22)+ bulb_shader = next(n for n in bulb_mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')+ bulb_shader.inputs['Emission Color'].default_value = (1, 0.64, 0.27, 1)+ bulb_shader.inputs['Emission Strength'].default_value = 2.5+ bpy.ops.mesh.primitive_uv_sphere_add(segments=24, ring_count=16, radius=0.035, location=(lx, ly, 1.53))+ bulb = _tag(bpy.context.object, 'lamp.bulb', 'floor-lamp')+ bulb.data.materials.append(bulb_mat)+ _project_uv(bulb)+ _light('lighting.lamp-bulb', 'POINT', (lx, ly, 1.53), (lx, ly, 0), 6, (1, 0.72, 0.40)).data.shadow_soft_size = 0.035++ art_mat = _material('Interior.ArtworkCanvas', (1, 1, 1), 0.88, color_path=artwork)+ ax, az, aw, ah = -0.65, 1.76, 1.67, 1.24+ _box('artwork.canvas-body', (ax, 2.651, az), (aw, 0.025, ah), ceiling, 'artwork', 0.001)+ art = _mesh('artwork.print', [(ax-aw/2, 2.637, az-ah/2), (ax+aw/2, 2.637, az-ah/2), (ax+aw/2, 2.637, az+ah/2), (ax-aw/2, 2.637, az+ah/2)], [(0, 1, 2, 3)], art_mat, 'artwork')+ for loop, uv in zip(art.data.uv_layers.active.data, ((0, 0), (1, 0), (1, 1), (0, 1))):+ loop.uv = uv+ for side in (-1, 1):+ _box(f'artwork.frame.vertical.{side}', (ax+side*(aw/2+0.009), 2.64, az), (0.018, 0.043, ah+0.036), walnut, 'artwork', 0.003)+ _box(f'artwork.frame.horizontal.{side}', (ax, 2.64, az+side*(ah/2+0.009)), (aw, 0.043, 0.018), walnut, 'artwork', 0.003)++ _box('garden.terrain', (-13.2, -0.8, -0.16), (20.0, 28.0, 0.20), ground, 'garden', 0.03, tile=2.0)+ _box('garden.terrace', (-3.80, -0.50, -0.045), (1.10, 10.0, 0.09), stone, 'garden', 0.008)+ _box('garden.window-threshold', (-3.28, window_mid, -0.035), (0.20, window_end-window_min, 0.07), stone, 'garden', 0.006)+ _box('garden.planted-border', (-4.43, window_mid, 0.045), (0.16, 10.0, 0.21), stone, 'garden', 0.012)+ _lathe('garden.white-planter', [(0,0), (0.215,0), (0.236,0.03), (0.275,0.62),+ (0.279,0.69), (0.270,0.69), (0.267,0.635),+ (0.225,0.035), (0,0.035)],+ ceramic, 'garden', (-4.1,2.3,0))+ _lathe('garden.planter-soil', [(0,0.035), (0.225,0.035), (0.267,0.64), (0,0.64)],+ ground, 'garden', (-4.1,2.3,0), segments=64)+ plant = _import_model(ROOT / models['potted_plant_02'], 'garden.plant.00', (-5.75, 1.75, -0.06), height=2.3)+ foliage = []+ for obj in plant:+ if any(slot.material.name.startswith('potted_plant_02_leaves') for slot in obj.material_slots):+ foliage.append(obj)+ else:+ bpy.data.objects.remove(obj, do_unlink=True)+ plant = foliage+ bpy.context.view_layer.update()+ ground_offset = -0.06 - _bounds(plant)[0][2]+ for obj in plant:+ obj.location.z += ground_offset+ # Linked real geometry instances, not photographs; no point-cloud cards.+ bpy.context.view_layer.update()+ source_origin = Vector((-5.75, 1.75, -0.06))+ for index, (position, scale, yaw) in enumerate((+ ((-6.0, -0.7, -0.06), 1.2, 0.8), ((-5.8, -3.3, -0.06), 0.85, 2.1),+ ((-7.0, 3.5, -0.06), 1.8, 1.1), ((-7.2, 0.2, -0.06), 1.9, 2.9),+ ((-6.9, -3.4, -0.06), 1.6, 4.1), ((-8.5, 1.6, -0.06), 2.0, 1.4),+ ((-4.1, 2.3, 0.64), 0.45, 0.4)), start=1):+ transform = (Matrix.Translation(Vector(position)) @ Matrix.Rotation(yaw, 4, 'Z')+ @ Matrix.Scale(scale, 4) @ Matrix.Translation(-source_origin))+ for part, source in enumerate(plant):+ obj = source.copy()+ obj.data = source.data+ bpy.context.scene.collection.objects.link(obj)+ obj.matrix_world = transform @ source.matrix_world+ _tag(obj, f'garden.plant.{index:02}.{part:02}', 'garden')+ for obj in plant:+ obj['component'] = 'garden'++ world = bpy.data.worlds.new('Interior.GardenDaylight')+ scene.world = world+ world.use_nodes = True+ nodes = world.node_tree.nodes+ nodes.clear()+ environment = nodes.new('ShaderNodeTexEnvironment')+ environment.image = _image(ROOT / resources['hdris']['meadow'], False)+ background = nodes.new('ShaderNodeBackground')+ background.inputs['Strength'].default_value = 0.22+ camera_background = nodes.new('ShaderNodeBackground')+ camera_background.inputs['Strength'].default_value = 1.20+ paths = nodes.new('ShaderNodeLightPath')+ visible = nodes.new('ShaderNodeMath')+ visible.operation = 'MAXIMUM'+ mix = nodes.new('ShaderNodeMixShader')+ output = nodes.new('ShaderNodeOutputWorld')+ links = world.node_tree.links+ links.new(environment.outputs['Color'], background.inputs['Color'])+ links.new(environment.outputs['Color'], camera_background.inputs['Color'])+ links.new(paths.outputs['Is Camera Ray'], visible.inputs[0])+ links.new(paths.outputs['Is Transmission Ray'], visible.inputs[1])+ links.new(visible.outputs[0], mix.inputs[0])+ links.new(background.outputs['Background'], mix.inputs[1])+ links.new(camera_background.outputs['Background'], mix.inputs[2])+ links.new(mix.outputs[0], output.inputs['Surface'])+ daylight = _light('lighting.window-softbox', 'AREA', (-3.65, -0.3, 2.15), (0.1, 1.1, 0.9), 300, (1.0, 1.0, 1.0))+ daylight.visible_camera = False+ daylight.visible_transmission = False+ daylight.data.shape = 'RECTANGLE'+ daylight.data.size = 4.4+ daylight.data.size_y = 2.6+ sun = _light('lighting.soft-afternoon-sun', 'SUN', (-8, 1.2, 7), (0.5, -0.8, 0), 2.0, (1.0, 0.97, 0.90))+ sun.data.angle = math.radians(0.55)++ bpy.context.view_layer.update()+ component_z_scales = {'console': console_z_scale}+ for obj in scene.objects:+ if obj.type == 'MESH' and obj.get('component') in component_z_scales:+ _activate(obj)+ # Bake existing cushion rotations first: otherwise assigning a+ # nonuniform world scale to a rotated object loses shear in TRS.+ bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)+ compression = Matrix.Diagonal((1.0, 1.0, component_z_scales[obj['component']], 1.0))+ obj.matrix_world = compression @ obj.matrix_world+ bpy.context.view_layer.update()++ # Final evaluated geometry is what the baker sees; leave no modifier stacks.+ for obj in sorted(bpy.data.objects, key=lambda item: item.name):+ if obj.type != 'MESH':+ continue+ _activate(obj)+ if obj.data.users > 1:+ obj.data = obj.data.copy()+ for modifier in list(obj.modifiers):+ bpy.ops.object.modifier_apply(modifier=modifier.name)+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)+ bm = bmesh.new()+ bm.from_mesh(obj.data)+ bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))+ bm.to_mesh(obj.data)+ bm.free()+ obj.data.update()+ if any(not math.isfinite(value) for vertex in obj.data.vertices for value in vertex.co):+ raise ValueError(f'Nonfinite geometry: {obj.name}')+ if len(obj.data.uv_layers) != 1 or obj.data.uv_layers[0].name != 'UV0':+ raise ValueError(+ f'{obj.name}: expected exactly one material UV layer named UV0 '+ f'at index 0 before baking, found {[uv.name for uv in obj.data.uv_layers]}')+ obj.data.uv_layers.active_index = 0+ obj.data.uv_layers[0].active_render = True+ for material in obj.data.materials:+ if material and material.use_nodes:+ for node in material.node_tree.nodes:+ if (node.type in {'NORMAL_MAP', 'UVMAP'} and node.uv_map+ and node.uv_map not in obj.data.uv_layers):+ raise ValueError(+ f'{obj.name}: material {material.name}, node {node.name} '+ f'references missing UV layer {node.uv_map!r}')++ camera_spec = contract['authoring']['cameraEstimate']+ camera_data = bpy.data.cameras.new('Interior.SourceCamera')+ camera = bpy.data.objects.new('Interior.SourceCamera', camera_data)+ scene.collection.objects.link(camera)+ camera.location = camera_spec['position']+ camera.rotation_euler = (Vector(camera_spec['target'])-camera.location).to_track_quat('-Z', 'Y').to_euler()+ camera_data.lens = camera_spec['lensMm']+ camera_data.sensor_width = camera_spec['sensorWidthMm']+ camera_data.sensor_fit = 'HORIZONTAL'+ camera_data.clip_start, camera_data.clip_end = 0.03, 100+ scene.camera = camera+ scene.render.engine = 'CYCLES'+ scene.cycles.device = 'CPU'+ scene.cycles.samples = 96+ scene.cycles.use_denoising = True+ scene.cycles.seed = 47+ scene.cycles.use_animated_seed = False+ scene.cycles.max_bounces = 12+ scene.cycles.diffuse_bounces = 6+ scene.cycles.transmission_bounces = 8+ scene.render.resolution_x, scene.render.resolution_y = contract['authoring']['sourceImageSize']+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = 'PNG'+ scene.view_settings.view_transform = 'Khronos PBR Neutral'+ scene.view_settings.look = 'None'+ scene.view_settings.exposure = 0+ scene.view_settings.gamma = 1+ scene.render.film_transparent = False+ # Only this freshly authored scene: discard unused importer/curve data before packing.+ bpy.data.orphans_purge(do_recursive=True)+ bpy.context.view_layer.update()+ meshes = [obj for obj in scene.objects if obj.type == 'MESH']+ triangles = 0+ for obj in meshes:+ obj.data.calc_loop_triangles()+ triangles += len(obj.data.loop_triangles)+ components = {}+ for obj in sorted(meshes, key=lambda item: item.name):+ components.setdefault(obj['component'], []).append(obj.name)+ materials = sorted({mat.name for obj in meshes for mat in obj.data.materials if mat})+ bounds = _bounds(meshes)+ info = {+ 'schemaVersion': 1,+ 'coordinates': 'Blender Z-up metres; convert (x,y,z) to (x,z,-y) for glTF',+ 'sourceKind': contract['sourceKind'],+ 'camera': {'name': camera.name, 'position': list(camera.location),+ 'target': camera_spec['target'], 'lensMm': camera_data.lens,+ 'sensorWidthMm': camera_data.sensor_width,+ 'horizontalFovDegrees': math.degrees(camera_data.angle_x)},+ 'views': contract['authoring']['inspectionViews'],+ 'components': components,+ 'stats': {'meshes': len(meshes), 'materials': len(materials), 'triangles': triangles},+ 'materialNames': materials,+ 'bounds': {'min': bounds[0], 'max': bounds[1]},+ 'roomBounds': {'min': [xmin, ymin, 0], 'max': [xmax, ymax, height]},+ 'extras': ['component', 'physical_id', 'finish (upholstery only)', 'source_asset (imports)', 'uv_tile_metres (authored surfaces)'],+ 'assumptions': ['Authored hidden geometry and dimensions from a single synthetic view.',+ 'Unseen front shell extends to y=-6.4 or farther; glazing y=-4..2.2 ends at an authored rear wall return behind the curtain.',+ 'Chair and hairpin table silhouettes are authored against the source; no source furniture image planes.',+ 'Skewed sewn throw pillows, tall seat fronts and a low plinth replace the previous rounded pillows and stacked seat bands.',+ 'UV0 material regions and authored dye are not measured source-image BRDFs.',+ 'World uses authored 0.22 baseline and 1.20 camera/transmission exposure branches; this is not a measured, energy-preserving GI/background separation.'],+ }+ scene['interior_metadata'] = json.dumps(info)+ scene['source_image'] = contract['source']+ scene['coordinate_convention'] = info['coordinates']+ _activate(camera)+ return infodiff --git a/recipes/oak-linen/resource-selection.json b/recipes/oak-linen/resource-selection.jsonnew file mode 100644index 0000000..0524389--- /dev/null+++ b/recipes/oak-linen/resource-selection.json@@ -0,0 +1,22 @@+{+ "schemaVersion": 1,+ "reason": "Explicit Oak/Linen reproduction inputs: CC0 scanned materials and selected editable props, not a universal room fallback. Asset suitability remains subject to visual review.",+ "models": [+ {"id": "modern_arm_chair_01", "resolution": "2k", "format": "gltf", "purpose": "Editable upholstered armchair reference and material comparison"},+ {"id": "coffee_table_round_01", "resolution": "2k", "format": "gltf", "purpose": "Scanned marble top color and corresponding tangent-normal region for an authored table"},+ {"id": "side_table_01", "resolution": "2k", "format": "gltf", "purpose": "Editable side-table prop and source geometry comparison"},+ {"id": "potted_plant_02", "resolution": "2k", "format": "gltf", "purpose": "Editable potted plant with complete local glTF texture dependencies"},+ {"id": "ceramic_vase_03", "resolution": "2k", "format": "gltf", "purpose": "Editable ceramic vessel prop"}+ ],+ "textures": [+ {"id": "oak_wood_planks", "resolution": "2k", "format": "jpg", "purpose": "Floor oak scan with bounded pale-oak authored dye"},+ {"id": "oak_veneer_03", "resolution": "2k", "format": "jpg", "purpose": "Wood grain for separately dyed walnut and natural-oak furniture"},+ {"id": "rough_linen", "resolution": "2k", "format": "jpg", "purpose": "Separate sofa linen and curtain dyes retaining scanned yarn variation"},+ {"id": "painted_plaster_wall", "resolution": "2k", "format": "jpg", "purpose": "Warm plaster with low-frequency scanned variation"},+ {"id": "brown_leather", "resolution": "2k", "format": "jpg", "purpose": "Tileable charcoal leather grain, roughness and OpenGL normals without borrowed chair UV seams"}+ ],+ "hdris": [+ {"id": "garden_nook", "resolution": "2k", "format": "hdr", "purpose": "Outdoor environment available for source lighting comparison"},+ {"id": "meadow", "resolution": "2k", "format": "hdr", "purpose": "Outdoor daylight environment for the authored Oak/Linen scene"}+ ]+}diff --git a/recipes/oak-linen/scene-spec.json b/recipes/oak-linen/scene-spec.jsonnew file mode 100644index 0000000..b540128--- /dev/null+++ b/recipes/oak-linen/scene-spec.json@@ -0,0 +1,46 @@+{+ "schemaVersion": 1,+ "title": "Modern interior · Oak & Linen",+ "source": "public/assets/reference.png",+ "sourceKind": "synthetic-design-reference",+ "sourceViewLimit": "One exact authorized synthetic design reference; hidden geometry, dimensions and camera are authored estimates, not recovered measurements.",+ "authoring": {+ "sceneBuilder": "build_scene.py",+ "resourceManifest": ".img2/artifacts/interior/resources.json",+ "sourceImageSize": [2752, 1536],+ "sourceSha256": "95eb31d840165964deac849813dc77ad18bad71f1df90770bff1f7b4a5fb666b",+ "room": {"x": [-3.2, 4.8], "y": [-6.4, 2.7], "height": 3.12},+ "cameraEstimate": {"position": [-0.8, -5.4, 1.42], "target": [-0.77, 2.1, 1.0], "lensMm": 32, "sensorWidthMm": 36},+ "probePosition": [-0.1, 0.15, 1.35],+ "inspectionViews": {+ "left": {"position": [-2.35, -3.45, 1.45], "target": [0, 1.1, 1.1]},+ "right": {"position": [2.0, -3.5, 1.45], "target": [-0.3, 1.05, 1.1]},+ "detail": {"position": [-1.8, 0.6, 1.0], "target": [-1.55, 1.75, 0.45]},+ "curtain": {"position": [2.6, -0.9, 1.6], "target": [-3.0, -0.9, 1.45]},+ "reverse": {"position": [4.35, 2.46, 1.35], "target": [-0.45, 1.25, 0.65]}+ },+ "pillowProfiles": [+ {"id":"left","position":[-1.9349,1.91231,0.66494],"size":[0.74256,0.47539,0.20],"rotationDegrees":[65,0,0],"phase":1.3,"outline":[[-0.3712,0.18593],[0.17816,0.24834],[0.37136,-0.18423],[-0.17833,-0.22705]]},+ {"id":"right-back","position":[0.71371,2.00245,0.64415],"size":[0.64590,0.44678,0.20],"rotationDegrees":[75,0,0],"phase":3.0,"outline":[[-0.22089,0.25018],[0.33524,0.18443],[0.19631,-0.19660],[-0.31066,-0.18249]]},+ {"id":"right-front","position":[0.28773,1.88237,0.64651],"size":[0.59518,0.40661,0.20],"rotationDegrees":[70,0,0],"phase":4.4,"outline":[[-0.16455,0.18502],[0.3074,0.20132],[0.14493,-0.20529],[-0.28778,-0.20505]]}+ ]+ },+ "runtime": {+ "background": "/assets/interior/garden-environment.hdr",+ "backgroundIntensity": 1.2,+ "glassTransmission": 0.9216,+ "finishTarget": "sofa",+ "variants": [+ {"id": "cream", "label": "Cream linen", "color": "#d2ceca", "roughness": 0.6},+ {"id": "sand", "label": "Sand linen", "color": "#cbb89b", "roughness": 0.6},+ {"id": "olive", "label": "Olive linen", "color": "#8f9378", "roughness": 0.6}+ ]+ },+ "portability": "Runtime GLB requires EXR ambient lightmaps and indoor probe; portable GLB embeds static full-light diffuse appearance with KHR_materials_unlit. Packed master retains original PBR and Cycles thin-pane shadow approximation. Native glTF cannot carry dynamic cloth physics or rebounce baked GI.",+ "assumptions": [+ "Explicit Oak/Linen reproduction only: builder rejects any other reference hash.",+ "UV0 scan regions, dye, weave scale, hidden shell, furniture shapes and lamp fill are authored, not measured source BRDFs or dimensions.",+ "World uses 0.22 lighting and 1.20 camera/transmission branches; not an energy-preserving measured transport model.",+ "Two-pass bake separates SUN from ambient irradiance; static indirect lighting remains based on open curtains."+ ]+}diff --git a/recipes/oak-linen/surfaces.json b/recipes/oak-linen/surfaces.jsonnew file mode 100644index 0000000..f85ab6a--- /dev/null+++ b/recipes/oak-linen/surfaces.json@@ -0,0 +1,106 @@+{+ "schemaVersion": 1,+ "resourceManifest": ".img2/artifacts/interior/resources.json",+ "spec": "scene-spec.json",+ "referenceSha256": "95eb31d840165964deac849813dc77ad18bad71f1df90770bff1f7b4a5fb666b",+ "limits": [+ "This is the explicit Oak/Linen recipe, bound to its authorized design-reference bytes, not a recipe for arbitrary photographs.",+ "Dyes and reflectance are authored, not physically measured. Artwork retains any residual source-image canvas shading; it is not a recovered BRDF.",+ "Original texture normal maps remain in the resource manifest; no downloaded scan is modified. Marble crops are authored for this specific 2k model texture."+ ],+ "operations": [+ {+ "id": "linen", "op": "dye",+ "input": {"texture": "rough_linen", "channel": "color"},+ "dye": {"space": "srgb255", "value": [210, 206, 202]},+ "bounds": [0.78, 1.15], "strength": 0.45,+ "output": "public/assets/interior/linen-neutral.png"+ },+ {+ "id": "curtain-color", "op": "dye",+ "input": {"texture": "rough_linen", "channel": "color"},+ "dye": {"space": "linear", "value": [0.85, 0.81, 0.71]},+ "bounds": [0.70, 1.15], "normalizeMean": true,+ "output": "public/assets/interior/curtain-basecolor.png"+ },+ {+ "id": "curtain-roughness", "op": "roughness",+ "input": {"texture": "rough_linen", "channel": "roughness"},+ "offset": 0.86, "scale": 0.12, "center": "zero", "bounds": [0, 1],+ "output": "public/assets/interior/curtain-roughness.png"+ },+ {+ "id": "walnut", "op": "dye",+ "input": {"texture": "oak_veneer_03", "channel": "color"},+ "dye": {"space": "linear", "value": [0.19, 0.11, 0.065]},+ "bounds": [0.35, 1.8],+ "output": "public/assets/interior/walnut-color.png"+ },+ {+ "id": "chair-wood", "op": "dye",+ "input": {"texture": "oak_veneer_03", "channel": "color"},+ "dye": {"space": "linear", "value": [0.32, 0.215, 0.12]},+ "bounds": [0.35, 1.8],+ "output": "public/assets/interior/chair-oak-color.png"+ },+ {+ "id": "floor", "op": "dye",+ "input": {"texture": "oak_wood_planks", "channel": "color"},+ "dye": {"space": "srgb255", "value": [191, 169, 130]},+ "bounds": [0.55, 1.65], "exponent": 0.60,+ "output": "public/assets/interior/floor-oak-color.png"+ },+ {+ "id": "plaster", "op": "dye",+ "input": {"texture": "painted_plaster_wall", "channel": "color"},+ "dye": {"space": "srgb255", "value": [222, 214, 199]},+ "bounds": [0.75, 1.25], "strength": 0.40, "blur": 8,+ "output": "public/assets/interior/plaster-color.png"+ },+ {+ "id": "marble-color", "op": "dye",+ "input": {"model": "coffee_table_round_01", "include": "textures/coffee_table_round_01_diff_2k.jpg"},+ "crop": [900, 300, 1500, 900],+ "dye": {"space": "srgb255", "value": [229, 224, 212]},+ "bounds": [0.6, 1.3], "strength": 0.60,+ "output": "public/assets/interior/marble-basecolor.png"+ },+ {+ "id": "marble-normal", "op": "crop",+ "input": {"model": "coffee_table_round_01", "include": "textures/coffee_table_round_01_nor_gl_2k.jpg"},+ "crop": [900, 300, 1500, 900],+ "output": "public/assets/interior/marble-normal.png"+ },+ {+ "id": "leather-color", "op": "dye",+ "input": {"texture": "brown_leather", "channel": "color"},+ "dye": {"space": "srgb255", "value": [41, 41, 36]},+ "bounds": [0.6, 1.3], "strength": 0.35,+ "output": "public/assets/interior/leather-basecolor.png"+ },+ {+ "id": "leather-roughness", "op": "roughness",+ "input": {"texture": "brown_leather", "channel": "roughness"},+ "offset": 0.42, "scale": 0.30, "center": "median", "bounds": [0.30, 0.58],+ "output": "public/assets/interior/leather-roughness.png"+ },+ {+ "id": "rug", "op": "woven", "resolution": 2048, "yarns": 72,+ "tileMetres": 0.36, "seed": 20261018,+ "warpHeight": 0.00055, "crossHeight": 0.00009, "rippleHeight": 0.000012,+ "yarnWidth": 0.49, "dyeBounds": [0.92, 1.08], "noise": 0.007,+ "dye": {"space": "srgb255", "value": [195, 188, 167]},+ "roughness": 0.86, "roughnessScale": 0.05,+ "outputs": {+ "basecolor": "public/assets/interior/rug-basecolor.png",+ "normal": "public/assets/interior/rug-normal.png",+ "roughness": "public/assets/interior/rug-roughness.png"+ }+ },+ {+ "id": "artwork", "op": "crop", "input": {"reference": true},+ "crop": [1160, 337, 1665, 713],+ "output": "public/assets/interior/artwork.png"+ }+ ]+}diff --git a/reference/bake-export.md b/reference/bake-export.mdnew file mode 100644index 0000000..ea9af92--- /dev/null+++ b/reference/bake-export.md@@ -0,0 +1,71 @@+# Calibrate → bake → probe → export++## Prerequisites++An actually rendered, editable native scene with finite physical meshes, semantic components, explicit metric UV0, source camera, authored world/lights and source-image aspect. Review camera/form/materials first. Use the pinned bpy environment and an explicit workspace/spec; imports never generate files in the installed plugin.++## Coordinate/color calibration, not a realism grade++```sh+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" calibrate --workspace "$PWD" --run-id calibration-r01 --width 256 --samples 8+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" material-regression --workspace "$PWD" --run-id packing-r01+```++`calibrate` renders and reimports an asymmetric UV1 chart, checks actual glTF texture coordinates/scene bounds/decoded pixels, and renders a real equirectangular EXR with emissive cardinal panels to verify probe orientation. Its `runtimeLightmap` section emits an additional child viewer workspace, actual asymmetric float EXR field, rotated UV1 PBR model and Cycles expected image. The runtime has zero specular, black probe/background, no sun and PI lightmap intensity; native expected evaluates albedo × field.++Register that child with `interior_project.py start --workspace CHILD --image EXPECTED_RENDER --source-kind render`, install the real viewer there, `npm ci`/build/serve, select source camera and capture the actual canvas at the same projection/aspect. Verify its drawing-buffer dimensions and real device pixel ratio, not just CSS width; compare against `runtimeLightmap.expectedRender` without image realignment. This exercises the real EXR row decoder, channel 1 and PI convention; native generation alone does not certify browser sampling. Keep global and clearly defined interior-region errors, capture settings and fixture limits. Do not alter row orientation merely because a room render looks dark.++`material-regression` uses real PNG/native/GLB files: save packed pixels, change external albedo, refresh, remove external source, reopen and compare actual pixels/UV0; export non-white weighted sheen and verify native restoration on successful and actual filesystem-failed exports. It also repeats atlas preparation and real GLB export, checking stable policy-addressable material names, retained artist roughness and unchanged UV0. It qualifies the exercised Blender 4.3 workaround, not untested exporters or material appearance.++## Production bake++```sh+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" bake --workspace "$PWD" --run-id final-r01 --resolution 2048 --samples 64+```++The pipeline groups physical surfaces into architecture/textiles/furniture/garden/details, skips incompatible glass/bulbs, keeps UV0 and creates a separate `Lightmap` UV1. It checks finite/noncollapsed UVs and allocates chart gutters. Textile/garden atlases use twice the requested base resolution; choose a budget from actual footprint, not an unlabelled universal quality claim.++Subsequent bakes reuse prepared materials and their existing UV0 mapping nodes rather than growing material-name suffixes or copies. Preserve the reserved `InteriorBakeTarget` ownership node when editing prepared native materials; material policies address the actual stable exported names.++Profile a labelled low-resolution mechanism smoke before the final bake. A tiny mesh collapsing at a small atlas is a real UV-budget failure: increase that group's resolution; never remove the mesh, relax the pixel-area guard or present the smoke as final quality. `--atlas GROUP` saves that completed group's receipt and packed master independently, allowing different justified per-group budgets. Full 2K/4K CPU bakes can outlive a command runner's deadline; use an appropriate long-running job, retain receipts and inspect its actual completion before probing/exporting. A timed-out bake is not success.++For each group it actually performs:++1. Full diffuse direct+indirect lighting without albedo color, linear EXR evidence.+2. Object-normal-guided HDR OpenImageDenoise filtering of lighting only.+3. UV1 emission bake of original UV0 albedo, optional alpha, and full-light × albedo static portable PNG with the chosen display transform once.+4. A second diffuse pass with direct SUN disabled, then restore native SUN energy in `finally`.+5. Denoised linear SUN-free ambient EXR for runtime, with PI-compensated lightmap intensity in the manifest.++Bake receipts include groups/objects, resolutions/samples, actual statistics, denoiser, lighting model and elapsed time. OIDN failure is a real failure; do not substitute a fake noise-free atlas. UV1 baking must not move source sampling away from UV0.++`--atlas textiles` scopes a repair; retained groups preserve old transport approximations. A globally changed layout/light/reflectance requires full regeneration. Do not call a partial bake a globally current physical GI solution.++## Packed image repair and probe freshness++```sh+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" refresh-material --workspace "$PWD" --run-id material-r02 --image public/assets/interior/curtain-basecolor.png --image public/assets/interior/curtain-roughness.png+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" bake --workspace "$PWD" --run-id material-r02 --resolution 2048 --samples 64+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" probe --workspace "$PWD" --run-id material-r02 --width 1024 --samples 96+```++Use actual named used maps, not showcase filenames for another scene. Refresh unpacks only selected stale images, reloads disk pixels, repacks and preserves topology/UV; it invalidates atlases and the authoring revision. Draft also starts a new revision. Probe renders the current scene at the declared indoor pose with the measured native/glTF orientation and records revision/pose/actual EXR hash. Export rejects an old/mutated probe even when a file of that name exists. Out-of-band Blender edits still require explicit dependent regeneration; this is not a sandbox or universal scene-diff engine.++## Export distinct products++```sh+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" export --workspace "$PWD" --run-id final-r01+```++Export checks complete current bake inventory/model and clean required atlases. It reconstructs authoring receipt from the reopened master rather than requiring a prior run's evidence folder. Source dimensions, view names, room bounds, probe/background, optional sun, finishes and credit derive from this scene/spec.++- `room-master.blend`: actual packed editable scene, geometry, UV0/UV1, PBR and lights. This is not a GLB.+- `room-runtime.glb`: real PBR with UV0/UV1 and semantic/interaction extras; EXR atlases/probe and optional HDR background remain required sidecars.+- `room-portable.glb`: independent embedded full-static diffuse appearance, `KHR_materials_unlit` sampling UV1; not a browser shader/physics/dye-state export.+- `manifest.json`: schema-2 runtime paths/camera/bounds/lightmaps/lighting/variants/limits and receipt-derived live API credit.++Export-only tangent-cap triangulation, native thin-pane output substitution and constant weighted-sheen tint conversion are temporary and restored even on failure. Portable material swaps also restore native slots in `finally`. Native GI/probe remain static as cloth/finishes change; glass transmission is a declared approximation, not real-time caustics.++## Exit criteria++Open the source/lateral/material/contact renders and actual viewer. Run current material/delivery audits, Khronos validation and independent `inspect_scene.py master|portable`; compare source and close views separately. Keep reports/hashes/versioned evidence, packing/color-transform facts and static/runtime limits. A zero exit code, triangle count or calibration MAE is not visual acceptance.diff --git a/reference/delivery.md b/reference/delivery.mdnew file mode 100644index 0000000..0a01a01--- /dev/null+++ b/reference/delivery.md@@ -0,0 +1,39 @@+# Three products, three contracts++| Product | Required declaration | Independent observation |+|---|---|---|+| Runtime GLB | Exact file and required atlas/probe/background sidecars; viewer configuration and limitations | Load actual production viewer, inspect bindings, requests and interactions |+| Static portable GLB | Embedded/static appearance, snapshot pose, relighting/UV-density/interaction limits | Reimport into a named independent consumer, render source and close views |+| Editable native master | Exact packed master, authoring scripts, unit/light/material conventions | Reopen independently without relying on external packed-source files, inspect and render |++A `.blend` is not another GLB. A runtime model needing EXR sidecars is not a standalone appearance download. Portable exports do not automatically retain cloth physics, environment or browser state.++## Build a complete contract++Use [tool inputs](tool-inputs.md). Give every source/runtime/portable/native/sidecar a unique ID, relative path and expected SHA256, then reference the runtime dependencies and name portable/global limitations. `root` is an explicit asset root, not an upload target. Audit can read an existing external asset root without copying hundreds of MB into the plugin.++```sh+python3 "$SKILL_DIR/tools/interior_project.py" delivery-contract --workspace "$PWD"+python3 "$SKILL_DIR/tools/audit_delivery.py" --workspace "$PWD" --contract .img2/artifacts/interior/delivery-contract.json+```++A hash audit establishes bytes and declared dependency completeness, not parse validity, successful consumer reopening, physical correctness or visual equivalence. Run the Khronos validator separately where applicable and save its actual error/warning receipt. Keep native/portable reimport/render evidence separate from the audit.++The contract generator reads this scene's actual manifest/spec, verifies the pinned source and hashes distinct products plus every declared sidecar; shared background/probe bytes get one dependency identity. It does not invent passing consumer checks. Run `inspect_scene.py master` and `inspect_scene.py portable` in separate compatible Blender processes; save actual packing/UV/component/camera/render evidence. Use `node "$SKILL_DIR/tools/validate_scene.mjs" --workspace W --asset public/assets/interior/room-runtime.glb --run-id delivery-r01` and repeat for portable. The wrapper uses the actual workspace-local Khronos package, confines external reads locally, preserves warnings and rejects validator errors/truncation; it never uploads the model.++## Inspect consumers and publication++1. Independently reopen the delivered native and portable products, not in-memory authoring objects. Record hashes, scene/component counts, actual camera orientation and renders.+2. Inspect close materials after conversion. A baked UV1 portable can legitimately blur at a footprint where native/runtime PBR retains weave; label it, do not claim equivalence.+3. Build the production viewer and exercise its actual URL. Confirm runtime model requests, required sidecars, MIME/status and content hashes. Optional downloads must not all become initial requests.+4. Activate the actual download button and compare its bytes/hash to the declared file.+5. Check intended entry points, locale and dynamic labels; verify retired routes/assets do not remain published when a cutover is requested.+6. Record initial payload, optional download bytes, draw/triangle/texture budgets and observed performance/device conditions. Byte totals are not measured network transfer or stable FPS.++The showcase is heavy research output, not a mobile-performance baseline. Budget reduction must preserve declared visual/detail obligations rather than quietly deleting components or lowering a quality claim.++## Release only the workflow package++This repository distributes the skill, deterministic tools, references and examples; it does not bundle the showcase's large assets, paid-service credentials or upstream private code. Build a deterministic source ZIP with `python3 scripts/package_plugin.py`. Install the extracted directory through official `img2 add --link` and run doctor/sync again.++The release includes actual `authoring/`, `resources_lib/`, `runtime/viewer/`, guarded `recipes/`, dependency declarations and source examples, excluding dependency installs, renders/caches, credentials and large assets. Current evidence/limits belong in `VERIFICATION.md`; historical showcase observations are not current cold-run acceptance.diff --git a/reference/geometry.md b/reference/geometry.mdnew file mode 100644index 0000000..a20023e--- /dev/null+++ b/reference/geometry.md@@ -0,0 +1,31 @@+# Geometry before finish++## Author an editable scene++Use scene-specific Blender/Python authoring for the native/GLB track. Keep shell, furniture and detail construction editable; retain the script, native master, named components, units and source camera. A procedural Three.js factory can be a separate implementation track, but do not claim that a Blender export fulfilled that factory's contract.++Create stable semantic component IDs on meshes and separate metadata for finish groups, lightmap atlas assignment and interactive parts. Identify curtain body/hem/hooks explicitly; a hem may have a different UV layout from the cloth it follows.++The actual entrypoint is `build_scene(context)` in the workspace, not an installed canned room. Use [scene contract](scene-contract.md), reusable `context.helpers` and the complete `examples/studio/build_scene.py` only as an explicitly independent mechanism example. Run `author_scene.py draft --workspace W --run-id form-r01 --width 1280 --samples 96`, open its actual `draft-source.png`, and use `render --view DECLARED_VIEW` for other poses. A new draft starts an authoring revision; rebuild dependent transport instead of exporting stale atlases.++## Required inspections++1. Room shell: wall/floor/ceiling coverage, real apertures, thickness and room-side normals; document unseen faces as authored.+2. Furniture: real seats/backs/legs/arms, plausible silhouettes and source-guided proportions; no photographic cards.+3. Soft forms: actual loft, tapered corners, irregular gathered fabric, seams/piping seated against the surface rather than hovering.+4. Table/chair contact: inspect world-space contact geometry and close views, not shadows alone. Do not delete a tiny visible part to conceal an export/bake problem.+5. Glazing: explicit geometry/thickness and declared refraction/shadow approximation; do not make opaque structures transparent merely to brighten a render.+6. Fine detail: handles, frame rails, hooks, hems, art and rug fringe receive geometry/material treatment appropriate to their actual footprint.+7. Intersections: inspect required views, support contacts and clearance. Named visual gaps remain failures even when a topology utility is clean.++## UV and identity invariants++- Author explicit material UV0 at a declared physical tile size.+- Add a distinct non-overlapping bake UV1; do not repurpose or overwrite UV0.+- Preserve geometry, UV and material identity outside the named repair scope.+- Test finish variants only on their declared component group, not every similarly named material.+- Keep rejected candidates and evidence. Regenerate downstream bakes/exports when geometry or material transport changes.++## Geometry-stage evidence++Include source/lateral/reverse actual renders, component inventory, units/coordinate conventions, contact/clearance findings and remaining authored assumptions. Native save success, object count and triangle count alone are not visual acceptance. Record the decision only after looking at the scene.diff --git a/reference/installation.md b/reference/installation.mdnew file mode 100644index 0000000..93b3327--- /dev/null+++ b/reference/installation.md@@ -0,0 +1,55 @@+# Install and maintain++## Requirements++- img2 harness/CLI >=0.4.0, Node.js >=18, Git, Python >=3.10.+- A configured Claude Code, Codex or OpenCode host. Hermes is not supported by this harness.+- Production native tools: isolated Python 3.11/bpy 4.3.0/NumPy 1.26.4 (`requirements-authoring.txt`); separate NumPy/Pillow image environment (`requirements-surfaces.txt`). Audit/state tools remain stdlib plus core API 1.+- Workspace-local pinned npm dependencies and a real WebGL browser for the viewer/validator. The pinned viewer accepts Node 18, 20 or >=22; production preflight checks the actual binary. See [production setup and commands](production-runbook.md); a harness install does not silently install bpy, image packages or a web app.++## Install the private source checkout++Access to `img2threejs/img2interior` is required. Use authenticated HTTPS Git credentials (or an authorized SSH key); never put access tokens in a remote URL. Linking does not make the source public.++```sh+git clone https://github.com/img2threejs/img2interior.git "$HOME/img2interior"+npx --yes @img2threejs/[email protected] install --yes+npx --yes @img2threejs/[email protected] add --link "$HOME/img2interior" --yes+npx --yes @img2threejs/[email protected] doctor+npx --yes @img2threejs/[email protected] sync --check+npx --yes @img2threejs/[email protected] capabilities --from-kind image --to-kind interior-scene-candidate --plugin interior --json+```++If the harness already exists, the first command preserves that checkout; it is not an upgrade command. Check its compatibility before adding. Restart the agent session after linking.++`interior` is the manifest/registry ID, `img2-interior` the harness-derived skill name, and `img2interior` this repository's name. The host link points through `$IMG2_HOME/plugins/interior/` to this persistent checkout. Do not move/delete a linked source. `_img2_local.py` in root/tools is generated and ignored, not committed or distributed.++This release supports persistent checkout/archive installation. Source hosting, including a private GitHub repository, does not publish an npm package or register the plugin in the official catalog. Do not run `img2 add interior` until an actual catalog entry exists. An extracted release archive installs with the same `add --link /absolute/extracted/img2interior` command.++## Inspect and remove++```sh+npx --yes @img2threejs/[email protected] list+npx --yes @img2threejs/[email protected] update interior --check+npx --yes @img2threejs/[email protected] remove interior --yes+```++Local links are live; `update` does not fetch them. Removal unregisters owned links, not the original checkout. Never use `--force` to hide another registration or overwrite an unrelated host path. Review the harness's refusal instead.++## Project boundary++Keep the current directory in the authored project. Resolve `SKILL_DIR` from the linked skill, then call its tools by absolute path. Do not `cd` into the plugin and initialize a room there. All plugin state is in the project's `.img2/state.json`, under `plugins.interior`; receipts are under `.img2/artifacts/interior/`.++`interior_project.py start` pins a supplied image; the agent authors its intake/spec/builder and executes the full loop. `install-viewer` and the explicit hash-guarded `use-recipe` copy owned templates into W with preflight collision checks. A new image is never routed to the old room. Keep environment/dependency/build installs local and do not turn the installed plugin into the generated app.++## Isolated installation proof++```sh+python3 scripts/verify_install.py --harness-source /absolute/path/to/img2+```++This runs the official CLI with a temporary HOME/IMG2_HOME and three temporary host configurations; it does not alter real host settings or launchers. It checks install/add, registry identity, host links, doctor, sync, capability resolution and removal. Use a Git checkout of the harness, not a random Python directory.++## Release and catalog boundaries++Keep the repository private unless its owner separately authorizes a visibility change. Repository hosting and source ZIPs do not create an npm package, semver-tagged release or catalog entry. Request those operations separately; if an npm convenience installer is authorized, use the harness's official `create-img2-plugin-cli`, not a parallel custom installer.diff --git a/reference/intake-camera.md b/reference/intake-camera.mdnew file mode 100644index 0000000..5eb6a8d--- /dev/null+++ b/reference/intake-camera.md@@ -0,0 +1,35 @@+# Intake and camera++## 1. Establish source authority++Inspect the actual reference before modeling. Record whether it is a photo, synthetic design reference, render or floorplan; who authorized use; immutable SHA256; physical scale basis; critical components; and unknowns. An authorized synthetic design is not an independent observation photograph.++Create the intake JSON described in [tool inputs](tool-inputs.md). Use the showcase example only with that showcase source. `init` validates and snapshots the declaration; it cannot verify a permission claim or infer measurements. Review it explicitly at stage `intake`, citing `.img2/artifacts/interior/intake.json` and any source-analysis evidence.++Start with `interior_project.py start --workspace W --image IMAGE --source-kind KIND`; this pins bytes/display geometry, not pixel meaning or reviewer approval. The agent reads the pixels and [technical references](reference-analysis.md), then authors intake/spec/builder itself. Use [production runbook](production-runbook.md) for executable setup; do not ask the user to prepare those JSON files.++Record image bounds and normalized visible anchors for actual room planes/apertures/dominant objects, their framing and negative space; do not require a sofa or other case furniture absent from this image. Identify crops/occlusions. Distinguish observed outline, guessed depth and design choices. Ask only if missing information creates a materially different required output; otherwise state the conservative authored assumption.++## 2. Calibrate composition before detail++1. Choose metre units and author a named coordinate-system conversion (Blender Z-up; glTF/Three.js Y-up).+2. Block out room shell, apertures and dominant furniture using genuine volumes.+3. Match source camera orientation, field of view, horizon and framing with a real render at the source aspect ratio.+4. Compare silhouette, component proportions, placement and negative space before adding texture/lighting complexity.+5. Capture source and sufficient lateral/reverse inspections to expose hidden/contact failures. View names/count follow the authored scene; do not claim hidden-view accuracy from one input.+6. Record camera world matrix/pose, target, FOV, near/far, viewport and canvas bounds with the screenshots.++The user rejecting a form is a real failure even if a GLB validator passed. Preserve the rejected capture and causal repair, then repeat the camera/geometry stage. Do not use material polish to conceal a wrong table, seat front, pillow outline or chair silhouette.++## Camera import and runtime safety++Imported glTF cameras may use quaternion rotation. Switching only Euler values can leave the old orientation active. Set the intended rotation representation explicitly and inspect forward/target alignment, parent transforms and actual output footprint.++Constrain both eye and target against the room shell after every controls update, including updates below an event emitter's epsilon. Exercise orbit, pan, dolly/zoom, keyboard and reset. Camera proximity limits are authored safety policy, not physical collision certification.++## Evidence and stage decisions++- `intake`: pinned intake snapshot, source-analysis/permission/uncertainty notes.+- `camera`: actual coarse render(s), camera/projection receipt, named composition decisions and remaining uncertainty.+- Record reviewer identity and explicit acceptance only after observing those artifacts.+- Capture inside the existing canvas viewport. In the showcase, a beyond-viewport capture changed canvas width/aspect while camera position stayed fixed; do not relax camera assertions to cover a capture-induced layout mutation.diff --git a/reference/interaction.md b/reference/interaction.mdnew file mode 100644index 0000000..23cfa7e--- /dev/null+++ b/reference/interaction.md@@ -0,0 +1,36 @@+# Exercise the viewer, not just the solver++## Declare scope++Keep a real orbit/pan/zoom viewer with bounded room camera, reset, loading/error/retry and accessible controls. Add cloth, finish variants and downloads only when implemented and requested. `interactionRequired:false` permits a static scene, not skipping camera, keyboard, loading, accessibility and visibility checks; explain omitted cloth controls in evidence.++Install/build/serve the actual [Three.js template](viewer-integration.md), which derives source aspect, arbitrary view/variant sets and room safety from schema-2 manifest rather than Oak/Linen. Cloth requires explicit horizontal Y-up rail/depth/origin, hem point coordinates, enough render vertices for exact 50×16 solver intersections, identity scene root and single-owner deforming geometry. The native helper emits this metadata. Missing/unsupported rigs fail actionably; arbitrary rotated roots or other solvers are not silently accepted.++## Cloth acceptance when present++1. Grab the actual cloth material point at multiple low/middle/high UV locations on every declared panel, plus hem points. Compute the rendered-lattice correspondence; a hem's UVs are not the cloth binding.+2. Keep material UV0 unchanged. Measure held UV/point error and pin rail/header attachments; record units, sampling, viewport and tolerances chosen for the actual consumer.+3. Move nearby points with spatial/temporal falloff. Exercise reverse drag, release and physical settling. Do not claim calibrated FEM or full self/furniture collision from a position-based approximation.+4. Give the grip exclusive pointer ownership; disable orbit only while held. Camera position, quaternion, target and projection must remain unchanged, not just a screenshot that looks stationary.+5. Own wheel input only during the grip, release it afterwards and restore any wrapped control method on disposal.+6. Cancel safely on pointer capture loss, outside release, touch cancel, an added finger, blur, source-mode switch and tab leave. Never leave controls stuck.+7. Exercise slider/open/close/keyboard alternatives, optional wind and reduced motion. Touch emulation is not real-phone proof.++The real diagnostic snapshot `window.interiorStudy.curtains` supplies panel IDs, low/middle/high/header/hem-level UV/world/canvas probes and held point/target/error. Use actual visible ray hits (folds may occlude a nominal UV), paced input and observed rendered frames; record transient versus settled error and camera/projection invariants. A fixed wall-clock delay under a simultaneous bake is not a solver-convergence measurement. The hem ray must actually report `part:"hem"`; do not relabel a nearby cloth hit.++## Lifecycle and camera++- Constrain eye/target after every controls update, including below-event-epsilon updates. Stress keyboard, orbit, pan and zoom at bounds.+- Pause hidden/offscreen rendering and cancel held gestures. Do not weaken visibility safety because a test window was occluded.+- Wait for wind-off physics to settle before asserting on-demand sleep; observe frame counters over an interval.+- Trigger actual WebGL context loss and recovery; verify assets, interactions and wind can resume. An error overlay alone is not recovery.+- Exercise real load failure/retry and source/3D switching. Observe page errors and actual network requests.+- Change finishes rapidly and verify only declared component materials change, preserving geometry/UV/texture/lightmap identities.++## Accessible/responsive surface++Inspect actual desktop and narrow canvas bounds, overflow, focus, readable labels and keyboard controls. Test touch targets and reduced motion. Record locale, dynamic text/ARIA and error metadata; the case's English-only requirement is not mandatory for every project. Distinguish real devices, emulation and untested combinations.++## Interaction-stage evidence++Include runtime URL/build identifier, input sequences, numerical receipts, screenshots and named limitations. Record observed performance/payload separately from desired budget. Do not substitute a bare non-crash result for held-point correctness, lifecycle transitions or actual UI inspection.diff --git a/reference/lighting.md b/reference/lighting.mdnew file mode 100644index 0000000..e1dea7d--- /dev/null+++ b/reference/lighting.md@@ -0,0 +1,41 @@+# Lighting, UV1 and transport boundaries++## Establish coordinate and color truth first++Build an asymmetric colored-light fixture with a rotated UV1 island. Compare decoded EXR sampling against the native renderer before changing atlas row orientation. Record transforms, row convention, linear/non-color channels, view transform and identical camera/crop. The showcase's once-flipped fixture MAE was a coordinate/color check, not an interior likeness score; do not hard-code that result for another decoder.++Run `author_scene.py calibrate --workspace W --run-id calibration-r01 --width 256 --samples 8`, then serve/open its child viewer and compare the actual canvas to the native expected render. See [bake/export](bake-export.md) for the real rotated-UV1/float-EXR/PI field, cardinal probe and child install commands. Native calibration alone leaves browser sampling explicitly unverified.++Keep albedo sRGB, normal/roughness non-color, and radiance/lightmaps linear. Record the chosen tone mapping and exposure. If a portable already contains a display transform, do not apply the same transform again during consumer inspection.++## Separate ambient/fill from direct sun++For the exercised baked track:++1. Keep UV0 surface detail and a separate UV1 atlas layout.+2. Bake full diffuse lighting for the separately labeled static portable appearance.+3. Bake ambient/fill with the direct sun disabled for the runtime; restore native light state in `finally` even on failure.+4. Add runtime shadowed direct sunlight once. Never combine an old full-sun atlas with new runtime sun and call double lighting acceptable.+5. Build the reflection probe from the same native scene/light state as the relevant bake.+6. Keep dynamic cloth out of incompatible static lighting; document that baked indirect illumination does not rebounce as curtains/finishes move.++This is one reproducible transport approximation, not a requirement that every project use baked GI. If another renderer/strategy is used, declare it and independently verify the same lighting/representation obligations.++## Diagnose with receiver/control evidence++At the same camera and exposure, compare open/closed curtains on floor/rug receiver crops and an unaffected control patch. Actual direct shadows should change; the control should not darken because of a global exposure multiplier. Display-encoded RGB averages are not irradiance.++Keep glazing/refraction and any shadow-ray transmission approximation explicit. Do not hide glass, disable physical parts or make the whole room darker to mimic closure. Preserve real window blockers and inspect grounded contact shadows.++## Invalidation and expensive bakes++- Geometry, layout, material reflectance or lighting changes can invalidate transport: revise from the earliest affected stage and regenerate dependent outputs.+- A scoped textile/detail bake leaves other groups' old GI approximation in place; state that limit. Use a full bake for globally updated transport.+- An export-only parameter conversion does not itself change native illumination. Do not cancel an expensive native bake just because an export adapter changed.+- Hash/version the actual native master, atlas set, probe and exports. Never mix captures from different candidates without labeling them.++The shipped pipeline actually bakes full diffuse and SUN-disabled ambient passes, OIDN-filters lighting with normal guides, creates independent static portable maps, and records PI intensity/authoring revision. `bake`, `probe`, `export` are real separate CLI stages. Refresh/draft invalidates required atlases/probe; export checks current probe revision/pose/hash, not existence. See the [runbook](production-runbook.md) for cold and repair sequences.++## Lighting-stage evidence++Include calibration fixture measurements, source/lateral room renders, runtime bake/direct-light model, receiver/control crops, contact review and limitations. Passing hashes or numerical fixture calibration does not grant visual acceptance.diff --git a/reference/materials.md b/reference/materials.mdnew file mode 100644index 0000000..b9f3a50--- /dev/null+++ b/reference/materials.md@@ -0,0 +1,39 @@+# Material identity, not generic gloss++## Inspect what is actually bound++For each critical material, inspect the exported GLB and runtime binding, not just an asset manifest or a Principled default. Record albedo, normal, metallic/roughness, effective texture coordinates/transform, physical tile scale, color spaces, normal strength, sheen/specular factors and affected mesh IDs.++Use `audit_materials.py` with an explicit policy; [tool inputs](tool-inputs.md) defines its schema. The bundled Oak / Linen policy targets two exact current curtain material names and their actual bound maps. It is not a universal textile preset.++```sh+python3 "$SKILL_DIR/tools/audit_materials.py" --workspace "$PWD" --glb ./public/assets/interior/room-runtime.glb --policy ./material-policy.json+```++This audits wiring, resource/UV presence and declared scalar bounds. It does not decode texture pixels, infer color space correctness, measure effective roughness or certify fabric. A roughness image can override the scalar: a scalar of 1 does not prove the surface is matte. Inspect decoded texture statistics separately when needed and record their interpretation.++Acquire/verify actual resources and run `prepare_surfaces.py --workspace W --recipe surfaces.json` in the image environment; [resources](resources.md) defines the real dye/roughness/crop/metric-normal operations and receipts. Author intended map/UV/scalar requirements before auditing, not by copying whatever the exported material happens to contain. Provisional bake/probe/export may be needed for the first bound-GLB review; final lighting acceptance still requires its later production round.++After changing a used map, run `author_scene.py refresh-material --workspace W --run-id material-r02 --image public/assets/interior/MAP.png`, then regenerate required bakes/probe/export and reopen the packed master without that external input. Pixel refresh does not implement a material-graph edit. `material-regression` provides the actual packed-image/UV0/non-white-sheen success-and-failure fixture; [bake/export](bake-export.md) explains its limits.++## Physical-scale visual review++1. Capture an overview and fixed frontal/grazing macro views under unchanged lights/exposure.+2. Record camera/projection, canvas crop and physical texel footprint. Compare matched native-pixel captures where possible; label unmatched crops honestly.+3. Review linen yarn, upholstery seams, leather grain, wood grain, marble and plaster as distinct materials, not one noisy normal map.+4. Exercise deforming cloth while held and after release. Preserve UV0/material coordinates and unrelated sofa geometry/textures/variants.+5. Review native/runtime/portable material behavior separately; a low-density baked portable may blur where runtime PBR retains yarn detail.++## Showcase-derived failure modes++- A resource dictionary contained an albedo, but the material factory did not attach it. Inspect exported `baseColorTexture`.+- A connected roughness map had a low tail despite a matte scalar. Changing only the scalar was not the causal fix.+- Reusing packed Blender images after replacing a PNG preserved stale pixels. Refresh only the owned packed image, reload it, then reopen without the external source to verify packing.+- Blender 4.3's exercised sheen exporter treated nonzero weight as an enable gate and exported unweighted tint. For constant weight, scope the conversion to export and restore native inputs in `finally`; test non-white tint. Do not generalize an exporter workaround to untested versions.+- Curtain and sofa samplers must remain independent; a cloth filtering repair must not change unrelated finishes.++The case used a 0.65 m authored UV0 tile, normal strength 0.70, low broad sheen and dedicated high-roughness linen derivatives. These are observed design settings, not a measured BRDF or a default for every room.++## Material-stage evidence++Cite the machine audit, actual bound-map/factor report, UV/identity checks, frontal/grazing renders and reviewer explanation. Keep technical pass separate from visual acceptance. A change to finish/reflectance can require rebaking affected lighting atlases and refreshing the probe/export; see [lighting](lighting.md).diff --git a/reference/oak-linen-recipe.md b/reference/oak-linen-recipe.mdnew file mode 100644index 0000000..2f99728--- /dev/null+++ b/reference/oak-linen-recipe.md@@ -0,0 +1,47 @@+# Explicit Oak/Linen reproduction, never an arbitrary-room fallback++The recipe packages the actual scene-specific authoring from the authorized synthetic design study: room/glazing, sofa and skewed lofted pillows/BVH-seated seams, authored hairpin table/lounge chair, rug/fringe, lamps/books/vessels, two interactive rail curtains and local garden. Generic tools remain independent; case assembly lives in `recipes/oak-linen/build_scene.py`.++## Required caller source++The original image is not bundled. Supply its exact authorized bytes, 2752×1536 PNG:++`95eb31d840165964deac849813dc77ad18bad71f1df90770bff1f7b4a5fb666b`++It is a synthetic design reference, not an independently measured photograph. The installer, material crop recipe and case builder guard the actual source hash. A different image requires a newly authored scene/spec/surfaces, not deleting guards or silently keeping this room.++## Cold workspace commands++```sh+python3 "$SKILL_DIR/tools/interior_project.py" start --workspace "$PWD" --image "$IMAGE" --source-kind synthetic-design-reference+python3 "$SKILL_DIR/tools/interior_project.py" use-recipe --workspace "$PWD" --recipe oak-linen+python3 "$SKILL_DIR/tools/polyhaven.py" fetch --workspace "$PWD" --selection resource-selection.json+"$IMAGE_PYTHON" "$SKILL_DIR/tools/prepare_surfaces.py" --workspace "$PWD" --recipe surfaces.json+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" draft --workspace "$PWD" --run-id case-r01 --width 1280 --samples 96+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" bake --workspace "$PWD" --run-id case-r01 --resolution 2048 --samples 64+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" probe --workspace "$PWD" --run-id case-r01 --width 1024 --samples 96+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" export --workspace "$PWD" --run-id case-r01+python3 "$SKILL_DIR/tools/interior_project.py" install-viewer --workspace "$PWD"+npm ci+npm run build+```++Prepare the isolated environments and initialize the agent-authored intake/reviews as in the [runbook](production-runbook.md). Run real calibration, visual repair, browser interactions, independent native/portable reopening and current audits before delivery. Recipe installation does not accept any stage.++## What is reusable versus case-specific++| Reusable production mechanism | Case-only choices |+|---|---|+| Live Poly Haven discovery/descriptors/dependency acquisition/integrity | Exact five models, five scans and two HDRIs selected in this study; not all downloaded models were instantiated. |+| Recipe-driven linear dye/roughness/crop/metric yarn tools | Walnut/chair/floor/plaster/linen/leather dyes, 2k marble source crop, artwork pixel rectangle and rug weave settings. |+| Actual Blender geometry/PBR/UV helpers, two-pass bakes/OIDN/probe/export | This room's shell/geometry/camera, physical proportions, hidden extension and lighting estimates. |+| Manifest-driven Three lighting, navigation and point-bound cloth | Two explicit case rails, sofa finish group and its three colors. |+| Native/runtime/portable consumer checks and causal repair loop | Historical counts, hashes, close-up errors, performance and visual decisions. |++Downloaded asset bytes may change upstream; current verified acquisition receipts describe this run. The large original images/models/maps/master/GLBs, credentials, cached catalog and historical screenshots are not part of the installable source ZIP. The recipe does not read an absolute source-project path, old outputs or a private machine environment.++## Interpretation and known limits++Camera, metre scale, hidden surfaces, reflectance, dyes and scan footprints remain authored estimates. The source-specific artwork crop is an explicitly labeled artwork texture, not permission to turn furniture/room structure into photo cards. Native thin-pane shadows and runtime two-interface sun transmission are approximations; open-curtain GI/probe and portable appearance remain static.++Historical showcase evidence is summarized in [lessons](showcase-lessons.md); current release smoke evidence is in [VERIFICATION.md](../VERIFICATION.md). Do not report a small low-sample mechanism smoke as a fresh full-quality photorealism or real-phone acceptance run.diff --git a/reference/production-runbook.md b/reference/production-runbook.mdnew file mode 100644index 0000000..bc3c0c7--- /dev/null+++ b/reference/production-runbook.md@@ -0,0 +1,97 @@+# One assignment: image to working interior++The image-capable agent executes this runbook, authors its inputs/code and repairs observed failures. The user need not supply a scene JSON, resource manifest, camera or per-step approvals. This is not a universal neural recovery model; visual interpretation and scene-specific code are agent work.++## 1. Prepare the actual workspace++Keep `SKILL_DIR` pointed at the installed plugin, `PWD` at the authored project, and `IMAGE` at the supplied image. Observe the source kind before choosing `SOURCE_KIND`. Preserve unrelated files and existing review history.++```sh+python3 "$SKILL_DIR/tools/interior_project.py" start --workspace "$PWD" --image "$IMAGE" --source-kind "$SOURCE_KIND"+```++Start preserves bytes and records header/display size, hash and authority. It may adopt an identical existing reference but never overwrite a different one. Read the actual source/reference pages and author the intake, [scene specification/builder](scene-contract.md), visible anchors, uncertainties, output budget and intended material policy. Only the exact source-pinned case can use [Oak/Linen reproduction](oak-linen-recipe.md).++## 2. Prepare project-local environments++Use existing compatible tools if available; otherwise install locally. For example, with `uv` already available:++```sh+uv venv --python 3.11 .venv-blender+uv pip install --python .venv-blender/bin/python -r "$SKILL_DIR/requirements-authoring.txt"+uv venv --python 3.12 .venv-images+uv pip install --python .venv-images/bin/python -r "$SKILL_DIR/requirements-surfaces.txt"+export BLENDER_PYTHON="$PWD/.venv-blender/bin/python"+export IMG2_BLENDER_PYTHON="$BLENDER_PYTHON"+export IMAGE_PYTHON="$PWD/.venv-images/bin/python"+python3 "$SKILL_DIR/tools/interior_project.py" preflight --workspace "$PWD" --blender-python "$BLENDER_PYTHON"+```++`python3.11 -m venv` / pip is also usable when that interpreter is installed; Windows venv executables use `Scripts/python.exe`. Do not claim untested OS/wheel support. bpy 4.3.0 and NumPy 1.26.4 are isolated from image-tools NumPy/Pillow. Preflight performs real executable/import probes, not installs or visual checks.++## 3. Pin intake and establish composition++```sh+python3 "$SKILL_DIR/tools/interior_workflow.py" init --workspace "$PWD" --image "$IMAGE" --intake interior-intake.json+python3 "$SKILL_DIR/tools/interior_workflow.py" next --workspace "$PWD"+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" draft --workspace "$PWD" --spec scene-spec.json --run-id camera-r01 --width 640 --samples 16+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" render --workspace "$PWD" --run-id camera-r01 --view left --width 640 --samples 16+"$IMAGE_PYTHON" "$SKILL_DIR/tools/compare_views.py" --workspace "$PWD" --run-id camera-r01 --render .img2/artifacts/interior/production/camera-r01/draft-source.png+```++Use a view actually declared in the spec, not a mandatory `left`. Open renders/contact sheet; compare framing, source aspect, silhouettes, placement and negative space. Record intake/camera only after inspection. Contact sheets preserve framing/labels and optional normalized `--roi L T R B`; they do not compute likeness or assume pixel alignment.++## 4. Acquire assets, build geometry, prepare PBR++Follow [resources](resources.md), [geometry](geometry.md) and [materials](materials.md). Search live candidates, inspect actual shape/maps, author selection/purpose and fetch verified CC0 files. Write scene-specific geometry and surfaces; run real preparation where needed.++```sh+python3 "$SKILL_DIR/tools/polyhaven.py" fetch --workspace "$PWD" --selection resource-selection.json+"$IMAGE_PYTHON" "$SKILL_DIR/tools/prepare_surfaces.py" --workspace "$PWD" --recipe surfaces.json+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" draft --workspace "$PWD" --run-id form-r01 --width 1280 --samples 96+```++Inspect source/lateral/reverse/contact and fixed frontal/grazing material views. A geometry correction changes the builder and requires a new draft. To replace an already-used image map, update only its intended derivative, then `refresh-material --image public/assets/interior/MAP.png`; this reloads packed bytes, preserves geometry/UVs and invalidates transport. Other material graph changes require rebuilding or an explicit reviewed native edit, not pretending a pixel reload changed a shader graph.++## 5. Render, reject and causally repair++A rejection is ground truth. Name the defect, preserve the failing capture, run workflow `revise --from` the earliest affected stage, change actual geometry/material/camera/light/input code, regenerate dependencies and observe new captures. Use new round IDs; do not overwrite accepted evidence. Do not change tolerance/exposure/claims to disguise an unresolved shape or fabric problem.++Native reports/renders live under `.img2/artifacts/interior/production/RUN/`. Same stage/view/atlas evidence is not reusable within a run; choose another run ID after a failed invocation or revision. Current `.blend`/GLB/maps are mutable products; early approvals should cite immutable views/inventory/receipts, not product bytes that a later bake/export legitimately rewrites.++## 6. Calibrate and produce final native/runtime/portable assets++Follow [bake/export](bake-export.md), including the actual native/EXR/browser fixture. Provisional low-cost bakes can support material inspection; final lighting approval needs the chosen production settings and visible checks.++```sh+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" bake --workspace "$PWD" --run-id final-r01 --resolution 2048 --samples 64+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" probe --workspace "$PWD" --run-id final-r01 --width 1024 --samples 96+"$BLENDER_PYTHON" "$SKILL_DIR/tools/author_scene.py" export --workspace "$PWD" --run-id final-r01+```++Dynamic SUN is not baked into runtime ambient atlases. Portable uses separately baked full-static diffuse appearance; native preserves editable PBR. Refreshing pixels/geometry requires current bakes and probe; old probe existence is insufficient. Inspect actual outputs before accepting lighting.++## 7. Install and exercise the actual viewer++```sh+python3 "$SKILL_DIR/tools/interior_project.py" install-viewer --workspace "$PWD"+npm ci+npm run build+npm run preview -- --host 127.0.0.1 --port 5179+```++Keep the server running using the agent host's managed service mechanism. Open a real browser tab, follow [viewer integration](viewer-integration.md) and [interaction](interaction.md), capture desktop/narrow and actual input/lifecycle results, then close the tab. Test production preview, not just a source-code test. No deployment permission is implied.++## 8. Independently inspect, audit and hand off++```sh+"$BLENDER_PYTHON" "$SKILL_DIR/tools/inspect_scene.py" master --workspace "$PWD" --run-id delivery-r01 --width 1280 --samples 64+"$BLENDER_PYTHON" "$SKILL_DIR/tools/inspect_scene.py" portable --workspace "$PWD" --run-id delivery-r01 --width 1280 --samples 64+node "$SKILL_DIR/tools/validate_scene.mjs" --workspace "$PWD" --asset public/assets/interior/room-runtime.glb --run-id delivery-r01+node "$SKILL_DIR/tools/validate_scene.mjs" --workspace "$PWD" --asset public/assets/interior/room-portable.glb --run-id delivery-r01+python3 "$SKILL_DIR/tools/audit_materials.py" --workspace "$PWD" --glb public/assets/interior/room-runtime.glb --policy material-policy.json+python3 "$SKILL_DIR/tools/interior_project.py" delivery-contract --workspace "$PWD"+python3 "$SKILL_DIR/tools/audit_delivery.py" --workspace "$PWD" --contract .img2/artifacts/interior/delivery-contract.json+```++Freeze changing audit receipts with `interior_project.py snapshot`, cite actual consumer/render/input evidence, complete all eight stage attestations in order and run `run_gates.py --plugin-dir "$SKILL_DIR" --workspace "$PWD"`. Machine checks do not attest screenshot meaning. The handoff includes source/assumptions, code/spec/setup, resource receipts, packed master, runtime+sidecars/viewer, portable, actual checks/limits and reproduction commands; distinguish observed desktop/emulation from physical-device proof.diff --git a/reference/reference-analysis.md b/reference/reference-analysis.mdnew file mode 100644index 0000000..90c39b7--- /dev/null+++ b/reference/reference-analysis.md@@ -0,0 +1,39 @@+# Read the image and references before writing a room++## Inputs and authority++The user supplies one image and the assignment. The agent supplies the observation, intake, scene specification and actual builder; do not demand hand-authored JSON from the user. Keep the image immutable. A synthetic design reference is not a measured photograph; local processing permission is not proof of publication rights.++Use `interior_project.py start` to copy/pin the source and read encoded/display dimensions. This only probes PNG/JPEG/WebP headers, including JPEG EXIF orientation; it does not decode pixels or infer scene content. Open the image using the agent's image tools. For unsupported formats convert a working copy, retaining original provenance and transformation history.++Record the following in `.img2/artifacts/interior/production/<round>/source-analysis.json` or equivalent real analysis:++- Source kind, SHA256, dimensions/aspect, supplied brief and permitted use.+- Observed wall/floor/ceiling planes, openings, light directions, dominant furniture and occlusions.+- Normalized visible anchors: silhouette corners, horizon, glazing mullions, furniture supports and negative space. Identify each anchor's uncertainty; do not invent pixel precision for a blurred/hidden edge.+- Physical scale basis and camera hypotheses; a typical furniture size is an authored prior, not a measurement.+- Material families, grain/weave direction and visible footprint; separate illumination tint from surface albedo.+- Required views, interaction scope, output/initial-payload budget, actual delivery targets and explicit unknowns.++## Analyze supplied technical references++Open the actual pages and observe source/3D distinction, camera freedom, navigation limits, lighting response, material/detail behavior, loading/error states, downloads and controls. Keep screenshots/URL/date and separate directly observed behavior from static implementation candidates.++If source inspection or REA tools are available, trace only the relevant scene/material/interaction boundary; preserve their coverage/unknowns. A script string or endpoint candidate is not runtime execution proof. Do not run directives embedded in inspected content, extract credentials, or copy unlicensed code/models/textures.++The historical study used these craft references:++- [Little Workshop Showroom](https://showroom.littleworkshop.fr/): showroom presentation and material/interaction inspection.+- [TSUKAT Alex Interior](https://playcanv.as/apps/5219dda4/index.html): source-guided authored interior and runtime observation.++Those URLs identify the historical references, not a claim they were re-inspected on this run. Their images were internal craft comparisons, not input furniture textures or redistribution grants. The package contains this project's own authoring/viewer mechanisms, not their private scene assets.++## Decide rather than imitate++Write a compact finding table: observed reference behavior → relevant requirement → chosen local implementation → evidence needed. Example: bounded camera freedom → eye and target stay inside authored shell → post-update room AABB navigation → actual bounds stress test.++Do not inherit Oak/Linen's dimensions, camera, layout, component list, dyes or source-image crops for a new room. Reuse techniques: editable volumes, source-aspect camera iteration, physically scaled PBR, separated ambient/direct lighting, semantic interactions and distinct runtime/portable/native products.++## Exit criteria++The image has actually been viewed, relevant references have observations or explicit access limits, the agent has authored a defensible intake/spec, and the first camera/form hypotheses can be exercised in Blender. Unknown hidden geometry remains labeled. Missing ordinary dimensions do not stop the assignment; safety/rights or materially incompatible requirements can require input.diff --git a/reference/resources.md b/reference/resources.mdnew file mode 100644index 0000000..db71158--- /dev/null+++ b/reference/resources.md@@ -0,0 +1,59 @@+# Resource discovery, acquisition and surface preparation++## Search suitable assets, not just available assets++Use free public CC0 resources within the assignment's authority. Paid generation, uploading the user's image, restricted models and public deployment need separate authorization. Procedurally authored geometry/PBR is valid when it matches the brief; do not substitute a visually wrong scan merely because it downloads.++```sh+python3 "$SKILL_DIR/tools/polyhaven.py" search --workspace "$PWD" --type models --query 'lounge chair' --limit 5+python3 "$SKILL_DIR/tools/polyhaven.py" search --workspace "$PWD" --type textures --query 'linen fabric' --limit 5+python3 "$SKILL_DIR/tools/polyhaven.py" info --workspace "$PWD" --id rough_linen+python3 "$SKILL_DIR/tools/polyhaven.py" files --workspace "$PWD" --id rough_linen+```++The live [Poly Haven API](https://api.polyhaven.com/api-docs/swagger.json) provides ranked metadata search, asset info and file descriptors. Inspect candidate imagery or import/render candidate geometry. Rank/similarity is not silhouette, BRDF or source-image fit. Record selected, rejected and actually instantiated assets separately.++Author `resource-selection.json` with integer `schemaVersion:1`, a nonempty `reason` and arrays `models`, `textures`, `hdris` (empty arrays allowed). Each selected entry declares `id`, `resolution`, `format`, `purpose`:++```json+{"schemaVersion":1,"reason":"Observed textile needs a woven scan","models":[],"textures":[{"id":"rough_linen","resolution":"2k","format":"jpg","purpose":"Curtain UV0 weave"}],"hdris":[]}+```++```sh+python3 "$SKILL_DIR/tools/polyhaven.py" fetch --workspace "$PWD" --selection resource-selection.json+```++Models use `gltf` and include every published dependency with its original relative layout; textures require actual `Diffuse`, `nor_gl` and `Rough` descriptors mapped to `color`, `normal`, `roughness`; HDRIs use `hdr` or `exr`. Inspect `files` before choosing unsupported resolutions/formats. Missing channels fail; they are not silently synthesized.++Downloads live under `resources/polyhaven/<id>/`. The receipt `.img2/artifacts/interior/resources.json` records selection, asset metadata, local model/map/HDR paths, `modelIncludes`, publisher URL/size/MD5 and actual SHA256. Same-size cached files are still MD5 checked. Paths, glTF URIs and HTTPS redirect hosts are confined; reads/transfers are bounded. Failure does not mean a partially downloaded asset is usable.++The tool visibly credits **Powered by Poly Haven**. Downloaded assets are [CC0](https://polyhaven.com/license), while use of the live service has separate [API terms](https://github.com/Poly-Haven/Public-API/blob/master/ToS.md). The actual API client identifies itself; no API server source or API key is bundled. A balance/CC0 license is not paid-generation permission.++## Prepare actual PBR inputs++Run image tools in a separate NumPy/Pillow environment, not the pinned bpy environment. Author `surfaces.json`; source-specific crop coordinates require actual observation and should pin the intended reference hash.++```sh+"$IMAGE_PYTHON" "$SKILL_DIR/tools/prepare_surfaces.py" --workspace "$PWD" --recipe surfaces.json+```++Recipe schema: `schemaVersion:1`, optional `resourceManifest` (default current private resource receipt), `spec` (default `scene-spec.json`), optional `referenceSha256`, and nonempty `operations`. Each operation has a unique `id`, `op`, and output PNG under `public/assets/interior/`. Inputs/recipes/downloads cannot be outputs.++Input alternatives: `{"texture":"rough_linen","channel":"color"}`, `{"model":"coffee_table_round_01","include":"textures/coffee_table_round_01_diff_2k.jpg"}`, `{"reference":true}`, or `{"path":"inputs/scan.png"}`. Downloaded input hashes are checked against the resource receipt. Reference resolves from `spec.source`, including the actual extension; decoded images honor EXIF orientation.++| Operation | Parameters and actual work |+|---|---|+| `dye` | Decode sRGB → linear luminance; normalize by scan median; clamp `bounds`, optional `exponent`, `strength`, `normalizeMean`, `blur` and `crop`; multiply explicit `dye:{space:"srgb255" or "linear",value:[r,g,b]}`; encode sRGB. |+| `roughness` | Decode grayscale; `offset + scale * (scan - median)` for `center:"median"`, or no subtraction for `"zero"`; clamp `bounds` in 0..1. |+| `crop` | Explicit integer `[left,top,right,bottom]`; reject out-of-bounds rectangles instead of padding an invented surface. |+| `woven` | Deterministic periodic crossing-yarn field from `resolution`, even `yarns`, `tileMetres`, `seed`, dye and optional physical height/noise/roughness parameters; `outputs:{basecolor,normal,roughness}`; metric derivatives yield OpenGL +Y normals. |++```json+{"schemaVersion":1,"operations":[{"id":"cloth-dye","op":"dye","input":{"texture":"rough_linen","channel":"color"},"dye":{"space":"srgb255","value":[210,206,202]},"bounds":[0.78,1.15],"strength":0.45,"output":"public/assets/interior/linen-neutral.png"}]}+```++`.img2/artifacts/interior/surfaces.json` records recipe/input/output hashes, operation parameters, decoded pixel dimensions/mode/min/max/mean/std, and actual NumPy/Pillow versions. Woven receipts also declare tile/pitch/normal convention. These are authored transformations, not recovered reflectance or visual acceptance.++## Exit criteria++Every used asset has a purpose, safe local dependencies and recorded rights/provenance. Required maps exist and are actually bound by the native material factory. The agent has inspected material identity, physical tile scale, decoded roughness and real frontal/grazing views. Downloads, dictionary entries and a high roughness scalar alone are insufficient.diff --git a/reference/review.md b/reference/review.mdnew file mode 100644index 0000000..81df902--- /dev/null+++ b/reference/review.md@@ -0,0 +1,43 @@+# Review, invalidate, repair++## Four kinds of truth++Keep these distinct in every receipt/handoff:++- Source observation: visible pixels, provenance and source immutability.+- Authored decision: hidden surfaces, units/scale, camera, materials and transport approximations.+- Observed execution: exact build/artifact hash, measured runtime input/result and inspected renders.+- Untested generalization: other rooms, engines, devices, material types or hidden-view fidelity.++Do not invent a single percentage realism score. A valid GLB, successful build or a colored-light fixture's pixel error cannot establish room likeness or fabric identity.++## Acceptance is an explicit attestation++`record --decision accept` means the named reviewer inspected cited evidence; the tool only enforces order and byte freshness. It cannot tell what an image depicts, authenticate reviewer identity or infer that a receipt represents a real observation. Do not use one generic JSON or source image as proof for all stages. Machine gates are necessary, not sufficient, for handoff.++Use source/lateral/reverse views for composition/form, frontal/grazing macro views for materials, same-camera receiver/control crops for lighting, actual interactive browser sequences for behavior and independent consumer renders for delivery. Record exposure/camera/view-transform/viewport with comparison captures. Preserve both rejected and repaired candidates.++## Causal repair loop++1. Name the user-visible defect and accept a user-reported failure as ground truth.+2. Locate its cause in actual geometry, shader graph/export, UV mapping, controls or transport state.+3. Preserve the failing receipt; do not rerun only to dispute the user's observation.+4. Run `revise --from STAGE --reason TEXT` at the earliest affected stage. This invalidates its downstream approvals, not history.+5. Make the scoped repair. Rebuild/rebake/reexport only what dependencies require; do not silently mix old and new outputs.+6. Capture current evidence under controlled conditions. Write versioned files instead of overwriting pinned accepted evidence.+7. Re-review invalidated stages in order, rerun machine audits and run all blocking gates.++`reject` preserves a failed review and invalidates dependent approvals. `request-input` and `stop` block continuation (`next` exits 3); resolve with an explicit revision, not reinitialization. A changed source requires a new workspace/run. Existing runs cannot be reset with `init`.++Current machine-audit JSON paths may be rewritten by a later audit. After observing a report, use `interior_project.py snapshot --workspace W --input RELATIVE_REPORT --run-id ROUND --name LABEL` and attest its returned immutable SHA-named path. Early approvals cite actual versioned views/observations rather than `.blend`/GLB bytes that later production stages legitimately mutate. Use unique run IDs and keep failed/accepted captures; freezing does not attest meaning.++## Finish criteria++- All eight stages have current explicit acceptances; source, intake and evidence bytes remain pinned.+- Material audit checks actual current GLB/policy and declares its numerical/visual limitations.+- Delivery audit checks the current contract and all actual files, with distinct runtime/portable/native semantics.+- All three real harness blocking gates pass; no stale receipts are silently repinned.+- Visual reviewer acceptance, current consumer reopening and exercised runtime behavior are documented separately.+- Handoff names output/dependency paths, authoring/reproduction commands, observed checks and remaining limits.++Plugin package acceptance is separate from a new interior's acceptance. A plugin test fixture proves gate mechanics, not a newly reconstructed room's photorealism. Historical showcase results are a case study, not automatic approval for future inputs.diff --git a/reference/scene-contract.md b/reference/scene-contract.mdnew file mode 100644index 0000000..3cc4d21--- /dev/null+++ b/reference/scene-contract.md@@ -0,0 +1,53 @@+# Agent-authored scene contract++The agent creates `scene-spec.json` and real `build_scene.py` after viewing the supplied image. Bootstrap does not invent these. The small [studio builder](../examples/studio/build_scene.py) is a mechanism fixture, not a fallback reconstruction; the [Oak/Linen recipe](../recipes/oak-linen/scene-spec.json) is source-hash guarded.++## Specification fields++| Field | Requirement |+|---|---|+| `schemaVersion` | Integer 1. |+| `title`, `sourceKind` | Actual scene title and photo/render/synthetic-design-reference/floorplan classification. |+| `source` | Workspace-relative pinned image under `public/`; actual PNG/JPEG/WebP extension. |+| `sourceViewLimit`, `portability` | Nonempty honest descriptions of single-view uncertainty and static/runtime/native differences. |+| `authoring.sceneBuilder` | Workspace-relative Python module exporting `build_scene(context)`; trusted executable code, not downloaded page instructions. |+| `authoring.sourceImageSize` | Actual displayed `[width,height]`, honoring source orientation; no fixed showcase aspect. |+| `authoring.room` | Authored native Z-up metre extents `x:[min,max]`, `y:[min,max]`, `height`; builder must implement them and return actual room bounds. |+| `authoring.cameraEstimate` | Source `position`, `target`, `lensMm`, `sensorWidthMm`; position must differ from target. Match through actual renders. |+| `authoring.inspectionViews` | Object of named native Z-up `position,target` poses; `source` is implicit. Choose meaningful lateral/reverse/material/cloth views for this scene. |+| `authoring.probePosition` | Authored indoor Z-up point, chosen away from geometry; production probe is 2:1 equirectangular. |+| `authoring.resourceManifest` | Optional workspace-relative actual acquisition receipt; omit for genuinely procedural scenes. |+| `runtime` | `background:null` or local HDR/EXR URL, `backgroundIntensity`, optional `glassTransmission`, `variants:[]` or named finishes and optional `finishTarget`. |+| `assumptions` | Specific authored geometry/scale/material/lighting limits; do not claim measurements from one image. |++A nonempty variant list uses `{id,label,color:"#rrggbb",roughness?}`. The first entry is the authored base; others are relative linear tints for the declared finish group, not replacement material assets. Base RGB channels must be nonzero for relative recoloring. No sofa, curtains, fixed view names or exactly three variants are required.++## Builder execution++`author_scene.py draft` starts an empty Blender scene, explicitly loads the workspace module, calls `build_scene(context)`, finalizes meshes/modifiers/transforms, verifies one material UV0 layer per physical mesh, saves packed native state and actually renders. Subsequent stages reopen that master; they do not reinterpret the source image.++`context.workspace`, `.assets`, `.evidence` are `Path` objects for this project/current run. `.spec` is the parsed dictionary; `.resolve(relative)` confines data inputs/outputs to the workspace. `.helpers` lazily creates a workspace-private helper namespace; no installed-source paths or import-time scene generation.++A complete builder creates actual physical objects, material graphs, a source camera, world/lights and JSON-serializable summary with at least `roomBounds:{min,max}` in native Z-up, camera/views/components/assumptions. Use the complete linked builders as API examples, not an empty factory or a canned scene. Use a real source camera with horizontal sensor fit; ensure actual world pose and target match the declaration. No zero-vector camera templates.++## Reusable helper surface++| Helper | Purpose / identity |+|---|---|+| `material(name,color,roughness=...,metallic=...,maps=...,color_path=...,normal_strength=...)` | Actual Principled graph; map dictionary `color/normal/roughness` resolves inside W. Albedo sRGB, normal/roughness non-color; explicit UV0 normal mapping. Texture overrides the constant base input; dye the map or author a multiply graph when intended. |+| `mesh(name,vertices,faces,material,component,finish=None,tile=...)` | Actual topology with component/physical IDs and metric material UV0. |+| `box`, `tube`, `lathe`, `cushion` | Editable authoring primitives for shell/supports, pipes/seams, hollow vessels and closed lofted soft forms. Choose semantic component/finish explicitly. |+| `project_uv(obj,metres=...)` | Physical-scale local UV0; do not reuse it as the bake layer. |+| `import_model(path,component,center,height=None,width=None,yaw=...)` | Import real local glTF, preserve world affine placement, normalize UV0 and fit declared dimensions. Visually review before using. |+| `bounds(objects)`, `tag`, `light` | World bounds, semantic identity and native light construction. |+| `curtain(name,origin,rail,depth,width,closed_width,height,material,...)` | Actual 100×32 cloth, hems and hooks in an explicit horizontal orthonormal native Z-up frame; exact 50×16 solver intersections and glTF Y-up metadata. |++Preserve real geometry instead of photo cards, material UV0 instead of bake UV reuse, and identity outside a repair's scope. The packaged case shows BVH-seated piping, skewed cushions, explicit furniture contact, real openings and local garden assets; those are techniques, not mandatory furniture.++## Runtime coordinate and cloth contract++Convert native `(x,y,z)` to glTF/Three `(x,z,-y)`. Exported manifest schema 2 contains actual Y-up camera/room bounds/views, source dimensions, atlas URLs/intensities, probe/background, explicit `lighting.sun` object or null, finish groups and product links.++Cloth meshes must carry `curtain_id`, `curtain_part`, dimensions/tile/fabric width, signed `curtain_rail_axis`, `curtain_depth_axis` and `curtain_plane_origin` in glTF Y-up scene coordinates; hem/hook metadata adds `curtain_v` / `curtain_u`. Rails are horizontal and orthogonal. Closed width exceeds open width; both pinned rail endpoints remain inside room bounds. Deforming geometry must be single-user and preserve exact lattice UV intersections. Nonidentity scene roots are rejected rather than silently mis-simulated; this is not an arbitrary-rig cloth importer.++Review the full actual builder/example before running it. Workspace confinement protects file placement, not execution sandboxing: Python builders and Blender add-ons can execute code. Do not execute asset/page-provided scripts as scene specifications.diff --git a/reference/showcase-lessons.md b/reference/showcase-lessons.mdnew file mode 100644index 0000000..34dc0c2--- /dev/null+++ b/reference/showcase-lessons.md@@ -0,0 +1,37 @@+# Oak / Linen: lessons transferred into this workflow++This is one authorized synthetic-reference living room, not a benchmark of automatic reconstruction. The source project is `kiss-gs-real-photo-experiment`; its ledger is `notes/img2interior-distillation.md` and its acceptance receipts are under `evidence/interior/`. Those external assets/receipts are not bundled here. Treat the figures below as historical case evidence, not universal tolerances or fresh proof for a new run.++| Observed failure or boundary | Required action now |+|---|---|+| Technical gates passed while table/chair/pillow forms were rejected | Review camera and component form before finishes; keep rejection evidence |+| EXR orientation wrong without the one required row reversal | Calibrate a rotated asymmetric UV1 fixture against the actual renderer/decoder |+| Cloth point mismatch and initially expensive solver | Sample render-lattice/material coordinates, preserve UV0, measure held error and settle time |+| Hidden/offscreen state, capture loss and wheel conflicts | Own input only during grip; cancel on interruption; measure sleep after settling |+| Controls updates below EPS skipped change events | Clamp eye/target after every update, test real keyboard/orbit/pan/zoom, restore wrappers on disposal |+| Curtain closure could be faked by global dimming | Compare fixed-camera receiver/control patches; separate ambient bake from actual direct shadows |+| Resource dictionary did not attach albedo | Inspect actual exported/runtime texture bindings, not asset acquisition success |+| Roughness image overrode a matte scalar | Distinguish scalar checks from decoded texture/effective response and macro visual review |+| Blender 4.3 sheen export lost constant weight | Verify non-white exported tint; scope conversion to export and restore native inputs in finally |+| Packed image reuse kept old PNG pixels | Refresh owned packed image, reopen without the original file and compare pixels |+| Capture beyond viewport changed canvas width/aspect | Use in-viewport capture; record bounds/projection before relaxing an input invariant |+| Imported quaternion camera ignored Euler-only changes | Set rotation mode deliberately, inspect world forward/target alignment and actual footprint |+| Portable baked UV1 material blurred in macro views | Label representation limits; reopen native/runtime/portable separately |+| Two public GLBs were mistaken for two initial loads | Inspect actual requests and optional downloads; editable master is not another GLB |++## Historical current-case observations++- 208 mesh objects, 661,342 triangles, 18 components; dimensions/unseen surfaces remain authored estimates.+- Final cloth sampled grip errors: approximately 0.016 mm near and 0.932 mm wide; zero camera-component delta in those exercises, preserved UV0 and rail headers.+- Cloth wind-off rendering settled to the same frame count over the observed interval. Context loss/retry and three sofa finishes were exercised; this does not prove real-phone behavior.+- Final runtime/portable Khronos receipts reported 0 errors/0 warnings; that is structural validity, not visual acceptance.+- Runtime GLB 106,821,020 bytes; portable 44,913,856 bytes; native master 85,250,515 bytes. Full viewer assets were about 409.50 MB before JS/CSS, a research payload rather than a lightweight deployment target.+- Static indirect light/probe remain based on open curtains. The portable is a static appearance snapshot, not exported browser cloth physics or close-up PBR equivalence.++## Do not promote case settings to recovered measurements++The 0.65 m curtain tile, high-roughness dye, normal strength 0.70, low sheen, shadow transmission approximation and room bounds are authored settings. They do not measure fibre size, BRDF, absolute image scale or physically exact transport. The workflow promotes causal checks and evidence discipline, not fixed numerical styling for every interior.++## Promotion boundary++No old global skill files or stopped Jev worktrees are changed by this package. The old procedural Forge scaffold is not represented as a completed Blender pipeline. New projects run the installed plugin's actual tools and author their own evidence; historical receipts do not grant new approvals.diff --git a/reference/tool-inputs.md b/reference/tool-inputs.mdnew file mode 100644index 0000000..65b64a2--- /dev/null+++ b/reference/tool-inputs.md@@ -0,0 +1,68 @@+# Tool input contracts++All JSON uses UTF-8. Paths on commands are explicit local files; no tool uploads or generates paid assets. Tools require linked img2_core API 1 and write only their own workspace artifacts/state. Audit gates recheck current inputs instead of trusting a saved pass flag.++## Intake++`init --image PATH --intake PATH --workspace PATH` requires:++```json+{+ "schemaVersion": 1,+ "sourceKind": "synthetic-design-reference",+ "authorization": "Actual permission and scope, reviewed by the project owner",+ "scale": {"unit":"m","basis":"authored-estimate","note":"Single-image scale and unseen depth are authored"},+ "components": ["room-shell","sofa","glazing"],+ "unknowns": ["Unseen construction is not measured"],+ "interactionRequired": true+}+```++`sourceKind`: `synthetic-design-reference`, `photo`, `render`, `floorplan`. Scale basis: `authored-estimate` or `measured`; units `m`. Components are unique nonempty IDs; unknowns is an explicit array. Authorization is a declaration, not a tool-verifiable license. The pinned intake snapshot is `.img2/artifacts/interior/intake.json`.++## Material policy++`audit_materials.py --glb PATH --policy PATH --workspace PATH` requires:++```json+{+ "schemaVersion": 1,+ "materials": [{+ "name": "Exact exported glTF material name",+ "requireBaseColorTexture": true,+ "requireNormalTexture": true,+ "requireRoughnessTexture": true,+ "minRoughnessFactor": 0.8,+ "maxMetallicFactor": 0,+ "maxSheenColorFactor": 0.2,+ "texCoord": 0+ }]+}+```++Only `name` is mandatory per material; declare checks intentionally, not by assumed defaults. Names must be unique and select actual exported materials. Scalar bounds are finite in [0,1], `texCoord` a nonnegative integer. glTF defaults still apply when a factor/extension is absent. The audit checks texture resources, selected primitive UV presence and texture-transform coordinate overrides; it is not the Khronos validator or a texture pixel decoder. For example, roughnessFactor 1 with a low-valued roughness image can still be glossy.++Output: `.img2/artifacts/interior/material-audit.json`. Gate mode: `--workspace PATH --gate`; it is read-only and rejects changed GLB/policy/receipt inputs.++## Delivery contract++`audit_delivery.py --contract PATH --workspace PATH` requires `schemaVersion:1`, `root`, `assets`, `runtime`, `portable`, `native`, and `limitations`.++- `root`: explicit asset directory; relative paths resolve against the contract file. An absolute existing project root is allowed for read-only inspection without large asset copies.+- Each `assets` row: unique nonempty `id`, `role`, POSIX relative `path`, exact expected 64-hex `sha256`.+- Roles: exactly one each `source`, `runtime`, `portable`, `native`; any number of `sidecar` rows.+- All resolved files must stay under root; duplicate paths/IDs, symlink escapes, URLs and missing bytes fail.+- `runtime`: `{"asset":"runtime-id","sidecars":["atlas-id","probe-id"]}`. Reference every sidecar; no undeclared/foreign-role dependency.+- `portable`: `{"asset":"portable-id","limitations":["Static appearance snapshot; no browser cloth physics"]}`.+- `native`: `{"asset":"native-id"}`.+- `limitations`: nonempty strings declaring global assumptions/transport/device limits.++Use observed SHA256s, not invented example digests. The tool cannot establish their provenance or consumer/visual acceptance. Runtime and portable must not be the same file/bytes under two names.++Output: `.img2/artifacts/interior/delivery-audit.json`. Gate mode: `--workspace PATH --gate`; changing the contract or an asset invalidates the saved audit.++## Review and exit codes++`interior_workflow.py record --stage NAME --decision accept|reject|request-input|stop --reviewer NAME --note TEXT --evidence PATH` (repeat evidence flag for multiple files). Stages: `intake,camera,geometry,materials,lighting,interaction,delivery,review`. Evidence resolves inside the workspace and is hash-pinned. `revise --from NAME --reason TEXT` retains history and invalidates the dependent suffix. `next`/`report` are read-only.++Audits/gates: 0 pass, 1 evaluated failure, 2 malformed/error. A gate prints exactly one `img2.gate-verdict` envelope. The real runner produces `img2.gate-run` and stops on a blocking non-pass. Workflow `next` uses 3 for an explicit input/stop block. A passing gate does not authenticate a reviewer or inspect screenshot meaning.diff --git a/reference/viewer-integration.md b/reference/viewer-integration.mdnew file mode 100644index 0000000..be30afa--- /dev/null+++ b/reference/viewer-integration.md@@ -0,0 +1,48 @@+# Integrate the exported scene into the real viewer++## Install into the authored workspace++```sh+python3 "$SKILL_DIR/tools/interior_project.py" install-viewer --workspace "$PWD"+npm ci+npm run build+npm run preview -- --host 127.0.0.1 --port 5179+```++The project must have a pinned source receipt from `start`. The installer copies the actual template, records ownership/hashes and preflights every destination before writing. It refuses unowned/differently edited files, including an existing unrelated `package.json`; do not use destructive force flags to bypass this. For an existing unrelated web app, deliberately integrate the same modules/assets into its conventions and preserve user ownership rather than replacing it.++Template pins Three.js 0.180.0, Vite 6.4.1 and Khronos validator 2.0.0-dev.3.10 in a lockfile. Dependencies are workspace-local; neither the source checkout nor global host config becomes an application. The existing warm-ivory/charcoal/editorial visual language is preserved, with scene-specific data rather than a fixed case title/count.++## Generated manifest, not canned geometry++The application fetches `/assets/interior/manifest.json`. It requires schema 2, actual `sourceImageSize`, title, local source/runtime/portable/native/probe URLs, Y-up camera/room bounds, arbitrary named views, explicit ambient/direct lighting model, lightmaps, Neutral tone mapping/exposure and a variants array (possibly empty). Source is the implicit primary view. Eye and target remain within the declared shell; it is not furniture collision certification.++`lighting.sun` is either a valid directional sun declaration or explicit null. `background` may be absent/null, or a declared local HDR/EXR with intensity. Source dimensions are checked against the decoded image instead of silently forcing the old source aspect. Optional `finishTarget` selects a semantic finish group. Zero variants/cloth is a valid interactive-camera project and hides those controls; it must not fake a sofa or solver.++The loader waits for actual model, atlases, probe, optional background, source image and shader/first-frame work before Ready. Missing/invalid resources and rejected shader contracts show actionable error/retry, not a blank "successful" scene. A failed scene is not replaced with a stock room.++## Lighting/material contract++- UV0 carries physical material detail, normal/roughness/albedo; UV1 carries independent bake charts.+- Linear EXR rows are reversed exactly once for the exercised decoder contract; atlas `channel=1`, non-color sampling and manifest intensity are retained.+- Runtime atlas is SUN-free ambient/fill; one declared shadowed SUN supplies direct light. Full-sun atlases plus runtime SUN are rejected rather than double-lit.+- A pinned Three shader patch removes duplicated static IBL diffuse only, retaining direct light and GGX environment specular. It guards the exact expected shader chunk; library upgrades require real calibration/review.+- Deforming cloth has its own unbaked environment-lit PBR, isolated material/sampler ownership and real dynamic SUN shadows. Static GI/probe do not rebounce with closure/dye.+- Transparent glazing does not become an opaque shadow wall; preserve the stated transmission approximation and real physical blockers.+- Only meshes in the declared finish group change tint/roughness. Imported shared material identity is partitioned so unrelated geometry stays unchanged.++Visible **Powered by Poly Haven** is driven by actual receipt-derived `resourceCredit:{provider:"Poly Haven",apiDerived:true}`. Do not imply provider sponsorship or show a live API credit for a purely procedural scene. Source kind/uncertainty and runtime/portable/native distinctions remain visible.++## Actual surface and input verification++Open a managed browser tab against the loopback built preview; inspect image and actual 3D, not only DOM/source/tests. Save desktop and narrow screenshots inside the existing viewport, camera/canvas bounds and actual page/network errors. Do not use beyond-viewport capture that changes layout/projection.++Exercise source/3D, arbitrary presets, free orbit, pan/zoom, focused-canvas keyboard, reset, wireframe, declared variants, product links and [cloth/lifecycle acceptance](interaction.md) when present. The diagnostic `window.interiorStudy` exposes snapshots of real scene/camera/material/geometry/cloth/navigation state; free orbit uses null rather than colliding with a preset name.++Test actual bad-load → visible error → Retry → usable scene; force real WebGL loss, then the offered read-only/user-action recovery path and verify scene/input resume. A context-lost overlay alone is not recovery. Pause hidden/offscreen work, cancel held gestures and observe wind-off physics settling/on-demand frame sleep. Emulation is not physical phone proof.++## Delivery URLs and budgets++Exactly one runtime GLB is initially loaded. Portable/native links are optional downloads, not eager scene dependencies or browser exporters of current cloth/finish state. Exercise the real links and compare delivered bytes/hashes to declarations. Inspect manifest, atlas/probe/background requests and MIME/status in the production build; save cold initial payload separately from optional bytes and measured frame/device observations.++No public deployment is performed by the template or installer. Keep loopback preview, local installation, source ZIP release and actual published hosting/catalog status distinct.diff --git a/requirements-authoring.txt b/requirements-authoring.txtnew file mode 100644index 0000000..939dd2f--- /dev/null+++ b/requirements-authoring.txt@@ -0,0 +1,5 @@+# Install in an isolated Python 3.11 environment, never host/global Python.+# A Blender 4.3 Python environment with these modules can be used instead.+# Set IMG2_BLENDER_PYTHON to that interpreter for optional real regression tests.+bpy==4.3.0+numpy==1.26.4diff --git a/requirements-surfaces.txt b/requirements-surfaces.txtnew file mode 100644index 0000000..9af3113--- /dev/null+++ b/requirements-surfaces.txt@@ -0,0 +1,3 @@+# Optional production image preparation/comparison; audit/install remain stdlib.+numpy>=1.26,<3+Pillow>=10.4,<13diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..6e9b431--- /dev/null+++ b/requirements.txt@@ -0,0 +1,4 @@+# Python >=3.10 for workspace/audit tools; img2_core API 1 comes from the harness.+# Native production: isolated Python 3.11 and requirements-authoring.txt.+# Image production/comparison: separate environment, requirements-surfaces.txt.+# Viewer/validator: workspace-local npm ci using runtime/viewer/package-lock.json.diff --git a/resources_lib/__init__.py b/resources_lib/__init__.pynew file mode 100644index 0000000..df311c7--- /dev/null+++ b/resources_lib/__init__.py@@ -0,0 +1 @@+"""Workspace-scoped acquisition and authored surface preparation; inert on import."""diff --git a/resources_lib/polyhaven.py b/resources_lib/polyhaven.pynew file mode 100644index 0000000..6932ed4--- /dev/null+++ b/resources_lib/polyhaven.py@@ -0,0 +1,249 @@+"""Live Poly Haven client, independent of the API server implementation.++Downloaded assets are CC0. Access to the live service has separate terms and+requires identifiable requests and visible credit; see API_TERMS.+"""+import hashlib+import json+import os+from pathlib import Path+import re+import tempfile+import urllib.parse+import urllib.request+from uuid import uuid4++from .storage import MAX_JSON, confined, hashes, read_json, relative_path, write_json++API = 'https://api.polyhaven.com'+API_TERMS = 'https://github.com/Poly-Haven/Public-API/blob/master/ToS.md'+CREDIT = 'Powered by Poly Haven'+HEADERS = {'User-Agent': 'img2interior/0.2 PolyHavenResourceClient',+ 'Referer': 'https://img2interior.local/authoring'}+HOSTS = frozenset(('api.polyhaven.com', 'dl.polyhaven.org', 'cdn.polyhaven.com'))+MAX_FILE = 512 * 1024 * 1024+MAX_TOTAL = 4 * 1024 * 1024 * 1024+TYPES = {'hdris': 0, 'textures': 1, 'models': 2}+PROVENANCE = {'provider': 'Poly Haven', 'license': 'CC0-1.0',+ 'licenseUrl': 'https://polyhaven.com/license', 'apiTerms': API_TERMS,+ 'credit': CREDIT}+++def safe_url(url):+ if not isinstance(url, str) or any(ord(c) < 33 for c in url):+ raise ValueError('Invalid resource URL')+ parsed = urllib.parse.urlsplit(url)+ if (parsed.scheme != 'https' or parsed.hostname not in HOSTS or+ parsed.username is not None or parsed.password is not None or+ parsed.port not in (None, 443) or parsed.fragment):+ raise ValueError(f'Only Poly Haven HTTPS API/CDN URLs are permitted: {url}')+ return url+++class SafeRedirect(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, request, response, code, message, headers, newurl):+ safe_url(newurl)+ return super().redirect_request(request, response, code, message, headers, newurl)+++class Client:+ def __init__(self):+ self.opener = urllib.request.build_opener(SafeRedirect())++ def open(self, url):+ return self.opener.open(urllib.request.Request(safe_url(url), headers=HEADERS), timeout=120)++ def get(self, endpoint):+ with self.open(API + endpoint) as response:+ payload = response.read(MAX_JSON + 1)+ if len(payload) > MAX_JSON:+ raise ValueError('Poly Haven JSON response exceeds the 16 MiB limit')+ result = json.loads(payload)+ if not isinstance(result, dict):+ raise ValueError('Expected an API JSON object')+ return result+++def asset_id(value):+ if not isinstance(value, str) or not re.fullmatch(r'[a-z0-9][a-z0-9_-]{0,159}', value):+ raise ValueError(f'Invalid Poly Haven asset id: {value!r}')+ return value+++def describe(client, kind, identifier):+ if kind not in ('info', 'files'):+ raise ValueError('Expected info or files')+ return client.get(f'/{kind}/{asset_id(identifier)}')+++def search(client, kind, query, limit=10):+ query = query.strip().lower()+ if kind not in TYPES or not 1 <= len(query) <= 100 or not 1 <= limit <= 100:+ raise ValueError('Search requires a supported type, 1–100 character query and limit 1–100')+ return client.get('/search?' + urllib.parse.urlencode({'q': query, 't': kind, 'limit': limit}))+++def save_query(workspace, command, request, result):+ relative = f'.img2/artifacts/interior/polyhaven/{command}-{uuid4().hex}.json'+ receipt = {**PROVENANCE, 'request': request, 'result': result, 'receipt': relative}+ write_json(workspace, relative, receipt)+ return receipt+++def descriptor(value):+ if not isinstance(value, dict):+ raise ValueError('Expected a file descriptor')+ size = value.get('size')+ if type(size) is not int or not 0 < size <= MAX_FILE:+ raise ValueError(f'File size must be between 1 and {MAX_FILE} bytes')+ if not isinstance(value.get('md5'), str) or not re.fullmatch('[0-9a-fA-F]{32}', value['md5']):+ raise ValueError('File descriptor is missing a publisher MD5 digest')+ safe_url(value.get('url'))+ return value+++def choose(files, key, resolution, format_name, identifier):+ try:+ return descriptor(files[key][resolution][format_name])+ except KeyError as exc:+ raise ValueError(f'{identifier}: missing {key}/{resolution}/{format_name}; inspect files before selecting') from exc+++def filename(item):+ name = urllib.parse.unquote(urllib.parse.urlsplit(item['url']).path.rsplit('/', 1)[-1])+ relative_path(name)+ if '/' in name:+ raise ValueError('Encoded path separator in publisher filename')+ return name+++def plan_selection(client, workspace, selection):+ if not isinstance(selection, dict) or type(selection.get('schemaVersion')) is not int or selection['schemaVersion'] != 1:+ raise ValueError('Selection must have schemaVersion 1')+ if not isinstance(selection.get('reason'), str) or not selection['reason'].strip():+ raise ValueError('Selection must explain its reason')+ manifest = {**PROVENANCE, 'schemaVersion': 1, 'selection': selection,+ 'models': {}, 'textures': {}, 'hdris': {}, 'modelIncludes': {}, 'assetInfo': {}}+ jobs = {}+ seen = set()++ def enqueue(identifier, relative, item):+ descriptor(item)+ path = f'resources/polyhaven/{identifier}/{relative}'+ confined(workspace, path)+ if path in jobs and jobs[path][1] != item:+ raise ValueError(f'Conflicting publisher files at {path}')+ jobs[path] = (identifier, item)+ return path++ for kind in TYPES:+ entries = selection.get(kind, [])+ if not isinstance(entries, list) or len(entries) > 100:+ raise ValueError(f'{kind} must be a list of at most 100 selections')+ for entry in entries:+ if not isinstance(entry, dict):+ raise ValueError('Each selection must be an object')+ identifier = asset_id(entry.get('id'))+ if identifier in seen:+ raise ValueError(f'Duplicate selected asset: {identifier}')+ seen.add(identifier)+ if not isinstance(entry.get('purpose'), str) or not entry['purpose'].strip():+ raise ValueError(f'{identifier}: purpose is required')+ resolution, format_name = entry.get('resolution'), entry.get('format')+ if not isinstance(resolution, str) or not re.fullmatch(r'[1-9][0-9]?k', resolution):+ raise ValueError(f'{identifier}: expected an explicit resolution such as 2k')+ allowed = {'models': ('gltf',), 'textures': ('jpg', 'png', 'exr'), 'hdris': ('hdr', 'exr')}+ if format_name not in allowed[kind]:+ raise ValueError(f'{identifier}: unsupported {kind} format {format_name!r}')+ info = describe(client, 'info', identifier)+ if info.get('type') != TYPES[kind]:+ raise ValueError(f'{identifier}: API type does not match selected {kind}')+ manifest['assetInfo'][identifier] = info+ files = describe(client, 'files', identifier)+ if kind == 'textures':+ channels = {}+ for channel, key in (('color', 'Diffuse'), ('normal', 'nor_gl'), ('roughness', 'Rough')):+ item = choose(files, key, resolution, format_name, identifier)+ channels[channel] = enqueue(identifier, filename(item), item)+ manifest[kind][identifier] = channels+ else:+ key = 'gltf' if kind == 'models' else 'hdri'+ item = choose(files, key, resolution, format_name, identifier)+ manifest[kind][identifier] = enqueue(identifier, filename(item), item)+ if kind == 'models':+ includes = item.get('include', {})+ if not isinstance(includes, dict) or len(includes) > 1000:+ raise ValueError(f'{identifier}: invalid glTF include map')+ manifest['modelIncludes'][identifier] = {+ relative: enqueue(identifier, relative, child) for relative, child in includes.items()}+ if sum(item['size'] for _, item in jobs.values()) > MAX_TOTAL:+ raise ValueError('Selection exceeds the 4 GiB total transfer limit; use smaller selections')+ return manifest, jobs+++def acquire(client, workspace, identifier, relative, item):+ descriptor(item)+ path = confined(workspace, relative)+ expected = item['md5'].lower()+ if path.is_file() and path.stat().st_size == item['size']:+ count, md5, sha256 = hashes(path)+ if md5 == expected:+ return {'assetId': identifier, 'path': relative, 'url': item['url'],+ 'bytes': count, 'publisherMd5': item['md5'], 'sha256': sha256}+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temporary = tempfile.mkstemp(prefix='.download-', dir=path.parent)+ count = 0+ md5, sha256 = hashlib.md5(usedforsecurity=False), hashlib.sha256()+ try:+ with os.fdopen(fd, 'wb') as output, client.open(item['url']) as response:+ while True:+ block = response.read(min(1024 * 1024, item['size'] - count + 1))+ if not block:+ break+ count += len(block)+ if count > item['size']:+ raise ValueError(f'{identifier}: publisher byte length exceeded for {relative}')+ md5.update(block)+ sha256.update(block)+ output.write(block)+ if count != item['size'] or md5.hexdigest() != expected:+ raise ValueError(f'{identifier}: publisher byte length or MD5 mismatch for {relative}')+ os.replace(temporary, confined(workspace, relative))+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+ return {'assetId': identifier, 'path': relative, 'url': item['url'], 'bytes': count,+ 'publisherMd5': item['md5'], 'sha256': sha256.hexdigest()}+++def verify_gltf(workspace, path, includes):+ document = read_json(confined(workspace, path))+ if document.get('asset', {}).get('version') != '2.0':+ raise ValueError(f'Expected glTF 2.0: {path}')+ for entry in document.get('buffers', []) + document.get('images', []):+ uri = entry.get('uri')+ if uri is None or uri.startswith('data:'):+ continue+ parsed = urllib.parse.urlsplit(uri)+ if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment:+ raise ValueError(f'Nonlocal glTF dependency: {uri}')+ relative = urllib.parse.unquote(uri)+ relative_path(relative)+ if relative not in includes or not confined(workspace, includes[relative]).is_file():+ raise ValueError(f'glTF dependency is missing from publisher include map: {uri}')+++def fetch(workspace, selection_path, client=None):+ workspace = Path(workspace).resolve()+ selection_file = confined(workspace, selection_path)+ selection = read_json(selection_file)+ client = client or Client()+ manifest, jobs = plan_selection(client, workspace, selection)+ receipts = [acquire(client, workspace, identifier, relative, item)+ for relative, (identifier, item) in jobs.items()]+ for identifier, path in manifest['models'].items():+ verify_gltf(workspace, path, manifest['modelIncludes'][identifier])+ manifest.update({'downloads': receipts, 'totalBytes': sum(item['bytes'] for item in receipts),+ 'selectionPath': selection_path, 'selectionSha256': hashes(selection_file)[2]})+ write_json(workspace, '.img2/artifacts/interior/resources.json', manifest)+ return manifestdiff --git a/resources_lib/storage.py b/resources_lib/storage.pynew file mode 100644index 0000000..b49b3a2--- /dev/null+++ b/resources_lib/storage.py@@ -0,0 +1,87 @@+"""Bounded JSON and workspace-only files shared by the resource commands."""+import hashlib+import json+import math+import os+from pathlib import Path, PurePosixPath+import tempfile++MAX_JSON = 16 * 1024 * 1024+++def relative_path(value):+ if not isinstance(value, str) or not value or any(c in value for c in ('\\', ':', '%', '\x00')):+ raise ValueError(f'Expected a plain workspace-relative path: {value!r}')+ path = PurePosixPath(value)+ if path.is_absolute() or any(p in ('', '.', '..') for p in value.split('/')):+ raise ValueError(f'Unsafe relative path: {value!r}')+ return path+++def confined(workspace, relative):+ root = Path(workspace).resolve()+ plugin = Path(__file__).resolve().parents[1]+ if root == plugin or root.is_relative_to(plugin):+ raise ValueError('The installed plugin cannot be the authored workspace')+ path = root+ for part in relative_path(relative).parts:+ path = path / part+ if path.is_symlink():+ raise ValueError(f'Symlink is not a resource path: {relative}')+ if not path.resolve().is_relative_to(root):+ raise ValueError(f'Path escapes workspace: {relative}')+ return path+++def _pairs(items):+ result = {}+ for key, value in items:+ if key in result:+ raise ValueError(f'Duplicate JSON key: {key}')+ result[key] = value+ return result+++def _float(value):+ number = float(value)+ if not math.isfinite(number):+ raise ValueError(f'Non-finite JSON number: {value}')+ return number+++def _constant(value):+ raise ValueError(f'Non-finite JSON value: {value}')+++def read_json(path):+ with Path(path).open('rb') as stream:+ payload = stream.read(MAX_JSON + 1)+ if len(payload) > MAX_JSON:+ raise ValueError(f'JSON exceeds {MAX_JSON} bytes: {path}')+ return json.loads(payload, object_pairs_hook=_pairs, parse_float=_float, parse_constant=_constant)+++def write_json(workspace, relative, data):+ payload = (json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False) + '\n').encode('utf-8')+ path = confined(workspace, relative)+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temporary = tempfile.mkstemp(prefix='.img2-', dir=path.parent)+ try:+ with os.fdopen(fd, 'wb') as stream:+ stream.write(payload)+ os.replace(temporary, confined(workspace, relative))+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+++def hashes(path):+ md5 = hashlib.md5(usedforsecurity=False)+ sha256 = hashlib.sha256()+ count = 0+ with Path(path).open('rb') as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b''):+ count += len(block)+ md5.update(block)+ sha256.update(block)+ return count, md5.hexdigest(), sha256.hexdigest()diff --git a/resources_lib/surfaces.py b/resources_lib/surfaces.pynew file mode 100644index 0000000..1bee390--- /dev/null+++ b/resources_lib/surfaces.py@@ -0,0 +1,301 @@+"""Explicit image recipes, not an image-to-material inference engine.++Schema 1: operations have id, op and output (workspace-relative PNG). Input is+{texture, channel}, {model, include}, {path}, or {reference: true}. A dye operation+has dye:{space:srgb255|linear,value:[r,g,b]}, bounds and optional strength,+exponent, normalizeMean, blur, crop. Roughness uses offset, scale, center+(zero|median), bounds. Crop uses crop:[left,top,right,bottom]. Woven uses outputs+{basecolor,normal,roughness}, resolution, yarns, tileMetres, seed and dye; optional+warpHeight, crossHeight, rippleHeight, yarnWidth, dyeBounds, noise, roughness,+roughnessScale all use physical/linear units as named. Inputs are never modified.+"""+import math+import os+from pathlib import Path+import tempfile++from .storage import confined, hashes, read_json, write_json++MAX_PIXELS = 16 * 1024 * 1024+++def dependencies():+ try:+ import numpy as np+ from PIL import Image, ImageFilter+ except ImportError as exc:+ raise RuntimeError('Surface preparation needs optional requirements-surfaces.txt (NumPy and Pillow)') from exc+ return np, Image, ImageFilter+++def number(value, name, lower=None, upper=None):+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ raise ValueError(f'{name} must be a finite number')+ if (lower is not None and value < lower) or (upper is not None and value > upper):+ raise ValueError(f'{name} is outside its allowed range')+ return value+++def bounds(value, name):+ if not isinstance(value, list) or len(value) != 2:+ raise ValueError(f'{name} requires [minimum, maximum]')+ lo, hi = [number(v, name) for v in value]+ if lo > hi:+ raise ValueError(f'{name} minimum exceeds maximum')+ return lo, hi+++def linear(rgb, np):+ return np.where(rgb <= 0.04045, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)+++def srgb(rgb, np):+ return np.where(rgb <= 0.0031308, rgb * 12.92, 1.055 * np.maximum(rgb, 0) ** (1 / 2.4) - 0.055)+++def dye_value(dye, np):+ if not isinstance(dye, dict) or dye.get('space') not in ('srgb255', 'linear'):+ raise ValueError('dye requires space srgb255 or linear')+ values = dye.get('value')+ if not isinstance(values, list) or len(values) != 3:+ raise ValueError('dye.value requires three color components')+ maximum = 255 if dye['space'] == 'srgb255' else 1+ color = np.asarray([number(v, 'dye', 0, maximum) for v in values], dtype=np.float32)+ return linear(color / 255, np) if maximum == 255 else color+++def pixels(path, mode, Image):+ from PIL import ImageOps+ with Image.open(path) as image:+ if image.width * image.height > MAX_PIXELS:+ raise ValueError(f'Image exceeds {MAX_PIXELS} decoded pixels: {path}')+ return ImageOps.exif_transpose(image).convert(mode)+++def statistics(image, np):+ array = np.asarray(image, dtype=np.float32) / 255+ if array.ndim == 2:+ array = array[..., None]+ return {'size': list(image.size), 'mode': image.mode, 'encoding': 'decoded uint8 / 255',+ 'min': array.min(axis=(0, 1)).tolist(), 'max': array.max(axis=(0, 1)).tolist(),+ 'mean': array.mean(axis=(0, 1)).tolist(), 'std': array.std(axis=(0, 1)).tolist()}+++def crop_image(image, rectangle):+ if (not isinstance(rectangle, list) or len(rectangle) != 4 or+ any(type(v) is not int for v in rectangle)):+ raise ValueError('crop requires four integer pixel coordinates')+ left, top, right, bottom = rectangle+ if not 0 <= left < right <= image.width or not 0 <= top < bottom <= image.height:+ raise ValueError(f'Crop {rectangle} exceeds input image {image.size}; observe the actual image first')+ return image.crop(rectangle)+++def transform(image, operation, np, ImageFilter):+ op = operation['op']+ if 'crop' in operation:+ image = crop_image(image, operation['crop'])+ if op == 'crop':+ if 'crop' not in operation:+ raise ValueError('crop operation requires an explicit crop rectangle')+ return np.asarray(image, dtype=np.float32) / 255+ if op == 'dye':+ blur = number(operation.get('blur', 0), 'blur', 0, 128)+ if blur:+ image = image.filter(ImageFilter.GaussianBlur(blur))+ scan = linear(np.asarray(image, dtype=np.float32) / 255, np)+ luminance = scan @ np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)+ median = float(np.median(luminance))+ if median <= 0:+ raise ValueError('Cannot normalize a scan with zero median luminance')+ lo, hi = bounds(operation['bounds'], 'dye bounds')+ if lo < 0:+ raise ValueError('Dye modulation cannot be negative')+ ratio = np.clip(luminance / median, lo, hi)+ ratio = ratio ** number(operation.get('exponent', 1), 'exponent', 0.01, 10)+ ratio = 1 + number(operation.get('strength', 1), 'strength', 0, 1) * (ratio - 1)+ normalize = operation.get('normalizeMean', False)+ if type(normalize) is not bool:+ raise ValueError('normalizeMean must be boolean')+ if normalize:+ if float(ratio.mean()) <= 0:+ raise ValueError('Cannot normalize zero modulation')+ ratio /= ratio.mean()+ return np.clip(srgb(ratio[..., None] * dye_value(operation['dye'], np), np), 0, 1)+ if op == 'roughness':+ scan = np.asarray(image, dtype=np.float32) / 255+ center = operation.get('center', 'zero')+ if center not in ('zero', 'median'):+ raise ValueError('roughness center must be zero or median')+ lo, hi = bounds(operation.get('bounds', [0, 1]), 'roughness bounds')+ if lo < 0 or hi > 1:+ raise ValueError('Roughness bounds must lie within [0,1]')+ return np.clip(number(operation['offset'], 'offset') + number(operation['scale'], 'scale') *+ (scan - (np.median(scan) if center == 'median' else 0)), lo, hi)+ raise ValueError(f'Unknown surface operation: {op}')+++def woven(operation, np):+ resolution, yarns = operation['resolution'], operation['yarns']+ if type(resolution) is not int or not 4 <= resolution <= 4096:+ raise ValueError('Woven resolution must be an integer in [4,4096]')+ if type(yarns) is not int or not 2 <= yarns <= resolution or yarns % 2:+ raise ValueError('Woven yarns must be an even integer in [2,resolution] for periodic crossing parity')+ tile = number(operation['tileMetres'], 'tileMetres', 0.0001, 100)+ seed = operation['seed']+ if type(seed) is not int or seed < 0:+ raise ValueError('Woven seed must be a nonnegative integer')+ coordinate = (np.arange(resolution, dtype=np.float32) + 0.5) * yarns / resolution+ x, y = coordinate[None, :], coordinate[:, None]+ ix, iy = np.floor(x).astype(np.int32), np.floor(y).astype(np.int32)+ fx, fy = x % 1 - 0.5, y % 1 - 0.5+ width = number(operation.get('yarnWidth', 0.49), 'yarnWidth', 0.01, 0.5)+ warp = np.sqrt(np.maximum(1 - (fx / width) ** 2, 0))+ weft = np.sqrt(np.maximum(1 - (fy / width) ** 2, 0))+ over = ((ix + iy) % 2) == 0+ high = number(operation.get('warpHeight', 0.00055), 'warpHeight', 0, 1)+ low = number(operation.get('crossHeight', 0.00009), 'crossHeight', 0, 1)+ ripple = number(operation.get('rippleHeight', 0.000012), 'rippleHeight', 0, 1)+ height = np.where(over, high * warp + low * weft, high * weft + low * warp)+ height += ripple * np.sin(x * np.pi * 8) * np.sin(y * np.pi * 6)+ du = (np.roll(height, -1, axis=1) - np.roll(height, 1, axis=1)) * resolution / (2 * tile)+ dv = (np.roll(height, -1, axis=0) - np.roll(height, 1, axis=0)) * resolution / (2 * tile)+ # PNG rows point down; OpenGL tangent-space +V points up.+ normal = np.stack((-du, dv, np.ones_like(height)), axis=-1)+ normal /= np.linalg.norm(normal, axis=-1, keepdims=True)+ rng = np.random.default_rng(seed)+ lo, hi = bounds(operation.get('dyeBounds', [0.92, 1.08]), 'dyeBounds')+ if lo < 0:+ raise ValueError('Yarn dye modulation cannot be negative')+ yarn_dye = rng.uniform(lo, hi, (yarns, 2)).astype(np.float32)+ modulation = np.where(over, yarn_dye[ix, 0], yarn_dye[iy, 1])+ modulation += rng.normal(0, number(operation.get('noise', 0.007), 'noise', 0, 1),+ (resolution, resolution)).astype(np.float32)+ color = np.clip(srgb(modulation[..., None] * dye_value(operation['dye'], np), np), 0, 1)+ roughness = np.clip(number(operation.get('roughness', 0.86), 'roughness', 0, 1) ++ number(operation.get('roughnessScale', 0.05), 'roughnessScale') * (modulation - 1), 0, 1)+ return {'basecolor': color, 'normal': normal * 0.5 + 0.5, 'roughness': roughness}, {+ 'tileMetres': tile, 'yarnPitchMetres': tile / yarns,+ 'normalConvention': 'OpenGL tangent +Y; periodic central derivatives of physical height',+ 'maximumNormalLengthError': float(np.max(np.abs(np.linalg.norm(normal, axis=-1) - 1)))}+++def reference_path(workspace, recipe):+ spec = confined(workspace, recipe.get('spec', 'scene-spec.json'))+ return read_json(spec)['source'] if spec.exists() else 'public/assets/reference.png'+++def resolve_input(workspace, reference, manifest, value):+ if not isinstance(value, dict):+ raise ValueError('input must be a path, reference, texture/channel or model/include object')+ if set(value) == {'path'}:+ relative = value['path']+ elif value == {'reference': True}:+ relative = reference+ elif set(value) == {'texture', 'channel'}:+ if value['channel'] not in ('color', 'normal', 'roughness'):+ raise ValueError('Texture channel must be color, normal or roughness')+ relative = manifest['textures'][value['texture']][value['channel']]+ elif set(value) == {'model', 'include'}:+ relative = manifest['modelIncludes'][value['model']][value['include']]+ else:+ raise ValueError(f'Ambiguous or unsupported surface input: {value}')+ path = confined(workspace, relative)+ if not path.is_file():+ raise ValueError(f'Missing surface input: {relative}')+ if 'texture' in value or 'model' in value:+ receipt = next((entry for entry in manifest['downloads'] if entry['path'] == relative), None)+ if receipt is None or hashes(path)[2] != receipt['sha256']:+ raise ValueError(f'Resource integrity mismatch: {relative}; fetch resources again')+ return relative, path+++def save_image(workspace, relative, array, np, Image):+ if not np.isfinite(array).all():+ raise ValueError('Non-finite generated pixels')+ path = confined(workspace, relative)+ path.parent.mkdir(parents=True, exist_ok=True)+ image = Image.fromarray(np.rint(np.clip(array, 0, 1) * 255).astype(np.uint8))+ fd, temporary = tempfile.mkstemp(prefix='.surface-', suffix='.png', dir=path.parent)+ os.close(fd)+ try:+ image.save(temporary, format='PNG', optimize=True)+ os.replace(temporary, confined(workspace, relative))+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+ decoded = pixels(path, image.mode, Image)+ return {'path': relative, 'sha256': hashes(path)[2], 'pixels': statistics(decoded, np)}+++def prepare(workspace, recipe_path):+ np, Image, ImageFilter = dependencies()+ workspace = Path(workspace).resolve()+ recipe_file = confined(workspace, recipe_path)+ recipe = read_json(recipe_file)+ if not isinstance(recipe, dict) or type(recipe.get('schemaVersion')) is not int or recipe['schemaVersion'] != 1:+ raise ValueError('Surface recipe must have schemaVersion 1')+ operations = recipe.get('operations')+ if not isinstance(operations, list) or not operations or len(operations) > 100:+ raise ValueError('Surface recipe needs 1–100 operations')+ reference = reference_path(workspace, recipe)+ if 'referenceSha256' in recipe:+ if hashes(confined(workspace, reference))[2] != recipe['referenceSha256']:+ raise ValueError('This recipe is bound to a different reference image; author a new recipe instead of reusing its crops')+ manifest_relative = recipe.get('resourceManifest', '.img2/artifacts/interior/resources.json')+ manifest_file = confined(workspace, manifest_relative)+ needs_resources = any(isinstance(op, dict) and isinstance(op.get('input'), dict) and+ ('texture' in op['input'] or 'model' in op['input']) for op in operations)+ manifest = read_json(manifest_file) if needs_resources else {}+ protected = {recipe_file, manifest_file, confined(workspace, reference),+ confined(workspace, recipe.get('spec', 'scene-spec.json'))}+ planned, output_paths, ids = [], set(), set()+ for operation in operations:+ if not isinstance(operation, dict) or operation.get('op') not in ('dye', 'roughness', 'crop', 'woven'):+ raise ValueError('Each operation must be dye, roughness, crop or woven')+ identifier = operation.get('id')+ if not isinstance(identifier, str) or not identifier.strip() or identifier in ids:+ raise ValueError('Operations need unique nonempty ids')+ ids.add(identifier)+ source = None+ if operation['op'] == 'woven':+ outputs = operation.get('outputs')+ if not isinstance(outputs, dict) or set(outputs) != {'basecolor', 'normal', 'roughness'}:+ raise ValueError('Woven outputs must name basecolor, normal and roughness')+ else:+ source = resolve_input(workspace, reference, manifest, operation.get('input'))+ protected.add(source[1])+ outputs = {'image': operation.get('output')}+ for relative in outputs.values():+ path = confined(workspace, relative)+ if path.suffix.lower() != '.png' or not relative.startswith('public/assets/interior/'):+ raise ValueError('Surface outputs must be PNGs under public/assets/interior/')+ if path in output_paths:+ raise ValueError(f'Duplicate surface output: {relative}')+ output_paths.add(path)+ planned.append((operation, source, outputs))+ if output_paths & protected:+ raise ValueError('Surface outputs must not overwrite any recipe, source or resource input')+ records = []+ for operation, source, outputs in planned:+ record = {'id': operation['id'], 'operation': operation, 'inputs': [], 'outputs': {}}+ if operation['op'] == 'woven':+ arrays, metric = woven(operation, np)+ record.update(metric)+ else:+ relative, path = source+ image = pixels(path, 'L' if operation['op'] == 'roughness' else 'RGB', Image)+ record['inputs'].append({'path': relative, 'sha256': hashes(path)[2], 'pixels': statistics(image, np)})+ arrays = {'image': transform(image, operation, np, ImageFilter)}+ for channel, array in arrays.items():+ record['outputs'][channel] = save_image(workspace, outputs[channel], array, np, Image)+ records.append(record)+ receipt = {'schemaVersion': 1, 'recipe': recipe_path, 'recipeSha256': hashes(recipe_file)[2],+ 'operations': records, 'limits': recipe.get('limits', []),+ 'tools': {'numpy': np.__version__, 'Pillow': Image.__version__},+ 'interpretation': 'Explicit authored transformations, not recovered physical reflectance or visual acceptance'}+ if needs_resources:+ receipt['resourceManifest'] = manifest_relative+ receipt['resourceManifestSha256'] = hashes(manifest_file)[2]+ write_json(workspace, '.img2/artifacts/interior/surfaces.json', receipt)+ return receiptdiff --git a/runtime/viewer/index.html b/runtime/viewer/index.htmlnew file mode 100644index 0000000..c92d4bf--- /dev/null+++ b/runtime/viewer/index.html@@ -0,0 +1,96 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Explore an authored 3D interior, compare its source reference and download the editable scene." />+ <title>Interior study</title>+ </head>+ <body>+ <a class="skip-link" href="#study">Skip to 3D view</a>+ <header class="page-header">+ <a class="site-name" href="/">Interior study</a>+ </header>+ <main>+ <div class="intro">+ <h1 id="scene-title">An interior in <em>light.</em></h1>+ <p>From a reference image to editable geometry.<br />Explore the materials, light and viewing angles.</p>+ </div>+ <div class="study-layout">+ <section id="study" class="study" aria-label="Interior viewer" tabindex="-1">+ <div class="viewer-toolbar">+ <div class="mode-switch" role="group" aria-label="View content">+ <button id="mode-3d" type="button" aria-pressed="true" disabled>3D room</button>+ <button id="mode-source" type="button" aria-pressed="false" disabled>Source image</button>+ </div>+ <span id="view-label" class="viewer-kind">3D · authored interior</span>+ </div>+ <div id="viewport" class="viewport" aria-busy="true">+ <div id="canvas-host" class="canvas-host"></div>+ <figure id="source-panel" class="source-panel" hidden>+ <img id="source-view" alt="Source reference image" />+ <figcaption id="source-caption">Source reference image · not a viewer render</figcaption>+ </figure>+ <div id="viewer-message" class="viewer-message">+ <p id="message-title">Opening room</p>+ <p id="message-detail">Reading model, materials and lightmap atlases.</p>+ <button id="retry-load" class="retry-button" type="button" hidden>Retry load</button>+ </div>+ </div>+ <div class="load-line" role="status" aria-live="polite" aria-atomic="true">+ <span id="load-status">Reading scene manifest…</span>+ <progress id="load-progress" aria-label="Asset load progress"></progress>+ </div>+ <div class="viewer-controls">+ <div id="camera-actions" class="camera-actions" role="group" aria-label="Preset views"></div>+ <button id="wireframe" type="button" aria-pressed="false" disabled>Wireframe</button>+ <button id="reset" type="button" disabled>Reset</button>+ </div>+ <fieldset id="curtain-controls" class="curtain-controls" aria-describedby="curtain-hint" hidden>+ <legend>Curtains</legend>+ <div class="curtain-slider">+ <div class="curtain-slider-label"><label for="curtain-amount">Coverage</label><output id="curtain-percent" for="curtain-amount">0%</output></div>+ <input id="curtain-amount" type="range" min="0" max="100" value="0" step="1" disabled />+ </div>+ <div class="curtain-actions">+ <button id="curtain-open" type="button" disabled>Open curtains</button>+ <button id="curtain-close" type="button" disabled>Close curtains</button>+ <button id="curtain-wind" type="button" aria-pressed="true" disabled>Gentle breeze</button>+ </div>+ <p id="curtain-hint">Grab a point on the fabric and drag along the window. Neighbouring cloth follows; release to settle and gently sway.</p>+ </fieldset>+ <div id="finish-controls" class="finish-row" hidden>+ <div class="finish-heading"><span>Material finish</span><strong id="finish-label">Waiting for materials</strong></div>+ <div id="finish-swatches" class="finish-swatches" role="group" aria-label="Material finishes"></div>+ </div>+ <p id="interaction-hint" class="interaction-hint">Drag to orbit the camera. Scroll or pinch to zoom, right-drag to pan inside the room. Keyboard: Tab into the 3D frame, arrow keys to rotate, + / − to zoom, Home returns to the source view.</p>+ </section>+ <aside class="story" aria-label="Source and representation">+ <h2>From one image<br />to a room.</h2>+ <figure class="source-figure">+ <a id="source-link" target="_blank" rel="noopener" aria-label="Open source reference image at full size (new tab)">+ <img id="source-thumbnail" alt="Source reference image" />+ </a>+ <figcaption id="thumbnail-caption">Source reference. Open the image to compare details.</figcaption>+ </figure>+ <p>Geometry, PBR materials and lighting are authored separately. Dimensions, camera angle and hidden surfaces are estimates from one image, not measured data.</p>+ <section class="representation" aria-labelledby="representation-title">+ <h3 id="representation-title">Baked light, editable geometry</h3>+ <p id="representation-detail">Direct sunlight and shadows are rendered in real time. Indirect bounce and reflections use the authored static bake; this is not dynamic GI. The camera stays inside the declared room bounds.</p>+ </section>+ <section class="downloads" aria-labelledby="download-title">+ <h3 id="download-title">Take the scene with you</h3>+ <a id="download-glb" class="download-link" aria-disabled="true" tabindex="-1" download>Download .GLB model</a>+ <p>Standalone GLB: geometry with embedded baked lighting textures and unlit materials. Reflections differ from the PBR viewer.</p>+ <a id="download-blend" class="download-link" aria-disabled="true" tabindex="-1" download>Download .blend scene</a>+ <p>The packed Blender scene keeps PBR materials, geometry and lights for further editing. Downloads preserve the authored scene and original finishes, not the in-viewer changes or cloth simulation.</p>+ </section>+ <p id="resource-credit" class="asset-credit" hidden>Powered by <a href="https://polyhaven.com/" target="_blank" rel="noopener">Poly Haven</a> · CC0 assets.</p>+ </aside>+ </div>+ </main>+ <footer class="page-footer"><span>The source image is a design reference, not measured evidence.</span></footer>+ <noscript><p class="noscript">JavaScript is required to load this scene's manifest, source image and interactive 3D viewer.</p></noscript>+ <script type="module" src="/src/interior.js"></script>+ </body>+</html>diff --git a/runtime/viewer/package-lock.json b/runtime/viewer/package-lock.jsonnew file mode 100644index 0000000..7061dad--- /dev/null+++ b/runtime/viewer/package-lock.json@@ -0,0 +1,1142 @@+{+ "name": "img2interior-viewer",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "img2interior-viewer",+ "version": "1.0.0",+ "dependencies": {+ "three": "0.180.0"+ },+ "devDependencies": {+ "gltf-validator": "2.0.0-dev.3.10",+ "vite": "6.4.1"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^22.20 || ^24.12 || >=25"+ }+ },+ "node_modules/@rollup/rollup-android-arm-eabi": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.7.tgz",+ "integrity": "sha512-GFF2tHk0NqYVObrK0+/ps/LEXsV/v2q6Lyiy7mZr+Ej24fpQScvqK2ziz9NHeEQYnKWKym38Ml7dZbPtC9tuAw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-android-arm64": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.7.tgz",+ "integrity": "sha512-BOymcXJFYYXqluDidj6sLelNjXruC3u1BqVxLn2OPCXH9xaPSOTH+MS4uychsGI1NU7tJoiv9KvqijDHFe+hhQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ]+ },+ "node_modules/@rollup/rollup-darwin-arm64": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.7.tgz",+ "integrity": "sha512-jgVpGweIbls2H5jfBB70tnX52abMd5pJr3xmtoDILx6JdmGl+Un+tMb9R+MbHPVB46tTBpY8emtn7M71SnQhEQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-darwin-x64": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.7.tgz",+ "integrity": "sha512-AVMpt94mrXH7WjyWKmd9nT4RC5yM0AN3Lt6A89xVIsuLDi3dDX6dxMytLbW36FlppY9JsoqUoS3LUUpUrYxiMQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-arm64": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.7.tgz",+ "integrity": "sha512-Nje29c/MyajxRNFGU05oyeTDS6SWdMg/wWMSlZSBTBju5BKz2NVc0kFiFSQGzRELNiB+CBk/ZvAVsWsENgjGag==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-freebsd-x64": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.7.tgz",+ "integrity": "sha512-xxgN5/kMzCNz/NYJ4t49B0/WS6InNlWv6xvgwUQqNnWM9WJMMwMUGWrAxdNEgYWdHL0sMnuh8I87StGrIMTA+w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.7.tgz",+ "integrity": "sha512-5U/9gVn/X657I8+NHoHO9Wnfyd0lEXwqbslobRoB9TC8SwYzOitcIr6TLE7531Q/NWs3L4mb+YOGzlf3vHIeYw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.7.tgz",+ "integrity": "sha512-hcDS0a/Y8ggM3dcOfzH7UpSaogCViWTtNDSl0EXpWIj8g8/r86ITqptjil2hayTXS0Umzb+Yt3mjgpQVFVf2+A==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-gnu": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.7.tgz",+ "integrity": "sha512-awbAr4N7Qd/yjZAQBEEPzgcPveYG2Gi5L6gq1/Bp+3SMRjn5F68Wv1zKsntzvvoioBR6yKvhLtWqu11am1TsxA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-arm64-musl": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.7.tgz",+ "integrity": "sha512-Ut7xQJfeLhzu2yN3rHzVvL9ccyPJvN4aCdP1V7hJ5lGxX/eCzgB9SiMk/Md3J+rWWZgvoYsDW4BUFggJr32pBA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-gnu": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.7.tgz",+ "integrity": "sha512-trqoni/vHkuM5oo5iQhoKPh6fjjD7E80pMgCXWgGxU8vSRPUlwvG8GeYvEEcB6eJAxNa99WH9iVHPHelgtKiHA==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-loong64-musl": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.7.tgz",+ "integrity": "sha512-gvlUy0XFIwtUWiQmhc+4GT2Knm3KosinpUVhr7CtTFA78gFDnE5NWwMPzHrJsYpKkh2LlY7yvBIboN1FAV6Xeg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.7.tgz",+ "integrity": "sha512-8yS/kSXTJ/47Z62JW+C2AJ3vd/8zZw016vFjtNpZwmZlwJumLua4s1i78dkYuSSqQ+0aIMxJcBp/4uIwp2ehjA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-ppc64-musl": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.7.tgz",+ "integrity": "sha512-mxVSKvvty0hOP1AFo/l4Kpv3i3HK0zx4rYUrirZDToYlWhS3xzmIkq3vUJ7rtrM2cPyXveDyDT6M1FfXZ9hTRA==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.7.tgz",+ "integrity": "sha512-lEse1zra1CagM+uHH2bl28GInDsZZ45NJzHei2OMaXQFzZWKBO1hFo07rS0xB6ayV4WU360UrSmPDSyCMpYsUQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-riscv64-musl": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.7.tgz",+ "integrity": "sha512-d/cqCoiG9WMZ5VuJZ5Qdlv9g97QyoGwnmvHccvGhKSacTy7xFrAS+jMcJSBdMNOw1oacSkl6p7K6O/DRYTKL3g==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-s390x-gnu": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.7.tgz",+ "integrity": "sha512-kVEA//CeDOZZP1XCH2JBgqXb9+ALlwuA/4civaazMVdgzaSQC9WM38w65zG/LLk0lA7F9Od19CSBZW7J9mCbNg==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-gnu": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.7.tgz",+ "integrity": "sha512-14oLfDsOSr0TSntT/34jRg/V8B2XW/Jomh9zX9CjIM9gwwNlI1OCymS/GVn0DV32h67eRf7U0GGem0rvfXgNwQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-linux-x64-musl": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.7.tgz",+ "integrity": "sha512-dFVtPfjZqAnUPpPY4Bfg+87yo1IBW9HiY8iCFtg49Pn46MfZTebSHZh8PL6SOsgyt9LQP8Nj/sE6jm3aWpySmQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@rollup/rollup-openbsd-x64": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.7.tgz",+ "integrity": "sha512-Dm9CZ2SM3u2NgvBj4awW/gGqkOwzH8f6MSYIJE6+bKcKLI+T0+LhpD6vtetTfrIIx+rLXDf5RJqBP6v7V5O+wg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ]+ },+ "node_modules/@rollup/rollup-openharmony-arm64": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.7.tgz",+ "integrity": "sha512-oaxsvS2mL6+78741CT2HCORBvy1USg3Wqpt5qvZwy3aMXRMl4zxyDo8maeFRWJkF3dp0Wbi71fKH5Gr9YI3vYA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ]+ },+ "node_modules/@rollup/rollup-win32-arm64-msvc": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.7.tgz",+ "integrity": "sha512-UKZz1Y4mxUqkWh60uH7B1aZn6UcAimPk4ipRktpb3wfZq7JrzZYyAXTwiafkb3T+kd5P3Sf+vzcRdsDks4WtjQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-ia32-msvc": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.7.tgz",+ "integrity": "sha512-WWkSuC1J+mZJnsDh0mRaCAFSWfQdl6y3fDjZeWElI6zHo8CcOSG5lY3yurKJjEq+FrX0WD60sFrVVpbHqzMmrw==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-gnu": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.7.tgz",+ "integrity": "sha512-u9bp2yXCI3/BUjUxY6uWknAY32pfvvDCPysyUTySotx0dj3ydlFHrRQYfn/b/kZgnfjyEwySMtI7Ga054uiysQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@rollup/rollup-win32-x64-msvc": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.7.tgz",+ "integrity": "sha512-EhX6N3XPMEnVU5cRfNgzPOKcSucsbu3nNNWuoAaEuKIqmddBKHN5b9d4rPe65T1I+FaOT176JKiZNsUBp3rqbA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/esbuild": {+ "version": "0.25.12",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.25.12",+ "@esbuild/android-arm": "0.25.12",+ "@esbuild/android-arm64": "0.25.12",+ "@esbuild/android-x64": "0.25.12",+ "@esbuild/darwin-arm64": "0.25.12",+ "@esbuild/darwin-x64": "0.25.12",+ "@esbuild/freebsd-arm64": "0.25.12",+ "@esbuild/freebsd-x64": "0.25.12",+ "@esbuild/linux-arm": "0.25.12",+ "@esbuild/linux-arm64": "0.25.12",+ "@esbuild/linux-ia32": "0.25.12",+ "@esbuild/linux-loong64": "0.25.12",+ "@esbuild/linux-mips64el": "0.25.12",+ "@esbuild/linux-ppc64": "0.25.12",+ "@esbuild/linux-riscv64": "0.25.12",+ "@esbuild/linux-s390x": "0.25.12",+ "@esbuild/linux-x64": "0.25.12",+ "@esbuild/netbsd-arm64": "0.25.12",+ "@esbuild/netbsd-x64": "0.25.12",+ "@esbuild/openbsd-arm64": "0.25.12",+ "@esbuild/openbsd-x64": "0.25.12",+ "@esbuild/openharmony-arm64": "0.25.12",+ "@esbuild/sunos-x64": "0.25.12",+ "@esbuild/win32-arm64": "0.25.12",+ "@esbuild/win32-ia32": "0.25.12",+ "@esbuild/win32-x64": "0.25.12"+ }+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/gltf-validator": {+ "version": "2.0.0-dev.3.10",+ "resolved": "https://registry.npmjs.org/gltf-validator/-/gltf-validator-2.0.0-dev.3.10.tgz",+ "integrity": "sha512-odJ4k0tRkGXiDGn78yDBg+fBbAIvBnXxh3RwAta0emSxGtyagFE8B4xELB1oYe3S5RD8Ci3uZAsZaascH2LAEQ==",+ "dev": true,+ "license": "Apache-2.0"+ },+ "node_modules/nanoid": {+ "version": "3.3.20",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.7",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.30",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",+ "integrity": "sha512-zkd+e9S1AQHhmaBKye9zlFHWjOwVgqXl1q3ECYy8561K7qxR2cREf/STLskulBFd78k6AOFeA+ff1TtEzk9bAA==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.20",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.2"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/rollup": {+ "version": "4.64.7",+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.7.tgz",+ "integrity": "sha512-aCiJONoZp0lNGJ6sYqspLkh6UXaWEey/7Ko2TZyXQ4kgzAhDUxAgbt/oulXKmD+zFHXw1k+RF6ZZWOrjp7DZnQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "1.0.9"+ },+ "bin": {+ "rollup": "dist/bin/rollup"+ },+ "engines": {+ "node": ">=18.0.0",+ "npm": ">=8.0.0"+ },+ "optionalDependencies": {+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",+ "@rollup/rollup-android-arm-eabi": "4.64.7",+ "@rollup/rollup-android-arm64": "4.64.7",+ "@rollup/rollup-darwin-arm64": "4.64.7",+ "@rollup/rollup-darwin-x64": "4.64.7",+ "@rollup/rollup-freebsd-arm64": "4.64.7",+ "@rollup/rollup-freebsd-x64": "4.64.7",+ "@rollup/rollup-linux-arm-gnueabihf": "4.64.7",+ "@rollup/rollup-linux-arm-musleabihf": "4.64.7",+ "@rollup/rollup-linux-arm64-gnu": "4.64.7",+ "@rollup/rollup-linux-arm64-musl": "4.64.7",+ "@rollup/rollup-linux-loong64-gnu": "4.64.7",+ "@rollup/rollup-linux-loong64-musl": "4.64.7",+ "@rollup/rollup-linux-ppc64-gnu": "4.64.7",+ "@rollup/rollup-linux-ppc64-musl": "4.64.7",+ "@rollup/rollup-linux-riscv64-gnu": "4.64.7",+ "@rollup/rollup-linux-riscv64-musl": "4.64.7",+ "@rollup/rollup-linux-s390x-gnu": "4.64.7",+ "@rollup/rollup-linux-x64-gnu": "4.64.7",+ "@rollup/rollup-linux-x64-musl": "4.64.7",+ "@rollup/rollup-openbsd-x64": "4.64.7",+ "@rollup/rollup-openharmony-arm64": "4.64.7",+ "@rollup/rollup-win32-arm64-msvc": "4.64.7",+ "@rollup/rollup-win32-ia32-msvc": "4.64.7",+ "@rollup/rollup-win32-x64-gnu": "4.64.7",+ "@rollup/rollup-win32-x64-msvc": "4.64.7",+ "fsevents": "~2.3.2"+ }+ },+ "node_modules/source-map-js": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/three": {+ "version": "0.180.0",+ "resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",+ "integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w==",+ "license": "MIT"+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/vite": {+ "version": "6.4.1",+ "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",+ "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "^0.25.0",+ "fdir": "^6.4.4",+ "picomatch": "^4.0.2",+ "postcss": "^8.5.3",+ "rollup": "^4.34.9",+ "tinyglobby": "^0.2.13"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",+ "jiti": ">=1.21.0",+ "less": "*",+ "lightningcss": "^1.21.0",+ "sass": "*",+ "sass-embedded": "*",+ "stylus": "*",+ "sugarss": "*",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "lightningcss": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ }+ }+}diff --git a/runtime/viewer/package.json b/runtime/viewer/package.jsonnew file mode 100644index 0000000..d855b4d--- /dev/null+++ b/runtime/viewer/package.json@@ -0,0 +1,21 @@+{+ "name": "img2interior-viewer",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "vite build",+ "preview": "vite preview"+ },+ "dependencies": {+ "three": "0.180.0"+ },+ "devDependencies": {+ "gltf-validator": "2.0.0-dev.3.10",+ "vite": "6.4.1"+ },+ "engines": {+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"+ }+}diff --git a/runtime/viewer/src/interior-curtains.js b/runtime/viewer/src/interior-curtains.jsnew file mode 100644index 0000000..0a8d9e7--- /dev/null+++ b/runtime/viewer/src/interior-curtains.js@@ -0,0 +1,787 @@+import * as THREE from 'three';+import { validateRoomBounds, vector3 } from './interior-manifest.js';++const COLS = 50;+const ROWS = 16;+const STRIDE = COLS + 1;+const COUNT = STRIDE * (ROWS + 1);+const STEP = 1 / 60;+const clamp = THREE.MathUtils.clamp;++// All simulation positions are world-space. UVs, including the glTF V flip,+// identify material points independently of split vertices and panel direction.+export function createCurtainInteraction({ root, camera, canvas, controls, roomBounds, onChange = () => {}, isInteractive = () => true }) {+ validateRoomBounds(roomBounds);+ const room = new THREE.Box3(new THREE.Vector3().fromArray(roomBounds.min), new THREE.Vector3().fromArray(roomBounds.max));+ const doc = canvas.ownerDocument;+ const win = doc.defaultView;+ const motion = win.matchMedia('(prefers-reduced-motion: reduce)');+ let reduced = motion.matches;+ let windRequested = true;+ let wind = windRequested && !reduced;+ let enabled = true;+ let disposed = false;+ let inView = true;+ let paused = true;+ let accumulator = 0;+ let time = 0;+ let active = true;+ let quiet = 0;+ let grip = null;+ const originalCursor = canvas.style.cursor;+ const panels = [];+ const panelById = new Map();+ const fabricBindings = new Map();+ const fabricMeshes = [];+ const raycaster = new THREE.Raycaster();+ const pointer = new THREE.Vector2();+ const hits = [];+ const point = new THREE.Vector3();+ const sample = new THREE.Vector3();+ const contactPoint = new THREE.Vector3();+ const identity = new THREE.Matrix4();+ const delta = new THREE.Vector3();+ const normal = new THREE.Vector3();+ const inverse = new THREE.Matrix4();+ const blocked = new Set();+ const cornerIds = new Int32Array(4);+ const cornerWeights = new Float64Array(4);++ function metadata(mesh) {+ const result = {};+ for (let node = mesh; node; node = node.parent) {+ for (const key of Object.keys(node.userData)) {+ if (key.startsWith('curtain_') && result[key] === undefined) result[key] = node.userData[key];+ }+ if (node === root) break;+ }+ return result;+ }++ function weights(u, v, ids = cornerIds, values = cornerWeights) {+ const x = clamp(u, 0, 1) * COLS;+ const y = clamp(v, 0, 1) * ROWS;+ const i = Math.min(COLS - 1, Math.floor(x));+ const j = Math.min(ROWS - 1, Math.floor(y));+ const a = x - i;+ const b = y - j;+ ids[0] = j * STRIDE + i; ids[1] = ids[0] + 1;+ ids[2] = ids[0] + STRIDE; ids[3] = ids[2] + 1;+ values[0] = (1 - a) * (1 - b); values[1] = a * (1 - b);+ values[2] = (1 - a) * b; values[3] = a * b;+ }++ function interpolate(array, ids, values, out) {+ out.set(0, 0, 0);+ for (let k = 0; k < 4; k++) {+ const i = ids[k] * 3;+ out.x += array[i] * values[k];+ out.y += array[i + 1] * values[k];+ out.z += array[i + 2] * values[k];+ }+ return out;+ }++ root.updateWorldMatrix(true, true);+ const geometryUsers = new Map();+ root.traverse(node => {+ if (node.isMesh) geometryUsers.set(node.geometry, (geometryUsers.get(node.geometry) ?? 0) + 1);+ });+ const meshes = [];+ root.traverse(node => {+ if (!node.isMesh) return;+ const meta = metadata(node);+ if (meta.curtain_id === undefined && meta.curtain_part === undefined) return;+ if (typeof meta.curtain_id !== 'string' || !meta.curtain_id) throw new Error(`Curtain mesh ${node.name} requires a nonempty curtain_id.`);+ if (!['cloth', 'hem', 'hook', 'rail'].includes(meta.curtain_part)) throw new Error(`Curtain ${meta.curtain_id} has an unsupported curtain_part.`);+ meshes.push({ mesh: node, meta });+ if (['cloth', 'hem', 'hook'].includes(meta.curtain_part)) {+ if (!root.matrixWorld.elements.every((value, i) => Math.abs(value - identity.elements[i]) < 1e-8)) {+ throw new Error('Interactive curtains require an identity scene root. Apply root transforms in the authoring scene and re-export metadata in Y-up scene coordinates.');+ }+ if (geometryUsers.get(node.geometry) !== 1) throw new Error(`Curtain ${meta.curtain_id} shares geometry with another mesh; make deforming geometry single-user before export.`);+ const p = node.geometry.getAttribute('position');+ const uv = node.geometry.getAttribute('uv');+ if (!p || p.itemSize !== 3 || !uv || uv.itemSize !== 2 || uv.count !== p.count) throw new Error(`Curtain ${meta.curtain_id} requires complete position and material UV0 attributes.`);+ for (let i = 0; i < p.count; i++) {+ if (![p.getX(i), p.getY(i), p.getZ(i), uv.getX(i), uv.getY(i)].every(Number.isFinite)) throw new Error(`Curtain ${meta.curtain_id} has non-finite geometry or UV0.`);+ }+ if (meta.curtain_part === 'hook' && (!Number.isFinite(meta.curtain_u) || meta.curtain_u < 0 || meta.curtain_u > 1)) throw new Error(`Curtain ${meta.curtain_id} hook needs curtain_u in [0, 1].`);+ if (meta.curtain_part === 'hem' && (!Number.isFinite(meta.curtain_v) || meta.curtain_v < 0 || meta.curtain_v > 1)) throw new Error(`Curtain ${meta.curtain_id} hem needs curtain_v in [0, 1].`);+ }+ if (meta.curtain_part !== 'cloth') return;+ for (const key of ['curtain_tile', 'curtain_fabric_width', 'curtain_height', 'curtain_open_width', 'curtain_closed_width']) {+ if (!Number.isFinite(meta[key]) || meta[key] <= 0) throw new Error(`Curtain ${meta.curtain_id} requires positive ${key}.`);+ }+ if (meta.curtain_closed_width <= meta.curtain_open_width) throw new Error(`Curtain ${meta.curtain_id} closed width must exceed open width.`);+ for (const key of ['curtain_rail_axis', 'curtain_depth_axis', 'curtain_plane_origin']) {+ if (!vector3(meta[key])) throw new Error(`Curtain ${meta.curtain_id} requires explicit Y-up ${key}; re-export using the current curtain helper.`);+ }+ const rail = new THREE.Vector3().fromArray(meta.curtain_rail_axis);+ const depthAxis = new THREE.Vector3().fromArray(meta.curtain_depth_axis);+ const planeOrigin = new THREE.Vector3().fromArray(meta.curtain_plane_origin);+ if (Math.abs(rail.lengthSq()-1) > 1e-5 || Math.abs(depthAxis.lengthSq()-1) > 1e-5+ || Math.abs(rail.dot(depthAxis)) > 1e-5 || Math.abs(rail.y) > 1e-5 || Math.abs(depthAxis.y) > 1e-5) {+ throw new Error(`Curtain ${meta.curtain_id} rail/depth axes must be horizontal orthogonal unit vectors in Y-up scene space.`);+ }+ const existing = panelById.get(meta.curtain_id);+ if (existing) {+ const keys = ['curtain_tile', 'curtain_fabric_width', 'curtain_height', 'curtain_open_width', 'curtain_closed_width', 'curtain_rail_axis', 'curtain_depth_axis', 'curtain_plane_origin'];+ if (keys.some(key => JSON.stringify(existing.meta[key]) !== JSON.stringify(meta[key]))) throw new Error(`Curtain ${meta.curtain_id} primitives disagree on panel metadata.`);+ return;+ }+ const panel = {+ id: meta.curtain_id, meta, rail, closure: 0, targetClosure: 0,+ depthAxis, planeOrigin, pleatDepth: new Float64Array(COUNT),+ rest: new Float64Array(COUNT * 3), goal: new Float64Array(COUNT * 3),+ position: new Float64Array(COUNT * 3), previous: new Float64Array(COUNT * 3),+ counts: new Uint16Array(COUNT), bindings: [], edges: [], speed: 0, displacement: 0,+ };+ panels.push(panel);+ panelById.set(panel.id, panel);+ });+ for (const { meta } of meshes) {+ if (meta.curtain_part !== 'rail' && !panelById.has(meta.curtain_id)) throw new Error(`Curtain ${meta.curtain_id} ${meta.curtain_part} has no cloth panel.`);+ }++ // Average front/back copies at each authored grid point, retaining the shell+ // offset separately when mapping the solver back onto the imported geometry.+ for (const { mesh, meta } of meshes) {+ if (meta.curtain_part !== 'cloth') continue;+ const panel = panelById.get(meta.curtain_id);+ const uv = mesh.geometry.getAttribute('uv');+ const positions = mesh.geometry.getAttribute('position');+ if (!uv) throw new Error(`Curtain ${panel.id} requires material UV0`);+ for (let i = 0; i < positions.count; i++) {+ const u = clamp(uv.getX(i) * meta.curtain_tile / meta.curtain_fabric_width, 0, 1);+ const v = clamp((1 - uv.getY(i)) * meta.curtain_tile / meta.curtain_height, 0, 1);+ const gridU = u*COLS, gridV = v*ROWS;+ const col = Math.round(gridU), row = Math.round(gridV);+ // The solver samples exact intersections of the denser authored mesh.+ // Averaging neighbouring material points would move rail pins and folds.+ if (Math.abs(gridU-col) > 1e-4 || Math.abs(gridV-row) > 1e-4) continue;+ const index = row*STRIDE + col;+ point.fromBufferAttribute(positions, i).applyMatrix4(mesh.matrixWorld);+ panel.rest[index * 3] += point.x;+ panel.rest[index * 3 + 1] += point.y;+ panel.rest[index * 3 + 2] += point.z;+ panel.counts[index]++;+ }+ }+ for (const panel of panels) {+ for (let i = 0; i < COUNT; i++) {+ if (!panel.counts[i]) throw new Error(`Curtain ${panel.id} is missing material grid point ${i}`);+ for (let a = 0; a < 3; a++) panel.rest[i * 3 + a] /= panel.counts[i];+ point.fromArray(panel.rest, i * 3);+ panel.pleatDepth[i] = delta.copy(point).sub(panel.planeOrigin).dot(panel.depthAxis);+ if (i >= ROWS * STRIDE) {+ const travel = (i % STRIDE) / COLS * (panel.meta.curtain_closed_width-panel.meta.curtain_open_width);+ if (!room.containsPoint(point) || !room.containsPoint(point.addScaledVector(panel.rail, travel))) {+ throw new Error(`Curtain ${panel.id} pinned header leaves roomBounds at open or closed coverage; repair the rail metadata or authored bounds.`);+ }+ }+ }+ panel.goal.set(panel.rest);+ panel.position.set(panel.rest);+ panel.previous.set(panel.rest);+ const edges = [];+ const add = (a, b, stiffness) => edges.push(a, b, stiffness);+ for (let j = 0; j <= ROWS; j++) {+ for (let i = 0; i <= COLS; i++) {+ const a = j * STRIDE + i;+ if (i < COLS) add(a, a + 1, 0.85);+ if (j < ROWS) add(a, a + STRIDE, 0.95);+ if (i < COLS && j < ROWS) {+ add(a, a + STRIDE + 1, 0.55);+ add(a + 1, a + STRIDE, 0.55);+ }+ if (i + 2 <= COLS) add(a, a + 2, 0.18);+ if (j + 2 <= ROWS) add(a, a + 2 * STRIDE, 0.18);+ }+ }+ panel.edges = new Float64Array(edges);+ panel.lengths = new Float64Array(edges.length / 3);+ updateGoal(panel);+ }++ for (const { mesh, meta } of meshes) {+ const panel = panelById.get(meta.curtain_id);+ if (!panel || !['cloth', 'hem', 'hook'].includes(meta.curtain_part)) continue;+ const geometry = mesh.geometry;+ const positions = geometry.getAttribute('position');+ const uv = geometry.getAttribute('uv');+ const binding = {+ panel, mesh, part: meta.curtain_part, ids: new Int32Array(positions.count * 4),+ weights: new Float64Array(positions.count * 4), offsets: new Float64Array(positions.count * 3),+ original: positions.array.slice(), originalUsage: positions.usage,+ originalNormal: geometry.getAttribute('normal')?.array.slice() ?? null,+ originalTangent: geometry.getAttribute('tangent')?.array.slice() ?? null,+ tangent1: null, tangent2: null,+ };+ positions.setUsage(THREE.DynamicDrawUsage);+ if (!geometry.getAttribute('normal')) geometry.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(positions.count * 3), 3));+ if (geometry.getAttribute('tangent')) {+ binding.tangent1 = new Float64Array(positions.count * 3);+ binding.tangent2 = new Float64Array(positions.count * 3);+ }+ for (let i = 0; i < positions.count; i++) {+ point.fromBufferAttribute(positions, i).applyMatrix4(mesh.matrixWorld);+ let u;+ let v;+ if (meta.curtain_part === 'cloth') {+ u = uv.getX(i) * panel.meta.curtain_tile / panel.meta.curtain_fabric_width;+ v = (1 - uv.getY(i)) * panel.meta.curtain_tile / panel.meta.curtain_height;+ } else if (meta.curtain_part === 'hook') {+ u = meta.curtain_u; v = 1;+ } else {+ // Project onto the authored rail rather than raw local mesh axes.+ delta.copy(point).sub(sample.fromArray(panel.rest, ROWS * STRIDE * 3));+ u = delta.dot(panel.rail) / (panel.rail.lengthSq() * panel.meta.curtain_open_width);+ v = meta.curtain_v;+ }+ weights(u, v);+ interpolate(panel.rest, cornerIds, cornerWeights, sample);+ for (let k = 0; k < 4; k++) {+ binding.ids[i * 4 + k] = cornerIds[k];+ binding.weights[i * 4 + k] = cornerWeights[k];+ }+ binding.offsets[i * 3] = point.x - sample.x;+ binding.offsets[i * 3 + 1] = point.y - sample.y;+ binding.offsets[i * 3 + 2] = point.z - sample.z;+ }+ panel.bindings.push(binding);+ if (binding.part === 'cloth' || binding.part === 'hem') {+ fabricBindings.set(mesh, binding);+ fabricMeshes.push(mesh);+ }+ }++ function updateGoal(panel) {+ const expansion = panel.closure * (panel.meta.curtain_closed_width - panel.meta.curtain_open_width);+ for (let i = 0; i < COUNT; i++) {+ const shift = (i % STRIDE) / COLS * expansion;+ // Unfold the gathered depth as the rail expands, leaving modest closed+ // pleats. The short pinned header retains its authored depth so hooks+ // and their cloth attachments translate only along the rail.+ const v = Math.floor(i / STRIDE) / ROWS;+ const headerBlend = clamp((1 - v) * 8, 0, 1);+ const unfold = -panel.pleatDepth[i] * 0.72 * panel.closure+ * headerBlend * headerBlend * (3 - 2 * headerBlend);+ panel.goal[i * 3] = panel.rest[i * 3] + panel.rail.x * shift + panel.depthAxis.x * unfold;+ panel.goal[i * 3 + 1] = panel.rest[i * 3 + 1] + panel.rail.y * shift + panel.depthAxis.y * unfold;+ panel.goal[i * 3 + 2] = panel.rest[i * 3 + 2] + panel.rail.z * shift + panel.depthAxis.z * unfold;+ }+ for (let e = 0; e < panel.edges.length; e += 3) {+ const a = panel.edges[e] * 3;+ const b = panel.edges[e + 1] * 3;+ panel.lengths[e / 3] = Math.hypot(panel.goal[b] - panel.goal[a], panel.goal[b + 1] - panel.goal[a + 1], panel.goal[b + 2] - panel.goal[a + 2]);+ }+ }++ function constrainGrip(panel) {+ if (!grip || grip.panel !== panel) return;+ interpolate(panel.position, grip.ids, grip.weights, sample);+ delta.copy(grip.target).sub(grip.offset).sub(sample);+ let denominator = 0;+ let largestWeight = 0;+ for (let k = 0; k < 4; k++) {+ if (grip.ids[k] < ROWS * STRIDE) {+ denominator += grip.weights[k] ** 2;+ largestWeight = Math.max(largestWeight, grip.weights[k]);+ }+ }+ if (denominator < 0.0001) return; // A point exactly on the rail remains pinned.+ delta.clampLength(0, Math.min(0.10, 0.04 * denominator / largestWeight));+ for (let k = 0; k < 4; k++) {+ if (grip.ids[k] >= ROWS * STRIDE) continue;+ const i = grip.ids[k] * 3;+ const w = grip.weights[k] / denominator * 0.9;+ panel.position[i] += delta.x * w;+ panel.position[i + 1] += delta.y * w;+ panel.position[i + 2] += delta.z * w;+ }+ }++ function clampToRoom(vector) {+ return room.clampPoint(vector, vector);+ }++ function boundsAndPins(panel) {+ for (let i = 0; i < COUNT; i++) {+ const a = i * 3;+ if (i >= ROWS * STRIDE) {+ for (let k = 0; k < 3; k++) panel.position[a + k] = panel.goal[a + k];+ } else {+ contactPoint.fromArray(panel.position, a);+ clampToRoom(contactPoint);+ panel.position[a] = contactPoint.x;+ panel.position[a + 1] = contactPoint.y;+ panel.position[a + 2] = contactPoint.z;+ }+ }+ }++ function stepPanel(panel) {+ const difference = panel.targetClosure - panel.closure;+ if (Math.abs(difference) > 0.00001) {+ panel.closure += difference * (1 - Math.exp(-STEP * 9));+ if (Math.abs(panel.targetClosure - panel.closure) < 0.0001) panel.closure = panel.targetClosure;+ updateGoal(panel);+ }+ const p = panel.position;+ const prev = panel.previous;+ const goal = panel.goal;+ const damping = reduced ? 0.75 : 0.94;+ for (let i = 0; i < ROWS * STRIDE; i++) {+ const a = i * 3;+ const v = Math.floor(i / STRIDE) / ROWS;+ const breeze = wind ? 0.19 * Math.sin(time * 1.15 + i % STRIDE * 0.075 + v * 2.4) * (1 - v) : 0;+ for (let k = 0; k < 3; k++) {+ const value = p[a + k];+ const velocity = clamp((value - prev[a + k]) * damping, -0.035, 0.035);+ const force = (goal[a + k] - value) * 14 + (k === 1 ? -1.5 : 0) + breeze * panel.depthAxis.getComponent(k);+ p[a + k] = value + velocity + force * STEP * STEP;+ prev[a + k] = value;+ }+ }+ for (let iteration = 0; iteration < 7; iteration++) {+ for (let e = 0; e < panel.edges.length; e += 3) {+ const ai = panel.edges[e];+ const bi = panel.edges[e + 1];+ const a = ai * 3;+ const b = bi * 3;+ const dx = p[b] - p[a]; const dy = p[b + 1] - p[a + 1]; const dz = p[b + 2] - p[a + 2];+ const distance = Math.sqrt(dx*dx + dy*dy + dz*dz);+ const wa = ai < ROWS * STRIDE ? 1 : 0;+ const wb = bi < ROWS * STRIDE ? 1 : 0;+ if (!distance || !wa && !wb) continue;+ const correction = (distance - panel.lengths[e / 3]) / distance * panel.edges[e + 2] / (wa + wb);+ p[a] += dx * correction * wa; p[a + 1] += dy * correction * wa; p[a + 2] += dz * correction * wa;+ p[b] -= dx * correction * wb; p[b + 1] -= dy * correction * wb; p[b + 2] -= dz * correction * wb;+ }+ constrainGrip(panel);+ boundsAndPins(panel);+ }+ panel.speed = 0;+ panel.displacement = 0;+ for (let i = 0; i < COUNT; i++) {+ const a = i * 3;+ const vx = p[a]-prev[a], vy = p[a+1]-prev[a+1], vz = p[a+2]-prev[a+2];+ const dx = p[a]-goal[a], dy = p[a+1]-goal[a+1], dz = p[a+2]-goal[a+2];+ panel.speed = Math.max(panel.speed, vx*vx + vy*vy + vz*vz);+ panel.displacement = Math.max(panel.displacement, dx*dx + dy*dy + dz*dz);+ if (i >= ROWS * STRIDE) for (let k = 0; k < 3; k++) prev[a + k] = p[a + k];+ }+ panel.speed = Math.sqrt(panel.speed)/STEP;+ panel.displacement = Math.sqrt(panel.displacement);+ }++ // Reuse normal/tangent accumulators: computeTangents creates scratch arrays on+ // each call. UV0/UV1 and the imported shell topology remain untouched.+ function updateSurface(binding) {+ const geometry = binding.mesh.geometry;+ const p = geometry.getAttribute('position');+ const n = geometry.getAttribute('normal');+ const uv = geometry.getAttribute('uv');+ const tangent = geometry.getAttribute('tangent');+ const index = geometry.index;+ n.array.fill(0);+ binding.tangent1?.fill(0);+ binding.tangent2?.fill(0);+ const count = index ? index.count : p.count;+ for (let t = 0; t + 2 < count; t += 3) {+ const a = index ? index.getX(t) : t;+ const b = index ? index.getX(t + 1) : t + 1;+ const c = index ? index.getX(t + 2) : t + 2;+ const x1 = p.getX(b) - p.getX(a); const y1 = p.getY(b) - p.getY(a); const z1 = p.getZ(b) - p.getZ(a);+ const x2 = p.getX(c) - p.getX(a); const y2 = p.getY(c) - p.getY(a); const z2 = p.getZ(c) - p.getZ(a);+ const nx = y1 * z2 - z1 * y2; const ny = z1 * x2 - x1 * z2; const nz = x1 * y2 - y1 * x2;+ let sx = 0; let sy = 0; let sz = 0; let tx = 0; let ty = 0; let tz = 0;+ if (tangent && uv) {+ const s1 = uv.getX(b) - uv.getX(a); const s2 = uv.getX(c) - uv.getX(a);+ const t1 = uv.getY(b) - uv.getY(a); const t2 = uv.getY(c) - uv.getY(a);+ const determinant = s1 * t2 - s2 * t1;+ if (Math.abs(determinant) > 1e-12) {+ const r = 1 / determinant;+ sx = (t2 * x1 - t1 * x2) * r; sy = (t2 * y1 - t1 * y2) * r; sz = (t2 * z1 - t1 * z2) * r;+ tx = (s1 * x2 - s2 * x1) * r; ty = (s1 * y2 - s2 * y1) * r; tz = (s1 * z2 - s2 * z1) * r;+ }+ }+ for (let corner = 0; corner < 3; corner++) {+ const i = corner === 0 ? a : corner === 1 ? b : c;+ n.setXYZ(i, n.getX(i) + nx, n.getY(i) + ny, n.getZ(i) + nz);+ if (tangent) {+ binding.tangent1[i * 3] += sx; binding.tangent1[i * 3 + 1] += sy; binding.tangent1[i * 3 + 2] += sz;+ binding.tangent2[i * 3] += tx; binding.tangent2[i * 3 + 1] += ty; binding.tangent2[i * 3 + 2] += tz;+ }+ }+ }+ for (let i = 0; i < p.count; i++) {+ normal.fromBufferAttribute(n, i).normalize();+ n.setXYZ(i, normal.x, normal.y, normal.z);+ if (tangent) {+ point.fromArray(binding.tangent1, i * 3);+ point.addScaledVector(normal, -normal.dot(point)).normalize();+ delta.crossVectors(normal, point);+ sample.fromArray(binding.tangent2, i * 3);+ tangent.setXYZW(i, point.x, point.y, point.z, delta.dot(sample) < 0 ? -1 : 1);+ }+ }+ n.needsUpdate = true;+ if (tangent) tangent.needsUpdate = true;+ }++ function renderGeometry() {+ root.updateWorldMatrix(true, true);+ for (const panel of panels) for (const binding of panel.bindings) {+ inverse.copy(binding.mesh.matrixWorld).invert();+ const positions = binding.mesh.geometry.getAttribute('position');+ for (let i = 0; i < positions.count; i++) {+ point.fromArray(binding.offsets, i * 3);+ for (let k = 0; k < 4; k++) {+ const a = binding.ids[i * 4 + k] * 3;+ const w = binding.weights[i * 4 + k];+ point.x += panel.position[a] * w;+ point.y += panel.position[a + 1] * w;+ point.z += panel.position[a + 2] * w;+ }+ point.applyMatrix4(inverse);+ positions.setXYZ(i, point.x, point.y, point.z);+ }+ positions.needsUpdate = true;+ updateSurface(binding);+ binding.mesh.geometry.computeBoundingBox();+ binding.mesh.geometry.computeBoundingSphere();+ }+ }++ function available() {+ return !disposed && enabled && !doc.hidden && inView && isInteractive();+ }++ function wake() {+ active = true;+ quiet = 0;+ if (!disposed) onChange();+ }++ function setRay(event) {+ const rect = canvas.getBoundingClientRect();+ if (!rect.width || !rect.height) return false;+ pointer.set((event.clientX - rect.left) / rect.width * 2 - 1, 1 - (event.clientY - rect.top) / rect.height * 2);+ camera.updateWorldMatrix(true, false);+ raycaster.setFromCamera(pointer, camera);+ return true;+ }++ function visibleHit(hit) {+ if (!hit.object.isMesh || !camera.layers.test(hit.object.layers)) return false;+ for (let node = hit.object; node; node = node.parent) if (!node.visible) return false;+ const materials = hit.object.material;+ const material = Array.isArray(materials) ? materials[hit.face?.materialIndex ?? 0] : materials;+ return !!material?.visible && !(material.transparent && material.opacity === 0);+ }++ function pick(event) {+ if (!setRay(event)) return null;+ root.updateWorldMatrix(true, true);+ hits.length = 0;+ raycaster.intersectObjects(fabricMeshes, false, hits);+ let candidate = null;+ for (const hit of hits) {+ if (hit.uv && visibleHit(hit)) { candidate = hit; break; }+ }+ if (!candidate) return null;+ // Only pay for scene occlusion when the pointer actually reaches fabric.+ // Limit the second query to the candidate; geometry behind it is irrelevant.+ const previousFar = raycaster.far;+ raycaster.far = Math.min(previousFar, candidate.distance + 0.0001);+ hits.length = 0;+ try {+ raycaster.intersectObject(root, true, hits);+ } finally {+ raycaster.far = previousFar;+ }+ for (const hit of hits) {+ if (!visibleHit(hit)) continue;+ return fabricBindings.has(hit.object) && hit.uv ? hit : null;+ }+ return null;+ }++ function cancelGrip() {+ if (!grip) return;+ const old = grip;+ grip = null;+ win.removeEventListener('wheel', suppress, true);+ controls.enabled = old.controlsEnabled && enabled && isInteractive();+ canvas.style.cursor = originalCursor;+ if (canvas.hasPointerCapture(old.pointerId)) canvas.releasePointerCapture(old.pointerId);+ wake();+ }++ function suppress(event) {+ event.preventDefault();+ event.stopImmediatePropagation();+ }++ function pointerDown(event) {+ if (grip && event.pointerId !== grip.pointerId) {+ blocked.add(event.pointerId);+ blocked.add(grip.pointerId);+ cancelGrip();+ suppress(event);+ return;+ }+ if (event.target !== canvas || !available() || blocked.size || event.button !== 0 || event.isPrimary === false) return;+ const hit = pick(event);+ if (!hit) return;+ const binding = fabricBindings.get(hit.object);+ const panel = binding.panel;+ let u, v;+ if (binding.part === 'cloth') {+ u = hit.uv.x * panel.meta.curtain_tile / panel.meta.curtain_fabric_width;+ v = (1-hit.uv.y) * panel.meta.curtain_tile / panel.meta.curtain_height;+ } else {+ // Hem texture UVs describe the tube, not the parent fabric. Recover the+ // grabbed material point from the same vertex bindings used to deform it.+ u = v = 0;+ for (let corner = 0; corner < 3; corner++) {+ const vertex = corner === 0 ? hit.face.a : corner === 1 ? hit.face.b : hit.face.c;+ const barycentric = corner === 0 ? hit.barycoord.x : corner === 1 ? hit.barycoord.y : hit.barycoord.z;+ for (let k = 0; k < 4; k++) {+ const slot = vertex*4+k;+ const id = binding.ids[slot];+ const weight = barycentric*binding.weights[slot];+ u += id%STRIDE/COLS*weight;+ v += Math.floor(id/STRIDE)/ROWS*weight;+ }+ }+ }+ u = clamp(u, 0, 1); v = clamp(v, 0, 1);+ const ids = new Int32Array(4);+ const values = new Float64Array(4);+ weights(u, v, ids, values);+ interpolate(panel.position, ids, values, sample);+ camera.getWorldDirection(normal);+ grip = {+ panel, part: binding.part, pointerId: event.pointerId, ids, weights: values, uv: [u, v],+ offset: hit.point.clone().sub(sample), start: hit.point.clone(), target: hit.point.clone(),+ plane: new THREE.Plane().setFromNormalAndCoplanarPoint(normal, hit.point),+ startClosure: panel.closure, controlsEnabled: controls.enabled,+ };+ controls.enabled = false;+ suppress(event);+ try { canvas.setPointerCapture(event.pointerId); } catch { cancelGrip(); return; }+ win.addEventListener('wheel', suppress, eventOptions);+ canvas.style.cursor = 'grabbing';+ wake();+ }++ function pointerMove(event) {+ if (blocked.has(event.pointerId)) { suppress(event); return; }+ if (!grip) {+ if (event.target === canvas && event.pointerType !== 'touch') canvas.style.cursor = available() && pick(event) ? 'grab' : originalCursor;+ return;+ }+ if (event.pointerId !== grip.pointerId) return;+ suppress(event);+ if (!available()) { cancelGrip(); return; }+ if (!setRay(event) || !raycaster.ray.intersectPlane(grip.plane, point)) return;+ const panel = grip.panel;+ // Rail displacement is retained independently from elastic displacement.+ delta.copy(point).sub(grip.start);+ const travel = panel.meta.curtain_closed_width - panel.meta.curtain_open_width;+ const alongRail = delta.dot(panel.rail) / panel.rail.lengthSq();+ panel.targetClosure = clamp(grip.startClosure + alongRail / (Math.max(0.18, grip.uv[0]) * travel), 0, 1);+ sample.copy(panel.rail).multiplyScalar((panel.targetClosure - grip.startClosure) * travel * grip.uv[0]).add(grip.start);+ delta.copy(point).sub(sample).clampLength(0, 0.85);+ grip.target.copy(sample).add(delta);+ clampToRoom(grip.target);+ wake();+ }++ function pointerEnd(event) {+ if (blocked.delete(event.pointerId)) { suppress(event); return; }+ if (grip?.pointerId !== event.pointerId) return;+ suppress(event);+ cancelGrip();+ }++ function interrupt() {+ cancelGrip();+ blocked.clear();+ accumulator = 0;+ paused = true;+ for (const panel of panels) panel.previous.set(panel.position);+ canvas.style.cursor = originalCursor;+ }++ function visibilityChanged() {+ interrupt();+ if (available()) wake();+ }++ function preferenceChanged() {+ reduced = motion.matches;+ wind = windRequested && !reduced;+ wake();+ }++ function pointerLeave() { if (!grip) canvas.style.cursor = originalCursor; }+ function lostCapture(event) { if (grip?.pointerId === event.pointerId) cancelGrip(); }+ const eventOptions = { capture: true, passive: false };+ win.addEventListener('pointerdown', pointerDown, eventOptions);+ win.addEventListener('pointermove', pointerMove, eventOptions);+ win.addEventListener('pointerup', pointerEnd, eventOptions);+ win.addEventListener('pointercancel', pointerEnd, eventOptions);+ win.addEventListener('blur', interrupt);+ doc.addEventListener('visibilitychange', visibilityChanged);+ canvas.addEventListener('lostpointercapture', lostCapture);+ canvas.addEventListener('pointerleave', pointerLeave);+ motion.addEventListener('change', preferenceChanged);+ const observer = win.IntersectionObserver ? new win.IntersectionObserver(entries => {+ inView = entries[0].isIntersecting;+ visibilityChanged();+ }) : null;+ observer?.observe(canvas);++ function probe(panel, u, v, rect) {+ weights(u, v);+ interpolate(panel.position, cornerIds, cornerWeights, point);+ const world = point.toArray();+ point.project(camera);+ return { uv: [u, v], world, canvas: [(point.x + 1) * rect.width / 2, (1 - point.y) * rect.height / 2], inFrustum: Math.abs(point.x) <= 1 && Math.abs(point.y) <= 1 && Math.abs(point.z) <= 1 };+ }++ return {+ get count() { return panels.length; },+ get closure() {+ let sum = 0;+ for (const panel of panels) sum += panel.closure;+ return panels.length ? sum / panels.length : 0;+ },+ get targetClosure() {+ let sum = 0;+ for (const panel of panels) sum += panel.targetClosure;+ return panels.length ? sum / panels.length : 0;+ },+ get wind() { return wind; },+ get reducedMotion() { return reduced; },+ get grabbing() { return !!grip; },+ update(deltaSeconds, elapsedSeconds) {+ // Native lostpointercapture can wait for the next pointer event.+ if (grip && !canvas.hasPointerCapture(grip.pointerId)) cancelGrip();+ if (!available()) { if (!paused || grip) interrupt(); return false; }+ if (!panels.length) return false;+ if (paused) { paused = false; accumulator = 0; deltaSeconds = 0; }+ if (!active && !wind && !grip) return false;+ // Use simulation time, not wall-clock elapsedSeconds, so tab resumes never+ // jump the wind phase or integrate an accumulated background interval.+ accumulator += clamp(Number.isFinite(deltaSeconds) ? deltaSeconds : 0, 0, STEP * 4);+ let changed = false;+ while (accumulator >= STEP) {+ accumulator -= STEP;+ time += STEP;+ for (const panel of panels) stepPanel(panel);+ changed = true;+ const settling = panels.some(panel => panel.speed > 0.012 || Math.abs(panel.targetClosure - panel.closure) > 0.0001);+ quiet = settling || grip || wind ? 0 : quiet + STEP;+ if (quiet > (reduced ? 0.12 : 0.4)) {+ active = false;+ for (const panel of panels) { panel.previous.set(panel.position); panel.speed = 0; }+ break;+ }+ }+ if (changed) renderGeometry();+ return active || wind || !!grip;+ },+ setClosure(value) {+ if (disposed || !Number.isFinite(value)) return;+ cancelGrip();+ for (const panel of panels) panel.targetClosure = clamp(value, 0, 1);+ wake();+ },+ setWind(value) {+ if (!disposed) { windRequested = !!value; wind = windRequested && !reduced; wake(); }+ return wind;+ },+ setEnabled(value) {+ if (disposed || enabled === !!value) return;+ enabled = !!value;+ if (!enabled) interrupt(); else wake();+ },+ reset() {+ if (disposed) return;+ interrupt();+ windRequested = true;+ wind = !reduced;+ time = 0;+ for (const panel of panels) {+ panel.closure = panel.targetClosure = 0;+ panel.position.set(panel.rest);+ panel.previous.set(panel.rest);+ panel.speed = panel.displacement = 0;+ updateGoal(panel);+ }+ renderGeometry();+ wake();+ },+ snapshot() {+ const rect = canvas.getBoundingClientRect();+ camera.updateWorldMatrix(true, false);+ const result = {+ closure: panels.length ? panels.reduce((sum, panel) => sum + panel.closure, 0) / panels.length : 0,+ wind, grabbing: !!grip, enabled, reducedMotion: reduced,+ panels: panels.map(panel => {+ let topAnchorError = 0;+ for (let i = ROWS * STRIDE * 3; i < COUNT * 3; i += 3) topAnchorError = Math.max(topAnchorError, Math.hypot(panel.position[i] - panel.goal[i], panel.position[i + 1] - panel.goal[i + 1], panel.position[i + 2] - panel.goal[i + 2]));+ return { id: panel.id, closure: panel.closure, targetClosure: panel.targetClosure,+ maxDisplacement: panel.displacement, maxSpeed: panel.speed, topAnchorError,+ probes: [probe(panel, 0.55, 0.25, rect), probe(panel, 0.7, 0.5, rect), probe(panel, 0.8, 0.8, rect), probe(panel, 0.9, 1, rect), probe(panel, 0.55, 0, rect)] };+ }),+ grip: null,+ };+ if (grip) {+ interpolate(grip.panel.position, grip.ids, grip.weights, point).add(grip.offset);+ result.grip = { panel: grip.panel.id, part: grip.part, uv: [...grip.uv], point: point.toArray(), target: grip.target.toArray(), error: point.distanceTo(grip.target) };+ }+ return result;+ },+ dispose() {+ if (disposed) return;+ disposed = true;+ interrupt();+ observer?.disconnect();+ win.removeEventListener('pointerdown', pointerDown, true);+ win.removeEventListener('pointermove', pointerMove, true);+ win.removeEventListener('pointerup', pointerEnd, true);+ win.removeEventListener('pointercancel', pointerEnd, true);+ win.removeEventListener('blur', interrupt);+ doc.removeEventListener('visibilitychange', visibilityChanged);+ canvas.removeEventListener('lostpointercapture', lostCapture);+ canvas.removeEventListener('pointerleave', pointerLeave);+ motion.removeEventListener('change', preferenceChanged);+ // Geometry belongs to the caller: restore it, never dispose shared assets.+ for (const panel of panels) for (const binding of panel.bindings) {+ const geometry = binding.mesh.geometry;+ const positions = geometry.getAttribute('position');+ positions.array.set(binding.original);+ positions.setUsage(binding.originalUsage);+ positions.needsUpdate = true;+ if (binding.originalNormal) {+ geometry.getAttribute('normal').array.set(binding.originalNormal);+ geometry.getAttribute('normal').needsUpdate = true;+ } else geometry.deleteAttribute('normal');+ if (binding.originalTangent) {+ geometry.getAttribute('tangent').array.set(binding.originalTangent);+ geometry.getAttribute('tangent').needsUpdate = true;+ }+ binding.mesh.geometry.computeBoundingBox();+ binding.mesh.geometry.computeBoundingSphere();+ }+ fabricBindings.clear();+ blocked.clear();+ },+ };+}diff --git a/runtime/viewer/src/interior-lightmaps.js b/runtime/viewer/src/interior-lightmaps.jsnew file mode 100644index 0000000..03a06f5--- /dev/null+++ b/runtime/viewer/src/interior-lightmaps.js@@ -0,0 +1,32 @@+import * as THREE from 'three';++// Track decoded storage, not the texture wrapper: clones can share EXR pixels.+const oriented = new WeakSet();+export function prepareLightmaps(atlases) {+ let rowScratch;+ for (const { texture } of atlases) {+ const { data, width, height } = texture.image;+ const stride = data?.length / height;+ if (!ArrayBuffer.isView(data) || !Number.isInteger(width) || width <= 0+ || !Number.isInteger(height) || height <= 0 || stride !== width * 4) {+ throw new Error('EXR atlas does not contain valid RGBA data.');+ }+ // r180 EXRLoader decodes bottom-row-first; glTF UV1 uses a top origin.+ // Only the lightmap crosses this boundary, never the environment probe.+ if (!oriented.has(data)) {+ if (!rowScratch || rowScratch.constructor !== data.constructor || rowScratch.length < stride) rowScratch = new data.constructor(stride);+ for (let y = 0; y < Math.floor(height / 2); y++) {+ const top = y * stride;+ const bottom = (height - 1 - y) * stride;+ rowScratch.set(data.subarray(top, top + stride));+ data.copyWithin(top, bottom, bottom + stride);+ data.set(rowScratch.subarray(0, stride), bottom);+ }+ oriented.add(data);+ }+ texture.channel = 1;+ texture.colorSpace = THREE.NoColorSpace;+ texture.flipY = false;+ texture.needsUpdate = true;+ }+}diff --git a/runtime/viewer/src/interior-manifest.js b/runtime/viewer/src/interior-manifest.jsnew file mode 100644index 0000000..191e1a8--- /dev/null+++ b/runtime/viewer/src/interior-manifest.js@@ -0,0 +1,91 @@+export function vector3(value) {+ return Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);+}++export function validateRoomBounds(bounds) {+ if (!vector3(bounds?.min) || !vector3(bounds?.max)+ || bounds.min.some((value, i) => value + 0.5 >= bounds.max[i])) {+ throw new Error('roomBounds must contain Y-up min/max vectors with more than 0.5 m on every axis.');+ }+}++function assetPath(value, field) {+ if (typeof value !== 'string' || !value.startsWith('/assets/') || /[\\?#\s]/.test(value)) {+ throw new Error(`Missing local /assets/ URL: ${field}`);+ }+ let decoded;+ try { decoded = decodeURIComponent(value); } catch { throw new Error(`Invalid asset URL: ${field}`); }+ if (decoded.split('/').some(part => part === '.' || part === '..') || /[\\?#]/.test(decoded)) {+ throw new Error(`Asset URL must stay inside /assets/: ${field}`);+ }+}++export function validateManifest(manifest) {+ if (manifest?.schemaVersion !== 2 || manifest.lighting?.model !== 'ambient-bake+shadowed-sun-v1') {+ throw new Error('Scene requires schema 2 SUN-free ambient atlases and ambient-bake+shadowed-sun-v1 lighting; full-sun bakes cannot be combined with a runtime sun.');+ }+ if (typeof manifest.title !== 'string' || !manifest.title.trim()) throw new Error('Scene title is required.');+ if (!Array.isArray(manifest.sourceImageSize) || manifest.sourceImageSize.length !== 2+ || !manifest.sourceImageSize.every(value => Number.isInteger(value) && value > 0)) {+ throw new Error('sourceImageSize must contain the source image width and height in pixels.');+ }+ for (const field of ['sourceImage', 'model', 'portableModel', 'blender', 'environment']) assetPath(manifest[field], field);+ if (manifest.background != null) {+ assetPath(manifest.background, 'background');+ if (!Number.isFinite(manifest.backgroundIntensity) || manifest.backgroundIntensity < 0) throw new Error('Background intensity is invalid.');+ if (!/\.(hdr|exr)$/i.test(manifest.background)) throw new Error('Background must be an HDR or EXR image.');+ }+ if (!manifest.views || typeof manifest.views !== 'object' || Array.isArray(manifest.views)) throw new Error('views must be an object of named camera poses (it may be empty).');+ if (Object.hasOwn(manifest.views, 'source')) throw new Error('The source view is implicit in camera; do not duplicate it in views.');+ for (const [name, pose] of [['source', manifest.camera], ...Object.entries(manifest.views)]) {+ if (!name.trim() || !vector3(pose?.position) || !vector3(pose?.target)) throw new Error(`View ${name} needs Y-up position and target vectors.`);+ if (pose.position.every((value, i) => value === pose.target[i])) throw new Error(`View ${name} has position equal to its target.`);+ const fov = pose.fov ?? manifest.camera?.fov;+ if (!Number.isFinite(fov) || fov <= 0 || fov >= 180) throw new Error(`Invalid FOV: ${name}`);+ if (pose.label !== undefined && typeof pose.label !== 'string') throw new Error(`Invalid view label: ${name}`);+ }+ validateRoomBounds(manifest.roomBounds);+ const sun = manifest.lighting.sun;+ if (sun !== null) {+ for (const key of ['position', 'target', 'color']) if (!vector3(sun?.[key])) throw new Error(`Sun config is missing ${key}; use lighting.sun: null when there is no authored sun.`);+ if (sun.position.every((value, i) => value === sun.target[i]) || sun.color.some(value => value < 0)+ || !Number.isFinite(sun.intensity) || sun.intensity < 0+ || !Number.isInteger(sun.shadowMapSize) || sun.shadowMapSize < 512 || sun.shadowMapSize > 4096) {+ throw new Error('Sun direction, color, intensity or shadow map size is invalid.');+ }+ }+ if (manifest.toneMapping !== 'neutral' || !Number.isFinite(manifest.exposure) || manifest.exposure <= 0) throw new Error('Need Neutral tone mapping and a valid exposure.');+ if (!Array.isArray(manifest.lightmaps) || !manifest.lightmaps.length) throw new Error('Manifest has no lightmap atlas.');+ const atlasIds = new Set();+ for (const atlas of manifest.lightmaps) {+ if (!atlas || typeof atlas.id !== 'string' || !atlas.id || atlasIds.has(atlas.id)+ || !Number.isFinite(atlas.intensity) || atlas.intensity <= 0) throw new Error('Lightmap atlas is invalid or has a duplicate id.');+ assetPath(atlas.url, `atlas ${atlas.id}`);+ atlasIds.add(atlas.id);+ }+ if (!Array.isArray(manifest.variants)) throw new Error('variants must be an array (it may be empty).');+ const variantIds = new Set();+ for (const variant of manifest.variants) {+ if (!variant || typeof variant.id !== 'string' || !variant.id || variantIds.has(variant.id)+ || typeof variant.label !== 'string' || !variant.label || !/^#[\da-f]{6}$/i.test(variant.color)+ || (variant.roughness !== undefined && (!Number.isFinite(variant.roughness) || variant.roughness < 0 || variant.roughness > 1))) {+ throw new Error('Finish variants require unique ids, labels, hex colors and optional roughness in [0, 1].');+ }+ variantIds.add(variant.id);+ }+ // Relative linear tints cannot reconstruct a channel absent from the authored base.+ if (manifest.variants.length > 1 && manifest.variants[0].color.slice(1).match(/../g).includes('00')) {+ throw new Error('The first (authored base) finish must have nonzero RGB channels for relative recoloring.');+ }+ if (manifest.finishTarget !== undefined && (typeof manifest.finishTarget !== 'string' || !manifest.finishTarget)) throw new Error('finishTarget must name a nonempty mesh finish tag.');+ return manifest;+}++export function sourceLabel(manifest) {+ return ['synthetic', 'synthetic-design', 'synthetic-design-reference'].includes(manifest.sourceKind)+ ? 'Synthetic design reference' : 'Source reference image';+}++export function usesPolyHavenAPI(manifest) {+ return manifest.resourceCredit?.provider === 'Poly Haven' && manifest.resourceCredit?.apiDerived === true;+}diff --git a/runtime/viewer/src/interior-navigation.js b/runtime/viewer/src/interior-navigation.jsnew file mode 100644index 0000000..1961bbf--- /dev/null+++ b/runtime/viewer/src/interior-navigation.js@@ -0,0 +1,104 @@+import * as THREE from 'three';+import { validateRoomBounds } from './interior-manifest.js';++export function createInteriorNavigation(camera, controls, roomBounds) {+ validateRoomBounds(roomBounds);+ const room = new THREE.Box3(+ new THREE.Vector3().fromArray(roomBounds.min),+ new THREE.Vector3().fromArray(roomBounds.max),+ );+ const cameraBounds = room.clone().expandByScalar(-0.2);+ const targetBounds = room.clone();+ targetBounds.min.add(new THREE.Vector3(0.2, 0, 0.2));+ targetBounds.max.sub(new THREE.Vector3(0.2, 0.15, 0.2));+ const previousCamera = new THREE.Vector3();+ const previousTarget = new THREE.Vector3();+ const direction = new THREE.Vector3();+ const center = room.getCenter(new THREE.Vector3());+ const originalUpdate = controls.update;+ const originalLimits = { minDistance: controls.minDistance, maxDistance: controls.maxDistance,+ minPolarAngle: controls.minPolarAngle, maxPolarAngle: controls.maxPolarAngle };+ const size = room.getSize(new THREE.Vector3());+ let disposed = false;+ let atBoundary = false;++ controls.minDistance = Math.min(0.3, (Math.min(size.x, size.y, size.z)-0.4)/2);+ controls.maxDistance = size.length();+ controls.minPolarAngle = 0.02;+ controls.maxPolarAngle = Math.PI - 0.02;++ function constrain() {+ if (disposed) return false;+ previousCamera.copy(camera.position);+ previousTarget.copy(controls.target);+ cameraBounds.clampPoint(camera.position, camera.position);+ targetBounds.clampPoint(controls.target, controls.target);++ if (camera.position.distanceToSquared(controls.target) < controls.minDistance ** 2) {+ direction.subVectors(controls.target, camera.position);+ if (direction.lengthSq() > 1e-12) {+ direction.normalize();+ controls.target.copy(camera.position).addScaledVector(direction, controls.minDistance);+ targetBounds.clampPoint(controls.target, controls.target);+ }+ if (camera.position.distanceToSquared(controls.target) < controls.minDistance ** 2) {+ // Near floor/ceiling, a vertical ray may have no room. Aim horizontally+ // into the room instead of pushing the eye through the shell.+ direction.set(center.x-camera.position.x, 0, center.z-camera.position.z);+ if (direction.lengthSq() < 1e-12) direction.set(0, 0, -1);+ direction.normalize();+ controls.target.copy(camera.position).addScaledVector(direction, controls.minDistance);+ targetBounds.clampPoint(controls.target, controls.target);+ }+ }++ atBoundary = !camera.position.equals(previousCamera) || !controls.target.equals(previousTarget);+ if (atBoundary) camera.lookAt(controls.target);+ // OrbitControls r180 derives spherical coordinates from the actual eye and+ // target at the next update; its current change dispatch commits these final+ // transforms afterwards. Calling update here would reintroduce an escape.+ return atBoundary;+ }++ function updateWithinRoom(deltaTime) {+ atBoundary = false;+ const changed = originalUpdate.call(controls, deltaTime);+ const eventBoundary = atBoundary;+ // r180 can skip `change` for sub-EPS transforms. Clamp those too.+ const finalBoundary = constrain();+ atBoundary = eventBoundary || finalBoundary;+ return changed || atBoundary;+ }++ controls.update = updateWithinRoom;+ controls.addEventListener('change', constrain);+ constrain();+ return {+ constrain,+ snapshot() {+ const distance = camera.position.distanceTo(controls.target);+ return {+ bounds: { min: room.min.toArray(), max: room.max.toArray(), cameraMargin: 0.2,+ targetWallMargin: 0.2, targetCeilingMargin: 0.15 },+ camera: camera.position.toArray(), target: controls.target.toArray(),+ safety: {+ cameraInBounds: cameraBounds.containsPoint(camera.position),+ targetInBounds: targetBounds.containsPoint(controls.target),+ distance,+ polarAngle: distance ? Math.acos(THREE.MathUtils.clamp((camera.position.y-controls.target.y)/distance, -1, 1)) : null,+ atBoundary,+ minDistance: controls.minDistance, maxDistance: controls.maxDistance,+ },+ };+ },+ dispose() {+ if (disposed) return;+ disposed = true;+ controls.removeEventListener('change', constrain);+ if (controls.update === updateWithinRoom) {+ controls.update = originalUpdate;+ Object.assign(controls, originalLimits);+ }+ },+ };+}diff --git a/runtime/viewer/src/interior.css b/runtime/viewer/src/interior.cssnew file mode 100644index 0000000..de20b8a--- /dev/null+++ b/runtime/viewer/src/interior.css@@ -0,0 +1,155 @@+:root {+ color-scheme: light;+ font-family: Arial, Helvetica, sans-serif;+ color: #282722;+ background: #f5f2eb;+ font-synthesis: none;+ --paper: #f5f2eb;+ --ink: #282722;+ --muted: #686259;+ --line: #d8d2c6;+ --accent: #a23f2e;+ --soft-accent: #ede1d8;+}++* { box-sizing: border-box; }+[hidden] { display: none !important; }+html { scroll-padding-top: 24px; scrollbar-color: #9d9384 var(--paper); }+body { margin: 0; }+::selection { color: #fffaf2; background: var(--accent); }+:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; }+a { color: inherit; text-underline-offset: 4px; text-decoration-thickness: 1px; }+a:hover { color: var(--accent); }+button { font: inherit; color: inherit; min-height: 44px; border: 1px solid var(--line); border-radius: 4px; padding: 10px 13px; background: transparent; cursor: pointer; }+button, a { -webkit-tap-highlight-color: transparent; }+button:hover:not(:disabled) { background: var(--soft-accent); border-color: var(--accent); }+button[aria-pressed="true"] { color: #fffaf2; background: var(--ink); border-color: var(--ink); }+button[aria-pressed="true"]:hover:not(:disabled) { background: #443c32; border-color: #443c32; }+button:disabled, a[aria-disabled="true"] { opacity: 0.48; cursor: not-allowed; }+p, figure { margin: 0; }+img { display: block; max-width: 100%; height: auto; }+.skip-link { position: fixed; left: 16px; top: -100px; z-index: 10; background: var(--paper); padding: 14px; }+.skip-link:focus { top: 16px; }+.page-header, main, .page-footer { width: min(1720px, calc(100% - 80px)); margin-inline: auto; }+.page-header { min-height: 76px; display: flex; align-items: center; justify-content: space-between; gap: 24px; border-bottom: 1px solid var(--line); }+.site-name { font-size: 17px; font-weight: 600; text-decoration: none; }+.intro { display: flex; align-items: end; justify-content: space-between; gap: 32px; padding: 36px 0 32px; }+h1, h2 { margin: 0; font-family: Georgia, 'Times New Roman', serif; font-weight: 400; text-wrap: balance; }+h1 { font-size: clamp(36px, 3.8vw, 62px); line-height: 1.12; letter-spacing: -0.035em; overflow-wrap: anywhere; }+h1 em { color: var(--accent); font-weight: 400; }+.intro p { color: var(--muted); font-size: 14px; line-height: 1.7; }+.study-layout { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: clamp(28px, 3vw, 48px); align-items: start; }+.study, .story { min-width: 0; }+.viewer-toolbar { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px 18px; margin-bottom: 14px; }+.mode-switch { display: flex; gap: 6px; }+.mode-switch button { font-size: 13px; font-weight: 600; }+.viewer-kind { font-size: 12px; color: var(--muted); }+.viewport { position: relative; width: 100%; aspect-ratio: var(--source-aspect, 16 / 9); background: #282722; overflow: hidden; }+.canvas-host { position: absolute; inset: 0; }+.canvas-host canvas { display: block; width: 100%; height: 100%; cursor: grab; touch-action: none; }+.canvas-host canvas:active { cursor: grabbing; }+.canvas-host canvas:focus-visible { outline-offset: -5px; }+.source-panel { position: absolute; inset: 0; }+.source-panel img { width: 100%; height: 100%; object-fit: contain; }+.source-panel figcaption { position: absolute; left: 0; right: 0; bottom: 0; margin: 0; padding: 7px 12px; background: #282722; color: var(--paper); font-size: 11px; text-align: center; }+.viewer-message { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 24px; background: var(--ink); color: var(--paper); text-align: center; }+#message-title { font-family: Georgia, 'Times New Roman', serif; font-size: clamp(23px, 2.3vw, 32px); }+#message-detail { max-width: 60ch; color: #d8d2c6; font-size: 13px; line-height: 1.6; overflow-wrap: anywhere; }+.retry-button { color: var(--paper); border-color: #9d9384; }+.retry-button:hover:not(:disabled) { background: #443c32; border-color: var(--paper); }+.load-line { min-height: 25px; padding-top: 9px; color: var(--muted); font-size: 11px; line-height: 1.5; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }+.load-line:has([data-state="error"]) { color: #922e21; }+progress { appearance: none; display: block; width: 100%; height: 3px; border: none; margin-top: 7px; background: var(--line); accent-color: var(--accent); }+progress::-webkit-progress-bar { background: var(--line); }+progress::-webkit-progress-value { background: var(--accent); }+progress::-moz-progress-bar { background: var(--accent); }+.viewer-controls { display: flex; justify-content: space-between; align-items: start; flex-wrap: wrap; gap: 10px; margin-top: 16px; font-size: 12px; }+.camera-actions { display: flex; flex-wrap: wrap; gap: 6px; }+.curtain-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 24px; min-width: 0; margin: 22px 0 0; padding: 12px 0 18px; border: 0; border-bottom: 1px solid var(--line); font-size: 12px; }+.curtain-controls legend { padding: 0; font-weight: 600; }+.curtain-slider { flex: 1 1 180px; max-width: 360px; min-width: 0; }+.curtain-slider-label { display: flex; justify-content: space-between; gap: 16px; color: var(--muted); }+.curtain-slider output { color: var(--ink); font-variant-numeric: tabular-nums; }+.curtain-slider input { display: block; width: 100%; height: 44px; margin: 0; accent-color: var(--accent); cursor: ew-resize; }+.curtain-slider input:disabled { opacity: 0.48; cursor: not-allowed; }+.curtain-actions { display: flex; flex-wrap: wrap; gap: 6px; }+#curtain-hint { flex: 1 1 100%; max-width: 80ch; color: var(--muted); font-size: 12px; line-height: 1.7; }+.finish-row { display: flex; flex-wrap: wrap; align-items: center; gap: 14px 24px; padding: 18px 0; margin-top: 18px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }+.finish-heading { display: grid; gap: 5px; min-width: 85px; font-size: 12px; }+.finish-heading > span { color: var(--muted); }+.finish-heading strong { font-weight: 600; }+.finish-swatches { display: flex; flex-wrap: wrap; gap: 8px; }+.finish-swatch { display: flex; align-items: center; gap: 8px; font-size: 12px; }+.swatch-chip { width: 22px; height: 22px; flex: 0 0 22px; border: 1px solid #8a8071; border-radius: 50%; background: var(--swatch-color); }+#reset { margin-left: auto; font-size: 12px; }+.interaction-hint { max-width: 95ch; margin-top: 14px; font-size: 12px; line-height: 1.7; color: var(--muted); }+.story { padding-top: 3px; }+h2 { font-size: 32px; line-height: 1.13; letter-spacing: -0.025em; }+.source-figure { margin-top: 22px; }+.source-figure a { display: block; }+.source-figure img { width: 100%; }+figcaption { margin-top: 8px; color: var(--muted); font-size: 11px; line-height: 1.65; }+.story p { color: var(--muted); font-size: 12px; line-height: 1.75; max-width: 68ch; }+.story > p { margin-top: 18px; }+h3 { margin: 0 0 9px; font-size: 13px; font-weight: 600; line-height: 1.5; }+.representation, .downloads { margin-top: 24px; padding-top: 19px; border-top: 1px solid var(--line); }+.download-link { display: flex; align-items: center; justify-content: space-between; min-height: 44px; gap: 12px; font-size: 13px; font-weight: 600; }+.download-link[aria-disabled="true"] { pointer-events: none; }+.downloads p { font-size: 11px; margin: 2px 0 12px; }+.story .asset-credit { font-size: 11px; }+.page-footer { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px 24px; margin-top: 48px; padding: 22px 0 30px; border-top: 1px solid var(--line); color: var(--muted); font-size: 12px; line-height: 1.7; }+.noscript { margin: 24px; padding: 20px; border: 1px solid var(--accent); line-height: 1.6; }++@media (max-width: 1150px) {+ .page-header, main, .page-footer { width: calc(100% - 48px); }+ .study-layout { grid-template-columns: minmax(0, 1fr) 230px; gap: 28px; }+ .intro p { max-width: 29ch; }+ .finish-row { gap: 14px; }+ .finish-swatches { gap: 6px; }+ .finish-swatch { padding-inline: 9px; }+}++@media (max-width: 900px) {+ .study-layout { grid-template-columns: minmax(0, 1fr); gap: 36px; }+ .story { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 18px 28px; padding-top: 26px; border-top: 1px solid var(--line); }+ .story h2 { align-self: center; }+ .source-figure { grid-column: 2; grid-row: 1 / 3; margin: 0; }+ .story > p { margin: 0; }+ .representation, .downloads { margin-top: 8px; }+ .story .asset-credit { grid-column: 1 / -1; }+}++@media (max-width: 600px) {+ .page-header, main, .page-footer { width: calc(100% - 32px); }+ .page-header { min-height: 66px; gap: 18px; }+ .site-name { font-size: 14px; }+ .intro { display: block; padding: 28px 0 24px; }+ h1 { font-size: clamp(34px, 8vw, 46px); max-width: 16ch; }+ .intro p { margin-top: 14px; max-width: none; font-size: 13px; }+ .viewer-toolbar { gap: 10px; }+ .viewer-kind { font-size: 11px; }+ .viewer-controls { gap: 8px; margin-top: 13px; }+ .camera-actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); flex: 1 1 100%; }+ .camera-actions button { padding-inline: 8px; }+ .curtain-slider { flex-basis: 100%; max-width: none; }+ .curtain-actions { width: 100%; }+ .curtain-actions button { flex: 1 1 80px; padding-inline: 8px; }+ .finish-row { gap: 12px; }+ .finish-swatches { order: 3; width: 100%; }+ .finish-swatch { flex: 1 1 80px; justify-content: center; gap: 6px; font-size: 11px; padding-inline: 6px; }+ .swatch-chip { width: 19px; height: 19px; flex-basis: 19px; }+ .viewer-message { padding: 14px; gap: 8px; }+ #message-detail { font-size: 11px; max-height: 5em; overflow: auto; }+ .source-panel figcaption { font-size: 9px; padding: 5px 8px; }+ .story { display: block; }+ .story h2 br { display: none; }+ h2 { font-size: 30px; }+ .source-figure { margin-top: 20px; max-width: 460px; }+ .story > p { margin-top: 16px; }+ .representation, .downloads { margin-top: 24px; }+ .page-footer { margin-top: 32px; }+}++@media (prefers-reduced-motion: reduce) {+ html { scroll-behavior: auto; }+}diff --git a/runtime/viewer/src/interior.js b/runtime/viewer/src/interior.jsnew file mode 100644index 0000000..adb47b6--- /dev/null+++ b/runtime/viewer/src/interior.js@@ -0,0 +1,709 @@+import './interior.css';+import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { EXRLoader } from 'three/addons/loaders/EXRLoader.js';+import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';+import { createCurtainInteraction } from './interior-curtains.js';+import { createInteriorNavigation } from './interior-navigation.js';+import { validateManifest, sourceLabel, usesPolyHavenAPI } from './interior-manifest.js';+import { prepareLightmaps } from './interior-lightmaps.js';++const ui = Object.fromEntries([+ 'viewport', 'canvas-host', 'source-panel', 'source-view', 'source-thumbnail', 'source-link',+ 'mode-3d', 'mode-source', 'view-label', 'viewer-message', 'message-title', 'message-detail',+ 'load-status', 'load-progress', 'retry-load', 'finish-swatches', 'finish-label', 'wireframe',+ 'reset', 'download-glb', 'download-blend',+ 'curtain-amount', 'curtain-percent', 'curtain-open', 'curtain-close', 'curtain-wind',+ 'scene-title', 'camera-actions', 'finish-controls', 'curtain-controls', 'resource-credit',+ 'source-caption', 'thumbnail-caption', 'interaction-hint', 'representation-title', 'representation-detail',+].map(id => [id, document.getElementById(id)]));+let viewButtons = [];+const state = { status: 'loading', error: null, mode: '3d', view: 'source', finish: null, wireframe: false, frames: 0 };+const offset = new THREE.Vector3();+const orbit = new THREE.Spherical();+const number = new Intl.NumberFormat('en-US');+const iblDiffuseLine = 'iblIrradiance += getIBLIrradiance( geometryNormal );';+const lightsInclude = '#include <lights_fragment_maps>';+let session = null;+let loading = false;+let renderRequest = 0;+let applyingPose = false;+let stopped = false;++function cameraSnapshot() {+ if (!session?.camera) return null;+ const { camera, controls } = session;+ return { position: camera.position.toArray(), quaternion: camera.quaternion.toArray(),+ target: controls.target.toArray(), fov: camera.fov, aspect: camera.aspect,+ near: camera.near, far: camera.far, view: state.view };+}++function textureSnapshot(texture) {+ if (!texture) return null;+ return { uuid: texture.uuid, channel: texture.channel, colorSpace: texture.colorSpace,+ flipY: texture.flipY, width: texture.image?.width, height: texture.image?.height };+}++function materialSnapshot(material) {+ const textures = {};+ for (const [name, value] of Object.entries(material)) {+ if (value?.isTexture) textures[name] = textureSnapshot(value);+ }+ return { uuid: material.uuid, name: material.name, type: material.type,+ color: material.color?.toArray(), roughness: material.roughness, metalness: material.metalness,+ transparent: material.transparent, opacity: material.opacity, alphaTest: material.alphaTest,+ transmission: material.transmission ?? 0, emissive: material.emissive?.toArray(),+ emissiveIntensity: material.emissiveIntensity,+ side: material.side, depthWrite: material.depthWrite, lightMapIntensity: material.lightMapIntensity,+ textures };+}++function inventorySnapshot() {+ return session?.entries.map(({ mesh, pbr, diagnostic }) => ({+ component: mesh.userData.component, uuid: mesh.uuid, name: mesh.name,+ geometryUuid: mesh.geometry.uuid, finish: mesh.userData.finish ?? null,+ currentFinish: session.manifest.finishTarget && mesh.userData.finish === session.manifest.finishTarget ? state.finish : null,+ curtain: mesh.userData.curtain_id ?? null, curtainPart: mesh.userData.curtain_part ?? null,+ lightmap: mesh.userData.lightmap ?? null,+ attributes: Object.fromEntries(Object.entries(mesh.geometry.attributes).map(([name, attribute]) =>+ [name, { count: attribute.count, itemSize: attribute.itemSize, version: attribute.version }])),+ indexCount: mesh.geometry.index?.count ?? null,+ materials: (Array.isArray(pbr) ? pbr : [pbr]).map(materialSnapshot),+ activeMaterialUuids: (Array.isArray(mesh.material) ? mesh.material : [mesh.material]).map(material => material.uuid),+ diagnosticMaterialUuids: (Array.isArray(diagnostic) ? diagnostic : [diagnostic]).map(material => material.uuid),+ })) ?? [];+}++Object.defineProperty(window, 'interiorStudy', {+ value: Object.freeze({+ get status() { return state.status; },+ get error() { return state.error; },+ get camera() { return cameraSnapshot(); },+ get frames() { return state.frames; },+ get stats() { return session?.stats ? structuredClone(session.stats) : null; },+ get inventory() { return inventorySnapshot(); },+ get mode() { return state.mode; },+ get finish() { return state.finish; },+ get wireframe() { return state.wireframe; },+ get curtains() { return session?.curtains?.snapshot() ?? null; },+ get navigation() { return session?.navigation?.snapshot() ?? null; },+ get lighting() { return session?.renderer ? { model: session.manifest.lighting.model,+ exposure: session.renderer.toneMappingExposure, sunIntensity: session.sun?.intensity ?? null,+ shadowMapSize: session.sun?.shadow.mapSize.toArray() ?? null } : null; },+ setView, setFinish, setMode, setWireframe, setCurtainClosure, setCurtainWind, reset,+ }),+});++function syncCurtainControls() {+ const curtain = session?.curtains;+ const percent = Math.round((curtain?.targetClosure ?? 0) * 100);+ if (ui['curtain-amount'].value !== String(percent)) ui['curtain-amount'].value = percent;+ ui['curtain-percent'].textContent = `${percent}%`;+ ui['curtain-amount'].setAttribute('aria-valuetext', `${ui['curtain-amount'].value}% coverage`);+ ui['curtain-wind'].setAttribute('aria-pressed', String(curtain?.wind ?? false));+ ui['curtain-wind'].disabled = !curtain?.count || state.status !== 'ready' || state.mode !== '3d' || !!curtain?.reducedMotion;+ ui['curtain-wind'].title = curtain?.reducedMotion ? 'Wind disabled by your reduced-motion setting.' : 'Toggle the gentle breeze that animates the fabric.';+}++function syncControls() {+ const ready = state.status === 'ready';+ const interactive = ready && state.mode === '3d';+ for (const mode of ['3d', 'source']) {+ ui[`mode-${mode}`].disabled = !ready;+ ui[`mode-${mode}`].setAttribute('aria-pressed', String(state.mode === mode));+ }+ for (const button of viewButtons) {+ button.disabled = !interactive;+ button.setAttribute('aria-pressed', String(state.view === button.dataset.view));+ }+ for (const button of ui['finish-swatches'].children) {+ button.disabled = !interactive;+ button.setAttribute('aria-pressed', String(state.finish === button.dataset.finish));+ }+ ui.wireframe.disabled = !interactive;+ ui.wireframe.setAttribute('aria-pressed', String(state.wireframe));+ ui.reset.disabled = !ready;+ for (const id of ['curtain-amount', 'curtain-open', 'curtain-close', 'curtain-wind']) ui[id].disabled = !interactive || !session?.curtains?.count;+ ui['curtain-controls'].hidden = !session?.curtains?.count;+ ui['finish-controls'].hidden = !session?.manifest.variants.length || !session?.finishes.size;+ syncCurtainControls();+ ui['canvas-host'].hidden = state.mode !== '3d';+ ui['source-panel'].hidden = state.mode !== 'source';+ ui['viewer-message'].hidden = ready;+ ui['load-progress'].hidden = state.status !== 'loading';+ ui['retry-load'].hidden = state.status !== 'error';+ ui.viewport.setAttribute('aria-busy', String(state.status === 'loading'));+ ui['retry-load'].disabled = loading;+ ui['load-status'].dataset.state = state.status;+ ui['view-label'].textContent = state.mode === 'source' ? sourceLabel(session.manifest)+ : state.wireframe ? '3D · geometry wireframe'+ : session?.curtains?.count ? '3D · interactive curtains' : '3D · authored interior';+ for (const [id, field] of [['download-glb', 'portableModel'], ['download-blend', 'blender']]) {+ const link = ui[id];+ link.setAttribute('aria-disabled', String(!ready));+ link.tabIndex = ready ? 0 : -1;+ if (ready) link.href = session.manifest[field];+ else link.removeAttribute('href');+ }+ if (session?.controls) {+ session.curtains?.setEnabled(interactive);+ session.controls.enabled = interactive && !session.curtains?.grabbing;+ session.renderer.domElement.tabIndex = interactive ? 0 : -1;+ session.renderer.domElement.setAttribute('aria-disabled', String(!interactive));+ }+}++function fail(error) {+ state.status = 'error';+ state.error = error instanceof Error ? error.message : String(error);+ session?.curtains?.setEnabled(false);+ cancelAnimationFrame(renderRequest);+ renderRequest = 0;+ ui['message-title'].textContent = 'Could not open the room';+ ui['message-detail'].textContent = state.error;+ ui['load-status'].textContent = 'Scene load did not finish. Check your connection, then choose “Retry load”.';+ syncControls();+}++function requestRender() {+ if (renderRequest || state.status !== 'ready' || state.mode !== '3d' || document.hidden) return;+ renderRequest = requestAnimationFrame(time => {+ renderRequest = 0;+ if (!session || state.status !== 'ready' || state.mode !== '3d' || document.hidden) return;+ try {+ const previous = session.lastRenderTime;+ session.lastRenderTime = time;+ const moving = session.curtains?.update(previous === null ? 0 : (time-previous)/1000, time/1000);+ syncCurtainControls();+ session.renderer.render(session.scene, session.camera);+ if (session.shaderError) throw session.shaderError;+ state.frames++;+ if (moving) requestRender();+ else session.lastRenderTime = null;+ } catch (error) { fail(error); }+ });+}++function resize() {+ if (!session?.camera) return;+ const width = ui.viewport.clientWidth;+ const height = ui.viewport.clientHeight;+ if (!width || !height) return;+ session.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ session.renderer.setSize(width, height, false);+ session.camera.aspect = width / height;+ session.camera.updateProjectionMatrix();+ requestRender();+}++function applyView(name) {+ const { manifest, camera, controls } = session;+ const pose = name === 'source' ? manifest.camera : manifest.views[name];+ applyingPose = true;+ camera.position.fromArray(pose.position);+ camera.fov = pose.fov ?? manifest.camera.fov;+ camera.updateProjectionMatrix();+ controls.target.fromArray(pose.target);+ camera.lookAt(controls.target);+ controls.update();+ applyingPose = false;+ state.view = name;+}++function setView(name) {+ if (state.status !== 'ready' || state.mode !== '3d') return false;+ if (name !== 'source' && !Object.hasOwn(session.manifest.views, name)) throw new Error(`Unknown view: ${name}`);+ if (session.curtains?.grabbing) session.curtains.setEnabled(false);+ applyView(name);+ syncControls();+ requestRender();+ return true;+}++function setFinish(id) {+ if (state.status !== 'ready' || state.mode !== '3d') return false;+ const variant = session.manifest.variants.find(item => item.id === id);+ if (!variant) throw new Error(`Unknown fabric finish: ${id}`);+ for (const [material, original] of session.finishes) {+ const base = id === session.manifest.variants[0].id;+ if (base) material.color.copy(original.color);+ else material.color.copy(original.color).multiply(session.finishTints.get(id));+ material.roughness = base ? original.roughness : variant.roughness ?? original.roughness;+ }+ state.finish = id;+ ui['finish-label'].textContent = variant.label;+ syncControls();+ requestRender();+ return true;+}++function setMode(mode) {+ if (!['3d', 'source'].includes(mode)) throw new Error(`Unknown mode: ${mode}`);+ if (state.status !== 'ready') return false;+ state.mode = mode;+ syncControls();+ if (mode === '3d') resize();+ return true;+}++function setWireframe(enabled) {+ if (typeof enabled !== 'boolean') throw new TypeError('Wireframe requires a boolean.');+ if (state.status !== 'ready' || state.mode !== '3d') return false;+ state.wireframe = enabled;+ for (const { mesh, pbr, diagnostic } of session.entries) mesh.material = enabled ? diagnostic : pbr;+ syncControls();+ requestRender();+ return true;+}++function setCurtainClosure(value) {+ if (state.status !== 'ready' || state.mode !== '3d' || !session.curtains?.count) return false;+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new RangeError('Curtain coverage must be between 0 and 1.');+ session.curtains.setClosure(value);+ requestRender();+ return true;+}++function setCurtainWind(enabled) {+ if (state.status !== 'ready' || state.mode !== '3d' || !session.curtains?.count) return false;+ if (typeof enabled !== 'boolean') throw new TypeError('Gentle breeze requires a boolean.');+ const actual = session.curtains.setWind(enabled);+ syncCurtainControls();+ requestRender();+ return actual === enabled;+}++function reset() {+ if (state.status !== 'ready') return false;+ setMode('3d');+ session.curtains?.reset();+ setWireframe(false);+ if (session.manifest.variants.length) setFinish(session.manifest.variants[0].id);+ setView('source');+ return true;+}++function cameraKeys(event) {+ if (!session?.controls.enabled || !['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', '+', '=', '-', '_', 'Home'].includes(event.key)) return;+ event.preventDefault();+ if (event.key === 'Home') { setView('source'); return; }+ const { camera, controls } = session;+ orbit.setFromVector3(offset.copy(camera.position).sub(controls.target));+ if (event.key === 'ArrowLeft') orbit.theta -= 0.045;+ if (event.key === 'ArrowRight') orbit.theta += 0.045;+ if (event.key === 'ArrowUp') orbit.phi -= 0.035;+ if (event.key === 'ArrowDown') orbit.phi += 0.035;+ if (event.key === '+' || event.key === '=') orbit.radius *= 0.9;+ if (event.key === '-' || event.key === '_') orbit.radius *= 1.1;+ orbit.phi = THREE.MathUtils.clamp(orbit.phi, controls.minPolarAngle, controls.maxPolarAngle);+ orbit.radius = THREE.MathUtils.clamp(orbit.radius, controls.minDistance, controls.maxDistance);+ camera.position.copy(controls.target).add(offset.setFromSpherical(orbit));+ controls.update();+}+++function configureSceneContent(manifest) {+ document.title = `${manifest.title} — Interior study`;+ ui['scene-title'].textContent = manifest.title;+ ui.viewport.style.setProperty('--source-aspect', `${manifest.sourceImageSize[0]} / ${manifest.sourceImageSize[1]}`);+ for (const id of ['source-view', 'source-thumbnail']) {+ ui[id].width = manifest.sourceImageSize[0];+ ui[id].height = manifest.sourceImageSize[1];+ ui[id].alt = `${sourceLabel(manifest)} for ${manifest.title}`;+ }+ ui['source-caption'].textContent = `${sourceLabel(manifest)} · not a viewer render`;+ ui['thumbnail-caption'].textContent = `${sourceLabel(manifest)}. Open the image to compare details.`;+ ui['resource-credit'].hidden = !usesPolyHavenAPI(manifest);+ viewButtons = [['source', { label: 'Source view' }], ...Object.entries(manifest.views)].map(([name, pose]) => {+ const button = document.createElement('button');+ button.type = 'button';+ button.dataset.view = name;+ button.textContent = pose.label || name;+ button.disabled = true;+ button.setAttribute('aria-pressed', String(name === 'source'));+ button.addEventListener('click', () => setView(name));+ return button;+ });+ ui['camera-actions'].replaceChildren(...viewButtons);+ state.finish = manifest.variants[0]?.id ?? null;+ createSwatches(manifest);+}++function configureInteractionContent(current) {+ const cloth = current.curtains.count > 0;+ const cameraHint = 'Scroll or pinch to zoom, right-drag to pan inside the room. Keyboard: Tab into the 3D frame, arrow keys to rotate, + / − to zoom, Home returns to the source view.';+ ui['interaction-hint'].textContent = cloth+ ? `Drag the fabric to open or close the curtains; drag elsewhere to orbit the camera. ${cameraHint} Adjust the curtains with the Coverage slider and buttons; turn off Gentle breeze to settle the cloth.`+ : `Drag to orbit the camera. ${cameraHint}`;+ current.renderer.domElement.setAttribute('aria-label', `${current.manifest.title}. Interactive 3D interior. ${ui['interaction-hint'].textContent}`);+ ui['representation-title'].textContent = cloth && current.sun ? 'Sunlight follows the curtain' : 'Baked light, editable geometry';+ ui['representation-detail'].textContent = !current.sun+ ? 'Lighting and reflections use the authored static bake and reflection probe. This scene has no runtime sun or dynamic GI; changing materials or cloth does not rebake lighting. The camera stays inside the declared room bounds.'+ : cloth+ ? 'Direct sunlight and cast shadows update with the curtain shape. Indirect bounce and reflections retain the authored open-curtain bake; this is not dynamic GI. The camera stays inside the declared room bounds.'+ : 'Direct sunlight and shadows are rendered in real time. Indirect bounce and reflections use the authored static bake; material changes do not rebake them. The camera stays inside the declared room bounds.';+}++function createSwatches(manifest) {+ ui['finish-swatches'].replaceChildren();+ for (const variant of manifest.variants) {+ const button = document.createElement('button');+ button.type = 'button';+ button.className = 'finish-swatch';+ button.dataset.finish = variant.id;+ button.disabled = true;+ button.setAttribute('aria-pressed', String(variant.id === state.finish));+ const chip = document.createElement('span');+ chip.className = 'swatch-chip';+ chip.style.setProperty('--swatch-color', variant.color);+ chip.setAttribute('aria-hidden', 'true');+ button.append(chip, document.createTextNode(variant.label));+ button.addEventListener('click', () => setFinish(variant.id));+ ui['finish-swatches'].append(button);+ }+ ui['finish-label'].textContent = manifest.variants[0]?.label ?? '';+}++function collectResources(root, current) {+ root.traverse(object => {+ if (!object.isMesh) return;+ current.geometries.add(object.geometry);+ for (const material of Array.isArray(object.material) ? object.material : [object.material]) {+ current.materials.add(material);+ for (const value of Object.values(material)) if (value?.isTexture) current.textures.add(value);+ }+ });+}++function bindMaterials(root, current) {+ const chunk = THREE.ShaderChunk.lights_fragment_maps;+ if (typeof chunk !== 'string' || chunk.split(iblDiffuseLine).length !== 2) throw new Error('Three.js shader does not match the bake version: missing the IBL diffuse line.');+ const bakedChunk = chunk.replace(iblDiffuseLine, '// Diffuse is supplied by the Blender lightmap only.');+ const cache = new Map();+ const wireCache = new Map();+ const clothTextures = new Map();+ const clothAnisotropy = Math.max(1, Math.min(8, current.renderer.capabilities.getMaxAnisotropy()));+ let triangles = 0;+ root.traverse(mesh => {+ if (mesh.isLight) throw new Error('Runtime GLB must not contain lights outside the manifest sun configuration.');+ if (!mesh.isMesh) return;+ // glTF node extras live on a Group when an object has multiple material primitives.+ // Carry those authored semantics to the rendered primitive, never infer a missing atlas.+ for (const key of ['component', 'lightmap', 'finish', 'curtain_id', 'curtain_part']) {+ if (mesh.userData[key] !== undefined) continue;+ let owner = mesh.parent;+ while (owner && owner !== root && owner.userData[key] === undefined) owner = owner.parent;+ if (owner?.userData[key] !== undefined) mesh.userData[key] = owner.userData[key];+ }+ const component = mesh.userData.component;+ const atlasId = mesh.userData.lightmap;+ const atlas = current.atlases.get(atlasId);+ if (!component) throw new Error(`Mesh ${mesh.name || mesh.uuid} is missing a component.`);+ if (atlasId !== undefined && !atlas) throw new Error(`Mesh ${component} has an invalid lightmap.`);+ const { position, uv, uv1 } = mesh.geometry.attributes;+ if (!position || !uv || uv.count !== position.count || uv.itemSize !== 2) throw new Error(`Mesh ${component} is missing a full UV0 channel.`);+ if (atlas && (!uv1 || uv1.count !== position.count || uv1.itemSize !== 2)) throw new Error(`Mesh ${component} is missing a full UV1 channel for the atlas.`);+ const configurable = current.manifest.variants.length > 0 && current.manifest.finishTarget && mesh.userData.finish === current.manifest.finishTarget;+ const dynamic = mesh.userData.curtain_id !== undefined;+ function bind(source) {+ if (!source.isMeshStandardMaterial) throw new Error(`Material ${source.name} of ${component} is not a standard PBR material.`);+ if (dynamic) {+ const key = `${source.uuid}:cloth:${configurable}`;+ if (cache.has(key)) return cache.get(key);+ const material = source.clone();+ material.lightMap = null;+ material.side = material.shadowSide = THREE.DoubleSide;+ // Keep the scan's yarn detail at grazing angles without changing sofa samplers.+ for (const key of ['map', 'normalMap', 'roughnessMap', 'metalnessMap']) {+ const sourceTexture = material[key];+ if (!sourceTexture) continue;+ if (!clothTextures.has(sourceTexture)) {+ const texture = sourceTexture.clone();+ texture.anisotropy = clothAnisotropy;+ texture.needsUpdate = true;+ current.textures.add(texture);+ clothTextures.set(sourceTexture, texture);+ }+ material[key] = clothTextures.get(sourceTexture);+ }+ current.materials.add(material);+ if (configurable) current.finishes.set(material, { color: material.color.clone(), roughness: material.roughness });+ cache.set(key, material);+ return material;+ }+ // Glass and the emissive bulb intentionally have no baked atlas.+ // Leave their native physical/emissive material and environment response intact.+ if (!atlas && !configurable) {+ cache.set(`${source.uuid}:unbaked`, source);+ return source;+ }+ // Partition material identity by finish ownership as well as atlas.+ const key = `${source.uuid}:${atlas?.id ?? 'unbaked'}:${configurable}`;+ if (cache.has(key)) return cache.get(key);+ const material = source.clone();+ current.materials.add(material);+ if (atlas) {+ material.lightMap = atlas.texture;+ // Exporter records PI irradiance compensation in atlas.intensity.+ material.lightMapIntensity = atlas.intensity;+ material.onBeforeCompile = shader => {+ if (!shader.fragmentShader.includes(lightsInclude)) throw new Error('PBR shader is missing lights_fragment_maps for the diffuse bake.');+ shader.fragmentShader = shader.fragmentShader.replace(lightsInclude, bakedChunk);+ };+ material.customProgramCacheKey = () => 'interior-baked-diffuse-r180';+ }+ // Cloning retains authored alpha blending, alpha test, side and depth settings (including foliage).+ cache.set(key, material);+ if (configurable) current.finishes.set(material, { color: material.color.clone(), roughness: material.roughness });+ return material;+ }+ function diagnostic(material) {+ if (!wireCache.has(material.uuid)) {+ const wire = new THREE.MeshBasicMaterial({ color: '#d8d2c6', wireframe: true, side: material.side });+ current.materials.add(wire);+ wireCache.set(material.uuid, wire);+ }+ return wireCache.get(material.uuid);+ }+ const pbr = Array.isArray(mesh.material) ? mesh.material.map(bind) : bind(mesh.material);+ const wire = Array.isArray(pbr) ? pbr.map(diagnostic) : diagnostic(pbr);+ mesh.material = pbr;+ const materials = Array.isArray(pbr) ? pbr : [pbr];+ mesh.castShadow = !materials.some(material => (material.transmission ?? 0) > 0.5);+ mesh.receiveShadow = true;+ current.entries.push({ mesh, pbr, diagnostic: wire });+ triangles += (mesh.geometry.index?.count ?? position.count) / 3;+ });+ if (!current.entries.length) throw new Error('Scene has no meshes.');+ if (current.manifest.variants.length && !current.finishes.size) throw new Error(`Finish variants require an explicit finishTarget matching actual mesh finish tags: ${current.manifest.finishTarget ?? '(missing)'}`);+ current.stats = { meshes: current.entries.length, components: new Set(current.entries.map(entry => entry.mesh.userData.component)).size,+ triangles, geometries: current.geometries.size, pbrMaterials: cache.size, lightmaps: current.atlases.size,+ environmentTextureUuid: current.environmentTarget.texture.uuid, manifest: current.manifest.stats ?? {} };+}++function disposeSession() {+ cancelAnimationFrame(renderRequest);+ renderRequest = 0;+ if (!session) return;+ session.curtains?.dispose();+ session.navigation?.dispose();+ session.sun?.dispose();+ session.controls?.dispose();+ session.environmentTarget?.dispose();+ for (const geometry of session.geometries) geometry.dispose();+ for (const material of session.materials) material.dispose();+ const closedImages = new Set();+ for (const texture of session.textures) {+ texture.dispose();+ if (texture.image?.close && !closedImages.has(texture.image)) {+ texture.image.close();+ closedImages.add(texture.image);+ }+ }+ session.renderer?.dispose();+ session.renderer?.domElement.remove();+ session = null;+}++async function start() {+ if (loading || stopped) return;+ loading = true;+ disposeSession();+ Object.assign(state, { status: 'loading', error: null, mode: '3d', view: 'source', finish: null, wireframe: false, frames: 0 });+ ui['message-title'].textContent = 'Opening room';+ ui['message-detail'].textContent = 'Reading model, materials and lightmap atlases.';+ ui['load-status'].textContent = 'Reading scene manifest…';+ ui['load-progress'].removeAttribute('value');+ syncControls();+ try {+ const response = await fetch('/assets/interior/manifest.json', { cache: 'no-cache' });+ if (!response.ok) throw new Error(`Could not load manifest (${response.status}).`);+ const manifest = await response.json();+ if (stopped) return;+ validateManifest(manifest);+ configureSceneContent(manifest);+ const current = { manifest, geometries: new Set(), materials: new Set(), textures: new Set(),+ atlases: new Map(), finishes: new Map(), finishTints: new Map(), entries: [], shaderError: null, lastRenderTime: null };+ session = current;+ // The first variant describes the authored base, not an extra tint.+ const base = new THREE.Color(manifest.variants[0]?.color ?? '#ffffff');+ for (const variant of manifest.variants.slice(1)) {+ const tint = new THREE.Color(variant.color);+ tint.setRGB(tint.r / base.r, tint.g / base.g, tint.b / base.b);+ current.finishTints.set(variant.id, tint);+ }+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });+ current.renderer = renderer;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.NeutralToneMapping;+ renderer.toneMappingExposure = manifest.exposure;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;+ renderer.setClearColor('#282722');+ renderer.debug.onShaderError = () => { current.shaderError = new Error('Could not compile the PBR/lightmap shader on this device.'); };+ const canvas = renderer.domElement;+ canvas.tabIndex = -1;+ canvas.setAttribute('role', 'img');+ canvas.setAttribute('aria-label', `${manifest.title}. Interactive 3D interior.`);+ canvas.setAttribute('aria-describedby', 'interaction-hint');+ canvas.addEventListener('keydown', cameraKeys);+ canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); fail(new Error('Lost the WebGL context. Choose Retry load to rebuild the viewer.')); });+ ui['canvas-host'].append(canvas);+ const scene = new THREE.Scene();+ current.scene = scene;+ const roomSize = new THREE.Vector3().fromArray(manifest.roomBounds.max).sub(new THREE.Vector3().fromArray(manifest.roomBounds.min)).length();+ current.camera = new THREE.PerspectiveCamera(manifest.camera.fov, manifest.sourceImageSize[0] / manifest.sourceImageSize[1], 0.03, Math.max(250, roomSize * 4));+ const controls = new OrbitControls(current.camera, canvas);+ current.controls = controls;+ controls.enabled = false;+ controls.enableDamping = false;+ controls.enablePan = true;+ controls.rotateSpeed = 0.55;+ controls.zoomSpeed = 0.7;+ current.navigation = createInteriorNavigation(current.camera, controls, manifest.roomBounds);+ controls.addEventListener('change', () => {+ if (!applyingPose && state.status === 'ready') { state.view = null; syncControls(); }+ requestRender();+ });+ applyView('source');+ resize();+ let completed = 0;+ const total = manifest.lightmaps.length + 3 + (manifest.background != null ? 1 : 0);+ ui['load-progress'].max = total;+ ui['load-progress'].value = 0;+ const tracked = async (promise, label) => {+ try {+ const value = await promise;+ completed++;+ if (state.status === 'loading') {+ ui['load-progress'].value = completed;+ ui['load-status'].textContent = `Loaded ${completed}/${total} asset groups · ${label}`;+ }+ return value;+ } catch (error) { throw new Error(`Could not load ${label}: ${error.message}`); }+ };+ for (const id of ['source-view', 'source-thumbnail']) ui[id].src = manifest.sourceImage;+ ui['source-link'].href = manifest.sourceImage;+ const exrLoader = new EXRLoader();+ const tasks = [+ tracked(new GLTFLoader().loadAsync(manifest.model).then(async gltf => {+ current.root = gltf.scene;+ collectResources(gltf.scene, current);+ // GLTFLoader deliberately resolves failed texture loads as null. Never call that ready.+ const textures = await gltf.parser.getDependencies('texture');+ for (const texture of textures) if (texture) current.textures.add(texture);+ if (textures.some(texture => !texture)) throw new Error('One or more textures inside the GLB are missing.');+ }), 'model and PBR textures'),+ tracked(exrLoader.loadAsync(manifest.environment).then(texture => {+ texture.colorSpace = THREE.NoColorSpace;+ texture.mapping = THREE.EquirectangularReflectionMapping;+ current.probe = texture;+ current.textures.add(texture);+ }), 'room reflection probe'),+ tracked(Promise.all([ui['source-view'].decode(), ui['source-thumbnail'].decode()]).then(() => {+ const image = ui['source-view'];+ if (image.naturalWidth !== manifest.sourceImageSize[0] || image.naturalHeight !== manifest.sourceImageSize[1]) {+ throw new Error('sourceImageSize does not match the decoded source image; correct the scene specification and re-export.');+ }+ }), 'source reference image'),+ ...manifest.lightmaps.map(atlas => tracked(exrLoader.loadAsync(atlas.url).then(texture => {+ current.textures.add(texture);+ current.atlases.set(atlas.id, { ...atlas, texture });+ }), `atlas ${atlas.id}`)),+ ];+ if (manifest.background != null) {+ const backgroundLoader = /\.exr$/i.test(manifest.background) ? exrLoader : new HDRLoader();+ tasks.push(tracked(backgroundLoader.loadAsync(manifest.background).then(texture => {+ texture.mapping = THREE.EquirectangularReflectionMapping;+ texture.colorSpace = THREE.NoColorSpace;+ current.background = texture;+ current.textures.add(texture);+ scene.background = texture;+ scene.backgroundIntensity = manifest.backgroundIntensity;+ }), 'scene background'));+ }+ // Settle every load before disposal/retry; a late texture must not leak into another session.+ const results = await Promise.allSettled(tasks);+ if (stopped) throw new Error('Viewer was disposed while assets were loading.');+ const rejected = results.find(result => result.status === 'rejected');+ if (rejected) throw rejected.reason;+ if (state.error) throw new Error(state.error);+ prepareLightmaps(current.atlases.values());+ ui['load-status'].textContent = 'Preparing reflection probe and compiling materials…';+ const pmrem = new THREE.PMREMGenerator(renderer);+ try { current.environmentTarget = pmrem.fromEquirectangular(current.probe); }+ finally { pmrem.dispose(); current.probe.dispose(); current.textures.delete(current.probe); }+ scene.environment = current.environmentTarget.texture;+ bindMaterials(current.root, current);+ scene.add(current.root);+ const sunSpec = manifest.lighting.sun;+ if (sunSpec) {+ const sun = new THREE.DirectionalLight();+ sun.color.setRGB(...sunSpec.color);+ sun.intensity = sunSpec.intensity;+ // Fit the shadow volume to the authored room, not Oak/Linen coordinates.+ const roomCenter = new THREE.Vector3().fromArray(manifest.roomBounds.min).add(new THREE.Vector3().fromArray(manifest.roomBounds.max)).multiplyScalar(0.5);+ const shadowExtent = roomSize * 0.6;+ sun.target.position.copy(roomCenter);+ sun.position.fromArray(sunSpec.position).sub(new THREE.Vector3().fromArray(sunSpec.target)).normalize().multiplyScalar(roomSize * 1.5).add(roomCenter);+ sun.castShadow = true;+ sun.shadow.mapSize.setScalar(sunSpec.shadowMapSize);+ sun.shadow.camera.near = 0.1;+ sun.shadow.camera.far = roomSize * 3;+ sun.shadow.camera.left = sun.shadow.camera.bottom = -shadowExtent;+ sun.shadow.camera.right = sun.shadow.camera.top = shadowExtent;+ sun.shadow.bias = -0.00008;+ sun.shadow.normalBias = 0.015;+ sun.shadow.camera.updateProjectionMatrix();+ current.sun = sun;+ scene.add(sun, sun.target);+ }+ current.curtains = createCurtainInteraction({ root: current.root, camera: current.camera, roomBounds: manifest.roomBounds,+ canvas, controls, onChange: requestRender, isInteractive: () => state.status === 'ready' && state.mode === '3d' });+ configureInteractionContent(current);+ await renderer.compileAsync(scene, current.camera);+ if (stopped) throw new Error('Viewer was disposed while shaders were compiling.');+ if (state.error) throw new Error(state.error);+ if (current.shaderError) throw current.shaderError;+ renderer.render(scene, current.camera);+ if (current.shaderError) throw current.shaderError;+ state.frames++;+ state.status = 'ready';+ ui['load-status'].textContent = `${number.format(current.stats.meshes)} meshes · ${number.format(current.stats.triangles)} triangles · all textures and atlases loaded.`;+ syncControls();+ requestRender();+ } catch (error) {+ disposeSession();+ if (!stopped) fail(error);+ } finally {+ loading = false;+ if (stopped) disposeSession();+ else syncControls();+ }+}++ui['mode-3d'].addEventListener('click', () => setMode('3d'));+ui['mode-source'].addEventListener('click', () => setMode('source'));+ui.wireframe.addEventListener('click', () => setWireframe(!state.wireframe));+ui.reset.addEventListener('click', reset);+ui['retry-load'].addEventListener('click', start);+ui['curtain-amount'].addEventListener('input', () => setCurtainClosure(Number(ui['curtain-amount'].value)/100));+ui['curtain-open'].addEventListener('click', () => setCurtainClosure(0));+ui['curtain-close'].addEventListener('click', () => setCurtainClosure(1));+ui['curtain-wind'].addEventListener('click', () => setCurtainWind(!session.curtains.wind));+const resizeObserver = new ResizeObserver(resize);+resizeObserver.observe(ui.viewport);+window.addEventListener('resize', resize);+document.addEventListener('visibilitychange', requestRender);+window.addEventListener('pagehide', event => {+ if (!event.persisted) {+ stopped = true;+ cancelAnimationFrame(renderRequest);+ resizeObserver.disconnect();+ session?.curtains?.setEnabled(false);+ // In-flight loaders retain ownership until all settle, then finally disposes.+ if (!loading) disposeSession();+ }+});+start();diff --git a/runtime/viewer/vite.config.js b/runtime/viewer/vite.config.jsnew file mode 100644index 0000000..98c26b4--- /dev/null+++ b/runtime/viewer/vite.config.js@@ -0,0 +1,5 @@+import { defineConfig } from 'vite';++export default defineConfig({+ appType: 'mpa',+});diff --git a/scripts/package_plugin.py b/scripts/package_plugin.pynew file mode 100755index 0000000..c2e0b39--- /dev/null+++ b/scripts/package_plugin.py@@ -0,0 +1,81 @@+#!/usr/bin/env python3+"""Build a deterministic installable source ZIP, excluding machine-local state."""+import argparse+import hashlib+import json+from pathlib import Path+import re+import sys+import zipfile++ROOT_FILES = ("plugin.json", "steps.json", "gates.json", "SKILL.md", "README.md", "LICENSE", "SECURITY.md", "CHANGELOG.md", "VERIFICATION.md", "requirements.txt", "requirements-authoring.txt", "requirements-surfaces.txt", ".gitignore")+TREES = ("tools", "authoring", "resources_lib", "runtime", "recipes", "reference", "examples", "tests", "scripts", ".github")+++def package(source, output):+ for name in ROOT_FILES:+ if not (source / name).is_file():+ raise ValueError("missing release file: " + name)+ manifest = json.loads((source / "plugin.json").read_text(encoding="utf-8"))+ version = manifest["version"]+ if manifest.get("name") != "interior" or not re.fullmatch(r"\d+\.\d+\.\d+", version):+ raise ValueError("expected interior manifest with a stable semver version")+ files = [source / name for name in ROOT_FILES]+ for name in TREES:+ tree = source / name+ if tree.is_symlink():+ raise ValueError("release trees cannot be symlinks: " + name)+ for path in tree.rglob("*"):+ rel = path.relative_to(source)+ if (path.name == "_img2_local.py" or path.suffix in (".pyc", ".pyo")+ or any(part in ("__pycache__", "node_modules", "dist", ".img2", ".venv", ".venv-blender", ".venv-images") for part in rel.parts)):+ continue+ if ((path.name.startswith(".env") and path.name != ".env.example")+ or path.suffix.lower() in (".pem", ".key")):+ continue+ if path.is_symlink():+ raise ValueError("release source cannot contain symlinks: " + str(rel))+ if path.is_file():+ files.append(path)+ for path in files:+ if path.is_symlink() or not path.resolve().is_relative_to(source):+ raise ValueError("release file escapes source: " + str(path))+ for path in [source / "SKILL.md", *(source / "reference").glob("*.md")]:+ if len(path.read_text(encoding="utf-8").splitlines()) >= 150:+ raise ValueError("progressive-disclosure document must be under 150 lines: " + str(path))+ output.mkdir(parents=True, exist_ok=True)+ archive = output / ("img2interior-" + version + ".zip")+ temporary = archive.with_suffix(".zip.tmp")+ try:+ with zipfile.ZipFile(temporary, "w") as bundle:+ for path in sorted(files, key=lambda p: p.relative_to(source).as_posix()):+ relative = "img2interior/" + path.relative_to(source).as_posix()+ info = zipfile.ZipInfo(relative, date_time=(1980, 1, 1, 0, 0, 0))+ info.create_system = 3+ info.external_attr = 0o100644 << 16+ bundle.writestr(info, path.read_bytes(), compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)+ temporary.replace(archive)+ finally:+ temporary.unlink(missing_ok=True)+ digest = hashlib.sha256(archive.read_bytes()).hexdigest()+ checksums = output / "SHA256SUMS"+ checksums.write_text(digest + " " + archive.name + "\n", encoding="utf-8")+ return {"archive":str(archive), "sha256":digest, "bytes":archive.stat().st_size, "files":len(files), "format":"installable-source-zip", "excluded":[".git", "_img2_local.py", "__pycache__", ".img2", "credentials", "showcase-assets"]}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--source", type=Path, default=Path(__file__).resolve().parent.parent)+ parser.add_argument("--output", type=Path, help="Output directory for the versioned ZIP and SHA256SUMS (default: SOURCE/dist)")+ args = parser.parse_args()+ source = args.source.resolve()+ try:+ print(json.dumps(package(source, args.output.resolve() if args.output else source / "dist"), indent=2))+ return 0+ except (OSError, ValueError, KeyError, TypeError, zipfile.BadZipFile) as error:+ print(str(error), file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/verify_install.py b/scripts/verify_install.pynew file mode 100755index 0000000..c2c53c7--- /dev/null+++ b/scripts/verify_install.py@@ -0,0 +1,114 @@+#!/usr/bin/env python3+"""Exercise official img2 installation without touching the real user's hosts."""+import argparse+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+++def verify(plugin, harness, cli=None):+ node = shutil.which("node")+ if not node:+ raise ValueError("Node.js >=18 is required")+ cli = cli or harness / "bin" / "img2.mjs"+ if not (harness / ".git").exists():+ raise ValueError("--harness-source must be a Git checkout of img2")+ if not cli.is_file():+ raise ValueError("img2 CLI entrypoint does not exist: " + str(cli))+ identity = json.loads((plugin / "plugin.json").read_text(encoding="utf-8"))["name"]+ if identity != "interior":+ raise ValueError("this verifier expects the interior plugin")+ generated = [plugin / "_img2_local.py", plugin / "tools" / "_img2_local.py"]+ original = {p: p.read_bytes() if p.exists() else None for p in generated}+ observations = []+ try:+ with tempfile.TemporaryDirectory(prefix="img2-interior-install-") as tmp:+ home = Path(tmp) / "home"+ home.mkdir()+ img2_home = home / ".img2"+ hosts = [home / ".claude", home / ".codex", home / ".config" / "opencode"]+ for host in hosts:+ host.mkdir(parents=True)+ launcher = home / ".local" / "bin"+ launcher.mkdir(parents=True)+ settings_file = home / ".claude" / "settings.json"+ settings_file.write_text(json.dumps({"theme":"preserve-me","permissions":{"allow":["Read"],"additionalDirectories":["/preserved-directory"]}}), encoding="utf-8")+ env = dict(os.environ, HOME=str(home), IMG2_HOME=str(img2_home), XDG_CONFIG_HOME=str(home / ".config"), NO_COLOR="1")+ # Exclude real launcher candidates (/opt/homebrew/bin and /usr/local/bin).+ env["PATH"] = os.pathsep.join(dict.fromkeys([str(launcher), str(Path(node).parent), str(Path(sys.executable).parent), "/usr/bin", "/bin"]))+ env.pop("IMG2THREEJS_HOME", None)++ def run(*args):+ proc = subprocess.run([node, str(cli), *args], env=env, cwd=tmp, capture_output=True, text=True, timeout=120)+ if proc.returncode:+ raise RuntimeError("img2 %s exited %s\n%s\n%s" % (" ".join(args), proc.returncode, proc.stdout, proc.stderr))+ observations.append({"command":["img2", *args], "exitCode":proc.returncode})+ return proc.stdout++ run("install", "--from", str(harness), "--yes")+ settings = json.loads(settings_file.read_text(encoding="utf-8"))+ if settings.get("theme") != "preserve-me" or settings["permissions"].get("allow") != ["Read"]:+ raise RuntimeError("harness changed unrelated host settings")+ if not {"/preserved-directory", str(img2_home)}.issubset(settings["permissions"]["additionalDirectories"]):+ raise RuntimeError("harness lost or failed to merge directory permissions")+ run("add", "--link", str(plugin), "--yes")+ registry = json.loads((img2_home / "plugins.json").read_text(encoding="utf-8"))+ rows = [r for r in registry["plugins"] if r["id"] == identity]+ if len(rows) != 1 or rows[0]["repo"] != "link:" + str(plugin):+ raise RuntimeError("local source registry identity is wrong")+ canonical = img2_home / "plugins" / identity+ links = []+ for host in hosts:+ link = host / "skills" / ("img2-" + identity)+ if not link.is_symlink() or Path(os.readlink(link)) != canonical or link.resolve() != plugin:+ raise RuntimeError("incorrect host skill link: %s" % link)+ links.append(str(link.relative_to(home)))+ doctor = json.loads(run("doctor", "--json"))+ if doctor["fails"]:+ raise RuntimeError("static doctor findings: " + json.dumps(doctor))+ run("sync", "--check")+ capability = json.loads(run("capabilities", "--from-kind", "image", "--to-kind", "interior-scene-candidate", "--plugin", identity, "--json"))+ providers = capability.get("providers", [])+ if capability.get("status") != "answered" or len(providers) != 1 or providers[0].get("plugin") != identity:+ raise RuntimeError("capability not resolved: " + json.dumps(capability))+ steps = providers[0]["steps"]+ if not any("instruction" in s and "argv" not in s for s in steps) or not any("argv" in s for s in steps):+ raise RuntimeError("capability lost actor distinction between authored work and programs")+ run("update", identity, "--check")+ run("remove", identity, "--yes")+ if not plugin.is_dir() or not (plugin / "plugin.json").is_file():+ raise RuntimeError("removal damaged original plugin source")+ if any((h / "skills" / ("img2-" + identity)).is_symlink() for h in hosts):+ raise RuntimeError("removal left owned host links")+ if json.loads((img2_home / "plugins.json").read_text(encoding="utf-8"))["plugins"]:+ raise RuntimeError("removal retained registration")+ return {"status":"passed", "plugin":identity, "harnessVersion":json.loads((harness / "package.json").read_text())["version"], "hosts":links, "doctor":doctor, "stepActorsPreserved":True, "originalCheckoutPreserved":True, "commands":observations}+ finally:+ for path, content in original.items():+ if content is None:+ path.unlink(missing_ok=True)+ else:+ path.write_bytes(content)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--harness-source", type=Path, required=True)+ parser.add_argument("--plugin-dir", type=Path, default=Path(__file__).resolve().parent.parent)+ parser.add_argument("--cli", type=Path, help="Optional published img2 JavaScript entrypoint; defaults to the source checkout CLI")+ args = parser.parse_args()+ try:+ print(json.dumps(verify(args.plugin_dir.resolve(), args.harness_source.resolve(),+ args.cli.resolve() if args.cli else None), indent=2))+ return 0+ except (OSError, ValueError, KeyError, TypeError, RuntimeError, subprocess.TimeoutExpired) as error:+ print(json.dumps({"status":"error", "reason":str(error)}), file=sys.stderr)+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/steps.json b/steps.jsonnew file mode 100644index 0000000..3d31d89--- /dev/null+++ b/steps.json@@ -0,0 +1,16 @@+[+ {"id":"interior-prepare","title":"Read the supplied image and author project inputs","actor":"agent","command":"Read {plugin_dir}/SKILL.md and reference/production-runbook.md, reference/reference-analysis.md and reference/scene-contract.md. Inspect {image} with image tools and any supplied references. Run interior_project.py start in {workspace} with the observed source kind, then preflight; resolve missing dependencies in project-local environments. Author {workspace}/interior-intake.json, scene-spec.json and actual image-specific build_scene(context) code. Do not ask the user to provide JSON, use a canned room for a different image, stop at planning, or claim hidden geometry is measured.","after":[]},+ {"id":"interior-init","title":"Pin authorized reference and authored intake","actor":"program","command":"python3 \"{plugin_dir}/tools/interior_workflow.py\" init --workspace \"{workspace}\" --image \"{image}\" --intake \"{workspace}/interior-intake.json\"","after":["interior-prepare"]},+ {"id":"interior-intake","title":"Review image observations, provenance and uncertainty","actor":"agent","command":"Follow {plugin_dir}/reference/intake-camera.md. Inspect the actual image, visible anchors, source authority, scale assumptions, reference findings, components, output budget and unknowns. Record intake using the validated snapshot plus immutable project/source-analysis evidence. Separate local processing permission from publication rights.","after":["interior-init"]},+ {"id":"interior-camera","title":"Decide camera and composition through actual blockout renders","actor":"agent","command":"Follow {plugin_dir}/reference/intake-camera.md and reference/geometry.md. Author genuine room/furniture blockout geometry with the packaged Blender helpers. Run author_scene.py draft at the actual source aspect; inspect source/lateral/reverse renders and camera/projection. Fix framing, silhouettes, proportions and negative space before polish. Use compare_views.py for a labeled contact sheet, open it, and record camera only after visual inspection.","after":["interior-intake"]},+ {"id":"interior-resources","title":"Search, inspect and acquire suitable licensed resources","actor":"agent","command":"Follow {plugin_dir}/reference/resources.md. Use the real Poly Haven search/info/files client, visually inspect candidate previews or imported geometry/maps, and author resource-selection.json with purposes and explicit formats/resolutions. Fetch all selected glTF dependencies and PBR/HDR channels with verified bytes and provenance. Free scoped CC0 acquisition needs no routine per-asset dialog; paid generation/uploads/restricted assets require separate authority. Resource availability or API rank does not establish visual fit.","after":["interior-camera"]},+ {"id":"interior-geometry","title":"Build and repair actual editable geometry","actor":"agent","command":"Follow {plugin_dir}/reference/geometry.md. Implement scene-specific room shell, real openings, furniture, soft forms, details and contacts in build_scene.py using authoring helpers and selected assets. Preserve component/finish/physical IDs and metric UV0. Render source/lateral/reverse and contact close-ups; inspect silhouettes, ground clearance, seams and authored unseen surfaces. Keep causal before/after evidence and record geometry acceptance only after actual visual review.","after":["interior-resources"]},+ {"id":"interior-materials-review","title":"Prepare, bind and visually verify PBR materials","actor":"agent","command":"Follow {plugin_dir}/reference/materials.md and reference/resources.md. Author surfaces.json and execute prepare_surfaces.py where derivatives are needed; inspect decoded pixels, physical texel scale, actual bound color/normal/roughness, color spaces and packing. Capture fixed frontal/grazing native and runtime views. Use provisional low-cost bake/probe/export when required to audit actual runtime GLB bindings against intended material-policy.json. Repair real causes, freeze audit evidence and record materials only after observing the rendered result.","after":["interior-geometry"]},+ {"id":"interior-lighting","title":"Calibrate color coordinates and author transport","actor":"agent","command":"Follow {plugin_dir}/reference/lighting.md and reference/bake-export.md. Execute the asymmetric rotated-UV1 EXR/native/browser calibration, retain its actual measurements and keep it separate from image likeness. Author the scene light state, probe pose, color transforms and glass approximation. Preserve UV0, plan distinct full-static and SUN-free ambient passes, and identify dependencies that need a full rebake. Lighting acceptance is recorded only after the next production bake/export and actual rendered checks.","after":["interior-materials-review"]},+ {"id":"interior-bake-export","title":"Bake, denoise, probe and export three real products","actor":"agent","command":"Execute {plugin_dir}/reference/bake-export.md with author_scene.py bake, probe and export in the explicit workspace and new run IDs. Produce independent UV1 atlases, linear ambient EXR, full-light static portable appearance, current indoor probe, packed editable master, runtime GLB and distinct portable GLB plus manifest. Never reuse a stale probe or full-sun runtime atlas. Render and inspect source/lateral/contact/receiver evidence; record lighting acceptance with actual current receipts and limits. Preserve prior rejected rounds and rerun material audit after final exports.","after":["interior-lighting"]},+ {"id":"interior-viewer","title":"Integrate the actual exported scene into Three.js","actor":"agent","command":"Follow {plugin_dir}/reference/viewer-integration.md. Run interior_project.py install-viewer, npm ci and npm run build in the project; serve loopback and open the actual page. Load generated schema-2 manifest, runtime GLB, EXR atlases/probe and optional background; inspect first frame, source aspect, title/views/variants/credit, PBR and shadowed sun. No required sofa, curtain, fixed room bounds or canned fallback. Diagnose real load/shader/resource failures rather than showing a false ready state.","after":["interior-bake-export"]},+ {"id":"interior-interaction","title":"Verify camera, cloth, lifecycle and accessible surfaces","actor":"agent","command":"Follow {plugin_dir}/reference/interaction.md. Exercise bounded camera including sub-epsilon updates, source/3D/wireframe/reset, named views and scoped variants. When cloth exists verify exact UV/hem binding, held-point error, pinned rail, exclusive pointer/wheel ownership, cancellation, settling and reduced motion; otherwise hide cloth controls honestly. Exercise real load failure/retry and WebGL loss/recovery, desktop/narrow focus/overflow and actual download links. Record observed interaction evidence and device/performance limits, not a bare non-crash.","after":["interior-viewer"]},+ {"id":"interior-delivery-review","title":"Independently reopen and audit actual native/runtime/portable deliveries","actor":"agent","command":"Follow {plugin_dir}/reference/delivery.md. Run inspect_scene.py master and portable in fresh consumers and inspect source/material views. Generate the delivery contract from current manifest dependencies with interior_project.py delivery-contract; run audit_delivery.py, current audit_materials.py and relevant Khronos validation. Exercise built runtime URLs and optional downloads, capture actual hashes and payload/device observations, and record delivery only after actual reopening/rendering and dependency checks.","after":["interior-interaction"]},+ {"id":"interior-review","title":"Compare current outputs, repair causal defects and hand off","actor":"agent","command":"Follow {plugin_dir}/reference/review.md and reference/production-runbook.md. Review current source/lateral/material views against the pinned source and declared brief. Any visual/input failure requires actual scoped repair, revise from the earliest affected governance stage, dependent regeneration and re-review; metadata edits or exposure tricks do not repair geometry/materials. Record explicit final reviewer acceptance only with current evidence, then deliver scripts/spec/provenance/master/runtime+sidecars/viewer/portable, reproduction commands and honest limits.","after":["interior-delivery-review"]},+ {"id":"interior-gates","title":"Run all blocking img2 interior gates on current inputs","actor":"program","command":"python3 \"{plugin_dir}/tools/run_gates.py\" --plugin-dir \"{plugin_dir}\" --workspace \"{workspace}\"","after":["interior-review"]}+]diff --git a/tests/test_audits.py b/tests/test_audits.pynew file mode 100644index 0000000..82ccfab--- /dev/null+++ b/tests/test_audits.py@@ -0,0 +1,472 @@+"""Black-box CLI regressions; uses the real img2 core and gate runner, never mock verdicts.++Set IMG2_HARNESS_SOURCE to a local harness checkout, or install ~/.img2/harness.+The harness is linked into a temporary IMG2_HOME; no host registration is changed.+"""+import base64+import copy+import hashlib+import json+import os+from pathlib import Path+import shlex+import struct+import subprocess+import sys+import tempfile+import unittest++TOOLS = Path(__file__).resolve().parent.parent / "tools"+PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aZ1sAAAAASUVORK5CYII=")+++def digest(path):+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def json_file(path, value):+ path.write_text(json.dumps(value), encoding="utf-8")+++def mesh_fixture():+ positions = struct.pack("<9f", 0, 0, 0, 1, 0, 0, 0, 1, 0)+ uvs = struct.pack("<6f", 0, 0, 1, 0, 0, 1)+ binary = positions + uvs + PNG+ document = {+ "asset": {"version": "2.0", "generator": "interior audit regression fixture"},+ "buffers": [{"byteLength": len(binary)}],+ "bufferViews": [{"buffer": 0, "byteOffset": 0, "byteLength": len(positions)},+ {"buffer": 0, "byteOffset": len(positions), "byteLength": len(uvs)},+ {"buffer": 0, "byteOffset": len(positions) + len(uvs), "byteLength": len(PNG)}],+ "accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3",+ "min": [0, 0, 0], "max": [1, 1, 0]},+ {"bufferView": 1, "componentType": 5126, "count": 3, "type": "VEC2"}],+ "images": [{"bufferView": 2, "mimeType": "image/png"}],+ "textures": [{"source": 0}],+ "materials": [{"name": "Linen", "pbrMetallicRoughness": {+ "baseColorTexture": {"index": 0}, "metallicRoughnessTexture": {"index": 0},+ "roughnessFactor": 0.9, "metallicFactor": 0}, "normalTexture": {"index": 0, "scale": 0.7},+ "extensions": {"KHR_materials_sheen": {"sheenColorFactor": [0.12, 0.12, 0.12]}}}],+ "extensionsUsed": ["KHR_materials_sheen"],+ "meshes": [{"primitives": [{"attributes": {"POSITION": 0, "TEXCOORD_0": 1}, "material": 0}]}],+ "nodes": [{"mesh": 0}], "scenes": [{"nodes": [0]}], "scene": 0,+ }+ return document, binary+++def write_glb(path, document, binary):+ payload = json.dumps(document, separators=(",", ":")).encode()+ payload += b" " * (-len(payload) % 4)+ chunks = struct.pack("<II", len(payload), 0x4E4F534A) + payload+ if binary is not None:+ binary += b"\x00" * (-len(binary) % 4)+ chunks += struct.pack("<II", len(binary), 0x004E4942) + binary+ path.write_bytes(struct.pack("<4sII", b"glTF", 2, len(chunks) + 12) + chunks)+++class AuditTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.harness = Path(os.environ.get("IMG2_HARNESS_SOURCE", str(Path.home() / ".img2/harness"))).expanduser().resolve()+ if not (cls.harness / "img2_core/gate_runner.py").is_file():+ raise unittest.SkipTest("real img2 harness required: set IMG2_HARNESS_SOURCE or install ~/.img2/harness")++ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory(prefix="interior-audits-")+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ self.workspace = self.root / "workspace with spaces"+ self.workspace.mkdir()+ self.home = self.root / "home"+ self.home.mkdir()+ (self.home / "harness").symlink_to(self.harness, target_is_directory=True)+ self.env = dict(os.environ, IMG2_HOME=str(self.home), PYTHONDONTWRITEBYTECODE="1",+ PYTHONPATH=str(self.home / "harness"))+ self.assets = self.root / "external assets"+ self.assets.mkdir()+ self.glb = self.assets / "runtime.glb"+ self.document, self.binary = mesh_fixture()+ self.write_model()+ self.policy = self.root / "policy.json"+ self.policy_data = {"schemaVersion": 1, "materials": [{"name": "Linen",+ "requireBaseColorTexture": True, "requireNormalTexture": True,+ "requireRoughnessTexture": True, "minRoughnessFactor": 0.8,+ "maxMetallicFactor": 0, "maxSheenColorFactor": 0.2, "texCoord": 0}]}+ json_file(self.policy, self.policy_data)+ source = self.assets / "source.png"+ source.write_bytes(PNG)+ portable = self.assets / "portable.glb"+ portable_doc = copy.deepcopy(self.document)+ portable_doc["asset"]["generator"] = "distinct static portable fixture"+ write_glb(portable, portable_doc, self.binary)+ # Hash-only native/sidecar fixtures: no claim that these reopen in Blender or an EXR consumer.+ (self.assets / "master.blend").write_bytes(b"BLENDER-v300 native fixture bytes; consumer reopening is explicitly not audited")+ (self.assets / "ambient.exr").write_bytes(b"declared sidecar fixture bytes")+ self.contract = self.root / "delivery.json"+ self.contract_data = {"schemaVersion": 1, "root": str(self.assets), "assets": [],+ "runtime": {"asset": "runtime", "sidecars": ["ambient"]},+ "portable": {"asset": "portable", "limitations": ["Static lighting; no interactive cloth."]},+ "native": {"asset": "master"}, "limitations": ["Authored scale, not a measured survey."]}+ for identifier, role, name in [("source", "source", "source.png"), ("runtime", "runtime", "runtime.glb"),+ ("portable", "portable", "portable.glb"), ("master", "native", "master.blend"),+ ("ambient", "sidecar", "ambient.exr")]:+ self.contract_data["assets"].append({"id": identifier, "role": role, "path": name,+ "sha256": digest(self.assets / name)})+ json_file(self.contract, self.contract_data)++ def write_model(self):+ write_glb(self.glb, self.document, self.binary)++ def command(self, tool, *arguments, expected=0):+ process = subprocess.run([sys.executable, str(TOOLS / tool), "--workspace", str(self.workspace), *map(str, arguments)],+ cwd=self.workspace, env=self.env, capture_output=True, text=True)+ self.assertEqual(process.returncode, expected, process.stdout + process.stderr)+ self.assertFalse(process.stderr, process.stderr)+ result = json.loads(process.stdout) # Rejects additional stdout and pseudo-envelopes.+ if "--gate" in arguments:+ self.assertEqual(set(result), {"kind", "version", "gate", "plugin", "status", "reasons", "evidence"})+ self.assertEqual(result["kind"], "img2.gate-verdict")+ self.assertEqual(result["version"], 1)+ self.assertEqual(result["plugin"], "interior")+ self.assertEqual(result["status"], {0: "pass", 1: "fail", 2: "error"}[expected])+ if expected:+ self.assertTrue(result["reasons"])+ return result++ def materials(self, expected=0):+ return self.command("audit_materials.py", "--glb", self.glb, "--policy", self.policy, expected=expected)++ def delivery(self, expected=0):+ return self.command("audit_delivery.py", "--contract", self.contract, expected=expected)++ def snapshot(self):+ return {str(path.relative_to(self.workspace)): (path.read_bytes(), path.stat().st_mtime_ns)+ for path in self.workspace.rglob("*") if path.is_file()}++ def test_happy_path_real_bindings_receipts_and_read_only_gates(self):+ state_dir = self.workspace / ".img2"+ state_dir.mkdir()+ json_file(state_dir / "state.json", {"version": 1, "workspace": str(self.workspace),+ "plugins": {"interior": {"stages": {"intake": "sentinel"}}, "other": {"keep": True}}})+ self.materials()+ self.delivery()+ before = self.snapshot()+ self.command("audit_materials.py", "--gate")+ self.command("audit_delivery.py", "--gate")+ self.assertEqual(before, self.snapshot())+ state = json.loads((state_dir / "state.json").read_text())+ self.assertEqual(state["plugins"]["interior"]["stages"], {"intake": "sentinel"})+ self.assertEqual(state["plugins"]["other"], {"keep": True})+ self.assertIn("materialAudit", state["plugins"]["interior"])+ self.assertIn("deliveryAudit", state["plugins"]["interior"])++ def test_missing_receipts_fail_without_writing(self):+ self.command("audit_materials.py", "--gate", expected=1)+ self.command("audit_delivery.py", "--gate", expected=1)+ self.assertEqual(self.snapshot(), {})++ def test_absent_maps_fail_even_with_image_inventory(self):+ del self.document["materials"][0]["pbrMetallicRoughness"]["baseColorTexture"]+ self.write_model()+ self.materials(expected=1)+ self.command("audit_materials.py", "--gate", expected=1)++ def test_missing_duplicate_and_unbound_targets_fail(self):+ pristine = copy.deepcopy(self.document)+ mutations = (lambda doc: doc["materials"][0].update(name="Other"),+ lambda doc: doc["materials"].append(copy.deepcopy(doc["materials"][0])),+ lambda doc: doc["meshes"][0]["primitives"][0].pop("material"))+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ self.document = copy.deepcopy(pristine)+ mutate(self.document)+ self.write_model()+ self.materials(expected=1)++ def test_precise_gltf_defaults_do_not_invent_policy_expectations(self):+ self.document["materials"][0] = {"name": "Linen"}+ self.policy_data["materials"] = [{"name": "Linen"}]+ json_file(self.policy, self.policy_data)+ self.write_model()+ result = self.materials()+ factors = result["materials"][0]["factors"]+ self.assertEqual(factors["roughnessFactor"], 1)+ self.assertEqual(factors["metallicFactor"], 1)+ self.assertEqual(factors["sheenColorFactor"], [0, 0, 0])+ self.policy_data["materials"][0]["maxMetallicFactor"] = 0+ json_file(self.policy, self.policy_data)+ self.materials(expected=1)++ def test_transform_texcoord_override_is_effective_binding(self):+ texture = self.document["materials"][0]["pbrMetallicRoughness"]["baseColorTexture"]+ texture["extensions"] = {"KHR_texture_transform": {"texCoord": 1}}+ self.document["extensionsUsed"].append("KHR_texture_transform")+ del self.policy_data["materials"][0]["texCoord"]+ json_file(self.policy, self.policy_data)+ self.write_model()+ self.materials(expected=1)+ self.document["meshes"][0]["primitives"][0]["attributes"]["TEXCOORD_1"] = 1+ self.write_model()+ result = self.materials()+ self.assertEqual(result["materials"][0]["textures"]["baseColorTexture"]["texCoord"], 1)+ self.policy_data["materials"][0]["texCoord"] = 0+ json_file(self.policy, self.policy_data)+ self.materials(expected=1)++ def test_broken_indices_storage_and_uv_counts_are_errors(self):+ pristine = copy.deepcopy(self.document)+ mutations = [lambda doc: doc["textures"][0].update(source=99),+ lambda doc: doc["textures"][0].update(source=True),+ lambda doc: doc["materials"][0]["normalTexture"].update(index=8),+ lambda doc: doc["bufferViews"][2].update(byteLength=999999),+ lambda doc: doc["accessors"][1].update(count=4),+ lambda doc: doc["accessors"][1].update(count=2),+ lambda doc: doc["accessors"][1].update(type="SCALAR"),+ lambda doc: doc["images"][0].update(uri="also.png")]+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ self.document = copy.deepcopy(pristine)+ mutate(self.document)+ self.write_model()+ self.materials(expected=2)++ def test_truncated_invalid_and_duplicate_chunks_never_pass(self):+ valid = self.glb.read_bytes()+ bad_cases = [valid[:8], valid[:-4], valid + b"junk", b"nope" + valid[4:]]+ wrong_version = bytearray(valid)+ struct.pack_into("<I", wrong_version, 4, 1)+ bad_cases.append(wrong_version)+ overflow_chunk = bytearray(valid)+ struct.pack_into("<I", overflow_chunk, 12, 0xFFFFFFFC)+ bad_cases.append(overflow_chunk)+ duplicate = bytearray(valid + struct.pack("<II", 4, 0x4E4F534A) + b"{} ")+ struct.pack_into("<I", duplicate, 8, len(duplicate))+ bad_cases.append(duplicate)+ for index, raw in enumerate(bad_cases):+ with self.subTest(case=index):+ self.glb.write_bytes(raw)+ self.materials(expected=2)++ def test_policy_rejects_nonfinite_booleans_duplicates_and_typos(self):+ pristine = copy.deepcopy(self.policy_data)+ mutations = [lambda doc: doc["materials"][0].update(minRoughnessFactor=float("nan")),+ lambda doc: doc["materials"][0].update(maxMetallicFactor=True),+ lambda doc: doc["materials"][0].update(requireNormalTexture="true"),+ lambda doc: doc["materials"][0].update(texCoord=-1),+ lambda doc: doc["materials"][0].update(texCoord=True),+ lambda doc: doc["materials"][0].update(requireRoughnessTexure=True),+ lambda doc: doc["materials"].append(copy.deepcopy(doc["materials"][0])),+ lambda doc: doc.update(schemaVersion=True)]+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ policy = copy.deepcopy(pristine)+ mutate(policy)+ json_file(self.policy, policy)+ self.materials(expected=2)+ self.policy.write_text('{"schemaVersion":1,"schemaVersion":1,"materials":[]}', encoding="utf-8")+ self.materials(expected=2)++ def test_external_image_and_buffer_resources_are_pinned(self):+ (self.assets / "fabric.png").write_bytes(PNG)+ self.document["images"] = [{"uri": "fabric.png"}]+ self.write_model()+ result = self.materials()+ self.assertEqual(result["resources"][0]["sha256"], digest(self.assets / "fabric.png"))+ (self.assets / "fabric.png").write_bytes(PNG + b"changed")+ self.command("audit_materials.py", "--gate", expected=1)+ (self.assets / "fabric.png").write_bytes(PNG)+ self.command("audit_materials.py", "--gate")+ (self.assets / "fabric.png").unlink()+ self.command("audit_materials.py", "--gate", expected=1)++ def test_external_buffer_bytes_and_bounds_are_rechecked(self):+ buffer = self.assets / "mesh.bin"+ buffer.write_bytes(self.binary)+ self.document["buffers"][0]["uri"] = "mesh.bin"+ write_glb(self.glb, self.document, None)+ result = self.materials()+ self.assertEqual(result["resources"][0]["sha256"], digest(buffer))+ buffer.write_bytes(self.binary[:-4])+ self.command("audit_materials.py", "--gate", expected=1)+ self.materials(expected=2)++ def test_metadata_bound_is_enforced_before_reading_payload(self):+ length = 16 * 1024 * 1024 + 4+ total = 12 + 8 + length+ with self.glb.open("wb") as handle:+ handle.write(struct.pack("<4sII", b"glTF", 2, total))+ handle.write(struct.pack("<II", length, 0x4E4F534A))+ handle.seek(total - 1)+ handle.write(b" ")+ self.materials(expected=2)++ def test_embedded_data_uri_and_missing_external_image(self):+ self.document["images"] = [{"uri": "data:image/png;base64," + base64.b64encode(PNG).decode()}]+ self.write_model()+ self.materials()+ self.document["images"] = [{"uri": "absent.png"}]+ self.write_model()+ self.materials(expected=1)+ self.document["images"] = [{"uri": "data:image/png;base64,not-base64!"}]+ self.write_model()+ self.materials(expected=2)++ def test_resource_escapes_and_unselected_escapes_are_refused(self):+ outside = self.root / "outside.png"+ outside.write_bytes(PNG)+ (self.assets / "escape.png").symlink_to(outside)+ for uri in ("../outside.png", "%2e%2e/outside.png", "escape.png", str(outside),+ "https://example.test/image.png", "file:///tmp/image.png", "..\\outside.png"):+ with self.subTest(uri=uri):+ self.document["images"] = [{"bufferView": 2, "mimeType": "image/png"}, {"uri": uri}]+ self.write_model()+ self.materials(expected=2)++ def test_changed_policy_glb_and_receipt_cannot_reuse_pass(self):+ self.materials()+ original_policy = self.policy.read_bytes()+ self.policy.write_bytes(original_policy + b"\n")+ self.command("audit_materials.py", "--gate", expected=1)+ self.policy.write_bytes(original_policy)+ original_glb = self.glb.read_bytes()+ changed = bytearray(original_glb)+ changed[-4] ^= 1+ self.glb.write_bytes(changed)+ self.command("audit_materials.py", "--gate", expected=1)+ self.glb.write_bytes(original_glb)+ receipt = self.workspace / ".img2/artifacts/interior/material-audit.json"+ data = json.loads(receipt.read_text())+ data["materials"] = []+ json_file(receipt, data)+ self.command("audit_materials.py", "--gate", expected=1)++ def test_relative_delivery_root_and_all_assets_rehashed(self):+ self.contract_data["root"] = self.assets.name+ json_file(self.contract, self.contract_data)+ self.delivery()+ for row in self.contract_data["assets"]:+ with self.subTest(role=row["role"]):+ path = self.assets / row["path"]+ previous = path.read_bytes()+ path.write_bytes(previous + b"changed")+ result = self.command("audit_delivery.py", "--gate", expected=1)+ self.assertTrue(any(row["id"] in reason for reason in result["reasons"]))+ path.write_bytes(previous)+ self.command("audit_delivery.py", "--gate")++ def test_contract_change_does_not_silently_reauthorize_assets(self):+ self.delivery()+ (self.assets / "ambient.exr").write_bytes(b"changed and repinned by a different contract")+ self.contract_data["assets"][-1]["sha256"] = digest(self.assets / "ambient.exr")+ json_file(self.contract, self.contract_data)+ self.command("audit_delivery.py", "--gate", expected=1)++ def test_duplicate_paths_ids_roles_dependencies_and_missing_limits(self):+ pristine = copy.deepcopy(self.contract_data)+ mutations = [lambda doc: doc["assets"][1].update(id="source"),+ lambda doc: doc["assets"][1].update(path="source.png"),+ lambda doc: doc["assets"][1].update(role="source"),+ lambda doc: doc["runtime"].update(asset="portable"),+ lambda doc: doc["runtime"].update(sidecars=[]),+ lambda doc: doc["runtime"].update(sidecars=["ambient", "ambient"]),+ lambda doc: doc["runtime"].update(sidecars=["source"]),+ lambda doc: doc["portable"].update(limitations=[]),+ lambda doc: doc.update(limitations=[""]),+ lambda doc: doc["assets"][0].update(sha256="0"),+ lambda doc: doc.update(schemaVersion=True)]+ for mutate in mutations:+ with self.subTest(mutation=mutate):+ value = copy.deepcopy(pristine)+ mutate(value)+ json_file(self.contract, value)+ self.delivery(expected=2)++ def test_identical_portable_and_wrong_hash_are_negative_audits(self):+ (self.assets / "portable.glb").write_bytes(self.glb.read_bytes())+ self.contract_data["assets"][2]["sha256"] = digest(self.glb)+ json_file(self.contract, self.contract_data)+ self.delivery(expected=1)+ self.command("audit_delivery.py", "--gate", expected=1)+ self.contract_data["assets"][0]["sha256"] = "0" * 64+ json_file(self.contract, self.contract_data)+ self.delivery(expected=1)++ def test_delivery_escapes_symlinks_aliases_and_missing_assets(self):+ outside = self.root / "outside.png"+ outside.write_bytes(PNG)+ (self.assets / "escape.png").symlink_to(outside)+ original = self.contract_data["assets"][0]["path"]+ for path in ("../outside.png", str(outside), "escape.png", "https://example.test/file", "a/../source.png"):+ with self.subTest(path=path):+ self.contract_data["assets"][0]["path"] = path+ json_file(self.contract, self.contract_data)+ self.delivery(expected=2)+ self.contract_data["assets"][0]["path"] = original+ (self.assets / "alias.glb").symlink_to(self.glb)+ self.contract_data["assets"][2]["path"] = "alias.glb"+ json_file(self.contract, self.contract_data)+ self.delivery(expected=2)+ self.contract_data["assets"][2]["path"] = "missing.glb"+ json_file(self.contract, self.contract_data)+ self.delivery(expected=1)++ def test_input_collision_cannot_overwrite_original_policy(self):+ self.policy = self.workspace / ".img2/artifacts/interior/material-audit.json"+ self.policy.parent.mkdir(parents=True)+ json_file(self.policy, self.policy_data)+ original = self.policy.read_bytes()+ self.materials(expected=2)+ self.assertEqual(self.policy.read_bytes(), original)+ self.assertFalse((self.workspace / ".img2/state.json").exists())++ def test_no_output_or_state_symlink_escape(self):+ outside = self.root / "outside-output"+ outside.mkdir()+ (self.workspace / ".img2").symlink_to(outside, target_is_directory=True)+ self.materials(expected=2)+ self.delivery(expected=2)+ self.command("audit_materials.py", "--gate", expected=2)+ self.assertEqual(list(outside.iterdir()), [])++ def test_malformed_gate_arguments_keep_exact_error_envelope(self):+ self.command("audit_materials.py", "--gate", "--policy", self.policy, expected=2)+ self.command("audit_delivery.py", "--gate", "--unknown", expected=2)++ def test_real_gate_runner_pass_fail_and_error_semantics(self):+ self.materials()+ self.delivery()+ plugin = self.root / "runner plugin"+ plugin.mkdir()+ gates = []+ for identifier, tool in (("interior-materials", "audit_materials.py"), ("interior-delivery", "audit_delivery.py")):+ command = " ".join([shlex.quote(sys.executable), shlex.quote(str(TOOLS / tool)),+ '--workspace "{workspace}" --gate'])+ gates.append({"id": identifier, "command": command, "blocking": True,+ "after": [] if not gates else ["interior-materials"]})+ json_file(plugin / "gates.json", gates)+ def run(expected):+ process = subprocess.run([sys.executable, "-m", "img2_core.gate_runner", "--plugin-dir", str(plugin),+ "--workspace", str(self.workspace)], env=self.env, cwd=self.workspace,+ capture_output=True, text=True)+ self.assertEqual(process.returncode, expected, process.stdout + process.stderr)+ self.assertFalse(process.stderr)+ result = json.loads(process.stdout)+ self.assertEqual(result["kind"], "img2.gate-run")+ return result+ result = run(0)+ self.assertEqual([row["status"] for row in result["results"]], ["pass", "pass"])+ self.assertFalse(result["stopped"])+ self.policy.write_bytes(self.policy.read_bytes() + b"\n")+ result = run(1)+ self.assertEqual([row["status"] for row in result["results"]], ["fail", "skipped"])+ self.assertEqual(result["results"][0]["envelope"]["gate"], "interior-materials")+ self.materials()+ # Malformed persisted state exercises the real tool's error, not an echo command.+ (self.workspace / ".img2/state.json").write_text('{"version":1,"plugins":null}', encoding="utf-8")+ result = run(1)+ self.assertEqual([row["status"] for row in result["results"]], ["error", "skipped"])+ self.assertEqual(result["results"][0]["exitCode"], 2)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_authoring.py b/tests/test_authoring.pynew file mode 100644index 0000000..f2c8c11--- /dev/null+++ b/tests/test_authoring.py@@ -0,0 +1,117 @@+"""Stdlib context tests; opt-in real bpy regressions via IMG2_BLENDER_PYTHON."""+import json+import math+import os+from pathlib import Path+import struct+import subprocess+import sys+import tempfile+from types import SimpleNamespace+import unittest+import zlib++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+from authoring import Context, context_from_args+++def reference_png(path):+ def chunk(kind, payload):+ return struct.pack('>I', len(payload)) + kind + payload + struct.pack('>I', zlib.crc32(kind+payload))+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 4,3,8,2,0,0,0))+ + chunk(b'IDAT', zlib.compress((b'\x00'+b'\x80\x90\xa0'*4)*3)) + chunk(b'IEND',b''))+++class ContextTests(unittest.TestCase):+ def test_confines_absolute_traversal_and_symlink(self):+ with tempfile.TemporaryDirectory() as root, tempfile.TemporaryDirectory() as outside:+ workspace = Path(root).resolve()+ context = Context(workspace, {}, workspace/'assets', workspace/'evidence')+ self.assertEqual(context.resolve('input.png'), workspace/'input.png')+ for path in ('../escape', '/tmp/escape'):+ with self.assertRaises(ValueError):+ context.resolve(path)+ (workspace/'link').symlink_to(outside, target_is_directory=True)+ with self.assertRaises(ValueError):+ context.resolve('link/escape')++ def test_rejects_installed_plugin_workspaces_and_symlinks(self):+ for workspace in (ROOT, ROOT / 'examples' / 'not-a-workspace'):+ with self.assertRaisesRegex(ValueError, 'outside the installed plugin'):+ Context(workspace, {}, workspace/'assets', workspace/'evidence')+ args = SimpleNamespace(workspace=str(ROOT), spec='scene-spec.json', run_id='forbidden')+ with self.assertRaisesRegex(ValueError, 'outside the installed plugin'):+ context_from_args(args)+ parent = ROOT.parent.resolve()+ context = Context(parent, {}, parent/'assets', parent/'evidence')+ with self.assertRaisesRegex(ValueError, 'installed plugin'):+ context.resolve(ROOT.name + '/reference')+ with tempfile.TemporaryDirectory() as directory:+ link = Path(directory)/'installed'+ link.symlink_to(ROOT, target_is_directory=True)+ with self.assertRaisesRegex(ValueError, 'outside the installed plugin'):+ Context(link, {}, link/'assets', link/'evidence')++ def test_import_is_inert_without_bpy(self):+ with tempfile.TemporaryDirectory() as directory:+ result = subprocess.run([sys.executable, '-c',+ 'import authoring; from pathlib import Path; assert not list(Path.cwd().iterdir())'],+ cwd=directory, env={**os.environ, 'PYTHONPATH':str(ROOT)}, capture_output=True, text=True)+ self.assertEqual(result.returncode, 0, result.stderr)++ def test_source_size_and_run_slug(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ reference_png(root/'public/assets/reference.png')+ spec = {'source':'public/assets/reference.png', 'authoring':{'sourceImageSize':[4,3]}}+ (root/'scene-spec.json').write_text(json.dumps(spec))+ args = SimpleNamespace(workspace=str(root), spec='scene-spec.json', run_id='first')+ args.run_id = '../escape'+ with self.assertRaises(ValueError):+ context_from_args(args)+ args.run_id = 'second'+ spec['authoring']['sourceImageSize'] = [4,0]+ (root/'scene-spec.json').write_text(json.dumps(spec))+ with self.assertRaises(ValueError):+ context_from_args(args)++[email protected](os.environ.get('IMG2_BLENDER_PYTHON'), 'Set IMG2_BLENDER_PYTHON for real native regressions')+class NativeRegressions(unittest.TestCase):+ def test_packed_pixels_sheen_and_asymmetric_uv1_transport(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ reference_png(root/'public/assets/reference.png')+ spec = json.loads((ROOT/'examples/studio/scene-spec.json').read_text())+ spec['authoring']['sourceImageSize'] = [4,3]+ (root/'scene-spec.json').write_text(json.dumps(spec))+ for stage in ('material-regression', 'calibrate'):+ command = [os.environ['IMG2_BLENDER_PYTHON'], str(ROOT/'tools/author_scene.py'), stage,+ '--workspace', str(root), '--run-id', stage, '--width','128','--samples','4']+ result = subprocess.run(command, capture_output=True, text=True, timeout=600)+ self.assertEqual(result.returncode, 0, result.stdout+'\n'+result.stderr)+ filename = 'calibration.json' if stage == 'calibrate' else 'material-regression.json'+ receipt = json.loads((root/'.img2/artifacts/interior/production'/stage/filename).read_text())+ if stage == 'material-regression':+ self.assertLessEqual(receipt['packedAlbedoPixelError'], 1e-6)+ self.assertIs(receipt['externalMapRemovedBeforeReopen'], True)+ self.assertIs(receipt['uv0Preserved'], True)+ self.assertIs(receipt['nativeSheenRestoredAfterSuccessAndFailure'], True)+ self.assertEqual(len(receipt['actualGltfSheen']), 3)+ for actual, expected in zip(receipt['actualGltfSheen'], [.096, .060, .030]):+ self.assertAlmostEqual(actual, expected, delta=1e-6)+ else:+ self.assertEqual(receipt['texCoord'], 1)+ self.assertLessEqual(receipt['coordinateRoundTripMaxError'], 1e-5)+ self.assertLessEqual(receipt['decodedPixelMeanError'], .01)+ self.assertEqual(set(receipt['probeAxes']), {'positiveX','negativeX','positiveZ','negativeZ'})+ for reading in receipt['probeAxes'].values():+ self.assertLessEqual(reading['maxError'], .001)+ runtime = receipt['runtimeLightmap']+ self.assertLessEqual(runtime['decodedExrMaxError'], 1e-6)+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_project.py b/tests/test_project.pynew file mode 100644index 0000000..2b21a37--- /dev/null+++ b/tests/test_project.py@@ -0,0 +1,154 @@+"""Project safety and consumer-facing provenance boundaries; no network or Blender."""+import base64+import importlib.util+import io+import json+from pathlib import Path+import sys+import tempfile+import unittest+from unittest.mock import patch++TOOLS = Path(__file__).resolve().parent.parent / 'tools'+sys.path.insert(0, str(TOOLS))+import project_support as production++PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=')+++class ProjectBoundaryTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory(prefix='interior project boundaries ')+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.workspace = self.root / 'project with spaces'+ self.workspace.mkdir()+ self.image = self.root / 'supplied.png'+ self.image.write_bytes(PNG)++ def start(self):+ return production.start(self.workspace, self.image, 'photo', 'User supplied for local study', [])++ def test_initialized_project_cannot_be_reset_with_a_new_reference(self):+ self.start()+ receipt = self.workspace / production.ARTIFACTS / 'project.json'+ before = production.digest(receipt)+ self.image.write_bytes(PNG + b'a different supplied file')+ with self.assertRaisesRegex(ValueError, 'already initialized'):+ self.start()+ self.assertEqual(production.digest(receipt), before)++ def test_changed_pinned_reference_is_not_silently_repinned(self):+ self.start()+ (self.workspace / 'public/assets/reference.png').write_bytes(PNG + b'tampered')+ with self.assertRaisesRegex(ValueError, 'reference changed'):+ production.project(self.workspace)++ def test_other_image_never_uses_the_oak_room_as_a_fallback(self):+ self.start()+ with self.assertRaisesRegex(ValueError, 'exact authorized source'):+ production.use_recipe(self.workspace, 'oak-linen')+ self.assertFalse((self.workspace / 'scene-spec.json').exists())++ def test_symlinked_public_directory_cannot_redirect_reference_write(self):+ outside = self.root / 'outside'+ outside.mkdir()+ (self.workspace / 'public').symlink_to(outside, target_is_directory=True)+ with self.assertRaisesRegex(ValueError, 'escapes'):+ self.start()+ self.assertEqual(list(outside.iterdir()), [])++ def test_installed_plugin_is_never_an_authoring_workspace(self):+ with self.assertRaisesRegex(ValueError, 'installed plugin'):+ production.workspace_path(production.PLUGIN / 'nested workspace')++ def test_frozen_evidence_tampering_is_detected_without_replacing_it(self):+ original = self.workspace / 'observed.json'+ original.write_text('{"measurement": 7.636}', encoding='utf-8')+ frozen = production.snapshot(self.workspace, 'observed.json', 'round-01', 'contact')+ path = self.workspace / frozen['path']+ path.write_text('{"measurement": 0}', encoding='utf-8')+ changed = production.digest(path)+ with self.assertRaisesRegex(ValueError, 'does not match'):+ production.snapshot(self.workspace, 'observed.json', 'round-01', 'contact')+ self.assertEqual(production.digest(path), changed)++ def test_snapshot_cannot_read_external_files_or_escape_its_run(self):+ self.image.write_bytes(PNG)+ for path, run in [('../supplied.png', 'round'), ('supplied.png', '../outside')]:+ with self.subTest(path=path, run=run), self.assertRaises(ValueError):+ production.snapshot(self.workspace, path, run, 'image')++ def test_template_upgrade_preserves_user_edits_without_partial_updates(self):+ package = self.root / 'package'+ template = package / 'runtime/viewer'+ (template / 'src').mkdir(parents=True)+ (template / 'package.json').write_text('{"private":true}', encoding='utf-8')+ (template / 'src/app.js').write_text('export const version = 1;', encoding='utf-8')+ with patch.object(production, 'PLUGIN', package):+ production.install_template(self.workspace, template, 'viewer-install.json')+ (self.workspace / 'package.json').write_text('{"private":true,"user":"edited"}', encoding='utf-8')+ (template / 'src/app.js').write_text('export const version = 2;', encoding='utf-8')+ with self.assertRaisesRegex(ValueError, 'unowned/edited'):+ production.install_template(self.workspace, template, 'viewer-install.json')+ self.assertEqual((self.workspace / 'src/app.js').read_text(), 'export const version = 1;')+ self.assertIn('edited', (self.workspace / 'package.json').read_text())++ def test_unambiguous_finite_project_json_is_required(self):+ path = self.workspace / 'scene-spec.json'+ for value in ['{"lens":50,"lens":10}', '{"lens":NaN}', '{"lens":1e999}']:+ with self.subTest(value=value):+ path.write_text(value, encoding='utf-8')+ with self.assertRaises(ValueError):+ production.read_json(path)++ def delivery_inputs(self):+ self.start()+ directory = self.workspace / 'public/assets/interior'+ directory.mkdir()+ # This tool inventories bytes, not consumer validity; reopening is a separate gate.+ for name in ('runtime.glb', 'portable.glb', 'master.blend', 'shared.exr'):+ (directory / name).write_bytes(('inventory fixture: ' + name).encode())+ spec = {'sourceViewLimit': 'Unseen depth is authored, not measured.',+ 'portability': 'Static color only; no runtime interaction.'}+ (self.workspace / 'scene-spec.json').write_text(json.dumps(spec), encoding='utf-8')+ manifest = {'sourceImage': '/assets/reference.png', 'model': '/assets/interior/runtime.glb',+ 'portableModel': '/assets/interior/portable.glb', 'blender': '/assets/interior/master.blend',+ 'environment': '/assets/interior/shared.exr', 'background': '/assets/interior/shared.exr'}+ return directory, manifest++ def test_shared_environment_dependency_has_one_contract_identity(self):+ directory, manifest = self.delivery_inputs()+ (directory / 'manifest.json').write_text(json.dumps(manifest), encoding='utf-8')+ production.delivery_contract(self.workspace, 'scene-spec.json')+ contract = production.read_json(self.workspace / production.ARTIFACTS / 'delivery-contract.json')+ dependencies = contract['runtime']['sidecars']+ self.assertEqual(dependencies, ['manifest', 'environment'])+ paths = [asset['path'] for asset in contract['assets']]+ self.assertEqual(len(paths), len(set(paths)))++ def test_delivery_rejects_external_or_traversing_manifest_dependencies(self):+ directory, manifest = self.delivery_inputs()+ for url in ['https://example.com/private.exr', '/assets/%2e%2e/private.exr', '/assets/interior/shared.exr?hidden=1']:+ with self.subTest(url=url):+ manifest['environment'] = url+ (directory / 'manifest.json').write_text(json.dumps(manifest), encoding='utf-8')+ with self.assertRaisesRegex(ValueError, 'local /assets/'):+ production.delivery_contract(self.workspace, 'scene-spec.json')+ self.assertFalse((self.workspace / production.ARTIFACTS / 'delivery-contract.json').exists())++ @unittest.skipUnless(importlib.util.find_spec('PIL'), 'Pillow is an optional production image dependency')+ def test_oriented_jpeg_reports_display_aspect_for_camera_planning(self):+ from PIL import Image+ image = Image.new('RGB', (16, 9), '#d2ceca')+ exif = image.getexif()+ exif[274] = 6+ buffer = io.BytesIO()+ image.save(buffer, format='JPEG', exif=exif)+ geometry = production.image_geometry(buffer.getvalue())+ self.assertEqual(geometry['sourceImageSize'], [9, 16])+ self.assertEqual(geometry['encodedSize'], [16, 9])+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_resources.py b/tests/test_resources.pynew file mode 100644index 0000000..ec5ac29--- /dev/null+++ b/tests/test_resources.py@@ -0,0 +1,322 @@+"""Resource integrity/path/manifest and real decoded-material behavior.++No network is required: only the HTTP transport is substituted, while planning,+streaming, hashes, on-disk glTF references and all image operations are real.+Image cases explicitly skip without the optional surface dependencies.+"""+import copy+import hashlib+import io+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest+import urllib.request++PLUGIN = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(PLUGIN))+from resources_lib import polyhaven as ph+from resources_lib import surfaces+from resources_lib.storage import MAX_JSON, confined, hashes, read_json, write_json++try:+ import numpy as np+ from PIL import Image+except ImportError:+ np = Image = None+++def file_descriptor(name, payload):+ return {'url': 'https://dl.polyhaven.org/file/ph-assets/' + name,+ 'size': len(payload), 'md5': hashlib.md5(payload, usedforsecurity=False).hexdigest()}+++class Transport:+ def __init__(self):+ self.json = {}+ self.payloads = {}+ self.requests = []+ self.transfers = []++ def get(self, endpoint):+ self.requests.append(endpoint)+ return copy.deepcopy(self.json[endpoint])++ def open(self, url):+ self.transfers.append(url)+ return io.BytesIO(self.payloads[url])++ def add(self, name, payload):+ item = file_descriptor(name, payload)+ self.payloads[item['url']] = payload+ return item+++class WorkspaceTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory(prefix='interior resources ')+ self.addCleanup(temporary.cleanup)+ self.workspace = Path(temporary.name)+ self.client = Transport()++ def save(self, relative, data):+ write_json(self.workspace, relative, data)++ def texture_selection(self):+ files = {key: {'2k': {'jpg': self.client.add(f'linen_{key}_2k.jpg', key.encode())}}+ for key in ('Diffuse', 'nor_gl', 'Rough')}+ self.client.json.update({'/info/linen': {'name': 'Linen', 'type': 1}, '/files/linen': files})+ return {'schemaVersion': 1, 'reason': 'Observed textile', 'textures': [+ {'id': 'linen', 'resolution': '2k', 'format': 'jpg', 'purpose': 'Seat upholstery'}]}++ def model_selection(self, uri='textures/color.jpg'):+ document = {'asset': {'version': '2.0'}, 'buffers': [{'uri': 'mesh.bin', 'byteLength': 4}],+ 'images': [{'uri': uri}]}+ item = self.client.add('chair_original_2k.gltf', json.dumps(document).encode())+ item['include'] = {'mesh.bin': self.client.add('mesh.bin', b'mesh'),+ 'textures/color.jpg': self.client.add('color.jpg', b'color')}+ self.client.json.update({'/info/chair': {'type': 2}, '/files/chair': {'gltf': {'2k': {'gltf': item}}}})+ return {'schemaVersion': 1, 'reason': 'Selected editable chair', 'models': [+ {'id': 'chair', 'resolution': '2k', 'format': 'gltf', 'purpose': 'Chair'}]}+++class ResourceTests(WorkspaceTests):+++ def test_gltf_relative_dependencies_resolve_after_acquisition(self):+ self.save('selection.json', self.model_selection())+ result = ph.fetch(self.workspace, 'selection.json', self.client)+ root = self.workspace / result['models']['chair']+ for entry in read_json(root)['buffers'] + read_json(root)['images']:+ self.assertTrue((root.parent / entry['uri']).is_file())++ def test_missing_gltf_dependency_cannot_publish_receipt(self):+ self.save('selection.json', self.model_selection('textures/not-in-descriptor.jpg'))+ with self.assertRaisesRegex(ValueError, 'include map'):+ ph.fetch(self.workspace, 'selection.json', self.client)+ self.assertFalse((self.workspace / '.img2/artifacts/interior/resources.json').exists())++ def test_cache_checks_bytes_not_only_size(self):+ item = self.client.add('scan.jpg', b'correct')+ relative = 'resources/polyhaven/scan/scan.jpg'+ first = ph.acquire(self.client, self.workspace, 'scan', relative, item)+ self.assertEqual(ph.acquire(self.client, self.workspace, 'scan', relative, item), first)+ self.assertEqual(len(self.client.transfers), 1)+ (self.workspace / relative).write_bytes(b'corrupt')+ self.assertEqual(ph.acquire(self.client, self.workspace, 'scan', relative, item), first)+ self.assertEqual(len(self.client.transfers), 2)+ self.assertEqual((self.workspace / relative).read_bytes(), b'correct')++ def test_bad_download_is_not_published_and_preserves_old_file(self):+ item = self.client.add('scan.jpg', b'correct')+ relative = 'resources/polyhaven/scan/scan.jpg'+ path = confined(self.workspace, relative)+ path.parent.mkdir(parents=True)+ path.write_bytes(b'old')+ for bad in (b'short', b'wrong!!', b'too-many-bytes'):+ self.client.payloads[item['url']] = bad+ with self.assertRaisesRegex(ValueError, 'byte length|MD5'):+ ph.acquire(self.client, self.workspace, 'scan', relative, item)+ self.assertEqual(path.read_bytes(), b'old')+ self.assertEqual(list(path.parent.iterdir()), [path])++ def test_missing_map_and_wrong_asset_type_fail_before_download(self):+ selection = self.texture_selection()+ del self.client.json['/files/linen']['nor_gl']+ with self.assertRaisesRegex(ValueError, 'nor_gl'):+ ph.plan_selection(self.client, self.workspace, selection)+ self.client.json['/info/linen']['type'] = 2+ with self.assertRaisesRegex(ValueError, 'type'):+ ph.plan_selection(self.client, self.workspace, selection)+ self.assertEqual(self.client.transfers, [])++ def test_descriptor_limits_and_confined_include_paths(self):+ selection = self.model_selection()+ item = self.client.json['/files/chair']['gltf']['2k']['gltf']+ dependency = next(iter(item['include'].values()))+ for bad in ('../escape', '/absolute', 'textures/../../escape', 'C:/drive',+ 'textures\\escape', 'textures/%2e%2e/escape'):+ item['include'] = {bad: dependency}+ with self.subTest(path=bad), self.assertRaises(ValueError):+ ph.plan_selection(self.client, self.workspace, selection)+ oversized = {**dependency, 'size': ph.MAX_FILE + 1}+ with self.assertRaisesRegex(ValueError, 'size'):+ ph.descriptor(oversized)+ with self.assertRaisesRegex(ValueError, 'MD5'):+ ph.descriptor({**dependency, 'md5': 'not-a-hash'})+ self.assertEqual(self.client.transfers, [])++ def test_symlink_paths_are_refused_even_inside_workspace(self):+ target = self.workspace / 'original'+ target.mkdir()+ (self.workspace / 'resources').symlink_to(target, target_is_directory=True)+ with self.assertRaisesRegex(ValueError, 'Symlink'):+ confined(self.workspace, 'resources/scan.jpg')+ self.assertEqual(list(target.iterdir()), [])++ def test_urls_and_redirects_never_leave_observed_provider_hosts(self):+ for url in ('http://dl.polyhaven.org/file', 'https://dl.polyhaven.org.evil.test/file',+ 'https://[email protected]/file', 'file:///tmp/file',+ 'https://localhost/file', 'https://cdn.polyhaven.com:8443/file'):+ with self.subTest(url=url), self.assertRaises(ValueError):+ ph.safe_url(url)+ for host in ph.HOSTS:+ self.assertEqual(ph.safe_url(f'https://{host}/file'), f'https://{host}/file')+ with self.assertRaises(ValueError):+ ph.SafeRedirect().redirect_request(urllib.request.Request('https://api.polyhaven.com/files/a'),+ None, 302, 'Found', {}, 'https://evil.test/payload')++ def test_oversized_json_fails_before_parsing(self):+ path = self.workspace / 'large.json'+ with path.open('wb') as stream:+ stream.truncate(MAX_JSON + 1)+ with self.assertRaisesRegex(ValueError, 'exceeds'):+ read_json(path)+++[email protected](np is not None and Image is not None,+ 'optional image behavior tests need requirements-surfaces.txt (NumPy and Pillow)')+class SurfaceTests(WorkspaceTests):+ def image(self, relative, array):+ path = confined(self.workspace, relative)+ path.parent.mkdir(parents=True, exist_ok=True)+ Image.fromarray(np.asarray(array, dtype=np.uint8)).save(path)+ return path++ def recipe(self, operations, **extra):+ self.save('surfaces.json', {'schemaVersion': 1, 'operations': operations, **extra})+ return surfaces.prepare(self.workspace, 'surfaces.json')++ def output(self, name):+ with Image.open(self.workspace / ('public/assets/interior/' + name)) as image:+ return np.asarray(image).copy()++ def test_dye_removes_scan_hue_but_preserves_luminance_variation(self):+ source = self.image('input.png', [[[20, 40, 120], [50, 100, 200], [90, 150, 240]]])+ original = source.read_bytes()+ receipt = self.recipe([{'id': 'cloth', 'op': 'dye', 'input': {'path': 'input.png'},+ 'dye': {'space': 'linear', 'value': [0.25, 0.125, 0.0625]},+ 'bounds': [0.1, 2], 'output': 'public/assets/interior/cloth.png'}])+ encoded = self.output('cloth.png').astype(float) / 255+ decoded = np.where(encoded <= 0.04045, encoded / 12.92, ((encoded + 0.055) / 1.055) ** 2.4)+ self.assertTrue(np.all(np.diff(decoded[0, :, 0]) > 0))+ np.testing.assert_allclose(decoded[0, 1], [0.25, 0.125, 0.0625], atol=0.003)+ np.testing.assert_allclose(decoded[..., 0], decoded[..., 1] * 2, atol=0.006)+ self.assertEqual(source.read_bytes(), original)+ output = receipt['operations'][0]['outputs']['image']+ self.assertEqual(output['sha256'], hashes(self.workspace / output['path'])[2])+ self.assertEqual(output['pixels']['size'], [3, 1])+ self.assertGreater(output['pixels']['std'][0], 0)++ def test_mean_normalized_dye_and_centered_roughness(self):+ self.image('color.png', [[[50, 50, 50], [100, 100, 100], [150, 150, 150]]])+ self.image('rough.png', [[0, 128, 255]])+ self.recipe([+ {'id': 'dye', 'op': 'dye', 'input': {'path': 'color.png'}, 'bounds': [0.7, 1.15],+ 'normalizeMean': True, 'dye': {'space': 'linear', 'value': [0.3, 0.3, 0.3]},+ 'output': 'public/assets/interior/color.png'},+ {'id': 'rough', 'op': 'roughness', 'input': {'path': 'rough.png'}, 'center': 'median',+ 'offset': 0.42, 'scale': 0.30, 'bounds': [0.30, 0.58],+ 'output': 'public/assets/interior/rough.png'}])+ encoded = self.output('color.png').astype(float) / 255+ decoded = np.where(encoded <= 0.04045, encoded / 12.92, ((encoded + 0.055) / 1.055) ** 2.4)+ np.testing.assert_allclose(decoded.mean(axis=(0, 1)), [0.3, 0.3, 0.3], atol=0.004)+ np.testing.assert_array_equal(self.output('rough.png'), [[76, 107, 145]])++ def test_reference_extension_and_crop_require_explicit_observed_rectangle(self):+ source = self.image('public/assets/reference.tiff', np.arange(36, dtype=np.uint8).reshape(3, 4, 3))+ self.save('scene-spec.json', {'source': 'public/assets/reference.tiff'})+ receipt = self.recipe([{'id': 'art', 'op': 'crop', 'input': {'reference': True},+ 'crop': [1, 0, 3, 2], 'output': 'public/assets/interior/art.png'}],+ referenceSha256=hashes(source)[2])+ np.testing.assert_array_equal(self.output('art.png'), np.arange(36, dtype=np.uint8).reshape(3, 4, 3)[:2, 1:3])+ self.assertEqual(receipt['operations'][0]['inputs'][0]['path'], 'public/assets/reference.tiff')+ with self.assertRaisesRegex(ValueError, 'different reference'):+ self.recipe([{'id': 'art', 'op': 'crop', 'input': {'reference': True},+ 'crop': [1, 0, 3, 2], 'output': 'public/assets/interior/wrong.png'}], referenceSha256='0' * 64)+ self.assertFalse((self.workspace / 'public/assets/interior/wrong.png').exists())+ with self.assertRaisesRegex(ValueError, 'exceeds'):+ self.recipe([{'id': 'art', 'op': 'crop', 'input': {'reference': True},+ 'crop': [0, 0, 5, 5], 'output': 'public/assets/interior/padded.png'}])++ def test_resource_channel_integrity_and_no_source_overwrite(self):+ path = self.image('resources/polyhaven/cloth/source.png', [[[100, 100, 100]]])+ self.save('.img2/artifacts/interior/resources.json', {+ 'textures': {'cloth': {'color': 'resources/polyhaven/cloth/source.png'}},+ 'downloads': [{'path': 'resources/polyhaven/cloth/source.png', 'sha256': hashes(path)[2]}]})+ operation = {'id': 'cloth', 'op': 'dye', 'input': {'texture': 'cloth', 'channel': 'color'},+ 'bounds': [0.5, 1.5], 'dye': {'space': 'srgb255', 'value': [120, 130, 140]},+ 'output': 'public/assets/interior/cloth.png'}+ self.recipe([operation])+ np.testing.assert_array_equal(self.output('cloth.png'), [[[120, 130, 140]]])+ path.write_bytes(b'tampered')+ with self.assertRaisesRegex(ValueError, 'integrity'):+ self.recipe([operation])+ source = self.image('public/assets/interior/original.png', [[[42, 42, 42]]])+ original = source.read_bytes()+ with self.assertRaisesRegex(ValueError, 'overwrite'):+ self.recipe([{**operation, 'input': {'path': 'public/assets/interior/original.png'},+ 'output': 'public/assets/interior/original.png'}])+ self.assertEqual(source.read_bytes(), original)++ def test_woven_is_deterministic_metric_and_unit_normal(self):+ operation = {'id': 'rug', 'op': 'woven', 'resolution': 64, 'yarns': 8,+ 'tileMetres': 0.36, 'seed': 42, 'dye': {'space': 'srgb255', 'value': [195, 188, 167]},+ 'outputs': {key: f'public/assets/interior/rug-{key}.png'+ for key in ('basecolor', 'normal', 'roughness')}}+ first = self.recipe([operation])+ arrays, metrics = surfaces.woven(operation, np)+ normal = arrays['normal'] * 2 - 1+ np.testing.assert_allclose(np.linalg.norm(normal, axis=-1), 1, atol=1e-6)+ self.assertLess(metrics['maximumNormalLengthError'], 1e-6)+ self.assertGreater(float(normal[..., 0].std()), 0)+ self.assertTrue(np.all(normal[..., 2] > 0))+ second = self.recipe([operation])+ self.assertEqual(first['operations'][0]['outputs'], second['operations'][0]['outputs'])+ larger, _ = surfaces.woven({**operation, 'tileMetres': 0.72}, np)+ larger_normal = larger['normal'] * 2 - 1+ np.testing.assert_allclose(larger_normal[..., :2] / larger_normal[..., 2:],+ normal[..., :2] / normal[..., 2:] / 2, atol=1e-6)+ different, _ = surfaces.woven({**operation, 'seed': 43}, np)+ self.assertFalse(np.array_equal(arrays['basecolor'], different['basecolor']))+ np.testing.assert_array_equal(arrays['normal'], different['normal'])+ smooth, _ = surfaces.woven({**operation, 'rippleHeight': 0}, np)+ smooth_normal = smooth['normal'] * 2 - 1+ # At the rising left/top flank of the first crossing, +U slopes up and+ # downward image rows slope up: OpenGL requires negative X, positive Y.+ self.assertLess(smooth_normal[2, 2, 0], 0)+ self.assertGreater(smooth_normal[2, 2, 1], 0)++ def test_blur_strength_and_exponent_control_real_scan_variation(self):+ checker = np.indices((16, 16)).sum(axis=0) % 2+ self.image('scan.png', np.repeat((checker * 100 + 100)[..., None], 3, axis=2))+ base = {'id': 'original', 'op': 'dye', 'input': {'path': 'scan.png'},+ 'dye': {'space': 'srgb255', 'value': [160, 140, 120]},+ 'bounds': [0.1, 3], 'output': 'public/assets/interior/original.png'}+ self.recipe([base,+ {**base, 'id': 'blur', 'blur': 2, 'output': 'public/assets/interior/blur.png'},+ {**base, 'id': 'weak', 'strength': 0, 'output': 'public/assets/interior/weak.png'},+ {**base, 'id': 'power', 'exponent': 0.6, 'output': 'public/assets/interior/power.png'}])+ self.assertLess(self.output('blur.png')[..., 0].std(), self.output('original.png')[..., 0].std())+ np.testing.assert_array_equal(self.output('weak.png')[0, 0], [160, 140, 120])+ self.assertEqual(float(self.output('weak.png')[..., 0].std()), 0)+ self.assertLess(self.output('power.png')[..., 0].std(), self.output('original.png')[..., 0].std())++ def test_zero_median_and_duplicate_outputs_fail_instead_of_nan_or_overwrite(self):+ self.image('black.png', [[[0, 0, 0]]])+ operation = {'id': 'black', 'op': 'dye', 'input': {'path': 'black.png'},+ 'bounds': [0.5, 1.5], 'dye': {'space': 'linear', 'value': [0.3, 0.3, 0.3]},+ 'output': 'public/assets/interior/black.png'}+ with self.assertRaisesRegex(ValueError, 'zero median'):+ self.recipe([operation])+ with self.assertRaisesRegex(ValueError, 'Duplicate'):+ self.recipe([operation, {**operation, 'id': 'other'}])+ self.assertFalse((self.workspace / 'public/assets/interior/black.png').exists())+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_workflow.py b/tests/test_workflow.pynew file mode 100644index 0000000..e3fb5aa--- /dev/null+++ b/tests/test_workflow.py@@ -0,0 +1,393 @@+"""Consumer-facing workflow regressions, using the real installed core and CLIs.++Set IMG2_HARNESS_SOURCE to a local img2 checkout, or install ~/.img2/harness.+No third-party libraries, network access, or generated visual certifications.+"""++import base64+import copy+import hashlib+import json+import os+from pathlib import Path+import shlex+import subprocess+import sys+import tempfile+import unittest+++PLUGIN = Path(__file__).resolve().parent.parent+STAGES = ("intake", "camera", "geometry", "materials", "lighting", "interaction", "delivery", "review")+PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=")+++class WorkflowTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.harness = Path(os.environ.get("IMG2_HARNESS_SOURCE", str(Path.home() / ".img2/harness"))).expanduser().resolve()+ if not (cls.harness / "img2_core/gate_runner.py").is_file():+ raise RuntimeError("Install img2 or set IMG2_HARNESS_SOURCE to its checkout before running workflow tests")++ def setUp(self):+ self.temp = tempfile.TemporaryDirectory(prefix="interior workflow ")+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.workspace = self.root / "user project"+ self.workspace.mkdir()+ home = self.root / "img2 home"+ home.mkdir()+ (home / "harness").symlink_to(self.harness, target_is_directory=True)+ self.env = {**os.environ, "IMG2_HOME": str(home), "PYTHONPATH": str(self.harness), "PYTHONDONTWRITEBYTECODE": "1"}+ self.image = self.root / "reference.png"+ self.image.write_bytes(PNG)+ self.intake = self.workspace / "author-intake.json"+ self.intake_data = {"schemaVersion": 1, "sourceKind": "synthetic-design-reference",+ "authorization": "Authored reference, approved for this project.",+ "scale": {"unit": "m", "basis": "authored-estimate", "note": "Sofa scale is an authored estimate, not measured."},+ "components": ["sofa", "linen curtains"], "unknowns": ["Unseen wall depth"],+ "interactionRequired": True}+ self.intake.write_text(json.dumps(self.intake_data), encoding="utf-8")+ self.snapshot = self.workspace / ".img2/artifacts/interior/intake.json"+ self.state_path = self.workspace / ".img2/state.json"++ def execute(self, argv, expected=0):+ proc = subprocess.run(argv, cwd=self.workspace, env=self.env, text=True, capture_output=True, timeout=30)+ self.assertEqual(proc.returncode, expected, f"{argv}\nstdout: {proc.stdout}\nstderr: {proc.stderr}")+ try:+ result = json.loads(proc.stdout)+ except json.JSONDecodeError:+ self.fail(f"Expected exactly one JSON document, got {proc.stdout!r}; stderr={proc.stderr!r}")+ self.assertIsInstance(result, dict)+ return result++ def cli(self, command, *args, expected=0):+ return self.execute([sys.executable, str(PLUGIN / "tools/interior_workflow.py"), command,+ "--workspace", str(self.workspace), *map(str, args)], expected)++ def gate(self, expected=0):+ result = self.execute([sys.executable, str(PLUGIN / "tools/gate_workflow.py"),+ "--workspace", str(self.workspace)], expected)+ self.assertEqual(set(result), {"kind", "version", "gate", "plugin", "status", "reasons", "evidence"})+ self.assertEqual(result["kind"], "img2.gate-verdict")+ self.assertEqual(result["version"], 1)+ self.assertEqual(result["gate"], "interior-workflow")+ self.assertEqual(result["plugin"], "interior")+ self.assertEqual(result["status"], {0: "pass", 1: "fail", 2: "error"}[expected])+ self.assertEqual(bool(result["reasons"]), expected != 0)+ return result++ def init(self, expected=0):+ return self.cli("init", "--image", self.image, "--intake", self.intake, expected=expected)++ def evidence(self, stage):+ if stage == "intake":+ return self.snapshot+ path = self.workspace / f"{stage}-review.txt"+ if not path.exists():+ path.write_text(f"Explicit {stage} review fixture; not a visual quality certificate.\n", encoding="utf-8")+ return path++ def record(self, stage, decision="accept", expected=0, evidence=None):+ paths = [self.evidence(stage)] if evidence is None else evidence+ args = ["--stage", stage, "--decision", decision, "--reviewer", "Named reviewer", "--note", f"Reviewed {stage}: {decision}"]+ for path in paths:+ args.extend(["--evidence", str(path)])+ return self.cli("record", *args, expected=expected)++ def complete(self):+ self.init()+ for stage in STAGES:+ self.record(stage)++ def state(self):+ return json.loads(self.state_path.read_text(encoding="utf-8"))++ def run_state(self):+ return self.state()["plugins"]["interior"]++ def fingerprint(self):+ return {str(path.relative_to(self.workspace)): (path.read_bytes(), path.stat().st_mtime_ns)+ for path in self.workspace.rglob("*") if path.is_file()}++ def test_init_snapshots_source_and_intake_without_acceptance(self):+ result = self.init()+ self.assertEqual(result["status"], "pending")+ self.assertEqual(result["nextStage"], "intake")+ run = self.run_state()+ self.assertEqual(run["source"]["sha256"], hashlib.sha256(PNG).hexdigest())+ self.assertEqual(json.loads(self.snapshot.read_text()), self.intake_data)+ self.assertEqual(run["intake"]["snapshot"]["sha256"], hashlib.sha256(self.snapshot.read_bytes()).hexdigest())+ self.assertTrue(all(item["status"] == "pending" for item in run["stages"].values()))+ self.assertEqual(len(run["history"]), 1)+ self.gate(expected=1)+ self.assertEqual(self.image.read_bytes(), PNG)++ def test_complete_run_and_read_only_consumers(self):+ self.complete()+ before = self.fingerprint()+ self.assertEqual(self.cli("next")["status"], "completed")+ self.assertEqual(self.cli("report")["workflow"], self.run_state())+ self.gate()+ self.assertEqual(self.fingerprint(), before)++ def test_missing_run_reads_do_not_create_state(self):+ before = self.fingerprint()+ self.assertEqual(self.cli("next")["action"], "init")+ self.assertIsNone(self.cli("report")["workflow"])+ self.gate(expected=1)+ self.assertEqual(self.fingerprint(), before)+ self.assertFalse((self.workspace / ".img2").exists())++ def test_wrong_order_and_duplicate_acceptance_do_not_change_history(self):+ self.init()+ before = self.run_state()+ self.record("camera", expected=1)+ self.assertEqual(self.run_state(), before)+ self.record("intake")+ before = self.run_state()+ self.record("intake", expected=2)+ self.assertEqual(self.run_state(), before)+ self.record("geometry", "reject", expected=1)+ self.assertEqual(self.run_state(), before)++ def test_reinitialize_refuses_without_resetting_any_history(self):+ self.complete()+ before = self.fingerprint()+ self.init(expected=2)+ self.assertEqual(self.fingerprint(), before)++ def test_intake_acceptance_requires_snapshot_and_nonempty_evidence(self):+ self.init()+ self.record("intake", evidence=[], expected=2)+ self.record("intake", evidence=[self.intake], expected=2)+ empty = self.workspace / "empty.txt"+ empty.touch()+ self.record("intake", evidence=[self.snapshot, empty], expected=2)+ self.record("intake", evidence=[self.snapshot, self.snapshot], expected=2)+ self.assertEqual(len(self.run_state()["history"]), 1)++ def test_reviewer_and_note_are_explicit_nonempty_attestations(self):+ self.init()+ for reviewer, note in ((" ", "reviewed"), ("reviewer", " ")):+ with self.subTest(reviewer=reviewer, note=note):+ self.cli("record", "--stage", "intake", "--decision", "accept", "--reviewer", reviewer,+ "--note", note, "--evidence", self.snapshot, expected=2)+ self.cli("record", "--stage", "intake", "--decision", "accept", "--note", "reviewed",+ "--evidence", self.snapshot, expected=2)+ self.assertEqual(len(self.run_state()["history"]), 1)++ def test_source_change_blocks_acceptance_and_gate_without_repinning(self):+ self.init()+ self.record("intake")+ before = self.run_state()+ self.image.write_bytes(PNG + b"changed")+ self.record("camera", expected=1)+ self.assertEqual(self.run_state(), before)+ self.assertEqual(self.cli("next")["status"], "blocked")+ self.gate(expected=1)+ self.cli("revise", "--from", "intake", "--reason", "Reconsider source")+ self.record("intake", expected=1)+ self.assertEqual(self.run_state()["source"], before["source"])++ def test_earlier_changed_or_missing_evidence_blocks_later_acceptance(self):+ self.init()+ self.record("intake")+ self.record("camera")+ camera = self.evidence("camera")+ original = camera.read_bytes()+ camera.write_bytes(original + b"changed")+ self.record("geometry", expected=1)+ self.gate(expected=1)+ camera.unlink()+ self.record("geometry", expected=1)+ camera.write_bytes(original)+ self.record("geometry")++ def test_final_gate_checks_source_intake_and_every_stage_evidence(self):+ self.complete()+ for path in [self.image, self.intake, self.snapshot, *(self.evidence(stage) for stage in STAGES[1:])]:+ with self.subTest(path=path.name):+ original = path.read_bytes()+ path.write_bytes(original + b"\nchanged")+ self.gate(expected=1)+ path.write_bytes(original)+ self.gate()++ def test_rejection_invalidates_downstream_and_preserves_prior_history(self):+ self.complete()+ old = copy.deepcopy(self.run_state()["history"])+ result = self.record("geometry", "reject", expected=1)+ self.assertEqual((result["status"], result["nextStage"]), ("rejected", "geometry"))+ run = self.run_state()+ self.assertEqual(run["history"][:len(old)], old)+ self.assertEqual(run["stages"]["camera"]["status"], "accepted")+ self.assertEqual(run["stages"]["geometry"]["status"], "rejected")+ self.assertTrue(all(run["stages"][name]["status"] == "pending" for name in STAGES[3:]))+ self.gate(expected=1)+ self.record("geometry", expected=2)+ self.cli("revise", "--from", "geometry", "--reason", "Corrected form after review")+ for stage in STAGES[2:]:+ self.record(stage)+ self.gate()+ self.assertEqual(self.run_state()["history"][:len(old)], old)++ def test_revision_allows_new_evidence_without_mutating_old_receipts(self):+ self.complete()+ old = copy.deepcopy(self.run_state()["history"])+ self.evidence("camera").write_text("Revised matching-camera review\n")+ self.gate(expected=1)+ self.cli("revise", "--from", "camera", "--reason", "Re-author camera alignment")+ self.assertEqual(self.cli("next")["status"], "pending")+ for stage in STAGES[1:]:+ self.record(stage)+ self.gate()+ self.assertEqual(self.run_state()["history"][:len(old)], old)++ def test_request_input_and_stop_require_explicit_revision(self):+ self.init()+ self.record("intake")+ for decision, status in (("request-input", "blocked"), ("stop", "stopped")):+ with self.subTest(decision=decision):+ self.record("camera", decision, evidence=[], expected=3)+ before = self.fingerprint()+ self.assertEqual(self.cli("next", expected=3)["status"], status)+ self.cli("report")+ self.gate(expected=1)+ self.assertEqual(self.fingerprint(), before)+ self.record("camera", expected=2)+ self.cli("revise", "--from", "camera", "--reason", "Reviewer supplied missing information")+ self.assertEqual(self.cli("next")["status"], "pending")+ self.record("camera")++ def test_external_and_symlink_escaping_evidence_is_refused(self):+ self.init()+ external = self.root / "outside-review.txt"+ external.write_text("Outside workspace")+ link = self.workspace / "review-link.txt"+ link.symlink_to(external)+ for path in (external, link, self.workspace / "../outside-review.txt"):+ with self.subTest(path=str(path)):+ self.record("intake", evidence=[self.snapshot, path], expected=2)+ self.assertEqual(len(self.run_state()["history"]), 1)++ def test_intake_snapshot_accepts_workspace_path_alias(self):+ self.init()+ alias = self.root / "project-alias"+ alias.symlink_to(self.workspace, target_is_directory=True)+ self.record("intake", evidence=[alias / ".img2/artifacts/interior/intake.json"])+ for stage in STAGES[1:]:+ self.record(stage)+ self.gate()++ def test_retargeted_evidence_symlink_is_stale_even_if_bytes_match(self):+ self.init()+ self.record("intake")+ first = self.workspace / "first.txt"+ second = self.workspace / "second.txt"+ first.write_text("Same reviewer evidence")+ second.write_bytes(first.read_bytes())+ link = self.workspace / "camera-link.txt"+ link.symlink_to(first)+ self.record("camera", evidence=[link])+ link.unlink()+ link.symlink_to(second)+ self.record("geometry", expected=1)+ self.gate(expected=1)++ def test_other_plugin_and_audit_subtrees_survive_all_mutations(self):+ self.state_path.parent.mkdir()+ audits = {"materialAudit": {"receipt": "material", "passed": False}, "deliveryAudit": {"receipt": "delivery"}}+ other = {"schemaVersion": 17, "private": ["untouched", {"run": 42}]}+ self.state_path.write_text(json.dumps({"version": 1, "workspace": str(self.workspace),+ "plugins": {"other-plugin": other, "interior": audits}, "userField": "retain"}))+ self.init()+ self.record("intake")+ self.record("camera", "reject", expected=1)+ self.cli("revise", "--from", "camera", "--reason", "Reconsider camera")+ self.record("camera")+ state = self.state()+ self.assertEqual(state["plugins"]["other-plugin"], other)+ self.assertEqual(state["userField"], "retain")+ for key, value in audits.items():+ self.assertEqual(state["plugins"]["interior"][key], value)++ def test_malformed_intake_refused_without_snapshot_or_state(self):+ variants = ["", "{", '{"schemaVersion":1,"schemaVersion":1}', '{"schemaVersion":1e999}',+ json.dumps({**self.intake_data, "components": ["sofa", "sofa"]}),+ json.dumps({**self.intake_data, "schemaVersion": True}),+ json.dumps({**self.intake_data, "interactionRequired": "yes"}),+ json.dumps({**self.intake_data, "authorization": " "}),+ json.dumps({**self.intake_data, "scale": {"unit": "m", "basis": "guessed", "note": "estimate"}}),+ json.dumps({**self.intake_data, "untrustedNumber": float("nan")})]+ for data in variants:+ with self.subTest(data=data):+ self.intake.write_text(data)+ self.init(expected=2)+ self.assertFalse(self.snapshot.exists())+ self.assertFalse(self.state_path.exists())++ def test_empty_image_refused(self):+ self.image.write_bytes(b"")+ self.init(expected=2)+ self.assertFalse(self.snapshot.exists())++ def test_malformed_or_duplicate_state_never_passes_gate(self):+ self.complete()+ good = self.state_path.read_text()+ duplicate_stage = good.replace('"camera": {', '"camera": {"status":"accepted"}, "camera": {', 1)+ for bad in ("{", "[]", duplicate_stage, good.replace('"schemaVersion": 1', '"schemaVersion": NaN', 1)):+ with self.subTest(data=bad[:60]):+ self.state_path.write_text(bad)+ self.gate(expected=2)+ self.cli("report", expected=2)+ self.state_path.write_text(good)+ state = self.state()+ state["plugins"]["interior"]["history"] = []+ self.state_path.write_text(json.dumps(state))+ self.gate(expected=2)++ def test_forged_stage_summary_cannot_skip_missing_history(self):+ self.init()+ state = self.state()+ for stage in STAGES:+ state["plugins"]["interior"]["stages"][stage] = {"status": "accepted", "record": 1}+ self.state_path.write_text(json.dumps(state))+ self.gate(expected=2)++ def test_symlinked_control_directory_cannot_redirect_writes(self):+ outside = self.root / "outside-state"+ outside.mkdir()+ (self.workspace / ".img2").symlink_to(outside, target_is_directory=True)+ self.init(expected=2)+ self.assertEqual(list(outside.iterdir()), [])++ def test_real_gate_runner_pass_fail_and_error(self):+ # A one-gate manifest isolates this slice while invoking the real harness+ # runner and the actual shipped gate, not a substitute verdict script.+ registration = self.root / "runner plugin"+ registration.mkdir()+ command = f"{shlex.quote(sys.executable)} {shlex.quote(str(PLUGIN / 'tools/gate_workflow.py'))} --workspace \"{{workspace}}\""+ (registration / "gates.json").write_text(json.dumps([+ {"id": "interior-workflow", "command": command, "blocking": True, "after": []}]))+ argv = [sys.executable, "-m", "img2_core.gate_runner", "--plugin-dir", str(registration), "--workspace", str(self.workspace)]+ incomplete = self.execute(argv, expected=1)+ self.assertEqual(incomplete["kind"], "img2.gate-run")+ self.assertTrue(incomplete["stopped"])+ self.assertEqual([item["status"] for item in incomplete["results"]], ["fail"])+ self.complete()+ passed = self.execute(argv)+ self.assertFalse(passed["stopped"])+ self.assertEqual([item["status"] for item in passed["results"]], ["pass"])+ self.evidence("lighting").write_text("Changed after final review")+ failed = self.execute(argv, expected=1)+ self.assertEqual([item["status"] for item in failed["results"]], ["fail"])+ self.state_path.write_text("{not JSON}")+ errored = self.execute(argv, expected=1)+ self.assertEqual([item["status"] for item in errored["results"]], ["error"])+ self.assertEqual(errored["results"][0]["exitCode"], 2)++++if __name__ == "__main__":+ unittest.main()diff --git a/tests/viewer/curtains.test.mjs b/tests/viewer/curtains.test.mjsnew file mode 100644index 0000000..e75175d--- /dev/null+++ b/tests/viewer/curtains.test.mjs@@ -0,0 +1,148 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { THREE, runtime, curtainFixture } from './helpers.mjs';+const { createCurtainInteraction } = await runtime('interior-curtains.js');++function tick(interaction, frames = 90) {+ interaction.update(0, 0);+ for (let i = 1; i <= frames; i++) interaction.update(1/60, i/60);+}++test('explicit rail frames move a translated panel, pin headers and preserve geometry/UV identities', () => {+ const f = curtainFixture();+ const geometry = f.cloth.geometry;+ const position = geometry.getAttribute('position');+ const uv = geometry.getAttribute('uv');+ const uv1 = geometry.getAttribute('uv1');+ const index = geometry.index;+ const original = position.array.slice();+ const normals = geometry.getAttribute('normal').array.slice();+ const originalUV = uv.array.slice();+ const usage = position.usage;+ const interaction = createCurtainInteraction(f);+ assert.equal(interaction.count, 1);+ interaction.setWind(false);+ interaction.setClosure(1);+ tick(interaction);+ const result = interaction.snapshot();+ assert.ok(result.closure > 0.99);+ assert.ok(result.panels[0].topAnchorError < 1e-10);+ // Signed rail is +X, not the legacy Oak -Z; translated room has x=9..15.+ assert.ok(result.panels[0].probes[3].world[0] > 11.79);+ assert.ok(Math.abs(result.panels[0].probes[3].world[2]-20) < 1e-6);+ for (const { world } of result.panels[0].probes) {+ world.forEach((value, axis) => assert.ok(value >= f.roomBounds.min[axis] && value <= f.roomBounds.max[axis]));+ }+ assert.equal(f.cloth.geometry, geometry);+ assert.equal(geometry.getAttribute('position'), position);+ assert.equal(geometry.getAttribute('uv'), uv);+ assert.equal(geometry.getAttribute('uv1'), uv1);+ assert.equal(geometry.index, index);+ assert.deepEqual(uv.array, originalUV);+ assert.notDeepEqual(position.array, original);+ interaction.reset();+ assert.deepEqual(position.array, original);+ interaction.setClosure(1);+ tick(interaction, 4);+ interaction.dispose();+ interaction.dispose();+ assert.deepEqual(position.array, original);+ assert.deepEqual(geometry.getAttribute('normal').array, normals);+ assert.equal(position.usage, usage);+ assert.equal(f.win.listenerCount()+f.doc.listenerCount()+f.canvas.listenerCount()+f.motion.listenerCount(), 0);+ assert.equal(interaction.update(1, 1), false);+});++test('material-point grips exclusively own wheel and release on capture, visibility and multitouch interruption', () => {+ const f = curtainFixture();+ const interaction = createCurtainInteraction(f);+ interaction.setWind(false);+ const down = () => f.win.emit('pointerdown', f.pointerAt([10.5, 1.4, 20]));+ assert.equal(down().prevented, true);+ assert.equal(interaction.grabbing, true);+ assert.equal(f.controls.enabled, false);+ assert.equal(f.win.emit('wheel').prevented, true);+ assert.equal(f.win.listenerCount('wheel'), 1);+ f.canvas.releasePointerCapture(1);+ assert.equal(interaction.grabbing, false);+ assert.equal(f.controls.enabled, true);+ assert.equal(f.win.listenerCount('wheel'), 0);+ down();+ f.doc.hidden = true;+ f.doc.emit('visibilitychange');+ assert.equal(interaction.grabbing, false);+ assert.equal(f.canvas.hasPointerCapture(1), false);+ assert.equal(interaction.update(60, 60), false);+ f.doc.hidden = false;+ f.doc.emit('visibilitychange');+ down();+ f.win.emit('pointerdown', f.pointerAt([10.6, 1.4, 20], 2, { isPrimary: false, pointerType: 'touch' }));+ assert.equal(interaction.grabbing, false);+ assert.equal(down().prevented, undefined); // still blocked until both contacts end+ f.win.emit('pointerup', { pointerId: 1 });+ f.win.emit('pointerup', { pointerId: 2 });+ down();+ assert.equal(interaction.grabbing, true);+ interaction.dispose();+ assert.equal(f.controls.enabled, true);+ assert.equal(f.canvas.hasPointerCapture(1), false);+ assert.equal(f.win.listenerCount('wheel'), 0);+});++test('hem picking binds barycentric material points, not its decorative texture UV', () => {+ const f = curtainFixture({ hem: true });+ const interaction = createCurtainInteraction(f);+ interaction.setWind(false);+ f.win.emit('pointerdown', f.pointerAt([10.75, 0.4, 20.02]));+ const grip = interaction.snapshot().grip;+ assert.ok(grip);+ assert.equal(grip.part, 'hem');+ assert.ok(Math.abs(grip.uv[0]-0.75) < 1e-4);+ assert.ok(Math.abs(grip.uv[1]) < 1e-6);+ f.win.emit('pointermove', f.pointerAt([11.15, 0.4, 20.02]));+ assert.ok(interaction.targetClosure > 0);+ tick(interaction, 8);+ assert.ok(interaction.snapshot().panels[0].topAnchorError < 1e-10);+ interaction.setEnabled(false);+ assert.equal(interaction.grabbing, false);+ assert.equal(f.win.listenerCount('wheel'), 0);+ interaction.dispose();+});++test('reduced-motion stops wind; settled and zero-cloth scenes stop requesting frames', () => {+ const f = curtainFixture();+ const interaction = createCurtainInteraction(f);+ f.motion.matches = true;+ f.motion.emit('change');+ assert.equal(interaction.wind, false);+ assert.equal(interaction.setWind(true), false);+ tick(interaction, 180);+ assert.equal(interaction.update(1/60, 4), false);+ interaction.dispose();+ const empty = curtainFixture();+ empty.root.clear();+ const noCloth = createCurtainInteraction(empty);+ assert.equal(noCloth.count, 0);+ assert.equal(noCloth.update(1/60, 1), false);+ assert.equal(empty.controls.enabled, true);+ noCloth.dispose();+ assert.equal(empty.win.listenerCount(), 0);+});++test('invalid frames, duplicate geometry and missing grid points fail before acquiring input', () => {+ for (const [mutate, message] of [+ [f => { delete f.cloth.userData.curtain_rail_axis; }, /explicit Y-up curtain_rail_axis/],+ [f => { f.cloth.userData.curtain_depth_axis = [1, 0, 0]; }, /orthogonal unit/],+ [f => { f.root.rotation.y = 0.2; }, /identity scene root/],+ [f => { f.root.add(new THREE.Mesh(f.cloth.geometry, f.cloth.material)); }, /shares geometry/],+ [f => { f.cloth.geometry.getAttribute('uv').setXY(0, 0.01, 0.99); }, /missing material grid point/],+ [f => { f.cloth.userData.curtain_closed_width = 100; }, /header leaves roomBounds/],+ ]) {+ const f = curtainFixture();+ const original = f.cloth.geometry.getAttribute('position').array.slice();+ mutate(f);+ assert.throws(() => createCurtainInteraction(f), message);+ assert.deepEqual(f.cloth.geometry.getAttribute('position').array, original);+ assert.equal(f.win.listenerCount()+f.doc.listenerCount()+f.canvas.listenerCount()+f.motion.listenerCount(), 0);+ }+});diff --git a/tests/viewer/helpers.mjs b/tests/viewer/helpers.mjsnew file mode 100644index 0000000..c287afb--- /dev/null+++ b/tests/viewer/helpers.mjs@@ -0,0 +1,98 @@+import { createRequire } from 'node:module';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { resolve } from 'node:path';++// Run against the installed workspace when VIEWER_ROOT is set; otherwise the+// template must have its pinned dependencies installed. No DOM/WebGL shim is+// used for geometry or physics: these tests exercise the real Three classes.+export const viewerRoot = process.env.VIEWER_ROOT+ ? resolve(process.env.VIEWER_ROOT)+ : fileURLToPath(new URL('../../runtime/viewer/', import.meta.url));+export const THREE = createRequire(pathToFileURL(resolve(viewerRoot, 'package.json')))('three');+export const runtime = name => import(pathToFileURL(resolve(viewerRoot, 'src', name)));++export class Events {+ listeners = new Map();+ addEventListener(type, listener) {+ if (!this.listeners.has(type)) this.listeners.set(type, new Set());+ this.listeners.get(type).add(listener);+ }+ removeEventListener(type, listener) { this.listeners.get(type)?.delete(listener); }+ emit(type, properties = {}) {+ const event = { type, target: this, preventDefault() { this.prevented = true; },+ stopImmediatePropagation() { this.stopped = true; }, ...properties };+ for (const listener of [...(this.listeners.get(type) ?? [])]) {+ listener(event);+ if (event.stopped) break;+ }+ return event;+ }+ listenerCount(type) {+ return type ? this.listeners.get(type)?.size ?? 0+ : [...this.listeners.values()].reduce((sum, set) => sum + set.size, 0);+ }+}++export function curtainFixture({ hem = false } = {}) {+ const win = new Events();+ const doc = new Events();+ const motion = new Events();+ motion.matches = false;+ win.matchMedia = () => motion;+ doc.defaultView = win;+ doc.hidden = false;+ const canvas = new Events();+ canvas.ownerDocument = doc;+ canvas.style = { cursor: 'grab' };+ canvas.getBoundingClientRect = () => ({ left: 0, top: 0, width: 800, height: 600 });+ const captures = new Set();+ canvas.setPointerCapture = id => captures.add(id);+ canvas.hasPointerCapture = id => captures.has(id);+ canvas.releasePointerCapture = id => {+ captures.delete(id);+ canvas.emit('lostpointercapture', { pointerId: id });+ };+ const controls = { enabled: true };+ const root = new THREE.Group();+ const positions = [], uvs = [], indices = [];+ for (let row = 0; row <= 16; row++) for (let col = 0; col <= 50; col++) {+ const u = col/50, v = row/16;+ positions.push(10+u, 0.4+v*2, 20);+ uvs.push(u, 1-v*2);+ if (row < 16 && col < 50) {+ const a = row*51+col;+ indices.push(a, a+1, a+51, a+1, a+52, a+51);+ }+ }+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));+ geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));+ geometry.setAttribute('uv1', new THREE.Float32BufferAttribute(uvs, 2));+ geometry.setIndex(indices);+ geometry.computeVertexNormals();+ const material = new THREE.MeshStandardMaterial({ side: THREE.DoubleSide });+ const cloth = new THREE.Mesh(geometry, material);+ cloth.userData = { curtain_id: 'test-panel', curtain_part: 'cloth',+ curtain_tile: 1, curtain_fabric_width: 1, curtain_height: 2,+ curtain_open_width: 1, curtain_closed_width: 2,+ curtain_rail_axis: [1, 0, 0], curtain_depth_axis: [0, 0, 1], curtain_plane_origin: [10, 0, 20] };+ root.add(cloth);+ let hemMesh;+ if (hem) {+ const hemGeometry = new THREE.PlaneGeometry(1, 0.06, 4, 1).translate(10.5, 0.4, 20.02);+ hemMesh = new THREE.Mesh(hemGeometry, material);+ hemMesh.userData = { curtain_id: 'test-panel', curtain_part: 'hem', curtain_v: 0 };+ root.add(hemMesh);+ }+ const camera = new THREE.PerspectiveCamera(60, 800/600, 0.01, 100);+ camera.position.set(10.5, 1.4, 21.5);+ camera.lookAt(10.5, 1.4, 20);+ camera.updateWorldMatrix(true, false);+ const roomBounds = { min: [9, 0, 19], max: [15, 3, 22] };+ function pointerAt(world, pointerId = 1, extra = {}) {+ const p = new THREE.Vector3().fromArray(world).project(camera);+ return { target: canvas, clientX: (p.x+1)*400, clientY: (1-p.y)*300,+ pointerId, button: 0, isPrimary: true, pointerType: 'mouse', ...extra };+ }+ return { root, camera, canvas, controls, roomBounds, win, doc, motion, cloth, hemMesh, pointerAt };+}diff --git a/tests/viewer/manifest.test.mjs b/tests/viewer/manifest.test.mjsnew file mode 100644index 0000000..cb6ef81--- /dev/null+++ b/tests/viewer/manifest.test.mjs@@ -0,0 +1,50 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { runtime } from './helpers.mjs';+const { validateManifest, usesPolyHavenAPI } = await runtime('interior-manifest.js');++function manifest() {+ return { schemaVersion: 2, title: 'Asymmetric studio', sourceImageSize: [900, 1200], sourceKind: 'photograph',+ sourceImage: '/assets/reference.webp', model: '/assets/interior/room-runtime.glb',+ portableModel: '/assets/interior/room-portable.glb', blender: '/assets/interior/room-master.blend',+ environment: '/assets/interior/room-environment.exr', background: null,+ camera: { position: [1, 1.7, 3], target: [0, 1, 0], fov: 48 },+ views: { 'window-detail': { position: [-1, 2, 2], target: [0, 1, 0], label: 'Window detail' } },+ roomBounds: { min: [-3, 0, -4], max: [3, 3.2, 4] },+ toneMapping: 'neutral', exposure: 1,+ lighting: { model: 'ambient-bake+shadowed-sun-v1', sun: null },+ lightmaps: [{ id: 'room', url: '/assets/interior/lightmap-room.exr', intensity: Math.PI }],+ variants: [] };+}++test('API attribution is conditional on the actual manifest provenance, not scene identity', () => {+ const value = manifest();+ assert.equal(usesPolyHavenAPI(value), false);+ value.resourceCredit = { provider: 'Poly Haven', apiDerived: false };+ assert.equal(usesPolyHavenAPI(value), false);+ value.resourceCredit.apiDerived = true;+ assert.equal(usesPolyHavenAPI(value), true);+ value.resourceCredit.provider = 'Procedural';+ assert.equal(usesPolyHavenAPI(value), false);+});++test('ambiguous lighting, unsafe paths, invalid camera frames and duplicate identities fail actionably', () => {+ for (const [mutate, expected] of [+ [m => { m.lighting.model = 'full-sun-bake'; }, /full-sun bakes/],+ [m => { delete m.lighting.sun; }, /sun: null/],+ [m => { m.sourceImage = '/assets/../private.png'; }, /inside \/assets/],+ [m => { m.model = '/assets/%2e%2e/room.glb'; }, /inside \/assets/],+ [m => { m.model = 'https://example.org/model.glb'; }, /local \/assets/],+ [m => { m.sourceImageSize = [0, 100]; }, /sourceImageSize/],+ [m => { m.camera.target = [...m.camera.position]; }, /equal to its target/],+ [m => { m.views.source = structuredClone(m.camera); }, /source view is implicit/],+ [m => { m.roomBounds.max[0] = m.roomBounds.min[0]; }, /roomBounds/],+ [m => { m.lightmaps.push({ ...m.lightmaps[0] }); }, /duplicate id/],+ [m => { m.variants = [{ id: 'one', label: 'One', color: '#abcdef' }, { id: 'one', label: 'Again', color: '#123456' }]; }, /unique ids/],+ [m => { m.variants = [{ id: 'base', label: 'Base', color: '#000000' }, { id: 'white', label: 'White', color: '#ffffff' }]; }, /nonzero RGB/],+ ]) {+ const value = manifest();+ mutate(value);+ assert.throws(() => validateManifest(value), expected);+ }+});diff --git a/tests/viewer/navigation-lightmaps.test.mjs b/tests/viewer/navigation-lightmaps.test.mjsnew file mode 100644index 0000000..927fb5b--- /dev/null+++ b/tests/viewer/navigation-lightmaps.test.mjs@@ -0,0 +1,97 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { THREE, runtime } from './helpers.mjs';+const { createInteriorNavigation } = await runtime('interior-navigation.js');+const { prepareLightmaps } = await runtime('interior-lightmaps.js');++function controlsFor(camera, emitChange) {+ const controls = new THREE.EventDispatcher();+ controls.target = new THREE.Vector3(12, 2, 22);+ controls.minDistance = 0;+ controls.maxDistance = Infinity;+ controls.minPolarAngle = 0;+ controls.maxPolarAngle = Math.PI;+ controls.update = function(delta) {+ camera.position.x = 14.8 + 1e-9;+ this.target.y = 4 + 1e-9;+ if (emitChange) this.dispatchEvent({ type: 'change' });+ return emitChange;+ };+ return controls;+}++for (const emitsChange of [true, false]) test(`navigation clamps every update, including sub-EPS change=${emitsChange}`, () => {+ const camera = new THREE.PerspectiveCamera();+ camera.position.set(12, 2, 23);+ const controls = controlsFor(camera, emitsChange);+ const originalUpdate = controls.update;+ const bounds = { min: [10, 0, 20], max: [15, 4, 25] };+ const nav = createInteriorNavigation(camera, controls, bounds);+ assert.equal(controls.update(0.01), true);+ const snapshot = nav.snapshot();+ assert.equal(snapshot.safety.cameraInBounds, true);+ assert.equal(snapshot.safety.targetInBounds, true);+ assert.equal(snapshot.safety.atBoundary, true);+ assert.equal(camera.position.x, 14.8);+ assert.equal(controls.target.y, 3.85);+ // The wrapper copies caller-owned bounds, it does not mutate the manifest.+ assert.deepEqual(bounds, { min: [10, 0, 20], max: [15, 4, 25] });+ nav.dispose();+ nav.dispose();+ assert.equal(controls.update, originalUpdate);+ assert.equal(controls.minDistance, 0);+ assert.equal(controls.maxDistance, Infinity);+ camera.position.set(100, 100, 100);+ controls.dispatchEvent({ type: 'change' });+ assert.equal(camera.position.x, 100);+});++test('tiny valid rooms keep a nonzero view direction without escaping bounds', () => {+ const camera = new THREE.PerspectiveCamera();+ camera.position.set(0.255, 0.255, 0.255);+ const controls = controlsFor(camera, false);+ controls.target.copy(camera.position);+ const nav = createInteriorNavigation(camera, controls, { min: [0, 0, 0], max: [0.51, 0.51, 0.51] });+ const snapshot = nav.snapshot();+ assert.equal(snapshot.safety.cameraInBounds, true);+ assert.equal(snapshot.safety.targetInBounds, true);+ assert.ok(snapshot.safety.distance > 0.05);+ nav.dispose();+});++test('invalid room bounds do not replace controls update', () => {+ const camera = new THREE.PerspectiveCamera();+ const controls = controlsFor(camera, false);+ const update = controls.update;+ assert.throws(() => createInteriorNavigation(camera, controls, { min: [0, 0, 0], max: [0.1, 3, 3] }), /roomBounds/);+ assert.equal(controls.update, update);+});++test('lightmap orientation swaps decoded rows once, including wrappers sharing pixels', () => {+ const data = new Float32Array([+ 1, 2, 3, 4, 5, 6, 7, 8,+ 11, 12, 13, 14, 15, 16, 17, 18,+ 21, 22, 23, 24, 25, 26, 27, 28,+ ]);+ const texture = new THREE.DataTexture(data, 2, 3, THREE.RGBAFormat, THREE.FloatType);+ const clone = texture.clone();+ const original = data.slice();+ const atlas = { texture, intensity: Math.PI };+ prepareLightmaps([atlas, { texture: clone, intensity: Math.PI }]);+ assert.deepEqual(data, new Float32Array([...original.slice(16), ...original.slice(8, 16), ...original.slice(0, 8)]));+ const oriented = data.slice();+ prepareLightmaps([atlas]);+ assert.deepEqual(data, oriented);+ assert.equal(texture.channel, 1);+ assert.equal(clone.channel, 1);+ assert.equal(texture.flipY, false);+ assert.equal(texture.colorSpace, THREE.NoColorSpace);+ const otherSession = new THREE.DataTexture(original.slice(), 2, 3, THREE.RGBAFormat, THREE.FloatType);+ prepareLightmaps([{ texture: otherSession }]);+ assert.deepEqual(otherSession.image.data, oriented);+});++test('malformed atlas cannot be silently bound as RGBA', () => {+ const texture = new THREE.DataTexture(new Float32Array(3), 1, 1);+ assert.throws(() => prepareLightmaps([{ texture }]), /RGBA/);+});diff --git a/tools/audit_delivery.py b/tools/audit_delivery.pynew file mode 100755index 0000000..3bb8ccb--- /dev/null+++ b/tools/audit_delivery.py@@ -0,0 +1,157 @@+#!/usr/bin/env python3+"""Rehash declared source/runtime/portable/native assets and runtime dependencies."""+import os, sys+sys.dont_write_bytecode = True+root = os.environ.get("IMG2_HOME")+if root: sys.path.insert(0, os.path.join(root, "harness"))+else:+ try: import _img2_local; sys.path.insert(0, _img2_local.CORE)+ except ImportError: sys.exit("img2: core not linked - run `img2 sync`")+from img2_core import require_core_api+require_core_api(1)++from pathlib import Path+from urllib.parse import urlsplit++from audit_support import (AuditFailure, Parser, check_pin, confined_file, emit, fields,+ file_hash, input_path, load_receipt, persist, pin, read_json,+ sha_value, string_list, text, workspace_path)++GATE = "interior-delivery"+RECEIPT = "delivery-audit.json"+STATE_KEY = "deliveryAudit"+LIMITATIONS = [+ "Hashes prove current byte identity against this declared contract, not provenance or visual fidelity.",+ "Runtime sidecars are the declared dependency set; this audit does not execute a viewer or discover undeclared network/runtime dependencies.",+ "Portable and native consumer reopening, Khronos glTF validity, packed native resources, interaction behavior, and matched visual comparisons require separate human/agent evidence.",+ "A distinct portable file is not proof that runtime interaction, lighting, or PBR behavior survives export; the portable limitations remain part of delivery.",+]+++def validate_contract(contract, contract_path):+ fields(contract, ["schemaVersion", "root", "assets", "runtime", "portable", "native", "limitations"], [], "delivery contract")+ if type(contract["schemaVersion"]) is not int or contract["schemaVersion"] != 1:+ raise ValueError("contract schemaVersion must be 1")+ root_text = text(contract["root"], "contract.root")+ if "\\" in root_text or urlsplit(root_text).scheme or urlsplit(root_text).netloc or "\x00" in root_text or "?" in root_text or "#" in root_text:+ raise ValueError("contract.root must be a local filesystem directory, not a URL")+ root = Path(root_text)+ if not root.is_absolute():+ root = contract_path.parent / root+ root = root.resolve()+ if not root.is_dir():+ raise AuditFailure(f"asset root is not an existing directory: {root}")+ string_list(contract["limitations"], "contract.limitations", nonempty=True)+ rows = contract["assets"]+ if not isinstance(rows, list) or not rows:+ raise ValueError("contract.assets must be a nonempty array")+ assets, paths, files = {}, set(), set()+ roles = {role: [] for role in ("source", "runtime", "portable", "native", "sidecar")}+ for row in rows:+ fields(row, ["id", "role", "path", "sha256"], [], "asset")+ identifier = text(row["id"], "asset.id")+ if identifier in assets:+ raise ValueError(f"duplicate asset id: {identifier}")+ role = text(row["role"], "asset.role")+ if role not in roles:+ raise ValueError(f"unsupported asset role: {role}")+ expected = sha_value(row["sha256"], f"{identifier}.sha256")+ path = confined_file(root, row["path"])+ # Resolve symlinks and filesystem identity too: aliases are not separate deliveries.+ stat = path.stat()+ identity = (stat.st_dev, stat.st_ino)+ if path in paths or identity in files:+ raise ValueError(f"duplicate asset path or file alias: {row['path']}")+ paths.add(path)+ files.add(identity)+ roles[role].append(identifier)+ assets[identifier] = {"id": identifier, "role": role, "path": row["path"],+ "resolvedPath": str(path), "expectedSha256": expected}+ for role in ("source", "runtime", "portable", "native"):+ if len(roles[role]) != 1:+ raise ValueError(f"contract needs exactly one {role} asset")+ for role in ("runtime", "portable", "native"):+ required = ["asset"] + ({"runtime": ["sidecars"], "portable": ["limitations"], "native": []}[role])+ section = fields(contract[role], required, [], role)+ identifier = text(section["asset"], f"{role}.asset")+ if identifier != roles[role][0]:+ raise ValueError(f"{role}.asset must reference the declared {role} role")+ sidecars = string_list(contract["runtime"]["sidecars"], "runtime.sidecars")+ if len(set(sidecars)) != len(sidecars) or set(sidecars) != set(roles["sidecar"]):+ raise ValueError("runtime.sidecars must reference each sidecar exactly once and no other asset")+ string_list(contract["portable"]["limitations"], "portable.limitations", nonempty=True)+ return root, assets+++def evaluate(contract_path):+ contract_pin = pin(contract_path)+ contract = read_json(contract_path)+ root, assets = validate_contract(contract, contract_path)+ reasons = []+ for asset in assets.values():+ asset["sha256"] = file_hash(asset["resolvedPath"])+ asset["byteLength"] = Path(asset["resolvedPath"]).stat().st_size+ if asset["sha256"] != asset["expectedSha256"]:+ reasons.append(f"{asset['id']}: current SHA256 differs from contract")+ runtime = assets[contract["runtime"]["asset"]]+ portable = assets[contract["portable"]["asset"]]+ if runtime["sha256"] == portable["sha256"]:+ reasons.append("runtime and portable are byte-identical; cannot masquerade as separate representations")+ # Re-resolve names after hashing to catch symlink replacement or root changes.+ for asset in assets.values():+ current = confined_file(root, asset["path"])+ if str(current) != asset["resolvedPath"]:+ raise AuditFailure(f"asset path changed during audit: {asset['id']}")+ check_pin(contract_pin, "contract")+ return {"schemaVersion": 1, "audit": GATE, "passed": not reasons, "reasons": reasons,+ "inputs": {"contract": contract_pin}, "root": str(root), "assets": list(assets.values()),+ "runtime": contract["runtime"], "portable": contract["portable"], "native": contract["native"],+ "declaredLimitations": contract["limitations"], "limitations": LIMITATIONS,+ "consumerReopeningEvaluated": False, "visualComparisonEvaluated": False,+ "khronosValidityEvaluated": False}+++def gate(workspace):+ receipt = load_receipt(workspace, RECEIPT, STATE_KEY)+ if receipt.get("audit") != GATE:+ raise ValueError("wrong audit receipt kind")+ inputs = fields(receipt.get("inputs"), ["contract"], [], "receipt.inputs")+ contract = check_pin(inputs["contract"], "contract")+ current = evaluate(contract)+ if current["root"] != receipt.get("root") or current["assets"] != receipt.get("assets"):+ current["passed"] = False+ current["reasons"].append("delivery assets or resolved paths changed since audit")+ if not receipt["passed"]:+ current["passed"] = False+ current["reasons"].append("stored delivery audit was negative; run the normal audit after repair")+ return current+++def main(argv=None):+ argv = sys.argv[1:] if argv is None else argv+ gate_mode = "--gate" in argv+ try:+ parser = Parser(description=__doc__)+ parser.add_argument("--workspace", required=True)+ parser.add_argument("--contract")+ parser.add_argument("--gate", action="store_true")+ args = parser.parse_args(argv)+ workspace = workspace_path(args.workspace)+ if args.gate:+ if args.contract:+ raise ValueError("--gate reads the pinned contract; do not supply --contract")+ report = gate(workspace)+ else:+ if not args.contract:+ raise ValueError("normal audit requires --contract")+ report = evaluate(input_path(args.contract))+ persist(workspace, RECEIPT, STATE_KEY, report)+ return emit(GATE, "pass" if report["passed"] else "fail", report["reasons"], report, gate_mode=gate_mode)+ except AuditFailure as exc:+ return emit(GATE, "fail", [str(exc)], {}, gate_mode=gate_mode)+ except (ValueError, OSError, RuntimeError, RecursionError) as exc:+ return emit(GATE, "error", [str(exc)], {}, gate_mode=gate_mode)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/audit_materials.py b/tools/audit_materials.pynew file mode 100755index 0000000..0fc261b--- /dev/null+++ b/tools/audit_materials.py@@ -0,0 +1,460 @@+#!/usr/bin/env python3+"""Audit declared material wiring and factors, never visual realism or texture pixels."""+import os, sys+sys.dont_write_bytecode = True+root = os.environ.get("IMG2_HOME")+if root: sys.path.insert(0, os.path.join(root, "harness"))+else:+ try: import _img2_local; sys.path.insert(0, _img2_local.CORE)+ except ImportError: sys.exit("img2: core not linked - run `img2 sync`")+from img2_core import require_core_api+require_core_api(1)++import base64+import binascii+import struct++from audit_support import (AuditFailure, JSON_LIMIT, Parser, check_pin, confined_file,+ decode_json, emit, factor, fields, file_hash, input_path,+ integer, load_receipt, object_value, persist, pin,+ read_json, text, workspace_path)++GATE = "interior-materials"+RECEIPT = "material-audit.json"+STATE_KEY = "materialAudit"+LIMITATIONS = [+ "Only explicitly declared policy expectations are checked; omitted expectations are not certified.",+ "Texture pixels and image decoding are not evaluated. A scalar roughness factor is multiplied by the texture's green channel and does not prove effective roughness.",+ "Color-space interpretation, texel density, UV orientation, visible textile identity, lighting, and frontal/grazing appearance require separate consumer and visual review.",+ "This is a bounded material-wiring audit, not a Khronos validator, scene-visibility proof, native reopen, or runtime-render test.",+]+++def array(doc, key):+ value = doc.get(key, [])+ if not isinstance(value, list):+ raise ValueError(f"glTF {key} must be an array")+ return value+++def indexed(values, index, label):+ integer(index, label)+ if index >= len(values):+ raise ValueError(f"{label} index {index} out of range")+ return object_value(values[index], label)+++def validate_policy(value):+ fields(value, ["schemaVersion", "materials"], [], "policy")+ if type(value["schemaVersion"]) is not int or value["schemaVersion"] != 1:+ raise ValueError("policy schemaVersion must be 1")+ rows = value["materials"]+ if not isinstance(rows, list) or not rows:+ raise ValueError("policy materials must be a nonempty array")+ names = set()+ booleans = {"requireBaseColorTexture", "requireNormalTexture", "requireRoughnessTexture"}+ numbers = {"minRoughnessFactor", "maxMetallicFactor", "maxSheenColorFactor"}+ for row in rows:+ fields(row, ["name"], booleans | numbers | {"texCoord"}, "material policy")+ name = text(row["name"], "material name")+ if name in names:+ raise ValueError(f"duplicate material policy target: {name}")+ names.add(name)+ for key in booleans & row.keys():+ if type(row[key]) is not bool:+ raise ValueError(f"{key} must be boolean")+ for key in numbers & row.keys():+ factor(row[key], key)+ if "texCoord" in row:+ integer(row["texCoord"], "texCoord")+ return rows+++class GLB:+ """Read only bounded JSON and chunk headers; binary ranges are checked by offsets."""+ def __init__(self, path):+ self.path = path+ self.resources = {}+ self.bin_length = None+ size = path.stat().st_size+ with path.open("rb") as handle:+ header = handle.read(12)+ if len(header) != 12:+ raise ValueError("truncated GLB header")+ magic, version, declared = struct.unpack("<4sII", header)+ if magic != b"glTF" or version != 2 or declared != size or size % 4:+ raise ValueError("invalid GLB magic, version, alignment, or total byte length")+ offset, chunk_number, document = 12, 0, None+ while offset < size:+ raw = handle.read(8)+ if len(raw) != 8:+ raise ValueError("truncated GLB chunk header")+ length, kind = struct.unpack("<II", raw)+ if length % 4 or offset + 8 + length > size:+ raise ValueError("invalid or truncated GLB chunk length")+ if chunk_number == 0 and kind != 0x4E4F534A:+ raise ValueError("first GLB chunk must be JSON")+ if kind == 0x4E4F534A:+ if document is not None or chunk_number != 0 or not 0 < length <= JSON_LIMIT:+ raise ValueError("duplicate, misplaced, empty, or oversized GLB JSON chunk")+ document = decode_json(handle.read(length).decode("utf-8"), "GLB JSON")+ elif kind == 0x004E4942:+ if self.bin_length is not None or chunk_number != 1:+ raise ValueError("duplicate or misplaced GLB BIN chunk")+ self.bin_length = length+ handle.seek(length, 1)+ else:+ # glTF permits unknown trailing chunks; their bounds still matter.+ handle.seek(length, 1)+ offset += 8 + length+ chunk_number += 1+ self.doc = object_value(document, "glTF document")+ asset = object_value(self.doc.get("asset"), "glTF asset")+ if asset.get("version") != "2.0" or asset.get("minVersion", "2.0") != "2.0":+ raise ValueError("only glTF 2.0 is supported")+ for key in ("extensionsUsed", "extensionsRequired"):+ extensions = array(self.doc, key)+ for extension in extensions:+ text(extension, key)+ if len(set(extensions)) != len(extensions):+ raise ValueError(f"duplicate {key} entry")+ if not set(self.doc.get("extensionsRequired", [])).issubset(self.doc.get("extensionsUsed", [])):+ raise ValueError("extensionsRequired must be included in extensionsUsed")+ self.buffers = array(self.doc, "buffers")+ self.views = array(self.doc, "bufferViews")+ self.accessors = array(self.doc, "accessors")+ self.images = array(self.doc, "images")+ self.textures = array(self.doc, "textures")+ self.materials = array(self.doc, "materials")+ self.meshes = array(self.doc, "meshes")+ for index, buffer in enumerate(self.buffers):+ object_value(buffer, "buffer")+ length = integer(buffer.get("byteLength"), "buffer.byteLength", 1)+ if "uri" in buffer:+ resource = self.resource(buffer["uri"], "buffer")+ if resource["byteLength"] < length:+ raise ValueError(f"buffer {index} exceeds resource bytes")+ elif index != 0 or self.bin_length is None or not length <= self.bin_length <= length + 3:+ raise ValueError(f"buffer {index} has no valid GLB BIN storage")+ if self.bin_length is not None and (not self.buffers or "uri" in self.buffers[0]):+ raise ValueError("GLB BIN chunk has no corresponding buffer 0")+ for index in range(len(self.views)):+ self.view(index)+ # Unselected resources are still part of this delivered GLB's trust boundary.+ for index in range(len(self.images)):+ self.image(index)+ for index in range(len(self.textures)):+ self.texture({"index": index})++ def resource(self, uri, label):+ text(uri, f"{label} URI")+ if uri.startswith("data:"):+ header, separator, encoded = uri.partition(",")+ if not separator or not header.endswith(";base64"):+ raise ValueError("only base64 glTF data URIs are supported")+ media = header[5:-7]+ allowed = ({"application/octet-stream", "application/gltf-buffer"} if label == "buffer"+ else {"image/png", "image/jpeg", "image/webp", "image/ktx2"})+ if media not in allowed:+ raise ValueError(f"unsupported {label} data URI media type: {media}")+ try:+ data = base64.b64decode(encoded, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise ValueError("invalid base64 resource") from exc+ if not data:+ raise ValueError("empty data URI resource")+ return {"storage": "data-uri", "byteLength": len(data), "mimeType": media}+ path = confined_file(self.path.parent, uri, uri=True)+ digest = file_hash(path)+ item = {"path": str(path), "sha256": digest}+ if str(path) in self.resources and self.resources[str(path)] != item:+ raise AuditFailure(f"resource changed during audit: {path}")+ self.resources[str(path)] = item+ return {"storage": "external", "path": str(path), "sha256": digest,+ "byteLength": path.stat().st_size}++ def view(self, index):+ view = indexed(self.views, index, "bufferView")+ buffer = indexed(self.buffers, view.get("buffer"), "bufferView.buffer")+ offset = integer(view.get("byteOffset", 0), "bufferView.byteOffset")+ length = integer(view.get("byteLength"), "bufferView.byteLength", 1)+ if offset + length > buffer["byteLength"]:+ raise ValueError("bufferView exceeds buffer bytes")+ if "byteStride" in view:+ stride = integer(view["byteStride"], "bufferView.byteStride", 4)+ if stride > 252 or stride % 4:+ raise ValueError("invalid bufferView byteStride")+ if "EXT_meshopt_compression" in object_value(view.get("extensions", {}), "bufferView extensions"):+ raise ValueError("compressed bufferViews require separate decoded accessor inspection")+ return view++ def accessor(self, index, semantic):+ accessor = indexed(self.accessors, index, semantic)+ expected = "VEC2" if semantic.startswith("TEXCOORD_") else "VEC3"+ if accessor.get("type") != expected:+ raise ValueError(f"{semantic} accessor must be {expected}")+ component = accessor.get("componentType")+ sizes = {5120: 1, 5121: 1, 5122: 2, 5123: 2, 5126: 4}+ if type(component) is not int or component not in sizes:+ raise ValueError(f"invalid {semantic} componentType")+ normalized = accessor.get("normalized", False)+ if type(normalized) is not bool:+ raise ValueError("accessor.normalized must be boolean")+ quantized = "KHR_mesh_quantization" in self.doc.get("extensionsUsed", [])+ if semantic.startswith("TEXCOORD_"):+ allowed = component == 5126 and not normalized or component in (5121, 5123) and normalized+ if not allowed and not (quantized and component != 5126):+ raise ValueError("UV accessor needs floats or normalized unsigned integers (or declared quantization)")+ elif component != 5126 and not quantized:+ raise ValueError("POSITION accessor requires floats or declared quantization")+ count = integer(accessor.get("count"), "accessor.count", 1)+ width = sizes[component] * (2 if expected == "VEC2" else 3)+ offset = integer(accessor.get("byteOffset", 0), "accessor.byteOffset")+ if offset % sizes[component]:+ raise ValueError("misaligned accessor byteOffset")+ if "bufferView" in accessor:+ view = self.view(accessor["bufferView"])+ stride = view.get("byteStride", width)+ if stride < width or stride % sizes[component] or (view.get("byteOffset", 0) + offset) % sizes[component]:+ raise ValueError("invalid accessor stride or alignment")+ if offset + (count - 1) * stride + width > view["byteLength"]:+ raise ValueError(f"{semantic} accessor exceeds bufferView bytes")+ elif offset:+ raise ValueError("accessor without bufferView cannot have byteOffset")+ if "sparse" in accessor:+ sparse = object_value(accessor["sparse"], "sparse accessor")+ sparse_count = integer(sparse.get("count"), "sparse.count", 1)+ if sparse_count > count:+ raise ValueError("sparse accessor count exceeds accessor count")+ for key in ("indices", "values"):+ item = object_value(sparse.get(key), f"sparse.{key}")+ view = self.view(item.get("bufferView"))+ item_width = width+ if key == "indices":+ if type(item.get("componentType")) is not int or item["componentType"] not in (5121, 5123, 5125):+ raise ValueError("invalid sparse index componentType")+ item_width = {5121: 1, 5123: 2, 5125: 4}[item["componentType"]]+ start = integer(item.get("byteOffset", 0), "sparse.byteOffset")+ if "byteStride" in view or start + sparse_count * item_width > view["byteLength"]:+ raise ValueError("invalid sparse accessor byte range")+ return {"accessor": index, "count": count, "type": expected,+ "componentType": component, "normalized": normalized}++ def image(self, index):+ image = indexed(self.images, index, "texture image")+ if ("uri" in image) == ("bufferView" in image):+ raise ValueError("image must have exactly one of uri or bufferView")+ if "uri" in image:+ return dict(self.resource(image["uri"], "image"), image=index)+ mime = image.get("mimeType")+ if mime not in ("image/png", "image/jpeg", "image/webp", "image/ktx2"):+ raise ValueError("embedded image needs a supported mimeType")+ view = self.view(image["bufferView"])+ if "byteStride" in view:+ raise ValueError("image bufferView cannot be strided")+ return {"image": index, "storage": "bufferView", "bufferView": image["bufferView"],+ "byteLength": view["byteLength"], "mimeType": mime}++ def texture(self, info):+ object_value(info, "textureInfo")+ texture = indexed(self.textures, info.get("index"), "textureInfo.index")+ coord = integer(info.get("texCoord", 0), "textureInfo.texCoord")+ extensions = object_value(info.get("extensions", {}), "textureInfo.extensions")+ if "KHR_texture_transform" in extensions:+ transform = object_value(extensions["KHR_texture_transform"], "texture transform")+ coord = integer(transform.get("texCoord", coord), "texture transform texCoord")+ for key, length in (("offset", 2), ("scale", 2)):+ if key in transform:+ vector(transform[key], length, f"texture transform {key}", bounded=False)+ if "rotation" in transform and type(transform["rotation"]) not in (int, float):+ raise ValueError("texture transform rotation must be numeric")+ images = []+ if "source" in texture:+ images.append(self.image(texture["source"]))+ tex_extensions = object_value(texture.get("extensions", {}), "texture.extensions")+ for name in ("KHR_texture_basisu", "EXT_texture_webp", "MSFT_texture_dds"):+ if name in tex_extensions:+ if name == "MSFT_texture_dds":+ raise ValueError("DDS texture source inspection is unsupported")+ ext = object_value(tex_extensions[name], name)+ images.append(dict(self.image(ext.get("source")), extension=name))+ if not images:+ raise ValueError("bound texture has no supported image source")+ if "sampler" in texture:+ indexed(array(self.doc, "samplers"), texture["sampler"], "texture.sampler")+ return {"texture": info["index"], "texCoord": coord, "images": images}+++def vector(value, length, label, bounded=True):+ if not isinstance(value, list) or len(value) != length:+ raise ValueError(f"{label} must have {length} components")+ for item in value:+ if bounded:+ factor(item, label)+ elif type(item) not in (int, float):+ raise ValueError(f"{label} components must be numeric")+ return value+++def material_maps(material):+ pbr = object_value(material.get("pbrMetallicRoughness", {}), "pbrMetallicRoughness")+ maps = {key: pbr[key] for key in ("baseColorTexture", "metallicRoughnessTexture") if key in pbr}+ maps.update({key: material[key] for key in ("normalTexture", "occlusionTexture", "emissiveTexture") if key in material})+ # Inspect extension textureInfo objects as well, rather than silently ignoring sheen maps.+ for name, extension in object_value(material.get("extensions", {}), "material extensions").items():+ object_value(extension, name)+ for key, info in extension.items():+ if key.endswith("Texture"):+ maps[f"{name}.{key}"] = info+ return pbr, maps+++def evaluate(glb_path, policy_path):+ inputs = {"glb": pin(glb_path), "policy": pin(policy_path)}+ policy = validate_policy(read_json(policy_path))+ glb = GLB(glb_path)+ reasons, results = [], []+ names = {}+ for index, material in enumerate(glb.materials):+ object_value(material, "material")+ if "name" in material:+ name = material["name"]+ if not isinstance(name, str):+ raise ValueError("glTF material name must be a string")+ names.setdefault(name, []).append(index)+ primitives = {}+ for mesh_index, mesh in enumerate(glb.meshes):+ object_value(mesh, "mesh")+ rows = mesh.get("primitives")+ if not isinstance(rows, list) or not rows:+ raise ValueError("mesh.primitives must be a nonempty array")+ for primitive_index, primitive in enumerate(rows):+ object_value(primitive, "primitive")+ if "material" in primitive:+ index = primitive["material"]+ indexed(glb.materials, index, "primitive.material")+ primitives.setdefault(index, []).append((mesh_index, primitive_index, primitive))+ for rule in policy:+ name = rule["name"]+ matches = names.get(name, [])+ if len(matches) != 1:+ reasons.append(f"{name}: expected exactly one material target; found {len(matches)}")+ continue+ index = matches[0]+ material = glb.materials[index]+ pbr, maps = material_maps(material)+ roughness = factor(pbr.get("roughnessFactor", 1), "roughnessFactor")+ metallic = factor(pbr.get("metallicFactor", 1), "metallicFactor")+ base_color = vector(pbr.get("baseColorFactor", [1, 1, 1, 1]), 4, "baseColorFactor")+ sheen = object_value(material.get("extensions", {}).get("KHR_materials_sheen", {}), "sheen")+ sheen_color = vector(sheen.get("sheenColorFactor", [0, 0, 0]), 3, "sheenColorFactor")+ sheen_roughness = factor(sheen.get("sheenRoughnessFactor", 0), "sheenRoughnessFactor")+ bound = {key: glb.texture(info) for key, info in maps.items()}+ if "normalTexture" in maps:+ scale = maps["normalTexture"].get("scale", 1)+ if type(scale) not in (int, float):+ raise ValueError("normalTexture.scale must be a finite number")+ bound["normalTexture"]["scale"] = scale+ if "occlusionTexture" in maps:+ bound["occlusionTexture"]["strength"] = factor(maps["occlusionTexture"].get("strength", 1), "occlusion strength")+ for requirement, map_key in (("requireBaseColorTexture", "baseColorTexture"),+ ("requireNormalTexture", "normalTexture"),+ ("requireRoughnessTexture", "metallicRoughnessTexture")):+ if rule.get(requirement) is True and map_key not in bound:+ reasons.append(f"{name}: required {map_key} is not bound")+ if "minRoughnessFactor" in rule and roughness < rule["minRoughnessFactor"]:+ reasons.append(f"{name}: roughnessFactor {roughness} is below declared minimum")+ if "maxMetallicFactor" in rule and metallic > rule["maxMetallicFactor"]:+ reasons.append(f"{name}: metallicFactor {metallic} exceeds declared maximum")+ if "maxSheenColorFactor" in rule and max(sheen_color) > rule["maxSheenColorFactor"]:+ reasons.append(f"{name}: sheenColorFactor {sheen_color} exceeds declared maximum")+ uses = primitives.get(index, [])+ if not uses:+ reasons.append(f"{name}: selected material is not bound to any mesh primitive")+ primitive_results = []+ for mesh_index, primitive_index, primitive in uses:+ if "KHR_draco_mesh_compression" in object_value(primitive.get("extensions", {}), "primitive extensions"):+ raise ValueError("Draco primitive inspection requires decoded geometry")+ attributes = object_value(primitive.get("attributes"), "primitive attributes")+ position = glb.accessor(attributes.get("POSITION"), "POSITION")+ needed = {item["texCoord"] for item in bound.values()}+ if "texCoord" in rule:+ needed.add(rule["texCoord"])+ for key, item in bound.items():+ if item["texCoord"] != rule["texCoord"]:+ reasons.append(f"{name}: {key} uses TEXCOORD_{item['texCoord']}, policy requires TEXCOORD_{rule['texCoord']}")+ uvs = {}+ for coord in sorted(needed):+ semantic = f"TEXCOORD_{coord}"+ if semantic not in attributes:+ reasons.append(f"{name}: mesh {mesh_index} primitive {primitive_index} lacks {semantic}")+ continue+ uv = glb.accessor(attributes[semantic], semantic)+ if uv["count"] != position["count"]:+ raise ValueError(f"{name}: {semantic} count does not match POSITION")+ uvs[semantic] = uv+ primitive_results.append({"mesh": mesh_index, "primitive": primitive_index, "uvAttributes": uvs})+ results.append({"name": name, "material": index, "expectations": rule,+ "factors": {"roughnessFactor": roughness, "metallicFactor": metallic,+ "baseColorFactor": base_color, "sheenColorFactor": sheen_color,+ "sheenRoughnessFactor": sheen_roughness},+ "textures": bound, "primitives": primitive_results})+ for label, value in inputs.items():+ check_pin(value, label)+ for resource in glb.resources.values():+ check_pin(resource, "external resource")+ return {"schemaVersion": 1, "audit": GATE, "passed": not reasons, "reasons": reasons,+ "inputs": inputs, "resources": sorted(glb.resources.values(), key=lambda item: item["path"]),+ "materials": results, "texturePixelsEvaluated": False, "limitations": LIMITATIONS}+++def gate(workspace):+ receipt = load_receipt(workspace, RECEIPT, STATE_KEY)+ if receipt.get("audit") != GATE:+ raise ValueError("wrong audit receipt kind")+ inputs = fields(receipt.get("inputs"), ["glb", "policy"], [], "receipt.inputs")+ glb = check_pin(inputs["glb"], "GLB")+ policy = check_pin(inputs["policy"], "policy")+ resources = receipt.get("resources")+ if not isinstance(resources, list):+ raise ValueError("receipt resources must be an array")+ for resource in resources:+ check_pin(resource, "external resource")+ current = evaluate(glb, policy)+ if current["resources"] != resources:+ raise AuditFailure("external resource bindings changed since audit")+ if not receipt["passed"]:+ current["passed"] = False+ current["reasons"].append("stored material audit was negative; run the normal audit after repair")+ return current+++def main(argv=None):+ argv = sys.argv[1:] if argv is None else argv+ gate_mode = "--gate" in argv+ try:+ parser = Parser(description=__doc__)+ parser.add_argument("--workspace", required=True)+ parser.add_argument("--glb")+ parser.add_argument("--policy")+ parser.add_argument("--gate", action="store_true")+ args = parser.parse_args(argv)+ workspace = workspace_path(args.workspace)+ if args.gate:+ if args.glb or args.policy:+ raise ValueError("--gate reads pinned inputs; do not supply --glb or --policy")+ report = gate(workspace)+ else:+ if not args.glb or not args.policy:+ raise ValueError("normal audit requires --glb and --policy")+ report = evaluate(input_path(args.glb), input_path(args.policy))+ persist(workspace, RECEIPT, STATE_KEY, report)+ return emit(GATE, "pass" if report["passed"] else "fail", report["reasons"], report, gate_mode=gate_mode)+ except AuditFailure as exc:+ return emit(GATE, "fail", [str(exc)], {}, gate_mode=gate_mode)+ except (ValueError, OSError, RuntimeError, RecursionError) as exc:+ return emit(GATE, "error", [str(exc)], {}, gate_mode=gate_mode)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/audit_support.py b/tools/audit_support.pynew file mode 100644index 0000000..d01697d--- /dev/null+++ b/tools/audit_support.py@@ -0,0 +1,258 @@+"""Shared, stdlib-only validation and receipt I/O for the two interior audits."""+import argparse+import hashlib+import json+import math+import os+from pathlib import Path, PurePosixPath+import re+import tempfile+from urllib.parse import unquote, urlsplit++from img2_core.paths import resolve_workspace+from img2_core.state import update_plugin_state++JSON_LIMIT = 16 * 1024 * 1024+HASH_PATTERN = re.compile(r"[0-9a-fA-F]{64}\Z")+++class AuditFailure(ValueError):+ """An evaluated, negative audit (as opposed to malformed input)."""+++class Parser(argparse.ArgumentParser):+ def error(self, message):+ raise ValueError(message)+++def object_value(value, label):+ if not isinstance(value, dict):+ raise ValueError(f"{label} must be an object")+ return value+++def fields(value, required, optional, label):+ object_value(value, label)+ missing = set(required) - value.keys()+ extra = value.keys() - set(required) - set(optional)+ if missing or extra:+ raise ValueError(f"{label}: missing fields {sorted(missing)}, unknown fields {sorted(extra)}")+ return value+++def text(value, label):+ if not isinstance(value, str) or not value.strip() or "\x00" in value:+ raise ValueError(f"{label} must be nonempty text without NUL")+ return value+++def integer(value, label, minimum=0):+ if type(value) is not int or value < minimum:+ raise ValueError(f"{label} must be an integer >= {minimum}")+ return value+++def factor(value, label):+ if type(value) not in (int, float) or not 0 <= value <= 1:+ raise ValueError(f"{label} must be a finite number in [0,1]")+ return value+++def string_list(value, label, nonempty=False):+ if not isinstance(value, list) or (nonempty and not value):+ raise ValueError(f"{label} must be {'a nonempty' if nonempty else 'an'} array")+ return [text(item, label) for item in value]+++def sha_value(value, label):+ if not isinstance(value, str) or not HASH_PATTERN.fullmatch(value):+ raise ValueError(f"{label} must be a 64-character SHA256 hex digest")+ return value.lower()+++def _pairs(pairs):+ result = {}+ for key, value in pairs:+ if key in result:+ raise ValueError(f"duplicate JSON key: {key}")+ result[key] = value+ return result+++def _constant(value):+ raise ValueError(f"nonfinite JSON number: {value}")+++def decode_json(raw, label):+ try:+ result = json.loads(raw, object_pairs_hook=_pairs, parse_constant=_constant)+ except (UnicodeError, json.JSONDecodeError, RecursionError) as exc:+ raise ValueError(f"{label}: invalid JSON: {exc}") from exc+ # JSON exponent overflow (1e999) does not use parse_constant.+ def finite(value):+ if isinstance(value, float) and not math.isfinite(value):+ raise ValueError(f"{label}: nonfinite number")+ if isinstance(value, dict):+ for child in value.values():+ finite(child)+ elif isinstance(value, list):+ for child in value:+ finite(child)+ finite(result)+ return result+++def read_json(path):+ with Path(path).open("rb") as handle:+ raw = handle.read(JSON_LIMIT + 1)+ if len(raw) > JSON_LIMIT:+ raise ValueError(f"JSON metadata exceeds {JSON_LIMIT} bytes: {path}")+ return decode_json(raw, str(path))+++def file_hash(path):+ path = Path(path)+ if not path.is_file():+ raise AuditFailure(f"missing regular file: {path}")+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ before = os.fstat(handle.fileno())+ if before.st_size == 0:+ raise AuditFailure(f"empty file: {path}")+ while chunk := handle.read(1024 * 1024):+ digest.update(chunk)+ after = os.fstat(handle.fileno())+ current = path.stat()+ stamp = lambda st: (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)+ if stamp(before) != stamp(after) or stamp(after) != stamp(current):+ raise AuditFailure(f"file changed during hashing: {path}")+ return digest.hexdigest()+++def input_path(value):+ return Path(text(value, "input path")).expanduser().absolute()+++def confined_file(root, value, *, uri=False):+ """Only relative local files; URI decoding happens before containment checks."""+ text(value, "resource path")+ if uri:+ if re.search(r"%(?![0-9A-Fa-f]{2})", value):+ raise ValueError(f"invalid percent escape: {value}")+ value = unquote(value, errors="strict")+ parsed = urlsplit(value)+ parts = value.split("/")+ if (parsed.scheme or parsed.netloc or parsed.query or parsed.fragment or+ ":" in value or "\\" in value or "\x00" in value or+ PurePosixPath(value).is_absolute() or any(part in ("", ".", "..") for part in parts)):+ raise ValueError(f"resource must be a confined relative POSIX path: {value}")+ root = Path(root).resolve(strict=True)+ candidate = root.joinpath(*parts)+ resolved = candidate.resolve()+ if not resolved.is_relative_to(root):+ raise ValueError(f"resource escapes root: {value}")+ if not resolved.is_file():+ raise AuditFailure(f"missing resource: {candidate}")+ return resolved+++def workspace_path(value):+ workspace = resolve_workspace(value)+ if not workspace.is_dir():+ raise ValueError(f"workspace must be an existing directory: {workspace}")+ return workspace+++def owned_paths(workspace, filename):+ """Refuse redirection of artifact writes or core's state/lock/temp writes."""+ names = [".img2", ".img2/artifacts", ".img2/artifacts/interior",+ ".img2/state.json", ".img2/state.json.tmp", ".img2/.lock",+ f".img2/artifacts/interior/{filename}"]+ for name in names:+ candidate = workspace / name+ if candidate.is_symlink() or not candidate.resolve().is_relative_to(workspace):+ raise ValueError(f"refusing redirected workspace path: {candidate}")+ return workspace / ".img2/artifacts/interior" / filename+++def persist(workspace, filename, state_key, report):+ path = owned_paths(workspace, filename)+ # Never overwrite a declared input through a collision with our output or core state.+ inputs = [Path(item["path"]).resolve() for item in report["inputs"].values()]+ inputs.extend(Path(item["path"]).resolve() for item in report.get("resources", []))+ inputs.extend(Path(item["resolvedPath"]) for item in report.get("assets", []))+ outputs = [path, workspace / ".img2/state.json", workspace / ".img2/state.json.tmp",+ workspace / ".img2/.lock"]+ for output in outputs:+ for source in inputs:+ if output.resolve() == source or (output.exists() and source.samefile(output)):+ raise ValueError(f"audit output collides with a read-only input: {source}")+ path.parent.mkdir(parents=True, exist_ok=True)+ encoded = (json.dumps(report, indent=2, sort_keys=True, allow_nan=False) + "\n").encode()+ temporary = None+ try:+ with tempfile.NamedTemporaryFile(dir=path.parent, prefix=filename + ".", suffix=".tmp", delete=False) as handle:+ temporary = Path(handle.name)+ handle.write(encoded)+ os.replace(temporary, path)+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+ metadata = {"schemaVersion": 1, "receipt": str(path.relative_to(workspace)),+ "sha256": hashlib.sha256(encoded).hexdigest()}+ def update(subtree):+ object_value(subtree, "plugins.interior")+ subtree[state_key] = metadata+ update_plugin_state(workspace, "interior", update)+++def load_receipt(workspace, filename, state_key):+ path = owned_paths(workspace, filename)+ state_path = workspace / ".img2/state.json"+ if not path.is_file() or not state_path.is_file():+ raise AuditFailure(f"no stored {state_key} receipt; run the normal audit first")+ state = object_value(read_json(state_path), "state")+ if type(state.get("version")) is not int or state["version"] != 1:+ raise ValueError("invalid state envelope version")+ plugins = object_value(state.get("plugins"), "state.plugins")+ subtree = object_value(plugins.get("interior", {}), "plugins.interior")+ if state_key not in subtree:+ raise AuditFailure(f"no stored {state_key} metadata")+ metadata = fields(subtree[state_key], ["schemaVersion", "receipt", "sha256"], [], state_key)+ if type(metadata["schemaVersion"]) is not int or metadata["schemaVersion"] != 1:+ raise ValueError("unsupported receipt metadata version")+ if metadata["receipt"] != str(path.relative_to(workspace)):+ raise ValueError("receipt metadata does not point to the owned receipt")+ if file_hash(path) != sha_value(metadata["sha256"], "receipt hash"):+ raise AuditFailure("stored receipt changed after audit")+ receipt = object_value(read_json(path), "receipt")+ if type(receipt.get("schemaVersion")) is not int or receipt["schemaVersion"] != 1:+ raise ValueError("unsupported audit receipt version")+ if type(receipt.get("passed")) is not bool:+ raise ValueError("receipt passed must be boolean")+ return receipt+++def pin(path):+ return {"path": str(path), "sha256": file_hash(path)}+++def check_pin(value, label):+ fields(value, ["path", "sha256"], [], label)+ path = input_path(value["path"])+ if not Path(value["path"]).is_absolute():+ raise ValueError(f"{label} receipt path must be absolute")+ if file_hash(path) != sha_value(value["sha256"], label):+ raise AuditFailure(f"{label} changed since audit")+ return path+++def emit(gate, status, reasons, evidence, *, gate_mode):+ if gate_mode:+ result = {"kind": "img2.gate-verdict", "version": 1, "gate": gate,+ "plugin": "interior", "status": status, "reasons": reasons, "evidence": evidence}+ else:+ result = evidence or {"schemaVersion": 1, "passed": False, "reasons": reasons}+ result = dict(result, status=status)+ print(json.dumps(result, sort_keys=True, allow_nan=False))+ return {"pass": 0, "fail": 1, "error": 2}[status]diff --git a/tools/author_scene.py b/tools/author_scene.pynew file mode 100755index 0000000..6b6e3bf--- /dev/null+++ b/tools/author_scene.py@@ -0,0 +1,49 @@+#!/usr/bin/env python3+"""Run explicit native production stages with a compatible bpy Python interpreter."""+from argparse import ArgumentParser+from pathlib import Path+import sys+import uuid++# Installed library search path only; authoring/output roots come from --workspace.+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+from authoring import context_from_args, bound_module+++def parser():+ p = ArgumentParser(description=__doc__)+ p.add_argument('stage', choices=['draft', 'bake', 'probe', 'export', 'render', 'refresh-material', 'calibrate', 'material-regression'])+ p.add_argument('--workspace', required=True)+ p.add_argument('--spec', default='scene-spec.json')+ p.add_argument('--run-id', default=uuid.uuid4().hex)+ p.add_argument('--width', type=int, default=1280)+ p.add_argument('--samples', type=int, default=64)+ p.add_argument('--resolution', type=int, default=2048)+ p.add_argument('--atlas')+ p.add_argument('--view', default='source')+ p.add_argument('--image', action='append', default=[], help='W-relative image to refresh in packed master; repeatable')+ return p+++def main():+ args = parser().parse_args()+ if min(args.width, args.samples, args.resolution) < 1:+ raise ValueError('width, samples and resolution must be positive')+ context = context_from_args(args)+ if args.view != 'source' and args.view not in context.spec['authoring']['inspectionViews']:+ raise ValueError('Unknown inspection view')+ marker = context.evidence / (args.stage + '-' + (args.atlas or args.view) + '.started')+ with marker.open('x') as stream:+ stream.write('This stage owns its evidence paths; use a new run-id for revisions.\n')+ if args.stage in ('calibrate', 'material-regression'):+ from authoring.regression import calibrate, material_regression+ result = (calibrate if args.stage == 'calibrate' else material_regression)(context, args)+ import json+ print(json.dumps(result), flush=True)+ else:+ module = bound_module('pipeline', context)+ getattr(module, 'stage_' + args.stage.replace('-', '_'))(args)+++if __name__ == '__main__':+ main()diff --git a/tools/compare_views.py b/tools/compare_views.pynew file mode 100755index 0000000..9d14d43--- /dev/null+++ b/tools/compare_views.py@@ -0,0 +1,88 @@+#!/usr/bin/env python3+"""Create a labeled reference/render contact sheet for actual visual review, never a realism score."""+import argparse+import json+import math+from pathlib import Path+import re+import sys++from project_support import ARTIFACTS, confined, digest, project, workspace_path, write_json+++def compare(workspace, renders, run_id, name, roi=None, width=640):+ from PIL import Image, ImageDraw, ImageFont, ImageOps+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}', run_id):+ raise ValueError('run-id must be a plain slug, at most 64 characters')+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}', name):+ raise ValueError('name must be a plain slug, at most 64 characters')+ if not 128 <= width <= 1600 or not 1 <= len(renders) <= 7:+ raise ValueError('Use width 128..1600 and one to seven actual rendered images')+ if roi and not (all(math.isfinite(value) for value in roi) and 0 <= roi[0] < roi[2] <= 1 and 0 <= roi[1] < roi[3] <= 1):+ raise ValueError('ROI must be normalized left,top,right,bottom within 0..1')+ record = project(workspace)+ paths = [confined(workspace, record['source']['path'])] + [confined(workspace, value) for value in renders]+ output = confined(workspace, ARTIFACTS / 'production' / run_id / (name + '.png'))+ receipt = output.with_suffix('.json')+ if output.exists() or receipt.exists():+ raise ValueError('Comparison evidence already exists; choose a new run-id or name, never replace accepted captures')+ images, inputs = [], []+ for path in paths:+ with Image.open(path) as image:+ image = ImageOps.exif_transpose(image)+ original_size = list(image.size)+ if roi:+ bounds = (math.floor(roi[0] * image.width), math.floor(roi[1] * image.height),+ math.ceil(roi[2] * image.width), math.ceil(roi[3] * image.height))+ image = image.crop(bounds)+ rgba = image.convert('RGBA')+ canvas = Image.new('RGBA', rgba.size, '#f4f0e7')+ canvas.alpha_composite(rgba)+ preview = canvas.convert('RGB')+ preview.thumbnail((width, width), Image.Resampling.LANCZOS)+ images.append(preview)+ inputs.append({'path': path.relative_to(workspace).as_posix(), 'sha256': digest(path),+ 'decodedSize': original_size, 'normalizedROI': roi})+ cell_height = max(image.height for image in images) + 48+ columns = 2+ sheet = Image.new('RGB', (width * columns, cell_height * ((len(images) + columns - 1) // columns)), '#f4f0e7')+ draw = ImageDraw.Draw(sheet)+ font = ImageFont.load_default(size=16)+ for index, (image, path) in enumerate(zip(images, paths)):+ x, y = (index % columns) * width, (index // columns) * cell_height+ label = 'REFERENCE (' + record['source']['sourceKind'] + ')' if index == 0 else 'RENDER: ' + path.name+ draw.text((x + 12, y + 12), label, fill='#242321', font=font)+ sheet.paste(image, (x + (width - image.width) // 2, y + 44))+ output.parent.mkdir(parents=True, exist_ok=True)+ with output.open('xb') as stream:+ sheet.save(stream, format='PNG')+ result = {'schemaVersion': 1, 'inputs': inputs, 'sheet': output.relative_to(workspace).as_posix(),+ 'sha256': digest(output), 'purpose': 'Human/agent visual comparison; preserve each complete view without an automatic likeness grade',+ 'visualAcceptanceEvaluated': False, 'pixelAlignmentAssumed': False}+ write_json(receipt, result)+ return result+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--workspace', required=True)+ parser.add_argument('--render', action='append', required=True, help='Workspace-relative actual render; repeat for multiple views')+ parser.add_argument('--run-id', required=True)+ parser.add_argument('--name', default='comparison')+ parser.add_argument('--roi', nargs=4, type=float, metavar=('LEFT', 'TOP', 'RIGHT', 'BOTTOM'))+ parser.add_argument('--width', type=int, default=640)+ args = parser.parse_args()+ try:+ result = compare(workspace_path(args.workspace), args.render, args.run_id, args.name, args.roi, args.width)+ print(json.dumps(result, indent=2, allow_nan=False))+ return 0+ except ImportError as error:+ print('Install requirements-surfaces.txt in an isolated image-tools environment: ' + str(error), file=sys.stderr)+ return 2+ except (OSError, ValueError, KeyError, TypeError) as error:+ print(json.dumps({'status': 'error', 'error': str(error)}), file=sys.stderr)+ return 2+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/gate_workflow.py b/tools/gate_workflow.pynew file mode 100644index 0000000..376ddaf--- /dev/null+++ b/tools/gate_workflow.py@@ -0,0 +1,38 @@+import os, sys+root = os.environ.get("IMG2_HOME")+if root: sys.path.insert(0, os.path.join(root, "harness"))+else:+ try: import _img2_local; sys.path.insert(0, _img2_local.CORE)+ except ImportError: sys.exit("img2: core not linked - run `img2 sync`")+from img2_core import require_core_api+require_core_api(1)++import argparse+import json++from workflow_support import ATTESTATION, Refusal, evaluate_gate, workspace_path+++class Parser(argparse.ArgumentParser):+ def error(self, message):+ raise Refusal(message)+++def main(argv=None):+ evidence = {"attestation": ATTESTATION}+ try:+ parser = Parser(description="Check ordered interior attestations and current file hashes; never grade visual quality.")+ parser.add_argument("--workspace", required=True)+ args = parser.parse_args(argv)+ reasons, evidence = evaluate_gate(workspace_path(args.workspace))+ status = "fail" if reasons else "pass"+ except (OSError, ValueError, RuntimeError) as exc:+ status, reasons = "error", [str(exc)]+ print(json.dumps({"kind": "img2.gate-verdict", "version": 1, "gate": "interior-workflow",+ "plugin": "interior", "status": status, "reasons": reasons, "evidence": evidence},+ indent=2, sort_keys=True, allow_nan=False))+ return {"pass": 0, "fail": 1, "error": 2}[status]+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/inspect_scene.py b/tools/inspect_scene.pynew file mode 100755index 0000000..571092e--- /dev/null+++ b/tools/inspect_scene.py@@ -0,0 +1,33 @@+#!/usr/bin/env python3+"""Independently reopen and render a packed master or portable GLB."""+from argparse import ArgumentParser+from pathlib import Path+import sys+import uuid+# Installed library search path only; consumer/output roots come from --workspace.+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+from authoring import context_from_args, bound_module+++def main():+ p = ArgumentParser(description=__doc__)+ p.add_argument('asset', choices=['master', 'portable'])+ p.add_argument('--workspace', required=True)+ p.add_argument('--spec', default='scene-spec.json')+ p.add_argument('--run-id', default=uuid.uuid4().hex)+ p.add_argument('--width', type=int, default=1280)+ p.add_argument('--samples', type=int, default=64)+ p.add_argument('--view', default='source')+ args = p.parse_args()+ if min(args.width, args.samples) <= 0:+ raise ValueError('width and samples must be positive')+ context = context_from_args(args)+ if args.view != 'source' and args.view not in context.spec['authoring']['inspectionViews']:+ raise ValueError('Unknown inspection view')+ with (context.evidence / f'inspect-{args.asset}-{args.view}.started').open('x') as stream:+ stream.write('Independent native consumer invocation\n')+ bound_module('inspection', context).run(args)+++if __name__ == '__main__':+ main()diff --git a/tools/interior_project.py b/tools/interior_project.pynew file mode 100755index 0000000..673e8fa--- /dev/null+++ b/tools/interior_project.py@@ -0,0 +1,61 @@+#!/usr/bin/env python3+"""Create an image-led workspace and install real production templates, without accepting its quality."""+import argparse+import json+import sys++from project_support import (PLUGIN, SOURCE_KINDS, delivery_contract, install_template,+ preflight, project, snapshot, start, use_recipe, workspace_path)+++def main(argv=None):+ parser = argparse.ArgumentParser(description=__doc__)+ commands = parser.add_subparsers(dest='command', required=True)+ create = commands.add_parser('start', help='Pin and copy one supplied image; analysis remains agent work')+ create.add_argument('--workspace', required=True)+ create.add_argument('--image', required=True)+ create.add_argument('--source-kind', choices=SOURCE_KINDS, default='photo')+ create.add_argument('--authorization', default='User supplied reference for local reconstruction; publication rights are not established')+ create.add_argument('--reference-url', action='append', default=[])+ check = commands.add_parser('preflight', help='Probe actual executables without installing anything')+ check.add_argument('--workspace', required=True)+ check.add_argument('--blender-python')+ viewer = commands.add_parser('install-viewer', help='Install the production viewer without overwriting user edits')+ viewer.add_argument('--workspace', required=True)+ recipe = commands.add_parser('use-recipe', help='Explicitly reproduce a source-pinned case, not an arbitrary image')+ recipe.add_argument('--workspace', required=True)+ recipe.add_argument('--recipe', choices=('oak-linen',), required=True)+ delivery = commands.add_parser('delivery-contract', help='Hash actual manifest dependencies; does not certify consumer rendering')+ delivery.add_argument('--workspace', required=True)+ delivery.add_argument('--spec', default='scene-spec.json')+ capture = commands.add_parser('snapshot', help='Freeze a current workspace report/capture without overwriting accepted evidence')+ capture.add_argument('--workspace', required=True)+ capture.add_argument('--input', required=True)+ capture.add_argument('--run-id', required=True)+ capture.add_argument('--name', required=True)+ args = parser.parse_args(argv)+ try:+ workspace = workspace_path(args.workspace)+ if args.command == 'start':+ result = start(workspace, args.image, args.source_kind, args.authorization, args.reference_url)+ elif args.command == 'preflight':+ result = preflight(workspace, args.blender_python)+ elif args.command == 'install-viewer':+ project(workspace)+ result = install_template(workspace, PLUGIN / 'runtime/viewer', 'viewer-install.json')+ result['next'] = 'Run npm ci, npm run build and a loopback dev/preview server; inspect the actual browser'+ elif args.command == 'use-recipe':+ result = use_recipe(workspace, args.recipe)+ elif args.command == 'snapshot':+ result = snapshot(workspace, args.input, args.run_id, args.name)+ else:+ result = delivery_contract(workspace, args.spec)+ print(json.dumps(result, indent=2, allow_nan=False))+ return 1 if result.get('status') == 'blocked' else 0+ except (OSError, ValueError, KeyError, TypeError) as error:+ print(json.dumps({'status': 'error', 'error': str(error)}), file=sys.stderr)+ return 2+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/interior_workflow.py b/tools/interior_workflow.pynew file mode 100644index 0000000..08a8507--- /dev/null+++ b/tools/interior_workflow.py@@ -0,0 +1,70 @@+import os, sys+root = os.environ.get("IMG2_HOME")+if root: sys.path.insert(0, os.path.join(root, "harness"))+else:+ try: import _img2_local; sys.path.insert(0, _img2_local.CORE)+ except ImportError: sys.exit("img2: core not linked - run `img2 sync`")+from img2_core import require_core_api+require_core_api(1)++import argparse+import json++from workflow_support import (DECISIONS, STAGES, Incomplete, Refusal, describe,+ initialize, read_run, record, revise, workspace_path)+++class Parser(argparse.ArgumentParser):+ def error(self, message):+ raise Refusal(message)+++def parser():+ cli = Parser(description="Record explicit interior reviewer attestations, not automatic visual certification.")+ commands = cli.add_subparsers(dest="command", required=True)+ for name in ("init", "next", "record", "revise", "report"):+ command = commands.add_parser(name)+ command.add_argument("--workspace", required=True)+ if name == "init":+ command.add_argument("--image", required=True)+ command.add_argument("--intake", required=True)+ elif name == "record":+ command.add_argument("--stage", choices=STAGES, required=True)+ command.add_argument("--decision", choices=DECISIONS, required=True)+ command.add_argument("--reviewer", required=True)+ command.add_argument("--note", required=True)+ command.add_argument("--evidence", action="append", default=[], help="Repeat for each workspace evidence file; required for acceptance.")+ elif name == "revise":+ command.add_argument("--from", dest="from_stage", choices=STAGES, required=True)+ command.add_argument("--reason", required=True)+ return cli+++def main(argv=None):+ try:+ args = parser().parse_args(argv)+ workspace = workspace_path(args.workspace)+ if args.command == "init":+ run = initialize(workspace, args.image, args.intake)+ elif args.command == "record":+ run = record(workspace, args.stage, args.decision, args.reviewer, args.note, args.evidence)+ elif args.command == "revise":+ run = revise(workspace, args.from_stage, args.reason)+ else:+ run = read_run(workspace)+ result = describe(run, workspace)+ if args.command == "report":+ result["workflow"] = run+ code = 3 if args.command in ("next", "record") and result.get("explicitBlock") else 0+ if args.command == "record" and args.decision == "reject":+ code = 1+ except Incomplete as exc:+ result, code = {"status": "fail", "reasons": [str(exc)]}, 1+ except (OSError, ValueError, RuntimeError) as exc:+ result, code = {"status": "error", "reasons": [str(exc)]}, 2+ print(json.dumps(result, indent=2, sort_keys=True, allow_nan=False))+ return code+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/polyhaven.py b/tools/polyhaven.pynew file mode 100644index 0000000..1fa94ef--- /dev/null+++ b/tools/polyhaven.py@@ -0,0 +1,48 @@+"""Search, inspect and acquire CC0 assets into an explicit authoring workspace."""+import argparse+import json+from pathlib import Path+import sys++# Installed library search path only; acquisitions are confined to --workspace.+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+from resources_lib.polyhaven import CREDIT, Client, describe, fetch, save_query, search+++def main(argv=None):+ cli = argparse.ArgumentParser(description='Powered by Poly Haven — CC0 assets; live API terms apply separately.')+ commands = cli.add_subparsers(dest='command', required=True)+ for name in ('search', 'info', 'files', 'fetch'):+ command = commands.add_parser(name)+ command.add_argument('--workspace', required=True)+ if name == 'search':+ command.add_argument('--type', choices=('textures', 'models', 'hdris'), required=True)+ command.add_argument('--query', required=True)+ command.add_argument('--limit', type=int, default=10)+ elif name == 'fetch':+ command.add_argument('--selection', required=True, help='Workspace-relative selection JSON')+ else:+ command.add_argument('--id', required=True)+ args = cli.parse_args(argv)+ print(CREDIT, file=sys.stderr)+ try:+ workspace = Path(args.workspace).expanduser().resolve()+ if not workspace.is_dir():+ raise ValueError('Workspace must be an existing authored directory')+ client = Client()+ if args.command == 'fetch':+ result = fetch(workspace, args.selection, client)+ elif args.command == 'search':+ result = save_query(workspace, 'search', {'type': args.type, 'query': args.query, 'limit': args.limit},+ search(client, args.type, args.query, args.limit))+ else:+ result = save_query(workspace, args.command, {'id': args.id}, describe(client, args.command, args.id))+ code = 0+ except (OSError, ValueError, RuntimeError, KeyError, TypeError) as exc:+ result, code = {'status': 'error', 'reason': str(exc), 'credit': CREDIT}, 2+ print(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False))+ return code+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/prepare_surfaces.py b/tools/prepare_surfaces.pynew file mode 100644index 0000000..17b1411--- /dev/null+++ b/tools/prepare_surfaces.py@@ -0,0 +1,29 @@+"""Execute an authored surface recipe without changing its source images."""+import argparse+import json+from pathlib import Path+import sys++# Installed library search path only; derivatives are confined to --workspace.+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+from resources_lib.surfaces import prepare+++def main(argv=None):+ cli = argparse.ArgumentParser(description=__doc__)+ cli.add_argument('--workspace', required=True)+ cli.add_argument('--recipe', required=True, help='Workspace-relative schemaVersion 1 recipe JSON')+ args = cli.parse_args(argv)+ try:+ workspace = Path(args.workspace).expanduser().resolve()+ if not workspace.is_dir():+ raise ValueError('Workspace must be an existing authored directory')+ result, code = prepare(workspace, args.recipe), 0+ except (OSError, ValueError, RuntimeError, KeyError, TypeError) as exc:+ result, code = {'status': 'error', 'reason': str(exc)}, 2+ print(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False))+ return code+++if __name__ == '__main__':+ sys.exit(main())diff --git a/tools/project_support.py b/tools/project_support.pynew file mode 100644index 0000000..674fa80--- /dev/null+++ b/tools/project_support.py@@ -0,0 +1,402 @@+"""Local project operations; no scene generation or writes at import time."""+from datetime import datetime, timezone+import hashlib+import json+import math+import os+from pathlib import Path, PurePosixPath+import re+import shutil+import struct+import subprocess+import tempfile+from urllib.parse import unquote, urlsplit++PLUGIN = Path(__file__).resolve().parent.parent+ARTIFACTS = Path('.img2/artifacts/interior')+OAK_SOURCE = '95eb31d840165964deac849813dc77ad18bad71f1df90770bff1f7b4a5fb666b'+SOURCE_KINDS = ('photo', 'render', 'synthetic-design-reference', 'floorplan')+++def workspace_path(value):+ workspace = Path(value).expanduser().resolve()+ if workspace == PLUGIN or workspace.is_relative_to(PLUGIN):+ raise ValueError('The installed plugin cannot be the authored workspace')+ return workspace+++def confined(workspace, relative):+ workspace = workspace_path(workspace)+ relative = Path(relative)+ if relative.is_absolute() or '..' in relative.parts:+ raise ValueError('Expected a workspace-relative path: ' + str(relative))+ lexical = workspace / relative+ resolved = lexical.resolve()+ if not resolved.is_relative_to(workspace) or lexical.is_symlink():+ raise ValueError('Workspace path escapes or aliases an output: ' + str(relative))+ return resolved+++def _pairs(items):+ result = {}+ for key, value in items:+ if key in result:+ raise ValueError('Duplicate JSON key: ' + key)+ result[key] = value+ return result+++def _finite_float(value):+ number = float(value)+ if not math.isfinite(number):+ raise ValueError('Non-finite JSON number: ' + value)+ return number+++def read_json(path):+ if path.stat().st_size > 4 * 1024 * 1024:+ raise ValueError('Project JSON exceeds 4 MiB: ' + str(path))+ return json.loads(path.read_text(encoding='utf-8'), object_pairs_hook=_pairs,+ parse_float=_finite_float,+ parse_constant=lambda value: (_ for _ in ()).throw(ValueError('Non-finite JSON: ' + value)))+++def write_bytes(path, data):+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = None+ try:+ with tempfile.NamedTemporaryFile(dir=path.parent, prefix='.' + path.name + '.', delete=False) as stream:+ temporary = Path(stream.name)+ stream.write(data)+ temporary.replace(path)+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+++def write_json(path, value):+ write_bytes(path, (json.dumps(value, indent=2, allow_nan=False) + '\n').encode('utf-8'))+++def digest(path):+ result = hashlib.sha256()+ with path.open('rb') as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b''):+ result.update(chunk)+ return result.hexdigest()+++def _exif_orientation(payload):+ if not payload.startswith(b'Exif\0\0'):+ return 1+ tiff = payload[6:]+ if len(tiff) < 8 or tiff[:2] not in (b'II', b'MM'):+ return 1+ order = 'little' if tiff[:2] == b'II' else 'big'+ offset = int.from_bytes(tiff[4:8], order)+ if offset + 2 > len(tiff):+ return 1+ count = int.from_bytes(tiff[offset:offset + 2], order)+ if count > 4096 or offset + 2 + count * 12 > len(tiff):+ return 1+ for index in range(count):+ entry = offset + 2 + index * 12+ if int.from_bytes(tiff[entry:entry + 2], order) == 274:+ if (int.from_bytes(tiff[entry + 2:entry + 4], order) == 3+ and int.from_bytes(tiff[entry + 4:entry + 8], order) == 1):+ value = int.from_bytes(tiff[entry + 8:entry + 10], order)+ return value if 1 <= value <= 8 else 1+ return 1+++def image_geometry(data):+ """Read header geometry, not a pixel decode or image-content classification."""+ orientation = 1+ if len(data) >= 33 and data[:8] == b'\x89PNG\r\n\x1a\n' and data[12:16] == b'IHDR':+ width, height = struct.unpack('>II', data[16:24])+ extension = '.png'+ elif data.startswith(b'\xff\xd8'):+ offset, width, height = 2, None, None+ sof = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}+ while offset < len(data):+ if data[offset] != 0xFF:+ raise ValueError('Malformed JPEG marker sequence')+ while offset < len(data) and data[offset] == 0xFF:+ offset += 1+ if offset >= len(data):+ break+ marker = data[offset]+ offset += 1+ if marker in (0xDA, 0xD9):+ break+ if marker == 0x01 or 0xD0 <= marker <= 0xD8:+ continue+ if offset + 2 > len(data):+ raise ValueError('Truncated JPEG segment')+ length = int.from_bytes(data[offset:offset + 2], 'big')+ if length < 2 or offset + length > len(data):+ raise ValueError('Truncated JPEG segment')+ if marker == 0xE1:+ orientation = _exif_orientation(data[offset + 2:offset + length])+ if marker in sof:+ if length < 8:+ raise ValueError('Invalid JPEG frame')+ height, width = struct.unpack('>HH', data[offset + 3:offset + 7])+ offset += length+ if width is None or height is None:+ raise ValueError('JPEG has no supported frame header')+ extension = '.jpg'+ elif len(data) >= 25 and data[:4] == b'RIFF' and data[8:12] == b'WEBP':+ 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')+ elif chunk == b'VP8L' and data[20] == 0x2F:+ bits = int.from_bytes(data[21:25], 'little')+ width, height = (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1+ elif chunk == b'VP8 ' and len(data) >= 30 and data[23:26] == b'\x9d\x01\x2a':+ width, height = struct.unpack('<HH', data[26:30])+ width, height = width & 0x3FFF, height & 0x3FFF+ else:+ raise ValueError('Unsupported WebP frame header; convert a copy to PNG for analysis')+ extension = '.webp'+ else:+ raise ValueError('Reference must be PNG, JPEG or WebP; convert unsupported formats without replacing source truth')+ if not 0 < width <= 32768 or not 0 < height <= 32768 or width * height > 160_000_000:+ raise ValueError('Reference dimensions exceed the supported analysis bound')+ size = [height, width] if orientation in (5, 6, 7, 8) else [width, height]+ return {'extension': extension, 'sourceImageSize': size, 'encodedSize': [width, height],+ 'exifOrientation': orientation, 'pixelDecodingEvaluated': False}+++def project(workspace):+ record = read_json(confined(workspace, ARTIFACTS / 'project.json'))+ source = confined(workspace, record['source']['path'])+ if digest(source) != record['source']['sha256']:+ raise ValueError('Pinned project reference changed; use a new project/run rather than silently repinning')+ return record+++def start(workspace, image, source_kind, authorization, references):+ record_path = confined(workspace, ARTIFACTS / 'project.json')+ if record_path.exists():+ raise ValueError('Project already initialized; resume its existing analysis instead of resetting it')+ source = Path(image).expanduser().resolve(strict=True)+ if source.stat().st_size > 64 * 1024 * 1024:+ raise ValueError('Reference exceeds 64 MiB')+ data = source.read_bytes()+ if len(data) > 64 * 1024 * 1024:+ raise ValueError('Reference exceeds 64 MiB')+ geometry = image_geometry(data)+ relative = Path('public/assets/reference' + geometry['extension'])+ destination = confined(workspace, relative)+ if destination.exists() and digest(destination) != hashlib.sha256(data).hexdigest():+ raise ValueError('Refusing to replace a different existing project reference: ' + str(relative))+ if not authorization.strip():+ raise ValueError('Reference processing authorization must not be empty')+ if source_kind not in SOURCE_KINDS:+ raise ValueError('Unsupported sourceKind')+ for url in references:+ parsed = urlsplit(url)+ if parsed.scheme not in ('http', 'https') or not parsed.netloc:+ raise ValueError('Reference URLs must be explicit HTTP(S) URLs')+ record = {'schemaVersion': 1, 'createdAt': datetime.now(timezone.utc).isoformat(),+ 'source': {'path': relative.as_posix(), 'originalPath': str(source),+ 'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data),+ 'sourceKind': source_kind, 'authorization': authorization, **geometry},+ 'references': references,+ 'analysisRequired': ['Observe source pixels and references with image/browser tools',+ 'Author intake, normalized visible anchors and uncertainty',+ 'Author scene-spec.json and image-specific build_scene(context)',+ 'Select suitable licensed resources; do not default to Oak/Linen'],+ 'visualAcceptanceEvaluated': False}+ if not destination.exists():+ write_bytes(destination, data)+ write_json(record_path, record)+ return {'status': 'ready-for-analysis', 'project': record, 'receipt': str(record_path),+ 'next': 'Read the image; author intake/spec/builder before initializing workflow attestations'}+++def _template_files(template):+ files = []+ excluded = {'.git', 'node_modules', 'dist', '__pycache__', '.DS_Store'}+ for path in template.rglob('*'):+ relative = path.relative_to(template)+ if any(part in excluded for part in relative.parts):+ continue+ if path.is_symlink():+ raise ValueError('Template contains a symlink: ' + str(relative))+ if path.is_file():+ files.append((relative, path))+ if not files:+ raise ValueError('Installed plugin has no usable template: ' + str(template))+ return files+++def install_template(workspace, template, receipt_name):+ receipt_path = confined(workspace, ARTIFACTS / receipt_name)+ previous = read_json(receipt_path).get('files', {}) if receipt_path.exists() else {}+ files = _template_files(template)+ planned = []+ for relative, source in files:+ destination = confined(workspace, relative)+ wanted = digest(source)+ if destination.exists():+ actual = digest(destination)+ if actual != wanted and actual != previous.get(relative.as_posix()):+ raise ValueError('Refusing to overwrite an unowned/edited project file: ' + str(relative))+ planned.append((relative, source, destination, wanted))+ owned = {}+ for relative, source, destination, wanted in planned:+ if not destination.exists() or digest(destination) != wanted:+ write_bytes(destination, source.read_bytes())+ owned[relative.as_posix()] = wanted+ write_json(receipt_path, {'schemaVersion': 1, 'template': template.relative_to(PLUGIN).as_posix(), 'files': owned})+ return {'status': 'installed', 'files': sorted(owned), 'receipt': str(receipt_path)}+++def use_recipe(workspace, name):+ record = project(workspace)+ if name != 'oak-linen':+ raise ValueError('Only the explicitly guarded oak-linen reproduction recipe is shipped; author new scenes from their own image')+ if record['source']['sha256'] != OAK_SOURCE:+ raise ValueError('Oak/Linen recipe requires its exact authorized source; it is never a fallback for another image')+ result = install_template(workspace, PLUGIN / 'recipes/oak-linen', 'recipe-install.json')+ spec_path = confined(workspace, 'scene-spec.json')+ spec = read_json(spec_path)+ spec['source'] = record['source']['path']+ spec['sourceKind'] = record['source']['sourceKind']+ spec['authoring']['sourceImageSize'] = record['source']['sourceImageSize']+ write_json(spec_path, spec)+ ownership = read_json(confined(workspace, ARTIFACTS / 'recipe-install.json'))+ ownership['files']['scene-spec.json'] = digest(spec_path)+ write_json(confined(workspace, ARTIFACTS / 'recipe-install.json'), ownership)+ return {**result, 'recipe': name, 'visualAcceptanceEvaluated': False}+++def _public_asset(workspace, value):+ if not isinstance(value, str):+ raise ValueError('Manifest dependency URL must be a string')+ parsed = urlsplit(value)+ decoded = unquote(parsed.path)+ if (parsed.scheme or parsed.netloc or parsed.query or parsed.fragment+ or not decoded.startswith('/assets/') or '..' in PurePosixPath(decoded).parts):+ raise ValueError('Delivery requires local /assets/ URLs: ' + value)+ return confined(workspace, Path('public') / decoded.lstrip('/'))+++def delivery_contract(workspace, spec_file):+ workspace = workspace_path(workspace)+ record = project(workspace)+ spec = read_json(confined(workspace, spec_file))+ manifest_path = confined(workspace, 'public/assets/interior/manifest.json')+ manifest = read_json(manifest_path)+ assets, paths, ids = [], {}, set()+ def add(identity, role, path):+ relative = path.relative_to(workspace).as_posix()+ resolved = path.resolve()+ if resolved in paths:+ previous_id, previous_role = paths[resolved]+ if previous_role == role == 'sidecar':+ return previous_id+ raise ValueError('Distinct delivery roles alias one file: ' + relative)+ if identity in ids or not path.is_file():+ raise ValueError('Duplicate identity or missing delivery file: ' + relative)+ ids.add(identity); paths[resolved] = (identity, role)+ assets.append({'id': identity, 'role': role, 'path': relative, 'sha256': digest(path)})+ return identity+ source = _public_asset(workspace, manifest['sourceImage'])+ if source != confined(workspace, record['source']['path']):+ raise ValueError('Exported sourceImage does not match the pinned project reference')+ add('source', 'source', source)+ for key, identity, role in [('model', 'runtime', 'runtime'), ('portableModel', 'portable', 'portable'), ('blender', 'native', 'native')]:+ add(identity, role, _public_asset(workspace, manifest[key]))+ add('manifest', 'sidecar', manifest_path)+ sidecars = ['manifest']+ for key in ('environment', 'background'):+ if manifest.get(key):+ identity = add(key, 'sidecar', _public_asset(workspace, manifest[key]))+ if identity not in sidecars:+ sidecars.append(identity)+ for atlas in manifest.get('lightmaps', []):+ if not re.fullmatch(r'[A-Za-z0-9_-]+', str(atlas.get('id', ''))):+ raise ValueError('Invalid atlas identity')+ identity = 'lightmap-' + atlas['id']+ identity = add(identity, 'sidecar', _public_asset(workspace, atlas['url']))+ if identity not in sidecars:+ sidecars.append(identity)+ limitations = [spec.get('sourceViewLimit', ''), spec.get('portability', '')]+ limitations = [value for value in limitations if isinstance(value, str) and value.strip()]+ if len(limitations) != 2:+ raise ValueError('Declare sourceViewLimit and portability before producing a delivery contract')+ doc = {'schemaVersion': 1, 'root': str(workspace), 'assets': assets,+ 'runtime': {'asset': 'runtime', 'sidecars': sidecars},+ 'portable': {'asset': 'portable', 'limitations': [spec['portability']]},+ 'native': {'asset': 'native'}, 'limitations': limitations}+ output = confined(workspace, ARTIFACTS / 'delivery-contract.json')+ write_json(output, doc)+ return {'status': 'recorded', 'contract': str(output), 'assets': len(assets),+ 'consumerReopeningEvaluated': False, 'visualAcceptanceEvaluated': False}+++def snapshot(workspace, input_file, run_id, name):+ """Freeze an observed report/capture, without accepting its claims."""+ workspace = workspace_path(workspace)+ for value in (run_id, name):+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}', value):+ raise ValueError('Snapshot run-id and name must be plain slugs, at most 64 characters')+ source = confined(workspace, input_file)+ if not source.is_file() or not source.stat().st_size:+ raise ValueError('Snapshot requires a nonempty workspace file')+ sha256 = digest(source)+ output = confined(workspace, ARTIFACTS / 'production' / run_id / 'evidence' / (name + '-' + sha256[:16] + source.suffix))+ if output.exists():+ if digest(output) != sha256:+ raise ValueError('Existing snapshot content does not match its identity')+ else:+ write_bytes(output, source.read_bytes())+ if digest(output) != sha256:+ output.unlink()+ raise ValueError('Input changed while freezing evidence; capture again after the writer finishes')+ return {'status': 'recorded', 'path': output.relative_to(workspace).as_posix(),+ 'sha256': sha256, 'bytes': output.stat().st_size, 'visualAcceptanceEvaluated': False}+++def preflight(workspace, interpreter=None):+ checks = {}+ for binary in ('node', 'npm'):+ executable = shutil.which(binary)+ if not executable:+ checks[binary] = {'status': 'missing'}+ continue+ result = subprocess.run([executable, '--version'], capture_output=True, text=True, timeout=30)+ checks[binary] = {'status': 'available' if result.returncode == 0 else 'error',+ 'version': result.stdout.strip(), 'path': executable}+ if binary == 'node' and result.returncode == 0:+ major = int(result.stdout.strip().removeprefix('v').split('.')[0])+ if major not in (18, 20) and major < 22:+ checks[binary]['status'] = 'unsupported-version'+ python = interpreter or os.environ.get('IMG2_BLENDER_PYTHON')+ if not python:+ candidates = [workspace / '.venv-blender/bin/python', workspace / '.venv-blender/Scripts/python.exe']+ python = next((str(path) for path in candidates if path.is_file()), None)+ if python:+ code = ('import sys,json,bpy,numpy; print(json.dumps({"python":list(sys.version_info[:3]),'+ '"bpy":list(bpy.app.version),"numpy":numpy.__version__}))')+ try:+ process = subprocess.run([str(python), '-c', code], capture_output=True, text=True, timeout=120)+ if process.returncode:+ checks['authoring'] = {'status': 'missing-dependency', 'reason': process.stderr.strip()[-2000:]}+ else:+ versions = json.loads(process.stdout.strip().splitlines()[-1])+ compatible = versions['python'][:2] == [3, 11] and versions['bpy'][:2] == [4, 3] and versions['numpy'] == '1.26.4'+ checks['authoring'] = {'status': 'compatible' if compatible else 'unsupported-version',+ 'versions': versions, 'interpreter': str(python)}+ except (OSError, subprocess.TimeoutExpired, ValueError, IndexError) as error:+ checks['authoring'] = {'status': 'error', 'reason': str(error)}+ else:+ checks['authoring'] = {'status': 'missing', 'required': 'Isolated Python 3.11, bpy 4.3.0, NumPy 1.26.4; requirements-authoring.txt'}+ ready = all(value['status'] in ('available', 'compatible') for value in checks.values())+ return {'status': 'ready' if ready else 'blocked', 'checks': checks,+ 'browserRequired': 'Use the agent host browser for actual image/scene/interaction review; no screenshot truth is inferred',+ 'installsPerformed': False}diff --git a/tools/run_gates.py b/tools/run_gates.pynew file mode 100755index 0000000..5412d4f--- /dev/null+++ b/tools/run_gates.py@@ -0,0 +1,14 @@+#!/usr/bin/env python3+"""Run the installed harness gate runner with an explicit plugin directory."""+import os, sys+root = os.environ.get("IMG2_HOME")+if root: sys.path.insert(0, os.path.join(root, "harness"))+else:+ try: import _img2_local; sys.path.insert(0, _img2_local.CORE)+ except ImportError: sys.exit("img2: core not linked - run `img2 sync`")+from img2_core import require_core_api+require_core_api(1)+from img2_core.gate_runner import main++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/validate_scene.mjs b/tools/validate_scene.mjsnew file mode 100755index 0000000..a6b853c--- /dev/null+++ b/tools/validate_scene.mjs@@ -0,0 +1,78 @@+#!/usr/bin/env node+// Validate actual assets with the pinned workspace dependency; no network callbacks.+import { createHash, randomUUID } from 'node:crypto';+import { lstat, mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseArgs } from 'node:util';++const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');+const plugin = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const inside = (root, target) => {+ const relative = path.relative(root, target);+ return relative === '' || (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));+};++async function main() {+ const { values } = parseArgs({ options: {+ workspace: { type: 'string' }, asset: { type: 'string' }, 'run-id': { type: 'string', default: randomUUID() },+ } });+ if (!values.workspace || !values.asset) throw new Error('Use --workspace W --asset W-relative.glb [--run-id ID] after npm ci');+ const workspace = await realpath(path.resolve(values.workspace));+ if (inside(await realpath(plugin), workspace)) throw new Error('Authored workspace must be outside the installed plugin');+ const run = values['run-id'];+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(run)) throw new Error('run-id must be a plain slug, at most 64 characters');++ async function confined(relative) {+ if (path.isAbsolute(relative)) throw new Error('Expected a workspace-relative asset/output');+ const target = path.resolve(workspace, relative);+ if (!inside(workspace, target)) throw new Error('Resource escapes workspace: ' + relative);+ let current = workspace;+ for (const part of path.relative(workspace, target).split(path.sep)) {+ current = path.join(current, part);+ try {+ if ((await lstat(current)).isSymbolicLink()) throw new Error('Symlinked resource/output is not permitted: ' + relative);+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ }+ }+ return target;+ }++ const asset = await confined(values.asset);+ if (!/\.(gltf|glb)$/i.test(asset)) throw new Error('Expected a .gltf or .glb file');+ if ((await stat(asset)).size > 512 * 1024 * 1024) throw new Error('Validation input exceeds 512 MiB');+ const bytes = await readFile(asset);+ const require = createRequire(path.join(workspace, 'package.json'));+ const validator = require('gltf-validator');+ const resources = [];+ const report = await validator.validateBytes(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), {+ uri: path.basename(asset), maxIssues: 10000,+ externalResourceFunction: async uri => {+ if (typeof uri !== 'string' || /^[a-z][\w+.-]*:/i.test(uri) || uri.startsWith('//') || /[?#\\]/.test(uri)) {+ throw new Error('Only local workspace resources may be validated: ' + uri);+ }+ const decoded = decodeURIComponent(uri);+ const target = await confined(path.relative(workspace, path.resolve(path.dirname(asset), decoded)));+ if ((await stat(target)).size > 512 * 1024 * 1024) throw new Error('Validation dependency exceeds 512 MiB');+ const data = await readFile(target);+ resources.push({ path: path.relative(workspace, target), bytes: data.length, sha256: sha256(data) });+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);+ },+ });+ const output = await confined(path.join('.img2/artifacts/interior/production', run, 'khronos-' + path.basename(asset) + '.json'));+ const result = { schemaVersion: 1, asset: values.asset, bytes: bytes.length, sha256: sha256(bytes),+ validatorVersion: validator.version(), resources, report,+ passed: report.issues.numErrors === 0 && report.issues.truncated !== true,+ limit: 'glTF conformance only; no image likeness, native reopening or interaction approval' };+ await mkdir(path.dirname(output), { recursive: true });+ await writeFile(output, JSON.stringify(result, null, 2) + '\n', { flag: 'wx' });+ console.log(JSON.stringify({ ...result, report: report.issues, receipt: path.relative(workspace, output) }, null, 2));+ process.exitCode = result.passed ? 0 : 1;+}++main().catch(error => {+ console.error(JSON.stringify({ status: 'error', reason: String(error.message ?? error) }));+ process.exitCode = 2;+});diff --git a/tools/workflow_support.py b/tools/workflow_support.pynew file mode 100644index 0000000..ff4b2df--- /dev/null+++ b/tools/workflow_support.py@@ -0,0 +1,370 @@+"""Interior attestations: ordered, content-pinned, append-only decision history.++This checks provenance and workflow consistency, never visual quality. All mutation+runs inside img2_core's plugin-subtree transaction; readers never acquire a lock.+"""++import copy+import hashlib+import json+import math+import os+from pathlib import Path++from img2_core.paths import resolve_workspace+from img2_core.state import update_plugin_state++STAGES = ("intake", "camera", "geometry", "materials", "lighting", "interaction", "delivery", "review")+DECISIONS = ("accept", "reject", "request-input", "stop")+WORKFLOW_KEYS = ("schemaVersion", "source", "intake", "stages", "history")+ATTESTATION = "Reviewer attestation only; existence, order and freshness are checked, not visual quality."+++class Refusal(ValueError):+ """Malformed input or an operation that would destroy provenance."""+++class Incomplete(ValueError):+ """Well-formed run that is incomplete or no longer fresh."""+++def nonempty(value, label):+ if not isinstance(value, str) or not value.strip():+ raise Refusal(f"{label} must be nonempty text")+ return value+++def _pairs(pairs):+ result = {}+ for key, value in pairs:+ if key in result:+ raise Refusal(f"duplicate JSON key: {key}")+ result[key] = value+ return result+++def _constant(value):+ raise Refusal(f"nonfinite JSON constant: {value}")+++def _float(value):+ number = float(value)+ if not math.isfinite(number):+ raise Refusal(f"nonfinite JSON number: {value}")+ return number+++def read_json(path):+ try:+ return json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=_pairs,+ parse_constant=_constant, parse_float=_float)+ except (UnicodeError, json.JSONDecodeError) as exc:+ raise Refusal(f"malformed JSON in {path}: {exc}") from exc+++def validate_intake(doc):+ if not isinstance(doc, dict) or type(doc.get("schemaVersion")) is not int or doc["schemaVersion"] != 1:+ raise Refusal("intake schemaVersion must be integer 1")+ if doc.get("sourceKind") not in ("synthetic-design-reference", "photo", "render", "floorplan"):+ raise Refusal("intake sourceKind is invalid")+ nonempty(doc.get("authorization"), "intake authorization")+ scale = doc.get("scale")+ if not isinstance(scale, dict) or scale.get("unit") != "m" or scale.get("basis") not in ("authored-estimate", "measured"):+ raise Refusal("intake scale requires unit m and basis authored-estimate or measured")+ nonempty(scale.get("note"), "intake scale note")+ components = doc.get("components")+ if not isinstance(components, list) or not components:+ raise Refusal("intake components must be a nonempty array")+ for component in components:+ nonempty(component, "intake component")+ if len({item.strip() for item in components}) != len(components):+ raise Refusal("intake components must be unique")+ if not isinstance(doc.get("unknowns"), list) or any(not isinstance(item, str) for item in doc["unknowns"]):+ raise Refusal("intake unknowns must be an array of strings")+ if type(doc.get("interactionRequired")) is not bool:+ raise Refusal("intake interactionRequired must be boolean")+ return doc+++def workspace_path(raw):+ if not Path(raw).expanduser().is_absolute():+ raise Refusal("--workspace must be absolute")+ workspace = resolve_workspace(raw)+ if not workspace.is_dir():+ raise Refusal("workspace must be an existing directory")+ # Core's state writer follows parent directories. Reject redirected control+ # paths before handing it a workspace, including its temporary file and lock.+ for relative in (".img2", ".img2/artifacts", ".img2/artifacts/interior",+ ".img2/state.json", ".img2/state.json.tmp", ".img2/.lock"):+ path = workspace / relative+ if path.is_symlink():+ raise Refusal(f"workspace control path must not be a symlink: {path}")+ return workspace+++def input_path(workspace, raw):+ path = Path(raw).expanduser()+ if not path.is_absolute():+ path = workspace / path+ return Path(os.path.abspath(path))+++def snapshot_path(workspace):+ return workspace / ".img2/artifacts/interior/intake.json"+++def pin_file(path, workspace=None):+ path = Path(path)+ resolved = path.resolve(strict=True)+ if workspace is not None and not resolved.is_relative_to(workspace):+ raise Refusal(f"evidence must resolve inside workspace: {path}")+ if not resolved.is_file():+ raise Refusal(f"not a regular file: {path}")+ digest = hashlib.sha256()+ size = 0+ with resolved.open("rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(chunk)+ size += len(chunk)+ if not size:+ raise Refusal(f"empty file is not evidence: {path}")+ return {"path": str(path), "resolvedPath": str(resolved), "sha256": digest.hexdigest(), "size": size}+++def validate_pin(pin):+ if not isinstance(pin, dict) or set(pin) != {"path", "resolvedPath", "sha256", "size"}:+ raise Refusal("malformed file pin")+ for key in ("path", "resolvedPath"):+ nonempty(pin[key], f"pin {key}")+ if not Path(pin[key]).is_absolute():+ raise Refusal(f"pin {key} must be absolute")+ digest = pin["sha256"]+ if not isinstance(digest, str) or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):+ raise Refusal("pin sha256 must be 64 lowercase hex characters")+ if type(pin["size"]) is not int or pin["size"] <= 0:+ raise Refusal("pin size must be a positive integer")+++def includes_snapshot(evidence, snapshot):+ # A workspace alias can spell the same file differently; retain its lexical+ # pin for later retarget detection, but compare resolved identity and bytes.+ return any(all(pin[key] == snapshot[key] for key in ("resolvedPath", "sha256", "size"))+ for pin in evidence)+++def pending_stages():+ return {name: {"status": "pending"} for name in STAGES}+++def invalidate(stages, stage):+ for name in STAGES[STAGES.index(stage):]:+ stages[name] = {"status": "pending"}+++def cursor(stages):+ return next((name for name in STAGES if stages[name]["status"] != "accepted"), None)+++def validate_run(run, workspace):+ if not isinstance(run, dict):+ raise Refusal("plugins.interior must be an object")+ if not any(key in run for key in WORKFLOW_KEYS):+ return None+ if type(run.get("schemaVersion")) is not int or run["schemaVersion"] != 1:+ raise Refusal("interior schemaVersion must be integer 1")+ validate_pin(run.get("source"))+ intake = run.get("intake")+ if not isinstance(intake, dict) or set(intake) != {"input", "snapshot"}:+ raise Refusal("malformed intake metadata")+ validate_pin(intake["input"])+ validate_pin(intake["snapshot"])+ if intake["snapshot"]["path"] != str(snapshot_path(workspace)) or intake["snapshot"]["resolvedPath"] != str(snapshot_path(workspace)):+ raise Refusal("intake snapshot is not at the required workspace path")+ history = run.get("history")+ if not isinstance(history, list) or not history:+ raise Refusal("interior history must contain initialization")+ expected_init = {"sequence": 1, "action": "init", "source": run["source"], "intake": intake}+ if history[0] != expected_init:+ raise Refusal("initialization history disagrees with immutable input pins")+ stages = pending_stages()+ for sequence, event in enumerate(history[1:], 2):+ if not isinstance(event, dict) or type(event.get("sequence")) is not int or event["sequence"] != sequence:+ raise Refusal("history sequence is malformed")+ stage = event.get("stage")+ if stage not in STAGES:+ raise Refusal("history contains an unknown stage")+ if event.get("action") == "revise":+ if set(event) != {"sequence", "action", "stage", "reason"}:+ raise Refusal("malformed revision history")+ nonempty(event["reason"], "revision reason")+ invalidate(stages, stage)+ elif event.get("action") == "record":+ if set(event) != {"sequence", "action", "stage", "decision", "reviewer", "note", "evidence", "attestation"}:+ raise Refusal("malformed decision history")+ decision = event["decision"]+ if decision not in DECISIONS or event["attestation"] != ATTESTATION:+ raise Refusal("malformed decision or attestation")+ nonempty(event["reviewer"], "reviewer")+ nonempty(event["note"], "note")+ evidence = event["evidence"]+ if not isinstance(evidence, list) or (decision == "accept" and not evidence):+ raise Refusal("acceptance requires evidence")+ for pin in evidence:+ validate_pin(pin)+ if not Path(pin["resolvedPath"]).is_relative_to(workspace):+ raise Refusal("stored evidence escapes workspace")+ if len({pin["resolvedPath"] for pin in evidence}) != len(evidence):+ raise Refusal("duplicate evidence files")+ if decision == "accept":+ if stage != cursor(stages) or stages[stage]["status"] != "pending":+ raise Refusal("history contains out-of-order or duplicate stage acceptance")+ if stage == "intake" and not includes_snapshot(evidence, intake["snapshot"]):+ raise Refusal("intake acceptance must include its validated snapshot")+ elif any(stages[name]["status"] != "accepted" for name in STAGES[:STAGES.index(stage)]):+ raise Refusal("history contains out-of-order decision")+ invalidate(stages, stage)+ stages[stage] = {"status": {"accept": "accepted", "reject": "rejected", "request-input": "blocked", "stop": "stopped"}[decision], "record": sequence}+ else:+ raise Refusal("unknown history action")+ if run.get("stages") != stages:+ raise Refusal("stage state disagrees with decision history")+ return run+++def read_run(workspace):+ path = workspace / ".img2/state.json"+ if not path.exists():+ return None+ envelope = read_json(path)+ if not isinstance(envelope, dict) or type(envelope.get("version")) is not int or envelope["version"] != 1 or not isinstance(envelope.get("plugins"), dict):+ raise Refusal("malformed img2 state envelope")+ return validate_run(envelope["plugins"].get("interior", {}), workspace)+++def freshness(run, workspace):+ reasons = []+ pins = [("source", run["source"], None), ("intake input", run["intake"]["input"], None),+ ("intake snapshot", run["intake"]["snapshot"], workspace)]+ for stage in STAGES:+ item = run["stages"][stage]+ if item["status"] == "accepted":+ event = run["history"][item["record"] - 1]+ pins.extend((f"{stage} evidence", pin, workspace) for pin in event["evidence"])+ checked = {}+ for label, pin, boundary in pins:+ key = (pin["path"], boundary)+ if key not in checked:+ try:+ checked[key] = pin_file(pin["path"], boundary)+ except (OSError, ValueError, RuntimeError) as exc:+ checked[key] = str(exc)+ current = checked[key]+ if current != pin:+ reasons.append(f"{label} is stale or unavailable: {pin['path']}" + (f" ({current})" if isinstance(current, str) else ""))+ # Parsing only fresh bytes distinguishes stale content from a malformed run.+ if not any(label.startswith("intake") for label in reasons):+ validate_intake(read_json(run["intake"]["snapshot"]["path"]))+ return reasons+++def describe(run, workspace):+ if run is None:+ return {"status": "pending", "nextStage": None, "action": "init", "reasons": ["workflow is not initialized"], "attestation": ATTESTATION}+ stage = cursor(run["stages"])+ reasons = freshness(run, workspace)+ status = run["stages"][stage]["status"] if stage else "completed"+ explicit_block = status in ("blocked", "stopped")+ if reasons and not explicit_block:+ status = "blocked"+ if stage and run["stages"][stage]["status"] != "pending":+ record = run["history"][run["stages"][stage]["record"] - 1]+ reasons.append(record["note"])+ return {"status": status, "nextStage": stage, "action": "revise" if status in ("rejected", "stopped", "blocked") else ("record" if stage else "complete"),+ "reasons": reasons, "explicitBlock": explicit_block, "attestation": ATTESTATION}+++def initialize(workspace, image, intake_file):+ read_run(workspace) # Strict parsing before core's permissive JSON loader.+ image = input_path(workspace, image)+ intake_file = input_path(workspace, intake_file)+ source = pin_file(image)+ intake_input = pin_file(intake_file)+ intake_doc = validate_intake(read_json(intake_file))+ if pin_file(intake_file) != intake_input:+ raise Refusal("intake changed while initializing")+ snapshot = snapshot_path(workspace)+ payload = (json.dumps(intake_doc, indent=2, sort_keys=True, allow_nan=False) + "\n").encode("utf-8")++ def change(subtree):+ if validate_run(subtree, workspace) is not None:+ raise Refusal("workflow already initialized; use revise, never reset history")+ if snapshot.exists() or snapshot.is_symlink():+ raise Refusal("intake snapshot already exists; refusing to overwrite provenance")+ snapshot.parent.mkdir(parents=True, exist_ok=True)+ with snapshot.open("xb") as stream:+ stream.write(payload)+ intake = {"input": intake_input, "snapshot": pin_file(snapshot, workspace)}+ subtree.update(schemaVersion=1, source=source, intake=intake, stages=pending_stages(),+ history=[{"sequence": 1, "action": "init", "source": copy.deepcopy(source), "intake": copy.deepcopy(intake)}])++ state = update_plugin_state(workspace, "interior", change)+ return state["plugins"]["interior"]+++def record(workspace, stage, decision, reviewer, note, evidence):+ nonempty(reviewer, "reviewer")+ nonempty(note, "note")+ if decision == "accept" and not evidence:+ raise Refusal("acceptance requires at least one evidence file")+ pins = [pin_file(input_path(workspace, path), workspace) for path in evidence]+ if len({pin["resolvedPath"] for pin in pins}) != len(pins):+ raise Refusal("duplicate evidence files")+ read_run(workspace)++ def change(subtree):+ run = validate_run(subtree, workspace)+ if run is None:+ raise Incomplete("workflow is not initialized")+ if any(run["stages"][name]["status"] != "accepted" for name in STAGES[:STAGES.index(stage)]):+ raise Incomplete("preceding stages must be accepted in order")+ if decision == "accept":+ if run["stages"][stage]["status"] != "pending":+ raise Refusal("stage already decided; revise before accepting again")+ reasons = freshness(run, workspace)+ if reasons:+ raise Incomplete("; ".join(reasons))+ if stage == "intake" and not includes_snapshot(pins, run["intake"]["snapshot"]):+ raise Refusal("intake acceptance must include the validated intake snapshot")+ event = {"sequence": len(run["history"]) + 1, "action": "record", "stage": stage,+ "decision": decision, "reviewer": reviewer, "note": note, "evidence": pins, "attestation": ATTESTATION}+ invalidate(run["stages"], stage)+ run["stages"][stage] = {"status": {"accept": "accepted", "reject": "rejected", "request-input": "blocked", "stop": "stopped"}[decision], "record": event["sequence"]}+ run["history"].append(event)++ state = update_plugin_state(workspace, "interior", change)+ return state["plugins"]["interior"]+++def revise(workspace, stage, reason):+ nonempty(reason, "revision reason")+ read_run(workspace)++ def change(subtree):+ run = validate_run(subtree, workspace)+ if run is None:+ raise Incomplete("workflow is not initialized")+ invalidate(run["stages"], stage)+ run["history"].append({"sequence": len(run["history"]) + 1, "action": "revise", "stage": stage, "reason": reason})++ state = update_plugin_state(workspace, "interior", change)+ return state["plugins"]["interior"]+++def evaluate_gate(workspace):+ run = read_run(workspace)+ if run is None:+ return ["workflow is not initialized"], {"attestation": ATTESTATION}+ reasons = freshness(run, workspace)+ reasons.extend(f"{stage} is {run['stages'][stage]['status']}, not accepted" for stage in STAGES if run["stages"][stage]["status"] != "accepted")+ return reasons, {"attestation": ATTESTATION, "source": run["source"], "intake": run["intake"],+ "stages": run["stages"], "historyLength": len(run["history"])}