Skip to main content

vrm_runtime/
humanoid.rs

1use std::collections::HashMap;
2use vrm_spec::vrmc_vrm_1_0::{HumanBoneName, Humanoid as SpecHumanoid};
3
4use crate::NodeId;
5
6/// The standard humanoid bone set of a VRM avatar.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum HumanBone {
9    // Torso
10    /// The pelvis and root of the humanoid skeleton.
11    Hips,
12    /// The lower spine.
13    Spine,
14    /// The chest above the spine.
15    Chest,
16    /// The optional upper chest above the chest.
17    UpperChest,
18    /// The neck below the head.
19    Neck,
20    // Head
21    /// The head.
22    Head,
23    /// The left eye.
24    LeftEye,
25    /// The right eye.
26    RightEye,
27    /// The jaw.
28    Jaw,
29    // Leg
30    /// The left thigh.
31    LeftUpperLeg,
32    /// The left lower leg.
33    LeftLowerLeg,
34    /// The left foot.
35    LeftFoot,
36    /// The left toes.
37    LeftToes,
38    /// The right thigh.
39    RightUpperLeg,
40    /// The right lower leg.
41    RightLowerLeg,
42    /// The right foot.
43    RightFoot,
44    /// The right toes.
45    RightToes,
46    // Arm
47    /// The left shoulder.
48    LeftShoulder,
49    /// The left upper arm.
50    LeftUpperArm,
51    /// The left lower arm.
52    LeftLowerArm,
53    /// The left hand.
54    LeftHand,
55    /// The right shoulder.
56    RightShoulder,
57    /// The right upper arm.
58    RightUpperArm,
59    /// The right lower arm.
60    RightLowerArm,
61    /// The right hand.
62    RightHand,
63
64    // Finger
65    /// The left thumb metacarpal.
66    LeftThumbMetacarpal,
67    /// The left thumb proximal phalanx.
68    LeftThumbProximal,
69    /// The left thumb distal phalanx.
70    LeftThumbDistal,
71    /// The left index proximal phalanx.
72    LeftIndexProximal,
73    /// The left index intermediate phalanx.
74    LeftIndexIntermediate,
75    /// The left index distal phalanx.
76    LeftIndexDistal,
77    /// The left middle proximal phalanx.
78    LeftMiddleProximal,
79    /// The left middle intermediate phalanx.
80    LeftMiddleIntermediate,
81    /// The left middle distal phalanx.
82    LeftMiddleDistal,
83    /// The left ring proximal phalanx.
84    LeftRingProximal,
85    /// The left ring intermediate phalanx.
86    LeftRingIntermediate,
87    /// The left ring distal phalanx.
88    LeftRingDistal,
89    /// The left little-finger proximal phalanx.
90    LeftLittleProximal,
91    /// The left little-finger intermediate phalanx.
92    LeftLittleIntermediate,
93    /// The left little-finger distal phalanx.
94    LeftLittleDistal,
95    /// The right thumb metacarpal.
96    RightThumbMetacarpal,
97    /// The right thumb proximal phalanx.
98    RightThumbProximal,
99    /// The right thumb distal phalanx.
100    RightThumbDistal,
101    /// The right index proximal phalanx.
102    RightIndexProximal,
103    /// The right index intermediate phalanx.
104    RightIndexIntermediate,
105    /// The right index distal phalanx.
106    RightIndexDistal,
107    /// The right middle proximal phalanx.
108    RightMiddleProximal,
109    /// The right middle intermediate phalanx.
110    RightMiddleIntermediate,
111    /// The right middle distal phalanx.
112    RightMiddleDistal,
113    /// The right ring proximal phalanx.
114    RightRingProximal,
115    /// The right ring intermediate phalanx.
116    RightRingIntermediate,
117    /// The right ring distal phalanx.
118    RightRingDistal,
119    /// The right little-finger proximal phalanx.
120    RightLittleProximal,
121    /// The right little-finger intermediate phalanx.
122    RightLittleIntermediate,
123    /// The right little-finger distal phalanx.
124    RightLittleDistal,
125}
126
127impl HumanBone {
128    /// Returns the canonical humanoid parent from the VRM 1.0 bone hierarchy.
129    pub(crate) const fn parent(self) -> Option<Self> {
130        use HumanBone::*;
131
132        Some(match self {
133            Hips => return None,
134            Spine => Hips,
135            Chest => Spine,
136            UpperChest => Chest,
137            Neck => UpperChest,
138            Head => Neck,
139            LeftEye | RightEye | Jaw => Head,
140            LeftUpperLeg => Hips,
141            LeftLowerLeg => LeftUpperLeg,
142            LeftFoot => LeftLowerLeg,
143            LeftToes => LeftFoot,
144            RightUpperLeg => Hips,
145            RightLowerLeg => RightUpperLeg,
146            RightFoot => RightLowerLeg,
147            RightToes => RightFoot,
148            LeftShoulder => UpperChest,
149            LeftUpperArm => LeftShoulder,
150            LeftLowerArm => LeftUpperArm,
151            LeftHand => LeftLowerArm,
152            RightShoulder => UpperChest,
153            RightUpperArm => RightShoulder,
154            RightLowerArm => RightUpperArm,
155            RightHand => RightLowerArm,
156            LeftThumbMetacarpal | LeftIndexProximal | LeftMiddleProximal | LeftRingProximal
157            | LeftLittleProximal => LeftHand,
158            LeftThumbProximal => LeftThumbMetacarpal,
159            LeftThumbDistal => LeftThumbProximal,
160            LeftIndexIntermediate => LeftIndexProximal,
161            LeftIndexDistal => LeftIndexIntermediate,
162            LeftMiddleIntermediate => LeftMiddleProximal,
163            LeftMiddleDistal => LeftMiddleIntermediate,
164            LeftRingIntermediate => LeftRingProximal,
165            LeftRingDistal => LeftRingIntermediate,
166            LeftLittleIntermediate => LeftLittleProximal,
167            LeftLittleDistal => LeftLittleIntermediate,
168            RightThumbMetacarpal | RightIndexProximal | RightMiddleProximal | RightRingProximal
169            | RightLittleProximal => RightHand,
170            RightThumbProximal => RightThumbMetacarpal,
171            RightThumbDistal => RightThumbProximal,
172            RightIndexIntermediate => RightIndexProximal,
173            RightIndexDistal => RightIndexIntermediate,
174            RightMiddleIntermediate => RightMiddleProximal,
175            RightMiddleDistal => RightMiddleIntermediate,
176            RightRingIntermediate => RightRingProximal,
177            RightRingDistal => RightRingIntermediate,
178            RightLittleIntermediate => RightLittleProximal,
179            RightLittleDistal => RightLittleIntermediate,
180        })
181    }
182
183    /// Reports whether the VRM 1.0 table marks the parent bone as mandatory.
184    pub(crate) const fn requires_direct_parent(self) -> bool {
185        use HumanBone::*;
186
187        matches!(
188            self,
189            UpperChest
190                | LeftThumbProximal
191                | LeftThumbDistal
192                | LeftIndexIntermediate
193                | LeftIndexDistal
194                | LeftMiddleIntermediate
195                | LeftMiddleDistal
196                | LeftRingIntermediate
197                | LeftRingDistal
198                | LeftLittleIntermediate
199                | LeftLittleDistal
200                | RightThumbProximal
201                | RightThumbDistal
202                | RightIndexIntermediate
203                | RightIndexDistal
204                | RightMiddleIntermediate
205                | RightMiddleDistal
206                | RightRingIntermediate
207                | RightRingDistal
208                | RightLittleIntermediate
209                | RightLittleDistal
210        )
211    }
212
213    /// Returns the lower-camel-case identifier used by the VRM schemas.
214    pub(crate) const fn spec_name(self) -> &'static str {
215        use HumanBone::*;
216
217        match self {
218            Hips => "hips",
219            Spine => "spine",
220            Chest => "chest",
221            UpperChest => "upperChest",
222            Neck => "neck",
223            Head => "head",
224            LeftEye => "leftEye",
225            RightEye => "rightEye",
226            Jaw => "jaw",
227            LeftUpperLeg => "leftUpperLeg",
228            LeftLowerLeg => "leftLowerLeg",
229            LeftFoot => "leftFoot",
230            LeftToes => "leftToes",
231            RightUpperLeg => "rightUpperLeg",
232            RightLowerLeg => "rightLowerLeg",
233            RightFoot => "rightFoot",
234            RightToes => "rightToes",
235            LeftShoulder => "leftShoulder",
236            LeftUpperArm => "leftUpperArm",
237            LeftLowerArm => "leftLowerArm",
238            LeftHand => "leftHand",
239            RightShoulder => "rightShoulder",
240            RightUpperArm => "rightUpperArm",
241            RightLowerArm => "rightLowerArm",
242            RightHand => "rightHand",
243            LeftThumbMetacarpal => "leftThumbMetacarpal",
244            LeftThumbProximal => "leftThumbProximal",
245            LeftThumbDistal => "leftThumbDistal",
246            LeftIndexProximal => "leftIndexProximal",
247            LeftIndexIntermediate => "leftIndexIntermediate",
248            LeftIndexDistal => "leftIndexDistal",
249            LeftMiddleProximal => "leftMiddleProximal",
250            LeftMiddleIntermediate => "leftMiddleIntermediate",
251            LeftMiddleDistal => "leftMiddleDistal",
252            LeftRingProximal => "leftRingProximal",
253            LeftRingIntermediate => "leftRingIntermediate",
254            LeftRingDistal => "leftRingDistal",
255            LeftLittleProximal => "leftLittleProximal",
256            LeftLittleIntermediate => "leftLittleIntermediate",
257            LeftLittleDistal => "leftLittleDistal",
258            RightThumbMetacarpal => "rightThumbMetacarpal",
259            RightThumbProximal => "rightThumbProximal",
260            RightThumbDistal => "rightThumbDistal",
261            RightIndexProximal => "rightIndexProximal",
262            RightIndexIntermediate => "rightIndexIntermediate",
263            RightIndexDistal => "rightIndexDistal",
264            RightMiddleProximal => "rightMiddleProximal",
265            RightMiddleIntermediate => "rightMiddleIntermediate",
266            RightMiddleDistal => "rightMiddleDistal",
267            RightRingProximal => "rightRingProximal",
268            RightRingIntermediate => "rightRingIntermediate",
269            RightRingDistal => "rightRingDistal",
270            RightLittleProximal => "rightLittleProximal",
271            RightLittleIntermediate => "rightLittleIntermediate",
272            RightLittleDistal => "rightLittleDistal",
273        }
274    }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub(crate) enum HumanoidHierarchyViolation {
279    MissingRequiredParent {
280        bone: HumanBone,
281        required_parent: HumanBone,
282    },
283    InvalidParent {
284        bone: HumanBone,
285        expected_parent: Option<HumanBone>,
286        actual_parent: Option<HumanBone>,
287    },
288}
289
290impl HumanoidHierarchyViolation {
291    pub(crate) const fn bone(self) -> HumanBone {
292        match self {
293            Self::MissingRequiredParent { bone, .. } | Self::InvalidParent { bone, .. } => bone,
294        }
295    }
296
297    pub(crate) fn message(self) -> String {
298        match self {
299            Self::MissingRequiredParent {
300                bone,
301                required_parent,
302            } => format!(
303                "humanoid bone `{}` requires parent bone `{}`",
304                bone.spec_name(),
305                required_parent.spec_name()
306            ),
307            Self::InvalidParent {
308                bone,
309                expected_parent: Some(expected_parent),
310                actual_parent,
311            } => {
312                let found = actual_parent
313                    .map(|parent| format!("`{}`", parent.spec_name()))
314                    .unwrap_or_else(|| "no mapped humanoid ancestor".to_string());
315                format!(
316                    "humanoid bone `{}` must be a descendant of `{}` with that bone as its nearest mapped humanoid ancestor; found {found}",
317                    bone.spec_name(),
318                    expected_parent.spec_name()
319                )
320            }
321            Self::InvalidParent {
322                bone,
323                expected_parent: None,
324                actual_parent,
325            } => {
326                let found = actual_parent
327                    .map(|parent| format!("`{}`", parent.spec_name()))
328                    .unwrap_or_else(|| "an unknown bone".to_string());
329                format!(
330                    "humanoid root bone `{}` must not have mapped humanoid ancestor {found}",
331                    bone.spec_name()
332                )
333            }
334        }
335    }
336}
337
338/// Validates both mandatory optional-bone prerequisites and the nearest
339/// humanoid ancestor. Non-humanoid nodes may still occur between two bones.
340pub(crate) fn hierarchy_violations(
341    bones: impl IntoIterator<Item = (HumanBone, usize)>,
342    node_parents: &[Option<usize>],
343) -> Vec<HumanoidHierarchyViolation> {
344    let bone_nodes = bones.into_iter().collect::<HashMap<_, _>>();
345    let node_bones = bone_nodes
346        .iter()
347        .map(|(&bone, &node)| (node, bone))
348        .collect::<HashMap<_, _>>();
349    let mut violations = Vec::new();
350
351    for &bone in Humanoid::ALL_BONES {
352        let Some(&node) = bone_nodes.get(&bone) else {
353            continue;
354        };
355
356        let direct_parent = bone.parent();
357        if bone.requires_direct_parent()
358            && let Some(required_parent) = direct_parent
359            && !bone_nodes.contains_key(&required_parent)
360        {
361            violations.push(HumanoidHierarchyViolation::MissingRequiredParent {
362                bone,
363                required_parent,
364            });
365        }
366
367        let mut expected_parent = direct_parent;
368        while let Some(parent) = expected_parent {
369            if bone_nodes.contains_key(&parent) {
370                break;
371            }
372            expected_parent = parent.parent();
373        }
374
375        let mut cursor = node_parents.get(node).copied().flatten();
376        let mut actual_parent = None;
377        for _ in 0..node_parents.len() {
378            let Some(node) = cursor else {
379                break;
380            };
381            if let Some(&parent_bone) = node_bones.get(&node) {
382                actual_parent = Some(parent_bone);
383                break;
384            }
385            cursor = node_parents.get(node).copied().flatten();
386        }
387
388        if actual_parent != expected_parent {
389            violations.push(HumanoidHierarchyViolation::InvalidParent {
390                bone,
391                expected_parent,
392                actual_parent,
393            });
394        }
395    }
396
397    violations
398}
399
400impl From<HumanBoneName> for HumanBone {
401    fn from(name: HumanBoneName) -> Self {
402        match name {
403            HumanBoneName::Hips => Self::Hips,
404            HumanBoneName::Spine => Self::Spine,
405            HumanBoneName::Chest => Self::Chest,
406            HumanBoneName::UpperChest => Self::UpperChest,
407            HumanBoneName::Neck => Self::Neck,
408            HumanBoneName::Head => Self::Head,
409            HumanBoneName::LeftEye => Self::LeftEye,
410            HumanBoneName::RightEye => Self::RightEye,
411            HumanBoneName::Jaw => Self::Jaw,
412            HumanBoneName::LeftUpperLeg => Self::LeftUpperLeg,
413            HumanBoneName::LeftLowerLeg => Self::LeftLowerLeg,
414            HumanBoneName::LeftFoot => Self::LeftFoot,
415            HumanBoneName::LeftToes => Self::LeftToes,
416            HumanBoneName::RightUpperLeg => Self::RightUpperLeg,
417            HumanBoneName::RightLowerLeg => Self::RightLowerLeg,
418            HumanBoneName::RightFoot => Self::RightFoot,
419            HumanBoneName::RightToes => Self::RightToes,
420            HumanBoneName::LeftShoulder => Self::LeftShoulder,
421            HumanBoneName::LeftUpperArm => Self::LeftUpperArm,
422            HumanBoneName::LeftLowerArm => Self::LeftLowerArm,
423            HumanBoneName::LeftHand => Self::LeftHand,
424            HumanBoneName::RightShoulder => Self::RightShoulder,
425            HumanBoneName::RightUpperArm => Self::RightUpperArm,
426            HumanBoneName::RightLowerArm => Self::RightLowerArm,
427            HumanBoneName::RightHand => Self::RightHand,
428            HumanBoneName::LeftThumbMetacarpal => Self::LeftThumbMetacarpal,
429            HumanBoneName::LeftThumbProximal => Self::LeftThumbProximal,
430            HumanBoneName::LeftThumbDistal => Self::LeftThumbDistal,
431            HumanBoneName::LeftIndexProximal => Self::LeftIndexProximal,
432            HumanBoneName::LeftIndexIntermediate => Self::LeftIndexIntermediate,
433            HumanBoneName::LeftIndexDistal => Self::LeftIndexDistal,
434            HumanBoneName::LeftMiddleProximal => Self::LeftMiddleProximal,
435            HumanBoneName::LeftMiddleIntermediate => Self::LeftMiddleIntermediate,
436            HumanBoneName::LeftMiddleDistal => Self::LeftMiddleDistal,
437            HumanBoneName::LeftRingProximal => Self::LeftRingProximal,
438            HumanBoneName::LeftRingIntermediate => Self::LeftRingIntermediate,
439            HumanBoneName::LeftRingDistal => Self::LeftRingDistal,
440            HumanBoneName::LeftLittleProximal => Self::LeftLittleProximal,
441            HumanBoneName::LeftLittleIntermediate => Self::LeftLittleIntermediate,
442            HumanBoneName::LeftLittleDistal => Self::LeftLittleDistal,
443            HumanBoneName::RightThumbMetacarpal => Self::RightThumbMetacarpal,
444            HumanBoneName::RightThumbProximal => Self::RightThumbProximal,
445            HumanBoneName::RightThumbDistal => Self::RightThumbDistal,
446            HumanBoneName::RightIndexProximal => Self::RightIndexProximal,
447            HumanBoneName::RightIndexIntermediate => Self::RightIndexIntermediate,
448            HumanBoneName::RightIndexDistal => Self::RightIndexDistal,
449            HumanBoneName::RightMiddleProximal => Self::RightMiddleProximal,
450            HumanBoneName::RightMiddleIntermediate => Self::RightMiddleIntermediate,
451            HumanBoneName::RightMiddleDistal => Self::RightMiddleDistal,
452            HumanBoneName::RightRingProximal => Self::RightRingProximal,
453            HumanBoneName::RightRingIntermediate => Self::RightRingIntermediate,
454            HumanBoneName::RightRingDistal => Self::RightRingDistal,
455            HumanBoneName::RightLittleProximal => Self::RightLittleProximal,
456            HumanBoneName::RightLittleIntermediate => Self::RightLittleIntermediate,
457            HumanBoneName::RightLittleDistal => Self::RightLittleDistal,
458        }
459    }
460}
461
462/// The glTF node index that a [`HumanBone`] maps to.
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub struct HumanBoneNode(pub u32);
465
466/// The humanoid skeleton: the mapping from each [`HumanBone`] to a node.
467#[derive(Debug, Clone, Default)]
468pub struct Humanoid {
469    bones: HashMap<HumanBone, HumanBoneNode>,
470}
471
472impl Humanoid {
473    /// The full set of humanoid bones a VRM avatar can define.
474    pub const ALL_BONES: &[HumanBone] = &[
475        HumanBone::Hips,
476        HumanBone::Spine,
477        HumanBone::Chest,
478        HumanBone::UpperChest,
479        HumanBone::Neck,
480        HumanBone::Head,
481        HumanBone::LeftEye,
482        HumanBone::RightEye,
483        HumanBone::Jaw,
484        HumanBone::LeftUpperLeg,
485        HumanBone::LeftLowerLeg,
486        HumanBone::LeftFoot,
487        HumanBone::LeftToes,
488        HumanBone::RightUpperLeg,
489        HumanBone::RightLowerLeg,
490        HumanBone::RightFoot,
491        HumanBone::RightToes,
492        HumanBone::LeftShoulder,
493        HumanBone::LeftUpperArm,
494        HumanBone::LeftLowerArm,
495        HumanBone::LeftHand,
496        HumanBone::RightShoulder,
497        HumanBone::RightUpperArm,
498        HumanBone::RightLowerArm,
499        HumanBone::RightHand,
500        HumanBone::LeftThumbMetacarpal,
501        HumanBone::LeftThumbProximal,
502        HumanBone::LeftThumbDistal,
503        HumanBone::LeftIndexProximal,
504        HumanBone::LeftIndexIntermediate,
505        HumanBone::LeftIndexDistal,
506        HumanBone::LeftMiddleProximal,
507        HumanBone::LeftMiddleIntermediate,
508        HumanBone::LeftMiddleDistal,
509        HumanBone::LeftRingProximal,
510        HumanBone::LeftRingIntermediate,
511        HumanBone::LeftRingDistal,
512        HumanBone::LeftLittleProximal,
513        HumanBone::LeftLittleIntermediate,
514        HumanBone::LeftLittleDistal,
515        HumanBone::RightThumbMetacarpal,
516        HumanBone::RightThumbProximal,
517        HumanBone::RightThumbDistal,
518        HumanBone::RightIndexProximal,
519        HumanBone::RightIndexIntermediate,
520        HumanBone::RightIndexDistal,
521        HumanBone::RightMiddleProximal,
522        HumanBone::RightMiddleIntermediate,
523        HumanBone::RightMiddleDistal,
524        HumanBone::RightRingProximal,
525        HumanBone::RightRingIntermediate,
526        HumanBone::RightRingDistal,
527        HumanBone::RightLittleProximal,
528        HumanBone::RightLittleIntermediate,
529        HumanBone::RightLittleDistal,
530    ];
531
532    /// Returns the node index assigned to `bone`, if any.
533    pub fn bone(&self, bone: HumanBone) -> Option<&HumanBoneNode> {
534        self.bones.get(&bone)
535    }
536
537    /// Returns the type-safe asset node assigned to `bone`.
538    pub fn bone_id(&self, bone: HumanBone) -> Option<NodeId> {
539        self.bone(bone)
540            .map(|node| NodeId::from_index(node.0 as usize))
541    }
542
543    /// Iterates over every mapped bone and its raw glTF node index.
544    pub fn bones(&self) -> impl Iterator<Item = (&HumanBone, &HumanBoneNode)> {
545        self.bones.iter()
546    }
547
548    /// Iterates over mapped bones using type-safe node identifiers.
549    pub fn bone_ids(&self) -> impl Iterator<Item = (HumanBone, NodeId)> + '_ {
550        self.bones
551            .iter()
552            .map(|(&bone, node)| (bone, NodeId::from_index(node.0 as usize)))
553    }
554
555    /// Builder method that maps a [`HumanBone`] to a glTF node index.
556    pub fn with_bone(mut self, bone: HumanBone, node_index: u32) -> Self {
557        self.bones.insert(bone, HumanBoneNode(node_index));
558        self
559    }
560
561    pub(crate) fn load_humanoid(schema: &SpecHumanoid) -> Self {
562        let mut bones = HashMap::new();
563
564        for (bone_name, bone_spec) in &schema.human_bones.0 {
565            let Some(node) = bone_spec.as_ref().and_then(|spec| spec.node.as_ref()) else {
566                continue;
567            };
568            let human_bone = HumanBone::from(*bone_name);
569            let node_index = node.value() as u32;
570            bones.insert(human_bone, HumanBoneNode(node_index));
571        }
572
573        Self { bones }
574    }
575}