use super::interpolant::{Interpolant, InterpolantKind};
pub const INTERPOLATE_DISCRETE: u32 = 2300;
pub const INTERPOLATE_LINEAR: u32 = 2301;
pub const INTERPOLATE_SMOOTH: u32 = 2302;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ValueType {
Number,
Vector,
Quaternion,
Color,
Bool,
String,
}
impl ValueType {
pub fn name(self) -> &'static str {
match self {
ValueType::Number => "number",
ValueType::Vector => "vector",
ValueType::Quaternion => "quaternion",
ValueType::Color => "color",
ValueType::Bool => "bool",
ValueType::String => "string",
}
}
pub fn from_name(name: &str) -> Option<ValueType> {
Some(match name.to_ascii_lowercase().as_str() {
"scalar" | "double" | "float" | "number" | "integer" => ValueType::Number,
"vector" | "vector2" | "vector3" | "vector4" => ValueType::Vector,
"color" => ValueType::Color,
"quaternion" => ValueType::Quaternion,
"bool" | "boolean" => ValueType::Bool,
"string" => ValueType::String,
_ => return None,
})
}
pub fn default_interpolation(self) -> Interpolation {
match self {
ValueType::Bool | ValueType::String => Interpolation::Discrete,
_ => Interpolation::Linear,
}
}
pub fn supports(self, interpolation: Interpolation) -> bool {
match (self, interpolation) {
(ValueType::Bool | ValueType::String, Interpolation::Discrete) => true,
(ValueType::Bool | ValueType::String, _) => false,
(ValueType::Quaternion, Interpolation::Smooth) => false,
_ => true,
}
}
pub fn is_numeric(self) -> bool {
!matches!(self, ValueType::Bool | ValueType::String)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Interpolation {
Discrete,
Linear,
Smooth,
GltfCubicSpline,
}
impl Interpolation {
pub fn constant(self) -> Option<u32> {
match self {
Interpolation::Discrete => Some(INTERPOLATE_DISCRETE),
Interpolation::Linear => Some(INTERPOLATE_LINEAR),
Interpolation::Smooth => Some(INTERPOLATE_SMOOTH),
Interpolation::GltfCubicSpline => None,
}
}
pub fn from_constant(c: u32) -> Option<Interpolation> {
match c {
INTERPOLATE_DISCRETE => Some(Interpolation::Discrete),
INTERPOLATE_LINEAR => Some(Interpolation::Linear),
INTERPOLATE_SMOOTH => Some(Interpolation::Smooth),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum TrackValues {
Numeric(Vec<f32>),
Bool(Vec<bool>),
String(Vec<String>),
}
impl TrackValues {
pub fn len(&self) -> usize {
match self {
TrackValues::Numeric(v) => v.len(),
TrackValues::Bool(v) => v.len(),
TrackValues::String(v) => v.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn numeric(&self) -> Option<&[f32]> {
match self {
TrackValues::Numeric(v) => Some(v),
_ => None,
}
}
fn slice(&self, from: usize, to: usize) -> TrackValues {
let to = to.min(self.len());
let from = from.min(to);
match self {
TrackValues::Numeric(v) => TrackValues::Numeric(v[from..to].to_vec()),
TrackValues::Bool(v) => TrackValues::Bool(v[from..to].to_vec()),
TrackValues::String(v) => TrackValues::String(v[from..to].to_vec()),
}
}
fn same(&self, a: usize, b: usize) -> bool {
match self {
TrackValues::Numeric(v) => v.get(a) == v.get(b) && v.get(a).is_some(),
TrackValues::Bool(v) => v.get(a) == v.get(b),
TrackValues::String(v) => v.get(a) == v.get(b),
}
}
fn copy_within(&mut self, src: usize, dst: usize) {
match self {
TrackValues::Numeric(v) => v[dst] = v[src],
TrackValues::Bool(v) => v[dst] = v[src],
TrackValues::String(v) => v[dst] = v[src].clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TrackError {
NoKeyframes(String),
ValueKind(String),
}
impl std::fmt::Display for TrackError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TrackError::NoKeyframes(n) => {
write!(f, "THREE.KeyframeTrack: no keyframes in track named {n}")
}
TrackError::ValueKind(n) => write!(
f,
"THREE.KeyframeTrack: values of the wrong kind for track {n}"
),
}
}
}
impl std::error::Error for TrackError {}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TrackModifier {
Noise {
amplitude: f64,
frequency: f64,
seed: f64,
},
Cycles { before: f64, after: f64 },
Stepped { step_size: f64 },
Limit { min: f64, max: f64 },
}
impl TrackModifier {
pub fn remap_time(modifiers: &[TrackModifier], t: f64, duration: f64) -> f64 {
let mut time = t;
for m in modifiers {
match *m {
TrackModifier::Cycles { before, after } if duration > 0.0 => {
if time < 0.0 {
time = if before == 0.0 {
0.0
} else {
((time % duration) + duration) % duration
};
} else if time > duration {
time = if after == 0.0 {
duration
} else {
time % duration
};
}
}
TrackModifier::Stepped { step_size } => {
let s = step_size.max(1e-6);
time = (time / s).floor() * s;
}
_ => {}
}
}
time
}
pub fn apply_value(modifiers: &[TrackModifier], values: &mut [f64], t: f64) {
for m in modifiers {
match *m {
TrackModifier::Noise {
amplitude,
frequency,
seed,
} => {
for (i, v) in values.iter_mut().enumerate() {
let n = ((t * frequency + seed + i as f64 * 19.19) * 12.9898).sin()
* 43758.5453;
let f = n - n.floor();
*v += (f * 2.0 - 1.0) * amplitude;
}
}
TrackModifier::Limit { min, max } => {
for v in values.iter_mut() {
*v = max.min(min.max(*v));
}
}
_ => {}
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct KeyframeTrack {
pub name: String,
pub value_type: ValueType,
pub times: Vec<f32>,
pub values: TrackValues,
interpolation: Interpolation,
pub modifiers: Vec<TrackModifier>,
}
impl KeyframeTrack {
pub fn new(
value_type: ValueType,
name: impl Into<String>,
times: Vec<f32>,
values: TrackValues,
interpolation: Option<Interpolation>,
) -> Result<Self, TrackError> {
let name = name.into();
if times.is_empty() {
return Err(TrackError::NoKeyframes(name));
}
let ok = match (&values, value_type) {
(TrackValues::Bool(_), ValueType::Bool) => true,
(TrackValues::String(_), ValueType::String) => true,
(TrackValues::Numeric(_), t) => t.is_numeric(),
_ => false,
};
if !ok {
return Err(TrackError::ValueKind(name));
}
let mut track = Self {
name,
value_type,
times,
values,
interpolation: value_type.default_interpolation(),
modifiers: Vec::new(),
};
let wanted = interpolation.unwrap_or(value_type.default_interpolation());
if value_type.supports(wanted) {
track.interpolation = wanted;
} else {
log::warn!(
"THREE.KeyframeTrack: unsupported interpolation for {} keyframe track named {}",
value_type.name(),
track.name
);
}
Ok(track)
}
pub fn number(name: impl Into<String>, times: Vec<f32>, values: Vec<f32>) -> Self {
Self::numeric(ValueType::Number, name, times, values)
}
pub fn vector(name: impl Into<String>, times: Vec<f32>, values: Vec<f32>) -> Self {
Self::numeric(ValueType::Vector, name, times, values)
}
pub fn quaternion(name: impl Into<String>, times: Vec<f32>, values: Vec<f32>) -> Self {
Self::numeric(ValueType::Quaternion, name, times, values)
}
pub fn color(name: impl Into<String>, times: Vec<f32>, values: Vec<f32>) -> Self {
Self::numeric(ValueType::Color, name, times, values)
}
pub fn boolean(name: impl Into<String>, times: Vec<f32>, values: Vec<bool>) -> Self {
Self {
name: name.into(),
value_type: ValueType::Bool,
times,
values: TrackValues::Bool(values),
interpolation: Interpolation::Discrete,
modifiers: Vec::new(),
}
}
pub fn string(name: impl Into<String>, times: Vec<f32>, values: Vec<String>) -> Self {
Self {
name: name.into(),
value_type: ValueType::String,
times,
values: TrackValues::String(values),
interpolation: Interpolation::Discrete,
modifiers: Vec::new(),
}
}
fn numeric(
value_type: ValueType,
name: impl Into<String>,
times: Vec<f32>,
values: Vec<f32>,
) -> Self {
Self {
name: name.into(),
value_type,
times,
values: TrackValues::Numeric(values),
interpolation: Interpolation::Linear,
modifiers: Vec::new(),
}
}
pub fn with_interpolation(mut self, interpolation: Interpolation) -> Self {
self.set_interpolation(interpolation);
self
}
pub fn set_interpolation(&mut self, interpolation: Interpolation) -> &mut Self {
if self.value_type.supports(interpolation)
|| interpolation == Interpolation::GltfCubicSpline
{
self.interpolation = interpolation;
} else {
log::warn!(
"THREE.KeyframeTrack: unsupported interpolation for {} keyframe track named {}",
self.value_type.name(),
self.name
);
}
self
}
pub fn interpolation(&self) -> Interpolation {
self.interpolation
}
pub fn value_size(&self) -> usize {
if self.times.is_empty() {
0
} else {
self.values.len() / self.times.len()
}
}
pub fn value_size_f64(&self) -> f64 {
self.values.len() as f64 / self.times.len() as f64
}
pub fn create_interpolant(&self) -> Interpolant {
let size = self.value_size();
let kind = match self.interpolation {
Interpolation::Discrete => InterpolantKind::Discrete,
Interpolation::Linear => {
if self.value_type == ValueType::Quaternion {
InterpolantKind::QuaternionLinear
} else {
InterpolantKind::Linear
}
}
Interpolation::Smooth => InterpolantKind::Cubic,
Interpolation::GltfCubicSpline => {
return Interpolant::new(
if self.value_type == ValueType::Quaternion {
InterpolantKind::GltfCubicSplineQuaternion
} else {
InterpolantKind::GltfCubicSpline
},
size / 3,
);
}
};
Interpolant::new(kind, size)
}
pub fn shift(&mut self, time_offset: f64) -> &mut Self {
if time_offset != 0.0 {
for t in &mut self.times {
*t = (*t as f64 + time_offset) as f32;
}
}
self
}
pub fn scale(&mut self, time_scale: f64) -> &mut Self {
if time_scale != 1.0 {
for t in &mut self.times {
*t = (*t as f64 * time_scale) as f32;
}
}
self
}
pub fn trim(&mut self, start_time: f64, end_time: f64) -> &mut Self {
let n_keys = self.times.len() as isize;
let mut from: isize = 0;
let mut to: isize = n_keys - 1;
while from != n_keys && (self.times[from as usize] as f64) < start_time {
from += 1;
}
while to != -1 && (self.times[to as usize] as f64) > end_time {
to -= 1;
}
to += 1; if from != 0 || to != n_keys {
if from >= to {
to = to.max(1);
from = to - 1;
}
let stride = self.value_size();
let (f, t) = (from as usize, to as usize);
self.times = self.times[f.min(self.times.len())..t.min(self.times.len())].to_vec();
self.values = self.values.slice(f * stride, t * stride);
}
self
}
pub fn validate(&self) -> bool {
let mut valid = true;
let value_size = self.value_size_f64();
if value_size - value_size.floor() != 0.0 {
log::error!(
"THREE.KeyframeTrack: Invalid value size in track. {}",
self.name
);
valid = false;
}
let n_keys = self.times.len();
if n_keys == 0 {
log::error!("THREE.KeyframeTrack: Track is empty. {}", self.name);
valid = false;
}
let mut prev_time: Option<f32> = None;
for (i, &curr_time) in self.times.iter().enumerate() {
if curr_time.is_nan() {
log::error!(
"THREE.KeyframeTrack: Time is not a valid number. {} {i}",
self.name
);
valid = false;
break;
}
if let Some(p) = prev_time {
if p > curr_time {
log::error!("THREE.KeyframeTrack: Out of order keys. {} {i}", self.name);
valid = false;
break;
}
}
prev_time = Some(curr_time);
}
if let TrackValues::Numeric(values) = &self.values {
for (i, v) in values.iter().enumerate() {
if v.is_nan() {
log::error!(
"THREE.KeyframeTrack: Value is not a valid number. {} {i}",
self.name
);
valid = false;
break;
}
}
}
valid
}
pub fn optimize(&mut self) -> &mut Self {
if self.times.is_empty() {
return self;
}
let mut times = self.times.clone();
let mut values = self.values.clone();
let stride = self.value_size();
let smooth = self.interpolation == Interpolation::Smooth;
let last_index = times.len() as isize - 1;
let mut write_index: usize = 1;
let mut i: isize = 1;
while i < last_index {
let iu = i as usize;
let mut keep = false;
let time = times[iu];
let time_next = times[iu + 1];
if time != time_next && (iu != 1 || time != times[0]) {
if !smooth {
let offset = iu * stride;
let offset_p = offset - stride;
let offset_n = offset + stride;
for j in 0..stride {
if !values.same(offset + j, offset_p + j)
|| !values.same(offset + j, offset_n + j)
{
keep = true;
break;
}
}
} else {
keep = true;
}
}
if keep {
if iu != write_index {
times[write_index] = times[iu];
let read_offset = iu * stride;
let write_offset = write_index * stride;
for j in 0..stride {
values.copy_within(read_offset + j, write_offset + j);
}
}
write_index += 1;
}
i += 1;
}
if last_index > 0 {
let lu = last_index as usize;
times[write_index] = times[lu];
let read_offset = lu * stride;
let write_offset = write_index * stride;
for j in 0..stride {
values.copy_within(read_offset + j, write_offset + j);
}
write_index += 1;
}
if write_index != times.len() {
self.times = times[..write_index].to_vec();
self.values = values.slice(0, write_index * stride);
} else {
self.times = times;
self.values = values;
}
self
}
pub fn value_at(&self, i: usize) -> Option<&[f32]> {
let s = self.value_size();
self.values
.numeric()
.and_then(|v| v.get(i * s..(i + 1) * s))
}
}