nightshade 0.57.0

A cross-platform data-oriented game engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Animation component definitions.

use crate::ecs::animation::blend_tree::BlendTree;
use crate::ecs::animation::graph::AnimationGraph;
use crate::ecs::animation::ik::{AimConstraint, FootDefinition, IkChain, IkChainMulti};
use crate::ecs::animation::ragdoll::Ragdoll;
use nalgebra_glm::{Quat, Vec3};
use nightshade_ecs::Entity;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// One weighted contribution to the base pose. The graph and blend-tree
/// interpreters emit these; the pose pipeline blends the whole set into
/// `bone_transforms`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActiveClip {
    /// Index into the player's clip list.
    pub clip_index: usize,
    /// Playback time in seconds.
    pub time: f32,
    /// Current blend weight before normalization.
    pub weight: f32,
    /// Weight this clip ramps toward.
    pub target_weight: f32,
    /// Weight change per second; 0.0 snaps to `target_weight`.
    pub fade_rate: f32,
    /// Playback speed multiplier.
    pub speed: f32,
    /// How this clip behaves at its end.
    pub loop_mode: LoopMode,
    /// The clip that mirrors `AnimationPlayer::current_clip`/`time` for the legacy
    /// playback API and seeks.
    pub dominant: bool,
}

/// A named animation sequence with duration and channels.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AnimationClip {
    /// Name of the animation (e.g., "Walk", "Idle").
    pub name: String,
    /// Total duration in seconds.
    pub duration: f32,
    /// Channels targeting different properties on nodes.
    pub channels: Vec<AnimationChannel>,
    /// Named markers along the timeline. When playback crosses one, the player
    /// emits an `AnimationEvent`, the cue for footsteps, hit frames, and effects.
    #[serde(default)]
    pub events: Vec<AnimationEvent>,
}

/// A named marker at a point on a clip's timeline.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AnimationEvent {
    /// Time in seconds from the clip's start.
    pub time: f32,
    /// Label published with the emitted event.
    pub name: String,
}

/// How a layer combines with the base pose.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum LayerBlendMode {
    /// Blends toward the layer pose, overriding the bones it touches.
    #[default]
    Override,
    /// Adds the layer's difference from a reference pose on top of the base.
    Additive,
}

/// An additional clip blended on top of the base animation, optionally limited
/// to a subset of bones. Layers drive composites like a wave played on the upper
/// body while the legs keep walking.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AnimationLayer {
    /// Index of the clip this layer plays.
    pub clip_index: usize,
    /// Blend weight toward this layer's pose, 0.0 ignores it, 1.0 fully
    /// overrides the bones it touches.
    pub weight: f32,
    /// Playback time in seconds.
    pub time: f32,
    /// Playback speed multiplier.
    pub speed: f32,
    /// Whether the layer is advancing.
    pub playing: bool,
    /// Whether the layer loops at the end of its clip.
    pub looping: bool,
    /// Bone names this layer affects. Empty means every bone the clip targets.
    #[serde(default)]
    pub mask: Vec<String>,
    /// How the layer combines with the base pose.
    #[serde(default)]
    pub blend_mode: LayerBlendMode,
    /// Reference clip an additive layer is measured against, sampled at its
    /// first frame; ignored for override layers.
    #[serde(default)]
    pub reference_clip: Option<usize>,
}

impl AnimationLayer {
    /// A new looping layer at full weight on the given clip.
    pub fn new(clip_index: usize) -> Self {
        Self {
            clip_index,
            weight: 1.0,
            time: 0.0,
            speed: 1.0,
            playing: true,
            looping: true,
            mask: Vec::new(),
            blend_mode: LayerBlendMode::Override,
            reference_clip: None,
        }
    }

    /// Sets the blend weight.
    pub fn with_weight(mut self, weight: f32) -> Self {
        self.weight = weight;
        self
    }

    /// Restricts the layer to the named bones.
    pub fn with_mask(mut self, mask: Vec<String>) -> Self {
        self.mask = mask;
        self
    }
}

