Skip to main content

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(|alpha_val: &Keyframe3D, blue_val: &Keyframe3D| {
56            alpha_val
57                .get_time_secs()
58                .total_cmp(&blue_val.get_time_secs())
59        });
60        Self {
61            joint_index,
62            keyframes,
63        }
64    }
65
66    /// Samples this track at `time_secs` via O(log K) binary search, linearly interpolating between neighboring keyframes.
67    ///
68    /// # Arguments
69    ///
70    /// - `&Self` - Track reference.
71    /// - `f32` - Evaluation time in seconds.
72    /// - `Transform3D` - Fallback bind-pose transform when track is empty.
73    ///
74    /// # Returns
75    ///
76    /// - `Transform3D` - Interpolated local transform.
77    #[must_use]
78    pub fn sample(&self, time_secs: f32, fallback: Transform3D) -> Transform3D {
79        let keys: &[Keyframe3D] = self.get_keyframes().as_slice();
80        if keys.is_empty() {
81            return fallback;
82        }
83        if keys.len() == 1 || time_secs <= keys[0].get_time_secs() {
84            return keys[0].get_transform();
85        }
86        let last: Keyframe3D = keys[keys.len() - 1];
87        if time_secs >= last.get_time_secs() {
88            return last.get_transform();
89        }
90        let hi: usize = keys
91            .partition_point(|entry_index: &Keyframe3D| entry_index.get_time_secs() <= time_secs);
92        let idx1: usize = hi.clamp(1, keys.len() - 1);
93        let k0: Keyframe3D = keys[idx1 - 1];
94        let k1: Keyframe3D = keys[idx1];
95        let span: f32 = (k1.get_time_secs() - k0.get_time_secs()).max(1e-5);
96        let alpha: f32 = ((time_secs - k0.get_time_secs()) / span).clamp(0.0, 1.0);
97        k0.get_transform().lerp(k1.get_transform(), alpha)
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 - (time_secs / dur).floor() * 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    /// Samples normalized local joint transforms at `time_secs` for `clip` into an existing `SkeletonPoseSnapshot` with zero allocations.
188    ///
189    /// # Arguments
190    ///
191    /// - `&Self` - Skeleton rig reference.
192    /// - `&AnimationClip3D` - Active animation clip.
193    /// - `f32` - Playback timestamp in seconds.
194    /// - `bool` - Whether this sample represents a discontinuous animation cut.
195    /// - `&mut SkeletonPoseSnapshot` - Reusable destination pose snapshot overwritten in place.
196    pub fn sample_pose_snapshot_into(
197        &self,
198        clip: &AnimationClip3D,
199        time_secs: f32,
200        cut: bool,
201        out: &mut SkeletonPoseSnapshot,
202    ) {
203        let blend_factor: f32 = clip.normalize_time(time_secs);
204        let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
205        let locals: &mut Vec<Transform3D> = out.get_mut_joint_transforms();
206        locals.clear();
207        locals.reserve(joints.len());
208        for joint in joints.iter() {
209            locals.push(joint.get_rest_transform());
210        }
211        for track in clip.get_tracks().iter() {
212            let inner_index: usize = track.get_joint_index();
213            if inner_index < locals.len() {
214                locals[inner_index] = track.sample(blend_factor, locals[inner_index]);
215            }
216        }
217        out.set_cut(cut);
218    }
219
220    /// Samples normalized local joint transforms at `time_secs` for `clip` into a `SkeletonPoseSnapshot`.
221    ///
222    /// # Arguments
223    ///
224    /// - `&Self` - Skeleton rig reference.
225    /// - `&AnimationClip3D` - Active animation clip.
226    /// - `f32` - Playback timestamp in seconds.
227    /// - `bool` - Whether this sample represents a discontinuous animation cut.
228    ///
229    /// # Returns
230    ///
231    /// - `SkeletonPoseSnapshot` - Immutable local joint pose snapshot suitable for render-time interpolation.
232    #[must_use]
233    pub fn sample_pose_snapshot(
234        &self,
235        clip: &AnimationClip3D,
236        time_secs: f32,
237        cut: bool,
238    ) -> SkeletonPoseSnapshot {
239        let mut out: SkeletonPoseSnapshot = SkeletonPoseSnapshot::default();
240        self.sample_pose_snapshot_into(clip, time_secs, cut, &mut out);
241        out
242    }
243
244    /// Evaluates hierarchical world-space `Mat4` joint palettes from `pose` into a reusable caller buffer with zero allocations.
245    ///
246    /// # Arguments
247    ///
248    /// - `&Self` - Skeleton rig reference.
249    /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot.
250    /// - `Transform3D` - Root world transform of the animated actor.
251    /// - `&mut Vec<Mat4>` - Reusable output palette buffer cleared and populated in place.
252    pub fn evaluate_world_matrices_into(
253        &self,
254        pose: &SkeletonPoseSnapshot,
255        root_world: Transform3D,
256        out: &mut Vec<Mat4>,
257    ) {
258        let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
259        let locals: &[Transform3D] = pose.get_joint_transforms().as_slice();
260        let root_m: Mat4 = root_world.to_mat4();
261        out.clear();
262        out.reserve(joints.len());
263        for (idx, joint) in joints.iter().enumerate() {
264            let local_tr: Transform3D = locals
265                .get(idx)
266                .copied()
267                .unwrap_or_else(|| joint.get_rest_transform());
268            let local_m: Mat4 = local_tr.to_mat4();
269            let parent_m: Mat4 = match joint.parent_index() {
270                Some(point_val) if point_val < out.len() => out[point_val],
271                _ => root_m,
272            };
273            out.push(parent_m.mul(local_m));
274        }
275    }
276
277    /// Evaluates hierarchical world-space `Mat4` joint palettes from an interpolated `SkeletonPoseSnapshot`.
278    ///
279    /// # Arguments
280    ///
281    /// - `&Self` - Skeleton rig reference.
282    /// - `&SkeletonPoseSnapshot` - Local joint pose snapshot (e.g. interpolated between two fixed steps).
283    /// - `Transform3D` - Interpolated root world transform of the animated actor.
284    ///
285    /// # Returns
286    ///
287    /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
288    #[must_use]
289    pub fn evaluate_world_matrices(
290        &self,
291        pose: &SkeletonPoseSnapshot,
292        root_world: Transform3D,
293    ) -> Vec<Mat4> {
294        let mut world: Vec<Mat4> = Vec::with_capacity(self.get_joints().len());
295        self.evaluate_world_matrices_into(pose, root_world, &mut world);
296        world
297    }
298
299    /// Samples `clip` at `time_secs` and writes world-space `Mat4` joint palettes into reusable scratch buffers with zero allocations.
300    ///
301    /// # Arguments
302    ///
303    /// - `&Self` - Skeleton rig reference.
304    /// - `&AnimationClip3D` - Active animation clip.
305    /// - `f32` - Playback timestamp in seconds.
306    /// - `Transform3D` - Root world transform of the animated actor.
307    /// - `&mut SkeletonPoseSnapshot` - Reusable local pose scratch buffer.
308    /// - `&mut Vec<Mat4>` - Reusable world-matrix output buffer.
309    pub fn sample_world_matrices_into(
310        &self,
311        clip: &AnimationClip3D,
312        time_secs: f32,
313        root_world: Transform3D,
314        pose_scratch: &mut SkeletonPoseSnapshot,
315        out_matrices: &mut Vec<Mat4>,
316    ) {
317        self.sample_pose_snapshot_into(clip, time_secs, false, pose_scratch);
318        self.evaluate_world_matrices_into(pose_scratch, root_world, out_matrices);
319    }
320
321    /// Evaluates hierarchical world-space `Mat4` joint palettes at `time_secs` for `clip`.
322    ///
323    /// # Arguments
324    ///
325    /// - `&Self` - Skeleton rig reference.
326    /// - `&AnimationClip3D` - Active animation clip.
327    /// - `f32` - Playback timestamp in seconds.
328    /// - `Transform3D` - Root world transform of the animated actor.
329    ///
330    /// # Returns
331    ///
332    /// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
333    #[must_use]
334    pub fn sample_world_matrices(
335        &self,
336        clip: &AnimationClip3D,
337        time_secs: f32,
338        root_world: Transform3D,
339    ) -> Vec<Mat4> {
340        let pose: SkeletonPoseSnapshot = self.sample_pose_snapshot(clip, time_secs, false);
341        self.evaluate_world_matrices(&pose, root_world)
342    }
343
344    /// Evaluates 4-bone linear-blend vertex skinning from bind-pose vertices and joint palette into `out_vertices` with zero allocations.
345    ///
346    /// # Arguments
347    ///
348    /// - `&[Vertex3D]` - Bind-pose mesh vertices.
349    /// - `&[SkinWeight3D]` - Matching per-vertex joint indices and weights.
350    /// - `&[Mat4]` - World or skinning joint palette matrices.
351    /// - `&mut Vec<Vertex3D>` - Reusable destination skinned vertex buffer overwritten in place.
352    pub fn skin_vertices_into(
353        &self,
354        bind_vertices: &[Vertex3D],
355        skin_weights: &[SkinWeight3D],
356        world_matrices: &[Mat4],
357        out_vertices: &mut Vec<Vertex3D>,
358    ) {
359        let vertex_count: usize = bind_vertices.len().min(skin_weights.len());
360        out_vertices.clear();
361        out_vertices.reserve(vertex_count);
362        if world_matrices.is_empty() {
363            out_vertices.extend_from_slice(&bind_vertices[..vertex_count]);
364            return;
365        }
366        let max_joint: usize = world_matrices.len() - 1;
367        for vertex_idx in 0..vertex_count {
368            let bind_vertex: Vertex3D = bind_vertices[vertex_idx];
369            let bind_pos: Vec3 = bind_vertex.get_position();
370            let bind_normal: Vec3 = bind_vertex.get_normal();
371            let skin: SkinWeight3D = skin_weights[vertex_idx];
372            let indices: [u16; 4] = skin.get_joint_indices();
373            let weights: [f32; 4] = skin.get_weights();
374            let mut skinned_pos: Vec3 = Vec3::zero();
375            let mut skinned_normal: Vec3 = Vec3::zero();
376            let mut weight_sum: f32 = 0.0;
377            for lane in 0..4usize {
378                let bone_weight: f32 = weights[lane];
379                if bone_weight <= 1e-6 {
380                    continue;
381                }
382                let joint_idx: usize = (indices[lane] as usize).min(max_joint);
383                let bone_matrix: Mat4 = world_matrices[joint_idx];
384                skinned_pos = skinned_pos.add(bone_matrix.mul_point3(bind_pos).scale(bone_weight));
385                skinned_normal =
386                    skinned_normal.add(bone_matrix.mul_vec3(bind_normal).scale(bone_weight));
387                weight_sum += bone_weight;
388            }
389            if weight_sum > 1e-5 {
390                let inv_weight: f32 = 1.0 / weight_sum;
391                let final_pos: Vec3 = skinned_pos.scale(inv_weight);
392                let final_normal: Vec3 = if skinned_normal.length_sq() > 1e-8 {
393                    skinned_normal.normalize()
394                } else {
395                    bind_normal
396                };
397                out_vertices.push(Vertex3D::new(final_pos, final_normal));
398            } else {
399                out_vertices.push(bind_vertex);
400            }
401        }
402    }
403}