vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
use std::sync::Arc;

use glam::{Mat4, Quat, Vec3};

use crate::evaluated_material::{EvaluatedMaterial, evaluate_materials};
use crate::expressions::{MaterialColorUpdate, MorphTargetUpdate, TextureTransformUpdate};
use crate::instance::{AvatarInstance, BoneUpdate};
use crate::render::{self, CpuMesh};
use crate::spring_bone::SpringBoneSimulator;
use crate::{
    Avatar, CameraMode, HumanBone, MaterialId, NodeId, PrimitiveId, RenderPrimitive, SkinId,
    VrmAnimation,
};

/// Errors caused by invalid persistent controls.
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ControlError {
    /// The requested expression name is not defined by the asset.
    #[error("unknown expression `{0}`")]
    UnknownExpression(String),
    /// The requested humanoid bone is not mapped by the asset.
    #[error("humanoid bone `{0:?}` is not mapped by this asset")]
    MissingBone(HumanBone),
    /// A control value contains NaN or infinity.
    #[error("{field} must contain only finite values")]
    NonFinite {
        /// The name of the invalid control value.
        field: &'static str,
    },
    /// The animation clip or playback options are invalid.
    #[error("invalid animation: {0}")]
    InvalidAnimation(String),
}

/// Errors produced while evaluating a frame.
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum RuntimeError {
    /// The supplied delta time is negative, NaN, or infinite.
    #[error("delta time must be finite and non-negative")]
    InvalidDeltaTime,
    /// Advancing the material animation clock would overflow to a non-finite value.
    #[error("material time would become non-finite")]
    MaterialTimeOverflow,
    /// Applying the playback speed would make the clip time non-finite.
    #[error("animation time would become non-finite")]
    AnimationTimeOverflow,
}

/// Runtime switches that normally remain unchanged across frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuntimeOptions {
    /// Whether node constraints are evaluated each frame.
    pub enable_constraints: bool,
    /// Whether spring-bone simulation is evaluated each frame.
    pub enable_spring_bone: bool,
}

impl Default for RuntimeOptions {
    fn default() -> Self {
        Self {
            enable_constraints: true,
            enable_spring_bone: true,
        }
    }
}

/// Defines what happens when animation time reaches the clip duration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PlaybackMode {
    /// Stops on the final frame after one playback.
    Once,
    /// Repeats the clip after reaching its duration.
    #[default]
    Loop,
}

/// Persistent animation playback settings.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PlaybackOptions {
    /// Playback speed multiplier; must be finite and non-negative.
    pub speed: f32,
    /// Behavior when playback reaches the clip duration.
    pub mode: PlaybackMode,
    /// Scales loaded VRMA Hips translation by target/source rest-pose height.
    pub scale_hips_translation: bool,
}

impl Default for PlaybackOptions {
    fn default() -> Self {
        Self {
            speed: 1.0,
            mode: PlaybackMode::Loop,
            scale_hips_translation: true,
        }
    }
}

struct AnimationState {
    clip: Arc<VrmAnimation>,
    time: f32,
    speed: f32,
    mode: PlaybackMode,
    scale_hips_translation: bool,
    playing: bool,
}

/// Joint matrices for one glTF skin in the current frame.
#[derive(Debug, Clone, PartialEq)]
pub struct SkinningPalette {
    /// Stable identifier of the skin represented by this palette.
    pub skin_id: SkinId,
    /// Current joint matrices in the skin's joint order.
    pub joint_matrices: Vec<Mat4>,
}

#[derive(Debug, Clone, Default)]
struct FrameState {
    world_matrices: Vec<Mat4>,
    skinning_palettes: Vec<SkinningPalette>,
    morph_weights: Vec<Vec<f32>>,
    morph_updates: Vec<MorphTargetUpdate>,
    material_color_updates: Vec<MaterialColorUpdate>,
    texture_transform_updates: Vec<TextureTransformUpdate>,
    evaluated_materials: Vec<EvaluatedMaterial>,
    bone_updates: Vec<BoneUpdate>,
}

impl FrameState {
    fn rest(asset: &Avatar) -> Self {
        let bone_updates = Vec::new();
        let world_matrices = asset.compute_world_matrices(&bone_updates);
        let skinning_palettes = asset
            .skins()
            .iter()
            .enumerate()
            .map(|(skin_index, skin)| SkinningPalette {
                skin_id: SkinId::from_index(skin_index),
                joint_matrices: asset.compute_joint_matrices(skin, &bone_updates),
            })
            .collect();
        // VRMC_vrm's expression update algorithm starts every morph target at
        // zero, independently of the glTF node/mesh default weights.
        let morph_weights = asset
            .primitives()
            .iter()
            .map(|primitive| vec![0.0; primitive.morph_targets().len()])
            .collect();
        let evaluated_materials = evaluate_materials(asset, &[], &[], 0.0);

        Self {
            world_matrices,
            skinning_palettes,
            morph_weights,
            evaluated_materials,
            ..Self::default()
        }
    }
}

