Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Look out for imported 3d rigs that have multiple root bones. We can only support retargeting one.

Scott Petrovic036dfac1a235
diff --git a/src/retarget/MultiRootSkeletonResolver.ts b/src/retarget/MultiRootSkeletonResolver.ts
new file mode 100644
index 0000000..b996ea4
--- /dev/null
+++ b/src/retarget/MultiRootSkeletonResolver.ts
@@ -0,0 +1,263 @@
+import { Bone, Matrix4, Skeleton, type Object3D, type Scene, type SkinnedMesh } from 'three'
+
+/**
+ * Information about a single disconnected bone hierarchy (root bone chain)
+ * found inside an imported model.
+ */
+export interface RootBoneChain {
+ root_bone: Bone
+ bone_count: number
+ skinned_meshes: SkinnedMesh[]
+ vertex_count: number
+}
+
+/**
+ * Resolves FBX imports that contain multiple disconnected bone hierarchies
+ * (multiple root bones). Mesh2Motion only supports a single skeleton
+ * hierarchy, so the user picks the main root bone and everything belonging to
+ * the other hierarchies is removed: the skinned meshes bound to them, the
+ * bone subtrees, and the skeleton bindings are rebuilt so the removed bones no
+ * longer exist in the scene.
+ */
+export class MultiRootSkeletonResolver {
+ /**
+ * Detects whether the model contains more than one disconnected bone
+ * hierarchy. Returns all root bone chains found.
+ */
+ public static find_root_bone_chains (model: Scene): RootBoneChain[] {
+ const root_bones: Bone[] = this.find_root_bones(model)
+
+ return root_bones.map((root_bone) => {
+ const skinned_meshes: SkinnedMesh[] = []
+ model.traverse((child: Object3D) => {
+ if (child.type === 'SkinnedMesh') {
+ const skinned_mesh = child as SkinnedMesh
+ if (this.skinned_mesh_is_bound_to(skinned_mesh, root_bone)) {
+ skinned_meshes.push(skinned_mesh)
+ }
+ }
+ })
+
+ return {
+ root_bone,
+ bone_count: this.count_bones_in_chain(root_bone),
+ skinned_meshes,
+ vertex_count: this.count_vertices(skinned_meshes)
+ }
+ })
+ }
+
+ /**
+ * True when the model has more than one disconnected bone hierarchy.
+ */
+ public static has_multiple_root_bones (model: Scene): boolean {
+ return this.find_root_bones(model).length > 1
+ }
+
+ /**
+ * Removes every bone hierarchy except the one rooted at the bone with the
+ * given uuid. Meshes bound only to removed hierarchies are removed and
+ * disposed. Meshes whose skeletons reference the kept hierarchy are re-bound
+ * to rebuilt skeletons that no longer contain removed bones.
+ *
+ * This must run before the model is added to the render scene and before
+ * skeleton helpers or animation retargeting reference the bones.
+ */
+ public static keep_single_root_bone (model: Scene, kept_root_uuid: string): void {
+ const chains: RootBoneChain[] = this.find_root_bone_chains(model)
+ const kept_chain = chains.find((chain) => chain.root_bone.uuid === kept_root_uuid)
+
+ if (kept_chain === undefined) {
+ console.warn('MultiRootSkeletonResolver: could not find root bone to keep', kept_root_uuid)
+ return
+ }
+
+ const removed_chains = chains.filter((chain) => chain !== kept_chain)
+ const removed_bone_uuids: Set<string> = new Set<string>()
+
+ removed_chains.forEach((chain) => {
+ chain.root_bone.traverse((child: Object3D) => {
+ if (child.type === 'Bone') {
+ removed_bone_uuids.add(child.uuid)
+ }
+ })
+ })
+
+ // First pass: classify each skinned mesh and re-bind the ones we keep
+ const meshes_to_remove: SkinnedMesh[] = []
+
+ model.traverse((child: Object3D) => {
+ if (child.type !== 'SkinnedMesh') {
+ return
+ }
+
+ const skinned_mesh = child as SkinnedMesh
+ const references_kept = this.skinned_mesh_is_bound_to(skinned_mesh, kept_chain.root_bone)
+
+ if (!references_kept) {
+ // bound only to removed hierarchies: drop the mesh entirely
+ meshes_to_remove.push(skinned_mesh)
+ return
+ }
+
+ // kept mesh: rebuild the skeleton binding with only kept bones.
+ // snapshot the original bone uuids before rebinding, since the
+ // geometry's skinIndex attribute still points into the old skeleton
+ const old_bone_uuids: string[] = skinned_mesh.skeleton.bones.map((bone) => bone.uuid)
+ const kept_bones: Bone[] = []
+ const kept_bone_inverses: Matrix4[] = []
+ const kept_bone_index_by_uuid: Map<string, number> = new Map<string, number>()
+
+ skinned_mesh.skeleton.bones.forEach((bone, index) => {
+ if (!removed_bone_uuids.has(bone.uuid)) {
+ kept_bone_index_by_uuid.set(bone.uuid, kept_bones.length)
+ kept_bones.push(bone)
+ kept_bone_inverses.push(skinned_mesh.skeleton.boneInverses[index])
+ }
+ })
+
+ // swap the skeleton binding over to the rebuilt skeleton. we pass the
+ // explicit bone inverses so bind() does not recalculate them from the
+ // current pose, which would break the original skinning
+ skinned_mesh.bind(new Skeleton(kept_bones, kept_bone_inverses), skinned_mesh.bindMatrix)
+
+ // remap the vertex skin indices from old bone positions to new ones
+ this.remap_skin_indices(skinned_mesh, old_bone_uuids, kept_bone_index_by_uuid)
+ })
+
+ // Second pass: remove discarded meshes and bone subtrees from the scene
+ meshes_to_remove.forEach((skinned_mesh) => {
+ skinned_mesh.removeFromParent()
+ skinned_mesh.geometry.dispose()
+
+ const materials = Array.isArray(skinned_mesh.material) ? skinned_mesh.material : [skinned_mesh.material]
+ materials.forEach((material) => { material.dispose() })
+ })
+
+ removed_chains.forEach((chain) => {
+ chain.root_bone.removeFromParent()
+ })
+
+ model.updateMatrixWorld(true)
+ }
+
+ /**
+ * Collects the topmost bones of every disconnected bone hierarchy in the
+ * model. A bone is a root when its parent is not a Bone. Only bones actually
+ * referenced by a SkinnedMesh skeleton are considered, so unrelated
+ * decoration objects do not create phantom hierarchies.
+ */
+ private static find_root_bones (model: Scene): Bone[] {
+ const root_bones: Bone[] = []
+
+ model.traverse((child: Object3D) => {
+ if (child.type !== 'SkinnedMesh') {
+ return
+ }
+
+ const skinned_mesh = child as SkinnedMesh
+ skinned_mesh.skeleton.bones.forEach((bone) => {
+ const is_root = bone.parent === null || bone.parent.type !== 'Bone'
+ if (is_root && !root_bones.includes(bone)) {
+ root_bones.push(bone)
+ }
+ })
+ })
+
+ return root_bones
+ }
+
+ /**
+ * True when any bone in the mesh's skeleton is the root bone or one of its
+ * descendants.
+ */
+ private static skinned_mesh_is_bound_to (skinned_mesh: SkinnedMesh, root_bone: Bone): boolean {
+ return skinned_mesh.skeleton.bones.some((bone) => this.bone_is_in_chain(bone, root_bone))
+ }
+
+ private static bone_is_in_chain (bone: Bone, root_bone: Bone): boolean {
+ let current: Object3D | null = bone
+ while (current !== null) {
+ if (current === root_bone) {
+ return true
+ }
+ current = current.parent
+ }
+ return false
+ }
+
+ private static count_bones_in_chain (root_bone: Bone): number {
+ let count = 0
+ root_bone.traverse((child: Object3D) => {
+ if (child.type === 'Bone') {
+ count++
+ }
+ })
+ return count
+ }
+
+ private static count_vertices (skinned_meshes: SkinnedMesh[]): number {
+ let count = 0
+ skinned_meshes.forEach((skinned_mesh) => {
+ const position = skinned_mesh.geometry.getAttribute('position')
+ if (position !== undefined) {
+ count += position.count
+ }
+ })
+ return count
+ }
+
+ /**
+ * Rewrites the geometry's skinIndex attribute so it points at the same bones
+ * in the rebuilt skeleton. Weight and index entries that pointed at removed
+ * bones are zeroed so they contribute nothing.
+ * @param old_bone_uuids bone uuids in the skeleton's original bone order,
+ * captured before rebinding. The geometry's skinIndex still refers to these.
+ */
+ private static remap_skin_indices (
+ skinned_mesh: SkinnedMesh,
+ old_bone_uuids: string[],
+ kept_bone_index_by_uuid: Map<string, number>
+ ): void {
+ const skin_index = skinned_mesh.geometry.getAttribute('skinIndex')
+ const skin_weight = skinned_mesh.geometry.getAttribute('skinWeight')
+
+ if (skin_index === undefined || skin_weight === undefined) {
+ return
+ }
+
+ for (let vertex_index = 0; vertex_index < skin_index.count; vertex_index++) {
+ for (let component = 0; component < 4; component++) {
+ const old_bone_index: number = skin_index.getComponent(vertex_index, component)
+ const bone_uuid: string | undefined = old_bone_uuids[old_bone_index]
+ const new_index: number | undefined = bone_uuid !== undefined ? kept_bone_index_by_uuid.get(bone_uuid) : undefined
+
+ if (new_index === undefined) {
+ // pointed at a removed bone: contribute nothing
+ skin_index.setComponent(vertex_index, component, 0)
+ skin_weight.setComponent(vertex_index, component, 0)
+ } else {
+ skin_index.setComponent(vertex_index, component, new_index)
+ }
+ }
+ }
+
+ // renormalize weights per vertex so zeroed influences do not shrink the skin
+ for (let vertex_index = 0; vertex_index < skin_weight.count; vertex_index++) {
+ const total: number =
+ skin_weight.getComponent(vertex_index, 0) +
+ skin_weight.getComponent(vertex_index, 1) +
+ skin_weight.getComponent(vertex_index, 2) +
+ skin_weight.getComponent(vertex_index, 3)
+
+ if (total > 0 && total !== 1) {
+ for (let component = 0; component < 4; component++) {
+ skin_weight.setComponent(vertex_index, component, skin_weight.getComponent(vertex_index, component) / total)
+ }
+ }
+ }
+
+ skin_index.needsUpdate = true
+ skin_weight.needsUpdate = true
+ }
+}
diff --git a/src/retarget/RootBoneSelectionDialog.ts b/src/retarget/RootBoneSelectionDialog.ts
new file mode 100644
index 0000000..bd21e83
--- /dev/null
+++ b/src/retarget/RootBoneSelectionDialog.ts
@@ -0,0 +1,96 @@
+import type { RootBoneChain } from './MultiRootSkeletonResolver.ts'
+
+/**
+ * Modal dialog that asks the user which root bone is the main skeleton when
+ * an imported model contains multiple disconnected bone hierarchies. Resolves
+ * with the uuid of the chosen root bone, or null when the user cancels.
+ */
+export class RootBoneSelectionDialog {
+ private dialog_element: HTMLDivElement | null = null
+
+ /**
+ * Shows the dialog and waits for the user to pick a root bone.
+ * @returns The uuid of the chosen root bone, or null when cancelled.
+ */
+ public show (root_chains: RootBoneChain[]): Promise<string | null> {
+ return new Promise<string | null>((resolve) => {
+ this.remove()
+
+ const options_html: string = root_chains
+ .map((chain, index) => this.create_chain_option_html(chain, index))
+ .join('')
+
+ this.dialog_element = document.createElement('div')
+ this.dialog_element.className = 'modal-dialog-overlay root-bone-selection-modal'
+ this.dialog_element.innerHTML = `
+ <div class="modal-dialog-content">
+ <h2>Multiple Root Bones Detected in Skeleton</h2>
+ <div class="modal-dialog-body">
+ <p>
+ This model contains ${root_chains.length} separate root bones (which translates to multiple skeletons).
+ Mesh2Motion can only retarget a single skeleton hierarchy, so choose the main one to
+ keep. All other skeletons will be discarded.
+ </p>
+ <div class="root-bone-selection-list">${options_html}</div>
+ </div>
+ <div class="root-bone-selection-actions">
+ <button class="root-bone-selection-cancel">Cancel Import</button>
+ </div>
+ </div>
+ `
+ document.body.appendChild(this.dialog_element)
+
+ this.dialog_element.querySelectorAll<HTMLButtonElement>('[data-root-uuid]').forEach((button) => {
+ button.addEventListener('click', () => {
+ const root_uuid = button.dataset.rootUuid ?? null
+ this.remove()
+ resolve(root_uuid)
+ })
+ })
+
+ this.dialog_element.querySelector('.root-bone-selection-cancel')?.addEventListener('click', () => {
+ this.remove()
+ resolve(null)
+ })
+
+ this.dialog_element.addEventListener('click', (event) => {
+ if (event.target === this.dialog_element) {
+ this.remove()
+ resolve(null)
+ }
+ })
+ })
+ }
+
+ // Creates the HTML for a single root bone option in the dialog.
+ private create_chain_option_html (chain: RootBoneChain, index: number): string {
+ const bone_word = chain.bone_count === 1 ? 'bone' : 'bones'
+
+
+ return `
+ <button class="root-bone-selection-option" data-root-uuid="${chain.root_bone.uuid}">
+ <span class="root-bone-option-name">
+ Root ${index + 1}: ${this.escape_html(chain.root_bone.name)} bone (${chain.bone_count} ${bone_word})
+ </span>
+ </button>
+ `
+ }
+
+ // Removes the dialog from the DOM and cleans up event listeners.
+ public remove (): void {
+ if (this.dialog_element !== null && this.dialog_element.parentNode !== null) {
+ this.dialog_element.parentNode.removeChild(this.dialog_element)
+ this.dialog_element = null
+ }
+ }
+
+ // Bone names can contain HTML special characters, so escape them
+ private escape_html (value: string): string {
+ return value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;')
+ }
+}
diff --git a/src/retarget/retarget.css b/src/retarget/retarget.css
index d7ec036..80d6dac 100644
--- a/src/retarget/retarget.css
+++ b/src/retarget/retarget.css
@@ -184,4 +184,46 @@ h1 {
}
#view-bone-tree-button:hover {
opacity: 1;
+}
+
+/* Root bone selection dialog (multi-skeleton FBX imports) */
+
+.root-bone-selection-list {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ margin-top: 1rem;
+}
+
+.root-bone-selection-option {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.15rem;
+ width: 100%;
+ text-align: left;
+ padding: 0.6rem 0.8rem;
+ border: 2px solid var(--bg-tertiary);
+ border-radius: 0.25rem;
+ background: var(--bg-primary);
+ cursor: pointer;
+}
+
+.root-bone-selection-option:hover {
+ border-color: var(--primary-color);
+ transform: scale(1.02);
+}
+
+.root-bone-option-name {
+ font-weight: bold;
+}
+
+.root-bone-option-details {
+ opacity: 0.7;
+ font-size: 0.875rem;
+}
+
+.root-bone-selection-actions {
+ margin-top: 1rem;
+ text-align: center;
}
\ No newline at end of file
diff --git a/src/retarget/steps/StepLoadTargetModel.ts b/src/retarget/steps/StepLoadTargetModel.ts
index 125f8a1..033983d 100644
--- a/src/retarget/steps/StepLoadTargetModel.ts
+++ b/src/retarget/steps/StepLoadTargetModel.ts
@@ -1,7 +1,9 @@
import { type Bone, Box3, type Scene, type SkinnedMesh, Vector3 } from 'three'
import { type Mesh2MotionEngine } from '../../Mesh2MotionEngine.ts'
import { ModalDialog } from '../../lib/ModalDialog.ts'
+import { MultiRootSkeletonResolver, type RootBoneChain } from '../MultiRootSkeletonResolver.ts'
import { RetargetUtils } from '../RetargetUtils.ts'
+import { RootBoneSelectionDialog } from '../RootBoneSelectionDialog.ts'
import { TargetBoneTreeDialog } from '../TargetBoneTreeDialog.ts'
/**
@@ -10,6 +12,7 @@ import { TargetBoneTreeDialog } from '../TargetBoneTreeDialog.ts'
export class StepLoadTargetModel extends EventTarget {
private readonly mesh2motion_engine: Mesh2MotionEngine
private readonly target_bone_tree_dialog: TargetBoneTreeDialog
+ private readonly root_bone_selection_dialog: RootBoneSelectionDialog = new RootBoneSelectionDialog()
private file_input: HTMLInputElement | null = null
private load_model_button: HTMLLabelElement | null = null
@@ -110,41 +113,11 @@ export class StepLoadTargetModel extends EventTarget {
// read in mesh2motion engine's retargetable model data (this is the target)
const retargetable_meshes: Scene = this.mesh2motion_engine.load_model_step.get_final_retargetable_model_data()
const is_valid_skinned_mesh = RetargetUtils.validate_skinned_mesh_has_bones(retargetable_meshes)
+
if (is_valid_skinned_mesh) {
- // we have valid skinned mesh(s). The could be very large though,
- // we let's check to see how large everything is
- const bounding_box = new Box3().setFromObject(retargetable_meshes)
- const size = new Vector3()
- bounding_box.getSize(size)
- // console.log('Retargetable meshes bounding box size:', size)
- // console.log('Skinned mesh data to inspect:', retargetable_meshes)
-
- RetargetUtils.reset_skinned_mesh_to_rest_pose(retargetable_meshes)
- this.mesh2motion_engine.get_scene().add(retargetable_meshes)
- const largest_dimension: number = this.calculate_max_mesh_dimension(retargetable_meshes)
-
- // if the largest dimension is over 20, scale the entire scene down to be
- const target_height: number = 1.5 // in meters
- if (largest_dimension > 20) {
- // calculate scale factor
- const scale_factor = target_height / largest_dimension
- console.log('scaling model down because of ', largest_dimension)
- new ModalDialog('Large Rig Warning',
- `The model you imported is large (${largest_dimension.toFixed(1)} meters). Mesh2Motion expects 1 unit = 1 meter. Your model will be scaled down. Mixamo rigs will work as long as they only have one skeleton in the model file.`).show()
- retargetable_meshes.scale.set(scale_factor, scale_factor, scale_factor) // common case with 3d creation tools that use 1 cm = 1 unit
- }
-
- // need to compare skeletons. for some reason the GLBs scale down fine, but the FBX bones are not looking right
- console.log('Final retargetable meshes after potential scaling:', retargetable_meshes)
-
- // Add skeleton helper
- this.add_skeleton_helper(retargetable_meshes)
-
- // Save the final retargetable meshes and dispatch event
- this.retargetable_meshes = retargetable_meshes
- this.target_bone_tree_dialog.set_target_bones(this.get_first_skinned_mesh_bones())
- this.target_bone_tree_dialog.set_target_skinned_mesh_count(this.get_target_skinned_mesh_count())
- this.dispatchEvent(new CustomEvent('target-model-loaded'))
+ this.resolve_model_root_bones(retargetable_meshes).catch((error) => {
+ console.error('Error resolving multiple skeletons in model:', error)
+ })
}
}, { once: true })
} catch (error) {
@@ -163,6 +136,71 @@ export class StepLoadTargetModel extends EventTarget {
// class to see what is going on.
}
+ /**
+ * Some FBX files contain multiple disconnected bone hierarchies (multiple
+ * root bones). Mesh2Motion only supports a single hierarchy, so the user is
+ * asked which root bone is the main skeleton and everything else is removed.
+ * Once the model has a single hierarchy, the regular retarget setup runs.
+ */
+ private async resolve_model_root_bones (retargetable_meshes: Scene): Promise<void> {
+ if (MultiRootSkeletonResolver.has_multiple_root_bones(retargetable_meshes)) {
+ const root_chains: RootBoneChain[] = MultiRootSkeletonResolver.find_root_bone_chains(retargetable_meshes)
+ const chosen_root_uuid: string | null = await this.root_bone_selection_dialog.show(root_chains)
+
+ if (chosen_root_uuid === null) {
+ console.log('User cancelled import after being asked to choose a root bone')
+ return
+ }
+
+ MultiRootSkeletonResolver.keep_single_root_bone(retargetable_meshes, chosen_root_uuid)
+
+ // the extra hierarchies might have owned every skinned mesh
+ if (!RetargetUtils.validate_skinned_mesh_has_bones(retargetable_meshes)) {
+ console.warn('No skinned meshes remain after removing the extra skeletons')
+ return
+ }
+ }
+
+ this.process_retargetable_model(retargetable_meshes)
+ }
+
+ private process_retargetable_model (retargetable_meshes: Scene): void {
+ // we have valid skinned mesh(s). The could be very large though,
+ // we let's check to see how large everything is
+ const bounding_box = new Box3().setFromObject(retargetable_meshes)
+ const size = new Vector3()
+ bounding_box.getSize(size)
+ // console.log('Retargetable meshes bounding box size:', size)
+ // console.log('Skinned mesh data to inspect:', retargetable_meshes)
+
+ RetargetUtils.reset_skinned_mesh_to_rest_pose(retargetable_meshes)
+ this.mesh2motion_engine.get_scene().add(retargetable_meshes)
+ const largest_dimension: number = this.calculate_max_mesh_dimension(retargetable_meshes)
+
+ // if the largest dimension is over 20, scale the entire scene down to be
+ const target_height: number = 1.5 // in meters
+ if (largest_dimension > 20) {
+ // calculate scale factor
+ const scale_factor = target_height / largest_dimension
+ console.log('scaling model down because of ', largest_dimension)
+ new ModalDialog('Large Rig Warning',
+ `The model you imported is large (${largest_dimension.toFixed(1)} meters). Mesh2Motion expects 1 unit = 1 meter. Your model will be scaled down. Mixamo rigs will work as long as they only have one skeleton in the model file.`).show()
+ retargetable_meshes.scale.set(scale_factor, scale_factor, scale_factor) // common case with 3d creation tools that use 1 cm = 1 unit
+ }
+
+ // need to compare skeletons. for some reason the GLBs scale down fine, but the FBX bones are not looking right
+ console.log('Final retargetable meshes after potential scaling:', retargetable_meshes)
+
+ // Add skeleton helper
+ this.add_skeleton_helper(retargetable_meshes)
+
+ // Save the final retargetable meshes and dispatch event
+ this.retargetable_meshes = retargetable_meshes
+ this.target_bone_tree_dialog.set_target_bones(this.get_first_skinned_mesh_bones())
+ this.target_bone_tree_dialog.set_target_skinned_mesh_count(this.get_target_skinned_mesh_count())
+ this.dispatchEvent(new CustomEvent('target-model-loaded'))
+ }
+
private add_skeleton_helper (retargetable_meshes: Scene): void {
retargetable_meshes.traverse((child) => {
if (child.type === 'SkinnedMesh') {