/// Targets a specific property on a node for animation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AnimationChannel {
    /// Index of the target node in the glTF hierarchy.
    pub target_node: usize,
    /// Optional bone name for skeleton-based lookup.
    pub target_bone_name: Option<String>,
    /// Which property to animate.
    pub target_property: AnimationProperty,
    /// Keyframe data and interpolation settings.
    pub sampler: AnimationSampler,
}

/// Properties that can be animated.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum AnimationProperty {
    /// Position offset.
    Translation,
    /// Orientation.
    Rotation,
    /// Scale factors.
    Scale,
    /// Morph target blend weights.
    MorphWeights,
}

/// Keyframe data with times and output values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AnimationSampler {
    /// Keyframe times in seconds.
    pub input: Vec<f32>,
    /// Output values at each keyframe.
    pub output: AnimationSamplerOutput,
    /// How to interpolate between keyframes.
    pub interpolation: AnimationInterpolation,
}

/// Output value types for animation samplers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AnimationSamplerOutput {
    /// Translation or scale values.
    Vec3(Vec<Vec3>),
    /// Rotation values.
    Quat(Vec<Quat>),
    /// Morph weight arrays.
    Weights(Vec<Vec<f32>>),
    /// Cubic spline Vec3 with tangents.
    CubicSplineVec3 {
        values: Vec<Vec3>,
        in_tangents: Vec<Vec3>,
        out_tangents: Vec<Vec3>,
    },
    /// Cubic spline quaternion with tangents.
    CubicSplineQuat {
        values: Vec<Quat>,
        in_tangents: Vec<Quat>,
        out_tangents: Vec<Quat>,
    },
    /// Cubic spline weights with tangents.
    CubicSplineWeights {
        values: Vec<Vec<f32>>,
        in_tangents: Vec<Vec<f32>>,
        out_tangents: Vec<Vec<f32>>,
    },
}

/// Interpolation method between keyframes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnimationInterpolation {
    /// Linear interpolation (lerp for Vec3, slerp for Quat).
    Linear,
    /// Immediate jump to next value.
    Step,
    /// Hermite cubic spline interpolation.
    CubicSpline,
}

/// A chain of bones that dangles with spring dynamics for secondary motion like
/// hair, cloth, tails, and antennae. `bones` is ordered root to tip; the root
/// follows the animation and the rest lag with inertia, pulled back toward the
/// animated pose by `stiffness` and slowed by `damping`. Solved on the GPU.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SpringChain {
    /// Bone names ordered from the fixed root to the dangling tip.
    pub bones: Vec<String>,
    /// Pull back toward the animated pose per frame, 0.0 loose to 1.0 rigid.
    pub stiffness: f32,
    /// Velocity damping per frame, 0.0 free to 1.0 dead.
    pub damping: f32,
    /// Constant world-space acceleration, e.g. gravity.
    pub gravity: Vec3,
    /// Whether the chain simulates this frame.
    pub enabled: bool,
}

/// How playback behaves at the end of a clip.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum LoopMode {
    /// Wraps back to the start and keeps playing.
    #[default]
    Loop,
    /// Stops at the last frame and marks playback finished.
    Once,
    /// Holds the last frame indefinitely without finishing.
    Clamp,
    /// Reflects at each end, playing forward then backward.
    PingPong,
}

/// Wraps `time` into a clip of `duration` under a loop mode, returning the new
/// time and whether playback continues.
pub fn wrap_time(time: f32, duration: f32, mode: LoopMode) -> (f32, bool) {
    if duration <= 0.0 || time < duration {
        return (time.max(0.0), true);
    }
    match mode {
        LoopMode::Loop => (time.rem_euclid(duration), true),
        LoopMode::Once => (duration, false),
        LoopMode::Clamp => (duration, true),
        LoopMode::PingPong => {
            let cycle = duration * 2.0;
            let wrapped = time.rem_euclid(cycle);
            let reflected = if wrapped > duration {
                cycle - wrapped
            } else {
                wrapped
            };
            (reflected, true)
        }
    }
}