/// A high-level VRM instance that owns controls, animation, and simulation.
pub struct AvatarRuntime {
    asset: Arc<Avatar>,
    instance: AvatarInstance,
    spring_simulator: SpringBoneSimulator,
    options: RuntimeOptions,
    animation: Option<AnimationState>,
    material_time: f32,
    frame: FrameState,
}

impl AvatarRuntime {
    /// Creates an independent runtime from an owned or shared immutable asset.
    pub fn new(asset: impl Into<Arc<Avatar>>) -> Self {
        let asset = asset.into();
        let frame = FrameState::rest(&asset);
        Self {
            asset,
            instance: AvatarInstance::default(),
            spring_simulator: SpringBoneSimulator::new(),
            options: RuntimeOptions::default(),
            animation: None,
            material_time: 0.0,
            frame,
        }
    }

    /// Returns the immutable avatar asset evaluated by this runtime.
    pub fn asset(&self) -> &Avatar {
        &self.asset
    }

    /// Clones the shared handle to the immutable avatar asset.
    pub fn shared_asset(&self) -> Arc<Avatar> {
        Arc::clone(&self.asset)
    }

    /// Returns the currently active runtime switches.
    pub fn options(&self) -> RuntimeOptions {
        self.options
    }

    /// Enables or disables constraint evaluation for subsequent frames.
    pub fn set_constraints_enabled(&mut self, enabled: bool) {
        self.options.enable_constraints = enabled;
    }

    /// Enables or disables spring-bone simulation for subsequent frames.
    pub fn set_spring_bone_enabled(&mut self, enabled: bool) {
        self.options.enable_spring_bone = enabled;
    }

    /// Sets a persistent expression weight.
    pub fn set_expression(&mut self, name: &str, weight: f32) -> Result<(), ControlError> {
        if !weight.is_finite() {
            return Err(ControlError::NonFinite {
                field: "expression weight",
            });
        }
        if self.asset.expressions().get(name).is_none() {
            return Err(ControlError::UnknownExpression(name.to_string()));
        }
        self.instance.set_expression(name, weight);
        Ok(())
    }

    /// Removes the persistent weight for one expression.
    pub fn clear_expression(&mut self, name: &str) -> Result<(), ControlError> {
        if self.asset.expressions().get(name).is_none() {
            return Err(ControlError::UnknownExpression(name.to_string()));
        }
        self.instance.clear_expression(name);
        Ok(())
    }

    /// Removes all persistent expression weights.
    pub fn clear_expressions(&mut self) {
        self.instance.clear_expressions();
    }

    /// Returns a persistent expression weight, or zero if it was not set.
    pub fn expression_weight(&self, name: &str) -> Result<f32, ControlError> {
        if self.asset.expressions().get(name).is_none() {
            return Err(ControlError::UnknownExpression(name.to_string()));
        }
        Ok(self.instance.expression_weight(name))
    }

    /// Sets a normalized persistent local-space rotation for a humanoid bone.
    pub fn set_bone_rotation(
        &mut self,
        bone: HumanBone,
        rotation: Quat,
    ) -> Result<(), ControlError> {
        if !rotation.is_finite() {
            return Err(ControlError::NonFinite {
                field: "bone rotation",
            });
        }
        if self.asset.humanoid().bone(bone).is_none() {
            return Err(ControlError::MissingBone(bone));
        }
        let normalized = if rotation.length_squared() > f32::EPSILON {
            rotation.normalize()
        } else {
            Quat::IDENTITY
        };
        self.instance.set_bone_rotation(bone, normalized);
        Ok(())
    }

    /// Removes the persistent rotation override for one humanoid bone.
    pub fn clear_bone_rotation(&mut self, bone: HumanBone) -> Result<(), ControlError> {
        if self.asset.humanoid().bone(bone).is_none() {
            return Err(ControlError::MissingBone(bone));
        }
        self.instance.clear_bone_rotation(bone);
        Ok(())
    }

    /// Removes all persistent humanoid bone rotation overrides.
    pub fn clear_bone_rotations(&mut self) {
        self.instance.clear_bone_rotations();
    }

