Import a 3D Model and automatically assign and export animations
TypeScript
move bone mapping source of truth to retargeting service
Scott Petrovic419b931dd637
diff --git a/src/retarget/AnimationRetargetService.ts b/src/retarget/AnimationRetargetService.tsindex fc65c96..23f86d6 100644--- a/src/retarget/AnimationRetargetService.ts+++ b/src/retarget/AnimationRetargetService.ts@@ -26,8 +26,18 @@ export class AnimationRetargetService {private source_armature: Group = new Group()private skeleton_type: SkeletonType = SkeletonType.Noneprivate target_armature: Scene = new Scene()+private target_skinned_meshes: SkinnedMesh[] = []private target_mapping_type: TargetBoneMappingType = TargetBoneMappingType.None+ private bone_mappings: Map<string, string> = new Map<string, string>()++ public set_bone_mappings (mappings: Map<string, string>): void {+ this.bone_mappings = mappings+ }++ public get_bone_mappings (): Map<string, string> {+ return this.bone_mappings+ }public set_source_armature (armature: Group): void {this.source_armature = armature@@ -77,6 +87,8 @@ export class AnimationRetargetService {private constructor () {}+ // #region PUBLIC METHODS+public static getInstance (): AnimationRetargetService {if (AnimationRetargetService.instance === null) {AnimationRetargetService.instance = new AnimationRetargetService()@@ -90,10 +102,7 @@ export class AnimationRetargetService {* @param bone_mappings - Map of target bone name -> source bone name* @returns A new animation clip retargeted for the target skeleton*/- public retarget_animation_clip (- source_clip: AnimationClip,- bone_mappings: Map<string, string>- ): AnimationClip {+ public retarget_animation_clip (source_clip: AnimationClip): AnimationClip {const new_tracks: any[] = [] // store new retargeted tracks// Process each track in the source animation@@ -106,7 +115,7 @@ export class AnimationRetargetService {}// Check if this bone is mapped to any target bones- const target_bone_names = this.reverse_bone_mapping(bone_mappings).get(track_parts.bone_name)+ const target_bone_names = this.reverse_bone_mapping(this.bone_mappings).get(track_parts.bone_name)if (target_bone_names === undefined || target_bone_names.length === 0) {return // Skip unmapped bones}@@ -134,8 +143,7 @@ export class AnimationRetargetService {// Apply Mixamo-specific corrections if neededif (this.target_mapping_type === TargetBoneMappingType.Mixamo) {this.apply_bone_rotation_correction(- retargeted_clip,- bone_mappings+ retargeted_clip)}@@ -143,6 +151,10 @@ export class AnimationRetargetService {return retargeted_clip}+ // #endregion++ // #region PRIVATE METHODS+/*** Create a reverse mapping: source bone name -> array of target bone names*/@@ -164,10 +176,9 @@ export class AnimationRetargetService {* Apply bone rotation correction for fixing bone roll delta between target and source skeleton*/private apply_bone_rotation_correction (- animation_clip: AnimationClip,- bone_mappings: Map<string, string>+ animation_clip: AnimationClip): void {- bone_mappings.forEach((source_bone_name, target_bone_name) => {+ this.bone_mappings.forEach((source_bone_name, target_bone_name) => {const delta = this.calculate_bone_rotation_delta(source_bone_name,target_bone_name@@ -328,4 +339,5 @@ export class AnimationRetargetService {return null}+ // #endregion}diff --git a/src/retarget/RetargetAnimationListing.ts b/src/retarget/RetargetAnimationListing.tsindex f937727..92334fc 100644--- a/src/retarget/RetargetAnimationListing.ts+++ b/src/retarget/RetargetAnimationListing.ts@@ -5,7 +5,6 @@ import { type AnimationClip, AnimationMixer, type SkinnedMesh, Object3D, type Animport type { ThemeManager } from '../lib/ThemeManager.ts'import { type TransformedAnimationClipPair } from '../lib/processes/animations-listing/interfaces/TransformedAnimationClipPair.ts'import { AnimationRetargetService } from './AnimationRetargetService.ts'-import { type StepBoneMapping } from './steps/StepBoneMapping.ts'import { StepExportRetargetedAnimations } from './steps/StepExportRetargetedAnimations.ts'/**@@ -16,7 +15,6 @@ export class RetargetAnimationListing extends EventTarget {private readonly theme_manager: ThemeManagerprivate readonly animation_player: AnimationPlayerprivate readonly animation_loader: AnimationLoader = new AnimationLoader()- private readonly step_bone_mapping: StepBoneMappingprivate readonly step_export_retargeted_animations: StepExportRetargetedAnimations = new StepExportRetargetedAnimations()private animation_clips_loaded: TransformedAnimationClipPair[] = []private animation_mixer: AnimationMixer = new AnimationMixer(new Object3D())@@ -29,11 +27,10 @@ export class RetargetAnimationListing extends EventTarget {private export_button: HTMLButtonElement | null = null- constructor (theme_manager: ThemeManager, step_bone_mapping: StepBoneMapping) {+ constructor (theme_manager: ThemeManager) {super()this.theme_manager = theme_managerthis.animation_player = new AnimationPlayer()- this.step_bone_mapping = step_bone_mapping}public begin (): void {@@ -177,18 +174,9 @@ export class RetargetAnimationListing extends EventTarget {// Stop all current actionsthis.animation_mixer.stopAllAction()- // Get bone mappings from the bone mapping step- const bone_mappings = this.step_bone_mapping.get_bone_mapping()-- if (bone_mappings.size === 0) {- console.warn('No bone mappings available. Cannot play retargeted animation.')- return- }-// Retarget the animation using the shared serviceconst retargeted_clip: AnimationClip = AnimationRetargetService.getInstance().retarget_animation_clip(- display_clip,- bone_mappings+ display_clip)// Create new actions for each skinned mesh with the retargeted animation@@ -221,9 +209,6 @@ export class RetargetAnimationListing extends EventTarget {)// configure the export out step with retargeting info- this.step_export_retargeted_animations.setup_retargeting(- this.step_bone_mapping.get_bone_mapping()- )this.step_export_retargeted_animations.export('retargeted_animations')})}diff --git a/src/retarget/RetargetAnimationPreview.ts b/src/retarget/RetargetAnimationPreview.tsindex 0653ca3..7f4e794 100644--- a/src/retarget/RetargetAnimationPreview.ts+++ b/src/retarget/RetargetAnimationPreview.ts@@ -10,7 +10,6 @@ import { AnimationRetargetService } from './AnimationRetargetService.ts'* loading and playing animations while applying bone mappings in real-time*/export class RetargetAnimationPreview extends EventTarget {- private readonly _main_scene: Sceneprivate readonly step_bone_mapping: StepBoneMappingprivate readonly gltf_loader: GLTFLoader = new GLTFLoader()@@ -21,9 +20,8 @@ export class RetargetAnimationPreview extends EventTarget {private is_preview_active: boolean = falseprivate has_added_event_listeners: boolean = false- constructor (main_scene: Scene, step_bone_mapping: StepBoneMapping) {+ constructor (step_bone_mapping: StepBoneMapping) {super()- this._main_scene = main_scenethis.step_bone_mapping = step_bone_mapping}@@ -62,26 +60,6 @@ export class RetargetAnimationPreview extends EventTarget {return}- // bone mappings might have chnaged- // const target_skeleton_data = this.step_bone_mapping.get_target_skeleton_data()- // if (target_skeleton_data === null) {- // console.log('Cannot start preview: target skeleton data is null')- // return- // }-- // // Extract skinned meshes from target skeleton data- // this.target_skinned_meshes = []- // target_skeleton_data.traverse((child) => {- // if (child.type === 'SkinnedMesh') {- // this.target_skinned_meshes.push(child as SkinnedMesh)- // }- // })-- // if (this.target_skinned_meshes.length === 0) {- // console.log('Cannot start preview: no skinned meshes found in target')- // return- // }-// Create animation mixer for the target skeleton// Use a dummy Object3D as root since we apply animations directly to skinned meshes// there are often more than one skinned mesh we want to animate at a time@@ -173,18 +151,9 @@ export class RetargetAnimationPreview extends EventTarget {// Stop any currently playing animationthis.animation_mixer.stopAllAction()- // Get current bone mappings- const bone_mappings = this.step_bone_mapping.get_bone_mapping()-- if (bone_mappings.size === 0) {- console.log('No bone mappings yet, skipping animation retarget')- return- }-// Create retargeted animation clip using shared servicethis.retargeted_animation_clip = AnimationRetargetService.getInstance().retarget_animation_clip(- this.current_animation_clip,- bone_mappings+ this.current_animation_clip)this.play_default_animation()diff --git a/src/retarget/retarget.ts b/src/retarget/retarget.tsindex c0e1c2a..5dc7587 100644--- a/src/retarget/retarget.ts+++ b/src/retarget/retarget.ts@@ -37,13 +37,10 @@ class RetargetModule {this.step_load_target_model = new StepLoadTargetModel(this.mesh2motion_engine)// Initialize bone mapping step- this.step_bone_mapping = new StepBoneMapping(this.mesh2motion_engine.get_scene())+ this.step_bone_mapping = new StepBoneMapping()// Initialize animation preview- this.retarget_animation_preview = new RetargetAnimationPreview(- this.mesh2motion_engine.get_scene(),- this.step_bone_mapping- )+ this.retarget_animation_preview = new RetargetAnimationPreview(this.step_bone_mapping)}public init (): void {diff --git a/src/retarget/steps/StepBoneMapping.ts b/src/retarget/steps/StepBoneMapping.tsindex ddb0d59..4e5e592 100644--- a/src/retarget/steps/StepBoneMapping.ts+++ b/src/retarget/steps/StepBoneMapping.ts@@ -13,8 +13,6 @@ export enum TargetBoneMappingType {}export class StepBoneMapping extends EventTarget {- private readonly _main_scene: Scene-// DOM referencesprivate source_bones_list: HTMLDivElement | null = nullprivate target_bones_list: HTMLDivElement | null = null@@ -24,16 +22,11 @@ export class StepBoneMapping extends EventTarget {private target_bone_count: HTMLSpanElement | null = null// Bone mapping: target bone name (uploaded mesh) -> source bone name (Mesh2Motion skeleton)- private bone_mapping = new Map<string, string>()+ // private bone_mapping = new Map<string, string>()// Track if event listeners have been addedprivate has_added_event_listeners: boolean = false- constructor (main_scene: Scene) {- super()- this._main_scene = main_scene // might not need this, but keeping for now- }-public begin (): void {// Get DOM referencesthis.source_bones_list = document.getElementById('source-bones-list') as HTMLDivElement@@ -81,11 +74,21 @@ export class StepBoneMapping extends EventTarget {}public has_source_skeleton (): boolean {- return AnimationRetargetService.getInstance().get_source_armature() !== null+ // if the source armature is an empty Group, we consider it as not having a skeleton+ if (AnimationRetargetService.getInstance().get_source_armature()?.children.length === 0) {+ return false+ }++ return true}public has_target_skeleton (): boolean {- return AnimationRetargetService.getInstance().get_target_armature() !== null+ // if the target armature has no children, we consider it as not having a skeleton+ if (AnimationRetargetService.getInstance().get_target_armature()?.children.length === 0) {+ return false+ }++ return true}public has_both_skeletons (): boolean {@@ -115,8 +118,10 @@ export class StepBoneMapping extends EventTarget {// Extract bone names from target skeleton (uploaded mesh)public get_target_bone_names (): string[] {- const target_armature = AnimationRetargetService.getInstance().get_target_armature()- if (target_armature === null) {+ const skinned_meshes: SkinnedMesh[] = AnimationRetargetService.getInstance().get_target_skinned_meshes()++ if (skinned_meshes.length === 0) {+ console.warn('get_target_bone_names(): No skinned meshes found in target armature.')return []}@@ -127,14 +132,10 @@ export class StepBoneMapping extends EventTarget {// Target skeleton data contains SkinnedMesh objects with skeleton property// Use Set to avoid duplicates when multiple SkinnedMesh share the same skeleton- target_armature.traverse((child) => {- if (child.type === 'SkinnedMesh') {- const skinned_mesh = child as SkinnedMesh- const skeleton = skinned_mesh.skeleton- skeleton.bones.forEach((bone) => {- bone_names_set.add(bone.name)- })- }+ skinned_meshes.forEach((skinned_mesh) => {+ skinned_mesh.skeleton.bones.forEach((bone) => {+ bone_names_set.add(bone.name)+ })})return Array.from(bone_names_set).sort()@@ -201,7 +202,8 @@ export class StepBoneMapping extends EventTarget {bone_item.dataset.targetBoneName = name// Check if this target bone has a mapping- const mapped_source_bone = this.bone_mapping.get(name)+ const bone_mappings: Map<string, string> = AnimationRetargetService.getInstance().get_bone_mappings()+ const mapped_source_bone = bone_mappings.get(name)if (mapped_source_bone !== undefined) {const source_name_span = document.createElement('span')source_name_span.textContent = mapped_source_bone@@ -280,7 +282,9 @@ export class StepBoneMapping extends EventTarget {if (source_bone_name !== '' && target_bone_name !== undefined) {// Update the mapping- this.bone_mapping.set(target_bone_name, source_bone_name)+ // this.bone_mapping.set(target_bone_name, source_bone_name)+ AnimationRetargetService.getInstance().get_bone_mappings().set(target_bone_name, source_bone_name)+console.log(`Mapped: ${target_bone_name} <- ${source_bone_name}`)// Update the UI to show the mapping@@ -301,14 +305,9 @@ export class StepBoneMapping extends EventTarget {}}- // Getter for the bone mapping- public get_bone_mapping (): Map<string, string> {- return new Map(this.bone_mapping)- }-// Check if there are any bone mappingspublic has_bone_mappings (): boolean {- return this.bone_mapping.size > 0+ return AnimationRetargetService.getInstance().get_bone_mappings().size > 0}// Update visibility of clear mappings button@@ -321,13 +320,14 @@ export class StepBoneMapping extends EventTarget {// Update visibility of auto-map buttonprivate update_auto_map_button_visibility (): void {if (this.auto_map_button === null) return-this.auto_map_button.style.display = this.has_both_skeletons() ? 'block' : 'none'}// Clear a specific mappingpublic clear_bone_mapping (target_bone_name: string): void {- this.bone_mapping.delete(target_bone_name)+ // this.bone_mapping.delete(target_bone_name)+ AnimationRetargetService.getInstance().get_bone_mappings().delete(target_bone_name)+this.update_target_bones_list()this.update_clear_button_visibility()this.dispatchEvent(new CustomEvent('bone-mappings-changed'))@@ -335,7 +335,9 @@ export class StepBoneMapping extends EventTarget {// Clear all mappingspublic clear_all_bone_mappings (): void {- this.bone_mapping.clear()+ // this.bone_mapping.clear()+ AnimationRetargetService.getInstance().set_bone_mappings(new Map<string, string>())+this.update_target_bones_list()this.update_clear_button_visibility()this.dispatchEvent(new CustomEvent('bone-mappings-changed'))@@ -343,8 +345,7 @@ export class StepBoneMapping extends EventTarget {// Auto-map bones using string matchingpublic auto_map_bones (): void {- // Clear existing mappings first- this.bone_mapping.clear()+ this.clear_all_bone_mappings() // Clear existing mappings first// Check if we have both source and target skeletonsif (!this.has_both_skeletons()) {@@ -352,22 +353,23 @@ export class StepBoneMapping extends EventTarget {return}+ const retarget_service: AnimationRetargetService = AnimationRetargetService.getInstance()+// see if target bones follow a known templateif (MixamoMapper.is_target_valid_skeleton(this.get_target_bone_names())) {- AnimationRetargetService.getInstance().set_target_mapping_type(TargetBoneMappingType.Mixamo)+ retarget_service.set_target_mapping_type(TargetBoneMappingType.Mixamo)} else {- AnimationRetargetService.getInstance().set_target_mapping_type(TargetBoneMappingType.Custom)+ retarget_service.set_target_mapping_type(TargetBoneMappingType.Custom)}// Use BoneAutoMapper to generate mappingsconst auto_mappings = BoneAutoMapper.auto_map_bones(- AnimationRetargetService.getInstance().get_target_armature(),- AnimationRetargetService.getInstance().get_target_mapping_type()+ retarget_service.get_target_armature(),+ retarget_service.get_target_mapping_type())// Apply the auto-generated mappings- this.bone_mapping = auto_mappings-+ retarget_service.set_bone_mappings(auto_mappings)console.log(`Auto-mapped ${auto_mappings.size} bones:`, auto_mappings)// Update UIdiff --git a/src/retarget/steps/StepExportRetargetedAnimations.ts b/src/retarget/steps/StepExportRetargetedAnimations.tsindex a717ef0..3f75877 100644--- a/src/retarget/steps/StepExportRetargetedAnimations.ts+++ b/src/retarget/steps/StepExportRetargetedAnimations.ts@@ -5,13 +5,6 @@ import { AnimationRetargetService } from '../AnimationRetargetService'export class StepExportRetargetedAnimations extends EventTarget {public animation_clips_to_export: AnimationClip[] = []- // Retargeting-related properties- private bone_mapping = new Map<string, string>()-- public setup_retargeting (bone_mapping: Map<string, string>): void {- this.bone_mapping = bone_mapping- }-public set_animation_clips_to_export (all_animations_clips: AnimationClip[], animation_checkboxes: number[]): void {this.animation_clips_to_export = []animation_checkboxes.forEach((indx) => {@@ -30,10 +23,7 @@ export class StepExportRetargetedAnimations extends EventTarget {// Retarget all animation clips before exportlet retargeted_clips: AnimationClip[] = []retargeted_clips = this.animation_clips_to_export.map((clip) =>- AnimationRetargetService.getInstance().retarget_animation_clip(- clip,- this.bone_mapping- )+ AnimationRetargetService.getInstance().retarget_animation_clip(clip))console.log('Retargeted animation clips:', retargeted_clips)