Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(import): normalize skin weights across gltf attribute sets

yhh8ed0f81cff81
diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.ts
index 3340510c9..bfc43acdf 100644
--- a/pipeline/src/assets/gltfImport.ts
+++ b/pipeline/src/assets/gltfImport.ts
@@ -15,6 +15,7 @@ import { MESH_MAX_BONES, MeshChannel, MeshChannelType, packChannels,
type MeshMorphTargets } from 'esengine';
import { MeshoptDecoder } from 'meshoptimizer/decoder';
import { generateTangents } from './meshTangents';
+import { normalizeSkinWeights, type SkinWeights, type SkinWeightSet } from './skinWeights';
import { readSpringBones } from './springBoneSource';
import { readGltfPhysics } from './gltfPhysics';
import { readGltfParticle } from './gltfParticles';
@@ -894,6 +895,56 @@ function bindMatrices(src: GltfBytes, skin: NonNullable<GltfJson['skins']>[numbe
type GltfMesh = NonNullable<GltfJson['meshes']>[number];
type GltfPrimitive = GltfMesh['primitives'][number];
+function skinAttributes(src: GltfBytes, prim: GltfPrimitive,
+ skin: NonNullable<GltfJson['skins']>[number] | undefined,
+ vertexCount: number,
+ attribute: (semantic: string, index: number | undefined) => Float32Array | null,
+ label: string, warnings: string[]): SkinWeights | null {
+ const names = Object.keys(prim.attributes).filter(n => /^(JOINTS|WEIGHTS)_/.test(n));
+ const jointCount = skin?.joints?.length ?? 0;
+ if (jointCount > MESH_MAX_BONES) {
+ warnings.push(`${label}: the skin binds ${jointCount} joints and one`
+ + ` draw can be posed by ${MESH_MAX_BONES} — imported static`);
+ return null;
+ }
+ if (!jointCount || prim.attributes.WEIGHTS_0 === undefined) {
+ if (names.length) warnings.push(`${label}: JOINTS_0 without ${!jointCount
+ ? 'a skin naming joints on any node drawing it' : 'WEIGHTS_0'} — imported static`);
+ return null;
+ }
+ try {
+ if (names.length % 2 !== 0) throw new Error('unpaired JOINTS_n/WEIGHTS_n attributes');
+ const sets: SkinWeightSet[] = [];
+ for (let i = 0; i < names.length / 2; i++) {
+ const read = (kind: 'JOINTS' | 'WEIGHTS'): Float32Array => {
+ const semantic = `${kind}_${i}`;
+ const index = prim.attributes[semantic];
+ const acc = index === undefined ? undefined : src.json.accessors?.[index];
+ if (!acc) throw new Error(`${semantic} accessor is missing; skin attribute sets must be paired and consecutive`);
+ const integer = acc.componentType === 5121 || acc.componentType === 5123;
+ const validType = kind === 'JOINTS' ? integer && !acc.normalized
+ : (acc.componentType === 5126 && !acc.normalized) || (integer && acc.normalized);
+ if (!validType || acc.type !== 'VEC4' || acc.count !== vertexCount) {
+ throw new Error(`${semantic} must contain ${vertexCount} VEC4 values with a valid skin component type`);
+ }
+ const values = attribute(semantic, index);
+ if (values?.length !== vertexCount * 4) throw new Error(`${semantic} has an invalid decoded length`);
+ return values;
+ };
+ sets.push({ joints: read('JOINTS'), weights: read('WEIGHTS') });
+ }
+ const result = normalizeSkinWeights(sets, vertexCount, jointCount);
+ if (result.reducedVertices) warnings.push(`${label}: ${result.reducedVertices} vertices exceed four skin influences;`
+ + ` retained and normalized the strongest four (maximum discarded weight ${(100 * result.maxDiscardedWeight).toFixed(2)}%)`);
+ if (result.normalizedVertices) warnings.push(`${label}: normalized non-unit skin weights on ${result.normalizedVertices} vertices`);
+ if (result.mergedVertices) warnings.push(`${label}: merged duplicate joint weights on ${result.mergedVertices} vertices`);
+ return result;
+ } catch (error) {
+ warnings.push(`${label}: invalid skin: ${error instanceof Error ? error.message : String(error)} — imported static`);
+ return null;
+ }
+}
+
/**
* The shapes this primitive can be blended towards, as deltas off the vertices
* beside them. A target whose accessor does not cover every vertex is kept and
@@ -1270,7 +1321,7 @@ export async function importGltfMeshes(
// and whether its integers are normalized — as it always does.
const attribute = (semantic: string, index: number | undefined): Float32Array | null => {
if (index === undefined) return null;
- if (!geometry) return readAccessor(src, index);
+ if (!geometry || packed?.attributes[semantic] === undefined) return readAccessor(src, index);
const values = geometry.attributes.get(semantic);
if (!values) throw new Error(`${semantic} is missing from the Draco blob`);
const acc = json.accessors?.[index];
@@ -1308,26 +1359,10 @@ export async function importGltfMeshes(
return;
}
- // Both halves or neither: a joint index nothing weights moves the
- // vertex by an arbitrary bone, and a weight indexing nothing has
- // no bone to apply. A skin is what says which bind pose they mean.
const skinIndex = meshSkin.get(meshIndex);
const skin = skinIndex !== undefined ? json.skins?.[skinIndex] : undefined;
- // Joints past the pose block index a matrix nothing uploads, so
- // those vertices land somewhere arbitrary. Static is the honest
- // read, and the one JOINTS_0-without-WEIGHTS_0 already takes.
- const overBudget = (skin?.joints?.length ?? 0) > MESH_MAX_BONES;
- const joints = skin && !overBudget ? attribute('JOINTS_0', prim.attributes.JOINTS_0) : null;
- const weights = skin && !overBudget ? attribute('WEIGHTS_0', prim.attributes.WEIGHTS_0) : null;
- const skinned = !!(skin?.joints?.length && joints && weights);
- if (overBudget) {
- warnings.push(`${label}: the skin binds ${skin!.joints.length} joints and one`
- + ` draw can be posed by ${MESH_MAX_BONES} — imported static`);
- } else if (prim.attributes.JOINTS_0 !== undefined && !skinned) {
- warnings.push(`${label}: JOINTS_0 without ${!skin?.joints?.length
- ? 'a skin naming joints on any node drawing it' : 'WEIGHTS_0'}`
- + ' — imported static');
- }
+ const influences = skinAttributes(src, prim, skin, vertexCount, attribute, label, warnings);
+ const skinned = influences !== null;
// The frame the normal map was baked in, from the UVs as stored (V flipped below).
const tangents = normals && uvs && uvs.length >= vertexCount * 2
@@ -1397,8 +1432,8 @@ export async function importGltfMeshes(
}
if (jointsChannel && weightsChannel) {
for (let c = 0; c < 4; c++) {
- dv.setUint16(at + jointsChannel.offset + c * 2, joints![i * 4 + c] ?? 0, true);
- dv.setFloat32(at + weightsChannel.offset + c * 4, weights![i * 4 + c] ?? 0, true);
+ dv.setUint16(at + jointsChannel.offset + c * 2, influences!.joints[i * 4 + c]!, true);
+ dv.setFloat32(at + weightsChannel.offset + c * 4, influences!.weights[i * 4 + c]!, true);
}
}
}
diff --git a/pipeline/src/assets/skinWeights.ts b/pipeline/src/assets/skinWeights.ts
new file mode 100644
index 000000000..d9ebb0e78
--- /dev/null
+++ b/pipeline/src/assets/skinWeights.ts
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+
+export interface SkinWeightSet {
+ joints: Float32Array;
+ weights: Float32Array;
+}
+
+export interface SkinWeights {
+ joints: Uint16Array;
+ weights: Float32Array;
+ reducedVertices: number;
+ normalizedVertices: number;
+ mergedVertices: number;
+ maxDiscardedWeight: number;
+}
+
+/** Consolidates source influences into the runtime's four-weight vertex layout. */
+export function normalizeSkinWeights(sets: SkinWeightSet[], vertexCount: number,
+ jointCount: number): SkinWeights {
+ const result: SkinWeights = {
+ joints: new Uint16Array(vertexCount * 4), weights: new Float32Array(vertexCount * 4),
+ reducedVertices: 0, normalizedVertices: 0, mergedVertices: 0, maxDiscardedWeight: 0,
+ };
+ const accumulated = new Float64Array(jointCount);
+ const touched = new Uint16Array(jointCount);
+ const best = new Uint16Array(4);
+
+ for (let v = 0; v < vertexCount; v++) {
+ let count = 0, total = 0, merged = false;
+ for (const set of sets) {
+ for (let c = 0; c < 4; c++) {
+ const weight = set.weights[v * 4 + c]!;
+ if (!Number.isFinite(weight) || weight < 0) {
+ throw new Error(`vertex ${v} has a non-finite or negative skin weight`);
+ }
+ if (weight === 0) continue;
+ const joint = set.joints[v * 4 + c]!;
+ if (!Number.isInteger(joint) || joint < 0 || joint >= jointCount) {
+ throw new Error(`vertex ${v} weights joint ${joint} outside the skin's ${jointCount} joints`);
+ }
+ if (accumulated[joint] === 0) touched[count++] = joint;
+ else merged = true;
+ accumulated[joint]! += weight;
+ total += weight;
+ }
+ }
+ if (count === 0) throw new Error(`vertex ${v} has no positive skin weights`);
+ if (merged) result.mergedVertices++;
+ if (Math.abs(total - 1) > 1e-5) result.normalizedVertices++;
+
+ let kept = 0;
+ for (let i = 0; i < count; i++) {
+ const joint = touched[i]!;
+ if (count <= 4) {
+ best[kept++] = joint;
+ continue;
+ }
+ let at = 0;
+ // Equal weights retain source order, including across attribute sets.
+ while (at < kept && accumulated[joint]! <= accumulated[best[at]!]!) at++;
+ if (at >= 4) continue;
+ for (let k = Math.min(kept, 3); k > at; k--) best[k] = best[k - 1]!;
+ best[at] = joint;
+ kept = Math.min(kept + 1, 4);
+ }
+ let retained = 0;
+ for (let c = 0; c < kept; c++) retained += accumulated[best[c]!]!;
+ for (let c = 0; c < kept; c++) {
+ const joint = best[c]!;
+ result.joints[v * 4 + c] = joint;
+ result.weights[v * 4 + c] = accumulated[joint]! / retained;
+ }
+ if (count > 4) {
+ result.reducedVertices++;
+ result.maxDiscardedWeight = Math.max(result.maxDiscardedWeight, (total - retained) / total);
+ }
+ for (let i = 0; i < count; i++) accumulated[touched[i]!] = 0;
+ }
+ return result;
+}
diff --git a/pipeline/tests/fixtures/gltfFixtures.d.mts b/pipeline/tests/fixtures/gltfFixtures.d.mts
index 341658603..990e628cc 100644
--- a/pipeline/tests/fixtures/gltfFixtures.d.mts
+++ b/pipeline/tests/fixtures/gltfFixtures.d.mts
@@ -8,4 +8,6 @@ export function plainTriangle(): Uint8Array;
export function meshoptTriangle(): Promise<Uint8Array>;
/** The same triangle with its geometry in a Draco blob. */
-export function dracoTriangle(): Promise<Uint8Array>;
+export function dracoTriangle(extraAttributes?: Record<string, {
+ componentType: number; normalized?: boolean; values: number[];
+}>): Promise<Uint8Array>;
diff --git a/pipeline/tests/fixtures/gltfFixtures.mjs b/pipeline/tests/fixtures/gltfFixtures.mjs
index f4105317e..752769df3 100644
--- a/pipeline/tests/fixtures/gltfFixtures.mjs
+++ b/pipeline/tests/fixtures/gltfFixtures.mjs
@@ -129,7 +129,7 @@ export async function meshoptTriangle() {
* Draco reorders vertices to compress them, so a product built from this is
* geometrically the same triangle rather than the same bytes.
*/
-export async function dracoTriangle() {
+export async function dracoTriangle(extraAttributes = {}) {
const { createEncoderModule } = await import('draco3dgltf');
const draco = await createEncoderModule();
const mesh = new draco.Mesh();
@@ -137,6 +137,16 @@ export async function dracoTriangle() {
builder.AddFacesToMesh(mesh, 1, new Uint32Array(INDICES));
const position = builder.AddFloatAttributeToMesh(mesh, draco.POSITION, 3, 3, POSITIONS);
const texCoord = builder.AddFloatAttributeToMesh(mesh, draco.TEX_COORD, 3, 2, UVS);
+ const attributes = { POSITION: 0, TEXCOORD_0: 1 };
+ const compressedAttributes = { POSITION: position, TEXCOORD_0: texCoord };
+ const accessors = ACCESSORS.map(a => ({ ...a, bufferView: undefined }));
+ for (const [name, source] of Object.entries(extraAttributes)) {
+ attributes[name] = accessors.length;
+ accessors.push({ type: 'VEC4', count: 3, componentType: source.componentType,
+ normalized: source.normalized ?? false });
+ compressedAttributes[name] = builder.AddFloatAttributeToMesh(
+ mesh, draco.GENERIC, 3, 4, new Float32Array(source.values));
+ }
const encoder = new draco.Encoder();
const encoded = new draco.DracoInt8Array();
@@ -152,14 +162,14 @@ export async function dracoTriangle() {
bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: blob.length }],
// The accessors keep saying what the data MEANS — count and type — while
// Draco holds the data itself. That is the shape the spec asks for.
- accessors: ACCESSORS.map(a => ({ ...a, bufferView: undefined })),
+ accessors,
meshes: [{
name: 'Tri',
primitives: [{
- attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, mode: 4,
+ attributes, indices: 2, mode: 4,
extensions: {
KHR_draco_mesh_compression: {
- bufferView: 0, attributes: { POSITION: position, TEXCOORD_0: texCoord },
+ bufferView: 0, attributes: compressedAttributes,
},
},
}],
diff --git a/pipeline/tests/gltf-skin-weights.test.ts b/pipeline/tests/gltf-skin-weights.test.ts
new file mode 100644
index 000000000..63658da50
--- /dev/null
+++ b/pipeline/tests/gltf-skin-weights.test.ts
@@ -0,0 +1,253 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { MeshChannel, MeshChannelType } from 'esengine';
+import { MeshoptEncoder } from 'meshoptimizer/encoder';
+import { importGltfMeshes } from '../src/assets/gltfImport';
+import type { ImportedMesh } from '../src/assets/modelImport';
+import { dracoTriangle } from './fixtures/gltfFixtures.mjs';
+
+interface SourceSet { joints: number[]; weights: number[] }
+interface Accessor {
+ bufferView?: number; componentType: number; count: number; type: string; normalized?: boolean;
+ sparse?: { count: number; indices: { bufferView: number; componentType: number }; values: { bufferView: number } };
+}
+
+function fixture(sets: SourceSet[], weightType = 5126, jointType = 5123) {
+ const parts: Buffer[] = [];
+ const bufferViews: { buffer: number; byteOffset: number; byteLength: number }[] = [];
+ const accessors: Accessor[] = [];
+ let byteOffset = 0;
+ const add = (values: number[], componentType: number, type: string, normalized = false) => {
+ const pad = (4 - byteOffset % 4) % 4;
+ parts.push(Buffer.alloc(pad));
+ byteOffset += pad;
+ const data = componentType === 5121 ? new Uint8Array(values)
+ : componentType === 5123 ? new Uint16Array(values) : new Float32Array(values);
+ bufferViews.push({ buffer: 0, byteOffset, byteLength: data.byteLength });
+ parts.push(Buffer.from(data.buffer));
+ byteOffset += data.byteLength;
+ accessors.push({ bufferView: bufferViews.length - 1, componentType, count: 3, type, normalized });
+ return accessors.length - 1;
+ };
+ const attributes: Record<string, number> = { POSITION: add([0, 0, 0, 1, 0, 0, 0, 1, 0], 5126, 'VEC3') };
+ for (const [i, set] of sets.entries()) {
+ attributes[`JOINTS_${i}`] = add(Array.from({ length: 3 }, () => set.joints).flat(), jointType, 'VEC4');
+ attributes[`WEIGHTS_${i}`] = add(Array.from({ length: 3 }, () => set.weights).flat(), weightType, 'VEC4', weightType !== 5126);
+ }
+ const bytes = Buffer.concat(parts);
+ return {
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews, accessors,
+ meshes: [{ primitives: [{ attributes }] }],
+ nodes: [{ name: 'Rig', children: [1, 2, 3, 4, 5, 6, 7, 8, 9] },
+ ...Array.from({ length: 8 }, (_, i) => ({ name: `Joint${i}` })), { name: 'Body', mesh: 0, skin: 0 }],
+ skins: [{ joints: [1, 2, 3, 4, 5, 6, 7, 8] }], scenes: [{ nodes: [0] }], scene: 0,
+ };
+}
+
+const encode = (doc: object) => new TextEncoder().encode(JSON.stringify(doc));
+const normalSet = { joints: [0, 1, 0, 0], weights: [0.75, 0.25, 0, 0] };
+const eightWeights = [
+ { joints: [0, 1, 2, 3], weights: [0.05, 0.1, 0.15, 0.2] },
+ { joints: [4, 5, 6, 7], weights: [0.3, 0.12, 0.05, 0.03] },
+];
+
+function influences(mesh: ImportedMesh, vertex = 0) {
+ const joints = mesh.data.channels.find(c => c.semantic === MeshChannel.Joints)!;
+ const weights = mesh.data.channels.find(c => c.semantic === MeshChannel.Weights)!;
+ expect(joints).toMatchObject({ components: 4, type: MeshChannelType.UInt16 });
+ expect(weights).toMatchObject({ components: 4, type: MeshChannelType.Float32 });
+ const view = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);
+ const base = vertex * mesh.data.vertexStride;
+ return Array.from({ length: 4 }, (_, c) => ({
+ joint: view.getUint16(base + joints.offset + c * 2, true),
+ weight: view.getFloat32(base + weights.offset + c * 4, true),
+ }));
+}
+
+function expectRigidTranslation(mesh: ImportedMesh) {
+ const position = mesh.data.channels.find(c => c.semantic === MeshChannel.Position)!;
+ const view = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);
+ for (let v = 0; v < mesh.vertexCount; v++) {
+ const skin = influences(mesh, v);
+ for (const [axis, translation] of [17, -24, 8].entries()) {
+ const p = view.getFloat32(v * mesh.data.vertexStride + position.offset + axis * 4, true);
+ const posed = skin.reduce((sum, influence) => sum + influence.weight * (p + translation), 0);
+ expect(posed).toBeCloseTo(p + translation, 5);
+ }
+ }
+}
+
+async function expectStatic(doc: object, warning: RegExp) {
+ const result = await importGltfMeshes(encode(doc), 'skin');
+ expect(result.meshes).toHaveLength(1);
+ const mesh = result.meshes[0]!;
+ expect(mesh.vertexCount).toBe(3);
+ expect(mesh.triangleCount).toBe(1);
+ expect(mesh.data.channels.some(c => c.semantic === MeshChannel.Joints || c.semantic === MeshChannel.Weights)).toBe(false);
+ expect(mesh.skinJoints).toBeUndefined();
+ expect(mesh.data.inverseBindMatrices).toBeUndefined();
+ expect(result.warnings.some(w => warning.test(w) && w.includes('imported static'))).toBe(true);
+}
+
+describe('glTF skin weight normalization', () => {
+ it('keeps the strongest four across sets and preserves a rigid translation', async () => {
+ const result = await importGltfMeshes(encode(fixture(eightWeights)), 'skin');
+ const skin = influences(result.meshes[0]!);
+ expect(skin.map(x => x.joint)).toEqual([4, 3, 2, 5]);
+ for (const [i, w] of [0.3, 0.2, 0.15, 0.12].entries()) expect(skin[i]!.weight).toBeCloseTo(w / 0.77, 6);
+ expectRigidTranslation(result.meshes[0]!);
+ expect(result.warnings.some(w => /3 vertices exceed four.*23.00%/.test(w))).toBe(true);
+ });
+
+ it('reads a third set without reporting loss when only three joints contribute', async () => {
+ const doc = fixture([
+ { joints: [0, 0, 0, 0], weights: [0.25, 0, 0, 0] },
+ { joints: [5, 0, 0, 0], weights: [0.25, 0, 0, 0] },
+ { joints: [7, 0, 0, 0], weights: [0.5, 0, 0, 0] },
+ ]);
+ const result = await importGltfMeshes(encode(doc), 'skin');
+ expect(influences(result.meshes[0]!)).toEqual([
+ { joint: 0, weight: 0.25 }, { joint: 5, weight: 0.25 }, { joint: 7, weight: 0.5 }, { joint: 0, weight: 0 },
+ ]);
+ expect(result.warnings).toEqual([]);
+ expectRigidTranslation(result.meshes[0]!);
+ });
+
+ it('merges duplicate joints before selecting the strongest four', async () => {
+ const result = await importGltfMeshes(encode(fixture([
+ { joints: [3, 1, 2, 0], weights: [0.1, 0.2, 0.2, 0.2] },
+ { joints: [3, 4, 0, 0], weights: [0.2, 0.1, 0, 0] },
+ ])), 'skin');
+ const skin = influences(result.meshes[0]!);
+ expect(skin.map(x => x.joint)).toEqual([3, 1, 2, 0]);
+ expect(skin[0]!.weight).toBeCloseTo(1 / 3, 6);
+ expect(result.warnings.some(w => /merged duplicate joint/.test(w))).toBe(true);
+ expectRigidTranslation(result.meshes[0]!);
+ });
+
+ it('breaks equal-weight ties in source order', async () => {
+ const result = await importGltfMeshes(encode(fixture([
+ { joints: [7, 6, 5, 4], weights: [0.2, 0.2, 0.2, 0.2] },
+ { joints: [3, 0, 0, 0], weights: [0.2, 0, 0, 0] },
+ ])), 'skin');
+ expect(influences(result.meshes[0]!).map(x => x.joint)).toEqual([7, 6, 5, 4]);
+ expectRigidTranslation(result.meshes[0]!);
+ });
+
+ it.each([5126, 5121, 5123])('normalizes component type %i without shrinking the mesh', async weightType => {
+ const weights = weightType === 5126 ? [0.3, 0.2, 0, 0]
+ : weightType === 5121 ? [80, 174, 0, 0] : [10000, 50000, 0, 0];
+ const result = await importGltfMeshes(encode(fixture([{ joints: [1, 6, 0, 0], weights }], weightType, 5121)), 'skin');
+ const skin = influences(result.meshes[0]!);
+ expect(skin[0]!.weight).toBeCloseTo(weights[0]! / (weights[0]! + weights[1]!), 6);
+ expectRigidTranslation(result.meshes[0]!);
+ expect(result.warnings.some(w => /normalized non-unit skin weights on 3 vertices/.test(w))).toBe(true);
+ });
+
+ it('zeroes unused joint indices so zero-weight shader fetches stay within the palette', async () => {
+ const result = await importGltfMeshes(encode(fixture([
+ { joints: [1, 65535, 400, 8], weights: [1, 0, 0, 0] },
+ ])), 'skin');
+ expect(influences(result.meshes[0]!)).toEqual([
+ { joint: 1, weight: 1 }, { joint: 0, weight: 0 }, { joint: 0, weight: 0 }, { joint: 0, weight: 0 },
+ ]);
+ });
+
+ it.each([NaN, Infinity, -0.1, 0])('preserves static geometry for unusable weight %s', async weight => {
+ await expectStatic(fixture([{ joints: [0, 1, 0, 0], weights: [weight, 0, 0, 0] }]), /skin weight/);
+ });
+
+ it('preserves static geometry when a positive weight names an unbound joint', async () => {
+ await expectStatic(fixture([{ joints: [8, 0, 0, 0], weights: [1, 0, 0, 0] }]), /outside the skin/);
+ });
+
+ it.each(['count', 'shape', 'joint type', 'weight type', 'joint normalization', 'weight normalization', 'missing accessor', 'missing bytes'])
+ ('preserves static geometry for invalid %s', async failure => {
+ const doc = fixture([normalSet]);
+ if (failure === 'count') doc.accessors[2]!.count = 2;
+ if (failure === 'shape') doc.accessors[2]!.type = 'VEC3';
+ if (failure === 'joint type') doc.accessors[1]!.componentType = 5126;
+ if (failure === 'weight type') doc.accessors[2]!.componentType = 5122;
+ if (failure === 'joint normalization') doc.accessors[1]!.normalized = true;
+ if (failure === 'weight normalization') doc.accessors[2]!.componentType = 5121;
+ if (failure === 'missing accessor') doc.meshes[0]!.primitives[0]!.attributes.WEIGHTS_0 = 99;
+ if (failure === 'missing bytes') doc.bufferViews[2]!.byteLength = 4;
+ await expectStatic(doc, /invalid skin/);
+ });
+
+ it.each(['unpaired', 'gap', 'leading zero'])('does not silently omit a %s additional set', async failure => {
+ const doc = fixture(eightWeights);
+ const attributes = doc.meshes[0]!.primitives[0]!.attributes;
+ if (failure !== 'unpaired') {
+ const suffix = failure === 'gap' ? '2' : '01';
+ attributes[`JOINTS_${suffix}`] = attributes.JOINTS_1!;
+ attributes[`WEIGHTS_${suffix}`] = attributes.WEIGHTS_1!;
+ delete attributes.JOINTS_1;
+ }
+ delete attributes.WEIGHTS_1;
+ await expectStatic(doc, /paired/);
+ });
+
+ it('uses sparse values in additional weight sets', async () => {
+ const doc = fixture(eightWeights);
+ const expected = await importGltfMeshes(encode(doc), 'skin');
+ const indexView = doc.bufferViews.length;
+ doc.buffers.push({ byteLength: 3, uri: 'data:application/octet-stream;base64,AAEC' });
+ doc.bufferViews.push({ buffer: 1, byteOffset: 0, byteLength: 3 });
+ const acc = doc.accessors[4]!;
+ acc.sparse = { count: 3, indices: { bufferView: indexView, componentType: 5121 }, values: { bufferView: acc.bufferView! } };
+ delete acc.bufferView;
+ const result = await importGltfMeshes(encode(doc), 'skin');
+ expect(result.meshes[0]!.data.vertices).toEqual(expected.meshes[0]!.data.vertices);
+ expectRigidTranslation(result.meshes[0]!);
+ });
+
+ it('uses the same reduction for meshopt-compressed skin attributes', async () => {
+ const doc = fixture(eightWeights);
+ const expected = await importGltfMeshes(encode(doc), 'skin');
+ const bytes = Buffer.from(doc.buffers[0]!.uri.split(',')[1]!, 'base64');
+ await MeshoptEncoder.ready;
+ const bufferViews = doc.bufferViews.map(view => {
+ const stride = view.byteLength / 3;
+ const encoded = MeshoptEncoder.encodeVertexBuffer(bytes.subarray(view.byteOffset, view.byteOffset + view.byteLength), 3, stride);
+ const buffer = doc.buffers.length;
+ doc.buffers.push({ byteLength: encoded.byteLength, uri: `data:application/octet-stream;base64,${Buffer.from(encoded).toString('base64')}` });
+ return { ...view, extensions: { EXT_meshopt_compression: {
+ buffer, byteOffset: 0, byteLength: encoded.byteLength, byteStride: stride, count: 3, mode: 'ATTRIBUTES',
+ } } };
+ });
+ const result = await importGltfMeshes(encode({ ...doc, bufferViews, extensionsRequired: ['EXT_meshopt_compression'] }), 'skin');
+ expect(result.meshes[0]!.data.vertices).toEqual(expected.meshes[0]!.data.vertices);
+ expectRigidTranslation(result.meshes[0]!);
+ });
+
+ it.each([false, true])('reads Draco geometry with additional uncompressed skin sets: %s', async mixed => {
+ const plain = fixture(eightWeights);
+ const extra: Record<string, { componentType: number; values: number[] }> = {};
+ for (const [i, set] of eightWeights.entries()) {
+ if (mixed && i === 1) continue;
+ extra[`JOINTS_${i}`] = { componentType: 5123, values: Array.from({ length: 3 }, () => set.joints).flat() };
+ extra[`WEIGHTS_${i}`] = { componentType: 5126, values: Array.from({ length: 3 }, () => set.weights).flat() };
+ }
+ const packed = JSON.parse(new TextDecoder().decode(await dracoTriangle(extra))) as ReturnType<typeof fixture>;
+ const doc = { ...plain, ...packed, nodes: plain.nodes, skins: plain.skins, scenes: plain.scenes };
+ if (mixed) {
+ const buffer = doc.buffers.length;
+ doc.buffers.push(plain.buffers[0]!);
+ for (const name of ['JOINTS_1', 'WEIGHTS_1']) {
+ const source = plain.accessors[plain.meshes[0]!.primitives[0]!.attributes[name]!]!;
+ doc.meshes[0]!.primitives[0]!.attributes[name] = doc.accessors.length;
+ doc.accessors.push({ ...source, bufferView: doc.bufferViews.length });
+ doc.bufferViews.push({ ...plain.bufferViews[source.bufferView!]!, buffer });
+ }
+ }
+ const result = await importGltfMeshes(encode(doc), 'skin');
+ expect(result.meshes).toHaveLength(1);
+ expect(influences(result.meshes[0]!).map(x => x.joint)).toEqual([4, 3, 2, 5]);
+ expectRigidTranslation(result.meshes[0]!);
+ expect(result.warnings.some(w => /imported static|skipped/.test(w))).toBe(false);
+ });
+});