    /// Sets a persistent local-space translation for a humanoid bone.
    pub fn set_bone_translation(
        &mut self,
        bone: HumanBone,
        translation: Vec3,
    ) -> Result<(), ControlError> {
        if !translation.is_finite() {
            return Err(ControlError::NonFinite {
                field: "bone translation",
            });
        }
        if self.asset.humanoid().bone(bone).is_none() {
            return Err(ControlError::MissingBone(bone));
        }
        self.instance.set_bone_translation(bone, translation);
        Ok(())
    }

    /// Removes the persistent translation override for one humanoid bone.
    pub fn clear_bone_translation(&mut self, bone: HumanBone) -> Result<(), ControlError> {
        if self.asset.humanoid().bone(bone).is_none() {
            return Err(ControlError::MissingBone(bone));
        }
        self.instance.clear_bone_translation(bone);
        Ok(())
    }

    /// Removes all persistent humanoid bone translation overrides.
    pub fn clear_bone_translations(&mut self) {
        self.instance.clear_bone_translations();
    }

    /// Sets the world-space point that the avatar should look toward.
    pub fn set_look_at_target(&mut self, target: Option<Vec3>) -> Result<(), ControlError> {
        if target.is_some_and(|target| !target.is_finite()) {
            return Err(ControlError::NonFinite {
                field: "look-at target",
            });
        }
        self.instance.set_look_at_target(target);
        Ok(())
    }

    /// Removes the persistent look-at target.
    pub fn clear_look_at_target(&mut self) {
        self.instance.set_look_at_target(None);
    }

    /// Validates and starts a clip from time zero.
    ///
    /// Loaded VRMA clips are retargeted from their source rest pose to this
    /// runtime's avatar. [`PlaybackOptions::scale_hips_translation`] controls
    /// whether Hips motion is scaled by the source and target avatar heights.
    ///
    /// # Errors
    ///
    /// Returns [`ControlError::InvalidAnimation`] when the clip contains an
    /// invalid track or when the playback speed is negative or non-finite.
    pub fn play(
        &mut self,
        clip: impl Into<Arc<VrmAnimation>>,
        options: PlaybackOptions,
    ) -> Result<(), ControlError> {
        let clip = clip.into();
        clip.validate().map_err(ControlError::InvalidAnimation)?;
        if !options.speed.is_finite() || options.speed < 0.0 {
            return Err(ControlError::InvalidAnimation(
                "playback speed must be finite and non-negative".to_string(),
            ));
        }
        self.animation = Some(AnimationState {
            clip,
            time: 0.0,
            speed: options.speed,
            mode: options.mode,
            scale_hips_translation: options.scale_hips_translation,
            playing: true,
        });
        Ok(())
    }

    /// Pauses the current clip without discarding its time.
    pub fn pause(&mut self) {
        if let Some(animation) = &mut self.animation {
            animation.playing = false;
        }
    }

    /// Resumes the current clip, if one is loaded.
    pub fn resume(&mut self) {
        if let Some(animation) = &mut self.animation {
            animation.playing = true;
        }
    }

    /// Changes playback speed without replacing or rewinding the clip.
    pub fn set_playback_speed(&mut self, speed: f32) -> Result<(), ControlError> {
        if !speed.is_finite() || speed < 0.0 {
            return Err(ControlError::InvalidAnimation(
                "playback speed must be finite and non-negative".to_string(),
            ));
        }
        if let Some(animation) = &mut self.animation {
            animation.speed = speed;
        }
        Ok(())
    }

    /// Seeks the current clip to a non-negative time clamped to its duration.
    pub fn seek(&mut self, time: f32) -> Result<(), ControlError> {
        if !time.is_finite() || time < 0.0 {
            return Err(ControlError::NonFinite {
                field: "animation time",
            });
        }
        if let Some(animation) = &mut self.animation {
            animation.time = time.min(animation.clip.duration().max(0.0));
        }
        Ok(())
    }

    /// Stops and discards the current animation playback state.
    pub fn stop(&mut self) {
        self.animation = None;
    }

    /// Returns the current clip time, or `None` when no clip is loaded.
    pub fn playback_time(&self) -> Option<f32> {
        self.animation.as_ref().map(|animation| animation.time)
    }

    /// Reports whether a loaded clip is currently advancing.
    pub fn is_playing(&self) -> bool {
        self.animation
            .as_ref()
            .is_some_and(|animation| animation.playing)
    }

    /// Evaluates one frame while retaining all persistent controls.
    ///
    /// `dt` is elapsed time in seconds. Animation, expressions, LookAt, node
    /// constraints, SpringBone, world transforms, skinning palettes, and
    /// dynamic material values are evaluated in their runtime order.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeError::InvalidDeltaTime`] for a negative or non-finite
    /// delta and an overflow variant when a material or animation clock cannot
    /// advance without becoming non-finite.
    ///
    /// Invalid time arithmetic returns an error before either clock or the
    /// cached frame is mutated.
    pub fn update(&mut self, dt: f32) -> Result<FrameView<'_>, RuntimeError> {
        if !dt.is_finite() || dt < 0.0 {
            return Err(RuntimeError::InvalidDeltaTime);
        }