/// Resolves the effective loop mode from the mode plus the legacy `looping`
/// flag, so `looping = false` still means play once.
pub fn effective_loop_mode(mode: LoopMode, looping: bool) -> LoopMode {
    match mode {
        LoopMode::Loop if !looping => LoopMode::Once,
        other => other,
    }
}

/// Component controlling animation playback on an entity hierarchy.
///
/// Manages one or more animation clips, playback state, and cross-fading.
/// Maps animation targets to entities via node indices or bone names.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AnimationPlayer {
    /// All available animation clips.
    pub clips: Vec<AnimationClip>,
    /// Index of the currently playing clip.
    pub current_clip: Option<usize>,
    /// Current playback time in seconds.
    pub time: f32,
    /// Playback speed multiplier (1.0 = normal).
    pub speed: f32,
    /// Whether to loop when reaching the end.
    pub looping: bool,
    /// How the current clip behaves at its end.
    #[serde(default)]
    pub loop_mode: LoopMode,
    /// Whether the animation is currently advancing.
    pub playing: bool,
    /// Whether to play all clips sequentially.
    pub play_all: bool,
    /// Maps glTF node indices to entities.
    pub node_index_to_entity: HashMap<usize, Entity>,
    /// Maps bone names to entities for skeleton lookup.
    pub bone_name_to_entity: HashMap<String, Entity>,
    /// Previous clip index for cross-fade blending.
    pub blend_from_clip: Option<usize>,
    /// Time position in the previous clip during blend.
    pub blend_from_time: f32,
    /// Current blend weight (0 = old clip, 1 = new clip).
    pub blend_factor: f32,
    /// Duration of the cross-fade transition.
    pub blend_duration: f32,
    /// Extra clips composited on top of the base animation, each optionally
    /// masked to a subset of bones.
    #[serde(default)]
    pub layers: Vec<AnimationLayer>,
    /// The weighted clip set the pose pipeline blends. Rebuilt each frame by the
    /// graph/blend-tree interpreters or the legacy playback API.
    #[serde(default, skip)]
    pub active_clips: Vec<ActiveClip>,
    /// Named parameters driving blend trees and graph transitions.
    #[serde(default)]
    pub parameters: HashMap<String, f32>,
    /// Optional blend tree producing the base pose from `parameters`.
    #[serde(default)]
    pub blend_tree: Option<BlendTree>,
    /// Optional state machine; supersedes `blend_tree` when present.
    #[serde(default)]
    pub graph: Option<AnimationGraph>,
    /// Two-bone IK chains solved on the GPU pose after blending.
    #[serde(default)]
    pub ik_chains: Vec<IkChain>,
    /// Multi-bone IK chains solved on the GPU with cyclic coordinate descent.
    #[serde(default)]
    pub ik_chains_multi: Vec<IkChainMulti>,
    /// Look-at constraints aiming bone chains at world targets, solved on the GPU.
    #[serde(default)]
    pub aim_constraints: Vec<AimConstraint>,
    /// Spring-bone chains for secondary motion, simulated on the GPU.
    #[serde(default)]
    pub spring_chains: Vec<SpringChain>,
    /// Foot-placement rig steering leg IK chains onto the ground.
    #[serde(default)]
    pub foot_ik: Vec<FootDefinition>,
    /// Whether foot placement runs this frame.
    #[serde(default)]
    pub foot_ik_enabled: bool,
    /// Optional physics ragdoll driving the skeleton from proxy bodies.
    #[serde(default)]
    pub ragdoll: Option<Ragdoll>,
    /// Whether root motion drives the entity transform from the root bone.
    #[serde(default)]
    pub root_motion: bool,
    /// Name of the bone whose translation feeds root motion.
    #[serde(default)]
    pub root_motion_bone: Option<String>,
    /// Whether root motion is confined to the ground plane, leaving vertical
    /// travel to terrain following and foot placement.
    #[serde(default)]
    pub root_motion_planar: bool,
    /// Previous-frame root translation, for per-frame delta extraction.
    #[serde(default, skip)]
    pub root_motion_previous: Option<Vec3>,
    /// Previous-frame player time, to detect loop wraps in root motion.
    #[serde(default, skip)]
    pub root_motion_previous_time: f32,
}

