pub const CONTROL_INTERVAL: i64 = 32;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ControlSpan<'a> {
pub from: &'a [f32],
pub to: &'a [f32],
pub phase: usize,
}
impl ControlSpan<'_> {
#[must_use]
pub fn is_steady(&self) -> bool {
self.from.len() == self.to.len()
&& self
.from
.iter()
.zip(self.to)
.all(|(from, to)| from.to_bits() == to.to_bits())
}
#[must_use]
pub fn progress(&self, frame: usize) -> f32 {
progress(self.phase, frame)
}
}
pub(crate) fn progress(phase: usize, frame: usize) -> f32 {
const INTERVAL: u8 = 32;
const _: () = assert!(INTERVAL as i64 == CONTROL_INTERVAL);
let along =
u8::try_from(phase.saturating_add(frame)).map_or(INTERVAL, |along| along.min(INTERVAL));
f32::from(along) * (1.0 / f32::from(INTERVAL))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ControlLane {
pub node: usize,
pub first_point: i64,
pub points: usize,
pub offset: usize,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Controls<'a> {
pub lanes: &'a [ControlLane],
pub values: &'a [f32],
}
impl<'a> Controls<'a> {
pub(crate) fn span_at(
&self,
lane: &ControlLane,
sample: i64,
params: usize,
) -> ControlSpan<'a> {
let last = i64::try_from(lane.points).unwrap_or(i64::MAX) - 1;
let point = sample.div_euclid(CONTROL_INTERVAL);
let index = |point: i64| point.saturating_sub(lane.first_point).clamp(0, last.max(0));
let values = |index: i64| {
let start = lane.offset + usize::try_from(index).unwrap_or(0) * params;
self.values.get(start..start + params).unwrap_or(&[])
};
ControlSpan {
from: values(index(point)),
to: values(index(point.saturating_add(1))),
phase: usize::try_from(sample.rem_euclid(CONTROL_INTERVAL)).unwrap_or(0),
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Ramp<const N: usize> {
from: [f32; N],
change: [f32; N],
phase: usize,
}
impl<const N: usize> Ramp<N> {
pub(crate) fn between(from: [f32; N], to: [f32; N], phase: usize) -> Self {
Self {
from,
change: core::array::from_fn(|index| to[index] - from[index]),
phase,
}
}
pub(crate) fn at(&self, frame: usize) -> [f32; N] {
let progress = progress(self.phase, frame);
core::array::from_fn(|index| self.from[index] + self.change[index] * progress)
}
pub(crate) const fn after(self, frames: usize) -> Self {
Self {
phase: self.phase.saturating_add(frames),
..self
}
}
}