#[derive(Debug, Clone, Copy, PartialEq)]
struct Phase {
start: f64,
duration: f64,
label: &'static str,
index: usize,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Beat {
pub index: usize,
pub label: &'static str,
pub local: f64,
pub progress: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Timeline {
phases: Box<[Phase]>,
total: f64,
fallback_label: &'static str,
}
impl Timeline {
pub fn new(phases: &[(&'static str, f64)]) -> Self {
let mut total = 0.0;
let kept: Box<[Phase]> = phases
.iter()
.enumerate()
.filter(|(_, (_, d))| d.is_finite() && *d > 0.0)
.map(|(index, &(label, duration))| {
let start = total;
total += duration;
Phase {
start,
duration,
label,
index,
}
})
.collect();
let (phases_kept, total) = if total.is_finite() {
(kept, total)
} else {
(Box::default(), 0.0)
};
Self {
phases: phases_kept,
total,
fallback_label: phases.first().map_or("", |p| p.0),
}
}
#[inline]
pub fn total(&self) -> f64 {
self.total
}
#[inline]
pub fn is_empty(&self) -> bool {
self.phases.is_empty()
}
fn wrap(&self, t: f64) -> Option<(f64, f64)> {
if self.phases.is_empty() {
return None;
}
let t = if t.is_finite() { t } else { 0.0 };
let mut cycles = t.div_euclid(self.total);
let mut u = t.rem_euclid(self.total);
if u >= self.total {
u = 0.0;
cycles += 1.0;
}
Some((cycles, u))
}
pub fn at(&self, t: f64) -> Beat {
let Some((_, u)) = self.wrap(t) else {
return Beat {
index: 0,
label: self.fallback_label,
local: 0.0,
progress: 0.0,
};
};
let i = self
.phases
.partition_point(|p| p.start <= u)
.saturating_sub(1);
let p = &self.phases[i];
let local = (u - p.start).clamp(0.0, p.duration.next_down());
let progress = (local / p.duration).min(1.0f64.next_down());
Beat {
index: p.index,
label: p.label,
local,
progress,
}
}
pub fn cycle(&self, t: f64) -> i64 {
self.wrap(t).map_or(0, |(cycles, _)| cycles as i64)
}
}
pub mod ease {
#[inline]
fn unit(x: f64) -> f64 {
if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }
}
#[inline]
pub fn smoothstep(x: f64) -> f64 {
let x = unit(x);
x * x * (3.0 - 2.0 * x)
}
#[inline]
pub fn in_out_cubic(x: f64) -> f64 {
let x = unit(x);
if x < 0.5 {
4.0 * x * x * x
} else {
let r = 2.0 - 2.0 * x;
1.0 - 0.5 * r * r * r
}
}
#[inline]
pub fn out_quad(x: f64) -> f64 {
let r = 1.0 - unit(x);
1.0 - r * r
}
#[inline]
pub fn lerp(a: f64, b: f64, t: f64) -> f64 {
let d = b - a;
if t < 0.5 {
a + d * t
} else {
b - d * (1.0 - t)
}
}
}