#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Trs {
pub translation: [f32; 3],
pub rotation: [f32; 4],
pub scale: [f32; 3],
}
impl Trs {
pub const IDENTITY: Self = Self {
translation: [0.0; 3],
rotation: [0.0, 0.0, 0.0, 1.0],
scale: [1.0; 3],
};
#[must_use]
pub fn matrix(&self) -> [f32; 16] {
let m = crate::flatten::trs(
self.translation.map(f64::from),
self.rotation.map(f64::from),
self.scale.map(f64::from),
);
m.map(crate::num::f32_of)
}
}
impl Default for Trs {
fn default() -> Self {
Self::IDENTITY
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
pub name: Option<String>,
pub parent: Option<usize>,
pub children: Vec<usize>,
pub rest: Trs,
pub mesh: Option<usize>,
pub skin: Option<usize>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Skin {
pub name: Option<String>,
pub joints: Vec<usize>,
pub inverse_bind: Vec<[f32; 16]>,
pub skeleton: Option<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Property {
Translation,
Rotation,
Scale,
Weights,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Interpolation {
Linear,
Step,
CubicSpline,
}
impl Interpolation {
const fn name(self) -> &'static str {
match self {
Self::Linear => "LINEAR",
Self::Step => "STEP",
Self::CubicSpline => "CUBICSPLINE",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Channel {
pub node: usize,
pub property: Property,
pub interpolation: Interpolation,
pub times: Vec<f32>,
pub values: Vec<f32>,
}
impl Channel {
#[must_use]
pub fn sample(&self, t: f32) -> Option<Vec<f32>> {
let mut out = Vec::new();
self.sample_into(t, &mut out).then_some(out)
}
pub fn sample_into(&self, t: f32, out: &mut Vec<f32>) -> bool {
out.clear();
let interpolation = self.interpolation.name();
let Some(w) = crate::flatten::width(&self.times, &self.values, interpolation) else {
return false;
};
let rotation = self.property == Property::Rotation;
let k = self.times.partition_point(|&x| x <= t);
let mut small = [0.0f64; 64];
let mut large = Vec::new();
let v = if w <= small.len() {
&mut small[..w]
} else {
large.resize(w, 0.0);
&mut large[..]
};
if !crate::flatten::sample_after(&self.times, &self.values, interpolation, t, rotation, k, v) {
return false;
}
out.extend(v.iter().map(|&x| crate::num::f32_of(x)));
true
}
fn sample_small(&self, t: f32, k: usize) -> Option<([f32; 4], usize)> {
let interpolation = self.interpolation.name();
let w = crate::flatten::width(&self.times, &self.values, interpolation)?;
let mut v = [0.0f64; 4];
let rotation = self.property == Property::Rotation;
if w > 4 || !crate::flatten::sample_after(&self.times, &self.values, interpolation, t, rotation, k, &mut v[..w])
{
return None;
}
Some((v.map(crate::num::f32_of), w))
}
fn pose(&self, t: f32, k: usize, o: &mut Trs) {
if self.property == Property::Weights {
return;
}
let Some((v, w)) = self.sample_small(t, k) else {
return;
};
match (self.property, w) {
(Property::Translation, 3) => o.translation = [v[0], v[1], v[2]],
(Property::Scale, 3) => o.scale = [v[0], v[1], v[2]],
(Property::Rotation, 4) => o.rotation = v,
_ => {}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Animation {
pub name: Option<String>,
pub channels: Vec<Channel>,
pub frame_rate: Option<f64>,
}
impl Animation {
#[must_use]
pub fn span(&self) -> (f32, f32) {
let mut first = f32::INFINITY;
let mut last = f32::NEG_INFINITY;
for c in &self.channels {
if let (Some(a), Some(b)) = (c.times.first(), c.times.last()) {
first = first.min(*a);
last = last.max(*b);
}
}
if first <= last { (first, last) } else { (0.0, 0.0) }
}
#[must_use]
pub fn key_times(&self) -> Vec<f32> {
let mut sets: Vec<&[f32]> = Vec::new();
for c in &self.channels {
if !sets.contains(&c.times.as_slice()) {
sets.push(&c.times);
}
}
let mut t: Vec<f32> = sets.concat();
if sets.len() > 1 || !t.is_sorted_by(|a, b| a.total_cmp(b).is_le()) {
t.sort_unstable_by(f32::total_cmp);
}
t.dedup();
t
}
}
#[derive(Debug, Clone)]
pub struct Poser<'a> {
rig: &'a Rig,
channels: &'a [Channel],
keys: Vec<usize>,
}
impl Poser<'_> {
pub fn pose_into(&mut self, time: f32, out: &mut Vec<Trs>) {
out.clear();
out.extend(self.rig.nodes.iter().map(|n| n.rest));
for (c, k) in self.channels.iter().zip(&mut self.keys) {
let times = &c.times;
if *k > 0 && times.get(*k - 1).is_none_or(|&x| x > time) {
*k = times.partition_point(|&x| x <= time);
} else {
let mut steps = 0;
while times.get(*k).is_some_and(|&x| x <= time) {
*k += 1;
steps += 1;
if steps == 4 {
*k += times[*k..].partition_point(|&x| x <= time);
break;
}
}
}
if let Some(o) = out.get_mut(c.node) {
c.pose(time, *k, o);
}
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Rig {
pub nodes: Vec<Node>,
pub skins: Vec<Skin>,
pub animations: Vec<Animation>,
}
impl Rig {
#[must_use]
pub fn find(&self, name: &str) -> Option<usize> {
self.nodes.iter().position(|n| n.name.as_deref() == Some(name))
}
#[must_use]
pub fn pose(&self, animation: Option<usize>, time: f32) -> Vec<Trs> {
let mut out = Vec::with_capacity(self.nodes.len());
self.pose_into(animation, time, &mut out);
out
}
pub fn pose_into(&self, animation: Option<usize>, time: f32, out: &mut Vec<Trs>) {
out.clear();
out.extend(self.nodes.iter().map(|n| n.rest));
let Some(a) = animation.and_then(|a| self.animations.get(a)) else {
return;
};
for c in &a.channels {
if let Some(o) = out.get_mut(c.node) {
c.pose(time, c.times.partition_point(|&x| x <= time), o);
}
}
}
#[must_use]
pub fn poser(&self, animation: usize) -> Poser<'_> {
let channels = self.animations.get(animation).map_or(&[][..], |a| &a.channels);
Poser {
rig: self,
channels,
keys: vec![0; channels.len()],
}
}
#[must_use]
pub fn world(&self, local: &[Trs]) -> Vec<[f32; 16]> {
use crate::flatten::{M4, mul};
let own = |i: usize| -> M4 {
let t = local.get(i).unwrap_or(&self.nodes[i].rest);
crate::flatten::trs(
t.translation.map(f64::from),
t.rotation.map(f64::from),
t.scale.map(f64::from),
)
};
let mut world: Vec<M4> = (0..self.nodes.len()).map(own).collect();
for i in self.parents_first() {
if let Some(p) = self.nodes[i].parent.and_then(|p| world.get(p).copied()) {
world[i] = mul(&p, &world[i]);
}
}
world.into_iter().map(|m| m.map(crate::num::f32_of)).collect()
}
#[must_use]
pub fn skin_matrices(&self, skin: usize, world: &[[f32; 16]]) -> Vec<[f32; 16]> {
let Some(s) = self.skins.get(skin) else {
return Vec::new();
};
let wide = |m: &[f32; 16]| m.map(f64::from);
let identity = Trs::IDENTITY.matrix();
s.joints
.iter()
.zip(&s.inverse_bind)
.map(|(&j, ibm)| {
let w = world.get(j).unwrap_or(&identity);
crate::flatten::mul(&wide(w), &wide(ibm)).map(crate::num::f32_of)
})
.collect()
}
#[must_use]
pub fn parents_first(&self) -> Vec<usize> {
let mut out = Vec::with_capacity(self.nodes.len());
let mut seen = vec![false; self.nodes.len()];
let mut stack: Vec<usize> = (0..self.nodes.len())
.rev()
.filter(|&i| self.nodes[i].parent.is_none())
.collect();
while let Some(i) = stack.pop() {
if std::mem::replace(&mut seen[i], true) {
continue;
}
out.push(i);
stack.extend(self.nodes[i].children.iter().rev().filter(|&&c| c < seen.len()));
}
out
}
}
#[cfg(test)]
mod tests {
use super::{Animation, Channel, Interpolation, Node, Property, Rig, Trs};
fn rig() -> Rig {
let node = |name: &str, parent| Node {
name: Some(name.into()),
parent,
children: Vec::new(),
rest: Trs::IDENTITY,
mesh: None,
skin: None,
};
let channel = |node, property, interpolation, times: &[f32], values: &[f32]| Channel {
node,
property,
interpolation,
times: times.to_vec(),
values: values.to_vec(),
};
Rig {
nodes: vec![node("root", None), node("arm", Some(0))],
skins: Vec::new(),
animations: vec![Animation {
name: None,
frame_rate: None,
channels: vec![
channel(
0,
Property::Rotation,
Interpolation::Linear,
&[0.0, 1.0],
&[0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 0.0],
),
channel(
0,
Property::Translation,
Interpolation::Step,
&[0.0, 1.0],
&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
),
channel(
1,
Property::Scale,
Interpolation::CubicSpline,
&[0.0, 1.0],
&[
0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 0.0, 0.0, 0.0,
],
),
channel(
1,
Property::Weights,
Interpolation::Linear,
&[0.0],
&[0.5, 0.5, 0.5, 0.5, 0.5],
),
],
}],
}
}
#[test]
fn pose_into_reuses_its_vector_and_poses_as_pose_does() {
let rig = rig();
let mut out = Vec::new();
for t in [-1.0, 0.0, 0.25, 0.5, 1.0, 2.0] {
rig.pose_into(Some(0), t, &mut out);
assert_eq!(out, rig.pose(Some(0), t), "at {t}");
}
let at = out.as_ptr();
rig.pose_into(Some(0), 0.5, &mut out);
assert_eq!(out.as_ptr(), at, "allocated again");
rig.pose_into(None, 0.5, &mut out);
assert_eq!(out, vec![Trs::IDENTITY; 2]);
}
#[test]
fn key_times_holds_every_channels_keys_once_in_order() {
let mut rig = rig();
assert_eq!(rig.animations[0].key_times(), [0.0, 1.0]);
let channel = rig.animations[0].channels[0].clone();
for times in [vec![0.5, 1.0, 3.0], vec![0.0, 1.0], vec![-1.0, 0.25]] {
let values = channel.values[..4].repeat(times.len());
rig.animations[0].channels.push(Channel {
times,
values,
..channel.clone()
});
}
assert_eq!(rig.animations[0].key_times(), [-1.0, 0.0, 0.25, 0.5, 1.0, 3.0]);
assert_eq!(
Animation {
name: None,
channels: Vec::new(),
frame_rate: None,
}
.key_times(),
Vec::<f32>::new()
);
}
#[test]
fn a_poser_poses_as_pose_does_at_times_in_any_order() {
let mut rig = rig();
let times: Vec<f32> = (0..40u8).map(|k| f32::from(k) * 0.05).collect();
let values: Vec<f32> = (0..40u8).flat_map(|k| [f32::from(k), 0.0, -f32::from(k)]).collect();
rig.animations[0].channels.push(Channel {
node: 1,
property: Property::Translation,
interpolation: Interpolation::Linear,
times,
values,
});
let mut poser = rig.poser(0);
let mut out = Vec::new();
let mut check = |t: f32| {
poser.pose_into(t, &mut out);
assert_eq!(out, rig.pose(Some(0), t), "at {t}");
};
let forward = (-2..50i8).map(|k| f32::from(k) * 0.05);
let jumps = [0.0, 0.01, 0.9, 0.9, 1.95, 2.5, 0.3, -1.0, 1.0, 0.05, 0.0];
let backward = (-2..50i8).rev().map(|k| f32::from(k) * 0.037);
for t in forward.chain(jumps).chain(backward) {
check(t);
}
}
#[test]
fn rotations_come_out_unit_length_at_the_first_and_last_keys_too() {
let rig = rig();
for t in [-1.0, 0.0, 0.5, 1.0, 2.0] {
let q = rig.pose(Some(0), t)[0].rotation;
let len = q.iter().map(|c| c * c).sum::<f32>().sqrt();
assert!((len - 1.0).abs() < 1e-6, "{q:?} at {t}");
}
assert_eq!(rig.pose(Some(0), 0.0)[0].rotation, [0.0, 0.0, 0.0, 1.0]);
assert_eq!(rig.pose(Some(0), 0.5)[0].translation, [1.0, 2.0, 3.0]);
assert_eq!(rig.pose(Some(0), 0.5)[1].scale, [2.0, 2.0, 2.0]);
}
fn close(a: &[f32], b: &[f32]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)
}
#[test]
fn a_transform_composes_into_a_column_major_matrix() {
let half = std::f32::consts::FRAC_1_SQRT_2;
let t = Trs {
translation: [1.0, 2.0, 3.0],
rotation: [0.0, 0.0, half, half], scale: [2.0, 2.0, 2.0],
};
let want = [
0.0, 2.0, 0.0, 0.0, -2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 1.0, 2.0, 3.0, 1.0,
];
assert!(close(&t.matrix(), &want), "{:?}", t.matrix());
assert!(close(
&Trs::IDENTITY.matrix(),
&super::super::flatten::IDENTITY.map(crate::num::f32_of)
));
}
#[test]
fn world_transforms_and_skin_matrices_follow_the_tree() {
let mut rig = rig();
rig.nodes[0].children = vec![1];
let mut pose = vec![Trs::IDENTITY; 2];
pose[0].translation = [1.0, 0.0, 0.0];
pose[1].translation = [0.0, 1.0, 0.0];
let world = rig.world(&pose);
assert!(close(&world[1][12..15], &[1.0, 1.0, 0.0]), "{:?}", world[1]);
let undo = |m: &[f32; 16]| {
let mut i = Trs::IDENTITY.matrix();
i[12] = -m[12];
i[13] = -m[13];
i[14] = -m[14];
i
};
rig.skins.push(super::Skin {
name: None,
joints: vec![0, 1],
inverse_bind: vec![undo(&world[0]), undo(&world[1])],
skeleton: None,
});
for m in rig.skin_matrices(0, &world) {
assert!(close(&m, &Trs::IDENTITY.matrix()), "{m:?}");
}
assert_eq!(rig.skin_matrices(5, &world), Vec::<[f32; 16]>::new());
assert_eq!(rig.world(&[]).len(), 2, "nodes past the pose are at rest");
}
#[test]
fn an_animation_that_is_not_there_poses_the_rest_pose() {
let rig = rig();
assert_eq!(rig.pose(Some(9), 0.5), rig.pose(None, 0.5));
let mut out = Vec::new();
rig.poser(9).pose_into(0.5, &mut out);
assert_eq!(out, rig.pose(None, 0.5));
}
#[cfg(all(feature = "gltf", feature = "fs"))]
#[test]
fn an_animation_takes_its_own_frame_rate_before_the_files() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/gltf/skin_animated/skin.glb");
let mut doc = crate::open(&path).unwrap();
assert_eq!(
doc.rig().unwrap().animations[0].frame_rate,
None,
"glTF has no frame rate"
);
doc.json["asset"]["extras"] = serde_json::json!({ "source": { "frameRate": 30.0 } });
assert_eq!(doc.rig().unwrap().animations[0].frame_rate, Some(30.0));
doc.json["animations"][0]["extras"] = serde_json::json!({ "frameRate": 24.0 });
assert_eq!(doc.rig().unwrap().animations[0].frame_rate, Some(24.0));
}
}