Add craft-ease: easing curves, keyed tracks, motion paths and springs

The crate's parts come from AniCraft's anicraft-doc and EffectCraft's
effectcraft-keyframe.

- Easing: linear, hold, the Classic slider, the named In, Out and In Out
  families, CSS cubic-bezier(), speed and influence, editable custom and
  sampled curves, and a physical spring. apply() returns exactly 0 and 1
  at the ends and does not allocate.
- Track<T> over f32, f64, Vec2 and arrays, sampled by binary search.
- MotionPath: constant-speed Bezier paths with arc-length tables built once.
- Spring and SpringState: each step uses the exact solution of the damped
  spring equation, so a step costs O(1) at any frame rate.

serde is optional; without it the crate has no dependencies.
This commit is contained in:
dotCooCoo committed 2026-11-19 19:47:10 -08:00
1 parent 453b0da782
commit 377a354fa8
17 files changed
+3829

No files matched your search

Generated
+8
View File
@@ -1843,6 +1843,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-ease"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "craft-ecproj-format"
version = "0.1.0"
+1
View File
@@ -70,6 +70,7 @@ craft-deckcraft-format = { path = "crates/deckcraft-format" }
craft-designcraft-format = { path = "crates/designcraft-format" }
craft-dxf = { path = "crates/dxf" }
craft-drawingml = { path = "crates/drawingml" }
craft-ease = { path = "crates/ease" }
craft-eps = { path = "crates/eps" }
craft-elf = { path = "crates/elf" }
craft-file-formats = { path = "crates/file-formats" }
+4
View File
@@ -115,6 +115,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines
(`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps
(`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format.
- [`craft-ease`](crates/ease/README.md): easing curves, keyed tracks, constant-speed motion paths
and damped springs for animation: named eases, CSS `cubic-bezier()`, speed and influence,
editable custom and sampled curves, hold keys and a spring stepped by its exact solution.
From StudioCraft, AniCraft and EffectCraft. No dependencies without the optional `serde` feature.
- [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names.
- [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary
preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`),
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "craft-ease"
description = "Easing curves, keyed tracks, motion paths and springs for animation: named eases, cubic Bezier and speed/influence eases, editable custom curves, sampled tables, hold keys, constant-speed Bezier paths and an O(1) damped spring"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[features]
default = ["serde"]
# Reading and writing eases (spring eases included) and tracks with serde.
serde = ["dep:serde"]
[dependencies]
serde = { workspace = true, features = ["rc"], optional = true }
[dev-dependencies]
serde_json = { workspace = true }
+104
View File
@@ -0,0 +1,104 @@
# craft-ease
Easing curves, keyed tracks, constant-speed motion paths and damped springs for animation in the
Craft apps. The crate depends only on the standard library, with `serde` as an optional feature
(on by default). It builds for `wasm32-unknown-unknown`.
Moved from StudioCraft's `craft-ease`
([`crates/craft-ease`](https://github.com/blamejs/StudioCraft/tree/b1ead5a9db0d478bf7171ce9e942e600ca500fea/crates/craft-ease)).
Parts of it started in other Craft apps:
- `Easing`, `CustomEase`, `SampledEase` and the curve editing came from AniCraft's `anicraft-doc`
(`crates/doc/src/easing.rs`). They now use `f64` and the crate's own `Vec2`, the Back and
Elastic In Out curves follow the published equations, and `Hold` and `Spring` are new
variants.
- Speed and influence eases, hold keys and the constant-speed motion paths came from
EffectCraft's `effectcraft-keyframe` (`crates/keyframe/src/lib.rs`). `Track` takes any
`Animatable` value instead of the app's value type, and `MotionPath` continues in a straight
line past either end.
- `Spring` replaces AniCraft's stepped spring (`crates/doc/src/spring.rs`) with the exact
solution of the damped spring equation, so a step costs O(1) and any step length is stable.
Licensed under MIT OR Apache-2.0.
## Contents
- `Easing` maps linear progress `t` in `0..=1` to eased progress. The variants are no ease
(`Linear`), `Hold`, the Classic slider (−100 to +100), nine named families (Quad, Cubic, Quart,
Quint, Sine, Back, Circ, Bounce, Elastic) each In, Out and In Out, `CubicBezier` as the CSS
Easing Functions specification defines `cubic-bezier()`, an editable `CustomEase`, a
`SampledEase` table and a physical `SpringEase`. `Easing::apply(t)` returns exactly 0 for
`t <= 0` and NaN, and exactly 1 for `t >= 1`. It does not allocate.
- `Easing::from_temporal` builds the cubic Bezier for a segment from the speed and influence of
its two sides (`TemporalEase`), as keyframe velocity dialogs give them. `Easing::temporal`
reads them back.
- `Track<T>` holds keys of any `Animatable` value (`f32`, `f64`, `Vec2`, `[f32; N]`,
`[f64; N]`), each with the ease to the next key. `Track::sample` is a binary search and does
not allocate.
- `MotionPath` is a chain of cubic Bezier segments with an arc-length table per segment, built
once. `point_at` and `point_at_length` move at constant speed along it and continue in a
straight line past either end. `MotionPath::through` sets the handles of a smooth path through
a list of anchors.
- `Spring` and `SpringState` move a value toward a target. `SpringState::step` applies the exact
solution of the damped spring equation over the step, so a step costs O(1), any step length is
stable, and many short steps give the same value as one long one.
## Checked and lenient constructors
Every type has a checked constructor that returns `EaseError` for a value that is not finite or
is out of range: `Easing::cubic_bezier`, `Easing::from_temporal`, `Easing::spring`,
`CustomEase::try_new`, `SampledEase::try_new`, `Track::from_keys`, `MotionPath::new`,
`Spring::new` and `Spring::from_physical`. `CustomEase::new` and `SampledEase::new` repair what
they are given instead, and files are read through the same repairs. Reading a track refuses a
file with more than `MAX_TRACK_KEYS` keys while it reads.
## Limits
| Constant | Value |
| --- | --- |
| `MAX_EASE_Y` | 10 (eased values stay within ±10) |
| `MAX_EASE_POINTS` | 64 points in a custom ease |
| `MAX_EASE_SAMPLES` | 1,025 samples in a sampled ease |
| `MAX_TRACK_KEYS` | 100,000 keys in a track |
| `MAX_PATH_SEGMENTS` | 10,000 segments in a motion path |
| `MAX_SPRING_HZ` | 10,000 swings a second |
| `MAX_DAMPING_RATIO` | 1,000,000 |
| `MIN_INFLUENCE` | 0.001 |
## Sources
- The named families are the easing equations published by Robert Penner. Back In Out and
Elastic In Out use the published In Out equations, which scale Back's overshoot by 1.525 and
give Elastic a longer period.
- `CubicBezier` follows the CSS Easing Functions Level 1 specification.
## Details
- Values are `f64` throughout.
- The `serde` feature reads and writes `Easing` (spring eases included) and `Track`.
`MotionPath`, `Spring` and `SpringState` are not serialized.
- Serialized eases keep their form: presets are strings such as `"QuadIn"`, and `Classic`,
`CubicBezier`, `Custom` and `Sampled` are one-key objects. `Hold` and `Spring` are the last
variants. A track is read from its fields by name or in order.
- `Easing::apply` returns exactly 0 and 1 at the ends for every variant, and `+∞` gives 1.
- `CubicBezier` keeps y1 and y2 within ±10 when it is evaluated. Its solver inverts the curve
with both handles at full reach in closed form, and otherwise stops within 1e-12 of the span
in at most 64 steps.
- A sampled ease's name drops control characters, bidirectional overrides and invisible format
characters such as zero-width spaces. A sampled ease with no name left is named "Sampled ease".
Reading a file keeps the first 65,536 entries of a custom ease's points or a sampled ease's
values and skips the rest.
- Without the `serde` feature the crate has no dependencies, and its tests that read and write
files are left out.
- `Track` takes `Easing::Hold` for held keys and treats −0 and +0 as one time. It samples keys
at opposite ends of the `f64` range without overflow, and returns `EaseError::Overflow` when
an overshooting ease carries a value past what its type holds.
- Speed and influence become a `CubicBezier` (`Easing::from_temporal`), with the influence
allowed from 0.001 to 1 on each side, including a sum above 1.
- Motion paths are measured by Gauss-Legendre quadrature per table cell with Newton refinement.
`MotionPath::through` sets each handle to a sixth of the line between the anchor's neighbors.
A segment whose handles lie on its chord is treated as a straight line.
- `Spring::from_physical(mass, stiffness, damping)` takes a mass, a stiffness and a damping
coefficient. A spring ease that is still moving after 10 seconds has the distance it is still
off taken out evenly over the ease, so it reaches 1 without a jump. Any other spring ease is
within about 0.1 % of 1 just before it reaches 1.
+360
View File
@@ -0,0 +1,360 @@
//! [`CustomEase`]: an editable curve of several Bezier segments from (0, 0) to (1, 1).
use crate::{EaseError, Vec2, bez, solve_monotonic};
/// Most points (anchors) a custom ease keeps; longer curves are thinned evenly.
pub const MAX_EASE_POINTS: usize = 64;
/// Values a custom ease (and its handles) may reach: overshoot well past 0..1, never unbounded.
pub const MAX_EASE_Y: f64 = 10.0;
/// Most points read from a file or a caller before thinning (bounds the sort).
const MAX_EASE_INPUT: usize = 65_536;
/// A point of a custom ease: where it is (x = time, y = progress), its handles as offsets from
/// it (in toward the previous point, out toward the next), and whether it is smooth (handles in
/// line, moved together) or a corner. In files the in handle is `"in"`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EasePoint {
pub at: Vec2,
#[cfg_attr(feature = "serde", serde(rename = "in", default))]
pub h_in: Vec2,
#[cfg_attr(feature = "serde", serde(default))]
pub out: Vec2,
#[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "is_false"))]
pub smooth: bool,
}
#[cfg(feature = "serde")]
fn is_false(b: &bool) -> bool {
!*b
}
/// Which handle of a point.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Handle {
In,
Out,
}
/// A custom ease: Bezier segments through its points, from (0, 0) to (1, 1).
///
/// Always valid, however it was made: 2 to [`MAX_EASE_POINTS`] finite points sorted by x, the
/// ends fixed at (0, 0) and (1, 1), every handle's x between its point and the neighbor it
/// reaches toward (so each segment's x runs forwards and time never runs backwards), and every
/// value within ±[`MAX_EASE_Y`]. Reading a file repairs a curve the way [`CustomEase::new`]
/// does.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(from = "CustomEaseFile"))]
pub struct CustomEase {
points: Vec<EasePoint>,
}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct CustomEaseFile {
#[serde(default, deserialize_with = "read_points")]
points: Vec<EasePoint>,
}
/// The first [`MAX_EASE_INPUT`] points of a file's list, the way [`CustomEase::new`] keeps them.
#[cfg(feature = "serde")]
fn read_points<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<EasePoint>, D::Error> {
crate::read_first(d, MAX_EASE_INPUT)
}
#[cfg(feature = "serde")]
impl From<CustomEaseFile> for CustomEase {
fn from(f: CustomEaseFile) -> CustomEase {
CustomEase::new(f.points)
}
}
impl Default for CustomEase {
fn default() -> CustomEase {
CustomEase::linear()
}
}
impl CustomEase {
/// The straight line, its handles a third of the way along.
pub fn linear() -> CustomEase {
CustomEase::linear_points()
}
/// One segment with handles `(x1, y1)` and `(x2, y2)` in the unit box.
pub fn from_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> CustomEase {
CustomEase::new(vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(x1, y1), smooth: false },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(x2 - 1.0, y2 - 1.0), out: Vec2::ZERO, smooth: false },
])
}
/// The curve of absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them): `None`
/// when the count is wrong.
pub fn from_flat(pts: &[Vec2]) -> Option<CustomEase> {
if pts.len() < 4 || pts.len() % 3 != 1 || pts.len() > MAX_EASE_INPUT {
return None;
}
let mut out: Vec<EasePoint> = Vec::with_capacity(pts.len() / 3 + 1);
for (i, at) in pts.iter().enumerate().step_by(3) {
let h_in = if i == 0 { Vec2::ZERO } else { pts.get(i - 1).map_or(Vec2::ZERO, |c| *c - *at) };
let h_out = pts.get(i + 1).map_or(Vec2::ZERO, |c| *c - *at);
// Handles in line (opposite ways) make a smooth point, as an editor would draw it.
let smooth = h_in.length() > 1e-6 && h_out.length() > 1e-6 && (h_in.normalized().dot(h_out.normalized()) + 1.0).abs() < 1e-3;
out.push(EasePoint { at: *at, h_in, out: h_out, smooth });
}
Some(CustomEase::new(out))
}
/// A curve from points a caller supplies, checked: an error for a point or handle that is
/// not finite, fewer than 2 points or more than [`MAX_EASE_POINTS`]. The points are then
/// sorted, the ends pinned and the handles brought within reach as [`CustomEase::new`] does.
pub fn try_new(pts: Vec<EasePoint>) -> Result<CustomEase, EaseError> {
if pts.iter().any(|p| !(p.at.is_finite() && p.h_in.is_finite() && p.out.is_finite())) {
return Err(EaseError::NotFinite("ease point"));
}
if pts.len() < 2 {
return Err(EaseError::TooFew { what: "a custom ease", need: 2 });
}
if pts.len() > MAX_EASE_POINTS {
return Err(EaseError::Full(MAX_EASE_POINTS));
}
Ok(CustomEase::new(pts))
}
/// A valid curve from any points, as a file holds them (see the type's docs): non-finite
/// points are dropped and non-finite handles zeroed, the rest sorted by x, a curve longer
/// than [`MAX_EASE_POINTS`] thinned evenly, the ends pinned and every handle brought within
/// reach. Fewer than two points make the straight line.
pub fn new(mut pts: Vec<EasePoint>) -> CustomEase {
pts.truncate(MAX_EASE_INPUT);
pts.retain(|p| p.at.is_finite());
for p in pts.iter_mut() {
p.at = Vec2::new(p.at.x.clamp(0.0, 1.0), p.at.y.clamp(-MAX_EASE_Y, MAX_EASE_Y));
if !p.h_in.is_finite() {
p.h_in = Vec2::ZERO;
}
if !p.out.is_finite() {
p.out = Vec2::ZERO;
}
}
pts.sort_by(|a, b| a.at.x.total_cmp(&b.at.x));
if pts.len() > MAX_EASE_POINTS {
let n = pts.len();
let keep: Vec<usize> = (0..MAX_EASE_POINTS).map(|k| k * (n - 1) / (MAX_EASE_POINTS - 1)).collect();
pts = keep.into_iter().filter_map(|i| pts.get(i).copied()).collect();
}
if pts.len() < 2 {
return CustomEase::linear_points();
}
if let Some(p) = pts.first_mut() {
p.at = Vec2::ZERO;
}
if let Some(p) = pts.last_mut() {
p.at = Vec2::new(1.0, 1.0);
}
let mut c = CustomEase { points: pts };
c.clamp_handles();
c
}
/// [`CustomEase::linear`] built directly (so [`CustomEase::new`] does not recurse).
fn linear_points() -> CustomEase {
let third = 1.0 / 3.0;
CustomEase {
points: vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, third), smooth: false },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-third, -third), out: Vec2::ZERO, smooth: false },
],
}
}
/// Brings every handle within reach (see the type's docs).
fn clamp_handles(&mut self) {
let xs: Vec<f64> = self.points.iter().map(|p| p.at.x).collect();
let n = self.points.len();
for (i, p) in self.points.iter_mut().enumerate() {
let prev = if i == 0 { p.at.x } else { xs.get(i - 1).copied().unwrap_or(p.at.x) };
let next = xs.get(i + 1).copied().unwrap_or(p.at.x);
let y = |h: f64, at: f64| h.clamp(-MAX_EASE_Y - at, MAX_EASE_Y - at);
p.h_in = if i == 0 { Vec2::ZERO } else { Vec2::new(p.h_in.x.clamp(prev - p.at.x, 0.0), y(p.h_in.y, p.at.y)) };
p.out = if i + 1 == n { Vec2::ZERO } else { Vec2::new(p.out.x.clamp(0.0, next - p.at.x), y(p.out.y, p.at.y)) };
}
}
pub fn points(&self) -> &[EasePoint] {
&self.points
}
/// The control points of segment `i` (from point `i` to point `i + 1`), absolute; the inner
/// points' x always between the ends' (so x runs forwards along it).
pub fn segment(&self, i: usize) -> Option<[Vec2; 4]> {
let (a, b) = (self.points.get(i)?, self.points.get(i.checked_add(1)?)?);
let inner = |p: Vec2| Vec2::new(p.x.clamp(a.at.x, b.at.x.max(a.at.x)), p.y);
Some([a.at, inner(a.at + a.out), inner(b.at + b.h_in), b.at])
}
/// The segment that time `t` falls in.
fn segment_at(&self, t: f64) -> usize {
self.points.partition_point(|p| p.at.x <= t).saturating_sub(1).min(self.points.len().saturating_sub(2))
}
/// The eased value at time `t` (0 at the start, 1 at the end, anything between, overshoot
/// included). `t` outside `0..=1` is clamped, and NaN reads as 0.
pub fn apply(&self, t: f64) -> f64 {
if t.is_nan() || t <= 0.0 {
return 0.0;
}
if t >= 1.0 {
return 1.0;
}
let Some([p0, p1, p2, p3]) = self.segment(self.segment_at(t)) else { return t };
if p3.x <= p0.x {
return p3.y;
}
let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]);
bez(s, [p0.y, p1.y, p2.y, p3.y])
}
/// Adds a point on the curve at time `t`, leaving its shape as it was (the segment is split
/// in two): the new curve and the point's index. `None` at the ends, on an existing point,
/// or when the curve is full.
pub fn insert_at(&self, t: f64) -> Option<(CustomEase, usize)> {
if !t.is_finite()
|| t <= 1e-4
|| t >= 1.0 - 1e-4
|| self.points.len() >= MAX_EASE_POINTS
|| self.points.iter().any(|p| (p.at.x - t).abs() < 1e-4)
{
return None;
}
let i = self.segment_at(t);
let [p0, p1, p2, p3] = self.segment(i)?;
let s = solve_monotonic(t, [p0.x, p1.x, p2.x, p3.x]);
// de Casteljau at s.
let (a, b, c) = (p0.lerp(p1, s), p1.lerp(p2, s), p2.lerp(p3, s));
let (d, e) = (a.lerp(b, s), b.lerp(c, s));
let m = d.lerp(e, s);
let mut pts = self.points.clone();
if let Some(q) = pts.get_mut(i) {
q.out = a - p0;
}
if let Some(q) = pts.get_mut(i + 1) {
q.h_in = c - p3;
}
pts.insert(i + 1, EasePoint { at: m, h_in: d - m, out: e - m, smooth: true });
Some((CustomEase::new(pts), i + 1))
}
/// Moves point `i` (not an end) to `to`, its handles with it; its x stays between its
/// neighbors' so time keeps running forwards. `None` for an end, a missing point or a
/// non-finite `to`.
pub fn move_point(&self, i: usize, to: Vec2) -> Option<CustomEase> {
if i == 0 || i >= self.points.len().saturating_sub(1) || !to.is_finite() {
return None;
}
let (lo, hi) = (self.points.get(i - 1)?.at.x, self.points.get(i + 1)?.at.x);
let mut c = self.clone();
let p = c.points.get_mut(i)?;
p.at = Vec2::new(to.x.clamp(lo, hi), to.y.clamp(-MAX_EASE_Y, MAX_EASE_Y));
c.clamp_handles();
Some(c)
}
/// Moves handle `which` of point `i` to `to` (absolute); a smooth point's other handle turns
/// to stay in line, keeping its length. `None` for a handle the point does not have (the
/// first point's in, the last's out) or a non-finite `to`.
pub fn move_handle(&self, i: usize, which: Handle, to: Vec2) -> Option<CustomEase> {
let n = self.points.len();
if !to.is_finite() || i >= n || (which == Handle::In && i == 0) || (which == Handle::Out && i + 1 == n) {
return None;
}
let mut c = self.clone();
let p = c.points.get_mut(i)?;
let off = to - p.at;
match which {
Handle::In => p.h_in = off,
Handle::Out => p.out = off,
}
c.clamp_handles();
if i > 0 && i + 1 < n {
let (prev, next) = (c.points.get(i - 1)?.at.x, c.points.get(i + 1)?.at.x);
if let Some(p) = c.points.get_mut(i).filter(|p| p.smooth) {
let at = p.at;
let (moved, other, x_reach) = match which {
Handle::In => (p.h_in, &mut p.out, next - at.x),
Handle::Out => (p.out, &mut p.h_in, prev - at.x),
};
let dir = -moved.normalized();
if dir != Vec2::ZERO {
// Shortened to stay within reach along `dir`, so the clamp below does not
// turn it out of line.
let mut len = other.length().max(1e-3);
if dir.x != 0.0 {
len = len.min((x_reach / dir.x).max(0.0));
}
if dir.y != 0.0 {
let y_reach = if dir.y > 0.0 { MAX_EASE_Y - at.y } else { -MAX_EASE_Y - at.y };
len = len.min((y_reach / dir.y).max(0.0));
}
*other = dir * len;
}
}
}
c.clamp_handles();
Some(c)
}
/// Removes point `i` (not an end). `None` for an end or a missing point.
pub fn remove(&self, i: usize) -> Option<CustomEase> {
if i == 0 || i >= self.points.len().saturating_sub(1) {
return None;
}
let mut pts = self.points.clone();
pts.remove(i);
Some(CustomEase::new(pts))
}
/// Makes point `i` smooth (its handles in line with its neighbors' chord, a third of the way
/// to each) or a corner (its handles on the point, so the curve turns sharply there).
pub fn set_smooth(&self, i: usize, smooth: bool) -> Option<CustomEase> {
let n = self.points.len();
let prev = if i == 0 { None } else { self.points.get(i - 1).map(|p| p.at) };
let next = i.checked_add(1).and_then(|j| self.points.get(j)).map(|p| p.at);
let mut c = self.clone();
let p = c.points.get_mut(i)?;
p.smooth = smooth && i > 0 && i + 1 < n;
if smooth {
let (a, b) = (prev.unwrap_or(p.at), next.unwrap_or(p.at));
let chord = b - a;
let dir = if chord.x > 1e-6 { chord * (1.0 / chord.x) } else { Vec2::new(1.0, 0.0) };
if prev.is_some() {
p.h_in = -dir * ((p.at.x - a.x) / 3.0);
}
if next.is_some() {
p.out = dir * ((b.x - p.at.x) / 3.0);
}
} else {
p.h_in = Vec2::ZERO;
p.out = Vec2::ZERO;
}
c.clamp_handles();
Some(c)
}
/// The flat list of absolute points `[p0, c1, c2, p1, …]` (see [`CustomEase::from_flat`]).
pub fn to_flat(&self) -> Vec<Vec2> {
let mut out = Vec::with_capacity(self.points.len() * 3);
for (i, p) in self.points.iter().enumerate() {
if i > 0 {
out.push(p.at + p.h_in);
}
out.push(p.at);
if i + 1 < self.points.len() {
out.push(p.at + p.out);
}
}
out
}
}
+644
View File
@@ -0,0 +1,644 @@
//! [`Easing`]: maps linear progress to eased progress.
use std::sync::Arc;
use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y};
use crate::sampled::SampledEase;
use crate::spring::Spring;
use crate::{EaseError, Vec2, bez, finite, solve_monotonic, within};
/// The Back family's overshoot (about 10 %).
const BACK: f64 = 1.701_58;
/// Back In Out's overshoot, as the published equation scales it.
const BACK_IN_OUT: f64 = BACK * 1.525;
/// The smallest influence a [`TemporalEase`] may have.
pub const MIN_INFLUENCE: f64 = 0.001;
/// The families of named eases.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EaseFamily {
Quad,
Cubic,
Quart,
Quint,
Sine,
Back,
Circ,
Bounce,
Elastic,
}
impl EaseFamily {
pub const ALL: [EaseFamily; 9] = [
EaseFamily::Quad,
EaseFamily::Cubic,
EaseFamily::Quart,
EaseFamily::Quint,
EaseFamily::Sine,
EaseFamily::Back,
EaseFamily::Circ,
EaseFamily::Bounce,
EaseFamily::Elastic,
];
/// The family's English name.
pub fn label(self) -> &'static str {
match self {
EaseFamily::Quad => "Quad",
EaseFamily::Cubic => "Cubic",
EaseFamily::Quart => "Quart",
EaseFamily::Quint => "Quint",
EaseFamily::Sine => "Sine",
EaseFamily::Back => "Back",
EaseFamily::Circ => "Circ",
EaseFamily::Bounce => "Bounce",
EaseFamily::Elastic => "Elastic",
}
}
/// The ease in, `In(t)`. With `in_out` set, the curve whose halves make In Out: the
/// published In Out equations scale Back's overshoot by 1.525 and give Elastic a longer
/// period (4.5 instead of 3 per unit) and its own phase; the other families use `In(t)`.
fn ease_in(self, t: f64, in_out: bool) -> f64 {
use std::f64::consts::PI;
match self {
EaseFamily::Quad => t * t,
EaseFamily::Cubic => t * t * t,
EaseFamily::Quart => t * t * t * t,
EaseFamily::Quint => t * t * t * t * t,
EaseFamily::Sine => 1.0 - (t * PI * 0.5).cos(),
EaseFamily::Back => {
let c = if in_out { BACK_IN_OUT } else { BACK };
(c + 1.0) * t * t * t - c * t * t
}
EaseFamily::Circ => 1.0 - (1.0 - t * t).max(0.0).sqrt(),
EaseFamily::Bounce => 1.0 - bounce_out(1.0 - t),
EaseFamily::Elastic => {
if t <= 0.0 {
0.0
} else if t >= 1.0 {
1.0
} else if in_out {
-(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 11.125) * (2.0 * PI / 4.5)).sin()
} else {
-(2f64.powf(10.0 * t - 10.0)) * ((10.0 * t - 10.75) * (2.0 * PI / 3.0)).sin()
}
}
}
}
/// Where the ease in changes formula (other than 0 and 1): Bounce is four parabolas.
fn breaks_in(self) -> &'static [f64] {
match self {
// 1 − the Out breakpoints (1/2.75, 2/2.75, 2.5/2.75), in order.
EaseFamily::Bounce => &[0.25 / 2.75, 0.75 / 2.75, 1.75 / 2.75],
_ => &[],
}
}
/// Bezier segments per ease in that draw it to within a hair (see [`Easing::to_custom`]);
/// cubic polynomials (Quad, Cubic, Back) and the parabolas of Bounce are exact with one.
fn pieces_in(self) -> usize {
match self {
EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce | EaseFamily::Circ => 1,
EaseFamily::Quart | EaseFamily::Quint | EaseFamily::Sine => 4,
EaseFamily::Elastic => 24,
}
}
}
fn bounce_out(t: f64) -> f64 {
const N: f64 = 7.5625;
const D: f64 = 2.75;
if t < 1.0 / D {
N * t * t
} else if t < 2.0 / D {
let u = t - 1.5 / D;
N * u * u + 0.75
} else if t < 2.5 / D {
let u = t - 2.25 / D;
N * u * u + 0.9375
} else {
let u = t - 2.625 / D;
N * u * u + 0.984_375
}
}
/// Which way a named ease eases.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EaseDir {
In,
Out,
InOut,
}
impl EaseDir {
pub const ALL: [EaseDir; 3] = [EaseDir::In, EaseDir::Out, EaseDir::InOut];
pub fn label(self) -> &'static str {
match self {
EaseDir::In => "In",
EaseDir::Out => "Out",
EaseDir::InOut => "In Out",
}
}
}
/// One side of a segment's ease as a keyframe velocity dialog gives it: `speed` normalized
/// (speed × segment duration ÷ value change, so 1 is the straight line's speed) and
/// `influence` the fraction of the segment its handle reaches.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TemporalEase {
pub speed: f64,
pub influence: f64,
}
impl TemporalEase {
/// A side that leaves at rest with a third of the segment's influence.
pub const EASY: TemporalEase = TemporalEase { speed: 0.0, influence: 1.0 / 3.0 };
/// A linear side next to an eased one: the segment's average speed with a sixth of its
/// influence.
pub const LINEAR: TemporalEase = TemporalEase { speed: 1.0, influence: 1.0 / 6.0 };
}
/// A damped spring as an ease: a mass on a spring with damping, released from 0 toward 1 and
/// played over the time it takes to stay within 0.1 % of 1 (at most 10 seconds of its motion).
/// Values outside the ranges [`Spring::from_physical`] accepts are brought into them when the
/// ease is evaluated.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SpringEase {
pub mass: f64,
pub stiffness: f64,
pub damping: f64,
}
impl SpringEase {
/// A gentle spring with a small overshoot (mass 1, stiffness 100, damping 15).
pub const GENTLE: SpringEase = SpringEase { mass: 1.0, stiffness: 100.0, damping: 15.0 };
fn apply(self, t: f64) -> f64 {
Spring::physical_lenient(self.mass, self.stiffness, self.damping).ease(t)
}
}
/// Maps linear progress `t ∈ [0, 1]` to eased progress.
///
/// The unit variants are the named presets; their names are the file format and the names
/// commands use. [`Easing::apply`] returns exactly 0 for `t <= 0` (and for NaN) and exactly 1
/// for `t >= 1`, whatever the variant holds.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Easing {
#[default]
Linear,
QuadIn,
QuadOut,
QuadInOut,
CubicIn,
CubicOut,
CubicInOut,
/// The traditional single-slider ease: −100 (ease in) … 0 (linear) … +100 (ease out).
Classic(f64),
/// A cubic Bezier through (0, 0), (x1, y1), (x2, y2), (1, 1), as the CSS Easing Functions
/// specification defines `cubic-bezier()`. Evaluation keeps x1 and x2 within `0..=1` and
/// y1 and y2 within ±[`MAX_EASE_Y`].
CubicBezier(f64, f64, f64, f64),
QuartIn,
QuartOut,
QuartInOut,
QuintIn,
QuintOut,
QuintInOut,
SineIn,
SineOut,
SineInOut,
BackIn,
BackOut,
BackInOut,
CircIn,
CircOut,
CircInOut,
BounceIn,
BounceOut,
BounceInOut,
ElasticIn,
ElasticOut,
ElasticInOut,
/// A curve of several Bezier segments, shared when copied.
Custom(Arc<CustomEase>),
/// A table of values, read between samples by straight lines.
Sampled(Arc<SampledEase>),
/// A damped spring.
Spring(SpringEase),
/// Stays at the start until the end, then jumps: 0 for `t < 1`.
Hold,
}
impl Easing {
pub const LINEAR_LABEL: &'static str = "Linear";
/// The `smooth` alias's curve.
pub const SMOOTH: Easing = Easing::CubicBezier(0.25, 0.1, 0.25, 1.0);
/// A cubic Bezier ease, checked: every value finite, `x1` and `x2` within `0..=1` (so time
/// runs forwards), `y1` and `y2` within ±[`MAX_EASE_Y`].
pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> Result<Easing, EaseError> {
within(x1, 0.0, 1.0, "x1")?;
within(x2, 0.0, 1.0, "x2")?;
within(y1, -MAX_EASE_Y, MAX_EASE_Y, "y1")?;
within(y2, -MAX_EASE_Y, MAX_EASE_Y, "y2")?;
Ok(Easing::CubicBezier(x1, y1, x2, y2))
}
/// The ease of a segment from its two sides: `out` leaving the first key, `into` arriving at
/// the second. Each influence must be within [`MIN_INFLUENCE`] to 1 and each speed finite.
/// The result is the cubic Bezier with handles `(i0, s0 × i0)` and `(1 − i1, 1 − s1 × i1)`.
pub fn from_temporal(out: TemporalEase, into: TemporalEase) -> Result<Easing, EaseError> {
finite(out.speed, "out speed")?;
finite(into.speed, "in speed")?;
let i0 = within(out.influence, MIN_INFLUENCE, 1.0, "out influence")?;
let i1 = within(into.influence, MIN_INFLUENCE, 1.0, "in influence")?;
let (y1, y2) = (out.speed * i0, 1.0 - into.speed * i1);
if !(y1.abs() <= MAX_EASE_Y && y2.abs() <= MAX_EASE_Y) {
return Err(EaseError::OutOfRange { what: "speed × influence", min: -MAX_EASE_Y, max: MAX_EASE_Y });
}
Ok(Easing::CubicBezier(i0, y1, 1.0 - i1, y2))
}
/// The two sides of an ease that one cubic Bezier draws (see [`Easing::from_temporal`] and
/// [`Easing::as_bezier`]). A handle with no reach has speed 0.
pub fn temporal(&self) -> Option<(TemporalEase, TemporalEase)> {
let (x1, y1, x2, y2) = self.as_bezier()?;
let (i0, i1) = (x1.clamp(0.0, 1.0), (1.0 - x2).clamp(0.0, 1.0));
let s0 = if i0 > 0.0 { y1 / i0 } else { 0.0 };
let s1 = if i1 > 0.0 { (1.0 - y2) / i1 } else { 0.0 };
Some((TemporalEase { speed: s0, influence: i0 }, TemporalEase { speed: s1, influence: i1 }))
}
/// A spring ease, checked as [`Spring::from_physical`] checks its values.
pub fn spring(mass: f64, stiffness: f64, damping: f64) -> Result<Easing, EaseError> {
Spring::from_physical(mass, stiffness, damping)?;
Ok(Easing::Spring(SpringEase { mass, stiffness, damping }))
}
/// The named ease of `family` easing `dir`.
pub fn preset(family: EaseFamily, dir: EaseDir) -> Easing {
use EaseDir::*;
use EaseFamily::*;
match (family, dir) {
(Quad, In) => Easing::QuadIn,
(Quad, Out) => Easing::QuadOut,
(Quad, InOut) => Easing::QuadInOut,
(Cubic, In) => Easing::CubicIn,
(Cubic, Out) => Easing::CubicOut,
(Cubic, InOut) => Easing::CubicInOut,
(Quart, In) => Easing::QuartIn,
(Quart, Out) => Easing::QuartOut,
(Quart, InOut) => Easing::QuartInOut,
(Quint, In) => Easing::QuintIn,
(Quint, Out) => Easing::QuintOut,
(Quint, InOut) => Easing::QuintInOut,
(Sine, In) => Easing::SineIn,
(Sine, Out) => Easing::SineOut,
(Sine, InOut) => Easing::SineInOut,
(Back, In) => Easing::BackIn,
(Back, Out) => Easing::BackOut,
(Back, InOut) => Easing::BackInOut,
(Circ, In) => Easing::CircIn,
(Circ, Out) => Easing::CircOut,
(Circ, InOut) => Easing::CircInOut,
(Bounce, In) => Easing::BounceIn,
(Bounce, Out) => Easing::BounceOut,
(Bounce, InOut) => Easing::BounceInOut,
(Elastic, In) => Easing::ElasticIn,
(Elastic, Out) => Easing::ElasticOut,
(Elastic, InOut) => Easing::ElasticInOut,
}
}
/// The family and direction of a named ease.
pub fn family(&self) -> Option<(EaseFamily, EaseDir)> {
use EaseDir::*;
use EaseFamily::*;
Some(match self {
Easing::QuadIn => (Quad, In),
Easing::QuadOut => (Quad, Out),
Easing::QuadInOut => (Quad, InOut),
Easing::CubicIn => (Cubic, In),
Easing::CubicOut => (Cubic, Out),
Easing::CubicInOut => (Cubic, InOut),
Easing::QuartIn => (Quart, In),
Easing::QuartOut => (Quart, Out),
Easing::QuartInOut => (Quart, InOut),
Easing::QuintIn => (Quint, In),
Easing::QuintOut => (Quint, Out),
Easing::QuintInOut => (Quint, InOut),
Easing::SineIn => (Sine, In),
Easing::SineOut => (Sine, Out),
Easing::SineInOut => (Sine, InOut),
Easing::BackIn => (Back, In),
Easing::BackOut => (Back, Out),
Easing::BackInOut => (Back, InOut),
Easing::CircIn => (Circ, In),
Easing::CircOut => (Circ, Out),
Easing::CircInOut => (Circ, InOut),
Easing::BounceIn => (Bounce, In),
Easing::BounceOut => (Bounce, Out),
Easing::BounceInOut => (Bounce, InOut),
Easing::ElasticIn => (Elastic, In),
Easing::ElasticOut => (Elastic, Out),
Easing::ElasticInOut => (Elastic, InOut),
Easing::Linear
| Easing::Classic(_)
| Easing::CubicBezier(..)
| Easing::Custom(_)
| Easing::Sampled(_)
| Easing::Spring(_)
| Easing::Hold => return None,
})
}
/// Every named preset: no ease, then each family In, Out, In Out.
pub fn named() -> impl Iterator<Item = Easing> {
std::iter::once(Easing::Linear).chain(EaseFamily::ALL.into_iter().flat_map(|f| EaseDir::ALL.into_iter().map(move |d| Easing::preset(f, d))))
}
/// The preset's name in commands and files (`"QuadIn"`, `"ElasticInOut"`, `"Hold"`), `None`
/// for eases with values.
pub fn name(&self) -> Option<String> {
match self {
Easing::Linear => Some("Linear".into()),
Easing::Hold => Some("Hold".into()),
_ => self.family().map(|(f, d)| format!("{}{}", f.label(), d.label().replace(' ', ""))),
}
}
/// The preset named `name`, ignoring case, spaces, `-` and `_` (`"back in out"`), with the
/// aliases `none`, `easein`, `easeout`, `easeinout` and `smooth`.
pub fn from_name(name: &str) -> Option<Easing> {
let key: String = name.chars().filter(|c| !matches!(c, '-' | '_' | ' ')).flat_map(char::to_lowercase).collect();
match key.as_str() {
"none" | "noease" => return Some(Easing::Linear),
"hold" => return Some(Easing::Hold),
"easein" => return Some(Easing::QuadIn),
"easeout" => return Some(Easing::QuadOut),
"easeinout" => return Some(Easing::QuadInOut),
"smooth" => return Some(Easing::SMOOTH),
_ => {}
}
Easing::named().find(|e| e.name().is_some_and(|n| n.to_lowercase() == key))
}
/// An English label for menus and reports.
pub fn label(&self) -> String {
match self {
Easing::Linear => Easing::LINEAR_LABEL.to_string(),
Easing::Hold => "Hold".to_string(),
Easing::Classic(s) => format!("Classic {s:+.0}"),
Easing::CubicBezier(..) if *self == Easing::SMOOTH => "Smooth (bezier)".to_string(),
Easing::CubicBezier(a, b, c, d) => format!("Bezier({a:.2}, {b:.2}, {c:.2}, {d:.2})"),
Easing::Custom(_) => "Custom".to_string(),
Easing::Sampled(s) => s.name().to_string(),
Easing::Spring(s) => format!("Spring {:.0}, {:.0}, {:.0}", s.mass, s.stiffness, s.damping),
other => other.family().map_or_else(|| "Custom".to_string(), |(f, d)| format!("{} {}", f.label(), d.label())),
}
}
/// The single cubic Bezier `(x1, y1, x2, y2)` that draws this ease: exact for linear, the
/// Classic slider, the Quad, Cubic and Back eases in and out, and a custom ease of one
/// segment; the Quad and Cubic in-outs get their usual one-curve approximations. `None` for
/// eases one curve cannot draw (Bounce, Elastic, the other families, hold, springs, sampled
/// tables and custom eases of several segments).
pub fn as_bezier(&self) -> Option<(f64, f64, f64, f64)> {
const THIRD: f64 = 1.0 / 3.0;
Some(match self {
Easing::Linear => (THIRD, THIRD, 2.0 * THIRD, 2.0 * THIRD),
// t², t³ and (c+1)t³ − ct² and their mirrors, with x(s) = s.
Easing::QuadIn => (THIRD, 0.0, 2.0 * THIRD, THIRD),
Easing::QuadOut => (THIRD, 2.0 * THIRD, 2.0 * THIRD, 1.0),
Easing::CubicIn => (THIRD, 0.0, 2.0 * THIRD, 0.0),
Easing::CubicOut => (THIRD, 1.0, 2.0 * THIRD, 1.0),
Easing::BackIn => (THIRD, 0.0, 2.0 * THIRD, -BACK * THIRD),
Easing::BackOut => (THIRD, 1.0 + BACK * THIRD, 2.0 * THIRD, 1.0),
Easing::QuadInOut => (0.45, 0.0, 0.55, 1.0),
Easing::CubicInOut => (0.65, 0.0, 0.35, 1.0),
Easing::Classic(strength) => {
// The quadratic 2(1 − t)t·c + t², raised to a cubic.
let c = 0.5 + 0.5 * classic_strength(*strength);
(THIRD, 2.0 * c * THIRD, 2.0 * THIRD, (2.0 * c + 1.0) * THIRD)
}
Easing::CubicBezier(a, b, c, d) => bezier_handles(*a, *b, *c, *d),
Easing::Custom(c) => match c.points() {
[a, b] => (a.out.x, a.out.y, b.at.x + b.h_in.x, b.at.y + b.h_in.y),
_ => return None,
},
_ => return None,
})
}
/// Eased progress at `t`: exactly 0 for `t <= 0` or NaN, exactly 1 for `t >= 1`.
pub fn apply(&self, t: f64) -> f64 {
if t.is_nan() || t <= 0.0 {
return 0.0;
}
if t >= 1.0 {
return 1.0;
}
let v = match self {
Easing::Linear => t,
Easing::Hold => 0.0,
Easing::Classic(strength) => {
// Quadratic Bezier with the middle control point moved by `strength`.
let c = 0.5 + 0.5 * classic_strength(*strength);
2.0 * (1.0 - t) * t * c + t * t
}
Easing::CubicBezier(x1, y1, x2, y2) => {
let (x1, y1, x2, y2) = bezier_handles(*x1, *y1, *x2, *y2);
bez(solve_monotonic(t, [0.0, x1, x2, 1.0]), [0.0, y1, y2, 1.0])
}
Easing::Custom(c) => c.apply(t),
Easing::Sampled(s) => s.apply(t),
Easing::Spring(s) => s.apply(t),
named => match named.family() {
Some((f, d)) => eval_named(f, d, t),
None => t,
},
};
if v.is_finite() { v } else { t }
}
/// This ease as a custom curve for a graph editor: exact for linear, Classic, a Bezier,
/// the Quad, Cubic, Back and Bounce families and custom eases; Circ is two circular arcs,
/// and Quart, Quint, Sine and Elastic are fitted by matching values and slopes at a few
/// points (all within 0.5 % of the range everywhere). A sampled ease or a spring becomes the
/// straight segments through [`crate::POLYLINE_POINTS`] of its values, and a hold a corner
/// at the end.
pub fn to_custom(&self) -> CustomEase {
match self {
Easing::Custom(c) => (**c).clone(),
Easing::Sampled(s) => s.to_polyline(),
Easing::Spring(_) => {
let n = crate::MAX_EASE_SAMPLES;
let values = (0..n).map(|i| self.apply(i as f64 / (n - 1) as f64)).collect();
SampledEase::new("Spring", "", "", values).to_polyline()
}
Easing::Hold => {
// Flat at 0 across the segment, then straight up to 1 at the end.
let third = 1.0 / 3.0;
CustomEase::new(vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(third, 0.0), smooth: false },
EasePoint { at: Vec2::new(1.0, 0.0), h_in: Vec2::new(-third, 0.0), out: Vec2::ZERO, smooth: false },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false },
])
}
Easing::Linear => CustomEase::linear(),
Easing::Classic(_) | Easing::CubicBezier(..) => {
let Some((x1, y1, x2, y2)) = self.as_bezier() else { return CustomEase::linear() };
CustomEase::from_bezier(x1, y1, x2, y2)
}
named => match named.family() {
Some((f, d)) => fit_named(f, d),
None => CustomEase::linear(),
},
}
}
/// The custom curve, when this is one.
pub fn custom(&self) -> Option<&CustomEase> {
match self {
Easing::Custom(c) => Some(c),
_ => None,
}
}
/// The sampled curve, when this is one.
pub fn sampled(&self) -> Option<&SampledEase> {
match self {
Easing::Sampled(s) => Some(s),
_ => None,
}
}
}
/// A cubic Bezier's handles as evaluation uses them: x within `0..=1`, y within ±[`MAX_EASE_Y`],
/// and the straight line for a handle that is not finite.
fn bezier_handles(x1: f64, y1: f64, x2: f64, y2: f64) -> (f64, f64, f64, f64) {
if ![x1, y1, x2, y2].iter().all(|v| v.is_finite()) {
return (1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0);
}
(x1.clamp(0.0, 1.0), y1.clamp(-MAX_EASE_Y, MAX_EASE_Y), x2.clamp(0.0, 1.0), y2.clamp(-MAX_EASE_Y, MAX_EASE_Y))
}
fn classic_strength(s: f64) -> f64 {
if s.is_finite() { s.clamp(-100.0, 100.0) / 100.0 } else { 0.0 }
}
fn eval_named(f: EaseFamily, d: EaseDir, t: f64) -> f64 {
match d {
EaseDir::In => f.ease_in(t, false),
EaseDir::Out => 1.0 - f.ease_in(1.0 - t, false),
EaseDir::InOut => {
if t < 0.5 {
0.5 * f.ease_in(2.0 * t, true)
} else {
1.0 - 0.5 * f.ease_in(2.0 - 2.0 * t, true)
}
}
}
}
/// The slope of `y` at `x`, from inside `[lo, hi]`: one-sided, a step in from `x` (so a value
/// pinned at an end, as Elastic's are, does not count), exact for parabolas but for that step.
fn slope(y: &dyn Fn(f64) -> f64, x: f64, lo: f64, hi: f64) -> f64 {
const H: f64 = 1e-6;
let s = if x + 3.0 * H <= hi {
let d = (-3.0 * y(x + H) + 4.0 * y(x + 2.0 * H) - y(x + 3.0 * H)) / (2.0 * H);
let d2 = (y(x + H) - 2.0 * y(x + 2.0 * H) + y(x + 3.0 * H)) / (H * H);
d - d2 * H
} else if x - 3.0 * H >= lo {
let d = (3.0 * y(x - H) - 4.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (2.0 * H);
let d2 = (y(x - H) - 2.0 * y(x - 2.0 * H) + y(x - 3.0 * H)) / (H * H);
d + d2 * H
} else {
0.0
};
if s.is_finite() { s } else { 0.0 }
}
/// The ease in of `f` (its In Out form with `in_out`) as Bezier points: Hermite segments (value
/// and slope matched at each end, so exact for cubic polynomials and for each parabola of
/// Bounce), except Circ, whose quarter circle is two 45° arcs (within 4·10⁻⁶ of the circle).
fn fit_in(f: EaseFamily, in_out: bool) -> Vec<EasePoint> {
let pt = |x: f64, y: f64, i: (f64, f64), o: (f64, f64)| EasePoint {
at: Vec2::new(x, y),
h_in: Vec2::new(i.0, i.1),
out: Vec2::new(o.0, o.1),
smooth: false,
};
if f == EaseFamily::Circ {
// The circle about (0, 1) from (0, 0) to (1, 1); each arc's handles are k = 4/3·tan(φ/4)
// long along the tangents.
let k = 4.0 / 3.0 * (std::f64::consts::PI / 16.0).tan();
let c = std::f64::consts::FRAC_1_SQRT_2;
return vec![pt(0.0, 0.0, (0.0, 0.0), (k, 0.0)), pt(c, 1.0 - c, (-k * c, -k * c), (k * c, k * c)), pt(1.0, 1.0, (0.0, -k), (0.0, 0.0))];
}
let y = move |t: f64| f.ease_in(t, in_out);
let mut xs: Vec<f64> = Vec::new();
let pieces = f.pieces_in();
let bounds: Vec<f64> = std::iter::once(0.0).chain(f.breaks_in().iter().copied()).chain(std::iter::once(1.0)).collect();
for w in bounds.windows(2) {
if let [a, c] = w {
xs.extend((0..pieces).map(|k| a + (c - a) * k as f64 / pieces as f64));
}
}
xs.push(1.0);
let mut pts: Vec<EasePoint> = xs.iter().map(|&x| pt(x, y(x), (0.0, 0.0), (0.0, 0.0))).collect();
for i in 0..xs.len().saturating_sub(1) {
let (Some(&a), Some(&b)) = (xs.get(i), xs.get(i + 1)) else { continue };
let h = (b - a) / 3.0;
let (sa, sb) = (slope(&y, a, a, b), slope(&y, b, a, b));
if let Some(p) = pts.get_mut(i) {
p.out = Vec2::new(h, sa * h);
}
if let Some(p) = pts.get_mut(i + 1) {
p.h_in = Vec2::new(-h, -sb * h);
}
}
pts
}
/// The curve turned half a turn about (½, ½): an ease in becomes the ease out.
fn mirrored(pts: &[EasePoint]) -> Vec<EasePoint> {
pts.iter().rev().map(|p| EasePoint { at: Vec2::new(1.0 - p.at.x, 1.0 - p.at.y), h_in: -p.out, out: -p.h_in, smooth: p.smooth }).collect()
}
fn scaled(pts: &[EasePoint], by: f64, from: Vec2) -> Vec<EasePoint> {
pts.iter().map(|p| EasePoint { at: from + p.at * by, h_in: p.h_in * by, out: p.out * by, smooth: p.smooth }).collect()
}
/// A named ease as a custom curve (see [`Easing::to_custom`]).
fn fit_named(f: EaseFamily, d: EaseDir) -> CustomEase {
let mut pts = match d {
EaseDir::In => fit_in(f, false),
EaseDir::Out => mirrored(&fit_in(f, false)),
EaseDir::InOut => {
let half = fit_in(f, true);
let mut a = scaled(&half, 0.5, Vec2::ZERO);
let b = scaled(&mirrored(&half), 0.5, Vec2::new(0.5, 0.5));
// The two halves meet at (½, ½): one point, the first half's in, the second's out.
if let (Some(last), Some(first)) = (a.last_mut(), b.first()) {
last.out = first.out;
}
a.extend(b.into_iter().skip(1));
a
}
};
// Points where the slope carries on are smooth (Bounce's floor hits are corners).
let n = pts.len();
for (i, p) in pts.iter_mut().enumerate() {
p.smooth =
i > 0 && i + 1 < n && p.h_in.length() > 1e-9 && p.out.length() > 1e-9 && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-3;
}
CustomEase::new(pts)
}
+219
View File
@@ -0,0 +1,219 @@
//! Easing curves, keyed tracks, motion paths and springs.
//!
//! * [`Easing`] maps linear progress `t` in `0..=1` to eased progress: no ease, hold, the
//! Classic slider, nine named families (Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce,
//! Elastic), each In, Out and In Out, one cubic Bezier (also built from speed and influence,
//! [`TemporalEase`]), an editable multi-segment [`CustomEase`], a [`SampledEase`] table and a
//! [`SpringEase`]. [`Easing::apply`] is a pure function that does not allocate, and it returns
//! exactly 0 at the start and exactly 1 at the end.
//! * [`Track`] holds keys of any [`Animatable`] value (`f32`, `f64`, [`Vec2`], `[f32; N]`,
//! `[f64; N]`) at times in seconds, each easing into the next. Sampling is a binary search and
//! does not allocate.
//! * [`MotionPath`] is a chain of cubic Bezier segments with arc-length tables built once, for
//! constant-speed motion along a curve.
//! * [`Spring`] and [`SpringState`] move a value toward a target as a damped spring. Each step
//! uses the exact solution of the spring equation, so a step costs the same at any frame rate
//! and length.
//!
//! The named families are the classic public easing equations published by Robert Penner.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod custom;
mod easing;
mod path;
mod sampled;
mod spring;
mod track;
mod vec2;
pub use custom::{CustomEase, EasePoint, Handle, MAX_EASE_POINTS, MAX_EASE_Y};
pub use easing::{EaseDir, EaseFamily, Easing, MIN_INFLUENCE, SpringEase, TemporalEase};
pub use path::{MAX_PATH_SEGMENTS, MotionPath};
pub use sampled::{MAX_EASE_SAMPLES, POLYLINE_POINTS, SampledEase};
pub use spring::{MAX_DAMPING_RATIO, MAX_SPRING_HZ, Spring, SpringState};
pub use track::{Animatable, Key, MAX_TRACK_KEYS, Track};
pub use vec2::Vec2;
/// Why a value was refused.
#[derive(Clone, Debug, PartialEq)]
pub enum EaseError {
/// The named input is NaN or infinite.
NotFinite(&'static str),
/// The named input is outside the range it must lie in.
OutOfRange { what: &'static str, min: f64, max: f64 },
/// A track or path holds as many entries as it may.
Full(usize),
/// A path or curve needs more points than it was given.
TooFew { what: &'static str, need: usize },
/// The track has no keys.
Empty,
/// Two keys are at this time.
SameTime(f64),
/// The result is too large to represent.
Overflow,
}
impl std::fmt::Display for EaseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EaseError::NotFinite(what) => write!(f, "{what} is not a finite number"),
EaseError::OutOfRange { what, min, max } => write!(f, "{what} must be between {min} and {max}"),
EaseError::Full(n) => write!(f, "at most {n} entries are allowed"),
EaseError::TooFew { what, need } => write!(f, "{what} needs at least {need} points"),
EaseError::Empty => write!(f, "the track has no keys"),
EaseError::SameTime(t) => write!(f, "two keys are at {t} s"),
EaseError::Overflow => write!(f, "the result is too large"),
}
}
}
impl std::error::Error for EaseError {}
/// `v` itself when it is finite.
pub(crate) fn finite(v: f64, what: &'static str) -> Result<f64, EaseError> {
if v.is_finite() { Ok(v) } else { Err(EaseError::NotFinite(what)) }
}
/// `v` itself when it is finite and within `min..=max`.
pub(crate) fn within(v: f64, min: f64, max: f64, what: &'static str) -> Result<f64, EaseError> {
let v = finite(v, what)?;
if (min..=max).contains(&v) { Ok(v) } else { Err(EaseError::OutOfRange { what, min, max }) }
}
/// The value `t` of the way from `a` to `b`. When a step on the way is too large to represent
/// (`a` and `b` near opposite ends of the `f64` range, or an overshooting `t`), it is worked
/// out at half scale, so only a result too large to represent is infinite.
pub(crate) fn lerp(a: f64, b: f64, t: f64) -> f64 {
let r = a + (b - a) * t;
if r.is_finite() { r } else { 2.0 * (0.5 * a + (0.5 * b - 0.5 * a) * t) }
}
/// Reads a list, keeping its first `max` entries and skipping the rest without storing them.
#[cfg(feature = "serde")]
pub(crate) fn read_first<'de, D, T>(d: D, max: usize) -> Result<Vec<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de>,
{
use serde::de::{IgnoredAny, SeqAccess, Visitor};
struct V<T>(usize, std::marker::PhantomData<T>);
impl<'de, T: serde::Deserialize<'de>> Visitor<'de> for V<T> {
type Value = Vec<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a list")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(self.0).min(1024));
while out.len() < self.0 {
match seq.next_element()? {
Some(v) => out.push(v),
None => return Ok(out),
}
}
while seq.next_element::<IgnoredAny>()?.is_some() {}
Ok(out)
}
}
d.deserialize_seq(V(max, std::marker::PhantomData))
}
/// Reads a string and keeps only what `clean` makes of it, so a long string in a file is never
/// copied whole into the value.
///
/// This bounds the memory the value keeps. A format that has to decode escapes may still build
/// the whole string in a temporary buffer first; that buffer is no larger than the input, so the
/// caller bounds it by limiting the size of the file it reads.
#[cfg(feature = "serde")]
pub(crate) fn read_cleaned<'de, D: serde::Deserializer<'de>>(d: D, clean: fn(&str) -> String) -> Result<String, D::Error> {
struct V(fn(&str) -> String);
impl serde::de::Visitor<'_> for V {
type Value = String;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a string")
}
fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<String, E> {
Ok((self.0)(s))
}
}
d.deserialize_str(V(clean))
}
/// Cubic Bezier in one dimension.
pub(crate) fn bez(t: f64, p: [f64; 4]) -> f64 {
let mt = 1.0 - t;
mt * mt * mt * p[0] + 3.0 * mt * mt * t * p[1] + 3.0 * mt * t * t * p[2] + t * t * t * p[3]
}
/// The derivative of [`bez`].
pub(crate) fn dbez(t: f64, p: [f64; 4]) -> f64 {
let mt = 1.0 - t;
3.0 * mt * mt * (p[1] - p[0]) + 6.0 * mt * t * (p[2] - p[1]) + 3.0 * t * t * (p[3] - p[2])
}
/// Most steps [`solve_monotonic`] takes.
pub(crate) const SOLVE_STEPS: u32 = 64;
/// How close [`solve_monotonic`] brings `bez(s)` to `x`, relative to the curve's span.
pub(crate) const SOLVE_TOLERANCE: f64 = 1e-12;
/// The parameter where the Bezier `p` (non-decreasing: its inner points lie between its ends)
/// reaches `x`: Newton steps kept inside a shrinking bracket, halving when a step leaves it, to
/// within [`SOLVE_TOLERANCE`] of the span in at most [`SOLVE_STEPS`] steps. The curve with both
/// handles at full reach (`p1 = p3`, `p2 = p0`), whose slope is zero halfway, is inverted in
/// closed form.
pub(crate) fn solve_monotonic(x: f64, p: [f64; 4]) -> f64 {
solve_counted(x, p).0
}
/// [`solve_monotonic`] and the number of steps it took.
pub(crate) fn solve_counted(x: f64, p: [f64; 4]) -> (f64, u32) {
let span = p[3] - p[0];
if span.is_nan() || span <= 0.0 {
return (0.5, 0);
}
if x <= p[0] {
return (0.0, 0);
}
if x >= p[3] {
return (1.0, 0);
}
let u = (x - p[0]) / span;
if p[1] == p[3] && p[2] == p[0] {
// x(s) = 0.5 + 4 (s − 0.5)³ on the unit span.
return ((0.5 + ((u - 0.5) * 0.25).cbrt()).clamp(0.0, 1.0), 0);
}
let (mut lo, mut hi) = (0.0f64, 1.0f64);
let mut s = u.clamp(0.0, 1.0);
let tol = SOLVE_TOLERANCE * span;
for step in 1..=SOLVE_STEPS {
let err = bez(s, p) - x;
if err.abs() <= tol {
return (s, step);
}
if err < 0.0 {
lo = s;
} else {
hi = s;
}
let d = dbez(s, p);
let next = if d.abs() > 1e-300 { s - err / d } else { f64::NAN };
s = if next > lo && next < hi { next } else { 0.5 * (lo + hi) };
}
(s, SOLVE_STEPS)
}
#[cfg(test)]
#[path = "tests/easing_tests.rs"]
mod easing_tests;
#[cfg(test)]
#[path = "tests/track_tests.rs"]
mod track_tests;
#[cfg(test)]
#[path = "tests/path_tests.rs"]
mod path_tests;
#[cfg(test)]
#[path = "tests/spring_tests.rs"]
mod spring_tests;
+286
View File
@@ -0,0 +1,286 @@
//! [`MotionPath`]: constant-speed motion along a chain of cubic Bezier segments.
use crate::{EaseError, Vec2, bez, dbez};
/// Most segments one path holds.
pub const MAX_PATH_SEGMENTS: usize = 10_000;
/// Cells in each segment's arc-length table.
const ARC_N: usize = 32;
/// 5-point Gauss-Legendre nodes and weights on −1..1.
const GAUSS: [(f64, f64); 5] = [
(0.0, 0.568_888_888_888_888_9),
(-0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
(0.538_469_310_105_683_1, 0.478_628_670_499_366_5),
(-0.906_179_845_938_664, 0.236_926_885_056_189_1),
(0.906_179_845_938_664, 0.236_926_885_056_189_1),
];
#[derive(Clone, Debug, PartialEq)]
struct Segment {
p: [Vec2; 4],
/// Arc length from the segment's start at `u = i / ARC_N`.
table: [f64; ARC_N + 1],
/// Both handles on the chord: the segment is the straight line between its ends.
straight: bool,
/// Arc length from the path's start to this segment's start.
start: f64,
}
impl Segment {
fn new(p: [Vec2; 4], start: f64) -> Segment {
let straight = on_chord(p[0], p[1], p[3]) && on_chord(p[0], p[2], p[3]);
let mut table = [0.0; ARC_N + 1];
if straight {
let len = p[0].distance(p[3]);
for (i, v) in table.iter_mut().enumerate() {
*v = len * i as f64 / ARC_N as f64;
}
} else {
let mut acc = 0.0;
for i in 1..=ARC_N {
acc += arc(&p, (i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64);
if let Some(v) = table.get_mut(i) {
*v = acc;
}
}
}
Segment { p, table, straight, start }
}
fn length(&self) -> f64 {
self.table[ARC_N]
}
fn point(&self, u: f64) -> Vec2 {
let p = &self.p;
Vec2::new(bez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), bez(u, [p[0].y, p[1].y, p[2].y, p[3].y]))
}
/// The parameter at arc length `s` from the segment's start (`0..=length`): the table
/// cell's straight-line guess refined with Newton steps on the true arc length.
fn param_at(&self, s: f64) -> f64 {
let len = self.length();
if len <= 0.0 {
return 0.0;
}
let s = s.clamp(0.0, len);
if self.straight {
return s / len;
}
let i = self.table.partition_point(|&v| v < s).clamp(1, ARC_N);
let (Some(&a), Some(&b)) = (self.table.get(i - 1), self.table.get(i)) else { return s / len };
let (u0, u1) = ((i - 1) as f64 / ARC_N as f64, i as f64 / ARC_N as f64);
let mut u = u0 + if b > a { (s - a) / (b - a) } else { 0.0 } * (u1 - u0);
for _ in 0..4 {
let d = speed(&self.p, u);
if d <= 1e-12 * len {
break;
}
let e = a + arc(&self.p, u0, u) - s;
u = (u - e / d).clamp(u0, u1);
if e.abs() <= 1e-12 * len {
break;
}
}
u
}
/// The direction of travel at `u`, or the chord's where the curve's derivative vanishes.
fn direction(&self, u: f64) -> Vec2 {
let p = &self.p;
let d = Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).normalized();
if d != Vec2::ZERO {
return d;
}
// At an end whose handle sits on it, the curve leaves toward the next control point.
let toward = if u < 0.5 {
[p[1], p[2], p[3]].into_iter().find(|q| *q != p[0]).map(|q| q - p[0])
} else {
[p[2], p[1], p[0]].into_iter().find(|q| *q != p[3]).map(|q| p[3] - q)
};
toward.unwrap_or(Vec2::ZERO).normalized()
}
}
/// |dB/du|.
fn speed(p: &[Vec2; 4], u: f64) -> f64 {
Vec2::new(dbez(u, [p[0].x, p[1].x, p[2].x, p[3].x]), dbez(u, [p[0].y, p[1].y, p[2].y, p[3].y])).length()
}
/// Arc length between parameters `a` and `b` (Gauss-Legendre; exact enough on one table cell).
fn arc(p: &[Vec2; 4], a: f64, b: f64) -> f64 {
let (m, h) = ((a + b) * 0.5, (b - a) * 0.5);
GAUSS.iter().map(|(x, w)| w * speed(p, m + h * x)).sum::<f64>() * h
}
/// Whether control point `c` lies on the segment `a`–`b` (within rounding).
fn on_chord(a: Vec2, c: Vec2, b: Vec2) -> bool {
let (mut d, mut v) = (b - a, c - a);
// Scaled to the largest component first, so squaring coordinates near 1e154 and above does
// not overflow and make a curve look straight.
let scale = d.x.abs().max(d.y.abs()).max(v.x.abs()).max(v.y.abs());
if scale.is_finite() && scale > 0.0 {
(d, v) = (Vec2::new(d.x / scale, d.y / scale), Vec2::new(v.x / scale, v.y / scale));
}
let dd = d.dot(d);
if dd <= 0.0 {
// A segment of zero length is straight when its handles sit on its point.
return v == Vec2::ZERO;
}
let t = v.dot(d) / dd;
let off = v - d * t;
(0.0..=1.0).contains(&t) && off.dot(off) <= dd * 1e-28
}
/// A path of cubic Bezier segments with an arc-length table per segment, built once, so a point
/// at a distance along it costs a binary search and a few curve evaluations and does not
/// allocate.
///
/// A distance before the start or past the end continues in a straight line along the path's
/// direction there, so an ease that overshoots carries the motion past the end the same way on
/// curved and straight paths.
#[derive(Clone, Debug, PartialEq)]
pub struct MotionPath {
segments: Vec<Segment>,
length: f64,
/// The first and last segments that have length (the first and last when none has), so the
/// ends' directions skip anchors repeated at an end.
ends: (usize, usize),
}
impl MotionPath {
/// A path from the absolute points `[p0, c1, c2, p1, c3, c4, p2, …]` (3n + 1 of them, n from
/// 1 to [`MAX_PATH_SEGMENTS`]). An error for a wrong count, a point that is not finite, or
/// a path too long to measure.
pub fn new(points: &[Vec2]) -> Result<MotionPath, EaseError> {
if points.len() < 4 {
return Err(EaseError::TooFew { what: "a motion path", need: 4 });
}
if points.len() % 3 != 1 {
return Err(EaseError::OutOfRange { what: "the point count (3n + 1)", min: 4.0, max: (3 * MAX_PATH_SEGMENTS + 1) as f64 });
}
if points.len() > 3 * MAX_PATH_SEGMENTS + 1 {
return Err(EaseError::Full(MAX_PATH_SEGMENTS));
}
if points.iter().any(|p| !p.is_finite()) {
return Err(EaseError::NotFinite("path point"));
}
let mut segments = Vec::with_capacity(points.len() / 3);
let mut start = 0.0;
for w in points.windows(4).step_by(3) {
let [a, b, c, d] = w else { continue };
let s = Segment::new([*a, *b, *c, *d], start);
start += s.length();
segments.push(s);
}
if !start.is_finite() {
return Err(EaseError::Overflow);
}
let first = segments.iter().position(|g| g.length() > 0.0).unwrap_or(0);
let last = segments.iter().rposition(|g| g.length() > 0.0).unwrap_or(segments.len().saturating_sub(1));
Ok(MotionPath { segments, length: start, ends: (first, last) })
}
/// A smooth path through `anchors` (at least 2), its handles set automatically: each inner
/// anchor's handles point along the line from the anchor before it to the anchor after it,
/// a sixth of that line long, and an end anchor's handle points a sixth of the way toward
/// its neighbor. A side that faces an anchor at the same place has no handle, so two equal
/// anchors make a segment of zero length.
pub fn through(anchors: &[Vec2]) -> Result<MotionPath, EaseError> {
if anchors.len() < 2 {
return Err(EaseError::TooFew { what: "a motion path", need: 2 });
}
if anchors.len() > MAX_PATH_SEGMENTS + 1 {
return Err(EaseError::Full(MAX_PATH_SEGMENTS));
}
if anchors.iter().any(|p| !p.is_finite()) {
return Err(EaseError::NotFinite("path point"));
}
let n = anchors.len();
let at = |i: usize| anchors.get(i).copied().unwrap_or(Vec2::ZERO);
let handles = |i: usize| -> (Vec2, Vec2) {
let (a, p, c) = (at(i.saturating_sub(1)), at(i), at((i + 1).min(n - 1)));
let out = (c - a) * (1.0 / 6.0);
let h_in = if i > 0 && a == p { Vec2::ZERO } else { -out };
let h_out = if i + 1 < n && c == p { Vec2::ZERO } else { out };
(h_in, h_out)
};
let mut points = Vec::with_capacity(3 * n - 2);
for i in 0..n {
let (h_in, h_out) = handles(i);
if i > 0 {
points.push(at(i) + h_in);
}
points.push(at(i));
if i + 1 < n {
points.push(at(i) + h_out);
}
}
MotionPath::new(&points)
}
/// The path's length.
pub fn length(&self) -> f64 {
self.length
}
/// How many segments the path has.
pub fn segments(&self) -> usize {
self.segments.len()
}
/// The segment holding distance `s` (clamped to the path) and the distance into it.
fn locate(&self, s: f64) -> Option<(&Segment, f64)> {
let i = self.segments.partition_point(|g| g.start <= s).saturating_sub(1);
let g = self.segments.get(i)?;
Some((g, s - g.start))
}
/// The segments at the ends (see the `ends` field).
fn ends(&self) -> Option<(&Segment, &Segment)> {
Some((self.segments.get(self.ends.0)?, self.segments.get(self.ends.1)?))
}
/// The point `s` along the path. Before the start and past the end it continues along the
/// path's direction there; NaN and −∞ give the start, and +∞ the end.
pub fn point_at_length(&self, s: f64) -> Vec2 {
let Some((first, last)) = self.ends() else { return Vec2::ZERO };
if s.is_nan() || s <= 0.0 {
let s = if s.is_finite() { s } else { 0.0 };
return first.p[0] + first.direction(0.0) * s;
}
if s >= self.length {
let past = if s.is_finite() { s - self.length } else { 0.0 };
return last.p[3] + last.direction(1.0) * past;
}
match self.locate(s) {
Some((g, into)) if g.straight => {
let len = g.length();
if len > 0.0 { g.p[0].lerp(g.p[3], into / len) } else { g.p[0] }
}
Some((g, into)) => g.point(g.param_at(into)),
None => first.p[0],
}
}
/// The point `progress` of the way along the path (0 the start, 1 the end).
pub fn point_at(&self, progress: f64) -> Vec2 {
self.point_at_length(progress * self.length)
}
/// The unit direction of travel `s` along the path (zero for a path of zero length).
pub fn direction_at_length(&self, s: f64) -> Vec2 {
let Some((first, last)) = self.ends() else { return Vec2::ZERO };
if s.is_nan() || s <= 0.0 {
return first.direction(0.0);
}
if s >= self.length {
return last.direction(1.0);
}
match self.locate(s) {
Some((g, into)) => g.direction(g.param_at(into)),
None => Vec2::ZERO,
}
}
}
+203
View File
@@ -0,0 +1,203 @@
//! [`SampledEase`]: an ease kept as a table of values.
use crate::Vec2;
use crate::custom::{CustomEase, EasePoint, MAX_EASE_Y};
/// Most samples a sampled ease keeps (longer tables are thinned evenly).
pub const MAX_EASE_SAMPLES: usize = 1025;
/// Points of the custom curve a sampled ease becomes when edited (of [`crate::MAX_EASE_POINTS`]).
pub const POLYLINE_POINTS: usize = 48;
/// Longest source or ease id a sampled ease keeps.
const MAX_EASE_ID: usize = 64;
/// Longest name a sampled ease keeps.
const MAX_EASE_NAME: usize = 64;
/// An ease as a table: `values[i]` is the eased progress at `t = i / (n - 1)`, read between
/// samples by linear interpolation, so evaluation is a constant-time function of `t`. It keeps
/// a name and where it came from (a source id, such as a plug-in's, and the ease's id there).
///
/// Always valid, however it was made: 2 to [`MAX_EASE_SAMPLES`] finite values within
/// ±[`MAX_EASE_Y`], starting at exactly 0 and ending at exactly 1.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(from = "SampledEaseFile"))]
pub struct SampledEase {
name: String,
plugin: String,
ease: String,
values: Vec<f64>,
}
#[cfg(feature = "serde")]
#[derive(serde::Deserialize)]
struct SampledEaseFile {
#[serde(default, deserialize_with = "read_name")]
name: String,
#[serde(default, deserialize_with = "read_id")]
plugin: String,
#[serde(default, deserialize_with = "read_id")]
ease: String,
#[serde(default, deserialize_with = "read_values")]
values: Vec<f64>,
}
/// Most values read from a file's list; the rest are skipped.
#[cfg(feature = "serde")]
const MAX_SAMPLE_INPUT: usize = 65_536;
#[cfg(feature = "serde")]
fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
crate::read_cleaned(d, |s| ease_name(s).unwrap_or_default())
}
#[cfg(feature = "serde")]
fn read_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
crate::read_cleaned(d, ease_id)
}
#[cfg(feature = "serde")]
fn read_values<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<f64>, D::Error> {
crate::read_first(d, MAX_SAMPLE_INPUT)
}
#[cfg(feature = "serde")]
impl From<SampledEaseFile> for SampledEase {
fn from(f: SampledEaseFile) -> SampledEase {
SampledEase::new(&f.name, &f.plugin, &f.ease, f.values)
}
}
/// An id as a sampled ease keeps it: `[A-Za-z0-9._-]`, at most [`MAX_EASE_ID`] characters.
fn ease_id(s: &str) -> String {
s.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')).take(MAX_EASE_ID).collect()
}
/// A name as kept: control characters, bidirectional overrides and invisible format characters
/// (zero-width spaces and joiners, word joiners, the byte-order mark, soft hyphens) removed,
/// trimmed, at most [`MAX_EASE_NAME`] characters; `None` when nothing is left.
fn ease_name(name: &str) -> Option<String> {
let n: String = name
.chars()
.filter(|c| {
!c.is_control()
&& !matches!(
c,
'\u{ad}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}'
)
})
.skip_while(|c| c.is_whitespace())
.take(MAX_EASE_NAME)
.collect();
let n = n.trim().to_string();
(!n.is_empty()).then_some(n)
}
/// The index of the `k`th of [`MAX_EASE_SAMPLES`] samples spread evenly over `n` values,
/// computed in 128 bits so a long table cannot overflow a 32-bit `usize`.
pub(crate) fn thinned(k: usize, n: usize) -> usize {
let i = (k as u128) * (n.saturating_sub(1) as u128) / ((MAX_EASE_SAMPLES - 1) as u128);
usize::try_from(i).unwrap_or(usize::MAX)
}
impl SampledEase {
/// A valid table from any values (see the type's docs): a longer table is thinned evenly, a
/// value that is not finite becomes the straight line's, values are clamped, the ends pinned;
/// fewer than two values make the straight line.
pub fn new(name: &str, plugin: &str, ease: &str, mut values: Vec<f64>) -> SampledEase {
if values.len() > MAX_EASE_SAMPLES {
let n = values.len();
values = (0..MAX_EASE_SAMPLES).filter_map(|k| values.get(thinned(k, n)).copied()).collect();
}
if values.len() < 2 {
values = vec![0.0, 1.0];
}
let last = (values.len() - 1) as f64;
for (i, v) in values.iter_mut().enumerate() {
*v = if v.is_finite() { v.clamp(-MAX_EASE_Y, MAX_EASE_Y) } else { i as f64 / last };
}
if let Some(v) = values.first_mut() {
*v = 0.0;
}
if let Some(v) = values.last_mut() {
*v = 1.0;
}
SampledEase { name: ease_name(name).unwrap_or_else(|| "Sampled ease".to_string()), plugin: ease_id(plugin), ease: ease_id(ease), values }
}
/// The name an ease menu shows.
pub fn name(&self) -> &str {
&self.name
}
/// The id of the source it came from.
pub fn plugin(&self) -> &str {
&self.plugin
}
/// Its id within that source.
pub fn ease(&self) -> &str {
&self.ease
}
pub fn values(&self) -> &[f64] {
&self.values
}
/// A table a caller supplies, checked: an error for a value that is not finite or outside
/// ±[`MAX_EASE_Y`], fewer than 2 values or more than [`MAX_EASE_SAMPLES`]. The ends are then
/// pinned to 0 and 1 as [`SampledEase::new`] does.
pub fn try_new(name: &str, plugin: &str, ease: &str, values: Vec<f64>) -> Result<SampledEase, crate::EaseError> {
for v in &values {
crate::within(*v, -MAX_EASE_Y, MAX_EASE_Y, "sample")?;
}
if values.len() < 2 {
return Err(crate::EaseError::TooFew { what: "a sampled ease", need: 2 });
}
if values.len() > MAX_EASE_SAMPLES {
return Err(crate::EaseError::Full(MAX_EASE_SAMPLES));
}
Ok(SampledEase::new(name, plugin, ease, values))
}
/// The eased value at time `t`, between the two nearest samples. `t` outside `0..=1` is
/// clamped, and NaN reads as 0.
pub fn apply(&self, t: f64) -> f64 {
let t = if t.is_finite() {
t.clamp(0.0, 1.0)
} else if t > 0.0 {
1.0
} else {
0.0
};
let last = self.values.len().saturating_sub(1);
if last == 0 {
return t;
}
let x = t * last as f64;
let i = (x.floor() as usize).min(last - 1);
let f = x - i as f64;
let (a, b) = (self.values.get(i).copied().unwrap_or(0.0), self.values.get(i + 1).copied().unwrap_or(1.0));
a + (b - a) * f
}
/// The custom curve of straight segments through [`POLYLINE_POINTS`] of its samples, for a
/// graph editor: editing a sampled ease makes it a custom ease drawn like it, with room left
/// to add points.
pub fn to_polyline(&self) -> CustomEase {
let n = self.values.len();
let m = POLYLINE_POINTS.min(n).max(2);
let at: Vec<Vec2> = (0..m)
.map(|k| {
let i = k * (n - 1) / (m - 1);
Vec2::new(i as f64 / (n - 1).max(1) as f64, self.values.get(i).copied().unwrap_or(0.0))
})
.collect();
let pts = at
.iter()
.enumerate()
.map(|(k, p)| {
let prev = if k == 0 { *p } else { at.get(k - 1).copied().unwrap_or(*p) };
let next = at.get(k + 1).copied().unwrap_or(*p);
EasePoint { at: *p, h_in: (prev - *p) * (1.0 / 3.0), out: (next - *p) * (1.0 / 3.0), smooth: false }
})
.collect();
CustomEase::new(pts)
}
}
+223
View File
@@ -0,0 +1,223 @@
//! Damped springs: [`Spring`] and [`SpringState`].
//!
//! A spring pulls a value `x` toward a target with
//!
//! ```text
//! x'' = −ω² (x − target) − 2ζω x'
//! ```
//!
//! where `ω` is the natural angular frequency and `ζ` the damping ratio (below 1 the value
//! overshoots and swings back, at 1 it arrives as fast as it can without overshooting, above 1
//! it creeps in). [`SpringState::step`] moves the value by the exact solution of that equation
//! over the step, so a step costs O(1), any step length is stable, and many short steps give the
//! same value as one long one.
use crate::{EaseError, within};
/// Highest natural frequency a spring may have, in swings per second.
pub const MAX_SPRING_HZ: f64 = 10_000.0;
/// Highest damping ratio a spring may have.
pub const MAX_DAMPING_RATIO: f64 = 1e6;
/// The ranges [`Spring::from_physical`] accepts: mass, stiffness and damping coefficient.
const MASS: (f64, f64) = (0.01, 1e4);
const STIFFNESS: (f64, f64) = (0.01, 1e6);
const DAMPING: (f64, f64) = (0.0, 1e6);
/// Longest motion a spring ease plays, in seconds of the spring's own time.
const MAX_SETTLE: f64 = 10.0;
/// Damping ratios this close to 1 use the critically damped solution.
const CRITICAL_BAND: f64 = 1e-4;
/// A damped spring's constants.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
omega: f64,
zeta: f64,
}
impl Spring {
/// A spring that would swing `frequency` times a second without damping, with damping ratio
/// `damping`. `frequency` must be above 0 and at most [`MAX_SPRING_HZ`], `damping` within 0
/// to [`MAX_DAMPING_RATIO`].
pub fn new(frequency: f64, damping: f64) -> Result<Spring, EaseError> {
let f = within(frequency, 0.0, MAX_SPRING_HZ, "frequency")?;
if f <= 0.0 {
return Err(EaseError::OutOfRange { what: "frequency", min: f64::MIN_POSITIVE, max: MAX_SPRING_HZ });
}
let z = within(damping, 0.0, MAX_DAMPING_RATIO, "damping")?;
Ok(Spring::raw(f, z))
}
/// A spring from two `0..=1` controls: `strength` sets the frequency from 0.5 to 10 swings a
/// second, evenly spread in pitch, and `damping` the ratio (0 swings on, 2/3 is critical,
/// 1 gives [`MAX_DAMPING_RATIO`]).
pub fn from_controls(strength: f64, damping: f64) -> Result<Spring, EaseError> {
let s = within(strength, 0.0, 1.0, "strength")?;
let d = within(damping, 0.0, 1.0, "damping")?;
let zeta = if d >= 1.0 { MAX_DAMPING_RATIO } else { (0.5 * d / (1.0 - d)).min(MAX_DAMPING_RATIO) };
Ok(Spring::raw(0.5 * 20f64.powf(s), zeta))
}
/// A mass on a spring with damping: `mass` within 0.01 to 10,000, `stiffness` within 0.01
/// to 1,000,000 and the damping coefficient `damping` within 0 to 1,000,000. An error when
/// the three give a damping ratio above [`MAX_DAMPING_RATIO`].
pub fn from_physical(mass: f64, stiffness: f64, damping: f64) -> Result<Spring, EaseError> {
let m = within(mass, MASS.0, MASS.1, "mass")?;
let k = within(stiffness, STIFFNESS.0, STIFFNESS.1, "stiffness")?;
let c = within(damping, DAMPING.0, DAMPING.1, "damping")?;
if c / (2.0 * (k * m).sqrt()) > MAX_DAMPING_RATIO {
return Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO });
}
Ok(Spring::physical(m, k, c))
}
/// [`Spring::from_physical`] with each value brought into its range (a value that is not
/// finite takes the default: mass 1, stiffness 100, damping 15).
pub(crate) fn physical_lenient(mass: f64, stiffness: f64, damping: f64) -> Spring {
let ok = |v: f64, (lo, hi): (f64, f64), d: f64| if v.is_finite() { v.clamp(lo, hi) } else { d };
Spring::physical(ok(mass, MASS, 1.0), ok(stiffness, STIFFNESS, 100.0), ok(damping, DAMPING, 15.0))
}
fn physical(m: f64, k: f64, c: f64) -> Spring {
Spring { omega: (k / m).sqrt(), zeta: (c / (2.0 * (k * m).sqrt())).min(MAX_DAMPING_RATIO) }
}
/// A spring from values already in range.
pub(crate) fn raw(frequency: f64, damping: f64) -> Spring {
Spring { omega: std::f64::consts::TAU * frequency, zeta: damping }
}
/// Seconds until a spring released from rest stays within about 0.1 % of its target, at
/// least 0.05 and at most 10.
pub fn settle_time(&self) -> f64 {
let (w, z) = (self.omega, self.zeta);
// The slowest mode's decay rate; e^−6.9 is 0.1 %, and a critically or over-damped
// spring's larger lead factor needs about 9.2. Released from rest, an under-damped
// spring's offset stays within e^−ζωt · min(1/√(1 − ζ²), 1 + ζωt), so its lead factor
// grows by ln(1/√(1 − ζ²)) up to the critical spring's 9.2.
let (rate, k) = if z < 1.0 { (z * w, (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2)) } else { (w / (z + (z * z - 1.0).sqrt()), 9.2) };
let settle = if rate > 1e-6 { (k / rate).clamp(0.05, MAX_SETTLE) } else { MAX_SETTLE };
if settle.is_finite() { settle } else { MAX_SETTLE }
}
/// The spring as an ease: released from rest at 0 toward 1, `t` of the way through its
/// [`Spring::settle_time`]. Exactly 0 at `t <= 0` and exactly 1 at `t >= 1`. A spring with
/// so little damping that it is still moving after 10 seconds has the distance it is still
/// off at that point taken out evenly over the ease, so it reaches 1 without a jump.
pub fn ease(&self, t: f64) -> f64 {
if t.is_nan() || t <= 0.0 {
return 0.0;
}
if t >= 1.0 {
return 1.0;
}
let settle = self.settle_time();
let mut x = 1.0 + self.response(-1.0, 0.0, t * settle).0;
if settle >= MAX_SETTLE {
x -= t * self.response(-1.0, 0.0, settle).0;
}
if x.is_finite() { x } else { 1.0 }
}
/// The natural angular frequency `ω`, in radians a second.
pub fn omega(&self) -> f64 {
self.omega
}
/// The damping ratio `ζ`.
pub fn damping(&self) -> f64 {
self.zeta
}
/// Offset and velocity `(y, v)` after `t` seconds, from offset `y0` (value minus target) and
/// velocity `v0`: the exact solution of the spring equation.
pub(crate) fn response(&self, y0: f64, v0: f64, t: f64) -> (f64, f64) {
let (w, z) = (self.omega, self.zeta);
if t <= 0.0 {
return (y0, v0);
}
// Past this much decay e^(−decay) is below the smallest f64: the spring has settled.
const SETTLED: f64 = 800.0;
if (z - 1.0).abs() < CRITICAL_BAND {
if w * t > SETTLED {
return (0.0, 0.0);
}
let b = v0 + w * y0;
let e = (-w * t).exp();
return (e * (y0 + b * t), e * (b - w * (y0 + b * t)));
}
if z < 1.0 {
if z * w * t > SETTLED {
return (0.0, 0.0);
}
let wd = w * (1.0 - z * z).sqrt();
let q = v0 + z * w * y0;
let e = (-z * w * t).exp();
// A step so long that the phase overflows (a spring with little or no damping) is
// reduced by whole periods first.
let phase = if (wd * t).is_finite() { wd * t } else { wd * (t % (std::f64::consts::TAU / wd)) };
let (s, c) = phase.sin_cos();
// sin(phase) / ωd is at most t, so it stays finite for a spring of any low frequency,
// where q / ωd alone would overflow.
let sw = s / wd;
return (e * (y0 * c + q * sw), e * (v0 * c - (y0 * wd * s + z * w * q * sw)));
}
let root = (z * z - 1.0).sqrt();
// r1 = −ω(ζ − √(ζ² − 1)), written without the cancellation for large ζ.
let (r1, r2) = (-w / (z + root), -w * (z + root));
if -r1 * t > SETTLED {
return (0.0, 0.0);
}
let c1 = (v0 - r2 * y0) / (r1 - r2);
let c2 = y0 - c1;
let (e1, e2) = ((r1 * t).exp(), (r2 * t).exp());
(c1 * e1 + c2 * e2, c1 * r1 * e1 + c2 * r2 * e2)
}
}
/// A value moved by a spring: where it is and how fast it moves.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SpringState {
pub value: f64,
pub velocity: f64,
}
impl SpringState {
/// A value at rest at `value`.
pub fn at(value: f64) -> SpringState {
SpringState { value, velocity: 0.0 }
}
/// Moves the value `dt` seconds toward `target` (which holds still over the step) and
/// returns the new value. An error, with the state unchanged, for a `target` or `dt` that is
/// not finite, a negative `dt`, or a result too large to represent.
pub fn step(&mut self, spring: &Spring, target: f64, dt: f64) -> Result<f64, EaseError> {
let target = crate::finite(target, "target")?;
let dt = within(dt, 0.0, f64::MAX, "step")?;
if dt == 0.0 && self.value.is_finite() && self.velocity.is_finite() {
return Ok(self.value);
}
let (y, v) = spring.response(self.value - target, self.velocity, dt);
let (mut value, mut v) = (target + y, v);
if !(value.is_finite() && v.is_finite()) {
// The motion is linear in the offset and velocity, so they are moved again scaled by
// a power of two to at most 2, for a value and target near opposite ends of the f64
// range whose step overflowed on the way.
let (hy, hv) = (0.5 * self.value - 0.5 * target, 0.5 * self.velocity);
let m = hy.abs().max(hv.abs());
let scale = if m > 0.0 && m.is_finite() { 2f64.powi((m.log2().ceil() as i32).min(1023)) } else { 1.0 };
let (y, w) = spring.response(hy / scale, hv / scale, dt);
(value, v) = (2.0 * (0.5 * target + y * scale), 2.0 * (w * scale));
}
if !(value.is_finite() && v.is_finite()) {
return Err(EaseError::Overflow);
}
*self = SpringState { value, velocity: v };
Ok(value)
}
/// Whether the value is within `tolerance` of `target` and moves slower than `tolerance`
/// a second.
pub fn settled(&self, target: f64, tolerance: f64) -> bool {
(self.value - target).abs() <= tolerance && self.velocity.abs() <= tolerance
}
}
+826
View File
@@ -0,0 +1,826 @@
use crate::*;
use std::sync::Arc;
fn all() -> Vec<Easing> {
let mut v: Vec<Easing> = Easing::named().collect();
v.extend([Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), Easing::Custom(Arc::new(wave()))]);
v
}
/// Every ease kind, values included.
fn every_kind() -> Vec<Easing> {
let mut v = all();
v.extend([Easing::Hold, Easing::Spring(SpringEase::GENTLE), Easing::Sampled(Arc::new(steps()))]);
v
}
/// Three segments that overshoot both ways.
fn wave() -> CustomEase {
CustomEase::from_flat(
&[(0.0, 0.0), (0.1, 0.6), (0.2, 1.3), (0.3, 1.3), (0.4, 1.3), (0.5, -0.2), (0.6, 0.4), (0.7, 1.0), (0.9, 1.0), (1.0, 1.0)]
.map(|(x, y)| Vec2::new(x, y)),
)
.unwrap()
}
#[test]
fn a_narrow_custom_segment_is_evaluated_not_skipped() {
let d = 1e-10;
let e = CustomEase::from_flat(
&[
(0.0, 0.0),
(0.1, 0.0),
(0.4, 0.0),
(0.5, 0.0),
(0.5 + d / 3.0, 1.0 / 3.0),
(0.5 + 2.0 * d / 3.0, 2.0 / 3.0),
(0.5 + d, 1.0),
(0.6, 1.0),
(0.9, 1.0),
(1.0, 1.0),
]
.map(|(x, y)| Vec2::new(x, y)),
)
.unwrap();
let mid = e.apply(0.5 + d / 2.0);
assert!((mid - 0.5).abs() < 0.05, "{mid}");
}
/// Four steps, as a stepped ease samples them.
fn steps() -> SampledEase {
SampledEase::new("Stepped 4", "org.example.stepped-ease", "steps4", (0..257).map(|i| ((i as f64 / 256.0) * 4.0).floor() / 4.0).collect())
}
#[test]
fn endpoints_are_exact() {
for e in every_kind() {
assert_eq!(e.apply(0.0), 0.0, "{e:?}");
assert_eq!(e.apply(1.0), 1.0, "{e:?}");
assert_eq!(e.apply(-0.0), 0.0, "{e:?}");
assert_eq!(e.apply(-5.0), 0.0, "{e:?}");
assert_eq!(e.apply(5.0), 1.0, "{e:?}");
assert_eq!(e.apply(f64::NEG_INFINITY), 0.0, "{e:?}");
assert_eq!(e.apply(f64::INFINITY), 1.0, "{e:?}");
assert_eq!(e.apply(f64::NAN), 0.0, "{e:?}");
}
}
#[test]
fn presets_at_known_times() {
use std::f64::consts::{FRAC_1_SQRT_2, PI};
let cases: [(Easing, f64, f64); 22] = [
(Easing::Linear, 0.3, 0.3),
(Easing::QuadIn, 0.5, 0.25),
(Easing::QuadOut, 0.5, 0.75),
(Easing::QuadInOut, 0.25, 0.125),
(Easing::CubicIn, 0.5, 0.125),
(Easing::CubicOut, 0.5, 0.875),
(Easing::QuartIn, 0.5, 0.0625),
(Easing::QuartInOut, 0.75, 0.96875),
(Easing::QuintIn, 0.5, 0.03125),
(Easing::QuintOut, 0.5, 0.96875),
(Easing::SineIn, 0.5, 1.0 - FRAC_1_SQRT_2),
(Easing::SineOut, 1.0 / 3.0, 0.5),
(Easing::SineInOut, 0.25, 0.5 * (1.0 - FRAC_1_SQRT_2)),
// (c + 1)/8 − c/4 with c = 1.70158: dips below zero first.
(Easing::BackIn, 0.5, -0.087_697_5),
(Easing::BackOut, 0.5, 1.087_697_5),
(Easing::CircIn, 0.6, 0.2),
(Easing::CircOut, 0.5, 0.866_025_403_784_438_6),
(Easing::BounceOut, 0.5, 0.765_625),
(Easing::BounceIn, 0.5, 0.234_375),
(Easing::BounceOut, 1.0 / 2.75, 1.0),
// −2⁻⁵ · sin(−5.75 · 2π/3) = −1/64; Out is its mirror.
(Easing::ElasticIn, 0.5, -0.015_625),
(Easing::ElasticOut, 0.5, 1.015_625),
];
for (e, t, want) in cases {
assert!((e.apply(t) - want).abs() < 1e-9, "{e:?} at {t}: {} vs {want}", e.apply(t));
}
assert!((Easing::Classic(-100.0).apply(0.5) - 0.25).abs() < 1e-12);
assert!((Easing::Classic(100.0).apply(0.5) - 0.75).abs() < 1e-12);
assert!((Easing::SineIn.apply(1.0 / 3.0) - (1.0 - (PI / 6.0).cos())).abs() < 1e-12);
}
/// Back and Elastic In Out follow the published In Out equations, which are not In's halves.
#[test]
fn back_and_elastic_in_out_follow_the_published_equations() {
for (e, t, want) in [
(Easing::BackInOut, 0.25, -0.099_68),
(Easing::BackInOut, 0.75, 1.099_68),
(Easing::ElasticInOut, 0.25, 0.011_97),
(Easing::ElasticInOut, 0.4, -0.117_46),
(Easing::ElasticInOut, 0.75, 0.988_03),
] {
assert!((e.apply(t) - want).abs() < 5e-6, "{e:?} at {t}: {}", e.apply(t));
}
// Back In Out: ((2t)²((c+1)2t − c))/2 with c = 1.70158 × 1.525.
let c = 1.701_58 * 1.525;
for k in 1..20 {
let t = k as f64 / 40.0;
let want = (2.0 * t).powi(2) * ((c + 1.0) * 2.0 * t - c) / 2.0;
assert!((Easing::BackInOut.apply(t) - want).abs() < 1e-12, "{t}");
}
}
#[test]
fn out_mirrors_in_and_in_out_is_symmetric() {
for f in EaseFamily::ALL {
let (i, o, io) = (Easing::preset(f, EaseDir::In), Easing::preset(f, EaseDir::Out), Easing::preset(f, EaseDir::InOut));
for k in 0..=40 {
let t = k as f64 / 40.0;
assert!((o.apply(t) - (1.0 - i.apply(1.0 - t))).abs() < 1e-12, "{f:?} at {t}");
assert!((io.apply(t) + io.apply(1.0 - t) - 1.0).abs() < 1e-12, "{f:?} at {t}");
// In Out is In's halves for every family but Back and Elastic.
if !matches!(f, EaseFamily::Back | EaseFamily::Elastic) {
assert!((io.apply(t * 0.5) - 0.5 * i.apply(t)).abs() < 1e-12, "{f:?} at {t}");
}
}
assert_eq!(Easing::preset(f, EaseDir::In).family(), Some((f, EaseDir::In)));
}
}
#[test]
fn monotonic_families_never_turn_back_and_the_others_overshoot() {
for e in all() {
let overshoots = matches!(e.family(), Some((EaseFamily::Back | EaseFamily::Elastic, _))) || e.custom().is_some();
// Bounce turns back (off the floor) without leaving 0..1.
let turns = overshoots || matches!(e.family(), Some((EaseFamily::Bounce, _)));
let (mut lo, mut hi, mut prev, mut turned) = (0.0f64, 1.0f64, -1e-6f64, false);
for i in 0..=400 {
let v = e.apply(i as f64 / 400.0);
turned |= v < prev - 1e-4;
prev = v;
lo = lo.min(v);
hi = hi.max(v);
}
assert_eq!(turned, turns, "{e:?}");
assert_eq!(lo < -1e-3 || hi > 1.0 + 1e-3, overshoots, "{e:?}: {lo}..{hi}");
}
}
/// The eases meant to be monotonic never step backwards on a fine grid, not even by rounding.
#[test]
fn monotonic_eases_are_non_decreasing_everywhere() {
let mut eases: Vec<Easing> = [EaseFamily::Quad, EaseFamily::Cubic, EaseFamily::Quart, EaseFamily::Quint, EaseFamily::Sine, EaseFamily::Circ]
.into_iter()
.flat_map(|f| EaseDir::ALL.map(|d| Easing::preset(f, d)))
.collect();
eases.extend([
Easing::Linear,
Easing::Hold,
Easing::Classic(-100.0),
Easing::Classic(37.0),
Easing::Classic(100.0),
Easing::SMOOTH,
Easing::CubicBezier(1.0, 0.0, 0.0, 1.0),
Easing::CubicBezier(0.0, 1.0, 1.0, 0.0),
Easing::CubicBezier(0.9, 0.0, 0.1, 1.0),
]);
eases.push(Easing::from_temporal(TemporalEase::EASY, TemporalEase::EASY).unwrap());
eases.push(Easing::from_temporal(TemporalEase { speed: 0.0, influence: 1.0 }, TemporalEase { speed: 0.0, influence: 1.0 }).unwrap());
eases.push(Easing::Spring(SpringEase { mass: 1.0, stiffness: 100.0, damping: 40.0 }));
for e in eases {
let mut prev = 0.0;
for i in 0..=20_000 {
let v = e.apply(i as f64 / 20_000.0);
assert!(v >= prev, "{e:?} steps back at {i}: {prev} → {v}");
assert!((0.0..=1.0).contains(&v), "{e:?} leaves 0..1 at {i}: {v}");
prev = v;
}
}
}
#[test]
fn hostile_input_is_clamped() {
assert_eq!(Easing::Linear.apply(f64::NAN), 0.0);
assert_eq!(Easing::QuadIn.apply(5.0), 1.0);
assert_eq!(Easing::ElasticOut.apply(f64::INFINITY), 1.0);
assert!(Easing::CubicBezier(f64::NAN, 0.0, 1.0, 1.0).apply(0.5).is_finite());
assert!(Easing::Classic(f64::INFINITY).apply(0.5).is_finite());
assert!(Easing::Custom(Arc::new(wave())).apply(f64::NAN).is_finite());
assert!(Easing::Spring(SpringEase { mass: f64::NAN, stiffness: -1.0, damping: f64::INFINITY }).apply(0.5).is_finite());
// Huge handles are kept within ±MAX_EASE_Y when evaluated.
let wild = Easing::CubicBezier(0.5, 1e300, 0.5, -1e300);
for k in 0..=100 {
let v = wild.apply(k as f64 / 100.0);
assert!(v.abs() <= MAX_EASE_Y, "{k}: {v}");
}
// Times next to the ends, and subnormal ones.
for e in all() {
for t in [f64::MIN_POSITIVE, 5e-324, 1e-300, 1.0 - f64::EPSILON / 2.0, 1.0 - 1e-16] {
assert!(e.apply(t).is_finite(), "{e:?} at {t}");
}
}
}
#[test]
fn checked_constructors_refuse_bad_values() {
assert!(Easing::cubic_bezier(0.2, 0.0, 0.8, 1.0).is_ok());
assert_eq!(Easing::cubic_bezier(f64::NAN, 0.0, 0.8, 1.0), Err(EaseError::NotFinite("x1")));
assert!(matches!(Easing::cubic_bezier(1.2, 0.0, 0.8, 1.0), Err(EaseError::OutOfRange { what: "x1", .. })));
assert!(matches!(Easing::cubic_bezier(0.2, 0.0, -0.1, 1.0), Err(EaseError::OutOfRange { what: "x2", .. })));
assert!(matches!(Easing::cubic_bezier(0.2, 11.0, 0.8, 1.0), Err(EaseError::OutOfRange { what: "y1", .. })));
assert_eq!(Easing::cubic_bezier(0.2, 0.0, 0.8, f64::INFINITY), Err(EaseError::NotFinite("y2")));
let ok = TemporalEase { speed: 0.0, influence: 0.5 };
assert!(matches!(
Easing::from_temporal(TemporalEase { speed: 0.0, influence: 0.0 }, ok),
Err(EaseError::OutOfRange { what: "out influence", .. })
));
assert!(matches!(
Easing::from_temporal(ok, TemporalEase { speed: 0.0, influence: 1.5 }),
Err(EaseError::OutOfRange { what: "in influence", .. })
));
assert_eq!(Easing::from_temporal(TemporalEase { speed: f64::NAN, influence: 0.5 }, ok), Err(EaseError::NotFinite("out speed")));
assert!(matches!(Easing::from_temporal(TemporalEase { speed: 1e6, influence: 0.5 }, ok), Err(EaseError::OutOfRange { .. })));
assert!(Easing::spring(1.0, 100.0, 15.0).is_ok());
assert!(matches!(Easing::spring(0.0, 100.0, 15.0), Err(EaseError::OutOfRange { what: "mass", .. })));
assert_eq!(Easing::spring(1.0, f64::NAN, 15.0), Err(EaseError::NotFinite("stiffness")));
}
/// Sample values from a keyframe velocity dialog: two keys a second apart, both sides eased
/// with speed (units a second) and influence. The values are the ease's progress there.
#[test]
fn speed_and_influence_give_the_dialog_curves() {
for (out, into, samples) in [
(
TemporalEase { speed: 0.0, influence: 0.8 },
TemporalEase { speed: 0.0, influence: 0.8 },
[(0.1, 0.005_924_393_903_632_7), (0.25, 0.047_643_803_060_876_4), (0.4, 0.184_284_394_271_562), (0.75, 0.952_356_196_939_123)],
),
(
TemporalEase { speed: 0.2, influence: 0.8 },
TemporalEase { speed: 0.8, influence: 0.6 },
[(0.1, 0.022_575_494_262_157_7), (0.25, 0.069_984_188_941_293_1), (0.4, 0.149_334_636_959_052), (0.75, 0.738_196_785_378_389)],
),
(
TemporalEase { speed: 0.2, influence: 0.6 },
TemporalEase { speed: 0.8, influence: 0.8 },
[(0.1, 0.023_604_533_665_406), (0.25, 0.084_029_514_287_08), (0.4, 0.254_632_042_525_662), (0.75, 0.776_210_872_246_874)],
),
] {
let e = Easing::from_temporal(out, into).unwrap();
for (t, want) in samples {
assert!((e.apply(t) - want).abs() < 1e-9, "{out:?} {into:?} at {t}: {} vs {want}", e.apply(t));
}
let (o, i) = e.temporal().unwrap();
assert!((o.speed - out.speed).abs() < 1e-12 && (o.influence - out.influence).abs() < 1e-12);
assert!((i.speed - into.speed).abs() < 1e-12 && (i.influence - into.influence).abs() < 1e-12);
}
// The straight line's speed with a third of influence on both sides is no ease.
let line = Easing::from_temporal(TemporalEase { speed: 1.0, influence: 1.0 / 3.0 }, TemporalEase { speed: 1.0, influence: 1.0 / 3.0 }).unwrap();
for k in 0..=20 {
let t = k as f64 / 20.0;
assert!((line.apply(t) - t).abs() < 1e-12, "{t}");
}
// Easy ease is symmetric and slow at its ends.
let easy = Easing::from_temporal(TemporalEase::EASY, TemporalEase::EASY).unwrap();
assert!((easy.apply(0.5) - 0.5).abs() < 1e-12);
assert!(easy.apply(0.1) > 0.0 && easy.apply(0.1) < 0.1);
}
/// Both handles at full influence leave the time curve flat halfway; the closed-form inverse
/// keeps that point exact.
#[test]
fn full_influence_is_solved_exactly_at_the_flat_midpoint() {
let e = Easing::from_temporal(TemporalEase { speed: 0.0, influence: 1.0 }, TemporalEase { speed: 0.0, influence: 1.0 }).unwrap();
for t in [0.5 - 1e-9, 0.5 - 1e-12, 0.5, 0.5 + 1e-12, 0.5 + 1e-9, 0.1, 0.9] {
// x = 0.5 + 4 (u − 0.5)³ exactly, and y = bez(u, [0, 0, 1, 1]).
let u = 0.5 + ((t - 0.5) / 4.0f64).cbrt();
let want = 3.0 * (1.0 - u) * u * u + u * u * u;
assert!((e.apply(t) - want).abs() < 1e-12, "{t}: {} vs {want}", e.apply(t));
}
}
/// The Bezier solver converges inside its step limit for any monotonic curve, to its tolerance.
#[test]
fn the_bezier_solver_converges_within_its_bound() {
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
let mut rnd = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1_000_001) as f64 / 1_000_000.0
};
let mut worst = 0;
for _ in 0..20_000 {
let (x1, x2, t) = (rnd(), rnd(), rnd());
let p = [0.0, x1, x2, 1.0];
let (s, steps) = crate::solve_counted(t, p);
worst = worst.max(steps);
assert!(steps < crate::SOLVE_STEPS, "{p:?} at {t}");
assert!((crate::bez(s, p) - t).abs() <= crate::SOLVE_TOLERANCE, "{p:?} at {t}: {}", crate::bez(s, p));
}
// Near-flat curves, where Newton steps fail and halving takes over.
for (x1, x2) in [(1.0, 0.0), (0.999_999, 0.0), (1.0, 1e-9), (0.0, 1.0), (0.0, 0.0), (1.0, 1.0)] {
for k in 0..=1000 {
let t = k as f64 / 1000.0;
let p = [0.0, x1, x2, 1.0];
let (s, steps) = crate::solve_counted(t, p);
assert!(steps < crate::SOLVE_STEPS && (crate::bez(s, p) - t).abs() <= crate::SOLVE_TOLERANCE, "{p:?} at {t}: {steps} steps");
}
}
assert!(worst <= 20, "{worst} steps");
}
/// A Bezier with a handle past ±MAX_EASE_Y plays the same curve the graph editor shows for it.
#[test]
fn a_bezier_plays_the_curve_its_custom_form_draws() {
for e in [Easing::CubicBezier(0.3, 20.0, 0.6, 1.0), Easing::CubicBezier(0.3, -1e30, 0.6, 1e30)] {
let c = e.to_custom();
for k in 0..=40 {
let t = k as f64 * 0.025;
assert!((e.apply(t) - c.apply(t)).abs() < 1e-5, "{e:?} at {t}: {} vs {}", e.apply(t), c.apply(t));
}
}
}
/// Any speed and influence a caller can supply either is refused or plays a finite curve.
#[test]
fn speed_and_influence_over_their_whole_range_play_finite_curves() {
let mut seed = 0x51_7cc1_b727_220au64;
let mut rnd = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 1_000_001) as f64 / 1_000_000.0
};
let mut accepted = 0;
for _ in 0..20_000 {
// Speeds from 1e-4 to 1e4 either way, spread evenly in magnitude.
let side = |r: f64, i: f64| TemporalEase {
speed: (r - 0.5).signum() * 10f64.powf((r - 0.5).abs() * 16.0 - 4.0),
influence: MIN_INFLUENCE + i * (1.0 - MIN_INFLUENCE),
};
let (out, into) = (side(rnd(), rnd()), side(rnd(), rnd()));
let Ok(e) = Easing::from_temporal(out, into) else { continue };
accepted += 1;
for k in 0..=20 {
let v = e.apply(k as f64 / 20.0);
assert!(v.is_finite() && v.abs() <= MAX_EASE_Y, "{out:?} {into:?}: {v}");
}
}
assert!(accepted > 5_000, "{accepted}");
}
/// Eases, tracks and paths can be shared between render and export threads.
#[test]
fn the_types_are_send_and_sync() {
fn check<T: Send + Sync>() {}
check::<Easing>();
check::<Track<f64>>();
check::<Track<Vec2>>();
check::<MotionPath>();
check::<Spring>();
check::<SpringState>();
}
#[test]
fn bezier_forms_draw_the_same_curves() {
// Exact for these.
for e in [
Easing::Linear,
Easing::QuadIn,
Easing::QuadOut,
Easing::CubicIn,
Easing::CubicOut,
Easing::BackIn,
Easing::BackOut,
Easing::Classic(-60.0),
Easing::Classic(100.0),
Easing::CubicBezier(0.2, 1.4, 0.6, -0.3),
] {
let (a, b, c, d) = e.as_bezier().unwrap();
let bez = Easing::CubicBezier(a, b, c, d);
for i in 0..=20 {
let t = i as f64 / 20.0;
assert!((e.apply(t) - bez.apply(t)).abs() < 1e-9, "{e:?} at {t}");
}
}
for e in [Easing::QuadInOut, Easing::CubicInOut] {
let (a, b, c, d) = e.as_bezier().unwrap();
let bez = Easing::CubicBezier(a, b, c, d);
assert!((0..=20).all(|i| (e.apply(i as f64 / 20.0) - bez.apply(i as f64 / 20.0)).abs() < 0.08), "{e:?}");
}
// One curve can't draw a bounce, a hold or a multi-segment ease.
assert_eq!(Easing::BounceOut.as_bezier(), None);
assert_eq!(Easing::Hold.as_bezier(), None);
assert_eq!(Easing::Custom(Arc::new(wave())).as_bezier(), None);
let one = Easing::Custom(Arc::new(CustomEase::from_bezier(0.1, 0.9, 0.3, 1.2)));
let (a, b, c, d) = one.as_bezier().unwrap();
assert!((a - 0.1).abs() < 1e-15 && (b - 0.9).abs() < 1e-15 && (c - 0.3).abs() < 1e-15 && (d - 1.2).abs() < 1e-15);
}
#[test]
fn every_preset_becomes_a_custom_curve_for_the_graph() {
for e in all() {
let c = e.to_custom();
assert!(c.points().len() <= MAX_EASE_POINTS, "{e:?}");
let exact =
matches!(e.family(), Some((EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce, _))) || e.family().is_none();
let tol = if exact { 2e-4 } else { 5e-3 };
let mut worst = 0.0f64;
for i in 0..=500 {
let t = i as f64 / 500.0;
worst = worst.max((c.apply(t) - e.apply(t)).abs());
}
assert!(worst < tol, "{e:?}: off by {worst} with {} points", c.points().len());
}
// A hold stays flat until a jump at the end; a spring is its polyline.
let h = Easing::Hold.to_custom();
for t in [1e-9, 0.25, 0.5, 0.9, 0.999_999] {
assert_eq!(h.apply(t), Easing::Hold.apply(t), "{t}");
}
assert_eq!(h.apply(1.0), 1.0);
let s = Easing::Spring(SpringEase::GENTLE);
let sc = s.to_custom();
assert_eq!(sc.points().len(), POLYLINE_POINTS);
assert!((0..=100).all(|i| (sc.apply(i as f64 / 100.0) - s.apply(i as f64 / 100.0)).abs() < 0.02));
}
#[test]
fn ease_in_is_slow_at_start() {
assert!(Easing::QuadIn.apply(0.25) < 0.25);
assert!(Easing::QuadOut.apply(0.25) > 0.25);
assert!(Easing::Classic(-100.0).apply(0.25) < 0.25);
assert!(Easing::Classic(100.0).apply(0.25) > 0.25);
}
#[test]
fn hold_stays_at_the_start_until_the_end() {
for t in [1e-300, 0.25, 0.5, 0.999_999_999] {
assert_eq!(Easing::Hold.apply(t), 0.0);
}
assert_eq!(Easing::Hold.apply(1.0), 1.0);
assert_eq!(Easing::from_name("hold"), Some(Easing::Hold));
}
#[test]
fn names_round_trip_and_older_aliases_still_read() {
for e in Easing::named().chain([Easing::Hold]) {
let n = e.name().unwrap();
assert_eq!(Easing::from_name(&n), Some(e.clone()), "{n}");
// The file form is the same name.
#[cfg(feature = "serde")]
assert_eq!(serde_json::to_string(&e).unwrap(), format!("\"{n}\""));
}
assert_eq!(Easing::from_name("back in-out"), Some(Easing::BackInOut));
assert_eq!(Easing::from_name("ease_in"), Some(Easing::QuadIn));
assert_eq!(Easing::from_name("Smooth"), Some(Easing::CubicBezier(0.25, 0.1, 0.25, 1.0)));
assert_eq!(Easing::from_name("wobble"), None);
assert_eq!(Easing::named().count(), 28);
assert_eq!(Easing::BounceInOut.label(), "Bounce In Out");
// Files written with the variant names read back.
#[cfg(feature = "serde")]
{
let old: Vec<Easing> = serde_json::from_str(r#"["QuadIn", {"Classic": 30.0}, {"CubicBezier": [0.1, 0.2, 0.3, 0.4]}, "Linear"]"#).unwrap();
assert_eq!(old, [Easing::QuadIn, Easing::Classic(30.0), Easing::CubicBezier(0.1, 0.2, 0.3, 0.4), Easing::Linear]);
let spring: Easing = serde_json::from_str(r#"{"Spring": {"mass": 1.0, "stiffness": 600.0, "damping": 15.0}}"#).unwrap();
assert_eq!(spring, Easing::Spring(SpringEase { mass: 1.0, stiffness: 600.0, damping: 15.0 }));
assert_eq!(
serde_json::to_string(&Easing::Spring(SpringEase::GENTLE)).unwrap(),
r#"{"Spring":{"mass":1.0,"stiffness":100.0,"damping":15.0}}"#
);
}
}
#[test]
fn a_multi_segment_curve_evaluates_continuously_through_its_points() {
let c = wave();
assert_eq!(c.points().len(), 4);
for p in c.points() {
assert!((c.apply(p.at.x) - p.at.y).abs() < 1e-9 || p.at.x == 0.0, "{p:?}");
}
let mut prev = c.apply(0.0);
for i in 1..=10_000 {
let v = c.apply(i as f64 / 10_000.0);
assert!((v - prev).abs() < 2e-3, "a jump at {i}: {prev} → {v}");
prev = v;
}
// Rises past the end value, then falls back below where it was, as drawn.
assert!(c.apply(0.3) > 1.2 && c.apply(0.55) < 0.4);
}
#[test]
fn adding_a_point_keeps_the_shape() {
let c = wave();
let (d, i) = c.insert_at(0.42).unwrap();
assert_eq!((d.points().len(), i), (5, 2));
assert!(d.points()[2].smooth);
for k in 0..=200 {
let t = k as f64 / 200.0;
assert!((c.apply(t) - d.apply(t)).abs() < 1e-4, "at {t}");
}
// Not at an end or on a point.
assert!(c.insert_at(0.0).is_none() && c.insert_at(1.0).is_none() && c.insert_at(0.3).is_none() && c.insert_at(f64::NAN).is_none());
}
#[test]
fn point_edits_keep_time_running_forwards() {
let c = wave();
// Dragging a point past its neighbor stops at the neighbor.
let d = c.move_point(1, Vec2::new(0.95, 2.0)).unwrap();
assert_eq!(d.points()[1].at, Vec2::new(0.6, 2.0));
// The ends don't move.
assert!(c.move_point(0, Vec2::new(0.5, 0.5)).is_none() && c.move_point(3, Vec2::new(0.5, 0.5)).is_none());
// A handle dragged backwards in time stops at its point.
let h = c.move_handle(1, Handle::Out, Vec2::new(0.0, 5.0)).unwrap();
assert_eq!(h.points()[1].out.x, 0.0);
// A smooth point's other handle turns with it.
let s = c.set_smooth(1, true).unwrap();
let t = s.move_handle(1, Handle::Out, Vec2::new(0.45, 1.5)).unwrap();
let p = t.points()[1];
assert!(p.smooth && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-4, "{p:?}");
// A corner has its handles on the point.
let k = s.set_smooth(1, false).unwrap();
assert_eq!((k.points()[1].h_in, k.points()[1].out), (Vec2::ZERO, Vec2::ZERO));
// Removing.
assert_eq!(c.remove(2).unwrap().points().len(), 3);
assert!(c.remove(0).is_none() && c.remove(3).is_none());
}
/// Whether a smooth inner point's handles are in line (or one of them has no length).
fn in_line(p: &EasePoint) -> bool {
let (a, b) = (p.h_in, p.out);
a.length() < 1e-9 || b.length() < 1e-9 || (a.normalized().dot(b.normalized()) + 1.0).abs() < 1e-9
}
/// Turning a smooth point's other handle keeps it in line even where it has less room on its
/// side than its length: it is shortened along the line instead of clamped out of it.
#[test]
fn a_smooth_point_keeps_its_handles_in_line_near_a_neighbor() {
let c = CustomEase::new(vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::new(0.3, 0.0), smooth: false },
EasePoint { at: Vec2::new(0.9, 0.5), h_in: Vec2::new(-0.3, 0.0), out: Vec2::new(0.1, 0.3), smooth: true },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-0.05, 0.0), out: Vec2::ZERO, smooth: false },
]);
let d = c.move_handle(1, Handle::In, Vec2::new(0.5, 0.1)).unwrap();
let p = d.points()[1];
assert!(p.smooth && p.out.length() > 0.05 && in_line(&p), "{p:?}");
assert!(p.out.x <= 0.1 + 1e-12, "{p:?}");
assert_forwards(&d);
// The same near the y limit.
let e = CustomEase::new(vec![
EasePoint { at: Vec2::ZERO, h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false },
EasePoint { at: Vec2::new(0.5, 9.9), h_in: Vec2::new(-0.2, 0.0), out: Vec2::new(0.2, 0.0), smooth: true },
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::ZERO, out: Vec2::ZERO, smooth: false },
]);
let f = e.move_handle(1, Handle::Out, Vec2::new(0.6, 9.0)).unwrap();
let q = f.points()[1];
assert!(q.h_in.length() > 0.05 && in_line(&q) && q.at.y + q.h_in.y <= MAX_EASE_Y + 1e-12, "{q:?}");
}
/// Every segment's x control points lie between its ends, so x never decreases.
fn assert_forwards(c: &CustomEase) {
let pts = c.points();
assert!(pts.len() >= 2 && pts.len() <= MAX_EASE_POINTS);
assert_eq!((pts[0].at, pts[pts.len() - 1].at), (Vec2::ZERO, Vec2::new(1.0, 1.0)));
for i in 0..pts.len() - 1 {
let [a, b, cc, d] = c.segment(i).unwrap();
assert!(a.x <= b.x && b.x <= d.x && a.x <= cc.x && cc.x <= d.x, "segment {i}: {a:?} {b:?} {cc:?} {d:?}");
for v in [a, b, cc, d] {
assert!(v.is_finite() && v.y.abs() <= MAX_EASE_Y + 1e-9);
}
}
for k in 0..=100 {
assert!(c.apply(k as f64 / 100.0).is_finite());
}
}
#[test]
fn x_stays_monotonic_after_any_edit() {
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut rnd = || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % 10_000) as f64 / 10_000.0
};
let mut c = wave();
for _ in 0..3000 {
let n = c.points().len();
let i = (rnd() * n as f64) as usize % n;
let to = Vec2::new(rnd() * 1.6 - 0.3, rnd() * 30.0 - 15.0);
let op = (rnd() * 6.0) as u32;
let next = match op {
0 => c.insert_at(rnd()).map(|r| r.0),
1 => c.move_point(i, to),
2 => c.move_handle(i, Handle::In, to),
3 => c.move_handle(i, Handle::Out, to),
4 => c.set_smooth(i, rnd() > 0.5),
_ => {
if n > 6 {
c.remove(i)
} else {
None
}
}
};
if let Some(d) = next {
assert_forwards(&d);
if matches!(op, 2 | 3)
&& let Some(p) = d.points().get(i).filter(|p| p.smooth)
{
assert!(in_line(p), "{p:?}");
}
c = d;
}
}
}
#[test]
fn the_largest_index_is_a_missing_point() {
let w = wave();
assert!(w.segment(usize::MAX).is_none());
assert!(w.move_point(usize::MAX, Vec2::new(0.5, 0.5)).is_none());
assert!(w.move_handle(usize::MAX, Handle::Out, Vec2::new(0.1, 0.1)).is_none());
assert!(w.remove(usize::MAX).is_none());
assert!(w.set_smooth(usize::MAX, true).is_none());
}
#[test]
fn hostile_curves_are_repaired() {
// NaN, reversed x, out-of-range values and handles reaching backwards.
let nan = EasePoint { at: Vec2::new(f64::NAN, 0.5), ..Default::default() };
let pts = vec![
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-5.0, f64::INFINITY), ..Default::default() },
EasePoint { at: Vec2::new(0.6, 400.0), h_in: Vec2::new(3.0, 0.0), out: Vec2::new(-2.0, 0.0), smooth: true },
nan,
EasePoint { at: Vec2::new(0.2, -1.0), ..Default::default() },
EasePoint { at: Vec2::new(-3.0, 0.0), out: Vec2::new(f64::NAN, 1.0), ..Default::default() },
];
assert_eq!(CustomEase::try_new(pts.clone()), Err(EaseError::NotFinite("ease point")));
let c = CustomEase::new(pts);
assert_eq!(c.points().len(), 4);
assert_forwards(&c);
assert_eq!(c.points()[2].at, Vec2::new(0.6, MAX_EASE_Y));
// Thousands of points are thinned to the cap, and stay a valid curve.
let many: Vec<EasePoint> = (0..20_000)
.map(|i| EasePoint {
at: Vec2::new(((i * 7919) % 20_000) as f64 / 20_000.0, (i as f64 * 0.37).sin()),
out: Vec2::new(0.5, 0.0),
h_in: Vec2::new(-0.5, 0.0),
smooth: false,
})
.collect();
assert_eq!(CustomEase::try_new(many.clone()), Err(EaseError::Full(MAX_EASE_POINTS)));
let c = CustomEase::new(many);
assert_eq!(c.points().len(), MAX_EASE_POINTS);
assert_forwards(&c);
// Too few points: the line.
assert_eq!(CustomEase::new(vec![nan]), CustomEase::linear());
assert_eq!(CustomEase::try_new(vec![EasePoint::default()]), Err(EaseError::TooFew { what: "a custom ease", need: 2 }));
// From a file, the same repairs.
#[cfg(feature = "serde")]
{
let f: CustomEase = serde_json::from_str(
r#"{"points": [{"at": {"x": 0.9, "y": 3.0}}, {"at": {"x": 0.1, "y": 0.0}, "out": {"x": -1.0, "y": 0.0}}, {"at": {"x": 0.5, "y": 0.5}}]}"#,
)
.unwrap();
assert_forwards(&f);
let e: Easing = serde_json::from_str(r#"{"Custom": {"points": []}}"#).unwrap();
assert_eq!(e, Easing::Custom(Arc::new(CustomEase::linear())));
}
}
#[test]
fn custom_eases_round_trip_through_files_and_flat_lists() {
#[cfg(feature = "serde")]
{
let e = Easing::Custom(Arc::new(wave()));
let back: Easing = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(back, e);
}
let flat = wave().to_flat();
assert_eq!(flat.len(), 10);
assert_eq!(CustomEase::from_flat(&flat), Some(wave()));
assert!(CustomEase::from_flat(&flat[..9]).is_none());
}
#[test]
fn a_sampled_ease_reads_its_table_between_samples() {
let s = steps();
let e = Easing::Sampled(Arc::new(s.clone()));
assert_eq!((e.apply(0.0), e.apply(0.1), e.apply(0.25), e.apply(0.6), e.apply(0.9), e.apply(1.0)), (0.0, 0.0, 0.25, 0.5, 0.75, 1.0));
// Between two samples, the straight line between them.
let lin = SampledEase::new("Line", "p", "l", vec![0.0, 0.5, 1.0]);
assert!((lin.apply(0.25) - 0.25).abs() < 1e-12 && (lin.apply(0.75) - 0.75).abs() < 1e-12);
// Time outside 0..1, or not a number, is clamped.
assert_eq!((e.apply(-3.0), e.apply(7.0), e.apply(f64::NAN)), (0.0, 1.0, 0.0));
assert_eq!(e.label(), "Stepped 4");
assert!(e.family().is_none() && e.as_bezier().is_none());
assert_eq!(e.sampled().map(|s| (s.plugin(), s.ease())), Some(("org.example.stepped-ease", "steps4")));
}
#[test]
fn a_sampled_ease_is_always_valid() {
let s = SampledEase::new(" ", "bad id!/..", "x\u{202e}y", vec![0.3, f64::NAN, 99.0, -f64::INFINITY, 0.2]);
assert_eq!(s.values(), &[0.0, 0.25, MAX_EASE_Y, 0.75, 1.0]);
assert_eq!((s.name(), s.plugin(), s.ease()), ("Sampled ease", "badid..", "xy"));
assert_eq!(SampledEase::new("x", "p", "e", vec![]).values(), &[0.0, 1.0]);
assert_eq!(SampledEase::new("x", "p", "e", vec![0.5]).values(), &[0.0, 1.0]);
let long = SampledEase::new("x", "p", "e", (0..100_000).map(|i| i as f64 / 99_999.0).collect());
assert_eq!(long.values().len(), MAX_EASE_SAMPLES);
assert!((long.apply(0.5) - 0.5).abs() < 1e-3);
// The checked form refuses instead.
assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.0, f64::NAN, 1.0]), Err(EaseError::NotFinite("sample")));
assert!(matches!(SampledEase::try_new("x", "p", "e", vec![0.0, 99.0, 1.0]), Err(EaseError::OutOfRange { .. })));
assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.0]), Err(EaseError::TooFew { what: "a sampled ease", need: 2 }));
assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.5; MAX_EASE_SAMPLES + 1]), Err(EaseError::Full(MAX_EASE_SAMPLES)));
assert_eq!(SampledEase::try_new("x", "p", "e", vec![0.2, 0.5, 0.9]).unwrap().values(), &[0.0, 0.5, 1.0]);
}
/// Thinning a table picks evenly spread samples, first and last included, for any length a
/// `usize` can hold (a 32-bit target overflows `k · (n − 1)` from about 4.2 million values).
#[test]
fn thinning_a_huge_table_does_not_overflow() {
use crate::sampled::thinned;
let last = MAX_EASE_SAMPLES - 1;
for n in [MAX_EASE_SAMPLES + 1, 5_000_000, usize::MAX / 3, usize::MAX] {
assert_eq!(thinned(0, n), 0);
assert_eq!(thinned(last, n), n - 1, "{n}");
assert!(thinned(last / 2, n) >= (n - 1) / 2 - 1 && thinned(last / 2, n) <= (n - 1) / 2, "{n}");
assert!((1..=last).all(|k| thinned(k, n) > thinned(k - 1, n)), "{n}");
}
}
/// Invisible format characters do not count as a name, so a name of only those shows as
/// "Sampled ease"; they are taken out of a visible name too.
#[test]
fn a_sampled_ease_name_of_invisible_characters_is_no_name() {
let blank: String = "\u{200b}\u{200d}\u{feff}\u{2060}\u{ad}".repeat(13);
assert_eq!(SampledEase::new(&blank, "p", "e", vec![0.0, 1.0]).name(), "Sampled ease");
assert_eq!(SampledEase::new(" \u{200b} Bounce\u{200d}y \u{feff}", "p", "e", vec![0.0, 1.0]).name(), "Bouncey");
// A visible name longer than the limit keeps its first 64 characters, after leading padding.
let padded = format!("{}{}", " \u{200b}".repeat(100), "a".repeat(80));
assert_eq!(SampledEase::new(&padded, "p", "e", vec![0.0, 1.0]).name(), "a".repeat(64));
}
#[cfg(feature = "serde")]
#[test]
fn a_sampled_ease_round_trips_through_the_file_format_and_survives_bad_files() {
let e = Easing::Sampled(Arc::new(steps()));
let text = serde_json::to_string(&e).unwrap();
assert!(
text.starts_with("{\"Sampled\":{\"name\":\"Stepped 4\",\"plugin\":\"org.example.stepped-ease\",\"ease\":\"steps4\",\"values\":[0.0,"),
"{text}"
);
assert_eq!(serde_json::from_str::<Easing>(&text).unwrap(), e);
// A hand-edited table is made valid on load; a value that is not a number is a broken file.
assert!(serde_json::from_str::<Easing>(r#"{"Sampled":{"values":[5,0.5,"x"]}}"#).is_err());
let odd: Easing = serde_json::from_str(r#"{"Sampled":{"name":"Odd","values":[5,0.5,-20]}}"#).unwrap();
assert_eq!(odd.sampled().unwrap().values(), &[0.0, 0.5, 1.0]);
}
/// A file with a huge list loads from its first 65,536 entries; the rest are skipped unread,
/// so they are never stored (here they would not even parse as entries).
#[cfg(feature = "serde")]
#[test]
fn huge_lists_in_files_are_read_only_up_to_a_limit() {
let mut values = String::from(r#"{"Sampled":{"values":["#);
for i in 0..70_000 {
values.push_str(if i < 65_536 { "0.5," } else { r#"{"not":"a value"},"# });
}
values.push_str("1]}}");
let e: Easing = serde_json::from_str(&values).unwrap();
assert_eq!(e.sampled().unwrap().values().len(), MAX_EASE_SAMPLES);
let mut points = String::from(r#"{"Custom":{"points":["#);
for i in 0..70_000 {
points.push_str(if i < 65_536 { r#"{"at":{"x":0.5,"y":0.5}},"# } else { r#""not a point","# });
}
points.push_str(r#"{"at":{"x":1,"y":1}}]}}"#);
let c: Easing = serde_json::from_str(&points).unwrap();
assert!(matches!(&c, Easing::Custom(f) if f.points().len() <= MAX_EASE_POINTS), "{c:?}");
// A long name keeps only its first characters.
let long = format!(r#"{{"Sampled":{{"name":"{}","plugin":"p","ease":"e","values":[0,1]}}}}"#, "é".repeat(100_000));
let s: Easing = serde_json::from_str(&long).unwrap();
assert_eq!(s.sampled().unwrap().name(), "é".repeat(64));
// Characters the cleanup removes do not push the kept text out of reach.
let padded = format!(r#"{{"Sampled":{{"name":"{}Curve","plugin":"{}p1","ease":"e","values":[0,1]}}}}"#, " ".repeat(10_000), "!".repeat(10_000));
let s: Easing = serde_json::from_str(&padded).unwrap();
assert_eq!((s.sampled().unwrap().name(), s.sampled().unwrap().plugin()), ("Curve", "p1"));
}
#[test]
fn a_sampled_ease_becomes_a_custom_curve_through_its_samples() {
let wave = SampledEase::new(
"Wave",
"p",
"w",
(0..257)
.map(|i| {
let t = i as f64 / 256.0;
t + 0.2 * (t * std::f64::consts::TAU).sin()
})
.collect(),
);
let c = wave.to_polyline();
assert_eq!(c.points().len(), POLYLINE_POINTS);
for i in 0..=100 {
let t = i as f64 / 100.0;
assert!((c.apply(t) - wave.apply(t)).abs() < 0.01, "t = {t}: {} vs {}", c.apply(t), wave.apply(t));
}
let short = SampledEase::new("Short", "p", "s", vec![0.0, 0.8, 1.0]).to_polyline();
assert_eq!(short.points().len(), 3);
assert!((short.apply(0.5) - 0.8).abs() < 1e-3);
}
+165
View File
@@ -0,0 +1,165 @@
use crate::*;
/// A quarter circle of radius 100 about the origin, from (100, 0) to (0, 100).
fn quarter() -> MotionPath {
let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * 100.0;
MotionPath::new(&[Vec2::new(100.0, 0.0), Vec2::new(100.0, k), Vec2::new(k, 100.0), Vec2::new(0.0, 100.0)]).unwrap()
}
/// The length of the curve through `n` evenly spaced points along it.
fn polyline_length(p: &MotionPath, n: usize) -> f64 {
(1..=n).map(|i| p.point_at_length(p.length() * i as f64 / n as f64).distance(p.point_at_length(p.length() * (i - 1) as f64 / n as f64))).sum()
}
/// A tiny curve is walked at constant speed like the same curve at full size.
#[test]
fn a_tiny_curve_is_walked_at_constant_speed() {
let r = 1e-15;
let k = 4.0 / 3.0 * (std::f64::consts::PI / 8.0).tan() * r;
let tiny = MotionPath::new(&[Vec2::new(r, 0.0), Vec2::new(r, k), Vec2::new(k, r), Vec2::new(0.0, r)]).unwrap();
let big = quarter();
for i in 1..20 {
let t = i as f64 / 20.0;
let (a, b) = (tiny.point_at(t), big.point_at(t));
assert!((a.x / r - b.x / 100.0).abs() < 1e-9 && (a.y / r - b.y / 100.0).abs() < 1e-9, "{t}: {a:?} vs {b:?}");
}
}
#[test]
fn a_curve_is_measured_and_walked_at_constant_speed() {
let p = quarter();
// The Bezier quarter circle is within 0.03 % of the circle's length.
assert!((p.length() - 50.0 * std::f64::consts::PI).abs() < 0.05, "{}", p.length());
assert!((polyline_length(&p, 20_000) - p.length()).abs() < 1e-6, "{} vs {}", polyline_length(&p, 20_000), p.length());
// Equal steps of distance are equal chords.
let n = 200;
let steps: Vec<f64> = (1..=n).map(|i| p.point_at(i as f64 / n as f64).distance(p.point_at((i - 1) as f64 / n as f64))).collect();
let (lo, hi) = steps.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s)));
assert!(hi - lo < 1e-6, "{lo}..{hi}");
assert_eq!(p.point_at(0.0), Vec2::new(100.0, 0.0));
let end = p.point_at(1.0);
assert!(end.distance(Vec2::new(0.0, 100.0)) < 1e-9, "{end:?}");
// Each point is on the curve: about 100 from the center.
for i in 0..=50 {
let r = p.point_at(i as f64 / 50.0).length();
assert!((r - 100.0).abs() < 0.03, "{r}");
}
}
#[test]
fn a_straight_segment_with_uneven_handles_still_moves_evenly() {
// Handles on the chord but bunched near the start: the curve's own parameter speeds up.
let p = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap();
assert_eq!(p.length(), 100.0);
for i in 0..=10 {
assert_eq!(p.point_at(i as f64 / 10.0), Vec2::new(i as f64 * 10.0, 0.0));
}
}
#[test]
fn past_the_ends_the_motion_continues_along_the_path() {
let p = quarter();
// At the end the circle heads in −x; past it the point keeps going that way.
let past = p.point_at_length(p.length() + 10.0);
assert!(past.distance(Vec2::new(-10.0, 100.0)) < 1e-6, "{past:?}");
let before = p.point_at_length(-5.0);
assert!(before.distance(Vec2::new(100.0, -5.0)) < 1e-6, "{before:?}");
// A track's overshooting ease drives the same distance through point_at.
let over = Easing::BackOut;
let peak = (1..100).map(|i| over.apply(i as f64 / 100.0)).fold(f64::MIN, f64::max);
let beyond = p.point_at(peak);
assert!(beyond.x < 0.0 && (beyond.y - 100.0).abs() < 1e-6, "{beyond:?}");
let d = p.direction_at_length(p.length() * 2.0);
assert!(d.distance(Vec2::new(-1.0, 0.0)) < 1e-9, "{d:?}");
assert_eq!(p.point_at_length(f64::INFINITY), p.point_at(1.0));
assert_eq!(p.point_at_length(f64::NAN), Vec2::new(100.0, 0.0));
assert_eq!(p.point_at_length(f64::NEG_INFINITY), Vec2::new(100.0, 0.0));
let flat = MotionPath::new(&[Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(3.0, 0.0)]).unwrap();
assert_eq!(flat.point_at_length(f64::NEG_INFINITY), Vec2::ZERO);
}
/// Moving a handle off the chord by a rounding error does not change where an overshoot goes.
#[test]
fn an_overshoot_goes_the_same_way_on_a_straight_and_an_almost_straight_path() {
let straight = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 0.0), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap();
let bent = MotionPath::new(&[Vec2::ZERO, Vec2::new(30.0, 1e-6), Vec2::new(70.0, 0.0), Vec2::new(100.0, 0.0)]).unwrap();
for progress in [-0.2, 1.1, 1.25] {
let (a, b) = (straight.point_at(progress), bent.point_at(progress));
assert!(a.distance(b) < 0.01, "{progress}: {a:?} vs {b:?}");
}
assert!(straight.point_at(1.25).distance(Vec2::new(125.0, 0.0)) < 1e-9);
}
#[test]
fn a_path_through_anchors_passes_through_each_one() {
let anchors = [Vec2::new(0.0, 0.0), Vec2::new(100.0, 50.0), Vec2::new(200.0, 0.0), Vec2::new(300.0, 80.0)];
let p = MotionPath::through(&anchors).unwrap();
assert_eq!(p.segments(), 3);
// Each anchor is reached at some distance along it.
for a in anchors {
let nearest = (0..=4000).map(|i| p.point_at(i as f64 / 4000.0).distance(a)).fold(f64::MAX, f64::min);
assert!(nearest < 0.1, "{a:?}: {nearest}");
}
// Smooth through the inner anchors: no turn in direction across them.
let mut prev = p.direction_at_length(0.0);
for i in 1..=2000 {
let d = p.direction_at_length(p.length() * i as f64 / 2000.0);
assert!(d.dot(prev) > 0.99, "a corner at {i}");
prev = d;
}
// Two anchors at one place make a segment of zero length, which is skipped over.
let q = MotionPath::through(&[Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(20.0, 0.0)]).unwrap();
assert!((q.length() - 20.0).abs() < 1e-9, "{}", q.length());
assert!(q.point_at(0.75).distance(Vec2::new(15.0, 0.0)) < 1e-6);
// Anchors repeated at either end still let the motion continue past it.
let r = MotionPath::through(&[Vec2::ZERO, Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 0.0)]).unwrap();
assert!(r.point_at(1.2).distance(Vec2::new(12.0, 0.0)) < 1e-6, "{:?}", r.point_at(1.2));
assert!(r.point_at(-0.1).distance(Vec2::new(-1.0, 0.0)) < 1e-6, "{:?}", r.point_at(-0.1));
assert!(r.direction_at_length(20.0).distance(Vec2::new(1.0, 0.0)) < 1e-9);
assert!(r.direction_at_length(-1.0).distance(Vec2::new(1.0, 0.0)) < 1e-9);
}
#[test]
fn bad_paths_are_refused() {
assert_eq!(MotionPath::new(&[Vec2::ZERO; 3]), Err(EaseError::TooFew { what: "a motion path", need: 4 }));
assert!(matches!(MotionPath::new(&[Vec2::ZERO; 5]), Err(EaseError::OutOfRange { .. })));
assert_eq!(MotionPath::new(&[Vec2::ZERO, Vec2::new(f64::NAN, 0.0), Vec2::ZERO, Vec2::ZERO]), Err(EaseError::NotFinite("path point")));
assert_eq!(MotionPath::new(&vec![Vec2::ZERO; 3 * MAX_PATH_SEGMENTS + 4]), Err(EaseError::Full(MAX_PATH_SEGMENTS)));
assert_eq!(MotionPath::through(&[Vec2::ZERO]), Err(EaseError::TooFew { what: "a motion path", need: 2 }));
assert_eq!(MotionPath::through(&[Vec2::ZERO, Vec2::new(0.0, f64::INFINITY)]), Err(EaseError::NotFinite("path point")));
// A path too long to measure.
assert_eq!(
MotionPath::new(&[Vec2::new(-f64::MAX, 0.0), Vec2::new(-f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0), Vec2::new(f64::MAX, 0.0)]),
Err(EaseError::Overflow)
);
// A path of one point stands still.
let still = MotionPath::new(&[Vec2::new(3.0, 4.0); 4]).unwrap();
assert_eq!((still.length(), still.point_at(0.5), still.direction_at_length(1.0)), (0.0, Vec2::new(3.0, 4.0), Vec2::ZERO));
}
/// A curve with huge coordinates (whose squares overflow) is walked as the same curve scaled,
/// not taken for a straight line.
#[test]
fn a_huge_curve_is_not_taken_for_a_straight_line() {
let shape = |k: f64| MotionPath::new(&[Vec2::ZERO, Vec2::new(0.0, k), Vec2::new(0.0, k), Vec2::new(2.0 * k, 0.0)]).unwrap();
let (small, huge) = (shape(1.0), shape(1e154));
for i in 0..=10 {
let t = i as f64 / 10.0;
let (a, b) = (small.point_at(t), huge.point_at(t));
assert!((b.x / 1e154 - a.x).abs() < 1e-9 && (b.y / 1e154 - a.y).abs() < 1e-9, "{t}: {a:?} vs {b:?}");
}
assert!(huge.point_at(0.5).y > 5e153, "{:?}", huge.point_at(0.5));
// A long chord with handles a small distance off it still bends.
let long = MotionPath::new(&[Vec2::ZERO, Vec2::new(1e12 / 3.0, 1000.0), Vec2::new(2e12 / 3.0, 1000.0), Vec2::new(1e12, 0.0)]).unwrap();
let mid = long.point_at_length(long.length() / 2.0);
assert!((mid.y - 750.0).abs() < 1.0, "{mid:?}");
}
#[test]
fn a_long_path_finds_its_segment_by_binary_search() {
let anchors: Vec<Vec2> = (0..=MAX_PATH_SEGMENTS).map(|i| Vec2::new(i as f64, ((i as f64) * 0.1).sin())).collect();
let p = MotionPath::through(&anchors).unwrap();
assert_eq!(p.segments(), MAX_PATH_SEGMENTS);
let mid = p.point_at(0.5);
assert!(mid.x > 4000.0 && mid.x < 6000.0, "{mid:?}");
}
+259
View File
@@ -0,0 +1,259 @@
use crate::*;
/// A spring released from 0 toward 1, `t` seconds in, from the closed forms written out
/// separately: under-damped, critically damped and over-damped.
fn released(w: f64, z: f64, t: f64) -> f64 {
if z < 1.0 {
let wd = w * (1.0 - z * z).sqrt();
1.0 - (-z * w * t).exp() * ((wd * t).cos() + z * w / wd * (wd * t).sin())
} else if (z - 1.0).abs() < 1e-9 {
1.0 - (-w * t).exp() * (1.0 + w * t)
} else {
let s = (z * z - 1.0).sqrt();
let (r1, r2) = (-w / (z + s), -w * (z + s));
1.0 - (r2 * (r1 * t).exp() - r1 * (r2 * t).exp()) / (r2 - r1)
}
}
const PRESETS: [(f64, f64, f64); 5] = [(1.0, 100.0, 15.0), (1.0, 300.0, 20.0), (1.0, 600.0, 15.0), (1.0, 80.0, 20.0), (2.5, 40.0, 2.0)];
#[test]
fn a_physical_spring_ease_matches_the_closed_form() {
for (m, k, c) in PRESETS {
let spring = Spring::from_physical(m, k, c).unwrap();
let (w, z) = ((k / m).sqrt(), c / (2.0 * (k * m).sqrt()));
assert!((spring.omega() - w).abs() < 1e-12 && (spring.damping() - z).abs() < 1e-12);
let rate = if z < 1.0 { z * w } else { w / (z + (z * z - 1.0).sqrt()) };
let lead = if z < 1.0 { (6.9 - 0.5 * (1.0 - z * z).ln()).min(9.2) } else { 9.2 };
let settle = (lead / rate).clamp(0.05, 10.0);
assert!((spring.settle_time() - settle).abs() < 1e-12);
let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c });
// A spring cut short at 10 seconds has what it is still off taken out evenly.
let rest = if settle < 10.0 { 0.0 } else { 1.0 - released(w, z, settle) };
for i in 1..1000 {
let t = i as f64 / 1000.0;
let want = released(w, z, t * settle) + t * rest;
assert!((ease.apply(t) - want).abs() < 1e-12, "{m} {k} {c} at {t}: {} vs {want}", ease.apply(t));
}
// It ends within 0.1 % (0.2 % for the slower lead factor) of 1 before the jump to 1.
assert!((ease.apply(0.999_999) - 1.0).abs() < 2e-3, "{m} {k} {c}");
}
}
/// A step of no time returns the value unchanged, even when its distance to the target is too
/// large to represent.
#[test]
fn a_zero_length_step_keeps_a_far_value() {
let spring = Spring::new(1.0, 0.5).unwrap();
let mut s = SpringState::at(1e308);
assert_eq!(s.step(&spring, -1e308, 0.0), Ok(1e308));
assert_eq!(s, SpringState::at(1e308));
// A state that is not finite is still refused.
let mut bad = SpringState::at(f64::NAN);
assert_eq!(bad.step(&spring, 0.0, 0.0), Err(EaseError::Overflow));
}
/// A value and target at opposite ends of the f64 range move like any others.
#[test]
fn a_step_across_the_whole_range_does_not_overflow() {
let spring = Spring::new(1.0, 1.0).unwrap();
let mut s = SpringState::at(f64::MAX);
let v = s.step(&spring, -f64::MAX, 10.0).unwrap();
assert!(v.is_finite() && v < 0.0 && s.velocity.is_finite(), "{s:?}");
}
/// The smallest positive target is reached.
#[test]
fn a_spring_reaches_a_subnormal_target() {
let spring = Spring::new(1.0, 1.0).unwrap();
let mut s = SpringState::at(0.0);
assert_eq!(s.step(&spring, f64::from_bits(1), 1000.0), Ok(f64::from_bits(1)));
}
/// A spring of the lowest frequency still moves at its velocity over a step.
#[test]
fn a_very_slow_spring_steps_without_overflow() {
let spring = Spring::new(1e-320, 0.0).unwrap();
let mut s = SpringState { value: 0.0, velocity: 1.0 };
let v = s.step(&spring, 0.0, 1.0).unwrap();
assert!((v - 1.0).abs() < 1e-12 && (s.velocity - 1.0).abs() < 1e-12, "{s:?}");
}
/// Physical values whose damping ratio is above the limit are refused, not changed.
#[test]
fn physical_values_past_the_damping_ratio_limit_are_refused() {
assert_eq!(
Spring::from_physical(0.01, 0.01, 1_000_000.0),
Err(EaseError::OutOfRange { what: "damping ratio", min: 0.0, max: MAX_DAMPING_RATIO })
);
assert!(Spring::from_physical(0.01, 0.01, 19.0).is_ok());
}
/// A spring just under critical damping is within about 0.1 % of 1 just before the end, so the
/// ease does not jump when it reaches 1.
#[test]
fn a_nearly_critical_spring_ease_ends_without_a_jump() {
for z in [0.5, 0.9, 0.99, 0.999, 0.9999, 1.0 - 2e-4] {
let s = Spring::new(1.0, z).unwrap();
let end = s.ease(1.0 - 1e-9);
assert!((end - 1.0).abs() < 1.1e-3, "ζ {z}: {end}");
// The bound holds after the settle time too, not only at it.
let late = 1.0 + s.response(-1.0, 0.0, 1.5 * s.settle_time()).0;
assert!((late - 1.0).abs() < 1.1e-3, "ζ {z} later: {late}");
}
}
/// An undamped or barely damped spring ease still arrives at 1 without a jump.
#[test]
fn a_spring_that_never_settles_still_ends_at_one() {
for (m, k, c) in [(1.0, 100.0, 0.0), (1.0, 100.0, 0.01), (10.0, 0.5, 0.0)] {
let e = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c });
assert!((e.apply(1.0 - 1e-9) - 1.0).abs() < 1e-6, "{m} {k} {c}: {}", e.apply(1.0 - 1e-9));
assert!((1..1000).all(|i| e.apply(i as f64 / 1000.0).is_finite()));
}
}
/// Stepping a spring from rest toward 1 frame by frame traces its ease.
#[test]
fn stepping_from_rest_traces_the_spring_ease() {
// Springs that settle within 10 seconds (the others have their ease adjusted to end at 1).
for (m, k, c) in PRESETS.into_iter().filter(|&(m, k, c)| Spring::from_physical(m, k, c).unwrap().settle_time() < 10.0) {
let s = Spring::from_physical(m, k, c).unwrap();
let ease = Easing::Spring(SpringEase { mass: m, stiffness: k, damping: c });
let (settle, frames) = (s.settle_time(), 600);
let mut st = SpringState::at(0.0);
for f in 1..frames {
let v = st.step(&s, 1.0, settle / frames as f64).unwrap();
let want = ease.apply(f as f64 / frames as f64);
assert!((v - want).abs() < 1e-9, "{m} {k} {c} frame {f}: {v} vs {want}");
}
}
}
#[test]
fn the_three_damping_regimes_and_the_critical_band_agree() {
// Either side of critical damping, the solutions meet the critically damped one.
let w = 10.0;
for t in [0.01, 0.1, 0.3, 1.0] {
let crit = released(w, 1.0, t);
for z in [1.0 - 2e-4, 1.0 - 5e-5, 1.0, 1.0 + 5e-5, 1.0 + 2e-4] {
let s = Spring::new(w / std::f64::consts::TAU, z).unwrap();
let mut st = SpringState::at(0.0);
let v = st.step(&s, 1.0, t).unwrap();
assert!((v - crit).abs() < 1e-3, "ζ {z} at {t}: {v} vs {crit}");
}
}
}
#[test]
fn a_spring_settles_on_its_target() {
for (f, z) in [(2.0, 0.2), (1.0, 1.0), (0.5, 3.0), (8.0, 0.05)] {
let s = Spring::new(f, z).unwrap();
let mut st = SpringState::at(0.0);
for _ in 0..60 * 120 {
st.step(&s, 10.0, 1.0 / 60.0).unwrap();
}
assert!(st.settled(10.0, 1e-6), "{f} Hz ζ {z}: {st:?}");
}
// An undamped spring keeps swinging, its energy kept.
let s = Spring::new(1.0, 0.0).unwrap();
let mut st = SpringState::at(0.0);
for _ in 0..60 * 100 {
st.step(&s, 1.0, 1.0 / 60.0).unwrap();
}
let w = s.omega();
let energy = (st.value - 1.0).powi(2) + (st.velocity / w).powi(2);
assert!((energy - 1.0).abs() < 1e-9, "{energy}");
}
/// Many short steps land where one long step does: the step is exact, not an integrator.
#[test]
fn many_small_steps_equal_one_long_step() {
for (f, z) in [(3.0, 0.3), (1.0, 1.0), (1.0, 4.0), (0.7, 0.0)] {
let s = Spring::new(f, z).unwrap();
let mut one = SpringState { value: -2.0, velocity: 5.0 };
let mut many = one;
one.step(&s, 1.0, 2.0).unwrap();
for _ in 0..240 {
many.step(&s, 1.0, 2.0 / 240.0).unwrap();
}
assert!((one.value - many.value).abs() < 1e-9 && (one.velocity - many.velocity).abs() < 1e-8, "{f} {z}: {one:?} {many:?}");
}
// Variable frame lengths too.
let s = Spring::new(2.0, 0.4).unwrap();
let (mut a, mut b) = (SpringState::at(0.0), SpringState::at(0.0));
a.step(&s, 1.0, 0.5).unwrap();
for dt in [0.1, 0.016, 0.05, 0.034, 0.2, 0.1] {
b.step(&s, 1.0, dt).unwrap();
}
assert!((a.value - b.value).abs() < 1e-9);
}
#[test]
fn huge_steps_land_on_the_target() {
for (f, z) in [(MAX_SPRING_HZ, 0.0001), (1e-6, 0.5), (1.0, MAX_DAMPING_RATIO), (5.0, 1.0)] {
let s = Spring::new(f, z).unwrap();
for dt in [1e6, 1e300, f64::MAX] {
let mut st = SpringState { value: 5.0, velocity: -3.0 };
let v = st.step(&s, 2.0, dt).unwrap();
assert!(v.is_finite() && st.velocity.is_finite(), "{f} {z} {dt}");
}
}
let s = Spring::new(4.0, 0.5).unwrap();
let mut st = SpringState { value: 5.0, velocity: -3.0 };
assert_eq!(st.step(&s, 2.0, 1e300).unwrap(), 2.0);
assert_eq!(st.velocity, 0.0);
// An undamped spring keeps its energy over any finite step, the longest included.
let s = Spring::new(MAX_SPRING_HZ, 0.0).unwrap();
let w = s.omega();
for dt in [1e300, f64::MAX] {
let mut st = SpringState { value: 5.0, velocity: -3.0 };
st.step(&s, 2.0, dt).unwrap();
let energy = (st.value - 2.0).powi(2) + (st.velocity / w).powi(2);
assert!((energy - (9.0 + (3.0 / w).powi(2))).abs() < 1e-9, "{dt}: {st:?}");
}
let s = Spring::new(4.0, 0.5).unwrap();
// A zero step changes nothing.
let mut st = SpringState { value: 5.0, velocity: -3.0 };
assert_eq!(st.step(&s, 2.0, 0.0).unwrap(), 5.0);
assert_eq!(st.velocity, -3.0);
}
#[test]
fn bad_inputs_are_refused_and_leave_the_state_alone() {
assert_eq!(Spring::new(f64::NAN, 0.5), Err(EaseError::NotFinite("frequency")));
assert!(matches!(Spring::new(0.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. })));
assert!(matches!(Spring::new(MAX_SPRING_HZ * 2.0, 0.5), Err(EaseError::OutOfRange { what: "frequency", .. })));
assert!(matches!(Spring::new(1.0, -0.1), Err(EaseError::OutOfRange { what: "damping", .. })));
assert_eq!(Spring::new(1.0, f64::INFINITY), Err(EaseError::NotFinite("damping")));
assert!(matches!(Spring::from_controls(1.5, 0.5), Err(EaseError::OutOfRange { what: "strength", .. })));
assert!(matches!(Spring::from_physical(1.0, 0.0, 1.0), Err(EaseError::OutOfRange { what: "stiffness", .. })));
let s = Spring::new(1.0, 0.5).unwrap();
let start = SpringState { value: 1.0, velocity: 2.0 };
for (target, dt, err) in [
(f64::NAN, 0.1, EaseError::NotFinite("target")),
(f64::INFINITY, 0.1, EaseError::NotFinite("target")),
(0.0, f64::NAN, EaseError::NotFinite("step")),
(0.0, f64::INFINITY, EaseError::NotFinite("step")),
] {
let mut st = start;
assert_eq!(st.step(&s, target, dt), Err(err));
assert_eq!(st, start);
}
let mut st = start;
assert!(matches!(st.step(&s, 0.0, -0.1), Err(EaseError::OutOfRange { what: "step", .. })));
assert_eq!(st, start);
// A value too far from the target to measure is refused, not turned into NaN.
let mut far = SpringState { value: f64::MAX, velocity: 0.0 };
assert_eq!(far.step(&s, -f64::MAX, 0.1), Err(EaseError::Overflow));
assert_eq!(far, SpringState { value: f64::MAX, velocity: 0.0 });
}
#[test]
fn the_controls_map_onto_frequency_and_damping() {
let s = Spring::from_controls(0.0, 0.0).unwrap();
assert!((s.omega() - std::f64::consts::TAU * 0.5).abs() < 1e-12 && s.damping() == 0.0);
let s = Spring::from_controls(1.0, 2.0 / 3.0).unwrap();
assert!((s.omega() - std::f64::consts::TAU * 10.0).abs() < 1e-9 && (s.damping() - 1.0).abs() < 1e-12);
assert_eq!(Spring::from_controls(0.5, 1.0).unwrap().damping(), MAX_DAMPING_RATIO);
}
+162
View File
@@ -0,0 +1,162 @@
use crate::*;
fn key<T>(time: f64, value: T, ease: Easing) -> Key<T> {
Key { time, value, ease }
}
#[test]
fn a_track_eases_between_its_keys_and_holds_outside_them() {
let t = Track::from_keys(vec![
key(2.0, 10.0f64, Easing::QuadIn),
key(0.0, 0.0, Easing::Linear),
key(4.0, 0.0, Easing::Hold),
key(6.0, 50.0, Easing::Linear),
])
.unwrap();
assert_eq!(t.keys().iter().map(|k| k.time).collect::<Vec<_>>(), [0.0, 2.0, 4.0, 6.0]);
assert_eq!(t.sample(-1.0), Ok(0.0));
assert_eq!(t.sample(1.0), Ok(5.0));
assert_eq!(t.sample(2.0), Ok(10.0));
// Quad in: a quarter of the way at half time.
assert_eq!(t.sample(3.0), Ok(7.5));
// Hold keeps the value until the next key.
assert_eq!(t.sample(4.0), Ok(0.0));
assert_eq!(t.sample(5.999), Ok(0.0));
assert_eq!(t.sample(6.0), Ok(50.0));
assert_eq!(t.sample(1e300), Ok(50.0));
}
#[test]
fn an_overshooting_ease_carries_the_value_past_its_keys() {
let t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::BackOut), key(1.0, 100.0, Easing::Linear)]).unwrap();
let peak = (1..100).map(|i| t.sample(i as f64 / 100.0).unwrap()).fold(f64::MIN, f64::max);
assert!(peak > 105.0 && peak < 115.0, "{peak}");
}
#[test]
fn tracks_hold_any_animatable_value() {
let p = Track::from_keys(vec![key(0.0, Vec2::new(0.0, 0.0), Easing::Linear), key(1.0, Vec2::new(10.0, -20.0), Easing::Linear)]).unwrap();
assert_eq!(p.sample(0.5), Ok(Vec2::new(5.0, -10.0)));
let c = Track::from_keys(vec![key(0.0, [0.0f32, 1.0, 0.5, 1.0], Easing::Linear), key(2.0, [1.0, 0.0, 0.5, 0.0], Easing::Linear)]).unwrap();
assert_eq!(c.sample(1.0), Ok([0.5, 0.5, 0.5, 0.5]));
let s = Track::from_keys(vec![key(0.0, 1.0f32, Easing::Linear), key(1.0, 3.0, Easing::Linear)]).unwrap();
assert_eq!(s.sample(0.25), Ok(1.5));
let d = Track::from_keys(vec![key(0.0, [0.0f64; 3], Easing::Linear), key(1.0, [3.0, 6.0, 9.0], Easing::Linear)]).unwrap();
assert_eq!(d.sample(1.0 / 3.0).map(|v| v.map(|x| (x * 1e9).round() / 1e9)), Ok([1.0, 2.0, 3.0]));
}
#[test]
fn bad_keys_and_times_are_refused() {
assert_eq!(Track::<f64>::new().sample(0.0), Err(EaseError::Empty));
let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear)]).unwrap();
assert_eq!(t.sample(f64::NAN), Err(EaseError::NotFinite("time")));
assert_eq!(t.sample(f64::INFINITY), Err(EaseError::NotFinite("time")));
assert_eq!(t.sample(5.0), Ok(1.0));
assert_eq!(Track::from_keys(vec![key(f64::NAN, 1.0f64, Easing::Linear)]), Err(EaseError::NotFinite("time")));
assert_eq!(Track::from_keys(vec![key(0.0, f64::NAN, Easing::Linear)]), Err(EaseError::NotFinite("value")));
assert_eq!(Track::from_keys(vec![key(0.0, Vec2::new(0.0, f64::INFINITY), Easing::Linear)]), Err(EaseError::NotFinite("value")));
assert_eq!(Track::from_keys(vec![key(1.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(1.0)));
// −0 and +0 are one time.
assert_eq!(Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(0.0, 2.0, Easing::Linear)]), Err(EaseError::SameTime(0.0)));
let mut z = Track::from_keys(vec![key(-0.0, 1.0f64, Easing::Linear), key(1.0, 2.0, Easing::Linear)]).unwrap();
assert_eq!(z.key_at(0.0), Some(0));
assert_eq!(z.key_at(-0.0), Some(0));
assert_eq!(z.insert(0.0, 5.0), Ok(0));
assert_eq!(z.len(), 2);
let too_many: Vec<Key<f32>> = (0..=MAX_TRACK_KEYS).map(|i| key(i as f64, 0.0, Easing::Linear)).collect();
assert_eq!(Track::from_keys(too_many), Err(EaseError::Full(MAX_TRACK_KEYS)));
}
#[test]
fn inserting_splits_a_segment_with_its_ease() {
let mut t = Track::from_keys(vec![key(0.0, 0.0f64, Easing::CubicIn), key(2.0, 8.0, Easing::Linear)]).unwrap();
assert_eq!(t.insert(1.0, 1.0), Ok(1));
assert_eq!(t.keys()[1].ease, Easing::CubicIn);
// Setting an existing key keeps its ease.
t.set_ease(1, Easing::Hold).unwrap();
assert_eq!(t.insert(1.0, 3.0), Ok(1));
assert_eq!((t.keys()[1].value, &t.keys()[1].ease), (3.0, &Easing::Hold));
assert_eq!(t.insert(-0.0, 7.0), Ok(0));
assert_eq!(t.len(), 3);
assert_eq!(t.key_at(0.0), Some(0));
assert_eq!(t.insert(5.0, f64::NAN), Err(EaseError::NotFinite("value")));
assert_eq!(t.insert(f64::NEG_INFINITY, 1.0), Err(EaseError::NotFinite("time")));
assert_eq!(t.remove(1).map(|k| k.value), Some(3.0));
assert!(t.remove(9).is_none() && t.set_ease(9, Easing::Linear).is_none());
// Before the first key, a new key eases linearly.
assert_eq!(t.insert(-1.0, 0.0), Ok(0));
assert_eq!(t.keys()[0].ease, Easing::Linear);
}
#[test]
fn keys_at_the_ends_of_the_number_range_sample_without_overflow() {
let t = Track::from_keys(vec![key(-f64::MAX, -1.0f64, Easing::Linear), key(f64::MAX, 1.0, Easing::Linear)]).unwrap();
assert_eq!(t.sample(0.0), Ok(0.0));
let v = t.sample(f64::MAX / 2.0).unwrap();
assert!((v - 0.5).abs() < 1e-12, "{v}");
// Keys a hair apart.
let near = Track::from_keys(vec![key(1.0, 0.0f64, Easing::Linear), key(1.0 + f64::EPSILON, 1.0, Easing::Linear)]).unwrap();
assert!(near.sample(1.0 + f64::EPSILON / 2.0).unwrap().is_finite());
// Values at opposite ends of the range interpolate without overflowing their difference.
let wide = Track::from_keys(vec![key(0.0, f64::MAX, Easing::Linear), key(1.0, -f64::MAX, Easing::Linear)]).unwrap();
assert_eq!(wide.sample(0.5), Ok(0.0));
let v =
Track::from_keys(vec![key(0.0, Vec2::new(-f64::MAX, 1e308), Easing::Linear), key(1.0, Vec2::new(f64::MAX, -1e308), Easing::Linear)]).unwrap();
assert_eq!(v.sample(0.5), Ok(Vec2::ZERO));
let a = Track::from_keys(vec![key(0.0, [f64::MAX; 2], Easing::Linear), key(1.0, [-f64::MAX; 2], Easing::Linear)]).unwrap();
assert!(a.sample(0.25).unwrap().iter().all(|x| x.is_finite()));
// Keys a subnormal step either side of 0 still interpolate between them.
let tiny = Track::from_keys(vec![key(-f64::from_bits(1), 0.0f64, Easing::Linear), key(f64::from_bits(1), 1.0, Easing::Linear)]).unwrap();
assert_eq!(tiny.sample(0.0), Ok(0.5));
// An overshoot past the largest f32 is refused, not returned as infinity.
let over = Track::from_keys(vec![key(0.0, -f32::MAX, Easing::BackOut), key(1.0, f32::MAX, Easing::Linear)]).unwrap();
assert_eq!(over.sample(0.6), Err(EaseError::Overflow));
// An overshoot whose step past the far key is too large to represent, with a result that
// is not.
let r = crate::lerp(-1e308, 5e307, 1.25);
assert!((r / 8.75e307 - 1.0).abs() < 1e-12, "{r}");
let back = Track::from_keys(vec![key(0.0, -f64::MAX, Easing::BackOut), key(1.0, -1e300, Easing::Linear)]).unwrap();
assert!(back.sample(0.6).unwrap() > 0.0);
}
#[cfg(feature = "serde")]
#[test]
fn tracks_round_trip_through_files_and_bad_files_are_refused() {
let t = Track::from_keys(vec![key(0.0, 1.0f64, Easing::Linear), key(1.5, 2.0, Easing::Hold), key(3.0, 0.5, Easing::QuadOut)]).unwrap();
let text = serde_json::to_string(&t).unwrap();
assert_eq!(
text,
r#"{"keys":[{"time":0.0,"value":1.0,"ease":"Linear"},{"time":1.5,"value":2.0,"ease":"Hold"},{"time":3.0,"value":0.5,"ease":"QuadOut"}]}"#
);
assert_eq!(serde_json::from_str::<Track<f64>>(&text).unwrap(), t);
// Keys out of order are sorted; a missing ease is linear.
let r: Track<f64> = serde_json::from_str(r#"{"keys":[{"time":2,"value":1},{"time":1,"value":0}]}"#).unwrap();
assert_eq!((r.keys()[0].time, &r.keys()[1].ease), (1.0, &Easing::Linear));
// Two keys at one time, or a time that is not a number, are a broken file.
assert!(serde_json::from_str::<Track<f64>>(r#"{"keys":[{"time":1,"value":1},{"time":1,"value":0}]}"#).is_err());
assert!(serde_json::from_str::<Track<f64>>(r#"{"keys":[{"time":"x","value":1}]}"#).is_err());
// More keys than a track holds are refused while reading, before the rest are read.
let mut big = String::from(r#"{"keys":["#);
for i in 0..=MAX_TRACK_KEYS {
if i > 0 {
big.push(',');
}
big.push_str(&format!(r#"{{"time":{i},"value":0}}"#));
}
big.push_str("]}");
let err = serde_json::from_str::<Track<f32>>(&big).unwrap_err().to_string();
assert!(err.contains("more than 100000 keys"), "{err}");
}
/// Formats that write a struct as its fields in order (rather than by name) read a track too,
/// through the same checks.
#[cfg(feature = "serde")]
#[test]
fn tracks_read_from_formats_that_write_fields_in_order() {
let t: Track<f64> = serde_json::from_str(r#"[[{"time":2,"value":1},{"time":1,"value":0,"ease":"QuadIn"}]]"#).unwrap();
assert_eq!(t.keys().iter().map(|k| (k.time, k.value)).collect::<Vec<_>>(), [(1.0, 0.0), (2.0, 1.0)]);
assert_eq!(t.keys()[0].ease, Easing::QuadIn);
assert!(serde_json::from_str::<Track<f64>>(r#"[[{"time":1,"value":1},{"time":1,"value":0}]]"#).is_err());
assert!(serde_json::from_str::<Track<f64>>("[]").is_err());
assert!(serde_json::from_str::<Track<f64>>("[[], 1]").is_err());
}
+269
View File
@@ -0,0 +1,269 @@
//! [`Track`]: keyed values with an ease between each key and the next.
use crate::{EaseError, Easing, Vec2, finite};
/// Most keys one track holds.
pub const MAX_TRACK_KEYS: usize = 100_000;
/// A value a track can animate: interpolated in a straight line between keys, the ease giving
/// how far along. Eases that overshoot pass `t` outside `0..=1`, which extrapolates.
pub trait Animatable: Clone {
/// The value `t` of the way from `self` to `to`.
fn lerp(&self, to: &Self, t: f64) -> Self;
/// Whether every component is finite.
fn is_finite(&self) -> bool;
}
impl Animatable for f32 {
fn lerp(&self, to: &f32, t: f64) -> f32 {
crate::lerp(f64::from(*self), f64::from(*to), t) as f32
}
fn is_finite(&self) -> bool {
f32::is_finite(*self)
}
}
impl Animatable for f64 {
fn lerp(&self, to: &f64, t: f64) -> f64 {
crate::lerp(*self, *to, t)
}
fn is_finite(&self) -> bool {
f64::is_finite(*self)
}
}
impl Animatable for Vec2 {
fn lerp(&self, to: &Vec2, t: f64) -> Vec2 {
Vec2::lerp(*self, *to, t)
}
fn is_finite(&self) -> bool {
Vec2::is_finite(*self)
}
}
impl<const N: usize> Animatable for [f32; N] {
fn lerp(&self, to: &[f32; N], t: f64) -> [f32; N] {
let mut out = *self;
for (o, b) in out.iter_mut().zip(to) {
*o = Animatable::lerp(&*o, b, t);
}
out
}
fn is_finite(&self) -> bool {
self.iter().all(|v| v.is_finite())
}
}
impl<const N: usize> Animatable for [f64; N] {
fn lerp(&self, to: &[f64; N], t: f64) -> [f64; N] {
let mut out = *self;
for (o, b) in out.iter_mut().zip(to) {
*o = crate::lerp(*o, *b, t);
}
out
}
fn is_finite(&self) -> bool {
self.iter().all(|v| v.is_finite())
}
}
/// A key: a value at a time (seconds), and the ease to the next key ([`Easing::Hold`] keeps the
/// value until the next key).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Key<T> {
pub time: f64,
pub value: T,
#[cfg_attr(feature = "serde", serde(default))]
pub ease: Easing,
}
/// Keys sorted by time, one per time, at most [`MAX_TRACK_KEYS`], every time and value finite.
///
/// Before the first key a track gives the first key's value, after the last key the last's.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Track<T> {
keys: Vec<Key<T>>,
}
impl<T> Default for Track<T> {
fn default() -> Self {
Track { keys: Vec::new() }
}
}
impl<T: Animatable> Track<T> {
pub fn new() -> Self {
Track::default()
}
/// A track from keys a caller or a file supplies: an error for a time or value that is not
/// finite, two keys at one time, or more than [`MAX_TRACK_KEYS`]. The keys may come in any
/// order.
pub fn from_keys(mut keys: Vec<Key<T>>) -> Result<Self, EaseError> {
if keys.len() > MAX_TRACK_KEYS {
return Err(EaseError::Full(MAX_TRACK_KEYS));
}
for k in &mut keys {
check(k.time, &k.value)?;
// -0.0 and 0.0 are one time.
if k.time == 0.0 {
k.time = 0.0;
}
}
keys.sort_by(|a, b| a.time.total_cmp(&b.time));
if let Some(w) = keys.windows(2).find(|w| matches!(w, [a, b] if a.time == b.time)) {
return Err(EaseError::SameTime(w.first().map_or(0.0, |k| k.time)));
}
Ok(Track { keys })
}
pub fn keys(&self) -> &[Key<T>] {
&self.keys
}
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
pub fn len(&self) -> usize {
self.keys.len()
}
/// Sets the value at `time`, keeping that key's ease, or adds a key there that eases like
/// the segment it splits. Returns the key's index. An error for a time or value that is not
/// finite, or a full track.
pub fn insert(&mut self, time: f64, value: T) -> Result<usize, EaseError> {
check(time, &value)?;
// -0.0 and 0.0 are one time.
let time = if time == 0.0 { 0.0 } else { time };
match self.keys.binary_search_by(|k| k.time.total_cmp(&time)) {
Ok(i) => {
if let Some(k) = self.keys.get_mut(i) {
k.value = value;
}
Ok(i)
}
Err(i) => {
if self.keys.len() >= MAX_TRACK_KEYS {
return Err(EaseError::Full(MAX_TRACK_KEYS));
}
let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or_else(Easing::default, |k| k.ease.clone());
self.keys.insert(i, Key { time, value, ease });
Ok(i)
}
}
}
/// Sets the ease from key `i` to the next one. `None` for a missing key.
pub fn set_ease(&mut self, i: usize, ease: Easing) -> Option<()> {
self.keys.get_mut(i)?.ease = ease;
Some(())
}
/// Removes key `i`, returning it.
pub fn remove(&mut self, i: usize) -> Option<Key<T>> {
(i < self.keys.len()).then(|| self.keys.remove(i))
}
/// The index of the key at exactly `time` (−0 and +0 are one time).
pub fn key_at(&self, time: f64) -> Option<usize> {
let time = if time == 0.0 { 0.0 } else { time };
self.keys.binary_search_by(|k| k.time.total_cmp(&time)).ok()
}
/// The value at `time`. An error for an empty track, a `time` that is not finite, or an
/// overshooting ease that carries the value past what the type can hold.
pub fn sample(&self, time: f64) -> Result<T, EaseError> {
let time = finite(time, "time")?;
let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else { return Err(EaseError::Empty) };
if time <= first.time {
return Ok(first.value.clone());
}
if time >= last.time {
return Ok(last.value.clone());
}
let i = self.keys.partition_point(|k| k.time <= time);
let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| self.keys.get(j)), self.keys.get(i)) else { return Ok(last.value.clone()) };
if a.ease == Easing::Hold {
return Ok(a.value.clone());
}
// Keys at opposite ends of the f64 range overflow the span; halving both sides keeps it.
let span = b.time - a.time;
let t = if span.is_finite() { (time - a.time) / span } else { (time * 0.5 - a.time * 0.5) / (b.time * 0.5 - a.time * 0.5) };
let v = a.value.lerp(&b.value, a.ease.apply(t.clamp(0.0, 1.0)));
if v.is_finite() { Ok(v) } else { Err(EaseError::Overflow) }
}
}
fn check<T: Animatable>(time: f64, value: &T) -> Result<(), EaseError> {
finite(time, "time")?;
if value.is_finite() { Ok(()) } else { Err(EaseError::NotFinite("value")) }
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{Animatable, Key, MAX_TRACK_KEYS, Track};
use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor};
use std::marker::PhantomData;
/// The key list, read one key at a time and refused once it passes [`MAX_TRACK_KEYS`], so a
/// hostile file cannot make it allocate more.
struct Keys<T>(Vec<Key<T>>);
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Keys<T> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V<T>(PhantomData<T>);
impl<'de, T: Deserialize<'de>> Visitor<'de> for V<T> {
type Value = Keys<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a list of at most {MAX_TRACK_KEYS} keys")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Keys<T>, A::Error> {
let mut keys = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(1024));
while let Some(k) = seq.next_element()? {
if keys.len() >= MAX_TRACK_KEYS {
return Err(A::Error::custom(format!("more than {MAX_TRACK_KEYS} keys")));
}
keys.push(k);
}
Ok(Keys(keys))
}
}
d.deserialize_seq(V(PhantomData))
}
}
impl<'de, T: Animatable + Deserialize<'de>> Deserialize<'de> for Track<T> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V<T>(PhantomData<T>);
impl<'de, T: Animatable + Deserialize<'de>> Visitor<'de> for V<T> {
type Value = Track<T>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "a track")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Track<T>, A::Error> {
let mut keys: Option<Vec<Key<T>>> = None;
while let Some(name) = map.next_key::<String>()? {
if name == "keys" {
keys = Some(map.next_value::<Keys<T>>()?.0);
} else {
map.next_value::<serde::de::IgnoredAny>()?;
}
}
Track::from_keys(keys.unwrap_or_default()).map_err(A::Error::custom)
}
/// Formats that write a struct as its fields in order.
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Track<T>, A::Error> {
let keys = seq.next_element::<Keys<T>>()?.ok_or_else(|| A::Error::invalid_length(0, &self))?.0;
if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
return Err(A::Error::invalid_length(2, &self));
}
Track::from_keys(keys).map_err(A::Error::custom)
}
}
d.deserialize_struct("Track", &["keys"], V(PhantomData))
}
}
}
+74
View File
@@ -0,0 +1,74 @@
//! A 2D point or vector, for ease curve points and motion paths.
use std::ops::{Add, Mul, Neg, Sub};
/// A 2D point or vector. In files it is `{"x": …, "y": …}`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Vec2 {
pub x: f64,
pub y: f64,
}
impl Vec2 {
pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 };
pub const fn new(x: f64, y: f64) -> Self {
Vec2 { x, y }
}
pub fn dot(self, o: Vec2) -> f64 {
self.x * o.x + self.y * o.y
}
/// The length, without overflow for large components.
pub fn length(self) -> f64 {
self.x.hypot(self.y)
}
/// The vector scaled to length 1, or zero for a zero (or non-finite) vector.
pub fn normalized(self) -> Vec2 {
let l = self.length();
if l > 0.0 && l.is_finite() { Vec2::new(self.x / l, self.y / l) } else { Vec2::ZERO }
}
pub fn lerp(self, o: Vec2, t: f64) -> Vec2 {
Vec2::new(crate::lerp(self.x, o.x, t), crate::lerp(self.y, o.y, t))
}
pub fn distance(self, o: Vec2) -> f64 {
(o - self).length()
}
pub fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, o: Vec2) -> Vec2 {
Vec2::new(self.x + o.x, self.y + o.y)
}
}
impl Sub for Vec2 {
type Output = Vec2;
fn sub(self, o: Vec2) -> Vec2 {
Vec2::new(self.x - o.x, self.y - o.y)
}
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
fn mul(self, s: f64) -> Vec2 {
Vec2::new(self.x * s, self.y * s)
}
}
impl Neg for Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 {
Vec2::new(-self.x, -self.y)
}
}