3D engine that AI agents drive
Add GPU morph targets and deterministic film eyelids
Nguyen Xuan An18f0ccc07b2d
diff --git a/README.md b/README.mdindex 9863ba4f..3baec601 100644--- a/README.md+++ b/README.md@@ -164,6 +164,7 @@ The optional [physics addon](docs/physics.md) records Rapier contacts, articulatIt requires the separate `@dimforge/[email protected]` dependency; the core does not import or bundle that solver.Physics is source-only and is not included in the published `0.3.3` package.The source trailer includes an [offline physics recording](docs/film-physics.md) of colliding pendulums, played through retained animation tracks without loading a solver in the browser.+The source renderer also supports [relative GPU morph targets](docs/morph-targets.md) for position and normal changes before skinning, including deterministic eyelid animation in the film. This feature is not in the published `0.3.3` package.The trailer's rigid actor joints now use authored clips, with attached headwear and hands moving together.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.diff --git a/docs/morph-targets.md b/docs/morph-targets.mdnew file mode 100644index 00000000..951f5215--- /dev/null+++ b/docs/morph-targets.md@@ -0,0 +1,125 @@+# Relative morph targets++The source renderer blends relative position and normal targets on the GPU before skinning.+Color, benchmark and shadow passes share the same target texture and committed weights.+This source feature is not yet in the published npm release. glTF morph import remains unsupported.+The core module exports `createMorphPose` and `MAX_MORPH_TARGETS` without adding a dependency.++Each morph target contains mesh-local changes from the base geometry.+Position and normal channels use XYZ triples, independently of material color.+The blend uses `base + sum(weight * delta)` for each channel.+Weights can be negative or exceed one without normalization or clamping.++```js+import {+ createMorphPose, validateMorphGeometry, validateMorphPose, packMorphTargets,+} from '../src/morph.js';+import { skinTextureLayout } from '../src/skinning.js';++const geometry = {+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),+ morphTargets: [+ { positions: new Float32Array([0, 0, 0, 0, 0, 0, 0, 0.2, 0]) },+ { normals: new Float32Array([0, 0.1, 0, 0, 0.1, 0, 0, 0.1, 0]) },+ ],+};+const pose = createMorphPose(2);+const metadata = validateMorphGeometry(geometry, pose);+const layout = skinTextureLayout(metadata.texelCount, maximumTextureSize, 2);+const textureData = packMorphTargets(geometry, layout);+const part = { geometry, morph: pose }; // Other part fields come from the renderer contract.++pose.weights.set([0.75, -0.2]);+validateMorphPose(pose, metadata); // Validation does not change any weights or target arrays.+```++## Geometry and pose contract++`geometry.morphTargets` contains between one and `MAX_MORPH_TARGETS`, which is `64`.+Each target accepts only optional `positions` and `normals` fields, with at least one channel present.+Every present channel must be a `Float32Array` containing three finite values per base vertex.+A missing channel contributes zero changes.+Base positions and normals also require matching, nonempty `Float32Array` triples.++Base normal squared lengths must remain finite normal Float32 values, at least `2 ** -126`.+This condition prevents a zero or numerically unusable fallback normal.+Target deltas can cancel a normal during blending.+The renderer shader must use the base normal when the blended normal cannot normalize safely.+This module validates numerical bounds without calculating or replacing each blended normal.++`createMorphPose(targetCount)` returns `{ weights: new Float32Array(targetCount) }`, initially zero.+`validateMorphGeometry(geometry, pose)` performs full static preflight and validates the initial weights.+Geometry without morph targets and without a pose returns `undefined`.+Targets without a pose, or a pose without targets, fail validation.++`validateMorphPose(pose, metadata)` accepts any matching Float32 weight array and returns the same metadata.+One geometry metadata object supports several independent poses.+Renderer records must separately retain pose and weight identities after upload.+Shared pose identity can share a batch, while different pose identities need separate batches.++## Static data and atomic updates++Base arrays, target arrays and their contents remain static after upload.+Metadata stores geometry, target and channel identities plus frozen component maxima.+Each frame validates those identities without rescanning channel contents.+Replacing a channel or a target fails the identity check.+In-place content changes violate the static contract and require new geometry, preflight and upload.++Weight contents remain mutable.+The renderer must validate every pending pose before committing instance changes or uploading uniforms.+An invalid pose must leave the last rendered frame intact.+Validation throws without modifying caller arrays, clamping weights or partially applying a pose.+Retained arrays avoid allocation during `validateMorphPose`.++## Bounds and texture layout++Metadata exposes `vertexCount`, `targetCount`, `texelCount`, base component maxima and per-target component maxima.+Its `targets` snapshots contain the original target and channel identities.++The component bound is `abs(base maximum) + sum(abs(weight) * target maximum)`.+Float32 product and accumulation checks reject unsafe intermediate values.+Bounds round upward to cover fused shader arithmetic as well as separate multiply and add operations.+Position and normal component bounds must remain finite in Float32.+The normal squared length bound must also remain finite in Float32.++These bounds deliberately ignore cancellation and maxima occurring at different vertices.+They can reject a finite final blend when large opposing deltas cancel.+The renderer also checks conservative position bounds through its world and weighted skin matrix product.+Shared pose updates validate consumers outside the submitted part list using their committed world matrices.+The palette bound covers four normalized Float32 influences and may reject large cancelling transforms.+These checks do not cover camera projections, displacement, lighting or every transformed normal calculation.++`packMorphTargets(geometry, layout)` validates static channels and returns a new packed `Float32Array`.+Each target vertex occupies two RGBA texels, with a scalar offset of `(target * vertexCount + vertex) * 8`.+The first texel contains position XYZ and zero.+The second contains normal XYZ and zero.+Missing channels and unused texture padding contain zero.++`skinTextureLayout(vertexCount * targetCount * 2, maximumTextureSize, 2)` provides a compatible layout.+Even widths keep the two texels together across rows.+Packing rejects insufficient capacity, inconsistent byte counts and allocations exceeding `2 ** 31 - 1` bytes.+The renderer still needs an explicit texture memory budget before allocation.+Its shader can use a bounded loop of 64 targets and skip zero weights.++## Design choice and verification++Two designs were considered before fixing the data contract.++| Design | Geometry changes | Frame cost | Resource ownership |+| --- | --- | --- | --- |+| CPU blend and mesh upload | Rewrites each position and normal buffer | Visits every affected vertex and uploads buffers | Each pose needs its own mutable geometry. |+| Cached GPU targets and uniform weights | Retains base geometry and static target texture | Validates at most 64 weights and component bounds | Geometry shares a texture across independent poses. |++The selected GPU contract preserves geometry identity and avoids vertex rewrites during playback.+Uniform weights allow this design without consuming more vertex attributes.+Different poses split batches because their uniforms differ.+The parent renderer owns that batching and texture lifecycle.++Node tests compare signed relative position blends with literal expected values and the installed Three.js `Mesh.getVertexPosition` implementation.+Other checks cover channel packing, independent poses, normal cancellation, identity changes, overflow and texture capacity.+`scripts/smoke-morph.mjs` compares the actual built GPU module with a CPU-authored reference image.+It checks independent signed poses, the 64th target, retained buffers, atomic rejection and texture disposal.+`scripts/smoke-morph-composition.mjs` compares combined skinning, normal deltas, normal cancellation and shadow receivers with CPU-baked geometry.+The film scientist uses shared eyelid geometry with one retained blink pose per actor.+Visual quality and frame performance require separate scene measurements.diff --git a/package.json b/package.jsonindex ae253058..4cb94e74 100644--- a/package.json+++ b/package.json@@ -32,7 +32,8 @@"docs/physics.md","docs/lighting.md","docs/volumetric.md",- "docs/film-physics.md"+ "docs/film-physics.md",+ "docs/morph-targets.md"],"main": "./build/67.module.js","module": "./build/67.module.js",diff --git a/scripts/smoke-film-blink.mjs b/scripts/smoke-film-blink.mjsnew file mode 100644index 00000000..1a01d915--- /dev/null+++ b/scripts/smoke-film-blink.mjs@@ -0,0 +1,60 @@+import assert from 'node:assert/strict';+import { writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const browser = await chromium.launch({+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',+ headless: true,+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],+});+try {+ const page = await browser.newPage({ viewport: { width: 540, height: 960 } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.route('**/blink-smoke.html', route => route.fulfill({+ contentType: 'text/html', body: '<canvas style="width:540px;height:960px;display:block"></canvas>',+ }));+ await page.goto('http://127.0.0.1:5173/blink-smoke.html');+ const report = await page.evaluate(async () => {+ const { Renderer67 } = await import('/build/67.module.js');+ const { createFilmScenes } = await import('/build/film.js');+ const scene = createFilmScenes().portrait;+ const canvas = document.querySelector('canvas');+ const renderer = new Renderer67(canvas, scene.parts, {+ world: true, ground: false, environment: scene.environment,+ shadowBounds: scene.shadowBounds, samples: 2, pixelRatio: 1,+ hdr: true, memoryBudgetMiB: 128,+ });+ const frame = { eye: [0, 1.72, 0.72], target: [0, 1.7, 0], fov: 36, time: 0, effects: { grain: 0, bloom: { strength: 0 } } };+ function image(time, suppressBlink = false) {+ scene.animate(time);+ if (suppressBlink) {+ for (const part of scene.parts) if (part.morph) part.morph.weights.fill(0);+ }+ renderer.updateParts(scene.parts);+ renderer.render(frame);+ return canvas.toDataURL('image/png');+ }+ const open = image(0);+ const closed = image(1.92);+ const samePoseWithoutBlink = image(1.92, true);+ image(9);+ const repeated = image(1.92);+ const error = renderer.context.getError();+ const memory = renderer.memoryPlan;+ renderer.dispose();+ return { open, closed, samePoseWithoutBlink, repeated, error, memory };+ });+ assert.deepEqual(errors, []);+ assert.equal(report.error, 0);+ assert.notEqual(report.closed, report.samePoseWithoutBlink, 'Eyelid geometry must change pixels independently of head movement');+ assert.equal(report.closed, report.repeated);+ for (const name of ['open', 'closed']) {+ await writeFile(`artifacts/blink-${name}.png`, Buffer.from(report[name].split(',')[1], 'base64'));+ }+ console.log(JSON.stringify({ glError: report.error, repeatExact: true, independentBlinkPixels: true, memory: report.memory }));+} finally {+ await browser.close();+}diff --git a/scripts/smoke-morph-composition.mjs b/scripts/smoke-morph-composition.mjsnew file mode 100644index 00000000..c144b69f--- /dev/null+++ b/scripts/smoke-morph-composition.mjs@@ -0,0 +1,102 @@+import assert from 'node:assert/strict';+import { writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const browser = await chromium.launch({+ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',+ headless: true,+ args: ['--enable-webgl', '--ignore-gpu-blocklist'],+});+try {+ const page = await browser.newPage({ viewport: { width: 640, height: 480 } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.route('**/morph-composition.html', route => route.fulfill({+ contentType: 'text/html', body: '<canvas style="width:640px;height:480px;display:block"></canvas>',+ }));+ await page.goto('http://127.0.0.1:5173/morph-composition.html');+ const reports = await page.evaluate(async () => {+ const { Renderer67, box, createMorphPose, createSkinPose } = await import('/build/67.module.js');+ const { mat4, mat3, quat, vec3 } = await import('/node_modules/gl-matrix/esm/index.js');+ const reports = [];+ for (const mode of ['normals', 'cancellation', 'benchmark']) {+ const geometry = box();+ const positions = new Float32Array(geometry.positions.length);+ const normals = new Float32Array(geometry.normals.length);+ for (let offset = 0; offset < positions.length; offset += 3) {+ positions[offset] = 0.3 + geometry.positions[offset + 1] * 0.15;+ positions[offset + 1] = 0.2;+ for (let component = 0; component < 3; component++) {+ normals[offset + component] = mode === 'cancellation'+ ? -geometry.normals[offset + component]+ : component === 0 ? 0.3 : 0;+ }+ }+ geometry.morphTargets = [{ positions, normals }];+ const morph = createMorphPose(1);+ morph.weights[0] = 1;+ const skin = createSkinPose(1);+ mat4.fromRotationTranslationScale(skin.jointMatrices, quat.setAxisAngle(quat.create(), [0, 0, 1], 0.4), [0.1, 0.3, 0], [1.3, 0.8, 1.1]);+ geometry.skinIndices = new Uint16Array(geometry.positions.length / 3 * 4);+ geometry.skinWeights = new Float32Array(geometry.skinIndices.length);+ for (let influence = 0; influence < geometry.skinWeights.length; influence += 4) geometry.skinWeights[influence] = 1;+ const material = { color: [0.45, 0.5, 0.6], metallic: 0, roughness: 0.8, emission: 0 };+ const part = { name: 'combined deformation', geometry, morph, skin, matrix: mat4.fromScaling(mat4.create(), [1.1, 1, 0.9]), material };+ const floor = { name: 'shadow receiver', geometry: box(), matrix: mat4.fromRotationTranslationScale(mat4.create(), quat.create(), [0, -0.6, 0], [6, 0.1, 6]), material: { ...material, tag: 'floor' } };+ const canvas = document.querySelector('canvas');+ const options = { world: true, ground: false, samples: 1, pixelRatio: 1, memoryBudgetMiB: 64, benchmark: mode === 'benchmark', shadowBounds: { eye: [-3, 6, 4], target: [0, 0, 0], extent: 3, near: 0.1, far: 15 } };+ const frame = { eye: [2, 2, 6], target: [0, 0, 0], fov: 40, time: 0, effects: { grain: 0, bloom: { strength: 0 } } };+ function read(renderer) {+ renderer.render(frame);+ const values = new Uint8Array(canvas.width * canvas.height * 4);+ const context = renderer.context;+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, values);+ if (context.getError() !== 0) throw new Error('GPU composition generated a GL error');+ return values;+ }+ const renderer = new Renderer67(canvas, [part, floor], options);+ const gpuPixels = read(renderer);+ renderer.dispose();+ const referencePositions = new Float32Array(geometry.positions.length);+ const referenceNormals = new Float32Array(geometry.normals.length);+ const normalMatrix = mat3.normalFromMat4(mat3.create(), skin.jointMatrices);+ const vector = vec3.create();+ for (let offset = 0; offset < referencePositions.length; offset += 3) {+ for (let component = 0; component < 3; component++) vector[component] = geometry.positions[offset + component] + positions[offset + component];+ vec3.transformMat4(vector, vector, skin.jointMatrices);+ referencePositions.set(vector, offset);+ for (let component = 0; component < 3; component++) vector[component] = geometry.normals[offset + component] + normals[offset + component];+ if (vec3.length(vector) === 0) vector.set(geometry.normals.subarray(offset, offset + 3));+ vec3.normalize(vector, vector);+ vec3.transformMat3(vector, vector, normalMatrix);+ referenceNormals.set(vector, offset);+ }+ const referencePart = { ...part, skin: undefined, morph: undefined, geometry: { positions: referencePositions, normals: referenceNormals, indices: geometry.indices } };+ const reference = new Renderer67(canvas, [referencePart, floor], options);+ const cpuPixels = read(reference);+ reference.dispose();+ let maximumDifference = 0;+ let totalDifference = 0;+ let changedChannels = 0;+ for (let index = 0; index < gpuPixels.length; index++) {+ const difference = Math.abs(gpuPixels[index] - cpuPixels[index]);+ maximumDifference = Math.max(maximumDifference, difference);+ totalDifference += difference;+ if (difference) changedChannels++;+ }+ reports.push({ mode, maximumDifference, meanDifference: totalDifference / gpuPixels.length, changedChannels });+ }+ return reports;+ });+ assert.deepEqual(errors, []);+ for (const report of reports) {+ assert.ok(report.maximumDifference <= 3, JSON.stringify(report));+ assert.ok(report.meanDifference < 0.01, JSON.stringify(report));+ }+ await writeFile('artifacts/morph-composition.json', JSON.stringify(reports, null, 2));+ console.log(JSON.stringify(reports, null, 2));+} finally {+ await browser.close();+}diff --git a/scripts/smoke-morph.mjs b/scripts/smoke-morph.mjsnew file mode 100644index 00000000..d08d6472--- /dev/null+++ b/scripts/smoke-morph.mjs@@ -0,0 +1,113 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { chromium } from 'playwright';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir('artifacts', { recursive: true });+const browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist'] });+try {+ const page = await browser.newPage({ viewport: { width: 640, height: 480 } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.route('**/morph-smoke.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:640px;height:480px;display:block"></canvas>' }));+ await page.goto('http://127.0.0.1:5173/morph-smoke.html');+ const report = await page.evaluate(async () => {+ const { Renderer67, box, createMorphPose } = await import('/build/67.module.js');+ const { mat4 } = await import('/node_modules/gl-matrix/esm/index.js');+ const geometry = box();+ const deltas = new Float32Array(geometry.positions.length);+ for (let index = 0; index < deltas.length; index += 3) {+ deltas[index] = 0.5;+ deltas[index + 1] = 0.25;+ }+ const targets = Array.from({ length: 64 }, () => ({ positions: new Float32Array(deltas.length) }));+ targets[63] = { positions: deltas };+ geometry.morphTargets = targets;+ const firstPose = createMorphPose(64);+ const secondPose = createMorphPose(64);+ const canvas = document.querySelector('canvas');+ const material = { tag: 'unlit', color: [0.4, 0.6, 0.8], roughness: 0.7, metallic: 0, emission: 0 };+ const first = { name: 'positive blend', geometry, matrix: mat4.create(), material, morph: firstPose };+ const second = { name: 'negative blend', geometry, matrix: mat4.fromTranslation(mat4.create(), [-1.5, 0, 0]), material, morph: secondPose };+ const options = { ground: false, world: true, samples: 1, pixelRatio: 1, memoryBudgetMiB: 64 };+ const frame = { eye: [2, 2, 6], target: [-0.4, 0, 0], fov: 40, time: 0, effects: { grain: 0, bloom: { strength: 0 } } };+ const renderer = new Renderer67(canvas, [first, second], options);+ const record = renderer.morphTextures.get(geometry);+ const buffers = renderer.batches.map(batch => batch.instanceBuffer);+ const weights = renderer.batches.map(batch => batch.morphWeights);+ function pixels() {+ renderer.render(frame);+ const output = new Uint8Array(canvas.width * canvas.height * 4);+ const context = renderer.context;+ context.readPixels(0, 0, canvas.width, canvas.height, context.RGBA, context.UNSIGNED_BYTE, output);+ return output;+ }+ function checksum(values) {+ let result = 2166136261;+ for (const value of values) result = Math.imul(result ^ value, 16777619) >>> 0;+ return result;+ }+ const neutral = pixels();+ firstPose.weights[63] = 1.5;+ secondPose.weights[63] = -0.5;+ const uncommitted = pixels();+ renderer.updateParts([first, second]);+ const blended = pixels();+ const image = canvas.toDataURL('image/png');+ let retained = true;+ for (let index = 0; index < 60; index++) {+ firstPose.weights[63] = index % 2 ? 1.5 : 0;+ renderer.updateParts([first]);+ pixels();+ retained &&= renderer.morphTextures.get(geometry) === record && renderer.batches.every((batch, batchIndex) => batch.instanceBuffer === buffers[batchIndex] && batch.morphWeights === weights[batchIndex]);+ }+ firstPose.weights[63] = 1.5;+ renderer.updateParts([first]);+ const repeated = pixels();+ const committed = renderer.batches.map(batch => Array.from(batch.morphWeights));+ firstPose.weights[63] = NaN;+ let invalidRejected = false;+ try { renderer.updateParts([first]); } catch { invalidRejected = true; }+ const atomic = renderer.batches.every((batch, index) => Array.from(batch.morphWeights).every((value, target) => value === committed[index][target]));+ firstPose.weights[63] = 1.5;+ const glError = renderer.context.getError();+ const targetBytes = record.bytes;+ const textureCount = renderer.morphTextures.size;+ const batches = renderer.batches.length;+ const memory = renderer.memoryPlan;+ const context = renderer.context;+ const texture = record.texture;+ renderer.dispose();+ const released = !context.isTexture(texture);+ const referenceParts = [first, second].map(part => {+ const positions = new Float32Array(geometry.positions);+ const amount = part.morph.weights[63];+ for (let index = 0; index < positions.length; index++) positions[index] = geometry.positions[index] + deltas[index] * amount;+ return { ...part, morph: undefined, geometry: { positions, normals: geometry.normals, indices: geometry.indices } };+ });+ const reference = new Renderer67(canvas, referenceParts, options);+ reference.render(frame);+ const referencePixels = new Uint8Array(blended.length);+ reference.context.readPixels(0, 0, canvas.width, canvas.height, reference.context.RGBA, reference.context.UNSIGNED_BYTE, referencePixels);+ const referenceError = reference.context.getError();+ reference.dispose();+ return { neutral: checksum(neutral), uncommitted: checksum(uncommitted), blended: checksum(blended), repeated: checksum(repeated), reference: checksum(referencePixels), retained, invalidRejected, atomic, released, glError, referenceError, targetBytes, textureCount, batches, memory, image };+ });+ assert.deepEqual(errors, []);+ assert.equal(report.glError, 0);+ assert.equal(report.referenceError, 0);+ assert.equal(report.neutral, report.uncommitted);+ assert.notEqual(report.neutral, report.blended);+ assert.equal(report.blended, report.repeated);+ assert.equal(report.blended, report.reference, 'GPU relative blend must match the CPU-authored reference image');+ assert.equal(report.textureCount, 1);+ assert.equal(report.batches, 2);+ for (const field of ['retained', 'invalidRejected', 'atomic', 'released']) assert.equal(report[field], true);+ await writeFile('artifacts/morph-gpu.png', Buffer.from(report.image.split(',')[1], 'base64'));+ delete report.image;+ await writeFile('artifacts/morph-gpu.json', JSON.stringify(report, null, 2));+ console.log(JSON.stringify(report, null, 2));+} finally {+ await browser.close();+}diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 2da90ec9..886b994e 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -30,7 +30,7 @@ const sourceArchive = resolve(consumer, packedSource.filename);const installed = spawnSync(process.execPath, [npmCli, 'install', `67js@file:${sourceArchive.replaceAll('\\', '/')}`, '@dimforge/[email protected]', '--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, cameraView, fitPerspectiveDistance, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS } from '67js';+import { VERSION, Renderer67, box, assemblyOffset, cameraView, fitPerspectiveDistance, createAnimationClip, sampleAnimationClip, EFFECT_PRESETS, createMorphPose, MAX_MORPH_TARGETS } from '67js';import { createModel } from '67js/addons/model';import * as nature from '67js/addons/nature';import * as film from '67js/addons/film';@@ -40,6 +40,8 @@ import { parseGltf } from '67js/addons/gltf';import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';assert.equal(VERSION, '${metadata.version}');assert.equal(typeof Renderer67, 'function');+assert.equal(MAX_MORPH_TARGETS, 64);+assert.ok(createMorphPose(64).weights instanceof Float32Array);assert.throws(() => new Renderer67({}, [], { environment: { pointLights: Array(9).fill({ position: [0, 1, 0] }) } }), /at most/, 'Packed renderer must validate light limits before requesting a GPU context.');assert.ok(box().positions.length > 0);const parts = createModel();diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex db801ed0..b58837f7 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -20,6 +20,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- Local lights use the renderer environment and the checkout's `docs/lighting.md`.- Depth-clipped fog uses `{ hdr: true, depth: true }` and the checkout's `docs/volumetric.md`.- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.md`.+- Relative facial or shape deformation uses `src/morph.js` and the checkout's `docs/morph-targets.md`; check source versus published support first.- Recorded contacts or articulated physics use optional `src/physics.js` and the checkout's `docs/physics.md`.- 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`.diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 7af936f5..258314bc 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -92,6 +92,12 @@ Camera FOV uses degrees. Film time must be finite and independent of the wall clAnimation 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.+Source morph parts add `geometry.morphTargets: [{ positions, normals }]` and `morph: createMorphPose(count)`.+Targets contain static relative Float32 XYZ deltas, not absolute vertices. At least one channel is present.+Change retained `part.morph.weights`, then call `renderer.updateParts()` to commit the pose.+Separate pose identities split batches; repeated parts can share static target geometry.+Morphs run before skinning and use standard materials. Read `docs/morph-targets.md` for numeric limits and memory costs.+Do not silently export morphs through `exportGlb`; it currently rejects them. Check the decoder's capabilities before importing shape keys.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.diff --git a/src/export.js b/src/export.jsindex c47422d7..e659ec93 100644--- a/src/export.js+++ b/src/export.js@@ -4,6 +4,9 @@ function paddedLength(length) {export function exportGlb(parts) {for (const part of parts) {+ if (part.morph || part.geometry.morphTargets !== undefined) {+ throw new RangeError('GLB export cannot preserve morph targets yet. Bake the pose or export through a tool that preserves the targets.');+ }if (part.skin || part.geometry.skinIndices || part.geometry.skinWeights) {throw new RangeError('GLB export cannot preserve skinning yet. Bake the pose or export through a tool that preserves the skeleton.');}diff --git a/src/film.js b/src/film.jsindex 4c0039bc..2f6999a9 100644--- a/src/film.js+++ b/src/film.js@@ -6,6 +6,7 @@ import { box, cylinder, sphere, torus } from './geometry.js';import { extrude } from './modeling.js';import { createAnimationClip, createAnimationPlayer } from './animation.js';import { sampleScientistHead } from './film-character.js';+import { createMorphPose } from './morph.js';import { CRADLE, cradlePivot } from './film-physics-definition.js';import cradleRecording from './film-physics-clip.json' with { type: 'json' };@@ -124,6 +125,29 @@ function createScientistHeadMesh() {return geometry;}+function createEyelidMesh() {+ const surface = lowerLatitude => sampledSurface(32, 16, (horizontal, vertical) => {+ const longitude = (0.5 - horizontal) * 2.7;+ const latitude = 1.48 + vertical * (lowerLatitude - 1.48);+ const radius = 0.5;+ return [+ Math.sin(longitude) * Math.cos(latitude) * radius,+ Math.sin(latitude) * radius,+ Math.cos(longitude) * Math.cos(latitude) * radius,+ ];+ });+ const geometry = surface(0.55);+ const closed = surface(-0.75);+ const positions = new Float32Array(geometry.positions.length);+ const normals = new Float32Array(geometry.normals.length);+ for (let component = 0; component < positions.length; component++) {+ positions[component] = closed.positions[component] - geometry.positions[component];+ normals[component] = closed.normals[component] - geometry.normals[component];+ }+ geometry.morphTargets = [{ positions, normals }];+ return geometry;+}+function createFedoraBrim() {return sampledSurface(64, 20, (horizontal, vertical) => {const angle = horizontal * FULL_TURN;@@ -365,6 +389,7 @@ function createIgnition(meshes) {function addScientist(builder, position = [0, 0, 0], hat = true, rotation = 0) {const { add } = builder;const actorName = `Scientist ${builder.parts.length}`;+ const blinkPose = createMorphPose(1);const joints = new Map();const transform = point => [position[0] + point[0] * Math.cos(rotation) + point[2] * Math.sin(rotation), position[1] + point[1], position[2] - point[0] * Math.sin(rotation) + point[2] * Math.cos(rotation)];const actorMaterials = {@@ -428,7 +453,8 @@ function addScientist(builder, position = [0, 0, 0], hat = true, rotation = 0) {shape('Facial eye white', 'sphere', [side * 0.046, 1.711, 0.079], [0.021, 0.008, 0.013], 'eye');shape('Facial blue iris', 'sphere', [side * 0.046, 1.711, 0.0905], [0.0065, 0.0063, 0.0018], 'iris');shape('Facial pupil', 'sphere', [side * 0.046, 1.711, 0.092], [0.0027, 0.0034, 0.0009], 'pupil');- shape('Facial upper eyelid', 'sphere', [side * 0.046, 1.718, 0.085], [0.023, 0.0047, 0.006], 'skin');+ const eyelid = shape('Facial upper eyelid', 'eyelid', [side * 0.046, 1.711, 0.085], [0.047, 0.018, 0.017], 'skin');+ eyelid.morph = blinkPose;shape('Facial lower eyelid', 'sphere', [side * 0.046, 1.704, 0.085], [0.022, 0.0035, 0.005], 'skin');shape('Facial eyebrow', 'sphere', [side * 0.046, 1.735, 0.09], [0.028, 0.004, 0.005], 'graphite', [0, 0, side * -0.11]);shape('Facial nostril', 'sphere', [side * 0.008, 1.66, 0.1245], [0.0038, 0.0022, 0.0018], 'lip');@@ -721,6 +747,7 @@ function createSparks(meshes) {function animateSet(parts, sceneName) {const animateActors = createFilmActorRig(parts);+ const blinkPoses = [...new Set(parts.filter(part => part.morph).map(part => part.morph))];const animatePhysics = sceneName === 'apparatus' ? createCradleAnimation(parts) : null;const moving = parts.filter(part =>sceneName === 'sparks' || sceneName === 'atom' ||@@ -736,6 +763,13 @@ function animateSet(parts, sceneName) {}return function animate(time) {animateActors(time);+ for (let index = 0; index < blinkPoses.length; index++) {+ const phase = ((time + index * 0.73) % 3.7 + 3.7) % 3.7;+ const closure = phase >= 1.8 && phase <= 2.04+ ? Math.sin((phase - 1.8) / 0.24 * Math.PI) ** 2+ : 0;+ blinkPoses[index].weights[0] = closure;+ }animatePhysics?.(time);moving.forEach((part, index) => {const base = bases[index];@@ -779,6 +813,7 @@ function animateSet(parts, sceneName) {export function createFilmScenes() {const meshes = {+ eyelid: createEyelidMesh(),box: box(0.025, 2),head: createScientistHeadMesh(),hatCrown: createFedoraCrown(),diff --git a/src/index.js b/src/index.jsindex 3423d3cf..ee32db44 100644--- a/src/index.js+++ b/src/index.js@@ -7,6 +7,7 @@ export { exportGlb } from './export.js';export { createAnimationMixer } from './animation-mixer.js';export { createSceneGraph } from './scene-graph.js';export { createSkinPose, updateSkinPose } from './skinning.js';+export { createMorphPose, MAX_MORPH_TARGETS } from './morph.js';export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js';export { assemblyOffset } from './assembly.js';diff --git a/src/morph.js b/src/morph.jsnew file mode 100644index 00000000..6cbee26b--- /dev/null+++ b/src/morph.js@@ -0,0 +1,190 @@+export const MAX_MORPH_TARGETS = 64;++const validatedMetadata = new WeakSet();+const MIN_NORMAL_FLOAT32 = 2 ** -126;++// Round nonnegative bounds upward so fused shader arithmetic cannot exceed them.+function upperFloatBound(value) {+ const rounded = Math.fround(value);+ if (rounded >= value || !Number.isFinite(rounded)) return rounded;+ return Math.fround(rounded + Math.max(2 ** -149, rounded * 2 ** -23));+}++function targetCount(value) {+ if (!Number.isSafeInteger(value) || value < 1 || value > MAX_MORPH_TARGETS) {+ throw new RangeError('Morph target count must be within one and 64.');+ }+ return value;+}++export function createMorphPose(count) {+ return { weights: new Float32Array(targetCount(count)) };+}++function componentMaxima(values, length, label, requireNormal = false) {+ if (!(values instanceof Float32Array) || values.length !== length) {+ throw new TypeError(`${label} requires one Float32 RGB vector per vertex.`);+ }+ const maxima = [0, 0, 0];+ for (let offset = 0; offset < length; offset += 3) {+ let squaredLength = 0;+ for (let component = 0; component < 3; component++) {+ const value = values[offset + component];+ if (!Number.isFinite(value)) throw new RangeError(`${label} must contain finite Float32 values.`);+ maxima[component] = Math.max(maxima[component], Math.abs(value));+ squaredLength = Math.fround(squaredLength + Math.fround(value * value));+ }+ if (requireNormal && (!Number.isFinite(squaredLength) || squaredLength < MIN_NORMAL_FLOAT32)) {+ throw new RangeError('Base morph normals require a finite normal Float32 squared length.');+ }+ }+ return Object.freeze(maxima);+}++function geometryMetadata(geometry) {+ const componentCount = geometry?.positions?.length;+ if (!Number.isSafeInteger(componentCount) || componentCount < 3 || componentCount % 3 !== 0) {+ throw new TypeError('Morph base positions require a nonempty RGB vertex array.');+ }+ const basePositionMaxima = componentMaxima(geometry.positions, componentCount, 'Morph base positions');+ const baseNormalMaxima = componentMaxima(geometry.normals, componentCount, 'Morph base normals', true);+ if (!Array.isArray(geometry.morphTargets)) throw new TypeError('Morph geometry requires a target array.');+ const count = targetCount(geometry.morphTargets.length);+ const targets = [];+ for (let index = 0; index < count; index++) {+ const target = geometry.morphTargets[index];+ if (!target || typeof target !== 'object' || Array.isArray(target)) throw new TypeError('Each morph target must be an object.');+ for (const key of Object.keys(target)) {+ if (key !== 'positions' && key !== 'normals') throw new TypeError(`Morph target ${key} is unsupported.`);+ }+ if (target.positions === undefined && target.normals === undefined) throw new TypeError('Each morph target requires positions or normals.');+ const positionMaxima = target.positions === undefined ? Object.freeze([0, 0, 0]) : componentMaxima(target.positions, componentCount, 'Morph position deltas');+ const normalMaxima = target.normals === undefined ? Object.freeze([0, 0, 0]) : componentMaxima(target.normals, componentCount, 'Morph normal deltas');+ targets.push(Object.freeze({ target, positions: target.positions, normals: target.normals, positionMaxima, normalMaxima }));+ }+ const metadata = Object.freeze({+ geometry,+ positions: geometry.positions,+ normals: geometry.normals,+ morphTargets: geometry.morphTargets,+ vertexCount: componentCount / 3,+ targetCount: count,+ texelCount: componentCount / 3 * count * 2,+ basePositionMaxima,+ baseNormalMaxima,+ targets: Object.freeze(targets),+ });+ validatedMetadata.add(metadata);+ return metadata;+}++function validateIdentities(metadata) {+ if (!validatedMetadata.has(metadata)) throw new TypeError('Use metadata from validateMorphGeometry().');+ const geometry = metadata.geometry;+ if (geometry.positions !== metadata.positions || geometry.normals !== metadata.normals || geometry.morphTargets !== metadata.morphTargets+ || geometry.morphTargets.length !== metadata.targetCount) {+ throw new Error('Morph geometry array identities must remain unchanged after preflight.');+ }+ for (let index = 0; index < metadata.targetCount; index++) {+ const snapshot = metadata.targets[index];+ if (geometry.morphTargets[index] !== snapshot.target || snapshot.target.positions !== snapshot.positions || snapshot.target.normals !== snapshot.normals) {+ throw new Error('Morph target and channel identities must remain unchanged after preflight.');+ }+ }+}++/** Full static preflight. One geometry metadata object serves independent poses. */+export function validateMorphGeometry(geometry, pose) {+ if (!pose) {+ if (geometry?.morphTargets !== undefined) throw new TypeError('Morph targets require a morph pose.');+ return undefined;+ }+ const metadata = geometryMetadata(geometry);+ validateMorphPose(pose, metadata);+ return metadata;+}++/** Bounded validation of mutable weights without rescanning uploaded channel contents. */+export function validateMorphPose(pose, metadata) {+ validateIdentities(metadata);+ const weights = pose?.weights;+ if (!(weights instanceof Float32Array) || weights.length !== metadata.targetCount) {+ throw new TypeError('Morph pose requires one Float32 weight per target.');+ }+ for (let index = 0; index < weights.length; index++) {+ if (!Number.isFinite(weights[index])) throw new RangeError('Morph weights must remain finite Float32 values.');+ }+ let squaredNormalBound = 0;+ for (let component = 0; component < 3; component++) {+ let positionBound = metadata.basePositionMaxima[component];+ let normalBound = metadata.baseNormalMaxima[component];+ for (let index = 0; index < weights.length; index++) {+ const magnitude = Math.abs(weights[index]);+ positionBound = upperFloatBound(positionBound + upperFloatBound(magnitude * metadata.targets[index].positionMaxima[component]));+ normalBound = upperFloatBound(normalBound + upperFloatBound(magnitude * metadata.targets[index].normalMaxima[component]));+ }+ if (!Number.isFinite(positionBound) || !Number.isFinite(normalBound)) {+ throw new RangeError('Morph weights exceed finite Float32 position or normal bounds.');+ }+ squaredNormalBound = upperFloatBound(squaredNormalBound + upperFloatBound(normalBound * normalBound));+ }+ if (!Number.isFinite(squaredNormalBound)) throw new RangeError('Morph weights exceed a finite Float32 normal squared length bound.');+ return metadata;+}++/** Conservative Float32 bounds for the shader's world * skin * morphed position. */+export function validateMorphTransform(pose, metadata, worldMatrix, skin) {+ validateMorphPose(pose, metadata);+ for (let row = 0; row < 4; row++) {+ let coordinateBound = 0;+ for (let column = 0; column < 4; column++) {+ let localBound = column === 3 ? 1 : metadata.basePositionMaxima[column];+ if (column < 3) {+ for (let target = 0; target < metadata.targetCount; target++) {+ localBound = upperFloatBound(localBound + upperFloatBound(Math.abs(pose.weights[target]) * metadata.targets[target].positionMaxima[column]));+ }+ }+ let coefficientBound = Math.abs(Math.fround(worldMatrix[column * 4 + row]));+ if (skin) {+ coefficientBound = 0;+ for (let axis = 0; axis < 4; axis++) {+ let paletteBound = 0;+ for (let offset = column * 4 + axis; offset < skin.jointMatrices.length; offset += 16) {+ paletteBound = Math.max(paletteBound, Math.abs(Math.fround(skin.jointMatrices[offset])));+ }+ // Four normalized Float32 influences can sum slightly above one.+ paletteBound = upperFloatBound(paletteBound * (1 + 2 ** -21));+ coefficientBound = upperFloatBound(coefficientBound + upperFloatBound(Math.abs(Math.fround(worldMatrix[axis * 4 + row])) * paletteBound));+ }+ }+ if (!Number.isFinite(coefficientBound)) throw new RangeError('Morph world/skin matrix product exceeds finite Float32 bounds.');+ coordinateBound = upperFloatBound(coordinateBound + upperFloatBound(coefficientBound * localBound));+ }+ if (!Number.isFinite(coordinateBound)) throw new RangeError('Morph world position exceeds finite Float32 bounds.');+ }+}++/** Pack relative RGB channels as two RGBA texels per target vertex. */+export function packMorphTargets(geometry, layout) {+ const metadata = geometryMetadata(geometry);+ const width = layout?.width;+ const height = layout?.height;+ const texels = width * height;+ const bytes = texels * 16;+ if (!Number.isSafeInteger(width) || width < 2 || width % 2 !== 0 || !Number.isSafeInteger(height) || height < 1+ || !Number.isSafeInteger(bytes) || bytes > 2 ** 31 - 1 || texels < metadata.texelCount || (layout.bytes !== undefined && layout.bytes !== bytes)) {+ throw new RangeError('Morph texture layout requires even width, sufficient capacity and a bounded byte length.');+ }+ const data = new Float32Array(texels * 4);+ for (let target = 0; target < metadata.targetCount; target++) {+ const channels = metadata.targets[target];+ for (let vertex = 0; vertex < metadata.vertexCount; vertex++) {+ const offset = (target * metadata.vertexCount + vertex) * 8;+ for (let component = 0; component < 3; component++) {+ data[offset + component] = channels.positions?.[vertex * 3 + component] ?? 0;+ data[offset + 4 + component] = channels.normals?.[vertex * 3 + component] ?? 0;+ }+ }+ }+ return data;+}diff --git a/src/renderer.js b/src/renderer.jsindex 186e24f1..db4dc590 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -7,6 +7,7 @@ import { resolveEffects } from './effects.js';import { createLightingState, updateLightingState } from './lighting.js';import { resolveVolumeFog } from './volumetric.js';import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';+import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };const INSTANCE_STRIDE = 41;@@ -17,6 +18,7 @@ const MAP_FLAGS = ['hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasconst DEFAULT_NORMAL_SCALE = [1, 1];const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);const SKIN_UNIFORMS = ['skinEnabled', 'skinInfluences', 'jointPalette'];+const MORPH_UNIFORMS = ['morphEnabled', 'morphVertexCount', 'morphTargetCount', 'morphWeights[0]', 'morphTargets'];function validateMaterialMaps(material) {if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {@@ -122,16 +124,21 @@ function groundPart() {export function groupParts(parts, batching = true) {const groups = new Map();const batches = [];+ const morphInfos = new Map();for (const part of parts) {validateTransform(part);if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');validateSkinGeometry(part.geometry, part.skin);if (part.skin) validateSkinPose(part.skin, part.geometry, part.matrix);if (part.skin && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');+ if (!morphInfos.has(part.geometry)) morphInfos.set(part.geometry, validateMorphGeometry(part.geometry, part.morph));+ else if (part.morph || part.geometry.morphTargets) validateMorphPose(part.morph, morphInfos.get(part.geometry));+ if (part.morph && PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Morphed parts require a standard material tag.');+ if (part.morph) validateMorphTransform(part.morph, morphInfos.get(part.geometry), part.matrix, part.skin);const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());let maps = groups.get(key);- for (const value of [...materialMapState(part.material), part.skin ?? null, part.castShadow !== false]) {+ for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, part.castShadow !== false]) {if (!maps.has(value)) maps.set(value, new Map());maps = maps.get(value);}@@ -197,15 +204,27 @@ export class Renderer67 {this.partLocations = new Map();this.updateBatches = new Set();this.updateSkins = new Set();+ this.updateMorphs = new Set();this.skinTextures = new Map();this.influenceTextures = new Map();+ this.morphTextures = new Map();this.textures = new Map();this.textureBytes = 4;this.shadowsDirty = true;const groups = groupParts(ground ? [...parts, groundPart()] : parts, batching);const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);this.hasSkins = groups.some(group => group[0].skin);+ this.hasMorphs = groups.some(group => group[0].morph);if (this.hasSkins && (this.context.getParameter(this.context.MAX_VERTEX_TEXTURE_IMAGE_UNITS) < 2 || this.context.getParameter(this.context.MAX_COMBINED_TEXTURE_IMAGE_UNITS) < 8)) throw new Error('GPU skinning requires two vertex texture units and eight combined texture units.');+ if (this.hasMorphs && (this.context.getParameter(this.context.MAX_VERTEX_TEXTURE_IMAGE_UNITS) < (this.hasSkins ? 3 : 1) || this.context.getParameter(this.context.MAX_COMBINED_TEXTURE_IMAGE_UNITS) < 9)) throw new Error('GPU morphing requires one additional vertex texture unit and nine combined texture units.');+ const morphGeometries = new Set();+ for (const group of groups) {+ const part = group[0];+ if (!part.morph || morphGeometries.has(part.geometry)) continue;+ const texelCount = part.geometry.positions.length / 3 * part.geometry.morphTargets.length * 2;+ this.textureBytes += skinTextureLayout(texelCount, textureLimit, 2).bytes;+ morphGeometries.add(part.geometry);+ }const poses = new Set();const skinGeometries = new Set();for (const group of groups) {@@ -247,11 +266,12 @@ export class Renderer67 {this.inverseViewProjection = mat4.create();this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, 'normalScale', 'occlusionStrength', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'lightDirection', 'fogColor', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {this.uniforms[name] = this.context.getUniformLocation(this.program, name);}this.depthSkinUniforms = Object.fromEntries(SKIN_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));+ this.depthMorphUniforms = Object.fromEntries(MORPH_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));if (!benchmark) {this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);this.skyProgram = compileProgram(this.context, fullscreenVertex, skyFragment);@@ -271,7 +291,11 @@ export class Renderer67 {this.context.uniform1i(uniforms.skinInfluences, 6);this.context.uniform1i(uniforms.jointPalette, 7);}- for (const unit of [6, 7]) {+ for (const [program, uniforms] of [[this.program, this.uniforms], [this.depthProgram, this.depthMorphUniforms]]) {+ this.context.useProgram(program);+ this.context.uniform1i(uniforms.morphTargets, 8);+ }+ for (const unit of [6, 7, 8]) {this.context.activeTexture(this.context.TEXTURE0 + unit);this.context.bindTexture(this.context.TEXTURE_2D, this.whiteTexture);}@@ -380,8 +404,11 @@ export class Renderer67 {const skin = parts[0].skin ?? null;const skinTexture = skin ? this.createSkinTexture(this.skinTextures, skin, skin.jointMatrices, 4) : null;const influenceTexture = skin ? this.createSkinTexture(this.influenceTextures, geometry, null, 2) : null;- const batch = { vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false };- parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));+ const morph = parts[0].morph ?? null;+ const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;+ const morphWeights = morph ? new Float32Array(morph.weights) : null;+ const batch = { vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false };+ parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));return batch;}@@ -392,6 +419,24 @@ export class Renderer67 {const layout = skinTextureLayout(texelCount, context.getParameter(context.MAX_TEXTURE_SIZE), groupSize);const data = matrices ? new Float32Array(layout.width * layout.height * 4) : packSkinInfluences(identity, layout);if (matrices) data.set(matrices);+ const record = this.createPackedTexture(layout, data);+ record.pose = matrices ? identity : null;+ cache.set(identity, record);+ return record;+ }++ createMorphTexture(geometry, pose) {+ if (this.morphTextures.has(geometry)) return this.morphTextures.get(geometry);+ const info = validateMorphGeometry(geometry, pose);+ const layout = skinTextureLayout(info.vertexCount * info.targetCount * 2, this.context.getParameter(this.context.MAX_TEXTURE_SIZE), 2);+ const record = this.createPackedTexture(layout, packMorphTargets(geometry, layout));+ record.info = info;+ this.morphTextures.set(geometry, record);+ return record;+ }++ createPackedTexture(layout, data) {+ const context = this.context;const texture = context.createTexture();context.bindTexture(context.TEXTURE_2D, texture);try {@@ -404,15 +449,15 @@ export class Renderer67 {context.deleteTexture(texture);throw error;}- const record = { ...layout, texture, data, pose: matrices ? identity : null };- cache.set(identity, record);- return record;+ return { ...layout, texture, data };}updateParts(parts, { shadows = true } = {}) {this.updatePartIdentities ??= new Set();this.updatePartIdentities.clear();this.updateSkins.clear();+ this.updateMorphs ??= new Set();+ this.updateMorphs.clear();this.updateBatches.clear();// Preflight every part before touching packed data or submitting GPU writes.for (const part of parts) {@@ -428,6 +473,12 @@ export class Renderer67 {validateSkinPose(part.skin, part.geometry, part.matrix);this.updateSkins.add(location.batch.skinTexture);}+ if ((part.morph ?? null) !== (location.morph ?? null) || part.morph?.weights !== location.morphWeights || part.geometry.morphTargets !== location.morphTargets) throw new Error(`Morph identity changes require a new renderer: ${part.name}`);+ if (part.morph) {+ if (PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Morphed parts require a standard material tag.');+ validateMorphTransform(part.morph, location.batch.morphTexture.info, part.matrix, part.skin);+ this.updateMorphs.add(part.morph);+ }if ((part.material.map ?? null) !== location.map) throw new Error(`Texture map changes require a new renderer: ${part.name}`);validateMaterialMaps(part.material);const normalScale = part.material.normalScale ?? DEFAULT_NORMAL_SCALE;@@ -446,6 +497,13 @@ export class Renderer67 {validateSkinPose(location.skin, location.geometry, committedMatrix);}}+ // Shared weights also affect batches absent from the submitted part list.+ for (const [part, location] of this.partLocations) {+ if (!location.morph || this.updatePartIdentities.has(part)) continue;+ if (!this.updateMorphs.has(location.morph) && !this.updateSkins.has(location.batch.skinTexture)) continue;+ const committedMatrix = location.committedMatrix ?? location.batch.instanceData.subarray(location.index * INSTANCE_STRIDE, location.index * INSTANCE_STRIDE + 16);+ validateMorphTransform(location.morph, location.batch.morphTexture.info, committedMatrix, location.skin);+ }this.updateBatches.clear();for (const part of parts) {const location = this.partLocations.get(part);@@ -463,6 +521,9 @@ export class Renderer67 {this.context.bindTexture(this.context.TEXTURE_2D, record.texture);this.context.texSubImage2D(this.context.TEXTURE_2D, 0, 0, 0, record.width, record.height, this.context.RGBA, this.context.FLOAT, record.data);}+ for (const batch of this.batches ?? []) {+ if (batch.morph && this.updateMorphs.has(batch.morph)) batch.morphWeights.set(batch.morph.weights);+ }if (shadows && parts.length > 0) this.shadowsDirty = true;return parts.length;}@@ -693,6 +754,17 @@ export class Renderer67 {}drawBatch(batch, textured = false) {+ if (this.hasMorphs) {+ const uniforms = textured ? this.uniforms : this.depthMorphUniforms;+ this.context.uniform1f(uniforms.morphEnabled, batch.morph ? 1 : 0);+ if (batch.morph) {+ this.context.uniform1i(uniforms.morphVertexCount, batch.morphTexture.info.vertexCount);+ this.context.uniform1i(uniforms.morphTargetCount, batch.morphTexture.info.targetCount);+ this.context.uniform1fv(uniforms['morphWeights[0]'], batch.morphWeights);+ this.context.activeTexture(this.context.TEXTURE0 + 8);+ this.context.bindTexture(this.context.TEXTURE_2D, batch.morphTexture.texture);+ }+ }if (this.hasSkins) {const uniforms = textured ? this.uniforms : this.depthSkinUniforms;this.context.uniform1f(uniforms.skinEnabled, batch.skin ? 1 : 0);@@ -804,13 +876,14 @@ export class Renderer67 {if (this.bloomProgram) this.context.deleteProgram(this.bloomProgram);for (const texture of this.textures.values()) this.context.deleteTexture(texture);this.textures.clear();- for (const cache of [this.skinTextures, this.influenceTextures]) {+ for (const cache of [this.skinTextures, this.influenceTextures, this.morphTextures]) {for (const record of cache?.values() ?? []) this.context.deleteTexture(record.texture);cache?.clear();}this.partLocations.clear();this.updatePartIdentities?.clear();this.updateSkins?.clear();+ this.updateMorphs?.clear();this.updateBatches?.clear();}}diff --git a/src/shaders.js b/src/shaders.jsindex cfc4f722..55aa29cb 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -1,3 +1,37 @@+import { MAX_MORPH_TARGETS } from './morph.js';++const morphingShader = `+uniform float morphEnabled;+uniform int morphVertexCount;+uniform int morphTargetCount;+uniform float morphWeights[${MAX_MORPH_TARGETS}];+uniform highp sampler2D morphTargets;+vec3 morphDelta(int target, int channel) {+ int index = (target * morphVertexCount + gl_VertexID) * 2 + channel;+ int width = textureSize(morphTargets, 0).x;+ return texelFetch(morphTargets, ivec2(index % width, index / width), 0).xyz;+}+vec3 morphedPosition(vec3 base) {+ if (morphEnabled < 0.5) return base;+ vec3 result = base;+ for (int target = 0; target < ${MAX_MORPH_TARGETS}; target++) {+ if (target >= morphTargetCount) break;+ if (morphWeights[target] != 0.0) result += morphDelta(target, 0) * morphWeights[target];+ }+ return result;+}+vec3 morphedNormal(vec3 base) {+ if (morphEnabled < 0.5) return base;+ vec3 result = base;+ for (int target = 0; target < ${MAX_MORPH_TARGETS}; target++) {+ if (target >= morphTargetCount) break;+ if (morphWeights[target] != 0.0) result += morphDelta(target, 1) * morphWeights[target];+ }+ float largest = max(max(abs(result.x), abs(result.y)), abs(result.z));+ return largest > 0.0 ? normalize(result / largest) : base;+}+`;+const skinningShader = `uniform float skinEnabled;uniform highp sampler2D skinInfluences;@@ -49,9 +83,10 @@ out vec2 textureUV;out vec3 vertexTint;flat out vec3 emissionColor;${skinningShader}+${morphingShader}void main() {mat4 deformation = skinTransform();- vec4 world = instanceMatrix * deformation * vec4(position, 1.0);+ vec4 world = instanceMatrix * deformation * vec4(morphedPosition(position), 1.0);world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);if (instanceSurface.w == 4.0 || instanceSurface.w == 7.0) {world.x += sin(time * 1.2 + world.z * 0.31 + world.x * 0.17) * wind * 0.10 * max(position.y + 0.5, 0.0);@@ -63,7 +98,8 @@ void main() {world.xyz = mix(explosionCenter, world.xyz, 0.03 + explosionProgress * 0.97);}worldPosition = world.xyz;- vec3 deformedNormal = skinEnabled > 0.5 ? transpose(inverse(mat3(deformation))) * normal : normal;+ vec3 localNormal = morphedNormal(normal);+ vec3 deformedNormal = skinEnabled > 0.5 ? transpose(inverse(mat3(deformation))) * localNormal : localNormal;worldNormal = normalize(instanceNormal * deformedNormal);baseColor = instanceColor;textureUV = uv;@@ -83,8 +119,9 @@ layout(location=12) in vec3 assemblyDetailOffset;uniform mat4 lightProjection;uniform float assemblyAmount;${skinningShader}+${morphingShader}void main() {- vec4 world = instanceMatrix * skinTransform() * vec4(position, 1.0);+ vec4 world = instanceMatrix * skinTransform() * vec4(morphedPosition(position), 1.0);world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);gl_Position = lightProjection * world;}`;@@ -102,9 +139,10 @@ layout(location=9) in vec3 instanceColor;uniform mat4 viewProjection;out vec3 color;${skinningShader}+${morphingShader}void main() {color = instanceColor;- gl_Position = viewProjection * instanceMatrix * skinTransform() * vec4(position, 1.0);+ gl_Position = viewProjection * instanceMatrix * skinTransform() * vec4(morphedPosition(position), 1.0);}`;export const benchmarkFragmentShader = `#version 300 esdiff --git a/tests/export.test.js b/tests/export.test.jsindex a5ae337d..fce008d8 100644--- a/tests/export.test.js+++ b/tests/export.test.js@@ -30,3 +30,9 @@ test('GLB export rejects skinning instead of silently saving the undeformed bindassert.throws(() => exportGlb([{ ...part, skin: { jointMatrices: new Float32Array(16) } }]), /preserve skinning/);assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, skinIndices: new Uint16Array(4) } }]), /preserve skinning/);});++test('GLB export rejects morph targets rather than discarding expressions', () => {+ const part = createModel()[0];+ assert.throws(() => exportGlb([{ ...part, morph: { weights: new Float32Array(1) } }]), /preserve morph targets/);+ assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, morphTargets: [] } }]), /preserve morph targets/);+});diff --git a/tests/film.test.js b/tests/film.test.jsindex a629f09c..5a7b7b68 100644--- a/tests/film.test.js+++ b/tests/film.test.js@@ -88,11 +88,14 @@ test('sets keep shared geometry, valid surfaces and the 384 MiB target budget',assert.ok(triangleCount <= 700000, name);const geometries = new Set(scene.parts.map(part => part.geometry));// Two shared garment contours replace rectangular collars and lapels.- assert.ok(geometries.size <= 14);+ assert.ok(geometries.size <= 15);let geometryBytes = scene.parts.length * 41 * 4;for (const geometry of geometries) {geometryBytes += geometry.positions.byteLength + geometry.normals.byteLength + geometry.indices.byteLength;geometryBytes += geometry.colors?.byteLength ?? 0;+ for (const target of geometry.morphTargets ?? []) {+ geometryBytes += (target.positions?.byteLength ?? 0) + (target.normals?.byteLength ?? 0);+ }if (checkedGeometries.has(geometry)) continue;checkedGeometries.add(geometry);assert.ok(geometry.positions instanceof Float32Array);@@ -239,3 +242,23 @@ test('narrow portrait shots retain face and headwear through camera moves and ba}for (const aspect of [0, -1, NaN, Infinity, 1e-320]) assert.throws(() => sampleFilm(10, { aspect }));});++test('scientist blink poses are shared per eye pair and replay across arbitrary seeks', () => {+ const scene = createFilmScenes().portrait;+ const eyelids = scene.parts.filter(part => part.name === 'Facial upper eyelid');+ assert.equal(eyelids.length, 2);+ assert.equal(eyelids[0].morph, eyelids[1].morph);+ const weights = eyelids[0].morph.weights;+ const geometry = eyelids[0].geometry;+ scene.animate(0);+ assert.equal(weights[0], 0);+ scene.animate(1.92);+ assert.ok(weights[0] > 0.999);+ scene.animate(11);+ scene.animate(1.92);+ assert.ok(weights[0] > 0.999);+ assert.equal(eyelids[0].morph.weights, weights);+ assert.equal(eyelids[0].geometry, geometry);+ scene.animate(3.7);+ assert.equal(weights[0], 0);+});diff --git a/tests/morph-renderer.test.js b/tests/morph-renderer.test.jsnew file mode 100644index 00000000..909d52e2--- /dev/null+++ b/tests/morph-renderer.test.js@@ -0,0 +1,132 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mat4, mat3 } from 'gl-matrix';+import { box } from '../src/geometry.js';+import { Renderer67, groupParts } from '../src/renderer.js';+import { createMorphPose, validateMorphGeometry } from '../src/morph.js';++function makePart(name, geometry, morph) {+ return { name, geometry, morph, matrix: mat4.create(), material: { color: [0.4, 0.5, 0.6], metallic: 0, roughness: 0.7, emission: 0 } };+}++function makeGeometry(delta = 0.5) {+ const geometry = box();+ const positions = new Float32Array(geometry.positions.length).fill(delta);+ geometry.morphTargets = [{ positions }];+ return geometry;+}++function retainedRenderer(parts) {+ const renderer = Object.create(Renderer67.prototype);+ const writes = [];+ renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData() { writes.push(true); } };+ renderer.updateSkins = new Set();+ renderer.updateBatches = new Set();+ renderer.partLocations = new Map();+ renderer.batches = groupParts(parts).map(group => {+ const first = group[0];+ const batch = {+ morph: first.morph,+ morphTexture: { info: validateMorphGeometry(first.geometry, first.morph) },+ morphWeights: new Float32Array(first.morph.weights),+ instanceBuffer: {},+ instanceData: new Float32Array(group.length * 41),+ castShadow: true,+ };+ group.forEach((part, index) => renderer.partLocations.set(part, {+ batch, index, geometry: part.geometry, morph: part.morph,+ morphWeights: part.morph.weights, morphTargets: part.geometry.morphTargets,+ skin: null, map: null, mapState: [null, null, null, null, null, 1, 1, 1],+ normalMatrix: mat3.create(),+ }));+ return batch;+ });+ renderer.updateParts(parts);+ writes.length = 0;+ return { renderer, writes };+}++test('morph pose identity partitions batches while shared geometry and pose retain instancing', () => {+ const geometry = makeGeometry();+ const pose = createMorphPose(1);+ const first = makePart('first', geometry, pose);+ const second = makePart('second', geometry, pose);+ assert.equal(groupParts([first, second]).length, 1);+ second.morph = createMorphPose(1);+ assert.equal(groupParts([first, second]).length, 2);+});++test('shared morph consumers outside update list reject unsafe weights before any committed changes', () => {+ const pose = createMorphPose(1);+ const first = makePart('small delta', makeGeometry(), pose);+ const second = makePart('large delta', makeGeometry(2e38), pose);+ const { renderer, writes } = retainedRenderer([first, second]);+ const snapshots = renderer.batches.map(batch => new Float32Array(batch.instanceData));+ const weights = renderer.batches.map(batch => batch.morphWeights);+ pose.weights[0] = 2;+ first.matrix[12] = 9;+ assert.throws(() => renderer.updateParts([first]), /Float32/);+ assert.equal(writes.length, 0);+ renderer.batches.forEach((batch, index) => {+ assert.deepEqual(batch.instanceData, snapshots[index]);+ assert.equal(batch.morphWeights, weights[index]);+ assert.equal(batch.morphWeights[0], 0);+ });+ pose.weights[0] = 0.5;+ renderer.updateParts([first]);+ assert.equal(writes.length, 1);+ renderer.batches.forEach(batch => assert.equal(batch.morphWeights[0], 0.5));+ first.morph.weights = new Float32Array([0]);+ assert.throws(() => renderer.updateParts([first]), /Morph identity/);+ assert.equal(writes.length, 1);+});++test('main and shadow draws upload the retained morph weights and disable morphs for rigid batches', () => {+ const renderer = Object.create(Renderer67.prototype);+ renderer.hasMorphs = true;+ renderer.benchmark = true;+ renderer.uniforms = { morphEnabled: 'color enabled', morphVertexCount: 'vertices', morphTargetCount: 'targets', 'morphWeights[0]': 'color weights' };+ renderer.depthMorphUniforms = { morphEnabled: 'shadow enabled', morphVertexCount: 'vertices', morphTargetCount: 'targets', 'morphWeights[0]': 'shadow weights' };+ const uploads = [];+ renderer.context = {+ TEXTURE0: 33984, activeTexture() {}, bindTexture() {}, bindVertexArray() {}, drawElementsInstanced() {},+ uniform1f(name, value) { uploads.push([name, value]); }, uniform1i() {}, uniform1fv(name, values) { uploads.push([name, values]); },+ };+ const batch = { morph: {}, morphTexture: { info: { vertexCount: 3, targetCount: 1 }, texture: {} }, morphWeights: new Float32Array([0.5]) };+ renderer.drawBatch(batch, true);+ renderer.drawBatch(batch);+ renderer.drawBatch({});+ assert.ok(uploads.some(([name, value]) => name === 'color weights' && value === batch.morphWeights));+ assert.ok(uploads.some(([name, value]) => name === 'shadow weights' && value === batch.morphWeights));+ assert.deepEqual(uploads.at(-1), ['shadow enabled', 0]);+});++test('world scale overflow and shared unsent consumer transforms reject before publishing morph weights', () => {+ const geometry = makeGeometry(2e38);+ const pose = createMorphPose(1);+ const first = makePart('ordinary scale', geometry, pose);+ const second = makePart('doubled scale', geometry, pose);+ mat4.fromScaling(second.matrix, [2, 1, 1]);+ const { renderer, writes } = retainedRenderer([first, second]);+ pose.weights[0] = 1;+ assert.throws(() => groupParts([second]), /Morph world position/);+ assert.throws(() => renderer.updateParts([first]), /Morph world position/);+ second.morph = undefined;+ assert.throws(() => renderer.updateParts([first]), /Morph world position/);+ assert.equal(writes.length, 0);+ renderer.batches.forEach(batch => assert.equal(batch.morphWeights[0], 0));+});++test('morph world bounds use the same Float32 coefficients as instance upload', () => {+ const delta = Math.fround(1e38);+ const maximum = 3.4028234663852886e38;+ const geometry = makeGeometry(0);+ for (let offset = 0; offset < geometry.positions.length; offset += 3) geometry.morphTargets[0].positions[offset] = delta;+ const pose = createMorphPose(1);+ pose.weights[0] = 1;+ const item = makePart('Float64 transform rounds upward', geometry, pose);+ item.matrix = Float64Array.from(mat4.create());+ item.matrix[0] = maximum / delta;+ assert.equal(Math.fround(Math.fround(item.matrix[0]) * delta), Infinity);+ assert.throws(() => groupParts([item]), /Morph world position/);+});diff --git a/tests/morph.test.js b/tests/morph.test.jsnew file mode 100644index 00000000..f802edaf--- /dev/null+++ b/tests/morph.test.js@@ -0,0 +1,164 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { BufferGeometry, Float32BufferAttribute, Mesh, Vector3 } from 'three';+import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorphPose, packMorphTargets } from '../src/morph.js';+import { skinTextureLayout } from '../src/skinning.js';++function triangle() {+ return {+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),+ morphTargets: [+ { positions: new Float32Array([1, 2, 0, 0, 2, 0, 1, 0, 0]), normals: new Float32Array([0, 1, -1, 0, 1, -1, 0, 1, -1]) },+ { positions: new Float32Array([0, 0, 2, -2, 0, 1, 0, -1, 2]) },+ ],+ };+}++test('signed relative target blends match literal positions and the installed Three.js Mesh implementation', () => {+ const geometry = triangle();+ const pose = createMorphPose(2);+ pose.weights.set([0.5, -2]);+ const metadata = validateMorphGeometry(geometry, pose);+ const packed = packMorphTargets(geometry, skinTextureLayout(metadata.texelCount, 16, 2));+ const threeGeometry = new BufferGeometry();+ threeGeometry.setAttribute('position', new Float32BufferAttribute(geometry.positions, 3));+ threeGeometry.morphAttributes.position = geometry.morphTargets.map(target => new Float32BufferAttribute(target.positions, 3));+ threeGeometry.morphTargetsRelative = true;+ const mesh = new Mesh(threeGeometry);+ mesh.morphTargetInfluences = Array.from(pose.weights);+ const expected = [[0.5, 1, -4], [5, 1, -2], [0.5, 3, -4]];+ for (let vertex = 0; vertex < 3; vertex++) {+ const actual = Array.from(geometry.positions.subarray(vertex * 3, vertex * 3 + 3));+ for (let target = 0; target < 2; target++) {+ for (let component = 0; component < 3; component++) actual[component] += pose.weights[target] * packed[(target * 3 + vertex) * 8 + component];+ }+ assert.deepEqual(actual, expected[vertex]);+ assert.deepEqual(mesh.getVertexPosition(vertex, new Vector3()).toArray(), expected[vertex]);+ }+ assert.deepEqual(Array.from(pose.weights), [0.5, -2]);+ assert.deepEqual([0, 0.5, 0.5], [0, packed[5] * 0.5, 1 + packed[6] * 0.5]);+ mesh.material.dispose();+ threeGeometry.dispose();+});++test('target-major two-texel packing preserves channels, missing zeros and texture padding', () => {+ const geometry = triangle();+ geometry.morphTargets.push({ normals: new Float32Array([1, 0, 0, 0, 2, 0, 0, 0, 3]) });+ const metadata = validateMorphGeometry(geometry, createMorphPose(3));+ const layout = skinTextureLayout(metadata.texelCount, 8, 2);+ assert.deepEqual(layout, { width: 6, height: 3, bytes: 288 });+ const data = packMorphTargets(geometry, { width: 8, height: 3, bytes: 384 });+ assert.deepEqual(Array.from(data.subarray(0, 8)), [1, 2, 0, 0, 0, 1, -1, 0]);+ assert.deepEqual(Array.from(data.subarray(24, 32)), [0, 0, 2, 0, 0, 0, 0, 0]);+ assert.deepEqual(Array.from(data.subarray(48, 56)), [0, 0, 0, 0, 1, 0, 0, 0]);+ assert.deepEqual(Array.from(data.subarray(64, 72)), [0, 0, 0, 0, 0, 0, 3, 0]);+ assert.ok(data.subarray(72).every(value => value === 0));+ assert.equal(data.byteLength, 384);+ assert.equal(metadata.vertexCount, 3);+ assert.equal(metadata.targetCount, 3);+ assert.deepEqual(metadata.targets[0].positionMaxima, [1, 2, 0]);+});++test('one static metadata object accepts independent retained poses and validates without changing their weights', () => {+ const geometry = triangle();+ const first = createMorphPose(2);+ const second = createMorphPose(2);+ const weights = second.weights;+ const metadata = validateMorphGeometry(geometry, first);+ second.weights.set([-1, 1.5]);+ assert.equal(validateMorphPose(second, metadata), metadata);+ assert.equal(second.weights, weights);+ assert.deepEqual(Array.from(weights), [-1, 1.5]);+ second.weights[1] = NaN;+ assert.throws(() => validateMorphPose(second, metadata), /finite Float32/);+ assert.equal(second.weights, weights);+ assert.equal(second.weights[0], -1);+ assert.ok(Number.isNaN(second.weights[1]));+ assert.ok(Object.isFrozen(metadata));+ assert.ok(Object.isFrozen(metadata.targets[0].positionMaxima));+ assert.throws(() => validateMorphPose(first, { ...metadata }), /metadata/);+});++test('cheap pose validation pins static channel identities and leaves content rescans to full preflight', () => {+ const geometry = triangle();+ const pose = createMorphPose(2);+ const metadata = validateMorphGeometry(geometry, pose);+ const original = geometry.morphTargets[0].positions;+ geometry.morphTargets[0].positions = new Float32Array(original);+ assert.throws(() => validateMorphPose(pose, metadata), /identities/);+ geometry.morphTargets[0].positions = original;+ original[0] = NaN; // Deliberate contract violation proves the frame validator does not scan vertices.+ assert.equal(validateMorphPose(pose, metadata), metadata);+ assert.throws(() => validateMorphGeometry(geometry, pose), /finite/);+ original[0] = 1;+ geometry.positions = new Float32Array(geometry.positions);+ assert.throws(() => validateMorphPose(pose, metadata), /identities/);+});++test('zero and cancelled normal blends remain valid for shader fallback, while overflow bounds reject atomically', () => {+ const geometry = triangle();+ const pose = createMorphPose(2);+ const metadata = validateMorphGeometry(geometry, pose);+ geometry.morphTargets[0].normals.set([0, 0, -1, 0, 0, -1, 0, 0, -1]);+ const cancellationMetadata = validateMorphGeometry(geometry, pose);+ pose.weights[0] = 1;+ validateMorphPose(pose, cancellationMetadata);+ pose.weights[0] = 1e20;+ const before = Array.from(pose.weights);+ assert.throws(() => validateMorphPose(pose, metadata), /normal squared/);+ assert.deepEqual(Array.from(pose.weights), before);+ pose.weights[0] = 3e38;+ assert.throws(() => validateMorphPose(pose, metadata), /Float32 position or normal/);+ pose.weights[0] = Infinity;+ assert.throws(() => validateMorphPose(pose, metadata), /finite/);+});++test('Float32 accumulation guards aggregate overflow even when every target product is finite', () => {+ const geometry = triangle();+ geometry.morphTargets = [+ { positions: new Float32Array(9).fill(2e38) },+ { positions: new Float32Array(9).fill(-2e38) },+ ];+ const pose = createMorphPose(2);+ const metadata = validateMorphGeometry(geometry, pose);+ pose.weights.fill(1);+ assert.throws(() => validateMorphPose(pose, metadata), /Float32 position/);+});++test('malformed channels, poses, target counts and unsafe base normals reject before packing', () => {+ for (const count of [0, 65, 1.5, NaN, Infinity]) assert.throws(() => createMorphPose(count), /count/);+ assert.equal(MAX_MORPH_TARGETS, 64);+ assert.equal(createMorphPose(64).weights.length, 64);+ assert.equal(validateMorphGeometry({}, undefined), undefined);+ assert.throws(() => validateMorphGeometry(triangle(), null), /pose/);+ for (const targets of [[], new Array(65).fill({}), [{}], [{ position: new Float32Array(9) }], [null]]) {+ assert.throws(() => validateMorphGeometry({ ...triangle(), morphTargets: targets }, createMorphPose(1)));+ }+ for (const values of [new Float32Array(8), new Float64Array(9), new Array(9).fill(0), new Float32Array(9).fill(Infinity)]) {+ const geometry = triangle();+ geometry.morphTargets[0].positions = values;+ assert.throws(() => validateMorphGeometry(geometry, createMorphPose(2)), /Float32/);+ assert.throws(() => packMorphTargets(geometry, { width: 4, height: 3 }), /Float32/);+ }+ for (const normals of [new Float32Array(9), new Float32Array(9).fill(1e-30), new Float32Array(9).fill(1e-20), new Float32Array(9).fill(1e20)]) {+ assert.throws(() => validateMorphGeometry({ ...triangle(), normals }, createMorphPose(2)), /squared length/);+ }+ const geometry = triangle();+ const metadata = validateMorphGeometry(geometry, createMorphPose(2));+ for (const weights of [new Float64Array(2), [0, 0], new Float32Array(1)]) {+ assert.throws(() => validateMorphPose({ weights }, metadata), /Float32 weight/);+ }+});++test('all 64 targets pack within explicit texture capacity and invalid layouts fail before allocation', () => {+ const geometry = triangle();+ geometry.morphTargets = Array.from({ length: 64 }, () => ({ positions: new Float32Array(9) }));+ const metadata = validateMorphGeometry(geometry, createMorphPose(64));+ const layout = skinTextureLayout(metadata.texelCount, 32, 2);+ assert.equal(packMorphTargets(geometry, layout).byteLength, layout.bytes);+ assert.throws(() => skinTextureLayout(metadata.texelCount, 16, 2), /MAX_TEXTURE_SIZE/);+ for (const layout of [null, {}, { width: 3, height: 128 }, { width: 2, height: 1 }, { width: 32, height: 12, bytes: 1 }, { width: 2 ** 30, height: 2 ** 30 }]) {+ assert.throws(() => packMorphTargets(geometry, layout), /layout/);+ }+});