Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

First pass at getting the bone name matching working better with a tokenization process

Scott Petrovic59a8005977bd
diff --git a/src/retarget/bone-automap/BoneAutoMapper.ts b/src/retarget/bone-automap/BoneAutoMapper.ts
index 820d47a..55aeb09 100644
--- a/src/retarget/bone-automap/BoneAutoMapper.ts
+++ b/src/retarget/bone-automap/BoneAutoMapper.ts
@@ -1,61 +1,33 @@
import { Bone, Group, Object3D, Scene, SkinnedMesh } from 'three'
import { BoneCategoryMapper } from './BoneCategoryMapper'
+import { BoneChainResolver, type RawBoneRecord } from './BoneChainResolver'
+import { CanonicalSlotMapper } from './CanonicalSlotMapper'
import { MixamoMapper } from './MixamoMapper'
import { RigifyMapper } from './RigifyMapper'
import { TargetBoneMappingType } from '../steps/StepBoneMapping'
import { AnimationRetargetService } from '../AnimationRetargetService'
-/**
- * Bone categories for grouping bones by anatomical area
- */
-export enum BoneCategory {
- Torso = 'torso',
- Arms = 'arms',
- Hands = 'hands',
- Legs = 'legs',
- Wings = 'wings',
- Tail = 'tail',
- Unknown = 'unknown'
-}
-
-/**
- * Side of the body a bone belongs to
- */
-export enum BoneSide {
- Left = 'left',
- Right = 'right',
- Center = 'center',
- Unknown = 'unknown'
-}
-
-/**
- * Metadata extracted from a bone name
- */
-export interface BoneMetadata {
- name: string // Original bone name
- normalized_name: string // Normalized version for matching
- side: BoneSide // Which side of the body
- category: BoneCategory // Anatomical category
- parent_name: string | null // Name of parent bone, null if root
-}
+// 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)
- * Uses string comparison and pattern matching to suggest bone mappings
+ *
+ * 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.
*/
export class BoneAutoMapper {
/**
* Attempts to automatically map source bones (Mesh2Motion) to target bones (uploaded mesh)
- * @param source_armature - Source skeleton armature (Mesh2Motion skeleton)
- * @param target_armature - Target skeleton armature (uploaded mesh)
+ * Reads both armatures and the detected rig type from AnimationRetargetService.
* @returns Map of target bone name -> source bone name
*/
public static auto_map_bones (): Map<string, string> {
- // mappings: final output mapping of target bone name to source bone name
- let mappings = new 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) {
@@ -76,93 +48,67 @@ export class BoneAutoMapper {
target_bones_meta = BoneAutoMapper.create_all_bone_metadata(retarget_service.get_target_armature(), false)
}
- console.log('\n=== FINAL BONE METADATA ===')
- console.log('Source bones metadata:', source_bones_meta)
- console.log('Target bones metadata:', target_bones_meta)
-
// 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) {
console.log('Target skeleton appears to be a Mixamo rig, performing direct name mapping...')
- mappings = MixamoMapper.map_mixamo_bones(source_bones_meta, target_bones_meta)
- return mappings
+ return MixamoMapper.map_mixamo_bones(source_bones_meta, target_bones_meta)
}
if (retarget_service.get_target_mapping_type() === TargetBoneMappingType.Rigify) {
console.log('Target skeleton appears to be a Rigify rig, performing direct name mapping...')
- mappings = RigifyMapper.map_rigify_bones(source_bones_meta, target_bones_meta)
- return mappings
+ return RigifyMapper.map_rigify_bones(source_bones_meta, target_bones_meta)
}
- // Match bones within each category
- const categories: BoneCategory[] = [
- BoneCategory.Torso,
- BoneCategory.Arms,
- BoneCategory.Hands,
- BoneCategory.Legs,
- BoneCategory.Wings,
- BoneCategory.Tail,
- BoneCategory.Unknown
- ]
- for (const category of categories) {
- const source_bones_in_category: BoneMetadata[] = source_bones_meta.filter(b => b.category === category)
- const target_bones_in_category: BoneMetadata[] = target_bones_meta.filter(b => b.category === category)
-
- switch (category) {
- case BoneCategory.Torso: {
- const torso_mappings = BoneCategoryMapper.map_torso_bones(source_bones_in_category, target_bones_in_category)
- mappings = new Map([...mappings, ...torso_mappings])
- break
- }
- case BoneCategory.Arms: {
- const arm_mappings = BoneCategoryMapper.map_arm_bones(source_bones_in_category, target_bones_in_category)
- mappings = new Map([...mappings, ...arm_mappings])
- break
- }
- case BoneCategory.Hands: {
- const hand_mappings = BoneCategoryMapper.map_hand_bones(source_bones_in_category, target_bones_in_category)
- mappings = new Map([...mappings, ...hand_mappings])
- break
- }
- case BoneCategory.Legs: {
- const leg_mappings = BoneCategoryMapper.map_leg_bones(source_bones_in_category, target_bones_in_category)
- mappings = new Map([...mappings, ...leg_mappings])
- break
- }
- case BoneCategory.Wings: {
- const wing_mappings = BoneCategoryMapper.map_wing_bones(source_bones_in_category, target_bones_in_category)
- mappings = new Map([...mappings, ...wing_mappings])
- break
- }
- case BoneCategory.Tail: {
- const tail_mappings = BoneCategoryMapper.map_tail_bones(source_bones_in_category, target_bones_in_category)
- mappings = new Map([...mappings, ...tail_mappings])
- break
- }
- case BoneCategory.Unknown: {
- const unknown_mappings = BoneCategoryMapper.map_unknown_bones(source_bones_in_category, target_bones_in_category)
- mappings = new Map([...mappings, ...unknown_mappings])
- break
- }
- }
- }
+ return BoneAutoMapper.map_by_canonical_slots(source_bones_meta, target_bones_meta)
+ }
- console.log('\n=== Auto-mapped bones summary ===')
- console.log('Final mappings:', mappings)
+ /**
+ * Map an arbitrarily named rig in three passes.
+ *
+ * Exact names go first: if two rigs literally agree on a bone name, nothing the
+ * vocabulary infers should overrule that. Canonical slots handle the rest of the
+ * humanoid skeleton, and a final loose-name pass picks up anything anatomical the
+ * vocabulary has no word for - custom animal chains, accessory bones.
+ *
+ * Each pass carries the accumulated map forward, so a source bone claimed by one
+ * pass can never be handed out again by a later one.
+ *
+ * Kept separate from auto_map_bones so it can be unit tested without a three.js scene.
+ */
+ public static map_by_canonical_slots (
+ source_bones_meta: BoneMetadata[], target_bones_meta: BoneMetadata[]
+ ): Map<string, string> {
+ const exact_mappings = BoneCategoryMapper.match_exact_names(
+ source_bones_meta, target_bones_meta, new Map()
+ )
+
+ const slot_mappings = CanonicalSlotMapper.map_bones(
+ source_bones_meta, target_bones_meta, exact_mappings
+ )
+
+ const mappings = BoneCategoryMapper.match_loose_names(
+ source_bones_meta, target_bones_meta, slot_mappings
+ )
+
+ console.log(`Auto-mapped ${mappings.size} bones ` +
+ `(${exact_mappings.size} by exact name, ` +
+ `${slot_mappings.size - exact_mappings.size} by canonical slot, ` +
+ `${mappings.size - slot_mappings.size} by loose name)`)
return mappings
}
/**
- * Create metadata objects for all bones from a parent map
- * @param parent_map - Map of bone name -> parent bone name
- * @returns Array of BoneMetadata for all bones
+ * 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
*/
private static create_all_bone_metadata (armature: Group | Scene, is_source_skeleton: boolean): BoneMetadata[] {
- const metadata_list: BoneMetadata[] = []
const bones: Bone[] = []
- // the source M2M skeleton is a Group that contains a lot of bones...but no Skinned Meshes,
+ // 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) => {
@@ -191,102 +137,14 @@ export class BoneAutoMapper {
}
}
- // create metadata for each bone
- for (const bone of bones) {
- const bone_name: string = bone.name
- const parent_name: string | null = (bone.parent !== null) ? bone.parent.name : null
- const normalized_name: string = this.normalize_bone_name(bone_name)
- const side: BoneSide = this.detect_bone_side(bone_name)
- const category: BoneCategory = this.detect_bone_category(normalized_name)
- const metadata: BoneMetadata = {
- name: bone_name,
- normalized_name,
- side,
- category,
- parent_name
- }
- metadata_list.push(metadata)
- }
-
- return metadata_list
- }
-
- /**
- * Normalize bone names to simplify matching
- * - Lowercase
- * - Remove spaces and underscores
- * - Remove common prefixes and suffixes
- */
- private static normalize_bone_name (bone_name: string): string {
- let name = bone_name.toLowerCase()
-
- // Remove common prefixes
- name = name.replace(/^def-/g, '') // Blender DEF prefix
- name = name.replace(/^org-/g, '') // Rigify ORG prefix
- name = name.replace(/^mixamorig:?/g, '') // Mixamo prefix (with optional colon)
-
- // Remove spaces, underscores, dots, hyphens, colons
- name = name.replace(/[\s_.\-:]/g, '')
-
- // Remove L/R identifiers (we use side detection instead)
- name = name.replace(/l$/g, '')
- name = name.replace(/r$/g, '')
-
- // Remove trailing numbers (segment indices like ".001" or "01")
- name = name.replace(/\d+$/g, '')
-
- // Strip another trailing l/r in case digits sat between letter and number (e.g. "thumb01l")
- name = name.replace(/l$/g, '')
- name = name.replace(/r$/g, '')
-
- return name
- }
-
- /**
- * Detect which side of the body a bone belongs to
- * Based on common naming conventions (L/R, Left/Right)
- */
- private static detect_bone_side (bone_name: string): BoneSide {
- const lower_name = bone_name.toLowerCase()
-
- if (lower_name.includes('left') || lower_name.endsWith('l')) return BoneSide.Left
- if (lower_name.includes('right') || lower_name.endsWith('r')) return BoneSide.Right
-
- return BoneSide.Center
- }
-
- /**
- * Detect anatomical category based on normalized bone name and parent relationships
- */
- private static detect_bone_category (normalized_name: string): BoneCategory {
- if (normalized_name.includes('spine') || normalized_name.includes('chest') || normalized_name.includes('neck') ||
- normalized_name.includes('head') || normalized_name.includes('hips') || normalized_name.includes('pelvis')) {
- return BoneCategory.Torso
- }
-
- if (normalized_name.includes('shoulder') || normalized_name.includes('upperarm') ||
- normalized_name.includes('forearm') || normalized_name.includes('hand') || normalized_name.includes('wrist')) {
- return BoneCategory.Arms
- }
-
- if (normalized_name.includes('thumb') || normalized_name.includes('index') || normalized_name.includes('middle') ||
- normalized_name.includes('ring') || normalized_name.includes('pinky')) {
- return BoneCategory.Hands
- }
-
- if (normalized_name.includes('thigh') || normalized_name.includes('shin') || normalized_name.includes('knee') ||
- normalized_name.includes('foot') || normalized_name.includes('toe') || normalized_name.includes('calf')) {
- return BoneCategory.Legs
- }
-
- if (normalized_name.includes('wing') || normalized_name.includes('feather') || normalized_name.includes('pinion')) {
- return BoneCategory.Wings
- }
-
- if (normalized_name.includes('tail')) {
- return BoneCategory.Tail
- }
+ // 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.
+ const bone_records: RawBoneRecord[] = bones.map(bone => ({
+ name: bone.name,
+ parent_name: bone.parent !== null ? bone.parent.name : null
+ }))
- return BoneCategory.Unknown
+ return BoneChainResolver.build_metadata(bone_records)
}
}
diff --git a/src/retarget/bone-automap/BoneAutoMapping.test.ts b/src/retarget/bone-automap/BoneAutoMapping.test.ts
new file mode 100644
index 0000000..8781c61
--- /dev/null
+++ b/src/retarget/bone-automap/BoneAutoMapping.test.ts
@@ -0,0 +1,293 @@
+import { describe, it, expect } from 'vitest'
+import { BoneAutoMapper } from './BoneAutoMapper'
+import { BoneChainResolver, type RawBoneRecord } from './BoneChainResolver'
+import { MixamoMapper } from './MixamoMapper'
+import { RigifyMapper } from './RigifyMapper'
+import { type BoneMetadata, BoneSlot } from './BoneTypes'
+import {
+ bone_names, daz_rig, mesh2motion_rig, mixamo_rig, unreal_rig, vrm_rig
+} from './rig-fixtures'
+
+/** Run a target rig through the full canonical-slot pipeline against Mesh2Motion */
+function map_rig (target: RawBoneRecord[]): Map<string, string> {
+ return BoneAutoMapper.map_by_canonical_slots(
+ BoneChainResolver.build_metadata(mesh2motion_rig()),
+ BoneChainResolver.build_metadata(target)
+ )
+}
+
+function slot_of (metadata: BoneMetadata[], name: string): BoneSlot {
+ return (metadata.find(b => b.name === name) as BoneMetadata).slot
+}
+
+describe('BoneChainResolver', () => {
+ it('resolves the Mesh2Motion source rig to the expected slots', () => {
+ const meta = BoneChainResolver.build_metadata(mesh2motion_rig())
+
+ expect(slot_of(meta, 'pelvis')).toBe(BoneSlot.Pelvis)
+ expect(slot_of(meta, 'spine_02')).toBe(BoneSlot.Spine)
+ expect(slot_of(meta, 'neck_01')).toBe(BoneSlot.Neck)
+ expect(slot_of(meta, 'head_leaf')).toBe(BoneSlot.Head)
+ expect(slot_of(meta, 'clavicle_l')).toBe(BoneSlot.Clavicle)
+ expect(slot_of(meta, 'upperarm_l')).toBe(BoneSlot.UpperArm)
+ expect(slot_of(meta, 'lowerarm_l')).toBe(BoneSlot.LowerArm)
+ expect(slot_of(meta, 'ball_leaf_r')).toBe(BoneSlot.Ball)
+ expect(slot_of(meta, 'index_03_r')).toBe(BoneSlot.FingerIndex)
+ })
+
+ it('numbers chains from the hierarchy, not from the digits in the name', () => {
+ // Mixamo's Spine/Spine1/Spine2 must line up with spine_01/spine_02/spine_03
+ const mixamo = BoneChainResolver.build_metadata(mixamo_rig(''))
+ const ordinal_of = (name: string): number =>
+ (mixamo.find(b => b.name === name) as BoneMetadata).slot_ordinal
+
+ expect(ordinal_of('Spine')).toBe(1)
+ expect(ordinal_of('Spine1')).toBe(2)
+ expect(ordinal_of('Spine2')).toBe(3)
+ expect(ordinal_of('Head')).toBe(1)
+ expect(ordinal_of('HeadTop_End')).toBe(2)
+ })
+
+ it('settles shoulder ambiguity from the hierarchy, both ways round', () => {
+ // Mixamo: "LeftShoulder" is the clavicle, "LeftArm" is the upper arm
+ const mixamo = BoneChainResolver.build_metadata(mixamo_rig(''))
+ expect(slot_of(mixamo, 'LeftShoulder')).toBe(BoneSlot.Clavicle)
+ expect(slot_of(mixamo, 'LeftArm')).toBe(BoneSlot.UpperArm)
+ expect(slot_of(mixamo, 'LeftForeArm')).toBe(BoneSlot.LowerArm)
+
+ // DAZ: "lShldr" is the upper arm and "lCollar" is the clavicle
+ const daz = BoneChainResolver.build_metadata(daz_rig())
+ expect(slot_of(daz, 'lCollar')).toBe(BoneSlot.Clavicle)
+ expect(slot_of(daz, 'lShldr')).toBe(BoneSlot.UpperArm)
+ expect(slot_of(daz, 'lForeArm')).toBe(BoneSlot.LowerArm)
+ })
+
+ it('settles leg ambiguity: Mixamo LeftLeg is the calf', () => {
+ const mixamo = BoneChainResolver.build_metadata(mixamo_rig(''))
+ expect(slot_of(mixamo, 'LeftUpLeg')).toBe(BoneSlot.Thigh)
+ expect(slot_of(mixamo, 'LeftLeg')).toBe(BoneSlot.Calf)
+ expect(slot_of(mixamo, 'LeftToeBase')).toBe(BoneSlot.Ball)
+ })
+
+ it('rejects twist, IK and root bones instead of guessing at them', () => {
+ const unreal = BoneChainResolver.build_metadata(unreal_rig())
+
+ expect(slot_of(unreal, 'root')).toBe(BoneSlot.Unknown)
+ expect(slot_of(unreal, 'upperarm_twist_01_l')).toBe(BoneSlot.Unknown)
+ expect(slot_of(unreal, 'lowerarm_twist_01_r')).toBe(BoneSlot.Unknown)
+ expect(slot_of(unreal, 'calf_twist_01_l')).toBe(BoneSlot.Unknown)
+
+ // a twist bone sitting between the hand and the forearm must not absorb the
+ // forearm's slot during the arm walk
+ expect(slot_of(unreal, 'lowerarm_l')).toBe(BoneSlot.LowerArm)
+ expect(slot_of(unreal, 'upperarm_l')).toBe(BoneSlot.UpperArm)
+ })
+})
+
+describe('canonical slot mapping', () => {
+ it('maps a Mixamo rig whose "mixamorig" prefix was stripped', () => {
+ const mappings = map_rig(mixamo_rig(''))
+
+ expect(mappings.get('Hips')).toBe('pelvis')
+ expect(mappings.get('Spine')).toBe('spine_01')
+ expect(mappings.get('Spine2')).toBe('spine_03')
+ expect(mappings.get('Neck')).toBe('neck_01')
+ expect(mappings.get('Head')).toBe('head')
+ expect(mappings.get('HeadTop_End')).toBe('head_leaf')
+
+ expect(mappings.get('LeftShoulder')).toBe('clavicle_l')
+ expect(mappings.get('LeftArm')).toBe('upperarm_l')
+ expect(mappings.get('LeftForeArm')).toBe('lowerarm_l')
+ expect(mappings.get('LeftHand')).toBe('hand_l')
+ expect(mappings.get('RightForeArm')).toBe('lowerarm_r')
+
+ expect(mappings.get('LeftUpLeg')).toBe('thigh_l')
+ expect(mappings.get('LeftLeg')).toBe('calf_l')
+ expect(mappings.get('LeftFoot')).toBe('foot_l')
+ expect(mappings.get('LeftToeBase')).toBe('ball_l')
+ expect(mappings.get('LeftToe_End')).toBe('ball_leaf_l')
+
+ expect(mappings.get('LeftHandIndex1')).toBe('index_01_l')
+ expect(mappings.get('LeftHandIndex4')).toBe('index_04_leaf_l')
+ expect(mappings.get('RightHandPinky3')).toBe('pinky_03_r')
+
+ // every bone in the rig should map - it is the same skeleton, differently named
+ expect(mappings.size).toBe(mixamo_rig('').length)
+ })
+
+ it('never assigns one source bone to two targets', () => {
+ for (const rig of [mixamo_rig(''), unreal_rig(), daz_rig(), vrm_rig()]) {
+ const mappings = map_rig(rig)
+ expect(new Set(mappings.values()).size).toBe(mappings.size)
+ }
+ })
+
+ it('maps an Unreal mannequin and leaves its twist bones alone', () => {
+ const mappings = map_rig(unreal_rig())
+
+ expect(mappings.get('pelvis')).toBe('pelvis')
+ expect(mappings.get('clavicle_l')).toBe('clavicle_l')
+ expect(mappings.get('lowerarm_r')).toBe('lowerarm_r')
+ expect(mappings.get('ball_l')).toBe('ball_l')
+ expect(mappings.get('index_03_l')).toBe('index_03_l')
+
+ expect(mappings.has('root')).toBe(false)
+ expect(mappings.has('upperarm_twist_01_l')).toBe(false)
+ expect(mappings.has('thigh_twist_01_r')).toBe(false)
+ })
+
+ it('maps DAZ naming, including its inverted shoulder convention', () => {
+ const mappings = map_rig(daz_rig())
+
+ expect(mappings.get('hip')).toBe('pelvis')
+ expect(mappings.get('lCollar')).toBe('clavicle_l')
+ expect(mappings.get('lShldr')).toBe('upperarm_l')
+ expect(mappings.get('lForeArm')).toBe('lowerarm_l')
+ expect(mappings.get('lHand')).toBe('hand_l')
+ expect(mappings.get('rThigh')).toBe('thigh_r')
+ expect(mappings.get('rShin')).toBe('calf_r')
+ expect(mappings.get('rToe')).toBe('ball_r')
+ expect(mappings.get('lMid2')).toBe('middle_02_l')
+
+ // a 2-bone torso is spread across the 3-bone source spine rather than dropped
+ expect(mappings.get('abdomen')).toBe('spine_01')
+ expect(mappings.get('chest')).toBe('spine_03')
+ })
+
+ it('maps VRM naming, including proximal/intermediate/distal fingers', () => {
+ const mappings = map_rig(vrm_rig())
+
+ expect(mappings.get('hips')).toBe('pelvis')
+ expect(mappings.get('upperChest')).toBe('spine_03')
+ expect(mappings.get('leftShoulder')).toBe('clavicle_l')
+ expect(mappings.get('leftUpperArm')).toBe('upperarm_l')
+ expect(mappings.get('leftLowerArm')).toBe('lowerarm_l')
+ expect(mappings.get('rightUpperLeg')).toBe('thigh_r')
+ expect(mappings.get('rightLowerLeg')).toBe('calf_r')
+ expect(mappings.get('leftToes')).toBe('ball_l')
+ expect(mappings.get('leftIndexProximal')).toBe('index_01_l')
+ expect(mappings.get('leftIndexDistal')).toBe('index_03_l')
+ expect(mappings.get('rightLittleProximal')).toBe('pinky_01_r')
+ })
+
+ it('lets literal name agreement win over anything the vocabulary infers', () => {
+ // the animal rigs already use Mesh2Motion's naming, so a rig whose chain is
+ // shorter than the source must still map name-for-name rather than being spread
+ // proportionally along the source chain
+ const source = BoneChainResolver.build_metadata([
+ { name: 'pelvis', parent_name: null },
+ { name: 'tail_01', parent_name: 'pelvis' },
+ { name: 'tail_02', parent_name: 'tail_01' },
+ { name: 'tail_03', parent_name: 'tail_02' },
+ { name: 'tail_04', parent_name: 'tail_03' },
+ { name: 'tail_05', parent_name: 'tail_04' }
+ ])
+ const target = BoneChainResolver.build_metadata([
+ { name: 'pelvis', parent_name: null },
+ { name: 'tail_01', parent_name: 'pelvis' },
+ { name: 'tail_02', parent_name: 'tail_01' },
+ { name: 'tail_03', parent_name: 'tail_02' }
+ ])
+
+ const mappings = BoneAutoMapper.map_by_canonical_slots(source, target)
+
+ expect(mappings.get('tail_01')).toBe('tail_01')
+ expect(mappings.get('tail_02')).toBe('tail_02')
+ expect(mappings.get('tail_03')).toBe('tail_03')
+ })
+
+ it('spreads a differently-named chain of unequal length along the source', () => {
+ const source = BoneChainResolver.build_metadata([
+ { name: 'pelvis', parent_name: null },
+ { name: 'tail_01', parent_name: 'pelvis' },
+ { name: 'tail_02', parent_name: 'tail_01' },
+ { name: 'tail_03', parent_name: 'tail_02' }
+ ])
+ const target = BoneChainResolver.build_metadata([
+ { name: 'Hips', parent_name: null },
+ { name: 'Tail_A', parent_name: 'Hips' },
+ { name: 'Tail_B', parent_name: 'Tail_A' }
+ ])
+
+ const mappings = BoneAutoMapper.map_by_canonical_slots(source, target)
+
+ expect(mappings.get('Hips')).toBe('pelvis')
+ expect(mappings.get('Tail_A')).toBe('tail_01')
+ expect(mappings.get('Tail_B')).toBe('tail_03')
+ })
+
+ it('leaves an unrecognisable rig unmapped rather than mapping it wrongly', () => {
+ const nonsense: RawBoneRecord[] = [
+ { name: 'zzz_00', parent_name: null },
+ { name: 'zzz_01', parent_name: 'zzz_00' },
+ { name: 'zzz_02', parent_name: 'zzz_01' }
+ ]
+
+ expect(map_rig(nonsense).size).toBe(0)
+ })
+
+ it('survives a skeleton with a parent cycle', () => {
+ const cyclic: RawBoneRecord[] = [
+ { name: 'a', parent_name: 'c' },
+ { name: 'b', parent_name: 'a' },
+ { name: 'c', parent_name: 'b' }
+ ]
+
+ expect(() => BoneChainResolver.build_metadata(cyclic)).not.toThrow()
+ })
+})
+
+describe('template rig detection', () => {
+ it('detects a Mixamo rig with and without the mixamorig prefix', () => {
+ expect(MixamoMapper.is_target_valid_skeleton(bone_names(mixamo_rig()))).toBe(true)
+ expect(MixamoMapper.is_target_valid_skeleton(bone_names(mixamo_rig('')))).toBe(true)
+ })
+
+ it('does not mistake other rigs for Mixamo', () => {
+ expect(MixamoMapper.is_target_valid_skeleton(bone_names(unreal_rig()))).toBe(false)
+ expect(MixamoMapper.is_target_valid_skeleton(bone_names(daz_rig()))).toBe(false)
+ expect(MixamoMapper.is_target_valid_skeleton(bone_names(vrm_rig()))).toBe(false)
+ expect(MixamoMapper.is_target_valid_skeleton(bone_names(mesh2motion_rig()))).toBe(false)
+ expect(MixamoMapper.is_target_valid_skeleton([])).toBe(false)
+ })
+
+ it('maps a prefix-stripped Mixamo rig through the exact template table', () => {
+ const source = BoneChainResolver.build_metadata(mesh2motion_rig())
+ const target = BoneChainResolver.build_metadata(mixamo_rig(''))
+ const mappings = MixamoMapper.map_mixamo_bones(source, target)
+
+ expect(mappings.get('LeftForeArm')).toBe('lowerarm_l')
+ expect(mappings.get('LeftHandIndex1')).toBe('index_01_l')
+ expect(mappings.get('HeadTop_End')).toBe('head_leaf')
+ expect(mappings.size).toBe(mixamo_rig('').length)
+ })
+
+ it('still maps a prefixed Mixamo rig the way it always did', () => {
+ const source = BoneChainResolver.build_metadata(mesh2motion_rig())
+ const target = BoneChainResolver.build_metadata(mixamo_rig())
+ const mappings = MixamoMapper.map_mixamo_bones(source, target)
+
+ expect(mappings.get('mixamorigLeftForeArm')).toBe('lowerarm_l')
+ expect(mappings.size).toBe(mixamo_rig().length)
+ })
+
+ it('matches Rigify bones across exporter separator variations', () => {
+ const source = BoneChainResolver.build_metadata(mesh2motion_rig())
+
+ const dotted: RawBoneRecord[] = [
+ { name: 'DEF-upper_arm.L', parent_name: null },
+ { name: 'DEF-f_index.01.L', parent_name: 'DEF-upper_arm.L' }
+ ]
+ const flattened: RawBoneRecord[] = [
+ { name: 'DEF-upper_armL', parent_name: null },
+ { name: 'DEF-f_index01L', parent_name: 'DEF-upper_armL' }
+ ]
+
+ for (const variant of [dotted, flattened]) {
+ const mappings = RigifyMapper.map_rigify_bones(
+ source, BoneChainResolver.build_metadata(variant)
+ )
+ expect([...mappings.values()].sort()).toEqual(['index_01_l', 'upperarm_l'])
+ }
+ })
+})
diff --git a/src/retarget/bone-automap/BoneCategoryMapper.test.ts b/src/retarget/bone-automap/BoneCategoryMapper.test.ts
index a01917a..7c663c7 100644
--- a/src/retarget/bone-automap/BoneCategoryMapper.test.ts
+++ b/src/retarget/bone-automap/BoneCategoryMapper.test.ts
@@ -1,154 +1,75 @@
import { describe, it, expect } from 'vitest'
import { BoneCategoryMapper } from './BoneCategoryMapper'
-import { BoneCategory, type BoneMetadata, BoneSide } from './BoneAutoMapper'
+import { BoneChainResolver, type RawBoneRecord } from './BoneChainResolver'
+import { type BoneMetadata } from './BoneTypes'
/**
- * Helper function to create test bone metadata
+ * BoneCategoryMapper is the exact-name safety net that runs after the canonical
+ * slot pass. Building its input through BoneChainResolver keeps these tests honest -
+ * the old suite hand-fed normalized_name values the real normalizer never produced.
*/
-function create_bone_metadata (
- name: string,
- normalized_name: string,
- side: BoneSide = BoneSide.Center,
- category: BoneCategory = BoneCategory.Torso
-): BoneMetadata {
- return { name, normalized_name, side, category }
+function metadata (names: string[]): BoneMetadata[] {
+ const bones: RawBoneRecord[] = names.map((name, i) => ({
+ name,
+ parent_name: i === 0 ? null : names[i - 1]
+ }))
+ return BoneChainResolver.build_metadata(bones)
}
-describe('BoneCategoryMapper', () => {
- describe('map_torso_bones', () => {
- it('should map exact matching bone names', () => {
- const source_bones: BoneMetadata[] = [
- create_bone_metadata('Spine', 'spine', BoneSide.Center, BoneCategory.Torso),
- create_bone_metadata('Chest', 'chest', BoneSide.Center, BoneCategory.Torso),
- create_bone_metadata('Neck', 'neck', BoneSide.Center, BoneCategory.Torso)
- ]
-
- const target_bones: BoneMetadata[] = [
- create_bone_metadata('Spine', 'spine', BoneSide.Center, BoneCategory.Torso),
- create_bone_metadata('Chest', 'chest', BoneSide.Center, BoneCategory.Torso)
- ]
-
- const mappings = BoneCategoryMapper.map_torso_bones(source_bones, target_bones)
-
- expect(mappings.size).toBe(2)
- expect(mappings.get('Spine')).toBe('Spine')
- expect(mappings.get('Chest')).toBe('Chest')
- })
- })
+describe('BoneCategoryMapper name matching', () => {
+ it('matches bones the two rigs name identically', () => {
+ const source = metadata(['spine_01', 'spine_02', 'custom_prop_a'])
+ const target = metadata(['spine_01', 'custom_prop_a'])
- describe('map_arm_bones', () => {
- it('should map exact matching arm bone names', () => {
- const source_bones: BoneMetadata[] = [
- create_bone_metadata('LeftShoulder', 'leftshoulder', BoneSide.Left, BoneCategory.Arms),
- create_bone_metadata('LeftUpperArm', 'leftupperarm', BoneSide.Left, BoneCategory.Arms),
- create_bone_metadata('RightShoulder', 'rightshoulder', BoneSide.Right, BoneCategory.Arms)
- ]
-
- const target_bones: BoneMetadata[] = [
- create_bone_metadata('LeftShoulder', 'leftshoulder', BoneSide.Left, BoneCategory.Arms),
- create_bone_metadata('RightShoulder', 'rightshoulder', BoneSide.Right, BoneCategory.Arms)
- ]
-
- const mappings = BoneCategoryMapper.map_arm_bones(source_bones, target_bones)
-
- expect(mappings.size).toBe(2)
- expect(mappings.get('LeftShoulder')).toBe('LeftShoulder')
- expect(mappings.get('RightShoulder')).toBe('RightShoulder')
- })
- })
+ const mappings = BoneCategoryMapper.match_loose_names(source, target, new Map())
- describe('map_hand_bones', () => {
- it('should map exact matching hand bone names', () => {
- const source_bones: BoneMetadata[] = [
- create_bone_metadata('LeftHand', 'lefthand', BoneSide.Left, BoneCategory.Hands),
- create_bone_metadata('LeftThumb', 'leftthumb', BoneSide.Left, BoneCategory.Hands),
- create_bone_metadata('LeftIndex', 'leftindex', BoneSide.Left, BoneCategory.Hands)
- ]
-
- const target_bones: BoneMetadata[] = [
- create_bone_metadata('LeftHand', 'lefthand', BoneSide.Left, BoneCategory.Hands),
- create_bone_metadata('LeftThumb', 'leftthumb', BoneSide.Left, BoneCategory.Hands)
- ]
-
- const mappings = BoneCategoryMapper.map_hand_bones(source_bones, target_bones)
-
- expect(mappings.size).toBe(2)
- expect(mappings.get('LeftHand')).toBe('LeftHand')
- expect(mappings.get('LeftThumb')).toBe('LeftThumb')
- })
+ expect(mappings.get('spine_01')).toBe('spine_01')
+ expect(mappings.get('custom_prop_a')).toBe('custom_prop_a')
})
- describe('map_leg_bones', () => {
- it('should map exact matching leg bone names', () => {
- const source_bones: BoneMetadata[] = [
- create_bone_metadata('LeftThigh', 'leftthigh', BoneSide.Left, BoneCategory.Legs),
- create_bone_metadata('LeftKnee', 'leftknee', BoneSide.Left, BoneCategory.Legs),
- create_bone_metadata('RightThigh', 'rightthigh', BoneSide.Right, BoneCategory.Legs)
- ]
-
- const target_bones: BoneMetadata[] = [
- create_bone_metadata('LeftThigh', 'leftthigh', BoneSide.Left, BoneCategory.Legs),
- create_bone_metadata('RightThigh', 'rightthigh', BoneSide.Right, BoneCategory.Legs)
- ]
-
- const mappings = BoneCategoryMapper.map_leg_bones(source_bones, target_bones)
-
- expect(mappings.size).toBe(2)
- expect(mappings.get('LeftThigh')).toBe('LeftThigh')
- expect(mappings.get('RightThigh')).toBe('RightThigh')
- })
+ it('matches across separator and case differences', () => {
+ const source = metadata(['tail_01', 'tail_02'])
+ const target = metadata(['Tail.001', 'Tail.002'])
+
+ const mappings = BoneCategoryMapper.match_loose_names(source, target, new Map())
+
+ expect(mappings.get('Tail.001')).toBe('tail_01')
+ expect(mappings.get('Tail.002')).toBe('tail_02')
})
- describe('map_wing_bones', () => {
- it('should map exact matching wing bone names', () => {
- const source_bones: BoneMetadata[] = [
- create_bone_metadata('LeftWing1', 'leftwing1', BoneSide.Left, BoneCategory.Wings),
- create_bone_metadata('LeftWing2', 'leftwing2', BoneSide.Left, BoneCategory.Wings),
- create_bone_metadata('RightWing1', 'rightwing1', BoneSide.Right, BoneCategory.Wings)
- ]
-
- const target_bones: BoneMetadata[] = [
- create_bone_metadata('LeftWing1', 'leftwing1', BoneSide.Left, BoneCategory.Wings),
- create_bone_metadata('RightWing1', 'rightwing1', BoneSide.Right, BoneCategory.Wings)
- ]
-
- const mappings = BoneCategoryMapper.map_wing_bones(source_bones, target_bones)
-
- expect(mappings.size).toBe(2)
- expect(mappings.get('LeftWing1')).toBe('LeftWing1')
- expect(mappings.get('RightWing1')).toBe('RightWing1')
- })
+ it('will not pair a left bone with a right one', () => {
+ const source = metadata(['wing_01_l'])
+ const target = metadata(['wing_01_r'])
+
+ expect(BoneCategoryMapper.match_loose_names(source, target, new Map()).size).toBe(0)
})
- describe('map_tail_bones', () => {
- it('should map exact matching tail bone names', () => {
- const source_bones: BoneMetadata[] = [
- create_bone_metadata('Tail1', 'tail1', BoneSide.Center, BoneCategory.Tail),
- create_bone_metadata('Tail2', 'tail2', BoneSide.Center, BoneCategory.Tail),
- create_bone_metadata('Tail3', 'tail3', BoneSide.Center, BoneCategory.Tail)
- ]
-
- const target_bones: BoneMetadata[] = [
- create_bone_metadata('Tail1', 'tail1', BoneSide.Center, BoneCategory.Tail),
- create_bone_metadata('Tail2', 'tail2', BoneSide.Center, BoneCategory.Tail)
- ]
-
- const mappings = BoneCategoryMapper.map_tail_bones(source_bones, target_bones)
-
- expect(mappings.size).toBe(2)
- expect(mappings.get('Tail1')).toBe('Tail1')
- expect(mappings.get('Tail2')).toBe('Tail2')
- })
+ it('leaves existing mappings alone and never hands out their source bones twice', () => {
+ const source = metadata(['spine_01', 'spine_02'])
+ const target = metadata(['spine_01', 'spine_02'])
+
+ // the canonical slot pass already gave spine_01 away to a different target
+ const existing = new Map<string, string>([['spine_02', 'spine_01']])
+ const mappings = BoneCategoryMapper.match_loose_names(source, target, existing)
+
+ expect(mappings.get('spine_02')).toBe('spine_01')
+ // target spine_01 is left unmapped rather than taking spine_01 a second time
+ expect(mappings.has('spine_01')).toBe(false)
+ expect(new Set(mappings.values()).size).toBe(mappings.size)
})
- describe('map_unknown_bones', () => {
- it('should handle empty unknown bones', () => {
- const source_bones: BoneMetadata[] = []
- const target_bones: BoneMetadata[] = []
+ it('matches only literal name agreement in the exact pass', () => {
+ const source = metadata(['tail_01', 'tail_02'])
+ const target = metadata(['tail_01', 'Tail.002'])
- const mappings = BoneCategoryMapper.map_unknown_bones(source_bones, target_bones)
+ const mappings = BoneCategoryMapper.match_exact_names(source, target, new Map())
+
+ expect(mappings.get('tail_01')).toBe('tail_01')
+ expect(mappings.has('Tail.002')).toBe(false)
+ })
- expect(mappings.size).toBe(0)
- })
+ it('handles empty skeletons', () => {
+ expect(BoneCategoryMapper.match_exact_names([], [], new Map()).size).toBe(0)
+ expect(BoneCategoryMapper.match_loose_names([], [], new Map()).size).toBe(0)
})
})
diff --git a/src/retarget/bone-automap/BoneCategoryMapper.ts b/src/retarget/bone-automap/BoneCategoryMapper.ts
index 287f60d..bffee63 100644
--- a/src/retarget/bone-automap/BoneCategoryMapper.ts
+++ b/src/retarget/bone-automap/BoneCategoryMapper.ts
@@ -1,159 +1,90 @@
-import { BoneMetadata, BoneSide } from './BoneAutoMapper'
+import { type BoneMetadata, BoneSide } from './BoneTypes'
/**
- * BoneCategoryMapper - Handles category-specific bone mapping logic
- * Contains the actual matching algorithms for each anatomical category
+ * BoneCategoryMapper - name-based matching, run either side of CanonicalSlotMapper.
+ *
+ * Two passes, deliberately separated:
+ * - exact: the two rigs use literally the same bone name. Runs BEFORE the slot
+ * pass, because nothing the vocabulary infers should override two rigs simply
+ * agreeing - this is what keeps the animal skeletons, which already share
+ * Mesh2Motion's naming, mapping exactly as they did before.
+ * - loose: same name modulo case, separators and prefixes. Runs AFTER the slot
+ * pass, to catch bones whose anatomy the vocabulary has no word for.
+ *
+ * This used to be seven near-identical per-category methods, each carrying a
+ * "TODO: add category-specific matching logic here". The logic those were waiting
+ * for now lives in BoneSlotVocabulary / BoneChainResolver instead.
*/
export class BoneCategoryMapper {
/**
- * Map torso bones (spine, chest, neck, head, hips, pelvis)
+ * Match target bones to source bones with the exact same name.
+ * @returns a new map: the existing mappings plus whatever this pass added
*/
- static map_torso_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
- // if target or source torso bones are empty, return empty mapping
- if (source_bones === null || target_bones === null) {
- console.error('map_torso_bones(): No source or target bones found. This should not be reached.')
- return new Map<string, string>()
- }
-
- const category_mappings = new Map<string, string>()
-
- console.log('DEVELOPING THE TORSO MAPPER')
- console.log('Source Bones:', source_bones)
- console.log('Target Bones:', target_bones)
-
- // Perform exact name matching first
- this.perform_exact_name_matching(source_bones, target_bones, category_mappings)
-
- return category_mappings
- }
-
- /**
- * Map arm bones (shoulder, upper arm, elbow, forearm, wrist)
- */
- static map_arm_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
- const category_mappings = new Map<string, string>()
-
- // Perform exact name matching first
- this.perform_exact_name_matching(source_bones, target_bones, category_mappings)
-
- // TODO: Add category-specific matching logic here
-
- return category_mappings
- }
-
- /**
- * Map hand bones (hands, fingers, thumbs)
- */
- static map_hand_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
- const category_mappings = new Map<string, string>()
-
- // Perform exact name matching first
- this.perform_exact_name_matching(source_bones, target_bones, category_mappings)
-
- // TODO: Add category-specific matching logic here
-
- return category_mappings
- }
-
- /**
- * Map leg bones (hips, thighs, knees, calves, ankles, feet, toes)
- */
- static map_leg_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
- const category_mappings = new Map<string, string>()
-
- // Perform exact name matching first
- this.perform_exact_name_matching(source_bones, target_bones, category_mappings)
-
- // TODO: Add category-specific matching logic here
-
- return category_mappings
+ static match_exact_names (
+ source_bones: BoneMetadata[],
+ target_bones: BoneMetadata[],
+ existing_mappings: Map<string, string>
+ ): Map<string, string> {
+ return BoneCategoryMapper.match(
+ source_bones, target_bones, existing_mappings,
+ (source, target) => source.name === target.name
+ )
}
/**
- * Map wing bones (wings, feathers, pinions)
+ * Match remaining target bones by normalized name, but only across compatible
+ * sides so a left bone is never handed a right bone's animation.
+ * @returns a new map: the existing mappings plus whatever this pass added
*/
- static map_wing_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
- const category_mappings = new Map<string, string>()
-
- // Perform exact name matching first
- this.perform_exact_name_matching(source_bones, target_bones, category_mappings)
-
- // TODO: Add category-specific matching logic here
-
- return category_mappings
- }
-
- /**
- * Map tail bones
- */
- static map_tail_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
- const category_mappings = new Map<string, string>()
-
- // Perform exact name matching first
- this.perform_exact_name_matching(source_bones, target_bones, category_mappings)
-
- // TODO: Add category-specific matching logic here
-
- return category_mappings
- }
-
- /**
- * Map unknown/uncategorized bones
- */
- static map_unknown_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
- const category_mappings = new Map<string, string>()
-
- // Perform exact name matching first
- this.perform_exact_name_matching(source_bones, target_bones, category_mappings)
-
- // TODO: Add category-specific matching logic here
-
- return category_mappings
+ static match_loose_names (
+ source_bones: BoneMetadata[],
+ target_bones: BoneMetadata[],
+ existing_mappings: Map<string, string>
+ ): Map<string, string> {
+ return BoneCategoryMapper.match(
+ source_bones, target_bones, existing_mappings,
+ (source, target) =>
+ source.normalized_name === target.normalized_name &&
+ BoneCategoryMapper.sides_compatible(source.side, target.side)
+ )
}
/**
- * Match target bones to source bones by normalized name + compatible side.
- * Each source bone may only be used once.
- * @param source_bones - Array of source bone metadata
- * @param target_bones - Array of target bone metadata
- * @param category_mappings - Map to store the bone name mappings
+ * Shared body of both passes. Skips any target already mapped and any source
+ * already used, so passes compose in any order without double-assigning a bone.
*/
- private static perform_exact_name_matching (source_bones: BoneMetadata[],
- target_bones: BoneMetadata[], category_mappings: Map<string, string>): void {
-
- const used_source_names = new Set<string>(category_mappings.values())
-
- for (const target_bone_meta of target_bones) {
- if (category_mappings.has(target_bone_meta.name)) continue
-
- // Prefer same-side, exact-normalized match first
- let match: BoneMetadata | undefined = source_bones.find(sb =>
- !used_source_names.has(sb.name) &&
- sb.normalized_name === target_bone_meta.normalized_name &&
- BoneCategoryMapper.sides_compatible(sb.side, target_bone_meta.side)
+ private static match (
+ source_bones: BoneMetadata[],
+ target_bones: BoneMetadata[],
+ existing_mappings: Map<string, string>,
+ is_match: (source: BoneMetadata, target: BoneMetadata) => boolean
+ ): Map<string, string> {
+ const mappings = new Map<string, string>(existing_mappings)
+ const used_source_names = new Set<string>(mappings.values())
+
+ for (const target_bone of target_bones) {
+ if (mappings.has(target_bone.name)) continue
+
+ const match: BoneMetadata | undefined = source_bones.find(
+ source_bone => !used_source_names.has(source_bone.name) && is_match(source_bone, target_bone)
)
- // Fallback: raw-name match (preserves prior behavior for identical names)
- if (match === undefined) {
- match = source_bones.find(sb =>
- !used_source_names.has(sb.name) &&
- sb.name === target_bone_meta.name
- )
- }
-
if (match !== undefined) {
- category_mappings.set(target_bone_meta.name, match.name)
+ mappings.set(target_bone.name, match.name)
used_source_names.add(match.name)
}
}
+
+ return mappings
}
private static sides_compatible (a: BoneSide, b: BoneSide): boolean {
if (a === b) return true
+
+ // Unknown means the name carried no side marker, so it pairs with anything
if (a === BoneSide.Unknown || b === BoneSide.Unknown) return true
- if (a === BoneSide.Center || b === BoneSide.Center) {
- return a === BoneSide.Center && b === BoneSide.Center
- }
+
+ // a midline bone must not be paired with a left or right one
return false
}
}
diff --git a/src/retarget/bone-automap/BoneChainResolver.ts b/src/retarget/bone-automap/BoneChainResolver.ts
new file mode 100644
index 0000000..3660f01
--- /dev/null
+++ b/src/retarget/bone-automap/BoneChainResolver.ts
@@ -0,0 +1,308 @@
+import { type BoneMetadata, BoneSide, BoneSlot } from './BoneTypes'
+import { normalized_lookup_key, parse_bone_name, type ParsedBoneName } from './BoneNameTokenizer'
+import {
+ is_arm_ambiguous_slot, is_finger_slot, is_leg_ambiguous_slot, resolve_slot, slot_to_category
+} from './BoneSlotVocabulary'
+
+/**
+ * BoneChainResolver - builds BoneMetadata from a flat list of (bone, parent) pairs
+ * and resolves each bone to a canonical slot.
+ *
+ * Names alone cannot settle every joint. The two that matter in practice:
+ * - Mixamo calls the clavicle "LeftShoulder" and the upper arm "LeftArm";
+ * DAZ calls the upper arm "lShldr" and the clavicle "lCollar".
+ * - Mixamo calls the calf "LeftLeg"; plenty of rigs call the thigh "leg_l".
+ * Both are settled by walking up from the hand and the foot, where the terminal
+ * joint is named unambiguously in every rig we care about.
+ *
+ * Deliberately takes plain records rather than three.js Bones so it can be unit
+ * tested with nothing more than a list of names and parents.
+ */
+
+export interface RawBoneRecord {
+ name: string
+ parent_name: string | null
+}
+
+export class BoneChainResolver {
+ /**
+ * Build fully resolved metadata for a skeleton.
+ * @param bones - flat list of bone names with their parent bone name
+ */
+ static build_metadata (bones: RawBoneRecord[]): BoneMetadata[] {
+ const bone_names = new Set<string>(bones.map(b => b.name))
+
+ // a bone's recorded parent can be the armature/scene node rather than another
+ // bone - treat anything outside the bone set as "no parent"
+ const parent_of = new Map<string, string | null>()
+ const children_of = new Map<string, string[]>()
+ for (const bone of bones) {
+ const parent: string | null =
+ (bone.parent_name !== null && bone_names.has(bone.parent_name)) ? bone.parent_name : null
+ parent_of.set(bone.name, parent)
+ if (!children_of.has(bone.name)) {
+ children_of.set(bone.name, [])
+ }
+ if (parent !== null) {
+ const siblings: string[] = children_of.get(parent) ?? []
+ siblings.push(bone.name)
+ children_of.set(parent, siblings)
+ }
+ }
+
+ const depth_of = BoneChainResolver.compute_depths(bones, parent_of)
+ const parsed_of = new Map<string, ParsedBoneName>()
+ for (const bone of bones) {
+ parsed_of.set(bone.name, parse_bone_name(bone.name))
+ }
+
+ // side first: slot rules need to know the side, and a finger named "Middle1"
+ // only becomes mappable once it inherits Left/Right from an ancestor
+ const side_of = BoneChainResolver.resolve_sides(bones, parent_of, depth_of, parsed_of)
+
+ const metadata_of = new Map<string, BoneMetadata>()
+ const rejected = new Set<string>()
+ for (const bone of bones) {
+ const parsed = parsed_of.get(bone.name) as ParsedBoneName
+ const side = side_of.get(bone.name) as BoneSide
+ const slot: BoneSlot = resolve_slot(parsed, side)
+
+ // an Unknown slot on a bone that still had tokens means the vocabulary
+ // rejected it (twist/IK/prop) or simply does not know the word - either way
+ // the hierarchy pass must not promote it into a real joint
+ if (slot === BoneSlot.Unknown) {
+ rejected.add(bone.name)
+ }
+
+ metadata_of.set(bone.name, {
+ name: bone.name,
+ normalized_name: normalized_lookup_key(bone.name),
+ side,
+ category: slot_to_category(slot),
+ parent_name: parent_of.get(bone.name) ?? null,
+ depth: depth_of.get(bone.name) ?? 0,
+ children_names: children_of.get(bone.name) ?? [],
+ slot,
+ slot_ordinal: 0,
+ is_leaf_name: parsed.is_leaf
+ })
+ }
+
+ BoneChainResolver.infer_missing_hands(metadata_of)
+ BoneChainResolver.resolve_limb_chains(metadata_of, rejected)
+ BoneChainResolver.assign_ordinals(metadata_of)
+
+ // keep the caller's original ordering
+ return bones.map(b => metadata_of.get(b.name) as BoneMetadata)
+ }
+
+ /**
+ * Distance from the root. Iterative with a visited guard so a malformed skeleton
+ * with a parent cycle cannot hang the mapper.
+ */
+ private static compute_depths (
+ bones: RawBoneRecord[], parent_of: Map<string, string | null>
+ ): Map<string, number> {
+ const depth_of = new Map<string, number>()
+
+ for (const bone of bones) {
+ if (depth_of.has(bone.name)) continue
+
+ const path: string[] = []
+ const seen = new Set<string>()
+ let current: string | null = bone.name
+
+ while (current !== null && !depth_of.has(current) && !seen.has(current)) {
+ seen.add(current)
+ path.push(current)
+ current = parent_of.get(current) ?? null
+ }
+
+ let depth: number = (current !== null && depth_of.has(current))
+ ? (depth_of.get(current) as number) + 1
+ : 0
+
+ // path was built child-first, so walk it back down
+ for (let i = path.length - 1; i >= 0; i--) {
+ depth_of.set(path[i], depth)
+ depth++
+ }
+ }
+
+ return depth_of
+ }
+
+ /**
+ * A bone with no side marker in its own name inherits the nearest ancestor that
+ * has one. Only Left/Right is inherited - Center is never propagated, since a
+ * bone hanging off the pelvis is not thereby a midline bone.
+ */
+ private static resolve_sides (
+ bones: RawBoneRecord[],
+ parent_of: Map<string, string | null>,
+ depth_of: Map<string, number>,
+ parsed_of: Map<string, ParsedBoneName>
+ ): Map<string, BoneSide> {
+ const side_of = new Map<string, BoneSide>()
+
+ // shallowest first, so an ancestor is always resolved before its children
+ const ordered: RawBoneRecord[] = [...bones].sort(
+ (a, b) => (depth_of.get(a.name) ?? 0) - (depth_of.get(b.name) ?? 0)
+ )
+
+ for (const bone of ordered) {
+ const own_side: BoneSide = (parsed_of.get(bone.name) as ParsedBoneName).side
+
+ if (own_side === BoneSide.Left || own_side === BoneSide.Right) {
+ side_of.set(bone.name, own_side)
+ continue
+ }
+
+ const parent: string | null = parent_of.get(bone.name) ?? null
+ const inherited: BoneSide | undefined = parent !== null ? side_of.get(parent) : undefined
+
+ side_of.set(
+ bone.name,
+ (inherited === BoneSide.Left || inherited === BoneSide.Right) ? inherited : BoneSide.Center
+ )
+ }
+
+ return side_of
+ }
+
+ /**
+ * Some rigs name the wrist joint something the vocabulary does not recognise, but
+ * a bone with three or more finger children is a hand no matter what it is called.
+ * The arm walk anchors on Hand, so recovering it here is what lets the rest of the
+ * arm resolve.
+ */
+ private static infer_missing_hands (metadata_of: Map<string, BoneMetadata>): void {
+ for (const bone of metadata_of.values()) {
+ if (bone.slot === BoneSlot.Hand) continue
+
+ let finger_children: number = 0
+ for (const child_name of bone.children_names) {
+ const child: BoneMetadata | undefined = metadata_of.get(child_name)
+ if (child !== undefined && is_finger_slot(child.slot)) {
+ finger_children++
+ }
+ }
+
+ if (finger_children >= 3) {
+ bone.slot = BoneSlot.Hand
+ bone.category = slot_to_category(BoneSlot.Hand)
+ }
+ }
+ }
+
+ /**
+ * Walk up from each hand and each foot, assigning the joints above them by
+ * position rather than by name.
+ */
+ private static resolve_limb_chains (
+ metadata_of: Map<string, BoneMetadata>, rejected: Set<string>
+ ): void {
+ for (const bone of metadata_of.values()) {
+ if (bone.slot === BoneSlot.Hand) {
+ BoneChainResolver.walk_limb(
+ bone, metadata_of, rejected,
+ [BoneSlot.LowerArm, BoneSlot.UpperArm, BoneSlot.Clavicle],
+ [BoneSlot.Hand],
+ is_arm_ambiguous_slot
+ )
+ }
+
+ if (bone.slot === BoneSlot.Foot) {
+ BoneChainResolver.walk_limb(
+ bone, metadata_of, rejected,
+ [BoneSlot.Calf, BoneSlot.Thigh],
+ [BoneSlot.Foot, BoneSlot.Ball],
+ is_leg_ambiguous_slot
+ )
+ }
+ }
+ }
+
+ /**
+ * Assign `targets` to successive ancestors of `terminal`.
+ * @param passthrough_slots - slots that belong to the terminal cluster (a wrist
+ * above a hand) and are stepped over without consuming
+ * a target
+ * @param is_ambiguous - whether a slot is weakly enough named to be overwritten;
+ * hitting a confidently named joint (Spine, Neck) ends the walk
+ */
+ private static walk_limb (
+ terminal: BoneMetadata,
+ metadata_of: Map<string, BoneMetadata>,
+ rejected: Set<string>,
+ targets: BoneSlot[],
+ passthrough_slots: BoneSlot[],
+ is_ambiguous: (slot: BoneSlot) => boolean
+ ): void {
+ let target_index: number = 0
+ let current: BoneMetadata | undefined =
+ terminal.parent_name !== null ? metadata_of.get(terminal.parent_name) : undefined
+
+ while (current !== undefined && target_index < targets.length) {
+ // stepping outside the limb (into the spine, or across the midline) ends the walk
+ if (current.side !== terminal.side) break
+
+ // twist / IK / prop bones sit in the chain but are never real joints
+ if (rejected.has(current.name)) {
+ current = current.parent_name !== null ? metadata_of.get(current.parent_name) : undefined
+ continue
+ }
+
+ if (passthrough_slots.includes(current.slot)) {
+ current = current.parent_name !== null ? metadata_of.get(current.parent_name) : undefined
+ continue
+ }
+
+ if (!is_ambiguous(current.slot)) break
+
+ current.slot = targets[target_index]
+ current.category = slot_to_category(current.slot)
+ target_index++
+
+ current = current.parent_name !== null ? metadata_of.get(current.parent_name) : undefined
+ }
+ }
+
+ /**
+ * Number each (slot, side) group 1..N from the root outward.
+ *
+ * Doing this from the hierarchy rather than from the digits in the name is what
+ * makes chains line up across rigs that number differently: Mixamo's
+ * Spine/Spine1/Spine2 and Mesh2Motion's spine_01/spine_02/spine_03 both become
+ * 1/2/3, and Mixamo's Head + HeadTop_End pairs with head + head_leaf without
+ * either being a special case.
+ */
+ private static assign_ordinals (metadata_of: Map<string, BoneMetadata>): void {
+ const groups = new Map<string, BoneMetadata[]>()
+
+ for (const bone of metadata_of.values()) {
+ if (bone.slot === BoneSlot.Unknown) continue
+ const key = `${bone.slot}|${bone.side}`
+ const group: BoneMetadata[] = groups.get(key) ?? []
+ group.push(bone)
+ groups.set(key, group)
+ }
+
+ for (const group of groups.values()) {
+ group.sort((a, b) => {
+ if (a.depth !== b.depth) return a.depth - b.depth
+ // flat hierarchies (every bone parented to the armature) tie on depth, so
+ // fall back to the number in the name, then to the name itself
+ if (a.is_leaf_name !== b.is_leaf_name) return a.is_leaf_name ? 1 : -1
+ const a_index: number = parse_bone_name(a.name).index ?? 0
+ const b_index: number = parse_bone_name(b.name).index ?? 0
+ if (a_index !== b_index) return a_index - b_index
+ return a.name.localeCompare(b.name)
+ })
+
+ group.forEach((bone, i) => {
+ bone.slot_ordinal = i + 1
+ })
+ }
+ }
+}
diff --git a/src/retarget/bone-automap/BoneNameTokenizer.test.ts b/src/retarget/bone-automap/BoneNameTokenizer.test.ts
new file mode 100644
index 0000000..6723cb9
--- /dev/null
+++ b/src/retarget/bone-automap/BoneNameTokenizer.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect } from 'vitest'
+import { normalized_lookup_key, parse_bone_name } from './BoneNameTokenizer'
+import { BoneSide } from './BoneTypes'
+
+describe('parse_bone_name', () => {
+ it('splits camelCase, separators and letter/digit boundaries', () => {
+ expect(parse_bone_name('LeftHandIndex1').tokens).toEqual(['hand', 'index'])
+ expect(parse_bone_name('upperarm_l').tokens).toEqual(['upper', 'arm'])
+ expect(parse_bone_name('DEF-upper_arm.L').tokens).toEqual(['upper', 'arm'])
+ expect(parse_bone_name('lShldr').tokens).toEqual(['shldr'])
+ })
+
+ it('strips rig namespaces and prefixes', () => {
+ expect(parse_bone_name('mixamorig:Hips').tokens).toEqual(['hips'])
+ expect(parse_bone_name('mixamorigHips').tokens).toEqual(['hips'])
+ expect(parse_bone_name('Armature|mixamorig:LeftFoot').tokens).toEqual(['foot'])
+ expect(parse_bone_name('CC_Base_L_Upperarm').tokens).toEqual(['upper', 'arm'])
+ expect(parse_bone_name('Bip01 L UpperArm').tokens).toEqual(['upper', 'arm'])
+ })
+
+ it('never mistakes a trailing letter for a side marker', () => {
+ // the old normalizer read "shoulder" as right-sided and "tail" as left-sided,
+ // then chopped them down to "shoulde" and "tai"
+ const shoulder = parse_bone_name('shoulder')
+ expect(shoulder.tokens).toEqual(['shoulder'])
+ expect(shoulder.side).toBe(BoneSide.Unknown)
+
+ const tail = parse_bone_name('tail_01')
+ expect(tail.tokens).toEqual(['tail'])
+ expect(tail.side).toBe(BoneSide.Unknown)
+ expect(tail.index).toBe(1)
+ })
+
+ it('reads the side only from a standalone token', () => {
+ expect(parse_bone_name('LeftArm').side).toBe(BoneSide.Left)
+ expect(parse_bone_name('hand_r').side).toBe(BoneSide.Right)
+ expect(parse_bone_name('DEF-f_index.01.R').side).toBe(BoneSide.Right)
+ expect(parse_bone_name('lCollar').side).toBe(BoneSide.Left)
+ expect(parse_bone_name('spine_02').side).toBe(BoneSide.Unknown)
+ })
+
+ it('extracts segment indices and leaf markers', () => {
+ expect(parse_bone_name('spine_02').index).toBe(2)
+ expect(parse_bone_name('LeftHandThumb3').index).toBe(3)
+
+ const leaf = parse_bone_name('thumb_04_leaf_l')
+ expect(leaf.index).toBe(4)
+ expect(leaf.is_leaf).toBe(true)
+ expect(leaf.tokens).toEqual(['thumb'])
+
+ expect(parse_bone_name('HeadTop_End').is_leaf).toBe(true)
+ expect(parse_bone_name('LeftToe_End').is_leaf).toBe(true)
+ expect(parse_bone_name('head').is_leaf).toBe(false)
+ })
+
+ it('keeps a name that is nothing but a prefix', () => {
+ expect(parse_bone_name('mixamorig').tokens.length).toBeGreaterThan(0)
+ })
+})
+
+describe('normalized_lookup_key', () => {
+ it('collapses Mixamo prefix variations onto one key', () => {
+ expect(normalized_lookup_key('mixamorig:LeftForeArm')).toBe('leftforearm')
+ expect(normalized_lookup_key('mixamorigLeftForeArm')).toBe('leftforearm')
+ expect(normalized_lookup_key('LeftForeArm')).toBe('leftforearm')
+ })
+
+ it('collapses Rigify separator and leading-zero variations onto one key', () => {
+ expect(normalized_lookup_key('DEF-upper_arm.L')).toBe('upperarml')
+ expect(normalized_lookup_key('DEF-upper_armL')).toBe('upperarml')
+ expect(normalized_lookup_key('DEF-thumb.01.L')).toBe('thumb1l')
+ expect(normalized_lookup_key('DEF-thumb01L')).toBe('thumb1l')
+ expect(normalized_lookup_key('DEF-spine.001')).toBe('spine1')
+ expect(normalized_lookup_key('DEF-spine001')).toBe('spine1')
+ })
+
+ it('keeps side and index, unlike parse_bone_name', () => {
+ expect(normalized_lookup_key('LeftUpLeg')).toBe('leftupleg')
+ expect(normalized_lookup_key('upleg_l')).toBe('uplegl')
+ })
+})
diff --git a/src/retarget/bone-automap/BoneNameTokenizer.ts b/src/retarget/bone-automap/BoneNameTokenizer.ts
new file mode 100644
index 0000000..62961a8
--- /dev/null
+++ b/src/retarget/bone-automap/BoneNameTokenizer.ts
@@ -0,0 +1,207 @@
+import { BoneSide } from './BoneTypes'
+
+/**
+ * BoneNameTokenizer - turns a raw bone name from any rig into structured tokens.
+ *
+ * The old normalize_bone_name() worked on the raw string with substring/suffix
+ * regexes, which is what made "shoulder" end in "r" (detected as right side) and
+ * "tail" end in "l" (detected as left, and stripped down to "tai"). Splitting the
+ * name into whole word tokens first removes that entire class of bug: a side
+ * marker only counts when it stands alone as a token.
+ *
+ * This module stays purely mechanical - it splits and cleans names but knows
+ * nothing about anatomy. All synonym knowledge lives in BoneSlotVocabulary.
+ *
+ * Pure functions, no three.js - directly unit testable.
+ */
+
+export interface ParsedBoneName {
+ tokens: string[] // canonical lowercase word tokens, prefixes and side/index removed
+ side: BoneSide // Unknown when the name carried no side marker
+ index: number | null // numeric segment index found in the name, null if absent
+ is_leaf: boolean // name carried an end/tip/leaf/nub marker
+}
+
+/**
+ * Rig namespace prefixes that appear as a single glued-on chunk. Stripped from the
+ * raw string before tokenizing, because tokenizing them first would produce junk:
+ * "Bip01" would split into "bip" + "01" and the "01" would be mistaken for a
+ * segment index.
+ */
+const GLUED_PREFIXES = /^(mixamorig|valvebiped|bip001|bip01|ccbase|cc_base)[-_.\s]?/i
+
+/**
+ * Shorter prefixes that only count as a prefix when followed by a separator, so a
+ * bone genuinely named "org" or "b" is not mangled.
+ */
+const SEPARATED_PREFIXES = /^(def|org|mch|ctrl|bn|jnt|bone|armature|b|j)[-_.]/i
+
+/**
+ * Tokens that carry no anatomical meaning and are dropped after splitting.
+ * "f" comes from Rigify's f_index / f_middle finger bones; proximal/intermediate/
+ * distal come from VRM, where segment order is recovered from the hierarchy anyway.
+ */
+const NOISE_TOKENS = new Set([
+ 'bone', 'bones', 'jnt', 'joint', 'joints', 'def', 'deform', 'org', 'mch',
+ 'f', 'skin', 'rig', 'proximal', 'intermediate', 'distal'
+])
+
+/** A token that is exactly one of these marks the bone's side */
+const LEFT_TOKENS = new Set(['l', 'lf', 'lft', 'left'])
+const RIGHT_TOKENS = new Set(['r', 'rt', 'rgt', 'right'])
+
+/** Markers that this bone is the terminating tip of a chain */
+const LEAF_TOKENS = new Set(['end', 'tip', 'leaf', 'nub', 'top'])
+
+/**
+ * Glued compound words split into the same tokens a camelCase name would produce,
+ * so "upperarm", "upper_arm" and "UpperArm" all end up as ["upper", "arm"].
+ * These splits are mechanical only - deciding that upper+arm means the upper arm
+ * is BoneSlotVocabulary's job.
+ */
+const COMPOUND_TOKENS: Record<string, string[]> = {
+ upperarm: ['upper', 'arm'],
+ uparm: ['up', 'arm'],
+ lowerarm: ['lower', 'arm'],
+ loarm: ['lo', 'arm'],
+ forearm: ['fore', 'arm'],
+ upperleg: ['upper', 'leg'],
+ upleg: ['up', 'leg'],
+ lowerleg: ['lower', 'leg'],
+ loleg: ['lo', 'leg'],
+ upperchest: ['upper', 'chest'],
+ toebase: ['toe', 'base'],
+ collarbone: ['collar', 'bone'],
+ headtop: ['head', 'top'],
+ handthumb: ['hand', 'thumb'],
+ handindex: ['hand', 'index'],
+ handmiddle: ['hand', 'middle'],
+ handring: ['hand', 'ring'],
+ handpinky: ['hand', 'pinky'],
+ indexfinger: ['index', 'finger'],
+ middlefinger: ['middle', 'finger'],
+ ringfinger: ['ring', 'finger'],
+ pinkyfinger: ['pinky', 'finger'],
+ thumbfinger: ['thumb', 'finger']
+}
+
+/**
+ * Split a raw bone name into lowercase word tokens.
+ * Handles separators, camelCase boundaries, acronym boundaries (LArm -> l arm)
+ * and letter/digit boundaries (Index1 -> index 1).
+ */
+function split_into_tokens (name: string): string[] {
+ const spaced: string = name
+ .replace(/([a-z])([A-Z])/g, '$1 $2') // camelCase: LeftFore -> Left Fore
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') // acronym run: LArm -> L Arm
+ .replace(/([A-Za-z])(\d)/g, '$1 $2') // Index1 -> Index 1
+ .replace(/(\d)([A-Za-z])/g, '$1 $2') // 1Index -> 1 Index
+ .toLowerCase()
+
+ const raw_tokens: string[] = spaced.split(/[^a-z0-9]+/).filter(t => t.length > 0)
+
+ // expand glued compound words into their parts
+ const expanded: string[] = []
+ for (const token of raw_tokens) {
+ const compound: string[] | undefined = COMPOUND_TOKENS[token]
+ if (compound !== undefined) {
+ expanded.push(...compound)
+ } else {
+ expanded.push(token)
+ }
+ }
+
+ return expanded
+}
+
+/**
+ * Strip rig namespaces and known prefixes from a raw bone name.
+ * Maya/glTF namespaces ("Armature|mixamorig:Hips") keep only the last segment.
+ */
+function strip_prefixes (bone_name: string): string {
+ // keep only the last namespace segment
+ const segments: string[] = bone_name.split(/[|:]/)
+ const last_segment: string = segments[segments.length - 1]
+
+ // a trailing separator can leave an empty segment - fall back to the whole name
+ let name: string = last_segment.length > 0 ? last_segment : bone_name
+
+ name = name.replace(GLUED_PREFIXES, '')
+ name = name.replace(SEPARATED_PREFIXES, '')
+
+ // if stripping left nothing behind, the "prefix" was the entire name - keep it
+ if (name.trim().length === 0) {
+ return last_segment.length > 0 ? last_segment : bone_name
+ }
+
+ return name
+}
+
+/**
+ * Parse a bone name into tokens, side, numeric index and leaf marker.
+ */
+export function parse_bone_name (bone_name: string): ParsedBoneName {
+ const tokens: string[] = split_into_tokens(strip_prefixes(bone_name))
+
+ let side: BoneSide = BoneSide.Unknown
+ let index: number | null = null
+ let is_leaf: boolean = false
+ const remaining: string[] = []
+
+ for (const token of tokens) {
+ if (LEFT_TOKENS.has(token)) {
+ side = BoneSide.Left
+ continue
+ }
+
+ if (RIGHT_TOKENS.has(token)) {
+ side = BoneSide.Right
+ continue
+ }
+
+ if (LEAF_TOKENS.has(token)) {
+ is_leaf = true
+ continue
+ }
+
+ if (/^\d+$/.test(token)) {
+ // last numeric token wins: "f_index.01" -> 1, "Spine2" -> 2
+ index = parseInt(token, 10)
+ continue
+ }
+
+ if (NOISE_TOKENS.has(token)) {
+ continue
+ }
+
+ remaining.push(token)
+ }
+
+ return { tokens: remaining, side, index, is_leaf }
+}
+
+/**
+ * Build a loose lookup key for comparing a bone name against a hardcoded template
+ * table (MixamoMapper / RigifyMapper). Both sides of the comparison run through
+ * this, so exporter variations cancel out:
+ * "mixamorig:LeftForeArm" / "mixamorigLeftForeArm" / "LeftForeArm" -> "leftforearm"
+ * "DEF-upper_arm.L" / "DEF-upper_armL" -> "upperarml"
+ * "DEF-thumb.01.L" / "DEF-thumb01L" -> "thumb1l"
+ *
+ * Unlike parse_bone_name this keeps the side and index tokens, since those are what
+ * distinguish one template entry from another.
+ */
+export function normalized_lookup_key (bone_name: string): string {
+ const tokens: string[] = split_into_tokens(strip_prefixes(bone_name))
+
+ return tokens
+ .filter(token => !NOISE_TOKENS.has(token))
+ .map((token) => {
+ // normalize numeric segments so "01" and "1" compare equal
+ if (/^\d+$/.test(token)) {
+ return String(parseInt(token, 10))
+ }
+ return token
+ })
+ .join('')
+}
diff --git a/src/retarget/bone-automap/BoneSlotVocabulary.ts b/src/retarget/bone-automap/BoneSlotVocabulary.ts
new file mode 100644
index 0000000..494577b
--- /dev/null
+++ b/src/retarget/bone-automap/BoneSlotVocabulary.ts
@@ -0,0 +1,191 @@
+import { BoneCategory, BoneSide, BoneSlot } from './BoneTypes'
+import { type ParsedBoneName } from './BoneNameTokenizer'
+
+/**
+ * BoneSlotVocabulary - the synonym table that turns tokenized bone names into
+ * canonical joint slots.
+ *
+ * This is the file that grows as new rigs turn up, so it is deliberately a
+ * declarative rule list rather than branching code. Rules are evaluated in order
+ * and the first match wins, which is why the compound forms ("fore" + "arm") sit
+ * above the bare fallbacks (a lone "arm").
+ *
+ * Genuinely ambiguous names are resolved here only as a best guess; where the
+ * skeleton hierarchy disagrees, BoneChainResolver overrides this. The two known
+ * ambiguities:
+ * - "shoulder" is the clavicle in Mixamo but the upper arm in DAZ/Poser
+ * - "leg" is the calf in Mixamo but the thigh in plenty of hand-rolled rigs
+ */
+
+interface SlotRule {
+ slot: BoneSlot
+ all?: string[] // every one of these tokens must be present
+ any?: string[] // at least one of these tokens must be present
+ require_side?: boolean // only matches when the bone has a known left/right side
+ forbid_side?: boolean // only matches when the bone has no left/right side
+}
+
+/**
+ * Tokens that disqualify a bone from ever being mapped.
+ *
+ * This guard matters more than it looks. Loose matching without it happily binds a
+ * forearm *twist* bone to lowerarm_l, or an IK pole target to a real joint, and the
+ * result is a retarget that looks broken rather than one that looks unmapped.
+ */
+const REJECTED_TOKENS = new Set([
+ 'twist', 'roll', 'helper', 'ik', 'fk', 'pole', 'target', 'ctrl', 'control',
+ 'attach', 'prop', 'weapon', 'socket', 'camera', 'ground', 'marker', 'tag',
+ 'adj', 'corrective', 'wrinkle', 'root', 'cog', 'reference',
+ 'eye', 'eyelid', 'pupil', 'jaw', 'tongue', 'teeth', 'muzzle', 'nose', 'brow',
+ 'cheek', 'lip', 'chin', 'ear', 'horn', 'breast', 'belly',
+ 'cloth', 'hair', 'skirt', 'cape', 'coat', 'tassel', 'buckle'
+])
+
+/**
+ * Ordered rule list. First match wins.
+ */
+const SLOT_RULES: SlotRule[] = [
+ // --- Fingers, before Hand: "LeftHandIndex1" carries both "hand" and "index".
+ // All finger rules require a side - a finger with no left/right marker cannot be
+ // mapped usefully anyway, and requiring it stops a stray "middle" or "ring"
+ // elsewhere in the rig from being read as a finger.
+ { slot: BoneSlot.FingerThumb, any: ['thumb'], require_side: true },
+ { slot: BoneSlot.FingerIndex, any: ['index', 'pointer'], require_side: true },
+ { slot: BoneSlot.FingerMiddle, any: ['middle', 'mid'], require_side: true },
+ { slot: BoneSlot.FingerRing, any: ['ring'], require_side: true },
+ { slot: BoneSlot.FingerPinky, any: ['pinky', 'pink', 'little', 'small'], require_side: true },
+
+ // --- Arm segments. Compound forms first so "upper arm" never falls through to
+ // the bare "arm" rule at the bottom.
+ { slot: BoneSlot.LowerArm, all: ['fore', 'arm'] },
+ { slot: BoneSlot.LowerArm, all: ['lower', 'arm'] },
+ { slot: BoneSlot.LowerArm, all: ['lo', 'arm'] },
+ { slot: BoneSlot.LowerArm, any: ['elbow', 'ulna', 'radius'] },
+ { slot: BoneSlot.UpperArm, all: ['upper', 'arm'] },
+ { slot: BoneSlot.UpperArm, all: ['up', 'arm'] },
+ { slot: BoneSlot.UpperArm, any: ['humerus', 'shldr'] },
+
+ // --- Leg segments
+ { slot: BoneSlot.Thigh, all: ['upper', 'leg'] },
+ { slot: BoneSlot.Thigh, all: ['up', 'leg'] },
+ { slot: BoneSlot.Thigh, any: ['thigh', 'femur'] },
+ { slot: BoneSlot.Thigh, any: ['hip'], require_side: true }, // "hip_l" is a thigh
+ { slot: BoneSlot.Calf, all: ['lower', 'leg'] },
+ { slot: BoneSlot.Calf, all: ['lo', 'leg'] },
+ { slot: BoneSlot.Calf, any: ['calf', 'shin', 'knee', 'tibia', 'fibula'] },
+
+ // --- Limb terminals. Ball before Foot so "ToeBase" is not read as a foot.
+ { slot: BoneSlot.Ball, all: ['toe', 'base'] },
+ { slot: BoneSlot.Ball, any: ['ball', 'toe', 'toes'] },
+ { slot: BoneSlot.Foot, any: ['foot', 'feet', 'ankle'] },
+ { slot: BoneSlot.Hand, any: ['hand', 'wrist', 'palm'] },
+
+ // --- Shoulder girdle. "shoulder" defaults to the clavicle (Mixamo, Unreal,
+ // Rigify all use it that way); DAZ's "shldr" is caught by the UpperArm rule above.
+ { slot: BoneSlot.Clavicle, any: ['clavicle', 'collar', 'scapula', 'shoulder'] },
+
+ // --- Torso and head
+ { slot: BoneSlot.Head, any: ['head', 'skull'] },
+ { slot: BoneSlot.Neck, any: ['neck'] },
+ { slot: BoneSlot.Spine, all: ['upper', 'chest'] },
+ { slot: BoneSlot.Spine, any: ['spine', 'chest', 'torso', 'abdomen', 'ribcage', 'waist'] },
+ { slot: BoneSlot.Pelvis, any: ['pelvis', 'hips'] },
+ { slot: BoneSlot.Pelvis, any: ['hip'], forbid_side: true },
+
+ // --- Non-humanoid chains
+ { slot: BoneSlot.Tail, any: ['tail'] },
+ { slot: BoneSlot.Wing, any: ['wing', 'feather', 'pinion'] },
+
+ // --- Bare fallbacks, lowest priority. Mixamo names the upper arm "LeftArm" and
+ // the calf "LeftLeg"; the hierarchy pass corrects rigs that mean otherwise.
+ { slot: BoneSlot.UpperArm, any: ['arm'] },
+ { slot: BoneSlot.Calf, any: ['leg'] }
+]
+
+/** Slots whose length varies a lot between rigs and should be paired proportionally */
+const PROPORTIONAL_CHAIN_SLOTS = new Set<BoneSlot>([
+ BoneSlot.Spine,
+ BoneSlot.Tail,
+ BoneSlot.Wing
+])
+
+/** Legacy BoneCategory for each slot, so the existing category field stays meaningful */
+const SLOT_CATEGORY: Record<BoneSlot, BoneCategory> = {
+ [BoneSlot.Pelvis]: BoneCategory.Torso,
+ [BoneSlot.Spine]: BoneCategory.Torso,
+ [BoneSlot.Neck]: BoneCategory.Torso,
+ [BoneSlot.Head]: BoneCategory.Torso,
+ [BoneSlot.Clavicle]: BoneCategory.Arms,
+ [BoneSlot.UpperArm]: BoneCategory.Arms,
+ [BoneSlot.LowerArm]: BoneCategory.Arms,
+ [BoneSlot.Hand]: BoneCategory.Arms,
+ [BoneSlot.Thigh]: BoneCategory.Legs,
+ [BoneSlot.Calf]: BoneCategory.Legs,
+ [BoneSlot.Foot]: BoneCategory.Legs,
+ [BoneSlot.Ball]: BoneCategory.Legs,
+ [BoneSlot.FingerThumb]: BoneCategory.Hands,
+ [BoneSlot.FingerIndex]: BoneCategory.Hands,
+ [BoneSlot.FingerMiddle]: BoneCategory.Hands,
+ [BoneSlot.FingerRing]: BoneCategory.Hands,
+ [BoneSlot.FingerPinky]: BoneCategory.Hands,
+ [BoneSlot.Tail]: BoneCategory.Tail,
+ [BoneSlot.Wing]: BoneCategory.Wings,
+ [BoneSlot.Unknown]: BoneCategory.Unknown
+}
+
+/**
+ * Resolve a parsed bone name to a canonical slot.
+ * @param parsed - output of parse_bone_name()
+ * @param effective_side - the bone's side after hierarchy inheritance, which can be
+ * more informative than the side in its own name
+ */
+export function resolve_slot (parsed: ParsedBoneName, effective_side: BoneSide): BoneSlot {
+ const tokens = new Set(parsed.tokens)
+
+ // a single rejected token disqualifies the whole bone
+ for (const token of tokens) {
+ if (REJECTED_TOKENS.has(token)) {
+ return BoneSlot.Unknown
+ }
+ }
+
+ const has_side: boolean = effective_side === BoneSide.Left || effective_side === BoneSide.Right
+
+ for (const rule of SLOT_RULES) {
+ if (rule.require_side === true && !has_side) continue
+ if (rule.forbid_side === true && has_side) continue
+ if (rule.all !== undefined && !rule.all.every(token => tokens.has(token))) continue
+ if (rule.any !== undefined && !rule.any.some(token => tokens.has(token))) continue
+
+ return rule.slot
+ }
+
+ return BoneSlot.Unknown
+}
+
+export function slot_to_category (slot: BoneSlot): BoneCategory {
+ return SLOT_CATEGORY[slot]
+}
+
+export function is_proportional_chain_slot (slot: BoneSlot): boolean {
+ return PROPORTIONAL_CHAIN_SLOTS.has(slot)
+}
+
+export function is_finger_slot (slot: BoneSlot): boolean {
+ return slot === BoneSlot.FingerThumb || slot === BoneSlot.FingerIndex ||
+ slot === BoneSlot.FingerMiddle || slot === BoneSlot.FingerRing ||
+ slot === BoneSlot.FingerPinky
+}
+
+/**
+ * Slots the arm/leg hierarchy pass is allowed to overwrite. Anything outside this
+ * set was named unambiguously enough that we trust the name over the walk.
+ */
+export function is_arm_ambiguous_slot (slot: BoneSlot): boolean {
+ return slot === BoneSlot.Unknown || slot === BoneSlot.Clavicle ||
+ slot === BoneSlot.UpperArm || slot === BoneSlot.LowerArm
+}
+
+export function is_leg_ambiguous_slot (slot: BoneSlot): boolean {
+ return slot === BoneSlot.Unknown || slot === BoneSlot.Thigh || slot === BoneSlot.Calf
+}
diff --git a/src/retarget/bone-automap/BoneTypes.ts b/src/retarget/bone-automap/BoneTypes.ts
new file mode 100644
index 0000000..174ffc3
--- /dev/null
+++ b/src/retarget/bone-automap/BoneTypes.ts
@@ -0,0 +1,78 @@
+/**
+ * Shared types for the bone auto-mapping system.
+ *
+ * These live in their own module (rather than in BoneAutoMapper) so the
+ * tokenizer / vocabulary / resolver modules can use them without creating an
+ * import cycle back through BoneAutoMapper. BoneAutoMapper re-exports all three
+ * so existing `import { BoneSide } from './BoneAutoMapper'` call sites keep working.
+ */
+
+/**
+ * Bone categories for grouping bones by anatomical area
+ */
+export enum BoneCategory {
+ Torso = 'torso',
+ Arms = 'arms',
+ Hands = 'hands',
+ Legs = 'legs',
+ Wings = 'wings',
+ Tail = 'tail',
+ Unknown = 'unknown'
+}
+
+/**
+ * Side of the body a bone belongs to.
+ * Unknown means "the name carried no side information" - which is different from
+ * Center ("this bone is deliberately on the midline"). Side inheritance in
+ * BoneChainResolver only fills in Unknown, never overwrites Center.
+ */
+export enum BoneSide {
+ Left = 'left',
+ Right = 'right',
+ Center = 'center',
+ Unknown = 'unknown'
+}
+
+/**
+ * Canonical humanoid joint slots. Every bone - source or target - is resolved to
+ * one of these, and mapping is then a lookup on (slot, side, ordinal) rather than
+ * a comparison of two rig-specific bone names.
+ */
+export enum BoneSlot {
+ Pelvis = 'pelvis',
+ Spine = 'spine',
+ Neck = 'neck',
+ Head = 'head',
+ Clavicle = 'clavicle',
+ UpperArm = 'upperarm',
+ LowerArm = 'lowerarm',
+ Hand = 'hand',
+ Thigh = 'thigh',
+ Calf = 'calf',
+ Foot = 'foot',
+ Ball = 'ball',
+ FingerThumb = 'finger.thumb',
+ FingerIndex = 'finger.index',
+ FingerMiddle = 'finger.middle',
+ FingerRing = 'finger.ring',
+ FingerPinky = 'finger.pinky',
+ Tail = 'tail',
+ Wing = 'wing',
+ Unknown = 'unknown'
+}
+
+/**
+ * Metadata extracted from a bone name plus its place in the skeleton hierarchy
+ */
+export interface BoneMetadata {
+ name: string // Original bone name
+ normalized_name: string // Normalized version for matching
+ side: BoneSide // Which side of the body
+ category: BoneCategory // Anatomical category
+ parent_name: string | null // Name of parent bone, null if this bone has no bone parent
+ depth: number // Distance from the root bone (root = 0)
+ children_names: string[] // Names of direct child bones
+ slot: BoneSlot // Resolved canonical joint slot
+ slot_ordinal: number // 1-based position within its (slot, side) chain; 0 until resolved
+ is_leaf_name: boolean // Name carried an end/tip/leaf/nub marker
+}
diff --git a/src/retarget/bone-automap/CanonicalSlotMapper.ts b/src/retarget/bone-automap/CanonicalSlotMapper.ts
new file mode 100644
index 0000000..df8de2b
--- /dev/null
+++ b/src/retarget/bone-automap/CanonicalSlotMapper.ts
@@ -0,0 +1,115 @@
+import { type BoneMetadata, BoneSlot } from './BoneTypes'
+import { is_proportional_chain_slot } from './BoneSlotVocabulary'
+
+/**
+ * CanonicalSlotMapper - matches two skeletons by canonical joint slot rather than
+ * by bone name.
+ *
+ * Once BoneChainResolver has reduced every bone to (slot, side, ordinal), mapping
+ * is a join on that key. Chains of unequal length - a 4-bone spine against
+ * Mesh2Motion's 3, or a 3-segment finger against its 4 - are paired instead of
+ * dropped, which is what stops an entire torso going unmapped over an off-by-one.
+ */
+export class CanonicalSlotMapper {
+ /**
+ * @param source_bones - Mesh2Motion skeleton metadata
+ * @param target_bones - uploaded skeleton metadata
+ * @param existing_mappings - mappings already made; bones used on either side are
+ * left out of the chain pairing entirely, so a chain of
+ * three with one bone already spoken for is paired as a
+ * chain of two rather than being double-assigned
+ * @returns Map of target bone name -> source bone name, including the existing ones
+ */
+ static map_bones (
+ source_bones: BoneMetadata[],
+ target_bones: BoneMetadata[],
+ existing_mappings: Map<string, string> = new Map()
+ ): Map<string, string> {
+ const mappings = new Map<string, string>(existing_mappings)
+ const used_source_names = new Set<string>(mappings.values())
+
+ const source_groups = CanonicalSlotMapper.group_by_slot(
+ source_bones.filter(bone => !used_source_names.has(bone.name))
+ )
+ const target_groups = CanonicalSlotMapper.group_by_slot(
+ target_bones.filter(bone => !mappings.has(bone.name))
+ )
+
+ for (const [group_key, target_group] of target_groups) {
+ const source_group: BoneMetadata[] | undefined = source_groups.get(group_key)
+ if (source_group === undefined || source_group.length === 0) continue
+
+ const pairs: Array<[number, number]> = CanonicalSlotMapper.pair_chains(
+ source_group.length, target_group.length, target_group[0].slot
+ )
+
+ for (const [source_index, target_index] of pairs) {
+ mappings.set(target_group[target_index].name, source_group[source_index].name)
+ }
+ }
+
+ return mappings
+ }
+
+ /**
+ * Bucket bones by "slot|side" and order each bucket from the root outward.
+ * Unknown slots are dropped - an unrecognised, twist or IK bone is left unmapped
+ * on purpose rather than guessed at.
+ */
+ private static group_by_slot (bones: BoneMetadata[]): Map<string, BoneMetadata[]> {
+ const groups = new Map<string, BoneMetadata[]>()
+
+ for (const bone of bones) {
+ if (bone.slot === BoneSlot.Unknown) continue
+ const key = `${bone.slot}|${bone.side}`
+ const group: BoneMetadata[] = groups.get(key) ?? []
+ group.push(bone)
+ groups.set(key, group)
+ }
+
+ for (const group of groups.values()) {
+ group.sort((a, b) => a.slot_ordinal - b.slot_ordinal)
+ }
+
+ return groups
+ }
+
+ /**
+ * Decide which source chain link drives which target chain link.
+ * Returns [source_index, target_index] pairs, each index used at most once.
+ *
+ * Spine/tail/wing chains are spread evenly, because a 5-segment tail driven by a
+ * 3-segment one should bend along its whole length. Limbs and fingers align from
+ * the root instead: the first knuckle is the first knuckle regardless of how many
+ * segments follow it, and any extra tip segments are simply left unmapped.
+ */
+ private static pair_chains (
+ source_count: number, target_count: number, slot: BoneSlot
+ ): Array<[number, number]> {
+ const pair_count: number = Math.min(source_count, target_count)
+ const pairs: Array<[number, number]> = []
+
+ if (pair_count === 0) return pairs
+
+ if (pair_count === 1) {
+ return [[0, 0]]
+ }
+
+ if (is_proportional_chain_slot(slot)) {
+ for (let k = 0; k < pair_count; k++) {
+ const ratio: number = k / (pair_count - 1)
+ pairs.push([
+ Math.round(ratio * (source_count - 1)),
+ Math.round(ratio * (target_count - 1))
+ ])
+ }
+ return pairs
+ }
+
+ for (let k = 0; k < pair_count; k++) {
+ pairs.push([k, k])
+ }
+
+ return pairs
+ }
+}
diff --git a/src/retarget/bone-automap/MixamoMapper.ts b/src/retarget/bone-automap/MixamoMapper.ts
index ef895c6..3c10c61 100644
--- a/src/retarget/bone-automap/MixamoMapper.ts
+++ b/src/retarget/bone-automap/MixamoMapper.ts
@@ -1,9 +1,10 @@
-import { type BoneMetadata } from './BoneAutoMapper'
+import { type BoneMetadata } from './BoneTypes'
+import { normalized_lookup_key } from './BoneNameTokenizer'
/**
* MixamoMapper - Direct bone name mapping for Mixamo rigs
* Source: Mesh2Motion skeleton (hardcoded names)
- * Target: Mixamo skeleton (mixamorig: prefix)
+ * Target: Mixamo skeleton (usually, but not always, carrying a mixamorig prefix)
*/
export class MixamoMapper {
/**
@@ -107,12 +108,42 @@ export class MixamoMapper {
}
/**
- * Check if the given skeleton is a Mixamo skeleton
- * @param bones - Bones to check
- * @returns True if any bone name contains "mixamorig"
+ * The distinctive core of the Mixamo skeleton. Fingers are left out on purpose -
+ * plenty of exports strip them - and so is anything whose name a non-Mixamo rig
+ * might plausibly share.
+ */
+ private static readonly CORE_BONES: string[] = [
+ 'mixamorigHips', 'mixamorigSpine', 'mixamorigNeck', 'mixamorigHead',
+ 'mixamorigLeftShoulder', 'mixamorigLeftArm', 'mixamorigLeftForeArm', 'mixamorigLeftHand',
+ 'mixamorigRightShoulder', 'mixamorigRightArm', 'mixamorigRightForeArm', 'mixamorigRightHand',
+ 'mixamorigLeftUpLeg', 'mixamorigLeftLeg', 'mixamorigLeftFoot',
+ 'mixamorigRightUpLeg', 'mixamorigRightLeg', 'mixamorigRightFoot'
+ ]
+
+ /** Fraction of CORE_BONES a rig must carry before we treat it as Mixamo */
+ private static readonly CORE_MATCH_THRESHOLD: number = 0.8
+
+ /**
+ * Check if the given skeleton is a Mixamo skeleton.
+ *
+ * The "mixamorig" prefix is definitive when present, but several FBX -> glTF
+ * pipelines strip it, leaving bones named plain "Hips" / "LeftForeArm" /
+ * "LeftHandIndex1". Those are still Mixamo rigs and should still get the exact
+ * table, so fall back to scoring the distinctive core names.
+ *
+ * @param bone_names - target skeleton bone names
*/
static is_target_valid_skeleton (bone_names: string[]): boolean {
- return bone_names.some(name => name.toLowerCase().includes('mixamorig'))
+ if (bone_names.some(name => name.toLowerCase().includes('mixamorig'))) {
+ return true
+ }
+
+ const target_keys = new Set<string>(bone_names.map(name => normalized_lookup_key(name)))
+ const matched: number = this.CORE_BONES.filter(
+ core_name => target_keys.has(normalized_lookup_key(core_name))
+ ).length
+
+ return matched / this.CORE_BONES.length >= this.CORE_MATCH_THRESHOLD
}
/**
@@ -131,20 +162,26 @@ export class MixamoMapper {
static map_mixamo_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
const mappings = new Map<string, string>()
- // console.log('=== MIXAMO DIRECT MAPPING ===')
+ // Look targets up by loose key rather than exact name, so a rig whose export
+ // dropped the "mixamorig" prefix or the colon after it still resolves
+ const target_by_loose_key = new Map<string, BoneMetadata>()
+ for (const target_bone of target_bones) {
+ const key: string = normalized_lookup_key(target_bone.name)
+ if (!target_by_loose_key.has(key)) {
+ target_by_loose_key.set(key, target_bone)
+ }
+ }
// For each source bone (Mesh2Motion), find matching target bone (Mixamo)
for (const source_bone of source_bones) {
const expected_mixamo_name: string | undefined = this.BONE_MAP[source_bone.name]
+ if (expected_mixamo_name === undefined) continue
- if (expected_mixamo_name !== undefined) {
- // Find target bone with this Mixamo name
- const target_bone: BoneMetadata | undefined = target_bones.find(tb => tb.name === expected_mixamo_name)
+ const target_bone: BoneMetadata | undefined =
+ target_by_loose_key.get(normalized_lookup_key(expected_mixamo_name))
- if (target_bone !== undefined) {
- mappings.set(target_bone.name, source_bone.name)
- // console.log(`Mapped: ${target_bone.name} -> ${source_bone.name}`)
- }
+ if (target_bone !== undefined) {
+ mappings.set(target_bone.name, source_bone.name)
}
}
diff --git a/src/retarget/bone-automap/RigifyMapper.ts b/src/retarget/bone-automap/RigifyMapper.ts
index ecd29a4..f1717e3 100644
--- a/src/retarget/bone-automap/RigifyMapper.ts
+++ b/src/retarget/bone-automap/RigifyMapper.ts
@@ -1,4 +1,5 @@
-import { type BoneMetadata } from './BoneAutoMapper'
+import { type BoneMetadata } from './BoneTypes'
+import { normalized_lookup_key } from './BoneNameTokenizer'
/**
* RigifyMapper - Direct bone name mapping for Blender Rigify rigs
@@ -84,10 +85,13 @@ export class RigifyMapper {
* Normalize a Rigify bone name for tolerant matching.
* Different exporters strip or keep dots/underscores (e.g. Blender's GLTF exporter
* turns "DEF-spine.001" into "DEF-spine001", "DEF-upper_arm.L" into "DEF-upper_armL").
- * Lowercase + strip dots/underscores/hyphens so all variants compare equal.
+ *
+ * Delegates to the shared tokenizer so there is one normalizer in this folder
+ * rather than three: it also strips the DEF-/ORG- prefix and drops leading zeros,
+ * so "DEF-thumb.01.L" and "DEF-thumb1L" both come out as "thumb1l".
*/
private static loose_key (name: string): string {
- return name.toLowerCase().replace(/[._\-]/g, '')
+ return normalized_lookup_key(name)
}
static map_rigify_bones (source_bones: BoneMetadata[], target_bones: BoneMetadata[]): Map<string, string> {
diff --git a/src/retarget/bone-automap/rig-fixtures.ts b/src/retarget/bone-automap/rig-fixtures.ts
new file mode 100644
index 0000000..f9e8cf6
--- /dev/null
+++ b/src/retarget/bone-automap/rig-fixtures.ts
@@ -0,0 +1,166 @@
+import { type RawBoneRecord } from './BoneChainResolver'
+
+/**
+ * Skeleton fixtures for the auto-mapping tests.
+ *
+ * Each builder returns a flat (bone, parent) list - the same shape
+ * BoneAutoMapper extracts from a three.js armature - so the mapping pipeline can
+ * be exercised end to end without loading a model.
+ */
+
+const ARMATURE = 'Armature'
+
+class RigBuilder {
+ readonly bones: RawBoneRecord[] = []
+
+ add (name: string, parent_name: string): this {
+ this.bones.push({ name, parent_name })
+ return this
+ }
+
+ /** Add a parent-to-child chain, returning the last bone's name */
+ chain (parent: string, names: string[]): string {
+ let current: string = parent
+ for (const name of names) {
+ this.add(name, current)
+ current = name
+ }
+ return current
+ }
+}
+
+/** The Mesh2Motion human rig - always the source side of a mapping */
+export function mesh2motion_rig (): RawBoneRecord[] {
+ const rig = new RigBuilder()
+
+ rig.add('pelvis', ARMATURE)
+ rig.chain('pelvis', ['spine_01', 'spine_02', 'spine_03'])
+ rig.chain('spine_03', ['neck_01', 'head', 'head_leaf'])
+
+ for (const side of ['l', 'r']) {
+ const hand: string = rig.chain('spine_03',
+ [`clavicle_${side}`, `upperarm_${side}`, `lowerarm_${side}`, `hand_${side}`])
+
+ for (const finger of ['thumb', 'index', 'middle', 'ring', 'pinky']) {
+ rig.chain(hand, [
+ `${finger}_01_${side}`, `${finger}_02_${side}`, `${finger}_03_${side}`, `${finger}_04_leaf_${side}`
+ ])
+ }
+
+ rig.chain('pelvis',
+ [`thigh_${side}`, `calf_${side}`, `foot_${side}`, `ball_${side}`, `ball_leaf_${side}`])
+ }
+
+ return rig.bones
+}
+
+/**
+ * A Mixamo rig. Pass '' for the prefix to get the stripped-name variant that some
+ * FBX -> glTF pipelines produce ("Hips", "LeftForeArm", "LeftHandIndex1").
+ */
+export function mixamo_rig (prefix: string = 'mixamorig'): RawBoneRecord[] {
+ const rig = new RigBuilder()
+ const p = (name: string): string => prefix + name
+
+ rig.add(p('Hips'), ARMATURE)
+ rig.chain(p('Hips'), [p('Spine'), p('Spine1'), p('Spine2')])
+ rig.chain(p('Spine2'), [p('Neck'), p('Head'), p('HeadTop_End')])
+
+ for (const side of ['Left', 'Right']) {
+ const hand: string = rig.chain(p('Spine2'),
+ [p(`${side}Shoulder`), p(`${side}Arm`), p(`${side}ForeArm`), p(`${side}Hand`)])
+
+ for (const finger of ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky']) {
+ rig.chain(hand, [1, 2, 3, 4].map(i => p(`${side}Hand${finger}${i}`)))
+ }
+
+ rig.chain(p('Hips'), [
+ p(`${side}UpLeg`), p(`${side}Leg`), p(`${side}Foot`), p(`${side}ToeBase`), p(`${side}Toe_End`)
+ ])
+ }
+
+ return rig.bones
+}
+
+/**
+ * Unreal Engine mannequin. Shares Mesh2Motion's naming for the main joints but adds
+ * twist bones, which must be rejected rather than mapped onto real joints.
+ */
+export function unreal_rig (): RawBoneRecord[] {
+ const rig = new RigBuilder()
+
+ rig.add('root', ARMATURE)
+ rig.add('pelvis', 'root')
+ rig.chain('pelvis', ['spine_01', 'spine_02', 'spine_03'])
+ rig.chain('spine_03', ['neck_01', 'head'])
+
+ for (const side of ['l', 'r']) {
+ rig.chain('spine_03', [`clavicle_${side}`, `upperarm_${side}`])
+ rig.add(`upperarm_twist_01_${side}`, `upperarm_${side}`)
+ rig.add(`lowerarm_${side}`, `upperarm_${side}`)
+ rig.add(`lowerarm_twist_01_${side}`, `lowerarm_${side}`)
+ rig.add(`hand_${side}`, `lowerarm_${side}`)
+
+ for (const finger of ['thumb', 'index', 'middle', 'ring', 'pinky']) {
+ rig.chain(`hand_${side}`,
+ [`${finger}_01_${side}`, `${finger}_02_${side}`, `${finger}_03_${side}`])
+ }
+
+ rig.chain('pelvis', [`thigh_${side}`, `calf_${side}`, `foot_${side}`, `ball_${side}`])
+ rig.add(`thigh_twist_01_${side}`, `thigh_${side}`)
+ rig.add(`calf_twist_01_${side}`, `calf_${side}`)
+ }
+
+ return rig.bones
+}
+
+/**
+ * DAZ / Poser style naming. The interesting part is that "lShldr" is the upper arm
+ * here, the exact opposite of Mixamo's "LeftShoulder" being the clavicle.
+ */
+export function daz_rig (): RawBoneRecord[] {
+ const rig = new RigBuilder()
+
+ rig.add('hip', ARMATURE)
+ rig.chain('hip', ['abdomen', 'chest'])
+ rig.chain('chest', ['neck', 'head'])
+
+ for (const side of ['l', 'r']) {
+ const hand: string = rig.chain('chest',
+ [`${side}Collar`, `${side}Shldr`, `${side}ForeArm`, `${side}Hand`])
+
+ for (const finger of ['Thumb', 'Index', 'Mid', 'Ring', 'Pinky']) {
+ rig.chain(hand, [1, 2, 3].map(i => `${side}${finger}${i}`))
+ }
+
+ rig.chain('hip', [`${side}Thigh`, `${side}Shin`, `${side}Foot`, `${side}Toe`])
+ }
+
+ return rig.bones
+}
+
+/** VRM humanoid naming, including its proximal/intermediate/distal finger segments */
+export function vrm_rig (): RawBoneRecord[] {
+ const rig = new RigBuilder()
+
+ rig.add('hips', ARMATURE)
+ rig.chain('hips', ['spine', 'chest', 'upperChest'])
+ rig.chain('upperChest', ['neck', 'head'])
+
+ for (const side of ['left', 'right']) {
+ const hand: string = rig.chain('upperChest',
+ [`${side}Shoulder`, `${side}UpperArm`, `${side}LowerArm`, `${side}Hand`])
+
+ for (const finger of ['Thumb', 'Index', 'Middle', 'Ring', 'Little']) {
+ rig.chain(hand, ['Proximal', 'Intermediate', 'Distal'].map(seg => `${side}${finger}${seg}`))
+ }
+
+ rig.chain('hips', [`${side}UpperLeg`, `${side}LowerLeg`, `${side}Foot`, `${side}Toes`])
+ }
+
+ return rig.bones
+}
+
+export function bone_names (bones: RawBoneRecord[]): string[] {
+ return bones.map(b => b.name)
+}