Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add bounded GPU skinning and skeletal GLB animation

Nguyen Xuan An74ac4f18612a
diff --git a/README.md b/README.md
index d88c68f4..5c1a62b2 100644
--- a/README.md
+++ b/README.md
@@ -157,6 +157,8 @@ 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.
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 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/capability-audit.md b/docs/capability-audit.md
index 9bd90908..cfeb7c06 100644
--- a/docs/capability-audit.md
+++ b/docs/capability-audit.md
@@ -93,3 +93,19 @@ Invalid mixed updates still fail before changing packed instance data or submitt
Normal scratch buffers belong to uploaded parts and remain bounded by the scene size.
Live GPU frame timing and broader scene measurements remain required before claiming an overall speed improvement.
+
+## Trailer acceptance requirements
+
+The current trailer does not meet the requested visual quality.
+The scientist uses an unlit silhouette, which hides facial structure and prevents clear character recognition.
+Rigid joint animation and GPU skinning provide motion tools, but do not solve character modeling or material quality by themselves.
+
+The environment has procedural shaders, fog, bloom and grading. These features do not yet produce convincing cinematic atmosphere.
+Volumetric lighting, smoke, dust, explosion detail and lighting continuity require visible shot-level validation.
+
+The engine does not yet provide rigid-body physics, collision response, articulated constraints or ragdoll simulation.
+The requested final state includes these systems, with deterministic playback or recorded simulation for arbitrary film seeks.
+Simple sine motion does not satisfy the physics requirement.
+
+Completion requires recognizable characters, a convincing environment and integrated physical interactions, demonstrated in rendered trailer shots.
+Technical fixtures and passing API tests do not establish that result.
diff --git a/docs/gltf.md b/docs/gltf.md
index 6c2d7fe4..d7242f7d 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -39,6 +39,7 @@ The optional `signal` aborts those fetches.
| `maxParts` | 20,000 | Declared nodes and decoded mesh parts. |
| `maxResources` | 64 | Unique resource URIs. |
| `maxTexturePixels` | 16,777,216 | Combined texture image pixels, checked before decoding. |
+| `maxJoints` | 4,096 | Combined declared joints and joint palettes for instantiated meshes. |
Every numeric limit must be a positive safe integer.
The importer rejects cyclic hierarchies, multiple parents, and hierarchies deeper than 256 levels.
@@ -89,7 +90,7 @@ The importer rejects a requested texture that fails to decode, rather than retur
## Animation and ownership
`animations` contains the decoded Three.js animation clips, including their names, durations, and tracks.
-`applyAnimation(time, clipIndex = 0)` evaluates one rigid node animation at an absolute time in seconds.
+`applyAnimation(time, clipIndex = 0)` evaluates node and joint animation at an absolute time in seconds.
Time clamps to the selected clip's duration.
The hook updates the existing part matrices and returns the same `parts` array.
Seeking in a different order produces the same matrices.
@@ -102,7 +103,8 @@ renderer.render(camera);
Translation, rotation, and scale tracks are supported.
The importer rejects animation poses that become singular or change triangle winding.
-It does not support skinning or morph targets.
+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 caller owns the Renderer67 instance.
`asset.dispose()` releases importer textures, image bitmaps, parser resources, and temporary object URLs.
@@ -118,10 +120,11 @@ Disposal is idempotent, and subsequent animation calls fail explicitly.
The bridge supports triangle meshes, PNG/JPEG base color textures, rigid animations, and metallic-roughness material factors.
It also supports `KHR_mesh_quantization` and `KHR_materials_emissive_strength`.
-The importer rejects alpha blending, alpha masking, double-sided materials, vertex transparency, and additional material texture channels.
+The importer rejects alpha blending, alpha masking, double-sided materials and vertex transparency.
+It supports base-color, normal, metallic-roughness, occlusion and emissive texture channels.
It rejects texture transforms, DRACO, KTX2, GPU instancing, and unsupported extensions, including optional extensions.
Line and point primitives are unsupported.
-The bridge does not import cameras, lights, scene environments, or skin data into Renderer67.
+The bridge does not import cameras, lights or scene environments into Renderer67.
The caller supplies its own camera and lighting.
## Verification
diff --git a/docs/skinning.md b/docs/skinning.md
new file mode 100644
index 00000000..3a47218e
--- /dev/null
+++ b/docs/skinning.md
@@ -0,0 +1,127 @@
+# GPU skeletal deformation
+
+This API exists in the current source checkout. The published `0.3.3` package does not include it yet.
+
+`Renderer67` deforms skinned vertices in its color, shadow, and benchmark vertex shaders.
+The implementation uses four normalized influences per vertex and a mesh-local joint palette.
+All five PBR map channels remain available.
+
+```js
+const pose = createSkinPose(2);
+const part = {
+ geometry: {
+ positions,
+ normals,
+ indices,
+ skinIndices: new Uint16Array(joints),
+ skinWeights: new Float32Array(weights),
+ },
+ matrix: meshWorldMatrix,
+ material,
+ skin: pose,
+};
+updateSkinPose(pose, jointWorldMatrices, inverseBindMatrices, meshWorldMatrix, bindMatrix);
+renderer.updateParts([part]);
+```
+
+`createSkinPose(jointCount)` creates a retained `Float32Array` named `jointMatrices`.
+Each joint occupies 16 floats in column-major order. The initial palette contains identity matrices.
+`updateSkinPose()` calculates `inverse(meshWorldMatrix) * jointWorldMatrix * inverseBindMatrix * bindMatrix` for each joint.
+Both optional matrices default to identity. Invalid input leaves the public palette unchanged.
+
+The helper retains its scratch matrices and staging buffer.
+
+Each vertex requires four joint indices and four weights.
+Indices must reference the pose palette, including indices paired with zero weights.
+Weights must be finite and within zero and one. Their total must be positive.
+
+The renderer normalizes weights when packing its immutable influence texture. It does not modify the supplied weight array.
+Joint matrices must be finite, affine, and nonsingular.
+
+## GPU data and batching
+
+Two RGBA32F textures hold the deformation data.
+The influence texture stores four indices and four normalized weights in two texels per vertex.
+The palette texture stores each joint matrix in four texels.
+The shader fetches influences with `gl_VertexID`, so skinning uses no additional vertex attributes.
+
+| Design | Consequence |
+| --- | --- |
+| Conventional attributes, with instance normals calculated in GLSL | Frees attribute slots but changes the rigid shader and its per-vertex cost. |
+| Influence and palette textures | Preserves all 16 existing attribute locations and adds vertex texture fetches. |
+
+The renderer uses textures to preserve the existing instance layout and PBR inputs.
+Geometry identity shares influence textures. Pose identity shares palette textures.
+A batch includes geometry, material maps, fixed map scales, and pose identity.
+Parts sharing one pose can instance together. Independent poses form separate batches.
+
+`updateParts()` uploads each submitted pose once through `texSubImage2D` using a retained padded buffer.
+It validates all submitted parts and weighted transforms before modifying packed data or submitting GPU writes.
+The palette and influence GPU textures retain their identities across updates.
+Input validation is atomic. A WebGL failure during submission cannot roll back earlier GPU writes.
+
+Geometry, influence arrays, pose identity, and the `jointMatrices` array identity must remain unchanged while the renderer uses them.
+The matrix values inside `jointMatrices` can change before `updateParts()`.
+Changing topology, influences, joint count, or pose identity requires a new renderer.
+Pose changes mark shadows dirty unless the caller explicitly disables shadow updates.
+
+## Normals and supported transforms
+
+Positions use the weighted matrix blend. Normals use the inverse-transpose of its upper-left 3×3 matrix, followed by the instance normal matrix.
+This preserves perpendicularity under nonuniform joint scaling.
+The installed Three.js skin shader transforms normals directly with the blended matrix.
+
+The methods agree when the blended matrix represents a rigid transform. They can differ under nonuniform scale or blended rotations.
+Tests compare positions with Three.js and verify the normal's perpendicularity to a transformed tangent.
+
+Singular joints and singular weighted vertex transforms fail explicitly. Reflected weighted transforms in world space also fail.
+The renderer validates weighted transforms on the CPU before uploads. This validation visits every influenced vertex in submitted parts.
+Skinning uses linear matrix blending. It does not implement dual-quaternion deformation or preserve volume around bent joints.
+
+## glTF import and animation
+
+The [glTF skin contract](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#skins) defines joint indices, weights, and inverse binds.
+`parseGltf()` and `loadGltf()` import `JOINTS_0`, `WEIGHTS_0`, ordered joints, and inverse bind matrices.
+Normalized unsigned byte and short weights are supported. Missing inverse binds use identity matrices.
+The importer validates raw influences before Three.js can replace zero weight totals during normalization.
+
+Imported parts expose `part.skin`. `asset.skins` contains the corresponding pose objects.
+Each imported pose also contains `joints`, `inverseBindMatrices`, `jointWorldMatrices`, and `bindMatrix`.
+Each joint descriptor contains its name and parent index within the palette. A parent index of `-1` means no palette parent.
+
+`asset.applyAnimation(time, clipIndex)` samples node and joint tracks at an absolute, clamped time.
+It prepares every pose before updating public part matrices or palettes.
+Invalid animation transforms leave those arrays unchanged. Subsequent valid seeks can recover.
+The renderer requires `updateParts(asset.parts)` after each seek.
+Skinned mesh node transforms cancel through the mesh-local palette, following glTF skin semantics.
+
+The bending fixture is `tests/fixtures/skinned-strip.js`. Its `skinnedStripAsset()` function returns a self-contained GLB.
+The lower row stays fixed while the upper segment bends. The middle row blends both joints.
+The fixture includes separate bend and translation clips for deterministic seek tests.
+
+## Budgets and lifetime
+
+GPU skinning requires at least two vertex texture units and eight combined texture units.
+Texture dimensions must fit `MAX_TEXTURE_SIZE`.
+Both RGBA32F textures, including padding, contribute to the renderer's existing texture memory budget.
+Palette textures use 64 bytes per joint before padding. Influence textures use 32 bytes per vertex before padding.
+
+The importer limits declared joints and the combined joint count of instantiated poses through `maxJoints`, which defaults to `4096`.
+Existing byte, vertex, part, image, and resource limits remain active.
+Palette creation supports at most `65536` joints, subject to GPU texture capacity and memory budgets.
+
+1. Dispose the renderer before disposing its imported asset.
+2. Call `asset.dispose()` to release decoder skeletons, geometry, materials, textures, and decoded images.
+
+Renderer disposal deletes every cached palette and influence texture.
+The caller owns the native geometry and pose arrays.
+
+## Remaining limits
+
+Additional influence sets, morph targets, reflected skin transforms, and singular weighted transforms remain unsupported.
+Procedural material tags cannot combine with skinning. Standard PBR and unlit materials can.
+The existing glTF restrictions on transparency, texture transforms, unsupported extensions, and compressed textures remain active.
+GLB export rejects skinned parts, rather than silently discarding their skeleton and current deformation.
+
+This unit does not add skin export, pose-aware bounds, picking, retargeting, animation blending, or a bone editor.
+It does not establish full Three.js or Blender parity.
diff --git a/package.json b/package.json
index 38b60849..7a239b1e 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,8 @@
"docs/material-maps.md",
"docs/modeling.md",
"docs/scene-graph.md",
- "docs/camera-path.md"
+ "docs/camera-path.md",
+ "docs/skinning.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
diff --git a/scripts/smoke-skinning.mjs b/scripts/smoke-skinning.mjs
new file mode 100644
index 00000000..b25f3462
--- /dev/null
+++ b/scripts/smoke-skinning.mjs
@@ -0,0 +1,75 @@
+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 base = process.argv[2] ?? 'http://127.0.0.1:5173';
+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('**/skinning-smoke.html', route => route.fulfill({ contentType: 'text/html', body: '<canvas style="width:640px;height:480px;display:block"></canvas>' }));
+ await page.goto(`${base}/skinning-smoke.html`);
+ const report = await page.evaluate(async () => {
+ const { Renderer67 } = await import('/src/renderer.js');
+ const { parseGltf } = await import('/src/gltf.js');
+ const { skinnedStripAsset } = await import('/tests/fixtures/skinned-strip.js');
+ const asset = await parseGltf(skinnedStripAsset());
+ const canvas = document.querySelector('canvas');
+ const renderer = new Renderer67(canvas, asset.parts, { samples: 4, pixelRatio: 1, memoryBudgetMiB: 96 });
+ const palette = asset.parts[0].skin.jointMatrices;
+ const record = renderer.skinTextures.get(asset.parts[0].skin);
+ const influence = renderer.influenceTextures.get(asset.parts[0].geometry);
+ const frame = { eye: [1, 3, 6], target: [1, 3, 0], fov: 40, time: 0, effects: { grain: 0 } };
+ function sample(time) {
+ asset.applyAnimation(time);
+ renderer.updateParts(asset.parts);
+ renderer.render(frame);
+ const gl = renderer.context;
+ const pixels = new Uint8Array(canvas.width * canvas.height * 4);
+ gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
+ let checksum = 2166136261;
+ for (const value of pixels) checksum = Math.imul(checksum ^ value, 16777619) >>> 0;
+ return { checksum, palette: Array.from(palette), glError: gl.getError() };
+ }
+ const straight = sample(0);
+ const bent = sample(2);
+ const repeated = sample(0);
+ let retained = true;
+ for (let index = 0; index < 60; index++) {
+ sample(index % 3);
+ retained &&= asset.parts[0].skin.jointMatrices === palette && renderer.skinTextures.get(asset.parts[0].skin) === record && renderer.influenceTextures.get(asset.parts[0].geometry) === influence;
+ }
+ const memory = renderer.memoryPlan;
+ const gpu = renderer.context.getParameter(renderer.context.getExtension('WEBGL_debug_renderer_info').UNMASKED_RENDERER_WEBGL);
+ sample(2);
+ const image = canvas.toDataURL('image/png');
+ const gl = renderer.context;
+ const texture = record.texture;
+ const influenceTexture = influence.texture;
+ renderer.dispose();
+ const released = !gl.isTexture(texture) && !gl.isTexture(influenceTexture);
+ asset.dispose();
+ return { straight, bent, repeated, retained, released, memory, gpu, image };
+ });
+ assert.equal(report.straight.glError, 0);
+ assert.equal(report.bent.glError, 0);
+ assert.deepEqual(report.straight, report.repeated);
+ assert.notEqual(report.straight.checksum, report.bent.checksum, 'GPU deformation did not change rendered pixels');
+ assert.equal(report.retained, true);
+ assert.equal(report.released, true);
+ assert.deepEqual(errors, []);
+ await writeFile('artifacts/skinning-gpu.png', Buffer.from(report.image.split(',')[1], 'base64'));
+ delete report.image;
+ await writeFile('artifacts/skinning-gpu.json', JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report, null, 2));
+} finally {
+ await browser.close();
+}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 79ef33ce..fe677d45 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -16,6 +16,10 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- An outdoor world uses `src/nature.js` and `src/nature-viewer.js`.
- A deterministic film uses `src/film.js` and `src/film-player.js`.
- A keyframe scene uses `src/animation.js`, `src/motion.js` and `src/motion-player.js`.
+- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.
+- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.md`.
+- An authored camera uses `src/camera-path.js` and the checkout's `docs/camera-path.md`.
+- A skeletal asset uses `src/skinning.js`, `src/gltf.js` and the checkout's `docs/skinning.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`.
- An image or video export uses `render-67js-media`.
diff --git a/src/export.js b/src/export.js
index c0e5b5a4..c47422d7 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.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.');
+ }
for (const channel of ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap']) {
if (part.material[channel]) {
throw new RangeError(`GLB export cannot preserve ${channel} yet. Texture export must be implemented before exporting this material.`);
diff --git a/src/gltf.js b/src/gltf.js
index 53ffeb73..0bfd3fe2 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -1,11 +1,12 @@
import { AnimationMixer, LoadingManager, LoopOnce } from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { textureDescriptorInfo } from './renderer.js';
+import { createSkinPose, updateSkinPose, validateSkinGeometry, validateSkinPose } from './skinning.js';
export const GLTF_CAPABILITIES = Object.freeze({
formats: ['glb', 'gltf'],
- supported: ['triangle meshes', 'world transforms', 'rigid 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: ['skinning', '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', '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'],
});
const DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
@@ -32,6 +33,7 @@ function limitsFor(options) {
maxParts: options.maxParts ?? 20_000,
maxResources: options.maxResources ?? 64,
maxTexturePixels: options.maxTexturePixels ?? 16_777_216,
+ maxJoints: options.maxJoints ?? 4096,
};
for (const [name, value] of Object.entries(limits)) {
if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${name} must be a positive safe integer.`);
@@ -97,6 +99,14 @@ function validateDocument(document, limits) {
throw new Error('Each mesh primitive requires a valid POSITION accessor.');
}
vertices += position.count;
+ 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];
+ if (joints || weights) {
+ if (!joints || !weights || joints.type !== 'VEC4' || weights.type !== 'VEC4' || joints.count !== position.count || weights.count !== position.count) throw new Error('JOINTS_0 and WEIGHTS_0 must contain four values per POSITION.');
+ if (![5121, 5123].includes(joints.componentType) || joints.normalized) throw new Error('JOINTS_0 requires unnormalized unsigned byte or short indices.');
+ if (weights.componentType !== 5126 && (![5121, 5123].includes(weights.componentType) || !weights.normalized)) throw new Error('WEIGHTS_0 requires floats or normalized unsigned integers.');
+ } else if (primitive.attributes?.JOINTS_0 !== undefined || primitive.attributes?.WEIGHTS_0 !== undefined) throw new Error('Invalid skin attribute accessor index.');
const colorIndex = primitive.attributes?.COLOR_0;
if (colorIndex !== undefined) {
const color = document.accessors?.[colorIndex];
@@ -125,14 +135,33 @@ function validateDocument(document, limits) {
}
if (vertices > limits.maxVertices || indices > limits.maxVertices * 12) throw new Error('glTF geometry exceeds maxVertices or its index budget.');
if ((document.nodes?.length ?? 0) > limits.maxParts) throw new Error('glTF nodes exceed maxParts.');
+ let jointCount = 0;
+ for (const skin of document.skins ?? []) {
+ if (!Array.isArray(skin.joints) || !skin.joints.length || new Set(skin.joints).size !== skin.joints.length || skin.joints.some(joint => !Number.isInteger(joint) || !document.nodes?.[joint])) throw new Error('Skin joints require distinct valid node indices.');
+ jointCount += skin.joints.length;
+ if (jointCount > limits.maxJoints || skin.joints.length > 65536) throw new Error('Skin joints exceed maxJoints.');
+ if (skin.skeleton !== undefined && (!Number.isInteger(skin.skeleton) || !document.nodes?.[skin.skeleton])) throw new Error('Invalid skin skeleton node.');
+ if (skin.inverseBindMatrices !== undefined) {
+ const accessor = document.accessors?.[skin.inverseBindMatrices];
+ if (!accessor || accessor.type !== 'MAT4' || accessor.componentType !== 5126 || accessor.normalized || accessor.count !== skin.joints.length) throw new Error('Inverse bind matrices require one float MAT4 per joint.');
+ }
+ }
+ let poseJointCount = 0;
for (const node of document.nodes ?? []) {
- if (node.skin !== undefined) throw new Error('Skinned meshes are unsupported.');
+ 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 ?? []) {
+ if (primitive.attributes?.JOINTS_0 === undefined || primitive.attributes?.WEIGHTS_0 === undefined) throw new Error('Skinned meshes require JOINTS_0 and WEIGHTS_0.');
+ poseJointCount += document.skins[node.skin].joints.length;
+ if (poseJointCount > limits.maxJoints) throw new Error('Instanced skin poses exceed maxJoints.');
+ }
+ }
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 rigid node translation, rotation and scale animations are supported.');
+ if (!['translation', 'rotation', 'scale'].includes(channel.target?.path)) throw new Error('Only node translation, rotation and scale animations are supported.');
}
}
for (const material of document.materials ?? []) {
@@ -389,9 +418,59 @@ function convertGeometry(source, mirrored) {
if (uv) geometry.uvs = copyAttribute(uv, 2);
const color = source.getAttribute('color');
if (color) geometry.colors = convertVertexColors(color, position.count);
+ const skinIndices = source.getAttribute('skinIndex');
+ const skinWeights = source.getAttribute('skinWeight');
+ if (skinIndices) geometry.skinIndices = new Uint16Array(copyAttribute(skinIndices, 4));
+ if (skinWeights) geometry.skinWeights = copyAttribute(skinWeights, 4);
return geometry;
}
+function makeSkinBinding(node) {
+ const count = node.skeleton.bones.length;
+ const pose = createSkinPose(count);
+ const pendingPose = createSkinPose(count);
+ const inverseBindMatrices = new Float32Array(count * 16);
+ const jointWorldMatrices = new Float32Array(count * 16);
+ const pendingWorld = new Float32Array(count * 16);
+ const joints = node.skeleton.bones.map((bone, index) => {
+ inverseBindMatrices.set(node.skeleton.boneInverses[index].elements, index * 16);
+ 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 };
+}
+
+function prepareSkinBinding(binding, geometry) {
+ const { node, skin, pendingPose, pendingWorld } = binding;
+ 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);
+}
+
+function commitSkinBinding(binding) {
+ binding.skin.jointMatrices.set(binding.pendingPose.jointMatrices);
+ binding.skin.jointWorldMatrices.set(binding.pendingWorld);
+}
+
+function skinPreflightPlugin(parser, document) {
+ return {
+ name: '67SkinPreflight',
+ async beforeRoot() {
+ for (const node of document.nodes ?? []) {
+ if (node.skin === undefined) continue;
+ const pose = createSkinPose(document.skins[node.skin].joints.length);
+ for (const primitive of document.meshes[node.mesh].primitives) {
+ const [joints, weights] = await Promise.all([
+ parser.getDependency('accessor', primitive.attributes.JOINTS_0),
+ parser.getDependency('accessor', primitive.attributes.WEIGHTS_0),
+ ]);
+ validateSkinGeometry({ positions: { length: weights.count * 3 }, skinIndices: copyAttribute(joints, 4), skinWeights: copyAttribute(weights, 4) }, pose);
+ }
+ }
+ },
+ };
+}
+
function convertVertexColors(attribute, vertexCount) {
if (attribute.count !== vertexCount || ![3, 4].includes(attribute.itemSize)) {
throw new Error('COLOR_0 requires matching RGB or RGBA vertex values.');
@@ -456,9 +535,11 @@ function releaseParsed(gltf) {
const materials = new Set();
const textures = new Set();
const images = new Set();
+ const skeletons = new Set();
for (const scene of gltf.scenes) {
scene.traverse(node => {
if (node.geometry) geometries.add(node.geometry);
+ if (node.skeleton) skeletons.add(node.skeleton);
for (const material of Array.isArray(node.material) ? node.material : node.material ? [node.material] : []) {
materials.add(material);
for (const value of Object.values(material)) if (value?.isTexture) textures.add(value);
@@ -472,6 +553,7 @@ function releaseParsed(gltf) {
texture.dispose();
});
images.forEach(image => image.close?.());
+ skeletons.forEach(skeleton => skeleton.dispose());
}
/** Parse a bounded glTF 2.0 asset into Renderer67 parts. Three.js only decodes the asset. */
@@ -491,17 +573,20 @@ export async function parseGltf(data, options = {}) {
});
let gltf;
try {
- gltf = await new GLTFLoader(manager).parseAsync(data, options.baseUrl ?? '');
+ const loader = new GLTFLoader(manager);
+ loader.register(parser => skinPreflightPlugin(parser, document));
+ gltf = await loader.parseAsync(data, options.baseUrl ?? '');
gltf.scene.updateMatrixWorld(true);
const parts = [];
const bindings = [];
+ const skinBindings = [];
const geometries = new Map();
const materials = new Map();
const maps = new Map();
let actualVertices = 0;
gltf.scene.traverse(node => {
if (!node.isMesh) return;
- if (node.isSkinnedMesh || node.morphTargetInfluences?.length) throw new Error('Skinning and morph targets are unsupported.');
+ if (node.morphTargetInfluences?.length) throw new Error('Morph targets are unsupported.');
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) {
@@ -511,17 +596,26 @@ export async function parseGltf(data, options = {}) {
const determinant = node.matrixWorld.determinant();
if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-12) throw new Error('Mesh world transform is singular or non-finite.');
const mirrored = determinant < 0;
- const geometryKey = `${node.geometry.uuid}:${mirrored}`;
+ const geometryMirrored = node.isSkinnedMesh ? false : mirrored;
+ const geometryKey = `${node.geometry.uuid}:${geometryMirrored}`;
if (!geometries.has(geometryKey)) {
actualVertices += node.geometry.getAttribute('position').count;
if (actualVertices > limits.maxVertices) throw new Error('Decoded geometry exceeds maxVertices.');
- geometries.set(geometryKey, convertGeometry(node.geometry, mirrored));
+ geometries.set(geometryKey, convertGeometry(node.geometry, geometryMirrored));
}
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 };
+ if (node.isSkinnedMesh) {
+ const binding = makeSkinBinding(node);
+ prepareSkinBinding(binding, geometry);
+ commitSkinBinding(binding);
+ part.skin = binding.skin;
+ skinBindings.push({ ...binding, geometry });
+ }
+ validateSkinGeometry(geometry, part.skin);
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 });
@@ -557,10 +651,12 @@ export async function parseGltf(data, options = {}) {
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 skinBindings) commitSkinBinding(binding);
return parts;
}
- return { parts, animations: gltf.animations, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };
+ return { parts, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };
} catch (error) {
if (gltf) releaseParsed(gltf);
objectUrls.forEach(url => URL.revokeObjectURL(url));
diff --git a/src/index.js b/src/index.js
index 0deb5d8e..4e90a552 100644
--- a/src/index.js
+++ b/src/index.js
@@ -6,6 +6,7 @@ export { box, cylinder, sphere, torus } from './geometry.js';
export { exportGlb } from './export.js';
export { createAnimationMixer } from './animation-mixer.js';
export { createSceneGraph } from './scene-graph.js';
+export { createSkinPose, updateSkinPose } from './skinning.js';
export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js';
export { assemblyOffset } from './assembly.js';
diff --git a/src/renderer.js b/src/renderer.js
index 1ef89e49..90470ccd 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -4,6 +4,7 @@ import { fullscreenVertex, postFragment, skyFragment, bloomFragment } from './po
import { planRenderSize, estimateTextureBytes } from './budget.js';
import { applyProjection } from './camera.js';
import { resolveEffects } from './effects.js';
+import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.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;
@@ -13,6 +14,7 @@ const MAP_UNIFORMS = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusion
const MAP_FLAGS = ['hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap'];
const DEFAULT_NORMAL_SCALE = [1, 1];
const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);
+const SKIN_UNIFORMS = ['skinEnabled', 'skinInfluences', 'jointPalette'];
function validateMaterialMaps(material) {
if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {
@@ -120,10 +122,13 @@ export function groupParts(parts, batching = true) {
const batches = [];
for (const part of parts) {
validateTransform(part);
+ 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.');
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)) {
+ for (const value of [...materialMapState(part.material), part.skin ?? null]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@ -182,11 +187,26 @@ export class Renderer67 {
this.batches = [];
this.partLocations = new Map();
this.updateBatches = new Set();
+ this.updateSkins = new Set();
+ this.skinTextures = new Map();
+ this.influenceTextures = 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);
+ 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.');
+ const poses = new Set();
+ const skinGeometries = new Set();
+ for (const group of groups) {
+ const part = group[0];
+ if (!part.skin) continue;
+ if (!poses.has(part.skin)) this.textureBytes += skinTextureLayout(part.skin.jointMatrices.length / 4, textureLimit, 4).bytes;
+ if (!skinGeometries.has(part.geometry)) this.textureBytes += skinTextureLayout(part.geometry.positions.length / 3 * 2, textureLimit, 2).bytes;
+ poses.add(part.skin);
+ skinGeometries.add(part.geometry);
+ }
const maps = new Set();
for (const group of groups) {
for (const field of MATERIAL_MAPS) {
@@ -218,7 +238,8 @@ 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, '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, '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.depthSkinUniforms = Object.fromEntries(SKIN_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);
@@ -232,6 +253,16 @@ export class Renderer67 {
this.partCount = parts.length;
this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);
this.whiteTexture = this.createTexture(null);
+ // Disabled skin samplers still need distinct units from the depth sampler.
+ for (const [program, uniforms] of [[this.program, this.uniforms], [this.depthProgram, this.depthSkinUniforms]]) {
+ this.context.useProgram(program);
+ this.context.uniform1i(uniforms.skinInfluences, 6);
+ this.context.uniform1i(uniforms.jointPalette, 7);
+ }
+ for (const unit of [6, 7]) {
+ this.context.activeTexture(this.context.TEXTURE0 + unit);
+ this.context.bindTexture(this.context.TEXTURE_2D, this.whiteTexture);
+ }
groups.forEach((group) => this.batches.push(this.uploadBatch(group)));
this.createShadowMap();
this.resize();
@@ -334,17 +365,55 @@ export class Renderer67 {
const map = parts[0].material.map ?? null;
const mapState = materialMapState(parts[0].material);
const textures = mapState.slice(0, 5).map(descriptor => this.createTexture(descriptor));
- const batch = { vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor' };
- parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, normalMatrix: mat3.create() }));
+ 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' };
+ 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) }));
return batch;
}
+ createSkinTexture(cache, identity, matrices, groupSize) {
+ if (cache.has(identity)) return cache.get(identity);
+ const context = this.context;
+ const texelCount = matrices ? matrices.length / 4 : identity.positions.length / 3 * 2;
+ 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 texture = context.createTexture();
+ context.bindTexture(context.TEXTURE_2D, texture);
+ try {
+ context.texImage2D(context.TEXTURE_2D, 0, context.RGBA32F, layout.width, layout.height, 0, context.RGBA, context.FLOAT, data);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);
+ } catch (error) {
+ context.deleteTexture(texture);
+ throw error;
+ }
+ const record = { ...layout, texture, data, pose: matrices ? identity : null };
+ cache.set(identity, record);
+ return record;
+ }
+
updateParts(parts, { shadows = true } = {}) {
+ this.updatePartIdentities ??= new Set();
+ this.updatePartIdentities.clear();
+ this.updateSkins.clear();
+ this.updateBatches.clear();
// Preflight every part before touching packed data or submitting GPU writes.
for (const part of parts) {
+ this.updatePartIdentities.add(part);
const location = this.partLocations.get(part);
if (!location) throw new Error(`Unknown part identity: ${part.name}`);
if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);
+ if ((part.skin ?? null) !== location.skin || part.skin?.jointMatrices !== location.jointMatrices || part.geometry.skinIndices !== location.skinIndices || part.geometry.skinWeights !== location.skinWeights) throw new Error(`Skin identity changes require a new renderer: ${part.name}`);
+ if (part.skin) {
+ if (PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');
+ validateSkinPose(part.skin, part.geometry, part.matrix);
+ this.updateSkins.add(location.batch.skinTexture);
+ }
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;
@@ -355,6 +424,14 @@ export class Renderer67 {
if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
validateTransform(part, location.normalMatrix);
}
+ // A palette upload also changes consumers absent from the submitted part list.
+ if (this.updateSkins.size) {
+ for (const [part, location] of this.partLocations) {
+ if (!location.skin || !this.updateSkins.has(location.batch.skinTexture) || this.updatePartIdentities.has(part)) continue;
+ const committedMatrix = location.committedMatrix ?? location.batch.instanceData.subarray(location.index * INSTANCE_STRIDE, location.index * INSTANCE_STRIDE + 16);
+ validateSkinPose(location.skin, location.geometry, committedMatrix);
+ }
+ }
this.updateBatches.clear();
for (const part of parts) {
const location = this.partLocations.get(part);
@@ -365,6 +442,13 @@ export class Renderer67 {
this.context.bindBuffer(this.context.ARRAY_BUFFER, batch.instanceBuffer);
this.context.bufferSubData(this.context.ARRAY_BUFFER, 0, batch.instanceData);
}
+ for (const record of this.updateSkins) {
+ // Each texture record belongs to one pose and keeps its padded upload buffer.
+ const pose = record.pose;
+ record.data.set(pose.jointMatrices);
+ 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);
+ }
if (shadows && parts.length > 0) this.shadowsDirty = true;
return parts.length;
}
@@ -379,6 +463,7 @@ export class Renderer67 {
const context = this.context;
const allocateShadow = !this.shadowTexture;
if (allocateShadow) this.shadowTexture = context.createTexture();
+ context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
if (allocateShadow) context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, 2048, 2048, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);
@@ -561,6 +646,18 @@ export class Renderer67 {
}
drawBatch(batch, textured = false) {
+ if (this.hasSkins) {
+ const uniforms = textured ? this.uniforms : this.depthSkinUniforms;
+ this.context.uniform1f(uniforms.skinEnabled, batch.skin ? 1 : 0);
+ if (batch.skin) {
+ this.context.activeTexture(this.context.TEXTURE0 + 6);
+ this.context.bindTexture(this.context.TEXTURE_2D, batch.influenceTexture.texture);
+ this.context.uniform1i(uniforms.skinInfluences, 6);
+ this.context.activeTexture(this.context.TEXTURE0 + 7);
+ this.context.bindTexture(this.context.TEXTURE_2D, batch.skinTexture.texture);
+ this.context.uniform1i(uniforms.jointPalette, 7);
+ }
+ }
if (textured && !this.benchmark) {
for (let index = 0; index < MATERIAL_MAPS.length; index++) {
this.context.activeTexture(this.context.TEXTURE0 + index + 1);
@@ -644,6 +741,13 @@ 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 record of cache?.values() ?? []) this.context.deleteTexture(record.texture);
+ cache?.clear();
+ }
this.partLocations.clear();
+ this.updatePartIdentities?.clear();
+ this.updateSkins?.clear();
+ this.updateBatches?.clear();
}
}
diff --git a/src/shaders.js b/src/shaders.js
index 56ca986c..2747b2db 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -1,3 +1,25 @@
+const skinningShader = `
+uniform float skinEnabled;
+uniform highp sampler2D skinInfluences;
+uniform highp sampler2D jointPalette;
+vec4 skinTexel(sampler2D source, int index) {
+ int width = textureSize(source, 0).x;
+ return texelFetch(source, ivec2(index % width, index / width), 0);
+}
+mat4 jointMatrix(int joint) {
+ int offset = joint * 4;
+ return mat4(skinTexel(jointPalette, offset), skinTexel(jointPalette, offset + 1),
+ skinTexel(jointPalette, offset + 2), skinTexel(jointPalette, offset + 3));
+}
+mat4 skinTransform() {
+ if (skinEnabled < 0.5) return mat4(1.0);
+ ivec4 joints = ivec4(skinTexel(skinInfluences, gl_VertexID * 2));
+ vec4 weights = skinTexel(skinInfluences, gl_VertexID * 2 + 1);
+ return jointMatrix(joints.x) * weights.x + jointMatrix(joints.y) * weights.y
+ + jointMatrix(joints.z) * weights.z + jointMatrix(joints.w) * weights.w;
+}
+`;
+
export const vertexShader = `#version 300 es
precision highp float;
layout(location=0) in vec3 position;
@@ -26,8 +48,10 @@ out vec4 shadowPosition;
out vec2 textureUV;
out vec3 vertexTint;
flat out vec3 emissionColor;
+${skinningShader}
void main() {
- vec4 world = instanceMatrix * vec4(position, 1.0);
+ mat4 deformation = skinTransform();
+ vec4 world = instanceMatrix * deformation * vec4(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);
@@ -39,7 +63,8 @@ void main() {
world.xyz = mix(explosionCenter, world.xyz, 0.03 + explosionProgress * 0.97);
}
worldPosition = world.xyz;
- worldNormal = normalize(instanceNormal * normal);
+ vec3 deformedNormal = skinEnabled > 0.5 ? transpose(inverse(mat3(deformation))) * normal : normal;
+ worldNormal = normalize(instanceNormal * deformedNormal);
baseColor = instanceColor;
textureUV = uv;
vertexTint = vertexColor;
@@ -57,8 +82,9 @@ layout(location=11) in vec3 assemblyOffset;
layout(location=12) in vec3 assemblyDetailOffset;
uniform mat4 lightProjection;
uniform float assemblyAmount;
+${skinningShader}
void main() {
- vec4 world = instanceMatrix * vec4(position, 1.0);
+ vec4 world = instanceMatrix * skinTransform() * vec4(position, 1.0);
world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);
gl_Position = lightProjection * world;
}`;
@@ -75,9 +101,10 @@ layout(location=2) in mat4 instanceMatrix;
layout(location=9) in vec3 instanceColor;
uniform mat4 viewProjection;
out vec3 color;
+${skinningShader}
void main() {
color = instanceColor;
- gl_Position = viewProjection * instanceMatrix * vec4(position, 1.0);
+ gl_Position = viewProjection * instanceMatrix * skinTransform() * vec4(position, 1.0);
}`;
export const benchmarkFragmentShader = `#version 300 es
diff --git a/src/skinning.js b/src/skinning.js
new file mode 100644
index 00000000..8f6ae6a7
--- /dev/null
+++ b/src/skinning.js
@@ -0,0 +1,156 @@
+import { mat4 } from 'gl-matrix';
+
+const poseWorkspaces = new WeakMap();
+const IDENTITY_MATRIX = mat4.create();
+
+function finiteFloat(value) {
+ return Number.isFinite(value) && Number.isFinite(Math.fround(value));
+}
+
+function matrixDeterminant(values, offset) {
+ const matrixXX = Math.fround(values[offset]);
+ const matrixYX = Math.fround(values[offset + 1]);
+ const matrixZX = Math.fround(values[offset + 2]);
+ const matrixXY = Math.fround(values[offset + 4]);
+ const matrixYY = Math.fround(values[offset + 5]);
+ const matrixZY = Math.fround(values[offset + 6]);
+ const matrixXZ = Math.fround(values[offset + 8]);
+ const matrixYZ = Math.fround(values[offset + 9]);
+ const matrixZZ = Math.fround(values[offset + 10]);
+ return matrixXX * (matrixYY * matrixZZ - matrixYZ * matrixZY)
+ - matrixXY * (matrixYX * matrixZZ - matrixYZ * matrixZX)
+ + matrixXZ * (matrixYX * matrixZY - matrixYY * matrixZX);
+}
+
+function validateMatrices(values, count, label) {
+ if (values?.length !== count * 16) throw new Error(`${label} must contain one matrix per joint.`);
+ for (const value of values) if (!finiteFloat(value)) throw new Error(`${label} must contain finite floats.`);
+ for (let offset = 0; offset < values.length; offset += 16) {
+ if (values[offset + 3] !== 0 || values[offset + 7] !== 0 || values[offset + 11] !== 0 || values[offset + 15] !== 1) throw new Error(`${label} must contain affine matrices.`);
+ if (Math.abs(matrixDeterminant(values, offset)) < 1e-10) throw new Error(`${label} contains a singular joint transform.`);
+ }
+}
+
+/** Create a retained mesh-local joint palette. Shared pose identity shares a GPU palette. */
+export function createSkinPose(jointCount) {
+ if (!Number.isSafeInteger(jointCount) || jointCount < 1 || jointCount > 65536) throw new Error('Joint count must be within one and 65536.');
+ const jointMatrices = new Float32Array(jointCount * 16);
+ for (let joint = 0; joint < jointCount; joint++) jointMatrices.set(IDENTITY_MATRIX, joint * 16);
+ const pose = { jointMatrices };
+ poseWorkspaces.set(pose, {
+ jointMatrices,
+ pending: new Float32Array(jointMatrices.length),
+ meshWorld: mat4.create(), meshInverse: mat4.create(), bind: mat4.create(), world: mat4.create(), inverseBind: mat4.create(), product: mat4.create(),
+ });
+ return pose;
+}
+
+/** Atomically calculate inverse(meshWorld) * jointWorld * inverseBind * bindMatrix. */
+export function updateSkinPose(pose, jointWorldMatrices, inverseBindMatrices, meshWorldMatrix = IDENTITY_MATRIX, bindMatrix = IDENTITY_MATRIX) {
+ const workspace = poseWorkspaces.get(pose);
+ if (!workspace || pose.jointMatrices !== workspace.jointMatrices) throw new Error('Use an unchanged pose from createSkinPose().');
+ const count = pose.jointMatrices.length / 16;
+ validateMatrices(jointWorldMatrices, count, 'Joint world matrices');
+ validateMatrices(inverseBindMatrices, count, 'Inverse bind matrices');
+ validateMatrices(meshWorldMatrix, 1, 'Mesh world matrix');
+ validateMatrices(bindMatrix, 1, 'Bind matrix');
+ workspace.meshWorld.set(meshWorldMatrix);
+ workspace.bind.set(bindMatrix);
+ if (!mat4.invert(workspace.meshInverse, workspace.meshWorld)) throw new Error('Mesh world matrix cannot be inverted.');
+ validateMatrices(workspace.meshInverse, 1, 'Inverse mesh world matrix');
+ for (let joint = 0; joint < count; joint++) {
+ const offset = joint * 16;
+ for (let component = 0; component < 16; component++) {
+ workspace.world[component] = jointWorldMatrices[offset + component];
+ workspace.inverseBind[component] = inverseBindMatrices[offset + component];
+ }
+ mat4.multiply(workspace.product, workspace.world, workspace.inverseBind);
+ mat4.multiply(workspace.product, workspace.product, workspace.bind);
+ mat4.multiply(workspace.product, workspace.meshInverse, workspace.product);
+ workspace.pending.set(workspace.product, offset);
+ }
+ validateMatrices(workspace.pending, count, 'Joint palette');
+ pose.jointMatrices.set(workspace.pending);
+ return pose;
+}
+
+export function skinTextureLayout(texelCount, maximumSize, groupSize = 1) {
+ if (!Number.isSafeInteger(texelCount) || texelCount < 1 || !Number.isInteger(maximumSize) || maximumSize < groupSize) throw new Error('Invalid skin texture dimensions.');
+ const width = Math.min(Math.floor(maximumSize / groupSize) * groupSize, Math.max(groupSize, Math.ceil(Math.sqrt(texelCount) / groupSize) * groupSize));
+ const height = Math.ceil(texelCount / width);
+ if (height > maximumSize) throw new Error('Skin texture exceeds MAX_TEXTURE_SIZE.');
+ return { width, height, bytes: width * height * 16 };
+}
+
+export function validateSkinGeometry(geometry, pose) {
+ if (!pose) {
+ if (geometry.skinIndices || geometry.skinWeights) throw new Error('Skin attributes require a skin pose.');
+ return;
+ }
+ const jointCount = pose.jointMatrices?.length / 16;
+ if (!Number.isInteger(jointCount) || jointCount < 1 || jointCount > 65536 || !(pose.jointMatrices instanceof Float32Array)) throw new Error('Skin pose requires a Float32 joint palette.');
+ const vertexCount = geometry.positions.length / 3;
+ if (geometry.skinIndices?.length !== vertexCount * 4 || geometry.skinWeights?.length !== vertexCount * 4) throw new Error('Skin indices and weights require four values per vertex.');
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ let total = 0;
+ for (let influence = 0; influence < 4; influence++) {
+ const offset = vertex * 4 + influence;
+ const joint = geometry.skinIndices[offset];
+ const weight = geometry.skinWeights[offset];
+ if (!Number.isInteger(joint) || joint < 0 || joint >= jointCount) throw new Error('Skin joint index is out of range.');
+ if (!finiteFloat(weight) || weight < 0 || weight > 1) throw new Error('Skin weights must be finite values within zero and one.');
+ total += weight;
+ }
+ if (total <= 1e-8) throw new Error('Skin vertex weights must have a positive total.');
+ }
+ validateSkinPose(pose, geometry);
+}
+
+/** Validate weighted normal transforms without allocating temporary matrices. */
+export function validateSkinPose(pose, geometry, worldMatrix) {
+ const matrices = pose.jointMatrices;
+ validateMatrices(matrices, matrices.length / 16, 'Joint palette');
+ if (!geometry) return;
+ for (let vertex = 0; vertex < geometry.skinWeights.length / 4; vertex++) {
+ let matrixXX = 0;
+ let matrixYX = 0;
+ let matrixZX = 0;
+ let matrixXY = 0;
+ let matrixYY = 0;
+ let matrixZY = 0;
+ let matrixXZ = 0;
+ let matrixYZ = 0;
+ let matrixZZ = 0;
+ let total = 0;
+ for (let influence = 0; influence < 4; influence++) total += geometry.skinWeights[vertex * 4 + influence];
+ for (let influence = 0; influence < 4; influence++) {
+ const weight = Math.fround(geometry.skinWeights[vertex * 4 + influence] / total);
+ const offset = geometry.skinIndices[vertex * 4 + influence] * 16;
+ matrixXX += matrices[offset] * weight;
+ matrixYX += matrices[offset + 1] * weight;
+ matrixZX += matrices[offset + 2] * weight;
+ matrixXY += matrices[offset + 4] * weight;
+ matrixYY += matrices[offset + 5] * weight;
+ matrixZY += matrices[offset + 6] * weight;
+ matrixXZ += matrices[offset + 8] * weight;
+ matrixYZ += matrices[offset + 9] * weight;
+ matrixZZ += matrices[offset + 10] * weight;
+ }
+ const determinant = matrixXX * (matrixYY * matrixZZ - matrixYZ * matrixZY) - matrixXY * (matrixYX * matrixZZ - matrixYZ * matrixZX) + matrixXZ * (matrixYX * matrixZY - matrixYY * matrixZX);
+ if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-8) throw new Error('Skin pose produces a singular weighted vertex transform.');
+ if (worldMatrix && determinant * matrixDeterminant(worldMatrix, 0) < 0) throw new Error('Reflected weighted skin transforms are unsupported.');
+ }
+}
+
+export function packSkinInfluences(geometry, layout) {
+ const data = new Float32Array(layout.width * layout.height * 4);
+ for (let vertex = 0; vertex < geometry.skinWeights.length / 4; vertex++) {
+ let total = 0;
+ for (let influence = 0; influence < 4; influence++) total += geometry.skinWeights[vertex * 4 + influence];
+ for (let influence = 0; influence < 4; influence++) {
+ data[vertex * 8 + influence] = geometry.skinIndices[vertex * 4 + influence];
+ data[vertex * 8 + 4 + influence] = Math.fround(geometry.skinWeights[vertex * 4 + influence] / total);
+ }
+ }
+ return data;
+}
diff --git a/tests/export.test.js b/tests/export.test.js
index 0ffb1c8b..a5ae337d 100644
--- a/tests/export.test.js
+++ b/tests/export.test.js
@@ -24,3 +24,9 @@ test('GLB export refuses to silently discard any material texture channel', () =
error => error instanceof RangeError && error.message.includes(channel));
}
});
+
+test('GLB export rejects skinning instead of silently saving the undeformed bind mesh', () => {
+ const part = createModel()[0];
+ assert.throws(() => exportGlb([{ ...part, skin: { jointMatrices: new Float32Array(16) } }]), /preserve skinning/);
+ assert.throws(() => exportGlb([{ ...part, geometry: { ...part.geometry, skinIndices: new Uint16Array(4) } }]), /preserve skinning/);
+});
diff --git a/tests/fixtures/skinned-strip.js b/tests/fixtures/skinned-strip.js
new file mode 100644
index 00000000..2e9384c4
--- /dev/null
+++ b/tests/fixtures/skinned-strip.js
@@ -0,0 +1,64 @@
+/** Two-joint strip with blended middle vertices and a visibly bending upper segment. */
+export function skinnedStripAsset(edit = () => {}) {
+ const chunks = [];
+ const document = {
+ asset: { version: '2.0' }, scene: 0,
+ scenes: [{ nodes: [0] }],
+ nodes: [
+ { name: 'Character', translation: [1, 2, 0], children: [1, 2] },
+ { name: 'Strip', mesh: 0, skin: 0 },
+ { name: 'Root', children: [3] },
+ { name: 'Tip', translation: [0, 1, 0] },
+ ],
+ meshes: [{ primitives: [{ attributes: {}, material: 0 }] }],
+ materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.7, 0.2, 0.1, 1], metallicFactor: 0.1, roughnessFactor: 0.6 } }],
+ accessors: [], bufferViews: [], buffers: [{ byteLength: 0 }],
+ skins: [{ joints: [2, 3], skeleton: 2 }],
+ animations: [],
+ };
+ let offset = 0;
+ function append(data, type, normalized = false) {
+ const components = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16 }[type];
+ const accessor = document.accessors.length;
+ chunks.push(data);
+ document.bufferViews.push({ buffer: 0, byteOffset: offset, byteLength: data.byteLength });
+ offset += Math.ceil(data.byteLength / 4) * 4;
+ document.buffers[0].byteLength = offset;
+ document.accessors.push({ bufferView: chunks.length - 1, componentType: data instanceof Uint16Array ? 5123 : data instanceof Uint8Array ? 5121 : 5126, count: data.length / components, type, normalized });
+ return accessor;
+ }
+ const primitive = document.meshes[0].primitives[0];
+ primitive.attributes.POSITION = append(new Float32Array([-0.3, 0, 0, 0.3, 0, 0, -0.3, 1, 0, 0.3, 1, 0, -0.3, 2, 0, 0.3, 2, 0]), 'VEC3');
+ document.accessors[primitive.attributes.POSITION].min = [-0.3, 0, 0];
+ document.accessors[primitive.attributes.POSITION].max = [0.3, 2, 0];
+ primitive.attributes.NORMAL = append(new Float32Array(Array.from({ length: 6 }, () => [0, 0, 1]).flat()), 'VEC3');
+ primitive.attributes.TEXCOORD_0 = append(new Float32Array([0, 0, 1, 0, 0, 0.5, 1, 0.5, 0, 1, 1, 1]), 'VEC2');
+ primitive.attributes.JOINTS_0 = append(new Uint16Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]), 'VEC4');
+ primitive.attributes.WEIGHTS_0 = append(new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 0.5, 0.5, 0, 0, 0.5, 0.5, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]), 'VEC4');
+ primitive.indices = append(new Uint16Array([0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5]), 'SCALAR');
+ document.skins[0].inverseBindMatrices = append(new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -1, 0, 1]), 'MAT4');
+ const times = append(new Float32Array([0, 2]), 'SCALAR');
+ const rotations = append(new Float32Array([0, 0, 0, 1, 0, 0, Math.SQRT1_2, Math.SQRT1_2]), 'VEC4');
+ const translations = append(new Float32Array([0, 0, 0, 2, 0, 0]), 'VEC3');
+ document.animations = [
+ { name: 'Bend', samplers: [{ input: times, output: rotations, interpolation: 'LINEAR' }], channels: [{ sampler: 0, target: { node: 3, path: 'rotation' } }] },
+ { name: 'Move', samplers: [{ input: times, output: translations, interpolation: 'LINEAR' }], channels: [{ sampler: 0, target: { node: 2, path: 'translation' } }] },
+ ];
+ edit(document, append, chunks);
+ const json = new TextEncoder().encode(JSON.stringify(document));
+ const jsonLength = Math.ceil(json.length / 4) * 4;
+ const result = new ArrayBuffer(28 + jsonLength + offset);
+ 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, offset, true);
+ header.setUint32(24 + jsonLength, 0x004e4942, true);
+ chunks.forEach((chunk, index) => bytes.set(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength), 28 + jsonLength + document.bufferViews[index].byteOffset));
+ return result;
+}
diff --git a/tests/gltf.test.js b/tests/gltf.test.js
index 7a5987b5..fcede355 100644
--- a/tests/gltf.test.js
+++ b/tests/gltf.test.js
@@ -1,6 +1,9 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { Texture } from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { Matrix4, Vector3 } from 'three';
+import { skinnedStripAsset } from './fixtures/skinned-strip.js';
import { mat4 } from 'gl-matrix';
import { exportGlb } from '../src/export.js';
import { GLTF_CAPABILITIES, loadGltf, parseGltf } from '../src/gltf.js';
@@ -137,7 +140,7 @@ 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; }, /Skinned/],
+ [document => { document.nodes[1].skin = 0; }, /skin index/],
[document => { document.meshes[0].primitives[0].targets = [{ POSITION: 0 }]; }, /Morph/],
[document => { document.meshes[0].primitives[0].attributes.COLOR_0 = 1; }, /COLOR_0/],
[document => { document.meshes[0].primitives[0].mode = 1; }, /TRIANGLES/],
@@ -365,3 +368,109 @@ test('map preflight rejects unsupported UVs, sampler states, invalid scales and
}
await assert.rejects(parseGltf(triangleAsset(addMaterialMaps), { maxTexturePixels: 3 }), /maxTexturePixels/);
});
+
+function skinPosition(part, vertex) {
+ const result = new Vector3();
+ const input = new Vector3().fromArray(part.geometry.positions, vertex * 3);
+ for (let influence = 0; influence < 4; influence++) {
+ const offset = vertex * 4 + influence;
+ const matrix = new Matrix4().fromArray(part.skin.jointMatrices, part.geometry.skinIndices[offset] * 16);
+ result.addScaledVector(input.clone().applyMatrix4(matrix), part.geometry.skinWeights[offset]);
+ }
+ return result.applyMatrix4(new Matrix4().fromArray(part.matrix));
+}
+
+test('GLB skin import retains inverse binds, ordered bones and deterministic visibly bent poses matching Three', async () => {
+ const data = skinnedStripAsset();
+ const asset = await parseGltf(data);
+ const part = asset.parts[0];
+ const palette = part.skin.jointMatrices;
+ const matrix = part.matrix;
+ assert.equal(asset.skins.length, 1);
+ assert.equal(asset.skins[0], part.skin);
+ assert.deepEqual(part.skin.joints.map(joint => joint.name), ['Root', 'Tip']);
+ assert.deepEqual(part.skin.joints.map(joint => joint.parent), [-1, 0]);
+ assert.equal(part.skin.inverseBindMatrices[29], -1);
+ const restTop = skinPosition(part, 4);
+ const restBottom = skinPosition(part, 0);
+ asset.applyAnimation(2);
+ assert.ok(skinPosition(part, 4).distanceTo(restTop) > 1);
+ assert.ok(skinPosition(part, 0).distanceTo(restBottom) < 1e-6, 'lower vertices stay fixed while upper vertices bend');
+ const bent = Array.from(palette);
+ asset.applyAnimation(0.4);
+ asset.applyAnimation(2);
+ assert.deepEqual(Array.from(palette), bent);
+ asset.applyAnimation(2, 1);
+ asset.applyAnimation(2, 0);
+ assert.deepEqual(Array.from(palette), bent, 'switching clips restores unanimated bone properties');
+ assert.equal(part.skin.jointMatrices, palette);
+ assert.equal(part.matrix, matrix);
+ const decoded = await new GLTFLoader().parseAsync(data, '');
+ decoded.scene.updateMatrixWorld(true);
+ let mesh;
+ decoded.scene.traverse(node => { if (node.isSkinnedMesh) mesh = node; });
+ mesh.skeleton.bones[1].rotation.z = Math.PI / 2;
+ decoded.scene.updateMatrixWorld(true);
+ for (let vertex = 0; vertex < 6; vertex++) {
+ const expected = mesh.applyBoneTransform(vertex, new Vector3().fromBufferAttribute(mesh.geometry.getAttribute('position'), vertex)).applyMatrix4(mesh.matrixWorld);
+ assert.ok(skinPosition(part, vertex).distanceTo(expected) < 1e-6);
+ }
+ mesh.geometry.dispose();
+ mesh.material.dispose();
+ mesh.skeleton.dispose();
+ asset.dispose();
+ assert.throws(() => asset.applyAnimation(1), /disposed/);
+});
+
+test('skin preflight guards joints, influence shapes, raw zero weights, indices and budgets', async () => {
+ const cases = [
+ [document => { document.skins[0].joints = [2, 2]; }, /distinct/],
+ [document => { document.skins[0].joints = [2, 9]; }, /valid node/],
+ [document => { document.accessors[document.skins[0].inverseBindMatrices].type = 'VEC4'; }, /Inverse bind/],
+ [document => { document.meshes[0].primitives[0].attributes.JOINTS_1 = 0; }, /four/],
+ [document => { delete document.meshes[0].primitives[0].attributes.WEIGHTS_0; }, /JOINTS_0/],
+ [(document, append, chunks) => { chunks[document.meshes[0].primitives[0].attributes.WEIGHTS_0].fill(0); }, /positive total/],
+ [(document, append, chunks) => { chunks[document.meshes[0].primitives[0].attributes.JOINTS_0][0] = 9; }, /index/],
+ [(document, append, chunks) => { chunks[document.meshes[0].primitives[0].attributes.WEIGHTS_0][0] = -0.2; }, /weights/],
+ ];
+ for (const [edit, expected] of cases) await assert.rejects(parseGltf(skinnedStripAsset(edit)), expected);
+ await assert.rejects(parseGltf(skinnedStripAsset(), { maxJoints: 1 }), /maxJoints/);
+ await assert.rejects(parseGltf(skinnedStripAsset(document => {
+ document.nodes.push({ name: 'Second strip', mesh: 0, skin: 0 });
+ document.nodes[0].children.push(4);
+ }), { maxJoints: 2 }), /Instanced skin poses/);
+});
+
+test('invalid skeletal animation fails before public matrices or palettes change', async () => {
+ const asset = await parseGltf(skinnedStripAsset((document, append) => {
+ const scales = append(new Float32Array([1, 1, 1, 0, 1, 1]), 'VEC3');
+ document.animations[0].samplers[0].output = scales;
+ document.animations[0].channels[0].target.path = 'scale';
+ }));
+ const part = asset.parts[0];
+ const matrix = Array.from(part.matrix);
+ const palette = Array.from(part.skin.jointMatrices);
+ const world = Array.from(part.skin.jointWorldMatrices);
+ assert.throws(() => asset.applyAnimation(2), /singular/);
+ assert.deepEqual(Array.from(part.matrix), matrix);
+ assert.deepEqual(Array.from(part.skin.jointMatrices), palette);
+ assert.deepEqual(Array.from(part.skin.jointWorldMatrices), world);
+ asset.applyAnimation(0);
+ assert.deepEqual(Array.from(part.skin.jointMatrices), palette);
+ asset.dispose();
+});
+
+test('normalized integer skin weights import correctly and skinned mesh node transforms cancel without reversed winding', async () => {
+ const asset = await parseGltf(skinnedStripAsset((document, append) => {
+ const weights = new Uint8Array([255, 0, 0, 0, 255, 0, 0, 0, 128, 127, 0, 0, 128, 127, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0]);
+ document.meshes[0].primitives[0].attributes.WEIGHTS_0 = append(weights, 'VEC4', true);
+ document.nodes[1].scale = [-1, 1, 1];
+ }));
+ const part = asset.parts[0];
+ assert.deepEqual(Array.from(part.geometry.indices.subarray(0, 3)), [0, 1, 2]);
+ assert.ok(Math.abs(part.geometry.skinWeights[8] - 128 / 255) < 1e-6);
+ assert.ok(skinPosition(part, 0).distanceTo(new Vector3(0.7, 2, 0)) < 1e-6);
+ asset.applyAnimation(2);
+ assert.ok(skinPosition(part, 4).x < 0.1);
+ asset.dispose();
+});
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index 6123c7bb..2f8390f3 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -2,6 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { mat4, mat3 } from 'gl-matrix';
import { Renderer67, groupParts, textureDescriptorInfo } from '../src/renderer.js';
+import { createSkinPose } from '../src/skinning.js';
function part(name, geometry = {}, map) {
return { name, geometry, matrix: mat4.create(), material: { color: [0.1, 0.2, 0.3], metallic: 0.5, roughness: 0.3, emission: 0, map } };
@@ -13,10 +14,12 @@ function retainedRenderer(parts) {
const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).fill(7) };
renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { writes.push({ target, offset, data: Array.from(data) }); } };
renderer.partLocations = new Map(parts.map((item, index) => [item, {
- batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(),
+ batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(), skin: item.skin ?? null,
+ jointMatrices: item.skin?.jointMatrices, skinIndices: item.geometry.skinIndices, skinWeights: item.geometry.skinWeights,
mapState: ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'].map(field => item.material[field] ?? null).concat(item.material.normalScale ?? [1, 1], item.material.occlusionStrength ?? 1),
}]));
renderer.updateBatches = new Set();
+ renderer.updateSkins = new Set();
renderer.shadowsDirty = false;
return { renderer, batch, writes };
}
@@ -152,11 +155,17 @@ test('map and scale changes reject atomically before retained data uploads', ()
assert.throws(() => groupParts([procedural]), /Unlit materials/);
});
-function preflightCanvas() {
+function preflightCanvas({ vertexUnits = 2, combinedUnits = 8, maximumSize = 8192 } = {}) {
const context = {
MAX_TEXTURE_SIZE: 3379, MAX_SAMPLES: 36183,
+ MAX_VERTEX_TEXTURE_IMAGE_UNITS: 35660, MAX_COMBINED_TEXTURE_IMAGE_UNITS: 35661,
getInternalformatParameter() { return []; },
- getParameter(parameter) { return parameter === this.MAX_TEXTURE_SIZE ? 8192 : 4; },
+ getParameter(parameter) {
+ if (parameter === this.MAX_TEXTURE_SIZE) return maximumSize;
+ if (parameter === this.MAX_VERTEX_TEXTURE_IMAGE_UNITS) return vertexUnits;
+ if (parameter === this.MAX_COMBINED_TEXTURE_IMAGE_UNITS) return combinedUnits;
+ return 4;
+ },
createProgram() { throw new Error('Reached GPU allocation'); },
};
return { clientWidth: 64, clientHeight: 64, getContext() { return context; } };
@@ -228,3 +237,156 @@ test('draw batches bind all channels with their flags and scalar uniforms', () =
assert.ok(uniforms.some(values => values[0] === 'normalScale' && values[1] === 0.5 && values[2] === -1));
assert.ok(uniforms.some(values => values[0] === 'occlusionStrength' && values[1] === 0.4));
});
+
+function skinGeometry(vertexCount = 3) {
+ const geometry = {
+ positions: new Float32Array(vertexCount * 3), normals: new Float32Array(vertexCount * 3),
+ indices: new Uint32Array([0, 1, 2]), skinIndices: new Uint16Array(vertexCount * 4), skinWeights: new Float32Array(vertexCount * 4),
+ };
+ for (let vertex = 0; vertex < vertexCount; vertex++) geometry.skinWeights[vertex * 4] = 1;
+ return geometry;
+}
+
+test('pose identity partitions batches while shared poses retain instancing and all material maps', () => {
+ const geometry = skinGeometry();
+ const pose = createSkinPose(2);
+ const first = part('first pose', geometry);
+ const second = part('shared pose', geometry);
+ first.skin = pose;
+ second.skin = pose;
+ first.material.normalMap = second.material.normalMap = {};
+ assert.equal(groupParts([first, second]).length, 1);
+ second.skin = createSkinPose(2);
+ assert.equal(groupParts([first, second]).length, 2);
+ second.skin = pose;
+ second.material.emissiveMap = {};
+ assert.equal(groupParts([first, second]).length, 2);
+});
+
+test('GPU skin preflight checks capabilities, texture capacity and retained texture budgets', () => {
+ const item = part('skin', skinGeometry());
+ item.skin = createSkinPose(2);
+ assert.throws(() => new Renderer67(preflightCanvas({ vertexUnits: 1 }), [item], { ground: false }), /vertex texture units/);
+ assert.throws(() => new Renderer67(preflightCanvas({ combinedUnits: 7 }), [item], { ground: false }), /combined texture units/);
+ item.skin = createSkinPose(17);
+ assert.throws(() => new Renderer67(preflightCanvas({ maximumSize: 8 }), [item], { ground: false }), /MAX_TEXTURE_SIZE/);
+ item.geometry = skinGeometry(1000);
+ item.skin = createSkinPose(2);
+ assert.throws(() => new Renderer67(preflightCanvas(), [item], { ground: false, memoryBudgetMiB: 16.16 }), /Memory budget/);
+ const rigid = part('rigid', { positions: item.geometry.positions, normals: item.geometry.normals, indices: item.geometry.indices });
+ assert.throws(() => new Renderer67(preflightCanvas(), [rigid], { ground: false, memoryBudgetMiB: 16.16 }), /Reached GPU allocation/);
+});
+
+test('skin updates retain palette upload data, deduplicate shared poses and reject mixed invalid updates atomically', () => {
+ const geometry = skinGeometry();
+ const pose = createSkinPose(2);
+ const first = part('first', geometry);
+ const second = part('second', geometry);
+ first.skin = second.skin = pose;
+ const { renderer, batch, writes } = retainedRenderer([first, second]);
+ const record = { pose, texture: {}, width: 4, height: 2, data: new Float32Array(pose.jointMatrices) };
+ batch.skinTexture = record;
+ const uploads = [];
+ renderer.context.bindTexture = () => {};
+ renderer.context.texSubImage2D = (...arguments_) => uploads.push(arguments_);
+ pose.jointMatrices[12] = 2;
+ second.matrix[0] = 0;
+ assert.throws(() => renderer.updateParts([first, second]), /Singular/);
+ assert.ok(batch.instanceData.every(value => value === 7));
+ assert.equal(record.data[12], 0);
+ assert.equal(writes.length, 0);
+ assert.equal(uploads.length, 0);
+ second.matrix[0] = 1;
+ const data = record.data;
+ renderer.updateParts([first, second]);
+ assert.equal(record.data, data);
+ assert.equal(uploads.length, 1);
+ assert.equal(uploads[0][8], data);
+ assert.equal(data[12], 2);
+ assert.equal(writes.length, 1);
+ pose.jointMatrices[0] = 0;
+ assert.throws(() => renderer.updateParts([first]), /singular/);
+ assert.equal(uploads.length, 1);
+ pose.jointMatrices[0] = 1;
+ first.skin = createSkinPose(2);
+ assert.throws(() => renderer.updateParts([first]), /Skin identity/);
+ assert.equal(uploads.length, 1);
+});
+
+test('skin palette and influence textures cache by pose and geometry identity and dispose fully', () => {
+ const renderer = Object.create(Renderer67.prototype);
+ const allocations = [];
+ const deleted = [];
+ renderer.context = {
+ getParameter() { return 8192; }, createTexture() { return {}; }, bindTexture() {}, texParameteri() {},
+ texImage2D(...arguments_) { allocations.push(arguments_); }, deleteTexture(texture) { if (texture) deleted.push(texture); },
+ deleteFramebuffer() {}, deleteProgram() {},
+ };
+ renderer.skinTextures = new Map();
+ renderer.influenceTextures = new Map();
+ const pose = createSkinPose(2);
+ const geometry = skinGeometry();
+ const palette = renderer.createSkinTexture(renderer.skinTextures, pose, pose.jointMatrices, 4);
+ const influences = renderer.createSkinTexture(renderer.influenceTextures, geometry, null, 2);
+ assert.equal(renderer.createSkinTexture(renderer.skinTextures, pose, pose.jointMatrices, 4), palette);
+ assert.equal(renderer.createSkinTexture(renderer.influenceTextures, geometry, null, 2), influences);
+ assert.equal(allocations.length, 2);
+ renderer.releaseFrameTargets = () => {};
+ renderer.batches = [];
+ renderer.buffers = [];
+ renderer.textures = new Map();
+ renderer.partLocations = new Map();
+ renderer.dispose();
+ assert.deepEqual(deleted, [palette.texture, influences.texture]);
+ assert.equal(renderer.skinTextures.size, 0);
+ assert.equal(renderer.influenceTextures.size, 0);
+});
+
+test('a shared palette validates consumers outside the submitted update list before any upload', () => {
+ const pose = createSkinPose(2);
+ const first = part('single joint', skinGeometry());
+ const second = part('blended joints', skinGeometry());
+ for (let vertex = 0; vertex < 3; vertex++) {
+ second.geometry.skinIndices[vertex * 4 + 1] = 1;
+ second.geometry.skinWeights[vertex * 4] = 0.5;
+ second.geometry.skinWeights[vertex * 4 + 1] = 0.5;
+ }
+ first.skin = second.skin = pose;
+ const { renderer, batch, writes } = retainedRenderer([first, second]);
+ batch.skinTexture = { pose, texture: {}, data: new Float32Array(pose.jointMatrices) };
+ const uploads = [];
+ renderer.context.bindTexture = () => {};
+ renderer.context.texSubImage2D = () => uploads.push(true);
+ renderer.updateParts([first, second]);
+ writes.length = 0;
+ uploads.length = 0;
+ const before = new Float32Array(batch.instanceData);
+ pose.jointMatrices[16] = -1;
+ pose.jointMatrices[21] = -1;
+ assert.throws(() => renderer.updateParts([first]), /singular/);
+ assert.deepEqual(batch.instanceData, before);
+ assert.equal(writes.length, 0);
+ assert.equal(uploads.length, 0);
+});
+
+test('color, benchmark and shadow passes bind the same skin textures and disable skinning for rigid batches', () => {
+ const renderer = Object.create(Renderer67.prototype);
+ renderer.hasSkins = true;
+ renderer.benchmark = true;
+ renderer.uniforms = { skinEnabled: 'color enabled', skinInfluences: 'color influences', jointPalette: 'color palette' };
+ renderer.depthSkinUniforms = { skinEnabled: 'shadow enabled', skinInfluences: 'shadow influences', jointPalette: 'shadow palette' };
+ const uniforms = [];
+ const bindings = [];
+ renderer.context = {
+ TEXTURE0: 33984, activeTexture(unit) { bindings.push(unit); }, bindTexture() {}, bindVertexArray() {}, drawElementsInstanced() {},
+ uniform1f(name, value) { uniforms.push([name, value]); }, uniform1i(name, value) { uniforms.push([name, value]); },
+ };
+ const batch = { skin: {}, skinTexture: { texture: {} }, influenceTexture: { texture: {} } };
+ renderer.drawBatch(batch, true);
+ renderer.drawBatch(batch);
+ renderer.drawBatch({});
+ assert.deepEqual(bindings, [33990, 33991, 33990, 33991]);
+ assert.ok(uniforms.some(([name, value]) => name === 'color enabled' && value === 1));
+ assert.ok(uniforms.some(([name, value]) => name === 'shadow enabled' && value === 1));
+ assert.deepEqual(uniforms.at(-1), ['shadow enabled', 0]);
+});
diff --git a/tests/skinning.test.js b/tests/skinning.test.js
new file mode 100644
index 00000000..7c73f790
--- /dev/null
+++ b/tests/skinning.test.js
@@ -0,0 +1,182 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4 } from 'gl-matrix';
+import { Bone, Skeleton, SkinnedMesh, BufferGeometry, Float32BufferAttribute, Uint16BufferAttribute, Matrix4, Matrix3, Vector3 } from 'three';
+import { createSkinPose, updateSkinPose, validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from '../src/skinning.js';
+
+function influences() {
+ return { positions: new Float32Array([0.2, 1, 0]), skinIndices: new Uint16Array([0, 1, 0, 0]), skinWeights: new Float32Array([0.3, 0.7, 0, 0]) };
+}
+
+test('mesh-local palette produces the same bent position as Three.js with inverse binds and mesh transforms', () => {
+ const root = new Bone();
+ const child = new Bone();
+ root.add(child);
+ child.position.y = 1;
+ root.updateMatrixWorld(true);
+ const skeleton = new Skeleton([root, child]);
+ const geometry = new BufferGeometry();
+ const input = influences();
+ geometry.setAttribute('position', new Float32BufferAttribute(input.positions, 3));
+ geometry.setAttribute('skinIndex', new Uint16BufferAttribute(input.skinIndices, 4));
+ geometry.setAttribute('skinWeight', new Float32BufferAttribute(input.skinWeights, 4));
+ const mesh = new SkinnedMesh(geometry);
+ mesh.position.set(2, 3, 0);
+ mesh.updateMatrixWorld(true);
+ mesh.bind(skeleton, new Matrix4().makeTranslation(0.5, 0, 0));
+ child.rotation.z = 0.8;
+ child.scale.set(2, 0.7, 1);
+ root.updateMatrixWorld(true);
+ mesh.updateMatrixWorld(true);
+ const world = new Float32Array(32);
+ const inverse = new Float32Array(32);
+ [root, child].forEach((bone, index) => {
+ world.set(bone.matrixWorld.elements, index * 16);
+ inverse.set(skeleton.boneInverses[index].elements, index * 16);
+ });
+ const pose = createSkinPose(2);
+ updateSkinPose(pose, world, inverse, mesh.matrixWorld.elements, mesh.bindMatrix.elements);
+ validateSkinGeometry(input, pose);
+ const expected = mesh.applyBoneTransform(0, new Vector3(...input.positions));
+ const actual = new Vector3();
+ for (let influence = 0; influence < 4; influence++) {
+ const joint = input.skinIndices[influence];
+ actual.addScaledVector(new Vector3(...input.positions).applyMatrix4(new Matrix4().fromArray(pose.jointMatrices, joint * 16)), input.skinWeights[influence]);
+ }
+ assert.ok(actual.distanceTo(expected) < 1e-6);
+ const blended = new Matrix4();
+ blended.elements.fill(0);
+ for (let component = 0; component < 16; component++) blended.elements[component] = pose.jointMatrices[component] * 0.3 + pose.jointMatrices[16 + component] * 0.7;
+ const normal = new Vector3(1, 1, 0).normalize();
+ const correct = normal.clone().applyMatrix3(new Matrix3().getNormalMatrix(blended)).normalize();
+ const threeDirection = normal.clone().transformDirection(blended);
+ assert.ok(correct.distanceTo(threeDirection) > 0.1, 'nonuniform scaling requires inverse-transpose, unlike Three skin normal chunk');
+ const tangent = new Vector3(1, -1, 0).transformDirection(blended);
+ assert.ok(Math.abs(correct.dot(tangent)) < 1e-6);
+ geometry.dispose();
+ mesh.material.dispose();
+ skeleton.dispose();
+});
+
+test('pose update retains buffers and rejects invalid input atomically', context => {
+ const pose = createSkinPose(2);
+ const matrices = pose.jointMatrices;
+ const world = new Float32Array(matrices);
+ const inverses = new Float32Array(matrices);
+ world[28] = 2;
+ context.mock.method(mat4, 'create', () => { throw new Error('Per-frame matrix allocation'); });
+ updateSkinPose(pose, world, inverses);
+ assert.equal(pose.jointMatrices, matrices);
+ assert.equal(matrices[28], 2);
+ const before = Array.from(matrices);
+ world[16] = 0;
+ assert.throws(() => updateSkinPose(pose, world, inverses), /singular/);
+ assert.deepEqual(Array.from(matrices), before);
+ world[16] = Infinity;
+ assert.throws(() => updateSkinPose(pose, world, inverses), /finite/);
+ assert.deepEqual(Array.from(matrices), before);
+ assert.throws(() => createSkinPose(0), /Joint count/);
+});
+
+test('influences normalize explicitly without modifying inputs and guard malformed skin data', () => {
+ const geometry = influences();
+ const pose = createSkinPose(2);
+ geometry.skinWeights.set([0.2, 0.2, 0, 0]);
+ validateSkinGeometry(geometry, pose);
+ const layout = skinTextureLayout(2, 16, 2);
+ const data = packSkinInfluences(geometry, layout);
+ assert.deepEqual(Array.from(data.subarray(0, 8)), [0, 1, 0, 0, 0.5, 0.5, 0, 0]);
+ assert.ok(Math.abs(geometry.skinWeights[0] - 0.2) < 1e-7);
+ geometry.skinWeights.fill(0);
+ assert.throws(() => validateSkinGeometry(geometry, pose), /positive total/);
+ geometry.skinWeights[0] = -1;
+ assert.throws(() => validateSkinGeometry(geometry, pose), /weights/);
+ geometry.skinWeights[0] = NaN;
+ assert.throws(() => validateSkinGeometry(geometry, pose), /weights/);
+ geometry.skinWeights[0] = 1;
+ geometry.skinIndices[0] = 2;
+ assert.throws(() => validateSkinGeometry(geometry, pose), /index/);
+ assert.throws(() => validateSkinGeometry(geometry, null), /pose/);
+ assert.throws(() => validateSkinGeometry({ ...geometry, skinWeights: new Float32Array(3) }, pose), /four values/);
+});
+
+test('singular weighted transforms and texture capacity limits fail explicitly', () => {
+ const pose = createSkinPose(2);
+ const geometry = influences();
+ geometry.skinWeights.set([0.5, 0.5, 0, 0]);
+ mat4.fromScaling(pose.jointMatrices.subarray(16), [-1, -1, 1]);
+ assert.throws(() => validateSkinPose(pose, geometry), /weighted vertex/);
+ assert.throws(() => skinTextureLayout(65, 8, 4), /MAX_TEXTURE_SIZE/);
+ assert.equal(skinTextureLayout(64, 8, 4).bytes, 1024);
+});
+
+test('Float64 influences that round to a singular GPU blend are rejected', () => {
+ const pose = createSkinPose(2);
+ mat4.fromScaling(pose.jointMatrices.subarray(16), [-1, 1, 1]);
+ const geometry = influences();
+ geometry.skinWeights = new Float64Array([0.500000007, 0.499999993, 0, 0]);
+ const packed = packSkinInfluences(geometry, skinTextureLayout(2, 16, 2));
+ assert.deepEqual(Array.from(packed.subarray(4, 8)), [0.5, 0.5, 0, 0]);
+ assert.throws(() => validateSkinGeometry(geometry, pose), /singular weighted vertex/);
+ assert.throws(() => validateSkinPose(pose, geometry), /singular weighted vertex/);
+});
+
+test('near-affine singular mesh input cannot reuse a stale inverse or mutate the palette', () => {
+ const pose = createSkinPose(1);
+ const world = new Float64Array(pose.jointMatrices);
+ const inverseBind = new Float64Array(pose.jointMatrices);
+ const initialMesh = new Float64Array(pose.jointMatrices);
+ initialMesh[12] = 3;
+ updateSkinPose(pose, world, inverseBind, initialMesh);
+ const before = Array.from(pose.jointMatrices);
+ const invalidMesh = new Float64Array(mat4.create());
+ invalidMesh[3] = 1e-6;
+ invalidMesh[12] = 1e6;
+ assert.equal(mat4.determinant(invalidMesh), 0);
+ assert.throws(() => updateSkinPose(pose, world, inverseBind, invalidMesh), /affine/);
+ assert.deepEqual(Array.from(pose.jointMatrices), before);
+});
+
+test('matrix preflight rejects singular Float32 rounding for every pose input atomically', context => {
+ const pose = createSkinPose(1);
+ const identity = new Float64Array(pose.jointMatrices);
+ const roundedSingular = new Float64Array(identity);
+ roundedSingular[0] = 1;
+ roundedSingular[1] = 1;
+ roundedSingular[4] = 1;
+ roundedSingular[5] = 1.00000001;
+ assert.ok(mat4.determinant(roundedSingular) > 1e-10);
+ assert.equal(mat4.determinant(new Float32Array(roundedSingular)), 0);
+ const before = Array.from(pose.jointMatrices);
+ context.mock.method(mat4, 'multiply', () => { throw new Error('Math ran before Float32 input validation'); });
+ for (let input = 0; input < 4; input++) {
+ const inputs = [identity, identity, identity, identity];
+ inputs[input] = roundedSingular;
+ assert.throws(() => updateSkinPose(pose, ...inputs), /singular/);
+ assert.deepEqual(Array.from(pose.jointMatrices), before);
+ }
+});
+
+test('failed matrix inversion leaves the retained palette unchanged', context => {
+ const pose = createSkinPose(1);
+ const identity = new Float32Array(pose.jointMatrices);
+ const before = Array.from(pose.jointMatrices);
+ context.mock.method(mat4, 'invert', () => null);
+ assert.throws(() => updateSkinPose(pose, identity, identity), /invert/);
+ assert.deepEqual(Array.from(pose.jointMatrices), before);
+});
+
+test('pose calculations use Float32 mesh and bind matrices before inversion and multiplication', () => {
+ const pose = createSkinPose(1);
+ const identity = new Float64Array(pose.jointMatrices);
+ const mesh = new Float64Array(identity);
+ mesh[0] = 1.00000007;
+ const bind = new Float64Array(identity);
+ bind[0] = 1.00000007;
+ const expectedInverse = mat4.invert(mat4.create(), new Float32Array(mesh));
+ const expected = mat4.multiply(mat4.create(), expectedInverse, new Float32Array(bind));
+ updateSkinPose(pose, identity, identity, mesh, bind);
+ assert.deepEqual(Array.from(pose.jointMatrices), Array.from(expected));
+ updateSkinPose(pose, identity, identity, mesh);
+ assert.deepEqual(Array.from(pose.jointMatrices), Array.from(expectedInverse));
+});