        let next_material_time = self.material_time + dt;
        if !next_material_time.is_finite() {
            return Err(RuntimeError::MaterialTimeOverflow);
        }

        let next_animation_time = if let Some(animation) = &self.animation
            && animation.playing
        {
            let advance = dt * animation.speed;
            let next_time = animation.time + advance;
            if !advance.is_finite() || !next_time.is_finite() {
                return Err(RuntimeError::AnimationTimeOverflow);
            }
            Some(next_time)
        } else {
            None
        };

        // Commit both clocks only after every time calculation succeeds so an
        // overflow error leaves the entire runtime at its previous frame.
        self.material_time = next_material_time;

        if let Some(animation) = &mut self.animation
            && let Some(next_time) = next_animation_time
        {
            animation.time = next_time;
            if animation.clip.duration() <= 0.0 {
                animation.time = 0.0;
                if animation.mode == PlaybackMode::Once {
                    animation.playing = false;
                }
            } else if animation.time >= animation.clip.duration() {
                match animation.mode {
                    PlaybackMode::Loop => animation.time %= animation.clip.duration(),
                    PlaybackMode::Once => {
                        animation.time = animation.clip.duration();
                        animation.playing = false;
                    }
                }
            }
        }

        let mut frame_instance = AvatarInstance::default();
        if let Some(animation) = &self.animation {
            frame_instance.apply_animation_with_options(
                &animation.clip,
                animation.time,
                &self.asset,
                animation.scale_hips_translation,
            );
        }
        frame_instance.overlay(&self.instance);
        let evaluation = frame_instance.evaluate(&self.asset);
        let mut bone_updates = evaluation.bone_updates;

        if self.options.enable_constraints {
            let world = self.asset.compute_world_matrices(&bone_updates);
            bone_updates.extend(crate::constraint::solve_constraints(&self.asset, &world));
        }

        if self.options.enable_spring_bone {
            let world = self.asset.compute_world_matrices(&bone_updates);
            bone_updates.extend(self.spring_simulator.update(&self.asset, &world, dt));
        }

        let world_matrices = self.asset.compute_world_matrices(&bone_updates);
        let skinning_palettes = self
            .asset
            .skins()
            .iter()
            .enumerate()
            .map(|(skin_index, skin)| SkinningPalette {
                skin_id: SkinId::from_index(skin_index),
                joint_matrices: self.asset.compute_joint_matrices(skin, &bone_updates),
            })
            .collect();

        // Reinitialize from zero on every frame before accumulating expression
        // binds, as required by the VRM expression update algorithm.
        let mut morph_weights: Vec<Vec<f32>> = self
            .asset
            .primitives()
            .iter()
            .map(|primitive| vec![0.0; primitive.morph_targets().len()])
            .collect();
        for update in &evaluation.morph_updates {
            for (primitive_index, primitive) in self.asset.primitives().iter().enumerate() {
                if primitive.node_index() != update.node_index() {
                    continue;
                }
                if let Some(weight) =
                    morph_weights[primitive_index].get_mut(update.target_index() as usize)
                {
                    *weight = update.weight();
                }
            }
        }
        let evaluated_materials = evaluate_materials(
            &self.asset,
            &evaluation.material_color_updates,
            &evaluation.texture_transform_updates,
            self.material_time,
        );

        self.frame = FrameState {
            world_matrices,
            skinning_palettes,
            morph_weights,
            morph_updates: evaluation.morph_updates,
            material_color_updates: evaluation.material_color_updates,
            texture_transform_updates: evaluation.texture_transform_updates,
            evaluated_materials,
            bone_updates,
        };

        Ok(FrameView {
            asset: &self.asset,
            state: &self.frame,
        })
    }

    /// Resets controls, simulation, and all cached output to the rest state.
    pub fn reset(&mut self) {
        self.instance = AvatarInstance::default();
        self.spring_simulator.reset();
        self.animation = None;
        self.material_time = 0.0;
        self.frame = FrameState::rest(&self.asset);
    }

    /// Provides mutable low-level state for custom evaluation pipelines.
    pub fn instance_mut(&mut self) -> &mut AvatarInstance {
        &mut self.instance
    }

    /// Provides mutable access to the spring simulator for advanced use.
    pub fn spring_simulator_mut(&mut self) -> &mut SpringBoneSimulator {
        &mut self.spring_simulator
    }
}