impl Default for AnimationPlayer {
    fn default() -> Self {
        Self {
            clips: Vec::new(),
            current_clip: None,
            time: 0.0,
            speed: 1.0,
            looping: true,
            loop_mode: LoopMode::Loop,
            playing: false,
            play_all: false,
            node_index_to_entity: HashMap::new(),
            bone_name_to_entity: HashMap::new(),
            blend_from_clip: None,
            blend_from_time: 0.0,
            blend_factor: 1.0,
            blend_duration: 0.0,
            layers: Vec::new(),
            active_clips: Vec::new(),
            parameters: HashMap::new(),
            blend_tree: None,
            graph: None,
            ik_chains: Vec::new(),
            ik_chains_multi: Vec::new(),
            aim_constraints: Vec::new(),
            spring_chains: Vec::new(),
            foot_ik: Vec::new(),
            foot_ik_enabled: false,
            ragdoll: None,
            root_motion: false,
            root_motion_bone: None,
            root_motion_planar: false,
            root_motion_previous: None,
            root_motion_previous_time: 0.0,
        }
    }
}

impl AnimationPlayer {
    /// Starts playing a clip from the beginning.
    pub fn play(&mut self, clip_index: usize) {
        if clip_index < self.clips.len() {
            self.current_clip = Some(clip_index);
            self.time = 0.0;
            self.playing = true;
            self.blend_from_clip = None;
            self.blend_from_time = 0.0;
            self.blend_factor = 1.0;
        }
    }

    /// Stops playback and resets to the beginning.
    pub fn stop(&mut self) {
        self.playing = false;
        self.time = 0.0;
        self.blend_from_clip = None;
        self.blend_from_time = 0.0;
        self.blend_factor = 1.0;
    }

    /// Pauses playback at the current time.
    pub fn pause(&mut self) {
        self.playing = false;
    }

    /// Resumes playback from the current time.
    pub fn resume(&mut self) {
        self.playing = true;
    }

    /// Returns the currently playing clip, if any.
    pub fn get_current_clip(&self) -> Option<&AnimationClip> {
        self.current_clip.and_then(|index| self.clips.get(index))
    }

    /// Cross-fades from the current clip to another over the specified duration.
    pub fn blend_to(&mut self, clip_index: usize, duration: f32) {
        if clip_index >= self.clips.len() {
            return;
        }
        if self.current_clip == Some(clip_index) {
            return;
        }

        self.blend_from_clip = self.current_clip;
        self.blend_from_time = self.time;
        self.current_clip = Some(clip_index);
        self.time = 0.0;
        self.blend_factor = 0.0;
        self.blend_duration = duration;
        self.playing = true;
    }

    /// Returns `true` if currently cross-fading between clips.
    pub fn is_blending(&self) -> bool {
        self.blend_from_clip.is_some() && self.blend_factor < 1.0
    }

    /// Adds a clip and returns its index.
    pub fn add_clip(&mut self, clip: AnimationClip) -> usize {
        let index = self.clips.len();
        self.clips.push(clip);
        index
    }

    /// Adds multiple clips.
    pub fn add_clips(&mut self, clips: impl IntoIterator<Item = AnimationClip>) {
        self.clips.extend(clips);
    }

    /// Resolves an animation channel's target to an entity.
    pub fn resolve_target_entity(&self, channel: &AnimationChannel) -> Option<Entity> {
        if let Some(ref bone_name) = channel.target_bone_name
            && let Some(&entity) = self.bone_name_to_entity.get(bone_name)
        {
            return Some(entity);
        }
        self.node_index_to_entity.get(&channel.target_node).copied()
    }

