ferravex_play/animation/
retarget.rs

1//! Checked local-pose remapping between two real [`Skeleton`]s.
2//!
3//! Joint names and rest locals are parallel, caller-owned authoring metadata;
4//! neither changes the skeleton, animation, skin, save or replay format. Names
5//! are inspected only during preparation and are not retained. Each skeleton
6//! has 1..=[MAX_ANIMATION_JOINTS] joints, globally unique nonempty names of at
7//! most 4096 bytes, and parent-before-child order. Siblings may be reordered.
8//! Matched joints must have matched **immediate** parents (or both be roots).
9//!
10//! The convention is **local right delta**, not world-space motion or IK:
11//! `target_local = target_rest * inverse(source_rest) * source_local`.
12//! Thus the source rest maps to the target rest; translation deltas rotate
13//! into the target rest frame and scale by target/source rest scale. Rotation
14//! deltas act after the target rest orientation. Different bone lengths and
15//! orientations are supported, but no length fitting or end-effector constraint
16//! is inferred. Parent/world transforms are evaluated later by the target
17//! skeleton. Only finite translations, valid scene quaternions and strictly
18//! positive, exactly uniform scales are supported. Reflection, nonuniform scale,
19//! zero scale and unrepresentable checked inverses/results are explicit errors.
20//! Shear has no input representation: this API accepts TRS locals only and never
21//! decomposes arbitrary matrices. Uniform local scales cannot introduce shear
22//! during hierarchy composition. Existing inverse-bind matrices are left intact
23//! and are not assumed to be inverses of these caller-supplied rest locals.
24//! Checked success is subject to f32 rounding and inverse conditioning; it is
25//! not an accuracy certificate. Translation underflow may round to zero; scale
26//! underflow to zero is rejected. An offset or source full rest inverse that
27//! cannot be represented is rejected even if a particular final pose could fit.
28//!
29//! # Two-skeleton animation-to-skin recipe
30//!
31//! This headless recipe constructs real skeletons with different sibling order,
32//! bone lengths and rest orientations, samples a real animation, and uses the
33//! mapped locals with the existing world/skin APIs. No renderer is required.
34//!
35//! ```rust
36//! use ferravex_math::{Mat4, Quat};
37//! use ferravex_play::{animation::*, animation::retarget::*, scene::*};
38//!
39//! fn skeleton(parents: &[Option<usize>], rest: &[Transform]) -> Skeleton {
40//!     let provisional = Skeleton::new(parents.iter().map(|&parent| Joint {
41//!         parent, inverse_bind: IDENTITY,
42//!     }).collect()).unwrap();
43//!     let world = provisional.world_pose(rest).unwrap();
44//!     Skeleton::new(parents.iter().zip(world).map(|(&parent, world)| Joint {
45//!         parent,
46//!         inverse_bind: Mat4::from_cols_array(&world).checked_inverse().unwrap()
47//!             .to_cols_array(),
48//!     }).collect()).unwrap()
49//! }
50//!
51//! fn main() -> Result<(), Box<dyn std::error::Error>> {
52//!     let source_rest = [Transform::default(), Transform {
53//!         translation: [1., 0., 0.], ..Transform::default()
54//!     }, Transform { translation: [0., 0., 1.], ..Transform::default() }];
55//!     let target_rest = [Transform::default(), source_rest[2], Transform {
56//!         translation: [0., 2., 0.],
57//!         rotation: Quat::from_rotation_z(std::f32::consts::FRAC_PI_2).to_array(),
58//!         scale: [2.; 3],
59//!     }];
60//!     let source = skeleton(&[None, Some(0), Some(0)], &source_rest);
61//!     let target = skeleton(&[None, Some(0), Some(0)], &target_rest);
62//!     let map = PreparedRetarget::try_new(&source, &["root", "arm", "marker"],
63//!         &source_rest, &target, &["root", "marker", "arm"], &target_rest,
64//!         MissingJointPolicy::Strict)?;
65//!     let clip = AnimationClip::new(3, 1., LoopMode::Clamp, vec![JointTrack {
66//!         joint: 1,
67//!         translation: Some(Track::new(vec![
68//!             Keyframe { time: 0., value: [1., 0., 0.] },
69//!             Keyframe { time: 1., value: [2., 0., 0.] },
70//!         ], Interpolation::Linear).unwrap()),
71//!         rotation: Some(Track::new(vec![Keyframe { time: 1.,
72//!             value: Quat::from_rotation_x(0.5).to_array() }], Interpolation::Step).unwrap()),
73//!         scale: None,
74//!     }], vec![]).unwrap();
75//!     let mut sampled = [Transform::default(); 3];
76//!     clip.sample_into(1., &source_rest, &mut sampled).unwrap();
77//!     let mut mapped = [Transform::default(); 3];
78//!     map.map_pose_into(&sampled, &mut mapped)?;
79//!     assert!((mapped[2].translation[1] - 4.).abs() < 1e-5);
80//!     let expected = Quat::from_array(target_rest[2].rotation)
81//!         * Quat::from_rotation_x(0.5);
82//!     assert!(Quat::from_array(mapped[2].rotation).dot(expected).abs() > 0.99999);
83//!     let mut world = [IDENTITY; 3];
84//!     let mut palette = [IDENTITY; 3];
85//!     map.target().world_pose_into(&mapped, &mut world)?;
86//!     assert!((world[2][13] - 4.).abs() < 1e-5);
87//!     map.target().skin_palette_into(&mapped, &mut world, &mut palette)?;
88//!     assert!(palette.iter().flatten().all(|v| v.is_finite()));
89//!     // Feeding the rest again resets the result without any hidden history.
90//!     map.map_pose_into(&source_rest, &mut mapped)?;
91//!     assert_eq!(mapped, target_rest);
92//!     map.target().skin_palette_into(&mapped, &mut world, &mut palette)?;
93//!     for matrix in palette {
94//!         assert!(Mat4::from_cols_array(&matrix).abs_diff_eq(Mat4::IDENTITY, 1e-5));
95//!     }
96//!     assert!(matches!(PreparedRetarget::try_new(&source, &["root", "arm", "arm"],
97//!         &source_rest, &target, &["root", "marker", "arm"], &target_rest,
98//!         MissingJointPolicy::Strict), Err(RetargetError::DuplicateName { .. })));
99//!     assert!(matches!(PreparedRetarget::try_new(&source, &["root", "arm", "marker"],
100//!         &source_rest, &target, &["root", "unknown", "arm"], &target_rest,
101//!         MissingJointPolicy::Strict), Err(RetargetError::MissingJoint { .. })));
102//!     Ok(())
103//! }
104//! ```
105
106use super::MAX_ANIMATION_JOINTS;
107use crate::scene::{Skeleton, Transform, multiply};
108use ferravex_math::{
109    Mat4, MatrixError, Quat, Vec3,
110    affine::{AffineError, PreparedAffine3D},
111};
112
113/// Side of the mapping containing a diagnostic's joint index.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum SkeletonSide {
116    Source,
117    Target,
118}
119
120/// Explicit policy for names present on only one side.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub enum MissingJointPolicy {
123    /// Both name sets must match exactly; the first unmatched target, then
124    /// source, is reported. This does not require identical sibling ordering.
125    Strict,
126    /// Unmatched target joints keep their rest locals; unused source joints
127    /// are permitted (but their poses are still validated). Matched children
128    /// of unmatched parents are rejected rather than silently reparented.
129    TargetRestFallback,
130}
131
132/// Unsupported local TRS or failed checked arithmetic; no decomposition occurs.
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum RetargetTransformError {
136    InvalidTransform,
137    NonPositiveScale,
138    NonUniformScale,
139    Matrix(MatrixError),
140    Affine(AffineError),
141}
142
143/// Indexed authoring, compatibility, capacity or numeric diagnostic.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145#[non_exhaustive]
146pub enum RetargetError {
147    JointLimit {
148        side: SkeletonSide,
149        count: usize,
150    },
151    MetadataLength {
152        side: SkeletonSide,
153        joints: usize,
154        names: usize,
155        rest: usize,
156    },
157    InvalidName {
158        side: SkeletonSide,
159        joint: usize,
160    },
161    DuplicateName {
162        side: SkeletonSide,
163        first: usize,
164        duplicate: usize,
165    },
166    InvalidParent {
167        side: SkeletonSide,
168        joint: usize,
169    },
170    MissingJoint {
171        side: SkeletonSide,
172        joint: usize,
173    },
174    HierarchyMismatch {
175        source_joint: usize,
176        target_joint: usize,
177    },
178    Transform {
179        side: SkeletonSide,
180        joint: usize,
181        error: RetargetTransformError,
182    },
183    PoseLength {
184        required: usize,
185        actual: usize,
186    },
187    Capacity {
188        required: usize,
189        available: usize,
190    },
191}
192
193impl std::fmt::Display for RetargetTransformError {
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        match self {
196            Self::InvalidTransform => f.write_str("invalid scene TRS or unrepresentable result"),
197            Self::NonPositiveScale => f.write_str(
198                "scale must be strictly positive; reflections and singular scales are unsupported",
199            ),
200            Self::NonUniformScale => {
201                f.write_str("nonuniform scale is unsupported; no shear decomposition is performed")
202            }
203            Self::Matrix(error) => write!(f, "rest inverse: {error}"),
204            Self::Affine(error) => write!(f, "checked affine: {error}"),
205        }
206    }
207}
208impl std::error::Error for RetargetTransformError {
209    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
210        match self {
211            Self::Matrix(e) => Some(e),
212            Self::Affine(e) => Some(e),
213            _ => None,
214        }
215    }
216}
217impl std::fmt::Display for RetargetError {
218    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219        match self {
220            Self::Transform { side, joint, error } => write!(f, "{side:?} joint {joint}: {error}"),
221            _ => write!(f, "retarget: {self:?}"),
222        }
223    }
224}
225impl std::error::Error for RetargetError {
226    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
227        match self {
228            Self::Transform { error, .. } => Some(error),
229            _ => None,
230        }
231    }
232}
233
234#[derive(Clone, Copy, Debug)]
235struct JointMapping {
236    source: usize,
237    offset: PreparedAffine3D,
238    rotation: Quat,
239    scale_ratio: f64,
240}
241
242/// Immutable prepared map tied by shared borrows to the exact two skeletons.
243/// Names are discarded; normalized rest locals and indexed offsets are owned.
244/// Skeleton mutation/replacement while borrowed is prevented by Rust. Raw pose
245/// slices carry no identity: the caller must supply source-order locals and use
246/// the target-order output with [`Self::target`], not an unrelated same-size rig.
247///
248/// Construction allocates O(joints) bounded storage and compares names O(n²).
249/// Mapping is O(joints), with no allocation/name lookup and at most two 256-local
250/// stack buffers. There is no clock, playback state or mutable reconfiguration.
251/// To reconfigure, construct a replacement first, then assign it only on success;
252/// construction failure cannot mutate the last-good map. See the module recipe.
253#[derive(Debug)]
254pub struct PreparedRetarget<'s> {
255    source: &'s Skeleton,
256    target: &'s Skeleton,
257    source_rest: Vec<Transform>,
258    target_rest: Vec<Transform>,
259    mapping: Vec<Option<JointMapping>>,
260}
261
262impl<'s> PreparedRetarget<'s> {
263    /// Validate all metadata/rest locals before constructing reusable offsets.
264    /// Names/rest arrays need only live for this call; both skeleton borrows
265    /// live as long as the returned map. Bounds and names are checked before
266    /// lookup; no automatic aliases, ancestor skipping or case folding occurs.
267    /// Numeric failure on an offset is reported at its target joint index.
268    pub fn try_new(
269        source: &'s Skeleton,
270        source_names: &[&str],
271        source_rest: &[Transform],
272        target: &'s Skeleton,
273        target_names: &[&str],
274        target_rest: &[Transform],
275        policy: MissingJointPolicy,
276    ) -> Result<Self, RetargetError> {
277        let source_rest =
278            validate_metadata(source, source_names, source_rest, SkeletonSide::Source)?;
279        let target_rest =
280            validate_metadata(target, target_names, target_rest, SkeletonSide::Target)?;
281        let indices: Vec<_> = target_names
282            .iter()
283            .map(|name| source_names.iter().position(|s| s == name))
284            .collect();
285        if policy == MissingJointPolicy::Strict {
286            if let Some(joint) = indices.iter().position(Option::is_none) {
287                return Err(RetargetError::MissingJoint {
288                    side: SkeletonSide::Target,
289                    joint,
290                });
291            }
292            if let Some(joint) = (0..source_names.len()).find(|i| !indices.contains(&Some(*i))) {
293                return Err(RetargetError::MissingJoint {
294                    side: SkeletonSide::Source,
295                    joint,
296                });
297            }
298        }
299        let mut mapping = Vec::with_capacity(target_rest.len());
300        for (t, &s) in indices.iter().enumerate() {
301            let Some(s) = s else {
302                mapping.push(None);
303                continue;
304            };
305            let compatible = match (source.joints()[s].parent, target.joints()[t].parent) {
306                (None, None) => true,
307                (Some(sp), Some(tp)) => indices[tp] == Some(sp),
308                _ => false,
309            };
310            if !compatible {
311                return Err(RetargetError::HierarchyMismatch {
312                    source_joint: s,
313                    target_joint: t,
314                });
315            }
316            let entry = (|| {
317                let inverse = matrix(source_rest[s])
318                    .checked_inverse()
319                    .map_err(RetargetTransformError::Matrix)?;
320                let offset = PreparedAffine3D::try_new(Mat4::from_cols_array(&multiply(
321                    matrix(target_rest[t]).to_cols_array(),
322                    inverse.to_cols_array(),
323                )))
324                .map_err(RetargetTransformError::Affine)?;
325                let rotation = (Quat::from_array(target_rest[t].rotation)
326                    * Quat::from_array(source_rest[s].rotation)
327                        .try_inverse()
328                        .ok_or(RetargetTransformError::InvalidTransform)?)
329                .try_normalize()
330                .ok_or(RetargetTransformError::InvalidTransform)?;
331                Ok(JointMapping {
332                    source: s,
333                    offset,
334                    rotation,
335                    scale_ratio: f64::from(target_rest[t].scale[0])
336                        / f64::from(source_rest[s].scale[0]),
337                })
338            })()
339            .map_err(|error| RetargetError::Transform {
340                side: SkeletonSide::Target,
341                joint: t,
342                error,
343            })?;
344            mapping.push(Some(entry));
345        }
346        Ok(Self {
347            source,
348            target,
349            source_rest,
350            target_rest,
351            mapping,
352        })
353    }
354
355    /// The exact source skeleton whose joint order the input slice must use.
356    pub fn source(&self) -> &'s Skeleton {
357        self.source
358    }
359
360    /// The exact target skeleton whose joint order the output prefix uses.
361    pub fn target(&self) -> &'s Skeleton {
362        self.target
363    }
364
365    /// Remap a complete source local pose into the target-length output prefix.
366    /// Checks exact source length first, then sufficient output capacity. All
367    /// inputs (including unused joints) and results are checked before **any**
368    /// writes; all output bits/tails survive failure. Success preserves the
369    /// unused tail. Quaternions are normalized using checked existing math.
370    /// Feeding the original source rest metadata again returns the stored,
371    /// normalized target rest exactly.
372    /// Reusing the map after errors or feeding rest again requires no reset.
373    /// Downstream world/skin evaluation remains a separate checked operation.
374    pub fn map_pose_into(
375        &self,
376        source_pose: &[Transform],
377        output: &mut [Transform],
378    ) -> Result<(), RetargetError> {
379        if source_pose.len() != self.source_rest.len() {
380            return Err(RetargetError::PoseLength {
381                required: self.source_rest.len(),
382                actual: source_pose.len(),
383            });
384        }
385        if output.len() < self.target_rest.len() {
386            return Err(RetargetError::Capacity {
387                required: self.target_rest.len(),
388                available: output.len(),
389            });
390        }
391        let mut source = [Transform::default(); MAX_ANIMATION_JOINTS];
392        for (joint, (&pose, out)) in source_pose.iter().zip(&mut source).enumerate() {
393            *out = checked_local(pose).map_err(|error| RetargetError::Transform {
394                side: SkeletonSide::Source,
395                joint,
396                error,
397            })?;
398        }
399        let mut staged = [Transform::default(); MAX_ANIMATION_JOINTS];
400        for (joint, (&rest, mapping)) in self.target_rest.iter().zip(&self.mapping).enumerate() {
401            let result = (|| {
402                let Some(m) = mapping else {
403                    return Ok(rest);
404                };
405                let pose = source[m.source];
406                if pose == self.source_rest[m.source] {
407                    return Ok(rest);
408                }
409                let translation = m
410                    .offset
411                    .transform_point(Vec3::from_array(pose.translation))
412                    .map_err(RetargetTransformError::Affine)?
413                    .to_array();
414                let rotation = (m.rotation * Quat::from_array(pose.rotation))
415                    .try_normalize()
416                    .ok_or(RetargetTransformError::InvalidTransform)?
417                    .to_array();
418                let scale = [(m.scale_ratio * f64::from(pose.scale[0])) as f32; 3];
419                checked_local(Transform {
420                    translation,
421                    rotation,
422                    scale,
423                })
424            })()
425            .map_err(|error| RetargetError::Transform {
426                side: SkeletonSide::Target,
427                joint,
428                error,
429            })?;
430            staged[joint] = result;
431        }
432        output[..self.target_rest.len()].copy_from_slice(&staged[..self.target_rest.len()]);
433        Ok(())
434    }
435}
436
437fn matrix(local: Transform) -> Mat4 {
438    // Only called with checked, normalized local transforms.
439    Mat4::from_cols_array(&local.matrix().expect("checked scene transform"))
440}
441
442fn checked_local(mut local: Transform) -> Result<Transform, RetargetTransformError> {
443    if !local.valid() {
444        return Err(RetargetTransformError::InvalidTransform);
445    }
446    if local.scale.iter().any(|s| *s <= 0.) {
447        return Err(RetargetTransformError::NonPositiveScale);
448    }
449    if local.scale[0] != local.scale[1] || local.scale[0] != local.scale[2] {
450        return Err(RetargetTransformError::NonUniformScale);
451    }
452    local.rotation = Quat::from_array(local.rotation)
453        .try_normalize()
454        .ok_or(RetargetTransformError::InvalidTransform)?
455        .to_array();
456    PreparedAffine3D::try_new(matrix(local)).map_err(RetargetTransformError::Affine)?;
457    Ok(local)
458}
459
460fn validate_metadata(
461    skeleton: &Skeleton,
462    names: &[&str],
463    rest: &[Transform],
464    side: SkeletonSide,
465) -> Result<Vec<Transform>, RetargetError> {
466    let joints = skeleton.joint_count();
467    if joints == 0 || joints > MAX_ANIMATION_JOINTS {
468        return Err(RetargetError::JointLimit {
469            side,
470            count: joints,
471        });
472    }
473    if names.len() != joints || rest.len() != joints {
474        return Err(RetargetError::MetadataLength {
475            side,
476            joints,
477            names: names.len(),
478            rest: rest.len(),
479        });
480    }
481    for (joint, name) in names.iter().enumerate() {
482        if name.is_empty() || name.len() > 4096 {
483            return Err(RetargetError::InvalidName { side, joint });
484        }
485        if let Some(first) = names[..joint].iter().position(|n| n == name) {
486            return Err(RetargetError::DuplicateName {
487                side,
488                first,
489                duplicate: joint,
490            });
491        }
492        if skeleton.joints()[joint].parent.is_some_and(|p| p >= joint) {
493            return Err(RetargetError::InvalidParent { side, joint });
494        }
495    }
496    rest.iter()
497        .enumerate()
498        .map(|(joint, &local)| {
499            checked_local(local).map_err(|error| RetargetError::Transform { side, joint, error })
500        })
501        .collect()
502}