/// A zero-copy view of the most recently evaluated frame.
#[derive(Clone, Copy)]
pub struct FrameView<'a> {
    asset: &'a Arc<Avatar>,
    state: &'a FrameState,
}

impl<'a> FrameView<'a> {
    /// Returns GPU-oriented draw data without copying frame buffers.
    ///
    /// Each [`GpuDraw`] combines immutable primitive attributes with the
    /// current world matrix, morph weights, joint matrices, and evaluated
    /// material data required by a renderer.
    pub fn gpu(self) -> GpuFrameView<'a> {
        GpuFrameView {
            asset: self.asset.as_ref(),
            state: self.state,
        }
    }

    /// Applies morphing, skinning, and world transforms on the CPU.
    ///
    /// The returned [`CpuMesh`] values contain world-space vertices and can be
    /// rendered without morph-target or skinning shader stages.
    pub fn bake_cpu(self) -> Vec<CpuMesh> {
        render::bake_frame(
            self.asset,
            &self.state.world_matrices,
            &self.state.skinning_palettes,
            &self.state.morph_weights,
        )
    }

    /// Bakes CPU meshes with VRM first-person visibility already applied.
    pub fn bake_cpu_for(self, camera: CameraMode) -> Vec<CpuMesh> {
        apply_camera_visibility(self.asset, self.bake_cpu(), camera)
    }

    /// Clones this frame into an independently owned snapshot.
    pub fn to_owned(self) -> FrameSnapshot {
        FrameSnapshot {
            asset: Arc::clone(self.asset),
            state: self.state.clone(),
        }
    }

    /// Returns current world matrices in avatar node order.
    pub fn world_matrices(self) -> &'a [Mat4] {
        &self.state.world_matrices
    }

    /// Returns current joint-matrix palettes in skin order.
    pub fn skinning_palettes(self) -> &'a [SkinningPalette] {
        &self.state.skinning_palettes
    }

    /// Returns expression-produced morph target updates.
    pub fn morph_updates(self) -> &'a [MorphTargetUpdate] {
        &self.state.morph_updates
    }

    /// Returns expression-produced material color updates.
    pub fn material_color_updates(self) -> &'a [MaterialColorUpdate] {
        &self.state.material_color_updates
    }

    /// Returns expression-produced texture transform updates.
    pub fn texture_transform_updates(self) -> &'a [TextureTransformUpdate] {
        &self.state.texture_transform_updates
    }

    /// Returns renderer-ready dynamic values for every material in the asset.
    pub fn evaluated_materials(self) -> &'a [EvaluatedMaterial] {
        &self.state.evaluated_materials
    }

    /// Resolves one renderer-ready material value by its stable identifier.
    pub fn evaluated_material(self, id: MaterialId) -> Option<&'a EvaluatedMaterial> {
        self.state.evaluated_materials.get(id.index())
    }

    /// Returns local humanoid bone updates applied to this frame.
    pub fn bone_updates(self) -> &'a [BoneUpdate] {
        &self.state.bone_updates
    }
}

/// An owned frame that can be queued or moved to another thread.
#[derive(Debug, Clone)]
pub struct FrameSnapshot {
    asset: Arc<Avatar>,
    state: FrameState,
}

impl FrameSnapshot {
    /// Returns GPU-oriented draw data borrowed from this snapshot.
    pub fn gpu(&self) -> GpuFrameView<'_> {
        GpuFrameView {
            asset: &self.asset,
            state: &self.state,
        }
    }

    /// Applies morphing and skinning on the CPU for every primitive.
    pub fn bake_cpu(&self) -> Vec<CpuMesh> {
        render::bake_frame(
            &self.asset,
            &self.state.world_matrices,
            &self.state.skinning_palettes,
            &self.state.morph_weights,
        )
    }

    /// Bakes CPU meshes with VRM first-person visibility already applied.
    pub fn bake_cpu_for(&self, camera: CameraMode) -> Vec<CpuMesh> {
        apply_camera_visibility(&self.asset, self.bake_cpu(), camera)
    }

    /// Returns current world matrices in avatar node order.
    pub fn world_matrices(&self) -> &[Mat4] {
        &self.state.world_matrices
    }

    /// Returns current joint-matrix palettes in skin order.
    pub fn skinning_palettes(&self) -> &[SkinningPalette] {
        &self.state.skinning_palettes
    }

    /// Returns expression-produced morph target updates.
    pub fn morph_updates(&self) -> &[MorphTargetUpdate] {
        &self.state.morph_updates
    }

    /// Returns expression-produced material color updates.
    pub fn material_color_updates(&self) -> &[MaterialColorUpdate] {
        &self.state.material_color_updates
    }

    /// Returns expression-produced texture transform updates.
    pub fn texture_transform_updates(&self) -> &[TextureTransformUpdate] {
        &self.state.texture_transform_updates
    }

    /// Returns renderer-ready dynamic values for every material in the asset.
    pub fn evaluated_materials(&self) -> &[EvaluatedMaterial] {
        &self.state.evaluated_materials
    }

    /// Resolves one renderer-ready material value by its stable identifier.
    pub fn evaluated_material(&self, id: MaterialId) -> Option<&EvaluatedMaterial> {
        self.state.evaluated_materials.get(id.index())
    }

    /// Returns local humanoid bone updates applied to this frame.
    pub fn bone_updates(&self) -> &[BoneUpdate] {
        &self.state.bone_updates
    }
}

