Skip to main content

vrm_runtime/
animation.rs

1use crate::HumanBone;
2use crate::diagnostic::{Diagnostic, LoadOptions, ValidationMode};
3use glam::{Mat4, Quat, Vec3, Vec4};
4use std::collections::{HashMap, HashSet, VecDeque};
5use std::path::{Path, PathBuf};
6use vrm_spec::vrmc_vrm_1_0::{ExpressionPresetName, HumanBoneName};
7use vrm_spec::vrmc_vrm_animation_1_0::{VRMC_VRM_ANIMATION, VRMCVrmAnimationSchema};
8
9// No glTF KHR extension currently changes the animation channels or rest-pose
10// data interpreted by this loader.
11const SUPPORTED_VRMA_EXTENSIONS: &[&str] = &[VRMC_VRM_ANIMATION];
12
13/// The interpolation algorithm attached to a glTF animation sampler.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum Interpolation {
16    /// Interpolate linearly, using spherical interpolation for quaternions.
17    #[default]
18    Linear,
19    /// Hold the preceding sample until the following keyframe is reached.
20    Step,
21    /// Evaluate the glTF Hermite spline using its stored derivatives.
22    CubicSpline,
23}
24
25impl From<gltf::animation::Interpolation> for Interpolation {
26    fn from(value: gltf::animation::Interpolation) -> Self {
27        match value {
28            gltf::animation::Interpolation::Linear => Self::Linear,
29            gltf::animation::Interpolation::Step => Self::Step,
30            gltf::animation::Interpolation::CubicSpline => Self::CubicSpline,
31        }
32    }
33}
34
35/// One typed animation sample and, for cubic splines, its derivatives.
36#[derive(Debug, Clone, Copy, PartialEq)]
37pub struct Keyframe<T> {
38    time: f32,
39    value: T,
40    in_tangent: Option<T>,
41    out_tangent: Option<T>,
42}
43
44impl<T: Copy> Keyframe<T> {
45    /// Creates a keyframe for a STEP or LINEAR track.
46    pub const fn new(time: f32, value: T) -> Self {
47        Self {
48            time,
49            value,
50            in_tangent: None,
51            out_tangent: None,
52        }
53    }
54
55    /// Creates a CUBICSPLINE keyframe.
56    pub const fn cubic(time: f32, value: T, in_tangent: T, out_tangent: T) -> Self {
57        Self {
58            time,
59            value,
60            in_tangent: Some(in_tangent),
61            out_tangent: Some(out_tangent),
62        }
63    }
64
65    /// Returns the keyframe timestamp in seconds.
66    pub const fn time(&self) -> f32 {
67        self.time
68    }
69
70    /// Returns the sampled value stored at this keyframe.
71    pub const fn value(&self) -> T {
72        self.value
73    }
74
75    /// Returns the incoming derivative for a CUBICSPLINE keyframe.
76    pub const fn in_tangent(&self) -> Option<T> {
77        self.in_tangent
78    }
79
80    /// Returns the outgoing derivative for a CUBICSPLINE keyframe.
81    pub const fn out_tangent(&self) -> Option<T> {
82        self.out_tangent
83    }
84}
85
86/// Operations required to evaluate a typed animation track.
87pub trait TrackValue: Copy {
88    /// Interpolates between two values for a LINEAR sampler.
89    fn linear(self, other: Self, amount: f32) -> Self;
90
91    /// Evaluates a Hermite segment. Tangents are derivatives and are scaled by
92    /// the segment duration as required by glTF.
93    fn cubic(
94        start: Self,
95        start_tangent: Self,
96        end: Self,
97        end_tangent: Self,
98        amount: f32,
99        duration: f32,
100    ) -> Self;
101
102    /// Reports whether a value contains only finite components.
103    fn is_finite(self) -> bool;
104
105    /// Reports whether a sampled value is valid. Quaternion values additionally
106    /// reject zero length, while tangents only need to be finite.
107    fn is_valid_value(self) -> bool {
108        self.is_finite()
109    }
110
111    /// Normalizes values that require a canonical sampled representation.
112    fn normalized(self) -> Self {
113        self
114    }
115}
116
117impl TrackValue for f32 {
118    fn linear(self, other: Self, amount: f32) -> Self {
119        self + (other - self) * amount
120    }
121
122    fn cubic(
123        start: Self,
124        start_tangent: Self,
125        end: Self,
126        end_tangent: Self,
127        amount: f32,
128        duration: f32,
129    ) -> Self {
130        hermite(start, start_tangent, end, end_tangent, amount, duration)
131    }
132
133    fn is_finite(self) -> bool {
134        f32::is_finite(self)
135    }
136}
137
138impl TrackValue for Vec3 {
139    fn linear(self, other: Self, amount: f32) -> Self {
140        self.lerp(other, amount)
141    }
142
143    fn cubic(
144        start: Self,
145        start_tangent: Self,
146        end: Self,
147        end_tangent: Self,
148        amount: f32,
149        duration: f32,
150    ) -> Self {
151        let t2 = amount * amount;
152        let t3 = t2 * amount;
153        let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
154        let h10 = t3 - 2.0 * t2 + amount;
155        let h01 = -2.0 * t3 + 3.0 * t2;
156        let h11 = t3 - t2;
157        start * h00 + start_tangent * (duration * h10) + end * h01 + end_tangent * (duration * h11)
158    }
159
160    fn is_finite(self) -> bool {
161        Vec3::is_finite(self)
162    }
163}
164
165impl TrackValue for Quat {
166    fn linear(self, other: Self, amount: f32) -> Self {
167        self.normalize().slerp(other.normalize(), amount)
168    }
169
170    fn cubic(
171        start: Self,
172        start_tangent: Self,
173        end: Self,
174        end_tangent: Self,
175        amount: f32,
176        duration: f32,
177    ) -> Self {
178        let start = Vec4::from_array(start.to_array());
179        let start_tangent = Vec4::from_array(start_tangent.to_array());
180        let end = Vec4::from_array(end.to_array());
181        let end_tangent = Vec4::from_array(end_tangent.to_array());
182        let t2 = amount * amount;
183        let t3 = t2 * amount;
184        let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
185        let h10 = t3 - 2.0 * t2 + amount;
186        let h01 = -2.0 * t3 + 3.0 * t2;
187        let h11 = t3 - t2;
188        let value = start * h00
189            + start_tangent * (duration * h10)
190            + end * h01
191            + end_tangent * (duration * h11);
192        let value = Quat::from_array(value.to_array());
193        normalize_quaternion(value).unwrap_or_else(|| {
194            // Opposite quaternion representations can cancel to exactly zero
195            // under component-wise Hermite interpolation. Both endpoints
196            // still describe valid rotations, so the nearer endpoint is a
197            // deterministic finite fallback for that singular sample.
198            let endpoint = if amount <= 0.5 {
199                Quat::from_array(start.to_array())
200            } else {
201                Quat::from_array(end.to_array())
202            };
203            normalize_quaternion(endpoint).unwrap_or(Quat::IDENTITY)
204        })
205    }
206
207    fn is_finite(self) -> bool {
208        Quat::is_finite(self)
209    }
210
211    fn is_valid_value(self) -> bool {
212        self.is_finite() && self.length_squared() > f32::EPSILON
213    }
214
215    fn normalized(self) -> Self {
216        normalize_quaternion(self).unwrap_or(Quat::IDENTITY)
217    }
218}
219
220fn normalize_quaternion(value: Quat) -> Option<Quat> {
221    let length_squared = value.length_squared();
222    if value.is_finite() && length_squared > f32::EPSILON {
223        Some(value / length_squared.sqrt())
224    } else {
225        None
226    }
227}
228
229/// A typed, independently interpolated animation channel.
230#[derive(Debug, Clone, PartialEq)]
231pub struct Track<T> {
232    interpolation: Interpolation,
233    keyframes: Vec<Keyframe<T>>,
234}
235
236impl<T> Track<T> {
237    /// Creates a typed channel with its interpolation and keyframes.
238    ///
239    /// Keyframes are checked when the containing clip is passed to
240    /// [`AvatarRuntime::play`](crate::AvatarRuntime::play).
241    pub fn new(interpolation: Interpolation, keyframes: Vec<Keyframe<T>>) -> Self {
242        Self {
243            interpolation,
244            keyframes,
245        }
246    }
247
248    /// Returns the interpolation algorithm used by this track.
249    pub const fn interpolation(&self) -> Interpolation {
250        self.interpolation
251    }
252
253    /// Returns all keyframes in timestamp order.
254    pub fn keyframes(&self) -> &[Keyframe<T>] {
255        &self.keyframes
256    }
257
258    /// Returns the number of keyframes in this track.
259    pub fn len(&self) -> usize {
260        self.keyframes.len()
261    }
262
263    /// Reports whether this track has no keyframes.
264    pub fn is_empty(&self) -> bool {
265        self.keyframes.is_empty()
266    }
267}
268
269impl<T: TrackValue> Track<T> {
270    /// Samples the track and clamps time to its first and last keyframes.
271    pub fn sample(&self, time: f32) -> Option<T> {
272        let (left, right, amount) = track_segment(&self.keyframes, time)?;
273        let start = self.keyframes[left];
274        if left == right {
275            return Some(start.value.normalized());
276        }
277        let end = self.keyframes[right];
278        Some(match self.interpolation {
279            Interpolation::Step => start.value.normalized(),
280            Interpolation::Linear => start.value.linear(end.value, amount),
281            Interpolation::CubicSpline => T::cubic(
282                start.value,
283                start.out_tangent?,
284                end.value,
285                end.in_tangent?,
286                amount,
287                end.time - start.time,
288            ),
289        })
290    }
291
292    fn validate(&self, label: &str, duration: f32) -> Result<(), String> {
293        if self.keyframes.is_empty() {
294            return Err(format!("{label} must contain at least one keyframe"));
295        }
296        if self.keyframes.iter().any(|keyframe| {
297            !keyframe.time.is_finite() || keyframe.time < 0.0 || keyframe.time > duration
298        }) {
299            return Err(format!("{label} contains a time outside the clip duration"));
300        }
301        if self
302            .keyframes
303            .windows(2)
304            .any(|pair| pair[0].time >= pair[1].time)
305        {
306            return Err(format!(
307                "{label} keyframe times must be strictly increasing"
308            ));
309        }
310        if self
311            .keyframes
312            .iter()
313            .any(|keyframe| !keyframe.value.is_valid_value())
314        {
315            return Err(format!("{label} contains an invalid value"));
316        }
317        if self.interpolation == Interpolation::CubicSpline {
318            if self.keyframes.len() < 2 {
319                return Err(format!(
320                    "{label} CUBICSPLINE requires at least two keyframes"
321                ));
322            }
323            if self.keyframes.iter().any(|keyframe| {
324                keyframe.in_tangent.is_none_or(|value| !value.is_finite())
325                    || keyframe.out_tangent.is_none_or(|value| !value.is_finite())
326            }) {
327                return Err(format!("{label} contains an invalid CUBICSPLINE tangent"));
328            }
329        }
330        Ok(())
331    }
332}
333
334fn hermite(
335    start: f32,
336    start_tangent: f32,
337    end: f32,
338    end_tangent: f32,
339    amount: f32,
340    duration: f32,
341) -> f32 {
342    let t2 = amount * amount;
343    let t3 = t2 * amount;
344    let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
345    let h10 = t3 - 2.0 * t2 + amount;
346    let h01 = -2.0 * t3 + 3.0 * t2;
347    let h11 = t3 - t2;
348    start * h00 + start_tangent * duration * h10 + end * h01 + end_tangent * duration * h11
349}
350
351fn track_segment<T>(keyframes: &[Keyframe<T>], time: f32) -> Option<(usize, usize, f32)> {
352    if !time.is_finite() {
353        return None;
354    }
355    let first = keyframes.first()?;
356    let last_index = keyframes.len() - 1;
357    if time <= first.time {
358        return Some((0, 0, 0.0));
359    }
360    if time >= keyframes[last_index].time {
361        return Some((last_index, last_index, 0.0));
362    }
363    let right = keyframes.partition_point(|keyframe| keyframe.time < time);
364    if keyframes[right].time == time {
365        return Some((right, right, 0.0));
366    }
367    let left = right - 1;
368    let span = keyframes[right].time - keyframes[left].time;
369    Some((left, right, (time - keyframes[left].time) / span))
370}
371
372/// Rotation and optional Hips translation channels for one humanoid bone.
373#[derive(Debug, Clone, Default, PartialEq)]
374pub struct BoneTrack {
375    rotation: Option<Track<Quat>>,
376    translation: Option<Track<Vec3>>,
377}
378
379impl BoneTrack {
380    /// Creates an empty bone track.
381    pub const fn new() -> Self {
382        Self {
383            rotation: None,
384            translation: None,
385        }
386    }
387
388    /// Adds or replaces the rotation channel.
389    pub fn with_rotation(mut self, rotation: Track<Quat>) -> Self {
390        self.rotation = Some(rotation);
391        self
392    }
393
394    /// Adds or replaces the translation channel.
395    ///
396    /// Clip validation permits translation only when this track is assigned
397    /// to [`HumanBone::Hips`].
398    pub fn with_translation(mut self, translation: Track<Vec3>) -> Self {
399        self.translation = Some(translation);
400        self
401    }
402
403    /// Returns the rotation channel, if present.
404    pub fn rotation(&self) -> Option<&Track<Quat>> {
405        self.rotation.as_ref()
406    }
407
408    /// Returns the translation channel, if present.
409    pub fn translation(&self) -> Option<&Track<Vec3>> {
410        self.translation.as_ref()
411    }
412}
413
414/// Rest-pose information retained from a VRMA source for pose retargeting.
415#[derive(Debug, Clone, Copy, PartialEq)]
416pub struct SourceBoneRestPose {
417    local_rotation: Quat,
418    world_rotation: Quat,
419    world_translation: Vec3,
420}
421
422impl SourceBoneRestPose {
423    /// Returns the source bone's local rest rotation.
424    pub const fn local_rotation(&self) -> Quat {
425        self.local_rotation
426    }
427
428    /// Returns the source bone's world rest rotation.
429    pub const fn world_rotation(&self) -> Quat {
430        self.world_rotation
431    }
432
433    /// Returns the source bone's world rest translation.
434    pub const fn world_translation(&self) -> Vec3 {
435        self.world_translation
436    }
437}
438
439/// A playable VRM humanoid animation.
440///
441/// Programmatic clips store target-local rotation deltas. Clips loaded from
442/// `.vrma` additionally retain the source rest pose needed for retargeting.
443#[doc(alias = "VRMA")]
444#[derive(Debug, Clone, Default)]
445pub struct VrmAnimation {
446    duration: f32,
447    bone_tracks: HashMap<HumanBone, BoneTrack>,
448    expression_tracks: HashMap<String, Track<f32>>,
449    look_at_rotation_track: Option<Track<Quat>>,
450    source_rest_pose: HashMap<HumanBone, SourceBoneRestPose>,
451    look_at_offset_from_head_bone: Option<Vec3>,
452}
453
454/// A loaded animation plus recoverable diagnostics.
455#[derive(Debug, Clone)]
456pub struct AnimationLoadOutcome {
457    /// The validated animation, including any permissive recoveries.
458    pub animation: VrmAnimation,
459    /// Machine-readable warnings produced while loading in permissive mode.
460    pub diagnostics: Vec<Diagnostic>,
461}
462
463/// Errors raised while loading a `VRMC_vrm_animation` document.
464#[derive(Debug, thiserror::Error)]
465pub enum AnimationLoadError {
466    /// Reading the animation file or an external buffer failed.
467    #[error("failed to read `{path}`: {source}")]
468    Io {
469        /// Path that could not be read.
470        path: PathBuf,
471        /// Underlying file-system error.
472        #[source]
473        source: std::io::Error,
474    },
475    /// The glTF container or core document is malformed.
476    #[error("glTF parse error: {0}")]
477    Gltf(#[from] gltf::Error),
478    /// The required top-level `VRMC_vrm_animation` extension is absent.
479    #[error("VRMC_vrm_animation extension missing")]
480    MissingExtension,
481    /// The `VRMC_vrm_animation` payload could not be decoded.
482    #[error("invalid VRMC_vrm_animation extension: {0}")]
483    InvalidExtension(#[from] serde_json::Error),
484    /// Animation channels or humanoid metadata violate the VRMA profile.
485    #[error("invalid VRM animation: {0}")]
486    InvalidAnimation(String),
487    /// The document requires an extension unsupported by the VRMA loader.
488    #[error("required extension `{0}` is not supported by the VRMA loader")]
489    UnsupportedRequiredExtension(String),
490}
491
492impl VrmAnimation {
493    /// Creates an empty programmatic clip with the given duration in seconds.
494    ///
495    /// Tracks may be inserted before validation. [`AvatarRuntime::play`](crate::AvatarRuntime::play)
496    /// validates the complete clip before it becomes active.
497    pub fn new(duration: f32) -> Self {
498        Self {
499            duration,
500            bone_tracks: HashMap::new(),
501            expression_tracks: HashMap::new(),
502            look_at_rotation_track: None,
503            source_rest_pose: HashMap::new(),
504            look_at_offset_from_head_bone: None,
505        }
506    }
507
508    /// Returns the clip duration in seconds.
509    pub const fn duration(&self) -> f32 {
510        self.duration
511    }
512
513    /// Adds or replaces a humanoid bone track.
514    pub fn with_bone_track(mut self, bone: HumanBone, track: BoneTrack) -> Self {
515        self.insert_bone_track(bone, track);
516        self
517    }
518
519    /// Inserts a humanoid bone track and returns the previous value, if any.
520    pub fn insert_bone_track(&mut self, bone: HumanBone, track: BoneTrack) -> Option<BoneTrack> {
521        self.bone_tracks.insert(bone, track)
522    }
523
524    /// Adds or replaces an expression weight track.
525    pub fn with_expression_track(mut self, name: impl Into<String>, track: Track<f32>) -> Self {
526        self.insert_expression_track(name, track);
527        self
528    }
529
530    /// Inserts an expression weight track and returns the previous value, if any.
531    pub fn insert_expression_track(
532        &mut self,
533        name: impl Into<String>,
534        track: Track<f32>,
535    ) -> Option<Track<f32>> {
536        self.expression_tracks.insert(name.into(), track)
537    }
538
539    /// Adds or replaces the LookAt rotation track.
540    pub fn with_look_at_rotation_track(mut self, track: Track<Quat>) -> Self {
541        self.look_at_rotation_track = Some(track);
542        self
543    }
544
545    /// Replaces the LookAt rotation track and returns the previous value, if any.
546    pub fn set_look_at_rotation_track(&mut self, track: Track<Quat>) -> Option<Track<Quat>> {
547        self.look_at_rotation_track.replace(track)
548    }
549
550    /// Loads the first animation from a VRMA file using strict validation.
551    ///
552    /// Relative external buffers are resolved against the file's parent
553    /// directory. Use [`Self::load_with_options`] to collect diagnostics from
554    /// permissive validation.
555    ///
556    /// # Errors
557    ///
558    /// Returns [`AnimationLoadError`] when the file cannot be read, its glTF or
559    /// `VRMC_vrm_animation` data is invalid, or it requires an unsupported
560    /// extension.
561    ///
562    /// # Examples
563    ///
564    /// ```no_run
565    /// use vrm_runtime::VrmAnimation;
566    ///
567    /// let animation = VrmAnimation::load("motion.vrma")?;
568    /// println!("duration: {} seconds", animation.duration());
569    /// # Ok::<(), vrm_runtime::AnimationLoadError>(())
570    /// ```
571    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, AnimationLoadError> {
572        Self::from_file(path)
573    }
574
575    /// Loads a VRMA file using strict validation.
576    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, AnimationLoadError> {
577        Ok(Self::from_file_with_options(path, LoadOptions::default())?.animation)
578    }
579
580    /// Parses a GLB/VRMA byte slice using strict validation.
581    pub fn from_bytes(bytes: &[u8]) -> Result<Self, AnimationLoadError> {
582        Ok(Self::from_bytes_with_options(bytes, LoadOptions::default())?.animation)
583    }
584
585    /// Loads a VRMA file and returns recoverable diagnostics.
586    pub fn load_with_options<P: AsRef<Path>>(
587        path: P,
588        options: LoadOptions,
589    ) -> Result<AnimationLoadOutcome, AnimationLoadError> {
590        Self::from_file_with_options(path, options)
591    }
592
593    /// Loads a VRMA file and returns recoverable diagnostics.
594    pub fn from_file_with_options<P: AsRef<Path>>(
595        path: P,
596        options: LoadOptions,
597    ) -> Result<AnimationLoadOutcome, AnimationLoadError> {
598        let path = path.as_ref();
599        let file = std::fs::File::open(path).map_err(|source| AnimationLoadError::Io {
600            path: path.to_path_buf(),
601            source,
602        })?;
603        let gltf = gltf::Gltf::from_reader_without_validation(std::io::BufReader::new(file))?;
604        validate_gltf_document(&gltf.document)?;
605        let base = path.parent();
606        let buffers = gltf::import_buffers(&gltf.document, base, gltf.blob)?;
607        load_document(&gltf.document, &buffers, options)
608    }
609
610    /// Parses a GLB/VRMA byte slice and returns recoverable diagnostics.
611    pub fn from_bytes_with_options(
612        bytes: &[u8],
613        options: LoadOptions,
614    ) -> Result<AnimationLoadOutcome, AnimationLoadError> {
615        let gltf = gltf::Gltf::from_slice_without_validation(bytes)?;
616        validate_gltf_document(&gltf.document)?;
617        let buffers = gltf::import_buffers(&gltf.document, None, gltf.blob)?;
618        load_document(&gltf.document, &buffers, options)
619    }
620
621    /// Returns the channels assigned to a humanoid bone.
622    pub fn bone_track(&self, bone: HumanBone) -> Option<&BoneTrack> {
623        self.bone_tracks.get(&bone)
624    }
625
626    /// Iterates over bones that have at least one animation channel.
627    pub fn bone_tracks(&self) -> impl Iterator<Item = (HumanBone, &BoneTrack)> {
628        self.bone_tracks.iter().map(|(&bone, track)| (bone, track))
629    }
630
631    /// Returns an expression weight track.
632    pub fn expression_track(&self, name: &str) -> Option<&Track<f32>> {
633        self.expression_tracks.get(name)
634    }
635
636    /// Iterates over all expression weight tracks.
637    pub fn expression_tracks(&self) -> impl Iterator<Item = (&str, &Track<f32>)> {
638        self.expression_tracks
639            .iter()
640            .map(|(name, track)| (name.as_str(), track))
641    }
642
643    /// Returns the LookAt rotation track, if present.
644    pub fn look_at_rotation_track(&self) -> Option<&Track<Quat>> {
645        self.look_at_rotation_track.as_ref()
646    }
647
648    /// Returns the source animation's LookAt origin offset.
649    pub fn look_at_offset_from_head_bone(&self) -> Option<Vec3> {
650        self.look_at_offset_from_head_bone
651    }
652
653    /// Returns source T-pose information required for humanoid retargeting.
654    pub fn source_bone_rest_pose(&self, bone: HumanBone) -> Option<SourceBoneRestPose> {
655        self.source_rest_pose.get(&bone).copied()
656    }
657
658    pub(crate) fn has_source_rest_pose(&self) -> bool {
659        !self.source_rest_pose.is_empty()
660    }
661
662    /// Returns the source Hips height used to scale locomotion across avatars.
663    pub fn source_hips_height(&self) -> Option<f32> {
664        self.source_bone_rest_pose(HumanBone::Hips)
665            .map(|pose| pose.world_translation.y)
666    }
667
668    /// Validates keyframe ordering and all numeric values before playback.
669    pub fn validate(&self) -> Result<(), String> {
670        if !self.duration.is_finite() || self.duration < 0.0 {
671            return Err("duration must be finite and non-negative".to_string());
672        }
673
674        for (bone, track) in &self.bone_tracks {
675            if track.rotation.is_none() && track.translation.is_none() {
676                return Err(format!(
677                    "bone track {bone:?} must contain a rotation or translation channel"
678                ));
679            }
680            if let Some(rotation) = &track.rotation {
681                rotation.validate(&format!("bone rotation track {bone:?}"), self.duration)?;
682            }
683            if let Some(translation) = &track.translation {
684                if *bone != HumanBone::Hips {
685                    return Err(format!(
686                        "bone translation track {bone:?} is not allowed; only Hips may translate"
687                    ));
688                }
689                translation.validate(&format!("bone translation track {bone:?}"), self.duration)?;
690            }
691        }
692        for (name, track) in &self.expression_tracks {
693            if name.is_empty() {
694                return Err("expression track names must not be empty".to_string());
695            }
696            track.validate(&format!("expression track `{name}`"), self.duration)?;
697            if track
698                .keyframes
699                .iter()
700                .any(|keyframe| !(0.0..=1.0).contains(&keyframe.value))
701            {
702                return Err(format!(
703                    "expression track `{name}` contains a weight outside 0..=1"
704                ));
705            }
706        }
707        if let Some(track) = &self.look_at_rotation_track {
708            track.validate("LookAt rotation track", self.duration)?;
709        }
710        if self.source_rest_pose.values().any(|pose| {
711            !pose.local_rotation.is_finite()
712                || !pose.world_rotation.is_finite()
713                || !pose.world_translation.is_finite()
714        }) {
715            return Err("source rest pose contains a non-finite transform".to_string());
716        }
717        if self
718            .look_at_offset_from_head_bone
719            .is_some_and(|offset| !offset.is_finite())
720        {
721            return Err("LookAt offset contains a non-finite value".to_string());
722        }
723
724        Ok(())
725    }
726
727    /// Samples the LookAt rotation while preserving its glTF interpolation.
728    pub fn sample_look_at_rotation(&self, time: f32) -> Option<Quat> {
729        self.look_at_rotation_track
730            .as_ref()?
731            .sample(time)
732            .map(Quat::normalize)
733    }
734
735    /// Samples a target-local rotation delta from a programmatic clip.
736    ///
737    /// This returns `None` for loaded VRMA tracks because their rotations are
738    /// source-local poses that must be retargeted.
739    pub fn sample_programmatic_bone_rotation_delta(
740        &self,
741        bone: HumanBone,
742        time: f32,
743    ) -> Option<Quat> {
744        if self.source_rest_pose.contains_key(&bone) {
745            return None;
746        }
747        self.bone_track(bone)?
748            .rotation()?
749            .sample(time)
750            .map(Quat::normalize)
751    }
752
753    /// Samples the raw local-space rotation stored by a loaded VRMA source.
754    ///
755    /// This returns `None` for programmatic clips, whose rotations already
756    /// represent target-local deltas.
757    pub fn sample_source_bone_rotation(&self, bone: HumanBone, time: f32) -> Option<Quat> {
758        self.source_rest_pose.get(&bone)?;
759        self.bone_track(bone)?
760            .rotation()?
761            .sample(time)
762            .map(Quat::normalize)
763    }
764
765    /// Samples a loaded VRMA source rotation in normalized humanoid space.
766    pub fn sample_normalized_source_bone_rotation(
767        &self,
768        bone: HumanBone,
769        time: f32,
770    ) -> Option<Quat> {
771        let rotation = self.sample_source_bone_rotation(bone, time)?;
772        let rest = self.source_bone_rest_pose(bone)?;
773        Some(
774            (rest.world_rotation
775                * rest.local_rotation.inverse()
776                * rotation
777                * rest.world_rotation.inverse())
778            .normalize(),
779        )
780    }
781
782    /// Converts a normalized source pose into the delta expected by a target
783    /// avatar whose world rest rotation is supplied by the caller.
784    pub fn sample_retargeted_source_bone_rotation(
785        &self,
786        bone: HumanBone,
787        time: f32,
788        target_world_rest_rotation: Quat,
789    ) -> Option<Quat> {
790        let normalized = self.sample_normalized_source_bone_rotation(bone, time)?;
791        Some(
792            (target_world_rest_rotation.inverse() * normalized * target_world_rest_rotation)
793                .normalize(),
794        )
795    }
796
797    /// Samples the Hips translation delta while preserving its interpolation.
798    pub fn sample_bone_translation_delta(&self, bone: HumanBone, time: f32) -> Option<Vec3> {
799        self.bone_track(bone)?.translation()?.sample(time)
800    }
801
802    /// Samples an expression weight and clamps it to the VRM range.
803    pub fn sample_expression_weight(&self, name: &str, time: f32) -> f32 {
804        let Some(track) = self.expression_tracks.get(name) else {
805            return 0.0;
806        };
807        track.sample(time).unwrap_or(0.0).clamp(0.0, 1.0)
808    }
809}
810
811fn load_document(
812    document: &gltf::Document,
813    buffers: &[gltf::buffer::Data],
814    options: LoadOptions,
815) -> Result<AnimationLoadOutcome, AnimationLoadError> {
816    for required in document.extensions_required() {
817        if !SUPPORTED_VRMA_EXTENSIONS.contains(&required) {
818            return Err(AnimationLoadError::UnsupportedRequiredExtension(
819                required.to_string(),
820            ));
821        }
822    }
823
824    let extension_value = document
825        .extension_value(VRMC_VRM_ANIMATION)
826        .ok_or(AnimationLoadError::MissingExtension)?;
827    let schema: VRMCVrmAnimationSchema = serde_json::from_value(extension_value.clone())?;
828    let mut diagnostics = Vec::new();
829    if options.validation == ValidationMode::Permissive {
830        let required_extensions = document.extensions_required().collect::<HashSet<_>>();
831        for extension in document.extensions_used() {
832            if !SUPPORTED_VRMA_EXTENSIONS.contains(&extension)
833                && !required_extensions.contains(extension)
834            {
835                diagnostics.push(Diagnostic::warning(
836                    "VRMA_UNSUPPORTED_OPTIONAL_EXTENSION",
837                    "/extensionsUsed",
838                    format!(
839                        "optional extension `{extension}` is not interpreted by the VRMA loader"
840                    ),
841                ));
842            }
843        }
844    }
845    let mappings = validate_schema(document, &schema, options.validation, &mut diagnostics)?;
846
847    let mut animations = document.animations();
848    let animation = animations.next().ok_or_else(|| {
849        AnimationLoadError::InvalidAnimation(
850            "VRMA document must contain at least one glTF animation".to_string(),
851        )
852    })?;
853    if animations.next().is_some() {
854        diagnostics.push(Diagnostic::warning(
855            "VRMA_ADDITIONAL_ANIMATIONS_IGNORED",
856            "/animations/1",
857            "only the first glTF animation is loaded",
858        ));
859    }
860
861    let (source_rest_pose, local_translations) =
862        source_rest_pose(document, &mappings.bone_by_node)?;
863    let mut bone_tracks = HashMap::new();
864    let mut expression_tracks = HashMap::new();
865    let mut look_at_rotation_track = None;
866    let mut duration = 0.0_f32;
867
868    for channel in animation.channels() {
869        validate_channel_accessors(&channel)?;
870        let node_index = channel.target().node().index();
871        let property = channel.target().property();
872        let interpolation = Interpolation::from(channel.sampler().interpolation());
873        let reader =
874            channel.reader(|buffer| buffers.get(buffer.index()).map(|data| data.0.as_slice()));
875        let times = reader
876            .read_inputs()
877            .ok_or_else(|| invalid_channel(channel.index(), "input accessor cannot be read"))?
878            .collect::<Vec<_>>();
879        validate_input_times(channel.index(), &times)?;
880        duration = duration.max(times.last().copied().unwrap_or(0.0));
881        let outputs = reader
882            .read_outputs()
883            .ok_or_else(|| invalid_channel(channel.index(), "output accessor cannot be read"))?;
884
885        if let Some(&bone) = mappings.bone_by_node.get(&node_index) {
886            match (property, outputs) {
887                (
888                    gltf::animation::Property::Rotation,
889                    gltf::animation::util::ReadOutputs::Rotations(values),
890                ) => {
891                    let values = values.into_f32().map(Quat::from_array).collect::<Vec<_>>();
892                    let track = make_track(&times, values, interpolation, channel.index())?;
893                    let slot = &mut bone_tracks
894                        .entry(bone)
895                        .or_insert_with(BoneTrack::new)
896                        .rotation;
897                    if slot.replace(track).is_some() {
898                        return Err(invalid_channel(
899                            channel.index(),
900                            "duplicate humanoid rotation channel",
901                        ));
902                    }
903                }
904                (
905                    gltf::animation::Property::Translation,
906                    gltf::animation::util::ReadOutputs::Translations(values),
907                ) => {
908                    if bone != HumanBone::Hips {
909                        handle_violation(
910                            options.validation,
911                            &mut diagnostics,
912                            "VRMA_NON_HIPS_TRANSLATION",
913                            format!("/animations/0/channels/{}", channel.index()),
914                            format!("translation is not allowed for humanoid bone {bone:?}"),
915                        )?;
916                        continue;
917                    }
918                    let values = values.map(Vec3::from_array).collect::<Vec<_>>();
919                    let mut track = make_track(&times, values, interpolation, channel.index())?;
920                    let rest_translation = local_translations[node_index];
921                    for keyframe in &mut track.keyframes {
922                        keyframe.value -= rest_translation;
923                    }
924                    let slot = &mut bone_tracks
925                        .entry(bone)
926                        .or_insert_with(BoneTrack::new)
927                        .translation;
928                    if slot.replace(track).is_some() {
929                        return Err(invalid_channel(
930                            channel.index(),
931                            "duplicate Hips translation channel",
932                        ));
933                    }
934                }
935                (gltf::animation::Property::Scale, _) => {
936                    handle_violation(
937                        options.validation,
938                        &mut diagnostics,
939                        "VRMA_HUMANOID_SCALE_CHANNEL",
940                        format!("/animations/0/channels/{}", channel.index()),
941                        format!("scale animation is not allowed for humanoid bone {bone:?}"),
942                    )?;
943                }
944                _ => {}
945            }
946            continue;
947        }
948
949        if let Some(name) = mappings.expression_by_node.get(&node_index) {
950            if let (
951                gltf::animation::Property::Translation,
952                gltf::animation::util::ReadOutputs::Translations(values),
953            ) = (property, outputs)
954            {
955                let vector_track = make_track(
956                    &times,
957                    values.map(Vec3::from_array).collect(),
958                    interpolation,
959                    channel.index(),
960                )?;
961                let scalar_track = Track::new(
962                    vector_track.interpolation,
963                    vector_track
964                        .keyframes
965                        .into_iter()
966                        .map(|keyframe| Keyframe {
967                            time: keyframe.time,
968                            value: keyframe.value.x.clamp(0.0, 1.0),
969                            in_tangent: keyframe.in_tangent.map(|value| value.x),
970                            out_tangent: keyframe.out_tangent.map(|value| value.x),
971                        })
972                        .collect(),
973                );
974                if expression_tracks
975                    .insert(name.clone(), scalar_track)
976                    .is_some()
977                {
978                    return Err(invalid_channel(
979                        channel.index(),
980                        "duplicate expression translation channel",
981                    ));
982                }
983            }
984            continue;
985        }
986
987        if mappings.look_at_node == Some(node_index)
988            && property == gltf::animation::Property::Rotation
989            && let gltf::animation::util::ReadOutputs::Rotations(values) = outputs
990        {
991            let track = make_track(
992                &times,
993                values.into_f32().map(Quat::from_array).collect(),
994                interpolation,
995                channel.index(),
996            )?;
997            if look_at_rotation_track.replace(track).is_some() {
998                return Err(invalid_channel(
999                    channel.index(),
1000                    "duplicate LookAt rotation channel",
1001                ));
1002            }
1003        }
1004    }
1005
1006    let result = VrmAnimation {
1007        duration,
1008        bone_tracks,
1009        expression_tracks,
1010        look_at_rotation_track,
1011        source_rest_pose,
1012        look_at_offset_from_head_bone: mappings.look_at_offset,
1013    };
1014    result
1015        .validate()
1016        .map_err(AnimationLoadError::InvalidAnimation)?;
1017    Ok(AnimationLoadOutcome {
1018        animation: result,
1019        diagnostics,
1020    })
1021}
1022
1023fn validate_channel_accessors(
1024    channel: &gltf::animation::Channel<'_>,
1025) -> Result<(), AnimationLoadError> {
1026    use gltf::accessor::{DataType, Dimensions};
1027    use gltf::animation::Property;
1028
1029    let input = channel.sampler().input();
1030    if input.data_type() != DataType::F32
1031        || input.dimensions() != Dimensions::Scalar
1032        || input.normalized()
1033        || input.min().is_none()
1034        || input.max().is_none()
1035    {
1036        return Err(invalid_channel(
1037            channel.index(),
1038            "input accessor must be a non-normalized FLOAT SCALAR with min and max",
1039        ));
1040    }
1041
1042    let output = channel.sampler().output();
1043    let property = channel.target().property();
1044    let float_vector = |dimensions| {
1045        output.data_type() == DataType::F32
1046            && output.dimensions() == dimensions
1047            && !output.normalized()
1048    };
1049    let normalized_scalar_or_vector = |dimensions| {
1050        output.dimensions() == dimensions
1051            && match output.data_type() {
1052                DataType::F32 => !output.normalized(),
1053                DataType::I8 | DataType::U8 | DataType::I16 | DataType::U16 => output.normalized(),
1054                DataType::U32 => false,
1055            }
1056    };
1057    let valid_output = match property {
1058        Property::Translation | Property::Scale => float_vector(Dimensions::Vec3),
1059        Property::Rotation => normalized_scalar_or_vector(Dimensions::Vec4),
1060        Property::MorphTargetWeights => normalized_scalar_or_vector(Dimensions::Scalar),
1061    };
1062    if !valid_output {
1063        let property_name = match property {
1064            Property::Translation => "translation",
1065            Property::Rotation => "rotation",
1066            Property::Scale => "scale",
1067            Property::MorphTargetWeights => "weights",
1068        };
1069        return Err(invalid_channel(
1070            channel.index(),
1071            format!("output accessor is not valid for the {property_name} animation target"),
1072        ));
1073    }
1074
1075    if property != Property::MorphTargetWeights {
1076        let interpolation_multiplier =
1077            if channel.sampler().interpolation() == gltf::animation::Interpolation::CubicSpline {
1078                3
1079            } else {
1080                1
1081            };
1082        let expected = input
1083            .count()
1084            .checked_mul(interpolation_multiplier)
1085            .ok_or_else(|| invalid_channel(channel.index(), "animation sample count overflows"))?;
1086        if output.count() != expected {
1087            return Err(invalid_channel(
1088                channel.index(),
1089                format!(
1090                    "output accessor count {} does not match the expected {expected}",
1091                    output.count()
1092                ),
1093            ));
1094        }
1095    }
1096
1097    Ok(())
1098}
1099
1100struct AnimationMappings {
1101    bone_by_node: HashMap<usize, HumanBone>,
1102    expression_by_node: HashMap<usize, String>,
1103    look_at_node: Option<usize>,
1104    look_at_offset: Option<Vec3>,
1105}
1106
1107fn validate_schema(
1108    document: &gltf::Document,
1109    schema: &VRMCVrmAnimationSchema,
1110    validation: ValidationMode,
1111    diagnostics: &mut Vec<Diagnostic>,
1112) -> Result<AnimationMappings, AnimationLoadError> {
1113    if schema.spec_version != "1.0" {
1114        return Err(AnimationLoadError::InvalidAnimation(format!(
1115            "VRMC_vrm_animation specVersion must be exactly `1.0`, found `{}`",
1116            schema.spec_version
1117        )));
1118    }
1119    let node_count = document.nodes().len();
1120    let mut claimed_nodes = HashSet::new();
1121    let mut bone_by_node = HashMap::new();
1122    if let Some(humanoid) = &schema.humanoid {
1123        const REQUIRED: [HumanBoneName; 15] = [
1124            HumanBoneName::Hips,
1125            HumanBoneName::Spine,
1126            HumanBoneName::Head,
1127            HumanBoneName::LeftUpperLeg,
1128            HumanBoneName::LeftLowerLeg,
1129            HumanBoneName::LeftFoot,
1130            HumanBoneName::RightUpperLeg,
1131            HumanBoneName::RightLowerLeg,
1132            HumanBoneName::RightFoot,
1133            HumanBoneName::LeftUpperArm,
1134            HumanBoneName::LeftLowerArm,
1135            HumanBoneName::LeftHand,
1136            HumanBoneName::RightUpperArm,
1137            HumanBoneName::RightLowerArm,
1138            HumanBoneName::RightHand,
1139        ];
1140        for required in REQUIRED {
1141            if humanoid
1142                .human_bones
1143                .0
1144                .get(&required)
1145                .and_then(Option::as_ref)
1146                .and_then(|bone| bone.node.as_ref())
1147                .is_none()
1148            {
1149                return Err(AnimationLoadError::InvalidAnimation(format!(
1150                    "required humanoid bone {required:?} is missing"
1151                )));
1152            }
1153        }
1154        for (name, bone) in &humanoid.human_bones.0 {
1155            if matches!(name, HumanBoneName::LeftEye | HumanBoneName::RightEye) {
1156                return Err(AnimationLoadError::InvalidAnimation(format!(
1157                    "{name:?} cannot be mapped by VRMC_vrm_animation"
1158                )));
1159            }
1160            let node = bone
1161                .as_ref()
1162                .and_then(|bone| bone.node.as_ref())
1163                .ok_or_else(|| {
1164                    AnimationLoadError::InvalidAnimation(format!(
1165                        "humanoid bone {name:?} must contain a node"
1166                    ))
1167                })?;
1168            let index = node.value();
1169            claim_node(&mut claimed_nodes, index, node_count, "humanoid bone")?;
1170            bone_by_node.insert(index, HumanBone::from(*name));
1171        }
1172        validate_humanoid_rest_pose(document, &humanoid.human_bones, validation, diagnostics)?;
1173    }
1174
1175    let mut expression_by_node = HashMap::new();
1176    if let Some(expressions) = &schema.expressions {
1177        if let Some(preset) = &expressions.preset {
1178            for (name, expression) in &preset.0 {
1179                if matches!(
1180                    name,
1181                    ExpressionPresetName::LookUp
1182                        | ExpressionPresetName::LookDown
1183                        | ExpressionPresetName::LookLeft
1184                        | ExpressionPresetName::LookRight
1185                ) {
1186                    return Err(AnimationLoadError::InvalidAnimation(format!(
1187                        "LookAt preset expression `{}` cannot be animated by an expression node",
1188                        expression_preset_name(*name)
1189                    )));
1190                }
1191                let node = expression.node.as_ref().ok_or_else(|| {
1192                    AnimationLoadError::InvalidAnimation(format!(
1193                        "preset expression `{}` has no node",
1194                        expression_preset_name(*name)
1195                    ))
1196                })?;
1197                let index = node.value();
1198                claim_node(&mut claimed_nodes, index, node_count, "expression")?;
1199                expression_by_node.insert(index, expression_preset_name(*name).to_string());
1200            }
1201        }
1202        if let Some(custom) = &expressions.custom {
1203            for (name, expression) in custom {
1204                if name.is_empty() || is_preset_expression_name(name) {
1205                    return Err(AnimationLoadError::InvalidAnimation(format!(
1206                        "custom expression name `{name}` is invalid"
1207                    )));
1208                }
1209                let node = expression.node.as_ref().ok_or_else(|| {
1210                    AnimationLoadError::InvalidAnimation(format!(
1211                        "custom expression `{name}` has no node"
1212                    ))
1213                })?;
1214                let index = node.value();
1215                claim_node(&mut claimed_nodes, index, node_count, "expression")?;
1216                expression_by_node.insert(index, name.clone());
1217            }
1218        }
1219    }
1220
1221    let (look_at_node, look_at_offset) = if let Some(look_at) = &schema.look_at {
1222        let node = look_at.node.as_ref().ok_or_else(|| {
1223            AnimationLoadError::InvalidAnimation("LookAt mapping has no node".to_string())
1224        })?;
1225        let index = node.value();
1226        claim_node(&mut claimed_nodes, index, node_count, "LookAt")?;
1227        let offset = look_at
1228            .offset_from_head_bone
1229            .map(|offset| Vec3::new(offset[0] as f32, offset[1] as f32, offset[2] as f32));
1230        if offset.is_some_and(|offset| !offset.is_finite()) {
1231            return Err(AnimationLoadError::InvalidAnimation(
1232                "LookAt offsetFromHeadBone must contain finite values".to_string(),
1233            ));
1234        }
1235        (Some(index), offset)
1236    } else {
1237        (None, None)
1238    };
1239
1240    Ok(AnimationMappings {
1241        bone_by_node,
1242        expression_by_node,
1243        look_at_node,
1244        look_at_offset,
1245    })
1246}
1247
1248fn validate_humanoid_rest_pose(
1249    document: &gltf::Document,
1250    bones: &vrm_spec::vrmc_vrm_animation_1_0::VRMCVrmAnimationHumanBones,
1251    validation: ValidationMode,
1252    diagnostics: &mut Vec<Diagnostic>,
1253) -> Result<(), AnimationLoadError> {
1254    for node in document.nodes() {
1255        let (_, _, scale) = node.transform().decomposed();
1256        let max_scale = scale.iter().copied().fold(0.0_f32, f32::max);
1257        let tolerance = max_scale * 2.0e-3;
1258        let valid = scale.iter().all(|value| value.is_finite() && *value > 0.0)
1259            && (scale[0] - scale[1]).abs() <= tolerance
1260            && (scale[1] - scale[2]).abs() <= tolerance;
1261        if !valid {
1262            handle_violation(
1263                validation,
1264                diagnostics,
1265                "VRMA_HUMANOID_SCALE_INVALID",
1266                format!("/nodes/{}/scale", node.index()),
1267                "every T-pose node scale must be positive and uniform".to_string(),
1268            )?;
1269        }
1270    }
1271
1272    let mut parents = vec![None; document.nodes().len()];
1273    for node in document.nodes() {
1274        for child in node.children() {
1275            parents[child.index()] = Some(node.index());
1276        }
1277    }
1278    let mapped_bones = bones.0.iter().filter_map(|(name, entry)| {
1279        entry.as_ref().and_then(|bone| {
1280            bone.node
1281                .as_ref()
1282                .map(|node| (HumanBone::from(*name), node.value()))
1283        })
1284    });
1285    for violation in crate::humanoid::hierarchy_violations(mapped_bones, &parents) {
1286        let bone_name = violation.bone().spec_name();
1287        handle_violation(
1288            validation,
1289            diagnostics,
1290            "VRMA_HUMANOID_HIERARCHY_INVALID",
1291            format!("/extensions/{VRMC_VRM_ANIMATION}/humanoid/humanBones/{bone_name}"),
1292            violation.message(),
1293        )?;
1294    }
1295    Ok(())
1296}
1297
1298fn claim_node(
1299    claimed: &mut HashSet<usize>,
1300    index: usize,
1301    node_count: usize,
1302    role: &str,
1303) -> Result<(), AnimationLoadError> {
1304    if index >= node_count {
1305        return Err(AnimationLoadError::InvalidAnimation(format!(
1306            "{role} references node {index}, but only {node_count} nodes exist"
1307        )));
1308    }
1309    if !claimed.insert(index) {
1310        return Err(AnimationLoadError::InvalidAnimation(format!(
1311            "node {index} is assigned to more than one VRMA role"
1312        )));
1313    }
1314    Ok(())
1315}
1316
1317fn expression_preset_name(name: ExpressionPresetName) -> &'static str {
1318    match name {
1319        ExpressionPresetName::Aa => "aa",
1320        ExpressionPresetName::Angry => "angry",
1321        ExpressionPresetName::Blink => "blink",
1322        ExpressionPresetName::BlinkLeft => "blinkLeft",
1323        ExpressionPresetName::BlinkRight => "blinkRight",
1324        ExpressionPresetName::Ee => "ee",
1325        ExpressionPresetName::Happy => "happy",
1326        ExpressionPresetName::Ih => "ih",
1327        ExpressionPresetName::LookDown => "lookDown",
1328        ExpressionPresetName::LookLeft => "lookLeft",
1329        ExpressionPresetName::LookRight => "lookRight",
1330        ExpressionPresetName::LookUp => "lookUp",
1331        ExpressionPresetName::Neutral => "neutral",
1332        ExpressionPresetName::Oh => "oh",
1333        ExpressionPresetName::Ou => "ou",
1334        ExpressionPresetName::Relaxed => "relaxed",
1335        ExpressionPresetName::Sad => "sad",
1336        ExpressionPresetName::Surprised => "surprised",
1337    }
1338}
1339
1340fn is_preset_expression_name(name: &str) -> bool {
1341    [
1342        "aa",
1343        "angry",
1344        "blink",
1345        "blinkLeft",
1346        "blinkRight",
1347        "ee",
1348        "happy",
1349        "ih",
1350        "lookDown",
1351        "lookLeft",
1352        "lookRight",
1353        "lookUp",
1354        "neutral",
1355        "oh",
1356        "ou",
1357        "relaxed",
1358        "sad",
1359        "surprised",
1360    ]
1361    .contains(&name)
1362}
1363
1364fn make_track<T: TrackValue>(
1365    times: &[f32],
1366    values: Vec<T>,
1367    interpolation: Interpolation,
1368    channel: usize,
1369) -> Result<Track<T>, AnimationLoadError> {
1370    let keyframes = if interpolation == Interpolation::CubicSpline {
1371        if values.len() != times.len() * 3 {
1372            return Err(invalid_channel(
1373                channel,
1374                "CUBICSPLINE output count must be three times the input count",
1375            ));
1376        }
1377        times
1378            .iter()
1379            .copied()
1380            .zip(values.chunks_exact(3))
1381            .map(|(time, values)| Keyframe::cubic(time, values[1], values[0], values[2]))
1382            .collect()
1383    } else {
1384        if values.len() != times.len() {
1385            return Err(invalid_channel(
1386                channel,
1387                "animation output count must equal the input count",
1388            ));
1389        }
1390        times
1391            .iter()
1392            .copied()
1393            .zip(values)
1394            .map(|(time, value)| Keyframe::new(time, value))
1395            .collect()
1396    };
1397    Ok(Track::new(interpolation, keyframes))
1398}
1399
1400fn validate_input_times(channel: usize, times: &[f32]) -> Result<(), AnimationLoadError> {
1401    if times.is_empty() {
1402        return Err(invalid_channel(channel, "input accessor is empty"));
1403    }
1404    if times.iter().any(|time| !time.is_finite() || *time < 0.0) {
1405        return Err(invalid_channel(
1406            channel,
1407            "input times must be finite and non-negative",
1408        ));
1409    }
1410    if times.windows(2).any(|pair| pair[0] >= pair[1]) {
1411        return Err(invalid_channel(
1412            channel,
1413            "input times must be strictly increasing",
1414        ));
1415    }
1416    Ok(())
1417}
1418
1419fn invalid_channel(channel: usize, message: impl Into<String>) -> AnimationLoadError {
1420    AnimationLoadError::InvalidAnimation(format!("animation channel {channel}: {}", message.into()))
1421}
1422
1423fn handle_violation(
1424    mode: ValidationMode,
1425    diagnostics: &mut Vec<Diagnostic>,
1426    code: &'static str,
1427    path: String,
1428    message: String,
1429) -> Result<(), AnimationLoadError> {
1430    match mode {
1431        ValidationMode::Strict => Err(AnimationLoadError::InvalidAnimation(message)),
1432        ValidationMode::Permissive => {
1433            diagnostics.push(Diagnostic::warning(code, path, message));
1434            Ok(())
1435        }
1436    }
1437}
1438
1439fn source_rest_pose(
1440    document: &gltf::Document,
1441    bone_by_node: &HashMap<usize, HumanBone>,
1442) -> Result<(HashMap<HumanBone, SourceBoneRestPose>, Vec<Vec3>), AnimationLoadError> {
1443    let nodes = document.nodes().collect::<Vec<_>>();
1444    let mut parents = vec![None; nodes.len()];
1445    let mut indegree = vec![0_usize; nodes.len()];
1446    let mut children = vec![Vec::new(); nodes.len()];
1447    let mut local_matrices = Vec::with_capacity(nodes.len());
1448    let mut local_rotations = Vec::with_capacity(nodes.len());
1449    let mut local_translations = Vec::with_capacity(nodes.len());
1450    for node in &nodes {
1451        let (translation, rotation, scale) = node.transform().decomposed();
1452        let translation = Vec3::from_array(translation);
1453        let rotation = Quat::from_array(rotation).normalize();
1454        local_translations.push(translation);
1455        local_rotations.push(rotation);
1456        local_matrices.push(Mat4::from_scale_rotation_translation(
1457            Vec3::from_array(scale),
1458            rotation,
1459            translation,
1460        ));
1461        for child in node.children() {
1462            parents[child.index()] = Some(node.index());
1463            indegree[child.index()] += 1;
1464            children[node.index()].push(child.index());
1465        }
1466    }
1467    let mut queue = indegree
1468        .iter()
1469        .enumerate()
1470        .filter_map(|(index, &degree)| (degree == 0).then_some(index))
1471        .collect::<VecDeque<_>>();
1472    let mut world_matrices = vec![Mat4::IDENTITY; nodes.len()];
1473    let mut visited = 0;
1474    while let Some(index) = queue.pop_front() {
1475        world_matrices[index] = parents[index]
1476            .map(|parent| world_matrices[parent] * local_matrices[index])
1477            .unwrap_or(local_matrices[index]);
1478        visited += 1;
1479        for &child in &children[index] {
1480            indegree[child] -= 1;
1481            if indegree[child] == 0 {
1482                queue.push_back(child);
1483            }
1484        }
1485    }
1486    if visited != nodes.len() {
1487        return Err(AnimationLoadError::InvalidAnimation(
1488            "node graph contains a cycle".to_string(),
1489        ));
1490    }
1491
1492    let rest_pose = bone_by_node
1493        .iter()
1494        .map(|(&node, &bone)| {
1495            let (_, world_rotation, world_translation) =
1496                world_matrices[node].to_scale_rotation_translation();
1497            (
1498                bone,
1499                SourceBoneRestPose {
1500                    local_rotation: local_rotations[node],
1501                    world_rotation: world_rotation.normalize(),
1502                    world_translation,
1503                },
1504            )
1505        })
1506        .collect();
1507    Ok((rest_pose, local_translations))
1508}
1509
1510fn validate_gltf_document(document: &gltf::Document) -> Result<(), AnimationLoadError> {
1511    validate_raw_node_graph(document.as_json())?;
1512    crate::extension_declarations::validate(document.as_json())
1513        .map_err(AnimationLoadError::InvalidAnimation)?;
1514    use gltf::json::validation::Validate;
1515    let root = document.as_json();
1516    let mut errors = Vec::new();
1517    root.validate(root, gltf::json::Path::new, &mut |path, error| {
1518        // gltf-json cannot know about VRM extensions. Required extensions are
1519        // checked against this loader's registry in `load_document` instead.
1520        if error != gltf::json::validation::Error::Unsupported {
1521            errors.push((path(), error));
1522        }
1523    });
1524    if errors.is_empty() {
1525        Ok(())
1526    } else {
1527        Err(AnimationLoadError::Gltf(gltf::Error::Validation(errors)))
1528    }
1529}
1530
1531fn validate_raw_node_graph(root: &gltf::json::Root) -> Result<(), AnimationLoadError> {
1532    let mut indegree = vec![0_usize; root.nodes.len()];
1533    let mut children = vec![Vec::new(); root.nodes.len()];
1534    for (parent, node) in root.nodes.iter().enumerate() {
1535        for child in node.children.as_deref().unwrap_or_default() {
1536            let child = child.value();
1537            if child >= root.nodes.len() {
1538                return Err(AnimationLoadError::InvalidAnimation(format!(
1539                    "node {parent} references out-of-range child {child}"
1540                )));
1541            }
1542            indegree[child] += 1;
1543            if indegree[child] > 1 {
1544                return Err(AnimationLoadError::InvalidAnimation(format!(
1545                    "node {child} has multiple parents"
1546                )));
1547            }
1548            children[parent].push(child);
1549        }
1550    }
1551    let mut queue = indegree
1552        .iter()
1553        .enumerate()
1554        .filter_map(|(index, &degree)| (degree == 0).then_some(index))
1555        .collect::<VecDeque<_>>();
1556    let mut visited = 0;
1557    while let Some(node) = queue.pop_front() {
1558        visited += 1;
1559        for &child in &children[node] {
1560            indegree[child] -= 1;
1561            if indegree[child] == 0 {
1562                queue.push_back(child);
1563            }
1564        }
1565    }
1566    if visited != root.nodes.len() {
1567        return Err(AnimationLoadError::InvalidAnimation(
1568            "node graph contains a cycle".to_string(),
1569        ));
1570    }
1571    Ok(())
1572}