use serde::{Deserialize, Serialize};
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CubicBezier {
pub x1: f32,
pub y1: f32,
pub x2: f32,
pub y2: f32,
}
const NEWTON_STEPS: usize = 8;
const BISECTION_STEPS: usize = 64;
const TOLERANCE: f64 = 1e-12;
const MIN_SLOPE: f64 = 1e-9;
impl CubicBezier {
#[must_use]
pub const fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
Self { x1, y1, x2, y2 }
}
#[must_use]
pub fn is_valid(self) -> bool {
self.y1.is_finite() && self.y2.is_finite() && time_handles_valid(self.x1, self.x2)
}
#[must_use]
pub fn apply(self, progress: f64) -> f64 {
let x = progress.clamp(0.0, 1.0);
if x <= 0.0 {
return 0.0;
}
if x >= 1.0 {
return 1.0;
}
let parameter = self.time().parameter_at(x);
component(parameter, f64::from(self.y1), f64::from(self.y2))
}
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn between(self, from: f64, to: f64) -> Option<Self> {
let parameter = |progress: f64| {
if progress <= 0.0 {
0.0
} else if progress >= 1.0 {
1.0
} else {
self.time().parameter_at(progress)
}
};
let (u, v) = (parameter(from), parameter(to));
let part = |p1: f32, p2: f32| {
let points = [0.0, f64::from(p1), f64::from(p2), 1.0];
[
blossom(points, u, u, u),
blossom(points, u, u, v),
blossom(points, u, v, v),
blossom(points, v, v, v),
]
};
let (x, y) = (part(self.x1, self.x2), part(self.y1, self.y2));
let (width, height) = (x[3] - x[0], y[3] - y[0]);
if width <= 0.0 || height == 0.0 {
return None;
}
let (x1, x2) = settle_time_handles((x[1] - x[0]) / width, (x[2] - x[0]) / width);
let curve = Self::new(
x1,
((y[1] - y[0]) / height) as f32,
x2,
((y[2] - y[0]) / height) as f32,
);
curve.is_valid().then_some(curve)
}
#[must_use]
pub fn reversed(self) -> Self {
let (x1, x2) = settle_time_handles(1.0 - f64::from(self.x2), 1.0 - f64::from(self.x1));
Self::new(x1, 1.0 - self.y2, x2, 1.0 - self.y1)
}
#[must_use]
pub fn slope(self, progress: f64) -> f64 {
let time = self.time();
let u = time.parameter_within(progress);
rise_over_run(
slope(u, f64::from(self.y1), f64::from(self.y2)),
slope(u, time.x1, time.x2),
)
}
#[must_use]
pub fn end_slope(self, at_end: bool) -> f64 {
let (x1, y1) = (f64::from(self.x1), f64::from(self.y1));
let (x2, y2) = (f64::from(self.x2), f64::from(self.y2));
let legs = if at_end {
[(1.0 - x2, 1.0 - y2), (1.0 - x1, 1.0 - y1)]
} else {
[(x1, y1), (x2, y2)]
};
first_leg_slope(legs).unwrap_or(1.0)
}
#[must_use]
pub fn turns(self) -> [Option<f64>; 2] {
let time = self.time();
let (y1, y2) = (f64::from(self.y1), f64::from(self.y2));
let c = 3.0 * y1;
let b = 3.0 * (y2 - y1) - c;
let a = 1.0 - c - b;
quadratic_roots(3.0 * a, 2.0 * b, c)
.map(|turn| turn.filter(|u| *u > 0.0 && *u < 1.0))
.map(|turn| turn.map(|u| component(u, time.x1, time.x2)))
}
fn time(self) -> TimeCurve {
TimeCurve::new(self.x1, self.x2)
}
}
fn quadratic_roots(qa: f64, qb: f64, qc: f64) -> [Option<f64>; 2] {
if qa.abs() <= f64::EPSILON {
return [(qb.abs() > f64::EPSILON).then(|| -qc / qb), None];
}
let discriminant = qb * qb - 4.0 * qa * qc;
if discriminant < 0.0 {
return [None, None];
}
let root = discriminant.sqrt();
[
Some((-qb + root) / (2.0 * qa)),
Some((-qb - root) / (2.0 * qa)),
]
}
fn rise_over_run(rise: f64, run: f64) -> f64 {
if run >= MIN_RUN {
rise / run
} else if rise > 0.0 {
VERTICAL_SLOPE
} else if rise < 0.0 {
-VERTICAL_SLOPE
} else {
0.0
}
}
const SETTLE_STEPS: usize = 32;
#[expect(
clippy::cast_possible_truncation,
reason = "time handles are stored as `f32`"
)]
fn settle_time_handles(x1: f64, x2: f64) -> (f32, f32) {
let step = |value: f32, direction: f64| {
if direction > 0.0 {
value.next_up()
} else if direction < 0.0 {
value.next_down()
} else {
value
}
};
let rounded = (
if x1 > 0.0 { x1 } else { 0.0 } as f32,
if x2 < 1.0 { x2 } else { 1.0 } as f32,
);
let (mut first, mut second) = rounded;
for _ in 0..SETTLE_STEPS {
if time_handles_valid(first, second) {
return (first, second);
}
let apart = 2.0 * (f64::from(first) - f64::from(second));
(first, second) = (
step(first, (1.0 - f64::from(second)) - apart),
step(second, apart - f64::from(first)),
);
}
if time_handles_valid(first, second) {
return (first, second);
}
(rounded.0.clamp(0.0, 1.0), rounded.1.clamp(0.0, 1.0))
}
fn first_leg_slope(legs: [(f64, f64); 2]) -> Option<f64> {
legs.into_iter()
.find(|(run, _)| *run > 0.0)
.map(|(run, rise)| rise / run)
}
#[must_use]
pub fn time_handles_valid(x1: f32, x2: f32) -> bool {
if !(x1.is_finite() && x2.is_finite()) {
return false;
}
let (first, last) = (f64::from(x1), 1.0 - f64::from(x2));
let middle = f64::from(x2) - f64::from(x1);
first >= 0.0 && last >= 0.0 && (middle >= 0.0 || middle * middle <= first * last)
}
#[derive(Copy, Clone)]
struct TimeCurve {
x1: f64,
x2: f64,
}
impl TimeCurve {
fn new(x1: f32, x2: f32) -> Self {
Self {
x1: f64::from(x1),
x2: f64::from(x2),
}
}
fn parameter_within(self, progress: f64) -> f64 {
if progress <= 0.0 {
0.0
} else if progress >= 1.0 {
1.0
} else {
self.parameter_at(progress)
}
}
fn parameter_at(self, x: f64) -> f64 {
self.newton(x).unwrap_or_else(|| self.bisection(x))
}
fn newton(self, x: f64) -> Option<f64> {
let Self { x1, x2 } = self;
let mut parameter = x;
for _ in 0..NEWTON_STEPS {
let error = component(parameter, x1, x2) - x;
if error.abs() < TOLERANCE {
return (0.0..=1.0).contains(¶meter).then_some(parameter);
}
let slope = slope(parameter, x1, x2);
if slope.abs() < MIN_SLOPE {
return None;
}
parameter -= error / slope;
}
None
}
fn bisection(self, x: f64) -> f64 {
let Self { x1, x2 } = self;
let (mut low, mut high) = (0.0_f64, 1.0_f64);
let mut parameter = x;
for _ in 0..BISECTION_STEPS {
let value = component(parameter, x1, x2);
if (value - x).abs() < TOLERANCE {
break;
}
if value < x {
low = parameter;
} else {
high = parameter;
}
parameter = low + (high - low) * 0.5;
}
parameter
}
}
fn component(t: f64, p1: f64, p2: f64) -> f64 {
let c = 3.0 * p1;
let b = 3.0 * (p2 - p1) - c;
let a = 1.0 - c - b;
((a * t + b) * t + c) * t
}
fn blossom(points: [f64; 4], u: f64, v: f64, w: f64) -> f64 {
let lerp = |a: f64, b: f64, t: f64| a + (b - a) * t;
let first = [
lerp(points[0], points[1], u),
lerp(points[1], points[2], u),
lerp(points[2], points[3], u),
];
let second = [lerp(first[0], first[1], v), lerp(first[1], first[2], v)];
lerp(second[0], second[1], w)
}
fn slope(t: f64, p1: f64, p2: f64) -> f64 {
let c = 3.0 * p1;
let b = 3.0 * (p2 - p1) - c;
let a = 1.0 - c - b;
(3.0 * a * t + 2.0 * b) * t + c
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ValueBezier {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x1: Option<f32>,
pub leave: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub x2: Option<f32>,
pub arrive: f32,
}
const VERTICAL_SLOPE: f64 = f64::MAX;
const MIN_RUN: f64 = 1e-12;
impl ValueBezier {
#[must_use]
pub const fn unweighted(leave: f32, arrive: f32) -> Self {
Self {
x1: None,
leave,
x2: None,
arrive,
}
}
#[must_use]
pub const fn weighted(x1: f32, leave: f32, x2: f32, arrive: f32) -> Self {
Self {
x1: Some(x1),
leave,
x2: Some(x2),
arrive,
}
}
#[must_use]
pub fn is_valid(self) -> bool {
self.leave.is_finite()
&& self.arrive.is_finite()
&& match (self.x1, self.x2) {
(None, None) => true,
(Some(x1), Some(x2)) => time_handles_valid(x1, x2),
_ => false,
}
}
#[must_use]
pub fn weights(self) -> Option<(f32, f32)> {
self.x1.zip(self.x2)
}
#[must_use]
pub fn value(self, from: f32, to: f32, progress: f64) -> f64 {
self.value_between(f64::from(from), f64::from(to), progress)
}
#[must_use]
pub fn value_between(self, from: f64, to: f64, progress: f64) -> f64 {
if progress <= 0.0 {
return from;
}
if progress >= 1.0 {
return to;
}
let u = match self.weights() {
None => progress,
Some((x1, x2)) => TimeCurve::new(x1, x2).parameter_at(progress),
};
let [a, b, c] = self.polynomial(from, to);
from + ((a * u + b) * u + c) * u
}
#[must_use]
pub fn slope(self, from: f32, to: f32, progress: f64) -> f64 {
self.slope_between(f64::from(from), f64::from(to), progress)
}
#[must_use]
pub fn slope_between(self, from: f64, to: f64, progress: f64) -> f64 {
let progress = progress.clamp(0.0, 1.0);
let [a, b, c] = self.polynomial(from, to);
let rise = |u: f64| (3.0 * a * u + 2.0 * b) * u + c;
let Some((x1, x2)) = self.weights() else {
return rise(progress);
};
let time = TimeCurve::new(x1, x2);
let u = time.parameter_within(progress);
rise_over_run(rise(u), slope(u, time.x1, time.x2))
}
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "values and handles are stored as `f32`"
)]
pub fn between(self, from: f32, to: f32, start: f64, end: f64) -> (f32, f32, Self) {
let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
let (low, high) = (
narrow(self.value(from, to, start)),
narrow(self.value(from, to, end)),
);
let part = self.part_between(
(f64::from(from), f64::from(to)),
(start, end),
(f64::from(low), f64::from(high)),
);
(low, high, part)
}
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "handles are stored as `f32`"
)]
pub fn part_between(self, ends: (f64, f64), span: (f64, f64), part_ends: (f64, f64)) -> Self {
let time = self.weights().map(|(x1, x2)| TimeCurve::new(x1, x2));
let parameter = |progress: f64| {
time.map_or(progress.clamp(0.0, 1.0), |time| {
time.parameter_within(progress)
})
};
let (u, v) = (parameter(span.0), parameter(span.1));
let part = |points: [f64; 4]| {
[
blossom(points, u, u, u),
blossom(points, u, u, v),
blossom(points, u, v, v),
blossom(points, v, v, v),
]
};
let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
let (from, to) = ends;
let y = part([
from,
from + f64::from(self.leave),
to + f64::from(self.arrive),
to,
]);
let weights = time.and_then(|time| {
let x = part([0.0, time.x1, time.x2, 1.0]);
let width = x[3] - x[0];
(width > 0.0).then(|| settle_time_handles((x[1] - x[0]) / width, (x[2] - x[0]) / width))
});
Self {
x1: weights.map(|(x1, _)| x1),
leave: narrow(y[1] - part_ends.0),
x2: weights.map(|(_, x2)| x2),
arrive: narrow(y[2] - part_ends.1),
}
}
#[must_use]
pub fn reversed(self) -> Self {
let weights = self
.weights()
.map(|(x1, x2)| settle_time_handles(1.0 - f64::from(x2), 1.0 - f64::from(x1)));
Self {
x1: weights.map(|(x1, _)| x1),
leave: self.arrive,
x2: weights.map(|(_, x2)| x2),
arrive: self.leave,
}
}
#[must_use]
pub fn rebased(self, from: f32, to: f32, new_from: f32, new_to: f32) -> Self {
self.rebased_between(
(f64::from(from), f64::from(to)),
(f64::from(new_from), f64::from(new_to)),
)
}
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "clamped to the `f32` range first"
)]
pub fn rebased_between(self, ends: (f64, f64), new_ends: (f64, f64)) -> Self {
let narrow = |value: f64| value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32;
Self {
leave: narrow(ends.0 + f64::from(self.leave) - new_ends.0),
arrive: narrow(ends.1 + f64::from(self.arrive) - new_ends.1),
..self
}
}
#[must_use]
pub fn range(self, from: f32, to: f32) -> [f64; 2] {
let (from, to) = (f64::from(from), f64::from(to));
let [a, b, c] = self.polynomial(from, to);
let value = |u: f64| from + ((a * u + b) * u + c) * u;
quadratic_roots(3.0 * a, 2.0 * b, c)
.into_iter()
.flatten()
.filter(|u| *u > 0.0 && *u < 1.0)
.map(value)
.fold([from.min(to), from.max(to)], |[low, high], value| {
[low.min(value), high.max(value)]
})
}
#[must_use]
pub fn end_slope(self, from: f32, to: f32, at_end: bool) -> f64 {
self.end_slope_between(f64::from(from), f64::from(to), at_end)
}
#[must_use]
pub fn end_slope_between(self, from: f64, to: f64, at_end: bool) -> f64 {
let (x1, x2) = self.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
(f64::from(x1), f64::from(x2))
});
let change = to - from;
let (leave, arrive) = (f64::from(self.leave), f64::from(self.arrive));
let legs = if at_end {
[(1.0 - x2, -arrive), (1.0 - x1, change - leave)]
} else {
[(x1, leave), (x2, change + arrive)]
};
first_leg_slope(legs).unwrap_or(change)
}
#[must_use]
pub fn turns_between(self, from: f64, to: f64) -> [Option<f64>; 2] {
let [a, b, c] = self.polynomial(from, to);
let time = self.weights().map(|(x1, x2)| TimeCurve::new(x1, x2));
quadratic_roots(3.0 * a, 2.0 * b, c)
.map(|turn| turn.filter(|u| *u > 0.0 && *u < 1.0))
.map(|turn| turn.map(|u| time.map_or(u, |time| component(u, time.x1, time.x2))))
}
fn polynomial(self, from: f64, to: f64) -> [f64; 3] {
let change = to - from;
let c = 3.0 * f64::from(self.leave);
let b = 3.0 * (change + f64::from(self.arrive) - f64::from(self.leave)) - c;
let a = change - c - b;
[a, b, c]
}
}
pub const MAX_EASING_STEPS: u32 = 65_536;
pub const MAX_EASING_POINTS: usize = 256;
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum StepPosition {
Start,
#[default]
End,
None,
Both,
}
impl StepPosition {
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde passes a field by reference"
)]
fn is_end(&self) -> bool {
*self == Self::End
}
}
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Steps {
#[serde(deserialize_with = "step_count")]
#[cfg_attr(
feature = "schema",
schemars(range(min = 1, max = MAX_EASING_STEPS))
)]
pub count: u32,
#[serde(default, skip_serializing_if = "StepPosition::is_end")]
pub position: StepPosition,
}
fn step_count<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
let count = u32::deserialize(deserializer)?;
if (1..=MAX_EASING_STEPS).contains(&count) {
Ok(count)
} else {
Err(serde::de::Error::custom(format!(
"a steps count is 1 to {MAX_EASING_STEPS}, not {count}"
)))
}
}
impl Steps {
#[must_use]
pub const fn is_valid(self) -> bool {
let least = if matches!(self.position, StepPosition::None) {
2
} else {
1
};
self.count >= least && self.count <= MAX_EASING_STEPS
}
#[must_use]
pub const fn index(self, elapsed: i128, length: i128) -> i128 {
let last = self.count as i128 - 1;
let index = (elapsed * self.count as i128).div_euclid(length);
if index < 0 {
0
} else if index > last {
last
} else {
index
}
}
#[must_use]
#[expect(clippy::cast_precision_loss, reason = "counts of at most 65,537")]
pub const fn amount(self, index: i128) -> f64 {
let (rises, of) = self.fraction(index);
rises as f64 / of as f64
}
#[must_use]
pub const fn fraction(self, index: i128) -> (i128, i128) {
let count = self.count as i128;
match self.position {
StepPosition::End => (index, count),
StepPosition::Start => (index + 1, count),
StepPosition::None => (index, count - 1),
StepPosition::Both => (index + 1, count + 1),
}
}
#[must_use]
pub fn apply(self, progress: f64) -> f64 {
if progress >= 1.0 {
return 1.0;
}
if progress < 0.0 || progress.is_nan() {
return 0.0;
}
#[expect(
clippy::cast_possible_truncation,
reason = "a progress below 1 times a count of at most 65,536"
)]
let index = (progress * f64::from(self.count)).floor() as i128;
self.amount(index.clamp(0, i128::from(self.count) - 1))
}
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct EasingPoint {
pub x: f32,
pub y: f32,
}
#[must_use]
pub fn easing_points_valid(points: &[EasingPoint]) -> bool {
points.len() <= MAX_EASING_POINTS
&& points
.iter()
.all(|point| point.x > 0.0 && point.x < 1.0 && point.y.is_finite())
&& points.windows(2).all(|pair| pair[0].x < pair[1].x)
}
fn table_piece(points: &[EasingPoint], progress: f64) -> [(f64, f64); 2] {
let wide = |point: &EasingPoint| (f64::from(point.x), f64::from(point.y));
let next = points.partition_point(|point| f64::from(point.x) <= progress);
[
next.checked_sub(1)
.and_then(|index| points.get(index))
.map_or((0.0, 0.0), wide),
points.get(next).map_or((1.0, 1.0), wide),
]
}
#[must_use]
pub fn easing_points_at(points: &[EasingPoint], progress: f64) -> f64 {
if progress <= 0.0 || progress.is_nan() {
return 0.0;
}
if progress >= 1.0 {
return 1.0;
}
let [(xa, ya), (xb, yb)] = table_piece(points, progress);
ya + (yb - ya) * ((progress - xa) / (xb - xa))
}
#[must_use]
pub fn easing_points_slope(points: &[EasingPoint], progress: f64) -> f64 {
let [(xa, ya), (xb, yb)] = table_piece(points, progress.clamp(0.0, 1.0));
(yb - ya) / (xb - xa)
}
#[must_use]
pub fn easing_points_range(points: &[EasingPoint]) -> [f64; 2] {
points.iter().fold([0.0, 1.0], |[low, high], point| {
[low.min(f64::from(point.y)), high.max(f64::from(point.y))]
})
}
#[expect(
clippy::cast_possible_truncation,
reason = "easing points are stored as `f32`"
)]
fn rising_points(points: impl Iterator<Item = (f64, f64)>) -> Vec<EasingPoint> {
let mut rising: Vec<EasingPoint> = Vec::new();
for (x, y) in points {
let point = EasingPoint {
x: x as f32,
y: y.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32,
};
if point.x > rising.last().map_or(0.0, |last| last.x) && point.x < 1.0 {
rising.push(point);
}
}
rising
}
#[must_use]
pub fn easing_points_reversed(points: &[EasingPoint]) -> Vec<EasingPoint> {
rising_points(
points
.iter()
.rev()
.map(|point| (1.0 - f64::from(point.x), 1.0 - f64::from(point.y))),
)
}
#[must_use]
pub fn easing_points_between(
points: &[EasingPoint],
start: f64,
end: f64,
output: impl Fn(f64) -> f64,
) -> Option<Vec<EasingPoint>> {
let inside: Vec<(f64, f64)> = points
.iter()
.map(|point| (f64::from(point.x), output(f64::from(point.y))))
.filter(|(x, _)| *x > start && *x < end)
.map(|(x, y)| ((x - start) / (end - start), y))
.collect();
inside
.iter()
.all(|(_, y)| y.is_finite())
.then(|| rising_points(inside.into_iter()))
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case", from = "EasingWire")]
pub enum Easing {
Linear,
CubicBezier(CubicBezier),
Steps(Steps),
Points {
points: Vec<EasingPoint>,
},
}
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "Easing"))]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum EasingWire {
Linear {},
CubicBezier(CubicBezier),
Steps(Steps),
Points {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, MAX_EASING_POINTS>")]
#[cfg_attr(feature = "schema", schemars(length(max = MAX_EASING_POINTS)))]
points: Vec<EasingPoint>,
},
}
impl From<EasingWire> for Easing {
fn from(wire: EasingWire) -> Self {
match wire {
EasingWire::Linear {} => Self::Linear,
EasingWire::CubicBezier(curve) => Self::CubicBezier(curve),
EasingWire::Steps(steps) => Self::Steps(steps),
EasingWire::Points { points } => Self::Points { points },
}
}
}
impl Easing {
#[must_use]
pub fn is_valid(&self) -> bool {
match self {
Self::Linear => true,
Self::CubicBezier(curve) => curve.is_valid(),
Self::Steps(steps) => steps.is_valid(),
Self::Points { points } => easing_points_valid(points),
}
}
#[must_use]
pub fn apply(&self, progress: f64) -> f64 {
match self {
Self::Linear => progress.clamp(0.0, 1.0),
Self::CubicBezier(curve) => curve.apply(progress),
Self::Steps(steps) => steps.apply(progress),
Self::Points { points } => easing_points_at(points, progress),
}
}
}
#[cfg(test)]
#[path = "easing_parts_tests.rs"]
mod parts_tests;
#[cfg(test)]
#[path = "easing_steps_tests.rs"]
mod steps_tests;
#[cfg(test)]
mod tests {
use super::{CubicBezier, Easing, ValueBezier, time_handles_valid};
const EASE: CubicBezier = CubicBezier::new(0.25, 0.1, 0.25, 1.0);
#[test]
fn css_ease_matches_its_reference_value() {
assert!((EASE.apply(0.5) - 0.802_403_387_584_857).abs() < 1e-9);
assert!((EASE.time().parameter_at(0.5) - 0.699_572_438_706_385_6).abs() < 1e-9);
let ease_in_out = CubicBezier::new(0.42, 0.0, 0.58, 1.0);
assert!((ease_in_out.apply(0.5) - 0.5).abs() < 1e-7);
for x in [0.1, 0.25, 0.4] {
let mirrored = 1.0 - ease_in_out.apply(1.0 - x);
assert!((ease_in_out.apply(x) - mirrored).abs() < 1e-7);
}
}
#[test]
fn ends_are_exact_and_input_is_clamped() {
for curve in [EASE, CubicBezier::new(0.0, -2.0, 1.0, 3.0)] {
assert_eq!(curve.apply(0.0).to_bits(), 0.0_f64.to_bits());
assert_eq!(curve.apply(1.0).to_bits(), 1.0_f64.to_bits());
assert_eq!(curve.apply(-4.0).to_bits(), 0.0_f64.to_bits());
assert_eq!(curve.apply(9.0).to_bits(), 1.0_f64.to_bits());
}
}
#[test]
fn the_linear_curve_is_the_identity() {
let linear = CubicBezier::new(0.0, 0.0, 1.0, 1.0);
for index in 0..=64 {
let x = f64::from(index) / 64.0;
assert!((linear.apply(x) - x).abs() < 1e-12, "{x}");
assert!((Easing::Linear.apply(x) - x).abs() < f64::EPSILON);
}
}
#[test]
fn flat_curves_fall_back_to_bisection_and_stay_accurate() {
let cases = [
(CubicBezier::new(0.0, 0.0, 0.0, 0.0), 0.001, 0.1),
(CubicBezier::new(1.0, 1.0, 1.0, 1.0), 0.999, 0.9),
];
for (curve, x, parameter) in cases {
assert_eq!(
curve.time().newton(x),
None,
"Newton must give up on {curve:?}"
);
let found = curve.time().parameter_at(x);
assert!((found - parameter).abs() < 1e-9, "{curve:?}: {found}");
let x_back = super::component(found, f64::from(curve.x1), f64::from(curve.x2));
assert!((x_back - x).abs() < 1e-12);
}
}
#[test]
fn a_part_of_a_curve_rescaled_shows_the_same_output() {
let curves = [
EASE,
CubicBezier::new(0.42, 0.0, 0.58, 1.0),
CubicBezier::new(0.3, -0.5, 0.7, 1.5),
CubicBezier::new(0.0, 0.0, 1.0, 1.0),
];
for curve in curves {
for (from, to) in [
(0.0, 0.37),
(0.37, 1.0),
(0.1, 0.9),
(0.5, 0.55),
(0.0, 1.0),
] {
let part = curve.between(from, to).expect("a curve that moves");
assert!(part.is_valid(), "{curve:?} {from} {to}");
let (low, high) = (curve.apply(from), curve.apply(to));
for step in 0..=1000 {
let x = from + (to - from) * f64::from(step) / 1000.0;
let local = (x - from) / (to - from);
let shown = low + (high - low) * part.apply(local);
assert!(
(shown - curve.apply(x)).abs() < 1e-6,
"{curve:?} {from}..{to} at {x}: {shown} {}",
curve.apply(x)
);
}
}
}
}
#[test]
fn an_empty_part_has_no_curve() {
assert_eq!(EASE.between(0.4, 0.4), None);
}
#[test]
fn overshooting_curves_leave_the_unit_interval_between_the_ends() {
let back = CubicBezier::new(0.34, 1.56, 0.64, 1.0);
let peak = (1..100)
.map(|index| back.apply(f64::from(index) / 100.0))
.fold(f64::MIN, f64::max);
assert!(peak > 1.05, "ease-out-back overshoots: {peak}");
assert!((Easing::CubicBezier(back).apply(1.0) - 1.0).abs() < f64::EPSILON);
}
#[test]
fn only_time_coordinates_that_run_backwards_are_rejected() {
assert!(CubicBezier::new(0.0, -5.0, 1.0, 5.0).is_valid());
assert!(CubicBezier::new(1.136, 0.0, 0.909, 1.0).is_valid());
assert!(!CubicBezier::new(-0.1, 0.0, 1.0, 1.0).is_valid());
assert!(!CubicBezier::new(0.0, 0.0, 1.1, 1.0).is_valid());
assert!(!CubicBezier::new(1.2, 0.0, 0.2, 1.0).is_valid());
assert!(!CubicBezier::new(0.0, f32::NAN, 1.0, 1.0).is_valid());
assert!(!CubicBezier::new(f32::NAN, 0.0, 1.0, 1.0).is_valid());
assert!(!CubicBezier::new(0.0, 0.0, f32::INFINITY, 1.0).is_valid());
assert!(!Easing::CubicBezier(CubicBezier::new(0.0, 0.0, 2.0, 1.0)).is_valid());
}
fn least_time_speed(x1: f32, x2: f32) -> f64 {
let (first, last) = (f64::from(x1), 1.0 - f64::from(x2));
let middle = f64::from(x2) - f64::from(x1);
(0..=4096)
.map(|step| {
let u = f64::from(step) / 4096.0;
let rest = 1.0 - u;
rest * rest * first + 2.0 * rest * u * middle + u * u * last
})
.fold(f64::INFINITY, f64::min)
}
#[test]
fn time_handles_are_valid_exactly_where_time_never_runs_backwards() {
let coordinate = |index: u16| f32::from(index) / 64.0 - 0.5;
let mut valid = 0;
for x1 in (0..=128).map(coordinate) {
for x2 in (0..=128).map(coordinate) {
let least = least_time_speed(x1, x2);
let verdict = time_handles_valid(x1, x2);
valid += u32::from(verdict);
assert!(
verdict == (least >= -1e-12) || least.abs() < 1e-6,
"({x1}, {x2}): {verdict}, least speed {least}"
);
}
}
assert!(valid > 65 * 65, "more than the CSS box: {valid}");
assert!(!time_handles_valid(f32::NAN, 0.5));
assert!(!time_handles_valid(0.5, f32::INFINITY));
}
#[test]
fn the_css_box_is_inside_the_valid_time_handles() {
let coordinate = |index: u16| f32::from(index) / 64.0;
for x1 in (0..=64).map(coordinate) {
for x2 in (0..=64).map(coordinate) {
assert!(time_handles_valid(x1, x2), "({x1}, {x2})");
}
}
}
#[test]
fn the_widest_valid_handles_are_near_four_thirds_and_minus_one_third() {
assert!(time_handles_valid(1.333, 2.0 / 3.0));
assert!(time_handles_valid(1.0 / 3.0, -0.333));
let partners = || (0..=2048_u16).map(|index| f32::from(index) / 1024.0 - 0.5);
for partner in partners() {
assert!(!time_handles_valid(1.34, partner), "x2 = {partner}");
assert!(!time_handles_valid(partner, -0.34), "x1 = {partner}");
}
}
#[test]
fn a_curve_outside_the_css_box_still_reaches_every_progress() {
let curve = CubicBezier::new(1.136, 0.0, 0.909, 1.0);
let mut previous = 0.0;
for step in 1..1000 {
let x = f64::from(step) / 1000.0;
let parameter = curve.time().parameter_at(x);
let back = super::component(parameter, f64::from(curve.x1), f64::from(curve.x2));
assert!((back - x).abs() < 1e-9, "{x}: {back}");
assert!(parameter >= previous, "{x}: {parameter} after {previous}");
previous = parameter;
}
}
#[test]
fn an_unweighted_value_curve_has_its_control_points_at_the_thirds() {
let curve = ValueBezier::unweighted(0.75, -0.25);
let thirds = ValueBezier::weighted(1.0 / 3.0, 0.75, 2.0 / 3.0, -0.25);
assert_eq!(curve.weights(), None);
assert_eq!(thirds.weights(), Some((1.0 / 3.0, 2.0 / 3.0)));
for step in 0..=64 {
let progress = f64::from(step) / 64.0;
let (plain, solved) = (
curve.value(-1.0, 2.5, progress),
thirds.value(-1.0, 2.5, progress),
);
assert!(
(plain - solved).abs() < 1e-6,
"{progress}: {plain} {solved}"
);
}
}
#[test]
fn the_ends_of_a_value_curve_are_its_two_values_exactly() {
for curve in [
ValueBezier::unweighted(3.0, -7.0),
ValueBezier::weighted(0.0, 5.0, 1.0, 5.0),
ValueBezier::weighted(1.136, -2.0, 0.909, 0.5),
] {
for progress in [-4.0, 0.0] {
assert_eq!(
curve.value(0.1, 0.7, progress).to_bits(),
f64::from(0.1_f32).to_bits()
);
}
for progress in [1.0, 9.0] {
assert_eq!(
curve.value(0.1, 0.7, progress).to_bits(),
f64::from(0.7_f32).to_bits()
);
}
}
}
#[test]
fn a_value_curves_slope_is_its_rise_over_its_run() {
let straight = ValueBezier::unweighted(1.0, -1.0);
for progress in [0.0, 0.3, 1.0] {
assert!((straight.slope(2.0, 5.0, progress) - 3.0).abs() < 1e-12);
}
let weighted = ValueBezier::weighted(0.25, 0.5, 0.5, -1.0);
assert!((weighted.slope(0.0, 1.0, 0.0) - 0.5 / 0.25).abs() < 1e-9);
assert!((weighted.slope(0.0, 1.0, 1.0) - 1.0 / 0.5).abs() < 1e-9);
for step in 1..64 {
let progress = f64::from(step) / 64.0;
let numeric = (weighted.value(0.0, 1.0, progress + 1e-6)
- weighted.value(0.0, 1.0, progress - 1e-6))
/ 2e-6;
let slope = weighted.slope(0.0, 1.0, progress);
assert!(
(slope - numeric).abs() < 1e-4,
"{progress}: {slope} {numeric}"
);
}
let vertical = ValueBezier::weighted(0.0, 0.5, 1.0, 0.5);
assert_eq!(vertical.slope(0.0, 1.0, 0.0).to_bits(), f64::MAX.to_bits());
assert_eq!(
vertical.slope(0.0, 1.0, 1.0).to_bits(),
(-f64::MAX).to_bits()
);
let level = ValueBezier::weighted(0.0, 0.0, 1.0, 0.0);
assert_eq!(level.slope(1.0, 1.0, 0.0).to_bits(), 0.0_f64.to_bits());
}
#[test]
fn a_value_curves_range_holds_every_value_and_is_reached() {
let curves = [
ValueBezier::unweighted(0.6, 0.6),
ValueBezier::unweighted(-2.0, 3.0),
ValueBezier::weighted(0.1, 4.0, 0.2, -3.0),
ValueBezier::weighted(1.136, 0.0, 0.909, 0.0),
ValueBezier::unweighted(0.0, 0.0),
];
for curve in curves {
for (from, to) in [(1.0, 1.0), (0.0, 1.0), (2.25, -3.5)] {
let [low, high] = curve.range(from, to);
let (mut least, mut greatest) = (f64::INFINITY, f64::NEG_INFINITY);
for step in 0..=4096 {
let value = curve.value(from, to, f64::from(step) / 4096.0);
least = least.min(value);
greatest = greatest.max(value);
}
assert!(low <= least + 1e-9 && greatest <= high + 1e-9, "{curve:?}");
assert!(
(low - least).abs() < 1e-5 && (high - greatest).abs() < 1e-5,
"{curve:?} {from}..{to}: {low}..{high} sampled {least}..{greatest}"
);
}
}
}
#[test]
fn an_end_slope_is_the_first_control_leg_with_a_time_extent() {
let near = |slope: f64, expected: f64| (slope - expected).abs() < 1e-12;
let timing = CubicBezier::new(0.25, 0.5, 0.5, 0.75);
assert!(near(timing.end_slope(false), 2.0));
assert!(near(timing.end_slope(true), 0.5));
let upright = CubicBezier::new(0.0, 0.5, 1.0, 0.25);
assert!(near(upright.end_slope(false), 0.25));
assert!(near(upright.end_slope(true), 0.5));
assert!(near(
CubicBezier::new(0.0, 0.5, 0.0, 0.25).end_slope(false),
1.0
));
assert!(near(
CubicBezier::new(1.0, 0.5, 1.0, 0.25).end_slope(true),
1.0
));
assert!(near(
CubicBezier::new(0.0, 0.0, 1.0, 1.0).end_slope(false),
1.0
));
let value = ValueBezier::weighted(0.25, 1.5, 0.5, -3.0);
assert!(near(value.end_slope(1.0, 3.0, false), 6.0));
assert!(near(value.end_slope(1.0, 3.0, true), 6.0));
let thirds = ValueBezier::unweighted(1.5, -3.0);
assert!((thirds.end_slope(1.0, 3.0, false) - 4.5).abs() < 1e-9);
assert!((thirds.end_slope(1.0, 3.0, true) - 9.0).abs() < 1e-9);
assert!((thirds.end_slope(1.0, 3.0, false) - thirds.slope(1.0, 3.0, 0.0)).abs() < 1e-9);
assert!((thirds.end_slope(1.0, 3.0, true) - thirds.slope(1.0, 3.0, 1.0)).abs() < 1e-9);
let upright = ValueBezier::weighted(0.0, 1.5, 1.0, -3.0);
assert!(near(upright.end_slope(1.0, 3.0, false), 2.0 - 3.0));
assert!(near(upright.end_slope(1.0, 3.0, true), 2.0 - 1.5));
let chord = ValueBezier::weighted(0.0, 1.5, 0.0, -3.0);
assert!(near(chord.end_slope(1.0, 3.0, false), 2.0));
assert!(near(
ValueBezier::weighted(1.0, 1.5, 1.0, -3.0).end_slope(1.0, 3.0, true),
2.0
));
}
#[test]
fn a_value_curve_needs_finite_offsets_and_both_time_coordinates() {
assert!(ValueBezier::unweighted(1e30, -1e30).is_valid());
assert!(ValueBezier::weighted(1.2, 0.0, 0.9, 0.0).is_valid());
assert!(!ValueBezier::unweighted(f32::NAN, 0.0).is_valid());
assert!(!ValueBezier::unweighted(0.0, f32::INFINITY).is_valid());
assert!(!ValueBezier::weighted(1.2, 0.0, 0.2, 0.0).is_valid());
let half = ValueBezier {
x1: Some(0.5),
..ValueBezier::unweighted(0.0, 0.0)
};
assert!(!half.is_valid());
}
#[test]
fn the_wire_form_is_a_tagged_object() {
let easing: Easing =
serde_json::from_str(r#"{"type":"cubic_bezier","x1":0.42,"y1":0,"x2":0.58,"y2":1}"#)
.expect("cubic bezier easing");
assert_eq!(
easing,
Easing::CubicBezier(CubicBezier::new(0.42, 0.0, 0.58, 1.0))
);
let linear: Easing = serde_json::from_str(r#"{"type":"linear"}"#).expect("linear");
assert_eq!(linear, Easing::Linear);
assert!(serde_json::from_str::<Easing>(r#""linear""#).is_err());
assert!(serde_json::from_str::<Easing>(r#"{"type":"linear","x1":0}"#).is_err());
}
}