/// GPU-oriented access to static primitive buffers and dynamic frame data.
#[derive(Clone, Copy)]
pub struct GpuFrameView<'a> {
    asset: &'a Avatar,
    state: &'a FrameState,
}

impl<'a> GpuFrameView<'a> {
    /// Iterates over renderer-ready draw records for every primitive.
    pub fn draws(self) -> impl ExactSizeIterator<Item = GpuDraw<'a>> + 'a {
        self.asset
            .primitives()
            .iter()
            .enumerate()
            .map(move |(primitive_index, primitive)| {
                let skin_id = primitive.skin_index().map(SkinId::from_index);
                let material_id = primitive.material_index().map(MaterialId::from_index);
                let joint_matrices = skin_id
                    .and_then(|skin_id| self.state.skinning_palettes.get(skin_id.index()))
                    .map(|palette| palette.joint_matrices.as_slice())
                    .unwrap_or(&[]);
                GpuDraw {
                    asset: self.asset,
                    primitive_id: PrimitiveId::from_index(primitive_index),
                    node_id: NodeId::from_index(primitive.node_index() as usize),
                    material_id,
                    evaluated_material: material_id
                        .and_then(|id| self.state.evaluated_materials.get(id.index())),
                    skin_id,
                    primitive,
                    world_matrix: self
                        .state
                        .world_matrices
                        .get(primitive.node_index() as usize)
                        .copied()
                        .unwrap_or(Mat4::IDENTITY),
                    morph_weights: self
                        .state
                        .morph_weights
                        .get(primitive_index)
                        .map(Vec::as_slice)
                        .unwrap_or(&[]),
                    joint_matrices,
                }
            })
    }
}

/// One GPU draw with stable asset identifiers and frame-local values.
pub struct GpuDraw<'a> {
    asset: &'a Avatar,
    /// Stable identifier of the source primitive.
    pub primitive_id: PrimitiveId,
    /// Stable identifier of the node that instantiates the primitive.
    pub node_id: NodeId,
    /// Stable identifier of the primitive material, if present.
    pub material_id: Option<MaterialId>,
    /// Dynamic material values matching `material_id`, when the draw has one.
    pub evaluated_material: Option<&'a EvaluatedMaterial>,
    /// Stable identifier of the skin used by the draw, if present.
    pub skin_id: Option<SkinId>,
    /// Immutable geometry and attribute data for the draw.
    pub primitive: &'a RenderPrimitive,
    /// Current world transform of the primitive node.
    ///
    /// Apply this matrix to unskinned primitives. [`Self::joint_matrices`]
    /// already produce world-space output for skinned primitives, so applying
    /// both would transform those vertices twice.
    pub world_matrix: Mat4,
    /// Current morph weights in the order of [`RenderPrimitive::morph_targets`].
    pub morph_weights: &'a [f32],
    /// Current world-space joint matrices in the selected [`crate::Skin`] joint order.
    ///
    /// The slice is empty for an unskinned draw. A shader indexes it through
    /// every consecutive `JOINTS_n` / `WEIGHTS_n` set on [`Self::primitive`].
    pub joint_matrices: &'a [Mat4],
}

impl<'a> GpuDraw<'a> {
    /// Returns the source indices visible to the selected camera.
    pub fn indices(&self, camera: CameraMode) -> std::borrow::Cow<'a, [u32]> {
        self.asset
            .first_person()
            .visible_indices(self.asset, self.primitive, camera)
    }
}

