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` via O(log K) binary search, 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 let hi: usize = keys.partition_point(|k: &Keyframe3D| k.get_time_secs() <= time_secs);
89 let idx1: usize = hi.clamp(1, keys.len() - 1);
90 let k0: Keyframe3D = keys[idx1 - 1];
91 let k1: Keyframe3D = keys[idx1];
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 k0.get_transform().lerp(k1.get_transform(), alpha)
95 }
96}
97
98/// Clip construction and time normalization for `AnimationClip3D`.
99impl AnimationClip3D {
100 /// Creates a new `AnimationClip3D`.
101 ///
102 /// # Arguments
103 ///
104 /// - `&str` - Clip name.
105 /// - `f32` - Total duration in seconds.
106 /// - `bool` - Looping flag.
107 ///
108 /// # Returns
109 ///
110 /// - `Self` - Empty animation clip ready for tracks.
111 #[must_use]
112 pub fn new(name: &str, duration_secs: f32, looping: bool) -> Self {
113 Self {
114 name: name.to_string(),
115 duration_secs: duration_secs.max(1e-4),
116 looping,
117 tracks: Vec::new(),
118 }
119 }
120
121 /// Appends a `JointTrack3D` to this clip and returns `self` for fluent chaining.
122 ///
123 /// # Arguments
124 ///
125 /// - `Self` - Base animation clip.
126 /// - `JointTrack3D` - Joint animation track.
127 ///
128 /// # Returns
129 ///
130 /// - `Self` - Updated animation clip.
131 #[must_use]
132 pub fn with_track(mut self, track: JointTrack3D) -> Self {
133 self.get_mut_tracks().push(track);
134 self
135 }
136
137 /// Normalizes raw playback time into `[0.0, duration_secs]` respecting `looping`.
138 ///
139 /// # Arguments
140 ///
141 /// - `&Self` - Clip reference.
142 /// - `f32` - Unclamped playback time in seconds.
143 ///
144 /// # Returns
145 ///
146 /// - `f32` - Normalized local evaluation timestamp.
147 #[must_use]
148 pub fn normalize_time(&self, time_secs: f32) -> f32 {
149 let dur: f32 = self.get_duration_secs().max(1e-4);
150 if self.get_looping() {
151 time_secs - (time_secs / dur).floor() * dur
152 } else {
153 time_secs.clamp(0.0, dur)
154 }
155 }
156}
157
158/// Hierarchical forward-kinematics solver for `SkeletonRig3D`.
159impl SkeletonRig3D {
160 /// Appends a joint to the skeleton hierarchy and returns its assigned index.
161 ///
162 /// # Arguments
163 ///
164 /// - `&Self` - Mutable skeleton rig.
165 /// - `&str` - Joint label.
166 /// - `Option<usize>` - Optional parent joint index.
167 /// - `Transform3D` - Bind-pose local transform.
168 ///
169 /// # Returns
170 ///
171 /// - `usize` - Assigned joint index.
172 pub fn add_joint(
173 &mut self,
174 name: &str,
175 parent: Option<usize>,
176 rest_transform: Transform3D,
177 ) -> usize {
178 let idx: usize = self.get_joints().len();
179 self.get_mut_joints()
180 .push(SkeletonJoint3D::new(name, parent, rest_transform));
181 idx
182 }
183
184 /// Samples normalized local joint transforms at `time_secs` for `clip` into an existing `SkeletonPoseSnapshot` with zero allocations.
185 ///
186 /// # Arguments
187 ///
188 /// - `&Self` - Skeleton rig reference.
189 /// - `&AnimationClip3D` - Active animation clip.
190 /// - `f32` - Playback timestamp in seconds.
191 /// - `bool` - Whether this sample represents a discontinuous animation cut.
192 /// - `&mut SkeletonPoseSnapshot` - Reusable destination pose snapshot overwritten in place.
193 pub fn sample_pose_snapshot_into(
194 &self,
195 clip: &AnimationClip3D,
196 time_secs: f32,
197 cut: bool,
198 out: &mut SkeletonPoseSnapshot,
199 ) {
200 let t: f32 = clip.normalize_time(time_secs);
201 let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
202 let locals: &mut Vec<Transform3D> = out.get_mut_joint_transforms();
203 locals.clear();
204 locals.reserve(joints.len());
205 for joint in joints.iter() {
206 locals.push(joint.get_rest_transform());
207 }
208 for track in clip.get_tracks().iter() {
209 let j: usize = track.get_joint_index();
210 if j < locals.len() {
211 locals[j] = track.sample(t, locals[j]);
212 }
213 }
214 out.set_cut(cut);
215 }
216
217 /// Samples normalized local joint transforms at `time_secs` for `clip` into a `SkeletonPoseSnapshot`.
218 ///
219 /// # Arguments
220 ///
221 /// - `&Self` - Skeleton rig reference.
222 /// - `&AnimationClip3D` - Active animation clip.
223 /// - `f32` - Playback timestamp in seconds.
224 /// - `bool` - Whether this sample represents a discontinuous animation cut.
225 ///
226 /// # Returns
227 ///
228 /// - `SkeletonPoseSnapshot` - Immutable local joint pose snapshot suitable for render-time interpolation.
229 #[must_use]
230 pub fn sample_pose_snapshot(
231 &self,
232 clip: &AnimationClip3D,
233 time_secs: f32,
234 cut: bool,
235 ) -> SkeletonPoseSnapshot {
236 let mut out: SkeletonPoseSnapshot = SkeletonPoseSnapshot::default();
237 self.sample_pose_snapshot_into(clip, time_secs, cut, &mut out);
238 out
239 }
240
241 /// Evaluates hierarchical world-space `Mat4` joint palettes from `pose` into a reusable caller buffer with zero allocations.
242 ///
243 /// # Arguments
244 ///
245 /// - `&Self` - Skeleton rig reference.
246 /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot.
247 /// - `Transform3D` - Root world transform of the animated actor.
248 /// - `&mut Vec<Mat4>` - Reusable output palette buffer cleared and populated in place.
249 pub fn evaluate_world_matrices_into(
250 &self,
251 pose: &SkeletonPoseSnapshot,
252 root_world: Transform3D,
253 out: &mut Vec<Mat4>,
254 ) {
255 let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
256 let locals: &[Transform3D] = pose.get_joint_transforms().as_slice();
257 let root_m: Mat4 = root_world.to_mat4();
258 out.clear();
259 out.reserve(joints.len());
260 for (idx, joint) in joints.iter().enumerate() {
261 let local_tr: Transform3D = locals
262 .get(idx)
263 .copied()
264 .unwrap_or_else(|| joint.get_rest_transform());
265 let local_m: Mat4 = local_tr.to_mat4();
266 let parent_m: Mat4 = match joint.parent_index() {
267 Some(p) if p < out.len() => out[p],
268 _ => root_m,
269 };
270 out.push(parent_m.mul(local_m));
271 }
272 }
273
274 /// Evaluates hierarchical world-space `Mat4` joint palettes from an interpolated `SkeletonPoseSnapshot`.
275 ///
276 /// # Arguments
277 ///
278 /// - `&Self` - Skeleton rig reference.
279 /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot (e.g. interpolated between two fixed steps).
280 /// - `Transform3D` - Interpolated root world transform of the animated actor.
281 ///
282 /// # Returns
283 ///
284 /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
285 #[must_use]
286 pub fn evaluate_world_matrices(
287 &self,
288 pose: &SkeletonPoseSnapshot,
289 root_world: Transform3D,
290 ) -> Vec<Mat4> {
291 let mut world: Vec<Mat4> = Vec::with_capacity(self.get_joints().len());
292 self.evaluate_world_matrices_into(pose, root_world, &mut world);
293 world
294 }
295
296 /// Samples `clip` at `time_secs` and writes world-space `Mat4` joint palettes into reusable scratch buffers with zero allocations.
297 ///
298 /// # Arguments
299 ///
300 /// - `&Self` - Skeleton rig reference.
301 /// - `&AnimationClip3D` - Active animation clip.
302 /// - `f32` - Playback timestamp in seconds.
303 /// - `Transform3D` - Root world transform of the animated actor.
304 /// - `&mut SkeletonPoseSnapshot` - Reusable local pose scratch buffer.
305 /// - `&mut Vec<Mat4>` - Reusable world-matrix output buffer.
306 pub fn sample_world_matrices_into(
307 &self,
308 clip: &AnimationClip3D,
309 time_secs: f32,
310 root_world: Transform3D,
311 pose_scratch: &mut SkeletonPoseSnapshot,
312 out_matrices: &mut Vec<Mat4>,
313 ) {
314 self.sample_pose_snapshot_into(clip, time_secs, false, pose_scratch);
315 self.evaluate_world_matrices_into(pose_scratch, root_world, out_matrices);
316 }
317
318 /// Evaluates hierarchical world-space `Mat4` joint palettes at `time_secs` for `clip`.
319 ///
320 /// # Arguments
321 ///
322 /// - `&Self` - Skeleton rig reference.
323 /// - `&AnimationClip3D` - Active animation clip.
324 /// - `f32` - Playback timestamp in seconds.
325 /// - `Transform3D` - Root world transform of the animated actor.
326 ///
327 /// # Returns
328 ///
329 /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
330 #[must_use]
331 pub fn sample_world_matrices(
332 &self,
333 clip: &AnimationClip3D,
334 time_secs: f32,
335 root_world: Transform3D,
336 ) -> Vec<Mat4> {
337 let pose: SkeletonPoseSnapshot = self.sample_pose_snapshot(clip, time_secs, false);
338 self.evaluate_world_matrices(&pose, root_world)
339 }
340}