1mod clip;
31mod curve;
32mod joint;
33mod keyframe;
34mod pose;
35
36pub use clip::{AnimClip, AnimWrapMode};
37pub use curve::AnimCurve;
38pub use joint::{Joint, JointDegreesOfFreedom, JointRotationLimits};
39pub use keyframe::{AnimCurveValue, AnimInterpolation, Keyframe};
40pub use pose::SkelPose;
41
42use crate::{
43 Error, Result,
44 core::{Duration, Transform},
45};
46
47fn checked_sample_count(frame_count: u32, joint_count: u32) -> Option<usize> {
48 if frame_count == 0 || joint_count == 0 {
49 return None;
50 }
51 (frame_count as usize).checked_mul(joint_count as usize)
52}
53
54fn validate_transforms(transforms: &[Transform]) -> Result<()> {
55 if transforms.is_empty() {
56 return Err(Error::invalid_argument(
57 "Animation transform array is empty",
58 ));
59 }
60 for transform in transforms {
61 transform.validate()?;
62 }
63 Ok(())
64}
65
66fn validate_clip_metadata(clip: &AnimClip) -> Result<()> {
67 if clip.joint_count == 0
68 || clip.frame_count == 0
69 || !clip.frames_per_second.is_finite()
70 || clip.frames_per_second <= 0.0
71 {
72 return Err(Error::invalid_argument("AnimClip metadata is invalid"));
73 }
74 let expected = checked_sample_count(clip.frame_count, clip.joint_count)
75 .ok_or_else(|| Error::invalid_argument("AnimClip sample count is invalid"))?;
76 if expected != clip.samples.len() {
77 return Err(Error::invalid_argument("AnimClip sample count is invalid"));
78 }
79 Ok(())
80}
81
82fn interpolate_transform(a: &Transform, b: &Transform, weight: f32) -> Transform {
83 let mut result = Transform::default();
84 result.set_position(a.position().lerp(b.position(), weight));
85 result.set_rotation(
86 a.rotation()
87 .try_slerp(b.rotation(), weight)
88 .unwrap_or_else(|| a.rotation()),
89 );
90 result.set_scale(a.scale().lerp(b.scale(), weight));
91 result.set_shear(a.shear().lerp(b.shear(), weight));
92 result
93}
94
95fn curve_span_is_representable(first: i64, last: i64) -> bool {
96 first >= 0 || last <= i64::MAX + first
97}
98
99fn validate_curve_keyframes<T: AnimCurveValue>(keyframes: &[Keyframe<T>]) -> Result<()> {
100 if keyframes.is_empty() {
101 return Err(Error::invalid_argument(
102 "AnimCurve requires at least one keyframe",
103 ));
104 }
105 if keyframes.len() > u32::MAX as usize {
106 return Err(Error::out_of_range(
107 "AnimCurve keyframe count exceeds the supported range",
108 ));
109 }
110 for (index, keyframe) in keyframes.iter().enumerate() {
111 if !keyframe.value.curve_is_valid()
112 || !keyframe.in_tangent.curve_is_finite()
113 || !keyframe.out_tangent.curve_is_finite()
114 {
115 return Err(Error::invalid_argument(
116 "AnimCurve values and tangents must be finite; quaternion values must be non-zero",
117 ));
118 }
119 if index > 0 && keyframe.time <= keyframes[index - 1].time {
120 return Err(Error::invalid_argument(
121 "AnimCurve keyframe times must be strictly increasing",
122 ));
123 }
124 }
125 if !curve_span_is_representable(
126 keyframes[0].time.nanoseconds(),
127 keyframes[keyframes.len() - 1].time.nanoseconds(),
128 ) {
129 return Err(Error::out_of_range(
130 "AnimCurve time span exceeds the supported duration range",
131 ));
132 }
133 Ok(())
134}
135
136fn validate_curve_metadata<T: AnimCurveValue>(curve: &AnimCurve<T>) -> Result<()> {
137 let keyframes = &curve.keyframes;
138 if keyframes.is_empty() || keyframes.len() > u32::MAX as usize {
139 return Err(Error::invalid_argument("AnimCurve metadata is invalid"));
140 }
141 if !curve_span_is_representable(
142 keyframes[0].time.nanoseconds(),
143 keyframes[keyframes.len() - 1].time.nanoseconds(),
144 ) {
145 return Err(Error::out_of_range(
146 "AnimCurve time span exceeds the supported duration range",
147 ));
148 }
149 Ok(())
150}
151
152fn interpolate_curve_cubic<T: AnimCurveValue>(
153 a: &Keyframe<T>,
154 b: &Keyframe<T>,
155 weight: f32,
156 segment_seconds: f32,
157) -> Result<T> {
158 let squared = weight * weight;
159 let cubed = squared * weight;
160 let value_a_weight = 2.0 * cubed - 3.0 * squared + 1.0;
161 let tangent_a_weight = cubed - 2.0 * squared + weight;
162 let value_b_weight = -2.0 * cubed + 3.0 * squared;
163 let tangent_b_weight = cubed - squared;
164 let value = a.value * value_a_weight
165 + a.out_tangent * (segment_seconds * tangent_a_weight)
166 + b.value * value_b_weight
167 + b.in_tangent * (segment_seconds * tangent_b_weight);
168 if !value.curve_is_valid() {
169 return Err(Error::out_of_range(
170 "AnimCurve cubic interpolation produced a non-finite or zero quaternion value",
171 ));
172 }
173 Ok(value.curve_normalize())
174}
175
176fn wrap_curve_time(time: i64, first: i64, last: i64) -> i64 {
177 let span = (last - first) as u64;
178 if time >= first {
179 let distance = time.wrapping_sub(first) as u64;
180 return first + (distance % span) as i64;
181 }
182 let distance = first.wrapping_sub(time) as u64;
183 let remainder = distance % span;
184 let offset = if remainder == 0 { 0 } else { span - remainder };
185 first + offset as i64
186}
187
188fn sample_curve_validated<T: AnimCurveValue>(
189 curve: &AnimCurve<T>,
190 time: Duration,
191 wrap_mode: AnimWrapMode,
192) -> Result<T> {
193 let keyframes = &curve.keyframes;
194 if keyframes.len() == 1 {
195 return Ok(keyframes[0].value);
196 }
197 let first = keyframes[0].time.nanoseconds();
198 let last = keyframes[keyframes.len() - 1].time.nanoseconds();
199 let mut time = time.nanoseconds();
200 match wrap_mode {
201 AnimWrapMode::Loop => {
202 time = wrap_curve_time(time, first, last);
203 }
204 AnimWrapMode::Clamp => {
205 if time <= first {
206 return Ok(keyframes[0].value);
207 }
208 if time >= last {
209 return Ok(keyframes[keyframes.len() - 1].value);
210 }
211 }
212 }
213
214 let mut lower = 1usize;
215 let mut upper = keyframes.len();
216 while lower < upper {
217 let middle = lower + (upper - lower) / 2;
218 if keyframes[middle].time.nanoseconds() <= time {
219 lower = middle + 1;
220 } else {
221 upper = middle;
222 }
223 }
224 let index_b = lower;
225 let index_a = index_b - 1;
226 let key_a = &keyframes[index_a];
227 let key_b = &keyframes[index_b];
228 if curve.interpolation == AnimInterpolation::Step {
229 return Ok(key_a.value);
230 }
231 let segment_nanoseconds = key_b.time.nanoseconds() - key_a.time.nanoseconds();
232 let weight = ((time - key_a.time.nanoseconds()) as f64 / segment_nanoseconds as f64) as f32;
233 if curve.interpolation == AnimInterpolation::Linear {
234 let value = key_a.value.curve_lerp(key_b.value, weight);
235 if !value.curve_is_valid() {
236 return Err(Error::out_of_range(
237 "AnimCurve linear interpolation produced an invalid value",
238 ));
239 }
240 return Ok(value.curve_normalize());
241 }
242 interpolate_curve_cubic(
243 key_a,
244 key_b,
245 weight,
246 segment_nanoseconds as f32 / 1_000_000_000.0,
247 )
248}
249
250fn checked_bake_time(start_nanoseconds: i64, frame: u32, frames_per_second: f32) -> Option<i64> {
251 let seconds = f64::from(frame) / f64::from(frames_per_second);
252 let nanoseconds = seconds * 1.0e9;
253 if !nanoseconds.is_finite() || nanoseconds < 0.0 || nanoseconds >= 9.223372036854776e18 {
254 return None;
255 }
256 let offset = nanoseconds as i64;
257 if start_nanoseconds > 0 && offset > i64::MAX - start_nanoseconds {
258 return None;
259 }
260 Some(start_nanoseconds + offset)
261}
262
263pub fn create_pose(skeleton_id: u32, local_transforms: &[Transform]) -> Result<SkelPose> {
272 validate_transforms(local_transforms)?;
273 if local_transforms.len() > u32::MAX as usize {
274 return Err(Error::out_of_range(
275 "SkelPose joint count exceeds the supported range",
276 ));
277 }
278 Ok(SkelPose {
279 skeleton_id,
280 local_transforms: local_transforms.to_vec(),
281 })
282}
283
284pub fn validate_pose(pose: &SkelPose) -> Result<()> {
292 if pose.local_transforms.len() > u32::MAX as usize {
293 return Err(Error::out_of_range(
294 "SkelPose joint count exceeds the supported range",
295 ));
296 }
297 validate_transforms(&pose.local_transforms)
298}
299
300pub fn create_clip(
312 skeleton_id: u32,
313 joint_count: u32,
314 frames_per_second: f32,
315 samples: &[Transform],
316) -> Result<AnimClip> {
317 if joint_count == 0
318 || !frames_per_second.is_finite()
319 || frames_per_second <= 0.0
320 || samples.is_empty()
321 || !samples.len().is_multiple_of(joint_count as usize)
322 {
323 return Err(Error::invalid_argument(
324 "AnimClip requires positive joint/frame counts, finite positive FPS, and complete frames",
325 ));
326 }
327 let frame_count = samples.len() / joint_count as usize;
328 if frame_count > u32::MAX as usize {
329 return Err(Error::out_of_range(
330 "AnimClip frame count exceeds the supported range",
331 ));
332 }
333 validate_transforms(samples)?;
334 Ok(AnimClip {
335 skeleton_id,
336 joint_count,
337 frame_count: frame_count as u32,
338 frames_per_second,
339 samples: samples.to_vec(),
340 })
341}
342
343pub fn validate_clip(clip: &AnimClip) -> Result<()> {
351 validate_clip_metadata(clip)?;
352 validate_transforms(&clip.samples)
353}
354
355pub fn frame(clip: &AnimClip, frame: u32) -> Result<SkelPose> {
363 validate_clip_metadata(clip)?;
364 if frame >= clip.frame_count {
365 return Err(Error::out_of_range("AnimClip frame is out of range"));
366 }
367 let offset = frame as usize * clip.joint_count as usize;
368 create_pose(
369 clip.skeleton_id,
370 &clip.samples[offset..offset + clip.joint_count as usize],
371 )
372}
373
374pub fn sample_clip(
383 clip: &AnimClip,
384 time_seconds: f64,
385 wrap_mode: AnimWrapMode,
386) -> Result<SkelPose> {
387 validate_clip_metadata(clip)?;
388 if !time_seconds.is_finite() {
389 return Err(Error::invalid_argument(
390 "AnimClip sample time must be finite",
391 ));
392 }
393 if clip.frame_count == 1 {
394 return frame(clip, 0);
395 }
396 let fps = f64::from(clip.frames_per_second);
397 let (frame_a, frame_b, frame_position) = match wrap_mode {
398 AnimWrapMode::Loop => {
399 let period = f64::from(clip.frame_count) / fps;
400 let mut wrapped = time_seconds % period;
401 if wrapped < 0.0 {
402 wrapped += period;
403 }
404 let frame_position = wrapped * fps;
405 let mut a = frame_position.floor() as u32;
406 if a >= clip.frame_count {
407 a = clip.frame_count - 1;
408 }
409 (a, (a + 1) % clip.frame_count, frame_position)
410 }
411 AnimWrapMode::Clamp => {
412 let maximum_frame = f64::from(clip.frame_count - 1);
413 let duration = maximum_frame / fps;
414 let frame_position = if time_seconds <= 0.0 {
415 0.0
416 } else if time_seconds >= duration {
417 maximum_frame
418 } else {
419 time_seconds * fps
420 };
421 let a = frame_position.floor() as u32;
422 (a, (a + 1).min(clip.frame_count - 1), frame_position)
423 }
424 };
425 let weight = (frame_position - frame_position.floor()) as f32;
426 let offset_a = frame_a as usize * clip.joint_count as usize;
427 let offset_b = frame_b as usize * clip.joint_count as usize;
428 let mut local_transforms = Vec::with_capacity(clip.joint_count as usize);
429 for joint in 0..clip.joint_count as usize {
430 local_transforms.push(interpolate_transform(
431 &clip.samples[offset_a + joint],
432 &clip.samples[offset_b + joint],
433 weight,
434 ));
435 }
436 Ok(SkelPose {
437 skeleton_id: clip.skeleton_id,
438 local_transforms,
439 })
440}
441
442pub fn create_curve<T: AnimCurveValue>(
454 interpolation: AnimInterpolation,
455 keyframes: &[Keyframe<T>],
456) -> Result<AnimCurve<T>> {
457 validate_curve_keyframes(keyframes)?;
458 let mut stored = keyframes.to_vec();
459 for keyframe in &mut stored {
462 keyframe.value = keyframe.value.curve_normalize();
463 }
464 Ok(AnimCurve {
465 interpolation,
466 keyframes: stored,
467 })
468}
469
470pub fn validate_curve<T: AnimCurveValue>(curve: &AnimCurve<T>) -> Result<()> {
478 validate_curve_keyframes(&curve.keyframes)
479}
480
481pub fn sample_curve<T: AnimCurveValue>(
490 curve: &AnimCurve<T>,
491 time: Duration,
492 wrap_mode: AnimWrapMode,
493) -> Result<T> {
494 validate_curve_metadata(curve)?;
495 sample_curve_validated(curve, time, wrap_mode)
496}
497
498pub fn bake<T: AnimCurveValue>(
509 curve: &AnimCurve<T>,
510 start_time: Duration,
511 frames_per_second: f32,
512 frame_count: u32,
513 wrap_mode: AnimWrapMode,
514) -> Result<Vec<T>> {
515 validate_curve_metadata(curve)?;
516 if !frames_per_second.is_finite() || frames_per_second <= 0.0 || frame_count == 0 {
517 return Err(Error::invalid_argument(
518 "AnimCurve baking requires finite positive FPS and frame count",
519 ));
520 }
521 let mut values = Vec::with_capacity(frame_count as usize);
522 for frame in 0..frame_count {
523 let nanoseconds = checked_bake_time(start_time.nanoseconds(), frame, frames_per_second)
524 .ok_or_else(|| {
525 Error::out_of_range("AnimCurve bake time exceeds the supported duration range")
526 })?;
527 values.push(sample_curve_validated(
528 curve,
529 Duration::from_nanoseconds(nanoseconds),
530 wrap_mode,
531 )?);
532 }
533 Ok(values)
534}