fn apply_camera_visibility(
    asset: &Avatar,
    meshes: Vec<CpuMesh>,
    camera: CameraMode,
) -> Vec<CpuMesh> {
    meshes
        .into_iter()
        .enumerate()
        .filter_map(|(index, mut mesh)| {
            let primitive = asset.primitives().get(index)?;
            mesh.indices = asset
                .first_person()
                .visible_indices(asset, primitive, camera)
                .into_owned();
            (!mesh.indices.is_empty()).then_some(mesh)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitive::{PrimitiveTopology, RenderPrimitive};
    use crate::{
        Avatar, AvatarNode, BoneTrack, Expression, Expressions, Humanoid, Interpolation, Keyframe,
        Material, MaterialColorBind, MaterialColorType, MorphTarget, MorphTargetBind,
        TextureTransformBind, Track, Transform,
    };

    fn test_asset() -> Avatar {
        let expression =
            Expression::new("happy").with_morph_target_binds(vec![MorphTargetBind::new(0, 0, 1.0)]);
        let primitive = RenderPrimitive::new(
            0,
            Transform::IDENTITY,
            vec![[0.0, 0.0, 0.0]],
            vec![[0.0, 0.0, 1.0]],
            vec![0],
            vec![[0; 4]],
            vec![[0.0; 4]],
            vec![MorphTarget::new(vec![[1.0, 0.0, 0.0]], None, None)],
            vec![[0.0, 0.0]],
            vec![[1.0, 0.0, 0.0, 1.0]],
            vec![[1.0; 4]],
            vec![[0.0, 0.0]],
            None,
            None,
            PrimitiveTopology::Triangles,
            vec![0.75],
            false,
            None,
            0,
        );
        Avatar::new()
            .with_expressions(Expressions::new(vec![expression]))
            .with_primitives(vec![primitive])
    }

    #[test]
    fn expression_controls_persist_between_updates() {
        let mut runtime = AvatarRuntime::new(test_asset());
        runtime.set_constraints_enabled(false);
        runtime.set_spring_bone_enabled(false);
        runtime.set_expression("happy", 0.5).unwrap();

        let first = runtime.update(0.016).unwrap().gpu().draws().next().unwrap();
        assert_eq!(first.morph_weights, &[0.5]);
        let second = runtime.update(0.016).unwrap().gpu().draws().next().unwrap();
        assert_eq!(second.morph_weights, &[0.5]);
    }

    #[test]
    fn expression_morphs_start_at_zero_instead_of_gltf_weights() {
        let mut runtime = AvatarRuntime::new(test_asset());
        runtime.set_constraints_enabled(false);
        runtime.set_spring_bone_enabled(false);
        runtime.set_expression("happy", 0.25).unwrap();

        let draw = runtime.update(0.0).unwrap().gpu().draws().next().unwrap();
        assert_eq!(draw.morph_weights, &[0.25]);
    }

    #[test]
    fn frame_exposes_expression_evaluated_material_values() {
        let expression = Expression::new("happy")
            .with_material_color_binds(vec![MaterialColorBind {
                material_index: 0,
                color_type: MaterialColorType::Color,
                target_value: [1.0, 0.0, 0.0, 0.5],
            }])
            .with_texture_transform_binds(vec![TextureTransformBind {
                material_index: 0,
                scale: [2.0, 3.0],
                offset: [0.25, 0.5],
            }]);
        let mut material = Material::default();
        material.base_color_factor = [0.2, 0.4, 0.6, 1.0];
        let mut asset = Avatar::new().with_expressions(Expressions::new(vec![expression]));
        asset.materials = vec![material];
        let mut runtime = AvatarRuntime::new(asset);
        runtime.set_expression("happy", 0.5).unwrap();

        let frame = runtime.update(0.0).unwrap();
        let evaluated = &frame.evaluated_materials()[0];

        assert_eq!(evaluated.material_id, MaterialId::from_index(0));
        assert_eq!(evaluated.base_color_factor, [0.6, 0.2, 0.3, 0.75]);
        assert_eq!(evaluated.texture_transform.scale, [1.5, 2.0]);
        assert_eq!(evaluated.texture_transform.offset, [0.125, 0.25]);
    }

    #[test]
    fn cpu_and_gpu_paths_use_the_same_morph_weights() {
        let mut runtime = AvatarRuntime::new(test_asset());
        runtime.set_constraints_enabled(false);
        runtime.set_spring_bone_enabled(false);
        runtime.set_expression("happy", 1.0).unwrap();

        let frame = runtime.update(0.0).unwrap();
        let draw = frame.gpu().draws().next().unwrap();
        let mesh = frame.bake_cpu().pop().unwrap();
        assert_eq!(draw.morph_weights, &[1.0]);
        assert_eq!(mesh.positions[0], [1.0, 0.0, 0.0]);
    }

    #[test]
    fn reset_clears_controls_and_cached_morphs() {
        let mut runtime = AvatarRuntime::new(test_asset());
        runtime.set_expression("happy", 1.0).unwrap();
        runtime.update(0.0).unwrap();
        runtime.reset();

        assert_eq!(runtime.expression_weight("happy").unwrap(), 0.0);
        let draw = runtime.update(0.0).unwrap().gpu().draws().next().unwrap();
        assert_eq!(draw.morph_weights, &[0.0]);
    }

    #[test]
    fn shared_asset_does_not_share_instance_state() {
        let asset = Arc::new(test_asset());
        let mut first = AvatarRuntime::new(Arc::clone(&asset));
        let mut second = AvatarRuntime::new(asset);
        first.set_expression("happy", 1.0).unwrap();

        let first_weight = first
            .update(0.0)
            .unwrap()
            .gpu()
            .draws()
            .next()
            .unwrap()
            .morph_weights[0];
        let second_weight = second
            .update(0.0)
            .unwrap()
            .gpu()
            .draws()
            .next()
            .unwrap()
            .morph_weights[0];
        assert_eq!(first_weight, 1.0);
        assert_eq!(second_weight, 0.0);
    }

    #[test]
    fn rejects_invalid_runtime_inputs() {
        let mut runtime = AvatarRuntime::new(test_asset());
        assert!(matches!(
            runtime.set_expression("missing", 1.0),
            Err(ControlError::UnknownExpression(_))
        ));
        assert_eq!(
            runtime.update(f32::NAN).err(),
            Some(RuntimeError::InvalidDeltaTime)
        );
    }

    #[test]
    fn rejects_material_clock_overflow_without_mutating_time() {
        let mut runtime = AvatarRuntime::new(test_asset());
        runtime.set_constraints_enabled(false);
        runtime.set_spring_bone_enabled(false);

        runtime.update(f32::MAX).unwrap();
        let material_time_before_error = runtime.material_time;

        assert_eq!(
            runtime.update(f32::MAX).err(),
            Some(RuntimeError::MaterialTimeOverflow)
        );
        assert_eq!(runtime.material_time, material_time_before_error);
        assert!(runtime.material_time.is_finite());
    }

    #[test]
    fn rejects_animation_step_overflow_without_mutating_any_clock() {
        let mut runtime = AvatarRuntime::new(test_asset());
        runtime.set_constraints_enabled(false);
        runtime.set_spring_bone_enabled(false);
        runtime
            .play(
                VrmAnimation::new(f32::MAX),
                PlaybackOptions {
                    speed: f32::MAX,
                    ..PlaybackOptions::default()
                },
            )
            .unwrap();

        assert_eq!(
            runtime.update(2.0).err(),
            Some(RuntimeError::AnimationTimeOverflow)
        );
        assert_eq!(runtime.playback_time(), Some(0.0));
        assert_eq!(runtime.material_time, 0.0);
    }

    #[test]
    fn update_advances_animation_before_producing_the_frame() {
        let asset = Avatar::new()
            .with_humanoid(Humanoid::default().with_bone(HumanBone::Hips, 0))
            .with_nodes(vec![AvatarNode {
                index: 0,
                name: Some("hips".to_string()),
                parent: None,
                children: vec![],
                initial_translation: Vec3::ZERO,
                initial_rotation: Quat::IDENTITY,
                initial_scale: Vec3::ONE,
            }]);
        let clip = VrmAnimation::new(1.0).with_bone_track(
            HumanBone::Hips,
            BoneTrack::new().with_translation(Track::new(
                Interpolation::Linear,
                vec![
                    Keyframe::new(0.0, Vec3::ZERO),
                    Keyframe::new(1.0, Vec3::new(2.0, 0.0, 0.0)),
                ],
            )),
        );
        let mut runtime = AvatarRuntime::new(asset);
        runtime.set_constraints_enabled(false);
        runtime.set_spring_bone_enabled(false);
        runtime
            .play(
                clip,
                PlaybackOptions {
                    speed: 1.0,
                    mode: PlaybackMode::Once,
                    ..PlaybackOptions::default()
                },
            )
            .unwrap();

        let frame = runtime.update(0.5).unwrap();
        let translation = frame.world_matrices()[0].transform_point3(Vec3::ZERO);

        assert!(translation.abs_diff_eq(Vec3::new(1.0, 0.0, 0.0), 1.0e-5));
        assert_eq!(runtime.playback_time(), Some(0.5));
        assert!(runtime.is_playing());
    }

    #[test]
    fn play_rejects_malformed_keyframes() {
        let clip = VrmAnimation::new(1.0).with_bone_track(
            HumanBone::Hips,
            BoneTrack::new().with_rotation(Track::new(
                Interpolation::Linear,
                vec![Keyframe::new(f32::NAN, Quat::IDENTITY)],
            )),
        );
        let mut runtime = AvatarRuntime::new(test_asset());

        assert!(matches!(
            runtime.play(clip, PlaybackOptions::default()),
            Err(ControlError::InvalidAnimation(_))
        ));
    }
}