euv_core/game/engine3d/animation/impl.rs
1use super::*;
2
3/// Parent accessor for `SkeletonJoint3D`.
4impl SkeletonJoint3D {
5 /// Creates a new `SkeletonJoint3D`.
6 ///
7 /// # Arguments
8 ///
9 /// - `&str` - Joint label.
10 /// - `Option<usize>` - Optional parent joint index.
11 /// - `Transform3D` - Bind-pose local transform.
12 ///
13 /// # Returns
14 ///
15 /// - `Self` - Constructed joint record.
16 #[must_use]
17 pub fn new(name: &str, parent: Option<usize>, rest_transform: Transform3D) -> Self {
18 Self {
19 name: name.to_string(),
20 parent,
21 rest_transform,
22 }
23 }
24
25 /// Returns the optional parent joint index.
26 ///
27 /// # Arguments
28 ///
29 /// - `&Self` - Joint reference.
30 ///
31 /// # Returns
32 ///
33 /// - `Option<usize>` - Parent joint index if non-root.
34 #[must_use]
35 pub fn parent_index(&self) -> Option<usize> {
36 let Self { parent, .. } = self;
37 *parent
38 }
39}
40
41/// Keyframe sampling helpers for `JointTrack3D`.
42impl JointTrack3D {
43 /// Creates a new `JointTrack3D` for `joint_index` sorting keyframes by timestamp.
44 ///
45 /// # Arguments
46 ///
47 /// - `usize` - Target joint index.
48 /// - `Vec<Keyframe3D>` - Unsorted or sorted keyframes.
49 ///
50 /// # Returns
51 ///
52 /// - `Self` - Ready animation track.
53 #[must_use]
54 pub fn new(joint_index: usize, mut keyframes: Vec<Keyframe3D>) -> Self {
55 keyframes.sort_by(|a: &Keyframe3D, b: &Keyframe3D| {
56 a.get_time_secs().total_cmp(&b.get_time_secs())
57 });
58 Self {
59 joint_index,
60 keyframes,
61 }
62 }
63
64 /// Samples this track at `time_secs`, linearly interpolating between neighboring keyframes.
65 ///
66 /// # Arguments
67 ///
68 /// - `&Self` - Track reference.
69 /// - `f32` - Evaluation time in seconds.
70 /// - `Transform3D` - Fallback bind-pose transform when track is empty.
71 ///
72 /// # Returns
73 ///
74 /// - `Transform3D` - Interpolated local transform.
75 #[must_use]
76 pub fn sample(&self, time_secs: f32, fallback: Transform3D) -> Transform3D {
77 let keys: &[Keyframe3D] = self.get_keyframes().as_slice();
78 if keys.is_empty() {
79 return fallback;
80 }
81 if keys.len() == 1 || time_secs <= keys[0].get_time_secs() {
82 return keys[0].get_transform();
83 }
84 let last: Keyframe3D = keys[keys.len() - 1];
85 if time_secs >= last.get_time_secs() {
86 return last.get_transform();
87 }
88 for i in 0..(keys.len() - 1) {
89 let k0: Keyframe3D = keys[i];
90 let k1: Keyframe3D = keys[i + 1];
91 if time_secs <= k1.get_time_secs() {
92 let span: f32 = (k1.get_time_secs() - k0.get_time_secs()).max(1e-5);
93 let alpha: f32 = ((time_secs - k0.get_time_secs()) / span).clamp(0.0, 1.0);
94 return k0.get_transform().lerp(k1.get_transform(), alpha);
95 }
96 }
97 last.get_transform()
98 }
99}
100
101/// Clip construction and time normalization for `AnimationClip3D`.
102impl AnimationClip3D {
103 /// Creates a new `AnimationClip3D`.
104 ///
105 /// # Arguments
106 ///
107 /// - `&str` - Clip name.
108 /// - `f32` - Total duration in seconds.
109 /// - `bool` - Looping flag.
110 ///
111 /// # Returns
112 ///
113 /// - `Self` - Empty animation clip ready for tracks.
114 #[must_use]
115 pub fn new(name: &str, duration_secs: f32, looping: bool) -> Self {
116 Self {
117 name: name.to_string(),
118 duration_secs: duration_secs.max(1e-4),
119 looping,
120 tracks: Vec::new(),
121 }
122 }
123
124 /// Appends a `JointTrack3D` to this clip and returns `self` for fluent chaining.
125 ///
126 /// # Arguments
127 ///
128 /// - `Self` - Base animation clip.
129 /// - `JointTrack3D` - Joint animation track.
130 ///
131 /// # Returns
132 ///
133 /// - `Self` - Updated animation clip.
134 #[must_use]
135 pub fn with_track(mut self, track: JointTrack3D) -> Self {
136 self.get_mut_tracks().push(track);
137 self
138 }
139
140 /// Normalizes raw playback time into `[0.0, duration_secs]` respecting `looping`.
141 ///
142 /// # Arguments
143 ///
144 /// - `&Self` - Clip reference.
145 /// - `f32` - Unclamped playback time in seconds.
146 ///
147 /// # Returns
148 ///
149 /// - `f32` - Normalized local evaluation timestamp.
150 #[must_use]
151 pub fn normalize_time(&self, time_secs: f32) -> f32 {
152 let dur: f32 = self.get_duration_secs().max(1e-4);
153 if self.get_looping() {
154 time_secs.rem_euclid(dur)
155 } else {
156 time_secs.clamp(0.0, dur)
157 }
158 }
159}
160
161/// Hierarchical forward-kinematics solver for `SkeletonRig3D`.
162impl SkeletonRig3D {
163 /// Appends a joint to the skeleton hierarchy and returns its assigned index.
164 ///
165 /// # Arguments
166 ///
167 /// - `&Self` - Mutable skeleton rig.
168 /// - `&str` - Joint label.
169 /// - `Option<usize>` - Optional parent joint index.
170 /// - `Transform3D` - Bind-pose local transform.
171 ///
172 /// # Returns
173 ///
174 /// - `usize` - Assigned joint index.
175 pub fn add_joint(
176 &mut self,
177 name: &str,
178 parent: Option<usize>,
179 rest_transform: Transform3D,
180 ) -> usize {
181 let idx: usize = self.get_joints().len();
182 self.get_mut_joints()
183 .push(SkeletonJoint3D::new(name, parent, rest_transform));
184 idx
185 }
186
187 /// Evaluates hierarchical world-space `Mat4` joint palettes at `time_secs` for `clip`.
188 ///
189 /// # Arguments
190 ///
191 /// - `&Self` - Skeleton rig reference.
192 /// - `&AnimationClip3D` - Active animation clip.
193 /// - `f32` - Playback timestamp in seconds.
194 /// - `Transform3D` - Root world transform of the animated actor.
195 ///
196 /// # Returns
197 ///
198 /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
199 #[must_use]
200 pub fn sample_world_matrices(
201 &self,
202 clip: &AnimationClip3D,
203 time_secs: f32,
204 root_world: Transform3D,
205 ) -> Vec<Mat4> {
206 let t: f32 = clip.normalize_time(time_secs);
207 let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
208 let mut locals: Vec<Transform3D> = joints
209 .iter()
210 .map(SkeletonJoint3D::get_rest_transform)
211 .collect();
212 for track in clip.get_tracks().iter() {
213 let j: usize = track.get_joint_index();
214 if j < locals.len() {
215 locals[j] = track.sample(t, locals[j]);
216 }
217 }
218 let root_m: Mat4 = root_world.to_mat4();
219 let mut world: Vec<Mat4> = Vec::with_capacity(joints.len());
220 for (idx, joint) in joints.iter().enumerate() {
221 let local_m: Mat4 = locals[idx].to_mat4();
222 let parent_m: Mat4 = match joint.parent_index() {
223 Some(p) if p < world.len() => world[p],
224 _ => root_m,
225 };
226 world.push(parent_m.mul(local_m));
227 }
228 world
229 }
230}