    /// Advances playback time and handles looping/blending.
    pub fn update(&mut self, delta_time: f32) {
        if !self.playing {
            return;
        }

        let clip_duration = if let Some(index) = self.current_clip {
            if let Some(clip) = self.clips.get(index) {
                clip.duration
            } else {
                return;
            }
        } else {
            return;
        };

        self.time += delta_time * self.speed;

        let mode = effective_loop_mode(self.loop_mode, self.looping);
        let (wrapped, still_playing) = wrap_time(self.time, clip_duration, mode);
        self.time = wrapped;
        if !still_playing {
            self.playing = false;
        }

        if self.blend_from_clip.is_some() {
            self.blend_factor += delta_time / self.blend_duration.max(0.001);
            if self.blend_factor >= 1.0 {
                self.blend_factor = 1.0;
                self.blend_from_clip = None;
                self.blend_from_time = 0.0;
            } else if let Some(from_index) = self.blend_from_clip
                && let Some(from_clip) = self.clips.get(from_index)
            {
                self.blend_from_time += delta_time * self.speed;
                if self.blend_from_time >= from_clip.duration && self.looping {
                    self.blend_from_time %= from_clip.duration;
                }
            }
        }

        for layer_index in 0..self.layers.len() {
            let layer = &self.layers[layer_index];
            if !layer.playing {
                continue;
            }
            let Some(duration) = self
                .clips
                .get(layer.clip_index)
                .map(|clip| clip.duration)
                .filter(|duration| *duration > 0.0)
            else {
                continue;
            };
            let layer = &mut self.layers[layer_index];
            layer.time += delta_time * layer.speed;
            if layer.time >= duration {
                if layer.looping {
                    layer.time %= duration;
                } else {
                    layer.time = duration;
                    layer.playing = false;
                }
            }
        }
    }
}

/// Sampled animation value at a point in time.
#[derive(Debug, Clone)]
pub enum AnimationValue {
    /// Translation or scale value.
    Vec3(Vec3),
    /// Rotation value.
    Quat(Quat),
    /// Morph target weights.
    Weights(Vec<f32>),
}

/// Interpolates between two Vec3 values.
pub fn interpolate_vec3(a: &Vec3, b: &Vec3, t: f32, interpolation: AnimationInterpolation) -> Vec3 {
    match interpolation {
        AnimationInterpolation::Linear => *a + (*b - *a) * t,
        AnimationInterpolation::Step => *a,
        AnimationInterpolation::CubicSpline => *a + (*b - *a) * t,
    }
}

/// Interpolates between two weight arrays.
pub fn interpolate_weights(
    a: &[f32],
    b: &[f32],
    t: f32,
    interpolation: AnimationInterpolation,
) -> Vec<f32> {
    match interpolation {
        AnimationInterpolation::Linear => a
            .iter()
            .zip(b.iter())
            .map(|(a_val, b_val)| a_val + (b_val - a_val) * t)
            .collect(),
        AnimationInterpolation::Step => a.to_vec(),
        AnimationInterpolation::CubicSpline => a
            .iter()
            .zip(b.iter())
            .map(|(a_val, b_val)| a_val + (b_val - a_val) * t)
            .collect(),
    }
}

fn cubic_spline_weights(
    p0: &[f32],
    m0: &[f32],
    p1: &[f32],
    m1: &[f32],
    t: f32,
    dt: f32,
) -> Vec<f32> {
    let t2 = t * t;
    let t3 = t2 * t;

    let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
    let h10 = t3 - 2.0 * t2 + t;
    let h01 = -2.0 * t3 + 3.0 * t2;
    let h11 = t3 - t2;

    p0.iter()
        .zip(m0.iter())
        .zip(p1.iter())
        .zip(m1.iter())
        .map(|(((p0_val, m0_val), p1_val), m1_val)| {
            p0_val * h00 + m0_val * (h10 * dt) + p1_val * h01 + m1_val * (h11 * dt)
        })
        .collect()
}

fn cubic_spline_vec3(p0: &Vec3, m0: &Vec3, p1: &Vec3, m1: &Vec3, t: f32, dt: f32) -> Vec3 {
    let t2 = t * t;
    let t3 = t2 * t;

    let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
    let h10 = t3 - 2.0 * t2 + t;
    let h01 = -2.0 * t3 + 3.0 * t2;
    let h11 = t3 - t2;

    *p0 * h00 + *m0 * (h10 * dt) + *p1 * h01 + *m1 * (h11 * dt)
}

