Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Import relative GLB morph animation with stable scene mapping

Nguyen Xuan An5eed3c2c6348
diff --git a/.gitignore b/.gitignore
index 62b8a0c8..617a546e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,6 +7,10 @@ public/release.json
public/changelog.md
public/guide.md
public/gltf.md
+public/gltf-morph.md
+public/morph-targets.md
+public/skinning.md
+public/physics.md
artifacts/
.env
.env.*
diff --git a/README.md b/README.md
index 3baec601..968a11c5 100644
--- a/README.md
+++ b/README.md
@@ -156,17 +156,22 @@ renderer.render({ eye: [4, 3, 7], target: [0, 1.5, 0], assemblyAmount: 0.5 });
The core exports animation helpers, camera views and effect presets. `renderer.updateParts(parts)` uploads changes without replacing geometry buffers.
The current source adds [camera paths](docs/camera-path.md) with cubic moves, target tracking, roll and focal-length conversion.
+
It also adds [local lighting](docs/lighting.md) with eight point lights and separate key, fill and ambient controls. These controls remain source-only until the next package release.
The source also adds [depth-clipped volume fog](docs/volumetric.md) with directional scattering, shadow occlusion and deterministic density drift. It requires an opaque HDR renderer with resolved depth enabled.
These camera helpers are not included in the published `0.3.3` package yet.
The current source also adds [GPU skinning](docs/skinning.md) and skeletal GLB import, with four influences per vertex.
-The optional [physics addon](docs/physics.md) records Rapier contacts, articulated joints, hinge and slider limits, and force-bounded position or velocity motors into a timeline for repeatable film seeks.
-It requires the separate `@dimforge/[email protected]` dependency; the core does not import or bundle that solver.
+
+The optional [physics addon](docs/physics.md) records Rapier contacts, articulated joints, hinge and slider limits, and bounded motors into a timeline for repeatable film seeks.
+It 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 source [glTF morph bridge](docs/gltf-morph.md) preserves relative targets, independent instance weights and linear, step or cubic weight animations.
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.
Skinning, morph targets, transparent materials, compressed assets and ray tracing remain outside this release.
diff --git a/docs/capability-audit.md b/docs/capability-audit.md
index 96679306..0efc11da 100644
--- a/docs/capability-audit.md
+++ b/docs/capability-audit.md
@@ -21,10 +21,10 @@ The Blender references describe authoring capabilities. Their interpolation and
| Modeling | Base primitives, lathe, hole extrusion with bevels, and curve tubes integrated in source | Mesh editing, subdivision, modifiers, package release | Edited models retain topology, normals, UVs, and export behavior |
| Animation curves | Linear, step, smooth and Hermite tangent interpolation in source | Curve editor; package release verification | Known curve samples, quaternion normalization, and continuous velocity checks |
| Animation composition | Weighted clips and absolute-time crossfades integrated in source | Additive motion, layer masks, events, package verification | Walking and gestures blend without pose discontinuities |
-| Character deformation | Rigid joints, GPU skinning and skeletal GLB animation integrated in source | Morph targets, IK, retargeting, facial assets, package release | Animated imported character, expressions, and joint contact tests |
+| Character deformation | Rigid joints, GPU skinning, relative position/normal morphs and skeletal GLB animation integrated in source | IK, retargeting, recognizable facial assets, package release | Animated imported character, expressions, and joint contact tests |
| Camera authoring | Absolute-time paths, target tracking, roll, focal-length conversion and aspect-aware film subject framing integrated in source | Focus control, editing, automatic animated bounds, package release | Reviewed moving shot previews across aspect ratios |
| Film authoring | Scene-specific shot list and player | Shared timeline, shot editing, transitions, audio cues | Edited timeline seeks and exports deterministically |
-| Asset import | Opaque glTF meshes, five material maps, rigid and skeletal animation integrated in source | Morphs, transparency, compression, streaming, package release | Blender fixtures preserve geometry, materials, and animation |
+| Asset import | Opaque glTF meshes, five material maps, rigid, skeletal and morph weight animation integrated in source | Tangent morphs, generated morph normals, transparency, compression, streaming, package release | Blender fixtures preserve geometry, materials, and animation |
| Materials | Factors and five PBR texture channels integrated in source | Layered materials, advanced extensions, authored tangents, package verification | Reference material scenes and texture budget checks |
| Lighting | Directional shadows, configurable key/fill/ambient strength and eight local point lights integrated in source | Local shadows, spot/area lights, HDR environments, baked lighting, reflection probes; package release | Reference lighting scenes, stable shadows, and measured render cost |
| Image rendering | HDR, bloom, grading, MSAA, FXAA | Depth of field, motion blur, temporal sampling, render passes | Reviewed stills and moving previews with measured artifacts |
@@ -104,7 +104,8 @@ Run `node scripts/benchmark-shadows.mjs 1d4f4d0` to compare the previous shader
The native RTX 3060 check used the same portrait scene at 1280 × 720, HDR and four MSAA samples.
After ten warmup draws, forty GPU timer queries reported medians of `0.811 ms` before and `0.838 ms` after.
Estimated render allocation remained `88,630,276` bytes. Both draws reported WebGL error zero.
-The increase is about `0.027 ms` in this fixed scene; it is not a general performance result or an animation benchmark.
+
+The increase is about `0.027 ms` in this fixed scene. It is not a general performance result or an animation benchmark.
SwiftShader also rendered the updated shader without a WebGL error.
## Trailer acceptance requirements
@@ -112,8 +113,12 @@ SwiftShader also rendered the updated shader without a WebGL error.
The current trailer does not meet the requested visual quality.
The current source replaces the scientist's unlit silhouette with lit facial features, shared head attachments and shaped headwear.
The rendered close-up still looks like a stylized mannequin with insufficient facial likeness.
-The next source build narrows the temples and jaw, defines continuous nose and cheek surfaces, adds subtle vertex-color skin variation and replaces box-shaped lapels and collars with shared extruded contours. These changes remain stylized and do not establish recognizable facial likeness.
-The current source frames portrait shots by output aspect and retains the face and headwear in inspected 540 × 960 renders. Wide cameras retain their authored framing. The subject bounds are authored for these shots; automatic animated-subject framing remains unfinished.
+The source build narrows the temples and jaw, defines continuous nose and cheek surfaces, and adds subtle vertex-color skin variation.
+Shared extruded contours replace box-shaped lapels and collars.
+These changes remain stylized and do not establish recognizable facial likeness.
+
+The current source frames portrait shots by output aspect and retains the face and headwear in inspected 540 × 960 renders.
+Wide cameras retain their authored framing. The subject bounds are authored for these shots. Automatic animated-subject framing remains unfinished.
This source change has not been deployed or published to npm.
Rigid joint animation and GPU skinning provide motion tools, but do not solve character modeling or material quality by themselves.
@@ -122,11 +127,13 @@ Visible shafts, smoke, dust, explosion detail and lighting continuity still requ
The current source provides an optional Rapier addon for rigid-body contacts and articulated spherical, revolute and fixed joints.
A native render fixture records twelve bodies and ten joints, then reproduces the same pose and pixels after a backward seek.
-Its 241-frame timeline uses exactly `80,976` bytes; solver allocation is estimated separately and shared WASM capacity remains resident.
+Its 241-frame timeline uses exactly `80,976` bytes. Solver allocation is estimated separately and shared WASM capacity remains resident.
The technical ragdoll fixture does not establish convincing humanoid motion.
+
The opening apparatus shot now integrates an offline recording of five colliding pendulums through retained animation tracks.
Fresh solver replay matches every captured pose. Removing contacts prevents the initially stationary end ball from moving.
This provides physical action in a trailer shot, while actor contact and humanoid ragdolls remain unfinished.
+
Revolute and prismatic limits, position and velocity motors, and scheduled motor changes are integrated in source. Bone binding and off-thread baking remain unfinished.
The requested final state includes integrated physical interactions with deterministic playback or recorded simulation for arbitrary film seeks.
Simple sine motion does not satisfy the physics requirement.
diff --git a/docs/gltf-morph.md b/docs/gltf-morph.md
new file mode 100644
index 00000000..2941c847
--- /dev/null
+++ b/docs/gltf-morph.md
@@ -0,0 +1,128 @@
+# glTF morph import and animation
+
+`parseGltf` imports relative `POSITION` and `NORMAL` morph targets into existing renderer parts.
+The bridge uses the installed Three.js `GLTFLoader` and `AnimationMixer` for decoding and interpolation.
+Each imported part exposes a retained `part.morph.weights` Float32 array.
+This feature is available in the source checkout and next library build, but not in the published `0.3.3` package.
+The source renderer applies the imported targets on the GPU before skeletal deformation.
+
+```js
+import { parseGltf } from '../src/gltf.js';
+
+const asset = await parseGltf(glbBytes, { maxBytes: 32 * 1024 * 1024 });
+const morphParts = asset.parts.filter(part => part.morph);
+const weights = morphParts[0].morph.weights;
+asset.applyAnimation(1, 0);
+asset.applyAnimation(0.25, 0); // Sampling order does not change the resulting pose.
+console.assert(weights === morphParts[0].morph.weights);
+asset.dispose();
+```
+
+## Imported data
+
+Morph primitives contain between one and 64 targets, with matching target counts across their mesh.
+Each target accepts `POSITION`, `NORMAL`, or both.
+Channels require unnormalized float `VEC3` accessors matching the base vertex count.
+Position deltas require finite ordered `min` and `max` bounds.
+A target channel also requires its corresponding base attribute.
+Unsupported semantics, including `TANGENT`, fail explicitly before resource decoding.
+
+Morph primitives require authored base normals.
+The bridge rejects missing base normals instead of silently preserving normals when a target requires new flat normals.
+Per-target flat normal generation remains unsupported.
+
+The converted geometry stores relative Float32 deltas in `geometry.morphTargets`.
+Missing target channels remain absent and contribute zero.
+The converter follows the declared channels because the maintained loader fills some missing channels with base attributes.
+Copying those loader placeholders as relative deltas changes the deformation incorrectly.
+
+Defaults follow `node.weights`, then `mesh.weights`, then zeros.
+Default arrays require one finite Float32 value per target.
+Signed weights and values above one remain valid when numerical bounds permit them.
+Independent mesh instances share converted geometry but receive independent morph poses.
+Their weight buffers retain their identity during animation.
+
+The bridge captures original primitive declarations before the loader reduces scene associations.
+It resolves declared scene roots and their dependencies, without eagerly decoding unrelated nodes.
+Scene clones retain the correct channel declarations even when an asset contains several scenes or primitives.
+
+## Weight channels
+
+Animation outputs for `weights` use scalar streams grouped by target count.
+The bridge supports `LINEAR`, `STEP`, and `CUBICSPLINE` through the maintained loader.
+Cubic streams contain incoming tangents, values and outgoing tangents for each keyframe.
+The loader evaluates those tangents with the interval duration.
+
+Document preflight validates every animation channel, including clips that the caller never selects.
+Checks cover node references, duplicate targets, sampler references, interpolation, accessor shapes and output counts.
+Decoded keyframe times must be finite, nonnegative and strictly increasing.
+Decoded outputs must remain finite, and rotation values must represent unit quaternions within quantization tolerance.
+Normalized signed or unsigned byte and short weights also decode through the loader.
+
+`applyAnimation(time, clipIndex)` retains its existing absolute-time interface.
+Finite times clamp to the selected clip's duration.
+Switching clips restores properties that the new clip does not animate through the mixer's action lifecycle.
+Channels without a target node remain ignored, as the glTF specification permits.
+
+## Atomic publication
+
+The mixer samples private decoded nodes first.
+The bridge then validates all node world transforms after Float32 conversion.
+Mesh transforms must preserve their winding, while every node transform must remain finite and nonsingular.
+Skin palettes, morph weights and matrices each use retained pending buffers.
+Morph bounds also include the pending world transform and pending skin palette.
+
+No public matrix, palette or morph weight changes until every pending value passes validation.
+An unsafe sample throws and retains the last successful public pose.
+A later valid seek can still reproduce its previous successful result.
+Replacing public matrix, skin palette or morph pose buffer identities fails before publication.
+
+Target deltas and base geometry remain static after upload.
+The retained metadata validates identities without scanning every vertex during each sample.
+In-place changes to static target contents require new geometry and a new import.
+The returned Three.js animation clips also remain authored data after import.
+
+## Resource limits
+
+Preflight includes one base vertex plus one vertex per target in `maxVertices` accounting.
+It reserves two Float32 RGB channels per target vertex in the existing decoded byte budget.
+Generated base normals for non-morph geometry also reserve their decoder and converted Float32 storage.
+Per-instance decoded influences and pending and published weight buffers also contribute to that reservation.
+Decoded accessors plus these reservations must fit the existing four-times-`maxBytes` limit.
+Declared primitive instances also count against `maxParts` before the loader runs.
+
+These checks bound declared expansion before mesh decoding, including repeated references to one target accessor.
+The limits do not measure JavaScript object overhead or GPU allocation.
+The renderer still needs its own memory plan for packed morph textures and instance batches.
+
+## Design and checks
+
+Two implementation shapes were considered.
+
+| Shape | Interpolation | Geometry and state |
+| --- | --- | --- |
+| Custom decoder and weight curves | New linear, step and Hermite sampling code | Own accessor decoding and animation state. |
+| Maintained loader with staged bridge | Installed glTF interpolation and mixer | Convert declared deltas and publish retained pending poses. |
+
+The selected bridge reuses the maintained interpolation instead of creating another curve implementation.
+Its pending publication extends the existing skin pipeline to cover transforms and morphs together.
+The converter preserves relative deltas and independent instance weights.
+
+Embedded GLB and glTF tests cover missing channels, defaults, independent instances, signed weights and all three interpolation modes.
+Additional checks cover 64 targets, malformed channels, pre-decode budgets, skin composition, world overflow and failed-sample recovery.
+Scene regressions cover both selected scenes, shared root clones, distinct primitive channels and disposal without decoding orphan meshes.
+These tests inspect imported data and animation behavior.
+
+`node scripts/smoke-gltf-morph.mjs` runs the built decoder, film addon and renderer in native headless Chrome.
+The fixture exports the film portrait as a static GLB, appends explicit weight-animation channels, and imports it again.
+It compares open and closed eyelid pixels at an unchanged head pose, checks exact backward-seek reproduction and retains GPU resources across 60 updates.
+Wide and portrait runs report WebGL errors and the renderer memory estimate.
+The fixture verifies imported deformation, not character likeness or cinematic quality.
+The exporter still omits vertex colors and UVs, so this fixture is not a lossless asset round trip.
+
+`node scripts/smoke-gltf-skin-morph.mjs` imports a GLB containing both bone and weight channels through the built package entry points.
+It isolates morph pixels at a fixed skin pose, verifies exact reverse seeks, retains all three deformation textures and checks disposal.
+The 640 by 480 fixture reports a renderer allocation estimate of 33,367,220 bytes with four MSAA samples and no WebGL errors.
+This estimate excludes browser and driver overhead.
+
+The data semantics follow the [Khronos glTF 2.0 morph target and animation specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html).
diff --git a/docs/gltf.md b/docs/gltf.md
index d7242f7d..42701cd3 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -103,8 +103,10 @@ renderer.render(camera);
Translation, rotation, and scale tracks are supported.
The importer rejects animation poses that become singular or change triangle winding.
+
The current source supports four-influence [GPU skinning](skinning.md). The published `0.3.3` package still supports rigid animation only.
-Morph targets remain unsupported.
+The current source also supports relative POSITION/NORMAL morph targets and weight animations. See [morph import](gltf-morph.md).
+Morph primitives require authored base normals. TANGENT targets and per-target flat normal generation remain unsupported.
The caller owns the Renderer67 instance.
`asset.dispose()` releases importer textures, image bitmaps, parser resources, and temporary object URLs.
diff --git a/docs/morph-targets.md b/docs/morph-targets.md
index e1a6a183..0bc6e37b 100644
--- a/docs/morph-targets.md
+++ b/docs/morph-targets.md
@@ -2,7 +2,7 @@
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.
+This source feature is not yet in the published npm release. The source [glTF bridge](gltf-morph.md) imports relative targets and weight animations.
The core module exports `createMorphPose` and `MAX_MORPH_TARGETS` without adding a dependency.
Each morph target contains mesh-local changes from the base geometry.
@@ -87,7 +87,7 @@ These bounds deliberately ignore cancellation and maxima occurring at different
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.
+The palette bound covers four normalized Float32 influences and can 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`.
@@ -118,6 +118,7 @@ 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.
@@ -130,7 +131,9 @@ Visual quality and frame performance require separate scene measurements.
Repeated instances retain shared meshes while their signed weights remain independent.
The export contains editable targets and a static pose, rather than baked vertex positions.
It does not serialize animation clips. Skinning and material textures still fail explicitly at export.
-The importer must support morph targets before opening the snapshot in 67.js.
+
+The source importer opens these snapshots. Morph import requires authored base normals and rejects tangent targets.
+The exporter still omits vertex colors and UV attributes. This is not a complete asset roundtrip.
The output follows [glTF morph target and node weight semantics](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#morph-targets).
Export tests inspect the serialized accessors and load the GLB with the independent Three.js loader.
diff --git a/package.json b/package.json
index 4cb94e74..dfe7bd25 100644
--- a/package.json
+++ b/package.json
@@ -33,7 +33,8 @@
"docs/lighting.md",
"docs/volumetric.md",
"docs/film-physics.md",
- "docs/morph-targets.md"
+ "docs/morph-targets.md",
+ "docs/gltf-morph.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
diff --git a/public/llms.txt b/public/llms.txt
index bd92df9d..5a724754 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -71,8 +71,14 @@ Report estimates separately from observed process metrics. Reduce resolution, MS
## Limits and honest claims
67.js currently uses WebGL2. It is not API-compatible with Three.js and is not a complete Blender editor.
-There is no WebGPU backend, general physics engine, mesh editor, skinning or morph-target support.
-GLB support excludes transparent and double-sided materials, compressed geometry and additional PBR maps. Unsupported features require visible errors.
+There is no WebGPU backend or complete mesh editor.
+
+The published `0.3.3` package supports rigid GLB animation. A checkout can contain newer features without a package version change.
+The current source adds GPU skinning, relative POSITION/NORMAL morphs, weight animation and an optional Rapier physics addon.
+Read `docs/skinning.md`, `docs/morph-targets.md`, `docs/gltf-morph.md` and `docs/physics.md` in the matching checkout before using these features.
+Source morphs require authored base normals. Tangent targets and per-target flat normal generation remain unsupported.
+
+GLB support excludes transparent and double-sided materials and compressed geometry. Unsupported features require visible errors.
The optional GLB decoder uses Three.js GLTFLoader. The renderer remains 67.js.
Adaptive quality, GPU timing and picking are roadmap work. Speed claims require comparable scenes, hardware, settings and measurements.
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 61b4d903..b1bcb39c 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -35,6 +35,9 @@ await copyFile(resolve(root, 'build-browser/67.module.js'), resolve(releases, me
await copyFile(resolve(root, 'CHANGELOG.md'), resolve(root, 'public/changelog.md'));
await copyFile(resolve(root, 'docs/guide.md'), resolve(root, 'public/guide.md'));
await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));
+for (const name of ['gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md']) {
+ await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
+}
let registryVersion = null;
let registryPublished = false;
diff --git a/scripts/smoke-gltf-morph.mjs b/scripts/smoke-gltf-morph.mjs
new file mode 100644
index 00000000..0aa5707d
--- /dev/null
+++ b/scripts/smoke-gltf-morph.mjs
@@ -0,0 +1,113 @@
+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 width = Number(process.argv[2] ?? 540);
+const height = Number(process.argv[3] ?? 960);
+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, height } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.route('**/gltf-morph-smoke.html', route => route.fulfill({
+ contentType: 'text/html', body: `<canvas style="width:${width}px;height:${height}px;display:block"></canvas>`,
+ }));
+ await page.goto('http://127.0.0.1:5173/gltf-morph-smoke.html');
+ const report = await page.evaluate(async () => {
+ const { Renderer67, exportGlb } = await import('/build/67.module.js');
+ const { createFilmScenes } = await import('/build/film.js');
+ const { parseGltf } = await import('/build/gltf.js');
+ const source = createFilmScenes().portrait;
+ const snapshot = exportGlb(source.parts);
+ const snapshotHeader = new DataView(snapshot);
+ const jsonLength = snapshotHeader.getUint32(12, true);
+ const gltfDocument = JSON.parse(new TextDecoder().decode(new Uint8Array(snapshot, 20, jsonLength)));
+ const binaryLength = snapshotHeader.getUint32(20 + jsonLength, true);
+ const binary = new Uint8Array(binaryLength + 40);
+ binary.set(new Uint8Array(snapshot, 28 + jsonLength, binaryLength));
+ const times = new Float32Array([0, 1, 1.12, 1.24, 2]);
+ const weights = new Float32Array([0, 0, 1, 0, 0]);
+ binary.set(new Uint8Array(times.buffer), binaryLength);
+ binary.set(new Uint8Array(weights.buffer), binaryLength + 20);
+ const inputView = gltfDocument.bufferViews.length;
+ gltfDocument.bufferViews.push({ buffer: 0, byteOffset: binaryLength, byteLength: 20 });
+ gltfDocument.bufferViews.push({ buffer: 0, byteOffset: binaryLength + 20, byteLength: 20 });
+ const input = gltfDocument.accessors.length;
+ gltfDocument.accessors.push({ bufferView: inputView, componentType: 5126, count: 5, type: 'SCALAR', min: [0], max: [2] });
+ gltfDocument.accessors.push({ bufferView: inputView + 1, componentType: 5126, count: 5, type: 'SCALAR' });
+ gltfDocument.buffers[0].byteLength = binary.length;
+ gltfDocument.animations = [{ name: 'Imported blink', samplers: [{ input, output: input + 1, interpolation: 'LINEAR' }], channels: gltfDocument.nodes.flatMap((node, index) => node.weights ? [{ sampler: 0, target: { node: index, path: 'weights' } }] : []) }];
+ const json = new TextEncoder().encode(JSON.stringify(gltfDocument));
+ const paddedJson = Math.ceil(json.length / 4) * 4;
+ const animated = new ArrayBuffer(28 + paddedJson + binary.length);
+ const header = new DataView(animated);
+ header.setUint32(0, 0x46546c67, true);
+ header.setUint32(4, 2, true);
+ header.setUint32(8, animated.byteLength, true);
+ header.setUint32(12, paddedJson, true);
+ header.setUint32(16, 0x4e4f534a, true);
+ const bytes = new Uint8Array(animated);
+ bytes.fill(32, 20, 20 + paddedJson);
+ bytes.set(json, 20);
+ header.setUint32(20 + paddedJson, binary.length, true);
+ header.setUint32(24 + paddedJson, 0x004e4942, true);
+ bytes.set(binary, 28 + paddedJson);
+ const asset = await parseGltf(animated);
+ const canvas = document.querySelector('canvas');
+ const renderer = new Renderer67(canvas, asset.parts, {
+ world: true, ground: false, environment: source.environment, shadowBounds: source.shadowBounds,
+ samples: 2, pixelRatio: 1, hdr: true, memoryBudgetMiB: 128,
+ });
+ const morphParts = asset.parts.filter(part => part.morph);
+ const matrices = asset.parts.map(part => part.matrix);
+ const weightBuffers = morphParts.map(part => part.morph.weights);
+ const textures = [...renderer.morphTextures.values()];
+ 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) {
+ renderer.updateParts(asset.applyAnimation(time));
+ renderer.render(frame);
+ return canvas.toDataURL('image/png');
+ }
+ const open = image(0);
+ const closed = image(1.12);
+ image(2);
+ const repeated = image(1.12);
+ let retained = true;
+ for (let index = 0; index < 60; index++) {
+ image(index % 2 ? 1.12 : 0);
+ retained &&= asset.parts.every((part, partIndex) => part.matrix === matrices[partIndex]);
+ retained &&= morphParts.every((part, partIndex) => part.morph.weights === weightBuffers[partIndex]);
+ retained &&= [...renderer.morphTextures.values()].every((record, recordIndex) => record === textures[recordIndex]);
+ }
+ const memory = renderer.memoryPlan;
+ const glError = renderer.context.getError();
+ const partCount = asset.parts.length;
+ const morphCount = morphParts.length;
+ renderer.dispose();
+ asset.dispose();
+ return { open, closed, repeated, retained, memory, glError, partCount, morphCount, clipCount: gltfDocument.animations.length, snapshotBytes: animated.byteLength };
+ });
+ assert.deepEqual(errors, []);
+ assert.equal(report.glError, 0);
+ assert.equal(report.morphCount, 2);
+ assert.equal(report.clipCount, 1);
+ assert.equal(report.retained, true);
+ assert.notEqual(report.open, report.closed);
+ assert.equal(report.closed, report.repeated);
+ for (const name of ['open', 'closed']) {
+ await writeFile(`artifacts/gltf-blink-${width}x${height}-${name}.png`, Buffer.from(report[name].split(',')[1], 'base64'));
+ }
+ delete report.open;
+ delete report.closed;
+ delete report.repeated;
+ await writeFile(`artifacts/gltf-morph-${width}x${height}-gpu.json`, JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report, null, 2));
+} finally {
+ await browser.close();
+}
diff --git a/scripts/smoke-gltf-skin-morph.mjs b/scripts/smoke-gltf-skin-morph.mjs
new file mode 100644
index 00000000..8fbbbd18
--- /dev/null
+++ b/scripts/smoke-gltf-skin-morph.mjs
@@ -0,0 +1,97 @@
+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('**/skin-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/skin-morph-smoke.html');
+ const report = await page.evaluate(async () => {
+ const { Renderer67 } = await import('/build/67.module.js');
+ const { parseGltf } = await import('/build/gltf.js');
+ const { skinnedStripAsset } = await import('/tests/fixtures/skinned-strip.js');
+ const bytes = skinnedStripAsset((definition, append) => {
+ const position = append(new Float32Array([
+ -0.2, 0, 0, 0.2, 0, 0, -0.25, 0, 0, 0.25, 0, 0, -0.35, 0, 0, 0.35, 0, 0,
+ ]), 'VEC3');
+ definition.accessors[position].min = [-0.35, 0, 0];
+ definition.accessors[position].max = [0.35, 0, 0];
+ const normal = append(new Float32Array(Array.from({ length: 6 }, () => [0.3, 0, -0.05]).flat()), 'VEC3');
+ definition.meshes[0].primitives[0].targets = [{ POSITION: position, NORMAL: normal }];
+ definition.meshes[0].weights = [0];
+ const input = append(new Float32Array([0, 2]), 'SCALAR');
+ const output = append(new Float32Array([0, 1]), 'SCALAR');
+ definition.animations[0].samplers.push({ input, output, interpolation: 'LINEAR' });
+ definition.animations[0].channels.push({ sampler: 1, target: { node: 1, path: 'weights' } });
+ });
+ const asset = await parseGltf(bytes);
+ const part = asset.parts[0];
+ const canvas = document.querySelector('canvas');
+ const renderer = new Renderer67(canvas, asset.parts, { samples: 4, pixelRatio: 1, memoryBudgetMiB: 96 });
+ const frame = { eye: [1, 3, 6], target: [1, 3, 0], fov: 40, time: 0, effects: { grain: 0 } };
+ const palette = part.skin.jointMatrices;
+ const weights = part.morph.weights;
+ const skinRecord = renderer.skinTextures.get(part.skin);
+ const influenceRecord = renderer.influenceTextures.get(part.geometry);
+ const morphRecord = renderer.morphTextures.get(part.geometry);
+ function pixels() {
+ renderer.updateParts(asset.parts);
+ renderer.render(frame);
+ return canvas.toDataURL('image/png');
+ }
+ function sample(time) {
+ asset.applyAnimation(time, 0);
+ return pixels();
+ }
+ const straight = sample(0);
+ const combined = sample(2);
+ const finalPalette = Array.from(palette);
+ const finalWeights = Array.from(weights);
+ weights[0] = 0;
+ const skinOnly = pixels();
+ sample(0.5);
+ const repeated = sample(2);
+ let retained = true;
+ for (let index = 0; index < 60; index++) {
+ sample(index % 3);
+ retained &&= part.skin.jointMatrices === palette && part.morph.weights === weights;
+ retained &&= renderer.skinTextures.get(part.skin) === skinRecord;
+ retained &&= renderer.influenceTextures.get(part.geometry) === influenceRecord;
+ retained &&= renderer.morphTextures.get(part.geometry) === morphRecord;
+ }
+ const memory = renderer.memoryPlan;
+ const context = renderer.context;
+ const glError = context.getError();
+ const textures = [skinRecord.texture, influenceRecord.texture, morphRecord.texture];
+ renderer.dispose();
+ const released = textures.every(texture => !context.isTexture(texture));
+ asset.dispose();
+ return { straight, combined, skinOnly, repeated, finalPalette, finalWeights, retained, released, glError, memory };
+ });
+ assert.deepEqual(errors, []);
+ assert.equal(report.glError, 0);
+ assert.equal(report.retained, true);
+ assert.equal(report.released, true);
+ assert.deepEqual(report.finalWeights, [1]);
+ assert.notEqual(report.straight, report.combined);
+ assert.notEqual(report.skinOnly, report.combined, 'Imported morph must change pixels while the imported skin pose stays fixed.');
+ assert.equal(report.combined, report.repeated);
+ await writeFile('artifacts/gltf-skin-morph.png', Buffer.from(report.combined.split(',')[1], 'base64'));
+ for (const name of ['straight', 'combined', 'skinOnly', 'repeated']) delete report[name];
+ await writeFile('artifacts/gltf-skin-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.mjs
index b6a1a32a..fef8ec96 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -51,6 +51,11 @@ const morphHeader = new DataView(morphSnapshot);
const morphDocument = JSON.parse(new TextDecoder().decode(new Uint8Array(morphSnapshot, 20, morphHeader.getUint32(12, true))));
assert.deepEqual(morphDocument.nodes[0].weights, [-0.5]);
assert.ok(Number.isInteger(morphDocument.meshes[0].primitives[0].targets[0].POSITION));
+const importedMorph = await parseGltf(morphSnapshot);
+assert.equal(importedMorph.parts.length, 1);
+assert.deepEqual(Array.from(importedMorph.parts[0].morph.weights), [-0.5]);
+assert.deepEqual(importedMorph.parts[0].geometry.morphTargets[0].positions, morphGeometry.morphTargets[0].positions);
+importedMorph.dispose();
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/src/gltf.js b/src/gltf.js
index 0bfd3fe2..8e7d2631 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -1,12 +1,13 @@
-import { AnimationMixer, LoadingManager, LoopOnce } from 'three';
+import { AnimationMixer, LoadingManager, LoopOnce, Matrix4 } from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { textureDescriptorInfo } from './renderer.js';
import { createSkinPose, updateSkinPose, validateSkinGeometry, validateSkinPose } from './skinning.js';
+import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorphPose, validateMorphTransform } from './morph.js';
export const GLTF_CAPABILITIES = Object.freeze({
formats: ['glb', 'gltf'],
- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],
- unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'morph targets', 'vertex alpha below one', 'alpha blending or masking', 'double-sided materials', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],
+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'linear RGB vertex colors', 'metallic roughness factors', 'emissive factors', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength'],
+ unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'TANGENT morph targets', 'morph targets without authored base normals', 'vertex alpha below one', 'alpha blending or masking', 'double-sided materials', 'texture transforms', 'DRACO', 'KTX2', 'GPU instancing'],
});
const DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
@@ -68,6 +69,49 @@ function documentFrom(data, maxBytes) {
return JSON.parse(new TextDecoder().decode(new Uint8Array(data, 20, jsonLength)));
}
+function morphCount(mesh) {
+ return mesh?.primitives?.[0]?.targets?.length ?? 0;
+}
+
+function validateDefaultWeights(weights, count) {
+ if (weights === undefined) return;
+ if (!count || !Array.isArray(weights) || weights.length !== count || weights.some(value => typeof value !== 'number' || !Number.isFinite(Math.fround(value)))) {
+ throw new Error('Morph default weights require one finite Float32 value per target.');
+ }
+}
+
+function validateAnimationChannels(document) {
+ for (const animation of document.animations ?? []) {
+ const targets = new Set();
+ for (const channel of animation.channels ?? []) {
+ const path = channel.target?.path;
+ const nodeIndex = channel.target?.node;
+ const node = document.nodes?.[nodeIndex];
+ if (!['translation', 'rotation', 'scale', 'weights'].includes(path)) throw new Error('Only node translation, rotation, scale and weights animations are supported.');
+ if (nodeIndex === undefined) continue;
+ if (!Number.isInteger(nodeIndex) || !node) throw new Error('Animation channel requires a valid target node.');
+ const targetKey = `${nodeIndex}:${path}`;
+ if (targets.has(targetKey)) throw new Error('Animation channels must have distinct node and path targets.');
+ targets.add(targetKey);
+ const sampler = animation.samplers?.[channel.sampler];
+ if (!Number.isInteger(channel.sampler) || !sampler) throw new Error('Invalid animation sampler index.');
+ const interpolation = sampler.interpolation ?? 'LINEAR';
+ if (!['LINEAR', 'STEP', 'CUBICSPLINE'].includes(interpolation)) throw new Error('Unsupported animation interpolation.');
+ const input = document.accessors?.[sampler.input];
+ const output = document.accessors?.[sampler.output];
+ if (!Number.isInteger(sampler.input) || !input || input.type !== 'SCALAR' || input.componentType !== 5126 || input.normalized
+ || !Number.isSafeInteger(input.count) || input.count < (interpolation === 'CUBICSPLINE' ? 2 : 1)) throw new Error('Animation inputs require float SCALAR keyframe times.');
+ const count = path === 'weights' ? morphCount(document.meshes?.[node.mesh]) : 1;
+ if (!count) throw new Error('Weights animation requires a node with morph targets.');
+ const shape = path === 'weights' ? 'SCALAR' : path === 'rotation' ? 'VEC4' : 'VEC3';
+ const outputCount = input.count * count * (interpolation === 'CUBICSPLINE' ? 3 : 1);
+ const integerOutput = ['rotation', 'weights'].includes(path) && [5120, 5121, 5122, 5123].includes(output?.componentType) && output.normalized;
+ if (!Number.isInteger(sampler.output) || !output || output.type !== shape || output.count !== outputCount
+ || !(output.componentType === 5126 && !output.normalized || integerOutput)) throw new Error('Animation output shape, count or component type does not match its target.');
+ }
+ }
+}
+
function validateDocument(document, limits) {
if (document.asset?.version !== '2.0') throw new Error('Only glTF 2.0 assets are supported.');
const pending = [document];
@@ -90,15 +134,34 @@ function validateDocument(document, limits) {
if (declaredBytes > limits.maxBytes) throw new Error('glTF buffers exceed maxBytes.');
let vertices = 0;
let indices = 0;
+ let morphBytes = 0;
for (const mesh of document.meshes ?? []) {
+ const targetCount = morphCount(mesh);
+ if (targetCount > MAX_MORPH_TARGETS) throw new Error('Morph target count exceeds 64.');
+ validateDefaultWeights(mesh.weights, targetCount);
for (const primitive of mesh.primitives ?? []) {
if ((primitive.mode ?? 4) !== 4) throw new Error('Only glTF TRIANGLES primitives are supported.');
- if (primitive.targets?.length) throw new Error('Morph targets are unsupported.');
const position = document.accessors?.[primitive.attributes?.POSITION];
if (!position || position.type !== 'VEC3' || !Number.isSafeInteger(position.count) || position.count < 3) {
throw new Error('Each mesh primitive requires a valid POSITION accessor.');
}
- vertices += position.count;
+ if (primitive.targets !== undefined && (!Array.isArray(primitive.targets) || !primitive.targets.length || primitive.targets.length !== targetCount)) throw new Error('Morph target counts must match across all mesh primitives.');
+ if ((primitive.targets?.length ?? 0) !== targetCount) throw new Error('Morph target counts must match across all mesh primitives.');
+ if (targetCount && primitive.attributes?.NORMAL === undefined) throw new Error('Morph targets require authored base NORMAL. Per-target flat normal generation is unsupported.');
+ for (const target of primitive.targets ?? []) {
+ if (!target || typeof target !== 'object' || Array.isArray(target) || !Object.keys(target).length) throw new Error('Morph targets require POSITION or NORMAL channels.');
+ for (const [semantic, accessorIndex] of Object.entries(target)) {
+ if (!['POSITION', 'NORMAL'].includes(semantic)) throw new Error(`Unsupported morph target semantic: ${semantic}.`);
+ const accessor = document.accessors?.[accessorIndex];
+ if (primitive.attributes?.[semantic] === undefined) throw new Error('Morph target channels require corresponding base attributes.');
+ if (!Number.isInteger(accessorIndex) || !accessor || accessor.type !== 'VEC3' || accessor.componentType !== 5126 || accessor.normalized || accessor.count !== position.count) throw new Error('Morph target channels require matching float VEC3 accessors.');
+ if (semantic === 'POSITION' && (!Array.isArray(accessor.min) || !Array.isArray(accessor.max) || accessor.min.length !== 3 || accessor.max.length !== 3
+ || accessor.min.some((value, axis) => typeof value !== 'number' || !Number.isFinite(Math.fround(value)) || typeof accessor.max[axis] !== 'number' || !Number.isFinite(Math.fround(accessor.max[axis])) || value > accessor.max[axis]))) throw new Error('Morph POSITION requires finite ordered min/max bounds.');
+ }
+ }
+ vertices += position.count * (1 + targetCount);
+ morphBytes += position.count * targetCount * 24;
+ if (primitive.attributes?.NORMAL === undefined) morphBytes += position.count * 24;
if (Object.keys(primitive.attributes ?? {}).some(name => /^(JOINTS|WEIGHTS)_/.test(name) && !['JOINTS_0', 'WEIGHTS_0'].includes(name))) throw new Error('Only four JOINTS_0/WEIGHTS_0 skin influences are supported.');
const joints = document.accessors?.[primitive.attributes?.JOINTS_0];
const weights = document.accessors?.[primitive.attributes?.WEIGHTS_0];
@@ -147,7 +210,14 @@ function validateDocument(document, limits) {
}
}
let poseJointCount = 0;
+ let declaredParts = 0;
for (const node of document.nodes ?? []) {
+ const mesh = document.meshes?.[node.mesh];
+ if (node.mesh !== undefined && (!Number.isInteger(node.mesh) || !mesh)) throw new Error('Invalid mesh node index.');
+ declaredParts += mesh?.primitives?.length ?? 0;
+ if (declaredParts > limits.maxParts) throw new Error('glTF primitive instances exceed maxParts.');
+ validateDefaultWeights(node.weights, morphCount(mesh));
+ morphBytes += morphCount(mesh) * (mesh?.primitives?.length ?? 0) * 16;
if (node.skin !== undefined) {
if (!Number.isInteger(node.skin) || !document.skins?.[node.skin] || !document.meshes?.[node.mesh]) throw new Error('Invalid skinned mesh or skin index.');
for (const primitive of document.meshes[node.mesh].primitives ?? []) {
@@ -159,11 +229,7 @@ function validateDocument(document, limits) {
if (node.extensions && Object.keys(node.extensions).length) throw new Error('Node extensions are unsupported.');
}
validateHierarchy(document.nodes ?? []);
- for (const animation of document.animations ?? []) {
- for (const channel of animation.channels ?? []) {
- if (!['translation', 'rotation', 'scale'].includes(channel.target?.path)) throw new Error('Only node translation, rotation and scale animations are supported.');
- }
- }
+ validateAnimationChannels(document);
for (const material of document.materials ?? []) {
const pbr = material.pbrMetallicRoughness ?? {};
const factors = [pbr.baseColorFactor ?? [1, 1, 1, 1], material.emissiveFactor ?? [0, 0, 0]];
@@ -198,7 +264,7 @@ function validateDocument(document, limits) {
if (material && MATERIAL_TEXTURES.some(([, field]) => materialTexture(material, field)) && primitive.attributes?.TEXCOORD_0 === undefined) throw new Error('Material textures require TEXCOORD_0.');
}
}
- let decodedBytes = 0;
+ let decodedBytes = morphBytes;
const components = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16 };
for (const accessor of document.accessors ?? []) {
if (!Number.isSafeInteger(accessor.count) || accessor.count < 0 || accessor.count > limits.maxVertices * 12) {
@@ -389,7 +455,7 @@ function copyAttribute(attribute, size) {
return result;
}
-function convertGeometry(source, mirrored) {
+function convertGeometry(source, mirrored, primitive) {
const position = source.getAttribute('position');
if (!source.getAttribute('normal')) source.computeVertexNormals();
if (source.getAttribute('normal').count !== position.count) throw new Error('NORMAL and POSITION counts must match.');
@@ -422,6 +488,15 @@ function convertGeometry(source, mirrored) {
const skinWeights = source.getAttribute('skinWeight');
if (skinIndices) geometry.skinIndices = new Uint16Array(copyAttribute(skinIndices, 4));
if (skinWeights) geometry.skinWeights = copyAttribute(skinWeights, 4);
+ if (primitive.targets?.length) {
+ if (!source.morphTargetsRelative) throw new Error('Decoded morph targets must contain relative deltas.');
+ geometry.morphTargets = primitive.targets.map((target, index) => {
+ const channels = {};
+ if (target.POSITION !== undefined) channels.positions = copyAttribute(source.morphAttributes.position[index], 3);
+ if (target.NORMAL !== undefined) channels.normals = copyAttribute(source.morphAttributes.normal[index], 3);
+ return channels;
+ });
+ }
return geometry;
}
@@ -437,11 +512,12 @@ function makeSkinBinding(node) {
return { name: bone.name, parent: node.skeleton.bones.indexOf(bone.parent) };
});
const skin = Object.assign(pose, { joints, inverseBindMatrices, jointWorldMatrices, bindMatrix: new Float32Array(node.bindMatrix.elements) });
- return { node, skin, pendingPose, pendingWorld };
+ return { node, skin, pendingPose, pendingWorld, palette: skin.jointMatrices, jointWorld: skin.jointWorldMatrices };
}
function prepareSkinBinding(binding, geometry) {
const { node, skin, pendingPose, pendingWorld } = binding;
+ if (skin.jointMatrices !== binding.palette || skin.jointWorldMatrices !== binding.jointWorld || binding.palette.length !== pendingPose.jointMatrices.length || binding.jointWorld.length !== pendingWorld.length) throw new Error('Imported skin palette identities must remain unchanged.');
for (let joint = 0; joint < node.skeleton.bones.length; joint++) pendingWorld.set(node.skeleton.bones[joint].matrixWorld.elements, joint * 16);
updateSkinPose(pendingPose, pendingWorld, skin.inverseBindMatrices, node.matrixWorld.elements, skin.bindMatrix);
validateSkinPose(pendingPose, geometry, node.matrixWorld.elements);
@@ -452,10 +528,77 @@ function commitSkinBinding(binding) {
binding.skin.jointWorldMatrices.set(binding.pendingWorld);
}
-function skinPreflightPlugin(parser, document) {
+function makeMorphBinding(node, geometry, metadataCache) {
+ const pose = createMorphPose(geometry.morphTargets.length);
+ pose.weights.set(node.morphTargetInfluences);
+ const pendingPose = createMorphPose(pose.weights.length);
+ let metadata = metadataCache.get(geometry);
+ if (metadata) validateMorphPose(pose, metadata);
+ else {
+ metadata = validateMorphGeometry(geometry, pose);
+ metadataCache.set(geometry, metadata);
+ }
+ return { node, pose, weights: pose.weights, pendingPose, metadata };
+}
+
+function prepareMorphBinding(binding) {
+ if (binding.pose.weights !== binding.weights || binding.weights.length !== binding.metadata.targetCount) throw new Error('Imported morph weight identity must remain unchanged.');
+ const influences = binding.node.morphTargetInfluences;
+ if (influences.length !== binding.weights.length) throw new Error('Decoded morph weight count changed.');
+ binding.pendingPose.weights.set(influences);
+ validateMorphPose(binding.pendingPose, binding.metadata);
+}
+
+function validateNodeTransforms(nodes, pending, transform) {
+ for (const node of nodes) {
+ pending.set(node.matrixWorld.elements);
+ for (const value of pending) if (!Number.isFinite(value)) throw new Error('Animation creates a non-finite Float32 world matrix.');
+ const determinant = transform.fromArray(pending).determinant();
+ if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-12) throw new Error('Animation creates a singular Float32 node transform.');
+ }
+}
+
+function copyPrimitiveAssociations(original, decoded, associations) {
+ const association = associations.get(original);
+ if (original.isMesh && !association) throw new Error('Decoded mesh lost its original primitive association.');
+ if (association) associations.set(decoded, association);
+ if (original.children.length !== decoded.children.length) throw new Error('Decoded scene clone changed the node hierarchy.');
+ for (let index = 0; index < original.children.length; index++) {
+ copyPrimitiveAssociations(original.children[index], decoded.children[index], associations);
+ }
+}
+
+function skinPreflightPlugin(parser, document, primitiveAssociations) {
+ let originalRoots;
return {
name: '67SkinPreflight',
async beforeRoot() {
+ for (const mesh of document.meshes ?? []) {
+ for (const primitive of mesh.primitives ?? []) {
+ for (const target of primitive.targets ?? []) {
+ for (const accessor of Object.values(target)) copyAttribute(await parser.getDependency('accessor', accessor), 3);
+ }
+ }
+ }
+ for (const animation of document.animations ?? []) {
+ for (const channel of animation.channels ?? []) {
+ if (channel.target.node === undefined) continue;
+ const sampler = animation.samplers[channel.sampler];
+ const input = copyAttribute(await parser.getDependency('accessor', sampler.input), 1);
+ for (let index = 0; index < input.length; index++) {
+ if (input[index] < 0 || index && input[index] <= input[index - 1]) throw new Error('Animation times must be nonnegative and strictly increasing.');
+ }
+ const size = channel.target.path === 'rotation' ? 4 : channel.target.path === 'weights' ? 1 : 3;
+ const output = copyAttribute(await parser.getDependency('accessor', sampler.output), size);
+ if (channel.target.path === 'rotation') {
+ const cubic = sampler.interpolation === 'CUBICSPLINE';
+ for (let offset = cubic ? 4 : 0; offset < output.length; offset += cubic ? 12 : 4) {
+ const length = Math.hypot(output[offset], output[offset + 1], output[offset + 2], output[offset + 3]);
+ if (Math.abs(length - 1) > 0.01) throw new Error('Animation rotation values require unit quaternions.');
+ }
+ }
+ }
+ }
for (const node of document.nodes ?? []) {
if (node.skin === undefined) continue;
const pose = createSkinPose(document.skins[node.skin].joints.length);
@@ -467,6 +610,26 @@ function skinPreflightPlugin(parser, document) {
validateSkinGeometry({ positions: { length: weights.count * 3 }, skinIndices: copyAttribute(joints, 4), skinWeights: copyAttribute(weights, 4) }, pose);
}
}
+ // loadScene reduces parser.associations globally, so capture before any scene loads.
+ const rootIndices = new Set();
+ for (const scene of document.scenes ?? []) {
+ for (const root of scene.nodes ?? []) rootIndices.add(root);
+ }
+ const roots = await Promise.all(Array.from(rootIndices, async index => [index, await parser.getDependency('node', index)]));
+ originalRoots = new Map(roots);
+ for (const [node, association] of parser.associations) {
+ if (node.isMesh) primitiveAssociations.set(node, Object.freeze({ ...association }));
+ }
+ },
+ afterRoot(result) {
+ for (let index = 0; index < result.scenes.length; index++) {
+ const roots = document.scenes[index].nodes ?? [];
+ const scene = result.scenes[index];
+ if (roots.length !== scene.children.length) throw new Error('Decoded scene root count changed.');
+ for (let root = 0; root < roots.length; root++) {
+ copyPrimitiveAssociations(originalRoots.get(roots[root]), scene.children[root], primitiveAssociations);
+ }
+ }
},
};
}
@@ -572,21 +735,30 @@ export async function parseGltf(data, options = {}) {
throw new Error(`Unregistered glTF resource: ${url}.`);
});
let gltf;
+ const primitiveAssociations = new WeakMap();
try {
const loader = new GLTFLoader(manager);
- loader.register(parser => skinPreflightPlugin(parser, document));
+ loader.register(parser => skinPreflightPlugin(parser, document, primitiveAssociations));
gltf = await loader.parseAsync(data, options.baseUrl ?? '');
gltf.scene.updateMatrixWorld(true);
const parts = [];
const bindings = [];
const skinBindings = [];
+ const morphBindings = [];
const geometries = new Map();
+ const morphMetadata = new Map();
const materials = new Map();
const maps = new Map();
+ const nodes = [];
+ const pendingTransform = new Matrix4();
+ const pendingNodeMatrix = new Float32Array(16);
let actualVertices = 0;
gltf.scene.traverse(node => {
+ nodes.push(node);
if (!node.isMesh) return;
- if (node.morphTargetInfluences?.length) throw new Error('Morph targets are unsupported.');
+ const association = primitiveAssociations.get(node);
+ const primitive = document.meshes?.[association?.meshes]?.primitives?.[association?.primitives];
+ if (!primitive) throw new Error('Decoded mesh requires a valid original primitive association.');
if (Array.isArray(node.material)) throw new Error('Multiple materials on one decoded primitive are unsupported.');
const materialIndex = gltf.parser.associations.get(node.material)?.materials;
for (const [field, sourceField] of MATERIAL_TEXTURES) {
@@ -599,28 +771,39 @@ export async function parseGltf(data, options = {}) {
const geometryMirrored = node.isSkinnedMesh ? false : mirrored;
const geometryKey = `${node.geometry.uuid}:${geometryMirrored}`;
if (!geometries.has(geometryKey)) {
- actualVertices += node.geometry.getAttribute('position').count;
+ actualVertices += node.geometry.getAttribute('position').count * (1 + (primitive.targets?.length ?? 0));
if (actualVertices > limits.maxVertices) throw new Error('Decoded geometry exceeds maxVertices.');
- geometries.set(geometryKey, convertGeometry(node.geometry, geometryMirrored));
+ geometries.set(geometryKey, convertGeometry(node.geometry, geometryMirrored, primitive));
}
if (!materials.has(node.material)) materials.set(node.material, convertMaterial(node.material, limits, maps, document.materials?.[materialIndex]));
const geometry = geometries.get(geometryKey);
const material = materials.get(node.material);
if (MATERIAL_TEXTURES.some(([field]) => material[field]) && !geometry.uvs) throw new Error('Material textures require TEXCOORD_0.');
const part = { name: node.name || `glTF mesh ${parts.length + 1}`, geometry, matrix: new Float32Array(node.matrixWorld.elements), material };
+ const transformBinding = { node, part, mirrored, matrix: part.matrix, pendingMatrix: new Float32Array(16) };
+ let pendingSkin;
if (node.isSkinnedMesh) {
const binding = makeSkinBinding(node);
prepareSkinBinding(binding, geometry);
commitSkinBinding(binding);
part.skin = binding.skin;
skinBindings.push({ ...binding, geometry });
+ pendingSkin = binding.pendingPose;
}
validateSkinGeometry(geometry, part.skin);
+ transformBinding.skin = part.skin;
+ if (geometry.morphTargets) {
+ const binding = makeMorphBinding(node, geometry, morphMetadata);
+ part.morph = binding.pose;
+ validateMorphTransform(binding.pose, binding.metadata, part.matrix, part.skin);
+ morphBindings.push({ ...binding, part, pendingMatrix: transformBinding.pendingMatrix, pendingSkin });
+ }
if (!Array.from(part.matrix).every(Number.isFinite)) throw new Error('Mesh world matrix must be finite.');
parts.push(part);
- bindings.push({ node, part, mirrored });
+ bindings.push(transformBinding);
if (parts.length > limits.maxParts) throw new Error('Decoded parts exceed maxParts.');
});
+ validateNodeTransforms(nodes, pendingNodeMatrix, pendingTransform);
if (!parts.length) throw new Error('glTF scene contains no supported triangle meshes.');
const mixer = new AnimationMixer(gltf.scene);
let disposed = false;
@@ -645,15 +828,27 @@ export async function parseGltf(data, options = {}) {
action.play();
mixer.setTime(Math.max(0, Math.min(time, clip.duration)));
gltf.scene.updateMatrixWorld(true);
- for (const { node, mirrored } of bindings) {
+ validateNodeTransforms(nodes, pendingNodeMatrix, pendingTransform);
+ for (const { node, part, mirrored, matrix, pendingMatrix, skin } of bindings) {
+ if (part.matrix !== matrix || matrix.length !== 16) throw new Error('Imported part matrix identity must remain unchanged.');
+ if (part.skin !== skin) throw new Error('Imported skin pose identity must remain unchanged.');
+ pendingMatrix.set(node.matrixWorld.elements);
+ for (const value of pendingMatrix) if (!Number.isFinite(value)) throw new Error('Animation creates a non-finite Float32 world matrix.');
const determinant = node.matrixWorld.determinant();
- if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-12 || (determinant < 0) !== mirrored) {
+ const roundedDeterminant = pendingTransform.fromArray(pendingMatrix).determinant();
+ if (!Number.isFinite(determinant) || !Number.isFinite(roundedDeterminant) || Math.abs(roundedDeterminant) < 1e-12 || (determinant < 0) !== mirrored || (roundedDeterminant < 0) !== mirrored) {
throw new Error('Animation creates a singular transform or changes triangle winding.');
}
}
for (const binding of skinBindings) prepareSkinBinding(binding, binding.geometry);
- for (const { node, part } of bindings) part.matrix.set(node.matrixWorld.elements);
+ for (const binding of morphBindings) {
+ if (binding.part.morph !== binding.pose) throw new Error('Imported morph pose identity must remain unchanged.');
+ prepareMorphBinding(binding);
+ validateMorphTransform(binding.pendingPose, binding.metadata, binding.pendingMatrix, binding.pendingSkin);
+ }
+ for (const { matrix, pendingMatrix } of bindings) matrix.set(pendingMatrix);
for (const binding of skinBindings) commitSkinBinding(binding);
+ for (const binding of morphBindings) binding.weights.set(binding.pendingPose.weights);
return parts;
}
return { parts, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };
diff --git a/tests/gltf-morph.test.js b/tests/gltf-morph.test.js
new file mode 100644
index 00000000..0ee0f4b5
--- /dev/null
+++ b/tests/gltf-morph.test.js
@@ -0,0 +1,341 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { parseGltf } from '../src/gltf.js';
+import { skinnedStripAsset } from './fixtures/skinned-strip.js';
+
+function morphAsset(edit = () => {}, jsonOnly = false) {
+ const chunks = [];
+ let byteLength = 0;
+ const document = {
+ asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0, 1] }],
+ nodes: [{ name: 'First', mesh: 0 }, { name: 'Second', mesh: 0, translation: [2, 0, 0] }],
+ meshes: [{ primitives: [{ attributes: {} }] }],
+ accessors: [], bufferViews: [], buffers: [{ byteLength: 0 }],
+ };
+ function append(values, type) {
+ const components = { SCALAR: 1, VEC3: 3, VEC4: 4 }[type];
+ const index = document.accessors.length;
+ chunks.push(values);
+ document.bufferViews.push({ buffer: 0, byteOffset: byteLength, byteLength: values.byteLength });
+ byteLength += Math.ceil(values.byteLength / 4) * 4;
+ document.buffers[0].byteLength = byteLength;
+ const accessor = { bufferView: index, componentType: 5126, count: values.length / components, type };
+ if (type === 'SCALAR') {
+ accessor.min = [Math.min(...values)];
+ accessor.max = [Math.max(...values)];
+ }
+ document.accessors.push(accessor);
+ return index;
+ }
+ const primitive = document.meshes[0].primitives[0];
+ primitive.attributes.POSITION = append(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), 'VEC3');
+ Object.assign(document.accessors[0], { min: [0, 0, 0], max: [1, 1, 0] });
+ primitive.attributes.NORMAL = append(new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]), 'VEC3');
+ const positions = append(new Float32Array([0, 0, 0, 0, 0, 0, 0, 1, 0]), 'VEC3');
+ Object.assign(document.accessors[positions], { min: [0, 0, 0], max: [0, 1, 0] });
+ const normals = append(new Float32Array([0, 0.2, 0, 0, 0.2, 0, 0, 0.2, 0]), 'VEC3');
+ primitive.targets = [{ POSITION: positions }, { NORMAL: normals }];
+ edit(document, append, chunks);
+ const binary = new Uint8Array(byteLength);
+ chunks.forEach((chunk, index) => binary.set(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength), document.bufferViews[index].byteOffset));
+ if (jsonOnly) {
+ document.buffers[0].uri = `data:application/octet-stream;base64,${Buffer.from(binary).toString('base64')}`;
+ return JSON.stringify(document);
+ }
+ const json = new TextEncoder().encode(JSON.stringify(document));
+ const jsonLength = Math.ceil(json.length / 4) * 4;
+ const result = new ArrayBuffer(28 + jsonLength + byteLength);
+ const header = new DataView(result);
+ header.setUint32(0, 0x46546c67, true);
+ header.setUint32(4, 2, true);
+ header.setUint32(8, result.byteLength, true);
+ header.setUint32(12, jsonLength, true);
+ header.setUint32(16, 0x4e4f534a, true);
+ const bytes = new Uint8Array(result);
+ bytes.fill(32, 20, 20 + jsonLength);
+ bytes.set(json, 20);
+ header.setUint32(20 + jsonLength, byteLength, true);
+ header.setUint32(24 + jsonLength, 0x004e4942, true);
+ bytes.set(binary, 28 + jsonLength);
+ return result;
+}
+
+function addWeightsClip(document, append, interpolation = 'LINEAR', values = [0, 0, 1, -1]) {
+ const input = append(new Float32Array([0, 2]), 'SCALAR');
+ const output = append(new Float32Array(values), 'SCALAR');
+ document.animations = [{ samplers: [{ input, output, interpolation }], channels: [{ sampler: 0, target: { node: 0, path: 'weights' } }] }];
+}
+
+test('GLB imports relative channels with missing zeros, independent node defaults and shared geometry', async () => {
+ const asset = await parseGltf(morphAsset(document => {
+ document.meshes[0].weights = [-0.25, 0.5];
+ document.nodes[0].weights = [0.75, -1];
+ }));
+ const [first, second] = asset.parts;
+ assert.equal(first.geometry, second.geometry);
+ assert.notEqual(first.morph, second.morph);
+ assert.notEqual(first.morph.weights, second.morph.weights);
+ assert.deepEqual(Array.from(first.morph.weights), [0.75, -1]);
+ assert.deepEqual(Array.from(second.morph.weights), [-0.25, 0.5]);
+ assert.equal(first.geometry.morphTargets[0].normals, undefined);
+ assert.equal(first.geometry.morphTargets[1].positions, undefined);
+ assert.deepEqual(Array.from(first.geometry.morphTargets[0].positions), [0, 0, 0, 0, 0, 0, 0, 1, 0]);
+ assert.ok(Math.abs(first.geometry.morphTargets[1].normals[1] - 0.2) < 1e-7);
+ first.morph.weights[0] = -2;
+ assert.equal(second.morph.weights[0], -0.25);
+ asset.dispose();
+});
+
+for (const scene of [0, 1]) {
+ test(`selected scene ${scene} preserves morph primitive declarations after association reduction`, async () => {
+ const asset = await parseGltf(morphAsset(document => {
+ document.scenes = [{ nodes: [0] }, { nodes: [1] }];
+ document.scene = scene;
+ document.nodes[0].weights = [0.25, -0.5];
+ document.nodes[1].weights = [-0.75, 1];
+ }));
+ assert.equal(asset.parts.length, 1);
+ assert.equal(asset.parts[0].name, scene === 0 ? 'First' : 'Second');
+ assert.deepEqual(Array.from(asset.parts[0].morph.weights), scene === 0 ? [0.25, -0.5] : [-0.75, 1]);
+ assert.equal(asset.parts[0].geometry.morphTargets[0].normals, undefined);
+ assert.equal(asset.parts[0].geometry.morphTargets[1].positions, undefined);
+ asset.dispose();
+ });
+ test(`selected scene ${scene} still imports ordinary meshes without morph targets`, async () => {
+ const asset = await parseGltf(morphAsset(document => {
+ document.scenes = [{ nodes: [0] }, { nodes: [1] }];
+ document.scene = scene;
+ delete document.meshes[0].primitives[0].targets;
+ }));
+ assert.equal(asset.parts.length, 1);
+ assert.equal(asset.parts[0].morph, undefined);
+ assert.equal(asset.parts[0].matrix[12], scene * 2);
+ asset.dispose();
+ });
+}
+
+test('multi-scene multi-primitive mappings retain each distinct morph channel declaration, including cloned scene roots', async () => {
+ for (const scene of [0, 1]) {
+ const asset = await parseGltf(morphAsset(document => {
+ document.scenes = [{ nodes: [0] }, { nodes: [0] }];
+ document.scene = scene;
+ const original = document.meshes[0].primitives[0];
+ document.meshes[0].primitives.push({ attributes: { ...original.attributes }, targets: [{ NORMAL: 3 }, { POSITION: 2 }] });
+ }));
+ assert.equal(asset.parts.length, 2);
+ const [first, second] = asset.parts;
+ assert.ok(first.geometry.morphTargets[0].positions);
+ assert.equal(first.geometry.morphTargets[0].normals, undefined);
+ assert.equal(second.geometry.morphTargets[0].positions, undefined);
+ assert.ok(second.geometry.morphTargets[0].normals);
+ assert.ok(second.geometry.morphTargets[1].positions);
+ assert.equal(second.geometry.morphTargets[1].normals, undefined);
+ asset.dispose();
+ }
+});
+
+test('association capture does not decode orphan meshes and disposes all decoded geometry', async context => {
+ const decodedMeshes = [];
+ const decodedGeometries = new Set();
+ const disposedGeometries = new Set();
+ const originalParse = GLTFLoader.prototype.parseAsync;
+ context.mock.method(GLTFLoader.prototype, 'parseAsync', function (...argumentsList) {
+ this.register(parser => ({
+ name: 'MorphLifecycleProbe',
+ loadMesh(index) {
+ decodedMeshes.push(index);
+ return parser.loadMesh(index).then(mesh => {
+ mesh.traverse(node => {
+ if (!node.geometry || decodedGeometries.has(node.geometry)) return;
+ decodedGeometries.add(node.geometry);
+ node.geometry.addEventListener('dispose', () => disposedGeometries.add(node.geometry));
+ });
+ return mesh;
+ });
+ },
+ }));
+ return originalParse.apply(this, argumentsList);
+ });
+ const asset = await parseGltf(morphAsset((document, append) => {
+ document.scenes = [{ nodes: [0] }, { nodes: [1] }];
+ const positions = append(new Float32Array([0, 0, 0, 2, 0, 0, 0, 2, 0]), 'VEC3');
+ Object.assign(document.accessors[positions], { min: [0, 0, 0], max: [2, 2, 0] });
+ document.meshes.push({ primitives: [{ attributes: { POSITION: positions, NORMAL: 1 } }] });
+ document.nodes.push({ name: 'Orphan', mesh: 1 });
+ }));
+ assert.deepEqual(decodedMeshes, [0]);
+ assert.equal(decodedGeometries.size, 1);
+ asset.dispose();
+ assert.equal(disposedGeometries.size, decodedGeometries.size);
+});
+
+test('embedded glTF JSON defaults omitted node and mesh weights to retained zeros', async () => {
+ const previous = globalThis.ProgressEvent;
+ globalThis.ProgressEvent ??= class { constructor(type) { this.type = type; } };
+ try {
+ const asset = await parseGltf(morphAsset(() => {}, true));
+ assert.ok(asset.parts[0].morph.weights instanceof Float32Array);
+ assert.deepEqual(Array.from(asset.parts[0].morph.weights), [0, 0]);
+ asset.dispose();
+ } finally {
+ if (previous === undefined) delete globalThis.ProgressEvent;
+ else globalThis.ProgressEvent = previous;
+ }
+});
+
+for (const [interpolation, values, expected] of [
+ ['LINEAR', [0, 0, 1, -1], [0.5, -0.5]],
+ ['STEP', [0, 0, 1, -1], [0, 0]],
+ ['CUBICSPLINE', [0, 0, 0, 0, 2, 0, 0, 0, 1, -1, 0, 0], [1, -0.5]],
+]) {
+ test(`${interpolation} weights animation uses loader interpolation and repeated absolute seeks`, async () => {
+ const asset = await parseGltf(morphAsset((document, append) => addWeightsClip(document, append, interpolation, values)));
+ const weights = asset.parts[0].morph.weights;
+ const matrix = asset.parts[0].matrix;
+ asset.applyAnimation(1);
+ assert.deepEqual(Array.from(weights), expected);
+ asset.applyAnimation(2);
+ assert.deepEqual(Array.from(weights), [1, -1]);
+ asset.applyAnimation(0.1);
+ asset.applyAnimation(1);
+ assert.deepEqual(Array.from(weights), expected);
+ assert.equal(asset.parts[0].morph.weights, weights);
+ assert.equal(asset.parts[0].matrix, matrix);
+ assert.deepEqual(Array.from(asset.parts[1].morph.weights), [0, 0]);
+ asset.applyAnimation(-1);
+ assert.deepEqual(Array.from(weights), [0, 0]);
+ asset.dispose();
+ });
+}
+
+test('morphs compose with skin palettes and invalid samples publish no matrix, palette or weights', async () => {
+ const asset = await parseGltf(skinnedStripAsset((document, append) => {
+ const primitive = document.meshes[0].primitives[0];
+ const delta = append(new Float32Array(18).fill(2), 'VEC3');
+ Object.assign(document.accessors[delta], { min: [2, 2, 2], max: [2, 2, 2] });
+ primitive.targets = [{ POSITION: delta }];
+ const input = document.animations[0].samplers[0].input;
+ const output = append(new Float32Array([0.5, 3e38]), 'SCALAR');
+ document.animations[0].samplers.push({ input, output, interpolation: 'STEP' });
+ document.animations[0].channels.push({ sampler: 1, target: { node: 1, path: 'weights' } });
+ }));
+ const part = asset.parts[0];
+ assert.ok(part.skin && part.morph);
+ asset.applyAnimation(1);
+ const matrix = Array.from(part.matrix);
+ const palette = Array.from(part.skin.jointMatrices);
+ const weights = Array.from(part.morph.weights);
+ assert.equal(weights[0], 0.5);
+ assert.ok(Math.abs(part.skin.jointMatrices[16 + 1]) > 0.5);
+ assert.throws(() => asset.applyAnimation(2), /Float32 position/);
+ assert.deepEqual(Array.from(part.matrix), matrix);
+ assert.deepEqual(Array.from(part.skin.jointMatrices), palette);
+ assert.deepEqual(Array.from(part.morph.weights), weights);
+ asset.applyAnimation(0);
+ asset.applyAnimation(1);
+ assert.deepEqual(Array.from(part.skin.jointMatrices), palette);
+ assert.deepEqual(Array.from(part.morph.weights), weights);
+ asset.dispose();
+});
+
+test('target expansion and primitive instance budgets reject before loader decoding', async context => {
+ let calls = 0;
+ context.mock.method(GLTFLoader.prototype, 'parseAsync', () => { calls++; throw new Error('Unexpected decode'); });
+ await assert.rejects(parseGltf(morphAsset(), { maxVertices: 8 }), /maxVertices/);
+ await assert.rejects(parseGltf(morphAsset(document => {
+ document.meshes[0].primitives = Array.from({ length: 3 }, () => document.meshes[0].primitives[0]);
+ }), { maxParts: 2 }), /maxParts/);
+ const repeated = morphAsset((document, append) => {
+ const primitive = document.meshes[0].primitives[0];
+ const positions = append(new Float32Array(900), 'VEC3');
+ Object.assign(document.accessors[positions], { min: [0, 0, 0], max: [0, 0, 0] });
+ const normals = new Float32Array(900);
+ for (let index = 2; index < normals.length; index += 3) normals[index] = 1;
+ primitive.attributes = { POSITION: positions, NORMAL: append(normals, 'VEC3') };
+ primitive.targets = Array.from({ length: 64 }, () => ({ POSITION: positions }));
+ });
+ await assert.rejects(parseGltf(repeated, { maxBytes: repeated.byteLength }), /Decoded glTF accessors/);
+ assert.equal(calls, 0);
+});
+
+test('composed world bounds and changed public identities fail before any part publishes', async () => {
+ const asset = await parseGltf(morphAsset((document, append) => {
+ document.nodes[0].scale = [2e38, 2e38, 2e38];
+ addWeightsClip(document, append, 'STEP', [0, 0, 2, 0]);
+ const output = append(new Float32Array([2, 0, 0, 4, 0, 0]), 'VEC3');
+ document.animations[0].samplers.push({ input: 4, output, interpolation: 'LINEAR' });
+ document.animations[0].channels.push({ sampler: 1, target: { node: 1, path: 'translation' } });
+ }));
+ asset.applyAnimation(1);
+ const previous = asset.parts.map(part => ({ matrix: Array.from(part.matrix), weights: Array.from(part.morph.weights) }));
+ assert.throws(() => asset.applyAnimation(2), /Morph world position/);
+ asset.parts.forEach((part, index) => {
+ assert.deepEqual(Array.from(part.matrix), previous[index].matrix);
+ assert.deepEqual(Array.from(part.morph.weights), previous[index].weights);
+ });
+ const weights = asset.parts[1].morph.weights;
+ asset.parts[1].morph.weights = new Float32Array(weights);
+ assert.throws(() => asset.applyAnimation(0), /weight identity/);
+ assert.deepEqual(Array.from(asset.parts[0].matrix), previous[0].matrix);
+ asset.parts[1].morph.weights = weights;
+ asset.applyAnimation(1);
+ assert.deepEqual(Array.from(asset.parts[1].matrix), previous[1].matrix);
+ asset.dispose();
+});
+
+test('clip switches restore untracked instance defaults before later weight seeks', async () => {
+ const asset = await parseGltf(morphAsset((document, append) => {
+ document.nodes[0].weights = [-0.25, 0.5];
+ addWeightsClip(document, append);
+ const translation = append(new Float32Array([0, 0, 0, 2, 0, 0]), 'VEC3');
+ document.animations.push({ samplers: [{ input: 4, output: translation }], channels: [{ sampler: 0, target: { node: 0, path: 'translation' } }] });
+ }));
+ asset.applyAnimation(1, 0);
+ assert.deepEqual(Array.from(asset.parts[0].morph.weights), [0.5, -0.5]);
+ asset.applyAnimation(1, 1);
+ assert.deepEqual(Array.from(asset.parts[0].morph.weights), [-0.25, 0.5]);
+ assert.equal(asset.parts[0].matrix[12], 1);
+ asset.applyAnimation(1, 0);
+ assert.deepEqual(Array.from(asset.parts[0].morph.weights), [0.5, -0.5]);
+ assert.equal(asset.parts[0].matrix[12], 0);
+ asset.dispose();
+});
+
+test('exactly 64 targets import and larger counts reject explicitly', async () => {
+ const asset = await parseGltf(morphAsset(document => {
+ document.meshes[0].primitives[0].targets = Array.from({ length: 64 }, () => ({ POSITION: 2 }));
+ }));
+ assert.equal(asset.parts[0].morph.weights.length, 64);
+ assert.equal(asset.parts[0].geometry.morphTargets.length, 64);
+ asset.dispose();
+ await assert.rejects(parseGltf(morphAsset(document => {
+ document.meshes[0].primitives[0].targets = Array.from({ length: 65 }, () => ({ POSITION: 2 }));
+ })), /64/);
+});
+
+test('malformed deltas, defaults, accessor shapes and all animation channels reject', async () => {
+ const cases = [
+ document => { document.meshes[0].primitives[0].targets[0] = { TANGENT: 2 }; },
+ document => { document.meshes[0].primitives[0].targets[0] = {}; },
+ document => { document.accessors[2].type = 'VEC4'; },
+ document => { document.accessors[2].count = 2; },
+ document => { document.accessors[2].componentType = 5123; },
+ document => { document.accessors[2].normalized = true; },
+ document => { delete document.accessors[2].min; },
+ document => { delete document.meshes[0].primitives[0].attributes.NORMAL; },
+ document => { document.meshes[0].primitives.push({ attributes: { POSITION: 0, NORMAL: 1 }, targets: [{ POSITION: 2 }] }); },
+ document => { document.meshes[0].weights = [0]; },
+ document => { document.nodes[0].weights = [1e39, 0]; },
+ (document, append, chunks) => { chunks[2][0] = NaN; },
+ (document, append) => { addWeightsClip(document, append); document.animations[0].samplers[0].output = 0; },
+ (document, append) => { addWeightsClip(document, append); document.nodes[0].mesh = undefined; },
+ (document, append) => { addWeightsClip(document, append); document.animations[0].channels[0].target.node = 99; },
+ (document, append) => { addWeightsClip(document, append); document.animations[0].samplers[0].interpolation = 'BEZIER'; },
+ (document, append, chunks) => { addWeightsClip(document, append); chunks[4][1] = 0; },
+ (document, append, chunks) => { addWeightsClip(document, append); chunks[5][0] = Infinity; },
+ (document, append) => { addWeightsClip(document, append); document.animations[0].channels.push({ ...document.animations[0].channels[0] }); },
+ (document, append) => { addWeightsClip(document, append); document.animations.push({ samplers: [{ input: 4, output: 0 }], channels: [{ sampler: 0, target: { node: 0, path: 'weights' } }] }); },
+ ];
+ for (const edit of cases) await assert.rejects(parseGltf(morphAsset(edit)));
+});
diff --git a/tests/gltf.test.js b/tests/gltf.test.js
index fcede355..98d40291 100644
--- a/tests/gltf.test.js
+++ b/tests/gltf.test.js
@@ -141,7 +141,11 @@ test('mirrored static transforms reverse triangle winding without altering world
test('unsupported features fail explicitly before loading resources', async () => {
const cases = [
[document => { document.nodes[1].skin = 0; }, /skin index/],
- [document => { document.meshes[0].primitives[0].targets = [{ POSITION: 0 }]; }, /Morph/],
+ [document => {
+ const primitive = document.meshes[0].primitives[0];
+ primitive.attributes.NORMAL = primitive.attributes.POSITION;
+ primitive.targets = [{ TANGENT: 0 }];
+ }, /Unsupported morph/],
[document => { document.meshes[0].primitives[0].attributes.COLOR_0 = 1; }, /COLOR_0/],
[document => { document.meshes[0].primitives[0].mode = 1; }, /TRIANGLES/],
[document => { document.materials[0].alphaMode = 'BLEND'; }, /alpha mode/],