Import a 3D Model and automatically assign and export animations
TypeScript
Start trying to add a very simple auto-bone mapping logic to help with the process
Scott Petrovic9b4f9ebd2f33
diff --git a/src/retarget/BoneAutoMapper.ts b/src/retarget/BoneAutoMapper.tsnew file mode 100644index 0000000..ff03a2e--- /dev/null+++ b/src/retarget/BoneAutoMapper.ts@@ -0,0 +1,132 @@+/**+ * BoneAutoMapper - Handles automatic bone mapping between source and target skeletons+ * Uses string comparison and pattern matching to suggest bone mappings+ */+export class BoneAutoMapper {+ /**+ * Attempts to automatically map source bones to target bones+ * @param source_bone_names - Array of bone names from the source skeleton+ * @param target_bone_names - Array of bone names from the target skeleton+ * @returns Map of target bone name -> source bone name+ */+ public static auto_map_bones (source_bone_names: string[], target_bone_names: string[]): Map<string, string> {+ const mappings = new Map<string, string>()++ for (const target_bone of target_bone_names) {+ const best_match = this.find_best_match(target_bone, source_bone_names)+ if (best_match !== null) {+ mappings.set(target_bone, best_match)+ }+ }++ return mappings+ }++ /**+ * Find the best matching source bone for a given target bone+ * @param target_bone - Target bone name to match+ * @param source_bones - Array of source bone names to search+ * @returns Best matching source bone name, or null if no good match found+ */+ private static find_best_match (target_bone: string, source_bones: string[]): string | null {+ const normalized_target = this.normalize_bone_name(target_bone)+ let best_match: string | null = null+ let best_score = 0++ for (const source_bone of source_bones) {+ const normalized_source = this.normalize_bone_name(source_bone)+ const score = this.calculate_similarity(normalized_target, normalized_source)++ // Require a minimum threshold for matching+ if (score > best_score && score >= 0.6) {+ best_score = score+ best_match = source_bone+ }+ }++ return best_match+ }++ /**+ * Normalize bone names for comparison by:+ * - Converting to lowercase+ * - Removing common prefixes/suffixes+ * - Standardizing separators+ */+ private static normalize_bone_name (bone_name: string): string {+ let normalized = bone_name.toLowerCase()++ // Replace various separators with underscores+ normalized = normalized.replace(/[-.\s]/g, '_')++ // Remove common prefixes+ normalized = normalized.replace(/^(mixamorig|mixamorig_|rig_|bone_|jnt_|joint_)/i, '')++ // Standardize left/right notation+ normalized = normalized.replace(/\bleft\b/g, 'l')+ normalized = normalized.replace(/\bright\b/g, 'r')+ normalized = normalized.replace(/^l_/g, 'left_')+ normalized = normalized.replace(/^r_/g, 'right_')+ normalized = normalized.replace(/_l$/g, '_left')+ normalized = normalized.replace(/_r$/g, '_right')++ return normalized+ }++ /**+ * Calculate similarity score between two normalized bone names+ * Uses a combination of exact match, contains, and Levenshtein distance+ */+ private static calculate_similarity (name1: string, name2: string): number {+ // Exact match+ if (name1 === name2) {+ return 1.0+ }++ // One contains the other+ if (name1.includes(name2) || name2.includes(name1)) {+ const longer = Math.max(name1.length, name2.length)+ const shorter = Math.min(name1.length, name2.length)+ return 0.8 + (shorter / longer) * 0.2+ }++ // Use Levenshtein distance for fuzzy matching+ const distance = this.levenshtein_distance(name1, name2)+ const max_length = Math.max(name1.length, name2.length)+ const similarity = 1 - (distance / max_length)++ return similarity+ }++ /**+ * Calculate Levenshtein distance between two strings+ * (minimum number of single-character edits required to change one string into another)+ */+ private static levenshtein_distance (str1: string, str2: string): number {+ const len1 = str1.length+ const len2 = str2.length+ const matrix: number[][] = []++ // Initialize matrix+ for (let i = 0; i <= len1; i++) {+ matrix[i] = [i]+ }+ for (let j = 0; j <= len2; j++) {+ matrix[0][j] = j+ }++ // Fill matrix+ for (let i = 1; i <= len1; i++) {+ for (let j = 1; j <= len2; j++) {+ const cost = str1[i - 1] === str2[j - 1] ? 0 : 1+ matrix[i][j] = Math.min(+ matrix[i - 1][j] + 1, // deletion+ matrix[i][j - 1] + 1, // insertion+ matrix[i - 1][j - 1] + cost // substitution+ )+ }+ }++ return matrix[len1][len2]+ }+}diff --git a/src/retarget/StepBoneMapping.ts b/src/retarget/StepBoneMapping.tsindex 90a1372..f8c81e6 100644--- a/src/retarget/StepBoneMapping.ts+++ b/src/retarget/StepBoneMapping.ts@@ -1,5 +1,6 @@import { type Group, type Object3D, type Object3DEventMap, type Scene, type SkinnedMesh } from 'three'import { SkeletonType } from '../lib/enums/SkeletonType.ts'+import { BoneAutoMapper } from './BoneAutoMapper.ts'export class StepBoneMapping extends EventTarget {private readonly _main_scene: Scene@@ -11,6 +12,7 @@ export class StepBoneMapping extends EventTarget {private source_bones_list: HTMLDivElement | null = nullprivate target_bones_list: HTMLDivElement | null = nullprivate clear_mappings_button: HTMLButtonElement | null = null+ private auto_map_button: HTMLButtonElement | null = null// Bone mapping: target bone name -> source bone nameprivate bone_mapping: Map<string, string> = new Map()@@ -28,6 +30,7 @@ export class StepBoneMapping extends EventTarget {this.source_bones_list = document.getElementById('source-bones-list') as HTMLDivElementthis.target_bones_list = document.getElementById('target-bones-list') as HTMLDivElementthis.clear_mappings_button = document.getElementById('clear-mappings-button') as HTMLButtonElement+ this.auto_map_button = document.getElementById('auto-map-button') as HTMLButtonElement// Add event listener for clear mappings buttonthis.clear_mappings_button?.addEventListener('click', () => {@@ -35,15 +38,22 @@ export class StepBoneMapping extends EventTarget {console.log('All bone mappings cleared')})+ // Add event listener for auto-map button+ this.auto_map_button?.addEventListener('click', () => {+ this.auto_map_bones()+ })+// Populate the liststhis.update_bone_lists()this.update_clear_button_visibility()+ this.update_auto_map_button_visibility()}public set_source_skeleton_data (skeleton_data: Group<Object3DEventMap>): void {this.source_skeleton_data = skeleton_dataconsole.log('Source skeleton data set in bone mapping:', this.source_skeleton_data)this.update_source_bones_list()+ this.update_auto_map_button_visibility()}public set_target_skeleton_data (armature: Object3D, skeleton_type: SkeletonType): void {@@ -51,6 +61,7 @@ export class StepBoneMapping extends EventTarget {this.target_skeleton_type = skeleton_typeconsole.log('Target skeleton data set in bone mapping:', this.target_armature, 'Type:', this.target_skeleton_type)this.update_target_bones_list()+ this.update_auto_map_button_visibility()}public has_source_skeleton (): boolean {@@ -276,6 +287,13 @@ export class StepBoneMapping extends EventTarget {this.clear_mappings_button.style.display = this.has_bone_mappings() ? 'block' : 'none'}+ // Update visibility of auto-map button+ private 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)@@ -291,4 +309,32 @@ export class StepBoneMapping extends EventTarget {this.update_clear_button_visibility()this.dispatchEvent(new CustomEvent('bone-mappings-changed'))}++ // Auto-map bones using string matching+ public auto_map_bones (): void {+ // Clear existing mappings first+ this.bone_mapping.clear()++ // Check if we have both source and target skeletons+ if (!this.has_both_skeletons()) {+ console.warn('Cannot auto-map: both source and target skeletons are required')+ return+ }++ const source_bone_names = this.get_source_bone_names()+ const target_bone_names = this.get_target_bone_names()++ // Use BoneAutoMapper to generate mappings+ const auto_mappings = BoneAutoMapper.auto_map_bones(source_bone_names, target_bone_names)++ // Apply the auto-generated mappings+ this.bone_mapping = auto_mappings++ console.log(`Auto-mapped ${auto_mappings.size} bones:`, auto_mappings)++ // Update UI+ this.update_target_bones_list()+ this.update_clear_button_visibility()+ this.dispatchEvent(new CustomEvent('bone-mappings-changed'))+ }}diff --git a/src/retarget/index.html b/src/retarget/index.htmlindex 377da62..5851a74 100644--- a/src/retarget/index.html+++ b/src/retarget/index.html@@ -79,7 +79,10 @@</div></div>- <button id="clear-mappings-button" class="button" style="margin-top: 1rem; display: none;">Clear All Mappings</button>+ <div style="display: flex; gap: 0.5rem; margin-top: 1rem;">+ <button id="auto-map-button" class="button" style="display: none;">Auto-Map Bones</button>+ <button id="clear-mappings-button" class="button" style="display: none;">Clear All Mappings</button>+ </div></div><!-- 3d view controls shown on bottom right. This helps with click events -->