fn cubic_spline_quat(p0: &Quat, m0: &Quat, p1: &Quat, m1: &Quat, t: f32, dt: f32) -> Quat {
    let t2 = t * t;
    let t3 = t2 * t;

    let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
    let h10 = t3 - 2.0 * t2 + t;
    let h01 = -2.0 * t3 + 3.0 * t2;
    let h11 = t3 - t2;

    let w = p0.w * h00 + m0.w * (h10 * dt) + p1.w * h01 + m1.w * (h11 * dt);
    let i = p0.i * h00 + m0.i * (h10 * dt) + p1.i * h01 + m1.i * (h11 * dt);
    let j = p0.j * h00 + m0.j * (h10 * dt) + p1.j * h01 + m1.j * (h11 * dt);
    let k = p0.k * h00 + m0.k * (h10 * dt) + p1.k * h01 + m1.k * (h11 * dt);

    Quat::new(w, i, j, k).normalize()
}

/// Interpolates between two quaternions using slerp.
pub fn interpolate_quat(a: &Quat, b: &Quat, t: f32, interpolation: AnimationInterpolation) -> Quat {
    match interpolation {
        AnimationInterpolation::Linear => {
            let a_norm = a.normalize();
            let b_norm = b.normalize();

            let dot = a_norm.dot(&b_norm);
            if dot < 0.0 {
                nalgebra_glm::quat_slerp(&a_norm, &-b_norm, t).normalize()
            } else {
                nalgebra_glm::quat_slerp(&a_norm, &b_norm, t).normalize()
            }
        }
        AnimationInterpolation::Step => a.normalize(),
        AnimationInterpolation::CubicSpline => {
            let a_norm = a.normalize();
            let b_norm = b.normalize();

            let dot = a_norm.dot(&b_norm);
            if dot < 0.0 {
                nalgebra_glm::quat_slerp(&a_norm, &-b_norm, t).normalize()
            } else {
                nalgebra_glm::quat_slerp(&a_norm, &b_norm, t).normalize()
            }
        }
    }
}

