Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Import Mixamo and other humanoid animations by retargeting

Scott Petrovic1168413fa17a
diff --git a/src/create.html b/src/create.html
index a62efeb..dbc33d7 100644
--- a/src/create.html
+++ b/src/create.html
@@ -400,8 +400,8 @@
<button
class="secondary-button"
id="import-animations-button"
- data-tippy-content="Import GLB animations. Only Mesh2Motion rigs are supported at this time."
- aria-label="Import GLB animations. Only Mesh2Motion rigs are supported at this time."
+ data-tippy-content="Import GLB or FBX animations. Mesh2Motion rigs are supported, and Mixamo animations can be retargeted onto the Human rig."
+ aria-label="Import GLB or FBX animations. Mesh2Motion rigs are supported, and Mixamo animations can be retargeted onto the Human rig."
>
<img src="images/icons/upload.svg" alt="Upload" width="16" height="16" />
@@ -410,7 +410,7 @@
<input
id="import-animations-input"
type="file"
- accept=".glb"
+ accept=".glb,.fbx"
multiple
style="display: none"
/>
diff --git a/src/index.html b/src/index.html
index 4e17ee3..5b60b1f 100644
--- a/src/index.html
+++ b/src/index.html
@@ -160,10 +160,10 @@
</label>
</div>
- <button class="secondary-button" id="import-animations-button" data-tippy-content="Import GLB animations. Only Mesh2Motion rigs are supported at this time." aria-label="Import GLB animations. Only Mesh2Motion rigs are supported at this time.">
+ <button class="secondary-button" id="import-animations-button" data-tippy-content="Import GLB or FBX animations. Mesh2Motion rigs are supported, and Mixamo animations can be retargeted onto the Human rig." aria-label="Import GLB or FBX animations. Mesh2Motion rigs are supported, and Mixamo animations can be retargeted onto the Human rig.">
<img src="images/icons/upload.svg" alt="Upload" width="20" height="20" />
</button>
- <input id="import-animations-input" type="file" accept=".glb" multiple style="display:none" />
+ <input id="import-animations-input" type="file" accept=".glb,.fbx" multiple style="display:none" />
<div id="download-control-mount"></div>
</div>
diff --git a/src/lib/processes/animations-listing/AnimationLoader.ts b/src/lib/processes/animations-listing/AnimationLoader.ts
index f94e4b0..5942f3d 100644
--- a/src/lib/processes/animations-listing/AnimationLoader.ts
+++ b/src/lib/processes/animations-listing/AnimationLoader.ts
@@ -1,6 +1,7 @@
-import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
+import { type GLTF, GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js'
-import { type AnimationClip } from 'three'
+import { type AnimationClip, type Group, type Object3D } from 'three'
+import { FBXLoader } from '../../io/FBXLoader.ts'
import { AnimationUtility } from './AnimationUtility.ts'
import { type SkeletonType } from '../../enums/SkeletonType.ts'
import { RigConfig } from '../../RigConfig.ts'
@@ -19,9 +20,17 @@ export interface AnimationLoadProgress {
overallBytesTotal: number
}
+export interface LoadedAnimationSource {
+ animations: AnimationClip[]
+ // scene the animations came with. Holds the rig they were authored on
+ scene: Object3D
+}
+
export class AnimationLoader extends EventTarget {
// animation GLBs from the asset library are meshopt compressed
private readonly gltf_loader: GLTFLoader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder)
+ // custom imports can also come in as FBX, which is what Mixamo hands out
+ private readonly fbx_loader: FBXLoader = new FBXLoader()
// prefix that points from the current page to the static root, e.g. '../' for pages in a sub-folder
private static_root_path: string = ''
private readonly file_progress_map = new Map<string, { loaded: number, total: number }>()
@@ -67,21 +76,18 @@ export class AnimationLoader extends EventTarget {
}
/**
- * Loads animations from a local GLB file and validates against target skeleton.
- * @param file The GLB file to load
- * @param skinned_meshes Target skinned meshes to validate against
- * @param skeleton_scale Scale factor to apply to position keyframes
- * @returns Promise that resolves with the loaded animation clips
+ * Loads the raw animations from a local GLB or FBX file, along with the scene they were
+ * authored on. The scene holds the source rig, which is needed when the animations have
+ * to be retargeted onto our skeleton. Nothing is processed or validated here.
+ * @param file The GLB or FBX file to load
+ * @returns Promise that resolves with the unprocessed clips and their scene
* @throws {NoAnimationsError} If no animations found in file
* @throws {LoadError} If file cannot be loaded
*/
- public async load_animations_from_file (
- file: File,
- skeleton_scale: number = 1.0,
- metadata_override: Partial<AnimationClipMetadata> = {}
- ): Promise<TransformedAnimationClipPair[]> {
+ public async load_animation_source_file (file: File): Promise<LoadedAnimationSource> {
const file_url = URL.createObjectURL(file)
const file_total = file.size > 0 ? file.size : 1
+ const is_fbx: boolean = file.name.toLowerCase().endsWith('.fbx')
this.file_progress_map.clear()
this.completed_files = 0
@@ -89,58 +95,46 @@ export class AnimationLoader extends EventTarget {
this.file_progress_map.set(file.name, { loaded: 0, total: file_total })
this.emit_enhanced_progress(file.name, 0, file_total)
+ const finish_progress = (): void => {
+ // Emit final progress to hide the loader UI
+ this.file_progress_map.set(file.name, { loaded: file_total, total: file_total })
+ this.completed_files = 1
+ this.emit_enhanced_progress(file.name, file_total, file_total)
+ }
+
return await new Promise((resolve, reject) => {
- this.gltf_loader.load(
- file_url,
- (gltf: any) => {
- URL.revokeObjectURL(file_url)
-
- try {
- const animations = gltf.animations as AnimationClip[]
- if (animations === null || animations === undefined || animations.length === 0) {
- this.file_progress_map.set(file.name, { loaded: file_total, total: file_total })
- this.completed_files = 1
- this.emit_enhanced_progress(file.name, file_total, file_total)
- throw new NoAnimationsError('No animations found in the GLB file.')
- }
-
- this.file_progress_map.set(file.name, { loaded: file_total, total: file_total })
- this.completed_files = 1
- this.emit_enhanced_progress(file.name, file_total, file_total)
-
- const processed_clips = this.process_loaded_animations(
- animations,
- skeleton_scale,
- metadata_override
- )
- resolve(processed_clips)
- } catch (error) {
- // Emit final progress to hide the loader UI
- this.file_progress_map.set(file.name, { loaded: file_total, total: file_total })
- this.completed_files = 1
- this.emit_enhanced_progress(file.name, file_total, file_total)
-
- const error_message = error instanceof Error ? error.message : String(error)
- if (error instanceof NoAnimationsError) {
- reject(error)
- } else {
- reject(new LoadError(`Failed to process animations from ${file.name}: ${error_message}`))
- }
- }
- },
- (progress_event) => {
- if (progress_event.lengthComputable) {
- const total_bytes = progress_event.total > 0 ? progress_event.total : file_total
- this.file_progress_map.set(file.name, { loaded: progress_event.loaded, total: total_bytes })
- this.emit_enhanced_progress(file.name, progress_event.loaded, total_bytes)
- }
- },
- (error) => {
- URL.revokeObjectURL(file_url)
- const error_message = error instanceof Error ? error.message : String(error)
- reject(new LoadError(`Failed to load animation file ${file.name}: ${error_message}`))
+ const on_load = (scene: Object3D, animations: AnimationClip[] | undefined): void => {
+ URL.revokeObjectURL(file_url)
+ finish_progress()
+
+ if (animations === undefined || animations.length === 0) {
+ reject(new NoAnimationsError('No animations found in the file.'))
+ return
}
- )
+
+ resolve({ animations, scene })
+ }
+
+ const on_progress = (progress_event: ProgressEvent): void => {
+ if (progress_event.lengthComputable) {
+ const total_bytes = progress_event.total > 0 ? progress_event.total : file_total
+ this.file_progress_map.set(file.name, { loaded: progress_event.loaded, total: total_bytes })
+ this.emit_enhanced_progress(file.name, progress_event.loaded, total_bytes)
+ }
+ }
+
+ const on_error = (error: unknown): void => {
+ URL.revokeObjectURL(file_url)
+ finish_progress()
+ const error_message = error instanceof Error ? error.message : String(error)
+ reject(new LoadError(`Failed to load animation file ${file.name}: ${error_message}`))
+ }
+
+ if (is_fbx) {
+ this.fbx_loader.load(file_url, (fbx: Group) => { on_load(fbx, fbx.animations) }, on_progress, on_error)
+ } else {
+ this.gltf_loader.load(file_url, (gltf: GLTF) => { on_load(gltf.scene, gltf.animations) }, on_progress, on_error)
+ }
})
}
diff --git a/src/lib/processes/animations-listing/CustomAnimationImporter.ts b/src/lib/processes/animations-listing/CustomAnimationImporter.ts
index 8339f61..dbe8dbe 100644
--- a/src/lib/processes/animations-listing/CustomAnimationImporter.ts
+++ b/src/lib/processes/animations-listing/CustomAnimationImporter.ts
@@ -1,20 +1,33 @@
import { UI } from '../../UI.ts'
import { ModalDialog } from '../../ModalDialog.ts'
import { type AnimationClip, type SkinnedMesh } from 'three'
-import { type AnimationLoader } from './AnimationLoader.ts'
+import { type AnimationLoader, type LoadedAnimationSource } from './AnimationLoader.ts'
import CustomAnimationValidation from './CustomAnimationValidation.ts'
+import { IncompatibleSkeletonError } from './AnimationImportErrors.ts'
+import { ImportedAnimationRetargeter } from './ImportedAnimationRetargeter.ts'
import { type AnimationClipMetadata, type TransformedAnimationClipPair } from './interfaces/TransformedAnimationClipPair.ts'
+import { SkeletonType } from '../../enums/SkeletonType.ts'
+
+export interface AnimationImportContext {
+ skinned_meshes_to_animate: SkinnedMesh[]
+ skeleton_scale: number
+ skeleton_type: SkeletonType
+}
/**
- * Handles the importing of custom animations from GLB files.
+ * Handles the importing of custom animations from GLB and FBX files.
* This class encapsulates the UI and logic for the import process.
+ *
+ * Animations authored on the Mesh2Motion rig are used as they are. Animations authored on
+ * another humanoid rig (Mixamo, etc) are retargeted onto the human skeleton.
*/
export class CustomAnimationImporter extends EventTarget {
private readonly ui: UI
private readonly animation_loader: AnimationLoader
private skinned_meshes_to_animate: SkinnedMesh[] = []
private skeleton_scale: number = 1.0
- private import_context_provider: (() => { skinned_meshes_to_animate: SkinnedMesh[], skeleton_scale: number }) | null = null
+ private skeleton_type: SkeletonType = SkeletonType.None
+ private import_context_provider: (() => AnimationImportContext) | null = null
private enabled: boolean = true
private has_added_event_listeners: boolean = false
@@ -25,12 +38,13 @@ export class CustomAnimationImporter extends EventTarget {
this.add_event_listeners()
}
- public set_import_context (skinned_meshes_to_animate: SkinnedMesh[], skeleton_scale: number): void {
- this.skinned_meshes_to_animate = skinned_meshes_to_animate
- this.skeleton_scale = skeleton_scale
+ public set_import_context (context: AnimationImportContext): void {
+ this.skinned_meshes_to_animate = context.skinned_meshes_to_animate
+ this.skeleton_scale = context.skeleton_scale
+ this.skeleton_type = context.skeleton_type
}
- public set_import_context_provider (provider: () => { skinned_meshes_to_animate: SkinnedMesh[], skeleton_scale: number }): void {
+ public set_import_context_provider (provider: () => AnimationImportContext): void {
this.import_context_provider = provider
}
@@ -84,11 +98,11 @@ export class CustomAnimationImporter extends EventTarget {
try {
for (const file of Array.from(files)) {
const file_name = file.name.toLowerCase()
- if (!file_name.endsWith('.glb')) {
- new ModalDialog('Unsupported file type. Please select a GLB file.', 'Error').show()
+ if (!file_name.endsWith('.glb') && !file_name.endsWith('.fbx')) {
+ new ModalDialog('Unsupported file type. Please select a GLB or FBX file.', 'Error').show()
continue
}
- await this.import_animation_glb(file)
+ await this.import_animation_file(file)
}
} finally {
input.value = ''
@@ -101,11 +115,10 @@ export class CustomAnimationImporter extends EventTarget {
return
}
- const { skinned_meshes_to_animate, skeleton_scale } = this.import_context_provider()
- this.set_import_context(skinned_meshes_to_animate, skeleton_scale)
+ this.set_import_context(this.import_context_provider())
}
- private async import_animation_glb (file: File): Promise<{ success: boolean, clipCount: number }> {
+ private async import_animation_file (file: File): Promise<{ success: boolean, clipCount: number }> {
// tell the animation data these are custom animations to help differentiate for custom video previews
// tags are unused right now, but I want to eventually use them to help filtering
const metadata_override: Partial<AnimationClipMetadata> = {
@@ -114,26 +127,34 @@ export class CustomAnimationImporter extends EventTarget {
}
try {
- const new_animation_clips = await this.animation_loader.load_animations_from_file(
- file,
- this.skeleton_scale,
- metadata_override
- )
+ const source: LoadedAnimationSource = await this.animation_loader.load_animation_source_file(file)
- // Validate custom animations against our target skeleton
- const animation_clip_names_imported = new_animation_clips.map(clip_pair => clip_pair.display_animation_clip.name).join(', ')
- const clips_to_validate: AnimationClip[] = new_animation_clips.map((clip_pair) => clip_pair.display_animation_clip)
- CustomAnimationValidation.validate_animation_bones_match(clips_to_validate, this.skinned_meshes_to_animate)
+ let new_animation_clips: TransformedAnimationClipPair[]
+ let success_note: string = ''
+
+ try {
+ new_animation_clips = this.process_mesh2motion_animations(source, metadata_override)
+ } catch (error) {
+ // not authored on our rig. See if it is a rig we can retarget from
+ if (!(error instanceof IncompatibleSkeletonError) || !this.can_retarget()) {
+ throw error
+ }
+
+ const retargeter = ImportedAnimationRetargeter.create(source.scene, this.skinned_meshes_to_animate[0])
+ new_animation_clips = this.process_retargeted_animations(source, retargeter, file.name, metadata_override)
+ success_note = ` (retargeted from a ${retargeter.mapping_type} rig)`
+ }
this.dispatchEvent(new CustomEvent<TransformedAnimationClipPair[]>('import-success', {
detail: new_animation_clips
}))
+ const animation_clip_names_imported = new_animation_clips.map(clip_pair => clip_pair.display_animation_clip.name).join(', ')
const animation_count = new_animation_clips.length
const animation_word = animation_count === 1 ? 'animation' : 'animations'
new ModalDialog(
'Import Success',
- `${animation_count} ${animation_word} Imported successfully: ${animation_clip_names_imported}`
+ `${animation_count} ${animation_word} Imported successfully${success_note}: ${animation_clip_names_imported}`
).show()
return { success: true, clipCount: new_animation_clips.length }
@@ -141,4 +162,51 @@ export class CustomAnimationImporter extends EventTarget {
return CustomAnimationValidation.handle_import_error(error)
}
}
+
+ /**
+ * Animations authored on the Mesh2Motion rig play as they are
+ * @throws {IncompatibleSkeletonError} If the bones don't match our skeleton
+ */
+ private process_mesh2motion_animations (
+ source: LoadedAnimationSource,
+ metadata_override: Partial<AnimationClipMetadata>
+ ): TransformedAnimationClipPair[] {
+ const clip_pairs = this.animation_loader.process_loaded_animations(
+ source.animations,
+ this.skeleton_scale,
+ metadata_override
+ )
+
+ // Validate custom animations against our target skeleton
+ const clips_to_validate: AnimationClip[] = clip_pairs.map((clip_pair) => clip_pair.display_animation_clip)
+ CustomAnimationValidation.validate_animation_bones_match(clips_to_validate, this.skinned_meshes_to_animate)
+
+ return clip_pairs
+ }
+
+ /**
+ * Animations from other rigs get baked onto our skeleton first
+ * @throws {IncompatibleSkeletonError} If the file's rig can't be mapped onto ours
+ */
+ private process_retargeted_animations (
+ source: LoadedAnimationSource,
+ retargeter: ImportedAnimationRetargeter,
+ file_name: string,
+ metadata_override: Partial<AnimationClipMetadata>
+ ): TransformedAnimationClipPair[] {
+ // Mixamo names every clip "mixamo.com", so a single clip is better off named after its file
+ const file_base_name: string = file_name.replace(/\.[^.]+$/, '')
+ const retargeted_clips: AnimationClip[] = source.animations.map((clip) =>
+ retargeter.retarget(clip, source.animations.length === 1 ? file_base_name : clip.name))
+
+ // baked against the final skeleton, which already has the skeleton scale in it
+ return this.animation_loader.process_loaded_animations(retargeted_clips, 1.0, metadata_override)
+ }
+
+ /**
+ * Retargeting maps onto human chains (arms, legs, spine), so it only works for the human skeleton
+ */
+ private can_retarget (): boolean {
+ return this.skeleton_type === SkeletonType.Human && this.skinned_meshes_to_animate.length > 0
+ }
}
diff --git a/src/lib/processes/animations-listing/CustomAnimationValidation.ts b/src/lib/processes/animations-listing/CustomAnimationValidation.ts
index 735dabb..bfbd16c 100644
--- a/src/lib/processes/animations-listing/CustomAnimationValidation.ts
+++ b/src/lib/processes/animations-listing/CustomAnimationValidation.ts
@@ -131,7 +131,7 @@ export default class CustomAnimationValidation {
static handle_import_error (error: unknown): { success: boolean, clipCount: number } {
const error_title = 'Error Importing Animation(s)'
if (error instanceof NoAnimationsError) {
- new ModalDialog(error_title, 'No animations found in that glb file').show()
+ new ModalDialog(error_title, 'No animations found in that file').show()
return { success: false, clipCount: 0 }
}
@@ -147,7 +147,7 @@ export default class CustomAnimationValidation {
}
// Unknown error
- new ModalDialog(error_title, 'failed to import animations from the glb file for an unknown reason').show()
+ new ModalDialog(error_title, 'failed to import animations from the file for an unknown reason').show()
return { success: false, clipCount: 0 }
}
}
diff --git a/src/lib/processes/animations-listing/ImportedAnimationRetargeter.ts b/src/lib/processes/animations-listing/ImportedAnimationRetargeter.ts
new file mode 100644
index 0000000..ed8f326
--- /dev/null
+++ b/src/lib/processes/animations-listing/ImportedAnimationRetargeter.ts
@@ -0,0 +1,125 @@
+import { type AnimationClip, type Bone, type Object3D, Skeleton, type SkinnedMesh } from 'three'
+import { BoneAutoMapper } from '../../../retarget/bone-automap/BoneAutoMapper.ts'
+import { type TargetBoneMappingType } from '../../../retarget/bone-automap/TargetBoneMappingType.ts'
+import { HumanChainConfig } from '../../../retarget/human-retargeting/HumanChainConfig.ts'
+import { HumanClipRetargeter } from '../../../retarget/human-retargeting/HumanClipRetargeter.ts'
+import { Rig } from '../../../retarget/human-retargeting/Rig.ts'
+import { RetargetUtils, type BoneRestTransform } from '../../../retarget/RetargetUtils.ts'
+import { IncompatibleSkeletonError } from './AnimationImportErrors.ts'
+
+/**
+ * Retargets animations authored on another humanoid rig (Mixamo, Rigify, etc) onto the
+ * Mesh2Motion human skeleton the user is animating.
+ *
+ * This is the retarget page run backwards: there, Mesh2Motion animations drive an
+ * uploaded rig. Here, the imported file's rig drives the Mesh2Motion rig. Bone mapping
+ * and swing-twist retargeting are shared with the retarget page; only the direction differs.
+ */
+export class ImportedAnimationRetargeter {
+ // chains that have to map completely before a retarget is worth showing. Without
+ // these the character would be missing a limb or its hips
+ private static readonly REQUIRED_CHAINS: string[] = ['pelvis', 'armL', 'armR', 'legL', 'legR']
+
+ private readonly source_skeleton: Skeleton
+ private readonly source_rest_transforms: BoneRestTransform[]
+ private readonly source_config: Record<string, string[]>
+
+ private readonly target_skinned_mesh: SkinnedMesh
+ private readonly target_rest_transforms: BoneRestTransform[]
+ private readonly target_config: Record<string, string[]>
+
+ public readonly mapping_type: TargetBoneMappingType
+
+ private constructor (
+ source_skeleton: Skeleton,
+ source_config: Record<string, string[]>,
+ target_skinned_mesh: SkinnedMesh,
+ target_config: Record<string, string[]>,
+ mapping_type: TargetBoneMappingType
+ ) {
+ this.source_skeleton = source_skeleton
+ this.source_config = source_config
+ this.target_skinned_mesh = target_skinned_mesh
+ this.target_config = target_config
+ this.mapping_type = mapping_type
+
+ // the file was just loaded and nothing has played on it, so its bones are at rest
+ this.source_rest_transforms = RetargetUtils.capture_bone_rest_transforms(source_skeleton)
+
+ // our skeleton is probably mid-animation, so recover its rest pose from the bind matrices
+ this.target_rest_transforms = RetargetUtils.capture_bind_pose_rest_transforms(target_skinned_mesh)
+ }
+
+ /**
+ * Map the imported file's rig onto the Mesh2Motion skeleton
+ * @param source_scene - scene that came with the imported animations, holding their rig
+ * @param target_skinned_mesh - any skinned mesh bound to the Mesh2Motion skeleton
+ * @throws {IncompatibleSkeletonError} If the file has no rig or it does not map onto a human
+ */
+ public static create (source_scene: Object3D, target_skinned_mesh: SkinnedMesh): ImportedAnimationRetargeter {
+ // bones come out parents-first, which Pose relies on
+ const source_bones: Bone[] = RetargetUtils.collect_bones(source_scene)
+ if (source_bones.length === 0) {
+ throw new IncompatibleSkeletonError('The file has no skeleton, so its animations can\'t be retargeted.')
+ }
+
+ const target_bones: Bone[] = target_skinned_mesh.skeleton.bones
+
+ // the bone mapper calls the Mesh2Motion rig the source. Ours is the receiving end here,
+ // so the file's rig goes in as the mapper's "target"
+ const mapping_type: TargetBoneMappingType = BoneAutoMapper.detect_mapping_type(
+ target_bones.map(bone => bone.name),
+ source_bones.map(bone => bone.name)
+ )
+ const bone_mapping: Map<string, string> = BoneAutoMapper.map_bones(target_bones, source_bones, mapping_type)
+
+ const { mesh2motion_config, other_rig_config } = HumanChainConfig.build_mapped_chain_configs(bone_mapping)
+ ImportedAnimationRetargeter.validate_required_chains(mesh2motion_config)
+
+ source_scene.updateMatrixWorld(true)
+ const source_skeleton = new Skeleton(source_bones)
+
+ return new ImportedAnimationRetargeter(
+ source_skeleton, other_rig_config, target_skinned_mesh, mesh2motion_config, mapping_type)
+ }
+
+ /**
+ * Bake one clip from the imported rig onto the Mesh2Motion skeleton
+ * @param clip - clip authored on the imported rig
+ * @param clip_name - name for the baked clip
+ * @returns new clip with tracks named after the Mesh2Motion bones. Positions are already
+ * in the final skeleton's space, so skeleton scale must not be applied again
+ */
+ public retarget (clip: AnimationClip, clip_name: string): AnimationClip {
+ // a previous clip leaves the source bones mid-animation. Bones the next clip never
+ // touches would keep that pose, and the rig has to be built from rest anyway
+ this.source_skeleton.bones.forEach((bone, index) => {
+ bone.position.copy(this.source_rest_transforms[index].position)
+ bone.quaternion.copy(this.source_rest_transforms[index].quaternion)
+ bone.scale.copy(this.source_rest_transforms[index].scale)
+ })
+ this.source_skeleton.bones[0].parent?.updateMatrixWorld(true)
+
+ const source_rig: Rig = new Rig(this.source_skeleton).fromConfig(this.source_config)
+
+ // baking poses the target skeleton, so work on a detached copy of ours
+ const target_skeleton: Skeleton = RetargetUtils.clone_skeleton(
+ this.target_skinned_mesh.skeleton, this.target_rest_transforms)
+ const target_rig: Rig = new Rig(target_skeleton).fromConfig(this.target_config)
+
+ return HumanClipRetargeter.retarget(clip, source_rig, target_rig, { clip_name })
+ }
+
+ private static validate_required_chains (mesh2motion_config: Record<string, string[]>): void {
+ const missing_bones: string[] = ImportedAnimationRetargeter.REQUIRED_CHAINS
+ .flatMap(chain_name => HumanChainConfig.mesh2motion_config[chain_name]
+ .filter((_bone_name, index) => mesh2motion_config[chain_name][index] === ''))
+
+ if (missing_bones.length > 0) {
+ throw new IncompatibleSkeletonError(
+ 'We couldn\'t match this animation\'s skeleton to the Mesh2Motion human rig.\n' +
+ 'Mesh2Motion and Mixamo rigs are supported. Other humanoid rigs work when their bone names are recognizable.\n\n' +
+ 'No match found for: ' + missing_bones.join(', '))
+ }
+ }
+}
diff --git a/src/lib/processes/animations-listing/StepAnimationsListing.ts b/src/lib/processes/animations-listing/StepAnimationsListing.ts
index 87a9d53..dca92b5 100644
--- a/src/lib/processes/animations-listing/StepAnimationsListing.ts
+++ b/src/lib/processes/animations-listing/StepAnimationsListing.ts
@@ -85,7 +85,8 @@ export class StepAnimationsListing extends EventTarget {
this.custom_animation_importer.set_import_context_provider(() => {
return {
skinned_meshes_to_animate: this.skinned_meshes_to_animate,
- skeleton_scale: this.skeleton_scale
+ skeleton_scale: this.skeleton_scale,
+ skeleton_type: this.skeleton_type
}
})
@@ -300,6 +301,10 @@ export class StepAnimationsListing extends EventTarget {
if (this.ui.dom_animation_count != null) {
this.ui.dom_animation_count.innerHTML = this.animation_search?.get_selected_export_animation_count().toString() ?? '0'
}
+
+ // the clip list's click handler runs before the checkbox change is recorded,
+ // so the button has to be refreshed here once the selection is up to date
+ this.update_download_button_enabled()
})
// add event listener to listen for filtered animations listing
diff --git a/src/retarget/AnimationRetargetService.ts b/src/retarget/AnimationRetargetService.ts
index 20a6550..5e4ae5b 100644
--- a/src/retarget/AnimationRetargetService.ts
+++ b/src/retarget/AnimationRetargetService.ts
@@ -4,9 +4,9 @@ import {
type Skeleton
} from 'three'
import { RetargetUtils, type TrackNameParts, type BoneRestTransform } from './RetargetUtils.ts'
-import { TargetBoneMappingType } from './steps/StepBoneMapping.ts'
+import { TargetBoneMappingType } from './bone-automap/TargetBoneMappingType.ts'
import { SkeletonType } from '../lib/enums/SkeletonType.ts'
-import { Retargeter } from './human-retargeting/Retargeter.ts'
+import { HumanClipRetargeter } from './human-retargeting/HumanClipRetargeter.ts'
import { Rig } from './human-retargeting/Rig.ts'
import { HumanChainConfig } from './human-retargeting/HumanChainConfig.ts'
import { RetargetDiagnostics, type RestPoseSnapshot } from './RetargetDiagnostics.ts'
@@ -242,11 +242,11 @@ export class AnimationRetargetService {
// so a Mixamo rig exported without the prefix resolved to no joints at all and
// came out as an empty rig. The bone mapping already encodes the same chains
// using the target's real bone names, so there is nothing to shortcut.
- const custom_source_config = HumanChainConfig.build_custom_source_config(this.get_bone_mappings())
- const custom_target_config = HumanChainConfig.build_custom_target_config(custom_source_config, this.get_bone_mappings())
+ // the source here is always the Mesh2Motion rig, the target is the uploaded rig
+ const { mesh2motion_config, other_rig_config } = HumanChainConfig.build_mapped_chain_configs(this.get_bone_mappings())
- source_rig.fromConfig(custom_source_config)
- target_rig.fromConfig(custom_target_config)
+ source_rig.fromConfig(mesh2motion_config)
+ target_rig.fromConfig(other_rig_config)
// instrumentation. Runs before the retargeter drives anything, so the rigs are still
// holding the rest pose they captured. See RetargetDiagnostics for why each check exists
@@ -256,35 +256,16 @@ export class AnimationRetargetService {
RetargetDiagnostics.report_pose_fidelity('SOURCE', source_rest_snapshot, source_rig)
RetargetDiagnostics.report_source_consistency(source_rig, source_skeleton)
- const retargeter: Retargeter = new Retargeter(source_rig, target_rig, source_clip)
-
- // apply any global rig correction the user has set (fixes tilted rigs that
- // have no root bone, only a pelvis bone at the top of the hierarchy)
- retargeter.set_root_correction_x(this.root_correction_x_degrees)
-
- // TODO: experiment with the additives later with T-pose correction
- // retargeter.additives.push(
- // (Ref.addAxis = new AxisAdditive( 'armL', 'y', 0 * Math.PI / 180 )),
- // (Ref.addTwist = new ChainTwistAdditive( 'armR', 0 * Math.PI / 180 )),
- // );
-
- // Initialize the retargeter with a small delta
- retargeter.update(0.001)
-
- // Bake the retargeted animation into keyframe tracks
- // 30 fps for input animations is usually sufficient for now
- const retargeted_tracks: Array<QuaternionKeyframeTrack | VectorKeyframeTrack> = retargeter.bake_animation_to_tracks(30)
+ const retargeted_clip: AnimationClip = HumanClipRetargeter.retarget(source_clip, source_rig, target_rig, {
+ clip_name: `${source_clip.name} RT`, // RT means retargeted
+ // apply any global rig correction the user has set
+ root_correction_x_degrees: this.root_correction_x_degrees
+ })
// the decisive check: any UNMAPPED bone that moves off its rest pose on frame 0 is
// carrying a corrupted rest pose out of the cloned skeleton
- RetargetDiagnostics.report_baked_frame_zero(retargeted_tracks, target_rest_snapshot, target_rig)
-
- // Create and return the new retargeted animation clip
- const retargeted_clip = new AnimationClip(
- `${source_clip.name} RT`, // RT means retargeted
- source_clip.duration,
- retargeted_tracks
- )
+ RetargetDiagnostics.report_baked_frame_zero(
+ retargeted_clip.tracks as Array<QuaternionKeyframeTrack | VectorKeyframeTrack>, target_rest_snapshot, target_rig)
console.log(`Swing-Twist retargeting complete: ${source_clip.name} -> ${retargeted_clip.name}`)
console.log('getting source clip before bone correction:', source_clip.tracks)
diff --git a/src/retarget/RetargetUtils.test.ts b/src/retarget/RetargetUtils.test.ts
new file mode 100644
index 0000000..75c71ba
--- /dev/null
+++ b/src/retarget/RetargetUtils.test.ts
@@ -0,0 +1,86 @@
+import { describe, it, expect } from 'vitest'
+import { Bone, BufferGeometry, Group, MeshBasicMaterial, Quaternion, Skeleton, SkinnedMesh, Vector3 } from 'three'
+import { RetargetUtils } from './RetargetUtils.ts'
+import { HumanChainConfig } from './human-retargeting/HumanChainConfig.ts'
+
+// two bone chain bound under a scaled, offset parent, the way a loaded model usually sits
+function create_bound_chain (): { parent: Group, mesh: SkinnedMesh, root: Bone, child: Bone } {
+ const parent = new Group()
+ parent.position.set(1, 2, 3)
+ parent.scale.setScalar(0.5)
+
+ const root = new Bone()
+ root.position.set(0, 1, 0)
+ root.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 4)
+
+ const child = new Bone()
+ child.position.set(0, 0.5, 0)
+ child.quaternion.setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 6)
+ root.add(child)
+
+ const mesh = new SkinnedMesh(new BufferGeometry(), new MeshBasicMaterial())
+ mesh.add(root)
+ parent.add(mesh)
+ parent.updateMatrixWorld(true)
+ mesh.bind(new Skeleton([root, child]))
+
+ return { parent, mesh, root, child }
+}
+
+describe('RetargetUtils.capture_bind_pose_rest_transforms', () => {
+ it('recovers the rest pose after the bones have been animated', () => {
+ const { mesh, root, child } = create_bound_chain()
+ const expected = RetargetUtils.capture_bone_rest_transforms(mesh.skeleton)
+
+ // pose the skeleton like an animation would
+ root.position.set(0.3, 0.2, 0.1)
+ child.quaternion.setFromAxisAngle(new Vector3(0, 0, 1), 1.2)
+ mesh.updateMatrixWorld(true)
+
+ const recovered = RetargetUtils.capture_bind_pose_rest_transforms(mesh)
+
+ recovered.forEach((rest, index) => {
+ expect(rest.position.distanceTo(expected[index].position)).toBeLessThan(1e-5)
+ expect(rest.quaternion.angleTo(expected[index].quaternion)).toBeLessThan(1e-5)
+ expect(rest.scale.distanceTo(expected[index].scale)).toBeLessThan(1e-5)
+ })
+ })
+
+ it('still recovers bone locals when the model was moved after binding', () => {
+ const { parent, mesh } = create_bound_chain()
+ const expected = RetargetUtils.capture_bone_rest_transforms(mesh.skeleton)
+
+ parent.position.set(-4, 0, 7)
+ parent.quaternion.copy(new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), 2))
+ parent.updateMatrixWorld(true)
+
+ const recovered = RetargetUtils.capture_bind_pose_rest_transforms(mesh)
+
+ recovered.forEach((rest, index) => {
+ expect(rest.position.distanceTo(expected[index].position)).toBeLessThan(1e-5)
+ expect(rest.quaternion.angleTo(expected[index].quaternion)).toBeLessThan(1e-5)
+ })
+ })
+})
+
+describe('HumanChainConfig.build_mapped_chain_configs', () => {
+ it('builds both sides of a mapping and leaves unmapped bones empty', () => {
+ // other rig -> Mesh2Motion. head_leaf is mapped but head is not
+ const mapping = new Map<string, string>([
+ ['Hips', 'pelvis'],
+ ['HeadTop_End', 'head_leaf'],
+ ['Neck', 'neck_01']
+ ])
+
+ const { mesh2motion_config, other_rig_config } = HumanChainConfig.build_mapped_chain_configs(mapping)
+
+ expect(mesh2motion_config.pelvis).toEqual(['pelvis'])
+ expect(other_rig_config.pelvis).toEqual(['Hips'])
+
+ // 'head' must not count as mapped just because 'head_leaf' is
+ expect(mesh2motion_config.head).toEqual(['neck_01', ''])
+ expect(other_rig_config.head).toEqual(['Neck', ''])
+
+ expect(mesh2motion_config.armL).toEqual(['', '', ''])
+ })
+})
diff --git a/src/retarget/RetargetUtils.ts b/src/retarget/RetargetUtils.ts
index a310b4b..d0bcca2 100644
--- a/src/retarget/RetargetUtils.ts
+++ b/src/retarget/RetargetUtils.ts
@@ -108,6 +108,56 @@ export class RetargetUtils {
}))
}
+ /**
+ * Recover the rest pose of a skinned mesh's skeleton from its bind matrices, without
+ * touching the live bones. For skeletons that may already be mid-animation, where
+ * capture_bone_rest_transforms is too late.
+ *
+ * At rest, skinning is the identity, which pins each bone's world matrix to
+ * meshWorld * bindMatrix^-1 * boneInverse^-1 (attached bind mode). Root bones are then
+ * divided by whatever their non-bone parent currently is, so a mesh that was moved or
+ * scaled after binding still comes out right.
+ */
+ static capture_bind_pose_rest_transforms (skinned_mesh: SkinnedMesh): BoneRestTransform[] {
+ const skeleton: Skeleton = skinned_mesh.skeleton
+ skinned_mesh.updateWorldMatrix(true, false)
+
+ // bindMatrixInverse can't be used here: in attached mode three.js overwrites it with the
+ // mesh's current inverse world every frame, so invert bindMatrix itself
+ const bind_space_to_world = new Matrix4()
+ if (skinned_mesh.bindMode === 'attached') {
+ bind_space_to_world.copy(skinned_mesh.matrixWorld).multiply(skinned_mesh.bindMatrix.clone().invert())
+ }
+
+ const rest_world_matrices: Matrix4[] = skeleton.boneInverses.map((bone_inverse) =>
+ bind_space_to_world.clone().multiply(bone_inverse.clone().invert()))
+
+ const parent_inverse = new Matrix4()
+ const local = new Matrix4()
+
+ return skeleton.bones.map((bone, index) => {
+ const parent_index: number = bone.parent !== null ? skeleton.bones.indexOf(bone.parent as Bone) : -1
+ if (parent_index !== -1) {
+ parent_inverse.copy(rest_world_matrices[parent_index]).invert()
+ } else if (bone.parent !== null) {
+ bone.parent.updateWorldMatrix(true, false)
+ parent_inverse.copy(bone.parent.matrixWorld).invert()
+ } else {
+ parent_inverse.identity()
+ }
+
+ local.copy(parent_inverse).multiply(rest_world_matrices[index])
+
+ const rest_transform: BoneRestTransform = {
+ position: new Vector3(),
+ quaternion: new Quaternion(),
+ scale: new Vector3()
+ }
+ local.decompose(rest_transform.position, rest_transform.quaternion, rest_transform.scale)
+ return rest_transform
+ })
+ }
+
/**
* Validates that the retargetable model contains SkinnedMeshes with bones
* @returns true if valid SkinnedMeshes are found, false otherwise
diff --git a/src/retarget/bone-automap/BoneAutoMapper.ts b/src/retarget/bone-automap/BoneAutoMapper.ts
index 55aeb09..70d296e 100644
--- a/src/retarget/bone-automap/BoneAutoMapper.ts
+++ b/src/retarget/bone-automap/BoneAutoMapper.ts
@@ -1,61 +1,92 @@
-import { Bone, Group, Object3D, Scene, SkinnedMesh } from 'three'
+import { type Bone, type Object3D, type SkinnedMesh } from 'three'
import { BoneCategoryMapper } from './BoneCategoryMapper'
import { BoneChainResolver, type RawBoneRecord } from './BoneChainResolver'
import { CanonicalSlotMapper } from './CanonicalSlotMapper'
+import { Mesh2MotionMapper } from './Mesh2MotionMapper'
import { MixamoMapper } from './MixamoMapper'
import { RigifyMapper } from './RigifyMapper'
-import { TargetBoneMappingType } from '../steps/StepBoneMapping'
-import { AnimationRetargetService } from '../AnimationRetargetService'
+import { TargetBoneMappingType } from './TargetBoneMappingType'
// re-exported so existing imports from './BoneAutoMapper' keep working
export { BoneCategory, BoneSide, BoneSlot, type BoneMetadata } from './BoneTypes'
import { type BoneMetadata } from './BoneTypes'
/**
- * BoneAutoMapper - Handles automatic bone mapping between source and target skeletons
- * Source = Mesh2Motion skeleton (draggable bones)
- * Target = Uploaded mesh skeleton (drop zones)
+ * BoneAutoMapper - Handles automatic bone mapping between a Mesh2Motion skeleton and another rig
+ * Source = Mesh2Motion skeleton
+ * Target = the other rig (an uploaded mesh on the retarget page, or the rig an imported
+ * animation was authored on in the main app)
*
* Rigs that match a known template (Mixamo, Rigify) go through that template's
* exact table. Everything else goes through canonical slot resolution, which
* reduces both skeletons to (joint, side, position-in-chain) and matches on that -
* see BoneSlotVocabulary and BoneChainResolver.
+ *
+ * Holds no state, so it works the same whichever direction the animation flows.
*/
export class BoneAutoMapper {
/**
- * Attempts to automatically map source bones (Mesh2Motion) to target bones (uploaded mesh)
- * Reads both armatures and the detected rig type from AnimationRetargetService.
- * @returns Map of target bone name -> source bone name
+ * Work out which known template, if any, the target rig follows
+ * @param source_bone_names - Mesh2Motion bone names
+ * @param target_bone_names - other rig's bone names
*/
- public static auto_map_bones (): Map<string, string> {
- // Traverse source skeleton to build parent-child relationships
- const source_armature: Group | null = AnimationRetargetService.getInstance().get_source_armature()
- if (source_armature === null) {
- console.error('Source armature is null while extracting bone parent map.')
- return new Map<string, string>()
+ public static detect_mapping_type (source_bone_names: string[], target_bone_names: string[]): TargetBoneMappingType {
+ if (MixamoMapper.is_target_valid_skeleton(target_bone_names)) {
+ return TargetBoneMappingType.Mixamo
}
- // Create metadata for both source and target bones
- const retarget_service: AnimationRetargetService = AnimationRetargetService.getInstance()
- let source_bones_meta: BoneMetadata[] = []
- let target_bones_meta: BoneMetadata[] = []
-
- if (retarget_service.get_source_armature().children.length > 0) {
- source_bones_meta = BoneAutoMapper.create_all_bone_metadata(retarget_service.get_source_armature(), true)
+ if (RigifyMapper.is_target_valid_skeleton(target_bone_names)) {
+ return TargetBoneMappingType.Rigify
}
- if (retarget_service.get_target_armature().children.length > 0) {
- target_bones_meta = BoneAutoMapper.create_all_bone_metadata(retarget_service.get_target_armature(), false)
+ if (Mesh2MotionMapper.is_source_bones_same_as_target(source_bone_names, target_bone_names)) {
+ return TargetBoneMappingType.Mesh2Motion
}
- // if the target is a mixamo rig and our skeleton type is human, we can do a direct name mapping
- // without worrying about guessing
- if (retarget_service.get_target_mapping_type() === TargetBoneMappingType.Mixamo) {
+ return TargetBoneMappingType.Custom
+ }
+
+ /**
+ * Attempts to automatically map source bones (Mesh2Motion) to target bones (uploaded mesh)
+ * @param source_armature - Mesh2Motion armature. A plain Group of Bones, no skinned meshes
+ * @param target_armature - other rig. Bones are read off its first SkinnedMesh
+ * @param mapping_type - template detected for the target rig
+ * @returns Map of target bone name -> source bone name
+ */
+ public static auto_map_bones (
+ source_armature: Object3D, target_armature: Object3D, mapping_type: TargetBoneMappingType
+ ): Map<string, string> {
+ const source_bones: Bone[] = source_armature.children.length > 0
+ ? BoneAutoMapper.collect_armature_bones(source_armature)
+ : []
+
+ const target_bones: Bone[] = target_armature.children.length > 0
+ ? BoneAutoMapper.collect_skinned_mesh_bones(target_armature)
+ : []
+
+ return BoneAutoMapper.map_bones(source_bones, target_bones, mapping_type)
+ }
+
+ /**
+ * Map Mesh2Motion bones to another rig's bones
+ * @param source_bones - Mesh2Motion bones
+ * @param target_bones - other rig's bones
+ * @param mapping_type - template detected for the target rig
+ * @returns Map of target bone name -> source bone name
+ */
+ public static map_bones (
+ source_bones: Bone[], target_bones: Bone[], mapping_type: TargetBoneMappingType
+ ): Map<string, string> {
+ const source_bones_meta: BoneMetadata[] = BoneAutoMapper.create_bone_metadata(source_bones)
+ const target_bones_meta: BoneMetadata[] = BoneAutoMapper.create_bone_metadata(target_bones)
+
+ // known templates get a direct name mapping without worrying about guessing
+ if (mapping_type === TargetBoneMappingType.Mixamo) {
console.log('Target skeleton appears to be a Mixamo rig, performing direct name mapping...')
return MixamoMapper.map_mixamo_bones(source_bones_meta, target_bones_meta)
}
- if (retarget_service.get_target_mapping_type() === TargetBoneMappingType.Rigify) {
+ if (mapping_type === TargetBoneMappingType.Rigify) {
console.log('Target skeleton appears to be a Rigify rig, performing direct name mapping...')
return RigifyMapper.map_rigify_bones(source_bones_meta, target_bones_meta)
}
@@ -100,46 +131,45 @@ export class BoneAutoMapper {
}
/**
- * Build resolved metadata for every bone in an armature.
- * @param armature - the armature to read bones from
- * @param is_source_skeleton - source is a plain Group of Bones; target bones come
- * off a SkinnedMesh's skeleton
+ * the source M2M skeleton is a Group that contains a lot of bones...but no Skinned Meshes,
+ * so just traverse the tree and build the bone list directly
*/
- private static create_all_bone_metadata (armature: Group | Scene, is_source_skeleton: boolean): BoneMetadata[] {
+ private static collect_armature_bones (armature: Object3D): Bone[] {
const bones: Bone[] = []
+ armature.traverse((child: Object3D) => {
+ if (child.type === 'Bone') {
+ bones.push(child as Bone)
+ }
+ })
+ return bones
+ }
- // the source M2M skeleton is a Group that contains a lot of bones...but no Skinned Meshes,
- // so just traverse the tree and build the bone list directly
- if (is_source_skeleton) {
- armature.traverse((child: Object3D) => {
- if (child.type === 'Bone') {
- bones.push(child as Bone)
- }
- })
- } else {
- // if we find multiple skinned meshes, we will log a warning. Probably won't be an issue, but just putting
- // this in there for now
- let skinned_mesh_found: boolean = false
- let skinned_mesh: SkinnedMesh | null = null
- armature.traverse((child: Object3D) => {
- if (child.type === 'SkinnedMesh') {
- if (skinned_mesh_found) {
- console.log('create_all_bone_metadata(): Multiple SkinnedMesh objects found in armature. Only processing the first one.')
- return
- }
- skinned_mesh_found = true
- skinned_mesh = child as SkinnedMesh
+ /**
+ * target bones come off a SkinnedMesh's skeleton. If we find multiple skinned meshes,
+ * we will log a warning. Probably won't be an issue, but just putting this in there for now
+ */
+ private static collect_skinned_mesh_bones (armature: Object3D): Bone[] {
+ let skinned_mesh: SkinnedMesh | null = null
+ armature.traverse((child: Object3D) => {
+ if (child.type === 'SkinnedMesh') {
+ if (skinned_mesh !== null) {
+ console.log('collect_skinned_mesh_bones(): Multiple SkinnedMesh objects found in armature. Only processing the first one.')
+ return
}
- })
-
- if (skinned_mesh !== null) {
- bones.push(...(skinned_mesh as SkinnedMesh).skeleton.bones)
+ skinned_mesh = child as SkinnedMesh
}
- }
+ })
- // BoneChainResolver works on plain records, so it can be tested without a scene.
- // A bone's parent is often the armature node rather than another bone; the
- // resolver treats any parent outside the bone list as no parent.
+ return skinned_mesh !== null ? [...(skinned_mesh as SkinnedMesh).skeleton.bones] : []
+ }
+
+ /**
+ * Build resolved metadata for every bone.
+ * BoneChainResolver works on plain records, so it can be tested without a scene.
+ * A bone's parent is often the armature node rather than another bone; the
+ * resolver treats any parent outside the bone list as no parent.
+ */
+ private static create_bone_metadata (bones: Bone[]): BoneMetadata[] {
const bone_records: RawBoneRecord[] = bones.map(bone => ({
name: bone.name,
parent_name: bone.parent !== null ? bone.parent.name : null
diff --git a/src/retarget/bone-automap/TargetBoneMappingType.ts b/src/retarget/bone-automap/TargetBoneMappingType.ts
new file mode 100644
index 0000000..3945ff7
--- /dev/null
+++ b/src/retarget/bone-automap/TargetBoneMappingType.ts
@@ -0,0 +1,11 @@
+// when we are auto-mapping, keep track of what rig type we matched the other rig against.
+// Lives in its own file so the main app can use bone auto-mapping without pulling in the
+// retarget page's UI steps
+export enum TargetBoneMappingType {
+ Mixamo = 'mixamo',
+ Rigify = 'rigify',
+ Mesh2Motion = 'mesh2motion',
+ Custom = 'custom', // trying to figure out bone mappings with bone name analysis
+ None = 'none'
+ // TODO: Add more types later
+}
diff --git a/src/retarget/human-retargeting/HumanChainConfig.ts b/src/retarget/human-retargeting/HumanChainConfig.ts
index 79c3316..fa22c01 100644
--- a/src/retarget/human-retargeting/HumanChainConfig.ts
+++ b/src/retarget/human-retargeting/HumanChainConfig.ts
@@ -47,16 +47,34 @@ export class HumanChainConfig {
// then we can duplicate that source config to a target config. We can go through the bone
// mapping and swap out all the source bone names for the target bone names
+ /**
+ * Build the chain configs for both sides of a bone mapping. The mapping is direction
+ * neutral, so the caller decides which config drives the animation and which receives it:
+ * the retarget page plays Mesh2Motion animations onto the other rig, while importing
+ * animations in the main app goes the other way.
+ * @param bone_mapping - other rig bone name -> Mesh2Motion bone name
+ */
+ public static build_mapped_chain_configs (bone_mapping: Map<string, string>): {
+ mesh2motion_config: Record<string, string[]>
+ other_rig_config: Record<string, string[]>
+ } {
+ const mesh2motion_config = HumanChainConfig.build_custom_source_config(bone_mapping)
+ const other_rig_config = HumanChainConfig.build_custom_target_config(mesh2motion_config, bone_mapping)
+ return { mesh2motion_config, other_rig_config }
+ }
+
public static build_custom_source_config (bone_mapping: Map<string, string>): Record<string, string[]> {
// we will bring in the bones that are mapped
const base_source_config = structuredClone(HumanChainConfig.mesh2motion_config)
- const flat_source_bone_names: string = this.flat_bone_name_list(bone_mapping.values()) // values store the Mesh2Motion bones
+
+ // values store the Mesh2Motion bones. A Set keeps 'head' from matching 'head_leaf'
+ const mapped_source_bone_names = new Set<string>(bone_mapping.values())
for (const chain_name in base_source_config) {
const bone_names_in_chain = base_source_config[chain_name]
for (let i = 0; i < bone_names_in_chain.length; i++) {
const bone_name = bone_names_in_chain[i]
- if (!flat_source_bone_names.includes(bone_name)) {
+ if (!mapped_source_bone_names.has(bone_name)) {
// no mapping for this bone, so we will replace it with an empty string
bone_names_in_chain[i] = ''
}
@@ -68,21 +86,6 @@ export class HumanChainConfig {
return base_source_config
}
- /**
- * To speed up finding bones in the list of chains and list of bones, flatten everything for faster searching
- * @param bone_config
- * @returns string of all the bone names separated by commas
- */
- private static flat_bone_name_list (bones_list: MapIterator<string>): string {
- let easy_searchable_bone_names: string = ''
-
- // flatten all keys (source bone names)
- for (const key of bones_list) {
- easy_searchable_bone_names += key + ','
- }
- return easy_searchable_bone_names
- }
-
public static build_custom_target_config (source_config: Record<string, string[]>, bone_mapping: Map<string, string>): Record<string, string[]> {
// swap key/value so source (Mesh2Motion) bone names can resolve to target rig names
const reverse_bone_mapping = RetargetUtils.reverse_bone_mapping_one_to_one(bone_mapping)
diff --git a/src/retarget/human-retargeting/HumanClipRetargeter.ts b/src/retarget/human-retargeting/HumanClipRetargeter.ts
new file mode 100644
index 0000000..710f307
--- /dev/null
+++ b/src/retarget/human-retargeting/HumanClipRetargeter.ts
@@ -0,0 +1,61 @@
+import { AnimationClip, type QuaternionKeyframeTrack, type VectorKeyframeTrack } from 'three'
+import { Retargeter } from './Retargeter'
+import { type Rig } from './Rig'
+
+export interface HumanClipRetargetOptions {
+ // name for the baked clip. Defaults to the source clip name
+ clip_name?: string
+ // corrective X-axis rotation (degrees) applied to the whole target rig. See Retargeter.set_root_correction_x
+ root_correction_x_degrees?: number
+ // 30 fps for input animations is usually sufficient for now
+ fps?: number
+}
+
+/**
+ * Bakes a swing-twist retarget of one clip from a source rig onto a target rig.
+ *
+ * Has no idea which side is the Mesh2Motion rig. The retarget page drives other rigs
+ * with Mesh2Motion animations, and the main app's animation import drives the
+ * Mesh2Motion rig with animations authored on other rigs (Mixamo, etc). Both build
+ * their own rigs and hand them in here.
+ */
+export class HumanClipRetargeter {
+ /**
+ * @param source_clip - animation authored on the source rig
+ * @param source_rig - rig the clip's tracks bind to. Must be at rest when the Rig was built
+ * @param target_rig - rig to bake onto. Its skeleton gets posed while baking, so it
+ * should be a detached working copy, not a skeleton in the scene
+ * @returns a new clip with tracks named after the target rig's bones
+ */
+ public static retarget (
+ source_clip: AnimationClip,
+ source_rig: Rig,
+ target_rig: Rig,
+ options: HumanClipRetargetOptions = {}
+ ): AnimationClip {
+ const retargeter: Retargeter = new Retargeter(source_rig, target_rig, source_clip)
+
+ // apply any global rig correction (fixes tilted rigs that have no root bone,
+ // only a pelvis bone at the top of the hierarchy)
+ retargeter.set_root_correction_x(options.root_correction_x_degrees ?? 0)
+
+ // TODO: experiment with the additives later with T-pose correction
+ // retargeter.additives.push(
+ // (Ref.addAxis = new AxisAdditive( 'armL', 'y', 0 * Math.PI / 180 )),
+ // (Ref.addTwist = new ChainTwistAdditive( 'armR', 0 * Math.PI / 180 )),
+ // );
+
+ // Initialize the retargeter with a small delta
+ retargeter.update(0.001)
+
+ // Bake the retargeted animation into keyframe tracks
+ const retargeted_tracks: Array<QuaternionKeyframeTrack | VectorKeyframeTrack> =
+ retargeter.bake_animation_to_tracks(options.fps ?? 30)
+
+ return new AnimationClip(
+ options.clip_name ?? source_clip.name,
+ source_clip.duration,
+ retargeted_tracks
+ )
+ }
+}
diff --git a/src/retarget/steps/StepBoneMapping.ts b/src/retarget/steps/StepBoneMapping.ts
index d952583..2dfc3e3 100644
--- a/src/retarget/steps/StepBoneMapping.ts
+++ b/src/retarget/steps/StepBoneMapping.ts
@@ -1,19 +1,10 @@
import { type Scene, type SkinnedMesh } from 'three'
import { BoneAutoMapper } from '../bone-automap/BoneAutoMapper.ts'
-import { MixamoMapper } from '../bone-automap/MixamoMapper.ts'
-import { RigifyMapper } from '../bone-automap/RigifyMapper.ts'
import { AnimationRetargetService } from '../AnimationRetargetService.ts'
-import { Mesh2MotionMapper } from '../bone-automap/Mesh2MotionMapper.ts'
-
-// when we are auto-mapping, keep track of what rig type we matched target against
-export enum TargetBoneMappingType {
- Mixamo = 'mixamo',
- Rigify = 'rigify',
- Mesh2Motion = 'mesh2motion',
- Custom = 'custom', // trying to figure out bone mappings with bone name analysis
- None = 'none'
- // TODO: Add more types later
-}
+import { TargetBoneMappingType } from '../bone-automap/TargetBoneMappingType.ts'
+
+// re-exported so existing imports from './StepBoneMapping' keep working
+export { TargetBoneMappingType }
export class StepBoneMapping extends EventTarget {
// DOM references
@@ -428,22 +419,17 @@ export class StepBoneMapping extends EventTarget {
const retarget_service: AnimationRetargetService = AnimationRetargetService.getInstance()
// see if target bones follow a known template
- const target_bone_names = this.get_target_bone_names()
- if (MixamoMapper.is_target_valid_skeleton(target_bone_names)) {
- retarget_service.set_target_mapping_type(TargetBoneMappingType.Mixamo)
- } else if (RigifyMapper.is_target_valid_skeleton(target_bone_names)) {
- retarget_service.set_target_mapping_type(TargetBoneMappingType.Rigify)
- } else if (Mesh2MotionMapper.is_source_bones_same_as_target(
+ retarget_service.set_target_mapping_type(BoneAutoMapper.detect_mapping_type(
this.get_source_bone_names(),
this.get_target_bone_names()
- )) {
- retarget_service.set_target_mapping_type(TargetBoneMappingType.Mesh2Motion)
- } else {
- retarget_service.set_target_mapping_type(TargetBoneMappingType.Custom)
- }
+ ))
// Use BoneAutoMapper to generate mappings
- const auto_mappings = BoneAutoMapper.auto_map_bones()
+ const auto_mappings = BoneAutoMapper.auto_map_bones(
+ retarget_service.get_source_armature(),
+ retarget_service.get_target_armature(),
+ retarget_service.get_target_mapping_type()
+ )
// Apply the auto-generated mappings
retarget_service.set_bone_mappings(auto_mappings)