3D engine that AI agents drive
Release 0.3.0 graphics workflows and rewrite engine documentation
Nguyen Xuan An9a4f6f468d3a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a7f908ad..615dff56 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,15 @@# Changelog+## 0.3.0++- Introduce deterministic keyframe animation and persistent instance updates.+- Add opt-in HDR, bloom and color grading with render budget accounting.+- Add orthographic cameras and a flat 2D scene viewer.+- Import bounded glTF/GLB assets with textures, vertex colors and rigid node animation through an optional addon.+- Export landscape, portrait and square media, including imported asset animation.+- Add motion and asset studios, implementation roadmap and graphics engine documentation.+- Keep the website package archive identical to the published npm archive.+## 0.2.4- Publish changed versions through GitHub Actions and npm trusted publishing.diff --git a/README.md b/README.mdindex e7c8382b..7d186b54 100644--- a/README.md+++ b/README.md@@ -1,11 +1,13 @@# 67.js-67.js is a JavaScript graphics engine for the browser, built around meshes, materials and cameras familiar to Three.js users.-It combines a focused WebGL2 renderer with interactive scene studios and a workflow for exporting images and cinematic video.-Its optimization work targets shared geometry, predictable frame allocation and explicit CPU/GPU render budgets.+67.js is a JavaScript graphics engine for interactive worlds, animated models and cinematic media in the browser.+Meshes, materials and cameras give Three.js users a familiar foundation. Scene studios, assembly inspection and image/video export extend that foundation into a production workflow.-The current release includes an explodable WALL·E study, an interactive nature world and a deterministic 3D short film.-The viewers use the 67.js renderer. The optional benchmark loads Three.js for comparison.+The renderer is designed around shared geometry, predictable frame allocation and explicit CPU/GPU render budgets.+The aim is to spend less time managing draw calls, capture scripts and memory limits, and more time building the scene.++The current release includes an explodable WALL·E study, an interactive nature world, a 3D short film and a keyframe motion studio.+It also includes flat 2D views and an asset viewer. Every viewer uses the 67.js renderer.## What it includes@@ -14,15 +16,18 @@ The viewers use the 67.js renderer. The optional benchmark loads Three.js for co- Interactive studios with orbit controls, material settings, assembly views and GLB export.- CPU and GPU image/video export with memory planning and encoder backpressure.- A versioned npm package, standalone browser module and release metadata shared by the website and guide.+- Deterministic keyframe animation with retained instance buffers and absolute timeline seeking.+- Optional HDR, bloom and color grading, with reused targets included in the render budget.+- Orthographic cameras and flat XY scenes with pan, zoom and PNG capture.+- An optional glTF/GLB decoder for textured meshes, vertex colors and rigid node animation.## Direction67.js aims to make rendering, interaction and media production available through one browser graphics workflow.-The next implementation adds HDR targets, bloom, color grading, reusable keyframe animation and orthographic 2D views.-It also adds glTF asset input and landscape, portrait and square export presets for films and shorts.-These features are tracked as implementation work. They are not part of the current published API until their release passes verification.+The next implementation targets adaptive quality, GPU timing, picking and reusable interaction controls. See the [implementation roadmap](ROADMAP.md).+Performance improvements are evaluated on matching scenes and hardware. Visual quality follows the needs of each authored scene.-+The WALL·E study contains 574 parts, 860,380 triangles and seven shared geometries.The studio submits eight geometry draws, including the floor.@@ -56,6 +61,9 @@ The library is ESM and bundles its runtime dependencies. Core exports include `R| `/object.html` | WALL·E studio with orbit, zoom, explosion, layers, finishes and GLB export. || `/nature.html` | Silverwater valley with viewpoints, daylight, wind, detail settings and water ripples. || `/film.html` | CRITICAL, a 32-second procedural film with playback and timeline controls. |+| `/motion.html` | Clockwork orbit, a 12-second keyframe animation with HDR and landscape, portrait and square framing. |+| `/view2d.html` | Flat vector scenes and front, right, top or perspective model inspection. |+| `/assets.html` | GLB loading, texture inspection, rigid animation, orbit controls and PNG capture. |CRITICAL combines mechanical details, atomic orbits, waves, a desert test tower and a volumetric ignition sequence.It uses an original synthesized score. The playable MP4 is in `public/media/critical.mp4`.@@ -72,6 +80,9 @@ npm run render -- --kind image --scene object --backend gpu --preset high --outpnpm run render -- --kind image --scene nature --backend gpu --preset high --output artifacts/nature.pngnpm run render -- --kind image --scene object --backend cpu --preset cpu --output artifacts/wall-e-cpu.pngnpm run render -- --kind video --scene film --backend gpu --preset balanced --encoder gpu --output public/media/critical.mp4+npm run render -- --kind video --scene motion --aspect portrait --backend gpu --encoder gpu --output artifacts/short.mp4+npm run render -- --kind image --scene view2d --aspect square --backend cpu --preset cpu --output artifacts/poster.png+npm run render -- --kind video --scene assets --asset model.glb --duration 2 --output artifacts/model.mp4```| Preset | Dimensions | MSAA samples | FPS | Target budget |@@ -87,7 +98,7 @@ The exporter streams one frame at a time and waits for encoder backpressure.It keeps one live scene renderer and disables development reloads during capture.The planner reduces render dimensions before targets exceed their estimated budget.-The estimate includes geometry, shadows, targets and frame staging. It excludes some browser and driver allocations.+The estimate includes geometry, texture mipmaps, shadows, HDR/bloom targets and frame staging. It excludes some browser and driver allocations.The report records actual dimensions, estimated render memory, Node RSS and sampled browser JavaScript heap.Node and JavaScript heap guards stop capture above 512 MiB and 256 MiB respectively.These guards cannot guarantee that every driver or system allocation succeeds.@@ -102,8 +113,9 @@ The repository includes two reusable Codex skills.## Checks and performance1. Run `npm test` to validate geometry, scene budgets, the timeline and independent GLB loading.-2. Run `npm run build` to create the homepage, guide and three production viewers in `dist/`.+2. Run `npm run build` to create the homepage, guide and six production viewers in `dist/`.3. Run `npm run smoke` to exercise the studio in headless Chrome.+4. Run `npm run smoke:enhancements` against the running development server to check motion, orthographic views and textured asset animation.The smoke saves rendered screenshots, a GLB and benchmark results under the ignored `artifacts/` directory.The benchmark compares identical geometry, camera, resolution and flat shaders with both instanced and individual draws.@@ -116,7 +128,7 @@ Detailed measured results and limits are in [verification.md](docs/verification.## API`createModel()` returns shared geometries, column-major matrices, linear RGB materials and optional assembly offsets.-`Renderer67` groups geometry identities into instanced batches.+`Renderer67` groups geometry and texture descriptor identities into instanced batches.```jsimport { Renderer67 } from '67js';@@ -131,8 +143,12 @@ renderer.render({ eye: [4, 3, 7], target: [0, 1.5, 0], assemblyAmount: 0.5 });// Call dispose() before replacing the renderer.```-This prototype supports procedural scenes and authored animation. It lacks texture loading, ray tracing and a general scene graph.-Blender-level realism remains a visual target.+The core exports animation helpers, camera views and effect presets. `renderer.updateParts(parts)` uploads changes without replacing geometry buffers.+The [optional asset addon](docs/gltf.md) loads glTF/GLB meshes, base-color textures, opaque vertex colors and rigid node animation.+It uses Three.js as a decoder. The core renderer and standalone module remain separate from this dependency.++Skinning, morph targets, transparent materials, compressed assets and ray tracing remain outside this release.+Blender-level realism remains a visual target. 67.js does not provide Three.js API compatibility.## Credits@@ -141,6 +157,7 @@ CRITICAL draws inspiration from the visual themes of the [official Oppenheimer tIt includes no film footage, dialogue or soundtrack samples.- [Three.js](https://threejs.org/) and its [source](https://github.com/mrdoob/three.js/) provide the benchmark reference.+- The optional asset addon bundles the Three.js glTF decoder under its MIT license.- [Blender](https://projects.blender.org/blender/blender) provides the visual quality target.- [gl-matrix](https://github.com/toji/gl-matrix) supplies matrix operations.@@ -154,5 +171,5 @@ The homepage and guide read this endpoint for their commands and downloads.2. Run `npm test` and `npm run build`.3. Run `npm run smoke:package`. It verifies a clean consumer installation.4. Commit and push the release.-5. Run `npm publish --access public`. It publishes the library.-6. Run `npm run deploy`. It verifies the pushed commit, rebuilds and checks the live release.+5. The `publish.yml` GitHub Actions workflow verifies the package and publishes new versions through the npm trusted publisher. Wait for a successful run and registry availability.+6. Run `npm run deploy`. It verifies the pushed commit, rebuilds and checks the live release. If npm has published the version, the site serves its canonical package archive and integrity.diff --git a/ROADMAP.md b/ROADMAP.mdnew file mode 100644index 00000000..033550ee--- /dev/null+++ b/ROADMAP.md@@ -0,0 +1,29 @@+# 67.js implementation roadmap++67.js develops a browser graphics engine with a shared workflow for interactive scenes, animation and exported media.+This document separates shipping capabilities from work in progress. Performance claims require measurements on matching scenes and hardware.++## Available++- Instanced shared geometry, PBR lighting, shadows, MSAA, FXAA and ACES tone mapping.+- Object inspection, individual assembly explosion, environment controls and deterministic film sampling.+- GLB geometry export and streamed PNG/MP4 capture on hardware WebGL or CPU SwiftShader.+- Render memory estimates, capture guards, npm distribution and synchronized website release metadata.+- General keyframe animation with reusable transforms, material tracks and deterministic seeking.+- Optional HDR, bloom, color grading and reused render targets within the render budget.+- Orthographic front, right and top views, plus flat XY scenes with pan, zoom and capture.+- glTF/GLB mesh input, base-color textures, opaque vertex colors and rigid node animation.+- Landscape, portrait and square presets, time ranges and a generic capture interface for scenes and imported assets.++## Next++1. Adaptive quality with a target frame time, explicit minimum resolution and stable changes to avoid visible oscillation.+2. GPU timing and scene diagnostics that distinguish CPU submission, GPU work and estimated memory.+3. Picking and reusable interaction controls for object selection, annotations and assembly inspection.+4. Asset budgets and loading diagnostics for AI-generated models, including texture sizes, unsupported materials and geometry complexity.+5. Declarative scene recipes for product viewers, interactive worlds and short films, with reusable camera and lighting presets.++## Longer term++Evaluate WebGPU after collecting WebGL2 bottleneck measurements. Add skinning, morph targets and more glTF materials as bounded asset support grows.+Blender is the visual quality reference for authored scenes. Rendering parity and universal speed advantages remain goals that need evidence.diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdnew file mode 100644index 00000000..8ada2a5f--- /dev/null+++ b/THIRD-PARTY-NOTICES.md@@ -0,0 +1,21 @@+The MIT License++Copyright © 2010-2026 three.js authors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.diff --git a/assets.html b/assets.htmlnew file mode 100644index 00000000..8dcbd01c--- /dev/null+++ b/assets.html@@ -0,0 +1,35 @@+<!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="Load a GLB asset into 67.js, inspect its materials and scrub rigid node animation." />+ <title>Asset viewer · 67.js</title>+ </head>+ <body>+ <main class="workspace">+ <header class="toolbar">+ <a class="brand" href="./index.html">67<span>.js</span></a>+ <h1>Asset viewer</h1>+ <nav aria-label="Camera view">+ <button data-view="perspective" aria-pressed="true">Perspective</button>+ <button data-view="front" aria-pressed="false">Front</button>+ <button data-view="right" aria-pressed="false">Right</button>+ <button data-view="top" aria-pressed="false">Top</button>+ </nav>+ <div class="toolbar-actions"><button id="fit">Fit</button><button id="open" class="primary">Open GLB</button></div>+ <input id="file" type="file" accept=".glb,model/gltf-binary" hidden />+ </header>+ <section class="asset-controls" aria-label="Materials and animation">+ <label>Exposure <input id="exposure" type="range" min="0.25" max="2" step="0.05" value="1" /></label>+ <label>Bloom <input id="bloom" type="range" min="0" max="1" step="0.05" value="0" /></label>+ <label>Animation <select id="clip" disabled><option>No animation</option></select></label>+ <button id="save">Save PNG</button>+ </section>+ <section class="stage" aria-label="3D asset"><canvas id="viewport" tabindex="0" aria-label="Asset view. Drag to orbit, scroll to zoom."></canvas><p id="notice" class="notice" role="status" hidden></p></section>+ <div class="timeline"><button id="play" disabled>▶ Play</button><label for="time">Timeline</label><input id="time" type="range" min="0" max="1" step="0.01" value="0" disabled /><output id="time-value">0.00 s</output><span class="metrics" id="metrics"></span></div>+ <p class="hint"><span>Drag to orbit · Scroll to zoom · Drop a GLB file</span><a href="./getting-started.html">API guide ↗</a></p>+ </main>+ <script type="module" src="/src/asset-viewer.js"></script>+ </body>+</html>diff --git a/docs/gltf.md b/docs/gltf.mdindex 52cdee01..6c2d7fe4 100644--- a/docs/gltf.md+++ b/docs/gltf.md@@ -5,8 +5,8 @@ It uses the optional Three.js `GLTFLoader` for decoding, without creating a ThreThe core renderer does not import this addon.```js-import { loadGltf } from './src/gltf.js';-import { Renderer67 } from './src/renderer.js';+import { loadGltf } from '67js/addons/gltf';+import { Renderer67 } from '67js';const asset = await loadGltf('/models/object.glb');const renderer = new Renderer67(canvas, asset.parts, {@@ -59,6 +59,7 @@ Geometry contains `positions` and `normals` as `Float32Array` values, plus `indiThe importer computes missing normals and normalizes supplied normals.It rejects non-finite attributes, invalid indices, singular transforms, and unusable normals.`geometry.uvs` preserves `TEXCOORD_0` as two floats per vertex.+`geometry.colors` preserves opaque `COLOR_0` values as three linear RGB floats per vertex.Materials preserve linear `color`, `metallic`, `roughness`, and `emissiveColor` factors.`emission` contains the emissive intensity.@@ -117,7 +118,7 @@ Disposal is idempotent, and subsequent animation calls fail explicitly.The bridge supports triangle meshes, PNG/JPEG base color textures, rigid animations, and metallic-roughness material factors.It also supports `KHR_mesh_quantization` and `KHR_materials_emissive_strength`.-The importer rejects alpha blending, alpha masking, double-sided materials, vertex colors, and additional material texture channels.+The importer rejects alpha blending, alpha masking, double-sided materials, vertex transparency, and additional material texture channels.It rejects texture transforms, DRACO, KTX2, GPU instancing, and unsupported extensions, including optional extensions.Line and point primitives are unsupported.The bridge does not import cameras, lights, scene environments, or skin data into Renderer67.diff --git a/docs/release-verification.md b/docs/release-verification.mdindex ee635154..d1e5e6c8 100644--- a/docs/release-verification.md+++ b/docs/release-verification.md@@ -1,6 +1,35 @@# Release verification-The 0.2.0 release uses the package name `67js`. The display name remains 67.js.+## 0.3.0++The package is `@codepawlhq/67js`, installed locally through the `67js` alias. The display name remains 67.js.++| Check | Measured result |+| --- | --- |+| Node tests | 64 tests passed, including ordered and reverse-index hierarchy limits, relative resource paths and negotiated sample reporting. |+| Consumer | A clean project installed the archive and imported the core plus all six addons. |+| HDR and effects | Hardware WebGL negotiated RGBA16F targets. Bloom and color grading changed pixel checksums without graphics errors. |+| Determinism | Out-of-order motion seeks reproduced exact pixel checksums. |+| Resource reuse | Eighty motion updates created zero additional buffers, textures, framebuffers or renderbuffers. |+| Standard assets | An imported GLB displayed two distinct base-color textures and reproduced absolute node animation seeks. |+| Views | Flat XY geometry and front, top, right and perspective model views rendered without graphics errors. |+| CPU | SwiftShader rendered the HDR motion scene and encoded a square 2D clip through libx264. |+| Video | Landscape and portrait motion exports each contain 144 H.264 frames over 12 seconds. Imported GLB animation contains 24 frames over two seconds. |+| Capture queue | Every tested video kept one pending frame and remained within its configured allocation estimate. |+| Regression | WALL·E assembly, layers, exports, benchmark pixel agreement, keyboard controls and context restoration passed. |+| Layout | New studios rendered at 1440, 390 and 320 pixels without horizontal overflow. |++The tested hardware was an RTX 3060 through ANGLE D3D11. Software rendering used Chrome ANGLE SwiftShader.+The allocation figures estimate renderer targets, geometry, textures and capture staging. They do not measure total driver VRAM or browser RSS.++The Codex review found three actionable issues: mismatched capture samples, unnormalized glTF resource URLs and hierarchy limits that depended on node ordering.+Constructor options now select capture samples, and sample reporting follows the negotiated allocation count.+Resource lookup normalizes URLs, and hierarchy validation visits roots before descendant nodes. Regression tests cover all three paths.+Claude reached its weekly limit on both review attempts. This release therefore has one-family source review, with weaker coverage than a completed cross review.++## Historical 0.2.0 checks++The early archive used the unscoped `67js` name before npm rejected that name. The scoped organization package supersedes it.| Check | Measured result || --- | --- |diff --git a/getting-started.html b/getting-started.htmlindex 301d7c64..f7c05333 100644--- a/getting-started.html+++ b/getting-started.html@@ -97,6 +97,45 @@ renderer.dispose(); // Release GPU resources when the scene closes.</code></pre><p>The core exports <code>box</code>, <code>cylinder</code>, <code>sphere</code> and <code>torus</code>. Scene modules use separate addon imports.</p><div class="release-links"><a data-release-api aria-disabled="true">API for this release ↗</a><span data-release-commit>Release commit</span></div></section>+ <section aria-labelledby="effects-title">+ <h2 id="effects-title">Animate and grade a scene</h2>+ <p>Mutate existing part transforms or materials, then upload their changes with <code>updateParts</code>. The renderer reuses instance buffers.</p>+ <pre><code>import { Renderer67, EFFECT_PRESETS, cameraView } from '67js';++const renderer = new Renderer67(canvas, parts, {+ hdr: true,+ samples: 4,+ memoryBudgetMiB: 256,+});+renderer.updateParts(parts); // Upload changed matrices and materials.+renderer.render({+ ...cameraView('front', { target: [0, 0, 0], height: 4 }),+ time: 1,+ effects: EFFECT_PRESETS.cinematic,+});</code></pre>+ <p>HDR uses floating-point targets when the browser supports them. <code>renderer.capabilities</code> reports HDR availability and its fallback reason.</p>+ <p>Effects include bloom, saturation, contrast, temperature, vignette and grain. The neutral defaults preserve the existing renderer appearance.</p>+ <p><code>createAnimationClip</code>, <code>sampleAnimationClip</code> and <code>createAnimationPlayer</code> provide deterministic transform and material tracks.</p>+ </section>+ <section aria-labelledby="assets-title">+ <h2 id="assets-title">Load an asset</h2>+ <pre><code>import { Renderer67 } from '67js';+import { loadGltf } from '67js/addons/gltf';++const asset = await loadGltf('/model.glb');+const renderer = new Renderer67(canvas, asset.parts, {+ ground: false,+ hdr: true,+ memoryBudgetMiB: 256,+});+if (asset.animations.length) {+ renderer.updateParts(asset.applyAnimation(1));+}+renderer.render({ eye: [3, 2, 4], target: [0, 0, 0] });+// On teardown: renderer.dispose(), then asset.dispose().</code></pre>+ <p>The optional addon loads standard meshes, base-color textures, vertex colors and rigid node animation. Unsupported asset features produce explicit errors.</p>+ <p>Skinning, morph targets, transparent materials and compressed geometry remain outside this release. Try a model in the <a class="start-link" href="./assets.html">asset viewer ↗</a>.</p>+ </section></main><script type="module" src="/src/home.js"></script></body>diff --git a/index.html b/index.htmlindex df5446d1..f8fc6deb 100644--- a/index.html+++ b/index.html@@ -23,7 +23,7 @@</aside><main id="content"><header class="introduction">- <div><h1>Browser graphics, in JavaScript</h1><p>A graphics engine with interactive scene studios and an integrated workflow for rendering images and cinematic video</p></div>+ <div><h1>Graphics for interactive worlds and films</h1><p>Create meshes, materials and cameras, then animate scenes and render media in one workflow. Shared geometry and explicit memory budgets guide the renderer.</p></div><a class="start-link" href="./getting-started.html">Build your first scene <span aria-hidden="true">↗</span></a></header><section class="install" aria-label="Install the current release">@@ -38,6 +38,9 @@<a class="example" href="./nature.html"><img src="./previews/nature.png" alt="A winding stream through Silverwater valley" width="1280" height="720" /><div class="example-caption"><h3>Silverwater valley</h3><span>Nature <span aria-hidden="true">↗</span></span></div><p>Move through the landscape and change the light and wind</p></a><a class="example" href="./film.html"><img src="./previews/film-contact.png" alt="Scenes from CRITICAL, a procedural 3D short film" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>CRITICAL</h3><span>Short film <span aria-hidden="true">↗</span></span></div><p>Watch a deterministic film with an original synthesized score</p></a><a class="example" href="./object.html?explosion=1"><img src="./previews/wall-e-exploded.png" alt="WALL·E assemblies separated to reveal the internal mechanisms" width="1280" height="720" loading="lazy" /><div class="example-caption"><h3>Inside the machine</h3><span>Exploded assembly <span aria-hidden="true">↗</span></span></div><p>Separate the assemblies to inspect the electronics and mechanisms</p></a>+ <a class="example" href="./motion.html"><img src="./previews/motion.png" alt="A luminous clockwork mechanism animated from keyframes" width="960" height="540" loading="lazy" /><div class="example-caption"><h3>Clockwork orbit</h3><span>Animation <span aria-hidden="true">↗</span></span></div><p>Scrub keyframes, switch compositions and render a short film</p></a>+ <a class="example" href="./view2d.html"><img src="./previews/view2d.png" alt="A flat orbital poster rendered through an orthographic camera" width="960" height="540" loading="lazy" /><div class="example-caption"><h3>Orbital field</h3><span>2D and views <span aria-hidden="true">↗</span></span></div><p>Pan a vector scene or inspect a model from front, right and top</p></a>+ <a class="example" href="./assets.html"><img src="./previews/assets.png" alt="An imported geometric study displayed in the asset viewer" width="960" height="540" loading="lazy" /><div class="example-caption"><h3>Your models</h3><span>GLB assets <span aria-hidden="true">↗</span></span></div><p>Open a GLB, inspect its materials and sample node animation</p></a></div></section><section id="downloads" class="downloads" aria-labelledby="downloads-title">diff --git a/motion.html b/motion.htmlindex 6bacd5c8..1b96ee79 100644--- a/motion.html+++ b/motion.html@@ -22,6 +22,7 @@<label class="timeline-label" for="motion-time">Timeline <output id="motion-clock">0.0 / 12.0 s</output></label><input id="motion-time" type="range" min="0" max="12" step="0.01" value="0" /><div class="motion-details"><span id="motion-shot">Shot 1 of 3</span><span id="motion-stat"></span></div>+ <p class="motion-details"><a href="./media/clockwork.mp4">Landscape MP4 ↗</a><a href="./media/clockwork-portrait.mp4">Portrait MP4 ↗</a></p></section><p class="interface motion-error" id="motion-error" role="status" hidden></p></main>diff --git a/package-lock.json b/package-lock.jsonindex b0846eb9..d38e668f 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@codepawlhq/67js",- "version": "0.2.4",+ "version": "0.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@codepawlhq/67js",- "version": "0.2.4",+ "version": "0.3.0","license": "MIT","devDependencies": {"gl-matrix": "3.4.4",diff --git a/package.json b/package.jsonindex 3f713ef2..fd8e04d5 100644--- a/package.json+++ b/package.json@@ -1,9 +1,9 @@{"name": "@codepawlhq/67js",- "version": "0.2.4",+ "version": "0.3.0","private": false,"type": "module",- "description": "A browser graphics engine for interactive 3D scenes and cinematic media, with bounded CPU/GPU export",+ "description": "A browser graphics engine for interactive worlds, animation and cinematic media, with memory-aware CPU/GPU export","license": "MIT","homepage": "https://67js.codepawl.com","repository": {@@ -14,7 +14,13 @@"build","README.md","LICENSE",- "CHANGELOG.md"+ "CHANGELOG.md",+ "ROADMAP.md",+ "THIRD-PARTY-NOTICES.md",+ "skills",+ "docs/gltf.md",+ "docs/verification.md",+ "docs/release-verification.md"],"main": "./build/67.module.js","module": "./build/67.module.js",@@ -23,6 +29,9 @@"./addons/model": "./build/model.js","./addons/nature": "./build/nature.js","./addons/film": "./build/film.js",+ "./addons/motion": "./build/motion.js",+ "./addons/canvas2d": "./build/canvas2d.js",+ "./addons/gltf": "./build/gltf.js","./package.json": "./package.json"},"scripts": {@@ -40,6 +49,7 @@"score": "node scripts/score.mjs","export:model": "node scripts/export-model.mjs","smoke:package": "node scripts/smoke-package.mjs",+ "smoke:enhancements": "node scripts/smoke-enhancements.mjs","publish:ci": "node scripts/publish-ci.mjs"},"devDependencies": {diff --git a/public/media/clockwork-portrait.mp4 b/public/media/clockwork-portrait.mp4new file mode 100644index 00000000..bd6f5dbcBinary files /dev/null and b/public/media/clockwork-portrait.mp4 differdiff --git a/public/media/clockwork-portrait.mp4.json b/public/media/clockwork-portrait.mp4.jsonnew file mode 100644index 00000000..c4f8c34c--- /dev/null+++ b/public/media/clockwork-portrait.mp4.json@@ -0,0 +1,40 @@+{+ "scene": "motion",+ "kind": "video",+ "backend": "gpu",+ "preset": "preview",+ "aspect": "portrait",+ "start": 0,+ "encoder": "gpu",+ "assembly": null,+ "width": 540,+ "height": 960,+ "actualRenderSize": {+ "width": 540,+ "height": 960,+ "reduced": false+ },+ "fps": 12,+ "duration": 12,+ "memoryBudgetMiB": 256,+ "peakEstimatedRenderBytes": 43856404,+ "peakNodeBytes": 211009536,+ "peakBrowserHeap": 7310336,+ "maximumPendingFrames": 1,+ "firstFrameBytes": 481082,+ "elapsedSeconds": 25.7497098,+ "graphics": {+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",+ "samples": 2,+ "capabilities": {+ "hdr": true,+ "hdrRequested": true,+ "hdrFallbackReason": null,+ "samples": 2,+ "maximumTextureSize": 16384+ },+ "glError": 0+ },+ "output": "clockwork-portrait.mp4",+ "errors": []+}\ No newline at end of filediff --git a/public/media/clockwork.mp4 b/public/media/clockwork.mp4new file mode 100644index 00000000..f8da2331Binary files /dev/null and b/public/media/clockwork.mp4 differdiff --git a/public/media/clockwork.mp4.json b/public/media/clockwork.mp4.jsonnew file mode 100644index 00000000..ca269162--- /dev/null+++ b/public/media/clockwork.mp4.json@@ -0,0 +1,40 @@+{+ "scene": "motion",+ "kind": "video",+ "backend": "gpu",+ "preset": "preview",+ "aspect": "landscape",+ "start": 0,+ "encoder": "gpu",+ "assembly": null,+ "width": 960,+ "height": 540,+ "actualRenderSize": {+ "width": 960,+ "height": 540,+ "reduced": false+ },+ "fps": 12,+ "duration": 12,+ "memoryBudgetMiB": 256,+ "peakEstimatedRenderBytes": 43856404,+ "peakNodeBytes": 211288064,+ "peakBrowserHeap": 7372700,+ "maximumPendingFrames": 1,+ "firstFrameBytes": 483420,+ "elapsedSeconds": 25.766068999999998,+ "graphics": {+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",+ "samples": 2,+ "capabilities": {+ "hdr": true,+ "hdrRequested": true,+ "hdrFallbackReason": null,+ "samples": 2,+ "maximumTextureSize": 16384+ },+ "glError": 0+ },+ "output": "clockwork.mp4",+ "errors": []+}\ No newline at end of filediff --git a/public/previews/assets.png b/public/previews/assets.pngnew file mode 100644index 00000000..b2a5dfe3Binary files /dev/null and b/public/previews/assets.png differdiff --git a/public/previews/assets.png.json b/public/previews/assets.png.jsonnew file mode 100644index 00000000..ad7e2dba--- /dev/null+++ b/public/previews/assets.png.json@@ -0,0 +1,40 @@+{+ "scene": "assets",+ "kind": "image",+ "backend": "gpu",+ "preset": "preview",+ "aspect": "landscape",+ "start": 0,+ "encoder": null,+ "assembly": null,+ "width": 960,+ "height": 540,+ "actualRenderSize": {+ "width": 960,+ "height": 540,+ "reduced": false+ },+ "fps": 24,+ "duration": null,+ "memoryBudgetMiB": 256,+ "peakEstimatedRenderBytes": 43838004,+ "peakNodeBytes": 126935040,+ "peakBrowserHeap": 0,+ "maximumPendingFrames": 0,+ "firstFrameBytes": 37198,+ "elapsedSeconds": 2.0140044,+ "graphics": {+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",+ "samples": 2,+ "capabilities": {+ "hdr": true,+ "hdrRequested": true,+ "hdrFallbackReason": null,+ "samples": 2,+ "maximumTextureSize": 16384+ },+ "glError": 0+ },+ "output": "assets.png",+ "errors": []+}\ No newline at end of filediff --git a/public/previews/motion.png b/public/previews/motion.pngnew file mode 100644index 00000000..b97043eeBinary files /dev/null and b/public/previews/motion.png differdiff --git a/public/previews/motion.png.json b/public/previews/motion.png.jsonnew file mode 100644index 00000000..7c57f9f2--- /dev/null+++ b/public/previews/motion.png.json@@ -0,0 +1,40 @@+{+ "scene": "motion",+ "kind": "image",+ "backend": "gpu",+ "preset": "preview",+ "aspect": "landscape",+ "start": 0,+ "encoder": null,+ "assembly": null,+ "width": 960,+ "height": 540,+ "actualRenderSize": {+ "width": 960,+ "height": 540,+ "reduced": false+ },+ "fps": 24,+ "duration": null,+ "memoryBudgetMiB": 256,+ "peakEstimatedRenderBytes": 43856404,+ "peakNodeBytes": 122605568,+ "peakBrowserHeap": 0,+ "maximumPendingFrames": 0,+ "firstFrameBytes": 566093,+ "elapsedSeconds": 1.5091984999999999,+ "graphics": {+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",+ "samples": 2,+ "capabilities": {+ "hdr": true,+ "hdrRequested": true,+ "hdrFallbackReason": null,+ "samples": 2,+ "maximumTextureSize": 16384+ },+ "glError": 0+ },+ "output": "motion.png",+ "errors": []+}\ No newline at end of filediff --git a/public/previews/view2d.png b/public/previews/view2d.pngnew file mode 100644index 00000000..44565030Binary files /dev/null and b/public/previews/view2d.png differdiff --git a/public/previews/view2d.png.json b/public/previews/view2d.png.jsonnew file mode 100644index 00000000..22a5d446--- /dev/null+++ b/public/previews/view2d.png.json@@ -0,0 +1,40 @@+{+ "scene": "view2d",+ "kind": "image",+ "backend": "gpu",+ "preset": "preview",+ "aspect": "landscape",+ "start": 0,+ "encoder": null,+ "assembly": null,+ "width": 960,+ "height": 540,+ "actualRenderSize": {+ "width": 960,+ "height": 540,+ "reduced": false+ },+ "fps": 24,+ "duration": null,+ "memoryBudgetMiB": 256,+ "peakEstimatedRenderBytes": 36517120,+ "peakNodeBytes": 124506112,+ "peakBrowserHeap": 0,+ "maximumPendingFrames": 0,+ "firstFrameBytes": 36317,+ "elapsedSeconds": 1.9533025,+ "graphics": {+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",+ "samples": 2,+ "capabilities": {+ "hdr": false,+ "hdrRequested": false,+ "hdrFallbackReason": null,+ "samples": 2,+ "maximumTextureSize": 16384+ },+ "glError": 0+ },+ "output": "view2d.png",+ "errors": []+}\ No newline at end of filediff --git a/scripts/render-media.mjs b/scripts/render-media.mjsindex 4e8130bb..b0337a37 100644--- a/scripts/render-media.mjs+++ b/scripts/render-media.mjs@@ -1,7 +1,7 @@import { chromium } from 'playwright';import { spawn } from 'node:child_process';import { once } from 'node:events';-import { mkdir, writeFile } from 'node:fs/promises';+import { mkdir, writeFile, stat } from 'node:fs/promises';import { existsSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { resolve, dirname, basename } from 'node:path';@@ -9,7 +9,7 @@ import { RENDER_PRESETS } from '../src/budget.js';function argumentsFrom(values) {const result = {};- const allowed = new Set(['kind', 'backend', 'scene', 'preset', 'width', 'height', 'fps', 'duration', 'time', 'memory', 'assembly', 'output', 'audio', 'encoder', 'start', 'aspect']);+ const allowed = new Set(['kind', 'backend', 'scene', 'preset', 'width', 'height', 'fps', 'duration', 'time', 'memory', 'assembly', 'output', 'audio', 'encoder', 'start', 'aspect', 'asset']);for (let index = 0; index < values.length; index += 2) {if (!values[index].startsWith('--') || values[index + 1] === undefined) throw new Error('Every option needs a value.');const name = values[index].slice(2);@@ -27,7 +27,8 @@ export function parseRenderOptions(values) {const presetName = options.preset ?? (backend === 'cpu' ? 'cpu' : 'balanced');const preset = RENDER_PRESETS[presetName];const aspect = options.aspect ?? 'landscape';- if (!preset || !['image', 'video', 'stills'].includes(kind) || !['gpu', 'cpu'].includes(backend) || !['film', 'nature', 'object', 'motion', 'view2d'].includes(scene) || !['landscape', 'portrait', 'square'].includes(aspect)) throw new Error('Unknown render kind, backend, scene, aspect or preset.');+ if (!preset || !['image', 'video', 'stills'].includes(kind) || !['gpu', 'cpu'].includes(backend) || !['film', 'nature', 'object', 'motion', 'view2d', 'assets'].includes(scene) || !['landscape', 'portrait', 'square'].includes(aspect)) throw new Error('Unknown render kind, backend, scene, aspect or preset.');+ if (options.asset && scene !== 'assets') throw new Error('The asset file option requires --scene assets.');const numberOption = (name, fallback, minimum, maximum) => {const value = Number(options[name] ?? fallback);if (!Number.isFinite(value) || value < minimum || value > maximum) throw new Error(`${name} must be between ${minimum} and ${maximum}.`);@@ -45,7 +46,7 @@ export function parseRenderOptions(values) {if (kind === 'video' && (width % 2 || height % 2)) throw new Error('Video dimensions must be even for yuv420p output.');const fps = numberOption('fps', preset.fps, 1, 60);const duration = numberOption('duration', scene === 'motion' ? 12 : 32, 0.1, 120);- const time = numberOption('time', 3, 0, 3600);+ const time = numberOption('time', scene === 'assets' ? 0 : 3, 0, 3600);const start = numberOption('start', 0, 0, 3600);const memory = numberOption('memory', preset.memoryBudgetMiB, 32, 1024);const assembly = numberOption('assembly', 0, 0, 1);@@ -60,6 +61,10 @@ export async function renderMedia(values = process.argv.slice(2)) {const plan = parseRenderOptions(values);const { options, kind, backend, scene, presetName, preset, aspect, width, height, fps, time, start, memory, assembly, output, encoderBackend } = plan;let duration = plan.duration;+ if (options.asset) {+ const details = await stat(resolve(options.asset));+ if (!details.isFile() || details.size > 32 * 1024 ** 2) throw new Error('Asset capture requires a GLB file of at most 32 MiB.');+ }await mkdir(dirname(output), { recursive: true });const root = fileURLToPath(new URL('..', import.meta.url));const ffmpeg = process.platform === 'win32' ? resolve(process.env.USERPROFILE, '.local/bin/ffmpeg.exe') : 'ffmpeg';@@ -94,6 +99,12 @@ export async function renderMedia(values = process.argv.slice(2)) {const query = new URLSearchParams({ export: '1', width: String(width), height: String(height), aspect, memory: String(memory), samples: String(backend === 'cpu' ? 1 : preset.samples) });await page.goto(`http://127.0.0.1:5181/${route}?${query}`);await page.waitForFunction((mode) => window.__scene?.renderer || (mode === 'film' ? window.__filmReady : mode === 'nature' ? window.__nature?.renderer : mode === 'object' ? window.__studio?.renderer : false), scene, { timeout: 60000 });+ if (options.asset) {+ await page.locator('#file').setInputFiles(resolve(options.asset));+ await page.waitForFunction(() => document.querySelector('#notice').hidden || document.querySelector('#notice').textContent.startsWith('⚠'));+ const failure = await page.locator('#notice').evaluate(element => element.hidden ? null : element.textContent);+ if (failure) throw new Error(`Asset import failed: ${failure}`);+ }const sceneDuration = await page.evaluate(() => window.__scene?.duration ?? (window.__film ? 32 : null));if (Number.isFinite(sceneDuration) && sceneDuration > 0) {if (start >= sceneDuration) throw new Error('Start time must precede the end of the scene.');@@ -113,7 +124,6 @@ export async function renderMedia(values = process.argv.slice(2)) {const renderer = window.__scene?.renderer ?? (scene === 'object' ? window.__studio.renderer : window.__nature.renderer);renderer.memoryBudgetMiB = memory;renderer.pixelRatio = 1;- renderer.samples = samples;renderer.resize();if (window.__scene) return;if (scene === 'object') {@@ -194,7 +204,7 @@ export async function renderMedia(values = process.argv.slice(2)) {const renderer = window.__scene?.renderer ?? window.__film?.renderer ?? window.__nature?.renderer ?? window.__studio?.renderer;const context = renderer.context;const extension = context.getExtension('WEBGL_debug_renderer_info');- return { gpu: extension ? context.getParameter(extension.UNMASKED_RENDERER_WEBGL) : 'unavailable', samples: renderer.samples, glError: context.getError() };+ return { gpu: extension ? context.getParameter(extension.UNMASKED_RENDERER_WEBGL) : 'unavailable', samples: renderer.capabilities?.samples ?? renderer.samples, capabilities: renderer.capabilities, glError: context.getError() };});if (graphics.glError !== 0) throw new Error(`WebGL render error ${graphics.glError}.`);if (backend === 'cpu' && !graphics.gpu.toLowerCase().includes('swiftshader')) throw new Error('CPU backend did not select SwiftShader.');diff --git a/scripts/smoke-enhancements.mjs b/scripts/smoke-enhancements.mjsnew file mode 100644index 00000000..c9c21054--- /dev/null+++ b/scripts/smoke-enhancements.mjs@@ -0,0 +1,203 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { deflateSync } from 'node:zlib';+import { chromium } from 'playwright';++const origin = process.argv[2] ?? 'http://127.0.0.1:5173';+await mkdir('artifacts', { recursive: true });++function checksum(bytes) {+ let result = 0xffffffff;+ for (const byte of bytes) {+ result ^= byte;+ for (let bit = 0; bit < 8; bit++) result = result & 1 ? 0xedb88320 ^ result >>> 1 : result >>> 1;+ }+ return (result ^ 0xffffffff) >>> 0;+}++function png(color) {+ const chunk = (type, bytes) => {+ const name = Buffer.from(type);+ const output = Buffer.alloc(bytes.length + 12);+ output.writeUInt32BE(bytes.length);+ name.copy(output, 4);+ bytes.copy(output, 8);+ output.writeUInt32BE(checksum(Buffer.concat([name, bytes])), output.length - 4);+ return output;+ };+ const header = Buffer.alloc(13);+ header.writeUInt32BE(16, 0);+ header.writeUInt32BE(16, 4);+ header[8] = 8;+ header[9] = 6;+ const pixels = Buffer.alloc(16 * 65);+ for (let row = 0; row < 16; row++) {+ for (let column = 0; column < 16; column++) {+ const offset = row * 65 + 1 + column * 4;+ const light = ((row >> 2) + (column >> 2)) % 2 ? [230, 230, 230] : color;+ light.forEach((value, channel) => { pixels[offset + channel] = value; });+ pixels[offset + 3] = 255;+ }+ }+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', header), chunk('IDAT', deflateSync(pixels)), chunk('IEND', Buffer.alloc(0))]);+}++function fixture() {+ const chunks = [];+ const bufferViews = [];+ let length = 0;+ const add = data => {+ const bytes = Buffer.from(data.buffer ?? data, data.byteOffset ?? 0, data.byteLength ?? data.length);+ const view = bufferViews.length;+ bufferViews.push({ buffer: 0, byteOffset: length, byteLength: bytes.length });+ chunks.push(bytes, Buffer.alloc((4 - bytes.length % 4) % 4));+ length += Math.ceil(bytes.length / 4) * 4;+ return view;+ };+ const positions = add(new Float32Array([-0.8, -0.8, 0, 0.8, -0.8, 0, 0.8, 0.8, 0, -0.8, 0.8, 0]));+ const normals = add(new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]));+ const uvs = add(new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]));+ const indices = add(new Uint16Array([0, 1, 2, 0, 2, 3]));+ const times = add(new Float32Array([0, 1, 2]));+ const translation = add(new Float32Array([-1.1, 0, 0, -1.1, 0.5, 0, -1.1, 0, 0]));+ const red = add(png([230, 30, 30]));+ const blue = add(png([30, 90, 230]));+ const accessor = (bufferView, componentType, count, type, extra = {}) => ({ bufferView, componentType, count, type, ...extra });+ const document = {+ asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0, 1] }],+ nodes: [{ name: 'Red panel', mesh: 0, translation: [-1.1, 0, 0] }, { name: 'Blue panel', mesh: 1, translation: [1.1, 0, 0] }],+ meshes: [0, 1].map(material => ({ primitives: [{ attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, indices: 3, material }] })),+ materials: [0, 1].map(index => ({ pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], baseColorTexture: { index }, metallicFactor: 0, roughnessFactor: 0.8 } })),+ textures: [{ source: 0 }, { source: 1 }], images: [{ bufferView: red, mimeType: 'image/png' }, { bufferView: blue, mimeType: 'image/png' }],+ animations: [{ name: 'Panel rise', samplers: [{ input: 4, output: 5, interpolation: 'LINEAR' }], channels: [{ sampler: 0, target: { node: 0, path: 'translation' } }] }],+ accessors: [accessor(positions, 5126, 4, 'VEC3', { min: [-0.8, -0.8, 0], max: [0.8, 0.8, 0] }), accessor(normals, 5126, 4, 'VEC3'), accessor(uvs, 5126, 4, 'VEC2'), accessor(indices, 5123, 6, 'SCALAR'), accessor(times, 5126, 3, 'SCALAR', { min: [0], max: [2] }), accessor(translation, 5126, 3, 'VEC3')],+ bufferViews, buffers: [{ byteLength: length }],+ };+ const json = Buffer.from(JSON.stringify(document));+ const padded = Buffer.concat([json, Buffer.alloc((4 - json.length % 4) % 4, 32)]);+ const binary = Buffer.concat(chunks);+ const output = Buffer.alloc(28 + padded.length + binary.length);+ output.writeUInt32LE(0x46546c67, 0);+ output.writeUInt32LE(2, 4);+ output.writeUInt32LE(output.length, 8);+ output.writeUInt32LE(padded.length, 12);+ output.writeUInt32LE(0x4e4f534a, 16);+ padded.copy(output, 20);+ output.writeUInt32LE(binary.length, 20 + padded.length);+ output.writeUInt32LE(0x004e4942, 24 + padded.length);+ binary.copy(output, 28 + padded.length);+ return output;+}++await writeFile('artifacts/textured-animation.glb', fixture());+const browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist'] });+const errors = [];+const report = {};+try {+ const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });+ page.on('pageerror', error => errors.push(error.message));+ await page.goto(`${origin}/motion.html`);+ await page.waitForFunction(() => window.__scene?.renderer);+ report.motion = await page.evaluate(() => {+ const scene = window.__scene;+ scene.pause();+ const renderer = scene.renderer;+ const context = renderer.context;+ const counts = { buffer: 0, texture: 0, framebuffer: 0, renderbuffer: 0 };+ for (const [key, method] of Object.entries({ buffer: 'createBuffer', texture: 'createTexture', framebuffer: 'createFramebuffer', renderbuffer: 'createRenderbuffer' })) {+ const original = context[method].bind(context);+ context[method] = (...argumentsList) => { counts[key]++; return original(...argumentsList); };+ }+ const pixels = new Uint8Array(4 * renderer.canvas.width * renderer.canvas.height);+ const checksum = () => {+ context.readPixels(0, 0, renderer.canvas.width, renderer.canvas.height, context.RGBA, context.UNSIGNED_BYTE, pixels);+ let sum = 0;+ for (let index = 0; index < pixels.length; index += 17) sum = (sum * 31 + pixels[index]) >>> 0;+ return sum;+ };+ scene.renderAt(6);+ const first = checksum();+ for (let index = 0; index < 80; index++) scene.renderAt(index * 0.1);+ scene.renderAt(6);+ const repeated = checksum();+ const sampled = window.__motion.scene.sample(6);+ renderer.render({ ...sampled.camera, time: 6, effects: {} });+ const neutral = checksum();+ renderer.render({ ...sampled.camera, time: 6, effects: { bloom: { strength: 1, threshold: 0.5 } } });+ const bloom = checksum();+ renderer.render({ ...sampled.camera, time: 6, effects: { saturation: 0 } });+ const graded = checksum();+ scene.renderAt(6);+ return { first, repeated, neutral, bloom, graded, counts, error: context.getError(), capabilities: renderer.capabilities, memory: renderer.memoryPlan, draws: renderer.batches.length };+ });+ assert.equal(report.motion.first, report.motion.repeated, 'Seeking must reproduce exact pixels.');+ assert.ok(report.motion.first > 0);+ assert.deepEqual(report.motion.counts, { buffer: 0, texture: 0, framebuffer: 0, renderbuffer: 0 });+ assert.equal(report.motion.error, 0);+ assert.notEqual(report.motion.neutral, report.motion.bloom, 'Bloom must change rendered pixels.');+ assert.notEqual(report.motion.neutral, report.motion.graded, 'Color grading must change rendered pixels.');+ await page.screenshot({ path: 'artifacts/motion-studio.png' });+ await page.goto(`${origin}/view2d.html`);+ await page.waitForFunction(() => window.__scene?.renderer);+ report.view2d = await page.evaluate(() => { window.__scene.renderAt(3); return { error: window.__scene.renderer.context.getError(), draws: window.__scene.renderer.batches.length }; });+ assert.equal(report.view2d.error, 0);+ await page.screenshot({ path: 'artifacts/view2d-studio.png' });+ await page.selectOption('#scene', 'model');+ for (const view of ['front', 'top', 'right', 'perspective']) {+ await page.locator(`[data-view="${view}"]`).click();+ await page.waitForTimeout(60);+ assert.equal(await page.evaluate(() => window.__scene.renderer.context.getError()), 0);+ }+ await page.goto(`${origin}/assets.html`);+ await page.waitForFunction(() => window.__assetViewer?.renderer);+ await page.locator('#file').setInputFiles('artifacts/textured-animation.glb');+ await page.waitForFunction(() => window.__assetViewer?.asset?.animations.length === 1);+ report.asset = await page.evaluate(() => {+ const viewer = window.__assetViewer;+ viewer.renderAt(1);+ const result = { error: viewer.renderer.context.getError(), draws: viewer.renderer.batches.length, parts: viewer.asset.parts.length, textures: viewer.asset.parts.map(part => [part.material.map.image.width, part.material.map.image.height]), position: viewer.asset.parts[0].matrix[13] };+ viewer.renderAt(0);+ viewer.renderAt(1);+ result.repeated = viewer.asset.parts[0].matrix[13];+ return result;+ });+ assert.equal(report.asset.error, 0);+ assert.equal(report.asset.draws, 2, 'Different textures require distinct batches.');+ assert.equal(report.asset.position, 0.5);+ assert.equal(report.asset.repeated, report.asset.position);+ assert.deepEqual(report.asset.textures, [[16, 16], [16, 16]]);+ await page.screenshot({ path: 'artifacts/asset-studio.png' });+ for (const width of [390, 320]) {+ await page.setViewportSize({ width, height: 900 });+ for (const route of ['motion.html', 'view2d.html', 'assets.html']) {+ await page.goto(`${origin}/${route}`);+ await page.waitForFunction(() => window.__scene?.renderer || window.__assetViewer?.renderer);+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, `${route} overflow at ${width}`);+ await page.screenshot({ path: `artifacts/${route}-${width}.png`, fullPage: true });+ }+ }+ report.fallback = await page.evaluate(async () => {+ const { Renderer67, box } = await import('/src/index.js');+ const canvas = document.createElement('canvas');+ canvas.style.cssText = 'width:128px;height:128px';+ document.body.append(canvas);+ const context = canvas.getContext('webgl2');+ const extension = context.getExtension.bind(context);+ context.getExtension = name => name === 'EXT_color_buffer_float' ? null : extension(name);+ const part = { name: 'Fallback cube', geometry: box(), matrix: new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]), material: { color: [0.2,0.5,0.3], metallic: 0, roughness: 0.5 } };+ const renderer = new Renderer67(canvas, [part], { ground: false, hdr: true, samples: 2, pixelRatio: 1, memoryBudgetMiB: 32 });+ renderer.render({ eye: [3,2,4], target: [0,0,0] });+ const result = { capabilities: renderer.capabilities, error: context.getError() };+ renderer.dispose();+ canvas.remove();+ return result;+ });+ assert.equal(report.fallback.capabilities.hdr, false);+ assert.equal(report.fallback.capabilities.hdrFallbackReason, 'EXT_color_buffer_float is unavailable');+ assert.equal(report.fallback.error, 0);+ assert.deepEqual(errors, []);+ await writeFile('artifacts/enhancement-smoke.json', JSON.stringify(report, null, 2));+ console.log('Deterministic motion, persistent GPU resources, 2D/orthographic views, textured GLB animation and responsive studios passed.');+} finally {+ await browser.close();+}diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex f2411828..1eba4cf9 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -13,17 +13,21 @@ assert.equal(release.version, metadata.version);assert.equal(release.packageName, metadata.name);assert.equal(release.packageAlias, '67js');assert.equal(release.integrity, `sha512-${createHash('sha512').update(binary).digest('base64')}`);-assert.ok(binary.length < 100000, 'Library archive must not contain preview media.');+assert.ok(binary.length < 1024 * 1024, 'Library plus optional glTF decoder must fit within a 1 MiB archive.');+assert.ok((await readFile('build/67.module.js')).length < 150000, 'The core must exclude the optional asset decoder.');const consumer = await mkdtemp(resolve(tmpdir(), '67js-consumer-'));await writeFile(resolve(consumer, 'package.json'), JSON.stringify({ private: true, type: 'module' }));const npmCli = process.env.npm_execpath ?? resolve(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');const installed = spawnSync(process.execPath, [npmCli, 'install', `67js@file:${archive.replaceAll('\\', '/')}`, '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });assert.equal(installed.status, 0, installed.stderr);const example = `import assert from 'node:assert/strict';-import { VERSION, Renderer67, box, assemblyOffset } from '67js';+import { VERSION, Renderer67, box, assemblyOffset, cameraView, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS } from '67js';import { createModel } from '67js/addons/model';import * as nature from '67js/addons/nature';import * as film from '67js/addons/film';+import { createMotionScene } from '67js/addons/motion';+import { createCanvas2D } from '67js/addons/canvas2d';+import { parseGltf } from '67js/addons/gltf';assert.equal(VERSION, '${metadata.version}');assert.equal(typeof Renderer67, 'function');assert.ok(box().positions.length > 0);@@ -32,6 +36,13 @@ assert.equal(parts.length, 574);assert.ok(parts.every(part => assemblyOffset(part, 1).some(value => value !== 0)));assert.ok(Object.keys(nature).length > 0);assert.ok(Object.keys(film).length > 0);+assert.equal(cameraView('top').projection, 'orthographic');+assert.ok(EFFECT_PRESETS.cinematic.bloom.strength > 0);+const clip = createAnimationClip({ duration: 2, tracks: [{ target: 'cube', property: 'value', keyframes: [{ time: 0, value: 0 }, { time: 2, value: 2 }] }] });+assert.equal(sampleAnimationClip(clip, 1)[0].value, 1);+assert.ok(createMotionScene().parts.length > 0);+assert.ok(createCanvas2D().parts.length > 0);+assert.equal(typeof parseGltf, 'function');console.log('Clean consumer: core, geometry, all addons and all574 explosion offsets passed.');`;await writeFile(resolve(consumer, 'check.mjs'), example);const result = spawnSync(process.execPath, ['check.mjs'], { cwd: consumer, windowsHide: true, encoding: 'utf8' });diff --git a/scripts/smoke.mjs b/scripts/smoke.mjsindex ec8a0e76..64dcc3eb 100644--- a/scripts/smoke.mjs+++ b/scripts/smoke.mjs@@ -95,7 +95,8 @@ try {const download = await downloadPromise;await download.saveAs(fileURLToPath(new URL('wall-e.glb', artifactDirectory)));await page.getByRole('button', { name: 'Measure performance' }).click();- await page.waitForFunction(() => window.__benchmarkReport, null, { timeout: 90000 });+ await page.waitForFunction(() => window.__benchmarkReport || document.querySelector('#benchmark-summary').textContent.startsWith('⚠'), null, { timeout: 90000 });+ assert.ok(await page.evaluate(() => Boolean(window.__benchmarkReport)), await page.locator('#benchmark-summary').textContent());const report = await page.evaluate(() => window.__benchmarkReport);assert.equal(report.results.length, 4);assert.deepEqual(report.results.map((result) => result.calls), [8, 575, 8, 575]);diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 885b132a..79ef33ce 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -15,6 +15,9 @@ Use `simplify-code` and `engineering-workflows` for implementation.- An object studio uses `src/model.js` and `src/main.js`.- An outdoor world uses `src/nature.js` and `src/nature-viewer.js`.- A deterministic film uses `src/film.js` and `src/film-player.js`.+- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.+- A flat scene or axis view uses `src/canvas2d.js`, `src/camera.js` and `src/view2d.js`.+- A GLB asset viewer uses the optional `src/gltf.js` addon and `src/asset-viewer.js`.- An image or video export uses `render-67js-media`.Read [scene-contract.md](references/scene-contract.md) before creating parts or changing materials.diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 2550bb52..0509f3e4 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -23,7 +23,7 @@ Each part has these fields.The transform is a column-major matrix. Colors are linear RGB.Normals are unit vectors. Triangle winding faces outward.-Each geometry identity becomes one instanced batch.+Each geometry and texture descriptor identity pair becomes one instanced batch.Explodable parts also provide `assembly: { layer: 'exterior' | 'interior', section: 'front-panel', offset: [0, 0, 1.7], detailOffset: [0.1, 0.05, 0.3] }`.Both offsets are world-space translations. The shader applies `offset * amount + detailOffset * smoothstep(0.3, 1, amount)`.@@ -43,6 +43,7 @@ The material tags select renderer behavior.| `foliage`, `grass` | Wind movement and backlighting. || `terrain` | Subtle natural surface variation. || `fire`, `smoke` | Film ignition expansion and procedural shading. |+| `unlit` | Flat linear color for vector scenes. || Other tags | Standard metallic/roughness shading. |Material tags and colors use flat varyings.@@ -72,3 +73,20 @@ The planner can reduce resolution to stay within its target budget.Films sample their timeline through `sampleFilm(time)`.Camera FOV uses degrees. Film time must be finite and independent of the wall clock.`renderAt(time)` must produce the same frame when called in a different order.++Animation changes existing part matrices and materials. `renderer.updateParts(changedParts)` uploads them through retained instance buffers.+New part, geometry or texture descriptor identities require a new renderer.+The optional `{ shadows: false }` update option suits flat scenes without moving shadow casters.++`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.+`fitOrthographicHeight(bounds, view, aspect)` frames both model width and height.+The `unlit` tag and a front orthographic camera produce flat XY geometry.++An HDR renderer sets `{ hdr: true }` at construction. `capabilities.hdr` reports the negotiated result.+`frame.effects` accepts `bloom`, `saturation`, `contrast`, `temperature`, `vignette` and `grain`.+The renderer reuses bloom targets and includes them in `memoryPlan`.++Imported GLB parts can include `geometry.uvs`, opaque linear `geometry.colors` and `material.map`.+The optional decoder preserves `material.emissiveColor` independently of its base color.+`asset.applyAnimation(time, clipIndex)` mutates existing matrices before `renderer.updateParts()`.+After closing an imported scene, dispose the renderer before the asset to release GPU textures before decoded images.diff --git a/skills/render-67js-media/references/rendering.md b/skills/render-67js-media/references/rendering.mdindex e6f336fa..49e5e6b3 100644--- a/skills/render-67js-media/references/rendering.md+++ b/skills/render-67js-media/references/rendering.md@@ -10,7 +10,7 @@ node scripts/score.mjsnode scripts/render-media.mjs --kind video --scene film --backend gpu --preset balanced --encoder gpu --output artifacts/critical.mp4```-The available scenes are `object`, `nature` and `film`.+The available scenes are `object`, `nature`, `film`, `motion`, `view2d` and `assets`.GPU rendering selects hardware WebGL through Chrome. CPU rendering requests ANGLE SwiftShader.The CPU exporter verifies that the selected backend reports SwiftShader.@@ -38,6 +38,7 @@ The renderer does not silently replace a failed hardware export with a lower-qua`scripts/score.mjs` generates the original film score.The `--audio <path>` option selects an existing score.+Only `film` selects the CRITICAL score automatically.Do not use movie dialogue, footage or music without authorization.```powershell@@ -47,3 +48,20 @@ ffprobe -v error -count_frames -show_entries stream=codec_name,width,height,r_frInspect the sidecar `<output>.json` for backend, estimated allocation, process memory, frame queue and graphics errors.The process guard stops Node above 512 MiB and sampled browser JavaScript heap above 256 MiB.Heap samples do not establish peak browser RSS or total VRAM use.++## Animation, shorts and assets++```powershell+node scripts/render-media.mjs --kind video --scene motion --aspect portrait --backend gpu --encoder gpu --output artifacts/short.mp4+node scripts/render-media.mjs --kind image --scene view2d --aspect square --backend cpu --preset cpu --output artifacts/poster.png+node scripts/render-media.mjs --kind video --scene assets --asset model.glb --start 0 --duration 2 --output artifacts/model.mp4+```++`--aspect` accepts `landscape`, `portrait` or `square`. Explicit width and height override preset dimensions.+`--start` selects the first video sample. A scene duration limits the selected range.+`--asset` accepts a local GLB of at most 32 MiB and requires `--scene assets`.+The importer reports unsupported features before capture.++A reusable viewer exposes `window.__scene = { renderer, renderAt, duration, pause }`.+The exporter prioritizes this interface and samples absolute scene time.+The JSON report includes negotiated HDR and MSAA capabilities, alongside estimated allocation.diff --git a/src/asset-viewer.css b/src/asset-viewer.cssnew file mode 100644index 00000000..08f1516c--- /dev/null+++ b/src/asset-viewer.css@@ -0,0 +1,12 @@+.asset-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 20px; }+.asset-controls label { display: flex; align-items: center; gap: 10px; font-size: 12px; color: #bec9cc; }+.asset-controls input { width: 110px; }+.asset-controls select { max-width: 220px; }+.asset-controls button { margin-left: auto; }+.export-view .asset-controls { display: none; }+@media (max-width: 750px) {+ .asset-controls { gap: 10px 16px; }+ .asset-controls input { width: 72px; }+ .toolbar nav { flex-wrap: wrap; }+ .asset-controls select { max-width: 150px; }+}diff --git a/src/asset-viewer.js b/src/asset-viewer.jsnew file mode 100644index 00000000..f4dd7cc0--- /dev/null+++ b/src/asset-viewer.js@@ -0,0 +1,221 @@+import './view2d.css';+import './asset-viewer.css';+import { mat4, vec3 } from 'gl-matrix';+import { Renderer67, box, torus, exportGlb, cameraView, fitOrthographicHeight } from './index.js';+import { loadGltf, parseGltf } from './gltf.js';++const canvas = document.querySelector('#viewport');+const parameters = new URLSearchParams(location.search);+if (parameters.get('export') === '1') {+ document.body.classList.add('export-view');+ const width = Number(parameters.get('width'));+ const height = Number(parameters.get('height'));+ if (width > 0 && height > 0) {+ document.querySelector('.workspace').style.width = `${width}px`;+ document.querySelector('.workspace').style.height = `${height}px`;+ }+}+const state = { view: 'perspective', yaw: 0.65, pitch: 0.3, zoom: 1, time: 0, clip: 0, playing: false };+let asset;+let renderer;+let bounds;+let scheduledFrame = 0;+let lastTime = 0;+let pointer;+let loadingRequest = 0;++function notice(message, failed = false, waiting = false) {+ const element = document.querySelector('#notice');+ element.textContent = `${waiting ? '◷' : failed ? '⚠' : '✓'} ${message}`;+ element.hidden = false;+}++function measureBounds(parts) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ const transformed = vec3.create();+ for (const part of parts) {+ for (let index = 0; index < part.geometry.positions.length; index += 3) {+ vec3.transformMat4(transformed, part.geometry.positions.subarray(index, index + 3), part.matrix);+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], transformed[axis]);+ maximum[axis] = Math.max(maximum[axis], transformed[axis]);+ }+ }+ }+ return { minimum, maximum };+}++function duration() {+ return asset?.animations[state.clip]?.duration ?? 0;+}++function frame() {+ const aspect = canvas.width / canvas.height;+ const target = bounds.minimum.map((value, axis) => (value + bounds.maximum[axis]) / 2);+ const extent = Math.max(...bounds.maximum.map((value, axis) => value - bounds.minimum[axis]), 0.01);+ const view = cameraView(state.view, { target, distance: extent * 2.5 });+ const height = Math.max(extent * 0.01, fitOrthographicHeight(bounds, view, aspect, 1.25)) * state.zoom;+ view.orthographicHeight = height;+ view.near = Math.max(0.0001, extent / 1000);+ view.far = extent * 100;+ if (state.view === 'perspective') {+ const distance = height * 1.7;+ view.eye = [target[0] + Math.sin(state.yaw) * Math.cos(state.pitch) * distance, target[1] + Math.sin(state.pitch) * distance, target[2] + Math.cos(state.yaw) * Math.cos(state.pitch) * distance];+ }+ return { ...view, time: state.time, exposure: Number(document.querySelector('#exposure').value), effects: { bloom: { strength: Number(document.querySelector('#bloom').value), threshold: 0.8 } } };+}++function renderAt(time = state.time) {+ if (!renderer) return;+ state.time = Math.max(0, Math.min(duration(), time));+ if (asset.animations.length) renderer.updateParts(asset.applyAnimation(state.time, state.clip));+ renderer.render(frame());+ document.querySelector('#time').value = String(state.time);+ document.querySelector('#time-value').textContent = `${state.time.toFixed(2)} s`;+}++function tick(timestamp) {+ scheduledFrame = 0;+ if (document.hidden) return;+ if (state.playing && duration()) state.time = (state.time + Math.min((timestamp - lastTime) / 1000, 0.05)) % duration();+ lastTime = timestamp;+ try {+ renderAt();+ } catch (error) {+ pause();+ notice(error.message, true);+ }+ if (state.playing) invalidate();+}++function invalidate() {+ if (!scheduledFrame && renderer && !document.hidden) scheduledFrame = requestAnimationFrame(tick);+}++function pause() {+ state.playing = false;+ document.querySelector('#play').textContent = '▶ Play';+}++function syncAnimation() {+ document.querySelector('#time').max = String(duration() || 1);+ document.querySelector('#time').disabled = !duration();+ document.querySelector('#play').disabled = !duration();+}++function showAsset(loaded, title) {+ const nextBounds = measureBounds(loaded.parts);+ const center = nextBounds.minimum.map((value, axis) => (value + nextBounds.maximum[axis]) / 2);+ const extent = Math.max(...nextBounds.maximum.map((value, axis) => value - nextBounds.minimum[axis]), 0.01);+ renderer?.dispose();+ renderer = null;+ asset?.dispose();+ asset = null;+ let nextRenderer;+ try {+ nextRenderer = new Renderer67(canvas, loaded.parts, { ground: false, hdr: true, samples: Number(parameters.get('samples') ?? 4), pixelRatio: parameters.get('export') === '1' ? 1 : Math.min(devicePixelRatio, 1.5), memoryBudgetMiB: Number(parameters.get('memory') ?? 256), shadowBounds: { target: center, eye: [center[0] - extent, center[1] + extent * 2, center[2] + extent], extent: extent * 1.5, near: extent * 0.01, far: extent * 8 } });+ } catch (error) {+ loaded.dispose();+ throw error;+ }+ renderer = nextRenderer;+ asset = loaded;+ bounds = nextBounds;+ state.zoom = 1;+ state.time = 0;+ state.clip = 0;+ pause();+ const clip = document.querySelector('#clip');+ clip.replaceChildren();+ const names = asset.animations.length ? asset.animations.map((animation, index) => animation.name || `Clip ${index + 1}`) : ['No animation'];+ names.forEach((name, index) => clip.add(new Option(name, String(index))));+ clip.disabled = !asset.animations.length;+ syncAnimation();+ document.querySelector('#metrics').textContent = `${asset.parts.length.toLocaleString()} parts · ${renderer.batches.length} draws`;+ document.querySelector('#notice').hidden = true;+ document.title = `${title} · 67.js asset viewer`;+ invalidate();+}++async function openFile(file) {+ if (!file) return;+ const request = ++loadingRequest;+ pause();+ notice('Loading asset…', false, true);+ try {+ const loaded = await loadGltf(file, { maxBytes: 32 * 1024 * 1024, maxTexturePixels: 4 * 1024 * 1024 });+ if (request !== loadingRequest) {+ loaded.dispose();+ return;+ }+ showAsset(loaded, file.name);+ } catch (error) {+ if (request === loadingRequest) notice(error.message, true);+ }+}++document.querySelector('#open').addEventListener('click', () => document.querySelector('#file').click());+document.querySelector('#file').addEventListener('change', event => openFile(event.target.files[0]));+document.querySelector('#fit').addEventListener('click', () => { state.zoom = 1; invalidate(); });+document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', () => {+ state.view = button.dataset.view;+ document.querySelectorAll('[data-view]').forEach(item => item.setAttribute('aria-pressed', String(item === button)));+ invalidate();+}));+for (const id of ['exposure', 'bloom']) document.querySelector(`#${id}`).addEventListener('input', invalidate);+document.querySelector('#clip').addEventListener('change', event => { state.clip = Number(event.target.value); state.time = 0; syncAnimation(); invalidate(); });+document.querySelector('#time').addEventListener('input', event => { pause(); state.time = Number(event.target.value); invalidate(); });+document.querySelector('#play').addEventListener('click', () => { state.playing = !state.playing; document.querySelector('#play').textContent = state.playing ? 'Ⅱ Pause' : '▶ Play'; lastTime = performance.now(); invalidate(); });+canvas.addEventListener('pointerdown', event => { pointer = { x: event.clientX, y: event.clientY }; canvas.setPointerCapture(event.pointerId); });+canvas.addEventListener('pointermove', event => {+ if (!pointer || state.view !== 'perspective') return;+ state.yaw -= (event.clientX - pointer.x) * 0.008;+ state.pitch = Math.max(-1.4, Math.min(1.4, state.pitch + (event.clientY - pointer.y) * 0.008));+ pointer = { x: event.clientX, y: event.clientY };+ invalidate();+});+canvas.addEventListener('pointerup', () => { pointer = null; });+canvas.addEventListener('wheel', event => { event.preventDefault(); state.zoom = Math.max(0.1, Math.min(10, state.zoom * Math.exp(event.deltaY * 0.001))); invalidate(); }, { passive: false });+canvas.addEventListener('keydown', event => { if (event.key.toLowerCase() === 'f') { state.zoom = 1; invalidate(); } });+document.querySelector('.stage').addEventListener('dragover', event => event.preventDefault());+document.querySelector('.stage').addEventListener('drop', event => { event.preventDefault(); openFile(event.dataTransfer.files[0]); });+document.addEventListener('visibilitychange', () => { lastTime = performance.now(); if (!document.hidden) invalidate(); });+canvas.addEventListener('webglcontextlost', event => {+ event.preventDefault();+ pause();+ renderer?.dispose();+ renderer = null;+ notice('Graphics context lost. Open the asset again after recovery.', true);+});+window.addEventListener('pagehide', () => {+ loadingRequest++;+ pause();+ if (scheduledFrame) cancelAnimationFrame(scheduledFrame);+ renderer?.dispose();+ renderer = null;+ asset?.dispose();+ asset = null;+});+new ResizeObserver(() => { if (renderer) { renderer.resize(); invalidate(); } }).observe(canvas);+document.querySelector('#save').addEventListener('click', async () => {+ if (!renderer) return notice('Open a valid GLB asset before saving an image', true);+ pause();+ renderAt();+ const blob = await new Promise(resolve => canvas.toBlob(resolve));+ if (!blob) return notice('Image capture failed', true);+ const url = URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = '67js-asset.png';+ link.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+ notice('Image saved');+});++window.__assetViewer = { state, openFile, showAsset, get renderer() { return renderer; }, get asset() { return asset; }, renderAt };+window.__scene = { get renderer() { return renderer; }, get duration() { return duration(); }, pause, renderAt };+const material = { tag: 'surface', color: [0.16, 0.48, 0.42], metallic: 0.55, roughness: 0.3, emission: 0 };+const ringMatrix = mat4.fromScaling(mat4.create(), [1.5, 1.5, 1.5]);+const demo = [{ name: 'Core', geometry: box(), matrix: mat4.create(), material }, { name: 'Ring', geometry: torus(0.08, 64, 16), matrix: ringMatrix, material }];+try { showAsset(await parseGltf(exportGlb(demo)), 'Machine study'); } catch (error) { notice(error.message, true); }diff --git a/src/benchmark.js b/src/benchmark.jsindex 1822e877..dfc72bd5 100644--- a/src/benchmark.js+++ b/src/benchmark.js@@ -72,7 +72,8 @@ export async function runBenchmark(parts, onProgress = () => {}) {const floor = {geometry: { positions: new Float32Array([-100, 0.019, -100, -100, 0.019, 100, 100, 0.019, 100, 100, 0.019, -100]), indices: new Uint32Array([0, 1, 2, 0, 2, 3]) },matrix: new THREE.Matrix4().elements,- material: { color: [0.04, 0.05, 0.06] },+ name: 'Benchmark floor',+ material: { color: [0.04, 0.05, 0.06], metallic: 0, roughness: 1, emission: 0, tag: 'floor' },};for (const group of groupParts([...parts, floor], batching)) {const source = group[0].geometry;diff --git a/src/gltf.js b/src/gltf.jsindex d0d1928a..a1b4813a 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -166,8 +166,10 @@ function validateHierarchy(nodes) {}}const states = new Uint8Array(nodes.length);- for (let root = 0; root < nodes.length; root++) {- const pending = [{ index: root, exit: false, depth: 0 }];+ const roots = Array.from(nodes.keys()).filter(index => !parents.has(index));+ const remaining = Array.from(nodes.keys()).filter(index => parents.has(index));+ for (const root of [...roots, ...remaining]) {+ const pending = [{ index: root, exit: false, depth: 1 }];while (pending.length) {const current = pending.pop();if (current.exit) {@@ -447,6 +449,8 @@ export async function parseGltf(data, options = {}) {const manager = new LoadingManager();manager.setURLModifier(url => {if (resources.has(url)) return resources.get(url);+ const normalized = new URL(url, options.baseUrl || undefined).href;+ if (resources.has(normalized)) return resources.get(normalized);if (url.startsWith('blob:')) return url;throw new Error(`Unregistered glTF resource: ${url}.`);});diff --git a/src/index.js b/src/index.jsindex 409ccaa7..53b14718 100644--- a/src/index.js+++ b/src/index.js@@ -7,3 +7,6 @@ export { exportGlb } from './export.js';export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js';export { assemblyOffset } from './assembly.js';+export { cameraView, fitOrthographicHeight } from './camera.js';+export { EFFECT_PRESETS, resolveEffects } from './effects.js';+export { createAnimationClip, sampleAnimationClip, createAnimationPlayer } from './animation.js';diff --git a/src/main.js b/src/main.jsindex 413afa0d..47efc208 100644--- a/src/main.js+++ b/src/main.js@@ -5,6 +5,7 @@ import { downloadGlb } from './export.js';import { assemblyOffset } from './assembly.js';const canvas = document.querySelector('#viewport');+const renderParameters = new URLSearchParams(location.search);const parts = createModel();const finishes = {yellow: { name: 'Factory yellow', color: [0.62, 0.34, 0.035], surface: [0.48, 0.43] },@@ -63,7 +64,7 @@ function invalidate() {function initialize() {const visibleParts = state.layer === 'all' ? parts : parts.filter((part) => part.assembly?.layer === state.layer);- renderer = new Renderer67(canvas, visibleParts, { shadowBounds: { extent: 6, eye: [-3, 7, 4], target: [0, 1.5, 0] } });+ renderer = new Renderer67(canvas, visibleParts, { samples: Number(renderParameters.get('samples') ?? 4), memoryBudgetMiB: Number(renderParameters.get('memory') ?? 256), pixelRatio: renderParameters.get('export') === '1' ? 1 : 1.5, shadowBounds: { extent: 6, eye: [-3, 7, 4], target: [0, 1.5, 0] } });document.querySelector('#parts').textContent = `${visibleParts.length} parts · ${Math.round(renderer.triangles / 1000)}k triangles`;document.querySelector('#calls').textContent = `${renderer.batches.length} geometry draws`;invalidate();diff --git a/src/motion.js b/src/motion.jsindex b7954802..cd9d2b3d 100644--- a/src/motion.js+++ b/src/motion.js@@ -98,7 +98,7 @@ export function createMotionScene() {player.apply(current);const shot = Math.min(2, Math.floor(current / 4));const cameraValues = Object.fromEntries(sampleAnimationClip(cameras[shot], current - shot * 4).map(value => [value.target, value.value]));- const framing = aspect === 'portrait' ? 2.35 : aspect === 'square' ? 1.18 : 1;+ const framing = aspect === 'portrait' ? 2.35 : aspect === 'square' ? 1.4 : 1.2;return {time: current,shot,diff --git a/src/nature-viewer.js b/src/nature-viewer.jsindex 58e4558c..f6ab8aae 100644--- a/src/nature-viewer.js+++ b/src/nature-viewer.js@@ -3,6 +3,7 @@ import { vec4 } from 'gl-matrix';import { Renderer67 } from './renderer.js';import { createNatureWorld } from './nature.js';+const renderParameters = new URLSearchParams(location.search);const canvas = document.querySelector('#viewport');const motionButton = document.querySelector('#motion');const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');@@ -97,7 +98,7 @@ function updateStatistics() {function initializeRenderer() {renderer = new Renderer67(canvas, world.parts, {world: true, ground: false, environment: world.environment,- pixelRatio: 1.25, memoryBudgetMiB: 256, samples: 4,+ pixelRatio: renderParameters.get('export') === '1' ? 1 : 1.25, memoryBudgetMiB: Number(renderParameters.get('memory') ?? 256), samples: Number(renderParameters.get('samples') ?? 4),});updateStatistics();renderFrame();diff --git a/src/renderer.js b/src/renderer.jsindex c3e5aa67..9d756733 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -122,7 +122,6 @@ export class Renderer67 {this.memoryBudgetMiB = memoryBudgetMiB;this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(samples, this.context.getParameter(this.context.MAX_SAMPLES)));- this.samples = Math.max(1, this.multisampleSamples);this.capabilities = { hdr: this.hdr, hdrRequested: Boolean(hdr), hdrFallbackReason: hdr && !this.hdr ? benchmark ? 'HDR is disabled in benchmark mode' : 'EXT_color_buffer_float is unavailable' : null, samples: this.multisampleSamples };this.geometryBytes = 0;this.buffers = [];@@ -171,6 +170,10 @@ export class Renderer67 {if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);}+ get samples() {+ return Math.max(1, this.multisampleSamples);+ }+uploadBuffer(target, data, usage = this.context.STATIC_DRAW) {const buffer = this.context.createBuffer();this.buffers.push(buffer);diff --git a/src/view2d.js b/src/view2d.jsindex fddfdde2..a97775ec 100644--- a/src/view2d.js+++ b/src/view2d.js@@ -96,7 +96,7 @@ function initialize() {setPlaying(false);renderer?.dispose();const parts = state.scene === 'poster' ? poster.parts : model;- renderer = new Renderer67(canvas, parts, { ground: false, samples: 4, pixelRatio: exporting ? 1 : 1.25, memoryBudgetMiB: 192 });+ renderer = new Renderer67(canvas, parts, { ground: false, samples: Number(parameters.get('samples') ?? 4), pixelRatio: exporting ? 1 : 1.25, memoryBudgetMiB: Number(parameters.get('memory') ?? 192) });document.querySelector('#scene').value = state.scene;document.querySelector('#view-controls').hidden = state.scene === 'poster';document.querySelectorAll('[data-view]').forEach(control => control.setAttribute('aria-pressed', String(control.dataset.view === state.view)));diff --git a/tests/export-options.test.js b/tests/export-options.test.jsindex 945ad560..e9fd5b96 100644--- a/tests/export-options.test.js+++ b/tests/export-options.test.js@@ -51,3 +51,11 @@ test('invalid export options fail before starting resources', () => {['--unknown', 'value'], ['--aspect'], ['--kind', 'video', '--width', '101', '--height', '100'],]) assert.throws(() => parseRenderOptions(args));});++test('asset captures select a supplied file and avoid an automatic soundtrack', () => {+ const plan = parseRenderOptions(['--scene', 'assets', '--asset', 'model.glb']);+ assert.equal(plan.options.asset, 'model.glb');+ assert.equal(plan.audio, null);+ assert.equal(plan.time, 0);+ assert.throws(() => parseRenderOptions(['--scene', 'motion', '--asset', 'model.glb']));+});diff --git a/tests/gltf.test.js b/tests/gltf.test.jsindex 918e41c7..c1a486c5 100644--- a/tests/gltf.test.js+++ b/tests/gltf.test.js@@ -186,6 +186,45 @@ test('texture pixel budgets reject compressed images before browser decoding', aawait assert.rejects(parseGltf(oversized), /maxTexturePixels before decoding/);});+test('hierarchy depth guards reject long chains regardless of node ordering', async () => {+ for (const reverse of [false, true]) {+ const asset = triangleAsset(document => {+ document.nodes = Array.from({ length: 300 }, (_, index) => {+ const child = reverse ? index - 1 : index + 1;+ return child >= 0 && child < 300 ? { children: [child] } : { mesh: 0 };+ });+ document.scenes = [{ nodes: [reverse ? 299 : 0] }];+ });+ await assert.rejects(parseGltf(asset), /256 levels/);+ }+});++test('relative external buffer paths normalize both fetch and decoder lookups', async context => {+ const previousProgressEvent = globalThis.ProgressEvent;+ globalThis.ProgressEvent = class ProgressEvent {+ constructor(type, details) { this.type = type; Object.assign(this, details); }+ };+ context.after(() => {+ if (previousProgressEvent) globalThis.ProgressEvent = previousProgressEvent;+ else delete globalThis.ProgressEvent;+ });+ const source = triangleAsset();+ const header = new DataView(source);+ const jsonLength = header.getUint32(12, true);+ const document = JSON.parse(new TextDecoder().decode(new Uint8Array(source, 20, jsonLength)));+ document.buffers[0].uri = '../mesh.bin';+ const binary = new Uint8Array(source, 28 + jsonLength);+ const fetched = [];+ context.mock.method(globalThis, 'fetch', async url => {+ fetched.push(String(url));+ return new Response(binary);+ });+ const asset = await parseGltf(JSON.stringify(document), { baseUrl: 'https://example.test/models/' });+ assert.equal(asset.parts.length, 2);+ assert.equal(fetched[0], 'https://example.test/mesh.bin');+ asset.dispose();+});+test('URL loading streams within maxBytes and cancels oversized responses', async context => {const data = triangleAsset();const url = `data:model/gltf-binary;base64,${Buffer.from(data).toString('base64')}`;diff --git a/tests/renderer.test.js b/tests/renderer.test.jsindex 1a66df9e..5e6c522f 100644--- a/tests/renderer.test.js+++ b/tests/renderer.test.js@@ -17,6 +17,16 @@ function retainedRenderer(parts) {return { renderer, batch, writes };}+test('sample reporting uses the negotiated allocation count and cannot diverge through assignment', () => {+ const renderer = Object.create(Renderer67.prototype);+ renderer.multisampleSamples = 4;+ assert.equal(renderer.samples, 4);+ assert.throws(() => { renderer.samples = 1; }, TypeError);+ assert.equal(renderer.samples, 4);+ renderer.multisampleSamples = 0;+ assert.equal(renderer.samples, 1);+});+test('batching shares geometry only when texture descriptor identities also match', () => {const geometry = {};const map = {};diff --git a/vite.config.js b/vite.config.jsindex de947fb3..206efdeb 100644--- a/vite.config.js+++ b/vite.config.js@@ -8,5 +8,5 @@ const headers = {export default defineConfig({server: { headers },preview: { headers },- build: { rolldownOptions: { input: { home: 'index.html', object: 'object.html', nature: 'nature.html', film: 'film.html', guide: 'getting-started.html' } } },+ build: { rolldownOptions: { input: { home: 'index.html', object: 'object.html', nature: 'nature.html', film: 'film.html', motion: 'motion.html', view2d: 'view2d.html', assets: 'assets.html', guide: 'getting-started.html' } } },});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 676d24cb..2a6f7dca 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -4,7 +4,7 @@ import { defineConfig } from 'vite';export default defineConfig({build: {copyPublicDir: false,- rolldownOptions: { output: { banner: `/*! ${readFileSync('LICENSE', 'utf8')} */` } },+ rolldownOptions: { output: { banner: `/*! ${readFileSync('LICENSE', 'utf8')}\nOptional glTF decoder: ${readFileSync('THIRD-PARTY-NOTICES.md', 'utf8')} */` } },outDir: 'build',lib: {entry: {@@ -12,6 +12,9 @@ export default defineConfig({model: 'src/model.js',nature: 'src/nature.js',film: 'src/film.js',+ motion: 'src/motion.js',+ canvas2d: 'src/canvas2d.js',+ gltf: 'src/gltf.js',},formats: ['es'],fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,