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
use super::*;
/// Parent accessor for `SkeletonJoint3D`.
impl SkeletonJoint3D {
/// Creates a new `SkeletonJoint3D`.
///
/// # Arguments
///
/// - `&str` - Joint label.
/// - `Option<usize>` - Optional parent joint index.
/// - `Transform3D` - Bind-pose local transform.
///
/// # Returns
///
/// - `Self` - Constructed joint record.
#[must_use]
pub fn new(name: &str, parent: Option<usize>, rest_transform: Transform3D) -> Self {
Self {
name: name.to_string(),
parent,
rest_transform,
}
}
/// Returns the optional parent joint index.
///
/// # Arguments
///
/// - `&Self` - Joint reference.
///
/// # Returns
///
/// - `Option<usize>` - Parent joint index if non-root.
#[must_use]
pub fn parent_index(&self) -> Option<usize> {
let Self { parent, .. } = self;
*parent
}
}
/// Keyframe sampling helpers for `JointTrack3D`.
impl JointTrack3D {
/// Creates a new `JointTrack3D` for `joint_index` sorting keyframes by timestamp.
///
/// # Arguments
///
/// - `usize` - Target joint index.
/// - `Vec<Keyframe3D>` - Unsorted or sorted keyframes.
///
/// # Returns
///
/// - `Self` - Ready animation track.
#[must_use]
pub fn new(joint_index: usize, mut keyframes: Vec<Keyframe3D>) -> Self {
keyframes.sort_by(|a: &Keyframe3D, b: &Keyframe3D| {
a.get_time_secs().total_cmp(&b.get_time_secs())
});
Self {
joint_index,
keyframes,
}
}
/// Samples this track at `time_secs` via O(log K) binary search, linearly interpolating between neighboring keyframes.
///
/// # Arguments
///
/// - `&Self` - Track reference.
/// - `f32` - Evaluation time in seconds.
/// - `Transform3D` - Fallback bind-pose transform when track is empty.
///
/// # Returns
///
/// - `Transform3D` - Interpolated local transform.
#[must_use]
pub fn sample(&self, time_secs: f32, fallback: Transform3D) -> Transform3D {
let keys: &[Keyframe3D] = self.get_keyframes().as_slice();
if keys.is_empty() {
return fallback;
}
if keys.len() == 1 || time_secs <= keys[0].get_time_secs() {
return keys[0].get_transform();
}
let last: Keyframe3D = keys[keys.len() - 1];
if time_secs >= last.get_time_secs() {
return last.get_transform();
}
let hi: usize = keys.partition_point(|k: &Keyframe3D| k.get_time_secs() <= time_secs);
let idx1: usize = hi.clamp(1, keys.len() - 1);
let k0: Keyframe3D = keys[idx1 - 1];
let k1: Keyframe3D = keys[idx1];
let span: f32 = (k1.get_time_secs() - k0.get_time_secs()).max(1e-5);
let alpha: f32 = ((time_secs - k0.get_time_secs()) / span).clamp(0.0, 1.0);
k0.get_transform().lerp(k1.get_transform(), alpha)
}
}
/// Clip construction and time normalization for `AnimationClip3D`.
impl AnimationClip3D {
/// Creates a new `AnimationClip3D`.
///
/// # Arguments
///
/// - `&str` - Clip name.
/// - `f32` - Total duration in seconds.
/// - `bool` - Looping flag.
///
/// # Returns
///
/// - `Self` - Empty animation clip ready for tracks.
#[must_use]
pub fn new(name: &str, duration_secs: f32, looping: bool) -> Self {
Self {
name: name.to_string(),
duration_secs: duration_secs.max(1e-4),
looping,
tracks: Vec::new(),
}
}
/// Appends a `JointTrack3D` to this clip and returns `self` for fluent chaining.
///
/// # Arguments
///
/// - `Self` - Base animation clip.
/// - `JointTrack3D` - Joint animation track.
///
/// # Returns
///
/// - `Self` - Updated animation clip.
#[must_use]
pub fn with_track(mut self, track: JointTrack3D) -> Self {
self.get_mut_tracks().push(track);
self
}
/// Normalizes raw playback time into `[0.0, duration_secs]` respecting `looping`.
///
/// # Arguments
///
/// - `&Self` - Clip reference.
/// - `f32` - Unclamped playback time in seconds.
///
/// # Returns
///
/// - `f32` - Normalized local evaluation timestamp.
#[must_use]
pub fn normalize_time(&self, time_secs: f32) -> f32 {
let dur: f32 = self.get_duration_secs().max(1e-4);
if self.get_looping() {
time_secs - (time_secs / dur).floor() * dur
} else {
time_secs.clamp(0.0, dur)
}
}
}
/// Hierarchical forward-kinematics solver for `SkeletonRig3D`.
impl SkeletonRig3D {
/// Appends a joint to the skeleton hierarchy and returns its assigned index.
///
/// # Arguments
///
/// - `&Self` - Mutable skeleton rig.
/// - `&str` - Joint label.
/// - `Option<usize>` - Optional parent joint index.
/// - `Transform3D` - Bind-pose local transform.
///
/// # Returns
///
/// - `usize` - Assigned joint index.
pub fn add_joint(
&mut self,
name: &str,
parent: Option<usize>,
rest_transform: Transform3D,
) -> usize {
let idx: usize = self.get_joints().len();
self.get_mut_joints()
.push(SkeletonJoint3D::new(name, parent, rest_transform));
idx
}
/// Samples normalized local joint transforms at `time_secs` for `clip` into an existing `SkeletonPoseSnapshot` with zero allocations.
///
/// # Arguments
///
/// - `&Self` - Skeleton rig reference.
/// - `&AnimationClip3D` - Active animation clip.
/// - `f32` - Playback timestamp in seconds.
/// - `bool` - Whether this sample represents a discontinuous animation cut.
/// - `&mut SkeletonPoseSnapshot` - Reusable destination pose snapshot overwritten in place.
pub fn sample_pose_snapshot_into(
&self,
clip: &AnimationClip3D,
time_secs: f32,
cut: bool,
out: &mut SkeletonPoseSnapshot,
) {
let t: f32 = clip.normalize_time(time_secs);
let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
let locals: &mut Vec<Transform3D> = out.get_mut_joint_transforms();
locals.clear();
locals.reserve(joints.len());
for joint in joints.iter() {
locals.push(joint.get_rest_transform());
}
for track in clip.get_tracks().iter() {
let j: usize = track.get_joint_index();
if j < locals.len() {
locals[j] = track.sample(t, locals[j]);
}
}
out.set_cut(cut);
}
/// Samples normalized local joint transforms at `time_secs` for `clip` into a `SkeletonPoseSnapshot`.
///
/// # Arguments
///
/// - `&Self` - Skeleton rig reference.
/// - `&AnimationClip3D` - Active animation clip.
/// - `f32` - Playback timestamp in seconds.
/// - `bool` - Whether this sample represents a discontinuous animation cut.
///
/// # Returns
///
/// - `SkeletonPoseSnapshot` - Immutable local joint pose snapshot suitable for render-time interpolation.
#[must_use]
pub fn sample_pose_snapshot(
&self,
clip: &AnimationClip3D,
time_secs: f32,
cut: bool,
) -> SkeletonPoseSnapshot {
let mut out: SkeletonPoseSnapshot = SkeletonPoseSnapshot::default();
self.sample_pose_snapshot_into(clip, time_secs, cut, &mut out);
out
}
/// Evaluates hierarchical world-space `Mat4` joint palettes from `pose` into a reusable caller buffer with zero allocations.
///
/// # Arguments
///
/// - `&Self` - Skeleton rig reference.
/// - `&SkeletonPoseSnapshot` - Local joint pose snapshot.
/// - `Transform3D` - Root world transform of the animated actor.
/// - `&mut Vec<Mat4>` - Reusable output palette buffer cleared and populated in place.
pub fn evaluate_world_matrices_into(
&self,
pose: &SkeletonPoseSnapshot,
root_world: Transform3D,
out: &mut Vec<Mat4>,
) {
let joints: &[SkeletonJoint3D] = self.get_joints().as_slice();
let locals: &[Transform3D] = pose.get_joint_transforms().as_slice();
let root_m: Mat4 = root_world.to_mat4();
out.clear();
out.reserve(joints.len());
for (idx, joint) in joints.iter().enumerate() {
let local_tr: Transform3D = locals
.get(idx)
.copied()
.unwrap_or_else(|| joint.get_rest_transform());
let local_m: Mat4 = local_tr.to_mat4();
let parent_m: Mat4 = match joint.parent_index() {
Some(p) if p < out.len() => out[p],
_ => root_m,
};
out.push(parent_m.mul(local_m));
}
}
/// Evaluates hierarchical world-space `Mat4` joint palettes from an interpolated `SkeletonPoseSnapshot`.
///
/// # Arguments
///
/// - `&Self` - Skeleton rig reference.
/// - `&SkeletonPoseSnapshot` - Local joint pose snapshot (e.g. interpolated between two fixed steps).
/// - `Transform3D` - Interpolated root world transform of the animated actor.
///
/// # Returns
///
/// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
#[must_use]
pub fn evaluate_world_matrices(
&self,
pose: &SkeletonPoseSnapshot,
root_world: Transform3D,
) -> Vec<Mat4> {
let mut world: Vec<Mat4> = Vec::with_capacity(self.get_joints().len());
self.evaluate_world_matrices_into(pose, root_world, &mut world);
world
}
/// Samples `clip` at `time_secs` and writes world-space `Mat4` joint palettes into reusable scratch buffers with zero allocations.
///
/// # Arguments
///
/// - `&Self` - Skeleton rig reference.
/// - `&AnimationClip3D` - Active animation clip.
/// - `f32` - Playback timestamp in seconds.
/// - `Transform3D` - Root world transform of the animated actor.
/// - `&mut SkeletonPoseSnapshot` - Reusable local pose scratch buffer.
/// - `&mut Vec<Mat4>` - Reusable world-matrix output buffer.
pub fn sample_world_matrices_into(
&self,
clip: &AnimationClip3D,
time_secs: f32,
root_world: Transform3D,
pose_scratch: &mut SkeletonPoseSnapshot,
out_matrices: &mut Vec<Mat4>,
) {
self.sample_pose_snapshot_into(clip, time_secs, false, pose_scratch);
self.evaluate_world_matrices_into(pose_scratch, root_world, out_matrices);
}
/// Evaluates hierarchical world-space `Mat4` joint palettes at `time_secs` for `clip`.
///
/// # Arguments
///
/// - `&Self` - Skeleton rig reference.
/// - `&AnimationClip3D` - Active animation clip.
/// - `f32` - Playback timestamp in seconds.
/// - `Transform3D` - Root world transform of the animated actor.
///
/// # Returns
///
/// - `Vec<Mat4>` - World-space bone matrices indexed by joint id.
#[must_use]
pub fn sample_world_matrices(
&self,
clip: &AnimationClip3D,
time_secs: f32,
root_world: Transform3D,
) -> Vec<Mat4> {
let pose: SkeletonPoseSnapshot = self.sample_pose_snapshot(clip, time_secs, false);
self.evaluate_world_matrices(&pose, root_world)
}
}