/// Samples an animation channel at the given time, returning the interpolated value.
pub fn sample_animation_channel(channel: &AnimationChannel, time: f32) -> Option<AnimationValue> {
    let sampler = &channel.sampler;

    if sampler.input.is_empty() {
        return None;
    }

    if time < sampler.input[0] {
        return match &sampler.output {
            AnimationSamplerOutput::Vec3(values) => {
                values.first().map(|v| AnimationValue::Vec3(*v))
            }
            AnimationSamplerOutput::Quat(values) => {
                values.first().map(|q| AnimationValue::Quat(*q))
            }
            AnimationSamplerOutput::Weights(values) => {
                values.first().map(|w| AnimationValue::Weights(w.clone()))
            }
            AnimationSamplerOutput::CubicSplineVec3 { values, .. } => {
                values.first().map(|v| AnimationValue::Vec3(*v))
            }
            AnimationSamplerOutput::CubicSplineQuat { values, .. } => {
                values.first().map(|q| AnimationValue::Quat(*q))
            }
            AnimationSamplerOutput::CubicSplineWeights { values, .. } => {
                values.first().map(|w| AnimationValue::Weights(w.clone()))
            }
        };
    }

    if time >= sampler.input[sampler.input.len() - 1] {
        let last_index = sampler.input.len() - 1;
        return match &sampler.output {
            AnimationSamplerOutput::Vec3(values) => {
                values.get(last_index).map(|v| AnimationValue::Vec3(*v))
            }
            AnimationSamplerOutput::Quat(values) => {
                values.get(last_index).map(|q| AnimationValue::Quat(*q))
            }
            AnimationSamplerOutput::Weights(values) => values
                .get(last_index)
                .map(|w| AnimationValue::Weights(w.clone())),
            AnimationSamplerOutput::CubicSplineVec3 { values, .. } => {
                values.get(last_index).map(|v| AnimationValue::Vec3(*v))
            }
            AnimationSamplerOutput::CubicSplineQuat { values, .. } => {
                values.get(last_index).map(|q| AnimationValue::Quat(*q))
            }
            AnimationSamplerOutput::CubicSplineWeights { values, .. } => values
                .get(last_index)
                .map(|w| AnimationValue::Weights(w.clone())),
        };
    }

    let key_index = sampler
        .input
        .partition_point(|&keyframe_time| keyframe_time <= time)
        - 1;

    let next_key_index = key_index + 1;

    if key_index == next_key_index {
        return match &sampler.output {
            AnimationSamplerOutput::Vec3(values) => {
                values.get(key_index).map(|v| AnimationValue::Vec3(*v))
            }
            AnimationSamplerOutput::Quat(values) => {
                values.get(key_index).map(|q| AnimationValue::Quat(*q))
            }
            AnimationSamplerOutput::Weights(values) => values
                .get(key_index)
                .map(|w| AnimationValue::Weights(w.clone())),
            AnimationSamplerOutput::CubicSplineVec3 { values, .. } => {
                values.get(key_index).map(|v| AnimationValue::Vec3(*v))
            }
            AnimationSamplerOutput::CubicSplineQuat { values, .. } => {
                values.get(key_index).map(|q| AnimationValue::Quat(*q))
            }
            AnimationSamplerOutput::CubicSplineWeights { values, .. } => values
                .get(key_index)
                .map(|w| AnimationValue::Weights(w.clone())),
        };
    }

    let key_time = sampler.input[key_index];
    let next_key_time = sampler.input[next_key_index];
    let dt = next_key_time - key_time;
    let t = (time - key_time) / dt;

    match &sampler.output {
        AnimationSamplerOutput::Vec3(values) => {
            if let (Some(a), Some(b)) = (values.get(key_index), values.get(next_key_index)) {
                Some(AnimationValue::Vec3(interpolate_vec3(
                    a,
                    b,
                    t,
                    sampler.interpolation,
                )))
            } else {
                None
            }
        }
        AnimationSamplerOutput::Quat(values) => {
            if let (Some(a), Some(b)) = (values.get(key_index), values.get(next_key_index)) {
                Some(AnimationValue::Quat(interpolate_quat(
                    a,
                    b,
                    t,
                    sampler.interpolation,
                )))
            } else {
                None
            }
        }
        AnimationSamplerOutput::CubicSplineVec3 {
            values,
            in_tangents,
            out_tangents,
        } => {
            if let (Some(p0), Some(p1), Some(m0), Some(m1)) = (
                values.get(key_index),
                values.get(next_key_index),
                out_tangents.get(key_index),
                in_tangents.get(next_key_index),
            ) {
                Some(AnimationValue::Vec3(cubic_spline_vec3(
                    p0, m0, p1, m1, t, dt,
                )))
            } else {
                None
            }
        }
        AnimationSamplerOutput::CubicSplineQuat {
            values,
            in_tangents,
            out_tangents,
        } => {
            if let (Some(p0), Some(p1), Some(m0), Some(m1)) = (
                values.get(key_index),
                values.get(next_key_index),
                out_tangents.get(key_index),
                in_tangents.get(next_key_index),
            ) {
                Some(AnimationValue::Quat(cubic_spline_quat(
                    p0, m0, p1, m1, t, dt,
                )))
            } else {
                None
            }
        }
        AnimationSamplerOutput::Weights(values) => {
            if let (Some(a), Some(b)) = (values.get(key_index), values.get(next_key_index)) {
                Some(AnimationValue::Weights(interpolate_weights(
                    a,
                    b,
                    t,
                    sampler.interpolation,
                )))
            } else {
                None
            }
        }
        AnimationSamplerOutput::CubicSplineWeights {
            values,
            in_tangents,
            out_tangents,
        } => {
            if let (Some(p0), Some(p1), Some(m0), Some(m1)) = (
                values.get(key_index),
                values.get(next_key_index),
                out_tangents.get(key_index),
                in_tangents.get(next_key_index),
            ) {
                Some(AnimationValue::Weights(cubic_spline_weights(
                    p0, m0, p1, m1, t, dt,
                )))
            } else {
                None
            }
        }
    }
}