Import a 3D Model and automatically assign and export animations
TypeScript
FBX fixes - Fix disprepencies between broken materials and skeleton hierarchies
Scott Petrovic9e9ff4b81b92
diff --git a/src/lib/io/fbx/FBXTreeParser.test.ts b/src/lib/io/fbx/FBXTreeParser.test.tsnew file mode 100644index 0000000..5a63227--- /dev/null+++ b/src/lib/io/fbx/FBXTreeParser.test.ts@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest'+import { BufferGeometry, Float32BufferAttribute, LoadingManager, TextureLoader, Uint16BufferAttribute } from 'three'+import { FBXTreeParser } from './FBXTreeParser'++/** One vertex, influenced by the four clusters passed in. */+function make_skinned_geometry (cluster_indices: number[], weights: number[]): BufferGeometry {+ const geometry = new BufferGeometry()+ geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0], 3))+ geometry.setAttribute('skinIndex', new Uint16BufferAttribute(cluster_indices, 4))+ geometry.setAttribute('skinWeight', new Float32BufferAttribute(weights, 4))+ return geometry+}++function make_parser (): FBXTreeParser {+ return new FBXTreeParser(new TextureLoader(), new LoadingManager())+}++describe('FBXTreeParser.remapSkinIndices', () => {+ it('points skin indices at the compacted bone list', () => {+ // cluster 1 had no bone in the file, so clusters 0, 2 and 3 shifted down+ const geometry = make_skinned_geometry([0, 2, 3, 0], [0.25, 0.25, 0.25, 0.25])++ make_parser().remapSkinIndices(geometry, [0, -1, 1, 2])++ expect(Array.from(geometry.attributes.skinIndex.array)).toEqual([0, 1, 2, 0])+ })++ it('drops influences of a missing bone and renormalizes what is left', () => {+ const geometry = make_skinned_geometry([0, 1, 2, 0], [0.5, 0.25, 0.25, 0])++ make_parser().remapSkinIndices(geometry, [0, -1, 1, 2])++ expect(Array.from(geometry.attributes.skinIndex.array)).toEqual([0, 0, 1, 0])++ const weights = Array.from(geometry.attributes.skinWeight.array)+ expect(weights[0]).toBeCloseTo(2 / 3)+ expect(weights[1]).toBe(0)+ expect(weights[2]).toBeCloseTo(1 / 3)+ expect(weights[0] + weights[1] + weights[2] + weights[3]).toBeCloseTo(1)+ })++ it('leaves an unweighted vertex alone', () => {+ const geometry = make_skinned_geometry([0, 0, 0, 0], [0, 0, 0, 0])++ make_parser().remapSkinIndices(geometry, [0, 1])++ expect(Array.from(geometry.attributes.skinWeight.array)).toEqual([0, 0, 0, 0])+ })+})diff --git a/src/lib/io/fbx/FBXTreeParser.ts b/src/lib/io/fbx/FBXTreeParser.tsindex cdcd2ba..2c6c760 100644--- a/src/lib/io/fbx/FBXTreeParser.ts+++ b/src/lib/io/fbx/FBXTreeParser.ts@@ -1,6 +1,7 @@import {AmbientLight,Bone,+ type BufferGeometry,ClampToEdgeWrapping,Color,ColorManagement,@@ -1404,41 +1405,74 @@ class FBXTreeParser {const skeleton = skeletons[ID];+ // skeleton.bones is filled in by index as the models are parsed, so a+ // cluster whose bone model is missing from the file leaves an undefined+ // hole in the list. Those holes reach the exporters, where an undefined+ // joint is written out as null and the file is rejected on load+ // ("/skins/0/joints/null: failed to find index (null)"). Drop the holes+ // and keep a map of where each cluster ended up, so the skin indices+ // stored on the geometry can be moved along with them.+ //// Compute bone inverses from TransformLink rather than from the// bones' current matrixWorld. The TransformLink matrices represent// each bone's global transform at the time the skin weights were// painted, which may differ from the scene-reconstructed transforms.const boneInverses: Matrix4[] = [];+ const bones: Bone[] = [];+ const clusterToBoneIndex: number[] = [];- for (let i = 0, l = skeleton.bones.length; i < l; i++) {+ for (let i = 0, l = skeleton.rawBones.length; i < l; i++) {- const inverse = new Matrix4();+ const bone = skeleton.bones[i];- if (skeleton.bones[i] && skeleton.rawBones[i]) {+ if (!bone) {- inverse.copy(skeleton.rawBones[i].transformLink).invert();+ clusterToBoneIndex[i] = - 1;+ continue;}- boneInverses.push(inverse);+ clusterToBoneIndex[i] = bones.length;+ bones.push(bone);+ boneInverses.push(new Matrix4().copy(skeleton.rawBones[i].transformLink).invert());}+ const hasMissingBones = bones.length !== skeleton.rawBones.length;+ const remappedGeometries = new Set();++ if (hasMissingBones) {++ console.warn('THREE.FBXLoader: ' + (skeleton.rawBones.length - bones.length) + ' skin cluster(s) have no bone in this file. Their influences are being dropped.');++ }++ skeleton.bones = bones;+const parents = fbxGlobals.connections.get(parseInt(skeleton.ID))!.parents;- parents.forEach(function (parent: any) {+ parents.forEach((parent: any) => {if (geometryMap.has(parent.ID)) {const geoID = parent.ID;const geoRelationships = fbxGlobals.connections.get(geoID)!- geoRelationships.parents.forEach(function (geoConnParent: any) {+ geoRelationships.parents.forEach((geoConnParent: any) => {if (modelMap.has(geoConnParent.ID)) {const model = modelMap.get(geoConnParent.ID);+ // the skin indices on the geometry are cluster indices, so+ // they only line up with the bone list while it is complete+ if (hasMissingBones && !remappedGeometries.has(model.geometry)) {++ remappedGeometries.add(model.geometry);+ this.remapSkinIndices(model.geometry, clusterToBoneIndex);++ }+// Use the mesh's current matrixWorld as bind matrix.// The BindPose section is intentionally not used here// since it may contain scale/rotation from the model@@ -1448,7 +1482,7 @@ class FBXTreeParser {// would overwrite the bone inverses computed above.model.updateMatrixWorld(true);- model.bind(new Skeleton(skeleton.bones, boneInverses), model.matrixWorld);+ model.bind(new Skeleton(bones, boneInverses), model.matrixWorld);}@@ -1462,6 +1496,54 @@ class FBXTreeParser {}+ // Points a geometry's skin indices at the compacted bone list. Influences that+ // referenced a cluster with no bone are dropped, and what is left is renormalized+ // so every vertex still sums to a full weight.+ remapSkinIndices (geometry: BufferGeometry, clusterToBoneIndex: number[]): void {++ const skinIndex = geometry.attributes.skinIndex;+ const skinWeight = geometry.attributes.skinWeight;++ if (skinIndex === undefined || skinWeight === undefined) return;++ for (let vertex = 0, l = skinIndex.count; vertex < l; vertex++) {++ let weightTotal = 0;++ for (let influence = 0; influence < 4; influence++) {++ const boneIndex = clusterToBoneIndex[skinIndex.getComponent(vertex, influence)];++ if (boneIndex === undefined || boneIndex === - 1) {++ skinIndex.setComponent(vertex, influence, 0);+ skinWeight.setComponent(vertex, influence, 0);+ continue;++ }++ skinIndex.setComponent(vertex, influence, boneIndex);+ weightTotal += skinWeight.getComponent(vertex, influence);++ }++ // a vertex that was only influenced by dropped bones has nothing left to+ // normalize, and it was not skinned to anything before either, so leave it+ if (weightTotal === 0) continue;++ for (let influence = 0; influence < 4; influence++) {++ skinWeight.setComponent(vertex, influence, skinWeight.getComponent(vertex, influence) / weightTotal);++ }++ }++ skinIndex.needsUpdate = true;+ skinWeight.needsUpdate = true;++ }+// Parse BindPose nodes and return a map of node ID to bind matrix.parsePoseNodes () {diff --git a/src/lib/io/fbx/GeometryParser.ts b/src/lib/io/fbx/GeometryParser.tsindex a992df9..c6ce2cb 100644--- a/src/lib/io/fbx/GeometryParser.ts+++ b/src/lib/io/fbx/GeometryParser.ts@@ -422,6 +422,22 @@ class GeometryParser {}+ // Skinning assumes the four weights on a vertex add up to 1. FBX files+ // do not guarantee that, and dropping the extra influences above makes+ // the total smaller still, which pulls those vertices toward the origin+ // once the mesh is posed or exported to glTF.+ const weightTotal = weights[0] + weights[1] + weights[2] + weights[3];++ if (weightTotal > 0) {++ for (let i = 0; i < 4; ++i) {++ weights[i] = weights[i] / weightTotal;++ }++ }+for (let i = 0; i < 4; ++i) {faceWeights.push(weights[i]);diff --git a/src/lib/processes/export-to-file/ExportHierarchyService.test.ts b/src/lib/processes/export-to-file/ExportHierarchyService.test.tsnew file mode 100644index 0000000..482434a--- /dev/null+++ b/src/lib/processes/export-to-file/ExportHierarchyService.test.ts@@ -0,0 +1,122 @@+import { describe, it, expect } from 'vitest'+import { BoxGeometry, Bone, Float32BufferAttribute, Group, MeshBasicMaterial, Scene, Skeleton, SkinnedMesh, Uint16BufferAttribute } from 'three'+import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js'+import { ExportHierarchyService } from './ExportHierarchyService'++interface TestRig {+ scene: Scene+ skinned_mesh: SkinnedMesh+ hips: Bone+ spine: Bone+}++function make_skinned_mesh (bones: Bone[]): SkinnedMesh {+ const geometry = new BoxGeometry(1, 1, 1)+ const vertex_count = geometry.attributes.position.count++ geometry.setAttribute('skinIndex', new Uint16BufferAttribute(new Uint16Array(vertex_count * 4), 4))+ geometry.setAttribute('skinWeight', new Float32BufferAttribute(+ Float32Array.from({ length: vertex_count * 4 }, (_, index) => (index % 4 === 0 ? 1 : 0)), 4))++ const skinned_mesh = new SkinnedMesh(geometry, new MeshBasicMaterial())+ skinned_mesh.name = 'Body'+ skinned_mesh.bind(new Skeleton(bones))+ return skinned_mesh+}++/** How an imported FBX rig is laid out: the bones are siblings of the mesh. */+function make_imported_rig (): TestRig {+ const scene = new Scene()+ const model_root = new Group()+ model_root.name = 'FBX Root'+ scene.add(model_root)++ const hips = new Bone()+ hips.name = 'Hips'+ const spine = new Bone()+ spine.name = 'Spine'+ hips.add(spine)+ model_root.add(hips)++ const skinned_mesh = make_skinned_mesh([hips, spine])+ model_root.add(skinned_mesh)++ return { scene, skinned_mesh, hips, spine }+}++/** How a mesh rigged in Mesh2Motion is laid out: the root bone is a child of the mesh. */+function make_mesh2motion_rig (): TestRig {+ const scene = new Scene()++ const hips = new Bone()+ hips.name = 'Hips'+ const spine = new Bone()+ spine.name = 'Spine'+ hips.add(spine)++ const skinned_mesh = make_skinned_mesh([hips, spine])+ skinned_mesh.add(hips)+ scene.add(skinned_mesh)++ return { scene, skinned_mesh, hips, spine }+}++interface ExportedGltf {+ skins: Array<{ joints: Array<number | null> }>+}++async function export_gltf (scene: Scene): Promise<ExportedGltf> {+ const gltf = await new GLTFExporter().parseAsync(scene, { binary: false, onlyVisible: false })+ return gltf as unknown as ExportedGltf+}++describe('ExportHierarchyService.collect_objects_to_export', () => {+ it('keeps an imported rig together with its bones', () => {+ const { scene, skinned_mesh } = make_imported_rig()++ const objects = ExportHierarchyService.collect_objects_to_export([skinned_mesh], false)++ // the mesh and the bones share a parent, so the whole subtree moves as one object+ expect(objects).toEqual([scene.children[0]])+ })++ it('moves only the meshes when the bones already hang off them', () => {+ const { skinned_mesh } = make_mesh2motion_rig()++ const objects = ExportHierarchyService.collect_objects_to_export([skinned_mesh], false)++ expect(objects).toEqual([skinned_mesh])+ })++ it('leaves the mesh behind for a skeleton-only export', () => {+ const { skinned_mesh, hips } = make_imported_rig()++ const objects = ExportHierarchyService.collect_objects_to_export([skinned_mesh], true)++ expect(objects).toEqual([hips])+ })++ it('finds the root bone when the bone list is not in hierarchical order', () => {+ const { skinned_mesh, hips, spine } = make_imported_rig()+ skinned_mesh.bind(new Skeleton([spine, hips]))++ expect(ExportHierarchyService.collect_objects_to_export([skinned_mesh], true)).toEqual([hips])+ })+})++describe('exported glTF skins', () => {+ it('writes a joint for every bone of an imported rig', async () => {+ const { skinned_mesh } = make_imported_rig()+ const export_scene = new Scene()++ ExportHierarchyService.collect_objects_to_export([skinned_mesh], false)+ .forEach((object) => export_scene.add(object))++ const gltf = await export_gltf(export_scene)++ // a null joint here is what makes viewers reject the file with+ // "/skins/0/joints/null: failed to find index (null)"+ expect(gltf.skins[0].joints).toHaveLength(2)+ expect(gltf.skins[0].joints.some((joint) => joint === null || joint === undefined)).toBe(false)+ })+})diff --git a/src/lib/processes/export-to-file/ExportHierarchyService.ts b/src/lib/processes/export-to-file/ExportHierarchyService.tsnew file mode 100644index 0000000..3f12f02--- /dev/null+++ b/src/lib/processes/export-to-file/ExportHierarchyService.ts@@ -0,0 +1,86 @@+import { type Bone, type Object3D, type Scene, type Skeleton, type SkinnedMesh } from 'three'++/**+ * Works out which objects have to be moved into the export scene.+ *+ * Exporters only see what is inside the scene they are handed, and a skin is only+ * valid if every bone it references was written out as a node. Meshes rigged inside+ * Mesh2Motion keep their root bone as a child of the skinned mesh, so moving the mesh+ * was enough to bring the skeleton along. Rigs imported for retargeting keep their+ * bones as siblings of the mesh instead (this is what FBX files look like), so moving+ * only the mesh left every joint pointing at a node that was never exported. Loaders+ * report that as "/skins/0/joints/null: failed to find index (null)".+ */+export class ExportHierarchyService {+ /**+ * @param skinned_meshes the meshes being exported+ * @param skeleton_only true when only the bone hierarchy should be exported+ * @returns the objects to move into the export scene. No returned object is a+ * descendant of another, so each one can be moved and restored on its own.+ */+ public static collect_objects_to_export (skinned_meshes: SkinnedMesh[], skeleton_only: boolean): Object3D[] {+ const collected: Object3D[] = []++ skinned_meshes.forEach((skinned_mesh) => {+ this.skeleton_root_bones(skinned_mesh.skeleton).forEach((root_bone) => {+ // a skeleton-only export stops at the bones on purpose. Going any higher would+ // pull the mesh back in through a parent the bones and the mesh share.+ collected.push(skeleton_only ? root_bone : this.highest_ancestor_below_scene(root_bone))+ })++ if (!skeleton_only) {+ collected.push(this.highest_ancestor_below_scene(skinned_mesh))+ }+ })++ // moving the whole subtree keeps the transforms on the nodes between the mesh and+ // its bones, so anything already travelling with a parent is dropped here+ const unique_objects = Array.from(new Set(collected))+ return unique_objects.filter((object) => !this.has_ancestor_in(object, unique_objects))+ }++ /**+ * Bones are not stored in hierarchical order, and a rig can have more than one root,+ * so the first bone in the list is not reliably the top of the tree.+ */+ private static skeleton_root_bones (skeleton: Skeleton): Bone[] {+ const bones_in_skeleton = new Set<Object3D>(skeleton.bones)++ return skeleton.bones.filter((bone) => {+ // a broken file can leave gaps in the bone list, and those are not ours to export+ if (bone === undefined || bone === null) {+ return false+ }++ return bone.parent === null || !bones_in_skeleton.has(bone.parent)+ })+ }++ /**+ * Climbs to the top of the model hierarchy, stopping below the scene the model was+ * loaded into. The scene is the container we are moving out of, not part of the model.+ */+ private static highest_ancestor_below_scene (object: Object3D): Object3D {+ let highest_ancestor: Object3D = object++ while (highest_ancestor.parent !== null && (highest_ancestor.parent as Scene).isScene !== true) {+ highest_ancestor = highest_ancestor.parent+ }++ return highest_ancestor+ }++ private static has_ancestor_in (object: Object3D, candidates: Object3D[]): boolean {+ let ancestor: Object3D | null = object.parent++ while (ancestor !== null) {+ if (candidates.includes(ancestor)) {+ return true+ }++ ancestor = ancestor.parent+ }++ return false+ }+}diff --git a/src/lib/processes/export-to-file/GlbSkinCleanupService.test.ts b/src/lib/processes/export-to-file/GlbSkinCleanupService.test.tsnew file mode 100644index 0000000..5b9382b--- /dev/null+++ b/src/lib/processes/export-to-file/GlbSkinCleanupService.test.ts@@ -0,0 +1,100 @@+import { describe, it, expect } from 'vitest'+import { BoxGeometry, Bone, Float32BufferAttribute, MeshBasicMaterial, Mesh, Scene, Skeleton, SkinnedMesh, Uint16BufferAttribute } from 'three'+import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter.js'+import { GlbSkinCleanupService } from './GlbSkinCleanupService'++/**+ * Builds a rig the way an imported FBX file produces one: the bone list starts+ * with a joint from the middle of the hierarchy, not the root. GLTFExporter+ * writes bones[0] as the skin's `skeleton`, which is what validators reject+ * with SKIN_SKELETON_INVALID.+ */+function make_scene_with_unordered_bones (): Scene {+ const scene = new Scene()++ const hips = new Bone()+ hips.name = 'Hips'+ const spine = new Bone()+ spine.name = 'Spine'+ hips.add(spine)++ const geometry = new BoxGeometry(1, 1, 1)+ const vertex_count = geometry.attributes.position.count+ geometry.setAttribute('skinIndex', new Uint16BufferAttribute(new Uint16Array(vertex_count * 4), 4))+ geometry.setAttribute('skinWeight', new Float32BufferAttribute(+ Float32Array.from({ length: vertex_count * 4 }, (_, index) => (index % 4 === 0 ? 1 : 0)), 4))++ const skinned_mesh = new SkinnedMesh(geometry, new MeshBasicMaterial())+ skinned_mesh.name = 'Body'+ skinned_mesh.add(hips)+ skinned_mesh.bind(new Skeleton([spine, hips]))+ scene.add(skinned_mesh)++ return scene+}++async function export_glb (scene: Scene): Promise<ArrayBuffer> {+ const result = await new GLTFExporter().parseAsync(scene, { binary: true, onlyVisible: false })+ return result as ArrayBuffer+}++interface ParsedGlb {+ declared_length: number+ json: { skins?: Array<Record<string, unknown>> }+ remaining_bytes: Uint8Array+}++function parse_glb (glb: ArrayBuffer): ParsedGlb {+ const view = new DataView(glb)+ expect(view.getUint32(0, true)).toBe(0x46546C67) // 'glTF'+ expect(view.getUint32(4, true)).toBe(2)++ const json_length = view.getUint32(12, true)+ expect(view.getUint32(16, true)).toBe(0x4E4F534A) // 'JSON'++ return {+ declared_length: view.getUint32(8, true),+ json: JSON.parse(new TextDecoder().decode(new Uint8Array(glb, 20, json_length))),+ remaining_bytes: new Uint8Array(glb, 20 + json_length)+ }+}++describe('GlbSkinCleanupService.remove_skin_skeleton_properties', () => {+ it('removes the skeleton property the exporter wrote from a non-root bone', async () => {+ const exported = await export_glb(make_scene_with_unordered_bones())+ expect(parse_glb(exported).json.skins?.[0]).toHaveProperty('skeleton')++ const cleaned = parse_glb(GlbSkinCleanupService.remove_skin_skeleton_properties(exported))++ expect(cleaned.json.skins).toHaveLength(1)+ expect(cleaned.json.skins?.[0]).not.toHaveProperty('skeleton')+ expect(cleaned.json.skins?.[0].joints).toHaveLength(2)+ })++ it('keeps the file structurally valid after rewriting the JSON chunk', async () => {+ const exported = await export_glb(make_scene_with_unordered_bones())++ const cleaned_buffer = GlbSkinCleanupService.remove_skin_skeleton_properties(exported)+ const cleaned = parse_glb(cleaned_buffer)++ expect(cleaned.declared_length).toBe(cleaned_buffer.byteLength)+ expect(cleaned_buffer.byteLength % 4).toBe(0)++ // the binary chunk must be carried over byte for byte+ expect(cleaned.remaining_bytes).toEqual(parse_glb(exported).remaining_bytes)+ })++ it('returns the buffer untouched when the file has no skins', async () => {+ const scene = new Scene()+ scene.add(new Mesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial()))+ const exported = await export_glb(scene)++ expect(GlbSkinCleanupService.remove_skin_skeleton_properties(exported)).toBe(exported)+ })++ it('returns non-GLB data untouched', () => {+ const not_a_glb = new TextEncoder().encode('{"not":"a glb file"}').buffer as ArrayBuffer++ expect(GlbSkinCleanupService.remove_skin_skeleton_properties(not_a_glb)).toBe(not_a_glb)+ })+})diff --git a/src/lib/processes/export-to-file/GlbSkinCleanupService.ts b/src/lib/processes/export-to-file/GlbSkinCleanupService.tsnew file mode 100644index 0000000..ef40fcc--- /dev/null+++ b/src/lib/processes/export-to-file/GlbSkinCleanupService.ts@@ -0,0 +1,90 @@+/**+ * Fixes up the skins in a GLB produced by three's GLTFExporter.+ *+ * The exporter writes `skeleton.bones[0]` into each skin's optional `skeleton`+ * property, assuming the first bone is the root of the hierarchy. Rigs imported+ * from FBX list their bones in whatever order the skin clusters appear in the+ * file, so the first bone is usually some joint in the middle of the tree.+ * Validators then reject the file with "SKIN_SKELETON_INVALID: Skeleton node is+ * not a common root". The property is only a hint (viewers skin entirely from+ * `joints` + `inverseBindMatrices`), so the safe fix is to drop it.+ */+export class GlbSkinCleanupService {+ private static readonly GLB_HEADER_BYTES = 12+ private static readonly CHUNK_HEADER_BYTES = 8+ private static readonly GLB_MAGIC = 0x46546C67 // 'glTF'+ private static readonly JSON_CHUNK_TYPE = 0x4E4F534A // 'JSON'++ /**+ * @param glb a binary glTF file as produced by GLTFExporter+ * @returns a new GLB with every skin's `skeleton` property removed, or the+ * original buffer untouched when there is nothing to remove+ */+ public static remove_skin_skeleton_properties (glb: ArrayBuffer): ArrayBuffer {+ const min_length = this.GLB_HEADER_BYTES + this.CHUNK_HEADER_BYTES+ if (glb.byteLength < min_length) {+ return glb+ }++ const view = new DataView(glb)+ if (view.getUint32(0, true) !== this.GLB_MAGIC) {+ return glb+ }++ // the JSON chunk is required to be first in a GLB+ const json_chunk_length = view.getUint32(this.GLB_HEADER_BYTES, true)+ const json_chunk_type = view.getUint32(this.GLB_HEADER_BYTES + 4, true)+ const json_start = min_length++ if (json_chunk_type !== this.JSON_CHUNK_TYPE || json_start + json_chunk_length > glb.byteLength) {+ return glb+ }++ const json_bytes = new Uint8Array(glb, json_start, json_chunk_length)+ const gltf = JSON.parse(new TextDecoder().decode(json_bytes)) as { skins?: Array<Record<string, unknown>> }++ const skins = gltf.skins+ if (!Array.isArray(skins) || !skins.some((skin) => 'skeleton' in skin)) {+ return glb+ }++ skins.forEach((skin) => {+ delete skin.skeleton+ })++ return this.replace_json_chunk(glb, view, json_start, json_chunk_length, gltf)+ }++ private static replace_json_chunk (+ glb: ArrayBuffer,+ view: DataView,+ json_start: number,+ json_chunk_length: number,+ gltf: object+ ): ArrayBuffer {+ const encoded_json = new TextEncoder().encode(JSON.stringify(gltf))++ // the spec requires the JSON chunk to be padded to 4 bytes with spaces+ const padded_length = Math.ceil(encoded_json.byteLength / 4) * 4+ const padded_json = new Uint8Array(padded_length).fill(0x20)+ padded_json.set(encoded_json)++ // everything after the JSON chunk (the BIN chunk) is carried over verbatim+ const remaining_chunks = new Uint8Array(glb, json_start + json_chunk_length)+ const total_length = json_start + padded_length + remaining_chunks.byteLength++ const output = new ArrayBuffer(total_length)+ const output_bytes = new Uint8Array(output)+ const output_view = new DataView(output)++ output_view.setUint32(0, this.GLB_MAGIC, true)+ output_view.setUint32(4, view.getUint32(4, true), true) // glTF version+ output_view.setUint32(8, total_length, true)+ output_view.setUint32(this.GLB_HEADER_BYTES, padded_length, true)+ output_view.setUint32(this.GLB_HEADER_BYTES + 4, this.JSON_CHUNK_TYPE, true)+ output_bytes.set(padded_json, json_start)+ output_bytes.set(remaining_chunks, json_start + padded_length)++ return output+ }+}diff --git a/src/lib/processes/export-to-file/StepExportToFile.ts b/src/lib/processes/export-to-file/StepExportToFile.tsindex ee482cb..5455d9c 100644--- a/src/lib/processes/export-to-file/StepExportToFile.ts+++ b/src/lib/processes/export-to-file/StepExportToFile.ts@@ -4,6 +4,8 @@ import { FBXExporter } from '@comfyorg/fbx-exporter-three'import { type AnimationClip, Scene, type SkinnedMesh, type Object3D } from 'three'import { type DownloadSettings, ExportContents, ExportFormat, type FbxExportPreset } from './DownloadSettings.ts'import { ExportBoneNamingService } from './ExportBoneNamingService.ts'+import { ExportHierarchyService } from './ExportHierarchyService.ts'+import { GlbSkinCleanupService } from './GlbSkinCleanupService.ts'import { AnimationUtility } from '../animations-listing/AnimationUtility.ts'import { type AnimationExportSelection } from '../animations-listing/interfaces/AnimationExportSelection.ts'import { FbxTextureCompatibilityService } from './FbxTextureCompatibilityService.ts'@@ -70,9 +72,7 @@ export class StepExportToFile extends EventTarget {// The animation clips still target the bone names, so the selected animations continue// to work against the exported skeleton.const skeleton_only = download_settings.export_contents() === ExportContents.Skeleton- const objects_to_export: Object3D[] = skeleton_only- ? Array.from(new Set(skinned_meshes.map((mesh) => mesh.skeleton.bones[0])))- : skinned_meshes+ const objects_to_export: Object3D[] = ExportHierarchyService.collect_objects_to_export(skinned_meshes, skeleton_only)// When exporting to a file, we need to temporarily move the exported objects to a new// scene. An object can only be part of one scene at a time, so we must move it back to@@ -151,7 +151,8 @@ export class StepExportToFile extends EventTarget {(result: ArrayBuffer) => {// Handle the result of the exportif (result !== null) {- this.save_array_buffer(result, `${file_name}.glb`)+ const cleaned_result = GlbSkinCleanupService.remove_skin_skeleton_properties(result)+ this.save_array_buffer(cleaned_result, `${file_name}.glb`)resolve() // Resolve the promise when the export is complete} else {console.log('ERROR: result is not an instance of ArrayBuffer')diff --git a/src/retarget/steps/StepExportRetargetedAnimations.ts b/src/retarget/steps/StepExportRetargetedAnimations.tsindex c08dbfd..30ce0c0 100644--- a/src/retarget/steps/StepExportRetargetedAnimations.ts+++ b/src/retarget/steps/StepExportRetargetedAnimations.ts@@ -6,6 +6,8 @@ import { AnimationUtility } from '../../lib/processes/animations-listing/Animatiimport { type AnimationExportSelection } from '../../lib/processes/animations-listing/interfaces/AnimationExportSelection'import { type DownloadSettings, ExportContents, ExportFormat, type FbxExportPreset } from '../../lib/processes/export-to-file/DownloadSettings'import { ExportBoneNamingService } from '../../lib/processes/export-to-file/ExportBoneNamingService'+import { ExportHierarchyService } from '../../lib/processes/export-to-file/ExportHierarchyService'+import { GlbSkinCleanupService } from '../../lib/processes/export-to-file/GlbSkinCleanupService'import { FbxTextureCompatibilityService } from '../../lib/processes/export-to-file/FbxTextureCompatibilityService'export class StepExportRetargetedAnimations extends EventTarget {@@ -69,9 +71,7 @@ export class StepExportRetargetedAnimations extends EventTarget {)const skeleton_only = download_settings.export_contents() === ExportContents.Skeleton- const objects_to_export: Object3D[] = skeleton_only- ? Array.from(new Set(skinned_meshes.map((mesh) => mesh.skeleton.bones[0])))- : skinned_meshes+ const objects_to_export: Object3D[] = ExportHierarchyService.collect_objects_to_export(skinned_meshes, skeleton_only)const original_parents = new Map<Object3D, Object3D | null>()@@ -133,7 +133,8 @@ export class StepExportRetargetedAnimations extends EventTarget {(result: ArrayBuffer | { [key: string]: unknown }) => {// Handle the result of the exportif (result instanceof ArrayBuffer) {- this.save_array_buffer(result, `${file_name}.glb`)+ const cleaned_result = GlbSkinCleanupService.remove_skin_skeleton_properties(result)+ this.save_array_buffer(cleaned_result, `${file_name}.glb`)resolve() // Resolve the promise when the export is complete} else {console.log('ERROR: result is not an instance of ArrayBuffer')